@dxos/react-ui-editor 0.3.11-main.870164f → 0.3.11-main.8be6c8a

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 (142) hide show
  1. package/dist/lib/browser/index.mjs +1609 -1139
  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 +9 -5
  5. package/dist/types/src/components/TextEditor/MarkdownEditor.stories.d.ts.map +1 -1
  6. package/dist/types/src/components/TextEditor/TextEditor.d.ts +10 -10
  7. package/dist/types/src/components/TextEditor/TextEditor.d.ts.map +1 -1
  8. package/dist/types/src/components/TextEditor/TextEditor.stories.d.ts +2 -2
  9. package/dist/types/src/components/TextEditor/TextEditor.stories.d.ts.map +1 -1
  10. package/dist/types/src/{hooks/automerge → components/TextEditor}/automerge.stories.d.ts +6 -1
  11. package/dist/types/src/components/TextEditor/automerge.stories.d.ts.map +1 -0
  12. package/dist/types/src/components/TextEditor/codemirror.stories.d.ts.map +1 -1
  13. package/dist/types/src/{hooks/yjs → components/TextEditor}/yjs.stories.d.ts +1 -1
  14. package/dist/types/src/components/TextEditor/yjs.stories.d.ts.map +1 -0
  15. package/dist/types/src/extensions/autocomplete.d.ts.map +1 -1
  16. package/dist/types/src/extensions/automerge/automerge.d.ts +9 -0
  17. package/dist/types/src/extensions/automerge/automerge.d.ts.map +1 -0
  18. package/dist/types/src/extensions/automerge/cursor.d.ts +5 -0
  19. package/dist/types/src/extensions/automerge/cursor.d.ts.map +1 -0
  20. package/dist/types/src/extensions/automerge/defs.d.ts +26 -0
  21. package/dist/types/src/extensions/automerge/defs.d.ts.map +1 -0
  22. package/dist/types/src/extensions/automerge/index.d.ts +4 -0
  23. package/dist/types/src/extensions/automerge/index.d.ts.map +1 -0
  24. package/dist/types/src/{hooks → extensions}/automerge/semaphore.d.ts +4 -4
  25. package/dist/types/src/extensions/automerge/semaphore.d.ts.map +1 -0
  26. package/dist/types/src/extensions/automerge/update-automerge.d.ts +5 -0
  27. package/dist/types/src/extensions/automerge/update-automerge.d.ts.map +1 -0
  28. package/dist/types/src/extensions/automerge/update-codemirror.d.ts.map +1 -0
  29. package/dist/types/src/extensions/awareness.d.ts +46 -0
  30. package/dist/types/src/extensions/awareness.d.ts.map +1 -0
  31. package/dist/types/src/extensions/code.d.ts.map +1 -1
  32. package/dist/types/src/extensions/comments.d.ts.map +1 -1
  33. package/dist/types/src/extensions/hr.d.ts.map +1 -1
  34. package/dist/types/src/extensions/image.d.ts.map +1 -1
  35. package/dist/types/src/extensions/index.d.ts +3 -1
  36. package/dist/types/src/extensions/index.d.ts.map +1 -1
  37. package/dist/types/src/extensions/link.d.ts.map +1 -1
  38. package/dist/types/src/extensions/markdown/highlight.d.ts.map +1 -1
  39. package/dist/types/src/extensions/tasklist.d.ts.map +1 -1
  40. package/dist/types/src/extensions/yjs/cursor.d.ts +4 -0
  41. package/dist/types/src/extensions/yjs/cursor.d.ts.map +1 -0
  42. package/dist/types/src/extensions/yjs/index.d.ts +2 -0
  43. package/dist/types/src/extensions/yjs/index.d.ts.map +1 -0
  44. package/dist/types/src/extensions/yjs/yjs.d.ts +4 -0
  45. package/dist/types/src/extensions/yjs/yjs.d.ts.map +1 -0
  46. package/dist/types/src/extensions/yjs/yjs.test.d.ts.map +1 -0
  47. package/dist/types/src/hooks/automerge.d.ts +3 -0
  48. package/dist/types/src/hooks/automerge.d.ts.map +1 -0
  49. package/dist/types/src/hooks/awareness-provider.d.ts +28 -0
  50. package/dist/types/src/hooks/awareness-provider.d.ts.map +1 -0
  51. package/dist/types/src/hooks/index.d.ts +2 -0
  52. package/dist/types/src/hooks/index.d.ts.map +1 -1
  53. package/dist/types/src/hooks/useTextModel.d.ts +8 -7
  54. package/dist/types/src/hooks/useTextModel.d.ts.map +1 -1
  55. package/dist/types/src/hooks/{yjs/space-provider.d.ts → yjs.d.ts} +8 -8
  56. package/dist/types/src/hooks/yjs.d.ts.map +1 -0
  57. package/dist/types/src/index.d.ts +3 -0
  58. package/dist/types/src/index.d.ts.map +1 -1
  59. package/dist/types/src/styles/cursors.d.ts.map +1 -0
  60. package/dist/types/src/styles/index.d.ts +1 -0
  61. package/dist/types/src/styles/index.d.ts.map +1 -1
  62. package/dist/types/src/styles/tokens.d.ts +1 -0
  63. package/dist/types/src/styles/tokens.d.ts.map +1 -1
  64. package/dist/types/src/testing/replicator.d.ts +2 -2
  65. package/dist/types/src/testing/replicator.d.ts.map +1 -1
  66. package/dist/types/src/themes/default.d.ts.map +1 -1
  67. package/dist/types/src/util/cursor.d.ts +17 -0
  68. package/dist/types/src/util/cursor.d.ts.map +1 -0
  69. package/dist/types/src/util/index.d.ts +3 -0
  70. package/dist/types/src/util/index.d.ts.map +1 -0
  71. package/dist/types/src/util/util.d.ts.map +1 -0
  72. package/package.json +22 -21
  73. package/src/components/TextEditor/MarkdownEditor.stories.tsx +13 -11
  74. package/src/components/TextEditor/TextEditor.stories.tsx +3 -4
  75. package/src/components/TextEditor/TextEditor.tsx +60 -46
  76. package/src/{hooks/automerge → components/TextEditor}/automerge.stories.tsx +66 -6
  77. package/src/components/TextEditor/codemirror.stories.ts +3 -2
  78. package/src/{hooks/yjs → components/TextEditor}/yjs.stories.tsx +1 -1
  79. package/src/extensions/autocomplete.ts +18 -17
  80. package/src/{hooks/automerge/plugin.ts → extensions/automerge/automerge.ts} +20 -58
  81. package/src/extensions/automerge/cursor.ts +51 -0
  82. package/src/extensions/automerge/defs.ts +62 -0
  83. package/src/extensions/automerge/index.ts +7 -0
  84. package/src/{hooks → extensions}/automerge/semaphore.ts +14 -12
  85. package/src/{hooks → extensions}/automerge/update-automerge.ts +5 -6
  86. package/src/{hooks → extensions}/automerge/update-codemirror.ts +13 -5
  87. package/src/extensions/awareness.ts +316 -0
  88. package/src/extensions/code.ts +4 -5
  89. package/src/extensions/comments.ts +30 -15
  90. package/src/extensions/hr.ts +2 -3
  91. package/src/extensions/image.ts +38 -20
  92. package/src/extensions/index.ts +3 -1
  93. package/src/extensions/link.ts +82 -84
  94. package/src/extensions/markdown/highlight.ts +3 -4
  95. package/src/extensions/table.ts +9 -3
  96. package/src/extensions/tasklist.ts +1 -3
  97. package/src/extensions/yjs/cursor.ts +21 -0
  98. package/src/extensions/yjs/index.ts +5 -0
  99. package/src/{hooks → extensions}/yjs/yjs.test.ts +1 -25
  100. package/src/extensions/yjs/yjs.ts +16 -0
  101. package/src/hooks/automerge.ts +52 -0
  102. package/src/hooks/awareness-provider.ts +120 -0
  103. package/src/hooks/index.ts +2 -0
  104. package/src/hooks/useTextModel.ts +20 -94
  105. package/src/hooks/{yjs/space-provider.ts → yjs.ts} +71 -19
  106. package/src/index.ts +3 -0
  107. package/src/styles/index.ts +1 -0
  108. package/src/styles/tokens.ts +3 -0
  109. package/src/testing/replicator.ts +10 -15
  110. package/src/themes/default.ts +39 -33
  111. package/src/util/cursor.ts +29 -0
  112. package/src/util/index.ts +6 -0
  113. package/dist/types/src/extensions/mermaid.d.ts +0 -3
  114. package/dist/types/src/extensions/mermaid.d.ts.map +0 -1
  115. package/dist/types/src/extensions/util.d.ts.map +0 -1
  116. package/dist/types/src/hooks/automerge/automerge.stories.d.ts.map +0 -1
  117. package/dist/types/src/hooks/automerge/handle.d.ts +0 -9
  118. package/dist/types/src/hooks/automerge/handle.d.ts.map +0 -1
  119. package/dist/types/src/hooks/automerge/index.d.ts +0 -3
  120. package/dist/types/src/hooks/automerge/index.d.ts.map +0 -1
  121. package/dist/types/src/hooks/automerge/plugin.d.ts +0 -26
  122. package/dist/types/src/hooks/automerge/plugin.d.ts.map +0 -1
  123. package/dist/types/src/hooks/automerge/semaphore.d.ts.map +0 -1
  124. package/dist/types/src/hooks/automerge/update-automerge.d.ts +0 -6
  125. package/dist/types/src/hooks/automerge/update-automerge.d.ts.map +0 -1
  126. package/dist/types/src/hooks/automerge/update-codemirror.d.ts.map +0 -1
  127. package/dist/types/src/hooks/yjs/cursors.d.ts.map +0 -1
  128. package/dist/types/src/hooks/yjs/index.d.ts +0 -3
  129. package/dist/types/src/hooks/yjs/index.d.ts.map +0 -1
  130. package/dist/types/src/hooks/yjs/space-provider.d.ts.map +0 -1
  131. package/dist/types/src/hooks/yjs/yjs.stories.d.ts.map +0 -1
  132. package/dist/types/src/hooks/yjs/yjs.test.d.ts.map +0 -1
  133. package/src/extensions/mermaid.ts +0 -11
  134. package/src/hooks/automerge/handle.ts +0 -14
  135. package/src/hooks/automerge/index.ts +0 -6
  136. package/src/hooks/yjs/index.ts +0 -6
  137. /package/dist/types/src/{hooks → extensions}/automerge/update-codemirror.d.ts +0 -0
  138. /package/dist/types/src/{hooks → extensions}/yjs/yjs.test.d.ts +0 -0
  139. /package/dist/types/src/{hooks/yjs → styles}/cursors.d.ts +0 -0
  140. /package/dist/types/src/{extensions → util}/util.d.ts +0 -0
  141. /package/src/{hooks/yjs → styles}/cursors.ts +0 -0
  142. /package/src/{extensions → util}/util.ts +0 -0
@@ -11,512 +11,288 @@ 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, useRef } 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";
18
18
 
19
19
  // packages/ui/react-ui-editor/src/extensions/autocomplete.ts
20
20
  import { autocompletion, completionKeymap } from "@codemirror/autocomplete";
21
+ import { markdownLanguage } from "@codemirror/lang-markdown";
21
22
  import { keymap } from "@codemirror/view";
