MessageInput.svelte 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  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 { blobToFile, calculateSHA256, findWordIndices } from '$lib/utils';
  6. import Prompts from './MessageInput/PromptCommands.svelte';
  7. import Suggestions from './MessageInput/Suggestions.svelte';
  8. import { uploadDocToVectorDB, uploadWebToVectorDB } from '$lib/apis/rag';
  9. import AddFilesPlaceholder from '../AddFilesPlaceholder.svelte';
  10. import { SUPPORTED_FILE_TYPE, SUPPORTED_FILE_EXTENSIONS } from '$lib/constants';
  11. import Documents from './MessageInput/Documents.svelte';
  12. import Models from './MessageInput/Models.svelte';
  13. import { transcribeAudio } from '$lib/apis/audio';
  14. export let submitPrompt: Function;
  15. export let stopResponse: Function;
  16. export let suggestionPrompts = [];
  17. export let autoScroll = true;
  18. let filesInputElement;
  19. let promptsElement;
  20. let documentsElement;
  21. let modelsElement;
  22. let inputFiles;
  23. let dragged = false;
  24. let user = null;
  25. let chatInputPlaceholder = '';
  26. export let files = [];
  27. export let fileUploadEnabled = true;
  28. export let speechRecognitionEnabled = true;
  29. export let prompt = '';
  30. export let messages = [];
  31. let speechRecognition;
  32. $: if (prompt) {
  33. const chatInput = document.getElementById('chat-textarea');
  34. if (chatInput) {
  35. chatInput.style.height = '';
  36. chatInput.style.height = Math.min(chatInput.scrollHeight, 200) + 'px';
  37. }
  38. }
  39. let mediaRecorder;
  40. let audioChunks = [];
  41. let isRecording = false;
  42. const MIN_DECIBELS = -45;
  43. const startRecording = async () => {
  44. const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
  45. mediaRecorder = new MediaRecorder(stream);
  46. mediaRecorder.onstart = () => {
  47. isRecording = true;
  48. console.log('Recording started');
  49. };
  50. mediaRecorder.ondataavailable = (event) => audioChunks.push(event.data);
  51. mediaRecorder.onstop = async () => {
  52. isRecording = false;
  53. console.log('Recording stopped');
  54. // Create a blob from the audio chunks
  55. const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
  56. const file = blobToFile(audioBlob, 'recording.wav');
  57. const res = await transcribeAudio(localStorage.token, file).catch((error) => {
  58. toast.error(error);
  59. return null;
  60. });
  61. if (res) {
  62. prompt = res.text;
  63. await tick();
  64. const inputElement = document.getElementById('chat-textarea');
  65. inputElement?.focus();
  66. if (prompt !== '' && $settings?.speechAutoSend === true) {
  67. submitPrompt(prompt, user);
  68. }
  69. }
  70. // saveRecording(audioBlob);
  71. audioChunks = [];
  72. };
  73. // Start recording
  74. mediaRecorder.start();
  75. // Monitor silence
  76. monitorSilence(stream);
  77. };
  78. const monitorSilence = (stream) => {
  79. const audioContext = new AudioContext();
  80. const audioStreamSource = audioContext.createMediaStreamSource(stream);
  81. const analyser = audioContext.createAnalyser();
  82. analyser.minDecibels = MIN_DECIBELS;
  83. audioStreamSource.connect(analyser);
  84. const bufferLength = analyser.frequencyBinCount;
  85. const domainData = new Uint8Array(bufferLength);
  86. let lastSoundTime = Date.now();
  87. const detectSound = () => {
  88. analyser.getByteFrequencyData(domainData);
  89. if (domainData.some((value) => value > 0)) {
  90. lastSoundTime = Date.now();
  91. }
  92. if (isRecording && Date.now() - lastSoundTime > 3000) {
  93. mediaRecorder.stop();
  94. audioContext.close();
  95. return;
  96. }
  97. window.requestAnimationFrame(detectSound);
  98. };
  99. window.requestAnimationFrame(detectSound);
  100. };
  101. const saveRecording = (blob) => {
  102. const url = URL.createObjectURL(blob);
  103. const a = document.createElement('a');
  104. document.body.appendChild(a);
  105. a.style = 'display: none';
  106. a.href = url;
  107. a.download = 'recording.wav';
  108. a.click();
  109. window.URL.revokeObjectURL(url);
  110. };
  111. const speechRecognitionHandler = () => {
  112. // Check if SpeechRecognition is supported
  113. if (isRecording) {
  114. if (speechRecognition) {
  115. speechRecognition.stop();
  116. }
  117. if (mediaRecorder) {
  118. mediaRecorder.stop();
  119. }
  120. } else {
  121. isRecording = true;
  122. if ($settings?.audio?.STTEngine ?? '' !== '') {
  123. startRecording();
  124. } else {
  125. if ('SpeechRecognition' in window || 'webkitSpeechRecognition' in window) {
  126. // Create a SpeechRecognition object
  127. speechRecognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
  128. // Set continuous to true for continuous recognition
  129. speechRecognition.continuous = true;
  130. // Set the timeout for turning off the recognition after inactivity (in milliseconds)
  131. const inactivityTimeout = 3000; // 3 seconds
  132. let timeoutId;
  133. // Start recognition
  134. speechRecognition.start();
  135. // Event triggered when speech is recognized
  136. speechRecognition.onresult = async (event) => {
  137. // Clear the inactivity timeout
  138. clearTimeout(timeoutId);
  139. // Handle recognized speech
  140. console.log(event);
  141. const transcript = event.results[Object.keys(event.results).length - 1][0].transcript;
  142. prompt = `${prompt}${transcript}`;
  143. await tick();
  144. const inputElement = document.getElementById('chat-textarea');
  145. inputElement?.focus();
  146. // Restart the inactivity timeout
  147. timeoutId = setTimeout(() => {
  148. console.log('Speech recognition turned off due to inactivity.');
  149. speechRecognition.stop();
  150. }, inactivityTimeout);
  151. };
  152. // Event triggered when recognition is ended
  153. speechRecognition.onend = function () {
  154. // Restart recognition after it ends
  155. console.log('recognition ended');
  156. isRecording = false;
  157. if (prompt !== '' && $settings?.speechAutoSend === true) {
  158. submitPrompt(prompt, user);
  159. }
  160. };
  161. // Event triggered when an error occurs
  162. speechRecognition.onerror = function (event) {
  163. console.log(event);
  164. toast.error(`Speech recognition error: ${event.error}`);
  165. isRecording = false;
  166. };
  167. } else {
  168. toast.error('SpeechRecognition API is not supported in this browser.');
  169. }
  170. }
  171. }
  172. };
  173. const uploadDoc = async (file) => {
  174. console.log(file);
  175. const doc = {
  176. type: 'doc',
  177. name: file.name,
  178. collection_name: '',
  179. upload_status: false,
  180. error: ''
  181. };
  182. try {
  183. files = [...files, doc];
  184. if (['audio/mpeg', 'audio/wav'].includes(file['type'])) {
  185. const res = await transcribeAudio(localStorage.token, file).catch((error) => {
  186. toast.error(error);
  187. return null;
  188. });
  189. if (res) {
  190. console.log(res);
  191. const blob = new Blob([res.text], { type: 'text/plain' });
  192. file = blobToFile(blob, `${file.name}.txt`);
  193. }
  194. }
  195. const res = await uploadDocToVectorDB(localStorage.token, '', file);
  196. if (res) {
  197. doc.upload_status = true;
  198. doc.collection_name = res.collection_name;
  199. files = files;
  200. }
  201. } catch (e) {
  202. // Remove the failed doc from the files array
  203. files = files.filter((f) => f.name !== file.name);
  204. toast.error(e);
  205. }
  206. };
  207. const uploadWeb = async (url) => {
  208. console.log(url);
  209. const doc = {
  210. type: 'doc',
  211. name: url,
  212. collection_name: '',
  213. upload_status: false,
  214. url: url,
  215. error: ''
  216. };
  217. try {
  218. files = [...files, doc];
  219. const res = await uploadWebToVectorDB(localStorage.token, '', url);
  220. if (res) {
  221. doc.upload_status = true;
  222. doc.collection_name = res.collection_name;
  223. files = files;
  224. }
  225. } catch (e) {
  226. // Remove the failed doc from the files array
  227. files = files.filter((f) => f.name !== url);
  228. toast.error(e);
  229. }
  230. };
  231. onMount(() => {
  232. const dropZone = document.querySelector('body');
  233. const onDragOver = (e) => {
  234. e.preventDefault();
  235. dragged = true;
  236. };
  237. const onDragLeave = () => {
  238. dragged = false;
  239. };
  240. const onDrop = async (e) => {
  241. e.preventDefault();
  242. console.log(e);
  243. if (e.dataTransfer?.files) {
  244. let reader = new FileReader();
  245. reader.onload = (event) => {
  246. files = [
  247. ...files,
  248. {
  249. type: 'image',
  250. url: `${event.target.result}`
  251. }
  252. ];
  253. };
  254. const inputFiles = e.dataTransfer?.files;
  255. if (inputFiles && inputFiles.length > 0) {
  256. const file = inputFiles[0];
  257. console.log(file, file.name.split('.').at(-1));
  258. if (['image/gif', 'image/jpeg', 'image/png'].includes(file['type'])) {
  259. reader.readAsDataURL(file);
  260. } else if (
  261. SUPPORTED_FILE_TYPE.includes(file['type']) ||
  262. SUPPORTED_FILE_EXTENSIONS.includes(file.name.split('.').at(-1))
  263. ) {
  264. uploadDoc(file);
  265. } else {
  266. toast.error(
  267. `Unknown File Type '${file['type']}', but accepting and treating as plain text`
  268. );
  269. uploadDoc(file);
  270. }
  271. } else {
  272. toast.error(`File not found.`);
  273. }
  274. }
  275. dragged = false;
  276. };
  277. dropZone?.addEventListener('dragover', onDragOver);
  278. dropZone?.addEventListener('drop', onDrop);
  279. dropZone?.addEventListener('dragleave', onDragLeave);
  280. return () => {
  281. dropZone?.removeEventListener('dragover', onDragOver);
  282. dropZone?.removeEventListener('drop', onDrop);
  283. dropZone?.removeEventListener('dragleave', onDragLeave);
  284. };
  285. });
  286. </script>
  287. {#if dragged}
  288. <div
  289. class="fixed w-full h-full flex z-50 touch-none pointer-events-none"
  290. id="dropzone"
  291. role="region"
  292. aria-label="Drag and Drop Container"
  293. >
  294. <div class="absolute rounded-xl w-full h-full backdrop-blur bg-gray-800/40 flex justify-center">
  295. <div class="m-auto pt-64 flex flex-col justify-center">
  296. <div class="max-w-md">
  297. <AddFilesPlaceholder />
  298. </div>
  299. </div>
  300. </div>
  301. </div>
  302. {/if}
  303. <div class="fixed bottom-0 w-full">
  304. <div class="px-2.5 pt-2.5 -mb-0.5 mx-auto inset-x-0 bg-transparent flex justify-center">
  305. <div class="flex flex-col max-w-3xl w-full">
  306. <div>
  307. {#if autoScroll === false && messages.length > 0}
  308. <div class=" flex justify-center mb-4">
  309. <button
  310. class=" bg-white border border-gray-100 dark:border-none dark:bg-white/20 p-1.5 rounded-full"
  311. on:click={() => {
  312. autoScroll = true;
  313. window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
  314. }}
  315. >
  316. <svg
  317. xmlns="http://www.w3.org/2000/svg"
  318. viewBox="0 0 20 20"
  319. fill="currentColor"
  320. class="w-5 h-5"
  321. >
  322. <path
  323. fill-rule="evenodd"
  324. 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"
  325. clip-rule="evenodd"
  326. />
  327. </svg>
  328. </button>
  329. </div>
  330. {/if}
  331. </div>
  332. <div class="w-full">
  333. {#if prompt.charAt(0) === '/'}
  334. <Prompts bind:this={promptsElement} bind:prompt />
  335. {:else if prompt.charAt(0) === '#'}
  336. <Documents
  337. bind:this={documentsElement}
  338. bind:prompt
  339. on:url={(e) => {
  340. console.log(e);
  341. uploadWeb(e.detail);
  342. }}
  343. on:select={(e) => {
  344. console.log(e);
  345. files = [
  346. ...files,
  347. {
  348. type: e?.detail?.type ?? 'doc',
  349. ...e.detail,
  350. upload_status: true
  351. }
  352. ];
  353. }}
  354. />
  355. {:else if prompt.charAt(0) === '@'}
  356. <Models
  357. bind:this={modelsElement}
  358. bind:prompt
  359. bind:user
  360. bind:chatInputPlaceholder
  361. {messages}
  362. />
  363. {:else if messages.length == 0 && suggestionPrompts.length !== 0}
  364. <Suggestions {suggestionPrompts} {submitPrompt} />
  365. {/if}
  366. </div>
  367. </div>
  368. </div>
  369. <div class="bg-white dark:bg-gray-900">
  370. <div class="max-w-3xl px-2.5 -mb-0.5 mx-auto inset-x-0">
  371. <div class=" pb-2">
  372. <input
  373. bind:this={filesInputElement}
  374. bind:files={inputFiles}
  375. type="file"
  376. hidden
  377. on:change={async () => {
  378. let reader = new FileReader();
  379. reader.onload = (event) => {
  380. files = [
  381. ...files,
  382. {
  383. type: 'image',
  384. url: `${event.target.result}`
  385. }
  386. ];
  387. inputFiles = null;
  388. filesInputElement.value = '';
  389. };
  390. if (inputFiles && inputFiles.length > 0) {
  391. const file = inputFiles[0];
  392. if (['image/gif', 'image/jpeg', 'image/png'].includes(file['type'])) {
  393. reader.readAsDataURL(file);
  394. } else if (
  395. SUPPORTED_FILE_TYPE.includes(file['type']) ||
  396. SUPPORTED_FILE_EXTENSIONS.includes(file.name.split('.').at(-1))
  397. ) {
  398. uploadDoc(file);
  399. filesInputElement.value = '';
  400. } else {
  401. toast.error(
  402. `Unknown File Type '${file['type']}', but accepting and treating as plain text`
  403. );
  404. uploadDoc(file);
  405. filesInputElement.value = '';
  406. }
  407. } else {
  408. toast.error(`File not found.`);
  409. }
  410. }}
  411. />
  412. <form
  413. class=" flex flex-col relative w-full rounded-xl border dark:border-gray-700 bg-white dark:bg-gray-900 dark:text-gray-100"
  414. on:submit|preventDefault={() => {
  415. submitPrompt(prompt, user);
  416. }}
  417. >
  418. {#if files.length > 0}
  419. <div class="mx-2 mt-2 mb-1 flex flex-wrap gap-2">
  420. {#each files as file, fileIdx}
  421. <div class=" relative group">
  422. {#if file.type === 'image'}
  423. <img src={file.url} alt="input" class=" h-16 w-16 rounded-xl object-cover" />
  424. {:else if file.type === 'doc'}
  425. <div
  426. 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"
  427. >
  428. <div class="p-2.5 bg-red-400 text-white rounded-lg">
  429. {#if file.upload_status}
  430. <svg
  431. xmlns="http://www.w3.org/2000/svg"
  432. viewBox="0 0 24 24"
  433. fill="currentColor"
  434. class="w-6 h-6"
  435. >
  436. <path
  437. fill-rule="evenodd"
  438. 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"
  439. clip-rule="evenodd"
  440. />
  441. <path
  442. 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"
  443. />
  444. </svg>
  445. {:else}
  446. <svg
  447. class=" w-6 h-6 translate-y-[0.5px]"
  448. fill="currentColor"
  449. viewBox="0 0 24 24"
  450. xmlns="http://www.w3.org/2000/svg"
  451. ><style>
  452. .spinner_qM83 {
  453. animation: spinner_8HQG 1.05s infinite;
  454. }
  455. .spinner_oXPr {
  456. animation-delay: 0.1s;
  457. }
  458. .spinner_ZTLf {
  459. animation-delay: 0.2s;
  460. }
  461. @keyframes spinner_8HQG {
  462. 0%,
  463. 57.14% {
  464. animation-timing-function: cubic-bezier(0.33, 0.66, 0.66, 1);
  465. transform: translate(0);
  466. }
  467. 28.57% {
  468. animation-timing-function: cubic-bezier(0.33, 0, 0.66, 0.33);
  469. transform: translateY(-6px);
  470. }
  471. 100% {
  472. transform: translate(0);
  473. }
  474. }
  475. </style><circle class="spinner_qM83" cx="4" cy="12" r="2.5" /><circle
  476. class="spinner_qM83 spinner_oXPr"
  477. cx="12"
  478. cy="12"
  479. r="2.5"
  480. /><circle
  481. class="spinner_qM83 spinner_ZTLf"
  482. cx="20"
  483. cy="12"
  484. r="2.5"
  485. /></svg
  486. >
  487. {/if}
  488. </div>
  489. <div class="flex flex-col justify-center -space-y-0.5">
  490. <div class=" dark:text-gray-100 text-sm font-medium line-clamp-1">
  491. {file.name}
  492. </div>
  493. <div class=" text-gray-500 text-sm">Document</div>
  494. </div>
  495. </div>
  496. {:else if file.type === 'collection'}
  497. <div
  498. 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"
  499. >
  500. <div class="p-2.5 bg-red-400 text-white rounded-lg">
  501. <svg
  502. xmlns="http://www.w3.org/2000/svg"
  503. viewBox="0 0 24 24"
  504. fill="currentColor"
  505. class="w-6 h-6"
  506. >
  507. <path
  508. d="M7.5 3.375c0-1.036.84-1.875 1.875-1.875h.375a3.75 3.75 0 0 1 3.75 3.75v1.875C13.5 8.161 14.34 9 15.375 9h1.875A3.75 3.75 0 0 1 21 12.75v3.375C21 17.16 20.16 18 19.125 18h-9.75A1.875 1.875 0 0 1 7.5 16.125V3.375Z"
  509. />
  510. <path
  511. d="M15 5.25a5.23 5.23 0 0 0-1.279-3.434 9.768 9.768 0 0 1 6.963 6.963A5.23 5.23 0 0 0 17.25 7.5h-1.875A.375.375 0 0 1 15 7.125V5.25ZM4.875 6H6v10.125A3.375 3.375 0 0 0 9.375 19.5H16.5v1.125c0 1.035-.84 1.875-1.875 1.875h-9.75A1.875 1.875 0 0 1 3 20.625V7.875C3 6.839 3.84 6 4.875 6Z"
  512. />
  513. </svg>
  514. </div>
  515. <div class="flex flex-col justify-center -space-y-0.5">
  516. <div class=" dark:text-gray-100 text-sm font-medium line-clamp-1">
  517. {file?.title ?? `#${file.name}`}
  518. </div>
  519. <div class=" text-gray-500 text-sm">Collection</div>
  520. </div>
  521. </div>
  522. {/if}
  523. <div class=" absolute -top-1 -right-1">
  524. <button
  525. class=" bg-gray-400 text-white border border-white rounded-full group-hover:visible invisible transition"
  526. type="button"
  527. on:click={() => {
  528. files.splice(fileIdx, 1);
  529. files = files;
  530. }}
  531. >
  532. <svg
  533. xmlns="http://www.w3.org/2000/svg"
  534. viewBox="0 0 20 20"
  535. fill="currentColor"
  536. class="w-4 h-4"
  537. >
  538. <path
  539. 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"
  540. />
  541. </svg>
  542. </button>
  543. </div>
  544. </div>
  545. {/each}
  546. </div>
  547. {/if}
  548. <div class=" flex">
  549. {#if fileUploadEnabled}
  550. <div class=" self-end mb-2 ml-1.5">
  551. <button
  552. class=" text-gray-600 dark:text-gray-200 transition rounded-lg p-1 ml-1"
  553. type="button"
  554. on:click={() => {
  555. filesInputElement.click();
  556. }}
  557. >
  558. <svg
  559. xmlns="http://www.w3.org/2000/svg"
  560. viewBox="0 0 20 20"
  561. fill="currentColor"
  562. class="w-5 h-5"
  563. >
  564. <path
  565. fill-rule="evenodd"
  566. 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"
  567. clip-rule="evenodd"
  568. />
  569. </svg>
  570. </button>
  571. </div>
  572. {/if}
  573. <textarea
  574. id="chat-textarea"
  575. class=" dark:bg-gray-900 dark:text-gray-100 outline-none w-full py-3 px-2 {fileUploadEnabled
  576. ? ''
  577. : ' pl-4'} rounded-xl resize-none h-[48px]"
  578. placeholder={chatInputPlaceholder !== ''
  579. ? chatInputPlaceholder
  580. : isRecording
  581. ? 'Listening...'
  582. : 'Send a message'}
  583. bind:value={prompt}
  584. on:keypress={(e) => {
  585. if (e.keyCode == 13 && !e.shiftKey) {
  586. e.preventDefault();
  587. }
  588. if (prompt !== '' && e.keyCode == 13 && !e.shiftKey) {
  589. submitPrompt(prompt, user);
  590. }
  591. }}
  592. on:keydown={async (e) => {
  593. const isCtrlPressed = e.ctrlKey || e.metaKey; // metaKey is for Cmd key on Mac
  594. // Check if Ctrl + R is pressed
  595. if (prompt === '' && isCtrlPressed && e.key.toLowerCase() === 'r') {
  596. e.preventDefault();
  597. console.log('regenerate');
  598. const regenerateButton = [
  599. ...document.getElementsByClassName('regenerate-response-button')
  600. ]?.at(-1);
  601. regenerateButton?.click();
  602. }
  603. if (prompt === '' && e.key == 'ArrowUp') {
  604. e.preventDefault();
  605. const userMessageElement = [
  606. ...document.getElementsByClassName('user-message')
  607. ]?.at(-1);
  608. const editButton = [
  609. ...document.getElementsByClassName('edit-user-message-button')
  610. ]?.at(-1);
  611. console.log(userMessageElement);
  612. userMessageElement.scrollIntoView({ block: 'center' });
  613. editButton?.click();
  614. }
  615. if (['/', '#', '@'].includes(prompt.charAt(0)) && e.key === 'ArrowUp') {
  616. e.preventDefault();
  617. (promptsElement || documentsElement || modelsElement).selectUp();
  618. const commandOptionButton = [
  619. ...document.getElementsByClassName('selected-command-option-button')
  620. ]?.at(-1);
  621. commandOptionButton.scrollIntoView({ block: 'center' });
  622. }
  623. if (['/', '#', '@'].includes(prompt.charAt(0)) && e.key === 'ArrowDown') {
  624. e.preventDefault();
  625. (promptsElement || documentsElement || modelsElement).selectDown();
  626. const commandOptionButton = [
  627. ...document.getElementsByClassName('selected-command-option-button')
  628. ]?.at(-1);
  629. commandOptionButton.scrollIntoView({ block: 'center' });
  630. }
  631. if (['/', '#', '@'].includes(prompt.charAt(0)) && e.key === 'Enter') {
  632. e.preventDefault();
  633. const commandOptionButton = [
  634. ...document.getElementsByClassName('selected-command-option-button')
  635. ]?.at(-1);
  636. commandOptionButton?.click();
  637. }
  638. if (['/', '#', '@'].includes(prompt.charAt(0)) && e.key === 'Tab') {
  639. e.preventDefault();
  640. const commandOptionButton = [
  641. ...document.getElementsByClassName('selected-command-option-button')
  642. ]?.at(-1);
  643. commandOptionButton?.click();
  644. } else if (e.key === 'Tab') {
  645. const words = findWordIndices(prompt);
  646. if (words.length > 0) {
  647. const word = words.at(0);
  648. const fullPrompt = prompt;
  649. prompt = prompt.substring(0, word?.endIndex + 1);
  650. await tick();
  651. e.target.scrollTop = e.target.scrollHeight;
  652. prompt = fullPrompt;
  653. await tick();
  654. e.preventDefault();
  655. e.target.setSelectionRange(word?.startIndex, word.endIndex + 1);
  656. }
  657. }
  658. }}
  659. rows="1"
  660. on:input={(e) => {
  661. e.target.style.height = '';
  662. e.target.style.height = Math.min(e.target.scrollHeight, 200) + 'px';
  663. user = null;
  664. }}
  665. on:focus={(e) => {
  666. e.target.style.height = '';
  667. e.target.style.height = Math.min(e.target.scrollHeight, 200) + 'px';
  668. }}
  669. on:paste={(e) => {
  670. const clipboardData = e.clipboardData || window.clipboardData;
  671. if (clipboardData && clipboardData.items) {
  672. for (const item of clipboardData.items) {
  673. if (item.type.indexOf('image') !== -1) {
  674. const blob = item.getAsFile();
  675. const reader = new FileReader();
  676. reader.onload = function (e) {
  677. files = [
  678. ...files,
  679. {
  680. type: 'image',
  681. url: `${e.target.result}`
  682. }
  683. ];
  684. };
  685. reader.readAsDataURL(blob);
  686. }
  687. }
  688. }
  689. }}
  690. />
  691. <div class="self-end mb-2 flex space-x-0.5 mr-2">
  692. {#if messages.length == 0 || messages.at(-1).done == true}
  693. {#if speechRecognitionEnabled}
  694. <button
  695. id="voice-input-button"
  696. class=" text-gray-600 dark:text-gray-300 transition rounded-lg p-1.5 mr-0.5 self-center"
  697. type="button"
  698. on:click={() => {
  699. speechRecognitionHandler();
  700. }}
  701. >
  702. {#if isRecording}
  703. <svg
  704. class=" w-5 h-5 translate-y-[0.5px]"
  705. fill="currentColor"
  706. viewBox="0 0 24 24"
  707. xmlns="http://www.w3.org/2000/svg"
  708. ><style>
  709. .spinner_qM83 {
  710. animation: spinner_8HQG 1.05s infinite;
  711. }
  712. .spinner_oXPr {
  713. animation-delay: 0.1s;
  714. }
  715. .spinner_ZTLf {
  716. animation-delay: 0.2s;
  717. }
  718. @keyframes spinner_8HQG {
  719. 0%,
  720. 57.14% {
  721. animation-timing-function: cubic-bezier(0.33, 0.66, 0.66, 1);
  722. transform: translate(0);
  723. }
  724. 28.57% {
  725. animation-timing-function: cubic-bezier(0.33, 0, 0.66, 0.33);
  726. transform: translateY(-6px);
  727. }
  728. 100% {
  729. transform: translate(0);
  730. }
  731. }
  732. </style><circle class="spinner_qM83" cx="4" cy="12" r="2.5" /><circle
  733. class="spinner_qM83 spinner_oXPr"
  734. cx="12"
  735. cy="12"
  736. r="2.5"
  737. /><circle class="spinner_qM83 spinner_ZTLf" cx="20" cy="12" r="2.5" /></svg
  738. >
  739. {:else}
  740. <svg
  741. xmlns="http://www.w3.org/2000/svg"
  742. viewBox="0 0 20 20"
  743. fill="currentColor"
  744. class="w-5 h-5 translate-y-[0.5px]"
  745. >
  746. <path d="M7 4a3 3 0 016 0v6a3 3 0 11-6 0V4z" />
  747. <path
  748. 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"
  749. />
  750. </svg>
  751. {/if}
  752. </button>
  753. {/if}
  754. <button
  755. class="{prompt !== ''
  756. ? 'bg-black text-white hover:bg-gray-900 dark:bg-white dark:text-black dark:hover:bg-gray-100 '
  757. : 'text-white bg-gray-100 dark:text-gray-900 dark:bg-gray-800 disabled'} transition rounded-lg p-1 mr-0.5 w-7 h-7 self-center"
  758. type="submit"
  759. disabled={prompt === ''}
  760. >
  761. <svg
  762. xmlns="http://www.w3.org/2000/svg"
  763. viewBox="0 0 16 16"
  764. fill="currentColor"
  765. class="w-4.5 h-4.5 mx-auto"
  766. >
  767. <path
  768. fill-rule="evenodd"
  769. d="M8 14a.75.75 0 0 1-.75-.75V4.56L4.03 7.78a.75.75 0 0 1-1.06-1.06l4.5-4.5a.75.75 0 0 1 1.06 0l4.5 4.5a.75.75 0 0 1-1.06 1.06L8.75 4.56v8.69A.75.75 0 0 1 8 14Z"
  770. clip-rule="evenodd"
  771. />
  772. </svg>
  773. </button>
  774. {:else}
  775. <button
  776. 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"
  777. on:click={stopResponse}
  778. >
  779. <svg
  780. xmlns="http://www.w3.org/2000/svg"
  781. viewBox="0 0 24 24"
  782. fill="currentColor"
  783. class="w-5 h-5"
  784. >
  785. <path
  786. fill-rule="evenodd"
  787. 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"
  788. clip-rule="evenodd"
  789. />
  790. </svg>
  791. </button>
  792. {/if}
  793. </div>
  794. </div>
  795. </form>
  796. <div class="mt-1.5 text-xs text-gray-500 text-center">
  797. LLMs can make mistakes. Verify important information.
  798. </div>
  799. </div>
  800. </div>
  801. </div>
  802. </div>