sigla
v0.1.0
Published
Sub-4KB UI framework designed for AI coding agents. Signals, direct DOM, keyed lists, SSR, router — zero dependencies.
Maintainers
Readme
sigla
A sub-4KB UI framework designed for AI coding agents.
sigla prioritizes agentic developers over human developers. Every API decision — mandatory props, zero overloads, single call signatures, plain function components — optimizes for LLM code generation accuracy and speed.
Size
Gzipped: 3,926 bytes (95.8% of 4KB budget)
Brotli: 3,529 bytesFeatures
- Signals-based reactivity — push-pull hybrid with diamond dependency resolution and automatic disposal
- Direct DOM rendering —
h()hyperscript +tagsProxy, no virtual DOM - Keyed list reconciliation — prefix/suffix trim + Longest Increasing Subsequence for minimum DOM moves
- Event delegation —
$$propertystorage on DOM nodes, single document-level listener per event type - Client router — flat first-match,
:params, wildcards, guards, History API or hash mode - Server API router — universal
Request → Responsehandler for Workers, Deno, Bun, Node - SSR + hydration —
renderToStringwith server shims, wipe-and-replace client hydration - Context — stack-based dependency injection
- Error boundaries — component-level error catching with fallback rendering
Quick Start
npm install siglaNo build step required — sigla is plain JS with JSDoc types. Import directly from source via ESM.
Usage
Client
import { signal, computed, effect, onCleanup } from 'sigla';
import { h, tags, list } from 'sigla';
import { delegateEvents } from 'sigla';
import { createRouter } from 'sigla';
// Initialize event delegation
delegateEvents();
// Destructure tag functions (eliminates string typos for agents)
const { div, h1, button, ul, li, span } = tags;
// Components are plain functions that run once
const Counter = (props) => {
const count = signal(props.initial);
return div({},
span({}, () => `Count: ${count.value}`),
button({ onclick: () => count.value++ }, '+'),
button({ onclick: () => count.value-- }, '-'),
);
};
// Mount
document.getElementById('app').appendChild(Counter({ initial: 0 }));Reactive Primitives
// Signal — reactive value
const name = signal('world');
name.value = 'sigla'; // write
console.log(name.value); // read (tracked inside effects)
console.log(name.peek()); // read (untracked)
// Computed — derived value, lazy evaluation
const greeting = computed(() => `Hello, ${name.value}!`);
// Effect — side-effect, auto-tracks dependencies
const dispose = effect(() => {
console.log(greeting.value); // re-runs when greeting changes
});
// Cleanup
effect(() => {
const timer = setInterval(() => {}, 1000);
onCleanup(() => clearInterval(timer)); // runs on re-execution or disposal
});
// Batch — coalesce multiple signal writes
batch(() => {
a.value = 1;
b.value = 2;
// effects run once after batch, not twice
});
// Untracked — read without creating dependency
effect(() => {
const tracked = a.value;
const notTracked = untracked(() => b.value);
});Lists
const todos = signal([
{ id: 1, text: 'Learn sigla' },
{ id: 2, text: 'Build something' },
]);
const todoList = ul({},
list(
() => todos.value, // reactive array
(todo) => todo.id, // key function
(todo) => li({}, todo.text), // render function (runs once per item)
)
);Client Router
// History API mode (default)
const router = createRouter({
'/': () => showHome(),
'/users/:id': (p) => showUser(p.id),
'/posts/:slug?': (p) => showPost(p.slug),
'*': () => show404(),
});
// Hash mode (for static hosting)
const router = createRouter({ ... }, { hash: true });
// Programmatic navigation
router.navigate('/users/42');
router.navigate('/other', { replace: true });
// Guards
router.beforeNavigate((to, from) => {
if (to.startsWith('/admin') && !isLoggedIn()) return '/login';
return true;
});
// Reactive route state
effect(() => {
console.log('Current path:', router.path.value);
console.log('Params:', router.params.value);
});Server API
import { createAPI, json, redirect } from 'sigla';
const api = createAPI();
api.get('/api/users', () => json(users));
api.get('/api/users/:id', (ctx) => {
const user = db.get(ctx.params.id);
return user ? json(user) : json({ error: 'Not found' }, 404);
});
api.post('/api/users', async (ctx) => {
const body = await ctx.json();
return json(created, 201);
});
// SSR pages on the same router
api.get('/', (ctx) => ctx.html(() =>
hServer('h1', {}, 'Hello from sigla')
));
// Static file fallback
const api = createAPI({
static: async (path) => {
// serve files — implementation is runtime-specific
},
});
// Deploy anywhere:
Bun.serve({ fetch: api.handle });
Deno.serve(api.handle);
export default { fetch: api.handle }; // WorkersContext
const ThemeCtx = createContext('light');
const App = () =>
provide(ThemeCtx, 'dark', () =>
div({}, Child({}))
);
const Child = () => {
const theme = use(ThemeCtx);
return div({ class: theme }, 'themed content');
};SSR
// Server
import { renderToString, hServer, signalServer } from 'sigla';
const name = signalServer('world');
const html = renderToString(() =>
hServer('div', { class: 'app' },
hServer('h1', {}, `Hello ${name.value}`)
)
);
// => '<div class="app"><h1>Hello world</h1></div>'
// Client
import { hydrate } from 'sigla';
hydrate(document.getElementById('app'), () => App({}));Error Boundaries
const Safe = () =>
errorBoundary(
() => RiskyComponent({}),
(err) => div({ class: 'error' }, `Something broke: ${err}`)
);API Reference
| Function | Signature | Module |
|----------|-----------|--------|
| signal | (value) => Signal | reactive |
| computed | (fn) => Computed | reactive |
| effect | (fn) => disposeFn | reactive |
| batch | (fn) => void | reactive |
| untracked | (fn) => result | reactive |
| onCleanup | (fn) => void | reactive |
| h | (tag, props, ...children) => Element | dom |
| tags | Proxy<Record<string, TagFn>> | dom |
| list | (items, keyFn, renderFn) => DocumentFragment | list |
| delegateEvents | (types?, root?) => void | events |
| createRouter | (routes, opts?) => Route | router |
| navigate | (to, opts?) => void | router |
| createAPI | (opts?) => Api | api |
| json | (data, status?, headers?) => Response | api |
| redirect | (url, status?) => Response | api |
| compile | (pattern) => [RegExp, keys] | route |
| match | (url, pattern, keys) => params | route |
| createContext | (default) => Context | context |
| provide | (ctx, value, fn) => result | context |
| use | (ctx) => value | context |
| errorBoundary | (tryFn, catchFn) => Node | error |
| renderToString | (fn) => string | server |
| hServer | (tag, props, ...children) => VNode | server |
| hydrate | (root, fn) => void | server |
Examples
Client-side apps
# Serve the examples directory and open in browser
npx serve .
# Then visit:
# examples/todo-app.html — Todo app (signals, list, tags, context)
# examples/hackernews.html — HN clone (router, async data, nested comments)Server-side
# REST API
node examples/api.js
# SSR + API combo
node examples/ssr-api.jsFull-stack (realistic project structure)
node examples/bookmarks/server.js
# open http://localhost:3000examples/bookmarks/
├── index.html # HTML shell
├── server.js # Server (createAPI + static files)
├── public/
│ └── styles.css
└── src/
├── client.js # Client entry (router, mount)
├── api/
│ └── bookmarks.js # CRUD route handlers
├── components/
│ ├── AddForm.js
│ ├── BookmarkCard.js
│ ├── Flash.js
│ ├── Header.js
│ └── Toolbar.js
├── lib/
│ ├── store.js # Shared signals + actions
│ └── utils.js
└── pages/
├── Home.js
├── Add.js
└── Tags.jsDesign Principles
Zero overloads. Every function has exactly one call signature. Props is always mandatory — pass {} for none.
One-shot components. Components are plain functions that execute once. The reactive system handles updates. h() is a DOM builder, not a render function.
Explicit over implicit. No magic this, no class lifecycle, no implicit context. Lifecycle is onCleanup(). State is signal(). Derivation is computed().
Consistent patterns. Reactive values always use .value. Side effects always use effect(). Lists always use list().
Same patterns everywhere. Client router and server API use the same route pattern syntax (:params, * wildcards, optional :param?).
Tests
node tests/test-reactive.js # 13 tests
node tests/test-router.js # 7 tests
node tests/test-ssr.js # 10 tests
node tests/test-context.js # 4 tests
node tests/test-api.js # 14 testsLicense
MIT
