Skip to content

Interactive Cells

Interactive cells are ordinary MDX code blocks with metadata comments at the top. Oxiquill extracts those blocks during generation and replaces them with a runtime UI.

Rust cells are compiled to WebAssembly at build time. Python cells run in a browser Pyodide worker. Haskell cells are compiled to a WASI WebAssembly module at build time. All three languages use the same input metadata and run-mode model.

Reruns retain the last successful output, with an error and retry action if execution fails. Cancellation and invalid input also keep the output. Compatible charts update the same canvas with a default 180ms transition, respecting OS reduced-motion preferences. See rich output for the exact style schema, limits, and Rust overloads. Explicit artifact IDs are recommended for dynamically changing output sequences.

Interactive fences use rust, python, or haskell (including Markdown’s {.rust} form) and may use legal backtick or tilde fences and indentation. Metadata is one contiguous block of language-appropriate option comments at the beginning of the fence: //| or ///| for Rust, #| for Python, and --| for Haskell. An option-looking comment after the first source line remains source code.

Only these top-level fields are accepted; unknown fields are errors:

FieldType and ruleDefault
refOptional stable lowercase kebab-case name, at most 64 characters; unique across cells and headings per locale.None
idRequired lowercase kebab-case matching ^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$; unique within the page and after route scoping.—
titleNon-empty string shown in the cell header; explicit values are trimmed.id
runbutton, reactive, or autorun.button
inputsMapping from lowercase cross-language identifiers matching ^[a-z][a-z0-9_]*$ to input specs. Not allowed with autorun.{}
casesList of named input presets. Not allowed with autorun.[]
packagesUnique non-empty Pyodide package names; Python only.[]
cratesUnique non-empty helper package names from direct children of cratesDir; Rust only.[]
timeoutMsInteger milliseconds from 1 through 2147483647, inclusive.30000
showSourceBoolean controlling initial source visibility.true
outputLayoutstack, or columns to let charts and images share a row in a wide cell (Output Layout).stack
editableBoolean allowing readers to edit and run a local draft; Python only.true
setupOne page-local Python cell ID without inputs; requires python.experimentalSetup: true.None

The source must contain non-metadata code. Malformed YAML, a wrong scalar/collection type, duplicate normalized ID/binding/function, unknown package/crate, or language-mismatched dependency field fails before output is written. Diagnostics include page path, fence start line, cell ID when available, and the exact field path.

Haskell cells use standard-library code only and accept neither packages nor crates. Rust cells without helpers should explicitly use crates: [] in examples. Package and crate lists are deduplicated and sorted after strict validation.

Python setup executes before each body in fresh globals. Successful setup output is hidden, input values are injected afterward, and setup timeouts add to the body’s timeout. See Experimental Setup. Haskell’s bundled Oxiquill.Output module supports structured output without additional package dependencies.

  • button: show inputs and a Run button; do not execute on mount.
  • reactive: show inputs, hide the Run button, execute once on mount, then use a 150 ms trailing debounce. At most one execution and one newest replacement are retained.
  • autorun: show neither inputs nor Run button and execute exactly once for each cell.id + runtimeVersion + source. Source updates during development invalidate the previous execution even if the runtime-version update arrives first.

This button cell waits for an explicit run even when its input changes.

Rust + Wasm

Explicit button execution

Cell actions
Cell inputs

Choose an integer from 1 through 10.

println!("button value = {value}");

Run the cell to show its output.

This autorun cell has no execution controls and runs once for the current generated runtime.

Rust + Wasm

One-time autorun execution

Cell actions
println!("autorun ready");

Waiting for the runtime to start.

Superseding a reactive run actively cancels its worker request, rejects every request affected by the worker recycle, clears their timers, and starts the latest complete values after the debounce. Cancellation is not shown as an execution error, and stale results cannot replace newer state. Timeout and worker-fault recovery use the same deterministic recycle boundary. Unmounting cancels pending and active work.

Every input accepts only fields relevant to its type. Common fields are type, label, description, and value; numeric inputs also use min, max, step, and integer, while select and radio use options.

TypeValue and constraints
range, numberFinite number; step > 0, min <= max, and the default must be within bounds and on the step grid.
integerSigned 32-bit integer from -2147483648 through 2147483647; bounds and step use the same domain.
text, textareaString value.
checkboxBoolean value.
select, radioNon-empty unique string options or { label, value } objects; the default must equal an option value.

type defaults to text, and label defaults to the input name. description is an optional non-empty string associated with the control for assistive technology. Default values are false for checkbox, 0 for numeric inputs, and an empty string for text inputs. Numeric-only fields are rejected on non-numeric controls, and options is rejected outside select and radio.

