@dxos/react-ui-editor 0.3.11-main.5a4849d → 0.3.11-main.690ca41

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 (135) hide show
  1. package/dist/lib/browser/index.mjs +1362 -895
  2. package/dist/lib/browser/index.mjs.map +4 -4
  3. package/dist/lib/browser/meta.json +1 -1
  4. package/dist/types/src/components/TextEditor/MarkdownEditor.stories.d.ts +3 -3
  5. package/dist/types/src/components/TextEditor/MarkdownEditor.stories.d.ts.map +1 -1
  6. package/dist/types/src/{hooks/automerge → components/TextEditor}/automerge.stories.d.ts +6 -1
  7. package/dist/types/src/components/TextEditor/automerge.stories.d.ts.map +1 -0
  8. package/dist/types/src/components/TextEditor/codemirror.stories.d.ts.map +1 -1
  9. package/dist/types/src/{hooks/yjs → components/TextEditor}/yjs.stories.d.ts +1 -1
  10. package/dist/types/src/components/TextEditor/yjs.stories.d.ts.map +1 -0
  11. package/dist/types/src/extensions/automerge/automerge.d.ts +9 -0
  12. package/dist/types/src/extensions/automerge/automerge.d.ts.map +1 -0
  13. package/dist/types/src/extensions/automerge/cursor.d.ts +5 -0
  14. package/dist/types/src/extensions/automerge/cursor.d.ts.map +1 -0
  15. package/dist/types/src/extensions/automerge/defs.d.ts +26 -0
  16. package/dist/types/src/extensions/automerge/defs.d.ts.map +1 -0
  17. package/dist/types/src/extensions/automerge/index.d.ts +3 -0
  18. package/dist/types/src/extensions/automerge/index.d.ts.map +1 -0
  19. package/dist/types/src/{hooks → extensions}/automerge/semaphore.d.ts +4 -4
  20. package/dist/types/src/extensions/automerge/semaphore.d.ts.map +1 -0
  21. package/dist/types/src/extensions/automerge/update-automerge.d.ts +5 -0
  22. package/dist/types/src/extensions/automerge/update-automerge.d.ts.map +1 -0
  23. package/dist/types/src/extensions/automerge/update-codemirror.d.ts.map +1 -0
  24. package/dist/types/src/extensions/awareness.d.ts +46 -0
  25. package/dist/types/src/extensions/awareness.d.ts.map +1 -0
  26. package/dist/types/src/extensions/code.d.ts.map +1 -1
  27. package/dist/types/src/extensions/comments.d.ts.map +1 -1
  28. package/dist/types/src/extensions/hr.d.ts.map +1 -1
  29. package/dist/types/src/extensions/image.d.ts.map +1 -1
  30. package/dist/types/src/extensions/index.d.ts +3 -1
  31. package/dist/types/src/extensions/index.d.ts.map +1 -1
  32. package/dist/types/src/extensions/link.d.ts.map +1 -1
  33. package/dist/types/src/extensions/markdown/highlight.d.ts.map +1 -1
  34. package/dist/types/src/extensions/tasklist.d.ts.map +1 -1
  35. package/dist/types/src/extensions/yjs/cursor.d.ts +4 -0
  36. package/dist/types/src/extensions/yjs/cursor.d.ts.map +1 -0
  37. package/dist/types/src/extensions/yjs/index.d.ts +2 -0
  38. package/dist/types/src/extensions/yjs/index.d.ts.map +1 -0
  39. package/dist/types/src/extensions/yjs/yjs.d.ts +4 -0
  40. package/dist/types/src/extensions/yjs/yjs.d.ts.map +1 -0
  41. package/dist/types/src/extensions/yjs/yjs.test.d.ts.map +1 -0
  42. package/dist/types/src/hooks/automerge.d.ts +3 -0
  43. package/dist/types/src/hooks/automerge.d.ts.map +1 -0
  44. package/dist/types/src/hooks/awareness-provider.d.ts +28 -0
  45. package/dist/types/src/hooks/awareness-provider.d.ts.map +1 -0
  46. package/dist/types/src/hooks/index.d.ts +2 -0
  47. package/dist/types/src/hooks/index.d.ts.map +1 -1
  48. package/dist/types/src/hooks/useTextModel.d.ts +8 -7
  49. package/dist/types/src/hooks/useTextModel.d.ts.map +1 -1
  50. package/dist/types/src/hooks/{yjs/space-provider.d.ts → yjs.d.ts} +8 -8
  51. package/dist/types/src/hooks/yjs.d.ts.map +1 -0
  52. package/dist/types/src/index.d.ts +1 -0
  53. package/dist/types/src/index.d.ts.map +1 -1
  54. package/dist/types/src/styles/cursors.d.ts.map +1 -0
  55. package/dist/types/src/styles/index.d.ts +1 -0
  56. package/dist/types/src/styles/index.d.ts.map +1 -1
  57. package/dist/types/src/styles/tokens.d.ts +1 -0
  58. package/dist/types/src/styles/tokens.d.ts.map +1 -1
  59. package/dist/types/src/testing/replicator.d.ts +2 -2
  60. package/dist/types/src/testing/replicator.d.ts.map +1 -1
  61. package/dist/types/src/themes/default.d.ts.map +1 -1
  62. package/dist/types/src/util/cursor.d.ts +17 -0
  63. package/dist/types/src/util/cursor.d.ts.map +1 -0
  64. package/dist/types/src/util/index.d.ts +3 -0
  65. package/dist/types/src/util/index.d.ts.map +1 -0
  66. package/dist/types/src/util/util.d.ts.map +1 -0
  67. package/package.json +22 -21
  68. package/src/components/TextEditor/MarkdownEditor.stories.tsx +6 -7
  69. package/src/components/TextEditor/TextEditor.tsx +1 -1
  70. package/src/{hooks/automerge → components/TextEditor}/automerge.stories.tsx +66 -6
  71. package/src/components/TextEditor/codemirror.stories.ts +3 -2
  72. package/src/{hooks/yjs → components/TextEditor}/yjs.stories.tsx +1 -1
  73. package/src/{hooks/automerge/plugin.ts → extensions/automerge/automerge.ts} +20 -58
  74. package/src/extensions/automerge/cursor.ts +51 -0
  75. package/src/extensions/automerge/defs.ts +62 -0
  76. package/src/extensions/automerge/index.ts +6 -0
  77. package/src/{hooks → extensions}/automerge/semaphore.ts +14 -12
  78. package/src/{hooks → extensions}/automerge/update-automerge.ts +5 -6
  79. package/src/{hooks → extensions}/automerge/update-codemirror.ts +13 -5
  80. package/src/extensions/awareness.ts +316 -0
  81. package/src/extensions/code.ts +4 -5
  82. package/src/extensions/comments.ts +30 -15
  83. package/src/extensions/hr.ts +2 -3
  84. package/src/extensions/image.ts +38 -20
  85. package/src/extensions/index.ts +3 -1
  86. package/src/extensions/link.ts +82 -84
  87. package/src/extensions/markdown/highlight.ts +3 -4
  88. package/src/extensions/table.ts +5 -2
  89. package/src/extensions/tasklist.ts +1 -3
  90. package/src/extensions/yjs/cursor.ts +21 -0
  91. package/src/extensions/yjs/index.ts +5 -0
  92. package/src/{hooks → extensions}/yjs/yjs.test.ts +1 -25
  93. package/src/extensions/yjs/yjs.ts +16 -0
  94. package/src/hooks/automerge.ts +52 -0
  95. package/src/hooks/awareness-provider.ts +120 -0
  96. package/src/hooks/index.ts +2 -0
  97. package/src/hooks/useTextModel.ts +19 -93
  98. package/src/hooks/{yjs/space-provider.ts → yjs.ts} +71 -19
  99. package/src/index.ts +1 -0
  100. package/src/styles/index.ts +1 -0
  101. package/src/styles/tokens.ts +3 -0
  102. package/src/testing/replicator.ts +10 -15
  103. package/src/themes/default.ts +39 -33
  104. package/src/util/cursor.ts +29 -0
  105. package/src/util/index.ts +6 -0
  106. package/dist/types/src/extensions/mermaid.d.ts +0 -3
  107. package/dist/types/src/extensions/mermaid.d.ts.map +0 -1
  108. package/dist/types/src/extensions/util.d.ts.map +0 -1
  109. package/dist/types/src/hooks/automerge/automerge.stories.d.ts.map +0 -1
  110. package/dist/types/src/hooks/automerge/handle.d.ts +0 -9
  111. package/dist/types/src/hooks/automerge/handle.d.ts.map +0 -1
  112. package/dist/types/src/hooks/automerge/index.d.ts +0 -3
  113. package/dist/types/src/hooks/automerge/index.d.ts.map +0 -1
  114. package/dist/types/src/hooks/automerge/plugin.d.ts +0 -26
  115. package/dist/types/src/hooks/automerge/plugin.d.ts.map +0 -1
  116. package/dist/types/src/hooks/automerge/semaphore.d.ts.map +0 -1
  117. package/dist/types/src/hooks/automerge/update-automerge.d.ts +0 -6
  118. package/dist/types/src/hooks/automerge/update-automerge.d.ts.map +0 -1
  119. package/dist/types/src/hooks/automerge/update-codemirror.d.ts.map +0 -1
  120. package/dist/types/src/hooks/yjs/cursors.d.ts.map +0 -1
  121. package/dist/types/src/hooks/yjs/index.d.ts +0 -3
  122. package/dist/types/src/hooks/yjs/index.d.ts.map +0 -1
  123. package/dist/types/src/hooks/yjs/space-provider.d.ts.map +0 -1
  124. package/dist/types/src/hooks/yjs/yjs.stories.d.ts.map +0 -1
  125. package/dist/types/src/hooks/yjs/yjs.test.d.ts.map +0 -1
  126. package/src/extensions/mermaid.ts +0 -11
  127. package/src/hooks/automerge/handle.ts +0 -14
  128. package/src/hooks/automerge/index.ts +0 -6
  129. package/src/hooks/yjs/index.ts +0 -6
  130. /package/dist/types/src/{hooks → extensions}/automerge/update-codemirror.d.ts +0 -0
  131. /package/dist/types/src/{hooks → extensions}/yjs/yjs.test.d.ts +0 -0
  132. /package/dist/types/src/{hooks/yjs → styles}/cursors.d.ts +0 -0
  133. /package/dist/types/src/{extensions → util}/util.d.ts +0 -0
  134. /package/src/{hooks/yjs → styles}/cursors.ts +0 -0
  135. /package/src/{extensions → util}/util.ts +0 -0
@@ -11,7 +11,7 @@ import { EditorView as EditorView12 } from "@codemirror/view";
11
11
  import { useFocusableGroup } from "@fluentui/react-tabster";
12
12
  import { vim } from "@replit/codemirror-vim";
13
13
  import defaultsDeep2 from "lodash.defaultsdeep";
14
- import React, { forwardRef, useCallback, useEffect as useEffect2, useImperativeHandle, useState as useState2 } from "react";
14
+ import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useState } from "react";
15
15
  import { generateName } from "@dxos/display-name";
16
16
  import { useThemeContext } from "@dxos/react-ui";
17
17
  import { getColorForValue, inputSurface, mx as mx3 } from "@dxos/react-ui-theme";
@@ -49,13 +49,565 @@ var autocomplete = ({ onSearch }) => {
49
49
  ];
50
50
  };
51
51
 
