Sidebar.svelte 23 KB

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