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
2 changes: 1 addition & 1 deletion src/renderer/components/NotebookCell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,7 @@ export default function NotebookCellView({
)
)}

{cell.cellType === 'code' && <NotebookOutputs outputs={cell.outputs} />}
{cell.cellType === 'code' && <NotebookOutputs outputs={cell.outputs} effectiveTheme={effectiveTheme} />}
</div>
)
}
25 changes: 19 additions & 6 deletions src/renderer/components/NotebookOutputs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,17 @@ function TruncationNote(): React.ReactElement {
)
}

function OutputBlock({ output }: { output: NotebookOutput }): React.ReactElement | null {
// Kernel HTML is sanitized (no scripts, no event handlers) and may not carry CSS:
// a <style> block or inline `position: fixed` would restyle or cover the app.
const KERNEL_HTML_SANITIZE = { FORBID_TAGS: ['style'], FORBID_ATTR: ['style'] }

function OutputBlock({
output,
effectiveTheme
}: {
output: NotebookOutput
effectiveTheme: 'dark' | 'light'
}): React.ReactElement | null {
if (output.type === 'stream') {
const color = output.name === 'stderr' ? 'var(--color-danger)' : undefined
return (
Expand Down Expand Up @@ -66,11 +76,13 @@ function OutputBlock({ output }: { output: NotebookOutput }): React.ReactElement
{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) }} />
<div
className="note-preview text-sm overflow-x-auto"
dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(display.html, KERNEL_HTML_SANITIZE) }}
/>
)}
{display.kind === 'markdown' && (
<MarkdownPreview content={display.markdown} effectiveTheme="dark" variant="flow" />
<MarkdownPreview content={display.markdown} effectiveTheme={effectiveTheme} variant="flow" />
)}
{display.kind === 'unsupported' && (
<div className="text-2xs text-text-muted italic">Output not shown here: {display.mimeTypes.join(', ')}</div>
Expand All @@ -85,14 +97,15 @@ function OutputBlock({ output }: { output: NotebookOutput }): React.ReactElement

interface Props {
outputs: NotebookOutput[]
effectiveTheme: 'dark' | 'light'
}

export default function NotebookOutputs({ outputs }: Props): React.ReactElement | null {
export default function NotebookOutputs({ outputs, effectiveTheme }: Props): React.ReactElement | null {
if (outputs.length === 0) return null
return (
<div className="border-t border-hair bg-bg">
{outputs.map((output, index) => (
<OutputBlock key={index} output={output} />
<OutputBlock key={index} output={output} effectiveTheme={effectiveTheme} />
))}
</div>
)
Expand Down
22 changes: 18 additions & 4 deletions src/shared/notebook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -948,6 +948,8 @@ export function storedCellIds(text: string): Set<string> {
* 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.
* A plain text that is only an object repr (`display(HTML(...))` sends
* `<IPython.core.display.HTML object>`) yields to any richer form.
*/
export type NotebookDisplay =
| { kind: 'image'; src: string }
Expand All @@ -957,6 +959,8 @@ export type NotebookDisplay =
| { kind: 'json'; text: string }
| { kind: 'unsupported'; mimeTypes: string[] }

const OBJECT_REPR = /^<[\w.]+ object(?: at 0x[0-9a-f]+)?>$/i

export function notebookOutputDisplay(
data: Record<string, string>,
jsonData?: Record<string, unknown>
Expand All @@ -968,25 +972,35 @@ export function notebookOutputDisplay(
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 }
const placeholder = plain != null && OBJECT_REPR.test(plain.trim())
if (plain && !placeholder) 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) }
if (plain) return { kind: 'text', text: plain }
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.
* those references to data URLs so the preview can show them. Unknown names,
* and anything inside code spans or fenced blocks, 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) => {
// Odd entries are code (the split keeps the captured delimiters' contents).
return source
.split(/(```[\s\S]*?(?:```|$)|~~~[\s\S]*?(?:~~~|$)|`[^`\n]+`)/)
.map((part, index) => (index % 2 === 1 ? part : resolveAttachmentRefs(part, record)))
.join('')
}

function resolveAttachmentRefs(text: string, record: Record<string, unknown>): string {
return text.replace(/attachment:([^\s)"'<>]+)/g, (match, rawName: string) => {
let name = rawName
try { name = decodeURIComponent(rawName) } catch { /* keep raw */ }
const bundle = asRecord(record[name] ?? record[rawName])
Expand Down
31 changes: 29 additions & 2 deletions tests/notebook-rich-output.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,14 @@ describe('notebookOutputDisplay', () => {
expect(notebookOutputDisplay({ 'text/markdown': '# x' })).toEqual({ kind: 'markdown', markdown: '# x' })
})

it('prefers rich forms over an IPython display object placeholder', () => {
const repr = (name: string): string => `<IPython.core.display.${name} object>`
expect(notebookOutputDisplay({ 'text/html': '<b>x</b>', 'text/plain': repr('HTML') })).toEqual({ kind: 'html', html: '<b>x</b>' })
expect(notebookOutputDisplay({ 'text/markdown': '# x', 'text/plain': repr('Markdown') })).toEqual({ kind: 'markdown', markdown: '# x' })
expect(notebookOutputDisplay({ 'text/plain': repr('JSON') }, { 'application/json': { a: 1 } })).toMatchObject({ kind: 'json' })
expect(notebookOutputDisplay({ 'text/plain': '<Foo object at 0x10a2b>' })).toEqual({ kind: 'text', text: '<Foo object at 0x10a2b>' })
})

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()
Expand Down Expand Up @@ -58,7 +66,7 @@ describe('NotebookOutputs rendering', () => {
data: {},
jsonData: { 'application/json': { a: 1, message: 'survives' } }
}]
const { container } = render(<NotebookOutputs outputs={outputs} />)
const { container } = render(<NotebookOutputs outputs={outputs} effectiveTheme="dark" />)
expect(container.textContent).toContain('"message": "survives"')
})

Expand All @@ -67,11 +75,22 @@ describe('NotebookOutputs rendering', () => {
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} />)
const { container } = render(<NotebookOutputs outputs={outputs} effectiveTheme="dark" />)
expect(container.querySelector('td')?.textContent).toBe('cell')
expect(container.querySelector('script')).toBeNull()
expect(container.querySelector('img')?.getAttribute('onerror')).toBeNull()
})

it('strips CSS from HTML output so it cannot restyle the app', () => {
const outputs: NotebookOutput[] = [{
type: 'display_data',
data: { 'text/html': '<p>a</p><style>body { display: none }</style><div style="position:fixed;inset:0">cover</div>' }
}]
const { container } = render(<NotebookOutputs outputs={outputs} effectiveTheme="dark" />)
expect(container.querySelector('style')).toBeNull()
expect(container.querySelector('[style]')).toBeNull()
expect(container.textContent).toContain('cover')
})
})

describe('markdown attachments', () => {
Expand All @@ -88,6 +107,14 @@ describe('markdown attachments', () => {
expect(resolveMarkdownAttachments('![a](attachment:x.png)', undefined)).toBe('![a](attachment:x.png)')
})

it('leaves attachment: references inside code alone', () => {
const source = 'see `attachment:checker.png`\n\n```\n![x](attachment:checker.png)\n```\n\n![y](attachment:checker.png)'
const out = resolveMarkdownAttachments(source, attachments)
expect(out).toContain('`attachment:checker.png`')
expect(out).toContain('```\n![x](attachment:checker.png)\n```')
expect(out).toContain(`![y](data:image/png;base64,${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,')
Expand Down
Loading