52
+ // packages/ui/react-ui-editor/src/extensions/automerge/automerge.ts
53
+ import { Facet as Facet2, StateField } from "@codemirror/state";
54
+ import { ViewPlugin } from "@codemirror/view";
55
+ import { next as A } from "@dxos/automerge/automerge";
56
+
57
+ // packages/ui/react-ui-editor/src/extensions/automerge/cursor.ts
58
+ import get from "lodash.get";
59
+ import { next as automerge } from "@dxos/automerge/automerge";
60
+ var cursorConverter = (handle, path) => ({
61
+ // TODO(burdon): Handle assoc to associate with a previous character.
62
+ toCursor: (pos) => {
63
+ const doc = handle.docSync();
64
+ if (!doc) {
65
+ return "";
66
+ }
67
+ const value = get(doc, path);
68
+ if (typeof value === "string" && value.length <= pos) {
69
+ return "end";
70
+ }
71
+ return automerge.getCursor(doc, path.slice(), pos);
72
+ },
73
+ fromCursor: (cursor) => {
74
+ if (cursor === "") {
75
+ return 0;
76
+ }
77
+ const doc = handle.docSync();
78
+ if (!doc) {
79
+ return 0;
80
+ }
81
+ if (cursor === "end") {
82
+ const value = get(doc, path);
83
+ if (typeof value === "string") {
84
+ return value.length;
85
+ } else {
86
+ return 0;
87
+ }
88
+ }
89
+ return automerge.getCursorPosition(doc, path.slice(), cursor);
90
+ }
91
+ });
92
+
93
+ // packages/ui/react-ui-editor/src/extensions/automerge/defs.ts
94
+ import { Annotation, StateEffect } from "@codemirror/state";
95
+ var effectType = StateEffect.define({});
96
+ var updateHeads = (newHeads) => effectType.of({
97
+ newHeads
98
+ });
99
+ var getLastHeads = (state, field) => state.field(field).lastHeads;
100
+ var getPath = (state, field) => state.field(field).path;
101
+ var reconcileAnnotationType = Annotation.define();
102
+ var isReconcileTx = (tr) => !!tr.annotation(reconcileAnnotationType);
103
+
104
+ // packages/ui/react-ui-editor/src/extensions/automerge/semaphore.ts
105
+ import { next as automerge2 } from "@dxos/automerge/automerge";
106
+
107
+ // packages/ui/react-ui-editor/src/extensions/automerge/update-automerge.ts
108
+ import { next as am } from "@dxos/automerge/automerge";
109
+ var updateAutomerge = (field, handle, transactions, state) => {
110
+ const { lastHeads, path } = state.field(field);
111
+ let hasChanges = false;
112
+ for (const tr of transactions) {
113
+ tr.changes.iterChanges(() => {
114
+ hasChanges = true;
115
+ });
116
+ }
117
+ if (!hasChanges) {
118
+ return void 0;
119
+ }
120
+ const newHeads = handle.changeAt(lastHeads, (doc) => {
121
+ for (const tr of transactions) {
122
+ tr.changes.iterChanges((fromA, toA, _fromB, _toB, inserted) => {
123
+ am.splice(doc, path, fromA, toA - fromA, inserted.toString());
124
+ });
125
+ }
126
+ });
127
+ return newHeads ?? void 0;
128
+ };
129
+
130
+ // packages/ui/react-ui-editor/src/extensions/automerge/update-codemirror.ts
131
+ import { ChangeSet } from "@codemirror/state";
132
+ var updateCodeMirror = (view, selection, target, patches) => {
133
+ for (const patch of patches) {
134
+ const changeSpec = handlePatch(patch, target, view.state);
135
+ if (changeSpec != null) {
136
+ const changeSet = ChangeSet.of(changeSpec, view.state.doc.length, "\n");
137
+ selection = selection.map(changeSet, 1);
138
+ view.dispatch({
139
+ changes: changeSet,
140
+ annotations: reconcileAnnotationType.of({})
141
+ });
142
+ }
143
+ }
144
+ view.dispatch({
145
+ selection,
146
+ annotations: reconcileAnnotationType.of({})
147
+ });
148
+ };
149
+ var handlePatch = (patch, target, state) => {
150
+ if (patch.action === "insert") {
151
+ return handleInsert(target, patch);
152
+ } else if (patch.action === "splice") {
153
+ return handleSplice(target, patch);
154
+ } else if (patch.action === "del") {
155
+ return handleDel(target, patch);
156
+ } else if (patch.action === "put") {
157
+ return handlePut(target, patch, state);
158
+ } else {
159
+ return null;
160
+ }
161
+ };
162
+ var handleInsert = (target, patch) => {
163
+ const index = charPath(target, patch.path);
164
+ if (index == null) {
165
+ return [];
166
+ }
167
+ const text = patch.values.map((v) => v ? v.toString() : "").join("");
168
+ return [
169
+ {
170
+ from: index,
171
+ to: index,
172
+ insert: text
173
+ }
174
+ ];
175
+ };
176
+ var handleSplice = (target, patch) => {
177
+ const index = charPath(target, patch.path);
178
+ if (index == null) {
179
+ return [];
180
+ }
181
+ return [
182
+ {
183
+ from: index,
184
+ insert: patch.value
185
+ }
186
+ ];
187
+ };
188
+ var handleDel = (target, patch) => {
189
+ const index = charPath(target, patch.path);
190
+ if (index == null) {
191
+ return [];
192
+ }
193
+ const length = patch.length || 1;
194
+ return [
195
+ {
196
+ from: index,
197
+ to: index + length
198
+ }
199
+ ];
200
+ };
201
+ var handlePut = (target, patch, state) => {
202
+ const index = charPath(target, [
203
+ ...patch.path,
204
+ 0
205
+ ]);
206
+ if (index == null) {
207
+ return [];
208
+ }
209
+ const length = state.doc.length;
210
+ if (typeof patch.value !== "string") {
211
+ return [];
212
+ }
213
+ return [
214
+ {
215
+ from: 0,
216
+ to: length,
217
+ insert: patch.value
218
+ }
219
+ ];
220
+ };
221
+ var charPath = (textPath, candidatePath) => {
222
+ if (candidatePath.length !== textPath.length + 1) {
223
+ return null;
224
+ }
225
+ for (let i = 0; i < textPath.length; i++) {
226
+ if (textPath[i] !== candidatePath[i]) {
227
+ return null;
228
+ }
229
+ }
230
+ const index = candidatePath[candidatePath.length - 1];
231
+ if (typeof index === "number") {
232
+ return index;
233
+ }
234
+ return null;
235
+ };
236
+
237
+ // packages/ui/react-ui-editor/src/extensions/automerge/semaphore.ts
238
+ var PatchSemaphore = class {
239
+ constructor(_field) {
240
+ this._field = _field;
241
+ this._inReconcile = false;
242
+ this._queue = [];
243
+ this.reconcile = (handle, view) => {
244
+ if (this._inReconcile) {
245
+ return;
246
+ }
247
+ this._inReconcile = true;
248
+ const path = getPath(view.state, this._field);
249
+ const oldHeads = getLastHeads(view.state, this._field);
250
+ let selection = view.state.selection;
251
+ const transactions = view.state.field(this._field).unreconciledTransactions.filter((tx) => !isReconcileTx(tx));
252
+ const toInvert = transactions.slice().reverse();
253
+ for (const tx of toInvert) {
254
+ const inverted = tx.changes.invert(tx.startState.doc);
255
+ selection = selection.map(inverted);
256
+ view.dispatch({
257
+ changes: inverted,
258
+ annotations: reconcileAnnotationType.of(true)
259
+ });
260
+ }
261
+ let newHeads = updateAutomerge(this._field, handle, transactions, view.state);
262
+ if (newHeads === null || newHeads === void 0) {
263
+ newHeads = automerge2.getHeads(handle.docSync());
264
+ }
265
+ const diff = automerge2.equals(oldHeads, newHeads) ? [] : automerge2.diff(handle.docSync(), oldHeads, newHeads);
266
+ updateCodeMirror(view, selection, path, diff);
267
+ view.dispatch({
268
+ effects: updateHeads(newHeads),
269
+ annotations: reconcileAnnotationType.of({})
270
+ });
271
+ this._inReconcile = false;
272
+ };
273
+ }
274
+ };
275
+
276
+ // packages/ui/react-ui-editor/src/util/cursor.ts
277
+ import { Facet } from "@codemirror/state";
278
+ var DEFAULT_CURSOR_CONVERTER = {
279
+ toCursor: (position) => position.toString(),
280
+ fromCursor: (cursor) => parseInt(cursor)
281
+ };
282
+ var CursorConverter = Facet.define({
283
+ combine: (providers) => providers[0] ?? DEFAULT_CURSOR_CONVERTER
284
+ });
285
+
286
+ // packages/ui/react-ui-editor/src/util/util.ts
287
+ import { log } from "@dxos/log";
288
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/util/util.ts";
289
+ var callbackWrapper = (fn) => (...args) => {
290
+ try {
291
+ return fn(...args);
292
+ } catch (error) {
293
+ log.catch(error, void 0, {
294
+ F: __dxlog_file,
295
+ L: 16,
296
+ S: void 0,
297
+ C: (f, a) => f(...a)
298
+ });
299
+ }
300
+ };
301
+
302
+ // packages/ui/react-ui-editor/src/extensions/automerge/automerge.ts
303
+ var semaphoreFacet = Facet2.define({
304
+ combine: (values) => values.at(-1)
305
+ });
306
+ var automerge3 = ({ handle, path }) => {
307
+ const stateField = StateField.define({
308
+ create: () => ({
309
+ lastHeads: A.getHeads(handle.docSync()),
310
+ unreconciledTransactions: [],
311
+ path: path.slice()
312
+ }),
313
+ update: (value, tr) => {
314
+ const result = {
315
+ lastHeads: value.lastHeads,
316
+ unreconciledTransactions: value.unreconciledTransactions.slice(),
317
+ path: path.slice()
318
+ };
319
+ let clearUnreconciled = false;
320
+ for (const effect of tr.effects) {
321
+ if (effect.is(effectType)) {
322
+ result.lastHeads = effect.value.newHeads;
323
+ clearUnreconciled = true;
324
+ }
325
+ }
326
+ if (clearUnreconciled) {
327
+ result.unreconciledTransactions = [];
328
+ } else {
329
+ if (!isReconcileTx(tr)) {
330
+ result.unreconciledTransactions.push(tr);
331
+ }
332
+ }
333
+ return result;
334
+ }
335
+ });
336
+ const semaphore = new PatchSemaphore(stateField);
337
+ const viewPlugin = ViewPlugin.fromClass(class AutomergeCodemirrorViewPlugin {
338
+ constructor(_view) {
339
+ this._view = _view;
340
+ this._handleChange = () => {
341
+ this._view.state.facet(semaphoreFacet).reconcile(handle, this._view);
342
+ };
343
+ handle.addListener("change", this._handleChange);
344
+ }
345
+ update(update2) {
346
+ if (update2.transactions.length > 0 && update2.transactions.some((tr) => !isReconcileTx(tr))) {
347
+ queueMicrotask(() => {
348
+ this._view.state.facet(semaphoreFacet).reconcile(handle, this._view);
349
+ });
350
+ }
351
+ }
352
+ destroy() {
353
+ handle.addListener("change", this._handleChange);
354
+ }
355
+ });
356
+ return {
357
+ extension: [
358
+ CursorConverter.of(cursorConverter(handle, path)),
359
+ semaphoreFacet.of(semaphore),
360
+ stateField,
361
+ viewPlugin
362
+ ]
363
+ };
364
+ };
365
+
366
+ // packages/ui/react-ui-editor/src/extensions/awareness.ts
367
+ import { Annotation as Annotation2, Facet as Facet3, RangeSet } from "@codemirror/state";
368
+ import { Decoration, EditorView, ViewPlugin as ViewPlugin2, WidgetType } from "@codemirror/view";
369
+ import { Event } from "@dxos/async";
370
+ import { Context } from "@dxos/context";
371
+ var dummyProvider = {
372
+ remoteStateChange: new Event(),
373
+ open: () => {
374
+ },
375
+ close: () => {
376
+ },
377
+ update: () => {
378
+ },
379
+ getRemoteStates: () => []
380
+ };
381
+ var AwarenessProvider = Facet3.define({
382
+ combine: (providers) => providers[0] ?? dummyProvider
383
+ });
384
+ var RemoteSelectionChangedAnnotation = Annotation2.define();
385
+ var awareness = (provider = dummyProvider) => {
386
+ return [
387
+ AwarenessProvider.of(provider),
388
+ ViewPlugin2.fromClass(RemoteSelectionsDecorator, {
389
+ decorations: (value) => value.decorations
390
+ }),
391
+ styles
392
+ ];
393
+ };
394
+ var RemoteSelectionsDecorator = class {
395
+ constructor(view) {
396
+ this.decorations = RangeSet.of([]);
397
+ this._ctx = new Context();
398
+ this._lastAnchor = void 0;
399
+ this._lastHead = void 0;
400
+ this._cursorConverter = view.state.facet(CursorConverter);
401
+ this._provider = view.state.facet(AwarenessProvider);
402
+ this._provider.open();
403
+ this._provider.remoteStateChange.on(this._ctx, () => {
404
+ view.dispatch({
405
+ annotations: [
406
+ RemoteSelectionChangedAnnotation.of([])
407
+ ]
408
+ });
409
+ });
410
+ }
411
+ destroy() {
412
+ void this._ctx.dispose();
413
+ this._provider.close();
414
+ }
415
+ update(update2) {
416
+ this._updateLocalSelection(update2);
417
+ this._updateRemoteSelections(update2);
418
+ }
419
+ _updateLocalSelection(update2) {
420
+ const hasFocus = update2.view.hasFocus && update2.view.dom.ownerDocument.hasFocus();
421
+ const { anchor = void 0, head = void 0 } = hasFocus ? update2.state.selection.main : {};
422
+ if (this._lastAnchor === anchor && this._lastHead === head) {
423
+ return;
424
+ }
425
+ this._lastAnchor = anchor;
426
+ this._lastHead = head;
427
+ this._provider.update(anchor !== void 0 && head !== void 0 ? {
428
+ anchor: this._cursorConverter.toCursor(anchor),
429
+ head: this._cursorConverter.toCursor(head)
430
+ } : void 0);
431
+ }
432
+ _updateRemoteSelections(update2) {
433
+ const decorations = [];
434
+ const awarenessStates = this._provider.getRemoteStates();
435
+ for (const state of awarenessStates) {
436
+ const anchor = state.position?.anchor ? this._cursorConverter.fromCursor(state.position.anchor) : null;
437
+ const head = state.position?.head ? this._cursorConverter.fromCursor(state.position.head) : null;
438
+ if (anchor == null || head == null) {
439
+ continue;
440
+ }
441
+ const start = Math.min(Math.min(anchor, head), update2.view.state.doc.length);
442
+ const end = Math.min(Math.max(anchor, head), update2.view.state.doc.length);
443
+ const startLine = update2.view.state.doc.lineAt(start);
444
+ const endLine = update2.view.state.doc.lineAt(end);
445
+ const color = state.info.color ?? "#30bced";
446
+ const lightColor = state.info.lightColor ?? color + "33";
447
+ if (startLine.number === endLine.number) {
448
+ decorations.push({
449
+ from: start,
450
+ to: end,
451
+ value: Decoration.mark({
452
+ attributes: {
453
+ style: `background-color: ${lightColor}`
454
+ },
455
+ class: "cm-ySelection"
456
+ })
457
+ });
458
+ } else {
459
+ decorations.push({
460
+ from: start,
461
+ to: startLine.from + startLine.length,
462
+ value: Decoration.mark({
463
+ attributes: {
464
+ style: `background-color: ${color}`
465
+ },
466
+ class: "cm-ySelection"
467
+ })
468
+ });
469
+ decorations.push({
470
+ from: endLine.from,
471
+ to: end,
472
+ value: Decoration.mark({
473
+ attributes: {
474
+ style: `background-color: ${color}`
475
+ },
476
+ class: "cm-ySelection"
477
+ })
478
+ });
479
+ for (let i = startLine.number + 1; i < endLine.number; i++) {
480
+ const linePos = update2.view.state.doc.line(i).from;
481
+ decorations.push({
482
+ from: linePos,
483
+ to: linePos,
484
+ value: Decoration.line({
485
+ attributes: {
486
+ style: `background-color: ${color}`,
487
+ class: "cm-yLineSelection"
488
+ }
489
+ })
490
+ });
491
+ }
492
+ }
493
+ decorations.push({
494
+ from: head,
495
+ to: head,
496
+ value: Decoration.widget({
497
+ side: head - anchor > 0 ? -1 : 1,
498
+ block: false,
499
+ widget: new RemoteCaretWidget(state.info.displayName ?? "Anonymous", color)
500
+ })
501
+ });
502
+ }
503
+ this.decorations = Decoration.set(decorations, true);
504
+ }
505
+ };
506
+ var RemoteCaretWidget = class extends WidgetType {
507
+ constructor(name, color) {
508
+ super();
509
+ this.name = name;
510
+ this.color = color;
511
+ this.name = name;
512
+ this.color = color;
513
+ }
514
+ toDOM() {
515
+ const span = document.createElement("span");
516
+ span.className = "cm-ySelectionCaret";
517
+ span.style.backgroundColor = this.color;
518
+ span.style.borderColor = this.color;
519
+ const dot = document.createElement("div");
520
+ dot.className = "cm-ySelectionCaretDot";
521
+ const info = document.createElement("div");
522
+ info.className = "cm-ySelectionInfo";
523
+ info.innerText = this.name;
524
+ span.appendChild(document.createTextNode("\u2060"));
525
+ span.appendChild(dot);
526
+ span.appendChild(document.createTextNode("\u2060"));
527
+ span.appendChild(info);
528
+ span.appendChild(document.createTextNode("\u2060"));
529
+ return span;
530
+ }
531
+ eq(widget) {
532
+ return widget.color === this.color;
533
+ }
534
+ compare(widget) {
535
+ return widget.color === this.color;
536
+ }
537
+ updateDOM() {
538
+ return false;
539
+ }
540
+ get estimatedHeight() {
541
+ return -1;
542
+ }
543
+ ignoreEvent() {
544
+ return true;
545
+ }
546
+ };
547
+ var styles = EditorView.baseTheme({
548
+ ".cm-ySelection": {},
549
+ ".cm-yLineSelection": {
550
+ padding: 0,
551
+ margin: "0px 2px 0px 4px"
552
+ },
553
+ ".cm-ySelectionCaret": {
554
+ position: "relative",
555
+ borderLeft: "1px solid black",
556
+ borderRight: "1px solid black",
557
+ marginLeft: "-1px",
558
+ marginRight: "-1px",
559
+ boxSizing: "border-box",
560
+ display: "inline"
561
+ },
562
+ ".cm-ySelectionCaretDot": {
563
+ borderRadius: "50%",
564
+ position: "absolute",
565
+ width: ".4em",
566
+ height: ".4em",
567
+ top: "-.2em",
568
+ left: "-.2em",
569
+ backgroundColor: "inherit",
570
+ transition: "transform .3s ease-in-out",
571
+ boxSizing: "border-box"
572
+ },
573
+ ".cm-ySelectionCaret:hover > .cm-ySelectionCaretDot": {
574
+ transformOrigin: "bottom center",
575
+ transform: "scale(0)"
576
+ },
577
+ ".cm-ySelectionInfo": {
578
+ position: "absolute",
579
+ top: "-1.05em",
580
+ left: "-1px",
581
+ fontSize: ".75em",
582
+ fontFamily: "serif",
583
+ fontStyle: "normal",
584
+ fontWeight: "normal",
585
+ lineHeight: "normal",
586
+ userSelect: "none",
587
+ color: "white",
588
+ paddingLeft: "2px",
589
+ paddingRight: "2px",
590
+ zIndex: 101,
591
+ transition: "opacity .3s ease-in-out",
592
+ backgroundColor: "inherit",
593
+ // these should be separate
594
+ opacity: 0,
595
+ transitionDelay: "0s",
596
+ whiteSpace: "nowrap"
597
+ },
598
+ ".cm-ySelectionCaret:hover > .cm-ySelectionInfo": {
599
+ opacity: 1,
600
+ transitionDelay: "0s"
601
+ }
602
+ });
603
+
52
604
  // packages/ui/react-ui-editor/src/extensions/basic.ts
53
605
  import { closeBrackets } from "@codemirror/autocomplete";
54
606
  import { bracketMatching, defaultHighlightStyle, syntaxHighlighting } from "@codemirror/language";
55
607
  import { oneDarkHighlightStyle } from "@codemirror/theme-one-dark";
