@copilotkit/react-textarea 1.51.4 → 1.51.5-next.1

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 (396) hide show
  1. package/.attw.json +3 -0
  2. package/CHANGELOG.md +18 -0
  3. package/dist/index.cjs +1918 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.css +10 -639
  6. package/dist/index.css.map +1 -1
  7. package/dist/index.d.cts +318 -0
  8. package/dist/index.d.cts.map +1 -0
  9. package/dist/index.d.mts +318 -0
  10. package/dist/index.d.mts.map +1 -0
  11. package/dist/index.mjs +1879 -61
  12. package/dist/index.mjs.map +1 -1
  13. package/dist/index.umd.js +1900 -123
  14. package/dist/index.umd.js.map +1 -1
  15. package/package.json +18 -16
  16. package/src/components/copilot-textarea/copilot-textarea.tsx +1 -1
  17. package/tsdown.config.ts +60 -0
  18. package/vitest.config.mjs +11 -0
  19. package/dist/chunk-2C7O2EVM.mjs +0 -27
  20. package/dist/chunk-2C7O2EVM.mjs.map +0 -1
  21. package/dist/chunk-2X3CZVEP.mjs +0 -32
  22. package/dist/chunk-2X3CZVEP.mjs.map +0 -1
  23. package/dist/chunk-3WLGLZTY.mjs +0 -232
  24. package/dist/chunk-3WLGLZTY.mjs.map +0 -1
  25. package/dist/chunk-5UNJXFUO.mjs +0 -29
  26. package/dist/chunk-5UNJXFUO.mjs.map +0 -1
  27. package/dist/chunk-7GZWOXE4.mjs +0 -70
  28. package/dist/chunk-7GZWOXE4.mjs.map +0 -1
  29. package/dist/chunk-7V4ORVQX.mjs +0 -17
  30. package/dist/chunk-7V4ORVQX.mjs.map +0 -1
  31. package/dist/chunk-A6YGJFQI.mjs +0 -111
  32. package/dist/chunk-A6YGJFQI.mjs.map +0 -1
  33. package/dist/chunk-AHNPJMBR.mjs +0 -90
  34. package/dist/chunk-AHNPJMBR.mjs.map +0 -1
  35. package/dist/chunk-ARLBRSB7.mjs +0 -140
  36. package/dist/chunk-ARLBRSB7.mjs.map +0 -1
  37. package/dist/chunk-AZ7RF6ED.mjs +0 -120
  38. package/dist/chunk-AZ7RF6ED.mjs.map +0 -1
  39. package/dist/chunk-CFCMZVQ2.mjs +0 -136
  40. package/dist/chunk-CFCMZVQ2.mjs.map +0 -1
  41. package/dist/chunk-CMKGYQFX.mjs +0 -45
  42. package/dist/chunk-CMKGYQFX.mjs.map +0 -1
  43. package/dist/chunk-DE5K76I2.mjs +0 -1
  44. package/dist/chunk-DE5K76I2.mjs.map +0 -1
  45. package/dist/chunk-DZMQBOPG.mjs +0 -36
  46. package/dist/chunk-DZMQBOPG.mjs.map +0 -1
  47. package/dist/chunk-E7C63KQP.mjs +0 -64
  48. package/dist/chunk-E7C63KQP.mjs.map +0 -1
  49. package/dist/chunk-EGBZSVLK.mjs +0 -25
  50. package/dist/chunk-EGBZSVLK.mjs.map +0 -1
  51. package/dist/chunk-FTG7P3NP.mjs +0 -25
  52. package/dist/chunk-FTG7P3NP.mjs.map +0 -1
  53. package/dist/chunk-H4VKQGVU.mjs +0 -1
  54. package/dist/chunk-H4VKQGVU.mjs.map +0 -1
  55. package/dist/chunk-IBZTDP72.mjs +0 -56
  56. package/dist/chunk-IBZTDP72.mjs.map +0 -1
  57. package/dist/chunk-IU3WTXLQ.mjs +0 -1
  58. package/dist/chunk-IU3WTXLQ.mjs.map +0 -1
  59. package/dist/chunk-KNQIEOFP.mjs +0 -19
  60. package/dist/chunk-KNQIEOFP.mjs.map +0 -1
  61. package/dist/chunk-L7VVZH4Q.mjs +0 -1
  62. package/dist/chunk-L7VVZH4Q.mjs.map +0 -1
  63. package/dist/chunk-LYNGBKJR.mjs +0 -58
  64. package/dist/chunk-LYNGBKJR.mjs.map +0 -1
  65. package/dist/chunk-M7GTVHFB.mjs +0 -188
  66. package/dist/chunk-M7GTVHFB.mjs.map +0 -1
  67. package/dist/chunk-MCNXIA4Q.mjs +0 -75
  68. package/dist/chunk-MCNXIA4Q.mjs.map +0 -1
  69. package/dist/chunk-MMVDU6DF.mjs +0 -1
  70. package/dist/chunk-MMVDU6DF.mjs.map +0 -1
  71. package/dist/chunk-MQBPYOOZ.mjs +0 -97
  72. package/dist/chunk-MQBPYOOZ.mjs.map +0 -1
  73. package/dist/chunk-MQXYWOE2.mjs +0 -32
  74. package/dist/chunk-MQXYWOE2.mjs.map +0 -1
  75. package/dist/chunk-MRXNTQOX.mjs +0 -59
  76. package/dist/chunk-MRXNTQOX.mjs.map +0 -1
  77. package/dist/chunk-NFMCLTJU.mjs +0 -39
  78. package/dist/chunk-NFMCLTJU.mjs.map +0 -1
  79. package/dist/chunk-O4WCM57A.mjs +0 -30
  80. package/dist/chunk-O4WCM57A.mjs.map +0 -1
  81. package/dist/chunk-PDFIUPCS.mjs +0 -108
  82. package/dist/chunk-PDFIUPCS.mjs.map +0 -1
  83. package/dist/chunk-QFXR6DOA.mjs +0 -64
  84. package/dist/chunk-QFXR6DOA.mjs.map +0 -1
  85. package/dist/chunk-RUV6NBIF.mjs +0 -1
  86. package/dist/chunk-RUV6NBIF.mjs.map +0 -1
  87. package/dist/chunk-SWX3MRZ4.mjs +0 -278
  88. package/dist/chunk-SWX3MRZ4.mjs.map +0 -1
  89. package/dist/chunk-TGN3YVSO.mjs +0 -85
  90. package/dist/chunk-TGN3YVSO.mjs.map +0 -1
  91. package/dist/chunk-UB4Y22EF.mjs +0 -21
  92. package/dist/chunk-UB4Y22EF.mjs.map +0 -1
  93. package/dist/chunk-UIBUYQPG.mjs +0 -79
  94. package/dist/chunk-UIBUYQPG.mjs.map +0 -1
  95. package/dist/chunk-VBPZTMXB.mjs +0 -13
  96. package/dist/chunk-VBPZTMXB.mjs.map +0 -1
  97. package/dist/chunk-VH7INUR5.mjs +0 -82
  98. package/dist/chunk-VH7INUR5.mjs.map +0 -1
  99. package/dist/chunk-VVRGAA43.mjs +0 -59
  100. package/dist/chunk-VVRGAA43.mjs.map +0 -1
  101. package/dist/chunk-VYLLLBUP.mjs +0 -50
  102. package/dist/chunk-VYLLLBUP.mjs.map +0 -1
  103. package/dist/chunk-WADHCMPK.mjs +0 -1
  104. package/dist/chunk-WADHCMPK.mjs.map +0 -1
  105. package/dist/chunk-WJHSY5T6.mjs +0 -1
  106. package/dist/chunk-WJHSY5T6.mjs.map +0 -1
  107. package/dist/chunk-WXKPRNNO.mjs +0 -32
  108. package/dist/chunk-WXKPRNNO.mjs.map +0 -1
  109. package/dist/chunk-YINY56BI.mjs +0 -49
  110. package/dist/chunk-YINY56BI.mjs.map +0 -1
  111. package/dist/chunk-ZBP4SABT.mjs +0 -117
  112. package/dist/chunk-ZBP4SABT.mjs.map +0 -1
  113. package/dist/chunk-ZWI5KPQ5.mjs +0 -31
  114. package/dist/chunk-ZWI5KPQ5.mjs.map +0 -1
  115. package/dist/components/base-copilot-textarea/base-copilot-textarea.css +0 -9
  116. package/dist/components/base-copilot-textarea/base-copilot-textarea.css.map +0 -1
  117. package/dist/components/base-copilot-textarea/base-copilot-textarea.d.ts +0 -43
  118. package/dist/components/base-copilot-textarea/base-copilot-textarea.js +0 -1849
  119. package/dist/components/base-copilot-textarea/base-copilot-textarea.js.map +0 -1
  120. package/dist/components/base-copilot-textarea/base-copilot-textarea.mjs +0 -40
  121. package/dist/components/base-copilot-textarea/base-copilot-textarea.mjs.map +0 -1
  122. package/dist/components/base-copilot-textarea/render-element.d.ts +0 -7
  123. package/dist/components/base-copilot-textarea/render-element.js +0 -75
  124. package/dist/components/base-copilot-textarea/render-element.js.map +0 -1
  125. package/dist/components/base-copilot-textarea/render-element.mjs +0 -8
  126. package/dist/components/base-copilot-textarea/render-element.mjs.map +0 -1
  127. package/dist/components/base-copilot-textarea/render-placeholder.d.ts +0 -7
  128. package/dist/components/base-copilot-textarea/render-placeholder.js +0 -72
  129. package/dist/components/base-copilot-textarea/render-placeholder.js.map +0 -1
  130. package/dist/components/base-copilot-textarea/render-placeholder.mjs +0 -8
  131. package/dist/components/base-copilot-textarea/render-placeholder.mjs.map +0 -1
  132. package/dist/components/base-copilot-textarea/track-cursor-moved-since-last-text-change.d.ts +0 -8
  133. package/dist/components/base-copilot-textarea/track-cursor-moved-since-last-text-change.js +0 -112
  134. package/dist/components/base-copilot-textarea/track-cursor-moved-since-last-text-change.js.map +0 -1
  135. package/dist/components/base-copilot-textarea/track-cursor-moved-since-last-text-change.mjs +0 -9
  136. package/dist/components/base-copilot-textarea/track-cursor-moved-since-last-text-change.mjs.map +0 -1
  137. package/dist/components/base-copilot-textarea/use-add-branding-css.d.ts +0 -3
  138. package/dist/components/base-copilot-textarea/use-add-branding-css.js +0 -83
  139. package/dist/components/base-copilot-textarea/use-add-branding-css.js.map +0 -1
  140. package/dist/components/base-copilot-textarea/use-add-branding-css.mjs +0 -8
  141. package/dist/components/base-copilot-textarea/use-add-branding-css.mjs.map +0 -1
  142. package/dist/components/copilot-textarea/copilot-textarea.css +0 -9
  143. package/dist/components/copilot-textarea/copilot-textarea.css.map +0 -1
  144. package/dist/components/copilot-textarea/copilot-textarea.d.ts +0 -171
  145. package/dist/components/copilot-textarea/copilot-textarea.js +0 -2356
  146. package/dist/components/copilot-textarea/copilot-textarea.js.map +0 -1
  147. package/dist/components/copilot-textarea/copilot-textarea.mjs +0 -49
  148. package/dist/components/copilot-textarea/copilot-textarea.mjs.map +0 -1
  149. package/dist/components/hovering-toolbar/hovering-editor-provider.d.ts +0 -18
  150. package/dist/components/hovering-toolbar/hovering-editor-provider.js +0 -46
  151. package/dist/components/hovering-toolbar/hovering-editor-provider.js.map +0 -1
  152. package/dist/components/hovering-toolbar/hovering-editor-provider.mjs +0 -10
  153. package/dist/components/hovering-toolbar/hovering-editor-provider.mjs.map +0 -1
  154. package/dist/components/hovering-toolbar/hovering-toolbar-components.d.ts +0 -18
  155. package/dist/components/hovering-toolbar/hovering-toolbar-components.js +0 -158
  156. package/dist/components/hovering-toolbar/hovering-toolbar-components.js.map +0 -1
  157. package/dist/components/hovering-toolbar/hovering-toolbar-components.mjs +0 -16
  158. package/dist/components/hovering-toolbar/hovering-toolbar-components.mjs.map +0 -1
  159. package/dist/components/hovering-toolbar/hovering-toolbar.d.ts +0 -12
  160. package/dist/components/hovering-toolbar/hovering-toolbar.js +0 -934
  161. package/dist/components/hovering-toolbar/hovering-toolbar.js.map +0 -1
  162. package/dist/components/hovering-toolbar/hovering-toolbar.mjs +0 -23
  163. package/dist/components/hovering-toolbar/hovering-toolbar.mjs.map +0 -1
  164. package/dist/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box-core.d.ts +0 -16
  165. package/dist/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box-core.js +0 -649
  166. package/dist/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box-core.js.map +0 -1
  167. package/dist/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box-core.mjs +0 -18
  168. package/dist/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box-core.mjs.map +0 -1
  169. package/dist/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box.d.ts +0 -13
  170. package/dist/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box.js +0 -672
  171. package/dist/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box.js.map +0 -1
  172. package/dist/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box.mjs +0 -19
  173. package/dist/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box.mjs.map +0 -1
  174. package/dist/components/hovering-toolbar/text-insertion-prompt-box/included-files-preview.d.ts +0 -16
  175. package/dist/components/hovering-toolbar/text-insertion-prompt-box/included-files-preview.js +0 -144
  176. package/dist/components/hovering-toolbar/text-insertion-prompt-box/included-files-preview.js.map +0 -1
  177. package/dist/components/hovering-toolbar/text-insertion-prompt-box/included-files-preview.mjs +0 -12
  178. package/dist/components/hovering-toolbar/text-insertion-prompt-box/included-files-preview.mjs.map +0 -1
  179. package/dist/components/hovering-toolbar/text-insertion-prompt-box/index.d.ts +0 -4
  180. package/dist/components/hovering-toolbar/text-insertion-prompt-box/index.js +0 -672
  181. package/dist/components/hovering-toolbar/text-insertion-prompt-box/index.js.map +0 -1
  182. package/dist/components/hovering-toolbar/text-insertion-prompt-box/index.mjs +0 -20
  183. package/dist/components/hovering-toolbar/text-insertion-prompt-box/index.mjs.map +0 -1
  184. package/dist/components/index.css +0 -9
  185. package/dist/components/index.css.map +0 -1
  186. package/dist/components/index.d.ts +0 -15
  187. package/dist/components/index.js +0 -2360
  188. package/dist/components/index.js.map +0 -1
  189. package/dist/components/index.mjs +0 -53
  190. package/dist/components/index.mjs.map +0 -1
  191. package/dist/components/manual-ui/chip-with-icon.d.ts +0 -10
  192. package/dist/components/manual-ui/chip-with-icon.js +0 -49
  193. package/dist/components/manual-ui/chip-with-icon.js.map +0 -1
  194. package/dist/components/manual-ui/chip-with-icon.mjs +0 -26
  195. package/dist/components/manual-ui/chip-with-icon.mjs.map +0 -1
  196. package/dist/components/source-search-box/source-search-box.d.ts +0 -16
  197. package/dist/components/source-search-box/source-search-box.js +0 -263
  198. package/dist/components/source-search-box/source-search-box.js.map +0 -1
  199. package/dist/components/source-search-box/source-search-box.mjs +0 -13
  200. package/dist/components/source-search-box/source-search-box.mjs.map +0 -1
  201. package/dist/components/ui/button.d.ts +0 -14
  202. package/dist/components/ui/button.js +0 -120
  203. package/dist/components/ui/button.js.map +0 -1
  204. package/dist/components/ui/button.mjs +0 -11
  205. package/dist/components/ui/button.mjs.map +0 -1
  206. package/dist/components/ui/command.d.ts +0 -53
  207. package/dist/components/ui/command.js +0 -323
  208. package/dist/components/ui/command.js.map +0 -1
  209. package/dist/components/ui/command.mjs +0 -26
  210. package/dist/components/ui/command.mjs.map +0 -1
  211. package/dist/components/ui/dialog.d.ts +0 -19
  212. package/dist/components/ui/dialog.js +0 -205
  213. package/dist/components/ui/dialog.js.map +0 -1
  214. package/dist/components/ui/dialog.mjs +0 -21
  215. package/dist/components/ui/dialog.mjs.map +0 -1
  216. package/dist/components/ui/label.d.ts +0 -8
  217. package/dist/components/ui/label.js +0 -93
  218. package/dist/components/ui/label.js.map +0 -1
  219. package/dist/components/ui/label.mjs +0 -9
  220. package/dist/components/ui/label.mjs.map +0 -1
  221. package/dist/context/index.d.ts +0 -2
  222. package/dist/context/index.js +0 -19
  223. package/dist/context/index.js.map +0 -1
  224. package/dist/context/index.mjs +0 -2
  225. package/dist/context/index.mjs.map +0 -1
  226. package/dist/hooks/base-copilot-textarea-implementation/use-autosuggestions.d.ts +0 -15
  227. package/dist/hooks/base-copilot-textarea-implementation/use-autosuggestions.js +0 -194
  228. package/dist/hooks/base-copilot-textarea-implementation/use-autosuggestions.js.map +0 -1
  229. package/dist/hooks/base-copilot-textarea-implementation/use-autosuggestions.mjs +0 -11
  230. package/dist/hooks/base-copilot-textarea-implementation/use-autosuggestions.mjs.map +0 -1
  231. package/dist/hooks/base-copilot-textarea-implementation/use-copilot-textarea-editor.d.ts +0 -8
  232. package/dist/hooks/base-copilot-textarea-implementation/use-copilot-textarea-editor.js +0 -194
  233. package/dist/hooks/base-copilot-textarea-implementation/use-copilot-textarea-editor.js.map +0 -1
  234. package/dist/hooks/base-copilot-textarea-implementation/use-copilot-textarea-editor.mjs +0 -9
  235. package/dist/hooks/base-copilot-textarea-implementation/use-copilot-textarea-editor.mjs.map +0 -1
  236. package/dist/hooks/base-copilot-textarea-implementation/use-populate-copilot-textarea-ref.d.ts +0 -7
  237. package/dist/hooks/base-copilot-textarea-implementation/use-populate-copilot-textarea-ref.js +0 -180
  238. package/dist/hooks/base-copilot-textarea-implementation/use-populate-copilot-textarea-ref.js.map +0 -1
  239. package/dist/hooks/base-copilot-textarea-implementation/use-populate-copilot-textarea-ref.mjs +0 -10
  240. package/dist/hooks/base-copilot-textarea-implementation/use-populate-copilot-textarea-ref.mjs.map +0 -1
  241. package/dist/hooks/index.d.ts +0 -2
  242. package/dist/hooks/index.js +0 -19
  243. package/dist/hooks/index.js.map +0 -1
  244. package/dist/hooks/index.mjs +0 -2
  245. package/dist/hooks/index.mjs.map +0 -1
  246. package/dist/hooks/make-autosuggestions-function/use-make-standard-autosuggestions-function.d.ts +0 -22
  247. package/dist/hooks/make-autosuggestions-function/use-make-standard-autosuggestions-function.js +0 -142
  248. package/dist/hooks/make-autosuggestions-function/use-make-standard-autosuggestions-function.js.map +0 -1
  249. package/dist/hooks/make-autosuggestions-function/use-make-standard-autosuggestions-function.mjs +0 -9
  250. package/dist/hooks/make-autosuggestions-function/use-make-standard-autosuggestions-function.mjs.map +0 -1
  251. package/dist/hooks/make-autosuggestions-function/use-make-standard-insertion-function.d.ts +0 -23
  252. package/dist/hooks/make-autosuggestions-function/use-make-standard-insertion-function.js +0 -248
  253. package/dist/hooks/make-autosuggestions-function/use-make-standard-insertion-function.js.map +0 -1
  254. package/dist/hooks/make-autosuggestions-function/use-make-standard-insertion-function.mjs +0 -9
  255. package/dist/hooks/make-autosuggestions-function/use-make-standard-insertion-function.mjs.map +0 -1
  256. package/dist/hooks/misc/use-autosize-textarea.d.ts +0 -5
  257. package/dist/hooks/misc/use-autosize-textarea.js +0 -37
  258. package/dist/hooks/misc/use-autosize-textarea.js.map +0 -1
  259. package/dist/hooks/misc/use-autosize-textarea.mjs +0 -8
  260. package/dist/hooks/misc/use-autosize-textarea.mjs.map +0 -1
  261. package/dist/index.d.ts +0 -15
  262. package/dist/index.js +0 -2365
  263. package/dist/index.js.map +0 -1
  264. package/dist/lib/debouncer.d.ts +0 -11
  265. package/dist/lib/debouncer.js +0 -76
  266. package/dist/lib/debouncer.js.map +0 -1
  267. package/dist/lib/debouncer.mjs +0 -8
  268. package/dist/lib/debouncer.mjs.map +0 -1
  269. package/dist/lib/editor-to-text.d.ts +0 -7
  270. package/dist/lib/editor-to-text.js +0 -69
  271. package/dist/lib/editor-to-text.js.map +0 -1
  272. package/dist/lib/editor-to-text.mjs +0 -8
  273. package/dist/lib/editor-to-text.mjs.map +0 -1
  274. package/dist/lib/get-text-around-cursor.d.ts +0 -15
  275. package/dist/lib/get-text-around-cursor.js +0 -131
  276. package/dist/lib/get-text-around-cursor.js.map +0 -1
  277. package/dist/lib/get-text-around-cursor.mjs +0 -14
  278. package/dist/lib/get-text-around-cursor.mjs.map +0 -1
  279. package/dist/lib/retry.d.ts +0 -3
  280. package/dist/lib/retry.js +0 -43
  281. package/dist/lib/retry.js.map +0 -1
  282. package/dist/lib/retry.mjs +0 -8
  283. package/dist/lib/retry.mjs.map +0 -1
  284. package/dist/lib/slatejs-edits/add-autocompletions.d.ts +0 -8
  285. package/dist/lib/slatejs-edits/add-autocompletions.js +0 -51
  286. package/dist/lib/slatejs-edits/add-autocompletions.js.map +0 -1
  287. package/dist/lib/slatejs-edits/add-autocompletions.mjs +0 -8
  288. package/dist/lib/slatejs-edits/add-autocompletions.mjs.map +0 -1
  289. package/dist/lib/slatejs-edits/clear-autocompletions.d.ts +0 -8
  290. package/dist/lib/slatejs-edits/clear-autocompletions.js +0 -49
  291. package/dist/lib/slatejs-edits/clear-autocompletions.js.map +0 -1
  292. package/dist/lib/slatejs-edits/clear-autocompletions.mjs +0 -8
  293. package/dist/lib/slatejs-edits/clear-autocompletions.mjs.map +0 -1
  294. package/dist/lib/slatejs-edits/replace-text.d.ts +0 -5
  295. package/dist/lib/slatejs-edits/replace-text.js +0 -53
  296. package/dist/lib/slatejs-edits/replace-text.js.map +0 -1
  297. package/dist/lib/slatejs-edits/replace-text.mjs +0 -8
  298. package/dist/lib/slatejs-edits/replace-text.mjs.map +0 -1
  299. package/dist/lib/slatejs-edits/with-partial-history.d.ts +0 -8
  300. package/dist/lib/slatejs-edits/with-partial-history.js +0 -133
  301. package/dist/lib/slatejs-edits/with-partial-history.js.map +0 -1
  302. package/dist/lib/slatejs-edits/with-partial-history.mjs +0 -10
  303. package/dist/lib/slatejs-edits/with-partial-history.mjs.map +0 -1
  304. package/dist/lib/stream-promise-flatten.d.ts +0 -12
  305. package/dist/lib/stream-promise-flatten.js +0 -72
  306. package/dist/lib/stream-promise-flatten.js.map +0 -1
  307. package/dist/lib/stream-promise-flatten.mjs +0 -8
  308. package/dist/lib/stream-promise-flatten.mjs.map +0 -1
  309. package/dist/lib/utils.d.ts +0 -9
  310. package/dist/lib/utils.js +0 -94
  311. package/dist/lib/utils.js.map +0 -1
  312. package/dist/lib/utils.mjs +0 -16
  313. package/dist/lib/utils.mjs.map +0 -1
  314. package/dist/types/autosuggestions-config/autosuggestions-config-user-specified.d.ts +0 -23
  315. package/dist/types/autosuggestions-config/autosuggestions-config-user-specified.js +0 -19
  316. package/dist/types/autosuggestions-config/autosuggestions-config-user-specified.js.map +0 -1
  317. package/dist/types/autosuggestions-config/autosuggestions-config-user-specified.mjs +0 -1
  318. package/dist/types/autosuggestions-config/autosuggestions-config-user-specified.mjs.map +0 -1
  319. package/dist/types/autosuggestions-config/autosuggestions-config.d.ts +0 -20
  320. package/dist/types/autosuggestions-config/autosuggestions-config.js +0 -287
  321. package/dist/types/autosuggestions-config/autosuggestions-config.js.map +0 -1
  322. package/dist/types/autosuggestions-config/autosuggestions-config.mjs +0 -13
  323. package/dist/types/autosuggestions-config/autosuggestions-config.mjs.map +0 -1
  324. package/dist/types/autosuggestions-config/editing-api-config.d.ts +0 -15
  325. package/dist/types/autosuggestions-config/editing-api-config.js +0 -108
  326. package/dist/types/autosuggestions-config/editing-api-config.js.map +0 -1
  327. package/dist/types/autosuggestions-config/editing-api-config.mjs +0 -12
  328. package/dist/types/autosuggestions-config/editing-api-config.mjs.map +0 -1
  329. package/dist/types/autosuggestions-config/index.d.ts +0 -10
  330. package/dist/types/autosuggestions-config/index.js +0 -287
  331. package/dist/types/autosuggestions-config/index.js.map +0 -1
  332. package/dist/types/autosuggestions-config/index.mjs +0 -14
  333. package/dist/types/autosuggestions-config/index.mjs.map +0 -1
  334. package/dist/types/autosuggestions-config/insertions-api-config.d.ts +0 -15
  335. package/dist/types/autosuggestions-config/insertions-api-config.js +0 -101
  336. package/dist/types/autosuggestions-config/insertions-api-config.js.map +0 -1
  337. package/dist/types/autosuggestions-config/insertions-api-config.mjs +0 -12
  338. package/dist/types/autosuggestions-config/insertions-api-config.mjs.map +0 -1
  339. package/dist/types/autosuggestions-config/subtypes/make-system-prompt.d.ts +0 -3
  340. package/dist/types/autosuggestions-config/subtypes/make-system-prompt.js +0 -19
  341. package/dist/types/autosuggestions-config/subtypes/make-system-prompt.js.map +0 -1
  342. package/dist/types/autosuggestions-config/subtypes/make-system-prompt.mjs +0 -1
  343. package/dist/types/autosuggestions-config/subtypes/make-system-prompt.mjs.map +0 -1
  344. package/dist/types/autosuggestions-config/suggestions-api-config.d.ts +0 -15
  345. package/dist/types/autosuggestions-config/suggestions-api-config.js +0 -90
  346. package/dist/types/autosuggestions-config/suggestions-api-config.js.map +0 -1
  347. package/dist/types/autosuggestions-config/suggestions-api-config.mjs +0 -12
  348. package/dist/types/autosuggestions-config/suggestions-api-config.mjs.map +0 -1
  349. package/dist/types/base/autosuggestion-state.d.ts +0 -8
  350. package/dist/types/base/autosuggestion-state.js +0 -19
  351. package/dist/types/base/autosuggestion-state.js.map +0 -1
  352. package/dist/types/base/autosuggestion-state.mjs +0 -1
  353. package/dist/types/base/autosuggestion-state.mjs.map +0 -1
  354. package/dist/types/base/autosuggestions-bare-function.d.ts +0 -19
  355. package/dist/types/base/autosuggestions-bare-function.js +0 -19
  356. package/dist/types/base/autosuggestions-bare-function.js.map +0 -1
  357. package/dist/types/base/autosuggestions-bare-function.mjs +0 -1
  358. package/dist/types/base/autosuggestions-bare-function.mjs.map +0 -1
  359. package/dist/types/base/base-autosuggestions-config.d.ts +0 -87
  360. package/dist/types/base/base-autosuggestions-config.js +0 -54
  361. package/dist/types/base/base-autosuggestions-config.js.map +0 -1
  362. package/dist/types/base/base-autosuggestions-config.mjs +0 -8
  363. package/dist/types/base/base-autosuggestions-config.mjs.map +0 -1
  364. package/dist/types/base/base-copilot-textarea-props.d.ts +0 -5
  365. package/dist/types/base/base-copilot-textarea-props.js +0 -19
  366. package/dist/types/base/base-copilot-textarea-props.js.map +0 -1
  367. package/dist/types/base/base-copilot-textarea-props.mjs +0 -1
  368. package/dist/types/base/base-copilot-textarea-props.mjs.map +0 -1
  369. package/dist/types/base/custom-editor.d.ts +0 -29
  370. package/dist/types/base/custom-editor.js +0 -19
  371. package/dist/types/base/custom-editor.js.map +0 -1
  372. package/dist/types/base/custom-editor.mjs +0 -1
  373. package/dist/types/base/custom-editor.mjs.map +0 -1
  374. package/dist/types/base/editor-autocomplete-state.d.ts +0 -10
  375. package/dist/types/base/editor-autocomplete-state.js +0 -40
  376. package/dist/types/base/editor-autocomplete-state.js.map +0 -1
  377. package/dist/types/base/editor-autocomplete-state.mjs +0 -9
  378. package/dist/types/base/editor-autocomplete-state.mjs.map +0 -1
  379. package/dist/types/base/index.d.ts +0 -54
  380. package/dist/types/base/index.js +0 -56
  381. package/dist/types/base/index.js.map +0 -1
  382. package/dist/types/base/index.mjs +0 -9
  383. package/dist/types/base/index.mjs.map +0 -1
  384. package/dist/types/html-copilot-textarea-element.d.ts +0 -7
  385. package/dist/types/html-copilot-textarea-element.js +0 -19
  386. package/dist/types/html-copilot-textarea-element.js.map +0 -1
  387. package/dist/types/html-copilot-textarea-element.mjs +0 -2
  388. package/dist/types/html-copilot-textarea-element.mjs.map +0 -1
  389. package/dist/types/index.d.ts +0 -13
  390. package/dist/types/index.js +0 -289
  391. package/dist/types/index.js.map +0 -1
  392. package/dist/types/index.mjs +0 -19
  393. package/dist/types/index.mjs.map +0 -1
  394. package/jest.config.js +0 -5
  395. package/rollup.config.mjs +0 -64
  396. package/tsup.config.ts +0 -15