The signed 32-bit integer domain is exactly representable by JavaScript and maps consistently to Rust i32, Haskell Int, and Python int. Authoring rejects an integer value, min, max, or step outside that domain. Browser controls apply the same domain before constructing a worker request, including for integer: true numeric inputs.

Numeric defaults must align with the same step grid enforced by browser controls. The effective step is step when provided and 1 otherwise. The grid starts at min when provided; without min, the declared or default numeric value is the base. Oxiquill rejects a misaligned default during authoring instead of rounding or clamping it.

Number and integer controls keep their raw edit text separate from committed runtime values. Empty, incomplete, non-finite, out-of-range, and step-mismatched text remains visible but cannot update cell inputs. The Run button is disabled while any control is invalid, and reactive execution resumes exactly once with the latest complete value set after validity returns. Range labels derive their displayed precision from step.

The visible label is the control’s accessible name; the input key is only the generated language binding. Normalization must not make two Rust or Haskell bindings collide. Labels, descriptions, current values, validation messages, and grouped controls use stable IDs, keyboard focus remains visible, and run/error status is announced without stealing focus.

Python cells offer Edit Python with a plain textarea unless the cell sets editable: false. While editing, both source and input changes wait for Run, even in reactive cells. Restore original code resets the draft without running it; Finish editing discards the draft and its output and restores the authored run mode. Navigation and source refresh discard drafts. Editing does not change the published page or sharing link. Imports are limited to the packages bundled with the site, which are the packages declared by any Python cell and their dependencies; other Pyodide packages report an error instead of being downloaded. The normal cell timeout still applies.

To include an input in Copy input link, add share: true to that input’s metadata. Sharing is disabled by default, including for text fields. The link stores only differences from defaults for opted-in inputs on this page. Existing query parameters and heading links remain intact. Invalid or outdated input values are ignored when opening a link. Links longer than 8,192 characters cannot be copied. Code, outputs, random state, and external data are not included; identical inputs do not guarantee identical results.

Cells with inputs provide Reset inputs. It restores all defaults and clears incomplete edits and validation errors. Reactive cells recalculate once; button cells wait for Run. The previous successful output remains visible while the next result is pending.

Input controls fill as many columns as the cell’s own width allows, so a cell beside both navigation columns can show one column even on a wide screen. Each column is at least --oq-input-column-min-width wide (default 16rem); set it on :root in a stylesheet registered through starlight.customCss to change the count.

New sharing links use v: 2 and store each cell as { values, case? }. The values map still contains only opted-in differences. A case ID is included only for an exact match. A known case restores its complete authored values, including share: false inputs; an unknown case ID falls back to validated shared values. Legacy v: 1 links continue to restore.

Declare cases to offer presets that combine several inputs. Selecting a Case replaces every input in one transition. Reactive cells execute the complete combination once; button cells wait for Run. Python draft editing also waits for Run.

Each case has a cell-local unique kebab-case id, a required label, and an inputs mapping of partial overrides. The ID default is reserved. An optional description is non-empty plain text. Input and case labels are trimmed, nonblank strings of at most 256 characters. Omitted inputs use the declared defaults, rather than the reader’s current values. All values must satisfy the input’s type, bounds, step grid, integer domain, and options. Without min, the original input default remains the step-grid base.

The selector indicates a case when all current values match it, and Custom values otherwise. Editing back to an exact match restores the indication. If multiple cases match, the first authored case is indicated. Reset inputs restores declared defaults. During development, HMR retains valid current values, resets only invalid or added inputs to their new defaults, and recomputes the indication.

For stochastic computations, expose seeds as ordinary inputs and include them in cases so the preset determines the computation. Oxiquill adds no separate seed mechanism.

Rust + Wasm

Named input cases

Cell actions
Cell inputs
0.10
println!("samples = {samples}, noise = {noise:.2}, seed = {seed}, model = {model}, enabled = {enabled}");

Waiting for the runtime to start.

Code scrolls inside a fixed frame, and long lines never widen the page. The frame is keyboard focusable: Tab to it, then use the arrow keys to scroll. Its focus outline remains visible in both themes.

Source panes have no height cap by default. To bound them on screen, add this to a stylesheet registered through starlight.customCss:

:root {
--oq-source-max-height: 24rem;
}

The limit applies to the highlighted source frame itself. Sites that previously bounded .doc-source directly should use --oq-source-max-height instead. Printing removes the limit and shows the full source with long lines wrapped, using light syntax colors even when the screen theme is dark.

