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