diff --git a/src/renderer/components/NotebookCell.tsx b/src/renderer/components/NotebookCell.tsx index 1d427830..f5e6ee0e 100644 --- a/src/renderer/components/NotebookCell.tsx +++ b/src/renderer/components/NotebookCell.tsx @@ -6,6 +6,7 @@ import type { AppConfig } from '../../shared/types' import { isNotebookCellCollapsed, notebookCellSourcePreview, + resolveMarkdownAttachments, type NotebookCell, type NotebookCellType } from '../../shared/notebook' @@ -430,7 +431,7 @@ export default function NotebookCellView({ {cell.source.trim() ? ( - {png && ( - + {display.kind === 'image' && } + {display.kind === 'text' &&
{display.text}
} + {display.kind === 'json' &&
{display.text}
} + {display.kind === 'html' && ( + // Kernel HTML is sanitized (no scripts, no event handlers) before it is shown. +
)} - {!png && text && ( -
{text}
+ {display.kind === 'markdown' && ( + + )} + {display.kind === 'unsupported' && ( +
Output not shown here: {display.mimeTypes.join(', ')}
)} {truncated && }
diff --git a/src/shared/notebook.ts b/src/shared/notebook.ts index b70e2317..5ef50d48 100644 --- a/src/shared/notebook.ts +++ b/src/shared/notebook.ts @@ -708,6 +708,12 @@ export function truncateMimeBundle(data: Record): Record = {} let omittedPng = false for (const [key, value] of Object.entries(data)) { + // JSON mime values are objects, not text: keep them (the kernel helper already + // drops oversized ones). Turning them into text here made them "". + if (isJsonMimeType(key)) { + out[key] = value + continue + } const text = typeof value === 'string' ? value : joinNotebookText(value) if (key === 'image/png' && text.length > NOTEBOOK_MIME_CHAR_LIMIT) { omittedPng = true @@ -936,3 +942,60 @@ export function storedCellIds(text: string): Set { return new Set() } } + +/** + * What an `execute_result` / `display_data` output shows. Earlier entries win, + * keeping the long-standing PNG-then-plain-text order for the common outputs + * (a pandas frame keeps its text form); richer forms are used when nothing + * simpler is there, and anything left is named so a cell never looks empty. + */ +export type NotebookDisplay = + | { kind: 'image'; src: string } + | { kind: 'text'; text: string } + | { kind: 'html'; html: string } + | { kind: 'markdown'; markdown: string } + | { kind: 'json'; text: string } + | { kind: 'unsupported'; mimeTypes: string[] } + +export function notebookOutputDisplay( + data: Record, + jsonData?: Record +): NotebookDisplay | null { + const png = mimePng(data) + if (png) return { kind: 'image', src: `data:image/png;base64,${png.replace(/\s/g, '')}` } + const jpeg = data['image/jpeg'] + if (jpeg) return { kind: 'image', src: `data:image/jpeg;base64,${jpeg.replace(/\s/g, '')}` } + const svg = data['image/svg+xml'] + if (svg) return { kind: 'image', src: `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}` } + const plain = mimePlainText(data) + if (plain) return { kind: 'text', text: plain } + if (data['text/html']) return { kind: 'html', html: data['text/html'] } + if (data['text/markdown']) return { kind: 'markdown', markdown: data['text/markdown'] } + const jsonKey = Object.keys(jsonData ?? {}).find(isJsonMimeType) + if (jsonKey) return { kind: 'json', text: JSON.stringify(jsonData![jsonKey], null, 2) } + const mimeTypes = [...Object.keys(data), ...Object.keys(jsonData ?? {})].filter((m) => m !== 'text/plain') + return mimeTypes.length > 0 ? { kind: 'unsupported', mimeTypes } : null +} + +/** + * Markdown cells reference pasted images as `attachment:`; the bytes live + * in the cell's `attachments` (`{ name: { "image/png": base64 } }`). Rewrite + * those references to data URLs so the preview can show them. Unknown names + * are left alone. + */ +export function resolveMarkdownAttachments(source: string, attachments: unknown): string { + const record = asRecord(attachments) + if (!record) return source + return source.replace(/attachment:([^\s)"'<>]+)/g, (match, rawName: string) => { + let name = rawName + try { name = decodeURIComponent(rawName) } catch { /* keep raw */ } + const bundle = asRecord(record[name] ?? record[rawName]) + if (!bundle) return match + const mime = Object.keys(bundle).find((key) => key.startsWith('image/')) + const value = mime ? bundle[mime] : undefined + const base64 = typeof value === 'string' ? value : Array.isArray(value) ? value.join('') : null + if (!mime || !base64) return match + if (mime === 'image/svg+xml') return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(base64)}` + return `data:${mime};base64,${base64.replace(/\s/g, '')}` + }) +} diff --git a/tests/notebook-rich-output.test.tsx b/tests/notebook-rich-output.test.tsx new file mode 100644 index 00000000..b4ca3d3c --- /dev/null +++ b/tests/notebook-rich-output.test.tsx @@ -0,0 +1,101 @@ +// @vitest-environment jsdom +import { afterEach, describe, expect, it } from 'vitest' +import React from 'react' +import { cleanup, render } from '@testing-library/react' +import NotebookOutputs from '../src/renderer/components/NotebookOutputs' +import MarkdownPreview from '../src/renderer/components/MarkdownPreview' +import { applyKernelEventToOutputs, notebookOutputDisplay, parseKernelEventLine, resolveMarkdownAttachments, type NotebookOutput } from '../src/shared/notebook' + +void React + +afterEach(() => cleanup()) + +const PNG = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==' + +describe('notebookOutputDisplay', () => { + it('keeps PNG, then plain text, first', () => { + expect(notebookOutputDisplay({ 'image/png': PNG, 'text/plain': 'x' })).toMatchObject({ kind: 'image' }) + expect(notebookOutputDisplay({ 'text/html': 'x', 'text/plain': 'x' })).toEqual({ kind: 'text', text: 'x' }) + }) + + it('shows JSON-only output (display(..., raw=True)) pretty-printed', () => { + expect(notebookOutputDisplay({}, { 'application/json': { a: 1 } })).toEqual({ kind: 'json', text: '{\n "a": 1\n}' }) + }) + + it('uses JPEG, SVG, HTML and markdown when nothing simpler is there', () => { + expect(notebookOutputDisplay({ 'image/jpeg': 'abc' })).toEqual({ kind: 'image', src: 'data:image/jpeg;base64,abc' }) + expect(notebookOutputDisplay({ 'image/svg+xml': '' })?.kind).toBe('image') + expect(notebookOutputDisplay({ 'text/html': 'x' })).toEqual({ kind: 'html', html: 'x' }) + expect(notebookOutputDisplay({ 'text/markdown': '# x' })).toEqual({ kind: 'markdown', markdown: '# x' }) + }) + + it('names what it cannot show instead of showing nothing', () => { + expect(notebookOutputDisplay({ 'application/vnd.custom': 'z' })).toEqual({ kind: 'unsupported', mimeTypes: ['application/vnd.custom'] }) + expect(notebookOutputDisplay({})).toBeNull() + }) +}) + +describe('live kernel output path', () => { + it('keeps a JSON-only display_data object through parsing and into the cell outputs', () => { + const line = JSON.stringify({ + event: 'display_data', + id: 'req-1', + data: { 'application/json': { a: 1, message: 'This rich output should survive save/reopen.' } } + }) + const event = parseKernelEventLine(line) + expect(event).toMatchObject({ event: 'display_data', data: { 'application/json': { a: 1 } } }) + const outputs = applyKernelEventToOutputs([], event!)! + const out = outputs[0] as Extract + expect(notebookOutputDisplay(out.data, out.jsonData)).toMatchObject({ kind: 'json' }) + expect((notebookOutputDisplay(out.data, out.jsonData) as { text: string }).text).toContain('"message"') + }) +}) + +describe('NotebookOutputs rendering', () => { + it('renders a JSON-only display_data output', () => { + const outputs: NotebookOutput[] = [{ + type: 'display_data', + data: {}, + jsonData: { 'application/json': { a: 1, message: 'survives' } } + }] + const { container } = render() + expect(container.textContent).toContain('"message": "survives"') + }) + + it('sanitizes HTML output', () => { + const outputs: NotebookOutput[] = [{ + type: 'display_data', + data: { 'text/html': '
cell
' } + }] + const { container } = render() + expect(container.querySelector('td')?.textContent).toBe('cell') + expect(container.querySelector('script')).toBeNull() + expect(container.querySelector('img')?.getAttribute('onerror')).toBeNull() + }) +}) + +describe('markdown attachments', () => { + const attachments = { 'checker.png': { 'image/png': PNG } } + + it('rewrites attachment: references to data URLs', () => { + expect(resolveMarkdownAttachments('![alt](attachment:checker.png)', attachments)) + .toBe(`![alt](data:image/png;base64,${PNG})`) + }) + + it('leaves unknown attachments and plain text alone', () => { + expect(resolveMarkdownAttachments('![a](attachment:missing.png) attachment', attachments)) + .toBe('![a](attachment:missing.png) attachment') + expect(resolveMarkdownAttachments('![a](attachment:x.png)', undefined)).toBe('![a](attachment:x.png)') + }) + + it('handles URL-encoded names', () => { + const named = { 'my image.png': { 'image/png': PNG } } + expect(resolveMarkdownAttachments('![a](attachment:my%20image.png)', named)).toContain('data:image/png;base64,') + }) + + it('survives the markdown preview sanitizer as a data: image', () => { + const content = resolveMarkdownAttachments('![Checkerboard](attachment:checker.png)', attachments) + const { container } = render() + expect(container.querySelector('img')?.getAttribute('src')).toBe(`data:image/png;base64,${PNG}`) + }) +})