@copilotkit/react-textarea 0.28.0-alpha.1 → 0.28.0-alpha.2

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 (189) hide show
  1. package/.turbo/turbo-build.log +301 -152
  2. package/CHANGELOG.md +16 -1
  3. package/dist/{chunk-LQZBI6XD.mjs → chunk-5J3UZV77.mjs} +3 -3
  4. package/dist/chunk-5J3UZV77.mjs.map +1 -0
  5. package/dist/{chunk-YLXEQDMS.mjs → chunk-B6TKVDDY.mjs} +5 -5
  6. package/dist/chunk-B6TKVDDY.mjs.map +1 -0
  7. package/dist/{chunk-HSCZA5TS.mjs → chunk-BBZ7AWOB.mjs} +2 -2
  8. package/dist/chunk-BBZ7AWOB.mjs.map +1 -0
  9. package/dist/{chunk-47L4PLG4.mjs → chunk-LQ2OWQU7.mjs} +1 -1
  10. package/dist/chunk-LQ2OWQU7.mjs.map +1 -0
  11. package/dist/{chunk-XV7MLLXQ.mjs → chunk-LYB4B6MK.mjs} +1 -1
  12. package/dist/chunk-LYB4B6MK.mjs.map +1 -0
  13. package/dist/{chunk-KJNSWCJC.mjs → chunk-QCPS6IYI.mjs} +6 -10
  14. package/dist/chunk-QCPS6IYI.mjs.map +1 -0
  15. package/dist/{chunk-NT3GWKWK.mjs → chunk-RT4UTBH3.mjs} +7 -7
  16. package/dist/chunk-RT4UTBH3.mjs.map +1 -0
  17. package/dist/{chunk-JYWINDWZ.mjs → chunk-SNQEBH5I.mjs} +4 -4
  18. package/dist/{chunk-JYWINDWZ.mjs.map → chunk-SNQEBH5I.mjs.map} +1 -1
  19. package/dist/{chunk-EPBVNDKE.mjs → chunk-SX6NY5FW.mjs} +1 -1
  20. package/dist/chunk-SX6NY5FW.mjs.map +1 -0
  21. package/dist/{chunk-KTTN5H7S.mjs → chunk-VB4VNCIQ.mjs} +6 -4
  22. package/dist/chunk-VB4VNCIQ.mjs.map +1 -0
  23. package/dist/{chunk-OHO4G6DR.mjs → chunk-XW3ICO4S.mjs} +1 -1
  24. package/dist/chunk-XW3ICO4S.mjs.map +1 -0
  25. package/dist/components/base-copilot-textarea/base-copilot-textarea.js +1658 -0
  26. package/dist/components/base-copilot-textarea/base-copilot-textarea.js.map +1 -0
  27. package/dist/components/base-copilot-textarea/base-copilot-textarea.mjs +8 -8
  28. package/dist/components/base-copilot-textarea/render-element.js +53 -0
  29. package/dist/components/base-copilot-textarea/render-element.js.map +1 -0
  30. package/dist/components/base-copilot-textarea/render-placeholder.js +51 -0
  31. package/dist/components/base-copilot-textarea/render-placeholder.js.map +1 -0
  32. package/dist/components/base-copilot-textarea/render-placeholder.mjs +1 -1
  33. package/dist/components/base-copilot-textarea/track-cursor-moved-since-last-text-change.js +85 -0
  34. package/dist/components/base-copilot-textarea/track-cursor-moved-since-last-text-change.js.map +1 -0
  35. package/dist/components/base-copilot-textarea/track-cursor-moved-since-last-text-change.mjs +1 -1
  36. package/dist/components/base-copilot-textarea/use-add-branding-css.js +61 -0
  37. package/dist/components/base-copilot-textarea/use-add-branding-css.js.map +1 -0
  38. package/dist/components/copilot-textarea/copilot-textarea.js +2082 -0
  39. package/dist/components/copilot-textarea/copilot-textarea.js.map +1 -0
  40. package/dist/components/copilot-textarea/copilot-textarea.mjs +11 -11
  41. package/dist/components/hovering-toolbar/hovering-editor-provider.d.ts +2 -2
  42. package/dist/components/hovering-toolbar/hovering-editor-provider.js +21 -0
  43. package/dist/components/hovering-toolbar/hovering-editor-provider.js.map +1 -0
  44. package/dist/components/hovering-toolbar/hovering-editor-provider.mjs +1 -1
  45. package/dist/components/hovering-toolbar/hovering-toolbar-components.js +144 -0
  46. package/dist/components/hovering-toolbar/hovering-toolbar-components.js.map +1 -0
  47. package/dist/components/hovering-toolbar/hovering-toolbar.js +842 -0
  48. package/dist/components/hovering-toolbar/hovering-toolbar.js.map +1 -0
  49. package/dist/components/hovering-toolbar/hovering-toolbar.mjs +5 -5
  50. package/dist/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box-core.d.ts +1 -2
  51. package/dist/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box-core.js +544 -0
  52. package/dist/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box-core.js.map +1 -0
  53. package/dist/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box-core.mjs +2 -2
  54. package/dist/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box.d.ts +1 -2
  55. package/dist/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box.js +564 -0
  56. package/dist/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box.js.map +1 -0
  57. package/dist/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box.mjs +3 -3
  58. package/dist/components/hovering-toolbar/text-insertion-prompt-box/included-files-preview.d.ts +4 -4
  59. package/dist/components/hovering-toolbar/text-insertion-prompt-box/included-files-preview.js +122 -0
  60. package/dist/components/hovering-toolbar/text-insertion-prompt-box/included-files-preview.js.map +1 -0
  61. package/dist/components/hovering-toolbar/text-insertion-prompt-box/included-files-preview.mjs +1 -1
  62. package/dist/components/hovering-toolbar/text-insertion-prompt-box/index.d.ts +0 -1
  63. package/dist/components/hovering-toolbar/text-insertion-prompt-box/index.js +564 -0
  64. package/dist/components/hovering-toolbar/text-insertion-prompt-box/index.js.map +1 -0
  65. package/dist/components/hovering-toolbar/text-insertion-prompt-box/index.mjs +3 -3
  66. package/dist/components/index.js +2083 -0
  67. package/dist/components/index.js.map +1 -0
  68. package/dist/components/index.mjs +11 -11
  69. package/dist/components/manual-ui/chip-with-icon.d.ts +1 -3
  70. package/dist/components/manual-ui/chip-with-icon.js +16 -0
  71. package/dist/components/manual-ui/chip-with-icon.js.map +1 -0
  72. package/dist/components/manual-ui/chip-with-icon.mjs.map +1 -1
  73. package/dist/components/source-search-box/source-search-box.js +213 -0
  74. package/dist/components/source-search-box/source-search-box.js.map +1 -0
  75. package/dist/components/ui/button.js +103 -0
  76. package/dist/components/ui/button.js.map +1 -0
  77. package/dist/components/ui/card.js +124 -0
  78. package/dist/components/ui/card.js.map +1 -0
  79. package/dist/components/ui/command.js +243 -0
  80. package/dist/components/ui/command.js.map +1 -0
  81. package/dist/components/ui/dialog.js +162 -0
  82. package/dist/components/ui/dialog.js.map +1 -0
  83. package/dist/components/ui/label.js +78 -0
  84. package/dist/components/ui/label.js.map +1 -0
  85. package/dist/components/ui/separator.js +86 -0
  86. package/dist/components/ui/separator.js.map +1 -0
  87. package/dist/components/ui/textarea.js +83 -0
  88. package/dist/components/ui/textarea.js.map +1 -0
  89. package/dist/context/index.js +4 -0
  90. package/dist/context/index.js.map +1 -0
  91. package/dist/hooks/base-copilot-textarea-implementation/use-autosuggestions.js +158 -0
  92. package/dist/hooks/base-copilot-textarea-implementation/use-autosuggestions.js.map +1 -0
  93. package/dist/hooks/base-copilot-textarea-implementation/use-copilot-textarea-editor.js +169 -0
  94. package/dist/hooks/base-copilot-textarea-implementation/use-copilot-textarea-editor.js.map +1 -0
  95. package/dist/hooks/base-copilot-textarea-implementation/use-populate-copilot-textarea-ref.js +151 -0
  96. package/dist/hooks/base-copilot-textarea-implementation/use-populate-copilot-textarea-ref.js.map +1 -0
  97. package/dist/hooks/index.js +4 -0
  98. package/dist/hooks/index.js.map +1 -0
  99. package/dist/hooks/make-autosuggestions-function/use-make-standard-autosuggestions-function.js +113 -0
  100. package/dist/hooks/make-autosuggestions-function/use-make-standard-autosuggestions-function.js.map +1 -0
  101. package/dist/hooks/make-autosuggestions-function/use-make-standard-autosuggestions-function.mjs +1 -1
  102. package/dist/hooks/make-autosuggestions-function/use-make-standard-insertion-function.js +162 -0
  103. package/dist/hooks/make-autosuggestions-function/use-make-standard-insertion-function.js.map +1 -0
  104. package/dist/hooks/make-autosuggestions-function/use-make-standard-insertion-function.mjs +1 -1
  105. package/dist/hooks/misc/use-autosize-textarea.js +19 -0
  106. package/dist/hooks/misc/use-autosize-textarea.js.map +1 -0
  107. package/dist/index.js +2085 -0
  108. package/dist/index.js.map +1 -0
  109. package/dist/index.mjs +12 -12
  110. package/dist/lib/debouncer.js +54 -0
  111. package/dist/lib/debouncer.js.map +1 -0
  112. package/dist/lib/editor-to-text.js +47 -0
  113. package/dist/lib/editor-to-text.js.map +1 -0
  114. package/dist/lib/get-text-around-cursor.js +106 -0
  115. package/dist/lib/get-text-around-cursor.js.map +1 -0
  116. package/dist/lib/retry.js +20 -0
  117. package/dist/lib/retry.js.map +1 -0
  118. package/dist/lib/slatejs-edits/add-autocompletions.js +29 -0
  119. package/dist/lib/slatejs-edits/add-autocompletions.js.map +1 -0
  120. package/dist/lib/slatejs-edits/clear-autocompletions.js +24 -0
  121. package/dist/lib/slatejs-edits/clear-autocompletions.js.map +1 -0
  122. package/dist/lib/slatejs-edits/replace-text.js +31 -0
  123. package/dist/lib/slatejs-edits/replace-text.js.map +1 -0
  124. package/dist/lib/slatejs-edits/with-partial-history.js +110 -0
  125. package/dist/lib/slatejs-edits/with-partial-history.js.map +1 -0
  126. package/dist/lib/stream-promise-flatten.js +50 -0
  127. package/dist/lib/stream-promise-flatten.js.map +1 -0
  128. package/dist/lib/utils.js +73 -0
  129. package/dist/lib/utils.js.map +1 -0
  130. package/dist/lib/utils.test.js +10 -0
  131. package/dist/lib/utils.test.js.map +1 -0
  132. package/dist/types/autosuggestions-config/autosuggestions-config-user-specified.js +4 -0
  133. package/dist/types/autosuggestions-config/autosuggestions-config-user-specified.js.map +1 -0
  134. package/dist/types/autosuggestions-config/autosuggestions-config.js +273 -0
  135. package/dist/types/autosuggestions-config/autosuggestions-config.js.map +1 -0
  136. package/dist/types/autosuggestions-config/editing-api-config.js +90 -0
  137. package/dist/types/autosuggestions-config/editing-api-config.js.map +1 -0
  138. package/dist/types/autosuggestions-config/index.js +273 -0
  139. package/dist/types/autosuggestions-config/index.js.map +1 -0
  140. package/dist/types/autosuggestions-config/insertions-api-config.js +81 -0
  141. package/dist/types/autosuggestions-config/insertions-api-config.js.map +1 -0
  142. package/dist/types/autosuggestions-config/subtypes/make-system-prompt.js +4 -0
  143. package/dist/types/autosuggestions-config/subtypes/make-system-prompt.js.map +1 -0
  144. package/dist/types/autosuggestions-config/subtypes/minimal-chat-gpt-message.js +4 -0
  145. package/dist/types/autosuggestions-config/subtypes/minimal-chat-gpt-message.js.map +1 -0
  146. package/dist/types/autosuggestions-config/suggestions-api-config.js +67 -0
  147. package/dist/types/autosuggestions-config/suggestions-api-config.js.map +1 -0
  148. package/dist/types/base/autosuggestion-state.js +4 -0
  149. package/dist/types/base/autosuggestion-state.js.map +1 -0
  150. package/dist/types/base/autosuggestions-bare-function.js +4 -0
  151. package/dist/types/base/autosuggestions-bare-function.js.map +1 -0
  152. package/dist/types/base/base-autosuggestions-config.js +30 -0
  153. package/dist/types/base/base-autosuggestions-config.js.map +1 -0
  154. package/dist/types/base/base-copilot-textarea-props.js +4 -0
  155. package/dist/types/base/base-copilot-textarea-props.js.map +1 -0
  156. package/dist/types/base/custom-editor.js +4 -0
  157. package/dist/types/base/custom-editor.js.map +1 -0
  158. package/dist/types/base/editor-autocomplete-state.js +21 -0
  159. package/dist/types/base/editor-autocomplete-state.js.map +1 -0
  160. package/dist/types/base/index.js +30 -0
  161. package/dist/types/base/index.js.map +1 -0
  162. package/dist/types/html-copilot-textarea-element.js +4 -0
  163. package/dist/types/html-copilot-textarea-element.js.map +1 -0
  164. package/dist/types/index.js +274 -0
  165. package/dist/types/index.js.map +1 -0
  166. package/package.json +8 -7
  167. package/src/components/base-copilot-textarea/base-copilot-textarea.tsx +2 -3
  168. package/src/components/base-copilot-textarea/render-placeholder.tsx +1 -1
  169. package/src/components/base-copilot-textarea/track-cursor-moved-since-last-text-change.tsx +2 -2
  170. package/src/components/copilot-textarea/copilot-textarea.tsx +1 -1
  171. package/src/components/hovering-toolbar/hovering-editor-provider.tsx +2 -2
  172. package/src/components/hovering-toolbar/hovering-toolbar.tsx +4 -5
  173. package/src/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box-core.tsx +10 -5
  174. package/src/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box.tsx +1 -2
  175. package/src/components/hovering-toolbar/text-insertion-prompt-box/included-files-preview.tsx +4 -4
  176. package/src/components/manual-ui/chip-with-icon.tsx +1 -3
  177. package/src/hooks/make-autosuggestions-function/use-make-standard-autosuggestions-function.tsx +10 -11
  178. package/src/hooks/make-autosuggestions-function/use-make-standard-insertion-function.tsx +7 -11
  179. package/tsup.config.ts +1 -2
  180. package/dist/chunk-47L4PLG4.mjs.map +0 -1
  181. package/dist/chunk-EPBVNDKE.mjs.map +0 -1
  182. package/dist/chunk-HSCZA5TS.mjs.map +0 -1
  183. package/dist/chunk-KJNSWCJC.mjs.map +0 -1
  184. package/dist/chunk-KTTN5H7S.mjs.map +0 -1
  185. package/dist/chunk-LQZBI6XD.mjs.map +0 -1
  186. package/dist/chunk-NT3GWKWK.mjs.map +0 -1
  187. package/dist/chunk-OHO4G6DR.mjs.map +0 -1
  188. package/dist/chunk-XV7MLLXQ.mjs.map +0 -1
  189. package/dist/chunk-YLXEQDMS.mjs.map +0 -1
