Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/renderer/components/NotebookCell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type { AppConfig } from '../../shared/types'
import {
isNotebookCellCollapsed,
notebookCellSourcePreview,
resolveMarkdownAttachments,
type NotebookCell,
type NotebookCellType
} from '../../shared/notebook'
Expand Down Expand Up @@ -430,7 +431,7 @@ export default function NotebookCellView({
{cell.source.trim()
? (
<MarkdownPreview
content={cell.source}
content={resolveMarkdownAttachments(cell.source, cell.extra?.attachments)}
effectiveTheme={effectiveTheme}
variant="notebook"
fontSize={config.editorFontSize}
Expand Down
31 changes: 18 additions & 13 deletions src/renderer/components/NotebookOutputs.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import React from 'react'
import DOMPurify from 'dompurify'
import MarkdownPreview from './MarkdownPreview'
import {
mimePlainText,
mimePng,
notebookOutputDisplay,
NOTEBOOK_PNG_OMITTED,
NOTEBOOK_TRUNCATED_MARKER,
type NotebookOutput
Expand Down Expand Up @@ -55,20 +56,24 @@ function OutputBlock({ output }: { output: NotebookOutput }): React.ReactElement
}

if (output.type === 'execute_result' || output.type === 'display_data') {
const png = mimePng(output.data)
const text = mimePlainText(output.data)
const truncated = (text != null && looksTruncated(text)) || Object.values(output.data).some(looksTruncated)
const display = notebookOutputDisplay(output.data, output.jsonData)
if (!display) return null
const truncated = Object.values(output.data).some(looksTruncated)
const pre = 'm-0 text-[12px] leading-snug font-mono whitespace-pre-wrap break-words'
return (
<div className="px-3 py-1.5">
{png && (
<img
alt=""
src={`data:image/png;base64,${png.replace(/\s/g, '')}`}
className="max-w-full h-auto"
/>
{display.kind === 'image' && <img alt="" src={display.src} className="max-w-full h-auto" />}
{display.kind === 'text' && <pre className={pre}>{display.text}</pre>}
{display.kind === 'json' && <pre className={pre}>{display.text}</pre>}
{display.kind === 'html' && (
// Kernel HTML is sanitized (no scripts, no event handlers) before it is shown.
<div className="note-preview text-sm overflow-x-auto" dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(display.html) }} />
)}
{!png && text && (
<pre className="m-0 text-[12px] leading-snug font-mono whitespace-pre-wrap break-words">{text}</pre>
{display.kind === 'markdown' && (
<MarkdownPreview content={display.markdown} effectiveTheme="dark" variant="flow" />
)}
{display.kind === 'unsupported' && (
<div className="text-2xs text-text-muted italic">Output not shown here: {display.mimeTypes.join(', ')}</div>
)}
{truncated && <TruncationNote />}
</div>
Expand Down
63 changes: 63 additions & 0 deletions src/shared/notebook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -708,6 +708,12 @@ export function truncateMimeBundle(data: Record<string, unknown>): Record<string
const out: Record<string, unknown> = {}
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
Expand Down Expand Up @@ -936,3 +942,60 @@ export function storedCellIds(text: string): Set<string> {
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<string, string>,
jsonData?: Record<string, unknown>
): 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:<name>`; 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, '')}`
})
}
101 changes: 101 additions & 0 deletions tests/notebook-rich-output.test.tsx
Original file line number Diff line number Diff line change
@@ -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': '<b>x</b>', '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': '<svg/>' })?.kind).toBe('image')
expect(notebookOutputDisplay({ 'text/html': '<b>x</b>' })).toEqual({ kind: 'html', html: '<b>x</b>' })
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<NotebookOutput, { type: 'display_data' }>
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(<NotebookOutputs outputs={outputs} />)
expect(container.textContent).toContain('"message": "survives"')
})

it('sanitizes HTML output', () => {
const outputs: NotebookOutput[] = [{
type: 'display_data',
data: { 'text/html': '<table><tr><td>cell</td></tr></table><script>window.__bad = 1</script><img src=x onerror="window.__bad=1">' }
}]
const { container } = render(<NotebookOutputs outputs={outputs} />)
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(<MarkdownPreview content={content} effectiveTheme="dark" variant="notebook" />)
expect(container.querySelector('img')?.getAttribute('src')).toBe(`data:image/png;base64,${PNG}`)
})
})
Loading