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: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions ui-packages/code-lab/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"biwascheme": "^0.8.3",
"codemirror": "^6.0.2",
"dompurify": "^3.4.15",
"katex": "^0.18.7",
"lucide-react": "^1.46.0",
"sucrase": "^3.35.1"
},
Expand Down
12 changes: 12 additions & 0 deletions ui-packages/code-lab/src/components/code-cell/code-output.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ import styles from './style.module.scss'
const HtmlOutput = lazy(() =>
import('./html-output').then(module => ({ default: module.HtmlOutput })),
)
const LatexOutput = lazy(() =>
import('./latex-output').then(module => ({ default: module.LatexOutput })),
)

type CodeOutputProps = {
execution: CellExecution | undefined
Expand All @@ -31,6 +34,15 @@ const OutputValue = ({ output }: { output: CodeLabOutput }) => {
</div>
)
}
if (output.kind === 'latex') {
return (
<div className={styles.richOutput}>
<Suspense fallback={<span className={styles.muted}>Rendering formula…</span>}>
<LatexOutput latex={output.latex} />
</Suspense>
</div>
)
}
return <pre className={output.kind === 'stderr' ? styles.stderr : undefined}>{output.text}</pre>
}

Expand Down
16 changes: 16 additions & 0 deletions ui-packages/code-lab/src/components/code-cell/latex-output.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import katex from 'katex'
import 'katex/dist/katex.min.css'
import { useMemo } from 'react'

type LatexOutputProps = {
latex: string
}

export const LatexOutput = ({ latex }: LatexOutputProps) => {
const html = useMemo(
() => katex.renderToString(latex, { displayMode: true, throwOnError: false }),
[latex],
)
// biome-ignore lint/security/noDangerouslySetInnerHtml: KaTeX markup; its default trust: false rejects \href and \html* commands
return <div dangerouslySetInnerHTML={{ __html: html }} />
}
7 changes: 7 additions & 0 deletions ui-packages/code-lab/src/runtime/languages/biwascheme.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ declare module 'biwascheme' {
undef?: unknown
nil?: unknown
to_write?: (value: unknown) => string
define_libfunc(
name: string,
min: number,
max: number,
fn: (args: readonly unknown[]) => unknown,
): void
assert_string(value: unknown): asserts value is string
}

const runtime: BiwaSchemeRuntime
Expand Down
24 changes: 20 additions & 4 deletions ui-packages/code-lab/src/runtime/languages/clojure.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { CodeLabExecutionResult } from '../../types'
import type { CodeLabExecutionResult, CodeLabOutput } from '../../types'
import { createConsoleCapture, installConsoleCapture } from '../format-value'
import type { LanguageRuntime, RuntimeProgress } from '../protocol'

Expand All @@ -11,6 +11,17 @@ type Scittle = {
}
}

// Defined in the default `user` namespace; cells that switch namespaces call it as `user/latex`.
const latexHelper = `(defn latex [tex]
(when-not (string? tex) (throw (js/Error. (str "latex expects a string, got " (pr-str tex)))))
#js {:toLatex (fn [] tex)})`

// Values carrying toLatex() stay JS objects for the formula output; everything else is printed.
const wrapCell = (source: string): string => `(let [value (do
${source}
)]
(if (and (some? value) (fn? (.-toLatex value)) (string? (.toLatex value))) value (pr-str value)))`

let scittle: Scittle | null = null
let initialization: Promise<Scittle> | null = null

Expand All @@ -34,6 +45,7 @@ const initialize = async (progress: RuntimeProgress): Promise<Scittle> => {
loadScittle.call(globalThis)
const runtime = getGlobalScittle()
if (!runtime) throw new Error('Scittle loaded without exposing its runtime')
runtime.core.eval_string(latexHelper)
scittle = runtime
return runtime
})()
Expand All @@ -46,6 +58,11 @@ const initialize = async (progress: RuntimeProgress): Promise<Scittle> => {
}
}

const clojureValueOutput = (value: unknown): CodeLabOutput | null => {
if (typeof value === 'string') return value === 'nil' ? null : { kind: 'text', text: value }
return { kind: 'latex', latex: (value as { toLatex: () => string }).toLatex() }
}

