Sidebar.svelte 17 KB

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