@dxos/react-ui-editor 0.3.11-main.24b414e → 0.3.11-main.27967cf

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 (185) hide show
  1. package/dist/lib/browser/index.mjs +1676 -1068
  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 +13 -15
  5. package/dist/types/src/components/TextEditor/MarkdownEditor.stories.d.ts.map +1 -1
  6. package/dist/types/src/components/TextEditor/TextEditor.d.ts +14 -6
  7. package/dist/types/src/components/TextEditor/TextEditor.d.ts.map +1 -1
  8. package/dist/types/src/components/TextEditor/TextEditor.stories.d.ts +1 -1
  9. package/dist/types/src/components/TextEditor/automerge.stories.d.ts.map +1 -1
  10. package/dist/types/src/components/TextEditor/{yjs.stories.d.ts → hooks.stories.d.ts} +13 -2
  11. package/dist/types/src/components/TextEditor/hooks.stories.d.ts.map +1 -0
  12. package/dist/types/src/components/Toolbar/Toolbar.d.ts +25 -0
  13. package/dist/types/src/components/Toolbar/Toolbar.d.ts.map +1 -0
  14. package/dist/types/src/components/Toolbar/Toolbar.stories.d.ts +23 -0
  15. package/dist/types/src/components/Toolbar/Toolbar.stories.d.ts.map +1 -0
  16. package/dist/types/src/components/Toolbar/index.d.ts +2 -0
  17. package/dist/types/src/components/Toolbar/index.d.ts.map +1 -0
  18. package/dist/types/src/components/index.d.ts +1 -0
  19. package/dist/types/src/components/index.d.ts.map +1 -1
  20. package/dist/types/src/extensions/autocomplete.d.ts.map +1 -1
  21. package/dist/types/src/extensions/automerge/automerge.d.ts.map +1 -1
  22. package/dist/types/src/extensions/automerge/automerge.spec.d.ts +2 -0
  23. package/dist/types/src/extensions/automerge/automerge.spec.d.ts.map +1 -0
  24. package/dist/types/src/extensions/automerge/automerge.test.d.ts +2 -0
  25. package/dist/types/src/extensions/automerge/automerge.test.d.ts.map +1 -0
  26. package/dist/types/src/extensions/automerge/defs.d.ts +9 -11
  27. package/dist/types/src/extensions/automerge/defs.d.ts.map +1 -1
  28. package/dist/types/src/extensions/automerge/index.d.ts +0 -1
  29. package/dist/types/src/extensions/automerge/index.d.ts.map +1 -1
  30. package/dist/types/src/extensions/automerge/semaphore.d.ts +8 -12
  31. package/dist/types/src/extensions/automerge/semaphore.d.ts.map +1 -1
  32. package/dist/types/src/extensions/automerge/update-automerge.d.ts +2 -2
  33. package/dist/types/src/extensions/automerge/update-automerge.d.ts.map +1 -1
  34. package/dist/types/src/extensions/awareness.d.ts +2 -2
  35. package/dist/types/src/extensions/awareness.d.ts.map +1 -1
  36. package/dist/types/src/extensions/basic.d.ts +4 -5
  37. package/dist/types/src/extensions/basic.d.ts.map +1 -1
  38. package/dist/types/src/extensions/comments.d.ts +40 -19
  39. package/dist/types/src/extensions/comments.d.ts.map +1 -1
  40. package/dist/types/src/extensions/cursor.d.ts +3 -3
  41. package/dist/types/src/extensions/cursor.d.ts.map +1 -1
  42. package/dist/types/src/extensions/index.d.ts +1 -7
  43. package/dist/types/src/extensions/index.d.ts.map +1 -1
  44. package/dist/types/src/extensions/markdown/bundle.d.ts +3 -6
  45. package/dist/types/src/extensions/markdown/bundle.d.ts.map +1 -1
  46. package/dist/types/src/extensions/markdown/code.d.ts.map +1 -0
  47. package/dist/types/src/extensions/markdown/formatting.d.ts +13 -0
  48. package/dist/types/src/extensions/markdown/formatting.d.ts.map +1 -0
  49. package/dist/types/src/extensions/markdown/heading.d.ts +6 -0
  50. package/dist/types/src/extensions/markdown/heading.d.ts.map +1 -0
  51. package/dist/types/src/extensions/markdown/highlight.d.ts.map +1 -1
  52. package/dist/types/src/extensions/markdown/hr.d.ts.map +1 -0
  53. package/dist/types/src/extensions/markdown/image.d.ts.map +1 -0
  54. package/dist/types/src/extensions/markdown/index.d.ts +8 -0
  55. package/dist/types/src/extensions/markdown/index.d.ts.map +1 -1
  56. package/dist/types/src/extensions/markdown/link.d.ts.map +1 -0
  57. package/dist/types/src/extensions/markdown/table.d.ts.map +1 -0
  58. package/dist/types/src/extensions/markdown/tasklist.d.ts +3 -0
  59. package/dist/types/src/extensions/markdown/tasklist.d.ts.map +1 -0
  60. package/dist/types/src/extensions/mention.d.ts.map +1 -1
  61. package/dist/types/src/extensions/outliner.d.ts +4 -0
  62. package/dist/types/src/extensions/outliner.d.ts.map +1 -0
  63. package/dist/types/src/hooks/awareness-provider.d.ts +7 -4
  64. package/dist/types/src/hooks/awareness-provider.d.ts.map +1 -1
  65. package/dist/types/src/hooks/defs.d.ts +25 -0
  66. package/dist/types/src/hooks/defs.d.ts.map +1 -0
  67. package/dist/types/src/hooks/index.d.ts +4 -2
  68. package/dist/types/src/hooks/index.d.ts.map +1 -1
  69. package/dist/types/src/hooks/useActionHandler.d.ts +4 -0
  70. package/dist/types/src/hooks/useActionHandler.d.ts.map +1 -0
  71. package/dist/types/src/hooks/useEditorView.d.ts +17 -0
  72. package/dist/types/src/hooks/useEditorView.d.ts.map +1 -0
  73. package/dist/types/src/hooks/useTextEditor.d.ts +39 -0
  74. package/dist/types/src/hooks/useTextEditor.d.ts.map +1 -0
  75. package/dist/types/src/hooks/useTextModel.d.ts +14 -27
  76. package/dist/types/src/hooks/useTextModel.d.ts.map +1 -1
  77. package/dist/types/src/index.d.ts +1 -1
  78. package/dist/types/src/index.d.ts.map +1 -1
  79. package/dist/types/src/styles/markdown.d.ts +2 -2
  80. package/dist/types/src/styles/markdown.d.ts.map +1 -1
  81. package/dist/types/src/themes/default.d.ts.map +1 -1
  82. package/dist/types/src/util.d.ts +2 -0
  83. package/dist/types/src/util.d.ts.map +1 -1
  84. package/package.json +47 -37
  85. package/src/components/TextEditor/MarkdownEditor.stories.tsx +74 -83
  86. package/src/components/TextEditor/TextEditor.tsx +111 -75
  87. package/src/components/TextEditor/automerge.stories.tsx +1 -2
  88. package/src/components/TextEditor/hooks.stories.tsx +106 -0
  89. package/src/components/Toolbar/Toolbar.stories.tsx +90 -0
  90. package/src/components/Toolbar/Toolbar.tsx +166 -0
  91. package/src/components/Toolbar/index.ts +5 -0
  92. package/src/components/index.ts +1 -0
  93. package/src/extensions/autocomplete.ts +6 -3
  94. package/src/extensions/automerge/automerge.spec.tsx +76 -0
  95. package/src/extensions/automerge/automerge.test.ts +13 -0
  96. package/src/extensions/automerge/automerge.ts +54 -45
  97. package/src/extensions/automerge/cursor.ts +3 -3
  98. package/src/extensions/automerge/defs.ts +13 -34
  99. package/src/extensions/automerge/index.ts +0 -1
  100. package/src/extensions/automerge/semaphore.ts +33 -32
  101. package/src/extensions/automerge/update-automerge.ts +14 -8
  102. package/src/extensions/automerge/update-codemirror.ts +5 -5
  103. package/src/extensions/awareness.ts +22 -18
  104. package/src/extensions/basic.ts +17 -10
  105. package/src/extensions/blast.ts +4 -1
  106. package/src/extensions/comments.ts +328 -167
  107. package/src/extensions/cursor.ts +7 -3
  108. package/src/extensions/index.ts +1 -7
  109. package/src/extensions/markdown/bundle.ts +23 -28
  110. package/src/extensions/markdown/code.ts +150 -0
  111. package/src/extensions/markdown/formatting.ts +188 -0
  112. package/src/extensions/markdown/heading.ts +59 -0
  113. package/src/extensions/markdown/highlight.ts +9 -15
  114. package/src/extensions/markdown/hr.ts +71 -0
  115. package/src/extensions/markdown/index.ts +8 -0
  116. package/src/extensions/{link.ts → markdown/link.ts} +16 -7
  117. package/src/extensions/{tasklist.ts → markdown/tasklist.ts} +48 -33
  118. package/src/extensions/mention.ts +9 -2
  119. package/src/extensions/outliner.ts +12 -0
  120. package/src/hooks/awareness-provider.ts +24 -20
  121. package/src/hooks/defs.ts +42 -0
  122. package/src/hooks/index.ts +5 -2
  123. package/src/hooks/useActionHandler.ts +62 -0
  124. package/src/hooks/useEditorView.ts +29 -0
  125. package/src/hooks/useTextEditor.ts +153 -0
  126. package/src/hooks/useTextModel.ts +66 -56
  127. package/src/index.ts +1 -1
  128. package/src/styles/markdown.ts +9 -10
  129. package/src/themes/default.ts +11 -8
  130. package/src/util.ts +26 -3
  131. package/dist/types/src/components/TextEditor/codemirror.stories.d.ts +0 -12
  132. package/dist/types/src/components/TextEditor/codemirror.stories.d.ts.map +0 -1
  133. package/dist/types/src/components/TextEditor/comments.stories.d.ts +0 -26
  134. package/dist/types/src/components/TextEditor/comments.stories.d.ts.map +0 -1
  135. package/dist/types/src/components/TextEditor/yjs.stories.d.ts.map +0 -1
  136. package/dist/types/src/extensions/code.d.ts.map +0 -1
  137. package/dist/types/src/extensions/hr.d.ts.map +0 -1
  138. package/dist/types/src/extensions/image.d.ts.map +0 -1
  139. package/dist/types/src/extensions/link.d.ts.map +0 -1
  140. package/dist/types/src/extensions/table.d.ts.map +0 -1
  141. package/dist/types/src/extensions/tasklist.d.ts +0 -7
  142. package/dist/types/src/extensions/tasklist.d.ts.map +0 -1
  143. package/dist/types/src/extensions/yjs/cursor.d.ts +0 -4
  144. package/dist/types/src/extensions/yjs/cursor.d.ts.map +0 -1
  145. package/dist/types/src/extensions/yjs/index.d.ts +0 -2
  146. package/dist/types/src/extensions/yjs/index.d.ts.map +0 -1
  147. package/dist/types/src/extensions/yjs/yjs.d.ts +0 -4
  148. package/dist/types/src/extensions/yjs/yjs.d.ts.map +0 -1
  149. package/dist/types/src/extensions/yjs/yjs.test.d.ts +0 -2
  150. package/dist/types/src/extensions/yjs/yjs.test.d.ts.map +0 -1
  151. package/dist/types/src/hooks/automerge.d.ts +0 -3
  152. package/dist/types/src/hooks/automerge.d.ts.map +0 -1
  153. package/dist/types/src/hooks/yjs.d.ts +0 -27
  154. package/dist/types/src/hooks/yjs.d.ts.map +0 -1
  155. package/dist/types/src/testing/index.d.ts +0 -3
  156. package/dist/types/src/testing/index.d.ts.map +0 -1
  157. package/dist/types/src/testing/proto/gen/schema.d.ts +0 -15
  158. package/dist/types/src/testing/proto/gen/schema.d.ts.map +0 -1
  159. package/dist/types/src/testing/proto/index.d.ts +0 -2
  160. package/dist/types/src/testing/proto/index.d.ts.map +0 -1
  161. package/dist/types/src/testing/replicator.d.ts +0 -45
  162. package/dist/types/src/testing/replicator.d.ts.map +0 -1
  163. package/src/components/TextEditor/codemirror.stories.ts +0 -115
  164. package/src/components/TextEditor/comments.stories.tsx +0 -315
  165. package/src/components/TextEditor/yjs.stories.tsx +0 -56
  166. package/src/extensions/code.ts +0 -106
  167. package/src/extensions/hr.ts +0 -73
  168. package/src/extensions/yjs/cursor.ts +0 -22
  169. package/src/extensions/yjs/index.ts +0 -5
  170. package/src/extensions/yjs/yjs.test.ts +0 -35
  171. package/src/extensions/yjs/yjs.ts +0 -16
  172. package/src/hooks/automerge.ts +0 -52
  173. package/src/hooks/yjs.ts +0 -156
  174. package/src/testing/index.ts +0 -6
  175. package/src/testing/proto/gen/schema.ts +0 -49
  176. package/src/testing/proto/index.ts +0 -5
  177. package/src/testing/proto/schema.proto +0 -15
  178. package/src/testing/replicator.ts +0 -184
  179. /package/dist/types/src/extensions/{code.d.ts → markdown/code.d.ts} +0 -0
  180. /package/dist/types/src/extensions/{hr.d.ts → markdown/hr.d.ts} +0 -0
  181. /package/dist/types/src/extensions/{image.d.ts → markdown/image.d.ts} +0 -0
  182. /package/dist/types/src/extensions/{link.d.ts → markdown/link.d.ts} +0 -0
  183. /package/dist/types/src/extensions/{table.d.ts → markdown/table.d.ts} +0 -0
  184. /package/src/extensions/{image.ts → markdown/image.ts} +0 -0
  185. /package/src/extensions/{table.ts → markdown/table.ts} +0 -0
@@ -1,20 +1,21 @@
1
1
  // packages/ui/react-ui-editor/src/index.ts
2
2
  import { TextKind } from "@dxos/protocols/proto/dxos/echo/model/text";
3
3
  import { Doc, YText, YXmlFragment } from "@dxos/text-model";
4
+ import { keymap as keymap7 } from "@codemirror/view";
4
5
 
5
6
  // packages/ui/react-ui-editor/src/components/TextEditor/index.ts
6
7
  import { tags as tags2 } from "@lezer/highlight";
7
8
 
8
9
  // packages/ui/react-ui-editor/src/components/TextEditor/TextEditor.tsx
9
10
  import { EditorState as EditorState2 } from "@codemirror/state";
10
- import { EditorView as EditorView12 } from "@codemirror/view";
11
- import { useFocusableGroup } from "@fluentui/react-tabster";
11
+ import { EditorView as EditorView13 } from "@codemirror/view";
12
12
  import { vim } from "@replit/codemirror-vim";
13
13
  import defaultsDeep2 from "lodash.defaultsdeep";
14
- import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useState, useRef } from "react";
15
- import { generateName } from "@dxos/display-name";
14
+ import React, { forwardRef, useCallback, useEffect as useEffect2, useImperativeHandle, useRef, useState } from "react";
15
+ import { log as log2 } from "@dxos/log";
16
16
  import { useThemeContext } from "@dxos/react-ui";
17
- import { getColorForValue, inputSurface, mx as mx3 } from "@dxos/react-ui-theme";
17
+ import { focusRing, mx as mx3 } from "@dxos/react-ui-theme";
18
+ import { isNotFalsy as isNotFalsy3 } from "@dxos/util";
18
19
 
19
20
  // packages/ui/react-ui-editor/src/extensions/autocomplete.ts
20
21
  import { autocompletion, completionKeymap } from "@codemirror/autocomplete";