Text, JSON, and error outputs follow the same model with --oq-output-max-height, which is also unset by default. A bounded output scrolls inside its frame, is keyboard focusable, and prints in full:

:root {
--oq-output-max-height: 20rem;
}

This Rust cell uses a helper crate and redraws a plot whenever the sliders change.

Rust + Wasm

Calculate the logistic map with Rust

Cell actions
Cell inputs
3.20
0.20
let steps = u32::try_from(steps).map_err(|_| "steps must be non-negative".to_owned())?;
let points = doc_rust::logistic_series(r, x0, steps).map_err(|error| error.to_string())?;

for point in points.iter().take(5) {
    println!("n={} x={:.6}", point.n, point.x);
}

let coordinates: Vec<[f64; 2]> = points.iter().map(|point| [f64::from(point.n), point.x]).collect();
emit_line_chart!(&coordinates, "n", "x");

Waiting for the runtime to start.

A cell with crates: [] does not depend on helper crates. This example shows checkbox, select, and radio inputs.

Rust + Wasm

Rust input UI

Cell actions
Cell inputs
style
let base_score = match operation.as_str() {
    "triple" => 21_i32,
    "double" => 14_i32,
    _ => 7_i32,
};
let score = if include_bonus {
    base_score + 5
} else {
    base_score
};

println!("style = {style}");
println!("score = {score}");

Waiting for the runtime to start.

