MessageInput.svelte 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. <script lang="ts">
  2. import toast from 'svelte-french-toast';
  3. import { onMount, tick } from 'svelte';
  4. import { settings } from '$lib/stores';
  5. import { calculateSHA256, findWordIndices } from '$lib/utils';
  6. import Prompts from './MessageInput/PromptCommands.svelte';
  7. import Suggestions from './MessageInput/Suggestions.svelte';
  8. import { uploadDocToVectorDB } from '$lib/apis/rag';
  9. export let submitPrompt: Function;
  10. export let stopResponse: Function;
  11. export let suggestionPrompts = [];
  12. export let autoScroll = true;
  13. let filesInputElement;
  14. let promptsElement;
  15. let inputFiles;
  16. let dragged = false;
  17. export let files = [];
  18. export let fileUploadEnabled = true;
  19. export let speechRecognitionEnabled = true;
  20. export let speechRecognitionListening = false;
  21. export let prompt = '';
  22. export let messages = [];
  23. let speechRecognition;
  24. const speechRecognitionHandler = () => {
  25. // Check if SpeechRecognition is supported
  26. if (speechRecognitionListening) {
  27. speechRecognition.stop();
  28. } else {
  29. if ('SpeechRecognition' in window || 'webkitSpeechRecognition' in window) {
  30. // Create a SpeechRecognition object
  31. speechRecognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
  32. // Set continuous to true for continuous recognition
  33. speechRecognition.continuous = true;
  34. // Set the timeout for turning off the recognition after inactivity (in milliseconds)
  35. const inactivityTimeout = 3000; // 3 seconds
  36. let timeoutId;
  37. // Start recognition
  38. speechRecognition.start();
  39. speechRecognitionListening = true;
  40. // Event triggered when speech is recognized
  41. speechRecognition.onresult = function (event) {
  42. // Clear the inactivity timeout
  43. clearTimeout(timeoutId);
  44. // Handle recognized speech
  45. console.log(event);
  46. const transcript = event.results[Object.keys(event.results).length - 1][0].transcript;
  47. prompt = `${prompt}${transcript}`;
  48. // Restart the inactivity timeout
  49. timeoutId = setTimeout(() => {
  50. console.log('Speech recognition turned off due to inactivity.');
  51. speechRecognition.stop();
  52. }, inactivityTimeout);
  53. };
  54. // Event triggered when recognition is ended
  55. speechRecognition.onend = function () {
  56. // Restart recognition after it ends
  57. console.log('recognition ended');
  58. speechRecognitionListening = false;
  59. if (prompt !== '' && $settings?.speechAutoSend === true) {
  60. submitPrompt(prompt);
  61. }
  62. };
  63. // Event triggered when an error occurs
  64. speechRecognition.onerror = function (event) {
  65. console.log(event);
  66. toast.error(`Speech recognition error: ${event.error}`);
  67. speechRecognitionListening = false;
  68. };
  69. } else {
  70. toast.error('SpeechRecognition API is not supported in this browser.');
  71. }
  72. }
  73. };
  74. onMount(() => {
  75. const dropZone = document.querySelector('body');
  76. dropZone?.addEventListener('dragover', (e) => {
  77. e.preventDefault();
  78. dragged = true;
  79. });
  80. dropZone.addEventListener('drop', async (e) => {
  81. e.preventDefault();
  82. console.log(e);
  83. if (e.dataTransfer?.files) {
  84. let reader = new FileReader();
  85. reader.onload = (event) => {
  86. files = [
  87. ...files,
  88. {
  89. type: 'image',
  90. url: `${event.target.result}`
  91. }
  92. ];
  93. };
  94. const inputFiles = e.dataTransfer?.files;
  95. if (inputFiles && inputFiles.length > 0) {
  96. const file = inputFiles[0];
  97. if (['image/gif', 'image/jpeg', 'image/png'].includes(file['type'])) {
  98. reader.readAsDataURL(file);
  99. } else if (['application/pdf', 'text/plain'].includes(file['type'])) {
  100. console.log(file);
  101. // const hash = (await calculateSHA256(file)).substring(0, 63);
  102. const res = await uploadDocToVectorDB(localStorage.token, '', file);
  103. if (res) {
  104. files = [
  105. ...files,
  106. {
  107. type: 'doc',
  108. name: file.name,
  109. collection_name: res.collection_name
  110. }
  111. ];
  112. }
  113. } else {
  114. toast.error(`Unsupported File Type '${file['type']}'.`);
  115. }
  116. } else {
  117. toast.error(`File not found.`);
  118. }
  119. }
  120. dragged = false;
  121. });
  122. dropZone?.addEventListener('dragleave', () => {
  123. dragged = false;
  124. });
  125. });
  126. </script>
  127. {#if dragged}
  128. <div
  129. class="fixed w-full h-full flex z-50 touch-none pointer-events-none"
  130. id="dropzone"
  131. role="region"
  132. aria-label="Drag and Drop Container"
  133. >
  134. <div class="absolute rounded-xl w-full h-full backdrop-blur bg-gray-800/40 flex justify-center">
  135. <div class="m-auto pt-64 flex flex-col justify-center">
  136. <div class="max-w-md">
  137. <div class=" text-center text-6xl mb-3">🗂️</div>
  138. <div class="text-center dark:text-white text-2xl font-semibold z-50">Add Files</div>
  139. <div class=" mt-2 text-center text-sm dark:text-gray-200 w-full">
  140. Drop any files/images here to add to the conversation
  141. </div>
  142. </div>
  143. </div>
  144. </div>
  145. </div>
  146. {/if}
  147. <div class="fixed bottom-0 w-full">
  148. <div class="px-2.5 pt-2.5 -mb-0.5 mx-auto inset-x-0 bg-transparent flex justify-center">
  149. <div class="flex flex-col max-w-3xl w-full">
  150. <div>
  151. {#if autoScroll === false && messages.length > 0}
  152. <div class=" flex justify-center mb-4">
  153. <button
  154. class=" bg-white border border-gray-100 dark:border-none dark:bg-white/20 p-1.5 rounded-full"
  155. on:click={() => {
  156. autoScroll = true;
  157. window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
  158. }}
  159. >
  160. <svg
  161. xmlns="http://www.w3.org/2000/svg"
  162. viewBox="0 0 20 20"
  163. fill="currentColor"
  164. class="w-5 h-5"
  165. >
  166. <path
  167. fill-rule="evenodd"
  168. 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"
  169. clip-rule="evenodd"
  170. />
  171. </svg>
  172. </button>
  173. </div>
  174. {/if}
  175. </div>
  176. <div class="w-full">
  177. {#if prompt.charAt(0) === '/'}
  178. <Prompts bind:this={promptsElement} bind:prompt />
  179. {:else if messages.length == 0 && suggestionPrompts.length !== 0}
  180. <Suggestions {suggestionPrompts} {submitPrompt} />
  181. {/if}
  182. </div>
  183. </div>
  184. </div>
  185. <div class="bg-white dark:bg-gray-800">
  186. <div class="max-w-3xl px-2.5 -mb-0.5 mx-auto inset-x-0">
  187. <div class="bg-gradient-to-t from-white dark:from-gray-800 from-40% pb-2">
  188. <input
  189. bind:this={filesInputElement}
  190. bind:files={inputFiles}
  191. type="file"
  192. hidden
  193. on:change={async () => {
  194. let reader = new FileReader();
  195. reader.onload = (event) => {
  196. files = [
  197. ...files,
  198. {
  199. type: 'image',
  200. url: `${event.target.result}`
  201. }
  202. ];
  203. inputFiles = null;
  204. filesInputElement.value = '';
  205. };
  206. if (inputFiles && inputFiles.length > 0) {
  207. const file = inputFiles[0];
  208. if (['image/gif', 'image/jpeg', 'image/png'].includes(file['type'])) {
  209. reader.readAsDataURL(file);
  210. } else if (['application/pdf', 'text/plain'].includes(file['type'])) {
  211. console.log(file);
  212. // const hash = (await calculateSHA256(file)).substring(0, 63);
  213. const res = await uploadDocToVectorDB(localStorage.token, '', file);
  214. if (res) {
  215. files = [
  216. ...files,
  217. {
  218. type: 'doc',
  219. name: file.name,
  220. collection_name: res.collection_name
  221. }
  222. ];
  223. filesInputElement.value = '';
  224. }
  225. } else {
  226. toast.error(`Unsupported File Type '${file['type']}'.`);
  227. inputFiles = null;
  228. }
  229. } else {
  230. toast.error(`File not found.`);
  231. }
  232. }}
  233. />
  234. <form
  235. class=" flex flex-col relative w-full rounded-xl border dark:border-gray-600 bg-white dark:bg-gray-800 dark:text-gray-100"
  236. on:submit|preventDefault={() => {
  237. submitPrompt(prompt);
  238. }}
  239. >
  240. {#if files.length > 0}
  241. <div class="mx-2 mt-2 mb-1 flex flex-wrap gap-2">
  242. {#each files as file, fileIdx}
  243. <div class=" relative group">
  244. {#if file.type === 'image'}
  245. <img src={file.url} alt="input" class=" h-16 w-16 rounded-xl object-cover" />
  246. {:else if file.type === 'doc'}
  247. <div
  248. class="h-16 w-[15rem] flex items-center space-x-3 px-2.5 dark:bg-gray-600 rounded-xl border border-gray-200 dark:border-none"
  249. >
  250. <div class="p-2.5 bg-red-400 text-white rounded-lg">
  251. <svg
  252. xmlns="http://www.w3.org/2000/svg"
  253. viewBox="0 0 24 24"
  254. fill="currentColor"
  255. class="w-6 h-6"
  256. >
  257. <path
  258. fill-rule="evenodd"
  259. d="M5.625 1.5c-1.036 0-1.875.84-1.875 1.875v17.25c0 1.035.84 1.875 1.875 1.875h12.75c1.035 0 1.875-.84 1.875-1.875V12.75A3.75 3.75 0 0 0 16.5 9h-1.875a1.875 1.875 0 0 1-1.875-1.875V5.25A3.75 3.75 0 0 0 9 1.5H5.625ZM7.5 15a.75.75 0 0 1 .75-.75h7.5a.75.75 0 0 1 0 1.5h-7.5A.75.75 0 0 1 7.5 15Zm.75 2.25a.75.75 0 0 0 0 1.5H12a.75.75 0 0 0 0-1.5H8.25Z"
  260. clip-rule="evenodd"
  261. />
  262. <path
  263. d="M12.971 1.816A5.23 5.23 0 0 1 14.25 5.25v1.875c0 .207.168.375.375.375H16.5a5.23 5.23 0 0 1 3.434 1.279 9.768 9.768 0 0 0-6.963-6.963Z"
  264. />
  265. </svg>
  266. </div>
  267. <div class="flex flex-col justify-center -space-y-0.5">
  268. <div class=" dark:text-gray-100 text-sm font-medium line-clamp-1">
  269. {file.name}
  270. </div>
  271. <div class=" text-gray-500 text-sm">Document</div>
  272. </div>
  273. </div>
  274. {/if}
  275. <div class=" absolute -top-1 -right-1">
  276. <button
  277. class=" bg-gray-400 text-white border border-white rounded-full group-hover:visible invisible transition"
  278. type="button"
  279. on:click={() => {
  280. files.splice(fileIdx, 1);
  281. files = files;
  282. }}
  283. >
  284. <svg
  285. xmlns="http://www.w3.org/2000/svg"
  286. viewBox="0 0 20 20"
  287. fill="currentColor"
  288. class="w-4 h-4"
  289. >
  290. <path
  291. 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"
  292. />
  293. </svg>
  294. </button>
  295. </div>
  296. </div>
  297. {/each}
  298. </div>
  299. {/if}
  300. <div class=" flex">
  301. {#if fileUploadEnabled}
  302. <div class=" self-end mb-2 ml-1.5">
  303. <button
  304. class=" text-gray-600 dark:text-gray-200 transition rounded-lg p-1 ml-1"
  305. type="button"
  306. on:click={() => {
  307. filesInputElement.click();
  308. }}
  309. >
  310. <svg
  311. xmlns="http://www.w3.org/2000/svg"
  312. viewBox="0 0 20 20"
  313. fill="currentColor"
  314. class="w-5 h-5"
  315. >
  316. <path
  317. fill-rule="evenodd"
  318. 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"
  319. clip-rule="evenodd"
  320. />
  321. </svg>
  322. </button>
  323. </div>
  324. {/if}
  325. <textarea
  326. id="chat-textarea"
  327. class=" dark:bg-gray-800 dark:text-gray-100 outline-none w-full py-3 px-2 {fileUploadEnabled
  328. ? ''
  329. : ' pl-4'} rounded-xl resize-none h-[48px]"
  330. placeholder={speechRecognitionListening ? 'Listening...' : 'Send a message'}
  331. bind:value={prompt}
  332. on:keypress={(e) => {
  333. if (e.keyCode == 13 && !e.shiftKey) {
  334. e.preventDefault();
  335. }
  336. if (prompt !== '' && e.keyCode == 13 && !e.shiftKey) {
  337. submitPrompt(prompt);
  338. }
  339. }}
  340. on:keydown={async (e) => {
  341. if (prompt === '' && e.key == 'ArrowUp') {
  342. e.preventDefault();
  343. const userMessageElement = [
  344. ...document.getElementsByClassName('user-message')
  345. ]?.at(-1);
  346. const editButton = [
  347. ...document.getElementsByClassName('edit-user-message-button')
  348. ]?.at(-1);
  349. console.log(userMessageElement);
  350. userMessageElement.scrollIntoView({ block: 'center' });
  351. editButton?.click();
  352. }
  353. if (prompt.charAt(0) === '/' && e.key === 'ArrowUp') {
  354. promptsElement.selectUp();
  355. const commandOptionButton = [
  356. ...document.getElementsByClassName('selected-command-option-button')
  357. ]?.at(-1);
  358. commandOptionButton.scrollIntoView({ block: 'center' });
  359. }
  360. if (prompt.charAt(0) === '/' && e.key === 'ArrowDown') {
  361. promptsElement.selectDown();
  362. const commandOptionButton = [
  363. ...document.getElementsByClassName('selected-command-option-button')
  364. ]?.at(-1);
  365. commandOptionButton.scrollIntoView({ block: 'center' });
  366. }
  367. if (prompt.charAt(0) === '/' && e.key === 'Enter') {
  368. e.preventDefault();
  369. const commandOptionButton = [
  370. ...document.getElementsByClassName('selected-command-option-button')
  371. ]?.at(-1);
  372. commandOptionButton?.click();
  373. }
  374. if (prompt.charAt(0) === '/' && e.key === 'Tab') {
  375. e.preventDefault();
  376. const commandOptionButton = [
  377. ...document.getElementsByClassName('selected-command-option-button')
  378. ]?.at(-1);
  379. commandOptionButton?.click();
  380. } else if (e.key === 'Tab') {
  381. const words = findWordIndices(prompt);
  382. if (words.length > 0) {
  383. const word = words.at(0);
  384. const fullPrompt = prompt;
  385. prompt = prompt.substring(0, word?.endIndex + 1);
  386. await tick();
  387. e.target.scrollTop = e.target.scrollHeight;
  388. prompt = fullPrompt;
  389. await tick();
  390. e.preventDefault();
  391. e.target.setSelectionRange(word?.startIndex, word.endIndex + 1);
  392. }
  393. }
  394. }}
  395. rows="1"
  396. on:input={(e) => {
  397. e.target.style.height = '';
  398. e.target.style.height = Math.min(e.target.scrollHeight, 200) + 'px';
  399. }}
  400. on:paste={(e) => {
  401. const clipboardData = e.clipboardData || window.clipboardData;
  402. if (clipboardData && clipboardData.items) {
  403. for (const item of clipboardData.items) {
  404. if (item.type.indexOf('image') !== -1) {
  405. const blob = item.getAsFile();
  406. const reader = new FileReader();
  407. reader.onload = function (e) {
  408. files = [
  409. ...files,
  410. {
  411. type: 'image',
  412. url: `${e.target.result}`
  413. }
  414. ];
  415. };
  416. reader.readAsDataURL(blob);
  417. }
  418. }
  419. }
  420. }}
  421. />
  422. <div class="self-end mb-2 flex space-x-0.5 mr-2">
  423. {#if messages.length == 0 || messages.at(-1).done == true}
  424. {#if speechRecognitionEnabled}
  425. <button
  426. class=" text-gray-600 dark:text-gray-300 transition rounded-lg p-1.5 mr-0.5 self-center"
  427. type="button"
  428. on:click={() => {
  429. speechRecognitionHandler();
  430. }}
  431. >
  432. {#if speechRecognitionListening}
  433. <svg
  434. class=" w-5 h-5 translate-y-[0.5px]"
  435. fill="currentColor"
  436. viewBox="0 0 24 24"
  437. xmlns="http://www.w3.org/2000/svg"
  438. ><style>
  439. .spinner_qM83 {
  440. animation: spinner_8HQG 1.05s infinite;
  441. }
  442. .spinner_oXPr {
  443. animation-delay: 0.1s;
  444. }
  445. .spinner_ZTLf {
  446. animation-delay: 0.2s;
  447. }
  448. @keyframes spinner_8HQG {
  449. 0%,
  450. 57.14% {
  451. animation-timing-function: cubic-bezier(0.33, 0.66, 0.66, 1);
  452. transform: translate(0);
  453. }
  454. 28.57% {
  455. animation-timing-function: cubic-bezier(0.33, 0, 0.66, 0.33);
  456. transform: translateY(-6px);
  457. }
  458. 100% {
  459. transform: translate(0);
  460. }
  461. }
  462. </style><circle class="spinner_qM83" cx="4" cy="12" r="2.5" /><circle
  463. class="spinner_qM83 spinner_oXPr"
  464. cx="12"
  465. cy="12"
  466. r="2.5"
  467. /><circle class="spinner_qM83 spinner_ZTLf" cx="20" cy="12" r="2.5" /></svg
  468. >
  469. {:else}
  470. <svg
  471. xmlns="http://www.w3.org/2000/svg"
  472. viewBox="0 0 20 20"
  473. fill="currentColor"
  474. class="w-5 h-5 translate-y-[0.5px]"
  475. >
  476. <path d="M7 4a3 3 0 016 0v6a3 3 0 11-6 0V4z" />
  477. <path
  478. 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"
  479. />
  480. </svg>
  481. {/if}
  482. </button>
  483. {/if}
  484. <button
  485. class="{prompt !== ''
  486. ? 'bg-black text-white hover:bg-gray-900 dark:bg-white dark:text-black dark:hover:bg-gray-100 '
  487. : '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"
  488. type="submit"
  489. disabled={prompt === ''}
  490. >
  491. <svg
  492. xmlns="http://www.w3.org/2000/svg"
  493. viewBox="0 0 20 20"
  494. fill="currentColor"
  495. class="w-5 h-5"
  496. >
  497. <path
  498. fill-rule="evenodd"
  499. 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"
  500. clip-rule="evenodd"
  501. />
  502. </svg>
  503. </button>
  504. {:else}
  505. <button
  506. 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"
  507. on:click={stopResponse}
  508. >
  509. <svg
  510. xmlns="http://www.w3.org/2000/svg"
  511. viewBox="0 0 24 24"
  512. fill="currentColor"
  513. class="w-5 h-5"
  514. >
  515. <path
  516. fill-rule="evenodd"
  517. 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"
  518. clip-rule="evenodd"
  519. />
  520. </svg>
  521. </button>
  522. {/if}
  523. </div>
  524. </div>
  525. </form>
  526. <div class="mt-1.5 text-xs text-gray-500 text-center">
  527. LLMs can make mistakes. Verify important information.
  528. </div>
  529. </div>
  530. </div>
  531. </div>
  532. </div>