Upstream: WEB.md at
65f8eb43f710, MIT © Anomaly. Bundled by build-rune-apps; links point at this snapshot or at GitHub at that rev.
Run a Rune app in the browser
Rune's experimental web target renders one canvas through WebGPU. It uses the same Rust views, layout, glyph atlas and shaders as native. GPU initialization is asynchronous; the runtime stays on the browser's main thread and requests frames only while work is pending.
Build the example
Install the wasm target, Python 3.11 or newer, and the wasm-bindgen CLI version in Cargo.lock:
rustup target add wasm32-unknown-unknown
cargo install wasm-bindgen-cli --version 0.2.129 --locked
scripts/web-build.sh web-hello --out target/web
Serve the entire output folder over HTTPS, including snippets/. A local HTTP server on
localhost also works for development. The host must serve .wasm as application/wasm.
No application server, SharedArrayBuffer, COOP or COEP headers are required.
--opt additionally runs an installed wasm-opt -Oz; the default build does not need it.
A release build drops the wasm's function-name section, so a panic's stack shows offsets
instead of Rust names; --names keeps it for profiling, and --dev builds always keep it.
The script prints the raw and gzip wasm sizes. Configure gzip or Brotli on the static host
to get the corresponding transfer size.
usage: web-build.sh PACKAGE [--example NAME] [--out DIR] [--opt] [--dev] [--watch] [--no-html] [--names]
The script builds with the toolchain's own cargo (rustup which cargo), not a cargo wrapper
on PATH that might build on another machine, and stops with a message if the wasm isn't in
the local target folder afterwards. Set CARGO to pick the cargo binary.
The example is a scrollable message list with a composer, Send and Copy last. Its title opens an external link. Refreshing resets the in-memory messages.
Edit and reload
--dev builds fast instead of small: the debug profile without debug info, with dependencies
(Rune included) at opt-level 1 and your package unoptimized, in its own web-dev target folder
so it never rebuilds the release cache. It skips --opt. The wasm is about twice the release
size; don't ship it. On web-hello, a one-line change rebuilds in about 2 s, against 12 s for
a release build.
--watch rebuilds whenever a file in a workspace member changes (polling, no extra tools), and
the page reloads itself after each successful build. Serve the folder from a second terminal:
scripts/web-build.sh web-hello --dev --watch
python3 -m http.server 8000 -d target/web # then open http://localhost:8000
WebGPU works over plain HTTP on localhost; from another machine the page needs HTTPS. In
watch mode the script writes reload.js, which polls .stamp in the same folder and reloads
when a build changes it, and the generated page cache-busts app.js and app_bg.wasm. A
failed build leaves the page as it was. Each build stages its files in .next and renames them
into place, so a page loading mid-build gets one build's app.js and app_bg.wasm. Reloading
resets the app's state.
Your own page
The script writes index.html only if there is none, or if the existing one still has the
generated by rune web-build.sh comment, so a page of your own (with App::canvas_id and
fit_content_height, say) is kept. Delete that comment line to keep edits to the generated
page. --no-html never writes index.html. To reload your own page in watch mode, add
<script src="https://raw.githubusercontent.com/anomalyco/rune/65f8eb43f710e078f92cb82039212de50cb03113/reload.js"></script> while developing.
Give your app a wasm entrypoint
Add a cdylib target and a wasm-only wasm-bindgen dependency:
[lib]
crate-type = ["cdylib", "rlib"]
[target.'cfg(target_arch = "wasm32")'.dependencies]
wasm-bindgen = "0.2"
Export a start function that calls the usual Rune entrypoint:
#[cfg_attr(target_arch = "wasm32", wasm_bindgen::prelude::wasm_bindgen(start))]
pub fn start() {
rune::run(AppSpec::new("My app", (390.0, 760.0), State::default, view));
}
From your app's workspace, run path/to/rune/scripts/web-build.sh your-package. The script
selects one cdylib, or one binary if there is no cdylib. --example NAME selects a Cargo
example. Disable Rune's dev, hot and native-file-dialog features on wasm. Move native
filesystem, process and thread dependencies behind target conditions in your app too.
Use rune::time::Instant for deadlines passed to Rune; it is std::time::Instant on native.
Luau scripts
An app that hosts Luau with rune-luau builds for the web too: Luau's C++ compiles with
WASI SDK (33 or newer) against WASI libc, using
WebAssembly exception handling. Unpack the SDK and point WASI_SDK_PATH at it; web-build.sh
then sets the C and C++ compilers for the wasm target, and rune-luau links the SDK's C runtime
and defines the WASI calls libc makes inside the module, so the page loads like any other
Rune app. Luau runs as its interpreter there.
WASI_SDK_PATH=$HOME/wasi-sdk-34.0 scripts/web-build.sh luau-panel --out target/web-luau
node examples/luau-panel/web-proof.mjs target/web-luau target/web-luau-proof
Browsers with exception handling run it: current Chrome, Edge, Firefox and Safari.
Mount in a page
By default Rune appends its own canvas, covers the viewport and stops the body scrolling.
App::canvas_id("id") mounts onto a <canvas id="id"> the page already has instead:
// Inline in an article, as tall as its content; the page keeps scrolling.
App::new(spec).canvas_id("chart").fit_content_height().try_run()?;
// Full screen inside a single-page app's route, which owns the canvas.
App::new(spec).canvas_id("route-canvas").full_viewport().try_run()?;
Inline, the canvas is as wide as its parent and as tall as AppSpec::size (or its content with
fit_content_height, when vertical wheel and touch pans scroll the page); safe-area insets
are zero and the title doesn't touch document.title. With full_viewport the canvas is fixed to
the visual viewport like Rune's own, so an ancestor with a transform or filter would
become its containing block; mount it outside one.
AppHandle::quit unmounts the app when its route goes away: the loop stops, the GPU device is
destroyed, Rune's listeners come off the page, and the body style and title it changed go back.
Rune removes a canvas it made; a passed-in canvas stays, with its own style and attributes
back, for the page to remove. One app runs per page at a time. An app started while another is
quitting mounts once that one has gone, so a route can swap apps in the same tick:
let handle = app.handle(); // keep it with the route
App::new(spec).canvas_id("route-canvas").full_viewport().try_run()?; // after handle.quit()
A whole web page
App::web_document() makes the app the page itself, for a marketing site, docs or an article.
The root lays out at its natural height and the browser scrolls the document, so trackpad
momentum, the scroll bar, Page Down, Space, find-in-page, anchors and back/forward are the
browser's own. The canvas stays fixed to the viewport and draws the band the page is scrolled to;
a scroll moves only that band and rebuilds nothing.
Above the canvas Rune keeps a DOM mirror of the scene: landmarks (role("main"),
role("region"), role("navigation"), role("contentinfo")), headings with their level,
paragraphs, links and images, each at its element's place. Keys become element ids, so
#views scrolls to the element keyed views. Its text is transparent but real, so the browser
selects and copies it, and screen readers, crawlers and link previews read it. An element with
El::href(url) is an <a href>: middle-click, Cmd-click and Copy Link work, and a plain click
opens it in the same tab. Tab moves through the mirror's links and buttons; a press on one runs
the element's handler. The page tints selections and focus rings with --rune-selection and
--rune-focus, and sets the mirror's fonts with --rune-sans and --rune-mono, so match them
to the fonts the app draws with.
A static first frame
--html out.html lays the app out without a GPU, lets entrance motion land, and writes the
scene as HTML and CSS: each element's flexbox style, paint and text, with the same tags the
mirror uses. The browser draws that page before the wasm arrives, and a reader without WebGPU
(or with scripts off) keeps a readable page:
cargo run -p site -- --html dist/index.html --html-widths 360,640,1000 --html-template index.html
Each width in --html-widths lays the page out again; the narrowest is the base and each wider
one adds a @media (min-width) block where it differs, so the layout holds between the widths
taken. --html-template fills <!-- rune:css --> and <!-- rune:body --> in a page that
carries your meta tags. When Rune's first frame is on screen it removes the exported elements
([data-rune-static]), keeping the section at the top of the window where it was, and the
canvas dispatches a bubbling runepresent event. An image is exported as <img> when its
pixels came from ImageCache::url or ImageCache::file; shapes become inline SVG. Grid layout
and effects drawn by shaders (rune-fx, materials) aren't exported; give such an element a
fill to stand in for it.
Images
ImageCache::url fetches an image and lets the browser decode it with its own codecs
(createImageBitmap, off the main thread), so WebP, AVIF and anything else the browser reads
work, turned upright by EXIF orientation. The pixels land through the same mip path as
ImageCache::rgba and the cache's waker draws the frame. ImageCache::file does the same on
web with its path as a URL relative to the page, so one call loads a bundled asset in both
builds:
let logo = cache.file("assets/logo.webp", 48.0, env.scale); // disk on native, fetched on web
let avatar = cache.url(&user.avatar_url, 32.0, env.scale); // size and scale matter for SVG only
SVG (by Content-Type or a .svg/.svgz path) rasterizes with Rune's renderer at the size
asked for. Images over 8192 pixels a side are refused before their pixels are read, and a
failed request or a cross-origin image without CORS headers resolves to Image::error.
Cursor::Image sets the canvas's CSS cursor to the PNG at 2x (image-set(url(blob:…) 2x)),
so the browser decodes it and draws it at its size in points on any display.
Fonts and browser input
Web includes Inter Regular and IBM Plex Mono Regular (the embedded-fonts feature). There is
no system-font discovery. App::font_url("fonts/brand.ttf") fetches a TrueType or OpenType
font (not WOFF2) alongside GPU setup, before the first frame, and adds it to AppSpec::fonts;
on native it reads the same path from disk. Point the page's @font-face at the same file so the
browser downloads it once, and build with default-features = false to drop the embedded fonts.
Set AppSpec::fonts to static font bytes and AppSpec::families to your sans/mono family
names for branding, additional weights, emoji and scripts outside the default fonts.
For example, extend a static slice of rune_theme_opencode::FONTS with
include_bytes!("assets/NotoColorEmoji.ttf") and the CJK fonts your app needs, then assign
the combined slice to spec.fonts. Keep the theme's sans/mono family names in spec.families.
Missing emoji and CJK glyphs display fallback boxes; they do not trigger font downloads.
The embedded Inter is cut to Latin, Greek and Cyrillic text (Latin-1, Latin Extended-A, modern
Greek, Cyrillic, punctuation, arrows and the Mac's key symbols), under half its size. Once the
first frame is up the app fetches the full faces, Inter-Regular.ttf, Inter-Medium.ttf and
Inter-SemiBold.ttf, from beside app.js; scripts/web-build.sh copies them there. Text the
cut covers draws the same before and after; other text (Vietnamese, polytonic Greek, Cyrillic
beyond Russian, Ukrainian, Belarusian, Serbian, Macedonian and Bulgarian) draws in fallback
fonts or boxes until they arrive, and stays that way, with a console warning, on a host that
doesn't serve them.
In a Mac's browser text draws with macOS font smoothing (FontSmoothing::On), as Safari,
Chrome and Firefox draw the page's own text there, and without it elsewhere, iPhone and iPad
included. App::font_smoothing sets it either way.
Rust supplies the hidden textarea with up to 512 UTF-16 units on each side of the selection,
expanding for the selected range, and skips unchanged mirrors. Browser input events supply replacements; Rune validates the mirrored
context and converts window-relative UTF-16 positions to UTF-8 boundaries before editing.
Composition holds the mirror stable until commit and replaces the composing word's range.
Mobile beforeinput line breaks use Rune's Enter rules: submit, or Shift/Alt+Enter newline
in a multiline field. A completed touch tap focuses the editor synchronously;
a pan scrolls instead, with momentum and a damped edge return.
Secure fields use an <input type="password"> with autocomplete, autocorrect and spellcheck
disabled. It receives only new keystrokes and is emptied after every input; the model's
secret is never mirrored into the DOM. Leaving a field returns focus to the canvas so
shortcuts and Tab keep working. Continuous pointer movement and wheel events wait for rAF.
Tx::copy and Tx::request_paste use the browser clipboard. Call them from a user input
handler: permission and transient-activation rules still apply. Native Paste events work
without an asynchronous clipboard read. Secret-copy requests report failure because the
browser cannot promise native clipboard-history exclusion or conditional timed clearing.
rune::web::open_url accepts HTTP(S) and mail links and opens a tab with noopener,noreferrer.
Call it from a user input handler. Tx::open_url_same_tab (or rune::web::open_url_same_tab)
replaces the page instead, and takes links relative to the page (/notes/42). A single-page
app routes those itself with App::same_tab_router: it gets the absolute URL of each link on
the page's origin and returns true when it handled it; otherwise, and for other origins, the
browser loads the link with location.assign.
App::new(spec).same_tab_router(|href| router.push(href)) // true: routed with pushState
tx.open_url_same_tab("/notes/42")?; // from a handler
Cx::safe_area() returns top/right/bottom/left insets in
points (zero on native). Apply them inside a full-canvas background. The canvas follows
visualViewport when a software keyboard reduces the visible height. Keep the generated
page's viewport-fit=cover meta tag and the textarea's 16 px font size.
Scope and verification
This target needs WebGPU. It has no WebGL fallback (a page made with --html stays readable
without it), overlays,
extra windows, native menus, drag-out, native audio/video, networking layer or hot patching.
Native configuration types remain source-compatible, but their desktop host paths are not
used on wasm. Unsupported window requests warn in the console; Show/Open are ignored.
The document title follows AppSpec::title, and hidden tabs report is_visible() == false.
The functional proof uses headless Chromium and Playwright:
node scripts/web-smoke.mjs target/web target/web-proof
Install Playwright with its Chromium browser first. PLAYWRIGHT_MODULE and CHROMIUM_PATH
can select an existing installation. WEB_ENGINE=webkit tries an installed Playwright WebKit
and reports whether it has a WebGPU adapter. The proof checks GPU errors, idle rAF requests
and submissions, touch
focus and momentum, Unicode edits, a long sliding context, predictive replacement,
composition, selection, paste, copied model text, link isolation, theme and viewport resize.
In Chromium it also installs Playwright's fake clock after the app has started and checks that
a touch fling waits for clock.runFor instead of finishing in real time: Rune reads the page's
current performance.now() on every frame, so a capture can step it frame by frame.
The ?input-proof fixture adds password input, Tab/Escape focus, mobile Enter, recomposition,
same-field focus stability, continuous-input coalescing and visibility regression checks.
Its mobile DPR check exercises the Safari-style CSS-size fallback because Chromium device
emulation does not scale devicePixelContentBoxSize. This is not a real iPhone keyboard,
dictation, autocorrect or Safari WebGPU test; those still need device verification.
The shell follows PLAN's winit-first approach, retaining winit 0.30's rAF and ResizeObserver implementation. Unlike research/11's proposed custom shell, it adds a document-aware textarea beside winit rather than replacing winit. This also defers PLAN's proposed switch to an owned shell when text input lands. WebGL fallback and EditContext from that research remain later work.