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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/dist/lib/browser/index.mjs +1599 -1108
  2. package/dist/lib/browser/index.mjs.map +4 -4
  3. package/dist/lib/browser/meta.json +1 -1
  4. package/dist/types/src/components/TextEditor/MarkdownEditor.stories.d.ts +3 -3
  5. package/dist/types/src/components/TextEditor/MarkdownEditor.stories.d.ts.map +1 -1
  6. package/dist/types/src/components/TextEditor/TextEditor.stories.d.ts +3 -0
  7. package/dist/types/src/components/TextEditor/TextEditor.stories.d.ts.map +1 -1
  8. package/dist/types/src/{hooks/automerge → components/TextEditor}/automerge.stories.d.ts +6 -1
  9. package/dist/types/src/components/TextEditor/automerge.stories.d.ts.map +1 -0
  10. package/dist/types/src/components/TextEditor/codemirror.stories.d.ts.map +1 -1
  11. package/dist/types/src/{hooks/yjs → components/TextEditor}/yjs.stories.d.ts +1 -1
  12. package/dist/types/src/components/TextEditor/yjs.stories.d.ts.map +1 -0
  13. package/dist/types/src/extensions/autocomplete.d.ts.map +1 -1
  14. package/dist/types/src/extensions/automerge/automerge.d.ts +9 -0
  15. package/dist/types/src/extensions/automerge/automerge.d.ts.map +1 -0
  16. package/dist/types/src/extensions/automerge/cursor.d.ts +5 -0
  17. package/dist/types/src/extensions/automerge/cursor.d.ts.map +1 -0
  18. package/dist/types/src/extensions/automerge/defs.d.ts +26 -0
  19. package/dist/types/src/extensions/automerge/defs.d.ts.map +1 -0
  20. package/dist/types/src/extensions/automerge/index.d.ts +4 -0
  21. package/dist/types/src/extensions/automerge/index.d.ts.map +1 -0
  22. package/dist/types/src/{hooks → extensions}/automerge/semaphore.d.ts +4 -4
  23. package/dist/types/src/extensions/automerge/semaphore.d.ts.map +1 -0
  24. package/dist/types/src/extensions/automerge/update-automerge.d.ts +5 -0
  25. package/dist/types/src/extensions/automerge/update-automerge.d.ts.map +1 -0
  26. package/dist/types/src/extensions/automerge/update-codemirror.d.ts.map +1 -0
  27. package/dist/types/src/extensions/awareness.d.ts +46 -0
  28. package/dist/types/src/extensions/awareness.d.ts.map +1 -0
  29. package/dist/types/src/extensions/code.d.ts.map +1 -1
  30. package/dist/types/src/extensions/comments.d.ts +3 -1
  31. package/dist/types/src/extensions/comments.d.ts.map +1 -1
  32. package/dist/types/src/extensions/hr.d.ts.map +1 -1
  33. package/dist/types/src/extensions/image.d.ts.map +1 -1
  34. package/dist/types/src/extensions/index.d.ts +3 -1
  35. package/dist/types/src/extensions/index.d.ts.map +1 -1
  36. package/dist/types/src/extensions/link.d.ts.map +1 -1
  37. package/dist/types/src/extensions/markdown/highlight.d.ts.map +1 -1
  38. package/dist/types/src/extensions/tasklist.d.ts.map +1 -1
  39. package/dist/types/src/extensions/yjs/cursor.d.ts +4 -0
  40. package/dist/types/src/extensions/yjs/cursor.d.ts.map +1 -0
  41. package/dist/types/src/extensions/yjs/index.d.ts +2 -0
  42. package/dist/types/src/extensions/yjs/index.d.ts.map +1 -0
  43. package/dist/types/src/extensions/yjs/yjs.d.ts +4 -0
  44. package/dist/types/src/extensions/yjs/yjs.d.ts.map +1 -0
  45. package/dist/types/src/extensions/yjs/yjs.test.d.ts.map +1 -0
  46. package/dist/types/src/hooks/automerge.d.ts +3 -0
  47. package/dist/types/src/hooks/automerge.d.ts.map +1 -0
  48. package/dist/types/src/hooks/awareness-provider.d.ts +28 -0
  49. package/dist/types/src/hooks/awareness-provider.d.ts.map +1 -0
  50. package/dist/types/src/hooks/index.d.ts +2 -0
  51. package/dist/types/src/hooks/index.d.ts.map +1 -1
  52. package/dist/types/src/hooks/useTextModel.d.ts +8 -7
  53. package/dist/types/src/hooks/useTextModel.d.ts.map +1 -1
  54. package/dist/types/src/hooks/{yjs/space-provider.d.ts → yjs.d.ts} +8 -8
  55. package/dist/types/src/hooks/yjs.d.ts.map +1 -0
  56. package/dist/types/src/index.d.ts +2 -0
  57. package/dist/types/src/index.d.ts.map +1 -1
  58. package/dist/types/src/styles/cursors.d.ts.map +1 -0
  59. package/dist/types/src/styles/index.d.ts +1 -0
  60. package/dist/types/src/styles/index.d.ts.map +1 -1
  61. package/dist/types/src/styles/tokens.d.ts +1 -0
  62. package/dist/types/src/styles/tokens.d.ts.map +1 -1
  63. package/dist/types/src/testing/replicator.d.ts +2 -2
  64. package/dist/types/src/testing/replicator.d.ts.map +1 -1
  65. package/dist/types/src/themes/default.d.ts.map +1 -1
  66. package/dist/types/src/util/cursor.d.ts +17 -0
  67. package/dist/types/src/util/cursor.d.ts.map +1 -0
  68. package/dist/types/src/util/index.d.ts +3 -0
  69. package/dist/types/src/util/index.d.ts.map +1 -0
  70. package/dist/types/src/util/util.d.ts.map +1 -0
  71. package/package.json +22 -21
  72. package/src/components/TextEditor/MarkdownEditor.stories.tsx +6 -7
  73. package/src/components/TextEditor/TextEditor.stories.tsx +13 -0
  74. package/src/components/TextEditor/TextEditor.tsx +1 -1
  75. package/src/{hooks/automerge → components/TextEditor}/automerge.stories.tsx +66 -6
  76. package/src/components/TextEditor/codemirror.stories.ts +3 -2
  77. package/src/{hooks/yjs → components/TextEditor}/yjs.stories.tsx +1 -1
  78. package/src/extensions/autocomplete.ts +18 -17
  79. package/src/extensions/automerge/automerge.ts +94 -0
  80. package/src/extensions/automerge/cursor.ts +51 -0
  81. package/src/extensions/automerge/defs.ts +62 -0
  82. package/src/extensions/automerge/index.ts +7 -0
  83. package/src/{hooks → extensions}/automerge/semaphore.ts +14 -12
  84. package/src/{hooks → extensions}/automerge/update-automerge.ts +5 -6
  85. package/src/{hooks → extensions}/automerge/update-codemirror.ts +13 -5
  86. package/src/extensions/awareness.ts +316 -0
  87. package/src/extensions/code.ts +4 -5
  88. package/src/extensions/comments.ts +44 -15
  89. package/src/extensions/hr.ts +2 -3
  90. package/src/extensions/image.ts +38 -20
  91. package/src/extensions/index.ts +3 -1
  92. package/src/extensions/link.ts +82 -84
  93. package/src/extensions/markdown/highlight.ts +3 -4
  94. package/src/extensions/table.ts +9 -3
  95. package/src/extensions/tasklist.ts +1 -3
  96. package/src/extensions/yjs/cursor.ts +21 -0
  97. package/src/extensions/yjs/index.ts +5 -0
  98. package/src/{hooks → extensions}/yjs/yjs.test.ts +1 -25
  99. package/src/extensions/yjs/yjs.ts +16 -0
  100. package/src/hooks/automerge.ts +52 -0
  101. package/src/hooks/awareness-provider.ts +120 -0
  102. package/src/hooks/index.ts +2 -0
  103. package/src/hooks/useTextModel.ts +19 -93
  104. package/src/hooks/{yjs/space-provider.ts → yjs.ts} +71 -19
  105. package/src/index.ts +2 -0
  106. package/src/styles/index.ts +1 -0
  107. package/src/styles/tokens.ts +3 -0
  108. package/src/testing/replicator.ts +10 -15
  109. package/src/themes/default.ts +39 -33
  110. package/src/util/cursor.ts +29 -0
  111. package/src/util/index.ts +6 -0
  112. package/dist/types/src/extensions/mermaid.d.ts +0 -3
  113. package/dist/types/src/extensions/mermaid.d.ts.map +0 -1
  114. package/dist/types/src/extensions/util.d.ts.map +0 -1
  115. package/dist/types/src/hooks/automerge/automerge.stories.d.ts.map +0 -1
  116. package/dist/types/src/hooks/automerge/handle.d.ts +0 -9
  117. package/dist/types/src/hooks/automerge/handle.d.ts.map +0 -1
  118. package/dist/types/src/hooks/automerge/index.d.ts +0 -3
  119. package/dist/types/src/hooks/automerge/index.d.ts.map +0 -1
  120. package/dist/types/src/hooks/automerge/plugin.d.ts +0 -26
  121. package/dist/types/src/hooks/automerge/plugin.d.ts.map +0 -1
  122. package/dist/types/src/hooks/automerge/semaphore.d.ts.map +0 -1
  123. package/dist/types/src/hooks/automerge/update-automerge.d.ts +0 -6
  124. package/dist/types/src/hooks/automerge/update-automerge.d.ts.map +0 -1
  125. package/dist/types/src/hooks/automerge/update-codemirror.d.ts.map +0 -1
  126. package/dist/types/src/hooks/yjs/cursors.d.ts.map +0 -1
  127. package/dist/types/src/hooks/yjs/index.d.ts +0 -3
  128. package/dist/types/src/hooks/yjs/index.d.ts.map +0 -1
  129. package/dist/types/src/hooks/yjs/space-provider.d.ts.map +0 -1
  130. package/dist/types/src/hooks/yjs/yjs.stories.d.ts.map +0 -1
  131. package/dist/types/src/hooks/yjs/yjs.test.d.ts.map +0 -1
  132. package/src/extensions/mermaid.ts +0 -11
  133. package/src/hooks/automerge/handle.ts +0 -14
  134. package/src/hooks/automerge/index.ts +0 -6
  135. package/src/hooks/automerge/plugin.ts +0 -134
  136. package/src/hooks/yjs/index.ts +0 -6
  137. /package/dist/types/src/{hooks → extensions}/automerge/update-codemirror.d.ts +0 -0
  138. /package/dist/types/src/{hooks → extensions}/yjs/yjs.test.d.ts +0 -0
  139. /package/dist/types/src/{hooks/yjs → styles}/cursors.d.ts +0 -0
  140. /package/dist/types/src/{extensions → util}/util.d.ts +0 -0
  141. /package/src/{hooks/yjs → styles}/cursors.ts +0 -0
  142. /package/src/{extensions → util}/util.ts +0 -0
