SearchModal.svelte 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. <script lang="ts">
  2. import { toast } from 'svelte-sonner';
  3. import { getContext, onDestroy, onMount, tick } from 'svelte';
  4. const i18n = getContext('i18n');
  5. import Modal from '$lib/components/common/Modal.svelte';
  6. import SearchInput from './Sidebar/SearchInput.svelte';
  7. import { getChatById, getChatList, getChatListBySearchText } from '$lib/apis/chats';
  8. import Spinner from '../common/Spinner.svelte';
  9. import dayjs from '$lib/dayjs';
  10. import calendar from 'dayjs/plugin/calendar';
  11. import Loader from '../common/Loader.svelte';
  12. import { createMessagesList } from '$lib/utils';
  13. import { user } from '$lib/stores';
  14. import Messages from '../chat/Messages.svelte';
  15. dayjs.extend(calendar);
  16. export let show = false;
  17. export let onClose = () => {};
  18. let query = '';
  19. let page = 1;
  20. let chatList = null;
  21. let chatListLoading = false;
  22. let allChatsLoaded = false;
  23. let searchDebounceTimeout;
  24. let selectedIdx = 0;
  25. let selectedChat = null;
  26. let selectedModels = [''];
  27. let history = null;
  28. let messages = null;
  29. $: if (!chatListLoading && chatList) {
  30. loadChatPreview(selectedIdx);
  31. }
  32. const loadChatPreview = async (selectedIdx) => {
  33. if (!chatList || chatList.length === 0 || chatList[selectedIdx] === undefined) {
  34. selectedChat = null;
  35. messages = null;
  36. history = null;
  37. selectedModels = [''];
  38. return;
  39. }
  40. const chatId = chatList[selectedIdx].id;
  41. const chat = await getChatById(localStorage.token, chatId).catch(async (error) => {
  42. return null;
  43. });
  44. if (chat) {
  45. if (chat?.chat?.history) {
  46. selectedModels =
  47. (chat?.chat?.models ?? undefined) !== undefined
  48. ? chat?.chat?.models
  49. : [chat?.chat?.models ?? ''];
  50. history = chat?.chat?.history;
  51. messages = createMessagesList(chat?.chat?.history, chat?.chat?.history?.currentId);
  52. // scroll to the bottom of the messages container
  53. await tick();
  54. const messagesContainerElement = document.getElementById('chat-preview');
  55. if (messagesContainerElement) {
  56. messagesContainerElement.scrollTop = messagesContainerElement.scrollHeight;
  57. }
  58. } else {
  59. messages = [];
  60. }
  61. } else {
  62. toast.error($i18n.t('Failed to load chat preview'));
  63. selectedChat = null;
  64. messages = null;
  65. history = null;
  66. selectedModels = [''];
  67. return;
  68. }
  69. };
  70. const searchHandler = async () => {
  71. if (searchDebounceTimeout) {
  72. clearTimeout(searchDebounceTimeout);
  73. }
  74. page = 1;
  75. chatList = null;
  76. if (query === '') {
  77. chatList = await getChatList(localStorage.token, page);
  78. } else {
  79. searchDebounceTimeout = setTimeout(async () => {
  80. chatList = await getChatListBySearchText(localStorage.token, query, page);
  81. if ((chatList ?? []).length === 0) {
  82. allChatsLoaded = true;
  83. } else {
  84. allChatsLoaded = false;
  85. }
  86. }, 500);
  87. }
  88. selectedChat = null;
  89. messages = null;
  90. history = null;
  91. selectedModels = [''];
  92. if ((chatList ?? []).length === 0) {
  93. allChatsLoaded = true;
  94. } else {
  95. allChatsLoaded = false;
  96. }
  97. };
  98. const loadMoreChats = async () => {
  99. chatListLoading = true;
  100. page += 1;
  101. let newChatList = [];
  102. if (query) {
  103. newChatList = await getChatListBySearchText(localStorage.token, query, page);
  104. } else {
  105. newChatList = await getChatList(localStorage.token, page);
  106. }
  107. // once the bottom of the list has been reached (no results) there is no need to continue querying
  108. allChatsLoaded = newChatList.length === 0;
  109. if (newChatList.length > 0) {
  110. chatList = [...chatList, ...newChatList];
  111. }
  112. chatListLoading = false;
  113. };
  114. const init = () => {
  115. searchHandler();
  116. };
  117. const onKeyDown = (e) => {
  118. const searchOptions = document.getElementById('search-options-container');
  119. if (searchOptions || !show) {
  120. return;
  121. }
  122. if (e.code === 'Escape') {
  123. show = false;
  124. onClose();
  125. } else if (e.code === 'Enter' && (chatList ?? []).length > 0) {
  126. const item = document.querySelector(`[data-arrow-selected="true"]`);
  127. if (item) {
  128. item?.click();
  129. }
  130. show = false;
  131. return;
  132. } else if (e.code === 'ArrowDown') {
  133. const searchInput = document.getElementById('search-input');
  134. if (searchInput) {
  135. // check if focused on the search input
  136. if (document.activeElement === searchInput) {
  137. searchInput.blur();
  138. selectedIdx = 0;
  139. return;
  140. }
  141. }
  142. selectedIdx = Math.min(selectedIdx + 1, (chatList ?? []).length - 1);
  143. } else if (e.code === 'ArrowUp') {
  144. if (selectedIdx === 0) {
  145. const searchInput = document.getElementById('search-input');
  146. if (searchInput) {
  147. // check if focused on the search input
  148. if (document.activeElement !== searchInput) {
  149. searchInput.focus();
  150. selectedIdx = 0;
  151. return;
  152. }
  153. }
  154. }
  155. selectedIdx = Math.max(selectedIdx - 1, 0);
  156. }
  157. const item = document.querySelector(`[data-arrow-selected="true"]`);
  158. item?.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
  159. };
  160. onMount(() => {
  161. init();
  162. document.addEventListener('keydown', onKeyDown);
  163. });
  164. onDestroy(() => {
  165. if (searchDebounceTimeout) {
  166. clearTimeout(searchDebounceTimeout);
  167. }
  168. document.removeEventListener('keydown', onKeyDown);
  169. });
  170. </script>
  171. <Modal size="xl" bind:show>
  172. <div class="py-2.5 dark:text-gray-300 text-gray-700">
  173. <div class="px-3.5 pb-1.5">
  174. <SearchInput
  175. bind:value={query}
  176. on:input={searchHandler}
  177. placeholder={$i18n.t('Search')}
  178. showClearButton={true}
  179. onKeydown={(e) => {
  180. console.log('e', e);
  181. if (e.code === 'Enter' && (chatList ?? []).length > 0) {
  182. const item = document.querySelector(`[data-arrow-selected="true"]`);
  183. if (item) {
  184. item?.click();
  185. }
  186. show = false;
  187. return;
  188. } else if (e.code === 'ArrowDown') {
  189. selectedIdx = Math.min(selectedIdx + 1, (chatList ?? []).length - 1);
  190. } else if (e.code === 'ArrowUp') {
  191. selectedIdx = Math.max(selectedIdx - 1, 0);
  192. } else {
  193. selectedIdx = 0;
  194. }
  195. const item = document.querySelector(`[data-arrow-selected="true"]`);
  196. item?.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
  197. }}
  198. />
  199. </div>
  200. <!-- <hr class="border-gray-100 dark:border-gray-850 my-1" /> -->
  201. <div class="flex px-3 pb-1">
  202. <div
  203. class="flex flex-col overflow-y-auto h-96 md:h-[40rem] max-h-full scrollbar-hidden w-full flex-1"
  204. >
  205. {#if chatList}
  206. {#if chatList.length === 0}
  207. <div class="text-xs text-gray-500 dark:text-gray-400 text-center px-5">
  208. {$i18n.t('No results found')}
  209. </div>
  210. {/if}
  211. {#each chatList as chat, idx (chat.id)}
  212. {#if idx === 0 || (idx > 0 && chat.time_range !== chatList[idx - 1].time_range)}
  213. <div
  214. class="w-full text-xs text-gray-500 dark:text-gray-500 font-medium {idx === 0
  215. ? ''
  216. : 'pt-5'} pb-2 px-2"
  217. >
  218. {$i18n.t(chat.time_range)}
  219. <!-- localisation keys for time_range to be recognized from the i18next parser (so they don't get automatically removed):
  220. {$i18n.t('Today')}
  221. {$i18n.t('Yesterday')}
  222. {$i18n.t('Previous 7 days')}
  223. {$i18n.t('Previous 30 days')}
  224. {$i18n.t('January')}
  225. {$i18n.t('February')}
  226. {$i18n.t('March')}
  227. {$i18n.t('April')}
  228. {$i18n.t('May')}
  229. {$i18n.t('June')}
  230. {$i18n.t('July')}
  231. {$i18n.t('August')}
  232. {$i18n.t('September')}
  233. {$i18n.t('October')}
  234. {$i18n.t('November')}
  235. {$i18n.t('December')}
  236. -->
  237. </div>
  238. {/if}
  239. <a
  240. class=" w-full flex justify-between items-center rounded-lg text-sm py-2 px-3 hover:bg-gray-50 dark:hover:bg-gray-850 {selectedIdx ===
  241. idx
  242. ? 'bg-gray-50 dark:bg-gray-850'
  243. : ''}"
  244. href="/c/{chat.id}"
  245. draggable="false"
  246. data-arrow-selected={selectedIdx === idx ? 'true' : undefined}
  247. on:mouseenter={() => {
  248. selectedIdx = idx;
  249. }}
  250. on:click={() => {
  251. show = false;
  252. onClose();
  253. }}
  254. >
  255. <div class=" flex-1">
  256. <div class="text-ellipsis line-clamp-1 w-full">
  257. {chat?.title}
  258. </div>
  259. </div>
  260. <div class=" pl-3 shrink-0 text-gray-500 dark:text-gray-400 text-xs">
  261. {dayjs(chat?.updated_at * 1000).calendar()}
  262. </div>
  263. </a>
  264. {/each}
  265. {#if !allChatsLoaded}
  266. <Loader
  267. on:visible={(e) => {
  268. if (!chatListLoading) {
  269. loadMoreChats();
  270. }
  271. }}
  272. >
  273. <div class="w-full flex justify-center py-1 text-xs animate-pulse items-center gap-2">
  274. <Spinner className=" size-4" />
  275. <div class=" ">Loading...</div>
  276. </div>
  277. </Loader>
  278. {/if}
  279. {:else}
  280. <div class="w-full h-full flex justify-center items-center">
  281. <Spinner className="size-5" />
  282. </div>
  283. {/if}
  284. </div>
  285. <div
  286. id="chat-preview"
  287. class="hidden md:flex md:flex-1 w-full overflow-y-auto h-96 md:h-[40rem] scrollbar-hidden"
  288. >
  289. {#if messages === null}
  290. <div
  291. class="w-full h-full flex justify-center items-center text-gray-500 dark:text-gray-400 text-sm"
  292. >
  293. {$i18n.t('Select a conversation to preview')}
  294. </div>
  295. {:else}
  296. <div class="w-full h-full flex flex-col">
  297. <Messages
  298. className="h-full flex pt-4 pb-8 w-full"
  299. user={$user}
  300. readOnly={true}
  301. {selectedModels}
  302. bind:history
  303. bind:messages
  304. autoScroll={true}
  305. sendPrompt={() => {}}
  306. continueResponse={() => {}}
  307. regenerateResponse={() => {}}
  308. />
  309. </div>
  310. {/if}
  311. </div>
  312. </div>
  313. </div>
  314. </Modal>