@dxos/react-ui-chat 0.8.4-main.5ea62a8 → 0.8.4-main.66e292d

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 (26) hide show
  1. package/dist/lib/browser/index.mjs +68 -272
  2. package/dist/lib/browser/index.mjs.map +4 -4
  3. package/dist/lib/browser/meta.json +1 -1
  4. package/dist/lib/node-esm/index.mjs +68 -272
  5. package/dist/lib/node-esm/index.mjs.map +4 -4
  6. package/dist/lib/node-esm/meta.json +1 -1
  7. package/dist/types/src/components/ChatDialog/ChatDialog.d.ts +1 -1
  8. package/dist/types/src/components/ChatDialog/ChatDialog.d.ts.map +1 -1
  9. package/dist/types/src/components/ChatDialog/ChatDialog.stories.d.ts +1 -2
  10. package/dist/types/src/components/ChatDialog/ChatDialog.stories.d.ts.map +1 -1
  11. package/dist/types/src/components/ChatEditor/ChatEditor.d.ts +5 -8
  12. package/dist/types/src/components/ChatEditor/ChatEditor.d.ts.map +1 -1
  13. package/dist/types/src/components/ChatEditor/ChatEditor.stories.d.ts +1 -2
  14. package/dist/types/src/components/ChatEditor/ChatEditor.stories.d.ts.map +1 -1
  15. package/dist/types/src/components/ChatEditor/references.d.ts +4 -0
  16. package/dist/types/src/components/ChatEditor/references.d.ts.map +1 -1
  17. package/dist/types/tsconfig.tsbuildinfo +1 -1
  18. package/package.json +38 -37
  19. package/src/components/ChatDialog/ChatDialog.stories.tsx +3 -5
  20. package/src/components/ChatDialog/ChatDialog.tsx +7 -7
  21. package/src/components/ChatEditor/ChatEditor.stories.tsx +18 -18
  22. package/src/components/ChatEditor/ChatEditor.tsx +32 -61
  23. package/src/components/ChatEditor/references.ts +17 -11
  24. package/dist/types/src/components/ChatEditor/autocomplete.d.ts +0 -26
  25. package/dist/types/src/components/ChatEditor/autocomplete.d.ts.map +0 -1
  26. package/src/components/ChatEditor/autocomplete.ts +0 -220
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxos/react-ui-chat",
3
- "version": "0.8.4-main.5ea62a8",
3
+ "version": "0.8.4-main.66e292d",
4
4
  "description": "Chat components.",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
@@ -24,50 +24,51 @@
24
24
  "src"
25
25
  ],
