This commit is contained in:
Timothy Jaeryang Baek committed 2026-11-07 22:51:09 +09:00
1 parent dfc9832051
commit b5eaa59d0a
7 files changed
+206 -247

No files matched your search

+61 -7
View File
@@ -508,12 +508,15 @@
let draggedTabId = '';
let pendingTabDrop: (() => void) | null = null;
const clearChatDropPreview = () => (chatDropPreview = null);
const canDropChat = (event: DragEvent) =>
const canDropChat = (event: Pick<DragEvent, 'dataTransfer'>) =>
canSideChat &&
($user?.role === 'admin' || !($user?.permissions?.chat?.temporary_enforced ?? false)) &&
event.dataTransfer?.types.includes('application/x-open-webui-chat');
const chatDropBounds = (event: DragEvent): SplitDrop | null => {
const internal = event.dataTransfer?.types.includes('application/x-chat-panel-tab');
const chatDropBounds = (
event: Pick<DragEvent, 'target' | 'clientX' | 'clientY' | 'dataTransfer'>
): SplitDrop | null => {
const internal =
!!draggedTabId || event.dataTransfer?.types.includes('application/x-chat-panel-tab');
if ((!internal && !canDropChat(event)) || !(event.target instanceof Element)) return null;
if (!internal && event.target.closest('[data-composer-id]')) return null;
const group = event.target.closest<HTMLElement>('[data-panel-group]');
@@ -781,6 +784,24 @@
let tabDropHandled = false;
const sortableTabs = (node: HTMLElement) => {
let nextSibling: ChildNode | null = null;
let touchDrag = false;
const trackTouch = (event: TouchEvent) => {
if (!touchDrag) return;
const point = event.touches[0] ?? event.changedTouches[0];
chatDropPreview = point
? chatDropBounds({
target: document.elementFromPoint(point.clientX, point.clientY),
clientX: point.clientX,
clientY: point.clientY,
dataTransfer: null
})
: null;
};
const preventTouchMenu = (event: Event) => {
if ((event.target as Element).closest('[role="tab"]')) event.preventDefault();
};
document.addEventListener('touchmove', trackTouch, { passive: true });
node.addEventListener('contextmenu', preventTouchMenu);
const sortable = new Sortable(node, {
animation: 150,
direction: 'horizontal',
@@ -789,16 +810,33 @@
delay: 200,
delayOnTouchOnly: true,
touchStartThreshold: 5,
// Touch events let Sortable cancel scrolling after the hold without disabling quick swipes.
supportPointer: false,
fallbackOnBody: true,
ghostClass: 'opacity-40',
setData: (transfer: DataTransfer, item: HTMLElement) =>
transfer.setData('application/x-chat-panel-tab', item.dataset.panelTab ?? ''),
onStart: ({ item }: { item: HTMLElement }) => {
onStart: ({ item, originalEvent }: { item: HTMLElement; originalEvent?: Event }) => {
nextSibling = item.nextSibling;
touchDrag = !!originalEvent && 'touches' in originalEvent;
clearChatDropPreview();
tabDropHandled = false;
draggedTabId = item.dataset.panelTab ?? '';
dragged = true;
},
onEnd: ({ item, from }: { item: HTMLElement; from: HTMLElement }) => {
onEnd: ({
item,
from,
originalEvent
}: {
item: HTMLElement;
from: HTMLElement;
originalEvent?: Event;
}) => {
const cancelled = originalEvent?.type === 'touchcancel';
if (touchDrag && originalEvent && 'touches' in originalEvent)
trackTouch(originalEvent as TouchEvent);
const touchTarget = touchDrag && !cancelled ? chatDropPreview : null;
const id = item.dataset.panelTab!;
const group = tabGroups[id];
const order = Array.from(from.querySelectorAll<HTMLElement>('[data-panel-tab]'))
@@ -806,15 +844,27 @@
.filter((tabId) => group?.tabIds.includes(tabId));
// Restore the DOM before Svelte reconciles its keyed tabs.
from.insertBefore(item, nextSibling?.parentNode === from ? nextSibling : null);
if (!tabDropHandled) tabs = moveTab(tabs, id, order.indexOf(id));
if (touchTarget) {
tabs = touchTarget.edge
? splitTab(tabs, id, touchTarget.groupId, touchTarget.edge)
: moveTabToGroup(tabs, id, touchTarget.groupId);
} else if (!tabDropHandled && !cancelled) tabs = moveTab(tabs, id, order.indexOf(id));
const drop = pendingTabDrop;
pendingTabDrop = null;
drop?.();
draggedTabId = '';
dragged = false;
touchDrag = false;
clearChatDropPreview();
}
});
return { destroy: () => sortable.destroy() };
return {
destroy: () => {
sortable.destroy();
document.removeEventListener('touchmove', trackTouch);
node.removeEventListener('contextmenu', preventTouchMenu);
}
};
};
const navigateTabs = (event: KeyboardEvent) => {
if (!(event.target instanceof HTMLElement) || event.target.getAttribute('role') !== 'tab')
@@ -1907,6 +1957,10 @@
{/if}
<style>
.panel-tab {
-webkit-touch-callout: none;
}
.panel-tab:not(:has(:global(button:not([role='tab'])))) {
padding-inline: 0.625rem;
}
+4 -45
View File
@@ -39,7 +39,6 @@
type TerminalFileRoot,
type TerminalCwd
} from '$lib/apis/terminal';
import { isCodeFile } from '$lib/utils/codeHighlight';
import { isSavedChatId, isTemporaryChatId } from '$lib/utils/chatId';
import { copyToClipboard } from '$lib/utils';
import { normalizeDocumentTargetPage } from '$lib/utils/documentPreview';
@@ -104,7 +103,7 @@
await filePreviewRef?.restoreView(
view.preview.dirty || view.preview.baseText === fileContent
? view.preview
: { ...view.preview, text: fileContent ?? '', editor: undefined, editing: false }
: { ...view.preview, text: fileContent ?? '', editor: undefined }
);
}
for (const path of view.expanded ?? []) {
@@ -731,7 +730,6 @@
let excelWorkbook: import('xlsx').WorkBook | null = null;
// File preview toolbar state (bound from FilePreview)
let editing = false;
let showRaw = false;
let saving = false;
@@ -747,7 +745,6 @@
$: isJson = ['json', 'jsonc', 'jsonl', 'json5'].includes(getFileExt(selectedFile));
$: isSvg = getFileExt(selectedFile) === 'svg';
$: isNotebook = getFileExt(selectedFile) === 'ipynb';
$: isCode = isCodeFile(selectedFile);
$: isOfficeFile = OFFICE_EXTS.has(getFileExt(selectedFile));
$: isTextFile =
fileContent !== null && fileImageUrl === null && filePdfData === null && !isOfficeFile;
@@ -2360,7 +2357,7 @@
onSort={toggleSort}
onToggleHidden={toggleHidden}
>
{#if isMarkdown && fileContent !== null && !editing}
{#if isMarkdown && fileContent !== null}
{#each [{ label: 'Editor', icon: 'pencil', raw: false }, { label: 'Source', icon: 'code', raw: true }] as mode}
<Tooltip content={$i18n.t(mode.label)}>
<button
@@ -2375,13 +2372,12 @@
</button>
</Tooltip>
{/each}
{:else if (isCsv || isHtml || isJson || isSvg || isNotebook) && fileContent !== null && !editing}
{:else if (isCsv || isHtml || isJson || isSvg || isNotebook) && fileContent !== null}
<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"
on:click={async () => {
if (!(await protectBuffer())) return;
if (editing) filePreviewRef?.cancelEdit();
showRaw = !showRaw;
}}
aria-label={showRaw ? $i18n.t('Preview') : $i18n.t('Source')}
@@ -2472,7 +2468,7 @@
{/if}
</button>
</Tooltip>
{:else if isCode}
{:else if showRaw || (!isCsv && !isJson && !isSvg && !isNotebook) || dirty}
<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"
@@ -2488,42 +2484,6 @@
{/if}
</button>
</Tooltip>
{:else if editing}
<Tooltip content={$i18n.t('Cancel')}>
<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"
on:click={() => filePreviewRef?.cancelEdit()}
aria-label={$i18n.t('Cancel')}
>
<Icon name="xmark" size={11} strokeWidth={1.7} />
</button>
</Tooltip>
<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"
on:click={() =>
filePreviewRef?.saveEdit().catch((error) => toast.error(String(error)))}
disabled={saving || !selectedFileWritable}
aria-label={$i18n.t('Save')}
>
{#if saving}
<Spinner className="size-3.5" />
{:else}
<Icon name="check" size={11} strokeWidth={1.7} />
{/if}
</button>
</Tooltip>
{:else}
<Tooltip content={$i18n.t('Edit')}>
<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={() => filePreviewRef?.startEdit()}
disabled={!selectedFileWritable}
aria-label={$i18n.t('Edit')}
>
<Icon name="pencil" size={11} strokeWidth={1.4} />
</button>
</Tooltip>
{/if}
{/if}
</FileNavToolbar>
@@ -2674,7 +2634,6 @@
<FilePreview
{gitBaseContent}
bind:this={filePreviewRef}
bind:editing
bind:showRaw
bind:saving
bind:dirty
@@ -172,7 +172,10 @@
let languageGeneration = 0;
const detectLanguage = async (path: string | null) => {
const version = ++languageGeneration;
const match = path ? LanguageDescription.matchFilename(languages, path) : null;
const filename = path?.split(/[\\/]/).pop() ?? '';
const match =
LanguageDescription.matchFilename(languages, filename) ??
LanguageDescription.matchFilename(languages, filename.toLowerCase());
editor?.dispatch({ effects: editorLanguage.reconfigure([]) });
try {
const language = await match?.load();
@@ -248,13 +251,15 @@
placeholder ? editorPlaceholder(placeholder) : []
]),
EditorView.theme({
'&': { fontSize: '0.75rem', height: '100%' },
'&': { fontSize: '0.8125rem', height: '100%' },
'.cm-content': {
padding: '0.5rem 0',
fontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace'
padding: '0.5rem 0'
},
'.cm-scroller': { overflow: 'auto' },
'.cm-focused': { outline: 'none' }
'.cm-scroller': {
overflow: 'auto',
fontFamily: '"JetBrains Mono", "Fira Code", ui-monospace, monospace'
},
'&.cm-focused': { outline: 'none' }
})
];
@@ -290,11 +295,27 @@
<style>
.file-code-editor {
--editor-bg: #fff;
--editor-fg: #525252;
width: 100%;
height: 100%;
}
:global(.dark) .file-code-editor {
--editor-bg: #121212;
--editor-fg: #d4d4d4;
}
.file-code-editor :global(.cm-editor) {
height: 100%;
background-color: var(--editor-bg);
color: var(--editor-fg);
}
.file-code-editor :global(.cm-gutters) {
background-color: var(--editor-bg) !important;
color: color-mix(in oklab, var(--editor-fg) 48%, var(--editor-bg));
}
.file-code-editor :global(.cm-activeLine),
.file-code-editor :global(.cm-activeLineGutter) {
background-color: color-mix(in oklab, var(--editor-fg) 6%, transparent);
}
.file-code-editor :global(.cm-lineNumbers .cm-git-line-added) {
@@ -6,7 +6,6 @@
import MarkdownDocument from './MarkdownDocument.svelte';
import { settings, config } from '$lib/stores';
import { injectCsp } from '$lib/utils/csp';
import { isCodeFile } from '$lib/utils/codeHighlight';
import { sanitizeSvg } from '$lib/utils';
import Spinner from '../../common/Spinner.svelte';
import PdfPagesPreview from '../../common/PdfPagesPreview.svelte';
@@ -52,41 +51,28 @@
lastLoaded = content;
};
$: syncContent(fileContent, selectedFile);
$: dirty = editing ? editContent !== (fileContent ?? '') : codeValue !== (fileContent ?? '');
$: dirty = codeValue !== (fileContent ?? '');
export const getSelection = () =>
editing && editTextarea?.selectionStart !== editTextarea?.selectionEnd
? {
text: editContent.slice(editTextarea.selectionStart, editTextarea.selectionEnd),
location: ''
}
: isMarkdown && !showRaw
? markdownEditorRef?.getSelection()
: fileCodeEditorRef?.getSelection();
export const save = () => (editing ? saveEdit() : saveCodeFile());
isMarkdown && !showRaw && !searchTarget
? markdownEditorRef?.getSelection()
: fileCodeEditorRef?.getSelection();
export const save = () => saveCodeFile();
export const captureView = () => ({
baseText: fileContent ?? '',
text: editing ? editContent : codeValue,
text: codeValue,
dirty,
editing,
showRaw,
editor: fileCodeEditorRef?.captureView(),
selection: editTextarea ? [editTextarea.selectionStart, editTextarea.selectionEnd] : null,
scrollTop: editTextarea?.scrollTop ?? 0
editor: fileCodeEditorRef?.captureView()
});
export async function restoreView(view: any) {
if (!view) return;
editing = view.editing;
showRaw = view.showRaw;
codeValue = editContent = view.text;
codeValue = view.text;
lastLoaded = fileContent;
bufferPath = selectedFile;
await tick();
fileCodeEditorRef?.restoreView(view.editor);
if (editTextarea && view.selection) {
editTextarea.setSelectionRange(view.selection[0], view.selection[1]);
editTextarea.scrollTop = view.scrollTop;
}
}
// Office preview props
@@ -110,62 +96,24 @@
requestId: number;
} | null = null;
export let editing = false;
let editContent = '';
export let saving = false;
let editTextarea: HTMLTextAreaElement;
// Reset edit state when switching files
$: (selectedFile, resetEdit());
const resetEdit = () => {
editing = false;
editContent = '';
saving = false;
codeValue = fileContent ?? '';
};
export const startEdit = async () => {
if (readOnly) return;
editContent = fileContent ?? '';
editing = true;
showRaw = true;
await tick();
editTextarea?.focus();
};
export const saveEdit = async () => {
if (!onSave || readOnly) return;
saving = true;
const target = selectedFile,
content = editContent;
try {
await onSave(content);
if (selectedFile === target && editContent === content) editing = false;
} finally {
saving = false;
}
};
export const discard = () => {
codeValue = fileContent ?? '';
editContent = fileContent ?? '';
fileCodeEditorRef?.setValue(codeValue);
dirty = false;
};
export const cancelEdit = () => {
editing = false;
editContent = '';
};
/** Save code file directly from CodeMirror */
export const saveCodeFile = async () => {
if (!onSave || readOnly) return;
saving = true;
try {
if (isMarkdown && !showRaw) await markdownEditorRef?.flushUploads();
if (isMarkdown && !showRaw && !searchTarget) await markdownEditorRef?.flushUploads();
const content =
isMarkdown && !showRaw ? codeValue : (fileCodeEditorRef?.getValue() ?? codeValue);
isMarkdown && !showRaw && !searchTarget
? codeValue
: (fileCodeEditorRef?.getValue() ?? codeValue);
await onSave(content);
} finally {
saving = false;
@@ -186,7 +134,6 @@
$: isJson = JSON_EXTS.has(getExt(selectedFile));
$: isSvg = getExt(selectedFile) === 'svg';
$: isNotebook = getExt(selectedFile) === 'ipynb';
$: isCode = isCodeFile(selectedFile);
$: csvDelimiter = getExt(selectedFile) === 'tsv' ? '\t' : ',';
$: isPptx = getExt(selectedFile) === 'pptx';
@@ -239,46 +186,17 @@
$: csvHeader = csvRows.length > 0 ? csvRows[0] : [];
$: csvBody = csvRows.length > 1 ? csvRows.slice(1) : [];
// Shiki code highlighting (SVG only)
let highlightedHtml: string | null = null;
let highlightingFile: string | null = null;
$: if (isSvg && fileContent !== null && selectedFile) {
const currentFile = selectedFile;
highlightingFile = currentFile;
import('shiki')
.then(({ codeToHtml }) =>
codeToHtml(fileContent!, {
lang: 'xml',
themes: { light: 'github-light', dark: 'github-dark' },
defaultColor: 'light'
})
)
.then((html) => {
if (highlightingFile === currentFile) highlightedHtml = html;
})
.catch(() => {
if (highlightingFile === currentFile) highlightedHtml = null;
});
} else {
highlightedHtml = null;
}
// JSON parsing
let parsedJson: unknown = undefined;
let jsonError: string | null = null;
$: if (isJson && fileContent !== null) {
try {
parsedJson = JSON.parse(fileContent);
jsonError = null;
} catch (e) {
parsedJson = undefined;
jsonError = e instanceof Error ? e.message : $i18n.t('Invalid JSON');
}
} else {
parsedJson = undefined;
jsonError = null;
}
// Notebook parsing
@@ -306,7 +224,7 @@
let panzoomRef: PanzoomContainer;
let pptxPreviewRef: PptxPreview;
let imageZoomLevel = 1;
$: svgPreview = isSvg && !showRaw && !editing && !searchTarget && !!fileContent;
$: svgPreview = isSvg && !showRaw && !searchTarget && !!fileContent;
export const resetImageView = () => {
panzoomRef?.reset();
pptxPreviewRef?.resetView();
@@ -419,11 +337,11 @@
className="w-full h-full"
/>
{:else if fileContent !== null}
{#if searchTarget}
{#if searchTarget || showRaw}
<div class="absolute inset-0">
<FileCodeEditor
{gitBaseContent}
{readOnly}
readOnly={readOnly || !onSave}
bind:this={fileCodeEditorRef}
bind:value={codeValue}
filePath={selectedFile}
@@ -463,17 +381,6 @@
class="w-full h-full border-none bg-white"
title={$i18n.t('HTML Preview')}
/>
{:else if isHtml && showRaw}
<div class="absolute inset-0">
<FileCodeEditor
{gitBaseContent}
{readOnly}
bind:this={fileCodeEditorRef}
bind:value={codeValue}
filePath={selectedFile}
onSave={readOnly ? null : saveCodeFile}
/>
</div>
{:else if isMarkdown && !showRaw && onSave && !readOnly}
{#key selectedFile}
<MarkdownFileEditor
@@ -500,17 +407,6 @@
{onLocalLink}
/>
{/key}
{:else if isMarkdown && showRaw}
<div class="absolute inset-0">
<FileCodeEditor
{gitBaseContent}
{readOnly}
bind:this={fileCodeEditorRef}
bind:value={codeValue}
filePath={selectedFile}
onSave={readOnly ? null : saveCodeFile}
/>
</div>
{:else if isCsv && !showRaw && csvRows.length > 0}
<div class="absolute inset-0 overflow-auto px-3 pb-3">
<table class="csv-table text-xs font-mono border-collapse">
@@ -552,14 +448,6 @@
<div class="overflow-auto h-full">
<JsonTreeView data={parsedJson} />
</div>
{:else if isJson && !showRaw && jsonError}
<div class="p-3 text-xs">
<div class="text-gray-500 dark:text-gray-400 mb-2">
{$i18n.t('JSON parse error: {{error}}', { error: jsonError })}
</div>
<pre
class="text-xs font-mono text-gray-800 dark:text-gray-200 whitespace-pre-wrap break-all leading-relaxed">{fileContent}</pre>
</div>
{:else if isSvg && !showRaw && fileContent}
{#key selectedFile}
<PanzoomContainer
@@ -571,32 +459,17 @@
{@html sanitizeSvg(fileContent)}
</PanzoomContainer>
{/key}
{:else if isCode && !showRaw}
{:else}
<div class="absolute inset-0">
<FileCodeEditor
{gitBaseContent}
{readOnly}
readOnly={readOnly || !onSave}
bind:this={fileCodeEditorRef}
bind:value={codeValue}
filePath={selectedFile}
onSave={readOnly ? null : saveCodeFile}
/>
</div>
{:else if isSvg && highlightedHtml && !showRaw}
<div class="shiki-preview overflow-auto h-full text-xs">
{@html highlightedHtml}
</div>
{:else if editing}
<textarea
aria-label={$i18n.t('File content')}
bind:this={editTextarea}
bind:value={editContent}
class="w-full h-full text-xs font-mono text-gray-800 dark:text-gray-200 whitespace-pre break-all leading-relaxed p-3 bg-transparent border-none outline-none resize-none"
spellcheck="false"
/>
{:else}
<pre
class="text-xs font-mono text-gray-800 dark:text-gray-200 whitespace-pre-wrap break-all leading-relaxed p-3">{fileContent}</pre>
{/if}
{:else}
<div class="text-xs text-gray-400 text-center pt-8">
@@ -737,45 +610,4 @@
padding-left: 1.5em;
margin: 0.5em 0;
}
/* Shiki code highlighting */
.shiki-preview :global(pre.shiki) {
margin: 0;
padding: 0.75rem 1rem;
font-size: 0.75rem;
line-height: 1.6;
border-radius: 0;
overflow-x: auto;
min-height: 100%;
}
.shiki-preview :global(pre.shiki code) {
counter-reset: line;
}
.shiki-preview :global(pre.shiki code > .line) {
counter-increment: line;
display: inline-block;
width: 100%;
white-space: pre;
}
.shiki-preview :global(pre.shiki code > .line::before) {
content: counter(line);
display: inline-block;
width: 2.5em;
text-align: right;
margin-right: 1em;
color: #9ca3af;
user-select: none;
font-size: 0.65rem;
}
:global(.dark) .shiki-preview :global(pre.shiki code > .line::before) {
color: #4b5563;
}
/* Shiki dual-theme: swap CSS variables in dark mode */
:global(.dark) .shiki-preview :global(.shiki),
:global(.dark) .shiki-preview :global(.shiki span) {
color: var(--shiki-dark) !important;
background-color: var(--shiki-dark-bg) !important;
font-style: var(--shiki-dark-font-style) !important;
font-weight: var(--shiki-dark-font-weight) !important;
text-decoration: var(--shiki-dark-text-decoration) !important;
}
</style>
@@ -198,7 +198,7 @@
</script>
<div
class="min-h-full"
class="file-markdown-editor min-h-full"
role="presentation"
on:paste|capture={attachImages}
on:drop|capture={attachImages}
@@ -248,3 +248,46 @@
<Spinner className="size-4" />
{/if}
</div>
<style>
.file-markdown-editor :global(.tiptap .hljs-keyword) {
color: #c678dd;
}
.file-markdown-editor :global(.tiptap .hljs-string) {
color: #98c379;
}
.file-markdown-editor :global(.tiptap .hljs-number) {
color: #d19a66;
}
.file-markdown-editor :global(.tiptap .hljs-comment) {
color: #5c6370;
font-style: italic;
}
.file-markdown-editor :global(.tiptap .hljs-function) {
color: #61afef;
}
.file-markdown-editor :global(.tiptap .hljs-title) {
color: #61afef;
}
.file-markdown-editor :global(.tiptap .hljs-built_in) {
color: #e5c07b;
}
.file-markdown-editor :global(.tiptap .hljs-attr) {
color: #d19a66;
}
.file-markdown-editor :global(.tiptap .hljs-tag) {
color: #e06c75;
}
.file-markdown-editor :global(.tiptap .hljs-name) {
color: #e06c75;
}
.file-markdown-editor :global(.tiptap .hljs-selector-class) {
color: #d19a66;
}
.file-markdown-editor :global(.tiptap .hljs-variable) {
color: #e06c75;
}
.file-markdown-editor :global(.tiptap .hljs-type) {
color: #e5c07b;
}
</style>
@@ -1,5 +1,6 @@
<script lang="ts">
import hljs from 'highlight.js';
import { highlightCodeBlock } from '$lib/utils/codeHighlight';
import { toast } from 'svelte-sonner';
import { getContext, onMount, tick, onDestroy } from 'svelte';
import type { Writable } from 'svelte/store';
@@ -67,7 +68,19 @@
let renderHTML = null;
let renderError: { type: 'diagram' | 'visualization'; detail: string } | null = null;
let highlightedCode = null;
let highlightedCode: string | null = null;
let highlightGeneration = 0;
async function highlightDocument(code: string, language: string) {
const generation = ++highlightGeneration;
highlightedCode = null;
try {
const html = await highlightCodeBlock(code, language);
if (generation === highlightGeneration) highlightedCode = html;
} catch {
// Keep the escaped source visible if a grammar cannot be loaded.
}
}
$: if (markdown?.document && !edit && !isDiff) void highlightDocument(code, lang);
let executing = false;
let stdout = null;
@@ -436,6 +449,7 @@
});
onDestroy(() => {
highlightGeneration++;
if (localPyodideWorker) {
localPyodideWorker.terminate();
localPyodideWorker = null;
@@ -583,6 +597,14 @@
_code = value;
}}
/>
{:else if markdown?.document}
<div class="document-code">
{#if highlightedCode}
{@html highlightedCode}
{:else}
<pre><code>{code}</code></pre>
{/if}
</div>
{:else}
<pre
class=" hljs p-4 px-5 overflow-x-auto"
@@ -663,3 +685,26 @@
{/if}
</div>
</div>
<style>
.document-code :global(pre) {
margin: 0;
padding: 0.75rem 1rem;
overflow-x: auto;
font-size: 0.8125rem;
line-height: normal;
background: transparent !important;
}
.document-code :global(code) {
font-family: 'JetBrains Mono', 'Fira Code', ui-monospace, monospace;
font-size: inherit;
white-space: pre;
}
:global(.dark) .document-code :global(.shiki),
:global(.dark) .document-code :global(.shiki span) {
color: var(--shiki-dark) !important;
font-style: var(--shiki-dark-font-style) !important;
font-weight: var(--shiki-dark-font-weight) !important;
text-decoration: var(--shiki-dark-text-decoration) !important;
}
</style>
+7 -2
View File
@@ -183,9 +183,14 @@ export function isCodeFile(path: string | null): boolean {
* async, callers are completely unaffected by the change.
*/
export async function highlightCode(code: string, filePath: string): Promise<string> {
const lang = languageForFilePath(filePath) ?? 'text';
return highlightCodeBlock(code, languageForFilePath(filePath) ?? 'text');
}
const { codeToHtml } = await import('shiki');
/** Highlight a Markdown fence, falling back to plain text for unknown language tags. */
export async function highlightCodeBlock(code: string, language: string): Promise<string> {
const { codeToHtml, bundledLanguages } = await import('shiki');
const name = language.trim().toLowerCase();
const lang = Object.hasOwn(bundledLanguages, name) ? name : 'text';
return await codeToHtml(code, {
lang,
themes: {