@copilotkit/react-textarea 0.35.0-function-calling-fixes.2 → 0.35.0-mme-cloud.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 (117) hide show
  1. package/.turbo/turbo-build.log +428 -432
  2. package/CHANGELOG.md +4 -28
  3. package/dist/{chunk-VPEH6V7T.mjs → chunk-FMQG2ZM3.mjs} +1 -1
  4. package/dist/chunk-FMQG2ZM3.mjs.map +1 -0
  5. package/dist/{chunk-SP5HFO3H.mjs → chunk-HWM2CVKO.mjs} +2 -2
  6. package/dist/{chunk-22TYLEZZ.mjs → chunk-XU5Z5BWV.mjs} +2 -2
  7. package/dist/components/base-copilot-textarea/base-copilot-textarea.js.map +1 -1
  8. package/dist/components/base-copilot-textarea/base-copilot-textarea.mjs +36 -1752
  9. package/dist/components/base-copilot-textarea/base-copilot-textarea.mjs.map +1 -1
  10. package/dist/components/base-copilot-textarea/render-element.mjs +4 -48
  11. package/dist/components/base-copilot-textarea/render-element.mjs.map +1 -1
  12. package/dist/components/base-copilot-textarea/render-placeholder.mjs +4 -46
  13. package/dist/components/base-copilot-textarea/render-placeholder.mjs.map +1 -1
  14. package/dist/components/base-copilot-textarea/track-cursor-moved-since-last-text-change.mjs +5 -83
  15. package/dist/components/base-copilot-textarea/track-cursor-moved-since-last-text-change.mjs.map +1 -1
  16. package/dist/components/base-copilot-textarea/use-add-branding-css.mjs +4 -54
  17. package/dist/components/base-copilot-textarea/use-add-branding-css.mjs.map +1 -1
  18. package/dist/components/copilot-textarea/copilot-textarea.js.map +1 -1
  19. package/dist/components/copilot-textarea/copilot-textarea.mjs +45 -2196
  20. package/dist/components/copilot-textarea/copilot-textarea.mjs.map +1 -1
  21. package/dist/components/hovering-toolbar/hovering-editor-provider.mjs +5 -13
  22. package/dist/components/hovering-toolbar/hovering-editor-provider.mjs.map +1 -1
  23. package/dist/components/hovering-toolbar/hovering-toolbar-components.mjs +8 -130
  24. package/dist/components/hovering-toolbar/hovering-toolbar-components.mjs.map +1 -1
  25. package/dist/components/hovering-toolbar/hovering-toolbar.mjs +19 -876
  26. package/dist/components/hovering-toolbar/hovering-toolbar.mjs.map +1 -1
  27. package/dist/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box-core.mjs +14 -569
  28. package/dist/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box-core.mjs.map +1 -1
  29. package/dist/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box.mjs +15 -592
  30. package/dist/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box.mjs.map +1 -1
  31. package/dist/components/hovering-toolbar/text-insertion-prompt-box/included-files-preview.mjs +7 -98
  32. package/dist/components/hovering-toolbar/text-insertion-prompt-box/included-files-preview.mjs.map +1 -1
  33. package/dist/components/hovering-toolbar/text-insertion-prompt-box/index.mjs +16 -592
  34. package/dist/components/hovering-toolbar/text-insertion-prompt-box/index.mjs.map +1 -1
  35. package/dist/components/index.js.map +1 -1
  36. package/dist/components/index.mjs +48 -2196
  37. package/dist/components/index.mjs.map +1 -1
  38. package/dist/components/manual-ui/chip-with-icon.mjs +2 -0
  39. package/dist/components/manual-ui/chip-with-icon.mjs.map +1 -1
  40. package/dist/components/source-search-box/source-search-box.mjs +8 -207
  41. package/dist/components/source-search-box/source-search-box.mjs.map +1 -1
  42. package/dist/components/ui/button.mjs +6 -81
  43. package/dist/components/ui/button.mjs.map +1 -1
  44. package/dist/components/ui/card.mjs +7 -42
  45. package/dist/components/ui/card.mjs.map +1 -1
  46. package/dist/components/ui/command.mjs +14 -232
  47. package/dist/components/ui/command.mjs.map +1 -1
  48. package/dist/components/ui/dialog.mjs +11 -134
  49. package/dist/components/ui/dialog.mjs.map +1 -1
  50. package/dist/components/ui/label.mjs +5 -56
  51. package/dist/components/ui/label.mjs.map +1 -1
  52. package/dist/components/ui/separator.mjs +7 -42
  53. package/dist/components/ui/separator.mjs.map +1 -1
  54. package/dist/components/ui/textarea.mjs +7 -42
  55. package/dist/components/ui/textarea.mjs.map +1 -1
  56. package/dist/context/index.mjs +1 -0
  57. package/dist/hooks/base-copilot-textarea-implementation/use-autosuggestions.mjs +7 -155
  58. package/dist/hooks/base-copilot-textarea-implementation/use-autosuggestions.mjs.map +1 -1
  59. package/dist/hooks/base-copilot-textarea-implementation/use-copilot-textarea-editor.mjs +5 -165
  60. package/dist/hooks/base-copilot-textarea-implementation/use-copilot-textarea-editor.mjs.map +1 -1
  61. package/dist/hooks/base-copilot-textarea-implementation/use-populate-copilot-textarea-ref.js.map +1 -1
  62. package/dist/hooks/base-copilot-textarea-implementation/use-populate-copilot-textarea-ref.mjs +6 -145
  63. package/dist/hooks/base-copilot-textarea-implementation/use-populate-copilot-textarea-ref.mjs.map +1 -1
  64. package/dist/hooks/index.mjs +1 -0
  65. package/dist/hooks/make-autosuggestions-function/use-make-standard-autosuggestions-function.mjs +5 -111
  66. package/dist/hooks/make-autosuggestions-function/use-make-standard-autosuggestions-function.mjs.map +1 -1
  67. package/dist/hooks/make-autosuggestions-function/use-make-standard-insertion-function.mjs +5 -160
  68. package/dist/hooks/make-autosuggestions-function/use-make-standard-insertion-function.mjs.map +1 -1
  69. package/dist/hooks/misc/use-autosize-textarea.mjs +4 -12
  70. package/dist/hooks/misc/use-autosize-textarea.mjs.map +1 -1
  71. package/dist/index.js.map +1 -1
  72. package/dist/index.mjs +56 -2196
  73. package/dist/index.mjs.map +1 -1
  74. package/dist/lib/debouncer.mjs +4 -48
  75. package/dist/lib/debouncer.mjs.map +1 -1
  76. package/dist/lib/editor-to-text.mjs +4 -40
  77. package/dist/lib/editor-to-text.mjs.map +1 -1
  78. package/dist/lib/get-text-around-cursor.mjs +7 -96
  79. package/dist/lib/get-text-around-cursor.mjs.map +1 -1
  80. package/dist/lib/retry.mjs +4 -14
  81. package/dist/lib/retry.mjs.map +1 -1
  82. package/dist/lib/slatejs-edits/add-autocompletions.mjs +4 -22
  83. package/dist/lib/slatejs-edits/add-autocompletions.mjs.map +1 -1
  84. package/dist/lib/slatejs-edits/clear-autocompletions.mjs +4 -17
  85. package/dist/lib/slatejs-edits/clear-autocompletions.mjs.map +1 -1
  86. package/dist/lib/slatejs-edits/replace-text.mjs +4 -24
  87. package/dist/lib/slatejs-edits/replace-text.mjs.map +1 -1
  88. package/dist/lib/slatejs-edits/with-partial-history.mjs +5 -102
  89. package/dist/lib/slatejs-edits/with-partial-history.mjs.map +1 -1
  90. package/dist/lib/stream-promise-flatten.mjs +4 -44
  91. package/dist/lib/stream-promise-flatten.mjs.map +1 -1
  92. package/dist/lib/utils.mjs +9 -63
  93. package/dist/lib/utils.mjs.map +1 -1
  94. package/dist/types/autosuggestions-config/autosuggestions-config.mjs +9 -271
  95. package/dist/types/autosuggestions-config/autosuggestions-config.mjs.map +1 -1
  96. package/dist/types/autosuggestions-config/editing-api-config.mjs +6 -82
  97. package/dist/types/autosuggestions-config/editing-api-config.mjs.map +1 -1
  98. package/dist/types/autosuggestions-config/index.mjs +10 -271
  99. package/dist/types/autosuggestions-config/index.mjs.map +1 -1
  100. package/dist/types/autosuggestions-config/insertions-api-config.mjs +6 -73
  101. package/dist/types/autosuggestions-config/insertions-api-config.mjs.map +1 -1
  102. package/dist/types/autosuggestions-config/suggestions-api-config.mjs +6 -59
  103. package/dist/types/autosuggestions-config/suggestions-api-config.mjs.map +1 -1
  104. package/dist/types/base/base-autosuggestions-config.mjs +4 -23
  105. package/dist/types/base/base-autosuggestions-config.mjs.map +1 -1
  106. package/dist/types/base/editor-autocomplete-state.mjs +5 -14
  107. package/dist/types/base/editor-autocomplete-state.mjs.map +1 -1
  108. package/dist/types/base/index.mjs +5 -23
  109. package/dist/types/base/index.mjs.map +1 -1
  110. package/dist/types/html-copilot-textarea-element.mjs +1 -0
  111. package/dist/types/index.mjs +14 -271
  112. package/dist/types/index.mjs.map +1 -1
  113. package/package.json +6 -6
  114. package/src/hooks/base-copilot-textarea-implementation/use-populate-copilot-textarea-ref.ts +4 -1
  115. package/dist/chunk-VPEH6V7T.mjs.map +0 -1
  116. /package/dist/{chunk-SP5HFO3H.mjs.map → chunk-HWM2CVKO.mjs.map} +0 -0
  117. /package/dist/{chunk-22TYLEZZ.mjs.map → chunk-XU5Z5BWV.mjs.map} +0 -0
