Sidebar.svelte 18 KB

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