56
- import { drawSelection, EditorView, placeholder } from "@codemirror/view";
608
+ import { drawSelection, EditorView as EditorView2, placeholder } from "@codemirror/view";
57
609
  var basicBundle = ({ readonly, themeMode, placeholder: _placeholder }) => [
58
- EditorView.lineWrapping,
610
+ EditorView2.lineWrapping,
59
611
  // TODO(burdon): Compare with minimalSetup.
60
612
  // https://codemirror.net/docs/ref/#codemirror.minimalSetup
61
613
  bracketMatching(),
@@ -67,10 +619,10 @@ var basicBundle = ({ readonly, themeMode, placeholder: _placeholder }) => [
67
619
  ].filter(Boolean);
68
620
 
69
621
  // packages/ui/react-ui-editor/src/extensions/blast.ts
70
- import { EditorView as EditorView2, keymap as keymap2 } from "@codemirror/view";
622
+ import { EditorView as EditorView3, keymap as keymap2 } from "@codemirror/view";
71
623
  import defaultsDeep from "lodash.defaultsdeep";
72
624
  import { invariant } from "@dxos/invariant";
73
- var __dxlog_file = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/extensions/blast.ts";
625
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/extensions/blast.ts";
74
626
  var defaultOptions = {
75
627
  effect: 2,
76
628
  maxParticles: 200,
@@ -115,12 +667,12 @@ var blast = (options = defaultOptions) => {
115
667
  };
116
668
  return [
117
669
  // Cursor moved.
118
- EditorView2.updateListener.of((update4) => {
119
- if (blaster?.node !== update4.view.scrollDOM) {
670
+ EditorView3.updateListener.of((update2) => {
671
+ if (blaster?.node !== update2.view.scrollDOM) {
120
672
  if (blaster) {
121
673
  blaster.destroy();
122
674
  }
123
- blaster = new Blaster(update4.view.scrollDOM, defaultsDeep({
675
+ blaster = new Blaster(update2.view.scrollDOM, defaultsDeep({
124
676
  particleGravity: 0.2,
125
677
  particleShrinkRate: 0.995,
126
678
  color: () => [
@@ -134,10 +686,10 @@ var blast = (options = defaultOptions) => {
134
686
  } else {
135
687
  blaster.resize();
136
688
  }
137
- const current = update4.state.selection.main.head;
689
+ const current = update2.state.selection.main.head;
138
690
  if (current !== last) {
139
691
  last = current;
140
- const { element, point } = getPoint(update4.view, current - 1);
692
+ const { element, point } = getPoint(update2.view, current - 1);
141
693
  if (element && point) {
142
694
  blaster.spawn({
143
695
  element,
@@ -197,7 +749,7 @@ var Blaster = class {
197
749
  }
198
750
  initialize() {
199
751
  invariant(!this._canvas && !this._ctx, void 0, {
200
- F: __dxlog_file,
752
+ F: __dxlog_file2,
201
753
  L: 138,
202
754
  S: this,
203
755
  A: [
@@ -234,7 +786,7 @@ var Blaster = class {
234
786
  }
235
787
  start() {
236
788
  invariant(this._canvas && this._ctx, void 0, {
237
- F: __dxlog_file,
789
+ F: __dxlog_file2,
238
790
  L: 177,
239
791
  S: this,
240
792
  A: [
@@ -339,452 +891,48 @@ var Effect2 = class extends Effect {
339
891
  ctx.fill();
340
892
  }
341
893
  };
342
- function throttle(callback, limit) {
343
- let wait = false;
344
- return function(...args) {
345
- if (!wait) {
346
- callback.apply(this, args);
347
- wait = true;
348
- setTimeout(() => {
349
- wait = false;
350
- }, limit);
351
- }
352
- };
353
- }
354
- var getRGBComponents = (node, color) => {
355
- if (typeof color === "function") {
356
- return color();
357
- }
358
- const bgColor = getComputedStyle(node).color;
359
- if (bgColor) {
360
- const x = bgColor.match(/(\d+), (\d+), (\d+)/)?.slice(1);
361
- if (x) {
362
- return x;
363
- }
364
- }
365
- return [
366
- 50,
367
- 50,
368
- 50
369
- ];
370
- };
371
- var random = (min, max) => {
372
- if (!max) {
373
- max = min;
374
- min = 0;
375
- }
376
- return min + ~~(Math.random() * (max - min + 1));
377
- };
378
-
379
- // packages/ui/react-ui-editor/src/extensions/code.ts
380
- import { ViewPlugin, EditorView as EditorView3, Decoration } from "@codemirror/view";
381
- import get from "lodash.get";
382
- import { mx as mx2 } from "@dxos/react-ui-theme";
383
-
384
- // packages/ui/react-ui-editor/src/styles/markdown.ts
385
- import { mx } from "@dxos/react-ui-theme";
386
- var headings = {
387
- 1: [
388
- "mbs-4 mbe-2 font-medium text-inherit no-underline text-4xl",
389
- "-ml-[10px]"
390
- ],
391
- 2: [
392
- "mbs-4 mbe-2 font-medium text-inherit no-underline text-3xl",
393
- "-ml-[8px]"
394
- ],
395
- 3: [
396
- "mbs-4 mbe-2 font-medium text-inherit no-underline text-2xl",
397
- "-ml-[7px]"
398
- ],
399
- 4: [
400
- "mbs-4 mbe-2 font-medium text-inherit no-underline text-xl",
401
- "-ml-[6px]"
402
- ],
403
- 5: [
404
- "mbs-4 mbe-2 font-medium text-inherit no-underline text-lg",
405
- "-ml-[5px]"
406
- ],
407
- 6: [
408
- "mbs-4 mbe-2 font-medium text-inherit no-underline",
409
- "-ml-[4px]"
410
- ]
411
- };
412
- var heading = (level, readonly) => {
413
- const [style, offset] = headings[level];
414
- return mx(style, readonly && offset);
415
- };
416
- var light = "text-neutral-200 dark:text-neutral-800";
417
- var mark = mx("!font-normal !no-underline !text-inherit opacity-40", light);
418
- var bold = "font-bold";
419
- var italic = "italic";
420
- var strikethrough = "line-through";
421
- var code = "font-mono !no-underline text-neutral-700 dark:text-neutral-300";
422
- var codeMark = "font-mono text-primary-500";
423
- var inlineUrl = mx(code, "px-1");
424
- var blockquote = mx("pl-1 mr-1 border-is-4 border-primary-500/70 dark:border-primary-500/30", light);
425
-
426
- // packages/ui/react-ui-editor/src/styles/tokens.ts
427
- import { tailwindConfig } from "@dxos/react-ui-theme";
428
- var tokens = tailwindConfig({}).theme;
429
-
430
- // packages/ui/react-ui-editor/src/extensions/code.ts
431
- var CODE_REGEX = /```[\s\S]*?```/gs;
432
- var styles = EditorView3.baseTheme({
433
- "& .cm-codeblock": {
434
- fontFamily: get(tokens, "fontFamily.mono", []).join(",")
435
- },
436
- '&light [aria-readonly="true"] .cm-codeblock': {
437
- background: get(tokens, "extend.colors.neutral.50")
438
- },
439
- '&dark [aria-readonly="true"] .cm-codeblock': {
440
- background: get(tokens, "extend.colors.neutral.850")
441
- },
442
- '& [aria-readonly="true"] .cm-codeblock': {
443
- display: "block",
444
- paddingInline: "4px !important"
445
- },
446
- '& [aria-readonly="true"] .cm-codeblock-first': {
447
- paddingTop: "4px !important",
448
- borderTopLeftRadius: "4px",
449
- borderTopRightRadius: "4px"
450
- },
451
- '& [aria-readonly="true"] .cm-codeblock-last': {
452
- paddingBottom: "4px !important",
453
- borderBottomLeftRadius: "4px",
454
- borderBottomRightRadius: "4px"
455
- }
456
- });
457
- var getLineRange = (lines, from, to) => {
458
- const start = lines.findIndex((line) => line.from >= from);
459
- const end = lines.findIndex((line) => line.to >= to);
460
- return [
461
- start,
462
- end
463
- ];
464
- };
465
- var code2 = () => {
466
- const getDecorations = (view) => {
467
- const decorations = [];
468
- if (view.state.readOnly) {
469
- const text = view.state.doc.sliceString(0);
470
- const matches = text.matchAll(CODE_REGEX);
471
- const blocks = view.viewportLineBlocks;
472
- for (const match of matches) {
473
- const range = getLineRange(blocks, match.index, match.index + match[0].length);
474
- for (let i = range[0]; i <= range[1]; i++) {
475
- const block = blocks[i];
476
- decorations.push(Decoration.line({
477
- class: mx2("cm-codeblock", i === range[0] && "cm-codeblock-first", i === range[1] && "cm-codeblock-last")
478
- }).range(block.from));
479
- }
480
- }
481
- }
482
- return Decoration.set(decorations);
483
- };
484
- return [
485
- ViewPlugin.fromClass(class {
486
- constructor(view) {
487
- this.decorations = getDecorations(view);
488
- }
489
- update(update4) {
490
- if (update4.docChanged || update4.viewportChanged) {
491
- this.decorations = getDecorations(update4.view);
492
- }
493
- }
494
- }, {
495
- decorations: (value) => value.decorations
496
- }),
497
- styles
498
- ];
499
- };
500
-
501
- // packages/ui/react-ui-editor/src/extensions/comments.ts
502
- import { StateEffect as StateEffect2, StateField as StateField3 } from "@codemirror/state";
503
- import { hoverTooltip, keymap as keymap3, Decoration as Decoration2, EditorView as EditorView4, MatchDecorator, ViewPlugin as ViewPlugin3, WidgetType } from "@codemirror/view";
504
- import get3 from "lodash.get";
505
- import sortBy from "lodash.sortby";
506
- import { debounce } from "@dxos/async";
507
- import { invariant as invariant3 } from "@dxos/invariant";
508
- import { log as log3 } from "@dxos/log";
509
- import { nonNullable } from "@dxos/util";
510
-
511
- // packages/ui/react-ui-editor/src/extensions/util.ts
512
- import { log } from "@dxos/log";
513
- var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/extensions/util.ts";
514
- var callbackWrapper = (fn) => (...args) => {
515
- try {
516
- return fn(...args);
517
- } catch (error) {
518
- log.catch(error, void 0, {
519
- F: __dxlog_file2,
520
- L: 16,
521
- S: void 0,
522
- C: (f, a) => f(...a)
523
- });
524
- }
525
- };
526
-
527
- // packages/ui/react-ui-editor/src/hooks/useTextModel.ts
528
- import { StateField as StateField2 } from "@codemirror/state";
529
- import get2 from "lodash.get";
530
- import { useEffect, useState } from "react";
531
- import { yCollab } from "y-codemirror.next";
532
- import * as Y from "yjs";
533
- import { invariant as invariant2 } from "@dxos/invariant";
534
- import { getRawDoc, isActualAutomergeObject } from "@dxos/react-client/echo";
535
- import { arrayToString, stringToArray } from "@dxos/util";
536
-
537
- // packages/ui/react-ui-editor/src/hooks/automerge/plugin.ts
538
- import { Annotation, Facet, StateEffect, StateField } from "@codemirror/state";
539
- import { ViewPlugin as ViewPlugin2 } from "@codemirror/view";
540
- import * as automerge2 from "@dxos/automerge/automerge";
541
-
542
- // packages/ui/react-ui-editor/src/hooks/automerge/semaphore.ts
543
- import { next as automerge } from "@dxos/automerge/automerge";
544
-
545
- // packages/ui/react-ui-editor/src/hooks/automerge/update-automerge.ts
546
- import { next as am } from "@dxos/automerge/automerge";
547
- var updateAutomerge = (field, handle, transactions, state) => {
548
- const { lastHeads, path } = state.field(field);
549
- let hasChanges = false;
550
- for (const tr of transactions) {
551
- tr.changes.iterChanges(() => {
552
- hasChanges = true;
553
- });
554
- }
555
- if (!hasChanges) {
556
- return void 0;
557
- }
558
- const newHeads = handle.changeAt(lastHeads, (doc) => {
559
- for (const tr of transactions) {
560
- tr.changes.iterChanges((fromA, toA, _fromB, _toB, inserted) => {
561
- am.splice(doc, path, fromA, toA - fromA, inserted.toString());
562
- });
563
- }
564
- });
565
- return newHeads ?? void 0;
566
- };
567
-
568
- // packages/ui/react-ui-editor/src/hooks/automerge/update-codemirror.ts
569
- import { ChangeSet } from "@codemirror/state";
570
- var updateCodeMirror = (view, selection, target, patches) => {
571
- for (const patch of patches) {
572
- const changeSpec = handlePatch(patch, target, view.state);
573
- if (changeSpec != null) {
574
- const changeSet = ChangeSet.of(changeSpec, view.state.doc.length, "\n");
575
- selection = selection.map(changeSet, 1);
576
- view.dispatch({
577
- changes: changeSet,
578
- annotations: reconcileAnnotationType.of({})
579
- });
580
- }
581
- }
582
- view.dispatch({
583
- selection,
584
- annotations: reconcileAnnotationType.of({})
585
- });
586
- };
587
- var handlePatch = (patch, target, state) => {
588
- if (patch.action === "insert") {
589
- return handleInsert(target, patch);
590
- } else if (patch.action === "splice") {
591
- return handleSplice(target, patch);
592
- } else if (patch.action === "del") {
593
- return handleDel(target, patch);
594
- } else if (patch.action === "put") {
595
- return handlePut(target, patch, state);
596
- } else {
597
- return null;
598
- }
599
- };
600
- var handleInsert = (target, patch) => {
601
- const index = charPath(target, patch.path);
602
- if (index == null) {
603
- return [];
604
- }
605
- const text = patch.values.map((v) => v ? v.toString() : "").join("");
606
- return [
607
- {
608
- from: index,
609
- to: index,
610
- insert: text
611
- }
612
- ];
613
- };
614
- var handleSplice = (target, patch) => {
615
- const index = charPath(target, patch.path);
616
- if (index == null) {
617
- return [];
618
- }
619
- return [
620
- {
621
- from: index,
622
- insert: patch.value
894
+ function throttle(callback, limit) {
895
+ let wait = false;
896
+ return function(...args) {
897
+ if (!wait) {
898
+ callback.apply(this, args);
899
+ wait = true;
900
+ setTimeout(() => {
901
+ wait = false;
902
+ }, limit);
623
903
  }
624
- ];
625
- };
626
- var handleDel = (target, patch) => {
627
- const index = charPath(target, patch.path);
628
- if (index == null) {
629
- return [];
904
+ };
905
+ }
906
+ var getRGBComponents = (node, color) => {
907
+ if (typeof color === "function") {
908
+ return color();
630
909
  }
631
- const length = patch.length || 1;
632
- return [
633
- {
634
- from: index,
635
- to: index + length
910
+ const bgColor = getComputedStyle(node).color;
911
+ if (bgColor) {
912
+ const x = bgColor.match(/(\d+), (\d+), (\d+)/)?.slice(1);
913
+ if (x) {
914
+ return x;
636
915
  }
637
- ];
638
- };
639
- var handlePut = (target, patch, state) => {
640
- const index = charPath(target, [
641
- ...patch.path,
642
- 0
643
- ]);
644
- if (index == null) {
645
- return [];
646
- }
647
- const length = state.doc.length;
648
- if (typeof patch.value !== "string") {
649
- return [];
650
916
  }
651
917
  return [
652
- {
653
- from: 0,
654
- to: length,
655
- insert: patch.value
656
- }
918
+ 50,
919
+ 50,
920
+ 50
657
921
  ];
658
922
  };
659
- var charPath = (textPath, candidatePath) => {
660
- if (candidatePath.length !== textPath.length + 1) {
661
- return null;
662
- }
663
- for (let i = 0; i < textPath.length; i++) {
664
- if (textPath[i] !== candidatePath[i]) {
665
- return null;
666
- }
667
- }
668
- const index = candidatePath[candidatePath.length - 1];
669
- if (typeof index === "number") {
670
- return index;
671
- }
672
- return null;
673
- };
674
-
675
- // packages/ui/react-ui-editor/src/hooks/automerge/semaphore.ts
676
- var PatchSemaphore = class {
677
- constructor(field) {
678
- this._inReconcile = false;
679
- this._queue = [];
680
- this.reconcile = (handle, view) => {
681
- if (this._inReconcile) {
682
- return;
683
- }
684
- this._inReconcile = true;
685
- const path = getPath(view.state, this._field);
686
- const oldHeads = getLastHeads(view.state, this._field);
687
- let selection = view.state.selection;
688
- const transactions = view.state.field(this._field).unreconciledTransactions.filter((tx) => !isReconcileTx(tx));
689
- const toInvert = transactions.slice().reverse();
690
- for (const tx of toInvert) {
691
- const inverted = tx.changes.invert(tx.startState.doc);
692
- selection = selection.map(inverted);
693
- view.dispatch({
694
- changes: inverted,
695
- annotations: reconcileAnnotationType.of(true)
696
- });
697
- }
698
- let newHeads = updateAutomerge(this._field, handle, transactions, view.state);
699
- if (newHeads === null || newHeads === void 0) {
700
- newHeads = automerge.getHeads(handle.docSync());
701
- }
702
- const diff = automerge.equals(oldHeads, newHeads) ? [] : automerge.diff(handle.docSync(), oldHeads, newHeads);
703
- updateCodeMirror(view, selection, path, diff);
704
- view.dispatch({
705
- effects: updateHeads(newHeads),
706
- annotations: reconcileAnnotationType.of({})
707
- });
708
- this._inReconcile = false;
709
- };
710
- if (field !== void 0) {
711
- this._field = field;
712
- }
923
+ var random = (min, max) => {
924
+ if (!max) {
925
+ max = min;
926
+ min = 0;
713
927
  }
928
+ return min + ~~(Math.random() * (max - min + 1));
714
929
  };
715
930
 
716
- // packages/ui/react-ui-editor/src/hooks/automerge/plugin.ts
717
- var effectType = StateEffect.define({});
718
- var updateHeads = (newHeads) => effectType.of({
719
- newHeads
720
- });
721
- var getLastHeads = (state, field) => state.field(field).lastHeads;
722
- var getPath = (state, field) => state.field(field).path;
723
- var semaphoreFacet = Facet.define({
724
- combine: (values) => values.at(-1)
725
- });
726
- var automergePlugin = (handle, path) => {
727
- const stateField = StateField.define({
728
- create: () => ({
729
- lastHeads: automerge2.getHeads(handle.docSync()),
730
- unreconciledTransactions: [],
731
- path: path.slice()
732
- }),
733
- update: (value, tr) => {
734
- const result = {
735
- lastHeads: value.lastHeads,
736
- unreconciledTransactions: value.unreconciledTransactions.slice(),
737
- path: path.slice()
738
- };
739
- let clearUnreconciled = false;
740
- for (const effect of tr.effects) {
741
- if (effect.is(effectType)) {
742
- result.lastHeads = effect.value.newHeads;
743
- clearUnreconciled = true;
744
- }
745
- }
746
- if (clearUnreconciled) {
747
- result.unreconciledTransactions = [];
748
- } else {
749
- if (!isReconcileTx(tr)) {
750
- result.unreconciledTransactions.push(tr);
751
- }
752
- }
753
- return result;
754
- }
755
- });
756
- const semaphore = new PatchSemaphore(stateField);
757
- const viewPlugin = ViewPlugin2.fromClass(class AutomergeCodemirrorViewPlugin {
758
- constructor(_view) {
759
- this._view = _view;
760
- this._handleChange = () => {
761
- this._view.state.facet(semaphoreFacet).reconcile(handle, this._view);
762
- };
763
- handle.addListener("change", this._handleChange);
764
- }
765
- update(update4) {
766
- if (update4.transactions.length > 0 && update4.transactions.some((tr) => !isReconcileTx(tr))) {
767
- queueMicrotask(() => {
768
- this._view.state.facet(semaphoreFacet).reconcile(handle, this._view);
769
- });
770
- }
771
- }
772
- destroy() {
773
- handle.addListener("change", this._handleChange);
774
- }
775
- });
776
- return {
777
- extension: [
778
- stateField,
779
- semaphoreFacet.of(semaphore),
780
- viewPlugin
781
- ]
782
- };
783
- };
784
- var reconcileAnnotationType = Annotation.define();
785
- var isReconcileTx = (tr) => !!tr.annotation(reconcileAnnotationType);
931
+ // packages/ui/react-ui-editor/src/extensions/code.ts
932
+ import { ViewPlugin as ViewPlugin3, EditorView as EditorView4, Decoration as Decoration2 } from "@codemirror/view";
933
+ import { mx as mx2 } from "@dxos/react-ui-theme";
786
934
 
787
- // packages/ui/react-ui-editor/src/hooks/yjs/cursors.ts
935
+ // packages/ui/react-ui-editor/src/styles/cursors.ts
788
936
  import * as random2 from "lib0/random";
789
937
  var cursorColors = [
790
938
  {
@@ -807,231 +955,150 @@ var cursorColors = [
807
955
  color: "#ee6352",
808
956
  light: "#ee635233"
809
957
  },
810
- {
811
- color: "#9ac2c9",
812
- light: "#9ac2c933"
958
+ {
959
+ color: "#9ac2c9",
960
+ light: "#9ac2c933"
961
+ },
962
+ {
963
+ color: "#8acb88",
964
+ light: "#8acb8833"
965
+ },
966
+ {
967
+ color: "#1be7ff",
968
+ light: "#1be7ff33"
969
+ }
970
+ ];
971
+ var cursorColor = cursorColors[random2.uint32() % cursorColors.length];
972
+
973
+ // packages/ui/react-ui-editor/src/styles/markdown.ts
974
+ import { mx } from "@dxos/react-ui-theme";
975
+ var headings = {
976
+ 1: [
977
+ "mbs-4 mbe-2 font-medium text-inherit no-underline text-4xl",
978
+ "-ml-[10px]"
979
+ ],
980
+ 2: [
981
+ "mbs-4 mbe-2 font-medium text-inherit no-underline text-3xl",
982
+ "-ml-[8px]"
983
+ ],
984
+ 3: [
985
+ "mbs-4 mbe-2 font-medium text-inherit no-underline text-2xl",
986
+ "-ml-[7px]"
987
+ ],
988
+ 4: [
989
+ "mbs-4 mbe-2 font-medium text-inherit no-underline text-xl",
990
+ "-ml-[6px]"
991
+ ],
992
+ 5: [
993
+ "mbs-4 mbe-2 font-medium text-inherit no-underline text-lg",
994
+ "-ml-[5px]"
995
+ ],
996
+ 6: [
997
+ "mbs-4 mbe-2 font-medium text-inherit no-underline",
998
+ "-ml-[4px]"
999
+ ]
1000
+ };
1001
+ var heading = (level, readonly) => {
1002
+ const [style, offset] = headings[level];
1003
+ return mx(style, readonly && offset);
1004
+ };
1005
+ var light = "text-neutral-200 dark:text-neutral-800";
1006
+ var mark = mx("!font-normal !no-underline !text-inherit opacity-40", light);
1007
+ var bold = "font-bold";
1008
+ var italic = "italic";
1009
+ var strikethrough = "line-through";
1010
+ var code = "font-mono !no-underline text-neutral-700 dark:text-neutral-300";
1011
+ var codeMark = "font-mono text-primary-500";
1012
+ var inlineUrl = mx(code, "px-1");
1013
+ var blockquote = mx("pl-1 mr-1 border-is-4 border-primary-500/70 dark:border-primary-500/30", light);
1014
+
1015
+ // packages/ui/react-ui-editor/src/styles/tokens.ts
1016
+ import get2 from "lodash.get";
1017
+ import { tailwindConfig } from "@dxos/react-ui-theme";
1018
+ var tokens = tailwindConfig({}).theme;
1019
+ var getToken = (path, defaultValue = void 0) => get2(tokens, path, defaultValue);
1020
+
1021
+ // packages/ui/react-ui-editor/src/extensions/code.ts
1022
+ var CODE_REGEX = /```[\s\S]*?```/gs;
1023
+ var styles2 = EditorView4.baseTheme({
1024
+ "& .cm-codeblock": {
1025
+ fontFamily: getToken("fontFamily.mono", []).join(",")
1026
+ },
1027
+ '&light [aria-readonly="true"] .cm-codeblock': {
1028
+ background: getToken("extend.colors.neutral.50")
1029
+ },
1030
+ '&dark [aria-readonly="true"] .cm-codeblock': {
1031
+ background: getToken("extend.colors.neutral.850")
1032
+ },
1033
+ '& [aria-readonly="true"] .cm-codeblock': {
1034
+ display: "block",
1035
+ paddingInline: "4px !important"
813
1036
  },
814
- {
815
- color: "#8acb88",
816
- light: "#8acb8833"
1037
+ '& [aria-readonly="true"] .cm-codeblock-first': {
1038
+ paddingTop: "4px !important",
1039
+ borderTopLeftRadius: "4px",
1040
+ borderTopRightRadius: "4px"
817
1041
  },
818
- {
819
- color: "#1be7ff",
820
- light: "#1be7ff33"
821
- }
822
- ];
823
- var cursorColor = cursorColors[random2.uint32() % cursorColors.length];
824
-
825
- // packages/ui/react-ui-editor/src/hooks/yjs/space-provider.ts
826
- import * as decoding from "lib0/decoding";
827
- import * as encoding from "lib0/encoding";
828
- import { Observable } from "lib0/observable";
829
- import * as awarenessProtocol from "y-protocols/awareness";
830
- import { log as log2 } from "@dxos/log";
831
- var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/hooks/yjs/space-provider.ts";
832
- var messageAwareness = 1;
833
- var messageQueryAwareness = 3;
834
- var SpaceAwarenessProvider = class extends Observable {
835
- constructor({ space, doc, channel, awareness }) {
836
- super();
837
- this._space = space;
838
- this._awareness = awareness ?? new awarenessProtocol.Awareness(doc);
839
- this._channel = channel;
840
- this._clientId = doc.clientID;
841
- this._awareness.on("update", this._handleAwarenessUpdate.bind(this));
842
- this._space.listen(this._channel, this._handleSpaceMessage.bind(this));
843
- if (typeof window !== "undefined") {
844
- window.addEventListener("beforeunload", this._handleBeforeUnload.bind(this));
845
- } else if (typeof process !== "undefined") {
846
- process.on("exit", this._handleBeforeUnload.bind(this));
847
- }
848
- const encoderAwarenessQuery = encoding.createEncoder();
849
- encoding.writeVarUint(encoderAwarenessQuery, messageQueryAwareness);
850
- void this._space.postMessage(this._channel, encoding.toUint8Array(encoderAwarenessQuery));
851
- const encoderAwarenessState = encoding.createEncoder();
852
- encoding.writeVarUint(encoderAwarenessState, messageAwareness);
853
- encoding.writeVarUint8Array(encoderAwarenessState, awarenessProtocol.encodeAwarenessUpdate(this.awareness, [
854
- this._clientId
855
- ]));
856
- void this._space.postMessage(this._channel, encoding.toUint8Array(encoderAwarenessState));
857
- }
858
- get awareness() {
859
- return this._awareness;
860
- }
861
- _handleAwarenessUpdate({ added, updated, removed }, origin) {
862
- log2("awareness update", {
863
- added,
864
- updated,
865
- removed,
866
- origin
867
- }, {
868
- F: __dxlog_file3,
869
- L: 67,
870
- S: this,
871
- C: (f, a) => f(...a)
872
- });
873
- const changedClients = added.concat(updated).concat(removed);
874
- const encoderAwareness = encoding.createEncoder();
875
- encoding.writeVarUint(encoderAwareness, messageAwareness);
876
- encoding.writeVarUint8Array(encoderAwareness, awarenessProtocol.encodeAwarenessUpdate(this._awareness, changedClients));
877
- void this._space.postMessage(this._channel, encoding.toUint8Array(encoderAwareness));
878
- }
879
- _handleSpaceMessage({ payload }) {
880
- log2("space message", payload, {
881
- F: __dxlog_file3,
882
- L: 79,
883
- S: this,
884
- C: (f, a) => f(...a)
885
- });
886
- const data = new Uint8Array(Array.from(Object.values(payload)));
887
- const encoder = this._readMessage(data);
888
- if (encoder) {
889
- void this._space.postMessage(this._channel, encoding.toUint8Array(encoder));
890
- }
891
- }
892
- _readMessage(message) {
893
- const decoder = decoding.createDecoder(message);
894
- const encoder = encoding.createEncoder();
895
- const messageType = decoding.readVarUint(decoder);
896
- let sendReply = false;
897
- switch (messageType) {
898
- case messageAwareness: {
899
- awarenessProtocol.applyAwarenessUpdate(this._awareness, decoding.readVarUint8Array(decoder), this);
900
- break;
901
- }
902
- case messageQueryAwareness: {
903
- encoding.writeVarUint(encoder, messageAwareness);
904
- encoding.writeVarUint8Array(encoder, awarenessProtocol.encodeAwarenessUpdate(this._awareness, Array.from(this._awareness.getStates().keys())));
905
- sendReply = true;
906
- break;
907
- }
908
- default: {
909
- console.error("Invalid message:", messageType);
910
- return encoder;
911
- }
912
- }
913
- if (!sendReply) {
914
- return null;
915
- }
916
- return encoder;
917
- }
918
- _handleBeforeUnload() {
919
- awarenessProtocol.removeAwarenessStates(this._awareness, [
920
- this._clientId
921
- ], "window unload");
1042
+ '& [aria-readonly="true"] .cm-codeblock-last': {
1043
+ paddingBottom: "4px !important",
1044
+ borderBottomLeftRadius: "4px",
1045
+ borderBottomRightRadius: "4px"
922
1046
  }
923
- };
924
-
925
- // packages/ui/react-ui-editor/src/hooks/useTextModel.ts
926
- var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/hooks/useTextModel.ts";
927
- var modelState = StateField2.define({
928
- create: () => void 0,
929
- update: (model) => model
930
1047
  });
931
- var useTextModel = (props) => {
932
- const { identity, space, text } = props;
933
- const [model, setModel] = useState(() => createModel(props));
934
- useEffect(() => setModel(createModel(props)), [
935
- identity,
936
- space,
937
- text
938
- ]);
939
- return model;
1048
+ var getLineRange = (lines, from, to) => {
1049
+ const start = lines.findIndex((line) => line.from >= from);
1050
+ const end = lines.findIndex((line) => line.to >= to);
1051
+ return [
1052
+ start,
1053
+ end
1054
+ ];
940
1055
  };
941
- var createModel = (props) => {
942
- const { text } = props;
943
- if (isActualAutomergeObject(text)) {
944
- return createAutomergeModel(props);
945
- } else {
946
- if (!text?.doc) {
947
- return void 0;
1056
+ var code2 = () => {
1057
+ const getDecorations = (view) => {
1058
+ const decorations = [];
1059
+ if (view.state.readOnly) {
1060
+ const text = view.state.doc.sliceString(0);
1061
+ const matches = text.matchAll(CODE_REGEX);
1062
+ const blocks = view.viewportLineBlocks;
1063
+ for (const match of matches) {
1064
+ const range = getLineRange(blocks, match.index, match.index + match[0].length);
1065
+ for (let i = range[0]; i <= range[1]; i++) {
1066
+ const block = blocks[i];
1067
+ decorations.push(Decoration2.line({
1068
+ class: mx2("cm-codeblock", i === range[0] && "cm-codeblock-first", i === range[1] && "cm-codeblock-last")
1069
+ }).range(block.from));
1070
+ }
1071
+ }
948
1072
  }
949
- return createYjsModel(props);
950
- }
951
- };
952
- var createYjsModel = ({ identity, space, text }) => {
953
- invariant2(text?.doc && text?.content, void 0, {
954
- F: __dxlog_file4,
955
- L: 97,
956
- S: void 0,
957
- A: [
958
- "text?.doc && text?.content",
959
- ""
960
- ]
961
- });
962
- const provider = space ? new SpaceAwarenessProvider({
963
- space,
964
- doc: text.doc,
965
- channel: `yjs.awareness.${text.id}`
966
- }) : void 0;
967
- const model = {
968
- id: text.doc.guid,
969
- content: text.content,
970
- text: () => text.content.toString(),
971
- // https://github.com/yjs/yjs?tab=readme-ov-file#relative-positions
972
- getCursorFromRange: (range) => {
973
- const from = Y.encodeRelativePosition(Y.createRelativePositionFromTypeIndex(text.content, range.from));
974
- const to = Y.encodeRelativePosition(Y.createRelativePositionFromTypeIndex(text.content, range.to, -1));
975
- return [
976
- arrayToString(from),
977
- arrayToString(to)
978
- ].join(":");
979
- },
980
- getRangeFromCursor: (cursor) => {
981
- invariant2(text.doc, void 0, {
982
- F: __dxlog_file4,
983
- L: 113,
984
- S: void 0,
985
- A: [
986
- "text.doc",
987
- ""
988
- ]
989
- });
990
- const parts = cursor.split(":");
991
- const from = Y.createAbsolutePositionFromRelativePosition(Y.decodeRelativePosition(stringToArray(parts[0])), text.doc);
992
- const to = Y.createAbsolutePositionFromRelativePosition(Y.decodeRelativePosition(stringToArray(parts[1])), text.doc);
993
- return from && to ? {
994
- from: from.index,
995
- to: to.index
996
- } : void 0;
997
- },
998
- extension: [
999
- yCollab(text.content, provider?.awareness),
1000
- modelState.init(() => model)
1001
- ],
1002
- awareness: provider?.awareness,
1003
- peer: identity ? {
1004
- id: identity.identityKey.toHex(),
1005
- name: identity.profile?.displayName
1006
- } : void 0
1007
- };
1008
- return model;
1009
- };
1010
- var createAutomergeModel = ({ identity, text }) => {
1011
- const obj = text;
1012
- const doc = getRawDoc(obj, [
1013
- obj.field
1014
- ]);
1015
- const model = {
1016
- id: obj.id,
1017
- content: doc,
1018
- text: () => get2(doc.handle.docSync(), doc.path),
1019
- // TODO(burdon): https://automerge.org/automerge/api-docs/js/functions/next.getCursor.html
1020
- extension: [
1021
- automergePlugin(doc.handle, doc.path),
1022
- modelState.init(() => model)
1023
- ],
1024
- peer: identity ? {
1025
- id: identity.identityKey.toHex(),
1026
- name: identity.profile?.displayName
1027
- } : void 0
1073
+ return Decoration2.set(decorations);
1028
1074
  };
1029
- return model;
1075
+ return [
1076
+ ViewPlugin3.fromClass(class {
1077
+ constructor(view) {
1078
+ this.decorations = getDecorations(view);
1079
+ }
1080
+ update(update2) {
1081
+ if (update2.docChanged || update2.viewportChanged) {
1082
+ this.decorations = getDecorations(update2.view);
1083
+ }
1084
+ }
1085
+ }, {
1086
+ decorations: (value) => value.decorations
1087
+ }),
1088
+ styles2
1089
+ ];
1030
1090
  };
1031
1091
 
1032
1092
  // packages/ui/react-ui-editor/src/extensions/comments.ts
1033
- var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/extensions/comments.ts";
1034
- var styles2 = EditorView4.baseTheme({
1093
+ import { StateEffect as StateEffect2, StateField as StateField2 } from "@codemirror/state";
1094
+ import { hoverTooltip, keymap as keymap3, Decoration as Decoration3, EditorView as EditorView5, MatchDecorator, ViewPlugin as ViewPlugin4, WidgetType as WidgetType2 } from "@codemirror/view";
1095
+ import sortBy from "lodash.sortby";
1096
+ import { debounce } from "@dxos/async";
1097
+ import { invariant as invariant2 } from "@dxos/invariant";
1098
+ import { log as log2 } from "@dxos/log";
1099
+ import { nonNullable } from "@dxos/util";
1100
+ var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/extensions/comments.ts";
1101
+ var styles3 = EditorView5.baseTheme({
1035
1102
  "& .cm-bookmark": {
1036
1103
  cursor: "pointer",
1037
1104
  margin: "4px",
@@ -1042,17 +1109,17 @@ var styles2 = EditorView4.baseTheme({
1042
1109
  backgroundColor: "orange"
1043
1110
  },
1044
1111
  "& .cm-comment": {
1045
- backgroundColor: get3(tokens, "extend.colors.yellow.50")
1112
+ backgroundColor: getToken("extend.colors.yellow.50")
1046
1113
  },
1047
1114
  "& .cm-comment-active": {
1048
- backgroundColor: get3(tokens, "extend.colors.yellow.100")
1115
+ backgroundColor: getToken("extend.colors.yellow.100")
1049
1116
  }
1050
1117
  });
1051
1118
  var marks = {
1052
- highlight: Decoration2.mark({
1119
+ highlight: Decoration3.mark({
1053
1120
  class: "cm-comment"
1054
1121
  }),
1055
- highlightActive: Decoration2.mark({
1122
+ highlightActive: Decoration3.mark({
1056
1123
  class: "cm-comment-active"
1057
1124
  })
1058
1125
  };
@@ -1074,11 +1141,12 @@ var setFocus = (view, thread) => {
1074
1141
  var setCommentRange = StateEffect2.define();
1075
1142
  var setSelection = StateEffect2.define();
1076
1143
  var setCommentState = StateEffect2.define();
1077
- var commentsStateField = StateField3.define({
1144
+ var commentsStateField = StateField2.define({
1078
1145
  create: () => ({
1079
1146
  ranges: []
1080
1147
  }),
1081
1148
  update: (value, tr) => {
1149
+ const cursorConverter3 = tr.state.facet(CursorConverter);
1082
1150
  for (const effect of tr.effects) {
1083
1151
  if (effect.is(setSelection)) {
1084
1152
  return {
@@ -1087,9 +1155,9 @@ var commentsStateField = StateField3.define({
1087
1155
  };
1088
1156
  }
1089
1157
  if (effect.is(setCommentRange)) {
1090
- const { model, comments: comments2 } = effect.value;
1158
+ const { comments: comments2 } = effect.value;
1091
1159
  const ranges = comments2.map((comment) => {
1092
- const range = model.getRangeFromCursor(comment.cursor);
1160
+ const range = getRangeFromCursor(cursorConverter3, comment.cursor);
1093
1161
  return range && {
1094
1162
  ...comment,
1095
1163
  ...range
@@ -1107,7 +1175,7 @@ var commentsStateField = StateField3.define({
1107
1175
  return value;
1108
1176
  }
1109
1177
  });
1110
- var highlightDecorations = EditorView4.decorations.compute([
1178
+ var highlightDecorations = EditorView5.decorations.compute([
1111
1179
  commentsStateField
1112
1180
  ], (state) => {
1113
1181
  const { active, ranges } = state.field(commentsStateField);
@@ -1125,17 +1193,17 @@ var highlightDecorations = EditorView4.decorations.compute([
1125
1193
  return marks.highlight.range(range.from, range.to);
1126
1194
  }
1127
1195
  }).filter(nonNullable) ?? [];
1128
- return Decoration2.set(decorations);
1196
+ return Decoration3.set(decorations);
1129
1197
  });
1130
- var BookmarkWidget = class extends WidgetType {
1198
+ var BookmarkWidget = class extends WidgetType2 {
1131
1199
  constructor(_anchor, _id, _handleClick) {
1132
1200
  super();
1133
1201
  this._anchor = _anchor;
1134
1202
  this._id = _id;
1135
1203
  this._handleClick = _handleClick;
1136
- invariant3(this._id, void 0, {
1137
- F: __dxlog_file5,
1138
- L: 167,
1204
+ invariant2(this._id, void 0, {
1205
+ F: __dxlog_file3,
1206
+ L: 168,
1139
1207
  S: this,
1140
1208
  A: [
1141
1209
  "this._id",
@@ -1159,9 +1227,10 @@ var BookmarkWidget = class extends WidgetType {
1159
1227
  var comments = (options = {}) => {
1160
1228
  const handleSelect = debounce((state) => options.onSelect?.(state), 200);
1161
1229
  const createCommentThread = (view) => {
1162
- invariant3(options.onCreate, void 0, {
1163
- F: __dxlog_file5,
1164
- L: 221,
1230
+ const cursorConverter3 = view.state.facet(CursorConverter);
1231
+ invariant2(options.onCreate, void 0, {
1232
+ F: __dxlog_file3,
1233
+ L: 224,
1165
1234
  S: void 0,
1166
1235
  A: [
1167
1236
  "options.onCreate",
@@ -1172,8 +1241,7 @@ var comments = (options = {}) => {
1172
1241
  if (from === to) {
1173
1242
  return false;
1174
1243
  }
1175
- const model = view.state.field(modelState);
1176
- const relPos = model?.getCursorFromRange?.({
1244
+ const relPos = getCursorFromRange(cursorConverter3, {
1177
1245
  from,
1178
1246
  to
1179
1247
  });
@@ -1205,7 +1273,7 @@ var comments = (options = {}) => {
1205
1273
  }
1206
1274
  return false;
1207
1275
  };
1208
- const bookmarksViewPlugin = ViewPlugin3.fromClass(class BookmarkViewPlugin {
1276
+ const bookmarksViewPlugin = ViewPlugin4.fromClass(class BookmarkViewPlugin {
1209
1277
  static {
1210
1278
  // Match markdown footnotes (option).
1211
1279
  // https://www.markdownguide.org/extended-syntax/#footnotes
@@ -1213,7 +1281,7 @@ var comments = (options = {}) => {
1213
1281
  regexp: /\[\^(\w+)\]/g,
1214
1282
  decoration: (match, view, pos) => {
1215
1283
  const id = match[1];
1216
- return Decoration2.replace({
1284
+ return Decoration3.replace({
1217
1285
  id,
1218
1286
  widget: new BookmarkWidget(pos, id)
1219
1287
  });
@@ -1223,20 +1291,20 @@ var comments = (options = {}) => {
1223
1291
  constructor(view) {
1224
1292
  this.bookmarks = BookmarkViewPlugin.bookmarkMatcher.createDeco(view);
1225
1293
  }
1226
- update(update4) {
1227
- this.bookmarks = BookmarkViewPlugin.bookmarkMatcher.updateDeco(update4, this.bookmarks);
1294
+ update(update2) {
1295
+ this.bookmarks = BookmarkViewPlugin.bookmarkMatcher.updateDeco(update2, this.bookmarks);
1228
1296
  }
1229
1297
  }, {
1230
1298
  decorations: (instance) => instance.bookmarks,
1231
- provide: (plugin) => EditorView4.atomicRanges.of((view) => {
1232
- return view.plugin(plugin)?.bookmarks || Decoration2.none;
1299
+ provide: (plugin) => EditorView5.atomicRanges.of((view) => {
1300
+ return view.plugin(plugin)?.bookmarks || Decoration3.none;
1233
1301
  })
1234
1302
  });
1235
1303
  return [
1236
1304
  bookmarksViewPlugin,
1237
1305
  commentsStateField,
1238
1306
  highlightDecorations,
1239
- styles2,
1307
+ styles3,
1240
1308
  //
1241
1309
  // Keymap.
1242
1310
  //
@@ -1279,37 +1347,28 @@ var comments = (options = {}) => {
1279
1347
  // Monitor cursor movement and text updates.
1280
1348
  // TODO(burdon): Is there a better (finer grained) way to do this?
1281
1349
  //
1282
- EditorView4.updateListener.of(({ view, state, startState, changes }) => {
1350
+ EditorView5.updateListener.of(({ view, state, changes }) => {
1351
+ const cursorConverter3 = view.state.facet(CursorConverter);
1283
1352
  {
1284
1353
  let mod = false;
1285
- const model = state.field(modelState);
1286
1354
  const { active, ranges } = state.field(commentsStateField);
1287
1355
  changes.iterChanges((from, to, from2, to2) => {
1288
- invariant3(model, void 0, {
1289
- F: __dxlog_file5,
1290
- L: 350,
1291
- S: void 0,
1292
- A: [
1293
- "model",
1294
- ""
1295
- ]
1296
- });
1297
1356
  ranges.forEach((range) => {
1298
1357
  if (from2 === to2) {
1299
- const newRange = model.getRangeFromCursor(range.cursor);
1358
+ const newRange = getRangeFromCursor(cursorConverter3, range.cursor);
1300
1359
  if (!newRange || newRange.to - newRange.from === 0) {
1301
- log3.info("deleted comment", {
1360
+ log2.info("deleted comment", {
1302
1361
  thread: range.id
1303
1362
  }, {
1304
- F: __dxlog_file5,
1305
- L: 356,
1363
+ F: __dxlog_file3,
1364
+ L: 358,
1306
1365
  S: void 0,
1307
1366
  C: (f, a) => f(...a)
1308
1367
  });
1309
1368
  }
1310
1369
  }
1311
1370
  if (from <= range.to) {
1312
- const newRange = model.getRangeFromCursor(range.cursor);
1371
+ const newRange = getRangeFromCursor(cursorConverter3, range.cursor);
1313
1372
  Object.assign(range, newRange);
1314
1373
  mod = true;
1315
1374
  }
@@ -1358,18 +1417,34 @@ var comments = (options = {}) => {
1358
1417
  })
1359
1418
  ];
1360
1419
  };
1420
+ var getCursorFromRange = (cursorConverter3, range) => {
1421
+ const from = cursorConverter3.toCursor(range.from);
1422
+ const to = cursorConverter3.toCursor(range.to, -1);
1423
+ return [
1424
+ from,
1425
+ to
1426
+ ].join(":");
1427
+ };
1428
+ var getRangeFromCursor = (cursorConverter3, cursor) => {
1429
+ const parts = cursor.split(":");
1430
+ const from = cursorConverter3.fromCursor(parts[0]);
1431
+ const to = cursorConverter3.fromCursor(parts[1]);
1432
+ return from !== void 0 && to !== void 0 ? {
1433
+ from,
1434
+ to
1435
+ } : void 0;
1436
+ };
1361
1437
 
1362
1438
  // packages/ui/react-ui-editor/src/extensions/hr.ts
1363
- import { Decoration as Decoration3, EditorView as EditorView5, MatchDecorator as MatchDecorator2, ViewPlugin as ViewPlugin4, WidgetType as WidgetType2 } from "@codemirror/view";
1364
- import get4 from "lodash.get";
1365
- var styles3 = EditorView5.baseTheme({
1439
+ import { Decoration as Decoration4, EditorView as EditorView6, MatchDecorator as MatchDecorator2, ViewPlugin as ViewPlugin5, WidgetType as WidgetType3 } from "@codemirror/view";
1440
+ var styles4 = EditorView6.baseTheme({
1366
1441
  "& .cm-hr": {
1367
1442
  // TODO(burdon): ???
1368
1443
  // Note that block-level decorations should not have vertical margins,
1369
- borderBottom: `1px solid ${get4(tokens, "extend.colors.neutral.200")}`
1444
+ borderBottom: `1px solid ${getToken("extend.colors.neutral.200")}`
1370
1445
  }
1371
1446
  });
1372
- var HorizontalRuleWidget = class extends WidgetType2 {
1447
+ var HorizontalRuleWidget = class extends WidgetType3 {
1373
1448
  constructor(_pos) {
1374
1449
  super();
1375
1450
  this._pos = _pos;
@@ -1385,41 +1460,63 @@ var HorizontalRuleWidget = class extends WidgetType2 {
1385
1460
  };
1386
1461
  var placeholderMatcher = new MatchDecorator2({
1387
1462
  regexp: /^---$/g,
1388
- decoration: (match, view, pos) => Decoration3.replace({
1463
+ decoration: (match, view, pos) => Decoration4.replace({
1389
1464
  widget: new HorizontalRuleWidget(pos)
1390
1465
  })
1391
1466
  });
1392
1467
  var hr = () => [
1393
- styles3,
1394
- ViewPlugin4.fromClass(class {
1468
+ styles4,
1469
+ ViewPlugin5.fromClass(class {
1395
1470
  constructor(view) {
1396
1471
  this.rules = placeholderMatcher.createDeco(view);
1397
1472
  }
1398
- update(update4) {
1399
- this.rules = placeholderMatcher.updateDeco(update4, this.rules);
1473
+ update(update2) {
1474
+ this.rules = placeholderMatcher.updateDeco(update2, this.rules);
1400
1475
  }
1401
1476
  }, {
1402
1477
  decorations: (instance) => instance.rules,
1403
1478
  // TODO(burdon): Is this really atomic (cursor can move into ---).
1404
- provide: (plugin) => EditorView5.atomicRanges.of((view) => {
1405
- return view.plugin(plugin)?.rules || Decoration3.none;
1479
+ provide: (plugin) => EditorView6.atomicRanges.of((view) => {
1480
+ return view.plugin(plugin)?.rules || Decoration4.none;
1406
1481
  })
1407
1482
  })
1408
1483
  ];
1409
1484
 
1410
1485
  // packages/ui/react-ui-editor/src/extensions/image.ts
1411
1486
  import { syntaxTree } from "@codemirror/language";
1412
- import { RangeSetBuilder, StateField as StateField4 } from "@codemirror/state";
1413
- import { Decoration as Decoration4, EditorView as EditorView6, WidgetType as WidgetType3 } from "@codemirror/view";
1487
+ import { StateField as StateField3 } from "@codemirror/state";
1488
+ import { Decoration as Decoration5, EditorView as EditorView7, WidgetType as WidgetType4 } from "@codemirror/view";
1414
1489
  var image = (options = {}) => {
1415
- return StateField4.define({
1416
- create: (state) => update(state, options),
1417
- update: (_, tr) => update(tr.state, options),
1418
- provide: (field) => EditorView6.decorations.from(field)
1490
+ return StateField3.define({
1491
+ create: (state) => {
1492
+ return Decoration5.set(buildDecorations(0, state.doc.length, state));
1493
+ },
1494
+ update: (value, tr) => {
1495
+ if (!tr.docChanged && !tr.selection) {
1496
+ return value;
1497
+ }
1498
+ const cursor = tr.state.selection.main.head;
1499
+ const oldCursor = tr.changes.mapPos(tr.startState.selection.main.head);
1500
+ let from = Math.min(cursor, oldCursor);
1501
+ let to = Math.max(cursor, oldCursor);
1502
+ tr.changes.iterChangedRanges((fromA, toA, fromB, toB) => {
1503
+ from = Math.min(from, fromB);
1504
+ to = Math.max(to, toB);
1505
+ });
1506
+ from = tr.state.doc.lineAt(from).from;
1507
+ to = tr.state.doc.lineAt(to).to;
1508
+ return value.map(tr.changes).update({
1509
+ filterFrom: from,
1510
+ filterTo: to,
1511
+ filter: () => false,
1512
+ add: buildDecorations(from, to, tr.state)
1513
+ });
1514
+ },
1515
+ provide: (field) => EditorView7.decorations.from(field)
1419
1516
  });
1420
1517
  };
1421
- var update = (state, options) => {
1422
- const builder = new RangeSetBuilder();
1518
+ var buildDecorations = (from, to, state) => {
1519
+ const decorations = [];
1423
1520
  const cursor = state.selection.main.head;
1424
1521
  syntaxTree(state).iterate({
1425
1522
  enter: (node) => {
@@ -1428,22 +1525,23 @@ var update = (state, options) => {
1428
1525
  if (urlNode) {
1429
1526
  const hide = state.readOnly || cursor < node.from || cursor > node.to;
1430
1527
  const url = state.sliceDoc(urlNode.from, urlNode.to);
1431
- builder.add(hide ? node.from : node.to, node.to, Decoration4.replace({
1528
+ decorations.push(Decoration5.replace({
1432
1529
  block: true,
1433
1530
  widget: new ImageWidget(url)
1434
- }));
1531
+ }).range(hide ? node.from : node.to, node.to));
1435
1532
  }
1436
1533
  }
1437
- }
1534
+ },
1535
+ from,
1536
+ to
1438
1537
  });
1439
- return builder.finish();
1538
+ return decorations;
1440
1539
  };
1441
- var ImageWidget = class extends WidgetType3 {
1540
+ var ImageWidget = class extends WidgetType4 {
1442
1541
  constructor(_url) {
1443
1542
  super();
1444
1543
  this._url = _url;
1445
1544
  }
1446
- // TODO(burdon): Does this need to be unique for each position?
1447
1545
  eq(other) {
1448
1546
  return this._url === other._url;
1449
1547
  }
@@ -1451,22 +1549,29 @@ var ImageWidget = class extends WidgetType3 {
1451
1549
  const img = document.createElement("img");
1452
1550
  img.setAttribute("src", this._url);
1453
1551
  img.setAttribute("class", "cm-image");
1552
+ img.onload = () => img.classList.add("cm-loaded-image");
1454
1553
  return img;
1455
1554
  }
1456
1555
  };
1457
1556
 
1458
1557
  // packages/ui/react-ui-editor/src/extensions/link.ts
1459
1558
  import { syntaxTree as syntaxTree2 } from "@codemirror/language";
1460
- import { RangeSetBuilder as RangeSetBuilder2, StateField as StateField5 } from "@codemirror/state";
1461
- import { Decoration as Decoration5, EditorView as EditorView7, WidgetType as WidgetType4, hoverTooltip as hoverTooltip2 } from "@codemirror/view";
1559
+ import { RangeSetBuilder } from "@codemirror/state";
1560
+ import { Decoration as Decoration6, WidgetType as WidgetType5, hoverTooltip as hoverTooltip2, ViewPlugin as ViewPlugin6 } from "@codemirror/view";
1462
1561
  import { tooltipContent } from "@dxos/react-ui-theme";
1463
- var markdownLinkRegexp = /\[([^\]]+)]\(([^)]+)\)/;
1464
1562
  var link = (options = {}) => {
1465
1563
  const extensions = [
1466
- StateField5.define({
1467
- create: (state) => update2(state, options),
1468
- update: (_, tr) => update2(tr.state, options),
1469
- provide: (field) => EditorView7.decorations.from(field)
1564
+ ViewPlugin6.fromClass(class {
1565
+ constructor(view) {
1566
+ this.decorations = buildDecorations2(view, options);
1567
+ }
1568
+ update(update2) {
1569
+ if (update2.docChanged || update2.viewportChanged || update2.selectionSet) {
1570
+ this.decorations = buildDecorations2(update2.view, options);
1571
+ }
1572
+ }
1573
+ }, {
1574
+ decorations: (v) => v.decorations
1470
1575
  })
1471
1576
  ];
1472
1577
  if (options.onHover) {
@@ -1474,35 +1579,25 @@ var link = (options = {}) => {
1474
1579
  // https://codemirror.net/examples/tooltip
1475
1580
  // https://codemirror.net/docs/ref/#view.hoverTooltip
1476
1581
  // https://github.com/codemirror/view/blob/main/src/tooltip.ts
1477
- hoverTooltip2((view, pos) => {
1478
- const { from, text } = view.state.doc.lineAt(pos);
1479
- const p = pos - from;
1480
- let idx = 0;
1481
- let match;
1482
- do {
1483
- match = text.substring(idx).match(markdownLinkRegexp);
1484
- if (!match) {
1485
- match = void 0;
1486
- break;
1487
- }
1488
- idx = text.indexOf(match[0]);
1489
- if (p >= idx && p < idx + match[0].length) {
1490
- break;
1491
- }
1492
- idx += match[0].length;
1493
- } while (true);
1494
- if (!match) {
1582
+ hoverTooltip2((view, pos, side) => {
1583
+ const syntax = syntaxTree2(view.state).resolveInner(pos, side);
1584
+ let link2 = null;
1585
+ for (let i = 0, node = syntax; !link2 && node && i < 5; node = node.parent, i++) {
1586
+ link2 = node.name === "Link" ? node : null;
1587
+ }
1588
+ const url = link2 && link2.getChild("URL");
1589
+ if (!url || !link2) {
1495
1590
  return null;
1496
1591
  }
1497
- const [, , url] = match ?? [];
1592
+ const urlText = view.state.sliceDoc(url.from, url.to);
1498
1593
  return {
1499
- pos: idx + from,
1500
- end: idx + from + match[0].length,
1594
+ pos: link2.from,
1595
+ end: link2.to,
1501
1596
  above: true,
1502
1597
  create: () => {
1503
1598
  const el = document.createElement("div");
1504
1599
  el.className = tooltipContent({}, "pli-2 plb-1");
1505
- options.onHover(el, url);
1600
+ options.onHover(el, urlText);
1506
1601
  return {
1507
1602
  dom: el,
1508
1603
  offset: {
@@ -1517,15 +1612,14 @@ var link = (options = {}) => {
1517
1612
  }
1518
1613
  return extensions;
1519
1614
  };
1520
- var LinkButton = class extends WidgetType4 {
1521
- constructor(_pos, _url, _onAttach) {
1615
+ var LinkButton = class extends WidgetType5 {
1616
+ constructor(_url, _onAttach) {
1522
1617
  super();
1523
- this._pos = _pos;
1524
1618
  this._url = _url;
1525
1619
  this._onAttach = _onAttach;
1526
1620
  }
1527
1621
  eq(other) {
1528
- return this._pos === other._pos && this._url === other._url;
1622
+ return this._url === other._url;
1529
1623
  }
1530
1624
  toDOM(view) {
1531
1625
  const el = document.createElement("span");
@@ -1533,7 +1627,7 @@ var LinkButton = class extends WidgetType4 {
1533
1627
  return el;
1534
1628
  }
1535
1629
  };
1536
- var LinkText = class extends WidgetType4 {
1630
+ var LinkText = class extends WidgetType5 {
1537
1631
  constructor(_text, _url) {
1538
1632
  super();
1539
1633
  this._text = _text;
@@ -1562,33 +1656,38 @@ var LinkText = class extends WidgetType4 {
1562
1656
  return link2;
1563
1657
  }
1564
1658
  };
1565
- var update2 = (state, options) => {
1566
- const builder = new RangeSetBuilder2();
1659
+ var buildDecorations2 = (view, options) => {
1660
+ const builder = new RangeSetBuilder();
1661
+ const { state } = view;
1567
1662
  const cursor = state.selection.main.head;
1568
- syntaxTree2(state).iterate({
1569
- enter: (node) => {
1570
- if (node.name === "Link") {
1571
- const marks2 = node.node.getChildren("LinkMark");
1572
- const text = marks2.length >= 2 ? state.sliceDoc(marks2[0].to, marks2[1].from) : "";
1573
- const urlNode = node.node.getChild("URL");
1574
- const url = urlNode ? state.sliceDoc(urlNode.from, urlNode.to) : "";
1575
- if (!url) {
1663
+ for (const { from, to } of view.visibleRanges) {
1664
+ syntaxTree2(state).iterate({
1665
+ enter: (node) => {
1666
+ if (node.name === "Link") {
1667
+ const marks2 = node.node.getChildren("LinkMark");
1668
+ const text = marks2.length >= 2 ? state.sliceDoc(marks2[0].to, marks2[1].from) : "";
1669
+ const urlNode = node.node.getChild("URL");
1670
+ const url = urlNode ? state.sliceDoc(urlNode.from, urlNode.to) : "";
1671
+ if (!url) {
1672
+ return false;
1673
+ }
1674
+ if (!view.hasFocus || state.readOnly || cursor < node.from || cursor > node.to) {
1675
+ builder.add(node.from, node.to, Decoration6.replace({
1676
+ widget: new LinkText(text, options.link ? url : void 0)
1677
+ }));
1678
+ }
1679
+ if (options.onRender) {
1680
+ builder.add(node.to, node.to, Decoration6.replace({
1681
+ widget: new LinkButton(url, options.onRender)
1682
+ }));
1683
+ }
1576
1684
  return false;
1577
1685
  }
1578
- if (state.readOnly || cursor < node.from || cursor > node.to) {
1579
- builder.add(node.from, node.to, Decoration5.replace({
1580
- widget: new LinkText(text, options.link ? url : void 0)
1581
- }));
1582
- }
1583
- if (options.onRender) {
1584
- builder.add(node.to, node.to, Decoration5.replace({
1585
- widget: new LinkButton(node.from, url, options.onRender)
1586
- }));
1587
- }
1588
- return false;
1589
- }
1590
- }
1591
- });
1686
+ },
1687
+ from,
1688
+ to
1689
+ });
1690
+ }
1592
1691
  return builder.finish();
1593
1692
  };
1594
1693
 
@@ -1600,8 +1699,8 @@ var listener = ({ onFocus, onChange }) => {
1600
1699
  onFocus(focused);
1601
1700
  return null;
1602
1701
  }));
1603
- onChange && extensions.push(EditorView8.updateListener.of((update4) => {
1604
- onChange(update4.state.doc.toString());
1702
+ onChange && extensions.push(EditorView8.updateListener.of((update2) => {
1703
+ onChange(update2.state.doc.toString());
1605
1704
  }));
1606
1705
  return extensions;
1607
1706
  };
@@ -1622,7 +1721,6 @@ import { markdownLanguage } from "@codemirror/lang-markdown";
1622
1721
  import { HighlightStyle } from "@codemirror/language";
1623
1722
  import { tags, styleTags, Tag } from "@lezer/highlight";
1624
1723
  import { Table } from "@lezer/markdown";
1625
- import get5 from "lodash.get";
1626
1724
  var markdownTags = {
1627
1725
  Blockquote: Tag.define(),
1628
1726
  CodeMark: Tag.define(),
@@ -1808,7 +1906,7 @@ var markdownHighlightStyle = (readonly) => {
1808
1906
  ], {
1809
1907
  scope: markdownLanguage,
1810
1908
  all: {
1811
- fontFamily: get5(tokens, "fontFamily.body", []).join(",")
1909
+ fontFamily: getToken("fontFamily.body", []).join(",")
1812
1910
  }
1813
1911
  });
1814
1912
  };
@@ -1889,24 +1987,19 @@ var mention = ({ onSearch }) => {
1889
1987
  });
1890
1988
  };
1891
1989
 
1892
- // packages/ui/react-ui-editor/src/extensions/mermaid.ts
1893
- var mermaid = () => {
1894
- return [];
1895
- };
1896
-
1897
1990
  // packages/ui/react-ui-editor/src/extensions/table.ts
1898
1991
  import { syntaxTree as syntaxTree3 } from "@codemirror/language";
1899
- import { RangeSetBuilder as RangeSetBuilder3, StateField as StateField6 } from "@codemirror/state";
1900
- import { Decoration as Decoration6, EditorView as EditorView10, WidgetType as WidgetType5 } from "@codemirror/view";
1992
+ import { RangeSetBuilder as RangeSetBuilder2, StateField as StateField4 } from "@codemirror/state";
1993
+ import { Decoration as Decoration7, EditorView as EditorView10, WidgetType as WidgetType6 } from "@codemirror/view";
1901
1994
  var table = (options = {}) => {
1902
- return StateField6.define({
1903
- create: (state) => update3(state, options),
1904
- update: (_, tr) => update3(tr.state, options),
1995
+ return StateField4.define({
1996
+ create: (state) => update(state, options),
1997
+ update: (_, tr) => update(tr.state, options),
1905
1998
  provide: (field) => EditorView10.decorations.from(field)
1906
1999
  });
1907
2000
  };
1908
- var update3 = (state, options) => {
1909
- const builder = new RangeSetBuilder3();
2001
+ var update = (state, options) => {
2002
+ const builder = new RangeSetBuilder2();
1910
2003
  const cursor = state.selection.main.head;
1911
2004
  const tables = [];
1912
2005
  const getTable = () => tables[tables.length - 1];
@@ -1946,23 +2039,23 @@ var update3 = (state, options) => {
1946
2039
  });
1947
2040
  tables.forEach((table2) => {
1948
2041
  const hide = state.readOnly || cursor < table2.from || cursor > table2.to;
1949
- hide && builder.add(table2.from, table2.to, Decoration6.replace({
2042
+ hide && builder.add(table2.from, table2.to, Decoration7.replace({
1950
2043
  block: true,
1951
2044
  widget: new TableWidget(table2)
1952
2045
  }));
1953
- builder.add(table2.from, table2.to, Decoration6.mark({
2046
+ builder.add(table2.from, table2.to, Decoration7.mark({
1954
2047
  class: "cm-table"
1955
2048
  }));
1956
2049
  });
1957
2050
  return builder.finish();
1958
2051
  };
1959
- var TableWidget = class extends WidgetType5 {
2052
+ var TableWidget = class extends WidgetType6 {
1960
2053
  constructor(_table) {
1961
2054
  super();
1962
2055
  this._table = _table;
1963
2056
  }
1964
2057
  eq(other) {
1965
- return this._table.from === other?._table?.from;
2058
+ return this._table.header?.join() === other._table.header?.join() && this._table.rows?.join() === other._table.rows?.join();
1966
2059
  }
1967
2060
  toDOM(view) {
1968
2061
  const table2 = document.createElement("table");
@@ -1991,23 +2084,22 @@ var TableWidget = class extends WidgetType5 {
1991
2084
  };
1992
2085
 
1993
2086
  // packages/ui/react-ui-editor/src/extensions/tasklist.ts
1994
- import { EditorView as EditorView11, Decoration as Decoration7, WidgetType as WidgetType6, MatchDecorator as MatchDecorator3, ViewPlugin as ViewPlugin5 } from "@codemirror/view";
1995
- var styles4 = EditorView11.baseTheme({
2087
+ import { EditorView as EditorView11, Decoration as Decoration8, WidgetType as WidgetType7, MatchDecorator as MatchDecorator3, ViewPlugin as ViewPlugin7 } from "@codemirror/view";
2088
+ var styles5 = EditorView11.baseTheme({
1996
2089
  "& .cm-task-item": {
1997
2090
  paddingLeft: "4px",
1998
2091
  paddingRight: "8px"
1999
2092
  }
2000
2093
  });
2001
- var CheckboxWidget = class extends WidgetType6 {
2002
- constructor(_pos, _checked, _indent, _onCheck) {
2094
+ var CheckboxWidget = class extends WidgetType7 {
2095
+ constructor(_checked, _indent, _onCheck) {
2003
2096
  super();
2004
- this._pos = _pos;
2005
2097
  this._checked = _checked;
2006
2098
  this._indent = _indent;
2007
2099
  this._onCheck = _onCheck;
2008
2100
  }
2009
2101
  eq(other) {
2010
- return this._pos === other._pos && this._checked === other._checked && this._indent === other._indent;
2102
+ return this._checked === other._checked && this._indent === other._indent;
2011
2103
  }
2012
2104
  toDOM(view) {
2013
2105
  const wrap = document.createElement("span");
@@ -2038,8 +2130,8 @@ var tasklist = (options = {}) => {
2038
2130
  decoration: (match, view, pos) => {
2039
2131
  const indent = Math.floor(match[1].length / 2);
2040
2132
  const checked = match[2] === "x" || match[2] === "X";
2041
- return Decoration7.replace({
2042
- widget: new CheckboxWidget(pos, checked, indent, view.state.readOnly ? void 0 : (checked2) => {
2133
+ return Decoration8.replace({
2134
+ widget: new CheckboxWidget(checked, indent, view.state.readOnly ? void 0 : (checked2) => {
2043
2135
  const idx = pos + match[0].indexOf("[") + 1;
2044
2136
  view.dispatch({
2045
2137
  changes: {
@@ -2056,22 +2148,22 @@ var tasklist = (options = {}) => {
2056
2148
  });
2057
2149
  }
2058
2150
  });
2059
- const tasks = ViewPlugin5.fromClass(class {
2151
+ const tasks = ViewPlugin7.fromClass(class {
2060
2152
  constructor(view) {
2061
2153
  this.tasks = taskMatcher.createDeco(view);
2062
2154
  }
2063
- update(update4) {
2064
- this.tasks = taskMatcher.updateDeco(update4, this.tasks);
2155
+ update(update2) {
2156
+ this.tasks = taskMatcher.updateDeco(update2, this.tasks);
2065
2157
  }
2066
2158
  }, {
2067
2159
  decorations: (value) => value.tasks,
2068
2160
  provide: (plugin) => EditorView11.atomicRanges.of((view) => {
2069
- return view.plugin(plugin)?.tasks || Decoration7.none;
2161
+ return view.plugin(plugin)?.tasks || Decoration8.none;
2070
2162
  })
2071
2163
  });
2072
2164
  return [
2073
2165
  tasks,
2074
- styles4
2166
+ styles5
2075
2167
  ];
2076
2168
  };
2077
2169
 
@@ -2132,8 +2224,29 @@ var typewriter = ({ delay = 75, items = defaultItems } = {}) => {
2132
2224
  ];
2133
2225
  };
2134
2226
 
2227
+ // packages/ui/react-ui-editor/src/extensions/yjs/yjs.ts
2228
+ import { yCollab } from "y-codemirror.next";
2229
+
2230
+ // packages/ui/react-ui-editor/src/extensions/yjs/cursor.ts
2231
+ import * as Y from "yjs";
2232
+ import { arrayToString, stringToArray } from "@dxos/util";
2233
+ var cursorConverter2 = (text) => ({
2234
+ toCursor: (index, assoc) => {
2235
+ return arrayToString(Y.encodeRelativePosition(Y.createRelativePositionFromTypeIndex(text, index, assoc)));
2236
+ },
2237
+ fromCursor: (cursor) => {
2238
+ return Y.createAbsolutePositionFromRelativePosition(Y.decodeRelativePosition(stringToArray(cursor)), text.doc)?.index ?? 0;
2239
+ }
2240
+ });
2241
+
2242
+ // packages/ui/react-ui-editor/src/extensions/yjs/yjs.ts
2243
+ var yjs = (content, awareness2) => [
2244
+ CursorConverter.of(cursorConverter2(content)),
2245
+ yCollab(content, awareness2)
2246
+ ];
2247
+
2135
2248
  // packages/ui/react-ui-editor/src/themes/default.ts
2136
- import get6 from "lodash.get";
2249
+ import get3 from "lodash.get";
2137
2250
  var defaultTheme = {
2138
2251
  //
2139
2252
  // Main layout:
@@ -2162,21 +2275,21 @@ var defaultTheme = {
2162
2275
  "&.cm-focused": {
2163
2276
  outline: "none"
2164
2277
  },
2165
- "& .cm-scroller": {
2278
+ ".cm-scroller": {
2166
2279
  overflow: "visible",
2167
- fontFamily: get6(tokens, "fontFamily.mono", []).join(",")
2280
+ fontFamily: get3(tokens, "fontFamily.mono", []).join(",")
2168
2281
  },
2169
- "& .cm-content": {
2282
+ ".cm-content": {
2170
2283
  padding: 0,
2171
2284
  // NOTE: Base font size (otherwise defined by HTML tag, which might be different for storybook).
2172
2285
  fontSize: "16px"
2173
2286
  },
2174
2287
  "&light .cm-content": {
2175
- color: get6(tokens, "extend.colors.neutral.900", "black"),
2288
+ color: get3(tokens, "extend.colors.neutral.900", "black"),
2176
2289
  caretColor: "black"
2177
2290
  },
2178
2291
  "&dark .cm-content": {
2179
- color: get6(tokens, "extend.colors.neutral.100", "white"),
2292
+ color: get3(tokens, "extend.colors.neutral.100", "white"),
2180
2293
  caretColor: "white"
2181
2294
  },
2182
2295
  //
@@ -2188,41 +2301,41 @@ var defaultTheme = {
2188
2301
  "&dark .cm-cursor, &dark .cm-dropCursor": {
2189
2302
  borderLeft: "2px solid white"
2190
2303
  },
2191
- "& .cm-placeholder": {
2304
+ ".cm-placeholder": {
2192
2305
  fontWeight: 100
2193
2306
  },
2194
2307
  //
2195
2308
  // line
2196
2309
  //
2197
- "& .cm-line": {
2310
+ ".cm-line": {
2198
2311
  paddingInline: 0
2199
2312
  },
2200
- "& .cm-activeLine": {
2313
+ ".cm-activeLine": {
2201
2314
  background: "inherit"
2202
2315
  },
2203
2316
  //
2204
2317
  // Selection
2205
2318
  //
2206
2319
  "&light .cm-selectionBackground": {
2207
- background: get6(tokens, "extend.colors.primary.100")
2320
+ background: get3(tokens, "extend.colors.primary.100")
2208
2321
  },
2209
2322
  "&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground": {
2210
- background: get6(tokens, "extend.colors.primary.200")
2323
+ background: get3(tokens, "extend.colors.primary.200")
2211
2324
  },
2212
2325
  "&dark .cm-selectionBackground": {
2213
- background: get6(tokens, "extend.colors.primary.700")
2326
+ background: get3(tokens, "extend.colors.primary.700")
2214
2327
  },
2215
2328
  "&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground": {
2216
- background: get6(tokens, "extend.colors.primary.600")
2329
+ background: get3(tokens, "extend.colors.primary.600")
2217
2330
  },
2218
2331
  //
2219
2332
  // Search
2220
2333
  //
2221
2334
  "&light .cm-searchMatch": {
2222
- backgroundColor: get6(tokens, "extend.colors.yellow.100")
2335
+ backgroundColor: get3(tokens, "extend.colors.yellow.100")
2223
2336
  },
2224
2337
  "&dark .cm-searchMatch": {
2225
- backgroundColor: get6(tokens, "extend.colors.yellow.700")
2338
+ backgroundColor: get3(tokens, "extend.colors.yellow.700")
2226
2339
  },
2227
2340
  //
2228
2341
  // collaboration
@@ -2234,95 +2347,101 @@ var defaultTheme = {
2234
2347
  "&dark .cm-ySelection, &dark .cm-yLineSelection": {
2235
2348
  mixBlendMode: "screen"
2236
2349
  },
2237
- "& .cm-ySelectionInfo": {
2350
+ ".cm-ySelectionInfo": {
2238
2351
  padding: "2px 4px",
2239
2352
  marginBlockStart: "-4px"
2240
2353
  },
2241
- "& .cm-ySelection, & .cm-selectionMatch": {
2354
+ ".cm-ySelection, & .cm-selectionMatch": {
2242
2355
  paddingBlockStart: ".15em",
2243
2356
  paddingBlockEnd: ".15em"
2244
2357
  },
2245
- "& .cm-ySelectionCaret": {
2358
+ ".cm-ySelectionCaret": {
2246
2359
  display: "inline-block",
2247
2360
  insetBlockStart: ".1em",
2248
2361
  blockSize: "1.4em",
2249
2362
  verticalAlign: "top"
2250
2363
  },
2251
- "& .cm-yLineSelection": {
2364
+ ".cm-yLineSelection": {
2252
2365
  margin: 0
2253
2366
  },
2254
2367
  //
2255
2368
  // link
2256
2369
  //
2257
- "& .cm-link": {
2258
- color: get6(tokens, "extend.colors.primary.500"),
2370
+ ".cm-link": {
2371
+ color: get3(tokens, "extend.colors.primary.500"),
2259
2372
  textDecorationLine: "underline",
2260
2373
  textDecorationThickness: "1px",
2261
2374
  textUnderlineOffset: "2px",
2262
2375
  borderRadius: ".125rem",
2263
- fontFamily: get6(tokens, "fontFamily.body", []).join(",")
2376
+ fontFamily: get3(tokens, "fontFamily.body", []).join(",")
2264
2377
  },
2265
2378
  //
2266
2379
  // tooltip
2267
2380
  //
2268
- "& .cm-tooltip": {
2381
+ ".cm-tooltip": {
2269
2382
  border: "none"
2270
2383
  },
2271
- "& .cm-tooltip-below": {},
2384
+ ".cm-tooltip-below": {},
2272
2385
  //
2273
2386
  // autocomplete
2274
2387
  //
2275
- "& .cm-tooltip-autocomplete": {
2388
+ ".cm-tooltip-autocomplete": {
2276
2389
  marginTop: "4px",
2277
2390
  marginLeft: "-3px"
2278
2391
  },
2279
- "& .cm-tooltip-autocomplete ul li": {},
2280
- "& .cm-tooltip-autocomplete ul li[aria-selected]": {},
2281
- "& .cm-completionIcon": {
2392
+ ".cm-tooltip-autocomplete ul li": {},
2393
+ ".cm-tooltip-autocomplete ul li[aria-selected]": {},
2394
+ ".cm-completionIcon": {
2282
2395
  display: "none"
2283
2396
  },
2284
- "& .cm-completionLabel": {
2285
- fontFamily: get6(tokens, "fontFamily.body", []).join(",")
2397
+ ".cm-completionLabel": {
2398
+ fontFamily: get3(tokens, "fontFamily.body", []).join(",")
2286
2399
  },
2287
- "& .cm-completionMatchedText": {
2400
+ ".cm-completionMatchedText": {
2288
2401
  textDecoration: "none"
2289
2402
  },
2290
2403
  //
2291
2404
  // widgets
2292
2405
  //
2293
- "& .cm-widgetBuffer": {
2406
+ ".cm-widgetBuffer": {
2294
2407
  display: "none",
2295
2408
  height: 0
2296
2409
  },
2297
2410
  //
2298
2411
  // table
2299
2412
  //
2300
- "& .cm-table *": {
2301
- fontFamily: `${get6(tokens, "fontFamily.mono", []).join(",")} !important`,
2413
+ ".cm-table *": {
2414
+ fontFamily: `${get3(tokens, "fontFamily.mono", []).join(",")} !important`,
2302
2415
  textDecoration: "none !important"
2303
2416
  },
2304
- "& .cm-table-head": {
2417
+ ".cm-table-head": {
2305
2418
  padding: "2px 16px 2px 0px",
2306
- borderBottom: `1px solid ${get6(tokens, "extend.colors.neutral.500")}`,
2419
+ borderBottom: `1px solid ${get3(tokens, "extend.colors.neutral.500")}`,
2307
2420
  fontWeight: 100,
2308
2421
  textAlign: "left",
2309
- color: get6(tokens, "extend.colors.neutral.500")
2422
+ color: get3(tokens, "extend.colors.neutral.500")
2310
2423
  },
2311
- "& .cm-table-cell": {
2424
+ ".cm-table-cell": {
2312
2425
  padding: "2px 16px 2px 0px"
2313
2426
  },
2314
2427
  //
2315
2428
  // image
2316
2429
  //
2317
- "& .cm-image": {
2318
- margin: "0.5rem 0"
2430
+ ".cm-image": {
2431
+ display: "block",
2432
+ height: "0"
2433
+ },
2434
+ ".cm-image.cm-loaded-image": {
2435
+ height: "auto",
2436
+ borderTop: "0.5rem solid transparent",
2437
+ borderBottom: "0.5rem solid transparent"
2319
2438
  },
2320
2439
  //
2321
2440
  // font size
2322
2441
  // TODO(thure): This appears to be the best or only way to set selection caret heights, but it's far more verbose than it needs to be.
2323
2442
  //
2324
- ...Object.keys(get6(tokens, "extend.fontSize", {})).reduce((acc, fontSize) => {
2325
- const height = get6(tokens, [
2443
+ ...Object.keys(get3(tokens, "extend.fontSize", {})).reduce((acc, fontSize) => {
2444
+ const height = get3(tokens, [
2326
2445
  "extend",
2327
2446
  "fontSize",
2328
2447
  fontSize,
@@ -2356,51 +2475,51 @@ var defaultTheme = {
2356
2475
  * </div>
2357
2476
  * </div
2358
2477
  */
2359
- "& .cm-panels": {
2360
- border: `1px solid ${get6(tokens, "extend.colors.neutral.200")}`
2478
+ ".cm-panels": {
2479
+ border: `1px solid ${get3(tokens, "extend.colors.neutral.200")}`
2361
2480
  },
2362
- "& .cm-panel": {
2363
- background: get6(tokens, "extend.colors.neutral.50"),
2364
- fontFamily: get6(tokens, "fontFamily.body", []).join(",")
2481
+ ".cm-panel": {
2482
+ background: get3(tokens, "extend.colors.neutral.50"),
2483
+ fontFamily: get3(tokens, "fontFamily.body", []).join(",")
2365
2484
  },
2366
- "& .cm-button": {
2485
+ ".cm-button": {
2367
2486
  margin: "4px",
2368
- fontFamily: get6(tokens, "fontFamily.body", []).join(","),
2369
- background: get6(tokens, "extend.colors.neutral.100"),
2487
+ fontFamily: get3(tokens, "fontFamily.body", []).join(","),
2488
+ background: get3(tokens, "extend.colors.neutral.100"),
2370
2489
  backgroundImage: "none",
2371
2490
  border: "none",
2372
2491
  "&:hover": {
2373
- background: get6(tokens, "extend.colors.neutral.200")
2492
+ background: get3(tokens, "extend.colors.neutral.200")
2374
2493
  },
2375
2494
  "&:active": {
2376
- background: get6(tokens, "extend.colors.neutral.300"),
2495
+ background: get3(tokens, "extend.colors.neutral.300"),
2377
2496
  backgroundImage: "none"
2378
2497
  }
2379
2498
  },
2380
- "& .cm-panel input[type=checkbox]": {
2499
+ ".cm-panel input[type=checkbox]": {
2381
2500
  marginRight: "0.4rem !important"
2382
2501
  }
2383
2502
  };
2384
2503
  var textTheme = {
2385
- "& .cm-scroller": {
2386
- fontFamily: get6(tokens, "fontFamily.body", []).join(",")
2504
+ ".cm-scroller": {
2505
+ fontFamily: get3(tokens, "fontFamily.body", []).join(",")
2387
2506
  },
2388
- "& .cm-placeholder": {
2389
- fontFamily: get6(tokens, "fontFamily.body", []).join(",")
2507
+ ".cm-placeholder": {
2508
+ fontFamily: get3(tokens, "fontFamily.body", []).join(",")
2390
2509
  }
2391
2510
  };
2392
2511
  var markdownTheme = {
2393
2512
  // NOTE: Must leave base font family as is (i.e., monospace) due to fenced code blocks.
2394
- "& .cm-placeholder": {
2395
- fontFamily: get6(tokens, "fontFamily.body", []).join(",")
2513
+ ".cm-placeholder": {
2514
+ fontFamily: get3(tokens, "fontFamily.body", []).join(",")
2396
2515
  }
2397
2516
  };
2398
2517
  var codeTheme = {
2399
- "& .cm-scroller": {
2400
- fontFamily: get6(tokens, "fontFamily.mono", []).join(",")
2518
+ ".cm-scroller": {
2519
+ fontFamily: get3(tokens, "fontFamily.mono", []).join(",")
2401
2520
  },
2402
- "& .cm-placeholder": {
2403
- fontFamily: get6(tokens, "fontFamily.mono", []).join(",")
2521
+ ".cm-placeholder": {
2522
+ fontFamily: get3(tokens, "fontFamily.mono", []).join(",")
2404
2523
  }
2405
2524
  };
2406
2525
 
@@ -2414,8 +2533,8 @@ var BaseTextEditor = /* @__PURE__ */ forwardRef(({ model, readonly, comments: co
2414
2533
  const tabsterDOMAttribute = useFocusableGroup({
2415
2534
  tabBehavior: "limited"
2416
2535
  });
2417
- const [root, setRoot] = useState2(null);
2418
- const [{ state = void 0, view = void 0 } = {}, setEditor] = useState2();
2536
+ const [root, setRoot] = useState(null);
2537
+ const [{ state = void 0, view = void 0 } = {}, setEditor] = useState();
2419
2538
  useImperativeHandle(forwardedRef, () => ({
2420
2539
  root,
2421
2540
  state,
@@ -2425,10 +2544,10 @@ var BaseTextEditor = /* @__PURE__ */ forwardRef(({ model, readonly, comments: co
2425
2544
  state,
2426
2545
  root
2427
2546
  ]);
2428
- const { awareness, peer } = model;
2429
- useEffect2(() => {
2430
- if (awareness && peer) {
2431
- awareness.setLocalStateField("user", {
2547
+ const { awareness: awareness2, peer } = model;
2548
+ useEffect(() => {
2549
+ if (awareness2 && peer) {
2550
+ awareness2.setLocalStateField("user", {
2432
2551
  name: peer.name ?? generateName(peer.id),
2433
2552
  color: getColorForValue({
2434
2553
  value: peer.id,
@@ -2442,11 +2561,11 @@ var BaseTextEditor = /* @__PURE__ */ forwardRef(({ model, readonly, comments: co
2442
2561
  });
2443
2562
  }
2444
2563
  }, [
2445
- awareness,
2564
+ awareness2,
2446
2565
  peer,
2447
2566
  themeMode
2448
2567
  ]);
2449
- useEffect2(() => {
2568
+ useEffect(() => {
2450
2569
  if (view && comments2?.length) {
2451
2570
  view.dispatch({
2452
2571
  effects: setCommentRange.of({
@@ -2459,7 +2578,7 @@ var BaseTextEditor = /* @__PURE__ */ forwardRef(({ model, readonly, comments: co
2459
2578
  view,
2460
2579
  comments2
2461
2580
  ]);
2462
- useEffect2(() => {
2581
+ useEffect(() => {
2463
2582
  if (!root) {
2464
2583
  return;
2465
2584
  }
@@ -2577,28 +2696,376 @@ var defaultMarkdownSlots = {
2577
2696
  theme: markdownTheme
2578
2697
  }
2579
2698
  };
2699
+
2700
+ // packages/ui/react-ui-editor/src/hooks/automerge.ts
2701
+ import get4 from "lodash.get";
2702
+ import { getRawDoc } from "@dxos/echo-schema";
2703
+ import { isNotNullOrUndefined } from "@dxos/util";
2704
+
2705
+ // packages/ui/react-ui-editor/src/hooks/awareness-provider.ts
2706
+ import { DeferredTask, Event as Event2, sleep } from "@dxos/async";
2707
+ import { Context as Context2 } from "@dxos/context";
2708
+ import { invariant as invariant3 } from "@dxos/invariant";
2709
+ import { log as log3 } from "@dxos/log";
2710
+ var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/hooks/awareness-provider.ts";
2711
+ var DEBOUNCE_INTERVAL = 100;
2712
+ var SpaceAwarenessProvider = class {
2713
+ constructor(params) {
2714
+ this.remoteStateChange = new Event2();
2715
+ this._remoteStates = /* @__PURE__ */ new Map();
2716
+ this._space = params.space;
2717
+ this._channel = params.channel;
2718
+ this._peerId = params.peerId;
2719
+ this._info = params.info;
2720
+ }
2721
+ open() {
2722
+ this._ctx = new Context2();
2723
+ this._postTask = new DeferredTask(this._ctx, async () => {
2724
+ if (this._localState) {
2725
+ await this._space.postMessage(this._channel, {
2726
+ kind: "post",
2727
+ state: this._localState
2728
+ });
2729
+ await sleep(DEBOUNCE_INTERVAL);
2730
+ }
2731
+ });
2732
+ const unsubscribe = this._space.listen(this._channel, (message) => {
2733
+ switch (message.payload.kind) {
2734
+ case "query": {
2735
+ this._handleQueryMessage();
2736
+ break;
2737
+ }
2738
+ case "post": {
2739
+ this._handlePostMessage(message.payload);
2740
+ break;
2741
+ }
2742
+ }
2743
+ });
2744
+ this._ctx.onDispose(unsubscribe);
2745
+ void this._space.postMessage(this._channel, {
2746
+ kind: "query"
2747
+ }).catch((err) => {
2748
+ log3.debug("failed to query awareness", {
2749
+ err
2750
+ }, {
2751
+ F: __dxlog_file4,
2752
+ L: 85,
2753
+ S: this,
2754
+ C: (f, a) => f(...a)
2755
+ });
2756
+ });
2757
+ }
2758
+ close() {
2759
+ void this._ctx?.dispose();
2760
+ this._ctx = void 0;
2761
+ this._postTask = void 0;
2762
+ }
2763
+ update(position) {
2764
+ invariant3(this._postTask, void 0, {
2765
+ F: __dxlog_file4,
2766
+ L: 96,
2767
+ S: this,
2768
+ A: [
2769
+ "this._postTask",
2770
+ ""
2771
+ ]
2772
+ });
2773
+ this._localState = {
2774
+ peerId: this._peerId,
2775
+ position,
2776
+ info: this._info
2777
+ };
2778
+ this._postTask.schedule();
2779
+ }
2780
+ getRemoteStates() {
2781
+ return Array.from(this._remoteStates.values());
2782
+ }
2783
+ _handleQueryMessage() {
2784
+ invariant3(this._postTask, void 0, {
2785
+ F: __dxlog_file4,
2786
+ L: 111,
2787
+ S: this,
2788
+ A: [
2789
+ "this._postTask",
2790
+ ""
2791
+ ]
2792
+ });
2793
+ this._postTask.schedule();
2794
+ }
2795
+ _handlePostMessage(message) {
2796
+ invariant3(message.kind === "post", void 0, {
2797
+ F: __dxlog_file4,
2798
+ L: 116,
2799
+ S: this,
2800
+ A: [
2801
+ "message.kind === 'post'",
2802
+ ""
2803
+ ]
2804
+ });
2805
+ this._remoteStates.set(message.state.peerId, message.state);
2806
+ this.remoteStateChange.emit();
2807
+ }
2808
+ };
2809
+
2810
+ // packages/ui/react-ui-editor/src/hooks/useTextModel.ts
2811
+ import { StateField as StateField5 } from "@codemirror/state";
2812
+ import { useEffect as useEffect2, useState as useState2 } from "react";
2813
+ import { isAutomergeObject } from "@dxos/react-client/echo";
2814
+
2815
+ // packages/ui/react-ui-editor/src/hooks/yjs.ts
2816
+ import * as decoding from "lib0/decoding";
2817
+ import * as encoding from "lib0/encoding";
2818
+ import { Observable } from "lib0/observable";
2819
+ import * as YP from "y-protocols/awareness";
2820
+ import * as Y2 from "yjs";
2821
+ import { invariant as invariant4 } from "@dxos/invariant";
2822
+ import { log as log4 } from "@dxos/log";
2823
+ import { arrayToString as arrayToString2, stringToArray as stringToArray2 } from "@dxos/util";
2824
+ var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/hooks/yjs.ts";
2825
+ var createYjsModel = ({ identity, space, text }) => {
2826
+ invariant4(text?.doc && text?.content, void 0, {
2827
+ F: __dxlog_file5,
2828
+ L: 23,
2829
+ S: void 0,
2830
+ A: [
2831
+ "text?.doc && text?.content",
2832
+ ""
2833
+ ]
2834
+ });
2835
+ const provider = space ? new YAwarenessProvider({
2836
+ space,
2837
+ doc: text.doc,
2838
+ channel: `yjs.awareness.${text.id}`
2839
+ }) : void 0;
2840
+ const model = {
2841
+ id: text.doc.guid,
2842
+ content: text.content,
2843
+ text: () => text.content.toString(),
2844
+ // https://github.com/yjs/yjs?tab=readme-ov-file#relative-positions
2845
+ // TODO(dmaretskyi): Refactor as cursor-converter.
2846
+ getCursorFromRange: (range) => {
2847
+ const from = Y2.encodeRelativePosition(Y2.createRelativePositionFromTypeIndex(text.content, range.from));
2848
+ const to = Y2.encodeRelativePosition(Y2.createRelativePositionFromTypeIndex(text.content, range.to, -1));
2849
+ return [
2850
+ arrayToString2(from),
2851
+ arrayToString2(to)
2852
+ ].join(":");
2853
+ },
2854
+ getRangeFromCursor: (cursor) => {
2855
+ invariant4(text.doc, void 0, {
2856
+ F: __dxlog_file5,
2857
+ L: 40,
2858
+ S: void 0,
2859
+ A: [
2860
+ "text.doc",
2861
+ ""
2862
+ ]
2863
+ });
2864
+ const parts = cursor.split(":");
2865
+ const from = Y2.createAbsolutePositionFromRelativePosition(Y2.decodeRelativePosition(stringToArray2(parts[0])), text.doc);
2866
+ const to = Y2.createAbsolutePositionFromRelativePosition(Y2.decodeRelativePosition(stringToArray2(parts[1])), text.doc);
2867
+ return from && to ? {
2868
+ from: from.index,
2869
+ to: to.index
2870
+ } : void 0;
2871
+ },
2872
+ extension: [
2873
+ modelState.init(() => model),
2874
+ yjs(text.content, provider?.awareness)
2875
+ ],
2876
+ awareness: provider?.awareness,
2877
+ peer: identity ? {
2878
+ id: identity.identityKey.toHex(),
2879
+ name: identity.profile?.displayName
2880
+ } : void 0
2881
+ };
2882
+ return model;
2883
+ };
2884
+ var messageAwareness = 1;
2885
+ var messageQueryAwareness = 3;
2886
+ var YAwarenessProvider = class extends Observable {
2887
+ constructor({ space, doc, channel, awareness: awareness2 }) {
2888
+ super();
2889
+ this._space = space;
2890
+ this._awareness = awareness2 ?? new YP.Awareness(doc);
2891
+ this._channel = channel;
2892
+ this._clientId = doc.clientID;
2893
+ this._awareness.on("update", this._handleAwarenessUpdate.bind(this));
2894
+ this._space.listen(this._channel, this._handleSpaceMessage.bind(this));
2895
+ if (typeof window !== "undefined") {
2896
+ window.addEventListener("beforeunload", this._handleBeforeUnload.bind(this));
2897
+ } else if (typeof process !== "undefined") {
2898
+ process.on("exit", this._handleBeforeUnload.bind(this));
2899
+ }
2900
+ const encoderAwarenessQuery = encoding.createEncoder();
2901
+ encoding.writeVarUint(encoderAwarenessQuery, messageQueryAwareness);
2902
+ void this._space.postMessage(this._channel, encoding.toUint8Array(encoderAwarenessQuery));
2903
+ const encoderAwarenessState = encoding.createEncoder();
2904
+ encoding.writeVarUint(encoderAwarenessState, messageAwareness);
2905
+ encoding.writeVarUint8Array(encoderAwarenessState, YP.encodeAwarenessUpdate(this.awareness, [
2906
+ this._clientId
2907
+ ]));
2908
+ void this._space.postMessage(this._channel, encoding.toUint8Array(encoderAwarenessState));
2909
+ }
2910
+ get awareness() {
2911
+ return this._awareness;
2912
+ }
2913
+ _handleAwarenessUpdate({ added, updated, removed }, origin) {
2914
+ log4("awareness update", {
2915
+ added,
2916
+ updated,
2917
+ removed,
2918
+ origin
2919
+ }, {
2920
+ F: __dxlog_file5,
2921
+ L: 122,
2922
+ S: this,
2923
+ C: (f, a) => f(...a)
2924
+ });
2925
+ const changedClients = added.concat(updated).concat(removed);
2926
+ const encoderAwareness = encoding.createEncoder();
2927
+ encoding.writeVarUint(encoderAwareness, messageAwareness);
2928
+ encoding.writeVarUint8Array(encoderAwareness, YP.encodeAwarenessUpdate(this._awareness, changedClients));
2929
+ void this._space.postMessage(this._channel, encoding.toUint8Array(encoderAwareness));
2930
+ }
2931
+ _handleSpaceMessage({ payload }) {
2932
+ log4("space message", payload, {
2933
+ F: __dxlog_file5,
2934
+ L: 131,
2935
+ S: this,
2936
+ C: (f, a) => f(...a)
2937
+ });
2938
+ const data = new Uint8Array(Array.from(Object.values(payload)));
2939
+ const encoder = this._readMessage(data);
2940
+ if (encoder) {
2941
+ void this._space.postMessage(this._channel, encoding.toUint8Array(encoder));
2942
+ }
2943
+ }
2944
+ _readMessage(message) {
2945
+ const decoder = decoding.createDecoder(message);
2946
+ const encoder = encoding.createEncoder();
2947
+ const messageType = decoding.readVarUint(decoder);
2948
+ let sendReply = false;
2949
+ switch (messageType) {
2950
+ case messageAwareness: {
2951
+ YP.applyAwarenessUpdate(this._awareness, decoding.readVarUint8Array(decoder), this);
2952
+ break;
2953
+ }
2954
+ case messageQueryAwareness: {
2955
+ encoding.writeVarUint(encoder, messageAwareness);
2956
+ encoding.writeVarUint8Array(encoder, YP.encodeAwarenessUpdate(this._awareness, Array.from(this._awareness.getStates().keys())));
2957
+ sendReply = true;
2958
+ break;
2959
+ }
2960
+ default: {
2961
+ console.error("Invalid message:", messageType);
2962
+ return encoder;
2963
+ }
2964
+ }
2965
+ if (!sendReply) {
2966
+ return null;
2967
+ }
2968
+ return encoder;
2969
+ }
2970
+ _handleBeforeUnload() {
2971
+ YP.removeAwarenessStates(this._awareness, [
2972
+ this._clientId
2973
+ ], "window unload");
2974
+ }
2975
+ };
2976
+
2977
+ // packages/ui/react-ui-editor/src/hooks/useTextModel.ts
2978
+ var modelState = StateField5.define({
2979
+ create: () => void 0,
2980
+ update: (model) => model
2981
+ });
2982
+ var useTextModel = (props) => {
2983
+ const { identity, space, text } = props;
2984
+ const [model, setModel] = useState2(() => createModel(props));
2985
+ useEffect2(() => setModel(createModel(props)), [
2986
+ identity,
2987
+ space,
2988
+ text
2989
+ ]);
2990
+ return model;
2991
+ };
2992
+ var createModel = (props) => {
2993
+ const { text } = props;
2994
+ if (isAutomergeObject(text)) {
2995
+ return createAutomergeModel(props);
2996
+ } else if (text?.doc) {
2997
+ return createYjsModel(props);
2998
+ } else {
2999
+ return void 0;
3000
+ }
3001
+ };
3002
+
3003
+ // packages/ui/react-ui-editor/src/hooks/automerge.ts
3004
+ var createAutomergeModel = ({ space, identity, text }) => {
3005
+ const obj = text;
3006
+ const doc = getRawDoc(obj, [
3007
+ obj.field
3008
+ ]);
3009
+ const awarenessProvider = space && new SpaceAwarenessProvider({
3010
+ space,
3011
+ channel: `automerge.awareness.${obj.id}`,
3012
+ info: {
3013
+ displayName: identity?.profile?.displayName ?? "",
3014
+ color: cursorColor.color,
3015
+ lightColor: cursorColor.light
3016
+ },
3017
+ peerId: identity?.identityKey.toHex() ?? "Anonymous"
3018
+ });
3019
+ const model = {
3020
+ id: obj.id,
3021
+ content: doc,
3022
+ text: () => get4(doc.handle.docSync(), doc.path),
3023
+ // TODO(burdon): https://automerge.org/automerge/api-docs/js/functions/next.getCursor.html
3024
+ extension: [
3025
+ modelState.init(() => model),
3026
+ automerge3({
3027
+ handle: doc.handle,
3028
+ path: doc.path
3029
+ }),
3030
+ awarenessProvider && AwarenessProvider.of(awarenessProvider),
3031
+ awareness()
3032
+ ].filter(isNotNullOrUndefined),
3033
+ peer: identity ? {
3034
+ id: identity.identityKey.toHex(),
3035
+ name: identity.profile?.displayName
3036
+ } : void 0
3037
+ };
3038
+ return model;
3039
+ };
2580
3040
  export {
3041
+ AwarenessProvider,
2581
3042
  BaseTextEditor,
2582
3043
  Doc,
2583
3044
  EditorModes,
2584
3045
  MarkdownEditor,
3046
+ RemoteSelectionsDecorator,
2585
3047
  SpaceAwarenessProvider,
2586
3048
  TextEditor,
2587
3049
  TextKind,
3050
+ YAwarenessProvider,
2588
3051
  YText,
2589
3052
  YXmlFragment,
2590
3053
  autocomplete,
3054
+ automerge3 as automerge,
3055
+ awareness,
2591
3056
  basicBundle,
2592
3057
  blast,
2593
3058
  code2 as code,
2594
3059
  codeTheme,
2595
3060
  comments,
2596
- cursorColor,
3061
+ createAutomergeModel,
3062
+ createYjsModel,
2597
3063
  defaultMarkdownSlots,
2598
3064
  defaultOptions,
2599
3065
  defaultSlots,
2600
3066
  defaultTextSlots,
2601
3067
  defaultTheme,
3068
+ getToken,
2602
3069
  hr,
2603
3070
  image,
2604
3071
  link,
@@ -2609,7 +3076,6 @@ export {
2609
3076
  markdownTagsExtensions,
2610
3077
  markdownTheme,
2611
3078
  mention,
2612
- mermaid,
2613
3079
  modelState,
2614
3080
  setCommentRange,
2615
3081
  setFocus,
@@ -2619,6 +3085,7 @@ export {
2619
3085
  tasklist,
2620
3086
  textTheme,
2621
3087
  typewriter,
2622
- useTextModel
3088
+ useTextModel,
3089
+ yjs
2623
3090
  };
2624
3091
  //# sourceMappingURL=index.mjs.map