@copilotkit/react-textarea 0.11.0 → 0.12.0

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 (62) hide show
  1. package/.turbo/turbo-build.log +84 -73
  2. package/CHANGELOG.md +7 -0
  3. package/dist/chunk-AOEXKPIX.mjs +83 -0
  4. package/dist/chunk-AOEXKPIX.mjs.map +1 -0
  5. package/dist/{chunk-6SYD77G6.mjs → chunk-CSGFJU3L.mjs} +2 -2
  6. package/dist/chunk-CSGFJU3L.mjs.map +1 -0
  7. package/dist/chunk-DCQ27XRF.mjs +32 -0
  8. package/dist/chunk-DCQ27XRF.mjs.map +1 -0
  9. package/dist/chunk-DE5K76I2.mjs +3 -0
  10. package/dist/{chunk-E2UEE45I.mjs → chunk-HZGSG7ST.mjs} +1 -1
  11. package/dist/chunk-HZGSG7ST.mjs.map +1 -0
  12. package/dist/{chunk-THWPPG6M.mjs → chunk-IGQI27NI.mjs} +20 -2
  13. package/dist/chunk-IGQI27NI.mjs.map +1 -0
  14. package/dist/chunk-M6QFKIBE.mjs +161 -0
  15. package/dist/chunk-M6QFKIBE.mjs.map +1 -0
  16. package/dist/chunk-WADHCMPK.mjs +3 -0
  17. package/dist/components/base-copilot-textarea/base-copilot-textarea.d.ts +9 -4
  18. package/dist/components/base-copilot-textarea/base-copilot-textarea.mjs +9 -8
  19. package/dist/components/base-copilot-textarea/use-add-branding-css.mjs +1 -1
  20. package/dist/components/copilot-textarea/copilot-textarea.d.ts +3 -2
  21. package/dist/components/copilot-textarea/copilot-textarea.mjs +10 -9
  22. package/dist/components/index.d.ts +2 -1
  23. package/dist/components/index.mjs +10 -9
  24. package/dist/hooks/{use-autosuggestions.d.ts → base-copilot-textarea-implementation/use-autosuggestions.d.ts} +3 -3
  25. package/dist/hooks/base-copilot-textarea-implementation/use-autosuggestions.mjs +7 -0
  26. package/dist/hooks/{use-copilot-textarea-editor.d.ts → base-copilot-textarea-implementation/use-copilot-textarea-editor.d.ts} +1 -1
  27. package/dist/hooks/base-copilot-textarea-implementation/use-copilot-textarea-editor.mjs +5 -0
  28. package/dist/hooks/base-copilot-textarea-implementation/use-copilot-textarea-editor.mjs.map +1 -0
  29. package/dist/hooks/base-copilot-textarea-implementation/use-populate-copilot-textarea-ref.d.ts +7 -0
  30. package/dist/hooks/base-copilot-textarea-implementation/use-populate-copilot-textarea-ref.mjs +6 -0
  31. package/dist/hooks/base-copilot-textarea-implementation/use-populate-copilot-textarea-ref.mjs.map +1 -0
  32. package/dist/index.css +4 -0
  33. package/dist/index.css.map +1 -1
  34. package/dist/index.d.ts +1 -0
  35. package/dist/index.mjs +12 -10
  36. package/dist/types/html-copilot-textarea-element.d.ts +7 -0
  37. package/dist/types/html-copilot-textarea-element.mjs +3 -0
  38. package/dist/types/html-copilot-textarea-element.mjs.map +1 -0
  39. package/dist/types/index.d.ts +1 -0
  40. package/dist/types/index.mjs +2 -1
  41. package/package.json +1 -1
  42. package/src/components/base-copilot-textarea/base-copilot-textarea.tsx +160 -146
  43. package/src/components/base-copilot-textarea/use-add-branding-css.tsx +25 -1
  44. package/src/components/copilot-textarea/copilot-textarea.tsx +31 -21
  45. package/src/hooks/{use-autosuggestions.ts → base-copilot-textarea-implementation/use-autosuggestions.ts} +5 -5
  46. package/src/hooks/{use-copilot-textarea-editor.tsx → base-copilot-textarea-implementation/use-copilot-textarea-editor.tsx} +5 -5
  47. package/src/hooks/base-copilot-textarea-implementation/use-populate-copilot-textarea-ref.ts +101 -0
  48. package/src/types/html-copilot-textarea-element.ts +5 -0
  49. package/src/types/index.ts +1 -0
  50. package/dist/chunk-6SYD77G6.mjs.map +0 -1
  51. package/dist/chunk-E2UEE45I.mjs.map +0 -1
  52. package/dist/chunk-FD6FGKYY.mjs +0 -3
  53. package/dist/chunk-THWPPG6M.mjs.map +0 -1
  54. package/dist/chunk-YICIML6J.mjs +0 -154
  55. package/dist/chunk-YICIML6J.mjs.map +0 -1
  56. package/dist/chunk-YTT5NE6B.mjs +0 -25
  57. package/dist/chunk-YTT5NE6B.mjs.map +0 -1
  58. package/dist/hooks/use-autosuggestions.mjs +0 -7
  59. package/dist/hooks/use-copilot-textarea-editor.mjs +0 -5
  60. /package/dist/{chunk-FD6FGKYY.mjs.map → chunk-DE5K76I2.mjs.map} +0 -0
  61. /package/dist/{hooks/use-autosuggestions.mjs.map → chunk-WADHCMPK.mjs.map} +0 -0
  62. /package/dist/hooks/{use-copilot-textarea-editor.mjs.map → base-copilot-textarea-implementation/use-autosuggestions.mjs.map} +0 -0
@@ -1,9 +1,10 @@
1
- import { useCallback, useEffect, useMemo, useState } from "react";
1
+ import React, { useCallback, useEffect, useMemo, useState } from "react";
2
2
  import { Descendant, Editor } from "slate";
