@dxos/react-ui-editor 0.3.11-main.c95bc86 → 0.3.11-main.cb5abf5

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 (90) hide show
  1. package/dist/lib/browser/index.mjs +808 -252
  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 +1 -2
  5. package/dist/types/src/components/TextEditor/MarkdownEditor.stories.d.ts.map +1 -1
  6. package/dist/types/src/components/TextEditor/TextEditor.d.ts.map +1 -1
  7. package/dist/types/src/components/TextEditor/TextEditor.stories.d.ts +1 -1
  8. package/dist/types/src/components/TextEditor/automerge.stories.d.ts.map +1 -1
  9. package/dist/types/src/components/TextEditor/{comments.stories.d.ts → hooks.stories.d.ts} +9 -12
  10. package/dist/types/src/components/TextEditor/hooks.stories.d.ts.map +1 -0
  11. package/dist/types/src/components/Toolbar/Toolbar.d.ts +25 -0
  12. package/dist/types/src/components/Toolbar/Toolbar.d.ts.map +1 -0
  13. package/dist/types/src/components/Toolbar/Toolbar.stories.d.ts +23 -0
  14. package/dist/types/src/components/Toolbar/Toolbar.stories.d.ts.map +1 -0
  15. package/dist/types/src/components/Toolbar/index.d.ts +2 -0
  16. package/dist/types/src/components/Toolbar/index.d.ts.map +1 -0
  17. package/dist/types/src/components/index.d.ts +1 -0
  18. package/dist/types/src/components/index.d.ts.map +1 -1
  19. package/dist/types/src/extensions/automerge/automerge.d.ts.map +1 -1
  20. package/dist/types/src/extensions/automerge/automerge.spec.d.ts +2 -0
  21. package/dist/types/src/extensions/automerge/automerge.spec.d.ts.map +1 -0
  22. package/dist/types/src/extensions/automerge/automerge.test.d.ts +2 -0
  23. package/dist/types/src/extensions/automerge/automerge.test.d.ts.map +1 -0
  24. package/dist/types/src/extensions/automerge/defs.d.ts +5 -5
  25. package/dist/types/src/extensions/automerge/defs.d.ts.map +1 -1
  26. package/dist/types/src/extensions/automerge/semaphore.d.ts +2 -1
  27. package/dist/types/src/extensions/automerge/semaphore.d.ts.map +1 -1
  28. package/dist/types/src/extensions/automerge/update-automerge.d.ts.map +1 -1
  29. package/dist/types/src/extensions/awareness.d.ts +1 -1
  30. package/dist/types/src/extensions/basic.d.ts +1 -1
  31. package/dist/types/src/extensions/basic.d.ts.map +1 -1
  32. package/dist/types/src/extensions/comments.d.ts +6 -2
  33. package/dist/types/src/extensions/comments.d.ts.map +1 -1
  34. package/dist/types/src/extensions/markdown/bundle.d.ts +2 -2
  35. package/dist/types/src/extensions/markdown/bundle.d.ts.map +1 -1
  36. package/dist/types/src/extensions/markdown/code.d.ts.map +1 -1
  37. package/dist/types/src/extensions/markdown/formatting.d.ts +13 -0
  38. package/dist/types/src/extensions/markdown/formatting.d.ts.map +1 -0
  39. package/dist/types/src/extensions/markdown/index.d.ts +1 -0
  40. package/dist/types/src/extensions/markdown/index.d.ts.map +1 -1
  41. package/dist/types/src/extensions/markdown/link.d.ts.map +1 -1
  42. package/dist/types/src/hooks/index.d.ts +2 -0
  43. package/dist/types/src/hooks/index.d.ts.map +1 -1
  44. package/dist/types/src/hooks/useActionHandler.d.ts +4 -0
  45. package/dist/types/src/hooks/useActionHandler.d.ts.map +1 -0
  46. package/dist/types/src/hooks/useEditorView.d.ts +17 -0
  47. package/dist/types/src/hooks/useEditorView.d.ts.map +1 -0
  48. package/dist/types/src/hooks/useTextEditor.d.ts +36 -14
  49. package/dist/types/src/hooks/useTextEditor.d.ts.map +1 -1
  50. package/dist/types/src/hooks/useTextModel.d.ts +12 -0
  51. package/dist/types/src/hooks/useTextModel.d.ts.map +1 -1
  52. package/dist/types/src/index.d.ts +1 -1
  53. package/dist/types/src/index.d.ts.map +1 -1
  54. package/dist/types/src/themes/default.d.ts.map +1 -1
  55. package/package.json +38 -25
  56. package/src/components/TextEditor/MarkdownEditor.stories.tsx +10 -16
  57. package/src/components/TextEditor/TextEditor.tsx +27 -16
  58. package/src/components/TextEditor/automerge.stories.tsx +1 -2
  59. package/src/components/TextEditor/hooks.stories.tsx +106 -0
  60. package/src/components/Toolbar/Toolbar.stories.tsx +90 -0
  61. package/src/components/Toolbar/Toolbar.tsx +166 -0
  62. package/src/components/Toolbar/index.ts +5 -0
  63. package/src/components/index.ts +1 -0
  64. package/src/extensions/automerge/automerge.spec.tsx +76 -0
  65. package/src/extensions/automerge/automerge.test.ts +13 -0
  66. package/src/extensions/automerge/automerge.ts +26 -11
  67. package/src/extensions/automerge/cursor.ts +3 -3
  68. package/src/extensions/automerge/defs.ts +9 -9
  69. package/src/extensions/automerge/semaphore.ts +17 -19
  70. package/src/extensions/automerge/update-automerge.ts +12 -6
  71. package/src/extensions/automerge/update-codemirror.ts +5 -5
  72. package/src/extensions/awareness.ts +7 -4
  73. package/src/extensions/basic.ts +15 -13
  74. package/src/extensions/blast.ts +4 -1
  75. package/src/extensions/comments.ts +113 -65
  76. package/src/extensions/markdown/bundle.ts +10 -5
  77. package/src/extensions/markdown/code.ts +36 -13
  78. package/src/extensions/markdown/formatting.ts +188 -0
  79. package/src/extensions/markdown/heading.ts +1 -1
  80. package/src/extensions/markdown/index.ts +1 -0
  81. package/src/extensions/markdown/link.ts +12 -2
  82. package/src/hooks/index.ts +2 -0
  83. package/src/hooks/useActionHandler.ts +62 -0
  84. package/src/hooks/useEditorView.ts +29 -0
  85. package/src/hooks/useTextEditor.ts +143 -19
  86. package/src/hooks/useTextModel.ts +28 -9
  87. package/src/index.ts +1 -1
  88. package/src/themes/default.ts +9 -4
  89. package/dist/types/src/components/TextEditor/comments.stories.d.ts.map +0 -1
  90. package/src/components/TextEditor/comments.stories.tsx +0 -357
