MessageInput.svelte 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. <script lang="ts">
  2. import { settings } from '$lib/stores';
  3. import toast from 'svelte-french-toast';
  4. import Suggestions from './MessageInput/Suggestions.svelte';
  5. import { onMount } from 'svelte';
  6. export let submitPrompt: Function;
  7. export let stopResponse: Function;
  8. export let suggestionPrompts = [];
  9. export let autoScroll = true;
  10. let filesInputElement;
  11. let inputFiles;
  12. let dragged = false;
  13. export let files = [];
  14. export let fileUploadEnabled = true;
  15. export let speechRecognitionEnabled = true;
  16. export let speechRecognitionListening = false;
  17. export let prompt = '';
  18. export let messages = [];
  19. let speechRecognition;
  20. const speechRecognitionHandler = () => {
  21. // Check if SpeechRecognition is supported
  22. if (speechRecognitionListening) {
  23. speechRecognition.stop();
  24. } else {
  25. if ('SpeechRecognition' in window || 'webkitSpeechRecognition' in window) {
  26. // Create a SpeechRecognition object
  27. speechRecognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
  28. // Set continuous to true for continuous recognition
  29. speechRecognition.continuous = true;
  30. // Set the timeout for turning off the recognition after inactivity (in milliseconds)
  31. const inactivityTimeout = 3000; // 3 seconds
  32. let timeoutId;
  33. // Start recognition
  34. speechRecognition.start();
  35. speechRecognitionListening = true;
  36. // Event triggered when speech is recognized
  37. speechRecognition.onresult = function (event) {
  38. // Clear the inactivity timeout
  39. clearTimeout(timeoutId);
  40. // Handle recognized speech
  41. console.log(event);
  42. const transcript = event.results[Object.keys(event.results).length - 1][0].transcript;
  43. prompt = `${prompt}${transcript}`;
  44. // Restart the inactivity timeout
  45. timeoutId = setTimeout(() => {
  46. console.log('Speech recognition turned off due to inactivity.');
  47. speechRecognition.stop();
  48. }, inactivityTimeout);
  49. };
  50. // Event triggered when recognition is ended
  51. speechRecognition.onend = function () {
  52. // Restart recognition after it ends
  53. console.log('recognition ended');
  54. speechRecognitionListening = false;
  55. if (prompt !== '' && $settings?.speechAutoSend === true) {
  56. submitPrompt(prompt);
  57. }
  58. };
  59. // Event triggered when an error occurs
  60. speechRecognition.onerror = function (event) {
  61. console.log(event);
  62. toast.error(`Speech recognition error: ${event.error}`);
  63. speechRecognitionListening = false;
  64. };
  65. } else {
  66. toast.error('SpeechRecognition API is not supported in this browser.');
  67. }
  68. }
  69. };
  70. onMount(() => {
  71. const dropZone = document.querySelector('body');
  72. dropZone?.addEventListener('dragover', (e) => {
  73. e.preventDefault();
  74. dragged = true;
  75. });
  76. dropZone.addEventListener('drop', (e) => {
  77. e.preventDefault();
  78. console.log(e);
  79. if (e.dataTransfer?.files) {
  80. let reader = new FileReader();
  81. reader.onload = (event) => {
  82. files = [
  83. ...files,
  84. {
  85. type: 'image',
  86. url: `${event.target.result}`
  87. }
  88. ];
  89. };
  90. if (
  91. e.dataTransfer?.files &&
  92. e.dataTransfer?.files.length > 0 &&
  93. ['image/gif', 'image/jpeg', 'image/png'].includes(e.dataTransfer?.files[0]['type'])
  94. ) {
  95. reader.readAsDataURL(e.dataTransfer?.files[0]);
  96. } else {
  97. toast.error(`Unsupported File Type '${e.dataTransfer?.files[0]['type']}'.`);
  98. }
  99. }
  100. dragged = false;
  101. });
  102. dropZone?.addEventListener('dragleave', () => {
  103. dragged = false;
  104. });
  105. });
  106. </script>
  107. {#if dragged}
  108. <div
  109. class="fixed w-full h-full flex z-50 touch-none pointer-events-none"
  110. id="dropzone"
  111. role="region"
  112. aria-label="Drag and Drop Container"
  113. >
  114. <div class="absolute rounded-xl w-full h-full backdrop-blur bg-gray-800/40 flex justify-center">
  115. <div class="m-auto pt-64 flex flex-col justify-center">
  116. <div class="max-w-md">
  117. <div class=" text-center text-6xl mb-3">🏞️</div>
  118. <div class="text-center dark:text-white text-2xl font-semibold z-50">Add Images</div>
  119. <div class=" mt-2 text-center text-sm dark:text-gray-200 w-full">
  120. Drop any images here to add to the conversation
  121. </div>
  122. </div>
  123. </div>
  124. </div>
  125. </div>
  126. {/if}
  127. <div class="fixed bottom-0 w-full">
  128. <div class="px-2.5 pt-2.5 -mb-0.5 mx-auto inset-x-0 bg-transparent flex justify-center">
  129. {#if messages.length == 0 && suggestionPrompts.length !== 0}
  130. <div class="max-w-3xl w-full">
  131. <Suggestions {suggestionPrompts} {submitPrompt} />
  132. </div>
  133. {/if}
  134. {#if autoScroll === false && messages.length > 0}
  135. <div class=" flex justify-center mb-4">
  136. <button
  137. class=" bg-white border border-gray-100 dark:border-none dark:bg-white/20 p-1.5 rounded-full"
  138. on:click={() => {
  139. autoScroll = true;
  140. window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
  141. }}
  142. >
  143. <svg
  144. xmlns="http://www.w3.org/2000/svg"
  145. viewBox="0 0 20 20"
  146. fill="currentColor"
  147. class="w-5 h-5"
  148. >
  149. <path
  150. fill-rule="evenodd"
  151. d="M10 3a.75.75 0 01.75.75v10.638l3.96-4.158a.75.75 0 111.08 1.04l-5.25 5.5a.75.75 0 01-1.08 0l-5.25-5.5a.75.75 0 111.08-1.04l3.96 4.158V3.75A.75.75 0 0110 3z"
  152. clip-rule="evenodd"
  153. />
  154. </svg>
  155. </button>
  156. </div>
  157. {/if}
  158. </div>
  159. <div class="bg-white dark:bg-gray-800">
  160. <div class="max-w-3xl px-2.5 -mb-0.5 mx-auto inset-x-0">
  161. <div class="bg-gradient-to-t from-white dark:from-gray-800 from-40% pb-2">
  162. <input
  163. bind:this={filesInputElement}
  164. bind:files={inputFiles}
  165. type="file"
  166. hidden
  167. on:change={() => {
  168. let reader = new FileReader();
  169. reader.onload = (event) => {
  170. files = [
  171. ...files,
  172. {
  173. type: 'image',
  174. url: `${event.target.result}`
  175. }
  176. ];
  177. inputFiles = null;
  178. filesInputElement.value = '';
  179. };
  180. if (
  181. inputFiles &&
  182. inputFiles.length > 0 &&
  183. ['image/gif', 'image/jpeg', 'image/png'].includes(inputFiles[0]['type'])
  184. ) {
  185. reader.readAsDataURL(inputFiles[0]);
  186. } else {
  187. toast.error(`Unsupported File Type '${inputFiles[0]['type']}'.`);
  188. inputFiles = null;
  189. }
  190. }}
  191. />
  192. <form
  193. class=" flex flex-col relative w-full rounded-xl border dark:border-gray-600 bg-white dark:bg-gray-800 dark:text-gray-100"
  194. on:submit|preventDefault={() => {
  195. submitPrompt(prompt);
  196. }}
  197. >
  198. {#if files.length > 0}
  199. <div class="ml-2 mt-2 mb-1 flex space-x-2">
  200. {#each files as file, fileIdx}
  201. <div class=" relative group">
  202. <img src={file.url} alt="input" class=" h-16 w-16 rounded-xl object-cover" />
  203. <div class=" absolute -top-1 -right-1">
  204. <button
  205. class=" bg-gray-400 text-white border border-white rounded-full group-hover:visible invisible transition"
  206. type="button"
  207. on:click={() => {
  208. files.splice(fileIdx, 1);
  209. files = files;
  210. }}
  211. >
  212. <svg
  213. xmlns="http://www.w3.org/2000/svg"
  214. viewBox="0 0 20 20"
  215. fill="currentColor"
  216. class="w-4 h-4"
  217. >
  218. <path
  219. d="M6.28 5.22a.75.75 0 00-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 101.06 1.06L10 11.06l3.72 3.72a.75.75 0 101.06-1.06L11.06 10l3.72-3.72a.75.75 0 00-1.06-1.06L10 8.94 6.28 5.22z"
  220. />
  221. </svg>
  222. </button>
  223. </div>
  224. </div>
  225. {/each}
  226. </div>
  227. {/if}
  228. <div class=" flex">
  229. {#if fileUploadEnabled}
  230. <div class=" self-end mb-2 ml-1.5">
  231. <button
  232. class=" text-gray-600 dark:text-gray-200 transition rounded-lg p-1 ml-1"
  233. type="button"
  234. on:click={() => {
  235. filesInputElement.click();
  236. }}
  237. >
  238. <svg
  239. xmlns="http://www.w3.org/2000/svg"
  240. viewBox="0 0 20 20"
  241. fill="currentColor"
  242. class="w-5 h-5"
  243. >
  244. <path
  245. fill-rule="evenodd"
  246. d="M15.621 4.379a3 3 0 00-4.242 0l-7 7a3 3 0 004.241 4.243h.001l.497-.5a.75.75 0 011.064 1.057l-.498.501-.002.002a4.5 4.5 0 01-6.364-6.364l7-7a4.5 4.5 0 016.368 6.36l-3.455 3.553A2.625 2.625 0 119.52 9.52l3.45-3.451a.75.75 0 111.061 1.06l-3.45 3.451a1.125 1.125 0 001.587 1.595l3.454-3.553a3 3 0 000-4.242z"
  247. clip-rule="evenodd"
  248. />
  249. </svg>
  250. </button>
  251. </div>
  252. {/if}
  253. <textarea
  254. id="chat-textarea"
  255. class=" dark:bg-gray-800 dark:text-gray-100 outline-none w-full py-3 px-2 {fileUploadEnabled
  256. ? ''
  257. : ' pl-4'} rounded-xl resize-none"
  258. placeholder={speechRecognitionListening ? 'Listening...' : 'Send a message'}
  259. bind:value={prompt}
  260. on:keypress={(e) => {
  261. if (e.keyCode == 13 && !e.shiftKey) {
  262. e.preventDefault();
  263. }
  264. if (prompt !== '' && e.keyCode == 13 && !e.shiftKey) {
  265. submitPrompt(prompt);
  266. }
  267. }}
  268. rows="1"
  269. on:input={(e) => {
  270. e.target.style.height = '';
  271. e.target.style.height = Math.min(e.target.scrollHeight, 200) + 'px';
  272. }}
  273. on:paste={(e) => {
  274. const clipboardData = e.clipboardData || window.clipboardData;
  275. if (clipboardData && clipboardData.items) {
  276. for (const item of clipboardData.items) {
  277. if (item.type.indexOf('image') !== -1) {
  278. const blob = item.getAsFile();
  279. const reader = new FileReader();
  280. reader.onload = function (e) {
  281. files = [
  282. ...files,
  283. {
  284. type: 'image',
  285. url: `${e.target.result}`
  286. }
  287. ];
  288. };
  289. reader.readAsDataURL(blob);
  290. }
  291. }
  292. }
  293. }}
  294. />
  295. <div class="self-end mb-2 flex space-x-0.5 mr-2">
  296. {#if messages.length == 0 || messages.at(-1).done == true}
  297. {#if speechRecognitionEnabled}
  298. <button
  299. class=" text-gray-600 dark:text-gray-300 transition rounded-lg p-1.5 mr-0.5 self-center"
  300. type="button"
  301. on:click={() => {
  302. speechRecognitionHandler();
  303. }}
  304. >
  305. {#if speechRecognitionListening}
  306. <svg
  307. class=" w-5 h-5 translate-y-[0.5px]"
  308. fill="currentColor"
  309. viewBox="0 0 24 24"
  310. xmlns="http://www.w3.org/2000/svg"
  311. ><style>
  312. .spinner_qM83 {
  313. animation: spinner_8HQG 1.05s infinite;
  314. }
  315. .spinner_oXPr {
  316. animation-delay: 0.1s;
  317. }
  318. .spinner_ZTLf {
  319. animation-delay: 0.2s;
  320. }
  321. @keyframes spinner_8HQG {
  322. 0%,
  323. 57.14% {
  324. animation-timing-function: cubic-bezier(0.33, 0.66, 0.66, 1);
  325. transform: translate(0);
  326. }
  327. 28.57% {
  328. animation-timing-function: cubic-bezier(0.33, 0, 0.66, 0.33);
  329. transform: translateY(-6px);
  330. }
  331. 100% {
  332. transform: translate(0);
  333. }
  334. }
  335. </style><circle class="spinner_qM83" cx="4" cy="12" r="2.5" /><circle
  336. class="spinner_qM83 spinner_oXPr"
  337. cx="12"
  338. cy="12"
  339. r="2.5"
  340. /><circle class="spinner_qM83 spinner_ZTLf" cx="20" cy="12" r="2.5" /></svg
  341. >
  342. {:else}
  343. <svg
  344. xmlns="http://www.w3.org/2000/svg"
  345. viewBox="0 0 20 20"
  346. fill="currentColor"
  347. class="w-5 h-5 translate-y-[0.5px]"
  348. >
  349. <path d="M7 4a3 3 0 016 0v6a3 3 0 11-6 0V4z" />
  350. <path
  351. d="M5.5 9.643a.75.75 0 00-1.5 0V10c0 3.06 2.29 5.585 5.25 5.954V17.5h-1.5a.75.75 0 000 1.5h4.5a.75.75 0 000-1.5h-1.5v-1.546A6.001 6.001 0 0016 10v-.357a.75.75 0 00-1.5 0V10a4.5 4.5 0 01-9 0v-.357z"
  352. />
  353. </svg>
  354. {/if}
  355. </button>
  356. {/if}
  357. <button
  358. class="{prompt !== ''
  359. ? 'bg-black text-white hover:bg-gray-900 dark:bg-white dark:text-black dark:hover:bg-gray-100 '
  360. : 'text-white bg-gray-100 dark:text-gray-800 dark:bg-gray-600 disabled'} transition rounded-lg p-1 mr-0.5 w-7 h-7 self-center"
  361. type="submit"
  362. disabled={prompt === ''}
  363. >
  364. <svg
  365. xmlns="http://www.w3.org/2000/svg"
  366. viewBox="0 0 20 20"
  367. fill="currentColor"
  368. class="w-5 h-5"
  369. >
  370. <path
  371. fill-rule="evenodd"
  372. d="M10 17a.75.75 0 01-.75-.75V5.612L5.29 9.77a.75.75 0 01-1.08-1.04l5.25-5.5a.75.75 0 011.08 0l5.25 5.5a.75.75 0 11-1.08 1.04l-3.96-4.158V16.25A.75.75 0 0110 17z"
  373. clip-rule="evenodd"
  374. />
  375. </svg>
  376. </button>
  377. {:else}
  378. <button
  379. class="bg-white hover:bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-white dark:hover:bg-gray-800 transition rounded-lg p-1.5"
  380. on:click={stopResponse}
  381. >
  382. <svg
  383. xmlns="http://www.w3.org/2000/svg"
  384. viewBox="0 0 24 24"
  385. fill="currentColor"
  386. class="w-5 h-5"
  387. >
  388. <path
  389. fill-rule="evenodd"
  390. d="M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12zm6-2.438c0-.724.588-1.312 1.313-1.312h4.874c.725 0 1.313.588 1.313 1.313v4.874c0 .725-.588 1.313-1.313 1.313H9.564a1.312 1.312 0 01-1.313-1.313V9.564z"
  391. clip-rule="evenodd"
  392. />
  393. </svg>
  394. </button>
  395. {/if}
  396. </div>
  397. </div>
  398. </form>
  399. <div class="mt-1.5 text-xs text-gray-500 text-center">
  400. LLMs can make mistakes. Verify important information.
  401. </div>
  402. </div>
  403. </div>
  404. </div>
  405. </div>