@dxos/react-ui-editor 0.3.11-main.0e40963 → 0.3.11-main.1c19c60

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 (113) hide show
  1. package/dist/lib/browser/index.mjs +1274 -811
  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/TextEditor.stories.d.ts +3 -0
  5. package/dist/types/src/components/TextEditor/TextEditor.stories.d.ts.map +1 -1
  6. package/dist/types/src/{hooks/automerge → components/TextEditor}/automerge.stories.d.ts +6 -1
  7. package/dist/types/src/components/TextEditor/automerge.stories.d.ts.map +1 -0
  8. package/dist/types/src/components/TextEditor/codemirror.stories.d.ts.map +1 -1
  9. package/dist/types/src/{hooks/yjs → components/TextEditor}/yjs.stories.d.ts +1 -1
  10. package/dist/types/src/components/TextEditor/yjs.stories.d.ts.map +1 -0
  11. package/dist/types/src/extensions/automerge/automerge.d.ts +9 -0
  12. package/dist/types/src/extensions/automerge/automerge.d.ts.map +1 -0
  13. package/dist/types/src/extensions/automerge/cursor.d.ts +5 -0
  14. package/dist/types/src/extensions/automerge/cursor.d.ts.map +1 -0
  15. package/dist/types/src/extensions/automerge/defs.d.ts +26 -0
  16. package/dist/types/src/extensions/automerge/defs.d.ts.map +1 -0
  17. package/dist/types/src/extensions/automerge/index.d.ts +3 -0
  18. package/dist/types/src/extensions/automerge/index.d.ts.map +1 -0
  19. package/dist/types/src/{hooks → extensions}/automerge/semaphore.d.ts +4 -4
  20. package/dist/types/src/extensions/automerge/semaphore.d.ts.map +1 -0
  21. package/dist/types/src/extensions/automerge/update-automerge.d.ts +5 -0
  22. package/dist/types/src/extensions/automerge/update-automerge.d.ts.map +1 -0
  23. package/dist/types/src/extensions/automerge/update-codemirror.d.ts.map +1 -0
  24. package/dist/types/src/extensions/awareness.d.ts +46 -0
  25. package/dist/types/src/extensions/awareness.d.ts.map +1 -0
  26. package/dist/types/src/extensions/comments.d.ts +3 -1
  27. package/dist/types/src/extensions/comments.d.ts.map +1 -1
  28. package/dist/types/src/extensions/index.d.ts +3 -0
  29. package/dist/types/src/extensions/index.d.ts.map +1 -1
  30. package/dist/types/src/extensions/yjs/cursor.d.ts +4 -0
  31. package/dist/types/src/extensions/yjs/cursor.d.ts.map +1 -0
  32. package/dist/types/src/extensions/yjs/index.d.ts +2 -0
  33. package/dist/types/src/extensions/yjs/index.d.ts.map +1 -0
  34. package/dist/types/src/extensions/yjs/yjs.d.ts +4 -0
  35. package/dist/types/src/extensions/yjs/yjs.d.ts.map +1 -0
  36. package/dist/types/src/extensions/yjs/yjs.test.d.ts.map +1 -0
  37. package/dist/types/src/hooks/automerge.d.ts +3 -0
  38. package/dist/types/src/hooks/automerge.d.ts.map +1 -0
  39. package/dist/types/src/hooks/awareness-provider.d.ts +28 -0
  40. package/dist/types/src/hooks/awareness-provider.d.ts.map +1 -0
  41. package/dist/types/src/hooks/index.d.ts +2 -0
  42. package/dist/types/src/hooks/index.d.ts.map +1 -1
  43. package/dist/types/src/hooks/useTextModel.d.ts +8 -7
  44. package/dist/types/src/hooks/useTextModel.d.ts.map +1 -1
  45. package/dist/types/src/hooks/{yjs/space-provider.d.ts → yjs.d.ts} +8 -8
  46. package/dist/types/src/hooks/yjs.d.ts.map +1 -0
  47. package/dist/types/src/styles/cursors.d.ts.map +1 -0
  48. package/dist/types/src/styles/index.d.ts +1 -0
  49. package/dist/types/src/styles/index.d.ts.map +1 -1
  50. package/dist/types/src/testing/replicator.d.ts +2 -2
  51. package/dist/types/src/testing/replicator.d.ts.map +1 -1
  52. package/dist/types/src/util/cursor.d.ts +17 -0
  53. package/dist/types/src/util/cursor.d.ts.map +1 -0
  54. package/dist/types/src/util/index.d.ts +3 -0
  55. package/dist/types/src/util/index.d.ts.map +1 -0
  56. package/dist/types/src/util/util.d.ts.map +1 -0
  57. package/package.json +22 -21
  58. package/src/components/TextEditor/TextEditor.stories.tsx +13 -0
  59. package/src/components/TextEditor/TextEditor.tsx +1 -1
  60. package/src/{hooks/automerge → components/TextEditor}/automerge.stories.tsx +66 -6
  61. package/src/components/TextEditor/codemirror.stories.ts +3 -2
  62. package/src/{hooks/yjs → components/TextEditor}/yjs.stories.tsx +1 -1
  63. package/src/extensions/automerge/automerge.ts +94 -0
  64. package/src/extensions/automerge/cursor.ts +51 -0
  65. package/src/extensions/automerge/defs.ts +62 -0
  66. package/src/extensions/automerge/index.ts +6 -0
  67. package/src/{hooks → extensions}/automerge/semaphore.ts +14 -12
  68. package/src/{hooks → extensions}/automerge/update-automerge.ts +5 -6
  69. package/src/{hooks → extensions}/automerge/update-codemirror.ts +13 -5
  70. package/src/extensions/awareness.ts +316 -0
  71. package/src/extensions/comments.ts +45 -15
  72. package/src/extensions/index.ts +3 -0
  73. package/src/extensions/yjs/cursor.ts +21 -0
  74. package/src/extensions/yjs/index.ts +5 -0
  75. package/src/{hooks → extensions}/yjs/yjs.test.ts +1 -25
  76. package/src/extensions/yjs/yjs.ts +16 -0
  77. package/src/hooks/automerge.ts +52 -0
  78. package/src/hooks/awareness-provider.ts +120 -0
  79. package/src/hooks/index.ts +2 -0
  80. package/src/hooks/useTextModel.ts +19 -93
  81. package/src/hooks/{yjs/space-provider.ts → yjs.ts} +71 -19
  82. package/src/styles/index.ts +1 -0
  83. package/src/testing/replicator.ts +10 -15
  84. package/src/util/cursor.ts +29 -0
  85. package/src/util/index.ts +6 -0
  86. package/dist/types/src/extensions/util.d.ts.map +0 -1
  87. package/dist/types/src/hooks/automerge/automerge.stories.d.ts.map +0 -1
  88. package/dist/types/src/hooks/automerge/handle.d.ts +0 -9
  89. package/dist/types/src/hooks/automerge/handle.d.ts.map +0 -1
  90. package/dist/types/src/hooks/automerge/index.d.ts +0 -3
  91. package/dist/types/src/hooks/automerge/index.d.ts.map +0 -1
  92. package/dist/types/src/hooks/automerge/plugin.d.ts +0 -26
  93. package/dist/types/src/hooks/automerge/plugin.d.ts.map +0 -1
  94. package/dist/types/src/hooks/automerge/semaphore.d.ts.map +0 -1
  95. package/dist/types/src/hooks/automerge/update-automerge.d.ts +0 -6
  96. package/dist/types/src/hooks/automerge/update-automerge.d.ts.map +0 -1
  97. package/dist/types/src/hooks/automerge/update-codemirror.d.ts.map +0 -1
  98. package/dist/types/src/hooks/yjs/cursors.d.ts.map +0 -1
  99. package/dist/types/src/hooks/yjs/index.d.ts +0 -3
  100. package/dist/types/src/hooks/yjs/index.d.ts.map +0 -1
  101. package/dist/types/src/hooks/yjs/space-provider.d.ts.map +0 -1
  102. package/dist/types/src/hooks/yjs/yjs.stories.d.ts.map +0 -1
  103. package/dist/types/src/hooks/yjs/yjs.test.d.ts.map +0 -1
  104. package/src/hooks/automerge/handle.ts +0 -14
  105. package/src/hooks/automerge/index.ts +0 -6
  106. package/src/hooks/automerge/plugin.ts +0 -134
  107. package/src/hooks/yjs/index.ts +0 -6
  108. /package/dist/types/src/{hooks → extensions}/automerge/update-codemirror.d.ts +0 -0
  109. /package/dist/types/src/{hooks → extensions}/yjs/yjs.test.d.ts +0 -0
  110. /package/dist/types/src/{hooks/yjs → styles}/cursors.d.ts +0 -0
  111. /package/dist/types/src/{extensions → util}/util.d.ts +0 -0
  112. /package/src/{hooks/yjs → styles}/cursors.ts +0 -0
  113. /package/src/{extensions → util}/util.ts +0 -0