@@ -11,24 +11,23 @@ import {
11
11
  Decoration,
12
12
  type BlockInfo,
13
13
  } from '@codemirror/view';
14
- import get from 'lodash.get';
15
14
 
16
15
  import { mx } from '@dxos/react-ui-theme';
17
16
 
18
- import { tokens } from '../styles';
17
+ import { getToken } from '../styles';
19
18
 
20
19
  const CODE_REGEX = /```[\s\S]*?```/gs;
21
20
 
22
21
  // TODO(burdon): Reconcile with theme.
23
22
  const styles = EditorView.baseTheme({
24
23
  '& .cm-codeblock': {
25
- fontFamily: get(tokens, 'fontFamily.mono', []).join(','),
24
+ fontFamily: getToken('fontFamily.mono', []).join(','),
26
25
  },
27
26
  '&light [aria-readonly="true"] .cm-codeblock': {
28
- background: get(tokens, 'extend.colors.neutral.50'),
27
+ background: getToken('extend.colors.neutral.50'),
29
28
  },
30
29
  '&dark [aria-readonly="true"] .cm-codeblock': {
31
- background: get(tokens, 'extend.colors.neutral.850'),
30
+ background: getToken('extend.colors.neutral.850'),
32
31
  },
33
32
  '& [aria-readonly="true"] .cm-codeblock': {
34
33
  display: 'block',
@@ -23,10 +23,10 @@ import { invariant } from '@dxos/invariant';
23
23
  import { log } from '@dxos/log';
24
24
  import { nonNullable } from '@dxos/util';
25
25
 
26
- import { callbackWrapper } from './util';
27
- import { type CommentRange, type EditorModel, modelState, type Range } from '../hooks';
26
+ import { type CommentRange, type EditorModel, type Range } from '../hooks';
27
+ import { getToken } from '../styles';
28
+ import { callbackWrapper, CursorConverter } from '../util';
28
29
 
29
- // TODO(burdon): Handle scroll to.
30
30
  // TODO(burdon): Handle delete, cut, copy, and paste (separately) text that includes comment range.
31
31
  // TODO(burdon): Consider breaking into separate plugin (since not standalone)? Like mermaid?
32
32
 
@@ -42,10 +42,10 @@ const styles = EditorView.baseTheme({
42
42
  backgroundColor: 'orange',
43
43
  },
44
44
  '& .cm-comment': {
45
- backgroundColor: 'yellow',
45
+ backgroundColor: getToken('extend.colors.yellow.50'),
46
46
  },
47
47
  '& .cm-comment-active': {
48
- backgroundColor: 'orange',
48
+ backgroundColor: getToken('extend.colors.yellow.100'),
49
49
  },
50
50
  });
51
51
 
@@ -71,9 +71,22 @@ export type CommentsState = CommentSelected & {
71
71
  ranges: ExtendedCommentRange[];
72
72
  };
73
73
 
74
+ export const setFocus = (view: EditorView, thread: string) => {
75
+ const range = view.state.field(commentsStateField).ranges.find((range) => range.id === thread);
76
+ if (!range) {
77
+ return;
78
+ }
79
+
80
+ view.dispatch({
81
+ effects: setSelection.of({ active: thread }),
82
+ selection: { anchor: range.from },
83
+ scrollIntoView: true,
84
+ });
85
+ };
86
+
74
87
  export const setCommentRange = StateEffect.define<{ model: EditorModel; comments: CommentRange[] }>();
75
88
 
76
- const setSelection = StateEffect.define<CommentSelected>();
89
+ export const setSelection = StateEffect.define<CommentSelected>();
77
90
 
78
91
  const setCommentState = StateEffect.define<CommentsState>();
79
92
 
@@ -85,6 +98,8 @@ const setCommentState = StateEffect.define<CommentsState>();
85
98
  const commentsStateField = StateField.define<CommentsState>({
86
99
  create: () => ({ ranges: [] }),
87
100
  update: (value, tr) => {
101
+ const cursorConverter = tr.state.facet(CursorConverter);
102
+
88
103
  for (const effect of tr.effects) {
89
104
  // Update selection.
90
105
  if (effect.is(setSelection)) {
@@ -93,10 +108,10 @@ const commentsStateField = StateField.define<CommentsState>({
93
108
 
94
109
  // Update range from store.
95
110
  if (effect.is(setCommentRange)) {
96
- const { model, comments } = effect.value;
111
+ const { comments } = effect.value;
97
112
  const ranges: ExtendedCommentRange[] = comments
98
113
  .map((comment) => {
99
- const range = model.getRangeFromCursor!(comment.cursor);
114
+ const range = getRangeFromCursor(cursorConverter, comment.cursor);
100
115
  return range && { ...comment, ...range };
101
116
  })
102
117
  .filter(nonNullable);
@@ -204,14 +219,15 @@ export const comments = (options: CommentsOptions = {}): Extension => {
204
219
  * Create comment thread action.
205
220
  */
206
221
  const createCommentThread: Command = (view) => {
222
+ const cursorConverter = view.state.facet(CursorConverter);
223
+
207
224
  invariant(options.onCreate);
208
225
  const { head, from, to } = view.state.selection.main;
209
226
  if (from === to) {
210
227
  return false;
211
228
  }
212
229
 
213
- const model = view.state.field(modelState);
214
- const relPos = model?.getCursorFromRange?.({ from, to });
230
+ const relPos = getCursorFromRange(cursorConverter, { from, to });
215
231
  if (relPos) {
216
232
  // Create thread via callback.
217
233
  const id = callbackWrapper(options.onCreate)(relPos);
@@ -324,19 +340,19 @@ export const comments = (options: CommentsOptions = {}): Extension => {
324
340
  // Monitor cursor movement and text updates.
325
341
  // TODO(burdon): Is there a better (finer grained) way to do this?
326
342
  //
327
- EditorView.updateListener.of(({ view, state, startState, changes }) => {
343
+ EditorView.updateListener.of(({ view, state, changes }) => {
344
+ const cursorConverter = view.state.facet(CursorConverter);
345
+
328
346
  //
329
347
  // Test if need to recompute indexed range if document changes before the end of the range.
330
348
  //
331
349
  {
332
350
  let mod = false;
333
- const model = state.field(modelState);
334
351
  const { active, ranges } = state.field(commentsStateField);
335
352
  changes.iterChanges((from, to, from2, to2) => {
336
- invariant(model);
337
353
  ranges.forEach((range) => {
338
354
  if (from2 === to2) {
339
- const newRange = model.getRangeFromCursor!(range.cursor);
355
+ const newRange = getRangeFromCursor(cursorConverter, range.cursor);
340
356
  if (!newRange || newRange.to - newRange.from === 0) {
341
357
  // TODO(burdon): Delete range if empty.
342
358
  log.info('deleted comment', { thread: range.id });
@@ -344,7 +360,7 @@ export const comments = (options: CommentsOptions = {}): Extension => {
344
360
  }
345
361
 
346
362
  if (from <= range.to) {
347
- const newRange = model.getRangeFromCursor!(range.cursor);
363
+ const newRange = getRangeFromCursor(cursorConverter, range.cursor);
348
364
  Object.assign(range, newRange);
349
365
  mod = true;
350
366
  }
@@ -389,3 +405,16 @@ export const comments = (options: CommentsOptions = {}): Extension => {
389
405
  }),
390
406
  ];
391
407
  };
408
+
409
+ const getCursorFromRange = (cursorConverter: CursorConverter, range: Range) => {
410
+ const from = cursorConverter.toCursor(range.from);
411
+ const to = cursorConverter.toCursor(range.to, -1);
412
+ return [from, to].join(':');
413
+ };
414
+
415
+ const getRangeFromCursor = (cursorConverter: CursorConverter, cursor: string) => {
416
+ const parts = cursor.split(':');
417
+ const from = cursorConverter.fromCursor(parts[0]);
418
+ const to = cursorConverter.fromCursor(parts[1]);
419
+ return from !== undefined && to !== undefined ? { from, to } : undefined;
420
+ };
@@ -11,16 +11,15 @@ import {
11
11
  type ViewUpdate,
12
12
  WidgetType,
13
13
  } from '@codemirror/view';
14
- import get from 'lodash.get';
15
14
 
16
- import { tokens } from '../styles';
15
+ import { getToken } from '../styles';
17
16
 
18
17
  // TODO(burdon): Reconcile with theme.
19
18
  const styles = EditorView.baseTheme({
20
19
  '& .cm-hr': {
21
20
  // TODO(burdon): ???
22
21
  // Note that block-level decorations should not have vertical margins,
23
- borderBottom: `1px solid ${get(tokens, 'extend.colors.neutral.200')}`,
22
+ borderBottom: `1px solid ${getToken('extend.colors.neutral.200')}`,
24
23
  },
25
24
  });
26
25
 
@@ -3,28 +3,45 @@
3
3
  //
4
4
 
5
5
  import { syntaxTree } from '@codemirror/language';
6
- import {
7
- type EditorState,
8
- type Extension,
9
- type RangeSet,
10
- RangeSetBuilder,
11
- StateField,
12
- type Transaction,
13
- } from '@codemirror/state';
14
- import { Decoration, EditorView, WidgetType } from '@codemirror/view';
6
+ import { type EditorState, type Extension, StateField, type Transaction, type Range } from '@codemirror/state';
7
+ import { Decoration, type DecorationSet, EditorView, WidgetType } from '@codemirror/view';
15
8
 
16
9
  export type ImageOptions = {};
17
10
 
18
11
  export const image = (options: ImageOptions = {}): Extension => {
19
- return StateField.define<RangeSet<any>>({
20
- create: (state) => update(state, options),
21
- update: (_: RangeSet<any>, tr: Transaction) => update(tr.state, options),
12
+ return StateField.define<DecorationSet>({
13
+ create: (state) => {
14
+ return Decoration.set(buildDecorations(0, state.doc.length, state));
15
+ },
16
+ update: (value: DecorationSet, tr: Transaction) => {
17
+ if (!tr.docChanged && !tr.selection) {
18
+ return value;
19
+ }
20
+ // Find range of changes and cursor changes.
21
+ const cursor = tr.state.selection.main.head;
22
+ const oldCursor = tr.changes.mapPos(tr.startState.selection.main.head);
23
+ let from = Math.min(cursor, oldCursor);
24
+ let to = Math.max(cursor, oldCursor);
25
+ tr.changes.iterChangedRanges((fromA, toA, fromB, toB) => {
26
+ from = Math.min(from, fromB);
27
+ to = Math.max(to, toB);
28
+ });
29
+ // Expand to cover lines
30
+ from = tr.state.doc.lineAt(from).from;
31
+ to = tr.state.doc.lineAt(to).to;
32
+ return value.map(tr.changes).update({
33
+ filterFrom: from,
34
+ filterTo: to,
35
+ filter: () => false,
36
+ add: buildDecorations(from, to, tr.state),
37
+ });
38
+ },
22
39
  provide: (field) => EditorView.decorations.from(field),
23
40
  });
24
41
  };
25
42
 
26
- const update = (state: EditorState, options: ImageOptions) => {
27
- const builder = new RangeSetBuilder();
43
+ const buildDecorations = (from: number, to: number, state: EditorState) => {
44
+ const decorations: Range<Decoration>[] = [];
28
45
  const cursor = state.selection.main.head;
29
46
 
30
47
  syntaxTree(state).iterate({
@@ -34,20 +51,20 @@ const update = (state: EditorState, options: ImageOptions) => {
34
51
  if (urlNode) {
35
52
  const hide = state.readOnly || cursor < node.from || cursor > node.to;
36
53
  const url = state.sliceDoc(urlNode.from, urlNode.to);
37
- builder.add(
38
- hide ? node.from : node.to,
39
- node.to,
54
+ decorations.push(
40
55
  Decoration.replace({
41
56
  block: true, // Prevent cursor from entering.
42
57
  widget: new ImageWidget(url),
43
- }),
58
+ }).range(hide ? node.from : node.to, node.to),
44
59
  );
45
60
  }
46
61
  }
47
62
  },
63
+ from,
64
+ to,
48
65
  });
49
66
 
50
- return builder.finish();
67
+ return decorations;
51
68
  };
52
69
 
53
70
  class ImageWidget extends WidgetType {
@@ -55,7 +72,6 @@ class ImageWidget extends WidgetType {
55
72
  super();
56
73
  }
57
74
 
58
- // TODO(burdon): Does this need to be unique for each position?
59
75
  override eq(other: WidgetType) {
60
76
  return this._url === (other as any as ImageWidget)._url;
61
77
  }
@@ -64,6 +80,8 @@ class ImageWidget extends WidgetType {
64
80
  const img = document.createElement('img');
65
81
  img.setAttribute('src', this._url);
66
82
  img.setAttribute('class', 'cm-image');
83
+ // Images are hidden until successfully loaded to avoid flickering effects.
84
+ img.onload = () => img.classList.add('cm-loaded-image');
67
85
  return img;
68
86
  }
69
87
  }
@@ -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';
@@ -13,7 +15,7 @@ export * from './link';
13
15
  export * from './listener';
14
16
  export * from './markdown';
15
17
  export * from './mention';
16
- export * from './mermaid';
17
18
  export * from './table';
18
19
  export * from './tasklist';
19
20
  export * from './typewriter';
21
+ export * from './yjs';
@@ -4,20 +4,20 @@
4
4
  //
5
5
 
6
6
  import { syntaxTree } from '@codemirror/language';
7
+ import { type Extension, RangeSetBuilder } from '@codemirror/state';
7
8
  import {
8
- type EditorState,
9
- type Extension,
10
- type RangeSet,
11
- RangeSetBuilder,
12
- StateField,
13
- type Transaction,
14
- } from '@codemirror/state';
15
- import { Decoration, EditorView, WidgetType, hoverTooltip } from '@codemirror/view';
9
+ Decoration,
10
+ type EditorView,
11
+ WidgetType,
12
+ hoverTooltip,
13
+ ViewPlugin,
14
+ type ViewUpdate,
15
+ type DecorationSet,
16
+ } from '@codemirror/view';
17
+ import { type SyntaxNode } from '@lezer/common';
16
18
 
17
19
  import { tooltipContent } from '@dxos/react-ui-theme';
18
20
 
19
- const markdownLinkRegexp = /\[([^\]]+)]\(([^)]+)\)/;
20
-
21
21
  // Adapted from:
22
22
  // https://codemirror.net/try/?c=aW1wb3J0IHsgYmFzaWNTZXR1cCwgRWRpdG9yVmlldyB9IGZyb20gImNvZGVtaXJyb3IiCmltcG9ydCB7IG1hcmtkb3duIH0gZnJvbSAiQGNvZGVtaXJyb3IvbGFuZy1tYXJrZG93biIKaW1wb3J0IHsgc3ludGF4VHJlZSB9IGZyb20gIkBjb2RlbWlycm9yL2xhbmd1YWdlIjsKaW1wb3J0IHsgRWRpdG9yU3RhdGUsIFJhbmdlU2V0QnVpbGRlciwgU3RhdGVGaWVsZCB9IGZyb20gIkBjb2RlbWlycm9yL3N0YXRlIjsKaW1wb3J0IHsgRGVjb3JhdGlvbiwgV2lkZ2V0VHlwZSB9IGZyb20gIkBjb2RlbWlycm9yL3ZpZXciOwoKY2xhc3MgTGluayBleHRlbmRzIFdpZGdldFR5cGUgewogIGNvbnN0cnVjdG9yKHRleHQsIHVybCkgewogICAgc3VwZXIoKQogICAgdGhpcy50ZXh0ID0gdGV4dAogICAgdGhpcy51cmwgPSB1cmwKICB9CiAgZXEob3RoZXIpIHsgcmV0dXJuIHRoaXMudGV4dCA9PSBvdGhlci50ZXh0ICYmIHRoaXMudXJsID09IG90aGVyLnVybCB9CiAgdG9ET00oKSB7CiAgICBsZXQgbGluayA9IGRvY3VtZW50LmNyZWF0ZUVsZW1lbnQoImEiKQogICAgbGluay50ZXh0Q29udGVudCA9IHRoaXMudGV4dAogICAgbGluay5ocmVmID0gdGhpcy51cmwKICAgIHJldHVybiBsaW5rOwogIH0KfQoKbGV0IGRlY29yYXRpb25zRmllbGQgPSBTdGF0ZUZpZWxkLmRlZmluZSh7CiAgY3JlYXRlKCkgewogICAgcmV0dXJuIERlY29yYXRpb24ubm9uZTsKICB9LAogIHVwZGF0ZShfLCB0cikgewogICAgY29uc3QgYnVpbGRlciA9IG5ldyBSYW5nZVNldEJ1aWxkZXIoKTsKICAgIGxldCBjdXJzb3IgPSB0ci5zdGF0ZS5zZWxlY3Rpb24ubWFpbi5oZWFkOwogICAgc3ludGF4VHJlZSh0ci5zdGF0ZSkuaXRlcmF0ZSh7CiAgICAgIGVudGVyOiAobm9kZSkgPT4gewogICAgICAgIGlmICgoY3Vyc29yIDwgbm9kZS5mcm9tIHx8IGN1cnNvciA+IG5vZGUudG8pICYmIG5vZGUubmFtZSA9PSAiTGluayIpIHsKICAgICAgICAgIGxldCBtYXJrcyA9IG5vZGUubm9kZS5nZXRDaGlsZHJlbigiTGlua01hcmsiKTsKICAgICAgICAgIGxldCB0ZXh0ID0gbWFya3MubGVuZ3RoID49IDIgPyB0ci5zdGF0ZS5zbGljZURvYyhtYXJrc1swXS50bywgbWFya3NbMV0uZnJvbSkgOiAiIgoKICAgICAgICAgIGxldCB1cmxOb2RlID0gbm9kZS5ub2RlLmdldENoaWxkKCJVUkwiKTsKICAgICAgICAgIGxldCB1cmwgPSB1cmxOb2RlID8gdHIuc3RhdGUuc2xpY2VEb2ModXJsTm9kZS5mcm9tLCB1cmxOb2RlLnRvKSA6ICIiCiAgICAgICAgICBidWlsZGVyLmFkZChub2RlLmZyb20sIG5vZGUudG8sIERlY29yYXRpb24ucmVwbGFjZSh7CiAgICAgICAgICAgIHdpZGdldDogbmV3IExpbmsodGV4dCwgdXJsKSwKICAgICAgICAgIH0pLAogICAgICAgICAgICAgICAgICAgICApOwogICAgICAgICAgcmV0dXJuIGZhbHNlOwogICAgICAgIH0KICAgICAgICByZXR1cm4gdHJ1ZTsKICAgICAgfSwKICAgIH0pOwogICAgcmV0dXJuIGJ1aWxkZXIuZmluaXNoKCk7CiAgfSwKICBwcm92aWRlOiAoZikgPT4gRWRpdG9yVmlldy5kZWNvcmF0aW9ucy5mcm9tKGYpLAp9KTsKCmxldCB2aWV3ID0gbmV3IEVkaXRvclZpZXcoewogIGRvYzogIiMgSGVsbG8gV29ybGRcblxuW1Rlc3RdKGh0dHBzOi8vZXhhbXBsZS5jb20pXG5cblxuIiwKICBleHRlbnNpb25zOiBbZGVjb3JhdGlvbnNGaWVsZCwgbWFya2Rvd24oKV0sCiAgcGFyZW50OiBkb2N1bWVudC5ib2R5LAp9KTsKCnZpZXcuZm9jdXMoKTs=
23
23
  // https://discuss.codemirror.net/t/link-widget-is-clicked-only-if-editor-is-out-of-focus/7433
@@ -34,11 +34,24 @@ export type LinkOptions = {
34
34
  */
35
35
  export const link = (options: LinkOptions = {}): Extension => {
36
36
  const extensions: Extension[] = [
37
- StateField.define<RangeSet<any>>({
38
- create: (state) => update(state, options),
39
- update: (_: RangeSet<any>, tr: Transaction) => update(tr.state, options),
40
- provide: (field) => EditorView.decorations.from(field),
41
- }),
37
+ ViewPlugin.fromClass(
38
+ class {
39
+ decorations: DecorationSet;
40
+
41
+ constructor(view: EditorView) {
42
+ this.decorations = buildDecorations(view, options);
43
+ }
44
+
45
+ update(update: ViewUpdate) {
46
+ if (update.docChanged || update.viewportChanged || update.selectionSet) {
47
+ this.decorations = buildDecorations(update.view, options);
48
+ }
49
+ }
50
+ },
51
+ {
52
+ decorations: (v) => v.decorations,
53
+ },
54
+ ),
42
55
  ];
43
56
 
44
57
  if (options.onHover) {
@@ -46,41 +59,25 @@ export const link = (options: LinkOptions = {}): Extension => {
46
59
  // https://codemirror.net/examples/tooltip
47
60
  // https://codemirror.net/docs/ref/#view.hoverTooltip
48
61
  // https://github.com/codemirror/view/blob/main/src/tooltip.ts
49
- hoverTooltip((view, pos) => {
50
- const { from, text } = view.state.doc.lineAt(pos);
51
- const p = pos - from;
52
-
53
- let idx = 0;
54
- let match;
55
- do {
56
- match = text.substring(idx).match(markdownLinkRegexp);
57
- if (!match) {
58
- match = undefined;
59
- break;
60
- }
61
-
62
- idx = text.indexOf(match[0]);
63
- if (p >= idx && p < idx + match[0].length) {
64
- break;
65
- }
66
-
67
- idx += match[0].length;
68
- } while (true);
69
-
70
- if (!match) {
62
+ hoverTooltip((view, pos, side) => {
63
+ const syntax = syntaxTree(view.state).resolveInner(pos, side);
64
+ let link = null;
65
+ for (let i = 0, node: SyntaxNode | null = syntax; !link && node && i < 5; node = node.parent, i++) {
66
+ link = node.name === 'Link' ? node : null;
67
+ }
68
+ const url = link && link.getChild('URL');
69
+ if (!url || !link) {
71
70
  return null;
72
71
  }
73
-
74
- const [, , url] = match ?? [];
75
-
72
+ const urlText = view.state.sliceDoc(url.from, url.to);
76
73
  return {
77
- pos: idx + from,
78
- end: idx + from + match[0].length,
74
+ pos: link.from,
75
+ end: link.to,
79
76
  above: true,
80
77
  create: () => {
81
78
  const el = document.createElement('div');
82
79
  el.className = tooltipContent({}, 'pli-2 plb-1');
83
- options.onHover!(el, url);
80
+ options.onHover!(el, urlText);
84
81
  return { dom: el, offset: { x: 0, y: 4 } };
85
82
  },
86
83
  };
@@ -92,16 +89,12 @@ export const link = (options: LinkOptions = {}): Extension => {
92
89
  };
93
90
 
94
91
  class LinkButton extends WidgetType {
95
- constructor(
96
- private readonly _pos: number,
97
- private readonly _url: string,
98
- private readonly _onAttach: LinkOptions['onRender'],
99
- ) {
92
+ constructor(private readonly _url: string, private readonly _onAttach: LinkOptions['onRender']) {
100
93
  super();
101
94
  }
102
95
 
103
96
  override eq(other: LinkButton) {
104
- return this._pos === other._pos && this._url === other._url;
97
+ return this._url === other._url;
105
98
  }
106
99
 
107
100
  toDOM(view: EditorView) {
@@ -147,46 +140,51 @@ class LinkText extends WidgetType {
147
140
  * possibly overlapping ranges in such a way that they can efficiently be mapped though document changes.
148
141
  * https://codemirror.net/docs/ref/#state
149
142
  */
150
- const update = (state: EditorState, options: LinkOptions) => {
151
- const builder = new RangeSetBuilder();
143
+ const buildDecorations = (view: EditorView, options: LinkOptions): DecorationSet => {
144
+ const builder = new RangeSetBuilder<Decoration>();
145
+ const { state } = view;
152
146
  const cursor = state.selection.main.head;
153
147
 
154
- syntaxTree(state).iterate({
155
- enter: (node) => {
156
- // Check if cursor is inside text.
157
- if (node.name === 'Link') {
158
- const marks = node.node.getChildren('LinkMark');
159
- const text = marks.length >= 2 ? state.sliceDoc(marks[0].to, marks[1].from) : '';
160
- const urlNode = node.node.getChild('URL');
161
- const url = urlNode ? state.sliceDoc(urlNode.from, urlNode.to) : '';
162
- if (!url) {
163
- return false;
164
- }
148
+ for (const { from, to } of view.visibleRanges) {
149
+ syntaxTree(state).iterate({
150
+ enter: (node) => {
151
+ // Check if cursor is inside text.
152
+ if (node.name === 'Link') {
153
+ const marks = node.node.getChildren('LinkMark');
154
+ const text = marks.length >= 2 ? state.sliceDoc(marks[0].to, marks[1].from) : '';
155
+ const urlNode = node.node.getChild('URL');
156
+ const url = urlNode ? state.sliceDoc(urlNode.from, urlNode.to) : '';
157
+ if (!url) {
158
+ return false;
159
+ }
165
160
 
166
- if (state.readOnly || cursor < node.from || cursor > node.to) {
167
- builder.add(
168
- node.from,
169
- node.to,
170
- Decoration.replace({
171
- widget: new LinkText(text, options.link ? url : undefined),
172
- }),
173
- );
174
- }
161
+ if (!view.hasFocus || state.readOnly || cursor < node.from || cursor > node.to) {
162
+ builder.add(
163
+ node.from,
164
+ node.to,
165
+ Decoration.replace({
166
+ widget: new LinkText(text, options.link ? url : undefined),
167
+ }),
168
+ );
169
+ }
175
170
 
176
- if (options.onRender) {
177
- builder.add(
178
- node.to,
179
- node.to,
180
- Decoration.replace({
181
- widget: new LinkButton(node.from, url, options.onRender),
182
- }),
183
- );
184
- }
171
+ if (options.onRender) {
172
+ builder.add(
173
+ node.to,
174
+ node.to,
175
+ Decoration.replace({
176
+ widget: new LinkButton(url, options.onRender),
177
+ }),
178
+ );
179
+ }
185
180
 
186
- return false;
187
- }
188
- },
189
- });
181
+ return false;
182
+ }
183
+ },
184
+ from,
185
+ to,
186
+ });
187
+ }
190
188
 
191
189
  return builder.finish();
192
190
  };
@@ -6,19 +6,18 @@ import { markdownLanguage } from '@codemirror/lang-markdown';
6
6
  import { HighlightStyle } from '@codemirror/language';
7
7
  import { tags, styleTags, Tag } from '@lezer/highlight';
8
8
  import { type MarkdownConfig, Table } from '@lezer/markdown';
9
- import get from 'lodash.get';
10
9
 
11
10
  import {
12
11
  blockquote,
13
12
  bold,
14
13
  code,
15
14
  codeMark,
15
+ getToken,
16
16
  heading,
17
17
  inlineUrl,
18
18
  italic,
19
19
  mark,
20
20
  strikethrough,
21
- tokens,
22
21
  } from '../../styles';
23
22
 
24
23
  /**
@@ -193,12 +192,12 @@ export const markdownHighlightStyle = (readonly?: boolean) => {
193
192
  // Main content, paragraphs, etc.
194
193
  // {
195
194
  // tag: [tags.content],
196
- // fontFamily: get(tokens, 'fontFamily.body', []).join(','),
195
+ // fontFamily: getToken('fontFamily.body', []).join(','),
197
196
  // },
198
197
  ],
199
198
  {
200
199
  scope: markdownLanguage,
201
- all: { fontFamily: get(tokens, 'fontFamily.body', []).join(',') },
200
+ all: { fontFamily: getToken('fontFamily.body', []).join(',') },
202
201
  },
203
202
  );
204
203
  };
@@ -81,7 +81,6 @@ const update = (state: EditorState, options: TableOptions) => {
81
81
  table.from,
82
82
  table.to,
83
83
  Decoration.replace({
84
- block: true,
85
84
  widget: new TableWidget(table),
86
85
  }),
87
86
  );
@@ -98,8 +97,11 @@ class TableWidget extends WidgetType {
98
97
  super();
99
98
  }
100
99
 
101
- override eq(other: WidgetType) {
102
- return this._table.from === (other as any as TableWidget)?._table?.from;
100
+ override eq(other: TableWidget) {
101
+ return (
102
+ this._table.header?.join() === other._table.header?.join() &&
103
+ this._table.rows?.join() === other._table.rows?.join()
104
+ );
103
105
  }
104
106
 
105
107
  toDOM(view: EditorView) {
@@ -129,4 +131,8 @@ class TableWidget extends WidgetType {
129
131
 
130
132
  return table;
131
133
  }
134
+
135
+ override ignoreEvent(e: Event) {
136
+ return !/^mouse/.test(e.type);
137
+ }
132
138
  }
@@ -22,7 +22,6 @@ const styles = EditorView.baseTheme({
22
22
 
23
23
  class CheckboxWidget extends WidgetType {
24
24
  constructor(
25
- private readonly _pos: number,
26
25
  private _checked: boolean,
27
26
  private readonly _indent: number,
28
27
  private readonly _onCheck?: (check: boolean) => void,
@@ -31,7 +30,7 @@ class CheckboxWidget extends WidgetType {
31
30
  }
32
31
 
33
32
  override eq(other: CheckboxWidget) {
34
- return this._pos === other._pos && this._checked === other._checked && this._indent === other._indent;
33
+ return this._checked === other._checked && this._indent === other._indent;
35
34
  }
36
35
 
37
36
  toDOM(view: EditorView) {
@@ -73,7 +72,6 @@ export const tasklist = (options: TasklistOptions = {}) => {
73
72
  const checked = match[2] === 'x' || match[2] === 'X';
74
73
  return Decoration.replace({
75
74
  widget: new CheckboxWidget(
76
- pos,
77
75
  checked,
78
76
  indent,
79
77
  view.state.readOnly
@@ -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';