MessageInput.svelte 28 KB

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