26
26
  "dependencies": {
27
- "@codemirror/autocomplete": "^6.18.1",
28
- "@codemirror/language": "^6.10.3",
29
- "@codemirror/search": "^6.5.6",
30
- "@codemirror/state": "^6.4.1",
31
- "@codemirror/view": "^6.34.1",
27
+ "@codemirror/autocomplete": "^6.19.0",
28
+ "@codemirror/language": "^6.11.3",
29
+ "@codemirror/search": "^6.5.11",
30
+ "@codemirror/state": "^6.5.2",
31
+ "@codemirror/view": "^6.38.4",
32
+ "@fluentui/react-tabster": "^9.24.2",
32
33
  "@preact-signals/safe-react": "^0.9.0",
33
- "@preact/signals-core": "^1.9.0",
34
+ "@preact/signals-core": "^1.12.1",
34
35
  "@radix-ui/react-accordion": "1.2.3",
35
36
  "@radix-ui/react-context": "1.1.1",
36
- "@dxos/async": "0.8.4-main.5ea62a8",
37
- "@dxos/debug": "0.8.4-main.5ea62a8",
38
- "@dxos/invariant": "0.8.4-main.5ea62a8",
39
- "@dxos/log": "0.8.4-main.5ea62a8",
40
- "@dxos/live-object": "0.8.4-main.5ea62a8",
41
- "@dxos/react-ui-components": "0.8.4-main.5ea62a8",
42
- "@dxos/react-ui-dnd": "0.8.4-main.5ea62a8",
43
- "@dxos/echo-schema": "0.8.4-main.5ea62a8",
44
- "@dxos/react-ui-sfx": "0.8.4-main.5ea62a8",
45
- "@dxos/react-ui-editor": "0.8.4-main.5ea62a8",
46
- "@dxos/react-ui-syntax-highlighter": "0.8.4-main.5ea62a8",
47
- "@dxos/react-ui-text-tooltip": "0.8.4-main.5ea62a8",
48
- "@dxos/react-ui-theme": "0.8.4-main.5ea62a8",
49
- "@dxos/react-ui-types": "0.8.4-main.5ea62a8",
50
- "@dxos/util": "0.8.4-main.5ea62a8",
51
- "@dxos/react-ui": "0.8.4-main.5ea62a8"
37
+ "@dxos/async": "0.8.4-main.66e292d",
38
+ "@dxos/debug": "0.8.4-main.66e292d",
39
+ "@dxos/echo": "0.8.4-main.66e292d",
40
+ "@dxos/invariant": "0.8.4-main.66e292d",
41
+ "@dxos/live-object": "0.8.4-main.66e292d",
42
+ "@dxos/log": "0.8.4-main.66e292d",
43
+ "@dxos/react-ui-dnd": "0.8.4-main.66e292d",
44
+ "@dxos/react-ui-components": "0.8.4-main.66e292d",
45
+ "@dxos/react-ui": "0.8.4-main.66e292d",
46
+ "@dxos/react-ui-sfx": "0.8.4-main.66e292d",
47
+ "@dxos/react-ui-text-tooltip": "0.8.4-main.66e292d",
48
+ "@dxos/react-ui-theme": "0.8.4-main.66e292d",
49
+ "@dxos/react-ui-editor": "0.8.4-main.66e292d",
50
+ "@dxos/util": "0.8.4-main.66e292d",
51
+ "@dxos/react-ui-syntax-highlighter": "0.8.4-main.66e292d",
52
+ "@dxos/react-ui-types": "0.8.4-main.66e292d"
52
53
  },
53
54
  "devDependencies": {
54
- "@types/react": "~18.2.0",
55
- "@types/react-dom": "~18.2.0",
56
- "effect": "3.17.7",
57
- "react": "~18.2.0",
58
- "react-dom": "~18.2.0",
59
- "vite": "7.1.1",
60
- "@dxos/echo": "0.8.4-main.5ea62a8",
61
- "@dxos/random": "0.8.4-main.5ea62a8",
62
- "@dxos/storybook-utils": "0.8.4-main.5ea62a8",
63
- "@dxos/react-client": "0.8.4-main.5ea62a8"
55
+ "@types/react": "~19.2.2",
56
+ "@types/react-dom": "~19.2.2",
57
+ "effect": "3.18.3",
58
+ "react": "~19.2.0",
59
+ "react-dom": "~19.2.0",
60
+ "vite": "7.1.9",
61
+ "@dxos/echo": "0.8.4-main.66e292d",
62
+ "@dxos/random": "0.8.4-main.66e292d",
63
+ "@dxos/react-client": "0.8.4-main.66e292d",
64
+ "@dxos/storybook-utils": "0.8.4-main.66e292d"
64
65
  },
65
66
  "peerDependencies": {
66
67
  "effect": "^3.13.3",
67
- "react": "~18.2.0",
68
- "react-dom": "~18.2.0",
69
- "@dxos/react-ui": "0.8.4-main.5ea62a8",
70
- "@dxos/react-ui-theme": "0.8.4-main.5ea62a8"
68
+ "react": "^19.0.0",
69
+ "react-dom": "^19.0.0",
70
+ "@dxos/react-ui": "0.8.4-main.66e292d",
71
+ "@dxos/react-ui-theme": "0.8.4-main.66e292d"
71
72
  },
72
73
  "publishConfig": {
73
74
  "access": "public"
@@ -2,13 +2,11 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import '@dxos-theme';
6
-
7
5
  import { type Meta, type StoryObj } from '@storybook/react-vite';
8
6
  import React, { useState } from 'react';
9
7
 
10
8
  import { Input, Toolbar } from '@dxos/react-ui';
11
- import { withLayout, withTheme } from '@dxos/storybook-utils';
9
+ import { withLayout, withTheme } from '@dxos/react-ui/testing';
12
10
 
13
11
  import { translations } from '../../translations';
14
12
 
@@ -44,7 +42,7 @@ const meta = {
44
42
  </div>
45
43
  ))}
