@lemadane/primaljs
v0.4.2-beta
Published
Minimalists’ ReactJS — Pure JS, Function Components, Tagged Templates, Signals, Direct Real DOM Updates, No Virtual DOM, No Compiler.
Maintainers
Readme
PrimalJS
The Hyper Minimalists’ ReactJS — Pure JS, Function Components, Tagged Templates, Signals, Direct Real-DOM Updates, No Typescript, No Babel, No JSX, No Compiler, No Virtual DOM, No Re-Render.
PrimalJS is a zero-dependency, lightweight Single Page Application (SPA) and component framework currently in beta (v0.4.2-beta). Built directly on modern browser APIs, PrimalJS brings web development back to its fundamentals — JavaScript stays JavaScript.
Credits & Attribution
- Authored & Designed by: Lemuel Adane
- Coded & Architecture by: Google Antigravity
- Product Tested & QA by: ChatGPT
Table of Contents
- Core Principles
- Quick Start & Installation
- Standalone & Minified Bundles
- Mounting & DOM Hydration
- Reactivity System & State Management
- Reactive Control Flow & Keyed List Reconciliation
- Component Composition & Custom Components
- Declarative Lifecycle Components
<Focus>— Manage Keyboard Focus & Trapping<OnIdle>— Defer Mount Until Idle Time<Keep>— Preserve Dynamic Components<Animate>— Animate Before DOM Removal<WithinView>— Viewport-Aware Lazy Mounting<Place>— Render Subtree Elsewhere (Portal)<Load>— Dynamic Component Switcher<Delay>&<Wait>— Async Task & Promise Lifecycles<Guard>— Localized Error Boundary
- Lifecycle-Aware DOM Helpers
- Client-Side Router & SEO
- Zero-Dependency PWA Management
- Architecture & Verification Matrix
- License
Core Principles
- Compiler-Free & Build-Free: Runs natively in any browser via ES modules without Babel, Webpack, Vite, or JSX compilers.
- Virtual-DOM-Free: Updates real DOM elements directly via compiled instruction paths. Component functions run ONLY ONCE (
executions === 1). - Dependency-Free: 0 external npm dependencies (
dist/primal.standalone.jsis ~15 KB minified). - Signal-Driven Reactivity: Fine-grained signals trigger surgical DOM text, attribute, and style updates without component re-renders.
- Ownership & Lifecycle-Driven: Tree-structured
ComponentContexthierarchy manages subscriptions, event listeners, refs, and cleanup hooks automatically.
Quick Start & Installation
Option A: NPM Package
npm install primaljsimport { html, signal, mount } from "primaljs";
function Counter() {
const count = signal(0);
return html`
<button onclick=${() => count.value++}>
Count: ${count}
</button>
`;
}
mount(Counter, "#app");Option B: Zero-Build Standalone ES Module
Copy dist/primal.min.js (or dist/primal.standalone.js) into your project and import directly in index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Zero-Build PrimalJS App</title>
</head>
<body>
<div id="app"></div>
<script type="module">
import { html, signal, mount } from "./js/primal.min.js";
function App() {
const name = signal("World");
return html`<h1>Hello, ${name}!</h1>`;
}
mount(App, "#app");
</script>
</body>
</html>Standalone & Minified Bundles
PrimalJS produces two zero-dependency browser ES module distribution formats generated side-by-side during npm run build:
| File | Purpose | Size | Best Used For |
| :--- | :--- | :--- | :--- |
| dist/primal.standalone.js (or ./primal.js) | Unminified | ~180 KB | Development & Debugging — Readable source code with module section headers intact for line-by-line inspection in DevTools. |
| dist/primal.min.js (or ./primal.min.js) | Minified | ~143 KB | Production Deployment — Compressed whitespace and stripped comments for minimal network payload size. |
Both files exist independently in dist/ (and mirrored as ./primal.js and ./primal.min.js at the root directory), so you can pick whichever fits your workflow.
Minification & Bundle Features
Zero-Dependency Automated Build Pipeline:
- Bundles are constructed natively via scripts/build-standalone.js using Node.js standard APIs.
- Requires zero external bundlers or minifier npm dependencies (no Babel, Terser, or esbuild required).
JSDoc & IDE IntelliSense Preservation:
- The custom minification pass preserves all JSDoc annotations (
/** ... */) intact. - Editors like VS Code retain full hover tooltips, type parameters, and parameter documentation even when importing the minified module (
primal.min.js).
- The custom minification pass preserves all JSDoc annotations (
Flexible Import Options:
- NPM Package Import:
// Standard ES import import { signal, html, mount } from "primaljs"; // Production minified ES module import import { signal, html, mount } from "primaljs/min"; - Zero-Build Static HTML Import:
<!-- Production: Minified Bundle --> <script type="module"> import { signal, html, mount } from "./primal.min.js"; </script> <!-- Development: Unminified Bundle --> <script type="module"> import { signal, html, mount } from "./primal.standalone.js"; </script>
- NPM Package Import:
Mounting & DOM Hydration
PrimalJS provides two distinct runtime APIs for initializing applications:
| Function | Strategy | Primary Use Case |
| --- | --- | --- |
| mount(Component, target) | Create DOM | Pure client-side apps starting with an empty container (<div id="app"></div>). |
| hydrate(Component, target) | Adopt Existing DOM | Pre-rendered static HTML. Adopts existing DOM in-place (nodeBefore === nodeAfter) without clearing innerHTML or flashing. |
| unmount(target) | Teardown DOM | Disposes application context, stopping effects and detaching event listeners. |
mount() — Create & Mount New DOM
import { mount, html, signal } from "primaljs";
function App() {
const count = signal(0);
return html`<button onclick=${() => count.value++}>Count: ${count}</button>`;
}
const app = mount(App, "#app");hydrate() — Activate & Adopt Existing Static DOM
hydrate() attaches PrimalJS reactivity, event listeners, refs, and ComponentContext ownership directly to compatible DOM already present in the browser:
import { hydrate, html, signal } from "primaljs";
// Existing browser HTML: <div id="app"><button id="counter">Count: 0</button></div>
function Counter() {
const count = signal(0);
return html`<button id="counter" onclick=${() => count.value++}>Count: ${count}</button>`;
}
// Adopts existing DOM elements in-place, preserving live form input values and focus
const app = hydrate(Counter, "#app");- DOM Identity Preservation: Preserves exact DOM node identity (
nodeBefore === nodeAfter). - Form & Focus Retention: Live typed input values (
input.value), checkbox states, focus (document.activeElement), and scroll positions are retained without resetting. - Empty Target Fallback: If the target has no existing child DOM elements, automatically falls back to
mount()with a dev mode warning.
unmount() — Clean Application Teardown
import { unmount } from "primaljs";
// Disposes all effects, event listeners, and lifecycle hooks
unmount("#app");Reactivity System & State Management
signal() & computed() — Reactive State
import { signal, computed } from "primaljs";
const count = signal(0);
const double = computed(() => count.value * 2);
console.log(double.value); // 0
count.value = 5;
console.log(double.value); // 10effect(), batch(), untrack() — Side Effects & Sync
import { signal, effect, batch, untrack } from "primaljs";
const firstName = signal("Lemuel");
const lastName = signal("Adane");
// Runs automatically on dependency change; returns disposer
const dispose = effect(() => {
console.log(`User: ${firstName.value} ${untrack(() => lastName.value)}`);
});
// Defer dependent effects until the outermost batch finishes
batch(() => {
firstName.value = "Google";
lastName.value = "Antigravity";
});
dispose(); // Unsubscribes effectbatch() applies signal writes immediately and defers dependent effects until the outermost batch finishes. Computed values stay current when read inside a batch, including chains of computeds. An effect that reads both a signal and a computed derived from it runs once after the batch with consistent values.
const count = signal(1);
const doubled = computed(() => count.value * 2);
batch(() => {
count.value = 2;
console.log(doubled.value); // 4, even before the batch finishes
});Import computed from "primaljs" for this example.
ref() — Direct DOM Element References
import { html, ref, onMount } from "primaljs";
function AutoFocusInput() {
const inputRef = ref();
onMount(() => {
inputRef.current.focus();
});
return html`<input ref=${inputRef} type="text" placeholder="Search..." />`;
}Reactive Control Flow & Keyed List Reconciliation
Because component functions execute ONLY ONCE (executions === 1), standard JavaScript if statements and .map() loops evaluated outside functions run once on mount. Wrap reactive conditions and lists inside arrow functions ${() => ...}:
| Pattern | Static (Runs Once on Mount) | Reactive (Updates on Signal Change) |
| --- | --- | --- |
| Conditional | if (show.value) ... | ${() => show.value ? html\Active</p` : html`Inactive</p`}|
| **Keyed List** |items.map(i => ...)|${() => items.value.map(i => html`${i.name}`)}` |
Keyed List DOM Reconciliation
Dynamic lists ${() => list.value.map(...)} use item keys (key=${item.id}) to reconcile real DOM nodes in-place — preserving input focus, selection, and component state during array mutations.
Component Composition & Custom Components
PrimalJS function components can easily be nested and reused inside other PrimalJS components. Because PrimalJS uses standard JavaScript without JSX compilers, components are regular functions returning html tagged templates.
1. Registering Custom Components (register())
To use upper-case component tag syntax (e.g. <UserCard user=${u} /> or <Button variant="primary">Click</Button>) inside html templates, register your component functions with register():
import { html, signal, register, mount } from "primaljs";
// 1. Leaf Subcomponent
function Button(props) {
return html`
<button class="btn btn-${props.variant || 'default'}" onclick=${props.onclick}>
${props.children}
</button>
`;
}
// 2. Composite Subcomponent using <Button>
function UserCard(props) {
return html`
<div class="user-card">
<h3>${props.name}</h3>
<Button variant="danger" onclick=${props.onDelete}>
Delete User
</Button>
</div>
`;
}
// 3. Register components before mounting
register(Button, UserCard);
// 4. Top-Level Parent Component using <UserCard>
function App() {
const user = signal({ id: 1, name: "Lemuel Adane" });
return html`
<main>
<UserCard
name=${user.value.name}
onDelete=${() => console.log("Deleted")}
/>
</main>
`;
}
mount(App, "#app");2. Props, Callbacks & Slotted Children (props.children)
When a parent component renders a child component via XML tag syntax <MyComponent prop=${value}>Children</MyComponent>:
- Attributes to Props: Attributes like
name=${val}orvariant="primary"are passed as properties in thepropsobject. - Event Callbacks: Pass functions as props (e.g.
onDelete=${handleDelete}) to communicate from child back to parent. - Slotted Content (
props.children): Nested content inside component tags is passed asprops.children. - Reactive Signals: Signals passed as props (e.g.
count=${countSignal}) dynamically update child DOM bindings without re-executing component functions.
See examples/component-composition for a complete working example with modern styles.
Declarative Lifecycle Components
PrimalJS control flow remains pure JavaScript (if, switch, .map(), ternary). Built-in components are dedicated exclusively to managing reactive subtrees, browser interactions, and asynchronous lifecycles:
| Component | Responsibility |
| --- | --- |
| <Focus> | Keyboard Focus Management (Autofocus, Tab trapping, focus restoration, nested stacks) |
| <OnIdle> | Browser Idle Scheduling (Defer non-critical mounting until browser has idle time) |
| <Keep> | Subtree Preservation (Preserve inactive component instances & DOM state in cache) |
| <Animate> | Exit Animation Coordination (Coordinate visual CSS enter/leave before DOM removal) |
| <WithinView> | Viewport-Aware Lazy Mounting (Mount child subtrees when approaching viewport) |
| <Place> | Portal / Render Elsewhere (Render child subtree into another DOM target) |
| <Load> | Dynamic Component Switcher (Swap active component based on signal/route) |
| <Delay> | Async Task Execution (Execute async task with AbortController & timeout) |
| <Wait> | Promise Observation & Unwrap (Unwrap existing Promise with timeout & error boundary) |
| <Guard> | Localized Error Boundary (Catch exceptions and render fallback UI) |
<Focus> — Manage Keyboard Focus & Trapping
Manages accessibility, keyboard focus trapping, and focus restoration for modals, dialogs, drawers, and menus:
import { html, signal, Place, Focus } from "primaljs";
function App() {
const open = signal(false);
return html`
<button onclick=${() => open.value = true}>Open Modal</button>
${() => open.value ? html`
<Place to="#modal-root">
<Focus initial="#first-input">
<div role="dialog" aria-modal="true">
<h2>Settings</h2>
<input id="first-input" placeholder="Name" />
<button onclick=${() => open.value = false}>Close</button>
</div>
</Focus>
</Place>
` : null}
`;
}autofocus=${true}(Default): Automatically focuses first tabbable element orinitialtarget prop on mount.trap=${true}(Default): TrapsTabandShift+Tabcycling inside the owned subtree.restore=${true}(Default): Restores browser focus to the trigger button (document.activeElement) when unmounted.- Nested Focus Stack: Supports nested modals cleanly. Outer focus traps pause while an inner modal is open and resume when closed.
<OnIdle> — Defer Mount Until Idle Time
Delays creation and mounting of non-critical child subtrees until the browser has idle scheduling time (requestIdleCallback):
import { html, OnIdle } from "primaljs";
import { RecommendationsWidget } from "./widgets.js";
function Page() {
return html`
<main>
<h1>Main Content</h1>
<OnIdle timeout=${2000} fallback=${html`<div>Loading recommendations...</div>`}>
<RecommendationsWidget />
</OnIdle>
</main>
`;
}- 0-Execution Guarantee: Child component function is NOT executed before idle scheduling (
created === 0). - Forced Maximum Wait (
timeout):timeoutspecifies maximum wait before forced eligibility without throwing. - Unmount Cancellation: Unmounting parent before idle fires cancels the callback automatically.
<Keep> — Preserve Dynamic Components
Preserves previously mounted component instances and DOM subtrees in an internal LRU cache instead of destroying them:
import { html, signal, Keep, Load } from "primaljs";
import { DashboardTab, SettingsTab } from "./tabs.js";
const currentTab = signal(DashboardTab);
function App() {
return html`
<Keep max=${5}>
<Load component=${currentTab} />
</Keep>
`;
}- Preserves Native State: Retains typed form input values, scroll positions, and local signal state naturally.
DESTROYEDvsKEPT: While kept in background cache,onDestroyhooks do NOT run, and reactive bindings continue updating detached DOM so it is fresh when restored.
<Animate> — Animate Before DOM Removal
Coordinates visual CSS enter/leave animations with component teardown:
import { html, signal, Animate } from "primaljs";
const open = signal(false);
function App() {
return html`
<Animate enter="fade-in" leave="fade-out" duration=${200}>
${() => open.value ? html`<div class="card">Animated Dialog</div>` : null}
</Animate>
`;
}- Deferred Teardown: Keeps DOM nodes and
ComponentContextalive during leave animation. RunsonDestroyand removes DOM only after animation finishes. - Interruption Recovery: Toggling state back to
truemid-leave cancels the exit animation instantly.
<WithinView> — Viewport-Aware Lazy Mounting
Delays component instantiation until its position approaches the browser viewport (IntersectionObserver):
import { html, WithinView } from "primaljs";
import { HeavyChart } from "./chart.js";
function Page() {
return html`
<WithinView margin="200px" minHeight="400px" fallback=${html`<p>Loading chart...</p>`}>
<HeavyChart />
</WithinView>
`;
}<Place> — Render Subtree Elsewhere (Portal)
Renders child content into another DOM target (to="#modal-root") while maintaining 100% logical component ownership:
import { html, Place } from "primaljs";
function Modal({ children }) {
return html`
<Place to="#portal-root">
<div class="modal-overlay">${children}</div>
</Place>
`;
}<Load> — Dynamic Component Switcher
Dynamically swaps component functions based on a signal or function:
import { html, signal, Load } from "primaljs";
import { UserView, AdminView } from "./views.js";
const role = signal("user");
function ViewSwitcher() {
return html`<Load component=${() => role.value === "admin" ? AdminView : UserView} />`;
}<Delay> & <Wait> — Async Task & Promise Lifecycles
Manage asynchronous operations with AbortController, timeouts (timeout=${5000}), loading slots (<Briefly>), and error boundaries (<Failed>):
import { html, signal, Delay, Briefly, Failed } from "primaljs";
const query = signal("search");
function Search() {
return html`
<Delay task=${({ signal }) => fetch(`/api/search?q=${query.value}`, { signal }).then(r => r.json())} timeout=${5000}>
${data => html`<ul>${data.items.map(item => html`<li>${item.title}</li>`)}</ul>`}
<Briefly><p>Searching...</p></Briefly>
<Failed>${(err, retry) => html`<p>Error: ${err.message}</p><button onclick=${retry}>Retry</button>`}</Failed>
</Delay>
`;
}<Guard> — Localized Error Boundary
Catches runtime exceptions in child subtrees and renders fallback UI:
import { html, Guard } from "primaljs";
function App() {
return html`
<Guard fallback=${(err, retry) => html`<div><p>${err.message}</p><button onclick=${retry}>Retry</button></div>`}>
<UnsafeWidget />
</Guard>
`;
}Lifecycle-Aware DOM Helpers
PrimalJS provides explicit JavaScript helpers (NOT template tags) that manage browser listeners while automatically binding to ComponentContext lifecycle and <Keep> caches:
onKey() — Keyboard Event Listener
import { onKey } from "primaljs";
function Dialog() {
// Automatically unbinds on component unmount
onKey("Escape", () => closeModal());
onKey(btnRef, "Enter", (e) => submit(), { ctrl: true, ignoreEditable: true });
}scrollLock() — Reference-Counted Scroll Lock
import { scrollLock } from "primaljs";
function Modal() {
// Locks body scroll; restores scroll when all active locks reach 0
scrollLock();
}onOutsideClick() — Pointer Outside Detection
import { onOutsideClick } from "primaljs";
function Dropdown() {
// Supports array targets [triggerRef, menuRef] across <Place> portals
onOutsideClick([triggerRef, menuRef], () => closeMenu());
}Client-Side Router & SEO
SPA Router & Layouts
import { createRouter, RouteOutlet, html, mount } from "primaljs";
import { HomePage, AboutPage, UserPage } from "./pages.js";
const router = createRouter({
routes: [
{ path: "/", component: HomePage },
{ path: "/about", component: AboutPage },
{ path: "/users/:id", component: UserPage }
]
});
function App() {
return html`
<nav>${router.link({ href: "/", children: "Home" })} | ${router.link({ href: "/about", children: "About" })}</nav>
<main><RouteOutlet /></main>
`;
}
mount(App, "#app");Routes can define a synchronous or asynchronous beforeEnter guard. Return false to cancel navigation, a path string to redirect, or true (or nothing) to continue:
{ path: "/users/:id", component: UserPage, beforeEnter: () => isSignedIn() }When a guard cancels navigation, the router restores the previous route URL, including its query parameters and fragment. With mode: "hash", it restores the route inside the URL hash and preserves the outer pathname and query string.
head() — Dynamic Head Metadata
import { head } from "primaljs";
function Page() {
head({
title: "User Profile — PrimalJS",
meta: [{ name: "description", content: "User profile details" }]
});
return html`<h1>Profile</h1>`;
}Zero-Dependency PWA Management
Register service workers and manage offline caches:
import { setupPwa } from "primaljs";
setupPwa({
scriptUrl: "/sw.js",
scope: "/",
onUpdate: (reload) => {
if (confirm("New version available. Reload?")) reload();
}
});Architecture & Verification Matrix
PrimalJS enforces strict architectural guarantees across its test suite:
- Single Component Execution: Component functions execute exactly once (
executions === 1) on mount. Routine state changes mutate real DOM targets directly. - DOM Identity & Focus Preservation: Target DOM element instances remain untouched when state changes (
nodeBefore === nodeAfter), preserving input focus, form state, and text selections. - Root Disposal:
mount()andhydrate()return{ dispose() }for idempotent teardown of DOM nodes, event listeners, and subscriptions.
Test Suite Execution
# Run the configured unit test suite
npm test
# Run Playwright E2E browser suite (18 / 18 passing)
npm run test:e2e
# Run cross-browser suite targeting Chromium, Firefox, and mobile Chromium
npm run test:e2e:crossBrowser Verification Results
=== PRIMALJS TEST VERIFICATION MATRIX ===
ℹ Unit Tests: 171 / 171 PASSING (100%) across 31 test suites
ℹ E2E Browser Tests: 18 / 18 PASSING (100%) in real Playwright browser instances
ℹ Cross-Browser: PASSING on Chromium, Firefox, and Android Mobile WebLicense
MIT License © Lemuel Adane & PrimalJS Contributors
