A tiny reactive framework
Node 22 or newer is required (the framework itself ships no runtime dependencies; Node is needed only to build it and to serve the examples).
git clone <this repository>
cd app.js
npm install # installs dev deps and builds the framework
npm run ex:counter # counter example → http://localhost:8123/
npm run ex:form # form-submit example → http://localhost:8123/
npm run ex:todo # todo example → http://localhost:8123/
npm run ex:cards # slots example → http://localhost:8123/
npm run ex:profile # editable child example → http://localhost:8123/
npm run ex:registration # registration capstone → http://localhost:8123/Each example is served as its own web root: /app.js is the freshly built framework, /templates/ belongs to that example alone.
One component, one template. The framework loads /templates/root.html for the
root component, so those two files are the whole app:
<!-- index.html -->
<div id="app"></div>
<script type="module">
import Component from '/app.js';
new Component({
element: document.querySelector('#app'),
data: {name: 'world', count: 0},
methods: {
bump() { this.data.count += 1; },
},
});
</script><!-- templates/root.html -->
<template>
<h1>Hello, ${name}!</h1>
<button data-on-click="bump">clicks: ${count}</button>
</template>Everything else in this README is a variation on those pieces: ${} reads
state, data-* attributes bind behaviour to it, and writing this.data
re-renders whatever read it.
The examples form a ladder — each one introduces the next handful of ideas:
- counter — a component,
${}interpolation,data-on-click, state that re-renders when written. - form — two-way
data-valueon text inputs, selects, checkboxes, and a radio group;data-on-submit. - todo — keyed lists (
data-for+data-key),data-show-if, and a single-file child component with props and events. - cards — content projection: named and default slots, fallbacks, and parent-owned reactive content (a list, an input, a toggle) living inside a child component's markup.
- profile — an editable child component: a prop flows in, the child keeps its own draft of it, and edits flow back out as an event. Two instances of one component, each with its own state.
- registration — everything at once: a revealed section, repeatable
component rows, a submit button gated by
data-disabled-if, pipes, and real Zod validation. - csp — the same framework under
script-src 'self': the boot script is a real file, the child component's code loads through<script src="./tally.js">, and adata-srcbadge cycles bundled SVGs — nothing on the page needsunsafe-inline,unsafe-eval, ordata:. (The smoke test drives the page shape; the policy itself is enforced when you open it in a real browser.)
The registration example is the capstone: a heavier form that puts every recent feature to work at once — checkbox and radio bindings, a checkbox-revealed section, a repeatable list of contacts as per-item single-file components trading props and events with their parent, a submit button gated by data-disabled-if, and validation errors painted from a plain array via a method called from an expression. Its schema is validated with Zod — the framework composes with real libraries; Zod arrives as a plain ES module (serve.mjs aliases /zod.js to the installed package's own bundle), no bundler involved, and the framework itself stays dependency-free.
Read the framework the same way: docs/internals.md is the map, and the git
history is the long course — the engine grew one reviewed feature at a time,
and every stage still runs if you check it out.
-
Templates should be placed in /templates directory
-
Meaningful attributes in templates are: data-component, data-show-if, data-display-if, data-disabled-if, data-value, data-src, data-on-*, data-for + data-key, data-ref, data-slot
-
new Component({element, data, methods, componentName})— every option has a default (document.body,{},{}, and'root'), so all four are optional -
A Component instance exposes
ready— a promise that resolves when the initial mount finishes (and rejects with the original error if it fails). The initial render is already in the DOM whenreadyresolves — mount is not batched, so there is noupdated()to await after it -
app.destroy()stops the app: listeners are removed (oneAbortControllerfor everything), updates stop, the rendered DOM stays as-is -
A template that fails to load (network error or HTTP error status) is not cached — the next load retries the fetch
-
Template text supports
${expression}interpolation (escape a literal with\${) -
Lists render with
data-for(a bare array expression) plus a requireddata-key; item expressions see$item,$index,$array -
Arrays update by replacement:
todos = [...todos, item]— prefer copy-based expressions liketodos.filter(...)/[...todos].sort(...) -
data-src="expression"binds an element'ssrcattribute (interpolation is text-only, so<img src="${url}">has no meaning): the attribute follows the expression's string value and is removed outright when the value isnull,undefined, or''— an emptysrcwould make the browser fetch the page itself. Any src-bearing element works, except<script>: a reactive expression must not pick executable code, and that one is a loud error -
File inputs are never value-bound — a browser won't let script set
.files, sodata-valueontype="file"is a loud error. Handle thechangeevent directly and store only what you need from it:<input type="file" data-on-change="pickFile">
pickFile(event) { const [file] = event.target.files; // read/upload; store derived primitives (name, size) in data — not the File itself }
- A write to
dataschedules a render rather than running one immediately; every write that lands in the same microtask — one, or a dozen — coalesces into a single render. await app.updated()resolves once that pending render has settled onto the DOM — this component's render. Reach for it right after a write, in a test or inside a method, whenever you need to read the DOM back. If the write feeds a prop of a child component, the child re-renders on its own later microtask, so reading DOM that the child paints needs one more turn of the event loop after theawait(await new Promise(resolve => setTimeout(resolve))). Everything your own template's bindings paint is settled as soon asupdated()returns.- Writing the same value a key already holds is free: a primitive (or
null) write that doesn't actually change anything renders nothing at all. - Arrays and plain objects still update by replacement, but mutating one in place and then reassigning the very same reference is a sanctioned escape hatch that does render:
data.todos = data.todosafter pushing into it in place,data.user = data.userafter editing one of its keys, or reassigning partway down a chain (data.user.address = data.user.address) all work. Replacing a plain object with a genuinely different one is still a loud error — only self-assignment is allowed there. - The rule behind that error: a field's reactive shape is fixed by its initial value, and the data shape itself is fixed at construction — keys can never be added later. A key seeded with a plain object becomes a nested reactive object and stays replace-only for life; a key seeded with
null(or any non-object) stays a leaf you can freely replace — including with a whole fetched payload. A view that refetches server data wants exactly that: seed every payload field asnull(data: {status: null, messages: null}) and assign each response wholesale on every load. Reserve object seeds for state whose keys you edit in place — declare every key it will ever hold up front, then publish a batch of edits with the self-assignment hatch. - Inside a method, the idiom for "write, then read the DOM back" is: write
this.data,await this.updated(), then readthis.refs— your own elements are guaranteed settled by the time thatawaitreturns. (A child component you passed new props to is not: it flushes on its own later microtask.) - A subtree hidden by
data-show-ifis inert, not just invisible: nothing under it (including other directives on the hidden element itself) evaluates while it is down, so the guard against absent data lives in the visibility condition alone — no need for?.in every inner expression. The subtree catches up the moment it is shown. A child component inside a hidden subtree is the exception: it drains on its own and keeps rendering.
- Every directive attribute and every
${...}placeholder shares one small expression language: numbers, strings, booleans,null/undefined, array literals with spreads; property access via.,[], and?.; function calls; arrow functions; arithmetic (+ - * / %); comparison (< <= > >=) and strict equality (=== !==); the unary operators!,-,+, andtypeof; ternaries and logical operators (&&,||,??); and|>pipes. There is no assignment and no statements. That stops an expression from writing a name, but it does not make one pure: a method you call can do anything, and the built-in mutators are reachable —${todos.sort()}really does reordertodositself. Worse than the edit is its invisibility: an in-place mutation never notifies the ghost, so the framework does not know state changed and schedules nothing — what any given binding shows then depends on whether it happened to run after the mutation. Keep expressions to reads and copy-based calls ([...todos].sort(),todos.filter(...)); do the mutating in a method. - Names resolve through one fixed chain: item scope inside a
data-for($item,$index,$array) → component props →data→methods→ a small whitelist of globals (Math,JSON,Number,String,Boolean,Array,isNaN,isFinite,parseInt,parseFloat). - A pipe calls its right side with its left side as the sole argument, so a formatter is just a method:
<p>${todos |> left} left</p>callsmethods.left(todos)and renders the count. - A malformed expression is caught when the template loads, not when it renders — the console gets the expression text with a caret under the character that broke parsing. That includes expressions inside a
data-foritem template that has not rendered yet (even one whose list stays empty): every expression in the block compiles at load, and any parse failure is reported and drops the whole block. - Expressions are parsed and evaluated by the framework itself — no
eval, nounsafe-evalCSP requirement. Loading a component's inline<script>uses adata:module import; under a strictscript-srcgive the script asrcinstead (see Components) and nodata:allowance is needed. - What that sandbox does and does not promise:
constructor,__proto__andprototypeare blocked on every property access, and only a fixed whitelist of globals resolves, so an expression cannot reachFunctionoreval— verified against the obvious escapes. It is NOT a boundary against hostile templates: templates are yours, and an expression can still call whatever yourdataandmethodsexpose. Nesting is capped (200 levels) so a pathological expression fails as a parse error rather than exhausting the stack and taking the mount with it.
-
A component template file may carry a
<script>after its<template>— a single-file component (SFC), with its owndata,methods,props,events,refs, andmounted()lifecycle. A file with no<script>stays a template-only include, sharing the parent'sdata/methods. -
mounted()runs once the component's subtree is in the DOM. If it returns a function, that function is the component's cleanup and runs atdestroy()— the other half of the lifecycle. It runs before listeners are severed, so a partingthis.events.emit(...)still reaches the parent; a cleanup that throws is logged and does not stop the teardown. Use it to undo anything the framework does not own — a timer, a subscription, a listener onwindow:export default { data: () => ({ticks: 0}), mounted() { const id = setInterval(() => { this.data.ticks += 1; }, 1000); return () => clearInterval(id); }, };
-
Props flow in, events flow out:
<div data-component="todo-item" data-component-prop-todo="$item" data-component-on-toggled="toggleTodo"></div>
-
The emitting half lives on
this.eventsinside a component's<script>:emit(name, payload)fires an event the parent can catch withdata-component-on-<name>,on(name, handler)listens to the component's own emitter, andonParent(name, handler)listens to the parent's. The payload arrives as the event'sdetail.'props'is reserved — the framework emits it when props are re-seeded, so a component cannot emit it. Every subscription is torn down with the component. -
A prop whose name collides with a key in the component's own
datais a loud error that rejects that instance: props are inputs, and a name cannot mean two things at once. -
data-ref="name"collects an element intorefs. Two rules: a duplicate name is a loud error and the first element wins, anddata-refinside adata-foritem is a loud error — per-item elements have no single stable name, so reach them through the item component instead. -
An inline component
<script>is loaded through adata:module import, which a strictscript-src(e.g.'self') blocks. The strict-CSP form is<script src="./name.js"></script>— an ordinary module file resolved against the component file's own URL, so a relativesrcnames a sibling of the template. One place for the code, not both: a<script>carrying bothsrcand inline code is a loud error. -
Student trap: component events always ride the
data-component-prefix —data-on-removedon a component element binds a DOM event that will never fire.
-
A script-bearing component's template can declare
<slot>(default) and<slot name="x">(named) regions. The parent routes markup into them by marking adata-componentwrapper's top-level children withdata-slot="x"; everything else falls into the default slot. A slot's own children render as a fallback, but only when nothing was projected into it. Projected content keeps the parent's scope (its expressions and handlers still resolve through the parent); a rendered fallback is scoped to the child instead.<!-- templates/card.html --> <template> <div class="card"> <h2><slot name="title">Untitled</slot></h2> <div class="card-body"><slot>Nothing here yet.</slot></div> </div> </template> <script>export default {};</script>
<div data-component="card"> <span data-slot="title">Hello</span> <p>Landed in the default slot.</p> </div>
-
A component with no
<slot>at all can't take wrapper content — putting markup inside itsdata-componentelement is a loud error, and the content is dropped. -
A component written inside projected markup hears the component that wrote it, not the one whose slot it lands in. Ownership follows the markup, not the final DOM position — the same rule that keeps projected expressions resolving through the parent.
-
The rest of the loud errors around slots, all of which drop the offending piece rather than half-wiring it: a
<slot>in the root component's template (the root is nobody's child, so nothing can be projected into it); a<slot>inside the child's owndata-forblock; a directive ordata-on-*on the<slot>element itself (wrap the region in a container and decorate that); a<slot>nested inside another slot's fallback; a duplicate slot name (the first wins);data-slot="x"naming a slot the child's template doesn't declare (the content falls into the default bucket); an emptydata-slot=""; and default-bucket content arriving at a template that declares only named slots. -
The cards example runs projection end to end: one card component filled three different ways — both slots projected, reactive parent-owned content, and nothing at all (fallbacks).
-
A single-file component may also carry one
<style>after its<template>— one<script>and one<style>, in either order. The CSS is injected intodocument.headonce per component type, wrapped in the platform's@scoperule, so it applies inside every instance of that component and stops at any nested single-file component — whose own file styles its own subtree. The boundary falls just inside that nested wrapper: the wrapper ELEMENT is still in the outer component's scope and stays styleable by it, while everything below the wrapper is not. A template-only include is not a boundary: its markup is styled through the component that includes it, just as it shares that component's data and methods:<!-- templates/card.html --> <template> <section class="card">...</section> </template> <style> .card { border: 1px solid #ddd; } :scope { display: block; } </style> <script>export default {};</script>
-
:scope { }selects the component's own wrapper element (each instance'sdata-componentelement). Prefer this explicit form over bare declarations — it reads as a rule, and its 0-1-0 specificity matches the page-level attribute selector it replaces. -
Scoping follows geometry, not ownership: content the parent projects into a child's slot relocates inside the child's subtree, so the parent's scoped rules no longer reach it — the child's scoped rules do.
-
A scoped rule beats an equal-specificity page rule regardless of source order: scoped rules have finite proximity, page rules infinite.
-
At-rules ride along verbatim:
@medianests fine;@keyframesand@font-faceare valid, but their names are global — collisions across components are the author's to avoid;@importis silently invalid mid-sheet. -
Template-only includes have no style vocabulary — a
<style>in a scriptless file is a loud error, and so is one in the root component's own file: root styles belong to the host page's stylesheet. One naming caveat: don't give an SFC the root'scomponentName, and don't mount the root on an element whosedata-componentnames an SFC — the root mount would become a scoping root for that type's styles page-wide.
A data-component element is a real box in layout, which gets in the way inside flex or grid containers. A single-file component can make its own wrapper transparent from its <style> — the recommended form, since the transparency then ships with the component:
:scope {
display: contents;
}For template-only includes (which have no style vocabulary) and for components you don't own, the page-level rule does the same job:
[data-component="widget"] {
display: contents;
}Two caveats: the wrapper's own background/border/padding stop rendering, and the page-level rule should target specific components — the app stamps data-component on its root element (often <body>), which must keep its box; the root component's file must not do this either.
packages/app.js— the framework. TypeScript source insrc/, tests intests/, build output indist/(generated bynpm run buildand bynpm install; never committed).packages/examples— runnable teaching examples (counter/,form/,todo/,cards/,profile/,registration/,csp/) plusserve.mjs, a dependency-free static server, and smoke tests that drive the built framework over real HTTP.
npm run build # compile packages/app.js/src → packages/app.js/dist
npm run typecheck # all workspaces
npm test # framework unit suite + examples smoke suite