123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602 |
- <script lang="ts">
- import { getContext, onDestroy, onMount, tick } from 'svelte';
- import { v4 as uuidv4 } from 'uuid';
- import fileSaver from 'file-saver';
- const { saveAs } = fileSaver;
- import jsPDF from 'jspdf';
- import html2canvas from 'html2canvas-pro';
- const i18n = getContext('i18n');
- import { toast } from 'svelte-sonner';
- import { config, settings, showSidebar } from '$lib/stores';
- import { goto } from '$app/navigation';
- import { compressImage } from '$lib/utils';
- import { WEBUI_API_BASE_URL } from '$lib/constants';
- import { uploadFile } from '$lib/apis/files';
- import dayjs from '$lib/dayjs';
- import calendar from 'dayjs/plugin/calendar';
- import duration from 'dayjs/plugin/duration';
- import relativeTime from 'dayjs/plugin/relativeTime';
- dayjs.extend(calendar);
- dayjs.extend(duration);
- dayjs.extend(relativeTime);
- async function loadLocale(locales) {
- for (const locale of locales) {
- try {
- dayjs.locale(locale);
- break; // Stop after successfully loading the first available locale
- } catch (error) {
- console.error(`Could not load locale '${locale}':`, error);
- }
- }
- }
- // Assuming $i18n.languages is an array of language codes
- $: loadLocale($i18n.languages);
- import { deleteNoteById, getNoteById, updateNoteById } from '$lib/apis/notes';
- import RichTextInput from '../common/RichTextInput.svelte';
- import Spinner from '../common/Spinner.svelte';
- import MicSolid from '../icons/MicSolid.svelte';
- import VoiceRecording from '../chat/MessageInput/VoiceRecording.svelte';
- import DeleteConfirmDialog from '$lib/components/common/ConfirmDialog.svelte';
- import Calendar from '../icons/Calendar.svelte';
- import Users from '../icons/Users.svelte';
- import Image from '../common/Image.svelte';
- import FileItem from '../common/FileItem.svelte';
- import FilesOverlay from '../chat/MessageInput/FilesOverlay.svelte';
- import RecordMenu from './RecordMenu.svelte';
- import NoteMenu from './Notes/NoteMenu.svelte';
- import EllipsisHorizontal from '../icons/EllipsisHorizontal.svelte';
- export let id: null | string = null;
- let note = null;
- const newNote = {
- title: '',
- data: {
- content: {
- json: null,
- html: '',
- md: ''
- },
- files: null
- },
- meta: null,
- access_control: null
- };
- let files = [];
- let recording = false;
- let displayMediaRecord = false;
- let showDeleteConfirm = false;
- let dragged = false;
- let loading = false;
- const init = async () => {
- loading = true;
- const res = await getNoteById(localStorage.token, id).catch((error) => {
- toast.error(`${error}`);
- return null;
- });
- if (res) {
- note = res;
- files = res.data.files || [];
- } else {
- goto('/');
- return;
- }
- loading = false;
- };
- let debounceTimeout: NodeJS.Timeout | null = null;
- const changeDebounceHandler = () => {
- if (debounceTimeout) {
- clearTimeout(debounceTimeout);
- }
- debounceTimeout = setTimeout(async () => {
- if (!note) {
- return;
- }
- console.log('Saving note:', note);
- const res = await updateNoteById(localStorage.token, id, {
- ...note,
- title: note.title === '' ? $i18n.t('Untitled') : note.title
- }).catch((e) => {
- toast.error(`${e}`);
- });
- }, 200);
- };
- $: if (note) {
- changeDebounceHandler();
- }
- $: if (id) {
- init();
- }
- const uploadFileHandler = async (file) => {
- const tempItemId = uuidv4();
- const fileItem = {
- type: 'file',
- file: '',
- id: null,
- url: '',
- name: file.name,
- collection_name: '',
- status: 'uploading',
- size: file.size,
- error: '',
- itemId: tempItemId
- };
- if (fileItem.size == 0) {
- toast.error($i18n.t('You cannot upload an empty file.'));
- return null;
- }
- files = [...files, fileItem];
- try {
- // During the file upload, file content is automatically extracted.
- const uploadedFile = await uploadFile(localStorage.token, file);
- if (uploadedFile) {
- console.log('File upload completed:', {
- id: uploadedFile.id,
- name: fileItem.name,
- collection: uploadedFile?.meta?.collection_name
- });
- if (uploadedFile.error) {
- console.warn('File upload warning:', uploadedFile.error);
- toast.warning(uploadedFile.error);
- }
- fileItem.status = 'uploaded';
- fileItem.file = uploadedFile;
- fileItem.id = uploadedFile.id;
- fileItem.collection_name =
- uploadedFile?.meta?.collection_name || uploadedFile?.collection_name;
- fileItem.url = `${WEBUI_API_BASE_URL}/files/${uploadedFile.id}`;
- files = files;
- } else {
- files = files.filter((item) => item?.itemId !== tempItemId);
- }
- } catch (e) {
- toast.error(`${e}`);
- files = files.filter((item) => item?.itemId !== tempItemId);
- }
- if (files.length > 0) {
- note.data.files = files;
- } else {
- note.data.files = null;
- }
- };
- const inputFilesHandler = async (inputFiles) => {
- console.log('Input files handler called with:', inputFiles);
- inputFiles.forEach((file) => {
- console.log('Processing file:', {
- name: file.name,
- type: file.type,
- size: file.size,
- extension: file.name.split('.').at(-1)
- });
- if (
- ($config?.file?.max_size ?? null) !== null &&
- file.size > ($config?.file?.max_size ?? 0) * 1024 * 1024
- ) {
- console.log('File exceeds max size limit:', {
- fileSize: file.size,
- maxSize: ($config?.file?.max_size ?? 0) * 1024 * 1024
- });
- toast.error(
- $i18n.t(`File size should not exceed {{maxSize}} MB.`, {
- maxSize: $config?.file?.max_size
- })
- );
- return;
- }
- if (
- ['image/gif', 'image/webp', 'image/jpeg', 'image/png', 'image/avif'].includes(file['type'])
- ) {
- let reader = new FileReader();
- reader.onload = async (event) => {
- let imageUrl = event.target.result;
- if ($settings?.imageCompression ?? false) {
- const width = $settings?.imageCompressionSize?.width ?? null;
- const height = $settings?.imageCompressionSize?.height ?? null;
- if (width || height) {
- imageUrl = await compressImage(imageUrl, width, height);
- }
- }
- files = [
- ...files,
- {
- type: 'image',
- url: `${imageUrl}`
- }
- ];
- note.data.files = files;
- };
- reader.readAsDataURL(file);
- } else {
- uploadFileHandler(file);
- }
- });
- };
- const downloadHandler = async (type) => {
- console.log('downloadHandler', type);
- if (type === 'md') {
- const blob = new Blob([note.data.content.md], { type: 'text/markdown' });
- saveAs(blob, `${note.title}.md`);
- } else if (type === 'pdf') {
- await downloadPdf(note);
- }
- };
- const downloadPdf = async (note) => {
- try {
- // Define a fixed virtual screen size
- const virtualWidth = 1024; // Fixed width (adjust as needed)
- const virtualHeight = 1400; // Fixed height (adjust as needed)
- // STEP 1. Get a DOM node to render
- const html = note.data?.content?.html ?? '';
- let node;
- if (html instanceof HTMLElement) {
- node = html;
- } else {
- // If it's HTML string, render to a temporary hidden element
- node = document.createElement('div');
- node.innerHTML = html;
- document.body.appendChild(node);
- }
- // Render to canvas with predefined width
- const canvas = await html2canvas(node, {
- useCORS: true,
- scale: 2, // Keep at 1x to avoid unexpected enlargements
- width: virtualWidth, // Set fixed virtual screen width
- windowWidth: virtualWidth, // Ensure consistent rendering
- windowHeight: virtualHeight
- });
- // Remove hidden node if needed
- if (!(html instanceof HTMLElement)) {
- document.body.removeChild(node);
- }
- const imgData = canvas.toDataURL('image/png');
- // A4 page settings
- const pdf = new jsPDF('p', 'mm', 'a4');
- const imgWidth = 210; // A4 width in mm
- const pageHeight = 297; // A4 height in mm
- // Maintain aspect ratio
- const imgHeight = (canvas.height * imgWidth) / canvas.width;
- let heightLeft = imgHeight;
- let position = 0;
- pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
- heightLeft -= pageHeight;
- // Handle additional pages
- while (heightLeft > 0) {
- position -= pageHeight;
- pdf.addPage();
- pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
- heightLeft -= pageHeight;
- }
- pdf.save(`${note.title}.pdf`);
- } catch (error) {
- console.error('Error generating PDF', error);
- toast.error(`${error}`);
- }
- };
- const deleteNoteHandler = async (id) => {
- const res = await deleteNoteById(localStorage.token, id).catch((error) => {
- toast.error(`${error}`);
- return null;
- });
- if (res) {
- toast.success($i18n.t('Note deleted successfully'));
- goto('/notes');
- } else {
- toast.error($i18n.t('Failed to delete note'));
- }
- };
- const onDragOver = (e) => {
- e.preventDefault();
- // Check if a file is being dragged.
- if (e.dataTransfer?.types?.includes('Files')) {
- dragged = true;
- } else {
- dragged = false;
- }
- };
- const onDragLeave = () => {
- dragged = false;
- };
- const onDrop = async (e) => {
- e.preventDefault();
- console.log(e);
- if (e.dataTransfer?.files) {
- const inputFiles = Array.from(e.dataTransfer?.files);
- if (inputFiles && inputFiles.length > 0) {
- console.log(inputFiles);
- inputFilesHandler(inputFiles);
- }
- }
- dragged = false;
- };
- onMount(async () => {
- await tick();
- const dropzoneElement = document.getElementById('note-editor');
- dropzoneElement?.addEventListener('dragover', onDragOver);
- dropzoneElement?.addEventListener('drop', onDrop);
- dropzoneElement?.addEventListener('dragleave', onDragLeave);
- });
- onDestroy(() => {
- console.log('destroy');
- const dropzoneElement = document.getElementById('note-editor');
- if (dropzoneElement) {
- dropzoneElement?.removeEventListener('dragover', onDragOver);
- dropzoneElement?.removeEventListener('drop', onDrop);
- dropzoneElement?.removeEventListener('dragleave', onDragLeave);
- }
- });
- </script>
- <FilesOverlay show={dragged} />
- <DeleteConfirmDialog
- bind:show={showDeleteConfirm}
- title={$i18n.t('Delete note?')}
- on:confirm={() => {
- deleteNoteHandler(note.id);
- showDeleteConfirm = false;
- }}
- >
- <div class=" text-sm text-gray-500">
- {$i18n.t('This will delete')} <span class=" font-semibold">{note.title}</span>.
- </div>
- </DeleteConfirmDialog>
- <div class="relative flex-1 w-full h-full flex justify-center" id="note-editor">
- {#if loading}
- <div class=" absolute top-0 bottom-0 left-0 right-0 flex">
- <div class="m-auto">
- <Spinner />
- </div>
- </div>
- {:else}
- <div class=" w-full flex flex-col {loading ? 'opacity-20' : ''}">
- <div class="shrink-0 w-full flex justify-between items-center px-4.5 pt-1 mb-1.5">
- <div class="w-full flex">
- <input
- class="w-full text-2xl font-medium bg-transparent outline-hidden"
- type="text"
- bind:value={note.title}
- placeholder={$i18n.t('Title')}
- required
- />
- <div>
- <NoteMenu
- onDownload={(type) => {
- downloadHandler(type);
- }}
- onDelete={() => {
- showDeleteConfirm = true;
- }}
- >
- <button
- class="self-center w-fit text-sm p-1 dark:text-gray-300 dark:hover:text-white hover:bg-black/5 dark:hover:bg-white/5 rounded-xl"
- type="button"
- >
- <EllipsisHorizontal className="size-5" />
- </button>
- </NoteMenu>
- </div>
- </div>
- </div>
- <div class=" mb-2.5 px-3.5">
- <div class="flex gap-1 items-center text-xs font-medium text-gray-500 dark:text-gray-500">
- <button class=" flex items-center gap-1 w-fit py-1 px-1.5 rounded-lg">
- <Calendar className="size-3.5" strokeWidth="2" />
- <span>{dayjs(note.created_at / 1000000).calendar()}</span>
- </button>
- <button class=" flex items-center gap-1 w-fit py-1 px-1.5 rounded-lg">
- <Users className="size-3.5" strokeWidth="2" />
- <span> You </span>
- </button>
- </div>
- </div>
- <div class=" flex-1 w-full h-full overflow-auto px-4 pb-5">
- {#if files && files.length > 0}
- <div class="mb-3.5 mt-1.5 w-full flex gap-1 flex-wrap z-40">
- {#each files as file, fileIdx}
- <div class="w-fit">
- {#if file.type === 'image'}
- <Image
- src={file.url}
- imageClassName=" max-h-96 rounded-lg"
- dismissible={true}
- onDismiss={() => {
- files = files.filter((item, idx) => idx !== fileIdx);
- note.data.files = files.length > 0 ? files : null;
- }}
- />
- {:else}
- <FileItem
- item={file}
- dismissible={true}
- url={file.url}
- name={file.name}
- type={file.type}
- size={file?.size}
- loading={file.status === 'uploading'}
- on:dismiss={() => {
- files = files.filter((item) => item?.id !== file.id);
- note.data.files = files.length > 0 ? files : null;
- }}
- />
- {/if}
- </div>
- {/each}
- </div>
- {/if}
- <RichTextInput
- className="input-prose-sm px-0.5"
- bind:value={note.data.content.json}
- placeholder={$i18n.t('Write something...')}
- json={true}
- onChange={(content) => {
- note.data.content.html = content.html;
- note.data.content.md = content.md;
- }}
- />
- </div>
- </div>
- {/if}
- </div>
- <div class="absolute bottom-0 right-0 p-5 max-w-full flex justify-end">
- <div
- class="flex gap-0.5 justify-end w-full {$showSidebar && recording
- ? 'md:max-w-[calc(100%-260px)]'
- : ''} max-w-full"
- >
- {#if recording}
- <div class="flex-1 w-full">
- <VoiceRecording
- bind:recording
- className="p-1 w-full max-w-full"
- transcribe={false}
- displayMedia={displayMediaRecord}
- onCancel={() => {
- recording = false;
- displayMediaRecord = false;
- }}
- onConfirm={(data) => {
- if (data?.file) {
- uploadFileHandler(data?.file);
- }
- recording = false;
- displayMediaRecord = false;
- }}
- />
- </div>
- {:else}
- <RecordMenu
- onRecord={async () => {
- displayMediaRecord = false;
- try {
- let stream = await navigator.mediaDevices
- .getUserMedia({ audio: true })
- .catch(function (err) {
- toast.error(
- $i18n.t(`Permission denied when accessing microphone: {{error}}`, {
- error: err
- })
- );
- return null;
- });
- if (stream) {
- recording = true;
- const tracks = stream.getTracks();
- tracks.forEach((track) => track.stop());
- }
- stream = null;
- } catch {
- toast.error($i18n.t('Permission denied when accessing microphone'));
- }
- }}
- onCaptureAudio={async () => {
- displayMediaRecord = true;
- recording = true;
- }}
- onUpload={async () => {
- const input = document.createElement('input');
- input.type = 'file';
- input.accept = 'audio/*';
- input.multiple = false;
- input.click();
- input.onchange = async (e) => {
- const files = e.target.files;
- if (files && files.length > 0) {
- await uploadFileHandler(files[0]);
- }
- };
- }}
- >
- <button
- class="cursor-pointer p-2.5 flex rounded-full border border-gray-50 dark:border-none dark:bg-gray-850 hover:bg-gray-50 dark:hover:bg-gray-800 transition shadow-xl"
- type="button"
- >
- <MicSolid className="size-4.5" />
- </button>
- </RecordMenu>
- {/if}
- </div>
- </div>
|