const runClojure = async (
source: string,
progress: RuntimeProgress,
Expand All @@ -55,10 +72,9 @@ const runClojure = async (
const capture = createConsoleCapture()
const restoreConsole = installConsoleCapture(capture)
try {
const value = runtime.core.eval_string(`(pr-str (do\n${source}\n))`)
const text = typeof value === 'string' && value !== 'nil' ? value : null
const output = clojureValueOutput(runtime.core.eval_string(wrapCell(source)))
return {
outputs: [...capture.outputs(), ...(text === null ? [] : [{ kind: 'text' as const, text }])],
outputs: [...capture.outputs(), ...(output === null ? [] : [output])],
error: null,
}
} catch (error) {
Expand Down
22 changes: 21 additions & 1 deletion ui-packages/code-lab/src/runtime/languages/python.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ type PythonResult = {
stderr: string
valueText: string | null
valueHtml: string | null
valueLatex: string | null
imagePngBase64: string | null
error: string | null
}
Expand All @@ -50,6 +51,18 @@ from pyodide.code import eval_code_async

_gamma_lab_globals = {'__name__': '__main__'}

def _gamma_lab_latex(value):
# Classes carry an unbound _repr_latex_; only instances follow the Jupyter protocol.
repr_latex = None if isinstance(value, type) else getattr(value, '_repr_latex_', None)
if not callable(repr_latex):
return None
try:
latex = repr_latex()
except Exception:
traceback.print_exc(file=sys.stderr)
return None
return latex.strip().strip('$').strip() if isinstance(latex, str) else None

async def _gamma_lab_execute(source):
stdout_buffer = io.StringIO()
stderr_buffer = io.StringIO()
Expand All @@ -60,6 +73,7 @@ async def _gamma_lab_execute(source):
'stderr': '',
'valueText': None,
'valueHtml': None,
'valueLatex': None,
'imagePngBase64': None,
'error': None,
}
Expand All @@ -78,7 +92,11 @@ async def _gamma_lab_execute(source):
traceback.print_exc(file=sys.stderr)
result['valueText'] = repr(value)
else:
result['valueText'] = repr(value)
latex = _gamma_lab_latex(value)
if latex:
result['valueLatex'] = latex
else:
result['valueText'] = repr(value)

try:
import matplotlib.pyplot as plt
Expand Down Expand Up @@ -118,6 +136,7 @@ const normalizePythonResult = (value: unknown): PythonResult => {
stderr: requireString(record.stderr),
valueText: optionalString(record.valueText),
valueHtml: optionalString(record.valueHtml),
valueLatex: optionalString(record.valueLatex),
imagePngBase64: optionalString(record.imagePngBase64),
error: optionalString(record.error),
}
Expand Down Expand Up @@ -184,6 +203,7 @@ const runPython = async (
if (result.stderr) outputs.push({ kind: 'stderr', text: result.stderr })
if (result.valueText) outputs.push({ kind: 'text', text: result.valueText })
if (result.valueHtml) outputs.push({ kind: 'html', html: result.valueHtml })
if (result.valueLatex) outputs.push({ kind: 'latex', latex: result.valueLatex })
if (result.imagePngBase64) {
outputs.push({ kind: 'image', mediaType: 'image/png', base64: result.imagePngBase64 })
}
Expand Down
24 changes: 21 additions & 3 deletions ui-packages/code-lab/src/runtime/languages/scheme.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { BiwaSchemeRuntime, InterpreterInstance } from 'biwascheme'
import type { CodeLabExecutionResult } from '../../types'
import type { CodeLabExecutionResult, CodeLabOutput } from '../../types'
import { createConsoleCapture, installConsoleCapture } from '../format-value'
import type { LanguageRuntime, RuntimeProgress } from '../protocol'

Expand All @@ -18,6 +18,17 @@ const provideWorkerBrowserAliases = (): void => {
}
}

class LatexValue {
constructor(readonly latex: string) {}
}

const defineLatexProcedure = (runtime: BiwaSchemeRuntime): void => {
runtime.define_libfunc('latex', 1, 1, ([tex]) => {
runtime.assert_string(tex)
return new LatexValue(tex)
})
}

const createInterpreter = (runtime: BiwaSchemeRuntime): InterpreterInstance =>
new runtime.Interpreter(error => console.error('BiwaScheme interpreter error', error))

Expand All @@ -27,6 +38,7 @@ const initialize = async (progress: RuntimeProgress): Promise<void> => {
provideWorkerBrowserAliases()
const module = await import('biwascheme')
biwaScheme = module.default
defineLatexProcedure(biwaScheme)
interpreter = createInterpreter(biwaScheme)
}

Expand All @@ -39,6 +51,12 @@ const formatSchemeValue = (runtime: BiwaSchemeRuntime, value: unknown): string |
return String(value)
}

const schemeValueOutput = (runtime: BiwaSchemeRuntime, value: unknown): CodeLabOutput | null => {
if (value instanceof LatexValue) return { kind: 'latex', latex: value.latex }
const text = formatSchemeValue(runtime, value)
return text === null ? null : { kind: 'text', text }
}

const runScheme = async (
source: string,
progress: RuntimeProgress,
Expand All @@ -51,9 +69,9 @@ const runScheme = async (
const restoreConsole = installConsoleCapture(capture)
try {
const value = interpreter.evaluate(source)
const text = formatSchemeValue(biwaScheme, value)
const output = schemeValueOutput(biwaScheme, value)
return {
outputs: [...capture.outputs(), ...(text === null ? [] : [{ kind: 'text' as const, text }])],
outputs: [...capture.outputs(), ...(output === null ? [] : [output])],
error: null,
}
} catch (error) {
Expand Down
6 changes: 5 additions & 1 deletion ui-packages/code-lab/src/runtime/languages/typescript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,15 @@ const importLibrary = async (specifier: string): Promise<unknown> => {
const richValueOutput = (value: unknown): CodeLabOutput | null => {
if (value === undefined) return null
if (value !== null && typeof value === 'object') {
const richValue = value as { toHtml?: () => unknown }
const richValue = value as { toHtml?: () => unknown; toLatex?: () => unknown }
if (typeof richValue.toHtml === 'function') {
const html = richValue.toHtml()
if (typeof html === 'string') return { kind: 'html', html }
}
if (typeof richValue.toLatex === 'function') {
const latex = richValue.toLatex()
if (typeof latex === 'string') return { kind: 'latex', latex }
}
}
return { kind: 'text', text: formatValue(value) }
}
Expand Down
1 change: 1 addition & 0 deletions ui-packages/code-lab/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export type CodeLabCell = Readonly<{
export type CodeLabOutput =
| Readonly<{ kind: 'stdout' | 'stderr' | 'text'; text: string }>
| Readonly<{ kind: 'html'; html: string }>
| Readonly<{ kind: 'latex'; latex: string }>
| Readonly<{ kind: 'image'; mediaType: 'image/png'; base64: string }>

export type CodeLabExecutionResult = Readonly<{
Expand Down