@copilotkit/react-textarea 0.19.0-alpha.7 → 0.19.0-alpha.9

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