code-playpad
v0.23.2
Published
Embeddable browser code playground: a CodeMirror editor that runs Python, JavaScript, TypeScript, a subset of Java, experimental C/C++, C#, Rust and Go, multi-file React and Next.js in the browser. No backend. One shared worker per page, blocking input(),
Maintainers
Readme
code-playpad
Runnable code in any web page. A CodeMirror editor that executes what it shows — Python, JavaScript, TypeScript, a documented subset of Java, experimental C, C++ and Go, multi-file React, and Next.js App Router projects — entirely in the reader's browser. No backend, no sign-up.
<script type="module" src="https://cdn.jsdelivr.net/npm/[email protected]/dist/standalone.js"></script>
<code-playpad height="auto">
print("hello from a static page")
</code-playpad>Contents — Languages · Experimental C/C++ · Experimental C# · Experimental browser compiler for Rust · Experimental Go · React · Next.js · Install · Attributes · Sizing · Several files · Input · Controlling it from JavaScript · Events and grading · Saving work · Light and dark · Styling · Framework recipes · Production · Worth knowing · Contact
Languages
| language | Runtime | Downloaded at runtime |
| --- | --- | --- |
| python (default) | Python 3.14 via Pyodide — full standard library, input(), real tracebacks, numpy on demand | ~6 MB (13.5 MB unpacked), once, cached |
| javascript | The browser's own engine, in a Worker | nothing |
| typescript | Same engine, types stripped before running | nothing from another service: a ~47 KB (gzipped) transform chunk of this package, loaded the first time a widget needs it |
| java | A documented subset of Java 25, compiled and interpreted in a Worker by an engine built for this package — see Java | nothing: the engine is a ~105 KB (gzipped) chunk of this package, loaded with the first Java widget, and its library a ~75 KB chunk loaded the first time a program uses it |
| c, cpp | Experimental: C17 and C++20, compiled by a real Clang compiler in a Worker — see Experimental C/C++ | ~30 MB on the first C/C++ Run, then cached |
| csharp, cs | Experimental: C# 14, compiled by the real Roslyn compiler on .NET WebAssembly in a Worker — see Experimental C# | ~14 MB on the first C# Run, then cached |
| rust, rs | Experimental browser compiler for Rust, based on rustc 1.99.1: a modified rustc compiled to WebAssembly, in a Worker. Not affiliated with or endorsed by the Rust Project or the Rust Foundation — see Experimental browser compiler for Rust | ~57 MB on the first Rust Run, then cached |
| go, golang | Experimental: Go 1.27, compiled by the official Go 1.27.3 compiler for js/wasm, unmodified, in a Worker. Not affiliated with or endorsed by Google or the Go project — see Experimental Go | ~21 MB on the first Go Run, then cached |
| react | A multi-file React project, rendered in a sandboxed preview with a console — see React | nothing from another service: ~208 KB (gzipped) of this package's chunks, loaded with the first React widget |
| next | A Next.js App Router project, with server components and server actions running in a Worker in the sandboxed preview — see Next.js | nothing from another service: part of this package, loaded the first time a widget runs; Tailwind only for projects that use it |
<code-playpad height="auto">print("python is the default")</code-playpad>
<code-playpad language="javascript" height="auto">
const doubled = [1, 2, 3].map((n) => n * 2);
console.log(doubled);
doubled.reduce((a, b) => a + b, 0)
</code-playpad>
<code-playpad language="typescript" height="auto">
type Point = { x: number; y: number };
const dist = (p: Point): number => Math.hypot(p.x, p.y);
dist({ x: 3, y: 4 })
</code-playpad>A trailing expression prints its value, like a REPL. Each language loads only on pages that use it: a Python-only page never downloads a byte of the JavaScript runtime, and a JavaScript-only page never touches Pyodide's ~6 MB.
TypeScript here erases types, it does not check them — a type error will not
stop your code running. This is a playground, not tsc.
Java
<code-playpad language="java" height="auto">
int visits = 0;
void main() {
greet("Ada");
IO.println("greeted " + visits + " people");
}
void greet(String name) {
visits++;
IO.println("Hello, " + name + "!");
}
</code-playpad>Java runs on an engine written for code-playpad, not on a JVM. It covers a documented subset of Java 25 and checks its behaviour against a real JDK 25:
- Java 25 compact source files and instance
main, or a classicpublic class Mainwithpublic static void main(String[] args) - Objects: several classes per file, nested and inner classes,
constructors and
this(...),new, fields and methods on any object,private, andtoString()with@Override - Classes and interfaces: inheritance with
super, overriding and dispatch,abstractclasses, interfaces with default and static methods,Comparable,equals/hashCodeoverrides,instanceofwith patterns, casts; enums (with fields, methods andswitch) and records - Exceptions:
try/catch/finally, multi-catch, try-with-resources,throw, custom exception classes, checked exceptions checked as javac checks them,printStackTrace(), and traces withCaused by: - Numbers:
int,char,long,doublewith Java's conversions, overflow anddoubleprinting;Math(pow,floorMod,addExact, the trigonometric functions,random, …) andjava.util.Random, whose seeded sequences are the JDK's boolean,String; arrays of any dimension (of objects too); static and instance methods with overloading and recursion; fields- Control flow:
if,while,do,forand enhancedfor,switchstatements and expressions, labeledbreak/continue,return,?: - Strings:
substring,indexOf,split,replace,replaceAll,matches,trim/strip, case,repeat,join,valueOfand the rest, with Java's regex syntax;String.formatandSystem.out.printfwith Java's rounding (%.2fof 1.005 is1.01) System.out/System.err,IO.print/IO.println,System.exit,System.arraycopy,System.nanoTime- Input:
ScanneroverSystem.in(the widget's input box) or aString, withnextInt,nextLine,nextDoubleand the rest, andIO.readln. The classicnextInt()-then-nextLine()pitfall behaves exactly as in Java - Collections and library:
import, generics at use sites with the diamond, boxing;ArrayList,HashMap,HashSet,LinkedHashMap,ArrayDeque,PriorityQueue,TreeMap,TreeSet,LinkedList,Stack,EnumMap,EnumSet, their iterators and enhancedfor,subList;List.of,Map.of,Arrays.asList,toArray;StringBuilder, the wrapper classes,Character,ArraysandCollections. AHashMaporHashSetiterates and prints in the JDK's order. - Big numbers:
BigIntegerandBigDecimal, with the JDK's rounding modes andMathContext - Fast input and output, as competitive programmers write it:
BufferedReader,InputStreamReader,StringTokenizer,StreamTokenizer,PrintWriterandBufferedWriter. Output you forget to flush is lost exactly as on the JDK - Lambdas and method references for any functional interface
(
Integer::compare,Comparator.comparing(...).reversed(),merge,computeIfAbsent), capturing effectively final locals, with stack traces and sorting that match the JDK's (even a comparator that overflows) - Generics: generic classes, interfaces, records and methods with
bounds and wildcards; raw types;
var; varargs;@Override,@SuppressWarnings,@FunctionalInterface; javac's[unchecked]warnings (forList<Integer>[] g = new ArrayList[n], say) printed before the output, as the JDK's source launcher prints them - Anonymous and local classes (
new Comparator<Integer>() { ... }) named and capturing as javac does, and streams:Stream,IntStream,Collectors(groupingBy,toMap,counting,joining, …),Optional, run element by element in the JDK's order - Modern Java:
sealedclasses and interfaces, pattern matching inswitchandinstanceof(record patterns, guards,case null), text blocks, static imports, initializer blocks, enum constants with their own bodies, andInterface.super.method() - More types:
float,byteandshort, with Java's conversions and printing - Errors read like the JDK's: compile errors in javac's format, exceptions with Java stack traces and the JDK's NullPointerException messages
Anything outside the subset (java.time, Pattern and Matcher, parallel
streams, outer.new Inner()) is reported as not supported in this
version rather than run with a different meaning. The file is Main.java
unless entry says otherwise. Since engine 0.27, other .java files in the
widget are compiled as the JDK's launcher compiles them, when the program first
uses their class (see Several files). Packages are not
supported.
Speed. In loop-heavy code the engine runs roughly 150–300 million bytecode instructions a second on a laptop. A typical practice solution (10⁵–10⁶ elements, nested loops, maps, sorting with a comparator) finishes in well under a second. The engine stops a runaway program after 200 million steps (about 0.6–1.5 s of work) and explains why.
Exactly what is supported, feature by feature and method by method, with the evidence behind it and every known difference from the JDK, is in JAVA-COMPATIBILITY.md, which ships in the package.
Experimental C/C++
language="c" (C17) and language="cpp" (C++20) compile and run in a worker
with a real Clang compiler, prefilled stdin and Stop. No setup is needed:
<code-playpad language="cpp" height="auto">
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{3, 1, 2};
std::sort(v.begin(), v.end());
for (int n : v) std::cout << n << " ";
}
</code-playpad>Inside HTML, write < as <. They are experimental:
- The compiler loads on the first C/C++ Run. It is a separate package,
@code-playpad/cpp-toolchain, fetched from jsDelivr and checked by SHA-256. You don't install it, and installingcode-playpaddoesn't download it. A page with a strict Content-Security-Policy must allow the host inconnect-src,blob:inscript-srcandworker-src, and'wasm-unsafe-eval'. To host it yourself, see Production. - Not everything works. Exceptions and threads don't compile, input must be
prefilled (it can't wait for typing), and programs only get stdin, stdout and
stderr. A run stops after 120 seconds; change that with
configureCpp({ timeoutMs }). - Lightly tested on phones. Desktop Chromium, WebKit and Firefox pass the browser suite. One physical phone was checked by hand; memory on phones has not been measured.
Experimental C#
language="csharp" (or cs) compiles C# 14 with the real Roslyn compiler and runs it on
the .NET WebAssembly runtime in a worker, with prefilled stdin and Stop. No setup is needed:
<code-playpad language="csharp" height="auto">
var numbers = new List<int> { 3, 1, 2 };
numbers.Sort();
Console.WriteLine(string.Join(" ", numbers));
</code-playpad>Inside HTML, write < as <. It is experimental:
- The compiler loads on the first C# Run. It is a separate package,
@code-playpad/csharp-toolchain, fetched from jsDelivr and checked by SHA-256 on every Run. You don't install it, and installingcode-playpaddoesn't download it. A page with a strict Content-Security-Policy must allow the host inconnect-src,blob:inscript-srcandworker-src, and'wasm-unsafe-eval'. To host it yourself, see Production. - Every Run starts fresh. Each Run gets a new worker and starts the compiler again, so nothing crosses between Runs. In local tests that took about 1 second on a laptop, and a program with hundreds of methods took 9–13 seconds. An earlier prototype took about 2 seconds on one iPhone; this runtime, which also checks every file on each Run, hasn't been measured on a phone.
- Not everything works. Threads and blocking on an unfinished task throw
PlatformNotSupportedException, thoughawaitworks. Input must be prefilled, and tasks still pending when Main returns are ended with the worker. A project is up to 32.csfiles and 2 MB. A run stops after 120 seconds; change that withconfigureCSharp({ timeoutMs }). - Lightly tested on phones. Desktop Chromium, WebKit and Firefox pass the browser suite. It has been checked by hand in Chrome on one iPhone. Android and Safari on a phone are untested.
- Syntax highlighting needs the optional peer
@codemirror/legacy-modes.
This is an independent project, not affiliated with or endorsed by Microsoft.
Experimental browser compiler for Rust
language="rust" (or rs) compiles a Rust program with code-playpad's experimental browser
compiler for Rust, based on rustc 1.99.1, and runs it in a worker, with prefilled stdin and Stop.
No setup is needed:
<code-playpad language="rust" height="auto">
fn main() {
let mut numbers = vec![3, 1, 2];
numbers.sort();
println!("{numbers:?}");
}
</code-playpad>Inside HTML, write < as < and & as &. The compiler is rustc 1.99.1, modified and
compiled to WebAssembly, with a code generator written for code-playpad in place of LLVM. It is
not the Rust Project's compiler. It is experimental, and it may reject or miscompile programs
the official compiler accepts. This is an independent project, not affiliated with or endorsed
by the Rust Project or the Rust Foundation, and the widget says so in its toolbar.
- What compiles. One
bincrate in edition 2024, with the standard library and no external crates. Other files are modules (mod shapes;readsshapes.rs). It builds without optimisation (opt-level=0), with overflow checks and debug assertions on, and a panic aborts the program. Errors are rustc's own, with file and line. - The compiler loads on the first Rust Run. It is a separate package,
@code-playpad/toolchain-for-rust, fetched from jsDelivr: 18.7 MB for the compiler and 31.6 MB for the standard library, plus 7.1 MB for the linker it shares with C/C++, about 57 MB in all. Every file is checked by SHA-256 and kept in Cache Storage. You don't install it, and installingcode-playpaddoesn't download it. A page with a strict Content-Security-Policy must allowcdn.jsdelivr.netinconnect-src,blob:inscript-srcandworker-src, and'wasm-unsafe-eval'. To host it yourself, see Production. - Speed. In local tests on a laptop, a Run after the first took about 0.2–0.3 seconds in desktop Chrome, Firefox and Safari. The first Run, downloading from jsDelivr, took 10–15 seconds in Chromium, 6 seconds in WebKit and 37–45 seconds in Firefox, on one connection. Each Run gets a fresh worker; the compiled compiler is handed from one to the next.
- Not everything works. No threads, networking or files: a program has stdin, stdout and
stderr only, and input must be prefilled. A Run stops after 120 seconds, counted from the
start of compiling, so the first download doesn't count; change that with
configureRust({ timeoutMs }). A compile that overflows the worker's stack is tried again on the page, which Stop can't interrupt until it returns. Very large functions can exhaust the code generator's memory, and deep recursion in a program overflows sooner in Safari. - Not tested on phones. Desktop Chrome, Firefox, Safari and WebKit pass the browser suite.
- Syntax highlighting needs the optional peer
@codemirror/legacy-modes.
Experimental Go
language="go" (or golang) compiles a Go program with the official Go 1.27.3 compiler and
linker, built for js/wasm from the Go release with no changes, and runs it in a worker, with
prefilled stdin and Stop. No setup is needed:
<code-playpad language="go" height="auto">
package main
import "fmt"
func main() {
for i := range 3 {
fmt.Println("hello", i)
}
}
</code-playpad>Inside HTML, write < as < and & as &. This is an independent project, not
affiliated with or endorsed by Google or the Go project.
- What compiles. One
mainpackage: every.gofile in the top folder (no folders, no_test.gofiles), up to 32 files. A program may import 32 standard-library packages:bufio,bytes,cmp,container/heap,container/list,container/ring,context,encoding/json,errors,fmt,io,iter,maps,math,math/big,math/bits,math/cmplx,math/rand,math/rand/v2,os,regexp,runtime,slices,sort,strconv,strings,sync,sync/atomic,time,unicode,unicode/utf16andunicode/utf8. No modules or third-party packages.//go:directives other thanbuild,generate,noinlineandnosplitare refused. Errors are the Go compiler's own. - The compiler loads on the first Go Run. It is a separate package,
@code-playpad/toolchain-for-go, fetched from jsDelivr: about 21 MB over the network (58 MB unpacked). Every file is checked by SHA-256 (the compiler after it is decompressed) and kept in Cache Storage. You don't install it, and installingcode-playpaddoesn't download it. A page with a strict Content-Security-Policy must allowcdn.jsdelivr.netinconnect-src,blob:inscript-srcandworker-src, and'wasm-unsafe-eval'. To host it yourself, see Production. - Speed. In local tests on a laptop, with the files already downloaded, a first Run took about 1–1.4 seconds and later Runs about 0.1 seconds, in Chromium, Firefox and WebKit.
- Not everything works. No goroutines in parallel (one thread), networking or files: a
program has stdin, stdout and stderr only, and input must be prefilled. Output stops at 1 MB.
A Run stops after 120 seconds; change that with
configureGo({ timeoutMs }). Deep recursion overflows the browser's stack sooner than native Go, and soonest in Safari. A simple recursive function managed 10,000 levels but not 100,000 in Chrome and Firefox, and 2,000 but not 3,000 in WebKit, Safari's engine. - Syntax highlighting needs the optional peer
@codemirror/lang-go.
React
language="react" renders a React project next to the editor, in a sandboxed
frame the reader can click and type into, with a console under it. The layout
matches npm create vite.
<code-playpad language="react" height="auto" preview-height="320" autorun>
<playpad-file name="src/main.jsx">
<script type="text/plain">
import { createRoot } from "react-dom/client";
import App from "./App.jsx";
import "./styles.css";
createRoot(document.getElementById("root")).render(<App />);
</script>
</playpad-file>
<playpad-file name="src/App.jsx">
<script type="text/plain">
import { useState } from "react";
export default function App() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>;
}
</script>
</playpad-file>
<playpad-file name="src/styles.css">
button { font-size: 1.2rem; }
</playpad-file>
</code-playpad>Add file-view="tree" to list the files as a folder tree beside the editor instead
of as tabs. It works for every language. In a React project, the tree (20% of the
width) and the code share the first row, and the preview and console fill the second.
Set the tree's starting width with tree-width: a percentage such as tree-width="35%",
or a number of pixels. The default for other languages is 200 pixels.
Writing files in a page. HTML reads JSX as tags, so <App /> would vanish.
Use one of these:
- Put the code in
<script type="text/plain">, as above: it stays exact and never runs. It can't hold</script>. - Write
<as<, the way every other language does. - Set
pad.files = { ... }from JavaScript, the easiest for generated lessons.
An unescaped <script> inside <playpad-file> runs on your page, outside the
sandbox. The widget warns about tags it finds in a file's markup, but by then that
script has already run.
The project.
index.htmlis optional. Without it, the preview uses<div id="root"></div>and runssrc/main.jsx. With it, its<script src="/src/main.jsx">and project stylesheet links name the entry files, and nothing fetches them.- Files can be in folders. Imports resolve as in Vite:
./and../, and a missing extension tries.jsx,.js,/index.jsxand/index.js. import "./styles.css"adds a<style>, and.jsonimports as data.- The packages are
react,react-dom/client,react/jsx-runtimeandreact/jsx-dev-runtime. Any other import is an error naming the package and file..tsxand CSS Modules aren't supported. - React is 19.2.9, the development build, pinned so quoted warnings stay the same.
Attributes and layout. preview-height sets the preview's height (default 320
pixels). The preview sits beside the editor when the widget is at least 760px wide,
and under it otherwise; that depends on the widget's width, not the screen's. With a
file tree, it always sits under the tree and the code. It runs
on Run or Ctrl/⌘+Enter, and when it nears the viewport if you set autorun.
Resizing. Drag the dividers between the file tree, the code, the preview and the
console, or focus one and use the arrow keys. Double-click a divider to undo. Open in
window moves the project to a separate window that fills with the sections, and
Bring back here or closing that window returns it with its edits. The page keeps
getting the widget's events. pad.openWindow() and pad.closeWindow() do the same; call
openWindow() from a click, or the browser blocks it. To hide the button, use
code-playpad::part(window-button) { display: none; }.
Errors. Compile errors name the file, line and column, with a hint for common JSX
mistakes. Console output goes to the console pane, with React's warnings formatted,
and any error also shows as a banner over the preview. A warning doesn't fail a run.
Runtime errors name the file and line, except in Safari, which keeps that from the
page. An error from a listener added with addEventListener reaches Safari's preview
only as a note to open the developer console.
The sandbox. Code runs in <iframe sandbox="allow-scripts allow-forms">, with an
opaque origin and its own Content-Security-Policy, so it can't reach your page's DOM,
cookies or storage, or use the network.
alert()shows a notice instead of a dialog, because an open dialog freezes your page.confirm()returnstrueandprompt()returnsnull, each with a console note.- Infinite loops. A loop in a project's
.jsor.jsxfile throws after running for 1 second without a break: This loop ran for more than 1 second. Is it infinite? A loop that awaits a timer between steps never trips this. Inline<script>inindex.htmlisn't guarded, and neither is one very long call. If those hang, Stop ends them only where the browser gives the frame its own process, as desktop Chrome does; elsewhere the whole page can freeze. - Each live preview costs about 6–17 MB.
Host pages with a CSP
Your page's Content-Security-Policy also applies inside the frame. Without
'unsafe-inline', the frame needs a nonce: the widget uses the first
<script nonce> on the page, or configureReact({ nonce }). It puts the nonce on its
scripts and on the styles from CSS imports. A blocked preview shows an error after 5
seconds rather than staying blank.
| Your page's policy | Works? |
| --- | --- |
| None, or 'unsafe-inline' in script-src and style-src | Yes |
| script-src 'self' 'nonce-…'; style-src 'self' 'nonce-…' | Yes, with the nonce. A <style> or inline script written in index.html is blocked |
| script-src 'nonce-…' 'strict-dynamic' | Yes, with the nonce, but not with runtimeURL |
This package's tests cover the first two rows, except inline <style> and scripts in index.html. The rest were checked in Chromium only.
Serving the runtime yourself
By default the page sends React to the frame. To have frames load it from a URL, which
starts many widgets a little faster, serve dist/react-runtime-19.2.9.js and:
import { configureReact } from 'code-playpad';
configureReact({ runtimeURL: 'https://your-site.example/react-runtime-19.2.9.js' }); // before any widget runsNext.js
language="next" runs a Next.js App Router project in the browser, with no server
and no build. A worker inside the widget's sandboxed frame plays the server, using
React's real server components packages, and the frame renders what it streams.
<code-playpad language="next" height="auto" preview-height="360" autorun>
<playpad-file name="app/page.tsx">
import { Counter } from './Counter';
export default async function Page() {
const start: number = await Promise.resolve(41);
return <Counter start={start} />;
}
</playpad-file>
<playpad-file name="app/Counter.jsx">
'use client';
import { useState } from 'react';
export function Counter({ start }) {
const [n, setN] = useState(start);
return <button onClick={() => setN(n + 1)}>Count: {n}</button>;
}
</playpad-file>
</code-playpad>This is not Next.js. No code from the next package runs. The router and next/*
are this project's own, checked against recordings of real next dev 16.4.3 (run
scripts/record-next.mjs to record again). entry picks the page it opens at, and
the preview has an address bar, because a sandboxed frame has no URL to show.
| Works | |
|---|---|
| Files | page, layout, template, loading, error, not-found, route (.js, .jsx, .ts, .tsx), under app/ or src/app/. A missing root layout is created, as next dev does, unless a layout in a route group or folder renders <html>: that is a root layout, and every page then needs one |
| Routes | nested layouts, [slug], [...all], [[...all]], (groups), @/ imports |
| Server | async server components, streaming with loading, "use server" files and inline actions, cookies(), headers(), revalidatePath(), redirect(), notFound(), route handlers (fetch('/api/x')), metadata and generateMetadata |
| Client | "use client", next/link, next/form, next/navigation hooks, next/image, next/dynamic |
| Styles | global CSS, CSS Modules, Tailwind 4 (@import "tailwindcss"; its 75 KB gzipped only downloads for projects that use it) |
What differs from real Next:
- There is no server rendering of client components. A client component that reads
windowwhile rendering works here but throwswindow is not definedin real Next, and hydration errors never happen. Every page behaves as undernext dev: nothing is static or cached. - The sandbox stays.
location.pathnameissrcdoc;history.pushStateandlocalStoragethrow;fetchto other sites and remote images are blocked; onlypublic/*.svgis available tonext/image, and only throughnext/image. - Only
react,react-domandnext/*can be imported.next/fontkeeps the browser's default font. - Not available: the
pages/router (an error),proxy/middleware and parallel and intercepting routes (a console warning),use cache,unstable_cache,generateStaticParams,useSelectedLayoutSegment,forbidden(),unauthorized(),global-error. - A project with no
<html>in any layout still runs. The default root layout wraps it, even whennext devwould refuse a page beside a section layout. Once any layout renders<html>, the rules are Next's. - Moving to another root layout resets React state only. Real Next does a full page load, which also resets module variables; here they survive.
- A plain
<a href="/x">keeps client state. Real Next does a full page load, which loses it.next/linkbehaves the same in both. - A plain GET
<form>keeps client state too. Real Next does a full page load; here the router goes to the same URL. A<form>that posts to a stringaction, or leaves for another site, does nothing and says so in the console. Real Next posts it: use a server action orfetch()here. - A route handler's answer is shown as text. Opening one from the address bar, a
Linkor a form shows its status, content type and body, even for HTML. windowduring a client component's render gets no warning, though real Next fails there. A client layout'sparamsgets no warning either; pages do, with real Next's wording.- Each Run is a server restart: module state and cookies start over.
- Not yet measured on a phone. Desktop Chrome, Chromium, Firefox and WebKit pass the browser suite.
- Inline server actions keep their closures in memory. Each declaration keeps its
newest 4,096; a form still holding an older one gets
Failed to find Server Action. - Loops: a loop running over 1 second without yielding throws, on either side.
A host page's CSP must allow everything React previews need,
plus worker-src blob: and script-src blob:. configureReact({ nonce }) applies;
runtimeURL does not. The runtime is about 180 KB gzipped, on demand. A page with no
language="next" widget downloads none of it.
Download size
What a page downloads once a reader presses Run, with the CDN build, as measured for 0.4.0. Each one-widget page was loaded in a browser, and each code-playpad file it fetched was gzipped. The CDN column is what the CDN actually sent.
| Page uses | code-playpad (gzip) | Also fetched from a CDN at run time | 0.3.0 (gzip) | | --- | --- | --- | --- | | Python | 166.3 KB | Pyodide, about 6.0 MB (a 3.3 MB wasm file and a 2.4 MB standard library) | 165.8 KB | | JavaScript | 180.4 KB | nothing | 179.9 KB | | TypeScript | 227.3 KB (0.5.2: with the 46.9 KB transform) | nothing (before 0.5.2: Sucrase from esm.sh, 72 KB) | 179.9 KB | | Java | 288.1 KB (0.8.0: engine 0.39) | nothing | 216.4 KB | | Java, with collections | 373.1 KB (0.8.0) | nothing | 233.2 KB | | C or C++ (experimental) | 187.0 KB | the compiler, about 29.9 MB, from the host you configure | — | | C# (experimental) | 171.2 KB (0.15.0) | the compiler, about 13.8 MB, from jsDelivr or a host you configure | — | | Rust (experimental browser compiler) | 173.0 KB (0.21.0) | the compiler and standard library, about 50.3 MB, and the C/C++ linker, 7.1 MB, from jsDelivr or a host you configure | — | | Go (experimental) | 193.0 KB (0.23.0) | the compiler and standard library, about 20.6 MB, from jsDelivr or a host you configure | — | | All five | 520.0 KB | Pyodide and the C/C++ compiler | 273.9 KB |
- Every row includes a 144.5 KB shared base: the editor (CodeMirror) and the widget, the same as in 0.3.0.
- Each language adds:
- Python: 21.7 KB.
- JavaScript/TypeScript: 35.9 KB.
- Java: 143.5 KB (the 124.5 KB engine plus 19 KB of Java syntax highlighting).
- The first Java program that uses collections,
StringBuilderor another library class also adds the 85.0 KB Java library, once per page. - Since 0.7.0, four parts of the library load only for the first program
that uses them:
java.time16.8 KB,java.math6.7 KB,Pattern/Matcher2.7 KB andBitSet2.3 KB. The rows above leave them out. - C/C++: 42.5 KB (the 7.9 KB runtime plus 34.6 KB of C/C++ syntax highlighting). See the C/C++ note below.
- Go, measured on 0.23.0: 32.1 KB (the 10.7 KB runtime plus 21.4 KB of Go syntax highlighting).
- The Java figures for 0.8.0 are the 0.4.0 measurements plus what the engine's two chunks changed by in the build's gzip sizes (engines 0.28 to 0.39 added the collection staples, library subclasses, the tutorial APIs, regex, java.time, javac's error recovery and messages, packages and more; 0.32 moved the rarely used classes out of the library).
- C and C++ (experimental) were measured on 2026-10-29 as
the difference between pages with and without C/C++. Measured that day,
whole pages come out 4–8 KB larger than this table, with or without the
C/C++ code, so the C/C++ and All five rows add the measured 42.5 KB to this
table's figures. The compiler is the large part: Clang 15.2 MB, the linker 8.8 MB,
and headers and libraries 5.9 MB, gzipped as a host would typically send
them. It downloads on the first Run, from the address given to
configureCpp(by default, jsDelivr), and is cached after that. C and C++ share it, so a page with both downloads it once. 0.3.0 had no C/C++, so its All five figure is its four-language page. - Java grew from 0.3.0 because the subset did, from basic Java to most of what practice programs use (see the version history). The owner treats download size as secondary to coverage. The package's size checks still catch accidental growth: 128 KiB for the Java chunk, 96 KiB for its library and 24 KiB for each part of it.
- Languages load lazily. A Java page never fetches the Python or JavaScript runtimes, and Python and JavaScript pages never fetch Java. As a result, Python-only and JavaScript-only pages are the same size as in 0.3.0.
- Java and TypeScript need no other service: both are self-contained. Since 0.5.2 the TypeScript transform (Sucrase) is a 46.9 KB chunk of this package, loaded the first time a widget needs it (TypeScript, JSX, or JavaScript modules across several files); the TypeScript rows are the measured JavaScript page plus that chunk. Python's first run downloads about 6 MB of Pyodide (cached after that).
- With npm and a bundler, you already ship CodeMirror yourself.
code-playpad's own code then costs about 9 KB, plus the runtime chunk for
each language used. Java's chunk is 104 KB, and 74 KB more for its library
when a program uses it, plus
@codemirror/lang-javaif you install it.
Install
From a CDN — nothing to install
<script type="module" src="https://cdn.jsdelivr.net/npm/[email protected]/dist/standalone.js"></script>This is the standalone build: CodeMirror is bundled in, so a static blog post
or a Markdown-rendered page needs only that one tag. Pin the version — an
unpinned URL follows latest and will change under your readers.
The full path to dist/standalone.js works with every version. The short form,
https://cdn.jsdelivr.net/npm/[email protected], works from 0.3.1 on; with
0.3.0 and earlier it leaves the widgets as plain text, so use the full path for
those.
From npm, with a bundler
npm install code-playpad @codemirror/state @codemirror/view @codemirror/commands \
@codemirror/language @codemirror/autocomplete @codemirror/theme-one-dark @lezer/highlightCodeMirror is a peer dependency so you never end up with two copies of
@codemirror/state. npm and pnpm install the grammars for HTML, CSS and JSON with
it, since any project can hold those files; with Yarn, add them yourself. The other
grammars are optional — install only what you use (@codemirror/lang-python,
@codemirror/lang-javascript, @codemirror/lang-java, @codemirror/lang-cpp,
@codemirror/legacy-modes for C# and Rust); a missing one degrades to plain text rather
than throwing.
import 'code-playpad/element'; // registers <code-playpad>If your bundler is configured to drop side-effect-only imports, register explicitly instead:
import { defineCodePlayPad } from 'code-playpad/element';
defineCodePlayPad();Entry points
| Import | You get |
| --- | --- |
| code-playpad/element | registers <code-playpad>; smallest thing that works |
| code-playpad | the same, plus every helper below |
| code-playpad/react | the <CodePlayPad> React component |
| code-playpad/standalone | CodeMirror bundled in — what the CDN serves |
Importing on a server is safe: without a DOM the element degrades to a no-op, so
Next.js, Astro and SvelteKit need no dynamic import or client:only guard.
Attributes
| | |
| --- | --- |
| language | python (default), javascript, typescript, java, c, cpp, csharp (or cs), rust (or rs), react |
| height | number (px), any CSS length, or auto |
| min-height / max-height | bounds for auto |
| preview-height | react only: the preview's height |
| tree-width | the file tree's width with file-view="tree": 35% or pixels (default 20% for react, 200 pixels otherwise) |
| file-view | how a widget with several files lists them: tabs (default) or tree |
| open-file | which file is on screen to begin with, when not the entry |
| theme | light, dark, or auto (default — follows the reader's saved choice, then the page, then the OS) |
| theme-controls | off hides the theme button and editor theme list |
| readonly | editor cannot be typed into; Run still works |
| autorun | runs once, on its own, when scrolled into view |
| stdin | shows the standard-input box up front |
| persist | key under which edits are saved (see Saving work) |
| file-view-switch | shows a toolbar button that switches between tabs and the tree (see Several files) |
| file-actions | lets the reader add, rename and remove files (see Letting readers change the files). readonly turns it off |
| change-marks | off hides the marks that show code hasn't run yet (see Changes that haven't run) |
| entry | which file Run executes, for multi-file widgets. It must name one of the widget's files: a wrong name is an error, and no other file runs in its place. An inline snippet takes this name |
| practice | Java only: test cases for one method, as JSON (see Practice mode) |
<!-- a worked example nobody should edit -->
<code-playpad height="auto" readonly>
print("read this, don't change it")
</code-playpad>
<!-- output visible before the reader does anything -->
<code-playpad height="auto" autorun>
print("this already ran")
</code-playpad>
<!-- always dark, regardless of the reader's OS setting -->
<code-playpad height="auto" theme="dark">
print("always dark")
</code-playpad>readonly blocks typing but not execution, and the code can still be replaced
from JavaScript — useful for "show the answer" buttons.
Note it is language, not lang: lang is a standard HTML attribute for the
human language of an element's text, and putting python there confuses
screen readers.
Changes that haven't run
Edits are kept as the reader types, but the output only changes when they run the code. So the widget marks what hasn't run yet:
- Run gets a dot, and its tooltip says to run to see the changes.
- Each file that changed since the last run gets a filled
●. A file that differs from what the page shipped but has run gets a hollow○. - The output gets a "Code changed since this run" note in its corner, over the console or the preview. The note sits on top, so the widget doesn't change size.
Before the first run, Run and the files are compared with what the page shipped,
so a reader's restored persist work is marked until they run it. The standard
input box counts as well. Running, or Reset, clears the marks.
change-marks="off" (changeMarks={false} in React) hides all of them, for
example where readers should predict the output before running:
<code-playpad height="auto" change-marks="off">
print(sorted([3, 1, 2]))
</code-playpad>Sizing
height takes a number (pixels), any CSS length, or auto to fit the
snippet:
<code-playpad height="auto">print("no dead space, no hidden lines")</code-playpad>auto is usually what you want. A fixed height has to be guessed per snippet,
and no guess is right at every viewport width — lines wrap, so a 90-character
line is one row on a desktop and three on a phone.
Two bounds go with it:
<!-- a long listing that should not push the page off screen -->
<code-playpad height="auto" max-height="400">…</code-playpad>
<!-- an answer box: one line of content, but room to type -->
<code-playpad height="auto" min-height="170"># Your code here</code-playpad>max-height scrolls rather than clips. min-height grows the editor itself, so
the empty space below a short snippet is still part of the editor and clicking
it puts the cursor there. All three take a bare number as pixels, or any CSS
length (40vh, 30em).
Several files
A widget can hold a small project. Relative imports, packages and data files all work, and tracebacks name the real file and line.
<code-playpad entry="main.py" height="auto" max-height="420">
<playpad-file name="main.py">
from geometry import Circle
print(Circle(1).area())
</playpad-file>
<playpad-file name="geometry/__init__.py">
from .shapes import Circle
</playpad-file>
<playpad-file name="geometry/shapes.py">
from math import pi
class Circle:
def __init__(self, radius): self.radius = radius
def area(self): return pi * self.radius ** 2
</playpad-file>
</code-playpad>JavaScript and TypeScript work the same way, including .json imported as data:
<code-playpad language="javascript" entry="main.js" height="auto">
<playpad-file name="main.js">
import { total } from "./cart.js";
import items from "./items.json";
console.log(total(items));
</playpad-file>
<playpad-file name="cart.js">
export const total = (items) =>
items.reduce((sum, item) => sum + item.price, 0);
</playpad-file>
<playpad-file name="items.json">
[{ "price": 12 }, { "price": 30 }]
</playpad-file>
</code-playpad>Java compiles the other files as java Main.java does (JDK 25's source
launcher): Main.java runs, and Session.java is compiled when Main first
uses Session. Each file is named after its class and has its own imports, and
errors and stack traces name the file. A .java file in a folder belongs to that
folder's package (util/Tool.java declares package util;). Write < as < inside the markup (List<String>),
since it is HTML:
<code-playpad language="java" entry="Main.java" height="auto">
<playpad-file name="Main.java">
public class Main {
public static void main(String[] args) {
Session s = new Session("loops", 30);
System.out.println(s.describe());
}
}
</playpad-file>
<playpad-file name="Session.java">
public class Session {
private final String topic;
private final int minutes;
Session(String topic, int minutes) {
this.topic = topic;
this.minutes = minutes;
}
String describe() { return topic + ": " + minutes + " min"; }
}
</playpad-file>
</code-playpad>A tab bar appears once there is more than one file, with ▸ marking the entry
point, and each file keeps its own undo history. Editing a module takes effect
on the next run — the import cache is cleared between runs.
Highlighting follows the file, not the runtime: a .json beside your
JavaScript is highlighted as JSON, a .csv beside your Python is plain text.
Letting readers switch the view
Add file-view-switch (fileViewSwitch on the React wrapper) to show a toolbar button
that switches between tabs and the tree. It's off by default, and it only shows when the
widget has a file list. file-view sets the view it starts in, and the button changes that
attribute, so a page can read the current view from it. The choice isn't saved: a reload
goes back to the page's file-view.
The widget's height can change with the view, because tabs take a row above the code and a tree doesn't. In a wide React or Next.js widget the layout changes as well, since the preview sits beside the code with tabs and under it with a tree.
Letting readers change the files
Add file-actions (fileActions on the React wrapper) and a reader can add, rename
and remove files from inside the widget. It works for every language, and it's off by
default.
<code-playpad language="react" file-view="tree" file-actions>- In a tree, the header has New file and New folder buttons, and each folder has a
+for a new file inside it. They add to the open file's folder until you choose another place: click a folder to add there, or click Files to add at the top level. Opening a file goes back to that file's folder. The name box appears where the file will go. - In tabs, a
+ends the row. Tabs have no folder rows, so the name box starts with the open file's folder (src/), and you edit that text to put the file elsewhere. - A folder needs a file. A new folder asks for its first file straight away. It's
saved when that file is created, and Escape takes it away. In either view, a name such
as
components/TaskLine.jsxcreates the folders it needs. A folder disappears with its last file. - Rename and remove are in each file's
⋯button. Removing a file with code in it asks first. - The file bar always shows, even with one file, and the file list scrolls, so changing files never resizes the widget. New files start empty, and importing one before writing it gives that language's normal run error. Renaming a file doesn't change the imports that name it.
Some names and files are refused:
| Case | What happens |
| --- | --- |
| An empty name, a backslash, or an empty, . or .. folder | Refused, with a message by the name box |
| A name that exists | Refused, and the existing file opens, unchanged |
| A name that's a folder, or a path through a file | Refused, with a message |
| The only file, or the entry file | Nothing is offered |
| Files the language needs: in React, index.html, src/main.jsx and what index.html loads; in Next.js, the root layout | Nothing is offered |
A file a reader adds never takes over as the entry, even if it's called main.py.
Input
input() blocks for real. The prompt appears, a caret waits at the end of the
output, and the program continues when a line is sent — echoed the way a
terminal echoes typing:
name? Ada
age? 36
hello Ada, next year you turn 37Enter sends a line; EOF (or Ctrl-D) ends input, which is how you finish
a while True: loop.
In JavaScript and TypeScript, input() is a global returning a promise, so
await works at the top level:
<code-playpad language="javascript" height="auto">
const name = await input("your name? ");
console.log(`hello ${name}`);
</code-playpad>To script the answers instead of typing them — useful for a worked example — pre-fill the box. Those lines are used before the reader is asked:
<code-playpad height="auto" stdin>
name = input("name? ")
print("hi", name)
</code-playpad>To put the sample in the page itself, add a <playpad-stdin> child. Its text
is used exactly as written, with its leading spaces, blank lines and final
newline, so start it on the same line as the tag. A last line without a newline
stays without one. Like any text box, the input box turns carriage returns into
newlines. It opens the box, isn't part of the code, and Reset puts it back:
<code-playpad language="rust" height="auto">
<playpad-file name="main.rs">
use std::io::Read;
fn main() {
let mut input = String::new();
std::io::stdin().read_to_string(&mut input).unwrap();
println!("{} lines", input.lines().count());
}
</playpad-file>
<playpad-stdin>3 4
10 20
</playpad-stdin>
</code-playpad>From JavaScript, set the stdin property. It wins over a <playpad-stdin>
sample, even when it is set before code-playpad has loaded:
document.querySelector('code-playpad').stdin = 'Ada\n36';Echoed input is display-only: stdout stays exactly what the program printed,
so graders are unaffected.
Java reads the box as its standard input. new Scanner(System.in) and
IO.readln() see all of it at once, as when input is piped to java Main.java:
the program never stops to wait, and the input is not echoed into the output.
A program that reads past the end fails with the JDK's
NoSuchElementException, and the widget opens the box with a hint, as it
does for Python's input().
<code-playpad id="times" language="java" height="auto" stdin>
import java.util.Scanner;
void main() {
Scanner in = new Scanner(System.in);
IO.println(in.nextInt() * in.nextInt());
}
</code-playpad>
<script>
document.getElementById('times').stdin = '3 4';
</script>Controlling it from JavaScript
const pad = document.querySelector('code-playpad');
pad.code = 'print("set from outside")'; // replace the visible file
const source = pad.getCode(); // read it back
const result = await pad.run(); // { stdout, stderr?, value?, durationMs }
pad.reset(); // back to the snippet the page shipped
pad.stop(); // stop this widget's run, queued or running
await pad.prewarm(); // boot the runtime before the reader runs anythingMulti-file widgets add:
pad.files = { // replace the whole project
'main.py': 'from util import shout\nprint(shout("hi"))',
'util.py': 'def shout(s): return s.upper() + "!"'
};
pad.entry = 'main.py'; // which file Run executes
pad.openFile('util.py'); // bring a tab on screen
const everything = pad.getFiles(); // { name: contents }
pad.addFile('src/TaskLine.jsx', ''); // add and open a file; contents are optional
pad.renameFile('src/old.jsx', 'src/new.jsx');
pad.removeFile('src/old.jsx');addFile, renameFile and removeFile follow the same rules
as the reader's controls, and throw an error saying why when a rule refuses the change. An
existing name throws too, without opening that file. They work with or without file-actions.
prewarm() is worth calling when you know the reader is about to run something
— on a lesson page, for instance — so the ~6 MB Python download starts before
they press Run rather than after.
Events and grading
Four events bubble and cross the shadow boundary, so answer-checking lives outside the widget rather than inside it. They fire for every language:
| event | event.detail |
| --- | --- |
| playpad-ready | { language, label } — runtime booted |
| playpad-run | { code, entry, files, language } — a run started |
| playpad-output | { stdout, stderr?, value?, table?, durationMs, failed, language } |
| playpad-error | { message, hint?, language } |
Each one is also fired under its original name, py-ready, py-run,
py-output and py-error (first, with the same detail), from before the
widget ran anything but Python. Existing pages keep working; new code should
listen for the playpad-* names.
failed says whether the run failed, and playpad-error fires exactly when it
did. For Python and JavaScript, any stderr output counts as a failure. For Java,
the run's own status decides: an exception, a compile error or a non-zero
System.exit fail, while javac's [unchecked] warnings and System.err output
from a program that finished normally do not. That is how a terminal reads it;
the warnings are still printed, and still in stderr.
React differs, because an app keeps running after its run:
playpad-runfires when the run starts, andplaypad-outputwhen the entry module has loaded.failedis true only if loading threw. The output holds the console lines so far.playpad-erroralso fires for later errors, such as one in a click handler, and addsfile,lineandcolumnwhen known.playpad-consolefires per line, with{ level, text, language }.playpad-renderfires after#rootchanges, at most every 100 ms, with{ rootText, language }. Learner code can forge it, so use it to check a lesson, not as proof of completion.
These two new events have no py-* name.
playpad-files-change fires when the reader or addFile, renameFile or removeFile
changes the file list, but not when you assign pad.files. It has no py-* name either.
Its detail is { action, name, previousName?, files }, where action is add, rename
or remove, and previousName is there for a rename.
A complete exercise check:
<code-playpad id="ex1" height="auto" min-height="150" persist="ex1">
# Print the numbers 1 to 5, one per line.
</code-playpad>
<p id="ex1-result"></p>const expected = '1\n2\n3\n4\n5\n';
document.addEventListener('playpad-output', (event) => {
if (event.target.id !== 'ex1') return;
const el = document.getElementById('ex1-result');
if (event.detail.failed) {
el.textContent = 'Your code raised an error — read the message above.';
} else if (event.detail.stdout === expected) {
el.textContent = '✅ Correct';
} else {
el.textContent = `❌ Expected ${JSON.stringify(expected)}, got ${JSON.stringify(event.detail.stdout)}`;
}
});playpad-error also carries a hint when the runtime can explain the failure in
plain language — for example when a program calls input() more times than the
standard-input box has lines.
Practice mode (Java)
For LeetCode-style exercises, give a Java widget test cases for one method.
Run then calls that method once per case, instead of running main (no
main is needed), and reports each case. The output shows one line per
case and the tally; the status line says "2 of 3 passed".
<code-playpad language="java" height="auto"
practice='{"method": "lowerBound", "cases": [
{"args": [[1, 3, 3, 8], 3], "expected": 1},
{"args": [[1, 3, 3, 8], 9], "expected": 4},
{"args": [[], 5], "expected": 0}]}'>
class Solution {
static int lowerBound(int[] sorted, int target) {
return 0; // your code here
}
}
</code-playpad>Or set it from JavaScript (el.practice = { method, cases }), or pass the
practice prop to the React component. Each case's result arrives in
playpad-output as detail.cases, with detail.passed and detail.total,
so grading code can read them instead of comparing text:
document.addEventListener('playpad-output', (event) => {
const { cases, passed, total } = event.detail;
if (cases) console.log(`${passed} of ${total}`, cases.filter((c) => c.status !== 'passed'));
});The spec. method (required); cases, each { args, expected?, id? };
className when several classes have a method of that name; params
(["int[]", "int"]) to choose among overloads; compare: { kind: "argument",
index: 1 } to check an argument after the call, for a void method that
fills one in; tolerance in compare for doubles; nodes to describe a
linked-list or tree class whose fields do not make its shape obvious.
Values are JSON, the same way for arguments, expected and the
reported actual:
| Java | JSON |
| --- | --- |
| int, boolean, String, wrapper types | number, boolean, string, null |
| long | a decimal string, "4000000000" |
| char | a one-character string |
| double | a number, or "NaN", "Infinity", "-Infinity" |
| arrays, List / ArrayList | arrays (nested for int[][], List<List<Integer>>) |
| linked-list nodes (a class with one field of its own type) | the values in order, [1, 2, 3] |
| tree nodes (two fields of its own type) | level order with null gaps, [3, 9, 20, null, null, 15, 7] |
Maps, sets and Object cannot be passed or returned yet.
Each case's status: passed, failed (with expected and
actual), completed (no expected was given), runtime-error (with
error, the stack trace), resource-limit, engine-limitation,
invalid-case (the JSON does not fit the parameters: the exercise's
mistake, not the learner's) and not-run (with a reason, such as
compile-error). Each case also has what it printed (stdout, stderr).
Every case runs on fresh state: static fields start over.
Saving work
persist stores the whole file map in IndexedDB, so a reader's edits survive
navigation and a full reload:
<code-playpad height="auto" persist="lesson-3-exercise-1">
# Your code here
</code-playpad>The page's file list stays authoritative: edits come back, but files you add or remove later follow the page, not the old snapshot.
With file-actions as well, the reader's file list wins, so files they added, renamed
or removed survive a reload. What you change on the page later still reaches them:
- A file you add appears.
- A file you remove goes, unless they edited it.
- A file you change updates, unless they edited it.
- A starter file they removed stays removed, unless the widget can't run without it.
The Reset button restores the page's files and contents, and asks first if that would take
away or bring back files. pad.reset() doesn't ask.
For a course you usually also want completion state, which the package exports:
import { setProgress, getProgress, allProgress, loadSnippet, clearSnippet } from 'code-playpad';
// mark a lesson done when its exercise passes
document.addEventListener('playpad-output', async (event) => {
if (event.detail.stdout === expected) {
await setProgress('lesson-3', { completed: true, score: 100 });
}
});
await getProgress('lesson-3'); // { id, completed, score, updatedAt }
await allProgress(); // every record, for a progress bar
await loadSnippet('lesson-3-exercise-1'); // what the reader last wrote
await clearSnippet('lesson-3-exercise-1'); // a "start over" buttonAll of it is per-browser: nothing leaves the reader's machine.
Light and dark
theme takes light, dark, or auto (the default).
<code-playpad theme="dark" height="auto">print("always dark")</code-playpad>
<code-playpad theme="light" height="auto">print("always light")</code-playpad>
<code-playpad height="auto">print("follows the page, then the OS")</code-playpad>auto follows your site first, the operating system second. If your page
has its own light/dark switch, the widget follows it as long as the switch sets
color-scheme on the root element — which is how most themes are written:
:root { color-scheme: light; }
:root[data-theme="dark"] { color-scheme: dark; }Flip data-theme (or a class, or an inline style) and every widget on the page
re-themes itself. Nothing else to wire up. With no color-scheme on the page,
auto falls back to the reader's OS setting via prefers-color-scheme.
If your theme switch does not set color-scheme, drive the widgets directly:
function setTheme(mode) { // mode: 'light' | 'dark'
document.documentElement.dataset.theme = mode;
for (const pad of document.querySelectorAll('code-playpad')) {
pad.setAttribute('theme', mode);
}
}An explicit theme attribute always wins over the page, so a deliberately dark
snippet stays dark on a light page.
The reader's choice
Each widget has a moon or sun button and an editor theme list. The ids, for
setThemePreference, are default-dark (One Dark), monokai, dracula, nord,
solarized-dark, default-light, github-light and solarized-light.
The choice is saved in localStorage and every widget on the same site follows
it, including other tabs and separate windows. Picking a theme also restyles the
widget's toolbar and output, but not a React project's own preview.
The order is: an explicit theme attribute, then the reader's choice, then the
page's color-scheme, then the OS. A widget with an explicit theme shows no
controls, and uses the reader's editor theme for that mode. Your --cp-* colours
still win over an editor theme's.
If your site has its own switch, connect it, or hide the widget's controls with
theme-controls="off":
import { setThemePreference, onThemePreferenceChange } from 'code-playpad';
setThemePreference({ mode: 'dark', dark: 'monokai' });
onThemePreferenceChange(({ mode }) => {
if (mode) document.documentElement.dataset.theme = mode;
});Styling
The widget lives in a shadow root, so page CSS cannot leak in — and its own styles cannot leak out. Two supported ways to restyle it.
Custom properties inherit through the shadow boundary:
code-playpad {
--cp-accent: #b5179e; /* buttons, focus, the caret */
--cp-radius: 14px;
--cp-font-mono: "JetBrains Mono", monospace;
}| | |
| --- | --- |
| colours | --cp-bg, --cp-fg, --cp-muted, --cp-border, --cp-surface |
| accents | --cp-accent, --cp-accent-fg, --cp-danger, --cp-ok |
| shape and type | --cp-radius, --cp-font-mono, --cp-font-ui |
Parts expose the pieces worth targeting:
code-playpad::part(run-button) { border-radius: 999px; }
code-playpad::part(stop-button) { font-weight: 700; }
code-playpad::part(output) { background: #fff7fb; }
code-playpad::part(tabs) { border-bottom-width: 2px; }The other parts are file-view-button, theme-button, editor-theme-picker, window-button,
stale-note, preview, and notice (a line some runtimes show in the toolbar, such as a
compiler's statement that it is not affiliated with the language's project).
Both work from an ordinary stylesheet, no ::shadow hacks. For dark mode, see
Light and dark.
Framework recipes
Astro — put the import in a page or layout script; the element does the rest.
---
// src/layouts/Lesson.astro
---
<script>
import 'code-playpad/element';
</script>
<code-playpad height="auto" persist={Astro.props.id}>
{Astro.props.code}
</code-playpad>React — the wrapper assigns props through a ref, so React 18 behaves like 19.
import { useState } from 'react';
import { CodePlayPad } from 'code-playpad/react';
export function Exercise() {
const [passed, setPassed] = useState(false);
return (
<>
<CodePlayPad
language="python"
code={'# Your code here'}
height="auto"
minHeight={150}
persist="exercise-1"
onOutput={(r) => setPassed(r.stdout.trim() === '42')}
/>
{passed && <p>✅ Correct</p>}
</>
);
}Props: code, files, entry, openFile, language, height, minHeight,
maxHeight, previewHeight, treeWidth, fileView, stdin, theme, themeControls, changeMarks,
readOnly, autoRun, persist, practice, className, style, and the
callbacks onReady, onRun, onOutput, onError.
Next.js — the element is SSR-safe, so a plain import works in a client component:
'use client';
import 'code-playpad/element';
export default function Lesson() {
return <code-playpad height="auto">{'print("hi")'}</code-playpad>;
}Vue — tell the compiler the tag is a custom element, then use it directly:
// vite.config.js
export default {
plugins: [vue({ template: { compilerOptions: { isCustomElement: (tag) => tag === 'code-playpad' } } })]
};Plain HTML / Markdown — the CDN tag plus the element. Because the code lives in the element's text content, the snippet is still readable if JavaScript never loads.
Production
Serve Pyodide from your own origin so you control its cache headers, rather than depending on a public CDN:
import { configurePython, pyodideAssetUrls } from 'code-playpad';
configurePython({ indexURL: '/pyodide/' }); // before the first run
pyodideAssetUrls(); // the files worth <link rel=preload>-ingThe TypeScript transform needs no configuration: it ships in the package (since
0.5.2) and loads from wherever the package is served. configureTypeScript({
sucraseURL }) loads it from a URL of your own instead