@@ -1,15 +1,23 @@
1
1
  //
2
2
  // Copyright 2023 DXOS.org
3
+ // Copyright 2024 Automerge
4
+ // Ref: https://github.com/automerge/automerge-codemirror
3
5
  //
4
6
 
5
- // TODO(burdon): Additional copyright?
6
-
7
+ import { type StateField } from '@codemirror/state';
7
8
  import { type EditorView } from '@codemirror/view';
8
9
 
9
10
  import { next as automerge } from '@dxos/automerge/automerge';
10
11
 
11
- import { type IDocHandle } from './handle';
12
- import { type Field, isReconcileTx, getPath, reconcileAnnotationType, updateHeads, getLastHeads } from './plugin';
12
+ import {
13
+ getLastHeads,
14
+ getPath,
15
+ isReconcileTx,
16
+ reconcileAnnotationType,
17
+ updateHeads,
18
+ type IDocHandle,
19
+ type Value,
20
+ } from './defs';
13
21
  import { updateAutomerge } from './update-automerge';
14
22
  import { updateCodeMirror } from './update-codemirror';
15
23
 
@@ -22,15 +30,10 @@ type ChangeFn = (atHeads: Heads, change: (doc: Doc<unknown>) => void) => Heads |
22
30
  * TODO(burdon): Comment.
