@copilotkit/react-textarea 0.27.0-alpha.3 → 0.27.0-alpha.5

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