@@ -29,9 +30,11 @@ var autocomplete = ({ onSearch }) => {
29
30
  // https://codemirror.net/examples/autocompletion
30
31
  // https://codemirror.net/docs/ref/#autocomplete.autocompletion
31
32
  autocompletion({
32
- defaultKeymap: false,
33
- // Don't start unless key press.
34
- activateOnTyping: false
33
+ activateOnTyping: true,
34
+ // closeOnBlur: false,
35
+ // defaultKeymap: false,
36
+ // TODO(burdon): Styles/fragments.
37
+ tooltipClass: () => "shadow rounded"
35
38
  }),
36
39
  // TODO(burdon): Option to create new page?
37
40
  // TODO(burdon): Optional decoration via addToOptions
@@ -51,13 +54,14 @@ var autocomplete = ({ onSearch }) => {
51
54
  };
52
55
 
53
56
  // 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";
57
+ import { invertedEffects } from "@codemirror/commands";
58
+ import { StateField } from "@codemirror/state";
59
+ import { EditorView, ViewPlugin } from "@codemirror/view";
60
+ import { next as A4 } from "@dxos/automerge/automerge";
57
61
 
58
62
  // packages/ui/react-ui-editor/src/extensions/automerge/cursor.ts
59
63
  import get from "lodash.get";
60
- import { next as automerge } from "@dxos/automerge/automerge";
64
+ import { next as A } from "@dxos/automerge/automerge";
61
65
  var cursorConverter = (handle, path) => ({
62
66
  // TODO(burdon): Handle assoc to associate with a previous character.
63
67
  toCursor: (pos) => {
@@ -69,7 +73,7 @@ var cursorConverter = (handle, path) => ({
69
73
  if (typeof value === "string" && value.length <= pos) {
70
74
  return "end";
71
75
  }
72
- return automerge.getCursor(doc, path.slice(), pos);
76
+ return A.getCursor(doc, path.slice(), pos);
73
77
  },
74
78
  fromCursor: (cursor) => {
75
79
  if (cursor === "") {
@@ -87,26 +91,28 @@ var cursorConverter = (handle, path) => ({
87
91
  return 0;
88
92
  }
89
93
  }
90
- return automerge.getCursorPosition(doc, path.slice(), cursor);
94
+ return A.getCursorPosition(doc, path.slice(), cursor);
91
95
  }
92
96
  });
93
97
 
94
98
  // packages/ui/react-ui-editor/src/extensions/automerge/defs.ts
95
99
  import { Annotation, StateEffect } from "@codemirror/state";
96
- var effectType = StateEffect.define({});
97
- var updateHeads = (newHeads) => effectType.of({
100
+ var getPath = (state, field) => state.field(field).path;
101
+ var getLastHeads = (state, field) => state.field(field).lastHeads;
102
+ var updateHeadsEffect = StateEffect.define({});
103
+ var updateHeads = (newHeads) => updateHeadsEffect.of({
98
104
  newHeads
99
105
  });
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);
106
+ var reconcileAnnotation = Annotation.define();
107
+ var isReconcile = (tr) => {
108
+ return !!tr.annotation(reconcileAnnotation);
109
+ };
104
110
 
105
111
  // packages/ui/react-ui-editor/src/extensions/automerge/semaphore.ts
106
- import { next as automerge2 } from "@dxos/automerge/automerge";
112
+ import { next as A3 } from "@dxos/automerge/automerge";
107
113
 
108
114
  // packages/ui/react-ui-editor/src/extensions/automerge/update-automerge.ts
109
- import { next as am } from "@dxos/automerge/automerge";
115
+ import { next as A2 } from "@dxos/automerge/automerge";
110
116
  var updateAutomerge = (field, handle, transactions, state) => {
111
117
  const { lastHeads, path } = state.field(field);
112
118
  let hasChanges = false;
@@ -119,11 +125,19 @@ var updateAutomerge = (field, handle, transactions, state) => {
119
125
  return void 0;
120
126
  }
121
127
  const newHeads = handle.changeAt(lastHeads, (doc) => {
128
+ const invertedTransactions = [];
122
129
  for (const tr of transactions) {
123
- tr.changes.iterChanges((fromA, toA, _fromB, _toB, inserted) => {
124
- am.splice(doc, path, fromA, toA - fromA, inserted.toString());
130
+ tr.changes.iterChanges((fromA, toA, _fromB, _toB, insert) => {
131
+ invertedTransactions.push({
132
+ from: fromA,
133
+ del: toA - fromA,
134
+ insert
135
+ });
125
136
  });
126
137
  }
138
+ invertedTransactions.reverse().forEach(({ from, del, insert }) => {
139
+ A2.splice(doc, path.slice(), from, del, insert.toString());
140
+ });
127
141
  });
128
142
  return newHeads ?? void 0;
129
143
  };
@@ -138,13 +152,13 @@ var updateCodeMirror = (view, selection, target, patches) => {
138
152
  selection = selection.map(changeSet, 1);
139
153
  view.dispatch({
140
154
  changes: changeSet,
141
- annotations: reconcileAnnotationType.of({})
155
+ annotations: reconcileAnnotation.of(false)
142
156
  });
143
157
  }
144
158
  }
145
159
  view.dispatch({
146
160
  selection,
147
- annotations: reconcileAnnotationType.of({})
161
+ annotations: reconcileAnnotation.of(false)
148
162
  });
149
163
  };
150
164
  var handlePatch = (patch, target, state) => {
@@ -165,7 +179,7 @@ var handleInsert = (target, patch) => {
165
179
  if (index == null) {
166
180
  return [];
167
181
  }
168
- const text = patch.values.map((v) => v ? v.toString() : "").join("");
182
+ const text = patch.values.map((value) => value ? value.toString() : "").join("");
169
183
  return [
170
184
  {
171
185
  from: index,
@@ -237,40 +251,43 @@ var charPath = (textPath, candidatePath) => {
237
251
 
238
252
  // packages/ui/react-ui-editor/src/extensions/automerge/semaphore.ts
239
253
  var PatchSemaphore = class {
240
- constructor(_field) {
241
- this._field = _field;
254
+ // prettier-ignore
255
+ constructor(_handle, _state) {
256
+ this._handle = _handle;
257
+ this._state = _state;
242
258
  this._inReconcile = false;
243
- this._queue = [];
244
- this.reconcile = (handle, view) => {
245
- if (this._inReconcile) {
246
- return;
247
- }
259
+ }
260
+ reconcile(view) {
261
+ if (!this._inReconcile) {
248
262
  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);
263
+ this.doReconcile(view);
264
+ this._inReconcile = false;
265
+ }
266
+ }
267
+ doReconcile(view) {
268
+ const path = getPath(view.state, this._state);
269
+ const oldHeads = getLastHeads(view.state, this._state);
270
+ let selection = view.state.selection;
271
+ const transactions = view.state.field(this._state).unreconciledTransactions.filter((tx) => !isReconcile(tx));
272
+ const toInvert = transactions.slice().reverse();
273
+ for (const tr of toInvert) {
274
+ const inverted = tr.changes.invert(tr.startState.doc);
275
+ selection = selection.map(inverted);
268
276
  view.dispatch({
269
- effects: updateHeads(newHeads),
270
- annotations: reconcileAnnotationType.of({})
277
+ changes: inverted,
278
+ annotations: reconcileAnnotation.of(true)
271
279
  });
272
- this._inReconcile = false;
273
- };
280
+ }
281
+ let newHeads = updateAutomerge(this._state, this._handle, transactions, view.state);
282
+ if (newHeads === null || newHeads === void 0) {
283
+ newHeads = A3.getHeads(this._handle.docSync());
284
+ }
285
+ const diff = A3.equals(oldHeads, newHeads) ? [] : A3.diff(this._handle.docSync(), oldHeads, newHeads);
286
+ updateCodeMirror(view, selection, path, diff);
287
+ view.dispatch({
288
+ effects: updateHeads(newHeads),
289
+ annotations: reconcileAnnotation.of(false)
290
+ });
274
291
  }
275
292
  };
276
293
 
@@ -280,16 +297,17 @@ var defaultCursorConverter = {
280
297
  toCursor: (position) => position.toString(),
281
298
  fromCursor: (cursor) => parseInt(cursor)
282
299
  };
283
- var Cursor = class {
300
+ var Cursor = class _Cursor {
284
301
  static {
285
302
  this.converter = Facet.define({
286
303
  combine: (providers) => providers[0] ?? defaultCursorConverter
287
304
  });
288
305
  }
289
306
  static {
290
- this.getCursorFromRange = (cursorConverter3, range) => {
291
- const from = cursorConverter3.toCursor(range.from);
292
- const to = cursorConverter3.toCursor(range.to, -1);
307
+ this.getCursorFromRange = (state, range) => {
308
+ const cursorConverter2 = state.facet(_Cursor.converter);
309
+ const from = cursorConverter2.toCursor(range.from);
310
+ const to = cursorConverter2.toCursor(range.to, -1);
293
311
  return [
294
312
  from,
295
313
  to
@@ -297,10 +315,11 @@ var Cursor = class {
297
315
  };
298
316
  }
299
317
  static {
300
- this.getRangeFromCursor = (cursorConverter3, cursor) => {
318
+ this.getRangeFromCursor = (state, cursor) => {
319
+ const cursorConverter2 = state.facet(_Cursor.converter);
301
320
  const parts = cursor.split(":");
302
- const from = cursorConverter3.fromCursor(parts[0]);
303
- const to = cursorConverter3.fromCursor(parts[1]);
321
+ const from = cursorConverter2.fromCursor(parts[0]);
322
+ const to = cursorConverter2.fromCursor(parts[1]);
304
323
  return from !== void 0 && to !== void 0 ? {
305
324
  from,
306
325
  to
@@ -310,25 +329,22 @@ var Cursor = class {
310
329
  };
311
330
 
312
331
  // packages/ui/react-ui-editor/src/extensions/automerge/automerge.ts
313
- var semaphoreFacet = Facet2.define({
314
- combine: (values) => values.at(-1)
315
- });
316
- var automerge3 = ({ handle, path }) => {
317
- const stateField = StateField.define({
332
+ var automerge = ({ handle, path }) => {
333
+ const syncState = StateField.define({
318
334
  create: () => ({
319
- lastHeads: A.getHeads(handle.docSync()),
320
- unreconciledTransactions: [],
321
- path: path.slice()
335
+ path: path.slice(),
336
+ lastHeads: A4.getHeads(handle.docSync()),
337
+ unreconciledTransactions: []
322
338
  }),
323
339
  update: (value, tr) => {
324
340
  const result = {
341
+ path: path.slice(),
325
342
  lastHeads: value.lastHeads,
326
- unreconciledTransactions: value.unreconciledTransactions.slice(),
327
- path: path.slice()
343
+ unreconciledTransactions: value.unreconciledTransactions.slice()
328
344
  };
329
345
  let clearUnreconciled = false;
330
346
  for (const effect of tr.effects) {
331
- if (effect.is(effectType)) {
347
+ if (effect.is(updateHeadsEffect)) {
332
348
  result.lastHeads = effect.value.newHeads;
333
349
  clearUnreconciled = true;
334
350
  }
@@ -336,46 +352,53 @@ var automerge3 = ({ handle, path }) => {
336
352
  if (clearUnreconciled) {
337
353
  result.unreconciledTransactions = [];
338
354
  } else {
339
- if (!isReconcileTx(tr)) {
355
+ if (!isReconcile(tr)) {
340
356
  result.unreconciledTransactions.push(tr);
341
357
  }
342
358
  }
343
359
  return result;
344
360
  }
345
361
  });
346
- const semaphore = new PatchSemaphore(stateField);
347
- const viewPlugin = ViewPlugin.fromClass(class AutomergeCodemirrorViewPlugin {
348
- constructor(_view) {
349
- this._view = _view;
350
- this._handleChange = () => {
351
- this._view.state.facet(semaphoreFacet).reconcile(handle, this._view);
352
- };
353
- handle.addListener("change", this._handleChange);
354
- }
355
- update(update2) {
356
- if (update2.transactions.length > 0 && update2.transactions.some((tr) => !isReconcileTx(tr))) {
357
- queueMicrotask(() => {
358
- this._view.state.facet(semaphoreFacet).reconcile(handle, this._view);
362
+ const semaphore = new PatchSemaphore(handle, syncState);
363
+ return [
364
+ Cursor.converter.of(cursorConverter(handle, path)),
365
+ syncState,
366
+ // Reconcile external updates.
367
+ ViewPlugin.fromClass(class {
368
+ constructor(_view) {
369
+ this._view = _view;
370
+ handle.addListener("change", this._handleChange.bind(this));
371
+ }
372
+ destroy() {
373
+ handle.removeListener("change", this._handleChange.bind(this));
374
+ }
375
+ _handleChange() {
376
+ semaphore.reconcile(this._view);
377
+ }
378
+ }),
379
+ // Reconcile local updates.
380
+ EditorView.updateListener.of(({ view, changes }) => {
381
+ if (!changes.empty) {
382
+ semaphore.reconcile(view);
383
+ }
384
+ }),
385
+ // TODO(burdon): Record undo transactions.
386
+ // See https://github.com/yjs/y-codemirror.next/tree/main
387
+ // https://codemirror.net/examples/inverted-effect
388
+ invertedEffects.of((tr) => {
389
+ const effects = [];
390
+ if (!tr.changes.empty) {
391
+ tr.changes.iterChanges((fromA, toA, fromB, toB, inserted) => {
359
392
  });
360
393
  }
361
- }
362
- destroy() {
363
- handle.addListener("change", this._handleChange);
364
- }
365
- });
366
- return {
367
- extension: [
368
- Cursor.converter.of(cursorConverter(handle, path)),
369
- semaphoreFacet.of(semaphore),
370
- stateField,
371
- viewPlugin
372
- ]
373
- };
394
+ return effects;
395
+ })
396
+ ];
374
397
  };
375
398
 
376
399
  // packages/ui/react-ui-editor/src/extensions/awareness.ts
377
- import { Annotation as Annotation2, Facet as Facet3, RangeSet } from "@codemirror/state";
378
- import { Decoration, EditorView, ViewPlugin as ViewPlugin2, WidgetType } from "@codemirror/view";
400
+ import { Annotation as Annotation2, Facet as Facet2, RangeSet } from "@codemirror/state";
401
+ import { Decoration, EditorView as EditorView2, ViewPlugin as ViewPlugin2, WidgetType } from "@codemirror/view";
379
402
  import { Event } from "@dxos/async";
380
403
  import { Context } from "@dxos/context";
381
404
  var dummyProvider = {
@@ -384,17 +407,17 @@ var dummyProvider = {
384
407
  },
385
408
  close: () => {
386
409
  },
410
+ getRemoteStates: () => [],
387
411
  update: () => {
388
- },
389
- getRemoteStates: () => []
412
+ }
390
413
  };
391
- var AwarenessProvider = Facet3.define({
414
+ var awarenessProvider = Facet2.define({
392
415
  combine: (providers) => providers[0] ?? dummyProvider
393
416
  });
394
417
  var RemoteSelectionChangedAnnotation = Annotation2.define();
395
418
  var awareness = (provider = dummyProvider) => {
396
419
  return [
397
- AwarenessProvider.of(provider),
420
+ awarenessProvider.of(provider),
398
421
  ViewPlugin2.fromClass(RemoteSelectionsDecorator, {
399
422
  decorations: (value) => value.decorations
400
423
  }),
@@ -408,7 +431,7 @@ var RemoteSelectionsDecorator = class {
408
431
  this._lastAnchor = void 0;
409
432
  this._lastHead = void 0;
410
433
  this._cursorConverter = view.state.facet(Cursor.converter);
411
- this._provider = view.state.facet(AwarenessProvider);
434
+ this._provider = view.state.facet(awarenessProvider);
412
435
  this._provider.open();
413
436
  this._provider.remoteStateChange.on(this._ctx, () => {
414
437
  view.dispatch({
@@ -549,7 +572,7 @@ var RemoteCaretWidget = class extends WidgetType {
549
572
  return true;
550
573
  }
551
574
  };
552
- var styles = EditorView.baseTheme({
575
+ var styles = EditorView2.baseTheme({
553
576
  ".cm-collab-selection": {},
554
577
  ".cm-collab-selectionLine": {
555
578
  padding: 0,
@@ -562,40 +585,42 @@ var styles = EditorView.baseTheme({
562
585
  marginLeft: "-1px",
563
586
  marginRight: "-1px",
564
587
  boxSizing: "border-box",
565
- display: "inline"
588
+ display: "inline",
589
+ cursor: "pointer"
566
590
  },
567
591
  ".cm-collab-selectionCaretDot": {
568
592
  borderRadius: "50%",
569
593
  position: "absolute",
570
- width: ".4em",
571
- height: ".4em",
572
- top: "-.2em",
573
- left: "-.2em",
594
+ width: ".5em",
595
+ height: ".5em",
596
+ top: "-.25em",
597
+ left: "-.25em",
574
598
  backgroundColor: "inherit",
575
599
  transition: "transform .3s ease-in-out",
576
600
  boxSizing: "border-box"
577
601
  },
578
602
  ".cm-collab-selectionCaret:hover > .cm-collab-selectionCaretDot": {
579
- transformOrigin: "bottom center",
580
- transform: "scale(0)"
603
+ transform: "scale(0)",
604
+ transformOrigin: "center"
581
605
  },
582
606
  ".cm-collab-selectionInfo": {
583
607
  position: "absolute",
584
- top: "-1.05em",
585
- left: "-1px",
608
+ transform: "translate(-50%, 0)",
609
+ top: "-20px",
610
+ left: 0,
586
611
  fontSize: ".75em",
587
- fontFamily: "serif",
612
+ fontFamily: "sans-serif",
588
613
  fontStyle: "normal",
589
614
  fontWeight: "normal",
590
615
  lineHeight: "normal",
591
616
  userSelect: "none",
592
617
  color: "white",
593
- paddingLeft: "2px",
594
- paddingRight: "2px",
618
+ padding: "2px",
595
619
  zIndex: 101,
596
620
  transition: "opacity .3s ease-in-out",
597
621
  backgroundColor: "inherit",
598
- // these should be separate
622
+ borderRadius: "2px",
623
+ // These should be separate.
599
624
  opacity: 0,
600
625
  transitionDelay: "0s",
601
626
  whiteSpace: "nowrap"
@@ -608,23 +633,26 @@ var styles = EditorView.baseTheme({
608
633
 
609
634
  // packages/ui/react-ui-editor/src/extensions/basic.ts
610
635
  import { closeBrackets } from "@codemirror/autocomplete";
636
+ import { history } from "@codemirror/commands";
611
637
  import { bracketMatching, defaultHighlightStyle, syntaxHighlighting } from "@codemirror/language";
612
638
  import { oneDarkHighlightStyle } from "@codemirror/theme-one-dark";
613
- import { drawSelection, EditorView as EditorView2, placeholder } from "@codemirror/view";
614
- var basicBundle = ({ readonly, themeMode, placeholder: _placeholder }) => [
615
- EditorView2.lineWrapping,
616
- // TODO(burdon): Compare with minimalSetup.
639
+ import { drawSelection, EditorView as EditorView3, highlightActiveLine, placeholder } from "@codemirror/view";
640
+ import { isNotFalsy } from "@dxos/util";
641
+ var createBasicBundle = ({ themeMode, placeholder: _placeholder, lineWrapping = true } = {}) => [
642
+ lineWrapping && EditorView3.lineWrapping,
617
643
  // https://codemirror.net/docs/ref/#codemirror.minimalSetup
618
644
  bracketMatching(),
619
645
  closeBrackets(),
620
646
  drawSelection(),
647
+ highlightActiveLine(),
648
+ history(),
621
649
  _placeholder && placeholder(_placeholder),
622
- // TODO(burdon): Is this required?
650
+ // https://github.com/codemirror/theme-one-dark
623
651
  themeMode === "dark" ? syntaxHighlighting(oneDarkHighlightStyle) : syntaxHighlighting(defaultHighlightStyle)
624
- ].filter(Boolean);
652
+ ].filter(isNotFalsy);
625
653
 
626
654
  // packages/ui/react-ui-editor/src/extensions/blast.ts
627
- import { EditorView as EditorView3, keymap as keymap2 } from "@codemirror/view";
655
+ import { EditorView as EditorView4, keymap as keymap2 } from "@codemirror/view";
628
656
  import defaultsDeep from "lodash.defaultsdeep";
629
657
  import { invariant } from "@dxos/invariant";
630
658
  var __dxlog_file = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/extensions/blast.ts";
@@ -660,10 +688,10 @@ var blast = (options = defaultOptions) => {
660
688
  const getPoint = (view, pos) => {
661
689
  const { left: x = 0, top: y = 0 } = view.coordsForChar(pos) ?? {};
662
690
  const element = document.elementFromPoint(x, y);
663
- const { offsetLeft: left = 0, offsetTop: top = 0 } = view.scrollDOM.parentElement ?? {};
691
+ const { offsetLeft: left = 0, offsetTop: top2 = 0 } = view.scrollDOM.parentElement ?? {};
664
692
  const point = {
665
693
  x: x - left,
666
- y: y - top
694
+ y: y - top2
667
695
  };
668
696
  return {
669
697
  element,
@@ -672,7 +700,7 @@ var blast = (options = defaultOptions) => {
672
700
  };
673
701
  return [
674
702
  // Cursor moved.
675
- EditorView3.updateListener.of((update2) => {
703
+ EditorView4.updateListener.of((update2) => {
676
704
  if (blaster?.node !== update2.view.scrollDOM) {
677
705
  if (blaster) {
678
706
  blaster.destroy();
@@ -755,7 +783,7 @@ var Blaster = class {
755
783
  initialize() {
756
784
  invariant(!this._canvas && !this._ctx, void 0, {
757
785
  F: __dxlog_file,
758
- L: 138,
786
+ L: 141,
759
787
  S: this,
760
788
  A: [
761
789
  "!this._canvas && !this._ctx",
@@ -792,7 +820,7 @@ var Blaster = class {
792
820
  start() {
793
821
  invariant(this._canvas && this._ctx, void 0, {
794
822
  F: __dxlog_file,
795
- L: 177,
823
+ L: 180,
796
824
  S: this,
797
825
  A: [
798
826
  "this._canvas && this._ctx",
@@ -933,9 +961,14 @@ var random = (min, max) => {
933
961
  return min + ~~(Math.random() * (max - min + 1));
934
962
  };
935
963
 
936
- // packages/ui/react-ui-editor/src/extensions/code.ts
937
- import { ViewPlugin as ViewPlugin3, EditorView as EditorView4, Decoration as Decoration2 } from "@codemirror/view";
938
- import { mx as mx2 } from "@dxos/react-ui-theme";
964
+ // packages/ui/react-ui-editor/src/extensions/comments.ts
965
+ import { invertedEffects as invertedEffects2 } from "@codemirror/commands";
966
+ import { Facet as Facet3, StateEffect as StateEffect2, StateField as StateField2 } from "@codemirror/state";
967
+ import { hoverTooltip, keymap as keymap3, Decoration as Decoration2, EditorView as EditorView5 } from "@codemirror/view";
968
+ import sortBy from "lodash.sortby";
969
+ import { useEffect } from "react";
970
+ import { debounce } from "@dxos/async";
971
+ import { nonNullable } from "@dxos/util";
939
972
 
940
973
  // packages/ui/react-ui-editor/src/styles/cursors.ts
941
974
  import * as random2 from "lib0/random";
@@ -978,34 +1011,15 @@ var cursorColor = cursorColors[random2.uint32() % cursorColors.length];
978
1011
  // packages/ui/react-ui-editor/src/styles/markdown.ts
979
1012
  import { mx } from "@dxos/react-ui-theme";
980
1013
  var headings = {
981
- 1: [
982
- "mbs-4 mbe-2 font-medium text-inherit no-underline text-4xl",
983
- "-ml-[10px]"
984
- ],
985
- 2: [
986
- "mbs-4 mbe-2 font-medium text-inherit no-underline text-3xl",
987
- "-ml-[8px]"
988
- ],
989
- 3: [
990
- "mbs-4 mbe-2 font-medium text-inherit no-underline text-2xl",
991
- "-ml-[7px]"
992
- ],
993
- 4: [
994
- "mbs-4 mbe-2 font-medium text-inherit no-underline text-xl",
995
- "-ml-[6px]"
996
- ],
997
- 5: [
998
- "mbs-4 mbe-2 font-medium text-inherit no-underline text-lg",
999
- "-ml-[5px]"
1000
- ],
1001
- 6: [
1002
- "mbs-4 mbe-2 font-medium text-inherit no-underline",
1003
- "-ml-[4px]"
1004
- ]
1005
- };
1006
- var heading = (level, readonly) => {
1007
- const [style, offset] = headings[level];
1008
- return mx(style, readonly && offset);
1014
+ 1: "mbs-4 mbe-2 font-medium text-inherit no-underline text-4xl",
1015
+ 2: "mbs-4 mbe-2 font-medium text-inherit no-underline text-3xl",
1016
+ 3: "mbs-4 mbe-2 font-medium text-inherit no-underline text-2xl",
1017
+ 4: "mbs-4 mbe-2 font-medium text-inherit no-underline text-xl",
1018
+ 5: "mbs-4 mbe-2 font-medium text-inherit no-underline text-lg",
1019
+ 6: "mbs-4 mbe-2 font-medium text-inherit no-underline"
1020
+ };
1021
+ var heading = (level) => {
1022
+ return headings[level];
1009
1023
  };
1010
1024
  var light = "text-neutral-200 dark:text-neutral-800";
1011
1025
  var mark = mx("!font-normal !no-underline !text-inherit opacity-40", light);
@@ -1023,168 +1037,123 @@ import { tailwindConfig } from "@dxos/react-ui-theme";
1023
1037
  var tokens = tailwindConfig({}).theme;
1024
1038
  var getToken = (path, defaultValue = void 0) => get2(tokens, path, defaultValue);
1025
1039
 
1026
- // packages/ui/react-ui-editor/src/extensions/code.ts
1027
- var CODE_REGEX = /```[\s\S]*?```/gs;
1028
- var styles2 = EditorView4.baseTheme({
1029
- "& .cm-codeblock": {
1030
- fontFamily: getToken("fontFamily.mono", []).join(",")
1031
- },
1032
- '&light [aria-readonly="true"] .cm-codeblock': {
1033
- background: getToken("extend.colors.neutral.50")
1034
- },
1035
- '&dark [aria-readonly="true"] .cm-codeblock': {
1036
- background: getToken("extend.colors.neutral.850")
1037
- },
1038
- '& [aria-readonly="true"] .cm-codeblock': {
1039
- display: "block",
1040
- paddingInline: "4px !important"
1041
- },
1042
- '& [aria-readonly="true"] .cm-codeblock-first': {
1043
- paddingTop: "4px !important",
1044
- borderTopLeftRadius: "4px",
1045
- borderTopRightRadius: "4px"
1046
- },
1047
- '& [aria-readonly="true"] .cm-codeblock-last': {
1048
- paddingBottom: "4px !important",
1049
- borderBottomLeftRadius: "4px",
1050
- borderBottomRightRadius: "4px"
1051
- }
1052
- });
1053
- var getLineRange = (lines, from, to) => {
1054
- const start = lines.findIndex((line) => line.from >= from);
1055
- const end = lines.findIndex((line) => line.to >= to);
1056
- return [
1057
- start,
1058
- end
1059
- ];
1060
- };
1061
- var code2 = () => {
1062
- const getDecorations = (view) => {
1063
- const decorations = [];
1064
- if (!view.hasFocus || view.state.readOnly) {
1065
- const text = view.state.doc.sliceString(0);
1066
- const matches = text.matchAll(CODE_REGEX);
1067
- const blocks = view.viewportLineBlocks;
1068
- for (const match of matches) {
1069
- const range = getLineRange(blocks, match.index, match.index + match[0].length);
1070
- for (let i = range[0]; i <= range[1]; i++) {
1071
- const block = blocks[i];
1072
- decorations.push(Decoration2.line({
1073
- class: mx2("cm-codeblock", i === range[0] && "cm-codeblock-first", i === range[1] && "cm-codeblock-last")
1074
- }).range(block.from));
1075
- }
1076
- }
1077
- }
1078
- return Decoration2.set(decorations);
1079
- };
1080
- return [
1081
- ViewPlugin3.fromClass(class {
1082
- constructor(view) {
1083
- this.hasFocus = false;
1084
- this.decorations = getDecorations(view);
1085
- }
1086
- update(update2) {
1087
- if (
1088
- // TODO(burdon): Generalize for other extensions.
1089
- this.hasFocus !== update2.view.hasFocus || update2.startState.readOnly !== update2.view.state.readOnly || update2.docChanged || update2.viewportChanged
1090
- ) {
1091
- this.hasFocus = update2.view.hasFocus;
1092
- this.decorations = getDecorations(update2.view);
1093
- }
1094
- }
1095
- }, {
1096
- decorations: (value) => value.decorations
1097
- }),
1098
- styles2
1099
- ];
1100
- };
1101
-
1102
- // packages/ui/react-ui-editor/src/extensions/comments.ts
1103
- import { StateEffect as StateEffect2, StateField as StateField2 } from "@codemirror/state";
1104
- import { hoverTooltip, keymap as keymap3, Decoration as Decoration3, EditorView as EditorView5 } from "@codemirror/view";
1105
- import sortBy from "lodash.sortby";
1106
- import { debounce } from "@dxos/async";
1107
- import { invariant as invariant2 } from "@dxos/invariant";
1108
- import { log as log2 } from "@dxos/log";
1109
- import { nonNullable } from "@dxos/util";
1110
-
1111
1040
  // packages/ui/react-ui-editor/src/util.ts
1112
1041
  import { log } from "@dxos/log";
1113
1042
  var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/util.ts";
1114
1043
  var callbackWrapper = (fn) => (...args) => {
1115
1044
  try {
1116
1045
  return fn(...args);
1117
- } catch (error) {
1118
- log.catch(error, void 0, {
1046
+ } catch (err) {
1047
+ log.catch(err, void 0, {
1119
1048
  F: __dxlog_file2,
1120
- L: 16,
1049
+ L: 18,
1121
1050
  S: void 0,
1122
1051
  C: (f, a) => f(...a)
1123
1052
  });
1124
1053
  }
1125
1054
  };
1055
+ var logChanges = (trs) => {
1056
+ const changes = trs.flatMap((tr) => {
1057
+ if (tr.changes.empty) {
1058
+ return void 0;
1059
+ }
1060
+ const changes2 = [];
1061
+ tr.changes.iterChanges((fromA, toA, fromB, toB, inserted) => changes2.push(JSON.stringify({
1062
+ fromA,
1063
+ toA,
1064
+ fromB,
1065
+ toB,
1066
+ inserted: inserted.toString()
1067
+ })));
1068
+ return changes2;
1069
+ }).filter(Boolean);
1070
+ if (changes.length) {
1071
+ console.log("changes", changes);
1072
+ }
1073
+ };
1126
1074
 
1127
1075
  // packages/ui/react-ui-editor/src/extensions/comments.ts
1128
- var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/extensions/comments.ts";
1129
- var styles3 = EditorView5.baseTheme({
1130
- "& .cm-comment": {
1076
+ var styles2 = EditorView5.baseTheme({
1077
+ "&light .cm-comment, &light .cm-comment-current": {
1078
+ mixBlendMode: "darken"
1079
+ },
1080
+ "&dark .cm-comment, &dark .cm-comment-current": {
1081
+ mixBlendMode: "plus-lighter"
1082
+ },
1083
+ "&light .cm-comment": {
1131
1084
  backgroundColor: getToken("extend.colors.yellow.50")
1132
1085
  },
1133
- "& .cm-comment-active": {
1086
+ "&light .cm-comment-current": {
1134
1087
  backgroundColor: getToken("extend.colors.yellow.100")
1088
+ },
1089
+ "&dark .cm-comment": {
1090
+ color: getToken("extend.colors.yellow.50"),
1091
+ backgroundColor: getToken("extend.colors.yellow.900")
1092
+ },
1093
+ "&dark .cm-comment-current": {
1094
+ color: getToken("extend.colors.yellow.100"),
1095
+ backgroundColor: getToken("extend.colors.yellow.950")
1135
1096
  }
1136
1097
  });
1137
- var marks = {
1138
- highlight: Decoration3.mark({
1139
- class: "cm-comment"
1140
- }),
1141
- highlightActive: Decoration3.mark({
1142
- class: "cm-comment-active"
1143
- })
1144
- };
1145
- var setFocus = (view, thread) => {
1146
- const range = view.state.field(commentsStateField).ranges.find((range2) => range2.id === thread);
1147
- if (!range) {
1098
+ var commentMark = Decoration2.mark({
1099
+ class: "cm-comment"
1100
+ });
1101
+ var commentCurrentMark = Decoration2.mark({
1102
+ class: "cm-comment-current"
1103
+ });
1104
+ var focusComment = (view, id, center = true) => {
1105
+ const comment = view.state.field(commentsState).comments.find((range2) => range2.comment.id === id);
1106
+ if (!comment?.comment.cursor) {
1148
1107
  return;
1149
1108
  }
1150
- view.dispatch({
1151
- effects: setSelection.of({
1152
- active: thread
1153
- }),
1154
- selection: {
1155
- anchor: range.from
1156
- },
1157
- scrollIntoView: true
1158
- });
1109
+ const range = Cursor.getRangeFromCursor(view.state, comment.comment.cursor);
1110
+ if (range) {
1111
+ view.dispatch({
1112
+ selection: {
1113
+ anchor: range.from
1114
+ },
1115
+ effects: [
1116
+ //
1117
+ EditorView5.scrollIntoView(range.from, center ? {
1118
+ y: "center"
1119
+ } : void 0),
1120
+ setSelection.of({
1121
+ current: id
1122
+ })
1123
+ ]
1124
+ });
1125
+ }
1159
1126
  };
1160
- var setCommentRange = StateEffect2.define();
1127
+ var setComments = StateEffect2.define();
1161
1128
  var setSelection = StateEffect2.define();
1162
1129
  var setCommentState = StateEffect2.define();
1163
- var commentsStateField = StateField2.define({
1130
+ var commentsState = StateField2.define({
1164
1131
  create: () => ({
1165
- ranges: []
1132
+ comments: [],
1133
+ selection: {}
1166
1134
  }),
1167
1135
  update: (value, tr) => {
1168
- const cursorConverter3 = tr.state.facet(Cursor.converter);
1169
1136
  for (const effect of tr.effects) {
1170
1137
  if (effect.is(setSelection)) {
1171
1138
  return {
1172
1139
  ...value,
1173
- ...effect.value
1140
+ selection: effect.value
1174
1141
  };
1175
1142
  }
1176
- if (effect.is(setCommentRange)) {
1177
- const { comments: comments2 } = effect.value;
1178
- const ranges = comments2.map((comment) => {
1179
- const range = Cursor.getRangeFromCursor(cursorConverter3, comment.cursor);
1143
+ if (effect.is(setComments)) {
1144
+ const comments2 = effect.value.map((comment) => {
1145
+ if (!comment.cursor) {
1146
+ return void 0;
1147
+ }
1148
+ const range = Cursor.getRangeFromCursor(tr.state, comment.cursor);
1180
1149
  return range && {
1181
- ...comment,
1182
- ...range
1150
+ comment,
1151
+ range
1183
1152
  };
1184
1153
  }).filter(nonNullable);
1185
1154
  return {
1186
1155
  ...value,
1187
- ranges
1156
+ comments: comments2
1188
1157
  };
1189
1158
  }
1190
1159
  if (effect.is(setCommentState)) {
@@ -1194,87 +1163,178 @@ var commentsStateField = StateField2.define({
1194
1163
  return value;
1195
1164
  }
1196
1165
  });
1197
- var highlightDecorations = EditorView5.decorations.compute([
1198
- commentsStateField
1166
+ var commentsDecorations = EditorView5.decorations.compute([
1167
+ commentsState
1199
1168
  ], (state) => {
1200
- const { active, ranges } = state.field(commentsStateField);
1201
- const decorations = sortBy(ranges ?? [], (range) => range.from)?.flatMap((selection) => {
1202
- if (selection.from === selection.to) {
1169
+ const { selection: { current }, comments: comments2 } = state.field(commentsState);
1170
+ const decorations = sortBy(comments2 ?? [], (range) => range.range.from)?.flatMap((comment) => {
1171
+ const range = comment.range;
1172
+ if (!range || range.from === range.to) {
1173
+ console.warn("Invalid range:", range);
1203
1174
  return void 0;
1204
1175
  }
1205
- const range = {
1206
- from: selection.from,
1207
- to: selection.to
1208
- };
1209
- if (selection.id === active) {
1210
- return marks.highlightActive.range(range.from, range.to);
1176
+ if (comment.comment.id === current) {
1177
+ return commentCurrentMark.range(range.from, range.to);
1211
1178
  } else {
1212
- return marks.highlight.range(range.from, range.to);
1179
+ return commentMark.range(range.from, range.to);
1213
1180
  }
1214
- }).filter(nonNullable) ?? [];
1215
- return Decoration3.set(decorations);
1181
+ }).filter(nonNullable);
1182
+ return Decoration2.set(decorations);
1216
1183
  });
1217
- var comments = (options = {}) => {
1218
- const { key: shortcut = "meta-'" } = options;
1219
- const handleSelect = debounce((state) => options.onSelect?.(state), 200);
1220
- const createCommentThread = (view) => {
1221
- const cursorConverter3 = view.state.facet(Cursor.converter);
1222
- invariant2(options.onCreate, void 0, {
1223
- F: __dxlog_file3,
1224
- L: 177,
1225
- S: void 0,
1226
- A: [
1227
- "options.onCreate",
1228
- ""
1229
- ]
1230
- });
1231
- const { head, from, to } = view.state.selection.main;
1232
- if (from === to) {
1233
- return false;
1184
+ var trackPastedComments = (onUpdate) => {
1185
+ let tracked = null;
1186
+ const handleTrack = (event, view) => {
1187
+ const comments2 = view.state.field(commentsState);
1188
+ const { main } = view.state.selection;
1189
+ const selectedRanges = comments2.comments.filter(({ range }) => range.from >= main.from && range.to <= main.to && range.from < range.to);
1190
+ if (!selectedRanges.length) {
1191
+ tracked = null;
1192
+ } else {
1193
+ tracked = {
1194
+ text: view.state.doc.slice(main.from, main.to),
1195
+ comments: selectedRanges.map(({ comment, range }) => ({
1196
+ id: comment.id,
1197
+ from: range.from - main.from,
1198
+ to: range.to - main.from
1199
+ }))
1200
+ };
1234
1201
  }
1235
- const cursor = Cursor.getCursorFromRange(cursorConverter3, {
1236
- from,
1237
- to
1238
- });
1239
- if (cursor) {
1240
- const id = callbackWrapper(options.onCreate)(cursor, view.coordsAtPos(from));
1241
- if (id) {
1242
- view.dispatch({
1243
- effects: setSelection.of({
1244
- active: id
1245
- }),
1246
- selection: {
1247
- anchor: from
1202
+ };
1203
+ return [
1204
+ EditorView5.domEventHandlers({
1205
+ cut: handleTrack,
1206
+ copy: handleTrack
1207
+ }),
1208
+ // Track deleted comments.
1209
+ invertedEffects2.of((tr) => {
1210
+ const { comments: comments2 } = tr.startState.field(commentsState);
1211
+ const effects = [];
1212
+ tr.changes.iterChangedRanges((fromA, toA) => {
1213
+ for (const { comment: { id }, range: { from, to } } of comments2) {
1214
+ if (from < to && from >= fromA && to <= toA) {
1215
+ effects.push(restoreCommentEffect.of({
1216
+ id,
1217
+ from,
1218
+ to
1219
+ }));
1248
1220
  }
1249
- });
1250
- if (options.footnote) {
1251
- const tag = `[^${id}]`;
1252
- view.dispatch({
1253
- changes: {
1254
- from: head,
1255
- insert: tag
1256
- },
1257
- selection: {
1258
- anchor: head + tag.length
1221
+ }
1222
+ });
1223
+ return effects;
1224
+ }),
1225
+ // Handle paste or the undo of comment deletion.
1226
+ EditorView5.updateListener.of((update2) => {
1227
+ const restore = [];
1228
+ for (let i = 0; i < update2.transactions.length; i++) {
1229
+ const tr = update2.transactions[i];
1230
+ for (let j = 0; j < restore.length; j++) {
1231
+ restore[j] = mapTrackedComment(restore[j], tr.changes);
1232
+ }
1233
+ for (const effect of tr.effects) {
1234
+ if (effect.is(restoreCommentEffect)) {
1235
+ restore.push(effect.value);
1236
+ }
1237
+ }
1238
+ }
1239
+ if (tracked) {
1240
+ const paste = update2.transactions.find((tr) => tr.isUserEvent("input.paste"));
1241
+ if (paste) {
1242
+ let found = -1;
1243
+ paste.changes.iterChanges((fromA, toA, fromB, toB, text) => {
1244
+ if (text.eq(tracked.text)) {
1245
+ for (let i = update2.transactions.indexOf(paste) + 1; i < update2.transactions.length; i++) {
1246
+ fromB = update2.transactions[i].changes.mapPos(fromB);
1247
+ }
1248
+ found = fromB;
1259
1249
  }
1260
1250
  });
1251
+ if (found > -1) {
1252
+ for (const moved of tracked.comments) {
1253
+ restore.push({
1254
+ id: moved.id,
1255
+ from: found + moved.from,
1256
+ to: found + moved.to
1257
+ });
1258
+ }
1259
+ }
1260
+ tracked = null;
1261
1261
  }
1262
- return true;
1263
1262
  }
1264
- }
1263
+ for (const comment of restore) {
1264
+ const { comments: comments2 } = update2.startState.field(commentsState);
1265
+ const exists = comments2.some((c) => c.comment.id === comment.id && c.range.from < c.range.to);
1266
+ if (!exists) {
1267
+ const cursor = Cursor.getCursorFromRange(update2.state, comment);
1268
+ onUpdate(comment.id, cursor);
1269
+ }
1270
+ }
1271
+ })
1272
+ ];
1273
+ };
1274
+ var mapTrackedComment = (comment, changes) => ({
1275
+ id: comment.id,
1276
+ from: changes.mapPos(comment.from, 1),
1277
+ to: changes.mapPos(comment.to, 1)
1278
+ });
1279
+ var restoreCommentEffect = StateEffect2.define({
1280
+ map: mapTrackedComment
1281
+ });
1282
+ var optionsFacet = Facet3.define({
1283
+ combine: (providers) => providers[0]
1284
+ });
1285
+ var createComment = (view) => {
1286
+ const options = view.state.facet(optionsFacet);
1287
+ const { from, to } = view.state.selection.main;
1288
+ if (from === to) {
1265
1289
  return false;
1266
- };
1290
+ }
1291
+ if (to === view.state.doc.length) {
1292
+ view.dispatch({
1293
+ changes: {
1294
+ from: to,
1295
+ insert: "\n"
1296
+ }
1297
+ });
1298
+ }
1299
+ const cursor = Cursor.getCursorFromRange(view.state, {
1300
+ from,
1301
+ to
1302
+ });
1303
+ if (cursor) {
1304
+ const id = options.onCreate?.({
1305
+ cursor,
1306
+ from,
1307
+ location: view.coordsAtPos(from)
1308
+ });
1309
+ if (id) {
1310
+ view.dispatch({
1311
+ effects: setSelection.of({
1312
+ current: id
1313
+ }),
1314
+ selection: {
1315
+ anchor: to
1316
+ }
1317
+ });
1318
+ return true;
1319
+ }
1320
+ }
1321
+ return false;
1322
+ };
1323
+ var comments = (options = {}) => {
1324
+ const { key: shortcut = "meta-'" } = options;
1325
+ const handleSelect = debounce((state) => options.onSelect?.(state), 200);
1267
1326
  return [
1268
- commentsStateField,
1269
- highlightDecorations,
1270
- styles3,
1327
+ optionsFacet.of(options),
1328
+ commentsState,
1329
+ commentsDecorations,
1330
+ styles2,
1271
1331
  //
1272
1332
  // Keymap.
1273
1333
  //
1274
1334
  options.onCreate ? keymap3.of([
1275
1335
  {
1276
1336
  key: shortcut,
1277
- run: callbackWrapper(createCommentThread)
1337
+ run: callbackWrapper(createComment)
1278
1338
  }
1279
1339
  ]) : [],
1280
1340
  //
@@ -1290,7 +1350,7 @@ var comments = (options = {}) => {
1290
1350
  above: true,
1291
1351
  create: () => {
1292
1352
  const el = document.createElement("div");
1293
- options.onHover?.(el, shortcut);
1353
+ options.onHover(el, shortcut);
1294
1354
  return {
1295
1355
  dom: el,
1296
1356
  offset: {
@@ -1303,364 +1363,116 @@ var comments = (options = {}) => {
1303
1363
  }
1304
1364
  return null;
1305
1365
  }, {
1306
- hideOnChange: true,
1366
+ // TODO(burdon): Hide on change triggered immediately?
1367
+ // hideOnChange: true,
1307
1368
  hoverTime: 1e3
1308
1369
  }) : [],
1309
1370
  //
1310
- // Monitor cursor movement and text updates.
1311
- // TODO(burdon): Is there a better (finer grained) way to do this?
1371
+ // Track deleted ranges and update ranges for decorations.
1312
1372
  //
1313
1373
  EditorView5.updateListener.of(({ view, state, changes }) => {
1314
- const cursorConverter3 = view.state.facet(Cursor.converter);
1315
- {
1316
- let mod = false;
1317
- const { active, ranges } = state.field(commentsStateField);
1318
- changes.iterChanges((from, to, from2, to2) => {
1319
- ranges.forEach((range) => {
1320
- if (from2 === to2) {
1321
- const newRange = Cursor.getRangeFromCursor(cursorConverter3, range.cursor);
1322
- if (!newRange || newRange.to - newRange.from === 0) {
1323
- log2.info("deleted comment", {
1324
- thread: range.id
1325
- }, {
1326
- F: __dxlog_file3,
1327
- L: 274,
1328
- S: void 0,
1329
- C: (f, a) => f(...a)
1330
- });
1331
- }
1332
- }
1333
- if (from <= range.to) {
1334
- const newRange = Cursor.getRangeFromCursor(cursorConverter3, range.cursor);
1335
- Object.assign(range, newRange);
1336
- mod = true;
1374
+ let mod = false;
1375
+ const { comments: comments2, ...value } = state.field(commentsState);
1376
+ changes.iterChanges((from, to, from2, to2) => {
1377
+ comments2.forEach(({ comment, range }) => {
1378
+ if (from2 === to2) {
1379
+ const newRange = Cursor.getRangeFromCursor(view.state, comment.cursor);
1380
+ if (!newRange || newRange.to - newRange.from === 0) {
1381
+ options.onDelete?.(comment.id);
1337
1382
  }
1338
- });
1383
+ }
1384
+ if (from <= range.to) {
1385
+ const newRange = Cursor.getRangeFromCursor(view.state, comment.cursor);
1386
+ Object.assign(range, newRange);
1387
+ mod = true;
1388
+ }
1389
+ });
1390
+ });
1391
+ if (mod) {
1392
+ view.dispatch({
1393
+ effects: setCommentState.of({
1394
+ comments: comments2,
1395
+ ...value
1396
+ })
1339
1397
  });
1340
- if (mod) {
1341
- view.dispatch({
1342
- effects: setCommentState.of({
1343
- active,
1344
- ranges
1345
- })
1346
- });
1347
- }
1348
1398
  }
1349
- {
1350
- const { head } = state.selection.main;
1351
- let min = Infinity;
1352
- const { active, closest, ranges } = state.field(commentsStateField);
1353
- const selected = {
1354
- active: void 0,
1355
- closest: void 0
1356
- };
1357
- ranges.forEach((comment) => {
1358
- const d = Math.min(Math.abs(head - comment.from), Math.abs(head - comment.to));
1359
- if (head >= comment.from && head <= comment.to) {
1360
- selected.active = comment.id;
1361
- }
1399
+ }),
1400
+ //
1401
+ // Track selection/proximity.
1402
+ //
1403
+ EditorView5.updateListener.of(({ view, state }) => {
1404
+ let min = Infinity;
1405
+ const { selection: { current, closest }, comments: comments2 } = state.field(commentsState);
1406
+ const { head } = state.selection.main;
1407
+ const selection = {};
1408
+ comments2.forEach(({ comment, range }) => {
1409
+ if (head >= range.from && head <= range.to) {
1410
+ selection.current = comment.id;
1411
+ selection.closest = void 0;
1412
+ }
1413
+ if (!selection.current) {
1414
+ const d = Math.min(Math.abs(head - range.from), Math.abs(head - range.to));
1362
1415
  if (d < min) {
1363
- selected.closest = comment.id;
1416
+ selection.closest = comment.id;
1364
1417
  min = d;
1365
1418
  }
1366
- });
1367
- if (selected.active !== active || selected.closest !== closest) {
1368
- view.dispatch({
1369
- effects: setSelection.of(selected)
1370
- });
1371
- handleSelect({
1372
- ...selected,
1373
- ranges: ranges.map((range) => ({
1374
- ...range,
1375
- location: view.coordsAtPos(range.from)
1376
- }))
1377
- });
1378
1419
  }
1420
+ });
1421
+ if (selection.current !== current || selection.closest !== closest) {
1422
+ view.dispatch({
1423
+ effects: setSelection.of(selection)
1424
+ });
1425
+ handleSelect({
1426
+ selection,
1427
+ comments: comments2.map(({ comment, range }) => ({
1428
+ comment,
1429
+ range,
1430
+ location: view.coordsAtPos(range.from)
1431
+ }))
1432
+ });
1379
1433
  }
1380
- })
1434
+ }),
1435
+ options.onUpdate ? trackPastedComments(options.onUpdate) : []
1381
1436
  ];
1382
1437
  };
1438
+ var useComments = (view, comments2 = []) => {
1439
+ useEffect(() => {
1440
+ if (view) {
1441
+ view.dispatch({
1442
+ effects: setComments.of(comments2)
1443
+ });
1444
+ }
1445
+ }, [
1446
+ view,
1447
+ comments2
1448
+ ]);
1449
+ };
1383
1450
 
1384
- // packages/ui/react-ui-editor/src/extensions/hr.ts
1385
- import { Decoration as Decoration4, EditorView as EditorView6, MatchDecorator, ViewPlugin as ViewPlugin4, WidgetType as WidgetType2 } from "@codemirror/view";
1386
- var styles4 = EditorView6.baseTheme({
1387
- "& .cm-hr": {
1388
- // TODO(burdon): ???
1389
- // Note that block-level decorations should not have vertical margins,
1390
- borderBottom: `1px solid ${getToken("extend.colors.neutral.200")}`
1391
- }
1392
- });
1393
- var HorizontalRuleWidget = class extends WidgetType2 {
1394
- constructor(_pos) {
1395
- super();
1396
- this._pos = _pos;
1397
- }
1398
- eq(other) {
1399
- return this._pos === other._pos;
1400
- }
1401
- toDOM(view) {
1402
- const el = document.createElement("div");
1403
- el.className = "cm-hr";
1404
- return el;
1405
- }
1406
- };
1407
- var placeholderMatcher = new MatchDecorator({
1408
- regexp: /^---$/g,
1409
- decoration: (match, view, pos) => Decoration4.replace({
1410
- widget: new HorizontalRuleWidget(pos)
1411
- })
1412
- });
1413
- var hr = () => [
1414
- styles4,
1415
- ViewPlugin4.fromClass(class {
1416
- constructor(view) {
1417
- this.rules = placeholderMatcher.createDeco(view);
1418
- }
1419
- update(update2) {
1420
- this.rules = placeholderMatcher.updateDeco(update2, this.rules);
1421
- }
1422
- }, {
1423
- decorations: (instance) => instance.rules,
1424
- // TODO(burdon): Is this really atomic (cursor can move into ---).
1425
- provide: (plugin) => EditorView6.atomicRanges.of((view) => {
1426
- return view.plugin(plugin)?.rules || Decoration4.none;
1427
- })
1428
- })
1429
- ];
1430
-
1431
- // packages/ui/react-ui-editor/src/extensions/image.ts
1432
- import { syntaxTree } from "@codemirror/language";
1433
- import { StateField as StateField3 } from "@codemirror/state";
1434
- import { Decoration as Decoration5, EditorView as EditorView7, WidgetType as WidgetType3 } from "@codemirror/view";
1435
- var image = (options = {}) => {
1436
- return StateField3.define({
1437
- create: (state) => {
1438
- return Decoration5.set(buildDecorations(0, state.doc.length, state));
1439
- },
1440
- update: (value, tr) => {
1441
- if (!tr.docChanged && !tr.selection) {
1442
- return value;
1443
- }
1444
- const cursor = tr.state.selection.main.head;
1445
- const oldCursor = tr.changes.mapPos(tr.startState.selection.main.head);
1446
- let from = Math.min(cursor, oldCursor);
1447
- let to = Math.max(cursor, oldCursor);
1448
- tr.changes.iterChangedRanges((fromA, toA, fromB, toB) => {
1449
- from = Math.min(from, fromB);
1450
- to = Math.max(to, toB);
1451
- });
1452
- from = tr.state.doc.lineAt(from).from;
1453
- to = tr.state.doc.lineAt(to).to;
1454
- return value.map(tr.changes).update({
1455
- filterFrom: from,
1456
- filterTo: to,
1457
- filter: () => false,
1458
- add: buildDecorations(from, to, tr.state)
1459
- });
1460
- },
1461
- provide: (field) => EditorView7.decorations.from(field)
1462
- });
1463
- };
1464
- var buildDecorations = (from, to, state) => {
1465
- const decorations = [];
1466
- const cursor = state.selection.main.head;
1467
- syntaxTree(state).iterate({
1468
- enter: (node) => {
1469
- if (node.name === "Image") {
1470
- const urlNode = node.node.getChild("URL");
1471
- if (urlNode) {
1472
- const hide = state.readOnly || cursor < node.from || cursor > node.to;
1473
- const url = state.sliceDoc(urlNode.from, urlNode.to);
1474
- decorations.push(Decoration5.replace({
1475
- block: true,
1476
- widget: new ImageWidget(url)
1477
- }).range(hide ? node.from : node.to, node.to));
1478
- }
1479
- }
1480
- },
1481
- from,
1482
- to
1483
- });
1484
- return decorations;
1485
- };
1486
- var ImageWidget = class extends WidgetType3 {
1487
- constructor(_url) {
1488
- super();
1489
- this._url = _url;
1490
- }
1491
- eq(other) {
1492
- return this._url === other._url;
1493
- }
1494
- toDOM(view) {
1495
- const img = document.createElement("img");
1496
- img.setAttribute("src", this._url);
1497
- img.setAttribute("class", "cm-image");
1498
- img.onload = () => img.classList.add("cm-loaded-image");
1499
- return img;
1500
- }
1501
- };
1502
-
1503
- // packages/ui/react-ui-editor/src/extensions/link.ts
1504
- import { syntaxTree as syntaxTree2 } from "@codemirror/language";
1505
- import { RangeSetBuilder } from "@codemirror/state";
1506
- import { Decoration as Decoration6, WidgetType as WidgetType4, hoverTooltip as hoverTooltip2, ViewPlugin as ViewPlugin5 } from "@codemirror/view";
1507
- import { tooltipContent } from "@dxos/react-ui-theme";
1508
- var link = (options = {}) => {
1509
- const extensions = [
1510
- ViewPlugin5.fromClass(class {
1511
- constructor(view) {
1512
- this.decorations = buildDecorations2(view, options);
1513
- }
1514
- update(update2) {
1515
- if (update2.docChanged || update2.viewportChanged || update2.selectionSet) {
1516
- this.decorations = buildDecorations2(update2.view, options);
1517
- }
1518
- }
1519
- }, {
1520
- decorations: (v) => v.decorations
1521
- })
1522
- ];
1523
- if (options.onHover) {
1524
- extensions.push(
1525
- // https://codemirror.net/examples/tooltip
1526
- // https://codemirror.net/docs/ref/#view.hoverTooltip
1527
- // https://github.com/codemirror/view/blob/main/src/tooltip.ts
1528
- hoverTooltip2((view, pos, side) => {
1529
- const syntax = syntaxTree2(view.state).resolveInner(pos, side);
1530
- let link2 = null;
1531
- for (let i = 0, node = syntax; !link2 && node && i < 5; node = node.parent, i++) {
1532
- link2 = node.name === "Link" ? node : null;
1533
- }
1534
- const url = link2 && link2.getChild("URL");
1535
- if (!url || !link2) {
1536
- return null;
1537
- }
1538
- const urlText = view.state.sliceDoc(url.from, url.to);
1539
- return {
1540
- pos: link2.from,
1541
- end: link2.to,
1542
- above: true,
1543
- create: () => {
1544
- const el = document.createElement("div");
1545
- el.className = tooltipContent({}, "pli-2 plb-1");
1546
- options.onHover(el, urlText);
1547
- return {
1548
- dom: el,
1549
- offset: {
1550
- x: 0,
1551
- y: 4
1552
- }
1553
- };
1554
- }
1555
- };
1556
- })
1557
- );
1558
- }
1559
- return extensions;
1560
- };
1561
- var LinkButton = class extends WidgetType4 {
1562
- constructor(_url, _onAttach) {
1563
- super();
1564
- this._url = _url;
1565
- this._onAttach = _onAttach;
1566
- }
1567
- eq(other) {
1568
- return this._url === other._url;
1569
- }
1570
- toDOM(view) {
1571
- const el = document.createElement("span");
1572
- this._onAttach(el, this._url);
1573
- return el;
1574
- }
1575
- };
1576
- var LinkText = class extends WidgetType4 {
1577
- constructor(_text, _url) {
1578
- super();
1579
- this._text = _text;
1580
- this._url = _url;
1581
- }
1582
- eq(other) {
1583
- return this._url === other._url;
1584
- }
1585
- toDOM(view) {
1586
- const link2 = document.createElement("a");
1587
- link2.setAttribute("class", "cm-link");
1588
- link2.textContent = this._text;
1589
- if (this._url) {
1590
- link2.setAttribute("rel", "noreferrer");
1591
- link2.setAttribute("target", "_blank");
1592
- link2.href = this._url;
1593
- } else {
1594
- link2.onclick = () => {
1595
- view.dispatch({
1596
- selection: {
1597
- anchor: view.posAtDOM(link2)
1598
- }
1599
- });
1600
- };
1601
- }
1602
- return link2;
1603
- }
1604
- };
1605
- var buildDecorations2 = (view, options) => {
1606
- const builder = new RangeSetBuilder();
1607
- const { state } = view;
1608
- const cursor = state.selection.main.head;
1609
- for (const { from, to } of view.visibleRanges) {
1610
- syntaxTree2(state).iterate({
1611
- enter: (node) => {
1612
- if (node.name === "Link") {
1613
- const marks2 = node.node.getChildren("LinkMark");
1614
- const text = marks2.length >= 2 ? state.sliceDoc(marks2[0].to, marks2[1].from) : "";
1615
- const urlNode = node.node.getChild("URL");
1616
- const url = urlNode ? state.sliceDoc(urlNode.from, urlNode.to) : "";
1617
- if (!url) {
1618
- return false;
1619
- }
1620
- if (!view.hasFocus || state.readOnly || cursor < node.from || cursor > node.to) {
1621
- builder.add(node.from, node.to, Decoration6.replace({
1622
- widget: new LinkText(text, options.link ? url : void 0)
1623
- }));
1624
- }
1625
- if (options.onRender) {
1626
- builder.add(node.to, node.to, Decoration6.replace({
1627
- widget: new LinkButton(url, options.onRender)
1628
- }));
1629
- }
1630
- return false;
1631
- }
1632
- },
1633
- from,
1634
- to
1635
- });
1636
- }
1637
- return builder.finish();
1638
- };
1639
-
1640
- // packages/ui/react-ui-editor/src/extensions/listener.ts
1641
- import { EditorView as EditorView8 } from "@codemirror/view";
1642
- var listener = ({ onFocus, onChange }) => {
1643
- const extensions = [];
1644
- onFocus && extensions.push(EditorView8.focusChangeEffect.of((_, focused) => {
1645
- onFocus(focused);
1646
- return null;
1647
- }));
1648
- onChange && extensions.push(EditorView8.updateListener.of((update2) => {
1649
- onChange(update2.state.doc.toString());
1650
- }));
1651
- return extensions;
1451
+ // packages/ui/react-ui-editor/src/extensions/listener.ts
1452
+ import { EditorView as EditorView6 } from "@codemirror/view";
1453
+ var listener = ({ onFocus, onChange }) => {
1454
+ const extensions = [];
1455
+ onFocus && extensions.push(EditorView6.focusChangeEffect.of((_, focused) => {
1456
+ onFocus(focused);
1457
+ return null;
1458
+ }));
1459
+ onChange && extensions.push(EditorView6.updateListener.of((update2) => {
1460
+ onChange(update2.state.doc.toString());
1461
+ }));
1462
+ return extensions;
1652
1463
  };
1653
1464
 
1654
1465
  // packages/ui/react-ui-editor/src/extensions/markdown/bundle.ts
1655
1466
  import { closeBrackets as closeBrackets2, closeBracketsKeymap } from "@codemirror/autocomplete";
1656
- import { history, historyKeymap, indentWithTab, standardKeymap } from "@codemirror/commands";
1467
+ import { history as history2, historyKeymap, indentWithTab, standardKeymap } from "@codemirror/commands";
1657
1468
  import { markdownLanguage as markdownLanguage3, markdown } from "@codemirror/lang-markdown";
1658
1469
  import { bracketMatching as bracketMatching2, defaultHighlightStyle as defaultHighlightStyle2, indentOnInput, syntaxHighlighting as syntaxHighlighting2 } from "@codemirror/language";
1659
1470
  import { languages } from "@codemirror/language-data";
1660
1471
  import { searchKeymap } from "@codemirror/search";
1661
1472
  import { EditorState } from "@codemirror/state";
1662
1473
  import { oneDarkHighlightStyle as oneDarkHighlightStyle2 } from "@codemirror/theme-one-dark";
1663
- import { crosshairCursor, drawSelection as drawSelection2, dropCursor, EditorView as EditorView9, highlightActiveLine, keymap as keymap4, placeholder as placeholder2 } from "@codemirror/view";
1474
+ import { crosshairCursor, drawSelection as drawSelection2, dropCursor, EditorView as EditorView7, highlightActiveLine as highlightActiveLine2, keymap as keymap4, placeholder as placeholder2 } from "@codemirror/view";
1475
+ import { isNotFalsy as isNotFalsy2 } from "@dxos/util";
1664
1476
 
1665
1477
  // packages/ui/react-ui-editor/src/extensions/markdown/highlight.ts
1666
1478
  import { markdownLanguage as markdownLanguage2 } from "@codemirror/lang-markdown";
@@ -1757,7 +1569,7 @@ var markdownHighlightStyle = (readonly) => {
1757
1569
  markdownTags.QuoteMark,
1758
1570
  markdownTags.EmphasisMark
1759
1571
  ],
1760
- class: readonly ? "hidden" : mark
1572
+ class: mark
1761
1573
  },
1762
1574
  // E.g., code block language (after ```).
1763
1575
  {
@@ -1765,7 +1577,7 @@ var markdownHighlightStyle = (readonly) => {
1765
1577
  tags.function(tags.variableName),
1766
1578
  tags.labelName
1767
1579
  ],
1768
- class: readonly ? "hidden" : codeMark
1580
+ class: codeMark
1769
1581
  },
1770
1582
  {
1771
1583
  tag: [
@@ -1776,27 +1588,27 @@ var markdownHighlightStyle = (readonly) => {
1776
1588
  // Headings.
1777
1589
  {
1778
1590
  tag: tags.heading1,
1779
- class: heading(1, readonly)
1591
+ class: heading(1)
1780
1592
  },
1781
1593
  {
1782
1594
  tag: tags.heading2,
1783
- class: heading(2, readonly)
1595
+ class: heading(2)
1784
1596
  },
1785
1597
  {
1786
1598
  tag: tags.heading3,
1787
- class: heading(3, readonly)
1599
+ class: heading(3)
1788
1600
  },
1789
1601
  {
1790
1602
  tag: tags.heading4,
1791
- class: heading(4, readonly)
1603
+ class: heading(4)
1792
1604
  },
1793
1605
  {
1794
1606
  tag: tags.heading5,
1795
- class: heading(5, readonly)
1607
+ class: heading(5)
1796
1608
  },
1797
1609
  {
1798
1610
  tag: tags.heading6,
1799
- class: heading(6, readonly)
1611
+ class: heading(6)
1800
1612
  },
1801
1613
  // Emphasis.
1802
1614
  {
@@ -1822,7 +1634,7 @@ var markdownHighlightStyle = (readonly) => {
1822
1634
  // However, since `codeLanguages` is also defined, the `lezer` will not parse fenced code blocks,
1823
1635
  // when a language is specified. In this case, the syntax highlighting extensions will colorize
1824
1636
  // the code, but all other CSS properties will be inherited.
1825
- // IMPORTANT: Therefore, the fenced code block will use the base editor font.
1637
+ // IMPORTANT: Therefore, the fenced code block will use the base editor font unless changed by an extension.
1826
1638
  {
1827
1639
  tag: [
1828
1640
  markdownTags.CodeText,
@@ -1851,19 +1663,19 @@ var markdownHighlightStyle = (readonly) => {
1851
1663
  };
1852
1664
 
1853
1665
  // packages/ui/react-ui-editor/src/extensions/markdown/bundle.ts
1854
- var markdownBundle = ({ readonly, themeMode, placeholder: _placeholder }) => {
1666
+ var createMarkdownExtensions = ({ themeMode, placeholder: _placeholder, lineWrapping = true } = {}) => {
1855
1667
  return [
1668
+ lineWrapping && EditorView7.lineWrapping,
1856
1669
  EditorState.allowMultipleSelections.of(true),
1857
1670
  EditorState.tabSize.of(2),
1858
- EditorView9.lineWrapping,
1859
- customKeymap(),
1671
+ // https://github.com/codemirror/basic-setup
1860
1672
  bracketMatching2(),
1861
1673
  closeBrackets2(),
1862
1674
  crosshairCursor(),
1863
1675
  dropCursor(),
1864
1676
  drawSelection2(),
1865
- highlightActiveLine(),
1866
- history(),
1677
+ highlightActiveLine2(),
1678
+ history2(),
1867
1679
  indentOnInput(),
1868
1680
  _placeholder && placeholder2(_placeholder),
1869
1681
  // Main extension.
@@ -1887,66 +1699,610 @@ var markdownBundle = ({ readonly, themeMode, placeholder: _placeholder }) => {
1887
1699
  // https://github.com/codemirror/theme-one-dark
1888
1700
  themeMode === "dark" ? syntaxHighlighting2(oneDarkHighlightStyle2) : syntaxHighlighting2(defaultHighlightStyle2),
1889
1701
  // Custom styles.
1890
- syntaxHighlighting2(markdownHighlightStyle(readonly))
1891
- ].filter(Boolean);
1892
- };
1893
- var customKeymap = () => keymap4.of([
1894
- // https://codemirror.net/docs/ref/#commands.indentWithTab
1895
- indentWithTab,
1896
- // https://codemirror.net/docs/ref/#commands.standardKeymap
1897
- ...standardKeymap,
1898
- // https://codemirror.net/docs/ref/#commands.historyKeymap
1899
- ...historyKeymap,
1900
- // https://codemirror.net/docs/ref/#autocomplete.closeBracketsKeymap
1901
- ...closeBracketsKeymap,
1902
- // https://codemirror.net/docs/ref/#search.searchKeymap
1903
- ...searchKeymap
1904
- ]);
1905
-
1906
- // packages/ui/react-ui-editor/src/extensions/mention.ts
1907
- import { autocompletion as autocompletion2 } from "@codemirror/autocomplete";
1908
- var mention = ({ onSearch }) => {
1909
- return autocompletion2({
1910
- closeOnBlur: false,
1911
- override: [
1912
- (context) => {
1913
- const match = context.matchBefore(/@(\w+)?/);
1914
- if (!match || match.from === match.to && !context.explicit) {
1915
- return null;
1916
- }
1917
- console.log(match);
1918
- return {
1919
- from: match.from,
1920
- options: onSearch(match.text.slice(1).toLowerCase()).map((value) => ({
1921
- label: `@${value}`
1922
- }))
1923
- };
1924
- }
1925
- ]
1926
- });
1702
+ syntaxHighlighting2(markdownHighlightStyle()),
1703
+ keymap4.of([
1704
+ // https://codemirror.net/docs/ref/#commands.indentWithTab
1705
+ indentWithTab,
1706
+ // https://codemirror.net/docs/ref/#autocomplete.closeBracketsKeymap
1707
+ ...closeBracketsKeymap,
1708
+ // https://codemirror.net/docs/ref/#commands.historyKeymap
1709
+ ...historyKeymap,
1710
+ // https://codemirror.net/docs/ref/#search.searchKeymap
1711
+ ...searchKeymap,
1712
+ // https://codemirror.net/docs/ref/#commands.standardKeymap
1713
+ ...standardKeymap
1714
+ ])
1715
+ ].filter(isNotFalsy2);
1927
1716
  };
1928
1717
 
1929
- // packages/ui/react-ui-editor/src/extensions/table.ts
1930
- import { syntaxTree as syntaxTree3 } from "@codemirror/language";
1931
- import { RangeSetBuilder as RangeSetBuilder2, StateField as StateField4 } from "@codemirror/state";
1932
- import { Decoration as Decoration7, EditorView as EditorView10, WidgetType as WidgetType5 } from "@codemirror/view";
1933
- var table = (options = {}) => {
1934
- return StateField4.define({
1935
- create: (state) => update(state, options),
1936
- update: (_, tr) => update(tr.state, options),
1937
- provide: (field) => EditorView10.decorations.from(field)
1938
- });
1718
+ // packages/ui/react-ui-editor/src/extensions/markdown/code.ts
1719
+ import { syntaxTree } from "@codemirror/language";
1720
+ import { RangeSetBuilder } from "@codemirror/state";
1721
+ import { ViewPlugin as ViewPlugin3, EditorView as EditorView8, Decoration as Decoration3, WidgetType as WidgetType2 } from "@codemirror/view";
1722
+ import { mx as mx2 } from "@dxos/react-ui-theme";
1723
+ var styles3 = EditorView8.baseTheme({
1724
+ "& .cm-code": {
1725
+ fontFamily: getToken("fontFamily.mono", []).join(",")
1726
+ },
1727
+ "& .cm-codeblock": {
1728
+ width: "100%",
1729
+ paddingInline: "1rem !important",
1730
+ position: "relative",
1731
+ "&::after": {
1732
+ content: '""',
1733
+ position: "absolute",
1734
+ inset: 0
1735
+ }
1736
+ },
1737
+ "&light .cm-codeblock": {
1738
+ "&::after": {
1739
+ background: getToken("extend.semanticColors.input.light"),
1740
+ mixBlendMode: "darken"
1741
+ }
1742
+ },
1743
+ "&dark .cm-codeblock": {
1744
+ "&::after": {
1745
+ background: getToken("extend.semanticColors.input.dark"),
1746
+ mixBlendMode: "lighten"
1747
+ }
1748
+ },
1749
+ "& .cm-codeblock-first": {
1750
+ display: "inline-block",
1751
+ "&::after": {
1752
+ borderTopLeftRadius: ".5rem",
1753
+ borderTopRightRadius: ".5rem"
1754
+ }
1755
+ },
1756
+ "& .cm-codeblock-last": {
1757
+ display: "inline-block",
1758
+ "&::after": {
1759
+ borderBottomLeftRadius: ".5rem",
1760
+ borderBottomRightRadius: ".5rem"
1761
+ }
1762
+ }
1763
+ });
1764
+ var getLineRange = (lines, from, to) => {
1765
+ const start = lines.findIndex((line) => line.from >= from);
1766
+ const end = lines.findIndex((line) => line.to >= to);
1767
+ return [
1768
+ start,
1769
+ end
1770
+ ];
1939
1771
  };
1940
- var update = (state, options) => {
1941
- const builder = new RangeSetBuilder2();
1942
- const cursor = state.selection.main.head;
1943
- const tables = [];
1944
- const getTable = () => tables[tables.length - 1];
1945
- const getRow = () => {
1772
+ var LineWidget = class extends WidgetType2 {
1773
+ constructor(_className) {
1774
+ super();
1775
+ this._className = _className;
1776
+ }
1777
+ toDOM() {
1778
+ const el = document.createElement("span");
1779
+ el.innerHTML = "&nbsp;";
1780
+ el.className = mx2("cm-code cm-codeblock", this._className);
1781
+ return el;
1782
+ }
1783
+ };
1784
+ var top = new LineWidget("cm-codeblock-first");
1785
+ var bottom = new LineWidget("cm-codeblock-last");
1786
+ var buildDecorations = (view) => {
1787
+ const builder = new RangeSetBuilder();
1788
+ const { state } = view;
1789
+ const blocks = view.viewportLineBlocks;
1790
+ const cursor = state.selection.main.head;
1791
+ for (const { from, to } of view.visibleRanges) {
1792
+ syntaxTree(state).iterate({
1793
+ enter: (node) => {
1794
+ if (node.name === "FencedCode") {
1795
+ const edit = !view.state.readOnly && cursor >= node.from && cursor <= node.to;
1796
+ const range = getLineRange(blocks, node.from, node.to);
1797
+ for (let i = range[0]; i <= range[1]; i++) {
1798
+ const block = blocks[i];
1799
+ if (!edit && (i === range[0] || i === range[1])) {
1800
+ builder.add(block.from, block.to, Decoration3.replace({
1801
+ widget: i === range[0] ? top : bottom
1802
+ }));
1803
+ } else {
1804
+ builder.add(block.from, block.from, Decoration3.line({
1805
+ class: mx2("cm-code cm-codeblock", i === range[0] && "cm-codeblock-first", i === range[1] && "cm-codeblock-last")
1806
+ }));
1807
+ }
1808
+ }
1809
+ }
1810
+ },
1811
+ from,
1812
+ to
1813
+ });
1814
+ }
1815
+ return builder.finish();
1816
+ };
1817
+ var code2 = () => {
1818
+ return [
1819
+ ViewPlugin3.fromClass(class {
1820
+ constructor(view) {
1821
+ this.decorations = buildDecorations(view);
1822
+ }
1823
+ update(update2) {
1824
+ this.decorations = buildDecorations(update2.view);
1825
+ }
1826
+ }, {
1827
+ decorations: (value) => value.decorations
1828
+ }),
1829
+ styles3
1830
+ ];
1831
+ };
1832
+
1833
+ // packages/ui/react-ui-editor/src/extensions/markdown/formatting.ts
1834
+ import { snippet } from "@codemirror/autocomplete";
1835
+ import { syntaxTree as syntaxTree2 } from "@codemirror/language";
1836
+ import { RangeSetBuilder as RangeSetBuilder2 } from "@codemirror/state";
1837
+ import { Decoration as Decoration4, keymap as keymap5, ViewPlugin as ViewPlugin4 } from "@codemirror/view";
1838
+ var setHeading = (level) => (view) => {
1839
+ const { selection: { ranges }, doc } = view.state;
1840
+ const changes = [];
1841
+ for (const range of ranges) {
1842
+ const { number } = doc.lineAt(range.anchor);
1843
+ const { from, to } = doc.line(number);
1844
+ const line = doc.sliceString(from, to);
1845
+ const [_, marks, spaces] = line.match(/(#+)(\s+)/) ?? [];
1846
+ const current = marks?.length ?? 0;
1847
+ if (level !== current) {
1848
+ changes.push({
1849
+ from,
1850
+ to: from + current + (spaces?.length ?? 0),
1851
+ insert: "#".repeat(level) + (level > 0 ? " " : "")
1852
+ });
1853
+ }
1854
+ }
1855
+ if (changes.length) {
1856
+ view.dispatch({
1857
+ changes
1858
+ });
1859
+ }
1860
+ return true;
1861
+ };
1862
+ var toggleStyle = (mark2) => (view) => {
1863
+ const { ranges } = view.state.selection;
1864
+ for (const range of ranges) {
1865
+ if (range.from === range.to) {
1866
+ return false;
1867
+ }
1868
+ view.dispatch({
1869
+ changes: [
1870
+ {
1871
+ from: range.from,
1872
+ insert: mark2
1873
+ },
1874
+ {
1875
+ from: range.to,
1876
+ insert: mark2
1877
+ }
1878
+ ]
1879
+ });
1880
+ }
1881
+ return true;
1882
+ };
1883
+ var snippets = {
1884
+ codeblock: snippet([
1885
+ "```#{lang}",
1886
+ " #{}",
1887
+ "```"
1888
+ ].join("\n")),
1889
+ table: snippet([
1890
+ "| #{col1} | #{col2} |",
1891
+ "| ---- | ---- |",
1892
+ "| #{val1} | #{val2} |",
1893
+ "| #{val3} | #{val4} |"
1894
+ ].join("\n"))
1895
+ };
1896
+ var insertCodeblock = (view) => {
1897
+ const { selection: { main }, doc } = view.state;
1898
+ const { number } = doc.lineAt(main.anchor);
1899
+ const { from } = doc.line(number);
1900
+ snippets.codeblock(view, null, from, from);
1901
+ };
1902
+ var insertTable = (view) => {
1903
+ const { selection: { main }, doc } = view.state;
1904
+ const { number } = doc.lineAt(main.anchor);
1905
+ const { from } = doc.line(number);
1906
+ snippets.table(view, null, from, from);
1907
+ };
1908
+ var toggleBold = toggleStyle("**");
1909
+ var toggleItalic = toggleStyle("_");
1910
+ var toggleStrikethrough = toggleStyle("~~");
1911
+ var toggleList = (view) => {
1912
+ };
1913
+ var formatting = (options = {}) => {
1914
+ return [
1915
+ keymap5.of([
1916
+ {
1917
+ key: "meta-b",
1918
+ run: toggleBold
1919
+ }
1920
+ ]),
1921
+ styling()
1922
+ ];
1923
+ };
1924
+ var styling = () => {
1925
+ const buildDecorations7 = (view) => {
1926
+ const builder = new RangeSetBuilder2();
1927
+ const { state } = view;
1928
+ const cursor = state.selection.main.head;
1929
+ const replace = (node, marks) => {
1930
+ if (cursor <= node.from || cursor >= node.to) {
1931
+ for (const mark2 of marks) {
1932
+ builder.add(mark2.from, mark2.to, Decoration4.replace({}));
1933
+ }
1934
+ }
1935
+ };
1936
+ for (const { from, to } of view.visibleRanges) {
1937
+ syntaxTree2(state).iterate({
1938
+ enter: (node) => {
1939
+ switch (node.name) {
1940
+ case "Emphasis":
1941
+ case "StrongEmphasis": {
1942
+ const marks = node.node.getChildren("EmphasisMark");
1943
+ replace(node, marks);
1944
+ break;
1945
+ }
1946
+ case "Strikethrough": {
1947
+ const marks = node.node.getChildren("StrikethroughMark");
1948
+ replace(node, marks);
1949
+ break;
1950
+ }
1951
+ }
1952
+ },
1953
+ from,
1954
+ to
1955
+ });
1956
+ }
1957
+ return builder.finish();
1958
+ };
1959
+ return [
1960
+ ViewPlugin4.fromClass(class {
1961
+ constructor(view) {
1962
+ this.decorations = buildDecorations7(view);
1963
+ }
1964
+ update(update2) {
1965
+ this.decorations = buildDecorations7(update2.view);
1966
+ }
1967
+ }, {
1968
+ decorations: (value) => value.decorations
1969
+ })
1970
+ ];
1971
+ };
1972
+
1973
+ // packages/ui/react-ui-editor/src/extensions/markdown/heading.ts
1974
+ import { syntaxTree as syntaxTree3 } from "@codemirror/language";
1975
+ import { RangeSetBuilder as RangeSetBuilder3 } from "@codemirror/state";
1976
+ import { Decoration as Decoration5, ViewPlugin as ViewPlugin5 } from "@codemirror/view";
1977
+ var buildDecorations2 = (view) => {
1978
+ const builder = new RangeSetBuilder3();
1979
+ const { state } = view;
1980
+ const cursor = state.selection.main.head;
1981
+ for (const { from, to } of view.visibleRanges) {
1982
+ syntaxTree3(state).iterate({
1983
+ enter: (node) => {
1984
+ switch (node.name) {
1985
+ case "ATXHeading1":
1986
+ case "ATXHeading2":
1987
+ case "ATXHeading3":
1988
+ case "ATXHeading4":
1989
+ case "ATXHeading5":
1990
+ case "ATXHeading6": {
1991
+ const mark2 = node.node.getChild("HeaderMark");
1992
+ if (mark2) {
1993
+ if (!view.hasFocus || view.state.readOnly || cursor < node.from || cursor > node.to) {
1994
+ builder.add(mark2.from, mark2.to + 1, Decoration5.replace({}));
1995
+ }
1996
+ }
1997
+ }
1998
+ }
1999
+ },
2000
+ from,
2001
+ to
2002
+ });
2003
+ }
2004
+ return builder.finish();
2005
+ };
2006
+ var heading2 = () => {
2007
+ return [
2008
+ ViewPlugin5.fromClass(class {
2009
+ constructor(view) {
2010
+ this.decorations = buildDecorations2(view);
2011
+ }
2012
+ update(update2) {
2013
+ this.decorations = buildDecorations2(update2.view);
2014
+ }
2015
+ }, {
2016
+ decorations: (value) => value.decorations
2017
+ })
2018
+ ];
2019
+ };
2020
+
2021
+ // packages/ui/react-ui-editor/src/extensions/markdown/hr.ts
2022
+ import { syntaxTree as syntaxTree4 } from "@codemirror/language";
2023
+ import { RangeSetBuilder as RangeSetBuilder4 } from "@codemirror/state";
2024
+ import { Decoration as Decoration6, EditorView as EditorView9, ViewPlugin as ViewPlugin6, WidgetType as WidgetType3 } from "@codemirror/view";
2025
+ var styles4 = EditorView9.baseTheme({
2026
+ "& .cm-hr": {
2027
+ // Note that block-level decorations should not have vertical margins,
2028
+ borderTop: `1px solid ${getToken("extend.colors.neutral.200")}`
2029
+ }
2030
+ });
2031
+ var HorizontalRuleWidget = class extends WidgetType3 {
2032
+ toDOM() {
2033
+ const el = document.createElement("div");
2034
+ el.className = "cm-hr";
2035
+ return el;
2036
+ }
2037
+ };
2038
+ var decoration = Decoration6.replace({
2039
+ widget: new HorizontalRuleWidget()
2040
+ });
2041
+ var buildDecorations3 = (view) => {
2042
+ const builder = new RangeSetBuilder4();
2043
+ const { state } = view;
2044
+ const cursor = state.selection.main.head;
2045
+ for (const { from, to } of view.visibleRanges) {
2046
+ syntaxTree4(state).iterate({
2047
+ enter: (node) => {
2048
+ if (node.name === "HorizontalRule") {
2049
+ if (cursor <= node.from || cursor >= node.to) {
2050
+ builder.add(node.from, node.to, decoration);
2051
+ }
2052
+ }
2053
+ },
2054
+ from,
2055
+ to
2056
+ });
2057
+ }
2058
+ return builder.finish();
2059
+ };
2060
+ var hr = () => {
2061
+ return [
2062
+ ViewPlugin6.fromClass(class {
2063
+ constructor(view) {
2064
+ this.decorations = buildDecorations3(view);
2065
+ }
2066
+ update(update2) {
2067
+ this.decorations = buildDecorations3(update2.view);
2068
+ }
2069
+ }, {
2070
+ decorations: (value) => value.decorations
2071
+ }),
2072
+ styles4
2073
+ ];
2074
+ };
2075
+
2076
+ // packages/ui/react-ui-editor/src/extensions/markdown/image.ts
2077
+ import { syntaxTree as syntaxTree5 } from "@codemirror/language";
2078
+ import { StateField as StateField3 } from "@codemirror/state";
2079
+ import { Decoration as Decoration7, EditorView as EditorView10, WidgetType as WidgetType4 } from "@codemirror/view";
2080
+ var image = (options = {}) => {
2081
+ return StateField3.define({
2082
+ create: (state) => {
2083
+ return Decoration7.set(buildDecorations4(0, state.doc.length, state));
2084
+ },
2085
+ update: (value, tr) => {
2086
+ if (!tr.docChanged && !tr.selection) {
2087
+ return value;
2088
+ }
2089
+ const cursor = tr.state.selection.main.head;
2090
+ const oldCursor = tr.changes.mapPos(tr.startState.selection.main.head);
2091
+ let from = Math.min(cursor, oldCursor);
2092
+ let to = Math.max(cursor, oldCursor);
2093
+ tr.changes.iterChangedRanges((fromA, toA, fromB, toB) => {
2094
+ from = Math.min(from, fromB);
2095
+ to = Math.max(to, toB);
2096
+ });
2097
+ from = tr.state.doc.lineAt(from).from;
2098
+ to = tr.state.doc.lineAt(to).to;
2099
+ return value.map(tr.changes).update({
2100
+ filterFrom: from,
2101
+ filterTo: to,
2102
+ filter: () => false,
2103
+ add: buildDecorations4(from, to, tr.state)
2104
+ });
2105
+ },
2106
+ provide: (field) => EditorView10.decorations.from(field)
2107
+ });
2108
+ };
2109
+ var buildDecorations4 = (from, to, state) => {
2110
+ const decorations = [];
2111
+ const cursor = state.selection.main.head;
2112
+ syntaxTree5(state).iterate({
2113
+ enter: (node) => {
2114
+ if (node.name === "Image") {
2115
+ const urlNode = node.node.getChild("URL");
2116
+ if (urlNode) {
2117
+ const hide = state.readOnly || cursor < node.from || cursor > node.to;
2118
+ const url = state.sliceDoc(urlNode.from, urlNode.to);
2119
+ decorations.push(Decoration7.replace({
2120
+ block: true,
2121
+ widget: new ImageWidget(url)
2122
+ }).range(hide ? node.from : node.to, node.to));
2123
+ }
2124
+ }
2125
+ },
2126
+ from,
2127
+ to
2128
+ });
2129
+ return decorations;
2130
+ };
2131
+ var ImageWidget = class extends WidgetType4 {
2132
+ constructor(_url) {
2133
+ super();
2134
+ this._url = _url;
2135
+ }
2136
+ eq(other) {
2137
+ return this._url === other._url;
2138
+ }
2139
+ toDOM(view) {
2140
+ const img = document.createElement("img");
2141
+ img.setAttribute("src", this._url);
2142
+ img.setAttribute("class", "cm-image");
2143
+ img.onload = () => img.classList.add("cm-loaded-image");
2144
+ return img;
2145
+ }
2146
+ };
2147
+
2148
+ // packages/ui/react-ui-editor/src/extensions/markdown/link.ts
2149
+ import { syntaxTree as syntaxTree6 } from "@codemirror/language";
2150
+ import { RangeSetBuilder as RangeSetBuilder5 } from "@codemirror/state";
2151
+ import { hoverTooltip as hoverTooltip2, Decoration as Decoration8, ViewPlugin as ViewPlugin7, WidgetType as WidgetType5 } from "@codemirror/view";
2152
+ import { tooltipContent } from "@dxos/react-ui-theme";
2153
+ var link = (options = {}) => {
2154
+ const extensions = [
2155
+ ViewPlugin7.fromClass(class {
2156
+ constructor(view) {
2157
+ this.decorations = buildDecorations5(view, options);
2158
+ }
2159
+ update(update2) {
2160
+ if (update2.docChanged || update2.viewportChanged || update2.selectionSet) {
2161
+ this.decorations = buildDecorations5(update2.view, options);
2162
+ }
2163
+ }
2164
+ }, {
2165
+ decorations: (value) => value.decorations
2166
+ })
2167
+ ];
2168
+ if (options.onHover) {
2169
+ extensions.push(
2170
+ // https://codemirror.net/examples/tooltip
2171
+ // https://codemirror.net/docs/ref/#view.hoverTooltip
2172
+ // https://github.com/codemirror/view/blob/main/src/tooltip.ts
2173
+ hoverTooltip2((view, pos, side) => {
2174
+ const syntax = syntaxTree6(view.state).resolveInner(pos, side);
2175
+ let link2 = null;
2176
+ for (let i = 0, node = syntax; !link2 && node && i < 5; node = node.parent, i++) {
2177
+ link2 = node.name === "Link" ? node : null;
2178
+ }
2179
+ const url = link2 && link2.getChild("URL");
2180
+ if (!url || !link2) {
2181
+ return null;
2182
+ }
2183
+ const urlText = view.state.sliceDoc(url.from, url.to);
2184
+ return {
2185
+ pos: link2.from,
2186
+ end: link2.to,
2187
+ above: true,
2188
+ create: () => {
2189
+ const el = document.createElement("div");
2190
+ el.className = tooltipContent({}, "pli-2 plb-1");
2191
+ options.onHover(el, urlText);
2192
+ return {
2193
+ dom: el,
2194
+ offset: {
2195
+ x: 0,
2196
+ y: 4
2197
+ }
2198
+ };
2199
+ }
2200
+ };
2201
+ })
2202
+ );
2203
+ }
2204
+ return extensions;
2205
+ };
2206
+ var LinkButton = class extends WidgetType5 {
2207
+ constructor(_url, _onAttach) {
2208
+ super();
2209
+ this._url = _url;
2210
+ this._onAttach = _onAttach;
2211
+ }
2212
+ eq(other) {
2213
+ return this._url === other._url;
2214
+ }
2215
+ toDOM(view) {
2216
+ const el = document.createElement("span");
2217
+ this._onAttach(el, this._url);
2218
+ return el;
2219
+ }
2220
+ };
2221
+ var LinkText = class extends WidgetType5 {
2222
+ constructor(_text, _url) {
2223
+ super();
2224
+ this._text = _text;
2225
+ this._url = _url;
2226
+ }
2227
+ eq(other) {
2228
+ return this._url === other._url;
2229
+ }
2230
+ toDOM(view) {
2231
+ const link2 = document.createElement("a");
2232
+ link2.setAttribute("class", "cm-link");
2233
+ link2.textContent = this._text;
2234
+ if (this._url) {
2235
+ link2.setAttribute("rel", "noreferrer");
2236
+ link2.setAttribute("target", "_blank");
2237
+ link2.href = this._url;
2238
+ } else {
2239
+ link2.onclick = () => {
2240
+ view.dispatch({
2241
+ selection: {
2242
+ anchor: view.posAtDOM(link2)
2243
+ }
2244
+ });
2245
+ };
2246
+ }
2247
+ return link2;
2248
+ }
2249
+ };
2250
+ var buildDecorations5 = (view, options) => {
2251
+ const builder = new RangeSetBuilder5();
2252
+ const { state } = view;
2253
+ const cursor = state.selection.main.head;
2254
+ for (const { from, to } of view.visibleRanges) {
2255
+ syntaxTree6(state).iterate({
2256
+ enter: (node) => {
2257
+ if (node.name === "Link") {
2258
+ const marks = node.node.getChildren("LinkMark");
2259
+ const text = marks.length >= 2 ? state.sliceDoc(marks[0].to, marks[1].from) : "";
2260
+ const urlNode = node.node.getChild("URL");
2261
+ const url = urlNode ? state.sliceDoc(urlNode.from, urlNode.to) : "";
2262
+ if (!url) {
2263
+ return false;
2264
+ }
2265
+ if (!view.hasFocus || state.readOnly || cursor < node.from || cursor > node.to) {
2266
+ builder.add(node.from, node.to, Decoration8.replace({
2267
+ widget: new LinkText(text, options.link ? url : void 0)
2268
+ }));
2269
+ }
2270
+ if (options.onRender) {
2271
+ builder.add(node.to, node.to, Decoration8.replace({
2272
+ widget: new LinkButton(url, options.onRender)
2273
+ }));
2274
+ }
2275
+ return false;
2276
+ }
2277
+ },
2278
+ from,
2279
+ to
2280
+ });
2281
+ }
2282
+ return builder.finish();
2283
+ };
2284
+
2285
+ // packages/ui/react-ui-editor/src/extensions/markdown/table.ts
2286
+ import { syntaxTree as syntaxTree7 } from "@codemirror/language";
2287
+ import { RangeSetBuilder as RangeSetBuilder6, StateField as StateField4 } from "@codemirror/state";
2288
+ import { Decoration as Decoration9, EditorView as EditorView11, WidgetType as WidgetType6 } from "@codemirror/view";
2289
+ var table = (options = {}) => {
2290
+ return StateField4.define({
2291
+ create: (state) => update(state, options),
2292
+ update: (_, tr) => update(tr.state, options),
2293
+ provide: (field) => EditorView11.decorations.from(field)
2294
+ });
2295
+ };
2296
+ var update = (state, options) => {
2297
+ const builder = new RangeSetBuilder6();
2298
+ const cursor = state.selection.main.head;
2299
+ const tables = [];
2300
+ const getTable = () => tables[tables.length - 1];
2301
+ const getRow = () => {
1946
2302
  const table2 = getTable();
1947
2303
  return table2.rows?.[table2.rows.length - 1];
1948
2304
  };
1949
- syntaxTree3(state).iterate({
2305
+ syntaxTree7(state).iterate({
1950
2306
  enter: (node) => {
1951
2307
  switch (node.name) {
1952
2308
  case "Table": {
@@ -1978,16 +2334,16 @@ var update = (state, options) => {
1978
2334
  });
1979
2335
  tables.forEach((table2) => {
1980
2336
  const hide = state.readOnly || cursor < table2.from || cursor > table2.to;
1981
- hide && builder.add(table2.from, table2.to, Decoration7.replace({
2337
+ hide && builder.add(table2.from, table2.to, Decoration9.replace({
1982
2338
  widget: new TableWidget(table2)
1983
2339
  }));
1984
- builder.add(table2.from, table2.to, Decoration7.mark({
2340
+ builder.add(table2.from, table2.to, Decoration9.mark({
1985
2341
  class: "cm-table"
1986
2342
  }));
1987
2343
  });
1988
2344
  return builder.finish();
1989
2345
  };
1990
- var TableWidget = class extends WidgetType5 {
2346
+ var TableWidget = class extends WidgetType6 {
1991
2347
  constructor(_table) {
1992
2348
  super();
1993
2349
  this._table = _table;
@@ -2024,11 +2380,20 @@ var TableWidget = class extends WidgetType5 {
2024
2380
  }
2025
2381
  };
2026
2382
 
2027
- // packages/ui/react-ui-editor/src/extensions/tasklist.ts
2028
- import { syntaxTree as syntaxTree4 } from "@codemirror/language";
2029
- import { RangeSetBuilder as RangeSetBuilder3 } from "@codemirror/state";
2030
- import { EditorView as EditorView11, Decoration as Decoration8, WidgetType as WidgetType6, ViewPlugin as ViewPlugin6 } from "@codemirror/view";
2031
- var CheckboxWidget = class extends WidgetType6 {
2383
+ // packages/ui/react-ui-editor/src/extensions/markdown/tasklist.ts
2384
+ import { syntaxTree as syntaxTree8 } from "@codemirror/language";
2385
+ import { RangeSetBuilder as RangeSetBuilder7 } from "@codemirror/state";
2386
+ import { EditorView as EditorView12, Decoration as Decoration10, WidgetType as WidgetType7, ViewPlugin as ViewPlugin8 } from "@codemirror/view";
2387
+ var styles5 = EditorView12.baseTheme({
2388
+ "& .cm-task": {
2389
+ color: getToken("extend.colors.blue.500")
2390
+ },
2391
+ "& .cm-task-checkbox": {
2392
+ marginLeft: "4px",
2393
+ marginRight: "4px"
2394
+ }
2395
+ });
2396
+ var CheckboxWidget = class extends WidgetType7 {
2032
2397
  constructor(_checked) {
2033
2398
  super();
2034
2399
  this._checked = _checked;
@@ -2038,6 +2403,7 @@ var CheckboxWidget = class extends WidgetType6 {
2038
2403
  }
2039
2404
  toDOM(view) {
2040
2405
  const input = document.createElement("input");
2406
+ input.className = "cm-task-checkbox";
2041
2407
  input.type = "checkbox";
2042
2408
  input.checked = this._checked;
2043
2409
  if (view.state.readOnly) {
@@ -2064,39 +2430,27 @@ var CheckboxWidget = class extends WidgetType6 {
2064
2430
  return false;
2065
2431
  }
2066
2432
  };
2067
- var checkedDeco = Decoration8.replace({
2433
+ var checkedDecoration = Decoration10.replace({
2068
2434
  widget: new CheckboxWidget(true)
2069
2435
  });
2070
- var uncheckedDeco = Decoration8.replace({
2436
+ var uncheckedDecoration = Decoration10.replace({
2071
2437
  widget: new CheckboxWidget(false)
2072
2438
  });
2073
- var tasklist = (options = {}) => {
2074
- return ViewPlugin6.fromClass(class {
2075
- constructor(view) {
2076
- this.decorations = buildDecorations3(view);
2077
- }
2078
- update(update2) {
2079
- if (update2.docChanged || update2.viewportChanged || update2.selectionSet) {
2080
- this.decorations = buildDecorations3(update2.view);
2081
- }
2082
- }
2083
- }, {
2084
- decorations: (v) => v.decorations,
2085
- provide: (plugin) => EditorView11.atomicRanges.of((view) => {
2086
- return view.plugin(plugin)?.decorations || Decoration8.none;
2087
- })
2088
- });
2089
- };
2090
- var buildDecorations3 = (view) => {
2091
- const builder = new RangeSetBuilder3();
2439
+ var buildDecorations6 = (view) => {
2440
+ const builder = new RangeSetBuilder7();
2092
2441
  const { state } = view;
2093
2442
  const cursor = state.selection.main.head;
2094
2443
  for (const { from, to } of view.visibleRanges) {
2095
- syntaxTree4(state).iterate({
2444
+ syntaxTree8(state).iterate({
2096
2445
  enter: (node) => {
2097
- if (node.name === "TaskMarker" && (cursor < node.from || cursor > node.to)) {
2098
- const checked = state.doc.sliceString(node.from + 1, node.to - 1) === "x";
2099
- builder.add(node.from, node.to, checked ? checkedDeco : uncheckedDeco);
2446
+ if (node.name === "TaskMarker") {
2447
+ if (cursor < node.from || cursor > node.to) {
2448
+ const checked = state.doc.sliceString(node.from + 1, node.to - 1) === "x";
2449
+ builder.add(node.from - 2, node.from - 1, Decoration10.mark({
2450
+ class: "cm-task"
2451
+ }));
2452
+ builder.add(node.from, node.to, checked ? checkedDecoration : uncheckedDecoration);
2453
+ }
2100
2454
  }
2101
2455
  },
2102
2456
  from,
@@ -2105,9 +2459,60 @@ var buildDecorations3 = (view) => {
2105
2459
  }
2106
2460
  return builder.finish();
2107
2461
  };
2462
+ var tasklist = (options = {}) => {
2463
+ return [
2464
+ ViewPlugin8.fromClass(class {
2465
+ constructor(view) {
2466
+ this.decorations = buildDecorations6(view);
2467
+ }
2468
+ update(update2) {
2469
+ if (update2.docChanged || update2.viewportChanged || update2.selectionSet) {
2470
+ this.decorations = buildDecorations6(update2.view);
2471
+ }
2472
+ }
2473
+ }, {
2474
+ decorations: (value) => value.decorations
2475
+ }),
2476
+ styles5
2477
+ ];
2478
+ };
2479
+
2480
+ // packages/ui/react-ui-editor/src/extensions/mention.ts
2481
+ import { autocompletion as autocompletion2 } from "@codemirror/autocomplete";
2482
+ var mention = ({ onSearch }) => {
2483
+ return autocompletion2({
2484
+ // TODO(burdon): Not working.
2485
+ activateOnTyping: true,
2486
+ // activateOnTypingDelay: 100,
2487
+ // selectOnOpen: true,
2488
+ closeOnBlur: false,
2489
+ // defaultKeymap: false,
2490
+ icons: false,
2491
+ override: [
2492
+ (context) => {
2493
+ console.log(context);
2494
+ const match = context.matchBefore(/@(\w+)?/);
2495
+ if (!match || match.from === match.to && !context.explicit) {
2496
+ return null;
2497
+ }
2498
+ return {
2499
+ from: match.from,
2500
+ options: onSearch(match.text.slice(1).toLowerCase()).map((value) => ({
2501
+ label: `@${value}`
2502
+ }))
2503
+ };
2504
+ }
2505
+ ]
2506
+ });
2507
+ };
2508
+
2509
+ // packages/ui/react-ui-editor/src/extensions/outliner.ts
2510
+ var outliner = (options = {}) => {
2511
+ return [];
2512
+ };
2108
2513
 
2109
2514
  // packages/ui/react-ui-editor/src/extensions/typewriter.ts
2110
- import { keymap as keymap5 } from "@codemirror/view";
2515
+ import { keymap as keymap6 } from "@codemirror/view";
2111
2516
  var defaultItems = [
2112
2517
  "hello world!",
2113
2518
  "this is a test.",
@@ -2117,7 +2522,7 @@ var typewriter = ({ delay = 75, items = defaultItems } = {}) => {
2117
2522
  let t;
2118
2523
  let idx = 0;
2119
2524
  return [
2120
- keymap5.of([
2525
+ keymap6.of([
2121
2526
  {
2122
2527
  // Reset.
2123
2528
  key: "alt-meta-'",
@@ -2163,27 +2568,6 @@ var typewriter = ({ delay = 75, items = defaultItems } = {}) => {
2163
2568
  ];
2164
2569
  };
2165
2570
 
2166
- // packages/ui/react-ui-editor/src/extensions/yjs/yjs.ts
2167
- import { yCollab } from "y-codemirror.next";
2168
-
2169
- // packages/ui/react-ui-editor/src/extensions/yjs/cursor.ts
2170
- import * as Y from "yjs";
2171
- import { arrayToString, stringToArray } from "@dxos/util";
2172
- var cursorConverter2 = (text) => ({
2173
- toCursor: (index, assoc) => {
2174
- return arrayToString(Y.encodeRelativePosition(Y.createRelativePositionFromTypeIndex(text, index, assoc)));
2175
- },
2176
- fromCursor: (cursor) => {
2177
- return Y.createAbsolutePositionFromRelativePosition(Y.decodeRelativePosition(stringToArray(cursor)), text.doc)?.index ?? 0;
2178
- }
2179
- });
2180
-
2181
- // packages/ui/react-ui-editor/src/extensions/yjs/yjs.ts
2182
- var yjs = (content, awareness2) => [
2183
- Cursor.converter.of(cursorConverter2(content)),
2184
- yCollab(content, awareness2)
2185
- ];
2186
-
2187
2571
  // packages/ui/react-ui-editor/src/themes/default.ts
2188
2572
  import get3 from "lodash.get";
2189
2573
  var defaultTheme = {
@@ -2215,8 +2599,9 @@ var defaultTheme = {
2215
2599
  outline: "none"
2216
2600
  },
2217
2601
  ".cm-scroller": {
2218
- overflow: "visible",
2219
- fontFamily: get3(tokens, "fontFamily.mono", []).join(",")
2602
+ // overflow: 'visible',
2603
+ fontFamily: get3(tokens, "fontFamily.mono", []).join(","),
2604
+ lineHeight: 1.4
2220
2605
  },
2221
2606
  ".cm-content": {
2222
2607
  padding: 0,
@@ -2224,11 +2609,11 @@ var defaultTheme = {
2224
2609
  fontSize: "16px"
2225
2610
  },
2226
2611
  "&light .cm-content": {
2227
- color: get3(tokens, "extend.colors.neutral.900", "black"),
2612
+ color: get3(tokens, "extend.semanticColors.base.fg.light", "black"),
2228
2613
  caretColor: "black"
2229
2614
  },
2230
2615
  "&dark .cm-content": {
2231
- color: get3(tokens, "extend.colors.neutral.100", "white"),
2616
+ color: get3(tokens, "extend.semanticColors.base.fg.dark", "white"),
2232
2617
  caretColor: "white"
2233
2618
  },
2234
2619
  //
@@ -2240,8 +2625,11 @@ var defaultTheme = {
2240
2625
  "&dark .cm-cursor, &dark .cm-dropCursor": {
2241
2626
  borderLeft: "2px solid white"
2242
2627
  },
2243
- ".cm-placeholder": {
2244
- fontWeight: 100
2628
+ "&light .cm-placeholder": {
2629
+ color: get3(tokens, "extend.semanticColors.description.light", "rgba(0,0,0,.2)")
2630
+ },
2631
+ "&dark .cm-placeholder": {
2632
+ color: get3(tokens, "extend.semanticColors.description.dark", "rgba(255,255,255,.2)")
2245
2633
  },
2246
2634
  //
2247
2635
  // line
@@ -2250,7 +2638,7 @@ var defaultTheme = {
2250
2638
  paddingInline: 0
2251
2639
  },
2252
2640
  ".cm-activeLine": {
2253
- background: "inherit"
2641
+ background: "transparent"
2254
2642
  },
2255
2643
  //
2256
2644
  // Selection
@@ -2421,90 +2809,88 @@ var codeTheme = {
2421
2809
  };
2422
2810
 
2423
2811
  // packages/ui/react-ui-editor/src/components/TextEditor/TextEditor.tsx
2812
+ var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/components/TextEditor/TextEditor.tsx";
2424
2813
  var EditorModes = [
2425
2814
  "default",
2426
2815
  "vim"
2427
2816
  ];
2428
- var BaseTextEditor = /* @__PURE__ */ forwardRef(({ model, focus, selection, readonly, comments: comments2, extensions = [], editorMode, theme, slots = defaultSlots }, forwardedRef) => {
2429
- const tabsterDOMAttribute = useFocusableGroup({
2430
- tabBehavior: "limited"
2431
- });
2817
+ var BaseTextEditor = /* @__PURE__ */ forwardRef(({ model, readonly, autoFocus, scrollTo, selection, editorMode, theme, slots = defaultSlots, extensions = [], debug }, forwardedRef) => {
2432
2818
  const { themeMode } = useThemeContext();
2433
2819
  const rootRef = useRef(null);
2434
2820
  const [view, setView] = useState(null);
2435
2821
  useImperativeHandle(forwardedRef, () => view, [
2436
2822
  view
2437
2823
  ]);
2438
- useEffect(() => {
2439
- if (view && focus) {
2440
- view.focus();
2441
- }
2442
- }, [
2443
- view,
2444
- focus
2445
- ]);
2446
- const { awareness: awareness2, peer } = model;
2447
- useEffect(() => {
2448
- if (awareness2 && peer) {
2449
- awareness2.setLocalStateField("user", {
2450
- name: peer.name ?? generateName(peer.id),
2451
- color: getColorForValue({
2452
- value: peer.id,
2453
- type: "color"
2454
- }),
2455
- colorLight: getColorForValue({
2456
- value: peer.id,
2457
- themeMode,
2458
- type: "highlight"
2459
- })
2460
- });
2461
- }
2462
- }, [
2463
- awareness2,
2464
- peer,
2465
- themeMode
2466
- ]);
2467
- useEffect(() => {
2468
- if (view && comments2 !== void 0) {
2469
- view.dispatch({
2470
- effects: setCommentRange.of({
2471
- model,
2472
- comments: comments2
2473
- })
2474
- });
2824
+ useEffect2(() => {
2825
+ if (autoFocus && !view?.hasFocus) {
2826
+ if (view?.state.selection.main?.from === 0) {
2827
+ const { to } = view.state.doc.lineAt(0);
2828
+ view?.dispatch({
2829
+ selection: {
2830
+ anchor: to
2831
+ }
2832
+ });
2833
+ }
2834
+ view?.focus();
2475
2835
  }
2476
2836
  }, [
2477
2837
  view,
2478
- comments2
2838
+ autoFocus
2479
2839
  ]);
2480
- useEffect(() => {
2840
+ useEffect2(() => {
2481
2841
  if (!model || !rootRef.current) {
2482
2842
  return;
2483
2843
  }
2484
2844
  const state = EditorState2.create({
2485
2845
  doc: model.text(),
2486
- // TODO(burdon): Composer should store and set selection when switching documents.
2487
2846
  selection,
2488
2847
  extensions: [
2489
- readonly && EditorState2.readOnly.of(readonly),
2490
- // TODO(burdon): Factor out VIM mode? (manage via MarkdownPlugin).
2491
- editorMode === "vim" && vim(),
2848
+ // TODO(burdon): Doesn't catch errors in keymap functions.
2849
+ EditorView13.exceptionSink.of((err) => {
2850
+ log2.catch(err, void 0, {
2851
+ F: __dxlog_file3,
2852
+ L: 134,
2853
+ S: void 0,
2854
+ C: (f, a) => f(...a)
2855
+ });
2856
+ }),
2492
2857
  // Theme.
2493
- // TODO(burdon): Make theme configurable.
2494
- EditorView12.baseTheme(defaultTheme),
2495
- EditorView12.theme(theme ?? {}),
2496
- EditorView12.darkTheme.of(themeMode === "dark"),
2858
+ // TODO(burdon): Make configurable.
2859
+ EditorView13.baseTheme(defaultTheme),
2860
+ EditorView13.theme(theme ?? {}),
2861
+ EditorView13.darkTheme.of(themeMode === "dark"),
2862
+ EditorView13.editorAttributes.of({
2863
+ class: slots.editor?.className ?? ""
2864
+ }),
2865
+ EditorView13.contentAttributes.of({
2866
+ class: slots.content?.className ?? ""
2867
+ }),
2868
+ // State.
2869
+ EditorView13.editable.of(!readonly),
2870
+ EditorState2.readOnly.of(!!readonly),
2497
2871
  // Storage and replication.
2872
+ // NOTE: This must come before user extensions.
2498
2873
  model.extension,
2874
+ // TODO(burdon): Factor out? (Requires special handling for Escape/Enter below).
2875
+ editorMode === "vim" && vim(),
2499
2876
  // Custom.
2500
2877
  ...extensions
2501
- ].filter(Boolean)
2878
+ ].filter(isNotFalsy3)
2502
2879
  });
2503
- view?.destroy();
2504
- const newView = new EditorView12({
2880
+ const newView = new EditorView13({
2881
+ state,
2505
2882
  parent: rootRef.current,
2506
- state
2883
+ scrollTo,
2884
+ // NOTE: Uncomment to debug/monitor all transactions.
2885
+ // https://codemirror.net/docs/ref/#view.EditorView.dispatch
2886
+ dispatchTransactions: (trs, view2) => {
2887
+ if (debug) {
2888
+ logChanges(trs);
2889
+ }
2890
+ view2.update(trs);
2891
+ }
2507
2892
  });
2893
+ view?.destroy();
2508
2894
  setView(newView);
2509
2895
  return () => {
2510
2896
  newView?.destroy();
@@ -2520,8 +2906,14 @@ var BaseTextEditor = /* @__PURE__ */ forwardRef(({ model, focus, selection, read
2520
2906
  const handleKeyUp = useCallback((event) => {
2521
2907
  const { key, altKey, shiftKey, metaKey, ctrlKey } = event;
2522
2908
  switch (key) {
2909
+ case "Enter": {
2910
+ view?.focus();
2911
+ break;
2912
+ }
2523
2913
  case "Escape": {
2524
- editorMode === "vim" && (altKey || shiftKey || metaKey || ctrlKey) && rootRef.current?.focus();
2914
+ if (editorMode === "vim" && (altKey || shiftKey || metaKey || ctrlKey)) {
2915
+ view?.focus();
2916
+ }
2525
2917
  break;
2526
2918
  }
2527
2919
  }
@@ -2532,24 +2924,24 @@ var BaseTextEditor = /* @__PURE__ */ forwardRef(({ model, focus, selection, read
2532
2924
  return /* @__PURE__ */ React.createElement("div", {
2533
2925
  key: model.id,
2534
2926
  role: "none",
2535
- ref: rootRef,
2536
2927
  tabIndex: 0,
2537
- onKeyUp: handleKeyUp,
2538
2928
  ...slots.root,
2539
- ...editorMode !== "vim" && tabsterDOMAttribute
2929
+ // {...(editorMode !== 'vim' && tabsterDOMAttribute)}
2930
+ onKeyUp: handleKeyUp,
2931
+ ref: rootRef
2540
2932
  });
2541
2933
  });
2542
- var TextEditor = /* @__PURE__ */ forwardRef(({ readonly, placeholder: placeholder3, extensions = [], theme = textTheme, slots, ...props }, forwardedRef) => {
2934
+ var TextEditor = /* @__PURE__ */ forwardRef(({ readonly, placeholder: placeholder3, lineWrapping, theme = textTheme, slots, extensions = [], ...props }, forwardedRef) => {
2543
2935
  const { themeMode } = useThemeContext();
2544
2936
  const updatedSlots = defaultsDeep2({}, slots, defaultTextSlots);
2545
2937
  return /* @__PURE__ */ React.createElement(BaseTextEditor, {
2546
2938
  ref: forwardedRef,
2547
2939
  readonly,
2548
2940
  extensions: [
2549
- basicBundle({
2550
- readonly,
2941
+ createBasicBundle({
2551
2942
  themeMode,
2552
- placeholder: placeholder3
2943
+ placeholder: placeholder3,
2944
+ lineWrapping
2553
2945
  }),
2554
2946
  ...extensions
2555
2947
  ],
@@ -2558,15 +2950,14 @@ var TextEditor = /* @__PURE__ */ forwardRef(({ readonly, placeholder: placeholde
2558
2950
  ...props
2559
2951
  });
2560
2952
  });
2561
- var MarkdownEditor = /* @__PURE__ */ forwardRef(({ readonly, placeholder: placeholder3, extensions = [], theme = markdownTheme, slots, ...props }, forwardedRef) => {
2953
+ var MarkdownEditor = /* @__PURE__ */ forwardRef(({ readonly, placeholder: placeholder3, theme = markdownTheme, slots, extensions = [], ...props }, forwardedRef) => {
2562
2954
  const { themeMode } = useThemeContext();
2563
2955
  const updatedSlots = defaultsDeep2({}, slots, defaultMarkdownSlots);
2564
2956
  return /* @__PURE__ */ React.createElement(BaseTextEditor, {
2565
2957
  ref: forwardedRef,
2566
2958
  readonly,
2567
2959
  extensions: [
2568
- markdownBundle({
2569
- readonly,
2960
+ createMarkdownExtensions({
2570
2961
  themeMode,
2571
2962
  placeholder: placeholder3
2572
2963
  }),
@@ -2579,7 +2970,10 @@ var MarkdownEditor = /* @__PURE__ */ forwardRef(({ readonly, placeholder: placeh
2579
2970
  });
2580
2971
  var defaultSlots = {
2581
2972
  root: {
2582
- className: mx3("p-2 overflow-y-auto", inputSurface)
2973
+ className: mx3("grow", focusRing)
2974
+ },
2975
+ editor: {
2976
+ className: "bs-full"
2583
2977
  }
2584
2978
  };
2585
2979
  var defaultTextSlots = {
@@ -2589,22 +2983,178 @@ var defaultMarkdownSlots = {
2589
2983
  ...defaultSlots
2590
2984
  };
2591
2985
 
2592
- // packages/ui/react-ui-editor/src/hooks/automerge.ts
2593
- import get4 from "lodash.get";
2594
- import { getRawDoc } from "@dxos/echo-schema";
2595
- import { isNotNullOrUndefined } from "@dxos/util";
2986
+ // packages/ui/react-ui-editor/src/components/Toolbar/Toolbar.tsx
2987
+ import { At, CaretRight, ChatText, Code, Image, Link, ListBullets, ListChecks, ListNumbers, TextStrikethrough, Table as Table2, TextB, TextItalic } from "@phosphor-icons/react";
2988
+ import { createContext } from "@radix-ui/react-context";
2989
+ import React2 from "react";
2990
+ import { Button, DensityProvider, Select } from "@dxos/react-ui";
2991
+ import { getSize } from "@dxos/react-ui-theme";
2992
+ var [ToolbarContextProvider, useToolbarContext] = createContext("Toolbar");
2993
+ var ToolbarRoot = ({ children, onAction }) => {
2994
+ return /* @__PURE__ */ React2.createElement(ToolbarContextProvider, {
2995
+ onAction
2996
+ }, /* @__PURE__ */ React2.createElement(DensityProvider, {
2997
+ density: "fine"
2998
+ }, /* @__PURE__ */ React2.createElement("div", {
2999
+ role: "toolbar",
3000
+ className: "flex w-full shrink-0 p-2 gap-4 items-center whitespace-nowrap overflow-hidden"
3001
+ }, children)));
3002
+ };
3003
+ var ToolbarButton = ({ Icon, onClick, title }) => {
3004
+ const { onAction } = useToolbarContext("ToolbarButton");
3005
+ const handleClick = () => {
3006
+ const action = onClick();
3007
+ if (action) {
3008
+ onAction?.(action);
3009
+ }
3010
+ };
3011
+ return /* @__PURE__ */ React2.createElement(Button, {
3012
+ variant: "ghost",
3013
+ classNames: "p-2",
3014
+ onClick: handleClick,
3015
+ title
3016
+ }, /* @__PURE__ */ React2.createElement(Icon, {
3017
+ className: getSize(5)
3018
+ }));
3019
+ };
3020
+ var ToolbarSeparator = () => /* @__PURE__ */ React2.createElement("div", {
3021
+ className: "grow"
3022
+ });
3023
+ var MarkdownHeading = () => {
3024
+ const { onAction } = useToolbarContext("MarkdownFormatting");
3025
+ return /* @__PURE__ */ React2.createElement(Select.Root, {
3026
+ defaultValue: "0",
3027
+ onValueChange: (value) => onAction?.({
3028
+ type: "heading",
3029
+ data: parseInt(value)
3030
+ })
3031
+ }, /* @__PURE__ */ React2.createElement(Select.TriggerButton, {
3032
+ classNames: "w-[8rem]"
3033
+ }), /* @__PURE__ */ React2.createElement(Select.Portal, null, /* @__PURE__ */ React2.createElement(Select.Content, null, /* @__PURE__ */ React2.createElement(Select.Viewport, null, /* @__PURE__ */ React2.createElement(Select.Option, {
3034
+ value: "0"
3035
+ }, "Paragraph"), [
3036
+ 1,
3037
+ 2,
3038
+ 3,
3039
+ 4,
3040
+ 5,
3041
+ 6
3042
+ ].map((level) => /* @__PURE__ */ React2.createElement(Select.Option, {
3043
+ key: level,
3044
+ value: String(level)
3045
+ }, "Heading ", level))))));
3046
+ };
3047
+ var MarkdownStyles = () => /* @__PURE__ */ React2.createElement("div", {
3048
+ role: "none"
3049
+ }, /* @__PURE__ */ React2.createElement(ToolbarButton, {
3050
+ Icon: TextB,
3051
+ title: "Bold",
3052
+ onClick: () => ({
3053
+ type: "bold"
3054
+ })
3055
+ }), /* @__PURE__ */ React2.createElement(ToolbarButton, {
3056
+ Icon: TextItalic,
3057
+ title: "Italic",
3058
+ onClick: () => ({
3059
+ type: "italic"
3060
+ })
3061
+ }), /* @__PURE__ */ React2.createElement(ToolbarButton, {
3062
+ Icon: TextStrikethrough,
3063
+ title: "Strike-through",
3064
+ onClick: () => ({
3065
+ type: "strikethrough"
3066
+ })
3067
+ }));
3068
+ var MarkdownLists = () => /* @__PURE__ */ React2.createElement("div", {
3069
+ role: "none"
3070
+ }, /* @__PURE__ */ React2.createElement(ToolbarButton, {
3071
+ Icon: ListBullets,
3072
+ title: "Bullet list",
3073
+ onClick: () => ({
3074
+ type: "list"
3075
+ })
3076
+ }), /* @__PURE__ */ React2.createElement(ToolbarButton, {
3077
+ Icon: ListNumbers,
3078
+ title: "Numbered list",
3079
+ onClick: () => ({
3080
+ type: "list-ordered"
3081
+ })
3082
+ }), /* @__PURE__ */ React2.createElement(ToolbarButton, {
3083
+ Icon: ListChecks,
3084
+ title: "Task list",
3085
+ onClick: () => ({
3086
+ type: "list-tasks"
3087
+ })
3088
+ }));
3089
+ var MarkdownBlocks = () => /* @__PURE__ */ React2.createElement("div", {
3090
+ role: "none"
3091
+ }, /* @__PURE__ */ React2.createElement(ToolbarButton, {
3092
+ Icon: CaretRight,
3093
+ title: "Block quite",
3094
+ onClick: () => ({
3095
+ type: "blockquote"
3096
+ })
3097
+ }), /* @__PURE__ */ React2.createElement(ToolbarButton, {
3098
+ Icon: Code,
3099
+ title: "Code block",
3100
+ onClick: () => ({
3101
+ type: "codeblock"
3102
+ })
3103
+ }), /* @__PURE__ */ React2.createElement(ToolbarButton, {
3104
+ Icon: Table2,
3105
+ title: "Table",
3106
+ onClick: () => ({
3107
+ type: "table"
3108
+ })
3109
+ }));
3110
+ var MarkdownLinks = () => /* @__PURE__ */ React2.createElement("div", {
3111
+ role: "none"
3112
+ }, /* @__PURE__ */ React2.createElement(ToolbarButton, {
3113
+ Icon: Link,
3114
+ title: "Link",
3115
+ onClick: () => ({
3116
+ type: "link"
3117
+ })
3118
+ }), /* @__PURE__ */ React2.createElement(ToolbarButton, {
3119
+ Icon: At,
3120
+ title: "Mention",
3121
+ onClick: () => ({
3122
+ type: "mention"
3123
+ })
3124
+ }), /* @__PURE__ */ React2.createElement(ToolbarButton, {
3125
+ Icon: Image,
3126
+ title: "Image",
3127
+ onClick: () => ({
3128
+ type: "image"
3129
+ })
3130
+ }));
3131
+ var MarkdownStandard = () => /* @__PURE__ */ React2.createElement(React2.Fragment, null, /* @__PURE__ */ React2.createElement(MarkdownHeading, null), /* @__PURE__ */ React2.createElement(MarkdownStyles, null), /* @__PURE__ */ React2.createElement(MarkdownLists, null), /* @__PURE__ */ React2.createElement(MarkdownBlocks, null), /* @__PURE__ */ React2.createElement(MarkdownLinks, null));
3132
+ var MarkdownExtended = () => /* @__PURE__ */ React2.createElement(Toolbar.Button, {
3133
+ Icon: ChatText,
3134
+ title: "Create comment",
3135
+ onClick: () => ({
3136
+ type: "comment"
3137
+ })
3138
+ });
3139
+ var Toolbar = {
3140
+ Root: ToolbarRoot,
3141
+ Button: ToolbarButton,
3142
+ Separator: ToolbarSeparator,
3143
+ Markdown: MarkdownStandard,
3144
+ Extended: MarkdownExtended
3145
+ };
2596
3146
 
2597
3147
  // packages/ui/react-ui-editor/src/hooks/awareness-provider.ts
2598
3148
  import { DeferredTask, Event as Event2, sleep } from "@dxos/async";
2599
3149
  import { Context as Context2 } from "@dxos/context";
2600
- import { invariant as invariant3 } from "@dxos/invariant";
3150
+ import { invariant as invariant2 } from "@dxos/invariant";
2601
3151
  import { log as log3 } from "@dxos/log";
2602
3152
  var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/hooks/awareness-provider.ts";
2603
3153
  var DEBOUNCE_INTERVAL = 100;
2604
3154
  var SpaceAwarenessProvider = class {
2605
3155
  constructor(params) {
2606
- this.remoteStateChange = new Event2();
2607
3156
  this._remoteStates = /* @__PURE__ */ new Map();
3157
+ this.remoteStateChange = new Event2();
2608
3158
  this._space = params.space;
2609
3159
  this._channel = params.channel;
2610
3160
  this._peerId = params.peerId;
@@ -2621,7 +3171,7 @@ var SpaceAwarenessProvider = class {
2621
3171
  await sleep(DEBOUNCE_INTERVAL);
2622
3172
  }
2623
3173
  });
2624
- const unsubscribe = this._space.listen(this._channel, (message) => {
3174
+ this._ctx.onDispose(this._space.listen(this._channel, (message) => {
2625
3175
  switch (message.payload.kind) {
2626
3176
  case "query": {
2627
3177
  this._handleQueryMessage();
@@ -2632,8 +3182,7 @@ var SpaceAwarenessProvider = class {
2632
3182
  break;
2633
3183
  }
2634
3184
  }
2635
- });
2636
- this._ctx.onDispose(unsubscribe);
3185
+ }));
2637
3186
  void this._space.postMessage(this._channel, {
2638
3187
  kind: "query"
2639
3188
  }).catch((err) => {
@@ -2641,7 +3190,7 @@ var SpaceAwarenessProvider = class {
2641
3190
  err
2642
3191
  }, {
2643
3192
  F: __dxlog_file4,
2644
- L: 85,
3193
+ L: 89,
2645
3194
  S: this,
2646
3195
  C: (f, a) => f(...a)
2647
3196
  });
@@ -2652,10 +3201,13 @@ var SpaceAwarenessProvider = class {
2652
3201
  this._ctx = void 0;
2653
3202
  this._postTask = void 0;
2654
3203
  }
3204
+ getRemoteStates() {
3205
+ return Array.from(this._remoteStates.values());
3206
+ }
2655
3207
  update(position) {
2656
- invariant3(this._postTask, void 0, {
3208
+ invariant2(this._postTask, void 0, {
2657
3209
  F: __dxlog_file4,
2658
- L: 96,
3210
+ L: 104,
2659
3211
  S: this,
2660
3212
  A: [
2661
3213
  "this._postTask",
@@ -2669,13 +3221,10 @@ var SpaceAwarenessProvider = class {
2669
3221
  };
2670
3222
  this._postTask.schedule();
2671
3223
  }
2672
- getRemoteStates() {
2673
- return Array.from(this._remoteStates.values());
2674
- }
2675
3224
  _handleQueryMessage() {
2676
- invariant3(this._postTask, void 0, {
3225
+ invariant2(this._postTask, void 0, {
2677
3226
  F: __dxlog_file4,
2678
- L: 111,
3227
+ L: 115,
2679
3228
  S: this,
2680
3229
  A: [
2681
3230
  "this._postTask",
@@ -2685,9 +3234,9 @@ var SpaceAwarenessProvider = class {
2685
3234
  this._postTask.schedule();
2686
3235
  }
2687
3236
  _handlePostMessage(message) {
2688
- invariant3(message.kind === "post", void 0, {
3237
+ invariant2(message.kind === "post", void 0, {
2689
3238
  F: __dxlog_file4,
2690
- L: 116,
3239
+ L: 120,
2691
3240
  S: this,
2692
3241
  A: [
2693
3242
  "message.kind === 'post'",
@@ -2699,199 +3248,240 @@ var SpaceAwarenessProvider = class {
2699
3248
  }
2700
3249
  };
2701
3250
 
2702
- // packages/ui/react-ui-editor/src/hooks/useTextModel.ts
3251
+ // packages/ui/react-ui-editor/src/hooks/defs.ts
2703
3252
  import { StateField as StateField5 } from "@codemirror/state";
2704
- import { useEffect as useEffect2, useState as useState2 } from "react";
2705
- import { isAutomergeObject } from "@dxos/react-client/echo";
3253
+ var modelState = StateField5.define({
3254
+ create: () => void 0,
3255
+ update: (model) => model
3256
+ });
2706
3257
 
2707
- // packages/ui/react-ui-editor/src/hooks/yjs.ts
2708
- import * as decoding from "lib0/decoding";
2709
- import * as encoding from "lib0/encoding";
2710
- import { Observable } from "lib0/observable";
2711
- import * as YP from "y-protocols/awareness";
2712
- import { invariant as invariant4 } from "@dxos/invariant";
2713
- import { log as log4 } from "@dxos/log";
2714
- var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/hooks/yjs.ts";
2715
- var createYjsModel = ({ identity, space, text }) => {
2716
- invariant4(text?.doc && text?.content, void 0, {
2717
- F: __dxlog_file5,
2718
- L: 21,
2719
- S: void 0,
2720
- A: [
2721
- "text?.doc && text?.content",
2722
- ""
2723
- ]
2724
- });
2725
- const provider = space ? new YAwarenessProvider({
2726
- space,
2727
- doc: text.doc,
2728
- channel: `yjs.awareness.${text.id}`
2729
- }) : void 0;
2730
- const model = {
2731
- id: text.doc.guid,
2732
- content: text.content,
2733
- text: () => text.content.toString(),
2734
- extension: [
2735
- modelState.init(() => model),
2736
- yjs(text.content, provider?.awareness)
2737
- ],
2738
- awareness: provider?.awareness,
2739
- peer: identity ? {
2740
- id: identity.identityKey.toHex(),
2741
- name: identity.profile?.displayName
2742
- } : void 0
2743
- };
2744
- return model;
2745
- };
2746
- var messageAwareness = 1;
2747
- var messageQueryAwareness = 3;
2748
- var YAwarenessProvider = class extends Observable {
2749
- constructor({ space, doc, channel, awareness: awareness2 }) {
2750
- super();
2751
- this._space = space;
2752
- this._awareness = awareness2 ?? new YP.Awareness(doc);
2753
- this._channel = channel;
2754
- this._clientId = doc.clientID;
2755
- this._awareness.on("update", this._handleAwarenessUpdate.bind(this));
2756
- this._space.listen(this._channel, this._handleSpaceMessage.bind(this));
2757
- if (typeof window !== "undefined") {
2758
- window.addEventListener("beforeunload", this._handleBeforeUnload.bind(this));
2759
- } else if (typeof process !== "undefined") {
2760
- process.on("exit", this._handleBeforeUnload.bind(this));
3258
+ // packages/ui/react-ui-editor/src/hooks/useActionHandler.ts
3259
+ var useActionHandler = (view) => {
3260
+ return (action) => {
3261
+ if (!view) {
3262
+ return;
2761
3263
  }
2762
- const encoderAwarenessQuery = encoding.createEncoder();
2763
- encoding.writeVarUint(encoderAwarenessQuery, messageQueryAwareness);
2764
- void this._space.postMessage(this._channel, encoding.toUint8Array(encoderAwarenessQuery));
2765
- const encoderAwarenessState = encoding.createEncoder();
2766
- encoding.writeVarUint(encoderAwarenessState, messageAwareness);
2767
- encoding.writeVarUint8Array(encoderAwarenessState, YP.encodeAwarenessUpdate(this.awareness, [
2768
- this._clientId
2769
- ]));
2770
- void this._space.postMessage(this._channel, encoding.toUint8Array(encoderAwarenessState));
2771
- }
2772
- get awareness() {
2773
- return this._awareness;
2774
- }
2775
- _handleAwarenessUpdate({ added, updated, removed }, origin) {
2776
- log4("awareness update", {
2777
- added,
2778
- updated,
2779
- removed,
2780
- origin
2781
- }, {
2782
- F: __dxlog_file5,
2783
- L: 100,
2784
- S: this,
2785
- C: (f, a) => f(...a)
2786
- });
2787
- const changedClients = added.concat(updated).concat(removed);
2788
- const encoderAwareness = encoding.createEncoder();
2789
- encoding.writeVarUint(encoderAwareness, messageAwareness);
2790
- encoding.writeVarUint8Array(encoderAwareness, YP.encodeAwarenessUpdate(this._awareness, changedClients));
2791
- void this._space.postMessage(this._channel, encoding.toUint8Array(encoderAwareness));
2792
- }
2793
- _handleSpaceMessage({ payload }) {
2794
- log4("space message", payload, {
2795
- F: __dxlog_file5,
2796
- L: 109,
2797
- S: this,
2798
- C: (f, a) => f(...a)
3264
+ switch (action.type) {
3265
+ case "heading":
3266
+ setHeading(parseInt(action.data))(view);
3267
+ break;
3268
+ case "bold":
3269
+ toggleBold(view);
3270
+ break;
3271
+ case "italic":
3272
+ toggleItalic(view);
3273
+ break;
3274
+ case "strikethrough":
3275
+ toggleStrikethrough(view);
3276
+ break;
3277
+ case "list":
3278
+ toggleList(view);
3279
+ break;
3280
+ case "codeblock":
3281
+ insertCodeblock(view);
3282
+ break;
3283
+ case "table":
3284
+ insertTable(view);
3285
+ break;
3286
+ case "comment":
3287
+ createComment(view);
3288
+ break;
3289
+ }
3290
+ setTimeout(() => {
3291
+ view.focus();
3292
+ view.dispatch({
3293
+ selection: view.state.selection
3294
+ });
2799
3295
  });
2800
- const data = new Uint8Array(Array.from(Object.values(payload)));
2801
- const encoder = this._readMessage(data);
2802
- if (encoder) {
2803
- void this._space.postMessage(this._channel, encoding.toUint8Array(encoder));
3296
+ };
3297
+ };
3298
+
3299
+ // packages/ui/react-ui-editor/src/hooks/useEditorView.ts
3300
+ import { useState as useState2 } from "react";
3301
+ var useEditorView = () => {
3302
+ const [view, setView] = useState2(null);
3303
+ return [
3304
+ (ref) => {
3305
+ setView(ref);
3306
+ },
3307
+ view
3308
+ ];
3309
+ };
3310
+
3311
+ // packages/ui/react-ui-editor/src/hooks/useTextEditor.ts
3312
+ import { EditorSelection, EditorState as EditorState3 } from "@codemirror/state";
3313
+ import { EditorView as EditorView14 } from "@codemirror/view";
3314
+ import { useEffect as useEffect3, useRef as useRef2, useState as useState3 } from "react";
3315
+ import { log as log4 } from "@dxos/log";
3316
+ import { isNotFalsy as isNotFalsy4 } from "@dxos/util";
3317
+ var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/hooks/useTextEditor.ts";
3318
+ var useTextEditor = ({ autoFocus, scrollTo, debug, doc, selection, extensions } = {}) => {
3319
+ const onUpdate = useRef2();
3320
+ const [view, setView] = useState3();
3321
+ const parentRef = useRef2(null);
3322
+ useEffect3(() => {
3323
+ if (parentRef.current) {
3324
+ const state = EditorState3.create({
3325
+ doc,
3326
+ selection,
3327
+ extensions: [
3328
+ // TODO(burdon): Doesn't catch errors in keymap functions.
3329
+ EditorView14.exceptionSink.of((err) => {
3330
+ log4.catch(err, void 0, {
3331
+ F: __dxlog_file5,
3332
+ L: 57,
3333
+ S: void 0,
3334
+ C: (f, a) => f(...a)
3335
+ });
3336
+ }),
3337
+ extensions,
3338
+ EditorView14.updateListener.of(() => {
3339
+ onUpdate.current?.();
3340
+ })
3341
+ ].filter(isNotFalsy4)
3342
+ });
3343
+ const view2 = new EditorView14({
3344
+ parent: parentRef.current,
3345
+ scrollTo,
3346
+ state,
3347
+ // NOTE: Uncomment to debug/monitor all transactions.
3348
+ // https://codemirror.net/docs/ref/#view.EditorView.dispatch
3349
+ dispatchTransactions: (trs, view3) => {
3350
+ if (debug) {
3351
+ logChanges(trs);
3352
+ }
3353
+ view3.update(trs);
3354
+ }
3355
+ });
3356
+ setView(view2);
2804
3357
  }
2805
- }
2806
- _readMessage(message) {
2807
- const decoder = decoding.createDecoder(message);
2808
- const encoder = encoding.createEncoder();
2809
- const messageType = decoding.readVarUint(decoder);
2810
- let sendReply = false;
2811
- switch (messageType) {
2812
- case messageAwareness: {
2813
- YP.applyAwarenessUpdate(this._awareness, decoding.readVarUint8Array(decoder), this);
2814
- break;
3358
+ return () => {
3359
+ view?.destroy();
3360
+ };
3361
+ }, [
3362
+ parentRef
3363
+ ]);
3364
+ useEffect3(() => {
3365
+ if (view) {
3366
+ if (!selection && !view.state.selection.main.anchor) {
3367
+ selection = EditorSelection.single(view.state.doc.line(1).to);
2815
3368
  }
2816
- case messageQueryAwareness: {
2817
- encoding.writeVarUint(encoder, messageAwareness);
2818
- encoding.writeVarUint8Array(encoder, YP.encodeAwarenessUpdate(this._awareness, Array.from(this._awareness.getStates().keys())));
2819
- sendReply = true;
2820
- break;
3369
+ if (selection || scrollTo) {
3370
+ onUpdate.current = () => {
3371
+ onUpdate.current = void 0;
3372
+ view.dispatch({
3373
+ selection,
3374
+ effects: scrollTo && [
3375
+ scrollTo
3376
+ ],
3377
+ scrollIntoView: !scrollTo
3378
+ });
3379
+ };
2821
3380
  }
2822
- default: {
2823
- console.error("Invalid message:", messageType);
2824
- return encoder;
3381
+ if (autoFocus) {
3382
+ view.focus();
2825
3383
  }
2826
3384
  }
2827
- if (!sendReply) {
2828
- return null;
2829
- }
2830
- return encoder;
2831
- }
2832
- _handleBeforeUnload() {
2833
- YP.removeAwarenessStates(this._awareness, [
2834
- this._clientId
2835
- ], "window unload");
2836
- }
3385
+ }, [
3386
+ view,
3387
+ autoFocus,
3388
+ selection,
3389
+ scrollTo
3390
+ ]);
3391
+ return {
3392
+ parentRef,
3393
+ view
3394
+ };
3395
+ };
3396
+ var createDataExtensions = ({ readonly = false } = {}) => {
3397
+ return [
3398
+ //
3399
+ EditorState3.readOnly.of(readonly),
3400
+ EditorView14.editable.of(!readonly)
3401
+ ];
3402
+ };
3403
+ var createThemeExtensions = ({ theme, themeMode, slots } = {}) => {
3404
+ return [
3405
+ //
3406
+ EditorView14.baseTheme(defaultTheme),
3407
+ theme && EditorView14.theme(theme),
3408
+ EditorView14.darkTheme.of(themeMode === "dark"),
3409
+ EditorView14.editorAttributes.of({
3410
+ class: slots?.editor?.className ?? ""
3411
+ }),
3412
+ EditorView14.contentAttributes.of({
3413
+ class: slots?.content?.className ?? ""
3414
+ })
3415
+ ].filter(isNotFalsy4);
2837
3416
  };
2838
3417
 
2839
3418
  // packages/ui/react-ui-editor/src/hooks/useTextModel.ts
2840
- var modelState = StateField5.define({
2841
- create: () => void 0,
2842
- update: (model) => model
2843
- });
3419
+ import get4 from "lodash.get";
3420
+ import { useEffect as useEffect4, useState as useState4 } from "react";
3421
+ import { generateName } from "@dxos/display-name";
3422
+ import { getRawDoc } from "@dxos/echo-schema";
3423
+ import { invariant as invariant3 } from "@dxos/invariant";
3424
+ import { isAutomergeObject } from "@dxos/react-client/echo";
3425
+ var __dxlog_file6 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/hooks/useTextModel.ts";
2844
3426
  var useTextModel = (props) => {
2845
3427
  const { identity, space, text } = props;
2846
- const [model, setModel] = useState2();
2847
- useEffect2(() => setModel(createModel(props)), [
3428
+ const [model, setModel] = useState4();
3429
+ useEffect4(() => setModel(createModel(props)), [
2848
3430
  identity,
2849
3431
  space,
2850
3432
  text
2851
3433
  ]);
2852
3434
  return model;
2853
3435
  };
2854
- var createModel = (props) => {
2855
- const { text } = props;
2856
- if (isAutomergeObject(text)) {
2857
- return createAutomergeModel(props);
2858
- } else if (text?.doc) {
2859
- return createYjsModel(props);
2860
- } else {
2861
- return void 0;
2862
- }
3436
+ var useInMemoryTextModel = ({ id, defaultContent }) => {
3437
+ const [content, setContent] = useState4(defaultContent ?? "");
3438
+ return {
3439
+ id,
3440
+ content,
3441
+ setContent,
3442
+ text: () => content
3443
+ };
2863
3444
  };
2864
-
2865
- // packages/ui/react-ui-editor/src/hooks/automerge.ts
2866
- var createAutomergeModel = ({ space, identity, text }) => {
3445
+ var createModel = ({ space, identity, text }) => {
3446
+ invariant3(isAutomergeObject(text), void 0, {
3447
+ F: __dxlog_file6,
3448
+ L: 50,
3449
+ S: void 0,
3450
+ A: [
3451
+ "isAutomergeObject(text)",
3452
+ ""
3453
+ ]
3454
+ });
2867
3455
  const obj = text;
2868
3456
  const doc = getRawDoc(obj, [
2869
3457
  obj.field
2870
3458
  ]);
2871
- const awarenessProvider = space && new SpaceAwarenessProvider({
3459
+ const awarenessProvider2 = space && new SpaceAwarenessProvider({
2872
3460
  space,
2873
3461
  channel: `automerge.awareness.${obj.id}`,
2874
3462
  info: {
2875
- displayName: identity?.profile?.displayName ?? "",
3463
+ displayName: identity ? identity.profile?.displayName ?? generateName(identity.identityKey.toHex()) : void 0,
2876
3464
  color: cursorColor.color,
2877
3465
  lightColor: cursorColor.light
2878
3466
  },
2879
3467
  peerId: identity?.identityKey.toHex() ?? "Anonymous"
2880
3468
  });
3469
+ const extensions = [
3470
+ //
3471
+ modelState.init(() => model),
3472
+ automerge({
3473
+ handle: doc.handle,
3474
+ path: doc.path
3475
+ })
3476
+ ];
3477
+ if (awarenessProvider2) {
3478
+ extensions.push(awareness(awarenessProvider2));
3479
+ }
2881
3480
  const model = {
2882
3481
  id: obj.id,
2883
3482
  content: doc,
2884
3483
  text: () => get4(doc.handle.docSync(), doc.path),
2885
- // TODO(burdon): https://automerge.org/automerge/api-docs/js/functions/next.getCursor.html
2886
- extension: [
2887
- modelState.init(() => model),
2888
- automerge3({
2889
- handle: doc.handle,
2890
- path: doc.path
2891
- }),
2892
- awarenessProvider && AwarenessProvider.of(awarenessProvider),
2893
- awareness()
2894
- ].filter(isNotNullOrUndefined),
3484
+ extension: extensions,
2895
3485
  peer: identity ? {
2896
3486
  id: identity.identityKey.toHex(),
2897
3487
  name: identity.profile?.displayName
@@ -2900,7 +3490,6 @@ var createAutomergeModel = ({ space, identity, text }) => {
2900
3490
  return model;
2901
3491
  };
2902
3492
  export {
2903
- AwarenessProvider,
2904
3493
  BaseTextEditor,
2905
3494
  Cursor,
2906
3495
  Doc,
@@ -2910,47 +3499,66 @@ export {
2910
3499
  SpaceAwarenessProvider,
2911
3500
  TextEditor,
2912
3501
  TextKind,
2913
- YAwarenessProvider,
3502
+ Toolbar,
2914
3503
  YText,
2915
3504
  YXmlFragment,
2916
3505
  autocomplete,
2917
- automerge3 as automerge,
3506
+ automerge,
2918
3507
  awareness,
2919
- basicBundle,
3508
+ awarenessProvider,
2920
3509
  blast,
2921
3510
  callbackWrapper,
2922
3511
  code2 as code,
2923
3512
  codeTheme,
2924
3513
  comments,
2925
- createAutomergeModel,
2926
- createYjsModel,
2927
- cursorConverter,
3514
+ createBasicBundle,
3515
+ createComment,
3516
+ createDataExtensions,
3517
+ createMarkdownExtensions,
3518
+ createThemeExtensions,
2928
3519
  defaultMarkdownSlots,
2929
3520
  defaultOptions,
2930
3521
  defaultSlots,
2931
3522
  defaultTextSlots,
2932
3523
  defaultTheme,
3524
+ focusComment,
3525
+ formatting,
2933
3526
  getToken,
3527
+ heading2 as heading,
2934
3528
  hr,
2935
3529
  image,
3530
+ insertCodeblock,
3531
+ insertTable,
3532
+ keymap7 as keymap,
2936
3533
  link,
2937
3534
  listener,
2938
- markdownBundle,
3535
+ logChanges,
2939
3536
  markdownHighlightStyle,
2940
3537
  markdownTags,
2941
3538
  markdownTagsExtensions,
2942
3539
  markdownTheme,
2943
3540
  mention,
2944
3541
  modelState,
2945
- setCommentRange,
2946
- setFocus,
3542
+ outliner,
3543
+ setComments,
3544
+ setHeading,
2947
3545
  setSelection,
2948
3546
  table,
2949
3547
  tags2 as tags,
2950
3548
  tasklist,
2951
3549
  textTheme,
3550
+ toggleBold,
3551
+ toggleItalic,
3552
+ toggleList,
3553
+ toggleStrikethrough,
3554
+ toggleStyle,
2952
3555
  typewriter,
3556
+ useActionHandler,
3557
+ useComments,
3558
+ useEditorView,
3559
+ useInMemoryTextModel,
3560
+ useTextEditor,
2953
3561
  useTextModel,
2954
- yjs
3562
+ useToolbarContext
2955
3563
  };
2956
3564
  //# sourceMappingURL=index.mjs.map