NoteEditor.svelte 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091
  1. <script lang="ts">
  2. import { getContext, onDestroy, onMount, tick } from 'svelte';
  3. import { v4 as uuidv4 } from 'uuid';
  4. import heic2any from 'heic2any';
  5. import fileSaver from 'file-saver';
  6. const { saveAs } = fileSaver;
  7. import jsPDF from 'jspdf';
  8. import html2canvas from 'html2canvas-pro';
  9. const i18n = getContext('i18n');
  10. import { marked } from 'marked';
  11. import { toast } from 'svelte-sonner';
  12. import { goto } from '$app/navigation';
  13. import dayjs from '$lib/dayjs';
  14. import calendar from 'dayjs/plugin/calendar';
  15. import duration from 'dayjs/plugin/duration';
  16. import relativeTime from 'dayjs/plugin/relativeTime';
  17. dayjs.extend(calendar);
  18. dayjs.extend(duration);
  19. dayjs.extend(relativeTime);
  20. import { PaneGroup, Pane, PaneResizer } from 'paneforge';
  21. import { compressImage, copyToClipboard, splitStream } from '$lib/utils';
  22. import { WEBUI_API_BASE_URL, WEBUI_BASE_URL } from '$lib/constants';
  23. import { uploadFile } from '$lib/apis/files';
  24. import { chatCompletion } from '$lib/apis/openai';
  25. import { config, models, settings, showSidebar } from '$lib/stores';
  26. import NotePanel from '$lib/components/notes/NotePanel.svelte';
  27. import MenuLines from '../icons/MenuLines.svelte';
  28. import ChatBubbleOval from '../icons/ChatBubbleOval.svelte';
  29. import Settings from './NoteEditor/Settings.svelte';
  30. import Chat from './NoteEditor/Chat.svelte';
  31. async function loadLocale(locales) {
  32. for (const locale of locales) {
  33. try {
  34. dayjs.locale(locale);
  35. break; // Stop after successfully loading the first available locale
  36. } catch (error) {
  37. console.error(`Could not load locale '${locale}':`, error);
  38. }
  39. }
  40. }
  41. // Assuming $i18n.languages is an array of language codes
  42. $: loadLocale($i18n.languages);
  43. import { deleteNoteById, getNoteById, updateNoteById } from '$lib/apis/notes';
  44. import RichTextInput from '../common/RichTextInput.svelte';
  45. import Spinner from '../common/Spinner.svelte';
  46. import MicSolid from '../icons/MicSolid.svelte';
  47. import VoiceRecording from '../chat/MessageInput/VoiceRecording.svelte';
  48. import DeleteConfirmDialog from '$lib/components/common/ConfirmDialog.svelte';
  49. import Calendar from '../icons/Calendar.svelte';
  50. import Users from '../icons/Users.svelte';
  51. import Image from '../common/Image.svelte';
  52. import FileItem from '../common/FileItem.svelte';
  53. import FilesOverlay from '../chat/MessageInput/FilesOverlay.svelte';
  54. import RecordMenu from './RecordMenu.svelte';
  55. import NoteMenu from './Notes/NoteMenu.svelte';
  56. import EllipsisHorizontal from '../icons/EllipsisHorizontal.svelte';
  57. import Sparkles from '../icons/Sparkles.svelte';
  58. import SparklesSolid from '../icons/SparklesSolid.svelte';
  59. import Tooltip from '../common/Tooltip.svelte';
  60. import Bars3BottomLeft from '../icons/Bars3BottomLeft.svelte';
  61. import ArrowUturnLeft from '../icons/ArrowUturnLeft.svelte';
  62. import ArrowUturnRight from '../icons/ArrowUturnRight.svelte';
  63. import Sidebar from '../common/Sidebar.svelte';
  64. import ArrowRight from '../icons/ArrowRight.svelte';
  65. import Cog6 from '../icons/Cog6.svelte';
  66. export let id: null | string = null;
  67. let note = null;
  68. const newNote = {
  69. title: '',
  70. data: {
  71. content: {
  72. json: null,
  73. html: '',
  74. md: ''
  75. },
  76. versions: [],
  77. files: null
  78. },
  79. // pages: [], // TODO: Implement pages for notes to allow users to create multiple pages in a note
  80. meta: null,
  81. access_control: {}
  82. };
  83. let files = [];
  84. let messages = [];
  85. let versionIdx = null;
  86. let selectedModelId = null;
  87. let recording = false;
  88. let displayMediaRecord = false;
  89. let showPanel = false;
  90. let selectedPanel = 'chat';
  91. let showDeleteConfirm = false;
  92. let dragged = false;
  93. let loading = false;
  94. let enhancing = false;
  95. let streaming = false;
  96. let stopResponseFlag = false;
  97. let inputElement = null;
  98. const init = async () => {
  99. loading = true;
  100. const res = await getNoteById(localStorage.token, id).catch((error) => {
  101. toast.error(`${error}`);
  102. return null;
  103. });
  104. messages = [];
  105. if (res) {
  106. note = res;
  107. files = res.data.files || [];
  108. } else {
  109. goto('/');
  110. return;
  111. }
  112. loading = false;
  113. };
  114. let debounceTimeout: NodeJS.Timeout | null = null;
  115. const changeDebounceHandler = () => {
  116. if (debounceTimeout) {
  117. clearTimeout(debounceTimeout);
  118. }
  119. debounceTimeout = setTimeout(async () => {
  120. if (!note || enhancing || versionIdx !== null) {
  121. return;
  122. }
  123. console.log('Saving note:', note);
  124. const res = await updateNoteById(localStorage.token, id, {
  125. ...note,
  126. title: note.title === '' ? $i18n.t('Untitled') : note.title
  127. }).catch((e) => {
  128. toast.error(`${e}`);
  129. });
  130. }, 200);
  131. };
  132. $: if (note) {
  133. changeDebounceHandler();
  134. }
  135. $: if (id) {
  136. init();
  137. }
  138. function areContentsEqual(a, b) {
  139. return JSON.stringify(a) === JSON.stringify(b);
  140. }
  141. function insertNoteVersion(note) {
  142. const current = {
  143. json: note.data.content.json,
  144. html: note.data.content.html,
  145. md: note.data.content.md
  146. };
  147. const lastVersion = note.data.versions?.at(-1);
  148. if (!lastVersion || !areContentsEqual(lastVersion, current)) {
  149. note.data.versions = (note.data.versions ?? []).concat(current);
  150. return true;
  151. }
  152. return false;
  153. }
  154. async function enhanceNoteHandler() {
  155. if (selectedModelId === '') {
  156. toast.error($i18n.t('Please select a model.'));
  157. return;
  158. }
  159. const model = $models
  160. .filter((model) => model.id === selectedModelId && !(model?.info?.meta?.hidden ?? false))
  161. .find((model) => model.id === selectedModelId);
  162. if (!model) {
  163. selectedModelId = '';
  164. return;
  165. }
  166. enhancing = true;
  167. insertNoteVersion(note);
  168. await enhanceCompletionHandler(model);
  169. enhancing = false;
  170. versionIdx = null;
  171. }
  172. const stopResponseHandler = async () => {
  173. stopResponseFlag = true;
  174. console.log('stopResponse', stopResponseFlag);
  175. };
  176. function setContentByVersion(versionIdx) {
  177. if (!note.data.versions?.length) return;
  178. let idx = versionIdx;
  179. if (idx === null) idx = note.data.versions.length - 1; // latest
  180. const v = note.data.versions[idx];
  181. note.data.content.json = v.json;
  182. note.data.content.html = v.html;
  183. note.data.content.md = v.md;
  184. if (versionIdx === null) {
  185. const lastVersion = note.data.versions.at(-1);
  186. const currentContent = note.data.content;
  187. if (areContentsEqual(lastVersion, currentContent)) {
  188. // remove the last version
  189. note.data.versions = note.data.versions.slice(0, -1);
  190. }
  191. }
  192. }
  193. // Navigation
  194. function versionNavigateHandler(direction) {
  195. if (!note.data.versions || note.data.versions.length === 0) return;
  196. if (versionIdx === null) {
  197. // Get latest snapshots
  198. const lastVersion = note.data.versions.at(-1);
  199. const currentContent = note.data.content;
  200. if (!areContentsEqual(lastVersion, currentContent)) {
  201. // If the current content is different from the last version, insert a new version
  202. insertNoteVersion(note);
  203. versionIdx = note.data.versions.length - 1;
  204. } else {
  205. versionIdx = note.data.versions.length;
  206. }
  207. }
  208. if (direction === 'prev') {
  209. if (versionIdx > 0) versionIdx -= 1;
  210. } else if (direction === 'next') {
  211. if (versionIdx < note.data.versions.length - 1) versionIdx += 1;
  212. else versionIdx = null; // Reset to latest
  213. if (versionIdx === note.data.versions.length - 1) {
  214. // If we reach the latest version, reset to null
  215. versionIdx = null;
  216. }
  217. }
  218. setContentByVersion(versionIdx);
  219. }
  220. const uploadFileHandler = async (file) => {
  221. const tempItemId = uuidv4();
  222. const fileItem = {
  223. type: 'file',
  224. file: '',
  225. id: null,
  226. url: '',
  227. name: file.name,
  228. collection_name: '',
  229. status: 'uploading',
  230. size: file.size,
  231. error: '',
  232. itemId: tempItemId
  233. };
  234. if (fileItem.size == 0) {
  235. toast.error($i18n.t('You cannot upload an empty file.'));
  236. return null;
  237. }
  238. files = [...files, fileItem];
  239. try {
  240. // If the file is an audio file, provide the language for STT.
  241. let metadata = null;
  242. if (
  243. (file.type.startsWith('audio/') || file.type.startsWith('video/')) &&
  244. $settings?.audio?.stt?.language
  245. ) {
  246. metadata = {
  247. language: $settings?.audio?.stt?.language
  248. };
  249. }
  250. // During the file upload, file content is automatically extracted.
  251. const uploadedFile = await uploadFile(localStorage.token, file, metadata);
  252. if (uploadedFile) {
  253. console.log('File upload completed:', {
  254. id: uploadedFile.id,
  255. name: fileItem.name,
  256. collection: uploadedFile?.meta?.collection_name
  257. });
  258. if (uploadedFile.error) {
  259. console.warn('File upload warning:', uploadedFile.error);
  260. toast.warning(uploadedFile.error);
  261. }
  262. fileItem.status = 'uploaded';
  263. fileItem.file = uploadedFile;
  264. fileItem.id = uploadedFile.id;
  265. fileItem.collection_name =
  266. uploadedFile?.meta?.collection_name || uploadedFile?.collection_name;
  267. fileItem.url = `${WEBUI_API_BASE_URL}/files/${uploadedFile.id}`;
  268. files = files;
  269. } else {
  270. files = files.filter((item) => item?.itemId !== tempItemId);
  271. }
  272. } catch (e) {
  273. toast.error(`${e}`);
  274. files = files.filter((item) => item?.itemId !== tempItemId);
  275. }
  276. if (files.length > 0) {
  277. note.data.files = files;
  278. } else {
  279. note.data.files = null;
  280. }
  281. };
  282. const inputFilesHandler = async (inputFiles) => {
  283. console.log('Input files handler called with:', inputFiles);
  284. inputFiles.forEach(async (file) => {
  285. console.log('Processing file:', {
  286. name: file.name,
  287. type: file.type,
  288. size: file.size,
  289. extension: file.name.split('.').at(-1)
  290. });
  291. if (
  292. ($config?.file?.max_size ?? null) !== null &&
  293. file.size > ($config?.file?.max_size ?? 0) * 1024 * 1024
  294. ) {
  295. console.log('File exceeds max size limit:', {
  296. fileSize: file.size,
  297. maxSize: ($config?.file?.max_size ?? 0) * 1024 * 1024
  298. });
  299. toast.error(
  300. $i18n.t(`File size should not exceed {{maxSize}} MB.`, {
  301. maxSize: $config?.file?.max_size
  302. })
  303. );
  304. return;
  305. }
  306. if (file['type'].startsWith('image/')) {
  307. const compressImageHandler = async (imageUrl, settings = {}, config = {}) => {
  308. // Quick shortcut so we don’t do unnecessary work.
  309. const settingsCompression = settings?.imageCompression ?? false;
  310. const configWidth = config?.file?.image_compression?.width ?? null;
  311. const configHeight = config?.file?.image_compression?.height ?? null;
  312. // If neither settings nor config wants compression, return original URL.
  313. if (!settingsCompression && !configWidth && !configHeight) {
  314. return imageUrl;
  315. }
  316. // Default to null (no compression unless set)
  317. let width = null;
  318. let height = null;
  319. // If user/settings want compression, pick their preferred size.
  320. if (settingsCompression) {
  321. width = settings?.imageCompressionSize?.width ?? null;
  322. height = settings?.imageCompressionSize?.height ?? null;
  323. }
  324. // Apply config limits as an upper bound if any
  325. if (configWidth && (width === null || width > configWidth)) {
  326. width = configWidth;
  327. }
  328. if (configHeight && (height === null || height > configHeight)) {
  329. height = configHeight;
  330. }
  331. // Do the compression if required
  332. if (width || height) {
  333. return await compressImage(imageUrl, width, height);
  334. }
  335. return imageUrl;
  336. };
  337. let reader = new FileReader();
  338. reader.onload = async (event) => {
  339. let imageUrl = event.target.result;
  340. imageUrl = await compressImageHandler(imageUrl, $settings, $config);
  341. files = [
  342. ...files,
  343. {
  344. type: 'image',
  345. url: `${imageUrl}`
  346. }
  347. ];
  348. note.data.files = files;
  349. };
  350. reader.readAsDataURL(
  351. file['type'] === 'image/heic'
  352. ? await heic2any({ blob: file, toType: 'image/jpeg' })
  353. : file
  354. );
  355. } else {
  356. uploadFileHandler(file);
  357. }
  358. });
  359. };
  360. const downloadHandler = async (type) => {
  361. console.log('downloadHandler', type);
  362. if (type === 'txt') {
  363. const blob = new Blob([note.data.content.md], { type: 'text/plain' });
  364. saveAs(blob, `${note.title}.txt`);
  365. } else if (type === 'md') {
  366. const blob = new Blob([note.data.content.md], { type: 'text/markdown' });
  367. saveAs(blob, `${note.title}.md`);
  368. } else if (type === 'pdf') {
  369. await downloadPdf(note);
  370. }
  371. };
  372. const downloadPdf = async (note) => {
  373. try {
  374. // Define a fixed virtual screen size
  375. const virtualWidth = 1024; // Fixed width (adjust as needed)
  376. const virtualHeight = 1400; // Fixed height (adjust as needed)
  377. // STEP 1. Get a DOM node to render
  378. const html = note.data?.content?.html ?? '';
  379. let node;
  380. if (html instanceof HTMLElement) {
  381. node = html;
  382. } else {
  383. // If it's HTML string, render to a temporary hidden element
  384. node = document.createElement('div');
  385. node.innerHTML = html;
  386. document.body.appendChild(node);
  387. }
  388. // Render to canvas with predefined width
  389. const canvas = await html2canvas(node, {
  390. useCORS: true,
  391. scale: 2, // Keep at 1x to avoid unexpected enlargements
  392. width: virtualWidth, // Set fixed virtual screen width
  393. windowWidth: virtualWidth, // Ensure consistent rendering
  394. windowHeight: virtualHeight
  395. });
  396. // Remove hidden node if needed
  397. if (!(html instanceof HTMLElement)) {
  398. document.body.removeChild(node);
  399. }
  400. const imgData = canvas.toDataURL('image/png');
  401. // A4 page settings
  402. const pdf = new jsPDF('p', 'mm', 'a4');
  403. const imgWidth = 210; // A4 width in mm
  404. const pageHeight = 297; // A4 height in mm
  405. // Maintain aspect ratio
  406. const imgHeight = (canvas.height * imgWidth) / canvas.width;
  407. let heightLeft = imgHeight;
  408. let position = 0;
  409. pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
  410. heightLeft -= pageHeight;
  411. // Handle additional pages
  412. while (heightLeft > 0) {
  413. position -= pageHeight;
  414. pdf.addPage();
  415. pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
  416. heightLeft -= pageHeight;
  417. }
  418. pdf.save(`${note.title}.pdf`);
  419. } catch (error) {
  420. console.error('Error generating PDF', error);
  421. toast.error(`${error}`);
  422. }
  423. };
  424. const deleteNoteHandler = async (id) => {
  425. const res = await deleteNoteById(localStorage.token, id).catch((error) => {
  426. toast.error(`${error}`);
  427. return null;
  428. });
  429. if (res) {
  430. toast.success($i18n.t('Note deleted successfully'));
  431. goto('/notes');
  432. } else {
  433. toast.error($i18n.t('Failed to delete note'));
  434. }
  435. };
  436. const scrollToBottom = () => {
  437. const element = document.getElementById('note-content-container');
  438. if (element) {
  439. element.scrollTop = element?.scrollHeight;
  440. }
  441. };
  442. const enhanceCompletionHandler = async (model) => {
  443. let enhancedContent = {
  444. json: null,
  445. html: '',
  446. md: ''
  447. };
  448. const systemPrompt = `Enhance existing notes using additional context provided from audio transcription or uploaded file content. Your task is to make the notes more useful and comprehensive by incorporating relevant information from the provided context.
  449. Input will be provided within <notes> and <context> XML tags, providing a structure for the existing notes and context respectively.
  450. # Output Format
  451. Provide the enhanced notes in markdown format. Use markdown syntax for headings, lists, and emphasis to improve clarity and presentation. Ensure that all integrated content from the context is accurately reflected. Return only the markdown formatted note.
  452. `;
  453. const [res, controller] = await chatCompletion(
  454. localStorage.token,
  455. {
  456. model: model.id,
  457. stream: true,
  458. messages: [
  459. {
  460. role: 'system',
  461. content: systemPrompt
  462. },
  463. {
  464. role: 'user',
  465. content:
  466. `<notes>${note.data.content.md}</notes>` +
  467. (files && files.length > 0
  468. ? `\n<context>${files.map((file) => `${file.name}: ${file?.file?.data?.content ?? 'Could not extract content'}\n`).join('')}</context>`
  469. : '')
  470. }
  471. ]
  472. },
  473. `${WEBUI_BASE_URL}/api`
  474. );
  475. await tick();
  476. streaming = true;
  477. if (res && res.ok) {
  478. const reader = res.body
  479. .pipeThrough(new TextDecoderStream())
  480. .pipeThrough(splitStream('\n'))
  481. .getReader();
  482. while (true) {
  483. const { value, done } = await reader.read();
  484. if (done || stopResponseFlag) {
  485. if (stopResponseFlag) {
  486. controller.abort('User: Stop Response');
  487. }
  488. enhancing = false;
  489. streaming = false;
  490. break;
  491. }
  492. try {
  493. let lines = value.split('\n');
  494. for (const line of lines) {
  495. if (line !== '') {
  496. console.log(line);
  497. if (line === 'data: [DONE]') {
  498. console.log(line);
  499. } else {
  500. let data = JSON.parse(line.replace(/^data: /, ''));
  501. console.log(data);
  502. if (data.choices && data.choices.length > 0) {
  503. const choice = data.choices[0];
  504. if (choice.delta && choice.delta.content) {
  505. enhancedContent.md += choice.delta.content;
  506. enhancedContent.html = marked.parse(enhancedContent.md);
  507. note.data.content.md = enhancedContent.md;
  508. note.data.content.html = enhancedContent.html;
  509. note.data.content.json = null;
  510. scrollToBottom();
  511. }
  512. }
  513. }
  514. }
  515. }
  516. } catch (error) {
  517. console.log(error);
  518. }
  519. }
  520. }
  521. streaming = false;
  522. };
  523. const onDragOver = (e) => {
  524. e.preventDefault();
  525. // Check if a file is being dragged.
  526. if (e.dataTransfer?.types?.includes('Files')) {
  527. dragged = true;
  528. } else {
  529. dragged = false;
  530. }
  531. };
  532. const onDragLeave = () => {
  533. dragged = false;
  534. };
  535. const onDrop = async (e) => {
  536. e.preventDefault();
  537. console.log(e);
  538. if (e.dataTransfer?.files) {
  539. const inputFiles = Array.from(e.dataTransfer?.files);
  540. if (inputFiles && inputFiles.length > 0) {
  541. console.log(inputFiles);
  542. inputFilesHandler(inputFiles);
  543. }
  544. }
  545. dragged = false;
  546. };
  547. const insertHandler = (content) => {
  548. insertNoteVersion(note);
  549. inputElement?.insertContent(content);
  550. };
  551. onMount(async () => {
  552. await tick();
  553. if ($settings?.models) {
  554. selectedModelId = $settings?.models[0];
  555. } else if ($config?.default_models) {
  556. selectedModelId = $config?.default_models.split(',')[0];
  557. } else {
  558. selectedModelId = '';
  559. }
  560. if (selectedModelId) {
  561. const model = $models
  562. .filter((model) => model.id === selectedModelId && !(model?.info?.meta?.hidden ?? false))
  563. .find((model) => model.id === selectedModelId);
  564. if (!model) {
  565. selectedModelId = '';
  566. }
  567. }
  568. const dropzoneElement = document.getElementById('note-editor');
  569. dropzoneElement?.addEventListener('dragover', onDragOver);
  570. dropzoneElement?.addEventListener('drop', onDrop);
  571. dropzoneElement?.addEventListener('dragleave', onDragLeave);
  572. });
  573. onDestroy(() => {
  574. console.log('destroy');
  575. const dropzoneElement = document.getElementById('note-editor');
  576. if (dropzoneElement) {
  577. dropzoneElement?.removeEventListener('dragover', onDragOver);
  578. dropzoneElement?.removeEventListener('drop', onDrop);
  579. dropzoneElement?.removeEventListener('dragleave', onDragLeave);
  580. }
  581. });
  582. </script>
  583. <FilesOverlay show={dragged} />
  584. <DeleteConfirmDialog
  585. bind:show={showDeleteConfirm}
  586. title={$i18n.t('Delete note?')}
  587. on:confirm={() => {
  588. deleteNoteHandler(note.id);
  589. showDeleteConfirm = false;
  590. }}
  591. >
  592. <div class=" text-sm text-gray-500">
  593. {$i18n.t('This will delete')} <span class=" font-semibold">{note.title}</span>.
  594. </div>
  595. </DeleteConfirmDialog>
  596. <PaneGroup direction="horizontal" class="w-full h-full">
  597. <Pane defaultSize={70} minSize={30} class="h-full flex flex-col w-full relative">
  598. <div class="relative flex-1 w-full h-full flex justify-center pt-[11px]" id="note-editor">
  599. {#if loading}
  600. <div class=" absolute top-0 bottom-0 left-0 right-0 flex">
  601. <div class="m-auto">
  602. <Spinner className="size-5" />
  603. </div>
  604. </div>
  605. {:else}
  606. <div class=" w-full flex flex-col {loading ? 'opacity-20' : ''}">
  607. <div class="shrink-0 w-full flex justify-between items-center px-3.5 mb-1.5">
  608. <div class="w-full flex items-center">
  609. <div
  610. class="{$showSidebar
  611. ? 'md:hidden pl-0.5'
  612. : ''} flex flex-none items-center pr-1 -translate-x-1"
  613. >
  614. <button
  615. id="sidebar-toggle-button"
  616. class="cursor-pointer p-1.5 flex rounded-xl hover:bg-gray-100 dark:hover:bg-gray-850 transition"
  617. on:click={() => {
  618. showSidebar.set(!$showSidebar);
  619. }}
  620. aria-label="Toggle Sidebar"
  621. >
  622. <div class=" m-auto self-center">
  623. <MenuLines />
  624. </div>
  625. </button>
  626. </div>
  627. <input
  628. class="w-full text-xl font-medium bg-transparent outline-hidden"
  629. type="text"
  630. bind:value={note.title}
  631. placeholder={$i18n.t('Title')}
  632. required
  633. />
  634. <div class="flex items-center gap-0.5 translate-x-1">
  635. {#if note.data?.versions?.length > 0}
  636. <div>
  637. <div class="flex items-center gap-0.5 self-center min-w-fit" dir="ltr">
  638. <button
  639. class="self-center p-1 hover:enabled:bg-black/5 dark:hover:enabled:bg-white/5 dark:hover:enabled:text-white hover:enabled:text-black rounded-md transition disabled:cursor-not-allowed disabled:text-gray-500 disabled:hover:text-gray-500"
  640. on:click={() => {
  641. versionNavigateHandler('prev');
  642. }}
  643. disabled={(versionIdx === null && note.data.versions.length === 0) ||
  644. versionIdx === 0}
  645. >
  646. <ArrowUturnLeft className="size-4" />
  647. </button>
  648. <button
  649. class="self-center p-1 hover:enabled:bg-black/5 dark:hover:enabled:bg-white/5 dark:hover:enabled:text-white hover:enabled:text-black rounded-md transition disabled:cursor-not-allowed disabled:text-gray-500 disabled:hover:text-gray-500"
  650. on:click={() => {
  651. versionNavigateHandler('next');
  652. }}
  653. disabled={versionIdx >= note.data.versions.length || versionIdx === null}
  654. >
  655. <ArrowUturnRight className="size-4" />
  656. </button>
  657. </div>
  658. </div>
  659. {/if}
  660. <NoteMenu
  661. onDownload={(type) => {
  662. downloadHandler(type);
  663. }}
  664. onCopyToClipboard={async () => {
  665. const res = await copyToClipboard(note.data.content.md).catch((error) => {
  666. toast.error(`${error}`);
  667. return null;
  668. });
  669. if (res) {
  670. toast.success($i18n.t('Copied to clipboard'));
  671. }
  672. }}
  673. onDelete={() => {
  674. showDeleteConfirm = true;
  675. }}
  676. >
  677. <div class="p-1 bg-transparent hover:bg-white/5 transition rounded-lg">
  678. <EllipsisHorizontal className="size-5" />
  679. </div>
  680. </NoteMenu>
  681. <Tooltip placement="top" content={$i18n.t('Chat')} className="cursor-pointer">
  682. <button
  683. class="p-1.5 bg-transparent hover:bg-white/5 transition rounded-lg"
  684. on:click={() => {
  685. if (showPanel && selectedPanel === 'chat') {
  686. showPanel = false;
  687. } else {
  688. if (!showPanel) {
  689. showPanel = true;
  690. }
  691. selectedPanel = 'chat';
  692. }
  693. }}
  694. >
  695. <ChatBubbleOval />
  696. </button>
  697. </Tooltip>
  698. <Tooltip placement="top" content={$i18n.t('Settings')} className="cursor-pointer">
  699. <button
  700. class="p-1.5 bg-transparent hover:bg-white/5 transition rounded-lg"
  701. on:click={() => {
  702. if (showPanel && selectedPanel === 'settings') {
  703. showPanel = false;
  704. } else {
  705. if (!showPanel) {
  706. showPanel = true;
  707. }
  708. selectedPanel = 'settings';
  709. }
  710. }}
  711. >
  712. <Cog6 />
  713. </button>
  714. </Tooltip>
  715. </div>
  716. </div>
  717. </div>
  718. <div class=" mb-2.5 px-2.5">
  719. <div
  720. class="flex gap-1 items-center text-xs font-medium text-gray-500 dark:text-gray-500"
  721. >
  722. <button class=" flex items-center gap-1 w-fit py-1 px-1.5 rounded-lg">
  723. <Calendar className="size-3.5" strokeWidth="2" />
  724. <span>{dayjs(note.created_at / 1000000).calendar()}</span>
  725. </button>
  726. <button class=" flex items-center gap-1 w-fit py-1 px-1.5 rounded-lg">
  727. <Users className="size-3.5" strokeWidth="2" />
  728. <span> You </span>
  729. </button>
  730. </div>
  731. </div>
  732. <div
  733. class=" flex-1 w-full h-full overflow-auto px-3.5 pb-20 relative"
  734. id="note-content-container"
  735. >
  736. {#if enhancing}
  737. <div
  738. class="w-full h-full fixed top-0 left-0 {streaming
  739. ? ''
  740. : ' backdrop-blur-xs bg-white/10 dark:bg-gray-900/10'} flex items-center justify-center z-10 cursor-not-allowed"
  741. ></div>
  742. {/if}
  743. {#if files && files.length > 0}
  744. <div class="mb-2.5 w-full flex gap-1 flex-wrap z-40">
  745. {#each files as file, fileIdx}
  746. <div class="w-fit">
  747. {#if file.type === 'image'}
  748. <Image
  749. src={file.url}
  750. imageClassName=" max-h-96 rounded-lg"
  751. dismissible={true}
  752. onDismiss={() => {
  753. files = files.filter((item, idx) => idx !== fileIdx);
  754. note.data.files = files.length > 0 ? files : null;
  755. }}
  756. />
  757. {:else}
  758. <FileItem
  759. item={file}
  760. dismissible={true}
  761. url={file.url}
  762. name={file.name}
  763. type={file.type}
  764. size={file?.size}
  765. loading={file.status === 'uploading'}
  766. on:dismiss={() => {
  767. files = files.filter((item) => item?.id !== file.id);
  768. note.data.files = files.length > 0 ? files : null;
  769. }}
  770. />
  771. {/if}
  772. </div>
  773. {/each}
  774. </div>
  775. {/if}
  776. <RichTextInput
  777. bind:this={inputElement}
  778. className="input-prose-sm px-0.5"
  779. bind:value={note.data.content.json}
  780. html={note.data?.content?.html}
  781. json={true}
  782. placeholder={$i18n.t('Write something...')}
  783. editable={versionIdx === null && !enhancing}
  784. onChange={(content) => {
  785. note.data.content.html = content.html;
  786. note.data.content.md = content.md;
  787. }}
  788. />
  789. </div>
  790. </div>
  791. {/if}
  792. </div>
  793. <div class="absolute z-20 bottom-0 right-0 p-3.5 max-w-full w-full flex justify-end">
  794. <div class="flex gap-1 justify-between w-full max-w-full">
  795. {#if recording}
  796. <div class="flex-1 w-full">
  797. <VoiceRecording
  798. bind:recording
  799. className="p-1 w-full max-w-full"
  800. transcribe={false}
  801. displayMedia={displayMediaRecord}
  802. onCancel={() => {
  803. recording = false;
  804. displayMediaRecord = false;
  805. }}
  806. onConfirm={(data) => {
  807. if (data?.file) {
  808. uploadFileHandler(data?.file);
  809. }
  810. recording = false;
  811. displayMediaRecord = false;
  812. }}
  813. />
  814. </div>
  815. {:else}
  816. <RecordMenu
  817. onRecord={async () => {
  818. displayMediaRecord = false;
  819. try {
  820. let stream = await navigator.mediaDevices
  821. .getUserMedia({ audio: true })
  822. .catch(function (err) {
  823. toast.error(
  824. $i18n.t(`Permission denied when accessing microphone: {{error}}`, {
  825. error: err
  826. })
  827. );
  828. return null;
  829. });
  830. if (stream) {
  831. recording = true;
  832. const tracks = stream.getTracks();
  833. tracks.forEach((track) => track.stop());
  834. }
  835. stream = null;
  836. } catch {
  837. toast.error($i18n.t('Permission denied when accessing microphone'));
  838. }
  839. }}
  840. onCaptureAudio={async () => {
  841. displayMediaRecord = true;
  842. recording = true;
  843. }}
  844. onUpload={async () => {
  845. const input = document.createElement('input');
  846. input.type = 'file';
  847. input.accept = 'audio/*';
  848. input.multiple = false;
  849. input.click();
  850. input.onchange = async (e) => {
  851. const files = e.target.files;
  852. if (files && files.length > 0) {
  853. await uploadFileHandler(files[0]);
  854. }
  855. };
  856. }}
  857. >
  858. <Tooltip content={$i18n.t('Record')} placement="top">
  859. <button
  860. class="cursor-pointer p-2.5 flex rounded-full border border-gray-50 bg-white dark:border-none dark:bg-gray-850 hover:bg-gray-50 dark:hover:bg-gray-800 transition shadow-xl"
  861. type="button"
  862. >
  863. <MicSolid className="size-4.5" />
  864. </button>
  865. </Tooltip>
  866. </RecordMenu>
  867. <div
  868. class="cursor-pointer flex gap-0.5 rounded-full border border-gray-50 dark:border-gray-850 dark:bg-gray-850 transition shadow-xl"
  869. >
  870. <!-- <Tooltip content={$i18n.t('My Notes')} placement="top">
  871. <button
  872. class="p-2 size-8.5 flex justify-center items-center {selectedVersion === 'note'
  873. ? 'bg-gray-100 dark:bg-gray-800 '
  874. : ' hover:bg-gray-50 dark:hover:bg-gray-800'} rounded-full transition shrink-0"
  875. type="button"
  876. on:click={() => {
  877. selectedVersion = 'note';
  878. versionToggleHandler();
  879. }}
  880. >
  881. <Bars3BottomLeft />
  882. </button>
  883. </Tooltip> -->
  884. <Tooltip content={$i18n.t('Enhance')} placement="top">
  885. {#if enhancing}
  886. <button
  887. class="p-2 flex justify-center items-center hover:bg-gray-50 dark:hover:bg-gray-800 rounded-full transition shrink-0"
  888. on:click={() => {
  889. stopResponseHandler();
  890. }}
  891. type="button"
  892. >
  893. <Spinner className="size-5" />
  894. </button>
  895. {:else}
  896. <button
  897. class="p-2.5 flex justify-center items-center hover:bg-gray-50 dark:hover:bg-gray-800 rounded-full transition shrink-0"
  898. on:click={() => {
  899. enhanceNoteHandler();
  900. }}
  901. disabled={enhancing}
  902. type="button"
  903. >
  904. <SparklesSolid />
  905. </button>
  906. {/if}
  907. </Tooltip>
  908. </div>
  909. {/if}
  910. </div>
  911. </div>
  912. </Pane>
  913. <NotePanel bind:show={showPanel}>
  914. {#if selectedPanel === 'chat'}
  915. <Chat
  916. bind:show={showPanel}
  917. bind:selectedModelId
  918. bind:messages
  919. bind:note
  920. bind:enhancing
  921. bind:streaming
  922. bind:stopResponseFlag
  923. {files}
  924. onInsert={insertHandler}
  925. onStop={stopResponseHandler}
  926. insertNoteHandler={() => {
  927. insertNoteVersion(note);
  928. }}
  929. scrollToBottomHandler={scrollToBottom}
  930. />
  931. {:else if selectedPanel === 'settings'}
  932. <Settings bind:show={showPanel} bind:selectedModelId />
  933. {/if}
  934. </NotePanel>
  935. </PaneGroup>