NoteEditor.svelte 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458
  1. <script lang="ts">
  2. import { getContext, onDestroy, onMount, tick } from 'svelte';
  3. import { v4 as uuidv4 } from 'uuid';
  4. import fileSaver from 'file-saver';
  5. const { saveAs } = fileSaver;
  6. import jsPDF from 'jspdf';
  7. import html2canvas from 'html2canvas-pro';
  8. const i18n = getContext('i18n');
  9. import { marked } from 'marked';
  10. import { toast } from 'svelte-sonner';
  11. import { goto } from '$app/navigation';
  12. import dayjs from '$lib/dayjs';
  13. import calendar from 'dayjs/plugin/calendar';
  14. import duration from 'dayjs/plugin/duration';
  15. import relativeTime from 'dayjs/plugin/relativeTime';
  16. dayjs.extend(calendar);
  17. dayjs.extend(duration);
  18. dayjs.extend(relativeTime);
  19. import { PaneGroup, Pane, PaneResizer } from 'paneforge';
  20. import { compressImage, copyToClipboard, splitStream, convertHeicToJpeg } from '$lib/utils';
  21. import { WEBUI_API_BASE_URL, WEBUI_BASE_URL } from '$lib/constants';
  22. import { uploadFile } from '$lib/apis/files';
  23. import { chatCompletion, generateOpenAIChatCompletion } from '$lib/apis/openai';
  24. import {
  25. config,
  26. mobile,
  27. models,
  28. settings,
  29. showSidebar,
  30. socket,
  31. user,
  32. WEBUI_NAME
  33. } from '$lib/stores';
  34. import NotePanel from '$lib/components/notes/NotePanel.svelte';
  35. import Controls from './NoteEditor/Controls.svelte';
  36. import Chat from './NoteEditor/Chat.svelte';
  37. import AccessControlModal from '$lib/components/workspace/common/AccessControlModal.svelte';
  38. async function loadLocale(locales) {
  39. for (const locale of locales) {
  40. try {
  41. dayjs.locale(locale);
  42. break; // Stop after successfully loading the first available locale
  43. } catch (error) {
  44. console.error(`Could not load locale '${locale}':`, error);
  45. }
  46. }
  47. }
  48. // Assuming $i18n.languages is an array of language codes
  49. $: loadLocale($i18n.languages);
  50. import { deleteNoteById, getNoteById, updateNoteById } from '$lib/apis/notes';
  51. import RichTextInput from '../common/RichTextInput.svelte';
  52. import Spinner from '../common/Spinner.svelte';
  53. import MicSolid from '../icons/MicSolid.svelte';
  54. import VoiceRecording from '../chat/MessageInput/VoiceRecording.svelte';
  55. import DeleteConfirmDialog from '$lib/components/common/ConfirmDialog.svelte';
  56. import ChatBubbleOval from '../icons/ChatBubbleOval.svelte';
  57. import Calendar from '../icons/Calendar.svelte';
  58. import Users from '../icons/Users.svelte';
  59. import Image from '../common/Image.svelte';
  60. import FileItem from '../common/FileItem.svelte';
  61. import FilesOverlay from '../chat/MessageInput/FilesOverlay.svelte';
  62. import RecordMenu from './RecordMenu.svelte';
  63. import NoteMenu from './Notes/NoteMenu.svelte';
  64. import EllipsisHorizontal from '../icons/EllipsisHorizontal.svelte';
  65. import Sparkles from '../icons/Sparkles.svelte';
  66. import SparklesSolid from '../icons/SparklesSolid.svelte';
  67. import Tooltip from '../common/Tooltip.svelte';
  68. import Bars3BottomLeft from '../icons/Bars3BottomLeft.svelte';
  69. import ArrowUturnLeft from '../icons/ArrowUturnLeft.svelte';
  70. import ArrowUturnRight from '../icons/ArrowUturnRight.svelte';
  71. import Sidebar from '../icons/Sidebar.svelte';
  72. import ArrowRight from '../icons/ArrowRight.svelte';
  73. import Cog6 from '../icons/Cog6.svelte';
  74. import AiMenu from './AIMenu.svelte';
  75. import AdjustmentsHorizontalOutline from '../icons/AdjustmentsHorizontalOutline.svelte';
  76. export let id: null | string = null;
  77. let editor = null;
  78. let note = null;
  79. const newNote = {
  80. title: '',
  81. data: {
  82. content: {
  83. json: null,
  84. html: '',
  85. md: ''
  86. },
  87. versions: [],
  88. files: null
  89. },
  90. // pages: [], // TODO: Implement pages for notes to allow users to create multiple pages in a note
  91. meta: null,
  92. access_control: {}
  93. };
  94. let files = [];
  95. let messages = [];
  96. let wordCount = 0;
  97. let charCount = 0;
  98. let versionIdx = null;
  99. let selectedModelId = null;
  100. let recording = false;
  101. let displayMediaRecord = false;
  102. let showPanel = false;
  103. let selectedPanel = 'chat';
  104. let selectedContent = null;
  105. let showDeleteConfirm = false;
  106. let showAccessControlModal = false;
  107. let ignoreBlur = false;
  108. let titleInputFocused = false;
  109. let titleGenerating = false;
  110. let dragged = false;
  111. let loading = false;
  112. let editing = false;
  113. let streaming = false;
  114. let stopResponseFlag = false;
  115. let inputElement = null;
  116. const init = async () => {
  117. loading = true;
  118. const res = await getNoteById(localStorage.token, id).catch((error) => {
  119. toast.error(`${error}`);
  120. return null;
  121. });
  122. messages = [];
  123. if (res) {
  124. note = res;
  125. files = res.data.files || [];
  126. } else {
  127. goto('/');
  128. return;
  129. }
  130. loading = false;
  131. };
  132. let debounceTimeout: NodeJS.Timeout | null = null;
  133. const changeDebounceHandler = () => {
  134. if (debounceTimeout) {
  135. clearTimeout(debounceTimeout);
  136. }
  137. debounceTimeout = setTimeout(async () => {
  138. const res = await updateNoteById(localStorage.token, id, {
  139. title: note?.title === '' ? $i18n.t('Untitled') : note.title,
  140. data: {
  141. files: files
  142. },
  143. access_control: note?.access_control
  144. }).catch((e) => {
  145. toast.error(`${e}`);
  146. });
  147. }, 200);
  148. };
  149. $: if (id) {
  150. init();
  151. }
  152. function areContentsEqual(a, b) {
  153. return JSON.stringify(a) === JSON.stringify(b);
  154. }
  155. function insertNoteVersion(note) {
  156. const current = {
  157. json: note.data.content.json,
  158. html: note.data.content.html,
  159. md: note.data.content.md
  160. };
  161. const lastVersion = note.data.versions?.at(-1);
  162. if (!lastVersion || !areContentsEqual(lastVersion, current)) {
  163. note.data.versions = (note.data.versions ?? []).concat(current);
  164. return true;
  165. }
  166. return false;
  167. }
  168. const onEdited = async () => {
  169. if (!editor) return;
  170. editor.commands.setContent(note.data.content.html);
  171. };
  172. const generateTitleHandler = async () => {
  173. const content = note.data.content.md;
  174. const DEFAULT_TITLE_GENERATION_PROMPT_TEMPLATE = `### Task:
  175. Generate a concise, 3-5 word title with an emoji summarizing the content in the content's primary language.
  176. ### Guidelines:
  177. - The title should clearly represent the main theme or subject of the content.
  178. - Use emojis that enhance understanding of the topic, but avoid quotation marks or special formatting.
  179. - Write the title in the content's primary language.
  180. - Prioritize accuracy over excessive creativity; keep it clear and simple.
  181. - Your entire response must consist solely of the JSON object, without any introductory or concluding text.
  182. - The output must be a single, raw JSON object, without any markdown code fences or other encapsulating text.
  183. - Ensure no conversational text, affirmations, or explanations precede or follow the raw JSON output, as this will cause direct parsing failure.
  184. ### Output:
  185. JSON format: { "title": "your concise title here" }
  186. ### Examples:
  187. - { "title": "📉 Stock Market Trends" },
  188. - { "title": "🍪 Perfect Chocolate Chip Recipe" },
  189. - { "title": "Evolution of Music Streaming" },
  190. - { "title": "Remote Work Productivity Tips" },
  191. - { "title": "Artificial Intelligence in Healthcare" },
  192. - { "title": "🎮 Video Game Development Insights" }
  193. ### Content:
  194. <content>
  195. ${content}
  196. </content>`;
  197. const oldTitle = JSON.parse(JSON.stringify(note.title));
  198. note.title = '';
  199. titleGenerating = true;
  200. const res = await generateOpenAIChatCompletion(
  201. localStorage.token,
  202. {
  203. model: selectedModelId,
  204. stream: false,
  205. messages: [
  206. {
  207. role: 'user',
  208. content: DEFAULT_TITLE_GENERATION_PROMPT_TEMPLATE
  209. }
  210. ]
  211. },
  212. `${WEBUI_BASE_URL}/api`
  213. );
  214. if (res) {
  215. // Step 1: Safely extract the response string
  216. const response = res?.choices[0]?.message?.content ?? '';
  217. try {
  218. const jsonStartIndex = response.indexOf('{');
  219. const jsonEndIndex = response.lastIndexOf('}');
  220. if (jsonStartIndex !== -1 && jsonEndIndex !== -1) {
  221. const jsonResponse = response.substring(jsonStartIndex, jsonEndIndex + 1);
  222. const parsed = JSON.parse(jsonResponse);
  223. if (parsed && parsed.title) {
  224. note.title = parsed.title.trim();
  225. }
  226. }
  227. } catch (e) {
  228. console.error('Error parsing JSON response:', e);
  229. toast.error($i18n.t('Failed to generate title'));
  230. }
  231. }
  232. if (!note.title) {
  233. note.title = oldTitle;
  234. }
  235. titleGenerating = false;
  236. await tick();
  237. changeDebounceHandler();
  238. };
  239. async function enhanceNoteHandler() {
  240. if (selectedModelId === '') {
  241. toast.error($i18n.t('Please select a model.'));
  242. return;
  243. }
  244. const model = $models
  245. .filter((model) => model.id === selectedModelId && !(model?.info?.meta?.hidden ?? false))
  246. .find((model) => model.id === selectedModelId);
  247. if (!model) {
  248. selectedModelId = '';
  249. return;
  250. }
  251. editing = true;
  252. await enhanceCompletionHandler(model);
  253. editing = false;
  254. onEdited();
  255. versionIdx = null;
  256. }
  257. const stopResponseHandler = async () => {
  258. stopResponseFlag = true;
  259. console.log('stopResponse', stopResponseFlag);
  260. };
  261. function setContentByVersion(versionIdx) {
  262. if (!note.data.versions?.length) return;
  263. let idx = versionIdx;
  264. if (idx === null) idx = note.data.versions.length - 1; // latest
  265. const v = note.data.versions[idx];
  266. note.data.content.json = v.json;
  267. note.data.content.html = v.html;
  268. note.data.content.md = v.md;
  269. if (versionIdx === null) {
  270. const lastVersion = note.data.versions.at(-1);
  271. const currentContent = note.data.content;
  272. if (areContentsEqual(lastVersion, currentContent)) {
  273. // remove the last version
  274. note.data.versions = note.data.versions.slice(0, -1);
  275. }
  276. }
  277. }
  278. // Navigation
  279. function versionNavigateHandler(direction) {
  280. if (!note.data.versions || note.data.versions.length === 0) return;
  281. if (versionIdx === null) {
  282. // Get latest snapshots
  283. const lastVersion = note.data.versions.at(-1);
  284. const currentContent = note.data.content;
  285. if (!areContentsEqual(lastVersion, currentContent)) {
  286. // If the current content is different from the last version, insert a new version
  287. insertNoteVersion(note);
  288. versionIdx = note.data.versions.length - 1;
  289. } else {
  290. versionIdx = note.data.versions.length;
  291. }
  292. }
  293. if (direction === 'prev') {
  294. if (versionIdx > 0) versionIdx -= 1;
  295. } else if (direction === 'next') {
  296. if (versionIdx < note.data.versions.length - 1) versionIdx += 1;
  297. else versionIdx = null; // Reset to latest
  298. if (versionIdx === note.data.versions.length - 1) {
  299. // If we reach the latest version, reset to null
  300. versionIdx = null;
  301. }
  302. }
  303. setContentByVersion(versionIdx);
  304. }
  305. const uploadFileHandler = async (file) => {
  306. const tempItemId = uuidv4();
  307. const fileItem = {
  308. type: 'file',
  309. file: '',
  310. id: null,
  311. url: '',
  312. name: file.name,
  313. collection_name: '',
  314. status: 'uploading',
  315. size: file.size,
  316. error: '',
  317. itemId: tempItemId
  318. };
  319. if (fileItem.size == 0) {
  320. toast.error($i18n.t('You cannot upload an empty file.'));
  321. return null;
  322. }
  323. files = [...files, fileItem];
  324. // open the settings panel if it is not open
  325. selectedPanel = 'settings';
  326. if (!showPanel) {
  327. showPanel = true;
  328. }
  329. try {
  330. // If the file is an audio file, provide the language for STT.
  331. let metadata = null;
  332. if (
  333. (file.type.startsWith('audio/') || file.type.startsWith('video/')) &&
  334. $settings?.audio?.stt?.language
  335. ) {
  336. metadata = {
  337. language: $settings?.audio?.stt?.language
  338. };
  339. }
  340. // During the file upload, file content is automatically extracted.
  341. const uploadedFile = await uploadFile(localStorage.token, file, metadata);
  342. if (uploadedFile) {
  343. console.log('File upload completed:', {
  344. id: uploadedFile.id,
  345. name: fileItem.name,
  346. collection: uploadedFile?.meta?.collection_name
  347. });
  348. if (uploadedFile.error) {
  349. console.warn('File upload warning:', uploadedFile.error);
  350. toast.warning(uploadedFile.error);
  351. }
  352. fileItem.status = 'uploaded';
  353. fileItem.file = uploadedFile;
  354. fileItem.id = uploadedFile.id;
  355. fileItem.collection_name =
  356. uploadedFile?.meta?.collection_name || uploadedFile?.collection_name;
  357. fileItem.url = `${WEBUI_API_BASE_URL}/files/${uploadedFile.id}`;
  358. files = files;
  359. } else {
  360. files = files.filter((item) => item?.itemId !== tempItemId);
  361. }
  362. } catch (e) {
  363. toast.error(`${e}`);
  364. files = files.filter((item) => item?.itemId !== tempItemId);
  365. }
  366. if (files.length > 0) {
  367. note.data.files = files;
  368. } else {
  369. note.data.files = null;
  370. }
  371. editor.storage.files = files;
  372. changeDebounceHandler();
  373. return fileItem;
  374. };
  375. const compressImageHandler = async (imageUrl, settings = {}, config = {}) => {
  376. // Quick shortcut so we don’t do unnecessary work.
  377. const settingsCompression = settings?.imageCompression ?? false;
  378. const configWidth = config?.file?.image_compression?.width ?? null;
  379. const configHeight = config?.file?.image_compression?.height ?? null;
  380. // If neither settings nor config wants compression, return original URL.
  381. if (!settingsCompression && !configWidth && !configHeight) {
  382. return imageUrl;
  383. }
  384. // Default to null (no compression unless set)
  385. let width = null;
  386. let height = null;
  387. // If user/settings want compression, pick their preferred size.
  388. if (settingsCompression) {
  389. width = settings?.imageCompressionSize?.width ?? null;
  390. height = settings?.imageCompressionSize?.height ?? null;
  391. }
  392. // Apply config limits as an upper bound if any
  393. if (configWidth && (width === null || width > configWidth)) {
  394. width = configWidth;
  395. }
  396. if (configHeight && (height === null || height > configHeight)) {
  397. height = configHeight;
  398. }
  399. // Do the compression if required
  400. if (width || height) {
  401. return await compressImage(imageUrl, width, height);
  402. }
  403. return imageUrl;
  404. };
  405. const inputFileHandler = async (file) => {
  406. console.log('Processing file:', {
  407. name: file.name,
  408. type: file.type,
  409. size: file.size,
  410. extension: file.name.split('.').at(-1)
  411. });
  412. if (
  413. ($config?.file?.max_size ?? null) !== null &&
  414. file.size > ($config?.file?.max_size ?? 0) * 1024 * 1024
  415. ) {
  416. console.log('File exceeds max size limit:', {
  417. fileSize: file.size,
  418. maxSize: ($config?.file?.max_size ?? 0) * 1024 * 1024
  419. });
  420. toast.error(
  421. $i18n.t(`File size should not exceed {{maxSize}} MB.`, {
  422. maxSize: $config?.file?.max_size
  423. })
  424. );
  425. return;
  426. }
  427. if (file['type'].startsWith('image/')) {
  428. const uploadImagePromise = new Promise(async (resolve, reject) => {
  429. let reader = new FileReader();
  430. reader.onload = async (event) => {
  431. try {
  432. let imageUrl = event.target.result;
  433. imageUrl = await compressImageHandler(imageUrl, $settings, $config);
  434. const fileId = uuidv4();
  435. const fileItem = {
  436. id: fileId,
  437. type: 'image',
  438. url: `${imageUrl}`
  439. };
  440. files = [...files, fileItem];
  441. note.data.files = files;
  442. editor.storage.files = files;
  443. changeDebounceHandler();
  444. resolve(fileItem);
  445. } catch (err) {
  446. reject(err);
  447. }
  448. };
  449. reader.readAsDataURL(file['type'] === 'image/heic' ? await convertHeicToJpeg(file) : file);
  450. });
  451. return await uploadImagePromise;
  452. } else {
  453. return await uploadFileHandler(file);
  454. }
  455. };
  456. const inputFilesHandler = async (inputFiles) => {
  457. console.log('Input files handler called with:', inputFiles);
  458. inputFiles.forEach(async (file) => {
  459. await inputFileHandler(file);
  460. });
  461. };
  462. const downloadHandler = async (type) => {
  463. console.log('downloadHandler', type);
  464. if (type === 'txt') {
  465. const blob = new Blob([note.data.content.md], { type: 'text/plain' });
  466. saveAs(blob, `${note.title}.txt`);
  467. } else if (type === 'md') {
  468. const blob = new Blob([note.data.content.md], { type: 'text/markdown' });
  469. saveAs(blob, `${note.title}.md`);
  470. } else if (type === 'pdf') {
  471. await downloadPdf(note);
  472. }
  473. };
  474. const downloadPdf = async (note) => {
  475. try {
  476. // Define a fixed virtual screen size
  477. const virtualWidth = 1024; // Fixed width (adjust as needed)
  478. const virtualHeight = 1400; // Fixed height (adjust as needed)
  479. // STEP 1. Get a DOM node to render
  480. const html = note.data?.content?.html ?? '';
  481. let node;
  482. if (html instanceof HTMLElement) {
  483. node = html;
  484. } else {
  485. // If it's HTML string, render to a temporary hidden element
  486. node = document.createElement('div');
  487. node.innerHTML = html;
  488. document.body.appendChild(node);
  489. }
  490. // Render to canvas with predefined width
  491. const canvas = await html2canvas(node, {
  492. useCORS: true,
  493. scale: 2, // Keep at 1x to avoid unexpected enlargements
  494. width: virtualWidth, // Set fixed virtual screen width
  495. windowWidth: virtualWidth, // Ensure consistent rendering
  496. windowHeight: virtualHeight
  497. });
  498. // Remove hidden node if needed
  499. if (!(html instanceof HTMLElement)) {
  500. document.body.removeChild(node);
  501. }
  502. const imgData = canvas.toDataURL('image/jpeg', 0.7);
  503. // A4 page settings
  504. const pdf = new jsPDF('p', 'mm', 'a4');
  505. const imgWidth = 210; // A4 width in mm
  506. const pageHeight = 297; // A4 height in mm
  507. // Maintain aspect ratio
  508. const imgHeight = (canvas.height * imgWidth) / canvas.width;
  509. let heightLeft = imgHeight;
  510. let position = 0;
  511. pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight);
  512. heightLeft -= pageHeight;
  513. // Handle additional pages
  514. while (heightLeft > 0) {
  515. position -= pageHeight;
  516. pdf.addPage();
  517. pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight);
  518. heightLeft -= pageHeight;
  519. }
  520. pdf.save(`${note.title}.pdf`);
  521. } catch (error) {
  522. console.error('Error generating PDF', error);
  523. toast.error(`${error}`);
  524. }
  525. };
  526. const deleteNoteHandler = async (id) => {
  527. const res = await deleteNoteById(localStorage.token, id).catch((error) => {
  528. toast.error(`${error}`);
  529. return null;
  530. });
  531. if (res) {
  532. toast.success($i18n.t('Note deleted successfully'));
  533. goto('/notes');
  534. } else {
  535. toast.error($i18n.t('Failed to delete note'));
  536. }
  537. };
  538. const scrollToBottom = () => {
  539. const element = document.getElementById('note-content-container');
  540. if (element) {
  541. element.scrollTop = element?.scrollHeight;
  542. }
  543. };
  544. const enhanceCompletionHandler = async (model) => {
  545. stopResponseFlag = false;
  546. let enhancedContent = {
  547. json: null,
  548. html: '',
  549. md: ''
  550. };
  551. const systemPrompt = `Enhance existing notes using additional context provided from audio transcription or uploaded file content in the content's primary language. Your task is to make the notes more useful and comprehensive by incorporating relevant information from the provided context.
  552. Input will be provided within <notes> and <context> XML tags, providing a structure for the existing notes and context respectively.
  553. # Output Format
  554. Provide the enhanced notes in markdown format. Use markdown syntax for headings, lists, task lists ([ ]) where tasks or checklists are strongly implied, and emphasis to improve clarity and presentation. Ensure that all integrated content from the context is accurately reflected. Return only the markdown formatted note.
  555. `;
  556. const [res, controller] = await chatCompletion(
  557. localStorage.token,
  558. {
  559. model: model.id,
  560. stream: true,
  561. messages: [
  562. {
  563. role: 'system',
  564. content: systemPrompt
  565. },
  566. {
  567. role: 'user',
  568. content:
  569. `<notes>${note.data.content.md}</notes>` +
  570. (files && files.length > 0
  571. ? `\n<context>${files.map((file) => `${file.name}: ${file?.file?.data?.content ?? 'Could not extract content'}\n`).join('')}</context>`
  572. : '')
  573. }
  574. ]
  575. },
  576. `${WEBUI_BASE_URL}/api`
  577. );
  578. await tick();
  579. streaming = true;
  580. if (res && res.ok) {
  581. const reader = res.body
  582. .pipeThrough(new TextDecoderStream())
  583. .pipeThrough(splitStream('\n'))
  584. .getReader();
  585. while (true) {
  586. const { value, done } = await reader.read();
  587. if (done || stopResponseFlag) {
  588. if (stopResponseFlag) {
  589. controller.abort('User: Stop Response');
  590. }
  591. editing = false;
  592. streaming = false;
  593. break;
  594. }
  595. try {
  596. let lines = value.split('\n');
  597. for (const line of lines) {
  598. if (line !== '') {
  599. console.log(line);
  600. if (line === 'data: [DONE]') {
  601. console.log(line);
  602. } else {
  603. let data = JSON.parse(line.replace(/^data: /, ''));
  604. console.log(data);
  605. if (data.choices && data.choices.length > 0) {
  606. const choice = data.choices[0];
  607. if (choice.delta && choice.delta.content) {
  608. enhancedContent.md += choice.delta.content;
  609. enhancedContent.html = marked.parse(enhancedContent.md);
  610. note.data.content.md = enhancedContent.md;
  611. note.data.content.html = enhancedContent.html;
  612. note.data.content.json = null;
  613. scrollToBottom();
  614. }
  615. }
  616. }
  617. }
  618. }
  619. } catch (error) {
  620. console.log(error);
  621. }
  622. }
  623. }
  624. streaming = false;
  625. };
  626. const onDragOver = (e) => {
  627. e.preventDefault();
  628. if (
  629. e.dataTransfer?.types?.includes('text/plain') ||
  630. e.dataTransfer?.types?.includes('text/html')
  631. ) {
  632. dragged = false;
  633. return;
  634. }
  635. // Check if the dragged item is a file or image
  636. if (e.dataTransfer?.types?.includes('Files') && e.dataTransfer?.items) {
  637. const items = Array.from(e.dataTransfer.items);
  638. const hasFiles = items.some((item) => item.kind === 'file');
  639. const hasImages = items.some((item) => item.type.startsWith('image/'));
  640. if (hasFiles && !hasImages) {
  641. dragged = true;
  642. } else {
  643. dragged = false;
  644. }
  645. } else {
  646. dragged = false;
  647. }
  648. };
  649. const onDragLeave = () => {
  650. dragged = false;
  651. };
  652. const onDrop = async (e) => {
  653. e.preventDefault();
  654. console.log(e);
  655. if (e.dataTransfer?.files) {
  656. const inputFiles = Array.from(e.dataTransfer?.files);
  657. if (inputFiles && inputFiles.length > 0) {
  658. console.log(inputFiles);
  659. inputFilesHandler(inputFiles);
  660. }
  661. }
  662. dragged = false;
  663. };
  664. const insertHandler = (content) => {
  665. insertNoteVersion(note);
  666. inputElement?.insertContent(content);
  667. };
  668. const noteEventHandler = async (_note) => {
  669. console.log('noteEventHandler', _note);
  670. if (_note.id !== id) return;
  671. if (_note.access_control && _note.access_control !== note.access_control) {
  672. note.access_control = _note.access_control;
  673. }
  674. if (_note.data && _note.data.files) {
  675. files = _note.data.files;
  676. note.data.files = files;
  677. }
  678. if (_note.title && _note.title) {
  679. note.title = _note.title;
  680. }
  681. editor.storage.files = files;
  682. await tick();
  683. for (const file of files) {
  684. if (file.type === 'image') {
  685. const e = new CustomEvent('data', { files: files });
  686. const img = document.getElementById(`image:${file.id}`);
  687. if (img) {
  688. img.dispatchEvent(e);
  689. }
  690. }
  691. }
  692. };
  693. onMount(async () => {
  694. await tick();
  695. $socket?.emit('join-note', {
  696. note_id: id,
  697. auth: {
  698. token: localStorage.token
  699. }
  700. });
  701. $socket?.on('note-events', noteEventHandler);
  702. if ($settings?.models) {
  703. selectedModelId = $settings?.models[0];
  704. } else if ($config?.default_models) {
  705. selectedModelId = $config?.default_models.split(',')[0];
  706. } else {
  707. selectedModelId = '';
  708. }
  709. if (selectedModelId) {
  710. const model = $models
  711. .filter((model) => model.id === selectedModelId && !(model?.info?.meta?.hidden ?? false))
  712. .find((model) => model.id === selectedModelId);
  713. if (!model) {
  714. selectedModelId = '';
  715. }
  716. }
  717. if (!selectedModelId) {
  718. selectedModelId = $models.at(0)?.id || '';
  719. }
  720. const dropzoneElement = document.getElementById('note-editor');
  721. // dropzoneElement?.addEventListener('dragover', onDragOver);
  722. // dropzoneElement?.addEventListener('drop', onDrop);
  723. // dropzoneElement?.addEventListener('dragleave', onDragLeave);
  724. });
  725. onDestroy(() => {
  726. console.log('destroy');
  727. $socket?.off('note-events', noteEventHandler);
  728. const dropzoneElement = document.getElementById('note-editor');
  729. if (dropzoneElement) {
  730. // dropzoneElement?.removeEventListener('dragover', onDragOver);
  731. // dropzoneElement?.removeEventListener('drop', onDrop);
  732. // dropzoneElement?.removeEventListener('dragleave', onDragLeave);
  733. }
  734. });
  735. </script>
  736. <svelte:head>
  737. <title>
  738. {note?.title
  739. ? `${note?.title.length > 30 ? `${note?.title.slice(0, 30)}...` : note?.title} • ${$WEBUI_NAME}`
  740. : `${$WEBUI_NAME}`}
  741. </title>
  742. </svelte:head>
  743. {#if note}
  744. <AccessControlModal
  745. bind:show={showAccessControlModal}
  746. bind:accessControl={note.access_control}
  747. accessRoles={['read', 'write']}
  748. onChange={() => {
  749. changeDebounceHandler();
  750. }}
  751. />
  752. {/if}
  753. <FilesOverlay show={dragged} />
  754. <DeleteConfirmDialog
  755. bind:show={showDeleteConfirm}
  756. title={$i18n.t('Delete note?')}
  757. on:confirm={() => {
  758. deleteNoteHandler(note.id);
  759. showDeleteConfirm = false;
  760. }}
  761. >
  762. <div class=" text-sm text-gray-500">
  763. {$i18n.t('This will delete')} <span class=" font-semibold">{note.title}</span>.
  764. </div>
  765. </DeleteConfirmDialog>
  766. <PaneGroup direction="horizontal" class="w-full h-full">
  767. <Pane defaultSize={70} minSize={30} class="h-full flex flex-col w-full relative">
  768. <div class="relative flex-1 w-full h-full flex justify-center pt-[11px]" id="note-editor">
  769. {#if loading}
  770. <div class=" absolute top-0 bottom-0 left-0 right-0 flex">
  771. <div class="m-auto">
  772. <Spinner className="size-5" />
  773. </div>
  774. </div>
  775. {:else}
  776. <div class=" w-full flex flex-col {loading ? 'opacity-20' : ''}">
  777. <div class="shrink-0 w-full flex justify-between items-center px-3.5 mb-1.5">
  778. <div class="w-full flex items-center">
  779. {#if $mobile}
  780. <div
  781. class="{$showSidebar
  782. ? 'md:hidden pl-0.5'
  783. : ''} flex flex-none items-center pr-1 -translate-x-1"
  784. >
  785. <Tooltip
  786. content={$showSidebar ? $i18n.t('Close Sidebar') : $i18n.t('Open Sidebar')}
  787. >
  788. <button
  789. id="sidebar-toggle-button"
  790. class=" cursor-pointer flex rounded-lg hover:bg-gray-100 dark:hover:bg-gray-850 transition cursor-"
  791. on:click={() => {
  792. showSidebar.set(!$showSidebar);
  793. }}
  794. >
  795. <div class=" self-center p-1.5">
  796. <Sidebar />
  797. </div>
  798. </button>
  799. </Tooltip>
  800. </div>
  801. {/if}
  802. <input
  803. class="w-full text-2xl font-medium bg-transparent outline-hidden"
  804. type="text"
  805. bind:value={note.title}
  806. placeholder={titleGenerating ? $i18n.t('Generating...') : $i18n.t('Title')}
  807. disabled={(note?.user_id !== $user?.id && $user?.role !== 'admin') ||
  808. titleGenerating}
  809. required
  810. on:focus={() => {
  811. titleInputFocused = true;
  812. }}
  813. on:blur={(e) => {
  814. // check if target is generate button
  815. if (ignoreBlur) {
  816. ignoreBlur = false;
  817. return;
  818. }
  819. titleInputFocused = false;
  820. changeDebounceHandler();
  821. }}
  822. />
  823. {#if titleInputFocused && !titleGenerating}
  824. <div
  825. class="flex self-center items-center space-x-1.5 z-10 translate-y-[0.5px] -translate-x-[0.5px] pl-2"
  826. >
  827. <Tooltip content={$i18n.t('Generate')}>
  828. <button
  829. class=" self-center dark:hover:text-white transition"
  830. id="generate-title-button"
  831. disabled={(note?.user_id !== $user?.id && $user?.role !== 'admin') ||
  832. titleGenerating}
  833. on:mouseenter={() => {
  834. ignoreBlur = true;
  835. }}
  836. on:click={(e) => {
  837. e.preventDefault();
  838. e.stopImmediatePropagation();
  839. e.stopPropagation();
  840. generateTitleHandler();
  841. titleInputFocused = false;
  842. }}
  843. >
  844. <Sparkles strokeWidth="2" />
  845. </button>
  846. </Tooltip>
  847. </div>
  848. {/if}
  849. <div class="flex items-center gap-0.5 translate-x-1">
  850. {#if editor}
  851. <div>
  852. <div class="flex items-center gap-0.5 self-center min-w-fit" dir="ltr">
  853. <button
  854. 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"
  855. on:click={() => {
  856. editor.chain().focus().undo().run();
  857. // versionNavigateHandler('prev');
  858. }}
  859. disabled={!editor.can().undo()}
  860. >
  861. <ArrowUturnLeft className="size-4" />
  862. </button>
  863. <button
  864. 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"
  865. on:click={() => {
  866. editor.chain().focus().redo().run();
  867. // versionNavigateHandler('next');
  868. }}
  869. disabled={!editor.can().redo()}
  870. >
  871. <ArrowUturnRight className="size-4" />
  872. </button>
  873. </div>
  874. </div>
  875. {/if}
  876. <Tooltip placement="top" content={$i18n.t('Chat')} className="cursor-pointer">
  877. <button
  878. class="p-1.5 bg-transparent hover:bg-white/5 transition rounded-lg"
  879. on:click={() => {
  880. if (showPanel && selectedPanel === 'chat') {
  881. showPanel = false;
  882. } else {
  883. if (!showPanel) {
  884. showPanel = true;
  885. }
  886. selectedPanel = 'chat';
  887. }
  888. }}
  889. >
  890. <ChatBubbleOval />
  891. </button>
  892. </Tooltip>
  893. <Tooltip placement="top" content={$i18n.t('Controls')} className="cursor-pointer">
  894. <button
  895. class="p-1.5 bg-transparent hover:bg-white/5 transition rounded-lg"
  896. on:click={() => {
  897. if (showPanel && selectedPanel === 'settings') {
  898. showPanel = false;
  899. } else {
  900. if (!showPanel) {
  901. showPanel = true;
  902. }
  903. selectedPanel = 'settings';
  904. }
  905. }}
  906. >
  907. <AdjustmentsHorizontalOutline />
  908. </button>
  909. </Tooltip>
  910. <NoteMenu
  911. onDownload={(type) => {
  912. downloadHandler(type);
  913. }}
  914. onCopyLink={async () => {
  915. const baseUrl = window.location.origin;
  916. const res = await copyToClipboard(`${baseUrl}/notes/${note.id}`);
  917. if (res) {
  918. toast.success($i18n.t('Copied link to clipboard'));
  919. } else {
  920. toast.error($i18n.t('Failed to copy link'));
  921. }
  922. }}
  923. onCopyToClipboard={async () => {
  924. const res = await copyToClipboard(
  925. note.data.content.md,
  926. note.data.content.html,
  927. true
  928. ).catch((error) => {
  929. toast.error(`${error}`);
  930. return null;
  931. });
  932. if (res) {
  933. toast.success($i18n.t('Copied to clipboard'));
  934. }
  935. }}
  936. onDelete={() => {
  937. showDeleteConfirm = true;
  938. }}
  939. >
  940. <div class="p-1 bg-transparent hover:bg-white/5 transition rounded-lg">
  941. <EllipsisHorizontal className="size-5" />
  942. </div>
  943. </NoteMenu>
  944. </div>
  945. </div>
  946. </div>
  947. <div class=" px-2.5">
  948. <div
  949. class=" flex w-full bg-transparent overflow-x-auto scrollbar-none"
  950. on:wheel={(e) => {
  951. if (e.deltaY !== 0) {
  952. e.preventDefault();
  953. e.currentTarget.scrollLeft += e.deltaY;
  954. }
  955. }}
  956. >
  957. <div
  958. class="flex gap-1 items-center text-xs font-medium text-gray-500 dark:text-gray-500 w-fit"
  959. >
  960. <button class=" flex items-center gap-1 w-fit py-1 px-1.5 rounded-lg min-w-fit">
  961. <Calendar className="size-3.5" strokeWidth="2" />
  962. <!-- check for same date, yesterday, last week, and other -->
  963. {#if dayjs(note.created_at / 1000000).isSame(dayjs(), 'day')}
  964. <span
  965. >{dayjs(note.created_at / 1000000).format($i18n.t('[Today at] h:mm A'))}</span
  966. >
  967. {:else if dayjs(note.created_at / 1000000).isSame(dayjs().subtract(1, 'day'), 'day')}
  968. <span
  969. >{dayjs(note.created_at / 1000000).format(
  970. $i18n.t('[Yesterday at] h:mm A')
  971. )}</span
  972. >
  973. {:else if dayjs(note.created_at / 1000000).isSame(dayjs().subtract(1, 'week'), 'week')}
  974. <span
  975. >{dayjs(note.created_at / 1000000).format(
  976. $i18n.t('[Last] dddd [at] h:mm A')
  977. )}</span
  978. >
  979. {:else}
  980. <span>{dayjs(note.created_at / 1000000).format($i18n.t('DD/MM/YYYY'))}</span>
  981. {/if}
  982. </button>
  983. <button
  984. class=" flex items-center gap-1 w-fit py-1 px-1.5 rounded-lg min-w-fit"
  985. on:click={() => {
  986. showAccessControlModal = true;
  987. }}
  988. disabled={note?.user_id !== $user?.id && $user?.role !== 'admin'}
  989. >
  990. <Users className="size-3.5" strokeWidth="2" />
  991. <span> {note?.access_control ? $i18n.t('Private') : $i18n.t('Everyone')} </span>
  992. </button>
  993. {#if editor}
  994. <div class="flex items-center gap-1 px-1 min-w-fit">
  995. <div>
  996. {$i18n.t('{{COUNT}} words', {
  997. COUNT: wordCount
  998. })}
  999. </div>
  1000. <div>
  1001. {$i18n.t('{{COUNT}} characters', {
  1002. COUNT: charCount
  1003. })}
  1004. </div>
  1005. </div>
  1006. {/if}
  1007. </div>
  1008. </div>
  1009. </div>
  1010. <div
  1011. class=" flex-1 w-full h-full overflow-auto px-3.5 pb-20 relative pt-2.5"
  1012. id="note-content-container"
  1013. >
  1014. {#if editing}
  1015. <div
  1016. class="w-full h-full fixed top-0 left-0 {streaming
  1017. ? ''
  1018. : ' backdrop-blur-xs bg-white/10 dark:bg-gray-900/10'} flex items-center justify-center z-10 cursor-not-allowed"
  1019. ></div>
  1020. {/if}
  1021. <RichTextInput
  1022. bind:this={inputElement}
  1023. bind:editor
  1024. id={`note-${note.id}`}
  1025. className="input-prose-sm px-0.5"
  1026. json={true}
  1027. bind:value={note.data.content.json}
  1028. html={note.data?.content?.html}
  1029. documentId={`note:${note.id}`}
  1030. collaboration={true}
  1031. socket={$socket}
  1032. user={$user}
  1033. link={true}
  1034. image={true}
  1035. {files}
  1036. placeholder={$i18n.t('Write something...')}
  1037. editable={versionIdx === null && !editing}
  1038. onSelectionUpdate={({ editor }) => {
  1039. const { from, to } = editor.state.selection;
  1040. const selectedText = editor.state.doc.textBetween(from, to, ' ');
  1041. if (selectedText.length === 0) {
  1042. selectedContent = null;
  1043. } else {
  1044. selectedContent = {
  1045. text: selectedText,
  1046. from: from,
  1047. to: to
  1048. };
  1049. }
  1050. }}
  1051. onChange={(content) => {
  1052. note.data.content.html = content.html;
  1053. note.data.content.md = content.md;
  1054. if (editor) {
  1055. wordCount = editor.storage.characterCount.words();
  1056. charCount = editor.storage.characterCount.characters();
  1057. }
  1058. }}
  1059. fileHandler={true}
  1060. onFileDrop={(currentEditor, files, pos) => {
  1061. files.forEach(async (file) => {
  1062. const fileItem = await inputFileHandler(file).catch((error) => {
  1063. return null;
  1064. });
  1065. if (fileItem.type === 'image') {
  1066. // If the file is an image, insert it directly
  1067. currentEditor
  1068. .chain()
  1069. .insertContentAt(pos, {
  1070. type: 'image',
  1071. attrs: {
  1072. src: `data://${fileItem.id}`
  1073. }
  1074. })
  1075. .focus()
  1076. .run();
  1077. }
  1078. });
  1079. }}
  1080. onFilePaste={() => {}}
  1081. on:paste={async (e) => {
  1082. e = e.detail.event || e;
  1083. const clipboardData = e.clipboardData || window.clipboardData;
  1084. console.log('Clipboard data:', clipboardData);
  1085. if (clipboardData && clipboardData.items) {
  1086. console.log('Clipboard data items:', clipboardData.items);
  1087. for (const item of clipboardData.items) {
  1088. console.log('Clipboard item:', item);
  1089. if (item.type.indexOf('image') !== -1) {
  1090. const blob = item.getAsFile();
  1091. const fileItem = await inputFileHandler(blob);
  1092. if (editor) {
  1093. editor
  1094. ?.chain()
  1095. .insertContentAt(editor.state.selection.$anchor.pos, {
  1096. type: 'image',
  1097. attrs: {
  1098. src: `data://${fileItem.id}` // Use data URI for the image
  1099. }
  1100. })
  1101. .focus()
  1102. .run();
  1103. }
  1104. } else if (item?.kind === 'file') {
  1105. const file = item.getAsFile();
  1106. await inputFileHandler(file);
  1107. e.preventDefault();
  1108. }
  1109. }
  1110. }
  1111. }}
  1112. />
  1113. </div>
  1114. </div>
  1115. {/if}
  1116. </div>
  1117. <div class="absolute z-20 bottom-0 right-0 p-3.5 max-w-full w-full flex">
  1118. <div class="flex gap-1 w-full min-w-full justify-between">
  1119. {#if recording}
  1120. <div class="flex-1 w-full">
  1121. <VoiceRecording
  1122. bind:recording
  1123. className="p-1 w-full max-w-full"
  1124. transcribe={false}
  1125. displayMedia={displayMediaRecord}
  1126. echoCancellation={false}
  1127. noiseSuppression={false}
  1128. onCancel={() => {
  1129. recording = false;
  1130. displayMediaRecord = false;
  1131. }}
  1132. onConfirm={(data) => {
  1133. if (data?.file) {
  1134. uploadFileHandler(data?.file);
  1135. }
  1136. recording = false;
  1137. displayMediaRecord = false;
  1138. }}
  1139. />
  1140. </div>
  1141. {:else}
  1142. <RecordMenu
  1143. onRecord={async () => {
  1144. displayMediaRecord = false;
  1145. try {
  1146. let stream = await navigator.mediaDevices
  1147. .getUserMedia({ audio: true })
  1148. .catch(function (err) {
  1149. toast.error(
  1150. $i18n.t(`Permission denied when accessing microphone: {{error}}`, {
  1151. error: err
  1152. })
  1153. );
  1154. return null;
  1155. });
  1156. if (stream) {
  1157. recording = true;
  1158. const tracks = stream.getTracks();
  1159. tracks.forEach((track) => track.stop());
  1160. }
  1161. stream = null;
  1162. } catch {
  1163. toast.error($i18n.t('Permission denied when accessing microphone'));
  1164. }
  1165. }}
  1166. onCaptureAudio={async () => {
  1167. displayMediaRecord = true;
  1168. recording = true;
  1169. }}
  1170. onUpload={async () => {
  1171. const input = document.createElement('input');
  1172. input.type = 'file';
  1173. input.accept = 'audio/*';
  1174. input.multiple = false;
  1175. input.click();
  1176. input.onchange = async (e) => {
  1177. const files = e.target.files;
  1178. if (files && files.length > 0) {
  1179. await uploadFileHandler(files[0]);
  1180. }
  1181. };
  1182. }}
  1183. >
  1184. <Tooltip content={$i18n.t('Record')} placement="top">
  1185. <div
  1186. 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"
  1187. >
  1188. <MicSolid className="size-4.5" />
  1189. </div>
  1190. </Tooltip>
  1191. </RecordMenu>
  1192. <div
  1193. class="cursor-pointer flex gap-0.5 rounded-full border border-gray-50 dark:border-gray-850 dark:bg-gray-850 transition shadow-xl"
  1194. >
  1195. <Tooltip content={$i18n.t('AI')} placement="top">
  1196. {#if editing}
  1197. <button
  1198. class="p-2 flex justify-center items-center hover:bg-gray-50 dark:hover:bg-gray-800 rounded-full transition shrink-0"
  1199. on:click={() => {
  1200. stopResponseHandler();
  1201. }}
  1202. type="button"
  1203. >
  1204. <Spinner className="size-5" />
  1205. </button>
  1206. {:else}
  1207. <AiMenu
  1208. onEdit={() => {
  1209. enhanceNoteHandler();
  1210. }}
  1211. onChat={() => {
  1212. showPanel = true;
  1213. selectedPanel = 'chat';
  1214. }}
  1215. >
  1216. <div
  1217. 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"
  1218. >
  1219. <SparklesSolid />
  1220. </div>
  1221. </AiMenu>
  1222. {/if}
  1223. </Tooltip>
  1224. </div>
  1225. {/if}
  1226. </div>
  1227. </div>
  1228. </Pane>
  1229. <NotePanel bind:show={showPanel}>
  1230. {#if selectedPanel === 'chat'}
  1231. <Chat
  1232. bind:show={showPanel}
  1233. bind:selectedModelId
  1234. bind:messages
  1235. bind:note
  1236. bind:editing
  1237. bind:streaming
  1238. bind:stopResponseFlag
  1239. {editor}
  1240. {inputElement}
  1241. {selectedContent}
  1242. {files}
  1243. onInsert={insertHandler}
  1244. onStop={stopResponseHandler}
  1245. {onEdited}
  1246. insertNoteHandler={() => {
  1247. insertNoteVersion(note);
  1248. }}
  1249. scrollToBottomHandler={scrollToBottom}
  1250. />
  1251. {:else if selectedPanel === 'settings'}
  1252. <Controls
  1253. bind:show={showPanel}
  1254. bind:selectedModelId
  1255. bind:files
  1256. onUpdate={() => {
  1257. changeDebounceHandler();
  1258. }}
  1259. />
  1260. {/if}
  1261. </NotePanel>
  1262. </PaneGroup>