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