MessageInput.svelte 16 KB

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