This commit is contained in:
Timothy Jaeryang Baek committed 2026-11-07 21:32:04 +09:00
1 parent b6a77a0f12
commit c31cdb4e86
9 files changed
+218 -147

No files matched your search

+1 -1
View File
@@ -1919,7 +1919,7 @@ async def fork_chat_by_id(
}
# The source chat's folder may no longer be writable by the caller.
folder_id = chat.folder_id if is_owner else None
folder_id = chat.folder_id
if folder_id is not None and not await has_folder_write_access(user.id, folder_id, db=db):
folder_id = None
+112
View File
@@ -716,6 +716,118 @@ html.high-contrast.dark .ProseMirror p.is-editor-empty:first-child::before {
@apply dark:border-gray-850 text-xs;
}
.document-markdown {
font-size: 0.75rem;
line-height: 1.5;
overflow-wrap: anywhere;
}
.document-markdown h1,
.document-markdown h2,
.document-markdown h3,
.document-markdown h4,
.document-markdown h5,
.document-markdown h6 {
margin: 1rem 0 0.375rem;
font-weight: 600;
line-height: 1.3;
}
.document-markdown h1 {
font-size: 1.125rem;
}
.document-markdown h2 {
font-size: 1rem;
}
.document-markdown h3 {
font-size: 0.875rem;
}
.document-markdown h4,
.document-markdown h5,
.document-markdown h6 {
font-size: 0.75rem;
}
.document-markdown p,
.document-markdown ul,
.document-markdown ol {
margin: 0.5rem 0;
}
.document-markdown li {
margin-block: 0.125rem;
}
.document-markdown blockquote {
font-size: 0.75rem;
}
.document-markdown strong {
font-weight: 600;
}
.document-markdown hr {
margin: 0.75rem 0;
}
.document-markdown img {
margin: 0.5rem 0;
}
.document-markdown table {
font-size: 0.75rem;
margin: 0.5rem 0;
}
.document-markdown th,
.document-markdown td {
padding: 0.375rem 0.5rem !important;
}
.document-markdown pre {
margin: 0.5rem 0;
font-family: var(--font-mono);
}
.document-markdown pre.hljs {
padding: 0.5rem 0.75rem;
}
.document-markdown pre code {
font-size: 0.75rem;
}
.document-markdown .codespan {
font-size: 0.95em;
}
.document-markdown input[type='checkbox']:disabled {
cursor: default;
}
.document-markdown .document-code-block {
border-radius: 0.5rem;
}
.document-markdown .document-code-block > .sticky {
padding: 0.25rem 0.5rem;
}
.document-markdown .document-code-block > .sticky button {
height: 1.5rem;
padding-inline: 0.375rem;
font-size: 0.6875rem;
}
.document-markdown > :first-child,
.document-markdown .tiptap > :first-child {
margin-top: 0;
}
.document-markdown > :last-child,
.document-markdown .tiptap > :last-child {
margin-bottom: 0;
}
.document-markdown .tiptap th,
.document-markdown .tiptap td {
background: transparent;
border-width: 0 0 1px;
}
.document-markdown .tiptap :is(th, td, li) > p {
margin: 0;
}
.document-markdown .tiptap pre > code {
padding: 0;
background: transparent;
}
.document-markdown .tiptap > div:has(> pre) {
margin: 0.5rem 0;
}
.document-markdown .tiptap img {
max-height: none;
}
.tippy-box[data-theme~='transparent'] {
@apply bg-transparent p-0 m-0 text-inherit;
}
+24 -7
View File
@@ -1223,7 +1223,12 @@
session = chatId;
const previousView =
openedFile?.path === filePath
? { showRaw, currentSlide, selectedExcelSheet, scroll: viewerRoot?.scrollTop ?? 0 }
? {
showRaw,
currentSlide,
selectedExcelSheet,
scroll: viewerRoot?.scrollTop ?? 0
}
: null;
const current = () =>
generation === loadGeneration && selector === effectiveTerminalId && session === chatId;
@@ -2272,7 +2277,22 @@
onSort={toggleSort}
onToggleHidden={toggleHidden}
>
{#if (isMarkdown || isCsv || isHtml || isJson || isSvg || isNotebook) && fileContent !== null && !editing}
{#if isMarkdown && fileContent !== null && !editing}
{#each [{ label: 'Editor', icon: 'pencil', raw: false }, { label: 'Source', icon: 'code', raw: true }] as mode}
<Tooltip content={$i18n.t(mode.label)}>
<button
class="shrink-0 flex h-5 w-5 items-center justify-center rounded transition-colors duration-100 text-gray-500 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 aria-pressed:text-gray-900 dark:aria-pressed:text-white disabled:opacity-30"
aria-label={$i18n.t(mode.label)}
aria-pressed={showRaw === mode.raw}
on:click={() => {
showRaw = mode.raw;
}}
>
<Icon name={mode.icon} size={11} strokeWidth={1.4} />
</button>
</Tooltip>
{/each}
{:else if (isCsv || isHtml || isJson || isSvg || isNotebook) && fileContent !== null && !editing}
<Tooltip content={showRaw ? $i18n.t('Preview') : $i18n.t('Source')}>
<button
class="shrink-0 flex h-5 w-5 items-center justify-center rounded transition-colors duration-100 text-gray-500 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200"
@@ -2321,8 +2341,7 @@
<button
type="button"
class="shrink-0 flex h-5 w-5 items-center justify-center rounded transition-colors duration-100 text-gray-500 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 disabled:opacity-30 disabled:hover:bg-transparent"
on:click={() =>
commentPreviewRef?.save().catch((error) => toast.error(String(error)))}
on:click={() => commentPreviewRef?.save().catch((error) => toast.error(String(error)))}
disabled={saving || !dirty || !selectedFileWritable}
aria-label={$i18n.t('Save')}
>
@@ -2354,7 +2373,7 @@
</Tooltip>
{:else if isHtml}
<!-- HTML preview mode: no edit/save buttons -->
{:else if isMarkdown && showRaw}
{:else if isMarkdown}
<Tooltip content={$i18n.t('Save')}>
<button
class="shrink-0 flex h-5 w-5 items-center justify-center rounded transition-colors duration-100 text-gray-500 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 disabled:opacity-30 disabled:hover:bg-transparent"
@@ -2370,8 +2389,6 @@
{/if}
</button>
</Tooltip>
{:else if isMarkdown}
<!-- Markdown preview mode: no edit/save buttons -->
{:else if isCode}
<Tooltip content={$i18n.t('Save')}>
<button
@@ -2,6 +2,7 @@
import ExcelPreview from '$lib/components/common/ExcelPreview.svelte';
import { getContext, tick } from 'svelte';
import { downloadFileBlob } from '$lib/apis/terminal';
import MarkdownFileEditor from './MarkdownFileEditor.svelte';
import MarkdownDocument from './MarkdownDocument.svelte';
import { settings, config } from '$lib/stores';
import { injectCsp } from '$lib/utils/csp';
@@ -19,6 +20,7 @@
let pdfPagesPreviewRef: PdfPagesPreview;
let fileCodeEditorRef: FileCodeEditor;
let markdownEditorRef: MarkdownFileEditor;
const i18n: any = getContext('i18n');
@@ -56,7 +58,9 @@
text: editContent.slice(editTextarea.selectionStart, editTextarea.selectionEnd),
location: ''
}
: fileCodeEditorRef?.getSelection();
: isMarkdown && !showRaw
? markdownEditorRef?.getSelection()
: fileCodeEditorRef?.getSelection();
export const save = () => (editing ? saveEdit() : saveCodeFile());
export const captureView = () => ({
@@ -292,7 +296,7 @@
// Auto-switch to raw/editor mode for empty previewable files so the user
// can start editing immediately instead of seeing a blank preview.
$: if (fileContent !== null && fileContent.trim() === '' && (isMarkdown || isCsv || isJson)) {
$: if (fileContent !== null && fileContent.trim() === '' && (isCsv || isJson)) {
showRaw = true;
}
@@ -463,12 +467,23 @@
onSave={readOnly ? null : saveCodeFile}
/>
</div>
{:else if isMarkdown && !showRaw && onSave && !readOnly}
{#key selectedFile}
<MarkdownFileEditor
bind:this={markdownEditorRef}
bind:value={codeValue}
path={selectedFile ?? ''}
{baseUrl}
{apiKey}
{chatId}
{readOnly}
onSave={readOnly ? null : saveCodeFile}
/>
{/key}
{:else if isMarkdown && !showRaw}
{#key selectedFile}
<MarkdownDocument
content={fileContent}
onSave={readOnly ? null : onSave}
bind:saving
content={codeValue}
id={`file-${selectedFile}`}
path={selectedFile ?? ''}
{baseUrl}
@@ -35,7 +35,6 @@
}
return prefix + parts.join('/');
}
</script>
<script lang="ts">
@@ -260,96 +259,3 @@
<MarkdownTokens {id} {tokens} editCodeBlock={false} />
</div>
{/key}
<style>
.document-markdown {
font-size: 0.75rem;
line-height: 1.5;
overflow-wrap: anywhere;
}
.document-markdown :global(h1),
.document-markdown :global(h2),
.document-markdown :global(h3),
.document-markdown :global(h4),
.document-markdown :global(h5),
.document-markdown :global(h6) {
margin: 1rem 0 0.375rem;
font-weight: 600;
line-height: 1.3;
}
.document-markdown :global(h1) {
font-size: 1.125rem;
}
.document-markdown :global(h2) {
font-size: 1rem;
}
.document-markdown :global(h3) {
font-size: 0.875rem;
}
.document-markdown :global(h4),
.document-markdown :global(h5),
.document-markdown :global(h6) {
font-size: 0.75rem;
}
.document-markdown :global(p),
.document-markdown :global(ul),
.document-markdown :global(ol) {
margin: 0.5rem 0;
}
.document-markdown :global(li) {
margin-block: 0.125rem;
}
.document-markdown :global(blockquote) {
font-size: 0.75rem;
}
.document-markdown :global(strong) {
font-weight: 600;
}
.document-markdown :global(hr) {
margin: 0.75rem 0;
}
.document-markdown :global(img) {
margin: 0.5rem 0;
}
.document-markdown :global(table) {
font-size: 0.75rem;
margin: 0.5rem 0;
}
.document-markdown :global(th),
.document-markdown :global(td) {
padding: 0.375rem 0.5rem !important;
}
.document-markdown :global(pre) {
margin: 0.5rem 0;
font-family: var(--font-mono);
}
.document-markdown :global(pre.hljs) {
padding: 0.5rem 0.75rem;
}
.document-markdown :global(pre code) {
font-size: 0.75rem;
}
.document-markdown :global(.codespan) {
font-size: 0.95em;
}
.document-markdown :global(input[type='checkbox']:disabled) {
cursor: default;
}
.document-markdown :global(.document-code-block) {
border-radius: 0.5rem;
}
.document-markdown :global(.document-code-block > .sticky) {
padding: 0.25rem 0.5rem;
}
.document-markdown :global(.document-code-block > .sticky button) {
height: 1.5rem;
padding-inline: 0.375rem;
font-size: 0.6875rem;
}
.document-markdown > :global(:first-child) {
margin-top: 0;
}
.document-markdown > :global(:last-child) {
margin-bottom: 0;
}
</style>
@@ -1,9 +1,11 @@
<script lang="ts">
import { getContext, onDestroy } from 'svelte';
import { getContext, onDestroy, tick } from 'svelte';
import type { Editor } from '@tiptap/core';
import { Marked } from 'marked';
import DOMPurify from 'dompurify';
// @ts-expect-error The existing Turndown dependency does not ship declarations.
import TurndownService from 'turndown';
// @ts-expect-error The existing GFM plugin does not ship declarations.
import { gfm } from '@joplin/turndown-plugin-gfm';
import { toast } from 'svelte-sonner';
import RichTextInput from '$lib/components/common/RichTextInput.svelte';
@@ -25,18 +27,26 @@
list: (body, ordered, start) =>
body.includes('data-type="taskItem"')
? `<ul data-type="taskList">${body}</ul>`
: ordered ? `<ol start="${start}">${body}</ol>` : `<ul>${body}</ul>`,
listitem: (text, task, checked) => task
? `<li data-type="taskItem" data-checked="${checked}">${text.replace(/^<input[^>]*>\s*/, '')}</li>`
: `<li>${text}</li>`
: ordered
? `<ol start="${start}">${body}</ol>`
: `<ul>${body}</ul>`,
listitem: (text, task, checked) =>
task
? `<li data-type="taskItem" data-checked="${checked}">${text.replace(/^<input[^>]*>\s*/, '')}</li>`
: `<li>${text}</li>`
}
});
const serializer = new TurndownService({ headingStyle: 'atx', codeBlockStyle: 'fenced' });
serializer.use(gfm);
serializer.addRule('taskCheckbox', { filter: (node) => node.nodeName === 'INPUT', replacement: () => '' });
serializer.addRule('taskCheckbox', {
filter: (node: HTMLElement) => node.nodeName === 'INPUT',
replacement: () => ''
});
serializer.addRule('taskItem', {
filter: (node) => node.nodeName === 'LI' && node.getAttribute('data-type') === 'taskItem',
replacement: (content, node) => `- [${node.getAttribute('data-checked') === 'true' ? 'x' : ' '}] ${content.trim().replace(/\n(?=.)/g, '\n ')}\n`
filter: (node: HTMLElement) =>
node.nodeName === 'LI' && node.getAttribute('data-type') === 'taskItem',
replacement: (content: string, node: HTMLElement) =>
`- [${node.getAttribute('data-checked') === 'true' ? 'x' : ' '}] ${content.trim().replace(/\n(?=.)/g, '\n ')}\n`
});
let editor: Editor | null = null;
@@ -64,40 +74,54 @@
header = source.match(/^---\r?\n[\s\S]*?\r?\n(?:---|\.\.\.)\r?\n/)?.[0] ?? '';
const dom = document.createElement('div');
dom.innerHTML = DOMPurify.sanitize(markdown.parse(source.slice(header.length)) as string);
await Promise.all(Array.from(dom.querySelectorAll('img')).map(async (image) => {
const reference = image.getAttribute('src') ?? '';
const file = resolveDocumentPath(path, reference);
if (!file || !baseUrl) return;
try {
const result = await downloadFileBlob(baseUrl, apiKey, file, chatId ?? undefined);
if (!result || current !== generation) return;
const url = URL.createObjectURL(result.blob);
images.set(url, reference);
image.src = url;
} catch { /* Keep the original reference if an image cannot be loaded. */ }
}));
await Promise.all(
Array.from(dom.querySelectorAll('img')).map(async (image) => {
const reference = image.getAttribute('src') ?? '';
const file = resolveDocumentPath(path, reference);
if (!file || !baseUrl) return;
try {
const result = await downloadFileBlob(baseUrl, apiKey, file, chatId ?? undefined);
if (!result || current !== generation) return;
const url = URL.createObjectURL(result.blob);
images.set(url, reference);
image.src = url;
} catch {
/* Keep the original reference if an image cannot be loaded. */
}
})
);
if (current !== generation) return;
documentJSON = null;
revision++;
html = dom.innerHTML;
}
$: if (value !== lastValue) void load(value);
function attach(next: Editor | null) {
async function attach(next: Editor | null) {
if (!next || editor === next) return;
editor = next;
// Let Tiptap finish normalizing tables before recording the unchanged document.
await tick();
if (next.isDestroyed || editor !== next) return;
next.commands.setTextSelection(1);
originalDocument = JSON.stringify(next.getJSON());
next.view.dom.setAttribute('aria-label', i18n ? $i18n.t('Markdown editor') : 'Markdown editor');
next.on('update', () => {
if (readOnly) return;
const dom = document.createElement('div');
dom.innerHTML = next.getHTML();
for (const table of dom.querySelectorAll('table')) {
const row = table.rows[0];
if (row && Array.from(row.cells).every((cell) => cell.tagName === 'TH')) {
table.createTHead().append(row);
}
}
for (const image of dom.querySelectorAll('img')) {
const reference = images.get(image.getAttribute('src') ?? '');
if (reference) image.setAttribute('src', reference);
}
value = lastValue = JSON.stringify(next.getJSON()) === originalDocument
? original
: header + serializer.turndown(dom.innerHTML) + '\n';
value = lastValue =
JSON.stringify(next.getJSON()) === originalDocument
? original
: header + serializer.turndown(dom.innerHTML) + '\n';
});
}
export const getSelection = () => {
@@ -105,11 +129,14 @@
const { from, to } = editor.state.selection;
return { text: editor.state.doc.textBetween(from, to, '\n'), location: '' };
};
onDestroy(() => { generation++; releaseImages(); });
onDestroy(() => {
generation++;
releaseImages();
});
</script>
<div
class="min-h-full px-4 py-3"
class="min-h-full"
role="presentation"
on:keydown={(event) => {
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 's') {
@@ -122,14 +149,15 @@
{#if html !== null}
{#key revision}
<RichTextInput
messageInput={false}
json={true}
bind:value={documentJSON}
{html}
link={true}
image={true}
editable={!readOnly}
className="input-prose-sm min-h-[12rem]"
placeholder={$i18n.t('Write something...')}
className="document-markdown prose prose-sm dark:prose-invert min-w-0 max-w-none p-3 min-h-[12rem]"
placeholder={$i18n.t('Markdown editor')}
on:editor={(event) => attach(event.detail)}
/>
{/key}
@@ -123,12 +123,6 @@ export const Image = Node.create<ImageOptions>({
addNodeView() {
return ({ node, editor }) => {
const domImg = document.createElement('img');
domImg.setAttribute('src', node.attrs.src || '');
domImg.setAttribute('alt', node.attrs.alt || '');
domImg.setAttribute('title', node.attrs.title || '');
const container = document.createElement('div');
const img = document.createElement('img');
const fileId = node.attrs.src.replace('data://', '');
@@ -164,11 +158,8 @@ export const Image = Node.create<ImageOptions>({
}
});
container.append(img);
return {
dom: img,
contentDOM: domImg
};
// Images are leaf nodes; a detached contentDOM breaks cursor positioning.
return { dom: img };
};
},
+2
View File
@@ -12,6 +12,7 @@ const PLACEHOLDER_IMAGE = '/favicon.png';
* Allowed patterns:
* - Relative paths (starting with '/')
* - data:image/* URIs
* - Blob URLs created on this origin
* - Same-origin URLs (starting with WEBUI_BASE_URL)
* - Gravatar URLs (https://www.gravatar.com/avatar/)
* - External HTTP(S) URLs when allowExternal is true
@@ -27,6 +28,7 @@ export function safeImageUrl(url: string, allowExternal = false): string {
if (
(WEBUI_BASE_URL && url.startsWith(WEBUI_BASE_URL)) ||
url.startsWith('https://www.gravatar.com/avatar/') ||
(typeof location !== 'undefined' && url.startsWith(`blob:${location.origin}/`)) ||
(allowExternal && /^https?:\/\//i.test(url)) ||
url.startsWith('data:') ||
url.startsWith('/')
Binary file not shown.