Sidebar.svelte 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  1. <script lang="ts">
  2. import { toast } from 'svelte-sonner';
  3. import { v4 as uuidv4 } from 'uuid';
  4. import { goto } from '$app/navigation';
  5. import {
  6. user,
  7. chats,
  8. settings,
  9. showSettings,
  10. chatId,
  11. tags,
  12. showSidebar,
  13. mobile,
  14. showArchivedChats,
  15. pinnedChats,
  16. scrollPaginationEnabled,
  17. currentChatPage,
  18. temporaryChatEnabled,
  19. channels,
  20. socket,
  21. config,
  22. isApp
  23. } from '$lib/stores';
  24. import { onMount, getContext, tick, onDestroy } from 'svelte';
  25. const i18n = getContext('i18n');
  26. import {
  27. deleteChatById,
  28. getChatList,
  29. getAllTags,
  30. getChatListBySearchText,
  31. createNewChat,
  32. getPinnedChatList,
  33. toggleChatPinnedStatusById,
  34. getChatPinnedStatusById,
  35. getChatById,
  36. updateChatFolderIdById,
  37. importChat
  38. } from '$lib/apis/chats';
  39. import { createNewFolder, getFolders, updateFolderParentIdById } from '$lib/apis/folders';
  40. import { WEBUI_BASE_URL } from '$lib/constants';
  41. import ArchivedChatsModal from './Sidebar/ArchivedChatsModal.svelte';
  42. import UserMenu from './Sidebar/UserMenu.svelte';
  43. import ChatItem from './Sidebar/ChatItem.svelte';
  44. import Spinner from '../common/Spinner.svelte';
  45. import Loader from '../common/Loader.svelte';
  46. import AddFilesPlaceholder from '../AddFilesPlaceholder.svelte';
  47. import SearchInput from './Sidebar/SearchInput.svelte';
  48. import Folder from '../common/Folder.svelte';
  49. import Plus from '../icons/Plus.svelte';
  50. import Tooltip from '../common/Tooltip.svelte';
  51. import Folders from './Sidebar/Folders.svelte';
  52. import { getChannels, createNewChannel } from '$lib/apis/channels';
  53. import ChannelModal from './Sidebar/ChannelModal.svelte';
  54. import ChannelItem from './Sidebar/ChannelItem.svelte';
  55. import PencilSquare from '../icons/PencilSquare.svelte';
  56. import Home from '../icons/Home.svelte';
  57. const BREAKPOINT = 768;
  58. let navElement;
  59. let search = '';
  60. let shiftKey = false;
  61. let selectedChatId = null;
  62. let showDropdown = false;
  63. let showPinnedChat = true;
  64. let showCreateChannel = false;
  65. // Pagination variables
  66. let chatListLoading = false;
  67. let allChatsLoaded = false;
  68. let folders = {};
  69. let newFolderId = null;
  70. const initFolders = async () => {
  71. const folderList = await getFolders(localStorage.token).catch((error) => {
  72. toast.error(`${error}`);
  73. return [];
  74. });
  75. folders = {};
  76. // First pass: Initialize all folder entries
  77. for (const folder of folderList) {
  78. // Ensure folder is added to folders with its data
  79. folders[folder.id] = { ...(folders[folder.id] || {}), ...folder };
  80. if (newFolderId && folder.id === newFolderId) {
  81. folders[folder.id].new = true;
  82. newFolderId = null;
  83. }
  84. }
  85. // Second pass: Tie child folders to their parents
  86. for (const folder of folderList) {
  87. if (folder.parent_id) {
  88. // Ensure the parent folder is initialized if it doesn't exist
  89. if (!folders[folder.parent_id]) {
  90. folders[folder.parent_id] = {}; // Create a placeholder if not already present
  91. }
  92. // Initialize childrenIds array if it doesn't exist and add the current folder id
  93. folders[folder.parent_id].childrenIds = folders[folder.parent_id].childrenIds
  94. ? [...folders[folder.parent_id].childrenIds, folder.id]
  95. : [folder.id];
  96. // Sort the children by updated_at field
  97. folders[folder.parent_id].childrenIds.sort((a, b) => {
  98. return folders[b].updated_at - folders[a].updated_at;
  99. });
  100. }
  101. }
  102. };
  103. const createFolder = async (name = 'Untitled') => {
  104. if (name === '') {
  105. toast.error($i18n.t('Folder name cannot be empty.'));
  106. return;
  107. }
  108. const rootFolders = Object.values(folders).filter((folder) => folder.parent_id === null);
  109. if (rootFolders.find((folder) => folder.name.toLowerCase() === name.toLowerCase())) {
  110. // If a folder with the same name already exists, append a number to the name
  111. let i = 1;
  112. while (
  113. rootFolders.find((folder) => folder.name.toLowerCase() === `${name} ${i}`.toLowerCase())
  114. ) {
  115. i++;
  116. }
  117. name = `${name} ${i}`;
  118. }
  119. // Add a dummy folder to the list to show the user that the folder is being created
  120. const tempId = uuidv4();
  121. folders = {
  122. ...folders,
  123. tempId: {
  124. id: tempId,
  125. name: name,
  126. created_at: Date.now(),
  127. updated_at: Date.now()
  128. }
  129. };
  130. const res = await createNewFolder(localStorage.token, name).catch((error) => {
  131. toast.error(`${error}`);
  132. return null;
  133. });
  134. if (res) {
  135. newFolderId = res.id;
  136. await initFolders();
  137. }
  138. };
  139. const initChannels = async () => {
  140. await channels.set(await getChannels(localStorage.token));
  141. };
  142. const initChatList = async () => {
  143. // Reset pagination variables
  144. tags.set(await getAllTags(localStorage.token));
  145. pinnedChats.set(await getPinnedChatList(localStorage.token));
  146. initFolders();
  147. currentChatPage.set(1);
  148. allChatsLoaded = false;
  149. if (search) {
  150. await chats.set(await getChatListBySearchText(localStorage.token, search, $currentChatPage));
  151. } else {
  152. await chats.set(await getChatList(localStorage.token, $currentChatPage));
  153. }
  154. // Enable pagination
  155. scrollPaginationEnabled.set(true);
  156. };
  157. const loadMoreChats = async () => {
  158. chatListLoading = true;
  159. currentChatPage.set($currentChatPage + 1);
  160. let newChatList = [];
  161. if (search) {
  162. newChatList = await getChatListBySearchText(localStorage.token, search, $currentChatPage);
  163. } else {
  164. newChatList = await getChatList(localStorage.token, $currentChatPage);
  165. }
  166. // once the bottom of the list has been reached (no results) there is no need to continue querying
  167. allChatsLoaded = newChatList.length === 0;
  168. await chats.set([...($chats ? $chats : []), ...newChatList]);
  169. chatListLoading = false;
  170. };
  171. let searchDebounceTimeout;
  172. const searchDebounceHandler = async () => {
  173. console.log('search', search);
  174. chats.set(null);
  175. if (searchDebounceTimeout) {
  176. clearTimeout(searchDebounceTimeout);
  177. }
  178. if (search === '') {
  179. await initChatList();
  180. return;
  181. } else {
  182. searchDebounceTimeout = setTimeout(async () => {
  183. allChatsLoaded = false;
  184. currentChatPage.set(1);
  185. await chats.set(await getChatListBySearchText(localStorage.token, search));
  186. if ($chats.length === 0) {
  187. tags.set(await getAllTags(localStorage.token));
  188. }
  189. }, 1000);
  190. }
  191. };
  192. const importChatHandler = async (items, pinned = false, folderId = null) => {
  193. console.log('importChatHandler', items, pinned, folderId);
  194. for (const item of items) {
  195. console.log(item);
  196. if (item.chat) {
  197. await importChat(localStorage.token, item.chat, item?.meta ?? {}, pinned, folderId);
  198. }
  199. }
  200. initChatList();
  201. };
  202. const inputFilesHandler = async (files) => {
  203. console.log(files);
  204. for (const file of files) {
  205. const reader = new FileReader();
  206. reader.onload = async (e) => {
  207. const content = e.target.result;
  208. try {
  209. const chatItems = JSON.parse(content);
  210. importChatHandler(chatItems);
  211. } catch {
  212. toast.error($i18n.t(`Invalid file format.`));
  213. }
  214. };
  215. reader.readAsText(file);
  216. }
  217. };
  218. const tagEventHandler = async (type, tagName, chatId) => {
  219. console.log(type, tagName, chatId);
  220. if (type === 'delete') {
  221. initChatList();
  222. } else if (type === 'add') {
  223. initChatList();
  224. }
  225. };
  226. let draggedOver = false;
  227. const onDragOver = (e) => {
  228. e.preventDefault();
  229. // Check if a file is being draggedOver.
  230. if (e.dataTransfer?.types?.includes('Files')) {
  231. draggedOver = true;
  232. } else {
  233. draggedOver = false;
  234. }
  235. };
  236. const onDragLeave = () => {
  237. draggedOver = false;
  238. };
  239. const onDrop = async (e) => {
  240. e.preventDefault();
  241. console.log(e); // Log the drop event
  242. // Perform file drop check and handle it accordingly
  243. if (e.dataTransfer?.files) {
  244. const inputFiles = Array.from(e.dataTransfer?.files);
  245. if (inputFiles && inputFiles.length > 0) {
  246. console.log(inputFiles); // Log the dropped files
  247. inputFilesHandler(inputFiles); // Handle the dropped files
  248. }
  249. }
  250. draggedOver = false; // Reset draggedOver status after drop
  251. };
  252. let touchstart;
  253. let touchend;
  254. function checkDirection() {
  255. const screenWidth = window.innerWidth;
  256. const swipeDistance = Math.abs(touchend.screenX - touchstart.screenX);
  257. if (touchstart.clientX < 40 && swipeDistance >= screenWidth / 8) {
  258. if (touchend.screenX < touchstart.screenX) {
  259. showSidebar.set(false);
  260. }
  261. if (touchend.screenX > touchstart.screenX) {
  262. showSidebar.set(true);
  263. }
  264. }
  265. }
  266. const onTouchStart = (e) => {
  267. touchstart = e.changedTouches[0];
  268. console.log(touchstart.clientX);
  269. };
  270. const onTouchEnd = (e) => {
  271. touchend = e.changedTouches[0];
  272. checkDirection();
  273. };
  274. const onKeyDown = (e) => {
  275. if (e.key === 'Shift') {
  276. shiftKey = true;
  277. }
  278. };
  279. const onKeyUp = (e) => {
  280. if (e.key === 'Shift') {
  281. shiftKey = false;
  282. }
  283. };
  284. const onFocus = () => {};
  285. const onBlur = () => {
  286. shiftKey = false;
  287. selectedChatId = null;
  288. };
  289. onMount(async () => {
  290. showPinnedChat = localStorage?.showPinnedChat ? localStorage.showPinnedChat === 'true' : true;
  291. mobile.subscribe((value) => {
  292. if ($showSidebar && value) {
  293. showSidebar.set(false);
  294. }
  295. if ($showSidebar && !value) {
  296. const navElement = document.getElementsByTagName('nav')[0];
  297. if (navElement) {
  298. navElement.style['-webkit-app-region'] = 'drag';
  299. }
  300. }
  301. if (!$showSidebar && !value) {
  302. showSidebar.set(true);
  303. }
  304. });
  305. showSidebar.set(!$mobile ? localStorage.sidebar === 'true' : false);
  306. showSidebar.subscribe((value) => {
  307. localStorage.sidebar = value;
  308. // nav element is not available on the first render
  309. const navElement = document.getElementsByTagName('nav')[0];
  310. if (navElement) {
  311. if ($mobile) {
  312. if (!value) {
  313. navElement.style['-webkit-app-region'] = 'drag';
  314. } else {
  315. navElement.style['-webkit-app-region'] = 'no-drag';
  316. }
  317. } else {
  318. navElement.style['-webkit-app-region'] = 'drag';
  319. }
  320. }
  321. });
  322. await initChannels();
  323. await initChatList();
  324. window.addEventListener('keydown', onKeyDown);
  325. window.addEventListener('keyup', onKeyUp);
  326. window.addEventListener('touchstart', onTouchStart);
  327. window.addEventListener('touchend', onTouchEnd);
  328. window.addEventListener('focus', onFocus);
  329. window.addEventListener('blur-sm', onBlur);
  330. const dropZone = document.getElementById('sidebar');
  331. dropZone?.addEventListener('dragover', onDragOver);
  332. dropZone?.addEventListener('drop', onDrop);
  333. dropZone?.addEventListener('dragleave', onDragLeave);
  334. });
  335. onDestroy(() => {
  336. window.removeEventListener('keydown', onKeyDown);
  337. window.removeEventListener('keyup', onKeyUp);
  338. window.removeEventListener('touchstart', onTouchStart);
  339. window.removeEventListener('touchend', onTouchEnd);
  340. window.removeEventListener('focus', onFocus);
  341. window.removeEventListener('blur-sm', onBlur);
  342. const dropZone = document.getElementById('sidebar');
  343. dropZone?.removeEventListener('dragover', onDragOver);
  344. dropZone?.removeEventListener('drop', onDrop);
  345. dropZone?.removeEventListener('dragleave', onDragLeave);
  346. });
  347. </script>
  348. <ArchivedChatsModal
  349. bind:show={$showArchivedChats}
  350. on:change={async () => {
  351. await initChatList();
  352. }}
  353. />
  354. <ChannelModal
  355. bind:show={showCreateChannel}
  356. onSubmit={async ({ name, access_control }) => {
  357. const res = await createNewChannel(localStorage.token, {
  358. name: name,
  359. access_control: access_control
  360. }).catch((error) => {
  361. toast.error(`${error}`);
  362. return null;
  363. });
  364. if (res) {
  365. $socket.emit('join-channels', { auth: { token: $user.token } });
  366. await initChannels();
  367. showCreateChannel = false;
  368. }
  369. }}
  370. />
  371. <!-- svelte-ignore a11y-no-static-element-interactions -->
  372. {#if $showSidebar}
  373. <div
  374. class=" {$isApp
  375. ? ' ml-[4.5rem] md:ml-0'
  376. : ''} 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"
  377. on:mousedown={() => {
  378. showSidebar.set(!$showSidebar);
  379. }}
  380. />
  381. {/if}
  382. <div
  383. bind:this={navElement}
  384. id="sidebar"
  385. class="h-screen max-h-[100dvh] min-h-screen select-none {$showSidebar
  386. ? 'md:relative w-[260px] max-w-[260px]'
  387. : '-translate-x-[260px] w-[0px]'} {$isApp
  388. ? `ml-[4.5rem] md:ml-0 `
  389. : 'transition-width duration-200 ease-in-out'} shrink-0 bg-gray-50 text-gray-900 dark:bg-gray-950 dark:text-gray-200 text-sm fixed z-50 top-0 left-0 overflow-x-hidden
  390. "
  391. data-state={$showSidebar}
  392. >
  393. <div
  394. class="py-2 my-auto flex flex-col justify-between h-screen max-h-[100dvh] w-[260px] overflow-x-hidden z-50 {$showSidebar
  395. ? ''
  396. : 'invisible'}"
  397. >
  398. <div class="px-1.5 flex justify-between space-x-1 text-gray-600 dark:text-gray-400">
  399. <button
  400. class=" cursor-pointer p-[7px] flex rounded-xl hover:bg-gray-100 dark:hover:bg-gray-900 transition"
  401. on:click={() => {
  402. showSidebar.set(!$showSidebar);
  403. }}
  404. >
  405. <div class=" m-auto self-center">
  406. <svg
  407. xmlns="http://www.w3.org/2000/svg"
  408. fill="none"
  409. viewBox="0 0 24 24"
  410. stroke-width="2"
  411. stroke="currentColor"
  412. class="size-5"
  413. >
  414. <path
  415. stroke-linecap="round"
  416. stroke-linejoin="round"
  417. d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25H12"
  418. />
  419. </svg>
  420. </div>
  421. </button>
  422. <a
  423. id="sidebar-new-chat-button"
  424. class="flex justify-between items-center flex-1 rounded-lg px-2 py-1 h-full text-right hover:bg-gray-100 dark:hover:bg-gray-900 transition no-drag-region"
  425. href="/"
  426. draggable="false"
  427. on:click={async () => {
  428. selectedChatId = null;
  429. await goto('/');
  430. const newChatButton = document.getElementById('new-chat-button');
  431. setTimeout(() => {
  432. newChatButton?.click();
  433. if ($mobile) {
  434. showSidebar.set(false);
  435. }
  436. }, 0);
  437. }}
  438. >
  439. <div class="flex items-center">
  440. <div class="self-center mx-1.5">
  441. <img
  442. crossorigin="anonymous"
  443. src="{WEBUI_BASE_URL}/static/favicon.png"
  444. class=" size-5 -translate-x-1.5 rounded-full"
  445. alt="logo"
  446. />
  447. </div>
  448. <div class=" self-center font-medium text-sm text-gray-850 dark:text-white font-primary">
  449. {$i18n.t('New Chat')}
  450. </div>
  451. </div>
  452. <div>
  453. <PencilSquare className=" size-5" strokeWidth="2" />
  454. </div>
  455. </a>
  456. </div>
  457. <!-- {#if $user?.role === 'admin'}
  458. <div class="px-1.5 flex justify-center text-gray-800 dark:text-gray-200">
  459. <a
  460. class="grow flex items-center space-x-3 rounded-lg px-2 py-[7px] hover:bg-gray-100 dark:hover:bg-gray-900 transition"
  461. href="/home"
  462. on:click={() => {
  463. selectedChatId = null;
  464. chatId.set('');
  465. if ($mobile) {
  466. showSidebar.set(false);
  467. }
  468. }}
  469. draggable="false"
  470. >
  471. <div class="self-center">
  472. <Home strokeWidth="2" className="size-[1.1rem]" />
  473. </div>
  474. <div class="flex self-center translate-y-[0.5px]">
  475. <div class=" self-center font-medium text-sm font-primary">{$i18n.t('Home')}</div>
  476. </div>
  477. </a>
  478. </div>
  479. {/if} -->
  480. {#if $user?.role === 'admin' || $user?.permissions?.workspace?.models || $user?.permissions?.workspace?.knowledge || $user?.permissions?.workspace?.prompts || $user?.permissions?.workspace?.tools}
  481. <div class="px-1.5 flex justify-center text-gray-800 dark:text-gray-200">
  482. <a
  483. class="grow flex items-center space-x-3 rounded-lg px-2 py-[7px] hover:bg-gray-100 dark:hover:bg-gray-900 transition"
  484. href="/workspace"
  485. on:click={() => {
  486. selectedChatId = null;
  487. chatId.set('');
  488. if ($mobile) {
  489. showSidebar.set(false);
  490. }
  491. }}
  492. draggable="false"
  493. >
  494. <div class="self-center">
  495. <svg
  496. xmlns="http://www.w3.org/2000/svg"
  497. fill="none"
  498. viewBox="0 0 24 24"
  499. stroke-width="2"
  500. stroke="currentColor"
  501. class="size-[1.1rem]"
  502. >
  503. <path
  504. stroke-linecap="round"
  505. stroke-linejoin="round"
  506. 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"
  507. />
  508. </svg>
  509. </div>
  510. <div class="flex self-center translate-y-[0.5px]">
  511. <div class=" self-center font-medium text-sm font-primary">{$i18n.t('Workspace')}</div>
  512. </div>
  513. </a>
  514. </div>
  515. {/if}
  516. <div class="relative {$temporaryChatEnabled ? 'opacity-20' : ''}">
  517. {#if $temporaryChatEnabled}
  518. <div class="absolute z-40 w-full h-full flex justify-center"></div>
  519. {/if}
  520. <SearchInput
  521. bind:value={search}
  522. on:input={searchDebounceHandler}
  523. placeholder={$i18n.t('Search')}
  524. showClearButton={true}
  525. />
  526. </div>
  527. <div
  528. class="relative flex flex-col flex-1 overflow-y-auto overflow-x-hidden {$temporaryChatEnabled
  529. ? 'opacity-20'
  530. : ''}"
  531. >
  532. {#if $config?.features?.enable_channels && ($user.role === 'admin' || $channels.length > 0) && !search}
  533. <Folder
  534. className="px-2 mt-0.5"
  535. name={$i18n.t('Channels')}
  536. dragAndDrop={false}
  537. onAdd={async () => {
  538. if ($user.role === 'admin') {
  539. await tick();
  540. setTimeout(() => {
  541. showCreateChannel = true;
  542. }, 0);
  543. }
  544. }}
  545. onAddLabel={$i18n.t('Create Channel')}
  546. >
  547. {#each $channels as channel}
  548. <ChannelItem
  549. {channel}
  550. onUpdate={async () => {
  551. await initChannels();
  552. }}
  553. />
  554. {/each}
  555. </Folder>
  556. {/if}
  557. <Folder
  558. collapsible={!search}
  559. className="px-2 mt-0.5"
  560. name={$i18n.t('Chats')}
  561. onAdd={() => {
  562. createFolder();
  563. }}
  564. onAddLabel={$i18n.t('New Folder')}
  565. on:import={(e) => {
  566. importChatHandler(e.detail);
  567. }}
  568. on:drop={async (e) => {
  569. const { type, id, item } = e.detail;
  570. if (type === 'chat') {
  571. let chat = await getChatById(localStorage.token, id).catch((error) => {
  572. return null;
  573. });
  574. if (!chat && item) {
  575. chat = await importChat(localStorage.token, item.chat, item?.meta ?? {});
  576. }
  577. if (chat) {
  578. console.log(chat);
  579. if (chat.folder_id) {
  580. const res = await updateChatFolderIdById(localStorage.token, chat.id, null).catch(
  581. (error) => {
  582. toast.error(`${error}`);
  583. return null;
  584. }
  585. );
  586. }
  587. if (chat.pinned) {
  588. const res = await toggleChatPinnedStatusById(localStorage.token, chat.id);
  589. }
  590. initChatList();
  591. }
  592. } else if (type === 'folder') {
  593. if (folders[id].parent_id === null) {
  594. return;
  595. }
  596. const res = await updateFolderParentIdById(localStorage.token, id, null).catch(
  597. (error) => {
  598. toast.error(`${error}`);
  599. return null;
  600. }
  601. );
  602. if (res) {
  603. await initFolders();
  604. }
  605. }
  606. }}
  607. >
  608. {#if $temporaryChatEnabled}
  609. <div class="absolute z-40 w-full h-full flex justify-center"></div>
  610. {/if}
  611. {#if !search && $pinnedChats.length > 0}
  612. <div class="flex flex-col space-y-1 rounded-xl">
  613. <Folder
  614. className=""
  615. bind:open={showPinnedChat}
  616. on:change={(e) => {
  617. localStorage.setItem('showPinnedChat', e.detail);
  618. console.log(e.detail);
  619. }}
  620. on:import={(e) => {
  621. importChatHandler(e.detail, true);
  622. }}
  623. on:drop={async (e) => {
  624. const { type, id, item } = e.detail;
  625. if (type === 'chat') {
  626. let chat = await getChatById(localStorage.token, id).catch((error) => {
  627. return null;
  628. });
  629. if (!chat && item) {
  630. chat = await importChat(localStorage.token, item.chat, item?.meta ?? {});
  631. }
  632. if (chat) {
  633. console.log(chat);
  634. if (chat.folder_id) {
  635. const res = await updateChatFolderIdById(
  636. localStorage.token,
  637. chat.id,
  638. null
  639. ).catch((error) => {
  640. toast.error(`${error}`);
  641. return null;
  642. });
  643. }
  644. if (!chat.pinned) {
  645. const res = await toggleChatPinnedStatusById(localStorage.token, chat.id);
  646. }
  647. initChatList();
  648. }
  649. }
  650. }}
  651. name={$i18n.t('Pinned')}
  652. >
  653. <div
  654. class="ml-3 pl-1 mt-[1px] flex flex-col overflow-y-auto scrollbar-hidden border-s border-gray-100 dark:border-gray-900"
  655. >
  656. {#each $pinnedChats as chat, idx}
  657. <ChatItem
  658. className=""
  659. id={chat.id}
  660. title={chat.title}
  661. {shiftKey}
  662. selected={selectedChatId === chat.id}
  663. on:select={() => {
  664. selectedChatId = chat.id;
  665. }}
  666. on:unselect={() => {
  667. selectedChatId = null;
  668. }}
  669. on:change={async () => {
  670. initChatList();
  671. }}
  672. on:tag={(e) => {
  673. const { type, name } = e.detail;
  674. tagEventHandler(type, name, chat.id);
  675. }}
  676. />
  677. {/each}
  678. </div>
  679. </Folder>
  680. </div>
  681. {/if}
  682. {#if !search && folders}
  683. <Folders
  684. {folders}
  685. on:import={(e) => {
  686. const { folderId, items } = e.detail;
  687. importChatHandler(items, false, folderId);
  688. }}
  689. on:update={async (e) => {
  690. initChatList();
  691. }}
  692. on:change={async () => {
  693. initChatList();
  694. }}
  695. />
  696. {/if}
  697. <div class=" flex-1 flex flex-col overflow-y-auto scrollbar-hidden">
  698. <div class="pt-1.5">
  699. {#if $chats}
  700. {#each $chats as chat, idx}
  701. {#if idx === 0 || (idx > 0 && chat.time_range !== $chats[idx - 1].time_range)}
  702. <div
  703. class="w-full pl-2.5 text-xs text-gray-500 dark:text-gray-500 font-medium {idx ===
  704. 0
  705. ? ''
  706. : 'pt-5'} pb-1.5"
  707. >
  708. {$i18n.t(chat.time_range)}
  709. <!-- localisation keys for time_range to be recognized from the i18next parser (so they don't get automatically removed):
  710. {$i18n.t('Today')}
  711. {$i18n.t('Yesterday')}
  712. {$i18n.t('Previous 7 days')}
  713. {$i18n.t('Previous 30 days')}
  714. {$i18n.t('January')}
  715. {$i18n.t('February')}
  716. {$i18n.t('March')}
  717. {$i18n.t('April')}
  718. {$i18n.t('May')}
  719. {$i18n.t('June')}
  720. {$i18n.t('July')}
  721. {$i18n.t('August')}
  722. {$i18n.t('September')}
  723. {$i18n.t('October')}
  724. {$i18n.t('November')}
  725. {$i18n.t('December')}
  726. -->
  727. </div>
  728. {/if}
  729. <ChatItem
  730. className=""
  731. id={chat.id}
  732. title={chat.title}
  733. {shiftKey}
  734. selected={selectedChatId === chat.id}
  735. on:select={() => {
  736. selectedChatId = chat.id;
  737. }}
  738. on:unselect={() => {
  739. selectedChatId = null;
  740. }}
  741. on:change={async () => {
  742. initChatList();
  743. }}
  744. on:tag={(e) => {
  745. const { type, name } = e.detail;
  746. tagEventHandler(type, name, chat.id);
  747. }}
  748. />
  749. {/each}
  750. {#if $scrollPaginationEnabled && !allChatsLoaded}
  751. <Loader
  752. on:visible={(e) => {
  753. if (!chatListLoading) {
  754. loadMoreChats();
  755. }
  756. }}
  757. >
  758. <div
  759. class="w-full flex justify-center py-1 text-xs animate-pulse items-center gap-2"
  760. >
  761. <Spinner className=" size-4" />
  762. <div class=" ">Loading...</div>
  763. </div>
  764. </Loader>
  765. {/if}
  766. {:else}
  767. <div class="w-full flex justify-center py-1 text-xs animate-pulse items-center gap-2">
  768. <Spinner className=" size-4" />
  769. <div class=" ">Loading...</div>
  770. </div>
  771. {/if}
  772. </div>
  773. </div>
  774. </Folder>
  775. </div>
  776. <div class="px-2">
  777. <div class="flex flex-col font-primary">
  778. {#if $user !== undefined}
  779. <UserMenu
  780. role={$user.role}
  781. on:show={(e) => {
  782. if (e.detail === 'archived-chat') {
  783. showArchivedChats.set(true);
  784. }
  785. }}
  786. >
  787. <button
  788. class=" flex items-center rounded-xl py-2.5 px-2.5 w-full hover:bg-gray-100 dark:hover:bg-gray-900 transition"
  789. on:click={() => {
  790. showDropdown = !showDropdown;
  791. }}
  792. >
  793. <div class=" self-center mr-3">
  794. <img
  795. src={$user.profile_image_url}
  796. class=" max-w-[30px] object-cover rounded-full"
  797. alt="User profile"
  798. />
  799. </div>
  800. <div class=" self-center font-medium">{$user.name}</div>
  801. </button>
  802. </UserMenu>
  803. {/if}
  804. </div>
  805. </div>
  806. </div>
  807. </div>
  808. <style>
  809. .scrollbar-hidden:active::-webkit-scrollbar-thumb,
  810. .scrollbar-hidden:focus::-webkit-scrollbar-thumb,
  811. .scrollbar-hidden:hover::-webkit-scrollbar-thumb {
  812. visibility: visible;
  813. }
  814. .scrollbar-hidden::-webkit-scrollbar-thumb {
  815. visibility: hidden;
  816. }
  817. </style>