package/dist/index.cjs ADDED
@@ -0,0 +1,1918 @@
1
+ "use client";
2
+
3
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4
+ //#region \0rolldown/runtime.js
5
+ var __create = Object.create;
6
+ var __defProp = Object.defineProperty;
7
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
8
+ var __getOwnPropNames = Object.getOwnPropertyNames;
9
+ var __getProtoOf = Object.getPrototypeOf;
10
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
14
+ key = keys[i];
15
+ if (!__hasOwnProp.call(to, key) && key !== except) {
16
+ __defProp(to, key, {
17
+ get: ((k) => from[k]).bind(null, key),
18
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
19
+ });
20
+ }
21
+ }
22
+ }
23
+ return to;
24
+ };
25
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
26
+ value: mod,
27
+ enumerable: true
28
+ }) : target, mod));
29
+
30
+ //#endregion
31
+ let react = require("react");
32
+ react = __toESM(react);
33
+ let slate = require("slate");
34
+ let slate_react = require("slate-react");
35
+ let tailwind_merge = require("tailwind-merge");
36
+ let clsx = require("clsx");
37
+ let slate_history = require("slate-history");
38
+ let _copilotkit_react_core = require("@copilotkit/react-core");
39
+ let _copilotkit_shared = require("@copilotkit/shared");
40
+ let react_jsx_runtime = require("react/jsx-runtime");
41
+ let _emotion_css = require("@emotion/css");
42
+ let react_dom = require("react-dom");
43
+ react_dom = __toESM(react_dom);
44
+ let cmdk = require("cmdk");
45
+ let _radix_ui_react_slot = require("@radix-ui/react-slot");
46
+ let class_variance_authority = require("class-variance-authority");
47
+ let _radix_ui_react_label = require("@radix-ui/react-label");
48
+ _radix_ui_react_label = __toESM(_radix_ui_react_label);
49
+ let _mui_material_Chip_Chip_js = require("@mui/material/Chip/Chip.js");
50
+ _mui_material_Chip_Chip_js = __toESM(_mui_material_Chip_Chip_js);
51
+ let _mui_material_Avatar_Avatar_js = require("@mui/material/Avatar/Avatar.js");
52
+ _mui_material_Avatar_Avatar_js = __toESM(_mui_material_Avatar_Avatar_js);
53
+ let _copilotkit_runtime_client_gql = require("@copilotkit/runtime-client-gql");
54
+ let lodash_merge = require("lodash.merge");
55
+ lodash_merge = __toESM(lodash_merge);
56
+
57
+ //#region src/lib/debouncer.ts
58
+ var Debouncer = class {
59
+ constructor(wait) {
60
+ this.wait = wait;
61
+ this.debounce = async (func, ...args) => {
62
+ this.cancel();
63
+ this.timeoutId = setTimeout(async () => {
64
+ try {
65
+ this.activeAbortController = new AbortController();
66
+ await func(...args, this.activeAbortController.signal);
67
+ this.activeAbortController = void 0;
68
+ } catch (error) {}
69
+ }, this.wait);
70
+ };
71
+ this.cancel = () => {
72
+ if (this.activeAbortController) {
73
+ this.activeAbortController.abort();
74
+ this.activeAbortController = void 0;
75
+ }
76
+ if (this.timeoutId !== void 0) {
77
+ clearTimeout(this.timeoutId);
78
+ this.timeoutId = void 0;
79
+ }
80
+ };
81
+ }
82
+ };
83
+
84
+ //#endregion
85
+ //#region src/lib/utils.ts
86
+ function cn(...inputs) {
87
+ return (0, tailwind_merge.twMerge)((0, clsx.clsx)(inputs));
88
+ }
89
+ const arraysAreEqual = (arr1, arr2) => arr1.length === arr2.length && arr1.every((value, index) => value === arr2[index]);
90
+ function nullableCompatibleEqualityCheck(naiveEqualityCheck, a, b) {
91
+ if (a === null || a === void 0 || b === null || b === void 0) return a === b;
92
+ return naiveEqualityCheck(a, b);
93
+ }
94
+
95
+ //#endregion
96
+ //#region src/types/base/editor-autocomplete-state.ts
97
+ function areEqual_autocompleteState(prev, next) {
98
+ return prev.cursorPoint.offset === next.cursorPoint.offset && arraysAreEqual(prev.cursorPoint.path, next.cursorPoint.path) && prev.textBeforeCursor === next.textBeforeCursor && prev.textAfterCursor === next.textAfterCursor;
99
+ }
100
+
101
+ //#endregion
102
+ //#region src/hooks/base-copilot-textarea-implementation/use-autosuggestions.ts
103
+ function useAutosuggestions(debounceTime, shouldAcceptAutosuggestionOnKeyPress, shouldAcceptAutosuggestionOnTouch, autosuggestionFunction, insertAutocompleteSuggestion, disableWhenEmpty, disabled) {
104
+ const [previousAutocompleteState, setPreviousAutocompleteState] = (0, react.useState)(null);
105
+ const [currentAutocompleteSuggestion, setCurrentAutocompleteSuggestion] = (0, react.useState)(null);
106
+ const awaitForAndAppendSuggestion = (0, react.useCallback)(async (editorAutocompleteState, abortSignal) => {
107
+ if (disabled) return;
108
+ if (disableWhenEmpty && editorAutocompleteState.textBeforeCursor === "" && editorAutocompleteState.textAfterCursor === "") return;
109
+ const suggestion = await autosuggestionFunction(editorAutocompleteState, abortSignal);
110
+ if (!suggestion || abortSignal.aborted) throw new DOMException("Aborted", "AbortError");
111
+ setCurrentAutocompleteSuggestion({
112
+ text: suggestion,
113
+ point: editorAutocompleteState.cursorPoint
114
+ });
115
+ }, [
116
+ autosuggestionFunction,
117
+ setCurrentAutocompleteSuggestion,
118
+ disableWhenEmpty,
119
+ disabled
120
+ ]);
121
+ const debouncedFunction = (0, react.useMemo)(() => new Debouncer(debounceTime), [debounceTime]);
122
+ (0, react.useEffect)(() => {
123
+ return () => {
124
+ debouncedFunction.cancel();
125
+ setCurrentAutocompleteSuggestion(null);
126
+ };
127
+ }, [debouncedFunction, disabled]);
128
+ const onChange = (0, react.useCallback)((newEditorState) => {
129
+ const editorStateHasChanged = !nullableCompatibleEqualityCheck(areEqual_autocompleteState, previousAutocompleteState, newEditorState);
130
+ setPreviousAutocompleteState(newEditorState);
131
+ if (!editorStateHasChanged) return;
132
+ setCurrentAutocompleteSuggestion(null);
133
+ if (newEditorState) debouncedFunction.debounce(awaitForAndAppendSuggestion, newEditorState);
134
+ else debouncedFunction.cancel();
135
+ }, [
136
+ previousAutocompleteState,
137
+ setPreviousAutocompleteState,
138
+ debouncedFunction,
139
+ awaitForAndAppendSuggestion,
140
+ setCurrentAutocompleteSuggestion
141
+ ]);
142
+ const keyDownOrTouchHandler = (0, react.useCallback)((event) => {
143
+ if (currentAutocompleteSuggestion) {
144
+ if (event.type === "touchstart" ? shouldAcceptAutosuggestionOnTouch(event) : shouldAcceptAutosuggestionOnKeyPress(event)) {
145
+ event.preventDefault();
146
+ insertAutocompleteSuggestion(currentAutocompleteSuggestion);
147
+ setCurrentAutocompleteSuggestion(null);
148
+ }
149
+ }
150
+ }, [
151
+ currentAutocompleteSuggestion,
152
+ setCurrentAutocompleteSuggestion,
153
+ insertAutocompleteSuggestion,
154
+ shouldAcceptAutosuggestionOnKeyPress
155
+ ]);
156
+ return {
157
+ currentAutocompleteSuggestion,
158
+ onChangeHandler: onChange,
159
+ onKeyDownHandler: keyDownOrTouchHandler,
160
+ onTouchStartHandler: keyDownOrTouchHandler
161
+ };
162
+ }
163
+
164
+ //#endregion
165
+ //#region src/lib/slatejs-edits/with-partial-history.ts
166
+ const withPartialHistory = (editor, shouldSave) => {
167
+ const e = editor;
168
+ const { apply } = e;
169
+ e.history = {
170
+ undos: [],
171
+ redos: []
172
+ };
173
+ e.redo = () => {
174
+ const { history } = e;
175
+ const { redos } = history;
176
+ if (redos.length > 0) {
177
+ const batch = redos[redos.length - 1];
178
+ if (batch.selectionBefore) slate.Transforms.setSelection(e, batch.selectionBefore);
179
+ slate_history.HistoryEditor.withoutSaving(e, () => {
180
+ slate.Editor.withoutNormalizing(e, () => {
181
+ for (const op of batch.operations) e.apply(op);
182
+ });
183
+ });
184
+ history.redos.pop();
185
+ e.writeHistory("undos", batch);
186
+ }
187
+ };
188
+ e.undo = () => {
189
+ const { history } = e;
190
+ const { undos } = history;
191
+ if (undos.length > 0) {
192
+ const batch = undos[undos.length - 1];
193
+ slate_history.HistoryEditor.withoutSaving(e, () => {
194
+ slate.Editor.withoutNormalizing(e, () => {
195
+ const inverseOps = batch.operations.map(slate.Operation.inverse).reverse();
196
+ for (const op of inverseOps) e.apply(op);
197
+ if (batch.selectionBefore) slate.Transforms.setSelection(e, batch.selectionBefore);
198
+ });
199
+ });
200
+ e.writeHistory("redos", batch);
201
+ history.undos.pop();
202
+ }
203
+ };
204
+ e.apply = (op) => {
205
+ const { operations, history } = e;
206
+ const { undos } = history;
207
+ const lastBatch = undos[undos.length - 1];
208
+ const lastOp = lastBatch && lastBatch.operations[lastBatch.operations.length - 1];
209
+ let save = slate_history.HistoryEditor.isSaving(e);
210
+ let merge = slate_history.HistoryEditor.isMerging(e);
211
+ if (save == null) save = shouldSave(op, lastOp);
212
+ if (save) {
213
+ if (merge == null) if (lastBatch == null) merge = false;
214
+ else if (operations.length !== 0) merge = true;
215
+ else merge = shouldMerge(op, lastOp);
216
+ if (lastBatch && merge) lastBatch.operations.push(op);
217
+ else {
218
+ const batch = {
219
+ operations: [op],
220
+ selectionBefore: e.selection
221
+ };
222
+ e.writeHistory("undos", batch);
223
+ }
224
+ while (undos.length > 100) undos.shift();
225
+ history.redos = [];
226
+ }
227
+ apply(op);
228
+ };
229
+ e.writeHistory = (stack, batch) => {
230
+ e.history[stack].push(batch);
231
+ };
232
+ return e;
233
+ };
234
+ /**
235
+ * Check whether to merge an operation into the previous operation.
236
+ */
237
+ const shouldMerge = (op, prev) => {
238
+ if (prev && op.type === "insert_text" && prev.type === "insert_text" && op.offset === prev.offset + prev.text.length && slate.Path.equals(op.path, prev.path)) return true;
239
+ if (prev && op.type === "remove_text" && prev.type === "remove_text" && op.offset + op.text.length === prev.offset && slate.Path.equals(op.path, prev.path)) return true;
240
+ return false;
241
+ };
242
+ const defaultShouldSave = (op, prev) => {
243
+ if (op.type === "set_selection") return false;
244
+ return true;
245
+ };
246
+
247
+ //#endregion
248
+ //#region src/hooks/base-copilot-textarea-implementation/use-copilot-textarea-editor.tsx
249
+ const shouldSave = (op, prev) => {
250
+ const excludedNodeType = "suggestion";
251
+ if (op.type === "insert_node" && slate.Element.isElement(op.node) && op.node.type === excludedNodeType) return false;
252
+ if (op.type === "remove_node" && slate.Element.isElement(op.node) && op.node.type === excludedNodeType) return false;
253
+ if (op.type === "set_node" && "type" in op.newProperties && op.newProperties.type === excludedNodeType) return false;
254
+ if (op.type == "set_node" && "type" in op.properties && op.properties.type === excludedNodeType) return false;
255
+ if (op.type === "merge_node" && "type" in op.properties && op.properties.type === excludedNodeType) return false;
256
+ if (op.type === "split_node" && "type" in op.properties && op.properties.type === excludedNodeType) return false;
257
+ return defaultShouldSave(op, prev);
258
+ };
259
+ function useCopilotTextareaEditor() {
260
+ return (0, react.useMemo)(() => {
261
+ const editor = withPartialHistory((0, slate_react.withReact)((0, slate.createEditor)()), shouldSave);
262
+ const { isVoid } = editor;
263
+ editor.isVoid = (element) => {
264
+ switch (element.type) {
265
+ case "suggestion": return true;
266
+ default: return isVoid(element);
267
+ }
268
+ };
269
+ const { markableVoid } = editor;
270
+ editor.markableVoid = (element) => {
271
+ switch (element.type) {
272
+ case "suggestion": return true;
273
+ default: return markableVoid(element);
274
+ }
275
+ };
276
+ const { isInline } = editor;
277
+ editor.isInline = (element) => {
278
+ switch (element.type) {
279
+ case "suggestion": return element.inline;
280
+ default: return isInline(element);
281
+ }
282
+ };
283
+ return editor;
284
+ }, []);
285
+ }
286
+
287
+ //#endregion
288
+ //#region src/lib/get-text-around-cursor.ts
289
+ function getTextAroundCollapsedCursor(editor) {
290
+ const { selection } = editor;
291
+ if (!selection || !slate.Range.isCollapsed(selection)) return null;
292
+ const cursorPoint = selection.anchor;
293
+ const beforeRange = {
294
+ anchor: slate.Editor.start(editor, []),
295
+ focus: cursorPoint
296
+ };
297
+ const afterRange = {
298
+ anchor: cursorPoint,
299
+ focus: slate.Editor.end(editor, [])
300
+ };
301
+ return {
302
+ cursorPoint,
303
+ textBeforeCursor: extractTextWithNewlines(editor, beforeRange),
304
+ textAfterCursor: extractTextWithNewlines(editor, afterRange)
305
+ };
306
+ }
307
+ function getTextAroundSelection(editor) {
308
+ const { selection } = editor;
309
+ if (!selection) return null;
310
+ const wellOrderedSelection = wellOrderedRange(selection);
311
+ const beforeRange = {
312
+ anchor: slate.Editor.start(editor, []),
313
+ focus: wellOrderedSelection.anchor
314
+ };
315
+ const afterRange = {
316
+ anchor: wellOrderedSelection.focus,
317
+ focus: slate.Editor.end(editor, [])
318
+ };
319
+ const before = extractTextWithNewlines(editor, beforeRange);
320
+ const after = extractTextWithNewlines(editor, afterRange);
321
+ return {
322
+ selection: wellOrderedSelection,
323
+ textBeforeCursor: before,
324
+ selectedText: extractTextWithNewlines(editor, wellOrderedSelection),
325
+ textAfterCursor: after
326
+ };
327
+ }
328
+ function getFullEditorTextWithNewlines(editor) {
329
+ return extractTextWithNewlines(editor, {
330
+ anchor: slate.Editor.start(editor, []),
331
+ focus: slate.Editor.end(editor, [])
332
+ });
333
+ }
334
+ function extractTextWithNewlines(editor, range) {
335
+ const voids = false;
336
+ const [start, end] = slate.Range.edges(range);
337
+ let text = "";
338
+ let lastBlock = null;
339
+ for (const [node, path] of slate.Editor.nodes(editor, {
340
+ at: range,
341
+ match: slate.Text.isText,
342
+ voids
343
+ })) {
344
+ let t = node.text;
345
+ const [block] = slate.Editor.above(editor, {
346
+ at: path,
347
+ match: (n) => slate.Element.isElement(n) && n.type === "paragraph"
348
+ }) || [null];
349
+ if (lastBlock !== block && block) {
350
+ if (lastBlock) text += "\n";
351
+ lastBlock = block;
352
+ }
353
+ if (slate.Path.equals(path, end.path)) t = t.slice(0, end.offset);
354
+ if (slate.Path.equals(path, start.path)) t = t.slice(start.offset);
355
+ text += t;
356
+ }
357
+ return text;
358
+ }
359
+ function wellOrderedRange(range) {
360
+ const { anchor, focus } = range;
361
+ if (slate.Point.isBefore(anchor, focus)) return range;
362
+ return {
363
+ anchor: focus,
364
+ focus: anchor
365
+ };
366
+ }
367
+
368
+ //#endregion
369
+ //#region src/lib/slatejs-edits/replace-text.ts
370
+ function replaceEditorText(editor, newText) {
371
+ slate.Transforms.delete(editor, { at: {
372
+ anchor: slate.Editor.start(editor, []),
373
+ focus: slate.Editor.end(editor, [])
374
+ } });
375
+ if (newText && newText !== "") slate.Transforms.insertNodes(editor, [{
376
+ type: "paragraph",
377
+ children: [{ text: newText }]
378
+ }], { at: [0] });
379
+ }
380
+
381
+ //#endregion
382
+ //#region src/hooks/base-copilot-textarea-implementation/use-populate-copilot-textarea-ref.ts
383
+ function usePopulateCopilotTextareaRef(editor, ref) {
384
+ react.default.useImperativeHandle(ref, () => {
385
+ class Combined {
386
+ constructor(customMethods, editorHtmlElement) {
387
+ this.customMethods = customMethods;
388
+ this.editorHtmlElement = editorHtmlElement;
389
+ }
390
+ get(target, propKey) {
391
+ if (this.isKeyOfCustomMethods(propKey)) {
392
+ const value = this.customMethods[propKey];
393
+ if (typeof value === "function") return value.bind(this.customMethods);
394
+ return value;
395
+ } else if (this.isKeyOfHTMLElement(propKey)) {
396
+ const value = this.editorHtmlElement[propKey];
397
+ if (typeof value === "function") return value.bind(this.editorHtmlElement);
398
+ return value;
399
+ }
400
+ }
401
+ set(target, propKey, value) {
402
+ if (this.isKeyOfCustomMethods(propKey)) this.customMethods[propKey] = value;
403
+ else if (this.isKeyOfHTMLElement(propKey)) this.editorHtmlElement[propKey] = value;
404
+ else target[propKey] = value;
405
+ return true;
406
+ }
407
+ isKeyOfCustomMethods(key) {
408
+ return key in this.customMethods;
409
+ }
410
+ isKeyOfHTMLElement(key) {
411
+ return key in this.editorHtmlElement;
412
+ }
413
+ }
414
+ const handler = {
415
+ get(target, propKey) {
416
+ return target.get(target, propKey);
417
+ },
418
+ set(target, propKey, value) {
419
+ return target.set(target, propKey, value);
420
+ }
421
+ };
422
+ class CustomMethods {
423
+ constructor(editor) {
424
+ this.editor = editor;
425
+ }
426
+ focus() {
427
+ slate_react.ReactEditor.focus(this.editor);
428
+ }
429
+ blur() {
430
+ slate_react.ReactEditor.blur(this.editor);
431
+ }
432
+ get value() {
433
+ return getFullEditorTextWithNewlines(this.editor);
434
+ }
435
+ set value(value) {
436
+ replaceEditorText(this.editor, value);
437
+ }
438
+ }
439
+ const editorHtmlElement = slate_react.ReactEditor.toDOMNode(editor, editor);
440
+ const combined = new Combined(new CustomMethods(editor), editorHtmlElement);
441
+ return new Proxy(combined, handler);
442
+ }, [editor]);
443
+ }
444
+
445
+ //#endregion
446
+ //#region src/lib/slatejs-edits/add-autocompletions.ts
447
+ function addAutocompletionsToEditor(editor, newSuggestion, point) {
448
+ const editorPosition = editor.selection;
449
+ slate.Transforms.insertNodes(editor, [{
450
+ type: "suggestion",
451
+ inline: true,
452
+ content: newSuggestion,
453
+ children: [{ text: "" }]
454
+ }], { at: point });
455
+ if (editorPosition) editor.selection = editorPosition;
456
+ }
457
+
458
+ //#endregion
459
+ //#region src/lib/slatejs-edits/clear-autocompletions.ts
460
+ function clearAutocompletionsFromEditor(editor) {
461
+ const paths = [];
462
+ for (const [node, path] of slate.Node.nodes(editor)) if (slate.Element.isElement(node) && node.type === "suggestion") paths.push(path);
463
+ for (const path of paths) try {
464
+ slate.Transforms.removeNodes(editor, { at: path });
465
+ } catch (e) {
466
+ console.log("CopilotTextarea.clearAutocompletionsFromEditor: error removing node", e);
467
+ }
468
+ }
469
+
470
+ //#endregion
471
+ //#region src/types/base/base-autosuggestions-config.tsx
472
+ const defaultShouldToggleHoveringEditorOnKeyPress = (event, shortcut) => {
473
+ const isMetaKey = (0, _copilotkit_shared.isMacOS)() ? event.metaKey : event.ctrlKey;
474
+ return event.key === shortcut && isMetaKey;
475
+ };
476
+ const defaultShouldAcceptAutosuggestionOnKeyPress = (event) => {
477
+ if (event.key === "Tab") return true;
478
+ return false;
479
+ };
480
+ const defaultShouldAcceptAutosuggestionOnTouch = () => false;
481
+ /**
482
+ * Default configuration for the BaseAutosuggestions.
483
+ *
484
+ * @property {number} debounceTime - The amount of time to wait before triggering the autosuggestions API call.
485
+ * @property {string[]} contextCategories - The categories to use for context when making the autosuggestions API call.
486
+ * @property {boolean} disableWhenEmpty - Whether to disable the autosuggestions when the textarea is empty.
487
+ * @property {boolean} disabled - Whether to disable the autosuggestions feature entirely.
488
+ * @property {boolean} temporarilyDisableWhenMovingCursorWithoutChangingText - Whether to temporarily disable the autosuggestions when the cursor is moved without changing the text.
489
+ * @property {boolean} temporarilyDisableNotTrustedEvents - Temporarily disable the autosuggestions after change event from non-trusted sources (like text insertion from autocomplete plugins)
490
+ * @property {(event: React.KeyboardEvent<HTMLDivElement>) => boolean} shouldToggleHoveringEditorOnKeyPress - A function that determines whether to toggle the hovering editor based on a key press event.
491
+ * @property {(event: React.KeyboardEvent<HTMLDivElement>) => boolean} shouldAcceptAutosuggestionOnKeyPress - A function that determines whether to accept the autosuggestion based on a key press event.
492
+ * @property {() => boolean} defaultShouldAcceptAutosuggestionOnTouch - A function that determines whether to accept the autosuggestion based on a mobile touch event.
493
+ */
494
+ const defaultBaseAutosuggestionsConfig = {
495
+ debounceTime: 250,
496
+ contextCategories: _copilotkit_react_core.defaultCopilotContextCategories,
497
+ disableWhenEmpty: true,
498
+ disabled: false,
499
+ temporarilyDisableWhenMovingCursorWithoutChangingText: true,
500
+ temporarilyDisableNotTrustedEvents: true,
501
+ shouldToggleHoveringEditorOnKeyPress: defaultShouldToggleHoveringEditorOnKeyPress,
502
+ shouldAcceptAutosuggestionOnKeyPress: defaultShouldAcceptAutosuggestionOnKeyPress,
503
+ shouldAcceptAutosuggestionOnTouch: defaultShouldAcceptAutosuggestionOnTouch
504
+ };
505
+
506
+ //#endregion
507
+ //#region src/components/hovering-toolbar/hovering-editor-provider.tsx
508
+ const HoveringEditorContext = (0, react.createContext)({
509
+ isDisplayed: false,
510
+ setIsDisplayed: () => {}
511
+ });
512
+ /**
513
+ * A context provider for the hovering editor over the `CopilotTextarea`
514
+ * (used to edit and insert text into the `CopilotTextarea`).
515
+ */
516
+ const HoveringEditorProvider = ({ children }) => {
517
+ const [isDisplayed, setIsDisplayed] = (0, react.useState)(false);
518
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(HoveringEditorContext.Provider, {
519
+ value: {
520
+ isDisplayed,
521
+ setIsDisplayed
522
+ },
523
+ children
524
+ });
525
+ };
526
+ const useHoveringEditorContext = () => (0, react.useContext)(HoveringEditorContext);
527
+
528
+ //#endregion
529
+ //#region src/components/hovering-toolbar/hovering-toolbar-components.tsx
530
+ const Button$1 = react.default.forwardRef(({ className, active, reversed, ...props }, ref) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
531
+ ...props,
532
+ ref,
533
+ className: (0, _emotion_css.cx)(className, _emotion_css.css`
534
+ cursor: pointer;
535
+ color: ${reversed ? active ? "white" : "#aaa" : active ? "black" : "#ccc"};
536
+ `)
537
+ }));
538
+ const Icon = react.default.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
539
+ ...props,
540
+ ref,
541
+ className: (0, _emotion_css.cx)("material-icons", className, _emotion_css.css`
542
+ font-size: 18px;
543
+ vertical-align: text-bottom;
544
+ `)
545
+ }));
546
+ const Menu = react.default.forwardRef(({ className, ...props }, ref) => {
547
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
548
+ ...props,
549
+ "data-testid": "menu",
550
+ ref,
551
+ className: (0, _emotion_css.cx)(className, _emotion_css.css`
552
+ & > * {
553
+ display: inline-block;
554
+ }
555
+
556
+ & > * + * {
557
+ margin-left: 15px;
558
+ }
559
+ `)
560
+ });
561
+ });
562
+ const Portal = ({ children }) => {
563
+ return typeof document === "object" ? react_dom.default.createPortal(children, document.body) : null;
564
+ };
565
+ const Toolbar = react.default.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Menu, {
566
+ ...props,
567
+ ref,
568
+ className: (0, _emotion_css.cx)(className, _emotion_css.css`
569
+ position: relative;
570
+ padding: 1px 18px 17px;
571
+ margin: 0 -20px;
572
+ border-bottom: 2px solid #eee;
573
+ margin-bottom: 20px;
574
+ `)
575
+ }));
576
+
577
+ //#endregion
578
+ //#region src/hooks/misc/use-autosize-textarea.tsx
579
+ const useAutosizeTextArea = (textAreaRef, value) => {
580
+ (0, react.useEffect)(() => {
581
+ if (textAreaRef.current !== null) {
582
+ textAreaRef.current.style.height = "0px";
583
+ const scrollHeight = textAreaRef.current.scrollHeight;
584
+ textAreaRef.current.style.height = scrollHeight + "px";
585
+ }
586
+ }, [textAreaRef, value]);
587
+ };
588
+
589
+ //#endregion
590
+ //#region src/components/ui/command.tsx
591
+ const Command = react.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(cmdk.Command, {
592
+ ref,
593
+ className: cn("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground", className),
594
+ ...props
595
+ }));
596
+ Command.displayName = cmdk.Command.displayName;
597
+ const CommandInput = react.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
598
+ className: "flex items-center border-b px-3",
599
+ "cmdk-input-wrapper": "",
600
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(cmdk.Command.Input, {
601
+ ref,
602
+ className: cn("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", className),
603
+ ...props
604
+ })
605
+ }));
606
+ CommandInput.displayName = cmdk.Command.Input.displayName;
607
+ const CommandList = react.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(cmdk.Command.List, {
608
+ ref,
609
+ className: cn("max-h-[300px] overflow-y-auto overflow-x-hidden pb-2", className),
610
+ ...props
611
+ }));
612
+ CommandList.displayName = cmdk.Command.List.displayName;
613
+ const CommandEmpty = react.forwardRef((props, ref) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(cmdk.Command.Empty, {
614
+ ref,
615
+ className: "py-6 text-center text-sm",
616
+ ...props
617
+ }));
618
+ CommandEmpty.displayName = cmdk.Command.Empty.displayName;
619
+ const CommandGroup = react.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(cmdk.Command.Group, {
620
+ ref,
621
+ className: cn("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", className),
622
+ ...props
623
+ }));
624
+ CommandGroup.displayName = cmdk.Command.Group.displayName;
625
+ const CommandSeparator = react.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(cmdk.Command.Separator, {
626
+ ref,
627
+ className: cn("-mx-1 h-px bg-border", className),
628
+ ...props
629
+ }));
630
+ CommandSeparator.displayName = cmdk.Command.Separator.displayName;
631
+ const CommandItem = react.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(cmdk.Command.Item, {
632
+ ref,
633
+ className: cn("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", className),
634
+ ...props
635
+ }));
636
+ CommandItem.displayName = cmdk.Command.Item.displayName;
637
+ const CommandShortcut = ({ className, ...props }) => {
638
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
639
+ className: cn("ml-auto text-xs tracking-widest text-muted-foreground", className),
640
+ ...props
641
+ });
642
+ };
643
+ CommandShortcut.displayName = "CommandShortcut";
644
+
645
+ //#endregion
646
+ //#region src/components/source-search-box/source-search-box.tsx
647
+ function SourceSearchBox(props) {
648
+ const [selectedValue, setSelectedValue] = (0, react.useState)("");
649
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Command, {
650
+ className: "rounded-lg border shadow-md",
651
+ value: selectedValue,
652
+ onValueChange: (value) => {
653
+ setSelectedValue(value);
654
+ },
655
+ filter: (value, search) => {
656
+ if (props.searchTerm === "") return 1;
657
+ if (value.startsWith(props.searchTerm)) return 1;
658
+ return 0;
659
+ },
660
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(CommandInput, {
661
+ value: props.searchTerm,
662
+ className: "rounded-t-lg hidden",
663
+ placeholder: "Search for a command..."
664
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(CommandList, { children: [
665
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CommandEmpty, { children: "No results found." }),
666
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CommandGroup, {
667
+ heading: "Available resources",
668
+ children: props.suggestedFiles.map((filePointer) => {
669
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CommandItem, {
670
+ value: filePointer.name,
671
+ onSelect: (value) => {
672
+ props.onSelectedFile(filePointer);
673
+ },
674
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
675
+ className: " px-3 flex flex-row gap-1 items-center",
676
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Logo, {
677
+ width: "20px",
678
+ height: "20px",
679
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("img", {
680
+ src: filePointer.iconImageUri,
681
+ alt: filePointer.sourceApplication,
682
+ className: "w-full h-full"
683
+ })
684
+ }), filePointer.name]
685
+ })
686
+ }, `word-${filePointer.sourceApplication}.${filePointer.name}`);
687
+ })
688
+ }),
689
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CommandSeparator, {})
690
+ ] })]
691
+ });
692
+ }
693
+ function Logo({ children, width, height }) {
694
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
695
+ className: "flex items-center justify-center",
696
+ style: {
697
+ width,
698
+ height
699
+ },
700
+ children
701
+ });
702
+ }
703
+
704
+ //#endregion
705
+ //#region src/components/ui/button.tsx
706
+ const buttonVariants = (0, class_variance_authority.cva)("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", {
707
+ variants: {
708
+ variant: {
709
+ default: "bg-primary text-primary-foreground hover:bg-primary/90",
710
+ destructive: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
711
+ outline: "border border-input bg-background hover:bg-accent hover:text-accent-foreground",
712
+ secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
713
+ ghost: "hover:bg-accent hover:text-accent-foreground",
714
+ link: "text-primary underline-offset-4 hover:underline"
715
+ },
716
+ size: {
717
+ default: "h-10 px-4 py-2",
718
+ sm: "h-9 rounded-md px-3",
719
+ lg: "h-11 rounded-md px-8",
720
+ icon: "h-10 w-10"
721
+ }
722
+ },
723
+ defaultVariants: {
724
+ variant: "default",
725
+ size: "default"
726
+ }
727
+ });
728
+ const Button = react.forwardRef(({ className, variant, size, asChild = false, ...props }, ref) => {
729
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(asChild ? _radix_ui_react_slot.Slot : "button", {
730
+ className: cn(buttonVariants({
731
+ variant,
732
+ size,
733
+ className
734
+ })),
735
+ ref,
736
+ ...props
737
+ });
738
+ });
739
+ Button.displayName = "Button";
740
+
741
+ //#endregion
742
+ //#region src/components/ui/label.tsx
743
+ const labelVariants = (0, class_variance_authority.cva)("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70");
744
+ const Label = react.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_radix_ui_react_label.Root, {
745
+ ref,
746
+ className: cn(labelVariants(), className),
747
+ ...props
748
+ }));
749
+ Label.displayName = _radix_ui_react_label.Root.displayName;
750
+
751
+ //#endregion
752
+ //#region src/lib/stream-promise-flatten.ts
753
+ /**
754
+ * Flatten a promise of a stream, into a stream.
755
+ *
756
+ * Useful because a stream already includes the notion of async value delivery,
757
+ * so it often makes sense to simply await the values rather than the generator of the values.
758
+ *
759
+ * @param {Promise<ReadableStream<A>>} promise - The promise to flatten.
760
+ * @returns {ReadableStream<A>} - The flattened stream.
761
+ */
762
+ function streamPromiseFlatten(promise) {
763
+ return new ReadableStream({ async start(controller) {
764
+ try {
765
+ const reader = (await promise).getReader();
766
+ while (true) {
767
+ const { done, value } = await reader.read();
768
+ if (done) {
769
+ controller.close();
770
+ return;
771
+ }
772
+ controller.enqueue(value);
773
+ }
774
+ } catch (error) {
775
+ controller.error(error);
776
+ }
777
+ } });
778
+ }
779
+
780
+ //#endregion
781
+ //#region src/components/hovering-toolbar/text-insertion-prompt-box/included-files-preview.tsx
782
+ const IncludedFilesPreview = ({ includedFiles, setIncludedFiles }) => {
783
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
784
+ className: "flex flex-col gap-2 mt-2",
785
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Label, {
786
+ className: "",
787
+ children: "Included context:"
788
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
789
+ className: "flex flex-wrap gap-2",
790
+ children: includedFiles.map((filePointer, index) => {
791
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(FileChipPreview, {
792
+ filePointer,
793
+ onDelete: () => {
794
+ setIncludedFiles((prev) => prev.filter((fp) => fp !== filePointer));
795
+ }
796
+ }, `file-${filePointer.sourceApplication}.${filePointer.name}`);
797
+ })
798
+ })]
799
+ });
800
+ };
801
+ const FileChipPreview = ({ filePointer, onDelete }) => {
802
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_mui_material_Chip_Chip_js.default, {
803
+ label: filePointer.name,
804
+ onDelete,
805
+ avatar: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_mui_material_Avatar_Avatar_js.default, {
806
+ src: filePointer.iconImageUri,
807
+ alt: filePointer.sourceApplication,
808
+ sx: { backgroundColor: "transparent" }
809
+ })
810
+ });
811
+ };
812
+
813
+ //#endregion
814
+ //#region src/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box-core.tsx
815
+ const HoveringInsertionPromptBoxCore = ({ performInsertion, state, insertionOrEditingFunction, contextCategories }) => {
816
+ const { getDocumentsContext } = (0, _copilotkit_react_core.useCopilotContext)();
817
+ const [editSuggestion, setEditSuggestion] = (0, react.useState)("");
818
+ const [suggestionIsLoading, setSuggestionIsLoading] = (0, react.useState)(false);
819
+ const [adjustmentPrompt, setAdjustmentPrompt] = (0, react.useState)("");
820
+ const [generatingSuggestion, setGeneratingSuggestion] = (0, react.useState)(null);
821
+ const adjustmentTextAreaRef = (0, react.useRef)(null);
822
+ const suggestionTextAreaRef = (0, react.useRef)(null);
823
+ const [filePointers, setFilePointers] = (0, react.useState)([]);
824
+ const [suggestedFiles, setSuggestedFiles] = (0, react.useState)([]);
825
+ (0, react.useEffect)(() => {
826
+ setSuggestedFiles(getDocumentsContext(contextCategories));
827
+ }, [contextCategories, getDocumentsContext]);
828
+ useAutosizeTextArea(suggestionTextAreaRef, editSuggestion || "");
829
+ useAutosizeTextArea(adjustmentTextAreaRef, adjustmentPrompt || "");
830
+ (0, react.useEffect)(() => {
831
+ adjustmentTextAreaRef.current?.focus();
832
+ }, []);
833
+ (0, react.useEffect)(() => {
834
+ if (!generatingSuggestion) return;
835
+ if (generatingSuggestion.locked) return;
836
+ setEditSuggestion("");
837
+ const reader = generatingSuggestion.getReader();
838
+ const read = async () => {
839
+ setSuggestionIsLoading(true);
840
+ while (true) {
841
+ const { done, value } = await reader.read();
842
+ if (done) break;
843
+ setEditSuggestion((prev) => {
844
+ const newSuggestion = prev + value;
845
+ if (suggestionTextAreaRef.current) suggestionTextAreaRef.current.scrollTop = suggestionTextAreaRef.current.scrollHeight;
846
+ return newSuggestion;
847
+ });
848
+ }
849
+ setSuggestionIsLoading(false);
850
+ };
851
+ read();
852
+ return () => {
853
+ const releaseLockIfNotClosed = async () => {
854
+ try {
855
+ await reader.closed;
856
+ } catch {
857
+ reader.releaseLock();
858
+ }
859
+ };
860
+ releaseLockIfNotClosed();
861
+ };
862
+ }, [generatingSuggestion]);
863
+ const beginGeneratingAdjustment = (0, react.useCallback)(async () => {
864
+ if (!adjustmentPrompt.trim()) return;
865
+ let modificationState = state.editorState;
866
+ if (editSuggestion !== "") modificationState.selectedText = editSuggestion;
867
+ setGeneratingSuggestion(streamPromiseFlatten(insertionOrEditingFunction(modificationState, adjustmentPrompt, filePointers, new AbortController().signal)));
868
+ }, [
869
+ adjustmentPrompt,
870
+ editSuggestion,
871
+ state.editorState,
872
+ insertionOrEditingFunction,
873
+ filePointers
874
+ ]);
875
+ const isLoading = suggestionIsLoading;
876
+ const textToEdit = editSuggestion || state.editorState.selectedText;
877
+ const adjustmentLabel = textToEdit === "" ? "Describe the text you want to insert" : "Describe adjustments to the suggested text";
878
+ const placeholder = textToEdit === "" ? "e.g. 'summarize the client's top 3 pain-points from @CallTranscript'" : "e.g. 'make it more formal', 'be more specific', ...";
879
+ const { setIsDisplayed } = useHoveringEditorContext();
880
+ const AdjustmentPromptComponent = /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Label, {
881
+ className: "",
882
+ children: adjustmentLabel
883
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
884
+ className: "relative w-full flex items-center",
885
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("textarea", {
886
+ "data-testid": "adjustment-prompt",
887
+ disabled: suggestionIsLoading,
888
+ ref: adjustmentTextAreaRef,
889
+ value: adjustmentPrompt,
890
+ onChange: (e) => setAdjustmentPrompt(e.target.value),
891
+ onKeyDown: (e) => {
892
+ if (e.key === "Enter" && e.shiftKey) {
893
+ e.preventDefault();
894
+ setAdjustmentPrompt(adjustmentPrompt + "\n");
895
+ } else if (e.key === "Enter") {
896
+ e.preventDefault();
897
+ beginGeneratingAdjustment();
898
+ }
899
+ },
900
+ placeholder,
901
+ style: { minHeight: "3rem" },
902
+ 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]",
903
+ rows: 1
904
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
905
+ onClick: beginGeneratingAdjustment,
906
+ className: "absolute right-2 bg-blue-500 text-white w-8 h-8 rounded-full flex items-center justify-center",
907
+ "data-testid": "generate-button",
908
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("i", {
909
+ className: "material-icons",
910
+ children: "arrow_forward"
911
+ })
912
+ })]
913
+ })] });
914
+ const SuggestionComponent = /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
915
+ className: "flex justify-between items-end w-full",
916
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(Label, {
917
+ className: "mt-4",
918
+ children: "Suggested:"
919
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
920
+ className: "ml-auto",
921
+ children: isLoading && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
922
+ className: "flex justify-center items-center",
923
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
924
+ 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]",
925
+ role: "status",
926
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
927
+ className: "!absolute !-m-px !h-px !w-px !overflow-hidden !whitespace-nowrap !border-0 !p-0 ![clip:rect(0,0,0,0)]",
928
+ children: "Loading..."
929
+ })
930
+ })
931
+ })
932
+ })]
933
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("textarea", {
934
+ "data-testid": "suggestion-result",
935
+ ref: suggestionTextAreaRef,
936
+ value: editSuggestion,
937
+ disabled: suggestionIsLoading,
938
+ onChange: (e) => setEditSuggestion(e.target.value),
939
+ className: "w-full text-base p-2 border border-gray-300 rounded-md resize-none bg-green-50",
940
+ style: {
941
+ overflow: "auto",
942
+ maxHeight: "10em"
943
+ }
944
+ })] });
945
+ const SubmitComponent = /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
946
+ className: "flex w-full gap-4 justify-start",
947
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(Button, {
948
+ "data-testid": "insert-button",
949
+ className: " bg-green-700 text-white",
950
+ onClick: () => {
951
+ performInsertion(editSuggestion);
952
+ },
953
+ children: ["Insert ", /* @__PURE__ */ (0, react_jsx_runtime.jsx)("i", {
954
+ className: "material-icons",
955
+ children: "check"
956
+ })]
957
+ })
958
+ });
959
+ const sourceSearchCandidate = adjustmentPrompt.split(" ").pop();
960
+ const sourceSearchWord = sourceSearchCandidate?.startsWith("@") ? sourceSearchCandidate.slice(1) : void 0;
961
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
962
+ className: "w-full flex flex-col items-start relative gap-2",
963
+ children: [
964
+ AdjustmentPromptComponent,
965
+ filePointers.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(IncludedFilesPreview, {
966
+ includedFiles: filePointers,
967
+ setIncludedFiles: setFilePointers
968
+ }),
969
+ sourceSearchWord !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SourceSearchBox, {
970
+ searchTerm: sourceSearchWord,
971
+ suggestedFiles,
972
+ onSelectedFile: (filePointer) => {
973
+ setAdjustmentPrompt(adjustmentPrompt.replace(new RegExp(`@${sourceSearchWord}$`), ""));
974
+ setFilePointers((prev) => [...prev, filePointer]);
975
+ adjustmentTextAreaRef.current?.focus();
976
+ }
977
+ }),
978
+ generatingSuggestion ? SuggestionComponent : null,
979
+ generatingSuggestion ? SubmitComponent : null
980
+ ]
981
+ });
982
+ };
983
+
984
+ //#endregion
985
+ //#region src/components/hovering-toolbar/text-insertion-prompt-box/hovering-insertion-prompt-box.tsx
986
+ const HoveringInsertionPromptBox = (props) => {
987
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
988
+ className: "flex flex-col justify-center items-center space-y-4 rounded-md border shadow-lg p-4 border-gray- bg-white",
989
+ style: { width: "35rem" },
990
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(HoveringInsertionPromptBoxCore, {
991
+ state: { editorState: props.editorState },
992
+ insertionOrEditingFunction: props.apiConfig.insertionOrEditingFunction,
993
+ performInsertion: props.performInsertion,
994
+ contextCategories: props.contextCategories
995
+ })
996
+ });
997
+ };
998
+
999
+ //#endregion
1000
+ //#region src/components/hovering-toolbar/hovering-toolbar.tsx
1001
+ const HoveringToolbar = (props) => {
1002
+ const ref = (0, react.useRef)(null);
1003
+ const editor = (0, slate_react.useSlate)();
1004
+ const selection = (0, slate_react.useSlateSelection)();
1005
+ const { isDisplayed, setIsDisplayed } = useHoveringEditorContext();
1006
+ const [isClient, setIsClient] = (0, react.useState)(false);
1007
+ (0, react.useEffect)(() => {
1008
+ setIsClient(true);
1009
+ }, []);
1010
+ const isShown = isClient && isDisplayed && selection;
1011
+ (0, react.useLayoutEffect)(() => {
1012
+ const el = ref.current;
1013
+ const { selection } = editor;
1014
+ if (!el || !isShown) return;
1015
+ if (!selection) {
1016
+ el.removeAttribute("style");
1017
+ return;
1018
+ }
1019
+ const domSelection = window.getSelection();
1020
+ if (!domSelection || domSelection.rangeCount === 0) return;
1021
+ const rect = domSelection.getRangeAt(0).getBoundingClientRect();
1022
+ if (rect.top === 0 && rect.left === 0 && rect.width === 0 && rect.height === 0) return;
1023
+ const verticalOffsetFromCorner = 0;
1024
+ const horizontalOffsetFromCorner = 0;
1025
+ let top = rect.bottom + window.scrollY + verticalOffsetFromCorner;
1026
+ if (rect.bottom + el.offsetHeight > window.innerHeight - verticalOffsetFromCorner) top = rect.top + window.scrollY - el.offsetHeight - verticalOffsetFromCorner;
1027
+ let left = rect.left + window.scrollX - el.offsetWidth / 2 + rect.width / 2 + horizontalOffsetFromCorner;
1028
+ if (left < horizontalOffsetFromCorner) left = horizontalOffsetFromCorner;
1029
+ else if (left + el.offsetWidth > window.innerWidth - horizontalOffsetFromCorner) left = window.innerWidth - el.offsetWidth - horizontalOffsetFromCorner;
1030
+ el.style.opacity = "1";
1031
+ el.style.position = "absolute";
1032
+ el.style.top = `${top}px`;
1033
+ el.style.left = `${left}px`;
1034
+ }, [isShown]);
1035
+ (0, react.useEffect)(() => {
1036
+ const handleClickOutside = (event) => {
1037
+ if (ref.current && !ref.current.contains(event.target)) setIsDisplayed(false);
1038
+ };
1039
+ document.addEventListener("mousedown", handleClickOutside);
1040
+ return () => {
1041
+ document.removeEventListener("mousedown", handleClickOutside);
1042
+ };
1043
+ }, [ref, setIsDisplayed]);
1044
+ if (!isShown) return null;
1045
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Portal, { children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Menu, {
1046
+ ref,
1047
+ className: "copilot-kit-textarea-css-scope " + (props.hoverMenuClassname || "p-2 absolute z-10 top-[-10000px] left-[-10000px] mt-[-6px] opacity-0 transition-opacity duration-700"),
1048
+ "data-testid": "hovering-toolbar",
1049
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(HoveringInsertionPromptBox, {
1050
+ editorState: editorState(editor, selection),
1051
+ apiConfig: props.apiConfig,
1052
+ performInsertion: (insertedText) => {
1053
+ slate.Transforms.delete(editor, { at: selection });
1054
+ slate.Transforms.insertText(editor, insertedText, { at: selection });
1055
+ setIsDisplayed(false);
1056
+ },
1057
+ contextCategories: props.contextCategories
1058
+ })
1059
+ }) });
1060
+ };
1061
+ function editorState(editor, selection) {
1062
+ const textAroundCursor = getTextAroundSelection(editor);
1063
+ if (textAroundCursor) return textAroundCursor;
1064
+ return {
1065
+ textBeforeCursor: getFullEditorTextWithNewlines(editor),
1066
+ textAfterCursor: "",
1067
+ selectedText: ""
1068
+ };
1069
+ }
1070
+
1071
+ //#endregion
1072
+ //#region src/components/base-copilot-textarea/render-element.tsx
1073
+ function makeRenderElementFunction(suggestionsStyle) {
1074
+ return (props) => {
1075
+ switch (props.element.type) {
1076
+ case "paragraph": return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DefaultElement, { ...props });
1077
+ case "suggestion": return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SuggestionElement, {
1078
+ ...props,
1079
+ suggestionsStyle
1080
+ });
1081
+ }
1082
+ };
1083
+ }
1084
+ const DefaultElement = (props) => {
1085
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1086
+ ...props.attributes,
1087
+ children: props.children
1088
+ });
1089
+ };
1090
+ const SuggestionElement = (props) => {
1091
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1092
+ ...props.attributes,
1093
+ style: { ...props.suggestionsStyle },
1094
+ "data-testid": "suggestion",
1095
+ contentEditable: false,
1096
+ children: [props.children, props.element.type === "suggestion" && props.element.content]
1097
+ });
1098
+ };
1099
+
1100
+ //#endregion
1101
+ //#region src/components/base-copilot-textarea/render-placeholder.tsx
1102
+ function makeRenderPlaceholderFunction(placeholderStyle) {
1103
+ return (props) => {
1104
+ const { style, ...restAttributes } = props.attributes;
1105
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1106
+ ...restAttributes,
1107
+ style: {
1108
+ ...style,
1109
+ ...placeholderStyle
1110
+ },
1111
+ children: props.children
1112
+ });
1113
+ };
1114
+ }
1115
+
1116
+ //#endregion
1117
+ //#region src/components/base-copilot-textarea/use-add-branding-css.tsx
1118
+ function useAddBrandingCss(suggestionStyleAugmented, disableBranding) {
1119
+ const cssSelector = ".copilot-textarea.with-branding";
1120
+ (0, react.useEffect)(() => {
1121
+ if (disableBranding) return;
1122
+ const styleEl = document.createElement("style");
1123
+ styleEl.id = "dynamic-styles";
1124
+ let dynamicStyles = Object.entries(suggestionStyleAugmented).map(([key, value]) => {
1125
+ return `${key.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, "$1-$2").toLowerCase()}: ${value};`;
1126
+ }).join(" ");
1127
+ dynamicStyles += `font-style: normal; font-size: x-small;`;
1128
+ dynamicStyles += `content: "CopilotKit";`;
1129
+ dynamicStyles += `bottom: 6px;`;
1130
+ dynamicStyles += `right: 6px;`;
1131
+ dynamicStyles += `pointer-events: none;`;
1132
+ dynamicStyles += `font-weight: 200;`;
1133
+ dynamicStyles += `padding: 0;`;
1134
+ dynamicStyles += `margin: 0;`;
1135
+ dynamicStyles += `border: 0;`;
1136
+ dynamicStyles += `line-height: 1;`;
1137
+ dynamicStyles += `position: absolute;`;
1138
+ styleEl.innerHTML = `
1139
+ ${cssSelector}::after {
1140
+ ${dynamicStyles}
1141
+ }
1142
+ `;
1143
+ document.head.appendChild(styleEl);
1144
+ const textarea = document.querySelector(cssSelector);
1145
+ const handleScroll = () => {
1146
+ const styleEl = document.getElementById("dynamic-styles");
1147
+ if (styleEl && textarea) {
1148
+ const offsetFromBottom = -textarea.scrollTop + 6;
1149
+ const offsetFromRight = -textarea.scrollLeft + 6;
1150
+ styleEl.innerHTML = `
1151
+ ${cssSelector}::after {
1152
+ ${dynamicStyles}
1153
+ bottom: ${offsetFromBottom}px;
1154
+ right: ${offsetFromRight}px;
1155
+ }
1156
+ `;
1157
+ }
1158
+ };
1159
+ textarea?.addEventListener("scroll", handleScroll);
1160
+ return () => {
1161
+ document.getElementById("dynamic-styles")?.remove();
1162
+ textarea?.removeEventListener("scroll", handleScroll);
1163
+ };
1164
+ }, [disableBranding, suggestionStyleAugmented]);
1165
+ }
1166
+
1167
+ //#endregion
1168
+ //#region src/lib/editor-to-text.ts
1169
+ function nodeChildrenToTextComponents(editor, nodes) {
1170
+ const indeciesOfInlineElements = new Set(nodes.map((node, index) => {
1171
+ if (slate.Element.isElement(node) && editor.isInline(node)) return index;
1172
+ return -1;
1173
+ }).filter((index) => index !== -1));
1174
+ return nodes.filter((node, index) => {
1175
+ if (indeciesOfInlineElements.has(index)) return false;
1176
+ if (indeciesOfInlineElements.has(index - 1) || indeciesOfInlineElements.has(index + 1)) return node.text !== "";
1177
+ return true;
1178
+ }).map((node) => {
1179
+ if (slate.Element.isElement(node)) switch (node.type) {
1180
+ case "paragraph": return nodeChildrenToTextComponents(editor, node.children);
1181
+ case "suggestion": return [];
1182
+ }
1183
+ else return [node];
1184
+ }).reduce((acc, val) => acc.concat(val), []);
1185
+ }
1186
+ const editorToText = (editor) => {
1187
+ return nodeChildrenToTextComponents(editor, editor.children).map((textComponent) => textComponent.text).join("\n");
1188
+ };
1189
+
1190
+ //#endregion
1191
+ //#region src/components/base-copilot-textarea/track-cursor-moved-since-last-text-change.tsx
1192
+ function TrackerTextEditedSinceLastCursorMovement(props) {
1193
+ const cursorState = (0, slate_react.useSlateSelector)((state) => ({
1194
+ selection: state.selection,
1195
+ text: editorToText(state)
1196
+ }));
1197
+ const previousState = usePrevious(cursorState);
1198
+ (0, react.useEffect)(() => {
1199
+ if (!previousState) return;
1200
+ if (cursorChangedWithoutTextChanged(previousState, cursorState)) props.setCursorMovedSinceLastTextChange(true);
1201
+ }, [props.setCursorMovedSinceLastTextChange, cursorState]);
1202
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, {});
1203
+ }
1204
+ const cursorChangedWithoutTextChanged = (prev, next) => {
1205
+ const isSelectionChanged = !isSelectionEqual(prev.selection, next.selection);
1206
+ const isTextSame = prev.text === next.text;
1207
+ return isSelectionChanged && isTextSame;
1208
+ };
1209
+ const isSelectionEqual = (a, b) => {
1210
+ if (!a && !b) return true;
1211
+ if (!a || !b) return false;
1212
+ return slate.Range.equals(a, b);
1213
+ };
1214
+ /**
1215
+ * Easily keep track of the *previous* value of a variable.
1216
+ *
1217
+ * Example:
1218
+ * ```
1219
+ * const [count, setCount] = useState(0);
1220
+ * const prevCount = usePrevious(count);
1221
+ *
1222
+ * useEffect(() => {
1223
+ * if (count > prevCount) {
1224
+ * console.log('Now I know that count is bigger than before');
1225
+ * }
1226
+ * }, [count, prevCount]);
1227
+ * ```
1228
+ */
1229
+ function usePrevious(value) {
1230
+ const ref = (0, react.useRef)(void 0);
1231
+ (0, react.useEffect)(() => {
1232
+ ref.current = value;
1233
+ });
1234
+ return ref.current;
1235
+ }
1236
+
1237
+ //#endregion
1238
+ //#region src/components/base-copilot-textarea/base-copilot-textarea.tsx
1239
+ /**
1240
+ * Not intended for direct use. Use CopilotTextarea instead.
1241
+ *
1242
+ * The `BaseCopilotTextarea` includes the basic UX component,
1243
+ * without the business logic / AI logic that makes the content useful and coherent.
1244
+ *
1245
+ * It is useful if you want to build your own backend, with fully custom business logic
1246
+ * for figuring out which contnet to fill in.
1247
+ */
1248
+ const BaseCopilotTextarea = react.default.forwardRef((props, ref) => {
1249
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(HoveringEditorProvider, { children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(BaseCopilotTextareaWithHoveringContext, {
1250
+ ...props,
1251
+ ref
1252
+ }) });
1253
+ });
1254
+ /**
1255
+ * Not intended for direct use. Use `CopilotTextarea` instead.
1256
+ *
1257
+ * This is the private core of the `BaseCopilotTextarea` component.
1258
+ * For practical purposes the implementation is cleaner assuming containment in a `HoveringEditorProviderContext`.
1259
+ *
1260
+ * Therefore we separate the core logic into this component,
1261
+ * and wrap it in a `HoveringEditorProviderContext` in `BaseCopilotTextarea`.
1262
+ */
1263
+ const BaseCopilotTextareaWithHoveringContext = react.default.forwardRef((props, ref) => {
1264
+ const autosuggestionsConfig = {
1265
+ ...defaultBaseAutosuggestionsConfig,
1266
+ ...props.baseAutosuggestionsConfig
1267
+ };
1268
+ const valueOnInitialRender = (0, react.useMemo)(() => props.value ?? "", []);
1269
+ const [lastKnownFullEditorText, setLastKnownFullEditorText] = (0, react.useState)(valueOnInitialRender);
1270
+ const [cursorMovedSinceLastTextChange, setCursorMovedSinceLastTextChange] = (0, react.useState)(false);
1271
+ const [isUserInputActive, setIsUserInputActive] = (0, react.useState)(false);
1272
+ const initialValue = (0, react.useMemo)(() => {
1273
+ return [{
1274
+ type: "paragraph",
1275
+ children: [{ text: valueOnInitialRender }]
1276
+ }];
1277
+ }, [valueOnInitialRender]);
1278
+ const editor = useCopilotTextareaEditor();
1279
+ const { isDisplayed: hoveringEditorIsDisplayed, setIsDisplayed: setHoveringEditorIsDisplayed } = useHoveringEditorContext();
1280
+ const insertText = (0, react.useCallback)((autosuggestion) => {
1281
+ slate.Editor.insertText(editor, autosuggestion.text, { at: autosuggestion.point });
1282
+ }, [editor]);
1283
+ const shouldDisableAutosuggestions = autosuggestionsConfig.disabled || hoveringEditorIsDisplayed || cursorMovedSinceLastTextChange && autosuggestionsConfig.temporarilyDisableWhenMovingCursorWithoutChangingText || !isUserInputActive && autosuggestionsConfig.temporarilyDisableNotTrustedEvents;
1284
+ const { currentAutocompleteSuggestion, onChangeHandler: onChangeHandlerForAutocomplete, onKeyDownHandler: onKeyDownHandlerForAutocomplete, onTouchStartHandler: onTouchStartHandlerForAutocomplete } = useAutosuggestions(autosuggestionsConfig.debounceTime, autosuggestionsConfig.shouldAcceptAutosuggestionOnKeyPress, autosuggestionsConfig.shouldAcceptAutosuggestionOnTouch, autosuggestionsConfig.apiConfig.autosuggestionsFunction, insertText, autosuggestionsConfig.disableWhenEmpty, shouldDisableAutosuggestions);
1285
+ const onKeyDownHandlerForHoveringEditor = (0, react.useCallback)((event) => {
1286
+ if (autosuggestionsConfig.shouldToggleHoveringEditorOnKeyPress(event, props.shortcut ?? "k")) {
1287
+ event.preventDefault();
1288
+ setHoveringEditorIsDisplayed(!hoveringEditorIsDisplayed);
1289
+ }
1290
+ }, [
1291
+ hoveringEditorIsDisplayed,
1292
+ setHoveringEditorIsDisplayed,
1293
+ autosuggestionsConfig.shouldToggleHoveringEditorOnKeyPress
1294
+ ]);
1295
+ (0, react.useEffect)(() => {
1296
+ clearAutocompletionsFromEditor(editor);
1297
+ if (currentAutocompleteSuggestion) addAutocompletionsToEditor(editor, currentAutocompleteSuggestion.text, currentAutocompleteSuggestion.point);
1298
+ }, [currentAutocompleteSuggestion]);
1299
+ const suggestionStyleAugmented = (0, react.useMemo)(() => {
1300
+ return {
1301
+ fontStyle: "italic",
1302
+ color: "gray",
1303
+ ...props.suggestionsStyle
1304
+ };
1305
+ }, [props.suggestionsStyle]);
1306
+ const renderElementMemoized = (0, react.useMemo)(() => {
1307
+ return makeRenderElementFunction(suggestionStyleAugmented);
1308
+ }, [suggestionStyleAugmented]);
1309
+ const renderPlaceholderMemoized = (0, react.useMemo)(() => {
1310
+ return makeRenderPlaceholderFunction({
1311
+ top: void 0,
1312
+ ...props.placeholderStyle
1313
+ });
1314
+ }, [props.placeholderStyle]);
1315
+ (0, react.useEffect)(() => {
1316
+ if (props.value === lastKnownFullEditorText) return;
1317
+ setLastKnownFullEditorText(props.value ?? "");
1318
+ replaceEditorText(editor, props.value ?? "");
1319
+ }, [props.value]);
1320
+ const { placeholderStyle, value, hoverMenuClassname, onValueChange, baseAutosuggestionsConfig: autosuggestionsConfigFromProps, className, onChange, onKeyDown, disableBranding, ...propsToForward } = props;
1321
+ useAddBrandingCss(suggestionStyleAugmented, disableBranding);
1322
+ usePopulateCopilotTextareaRef(editor, ref);
1323
+ const moddedClassName = `copilot-textarea ${disableBranding ? "no-branding" : "with-branding"} ${(0, tailwind_merge.twMerge)("bg-white overflow-y-auto resize-y", className ?? "")}`;
1324
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(slate_react.Slate, {
1325
+ editor,
1326
+ initialValue,
1327
+ onChange: (value) => {
1328
+ const newEditorState = getTextAroundCollapsedCursor(editor);
1329
+ const fullEditorText = newEditorState ? newEditorState.textBeforeCursor + newEditorState.textAfterCursor : getFullEditorTextWithNewlines(editor);
1330
+ setLastKnownFullEditorText((prev) => {
1331
+ if (prev !== fullEditorText) setCursorMovedSinceLastTextChange(false);
1332
+ return fullEditorText;
1333
+ });
1334
+ onChangeHandlerForAutocomplete(newEditorState);
1335
+ props.onValueChange?.(fullEditorText);
1336
+ props.onChange?.(makeSemiFakeReactTextAreaEvent(fullEditorText));
1337
+ },
1338
+ children: [
1339
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TrackerTextEditedSinceLastCursorMovement, { setCursorMovedSinceLastTextChange }),
1340
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(HoveringToolbar, {
1341
+ apiConfig: autosuggestionsConfig.apiConfig,
1342
+ contextCategories: autosuggestionsConfig.contextCategories,
1343
+ hoverMenuClassname
1344
+ }),
1345
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(slate_react.Editable, {
1346
+ renderElement: renderElementMemoized,
1347
+ renderPlaceholder: renderPlaceholderMemoized,
1348
+ onKeyDown: (event) => {
1349
+ setIsUserInputActive(true);
1350
+ onKeyDownHandlerForHoveringEditor(event);
1351
+ onKeyDownHandlerForAutocomplete(event);
1352
+ props.onKeyDown?.(event);
1353
+ },
1354
+ onTouchStart: (event) => {
1355
+ onTouchStartHandlerForAutocomplete(event);
1356
+ },
1357
+ "data-testid": "copilot-textarea-editable",
1358
+ className: moddedClassName,
1359
+ onBlur: (ev) => {
1360
+ props.onBlur?.(ev);
1361
+ clearAutocompletionsFromEditor(editor);
1362
+ setIsUserInputActive(false);
1363
+ },
1364
+ ...propsToForward
1365
+ })
1366
+ ]
1367
+ });
1368
+ });
1369
+ function makeSemiFakeReactTextAreaEvent(currentText) {
1370
+ return {
1371
+ target: {
1372
+ value: currentText,
1373
+ type: "copilot-textarea"
1374
+ },
1375
+ currentTarget: {
1376
+ value: currentText,
1377
+ type: "copilot-textarea"
1378
+ }
1379
+ };
1380
+ }
1381
+
1382
+ //#endregion
1383
+ //#region src/lib/retry.tsx
1384
+ function retry(fn, retriesLeft = 2, interval = 200, backoff = 1.5) {
1385
+ return new Promise((resolve, reject) => {
1386
+ fn().then(resolve).catch((error) => {
1387
+ if (retriesLeft === 1) {
1388
+ reject(error);
1389
+ return;
1390
+ }
1391
+ setTimeout(() => {
1392
+ retry(fn, retriesLeft - 1, interval * backoff, backoff).then(resolve).catch(reject);
1393
+ }, interval);
1394
+ });
1395
+ });
1396
+ }
1397
+
1398
+ //#endregion
1399
+ //#region src/hooks/make-autosuggestions-function/use-make-standard-autosuggestions-function.tsx
1400
+ /**
1401
+ * Returns a memoized function that sends a request to the specified API endpoint to get an autosuggestion for the user's input.
1402
+ * The function takes in the text before and after the cursor, and an abort signal.
1403
+ * It sends a POST request to the API endpoint with the messages array containing the system message, few shot messages, and user messages.
1404
+ * The function returns the suggestion from the API response.
1405
+ *
1406
+ * @param textareaPurpose - The purpose of the textarea. This is included in the system message.
1407
+ * @param apiEndpoint - The API endpoint to send the autosuggestion request to.
1408
+ * @param makeSystemMessage - A function that takes in a context string and returns a system message to include in the autosuggestion request.
1409
+ * @param fewShotMessages - An array of few shot messages to include in the autosuggestion request.
1410
+ * @param contextCategories - The categories of context strings we want to include. By default, we include the (default) "global" context category.
1411
+ * @returns A memoized function that sends a request to the specified API endpoint to get an autosuggestion for the user's input.
1412
+ */
1413
+ function useMakeStandardAutosuggestionFunction(textareaPurpose, contextCategories, apiConfig) {
1414
+ const { getContextString, copilotApiConfig } = (0, _copilotkit_react_core.useCopilotContext)();
1415
+ const { chatApiEndpoint: url, publicApiKey, credentials, properties } = copilotApiConfig;
1416
+ ({
1417
+ ...copilotApiConfig.headers,
1418
+ ...publicApiKey ? { [_copilotkit_shared.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {}
1419
+ });
1420
+ const { maxTokens, stop, temperature = 0 } = apiConfig;
1421
+ return (0, react.useCallback)(async (editorState, abortSignal) => {
1422
+ return await retry(async () => {
1423
+ [
1424
+ new _copilotkit_runtime_client_gql.TextMessage({
1425
+ role: _copilotkit_runtime_client_gql.Role.System,
1426
+ content: apiConfig.makeSystemPrompt(textareaPurpose, getContextString([], contextCategories))
1427
+ }),
1428
+ ...apiConfig.fewShotMessages,
1429
+ editorState.textAfterCursor != "" ? new _copilotkit_runtime_client_gql.TextMessage({
1430
+ role: _copilotkit_runtime_client_gql.Role.User,
1431
+ content: editorState.textAfterCursor
1432
+ }) : null,
1433
+ new _copilotkit_runtime_client_gql.TextMessage({
1434
+ role: _copilotkit_runtime_client_gql.Role.User,
1435
+ content: `<TextAfterCursor>${editorState.textAfterCursor}</TextAfterCursor>`
1436
+ }),
1437
+ new _copilotkit_runtime_client_gql.TextMessage({
1438
+ role: _copilotkit_runtime_client_gql.Role.User,
1439
+ content: `<TextBeforeCursor>${editorState.textBeforeCursor}</TextBeforeCursor>`
1440
+ })
1441
+ ].filter(Boolean);
1442
+ const response = {};
1443
+ let result = "";
1444
+ for (const message of (0, _copilotkit_runtime_client_gql.convertGqlOutputToMessages)(response.data?.generateCopilotResponse?.messages ?? [])) {
1445
+ if (abortSignal.aborted) break;
1446
+ if (message.isTextMessage()) result += message.content;
1447
+ }
1448
+ return result;
1449
+ });
1450
+ }, [
1451
+ apiConfig,
1452
+ getContextString,
1453
+ contextCategories,
1454
+ textareaPurpose
1455
+ ]);
1456
+ }
1457
+
1458
+ //#endregion
1459
+ //#region src/types/autosuggestions-config/suggestions-api-config.tsx
1460
+ const defaultSuggestionsMakeSystemPrompt = (textareaPurpose, contextString) => {
1461
+ return `You are a versatile writing assistant.
1462
+
1463
+ The user is writing some text.
1464
+ The purpose is: \"${textareaPurpose}\"
1465
+
1466
+ Your job is to guess what the user will write next AS BEST YOU CAN.
1467
+ Only guess a SHORT distance ahead. Usually 1 sentence, or at most 1 paragraph.
1468
+
1469
+ Adjust yourself to the user's style and implied intent.
1470
+
1471
+ 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.
1472
+ <TextAfterCursor>
1473
+ <TextBeforeCursor>
1474
+ <YourSuggestion>
1475
+
1476
+ If we need to add a whitespace character to the suggested text, make sure to explicitly add it in.
1477
+ Refrain from adding <YourSuggestion> tags when responding
1478
+
1479
+ The following external context is also provided. Use it to help you make better suggestions!!!
1480
+ \`\`\`
1481
+ ${contextString}
1482
+ \`\`\`
1483
+ `;
1484
+ };
1485
+ const defaultSuggestionsFewShotMessages = [
1486
+ new _copilotkit_runtime_client_gql.TextMessage({
1487
+ role: _copilotkit_runtime_client_gql.Role.User,
1488
+ content: "<TextAfterCursor>While I was there I also picked up some apples, oranges, and bananas.</TextAfterCursor>"
1489
+ }),
1490
+ new _copilotkit_runtime_client_gql.TextMessage({
1491
+ role: _copilotkit_runtime_client_gql.Role.User,
1492
+ content: "This morning I woke up and went straight to the grocery store."
1493
+ }),
1494
+ new _copilotkit_runtime_client_gql.TextMessage({
1495
+ role: _copilotkit_runtime_client_gql.Role.Assistant,
1496
+ content: " When I arrived I went straight to the produce section and picked out a big watermelon. "
1497
+ }),
1498
+ new _copilotkit_runtime_client_gql.TextMessage({
1499
+ role: _copilotkit_runtime_client_gql.Role.User,
1500
+ content: "<TextAfterCursor>and (iii) to the appointment of the Equityholders' Representative pursuant to Section 10.7 of the Merger Agreement and to the provisions thereof.</TextAfterCursor>"
1501
+ }),
1502
+ new _copilotkit_runtime_client_gql.TextMessage({
1503
+ role: _copilotkit_runtime_client_gql.Role.User,
1504
+ content: "<TextBeforeCursor>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;</TextBeforeCursor>"
1505
+ }),
1506
+ new _copilotkit_runtime_client_gql.TextMessage({
1507
+ role: _copilotkit_runtime_client_gql.Role.Assistant,
1508
+ 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\"; "
1509
+ })
1510
+ ];
1511
+ const defaultSuggestionsApiConfig = {
1512
+ makeSystemPrompt: defaultSuggestionsMakeSystemPrompt,
1513
+ fewShotMessages: defaultSuggestionsFewShotMessages
1514
+ };
1515
+
1516
+ //#endregion
1517
+ //#region src/types/autosuggestions-config/insertions-api-config.tsx
1518
+ const defaultInsertionsMakeSystemPrompt = (textareaPurpose, contextString) => {
1519
+ return `You are a versatile writing assistant helping the user insert new text into their existing work.
1520
+
1521
+ The user is writing some text.
1522
+ The purpose is: \"${textareaPurpose}\"
1523
+
1524
+ The following external context is also provided. Use it to inform your suggestions when relevant!!!
1525
+ \`\`\`
1526
+ ${contextString}
1527
+ \`\`\`
1528
+
1529
+ The user will provide you with a prompt for an INSERTION into the text they are writing.
1530
+ Your job is to come up with an INSERTION into the text that the user would like to use, AS BEST YOU CAN.
1531
+ Only insert a SHORT segment. Usually 1 sentence, or at most 1 paragraph.
1532
+
1533
+ Adjust yourself to the user's style and implied intent.
1534
+
1535
+
1536
+ 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.
1537
+ The conversation will be structured as follows:
1538
+ <TextAfterCursor>
1539
+ <TextBeforeCursor>
1540
+ <InsertionPrompt>
1541
+
1542
+ <YourInsertionSuggestion>
1543
+ `;
1544
+ };
1545
+ const defaultInsertionsFewShotMessages = [
1546
+ new _copilotkit_runtime_client_gql.TextMessage({
1547
+ role: _copilotkit_runtime_client_gql.Role.User,
1548
+ content: "<TextAfterCursor>While I was there I also picked up some apples, oranges, and bananas.</TextAfterCursor>"
1549
+ }),
1550
+ new _copilotkit_runtime_client_gql.TextMessage({
1551
+ role: _copilotkit_runtime_client_gql.Role.User,
1552
+ content: "<TextBeforeCursor>This morning I woke up and went straight to the grocery store.</TextBeforeCursor>"
1553
+ }),
1554
+ new _copilotkit_runtime_client_gql.TextMessage({
1555
+ role: _copilotkit_runtime_client_gql.Role.User,
1556
+ content: "<InsertionPrompt>I bought a big watermelon</InsertionPrompt>"
1557
+ }),
1558
+ new _copilotkit_runtime_client_gql.TextMessage({
1559
+ role: _copilotkit_runtime_client_gql.Role.Assistant,
1560
+ content: "When I arrived I went straight to the produce section and picked out a big watermelon."
1561
+ }),
1562
+ new _copilotkit_runtime_client_gql.TextMessage({
1563
+ role: _copilotkit_runtime_client_gql.Role.User,
1564
+ content: "<TextAfterCursor>and (iii) to the appointment of the Equityholders' Representative pursuant to Section 10.7 of the Merger Agreement and to the provisions thereof.</TextAfterCursor>"
1565
+ }),
1566
+ new _copilotkit_runtime_client_gql.TextMessage({
1567
+ role: _copilotkit_runtime_client_gql.Role.User,
1568
+ content: "<TextBeforeCursor>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;</TextBeforeCursor>"
1569
+ }),
1570
+ new _copilotkit_runtime_client_gql.TextMessage({
1571
+ role: _copilotkit_runtime_client_gql.Role.User,
1572
+ content: "<InsertionPrompt>add section about the optionholder's pro rata share</InsertionPrompt>"
1573
+ }),
1574
+ new _copilotkit_runtime_client_gql.TextMessage({
1575
+ role: _copilotkit_runtime_client_gql.Role.Assistant,
1576
+ 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\"; "
1577
+ })
1578
+ ];
1579
+ const defaultInsertionsApiConfig = {
1580
+ makeSystemPrompt: defaultInsertionsMakeSystemPrompt,
1581
+ fewShotMessages: defaultInsertionsFewShotMessages,
1582
+ forwardedParams: void 0
1583
+ };
1584
+
1585
+ //#endregion
1586
+ //#region src/types/autosuggestions-config/editing-api-config.tsx
1587
+ const defaultEditingMakeSystemPrompt = (textareaPurpose, contextString) => {
1588
+ return `You are a versatile writing assistant helping the user edit a portion of their text.
1589
+
1590
+ The user is writing some text.
1591
+ The purpose is: \"${textareaPurpose}\"
1592
+
1593
+ The following external context is also provided. Use it when relevant.
1594
+ \`\`\`
1595
+ ${contextString}
1596
+ \`\`\`
1597
+
1598
+ The user has provided you with a PROMPT for EDITING a PORTION of the text.
1599
+ Your job is to come up with a new EDITED version OF THE SEGMENT IN QUESTION - AS BEST YOU CAN.
1600
+ Only rewrite the portion of the text that the user has marked as "TextToEdit"!!!
1601
+
1602
+ Adjust yourself to the user's style and implied intent.
1603
+
1604
+ The conversation will be structured as follows:
1605
+ <TextBeforeCursor>
1606
+ <TextToEdit>
1607
+ <TextAfterCursor>
1608
+ <EditingPrompt>
1609
+
1610
+ <YourEditSuggestion>
1611
+ `;
1612
+ };
1613
+ const defaultEditingFewShotMessages = [
1614
+ new _copilotkit_runtime_client_gql.TextMessage({
1615
+ role: _copilotkit_runtime_client_gql.Role.User,
1616
+ content: "<TextBeforeCursor>This morning I woke up and went straight to the grocery store. </TextBeforeCursor>"
1617
+ }),
1618
+ new _copilotkit_runtime_client_gql.TextMessage({
1619
+ role: _copilotkit_runtime_client_gql.Role.User,
1620
+ content: "<TextToEdit>While I was there I picked up some apples, oranges, and bananas. </TextToEdit>"
1621
+ }),
1622
+ new _copilotkit_runtime_client_gql.TextMessage({
1623
+ role: _copilotkit_runtime_client_gql.Role.User,
1624
+ content: "<TextAfterCursor>The grocery store was having a sale on fruit, so I decided to stock up.</TextAfterCursor>"
1625
+ }),
1626
+ new _copilotkit_runtime_client_gql.TextMessage({
1627
+ role: _copilotkit_runtime_client_gql.Role.User,
1628
+ content: "<EditingPrompt>I also bought a big watermelon</EditingPrompt>"
1629
+ }),
1630
+ new _copilotkit_runtime_client_gql.TextMessage({
1631
+ role: _copilotkit_runtime_client_gql.Role.Assistant,
1632
+ content: "While I was there I picked up some apples, oranges, and bananas, and a big watermelon."
1633
+ }),
1634
+ new _copilotkit_runtime_client_gql.TextMessage({
1635
+ role: _copilotkit_runtime_client_gql.Role.User,
1636
+ content: "<TextBeforeCursor>Yesterday, I spent the afternoon working on my new project.</TextBeforeCursor>"
1637
+ }),
1638
+ new _copilotkit_runtime_client_gql.TextMessage({
1639
+ role: _copilotkit_runtime_client_gql.Role.User,
1640
+ content: "<TextToEdit>It's quite challenging and requires a lot of focus.</TextToEdit>"
1641
+ }),
1642
+ new _copilotkit_runtime_client_gql.TextMessage({
1643
+ role: _copilotkit_runtime_client_gql.Role.User,
1644
+ content: "<TextAfterCursor>I'm really excited about the potential outcomes of this project.</TextAfterCursor>"
1645
+ }),
1646
+ new _copilotkit_runtime_client_gql.TextMessage({
1647
+ role: _copilotkit_runtime_client_gql.Role.User,
1648
+ content: "<EditingPrompt>emphasize the complexity and my enthusiasm for the project</EditingPrompt>"
1649
+ }),
1650
+ new _copilotkit_runtime_client_gql.TextMessage({
1651
+ role: _copilotkit_runtime_client_gql.Role.Assistant,
1652
+ content: "It's a highly complex task that demands intense concentration, but I'm incredibly enthusiastic about the promising prospects of this project."
1653
+ })
1654
+ ];
1655
+ const defaultEditingApiConfig = {
1656
+ makeSystemPrompt: defaultEditingMakeSystemPrompt,
1657
+ fewShotMessages: defaultEditingFewShotMessages,
1658
+ forwardedParams: void 0
1659
+ };
1660
+
1661
+ //#endregion
1662
+ //#region src/types/autosuggestions-config/autosuggestions-config.tsx
1663
+ const defaultAutosuggestionsConfig = {
1664
+ ...defaultBaseAutosuggestionsConfig,
1665
+ contextCategories: _copilotkit_react_core.defaultCopilotContextCategories,
1666
+ chatApiConfigs: {
1667
+ suggestionsApiConfig: defaultSuggestionsApiConfig,
1668
+ insertionApiConfig: defaultInsertionsApiConfig,
1669
+ editingApiConfig: defaultEditingApiConfig
1670
+ }
1671
+ };
1672
+
1673
+ //#endregion
1674
+ //#region src/hooks/make-autosuggestions-function/use-make-standard-insertion-function.tsx
1675
+ /**
1676
+ * Returns a memoized function that sends a request to the specified API endpoint to get an autosuggestion for the user's input.
1677
+ * The function takes in the text before and after the cursor, and an abort signal.
1678
+ * It sends a POST request to the API endpoint with the messages array containing the system message, few shot messages, and user messages.
1679
+ * The function returns the suggestion from the API response.
1680
+ *
1681
+ * @param textareaPurpose - The purpose of the textarea. This is included in the system message.
1682
+ * @param apiEndpoint - The API endpoint to send the autosuggestion request to.
1683
+ * @param makeSystemMessage - A function that takes in a context string and returns a system message to include in the autosuggestion request.
1684
+ * @param fewShotMessages - An array of few shot messages to include in the autosuggestion request.
1685
+ * @param contextCategories - The categories of context strings we want to include. By default, we include the (default) "global" context category.
1686
+ * @returns A memoized function that sends a request to the specified API endpoint to get an autosuggestion for the user's input.
1687
+ */
1688
+ function useMakeStandardInsertionOrEditingFunction(textareaPurpose, contextCategories, insertionApiConfig, editingApiConfig) {
1689
+ const runtimeClient = { generateCopilotResponse: (...args) => {} };
1690
+ const { getContextString, copilotApiConfig } = (0, _copilotkit_react_core.useCopilotContext)();
1691
+ ({ ...copilotApiConfig.publicApiKey ? { [_copilotkit_shared.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey } : {} });
1692
+ async function runtimeClientResponseToStringStream(responsePromise) {
1693
+ const messagesStream = runtimeClient.asStream(responsePromise);
1694
+ return new ReadableStream({ async start(controller) {
1695
+ const reader = messagesStream.getReader();
1696
+ let sentContent = "";
1697
+ while (true) {
1698
+ const { done, value } = await reader.read();
1699
+ if (done) break;
1700
+ const messages = (0, _copilotkit_runtime_client_gql.convertGqlOutputToMessages)(value.generateCopilotResponse.messages);
1701
+ let newContent = "";
1702
+ for (const message of messages) if (message.isTextMessage()) newContent += message.content;
1703
+ if (newContent) {
1704
+ const contentToSend = newContent.slice(sentContent.length);
1705
+ controller.enqueue(contentToSend);
1706
+ sentContent += contentToSend;
1707
+ }
1708
+ }
1709
+ controller.close();
1710
+ } });
1711
+ }
1712
+ const insertionFunction = (0, react.useCallback)(async (editorState, insertionPrompt, documents, abortSignal) => {
1713
+ return await retry(async () => {
1714
+ const messages = [
1715
+ new _copilotkit_runtime_client_gql.TextMessage({
1716
+ role: _copilotkit_runtime_client_gql.Role.System,
1717
+ content: insertionApiConfig.makeSystemPrompt(textareaPurpose, getContextString(documents, contextCategories))
1718
+ }),
1719
+ ...insertionApiConfig.fewShotMessages,
1720
+ new _copilotkit_runtime_client_gql.TextMessage({
1721
+ role: _copilotkit_runtime_client_gql.Role.User,
1722
+ content: `<TextAfterCursor>${editorState.textAfterCursor}</TextAfterCursor>`
1723
+ }),
1724
+ new _copilotkit_runtime_client_gql.TextMessage({
1725
+ role: _copilotkit_runtime_client_gql.Role.User,
1726
+ content: `<TextBeforeCursor>${editorState.textBeforeCursor}</TextBeforeCursor>`
1727
+ }),
1728
+ new _copilotkit_runtime_client_gql.TextMessage({
1729
+ role: _copilotkit_runtime_client_gql.Role.User,
1730
+ content: `<InsertionPrompt>${insertionPrompt}</InsertionPrompt>`
1731
+ })
1732
+ ];
1733
+ return runtimeClientResponseToStringStream(runtimeClient.generateCopilotResponse({
1734
+ data: {
1735
+ frontend: {
1736
+ actions: [],
1737
+ url: window.location.href
1738
+ },
1739
+ messages: (0, _copilotkit_runtime_client_gql.convertMessagesToGqlInput)((0, _copilotkit_runtime_client_gql.filterAgentStateMessages)(messages)),
1740
+ metadata: { requestType: _copilotkit_runtime_client_gql.CopilotRequestType.TextareaCompletion }
1741
+ },
1742
+ properties: copilotApiConfig.properties,
1743
+ signal: abortSignal
1744
+ }));
1745
+ });
1746
+ }, [
1747
+ insertionApiConfig,
1748
+ getContextString,
1749
+ contextCategories,
1750
+ textareaPurpose
1751
+ ]);
1752
+ const editingFunction = (0, react.useCallback)(async (editorState, editingPrompt, documents, abortSignal) => {
1753
+ return await retry(async () => {
1754
+ const messages = [
1755
+ new _copilotkit_runtime_client_gql.TextMessage({
1756
+ role: _copilotkit_runtime_client_gql.Role.System,
1757
+ content: editingApiConfig.makeSystemPrompt(textareaPurpose, getContextString(documents, contextCategories))
1758
+ }),
1759
+ ...editingApiConfig.fewShotMessages,
1760
+ new _copilotkit_runtime_client_gql.TextMessage({
1761
+ role: _copilotkit_runtime_client_gql.Role.User,
1762
+ content: `<TextBeforeCursor>${editorState.textBeforeCursor}</TextBeforeCursor>`
1763
+ }),
1764
+ new _copilotkit_runtime_client_gql.TextMessage({
1765
+ role: _copilotkit_runtime_client_gql.Role.User,
1766
+ content: `<TextToEdit>${editorState.selectedText}</TextToEdit>`
1767
+ }),
1768
+ new _copilotkit_runtime_client_gql.TextMessage({
1769
+ role: _copilotkit_runtime_client_gql.Role.User,
1770
+ content: `<TextAfterCursor>${editorState.textAfterCursor}</TextAfterCursor>`
1771
+ }),
1772
+ new _copilotkit_runtime_client_gql.TextMessage({
1773
+ role: _copilotkit_runtime_client_gql.Role.User,
1774
+ content: `<EditingPrompt>${editingPrompt}</EditingPrompt>`
1775
+ })
1776
+ ];
1777
+ return runtimeClientResponseToStringStream(runtimeClient.generateCopilotResponse({
1778
+ data: {
1779
+ frontend: {
1780
+ actions: [],
1781
+ url: window.location.href
1782
+ },
1783
+ messages: (0, _copilotkit_runtime_client_gql.convertMessagesToGqlInput)((0, _copilotkit_runtime_client_gql.filterAgentStateMessages)(messages)),
1784
+ metadata: { requestType: _copilotkit_runtime_client_gql.CopilotRequestType.TextareaCompletion }
1785
+ },
1786
+ properties: copilotApiConfig.properties,
1787
+ signal: abortSignal
1788
+ }));
1789
+ });
1790
+ }, [
1791
+ editingApiConfig,
1792
+ getContextString,
1793
+ contextCategories,
1794
+ textareaPurpose
1795
+ ]);
1796
+ return (0, react.useCallback)(async (editorState, insertionPrompt, documents, abortSignal) => {
1797
+ if (editorState.selectedText === "") return await insertionFunction(editorState, insertionPrompt, documents, abortSignal);
1798
+ else return await editingFunction(editorState, insertionPrompt, documents, abortSignal);
1799
+ }, [insertionFunction, editingFunction]);
1800
+ }
1801
+
1802
+ //#endregion
1803
+ //#region src/components/copilot-textarea/copilot-textarea.tsx
1804
+ /**
1805
+ * <br/>
1806
+ * <img src="https://cdn.copilotkit.ai/docs/copilotkit/images/CopilotTextarea.gif" width="500" />
1807
+ *
1808
+ * `<CopilotTextarea>` is a React component that acts as a drop-in replacement for the standard `<textarea>`,
1809
+ * offering enhanced autocomplete features powered by AI. It is context-aware, integrating seamlessly with the
1810
+ * [`useCopilotReadable`](/reference/v1/hooks/useCopilotReadable) hook to provide intelligent suggestions based on the application context.
1811
+ *
1812
+ * In addition, it provides a hovering editor window (available by default via `Cmd + K` on Mac and `Ctrl + K` on Windows) that allows the user to
1813
+ * suggest changes to the text, for example providing a summary or rephrasing the text.
1814
+ *
1815
+ * ## Example
1816
+ *
1817
+ * ```tsx
1818
+ * import { CopilotTextarea } from '@copilotkit/react-textarea';
1819
+ * import "@copilotkit/react-textarea/styles.css";
1820
+ *
1821
+ * <CopilotTextarea
1822
+ * autosuggestionsConfig={{
1823
+ * textareaPurpose:
1824
+ * "the body of an email message",
1825
+ * chatApiConfigs: {},
1826
+ * }}
1827
+ * />
1828
+ * ```
1829
+ *
1830
+ * ## Usage
1831
+ *
1832
+ * ### Install Dependencies
1833
+ *
1834
+ * This component is part of the [@copilotkit/react-textarea](https://npmjs.com/package/@copilotkit/react-textarea) package.
1835
+ *
1836
+ * ```shell npm2yarn \"@copilotkit/react-textarea"\
1837
+ * npm install @copilotkit/react-core @copilotkit/react-textarea
1838
+ * ```
1839
+ *
1840
+ * ### Usage
1841
+ *
1842
+ * Use the CopilotTextarea component in your React application similarly to a standard `<textarea />`,
1843
+ * with additional configurations for AI-powered features.
1844
+ *
1845
+ * For example:
1846
+ *
1847
+ * ```tsx
1848
+ * import { useState } from "react";
1849
+ * import { CopilotTextarea } from "@copilotkit/react-textarea";
1850
+ * import "@copilotkit/react-textarea/styles.css";
1851
+ *
1852
+ * export function ExampleComponent() {
1853
+ * const [text, setText] = useState("");
1854
+ *
1855
+ * return (
1856
+ * <CopilotTextarea
1857
+ * className="custom-textarea-class"
1858
+ * value={text}
1859
+ * onValueChange={(value: string) => setText(value)}
1860
+ * placeholder="Enter your text here..."
1861
+ * autosuggestionsConfig={{
1862
+ * textareaPurpose: "Provide context or purpose of the textarea.",
1863
+ * chatApiConfigs: {
1864
+ * suggestionsApiConfig: {
1865
+ * maxTokens: 20,
1866
+ * stop: [".", "?", "!"],
1867
+ * },
1868
+ * },
1869
+ * }}
1870
+ * />
1871
+ * );
1872
+ * }
1873
+ * ```
1874
+ *
1875
+ * ### Look & Feel
1876
+ *
1877
+ * By default, CopilotKit components do not have any styles. You can import CopilotKit's stylesheet at the root of your project:
1878
+ * ```tsx title="YourRootComponent.tsx"
1879
+ * ...
1880
+ * import "@copilotkit/react-textarea/styles.css"; // [!code highlight]
1881
+ *
1882
+ * export function YourRootComponent() {
1883
+ * return (
1884
+ * <CopilotKit>
1885
+ * ...
1886
+ * </CopilotKit>
1887
+ * );
1888
+ * }
1889
+ * ```
1890
+ * For more information about how to customize the styles, check out the [Customize Look & Feel](/guides/custom-look-and-feel/customize-built-in-ui-components) guide.
1891
+ * */
1892
+ /**
1893
+ * A copilot textarea that uses the standard autosuggestions function.
1894
+ */
1895
+ const CopilotTextarea = react.default.forwardRef((props, ref) => {
1896
+ const { autosuggestionsConfig: autosuggestionsConfigUserSpecified, ...forwardedProps } = props;
1897
+ const autosuggestionsConfig = (0, lodash_merge.default)(defaultAutosuggestionsConfig, autosuggestionsConfigUserSpecified);
1898
+ const autosuggestionsFunction = useMakeStandardAutosuggestionFunction(autosuggestionsConfig.textareaPurpose, autosuggestionsConfig.contextCategories, autosuggestionsConfig.chatApiConfigs.suggestionsApiConfig);
1899
+ const insertionOrEditingFunction = useMakeStandardInsertionOrEditingFunction(autosuggestionsConfig.textareaPurpose, autosuggestionsConfig.contextCategories, autosuggestionsConfig.chatApiConfigs.insertionApiConfig, autosuggestionsConfig.chatApiConfigs.editingApiConfig);
1900
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, { children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(BaseCopilotTextarea, {
1901
+ ref,
1902
+ ...forwardedProps,
1903
+ baseAutosuggestionsConfig: {
1904
+ ...autosuggestionsConfig,
1905
+ apiConfig: {
1906
+ insertionOrEditingFunction,
1907
+ autosuggestionsFunction
1908
+ }
1909
+ }
1910
+ }) });
1911
+ });
1912
+
1913
+ //#endregion
1914
+ exports.BaseCopilotTextarea = BaseCopilotTextarea;
1915
+ exports.CopilotTextarea = CopilotTextarea;
1916
+ exports.defaultAutosuggestionsConfig = defaultAutosuggestionsConfig;
1917
+ exports.defaultBaseAutosuggestionsConfig = defaultBaseAutosuggestionsConfig;
1918
+ //# sourceMappingURL=index.cjs.map