Sidebar.svelte 26 KB

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