3
3
  import { Editable, Slate } from "slate-react";
4
4
  import { twMerge } from "tailwind-merge";
5
- import { useAutosuggestions } from "../../hooks/use-autosuggestions";
6
- import { useCopilotTextareaEditor } from "../../hooks/use-copilot-textarea-editor";
5
+ import { useAutosuggestions } from "../../hooks/base-copilot-textarea-implementation/use-autosuggestions";
6
+ import { useCopilotTextareaEditor } from "../../hooks/base-copilot-textarea-implementation/use-copilot-textarea-editor";
7
+ import { usePopulateCopilotTextareaRef } from "../../hooks/base-copilot-textarea-implementation/use-populate-copilot-textarea-ref";
7
8
  import {
8
9
  getFullEditorTextWithNewlines,
9
10
  getTextAroundCursor,
@@ -23,158 +24,171 @@ import { makeRenderElementFunction } from "./render-element";
23
24
  import { makeRenderPlaceholderFunction } from "./render-placeholder";
24
25
  import { useAddBrandingCss } from "./use-add-branding-css";
25
26
 
26
- export function BaseCopilotTextarea(
27
- props: BaseCopilotTextareaProps & {
28
- autosuggestionsFunction: AutosuggestionsBareFunction;
29
- }
30
- ): JSX.Element {
31
- const autosuggestionsConfig: BaseAutosuggestionsConfig = {
32
- ...defaultBaseAutosuggestionsConfig,
33
- ...props.autosuggestionsConfig,
34
- };
35
-
36
- const valueOnInitialRender = useMemo(() => props.value ?? "", []);
37
- const [lastKnownFullEditorText, setLastKnownFullEditorText] =
38
- useState(valueOnInitialRender);
39
-
40
- const initialValue: Descendant[] = useMemo(() => {
41
- return [
42
- {
43
- type: "paragraph",
44
- children: [{ text: valueOnInitialRender }],
45
- },
46
- ];
47
- }, [valueOnInitialRender]);
48
-
49
- const editor = useCopilotTextareaEditor();
27
+ export interface HTMLCopilotTextAreaElement extends HTMLElement {
28
+ value: string;
29
+ focus: () => void;
30
+ blur: () => void;
31
+ }
50
32
 
51
- const insertText = useCallback(
52
- (autosuggestion: AutosuggestionState) => {
53
- Editor.insertText(editor, autosuggestion.text, {
54
- at: autosuggestion.point,
55
- });
33
+ export const BaseCopilotTextarea = React.forwardRef(
34
+ (
35
+ props: BaseCopilotTextareaProps & {
36
+ autosuggestionsFunction: AutosuggestionsBareFunction;
56
37
  },
57
- [editor]
58
- );
59
-
60
- const {
61
- currentAutocompleteSuggestion,
62
- onChangeHandler: onChangeHandlerForAutocomplete,
63
- onKeyDownHandler: onKeyDownHandlerForAutocomplete,
64
- } = useAutosuggestions(
65
- autosuggestionsConfig.debounceTime,
66
- autosuggestionsConfig.acceptAutosuggestionKey,
67
- props.autosuggestionsFunction,
68
- insertText,
69
- autosuggestionsConfig.disableWhenEmpty,
70
- autosuggestionsConfig.disabled
71
- );
72
-
73
- // sync autosuggestions state with the editor
74
- useEffect(() => {
75
- clearAutocompletionsFromEditor(editor);
76
- if (currentAutocompleteSuggestion) {
77
- addAutocompletionsToEditor(
78
- editor,
79
- currentAutocompleteSuggestion.text,
80
- currentAutocompleteSuggestion.point
81
- );
82
- }
83
- }, [currentAutocompleteSuggestion]);
84
-
85
- const suggestionStyleAugmented: React.CSSProperties = useMemo(() => {
86
- return {
87
- fontStyle: "italic",
88
- color: "gray",
89
- ...props.suggestionsStyle,
38
+ ref: React.Ref<HTMLCopilotTextAreaElement>
39
+ ): JSX.Element => {
40
+ const autosuggestionsConfig: BaseAutosuggestionsConfig = {
41
+ ...defaultBaseAutosuggestionsConfig,
42
+ ...props.autosuggestionsConfig,
90
43
  };
91
- }, [props.suggestionsStyle]);
92
44
 
93
- useAddBrandingCss(suggestionStyleAugmented, props.disableBranding);
45
+ const valueOnInitialRender = useMemo(() => props.value ?? "", []);
46
+ const [lastKnownFullEditorText, setLastKnownFullEditorText] =
47
+ useState(valueOnInitialRender);
48
+
49
+ const initialValue: Descendant[] = useMemo(() => {
50
+ return [
51
+ {
52
+ type: "paragraph",
53
+ children: [{ text: valueOnInitialRender }],
54
+ },
55
+ ];
56
+ }, [valueOnInitialRender]);
57
+
58
+ const editor = useCopilotTextareaEditor();
59
+
60
+ const insertText = useCallback(
61
+ (autosuggestion: AutosuggestionState) => {
62
+ Editor.insertText(editor, autosuggestion.text, {
63
+ at: autosuggestion.point,
64
+ });
65
+ },
66
+ [editor]
67
+ );
68
+
69
+ const {
70
+ currentAutocompleteSuggestion,
71
+ onChangeHandler: onChangeHandlerForAutocomplete,
72
+ onKeyDownHandler: onKeyDownHandlerForAutocomplete,
73
+ } = useAutosuggestions(
74
+ autosuggestionsConfig.debounceTime,
75
+ autosuggestionsConfig.acceptAutosuggestionKey,
76
+ props.autosuggestionsFunction,
77
+ insertText,
78
+ autosuggestionsConfig.disableWhenEmpty,
79
+ autosuggestionsConfig.disabled
80
+ );
81
+
82
+ // sync autosuggestions state with the editor
83
+ useEffect(() => {
84
+ clearAutocompletionsFromEditor(editor);
85
+ if (currentAutocompleteSuggestion) {
86
+ addAutocompletionsToEditor(
87
+ editor,
88
+ currentAutocompleteSuggestion.text,
89
+ currentAutocompleteSuggestion.point
90
+ );
91
+ }
92
+ }, [currentAutocompleteSuggestion]);
93
+
94
+ const suggestionStyleAugmented: React.CSSProperties = useMemo(() => {
95
+ return {
96
+ fontStyle: "italic",
97
+ color: "gray",
98
+ ...props.suggestionsStyle,
99
+ };
100
+ }, [props.suggestionsStyle]);
101
+
102
+ useAddBrandingCss(suggestionStyleAugmented, props.disableBranding);
103
+
104
+ const renderElementMemoized = useMemo(() => {
105
+ return makeRenderElementFunction(suggestionStyleAugmented);
106
+ }, [suggestionStyleAugmented]);
107
+
108
+ const renderPlaceholderMemoized = useMemo(() => {
109
+ // For some reason slateJS specifies a top value of 0, which makes for strange styling. We override this here.
110
+ const placeholderStyleSlatejsOverrides: React.CSSProperties = {
111
+ top: undefined,
112
+ };
113
+
114
+ const placeholderStyleAugmented: React.CSSProperties = {
115
+ ...placeholderStyleSlatejsOverrides,
116
+ ...props.placeholderStyle,
117
+ };
118
+
119
+ return makeRenderPlaceholderFunction(placeholderStyleAugmented);
120
+ }, [props.placeholderStyle]);
121
+
122
+ // update the editor text, but only when the value changes from outside the component
123
+ useEffect(() => {
124
+ if (props.value === lastKnownFullEditorText) {
125
+ return;
126
+ }
127
+
128
+ setLastKnownFullEditorText(props.value ?? "");
129
+ replaceEditorText(editor, props.value ?? "");
130
+ }, [props.value]);
131
+
132
+ // separate into TextareaHTMLAttributes<HTMLDivElement> and CopilotTextareaProps
133
+ const {
134
+ placeholderStyle,
135
+ value,
136
+ onValueChange,
137
+ autosuggestionsConfig: autosuggestionsConfigFromProps,
138
+ autosuggestionsFunction,
139
+ className,
140
+ onChange,
141
+ onKeyDown,
142
+ ...propsToForward
143
+ } = props;
144
+
145
+ const moddedClassName = (() => {
146
+ const baseClassName = "copilot-textarea";
147
+ const brandingClass = props.disableBranding
148
+ ? "no-branding"
149
+ : "with-branding";
150
+ const defaultTailwindClassName = "bg-white overflow-y-auto resize-y";
151
+ const mergedClassName = twMerge(
152
+ defaultTailwindClassName,
153
+ className ?? ""
154
+ );
155
+ return `${baseClassName} ${brandingClass} ${mergedClassName}`;
156
+ })();
157
+
158
+ usePopulateCopilotTextareaRef(editor, ref);
94
159
 
95
- const renderElementMemoized = useMemo(() => {
96
- return makeRenderElementFunction(suggestionStyleAugmented);
97
- }, [suggestionStyleAugmented]);
160
+ return (
161
+ <Slate
162
+ editor={editor}
163
+ initialValue={initialValue}
164
+ onChange={(value) => {
165
+ const newEditorState = getTextAroundCursor(editor);
98
166
 
99
- const renderPlaceholderMemoized = useMemo(() => {
100
- // For some reason slateJS specifies a top value of 0, which makes for strange styling. We override this here.
101
- const placeholderStyleSlatejsOverrides: React.CSSProperties = {
102
- top: undefined,
103
- };
167
+ const fullEditorText = newEditorState
168
+ ? newEditorState.textBeforeCursor + newEditorState.textAfterCursor
169
+ : getFullEditorTextWithNewlines(editor); // we don't double-parse the editor. When `newEditorState` is null, we didn't parse the editor yet.
104
170
 
105
- const placeholderStyleAugmented: React.CSSProperties = {
106
- ...placeholderStyleSlatejsOverrides,
107
- ...props.placeholderStyle,
108
- };
171
+ setLastKnownFullEditorText(fullEditorText);
172
+ onChangeHandlerForAutocomplete(newEditorState);
109
173
 
110
- return makeRenderPlaceholderFunction(placeholderStyleAugmented);
111
- }, [props.placeholderStyle]);
112
-
113
- // update the editor text, but only when the value changes from outside the component
114
- useEffect(() => {
115
- if (props.value === lastKnownFullEditorText) {
116
- return;
117
- }
118
-
119
- setLastKnownFullEditorText(props.value ?? "");
120
- replaceEditorText(editor, props.value ?? "");
121
- }, [props.value]);
122
-
123
- // separate into TextareaHTMLAttributes<HTMLDivElement> and CopilotTextareaProps
124
- const {
125
- placeholderStyle,
126
- value,
127
- onValueChange,
128
- autosuggestionsConfig: autosuggestionsConfigFromProps,
129
- autosuggestionsFunction,
130
- className,
131
- onChange,
132
- onKeyDown,
133
- ...propsToForward
134
- } = props;
135
-
136
- const moddedClassName = (() => {
137
- const baseClassName = "copilot-textarea";
138
- const brandingClass = props.disableBranding
139
- ? "no-branding"
140
- : "with-branding";
141
- const defaultTailwindClassName = "bg-white overflow-y-auto resize-y";
142
- const mergedClassName = twMerge(defaultTailwindClassName, className ?? "");
143
- return `${baseClassName} ${brandingClass} ${mergedClassName}`;
144
- })();
145
-
146
- return (
147
- // Add the editable component inside the context.
148
- <Slate
149
- editor={editor}
150
- initialValue={initialValue}
151
- onChange={(value) => {
152
- const newEditorState = getTextAroundCursor(editor);
153
-
154
- const fullEditorText = newEditorState
155
- ? newEditorState.textBeforeCursor + newEditorState.textAfterCursor
156
- : getFullEditorTextWithNewlines(editor); // we don't double-parse the editor. When `newEditorState` is null, we didn't parse the editor yet.
157
-
158
- setLastKnownFullEditorText(fullEditorText);
159
- onChangeHandlerForAutocomplete(newEditorState);
160
-
161
- props.onValueChange?.(fullEditorText);
162
- props.onChange?.(makeSemiFakeReactTextAreaEvent(fullEditorText));
163
- }}
164
- >
165
- <Editable
166
- renderElement={renderElementMemoized}
167
- renderPlaceholder={renderPlaceholderMemoized}
168
- onKeyDown={(event) => {
169
- onKeyDownHandlerForAutocomplete(event); // forward the event for internal use
170
- props.onKeyDown?.(event); // forward the event for external use
174
+ props.onValueChange?.(fullEditorText);
175
+ props.onChange?.(makeSemiFakeReactTextAreaEvent(fullEditorText));
171
176
  }}
172
- className={moddedClassName}
173
- {...propsToForward}
174
- />
175
- </Slate>
176
- );
177
- }
177
+ >
178
+ <Editable
179
+ renderElement={renderElementMemoized}
180
+ renderPlaceholder={renderPlaceholderMemoized}
181
+ onKeyDown={(event) => {
182
+ onKeyDownHandlerForAutocomplete(event); // forward the event for internal use
183
+ props.onKeyDown?.(event); // forward the event for external use
184
+ }}
185
+ className={moddedClassName}
186
+ {...propsToForward}
187
+ />
188
+ </Slate>
189
+ );
190
+ }
191
+ );
178
192
 
179
193
  // Consumers of <textarea> expect a `onChange: (React.ChangeEvent<HTMLTextAreaElement>) => void` event handler to be passed in.
180
194
  // This is *extremely* common, and we want to support it.
@@ -4,11 +4,14 @@ export function useAddBrandingCss(
4
4
  suggestionStyleAugmented: React.CSSProperties,
5
5
  disableBranding: boolean | undefined
6
6
  ) {
7
+ const cssSelector = ".copilot-textarea.with-branding";
7
8
  useEffect(() => {
8
9
  if (disableBranding) {
9
10
  return;
10
11
  }
11
12
 
13
+ // ---
14
+ // 1: Add the CSS to the DOM
12
15
  const styleEl = document.createElement("style");
13
16
  styleEl.id = "dynamic-styles";
14
17
 
@@ -36,16 +39,37 @@ export function useAddBrandingCss(
36
39
 
37
40
  // Append it to the ::after class
38
41
  styleEl.innerHTML = `
39
- .copilot-textarea.with-branding::after {
42
+ ${cssSelector}::after {
40
43
  ${dynamicStyles}
41
44
  }
42
45
  `;
43
46
 
44
47
  document.head.appendChild(styleEl);
45
48
 
49
+ // ---
50
+ // 2: Add the scroll listener (to keep the branding in the bottom right as the textarea scrolls)
51
+ const textarea = document.querySelector(cssSelector);
52
+ const handleScroll = () => {
53
+ const styleEl = document.getElementById("dynamic-styles");
54
+ if (styleEl && textarea) {
55
+ const offsetFromBottom = -textarea.scrollTop + 6;
56
+ const offsetFromRight = -textarea.scrollLeft + 6;
57
+ styleEl.innerHTML = `
58
+ ${cssSelector}::after {
59
+ ${dynamicStyles}
60
+ bottom: ${offsetFromBottom}px;
61
+ right: ${offsetFromRight}px;
62
+ }
63
+ `;
64
+ }
65
+ };
66
+
67
+ textarea?.addEventListener("scroll", handleScroll);
68
+
46
69
  // Cleanup
47
70
  return () => {
48
71
  document.getElementById("dynamic-styles")?.remove();
72
+ textarea?.removeEventListener("scroll", handleScroll);
49
73
  };
50
74
  }, [disableBranding, suggestionStyleAugmented]);
51
75
  }
@@ -1,5 +1,7 @@
1
1
  // This example is for an Editor with `ReactEditor` and `HistoryEditor`
2
+ import React from "react";
2
3
  import { useMakeStandardAutosuggestionFunction } from "../../hooks/make-autosuggestions-function/use-make-standard-autosuggestions-function";
4
+ import { HTMLCopilotTextAreaElement } from "../../types";
3
5
  import { BaseCopilotTextareaProps } from "../../types/base/base-copilot-textarea-props";
4
6
  import {
5
7
  AutosuggestionsConfig,
@@ -13,26 +15,34 @@ export interface CopilotTextareaProps extends BaseCopilotTextareaProps {
13
15
  };
14
16
  }
15
17
 
16
- export function CopilotTextarea(props: CopilotTextareaProps): JSX.Element {
17
- const autosuggestionsConfig: AutosuggestionsConfig = {
18
- ...defaultAutosuggestionsConfig,
19
- ...props.autosuggestionsConfig,
20
- };
18
+ export const CopilotTextarea = React.forwardRef(
19
+ (
20
+ props: CopilotTextareaProps,
21
+ ref: React.Ref<HTMLCopilotTextAreaElement>
22
+ ): JSX.Element => {
23
+ const autosuggestionsConfig: AutosuggestionsConfig = {
24
+ ...defaultAutosuggestionsConfig,
25
+ ...props.autosuggestionsConfig,
26
+ };
21
27
 
22
- const autosuggestionsFunction = useMakeStandardAutosuggestionFunction(
23
- autosuggestionsConfig.purposePrompt,
24
- autosuggestionsConfig.apiEndpoint,
25
- autosuggestionsConfig.makeSystemPrompt,
26
- autosuggestionsConfig.fewShotMessages,
27
- autosuggestionsConfig.externalContextCategories,
28
- autosuggestionsConfig.forwardedParams
29
- );
28
+ const autosuggestionsFunction = useMakeStandardAutosuggestionFunction(
29
+ autosuggestionsConfig.purposePrompt,
30
+ autosuggestionsConfig.apiEndpoint,
31
+ autosuggestionsConfig.makeSystemPrompt,
32
+ autosuggestionsConfig.fewShotMessages,
33
+ autosuggestionsConfig.externalContextCategories,
34
+ autosuggestionsConfig.forwardedParams
35
+ );
30
36
 
31
- return (
32
- <BaseCopilotTextarea
33
- {...props}
34
- autosuggestionsConfig={autosuggestionsConfig}
35
- autosuggestionsFunction={autosuggestionsFunction}
36
- />
37
- );
38
- }
37
+ return (
38
+ <>
39
+ <BaseCopilotTextarea
40
+ ref={ref}
41
+ {...props}
42
+ autosuggestionsConfig={autosuggestionsConfig}
43
+ autosuggestionsFunction={autosuggestionsFunction}
44
+ />
45
+ </>
46
+ );
47
+ }
48
+ );
@@ -1,12 +1,12 @@
1
1
  import { useCallback, useMemo, useState } from "react";
2
- import { Debouncer } from "../lib/debouncer";
3
- import { nullableCompatibleEqualityCheck } from "../lib/utils";
4
- import { AutosuggestionsBareFunction } from "../types/base";
5
- import { AutosuggestionState } from "../types/base/autosuggestion-state";
2
+ import { Debouncer } from "../../lib/debouncer";
3
+ import { nullableCompatibleEqualityCheck } from "../../lib/utils";
4
+ import { AutosuggestionsBareFunction } from "../../types/base";
5
+ import { AutosuggestionState } from "../../types/base/autosuggestion-state";
6
6
  import {
7
7
  EditorAutocompleteState,
8
8
  areEqual_autocompleteState,
9
- } from "../types/base/editor-autocomplete-state";
9
+ } from "../../types/base/editor-autocomplete-state";
10
10
 
11
11
  export interface UseAutosuggestionsResult {
12
12
  currentAutocompleteSuggestion: AutosuggestionState | null;
@@ -1,12 +1,12 @@
1
+ import { useMemo } from "react";
1
2
  import { createEditor, Element } from "slate";
2
3
  import { withReact } from "slate-react";
3
- import { useMemo } from "react";
4
4
  import {
5
- withPartialHistory,
6
- ShouldSaveToHistory,
7
5
  defaultShouldSave,
8
- } from "../lib/slatejs-edits/with-partial-history";
9
- import { CustomEditor } from "../types/base/custom-editor";
6
+ ShouldSaveToHistory,
7
+ withPartialHistory,
8
+ } from "../../lib/slatejs-edits/with-partial-history";
9
+ import { CustomEditor } from "../../types/base/custom-editor";
10
10
 
11
11
  const shouldSave: ShouldSaveToHistory = (op, prev) => {
12
12
  const excludedNodeType = "suggestion";
@@ -0,0 +1,101 @@
1
+ import React from "react";
2
+ import { Editor } from "slate";
3
+ import { ReactEditor } from "slate-react";
4
+ import { getFullEditorTextWithNewlines } from "../../lib/get-text-around-cursor";
5
+ import { replaceEditorText } from "../../lib/slatejs-edits/replace-text";
6
+ import { HTMLCopilotTextAreaElement } from "../../types";
7
+ import { CustomEditor } from "../../types/base/custom-editor";
8
+
9
+ export function usePopulateCopilotTextareaRef(
10
+ editor: Editor,
11
+ ref: React.Ref<HTMLCopilotTextAreaElement>
12
+ ) {
13
+ React.useImperativeHandle(
14
+ ref,
15
+ () => {
16
+ class Combined {
17
+ constructor(
18
+ private customMethods: CustomMethods,
19
+ private editorHtmlElement: HTMLElement
20
+ ) {}
21
+
22
+ [key: string]: any;
23
+
24
+ get(target: any, propKey: string): any {
25
+ if (this.isKeyOfCustomMethods(propKey)) {
26
+ const value = this.customMethods[propKey];
27
+ if (typeof value === "function") {
28
+ return value.bind(this.customMethods);
29
+ }
30
+ return value;
31
+ } else if (this.isKeyOfHTMLElement(propKey)) {
32
+ const value = this.editorHtmlElement[propKey];
33
+ if (typeof value === "function") {
34
+ return value.bind(this.editorHtmlElement);
35
+ }
36
+ return value;
37
+ }
38
+ }
39
+
40
+ set(target: any, propKey: string, value: any): boolean {
41
+ if (this.isKeyOfCustomMethods(propKey)) {
42
+ (this.customMethods as any)[propKey] = value;
43
+ } else if (this.isKeyOfHTMLElement(propKey)) {
44
+ (this.editorHtmlElement as any)[propKey] = value;
45
+ } else {
46
+ // Default behavior (optional)
47
+ target[propKey] = value;
48
+ }
49
+ return true;
50
+ }
51
+
52
+ private isKeyOfCustomMethods(key: string): key is keyof CustomMethods {
53
+ return key in this.customMethods;
54
+ }
55
+
56
+ private isKeyOfHTMLElement(key: string): key is keyof HTMLElement {
57
+ return key in this.editorHtmlElement;
58
+ }
59
+ }
60
+
61
+ const handler = {
62
+ get(target: any, propKey: keyof CustomMethods | keyof HTMLElement) {
63
+ return target.get(target, propKey);
64
+ },
65
+ set(
66
+ target: any,
67
+ propKey: keyof CustomMethods | keyof HTMLElement,
68
+ value: any
69
+ ) {
70
+ return target.set(target, propKey, value);
71
+ },
72
+ };
73
+
74
+ class CustomMethods {
75
+ constructor(private editor: CustomEditor) {}
76
+
77
+ focus() {
78
+ ReactEditor.focus(this.editor);
79
+ }
80
+
81
+ blur() {
82
+ ReactEditor.blur(this.editor);
83
+ }
84
+
85
+ get value() {
86
+ return getFullEditorTextWithNewlines(this.editor);
87
+ }
88
+ set value(value: string) {
89
+ replaceEditorText(this.editor, value);
90
+ }
91
+ }
92
+
93
+ const editorHtmlElement = ReactEditor.toDOMNode(editor, editor);
94
+ const customMethods = new CustomMethods(editor);
95
+
96
+ const combined = new Combined(customMethods, editorHtmlElement);
97
+ return new Proxy(combined, handler);
98
+ },
99
+ [editor]
100
+ );
101
+ }
@@ -0,0 +1,5 @@
1
+ export interface HTMLCopilotTextAreaElement extends HTMLElement {
2
+ value: string;
3
+ focus: () => void;
4
+ blur: () => void;
5
+ }
@@ -1,2 +1,3 @@
1
1
  export * from "./base";
2
+ export * from "./html-copilot-textarea-element";
2
3
  export * from "./standard-autosuggestions";
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/hooks/use-copilot-textarea-editor.tsx"],"names":["editor"],"mappings":";;;;;;AAAA,SAAS,cAAc,eAAe;AACtC,SAAS,iBAAiB;AAC1B,SAAS,eAAe;AAQxB,IAAM,aAAkC,CAAC,IAAI,SAAS;AACpD,QAAM,mBAAmB;AAEzB,MACE,GAAG,SAAS,iBACZ,QAAQ,UAAU,GAAG,IAAI,KACzB,GAAG,KAAK,SAAS,kBACjB;AACA,WAAO;AAAA,EACT;AAEA,MACE,GAAG,SAAS,iBACZ,QAAQ,UAAU,GAAG,IAAI,KACzB,GAAG,KAAK,SAAS,kBACjB;AACA,WAAO;AAAA,EACT;AAEA,MACE,GAAG,SAAS,cACZ,UAAU,GAAG,iBACb,GAAG,cAAc,SAAS,kBAC1B;AACA,WAAO;AAAA,EACT;AAEA,MACE,GAAG,QAAQ,cACX,UAAU,GAAG,cACb,GAAG,WAAW,SAAS,kBACvB;AACA,WAAO;AAAA,EACT;AAEA,MACE,GAAG,SAAS,gBACZ,UAAU,GAAG,cACb,GAAG,WAAW,SAAS,kBACvB;AACA,WAAO;AAAA,EACT;AAEA,MACE,GAAG,SAAS,gBACZ,UAAU,GAAG,cACb,GAAG,WAAW,SAAS,kBACvB;AACA,WAAO;AAAA,EACT;AAGA,SAAO,kBAAkB,IAAI,IAAI;AACnC;AAEO,SAAS,2BAAyC;AACvD,QAAM,SAAS,QAAQ,MAAM;AAC3B,UAAMA,UAAS,mBAAmB,UAAU,aAAa,CAAC,GAAG,UAAU;AAEvE,UAAM,EAAE,OAAO,IAAIA;AACnB,IAAAA,QAAO,SAAS,CAAC,YAAY;AAC3B,cAAQ,QAAQ,MAAM;AAAA,QACpB,KAAK;AACH,iBAAO;AAAA,QACT;AACE,iBAAO,OAAO,OAAO;AAAA,MACzB;AAAA,IACF;AAEA,UAAM,EAAE,aAAa,IAAIA;AACzB,IAAAA,QAAO,eAAe,CAAC,YAAY;AACjC,cAAQ,QAAQ,MAAM;AAAA,QACpB,KAAK;AACH,iBAAO;AAAA,QACT;AACE,iBAAO,aAAa,OAAO;AAAA,MAC/B;AAAA,IACF;AAEA,UAAM,EAAE,SAAS,IAAIA;AACrB,IAAAA,QAAO,WAAW,CAAC,YAAY;AAC7B,cAAQ,QAAQ,MAAM;AAAA,QACpB,KAAK;AACH,iBAAO,QAAQ;AAAA,QACjB;AACE,iBAAO,SAAS,OAAO;AAAA,MAC3B;AAAA,IACF;AAEA,WAAOA;AAAA,EACT,GAAG,CAAC,CAAC;AAEL,SAAO;AACT","sourcesContent":["import { createEditor, Element } from \"slate\";\nimport { withReact } from \"slate-react\";\nimport { useMemo } from \"react\";\nimport {\n withPartialHistory,\n ShouldSaveToHistory,\n defaultShouldSave,\n} from \"../lib/slatejs-edits/with-partial-history\";\nimport { CustomEditor } from \"../types/base/custom-editor\";\n\nconst shouldSave: ShouldSaveToHistory = (op, prev) => {\n const excludedNodeType = \"suggestion\";\n // Check if the operation involves the suggestion inline node type\n if (\n op.type === \"insert_node\" &&\n Element.isElement(op.node) &&\n op.node.type === excludedNodeType\n ) {\n return false;\n }\n\n if (\n op.type === \"remove_node\" &&\n Element.isElement(op.node) &&\n op.node.type === excludedNodeType\n ) {\n return false;\n }\n\n if (\n op.type === \"set_node\" &&\n \"type\" in op.newProperties &&\n op.newProperties.type === excludedNodeType\n ) {\n return false;\n }\n\n if (\n op.type == \"set_node\" &&\n \"type\" in op.properties &&\n op.properties.type === excludedNodeType\n ) {\n return false;\n }\n\n if (\n op.type === \"merge_node\" &&\n \"type\" in op.properties &&\n op.properties.type === excludedNodeType\n ) {\n return false;\n }\n\n if (\n op.type === \"split_node\" &&\n \"type\" in op.properties &&\n op.properties.type === excludedNodeType\n ) {\n return false;\n }\n\n // Otherwise, save the operation to history\n return defaultShouldSave(op, prev);\n};\n\nexport function useCopilotTextareaEditor(): CustomEditor {\n const editor = useMemo(() => {\n const editor = withPartialHistory(withReact(createEditor()), shouldSave);\n\n const { isVoid } = editor;\n editor.isVoid = (element) => {\n switch (element.type) {\n case \"suggestion\":\n return true;\n default:\n return isVoid(element);\n }\n };\n\n const { markableVoid } = editor;\n editor.markableVoid = (element) => {\n switch (element.type) {\n case \"suggestion\":\n return true;\n default:\n return markableVoid(element);\n }\n };\n\n const { isInline } = editor;\n editor.isInline = (element) => {\n switch (element.type) {\n case \"suggestion\":\n return element.inline;\n default:\n return isInline(element);\n }\n };\n\n return editor;\n }, []);\n\n return editor;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/hooks/use-autosuggestions.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,SAAS,aAAa,SAAS,gBAAgB;AAgBxC,SAAS,mBACd,cACA,yBACA,wBACA,8BACA,kBACA,UAC0B;AAC1B,QAAM,CAAC,2BAA2B,4BAA4B,IAC5D,SAAyC,IAAI;AAE/C,QAAM,CAAC,+BAA+B,gCAAgC,IACpE,SAAqC,IAAI;AAE3C,QAAM,8BAGe;AAAA,IACnB,CACE,yBACA,gBACG;AAEH,UAAI,UAAU;AACZ;AAAA,MACF;AAEA,UACE,oBACA,wBAAwB,qBAAqB,MAC7C,wBAAwB,oBAAoB,IAC5C;AACA;AAAA,MACF;AAGA,YAAM,aAAa,MAAM;AAAA,QACvB,wBAAwB;AAAA,QACxB,wBAAwB;AAAA,QACxB;AAAA,MACF;AAGA,UAAI,CAAC,cAAc,YAAY,SAAS;AACtC,cAAM,IAAI,aAAa,WAAW,YAAY;AAAA,MAChD;AAEA,uCAAiC;AAAA,QAC/B,MAAM;AAAA,QACN,OAAO,wBAAwB;AAAA,MACjC,CAAC;AAAA,IACH;AAAA,IACA;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,QAAM,oBAAoB;AAAA,IACxB,MACE,IAAI;AAAA,MACF;AAAA,IACF;AAAA,IACF,CAAC,YAAY;AAAA,EACf;AAEA,QAAM,WAAW;AAAA,IACf,CAAC,mBAAmD;AAClD,YAAM,wBAAwB,CAAC;AAAA,QAC7B;AAAA,QACA;AAAA,QACA;AAAA,MACF;AACA,mCAA6B,cAAc;AAG3C,UAAI,CAAC,uBAAuB;AAC1B;AAAA,MACF;AAGA,uCAAiC,IAAI;AAGrC,UAAI,gBAAgB;AAClB,0BAAkB,SAAS,6BAA6B,cAAc;AAAA,MACxE,OAAO;AACL,0BAAkB,OAAO;AAAA,MAC3B;AAAA,IACF;AAAA,IACA;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,QAAM,iBAAiB;AAAA,IACrB,CAAC,UAA+C;AAC9C,UAAI,+BAA+B;AACjC,YAAI,MAAM,QAAQ,yBAAyB;AACzC,gBAAM,eAAe;AACrB,uCAA6B,6BAA6B;AAC1D,2CAAiC,IAAI;AAAA,QACvC;AAAA,MACF;AAAA,IACF;AAAA,IACA;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA,iBAAiB;AAAA,IACjB,kBAAkB;AAAA,EACpB;AACF","sourcesContent":["import { useCallback, useMemo, useState } from \"react\";\nimport { Debouncer } from \"../lib/debouncer\";\nimport { nullableCompatibleEqualityCheck } from \"../lib/utils\";\nimport { AutosuggestionsBareFunction } from \"../types/base\";\nimport { AutosuggestionState } from \"../types/base/autosuggestion-state\";\nimport {\n EditorAutocompleteState,\n areEqual_autocompleteState,\n} from \"../types/base/editor-autocomplete-state\";\n\nexport interface UseAutosuggestionsResult {\n currentAutocompleteSuggestion: AutosuggestionState | null;\n onChangeHandler: (newEditorState: EditorAutocompleteState | null) => void;\n onKeyDownHandler: (event: React.KeyboardEvent<HTMLDivElement>) => void;\n}\n\nexport function useAutosuggestions(\n debounceTime: number,\n acceptAutosuggestionKey: string,\n autosuggestionFunction: AutosuggestionsBareFunction,\n insertAutocompleteSuggestion: (suggestion: AutosuggestionState) => void,\n disableWhenEmpty: boolean,\n disabled: boolean\n): UseAutosuggestionsResult {\n const [previousAutocompleteState, setPreviousAutocompleteState] =\n useState<EditorAutocompleteState | null>(null);\n\n const [currentAutocompleteSuggestion, setCurrentAutocompleteSuggestion] =\n useState<AutosuggestionState | null>(null);\n\n const awaitForAndAppendSuggestion: (\n editorAutocompleteState: EditorAutocompleteState,\n abortSignal: AbortSignal\n ) => Promise<void> = useCallback(\n async (\n editorAutocompleteState: EditorAutocompleteState,\n abortSignal: AbortSignal\n ) => {\n // early return if disabled\n if (disabled) {\n return;\n }\n\n if (\n disableWhenEmpty &&\n editorAutocompleteState.textBeforeCursor === \"\" &&\n editorAutocompleteState.textAfterCursor === \"\"\n ) {\n return;\n }\n\n // fetch the suggestion\n const suggestion = await autosuggestionFunction(\n editorAutocompleteState.textBeforeCursor,\n editorAutocompleteState.textAfterCursor,\n abortSignal\n );\n\n // We'll assume for now that the autocomplete function might or might not respect the abort signal.\n if (!suggestion || abortSignal.aborted) {\n throw new DOMException(\"Aborted\", \"AbortError\");\n }\n\n setCurrentAutocompleteSuggestion({\n text: suggestion,\n point: editorAutocompleteState.cursorPoint,\n });\n },\n [\n autosuggestionFunction,\n setCurrentAutocompleteSuggestion,\n disableWhenEmpty,\n disabled,\n ]\n );\n\n const debouncedFunction = useMemo(\n () =>\n new Debouncer<[editorAutocompleteState: EditorAutocompleteState]>(\n debounceTime\n ),\n [debounceTime]\n );\n\n const onChange = useCallback(\n (newEditorState: EditorAutocompleteState | null) => {\n const editorStateHasChanged = !nullableCompatibleEqualityCheck(\n areEqual_autocompleteState,\n previousAutocompleteState,\n newEditorState\n );\n setPreviousAutocompleteState(newEditorState);\n\n // if no change, do nothing\n if (!editorStateHasChanged) {\n return;\n }\n\n // if change, then first null out the current suggestion\n setCurrentAutocompleteSuggestion(null);\n\n // then try to get a new suggestion, debouncing to avoid too many requests while typing\n if (newEditorState) {\n debouncedFunction.debounce(awaitForAndAppendSuggestion, newEditorState);\n } else {\n debouncedFunction.cancel();\n }\n },\n [\n previousAutocompleteState,\n setPreviousAutocompleteState,\n debouncedFunction,\n awaitForAndAppendSuggestion,\n setCurrentAutocompleteSuggestion,\n ]\n );\n\n const keyDownHandler = useCallback(\n (event: React.KeyboardEvent<HTMLDivElement>) => {\n if (currentAutocompleteSuggestion) {\n if (event.key === acceptAutosuggestionKey) {\n event.preventDefault();\n insertAutocompleteSuggestion(currentAutocompleteSuggestion);\n setCurrentAutocompleteSuggestion(null);\n }\n }\n },\n [\n currentAutocompleteSuggestion,\n setCurrentAutocompleteSuggestion,\n insertAutocompleteSuggestion,\n acceptAutosuggestionKey,\n ]\n );\n\n return {\n currentAutocompleteSuggestion,\n onChangeHandler: onChange,\n onKeyDownHandler: keyDownHandler,\n };\n}\n"]}
@@ -1,3 +0,0 @@
1
-
2
- //# sourceMappingURL=out.js.map
3
- //# sourceMappingURL=chunk-FD6FGKYY.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/components/base-copilot-textarea/use-add-branding-css.tsx"],"names":[],"mappings":";AAAA,SAAS,iBAAiB;AAEnB,SAAS,kBACd,0BACA,iBACA;AACA,YAAU,MAAM;AACd,QAAI,iBAAiB;AACnB;AAAA,IACF;AAEA,UAAM,UAAU,SAAS,cAAc,OAAO;AAC9C,YAAQ,KAAK;AAGb,QAAI,gBAAgB,OAAO,QAAQ,wBAAwB,EACxD,IAAI,CAAC,CAAC,KAAK,KAAK,MAAM;AACrB,YAAM,eAAe,IAClB,QAAQ,gCAAgC,OAAO,EAC/C,YAAY;AACf,aAAO,GAAG,iBAAiB;AAAA,IAC7B,CAAC,EACA,KAAK,GAAG;AAGX,qBAAiB;AACjB,qBAAiB;AACjB,qBAAiB;AACjB,qBAAiB;AACjB,qBAAiB;AACjB,qBAAiB;AACjB,qBAAiB;AACjB,qBAAiB;AACjB,qBAAiB;AACjB,qBAAiB;AAGjB,YAAQ,YAAY;AAAA;AAAA,UAEd;AAAA;AAAA;AAIN,aAAS,KAAK,YAAY,OAAO;AAGjC,WAAO,MAAM;AA9CjB;AA+CM,qBAAS,eAAe,gBAAgB,MAAxC,mBAA2C;AAAA,IAC7C;AAAA,EACF,GAAG,CAAC,iBAAiB,wBAAwB,CAAC;AAChD","sourcesContent":["import { useEffect } from \"react\";\n\nexport function useAddBrandingCss(\n suggestionStyleAugmented: React.CSSProperties,\n disableBranding: boolean | undefined\n) {\n useEffect(() => {\n if (disableBranding) {\n return;\n }\n\n const styleEl = document.createElement(\"style\");\n styleEl.id = \"dynamic-styles\";\n\n // Build the CSS string dynamically\n let dynamicStyles = Object.entries(suggestionStyleAugmented)\n .map(([key, value]) => {\n const kebabCaseKey = key\n .replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, \"$1-$2\")\n .toLowerCase();\n return `${kebabCaseKey}: ${value};`;\n })\n .join(\" \");\n\n // Append overrides for italics and font-size\n dynamicStyles += `font-style: normal; font-size: x-small;`;\n dynamicStyles += `content: \"CopilotKit\";`;\n dynamicStyles += `bottom: 6px;`;\n dynamicStyles += `right: 6px;`;\n dynamicStyles += `pointer-events: none;`;\n dynamicStyles += `font-weight: 200;`;\n dynamicStyles += `padding: 0;`;\n dynamicStyles += `margin: 0;`;\n dynamicStyles += `border: 0;`;\n dynamicStyles += `line-height: 1;`;\n\n // Append it to the ::after class\n styleEl.innerHTML = `\n .copilot-textarea.with-branding::after {\n ${dynamicStyles}\n }\n `;\n\n document.head.appendChild(styleEl);\n\n // Cleanup\n return () => {\n document.getElementById(\"dynamic-styles\")?.remove();\n };\n }, [disableBranding, suggestionStyleAugmented]);\n}\n"]}