Each Rust cell declares the helper crates it needs. The names must match Cargo package names under crates/*.

Rust + Wasm

Rust cell with multiple crates

Cell actions
Cell inputs
style
let points = doc_rust::logistic_series(3.2, 0.2, 8).map_err(|error| error.to_string())?;
let final_point = points.last().ok_or_else(|| "series is empty".to_owned())?;

println!("{}", doc_rust_text::labeled_value("final step", final_point.n));
println!("{}", doc_rust_text::labeled_value("final x", format!("{:.6}", final_point.x)));
println!("{}", doc_rust_text::style_note(style.as_str()));

Waiting for the runtime to start.

Python cells use the same input metadata. Input values are available as Python variables.

Python + Pyodide

Python input UI

Cell actions
Cell inputs
style
values = [1, 2, 3, 4]

if method == "sum":
    result = sum(values) * scale
elif method == "max":
    result = max(values) * scale
else:
    result = sum(values) / len(values) * scale

name = label.upper() if enabled else label
print(f"{name}: {method} = {result}")
print(f"style = {style}")

Waiting for the runtime to start.

Haskell cells use --| metadata comments. Input values become Haskell variables, and text output written with putStrLn or print appears in the result panel.

Haskell + WASI

Haskell input UI

Cell actions
Cell inputs
{- Imports may use normal multiline Haskell layout. -}
import Data.List
  ( intercalate
  , sort
  )

let base = [1 .. 4 :: Int]
let scaled = map (* factor) base
let displayed = sort (if include_squares then map (\value -> value * value) scaled else scaled)

putStrLn (label ++ ": " ++ intercalate ", " (map show displayed))
putStrLn ("total = " ++ show (sum displayed))

Waiting for the runtime to start.

Python cells show Preparing Python… during initialization and package loading, then Running while authored code executes. See Python Runtime Assets for optional page preparation with python.preload.

Use kind: definitions to author ordinary Rust items once and share them through ordered, page-local uses references. Definitions show their title and source, without execution controls. Items and fields used by another block need normal Rust visibility, usually pub(crate).

Shared model

pub(crate) struct Model {
    pub(crate) a: i32,
}

pub(crate) fn value(model: &Model) -> i32 {
    model.a
}

Model helper

pub(crate) fn make_model() -> Model {
    Model { a: 7 }
}

Rust + Wasm

First consumer

Cell actions
let model = Model { a: 3 };
println!("{}", value(&model));

Run the cell to show its output.

Rust + Wasm

Second consumer

Cell actions
let model = Model { a: 5 };
println!("{}", value(&model));

Run the cell to show its output.

Rust + Wasm

Transitive consumer

Cell actions
println!("{}", value(&make_model()));

Run the cell to show its output.

A definitions block accepts only id, kind, title, crates, uses, and showSource. Explicit kind accepts only definitions; omit it for runnable cells. References must be unique, page-local definitions IDs and must not form cycles. Both metadata fields are currently supported only for Rust; Python setup behavior is unchanged.

Imports follow normal Rust glob rules: local items can shadow imported names, ambiguous names are compiler errors, and imports are not automatically re-exported. The third cell lists both blocks because it calls the helper and names the model function directly.

Consumers inherit helper crates from all reachable definitions. Unused definitions are checked for valid metadata and references but are not compiled and add no Rust dependencies. Editing a used block rebuilds the Rust modules of its consuming pages; editing an unused block only updates its displayed source.

Outputs remember the inputs that produced them. Editing an input, selecting a case, restoring inputs, or starting another run marks retained output with a previous-input note and data-stale="true". This note, the updating indicator, and the upstream-change and reuse notes overlay the top of the output instead of taking a row, so charts and tables keep their position while values change. Invalid numeric edits also mark results stale. Reactive cells keep the mark throughout debounce and execution; button cells keep it until Run succeeds. Editing an input also cancels the cell’s run in progress, because its result would describe the previous inputs. Restoring matching inputs alone does not clear it. Cancellation, superseded responses, and failed runs do not clear it either; runtime errors remain visible and previous results remain marked. A current successful run clears the mark. Source and runtime updates invalidate retained results too.

Authors can emit an outcome to state whether a successful execution met its computational criterion. Outcomes are marked stale together with tables, charts, and text. They do not replace execution errors.

A producer declares exports and writes each value with export!(name, value). A consumer’s dependsOn binds the producer’s complete export object. A plain cell ID gives an immutable &serde_json::Value; { cell, type } deserializes into a Rust type, including a type from uses. These metadata fields currently support Rust only.

data-model

#[derive(serde::Deserialize)]
pub(crate) struct Dataset {
    pub(crate) points: Vec<i32>,
    pub(crate) truth: i32,
}

Rust + Wasm

Generate data

Cell actions
Cell inputs
let points: Vec<i32> = (0..samples).map(|n| (n + seed) % 17).collect();
let truth = seed;
println!("Generated {} points with seed {seed}", points.len());
export!(points, &points);
export!(truth, &truth);

Run the cell to show its output.

Rust + Wasm

Summarize data

Cell actions
let total: i32 = data.points.iter().sum::<i32>() + data.truth;
println!("Total: {total}");
export!(total, &total);

Run the cell to show its output.

Rust + Wasm

Analyze data

Cell actions
Cell inputs
let total = data["total"].as_i64().ok_or("total must be an integer")?;
println!("Analysis: {}", total + i64::from(bias));

Waiting for the runtime to start.

Dependencies must form an acyclic graph on one page. Running a cell evaluates its complete upstream closure in deterministic order, once per node, using each node’s current complete inputs. Offscreen producers use restored or default inputs, and their results appear when they hydrate. Named cases change only their own cell; oxiquill test-wasm runs prerequisites at their defaults.

Changing a producer input recomputes the producer and its reactive and autorun descendants; prerequisites keep showing their current results while they are reused or recomputed. Button descendants show Upstream changed and wait for Run, except when needed as prerequisites of a reactive descendant. Running or recomputing a producer with unchanged inputs marks descendants only when its exports change. A descendant with invalid inputs is left out until its inputs are valid again; the other descendants still update. Results publish together only while their input snapshots remain current. Failed, timed-out, or cancelled producers prevent dependent execution; consumers link to the producer and its diagnostic. Previous exports are never a fallback.

Exports are separate from rendered outputs: they are never displayed automatically or encoded into share URLs. Every declared export must be written. Undeclared exports, non-finite numbers at any serialization depth, and export objects larger than 4 MiB fail the run without passing partial data onward. Export names match ^[a-z][a-z0-9_]*$; dependency bindings use the same pattern and cannot collide with inputs, generated names, or Rust keywords.

cache: inputs is valid only on a Rust producer with declared exports. It declares that the result is determined by normalized source, used definitions, the runtime-module fingerprint, complete typed inputs, declared exports, and direct dependency result fingerprints. Expose seeds and every other varying quantity as inputs; caching does not detect purity.

Changing only Bias in the example reuses both producers. Switching between previously used seeds can reuse earlier results. Each producer retains at most four results, and all producers on a page share 32 MiB, measured as serialized normalized results and evicted least recently used first. Entries include both displayed output and exports. Failures, cancellations, timeouts, rejected exports, invalid outputs, and truncated results are never cached.

A cache hit shows Reused result for these inputs. Recompute bypasses that producer’s cache and replaces its entry after success. Pressing Run on a cached button-mode producer also forces recomputation. Concurrent requests share matching in-flight computations, with or without cache; cancelling one request leaves work needed by another running.

Source, helper, definitions, or module changes invalidate affected keys. Invalidation follows Rust module boundaries: a rebuilt module invalidates the producers it contains, while producers in unchanged modules keep their results. Coarser groupings such as site therefore invalidate more pages at once. Cache data stays in memory and is cleared when leaving the page or ending the session.