@dxos/react-ui-editor 0.3.11-main.668f0ff → 0.3.11-main.68db74e

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 (209) hide show
  1. package/dist/lib/browser/index.mjs +1742 -1382
  2. package/dist/lib/browser/index.mjs.map +4 -4
  3. package/dist/lib/browser/meta.json +1 -1
  4. package/dist/types/src/components/TextEditor/MarkdownEditor.stories.d.ts +9 -8
  5. package/dist/types/src/components/TextEditor/MarkdownEditor.stories.d.ts.map +1 -1
  6. package/dist/types/src/components/TextEditor/TextEditor.d.ts +12 -17
  7. package/dist/types/src/components/TextEditor/TextEditor.d.ts.map +1 -1
  8. package/dist/types/src/components/TextEditor/TextEditor.stories.d.ts +6 -3
  9. package/dist/types/src/components/TextEditor/TextEditor.stories.d.ts.map +1 -1
  10. package/dist/types/src/{hooks/automerge → components/TextEditor}/automerge.stories.d.ts +6 -1
  11. package/dist/types/src/components/TextEditor/automerge.stories.d.ts.map +1 -0
  12. package/dist/types/src/components/TextEditor/codemirror.stories.d.ts.map +1 -1
  13. package/dist/types/src/components/TextEditor/comments.stories.d.ts +26 -0
  14. package/dist/types/src/components/TextEditor/comments.stories.d.ts.map +1 -0
  15. package/dist/types/src/components/TextEditor/index.d.ts +0 -2
  16. package/dist/types/src/components/TextEditor/index.d.ts.map +1 -1
  17. package/dist/types/src/{hooks/yjs → components/TextEditor}/yjs.stories.d.ts +1 -1
  18. package/dist/types/src/components/TextEditor/yjs.stories.d.ts.map +1 -0
  19. package/dist/types/src/extensions/autocomplete.d.ts.map +1 -0
  20. package/dist/types/src/extensions/automerge/automerge.d.ts +9 -0
  21. package/dist/types/src/extensions/automerge/automerge.d.ts.map +1 -0
  22. package/dist/types/src/extensions/automerge/cursor.d.ts +5 -0
  23. package/dist/types/src/extensions/automerge/cursor.d.ts.map +1 -0
  24. package/dist/types/src/extensions/automerge/defs.d.ts +26 -0
  25. package/dist/types/src/extensions/automerge/defs.d.ts.map +1 -0
  26. package/dist/types/src/extensions/automerge/index.d.ts +4 -0
  27. package/dist/types/src/extensions/automerge/index.d.ts.map +1 -0
  28. package/dist/types/src/{hooks → extensions}/automerge/semaphore.d.ts +4 -4
  29. package/dist/types/src/extensions/automerge/semaphore.d.ts.map +1 -0
  30. package/dist/types/src/extensions/automerge/update-automerge.d.ts +5 -0
  31. package/dist/types/src/extensions/automerge/update-automerge.d.ts.map +1 -0
  32. package/dist/types/src/extensions/automerge/update-codemirror.d.ts.map +1 -0
  33. package/dist/types/src/extensions/awareness.d.ts +46 -0
  34. package/dist/types/src/extensions/awareness.d.ts.map +1 -0
  35. package/dist/types/src/extensions/basic.d.ts.map +1 -0
  36. package/dist/types/src/extensions/blast.d.ts.map +1 -0
  37. package/dist/types/src/extensions/code.d.ts.map +1 -0
  38. package/dist/types/src/{components/TextEditor/extensions → extensions}/comments.d.ts +6 -4
  39. package/dist/types/src/extensions/comments.d.ts.map +1 -0
  40. package/dist/types/src/extensions/cursor.d.ts +25 -0
  41. package/dist/types/src/extensions/cursor.d.ts.map +1 -0
  42. package/dist/types/src/extensions/hr.d.ts.map +1 -0
  43. package/dist/types/src/extensions/image.d.ts.map +1 -0
  44. package/dist/types/src/{components/TextEditor/extensions → extensions}/index.d.ts +4 -2
  45. package/dist/types/src/extensions/index.d.ts.map +1 -0
  46. package/dist/types/src/{components/TextEditor/extensions → extensions}/link.d.ts +1 -0
  47. package/dist/types/src/extensions/link.d.ts.map +1 -0
  48. package/dist/types/src/extensions/listener.d.ts.map +1 -0
  49. package/dist/types/src/extensions/markdown/bundle.d.ts.map +1 -0
  50. package/dist/types/src/extensions/markdown/highlight.d.ts.map +1 -0
  51. package/dist/types/src/extensions/markdown/index.d.ts.map +1 -0
  52. package/dist/types/src/extensions/mention.d.ts.map +1 -0
  53. package/dist/types/src/extensions/table.d.ts.map +1 -0
  54. package/dist/types/src/extensions/tasklist.d.ts +7 -0
  55. package/dist/types/src/extensions/tasklist.d.ts.map +1 -0
  56. package/dist/types/src/extensions/typewriter.d.ts.map +1 -0
  57. package/dist/types/src/extensions/yjs/cursor.d.ts +4 -0
  58. package/dist/types/src/extensions/yjs/cursor.d.ts.map +1 -0
  59. package/dist/types/src/extensions/yjs/index.d.ts +2 -0
  60. package/dist/types/src/extensions/yjs/index.d.ts.map +1 -0
  61. package/dist/types/src/extensions/yjs/yjs.d.ts +4 -0
  62. package/dist/types/src/extensions/yjs/yjs.d.ts.map +1 -0
  63. package/dist/types/src/extensions/yjs/yjs.test.d.ts.map +1 -0
  64. package/dist/types/src/hooks/automerge.d.ts +3 -0
  65. package/dist/types/src/hooks/automerge.d.ts.map +1 -0
  66. package/dist/types/src/hooks/awareness-provider.d.ts +28 -0
  67. package/dist/types/src/hooks/awareness-provider.d.ts.map +1 -0
  68. package/dist/types/src/hooks/index.d.ts +2 -0
  69. package/dist/types/src/hooks/index.d.ts.map +1 -1
  70. package/dist/types/src/hooks/useTextModel.d.ts +4 -8
  71. package/dist/types/src/hooks/useTextModel.d.ts.map +1 -1
  72. package/dist/types/src/hooks/{yjs/space-provider.d.ts → yjs.d.ts} +8 -8
  73. package/dist/types/src/hooks/yjs.d.ts.map +1 -0
  74. package/dist/types/src/index.d.ts +5 -0
  75. package/dist/types/src/index.d.ts.map +1 -1
  76. package/dist/types/src/styles/cursors.d.ts.map +1 -0
  77. package/dist/types/src/styles/index.d.ts +1 -0
  78. package/dist/types/src/styles/index.d.ts.map +1 -1
  79. package/dist/types/src/styles/markdown.d.ts.map +1 -1
  80. package/dist/types/src/styles/tokens.d.ts +1 -0
  81. package/dist/types/src/styles/tokens.d.ts.map +1 -1
  82. package/dist/types/src/testing/replicator.d.ts +2 -2
  83. package/dist/types/src/testing/replicator.d.ts.map +1 -1
  84. package/dist/types/src/{components/TextEditor/themes → themes}/default.d.ts +1 -1
  85. package/dist/types/src/themes/default.d.ts.map +1 -0
  86. package/dist/types/src/themes/index.d.ts.map +1 -0
  87. package/dist/types/src/util.d.ts.map +1 -0
  88. package/package.json +24 -22
  89. package/src/components/TextEditor/MarkdownEditor.stories.tsx +36 -36
  90. package/src/components/TextEditor/TextEditor.stories.tsx +13 -34
  91. package/src/components/TextEditor/TextEditor.tsx +71 -67
  92. package/src/{hooks/automerge → components/TextEditor}/automerge.stories.tsx +66 -6
  93. package/src/components/TextEditor/codemirror.stories.ts +3 -2
  94. package/src/components/TextEditor/comments.stories.tsx +315 -0
  95. package/src/components/TextEditor/index.ts +0 -3
  96. package/src/{hooks/yjs → components/TextEditor}/yjs.stories.tsx +1 -1
  97. package/src/{components/TextEditor/extensions → extensions}/autocomplete.ts +18 -17
  98. package/src/extensions/automerge/automerge.ts +94 -0
  99. package/src/extensions/automerge/cursor.ts +52 -0
  100. package/src/extensions/automerge/defs.ts +62 -0
  101. package/src/extensions/automerge/index.ts +7 -0
  102. package/src/{hooks → extensions}/automerge/semaphore.ts +14 -12
  103. package/src/{hooks → extensions}/automerge/update-automerge.ts +5 -6
  104. package/src/{hooks → extensions}/automerge/update-codemirror.ts +13 -5
  105. package/src/extensions/awareness.ts +309 -0
  106. package/src/{components/TextEditor/extensions → extensions}/code.ts +14 -7
  107. package/src/{components/TextEditor/extensions → extensions}/comments.ts +49 -113
  108. package/src/extensions/cursor.ts +46 -0
  109. package/src/{components/TextEditor/extensions → extensions}/hr.ts +4 -5
  110. package/src/extensions/image.ts +87 -0
  111. package/src/{components/TextEditor/extensions → extensions}/index.ts +4 -2
  112. package/src/{components/TextEditor/extensions → extensions}/link.ts +116 -62
  113. package/src/extensions/listener.ts +35 -0
  114. package/src/{components/TextEditor/extensions → extensions}/markdown/highlight.ts +4 -13
  115. package/src/{components/TextEditor/extensions → extensions}/table.ts +10 -4
  116. package/src/extensions/tasklist.ts +95 -0
  117. package/src/{components/TextEditor/extensions → extensions}/typewriter.ts +1 -1
  118. package/src/extensions/yjs/cursor.ts +22 -0
  119. package/src/extensions/yjs/index.ts +5 -0
  120. package/src/{hooks → extensions}/yjs/yjs.test.ts +2 -26
  121. package/src/extensions/yjs/yjs.ts +16 -0
  122. package/src/hooks/automerge.ts +52 -0
  123. package/src/hooks/awareness-provider.ts +120 -0
  124. package/src/hooks/index.ts +2 -0
  125. package/src/hooks/useTextModel.ts +20 -96
  126. package/src/hooks/{yjs/space-provider.ts → yjs.ts} +49 -19
  127. package/src/index.ts +5 -0
  128. package/src/styles/index.ts +1 -0
  129. package/src/styles/markdown.ts +0 -2
  130. package/src/styles/tokens.ts +3 -0
  131. package/src/testing/replicator.ts +10 -15
  132. package/src/{components/TextEditor/themes → themes}/default.ts +52 -79
  133. package/dist/types/src/components/TextEditor/extensions/autocomplete.d.ts.map +0 -1
  134. package/dist/types/src/components/TextEditor/extensions/basic.d.ts.map +0 -1
  135. package/dist/types/src/components/TextEditor/extensions/blast.d.ts.map +0 -1
  136. package/dist/types/src/components/TextEditor/extensions/code.d.ts.map +0 -1
  137. package/dist/types/src/components/TextEditor/extensions/comments.d.ts.map +0 -1
  138. package/dist/types/src/components/TextEditor/extensions/hr.d.ts.map +0 -1
  139. package/dist/types/src/components/TextEditor/extensions/image.d.ts.map +0 -1
  140. package/dist/types/src/components/TextEditor/extensions/index.d.ts.map +0 -1
  141. package/dist/types/src/components/TextEditor/extensions/link.d.ts.map +0 -1
  142. package/dist/types/src/components/TextEditor/extensions/listener.d.ts.map +0 -1
  143. package/dist/types/src/components/TextEditor/extensions/markdown/bundle.d.ts.map +0 -1
  144. package/dist/types/src/components/TextEditor/extensions/markdown/highlight.d.ts.map +0 -1
  145. package/dist/types/src/components/TextEditor/extensions/markdown/index.d.ts.map +0 -1
  146. package/dist/types/src/components/TextEditor/extensions/mention.d.ts.map +0 -1
  147. package/dist/types/src/components/TextEditor/extensions/mermaid.d.ts +0 -3
  148. package/dist/types/src/components/TextEditor/extensions/mermaid.d.ts.map +0 -1
  149. package/dist/types/src/components/TextEditor/extensions/table.d.ts.map +0 -1
  150. package/dist/types/src/components/TextEditor/extensions/tasklist.d.ts +0 -3
  151. package/dist/types/src/components/TextEditor/extensions/tasklist.d.ts.map +0 -1
  152. package/dist/types/src/components/TextEditor/extensions/tooltip.d.ts +0 -12
  153. package/dist/types/src/components/TextEditor/extensions/tooltip.d.ts.map +0 -1
  154. package/dist/types/src/components/TextEditor/extensions/typewriter.d.ts.map +0 -1
  155. package/dist/types/src/components/TextEditor/extensions/util.d.ts.map +0 -1
  156. package/dist/types/src/components/TextEditor/themes/default.d.ts.map +0 -1
  157. package/dist/types/src/components/TextEditor/themes/index.d.ts.map +0 -1
  158. package/dist/types/src/hooks/automerge/automerge.stories.d.ts.map +0 -1
  159. package/dist/types/src/hooks/automerge/handle.d.ts +0 -9
  160. package/dist/types/src/hooks/automerge/handle.d.ts.map +0 -1
  161. package/dist/types/src/hooks/automerge/index.d.ts +0 -3
  162. package/dist/types/src/hooks/automerge/index.d.ts.map +0 -1
  163. package/dist/types/src/hooks/automerge/plugin.d.ts +0 -26
  164. package/dist/types/src/hooks/automerge/plugin.d.ts.map +0 -1
  165. package/dist/types/src/hooks/automerge/semaphore.d.ts.map +0 -1
  166. package/dist/types/src/hooks/automerge/update-automerge.d.ts +0 -6
  167. package/dist/types/src/hooks/automerge/update-automerge.d.ts.map +0 -1
  168. package/dist/types/src/hooks/automerge/update-codemirror.d.ts.map +0 -1
  169. package/dist/types/src/hooks/yjs/cursors.d.ts.map +0 -1
  170. package/dist/types/src/hooks/yjs/index.d.ts +0 -3
  171. package/dist/types/src/hooks/yjs/index.d.ts.map +0 -1
  172. package/dist/types/src/hooks/yjs/space-provider.d.ts.map +0 -1
  173. package/dist/types/src/hooks/yjs/yjs.stories.d.ts.map +0 -1
  174. package/dist/types/src/hooks/yjs/yjs.test.d.ts.map +0 -1
  175. package/src/components/TextEditor/extensions/image.ts +0 -69
  176. package/src/components/TextEditor/extensions/listener.ts +0 -39
  177. package/src/components/TextEditor/extensions/mermaid.ts +0 -11
  178. package/src/components/TextEditor/extensions/tasklist.ts +0 -121
  179. package/src/components/TextEditor/extensions/tooltip.ts +0 -61
  180. package/src/hooks/automerge/handle.ts +0 -14
  181. package/src/hooks/automerge/index.ts +0 -6
  182. package/src/hooks/automerge/plugin.ts +0 -134
  183. package/src/hooks/yjs/index.ts +0 -6
  184. /package/dist/types/src/{components/TextEditor/extensions → extensions}/autocomplete.d.ts +0 -0
  185. /package/dist/types/src/{hooks → extensions}/automerge/update-codemirror.d.ts +0 -0
  186. /package/dist/types/src/{components/TextEditor/extensions → extensions}/basic.d.ts +0 -0
  187. /package/dist/types/src/{components/TextEditor/extensions → extensions}/blast.d.ts +0 -0
  188. /package/dist/types/src/{components/TextEditor/extensions → extensions}/code.d.ts +0 -0
  189. /package/dist/types/src/{components/TextEditor/extensions → extensions}/hr.d.ts +0 -0
  190. /package/dist/types/src/{components/TextEditor/extensions → extensions}/image.d.ts +0 -0
  191. /package/dist/types/src/{components/TextEditor/extensions → extensions}/listener.d.ts +0 -0
  192. /package/dist/types/src/{components/TextEditor/extensions → extensions}/markdown/bundle.d.ts +0 -0
  193. /package/dist/types/src/{components/TextEditor/extensions → extensions}/markdown/highlight.d.ts +0 -0
  194. /package/dist/types/src/{components/TextEditor/extensions → extensions}/markdown/index.d.ts +0 -0
  195. /package/dist/types/src/{components/TextEditor/extensions → extensions}/mention.d.ts +0 -0
  196. /package/dist/types/src/{components/TextEditor/extensions → extensions}/table.d.ts +0 -0
  197. /package/dist/types/src/{components/TextEditor/extensions → extensions}/typewriter.d.ts +0 -0
  198. /package/dist/types/src/{hooks → extensions}/yjs/yjs.test.d.ts +0 -0
  199. /package/dist/types/src/{hooks/yjs → styles}/cursors.d.ts +0 -0
  200. /package/dist/types/src/{components/TextEditor/themes → themes}/index.d.ts +0 -0
  201. /package/dist/types/src/{components/TextEditor/extensions/util.d.ts → util.d.ts} +0 -0
  202. /package/src/{components/TextEditor/extensions → extensions}/basic.ts +0 -0
  203. /package/src/{components/TextEditor/extensions → extensions}/blast.ts +0 -0
  204. /package/src/{components/TextEditor/extensions → extensions}/markdown/bundle.ts +0 -0
  205. /package/src/{components/TextEditor/extensions → extensions}/markdown/index.ts +0 -0
  206. /package/src/{components/TextEditor/extensions → extensions}/mention.ts +0 -0
  207. /package/src/{hooks/yjs → styles}/cursors.ts +0 -0
  208. /package/src/{components/TextEditor/themes → themes}/index.ts +0 -0
  209. /package/src/{components/TextEditor/extensions/util.ts → util.ts} +0 -0
@@ -5,774 +5,939 @@ import { Doc, YText, YXmlFragment } from "@dxos/text-model";
5
5
  // packages/ui/react-ui-editor/src/components/TextEditor/index.ts
6
6
  import { tags as tags2 } from "@lezer/highlight";
7
7
 
8
- // packages/ui/react-ui-editor/src/components/TextEditor/extensions/autocomplete.ts
8
+ // packages/ui/react-ui-editor/src/components/TextEditor/TextEditor.tsx
9
+ import { EditorState as EditorState2 } from "@codemirror/state";
10
+ import { EditorView as EditorView12 } from "@codemirror/view";
11
+ import { useFocusableGroup } from "@fluentui/react-tabster";
12
+ import { vim } from "@replit/codemirror-vim";
13
+ import defaultsDeep2 from "lodash.defaultsdeep";
14
+ import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useState, useRef } from "react";
15
+ import { generateName } from "@dxos/display-name";
16
+ import { useThemeContext } from "@dxos/react-ui";
17
+ import { getColorForValue, inputSurface, mx as mx3 } from "@dxos/react-ui-theme";
18
+
19
+ // packages/ui/react-ui-editor/src/extensions/autocomplete.ts
9
20
  import { autocompletion, completionKeymap } from "@codemirror/autocomplete";
21
+ import { markdownLanguage } from "@codemirror/lang-markdown";
10
22
  import { keymap } from "@codemirror/view";
