@copilotkit/react-textarea 0.25.0 → 0.26.0-alpha.0

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