ChatMenu.svelte 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. <script lang="ts">
  2. import { DropdownMenu } from 'bits-ui';
  3. import { flyAndScale } from '$lib/utils/transitions';
  4. import { getContext, createEventDispatcher, tick } from 'svelte';
  5. import fileSaver from 'file-saver';
  6. const { saveAs } = fileSaver;
  7. const dispatch = createEventDispatcher();
  8. import Dropdown from '$lib/components/common/Dropdown.svelte';
  9. import GarbageBin from '$lib/components/icons/GarbageBin.svelte';
  10. import Pencil from '$lib/components/icons/Pencil.svelte';
  11. import Tooltip from '$lib/components/common/Tooltip.svelte';
  12. import Tags from '$lib/components/chat/Tags.svelte';
  13. import Share from '$lib/components/icons/Share.svelte';
  14. import ArchiveBox from '$lib/components/icons/ArchiveBox.svelte';
  15. import DocumentDuplicate from '$lib/components/icons/DocumentDuplicate.svelte';
  16. import Bookmark from '$lib/components/icons/Bookmark.svelte';
  17. import BookmarkSlash from '$lib/components/icons/BookmarkSlash.svelte';
  18. import {
  19. getChatById,
  20. getChatPinnedStatusById,
  21. toggleChatPinnedStatusById
  22. } from '$lib/apis/chats';
  23. import { chats, folders, settings, theme, user } from '$lib/stores';
  24. import { createMessagesList } from '$lib/utils';
  25. import { downloadChatAsPDF } from '$lib/apis/utils';
  26. import Download from '$lib/components/icons/Download.svelte';
  27. import Folder from '$lib/components/icons/Folder.svelte';
  28. import Messages from '$lib/components/chat/Messages.svelte';
  29. const i18n = getContext('i18n');
  30. export let shareHandler: Function;
  31. export let moveChatHandler: Function;
  32. export let cloneChatHandler: Function;
  33. export let archiveChatHandler: Function;
  34. export let renameHandler: Function;
  35. export let deleteHandler: Function;
  36. export let onClose: Function;
  37. export let chatId = '';
  38. let show = false;
  39. let pinned = false;
  40. let chat = null;
  41. let showFullMessages = false;
  42. const pinHandler = async () => {
  43. await toggleChatPinnedStatusById(localStorage.token, chatId);
  44. dispatch('change');
  45. };
  46. const checkPinned = async () => {
  47. pinned = await getChatPinnedStatusById(localStorage.token, chatId);
  48. };
  49. const getChatAsText = async (chat) => {
  50. const history = chat.chat.history;
  51. const messages = createMessagesList(history, history.currentId);
  52. const chatText = messages.reduce((a, message, i, arr) => {
  53. return `${a}### ${message.role.toUpperCase()}\n${message.content}\n\n`;
  54. }, '');
  55. return chatText.trim();
  56. };
  57. const downloadTxt = async () => {
  58. const chat = await getChatById(localStorage.token, chatId);
  59. if (!chat) {
  60. return;
  61. }
  62. const chatText = await getChatAsText(chat);
  63. let blob = new Blob([chatText], {
  64. type: 'text/plain'
  65. });
  66. saveAs(blob, `chat-${chat.chat.title}.txt`);
  67. };
  68. const downloadPdf = async () => {
  69. chat = await getChatById(localStorage.token, chatId);
  70. if (!chat) {
  71. return;
  72. }
  73. const [{ default: jsPDF }, { default: html2canvas }] = await Promise.all([
  74. import('jspdf'),
  75. import('html2canvas-pro')
  76. ]);
  77. if ($settings?.stylizedPdfExport ?? true) {
  78. showFullMessages = true;
  79. await tick();
  80. const containerElement = document.getElementById('full-messages-container');
  81. if (containerElement) {
  82. try {
  83. const isDarkMode = document.documentElement.classList.contains('dark');
  84. const virtualWidth = 800; // px, fixed width for cloned element
  85. // Clone and style
  86. const clonedElement = containerElement.cloneNode(true);
  87. clonedElement.classList.add('text-black');
  88. clonedElement.classList.add('dark:text-white');
  89. clonedElement.style.width = `${virtualWidth}px`;
  90. clonedElement.style.position = 'absolute';
  91. clonedElement.style.left = '-9999px';
  92. clonedElement.style.height = 'auto';
  93. document.body.appendChild(clonedElement);
  94. // Wait for DOM update/layout
  95. await new Promise((r) => setTimeout(r, 100));
  96. // Render entire content once
  97. const canvas = await html2canvas(clonedElement, {
  98. backgroundColor: isDarkMode ? '#000' : '#fff',
  99. useCORS: true,
  100. scale: 2, // increase resolution
  101. width: virtualWidth
  102. });
  103. document.body.removeChild(clonedElement);
  104. const pdf = new jsPDF('p', 'mm', 'a4');
  105. const pageWidthMM = 210;
  106. const pageHeightMM = 297;
  107. // Convert page height in mm to px on canvas scale for cropping
  108. // Get canvas DPI scale:
  109. const pxPerMM = canvas.width / virtualWidth; // width in px / width in px?
  110. // Since 1 page width is 210 mm, but canvas width is 800 px at scale 2
  111. // Assume 1 mm = px / (pageWidthMM scaled)
  112. // Actually better: Calculate scale factor from px/mm:
  113. // virtualWidth px corresponds directly to 210mm in PDF, so pxPerMM:
  114. const pxPerPDFMM = canvas.width / pageWidthMM; // canvas px per PDF mm
  115. // Height in px for one page slice:
  116. const pagePixelHeight = Math.floor(pxPerPDFMM * pageHeightMM);
  117. let offsetY = 0;
  118. let page = 0;
  119. while (offsetY < canvas.height) {
  120. // Height of slice
  121. const sliceHeight = Math.min(pagePixelHeight, canvas.height - offsetY);
  122. // Create temp canvas for slice
  123. const pageCanvas = document.createElement('canvas');
  124. pageCanvas.width = canvas.width;
  125. pageCanvas.height = sliceHeight;
  126. const ctx = pageCanvas.getContext('2d');
  127. // Draw the slice of original canvas onto pageCanvas
  128. ctx.drawImage(
  129. canvas,
  130. 0,
  131. offsetY,
  132. canvas.width,
  133. sliceHeight,
  134. 0,
  135. 0,
  136. canvas.width,
  137. sliceHeight
  138. );
  139. const imgData = pageCanvas.toDataURL('image/jpeg', 0.7);
  140. // Calculate image height in PDF units keeping aspect ratio
  141. const imgHeightMM = (sliceHeight * pageWidthMM) / canvas.width;
  142. if (page > 0) pdf.addPage();
  143. if (isDarkMode) {
  144. pdf.setFillColor(0, 0, 0);
  145. pdf.rect(0, 0, pageWidthMM, pageHeightMM, 'F'); // black bg
  146. }
  147. pdf.addImage(imgData, 'JPEG', 0, 0, pageWidthMM, imgHeightMM);
  148. offsetY += sliceHeight;
  149. page++;
  150. }
  151. pdf.save(`chat-${chat.chat.title}.pdf`);
  152. showFullMessages = false;
  153. } catch (error) {
  154. console.error('Error generating PDF', error);
  155. }
  156. }
  157. } else {
  158. console.log('Downloading PDF');
  159. const chatText = await getChatAsText(chat);
  160. const doc = new jsPDF();
  161. // Margins
  162. const left = 15;
  163. const top = 20;
  164. const right = 15;
  165. const bottom = 20;
  166. const pageWidth = doc.internal.pageSize.getWidth();
  167. const pageHeight = doc.internal.pageSize.getHeight();
  168. const usableWidth = pageWidth - left - right;
  169. const usableHeight = pageHeight - top - bottom;
  170. // Font size and line height
  171. const fontSize = 8;
  172. doc.setFontSize(fontSize);
  173. const lineHeight = fontSize * 1; // adjust if needed
  174. // Split the markdown into lines (handles \n)
  175. const paragraphs = chatText.split('\n');
  176. let y = top;
  177. for (let paragraph of paragraphs) {
  178. // Wrap each paragraph to fit the width
  179. const lines = doc.splitTextToSize(paragraph, usableWidth);
  180. for (let line of lines) {
  181. // If the line would overflow the bottom, add a new page
  182. if (y + lineHeight > pageHeight - bottom) {
  183. doc.addPage();
  184. y = top;
  185. }
  186. doc.text(line, left, y);
  187. y += lineHeight * 0.5;
  188. }
  189. // Add empty line at paragraph breaks
  190. y += lineHeight * 0.1;
  191. }
  192. doc.save(`chat-${chat.chat.title}.pdf`);
  193. }
  194. };
  195. const downloadJSONExport = async () => {
  196. const chat = await getChatById(localStorage.token, chatId);
  197. if (chat) {
  198. let blob = new Blob([JSON.stringify([chat])], {
  199. type: 'application/json'
  200. });
  201. saveAs(blob, `chat-export-${Date.now()}.json`);
  202. }
  203. };
  204. $: if (show) {
  205. checkPinned();
  206. }
  207. </script>
  208. {#if chat && showFullMessages}
  209. <div class="hidden w-full h-full flex-col">
  210. <div id="full-messages-container">
  211. <Messages
  212. className="h-full flex pt-4 pb-8 w-full"
  213. chatId={`chat-preview-${chat?.id ?? ''}`}
  214. user={$user}
  215. readOnly={true}
  216. history={chat.chat.history}
  217. messages={chat.chat.messages}
  218. autoScroll={true}
  219. sendMessage={() => {}}
  220. continueResponse={() => {}}
  221. regenerateResponse={() => {}}
  222. messagesCount={null}
  223. editCodeBlock={false}
  224. />
  225. </div>
  226. </div>
  227. {/if}
  228. <Dropdown
  229. bind:show
  230. on:change={(e) => {
  231. if (e.detail === false) {
  232. onClose();
  233. }
  234. }}
  235. >
  236. <Tooltip content={$i18n.t('More')}>
  237. <slot />
  238. </Tooltip>
  239. <div slot="content">
  240. <DropdownMenu.Content
  241. class="w-full max-w-[200px] rounded-2xl px-1 py-1 border border-gray-100 dark:border-gray-800 z-50 bg-white dark:bg-gray-850 dark:text-white shadow-lg transition"
  242. sideOffset={-2}
  243. side="bottom"
  244. align="start"
  245. transition={flyAndScale}
  246. >
  247. {#if $user?.role === 'admin' || ($user.permissions?.chat?.share ?? true)}
  248. <DropdownMenu.Item
  249. class="flex gap-2 items-center px-3 py-1.5 text-sm cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800 rounded-xl"
  250. on:click={() => {
  251. shareHandler();
  252. }}
  253. >
  254. <Share strokeWidth="1.5" />
  255. <div class="flex items-center">{$i18n.t('Share')}</div>
  256. </DropdownMenu.Item>
  257. {/if}
  258. <DropdownMenu.Sub>
  259. <DropdownMenu.SubTrigger
  260. class="flex gap-2 items-center px-3 py-1.5 text-sm cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800 rounded-xl"
  261. >
  262. <Download strokeWidth="1.5" />
  263. <div class="flex items-center">{$i18n.t('Download')}</div>
  264. </DropdownMenu.SubTrigger>
  265. <DropdownMenu.SubContent
  266. class="w-full rounded-2xl p-1 z-50 bg-white dark:bg-gray-850 dark:text-white shadow-lg border border-gray-100 dark:border-gray-800"
  267. transition={flyAndScale}
  268. sideOffset={8}
  269. >
  270. {#if $user?.role === 'admin' || ($user.permissions?.chat?.export ?? true)}
  271. <DropdownMenu.Item
  272. class="flex gap-2 items-center px-3 py-1.5 text-sm cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800 rounded-xl"
  273. on:click={() => {
  274. downloadJSONExport();
  275. }}
  276. >
  277. <div class="flex items-center line-clamp-1">{$i18n.t('Export chat (.json)')}</div>
  278. </DropdownMenu.Item>
  279. {/if}
  280. <DropdownMenu.Item
  281. class="flex gap-2 items-center px-3 py-1.5 text-sm cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800 rounded-xl"
  282. on:click={() => {
  283. downloadTxt();
  284. }}
  285. >
  286. <div class="flex items-center line-clamp-1">{$i18n.t('Plain text (.txt)')}</div>
  287. </DropdownMenu.Item>
  288. <DropdownMenu.Item
  289. class="flex gap-2 items-center px-3 py-1.5 text-sm cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800 rounded-xl select-none w-full"
  290. on:click={() => {
  291. downloadPdf();
  292. }}
  293. >
  294. <div class="flex items-center line-clamp-1">{$i18n.t('PDF document (.pdf)')}</div>
  295. </DropdownMenu.Item>
  296. </DropdownMenu.SubContent>
  297. </DropdownMenu.Sub>
  298. <DropdownMenu.Item
  299. class="flex gap-2 items-center px-3 py-1.5 text-sm cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800 rounded-xl"
  300. on:click={() => {
  301. renameHandler();
  302. }}
  303. >
  304. <Pencil strokeWidth="1.5" />
  305. <div class="flex items-center">{$i18n.t('Rename')}</div>
  306. </DropdownMenu.Item>
  307. <hr class="border-gray-50 dark:border-gray-800 my-1" />
  308. <DropdownMenu.Item
  309. class="flex gap-2 items-center px-3 py-1.5 text-sm cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800 rounded-xl"
  310. on:click={() => {
  311. pinHandler();
  312. }}
  313. >
  314. {#if pinned}
  315. <BookmarkSlash strokeWidth="1.5" />
  316. <div class="flex items-center">{$i18n.t('Unpin')}</div>
  317. {:else}
  318. <Bookmark strokeWidth="1.5" />
  319. <div class="flex items-center">{$i18n.t('Pin')}</div>
  320. {/if}
  321. </DropdownMenu.Item>
  322. <DropdownMenu.Item
  323. class="flex gap-2 items-center px-3 py-1.5 text-sm cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800 rounded-xl"
  324. on:click={() => {
  325. cloneChatHandler();
  326. }}
  327. >
  328. <DocumentDuplicate strokeWidth="1.5" />
  329. <div class="flex items-center">{$i18n.t('Clone')}</div>
  330. </DropdownMenu.Item>
  331. {#if chatId}
  332. <DropdownMenu.Sub>
  333. <DropdownMenu.SubTrigger
  334. class="flex gap-2 items-center px-3 py-1.5 text-sm cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800 rounded-xl select-none w-full"
  335. >
  336. <Folder />
  337. <div class="flex items-center">{$i18n.t('Move')}</div>
  338. </DropdownMenu.SubTrigger>
  339. <DropdownMenu.SubContent
  340. class="w-full rounded-2xl p-1 z-50 bg-white dark:bg-gray-850 dark:text-white border border-gray-100 dark:border-gray-800 shadow-lg max-h-52 overflow-y-auto scrollbar-hidden"
  341. transition={flyAndScale}
  342. sideOffset={8}
  343. >
  344. {#each $folders.sort((a, b) => b.updated_at - a.updated_at) as folder}
  345. <DropdownMenu.Item
  346. class="flex gap-2 items-center px-3 py-1.5 text-sm cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800 rounded-xl"
  347. on:click={() => {
  348. moveChatHandler(chatId, folder.id);
  349. }}
  350. >
  351. <Folder />
  352. <div class="flex items-center">{folder?.name ?? 'Folder'}</div>
  353. </DropdownMenu.Item>
  354. {/each}
  355. </DropdownMenu.SubContent>
  356. </DropdownMenu.Sub>
  357. {/if}
  358. <DropdownMenu.Item
  359. class="flex gap-2 items-center px-3 py-1.5 text-sm cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800 rounded-xl"
  360. on:click={() => {
  361. archiveChatHandler();
  362. }}
  363. >
  364. <ArchiveBox strokeWidth="1.5" />
  365. <div class="flex items-center">{$i18n.t('Archive')}</div>
  366. </DropdownMenu.Item>
  367. <DropdownMenu.Item
  368. class="flex gap-2 items-center px-3 py-1.5 text-sm cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800 rounded-xl"
  369. on:click={() => {
  370. deleteHandler();
  371. }}
  372. >
  373. <GarbageBin strokeWidth="1.5" />
  374. <div class="flex items-center">{$i18n.t('Delete')}</div>
  375. </DropdownMenu.Item>
  376. </DropdownMenu.Content>
  377. </div>
  378. </Dropdown>