11
23
  var autocomplete = ({ onSearch }) => {
12
24
  return [
13
25
  // https://codemirror.net/docs/ref/#view.keymap
14
26
  // https://discuss.codemirror.net/t/how-can-i-replace-the-default-autocompletion-keymap-v6/3322
27
+ // TODO(burdon): Set custom keymap.
15
28
  keymap.of(completionKeymap),
16
29
  // https://codemirror.net/examples/autocompletion
17
30
  // https://codemirror.net/docs/ref/#autocomplete.autocompletion
18
31
  autocompletion({
19
- // TODO(burdon): Set custom keymap.
20
- // defaultKeymap: false,
32
+ defaultKeymap: false,
21
33
  // Don't start unless key press.
22
- activateOnTyping: false,
23
- // TODO(burdon): Option to create new page?
24
- // TODO(burdon): Optional decoration via addToOptions
25
- override: [
26
- (context) => {
27
- const match = context.matchBefore(/\w*/);
28
- if (!match || match.from === match.to && !context.explicit) {
29
- return null;
30
- }
31
- return {
32
- from: match.from,
33
- options: onSearch(match.text.toLowerCase())
34
- };
34
+ activateOnTyping: false
35
+ }),
36
+ // TODO(burdon): Option to create new page?
37
+ // TODO(burdon): Optional decoration via addToOptions
38
+ markdownLanguage.data.of({
39
+ autocomplete: (context) => {
40
+ const match = context.matchBefore(/\w*/);
41
+ if (!match || match.from === match.to && !context.explicit) {
42
+ return null;
35
43
  }
36
- ]
44
+ return {
45
+ from: match.from,
46
+ options: onSearch(match.text.toLowerCase())
47
+ };
48
+ }
37
49
  })
38
50
  ];
39
51
  };
40
52
 
41
- // packages/ui/react-ui-editor/src/components/TextEditor/extensions/basic.ts
42
- import { closeBrackets } from "@codemirror/autocomplete";
43
- import { bracketMatching, defaultHighlightStyle, syntaxHighlighting } from "@codemirror/language";
44
- import { oneDarkHighlightStyle } from "@codemirror/theme-one-dark";
45
- import { drawSelection, EditorView, placeholder } from "@codemirror/view";
46
- var basicBundle = ({ readonly, themeMode, placeholder: _placeholder }) => [
47
- EditorView.lineWrapping,
48
- // TODO(burdon): Compare with minimalSetup.
49
- // https://codemirror.net/docs/ref/#codemirror.minimalSetup
50
- bracketMatching(),
51
- closeBrackets(),
52
- drawSelection(),
53
- _placeholder && placeholder(_placeholder),
54
- // TODO(burdon): Is this required?
55
- themeMode === "dark" ? syntaxHighlighting(oneDarkHighlightStyle) : syntaxHighlighting(defaultHighlightStyle)
56
- ].filter(Boolean);
53
+ // packages/ui/react-ui-editor/src/extensions/automerge/automerge.ts
54
+ import { Facet as Facet2, StateField } from "@codemirror/state";
55
+ import { ViewPlugin } from "@codemirror/view";
56
+ import { next as A } from "@dxos/automerge/automerge";
57
57
 
58
- // packages/ui/react-ui-editor/src/components/TextEditor/extensions/blast.ts
59
- import { EditorView as EditorView2, keymap as keymap2 } from "@codemirror/view";
60
- import defaultsDeep from "lodash.defaultsdeep";
61
- import { invariant } from "@dxos/invariant";
62
- var __dxlog_file = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/components/TextEditor/extensions/blast.ts";
63
- var defaultOptions = {
64
- effect: 2,
65
- maxParticles: 200,
66
- particleGravity: 0.08,
67
- particleAlphaFadeout: 0.996,
68
- particleSize: {
69
- min: 2,
70
- max: 8
71
- },
72
- particleNumRange: {
73
- min: 5,
74
- max: 10
75
- },
76
- particleVelocityRange: {
77
- x: [
78
- -1,
79
- 1
80
- ],
81
- y: [
82
- -3.5,
83
- -1.5
84
- ]
58
+ // packages/ui/react-ui-editor/src/extensions/automerge/cursor.ts
59
+ import get from "lodash.get";
60
+ import { next as automerge } from "@dxos/automerge/automerge";
61
+ var cursorConverter = (handle, path) => ({
62
+ // TODO(burdon): Handle assoc to associate with a previous character.
63
+ toCursor: (pos) => {
64
+ const doc = handle.docSync();
65
+ if (!doc) {
66
+ return "";
67
+ }
68
+ const value = get(doc, path);
69
+ if (typeof value === "string" && value.length <= pos) {
70
+ return "end";
71
+ }
72
+ return automerge.getCursor(doc, path.slice(), pos);
85
73
  },
86
- particleShrinkRate: 0.95,
87
- shakeIntensity: 5
88
- };
89
- var blast = (options = defaultOptions) => {
90
- let blaster;
91
- let last = 0;
92
- const getPoint = (view, pos) => {
93
- const { left: x = 0, top: y = 0 } = view.coordsForChar(pos) ?? {};
94
- const element = document.elementFromPoint(x, y);
95
- const { offsetLeft: left = 0, offsetTop: top = 0 } = view.scrollDOM.parentElement ?? {};
96
- const point = {
97
- x: x - left,
98
- y: y - top
99
- };
100
- return {
101
- element,
102
- point
103
- };
104
- };
105
- return [
106
- // Cursor moved.
107
- EditorView2.updateListener.of((update4) => {
108
- if (blaster?.node !== update4.view.scrollDOM) {
109
- if (blaster) {
110
- blaster.destroy();
111
- }
112
- blaster = new Blaster(update4.view.scrollDOM, defaultsDeep({
113
- particleGravity: 0.2,
114
- particleShrinkRate: 0.995,
115
- color: () => [
116
- 100 + Math.random() * 100,
117
- 0,
118
- 0
119
- ]
120
- }, options, defaultOptions));
121
- blaster.initialize();
122
- blaster.start();
74
+ fromCursor: (cursor) => {
75
+ if (cursor === "") {
76
+ return 0;
77
+ }
78
+ const doc = handle.docSync();
79
+ if (!doc) {
80
+ return 0;
81
+ }
82
+ if (cursor === "end") {
83
+ const value = get(doc, path);
84
+ if (typeof value === "string") {
85
+ return value.length;
123
86
  } else {
124
- blaster.resize();
125
- }
126
- const current = update4.state.selection.main.head;
127
- if (current !== last) {
128
- last = current;
129
- const { element, point } = getPoint(update4.view, current - 1);
130
- if (element && point) {
131
- blaster.spawn({
132
- element,
133
- point
134
- });
135
- }
136
- }
137
- }),
138
- keymap2.of([
139
- {
140
- any: (_, event) => {
141
- if (blaster) {
142
- if (event.key === "Enter" && event.shiftKey) {
143
- blaster.shake({
144
- time: 0.8
145
- });
146
- return true;
147
- }
148
- }
149
- return false;
150
- }
151
- }
152
- ])
153
- ];
154
- };
155
- var Blaster = class {
156
- constructor(_node, _options) {
157
- this._node = _node;
158
- this._options = _options;
159
- this._running = false;
160
- this._shakeTime = 0;
161
- this._shakeTimeMax = 0;
162
- this._particles = [];
163
- this._particlePointer = 0;
164
- this._lastPoint = {
165
- x: 0,
166
- y: 0
167
- };
168
- this.shake = throttle(({ time }) => {
169
- this._shakeTime = this._shakeTimeMax || time;
170
- this._shakeTimeMax = time;
171
- }, 100);
172
- this.spawn = throttle(({ element, point }) => {
173
- const color = getRGBComponents(element, this._options.color);
174
- const numParticles = random(this._options.particleNumRange.min, this._options.particleNumRange.max);
175
- const dir = this._lastPoint.x === point.x ? 0 : this._lastPoint.x < point.x ? 1 : -1;
176
- this._lastPoint = point;
177
- for (let i = numParticles; i--; i > 0) {
178
- this._particles[this._particlePointer] = this._effect.create(point.x - dir * 16, point.y, color);
179
- this._particlePointer = (this._particlePointer + 1) % this._options.maxParticles;
87
+ return 0;
180
88
  }
181
- }, 100);
182
- this._effect = this._options.effect === 1 ? new Effect1(_options) : new Effect2(_options);
183
- }
184
- get node() {
185
- return this._node;
186
- }
187
- initialize() {
188
- invariant(!this._canvas && !this._ctx, void 0, {
189
- F: __dxlog_file,
190
- L: 138,
191
- S: this,
192
- A: [
193
- "!this._canvas && !this._ctx",
194
- ""
195
- ]
196
- });
197
- this._canvas = document.createElement("canvas");
198
- this._canvas.id = "code-blast-canvas";
199
- this._canvas.style.position = "absolute";
200
- this._canvas.style.zIndex = "0";
201
- this._canvas.style.pointerEvents = "none";
202
- this._ctx = this._canvas.getContext("2d");
203
- const parent = this._node.parentElement?.parentElement;
204
- parent?.appendChild(this._canvas);
205
- this.resize();
206
- }
207
- destroy() {
208
- this.stop();
209
- if (this._canvas) {
210
- this._canvas.remove();
211
- this._canvas = void 0;
212
- this._ctx = void 0;
213
- }
214
- }
215
- resize() {
216
- if (this._node.parentElement && this._canvas) {
217
- const { offsetLeft: x, offsetTop: y, offsetWidth: width, offsetHeight: height } = this._node.parentElement;
218
- this._canvas.style.top = `${y}px`;
219
- this._canvas.style.left = `${x}px`;
220
- this._canvas.width = width;
221
- this._canvas.height = height;
222
89
  }
90
+ return automerge.getCursorPosition(doc, path.slice(), cursor);
223
91
  }
224
- start() {
225
- invariant(this._canvas && this._ctx, void 0, {
226
- F: __dxlog_file,
227
- L: 177,
228
- S: this,
229
- A: [
230
- "this._canvas && this._ctx",
231
- ""
232
- ]
92
+ });
93
+
94
+ // packages/ui/react-ui-editor/src/extensions/automerge/defs.ts
95
+ import { Annotation, StateEffect } from "@codemirror/state";
96
+ var effectType = StateEffect.define({});
97
+ var updateHeads = (newHeads) => effectType.of({
98
+ newHeads
99
+ });
100
+ var getLastHeads = (state, field) => state.field(field).lastHeads;
101
+ var getPath = (state, field) => state.field(field).path;
102
+ var reconcileAnnotationType = Annotation.define();
103
+ var isReconcileTx = (tr) => !!tr.annotation(reconcileAnnotationType);
104
+
105
+ // packages/ui/react-ui-editor/src/extensions/automerge/semaphore.ts
106
+ import { next as automerge2 } from "@dxos/automerge/automerge";
107
+
108
+ // packages/ui/react-ui-editor/src/extensions/automerge/update-automerge.ts
109
+ import { next as am } from "@dxos/automerge/automerge";
110
+ var updateAutomerge = (field, handle, transactions, state) => {
111
+ const { lastHeads, path } = state.field(field);
112
+ let hasChanges = false;
113
+ for (const tr of transactions) {
114
+ tr.changes.iterChanges(() => {
115
+ hasChanges = true;
233
116
  });
234
- this._running = true;
235
- this.loop();
236
117
  }
237
- stop() {
238
- this._running = false;
239
- this._node.style.transform = "translate(0px, 0px)";
118
+ if (!hasChanges) {
119
+ return void 0;
240
120
  }
241
- loop() {
242
- if (!this._running || !this._canvas || !this._ctx) {
243
- return;
244
- }
245
- this._ctx.clearRect(0, 0, this._canvas.width ?? 0, this._canvas.height ?? 0);
246
- const now = (/* @__PURE__ */ new Date()).getTime();
247
- this._lastTime ??= now;
248
- const dt = (now - this._lastTime) / 1e3;
249
- this._lastTime = now;
250
- if (this._shakeTime > 0) {
251
- this._shakeTime -= dt;
252
- const magnitude = this._shakeTime / this._shakeTimeMax * this._options.shakeIntensity;
253
- const shakeX = random(-magnitude, magnitude);
254
- const shakeY = random(-magnitude, magnitude);
255
- this._node.style.transform = `translate(${shakeX}px,${shakeY}px)`;
121
+ const newHeads = handle.changeAt(lastHeads, (doc) => {
122
+ for (const tr of transactions) {
123
+ tr.changes.iterChanges((fromA, toA, _fromB, _toB, inserted) => {
124
+ am.splice(doc, path, fromA, toA - fromA, inserted.toString());
125
+ });
256
126
  }
257
- this.drawParticles();
258
- requestAnimationFrame(this.loop.bind(this));
259
- }
260
- drawParticles() {
261
- for (let i = this._particles.length; i--; i > 0) {
262
- const particle = this._particles[i];
263
- if (!particle) {
264
- continue;
265
- }
266
- if (particle.alpha < 0.01 || particle.size <= 0.5) {
267
- continue;
268
- }
269
- this._effect.update(this._ctx, particle);
127
+ });
128
+ return newHeads ?? void 0;
129
+ };
130
+
131
+ // packages/ui/react-ui-editor/src/extensions/automerge/update-codemirror.ts
132
+ import { ChangeSet } from "@codemirror/state";
133
+ var updateCodeMirror = (view, selection, target, patches) => {
134
+ for (const patch of patches) {
135
+ const changeSpec = handlePatch(patch, target, view.state);
136
+ if (changeSpec != null) {
137
+ const changeSet = ChangeSet.of(changeSpec, view.state.doc.length, "\n");
138
+ selection = selection.map(changeSet, 1);
139
+ view.dispatch({
140
+ changes: changeSet,
141
+ annotations: reconcileAnnotationType.of({})
142
+ });
270
143
  }
271
144
  }
145
+ view.dispatch({
146
+ selection,
147
+ annotations: reconcileAnnotationType.of({})
148
+ });
272
149
  };
273
- var Effect = class {
274
- constructor(_options) {
275
- this._options = _options;
150
+ var handlePatch = (patch, target, state) => {
151
+ if (patch.action === "insert") {
152
+ return handleInsert(target, patch);
153
+ } else if (patch.action === "splice") {
154
+ return handleSplice(target, patch);
155
+ } else if (patch.action === "del") {
156
+ return handleDel(target, patch);
157
+ } else if (patch.action === "put") {
158
+ return handlePut(target, patch, state);
159
+ } else {
160
+ return null;
276
161
  }
277
162
  };
278
- var Effect1 = class extends Effect {
279
- create(x, y, color) {
280
- return {
281
- x,
282
- y: y + 10,
283
- vx: random(this._options.particleVelocityRange.x[0], this._options.particleVelocityRange.x[1]),
284
- vy: random(this._options.particleVelocityRange.y[0], this._options.particleVelocityRange.y[1]),
285
- size: random(this._options.particleSize.min, this._options.particleSize.max),
286
- color,
287
- alpha: 1
288
- };
289
- }
290
- update(ctx, particle) {
291
- particle.vy += this._options.particleGravity;
292
- particle.x += particle.vx;
293
- particle.y += particle.vy;
294
- particle.alpha *= this._options.particleAlphaFadeout;
295
- ctx.fillStyle = `rgba(${particle.color[0]},${particle.color[1]},${particle.color[2]},${particle.alpha})`;
296
- ctx.fillRect(Math.round(particle.x - 1), Math.round(particle.y - 1), particle.size, particle.size);
163
+ var handleInsert = (target, patch) => {
164
+ const index = charPath(target, patch.path);
165
+ if (index == null) {
166
+ return [];
297
167
  }
168
+ const text = patch.values.map((v) => v ? v.toString() : "").join("");
169
+ return [
170
+ {
171
+ from: index,
172
+ to: index,
173
+ insert: text
174
+ }
175
+ ];
298
176
  };
299
- var Effect2 = class extends Effect {
300
- create(x, y, color) {
301
- return {
302
- x,
303
- y: y + 10,
304
- vx: random(this._options.particleVelocityRange.x[0], this._options.particleVelocityRange.x[1]),
305
- vy: random(this._options.particleVelocityRange.y[0], this._options.particleVelocityRange.y[1]),
306
- size: random(this._options.particleSize.min, this._options.particleSize.max),
307
- color,
308
- alpha: 1,
309
- theta: random(0, 360) * Math.PI / 180,
310
- drag: 0.92,
311
- wander: 0.15
312
- };
313
- }
314
- update(ctx, particle) {
315
- particle.vy += this._options.particleGravity;
316
- particle.x += particle.vx;
317
- particle.y += particle.vy;
318
- particle.vx *= particle.drag;
319
- particle.vy *= particle.drag;
320
- particle.theta += random(-0.5, 0.5);
321
- particle.vx += Math.sin(particle.theta) * 0.1;
322
- particle.vy += Math.cos(particle.theta) * 0.1;
323
- particle.size *= this._options.particleShrinkRate;
324
- particle.alpha *= this._options.particleAlphaFadeout;
325
- ctx.fillStyle = `rgba(${particle.color[0]},${particle.color[1]},${particle.color[2]},${particle.alpha})`;
326
- ctx.beginPath();
327
- ctx.arc(Math.round(particle.x - 1), Math.round(particle.y - 1), particle.size, 0, 2 * Math.PI);
328
- ctx.fill();
177
+ var handleSplice = (target, patch) => {
178
+ const index = charPath(target, patch.path);
179
+ if (index == null) {
180
+ return [];
329
181
  }
330
- };
331
- function throttle(callback, limit) {
332
- let wait = false;
333
- return function(...args) {
334
- if (!wait) {
335
- callback.apply(this, args);
336
- wait = true;
337
- setTimeout(() => {
338
- wait = false;
339
- }, limit);
182
+ return [
183
+ {
184
+ from: index,
185
+ insert: patch.value
340
186
  }
341
- };
342
- }
343
- var getRGBComponents = (node, color) => {
344
- if (typeof color === "function") {
345
- return color();
187
+ ];
188
+ };
189
+ var handleDel = (target, patch) => {
190
+ const index = charPath(target, patch.path);
191
+ if (index == null) {
192
+ return [];
346
193
  }
347
- const bgColor = getComputedStyle(node).color;
348
- if (bgColor) {
349
- const x = bgColor.match(/(\d+), (\d+), (\d+)/)?.slice(1);
350
- if (x) {
351
- return x;
194
+ const length = patch.length || 1;
195
+ return [
196
+ {
197
+ from: index,
198
+ to: index + length
352
199
  }
200
+ ];
201
+ };
202
+ var handlePut = (target, patch, state) => {
203
+ const index = charPath(target, [
204
+ ...patch.path,
205
+ 0
206
+ ]);
207
+ if (index == null) {
208
+ return [];
209
+ }
210
+ const length = state.doc.length;
211
+ if (typeof patch.value !== "string") {
212
+ return [];
353
213
  }
354
214
  return [
355
- 50,
356
- 50,
357
- 50
215
+ {
216
+ from: 0,
217
+ to: length,
218
+ insert: patch.value
219
+ }
358
220
  ];
359
221
  };
360
- var random = (min, max) => {
361
- if (!max) {
362
- max = min;
363
- min = 0;
222
+ var charPath = (textPath, candidatePath) => {
223
+ if (candidatePath.length !== textPath.length + 1) {
224
+ return null;
364
225
  }
365
- return min + ~~(Math.random() * (max - min + 1));
226
+ for (let i = 0; i < textPath.length; i++) {
227
+ if (textPath[i] !== candidatePath[i]) {
228
+ return null;
229
+ }
230
+ }
231
+ const index = candidatePath[candidatePath.length - 1];
232
+ if (typeof index === "number") {
233
+ return index;
234
+ }
235
+ return null;
366
236
  };
367
237
 
368
- // packages/ui/react-ui-editor/src/components/TextEditor/extensions/code.ts
369
- import { ViewPlugin, EditorView as EditorView3, Decoration } from "@codemirror/view";
370
- import get from "lodash.get";
371
- import { mx as mx2 } from "@dxos/react-ui-theme";
238
+ // packages/ui/react-ui-editor/src/extensions/automerge/semaphore.ts
239
+ var PatchSemaphore = class {
240
+ constructor(_field) {
241
+ this._field = _field;
242
+ this._inReconcile = false;
243
+ this._queue = [];
244
+ this.reconcile = (handle, view) => {
245
+ if (this._inReconcile) {
246
+ return;
247
+ }
248
+ this._inReconcile = true;
249
+ const path = getPath(view.state, this._field);
250
+ const oldHeads = getLastHeads(view.state, this._field);
251
+ let selection = view.state.selection;
252
+ const transactions = view.state.field(this._field).unreconciledTransactions.filter((tx) => !isReconcileTx(tx));
253
+ const toInvert = transactions.slice().reverse();
254
+ for (const tx of toInvert) {
255
+ const inverted = tx.changes.invert(tx.startState.doc);
256
+ selection = selection.map(inverted);
257
+ view.dispatch({
258
+ changes: inverted,
259
+ annotations: reconcileAnnotationType.of(true)
260
+ });
261
+ }
262
+ let newHeads = updateAutomerge(this._field, handle, transactions, view.state);
263
+ if (newHeads === null || newHeads === void 0) {
264
+ newHeads = automerge2.getHeads(handle.docSync());
265
+ }
266
+ const diff = automerge2.equals(oldHeads, newHeads) ? [] : automerge2.diff(handle.docSync(), oldHeads, newHeads);
267
+ updateCodeMirror(view, selection, path, diff);
268
+ view.dispatch({
269
+ effects: updateHeads(newHeads),
270
+ annotations: reconcileAnnotationType.of({})
271
+ });
272
+ this._inReconcile = false;
273
+ };
274
+ }
275
+ };
372
276
 
373
- // packages/ui/react-ui-editor/src/styles/markdown.ts
374
- import { mx } from "@dxos/react-ui-theme";
375
- var headings = {
376
- 1: [
377
- "mbs-4 mbe-2 font-medium text-inherit no-underline text-4xl",
378
- "-ml-[10px]"
379
- ],
380
- 2: [
381
- "mbs-4 mbe-2 font-medium text-inherit no-underline text-3xl",
382
- "-ml-[8px]"
383
- ],
384
- 3: [
385
- "mbs-4 mbe-2 font-medium text-inherit no-underline text-2xl",
386
- "-ml-[7px]"
387
- ],
388
- 4: [
389
- "mbs-4 mbe-2 font-medium text-inherit no-underline text-xl",
390
- "-ml-[6px]"
391
- ],
392
- 5: [
393
- "mbs-4 mbe-2 font-medium text-inherit no-underline text-lg",
394
- "-ml-[5px]"
395
- ],
396
- 6: [
397
- "mbs-4 mbe-2 font-medium text-inherit no-underline",
398
- "-ml-[4px]"
399
- ]
277
+ // packages/ui/react-ui-editor/src/extensions/cursor.ts
278
+ import { Facet } from "@codemirror/state";
279
+ var defaultCursorConverter = {
280
+ toCursor: (position) => position.toString(),
281
+ fromCursor: (cursor) => parseInt(cursor)
400
282
  };
401
- var heading = (level, readonly) => {
402
- const [style, offset] = headings[level];
403
- return mx(style, readonly && offset);
283
+ var Cursor = class {
284
+ static {
285
+ this.converter = Facet.define({
286
+ combine: (providers) => providers[0] ?? defaultCursorConverter
287
+ });
288
+ }
289
+ static {
290
+ this.getCursorFromRange = (cursorConverter3, range) => {
291
+ const from = cursorConverter3.toCursor(range.from);
292
+ const to = cursorConverter3.toCursor(range.to, -1);
293
+ return [
294
+ from,
295
+ to
296
+ ].join(":");
297
+ };
298
+ }
299
+ static {
300
+ this.getRangeFromCursor = (cursorConverter3, cursor) => {
301
+ const parts = cursor.split(":");
302
+ const from = cursorConverter3.fromCursor(parts[0]);
303
+ const to = cursorConverter3.fromCursor(parts[1]);
304
+ return from !== void 0 && to !== void 0 ? {
305
+ from,
306
+ to
307
+ } : void 0;
308
+ };
309
+ }
404
310
  };
405
- var light = "text-neutral-200 dark:text-neutral-800";
406
- var mark = mx("!font-normal !no-underline !text-inherit opacity-40", light);
407
- var bold = "font-bold";
408
- var italic = "italic";
409
- var strikethrough = "line-through";
410
- var code = "font-mono !no-underline text-neutral-700 dark:text-neutral-300";
411
- var codeMark = "font-mono text-primary-500";
412
- var inlineUrl = mx(code, "px-1");
413
- var blockquote = mx("pl-1 mr-1 border-is-4 border-primary-500/70 dark:border-primary-500/30", light);
414
-
415
- // packages/ui/react-ui-editor/src/styles/tokens.ts
416
- import { tailwindConfig } from "@dxos/react-ui-theme";
417
- var tokens = tailwindConfig({}).theme;
418
311
 
419
- // packages/ui/react-ui-editor/src/components/TextEditor/extensions/code.ts
420
- var CODE_REGEX = /```[\s\S]*?```/gs;
421
- var styles = EditorView3.baseTheme({
422
- "& .cm-codeblock": {
423
- fontFamily: get(tokens, "fontFamily.mono", []).join(",")
424
- },
425
- '&light [aria-readonly="true"] .cm-codeblock': {
426
- background: get(tokens, "extend.colors.neutral.50")
427
- },
428
- '&dark [aria-readonly="true"] .cm-codeblock': {
429
- background: get(tokens, "extend.colors.neutral.850")
430
- },
431
- '& [aria-readonly="true"] .cm-codeblock': {
432
- display: "block",
433
- paddingInline: "4px !important"
434
- },
435
- '& [aria-readonly="true"] .cm-codeblock-first': {
436
- paddingTop: "4px !important",
437
- borderTopLeftRadius: "4px",
438
- borderTopRightRadius: "4px"
439
- },
440
- '& [aria-readonly="true"] .cm-codeblock-last': {
441
- paddingBottom: "4px !important",
442
- borderBottomLeftRadius: "4px",
443
- borderBottomRightRadius: "4px"
444
- }
312
+ // packages/ui/react-ui-editor/src/extensions/automerge/automerge.ts
313
+ var semaphoreFacet = Facet2.define({
314
+ combine: (values) => values.at(-1)
445
315
  });
446
- var getLineRange = (lines, from, to) => {
447
- const start = lines.findIndex((line) => line.from >= from);
448
- const end = lines.findIndex((line) => line.to >= to);
449
- return [
450
- start,
451
- end
452
- ];
453
- };
454
- var code2 = () => {
455
- const getDecorations = (view) => {
456
- const decorations = [];
457
- if (view.state.readOnly) {
458
- const text = view.state.doc.sliceString(0);
459
- const matches = text.matchAll(CODE_REGEX);
460
- const blocks = view.viewportLineBlocks;
461
- for (const match of matches) {
462
- const range = getLineRange(blocks, match.index, match.index + match[0].length);
463
- for (let i = range[0]; i <= range[1]; i++) {
464
- const block = blocks[i];
465
- decorations.push(Decoration.line({
466
- class: mx2("cm-codeblock", i === range[0] && "cm-codeblock-first", i === range[1] && "cm-codeblock-last")
467
- }).range(block.from));
316
+ var automerge3 = ({ handle, path }) => {
317
+ const stateField = StateField.define({
318
+ create: () => ({
319
+ lastHeads: A.getHeads(handle.docSync()),
320
+ unreconciledTransactions: [],
321
+ path: path.slice()
322
+ }),
323
+ update: (value, tr) => {
324
+ const result = {
325
+ lastHeads: value.lastHeads,
326
+ unreconciledTransactions: value.unreconciledTransactions.slice(),
327
+ path: path.slice()
328
+ };
329
+ let clearUnreconciled = false;
330
+ for (const effect of tr.effects) {
331
+ if (effect.is(effectType)) {
332
+ result.lastHeads = effect.value.newHeads;
333
+ clearUnreconciled = true;
334
+ }
335
+ }
336
+ if (clearUnreconciled) {
337
+ result.unreconciledTransactions = [];
338
+ } else {
339
+ if (!isReconcileTx(tr)) {
340
+ result.unreconciledTransactions.push(tr);
468
341
  }
469
342
  }
343
+ return result;
344
+ }
345
+ });
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);
359
+ });
360
+ }
361
+ }
362
+ destroy() {
363
+ handle.addListener("change", this._handleChange);
470
364
  }
471
- return Decoration.set(decorations);
365
+ });
366
+ return {
367
+ extension: [
368
+ Cursor.converter.of(cursorConverter(handle, path)),
369
+ semaphoreFacet.of(semaphore),
370
+ stateField,
371
+ viewPlugin
372
+ ]
472
373
  };
374
+ };
375
+
376
+ // 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";
379
+ import { Event } from "@dxos/async";
380
+ import { Context } from "@dxos/context";
381
+ var dummyProvider = {
382
+ remoteStateChange: new Event(),
383
+ open: () => {
384
+ },
385
+ close: () => {
386
+ },
387
+ update: () => {
388
+ },
389
+ getRemoteStates: () => []
390
+ };
391
+ var AwarenessProvider = Facet3.define({
392
+ combine: (providers) => providers[0] ?? dummyProvider
393
+ });
394
+ var RemoteSelectionChangedAnnotation = Annotation2.define();
395
+ var awareness = (provider = dummyProvider) => {
473
396
  return [
474
- ViewPlugin.fromClass(class {
475
- constructor(view) {
476
- this.decorations = getDecorations(view);
477
- }
478
- update(update4) {
479
- if (update4.docChanged || update4.viewportChanged) {
480
- this.decorations = getDecorations(update4.view);
481
- }
482
- }
483
- }, {
397
+ AwarenessProvider.of(provider),
398
+ ViewPlugin2.fromClass(RemoteSelectionsDecorator, {
484
399
  decorations: (value) => value.decorations
485
400
  }),
486
401
  styles
487
402
  ];
488
403
  };
489
-
490
- // packages/ui/react-ui-editor/src/components/TextEditor/extensions/comments.ts
491
- import { StateEffect as StateEffect2, StateField as StateField3 } from "@codemirror/state";
492
- import { hoverTooltip, keymap as keymap3, Decoration as Decoration2, EditorView as EditorView4, MatchDecorator, ViewPlugin as ViewPlugin3, WidgetType } from "@codemirror/view";
493
- import sortBy from "lodash.sortby";
494
- import { debounce } from "@dxos/async";
495
- import { invariant as invariant3 } from "@dxos/invariant";
496
- import { log as log3 } from "@dxos/log";
497
- import { nonNullable } from "@dxos/util";
498
-
499
- // packages/ui/react-ui-editor/src/components/TextEditor/extensions/util.ts
500
- import { log } from "@dxos/log";
501
- var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/components/TextEditor/extensions/util.ts";
502
- var callbackWrapper = (fn) => (...args) => {
503
- try {
504
- return fn(...args);
505
- } catch (error) {
506
- log.catch(error, void 0, {
507
- F: __dxlog_file2,
508
- L: 16,
509
- S: void 0,
510
- C: (f, a) => f(...a)
404
+ var RemoteSelectionsDecorator = class {
405
+ constructor(view) {
406
+ this.decorations = RangeSet.of([]);
407
+ this._ctx = new Context();
408
+ this._lastAnchor = void 0;
409
+ this._lastHead = void 0;
410
+ this._cursorConverter = view.state.facet(Cursor.converter);
411
+ this._provider = view.state.facet(AwarenessProvider);
412
+ this._provider.open();
413
+ this._provider.remoteStateChange.on(this._ctx, () => {
414
+ view.dispatch({
415
+ annotations: [
416
+ RemoteSelectionChangedAnnotation.of([])
417
+ ]
418
+ });
511
419
  });
512
420
  }
513
- };
514
-
515
- // packages/ui/react-ui-editor/src/hooks/useTextModel.ts
516
- import { StateField as StateField2 } from "@codemirror/state";
517
- import get2 from "lodash.get";
518
- import { useEffect, useState } from "react";
519
- import { yCollab } from "y-codemirror.next";
520
- import * as Y from "yjs";
521
- import { invariant as invariant2 } from "@dxos/invariant";
522
- import { getRawDoc, isActualAutomergeObject } from "@dxos/react-client/echo";
523
- import { arrayToString, stringToArray } from "@dxos/util";
524
-
525
- // packages/ui/react-ui-editor/src/hooks/automerge/plugin.ts
526
- import { Annotation, Facet, StateEffect, StateField } from "@codemirror/state";
527
- import { ViewPlugin as ViewPlugin2 } from "@codemirror/view";
528
- import * as automerge2 from "@dxos/automerge/automerge";
529
-
530
- // packages/ui/react-ui-editor/src/hooks/automerge/semaphore.ts
531
- import { next as automerge } from "@dxos/automerge/automerge";
532
-
533
- // packages/ui/react-ui-editor/src/hooks/automerge/update-automerge.ts
534
- import { next as am } from "@dxos/automerge/automerge";
535
- var updateAutomerge = (field, handle, transactions, state) => {
536
- const { lastHeads, path } = state.field(field);
537
- let hasChanges = false;
538
- for (const tr of transactions) {
539
- tr.changes.iterChanges(() => {
540
- hasChanges = true;
541
- });
421
+ destroy() {
422
+ void this._ctx.dispose();
423
+ this._provider.close();
542
424
  }
543
- if (!hasChanges) {
544
- return void 0;
425
+ update(update2) {
426
+ this._updateLocalSelection(update2);
427
+ this._updateRemoteSelections(update2);
545
428
  }
546
- const newHeads = handle.changeAt(lastHeads, (doc) => {
547
- for (const tr of transactions) {
548
- tr.changes.iterChanges((fromA, toA, _fromB, _toB, inserted) => {
549
- am.splice(doc, path, fromA, toA - fromA, inserted.toString());
550
- });
429
+ _updateLocalSelection(update2) {
430
+ const hasFocus = update2.view.hasFocus && update2.view.dom.ownerDocument.hasFocus();
431
+ const { anchor = void 0, head = void 0 } = hasFocus ? update2.state.selection.main : {};
432
+ if (this._lastAnchor === anchor && this._lastHead === head) {
433
+ return;
551
434
  }
552
- });
553
- return newHeads ?? void 0;
554
- };
555
-
556
- // packages/ui/react-ui-editor/src/hooks/automerge/update-codemirror.ts
557
- import { ChangeSet } from "@codemirror/state";
558
- var updateCodeMirror = (view, selection, target, patches) => {
559
- for (const patch of patches) {
560
- const changeSpec = handlePatch(patch, target, view.state);
561
- if (changeSpec != null) {
562
- const changeSet = ChangeSet.of(changeSpec, view.state.doc.length, "\n");
563
- selection = selection.map(changeSet, 1);
564
- view.dispatch({
565
- changes: changeSet,
566
- annotations: reconcileAnnotationType.of({})
435
+ this._lastAnchor = anchor;
436
+ this._lastHead = head;
437
+ this._provider.update(anchor !== void 0 && head !== void 0 ? {
438
+ anchor: this._cursorConverter.toCursor(anchor),
439
+ head: this._cursorConverter.toCursor(head)
440
+ } : void 0);
441
+ }
442
+ _updateRemoteSelections(update2) {
443
+ const decorations = [];
444
+ const awarenessStates = this._provider.getRemoteStates();
445
+ for (const state of awarenessStates) {
446
+ const anchor = state.position?.anchor ? this._cursorConverter.fromCursor(state.position.anchor) : null;
447
+ const head = state.position?.head ? this._cursorConverter.fromCursor(state.position.head) : null;
448
+ if (anchor == null || head == null) {
449
+ continue;
450
+ }
451
+ const start = Math.min(Math.min(anchor, head), update2.view.state.doc.length);
452
+ const end = Math.min(Math.max(anchor, head), update2.view.state.doc.length);
453
+ const startLine = update2.view.state.doc.lineAt(start);
454
+ const endLine = update2.view.state.doc.lineAt(end);
455
+ const color = state.info.color ?? "#30bced";
456
+ const lightColor = state.info.lightColor ?? color + "33";
457
+ if (startLine.number === endLine.number) {
458
+ decorations.push({
459
+ from: start,
460
+ to: end,
461
+ value: Decoration.mark({
462
+ attributes: {
463
+ style: `background-color: ${lightColor}`
464
+ },
465
+ class: "cm-collab-selection"
466
+ })
467
+ });
468
+ } else {
469
+ decorations.push({
470
+ from: start,
471
+ to: startLine.from + startLine.length,
472
+ value: Decoration.mark({
473
+ attributes: {
474
+ style: `background-color: ${color}`
475
+ },
476
+ class: "cm-collab-selection"
477
+ })
478
+ });
479
+ decorations.push({
480
+ from: endLine.from,
481
+ to: end,
482
+ value: Decoration.mark({
483
+ attributes: {
484
+ style: `background-color: ${color}`
485
+ },
486
+ class: "cm-collab-selection"
487
+ })
488
+ });
489
+ for (let i = startLine.number + 1; i < endLine.number; i++) {
490
+ const linePos = update2.view.state.doc.line(i).from;
491
+ decorations.push({
492
+ from: linePos,
493
+ to: linePos,
494
+ value: Decoration.line({
495
+ attributes: {
496
+ style: `background-color: ${color}`,
497
+ class: "cm-collab-selectionLine"
498
+ }
499
+ })
500
+ });
501
+ }
502
+ }
503
+ decorations.push({
504
+ from: head,
505
+ to: head,
506
+ value: Decoration.widget({
507
+ side: head - anchor > 0 ? -1 : 1,
508
+ block: false,
509
+ widget: new RemoteCaretWidget(state.info.displayName ?? "Anonymous", color)
510
+ })
567
511
  });
568
512
  }
513
+ this.decorations = Decoration.set(decorations, true);
569
514
  }
570
- view.dispatch({
571
- selection,
572
- annotations: reconcileAnnotationType.of({})
573
- });
574
515
  };
575
- var handlePatch = (patch, target, state) => {
576
- if (patch.action === "insert") {
577
- return handleInsert(target, patch);
578
- } else if (patch.action === "splice") {
579
- return handleSplice(target, patch);
580
- } else if (patch.action === "del") {
581
- return handleDel(target, patch);
582
- } else if (patch.action === "put") {
583
- return handlePut(target, patch, state);
584
- } else {
585
- return null;
516
+ var RemoteCaretWidget = class extends WidgetType {
517
+ constructor(_name, _color) {
518
+ super();
519
+ this._name = _name;
520
+ this._color = _color;
586
521
  }
587
- };
588
- var handleInsert = (target, patch) => {
589
- const index = charPath(target, patch.path);
590
- if (index == null) {
591
- return [];
522
+ toDOM() {
523
+ const span = document.createElement("span");
524
+ span.className = "cm-collab-selectionCaret";
525
+ span.style.backgroundColor = this._color;
526
+ span.style.borderColor = this._color;
527
+ const dot = document.createElement("div");
528
+ dot.className = "cm-collab-selectionCaretDot";
529
+ const info = document.createElement("div");
530
+ info.className = "cm-collab-selectionInfo";
531
+ info.innerText = this._name;
532
+ span.appendChild(document.createTextNode("\u2060"));
533
+ span.appendChild(dot);
534
+ span.appendChild(document.createTextNode("\u2060"));
535
+ span.appendChild(info);
536
+ span.appendChild(document.createTextNode("\u2060"));
537
+ return span;
592
538
  }
593
- const text = patch.values.map((v) => v ? v.toString() : "").join("");
594
- return [
595
- {
596
- from: index,
597
- to: index,
598
- insert: text
599
- }
600
- ];
601
- };
602
- var handleSplice = (target, patch) => {
603
- const index = charPath(target, patch.path);
604
- if (index == null) {
605
- return [];
539
+ updateDOM() {
540
+ return false;
606
541
  }
607
- return [
608
- {
609
- from: index,
610
- insert: patch.value
611
- }
612
- ];
613
- };
614
- var handleDel = (target, patch) => {
615
- const index = charPath(target, patch.path);
616
- if (index == null) {
617
- return [];
542
+ eq(widget) {
543
+ return widget._color === this._color;
618
544
  }
619
- const length = patch.length || 1;
620
- return [
621
- {
622
- from: index,
623
- to: index + length
624
- }
625
- ];
626
- };
627
- var handlePut = (target, patch, state) => {
628
- const index = charPath(target, [
629
- ...patch.path,
630
- 0
631
- ]);
632
- if (index == null) {
633
- return [];
545
+ get estimatedHeight() {
546
+ return -1;
634
547
  }
635
- const length = state.doc.length;
636
- if (typeof patch.value !== "string") {
637
- return [];
548
+ ignoreEvent() {
549
+ return true;
638
550
  }
551
+ };
552
+ var styles = EditorView.baseTheme({
553
+ ".cm-collab-selection": {},
554
+ ".cm-collab-selectionLine": {
555
+ padding: 0,
556
+ margin: "0px 2px 0px 4px"
557
+ },
558
+ ".cm-collab-selectionCaret": {
559
+ position: "relative",
560
+ borderLeft: "1px solid black",
561
+ borderRight: "1px solid black",
562
+ marginLeft: "-1px",
563
+ marginRight: "-1px",
564
+ boxSizing: "border-box",
565
+ display: "inline"
566
+ },
567
+ ".cm-collab-selectionCaretDot": {
568
+ borderRadius: "50%",
569
+ position: "absolute",
570
+ width: ".4em",
571
+ height: ".4em",
572
+ top: "-.2em",
573
+ left: "-.2em",
574
+ backgroundColor: "inherit",
575
+ transition: "transform .3s ease-in-out",
576
+ boxSizing: "border-box"
577
+ },
578
+ ".cm-collab-selectionCaret:hover > .cm-collab-selectionCaretDot": {
579
+ transformOrigin: "bottom center",
580
+ transform: "scale(0)"
581
+ },
582
+ ".cm-collab-selectionInfo": {
583
+ position: "absolute",
584
+ top: "-1.05em",
585
+ left: "-1px",
586
+ fontSize: ".75em",
587
+ fontFamily: "serif",
588
+ fontStyle: "normal",
589
+ fontWeight: "normal",
590
+ lineHeight: "normal",
591
+ userSelect: "none",
592
+ color: "white",
593
+ paddingLeft: "2px",
594
+ paddingRight: "2px",
595
+ zIndex: 101,
596
+ transition: "opacity .3s ease-in-out",
597
+ backgroundColor: "inherit",
598
+ // these should be separate
599
+ opacity: 0,
600
+ transitionDelay: "0s",
601
+ whiteSpace: "nowrap"
602
+ },
603
+ ".cm-collab-selectionCaret:hover > .cm-collab-selectionInfo": {
604
+ opacity: 1,
605
+ transitionDelay: "0s"
606
+ }
607
+ });
608
+
609
+ // packages/ui/react-ui-editor/src/extensions/basic.ts
610
+ import { closeBrackets } from "@codemirror/autocomplete";
611
+ import { bracketMatching, defaultHighlightStyle, syntaxHighlighting } from "@codemirror/language";
612
+ 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.
617
+ // https://codemirror.net/docs/ref/#codemirror.minimalSetup
618
+ bracketMatching(),
619
+ closeBrackets(),
620
+ drawSelection(),
621
+ _placeholder && placeholder(_placeholder),
622
+ // TODO(burdon): Is this required?
623
+ themeMode === "dark" ? syntaxHighlighting(oneDarkHighlightStyle) : syntaxHighlighting(defaultHighlightStyle)
624
+ ].filter(Boolean);
625
+
626
+ // packages/ui/react-ui-editor/src/extensions/blast.ts
627
+ import { EditorView as EditorView3, keymap as keymap2 } from "@codemirror/view";
628
+ import defaultsDeep from "lodash.defaultsdeep";
629
+ import { invariant } from "@dxos/invariant";
630
+ var __dxlog_file = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/extensions/blast.ts";
631
+ var defaultOptions = {
632
+ effect: 2,
633
+ maxParticles: 200,
634
+ particleGravity: 0.08,
635
+ particleAlphaFadeout: 0.996,
636
+ particleSize: {
637
+ min: 2,
638
+ max: 8
639
+ },
640
+ particleNumRange: {
641
+ min: 5,
642
+ max: 10
643
+ },
644
+ particleVelocityRange: {
645
+ x: [
646
+ -1,
647
+ 1
648
+ ],
649
+ y: [
650
+ -3.5,
651
+ -1.5
652
+ ]
653
+ },
654
+ particleShrinkRate: 0.95,
655
+ shakeIntensity: 5
656
+ };
657
+ var blast = (options = defaultOptions) => {
658
+ let blaster;
659
+ let last = 0;
660
+ const getPoint = (view, pos) => {
661
+ const { left: x = 0, top: y = 0 } = view.coordsForChar(pos) ?? {};
662
+ const element = document.elementFromPoint(x, y);
663
+ const { offsetLeft: left = 0, offsetTop: top = 0 } = view.scrollDOM.parentElement ?? {};
664
+ const point = {
665
+ x: x - left,
666
+ y: y - top
667
+ };
668
+ return {
669
+ element,
670
+ point
671
+ };
672
+ };
639
673
  return [
640
- {
641
- from: 0,
642
- to: length,
643
- insert: patch.value
644
- }
674
+ // Cursor moved.
675
+ EditorView3.updateListener.of((update2) => {
676
+ if (blaster?.node !== update2.view.scrollDOM) {
677
+ if (blaster) {
678
+ blaster.destroy();
679
+ }
680
+ blaster = new Blaster(update2.view.scrollDOM, defaultsDeep({
681
+ particleGravity: 0.2,
682
+ particleShrinkRate: 0.995,
683
+ color: () => [
684
+ 100 + Math.random() * 100,
685
+ 0,
686
+ 0
687
+ ]
688
+ }, options, defaultOptions));
689
+ blaster.initialize();
690
+ blaster.start();
691
+ } else {
692
+ blaster.resize();
693
+ }
694
+ const current = update2.state.selection.main.head;
695
+ if (current !== last) {
696
+ last = current;
697
+ const { element, point } = getPoint(update2.view, current - 1);
698
+ if (element && point) {
699
+ blaster.spawn({
700
+ element,
701
+ point
702
+ });
703
+ }
704
+ }
705
+ }),
706
+ keymap2.of([
707
+ {
708
+ any: (_, event) => {
709
+ if (blaster) {
710
+ if (event.key === "Enter" && event.shiftKey) {
711
+ blaster.shake({
712
+ time: 0.8
713
+ });
714
+ return true;
715
+ }
716
+ }
717
+ return false;
718
+ }
719
+ }
720
+ ])
645
721
  ];
646
722
  };
647
- var charPath = (textPath, candidatePath) => {
648
- if (candidatePath.length !== textPath.length + 1) {
649
- return null;
723
+ var Blaster = class {
724
+ constructor(_node, _options) {
725
+ this._node = _node;
726
+ this._options = _options;
727
+ this._running = false;
728
+ this._shakeTime = 0;
729
+ this._shakeTimeMax = 0;
730
+ this._particles = [];
731
+ this._particlePointer = 0;
732
+ this._lastPoint = {
733
+ x: 0,
734
+ y: 0
735
+ };
736
+ this.shake = throttle(({ time }) => {
737
+ this._shakeTime = this._shakeTimeMax || time;
738
+ this._shakeTimeMax = time;
739
+ }, 100);
740
+ this.spawn = throttle(({ element, point }) => {
741
+ const color = getRGBComponents(element, this._options.color);
742
+ const numParticles = random(this._options.particleNumRange.min, this._options.particleNumRange.max);
743
+ const dir = this._lastPoint.x === point.x ? 0 : this._lastPoint.x < point.x ? 1 : -1;
744
+ this._lastPoint = point;
745
+ for (let i = numParticles; i--; i > 0) {
746
+ this._particles[this._particlePointer] = this._effect.create(point.x - dir * 16, point.y, color);
747
+ this._particlePointer = (this._particlePointer + 1) % this._options.maxParticles;
748
+ }
749
+ }, 100);
750
+ this._effect = this._options.effect === 1 ? new Effect1(_options) : new Effect2(_options);
650
751
  }
651
- for (let i = 0; i < textPath.length; i++) {
652
- if (textPath[i] !== candidatePath[i]) {
653
- return null;
752
+ get node() {
753
+ return this._node;
754
+ }
755
+ initialize() {
756
+ invariant(!this._canvas && !this._ctx, void 0, {
757
+ F: __dxlog_file,
758
+ L: 138,
759
+ S: this,
760
+ A: [
761
+ "!this._canvas && !this._ctx",
762
+ ""
763
+ ]
764
+ });
765
+ this._canvas = document.createElement("canvas");
766
+ this._canvas.id = "code-blast-canvas";
767
+ this._canvas.style.position = "absolute";
768
+ this._canvas.style.zIndex = "0";
769
+ this._canvas.style.pointerEvents = "none";
770
+ this._ctx = this._canvas.getContext("2d");
771
+ const parent = this._node.parentElement?.parentElement;
772
+ parent?.appendChild(this._canvas);
773
+ this.resize();
774
+ }
775
+ destroy() {
776
+ this.stop();
777
+ if (this._canvas) {
778
+ this._canvas.remove();
779
+ this._canvas = void 0;
780
+ this._ctx = void 0;
654
781
  }
655
782
  }
656
- const index = candidatePath[candidatePath.length - 1];
657
- if (typeof index === "number") {
658
- return index;
783
+ resize() {
784
+ if (this._node.parentElement && this._canvas) {
785
+ const { offsetLeft: x, offsetTop: y, offsetWidth: width, offsetHeight: height } = this._node.parentElement;
786
+ this._canvas.style.top = `${y}px`;
787
+ this._canvas.style.left = `${x}px`;
788
+ this._canvas.width = width;
789
+ this._canvas.height = height;
790
+ }
659
791
  }
660
- return null;
661
- };
662
-
663
- // packages/ui/react-ui-editor/src/hooks/automerge/semaphore.ts
664
- var PatchSemaphore = class {
665
- constructor(field) {
666
- this._inReconcile = false;
667
- this._queue = [];
668
- this.reconcile = (handle, view) => {
669
- if (this._inReconcile) {
670
- return;
671
- }
672
- this._inReconcile = true;
673
- const path = getPath(view.state, this._field);
674
- const oldHeads = getLastHeads(view.state, this._field);
675
- let selection = view.state.selection;
676
- const transactions = view.state.field(this._field).unreconciledTransactions.filter((tx) => !isReconcileTx(tx));
677
- const toInvert = transactions.slice().reverse();
678
- for (const tx of toInvert) {
679
- const inverted = tx.changes.invert(tx.startState.doc);
680
- selection = selection.map(inverted);
681
- view.dispatch({
682
- changes: inverted,
683
- annotations: reconcileAnnotationType.of(true)
684
- });
792
+ start() {
793
+ invariant(this._canvas && this._ctx, void 0, {
794
+ F: __dxlog_file,
795
+ L: 177,
796
+ S: this,
797
+ A: [
798
+ "this._canvas && this._ctx",
799
+ ""
800
+ ]
801
+ });
802
+ this._running = true;
803
+ this.loop();
804
+ }
805
+ stop() {
806
+ this._running = false;
807
+ this._node.style.transform = "translate(0px, 0px)";
808
+ }
809
+ loop() {
810
+ if (!this._running || !this._canvas || !this._ctx) {
811
+ return;
812
+ }
813
+ this._ctx.clearRect(0, 0, this._canvas.width ?? 0, this._canvas.height ?? 0);
814
+ const now = (/* @__PURE__ */ new Date()).getTime();
815
+ this._lastTime ??= now;
816
+ const dt = (now - this._lastTime) / 1e3;
817
+ this._lastTime = now;
818
+ if (this._shakeTime > 0) {
819
+ this._shakeTime -= dt;
820
+ const magnitude = this._shakeTime / this._shakeTimeMax * this._options.shakeIntensity;
821
+ const shakeX = random(-magnitude, magnitude);
822
+ const shakeY = random(-magnitude, magnitude);
823
+ this._node.style.transform = `translate(${shakeX}px,${shakeY}px)`;
824
+ }
825
+ this.drawParticles();
826
+ requestAnimationFrame(this.loop.bind(this));
827
+ }
828
+ drawParticles() {
829
+ for (let i = this._particles.length; i--; i > 0) {
830
+ const particle = this._particles[i];
831
+ if (!particle) {
832
+ continue;
685
833
  }
686
- let newHeads = updateAutomerge(this._field, handle, transactions, view.state);
687
- if (newHeads === null || newHeads === void 0) {
688
- newHeads = automerge.getHeads(handle.docSync());
834
+ if (particle.alpha < 0.01 || particle.size <= 0.5) {
835
+ continue;
689
836
  }
690
- const diff = automerge.equals(oldHeads, newHeads) ? [] : automerge.diff(handle.docSync(), oldHeads, newHeads);
691
- updateCodeMirror(view, selection, path, diff);
692
- view.dispatch({
693
- effects: updateHeads(newHeads),
694
- annotations: reconcileAnnotationType.of({})
695
- });
696
- this._inReconcile = false;
837
+ this._effect.update(this._ctx, particle);
838
+ }
839
+ }
840
+ };
841
+ var Effect = class {
842
+ constructor(_options) {
843
+ this._options = _options;
844
+ }
845
+ };
846
+ var Effect1 = class extends Effect {
847
+ create(x, y, color) {
848
+ return {
849
+ x,
850
+ y: y + 10,
851
+ vx: random(this._options.particleVelocityRange.x[0], this._options.particleVelocityRange.x[1]),
852
+ vy: random(this._options.particleVelocityRange.y[0], this._options.particleVelocityRange.y[1]),
853
+ size: random(this._options.particleSize.min, this._options.particleSize.max),
854
+ color,
855
+ alpha: 1
856
+ };
857
+ }
858
+ update(ctx, particle) {
859
+ particle.vy += this._options.particleGravity;
860
+ particle.x += particle.vx;
861
+ particle.y += particle.vy;
862
+ particle.alpha *= this._options.particleAlphaFadeout;
863
+ ctx.fillStyle = `rgba(${particle.color[0]},${particle.color[1]},${particle.color[2]},${particle.alpha})`;
864
+ ctx.fillRect(Math.round(particle.x - 1), Math.round(particle.y - 1), particle.size, particle.size);
865
+ }
866
+ };
867
+ var Effect2 = class extends Effect {
868
+ create(x, y, color) {
869
+ return {
870
+ x,
871
+ y: y + 10,
872
+ vx: random(this._options.particleVelocityRange.x[0], this._options.particleVelocityRange.x[1]),
873
+ vy: random(this._options.particleVelocityRange.y[0], this._options.particleVelocityRange.y[1]),
874
+ size: random(this._options.particleSize.min, this._options.particleSize.max),
875
+ color,
876
+ alpha: 1,
877
+ theta: random(0, 360) * Math.PI / 180,
878
+ drag: 0.92,
879
+ wander: 0.15
697
880
  };
698
- if (field !== void 0) {
699
- this._field = field;
881
+ }
882
+ update(ctx, particle) {
883
+ particle.vy += this._options.particleGravity;
884
+ particle.x += particle.vx;
885
+ particle.y += particle.vy;
886
+ particle.vx *= particle.drag;
887
+ particle.vy *= particle.drag;
888
+ particle.theta += random(-0.5, 0.5);
889
+ particle.vx += Math.sin(particle.theta) * 0.1;
890
+ particle.vy += Math.cos(particle.theta) * 0.1;
891
+ particle.size *= this._options.particleShrinkRate;
892
+ particle.alpha *= this._options.particleAlphaFadeout;
893
+ ctx.fillStyle = `rgba(${particle.color[0]},${particle.color[1]},${particle.color[2]},${particle.alpha})`;
894
+ ctx.beginPath();
895
+ ctx.arc(Math.round(particle.x - 1), Math.round(particle.y - 1), particle.size, 0, 2 * Math.PI);
896
+ ctx.fill();
897
+ }
898
+ };
899
+ function throttle(callback, limit) {
900
+ let wait = false;
901
+ return function(...args) {
902
+ if (!wait) {
903
+ callback.apply(this, args);
904
+ wait = true;
905
+ setTimeout(() => {
906
+ wait = false;
907
+ }, limit);
908
+ }
909
+ };
910
+ }
911
+ var getRGBComponents = (node, color) => {
912
+ if (typeof color === "function") {
913
+ return color();
914
+ }
915
+ const bgColor = getComputedStyle(node).color;
916
+ if (bgColor) {
917
+ const x = bgColor.match(/(\d+), (\d+), (\d+)/)?.slice(1);
918
+ if (x) {
919
+ return x;
700
920
  }
701
921
  }
922
+ return [
923
+ 50,
924
+ 50,
925
+ 50
926
+ ];
702
927
  };
703
-
704
- // packages/ui/react-ui-editor/src/hooks/automerge/plugin.ts
705
- var effectType = StateEffect.define({});
706
- var updateHeads = (newHeads) => effectType.of({
707
- newHeads
708
- });
709
- var getLastHeads = (state, field) => state.field(field).lastHeads;
710
- var getPath = (state, field) => state.field(field).path;
711
- var semaphoreFacet = Facet.define({
712
- combine: (values) => values.at(-1)
713
- });
714
- var automergePlugin = (handle, path) => {
715
- const stateField = StateField.define({
716
- create: () => ({
717
- lastHeads: automerge2.getHeads(handle.docSync()),
718
- unreconciledTransactions: [],
719
- path: path.slice()
720
- }),
721
- update: (value, tr) => {
722
- const result = {
723
- lastHeads: value.lastHeads,
724
- unreconciledTransactions: value.unreconciledTransactions.slice(),
725
- path: path.slice()
726
- };
727
- let clearUnreconciled = false;
728
- for (const effect of tr.effects) {
729
- if (effect.is(effectType)) {
730
- result.lastHeads = effect.value.newHeads;
731
- clearUnreconciled = true;
732
- }
733
- }
734
- if (clearUnreconciled) {
735
- result.unreconciledTransactions = [];
736
- } else {
737
- if (!isReconcileTx(tr)) {
738
- result.unreconciledTransactions.push(tr);
739
- }
740
- }
741
- return result;
742
- }
743
- });
744
- const semaphore = new PatchSemaphore(stateField);
745
- const viewPlugin = ViewPlugin2.fromClass(class AutomergeCodemirrorViewPlugin {
746
- constructor(view) {
747
- this._handleChange = () => {
748
- this._view.state.facet(semaphoreFacet).reconcile(handle, this._view);
749
- };
750
- this._view = view;
751
- handle.addListener("change", this._handleChange);
752
- }
753
- update(update4) {
754
- if (update4.transactions.length > 0 && update4.transactions.some((t) => !isReconcileTx(t))) {
755
- queueMicrotask(() => {
756
- this._view.state.facet(semaphoreFacet).reconcile(handle, this._view);
757
- });
758
- }
759
- }
760
- destroy() {
761
- handle.addListener("change", this._handleChange);
762
- }
763
- });
764
- return {
765
- extension: [
766
- stateField,
767
- semaphoreFacet.of(semaphore),
768
- viewPlugin
769
- ]
770
- };
928
+ var random = (min, max) => {
929
+ if (!max) {
930
+ max = min;
931
+ min = 0;
932
+ }
933
+ return min + ~~(Math.random() * (max - min + 1));
771
934
  };
772
- var reconcileAnnotationType = Annotation.define();
773
- var isReconcileTx = (tr) => !!tr.annotation(reconcileAnnotationType);
774
935
 
775
- // packages/ui/react-ui-editor/src/hooks/yjs/cursors.ts
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";
939
+
940
+ // packages/ui/react-ui-editor/src/styles/cursors.ts
776
941
  import * as random2 from "lib0/random";
777
942
  var cursorColors = [
778
943
  {
@@ -810,239 +975,197 @@ var cursorColors = [
810
975
  ];
811
976
  var cursorColor = cursorColors[random2.uint32() % cursorColors.length];
812
977
 
813
- // packages/ui/react-ui-editor/src/hooks/yjs/space-provider.ts
814
- import * as decoding from "lib0/decoding";
815
- import * as encoding from "lib0/encoding";
816
- import { Observable } from "lib0/observable";
817
- import * as awarenessProtocol from "y-protocols/awareness";
818
- import { log as log2 } from "@dxos/log";
819
- var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/hooks/yjs/space-provider.ts";
820
- var messageAwareness = 1;
821
- var messageQueryAwareness = 3;
822
- var SpaceAwarenessProvider = class extends Observable {
823
- constructor({ space, doc, channel, awareness }) {
824
- super();
825
- this._space = space;
826
- this._awareness = awareness ?? new awarenessProtocol.Awareness(doc);
827
- this._channel = channel;
828
- this._clientId = doc.clientID;
829
- this._awareness.on("update", this._handleAwarenessUpdate.bind(this));
830
- this._space.listen(this._channel, this._handleSpaceMessage.bind(this));
831
- if (typeof window !== "undefined") {
832
- window.addEventListener("beforeunload", this._handleBeforeUnload.bind(this));
833
- } else if (typeof process !== "undefined") {
834
- process.on("exit", this._handleBeforeUnload.bind(this));
835
- }
836
- const encoderAwarenessQuery = encoding.createEncoder();
837
- encoding.writeVarUint(encoderAwarenessQuery, messageQueryAwareness);
838
- void this._space.postMessage(this._channel, encoding.toUint8Array(encoderAwarenessQuery));
839
- const encoderAwarenessState = encoding.createEncoder();
840
- encoding.writeVarUint(encoderAwarenessState, messageAwareness);
841
- encoding.writeVarUint8Array(encoderAwarenessState, awarenessProtocol.encodeAwarenessUpdate(this.awareness, [
842
- this._clientId
843
- ]));
844
- void this._space.postMessage(this._channel, encoding.toUint8Array(encoderAwarenessState));
845
- }
846
- get awareness() {
847
- return this._awareness;
848
- }
849
- _handleAwarenessUpdate({ added, updated, removed }, origin) {
850
- log2("awareness update", {
851
- added,
852
- updated,
853
- removed,
854
- origin
855
- }, {
856
- F: __dxlog_file3,
857
- L: 67,
858
- S: this,
859
- C: (f, a) => f(...a)
860
- });
861
- const changedClients = added.concat(updated).concat(removed);
862
- const encoderAwareness = encoding.createEncoder();
863
- encoding.writeVarUint(encoderAwareness, messageAwareness);
864
- encoding.writeVarUint8Array(encoderAwareness, awarenessProtocol.encodeAwarenessUpdate(this._awareness, changedClients));
865
- void this._space.postMessage(this._channel, encoding.toUint8Array(encoderAwareness));
866
- }
867
- _handleSpaceMessage({ payload }) {
868
- log2("space message", payload, {
869
- F: __dxlog_file3,
870
- L: 79,
871
- S: this,
872
- C: (f, a) => f(...a)
873
- });
874
- const data = new Uint8Array(Array.from(Object.values(payload)));
875
- const encoder = this._readMessage(data);
876
- if (encoder) {
877
- void this._space.postMessage(this._channel, encoding.toUint8Array(encoder));
878
- }
879
- }
880
- _readMessage(message) {
881
- const decoder = decoding.createDecoder(message);
882
- const encoder = encoding.createEncoder();
883
- const messageType = decoding.readVarUint(decoder);
884
- let sendReply = false;
885
- switch (messageType) {
886
- case messageAwareness: {
887
- awarenessProtocol.applyAwarenessUpdate(this._awareness, decoding.readVarUint8Array(decoder), this);
888
- break;
889
- }
890
- case messageQueryAwareness: {
891
- encoding.writeVarUint(encoder, messageAwareness);
892
- encoding.writeVarUint8Array(encoder, awarenessProtocol.encodeAwarenessUpdate(this._awareness, Array.from(this._awareness.getStates().keys())));
893
- sendReply = true;
894
- break;
895
- }
896
- default: {
897
- console.error("Invalid message:", messageType);
898
- return encoder;
899
- }
900
- }
901
- if (!sendReply) {
902
- return null;
903
- }
904
- return encoder;
905
- }
906
- _handleBeforeUnload() {
907
- awarenessProtocol.removeAwarenessStates(this._awareness, [
908
- this._clientId
909
- ], "window unload");
910
- }
911
- };
912
-
913
- // packages/ui/react-ui-editor/src/hooks/useTextModel.ts
914
- var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/hooks/useTextModel.ts";
915
- var modelState = StateField2.define({
916
- create: () => void 0,
917
- update: (model) => model
918
- });
919
- var useTextModel = (props) => {
920
- const { identity, space, text } = props;
921
- const [model, setModel] = useState(() => createModel(props));
922
- useEffect(() => setModel(createModel(props)), [
923
- identity,
924
- space,
925
- text
926
- ]);
927
- return model;
928
- };
929
- var createModel = (props) => {
930
- const { text } = props;
931
- if (isActualAutomergeObject(text)) {
932
- return createAutomergeModel(props);
933
- } else {
934
- if (!text?.doc) {
935
- return void 0;
936
- }
937
- return createYjsModel(props);
938
- }
939
- };
940
- var createYjsModel = ({ identity, space, text }) => {
941
- invariant2(text?.doc && text?.content, void 0, {
942
- F: __dxlog_file4,
943
- L: 97,
944
- S: void 0,
945
- A: [
946
- "text?.doc && text?.content",
947
- ""
948
- ]
949
- });
950
- const provider = space ? new SpaceAwarenessProvider({
951
- space,
952
- doc: text.doc,
953
- channel: `yjs.awareness.${text.id}`
954
- }) : void 0;
955
- const model = {
956
- id: text.doc.guid,
957
- content: text.content,
958
- text: () => text.content.toString(),
959
- // https://github.com/yjs/yjs?tab=readme-ov-file#relative-positions
960
- getCursorFromRange: (range) => {
961
- const from = Y.encodeRelativePosition(Y.createRelativePositionFromTypeIndex(text.content, range.from));
962
- const to = Y.encodeRelativePosition(Y.createRelativePositionFromTypeIndex(text.content, range.to, -1));
963
- return [
964
- arrayToString(from),
965
- arrayToString(to)
966
- ].join(":");
967
- },
968
- getRangeFromCursor: (cursor) => {
969
- const parts = cursor.split(":");
970
- const from = Y.createAbsolutePositionFromRelativePosition(Y.decodeRelativePosition(stringToArray(parts[0])), text.doc);
971
- const to = Y.createAbsolutePositionFromRelativePosition(Y.decodeRelativePosition(stringToArray(parts[1])), text.doc);
972
- return {
973
- from: from.index,
974
- to: to.index
975
- };
976
- },
977
- extension: [
978
- yCollab(text.content, provider?.awareness),
979
- modelState.init(() => model)
980
- ],
981
- awareness: provider?.awareness,
982
- peer: identity ? {
983
- id: identity.identityKey.toHex(),
984
- name: identity.profile?.displayName
985
- } : void 0
986
- };
987
- return model;
978
+ // packages/ui/react-ui-editor/src/styles/markdown.ts
979
+ import { mx } from "@dxos/react-ui-theme";
980
+ 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
+ ]
988
1005
  };
989
- var createAutomergeModel = ({ identity, text }) => {
990
- const obj = text;
991
- const doc = getRawDoc(obj, [
992
- obj.field
993
- ]);
994
- const model = {
995
- id: obj.id,
996
- content: doc,
997
- text: () => get2(doc.handle.docSync(), doc.path),
998
- // TODO(burdon): https://automerge.org/automerge/api-docs/js/functions/next.getCursor.html
999
- extension: [
1000
- automergePlugin(doc.handle, doc.path),
1001
- modelState.init(() => model)
1002
- ],
1003
- peer: identity ? {
1004
- id: identity.identityKey.toHex(),
1005
- name: identity.profile?.displayName
1006
- } : void 0
1007
- };
1008
- return model;
1006
+ var heading = (level, readonly) => {
1007
+ const [style, offset] = headings[level];
1008
+ return mx(style, readonly && offset);
1009
1009
  };
1010
+ var light = "text-neutral-200 dark:text-neutral-800";
1011
+ var mark = mx("!font-normal !no-underline !text-inherit opacity-40", light);
1012
+ var bold = "font-bold";
1013
+ var italic = "italic";
1014
+ var strikethrough = "line-through";
1015
+ var code = "font-mono !no-underline text-neutral-700 dark:text-neutral-300";
1016
+ var codeMark = "font-mono text-primary-500";
1017
+ var inlineUrl = mx(code, "px-1");
1018
+ var blockquote = mx("pl-1 mr-1 border-is-4 border-primary-500/70 dark:border-primary-500/30", light);
1019
+
1020
+ // packages/ui/react-ui-editor/src/styles/tokens.ts
1021
+ import get2 from "lodash.get";
1022
+ import { tailwindConfig } from "@dxos/react-ui-theme";
1023
+ var tokens = tailwindConfig({}).theme;
1024
+ var getToken = (path, defaultValue = void 0) => get2(tokens, path, defaultValue);
1010
1025
 
1011
- // packages/ui/react-ui-editor/src/components/TextEditor/extensions/comments.ts
1012
- var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/components/TextEditor/extensions/comments.ts";
1026
+ // packages/ui/react-ui-editor/src/extensions/code.ts
1027
+ var CODE_REGEX = /```[\s\S]*?```/gs;
1013
1028
  var styles2 = EditorView4.baseTheme({
1014
- "& .cm-bookmark": {
1015
- cursor: "pointer",
1016
- margin: "4px",
1017
- padding: "4px",
1018
- backgroundColor: "yellow"
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"
1019
1041
  },
1020
- "& .cm-bookmark-selected": {
1021
- backgroundColor: "orange"
1042
+ '& [aria-readonly="true"] .cm-codeblock-first': {
1043
+ paddingTop: "4px !important",
1044
+ borderTopLeftRadius: "4px",
1045
+ borderTopRightRadius: "4px"
1022
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
+ // packages/ui/react-ui-editor/src/util.ts
1112
+ import { log } from "@dxos/log";
1113
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/util.ts";
1114
+ var callbackWrapper = (fn) => (...args) => {
1115
+ try {
1116
+ return fn(...args);
1117
+ } catch (error) {
1118
+ log.catch(error, void 0, {
1119
+ F: __dxlog_file2,
1120
+ L: 16,
1121
+ S: void 0,
1122
+ C: (f, a) => f(...a)
1123
+ });
1124
+ }
1125
+ };
1126
+
1127
+ // 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({
1023
1130
  "& .cm-comment": {
1024
- backgroundColor: "yellow"
1131
+ backgroundColor: getToken("extend.colors.yellow.50")
1025
1132
  },
1026
1133
  "& .cm-comment-active": {
1027
- backgroundColor: "orange"
1134
+ backgroundColor: getToken("extend.colors.yellow.100")
1028
1135
  }
1029
1136
  });
1030
1137
  var marks = {
1031
- highlight: Decoration2.mark({
1138
+ highlight: Decoration3.mark({
1032
1139
  class: "cm-comment"
1033
1140
  }),
1034
- highlightActive: Decoration2.mark({
1141
+ highlightActive: Decoration3.mark({
1035
1142
  class: "cm-comment-active"
1036
1143
  })
1037
1144
  };
1145
+ var setFocus = (view, thread) => {
1146
+ const range = view.state.field(commentsStateField).ranges.find((range2) => range2.id === thread);
1147
+ if (!range) {
1148
+ return;
1149
+ }
1150
+ view.dispatch({
1151
+ effects: setSelection.of({
1152
+ active: thread
1153
+ }),
1154
+ selection: {
1155
+ anchor: range.from
1156
+ },
1157
+ scrollIntoView: true
1158
+ });
1159
+ };
1038
1160
  var setCommentRange = StateEffect2.define();
1039
1161
  var setSelection = StateEffect2.define();
1040
1162
  var setCommentState = StateEffect2.define();
1041
- var commentsStateField = StateField3.define({
1163
+ var commentsStateField = StateField2.define({
1042
1164
  create: () => ({
1043
1165
  ranges: []
1044
1166
  }),
1045
1167
  update: (value, tr) => {
1168
+ const cursorConverter3 = tr.state.facet(Cursor.converter);
1046
1169
  for (const effect of tr.effects) {
1047
1170
  if (effect.is(setSelection)) {
1048
1171
  return {
@@ -1051,14 +1174,14 @@ var commentsStateField = StateField3.define({
1051
1174
  };
1052
1175
  }
1053
1176
  if (effect.is(setCommentRange)) {
1054
- const { model, comments: comments2 } = effect.value;
1177
+ const { comments: comments2 } = effect.value;
1055
1178
  const ranges = comments2.map((comment) => {
1056
- const range = model.getRangeFromCursor(comment.cursor);
1057
- return {
1179
+ const range = Cursor.getRangeFromCursor(cursorConverter3, comment.cursor);
1180
+ return range && {
1058
1181
  ...comment,
1059
1182
  ...range
1060
1183
  };
1061
- });
1184
+ }).filter(nonNullable);
1062
1185
  return {
1063
1186
  ...value,
1064
1187
  ranges
@@ -1071,7 +1194,7 @@ var commentsStateField = StateField3.define({
1071
1194
  return value;
1072
1195
  }
1073
1196
  });
1074
- var highlightDecorations = EditorView4.decorations.compute([
1197
+ var highlightDecorations = EditorView5.decorations.compute([
1075
1198
  commentsStateField
1076
1199
  ], (state) => {
1077
1200
  const { active, ranges } = state.field(commentsStateField);
@@ -1089,43 +1212,16 @@ var highlightDecorations = EditorView4.decorations.compute([
1089
1212
  return marks.highlight.range(range.from, range.to);
1090
1213
  }
1091
1214
  }).filter(nonNullable) ?? [];
1092
- return Decoration2.set(decorations);
1215
+ return Decoration3.set(decorations);
1093
1216
  });
1094
- var BookmarkWidget = class extends WidgetType {
1095
- constructor(_anchor, _id, _handleClick) {
1096
- super();
1097
- this._anchor = _anchor;
1098
- this._id = _id;
1099
- this._handleClick = _handleClick;
1100
- invariant3(this._id, void 0, {
1101
- F: __dxlog_file5,
1102
- L: 151,
1103
- S: this,
1104
- A: [
1105
- "this._id",
1106
- ""
1107
- ]
1108
- });
1109
- }
1110
- eq(other) {
1111
- return this._anchor === other._anchor && this._id === other._id;
1112
- }
1113
- toDOM() {
1114
- const span = document.createElement("span");
1115
- span.className = "cm-bookmark";
1116
- span.textContent = "\u203B";
1117
- if (this._handleClick) {
1118
- span.onclick = () => this._handleClick();
1119
- }
1120
- return span;
1121
- }
1122
- };
1123
1217
  var comments = (options = {}) => {
1218
+ const { key: shortcut = "meta-'" } = options;
1124
1219
  const handleSelect = debounce((state) => options.onSelect?.(state), 200);
1125
1220
  const createCommentThread = (view) => {
1126
- invariant3(options.onCreate, void 0, {
1127
- F: __dxlog_file5,
1128
- L: 205,
1221
+ const cursorConverter3 = view.state.facet(Cursor.converter);
1222
+ invariant2(options.onCreate, void 0, {
1223
+ F: __dxlog_file3,
1224
+ L: 177,
1129
1225
  S: void 0,
1130
1226
  A: [
1131
1227
  "options.onCreate",
@@ -1136,13 +1232,12 @@ var comments = (options = {}) => {
1136
1232
  if (from === to) {
1137
1233
  return false;
1138
1234
  }
1139
- const model = view.state.field(modelState);
1140
- const relPos = model?.getCursorFromRange?.({
1235
+ const cursor = Cursor.getCursorFromRange(cursorConverter3, {
1141
1236
  from,
1142
1237
  to
1143
1238
  });
1144
- if (relPos) {
1145
- const id = callbackWrapper(options.onCreate)(relPos);
1239
+ if (cursor) {
1240
+ const id = callbackWrapper(options.onCreate)(cursor, view.coordsAtPos(from));
1146
1241
  if (id) {
1147
1242
  view.dispatch({
1148
1243
  effects: setSelection.of({
@@ -1169,44 +1264,16 @@ var comments = (options = {}) => {
1169
1264
  }
1170
1265
  return false;
1171
1266
  };
1172
- const bookmarksViewPlugin = ViewPlugin3.fromClass(class BookmarkViewPlugin {
1173
- static {
1174
- // Match markdown footnotes (option).
1175
- // https://www.markdownguide.org/extended-syntax/#footnotes
1176
- this.bookmarkMatcher = new MatchDecorator({
1177
- regexp: /\[\^(\w+)\]/g,
1178
- decoration: (match, view, pos) => {
1179
- const id = match[1];
1180
- return Decoration2.replace({
1181
- id,
1182
- widget: new BookmarkWidget(pos, id)
1183
- });
1184
- }
1185
- });
1186
- }
1187
- constructor(view) {
1188
- this.bookmarks = BookmarkViewPlugin.bookmarkMatcher.createDeco(view);
1189
- }
1190
- update(update4) {
1191
- this.bookmarks = BookmarkViewPlugin.bookmarkMatcher.updateDeco(update4, this.bookmarks);
1192
- }
1193
- }, {
1194
- decorations: (instance) => instance.bookmarks,
1195
- provide: (plugin) => EditorView4.atomicRanges.of((view) => {
1196
- return view.plugin(plugin)?.bookmarks || Decoration2.none;
1197
- })
1198
- });
1199
1267
  return [
1200
- bookmarksViewPlugin,
1201
1268
  commentsStateField,
1202
1269
  highlightDecorations,
1203
- styles2,
1270
+ styles3,
1204
1271
  //
1205
1272
  // Keymap.
1206
1273
  //
1207
1274
  options.onCreate ? keymap3.of([
1208
1275
  {
1209
- key: options?.key ?? "meta-'",
1276
+ key: shortcut,
1210
1277
  run: callbackWrapper(createCommentThread)
1211
1278
  }
1212
1279
  ]) : [],
@@ -1223,7 +1290,7 @@ var comments = (options = {}) => {
1223
1290
  above: true,
1224
1291
  create: () => {
1225
1292
  const el = document.createElement("div");
1226
- options.onHover?.(el);
1293
+ options.onHover?.(el, shortcut);
1227
1294
  return {
1228
1295
  dom: el,
1229
1296
  offset: {
@@ -1243,37 +1310,28 @@ var comments = (options = {}) => {
1243
1310
  // Monitor cursor movement and text updates.
1244
1311
  // TODO(burdon): Is there a better (finer grained) way to do this?
1245
1312
  //
1246
- EditorView4.updateListener.of(({ view, state, startState, changes }) => {
1313
+ EditorView5.updateListener.of(({ view, state, changes }) => {
1314
+ const cursorConverter3 = view.state.facet(Cursor.converter);
1247
1315
  {
1248
1316
  let mod = false;
1249
- const model = state.field(modelState);
1250
1317
  const { active, ranges } = state.field(commentsStateField);
1251
1318
  changes.iterChanges((from, to, from2, to2) => {
1252
- invariant3(model, void 0, {
1253
- F: __dxlog_file5,
1254
- L: 334,
1255
- S: void 0,
1256
- A: [
1257
- "model",
1258
- ""
1259
- ]
1260
- });
1261
1319
  ranges.forEach((range) => {
1262
1320
  if (from2 === to2) {
1263
- const newRange = model.getRangeFromCursor(range.cursor);
1264
- if (newRange.to - newRange.from === 0) {
1265
- log3.info("deleted comment", {
1321
+ const newRange = Cursor.getRangeFromCursor(cursorConverter3, range.cursor);
1322
+ if (!newRange || newRange.to - newRange.from === 0) {
1323
+ log2.info("deleted comment", {
1266
1324
  thread: range.id
1267
1325
  }, {
1268
- F: __dxlog_file5,
1269
- L: 340,
1326
+ F: __dxlog_file3,
1327
+ L: 274,
1270
1328
  S: void 0,
1271
1329
  C: (f, a) => f(...a)
1272
1330
  });
1273
1331
  }
1274
1332
  }
1275
1333
  if (from <= range.to) {
1276
- const newRange = model.getRangeFromCursor(range.cursor);
1334
+ const newRange = Cursor.getRangeFromCursor(cursorConverter3, range.cursor);
1277
1335
  Object.assign(range, newRange);
1278
1336
  mod = true;
1279
1337
  }
@@ -1323,14 +1381,13 @@ var comments = (options = {}) => {
1323
1381
  ];
1324
1382
  };
1325
1383
 
1326
- // packages/ui/react-ui-editor/src/components/TextEditor/extensions/hr.ts
1327
- import { Decoration as Decoration3, EditorView as EditorView5, MatchDecorator as MatchDecorator2, ViewPlugin as ViewPlugin4, WidgetType as WidgetType2 } from "@codemirror/view";
1328
- import get3 from "lodash.get";
1329
- var styles3 = EditorView5.baseTheme({
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({
1330
1387
  "& .cm-hr": {
1331
1388
  // TODO(burdon): ???
1332
1389
  // Note that block-level decorations should not have vertical margins,
1333
- borderBottom: `1px solid ${get3(tokens, "extend.colors.neutral.200")}`
1390
+ borderBottom: `1px solid ${getToken("extend.colors.neutral.200")}`
1334
1391
  }
1335
1392
  });
1336
1393
  var HorizontalRuleWidget = class extends WidgetType2 {
@@ -1347,43 +1404,65 @@ var HorizontalRuleWidget = class extends WidgetType2 {
1347
1404
  return el;
1348
1405
  }
1349
1406
  };
1350
- var placeholderMatcher = new MatchDecorator2({
1407
+ var placeholderMatcher = new MatchDecorator({
1351
1408
  regexp: /^---$/g,
1352
- decoration: (match, view, pos) => Decoration3.replace({
1409
+ decoration: (match, view, pos) => Decoration4.replace({
1353
1410
  widget: new HorizontalRuleWidget(pos)
1354
1411
  })
1355
1412
  });
1356
1413
  var hr = () => [
1357
- styles3,
1414
+ styles4,
1358
1415
  ViewPlugin4.fromClass(class {
1359
1416
  constructor(view) {
1360
1417
  this.rules = placeholderMatcher.createDeco(view);
1361
1418
  }
1362
- update(update4) {
1363
- this.rules = placeholderMatcher.updateDeco(update4, this.rules);
1419
+ update(update2) {
1420
+ this.rules = placeholderMatcher.updateDeco(update2, this.rules);
1364
1421
  }
1365
1422
  }, {
1366
1423
  decorations: (instance) => instance.rules,
1367
1424
  // TODO(burdon): Is this really atomic (cursor can move into ---).
1368
- provide: (plugin) => EditorView5.atomicRanges.of((view) => {
1369
- return view.plugin(plugin)?.rules || Decoration3.none;
1425
+ provide: (plugin) => EditorView6.atomicRanges.of((view) => {
1426
+ return view.plugin(plugin)?.rules || Decoration4.none;
1370
1427
  })
1371
1428
  })
1372
1429
  ];
1373
1430
 
1374
- // packages/ui/react-ui-editor/src/components/TextEditor/extensions/image.ts
1431
+ // packages/ui/react-ui-editor/src/extensions/image.ts
1375
1432
  import { syntaxTree } from "@codemirror/language";
1376
- import { RangeSetBuilder, StateField as StateField4 } from "@codemirror/state";
1377
- import { Decoration as Decoration4, EditorView as EditorView6, WidgetType as WidgetType3 } from "@codemirror/view";
1433
+ import { StateField as StateField3 } from "@codemirror/state";
1434
+ import { Decoration as Decoration5, EditorView as EditorView7, WidgetType as WidgetType3 } from "@codemirror/view";
1378
1435
  var image = (options = {}) => {
1379
- return StateField4.define({
1380
- create: (state) => update(state, options),
1381
- update: (_, tr) => update(tr.state, options),
1382
- provide: (field) => EditorView6.decorations.from(field)
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)
1383
1462
  });
1384
1463
  };
1385
- var update = (state, options) => {
1386
- const builder = new RangeSetBuilder();
1464
+ var buildDecorations = (from, to, state) => {
1465
+ const decorations = [];
1387
1466
  const cursor = state.selection.main.head;
1388
1467
  syntaxTree(state).iterate({
1389
1468
  enter: (node) => {
@@ -1392,22 +1471,23 @@ var update = (state, options) => {
1392
1471
  if (urlNode) {
1393
1472
  const hide = state.readOnly || cursor < node.from || cursor > node.to;
1394
1473
  const url = state.sliceDoc(urlNode.from, urlNode.to);
1395
- builder.add(hide ? node.from : node.to, node.to, Decoration4.replace({
1474
+ decorations.push(Decoration5.replace({
1396
1475
  block: true,
1397
1476
  widget: new ImageWidget(url)
1398
- }));
1477
+ }).range(hide ? node.from : node.to, node.to));
1399
1478
  }
1400
1479
  }
1401
- }
1480
+ },
1481
+ from,
1482
+ to
1402
1483
  });
1403
- return builder.finish();
1484
+ return decorations;
1404
1485
  };
1405
1486
  var ImageWidget = class extends WidgetType3 {
1406
1487
  constructor(_url) {
1407
1488
  super();
1408
1489
  this._url = _url;
1409
1490
  }
1410
- // TODO(burdon): Does this need to be unique for each position?
1411
1491
  eq(other) {
1412
1492
  return this._url === other._url;
1413
1493
  }
@@ -1415,30 +1495,77 @@ var ImageWidget = class extends WidgetType3 {
1415
1495
  const img = document.createElement("img");
1416
1496
  img.setAttribute("src", this._url);
1417
1497
  img.setAttribute("class", "cm-image");
1498
+ img.onload = () => img.classList.add("cm-loaded-image");
1418
1499
  return img;
1419
1500
  }
1420
1501
  };
1421
1502
 
1422
- // packages/ui/react-ui-editor/src/components/TextEditor/extensions/link.ts
1503
+ // packages/ui/react-ui-editor/src/extensions/link.ts
1423
1504
  import { syntaxTree as syntaxTree2 } from "@codemirror/language";
1424
- import { RangeSetBuilder as RangeSetBuilder2, StateField as StateField5 } from "@codemirror/state";
1425
- import { Decoration as Decoration5, EditorView as EditorView7, WidgetType as WidgetType4 } from "@codemirror/view";
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";
1426
1508
  var link = (options = {}) => {
1427
- return StateField5.define({
1428
- create: (state) => update2(state, options),
1429
- update: (_, tr) => update2(tr.state, options),
1430
- provide: (field) => EditorView7.decorations.from(field)
1431
- });
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;
1432
1560
  };
1433
1561
  var LinkButton = class extends WidgetType4 {
1434
- constructor(_pos, _url, _onAttach) {
1562
+ constructor(_url, _onAttach) {
1435
1563
  super();
1436
- this._pos = _pos;
1437
1564
  this._url = _url;
1438
1565
  this._onAttach = _onAttach;
1439
1566
  }
1440
1567
  eq(other) {
1441
- return this._pos === other._pos && this._url === other._url;
1568
+ return this._url === other._url;
1442
1569
  }
1443
1570
  toDOM(view) {
1444
1571
  const el = document.createElement("span");
@@ -1447,14 +1574,13 @@ var LinkButton = class extends WidgetType4 {
1447
1574
  }
1448
1575
  };
1449
1576
  var LinkText = class extends WidgetType4 {
1450
- constructor(_pos, _text, _url) {
1577
+ constructor(_text, _url) {
1451
1578
  super();
1452
- this._pos = _pos;
1453
1579
  this._text = _text;
1454
1580
  this._url = _url;
1455
1581
  }
1456
1582
  eq(other) {
1457
- return this._pos === other._pos && this._url === other._url;
1583
+ return this._url === other._url;
1458
1584
  }
1459
1585
  toDOM(view) {
1460
1586
  const link2 = document.createElement("a");
@@ -1468,7 +1594,7 @@ var LinkText = class extends WidgetType4 {
1468
1594
  link2.onclick = () => {
1469
1595
  view.dispatch({
1470
1596
  selection: {
1471
- anchor: this._pos
1597
+ anchor: view.posAtDOM(link2)
1472
1598
  }
1473
1599
  });
1474
1600
  };
@@ -1476,60 +1602,59 @@ var LinkText = class extends WidgetType4 {
1476
1602
  return link2;
1477
1603
  }
1478
1604
  };
1479
- var update2 = (state, options) => {
1480
- const builder = new RangeSetBuilder2();
1605
+ var buildDecorations2 = (view, options) => {
1606
+ const builder = new RangeSetBuilder();
1607
+ const { state } = view;
1481
1608
  const cursor = state.selection.main.head;
1482
- syntaxTree2(state).iterate({
1483
- enter: (node) => {
1484
- if (node.name === "Link") {
1485
- const marks2 = node.node.getChildren("LinkMark");
1486
- const text = marks2.length >= 2 ? state.sliceDoc(marks2[0].to, marks2[1].from) : "";
1487
- const urlNode = node.node.getChild("URL");
1488
- const url = urlNode ? state.sliceDoc(urlNode.from, urlNode.to) : "";
1489
- if (!url) {
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
+ }
1490
1630
  return false;
1491
1631
  }
1492
- if (state.readOnly || cursor < node.from || cursor > node.to) {
1493
- builder.add(node.from, node.to, Decoration5.replace({
1494
- widget: new LinkText(node.from, text, options.link ? url : void 0)
1495
- }));
1496
- }
1497
- if (options.onRender) {
1498
- builder.add(node.to, node.to, Decoration5.replace({
1499
- widget: new LinkButton(node.from, url, options.onRender)
1500
- }));
1501
- }
1502
- return false;
1503
- }
1504
- }
1505
- });
1632
+ },
1633
+ from,
1634
+ to
1635
+ });
1636
+ }
1506
1637
  return builder.finish();
1507
1638
  };
1508
1639
 
1509
- // packages/ui/react-ui-editor/src/components/TextEditor/extensions/listener.ts
1510
- import { StateField as StateField6 } from "@codemirror/state";
1640
+ // packages/ui/react-ui-editor/src/extensions/listener.ts
1511
1641
  import { EditorView as EditorView8 } from "@codemirror/view";
1512
- import { nonNullable as nonNullable2 } from "@dxos/util";
1513
- var listener = ({ onFocus, onChange }) => [
1514
- onFocus ? EditorView8.focusChangeEffect.of((view, focused) => {
1642
+ var listener = ({ onFocus, onChange }) => {
1643
+ const extensions = [];
1644
+ onFocus && extensions.push(EditorView8.focusChangeEffect.of((_, focused) => {
1515
1645
  onFocus(focused);
1516
1646
  return null;
1517
- }) : void 0,
1518
- onChange ? StateField6.define({
1519
- create: () => null,
1520
- update: (_value, transaction) => {
1521
- if (transaction.docChanged) {
1522
- onChange(transaction.newDoc.toString());
1523
- }
1524
- return null;
1525
- }
1526
- }) : void 0
1527
- ].filter(nonNullable2);
1647
+ }));
1648
+ onChange && extensions.push(EditorView8.updateListener.of((update2) => {
1649
+ onChange(update2.state.doc.toString());
1650
+ }));
1651
+ return extensions;
1652
+ };
1528
1653
 
1529
- // packages/ui/react-ui-editor/src/components/TextEditor/extensions/markdown/bundle.ts
1654
+ // packages/ui/react-ui-editor/src/extensions/markdown/bundle.ts
1530
1655
  import { closeBrackets as closeBrackets2, closeBracketsKeymap } from "@codemirror/autocomplete";
1531
1656
  import { history, historyKeymap, indentWithTab, standardKeymap } from "@codemirror/commands";
1532
- import { markdownLanguage as markdownLanguage2, markdown } from "@codemirror/lang-markdown";
1657
+ import { markdownLanguage as markdownLanguage3, markdown } from "@codemirror/lang-markdown";
1533
1658
  import { bracketMatching as bracketMatching2, defaultHighlightStyle as defaultHighlightStyle2, indentOnInput, syntaxHighlighting as syntaxHighlighting2 } from "@codemirror/language";
1534
1659
  import { languages } from "@codemirror/language-data";
1535
1660
  import { searchKeymap } from "@codemirror/search";
@@ -1537,19 +1662,17 @@ import { EditorState } from "@codemirror/state";
1537
1662
  import { oneDarkHighlightStyle as oneDarkHighlightStyle2 } from "@codemirror/theme-one-dark";
1538
1663
  import { crosshairCursor, drawSelection as drawSelection2, dropCursor, EditorView as EditorView9, highlightActiveLine, keymap as keymap4, placeholder as placeholder2 } from "@codemirror/view";
1539
1664
 
1540
- // packages/ui/react-ui-editor/src/components/TextEditor/extensions/markdown/highlight.ts
1541
- import { markdownLanguage } from "@codemirror/lang-markdown";
1665
+ // packages/ui/react-ui-editor/src/extensions/markdown/highlight.ts
1666
+ import { markdownLanguage as markdownLanguage2 } from "@codemirror/lang-markdown";
1542
1667
  import { HighlightStyle } from "@codemirror/language";
1543
1668
  import { tags, styleTags, Tag } from "@lezer/highlight";
1544
1669
  import { Table } from "@lezer/markdown";
1545
- import get4 from "lodash.get";
1546
1670
  var markdownTags = {
1547
1671
  Blockquote: Tag.define(),
1548
1672
  CodeMark: Tag.define(),
1549
1673
  CodeText: Tag.define(),
1550
1674
  EmphasisMark: Tag.define(),
1551
1675
  HeaderMark: Tag.define(),
1552
- // HorizontalRule: Tag.define(),
1553
1676
  InlineCode: Tag.define(),
1554
1677
  LinkLabel: Tag.define(),
1555
1678
  LinkReference: Tag.define(),
@@ -1713,12 +1836,6 @@ var markdownHighlightStyle = (readonly) => {
1713
1836
  ],
1714
1837
  class: blockquote
1715
1838
  },
1716
- // TODO(burdon): Replace with extension.
1717
- // {
1718
- // tag: [markdownTags.HorizontalRule],
1719
- // class: mx(horizontalRule, readonly && '-indent-[100rem]'),
1720
- // },
1721
- // TODO(burdon): Only if being edited.
1722
1839
  {
1723
1840
  tag: [
1724
1841
  markdownTags.TableCell
@@ -1726,14 +1843,14 @@ var markdownHighlightStyle = (readonly) => {
1726
1843
  class: "font-mono"
1727
1844
  }
1728
1845
  ], {
1729
- scope: markdownLanguage,
1846
+ scope: markdownLanguage2,
1730
1847
  all: {
1731
- fontFamily: get4(tokens, "fontFamily.body", []).join(",")
1848
+ fontFamily: getToken("fontFamily.body", []).join(",")
1732
1849
  }
1733
1850
  });
1734
1851
  };
1735
1852
 
1736
- // packages/ui/react-ui-editor/src/components/TextEditor/extensions/markdown/bundle.ts
1853
+ // packages/ui/react-ui-editor/src/extensions/markdown/bundle.ts
1737
1854
  var markdownBundle = ({ readonly, themeMode, placeholder: _placeholder }) => {
1738
1855
  return [
1739
1856
  EditorState.allowMultipleSelections.of(true),
@@ -1758,7 +1875,7 @@ var markdownBundle = ({ readonly, themeMode, placeholder: _placeholder }) => {
1758
1875
  // NOTE: This extends the parser; it doesn't affect rendering.
1759
1876
  // https://github.github.com/gfm
1760
1877
  // https://github.com/lezer-parser/markdown?tab=readme-ov-file#github-flavored-markdown
1761
- base: markdownLanguage2,
1878
+ base: markdownLanguage3,
1762
1879
  // Languages for syntax highlighting fenced code blocks.
1763
1880
  codeLanguages: languages,
1764
1881
  // Parser extensions.
@@ -1786,7 +1903,7 @@ var customKeymap = () => keymap4.of([
1786
1903
  ...searchKeymap
1787
1904
  ]);
1788
1905
 
1789
- // packages/ui/react-ui-editor/src/components/TextEditor/extensions/mention.ts
1906
+ // packages/ui/react-ui-editor/src/extensions/mention.ts
1790
1907
  import { autocompletion as autocompletion2 } from "@codemirror/autocomplete";
1791
1908
  var mention = ({ onSearch }) => {
1792
1909
  return autocompletion2({
@@ -1809,24 +1926,19 @@ var mention = ({ onSearch }) => {
1809
1926
  });
1810
1927
  };
1811
1928
 
1812
- // packages/ui/react-ui-editor/src/components/TextEditor/extensions/mermaid.ts
1813
- var mermaid = () => {
1814
- return [];
1815
- };
1816
-
1817
- // packages/ui/react-ui-editor/src/components/TextEditor/extensions/table.ts
1929
+ // packages/ui/react-ui-editor/src/extensions/table.ts
1818
1930
  import { syntaxTree as syntaxTree3 } from "@codemirror/language";
1819
- import { RangeSetBuilder as RangeSetBuilder3, StateField as StateField7 } from "@codemirror/state";
1820
- import { Decoration as Decoration6, EditorView as EditorView10, WidgetType as WidgetType5 } from "@codemirror/view";
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";
1821
1933
  var table = (options = {}) => {
1822
- return StateField7.define({
1823
- create: (state) => update3(state, options),
1824
- update: (_, tr) => update3(tr.state, options),
1934
+ return StateField4.define({
1935
+ create: (state) => update(state, options),
1936
+ update: (_, tr) => update(tr.state, options),
1825
1937
  provide: (field) => EditorView10.decorations.from(field)
1826
1938
  });
1827
1939
  };
1828
- var update3 = (state, options) => {
1829
- const builder = new RangeSetBuilder3();
1940
+ var update = (state, options) => {
1941
+ const builder = new RangeSetBuilder2();
1830
1942
  const cursor = state.selection.main.head;
1831
1943
  const tables = [];
1832
1944
  const getTable = () => tables[tables.length - 1];
@@ -1866,11 +1978,10 @@ var update3 = (state, options) => {
1866
1978
  });
1867
1979
  tables.forEach((table2) => {
1868
1980
  const hide = state.readOnly || cursor < table2.from || cursor > table2.to;
1869
- hide && builder.add(table2.from, table2.to, Decoration6.replace({
1870
- block: true,
1981
+ hide && builder.add(table2.from, table2.to, Decoration7.replace({
1871
1982
  widget: new TableWidget(table2)
1872
1983
  }));
1873
- builder.add(table2.from, table2.to, Decoration6.mark({
1984
+ builder.add(table2.from, table2.to, Decoration7.mark({
1874
1985
  class: "cm-table"
1875
1986
  }));
1876
1987
  });
@@ -1882,7 +1993,7 @@ var TableWidget = class extends WidgetType5 {
1882
1993
  this._table = _table;
1883
1994
  }
1884
1995
  eq(other) {
1885
- return this._table.from === other?._table?.from;
1996
+ return this._table.header?.join() === other._table.header?.join() && this._table.rows?.join() === other._table.rows?.join();
1886
1997
  }
1887
1998
  toDOM(view) {
1888
1999
  const table2 = document.createElement("table");
@@ -1908,138 +2019,94 @@ var TableWidget = class extends WidgetType5 {
1908
2019
  }
1909
2020
  return table2;
1910
2021
  }
2022
+ ignoreEvent(e) {
2023
+ return !/^mouse/.test(e.type);
2024
+ }
1911
2025
  };
1912
2026
 
1913
- // packages/ui/react-ui-editor/src/components/TextEditor/extensions/tasklist.ts
1914
- import { EditorView as EditorView11, Decoration as Decoration7, WidgetType as WidgetType6, MatchDecorator as MatchDecorator3, ViewPlugin as ViewPlugin5 } from "@codemirror/view";
1915
- var styles4 = EditorView11.baseTheme({
1916
- "& .cm-task-item": {
1917
- paddingLeft: "4px",
1918
- paddingRight: "8px"
1919
- }
1920
- });
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";
1921
2031
  var CheckboxWidget = class extends WidgetType6 {
1922
- constructor(_pos, _checked, _indent, _onCheck) {
2032
+ constructor(_checked) {
1923
2033
  super();
1924
- this._pos = _pos;
1925
2034
  this._checked = _checked;
1926
- this._indent = _indent;
1927
- this._onCheck = _onCheck;
1928
2035
  }
1929
2036
  eq(other) {
1930
- return this._pos === other._pos && this._checked === other._checked && this._indent === other._indent;
2037
+ return this._checked === other._checked;
1931
2038
  }
1932
2039
  toDOM(view) {
1933
- const wrap = document.createElement("span");
1934
- wrap.className = "cm-task-item";
1935
- wrap.setAttribute("aria-hidden", "true");
1936
- wrap.style.setProperty("margin-left", this._indent * 24 + "px");
1937
- const input = wrap.appendChild(document.createElement("input"));
2040
+ const input = document.createElement("input");
1938
2041
  input.type = "checkbox";
1939
2042
  input.checked = this._checked;
1940
- if (!this._onCheck) {
2043
+ if (view.state.readOnly) {
1941
2044
  input.setAttribute("disabled", "true");
1942
- }
1943
- if (this._onCheck) {
1944
- input.onchange = (event) => {
1945
- this._onCheck?.(event.target.checked);
1946
- return true;
2045
+ } else {
2046
+ input.onmousedown = (event) => {
2047
+ const pos = view.posAtDOM(input);
2048
+ const text = view.state.sliceDoc(pos, pos + 3);
2049
+ if (text === (this._checked ? "[x]" : "[ ]")) {
2050
+ view.dispatch({
2051
+ changes: {
2052
+ from: pos + 1,
2053
+ to: pos + 2,
2054
+ insert: this._checked ? " " : "x"
2055
+ }
2056
+ });
2057
+ event.preventDefault();
2058
+ }
1947
2059
  };
1948
2060
  }
1949
- return wrap;
2061
+ return input;
1950
2062
  }
1951
2063
  ignoreEvent() {
1952
2064
  return false;
1953
2065
  }
1954
2066
  };
2067
+ var checkedDeco = Decoration8.replace({
2068
+ widget: new CheckboxWidget(true)
2069
+ });
2070
+ var uncheckedDeco = Decoration8.replace({
2071
+ widget: new CheckboxWidget(false)
2072
+ });
1955
2073
  var tasklist = (options = {}) => {
1956
- const taskMatcher = new MatchDecorator3({
1957
- regexp: /^(\s*)- \[([ xX])\]\s/g,
1958
- decoration: (match, view, pos) => {
1959
- const indent = Math.floor(match[1].length / 2);
1960
- const checked = match[2] === "x" || match[2] === "X";
1961
- return Decoration7.replace({
1962
- widget: new CheckboxWidget(pos, checked, indent, view.state.readOnly ? void 0 : (checked2) => {
1963
- const idx = pos + match[0].indexOf("[") + 1;
1964
- view.dispatch({
1965
- changes: {
1966
- from: idx,
1967
- to: idx + 1,
1968
- insert: checked2 ? "x" : " "
1969
- },
1970
- // TODO(burdon): Restore cursor position? More useful to move to end of line (can indent).
1971
- selection: {
1972
- anchor: idx + 3
1973
- }
1974
- });
1975
- })
1976
- });
1977
- }
1978
- });
1979
- const tasks = ViewPlugin5.fromClass(class {
2074
+ return ViewPlugin6.fromClass(class {
1980
2075
  constructor(view) {
1981
- this.tasks = taskMatcher.createDeco(view);
1982
- }
1983
- update(update4) {
1984
- this.tasks = taskMatcher.updateDeco(update4, this.tasks);
1985
- }
1986
- }, {
1987
- decorations: (value) => value.tasks,
1988
- provide: (plugin) => EditorView11.atomicRanges.of((view) => {
1989
- return view.plugin(plugin)?.tasks || Decoration7.none;
1990
- })
1991
- });
1992
- return [
1993
- tasks,
1994
- styles4
1995
- ];
1996
- };
1997
-
1998
- // packages/ui/react-ui-editor/src/components/TextEditor/extensions/tooltip.ts
1999
- import { hoverTooltip as hoverTooltip2 } from "@codemirror/view";
2000
- import { tooltipContent } from "@dxos/react-ui-theme";
2001
- var markdownLinkRegexp = /\[([^\]]+)]\(([^)]+)\)/;
2002
- var tooltip = ({ onHover, regexp = markdownLinkRegexp }) => hoverTooltip2((view, pos) => {
2003
- const { from, text } = view.state.doc.lineAt(pos);
2004
- const p = pos - from;
2005
- let idx = 0;
2006
- let match;
2007
- do {
2008
- match = text.substring(idx).match(regexp);
2009
- if (!match) {
2010
- match = void 0;
2011
- break;
2012
- }
2013
- idx = text.indexOf(match[0]);
2014
- if (p >= idx && p < idx + match[0].length) {
2015
- break;
2016
- }
2017
- idx += match[0].length;
2018
- } while (true);
2019
- if (!match) {
2020
- return null;
2021
- }
2022
- const [, , url] = match ?? [];
2023
- return {
2024
- pos: idx + from,
2025
- end: idx + from + match[0].length,
2026
- above: true,
2027
- create: () => {
2028
- const el = document.createElement("div");
2029
- el.className = tooltipContent({}, "pli-2 plb-1");
2030
- onHover(el, url);
2031
- return {
2032
- dom: el,
2033
- offset: {
2034
- x: 0,
2035
- y: 4
2036
- }
2037
- };
2076
+ this.decorations = buildDecorations3(view);
2038
2077
  }
2039
- };
2040
- });
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();
2092
+ const { state } = view;
2093
+ const cursor = state.selection.main.head;
2094
+ for (const { from, to } of view.visibleRanges) {
2095
+ syntaxTree4(state).iterate({
2096
+ 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);
2100
+ }
2101
+ },
2102
+ from,
2103
+ to
2104
+ });
2105
+ }
2106
+ return builder.finish();
2107
+ };
2041
2108
 
2042
- // packages/ui/react-ui-editor/src/components/TextEditor/extensions/typewriter.ts
2109
+ // packages/ui/react-ui-editor/src/extensions/typewriter.ts
2043
2110
  import { keymap as keymap5 } from "@codemirror/view";
2044
2111
  var defaultItems = [
2045
2112
  "hello world!",
@@ -2096,8 +2163,29 @@ var typewriter = ({ delay = 75, items = defaultItems } = {}) => {
2096
2163
  ];
2097
2164
  };
2098
2165
 
2099
- // packages/ui/react-ui-editor/src/components/TextEditor/themes/default.ts
2100
- import get5 from "lodash.get";
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
+ // packages/ui/react-ui-editor/src/themes/default.ts
2188
+ import get3 from "lodash.get";
2101
2189
  var defaultTheme = {
2102
2190
  //
2103
2191
  // Main layout:
@@ -2126,21 +2214,21 @@ var defaultTheme = {
2126
2214
  "&.cm-focused": {
2127
2215
  outline: "none"
2128
2216
  },
2129
- "& .cm-scroller": {
2217
+ ".cm-scroller": {
2130
2218
  overflow: "visible",
2131
- fontFamily: get5(tokens, "fontFamily.mono", []).join(",")
2219
+ fontFamily: get3(tokens, "fontFamily.mono", []).join(",")
2132
2220
  },
2133
- "& .cm-content": {
2221
+ ".cm-content": {
2134
2222
  padding: 0,
2135
2223
  // NOTE: Base font size (otherwise defined by HTML tag, which might be different for storybook).
2136
2224
  fontSize: "16px"
2137
2225
  },
2138
2226
  "&light .cm-content": {
2139
- color: get5(tokens, "extend.colors.neutral.900", "black"),
2227
+ color: get3(tokens, "extend.colors.neutral.900", "black"),
2140
2228
  caretColor: "black"
2141
2229
  },
2142
2230
  "&dark .cm-content": {
2143
- color: get5(tokens, "extend.colors.neutral.100", "white"),
2231
+ color: get3(tokens, "extend.colors.neutral.100", "white"),
2144
2232
  caretColor: "white"
2145
2233
  },
2146
2234
  //
@@ -2152,158 +2240,120 @@ var defaultTheme = {
2152
2240
  "&dark .cm-cursor, &dark .cm-dropCursor": {
2153
2241
  borderLeft: "2px solid white"
2154
2242
  },
2155
- "& .cm-placeholder": {
2243
+ ".cm-placeholder": {
2156
2244
  fontWeight: 100
2157
2245
  },
2158
2246
  //
2159
2247
  // line
2160
2248
  //
2161
- "& .cm-line": {
2249
+ ".cm-line": {
2162
2250
  paddingInline: 0
2163
2251
  },
2164
- "& .cm-activeLine": {
2252
+ ".cm-activeLine": {
2165
2253
  background: "inherit"
2166
2254
  },
2167
2255
  //
2168
2256
  // Selection
2169
2257
  //
2170
2258
  "&light .cm-selectionBackground": {
2171
- background: get5(tokens, "extend.colors.primary.100")
2259
+ background: get3(tokens, "extend.colors.primary.100")
2172
2260
  },
2173
2261
  "&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground": {
2174
- background: get5(tokens, "extend.colors.primary.200")
2262
+ background: get3(tokens, "extend.colors.primary.200")
2175
2263
  },
2176
2264
  "&dark .cm-selectionBackground": {
2177
- background: get5(tokens, "extend.colors.primary.700")
2265
+ background: get3(tokens, "extend.colors.primary.700")
2178
2266
  },
2179
2267
  "&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground": {
2180
- background: get5(tokens, "extend.colors.primary.600")
2268
+ background: get3(tokens, "extend.colors.primary.600")
2181
2269
  },
2182
2270
  //
2183
2271
  // Search
2184
2272
  //
2185
2273
  "&light .cm-searchMatch": {
2186
- backgroundColor: get5(tokens, "extend.colors.yellow.100")
2274
+ backgroundColor: get3(tokens, "extend.colors.yellow.100")
2187
2275
  },
2188
2276
  "&dark .cm-searchMatch": {
2189
- backgroundColor: get5(tokens, "extend.colors.yellow.700")
2190
- },
2191
- //
2192
- // collaboration
2193
- // TODO(burdon): Review classnames (YJS dependent?) Note: e2e tests depend on this class.
2194
- //
2195
- "&light .cm-ySelection, &light .cm-yLineSelection": {
2196
- mixBlendMode: "multiply"
2197
- },
2198
- "&dark .cm-ySelection, &dark .cm-yLineSelection": {
2199
- mixBlendMode: "screen"
2200
- },
2201
- "& .cm-ySelectionInfo": {
2202
- padding: "2px 4px",
2203
- marginBlockStart: "-4px"
2204
- },
2205
- "& .cm-ySelection, & .cm-selectionMatch": {
2206
- paddingBlockStart: ".15em",
2207
- paddingBlockEnd: ".15em"
2208
- },
2209
- "& .cm-ySelectionCaret": {
2210
- display: "inline-block",
2211
- insetBlockStart: ".1em",
2212
- blockSize: "1.4em",
2213
- verticalAlign: "top"
2214
- },
2215
- "& .cm-yLineSelection": {
2216
- margin: 0
2277
+ backgroundColor: get3(tokens, "extend.colors.yellow.700")
2217
2278
  },
2218
2279
  //
2219
2280
  // link
2220
2281
  //
2221
- "& .cm-link": {
2222
- color: get5(tokens, "extend.colors.primary.500"),
2282
+ ".cm-link": {
2283
+ color: get3(tokens, "extend.colors.primary.500"),
2223
2284
  textDecorationLine: "underline",
2224
2285
  textDecorationThickness: "1px",
2225
2286
  textUnderlineOffset: "2px",
2226
2287
  borderRadius: ".125rem",
2227
- fontFamily: get5(tokens, "fontFamily.body", []).join(",")
2288
+ fontFamily: get3(tokens, "fontFamily.body", []).join(",")
2228
2289
  },
2229
2290
  //
2230
2291
  // tooltip
2231
2292
  //
2232
- "& .cm-tooltip": {
2293
+ ".cm-tooltip": {
2233
2294
  border: "none"
2234
2295
  },
2235
- "& .cm-tooltip-below": {},
2296
+ ".cm-tooltip-below": {},
2236
2297
  //
2237
2298
  // autocomplete
2238
2299
  //
2239
- "& .cm-tooltip-autocomplete": {
2300
+ ".cm-tooltip-autocomplete": {
2240
2301
  marginTop: "4px",
2241
2302
  marginLeft: "-3px"
2242
2303
  },
2243
- "& .cm-tooltip-autocomplete ul li": {},
2244
- "& .cm-tooltip-autocomplete ul li[aria-selected]": {},
2245
- "& .cm-completionIcon": {
2304
+ ".cm-tooltip-autocomplete ul li": {},
2305
+ ".cm-tooltip-autocomplete ul li[aria-selected]": {},
2306
+ ".cm-completionIcon": {
2246
2307
  display: "none"
2247
2308
  },
2248
- "& .cm-completionLabel": {
2249
- fontFamily: get5(tokens, "fontFamily.body", []).join(",")
2309
+ ".cm-completionLabel": {
2310
+ fontFamily: get3(tokens, "fontFamily.body", []).join(",")
2250
2311
  },
2251
- "& .cm-completionMatchedText": {
2312
+ ".cm-completionMatchedText": {
2252
2313
  textDecoration: "none"
2253
2314
  },
2254
2315
  //
2255
- // widgets
2256
- //
2257
- "& .cm-widgetBuffer": {
2258
- display: "none",
2259
- height: 0
2260
- },
2261
- //
2262
2316
  // table
2263
2317
  //
2264
- "& .cm-table *": {
2265
- fontFamily: `${get5(tokens, "fontFamily.mono", []).join(",")} !important`,
2318
+ ".cm-table *": {
2319
+ fontFamily: `${get3(tokens, "fontFamily.mono", []).join(",")} !important`,
2266
2320
  textDecoration: "none !important"
2267
2321
  },
2268
- "& .cm-table-head": {
2322
+ ".cm-table-head": {
2269
2323
  padding: "2px 16px 2px 0px",
2270
- borderBottom: `1px solid ${get5(tokens, "extend.colors.neutral.500")}`,
2324
+ borderBottom: `1px solid ${get3(tokens, "extend.colors.neutral.500")}`,
2271
2325
  fontWeight: 100,
2272
2326
  textAlign: "left",
2273
- color: get5(tokens, "extend.colors.neutral.500")
2327
+ color: get3(tokens, "extend.colors.neutral.500")
2274
2328
  },
2275
- "& .cm-table-cell": {
2329
+ ".cm-table-cell": {
2276
2330
  padding: "2px 16px 2px 0px"
2277
2331
  },
2278
2332
  //
2279
2333
  // image
2280
2334
  //
2281
- "& .cm-image": {
2282
- margin: "0.5rem 0"
2335
+ ".cm-image": {
2336
+ display: "block",
2337
+ height: "0"
2338
+ },
2339
+ ".cm-image.cm-loaded-image": {
2340
+ height: "auto",
2341
+ borderTop: "0.5rem solid transparent",
2342
+ borderBottom: "0.5rem solid transparent"
2283
2343
  },
2284
2344
  //
2285
2345
  // font size
2286
- // TODO(thure): This appears to be the best or only way to set selection caret heights, but it's far more verbose than it needs to be.
2346
+ // TODO(thure): This appears to be the best or only way to set selection caret heights,
2347
+ // but it's far more verbose than it needs to be.
2287
2348
  //
2288
- ...Object.keys(get5(tokens, "extend.fontSize", {})).reduce((acc, fontSize) => {
2289
- const height = get5(tokens, [
2290
- "extend",
2291
- "fontSize",
2292
- fontSize,
2293
- 1,
2294
- "lineHeight"
2295
- ]);
2296
- acc[`& .text-${fontSize} + .cm-ySelectionCaret`] = {
2297
- height
2298
- };
2299
- acc[`& .text-${fontSize} + .cm-ySelection + .cm-ySelectionCaret`] = {
2300
- height
2301
- };
2302
- acc[`& .text-${fontSize} + .cm-widgetBuffer + .cm-ySelectionCaret`] = {
2303
- height
2304
- };
2305
- return acc;
2306
- }, {}),
2349
+ // ...Object.keys(get(tokens, 'extend.fontSize', {})).reduce((acc: Record<string, any>, fontSize) => {
2350
+ // const height = get(tokens, ['extend', 'fontSize', fontSize, 1, 'lineHeight']);
2351
+ //
2352
+ // acc[`& .text-${fontSize} + .cm-ySelectionCaret`] = { height };
2353
+ // acc[`& .text-${fontSize} + .cm-ySelection + .cm-ySelectionCaret`] = { height };
2354
+ // acc[`& .text-${fontSize} + .cm-widgetBuffer + .cm-ySelectionCaret`] = { height };
2355
+ // return acc;
2356
+ // }, {}),
2307
2357
  /**
2308
2358
  * Panels
2309
2359
  * TODO(burdon): Needs styling attention (esp. dark mode).
@@ -2320,88 +2370,83 @@ var defaultTheme = {
2320
2370
  * </div>
2321
2371
  * </div
2322
2372
  */
2323
- "& .cm-panels": {
2324
- border: `1px solid ${get5(tokens, "extend.colors.neutral.200")}`
2373
+ ".cm-panels": {
2374
+ border: `1px solid ${get3(tokens, "extend.colors.neutral.200")}`
2325
2375
  },
2326
- "& .cm-panel": {
2327
- background: get5(tokens, "extend.colors.neutral.50"),
2328
- fontFamily: get5(tokens, "fontFamily.body", []).join(",")
2376
+ ".cm-panel": {
2377
+ background: get3(tokens, "extend.colors.neutral.50"),
2378
+ fontFamily: get3(tokens, "fontFamily.body", []).join(",")
2329
2379
  },
2330
- "& .cm-button": {
2380
+ ".cm-button": {
2331
2381
  margin: "4px",
2332
- fontFamily: get5(tokens, "fontFamily.body", []).join(","),
2333
- background: get5(tokens, "extend.colors.neutral.100"),
2382
+ fontFamily: get3(tokens, "fontFamily.body", []).join(","),
2383
+ background: get3(tokens, "extend.colors.neutral.100"),
2334
2384
  backgroundImage: "none",
2335
2385
  border: "none",
2336
2386
  "&:hover": {
2337
- background: get5(tokens, "extend.colors.neutral.200")
2387
+ background: get3(tokens, "extend.colors.neutral.200")
2338
2388
  },
2339
2389
  "&:active": {
2340
- background: get5(tokens, "extend.colors.neutral.300"),
2390
+ background: get3(tokens, "extend.colors.neutral.300"),
2341
2391
  backgroundImage: "none"
2342
2392
  }
2343
2393
  },
2344
- "& .cm-panel input[type=checkbox]": {
2394
+ ".cm-panel input[type=checkbox]": {
2345
2395
  marginRight: "0.4rem !important"
2346
2396
  }
2347
2397
  };
2348
2398
  var textTheme = {
2349
- "& .cm-scroller": {
2350
- fontFamily: get5(tokens, "fontFamily.body", []).join(",")
2399
+ ".cm-scroller": {
2400
+ fontFamily: get3(tokens, "fontFamily.body", []).join(",")
2351
2401
  },
2352
- "& .cm-placeholder": {
2353
- fontFamily: get5(tokens, "fontFamily.body", []).join(",")
2402
+ ".cm-placeholder": {
2403
+ fontFamily: get3(tokens, "fontFamily.body", []).join(",")
2354
2404
  }
2355
2405
  };
2356
2406
  var markdownTheme = {
2357
- // NOTE: Must leave base font family as is (i.e., monospace) due to fenced code blocks.
2358
- "& .cm-placeholder": {
2359
- fontFamily: get5(tokens, "fontFamily.body", []).join(",")
2407
+ ".cm-scroller": {
2408
+ fontFamily: get3(tokens, "fontFamily.body", []).join(",")
2409
+ },
2410
+ ".cm-placeholder": {
2411
+ fontFamily: get3(tokens, "fontFamily.body", []).join(",")
2360
2412
  }
2361
2413
  };
2362
2414
  var codeTheme = {
2363
- "& .cm-scroller": {
2364
- fontFamily: get5(tokens, "fontFamily.mono", []).join(",")
2415
+ ".cm-scroller": {
2416
+ fontFamily: get3(tokens, "fontFamily.mono", []).join(",")
2365
2417
  },
2366
- "& .cm-placeholder": {
2367
- fontFamily: get5(tokens, "fontFamily.mono", []).join(",")
2418
+ ".cm-placeholder": {
2419
+ fontFamily: get3(tokens, "fontFamily.mono", []).join(",")
2368
2420
  }
2369
2421
  };
2370
2422
 
2371
2423
  // packages/ui/react-ui-editor/src/components/TextEditor/TextEditor.tsx
2372
- import { EditorState as EditorState2 } from "@codemirror/state";
2373
- import { EditorView as EditorView12 } from "@codemirror/view";
2374
- import { useFocusableGroup } from "@fluentui/react-tabster";
2375
- import { vim } from "@replit/codemirror-vim";
2376
- import defaultsDeep2 from "lodash.defaultsdeep";
2377
- import React, { forwardRef, useCallback, useEffect as useEffect2, useImperativeHandle, useState as useState2 } from "react";
2378
- import { generateName } from "@dxos/display-name";
2379
- import { useThemeContext } from "@dxos/react-ui";
2380
- import { getColorForValue, inputSurface, mx as mx3 } from "@dxos/react-ui-theme";
2381
2424
  var EditorModes = [
2382
2425
  "default",
2383
2426
  "vim"
2384
2427
  ];
2385
- var BaseTextEditor = /* @__PURE__ */ forwardRef(({ model, readonly, comments: comments2, extensions = [], editorMode, slots = defaultSlots }, forwardedRef) => {
2386
- const { themeMode } = useThemeContext();
2428
+ var BaseTextEditor = /* @__PURE__ */ forwardRef(({ model, focus, selection, readonly, comments: comments2, extensions = [], editorMode, theme, slots = defaultSlots }, forwardedRef) => {
2387
2429
  const tabsterDOMAttribute = useFocusableGroup({
2388
2430
  tabBehavior: "limited"
2389
2431
  });
2390
- const [root, setRoot] = useState2(null);
2391
- const [{ state = void 0, view = void 0 } = {}, setEditor] = useState2();
2392
- useImperativeHandle(forwardedRef, () => ({
2393
- root,
2394
- state,
2432
+ const { themeMode } = useThemeContext();
2433
+ const rootRef = useRef(null);
2434
+ const [view, setView] = useState(null);
2435
+ useImperativeHandle(forwardedRef, () => view, [
2395
2436
  view
2396
- }), [
2437
+ ]);
2438
+ useEffect(() => {
2439
+ if (view && focus) {
2440
+ view.focus();
2441
+ }
2442
+ }, [
2397
2443
  view,
2398
- state,
2399
- root
2444
+ focus
2400
2445
  ]);
2401
- const { awareness, peer } = model;
2402
- useEffect2(() => {
2403
- if (awareness && peer) {
2404
- awareness.setLocalStateField("user", {
2446
+ const { awareness: awareness2, peer } = model;
2447
+ useEffect(() => {
2448
+ if (awareness2 && peer) {
2449
+ awareness2.setLocalStateField("user", {
2405
2450
  name: peer.name ?? generateName(peer.id),
2406
2451
  color: getColorForValue({
2407
2452
  value: peer.id,
@@ -2415,12 +2460,12 @@ var BaseTextEditor = /* @__PURE__ */ forwardRef(({ model, readonly, comments: co
2415
2460
  });
2416
2461
  }
2417
2462
  }, [
2418
- awareness,
2463
+ awareness2,
2419
2464
  peer,
2420
2465
  themeMode
2421
2466
  ]);
2422
- useEffect2(() => {
2423
- if (view && comments2?.length) {
2467
+ useEffect(() => {
2468
+ if (view && comments2 !== void 0) {
2424
2469
  view.dispatch({
2425
2470
  effects: setCommentRange.of({
2426
2471
  model,
@@ -2432,12 +2477,14 @@ var BaseTextEditor = /* @__PURE__ */ forwardRef(({ model, readonly, comments: co
2432
2477
  view,
2433
2478
  comments2
2434
2479
  ]);
2435
- useEffect2(() => {
2436
- if (!root) {
2480
+ useEffect(() => {
2481
+ if (!model || !rootRef.current) {
2437
2482
  return;
2438
2483
  }
2439
- const state2 = EditorState2.create({
2484
+ const state = EditorState2.create({
2440
2485
  doc: model.text(),
2486
+ // TODO(burdon): Composer should store and set selection when switching documents.
2487
+ selection,
2441
2488
  extensions: [
2442
2489
  readonly && EditorState2.readOnly.of(readonly),
2443
2490
  // TODO(burdon): Factor out VIM mode? (manage via MarkdownPlugin).
@@ -2445,7 +2492,7 @@ var BaseTextEditor = /* @__PURE__ */ forwardRef(({ model, readonly, comments: co
2445
2492
  // Theme.
2446
2493
  // TODO(burdon): Make theme configurable.
2447
2494
  EditorView12.baseTheme(defaultTheme),
2448
- EditorView12.theme(slots?.editor?.theme ?? {}),
2495
+ EditorView12.theme(theme ?? {}),
2449
2496
  EditorView12.darkTheme.of(themeMode === "dark"),
2450
2497
  // Storage and replication.
2451
2498
  model.extension,
@@ -2454,19 +2501,17 @@ var BaseTextEditor = /* @__PURE__ */ forwardRef(({ model, readonly, comments: co
2454
2501
  ].filter(Boolean)
2455
2502
  });
2456
2503
  view?.destroy();
2457
- setEditor({
2458
- state: state2,
2459
- view: new EditorView12({
2460
- state: state2,
2461
- parent: root
2462
- })
2504
+ const newView = new EditorView12({
2505
+ parent: rootRef.current,
2506
+ state
2463
2507
  });
2508
+ setView(newView);
2464
2509
  return () => {
2465
- view?.destroy();
2466
- setEditor(void 0);
2510
+ newView?.destroy();
2511
+ setView(null);
2467
2512
  };
2468
2513
  }, [
2469
- root,
2514
+ rootRef,
2470
2515
  model,
2471
2516
  readonly,
2472
2517
  editorMode,
@@ -2475,12 +2520,8 @@ var BaseTextEditor = /* @__PURE__ */ forwardRef(({ model, readonly, comments: co
2475
2520
  const handleKeyUp = useCallback((event) => {
2476
2521
  const { key, altKey, shiftKey, metaKey, ctrlKey } = event;
2477
2522
  switch (key) {
2478
- case "Enter": {
2479
- view?.contentDOM.focus();
2480
- break;
2481
- }
2482
2523
  case "Escape": {
2483
- editorMode === "vim" && (altKey || shiftKey || metaKey || ctrlKey) && root?.focus();
2524
+ editorMode === "vim" && (altKey || shiftKey || metaKey || ctrlKey) && rootRef.current?.focus();
2484
2525
  break;
2485
2526
  }
2486
2527
  }
@@ -2490,16 +2531,17 @@ var BaseTextEditor = /* @__PURE__ */ forwardRef(({ model, readonly, comments: co
2490
2531
  ]);
2491
2532
  return /* @__PURE__ */ React.createElement("div", {
2492
2533
  key: model.id,
2493
- ref: setRoot,
2534
+ role: "none",
2535
+ ref: rootRef,
2494
2536
  tabIndex: 0,
2495
- ...slots?.root,
2496
- ...editorMode !== "vim" && tabsterDOMAttribute,
2497
- onKeyUp: handleKeyUp
2537
+ onKeyUp: handleKeyUp,
2538
+ ...slots.root,
2539
+ ...editorMode !== "vim" && tabsterDOMAttribute
2498
2540
  });
2499
2541
  });
2500
- var TextEditor = /* @__PURE__ */ forwardRef(({ readonly, extensions = [], slots: _slots, ...props }, forwardedRef) => {
2542
+ var TextEditor = /* @__PURE__ */ forwardRef(({ readonly, placeholder: placeholder3, extensions = [], theme = textTheme, slots, ...props }, forwardedRef) => {
2501
2543
  const { themeMode } = useThemeContext();
2502
- const slots = defaultsDeep2({}, _slots, defaultTextSlots);
2544
+ const updatedSlots = defaultsDeep2({}, slots, defaultTextSlots);
2503
2545
  return /* @__PURE__ */ React.createElement(BaseTextEditor, {
2504
2546
  ref: forwardedRef,
2505
2547
  readonly,
@@ -2507,17 +2549,18 @@ var TextEditor = /* @__PURE__ */ forwardRef(({ readonly, extensions = [], slots:
2507
2549
  basicBundle({
2508
2550
  readonly,
2509
2551
  themeMode,
2510
- placeholder: slots?.editor?.placeholder
2552
+ placeholder: placeholder3
2511
2553
  }),
2512
2554
  ...extensions
2513
2555
  ],
2514
- slots,
2556
+ theme,
2557
+ slots: updatedSlots,
2515
2558
  ...props
2516
2559
  });
2517
2560
  });
2518
- var MarkdownEditor = /* @__PURE__ */ forwardRef(({ readonly, extensions = [], slots: _slots, ...props }, forwardedRef) => {
2561
+ var MarkdownEditor = /* @__PURE__ */ forwardRef(({ readonly, placeholder: placeholder3, extensions = [], theme = markdownTheme, slots, ...props }, forwardedRef) => {
2519
2562
  const { themeMode } = useThemeContext();
2520
- const slots = defaultsDeep2({}, _slots, defaultMarkdownSlots);
2563
+ const updatedSlots = defaultsDeep2({}, slots, defaultMarkdownSlots);
2521
2564
  return /* @__PURE__ */ React.createElement(BaseTextEditor, {
2522
2565
  ref: forwardedRef,
2523
2566
  readonly,
@@ -2525,53 +2568,369 @@ var MarkdownEditor = /* @__PURE__ */ forwardRef(({ readonly, extensions = [], sl
2525
2568
  markdownBundle({
2526
2569
  readonly,
2527
2570
  themeMode,
2528
- placeholder: slots?.editor?.placeholder
2571
+ placeholder: placeholder3
2529
2572
  }),
2530
2573
  ...extensions
2531
2574
  ],
2532
- slots,
2575
+ theme,
2576
+ slots: updatedSlots,
2533
2577
  ...props
2534
2578
  });
2535
2579
  });
2536
2580
  var defaultSlots = {
2537
2581
  root: {
2538
- className: mx3("p-2", inputSurface)
2582
+ className: mx3("p-2 overflow-y-auto", inputSurface)
2539
2583
  }
2540
2584
  };
2541
2585
  var defaultTextSlots = {
2542
- ...defaultSlots,
2543
- editor: {
2544
- theme: textTheme
2545
- }
2586
+ ...defaultSlots
2546
2587
  };
2547
2588
  var defaultMarkdownSlots = {
2548
- ...defaultSlots,
2549
- editor: {
2550
- theme: markdownTheme
2589
+ ...defaultSlots
2590
+ };
2591
+
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";
2596
+
2597
+ // packages/ui/react-ui-editor/src/hooks/awareness-provider.ts
2598
+ import { DeferredTask, Event as Event2, sleep } from "@dxos/async";
2599
+ import { Context as Context2 } from "@dxos/context";
2600
+ import { invariant as invariant3 } from "@dxos/invariant";
2601
+ import { log as log3 } from "@dxos/log";
2602
+ var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/ui/react-ui-editor/src/hooks/awareness-provider.ts";
2603
+ var DEBOUNCE_INTERVAL = 100;
2604
+ var SpaceAwarenessProvider = class {
2605
+ constructor(params) {
2606
+ this.remoteStateChange = new Event2();
2607
+ this._remoteStates = /* @__PURE__ */ new Map();
2608
+ this._space = params.space;
2609
+ this._channel = params.channel;
2610
+ this._peerId = params.peerId;
2611
+ this._info = params.info;
2612
+ }
2613
+ open() {
2614
+ this._ctx = new Context2();
2615
+ this._postTask = new DeferredTask(this._ctx, async () => {
2616
+ if (this._localState) {
2617
+ await this._space.postMessage(this._channel, {
2618
+ kind: "post",
2619
+ state: this._localState
2620
+ });
2621
+ await sleep(DEBOUNCE_INTERVAL);
2622
+ }
2623
+ });
2624
+ const unsubscribe = this._space.listen(this._channel, (message) => {
2625
+ switch (message.payload.kind) {
2626
+ case "query": {
2627
+ this._handleQueryMessage();
2628
+ break;
2629
+ }
2630
+ case "post": {
2631
+ this._handlePostMessage(message.payload);
2632
+ break;
2633
+ }
2634
+ }
2635
+ });
2636
+ this._ctx.onDispose(unsubscribe);
2637
+ void this._space.postMessage(this._channel, {
2638
+ kind: "query"
2639
+ }).catch((err) => {
2640
+ log3.debug("failed to query awareness", {
2641
+ err
2642
+ }, {
2643
+ F: __dxlog_file4,
2644
+ L: 85,
2645
+ S: this,
2646
+ C: (f, a) => f(...a)
2647
+ });
2648
+ });
2649
+ }
2650
+ close() {
2651
+ void this._ctx?.dispose();
2652
+ this._ctx = void 0;
2653
+ this._postTask = void 0;
2654
+ }
2655
+ update(position) {
2656
+ invariant3(this._postTask, void 0, {
2657
+ F: __dxlog_file4,
2658
+ L: 96,
2659
+ S: this,
2660
+ A: [
2661
+ "this._postTask",
2662
+ ""
2663
+ ]
2664
+ });
2665
+ this._localState = {
2666
+ peerId: this._peerId,
2667
+ position,
2668
+ info: this._info
2669
+ };
2670
+ this._postTask.schedule();
2671
+ }
2672
+ getRemoteStates() {
2673
+ return Array.from(this._remoteStates.values());
2674
+ }
2675
+ _handleQueryMessage() {
2676
+ invariant3(this._postTask, void 0, {
2677
+ F: __dxlog_file4,
2678
+ L: 111,
2679
+ S: this,
2680
+ A: [
2681
+ "this._postTask",
2682
+ ""
2683
+ ]
2684
+ });
2685
+ this._postTask.schedule();
2686
+ }
2687
+ _handlePostMessage(message) {
2688
+ invariant3(message.kind === "post", void 0, {
2689
+ F: __dxlog_file4,
2690
+ L: 116,
2691
+ S: this,
2692
+ A: [
2693
+ "message.kind === 'post'",
2694
+ ""
2695
+ ]
2696
+ });
2697
+ this._remoteStates.set(message.state.peerId, message.state);
2698
+ this.remoteStateChange.emit();
2699
+ }
2700
+ };
2701
+
2702
+ // packages/ui/react-ui-editor/src/hooks/useTextModel.ts
2703
+ 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";
2706
+
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));
2761
+ }
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)
2799
+ });
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));
2804
+ }
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;
2815
+ }
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;
2821
+ }
2822
+ default: {
2823
+ console.error("Invalid message:", messageType);
2824
+ return encoder;
2825
+ }
2826
+ }
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
+ }
2837
+ };
2838
+
2839
+ // packages/ui/react-ui-editor/src/hooks/useTextModel.ts
2840
+ var modelState = StateField5.define({
2841
+ create: () => void 0,
2842
+ update: (model) => model
2843
+ });
2844
+ var useTextModel = (props) => {
2845
+ const { identity, space, text } = props;
2846
+ const [model, setModel] = useState2();
2847
+ useEffect2(() => setModel(createModel(props)), [
2848
+ identity,
2849
+ space,
2850
+ text
2851
+ ]);
2852
+ return model;
2853
+ };
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;
2551
2862
  }
2552
2863
  };
2864
+
2865
+ // packages/ui/react-ui-editor/src/hooks/automerge.ts
2866
+ var createAutomergeModel = ({ space, identity, text }) => {
2867
+ const obj = text;
2868
+ const doc = getRawDoc(obj, [
2869
+ obj.field
2870
+ ]);
2871
+ const awarenessProvider = space && new SpaceAwarenessProvider({
2872
+ space,
2873
+ channel: `automerge.awareness.${obj.id}`,
2874
+ info: {
2875
+ displayName: identity?.profile?.displayName ?? "",
2876
+ color: cursorColor.color,
2877
+ lightColor: cursorColor.light
2878
+ },
2879
+ peerId: identity?.identityKey.toHex() ?? "Anonymous"
2880
+ });
2881
+ const model = {
2882
+ id: obj.id,
2883
+ content: doc,
2884
+ 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),
2895
+ peer: identity ? {
2896
+ id: identity.identityKey.toHex(),
2897
+ name: identity.profile?.displayName
2898
+ } : void 0
2899
+ };
2900
+ return model;
2901
+ };
2553
2902
  export {
2903
+ AwarenessProvider,
2554
2904
  BaseTextEditor,
2905
+ Cursor,
2555
2906
  Doc,
2556
2907
  EditorModes,
2557
2908
  MarkdownEditor,
2909
+ RemoteSelectionsDecorator,
2558
2910
  SpaceAwarenessProvider,
2559
2911
  TextEditor,
2560
2912
  TextKind,
2913
+ YAwarenessProvider,
2561
2914
  YText,
2562
2915
  YXmlFragment,
2563
2916
  autocomplete,
2917
+ automerge3 as automerge,
2918
+ awareness,
2564
2919
  basicBundle,
2565
2920
  blast,
2921
+ callbackWrapper,
2566
2922
  code2 as code,
2567
2923
  codeTheme,
2568
2924
  comments,
2569
- cursorColor,
2925
+ createAutomergeModel,
2926
+ createYjsModel,
2927
+ cursorConverter,
2570
2928
  defaultMarkdownSlots,
2571
2929
  defaultOptions,
2572
2930
  defaultSlots,
2573
2931
  defaultTextSlots,
2574
2932
  defaultTheme,
2933
+ getToken,
2575
2934
  hr,
2576
2935
  image,
2577
2936
  link,
@@ -2582,15 +2941,16 @@ export {
2582
2941
  markdownTagsExtensions,
2583
2942
  markdownTheme,
2584
2943
  mention,
2585
- mermaid,
2586
2944
  modelState,
2587
2945
  setCommentRange,
2946
+ setFocus,
2947
+ setSelection,
2588
2948
  table,
2589
2949
  tags2 as tags,
2590
2950
  tasklist,
2591
2951
  textTheme,
2592
- tooltip,
2593
2952
  typewriter,
2594
- useTextModel
2953
+ useTextModel,
2954
+ yjs
2595
2955
  };
2596
2956
  //# sourceMappingURL=index.mjs.map