@@ -1,1755 +1,39 @@
1
- var __defProp = Object.defineProperty;
2
- var __defProps = Object.defineProperties;
3
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
- var __spreadValues = (a, b) => {
9
- for (var prop in b || (b = {}))
10
- if (__hasOwnProp.call(b, prop))
11
- __defNormalProp(a, prop, b[prop]);
12
- if (__getOwnPropSymbols)
13
- for (var prop of __getOwnPropSymbols(b)) {
14
- if (__propIsEnum.call(b, prop))
15
- __defNormalProp(a, prop, b[prop]);
16
- }
17
- return a;
18
- };
19
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
- var __objRest = (source, exclude) => {
21
- var target = {};
22
- for (var prop in source)
23
- if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
24
- target[prop] = source[prop];
25
- if (source != null && __getOwnPropSymbols)
26
- for (var prop of __getOwnPropSymbols(source)) {
27
- if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
28
- target[prop] = source[prop];
29
- }
30
- return target;
31
- };
32
- var __async = (__this, __arguments, generator) => {
33
- return new Promise((resolve, reject) => {
34
- var fulfilled = (value) => {
35
- try {
36
- step(generator.next(value));
37
- } catch (e) {
38
- reject(e);
39
- }
40
- };
41
- var rejected = (value) => {
42
- try {
43
- step(generator.throw(value));
44
- } catch (e) {
45
- reject(e);
46
- }
47
- };
48
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
49
- step((generator = generator.apply(__this, __arguments)).next());
50
- });
51
- };
52
-
53
- // src/components/base-copilot-textarea/base-copilot-textarea.tsx
54
- import React6, { useCallback as useCallback3, useEffect as useEffect7, useMemo as useMemo3, useState as useState6 } from "react";
55
- import { Editor as Editor5 } from "slate";
56
- import { Editable, Slate } from "slate-react";
57
- import { twMerge as twMerge2 } from "tailwind-merge";
58
-
59
- // src/hooks/base-copilot-textarea-implementation/use-autosuggestions.ts
60
- import { useCallback, useEffect, useMemo, useState } from "react";
61
-
62
- // src/lib/debouncer.ts
63
- var Debouncer = class {
64
- constructor(wait) {
65
- this.wait = wait;
66
- this.debounce = (func, ...args) => __async(this, null, function* () {
67
- this.cancel();
68
- this.timeoutId = setTimeout(() => __async(this, null, function* () {
69
- try {
70
- this.activeAbortController = new AbortController();
71
- yield func(...args, this.activeAbortController.signal);
72
- this.activeAbortController = void 0;
73
- } catch (error) {
74
- }
75
- }), this.wait);
76
- });
77
- this.cancel = () => {
78
- if (this.activeAbortController) {
79
- this.activeAbortController.abort();
80
- this.activeAbortController = void 0;
81
- }
82
- if (this.timeoutId !== void 0) {
83
- clearTimeout(this.timeoutId);
84
- this.timeoutId = void 0;
85
- }
86
- };
87
- }
88
- };
89
-
90
- // src/lib/utils.ts
91
- import { clsx } from "clsx";
92
- import { customAlphabet } from "nanoid";
93
- import { twMerge } from "tailwind-merge";
94
- function cn(...inputs) {
95
- return twMerge(clsx(inputs));
96
- }
97
- var nanoid = customAlphabet(
98
- "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
99
- 7
100
- );
101
- var arraysAreEqual = (arr1, arr2) => arr1.length === arr2.length && arr1.every((value, index) => value === arr2[index]);
102
- function nullableCompatibleEqualityCheck(naiveEqualityCheck, a, b) {
103
- if (a === null || a === void 0 || b === null || b === void 0) {
104
- return a === b;
105
- }
106
- return naiveEqualityCheck(a, b);
107
- }
108
-
109
- // src/types/base/editor-autocomplete-state.ts
110
- function areEqual_autocompleteState(prev, next) {
111
- return prev.cursorPoint.offset === next.cursorPoint.offset && arraysAreEqual(prev.cursorPoint.path, next.cursorPoint.path) && prev.textBeforeCursor === next.textBeforeCursor && prev.textAfterCursor === next.textAfterCursor;
112
- }
113
-
114
- // src/hooks/base-copilot-textarea-implementation/use-autosuggestions.ts
115
- function useAutosuggestions(debounceTime, shouldAcceptAutosuggestionOnKeyPress, autosuggestionFunction, insertAutocompleteSuggestion, disableWhenEmpty, disabled) {
116
- const [previousAutocompleteState, setPreviousAutocompleteState] = useState(null);
117
- const [currentAutocompleteSuggestion, setCurrentAutocompleteSuggestion] = useState(null);
118
- const awaitForAndAppendSuggestion = useCallback(
119
- (editorAutocompleteState, abortSignal) => __async(this, null, function* () {
120
- if (disabled) {
121
- return;
122
- }
123
- if (disableWhenEmpty && editorAutocompleteState.textBeforeCursor === "" && editorAutocompleteState.textAfterCursor === "") {
124
- return;
125
- }
126
- const suggestion = yield autosuggestionFunction(editorAutocompleteState, abortSignal);
127
- if (!suggestion || abortSignal.aborted) {
128
- throw new DOMException("Aborted", "AbortError");
129
- }
130
- setCurrentAutocompleteSuggestion({
131
- text: suggestion,
132
- point: editorAutocompleteState.cursorPoint
133
- });
134
- }),
135
- [autosuggestionFunction, setCurrentAutocompleteSuggestion, disableWhenEmpty, disabled]
136
- );
137
- const debouncedFunction = useMemo(
138
- () => new Debouncer(debounceTime),
139
- [debounceTime]
140
- );
141
- useEffect(() => {
142
- return () => {
143
- debouncedFunction.cancel();
144
- setCurrentAutocompleteSuggestion(null);
145
- };
146
- }, [debouncedFunction, disabled]);
147
- const onChange = useCallback(
148
- (newEditorState) => {
149
- const editorStateHasChanged = !nullableCompatibleEqualityCheck(
150
- areEqual_autocompleteState,
151
- previousAutocompleteState,
152
- newEditorState
153
- );
154
- setPreviousAutocompleteState(newEditorState);
155
- if (!editorStateHasChanged) {
156
- return;
157
- }
158
- setCurrentAutocompleteSuggestion(null);
159
- if (newEditorState) {
160
- debouncedFunction.debounce(awaitForAndAppendSuggestion, newEditorState);
161
- } else {
162
- debouncedFunction.cancel();
163
- }
164
- },
165
- [
166
- previousAutocompleteState,
167
- setPreviousAutocompleteState,
168
- debouncedFunction,
169
- awaitForAndAppendSuggestion,
170
- setCurrentAutocompleteSuggestion
171
- ]
172
- );
173
- const keyDownHandler = useCallback(
174
- (event) => {
175
- if (currentAutocompleteSuggestion) {
176
- if (shouldAcceptAutosuggestionOnKeyPress(event)) {
177
- event.preventDefault();
178
- insertAutocompleteSuggestion(currentAutocompleteSuggestion);
179
- setCurrentAutocompleteSuggestion(null);
180
- }
181
- }
182
- },
183
- [
184
- currentAutocompleteSuggestion,
185
- setCurrentAutocompleteSuggestion,
186
- insertAutocompleteSuggestion,
187
- shouldAcceptAutosuggestionOnKeyPress
188
- ]
189
- );
190
- return {
191
- currentAutocompleteSuggestion,
192
- onChangeHandler: onChange,
193
- onKeyDownHandler: keyDownHandler
194
- };
195
- }
196
-
197
- // src/hooks/base-copilot-textarea-implementation/use-copilot-textarea-editor.tsx
198
- import { useMemo as useMemo2 } from "react";
199
- import { createEditor, Element } from "slate";
200
- import { withReact } from "slate-react";
201
-
202
- // src/lib/slatejs-edits/with-partial-history.ts
203
- import { Editor, Operation, Path, Transforms } from "slate";
204
- import { HistoryEditor } from "slate-history";
205
- var withPartialHistory = (editor, shouldSave2) => {
206
- const e = editor;
207
- const { apply } = e;
208
- e.history = { undos: [], redos: [] };
209
- e.redo = () => {
210
- const { history } = e;
211
- const { redos } = history;
212
- if (redos.length > 0) {
213
- const batch = redos[redos.length - 1];
214
- if (batch.selectionBefore) {
215
- Transforms.setSelection(e, batch.selectionBefore);
216
- }
217
- HistoryEditor.withoutSaving(e, () => {
218
- Editor.withoutNormalizing(e, () => {
219
- for (const op of batch.operations) {
220
- e.apply(op);
221
- }
222
- });
223
- });
224
- history.redos.pop();
225
- e.writeHistory("undos", batch);
226
- }
227
- };
228
- e.undo = () => {
229
- const { history } = e;
230
- const { undos } = history;
231
- if (undos.length > 0) {
232
- const batch = undos[undos.length - 1];
233
- HistoryEditor.withoutSaving(e, () => {
234
- Editor.withoutNormalizing(e, () => {
235
- const inverseOps = batch.operations.map(Operation.inverse).reverse();
236
- for (const op of inverseOps) {
237
- e.apply(op);
238
- }
239
- if (batch.selectionBefore) {
240
- Transforms.setSelection(e, batch.selectionBefore);
241
- }
242
- });
243
- });
244
- e.writeHistory("redos", batch);
245
- history.undos.pop();
246
- }
247
- };
248
- e.apply = (op) => {
249
- const { operations, history } = e;
250
- const { undos } = history;
251
- const lastBatch = undos[undos.length - 1];
252
- const lastOp = lastBatch && lastBatch.operations[lastBatch.operations.length - 1];
253
- let save = HistoryEditor.isSaving(e);
254
- let merge = HistoryEditor.isMerging(e);
255
- if (save == null) {
256
- save = shouldSave2(op, lastOp);
257
- }
258
- if (save) {
259
- if (merge == null) {
260
- if (lastBatch == null) {
261
- merge = false;
262
- } else if (operations.length !== 0) {
263
- merge = true;
264
- } else {
265
- merge = shouldMerge(op, lastOp);
266
- }
267
- }
268
- if (lastBatch && merge) {
269
- lastBatch.operations.push(op);
270
- } else {
271
- const batch = {
272
- operations: [op],
273
- selectionBefore: e.selection
274
- };
275
- e.writeHistory("undos", batch);
276
- }
277
- while (undos.length > 100) {
278
- undos.shift();
279
- }
280
- history.redos = [];
281
- }
282
- apply(op);
283
- };
284
- e.writeHistory = (stack, batch) => {
285
- e.history[stack].push(batch);
286
- };
287
- return e;
288
- };
289
- var shouldMerge = (op, prev) => {
290
- if (prev && op.type === "insert_text" && prev.type === "insert_text" && op.offset === prev.offset + prev.text.length && Path.equals(op.path, prev.path)) {
291
- return true;
292
- }
293
- if (prev && op.type === "remove_text" && prev.type === "remove_text" && op.offset + op.text.length === prev.offset && Path.equals(op.path, prev.path)) {
294
- return true;
295
- }
296
- return false;
297
- };
298
- var defaultShouldSave = (op, prev) => {
299
- if (op.type === "set_selection") {
300
- return false;
301
- }
302
- return true;
303
- };
304
-
305
- // src/hooks/base-copilot-textarea-implementation/use-copilot-textarea-editor.tsx
306
- var shouldSave = (op, prev) => {
307
- const excludedNodeType = "suggestion";
308
- if (op.type === "insert_node" && Element.isElement(op.node) && op.node.type === excludedNodeType) {
309
- return false;
310
- }
311
- if (op.type === "remove_node" && Element.isElement(op.node) && op.node.type === excludedNodeType) {
312
- return false;
313
- }
314
- if (op.type === "set_node" && "type" in op.newProperties && op.newProperties.type === excludedNodeType) {
315
- return false;
316
- }
317
- if (op.type == "set_node" && "type" in op.properties && op.properties.type === excludedNodeType) {
318
- return false;
319
- }
320
- if (op.type === "merge_node" && "type" in op.properties && op.properties.type === excludedNodeType) {
321
- return false;
322
- }
323
- if (op.type === "split_node" && "type" in op.properties && op.properties.type === excludedNodeType) {
324
- return false;
325
- }
326
- return defaultShouldSave(op, prev);
327
- };
328
- function useCopilotTextareaEditor() {
329
- const editor = useMemo2(() => {
330
- const editor2 = withPartialHistory(withReact(createEditor()), shouldSave);
331
- const { isVoid } = editor2;
332
- editor2.isVoid = (element) => {
333
- switch (element.type) {
334
- case "suggestion":
335
- return true;
336
- default:
337
- return isVoid(element);
338
- }
339
- };
340
- const { markableVoid } = editor2;
341
- editor2.markableVoid = (element) => {
342
- switch (element.type) {
343
- case "suggestion":
344
- return true;
345
- default:
346
- return markableVoid(element);
347
- }
348
- };
349
- const { isInline } = editor2;
350
- editor2.isInline = (element) => {
351
- switch (element.type) {
352
- case "suggestion":
353
- return element.inline;
354
- default:
355
- return isInline(element);
356
- }
357
- };
358
- return editor2;
359
- }, []);
360
- return editor;
361
- }
362
-
363
- // src/hooks/base-copilot-textarea-implementation/use-populate-copilot-textarea-ref.ts
364
- import React from "react";
365
- import { ReactEditor } from "slate-react";
366
-
367
- // src/lib/get-text-around-cursor.ts
368
- import { Editor as Editor2, Path as Path2, Range as Range2, Text, Element as Element2, Point } from "slate";
369
- function getTextAroundCollapsedCursor(editor) {
370
- const { selection } = editor;
371
- if (!selection || !Range2.isCollapsed(selection)) {
372
- return null;
373
- }
374
- const cursorPoint = selection.anchor;
375
- const beforeRange = {
376
- anchor: Editor2.start(editor, []),
377
- focus: cursorPoint
378
- };
379
- const afterRange = {
380
- anchor: cursorPoint,
381
- focus: Editor2.end(editor, [])
382
- };
383
- const before = extractTextWithNewlines(editor, beforeRange);
384
- const after = extractTextWithNewlines(editor, afterRange);
385
- return {
386
- cursorPoint,
387
- textBeforeCursor: before,
388
- textAfterCursor: after
389
- };
390
- }
391
- function getTextAroundSelection(editor) {
392
- const { selection } = editor;
393
- if (!selection) {
394
- return null;
395
- }
396
- const wellOrderedSelection = wellOrderedRange(selection);
397
- const beforeRange = {
398
- anchor: Editor2.start(editor, []),
399
- focus: wellOrderedSelection.anchor
400
- };
401
- const afterRange = {
402
- anchor: wellOrderedSelection.focus,
403
- focus: Editor2.end(editor, [])
404
- };
405
- const before = extractTextWithNewlines(editor, beforeRange);
406
- const after = extractTextWithNewlines(editor, afterRange);
407
- const selectedText = extractTextWithNewlines(editor, wellOrderedSelection);
408
- return {
409
- selection: wellOrderedSelection,
410
- textBeforeCursor: before,
411
- selectedText,
412
- textAfterCursor: after
413
- };
414
- }
415
- function getFullEditorTextWithNewlines(editor) {
416
- const fullDocumentRange = {
417
- anchor: Editor2.start(editor, []),
418
- focus: Editor2.end(editor, [])
419
- };
420
- return extractTextWithNewlines(editor, fullDocumentRange);
421
- }
422
- function extractTextWithNewlines(editor, range) {
423
- const voids = false;
424
- const [start, end] = Range2.edges(range);
425
- let text = "";
426
- let lastBlock = null;
427
- for (const [node, path] of Editor2.nodes(editor, {
428
- at: range,
429
- match: Text.isText,
430
- voids
431
- })) {
432
- let t = node.text;
433
- const [block] = Editor2.above(editor, {
434
- at: path,
435
- match: (n) => Element2.isElement(n) && n.type === "paragraph"
436
- }) || [null];
437
- if (lastBlock !== block && block) {
438
- if (lastBlock) {
439
- text += "\n";
440
- }
441
- lastBlock = block;
442
- }
443
- if (Path2.equals(path, end.path)) {
444
- t = t.slice(0, end.offset);
445
- }
446
- if (Path2.equals(path, start.path)) {
447
- t = t.slice(start.offset);
448
- }
449
- text += t;
450
- }
451
- return text;
452
- }
453
- function wellOrderedRange(range) {
454
- const { anchor, focus } = range;
455
- if (Point.isBefore(anchor, focus)) {
456
- return range;
457
- }
458
- return {
459
- anchor: focus,
460
- focus: anchor
461
- };
462
- }
463
-
464
- // src/lib/slatejs-edits/replace-text.ts
465
- import { Editor as Editor3, Transforms as Transforms2 } from "slate";
466
- function replaceEditorText(editor, newText) {
467
- Transforms2.delete(editor, {
468
- at: {
469
- anchor: Editor3.start(editor, []),
470
- focus: Editor3.end(editor, [])
471
- }
472
- });
473
- if (newText && newText !== "") {
474
- Transforms2.insertNodes(
475
- editor,
476
- [
477
- {
478
- type: "paragraph",
479
- children: [{ text: newText }]
480
- }
481
- ],
482
- {
483
- at: [0]
484
- }
485
- );
486
- }
487
- }
488
-
489
- // src/hooks/base-copilot-textarea-implementation/use-populate-copilot-textarea-ref.ts
490
- function usePopulateCopilotTextareaRef(editor, ref) {
491
- React.useImperativeHandle(
492
- ref,
493
- () => {
494
- class Combined {
495
- constructor(customMethods2, editorHtmlElement2) {
496
- this.customMethods = customMethods2;
497
- this.editorHtmlElement = editorHtmlElement2;
498
- }
499
- get(target, propKey) {
500
- if (this.isKeyOfCustomMethods(propKey)) {
501
- const value = this.customMethods[propKey];
502
- if (typeof value === "function") {
503
- return value.bind(this.customMethods);
504
- }
505
- return value;
506
- } else if (this.isKeyOfHTMLElement(propKey)) {
507
- const value = this.editorHtmlElement[propKey];
508
- if (typeof value === "function") {
509
- return value.bind(this.editorHtmlElement);
510
- }
511
- return value;
512
- }
513
- }
514
- set(target, propKey, value) {
515
- if (this.isKeyOfCustomMethods(propKey)) {
516
- this.customMethods[propKey] = value;
517
- } else if (this.isKeyOfHTMLElement(propKey)) {
518
- this.editorHtmlElement[propKey] = value;
519
- } else {
520
- target[propKey] = value;
521
- }
522
- return true;
523
- }
524
- isKeyOfCustomMethods(key) {
525
- return key in this.customMethods;
526
- }
527
- isKeyOfHTMLElement(key) {
528
- return key in this.editorHtmlElement;
529
- }
530
- }
531
- const handler = {
532
- get(target, propKey) {
533
- return target.get(target, propKey);
534
- },
535
- set(target, propKey, value) {
536
- return target.set(target, propKey, value);
537
- }
538
- };
539
- class CustomMethods {
540
- constructor(editor2) {
541
- this.editor = editor2;
542
- }
543
- focus() {
544
- ReactEditor.focus(this.editor);
545
- }
546
- blur() {
547
- ReactEditor.blur(this.editor);
548
- }
549
- get value() {
550
- return getFullEditorTextWithNewlines(this.editor);
551
- }
552
- set value(value) {
553
- replaceEditorText(this.editor, value);
554
- }
555
- }
556
- const editorHtmlElement = ReactEditor.toDOMNode(editor, editor);
557
- const customMethods = new CustomMethods(editor);
558
- const combined = new Combined(customMethods, editorHtmlElement);
559
- return new Proxy(combined, handler);
560
- },
561
- [editor]
562
- );
563
- }
564
-
565
- // src/lib/slatejs-edits/add-autocompletions.ts
566
- import { Transforms as Transforms3 } from "slate";
567
- function addAutocompletionsToEditor(editor, newSuggestion, point) {
568
- const editorPosition = editor.selection;
569
- Transforms3.insertNodes(
570
- editor,
571
- [
572
- {
573
- type: "suggestion",
574
- inline: true,
575
- content: newSuggestion,
576
- children: [{ text: "" }]
577
- }
578
- ],
579
- {
580
- at: point
581
- }
582
- );
583
- if (editorPosition) {
584
- editor.selection = editorPosition;
585
- }
586
- }
587
-
588
- // src/lib/slatejs-edits/clear-autocompletions.ts
589
- import { Element as Element3, Node as Node2, Transforms as Transforms4 } from "slate";
590
- function clearAutocompletionsFromEditor(editor) {
591
- const paths = [];
592
- for (const [node, path] of Node2.nodes(editor)) {
593
- if (Element3.isElement(node) && node.type === "suggestion") {
594
- paths.push(path);
595
- }
596
- }
597
- for (const path of paths) {
598
- try {
599
- Transforms4.removeNodes(editor, { at: path });
600
- } catch (e) {
601
- console.log("CopilotTextarea.clearAutocompletionsFromEditor: error removing node", e);
602
- }
603
- }
604
- }
605
-
606
- // src/types/base/base-autosuggestions-config.tsx
607
- import { defaultCopilotContextCategories } from "@copilotkit/react-core";
608
- var defaultShouldToggleHoveringEditorOnKeyPress = (event, shortcut) => {
609
- if (event.key === shortcut && event.metaKey) {
610
- return true;
611
- }
612
- return false;
613
- };
614
- var defaultShouldAcceptAutosuggestionOnKeyPress = (event) => {
615
- if (event.key === "Tab") {
616
- return true;
617
- }
618
- return false;
619
- };
620
- var defaultBaseAutosuggestionsConfig = {
621
- debounceTime: 250,
622
- contextCategories: defaultCopilotContextCategories,
623
- disableWhenEmpty: true,
624
- disabled: false,
625
- temporarilyDisableWhenMovingCursorWithoutChangingText: true,
626
- shouldToggleHoveringEditorOnKeyPress: defaultShouldToggleHoveringEditorOnKeyPress,
627
- shouldAcceptAutosuggestionOnKeyPress: defaultShouldAcceptAutosuggestionOnKeyPress
628
- };
629
-
630
- // src/components/hovering-toolbar/hovering-toolbar.tsx
631
- import { useEffect as useEffect4, useRef as useRef2, useState as useState5 } from "react";
632
- import { Transforms as Transforms5 } from "slate";
633
- import { useSlate, useSlateSelection } from "slate-react";
634
-
635
- // src/hooks/misc/use-autosize-textarea.tsx
636
- import { useEffect as useEffect2 } from "react";
637
- var useAutosizeTextArea = (textAreaRef, value) => {
638
- useEffect2(() => {
639
- if (textAreaRef.current !== null) {
640
- textAreaRef.current.style.height = "0px";
641
- const scrollHeight = textAreaRef.current.scrollHeight;
642
- textAreaRef.current.style.height = scrollHeight + "px";
643
- }
644
- }, [textAreaRef, value]);
645
- };
646
- var use_autosize_textarea_default = useAutosizeTextArea;
647
-
648
- // src/components/source-search-box/source-search-box.tsx
649
- import { useState as useState2 } from "react";
650
-
651
- // src/components/ui/command.tsx
652
- import * as React2 from "react";
653
- import { Command as CommandPrimitive } from "cmdk";
654
- import { jsx } from "react/jsx-runtime";
655
- var Command = React2.forwardRef((_a, ref) => {
656
- var _b = _a, { className } = _b, props = __objRest(_b, ["className"]);
657
- return /* @__PURE__ */ jsx(
658
- CommandPrimitive,
659
- __spreadValues({
660
- ref,
661
- className: cn(
662
- "flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",
663
- className
664
- )
665
- }, props)
666
- );
667
- });
668
- Command.displayName = CommandPrimitive.displayName;
669
- var CommandInput = React2.forwardRef((_a, ref) => {
670
- var _b = _a, { className } = _b, props = __objRest(_b, ["className"]);
671
- return /* @__PURE__ */ jsx("div", { className: "flex items-center border-b px-3", "cmdk-input-wrapper": "", children: /* @__PURE__ */ jsx(
672
- CommandPrimitive.Input,
673
- __spreadValues({
674
- ref,
675
- className: cn(
676
- "flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",
677
- className
678
- )
679
- }, props)
680
- ) });
681
- });
682
- CommandInput.displayName = CommandPrimitive.Input.displayName;
683
- var CommandList = React2.forwardRef((_a, ref) => {
684
- var _b = _a, { className } = _b, props = __objRest(_b, ["className"]);
685
- return /* @__PURE__ */ jsx(
686
- CommandPrimitive.List,
687
- __spreadValues({
688
- ref,
689
- className: cn("max-h-[300px] overflow-y-auto overflow-x-hidden pb-2", className)
690
- }, props)
691
- );
692
- });
693
- CommandList.displayName = CommandPrimitive.List.displayName;
694
- var CommandEmpty = React2.forwardRef((props, ref) => /* @__PURE__ */ jsx(CommandPrimitive.Empty, __spreadValues({ ref, className: "py-6 text-center text-sm" }, props)));
695
- CommandEmpty.displayName = CommandPrimitive.Empty.displayName;
696
- var CommandGroup = React2.forwardRef((_a, ref) => {
697
- var _b = _a, { className } = _b, props = __objRest(_b, ["className"]);
698
- return /* @__PURE__ */ jsx(
699
- CommandPrimitive.Group,
700
- __spreadValues({
701
- ref,
702
- className: cn(
703
- "overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",
704
- className
705
- )
706
- }, props)
707
- );
708
- });
709
- CommandGroup.displayName = CommandPrimitive.Group.displayName;
710
- var CommandSeparator = React2.forwardRef((_a, ref) => {
711
- var _b = _a, { className } = _b, props = __objRest(_b, ["className"]);
712
- return /* @__PURE__ */ jsx(
713
- CommandPrimitive.Separator,
714
- __spreadValues({
715
- ref,
716
- className: cn("-mx-1 h-px bg-border", className)
717
- }, props)
718
- );
719
- });
720
- CommandSeparator.displayName = CommandPrimitive.Separator.displayName;
721
- var CommandItem = React2.forwardRef((_a, ref) => {
722
- var _b = _a, { className } = _b, props = __objRest(_b, ["className"]);
723
- return /* @__PURE__ */ jsx(
724
- CommandPrimitive.Item,
725
- __spreadValues({
726
- ref,
727
- className: cn(
728
- "relative flex cursor-default select-none items-center rounded-sm text-sm outline-none aria-selected:bg-accent aria-selected:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
729
- className
730
- )
731
- }, props)
732
- );
733
- });
734
- CommandItem.displayName = CommandPrimitive.Item.displayName;
735
- var CommandShortcut = (_a) => {
736
- var _b = _a, { className } = _b, props = __objRest(_b, ["className"]);
737
- return /* @__PURE__ */ jsx(
738
- "span",
739
- __spreadValues({
740
- className: cn("ml-auto text-xs tracking-widest text-muted-foreground", className)
741
- }, props)
742
- );
743
- };
744
- CommandShortcut.displayName = "CommandShortcut";
745
-
746
- // src/components/source-search-box/source-search-box.tsx
747
- import { jsx as jsx2, jsxs } from "react/jsx-runtime";
748
- function SourceSearchBox(props) {
749
- const [selectedValue, setSelectedValue] = useState2("");
750
- return /* @__PURE__ */ jsxs(
751
- Command,
752
- {
753
- className: "rounded-lg border shadow-md",
754
- value: selectedValue,
755
- onValueChange: (value) => {
756
- setSelectedValue(value);
757
- },
758
- filter: (value, search) => {
759
- if (props.searchTerm === "")
760
- return 1;
761
- if (value.startsWith(props.searchTerm))
762
- return 1;
763
- return 0;
764
- },
765
- children: [
766
- /* @__PURE__ */ jsx2(
767
- CommandInput,
768
- {
769
- value: props.searchTerm,
770
- className: "rounded-t-lg hidden",
771
- placeholder: "Search for a command..."
772
- }
773
- ),
774
- /* @__PURE__ */ jsxs(CommandList, { children: [
775
- /* @__PURE__ */ jsx2(CommandEmpty, { children: "No results found." }),
776
- /* @__PURE__ */ jsx2(CommandGroup, { heading: "Available resources", children: props.suggestedFiles.map((filePointer) => {
777
- return /* @__PURE__ */ jsx2(
778
- CommandItem,
779
- {
780
- value: filePointer.name,
781
- onSelect: (value) => {
782
- props.onSelectedFile(filePointer);
783
- },
784
- children: /* @__PURE__ */ jsxs("div", { className: " px-3 flex flex-row gap-1 items-center", children: [
785
- /* @__PURE__ */ jsx2(Logo, { width: "20px", height: "20px", children: /* @__PURE__ */ jsx2(
786
- "img",
787
- {
788
- src: filePointer.iconImageUri,
789
- alt: filePointer.sourceApplication,
790
- className: "w-full h-full"
791
- }
792
- ) }),
793
- filePointer.name
794
- ] })
795
- },
796
- `word-${filePointer.sourceApplication}.${filePointer.name}`
797
- );
798
- }) }),
799
- /* @__PURE__ */ jsx2(CommandSeparator, {})
800
- ] })
801
- ]
802
- }
803
- );
804
- }
805
- function Logo({
806
- children,
807
- width,
808
- height
809
- }) {
810
- return /* @__PURE__ */ jsx2("div", { className: "flex items-center justify-center", style: { width, height }, children });
811
- }
812
-
813
- // src/components/ui/button.tsx
814
- import * as React3 from "react";
815
- import { Slot } from "@radix-ui/react-slot";
816
- import { cva } from "class-variance-authority";
817
- import { jsx as jsx3 } from "react/jsx-runtime";
818
- var buttonVariants = cva(
819
- "inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
820
- {
821
- variants: {
822
- variant: {
823
- default: "bg-primary text-primary-foreground hover:bg-primary/90",
824
- destructive: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
825
- outline: "border border-input bg-background hover:bg-accent hover:text-accent-foreground",
826
- secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
827
- ghost: "hover:bg-accent hover:text-accent-foreground",
828
- link: "text-primary underline-offset-4 hover:underline"
829
- },
830
- size: {
831
- default: "h-10 px-4 py-2",
832
- sm: "h-9 rounded-md px-3",
833
- lg: "h-11 rounded-md px-8",
834
- icon: "h-10 w-10"
835
- }
836
- },
837
- defaultVariants: {
838
- variant: "default",
839
- size: "default"
840
- }
841
- }
842
- );
843
- var Button = React3.forwardRef(
844
- (_a, ref) => {
845
- var _b = _a, { className, variant, size, asChild = false } = _b, props = __objRest(_b, ["className", "variant", "size", "asChild"]);
846
- const Comp = asChild ? Slot : "button";
847
- return /* @__PURE__ */ jsx3(Comp, __spreadValues({ className: cn(buttonVariants({ variant, size, className })), ref }, props));
848
- }
849
- );
850
- Button.displayName = "Button";
851
-
852
- // src/components/ui/label.tsx
853
- import * as React4 from "react";
854
- import * as LabelPrimitive from "@radix-ui/react-label";
855
- import { cva as cva2 } from "class-variance-authority";
856
- import { jsx as jsx4 } from "react/jsx-runtime";
857
- var labelVariants = cva2(
858
- "text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
859
- );
860
- var Label = React4.forwardRef((_a, ref) => {
861
- var _b = _a, { className } = _b, props = __objRest(_b, ["className"]);
862
- return /* @__PURE__ */ jsx4(LabelPrimitive.Root, __spreadValues({ ref, className: cn(labelVariants(), className) }, props));
863
- });
864
- Label.displayName = LabelPrimitive.Root.displayName;
865
-
866
- // src/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box-core.tsx
867
- import { useCallback as useCallback2, useContext as useContext2, useEffect as useEffect3, useRef, useState as useState4 } from "react";
868
-
869
- // src/lib/stream-promise-flatten.ts
870
- function streamPromiseFlatten(promise) {
871
- return new ReadableStream({
872
- start(controller) {
873
- return __async(this, null, function* () {
874
- try {
875
- const stream = yield promise;
876
- const reader = stream.getReader();
877
- while (true) {
878
- const { done, value } = yield reader.read();
879
- if (done) {
880
- controller.close();
881
- return;
882
- }
883
- controller.enqueue(value);
884
- }
885
- } catch (error) {
886
- controller.error(error);
887
- }
888
- });
889
- }
890
- });
891
- }
892
-
893
- // src/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box-core.tsx
894
- import { CopilotContext } from "@copilotkit/react-core";
895
-
896
- // src/components/hovering-toolbar/text-insertion-prompt-box/included-files-preview.tsx
897
- import Chip from "@mui/material/Chip/Chip.js";
898
- import Avatar from "@mui/material/Avatar/Avatar.js";
899
- import { jsx as jsx5, jsxs as jsxs2 } from "react/jsx-runtime";
900
- var IncludedFilesPreview = ({
901
- includedFiles,
902
- setIncludedFiles
903
- }) => {
904
- return /* @__PURE__ */ jsxs2("div", { className: "flex flex-col gap-2 mt-2", children: [
905
- /* @__PURE__ */ jsx5(Label, { className: "", children: "Included context:" }),
906
- /* @__PURE__ */ jsx5("div", { className: "flex flex-wrap gap-2", children: includedFiles.map((filePointer, index) => {
907
- return /* @__PURE__ */ jsx5(
908
- FileChipPreview,
909
- {
910
- filePointer,
911
- onDelete: () => {
912
- setIncludedFiles((prev) => prev.filter((fp) => fp !== filePointer));
913
- }
914
- },
915
- `file-${filePointer.sourceApplication}.${filePointer.name}`
916
- );
917
- }) })
918
- ] });
919
- };
920
- var FileChipPreview = ({ filePointer, onDelete }) => {
921
- return /* @__PURE__ */ jsx5(
922
- Chip,
923
- {
924
- label: filePointer.name,
925
- onDelete,
926
- avatar: /* @__PURE__ */ jsx5(
927
- Avatar,
928
- {
929
- src: filePointer.iconImageUri,
930
- alt: filePointer.sourceApplication,
931
- sx: { backgroundColor: "transparent" }
932
- }
933
- )
934
- }
935
- );
936
- };
937
-
938
- // src/components/hovering-toolbar/hovering-editor-provider.tsx
939
- import { createContext, useState as useState3, useContext } from "react";
940
- import { jsx as jsx6 } from "react/jsx-runtime";
941
- var HoveringEditorContext = createContext({
942
- isDisplayed: false,
943
- setIsDisplayed: () => {
944
- }
945
- });
946
- var HoveringEditorProvider = ({ children }) => {
947
- const [isDisplayed, setIsDisplayed] = useState3(false);
948
- return /* @__PURE__ */ jsx6(HoveringEditorContext.Provider, { value: { isDisplayed, setIsDisplayed }, children });
949
- };
950
- var useHoveringEditorContext = () => useContext(HoveringEditorContext);
951
-
952
- // src/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box-core.tsx
953
- import { Fragment, jsx as jsx7, jsxs as jsxs3 } from "react/jsx-runtime";
954
- var HoveringInsertionPromptBoxCore = ({
955
- performInsertion,
956
- state,
957
- insertionOrEditingFunction,
958
- contextCategories
959
- }) => {
960
- const { getDocumentsContext } = useContext2(CopilotContext);
961
- const [editSuggestion, setEditSuggestion] = useState4("");
962
- const [suggestionIsLoading, setSuggestionIsLoading] = useState4(false);
963
- const [adjustmentPrompt, setAdjustmentPrompt] = useState4("");
964
- const [generatingSuggestion, setGeneratingSuggestion] = useState4(
965
- null
966
- );
967
- const adjustmentTextAreaRef = useRef(null);
968
- const suggestionTextAreaRef = useRef(null);
969
- const [filePointers, setFilePointers] = useState4([]);
970
- const [suggestedFiles, setSuggestedFiles] = useState4([]);
971
- useEffect3(() => {
972
- setSuggestedFiles(getDocumentsContext(contextCategories));
973
- }, [contextCategories, getDocumentsContext]);
974
- use_autosize_textarea_default(suggestionTextAreaRef, editSuggestion || "");
975
- use_autosize_textarea_default(adjustmentTextAreaRef, adjustmentPrompt || "");
976
- useEffect3(() => {
977
- var _a;
978
- (_a = adjustmentTextAreaRef.current) == null ? void 0 : _a.focus();
979
- }, []);
980
- useEffect3(() => {
981
- if (!generatingSuggestion) {
982
- return;
983
- }
984
- if (generatingSuggestion.locked) {
985
- return;
986
- }
987
- setEditSuggestion("");
988
- const reader = generatingSuggestion.getReader();
989
- const read = () => __async(void 0, null, function* () {
990
- setSuggestionIsLoading(true);
991
- while (true) {
992
- const { done, value } = yield reader.read();
993
- if (done) {
994
- break;
995
- }
996
- setEditSuggestion((prev) => {
997
- const newSuggestion = prev + value;
998
- if (suggestionTextAreaRef.current) {
999
- suggestionTextAreaRef.current.scrollTop = suggestionTextAreaRef.current.scrollHeight;
1000
- }
1001
- return newSuggestion;
1002
- });
1003
- }
1004
- setSuggestionIsLoading(false);
1005
- });
1006
- read();
1007
- return () => {
1008
- const releaseLockIfNotClosed = () => __async(void 0, null, function* () {
1009
- try {
1010
- yield reader.closed;
1011
- } catch (e) {
1012
- reader.releaseLock();
1013
- }
1014
- });
1015
- releaseLockIfNotClosed();
1016
- };
1017
- }, [generatingSuggestion]);
1018
- const beginGeneratingAdjustment = useCallback2(() => __async(void 0, null, function* () {
1019
- if (!adjustmentPrompt.trim()) {
1020
- return;
1021
- }
1022
- let modificationState = state.editorState;
1023
- if (editSuggestion !== "") {
1024
- modificationState.selectedText = editSuggestion;
1025
- }
1026
- const adjustmentSuggestionTextStreamPromise = insertionOrEditingFunction(
1027
- modificationState,
1028
- adjustmentPrompt,
1029
- filePointers,
1030
- new AbortController().signal
1031
- );
1032
- const adjustmentSuggestionTextStream = streamPromiseFlatten(
1033
- adjustmentSuggestionTextStreamPromise
1034
- );
1035
- setGeneratingSuggestion(adjustmentSuggestionTextStream);
1036
- }), [
1037
- adjustmentPrompt,
1038
- editSuggestion,
1039
- state.editorState,
1040
- insertionOrEditingFunction,
1041
- filePointers
1042
- ]);
1043
- const isLoading = suggestionIsLoading;
1044
- const textToEdit = editSuggestion || state.editorState.selectedText;
1045
- const adjustmentLabel = textToEdit === "" ? "Describe the text you want to insert" : "Describe adjustments to the suggested text";
1046
- const placeholder = textToEdit === "" ? "e.g. 'summarize the client's top 3 pain-points from @CallTranscript'" : "e.g. 'make it more formal', 'be more specific', ...";
1047
- const { setIsDisplayed } = useHoveringEditorContext();
1048
- const AdjustmentPromptComponent = /* @__PURE__ */ jsxs3(Fragment, { children: [
1049
- /* @__PURE__ */ jsx7(Label, { className: "", children: adjustmentLabel }),
1050
- /* @__PURE__ */ jsxs3("div", { className: "relative w-full flex items-center", children: [
1051
- /* @__PURE__ */ jsx7(
1052
- "textarea",
1053
- {
1054
- disabled: suggestionIsLoading,
1055
- ref: adjustmentTextAreaRef,
1056
- value: adjustmentPrompt,
1057
- onChange: (e) => setAdjustmentPrompt(e.target.value),
1058
- onKeyDown: (e) => {
1059
- if (e.key === "Enter" && e.shiftKey) {
1060
- e.preventDefault();
1061
- setAdjustmentPrompt(adjustmentPrompt + "\n");
1062
- } else if (e.key === "Enter") {
1063
- e.preventDefault();
1064
- beginGeneratingAdjustment();
1065
- } else if (e.key == "Escape") {
1066
- e.preventDefault();
1067
- setIsDisplayed(false);
1068
- }
1069
- },
1070
- placeholder,
1071
- style: { minHeight: "3rem" },
1072
- className: "w-full bg-slate-100 h-auto h-min-14 text-sm p-2 rounded-md resize-none overflow-visible focus:outline-none focus:ring-0 focus:border-non pr-[3rem]",
1073
- rows: 1
1074
- }
1075
- ),
1076
- /* @__PURE__ */ jsx7(
1077
- "button",
1078
- {
1079
- onClick: beginGeneratingAdjustment,
1080
- className: "absolute right-2 bg-blue-500 text-white w-8 h-8 rounded-full flex items-center justify-center",
1081
- children: /* @__PURE__ */ jsx7("i", { className: "material-icons", children: "arrow_forward" })
1082
- }
1083
- )
1084
- ] })
1085
- ] });
1086
- const SuggestionComponent = /* @__PURE__ */ jsxs3(Fragment, { children: [
1087
- /* @__PURE__ */ jsxs3("div", { className: "flex justify-between items-end w-full", children: [
1088
- /* @__PURE__ */ jsx7(Label, { className: "mt-4", children: "Suggested:" }),
1089
- /* @__PURE__ */ jsx7("div", { className: "ml-auto", children: isLoading && /* @__PURE__ */ jsx7("div", { className: "flex justify-center items-center", children: /* @__PURE__ */ jsx7(
1090
- "div",
1091
- {
1092
- className: "inline-block h-4 w-4 animate-spin rounded-full border-4 border-solid border-current border-r-transparent align-[-0.125em] motion-reduce:animate-[spin_1.5s_linear_infinite]",
1093
- role: "status",
1094
- children: /* @__PURE__ */ jsx7("span", { className: "!absolute !-m-px !h-px !w-px !overflow-hidden !whitespace-nowrap !border-0 !p-0 ![clip:rect(0,0,0,0)]", children: "Loading..." })
1095
- }
1096
- ) }) })
1097
- ] }),
1098
- /* @__PURE__ */ jsx7(
1099
- "textarea",
1100
- {
1101
- ref: suggestionTextAreaRef,
1102
- value: editSuggestion,
1103
- disabled: suggestionIsLoading,
1104
- onChange: (e) => setEditSuggestion(e.target.value),
1105
- className: "w-full text-base p-2 border border-gray-300 rounded-md resize-none bg-green-50",
1106
- style: { overflow: "auto", maxHeight: "10em" }
1107
- }
1108
- )
1109
- ] });
1110
- const SubmitComponent = /* @__PURE__ */ jsx7("div", { className: "flex w-full gap-4 justify-start", children: /* @__PURE__ */ jsxs3(
1111
- Button,
1112
- {
1113
- className: " bg-green-700 text-white",
1114
- onClick: () => {
1115
- performInsertion(editSuggestion);
1116
- },
1117
- children: [
1118
- "Insert ",
1119
- /* @__PURE__ */ jsx7("i", { className: "material-icons", children: "check" })
1120
- ]
1121
- }
1122
- ) });
1123
- const sourceSearchCandidate = adjustmentPrompt.split(" ").pop();
1124
- const sourceSearchWord = (sourceSearchCandidate == null ? void 0 : sourceSearchCandidate.startsWith("@")) ? sourceSearchCandidate.slice(1) : void 0;
1125
- return /* @__PURE__ */ jsxs3("div", { className: "w-full flex flex-col items-start relative gap-2", children: [
1126
- AdjustmentPromptComponent,
1127
- filePointers.length > 0 && /* @__PURE__ */ jsx7(IncludedFilesPreview, { includedFiles: filePointers, setIncludedFiles: setFilePointers }),
1128
- sourceSearchWord !== void 0 && /* @__PURE__ */ jsx7(
1129
- SourceSearchBox,
1130
- {
1131
- searchTerm: sourceSearchWord,
1132
- suggestedFiles,
1133
- onSelectedFile: (filePointer) => {
1134
- var _a;
1135
- setAdjustmentPrompt(adjustmentPrompt.replace(new RegExp(`@${sourceSearchWord}$`), ""));
1136
- setFilePointers((prev) => [...prev, filePointer]);
1137
- (_a = adjustmentTextAreaRef.current) == null ? void 0 : _a.focus();
1138
- }
1139
- }
1140
- ),
1141
- generatingSuggestion ? SuggestionComponent : null,
1142
- generatingSuggestion ? SubmitComponent : null
1143
- ] });
1144
- };
1145
-
1146
- // src/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box.tsx
1147
- import { jsx as jsx8 } from "react/jsx-runtime";
1148
- var HoveringInsertionPromptBox = (props) => {
1149
- return /* @__PURE__ */ jsx8(
1150
- "div",
1151
- {
1152
- className: "flex flex-col justify-center items-center space-y-4 rounded-md border shadow-lg p-4 border-gray- bg-white",
1153
- style: { width: "35rem" },
1154
- children: /* @__PURE__ */ jsx8(
1155
- HoveringInsertionPromptBoxCore,
1156
- {
1157
- state: {
1158
- editorState: props.editorState
1159
- },
1160
- insertionOrEditingFunction: props.apiConfig.insertionOrEditingFunction,
1161
- performInsertion: props.performInsertion,
1162
- contextCategories: props.contextCategories
1163
- }
1164
- )
1165
- }
1166
- );
1167
- };
1168
-
1169
- // src/components/hovering-toolbar/hovering-toolbar-components.tsx
1170
- import { css, cx } from "@emotion/css";
1171
- import React5 from "react";
1172
- import ReactDOM from "react-dom";
1173
- import { jsx as jsx9 } from "react/jsx-runtime";
1174
- var Button2 = React5.forwardRef(
1175
- (_a, ref) => {
1176
- var _b = _a, {
1177
- className,
1178
- active,
1179
- reversed
1180
- } = _b, props = __objRest(_b, [
1181
- "className",
1182
- "active",
1183
- "reversed"
1184
- ]);
1185
- return /* @__PURE__ */ jsx9(
1186
- "span",
1187
- __spreadProps(__spreadValues({}, props), {
1188
- ref,
1189
- className: cx(
1190
- className,
1191
- css`
1192
- cursor: pointer;
1193
- color: ${reversed ? active ? "white" : "#aaa" : active ? "black" : "#ccc"};
1194
- `
1195
- )
1196
- })
1197
- );
1198
- }
1199
- );
1200
- var Icon = React5.forwardRef(
1201
- (_a, ref) => {
1202
- var _b = _a, { className } = _b, props = __objRest(_b, ["className"]);
1203
- return /* @__PURE__ */ jsx9(
1204
- "span",
1205
- __spreadProps(__spreadValues({}, props), {
1206
- ref,
1207
- className: cx(
1208
- "material-icons",
1209
- className,
1210
- css`
1211
- font-size: 18px;
1212
- vertical-align: text-bottom;
1213
- `
1214
- )
1215
- })
1216
- );
1217
- }
1218
- );
1219
- var Menu = React5.forwardRef(
1220
- (_a, ref) => {
1221
- var _b = _a, { className } = _b, props = __objRest(_b, ["className"]);
1222
- return /* @__PURE__ */ jsx9(
1223
- "div",
1224
- __spreadProps(__spreadValues({}, props), {
1225
- "data-test-id": "menu",
1226
- ref,
1227
- className: cx(
1228
- className,
1229
- css`
1230
- & > * {
1231
- display: inline-block;
1232
- }
1233
-
1234
- & > * + * {
1235
- margin-left: 15px;
1236
- }
1237
- `
1238
- )
1239
- })
1240
- );
1241
- }
1242
- );
1243
- var Portal = ({ children }) => {
1244
- return typeof document === "object" ? ReactDOM.createPortal(children, document.body) : null;
1245
- };
1246
- var Toolbar = React5.forwardRef(
1247
- (_a, ref) => {
1248
- var _b = _a, { className } = _b, props = __objRest(_b, ["className"]);
1249
- return /* @__PURE__ */ jsx9(
1250
- Menu,
1251
- __spreadProps(__spreadValues({}, props), {
1252
- ref,
1253
- className: cx(
1254
- className,
1255
- css`
1256
- position: relative;
1257
- padding: 1px 18px 17px;
1258
- margin: 0 -20px;
1259
- border-bottom: 2px solid #eee;
1260
- margin-bottom: 20px;
1261
- `
1262
- )
1263
- })
1264
- );
1265
- }
1266
- );
1267
-
1268
- // src/components/hovering-toolbar/hovering-toolbar.tsx
1269
- import { jsx as jsx10 } from "react/jsx-runtime";
1270
- var HoveringToolbar = (props) => {
1271
- const ref = useRef2(null);
1272
- const editor = useSlate();
1273
- const selection = useSlateSelection();
1274
- const { isDisplayed, setIsDisplayed } = useHoveringEditorContext();
1275
- const [isClient, setIsClient] = useState5(false);
1276
- useEffect4(() => {
1277
- setIsClient(true);
1278
- }, []);
1279
- useEffect4(() => {
1280
- const el = ref.current;
1281
- const { selection: selection2 } = editor;
1282
- if (!el) {
1283
- return;
1284
- }
1285
- if (!selection2) {
1286
- el.removeAttribute("style");
1287
- return;
1288
- }
1289
- const domSelection = window.getSelection();
1290
- if (!domSelection || domSelection.rangeCount === 0) {
1291
- return;
1292
- }
1293
- const domRange = domSelection.getRangeAt(0);
1294
- const rect = domRange.getBoundingClientRect();
1295
- if (rect.top === 0 && rect.left === 0 && rect.width === 0 && rect.height === 0) {
1296
- return;
1297
- }
1298
- const minGapFromEdge = 60;
1299
- const verticalOffsetFromCorner = 35;
1300
- const horizontalOffsetFromCorner = 15;
1301
- let top = rect.top + window.scrollY - el.offsetHeight + verticalOffsetFromCorner;
1302
- if (top < minGapFromEdge) {
1303
- top = rect.bottom + window.scrollY + minGapFromEdge;
1304
- } else if (top + el.offsetHeight > window.innerHeight - minGapFromEdge) {
1305
- top = rect.top + window.scrollY - el.offsetHeight - minGapFromEdge;
1306
- }
1307
- let left = rect.left + window.scrollX - el.offsetWidth / 2 + rect.width / 2 + horizontalOffsetFromCorner;
1308
- if (left < minGapFromEdge) {
1309
- left = minGapFromEdge;
1310
- } else if (left + el.offsetWidth > window.innerWidth - minGapFromEdge) {
1311
- left = window.innerWidth - el.offsetWidth - minGapFromEdge;
1312
- }
1313
- el.style.opacity = "1";
1314
- el.style.top = `${top}px`;
1315
- el.style.left = `${left}px`;
1316
- });
1317
- useEffect4(() => {
1318
- const handleClickOutside = (event) => {
1319
- if (ref.current && !ref.current.contains(event.target)) {
1320
- setIsDisplayed(false);
1321
- }
1322
- };
1323
- document.addEventListener("mousedown", handleClickOutside);
1324
- return () => {
1325
- document.removeEventListener("mousedown", handleClickOutside);
1326
- };
1327
- }, [ref, setIsDisplayed]);
1328
- if (!isClient) {
1329
- return null;
1330
- }
1331
- return /* @__PURE__ */ jsx10(Portal, { children: /* @__PURE__ */ jsx10(
1332
- Menu,
1333
- {
1334
- ref,
1335
- className: props.hoverMenuClassname || "p-2 absolute z-10 top-[-10000px] left-[-10000px] mt-[-6px] opacity-0 transition-opacity duration-700",
1336
- children: isDisplayed && selection && /* @__PURE__ */ jsx10(
1337
- HoveringInsertionPromptBox,
1338
- {
1339
- editorState: editorState(editor, selection),
1340
- apiConfig: props.apiConfig,
1341
- closeWindow: () => {
1342
- setIsDisplayed(false);
1343
- },
1344
- performInsertion: (insertedText) => {
1345
- console.log("inserted text", insertedText);
1346
- Transforms5.delete(editor, { at: selection });
1347
- Transforms5.insertText(editor, insertedText, {
1348
- at: selection
1349
- });
1350
- setIsDisplayed(false);
1351
- },
1352
- contextCategories: props.contextCategories
1353
- }
1354
- )
1355
- }
1356
- ) });
1357
- };
1358
- function editorState(editor, selection) {
1359
- const textAroundCursor = getTextAroundSelection(editor);
1360
- if (textAroundCursor) {
1361
- return textAroundCursor;
1362
- }
1363
- return {
1364
- textBeforeCursor: getFullEditorTextWithNewlines(editor),
1365
- textAfterCursor: "",
1366
- selectedText: ""
1367
- };
1368
- }
1369
-
1370
- // src/components/base-copilot-textarea/render-element.tsx
1371
- import { jsx as jsx11, jsxs as jsxs4 } from "react/jsx-runtime";
1372
- function makeRenderElementFunction(suggestionsStyle) {
1373
- return (props) => {
1374
- switch (props.element.type) {
1375
- case "paragraph":
1376
- return /* @__PURE__ */ jsx11(DefaultElement, __spreadValues({}, props));
1377
- case "suggestion":
1378
- return /* @__PURE__ */ jsx11(SuggestionElement, __spreadProps(__spreadValues({}, props), { suggestionsStyle }));
1379
- }
1380
- };
1381
- }
1382
- var DefaultElement = (props) => {
1383
- return /* @__PURE__ */ jsx11("div", __spreadProps(__spreadValues({}, props.attributes), { children: props.children }));
1384
- };
1385
- var SuggestionElement = (props) => {
1386
- return /* @__PURE__ */ jsxs4(
1387
- "span",
1388
- __spreadProps(__spreadValues({}, props.attributes), {
1389
- style: __spreadValues({}, props.suggestionsStyle),
1390
- contentEditable: false,
1391
- children: [
1392
- props.children,
1393
- props.element.type === "suggestion" && props.element.content
1394
- ]
1395
- })
1396
- );
1397
- };
1398
-
1399
- // src/components/base-copilot-textarea/render-placeholder.tsx
1400
- import { jsx as jsx12 } from "react/jsx-runtime";
1401
- function makeRenderPlaceholderFunction(placeholderStyle) {
1402
- return (props) => {
1403
- const _a = props.attributes, { style } = _a, restAttributes = __objRest(_a, ["style"]);
1404
- return /* @__PURE__ */ jsx12(
1405
- "div",
1406
- __spreadProps(__spreadValues({}, restAttributes), {
1407
- style: __spreadValues(__spreadValues({}, style), placeholderStyle),
1408
- children: props.children
1409
- })
1410
- );
1411
- };
1412
- }
1413
-
1414
- // src/components/base-copilot-textarea/use-add-branding-css.tsx
1415
- import { useEffect as useEffect5 } from "react";
1416
- function useAddBrandingCss(suggestionStyleAugmented, disableBranding) {
1417
- const cssSelector = ".copilot-textarea.with-branding";
1418
- useEffect5(() => {
1419
- if (disableBranding) {
1420
- return;
1421
- }
1422
- const styleEl = document.createElement("style");
1423
- styleEl.id = "dynamic-styles";
1424
- let dynamicStyles = Object.entries(suggestionStyleAugmented).map(([key, value]) => {
1425
- const kebabCaseKey = key.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, "$1-$2").toLowerCase();
1426
- return `${kebabCaseKey}: ${value};`;
1427
- }).join(" ");
1428
- dynamicStyles += `font-style: normal; font-size: x-small;`;
1429
- dynamicStyles += `content: "CopilotKit";`;
1430
- dynamicStyles += `bottom: 6px;`;
1431
- dynamicStyles += `right: 6px;`;
1432
- dynamicStyles += `pointer-events: none;`;
1433
- dynamicStyles += `font-weight: 200;`;
1434
- dynamicStyles += `padding: 0;`;
1435
- dynamicStyles += `margin: 0;`;
1436
- dynamicStyles += `border: 0;`;
1437
- dynamicStyles += `line-height: 1;`;
1438
- dynamicStyles += `position: absolute;`;
1439
- styleEl.innerHTML = `
1440
- ${cssSelector}::after {
1441
- ${dynamicStyles}
1442
- }
1443
- `;
1444
- document.head.appendChild(styleEl);
1445
- const textarea = document.querySelector(cssSelector);
1446
- const handleScroll = () => {
1447
- const styleEl2 = document.getElementById("dynamic-styles");
1448
- if (styleEl2 && textarea) {
1449
- const offsetFromBottom = -textarea.scrollTop + 6;
1450
- const offsetFromRight = -textarea.scrollLeft + 6;
1451
- styleEl2.innerHTML = `
1452
- ${cssSelector}::after {
1453
- ${dynamicStyles}
1454
- bottom: ${offsetFromBottom}px;
1455
- right: ${offsetFromRight}px;
1456
- }
1457
- `;
1458
- }
1459
- };
1460
- textarea == null ? void 0 : textarea.addEventListener("scroll", handleScroll);
1461
- return () => {
1462
- var _a;
1463
- (_a = document.getElementById("dynamic-styles")) == null ? void 0 : _a.remove();
1464
- textarea == null ? void 0 : textarea.removeEventListener("scroll", handleScroll);
1465
- };
1466
- }, [disableBranding, suggestionStyleAugmented]);
1467
- }
1468
-
1469
- // src/components/base-copilot-textarea/track-cursor-moved-since-last-text-change.tsx
1470
- import { useEffect as useEffect6, useRef as useRef3 } from "react";
1471
- import { useSlateSelector } from "slate-react";
1472
- import { Range as Range3 } from "slate";
1473
-
1474
- // src/lib/editor-to-text.ts
1475
- import { Element as Element4 } from "slate";
1476
- function nodeChildrenToTextComponents(editor, nodes) {
1477
- const indeciesOfInlineElements = new Set(
1478
- nodes.map((node, index) => {
1479
- if (Element4.isElement(node) && editor.isInline(node)) {
1480
- return index;
1481
- }
1482
- return -1;
1483
- }).filter((index) => index !== -1)
1484
- );
1485
- const nonIgnorableItems = nodes.filter((node, index) => {
1486
- const isInline = indeciesOfInlineElements.has(index);
1487
- if (isInline) {
1488
- return false;
1489
- }
1490
- const isNeighbourOfInline = indeciesOfInlineElements.has(index - 1) || indeciesOfInlineElements.has(index + 1);
1491
- if (isNeighbourOfInline) {
1492
- return node.text !== "";
1493
- }
1494
- return true;
1495
- });
1496
- return nonIgnorableItems.map((node) => {
1497
- if (Element4.isElement(node)) {
1498
- switch (node.type) {
1499
- case "paragraph":
1500
- return nodeChildrenToTextComponents(editor, node.children);
1501
- case "suggestion":
1502
- return [];
1503
- }
1504
- } else {
1505
- return [node];
1506
- }
1507
- }).reduce((acc, val) => acc.concat(val), []);
1508
- }
1509
- var editorToText = (editor) => {
1510
- const flattened = nodeChildrenToTextComponents(editor, editor.children);
1511
- const text = flattened.map((textComponent) => textComponent.text).join("\n");
1512
- return text;
1513
- };
1514
-
1515
- // src/components/base-copilot-textarea/track-cursor-moved-since-last-text-change.tsx
1516
- import { Fragment as Fragment2, jsx as jsx13 } from "react/jsx-runtime";
1517
- function TrackerTextEditedSinceLastCursorMovement(props) {
1518
- const cursorState = useSlateSelector((state) => ({
1519
- selection: state.selection,
1520
- text: editorToText(state)
1521
- }));
1522
- const previousState = usePrevious(cursorState);
1523
- useEffect6(() => {
1524
- if (!previousState) {
1525
- return;
1526
- }
1527
- if (cursorChangedWithoutTextChanged(previousState, cursorState)) {
1528
- props.setCursorMovedSinceLastTextChange(true);
1529
- }
1530
- }, [props.setCursorMovedSinceLastTextChange, cursorState]);
1531
- return /* @__PURE__ */ jsx13(Fragment2, {});
1532
- }
1533
- var cursorChangedWithoutTextChanged = (prev, next) => {
1534
- const isSelectionChanged = !isSelectionEqual(prev.selection, next.selection);
1535
- const isTextSame = prev.text === next.text;
1536
- return isSelectionChanged && isTextSame;
1537
- };
1538
- var isSelectionEqual = (a, b) => {
1539
- if (!a && !b)
1540
- return true;
1541
- if (!a || !b)
1542
- return false;
1543
- return Range3.equals(a, b);
1544
- };
1545
- function usePrevious(value) {
1546
- const ref = useRef3();
1547
- useEffect6(() => {
1548
- ref.current = value;
1549
- });
1550
- return ref.current;
1551
- }
1552
-
1553
- // src/components/base-copilot-textarea/base-copilot-textarea.tsx
1554
- import { jsx as jsx14, jsxs as jsxs5 } from "react/jsx-runtime";
1555
- var BaseCopilotTextarea = React6.forwardRef(
1556
- (props, ref) => {
1557
- return /* @__PURE__ */ jsx14(HoveringEditorProvider, { children: /* @__PURE__ */ jsx14(BaseCopilotTextareaWithHoveringContext, __spreadProps(__spreadValues({}, props), { ref })) });
1558
- }
1559
- );
1560
- var BaseCopilotTextareaWithHoveringContext = React6.forwardRef(
1561
- (props, ref) => {
1562
- const autosuggestionsConfig = __spreadValues(__spreadValues({}, defaultBaseAutosuggestionsConfig), props.baseAutosuggestionsConfig);
1563
- const valueOnInitialRender = useMemo3(() => {
1564
- var _a2;
1565
- return (_a2 = props.value) != null ? _a2 : "";
1566
- }, []);
1567
- const [lastKnownFullEditorText, setLastKnownFullEditorText] = useState6(valueOnInitialRender);
1568
- const [cursorMovedSinceLastTextChange, setCursorMovedSinceLastTextChange] = useState6(false);
1569
- const initialValue = useMemo3(() => {
1570
- return [
1571
- {
1572
- type: "paragraph",
1573
- children: [{ text: valueOnInitialRender }]
1574
- }
1575
- ];
1576
- }, [valueOnInitialRender]);
1577
- const editor = useCopilotTextareaEditor();
1578
- const { isDisplayed: hoveringEditorIsDisplayed, setIsDisplayed: setHoveringEditorIsDisplayed } = useHoveringEditorContext();
1579
- const insertText = useCallback3(
1580
- (autosuggestion) => {
1581
- Editor5.insertText(editor, autosuggestion.text, {
1582
- at: autosuggestion.point
1583
- });
1584
- },
1585
- [editor]
1586
- );
1587
- const shouldDisableAutosuggestions = (
1588
- // textarea is manually disabled:
1589
- autosuggestionsConfig.disabled || // hovering editor is displayed:
1590
- hoveringEditorIsDisplayed || // the cursor has moved since the last text change AND we are configured to disable autosuggestions in this case:
1591
- cursorMovedSinceLastTextChange && autosuggestionsConfig.temporarilyDisableWhenMovingCursorWithoutChangingText
1592
- );
1593
- const {
1594
- currentAutocompleteSuggestion,
1595
- onChangeHandler: onChangeHandlerForAutocomplete,
1596
- onKeyDownHandler: onKeyDownHandlerForAutocomplete
1597
- } = useAutosuggestions(
1598
- autosuggestionsConfig.debounceTime,
1599
- autosuggestionsConfig.shouldAcceptAutosuggestionOnKeyPress,
1600
- autosuggestionsConfig.apiConfig.autosuggestionsFunction,
1601
- insertText,
1602
- autosuggestionsConfig.disableWhenEmpty,
1603
- shouldDisableAutosuggestions
1604
- );
1605
- const onKeyDownHandlerForHoveringEditor = useCallback3(
1606
- (event) => {
1607
- var _a2;
1608
- if (autosuggestionsConfig.shouldToggleHoveringEditorOnKeyPress(event, (_a2 = props.shortcut) != null ? _a2 : "k")) {
1609
- event.preventDefault();
1610
- setHoveringEditorIsDisplayed(!hoveringEditorIsDisplayed);
1611
- }
1612
- },
1613
- [
1614
- hoveringEditorIsDisplayed,
1615
- setHoveringEditorIsDisplayed,
1616
- autosuggestionsConfig.shouldToggleHoveringEditorOnKeyPress
1617
- ]
1618
- );
1619
- useEffect7(() => {
1620
- clearAutocompletionsFromEditor(editor);
1621
- if (currentAutocompleteSuggestion) {
1622
- addAutocompletionsToEditor(
1623
- editor,
1624
- currentAutocompleteSuggestion.text,
1625
- currentAutocompleteSuggestion.point
1626
- );
1627
- }
1628
- }, [currentAutocompleteSuggestion]);
1629
- const suggestionStyleAugmented = useMemo3(() => {
1630
- return __spreadValues({
1631
- fontStyle: "italic",
1632
- color: "gray"
1633
- }, props.suggestionsStyle);
1634
- }, [props.suggestionsStyle]);
1635
- const renderElementMemoized = useMemo3(() => {
1636
- return makeRenderElementFunction(suggestionStyleAugmented);
1637
- }, [suggestionStyleAugmented]);
1638
- const renderPlaceholderMemoized = useMemo3(() => {
1639
- const placeholderStyleSlatejsOverrides = {
1640
- top: void 0
1641
- };
1642
- const placeholderStyleAugmented = __spreadValues(__spreadValues({}, placeholderStyleSlatejsOverrides), props.placeholderStyle);
1643
- return makeRenderPlaceholderFunction(placeholderStyleAugmented);
1644
- }, [props.placeholderStyle]);
1645
- useEffect7(() => {
1646
- var _a2, _b;
1647
- if (props.value === lastKnownFullEditorText) {
1648
- return;
1649
- }
1650
- setLastKnownFullEditorText((_a2 = props.value) != null ? _a2 : "");
1651
- replaceEditorText(editor, (_b = props.value) != null ? _b : "");
1652
- }, [props.value]);
1653
- const _a = props, {
1654
- placeholderStyle,
1655
- value,
1656
- hoverMenuClassname,
1657
- onValueChange,
1658
- baseAutosuggestionsConfig: autosuggestionsConfigFromProps,
1659
- className,
1660
- onChange,
1661
- onKeyDown,
1662
- disableBranding
1663
- } = _a, propsToForward = __objRest(_a, [
1664
- "placeholderStyle",
1665
- "value",
1666
- "hoverMenuClassname",
1667
- "onValueChange",
1668
- "baseAutosuggestionsConfig",
1669
- "className",
1670
- "onChange",
1671
- "onKeyDown",
1672
- "disableBranding"
1673
- ]);
1674
- useAddBrandingCss(suggestionStyleAugmented, disableBranding);
1675
- usePopulateCopilotTextareaRef(editor, ref);
1676
- const moddedClassName = (() => {
1677
- const baseClassName = "copilot-textarea";
1678
- const brandingClass = disableBranding ? "no-branding" : "with-branding";
1679
- const defaultTailwindClassName = "bg-white overflow-y-auto resize-y";
1680
- const mergedClassName = twMerge2(defaultTailwindClassName, className != null ? className : "");
1681
- return `${baseClassName} ${brandingClass} ${mergedClassName}`;
1682
- })();
1683
- return /* @__PURE__ */ jsxs5(
1684
- Slate,
1685
- {
1686
- editor,
1687
- initialValue,
1688
- onChange: (value2) => {
1689
- var _a2, _b;
1690
- const newEditorState = getTextAroundCollapsedCursor(editor);
1691
- const fullEditorText = newEditorState ? newEditorState.textBeforeCursor + newEditorState.textAfterCursor : getFullEditorTextWithNewlines(editor);
1692
- setLastKnownFullEditorText((prev) => {
1693
- if (prev !== fullEditorText) {
1694
- setCursorMovedSinceLastTextChange(false);
1695
- }
1696
- return fullEditorText;
1697
- });
1698
- onChangeHandlerForAutocomplete(newEditorState);
1699
- (_a2 = props.onValueChange) == null ? void 0 : _a2.call(props, fullEditorText);
1700
- (_b = props.onChange) == null ? void 0 : _b.call(props, makeSemiFakeReactTextAreaEvent(fullEditorText));
1701
- },
1702
- children: [
1703
- /* @__PURE__ */ jsx14(
1704
- TrackerTextEditedSinceLastCursorMovement,
1705
- {
1706
- setCursorMovedSinceLastTextChange
1707
- }
1708
- ),
1709
- /* @__PURE__ */ jsx14(
1710
- HoveringToolbar,
1711
- {
1712
- apiConfig: autosuggestionsConfig.apiConfig,
1713
- contextCategories: autosuggestionsConfig.contextCategories,
1714
- hoverMenuClassname
1715
- }
1716
- ),
1717
- /* @__PURE__ */ jsx14(
1718
- Editable,
1719
- __spreadValues({
1720
- renderElement: renderElementMemoized,
1721
- renderPlaceholder: renderPlaceholderMemoized,
1722
- onKeyDown: (event) => {
1723
- var _a2;
1724
- onKeyDownHandlerForHoveringEditor(event);
1725
- onKeyDownHandlerForAutocomplete(event);
1726
- (_a2 = props.onKeyDown) == null ? void 0 : _a2.call(props, event);
1727
- },
1728
- className: moddedClassName,
1729
- onBlur: (ev) => {
1730
- var _a2;
1731
- (_a2 = props.onBlur) == null ? void 0 : _a2.call(props, ev);
1732
- clearAutocompletionsFromEditor(editor);
1733
- }
1734
- }, propsToForward)
1735
- )
1736
- ]
1737
- }
1738
- );
1739
- }
1740
- );
1741
- function makeSemiFakeReactTextAreaEvent(currentText) {
1742
- return {
1743
- target: {
1744
- value: currentText,
1745
- type: "copilot-textarea"
1746
- },
1747
- currentTarget: {
1748
- value: currentText,
1749
- type: "copilot-textarea"
1750
- }
1751
- };
1752
- }
1
+ import {
2
+ BaseCopilotTextarea
3
+ } from "../../chunk-XU5Z5BWV.mjs";
4
+ import "../../chunk-DRV2FOHZ.mjs";
5
+ import "../../chunk-4NHVQZ67.mjs";
6
+ import "../../chunk-FMQG2ZM3.mjs";
7
+ import "../../chunk-2C7O2EVM.mjs";
8
+ import "../../chunk-GQN2HYFJ.mjs";
9
+ import "../../chunk-5UNJXFUO.mjs";
10
+ import "../../chunk-QKS2IOUH.mjs";
11
+ import "../../chunk-JJLQVT7S.mjs";
12
+ import "../../chunk-LQ2OWQU7.mjs";
13
+ import "../../chunk-7LSRNPNI.mjs";
14
+ import "../../chunk-DMLXXOXD.mjs";
15
+ import "../../chunk-L7VVZH4Q.mjs";
16
+ import "../../chunk-COQISBP2.mjs";
17
+ import "../../chunk-OGLVRSCO.mjs";
18
+ import "../../chunk-YNXNMCDX.mjs";
19
+ import "../../chunk-3PQ7GSFE.mjs";
20
+ import "../../chunk-WFTAAA7R.mjs";
21
+ import "../../chunk-YFK5BFEI.mjs";
22
+ import "../../chunk-LYB4B6MK.mjs";
23
+ import "../../chunk-CF5GISTC.mjs";
24
+ import "../../chunk-4OZR65UB.mjs";
25
+ import "../../chunk-FFSICDS5.mjs";
26
+ import "../../chunk-4HBKWUCT.mjs";
27
+ import "../../chunk-2QDCE7PD.mjs";
28
+ import "../../chunk-7SUZ6CXM.mjs";
29
+ import "../../chunk-WJHSY5T6.mjs";
30
+ import "../../chunk-LCDTIJSD.mjs";
31
+ import "../../chunk-224UKA7C.mjs";
32
+ import "../../chunk-XW3ICO4S.mjs";
33
+ import "../../chunk-DFTV4TST.mjs";
34
+ import "../../chunk-T6MTDQZ7.mjs";
35
+ import "../../chunk-ECR45NSD.mjs";
36
+ import "../../chunk-MRXNTQOX.mjs";
1753
37
  export {
1754
38
  BaseCopilotTextarea
1755
39
  };