@@ -0,0 +1,2083 @@
1
+ 'use strict';
2
+
3
+ var React2 = require('react');
4
+ var slate = require('slate');
5
+ var slateReact = require('slate-react');
6
+ var tailwindMerge = require('tailwind-merge');
7
+ var clsx = require('clsx');
8
+ var nanoid = require('nanoid');
9
+ var slateHistory = require('slate-history');
10
+ var reactCore = require('@copilotkit/react-core');
11
+ var cmdk = require('cmdk');
12
+ var jsxRuntime = require('react/jsx-runtime');
13
+ var reactSlot = require('@radix-ui/react-slot');
14
+ var classVarianceAuthority = require('class-variance-authority');
15
+ var LabelPrimitive = require('@radix-ui/react-label');
16
+ var Chip = require('@mui/material/Chip/Chip.js');
17
+ var Avatar = require('@mui/material/Avatar/Avatar.js');
18
+ var css = require('@emotion/css');
19
+ var ReactDOM = require('react-dom');
20
+ var merge = require('lodash.merge');
21
+
22
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
23
+
24
+ function _interopNamespace(e) {
25
+ if (e && e.__esModule) return e;
26
+ var n = Object.create(null);
27
+ if (e) {
28
+ Object.keys(e).forEach(function (k) {
29
+ if (k !== 'default') {
30
+ var d = Object.getOwnPropertyDescriptor(e, k);
31
+ Object.defineProperty(n, k, d.get ? d : {
32
+ enumerable: true,
33
+ get: function () { return e[k]; }
34
+ });
35
+ }
36
+ });
37
+ }
38
+ n.default = e;
39
+ return Object.freeze(n);
40
+ }
41
+
42
+ var React2__namespace = /*#__PURE__*/_interopNamespace(React2);
43
+ var LabelPrimitive__namespace = /*#__PURE__*/_interopNamespace(LabelPrimitive);
44
+ var Chip__default = /*#__PURE__*/_interopDefault(Chip);
45
+ var Avatar__default = /*#__PURE__*/_interopDefault(Avatar);
46
+ var ReactDOM__default = /*#__PURE__*/_interopDefault(ReactDOM);
47
+ var merge__default = /*#__PURE__*/_interopDefault(merge);
48
+
49
+ var __defProp = Object.defineProperty;
50
+ var __defProps = Object.defineProperties;
51
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
52
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
53
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
54
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
55
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
56
+ var __spreadValues = (a, b) => {
57
+ for (var prop in b || (b = {}))
58
+ if (__hasOwnProp.call(b, prop))
59
+ __defNormalProp(a, prop, b[prop]);
60
+ if (__getOwnPropSymbols)
61
+ for (var prop of __getOwnPropSymbols(b)) {
62
+ if (__propIsEnum.call(b, prop))
63
+ __defNormalProp(a, prop, b[prop]);
64
+ }
65
+ return a;
66
+ };
67
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
68
+ var __objRest = (source, exclude) => {
69
+ var target = {};
70
+ for (var prop in source)
71
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
72
+ target[prop] = source[prop];
73
+ if (source != null && __getOwnPropSymbols)
74
+ for (var prop of __getOwnPropSymbols(source)) {
75
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
76
+ target[prop] = source[prop];
77
+ }
78
+ return target;
79
+ };
80
+ var __async = (__this, __arguments, generator) => {
81
+ return new Promise((resolve, reject) => {
82
+ var fulfilled = (value) => {
83
+ try {
84
+ step(generator.next(value));
85
+ } catch (e) {
86
+ reject(e);
87
+ }
88
+ };
89
+ var rejected = (value) => {
90
+ try {
91
+ step(generator.throw(value));
92
+ } catch (e) {
93
+ reject(e);
94
+ }
95
+ };
96
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
97
+ step((generator = generator.apply(__this, __arguments)).next());
98
+ });
99
+ };
100
+
101
+ // src/lib/debouncer.ts
102
+ var Debouncer = class {
103
+ constructor(wait) {
104
+ this.wait = wait;
105
+ this.debounce = (func, ...args) => __async(this, null, function* () {
106
+ this.cancel();
107
+ this.timeoutId = setTimeout(() => __async(this, null, function* () {
108
+ try {
109
+ this.activeAbortController = new AbortController();
110
+ yield func(...args, this.activeAbortController.signal);
111
+ this.activeAbortController = void 0;
112
+ } catch (error) {
113
+ }
114
+ }), this.wait);
115
+ });
116
+ this.cancel = () => {
117
+ if (this.activeAbortController) {
118
+ this.activeAbortController.abort();
119
+ this.activeAbortController = void 0;
120
+ }
121
+ if (this.timeoutId !== void 0) {
122
+ clearTimeout(this.timeoutId);
123
+ this.timeoutId = void 0;
124
+ }
125
+ };
126
+ }
127
+ };
128
+ function cn(...inputs) {
129
+ return tailwindMerge.twMerge(clsx.clsx(inputs));
130
+ }
131
+ nanoid.customAlphabet(
132
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
133
+ 7
134
+ );
135
+ var arraysAreEqual = (arr1, arr2) => arr1.length === arr2.length && arr1.every((value, index) => value === arr2[index]);
136
+ function nullableCompatibleEqualityCheck(naiveEqualityCheck, a, b) {
137
+ if (a === null || a === void 0 || b === null || b === void 0) {
138
+ return a === b;
139
+ }
140
+ return naiveEqualityCheck(a, b);
141
+ }
142
+
143
+ // src/types/base/editor-autocomplete-state.ts
144
+ function areEqual_autocompleteState(prev, next) {
145
+ return prev.cursorPoint.offset === next.cursorPoint.offset && arraysAreEqual(prev.cursorPoint.path, next.cursorPoint.path) && prev.textBeforeCursor === next.textBeforeCursor && prev.textAfterCursor === next.textAfterCursor;
146
+ }
147
+
148
+ // src/hooks/base-copilot-textarea-implementation/use-autosuggestions.ts
149
+ function useAutosuggestions(debounceTime, shouldAcceptAutosuggestionOnKeyPress, autosuggestionFunction, insertAutocompleteSuggestion, disableWhenEmpty, disabled) {
150
+ const [previousAutocompleteState, setPreviousAutocompleteState] = React2.useState(null);
151
+ const [currentAutocompleteSuggestion, setCurrentAutocompleteSuggestion] = React2.useState(null);
152
+ const awaitForAndAppendSuggestion = React2.useCallback(
153
+ (editorAutocompleteState, abortSignal) => __async(this, null, function* () {
154
+ if (disabled) {
155
+ return;
156
+ }
157
+ if (disableWhenEmpty && editorAutocompleteState.textBeforeCursor === "" && editorAutocompleteState.textAfterCursor === "") {
158
+ return;
159
+ }
160
+ const suggestion = yield autosuggestionFunction(editorAutocompleteState, abortSignal);
161
+ if (!suggestion || abortSignal.aborted) {
162
+ throw new DOMException("Aborted", "AbortError");
163
+ }
164
+ setCurrentAutocompleteSuggestion({
165
+ text: suggestion,
166
+ point: editorAutocompleteState.cursorPoint
167
+ });
168
+ }),
169
+ [autosuggestionFunction, setCurrentAutocompleteSuggestion, disableWhenEmpty, disabled]
170
+ );
171
+ const debouncedFunction = React2.useMemo(
172
+ () => new Debouncer(debounceTime),
173
+ [debounceTime]
174
+ );
175
+ React2.useEffect(() => {
176
+ return () => {
177
+ debouncedFunction.cancel();
178
+ setCurrentAutocompleteSuggestion(null);
179
+ };
180
+ }, [debouncedFunction, disabled]);
181
+ const onChange = React2.useCallback(
182
+ (newEditorState) => {
183
+ const editorStateHasChanged = !nullableCompatibleEqualityCheck(
184
+ areEqual_autocompleteState,
185
+ previousAutocompleteState,
186
+ newEditorState
187
+ );
188
+ setPreviousAutocompleteState(newEditorState);
189
+ if (!editorStateHasChanged) {
190
+ return;
191
+ }
192
+ setCurrentAutocompleteSuggestion(null);
193
+ if (newEditorState) {
194
+ debouncedFunction.debounce(awaitForAndAppendSuggestion, newEditorState);
195
+ } else {
196
+ debouncedFunction.cancel();
197
+ }
198
+ },
199
+ [
200
+ previousAutocompleteState,
201
+ setPreviousAutocompleteState,
202
+ debouncedFunction,
203
+ awaitForAndAppendSuggestion,
204
+ setCurrentAutocompleteSuggestion
205
+ ]
206
+ );
207
+ const keyDownHandler = React2.useCallback(
208
+ (event) => {
209
+ if (currentAutocompleteSuggestion) {
210
+ if (shouldAcceptAutosuggestionOnKeyPress(event)) {
211
+ event.preventDefault();
212
+ insertAutocompleteSuggestion(currentAutocompleteSuggestion);
213
+ setCurrentAutocompleteSuggestion(null);
214
+ }
215
+ }
216
+ },
217
+ [
218
+ currentAutocompleteSuggestion,
219
+ setCurrentAutocompleteSuggestion,
220
+ insertAutocompleteSuggestion,
221
+ shouldAcceptAutosuggestionOnKeyPress
222
+ ]
223
+ );
224
+ return {
225
+ currentAutocompleteSuggestion,
226
+ onChangeHandler: onChange,
227
+ onKeyDownHandler: keyDownHandler
228
+ };
229
+ }
230
+ var withPartialHistory = (editor, shouldSave2) => {
231
+ const e = editor;
232
+ const { apply } = e;
233
+ e.history = { undos: [], redos: [] };
234
+ e.redo = () => {
235
+ const { history } = e;
236
+ const { redos } = history;
237
+ if (redos.length > 0) {
238
+ const batch = redos[redos.length - 1];
239
+ if (batch.selectionBefore) {
240
+ slate.Transforms.setSelection(e, batch.selectionBefore);
241
+ }
242
+ slateHistory.HistoryEditor.withoutSaving(e, () => {
243
+ slate.Editor.withoutNormalizing(e, () => {
244
+ for (const op of batch.operations) {
245
+ e.apply(op);
246
+ }
247
+ });
248
+ });
249
+ history.redos.pop();
250
+ e.writeHistory("undos", batch);
251
+ }
252
+ };
253
+ e.undo = () => {
254
+ const { history } = e;
255
+ const { undos } = history;
256
+ if (undos.length > 0) {
257
+ const batch = undos[undos.length - 1];
258
+ slateHistory.HistoryEditor.withoutSaving(e, () => {
259
+ slate.Editor.withoutNormalizing(e, () => {
260
+ const inverseOps = batch.operations.map(slate.Operation.inverse).reverse();
261
+ for (const op of inverseOps) {
262
+ e.apply(op);
263
+ }
264
+ if (batch.selectionBefore) {
265
+ slate.Transforms.setSelection(e, batch.selectionBefore);
266
+ }
267
+ });
268
+ });
269
+ e.writeHistory("redos", batch);
270
+ history.undos.pop();
271
+ }
272
+ };
273
+ e.apply = (op) => {
274
+ const { operations, history } = e;
275
+ const { undos } = history;
276
+ const lastBatch = undos[undos.length - 1];
277
+ const lastOp = lastBatch && lastBatch.operations[lastBatch.operations.length - 1];
278
+ let save = slateHistory.HistoryEditor.isSaving(e);
279
+ let merge2 = slateHistory.HistoryEditor.isMerging(e);
280
+ if (save == null) {
281
+ save = shouldSave2(op, lastOp);
282
+ }
283
+ if (save) {
284
+ if (merge2 == null) {
285
+ if (lastBatch == null) {
286
+ merge2 = false;
287
+ } else if (operations.length !== 0) {
288
+ merge2 = true;
289
+ } else {
290
+ merge2 = shouldMerge(op, lastOp);
291
+ }
292
+ }
293
+ if (lastBatch && merge2) {
294
+ lastBatch.operations.push(op);
295
+ } else {
296
+ const batch = {
297
+ operations: [op],
298
+ selectionBefore: e.selection
299
+ };
300
+ e.writeHistory("undos", batch);
301
+ }
302
+ while (undos.length > 100) {
303
+ undos.shift();
304
+ }
305
+ history.redos = [];
306
+ }
307
+ apply(op);
308
+ };
309
+ e.writeHistory = (stack, batch) => {
310
+ e.history[stack].push(batch);
311
+ };
312
+ return e;
313
+ };
314
+ var shouldMerge = (op, prev) => {
315
+ if (prev && op.type === "insert_text" && prev.type === "insert_text" && op.offset === prev.offset + prev.text.length && slate.Path.equals(op.path, prev.path)) {
316
+ return true;
317
+ }
318
+ if (prev && op.type === "remove_text" && prev.type === "remove_text" && op.offset + op.text.length === prev.offset && slate.Path.equals(op.path, prev.path)) {
319
+ return true;
320
+ }
321
+ return false;
322
+ };
323
+ var defaultShouldSave = (op, prev) => {
324
+ if (op.type === "set_selection") {
325
+ return false;
326
+ }
327
+ return true;
328
+ };
329
+
330
+ // src/hooks/base-copilot-textarea-implementation/use-copilot-textarea-editor.tsx
331
+ var shouldSave = (op, prev) => {
332
+ const excludedNodeType = "suggestion";
333
+ if (op.type === "insert_node" && slate.Element.isElement(op.node) && op.node.type === excludedNodeType) {
334
+ return false;
335
+ }
336
+ if (op.type === "remove_node" && slate.Element.isElement(op.node) && op.node.type === excludedNodeType) {
337
+ return false;
338
+ }
339
+ if (op.type === "set_node" && "type" in op.newProperties && op.newProperties.type === excludedNodeType) {
340
+ return false;
341
+ }
342
+ if (op.type == "set_node" && "type" in op.properties && op.properties.type === excludedNodeType) {
343
+ return false;
344
+ }
345
+ if (op.type === "merge_node" && "type" in op.properties && op.properties.type === excludedNodeType) {
346
+ return false;
347
+ }
348
+ if (op.type === "split_node" && "type" in op.properties && op.properties.type === excludedNodeType) {
349
+ return false;
350
+ }
351
+ return defaultShouldSave(op);
352
+ };
353
+ function useCopilotTextareaEditor() {
354
+ const editor = React2.useMemo(() => {
355
+ const editor2 = withPartialHistory(slateReact.withReact(slate.createEditor()), shouldSave);
356
+ const { isVoid } = editor2;
357
+ editor2.isVoid = (element) => {
358
+ switch (element.type) {
359
+ case "suggestion":
360
+ return true;
361
+ default:
362
+ return isVoid(element);
363
+ }
364
+ };
365
+ const { markableVoid } = editor2;
366
+ editor2.markableVoid = (element) => {
367
+ switch (element.type) {
368
+ case "suggestion":
369
+ return true;
370
+ default:
371
+ return markableVoid(element);
372
+ }
373
+ };
374
+ const { isInline } = editor2;
375
+ editor2.isInline = (element) => {
376
+ switch (element.type) {
377
+ case "suggestion":
378
+ return element.inline;
379
+ default:
380
+ return isInline(element);
381
+ }
382
+ };
383
+ return editor2;
384
+ }, []);
385
+ return editor;
386
+ }
387
+ function getTextAroundCollapsedCursor(editor) {
388
+ const { selection } = editor;
389
+ if (!selection || !slate.Range.isCollapsed(selection)) {
390
+ return null;
391
+ }
392
+ const cursorPoint = selection.anchor;
393
+ const beforeRange = {
394
+ anchor: slate.Editor.start(editor, []),
395
+ focus: cursorPoint
396
+ };
397
+ const afterRange = {
398
+ anchor: cursorPoint,
399
+ focus: slate.Editor.end(editor, [])
400
+ };
401
+ const before = extractTextWithNewlines(editor, beforeRange);
402
+ const after = extractTextWithNewlines(editor, afterRange);
403
+ return {
404
+ cursorPoint,
405
+ textBeforeCursor: before,
406
+ textAfterCursor: after
407
+ };
408
+ }
409
+ function getTextAroundSelection(editor) {
410
+ const { selection } = editor;
411
+ if (!selection) {
412
+ return null;
413
+ }
414
+ const wellOrderedSelection = wellOrderedRange(selection);
415
+ const beforeRange = {
416
+ anchor: slate.Editor.start(editor, []),
417
+ focus: wellOrderedSelection.anchor
418
+ };
419
+ const afterRange = {
420
+ anchor: wellOrderedSelection.focus,
421
+ focus: slate.Editor.end(editor, [])
422
+ };
423
+ const before = extractTextWithNewlines(editor, beforeRange);
424
+ const after = extractTextWithNewlines(editor, afterRange);
425
+ const selectedText = extractTextWithNewlines(editor, wellOrderedSelection);
426
+ return {
427
+ selection: wellOrderedSelection,
428
+ textBeforeCursor: before,
429
+ selectedText,
430
+ textAfterCursor: after
431
+ };
432
+ }
433
+ function getFullEditorTextWithNewlines(editor) {
434
+ const fullDocumentRange = {
435
+ anchor: slate.Editor.start(editor, []),
436
+ focus: slate.Editor.end(editor, [])
437
+ };
438
+ return extractTextWithNewlines(editor, fullDocumentRange);
439
+ }
440
+ function extractTextWithNewlines(editor, range) {
441
+ const voids = false;
442
+ const [start, end] = slate.Range.edges(range);
443
+ let text = "";
444
+ let lastBlock = null;
445
+ for (const [node, path] of slate.Editor.nodes(editor, {
446
+ at: range,
447
+ match: slate.Text.isText,
448
+ voids
449
+ })) {
450
+ let t = node.text;
451
+ const [block] = slate.Editor.above(editor, {
452
+ at: path,
453
+ match: (n) => slate.Element.isElement(n) && n.type === "paragraph"
454
+ }) || [null];
455
+ if (lastBlock !== block && block) {
456
+ if (lastBlock) {
457
+ text += "\n";
458
+ }
459
+ lastBlock = block;
460
+ }
461
+ if (slate.Path.equals(path, end.path)) {
462
+ t = t.slice(0, end.offset);
463
+ }
464
+ if (slate.Path.equals(path, start.path)) {
465
+ t = t.slice(start.offset);
466
+ }
467
+ text += t;
468
+ }
469
+ return text;
470
+ }
471
+ function wellOrderedRange(range) {
472
+ const { anchor, focus } = range;
473
+ if (slate.Point.isBefore(anchor, focus)) {
474
+ return range;
475
+ }
476
+ return {
477
+ anchor: focus,
478
+ focus: anchor
479
+ };
480
+ }
481
+ function replaceEditorText(editor, newText) {
482
+ slate.Transforms.delete(editor, {
483
+ at: {
484
+ anchor: slate.Editor.start(editor, []),
485
+ focus: slate.Editor.end(editor, [])
486
+ }
487
+ });
488
+ if (newText && newText !== "") {
489
+ slate.Transforms.insertNodes(
490
+ editor,
491
+ [
492
+ {
493
+ type: "paragraph",
494
+ children: [{ text: newText }]
495
+ }
496
+ ],
497
+ {
498
+ at: [0]
499
+ }
500
+ );
501
+ }
502
+ }
503
+
504
+ // src/hooks/base-copilot-textarea-implementation/use-populate-copilot-textarea-ref.ts
505
+ function usePopulateCopilotTextareaRef(editor, ref) {
506
+ React2__namespace.default.useImperativeHandle(
507
+ ref,
508
+ () => {
509
+ class Combined {
510
+ constructor(customMethods2, editorHtmlElement2) {
511
+ this.customMethods = customMethods2;
512
+ this.editorHtmlElement = editorHtmlElement2;
513
+ }
514
+ get(target, propKey) {
515
+ if (this.isKeyOfCustomMethods(propKey)) {
516
+ const value = this.customMethods[propKey];
517
+ if (typeof value === "function") {
518
+ return value.bind(this.customMethods);
519
+ }
520
+ return value;
521
+ } else if (this.isKeyOfHTMLElement(propKey)) {
522
+ const value = this.editorHtmlElement[propKey];
523
+ if (typeof value === "function") {
524
+ return value.bind(this.editorHtmlElement);
525
+ }
526
+ return value;
527
+ }
528
+ }
529
+ set(target, propKey, value) {
530
+ if (this.isKeyOfCustomMethods(propKey)) {
531
+ this.customMethods[propKey] = value;
532
+ } else if (this.isKeyOfHTMLElement(propKey)) {
533
+ this.editorHtmlElement[propKey] = value;
534
+ } else {
535
+ target[propKey] = value;
536
+ }
537
+ return true;
538
+ }
539
+ isKeyOfCustomMethods(key) {
540
+ return key in this.customMethods;
541
+ }
542
+ isKeyOfHTMLElement(key) {
543
+ return key in this.editorHtmlElement;
544
+ }
545
+ }
546
+ const handler = {
547
+ get(target, propKey) {
548
+ return target.get(target, propKey);
549
+ },
550
+ set(target, propKey, value) {
551
+ return target.set(target, propKey, value);
552
+ }
553
+ };
554
+ class CustomMethods {
555
+ constructor(editor2) {
556
+ this.editor = editor2;
557
+ }
558
+ focus() {
559
+ slateReact.ReactEditor.focus(this.editor);
560
+ }
561
+ blur() {
562
+ slateReact.ReactEditor.blur(this.editor);
563
+ }
564
+ get value() {
565
+ return getFullEditorTextWithNewlines(this.editor);
566
+ }
567
+ set value(value) {
568
+ replaceEditorText(this.editor, value);
569
+ }
570
+ }
571
+ const editorHtmlElement = slateReact.ReactEditor.toDOMNode(editor, editor);
572
+ const customMethods = new CustomMethods(editor);
573
+ const combined = new Combined(customMethods, editorHtmlElement);
574
+ return new Proxy(combined, handler);
575
+ },
576
+ [editor]
577
+ );
578
+ }
579
+ function addAutocompletionsToEditor(editor, newSuggestion, point) {
580
+ const editorPosition = editor.selection;
581
+ slate.Transforms.insertNodes(
582
+ editor,
583
+ [
584
+ {
585
+ type: "suggestion",
586
+ inline: true,
587
+ content: newSuggestion,
588
+ children: [{ text: "" }]
589
+ }
590
+ ],
591
+ {
592
+ at: point
593
+ }
594
+ );
595
+ if (editorPosition) {
596
+ editor.selection = editorPosition;
597
+ }
598
+ }
599
+ function clearAutocompletionsFromEditor(editor) {
600
+ const paths = [];
601
+ for (const [node, path] of slate.Node.nodes(editor)) {
602
+ if (slate.Element.isElement(node) && node.type === "suggestion") {
603
+ paths.push(path);
604
+ }
605
+ }
606
+ for (const path of paths) {
607
+ try {
608
+ slate.Transforms.removeNodes(editor, { at: path });
609
+ } catch (e) {
610
+ console.log("CopilotTextarea.clearAutocompletionsFromEditor: error removing node", e);
611
+ }
612
+ }
613
+ }
614
+ var defaultShouldToggleHoveringEditorOnKeyPress = (event) => {
615
+ if (event.key === "k" && event.metaKey) {
616
+ return true;
617
+ }
618
+ return false;
619
+ };
620
+ var defaultShouldAcceptAutosuggestionOnKeyPress = (event) => {
621
+ if (event.key === "Tab") {
622
+ return true;
623
+ }
624
+ return false;
625
+ };
626
+ var defaultBaseAutosuggestionsConfig = {
627
+ debounceTime: 250,
628
+ contextCategories: reactCore.defaultCopilotContextCategories,
629
+ disableWhenEmpty: true,
630
+ disabled: false,
631
+ temporarilyDisableWhenMovingCursorWithoutChangingText: true,
632
+ shouldToggleHoveringEditorOnKeyPress: defaultShouldToggleHoveringEditorOnKeyPress,
633
+ shouldAcceptAutosuggestionOnKeyPress: defaultShouldAcceptAutosuggestionOnKeyPress
634
+ };
635
+ var useAutosizeTextArea = (textAreaRef, value) => {
636
+ React2.useEffect(() => {
637
+ if (textAreaRef.current !== null) {
638
+ textAreaRef.current.style.height = "0px";
639
+ const scrollHeight = textAreaRef.current.scrollHeight;
640
+ textAreaRef.current.style.height = scrollHeight + "px";
641
+ }
642
+ }, [textAreaRef, value]);
643
+ };
644
+ var use_autosize_textarea_default = useAutosizeTextArea;
645
+ var Command = React2__namespace.forwardRef((_a, ref) => {
646
+ var _b = _a, { className } = _b, props = __objRest(_b, ["className"]);
647
+ return /* @__PURE__ */ jsxRuntime.jsx(
648
+ cmdk.Command,
649
+ __spreadValues({
650
+ ref,
651
+ className: cn(
652
+ "flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",
653
+ className
654
+ )
655
+ }, props)
656
+ );
657
+ });
658
+ Command.displayName = cmdk.Command.displayName;
659
+ var CommandInput = React2__namespace.forwardRef((_a, ref) => {
660
+ var _b = _a, { className } = _b, props = __objRest(_b, ["className"]);
661
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex items-center border-b px-3", "cmdk-input-wrapper": "", children: /* @__PURE__ */ jsxRuntime.jsx(
662
+ cmdk.Command.Input,
663
+ __spreadValues({
664
+ ref,
665
+ className: cn(
666
+ "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",
667
+ className
668
+ )
669
+ }, props)
670
+ ) });
671
+ });
672
+ CommandInput.displayName = cmdk.Command.Input.displayName;
673
+ var CommandList = React2__namespace.forwardRef((_a, ref) => {
674
+ var _b = _a, { className } = _b, props = __objRest(_b, ["className"]);
675
+ return /* @__PURE__ */ jsxRuntime.jsx(
676
+ cmdk.Command.List,
677
+ __spreadValues({
678
+ ref,
679
+ className: cn("max-h-[300px] overflow-y-auto overflow-x-hidden pb-2", className)
680
+ }, props)
681
+ );
682
+ });
683
+ CommandList.displayName = cmdk.Command.List.displayName;
684
+ var CommandEmpty = React2__namespace.forwardRef((props, ref) => /* @__PURE__ */ jsxRuntime.jsx(cmdk.Command.Empty, __spreadValues({ ref, className: "py-6 text-center text-sm" }, props)));
685
+ CommandEmpty.displayName = cmdk.Command.Empty.displayName;
686
+ var CommandGroup = React2__namespace.forwardRef((_a, ref) => {
687
+ var _b = _a, { className } = _b, props = __objRest(_b, ["className"]);
688
+ return /* @__PURE__ */ jsxRuntime.jsx(
689
+ cmdk.Command.Group,
690
+ __spreadValues({
691
+ ref,
692
+ className: cn(
693
+ "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",
694
+ className
695
+ )
696
+ }, props)
697
+ );
698
+ });
699
+ CommandGroup.displayName = cmdk.Command.Group.displayName;
700
+ var CommandSeparator = React2__namespace.forwardRef((_a, ref) => {
701
+ var _b = _a, { className } = _b, props = __objRest(_b, ["className"]);
702
+ return /* @__PURE__ */ jsxRuntime.jsx(
703
+ cmdk.Command.Separator,
704
+ __spreadValues({
705
+ ref,
706
+ className: cn("-mx-1 h-px bg-border", className)
707
+ }, props)
708
+ );
709
+ });
710
+ CommandSeparator.displayName = cmdk.Command.Separator.displayName;
711
+ var CommandItem = React2__namespace.forwardRef((_a, ref) => {
712
+ var _b = _a, { className } = _b, props = __objRest(_b, ["className"]);
713
+ return /* @__PURE__ */ jsxRuntime.jsx(
714
+ cmdk.Command.Item,
715
+ __spreadValues({
716
+ ref,
717
+ className: cn(
718
+ "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",
719
+ className
720
+ )
721
+ }, props)
722
+ );
723
+ });
724
+ CommandItem.displayName = cmdk.Command.Item.displayName;
725
+ function SourceSearchBox(props) {
726
+ const [selectedValue, setSelectedValue] = React2.useState("");
727
+ return /* @__PURE__ */ jsxRuntime.jsxs(
728
+ Command,
729
+ {
730
+ className: "rounded-lg border shadow-md",
731
+ value: selectedValue,
732
+ onValueChange: (value) => {
733
+ setSelectedValue(value);
734
+ },
735
+ filter: (value, search) => {
736
+ if (props.searchTerm === "")
737
+ return 1;
738
+ if (value.startsWith(props.searchTerm))
739
+ return 1;
740
+ return 0;
741
+ },
742
+ children: [
743
+ /* @__PURE__ */ jsxRuntime.jsx(
744
+ CommandInput,
745
+ {
746
+ value: props.searchTerm,
747
+ className: "rounded-t-lg hidden",
748
+ placeholder: "Search for a command..."
749
+ }
750
+ ),
751
+ /* @__PURE__ */ jsxRuntime.jsxs(CommandList, { children: [
752
+ /* @__PURE__ */ jsxRuntime.jsx(CommandEmpty, { children: "No results found." }),
753
+ /* @__PURE__ */ jsxRuntime.jsx(CommandGroup, { heading: "Available resources", children: props.suggestedFiles.map((filePointer) => {
754
+ return /* @__PURE__ */ jsxRuntime.jsx(
755
+ CommandItem,
756
+ {
757
+ value: filePointer.name,
758
+ onSelect: (value) => {
759
+ props.onSelectedFile(filePointer);
760
+ },
761
+ children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: " px-3 flex flex-row gap-1 items-center", children: [
762
+ /* @__PURE__ */ jsxRuntime.jsx(Logo, { width: "20px", height: "20px", children: /* @__PURE__ */ jsxRuntime.jsx(
763
+ "img",
764
+ {
765
+ src: filePointer.iconImageUri,
766
+ alt: filePointer.sourceApplication,
767
+ className: "w-full h-full"
768
+ }
769
+ ) }),
770
+ filePointer.name
771
+ ] })
772
+ },
773
+ `word-${filePointer.sourceApplication}.${filePointer.name}`
774
+ );
775
+ }) }),
776
+ /* @__PURE__ */ jsxRuntime.jsx(CommandSeparator, {})
777
+ ] })
778
+ ]
779
+ }
780
+ );
781
+ }
782
+ function Logo({
783
+ children,
784
+ width,
785
+ height
786
+ }) {
787
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex items-center justify-center", style: { width, height }, children });
788
+ }
789
+ var buttonVariants = classVarianceAuthority.cva(
790
+ "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",
791
+ {
792
+ variants: {
793
+ variant: {
794
+ default: "bg-primary text-primary-foreground hover:bg-primary/90",
795
+ destructive: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
796
+ outline: "border border-input bg-background hover:bg-accent hover:text-accent-foreground",
797
+ secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
798
+ ghost: "hover:bg-accent hover:text-accent-foreground",
799
+ link: "text-primary underline-offset-4 hover:underline"
800
+ },
801
+ size: {
802
+ default: "h-10 px-4 py-2",
803
+ sm: "h-9 rounded-md px-3",
804
+ lg: "h-11 rounded-md px-8",
805
+ icon: "h-10 w-10"
806
+ }
807
+ },
808
+ defaultVariants: {
809
+ variant: "default",
810
+ size: "default"
811
+ }
812
+ }
813
+ );
814
+ var Button = React2__namespace.forwardRef(
815
+ (_a, ref) => {
816
+ var _b = _a, { className, variant, size, asChild = false } = _b, props = __objRest(_b, ["className", "variant", "size", "asChild"]);
817
+ const Comp = asChild ? reactSlot.Slot : "button";
818
+ return /* @__PURE__ */ jsxRuntime.jsx(Comp, __spreadValues({ className: cn(buttonVariants({ variant, size, className })), ref }, props));
819
+ }
820
+ );
821
+ Button.displayName = "Button";
822
+ var labelVariants = classVarianceAuthority.cva(
823
+ "text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
824
+ );
825
+ var Label = React2__namespace.forwardRef((_a, ref) => {
826
+ var _b = _a, { className } = _b, props = __objRest(_b, ["className"]);
827
+ return /* @__PURE__ */ jsxRuntime.jsx(LabelPrimitive__namespace.Root, __spreadValues({ ref, className: cn(labelVariants(), className) }, props));
828
+ });
829
+ Label.displayName = LabelPrimitive__namespace.Root.displayName;
830
+
831
+ // src/lib/stream-promise-flatten.ts
832
+ function streamPromiseFlatten(promise) {
833
+ return new ReadableStream({
834
+ start(controller) {
835
+ return __async(this, null, function* () {
836
+ try {
837
+ const stream = yield promise;
838
+ const reader = stream.getReader();
839
+ while (true) {
840
+ const { done, value } = yield reader.read();
841
+ if (done) {
842
+ controller.close();
843
+ return;
844
+ }
845
+ controller.enqueue(value);
846
+ }
847
+ } catch (error) {
848
+ controller.error(error);
849
+ }
850
+ });
851
+ }
852
+ });
853
+ }
854
+ var IncludedFilesPreview = ({
855
+ includedFiles,
856
+ setIncludedFiles
857
+ }) => {
858
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col gap-2 mt-2", children: [
859
+ /* @__PURE__ */ jsxRuntime.jsx(Label, { className: "", children: "Included context:" }),
860
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex flex-wrap gap-2", children: includedFiles.map((filePointer, index) => {
861
+ return /* @__PURE__ */ jsxRuntime.jsx(
862
+ FileChipPreview,
863
+ {
864
+ filePointer,
865
+ onDelete: () => {
866
+ setIncludedFiles((prev) => prev.filter((fp) => fp !== filePointer));
867
+ }
868
+ },
869
+ `file-${filePointer.sourceApplication}.${filePointer.name}`
870
+ );
871
+ }) })
872
+ ] });
873
+ };
874
+ var FileChipPreview = ({ filePointer, onDelete }) => {
875
+ return /* @__PURE__ */ jsxRuntime.jsx(
876
+ Chip__default.default,
877
+ {
878
+ label: filePointer.name,
879
+ onDelete,
880
+ avatar: /* @__PURE__ */ jsxRuntime.jsx(
881
+ Avatar__default.default,
882
+ {
883
+ src: filePointer.iconImageUri,
884
+ alt: filePointer.sourceApplication,
885
+ sx: { backgroundColor: "transparent" }
886
+ }
887
+ )
888
+ }
889
+ );
890
+ };
891
+ var HoveringInsertionPromptBoxCore = ({
892
+ performInsertion,
893
+ state,
894
+ insertionOrEditingFunction,
895
+ contextCategories
896
+ }) => {
897
+ const { getDocumentsContext } = React2.useContext(reactCore.CopilotContext);
898
+ const [editSuggestion, setEditSuggestion] = React2.useState("");
899
+ const [suggestionIsLoading, setSuggestionIsLoading] = React2.useState(false);
900
+ const [adjustmentPrompt, setAdjustmentPrompt] = React2.useState("");
901
+ const [generatingSuggestion, setGeneratingSuggestion] = React2.useState(
902
+ null
903
+ );
904
+ const adjustmentTextAreaRef = React2.useRef(null);
905
+ const suggestionTextAreaRef = React2.useRef(null);
906
+ const [filePointers, setFilePointers] = React2.useState([]);
907
+ const [suggestedFiles, setSuggestedFiles] = React2.useState([]);
908
+ React2.useEffect(() => {
909
+ setSuggestedFiles(getDocumentsContext(contextCategories));
910
+ }, [contextCategories, getDocumentsContext]);
911
+ use_autosize_textarea_default(suggestionTextAreaRef, editSuggestion || "");
912
+ use_autosize_textarea_default(adjustmentTextAreaRef, adjustmentPrompt || "");
913
+ React2.useEffect(() => {
914
+ setTimeout(() => {
915
+ var _a;
916
+ (_a = adjustmentTextAreaRef.current) == null ? void 0 : _a.focus();
917
+ }, 0);
918
+ }, []);
919
+ React2.useEffect(() => {
920
+ if (!generatingSuggestion) {
921
+ return;
922
+ }
923
+ if (generatingSuggestion.locked) {
924
+ return;
925
+ }
926
+ setEditSuggestion("");
927
+ const reader = generatingSuggestion.getReader();
928
+ const read = () => __async(void 0, null, function* () {
929
+ setSuggestionIsLoading(true);
930
+ while (true) {
931
+ const { done, value } = yield reader.read();
932
+ if (done) {
933
+ break;
934
+ }
935
+ setEditSuggestion((prev) => {
936
+ const newSuggestion = prev + value;
937
+ if (suggestionTextAreaRef.current) {
938
+ suggestionTextAreaRef.current.scrollTop = suggestionTextAreaRef.current.scrollHeight;
939
+ }
940
+ return newSuggestion;
941
+ });
942
+ }
943
+ setSuggestionIsLoading(false);
944
+ });
945
+ read();
946
+ return () => {
947
+ const releaseLockIfNotClosed = () => __async(void 0, null, function* () {
948
+ try {
949
+ yield reader.closed;
950
+ } catch (e) {
951
+ reader.releaseLock();
952
+ }
953
+ });
954
+ releaseLockIfNotClosed();
955
+ };
956
+ }, [generatingSuggestion]);
957
+ const beginGeneratingAdjustment = React2.useCallback(() => __async(void 0, null, function* () {
958
+ if (!adjustmentPrompt.trim()) {
959
+ return;
960
+ }
961
+ let modificationState = state.editorState;
962
+ if (editSuggestion !== "") {
963
+ modificationState.selectedText = editSuggestion;
964
+ }
965
+ const adjustmentSuggestionTextStreamPromise = insertionOrEditingFunction(
966
+ modificationState,
967
+ adjustmentPrompt,
968
+ filePointers,
969
+ new AbortController().signal
970
+ );
971
+ const adjustmentSuggestionTextStream = streamPromiseFlatten(
972
+ adjustmentSuggestionTextStreamPromise
973
+ );
974
+ setGeneratingSuggestion(adjustmentSuggestionTextStream);
975
+ }), [
976
+ adjustmentPrompt,
977
+ editSuggestion,
978
+ state.editorState,
979
+ insertionOrEditingFunction,
980
+ filePointers
981
+ ]);
982
+ const isLoading = suggestionIsLoading;
983
+ const textToEdit = editSuggestion || state.editorState.selectedText;
984
+ const adjustmentLabel = textToEdit === "" ? "Describe the text you want to insert" : "Describe adjustments to the suggested text";
985
+ const placeholder = textToEdit === "" ? "e.g. 'summarize the client's top 3 pain-points from @CallTranscript'" : "e.g. 'make it more formal', 'be more specific', ...";
986
+ const AdjustmentPromptComponent = /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
987
+ /* @__PURE__ */ jsxRuntime.jsx(Label, { className: "", children: adjustmentLabel }),
988
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "relative w-full flex items-center", children: [
989
+ /* @__PURE__ */ jsxRuntime.jsx(
990
+ "textarea",
991
+ {
992
+ disabled: suggestionIsLoading,
993
+ ref: adjustmentTextAreaRef,
994
+ value: adjustmentPrompt,
995
+ onChange: (e) => setAdjustmentPrompt(e.target.value),
996
+ onKeyDown: (e) => {
997
+ if (e.key === "Enter" && e.shiftKey) {
998
+ e.preventDefault();
999
+ setAdjustmentPrompt(adjustmentPrompt + "\n");
1000
+ } else if (e.key === "Enter") {
1001
+ e.preventDefault();
1002
+ beginGeneratingAdjustment();
1003
+ }
1004
+ },
1005
+ placeholder,
1006
+ style: { minHeight: "3rem" },
1007
+ 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]",
1008
+ rows: 1
1009
+ }
1010
+ ),
1011
+ /* @__PURE__ */ jsxRuntime.jsx(
1012
+ "button",
1013
+ {
1014
+ onClick: beginGeneratingAdjustment,
1015
+ className: "absolute right-2 bg-blue-500 text-white w-8 h-8 rounded-full flex items-center justify-center",
1016
+ children: /* @__PURE__ */ jsxRuntime.jsx("i", { className: "material-icons", children: "arrow_forward" })
1017
+ }
1018
+ )
1019
+ ] })
1020
+ ] });
1021
+ const SuggestionComponent = /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1022
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex justify-between items-end w-full", children: [
1023
+ /* @__PURE__ */ jsxRuntime.jsx(Label, { className: "mt-4", children: "Suggested:" }),
1024
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "ml-auto", children: isLoading && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex justify-center items-center", children: /* @__PURE__ */ jsxRuntime.jsx(
1025
+ "div",
1026
+ {
1027
+ 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]",
1028
+ role: "status",
1029
+ children: /* @__PURE__ */ jsxRuntime.jsx("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..." })
1030
+ }
1031
+ ) }) })
1032
+ ] }),
1033
+ /* @__PURE__ */ jsxRuntime.jsx(
1034
+ "textarea",
1035
+ {
1036
+ ref: suggestionTextAreaRef,
1037
+ value: editSuggestion,
1038
+ disabled: suggestionIsLoading,
1039
+ onChange: (e) => setEditSuggestion(e.target.value),
1040
+ className: "w-full text-base p-2 border border-gray-300 rounded-md resize-none bg-green-50",
1041
+ style: { overflow: "auto", maxHeight: "10em" }
1042
+ }
1043
+ )
1044
+ ] });
1045
+ const SubmitComponent = /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex w-full gap-4 justify-start", children: /* @__PURE__ */ jsxRuntime.jsxs(
1046
+ Button,
1047
+ {
1048
+ className: " bg-green-700 text-white",
1049
+ onClick: () => {
1050
+ performInsertion(editSuggestion);
1051
+ },
1052
+ children: [
1053
+ "Insert ",
1054
+ /* @__PURE__ */ jsxRuntime.jsx("i", { className: "material-icons", children: "check" })
1055
+ ]
1056
+ }
1057
+ ) });
1058
+ const sourceSearchCandidate = adjustmentPrompt.split(" ").pop();
1059
+ const sourceSearchWord = (sourceSearchCandidate == null ? void 0 : sourceSearchCandidate.startsWith("@")) ? sourceSearchCandidate.slice(1) : void 0;
1060
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "w-full flex flex-col items-start relative gap-2", children: [
1061
+ AdjustmentPromptComponent,
1062
+ filePointers.length > 0 && /* @__PURE__ */ jsxRuntime.jsx(IncludedFilesPreview, { includedFiles: filePointers, setIncludedFiles: setFilePointers }),
1063
+ sourceSearchWord !== void 0 && /* @__PURE__ */ jsxRuntime.jsx(
1064
+ SourceSearchBox,
1065
+ {
1066
+ searchTerm: sourceSearchWord,
1067
+ suggestedFiles,
1068
+ onSelectedFile: (filePointer) => {
1069
+ var _a;
1070
+ setAdjustmentPrompt(adjustmentPrompt.replace(new RegExp(`@${sourceSearchWord}$`), ""));
1071
+ setFilePointers((prev) => [...prev, filePointer]);
1072
+ (_a = adjustmentTextAreaRef.current) == null ? void 0 : _a.focus();
1073
+ }
1074
+ }
1075
+ ),
1076
+ generatingSuggestion ? SuggestionComponent : null,
1077
+ generatingSuggestion ? SubmitComponent : null
1078
+ ] });
1079
+ };
1080
+ var HoveringInsertionPromptBox = (props) => {
1081
+ return /* @__PURE__ */ jsxRuntime.jsx(
1082
+ "div",
1083
+ {
1084
+ className: "flex flex-col justify-center items-center space-y-4 rounded-md border shadow-lg p-4 border-gray- bg-white",
1085
+ style: { width: "35rem" },
1086
+ children: /* @__PURE__ */ jsxRuntime.jsx(
1087
+ HoveringInsertionPromptBoxCore,
1088
+ {
1089
+ state: {
1090
+ editorState: props.editorState
1091
+ },
1092
+ insertionOrEditingFunction: props.apiConfig.insertionOrEditingFunction,
1093
+ performInsertion: props.performInsertion,
1094
+ contextCategories: props.contextCategories
1095
+ }
1096
+ )
1097
+ }
1098
+ );
1099
+ };
1100
+ React2__namespace.default.forwardRef(
1101
+ (_a, ref) => {
1102
+ var _b = _a, {
1103
+ className,
1104
+ active,
1105
+ reversed
1106
+ } = _b, props = __objRest(_b, [
1107
+ "className",
1108
+ "active",
1109
+ "reversed"
1110
+ ]);
1111
+ return /* @__PURE__ */ jsxRuntime.jsx(
1112
+ "span",
1113
+ __spreadProps(__spreadValues({}, props), {
1114
+ ref,
1115
+ className: css.cx(
1116
+ className,
1117
+ css.css`
1118
+ cursor: pointer;
1119
+ color: ${reversed ? active ? "white" : "#aaa" : active ? "black" : "#ccc"};
1120
+ `
1121
+ )
1122
+ })
1123
+ );
1124
+ }
1125
+ );
1126
+ React2__namespace.default.forwardRef(
1127
+ (_a, ref) => {
1128
+ var _b = _a, { className } = _b, props = __objRest(_b, ["className"]);
1129
+ return /* @__PURE__ */ jsxRuntime.jsx(
1130
+ "span",
1131
+ __spreadProps(__spreadValues({}, props), {
1132
+ ref,
1133
+ className: css.cx(
1134
+ "material-icons",
1135
+ className,
1136
+ css.css`
1137
+ font-size: 18px;
1138
+ vertical-align: text-bottom;
1139
+ `
1140
+ )
1141
+ })
1142
+ );
1143
+ }
1144
+ );
1145
+ var Menu = React2__namespace.default.forwardRef(
1146
+ (_a, ref) => {
1147
+ var _b = _a, { className } = _b, props = __objRest(_b, ["className"]);
1148
+ return /* @__PURE__ */ jsxRuntime.jsx(
1149
+ "div",
1150
+ __spreadProps(__spreadValues({}, props), {
1151
+ "data-test-id": "menu",
1152
+ ref,
1153
+ className: css.cx(
1154
+ className,
1155
+ css.css`
1156
+ & > * {
1157
+ display: inline-block;
1158
+ }
1159
+
1160
+ & > * + * {
1161
+ margin-left: 15px;
1162
+ }
1163
+ `
1164
+ )
1165
+ })
1166
+ );
1167
+ }
1168
+ );
1169
+ var Portal = ({ children }) => {
1170
+ return typeof document === "object" ? ReactDOM__default.default.createPortal(children, document.body) : null;
1171
+ };
1172
+ React2__namespace.default.forwardRef(
1173
+ (_a, ref) => {
1174
+ var _b = _a, { className } = _b, props = __objRest(_b, ["className"]);
1175
+ return /* @__PURE__ */ jsxRuntime.jsx(
1176
+ Menu,
1177
+ __spreadProps(__spreadValues({}, props), {
1178
+ ref,
1179
+ className: css.cx(
1180
+ className,
1181
+ css.css`
1182
+ position: relative;
1183
+ padding: 1px 18px 17px;
1184
+ margin: 0 -20px;
1185
+ border-bottom: 2px solid #eee;
1186
+ margin-bottom: 20px;
1187
+ `
1188
+ )
1189
+ })
1190
+ );
1191
+ }
1192
+ );
1193
+ var HoveringEditorContext = React2.createContext({
1194
+ isDisplayed: false,
1195
+ setIsDisplayed: () => {
1196
+ }
1197
+ });
1198
+ var HoveringEditorProvider = ({ children }) => {
1199
+ const [isDisplayed, setIsDisplayed] = React2.useState(false);
1200
+ return /* @__PURE__ */ jsxRuntime.jsx(HoveringEditorContext.Provider, { value: { isDisplayed, setIsDisplayed }, children });
1201
+ };
1202
+ var useHoveringEditorContext = () => React2.useContext(HoveringEditorContext);
1203
+ var HoveringToolbar = (props) => {
1204
+ const ref = React2.useRef(null);
1205
+ const editor = slateReact.useSlate();
1206
+ const selection = slateReact.useSlateSelection();
1207
+ const { isDisplayed, setIsDisplayed } = useHoveringEditorContext();
1208
+ const [isClient, setIsClient] = React2.useState(false);
1209
+ React2.useEffect(() => {
1210
+ setIsClient(true);
1211
+ }, []);
1212
+ React2.useEffect(() => {
1213
+ const el = ref.current;
1214
+ const { selection: selection2 } = editor;
1215
+ if (!el) {
1216
+ return;
1217
+ }
1218
+ if (!selection2) {
1219
+ el.removeAttribute("style");
1220
+ return;
1221
+ }
1222
+ const domSelection = window.getSelection();
1223
+ if (!domSelection) {
1224
+ return;
1225
+ }
1226
+ const domRange = domSelection.getRangeAt(0);
1227
+ const rect = domRange.getBoundingClientRect();
1228
+ if (rect.top === 0 && rect.left === 0 && rect.width === 0 && rect.height === 0) {
1229
+ return;
1230
+ }
1231
+ const minGapFromEdge = 60;
1232
+ const verticalOffsetFromCorner = 35;
1233
+ const horizontalOffsetFromCorner = 15;
1234
+ let top = rect.top + window.scrollY - el.offsetHeight + verticalOffsetFromCorner;
1235
+ if (top < minGapFromEdge) {
1236
+ top = rect.bottom + window.scrollY + minGapFromEdge;
1237
+ } else if (top + el.offsetHeight > window.innerHeight - minGapFromEdge) {
1238
+ top = rect.top + window.scrollY - el.offsetHeight - minGapFromEdge;
1239
+ }
1240
+ let left = rect.left + window.scrollX - el.offsetWidth / 2 + rect.width / 2 + horizontalOffsetFromCorner;
1241
+ if (left < minGapFromEdge) {
1242
+ left = minGapFromEdge;
1243
+ } else if (left + el.offsetWidth > window.innerWidth - minGapFromEdge) {
1244
+ left = window.innerWidth - el.offsetWidth - minGapFromEdge;
1245
+ }
1246
+ el.style.opacity = "1";
1247
+ el.style.top = `${top}px`;
1248
+ el.style.left = `${left}px`;
1249
+ });
1250
+ React2.useEffect(() => {
1251
+ const handleClickOutside = (event) => {
1252
+ if (ref.current && !ref.current.contains(event.target)) {
1253
+ setIsDisplayed(false);
1254
+ }
1255
+ };
1256
+ document.addEventListener("mousedown", handleClickOutside);
1257
+ return () => {
1258
+ document.removeEventListener("mousedown", handleClickOutside);
1259
+ };
1260
+ }, [ref, setIsDisplayed]);
1261
+ if (!isClient) {
1262
+ return null;
1263
+ }
1264
+ return /* @__PURE__ */ jsxRuntime.jsx(Portal, { children: /* @__PURE__ */ jsxRuntime.jsx(
1265
+ Menu,
1266
+ {
1267
+ ref,
1268
+ className: props.hoverMenuClassname || "p-2 absolute z-10 top-[-10000px] left-[-10000px] mt-[-6px] opacity-0 transition-opacity duration-700",
1269
+ children: isDisplayed && selection && /* @__PURE__ */ jsxRuntime.jsx(
1270
+ HoveringInsertionPromptBox,
1271
+ {
1272
+ editorState: editorState(editor),
1273
+ apiConfig: props.apiConfig,
1274
+ closeWindow: () => {
1275
+ setIsDisplayed(false);
1276
+ },
1277
+ performInsertion: (insertedText) => {
1278
+ console.log("inserted text", insertedText);
1279
+ slate.Transforms.delete(editor, { at: selection });
1280
+ slate.Transforms.insertText(editor, insertedText, {
1281
+ at: selection
1282
+ });
1283
+ setIsDisplayed(false);
1284
+ },
1285
+ contextCategories: props.contextCategories
1286
+ }
1287
+ )
1288
+ }
1289
+ ) });
1290
+ };
1291
+ function editorState(editor, selection) {
1292
+ const textAroundCursor = getTextAroundSelection(editor);
1293
+ if (textAroundCursor) {
1294
+ return textAroundCursor;
1295
+ }
1296
+ return {
1297
+ textBeforeCursor: getFullEditorTextWithNewlines(editor),
1298
+ textAfterCursor: "",
1299
+ selectedText: ""
1300
+ };
1301
+ }
1302
+ function makeRenderElementFunction(suggestionsStyle) {
1303
+ return (props) => {
1304
+ switch (props.element.type) {
1305
+ case "paragraph":
1306
+ return /* @__PURE__ */ jsxRuntime.jsx(DefaultElement, __spreadValues({}, props));
1307
+ case "suggestion":
1308
+ return /* @__PURE__ */ jsxRuntime.jsx(SuggestionElement, __spreadProps(__spreadValues({}, props), { suggestionsStyle }));
1309
+ }
1310
+ };
1311
+ }
1312
+ var DefaultElement = (props) => {
1313
+ return /* @__PURE__ */ jsxRuntime.jsx("div", __spreadProps(__spreadValues({}, props.attributes), { children: props.children }));
1314
+ };
1315
+ var SuggestionElement = (props) => {
1316
+ return /* @__PURE__ */ jsxRuntime.jsxs(
1317
+ "span",
1318
+ __spreadProps(__spreadValues({}, props.attributes), {
1319
+ style: __spreadValues({}, props.suggestionsStyle),
1320
+ contentEditable: false,
1321
+ children: [
1322
+ props.children,
1323
+ props.element.type === "suggestion" && props.element.content
1324
+ ]
1325
+ })
1326
+ );
1327
+ };
1328
+ function makeRenderPlaceholderFunction(placeholderStyle) {
1329
+ return (props) => {
1330
+ const _a = props.attributes, { style } = _a, restAttributes = __objRest(_a, ["style"]);
1331
+ return /* @__PURE__ */ jsxRuntime.jsx(
1332
+ "div",
1333
+ __spreadProps(__spreadValues({}, restAttributes), {
1334
+ style: __spreadValues(__spreadValues({}, style), placeholderStyle),
1335
+ children: props.children
1336
+ })
1337
+ );
1338
+ };
1339
+ }
1340
+ function useAddBrandingCss(suggestionStyleAugmented, disableBranding) {
1341
+ const cssSelector = ".copilot-textarea.with-branding";
1342
+ React2.useEffect(() => {
1343
+ if (disableBranding) {
1344
+ return;
1345
+ }
1346
+ const styleEl = document.createElement("style");
1347
+ styleEl.id = "dynamic-styles";
1348
+ let dynamicStyles = Object.entries(suggestionStyleAugmented).map(([key, value]) => {
1349
+ const kebabCaseKey = key.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, "$1-$2").toLowerCase();
1350
+ return `${kebabCaseKey}: ${value};`;
1351
+ }).join(" ");
1352
+ dynamicStyles += `font-style: normal; font-size: x-small;`;
1353
+ dynamicStyles += `content: "CopilotKit";`;
1354
+ dynamicStyles += `bottom: 6px;`;
1355
+ dynamicStyles += `right: 6px;`;
1356
+ dynamicStyles += `pointer-events: none;`;
1357
+ dynamicStyles += `font-weight: 200;`;
1358
+ dynamicStyles += `padding: 0;`;
1359
+ dynamicStyles += `margin: 0;`;
1360
+ dynamicStyles += `border: 0;`;
1361
+ dynamicStyles += `line-height: 1;`;
1362
+ dynamicStyles += `position: absolute;`;
1363
+ styleEl.innerHTML = `
1364
+ ${cssSelector}::after {
1365
+ ${dynamicStyles}
1366
+ }
1367
+ `;
1368
+ document.head.appendChild(styleEl);
1369
+ const textarea = document.querySelector(cssSelector);
1370
+ const handleScroll = () => {
1371
+ const styleEl2 = document.getElementById("dynamic-styles");
1372
+ if (styleEl2 && textarea) {
1373
+ const offsetFromBottom = -textarea.scrollTop + 6;
1374
+ const offsetFromRight = -textarea.scrollLeft + 6;
1375
+ styleEl2.innerHTML = `
1376
+ ${cssSelector}::after {
1377
+ ${dynamicStyles}
1378
+ bottom: ${offsetFromBottom}px;
1379
+ right: ${offsetFromRight}px;
1380
+ }
1381
+ `;
1382
+ }
1383
+ };
1384
+ textarea == null ? void 0 : textarea.addEventListener("scroll", handleScroll);
1385
+ return () => {
1386
+ var _a;
1387
+ (_a = document.getElementById("dynamic-styles")) == null ? void 0 : _a.remove();
1388
+ textarea == null ? void 0 : textarea.removeEventListener("scroll", handleScroll);
1389
+ };
1390
+ }, [disableBranding, suggestionStyleAugmented]);
1391
+ }
1392
+ function nodeChildrenToTextComponents(editor, nodes) {
1393
+ const indeciesOfInlineElements = new Set(
1394
+ nodes.map((node, index) => {
1395
+ if (slate.Element.isElement(node) && editor.isInline(node)) {
1396
+ return index;
1397
+ }
1398
+ return -1;
1399
+ }).filter((index) => index !== -1)
1400
+ );
1401
+ const nonIgnorableItems = nodes.filter((node, index) => {
1402
+ const isInline = indeciesOfInlineElements.has(index);
1403
+ if (isInline) {
1404
+ return false;
1405
+ }
1406
+ const isNeighbourOfInline = indeciesOfInlineElements.has(index - 1) || indeciesOfInlineElements.has(index + 1);
1407
+ if (isNeighbourOfInline) {
1408
+ return node.text !== "";
1409
+ }
1410
+ return true;
1411
+ });
1412
+ return nonIgnorableItems.map((node) => {
1413
+ if (slate.Element.isElement(node)) {
1414
+ switch (node.type) {
1415
+ case "paragraph":
1416
+ return nodeChildrenToTextComponents(editor, node.children);
1417
+ case "suggestion":
1418
+ return [];
1419
+ }
1420
+ } else {
1421
+ return [node];
1422
+ }
1423
+ }).reduce((acc, val) => acc.concat(val), []);
1424
+ }
1425
+ var editorToText = (editor) => {
1426
+ const flattened = nodeChildrenToTextComponents(editor, editor.children);
1427
+ const text = flattened.map((textComponent) => textComponent.text).join("\n");
1428
+ return text;
1429
+ };
1430
+ function TrackerTextEditedSinceLastCursorMovement(props) {
1431
+ const cursorState = slateReact.useSlateSelector((state) => ({
1432
+ selection: state.selection,
1433
+ text: editorToText(state)
1434
+ }));
1435
+ const previousState = usePrevious(cursorState);
1436
+ React2.useEffect(() => {
1437
+ if (!previousState) {
1438
+ return;
1439
+ }
1440
+ if (cursorChangedWithoutTextChanged(previousState, cursorState)) {
1441
+ props.setCursorMovedSinceLastTextChange(true);
1442
+ }
1443
+ }, [props.setCursorMovedSinceLastTextChange, cursorState]);
1444
+ return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, {});
1445
+ }
1446
+ var cursorChangedWithoutTextChanged = (prev, next) => {
1447
+ const isSelectionChanged = !isSelectionEqual(prev.selection, next.selection);
1448
+ const isTextSame = prev.text === next.text;
1449
+ return isSelectionChanged && isTextSame;
1450
+ };
1451
+ var isSelectionEqual = (a, b) => {
1452
+ if (!a && !b)
1453
+ return true;
1454
+ if (!a || !b)
1455
+ return false;
1456
+ return slate.Range.equals(a, b);
1457
+ };
1458
+ function usePrevious(value) {
1459
+ const ref = React2.useRef();
1460
+ React2.useEffect(() => {
1461
+ ref.current = value;
1462
+ });
1463
+ return ref.current;
1464
+ }
1465
+ var BaseCopilotTextarea = React2__namespace.default.forwardRef(
1466
+ (props, ref) => {
1467
+ return /* @__PURE__ */ jsxRuntime.jsx(HoveringEditorProvider, { children: /* @__PURE__ */ jsxRuntime.jsx(BaseCopilotTextareaWithHoveringContext, __spreadProps(__spreadValues({}, props), { ref })) });
1468
+ }
1469
+ );
1470
+ var BaseCopilotTextareaWithHoveringContext = React2__namespace.default.forwardRef(
1471
+ (props, ref) => {
1472
+ const autosuggestionsConfig = __spreadValues(__spreadValues({}, defaultBaseAutosuggestionsConfig), props.baseAutosuggestionsConfig);
1473
+ const valueOnInitialRender = React2.useMemo(() => {
1474
+ var _a2;
1475
+ return (_a2 = props.value) != null ? _a2 : "";
1476
+ }, []);
1477
+ const [lastKnownFullEditorText, setLastKnownFullEditorText] = React2.useState(valueOnInitialRender);
1478
+ const [cursorMovedSinceLastTextChange, setCursorMovedSinceLastTextChange] = React2.useState(false);
1479
+ const initialValue = React2.useMemo(() => {
1480
+ return [
1481
+ {
1482
+ type: "paragraph",
1483
+ children: [{ text: valueOnInitialRender }]
1484
+ }
1485
+ ];
1486
+ }, [valueOnInitialRender]);
1487
+ const editor = useCopilotTextareaEditor();
1488
+ const { isDisplayed: hoveringEditorIsDisplayed, setIsDisplayed: setHoveringEditorIsDisplayed } = useHoveringEditorContext();
1489
+ const insertText = React2.useCallback(
1490
+ (autosuggestion) => {
1491
+ slate.Editor.insertText(editor, autosuggestion.text, {
1492
+ at: autosuggestion.point
1493
+ });
1494
+ },
1495
+ [editor]
1496
+ );
1497
+ const shouldDisableAutosuggestions = (
1498
+ // textarea is manually disabled:
1499
+ autosuggestionsConfig.disabled || // hovering editor is displayed:
1500
+ hoveringEditorIsDisplayed || // the cursor has moved since the last text change AND we are configured to disable autosuggestions in this case:
1501
+ cursorMovedSinceLastTextChange && autosuggestionsConfig.temporarilyDisableWhenMovingCursorWithoutChangingText
1502
+ );
1503
+ const {
1504
+ currentAutocompleteSuggestion,
1505
+ onChangeHandler: onChangeHandlerForAutocomplete,
1506
+ onKeyDownHandler: onKeyDownHandlerForAutocomplete
1507
+ } = useAutosuggestions(
1508
+ autosuggestionsConfig.debounceTime,
1509
+ autosuggestionsConfig.shouldAcceptAutosuggestionOnKeyPress,
1510
+ autosuggestionsConfig.apiConfig.autosuggestionsFunction,
1511
+ insertText,
1512
+ autosuggestionsConfig.disableWhenEmpty,
1513
+ shouldDisableAutosuggestions
1514
+ );
1515
+ const onKeyDownHandlerForHoveringEditor = React2.useCallback(
1516
+ (event) => {
1517
+ if (autosuggestionsConfig.shouldToggleHoveringEditorOnKeyPress(event)) {
1518
+ event.preventDefault();
1519
+ setHoveringEditorIsDisplayed(!hoveringEditorIsDisplayed);
1520
+ }
1521
+ },
1522
+ [
1523
+ hoveringEditorIsDisplayed,
1524
+ setHoveringEditorIsDisplayed,
1525
+ autosuggestionsConfig.shouldToggleHoveringEditorOnKeyPress
1526
+ ]
1527
+ );
1528
+ React2.useEffect(() => {
1529
+ clearAutocompletionsFromEditor(editor);
1530
+ if (currentAutocompleteSuggestion) {
1531
+ addAutocompletionsToEditor(
1532
+ editor,
1533
+ currentAutocompleteSuggestion.text,
1534
+ currentAutocompleteSuggestion.point
1535
+ );
1536
+ }
1537
+ }, [currentAutocompleteSuggestion]);
1538
+ const suggestionStyleAugmented = React2.useMemo(() => {
1539
+ return __spreadValues({
1540
+ fontStyle: "italic",
1541
+ color: "gray"
1542
+ }, props.suggestionsStyle);
1543
+ }, [props.suggestionsStyle]);
1544
+ const renderElementMemoized = React2.useMemo(() => {
1545
+ return makeRenderElementFunction(suggestionStyleAugmented);
1546
+ }, [suggestionStyleAugmented]);
1547
+ const renderPlaceholderMemoized = React2.useMemo(() => {
1548
+ const placeholderStyleSlatejsOverrides = {
1549
+ top: void 0
1550
+ };
1551
+ const placeholderStyleAugmented = __spreadValues(__spreadValues({}, placeholderStyleSlatejsOverrides), props.placeholderStyle);
1552
+ return makeRenderPlaceholderFunction(placeholderStyleAugmented);
1553
+ }, [props.placeholderStyle]);
1554
+ React2.useEffect(() => {
1555
+ var _a2, _b;
1556
+ if (props.value === lastKnownFullEditorText) {
1557
+ return;
1558
+ }
1559
+ setLastKnownFullEditorText((_a2 = props.value) != null ? _a2 : "");
1560
+ replaceEditorText(editor, (_b = props.value) != null ? _b : "");
1561
+ }, [props.value]);
1562
+ const _a = props, {
1563
+ placeholderStyle,
1564
+ value,
1565
+ hoverMenuClassname,
1566
+ onValueChange,
1567
+ baseAutosuggestionsConfig: autosuggestionsConfigFromProps,
1568
+ className,
1569
+ onChange,
1570
+ onKeyDown,
1571
+ disableBranding
1572
+ } = _a, propsToForward = __objRest(_a, [
1573
+ "placeholderStyle",
1574
+ "value",
1575
+ "hoverMenuClassname",
1576
+ "onValueChange",
1577
+ "baseAutosuggestionsConfig",
1578
+ "className",
1579
+ "onChange",
1580
+ "onKeyDown",
1581
+ "disableBranding"
1582
+ ]);
1583
+ useAddBrandingCss(suggestionStyleAugmented, disableBranding);
1584
+ usePopulateCopilotTextareaRef(editor, ref);
1585
+ const moddedClassName = (() => {
1586
+ const baseClassName = "copilot-textarea";
1587
+ const brandingClass = disableBranding ? "no-branding" : "with-branding";
1588
+ const defaultTailwindClassName = "bg-white overflow-y-auto resize-y";
1589
+ const mergedClassName = tailwindMerge.twMerge(defaultTailwindClassName, className != null ? className : "");
1590
+ return `${baseClassName} ${brandingClass} ${mergedClassName}`;
1591
+ })();
1592
+ return /* @__PURE__ */ jsxRuntime.jsxs(
1593
+ slateReact.Slate,
1594
+ {
1595
+ editor,
1596
+ initialValue,
1597
+ onChange: (value2) => {
1598
+ var _a2, _b;
1599
+ const newEditorState = getTextAroundCollapsedCursor(editor);
1600
+ const fullEditorText = newEditorState ? newEditorState.textBeforeCursor + newEditorState.textAfterCursor : getFullEditorTextWithNewlines(editor);
1601
+ setLastKnownFullEditorText((prev) => {
1602
+ if (prev !== fullEditorText) {
1603
+ setCursorMovedSinceLastTextChange(false);
1604
+ }
1605
+ return fullEditorText;
1606
+ });
1607
+ onChangeHandlerForAutocomplete(newEditorState);
1608
+ (_a2 = props.onValueChange) == null ? void 0 : _a2.call(props, fullEditorText);
1609
+ (_b = props.onChange) == null ? void 0 : _b.call(props, makeSemiFakeReactTextAreaEvent(fullEditorText));
1610
+ },
1611
+ children: [
1612
+ /* @__PURE__ */ jsxRuntime.jsx(
1613
+ TrackerTextEditedSinceLastCursorMovement,
1614
+ {
1615
+ setCursorMovedSinceLastTextChange
1616
+ }
1617
+ ),
1618
+ /* @__PURE__ */ jsxRuntime.jsx(
1619
+ HoveringToolbar,
1620
+ {
1621
+ apiConfig: autosuggestionsConfig.apiConfig,
1622
+ contextCategories: autosuggestionsConfig.contextCategories,
1623
+ hoverMenuClassname
1624
+ }
1625
+ ),
1626
+ /* @__PURE__ */ jsxRuntime.jsx(
1627
+ slateReact.Editable,
1628
+ __spreadValues({
1629
+ renderElement: renderElementMemoized,
1630
+ renderPlaceholder: renderPlaceholderMemoized,
1631
+ onKeyDown: (event) => {
1632
+ var _a2;
1633
+ onKeyDownHandlerForHoveringEditor(event);
1634
+ onKeyDownHandlerForAutocomplete(event);
1635
+ (_a2 = props.onKeyDown) == null ? void 0 : _a2.call(props, event);
1636
+ },
1637
+ className: moddedClassName
1638
+ }, propsToForward)
1639
+ )
1640
+ ]
1641
+ }
1642
+ );
1643
+ }
1644
+ );
1645
+ function makeSemiFakeReactTextAreaEvent(currentText) {
1646
+ return {
1647
+ target: {
1648
+ value: currentText,
1649
+ type: "copilot-textarea"
1650
+ },
1651
+ currentTarget: {
1652
+ value: currentText,
1653
+ type: "copilot-textarea"
1654
+ }
1655
+ };
1656
+ }
1657
+
1658
+ // src/lib/retry.tsx
1659
+ function retry(fn, retriesLeft = 2, interval = 200, backoff = 1.5) {
1660
+ return new Promise((resolve, reject) => {
1661
+ fn().then(resolve).catch((error) => {
1662
+ if (retriesLeft === 1) {
1663
+ reject(error);
1664
+ return;
1665
+ }
1666
+ setTimeout(() => {
1667
+ retry(fn, retriesLeft - 1, interval * backoff, backoff).then(resolve).catch(reject);
1668
+ }, interval);
1669
+ });
1670
+ });
1671
+ }
1672
+ function useMakeStandardAutosuggestionFunction(textareaPurpose, contextCategories, apiConfig) {
1673
+ const { getContextString, copilotApiConfig } = React2.useContext(reactCore.CopilotContext);
1674
+ return React2.useCallback(
1675
+ (editorState2, abortSignal) => __async(this, null, function* () {
1676
+ const res = yield retry(() => __async(this, null, function* () {
1677
+ const messages = [
1678
+ {
1679
+ role: "system",
1680
+ content: apiConfig.makeSystemPrompt(
1681
+ textareaPurpose,
1682
+ getContextString([], contextCategories)
1683
+ )
1684
+ },
1685
+ ...apiConfig.fewShotMessages,
1686
+ {
1687
+ role: "user",
1688
+ name: "TextAfterCursor",
1689
+ content: editorState2.textAfterCursor
1690
+ },
1691
+ {
1692
+ role: "user",
1693
+ name: "TextBeforeCursor",
1694
+ content: editorState2.textBeforeCursor
1695
+ }
1696
+ ];
1697
+ const response = yield reactCore.fetchAndDecodeChatCompletionAsText(__spreadProps(__spreadValues({
1698
+ messages
1699
+ }, apiConfig.forwardedParams), {
1700
+ copilotConfig: copilotApiConfig,
1701
+ signal: abortSignal
1702
+ }));
1703
+ if (!response.events) {
1704
+ throw new Error("Failed to fetch chat completion");
1705
+ }
1706
+ const reader = response.events.getReader();
1707
+ let result = "";
1708
+ while (!abortSignal.aborted) {
1709
+ const { done, value } = yield reader.read();
1710
+ if (done) {
1711
+ break;
1712
+ }
1713
+ result += value;
1714
+ }
1715
+ return result;
1716
+ }));
1717
+ return res;
1718
+ }),
1719
+ [apiConfig, getContextString, contextCategories, textareaPurpose]
1720
+ );
1721
+ }
1722
+
1723
+ // src/types/autosuggestions-config/suggestions-api-config.tsx
1724
+ var defaultSuggestionsMakeSystemPrompt = (textareaPurpose, contextString) => {
1725
+ return `You are a versatile writing assistant.
1726
+
1727
+ The user is writing some text.
1728
+ The purpose is: "${textareaPurpose}"
1729
+
1730
+ Your job is to guess what the user will write next AS BEST YOU CAN.
1731
+ Only guess a SHORT distance ahead. Usually 1 sentence, or at most 1 paragraph.
1732
+
1733
+ Adjust yourself to the user's style and implied intent.
1734
+
1735
+ The user will provide both the text before and after the cursor. You should use this to infer what the user is likely to write next.
1736
+ <TextAfterCursor>
1737
+ <TextBeforeCursor>
1738
+ <YourSuggestion>
1739
+
1740
+ If we need to add a whitespace character to the suggested text, make sure to explicitly add it in.
1741
+
1742
+ The following external context is also provided. Use it to help you make better suggestions!!!
1743
+ \`\`\`
1744
+ ${contextString}
1745
+ \`\`\`
1746
+ `;
1747
+ };
1748
+ var defaultSuggestionsFewShotMessages = [
1749
+ {
1750
+ role: "user",
1751
+ name: "TextAfterCursor",
1752
+ content: "While I was there I also picked up some apples, oranges, and bananas."
1753
+ },
1754
+ {
1755
+ role: "user",
1756
+ content: "This morning I woke up and went straight to the grocery store."
1757
+ },
1758
+ {
1759
+ role: "assistant",
1760
+ content: " When I arrived I went straight to the produce section and picked out a big watermelon. "
1761
+ },
1762
+ {
1763
+ role: "user",
1764
+ name: "TextAfterCursor",
1765
+ content: "and (iii) to the appointment of the Equityholders' Representative pursuant to Section 10.7 of the Merger Agreement and to the provisions thereof."
1766
+ },
1767
+ {
1768
+ role: "user",
1769
+ name: "TextBeforeCursor",
1770
+ content: `The Optionholder, in the Optionholder's capacity as a holder of vested Options, hereby irrevocably and unconditionally agrees: (i) that the Optionholder shall be deemed an "Equityholder" under the Merger Agreement and shall be entitled to the rights and benefits, and subject to the obligations, of an "Equityholder" thereunder;`
1771
+ },
1772
+ {
1773
+ role: "assistant",
1774
+ content: ` (ii) that, for purposes of this Agreement and the Merger Agreement, the applicable percentage set forth opposite the name of the Optionholder in the Distribution Waterfall shall be such the Optionholder's "Pro Rata Share"; `
1775
+ }
1776
+ ];
1777
+ var defaultSuggestionsApiConfig = {
1778
+ makeSystemPrompt: defaultSuggestionsMakeSystemPrompt,
1779
+ fewShotMessages: defaultSuggestionsFewShotMessages,
1780
+ forwardedParams: void 0
1781
+ };
1782
+
1783
+ // src/types/autosuggestions-config/insertions-api-config.tsx
1784
+ var defaultInsertionsMakeSystemPrompt = (textareaPurpose, contextString) => {
1785
+ return `You are a versatile writing assistant helping the user insert new text into their existing work.
1786
+
1787
+ The user is writing some text.
1788
+ The purpose is: "${textareaPurpose}"
1789
+
1790
+ The following external context is also provided. Use it to inform your suggestions when relevant!!!
1791
+ \`\`\`
1792
+ ${contextString}
1793
+ \`\`\`
1794
+
1795
+ The user will provide you with a prompt for an INSERTION into the text they are writing.
1796
+ Your job is to come up with an INSERTION into the text that the user would like to use, AS BEST YOU CAN.
1797
+ Only insert a SHORT segment. Usually 1 sentence, or at most 1 paragraph.
1798
+
1799
+ Adjust yourself to the user's style and implied intent.
1800
+
1801
+
1802
+ The user will provide the text before and after the cursor, as well as the INSERTION prompt. You should use this to infer the best relevant insertion.
1803
+ The conversation will be structured as follows:
1804
+ <TextAfterCursor>
1805
+ <TextBeforeCursor>
1806
+ <InsertionPrompt>
1807
+
1808
+ <YourInsertionSuggestion>
1809
+ `;
1810
+ };
1811
+ var defaultInsertionsFewShotMessages = [
1812
+ {
1813
+ role: "user",
1814
+ name: "TextAfterCursor",
1815
+ content: "While I was there I also picked up some apples, oranges, and bananas."
1816
+ },
1817
+ {
1818
+ role: "user",
1819
+ name: "TextBeforeCursor",
1820
+ content: "This morning I woke up and went straight to the grocery store."
1821
+ },
1822
+ {
1823
+ role: "user",
1824
+ name: "InsertionPrompt",
1825
+ content: "I bought a big watermelon"
1826
+ },
1827
+ {
1828
+ role: "assistant",
1829
+ content: " When I arrived I went straight to the produce section and picked out a big watermelon. "
1830
+ },
1831
+ {
1832
+ role: "user",
1833
+ name: "TextAfterCursor",
1834
+ content: "and (iii) to the appointment of the Equityholders' Representative pursuant to Section 10.7 of the Merger Agreement and to the provisions thereof."
1835
+ },
1836
+ {
1837
+ role: "user",
1838
+ name: "TextBeforeCursor",
1839
+ content: `The Optionholder, in the Optionholder's capacity as a holder of vested Options, hereby irrevocably and unconditionally agrees: (i) that the Optionholder shall be deemed an "Equityholder" under the Merger Agreement and shall be entitled to the rights and benefits, and subject to the obligations, of an "Equityholder" thereunder;`
1840
+ },
1841
+ {
1842
+ role: "user",
1843
+ name: "InsertionPrompt",
1844
+ content: "add section about the optionholder's pro rata share"
1845
+ },
1846
+ {
1847
+ role: "assistant",
1848
+ content: ` (ii) that, for purposes of this Agreement and the Merger Agreement, the applicable percentage set forth opposite the name of the Optionholder in the Distribution Waterfall shall be such the Optionholder's "Pro Rata Share"; `
1849
+ }
1850
+ ];
1851
+ var defaultInsertionsApiConfig = {
1852
+ makeSystemPrompt: defaultInsertionsMakeSystemPrompt,
1853
+ fewShotMessages: defaultInsertionsFewShotMessages,
1854
+ forwardedParams: void 0
1855
+ };
1856
+
1857
+ // src/types/autosuggestions-config/editing-api-config.tsx
1858
+ var defaultEditingMakeSystemPrompt = (textareaPurpose, contextString) => {
1859
+ return `You are a versatile writing assistant helping the user edit a portion of their text.
1860
+
1861
+ The user is writing some text.
1862
+ The purpose is: "${textareaPurpose}"
1863
+
1864
+ The following external context is also provided. Use it when relevant.
1865
+ \`\`\`
1866
+ ${contextString}
1867
+ \`\`\`
1868
+
1869
+ The user has provided you with a PROMPT for EDITING a PORTION of the text.
1870
+ Your job is to come up with a new EDITED version OF THE SEGMENT IN QUESTION - AS BEST YOU CAN.
1871
+ Only rewrite the portion of the text that the user has marked as "TextToEdit"!!!
1872
+
1873
+ Adjust yourself to the user's style and implied intent.
1874
+
1875
+ The conversation will be structured as follows:
1876
+ <TextBeforeCursor>
1877
+ <TextToEdit>
1878
+ <TextAfterCursor>
1879
+ <EditingPrompt>
1880
+
1881
+ <YourEditSuggestion>
1882
+ `;
1883
+ };
1884
+ var defaultEditingFewShotMessages = [
1885
+ {
1886
+ role: "user",
1887
+ name: "TextBeforeCursor",
1888
+ content: "This morning I woke up and went straight to the grocery store. "
1889
+ },
1890
+ {
1891
+ role: "user",
1892
+ name: "TextToEdit",
1893
+ content: "While I was there I picked up some apples, oranges, and bananas. "
1894
+ },
1895
+ {
1896
+ role: "user",
1897
+ name: "TextAfterCursor",
1898
+ content: "The grocery store was having a sale on fruit, so I decided to stock up."
1899
+ },
1900
+ {
1901
+ role: "user",
1902
+ name: "EditingPrompt",
1903
+ content: "I also bought a big watermelon"
1904
+ },
1905
+ {
1906
+ role: "assistant",
1907
+ content: "While I was there I picked up some apples, oranges, and bananas, and a big watermelon."
1908
+ },
1909
+ {
1910
+ role: "user",
1911
+ name: "TextBeforeCursor",
1912
+ content: "Yesterday, I spent the afternoon working on my new project. "
1913
+ },
1914
+ {
1915
+ role: "user",
1916
+ name: "TextToEdit",
1917
+ content: "It's quite challenging and requires a lot of focus. "
1918
+ },
1919
+ {
1920
+ role: "user",
1921
+ name: "TextAfterCursor",
1922
+ content: "I'm really excited about the potential outcomes of this project."
1923
+ },
1924
+ {
1925
+ role: "user",
1926
+ name: "EditingPrompt",
1927
+ content: "emphasize the complexity and my enthusiasm for the project"
1928
+ },
1929
+ {
1930
+ role: "assistant",
1931
+ content: "It's a highly complex task that demands intense concentration, but I'm incredibly enthusiastic about the promising prospects of this project."
1932
+ }
1933
+ ];
1934
+ var defaultEditingApiConfig = {
1935
+ makeSystemPrompt: defaultEditingMakeSystemPrompt,
1936
+ fewShotMessages: defaultEditingFewShotMessages,
1937
+ forwardedParams: void 0
1938
+ };
1939
+ var defaultAutosuggestionsConfig = __spreadProps(__spreadValues({}, defaultBaseAutosuggestionsConfig), {
1940
+ contextCategories: reactCore.defaultCopilotContextCategories,
1941
+ chatApiConfigs: {
1942
+ suggestionsApiConfig: defaultSuggestionsApiConfig,
1943
+ insertionApiConfig: defaultInsertionsApiConfig,
1944
+ editingApiConfig: defaultEditingApiConfig
1945
+ }
1946
+ });
1947
+ function useMakeStandardInsertionOrEditingFunction(textareaPurpose, contextCategories, insertionApiConfig, editingApiConfig) {
1948
+ const { getContextString, copilotApiConfig } = React2.useContext(reactCore.CopilotContext);
1949
+ const insertionFunction = React2.useCallback(
1950
+ (editorState2, insertionPrompt, documents, abortSignal) => __async(this, null, function* () {
1951
+ const res = yield retry(() => __async(this, null, function* () {
1952
+ const messages = [
1953
+ {
1954
+ role: "system",
1955
+ content: insertionApiConfig.makeSystemPrompt(
1956
+ textareaPurpose,
1957
+ getContextString(documents, contextCategories)
1958
+ )
1959
+ },
1960
+ ...insertionApiConfig.fewShotMessages,
1961
+ {
1962
+ role: "user",
1963
+ name: "TextAfterCursor",
1964
+ content: editorState2.textAfterCursor
1965
+ },
1966
+ {
1967
+ role: "user",
1968
+ name: "TextBeforeCursor",
1969
+ content: editorState2.textBeforeCursor
1970
+ },
1971
+ {
1972
+ role: "user",
1973
+ name: "InsertionPrompt",
1974
+ content: insertionPrompt
1975
+ }
1976
+ ];
1977
+ const stream = yield reactCore.fetchAndDecodeChatCompletionAsText(__spreadProps(__spreadValues({
1978
+ messages
1979
+ }, insertionApiConfig.forwardedParams), {
1980
+ copilotConfig: copilotApiConfig,
1981
+ signal: abortSignal
1982
+ }));
1983
+ return stream.events;
1984
+ }));
1985
+ return res;
1986
+ }),
1987
+ [insertionApiConfig, getContextString, contextCategories, textareaPurpose]
1988
+ );
1989
+ const editingFunction = React2.useCallback(
1990
+ (editorState2, editingPrompt, documents, abortSignal) => __async(this, null, function* () {
1991
+ const res = yield retry(() => __async(this, null, function* () {
1992
+ const messages = [
1993
+ {
1994
+ role: "system",
1995
+ content: editingApiConfig.makeSystemPrompt(
1996
+ textareaPurpose,
1997
+ getContextString(documents, contextCategories)
1998
+ )
1999
+ },
2000
+ ...editingApiConfig.fewShotMessages,
2001
+ {
2002
+ role: "user",
2003
+ name: "TextBeforeCursor",
2004
+ content: editorState2.textBeforeCursor
2005
+ },
2006
+ {
2007
+ role: "user",
2008
+ name: "TextToEdit",
2009
+ content: editorState2.selectedText
2010
+ },
2011
+ {
2012
+ role: "user",
2013
+ name: "TextAfterCursor",
2014
+ content: editorState2.textAfterCursor
2015
+ },
2016
+ {
2017
+ role: "user",
2018
+ name: "EditingPrompt",
2019
+ content: editingPrompt
2020
+ }
2021
+ ];
2022
+ const stream = yield reactCore.fetchAndDecodeChatCompletionAsText(__spreadProps(__spreadValues({
2023
+ messages
2024
+ }, editingApiConfig.forwardedParams), {
2025
+ copilotConfig: copilotApiConfig,
2026
+ signal: abortSignal
2027
+ }));
2028
+ return stream.events;
2029
+ }));
2030
+ return res;
2031
+ }),
2032
+ [editingApiConfig, getContextString, contextCategories, textareaPurpose]
2033
+ );
2034
+ const insertionOrEditingFunction = React2.useCallback(
2035
+ (editorState2, insertionPrompt, documents, abortSignal) => __async(this, null, function* () {
2036
+ if (editorState2.selectedText === "") {
2037
+ return yield insertionFunction(editorState2, insertionPrompt, documents, abortSignal);
2038
+ } else {
2039
+ return yield editingFunction(editorState2, insertionPrompt, documents, abortSignal);
2040
+ }
2041
+ }),
2042
+ [insertionFunction, editingFunction]
2043
+ );
2044
+ return insertionOrEditingFunction;
2045
+ }
2046
+ var CopilotTextarea = React2__namespace.default.forwardRef(
2047
+ (props, ref) => {
2048
+ const _a = props, { autosuggestionsConfig: autosuggestionsConfigUserSpecified } = _a, forwardedProps = __objRest(_a, ["autosuggestionsConfig"]);
2049
+ const autosuggestionsConfig = merge__default.default(
2050
+ defaultAutosuggestionsConfig,
2051
+ autosuggestionsConfigUserSpecified
2052
+ );
2053
+ const autosuggestionsFunction = useMakeStandardAutosuggestionFunction(
2054
+ autosuggestionsConfig.textareaPurpose,
2055
+ autosuggestionsConfig.contextCategories,
2056
+ autosuggestionsConfig.chatApiConfigs.suggestionsApiConfig
2057
+ );
2058
+ const insertionOrEditingFunction = useMakeStandardInsertionOrEditingFunction(
2059
+ autosuggestionsConfig.textareaPurpose,
2060
+ autosuggestionsConfig.contextCategories,
2061
+ autosuggestionsConfig.chatApiConfigs.insertionApiConfig,
2062
+ autosuggestionsConfig.chatApiConfigs.editingApiConfig
2063
+ );
2064
+ return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: /* @__PURE__ */ jsxRuntime.jsx(
2065
+ BaseCopilotTextarea,
2066
+ __spreadProps(__spreadValues({
2067
+ ref
2068
+ }, forwardedProps), {
2069
+ baseAutosuggestionsConfig: __spreadProps(__spreadValues({}, autosuggestionsConfig), {
2070
+ apiConfig: {
2071
+ insertionOrEditingFunction,
2072
+ autosuggestionsFunction
2073
+ }
2074
+ })
2075
+ })
2076
+ ) });
2077
+ }
2078
+ );
2079
+
2080
+ exports.BaseCopilotTextarea = BaseCopilotTextarea;
2081
+ exports.CopilotTextarea = CopilotTextarea;
2082
+ //# sourceMappingURL=out.js.map
2083
+ //# sourceMappingURL=index.js.map