23
31
  */
24
32
  export class PatchSemaphore {
25
- _field!: Field;
26
33
  _inReconcile = false;
27
34
  _queue: Array<ChangeFn> = [];
28
35
 
29
- constructor(field?: Field) {
30
- if (field !== undefined) {
31
- this._field = field;
32
- }
33
- }
36
+ constructor(private readonly _field: StateField<Value>) {}
34
37
 
35
38
  reconcile = (handle: IDocHandle, view: EditorView) => {
36
39
  if (this._inReconcile) {
@@ -42,9 +45,8 @@ export class PatchSemaphore {
42
45
  const oldHeads = getLastHeads(view.state, this._field);
43
46
  let selection = view.state.selection;
44
47
 
45
- const transactions = view.state.field(this._field).unreconciledTransactions.filter((tx) => !isReconcileTx(tx));
46
-
47
48
  // First undo all the unreconciled transactions.
49
+ const transactions = view.state.field(this._field).unreconciledTransactions.filter((tx) => !isReconcileTx(tx));
48
50
  const toInvert = transactions.slice().reverse();
49
51
  for (const tx of toInvert) {
50
52
  const inverted = tx.changes.invert(tx.startState.doc);
@@ -1,18 +1,17 @@
1
1
  //
2
2
  // Copyright 2023 DXOS.org
3
+ // Copyright 2024 Automerge
4
+ // Ref: https://github.com/automerge/automerge-codemirror
3
5
  //
4
6
 
5
- // TODO(burdon): Additional copyright?
6
-
7
- import { type EditorState, type Text, type Transaction } from '@codemirror/state';
7
+ import { type EditorState, type StateField, type Text, type Transaction } from '@codemirror/state';
8
8
 
9
9
  import { next as am, type Heads } from '@dxos/automerge/automerge';
10
10
 
11
- import { type IDocHandle } from './handle';
12
- import { type Field } from './plugin';
11
+ import { type IDocHandle, type Value } from './defs';
13
12
 
14
13
  export const updateAutomerge = (
15
- field: Field,
14
+ field: StateField<Value>,
16
15
  handle: IDocHandle,
17
16
  transactions: Transaction[],
18
17
  state: EditorState,
@@ -1,9 +1,9 @@
1
1
  //
2
2
  // Copyright 2023 DXOS.org
3
+ // Copyright 2024 Automerge
4
+ // Ref: https://github.com/automerge/automerge-codemirror
3
5
  //
4
6
 
5
- // TODO(burdon): Additional copyright?
6
-
7
7
  import { ChangeSet, type ChangeSpec, type EditorSelection, type EditorState } from '@codemirror/state';
8
8
  import { type EditorView } from '@codemirror/view';
9
9
 
@@ -16,7 +16,7 @@ import {
16
16
  type SpliceTextPatch,
17
17
  } from '@dxos/automerge/automerge';
18
18
 
19
- import { reconcileAnnotationType } from './plugin';
19
+ import { reconcileAnnotationType } from './defs';
20
20
 
21
21
  export const updateCodeMirror = (view: EditorView, selection: EditorSelection, target: Prop[], patches: Patch[]) => {
22
22
  for (const patch of patches) {
@@ -56,6 +56,7 @@ const handleInsert = (target: Prop[], patch: InsertPatch): Array<ChangeSpec> =>
56
56
  if (index == null) {
57
57
  return [];
58
58
  }
59
+
59
60
  const text = patch.values.map((v) => (v ? v.toString() : '')).join('');
60
61
  return [{ from: index, to: index, insert: text }];
61
62
  };
@@ -65,6 +66,7 @@ const handleSplice = (target: Prop[], patch: SpliceTextPatch): Array<ChangeSpec>
65
66
  if (index == null) {
66
67
  return [];
67
68
  }
69
+
68
70
  return [{ from: index, insert: patch.value }];
69
71
  };
70
72
 
@@ -73,6 +75,7 @@ const handleDel = (target: Prop[], patch: DelPatch): Array<ChangeSpec> => {
73
75
  if (index == null) {
74
76
  return [];
75
77
  }
78
+
76
79
  const length = patch.length || 1;
77
80
  return [{ from: index, to: index + length }];
78
81
  };
@@ -82,27 +85,32 @@ const handlePut = (target: Prop[], patch: PutPatch, state: EditorState): Array<C
82
85
  if (index == null) {
83
86
  return [];
84
87
  }
88
+
85
89
  const length = state.doc.length;
86
90
  if (typeof patch.value !== 'string') {
87
91
  return []; // TODO(dmaretskyi): How to handle non string values?
88
92
  }
93
+
89
94
  return [{ from: 0, to: length, insert: patch.value as any }];
90
95
  };
91
96
 
92
- // If the path of the patch is of the form [path, <index>] then we know this is
93
- // a path to a character within the sequence given by path
97
+ // If the path of the patch is of the form [path, <index>] then we know this is a path to a character
98
+ // within the sequence given by path.
94
99
  const charPath = (textPath: Prop[], candidatePath: Prop[]): number | null => {
95
100
  if (candidatePath.length !== textPath.length + 1) {
96
101
  return null;
97
102
  }
103
+
98
104
  for (let i = 0; i < textPath.length; i++) {
99
105
  if (textPath[i] !== candidatePath[i]) {
100
106
  return null;
101
107
  }
102
108
  }
109
+
103
110
  const index = candidatePath[candidatePath.length - 1];
104
111
  if (typeof index === 'number') {
105
112
  return index;
106
113
  }
114
+
107
115
  return null;
108
116
  };
@@ -0,0 +1,316 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ import { Annotation, Facet, type Extension, RangeSet, type Range } from '@codemirror/state';
6
+ import {
7
+ Decoration,
8
+ type DecorationSet,
9
+ EditorView,
10
+ type PluginValue,
11
+ ViewPlugin,
12
+ type ViewUpdate,
13
+ WidgetType,
14
+ } from '@codemirror/view';
15
+
16
+ import { Event } from '@dxos/async';
17
+ import { Context } from '@dxos/context';
18
+
19
+ import { CursorConverter } from '../util';
20
+
21
+ export interface AwarenessProvider {
22
+ remoteStateChange: Event<void>;
23
+
24
+ open(): void;
25
+ close(): void;
26
+
27
+ update(position: AwarenessPosition | undefined): void;
28
+ getRemoteStates(): AwarenessState[];
29
+ }
30
+
31
+ const dummyProvider: AwarenessProvider = {
32
+ remoteStateChange: new Event(),
33
+
34
+ open: () => {},
35
+ close: () => {},
36
+
37
+ update: () => {},
38
+ getRemoteStates: () => [],
39
+ };
40
+
41
+ export const AwarenessProvider = Facet.define<AwarenessProvider, AwarenessProvider>({
42
+ combine: (providers) => providers[0] ?? dummyProvider,
43
+ });
44
+
45
+ // TODO(dmaretskyi): Specify the users that actually changed. Currently, we recalculate positions for every user.
46
+ const RemoteSelectionChangedAnnotation = Annotation.define();
47
+
48
+ export type AwarenessPosition = {
49
+ anchor?: string;
50
+ head?: string;
51
+ };
52
+
53
+ export type AwarenessInfo = {
54
+ displayName?: string;
55
+ // TODO(burdon): Rename light/dark.
56
+ color?: string;
57
+ lightColor?: string;
58
+ };
59
+
60
+ export type AwarenessState = {
61
+ position?: AwarenessPosition;
62
+ peerId: string;
63
+ info: AwarenessInfo;
64
+ };
65
+
66
+ /**
67
+ * Extension provides presence information about other peers.
68
+ */
69
+ // TODO(burdon): Why provide default?
70
+ export const awareness = (provider = dummyProvider): Extension => {
71
+ return [
72
+ AwarenessProvider.of(provider),
73
+ ViewPlugin.fromClass(RemoteSelectionsDecorator, {
74
+ decorations: (value) => value.decorations,
75
+ }),
76
+ styles,
77
+ ];
78
+ };
79
+
80
+ /**
81
+ * Generates selection decorations from remote peers.
82
+ */
83
+ export class RemoteSelectionsDecorator implements PluginValue {
84
+ public decorations: DecorationSet = RangeSet.of([]);
85
+
86
+ private readonly _ctx = new Context();
87
+
88
+ private _cursorConverter: CursorConverter;
89
+ private _provider: AwarenessProvider;
90
+ private _lastAnchor?: number = undefined;
91
+ private _lastHead?: number = undefined;
92
+
93
+ constructor(view: EditorView) {
94
+ this._cursorConverter = view.state.facet(CursorConverter);
95
+ this._provider = view.state.facet(AwarenessProvider);
96
+ this._provider.open();
97
+ this._provider.remoteStateChange.on(this._ctx, () => {
98
+ view.dispatch({ annotations: [RemoteSelectionChangedAnnotation.of([])] });
99
+ });
100
+ }
101
+
102
+ destroy() {
103
+ void this._ctx.dispose();
104
+ this._provider.close();
105
+ }
106
+
107
+ update(update: ViewUpdate) {
108
+ this._updateLocalSelection(update);
109
+ this._updateRemoteSelections(update);
110
+ }
111
+
112
+ private _updateLocalSelection(update: ViewUpdate) {
113
+ const hasFocus = update.view.hasFocus && update.view.dom.ownerDocument.hasFocus();
114
+ const { anchor = undefined, head = undefined } = hasFocus ? update.state.selection.main : {};
115
+ if (this._lastAnchor === anchor && this._lastHead === head) {
116
+ return;
117
+ }
118
+
119
+ this._lastAnchor = anchor;
120
+ this._lastHead = head;
121
+
122
+ this._provider.update(
123
+ anchor !== undefined && head !== undefined
124
+ ? {
125
+ anchor: this._cursorConverter.toCursor(anchor),
126
+ head: this._cursorConverter.toCursor(head),
127
+ }
128
+ : undefined,
129
+ );
130
+ }
131
+
132
+ private _updateRemoteSelections(update: ViewUpdate) {
133
+ const decorations: Range<Decoration>[] = [];
134
+ const awarenessStates = this._provider.getRemoteStates();
135
+ for (const state of awarenessStates) {
136
+ const anchor = state.position?.anchor ? this._cursorConverter.fromCursor(state.position.anchor) : null;
137
+ const head = state.position?.head ? this._cursorConverter.fromCursor(state.position.head) : null;
138
+ if (anchor == null || head == null) {
139
+ continue;
140
+ }
141
+
142
+ const start = Math.min(Math.min(anchor, head), update.view.state.doc.length);
143
+ const end = Math.min(Math.max(anchor, head), update.view.state.doc.length);
144
+
145
+ const startLine = update.view.state.doc.lineAt(start);
146
+ const endLine = update.view.state.doc.lineAt(end);
147
+
148
+ // TODO(burdon): Factor out styles.
149
+ const color = state.info.color ?? '#30bced';
150
+ const lightColor = state.info.lightColor ?? color + '33';
151
+
152
+ if (startLine.number === endLine.number) {
153
+ // Selected content in a single line.
154
+ decorations.push({
155
+ from: start,
156
+ to: end,
157
+ value: Decoration.mark({
158
+ attributes: { style: `background-color: ${lightColor}` },
159
+ class: 'cm-ySelection',
160
+ }),
161
+ });
162
+ } else {
163
+ // Selected content in multiple lines; first, render text-selection in the first line.
164
+ decorations.push({
165
+ from: start,
166
+ to: startLine.from + startLine.length,
167
+ value: Decoration.mark({
168
+ attributes: { style: `background-color: ${color}` },
169
+ class: 'cm-ySelection',
170
+ }),
171
+ });
172
+
173
+ // Render text-selection in the last line.
174
+ decorations.push({
175
+ from: endLine.from,
176
+ to: end,
177
+ value: Decoration.mark({
178
+ attributes: { style: `background-color: ${color}` },
179
+ class: 'cm-ySelection',
180
+ }),
181
+ });
182
+
183
+ for (let i = startLine.number + 1; i < endLine.number; i++) {
184
+ const linePos = update.view.state.doc.line(i).from;
185
+ decorations.push({
186
+ from: linePos,
187
+ to: linePos,
188
+ value: Decoration.line({
189
+ attributes: { style: `background-color: ${color}`, class: 'cm-yLineSelection' },
190
+ }),
191
+ });
192
+ }
193
+ }
194
+
195
+ decorations.push({
196
+ from: head,
197
+ to: head,
198
+ value: Decoration.widget({
199
+ side: head - anchor > 0 ? -1 : 1, // The local cursor should be rendered outside the remote selection.
200
+ block: false,
201
+ widget: new RemoteCaretWidget(state.info.displayName ?? 'Anonymous', color),
202
+ }),
203
+ });
204
+ }
205
+
206
+ this.decorations = Decoration.set(decorations, true);
207
+ }
208
+ }
209
+
210
+ class RemoteCaretWidget extends WidgetType {
211
+ constructor(public name: string, public color: string) {
212
+ super();
213
+ this.name = name;
214
+ this.color = color;
215
+ }
216
+
217
+ toDOM(): HTMLElement {
218
+ const span = document.createElement('span');
219
+ span.className = 'cm-ySelectionCaret';
220
+ span.style.backgroundColor = this.color;
221
+ span.style.borderColor = this.color;
222
+
223
+ const dot = document.createElement('div');
224
+ dot.className = 'cm-ySelectionCaretDot';
225
+
226
+ const info = document.createElement('div');
227
+ info.className = 'cm-ySelectionInfo';
228
+ info.innerText = this.name;
229
+
230
+ span.appendChild(document.createTextNode('\u2060'));
231
+ span.appendChild(dot);
232
+ span.appendChild(document.createTextNode('\u2060'));
233
+ span.appendChild(info);
234
+ span.appendChild(document.createTextNode('\u2060'));
235
+
236
+ return span;
237
+ }
238
+
239
+ override eq(widget: this) {
240
+ return widget.color === this.color;
241
+ }
242
+
243
+ compare(widget: this) {
244
+ return widget.color === this.color;
245
+ }
246
+
247
+ override updateDOM() {
248
+ return false;
249
+ }
250
+
251
+ override get estimatedHeight() {
252
+ return -1;
253
+ }
254
+
255
+ override ignoreEvent() {
256
+ return true;
257
+ }
258
+ }
259
+
260
+ // TODO(burdon): Rename prefix (y for yjs?)
261
+ const styles = EditorView.baseTheme({
262
+ '.cm-ySelection': {},
263
+ '.cm-yLineSelection': {
264
+ padding: 0,
265
+ margin: '0px 2px 0px 4px',
266
+ },
267
+ '.cm-ySelectionCaret': {
268
+ position: 'relative',
269
+ borderLeft: '1px solid black',
270
+ borderRight: '1px solid black',
271
+ marginLeft: '-1px',
272
+ marginRight: '-1px',
273
+ boxSizing: 'border-box',
274
+ display: 'inline',
275
+ },
276
+ '.cm-ySelectionCaretDot': {
277
+ borderRadius: '50%',
278
+ position: 'absolute',
279
+ width: '.4em',
280
+ height: '.4em',
281
+ top: '-.2em',
282
+ left: '-.2em',
283
+ backgroundColor: 'inherit',
284
+ transition: 'transform .3s ease-in-out',
285
+ boxSizing: 'border-box',
286
+ },
287
+ '.cm-ySelectionCaret:hover > .cm-ySelectionCaretDot': {
288
+ transformOrigin: 'bottom center',
289
+ transform: 'scale(0)',
290
+ },
291
+ '.cm-ySelectionInfo': {
292
+ position: 'absolute',
293
+ top: '-1.05em',
294
+ left: '-1px',
295
+ fontSize: '.75em',
296
+ fontFamily: 'serif',
297
+ fontStyle: 'normal',
298
+ fontWeight: 'normal',
299
+ lineHeight: 'normal',
300
+ userSelect: 'none',
301
+ color: 'white',
302
+ paddingLeft: '2px',
303
+ paddingRight: '2px',
304
+ zIndex: 101,
305
+ transition: 'opacity .3s ease-in-out',
306
+ backgroundColor: 'inherit',
307
+ // these should be separate
308
+ opacity: 0,
309
+ transitionDelay: '0s',
310
+ whiteSpace: 'nowrap',
311
+ },
312
+ '.cm-ySelectionCaret:hover > .cm-ySelectionInfo': {
313
+ opacity: 1,
314
+ transitionDelay: '0s',
315
+ },
316
+ });
@@ -16,6 +16,7 @@ import {
16
16
  WidgetType,
17
17
  type Rect,
18
18
  } from '@codemirror/view';
19
+ import get from 'lodash.get';
19
20
  import sortBy from 'lodash.sortby';
20
21
 
21
22
  import { debounce } from '@dxos/async';
@@ -23,10 +24,10 @@ import { invariant } from '@dxos/invariant';
23
24
  import { log } from '@dxos/log';
24
25
  import { nonNullable } from '@dxos/util';
25
26
 
26
- import { callbackWrapper } from './util';
27
- import { type CommentRange, type EditorModel, modelState, type Range } from '../hooks';
27
+ import { type CommentRange, type EditorModel, type Range } from '../hooks';
28
+ import { tokens } from '../styles';
29
+ import { callbackWrapper, CursorConverter } from '../util';
28
30
 
29
- // TODO(burdon): Handle scroll to.
30
31
  // TODO(burdon): Handle delete, cut, copy, and paste (separately) text that includes comment range.
31
32
  // TODO(burdon): Consider breaking into separate plugin (since not standalone)? Like mermaid?
32
33
 
@@ -42,10 +43,10 @@ const styles = EditorView.baseTheme({
42
43
  backgroundColor: 'orange',
43
44
  },
44
45
  '& .cm-comment': {
45
- backgroundColor: 'yellow',
46
+ backgroundColor: get(tokens, 'extend.colors.yellow.50'),
46
47
  },
47
48
  '& .cm-comment-active': {
48
- backgroundColor: 'orange',
49
+ backgroundColor: get(tokens, 'extend.colors.yellow.100'),
49
50
  },
50
51
  });
51
52
 
@@ -71,9 +72,22 @@ export type CommentsState = CommentSelected & {
71
72
  ranges: ExtendedCommentRange[];
72
73
  };
73
74
 
75
+ export const setFocus = (view: EditorView, thread: string) => {
76
+ const range = view.state.field(commentsStateField).ranges.find((range) => range.id === thread);
77
+ if (!range) {
78
+ return;
79
+ }
80
+
81
+ view.dispatch({
82
+ effects: setSelection.of({ active: thread }),
83
+ selection: { anchor: range.from },
84
+ scrollIntoView: true,
85
+ });
86
+ };
87
+
74
88
  export const setCommentRange = StateEffect.define<{ model: EditorModel; comments: CommentRange[] }>();
75
89
 
76
- const setSelection = StateEffect.define<CommentSelected>();
90
+ export const setSelection = StateEffect.define<CommentSelected>();
77
91
 
78
92
  const setCommentState = StateEffect.define<CommentsState>();
79
93
 
@@ -85,6 +99,8 @@ const setCommentState = StateEffect.define<CommentsState>();
85
99
  const commentsStateField = StateField.define<CommentsState>({
86
100
  create: () => ({ ranges: [] }),
87
101
  update: (value, tr) => {
102
+ const cursorConverter = tr.state.facet(CursorConverter);
103
+
88
104
  for (const effect of tr.effects) {
89
105
  // Update selection.
90
106
  if (effect.is(setSelection)) {
@@ -93,10 +109,10 @@ const commentsStateField = StateField.define<CommentsState>({
93
109
 
94
110
  // Update range from store.
95
111
  if (effect.is(setCommentRange)) {
96
- const { model, comments } = effect.value;
112
+ const { comments } = effect.value;
97
113
  const ranges: ExtendedCommentRange[] = comments
98
114
  .map((comment) => {
99
- const range = model.getRangeFromCursor!(comment.cursor);
115
+ const range = getRangeFromCursor(cursorConverter, comment.cursor);
100
116
  return range && { ...comment, ...range };
101
117
  })
102
118
  .filter(nonNullable);
@@ -204,14 +220,15 @@ export const comments = (options: CommentsOptions = {}): Extension => {
204
220
  * Create comment thread action.
205
221
  */
206
222
  const createCommentThread: Command = (view) => {
223
+ const cursorConverter = view.state.facet(CursorConverter);
224
+
207
225
  invariant(options.onCreate);
208
226
  const { head, from, to } = view.state.selection.main;
209
227
  if (from === to) {
210
228
  return false;
211
229
  }
212
230
 
213
- const model = view.state.field(modelState);
214
- const relPos = model?.getCursorFromRange?.({ from, to });
231
+ const relPos = getCursorFromRange(cursorConverter, { from, to });
215
232
  if (relPos) {
216
233
  // Create thread via callback.
217
234
  const id = callbackWrapper(options.onCreate)(relPos);
@@ -324,19 +341,19 @@ export const comments = (options: CommentsOptions = {}): Extension => {
324
341
  // Monitor cursor movement and text updates.
325
342
  // TODO(burdon): Is there a better (finer grained) way to do this?
326
343
  //
327
- EditorView.updateListener.of(({ view, state, startState, changes }) => {
344
+ EditorView.updateListener.of(({ view, state, changes }) => {
345
+ const cursorConverter = view.state.facet(CursorConverter);
346
+
328
347
  //
329
348
  // Test if need to recompute indexed range if document changes before the end of the range.
330
349
  //
331
350
  {
332
351
  let mod = false;
333
- const model = state.field(modelState);
334
352
  const { active, ranges } = state.field(commentsStateField);
335
353
  changes.iterChanges((from, to, from2, to2) => {
336
- invariant(model);
337
354
  ranges.forEach((range) => {
338
355
  if (from2 === to2) {
339
- const newRange = model.getRangeFromCursor!(range.cursor);
356
+ const newRange = getRangeFromCursor(cursorConverter, range.cursor);
340
357
  if (!newRange || newRange.to - newRange.from === 0) {
341
358
  // TODO(burdon): Delete range if empty.
342
359
  log.info('deleted comment', { thread: range.id });
@@ -344,7 +361,7 @@ export const comments = (options: CommentsOptions = {}): Extension => {
344
361
  }
345
362
 
346
363
  if (from <= range.to) {
347
- const newRange = model.getRangeFromCursor!(range.cursor);
364
+ const newRange = getRangeFromCursor(cursorConverter, range.cursor);
348
365
  Object.assign(range, newRange);
349
366
  mod = true;
350
367
  }
@@ -389,3 +406,16 @@ export const comments = (options: CommentsOptions = {}): Extension => {
389
406
  }),
390
407
  ];
391
408
  };
409
+
410
+ const getCursorFromRange = (cursorConverter: CursorConverter, range: Range) => {
411
+ const from = cursorConverter.toCursor(range.from);
412
+ const to = cursorConverter.toCursor(range.to, -1);
413
+ return [from, to].join(':');
414
+ };
415
+
416
+ const getRangeFromCursor = (cursorConverter: CursorConverter, cursor: string) => {
417
+ const parts = cursor.split(':');
418
+ const from = cursorConverter.fromCursor(parts[0]);
419
+ const to = cursorConverter.fromCursor(parts[1]);
420
+ return from && to ? { from, to } : undefined;
421
+ };
@@ -3,6 +3,8 @@
3
3
  //
4
4
 
5
5
  export * from './autocomplete';
6
+ export * from './automerge';
7
+ export * from './awareness';
6
8
  export * from './basic';
7
9
  export * from './blast';
8
10
  export * from './code';
@@ -17,3 +19,4 @@ export * from './mermaid';
17
19
  export * from './table';
18
20
  export * from './tasklist';
19
21
  export * from './typewriter';
22
+ export * from './yjs';
@@ -0,0 +1,21 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ import * as Y from 'yjs';
6
+
7
+ import { arrayToString, stringToArray } from '@dxos/util';
8
+
9
+ import { type CursorConverter } from '../../util';
10
+
11
+ export const cursorConverter = (text: Y.Text): CursorConverter => ({
12
+ toCursor: (index, assoc) => {
13
+ return arrayToString(Y.encodeRelativePosition(Y.createRelativePositionFromTypeIndex(text, index, assoc)));
14
+ },
15
+ fromCursor: (cursor) => {
16
+ return (
17
+ Y.createAbsolutePositionFromRelativePosition(Y.decodeRelativePosition(stringToArray(cursor)), text.doc!)?.index ??
18
+ 0
19
+ );
20
+ },
21
+ });
@@ -0,0 +1,5 @@
1
+ //
2
+ // Copyright 2023 DXOS.org
3
+ //
4
+
5
+ export * from './yjs';