Files
open-webui/src/lib/components/chat/Messages/CodeBlock.svelte
T
Classic298 da69677528 fix: screen readers do not announce selected or expanded state in chat messages (#35338)
After a thumbs up or down, the "How would you rate this response?" panel did not tell screen readers which score or reason was selected. The task list collapse button and the code block Collapse button also did not say whether they were open, and the task list button was read in English regardless of the interface language. Screen readers now hear the selected score and reason, the open or closed state of both buttons, and a translated task list label.

Fixes #35337
2026-11-30 18:26:08 +04:00

714 lines
20 KiB
Svelte

<script lang="ts">
import { highlightCodeBlock } from '$lib/utils/codeHighlight';
import { toast } from 'svelte-sonner';
import { getContext, onMount, tick, onDestroy } from 'svelte';
import type { Writable } from 'svelte/store';
import type { i18n as i18nType } from 'i18next';
import { config, pyodideWorker as pyodideWorkerStore, visibleControls } from '$lib/stores';
import { createPyodideWorker } from '$lib/pyodide/createPyodideWorker';
import { executeCode } from '$lib/apis/utils';
import {
copyToClipboard,
initMermaid,
renderMermaidDiagram,
renderVegaVisualization,
unescapeHtml
} from '$lib/utils';
import 'highlight.js/styles/github-dark.min.css';
import equal from 'fast-deep-equal';
import CodeEditor from '$lib/components/common/CodeEditor.svelte';
import DiffBlock from './DiffBlock.svelte';
import SvgPanZoom from '$lib/components/common/SVGPanZoom.svelte';
import ChevronUp from '$lib/components/icons/ChevronUp.svelte';
import ChevronUpDown from '$lib/components/icons/ChevronUpDown.svelte';
import CommandLine from '$lib/components/icons/CommandLine.svelte';
import Cube from '$lib/components/icons/Cube.svelte';
import Tooltip from '$lib/components/common/Tooltip.svelte';
const i18n = getContext<Writable<i18nType>>('i18n');
const markdown = getContext<{ allowRemoteContent: boolean; document?: boolean } | undefined>(
'markdown'
);
export let id = '';
export let edit = true;
export let onSave = (e) => {};
export let onUpdate = (e, codeBlockId = '') => {};
export let onPreview = (e) => {};
export let save = false;
export let run = true;
export let preview = false;
export let collapsed = false;
export let token;
export let lang = '';
export let code = '';
export let attributes = {};
export let className = '';
export let editorClassName = '';
export let stickyButtonsClassName = 'top-0';
let localPyodideWorker = null;
let _code = '';
$: _code = code;
$: isDiff = ['diff', 'patch'].includes(lang.trim().toLowerCase());
let editingDiff = false;
let _token = null;
let renderHTML = null;
let renderError: { type: 'diagram' | 'visualization'; detail: string } | null = 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;
let stderr = null;
let result = null;
let files = null;
let copied = false;
let saved = false;
const collapseCodeBlock = () => {
collapsed = !collapsed;
};
const saveCode = () => {
saved = true;
code = _code;
onSave(code);
setTimeout(() => {
saved = false;
}, 1000);
};
const copyCode = async () => {
copied = true;
await copyToClipboard(_code);
setTimeout(() => {
copied = false;
}, 1000);
};
const previewCode = () => {
onPreview(code);
};
const checkPythonCode = (str) => {
// Check if the string contains typical Python syntax characters
const pythonSyntax = [
'def ',
'else:',
'elif ',
'try:',
'except:',
'finally:',
'yield ',
'lambda ',
'assert ',
'nonlocal ',
'del ',
'True',
'False',
'None',
' and ',
' or ',
' not ',
' in ',
' is ',
' with '
];
for (let syntax of pythonSyntax) {
if (str.includes(syntax)) {
return true;
}
}
// If none of the above conditions met, it's probably not Python code
return false;
};
const executePython = async (code) => {
result = null;
stdout = null;
stderr = null;
files = null;
executing = true;
if ($config?.code?.engine === 'jupyter') {
const output = await executeCode(localStorage.token, code).catch((error) => {
toast.error(`${error}`);
return null;
});
if (output) {
if (output['stdout']) {
stdout = output['stdout'];
const stdoutLines = stdout.split('\n');
for (const [idx, line] of stdoutLines.entries()) {
if (line.startsWith('data:image/png;base64')) {
if (files) {
files.push({
type: 'image/png',
data: line
});
} else {
files = [
{
type: 'image/png',
data: line
}
];
}
if (stdout.includes(`${line}\n`)) {
stdout = stdout.replace(`${line}\n`, ``);
} else if (stdout.includes(`${line}`)) {
stdout = stdout.replace(`${line}`, ``);
}
}
}
}
if (output['result']) {
result = output['result'];
const resultLines = result.split('\n');
for (const [idx, line] of resultLines.entries()) {
if (line.startsWith('data:image/png;base64')) {
if (files) {
files.push({
type: 'image/png',
data: line
});
} else {
files = [
{
type: 'image/png',
data: line
}
];
}
if (result.includes(`${line}\n`)) {
result = result.replace(`${line}\n`, ``);
} else if (result.includes(`${line}`)) {
result = result.replace(`${line}`, ``);
}
}
}
}
output['stderr'] && (stderr = output['stderr']);
}
executing = false;
} else {
executePythonAsWorker(code);
}
};
const executePythonAsWorker = async (code) => {
let packages = [
/\bimport\s+requests\b|\bfrom\s+requests\b/.test(code) ? 'requests' : null,
/\bimport\s+bs4\b|\bfrom\s+bs4\b/.test(code) ? 'beautifulsoup4' : null,
/\bimport\s+numpy\b|\bfrom\s+numpy\b/.test(code) ? 'numpy' : null,
/\bimport\s+pandas\b|\bfrom\s+pandas\b/.test(code) ? 'pandas' : null,
/\bimport\s+matplotlib\b|\bfrom\s+matplotlib\b/.test(code) ? 'matplotlib' : null,
/\bimport\s+seaborn\b|\bfrom\s+seaborn\b/.test(code) ? 'seaborn' : null,
/\bimport\s+sklearn\b|\bfrom\s+sklearn\b/.test(code) ? 'scikit-learn' : null,
/\bimport\s+scipy\b|\bfrom\s+scipy\b/.test(code) ? 'scipy' : null,
/\bimport\s+re\b|\bfrom\s+re\b/.test(code) ? 'regex' : null,
/\bimport\s+seaborn\b|\bfrom\s+seaborn\b/.test(code) ? 'seaborn' : null,
/\bimport\s+sympy\b|\bfrom\s+sympy\b/.test(code) ? 'sympy' : null,
/\bimport\s+tiktoken\b|\bfrom\s+tiktoken\b/.test(code) ? 'tiktoken' : null,
/\bimport\s+pytz\b|\bfrom\s+pytz\b/.test(code) ? 'pytz' : null,
/\bimport\s+openpyxl\b|\bfrom\s+openpyxl\b/.test(code) ? 'openpyxl' : null,
/\.(read|to)_excel\(|\.Excel(Writer|File)\(/.test(code) ? 'openpyxl' : null,
/\bimport\s+pptx\b|\bfrom\s+pptx\b/.test(code) ? 'python-pptx' : null,
/\bimport\s+docx\b|\bfrom\s+docx\b/.test(code) ? 'python-docx' : null
].filter(Boolean);
console.log(packages);
// Reuse the shared Pyodide worker when code interpreter is active,
// so files written here are immediately visible in PyodideFileNav.
// Otherwise fall back to a throwaway worker.
const sharedWorker = $pyodideWorkerStore;
const isShared = !!sharedWorker;
const worker = sharedWorker ?? createPyodideWorker();
if (!isShared) {
localPyodideWorker = worker;
}
worker.postMessage({
id: id,
code: code,
packages: packages
});
const timeoutId = setTimeout(() => {
if (executing) {
executing = false;
stderr = 'Execution Time Limit Exceeded';
if (!isShared) {
worker.terminate();
localPyodideWorker = null;
}
}
}, 60000);
const handler = (event) => {
// Ignore messages from other requests on the shared worker
if (event.data?.id !== id) return;
console.log('pyodideWorker.onmessage', event);
const { id: _id, ...data } = event.data;
console.log(_id, data);
if (data['stdout']) {
stdout = data['stdout'];
const stdoutLines = stdout.split('\n');
for (const [idx, line] of stdoutLines.entries()) {
if (line.startsWith('data:image/png;base64')) {
if (files) {
files.push({
type: 'image/png',
data: line
});
} else {
files = [
{
type: 'image/png',
data: line
}
];
}
if (stdout.includes(`${line}\n`)) {
stdout = stdout.replace(`${line}\n`, ``);
} else if (stdout.includes(`${line}`)) {
stdout = stdout.replace(`${line}`, ``);
}
}
}
}
if (typeof data['result'] === 'string') {
result = data['result'];
const resultLines = result.split('\n');
for (const [idx, line] of resultLines.entries()) {
if (line.startsWith('data:image/png;base64')) {
if (files) {
files.push({
type: 'image/png',
data: line
});
} else {
files = [
{
type: 'image/png',
data: line
}
];
}
if (result.startsWith(`${line}\n`)) {
result = result.replace(`${line}\n`, ``);
} else if (result.startsWith(`${line}`)) {
result = result.replace(`${line}`, ``);
}
}
}
}
data['stderr'] && (stderr = data['stderr']);
data['result'] && (result = data['result']);
clearTimeout(timeoutId);
worker.removeEventListener('message', handler);
executing = false;
// Signal PyodideFileNav to auto-refresh after execution
window.dispatchEvent(new Event('pyodide:files'));
};
worker.addEventListener('message', handler);
worker.onerror = (event) => {
console.log('pyodideWorker.onerror', event);
clearTimeout(timeoutId);
worker.removeEventListener('message', handler);
executing = false;
};
};
let mermaid = null;
const renderMermaid = async (code) => {
if (!mermaid) {
mermaid = await initMermaid();
}
return await renderMermaidDiagram(mermaid, code);
};
const render = async () => {
onUpdate(token, id);
if (markdown?.allowRemoteContent === false) return;
if (
lang === 'mermaid' &&
(markdown?.document || (token?.raw ?? '').slice(-4).includes('```'))
) {
try {
renderHTML = await renderMermaid(code);
} catch (error) {
console.error('Failed to render mermaid diagram:', error);
const errorMsg = error instanceof Error ? error.message : String(error);
renderError = { type: 'diagram', detail: errorMsg };
renderHTML = null;
}
} else if (
(lang === 'vega' || lang === 'vega-lite') &&
(markdown?.document || (token?.raw ?? '').slice(-4).includes('```'))
) {
try {
renderHTML = await renderVegaVisualization(code, lang);
} catch (error) {
console.error('Failed to render Vega visualization:', error);
const errorMsg = error instanceof Error ? error.message : String(error);
renderError = { type: 'visualization', detail: errorMsg };
renderHTML = null;
}
}
};
$: if (token) {
if (token.text !== _token?.text || token.raw !== _token?.raw) {
_token = token;
} else if (!equal(token, _token)) {
_token = token;
}
}
$: if (_token) {
render();
}
$: if (attributes) {
onAttributesUpdate();
}
const onAttributesUpdate = () => {
if (attributes?.output) {
try {
const output = JSON.parse(unescapeHtml(attributes.output));
stdout = output.stdout;
stderr = output.stderr;
result = output.result;
} catch (error) {
console.error('Error:', error);
}
}
};
onMount(async () => {
if (token) {
onUpdate(token, id);
}
});
onDestroy(() => {
highlightGeneration++;
if (localPyodideWorker) {
localPyodideWorker.terminate();
localPyodideWorker = null;
}
});
</script>
<div>
<div
class="relative {className} flex flex-col rounded-2xl border border-base-100/30 dark:border-base-850/30 my-0.5 overflow-clip"
dir="ltr"
>
{#if markdown?.allowRemoteContent !== false && ['mermaid', 'vega', 'vega-lite'].includes(lang)}
{#if renderHTML}
<SvgPanZoom
className=" rounded-2xl max-h-fit overflow-hidden"
svg={renderHTML}
content={_token.text}
/>
{:else}
<div class="p-3">
{#if renderError}
<div
class="flex gap-2.5 border px-4 py-3 border-red-600/10 bg-red-600/10 rounded-2xl mb-2"
>
{renderError.type === 'diagram'
? $i18n.t('Failed to render diagram')
: $i18n.t('Failed to render visualization')}: {renderError.detail}
</div>
{/if}
<pre>{code}</pre>
</div>
{/if}
{:else}
<div
class="sticky {stickyButtonsClassName} left-0 right-0 py-0.5 px-3.5 gap-2 flex items-center justify-end w-full z-10 text-xs text-base-1000 dark:text-base-0 bg-base-0 dark:bg-base-1000"
>
<div class="flex-1 truncate">
<Tooltip content={lang} placement="top-start">
<span class=" truncate text-ellipsis">
{lang}
</span>
</Tooltip>
</div>
<div class="buttons flex max-w-full items-center gap-0.5 shrink-0 overflow-x-auto">
{#if isDiff && edit}
<button
class="flex h-6 shrink-0 items-center justify-center gap-1.5 rounded-lg px-2 text-xs font-normal text-base-600 transition-colors duration-100 hover:bg-base-100/40 disabled:opacity-60 dark:text-base-400 dark:hover:bg-base-0/5"
aria-pressed={editingDiff}
on:click={() => {
editingDiff = !editingDiff;
collapsed = false;
}}
>
{editingDiff ? $i18n.t('Done') : $i18n.t('Edit')}
</button>
{/if}
<button
class="flex h-6 shrink-0 items-center justify-center gap-1.5 rounded-lg px-2 text-xs font-normal text-base-600 transition-colors duration-100 hover:bg-base-100/40 disabled:opacity-60 dark:text-base-400 dark:hover:bg-base-0/5"
aria-expanded={!collapsed}
on:click={collapseCodeBlock}
>
<div class=" -translate-y-[0.5px]">
<ChevronUpDown className="size-3" />
</div>
<div>
{collapsed ? $i18n.t('Expand') : $i18n.t('Collapse')}
</div>
</button>
{#if ($config?.features?.enable_code_execution ?? true) && (lang.toLowerCase() === 'python' || lang.toLowerCase() === 'py' || (lang === '' && checkPythonCode(code)))}
{#if executing}
<div
class="run-code-button flex h-6 shrink-0 items-center justify-center gap-1.5 rounded-lg px-2 text-xs font-normal text-base-600 transition-colors duration-100 hover:bg-base-100/40 disabled:opacity-60 dark:text-base-400 dark:hover:bg-base-0/5 cursor-not-allowed opacity-60"
>
{$i18n.t('Running')}
</div>
{:else if run && markdown?.allowRemoteContent !== false}
<button
class="run-code-button flex h-6 shrink-0 items-center justify-center gap-1.5 rounded-lg px-2 text-xs font-normal text-base-600 transition-colors duration-100 hover:bg-base-100/40 disabled:opacity-60 dark:text-base-400 dark:hover:bg-base-0/5"
on:click={async () => {
code = _code;
await tick();
executePython(code);
}}
>
<div>
{$i18n.t('Run')}
</div>
</button>
{/if}
{/if}
{#if save}
<button
class="save-code-button flex h-6 shrink-0 items-center justify-center gap-1.5 rounded-lg px-2 text-xs font-normal text-base-600 transition-colors duration-100 hover:bg-base-100/40 disabled:opacity-60 dark:text-base-400 dark:hover:bg-base-0/5"
on:click={saveCode}
>
{saved ? $i18n.t('Saved') : $i18n.t('Save')}
</button>
{/if}
<button
class="copy-code-button flex h-6 shrink-0 items-center justify-center gap-1.5 rounded-lg px-2 text-xs font-normal text-base-600 transition-colors duration-100 hover:bg-base-100/40 disabled:opacity-60 dark:text-base-400 dark:hover:bg-base-0/5"
on:click={copyCode}>{copied ? $i18n.t('Copied') : $i18n.t('Copy')}</button
>
{#if preview && ['html', 'svg'].includes(lang) && $visibleControls['chat.code_preview']}
<button
class="run-code-button flex h-6 shrink-0 items-center justify-center gap-1.5 rounded-lg px-2 text-xs font-normal text-base-600 transition-colors duration-100 hover:bg-base-100/40 disabled:opacity-60 dark:text-base-400 dark:hover:bg-base-0/5"
on:click={previewCode}
>
<div>
{$i18n.t('Preview')}
</div>
</button>
{/if}
</div>
</div>
<div
class="language-{lang} rounded-t-2xl -mt-8 {editorClassName
? editorClassName
: executing || stdout || stderr || result
? ''
: 'rounded-b-2xl'} overflow-hidden"
>
<div class=" pt-6.5 bg-base-0 dark:bg-base-1000"></div>
{#if !collapsed}
{#if isDiff && !(edit && editingDiff)}
<DiffBlock code={_code} />
{:else if edit || markdown?.allowRemoteContent === false}
<CodeEditor
value={_code}
readOnly={!edit}
{id}
ariaLabel={$i18n.t('Code Editor')}
{lang}
onSave={() => {
saveCode();
}}
onChange={(value) => {
_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"
style="border-top-left-radius: 0px; border-top-right-radius: 0px; {(executing ||
stdout ||
stderr ||
result) &&
'border-bottom-left-radius: 0px; border-bottom-right-radius: 0px;'}"><code
class="language-{lang} rounded-t-none whitespace-pre text-sm"
>{#await import('highlight.js')}{code}{:then { default: hljs }}{#if lang && hljs.getLanguage(lang)}{@html hljs.highlight(
code,
{
language: lang,
ignoreIllegals: true
}
).value}{:else}{code}{/if}{:catch}{code}{/await}</code
></pre>
{/if}
{:else}
<div
class="bg-base-0 dark:bg-base-1000 dark:text-base-0 rounded-b-2xl! pt-1 pb-2 px-4 flex flex-col gap-2 text-xs"
>
<span class="text-base-500 italic">
{$i18n.t('{{COUNT}} hidden lines', {
COUNT: (isDiff ? _code : code).split('\n').length
})}
</span>
</div>
{/if}
</div>
{#if !collapsed}
<div
id="plt-canvas-{id}"
class="bg-base-50 dark:bg-base-1000 dark:text-base-0 max-w-full overflow-x-auto scrollbar-hidden"
/>
{#if executing || stdout || stderr || result || files}
<div
class="bg-base-50 dark:bg-base-1000 dark:text-base-0 rounded-b-2xl! pt-2 pb-3 px-3.5 flex flex-col gap-2"
>
{#if executing}
<div class=" ">
<div class=" text-base-500 text-xs mb-1">{$i18n.t('STDOUT/STDERR')}</div>
<div class="text-sm">{$i18n.t('Running...')}</div>
</div>
{:else}
{#if stdout || stderr}
<div class=" ">
<div class=" text-base-500 text-xs mb-1">{$i18n.t('STDOUT/STDERR')}</div>
<div
class="text-sm font-mono whitespace-pre-wrap {stdout?.split('\n')?.length > 100
? `max-h-96`
: ''} overflow-y-auto"
>
{`${stdout ?? ''}${stderr ?? ''}`}
</div>
</div>
{/if}
{#if result || files}
<div class=" ">
<div class=" text-base-500 text-xs mb-1">{$i18n.t('RESULT')}</div>
{#if result}
<div class="text-sm">{`${JSON.stringify(result)}`}</div>
{/if}
{#if files}
<div class="flex flex-col gap-2">
{#each files as file}
{#if file.type.startsWith('image')}
<img src={file.data} alt="Output" class=" w-full max-w-[36rem]" />
{/if}
{/each}
</div>
{/if}
</div>
{/if}
{/if}
</div>
{/if}
{/if}
{/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>