Sidebar.svelte 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. <script lang="ts">
  2. import { toast } from 'svelte-sonner';
  3. import { goto } from '$app/navigation';
  4. import {
  5. user,
  6. chats,
  7. settings,
  8. showSettings,
  9. chatId,
  10. tags,
  11. showSidebar,
  12. mobile,
  13. showArchivedChats,
  14. pinnedChats,
  15. scrollPaginationEnabled,
  16. currentChatPage,
  17. temporaryChatEnabled
  18. } from '$lib/stores';
  19. import { onMount, getContext, tick } from 'svelte';
  20. const i18n = getContext('i18n');
  21. import { updateUserSettings } from '$lib/apis/users';
  22. import {
  23. deleteChatById,
  24. getChatList,
  25. getChatById,
  26. getChatListByTagName,
  27. updateChatById,
  28. getAllChatTags,
  29. archiveChatById,
  30. cloneChatById
  31. } from '$lib/apis/chats';
  32. import { WEBUI_BASE_URL } from '$lib/constants';
  33. import ArchivedChatsModal from './Sidebar/ArchivedChatsModal.svelte';
  34. import UserMenu from './Sidebar/UserMenu.svelte';
  35. import ChatItem from './Sidebar/ChatItem.svelte';
  36. import DeleteConfirmDialog from '$lib/components/common/ConfirmDialog.svelte';
  37. import Spinner from '../common/Spinner.svelte';
  38. import Loader from '../common/Loader.svelte';
  39. const BREAKPOINT = 768;
  40. let navElement;
  41. let search = '';
  42. let shiftKey = false;
  43. let selectedChatId = null;
  44. let deleteChat = null;
  45. let showDeleteConfirm = false;
  46. let showDropdown = false;
  47. let filteredChatList = [];
  48. // Pagination variables
  49. let chatListLoading = false;
  50. let allChatsLoaded = false;
  51. $: filteredChatList = $chats.filter((chat) => {
  52. if (search === '') {
  53. return true;
  54. } else {
  55. let title = chat.title.toLowerCase();
  56. const query = search.toLowerCase();
  57. let contentMatches = false;
  58. // Access the messages within chat.chat.messages
  59. if (chat.chat && chat.chat.messages && Array.isArray(chat.chat.messages)) {
  60. contentMatches = chat.chat.messages.some((message) => {
  61. // Check if message.content exists and includes the search query
  62. return message.content && message.content.toLowerCase().includes(query);
  63. });
  64. }
  65. return title.includes(query) || contentMatches;
  66. }
  67. });
  68. const enablePagination = async () => {
  69. // Reset pagination variables
  70. currentChatPage.set(1);
  71. allChatsLoaded = false;
  72. await chats.set(await getChatList(localStorage.token, $currentChatPage));
  73. // Enable pagination
  74. scrollPaginationEnabled.set(true);
  75. };
  76. const loadMoreChats = async () => {
  77. chatListLoading = true;
  78. currentChatPage.set($currentChatPage + 1);
  79. const newChatList = await getChatList(localStorage.token, $currentChatPage);
  80. // once the bottom of the list has been reached (no results) there is no need to continue querying
  81. allChatsLoaded = newChatList.length === 0;
  82. await chats.set([...$chats, ...newChatList]);
  83. chatListLoading = false;
  84. };
  85. onMount(async () => {
  86. mobile.subscribe((e) => {
  87. if ($showSidebar && e) {
  88. showSidebar.set(false);
  89. }
  90. if (!$showSidebar && !e) {
  91. showSidebar.set(true);
  92. }
  93. });
  94. showSidebar.set(window.innerWidth > BREAKPOINT);
  95. await pinnedChats.set(await getChatListByTagName(localStorage.token, 'pinned'));
  96. await enablePagination();
  97. let touchstart;
  98. let touchend;
  99. function checkDirection() {
  100. const screenWidth = window.innerWidth;
  101. const swipeDistance = Math.abs(touchend.screenX - touchstart.screenX);
  102. if (touchstart.clientX < 40 && swipeDistance >= screenWidth / 8) {
  103. if (touchend.screenX < touchstart.screenX) {
  104. showSidebar.set(false);
  105. }
  106. if (touchend.screenX > touchstart.screenX) {
  107. showSidebar.set(true);
  108. }
  109. }
  110. }
  111. const onTouchStart = (e) => {
  112. touchstart = e.changedTouches[0];
  113. console.log(touchstart.clientX);
  114. };
  115. const onTouchEnd = (e) => {
  116. touchend = e.changedTouches[0];
  117. checkDirection();
  118. };
  119. const onKeyDown = (e) => {
  120. if (e.key === 'Shift') {
  121. shiftKey = true;
  122. }
  123. };
  124. const onKeyUp = (e) => {
  125. if (e.key === 'Shift') {
  126. shiftKey = false;
  127. }
  128. };
  129. const onFocus = () => {};
  130. const onBlur = () => {
  131. shiftKey = false;
  132. selectedChatId = null;
  133. };
  134. window.addEventListener('keydown', onKeyDown);
  135. window.addEventListener('keyup', onKeyUp);
  136. window.addEventListener('touchstart', onTouchStart);
  137. window.addEventListener('touchend', onTouchEnd);
  138. window.addEventListener('focus', onFocus);
  139. window.addEventListener('blur', onBlur);
  140. return () => {
  141. window.removeEventListener('keydown', onKeyDown);
  142. window.removeEventListener('keyup', onKeyUp);
  143. window.removeEventListener('touchstart', onTouchStart);
  144. window.removeEventListener('touchend', onTouchEnd);
  145. window.removeEventListener('focus', onFocus);
  146. window.removeEventListener('blur', onBlur);
  147. };
  148. });
  149. // Helper function to fetch and add chat content to each chat
  150. const enrichChatsWithContent = async (chatList) => {
  151. const enrichedChats = await Promise.all(
  152. chatList.map(async (chat) => {
  153. const chatDetails = await getChatById(localStorage.token, chat.id).catch((error) => null); // Handle error or non-existent chat gracefully
  154. if (chatDetails) {
  155. chat.chat = chatDetails.chat; // Assuming chatDetails.chat contains the chat content
  156. }
  157. return chat;
  158. })
  159. );
  160. await chats.set(enrichedChats);
  161. };
  162. const saveSettings = async (updated) => {
  163. await settings.set({ ...$settings, ...updated });
  164. await updateUserSettings(localStorage.token, { ui: $settings });
  165. location.href = '/';
  166. };
  167. const deleteChatHandler = async (id) => {
  168. const res = await deleteChatById(localStorage.token, id).catch((error) => {
  169. toast.error(error);
  170. return null;
  171. });
  172. if (res) {
  173. if ($chatId === id) {
  174. await chatId.set('');
  175. await tick();
  176. goto('/');
  177. }
  178. allChatsLoaded = false;
  179. currentChatPage.set(1);
  180. await chats.set(await getChatList(localStorage.token, $currentChatPage));
  181. await pinnedChats.set(await getChatListByTagName(localStorage.token, 'pinned'));
  182. }
  183. };
  184. </script>
  185. <ArchivedChatsModal
  186. bind:show={$showArchivedChats}
  187. on:change={async () => {
  188. await chats.set(await getChatList(localStorage.token));
  189. }}
  190. />
  191. <DeleteConfirmDialog
  192. bind:show={showDeleteConfirm}
  193. title={$i18n.t('Delete chat?')}
  194. on:confirm={() => {
  195. deleteChatHandler(deleteChat.id);
  196. }}
  197. >
  198. <div class=" text-sm text-gray-500">
  199. {$i18n.t('This will delete')} <span class=" font-semibold">{deleteChat.title}</span>.
  200. </div>
  201. </DeleteConfirmDialog>
  202. <!-- svelte-ignore a11y-no-static-element-interactions -->
  203. {#if $showSidebar}
  204. <div
  205. class=" fixed md:hidden z-40 top-0 right-0 left-0 bottom-0 bg-black/60 w-full min-h-screen h-screen flex justify-center overflow-hidden overscroll-contain"
  206. on:mousedown={() => {
  207. showSidebar.set(!$showSidebar);
  208. }}
  209. />
  210. {/if}
  211. <div
  212. bind:this={navElement}
  213. id="sidebar"
  214. class="h-screen max-h-[100dvh] min-h-screen select-none {$showSidebar
  215. ? 'md:relative w-[260px]'
  216. : '-translate-x-[260px] w-[0px]'} bg-gray-50 text-gray-900 dark:bg-gray-950 dark:text-gray-200 text-sm transition fixed z-50 top-0 left-0
  217. "
  218. data-state={$showSidebar}
  219. >
  220. <div
  221. class="py-2.5 my-auto flex flex-col justify-between h-screen max-h-[100dvh] w-[260px] z-50 {$showSidebar
  222. ? ''
  223. : 'invisible'}"
  224. >
  225. <div class="px-2.5 flex justify-between space-x-1 text-gray-600 dark:text-gray-400">
  226. <a
  227. id="sidebar-new-chat-button"
  228. class="flex flex-1 justify-between rounded-xl px-2 h-full hover:bg-gray-100 dark:hover:bg-gray-900 transition"
  229. href="/"
  230. draggable="false"
  231. on:click={async () => {
  232. selectedChatId = null;
  233. await goto('/');
  234. const newChatButton = document.getElementById('new-chat-button');
  235. setTimeout(() => {
  236. newChatButton?.click();
  237. if ($mobile) {
  238. showSidebar.set(false);
  239. }
  240. }, 0);
  241. }}
  242. >
  243. <div class="self-center mx-1.5">
  244. <img
  245. crossorigin="anonymous"
  246. src="{WEBUI_BASE_URL}/static/favicon.png"
  247. class=" size-6 -translate-x-1.5 rounded-full"
  248. alt="logo"
  249. />
  250. </div>
  251. <div class=" self-center font-medium text-sm text-gray-850 dark:text-white font-primary">
  252. {$i18n.t('New Chat')}
  253. </div>
  254. <div class="self-center ml-auto">
  255. <svg
  256. xmlns="http://www.w3.org/2000/svg"
  257. viewBox="0 0 20 20"
  258. fill="currentColor"
  259. class="size-5"
  260. >
  261. <path
  262. d="M5.433 13.917l1.262-3.155A4 4 0 017.58 9.42l6.92-6.918a2.121 2.121 0 013 3l-6.92 6.918c-.383.383-.84.685-1.343.886l-3.154 1.262a.5.5 0 01-.65-.65z"
  263. />
  264. <path
  265. d="M3.5 5.75c0-.69.56-1.25 1.25-1.25H10A.75.75 0 0010 3H4.75A2.75 2.75 0 002 5.75v9.5A2.75 2.75 0 004.75 18h9.5A2.75 2.75 0 0017 15.25V10a.75.75 0 00-1.5 0v5.25c0 .69-.56 1.25-1.25 1.25h-9.5c-.69 0-1.25-.56-1.25-1.25v-9.5z"
  266. />
  267. </svg>
  268. </div>
  269. </a>
  270. <button
  271. class=" cursor-pointer px-2 py-2 flex rounded-xl hover:bg-gray-100 dark:hover:bg-gray-900 transition"
  272. on:click={() => {
  273. showSidebar.set(!$showSidebar);
  274. }}
  275. >
  276. <div class=" m-auto self-center">
  277. <svg
  278. xmlns="http://www.w3.org/2000/svg"
  279. fill="none"
  280. viewBox="0 0 24 24"
  281. stroke-width="2"
  282. stroke="currentColor"
  283. class="size-5"
  284. >
  285. <path
  286. stroke-linecap="round"
  287. stroke-linejoin="round"
  288. d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25H12"
  289. />
  290. </svg>
  291. </div>
  292. </button>
  293. </div>
  294. {#if $user?.role === 'admin'}
  295. <div class="px-2.5 flex justify-center text-gray-800 dark:text-gray-200">
  296. <a
  297. class="flex-grow flex space-x-3 rounded-xl px-2.5 py-2 hover:bg-gray-100 dark:hover:bg-gray-900 transition"
  298. href="/workspace"
  299. on:click={() => {
  300. selectedChatId = null;
  301. chatId.set('');
  302. if ($mobile) {
  303. showSidebar.set(false);
  304. }
  305. }}
  306. draggable="false"
  307. >
  308. <div class="self-center">
  309. <svg
  310. xmlns="http://www.w3.org/2000/svg"
  311. fill="none"
  312. viewBox="0 0 24 24"
  313. stroke-width="2"
  314. stroke="currentColor"
  315. class="size-[1.1rem]"
  316. >
  317. <path
  318. stroke-linecap="round"
  319. stroke-linejoin="round"
  320. d="M13.5 16.875h3.375m0 0h3.375m-3.375 0V13.5m0 3.375v3.375M6 10.5h2.25a2.25 2.25 0 0 0 2.25-2.25V6a2.25 2.25 0 0 0-2.25-2.25H6A2.25 2.25 0 0 0 3.75 6v2.25A2.25 2.25 0 0 0 6 10.5Zm0 9.75h2.25A2.25 2.25 0 0 0 10.5 18v-2.25a2.25 2.25 0 0 0-2.25-2.25H6a2.25 2.25 0 0 0-2.25 2.25V18A2.25 2.25 0 0 0 6 20.25Zm9.75-9.75H18a2.25 2.25 0 0 0 2.25-2.25V6A2.25 2.25 0 0 0 18 3.75h-2.25A2.25 2.25 0 0 0 13.5 6v2.25a2.25 2.25 0 0 0 2.25 2.25Z"
  321. />
  322. </svg>
  323. </div>
  324. <div class="flex self-center">
  325. <div class=" self-center font-medium text-sm font-primary">{$i18n.t('Workspace')}</div>
  326. </div>
  327. </a>
  328. </div>
  329. {/if}
  330. <div class="relative flex flex-col flex-1 overflow-y-auto">
  331. {#if $temporaryChatEnabled}
  332. <div
  333. class="absolute z-40 w-full h-full bg-gray-50/90 dark:bg-black/90 flex justify-center"
  334. ></div>
  335. {/if}
  336. <div class="px-2 mt-0.5 mb-2 flex justify-center space-x-2">
  337. <div class="flex w-full rounded-xl" id="chat-search">
  338. <div class="self-center pl-3 py-2 rounded-l-xl bg-transparent">
  339. <svg
  340. xmlns="http://www.w3.org/2000/svg"
  341. viewBox="0 0 20 20"
  342. fill="currentColor"
  343. class="w-4 h-4"
  344. >
  345. <path
  346. fill-rule="evenodd"
  347. d="M9 3.5a5.5 5.5 0 100 11 5.5 5.5 0 000-11zM2 9a7 7 0 1112.452 4.391l3.328 3.329a.75.75 0 11-1.06 1.06l-3.329-3.328A7 7 0 012 9z"
  348. clip-rule="evenodd"
  349. />
  350. </svg>
  351. </div>
  352. <input
  353. class="w-full rounded-r-xl py-1.5 pl-2.5 pr-4 text-sm bg-transparent dark:text-gray-300 outline-none"
  354. placeholder={$i18n.t('Search')}
  355. bind:value={search}
  356. on:focus={async () => {
  357. // TODO: migrate backend for more scalable search mechanism
  358. scrollPaginationEnabled.set(false);
  359. await chats.set(await getChatList(localStorage.token)); // when searching, load all chats
  360. enrichChatsWithContent($chats);
  361. }}
  362. />
  363. </div>
  364. </div>
  365. {#if $tags.filter((t) => t.name !== 'pinned').length > 0}
  366. <div class="px-2.5 mb-2 flex gap-1 flex-wrap">
  367. <button
  368. class="px-2.5 text-xs font-medium bg-gray-50 dark:bg-gray-900 dark:hover:bg-gray-800 transition rounded-full"
  369. on:click={async () => {
  370. await enablePagination();
  371. }}
  372. >
  373. {$i18n.t('all')}
  374. </button>
  375. {#each $tags.filter((t) => t.name !== 'pinned') as tag}
  376. <button
  377. class="px-2.5 text-xs font-medium bg-gray-50 dark:bg-gray-900 dark:hover:bg-gray-800 transition rounded-full"
  378. on:click={async () => {
  379. scrollPaginationEnabled.set(false);
  380. let chatIds = await getChatListByTagName(localStorage.token, tag.name);
  381. if (chatIds.length === 0) {
  382. await tags.set(await getAllChatTags(localStorage.token));
  383. // if the tag we deleted is no longer a valid tag, return to main chat list view
  384. await enablePagination();
  385. }
  386. await chats.set(chatIds);
  387. chatListLoading = false;
  388. }}
  389. >
  390. {tag.name}
  391. </button>
  392. {/each}
  393. </div>
  394. {/if}
  395. {#if $pinnedChats.length > 0}
  396. <div class="pl-2 py-2 flex flex-col space-y-1">
  397. <div class="">
  398. <div class="w-full pl-2.5 text-xs text-gray-500 dark:text-gray-500 font-medium pb-1.5">
  399. {$i18n.t('Pinned')}
  400. </div>
  401. {#each $pinnedChats as chat, idx}
  402. <ChatItem
  403. {chat}
  404. {shiftKey}
  405. selected={selectedChatId === chat.id}
  406. on:select={() => {
  407. selectedChatId = chat.id;
  408. }}
  409. on:unselect={() => {
  410. selectedChatId = null;
  411. }}
  412. on:delete={(e) => {
  413. if ((e?.detail ?? '') === 'shift') {
  414. deleteChatHandler(chat.id);
  415. } else {
  416. deleteChat = chat;
  417. showDeleteConfirm = true;
  418. }
  419. }}
  420. />
  421. {/each}
  422. </div>
  423. </div>
  424. {/if}
  425. <div class="pl-2 my-2 flex-1 flex flex-col space-y-1 overflow-y-auto scrollbar-hidden">
  426. {#each filteredChatList as chat, idx}
  427. {#if idx === 0 || (idx > 0 && chat.time_range !== filteredChatList[idx - 1].time_range)}
  428. <div
  429. class="w-full pl-2.5 text-xs text-gray-500 dark:text-gray-500 font-medium {idx === 0
  430. ? ''
  431. : 'pt-5'} pb-0.5"
  432. >
  433. {$i18n.t(chat.time_range)}
  434. <!-- localisation keys for time_range to be recognized from the i18next parser (so they don't get automatically removed):
  435. {$i18n.t('Today')}
  436. {$i18n.t('Yesterday')}
  437. {$i18n.t('Previous 7 days')}
  438. {$i18n.t('Previous 30 days')}
  439. {$i18n.t('January')}
  440. {$i18n.t('February')}
  441. {$i18n.t('March')}
  442. {$i18n.t('April')}
  443. {$i18n.t('May')}
  444. {$i18n.t('June')}
  445. {$i18n.t('July')}
  446. {$i18n.t('August')}
  447. {$i18n.t('September')}
  448. {$i18n.t('October')}
  449. {$i18n.t('November')}
  450. {$i18n.t('December')}
  451. -->
  452. </div>
  453. {/if}
  454. <ChatItem
  455. {chat}
  456. {shiftKey}
  457. selected={selectedChatId === chat.id}
  458. on:select={() => {
  459. selectedChatId = chat.id;
  460. }}
  461. on:unselect={() => {
  462. selectedChatId = null;
  463. }}
  464. on:delete={(e) => {
  465. if ((e?.detail ?? '') === 'shift') {
  466. deleteChatHandler(chat.id);
  467. } else {
  468. deleteChat = chat;
  469. showDeleteConfirm = true;
  470. }
  471. }}
  472. />
  473. {/each}
  474. {#if $scrollPaginationEnabled && !allChatsLoaded}
  475. <Loader
  476. on:visible={(e) => {
  477. if (!chatListLoading) {
  478. loadMoreChats();
  479. }
  480. }}
  481. >
  482. <div class="w-full flex justify-center py-1 text-xs animate-pulse items-center gap-2">
  483. <Spinner className=" size-4" />
  484. <div class=" ">Loading...</div>
  485. </div>
  486. </Loader>
  487. {/if}
  488. </div>
  489. </div>
  490. <div class="px-2.5 pb-safe-bottom">
  491. <!-- <hr class=" border-gray-900 mb-1 w-full" /> -->
  492. <div class="flex flex-col font-primary">
  493. {#if $user !== undefined}
  494. <UserMenu
  495. role={$user.role}
  496. on:show={(e) => {
  497. if (e.detail === 'archived-chat') {
  498. showArchivedChats.set(true);
  499. }
  500. }}
  501. >
  502. <button
  503. class=" flex rounded-xl py-3 px-3.5 w-full hover:bg-gray-100 dark:hover:bg-gray-900 transition"
  504. on:click={() => {
  505. showDropdown = !showDropdown;
  506. }}
  507. >
  508. <div class=" self-center mr-3">
  509. <img
  510. src={$user.profile_image_url}
  511. class=" max-w-[30px] object-cover rounded-full"
  512. alt="User profile"
  513. />
  514. </div>
  515. <div class=" self-center font-medium">{$user.name}</div>
  516. </button>
  517. </UserMenu>
  518. {/if}
  519. </div>
  520. </div>
  521. </div>
  522. </div>
  523. <style>
  524. .scrollbar-hidden:active::-webkit-scrollbar-thumb,
  525. .scrollbar-hidden:focus::-webkit-scrollbar-thumb,
  526. .scrollbar-hidden:hover::-webkit-scrollbar-thumb {
  527. visibility: visible;
  528. }
  529. .scrollbar-hidden::-webkit-scrollbar-thumb {
  530. visibility: hidden;
  531. }
  532. </style>