46
44
  </ChatDialog.Content>
47
- <ChatDialog.Footer classNames='px-2 items-center'>
45
+ <ChatDialog.Footer classNames='pli-2 items-center'>
48
46
  <Input.Root>
49
47
  <Input.TextInput classNames='border-none' placeholder='Test' />
50
48
  </Input.Root>
@@ -53,7 +51,7 @@ const meta = {
53
51
  </>
54
52
  );
55
53
  },
56
- decorators: [withTheme, withLayout({ fullscreen: true, classNames: 'flex flex-col' })],
54
+ decorators: [withTheme, withLayout({ container: 'column' })],
57
55
  parameters: {
58
56
  translations,
59
57
  },
@@ -14,7 +14,7 @@ const preventDefault = (event: Event) => event.preventDefault();
14
14
  // TODO(burdon): Factor out.
15
15
  const Endcap = ({ children }: PropsWithChildren) => {
16
16
  return (
17
- <div className='grid w-[var(--rail-action)] h-[var(--rail-action)] items-center justify-center'>{children}</div>
17
+ <div className='grid is-[var(--rail-action)] bs-[var(--rail-action)] items-center justify-center'>{children}</div>
18
18
  );
19
19
  };
20
20
 
@@ -47,15 +47,15 @@ type ChatDialogRootProps = PropsWithChildren<{
47
47
 
48
48
  const ChatDialogRoot = ({
49
49
  children,
50
- open: _open = false,
51
- expanded: _expanded = false,
50
+ open: openParam = false,
51
+ expanded: expandedParam = false,
52
52
  onOpenChange,
53
53
  onExpandedChange,
54
54
  onEscape,
55
55
  }: ChatDialogRootProps) => {
56
56
  const [size, setSize] = useState<Size>('min-content');
57
- const [open, setOpen] = useControlledState<boolean>(_open, onOpenChange);
58
- const [expanded, setExpanded] = useControlledState<boolean>(_expanded, onExpandedChange);
57
+ const [open, setOpen] = useControlledState<boolean>(openParam, onOpenChange);
58
+ const [expanded, setExpanded] = useControlledState<boolean>(expandedParam, onExpandedChange);
59
59
 
60
60
  // NOTE: We set the min size to 5rem (80px), and the header and prompt bar to 40px (i.e., the rail-size) each.
61
61
  // The dialog has no vertical padding and has box-content so that when closed it collapses to the size of the header and prompt bar.
@@ -108,7 +108,7 @@ const ChatDialogHeader = ({ classNames, title }: ChatDialogHeaderProps) => {
108
108
  </Dialog.Close>
109
109
  </Endcap>
110
110
  <Dialog.Title
111
- classNames='flex w-full justify-center text-sm text-subdued select-none cursor-pointer'
111
+ classNames='flex is-full justify-center text-sm text-subdued select-none cursor-pointer'
112
112
  onClick={() => setExpanded((expanded) => !expanded)}
113
113
  >
114
114
  {title}
@@ -144,7 +144,7 @@ const ChatDialogContent = ({ children, classNames }: ChatDialogContentProps) =>
144
144
  return (
145
145
  <div
146
146
  className={mx(
147
- 'flex flex-col overflow-y-auto border-t border-b border-subduedSeparator',
147
+ 'flex flex-col overflow-y-auto border-t border-be border-subduedSeparator',
148
148
  'transition-[block-size] ease-in-out duration-0 [&:not([data-dx-resizing="true"])]:duration-200',
149
149
  classNames,
150
150
  )}
@@ -2,12 +2,10 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import '@dxos-theme';
6
-
7
5
  import { type Meta, type StoryObj } from '@storybook/react-vite';
8
6
 
9
7
  import { log } from '@dxos/log';
10
- import { withTheme } from '@dxos/storybook-utils';
8
+ import { withTheme } from '@dxos/react-ui/testing';
11
9
 
12
10
  import { translations } from '../../translations';
13
11
 
@@ -26,7 +24,7 @@ const meta = {
26
24
 
27
25
  export default meta;
28
26
 
29
- const classNames = 'w-[20rem] p-2 border border-separator';
27
+ const classNames = 'is-[20rem] p-2 border border-separator';
30
28
 
31
29
  type Story = StoryObj<typeof meta>;
32
30
 
@@ -36,31 +34,33 @@ export const Default: Story = {
36
34
  },
37
35
  };
38
36
 
37
+ // TODO(burdon): Restore and reconcile with suggest/typeahead.
39
38
  export const WithSuggestions: Story = {
40
39
  args: {
41
40
  classNames,
42
41
  onSubmit: (text) => {
43
42
  log('onSubmit', { text });
44
43
  },
45
- onSuggest: (text) => {
46
- const trimmed = text.trim().toLowerCase();
47
- if (trimmed.length < 2) {
48
- return [];
49
- }
44
+ // onSuggest: (text) => {
45
+ // const trimmed = text.trim().toLowerCase();
46
+ // if (trimmed.length < 2) {
47
+ // return [];
48
+ // }
50
49
 
51
- const suggestions = [
52
- 'Create a kanban board',
53
- 'Create a new project',
54
- 'Find flights to Tokyo',
55
- "Let's play chess",
56
- 'Show me Paris on a map',
57
- ];
50
+ // const suggestions = [
51
+ // 'Create a kanban board',
52
+ // 'Create a new project',
53
+ // 'Find flights to Tokyo',
54
+ // "Let's play chess",
55
+ // 'Show me Paris on a map',
56
+ // ];
58
57
 
59
- return suggestions.filter((s) => s.toLowerCase().startsWith(text));
60
- },
58
+ // return suggestions.filter((s) => s.toLowerCase().startsWith(text));
59
+ // },
61
60
  },
62
61
  };
63
62
 
63
+ // TODO(burdon): Replace.
64
64
  const references: ReferenceData[] = [
65
65
  {
66
66
  uri: 'dxn:echo:@:AAAAAAAA',
@@ -3,86 +3,57 @@
3
3
  //
4
4
 
5
5
  import { type Extension } from '@codemirror/state';
6
- import React, { forwardRef, useImperativeHandle } from 'react';
6
+ import React, { forwardRef, useMemo } from 'react';
7
7
 
8
8
  import { type ThemedClassName, useThemeContext } from '@dxos/react-ui';
9
9
  import {
10
10
  type BasicExtensionsOptions,
11
+ Editor,
12
+ type EditorController,
13
+ type SubmitOptions,
11
14
  type UseTextEditorProps,
12
15
  createBasicExtensions,
13
16
  createThemeExtensions,
14
- useTextEditor,
17
+ submit,
15
18
  } from '@dxos/react-ui-editor';
16
- import { mx } from '@dxos/react-ui-theme';
17
- import { isNonNullable } from '@dxos/util';
19
+ import { isTruthy } from '@dxos/util';
18
20
 
19
- import { type AutocompleteOptions, autocomplete } from './autocomplete';
20
- import { type ReferencesOptions, references as referencesExtension } from './references';
21
+ import { type ReferencesOptions } from './references';
21
22
 
22
- export interface ChatEditorController {
23
- focus(): void;
24
- getText(): string;
25
- setText(text: string): void;
26
- }
23
+ export interface ChatEditorController extends EditorController {}
27
24
 
28
25
  export type ChatEditorProps = ThemedClassName<
29
26
  {
30
27
  extensions?: Extension;
31
28
  references?: ReferencesOptions;
32
- } & AutocompleteOptions &
29
+ } & (SubmitOptions &
33
30
  Pick<UseTextEditorProps, 'id' | 'autoFocus'> &
34
- Pick<BasicExtensionsOptions, 'lineWrapping' | 'placeholder'>
31
+ Pick<BasicExtensionsOptions, 'lineWrapping' | 'placeholder'>)
35
32
  >;
36
33
 
37
- export const ChatEditor = forwardRef<ChatEditorController, ChatEditorProps>(
38
- (
39
- { classNames, extensions, references, autoFocus, lineWrapping = false, placeholder, onSubmit, onSuggest, onCancel },
40
- forwardRef,
41
- ) => {
42
- const { themeMode } = useThemeContext();
34
+ export const useChatExtensions = ({ extensions, lineWrapping = false, placeholder, onSubmit }: ChatEditorProps) => {
35
+ const { themeMode } = useThemeContext();
36
+ return useMemo<Extension[]>(
37
+ () =>
38
+ [
39
+ createThemeExtensions({ themeMode }),
40
+ createBasicExtensions({ bracketMatching: false, lineWrapping, placeholder }),
41
+ submit({ onSubmit }),
42
+ extensions,
43
+ ].filter(isTruthy),
44
+ [themeMode, extensions, onSubmit],
45
+ );
46
+ };
43
47
 
44
- const { parentRef, view } = useTextEditor(
45
- () => ({
46
- debug: true,
47
- autoFocus,
48
- extensions: [
49
- createThemeExtensions({ themeMode }),
50
- autocomplete({ onSubmit, onSuggest, onCancel }),
51
- references ? referencesExtension({ provider: references.provider }) : [],
52
- createBasicExtensions({
53
- bracketMatching: false,
54
- lineWrapping,
55
- placeholder,
56
- }),
57
- extensions,
58
- ].filter(isNonNullable),
59
- }),
60
- [themeMode, extensions, onSubmit, onSuggest, onCancel],
48
+ export const ChatEditor = forwardRef<ChatEditorController, ChatEditorProps>(
49
+ ({ classNames, autoFocus, extensions: extensionsParam, lineWrapping = false, placeholder, onSubmit }, forwardRef) => {
50
+ const extensions = useChatExtensions({ extensions: extensionsParam, lineWrapping, placeholder, onSubmit });
51
+
52
+ // TODO(burdon): Popover.
53
+ return (
54
+ <Editor.Root ref={forwardRef}>
55
+ <Editor.Content classNames={classNames} autoFocus={autoFocus} extensions={extensions} />
56
+ </Editor.Root>
61
57
  );
62
-
63
- // Expose editor view.
64
- useImperativeHandle(forwardRef, () => {
65
- return {
66
- focus: () => {
67
- view?.focus();
68
- },
69
- getText: () => view?.state.doc.toString() ?? '',
70
- setText: (text: string) => {
71
- view?.dispatch({
72
- changes: {
73
- from: 0,
74
- to: view.state.doc.length,
75
- insert: text,
76
- },
77
- selection: {
78
- anchor: text.length,
79
- head: text.length,
80
- },
81
- });
82
- },
83
- };
84
- }, [view, onSubmit]);
85
-
86
- return <div ref={parentRef} className={mx('is-full', classNames)} />;
87
58
  },
88
59
  );
@@ -19,10 +19,14 @@ import { invariant } from '@dxos/invariant';
19
19
 
20
20
  // TODO(dmaretskyi): Consider adding details renderer for when you hover over the reference.
21
21
  export type ReferenceData = {
22
- uri: string;
22
+ uri: string; // TODO(burdon): Rename dxn.
23
23
  label: string;
24
24
  };
25
25
 
26
+ /**
27
+ * @deprecated
28
+ */
29
+ // TODO(burdon): Remove.
26
30
  export interface ReferencesProvider {
27
31
  getReferences({ query }: { query: string }): Promise<ReferenceData[]>;
28
32
  resolveReference({ uri }: { uri: string }): Promise<ReferenceData | null>;
@@ -45,7 +49,9 @@ export type ReferencesOptions = {
45
49
 
46
50
  /**
47
51
  * Lookup object references.
52
+ * @deprecated
48
53
  */
54
+ // TODO(burdon): Remove.
49
55
  export const references = ({ provider, triggerCharacter = '@', debug = false }: ReferencesOptions): Extension => {
50
56
  invariant(triggerCharacter.length === 1);
51
57
 
@@ -103,7 +109,7 @@ export const references = ({ provider, triggerCharacter = '@', debug = false }:
103
109
  },
104
110
  {
105
111
  decorations: (v) => v.decorations,
106
- provide: (plugin) => [
112
+ provide: () => [
107
113
  EditorView.atomicRanges.of(
108
114
  (view): DecorationSet => view.plugin(decorationField)?.decorations ?? RangeSet.empty,
109
115
  ),
@@ -158,18 +164,18 @@ class ReferenceWidget extends WidgetType {
158
164
  super();
159
165
  }
160
166
 
161
- override toDOM(): HTMLSpanElement {
162
- const span = document.createElement('span');
163
- span.textContent = `@ ${this.data.label}`;
164
- span.className = 'cm-reference-pill';
165
- return span;
167
+ override ignoreEvent() {
168
+ return true;
166
169
  }
167
170
 
168
- override eq(other: ReferenceWidget): boolean {
169
- return other.data.uri === this.data.uri;
171
+ override eq(other: this) {
172
+ return this.data.uri === other.data.uri;
170
173
  }
171
174
 
172
- override ignoreEvent(): boolean {
173
- return true;
175
+ override toDOM() {
176
+ const span = document.createElement('span');
177
+ span.textContent = `@${this.data.label}`;
178
+ span.className = 'cm-reference-pill';
179
+ return span;
174
180
  }
175
181
  }
@@ -1,26 +0,0 @@
1
- import { type Extension } from '@codemirror/state';
2
- export type AutocompleteOptions = {
3
- fireIfEmpty?: boolean;
4
- /**
5
- * Callback triggered when Enter is pressed.
6
- * @param text The current text in the editor
7
- * @returns true if the editor should reset the document.
8
- */
9
- onSubmit?: (text: string) => boolean | void;
10
- /**
11
- * Function that returns a list of suggestions based on the current text.
12
- * @param text The current text before the cursor
13
- * @returns Array of suggestion strings
14
- */
15
- onSuggest?: (text: string) => string[];
16
- /**
17
- * ESC pressed.
18
- */
19
- onCancel?: () => void;
20
- };
21
- /**
22
- * Creates an autocomplete extension that shows inline suggestions.
23
- * Pressing Tab will complete the suggestion.
24
- */
25
- export declare const autocomplete: ({ fireIfEmpty, onSubmit, onSuggest, onCancel }: AutocompleteOptions) => Extension;
26
- //# sourceMappingURL=autocomplete.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"autocomplete.d.ts","sourceRoot":"","sources":["../../../../../src/components/ChatEditor/autocomplete.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,SAAS,EAAQ,MAAM,mBAAmB,CAAC;AAWzD,MAAM,MAAM,mBAAmB,GAAG;IAChC,WAAW,CAAC,EAAE,OAAO,CAAC;IAEtB;;;;OAIG;IACH,QAAQ,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,GAAG,IAAI,CAAC;IAE5C;;;;OAIG;IACH,SAAS,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAAM,EAAE,CAAC;IAEvC;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,IAAI,CAAC;CACvB,CAAC;AAEF;;;GAGG;AAEH,eAAO,MAAM,YAAY,GAAI,gDAAgD,mBAAmB,KAAG,SA+JlG,CAAC"}
@@ -1,220 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import { type Extension, Prec } from '@codemirror/state';
6
- import {
7
- Decoration,
8
- type DecorationSet,
9
- EditorView,
10
- ViewPlugin,
11
- type ViewUpdate,
12
- WidgetType,
13
- keymap,
14
- } from '@codemirror/view';
15
-
16
- export type AutocompleteOptions = {
17
- fireIfEmpty?: boolean;
18
-
19
- /**
20
- * Callback triggered when Enter is pressed.
21
- * @param text The current text in the editor
22
- * @returns true if the editor should reset the document.
23
- */
24
- onSubmit?: (text: string) => boolean | void;
25
-
26
- /**
27
- * Function that returns a list of suggestions based on the current text.
28
- * @param text The current text before the cursor
29
- * @returns Array of suggestion strings
30
- */
31
- onSuggest?: (text: string) => string[];
32
-
33
- /**
34
- * ESC pressed.
35
- */
36
- onCancel?: () => void;
37
- };
38
-
39
- /**
40
- * Creates an autocomplete extension that shows inline suggestions.
41
- * Pressing Tab will complete the suggestion.
42
- */
43
- // TODO(burdon): Move to react-ui-editor.
44
- export const autocomplete = ({ fireIfEmpty, onSubmit, onSuggest, onCancel }: AutocompleteOptions): Extension => {
45
- const suggest = ViewPlugin.fromClass(
46
- class {
47
- _decorations: DecorationSet;
48
- _currentSuggestion: string | null = null;
49
-
50
- constructor(view: EditorView) {
51
- this._decorations = this.computeDecorations(view);
52
- }
53
-
54
- update(update: ViewUpdate) {
55
- if (update.docChanged || update.selectionSet) {
56
- this._decorations = this.computeDecorations(update.view);
57
- }
58
- }
59
-
60
- private computeDecorations(view: EditorView): DecorationSet {
61
- const text = view.state.doc.toString();
62
- const suggestions = onSuggest?.(text) ?? [];
63
- if (!suggestions.length) {
64
- this._currentSuggestion = null;
65
- return Decoration.none;
66
- }
67
-
68
- // Get the first suggestion.
69
- this._currentSuggestion = suggestions[0];
70
- const suffix = this._currentSuggestion.slice(text.length);
71
- if (!suffix) {
72
- return Decoration.none;
73
- }
74
-
75
- // Always show ghost text at the end of the document.
76
- return Decoration.set([
77
- Decoration.widget({
78
- widget: new InlineSuggestionWidget(suffix),
79
- side: 1,
80
- }).range(view.state.doc.length),
81
- ]);
82
- }
83
-
84
- completeSuggestion(view: EditorView): boolean {
85
- if (!this._currentSuggestion) {
86
- return false;
87
- }
88
-
89
- const text = view.state.doc.toString();
90
- const suffix = this._currentSuggestion.slice(text.length);
91
- if (!suffix) {
92
- return false;
93
- }
94
-
95
- view.dispatch({
96
- changes: {
97
- from: view.state.doc.length,
98
- insert: suffix,
99
- },
100
- selection: {
101
- anchor: view.state.doc.length + suffix.length,
102
- },
103
- });
104
-
105
- return true;
106
- }
107
- },
108
- {
109
- decorations: (v) => v._decorations,
110
- },
111
- );
112
-
113
- return [
114
- suggest,
115
- EditorView.theme({
116
- '.cm-inline-suggestion': {
117
- opacity: 0.4,
118
- },
119
- }),
120
-
121
- Prec.highest(
122
- keymap.of([
123
- {
124
- key: 'Tab',
125
- preventDefault: true,
126
- run: (view) => {
127
- const plugin = view.plugin(suggest);
128
- return plugin?.completeSuggestion(view) ?? false;
129
- },
130
- },
131
- {
132
- key: 'ArrowRight',
133
- preventDefault: true,
134
- run: (view) => {
135
- // Only complete if cursor is at the end
136
- if (view.state.selection.main.head !== view.state.doc.length) {
137
- return false;
138
- }
139
-
140
- const plugin = view.plugin(suggest);
141
- return plugin?.completeSuggestion(view) ?? false;
142
- },
143
- },
144
- {
145
- key: 'Enter',
146
- preventDefault: true,
147
- run: (view) => {
148
- const text = view.state.doc.toString().trim();
149
- if (onSubmit && (fireIfEmpty || text.length > 0)) {
150
- const reset = onSubmit(text);
151
-
152
- // Clear the document after calling onEnter.
153
- if (reset) {
154
- view.dispatch({
155
- changes: {
156
- from: 0,
157
- to: view.state.doc.length,
158
- insert: '',
159
- },
160
- });
161
- }
162
- }
163
-
164
- return true;
165
- },
166
- },
167
- {
168
- key: 'Shift-Enter',
169
- preventDefault: true,
170
- run: (view) => {
171
- view.dispatch({
172
- changes: {
173
- from: view.state.selection.main.head,
174
- insert: '\n',
175
- },
176
- selection: {
177
- anchor: view.state.selection.main.head + 1,
178
- head: view.state.selection.main.head + 1,
179
- },
180
- });
181
- return true;
182
- },
183
- },
184
- {
185
- key: 'Escape',
186
- preventDefault: true,
187
- run: (view) => {
188
- // Clear the entire document.
189
- view.dispatch({
190
- changes: {
191
- from: 0,
192
- to: view.state.doc.length,
193
- insert: '',
194
- },
195
- });
196
- onCancel?.();
197
- return true;
198
- },
199
- },
200
- ]),
201
- ),
202
- ];
203
- };
204
-
205
- class InlineSuggestionWidget extends WidgetType {
206
- constructor(private suffix: string) {
207
- super();
208
- }
209
-
210
- override toDOM(): HTMLSpanElement {
211
- const span = document.createElement('span');
212
- span.textContent = this.suffix;
213
- span.className = 'cm-inline-suggestion';
214
- return span;
215
- }
216
-
217
- override eq(other: InlineSuggestionWidget): boolean {
218
- return other.suffix === this.suffix;
219
- }
220
- }