@@ -19,29 +19,45 @@ import { mx } from '@dxos/react-ui-theme';
19
19
  import { getToken } from '../../styles';
20
20
 
21
21
  // TODO(burdon): Reconcile with theme.
22
- // [aria-readonly="true"]
23
22
  const styles = EditorView.baseTheme({
24
23
  '& .cm-code': {
25
- paddingInline: '1rem !important',
26
24
  fontFamily: getToken('fontFamily.mono', []).join(','),
27
25
  },
28
26
  '& .cm-codeblock': {
29
- display: 'inline-block',
30
27
  width: '100%',
28
+ paddingInline: '1rem !important',
29
+ position: 'relative',
30
+ '&::after': {
31
+ content: '""',
32
+ position: 'absolute',
33
+ inset: 0,
34
+ },
31
35
  },
32
- '&light .cm-codeblock, &light .cm-codeblock.cm-activeLine': {
33
- background: getToken('extend.colors.neutral.25'),
36
+ '&light .cm-codeblock': {
37
+ '&::after': {
38
+ background: getToken('extend.semanticColors.input.light'),
39
+ mixBlendMode: 'darken',
40
+ },
34
41
  },
35
- '&dark .cm-codeblock, &dark .cm-codeblock.cm-activeLine': {
36
- background: getToken('extend.colors.neutral.850'),
42
+ '&dark .cm-codeblock': {
43
+ '&::after': {
44
+ background: getToken('extend.semanticColors.input.dark'),
45
+ mixBlendMode: 'lighten',
46
+ },
37
47
  },
38
48
  '& .cm-codeblock-first': {
39
- borderTopLeftRadius: '.5rem',
40
- borderTopRightRadius: '.5rem',
49
+ display: 'inline-block',
50
+ '&::after': {
51
+ borderTopLeftRadius: '.5rem',
52
+ borderTopRightRadius: '.5rem',
53
+ },
41
54
  },
42
55
  '& .cm-codeblock-last': {
43
- borderBottomLeftRadius: '.5rem',
44
- borderBottomRightRadius: '.5rem',
56
+ display: 'inline-block',
57
+ '&::after': {
58
+ borderBottomLeftRadius: '.5rem',
59
+ borderBottomRightRadius: '.5rem',
60
+ },
45
61
  },
46
62
  });
47
63
 
@@ -52,6 +68,7 @@ const getLineRange = (lines: BlockInfo[], from: number, to: number) => {
52
68
  return [start, end];
53
69
  };
54
70
 
71
+ // TODO(burdon): Add copy to clipboard widget.
55
72
  class LineWidget extends WidgetType {
56
73
  constructor(private readonly _className: string) {
57
74
  super();
@@ -68,17 +85,19 @@ class LineWidget extends WidgetType {
68
85
  const top = new LineWidget('cm-codeblock-first');
69
86
  const bottom = new LineWidget('cm-codeblock-last');
70
87
 
88
+ // TODO(burdon): Selection isn't visible unless multiline (e.g., can't highlight word).
89
+
71
90
  const buildDecorations = (view: EditorView): DecorationSet => {
72
91
  const builder = new RangeSetBuilder<Decoration>();
73
92
  const { state } = view;
74
93
  const blocks = view.viewportLineBlocks;
75
94
  const cursor = state.selection.main.head;
76
95
 
77
- // TODO(burdon): Add copy to clipboard widget.
78
96
  for (const { from, to } of view.visibleRanges) {
79
97
  syntaxTree(state).iterate({
80
98
  enter: (node) => {
81
99
  if (node.name === 'FencedCode') {
100
+ // FencedCode > CodeMark > [CodeInfo] > CodeText > CodeMark
82
101
  const edit = !view.state.readOnly && cursor >= node.from && cursor <= node.to;
83
102
  const range = getLineRange(blocks, node.from, node.to);
84
103
  for (let i = range[0]; i <= range[1]; i++) {
@@ -90,7 +109,11 @@ const buildDecorations = (view: EditorView): DecorationSet => {
90
109
  block.from,
91
110
  block.from,
92
111
  Decoration.line({
93
- class: mx('cm-code cm-codeblock'),
112
+ class: mx(
113
+ 'cm-code cm-codeblock',
114
+ i === range[0] && 'cm-codeblock-first',
115
+ i === range[1] && 'cm-codeblock-last',
116
+ ),
94
117
  }),
95
118
  );
96
119
  }
@@ -0,0 +1,188 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ import { snippet } from '@codemirror/autocomplete';
6
+ import { syntaxTree } from '@codemirror/language';
7
+ import { type Extension, RangeSetBuilder } from '@codemirror/state';
8
+ import {
9
+ type Command,
10
+ Decoration,
11
+ type DecorationSet,
12
+ type EditorView,
13
+ keymap,
14
+ ViewPlugin,
15
+ type ViewUpdate,
16
+ } from '@codemirror/view';
17
+ import { type SyntaxNodeRef, type SyntaxNode } from '@lezer/common';
18
+
19
+ export type FormattingOptions = {};
20
+
21
+ export const setHeading =
22
+ (level: number): Command =>
23
+ (view: EditorView) => {
24
+ const {
25
+ selection: { ranges },
26
+ doc,
27
+ } = view.state;
28
+ const changes = [];
29
+ for (const range of ranges) {
30
+ const { number } = doc.lineAt(range.anchor);
31
+ const { from, to } = doc.line(number);
32
+
33
+ // Check heading doesn't already exist.
34
+ const line = doc.sliceString(from, to);
35
+ const [_, marks, spaces] = line.match(/(#+)(\s+)/) ?? [];
36
+ const current = marks?.length ?? 0;
37
+ if (level !== current) {
38
+ changes.push({
39
+ from,
40
+ to: from + current + (spaces?.length ?? 0),
41
+ insert: '#'.repeat(level) + (level > 0 ? ' ' : ''),
42
+ });
43
+ }
44
+ }
45
+
46
+ if (changes.length) {
47
+ view.dispatch({ changes });
48
+ }
49
+
50
+ return true;
51
+ };
52
+
53
+ export const toggleStyle =
54
+ (mark: string): Command =>
55
+ (view) => {
56
+ const { ranges } = view.state.selection;
57
+ for (const range of ranges) {
58
+ if (range.from === range.to) {
59
+ return false;
60
+ }
61
+
62
+ // TODO(burdon): Detect if already styled (or nested).
63
+ view.dispatch({
64
+ changes: [
65
+ {
66
+ from: range.from,
67
+ insert: mark,
68
+ },
69
+ {
70
+ from: range.to,
71
+ insert: mark,
72
+ },
73
+ ],
74
+ });
75
+ }
76
+
77
+ return true;
78
+ };
79
+
80
+ // TODO(burdon): Define and trigger snippets for codeblock, table, etc.
81
+ const snippets = {
82
+ codeblock: snippet(['```#{lang}', '\t#{}', '```'].join('\n')),
83
+ table: snippet(
84
+ ['| #{col1} | #{col2} |', '| ---- | ---- |', '| #{val1} | #{val2} |', '| #{val3} | #{val4} |'].join('\n'),
85
+ ),
86
+ };
87
+
88
+ export const insertCodeblock = (view: EditorView) => {
89
+ const {
90
+ selection: { main },
91
+ doc,
92
+ } = view.state;
93
+ const { number } = doc.lineAt(main.anchor);
94
+ const { from } = doc.line(number);
95
+ snippets.codeblock(view, null, from, from);
96
+ };
97
+
98
+ export const insertTable = (view: EditorView) => {
99
+ const {
100
+ selection: { main },
101
+ doc,
102
+ } = view.state;
103
+ const { number } = doc.lineAt(main.anchor);
104
+ const { from } = doc.line(number);
105
+ snippets.table(view, null, from, from);
106
+ };
107
+
108
+ export const toggleBold = toggleStyle('**');
109
+ export const toggleItalic = toggleStyle('_');
110
+ export const toggleStrikethrough = toggleStyle('~~');
111
+
112
+ export const toggleList = (view: EditorView) => {};
113
+
114
+ export const formatting = (options: FormattingOptions = {}): Extension => {
115
+ return [
116
+ keymap.of([
117
+ {
118
+ key: 'meta-b',
119
+ run: toggleBold,
120
+ },
121
+ ]),
122
+ styling(),
123
+ ];
124
+ };
125
+
126
+ // https://github.github.com/gfm
127
+ // https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax
128
+
129
+ const styling = (): Extension => {
130
+ const buildDecorations = (view: EditorView): DecorationSet => {
131
+ const builder = new RangeSetBuilder<Decoration>();
132
+ const { state } = view;
133
+ const cursor = state.selection.main.head;
134
+
135
+ // TODO(burdon): Bug if '***foo***' (since StrongEmphasis is nested inside EmphasisMark).
136
+ // Ranges must be added sorted by `from` position and `startSide`.
137
+ const replace = (node: SyntaxNodeRef, marks: SyntaxNode[]) => {
138
+ if (cursor <= node.from || cursor >= node.to) {
139
+ for (const mark of marks) {
140
+ builder.add(mark.from, mark.to, Decoration.replace({}));
141
+ }
142
+ }
143
+ };
144
+
145
+ for (const { from, to } of view.visibleRanges) {
146
+ syntaxTree(state).iterate({
147
+ enter: (node) => {
148
+ switch (node.name) {
149
+ case 'Emphasis':
150
+ case 'StrongEmphasis': {
151
+ const marks = node.node.getChildren('EmphasisMark');
152
+ replace(node, marks);
153
+ break;
154
+ }
155
+
156
+ case 'Strikethrough': {
157
+ const marks = node.node.getChildren('StrikethroughMark');
158
+ replace(node, marks);
159
+ break;
160
+ }
161
+ }
162
+ },
163
+ from,
164
+ to,
165
+ });
166
+ }
167
+
168
+ return builder.finish();
169
+ };
170
+
171
+ return [
172
+ ViewPlugin.fromClass(
173
+ class {
174
+ decorations: DecorationSet;
175
+ constructor(view: EditorView) {
176
+ this.decorations = buildDecorations(view);
177
+ }
178
+
179
+ update(update: ViewUpdate) {
180
+ this.decorations = buildDecorations(update.view);
181
+ }
182
+ },
183
+ {
184
+ decorations: (value) => value.decorations,
185
+ },
186
+ ),
187
+ ];
188
+ };
@@ -23,7 +23,7 @@ const buildDecorations = (view: EditorView): DecorationSet => {
23
23
  case 'ATXHeading6': {
24
24
  const mark = node.node.getChild('HeaderMark');
25
25
  if (mark) {
26
- if (view.state.readOnly || cursor < node.from || cursor > node.to) {
26
+ if (!view.hasFocus || view.state.readOnly || cursor < node.from || cursor > node.to) {
27
27
  builder.add(mark.from, mark.to + 1, Decoration.replace({}));
28
28
  }
29
29
  }
@@ -4,6 +4,7 @@
4
4
 
5
5
  export * from './bundle';
6
6
  export * from './code';
7
+ export * from './formatting';
7
8
  export * from './heading';
8
9
  export * from './highlight';
9
10
  export * from './hr';
@@ -22,6 +22,7 @@ import { tooltipContent } from '@dxos/react-ui-theme';
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
24
24
 
25
+ // TODO(burdon): Callback to dynamically lookup title of linked pages.
25
26
  export type LinkOptions = {
26
27
  link?: boolean;
27
28
  onHover?: (el: Element, url: string) => void;
@@ -64,10 +65,12 @@ export const link = (options: LinkOptions = {}): Extension => {
64
65
  for (let i = 0, node: SyntaxNode | null = syntax; !link && node && i < 5; node = node.parent, i++) {
65
66
  link = node.name === 'Link' ? node : null;
66
67
  }
68
+
67
69
  const url = link && link.getChild('URL');
68
70
  if (!url || !link) {
69
71
  return null;
70
72
  }
73
+
71
74
  const urlText = view.state.sliceDoc(url.from, url.to);
72
75
  return {
73
76
  pos: link.from,
@@ -88,7 +91,10 @@ export const link = (options: LinkOptions = {}): Extension => {
88
91
  };
89
92
 
90
93
  class LinkButton extends WidgetType {
91
- constructor(private readonly _url: string, private readonly _onAttach: LinkOptions['onRender']) {
94
+ constructor(
95
+ private readonly _url: string,
96
+ private readonly _onAttach: LinkOptions['onRender'],
97
+ ) {
92
98
  super();
93
99
  }
94
100
 
@@ -104,7 +110,10 @@ class LinkButton extends WidgetType {
104
110
  }
105
111
 
106
112
  class LinkText extends WidgetType {
107
- constructor(private readonly _text: string, private readonly _url?: string) {
113
+ constructor(
114
+ private readonly _text: string,
115
+ private readonly _url?: string,
116
+ ) {
108
117
  super();
109
118
  }
110
119
 
@@ -157,6 +166,7 @@ const buildDecorations = (view: EditorView, options: LinkOptions): DecorationSet
157
166
  return false;
158
167
  }
159
168
 
169
+ // TODO(burdon): Don't expand if moving cursor up/down.
160
170
  if (!view.hasFocus || state.readOnly || cursor < node.from || cursor > node.to) {
161
171
  builder.add(
162
172
  node.from,
@@ -5,5 +5,7 @@
5
5
  export * from './awareness-provider';
6
6
  export * from './defs';
7
7
 
8
+ export * from './useActionHandler';
9
+ export * from './useEditorView';
8
10
  export * from './useTextEditor';
9
11
  export * from './useTextModel';
@@ -0,0 +1,62 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ import type { EditorView } from '@codemirror/view';
6
+
7
+ import type { ToolbarProps } from '../components';
8
+ import {
9
+ createComment,
10
+ insertCodeblock,
11
+ insertTable,
12
+ setHeading,
13
+ toggleBold,
14
+ toggleItalic,
15
+ toggleList,
16
+ toggleStrikethrough,
17
+ } from '../extensions';
18
+
19
+ export const useActionHandler = (view?: EditorView | null): ToolbarProps['onAction'] => {
20
+ return (action) => {
21
+ if (!view) {
22
+ return;
23
+ }
24
+
25
+ switch (action.type) {
26
+ case 'heading':
27
+ setHeading(parseInt(action.data))(view);
28
+ break;
29
+
30
+ case 'bold':
31
+ toggleBold(view);
32
+ break;
33
+ case 'italic':
34
+ toggleItalic(view);
35
+ break;
36
+ case 'strikethrough':
37
+ toggleStrikethrough(view);
38
+ break;
39
+
40
+ case 'list':
41
+ toggleList(view);
42
+ break;
43
+
44
+ case 'codeblock':
45
+ insertCodeblock(view);
46
+ break;
47
+ case 'table':
48
+ insertTable(view);
49
+ break;
50
+
51
+ case 'comment':
52
+ createComment(view);
53
+ break;
54
+ }
55
+
56
+ // TODO(burdon): Hack otherwise remains on heading selector.
57
+ setTimeout(() => {
58
+ view.focus();
59
+ view.dispatch({ selection: view.state.selection });
60
+ });
61
+ };
62
+ };
@@ -0,0 +1,29 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ import { type EditorView } from '@codemirror/view';
6
+ import { type RefCallback, useState } from 'react';
7
+
8
+ /**
9
+ * Hook for accessing the editor view.
10
+ *
11
+ * ```tsx
12
+ * const Test = () => {
13
+ * const [editorRef, editorView] = useEditorView();
14
+ * useEffect(() => {
15
+ * editorView?.focus();
16
+ * }, [editorView]);
17
+ * return <TextEditor ref={editorRef} />;
18
+ * };
19
+ * ```
20
+ */
21
+ export const useEditorView = (): [RefCallback<EditorView | null>, EditorView | null] => {
22
+ const [view, setView] = useState<EditorView | null>(null);
23
+ return [
24
+ (ref: EditorView | null) => {
25
+ setView(ref);
26
+ },
27
+ view,
28
+ ];
29
+ };
@@ -2,28 +2,152 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
- import { type EditorView } from '@codemirror/view';
6
- import { type RefCallback, useState } from 'react';
5
+ import {
6
+ EditorSelection,
7
+ EditorState,
8
+ type EditorStateConfig,
9
+ type Extension,
10
+ type StateEffect,
11
+ } from '@codemirror/state';
12
+ import { EditorView } from '@codemirror/view';
13
+ import { type RefObject, useEffect, useRef, useState } from 'react';
14
+
15
+ import { log } from '@dxos/log';
16
+ import { type ThemeMode } from '@dxos/react-ui';
17
+ import { isNotFalsy } from '@dxos/util';
18
+
19
+ import { type ThemeStyles } from '..//styles';
20
+ import { defaultTheme } from '../themes';
21
+ import { logChanges } from '../util';
22
+
23
+ export type UseTextEditorOptions = {
24
+ autoFocus?: boolean;
25
+ scrollTo?: StateEffect<any>;
26
+ debug?: boolean;
27
+ } & EditorStateConfig;
28
+
29
+ export type UseTextEditor = {
30
+ parentRef: RefObject<HTMLDivElement>;
31
+ view?: EditorView;
32
+ };
7
33
 
8
34
  /**
9
- * Hook for accessing the editor view.
10
- *
11
- * ```tsx
12
- * const Test = () => {
13
- * const [editorRef, editorView] = useTextEditor();
14
- * useEffect(() => {
15
- * editorView?.focus();
16
- * }, [editorView]);
17
- * return <TextEditor ref={editorRef} />;
18
- * };
19
- * ```
35
+ * Hook for creating editor.
20
36
  */
21
- export const useTextEditor = (): [RefCallback<EditorView | null>, EditorView | null] => {
22
- const [view, setView] = useState<EditorView | null>(null);
37
+ export const useTextEditor = ({
38
+ autoFocus,
39
+ scrollTo,
40
+ debug,
41
+ doc,
42
+ selection,
43
+ extensions,
44
+ }: UseTextEditorOptions = {}): UseTextEditor => {
45
+ const onUpdate = useRef<() => void>();
46
+ const [view, setView] = useState<EditorView>();
47
+ const parentRef = useRef<HTMLDivElement>(null);
48
+ useEffect(() => {
49
+ if (parentRef.current) {
50
+ // https://codemirror.net/docs/ref/#state.EditorStateConfig
51
+ const state = EditorState.create({
52
+ doc,
53
+ selection,
54
+ extensions: [
55
+ // TODO(burdon): Doesn't catch errors in keymap functions.
56
+ EditorView.exceptionSink.of((err) => {
57
+ log.catch(err);
58
+ }),
59
+ extensions,
60
+ EditorView.updateListener.of(() => {
61
+ onUpdate.current?.();
62
+ }),
63
+ ].filter(isNotFalsy),
64
+ });
65
+
66
+ // https://codemirror.net/docs/ref/#view.EditorViewConfig
67
+ const view = new EditorView({
68
+ parent: parentRef.current,
69
+ scrollTo,
70
+ state,
71
+ // NOTE: Uncomment to debug/monitor all transactions.
72
+ // https://codemirror.net/docs/ref/#view.EditorView.dispatch
73
+ dispatchTransactions: (trs, view) => {
74
+ if (debug) {
75
+ logChanges(trs);
76
+ }
77
+ view.update(trs);
78
+ },
79
+ });
80
+
81
+ setView(view);
82
+ }
83
+
84
+ return () => {
85
+ view?.destroy();
86
+ };
87
+ }, [parentRef]);
88
+
89
+ useEffect(() => {
90
+ if (view) {
91
+ // Select end of line if not specified.
92
+ if (!selection && !view.state.selection.main.anchor) {
93
+ selection = EditorSelection.single(view.state.doc.line(1).to);
94
+ }
95
+
96
+ // Set selection after first update (since content may rerender on focus).
97
+ // TODO(burdon): BUG on first render may appear in middle of formatted heading.
98
+ // TODO(burdon): Make invisible until first render?
99
+ if (selection || scrollTo) {
100
+ onUpdate.current = () => {
101
+ onUpdate.current = undefined;
102
+ view.dispatch({ selection, effects: scrollTo && [scrollTo], scrollIntoView: !scrollTo });
103
+ };
104
+ }
105
+
106
+ if (autoFocus) {
107
+ view.focus();
108
+ }
109
+ }
110
+ }, [view, autoFocus, selection, scrollTo]);
111
+
112
+ return { parentRef, view };
113
+ };
114
+
115
+ // TODO(burdon): Factor out extension factories.
116
+
117
+ export type DataExtensionsOptions = {
118
+ readonly?: boolean;
119
+ };
120
+
121
+ // TODO(burdon): Pass in TextObject (remove model).
122
+ export const createDataExtensions = ({ readonly = false } = {}): Extension => {
23
123
  return [
24
- (ref: EditorView | null) => {
25
- setView(ref);
26
- },
27
- view,
124
+ //
125
+ EditorState.readOnly.of(readonly),
126
+ EditorView.editable.of(!readonly),
28
127
  ];
29
128
  };
129
+
130
+ export type ThemeExtensionsOptions = {
131
+ theme?: ThemeStyles;
132
+ themeMode?: ThemeMode;
133
+ lineWrap?: boolean;
134
+ slots?: {
135
+ editor?: {
136
+ className?: string;
137
+ };
138
+ content?: {
139
+ className?: string;
140
+ };
141
+ };
142
+ };
143
+
144
+ export const createThemeExtensions = ({ theme, themeMode, slots }: ThemeExtensionsOptions = {}): Extension => {
145
+ return [
146
+ //
147
+ EditorView.baseTheme(defaultTheme),
148
+ theme && EditorView.theme(theme),
149
+ EditorView.darkTheme.of(themeMode === 'dark'),
150
+ EditorView.editorAttributes.of({ class: slots?.editor?.className ?? '' }),
151
+ EditorView.contentAttributes.of({ class: slots?.content?.className ?? '' }),
152
+ ].filter(isNotFalsy);
153
+ };