NoteEditor.svelte 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  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 === 'md') {
  363. const blob = new Blob([note.data.content.md], { type: 'text/markdown' });
  364. saveAs(blob, `${note.title}.md`);
  365. } else if (type === 'pdf') {
  366. await downloadPdf(note);
  367. }
  368. };
  369. const downloadPdf = async (note) => {
  370. try {
  371. // Define a fixed virtual screen size
  372. const virtualWidth = 1024; // Fixed width (adjust as needed)
  373. const virtualHeight = 1400; // Fixed height (adjust as needed)
  374. // STEP 1. Get a DOM node to render
  375. const html = note.data?.content?.html ?? '';
  376. let node;
  377. if (html instanceof HTMLElement) {
  378. node = html;
  379. } else {
  380. // If it's HTML string, render to a temporary hidden element
  381. node = document.createElement('div');
  382. node.innerHTML = html;
  383. document.body.appendChild(node);
  384. }
  385. // Render to canvas with predefined width
  386. const canvas = await html2canvas(node, {
  387. useCORS: true,
  388. scale: 2, // Keep at 1x to avoid unexpected enlargements
  389. width: virtualWidth, // Set fixed virtual screen width
  390. windowWidth: virtualWidth, // Ensure consistent rendering
  391. windowHeight: virtualHeight
  392. });
  393. // Remove hidden node if needed
  394. if (!(html instanceof HTMLElement)) {
  395. document.body.removeChild(node);
  396. }
  397. const imgData = canvas.toDataURL('image/png');
  398. // A4 page settings
  399. const pdf = new jsPDF('p', 'mm', 'a4');
  400. const imgWidth = 210; // A4 width in mm
  401. const pageHeight = 297; // A4 height in mm
  402. // Maintain aspect ratio
  403. const imgHeight = (canvas.height * imgWidth) / canvas.width;
  404. let heightLeft = imgHeight;
  405. let position = 0;
  406. pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
  407. heightLeft -= pageHeight;
  408. // Handle additional pages
  409. while (heightLeft > 0) {
  410. position -= pageHeight;
  411. pdf.addPage();
  412. pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
  413. heightLeft -= pageHeight;
  414. }
  415. pdf.save(`${note.title}.pdf`);
  416. } catch (error) {
  417. console.error('Error generating PDF', error);
  418. toast.error(`${error}`);
  419. }
  420. };
  421. const deleteNoteHandler = async (id) => {
  422. const res = await deleteNoteById(localStorage.token, id).catch((error) => {
  423. toast.error(`${error}`);
  424. return null;
  425. });
  426. if (res) {
  427. toast.success($i18n.t('Note deleted successfully'));
  428. goto('/notes');
  429. } else {
  430. toast.error($i18n.t('Failed to delete note'));
  431. }
  432. };
  433. const scrollToBottom = () => {
  434. const element = document.getElementById('note-content-container');
  435. if (element) {
  436. element.scrollTop = element?.scrollHeight;
  437. }
  438. };
  439. const enhanceCompletionHandler = async (model) => {
  440. let enhancedContent = {
  441. json: null,
  442. html: '',
  443. md: ''
  444. };
  445. 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.
  446. Input will be provided within <notes> and <context> XML tags, providing a structure for the existing notes and context respectively.
  447. # Output Format
  448. 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.
  449. `;
  450. const [res, controller] = await chatCompletion(
  451. localStorage.token,
  452. {
  453. model: model.id,
  454. stream: true,
  455. messages: [
  456. {
  457. role: 'system',
  458. content: systemPrompt
  459. },
  460. {
  461. role: 'user',
  462. content:
  463. `<notes>${note.data.content.md}</notes>` +
  464. (files && files.length > 0
  465. ? `\n<context>${files.map((file) => `${file.name}: ${file?.file?.data?.content ?? 'Could not extract content'}\n`).join('')}</context>`
  466. : '')
  467. }
  468. ]
  469. },
  470. `${WEBUI_BASE_URL}/api`
  471. );
  472. await tick();
  473. streaming = true;
  474. if (res && res.ok) {
  475. const reader = res.body
  476. .pipeThrough(new TextDecoderStream())
  477. .pipeThrough(splitStream('\n'))
  478. .getReader();
  479. while (true) {
  480. const { value, done } = await reader.read();
  481. if (done || stopResponseFlag) {
  482. if (stopResponseFlag) {
  483. controller.abort('User: Stop Response');
  484. }
  485. enhancing = false;
  486. streaming = false;
  487. break;
  488. }
  489. try {
  490. let lines = value.split('\n');
  491. for (const line of lines) {
  492. if (line !== '') {
  493. console.log(line);
  494. if (line === 'data: [DONE]') {
  495. console.log(line);
  496. } else {
  497. let data = JSON.parse(line.replace(/^data: /, ''));
  498. console.log(data);
  499. if (data.choices && data.choices.length > 0) {
  500. const choice = data.choices[0];
  501. if (choice.delta && choice.delta.content) {
  502. enhancedContent.md += choice.delta.content;
  503. enhancedContent.html = marked.parse(enhancedContent.md);
  504. note.data.content.md = enhancedContent.md;
  505. note.data.content.html = enhancedContent.html;
  506. note.data.content.json = null;
  507. scrollToBottom();
  508. }
  509. }
  510. }
  511. }
  512. }
  513. } catch (error) {
  514. console.log(error);
  515. }
  516. }
  517. }
  518. streaming = false;
  519. };
  520. const onDragOver = (e) => {
  521. e.preventDefault();
  522. // Check if a file is being dragged.
  523. if (e.dataTransfer?.types?.includes('Files')) {
  524. dragged = true;
  525. } else {
  526. dragged = false;
  527. }
  528. };
  529. const onDragLeave = () => {
  530. dragged = false;
  531. };
  532. const onDrop = async (e) => {
  533. e.preventDefault();
  534. console.log(e);
  535. if (e.dataTransfer?.files) {
  536. const inputFiles = Array.from(e.dataTransfer?.files);
  537. if (inputFiles && inputFiles.length > 0) {
  538. console.log(inputFiles);
  539. inputFilesHandler(inputFiles);
  540. }
  541. }
  542. dragged = false;
  543. };
  544. const insertHandler = (content) => {
  545. inputElement?.insertContent(content);
  546. };
  547. onMount(async () => {
  548. await tick();
  549. if ($settings?.models) {
  550. selectedModelId = $settings?.models[0];
  551. } else if ($config?.default_models) {
  552. selectedModelId = $config?.default_models.split(',')[0];
  553. } else {
  554. selectedModelId = '';
  555. }
  556. if (selectedModelId) {
  557. const model = $models
  558. .filter((model) => model.id === selectedModelId && !(model?.info?.meta?.hidden ?? false))
  559. .find((model) => model.id === selectedModelId);
  560. if (!model) {
  561. selectedModelId = '';
  562. }
  563. }
  564. const dropzoneElement = document.getElementById('note-editor');
  565. dropzoneElement?.addEventListener('dragover', onDragOver);
  566. dropzoneElement?.addEventListener('drop', onDrop);
  567. dropzoneElement?.addEventListener('dragleave', onDragLeave);
  568. });
  569. onDestroy(() => {
  570. console.log('destroy');
  571. const dropzoneElement = document.getElementById('note-editor');
  572. if (dropzoneElement) {
  573. dropzoneElement?.removeEventListener('dragover', onDragOver);
  574. dropzoneElement?.removeEventListener('drop', onDrop);
  575. dropzoneElement?.removeEventListener('dragleave', onDragLeave);
  576. }
  577. });
  578. </script>
  579. <FilesOverlay show={dragged} />
  580. <DeleteConfirmDialog
  581. bind:show={showDeleteConfirm}
  582. title={$i18n.t('Delete note?')}
  583. on:confirm={() => {
  584. deleteNoteHandler(note.id);
  585. showDeleteConfirm = false;
  586. }}
  587. >
  588. <div class=" text-sm text-gray-500">
  589. {$i18n.t('This will delete')} <span class=" font-semibold">{note.title}</span>.
  590. </div>
  591. </DeleteConfirmDialog>
  592. <PaneGroup direction="horizontal" class="w-full h-full">
  593. <Pane defaultSize={70} minSize={50} class="h-full flex flex-col w-full relative">
  594. <div class="relative flex-1 w-full h-full flex justify-center pt-[11px]" id="note-editor">
  595. {#if loading}
  596. <div class=" absolute top-0 bottom-0 left-0 right-0 flex">
  597. <div class="m-auto">
  598. <Spinner className="size-5" />
  599. </div>
  600. </div>
  601. {:else}
  602. <div class=" w-full flex flex-col {loading ? 'opacity-20' : ''}">
  603. <div class="shrink-0 w-full flex justify-between items-center px-3.5 mb-1.5">
  604. <div class="w-full flex items-center">
  605. <div
  606. class="{$showSidebar
  607. ? 'md:hidden pl-0.5'
  608. : ''} flex flex-none items-center pr-1 -translate-x-1"
  609. >
  610. <button
  611. id="sidebar-toggle-button"
  612. class="cursor-pointer p-1.5 flex rounded-xl hover:bg-gray-100 dark:hover:bg-gray-850 transition"
  613. on:click={() => {
  614. showSidebar.set(!$showSidebar);
  615. }}
  616. aria-label="Toggle Sidebar"
  617. >
  618. <div class=" m-auto self-center">
  619. <MenuLines />
  620. </div>
  621. </button>
  622. </div>
  623. <input
  624. class="w-full text-xl font-medium bg-transparent outline-hidden"
  625. type="text"
  626. bind:value={note.title}
  627. placeholder={$i18n.t('Title')}
  628. required
  629. />
  630. <div class="flex items-center gap-0.5 translate-x-1">
  631. {#if note.data?.versions?.length > 0}
  632. <div>
  633. <div class="flex items-center gap-0.5 self-center min-w-fit" dir="ltr">
  634. <button
  635. 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"
  636. on:click={() => {
  637. versionNavigateHandler('prev');
  638. }}
  639. disabled={(versionIdx === null && note.data.versions.length === 0) ||
  640. versionIdx === 0}
  641. >
  642. <ArrowUturnLeft className="size-4" />
  643. </button>
  644. <button
  645. 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"
  646. on:click={() => {
  647. versionNavigateHandler('next');
  648. }}
  649. disabled={versionIdx >= note.data.versions.length || versionIdx === null}
  650. >
  651. <ArrowUturnRight className="size-4" />
  652. </button>
  653. </div>
  654. </div>
  655. {/if}
  656. <NoteMenu
  657. onDownload={(type) => {
  658. downloadHandler(type);
  659. }}
  660. onCopyToClipboard={async () => {
  661. const res = await copyToClipboard(note.data.content.md).catch((error) => {
  662. toast.error(`${error}`);
  663. return null;
  664. });
  665. if (res) {
  666. toast.success($i18n.t('Copied to clipboard'));
  667. }
  668. }}
  669. onDelete={() => {
  670. showDeleteConfirm = true;
  671. }}
  672. >
  673. <div class="p-1 bg-transparent hover:bg-white/5 transition rounded-lg">
  674. <EllipsisHorizontal className="size-5" />
  675. </div>
  676. </NoteMenu>
  677. <Tooltip placement="top" content={$i18n.t('Chat')} className="cursor-pointer">
  678. <button
  679. class="p-1.5 bg-transparent hover:bg-white/5 transition rounded-lg"
  680. on:click={() => {
  681. if (showPanel && selectedPanel === 'chat') {
  682. showPanel = false;
  683. } else {
  684. if (!showPanel) {
  685. showPanel = true;
  686. }
  687. selectedPanel = 'chat';
  688. }
  689. }}
  690. >
  691. <ChatBubbleOval />
  692. </button>
  693. </Tooltip>
  694. <Tooltip placement="top" content={$i18n.t('Settings')} className="cursor-pointer">
  695. <button
  696. class="p-1.5 bg-transparent hover:bg-white/5 transition rounded-lg"
  697. on:click={() => {
  698. if (showPanel && selectedPanel === 'settings') {
  699. showPanel = false;
  700. } else {
  701. if (!showPanel) {
  702. showPanel = true;
  703. }
  704. selectedPanel = 'settings';
  705. }
  706. }}
  707. >
  708. <Cog6 />
  709. </button>
  710. </Tooltip>
  711. </div>
  712. </div>
  713. </div>
  714. <div class=" mb-2.5 px-2.5">
  715. <div
  716. class="flex gap-1 items-center text-xs font-medium text-gray-500 dark:text-gray-500"
  717. >
  718. <button class=" flex items-center gap-1 w-fit py-1 px-1.5 rounded-lg">
  719. <Calendar className="size-3.5" strokeWidth="2" />
  720. <span>{dayjs(note.created_at / 1000000).calendar()}</span>
  721. </button>
  722. <button class=" flex items-center gap-1 w-fit py-1 px-1.5 rounded-lg">
  723. <Users className="size-3.5" strokeWidth="2" />
  724. <span> You </span>
  725. </button>
  726. </div>
  727. </div>
  728. <div
  729. class=" flex-1 w-full h-full overflow-auto px-3.5 pb-20 relative"
  730. id="note-content-container"
  731. >
  732. {#if enhancing}
  733. <div
  734. class="w-full h-full fixed top-0 left-0 {streaming
  735. ? ''
  736. : ' backdrop-blur-xs bg-white/10 dark:bg-gray-900/10'} flex items-center justify-center z-10 cursor-not-allowed"
  737. ></div>
  738. {/if}
  739. {#if files && files.length > 0}
  740. <div class="mb-2.5 w-full flex gap-1 flex-wrap z-40">
  741. {#each files as file, fileIdx}
  742. <div class="w-fit">
  743. {#if file.type === 'image'}
  744. <Image
  745. src={file.url}
  746. imageClassName=" max-h-96 rounded-lg"
  747. dismissible={true}
  748. onDismiss={() => {
  749. files = files.filter((item, idx) => idx !== fileIdx);
  750. note.data.files = files.length > 0 ? files : null;
  751. }}
  752. />
  753. {:else}
  754. <FileItem
  755. item={file}
  756. dismissible={true}
  757. url={file.url}
  758. name={file.name}
  759. type={file.type}
  760. size={file?.size}
  761. loading={file.status === 'uploading'}
  762. on:dismiss={() => {
  763. files = files.filter((item) => item?.id !== file.id);
  764. note.data.files = files.length > 0 ? files : null;
  765. }}
  766. />
  767. {/if}
  768. </div>
  769. {/each}
  770. </div>
  771. {/if}
  772. <RichTextInput
  773. bind:this={inputElement}
  774. className="input-prose-sm px-0.5"
  775. bind:value={note.data.content.json}
  776. html={note.data?.content?.html}
  777. json={true}
  778. placeholder={$i18n.t('Write something...')}
  779. editable={versionIdx === null && !enhancing}
  780. onChange={(content) => {
  781. note.data.content.html = content.html;
  782. note.data.content.md = content.md;
  783. }}
  784. />
  785. </div>
  786. </div>
  787. {/if}
  788. </div>
  789. <div class="absolute z-20 bottom-0 right-0 p-5 max-w-full w-full flex justify-end">
  790. <div class="flex gap-1 justify-between w-full max-w-full">
  791. {#if recording}
  792. <div class="flex-1 w-full">
  793. <VoiceRecording
  794. bind:recording
  795. className="p-1 w-full max-w-full"
  796. transcribe={false}
  797. displayMedia={displayMediaRecord}
  798. onCancel={() => {
  799. recording = false;
  800. displayMediaRecord = false;
  801. }}
  802. onConfirm={(data) => {
  803. if (data?.file) {
  804. uploadFileHandler(data?.file);
  805. }
  806. recording = false;
  807. displayMediaRecord = false;
  808. }}
  809. />
  810. </div>
  811. {:else}
  812. <RecordMenu
  813. onRecord={async () => {
  814. displayMediaRecord = false;
  815. try {
  816. let stream = await navigator.mediaDevices
  817. .getUserMedia({ audio: true })
  818. .catch(function (err) {
  819. toast.error(
  820. $i18n.t(`Permission denied when accessing microphone: {{error}}`, {
  821. error: err
  822. })
  823. );
  824. return null;
  825. });
  826. if (stream) {
  827. recording = true;
  828. const tracks = stream.getTracks();
  829. tracks.forEach((track) => track.stop());
  830. }
  831. stream = null;
  832. } catch {
  833. toast.error($i18n.t('Permission denied when accessing microphone'));
  834. }
  835. }}
  836. onCaptureAudio={async () => {
  837. displayMediaRecord = true;
  838. recording = true;
  839. }}
  840. onUpload={async () => {
  841. const input = document.createElement('input');
  842. input.type = 'file';
  843. input.accept = 'audio/*';
  844. input.multiple = false;
  845. input.click();
  846. input.onchange = async (e) => {
  847. const files = e.target.files;
  848. if (files && files.length > 0) {
  849. await uploadFileHandler(files[0]);
  850. }
  851. };
  852. }}
  853. >
  854. <Tooltip content={$i18n.t('Record')} placement="top">
  855. <button
  856. 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"
  857. type="button"
  858. >
  859. <MicSolid className="size-4.5" />
  860. </button>
  861. </Tooltip>
  862. </RecordMenu>
  863. <div
  864. class="cursor-pointer flex gap-0.5 rounded-full border border-gray-50 dark:border-gray-850 dark:bg-gray-850 transition shadow-xl"
  865. >
  866. <!-- <Tooltip content={$i18n.t('My Notes')} placement="top">
  867. <button
  868. class="p-2 size-8.5 flex justify-center items-center {selectedVersion === 'note'
  869. ? 'bg-gray-100 dark:bg-gray-800 '
  870. : ' hover:bg-gray-50 dark:hover:bg-gray-800'} rounded-full transition shrink-0"
  871. type="button"
  872. on:click={() => {
  873. selectedVersion = 'note';
  874. versionToggleHandler();
  875. }}
  876. >
  877. <Bars3BottomLeft />
  878. </button>
  879. </Tooltip> -->
  880. <Tooltip content={$i18n.t('Enhance')} placement="top">
  881. {#if enhancing}
  882. <button
  883. class="p-2 flex justify-center items-center hover:bg-gray-50 dark:hover:bg-gray-800 rounded-full transition shrink-0"
  884. on:click={() => {
  885. stopResponseHandler();
  886. }}
  887. type="button"
  888. >
  889. <Spinner className="size-5" />
  890. </button>
  891. {:else}
  892. <button
  893. class="p-2.5 flex justify-center items-center hover:bg-gray-50 dark:hover:bg-gray-800 rounded-full transition shrink-0"
  894. on:click={() => {
  895. enhanceNoteHandler();
  896. }}
  897. disabled={enhancing}
  898. type="button"
  899. >
  900. <SparklesSolid />
  901. </button>
  902. {/if}
  903. </Tooltip>
  904. </div>
  905. {/if}
  906. </div>
  907. </div>
  908. </Pane>
  909. <NotePanel bind:show={showPanel}>
  910. {#if selectedPanel === 'chat'}
  911. <Chat
  912. bind:show={showPanel}
  913. bind:selectedModelId
  914. bind:messages
  915. bind:note
  916. bind:enhancing
  917. bind:streaming
  918. bind:stopResponseFlag
  919. {files}
  920. onInsert={insertHandler}
  921. onStop={stopResponseHandler}
  922. scrollToBottomHandler={scrollToBottom}
  923. />
  924. {:else if selectedPanel === 'settings'}
  925. <Settings bind:show={showPanel} bind:selectedModelId />
  926. {/if}
  927. </NotePanel>
  928. </PaneGroup>