22
23
  var autocomplete = ({ onSearch }) => {
23
24
  return [
24
25
  // https://codemirror.net/docs/ref/#view.keymap
25
26
  // https://discuss.codemirror.net/t/how-can-i-replace-the-default-autocompletion-keymap-v6/3322
27
+ // TODO(burdon): Set custom keymap.
26
28
  keymap.of(completionKeymap),
27
29
  // https://codemirror.net/examples/autocompletion
28
30
  // https://codemirror.net/docs/ref/#autocomplete.autocompletion
29
31
  autocompletion({
30
- // TODO(burdon): Set custom keymap.
31
- // defaultKeymap: false,
32
+ defaultKeymap: false,
32
33
  // Don't start unless key press.
33
- activateOnTyping: false,
34
- // TODO(burdon): Option to create new page?
35
- // TODO(burdon): Optional decoration via addToOptions
36
- override: [
37
- (context) => {
38
- const match = context.matchBefore(/\w*/);
39
- if (!match || match.from === match.to && !context.explicit) {
40
- return null;
41
- }
42
- return {
43
- from: match.from,
44
- options: onSearch(match.text.toLowerCase())
45
- };
34
+ activateOnTyping: false
35
+ }),
36
+ // TODO(burdon): Option to create new page?
37
+ // TODO(burdon): Optional decoration via addToOptions
38
+ markdownLanguage.data.of({
39
+ autocomplete: (context) => {
40
+ const match = context.matchBefore(/\w*/);
41
+ if (!match || match.from === match.to && !context.explicit) {
42
+ return null;
46
43
  }
47
- ]
44
+ return {
45
+ from: match.from,
46
+ options: onSearch(match.text.toLowerCase())
47
+ };
48
+ }
48
49
  })
49
50
  ];
50
51
  };
51
52
 
52
- // packages/ui/react-ui-editor/src/extensions/basic.ts
53
- import { closeBrackets } from "@codemirror/autocomplete";
54
- import { bracketMatching, defaultHighlightStyle, syntaxHighlighting } from "@codemirror/language";
55
- import { oneDarkHighlightStyle } from "@codemirror/theme-one-dark";
56
- import { drawSelection, EditorView, placeholder } from "@codemirror/view";
57
- var basicBundle = ({ readonly, themeMode, placeholder: _placeholder }) => [
58
- EditorView.lineWrapping,
59
- // TODO(burdon): Compare with minimalSetup.
60
- // https://codemirror.net/docs/ref/#codemirror.minimalSetup
61
- bracketMatching(),
62
- closeBrackets(),
63
- drawSelection(),
64
- _placeholder && placeholder(_placeholder),
65
- // TODO(burdon): Is this required?
66
- themeMode === "dark" ? syntaxHighlighting(oneDarkHighlightStyle) : syntaxHighlighting(defaultHighlightStyle)
67
- ].filter(Boolean);
53
+ // packages/ui/react-ui-editor/src/extensions/automerge/automerge.ts
54
+ import { Facet as Facet2, StateField } from "@codemirror/state";
55
+ import { ViewPlugin } from "@codemirror/view";
56
+ import { next as A } from "@dxos/automerge/automerge";
68
57
 
69
- // packages/ui/react-ui-editor/src/extensions/blast.ts
70
- import { EditorView as EditorView2, keymap as keymap2 } from "@codemirror/view";
71
- import defaultsDeep from "lodash.defaultsdeep";
72
- import { invariant } from "@dxos/invariant";
73
- var __dxlog_file = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/extensions/blast.ts";
74
- var defaultOptions = {
75
- effect: 2,
76
- maxParticles: 200,
77
- particleGravity: 0.08,
78
- particleAlphaFadeout: 0.996,
79
- particleSize: {
80
- min: 2,
81
- max: 8
82
- },
83
- particleNumRange: {
84
- min: 5,
85
- max: 10
86
- },
87
- particleVelocityRange: {
88
- x: [
89
- -1,
90
- 1
91
- ],
92
- y: [
93
- -3.5,
94
- -1.5
95
- ]
58
+ // packages/ui/react-ui-editor/src/extensions/automerge/cursor.ts
59
+ import get from "lodash.get";
60
+ import { next as automerge } from "@dxos/automerge/automerge";
61
+ var cursorConverter = (handle, path) => ({
62
+ // TODO(burdon): Handle assoc to associate with a previous character.
63
+ toCursor: (pos) => {
64
+ const doc = handle.docSync();
65
+ if (!doc) {
66
+ return "";
67
+ }
68
+ const value = get(doc, path);
69
+ if (typeof value === "string" && value.length <= pos) {
70
+ return "end";
71
+ }
72
+ return automerge.getCursor(doc, path.slice(), pos);
96
73
  },
97
- particleShrinkRate: 0.95,
98
- shakeIntensity: 5
99
- };
100
- var blast = (options = defaultOptions) => {
101
- let blaster;
102
- let last = 0;
103
- const getPoint = (view, pos) => {
104
- const { left: x = 0, top: y = 0 } = view.coordsForChar(pos) ?? {};
105
- const element = document.elementFromPoint(x, y);
106
- const { offsetLeft: left = 0, offsetTop: top = 0 } = view.scrollDOM.parentElement ?? {};
107
- const point = {
108
- x: x - left,
109
- y: y - top
110
- };
111
- return {
112
- element,
113
- point
114
- };
115
- };
116
- return [
117
- // Cursor moved.
118
- EditorView2.updateListener.of((update4) => {
119
- if (blaster?.node !== update4.view.scrollDOM) {
120
- if (blaster) {
121
- blaster.destroy();
122
- }
123
- blaster = new Blaster(update4.view.scrollDOM, defaultsDeep({
124
- particleGravity: 0.2,
125
- particleShrinkRate: 0.995,
126
- color: () => [
127
- 100 + Math.random() * 100,
128
- 0,
129
- 0
130
- ]
131
- }, options, defaultOptions));
132
- blaster.initialize();
133
- blaster.start();
74
+ fromCursor: (cursor) => {
75
+ if (cursor === "") {
76
+ return 0;
77
+ }
78
+ const doc = handle.docSync();
79
+ if (!doc) {
80
+ return 0;
81
+ }
82
+ if (cursor === "end") {
83
+ const value = get(doc, path);
84
+ if (typeof value === "string") {
85
+ return value.length;
134
86
  } else {
135
- blaster.resize();
136
- }
137
- const current = update4.state.selection.main.head;
138
- if (current !== last) {
139
- last = current;
140
- const { element, point } = getPoint(update4.view, current - 1);
141
- if (element && point) {
142
- blaster.spawn({
143
- element,
144
- point
145
- });
146
- }
147
- }
148
- }),
149
- keymap2.of([
150
- {
151
- any: (_, event) => {
152
- if (blaster) {
153
- if (event.key === "Enter" && event.shiftKey) {
154
- blaster.shake({
155
- time: 0.8
156
- });
157
- return true;
158
- }
159
- }
160
- return false;
161
- }
162
- }
163
- ])
164
- ];
165
- };
166
- var Blaster = class {
167
- constructor(_node, _options) {
168
- this._node = _node;
169
- this._options = _options;
170
- this._running = false;
171
- this._shakeTime = 0;
172
- this._shakeTimeMax = 0;
173
- this._particles = [];
174
- this._particlePointer = 0;
175
- this._lastPoint = {
176
- x: 0,
177
- y: 0
178
- };
179
- this.shake = throttle(({ time }) => {
180
- this._shakeTime = this._shakeTimeMax || time;
181
- this._shakeTimeMax = time;
182
- }, 100);
183
- this.spawn = throttle(({ element, point }) => {
184
- const color = getRGBComponents(element, this._options.color);
185
- const numParticles = random(this._options.particleNumRange.min, this._options.particleNumRange.max);
186
- const dir = this._lastPoint.x === point.x ? 0 : this._lastPoint.x < point.x ? 1 : -1;
187
- this._lastPoint = point;
188
- for (let i = numParticles; i--; i > 0) {
189
- this._particles[this._particlePointer] = this._effect.create(point.x - dir * 16, point.y, color);
190
- this._particlePointer = (this._particlePointer + 1) % this._options.maxParticles;
87
+ return 0;
191
88
  }
192
- }, 100);
193
- this._effect = this._options.effect === 1 ? new Effect1(_options) : new Effect2(_options);
194
- }
195
- get node() {
196
- return this._node;
197
- }
198
- initialize() {
199
- invariant(!this._canvas && !this._ctx, void 0, {
200
- F: __dxlog_file,
201
- L: 138,
202
- S: this,
203
- A: [
204
- "!this._canvas && !this._ctx",
205
- ""
206
- ]
207
- });
208
- this._canvas = document.createElement("canvas");
209
- this._canvas.id = "code-blast-canvas";
210
- this._canvas.style.position = "absolute";
211
- this._canvas.style.zIndex = "0";
212
- this._canvas.style.pointerEvents = "none";
213
- this._ctx = this._canvas.getContext("2d");
214
- const parent = this._node.parentElement?.parentElement;
215
- parent?.appendChild(this._canvas);
216
- this.resize();
217
- }
218
- destroy() {
219
- this.stop();
220
- if (this._canvas) {
221
- this._canvas.remove();
222
- this._canvas = void 0;
223
- this._ctx = void 0;
224
89
  }
90
+ return automerge.getCursorPosition(doc, path.slice(), cursor);
225
91
  }
226
- resize() {
227
- if (this._node.parentElement && this._canvas) {
228
- const { offsetLeft: x, offsetTop: y, offsetWidth: width, offsetHeight: height } = this._node.parentElement;
229
- this._canvas.style.top = `${y}px`;
230
- this._canvas.style.left = `${x}px`;
231
- this._canvas.width = width;
232
- this._canvas.height = height;
233
- }
234
- }
235
- start() {
236
- invariant(this._canvas && this._ctx, void 0, {
237
- F: __dxlog_file,
238
- L: 177,
239
- S: this,
240
- A: [
241
- "this._canvas && this._ctx",
242
- ""
243
- ]
92
+ });
93
+
94
+ // packages/ui/react-ui-editor/src/extensions/automerge/defs.ts
95
+ import { Annotation, StateEffect } from "@codemirror/state";
96
+ var effectType = StateEffect.define({});
97
+ var updateHeads = (newHeads) => effectType.of({
98
+ newHeads
99
+ });
100
+ var getLastHeads = (state, field) => state.field(field).lastHeads;
101
+ var getPath = (state, field) => state.field(field).path;
102
+ var reconcileAnnotationType = Annotation.define();
103
+ var isReconcileTx = (tr) => !!tr.annotation(reconcileAnnotationType);
104
+
105
+ // packages/ui/react-ui-editor/src/extensions/automerge/semaphore.ts
106
+ import { next as automerge2 } from "@dxos/automerge/automerge";
107
+
108
+ // packages/ui/react-ui-editor/src/extensions/automerge/update-automerge.ts
109
+ import { next as am } from "@dxos/automerge/automerge";
110
+ var updateAutomerge = (field, handle, transactions, state) => {
111
+ const { lastHeads, path } = state.field(field);
112
+ let hasChanges = false;
113
+ for (const tr of transactions) {
114
+ tr.changes.iterChanges(() => {
115
+ hasChanges = true;
244
116
  });
245
- this._running = true;
246
- this.loop();
247
117
  }
248
- stop() {
249
- this._running = false;
250
- this._node.style.transform = "translate(0px, 0px)";
118
+ if (!hasChanges) {
119
+ return void 0;
251
120
  }
252
- loop() {
253
- if (!this._running || !this._canvas || !this._ctx) {
254
- return;
121
+ const newHeads = handle.changeAt(lastHeads, (doc) => {
122
+ for (const tr of transactions) {
123
+ tr.changes.iterChanges((fromA, toA, _fromB, _toB, inserted) => {
124
+ am.splice(doc, path, fromA, toA - fromA, inserted.toString());
125
+ });
255
126
  }
256
- this._ctx.clearRect(0, 0, this._canvas.width ?? 0, this._canvas.height ?? 0);
257
- const now = (/* @__PURE__ */ new Date()).getTime();
258
- this._lastTime ??= now;
259
- const dt = (now - this._lastTime) / 1e3;
260
- this._lastTime = now;
261
- if (this._shakeTime > 0) {
262
- this._shakeTime -= dt;
263
- const magnitude = this._shakeTime / this._shakeTimeMax * this._options.shakeIntensity;
264
- const shakeX = random(-magnitude, magnitude);
265
- const shakeY = random(-magnitude, magnitude);
266
- this._node.style.transform = `translate(${shakeX}px,${shakeY}px)`;
267
- }
268
- this.drawParticles();
269
- requestAnimationFrame(this.loop.bind(this));
270
- }
271
- drawParticles() {
272
- for (let i = this._particles.length; i--; i > 0) {
273
- const particle = this._particles[i];
274
- if (!particle) {
275
- continue;
276
- }
277
- if (particle.alpha < 0.01 || particle.size <= 0.5) {
278
- continue;
279
- }
280
- this._effect.update(this._ctx, particle);
127
+ });
128
+ return newHeads ?? void 0;
129
+ };
130
+
131
+ // packages/ui/react-ui-editor/src/extensions/automerge/update-codemirror.ts
132
+ import { ChangeSet } from "@codemirror/state";
133
+ var updateCodeMirror = (view, selection, target, patches) => {
134
+ for (const patch of patches) {
135
+ const changeSpec = handlePatch(patch, target, view.state);
136
+ if (changeSpec != null) {
137
+ const changeSet = ChangeSet.of(changeSpec, view.state.doc.length, "\n");
138
+ selection = selection.map(changeSet, 1);
139
+ view.dispatch({
140
+ changes: changeSet,
141
+ annotations: reconcileAnnotationType.of({})
142
+ });
281
143
  }
282
144
  }
145
+ view.dispatch({
146
+ selection,
147
+ annotations: reconcileAnnotationType.of({})
148
+ });
283
149
  };
284
- var Effect = class {
285
- constructor(_options) {
286
- this._options = _options;
150
+ var handlePatch = (patch, target, state) => {
151
+ if (patch.action === "insert") {
152
+ return handleInsert(target, patch);
153
+ } else if (patch.action === "splice") {
154
+ return handleSplice(target, patch);
155
+ } else if (patch.action === "del") {
156
+ return handleDel(target, patch);
157
+ } else if (patch.action === "put") {
158
+ return handlePut(target, patch, state);
159
+ } else {
160
+ return null;
287
161
  }
288
162
  };
289
- var Effect1 = class extends Effect {
290
- create(x, y, color) {
291
- return {
292
- x,
293
- y: y + 10,
294
- vx: random(this._options.particleVelocityRange.x[0], this._options.particleVelocityRange.x[1]),
295
- vy: random(this._options.particleVelocityRange.y[0], this._options.particleVelocityRange.y[1]),
296
- size: random(this._options.particleSize.min, this._options.particleSize.max),
297
- color,
298
- alpha: 1
299
- };
300
- }
301
- update(ctx, particle) {
302
- particle.vy += this._options.particleGravity;
303
- particle.x += particle.vx;
304
- particle.y += particle.vy;
305
- particle.alpha *= this._options.particleAlphaFadeout;
306
- ctx.fillStyle = `rgba(${particle.color[0]},${particle.color[1]},${particle.color[2]},${particle.alpha})`;
307
- ctx.fillRect(Math.round(particle.x - 1), Math.round(particle.y - 1), particle.size, particle.size);
163
+ var handleInsert = (target, patch) => {
164
+ const index = charPath(target, patch.path);
165
+ if (index == null) {
166
+ return [];
308
167
  }
168
+ const text = patch.values.map((v) => v ? v.toString() : "").join("");
169
+ return [
170
+ {
171
+ from: index,
172
+ to: index,
173
+ insert: text
174
+ }
175
+ ];
309
176
  };
310
- var Effect2 = class extends Effect {
311
- create(x, y, color) {
312
- return {
313
- x,
314
- y: y + 10,
315
- vx: random(this._options.particleVelocityRange.x[0], this._options.particleVelocityRange.x[1]),
316
- vy: random(this._options.particleVelocityRange.y[0], this._options.particleVelocityRange.y[1]),
317
- size: random(this._options.particleSize.min, this._options.particleSize.max),
318
- color,
319
- alpha: 1,
320
- theta: random(0, 360) * Math.PI / 180,
321
- drag: 0.92,
322
- wander: 0.15
323
- };
324
- }
325
- update(ctx, particle) {
326
- particle.vy += this._options.particleGravity;
327
- particle.x += particle.vx;
328
- particle.y += particle.vy;
329
- particle.vx *= particle.drag;
330
- particle.vy *= particle.drag;
331
- particle.theta += random(-0.5, 0.5);
332
- particle.vx += Math.sin(particle.theta) * 0.1;
333
- particle.vy += Math.cos(particle.theta) * 0.1;
334
- particle.size *= this._options.particleShrinkRate;
335
- particle.alpha *= this._options.particleAlphaFadeout;
336
- ctx.fillStyle = `rgba(${particle.color[0]},${particle.color[1]},${particle.color[2]},${particle.alpha})`;
337
- ctx.beginPath();
338
- ctx.arc(Math.round(particle.x - 1), Math.round(particle.y - 1), particle.size, 0, 2 * Math.PI);
339
- ctx.fill();
177
+ var handleSplice = (target, patch) => {
178
+ const index = charPath(target, patch.path);
179
+ if (index == null) {
180
+ return [];
340
181
  }
341
- };
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);
182
+ return [
183
+ {
184
+ from: index,
185
+ insert: patch.value
351
186
  }
352
- };
353
- }
354
- var getRGBComponents = (node, color) => {
355
- if (typeof color === "function") {
356
- return color();
187
+ ];
188
+ };
189
+ var handleDel = (target, patch) => {
190
+ const index = charPath(target, patch.path);
191
+ if (index == null) {
192
+ return [];
357
193
  }
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;
194
+ const length = patch.length || 1;
195
+ return [
196
+ {
197
+ from: index,
198
+ to: index + length
363
199
  }
200
+ ];
201
+ };
202
+ var handlePut = (target, patch, state) => {
203
+ const index = charPath(target, [
204
+ ...patch.path,
205
+ 0
206
+ ]);
207
+ if (index == null) {
208
+ return [];
209
+ }
210
+ const length = state.doc.length;
211
+ if (typeof patch.value !== "string") {
212
+ return [];
364
213
  }
365
214
  return [
366
- 50,
367
- 50,
368
- 50
215
+ {
216
+ from: 0,
217
+ to: length,
218
+ insert: patch.value
219
+ }
369
220
  ];
370
221
  };
371
- var random = (min, max) => {
372
- if (!max) {
373
- max = min;
374
- min = 0;
222
+ var charPath = (textPath, candidatePath) => {
223
+ if (candidatePath.length !== textPath.length + 1) {
224
+ return null;
375
225
  }
376
- return min + ~~(Math.random() * (max - min + 1));
226
+ for (let i = 0; i < textPath.length; i++) {
227
+ if (textPath[i] !== candidatePath[i]) {
228
+ return null;
229
+ }
230
+ }
231
+ const index = candidatePath[candidatePath.length - 1];
232
+ if (typeof index === "number") {
233
+ return index;
234
+ }
235
+ return null;
377
236
  };
378
237
 
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);
238
+ // packages/ui/react-ui-editor/src/extensions/automerge/semaphore.ts
239
+ var PatchSemaphore = class {
240
+ constructor(_field) {
241
+ this._field = _field;
242
+ this._inReconcile = false;
243
+ this._queue = [];
244
+ this.reconcile = (handle, view) => {
245
+ if (this._inReconcile) {
246
+ return;
247
+ }
248
+ this._inReconcile = true;
249
+ const path = getPath(view.state, this._field);
250
+ const oldHeads = getLastHeads(view.state, this._field);
251
+ let selection = view.state.selection;
252
+ const transactions = view.state.field(this._field).unreconciledTransactions.filter((tx) => !isReconcileTx(tx));
253
+ const toInvert = transactions.slice().reverse();
254
+ for (const tx of toInvert) {
255
+ const inverted = tx.changes.invert(tx.startState.doc);
256
+ selection = selection.map(inverted);
257
+ view.dispatch({
258
+ changes: inverted,
259
+ annotations: reconcileAnnotationType.of(true)
260
+ });
261
+ }
262
+ let newHeads = updateAutomerge(this._field, handle, transactions, view.state);
263
+ if (newHeads === null || newHeads === void 0) {
264
+ newHeads = automerge2.getHeads(handle.docSync());
265
+ }
266
+ const diff = automerge2.equals(oldHeads, newHeads) ? [] : automerge2.diff(handle.docSync(), oldHeads, newHeads);
267
+ updateCodeMirror(view, selection, path, diff);
268
+ view.dispatch({
269
+ effects: updateHeads(newHeads),
270
+ annotations: reconcileAnnotationType.of({})
271
+ });
272
+ this._inReconcile = false;
273
+ };
274
+ }
415
275
  };
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
276
 
426
- // packages/ui/react-ui-editor/src/styles/tokens.ts
427
- import { tailwindConfig } from "@dxos/react-ui-theme";
428
- var tokens = tailwindConfig({}).theme;
277
+ // packages/ui/react-ui-editor/src/util/cursor.ts
278
+ import { Facet } from "@codemirror/state";
279
+ var DEFAULT_CURSOR_CONVERTER = {
280
+ toCursor: (position) => position.toString(),
281
+ fromCursor: (cursor) => parseInt(cursor)
282
+ };
283
+ var CursorConverter = Facet.define({
284
+ combine: (providers) => providers[0] ?? DEFAULT_CURSOR_CONVERTER
285
+ });
429
286
 
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
287
+ // packages/ui/react-ui-editor/src/util/util.ts
512
288
  import { log } from "@dxos/log";
513
- var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/extensions/util.ts";
289
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/util/util.ts";
514
290
  var callbackWrapper = (fn) => (...args) => {
515
291
  try {
516
292
  return fn(...args);
517
293
  } catch (error) {
518
294
  log.catch(error, void 0, {
519
- F: __dxlog_file2,
295
+ F: __dxlog_file,
520
296
  L: 16,
521
297
  S: void 0,
522
298
  C: (f, a) => f(...a)
@@ -524,209 +300,14 @@ var callbackWrapper = (fn) => (...args) => {
524
300
  }
525
301
  };
526
302
 
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
623
- }
624
- ];
625
- };
626
- var handleDel = (target, patch) => {
627
- const index = charPath(target, patch.path);
628
- if (index == null) {
629
- return [];
630
- }
631
- const length = patch.length || 1;
632
- return [
633
- {
634
- from: index,
635
- to: index + length
636
- }
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
- }
651
- return [
652
- {
653
- from: 0,
654
- to: length,
655
- insert: patch.value
656
- }
657
- ];
658
- };
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
- }
713
- }
714
- };
715
-
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({
303
+ // packages/ui/react-ui-editor/src/extensions/automerge/automerge.ts
304
+ var semaphoreFacet = Facet2.define({
724
305
  combine: (values) => values.at(-1)
725
306
  });
726
- var automergePlugin = (handle, path) => {
307
+ var automerge3 = ({ handle, path }) => {
727
308
  const stateField = StateField.define({
728
309
  create: () => ({
729
- lastHeads: automerge2.getHeads(handle.docSync()),
310
+ lastHeads: A.getHeads(handle.docSync()),
730
311
  unreconciledTransactions: [],
731
312
  path: path.slice()
732
313
  }),
@@ -754,7 +335,7 @@ var automergePlugin = (handle, path) => {
754
335
  }
755
336
  });
756
337
  const semaphore = new PatchSemaphore(stateField);
757
- const viewPlugin = ViewPlugin2.fromClass(class AutomergeCodemirrorViewPlugin {
338
+ const viewPlugin = ViewPlugin.fromClass(class AutomergeCodemirrorViewPlugin {
758
339
  constructor(_view) {
759
340
  this._view = _view;
760
341
  this._handleChange = () => {
@@ -762,8 +343,8 @@ var automergePlugin = (handle, path) => {
762
343
  };
763
344
  handle.addListener("change", this._handleChange);
764
345
  }
765
- update(update4) {
766
- if (update4.transactions.length > 0 && update4.transactions.some((tr) => !isReconcileTx(tr))) {
346
+ update(update2) {
347
+ if (update2.transactions.length > 0 && update2.transactions.some((tr) => !isReconcileTx(tr))) {
767
348
  queueMicrotask(() => {
768
349
  this._view.state.facet(semaphoreFacet).reconcile(handle, this._view);
769
350
  });
@@ -775,263 +356,750 @@ var automergePlugin = (handle, path) => {
775
356
  });
776
357
  return {
777
358
  extension: [
778
- stateField,
359
+ CursorConverter.of(cursorConverter(handle, path)),
779
360
  semaphoreFacet.of(semaphore),
361
+ stateField,
780
362
  viewPlugin
781
363
  ]
782
364
  };
783
365
  };
784
- var reconcileAnnotationType = Annotation.define();
785
- var isReconcileTx = (tr) => !!tr.annotation(reconcileAnnotationType);
786
366
 
787
- // packages/ui/react-ui-editor/src/hooks/yjs/cursors.ts
788
- import * as random2 from "lib0/random";
789
- var cursorColors = [
790
- {
791
- color: "#30bced",
792
- light: "#30bced33"
367
+ // packages/ui/react-ui-editor/src/extensions/awareness.ts
368
+ import { Annotation as Annotation2, Facet as Facet3, RangeSet } from "@codemirror/state";
369
+ import { Decoration, EditorView, ViewPlugin as ViewPlugin2, WidgetType } from "@codemirror/view";
370
+ import { Event } from "@dxos/async";
371
+ import { Context } from "@dxos/context";
372
+ var dummyProvider = {
373
+ remoteStateChange: new Event(),
374
+ open: () => {
793
375
  },
794
- {
795
- color: "#6eeb83",
796
- light: "#6eeb8333"
376
+ close: () => {
797
377
  },
798
- {
799
- color: "#ffbc42",
800
- light: "#ffbc4233"
378
+ update: () => {
801
379
  },
802
- {
803
- color: "#ecd444",
804
- light: "#ecd44433"
380
+ getRemoteStates: () => []
381
+ };
382
+ var AwarenessProvider = Facet3.define({
383
+ combine: (providers) => providers[0] ?? dummyProvider
384
+ });
385
+ var RemoteSelectionChangedAnnotation = Annotation2.define();
386
+ var awareness = (provider = dummyProvider) => {
387
+ return [
388
+ AwarenessProvider.of(provider),
389
+ ViewPlugin2.fromClass(RemoteSelectionsDecorator, {
390
+ decorations: (value) => value.decorations
391
+ }),
392
+ styles
393
+ ];
394
+ };
395
+ var RemoteSelectionsDecorator = class {
396
+ constructor(view) {
397
+ this.decorations = RangeSet.of([]);
398
+ this._ctx = new Context();
399
+ this._lastAnchor = void 0;
400
+ this._lastHead = void 0;
401
+ this._cursorConverter = view.state.facet(CursorConverter);
402
+ this._provider = view.state.facet(AwarenessProvider);
403
+ this._provider.open();
404
+ this._provider.remoteStateChange.on(this._ctx, () => {
405
+ view.dispatch({
406
+ annotations: [
407
+ RemoteSelectionChangedAnnotation.of([])
408
+ ]
409
+ });
410
+ });
411
+ }
412
+ destroy() {
413
+ void this._ctx.dispose();
414
+ this._provider.close();
415
+ }
416
+ update(update2) {
417
+ this._updateLocalSelection(update2);
418
+ this._updateRemoteSelections(update2);
419
+ }
420
+ _updateLocalSelection(update2) {
421
+ const hasFocus = update2.view.hasFocus && update2.view.dom.ownerDocument.hasFocus();
422
+ const { anchor = void 0, head = void 0 } = hasFocus ? update2.state.selection.main : {};
423
+ if (this._lastAnchor === anchor && this._lastHead === head) {
424
+ return;
425
+ }
426
+ this._lastAnchor = anchor;
427
+ this._lastHead = head;
428
+ this._provider.update(anchor !== void 0 && head !== void 0 ? {
429
+ anchor: this._cursorConverter.toCursor(anchor),
430
+ head: this._cursorConverter.toCursor(head)
431
+ } : void 0);
432
+ }
433
+ _updateRemoteSelections(update2) {
434
+ const decorations = [];
435
+ const awarenessStates = this._provider.getRemoteStates();
436
+ for (const state of awarenessStates) {
437
+ const anchor = state.position?.anchor ? this._cursorConverter.fromCursor(state.position.anchor) : null;
438
+ const head = state.position?.head ? this._cursorConverter.fromCursor(state.position.head) : null;
439
+ if (anchor == null || head == null) {
440
+ continue;
441
+ }
442
+ const start = Math.min(Math.min(anchor, head), update2.view.state.doc.length);
443
+ const end = Math.min(Math.max(anchor, head), update2.view.state.doc.length);
444
+ const startLine = update2.view.state.doc.lineAt(start);
445
+ const endLine = update2.view.state.doc.lineAt(end);
446
+ const color = state.info.color ?? "#30bced";
447
+ const lightColor = state.info.lightColor ?? color + "33";
448
+ if (startLine.number === endLine.number) {
449
+ decorations.push({
450
+ from: start,
451
+ to: end,
452
+ value: Decoration.mark({
453
+ attributes: {
454
+ style: `background-color: ${lightColor}`
455
+ },
456
+ class: "cm-ySelection"
457
+ })
458
+ });
459
+ } else {
460
+ decorations.push({
461
+ from: start,
462
+ to: startLine.from + startLine.length,
463
+ value: Decoration.mark({
464
+ attributes: {
465
+ style: `background-color: ${color}`
466
+ },
467
+ class: "cm-ySelection"
468
+ })
469
+ });
470
+ decorations.push({
471
+ from: endLine.from,
472
+ to: end,
473
+ value: Decoration.mark({
474
+ attributes: {
475
+ style: `background-color: ${color}`
476
+ },
477
+ class: "cm-ySelection"
478
+ })
479
+ });
480
+ for (let i = startLine.number + 1; i < endLine.number; i++) {
481
+ const linePos = update2.view.state.doc.line(i).from;
482
+ decorations.push({
483
+ from: linePos,
484
+ to: linePos,
485
+ value: Decoration.line({
486
+ attributes: {
487
+ style: `background-color: ${color}`,
488
+ class: "cm-yLineSelection"
489
+ }
490
+ })
491
+ });
492
+ }
493
+ }
494
+ decorations.push({
495
+ from: head,
496
+ to: head,
497
+ value: Decoration.widget({
498
+ side: head - anchor > 0 ? -1 : 1,
499
+ block: false,
500
+ widget: new RemoteCaretWidget(state.info.displayName ?? "Anonymous", color)
501
+ })
502
+ });
503
+ }
504
+ this.decorations = Decoration.set(decorations, true);
505
+ }
506
+ };
507
+ var RemoteCaretWidget = class extends WidgetType {
508
+ constructor(name, color) {
509
+ super();
510
+ this.name = name;
511
+ this.color = color;
512
+ this.name = name;
513
+ this.color = color;
514
+ }
515
+ toDOM() {
516
+ const span = document.createElement("span");
517
+ span.className = "cm-ySelectionCaret";
518
+ span.style.backgroundColor = this.color;
519
+ span.style.borderColor = this.color;
520
+ const dot = document.createElement("div");
521
+ dot.className = "cm-ySelectionCaretDot";
522
+ const info = document.createElement("div");
523
+ info.className = "cm-ySelectionInfo";
524
+ info.innerText = this.name;
525
+ span.appendChild(document.createTextNode("\u2060"));
526
+ span.appendChild(dot);
527
+ span.appendChild(document.createTextNode("\u2060"));
528
+ span.appendChild(info);
529
+ span.appendChild(document.createTextNode("\u2060"));
530
+ return span;
531
+ }
532
+ eq(widget) {
533
+ return widget.color === this.color;
534
+ }
535
+ compare(widget) {
536
+ return widget.color === this.color;
537
+ }
538
+ updateDOM() {
539
+ return false;
540
+ }
541
+ get estimatedHeight() {
542
+ return -1;
543
+ }
544
+ ignoreEvent() {
545
+ return true;
546
+ }
547
+ };
548
+ var styles = EditorView.baseTheme({
549
+ ".cm-ySelection": {},
550
+ ".cm-yLineSelection": {
551
+ padding: 0,
552
+ margin: "0px 2px 0px 4px"
805
553
  },
806
- {
807
- color: "#ee6352",
808
- light: "#ee635233"
554
+ ".cm-ySelectionCaret": {
555
+ position: "relative",
556
+ borderLeft: "1px solid black",
557
+ borderRight: "1px solid black",
558
+ marginLeft: "-1px",
559
+ marginRight: "-1px",
560
+ boxSizing: "border-box",
561
+ display: "inline"
809
562
  },
810
- {
811
- color: "#9ac2c9",
812
- light: "#9ac2c933"
563
+ ".cm-ySelectionCaretDot": {
564
+ borderRadius: "50%",
565
+ position: "absolute",
566
+ width: ".4em",
567
+ height: ".4em",
568
+ top: "-.2em",
569
+ left: "-.2em",
570
+ backgroundColor: "inherit",
571
+ transition: "transform .3s ease-in-out",
572
+ boxSizing: "border-box"
813
573
  },
814
- {
815
- color: "#8acb88",
816
- light: "#8acb8833"
574
+ ".cm-ySelectionCaret:hover > .cm-ySelectionCaretDot": {
575
+ transformOrigin: "bottom center",
576
+ transform: "scale(0)"
817
577
  },
818
- {
819
- color: "#1be7ff",
820
- light: "#1be7ff33"
578
+ ".cm-ySelectionInfo": {
579
+ position: "absolute",
580
+ top: "-1.05em",
581
+ left: "-1px",
582
+ fontSize: ".75em",
583
+ fontFamily: "serif",
584
+ fontStyle: "normal",
585
+ fontWeight: "normal",
586
+ lineHeight: "normal",
587
+ userSelect: "none",
588
+ color: "white",
589
+ paddingLeft: "2px",
590
+ paddingRight: "2px",
591
+ zIndex: 101,
592
+ transition: "opacity .3s ease-in-out",
593
+ backgroundColor: "inherit",
594
+ // these should be separate
595
+ opacity: 0,
596
+ transitionDelay: "0s",
597
+ whiteSpace: "nowrap"
598
+ },
599
+ ".cm-ySelectionCaret:hover > .cm-ySelectionInfo": {
600
+ opacity: 1,
601
+ transitionDelay: "0s"
821
602
  }
822
- ];
823
- var cursorColor = cursorColors[random2.uint32() % cursorColors.length];
603
+ });
824
604
 
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));
605
+ // packages/ui/react-ui-editor/src/extensions/basic.ts
606
+ import { closeBrackets } from "@codemirror/autocomplete";
607
+ import { bracketMatching, defaultHighlightStyle, syntaxHighlighting } from "@codemirror/language";
608
+ import { oneDarkHighlightStyle } from "@codemirror/theme-one-dark";
609
+ import { drawSelection, EditorView as EditorView2, placeholder } from "@codemirror/view";
610
+ var basicBundle = ({ readonly, themeMode, placeholder: _placeholder }) => [
611
+ EditorView2.lineWrapping,
612
+ // TODO(burdon): Compare with minimalSetup.
613
+ // https://codemirror.net/docs/ref/#codemirror.minimalSetup
614
+ bracketMatching(),
615
+ closeBrackets(),
616
+ drawSelection(),
617
+ _placeholder && placeholder(_placeholder),
618
+ // TODO(burdon): Is this required?
619
+ themeMode === "dark" ? syntaxHighlighting(oneDarkHighlightStyle) : syntaxHighlighting(defaultHighlightStyle)
620
+ ].filter(Boolean);
621
+
622
+ // packages/ui/react-ui-editor/src/extensions/blast.ts
623
+ import { EditorView as EditorView3, keymap as keymap2 } from "@codemirror/view";
624
+ import defaultsDeep from "lodash.defaultsdeep";
625
+ import { invariant } from "@dxos/invariant";
626
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/extensions/blast.ts";
627
+ var defaultOptions = {
628
+ effect: 2,
629
+ maxParticles: 200,
630
+ particleGravity: 0.08,
631
+ particleAlphaFadeout: 0.996,
632
+ particleSize: {
633
+ min: 2,
634
+ max: 8
635
+ },
636
+ particleNumRange: {
637
+ min: 5,
638
+ max: 10
639
+ },
640
+ particleVelocityRange: {
641
+ x: [
642
+ -1,
643
+ 1
644
+ ],
645
+ y: [
646
+ -3.5,
647
+ -1.5
648
+ ]
649
+ },
650
+ particleShrinkRate: 0.95,
651
+ shakeIntensity: 5
652
+ };
653
+ var blast = (options = defaultOptions) => {
654
+ let blaster;
655
+ let last = 0;
656
+ const getPoint = (view, pos) => {
657
+ const { left: x = 0, top: y = 0 } = view.coordsForChar(pos) ?? {};
658
+ const element = document.elementFromPoint(x, y);
659
+ const { offsetLeft: left = 0, offsetTop: top = 0 } = view.scrollDOM.parentElement ?? {};
660
+ const point = {
661
+ x: x - left,
662
+ y: y - top
663
+ };
664
+ return {
665
+ element,
666
+ point
667
+ };
668
+ };
669
+ return [
670
+ // Cursor moved.
671
+ EditorView3.updateListener.of((update2) => {
672
+ if (blaster?.node !== update2.view.scrollDOM) {
673
+ if (blaster) {
674
+ blaster.destroy();
675
+ }
676
+ blaster = new Blaster(update2.view.scrollDOM, defaultsDeep({
677
+ particleGravity: 0.2,
678
+ particleShrinkRate: 0.995,
679
+ color: () => [
680
+ 100 + Math.random() * 100,
681
+ 0,
682
+ 0
683
+ ]
684
+ }, options, defaultOptions));
685
+ blaster.initialize();
686
+ blaster.start();
687
+ } else {
688
+ blaster.resize();
689
+ }
690
+ const current = update2.state.selection.main.head;
691
+ if (current !== last) {
692
+ last = current;
693
+ const { element, point } = getPoint(update2.view, current - 1);
694
+ if (element && point) {
695
+ blaster.spawn({
696
+ element,
697
+ point
698
+ });
699
+ }
700
+ }
701
+ }),
702
+ keymap2.of([
703
+ {
704
+ any: (_, event) => {
705
+ if (blaster) {
706
+ if (event.key === "Enter" && event.shiftKey) {
707
+ blaster.shake({
708
+ time: 0.8
709
+ });
710
+ return true;
711
+ }
712
+ }
713
+ return false;
714
+ }
715
+ }
716
+ ])
717
+ ];
718
+ };
719
+ var Blaster = class {
720
+ constructor(_node, _options) {
721
+ this._node = _node;
722
+ this._options = _options;
723
+ this._running = false;
724
+ this._shakeTime = 0;
725
+ this._shakeTimeMax = 0;
726
+ this._particles = [];
727
+ this._particlePointer = 0;
728
+ this._lastPoint = {
729
+ x: 0,
730
+ y: 0
731
+ };
732
+ this.shake = throttle(({ time }) => {
733
+ this._shakeTime = this._shakeTimeMax || time;
734
+ this._shakeTimeMax = time;
735
+ }, 100);
736
+ this.spawn = throttle(({ element, point }) => {
737
+ const color = getRGBComponents(element, this._options.color);
738
+ const numParticles = random(this._options.particleNumRange.min, this._options.particleNumRange.max);
739
+ const dir = this._lastPoint.x === point.x ? 0 : this._lastPoint.x < point.x ? 1 : -1;
740
+ this._lastPoint = point;
741
+ for (let i = numParticles; i--; i > 0) {
742
+ this._particles[this._particlePointer] = this._effect.create(point.x - dir * 16, point.y, color);
743
+ this._particlePointer = (this._particlePointer + 1) % this._options.maxParticles;
744
+ }
745
+ }, 100);
746
+ this._effect = this._options.effect === 1 ? new Effect1(_options) : new Effect2(_options);
857
747
  }
858
- get awareness() {
859
- return this._awareness;
748
+ get node() {
749
+ return this._node;
860
750
  }
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,
751
+ initialize() {
752
+ invariant(!this._canvas && !this._ctx, void 0, {
753
+ F: __dxlog_file2,
754
+ L: 138,
870
755
  S: this,
871
- C: (f, a) => f(...a)
756
+ A: [
757
+ "!this._canvas && !this._ctx",
758
+ ""
759
+ ]
872
760
  });
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));
761
+ this._canvas = document.createElement("canvas");
762
+ this._canvas.id = "code-blast-canvas";
763
+ this._canvas.style.position = "absolute";
764
+ this._canvas.style.zIndex = "0";
765
+ this._canvas.style.pointerEvents = "none";
766
+ this._ctx = this._canvas.getContext("2d");
767
+ const parent = this._node.parentElement?.parentElement;
768
+ parent?.appendChild(this._canvas);
769
+ this.resize();
878
770
  }
879
- _handleSpaceMessage({ payload }) {
880
- log2("space message", payload, {
881
- F: __dxlog_file3,
882
- L: 79,
771
+ destroy() {
772
+ this.stop();
773
+ if (this._canvas) {
774
+ this._canvas.remove();
775
+ this._canvas = void 0;
776
+ this._ctx = void 0;
777
+ }
778
+ }
779
+ resize() {
780
+ if (this._node.parentElement && this._canvas) {
781
+ const { offsetLeft: x, offsetTop: y, offsetWidth: width, offsetHeight: height } = this._node.parentElement;
782
+ this._canvas.style.top = `${y}px`;
783
+ this._canvas.style.left = `${x}px`;
784
+ this._canvas.width = width;
785
+ this._canvas.height = height;
786
+ }
787
+ }
788
+ start() {
789
+ invariant(this._canvas && this._ctx, void 0, {
790
+ F: __dxlog_file2,
791
+ L: 177,
883
792
  S: this,
884
- C: (f, a) => f(...a)
793
+ A: [
794
+ "this._canvas && this._ctx",
795
+ ""
796
+ ]
885
797
  });
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));
798
+ this._running = true;
799
+ this.loop();
800
+ }
801
+ stop() {
802
+ this._running = false;
803
+ this._node.style.transform = "translate(0px, 0px)";
804
+ }
805
+ loop() {
806
+ if (!this._running || !this._canvas || !this._ctx) {
807
+ return;
890
808
  }
809
+ this._ctx.clearRect(0, 0, this._canvas.width ?? 0, this._canvas.height ?? 0);
810
+ const now = (/* @__PURE__ */ new Date()).getTime();
811
+ this._lastTime ??= now;
812
+ const dt = (now - this._lastTime) / 1e3;
813
+ this._lastTime = now;
814
+ if (this._shakeTime > 0) {
815
+ this._shakeTime -= dt;
816
+ const magnitude = this._shakeTime / this._shakeTimeMax * this._options.shakeIntensity;
817
+ const shakeX = random(-magnitude, magnitude);
818
+ const shakeY = random(-magnitude, magnitude);
819
+ this._node.style.transform = `translate(${shakeX}px,${shakeY}px)`;
820
+ }
821
+ this.drawParticles();
822
+ requestAnimationFrame(this.loop.bind(this));
891
823
  }
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;
824
+ drawParticles() {
825
+ for (let i = this._particles.length; i--; i > 0) {
826
+ const particle = this._particles[i];
827
+ if (!particle) {
828
+ continue;
907
829
  }
908
- default: {
909
- console.error("Invalid message:", messageType);
910
- return encoder;
830
+ if (particle.alpha < 0.01 || particle.size <= 0.5) {
831
+ continue;
911
832
  }
833
+ this._effect.update(this._ctx, particle);
912
834
  }
913
- if (!sendReply) {
914
- return null;
835
+ }
836
+ };
837
+ var Effect = class {
838
+ constructor(_options) {
839
+ this._options = _options;
840
+ }
841
+ };
842
+ var Effect1 = class extends Effect {
843
+ create(x, y, color) {
844
+ return {
845
+ x,
846
+ y: y + 10,
847
+ vx: random(this._options.particleVelocityRange.x[0], this._options.particleVelocityRange.x[1]),
848
+ vy: random(this._options.particleVelocityRange.y[0], this._options.particleVelocityRange.y[1]),
849
+ size: random(this._options.particleSize.min, this._options.particleSize.max),
850
+ color,
851
+ alpha: 1
852
+ };
853
+ }
854
+ update(ctx, particle) {
855
+ particle.vy += this._options.particleGravity;
856
+ particle.x += particle.vx;
857
+ particle.y += particle.vy;
858
+ particle.alpha *= this._options.particleAlphaFadeout;
859
+ ctx.fillStyle = `rgba(${particle.color[0]},${particle.color[1]},${particle.color[2]},${particle.alpha})`;
860
+ ctx.fillRect(Math.round(particle.x - 1), Math.round(particle.y - 1), particle.size, particle.size);
861
+ }
862
+ };
863
+ var Effect2 = class extends Effect {
864
+ create(x, y, color) {
865
+ return {
866
+ x,
867
+ y: y + 10,
868
+ vx: random(this._options.particleVelocityRange.x[0], this._options.particleVelocityRange.x[1]),
869
+ vy: random(this._options.particleVelocityRange.y[0], this._options.particleVelocityRange.y[1]),
870
+ size: random(this._options.particleSize.min, this._options.particleSize.max),
871
+ color,
872
+ alpha: 1,
873
+ theta: random(0, 360) * Math.PI / 180,
874
+ drag: 0.92,
875
+ wander: 0.15
876
+ };
877
+ }
878
+ update(ctx, particle) {
879
+ particle.vy += this._options.particleGravity;
880
+ particle.x += particle.vx;
881
+ particle.y += particle.vy;
882
+ particle.vx *= particle.drag;
883
+ particle.vy *= particle.drag;
884
+ particle.theta += random(-0.5, 0.5);
885
+ particle.vx += Math.sin(particle.theta) * 0.1;
886
+ particle.vy += Math.cos(particle.theta) * 0.1;
887
+ particle.size *= this._options.particleShrinkRate;
888
+ particle.alpha *= this._options.particleAlphaFadeout;
889
+ ctx.fillStyle = `rgba(${particle.color[0]},${particle.color[1]},${particle.color[2]},${particle.alpha})`;
890
+ ctx.beginPath();
891
+ ctx.arc(Math.round(particle.x - 1), Math.round(particle.y - 1), particle.size, 0, 2 * Math.PI);
892
+ ctx.fill();
893
+ }
894
+ };
895
+ function throttle(callback, limit) {
896
+ let wait = false;
897
+ return function(...args) {
898
+ if (!wait) {
899
+ callback.apply(this, args);
900
+ wait = true;
901
+ setTimeout(() => {
902
+ wait = false;
903
+ }, limit);
915
904
  }
916
- return encoder;
905
+ };
906
+ }
907
+ var getRGBComponents = (node, color) => {
908
+ if (typeof color === "function") {
909
+ return color();
917
910
  }
918
- _handleBeforeUnload() {
919
- awarenessProtocol.removeAwarenessStates(this._awareness, [
920
- this._clientId
921
- ], "window unload");
911
+ const bgColor = getComputedStyle(node).color;
912
+ if (bgColor) {
913
+ const x = bgColor.match(/(\d+), (\d+), (\d+)/)?.slice(1);
914
+ if (x) {
915
+ return x;
916
+ }
917
+ }
918
+ return [
919
+ 50,
920
+ 50,
921
+ 50
922
+ ];
923
+ };
924
+ var random = (min, max) => {
925
+ if (!max) {
926
+ max = min;
927
+ min = 0;
928
+ }
929
+ return min + ~~(Math.random() * (max - min + 1));
930
+ };
931
+
932
+ // packages/ui/react-ui-editor/src/extensions/code.ts
933
+ import { ViewPlugin as ViewPlugin3, EditorView as EditorView4, Decoration as Decoration2 } from "@codemirror/view";
934
+ import { mx as mx2 } from "@dxos/react-ui-theme";
935
+
936
+ // packages/ui/react-ui-editor/src/styles/cursors.ts
937
+ import * as random2 from "lib0/random";
938
+ var cursorColors = [
939
+ {
940
+ color: "#30bced",
941
+ light: "#30bced33"
942
+ },
943
+ {
944
+ color: "#6eeb83",
945
+ light: "#6eeb8333"
946
+ },
947
+ {
948
+ color: "#ffbc42",
949
+ light: "#ffbc4233"
950
+ },
951
+ {
952
+ color: "#ecd444",
953
+ light: "#ecd44433"
954
+ },
955
+ {
956
+ color: "#ee6352",
957
+ light: "#ee635233"
958
+ },
959
+ {
960
+ color: "#9ac2c9",
961
+ light: "#9ac2c933"
962
+ },
963
+ {
964
+ color: "#8acb88",
965
+ light: "#8acb8833"
966
+ },
967
+ {
968
+ color: "#1be7ff",
969
+ light: "#1be7ff33"
922
970
  }
971
+ ];
972
+ var cursorColor = cursorColors[random2.uint32() % cursorColors.length];
973
+
974
+ // packages/ui/react-ui-editor/src/styles/markdown.ts
975
+ import { mx } from "@dxos/react-ui-theme";
976
+ var headings = {
977
+ 1: [
978
+ "mbs-4 mbe-2 font-medium text-inherit no-underline text-4xl",
979
+ "-ml-[10px]"
980
+ ],
981
+ 2: [
982
+ "mbs-4 mbe-2 font-medium text-inherit no-underline text-3xl",
983
+ "-ml-[8px]"
984
+ ],
985
+ 3: [
986
+ "mbs-4 mbe-2 font-medium text-inherit no-underline text-2xl",
987
+ "-ml-[7px]"
988
+ ],
989
+ 4: [
990
+ "mbs-4 mbe-2 font-medium text-inherit no-underline text-xl",
991
+ "-ml-[6px]"
992
+ ],
993
+ 5: [
994
+ "mbs-4 mbe-2 font-medium text-inherit no-underline text-lg",
995
+ "-ml-[5px]"
996
+ ],
997
+ 6: [
998
+ "mbs-4 mbe-2 font-medium text-inherit no-underline",
999
+ "-ml-[4px]"
1000
+ ]
1001
+ };
1002
+ var heading = (level, readonly) => {
1003
+ const [style, offset] = headings[level];
1004
+ return mx(style, readonly && offset);
923
1005
  };
1006
+ var light = "text-neutral-200 dark:text-neutral-800";
1007
+ var mark = mx("!font-normal !no-underline !text-inherit opacity-40", light);
1008
+ var bold = "font-bold";
1009
+ var italic = "italic";
1010
+ var strikethrough = "line-through";
1011
+ var code = "font-mono !no-underline text-neutral-700 dark:text-neutral-300";
1012
+ var codeMark = "font-mono text-primary-500";
1013
+ var inlineUrl = mx(code, "px-1");
1014
+ var blockquote = mx("pl-1 mr-1 border-is-4 border-primary-500/70 dark:border-primary-500/30", light);
924
1015
 
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
1016
+ // packages/ui/react-ui-editor/src/styles/tokens.ts
1017
+ import get2 from "lodash.get";
1018
+ import { tailwindConfig } from "@dxos/react-ui-theme";
1019
+ var tokens = tailwindConfig({}).theme;
1020
+ var getToken = (path, defaultValue = void 0) => get2(tokens, path, defaultValue);
1021
+
1022
+ // packages/ui/react-ui-editor/src/extensions/code.ts
1023
+ var CODE_REGEX = /```[\s\S]*?```/gs;
1024
+ var styles2 = EditorView4.baseTheme({
1025
+ "& .cm-codeblock": {
1026
+ fontFamily: getToken("fontFamily.mono", []).join(",")
1027
+ },
1028
+ '&light [aria-readonly="true"] .cm-codeblock': {
1029
+ background: getToken("extend.colors.neutral.50")
1030
+ },
1031
+ '&dark [aria-readonly="true"] .cm-codeblock': {
1032
+ background: getToken("extend.colors.neutral.850")
1033
+ },
1034
+ '& [aria-readonly="true"] .cm-codeblock': {
1035
+ display: "block",
1036
+ paddingInline: "4px !important"
1037
+ },
1038
+ '& [aria-readonly="true"] .cm-codeblock-first': {
1039
+ paddingTop: "4px !important",
1040
+ borderTopLeftRadius: "4px",
1041
+ borderTopRightRadius: "4px"
1042
+ },
1043
+ '& [aria-readonly="true"] .cm-codeblock-last': {
1044
+ paddingBottom: "4px !important",
1045
+ borderBottomLeftRadius: "4px",
1046
+ borderBottomRightRadius: "4px"
1047
+ }
930
1048
  });
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;
1049
+ var getLineRange = (lines, from, to) => {
1050
+ const start = lines.findIndex((line) => line.from >= from);
1051
+ const end = lines.findIndex((line) => line.to >= to);
1052
+ return [
1053
+ start,
1054
+ end
1055
+ ];
940
1056
  };
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;
1057
+ var code2 = () => {
1058
+ const getDecorations = (view) => {
1059
+ const decorations = [];
1060
+ if (view.state.readOnly) {
1061
+ const text = view.state.doc.sliceString(0);
1062
+ const matches = text.matchAll(CODE_REGEX);
1063
+ const blocks = view.viewportLineBlocks;
1064
+ for (const match of matches) {
1065
+ const range = getLineRange(blocks, match.index, match.index + match[0].length);
1066
+ for (let i = range[0]; i <= range[1]; i++) {
1067
+ const block = blocks[i];
1068
+ decorations.push(Decoration2.line({
1069
+ class: mx2("cm-codeblock", i === range[0] && "cm-codeblock-first", i === range[1] && "cm-codeblock-last")
1070
+ }).range(block.from));
1071
+ }
1072
+ }
948
1073
  }
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
1074
+ return Decoration2.set(decorations);
1028
1075
  };
1029
- return model;
1076
+ return [
1077
+ ViewPlugin3.fromClass(class {
1078
+ constructor(view) {
1079
+ this.decorations = getDecorations(view);
1080
+ }
1081
+ update(update2) {
1082
+ if (update2.docChanged || update2.viewportChanged) {
1083
+ this.decorations = getDecorations(update2.view);
1084
+ }
1085
+ }
1086
+ }, {
1087
+ decorations: (value) => value.decorations
1088
+ }),
1089
+ styles2
1090
+ ];
1030
1091
  };
1031
1092
 
1032
1093
  // 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({
1094
+ import { StateEffect as StateEffect2, StateField as StateField2 } from "@codemirror/state";
1095
+ import { hoverTooltip, keymap as keymap3, Decoration as Decoration3, EditorView as EditorView5, MatchDecorator, ViewPlugin as ViewPlugin4, WidgetType as WidgetType2 } from "@codemirror/view";
1096
+ import sortBy from "lodash.sortby";
1097
+ import { debounce } from "@dxos/async";
1098
+ import { invariant as invariant2 } from "@dxos/invariant";
1099
+ import { log as log2 } from "@dxos/log";
1100
+ import { nonNullable } from "@dxos/util";
1101
+ var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/extensions/comments.ts";
1102
+ var styles3 = EditorView5.baseTheme({
1035
1103
  "& .cm-bookmark": {
1036
1104
  cursor: "pointer",
1037
1105
  margin: "4px",
@@ -1042,17 +1110,17 @@ var styles2 = EditorView4.baseTheme({
1042
1110
  backgroundColor: "orange"
1043
1111
  },
1044
1112
  "& .cm-comment": {
1045
- backgroundColor: get3(tokens, "extend.colors.yellow.50")
1113
+ backgroundColor: getToken("extend.colors.yellow.50")
1046
1114
  },
1047
1115
  "& .cm-comment-active": {
1048
- backgroundColor: get3(tokens, "extend.colors.yellow.100")
1116
+ backgroundColor: getToken("extend.colors.yellow.100")
1049
1117
  }
1050
1118
  });
1051
1119
  var marks = {
1052
- highlight: Decoration2.mark({
1120
+ highlight: Decoration3.mark({
1053
1121
  class: "cm-comment"
1054
1122
  }),
1055
- highlightActive: Decoration2.mark({
1123
+ highlightActive: Decoration3.mark({
1056
1124
  class: "cm-comment-active"
1057
1125
  })
1058
1126
  };
@@ -1074,11 +1142,12 @@ var setFocus = (view, thread) => {
1074
1142
  var setCommentRange = StateEffect2.define();
1075
1143
  var setSelection = StateEffect2.define();
1076
1144
  var setCommentState = StateEffect2.define();
1077
- var commentsStateField = StateField3.define({
1145
+ var commentsStateField = StateField2.define({
1078
1146
  create: () => ({
1079
1147
  ranges: []
1080
1148
  }),
1081
1149
  update: (value, tr) => {
1150
+ const cursorConverter3 = tr.state.facet(CursorConverter);
1082
1151
  for (const effect of tr.effects) {
1083
1152
  if (effect.is(setSelection)) {
1084
1153
  return {
@@ -1087,9 +1156,9 @@ var commentsStateField = StateField3.define({
1087
1156
  };
1088
1157
  }
1089
1158
  if (effect.is(setCommentRange)) {
1090
- const { model, comments: comments2 } = effect.value;
1159
+ const { comments: comments2 } = effect.value;
1091
1160
  const ranges = comments2.map((comment) => {
1092
- const range = model.getRangeFromCursor(comment.cursor);
1161
+ const range = getRangeFromCursor(cursorConverter3, comment.cursor);
1093
1162
  return range && {
1094
1163
  ...comment,
1095
1164
  ...range
@@ -1107,7 +1176,7 @@ var commentsStateField = StateField3.define({
1107
1176
  return value;
1108
1177
  }
1109
1178
  });
1110
- var highlightDecorations = EditorView4.decorations.compute([
1179
+ var highlightDecorations = EditorView5.decorations.compute([
1111
1180
  commentsStateField
1112
1181
  ], (state) => {
1113
1182
  const { active, ranges } = state.field(commentsStateField);
@@ -1125,17 +1194,17 @@ var highlightDecorations = EditorView4.decorations.compute([
1125
1194
  return marks.highlight.range(range.from, range.to);
1126
1195
  }
1127
1196
  }).filter(nonNullable) ?? [];
1128
- return Decoration2.set(decorations);
1197
+ return Decoration3.set(decorations);
1129
1198
  });
1130
- var BookmarkWidget = class extends WidgetType {
1199
+ var BookmarkWidget = class extends WidgetType2 {
1131
1200
  constructor(_anchor, _id, _handleClick) {
1132
1201
  super();
1133
1202
  this._anchor = _anchor;
1134
1203
  this._id = _id;
1135
1204
  this._handleClick = _handleClick;
1136
- invariant3(this._id, void 0, {
1137
- F: __dxlog_file5,
1138
- L: 167,
1205
+ invariant2(this._id, void 0, {
1206
+ F: __dxlog_file3,
1207
+ L: 168,
1139
1208
  S: this,
1140
1209
  A: [
1141
1210
  "this._id",
@@ -1159,9 +1228,10 @@ var BookmarkWidget = class extends WidgetType {
1159
1228
  var comments = (options = {}) => {
1160
1229
  const handleSelect = debounce((state) => options.onSelect?.(state), 200);
1161
1230
  const createCommentThread = (view) => {
1162
- invariant3(options.onCreate, void 0, {
1163
- F: __dxlog_file5,
1164
- L: 221,
1231
+ const cursorConverter3 = view.state.facet(CursorConverter);
1232
+ invariant2(options.onCreate, void 0, {
1233
+ F: __dxlog_file3,
1234
+ L: 224,
1165
1235
  S: void 0,
1166
1236
  A: [
1167
1237
  "options.onCreate",
@@ -1172,8 +1242,7 @@ var comments = (options = {}) => {
1172
1242
  if (from === to) {
1173
1243
  return false;
1174
1244
  }
1175
- const model = view.state.field(modelState);
1176
- const relPos = model?.getCursorFromRange?.({
1245
+ const relPos = getCursorFromRange(cursorConverter3, {
1177
1246
  from,
1178
1247
  to
1179
1248
  });
@@ -1205,7 +1274,7 @@ var comments = (options = {}) => {
1205
1274
  }
1206
1275
  return false;
1207
1276
  };
1208
- const bookmarksViewPlugin = ViewPlugin3.fromClass(class BookmarkViewPlugin {
1277
+ const bookmarksViewPlugin = ViewPlugin4.fromClass(class BookmarkViewPlugin {
1209
1278
  static {
1210
1279
  // Match markdown footnotes (option).
1211
1280
  // https://www.markdownguide.org/extended-syntax/#footnotes
@@ -1213,7 +1282,7 @@ var comments = (options = {}) => {
1213
1282
  regexp: /\[\^(\w+)\]/g,
1214
1283
  decoration: (match, view, pos) => {
1215
1284
  const id = match[1];
1216
- return Decoration2.replace({
1285
+ return Decoration3.replace({
1217
1286
  id,
1218
1287
  widget: new BookmarkWidget(pos, id)
1219
1288
  });
@@ -1223,20 +1292,20 @@ var comments = (options = {}) => {
1223
1292
  constructor(view) {
1224
1293
  this.bookmarks = BookmarkViewPlugin.bookmarkMatcher.createDeco(view);
1225
1294
  }
1226
- update(update4) {
1227
- this.bookmarks = BookmarkViewPlugin.bookmarkMatcher.updateDeco(update4, this.bookmarks);
1295
+ update(update2) {
1296
+ this.bookmarks = BookmarkViewPlugin.bookmarkMatcher.updateDeco(update2, this.bookmarks);
1228
1297
  }
1229
1298
  }, {
1230
1299
  decorations: (instance) => instance.bookmarks,
1231
- provide: (plugin) => EditorView4.atomicRanges.of((view) => {
1232
- return view.plugin(plugin)?.bookmarks || Decoration2.none;
1300
+ provide: (plugin) => EditorView5.atomicRanges.of((view) => {
1301
+ return view.plugin(plugin)?.bookmarks || Decoration3.none;
1233
1302
  })
1234
1303
  });
1235
1304
  return [
1236
1305
  bookmarksViewPlugin,
1237
1306
  commentsStateField,
1238
1307
  highlightDecorations,
1239
- styles2,
1308
+ styles3,
1240
1309
  //
1241
1310
  // Keymap.
1242
1311
  //
@@ -1279,37 +1348,28 @@ var comments = (options = {}) => {
1279
1348
  // Monitor cursor movement and text updates.
1280
1349
  // TODO(burdon): Is there a better (finer grained) way to do this?
1281
1350
  //
1282
- EditorView4.updateListener.of(({ view, state, startState, changes }) => {
1351
+ EditorView5.updateListener.of(({ view, state, changes }) => {
1352
+ const cursorConverter3 = view.state.facet(CursorConverter);
1283
1353
  {
1284
1354
  let mod = false;
1285
- const model = state.field(modelState);
1286
1355
  const { active, ranges } = state.field(commentsStateField);
1287
1356
  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
1357
  ranges.forEach((range) => {
1298
1358
  if (from2 === to2) {
1299
- const newRange = model.getRangeFromCursor(range.cursor);
1359
+ const newRange = getRangeFromCursor(cursorConverter3, range.cursor);
1300
1360
  if (!newRange || newRange.to - newRange.from === 0) {
1301
- log3.info("deleted comment", {
1361
+ log2.info("deleted comment", {
1302
1362
  thread: range.id
1303
1363
  }, {
1304
- F: __dxlog_file5,
1305
- L: 356,
1364
+ F: __dxlog_file3,
1365
+ L: 358,
1306
1366
  S: void 0,
1307
1367
  C: (f, a) => f(...a)
1308
1368
  });
1309
1369
  }
1310
1370
  }
1311
1371
  if (from <= range.to) {
1312
- const newRange = model.getRangeFromCursor(range.cursor);
1372
+ const newRange = getRangeFromCursor(cursorConverter3, range.cursor);
1313
1373
  Object.assign(range, newRange);
1314
1374
  mod = true;
1315
1375
  }
@@ -1358,18 +1418,34 @@ var comments = (options = {}) => {
1358
1418
  })
1359
1419
  ];
1360
1420
  };
1421
+ var getCursorFromRange = (cursorConverter3, range) => {
1422
+ const from = cursorConverter3.toCursor(range.from);
1423
+ const to = cursorConverter3.toCursor(range.to, -1);
1424
+ return [
1425
+ from,
1426
+ to
1427
+ ].join(":");
1428
+ };
1429
+ var getRangeFromCursor = (cursorConverter3, cursor) => {
1430
+ const parts = cursor.split(":");
1431
+ const from = cursorConverter3.fromCursor(parts[0]);
1432
+ const to = cursorConverter3.fromCursor(parts[1]);
1433
+ return from !== void 0 && to !== void 0 ? {
1434
+ from,
1435
+ to
1436
+ } : void 0;
1437
+ };
1361
1438
 
1362
1439
  // 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({
1440
+ import { Decoration as Decoration4, EditorView as EditorView6, MatchDecorator as MatchDecorator2, ViewPlugin as ViewPlugin5, WidgetType as WidgetType3 } from "@codemirror/view";
1441
+ var styles4 = EditorView6.baseTheme({
1366
1442
  "& .cm-hr": {
1367
1443
  // TODO(burdon): ???
1368
1444
  // Note that block-level decorations should not have vertical margins,
1369
- borderBottom: `1px solid ${get4(tokens, "extend.colors.neutral.200")}`
1445
+ borderBottom: `1px solid ${getToken("extend.colors.neutral.200")}`
1370
1446
  }
1371
1447
  });
1372
- var HorizontalRuleWidget = class extends WidgetType2 {
1448
+ var HorizontalRuleWidget = class extends WidgetType3 {
1373
1449
  constructor(_pos) {
1374
1450
  super();
1375
1451
  this._pos = _pos;
@@ -1385,41 +1461,63 @@ var HorizontalRuleWidget = class extends WidgetType2 {
1385
1461
  };
1386
1462
  var placeholderMatcher = new MatchDecorator2({
1387
1463
  regexp: /^---$/g,
1388
- decoration: (match, view, pos) => Decoration3.replace({
1464
+ decoration: (match, view, pos) => Decoration4.replace({
1389
1465
  widget: new HorizontalRuleWidget(pos)
1390
1466
  })
1391
1467
  });
1392
1468
  var hr = () => [
1393
- styles3,
1394
- ViewPlugin4.fromClass(class {
1469
+ styles4,
1470
+ ViewPlugin5.fromClass(class {
1395
1471
  constructor(view) {
1396
1472
  this.rules = placeholderMatcher.createDeco(view);
1397
1473
  }
1398
- update(update4) {
1399
- this.rules = placeholderMatcher.updateDeco(update4, this.rules);
1474
+ update(update2) {
1475
+ this.rules = placeholderMatcher.updateDeco(update2, this.rules);
1400
1476
  }
1401
1477
  }, {
1402
1478
  decorations: (instance) => instance.rules,
1403
1479
  // 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;
1480
+ provide: (plugin) => EditorView6.atomicRanges.of((view) => {
1481
+ return view.plugin(plugin)?.rules || Decoration4.none;
1406
1482
  })
1407
1483
  })
1408
1484
  ];
1409
1485
 
1410
1486
  // packages/ui/react-ui-editor/src/extensions/image.ts
1411
1487
  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";
1488
+ import { StateField as StateField3 } from "@codemirror/state";
1489
+ import { Decoration as Decoration5, EditorView as EditorView7, WidgetType as WidgetType4 } from "@codemirror/view";
1414
1490
  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)
1491
+ return StateField3.define({
1492
+ create: (state) => {
1493
+ return Decoration5.set(buildDecorations(0, state.doc.length, state));
1494
+ },
1495
+ update: (value, tr) => {
1496
+ if (!tr.docChanged && !tr.selection) {
1497
+ return value;
1498
+ }
1499
+ const cursor = tr.state.selection.main.head;
1500
+ const oldCursor = tr.changes.mapPos(tr.startState.selection.main.head);
1501
+ let from = Math.min(cursor, oldCursor);
1502
+ let to = Math.max(cursor, oldCursor);
1503
+ tr.changes.iterChangedRanges((fromA, toA, fromB, toB) => {
1504
+ from = Math.min(from, fromB);
1505
+ to = Math.max(to, toB);
1506
+ });
1507
+ from = tr.state.doc.lineAt(from).from;
1508
+ to = tr.state.doc.lineAt(to).to;
1509
+ return value.map(tr.changes).update({
1510
+ filterFrom: from,
1511
+ filterTo: to,
1512
+ filter: () => false,
1513
+ add: buildDecorations(from, to, tr.state)
1514
+ });
1515
+ },
1516
+ provide: (field) => EditorView7.decorations.from(field)
1419
1517
  });
1420
1518
  };
1421
- var update = (state, options) => {
1422
- const builder = new RangeSetBuilder();
1519
+ var buildDecorations = (from, to, state) => {
1520
+ const decorations = [];
1423
1521
  const cursor = state.selection.main.head;
1424
1522
  syntaxTree(state).iterate({
1425
1523
  enter: (node) => {
@@ -1428,22 +1526,23 @@ var update = (state, options) => {
1428
1526
  if (urlNode) {
1429
1527
  const hide = state.readOnly || cursor < node.from || cursor > node.to;
1430
1528
  const url = state.sliceDoc(urlNode.from, urlNode.to);
1431
- builder.add(hide ? node.from : node.to, node.to, Decoration4.replace({
1529
+ decorations.push(Decoration5.replace({
1432
1530
  block: true,
1433
1531
  widget: new ImageWidget(url)
1434
- }));
1532
+ }).range(hide ? node.from : node.to, node.to));
1435
1533
  }
1436
1534
  }
1437
- }
1535
+ },
1536
+ from,
1537
+ to
1438
1538
  });
1439
- return builder.finish();
1539
+ return decorations;
1440
1540
  };
1441
- var ImageWidget = class extends WidgetType3 {
1541
+ var ImageWidget = class extends WidgetType4 {
1442
1542
  constructor(_url) {
1443
1543
  super();
1444
1544
  this._url = _url;
1445
1545
  }
1446
- // TODO(burdon): Does this need to be unique for each position?
1447
1546
  eq(other) {
1448
1547
  return this._url === other._url;
1449
1548
  }
@@ -1451,22 +1550,29 @@ var ImageWidget = class extends WidgetType3 {
1451
1550
  const img = document.createElement("img");
1452
1551
  img.setAttribute("src", this._url);
1453
1552
  img.setAttribute("class", "cm-image");
1553
+ img.onload = () => img.classList.add("cm-loaded-image");
1454
1554
  return img;
1455
1555
  }
1456
1556
  };
1457
1557
 
1458
1558
  // packages/ui/react-ui-editor/src/extensions/link.ts
1459
1559
  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";
1560
+ import { RangeSetBuilder } from "@codemirror/state";
1561
+ import { Decoration as Decoration6, WidgetType as WidgetType5, hoverTooltip as hoverTooltip2, ViewPlugin as ViewPlugin6 } from "@codemirror/view";
1462
1562
  import { tooltipContent } from "@dxos/react-ui-theme";
1463
- var markdownLinkRegexp = /\[([^\]]+)]\(([^)]+)\)/;
1464
1563
  var link = (options = {}) => {
1465
1564
  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)
1565
+ ViewPlugin6.fromClass(class {
1566
+ constructor(view) {
1567
+ this.decorations = buildDecorations2(view, options);
1568
+ }
1569
+ update(update2) {
1570
+ if (update2.docChanged || update2.viewportChanged || update2.selectionSet) {
1571
+ this.decorations = buildDecorations2(update2.view, options);
1572
+ }
1573
+ }
1574
+ }, {
1575
+ decorations: (v) => v.decorations
1470
1576
  })
1471
1577
  ];
1472
1578
  if (options.onHover) {
@@ -1474,35 +1580,25 @@ var link = (options = {}) => {
1474
1580
  // https://codemirror.net/examples/tooltip
1475
1581
  // https://codemirror.net/docs/ref/#view.hoverTooltip
1476
1582
  // 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) {
1583
+ hoverTooltip2((view, pos, side) => {
1584
+ const syntax = syntaxTree2(view.state).resolveInner(pos, side);
1585
+ let link2 = null;
1586
+ for (let i = 0, node = syntax; !link2 && node && i < 5; node = node.parent, i++) {
1587
+ link2 = node.name === "Link" ? node : null;
1588
+ }
1589
+ const url = link2 && link2.getChild("URL");
1590
+ if (!url || !link2) {
1495
1591
  return null;
1496
1592
  }
1497
- const [, , url] = match ?? [];
1593
+ const urlText = view.state.sliceDoc(url.from, url.to);
1498
1594
  return {
1499
- pos: idx + from,
1500
- end: idx + from + match[0].length,
1595
+ pos: link2.from,
1596
+ end: link2.to,
1501
1597
  above: true,
1502
1598
  create: () => {
1503
1599
  const el = document.createElement("div");
1504
1600
  el.className = tooltipContent({}, "pli-2 plb-1");
1505
- options.onHover(el, url);
1601
+ options.onHover(el, urlText);
1506
1602
  return {
1507
1603
  dom: el,
1508
1604
  offset: {
@@ -1517,15 +1613,14 @@ var link = (options = {}) => {
1517
1613
  }
1518
1614
  return extensions;
1519
1615
  };
1520
- var LinkButton = class extends WidgetType4 {
1521
- constructor(_pos, _url, _onAttach) {
1616
+ var LinkButton = class extends WidgetType5 {
1617
+ constructor(_url, _onAttach) {
1522
1618
  super();
1523
- this._pos = _pos;
1524
1619
  this._url = _url;
1525
1620
  this._onAttach = _onAttach;
1526
1621
  }
1527
1622
  eq(other) {
1528
- return this._pos === other._pos && this._url === other._url;
1623
+ return this._url === other._url;
1529
1624
  }
1530
1625
  toDOM(view) {
1531
1626
  const el = document.createElement("span");
@@ -1533,7 +1628,7 @@ var LinkButton = class extends WidgetType4 {
1533
1628
  return el;
1534
1629
  }
1535
1630
  };
1536
- var LinkText = class extends WidgetType4 {
1631
+ var LinkText = class extends WidgetType5 {
1537
1632
  constructor(_text, _url) {
1538
1633
  super();
1539
1634
  this._text = _text;
@@ -1562,33 +1657,38 @@ var LinkText = class extends WidgetType4 {
1562
1657
  return link2;
1563
1658
  }
1564
1659
  };
1565
- var update2 = (state, options) => {
1566
- const builder = new RangeSetBuilder2();
1660
+ var buildDecorations2 = (view, options) => {
1661
+ const builder = new RangeSetBuilder();
1662
+ const { state } = view;
1567
1663
  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) {
1664
+ for (const { from, to } of view.visibleRanges) {
1665
+ syntaxTree2(state).iterate({
1666
+ enter: (node) => {
1667
+ if (node.name === "Link") {
1668
+ const marks2 = node.node.getChildren("LinkMark");
1669
+ const text = marks2.length >= 2 ? state.sliceDoc(marks2[0].to, marks2[1].from) : "";
1670
+ const urlNode = node.node.getChild("URL");
1671
+ const url = urlNode ? state.sliceDoc(urlNode.from, urlNode.to) : "";
1672
+ if (!url) {
1673
+ return false;
1674
+ }
1675
+ if (!view.hasFocus || state.readOnly || cursor < node.from || cursor > node.to) {
1676
+ builder.add(node.from, node.to, Decoration6.replace({
1677
+ widget: new LinkText(text, options.link ? url : void 0)
1678
+ }));
1679
+ }
1680
+ if (options.onRender) {
1681
+ builder.add(node.to, node.to, Decoration6.replace({
1682
+ widget: new LinkButton(url, options.onRender)
1683
+ }));
1684
+ }
1576
1685
  return false;
1577
1686
  }
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
- });
1687
+ },
1688
+ from,
1689
+ to
1690
+ });
1691
+ }
1592
1692
  return builder.finish();
1593
1693
  };
1594
1694
 
@@ -1600,8 +1700,8 @@ var listener = ({ onFocus, onChange }) => {
1600
1700
  onFocus(focused);
1601
1701
  return null;
1602
1702
  }));
1603
- onChange && extensions.push(EditorView8.updateListener.of((update4) => {
1604
- onChange(update4.state.doc.toString());
1703
+ onChange && extensions.push(EditorView8.updateListener.of((update2) => {
1704
+ onChange(update2.state.doc.toString());
1605
1705
  }));
1606
1706
  return extensions;
1607
1707
  };
@@ -1609,7 +1709,7 @@ var listener = ({ onFocus, onChange }) => {
1609
1709
  // packages/ui/react-ui-editor/src/extensions/markdown/bundle.ts
1610
1710
  import { closeBrackets as closeBrackets2, closeBracketsKeymap } from "@codemirror/autocomplete";
1611
1711
  import { history, historyKeymap, indentWithTab, standardKeymap } from "@codemirror/commands";
1612
- import { markdownLanguage as markdownLanguage2, markdown } from "@codemirror/lang-markdown";
1712
+ import { markdownLanguage as markdownLanguage3, markdown } from "@codemirror/lang-markdown";
1613
1713
  import { bracketMatching as bracketMatching2, defaultHighlightStyle as defaultHighlightStyle2, indentOnInput, syntaxHighlighting as syntaxHighlighting2 } from "@codemirror/language";
1614
1714
  import { languages } from "@codemirror/language-data";
1615
1715
  import { searchKeymap } from "@codemirror/search";
@@ -1618,11 +1718,10 @@ import { oneDarkHighlightStyle as oneDarkHighlightStyle2 } from "@codemirror/the
1618
1718
  import { crosshairCursor, drawSelection as drawSelection2, dropCursor, EditorView as EditorView9, highlightActiveLine, keymap as keymap4, placeholder as placeholder2 } from "@codemirror/view";
1619
1719
 
1620
1720
  // packages/ui/react-ui-editor/src/extensions/markdown/highlight.ts
1621
- import { markdownLanguage } from "@codemirror/lang-markdown";
1721
+ import { markdownLanguage as markdownLanguage2 } from "@codemirror/lang-markdown";
1622
1722
  import { HighlightStyle } from "@codemirror/language";
1623
1723
  import { tags, styleTags, Tag } from "@lezer/highlight";
1624
1724
  import { Table } from "@lezer/markdown";
1625
- import get5 from "lodash.get";
1626
1725
  var markdownTags = {
1627
1726
  Blockquote: Tag.define(),
1628
1727
  CodeMark: Tag.define(),
@@ -1806,9 +1905,9 @@ var markdownHighlightStyle = (readonly) => {
1806
1905
  class: "font-mono"
1807
1906
  }
1808
1907
  ], {
1809
- scope: markdownLanguage,
1908
+ scope: markdownLanguage2,
1810
1909
  all: {
1811
- fontFamily: get5(tokens, "fontFamily.body", []).join(",")
1910
+ fontFamily: getToken("fontFamily.body", []).join(",")
1812
1911
  }
1813
1912
  });
1814
1913
  };
@@ -1838,7 +1937,7 @@ var markdownBundle = ({ readonly, themeMode, placeholder: _placeholder }) => {
1838
1937
  // NOTE: This extends the parser; it doesn't affect rendering.
1839
1938
  // https://github.github.com/gfm
1840
1939
  // https://github.com/lezer-parser/markdown?tab=readme-ov-file#github-flavored-markdown
1841
- base: markdownLanguage2,
1940
+ base: markdownLanguage3,
1842
1941
  // Languages for syntax highlighting fenced code blocks.
1843
1942
  codeLanguages: languages,
1844
1943
  // Parser extensions.
@@ -1889,24 +1988,19 @@ var mention = ({ onSearch }) => {
1889
1988
  });
1890
1989
  };
1891
1990
 
1892
- // packages/ui/react-ui-editor/src/extensions/mermaid.ts
1893
- var mermaid = () => {
1894
- return [];
1895
- };
1896
-
1897
1991
  // packages/ui/react-ui-editor/src/extensions/table.ts
1898
1992
  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";
1993
+ import { RangeSetBuilder as RangeSetBuilder2, StateField as StateField4 } from "@codemirror/state";
1994
+ import { Decoration as Decoration7, EditorView as EditorView10, WidgetType as WidgetType6 } from "@codemirror/view";
1901
1995
  var table = (options = {}) => {
1902
- return StateField6.define({
1903
- create: (state) => update3(state, options),
1904
- update: (_, tr) => update3(tr.state, options),
1996
+ return StateField4.define({
1997
+ create: (state) => update(state, options),
1998
+ update: (_, tr) => update(tr.state, options),
1905
1999
  provide: (field) => EditorView10.decorations.from(field)
1906
2000
  });
1907
2001
  };
1908
- var update3 = (state, options) => {
1909
- const builder = new RangeSetBuilder3();
2002
+ var update = (state, options) => {
2003
+ const builder = new RangeSetBuilder2();
1910
2004
  const cursor = state.selection.main.head;
1911
2005
  const tables = [];
1912
2006
  const getTable = () => tables[tables.length - 1];
@@ -1946,23 +2040,22 @@ var update3 = (state, options) => {
1946
2040
  });
1947
2041
  tables.forEach((table2) => {
1948
2042
  const hide = state.readOnly || cursor < table2.from || cursor > table2.to;
1949
- hide && builder.add(table2.from, table2.to, Decoration6.replace({
1950
- block: true,
2043
+ hide && builder.add(table2.from, table2.to, Decoration7.replace({
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");
@@ -1988,26 +2081,28 @@ var TableWidget = class extends WidgetType5 {
1988
2081
  }
1989
2082
  return table2;
1990
2083
  }
2084
+ ignoreEvent(e) {
2085
+ return !/^mouse/.test(e.type);
2086
+ }
1991
2087
  };
1992
2088
 
1993
2089
  // 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({
2090
+ import { EditorView as EditorView11, Decoration as Decoration8, WidgetType as WidgetType7, MatchDecorator as MatchDecorator3, ViewPlugin as ViewPlugin7 } from "@codemirror/view";
2091
+ var styles5 = EditorView11.baseTheme({
1996
2092
  "& .cm-task-item": {
1997
2093
  paddingLeft: "4px",
1998
2094
  paddingRight: "8px"
1999
2095
  }
2000
2096
  });
2001
- var CheckboxWidget = class extends WidgetType6 {
2002
- constructor(_pos, _checked, _indent, _onCheck) {
2097
+ var CheckboxWidget = class extends WidgetType7 {
2098
+ constructor(_checked, _indent, _onCheck) {
2003
2099
  super();
2004
- this._pos = _pos;
2005
2100
  this._checked = _checked;
2006
2101
  this._indent = _indent;
2007
2102
  this._onCheck = _onCheck;
2008
2103
  }
2009
2104
  eq(other) {
2010
- return this._pos === other._pos && this._checked === other._checked && this._indent === other._indent;
2105
+ return this._checked === other._checked && this._indent === other._indent;
2011
2106
  }
2012
2107
  toDOM(view) {
2013
2108
  const wrap = document.createElement("span");
@@ -2038,8 +2133,8 @@ var tasklist = (options = {}) => {
2038
2133
  decoration: (match, view, pos) => {
2039
2134
  const indent = Math.floor(match[1].length / 2);
2040
2135
  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) => {
2136
+ return Decoration8.replace({
2137
+ widget: new CheckboxWidget(checked, indent, view.state.readOnly ? void 0 : (checked2) => {
2043
2138
  const idx = pos + match[0].indexOf("[") + 1;
2044
2139
  view.dispatch({
2045
2140
  changes: {
@@ -2056,22 +2151,22 @@ var tasklist = (options = {}) => {
2056
2151
  });
2057
2152
  }
2058
2153
  });
2059
- const tasks = ViewPlugin5.fromClass(class {
2154
+ const tasks = ViewPlugin7.fromClass(class {
2060
2155
  constructor(view) {
2061
2156
  this.tasks = taskMatcher.createDeco(view);
2062
2157
  }
2063
- update(update4) {
2064
- this.tasks = taskMatcher.updateDeco(update4, this.tasks);
2158
+ update(update2) {
2159
+ this.tasks = taskMatcher.updateDeco(update2, this.tasks);
2065
2160
  }
2066
2161
  }, {
2067
2162
  decorations: (value) => value.tasks,
2068
2163
  provide: (plugin) => EditorView11.atomicRanges.of((view) => {
2069
- return view.plugin(plugin)?.tasks || Decoration7.none;
2164
+ return view.plugin(plugin)?.tasks || Decoration8.none;
2070
2165
  })
2071
2166
  });
2072
2167
  return [
2073
2168
  tasks,
2074
- styles4
2169
+ styles5
2075
2170
  ];
2076
2171
  };
2077
2172
 
@@ -2132,8 +2227,29 @@ var typewriter = ({ delay = 75, items = defaultItems } = {}) => {
2132
2227
  ];
2133
2228
  };
2134
2229
 
2230
+ // packages/ui/react-ui-editor/src/extensions/yjs/yjs.ts
2231
+ import { yCollab } from "y-codemirror.next";
2232
+
2233
+ // packages/ui/react-ui-editor/src/extensions/yjs/cursor.ts
2234
+ import * as Y from "yjs";
2235
+ import { arrayToString, stringToArray } from "@dxos/util";
2236
+ var cursorConverter2 = (text) => ({
2237
+ toCursor: (index, assoc) => {
2238
+ return arrayToString(Y.encodeRelativePosition(Y.createRelativePositionFromTypeIndex(text, index, assoc)));
2239
+ },
2240
+ fromCursor: (cursor) => {
2241
+ return Y.createAbsolutePositionFromRelativePosition(Y.decodeRelativePosition(stringToArray(cursor)), text.doc)?.index ?? 0;
2242
+ }
2243
+ });
2244
+
2245
+ // packages/ui/react-ui-editor/src/extensions/yjs/yjs.ts
2246
+ var yjs = (content, awareness2) => [
2247
+ CursorConverter.of(cursorConverter2(content)),
2248
+ yCollab(content, awareness2)
2249
+ ];
2250
+
2135
2251
  // packages/ui/react-ui-editor/src/themes/default.ts
2136
- import get6 from "lodash.get";
2252
+ import get3 from "lodash.get";
2137
2253
  var defaultTheme = {
2138
2254
  //
2139
2255
  // Main layout:
@@ -2162,21 +2278,21 @@ var defaultTheme = {
2162
2278
  "&.cm-focused": {
2163
2279
  outline: "none"
2164
2280
  },
2165
- "& .cm-scroller": {
2281
+ ".cm-scroller": {
2166
2282
  overflow: "visible",
2167
- fontFamily: get6(tokens, "fontFamily.mono", []).join(",")
2283
+ fontFamily: get3(tokens, "fontFamily.mono", []).join(",")
2168
2284
  },
2169
- "& .cm-content": {
2285
+ ".cm-content": {
2170
2286
  padding: 0,
2171
2287
  // NOTE: Base font size (otherwise defined by HTML tag, which might be different for storybook).
2172
2288
  fontSize: "16px"
2173
2289
  },
2174
2290
  "&light .cm-content": {
2175
- color: get6(tokens, "extend.colors.neutral.900", "black"),
2291
+ color: get3(tokens, "extend.colors.neutral.900", "black"),
2176
2292
  caretColor: "black"
2177
2293
  },
2178
2294
  "&dark .cm-content": {
2179
- color: get6(tokens, "extend.colors.neutral.100", "white"),
2295
+ color: get3(tokens, "extend.colors.neutral.100", "white"),
2180
2296
  caretColor: "white"
2181
2297
  },
2182
2298
  //
@@ -2188,41 +2304,41 @@ var defaultTheme = {
2188
2304
  "&dark .cm-cursor, &dark .cm-dropCursor": {
2189
2305
  borderLeft: "2px solid white"
2190
2306
  },
2191
- "& .cm-placeholder": {
2307
+ ".cm-placeholder": {
2192
2308
  fontWeight: 100
2193
2309
  },
2194
2310
  //
2195
2311
  // line
2196
2312
  //
2197
- "& .cm-line": {
2313
+ ".cm-line": {
2198
2314
  paddingInline: 0
2199
2315
  },
2200
- "& .cm-activeLine": {
2316
+ ".cm-activeLine": {
2201
2317
  background: "inherit"
2202
2318
  },
2203
2319
  //
2204
2320
  // Selection
2205
2321
  //
2206
2322
  "&light .cm-selectionBackground": {
2207
- background: get6(tokens, "extend.colors.primary.100")
2323
+ background: get3(tokens, "extend.colors.primary.100")
2208
2324
  },
2209
2325
  "&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground": {
2210
- background: get6(tokens, "extend.colors.primary.200")
2326
+ background: get3(tokens, "extend.colors.primary.200")
2211
2327
  },
2212
2328
  "&dark .cm-selectionBackground": {
2213
- background: get6(tokens, "extend.colors.primary.700")
2329
+ background: get3(tokens, "extend.colors.primary.700")
2214
2330
  },
2215
2331
  "&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground": {
2216
- background: get6(tokens, "extend.colors.primary.600")
2332
+ background: get3(tokens, "extend.colors.primary.600")
2217
2333
  },
2218
2334
  //
2219
2335
  // Search
2220
2336
  //
2221
2337
  "&light .cm-searchMatch": {
2222
- backgroundColor: get6(tokens, "extend.colors.yellow.100")
2338
+ backgroundColor: get3(tokens, "extend.colors.yellow.100")
2223
2339
  },
2224
2340
  "&dark .cm-searchMatch": {
2225
- backgroundColor: get6(tokens, "extend.colors.yellow.700")
2341
+ backgroundColor: get3(tokens, "extend.colors.yellow.700")
2226
2342
  },
2227
2343
  //
2228
2344
  // collaboration
@@ -2234,95 +2350,101 @@ var defaultTheme = {
2234
2350
  "&dark .cm-ySelection, &dark .cm-yLineSelection": {
2235
2351
  mixBlendMode: "screen"
2236
2352
  },
2237
- "& .cm-ySelectionInfo": {
2353
+ ".cm-ySelectionInfo": {
2238
2354
  padding: "2px 4px",
2239
2355
  marginBlockStart: "-4px"
2240
2356
  },
2241
- "& .cm-ySelection, & .cm-selectionMatch": {
2357
+ ".cm-ySelection, & .cm-selectionMatch": {
2242
2358
  paddingBlockStart: ".15em",
2243
2359
  paddingBlockEnd: ".15em"
2244
2360
  },
2245
- "& .cm-ySelectionCaret": {
2361
+ ".cm-ySelectionCaret": {
2246
2362
  display: "inline-block",
2247
2363
  insetBlockStart: ".1em",
2248
2364
  blockSize: "1.4em",
2249
2365
  verticalAlign: "top"
2250
2366
  },
2251
- "& .cm-yLineSelection": {
2367
+ ".cm-yLineSelection": {
2252
2368
  margin: 0
2253
2369
  },
2254
2370
  //
2255
2371
  // link
2256
2372
  //
2257
- "& .cm-link": {
2258
- color: get6(tokens, "extend.colors.primary.500"),
2373
+ ".cm-link": {
2374
+ color: get3(tokens, "extend.colors.primary.500"),
2259
2375
  textDecorationLine: "underline",
2260
2376
  textDecorationThickness: "1px",
2261
2377
  textUnderlineOffset: "2px",
2262
2378
  borderRadius: ".125rem",
2263
- fontFamily: get6(tokens, "fontFamily.body", []).join(",")
2379
+ fontFamily: get3(tokens, "fontFamily.body", []).join(",")
2264
2380
  },
2265
2381
  //
2266
2382
  // tooltip
2267
2383
  //
2268
- "& .cm-tooltip": {
2384
+ ".cm-tooltip": {
2269
2385
  border: "none"
2270
2386
  },
2271
- "& .cm-tooltip-below": {},
2387
+ ".cm-tooltip-below": {},
2272
2388
  //
2273
2389
  // autocomplete
2274
2390
  //
2275
- "& .cm-tooltip-autocomplete": {
2391
+ ".cm-tooltip-autocomplete": {
2276
2392
  marginTop: "4px",
2277
2393
  marginLeft: "-3px"
2278
2394
  },
2279
- "& .cm-tooltip-autocomplete ul li": {},
2280
- "& .cm-tooltip-autocomplete ul li[aria-selected]": {},
2281
- "& .cm-completionIcon": {
2395
+ ".cm-tooltip-autocomplete ul li": {},
2396
+ ".cm-tooltip-autocomplete ul li[aria-selected]": {},
2397
+ ".cm-completionIcon": {
2282
2398
  display: "none"
2283
2399
  },
2284
- "& .cm-completionLabel": {
2285
- fontFamily: get6(tokens, "fontFamily.body", []).join(",")
2400
+ ".cm-completionLabel": {
2401
+ fontFamily: get3(tokens, "fontFamily.body", []).join(",")
2286
2402
  },
2287
- "& .cm-completionMatchedText": {
2403
+ ".cm-completionMatchedText": {
2288
2404
  textDecoration: "none"
2289
2405
  },
2290
2406
  //
2291
2407
  // widgets
2292
2408
  //
2293
- "& .cm-widgetBuffer": {
2409
+ ".cm-widgetBuffer": {
2294
2410
  display: "none",
2295
2411
  height: 0
2296
2412
  },
2297
2413
  //
2298
2414
  // table
2299
2415
  //
2300
- "& .cm-table *": {
2301
- fontFamily: `${get6(tokens, "fontFamily.mono", []).join(",")} !important`,
2416
+ ".cm-table *": {
2417
+ fontFamily: `${get3(tokens, "fontFamily.mono", []).join(",")} !important`,
2302
2418
  textDecoration: "none !important"
2303
2419
  },
2304
- "& .cm-table-head": {
2420
+ ".cm-table-head": {
2305
2421
  padding: "2px 16px 2px 0px",
2306
- borderBottom: `1px solid ${get6(tokens, "extend.colors.neutral.500")}`,
2422
+ borderBottom: `1px solid ${get3(tokens, "extend.colors.neutral.500")}`,
2307
2423
  fontWeight: 100,
2308
2424
  textAlign: "left",
2309
- color: get6(tokens, "extend.colors.neutral.500")
2425
+ color: get3(tokens, "extend.colors.neutral.500")
2310
2426
  },
2311
- "& .cm-table-cell": {
2427
+ ".cm-table-cell": {
2312
2428
  padding: "2px 16px 2px 0px"
2313
2429
  },
2314
2430
  //
2315
2431
  // image
2316
2432
  //
2317
- "& .cm-image": {
2318
- margin: "0.5rem 0"
2433
+ ".cm-image": {
2434
+ display: "block",
2435
+ height: "0"
2436
+ },
2437
+ ".cm-image.cm-loaded-image": {
2438
+ height: "auto",
2439
+ borderTop: "0.5rem solid transparent",
2440
+ borderBottom: "0.5rem solid transparent"
2319
2441
  },
2320
2442
  //
2321
2443
  // font size
2322
2444
  // 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
2445
  //
2324
- ...Object.keys(get6(tokens, "extend.fontSize", {})).reduce((acc, fontSize) => {
2325
- const height = get6(tokens, [
2446
+ ...Object.keys(get3(tokens, "extend.fontSize", {})).reduce((acc, fontSize) => {
2447
+ const height = get3(tokens, [
2326
2448
  "extend",
2327
2449
  "fontSize",
2328
2450
  fontSize,
@@ -2356,51 +2478,51 @@ var defaultTheme = {
2356
2478
  * </div>
2357
2479
  * </div
2358
2480
  */
2359
- "& .cm-panels": {
2360
- border: `1px solid ${get6(tokens, "extend.colors.neutral.200")}`
2481
+ ".cm-panels": {
2482
+ border: `1px solid ${get3(tokens, "extend.colors.neutral.200")}`
2361
2483
  },
2362
- "& .cm-panel": {
2363
- background: get6(tokens, "extend.colors.neutral.50"),
2364
- fontFamily: get6(tokens, "fontFamily.body", []).join(",")
2484
+ ".cm-panel": {
2485
+ background: get3(tokens, "extend.colors.neutral.50"),
2486
+ fontFamily: get3(tokens, "fontFamily.body", []).join(",")
2365
2487
  },
2366
- "& .cm-button": {
2488
+ ".cm-button": {
2367
2489
  margin: "4px",
2368
- fontFamily: get6(tokens, "fontFamily.body", []).join(","),
2369
- background: get6(tokens, "extend.colors.neutral.100"),
2490
+ fontFamily: get3(tokens, "fontFamily.body", []).join(","),
2491
+ background: get3(tokens, "extend.colors.neutral.100"),
2370
2492
  backgroundImage: "none",
2371
2493
  border: "none",
2372
2494
  "&:hover": {
2373
- background: get6(tokens, "extend.colors.neutral.200")
2495
+ background: get3(tokens, "extend.colors.neutral.200")
2374
2496
  },
2375
2497
  "&:active": {
2376
- background: get6(tokens, "extend.colors.neutral.300"),
2498
+ background: get3(tokens, "extend.colors.neutral.300"),
2377
2499
  backgroundImage: "none"
2378
2500
  }
2379
2501
  },
2380
- "& .cm-panel input[type=checkbox]": {
2502
+ ".cm-panel input[type=checkbox]": {
2381
2503
  marginRight: "0.4rem !important"
2382
2504
  }
2383
2505
  };
2384
2506
  var textTheme = {
2385
- "& .cm-scroller": {
2386
- fontFamily: get6(tokens, "fontFamily.body", []).join(",")
2507
+ ".cm-scroller": {
2508
+ fontFamily: get3(tokens, "fontFamily.body", []).join(",")
2387
2509
  },
2388
- "& .cm-placeholder": {
2389
- fontFamily: get6(tokens, "fontFamily.body", []).join(",")
2510
+ ".cm-placeholder": {
2511
+ fontFamily: get3(tokens, "fontFamily.body", []).join(",")
2390
2512
  }
2391
2513
  };
2392
2514
  var markdownTheme = {
2393
2515
  // 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(",")
2516
+ ".cm-placeholder": {
2517
+ fontFamily: get3(tokens, "fontFamily.body", []).join(",")
2396
2518
  }
2397
2519
  };
2398
2520
  var codeTheme = {
2399
- "& .cm-scroller": {
2400
- fontFamily: get6(tokens, "fontFamily.mono", []).join(",")
2521
+ ".cm-scroller": {
2522
+ fontFamily: get3(tokens, "fontFamily.mono", []).join(",")
2401
2523
  },
2402
- "& .cm-placeholder": {
2403
- fontFamily: get6(tokens, "fontFamily.mono", []).join(",")
2524
+ ".cm-placeholder": {
2525
+ fontFamily: get3(tokens, "fontFamily.mono", []).join(",")
2404
2526
  }
2405
2527
  };
2406
2528
 
@@ -2409,26 +2531,28 @@ var EditorModes = [
2409
2531
  "default",
2410
2532
  "vim"
2411
2533
  ];
2412
- var BaseTextEditor = /* @__PURE__ */ forwardRef(({ model, readonly, comments: comments2, extensions = [], editorMode, slots = defaultSlots }, forwardedRef) => {
2413
- const { themeMode } = useThemeContext();
2534
+ var BaseTextEditor = /* @__PURE__ */ forwardRef(({ model, focus, selection, readonly, comments: comments2, extensions = [], editorMode, slots = defaultSlots }, forwardedRef) => {
2414
2535
  const tabsterDOMAttribute = useFocusableGroup({
2415
2536
  tabBehavior: "limited"
2416
2537
  });
2417
- const [root, setRoot] = useState2(null);
2418
- const [{ state = void 0, view = void 0 } = {}, setEditor] = useState2();
2419
- useImperativeHandle(forwardedRef, () => ({
2420
- root,
2421
- state,
2538
+ const { themeMode } = useThemeContext();
2539
+ const rootRef = useRef(null);
2540
+ const [view, setView] = useState(null);
2541
+ useImperativeHandle(forwardedRef, () => view, [
2422
2542
  view
2423
- }), [
2543
+ ]);
2544
+ useEffect(() => {
2545
+ if (view && focus) {
2546
+ view.focus();
2547
+ }
2548
+ }, [
2424
2549
  view,
2425
- state,
2426
- root
2550
+ focus
2427
2551
  ]);
2428
- const { awareness, peer } = model;
2429
- useEffect2(() => {
2430
- if (awareness && peer) {
2431
- awareness.setLocalStateField("user", {
2552
+ const { awareness: awareness2, peer } = model;
2553
+ useEffect(() => {
2554
+ if (awareness2 && peer) {
2555
+ awareness2.setLocalStateField("user", {
2432
2556
  name: peer.name ?? generateName(peer.id),
2433
2557
  color: getColorForValue({
2434
2558
  value: peer.id,
@@ -2442,11 +2566,11 @@ var BaseTextEditor = /* @__PURE__ */ forwardRef(({ model, readonly, comments: co
2442
2566
  });
2443
2567
  }
2444
2568
  }, [
2445
- awareness,
2569
+ awareness2,
2446
2570
  peer,
2447
2571
  themeMode
2448
2572
  ]);
2449
- useEffect2(() => {
2573
+ useEffect(() => {
2450
2574
  if (view && comments2?.length) {
2451
2575
  view.dispatch({
2452
2576
  effects: setCommentRange.of({
@@ -2459,12 +2583,13 @@ var BaseTextEditor = /* @__PURE__ */ forwardRef(({ model, readonly, comments: co
2459
2583
  view,
2460
2584
  comments2
2461
2585
  ]);
2462
- useEffect2(() => {
2463
- if (!root) {
2586
+ useEffect(() => {
2587
+ if (!model || !rootRef.current) {
2464
2588
  return;
2465
2589
  }
2466
- const state2 = EditorState2.create({
2590
+ const state = EditorState2.create({
2467
2591
  doc: model.text(),
2592
+ selection,
2468
2593
  extensions: [
2469
2594
  readonly && EditorState2.readOnly.of(readonly),
2470
2595
  // TODO(burdon): Factor out VIM mode? (manage via MarkdownPlugin).
@@ -2481,19 +2606,17 @@ var BaseTextEditor = /* @__PURE__ */ forwardRef(({ model, readonly, comments: co
2481
2606
  ].filter(Boolean)
2482
2607
  });
2483
2608
  view?.destroy();
2484
- setEditor({
2485
- state: state2,
2486
- view: new EditorView12({
2487
- state: state2,
2488
- parent: root
2489
- })
2609
+ const newView = new EditorView12({
2610
+ parent: rootRef.current,
2611
+ state
2490
2612
  });
2613
+ setView(newView);
2491
2614
  return () => {
2492
- view?.destroy();
2493
- setEditor(void 0);
2615
+ newView?.destroy();
2616
+ setView(null);
2494
2617
  };
2495
2618
  }, [
2496
- root,
2619
+ rootRef,
2497
2620
  model,
2498
2621
  readonly,
2499
2622
  editorMode,
@@ -2502,12 +2625,8 @@ var BaseTextEditor = /* @__PURE__ */ forwardRef(({ model, readonly, comments: co
2502
2625
  const handleKeyUp = useCallback((event) => {
2503
2626
  const { key, altKey, shiftKey, metaKey, ctrlKey } = event;
2504
2627
  switch (key) {
2505
- case "Enter": {
2506
- view?.contentDOM.focus();
2507
- break;
2508
- }
2509
2628
  case "Escape": {
2510
- editorMode === "vim" && (altKey || shiftKey || metaKey || ctrlKey) && root?.focus();
2629
+ editorMode === "vim" && (altKey || shiftKey || metaKey || ctrlKey) && rootRef.current?.focus();
2511
2630
  break;
2512
2631
  }
2513
2632
  }
@@ -2517,16 +2636,16 @@ var BaseTextEditor = /* @__PURE__ */ forwardRef(({ model, readonly, comments: co
2517
2636
  ]);
2518
2637
  return /* @__PURE__ */ React.createElement("div", {
2519
2638
  key: model.id,
2520
- ref: setRoot,
2639
+ ref: rootRef,
2521
2640
  tabIndex: 0,
2522
2641
  ...slots?.root,
2523
2642
  ...editorMode !== "vim" && tabsterDOMAttribute,
2524
2643
  onKeyUp: handleKeyUp
2525
2644
  });
2526
2645
  });
2527
- var TextEditor = /* @__PURE__ */ forwardRef(({ readonly, extensions = [], slots: _slots, ...props }, forwardedRef) => {
2646
+ var TextEditor = /* @__PURE__ */ forwardRef(({ readonly, extensions = [], slots, ...props }, forwardedRef) => {
2528
2647
  const { themeMode } = useThemeContext();
2529
- const slots = defaultsDeep2({}, _slots, defaultTextSlots);
2648
+ const updatedSlots = defaultsDeep2({}, slots, defaultTextSlots);
2530
2649
  return /* @__PURE__ */ React.createElement(BaseTextEditor, {
2531
2650
  ref: forwardedRef,
2532
2651
  readonly,
@@ -2534,17 +2653,17 @@ var TextEditor = /* @__PURE__ */ forwardRef(({ readonly, extensions = [], slots:
2534
2653
  basicBundle({
2535
2654
  readonly,
2536
2655
  themeMode,
2537
- placeholder: slots?.editor?.placeholder
2656
+ placeholder: updatedSlots?.editor?.placeholder
2538
2657
  }),
2539
2658
  ...extensions
2540
2659
  ],
2541
- slots,
2660
+ slots: updatedSlots,
2542
2661
  ...props
2543
2662
  });
2544
2663
  });
2545
- var MarkdownEditor = /* @__PURE__ */ forwardRef(({ readonly, extensions = [], slots: _slots, ...props }, forwardedRef) => {
2664
+ var MarkdownEditor = /* @__PURE__ */ forwardRef(({ readonly, extensions = [], slots, ...props }, forwardedRef) => {
2546
2665
  const { themeMode } = useThemeContext();
2547
- const slots = defaultsDeep2({}, _slots, defaultMarkdownSlots);
2666
+ const updatedSlots = defaultsDeep2({}, slots, defaultMarkdownSlots);
2548
2667
  return /* @__PURE__ */ React.createElement(BaseTextEditor, {
2549
2668
  ref: forwardedRef,
2550
2669
  readonly,
@@ -2552,11 +2671,11 @@ var MarkdownEditor = /* @__PURE__ */ forwardRef(({ readonly, extensions = [], sl
2552
2671
  markdownBundle({
2553
2672
  readonly,
2554
2673
  themeMode,
2555
- placeholder: slots?.editor?.placeholder
2674
+ placeholder: updatedSlots?.editor?.placeholder
2556
2675
  }),
2557
2676
  ...extensions
2558
2677
  ],
2559
- slots,
2678
+ slots: updatedSlots,
2560
2679
  ...props
2561
2680
  });
2562
2681
  });
@@ -2577,28 +2696,379 @@ 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();
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,
3043
+ CursorConverter,
2582
3044
  Doc,
2583
3045
  EditorModes,
2584
3046
  MarkdownEditor,
3047
+ RemoteSelectionsDecorator,
2585
3048
  SpaceAwarenessProvider,
2586
3049
  TextEditor,
2587
3050
  TextKind,
3051
+ YAwarenessProvider,
2588
3052
  YText,
2589
3053
  YXmlFragment,
2590
3054
  autocomplete,
3055
+ automerge3 as automerge,
3056
+ awareness,
2591
3057
  basicBundle,
2592
3058
  blast,
3059
+ callbackWrapper,
2593
3060
  code2 as code,
2594
3061
  codeTheme,
2595
3062
  comments,
2596
- cursorColor,
3063
+ createAutomergeModel,
3064
+ createYjsModel,
3065
+ cursorConverter,
2597
3066
  defaultMarkdownSlots,
2598
3067
  defaultOptions,
2599
3068
  defaultSlots,
2600
3069
  defaultTextSlots,
2601
3070
  defaultTheme,
3071
+ getToken,
2602
3072
  hr,
2603
3073
  image,
2604
3074
  link,
@@ -2609,7 +3079,6 @@ export {
2609
3079
  markdownTagsExtensions,
2610
3080
  markdownTheme,
2611
3081
  mention,
2612
- mermaid,
2613
3082
  modelState,
2614
3083
  setCommentRange,
2615
3084
  setFocus,
@@ -2619,6 +3088,7 @@ export {
2619
3088
  tasklist,
2620
3089
  textTheme,
2621
3090
  typewriter,
2622
- useTextModel
3091
+ useTextModel,
3092
+ yjs
2623
3093
  };
2624
3094
  //# sourceMappingURL=index.mjs.map