From e486490521f10f383685875a5c257bb30b703fa0 Mon Sep 17 00:00:00 2001 From: Qijun Date: Thu, 1 Oct 2026 08:03:45 -0700 Subject: [PATCH 1/4] feat: render formula outputs from Python, TypeScript and Scheme cells --- pnpm-lock.yaml | 3 +++ ui-packages/code-lab/package.json | 1 + .../src/components/code-cell/code-output.tsx | 12 ++++++++++ .../src/components/code-cell/latex-output.tsx | 19 +++++++++++++++ .../src/runtime/languages/biwascheme.d.ts | 7 ++++++ .../code-lab/src/runtime/languages/python.ts | 22 ++++++++++++++++- .../code-lab/src/runtime/languages/scheme.ts | 24 ++++++++++++++++--- .../src/runtime/languages/typescript.ts | 6 ++++- ui-packages/code-lab/src/types.ts | 1 + 9 files changed, 90 insertions(+), 5 deletions(-) create mode 100644 ui-packages/code-lab/src/components/code-cell/latex-output.tsx diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f1c5639..338c0bc 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -47,6 +47,9 @@ importers: dompurify: specifier: ^3.4.15 version: 3.4.15 + katex: + specifier: ^0.18.7 + version: 0.18.7 lucide-react: specifier: ^1.46.0 version: 1.46.0(react@19.3.0) diff --git a/ui-packages/code-lab/package.json b/ui-packages/code-lab/package.json index d092a9b..45f006d 100644 --- a/ui-packages/code-lab/package.json +++ b/ui-packages/code-lab/package.json @@ -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" }, diff --git a/ui-packages/code-lab/src/components/code-cell/code-output.tsx b/ui-packages/code-lab/src/components/code-cell/code-output.tsx index bccfb2a..bbb1243 100644 --- a/ui-packages/code-lab/src/components/code-cell/code-output.tsx +++ b/ui-packages/code-lab/src/components/code-cell/code-output.tsx @@ -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 @@ -31,6 +34,15 @@ const OutputValue = ({ output }: { output: CodeLabOutput }) => { ) } + if (output.kind === 'latex') { + return ( +
+ Rendering formula…}> + + +
+ ) + } return
{output.text}
} diff --git a/ui-packages/code-lab/src/components/code-cell/latex-output.tsx b/ui-packages/code-lab/src/components/code-cell/latex-output.tsx new file mode 100644 index 0000000..3975fc8 --- /dev/null +++ b/ui-packages/code-lab/src/components/code-cell/latex-output.tsx @@ -0,0 +1,19 @@ +import katex from 'katex' +import 'katex/dist/katex.min.css' +import { useEffect, useRef } from 'react' + +type LatexOutputProps = { + latex: string +} + +export const LatexOutput = ({ latex }: LatexOutputProps) => { + const rootRef = useRef(null) + + useEffect(() => { + const root = rootRef.current + if (!root) return + katex.render(latex, root, { displayMode: true, throwOnError: false }) + }, [latex]) + + return
+} diff --git a/ui-packages/code-lab/src/runtime/languages/biwascheme.d.ts b/ui-packages/code-lab/src/runtime/languages/biwascheme.d.ts index ebf13a5..3d9642a 100644 --- a/ui-packages/code-lab/src/runtime/languages/biwascheme.d.ts +++ b/ui-packages/code-lab/src/runtime/languages/biwascheme.d.ts @@ -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 diff --git a/ui-packages/code-lab/src/runtime/languages/python.ts b/ui-packages/code-lab/src/runtime/languages/python.ts index b051a98..97bd4b1 100644 --- a/ui-packages/code-lab/src/runtime/languages/python.ts +++ b/ui-packages/code-lab/src/runtime/languages/python.ts @@ -34,6 +34,7 @@ type PythonResult = { stderr: string valueText: string | null valueHtml: string | null + valueLatex: string | null imagePngBase64: string | null error: string | null } @@ -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() @@ -60,6 +73,7 @@ async def _gamma_lab_execute(source): 'stderr': '', 'valueText': None, 'valueHtml': None, + 'valueLatex': None, 'imagePngBase64': None, 'error': None, } @@ -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 @@ -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), } @@ -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 }) } diff --git a/ui-packages/code-lab/src/runtime/languages/scheme.ts b/ui-packages/code-lab/src/runtime/languages/scheme.ts index b01226d..4721a89 100644 --- a/ui-packages/code-lab/src/runtime/languages/scheme.ts +++ b/ui-packages/code-lab/src/runtime/languages/scheme.ts @@ -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' @@ -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)) @@ -27,6 +38,7 @@ const initialize = async (progress: RuntimeProgress): Promise => { provideWorkerBrowserAliases() const module = await import('biwascheme') biwaScheme = module.default + defineLatexProcedure(biwaScheme) interpreter = createInterpreter(biwaScheme) } @@ -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, @@ -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) { diff --git a/ui-packages/code-lab/src/runtime/languages/typescript.ts b/ui-packages/code-lab/src/runtime/languages/typescript.ts index 22350d3..8960283 100644 --- a/ui-packages/code-lab/src/runtime/languages/typescript.ts +++ b/ui-packages/code-lab/src/runtime/languages/typescript.ts @@ -67,11 +67,15 @@ const importLibrary = async (specifier: string): Promise => { 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) } } diff --git a/ui-packages/code-lab/src/types.ts b/ui-packages/code-lab/src/types.ts index 53fe1ae..3531aed 100644 --- a/ui-packages/code-lab/src/types.ts +++ b/ui-packages/code-lab/src/types.ts @@ -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<{ From 173730418cd281e29a9f00e37b1278da9d3e3bbb Mon Sep 17 00:00:00 2001 From: Qijun Date: Thu, 1 Oct 2026 08:27:33 -0700 Subject: [PATCH 2/4] refactor: render KaTeX markup with renderToString --- .../src/components/code-cell/latex-output.tsx | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/ui-packages/code-lab/src/components/code-cell/latex-output.tsx b/ui-packages/code-lab/src/components/code-cell/latex-output.tsx index 3975fc8..37191f5 100644 --- a/ui-packages/code-lab/src/components/code-cell/latex-output.tsx +++ b/ui-packages/code-lab/src/components/code-cell/latex-output.tsx @@ -1,19 +1,16 @@ import katex from 'katex' import 'katex/dist/katex.min.css' -import { useEffect, useRef } from 'react' +import { useMemo } from 'react' type LatexOutputProps = { latex: string } export const LatexOutput = ({ latex }: LatexOutputProps) => { - const rootRef = useRef(null) - - useEffect(() => { - const root = rootRef.current - if (!root) return - katex.render(latex, root, { displayMode: true, throwOnError: false }) - }, [latex]) - - return
+ 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
} From b1a26774d5f5602badbe6d274992820afd8728ce Mon Sep 17 00:00:00 2001 From: Qijun Date: Thu, 1 Oct 2026 08:37:09 -0700 Subject: [PATCH 3/4] feat: render formula outputs from Clojure cells --- .../code-lab/src/runtime/languages/clojure.ts | 25 ++++++++++++++++--- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/ui-packages/code-lab/src/runtime/languages/clojure.ts b/ui-packages/code-lab/src/runtime/languages/clojure.ts index 11d8bb1..bfa94c4 100644 --- a/ui-packages/code-lab/src/runtime/languages/clojure.ts +++ b/ui-packages/code-lab/src/runtime/languages/clojure.ts @@ -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' @@ -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))) value (pr-str value)))` + let scittle: Scittle | null = null let initialization: Promise | null = null @@ -34,6 +45,7 @@ const initialize = async (progress: RuntimeProgress): Promise => { 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 })() @@ -46,6 +58,12 @@ const initialize = async (progress: RuntimeProgress): Promise => { } } +const clojureValueOutput = (value: unknown): CodeLabOutput | null => { + if (typeof value === 'string') return value === 'nil' ? null : { kind: 'text', text: value } + const latex = (value as { toLatex: () => unknown }).toLatex() + return typeof latex === 'string' ? { kind: 'latex', latex } : null +} + const runClojure = async ( source: string, progress: RuntimeProgress, @@ -55,10 +73,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) { From 9418800e7e6b2ea72c7e07a52513dc48ebbc7077 Mon Sep 17 00:00:00 2001 From: Qijun Date: Thu, 1 Oct 2026 08:40:19 -0700 Subject: [PATCH 4/4] fix: print Clojure values whose toLatex does not return a string --- ui-packages/code-lab/src/runtime/languages/clojure.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/ui-packages/code-lab/src/runtime/languages/clojure.ts b/ui-packages/code-lab/src/runtime/languages/clojure.ts index bfa94c4..0e104df 100644 --- a/ui-packages/code-lab/src/runtime/languages/clojure.ts +++ b/ui-packages/code-lab/src/runtime/languages/clojure.ts @@ -20,7 +20,7 @@ const latexHelper = `(defn latex [tex] const wrapCell = (source: string): string => `(let [value (do ${source} )] - (if (and (some? value) (fn? (.-toLatex value))) value (pr-str value)))` + (if (and (some? value) (fn? (.-toLatex value)) (string? (.toLatex value))) value (pr-str value)))` let scittle: Scittle | null = null let initialization: Promise | null = null @@ -60,8 +60,7 @@ const initialize = async (progress: RuntimeProgress): Promise => { const clojureValueOutput = (value: unknown): CodeLabOutput | null => { if (typeof value === 'string') return value === 'nil' ? null : { kind: 'text', text: value } - const latex = (value as { toLatex: () => unknown }).toLatex() - return typeof latex === 'string' ? { kind: 'latex', latex } : null + return { kind: 'latex', latex: (value as { toLatex: () => string }).toLatex() } } const runClojure = async (