skruv/skruv
Acerca de
No-dependency, no-build, small JS view-library/framework-ish-thing.
Herramientas de desarrolloCrecimiento de estrellas medido
- in 24h
- 0
- in 7 days
- Recopilando historial
- in 15 days
- Recopilando historial
- in 1 month
- Recopilando historial
Cambios netos en períodos que se solapan, no totales diarios. Los datos no disponibles se dejan en blanco. Las estrellas indican interés, no calidad.
README.md
Originalskruv
No-dependency, no-build, small JS view-library/framework-ish-thing.
Quick start • Examples • Docs • Upgrading • Contributing
- The core (
skruv.js) is one file of about 600 lines: 5.3 kB minified, 2.1 kB with brotli. - Optional modules, imported only if you use them:
- reactive state (
utils/state.js) - async generators and promises as components (
utils/syncify.js) - server-side rendering without jsdom (
utils/minidom.jsand theskruv-ssr/skruv-ssgcommands) - scoped CSS (
utils/css.js) - JSX (
skruv/jsx-runtime,skruv/react/jsx-runtime) - a bundler (
skruv-bundle, needs esbuild-wasm)
- reactive state (
- TypeScript types (from JSDoc) check element attributes, allowed children and event handlers.
Quick start
npm i skruv
import { elementFactory, render } from "skruv"
import { createState } from "skruv/utils/state.js"
import { syncify } from "skruv/utils/syncify.js"
const { html, body, button, p } = elementFactory
const state = createState({ count: 0 })
const tree = html(
body(
// An async generator re-renders its part of the page on every state change
p(async function* () {
for await (const s of state) {
yield `Clicked ${s.count} times`
}
}),
button({ onclick: () => state.count++ }, "Click"),
),
)
// syncify resolves the async parts and wires up re-rendering; render writes
// into document.documentElement and async parts fill in as they resolve
render(syncify(tree))
To use it in the browser without a build step, serve the page over http and map the package's paths with an import map:
<script type="importmap">
{ "imports": {
"skruv": "./node_modules/skruv/skruv.js",
"skruv/utils/": "./node_modules/skruv/utils/"
} }
</script>
<script type="module" src="./app.js"></script>
Examples
Todo list (state, scoped CSS and syncify) — source
A whole app in one file. createState holds the list, and the ol is an
async generator that yields new items whenever the list changes; the title
and the heading follow the first todo through getGenerator(0). Adding and
removing todos only change the state, never call render. The page loads
index.js as it is, with an import map for the skruv imports.
{% include_relative examples/todo/index.md %}
The same app with only the core — source
A plain object as state and a doRender() call after each change, instead of
createState and syncify.
{% include_relative examples/todo-core/index.md %}
Scoped CSS — source
Two css templates, each returning a class. One styles the whole page
through :scope on <html>; the other is put on the first div, so its p
rule colours "Hello" but not "World!" in the second. See
Scoped CSS.
{% include_relative examples/scopedcss/index.md %}
JSX — source
A page written in JSX with a typed function component (props.a and
children). It is the one example with a build step: browsers cannot run
JSX or TypeScript, so index.tsx is bundled to index.min.js with
skruv-bundle (in this repo, npm run build-jsx), and the page loads that
file. After changing index.tsx, rebuild before reloading. The other examples load their source
directly. See JSX for the setup.
{% include_relative examples/jsx/index.md %}
Loader — source
addLoader with deliberately slow content: a canvas animation is shown until
the content arrives.
{% include_relative examples/loader/index.md %}
Server-side rendering — source
The SSR walkthrough explains what the server sends and how the browser takes over. The rendered result and an unbuilt version are in the same folder.
Rendering
render(tree, container = document.documentElement) writes the tree into the
DOM. Later calls update the existing DOM in place.
- The tree's root element is the container, so their tags must match (otherwise the container is replaced). The container must have a parent node.
- With the default container, skruv owns the whole document and removes nodes
that are not in the tree. To use skruv inside a page it does not own, pass an
element:
render(div(...), document.getElementById("app")).
Elements
elementFactory returns an element function for any name:
const { div, p, "my-widget": myWidget } = elementFactory. If the first
argument is a plain object it holds the attributes; everything else is a child.
- Children: strings and numbers (including
0and"") become text; booleans,nullandundefinedrender nothing, socond && elworks for boolean conditions; arrays are flattened. Withsyncify, children can also be async generators, promises and functions. svg,math,feed,urlsetandsitemapindexswitch the namespace of their content;foreignObjectswitches back to HTML. Names that exist in several namespaces have a prefix:svgA,svgScript,svgStyle,svgTitle,atomTitle,atomLink,atomSummary,atomSource.- Custom elements (any name with a dash): every attribute except
on*handlers is set as a property as well as an attribute, so they can receive objects and arrays. - SSR helpers:
skruvComment(an HTML comment),skruvText(raw output, e.g. for arobots.txt) andskruvHeader({ name, value })(an HTTP response header; the namestatussets the status code) are written out by the server and skipped in the browser. See the SSR walkthrough.
Attributes
- Event handlers (
onclick, …) are compared by function identity: the same function keeps its listener, a new function replaces it, and a removed key removes it. A handler written inline is a new function on every render. Anyon<name>listens for<name>, so custom events work too. - Boolean attributes (
disabled,checked,open, …):trueadds the attribute andfalseremoves it. Any other value also adds it, because in HTML a boolean attribute is on whenever it is present, even asdisabled="false". null,undefinedandfalseremove an attribute, as they render nothing as children, soclass: active && "active"works. Attributes where"false"is a real value (aria-*,data-*,contenteditable,draggable,spellcheck,writingsuggestions,preserveAlpha) getfalseas the text"false"instead.checked,selected,value,mutedare also set as DOM properties, because the attribute only holds the initial value. Leaving the key out keeps what the user changed.value: undefinedsets the text"undefined"; use""to clear a value.- skruv attributes:
skruvKey: see Keys.skruvAfterCreate: (element) => {}: called once per element, after skruv first renders it (a new element, or one taken over from server-rendered HTML), for example to attach another library. Later renders do not call it again, even with a new function.skruvExternalChildren: true: another library owns the element's children (e.g. one attached withskruvAfterCreate). skruv still sets the element's attributes but never adds, changes or removes its children, and ignores children given in the tree. Without it, children skruv did not render are removed on the next render. To show skruv content next to the library's, give the library an element of its own:div( span(state.label), // skruv's content, updated on every render div({ skruvExternalChildren: true, skruvAfterCreate: mountChart }), )skruvOnRemove: (element) => {}: called (in a microtask) after skruv removes the element or an ancestor of it, for example to detach that library. See Component lifecycle.skruvRenderOnce: true: render the element only the first time. See Skipping unchanged elements.skruvWaitForNotEmpty: true: keep the old children until new ones are ready (avoids flicker when an async child is replaced).skruvFinished: false: marks an async result as incomplete (e.g. a loading message), sohydrationPromisewaits for the next result.
Keys
skruvKey must be an object or array; it identifies a child across renders.
- A child whose key matches a previous key reuses that DOM node (it is moved, not recreated), so its state, such as input values and child elements, is kept. Moving a node takes it out of the page and puts it back, so a focused element inside it loses focus, and iframes and CSS animations in it restart. Only nodes that change order with their siblings are moved: a node that just shifts because items before it are added or removed stays in the page. Use keys on list items that can be reordered or filtered.
- A key only decides which node is reused. The node's attributes and children are then diffed like any other node's, so what it shows is always up to date, whether or not it depends on the key.
- A
createStateitem is a good key: it keeps its identity when the array is reordered (li({ skruvKey: todo }, todo.text)). The key can also be mutated in place.
Skipping unchanged elements
Diffing a node is cheap, but a long list diffs every item on every render.
For elements whose content never changes once shown, add
skruvRenderOnce: true next to a skruvKey:
ol(rows.map((row) => li({ skruvKey: row, skruvRenderOnce: true }, row.label)))
- It needs a
skruvKey; rendering it without one throws aTypeError. The key makes sure a skipped element shows the item it was rendered for: without one, elements are matched by position, so a reused element could keep another item's content. For an element outside a list, any object works (const footerKey = {}). - The first render into the element renders it as usual: a new element, one that replaces an element with another tag, or one taken over from server-rendered HTML. So does a render with another key.
- After that, a parent's render with the same key leaves the element, its attributes and its
children as they are, so nothing in it is diffed. Its own async children
still update it, and a keyed element still moves. When one of them yields,
the element is diffed like any other, which removes children another
library added to it; give that library its own element with
skruvExternalChildren(see Attributes). - To show new content, give it a new key (e.g. a new object for a changed
row), or leave the flag off while it can change. A key changed in place
(a
createStateitem whose fields you assign) is the same key, so the change is not shown. Event handlers keep the functions from the first render, so read live state in them rather than values captured at render time. - Async components in the skipped part of a new tree are stopped at once; the ones from the first render keep running.
Component lifecycle
There is no mount/unmount API.
For setup, use
skruvAfterCreate; for cleanup,skruvOnRemove. It is called after skruv removes the element or an ancestor of it (its slot now renders something else, or its list item is gone). A keyed element that moves is not removed. A keyed element that is removed and shown again later (e.g. by a filter) has hadskruvOnRemovecalled, andskruvAfterCreatedoes not run for it again.Async components (async generator functions and async functions) are called with an
AbortSignal. It aborts as soon as the component is no longer used: its element is removed, or its parent yields a tree without it (a component written inline in the parent is a new one on every yield). Pass the signal tofetch, and iterate state withuntilAborted(state, signal)(utils/generators/untilAborted.js), so thefor awaitloop ends, andtry { … } finally { … }runs, at once:const Clock = async function* (signal) { try { for await (const s of untilAborted(state, signal)) yield p(s.time) } finally { // cleanup } }Without
untilAborted, a generator waiting on state is stopped at its next update. A component that already finished on its own (it returned, or its promise resolved) is not aborted. Async iterables and promises given directly (not as functions) get no signal; iterables are closed withreturn().A function component that was stopped starts again, with a new signal, when an enclosing async source yields it again (e.g. a module-level component that is hidden and shown again).
An inline component in a list item is a new one on every yield of the list: the new one is started and the one it replaces is stopped. In long lists, use a module-level component (
li({ skruvKey: t }, Badge)), which is only started once.JSX calls function components itself, with their props as the first argument, so
<Clock />gets props, not a signal. The generator it returns is closed withreturn()and stops at its next update. To get a signal, pass the function as a child:{Clock}.For connect/disconnect callbacks that also cover DOM changes made outside skruv, use a custom element (
connectedCallback/disconnectedCallback).
State (utils/state.js)
createState(object) returns a proxy. Change it with normal code
(assignment, delete, push, splice, …) and subscribe with for await:
const state = createState({ todos: ["Write todos"] })
async function* todoList() {
for await (const todos of state.todos) {
yield ol(todos.map((todo) => li(todo)))
}
}
h1(state.todos.getGenerator(0)) // a single value as a child
state.todos.unshift("Another one") // updates both
- A subscription gets the current value first, then a new value after each change in that object or below it. Several synchronous changes arrive as one update.
- Subscriptions run until you
breakout of the loop. In a long-running server, don't start them per request (see SSR). - Assigning an object or array to a key updates the existing one in place, so
existing subscriptions keep working. Array items keep their identity when the
array is reordered (
splice,sort, …). - Only plain objects and arrays are reactive, including ones made in another
realm (an iframe, or JSON from
fetchduring SSR). Other values (Dates, Maps, Sets, class instances, …) are stored as they are, and changes inside them are not noticed; assign a new value instead. Storing a Map, Set or class instance logs a console warning. state.toJSONis a plain copy, andJSON.stringify(state)works.- Limits:
getGeneratorandtoJSONcan't be used as keys, symbol keys are dropped from nested objects, the root object can't be replaced, and a key that changes type (e.g. array →null→ array) breaks loops over its old value (they get no more updates; a console warning reports it). Subscribe through the parent orgetGenerator(key)if a value can change type. - In TypeScript, assign objects and arrays with
setState(state, "key", value); plain=only type-checks for primitive values.
Async components (utils/syncify.js)
syncify(tree) returns a copy of the tree in which async generators, promises
and functions are replaced by their latest result (null until the first one).
When a new result arrives, only that part of the page is re-rendered.
- Event handlers,
skruvAfterCreateandskruvOnRemoveare kept as functions; other functions are components. Async ones are called with anAbortSignal(see Component lifecycle), others with no arguments. - Each async source runs once, even if it appears in several places or a parent generator yields it again: every place shows its latest result. Function components are called again whenever an enclosing async source yields. Syncifying the same tree again reuses the results.
hydrationPromiseresolves when the first results are in. In the browser you can render right away; async parts fill in as they resolve. Await it beforerenderonly when the first render must be complete: on the server (so the response is the whole page), when taking over server-rendered HTML (so it is not replaced by a half-empty page), or in tests. It resolves once per page load;reset()starts over.
Scoped CSS (utils/css.js)
css`...` returns a class name; cssTextGenerator yields the CSS of all
such stylesheets, each wrapped in a native @scope rule for elements with its
class (:scope is the element itself). Put style(cssTextGenerator) in the
head and the class on an element. Needs @scope support: Chrome/Edge 118,
Safari 17.4, Firefox 146.
skruv-bundle minifies the CSS in css`…` templates (and in templates
tagged with a /*css*/ comment) at build time. A template it cannot minify
is left as written, with a build warning; the app works either way. It finds
the templates with a small scanner rather than a full parser, and the
scanner reads JSX text as if it were code. In files with JSX this means:
- A
css`…`later on the same line as a JSX closing tag (</p>), or as a'or"in JSX text, is not found, so it is not minified. Start the template on a new line. - A lone backtick in JSX text pairs with the next backtick in the file, so
later templates are not found, and code between two backticks can be
taken for a template (it is then usually left as written, with a warning).
Write the backtick as
{"`"}. - Visible text such as
<p>use css`color: red`</p>is taken for a template. It cannot contain braces in JSX, so it is not valid CSS and is left as written, with a warning.
Generator helpers (utils/generators/)
| Helper | Description |
|---|---|
addLoader(component, loader, ms = 300) |
Shows loader if component has not yielded after ms. Give the loader skruvFinished: false. See the loader example. |
combineGens(...gens) |
Yields the latest value of every generator whenever one of them yields. Ends when they all have ended. |
combineGensSettled(...gens) |
Like combineGens, but only once every generator has yielded (any value, including 0 and ""). |
waitPromise(ms, value?) |
A promise that resolves with value after ms. |
waitGen(ms, value), interval(ms, value) |
Yield value once after ms, or ms after each next(). |
fromCallback(setup) |
Turns a callback-based source into an async generator. See below. |
untilAborted(iterable, signal) |
Iterates iterable until signal aborts, then ends the loop at once and closes the source (e.g. a state subscription). |
Ending any of them early (break, return(), or untilAborted when a
component is removed) takes effect at once: timers are cleared, and the
sources of combineGens and combineGensSettled are closed (so state
subscriptions are released). If one of their sources throws, the others are
closed and the error is thrown to the consumer.
fromCallback(setup) calls setup(callback, done, signal) on the first
next():
- every value passed to
callbackis yielded, in order; values that arrive while the consumer is busy are queued, not dropped; done()ends the iteration after the queued values, anddone(error)then throwserrorto the consumer;signalaborts when the iteration ends (bydone,break,return()oruntilAborted), so listeners and requests given it are removed.setupmay also return a cleanup function, called at the same time.
const resize = fromCallback((push, done, signal) => {
addEventListener("resize", () => push(innerWidth), { signal })
})
channel, fetcher and router (for a PostgREST backend) have moved to
experimental/ in the repository and are no
longer published.
JSX
Set jsxImportSource in tsconfig.json:
{ "compilerOptions": { "jsx": "react-jsx", "jsxImportSource": "skruv" } }
skruvuses HTML names (class,for,onclick);skruv/reactuses React names (className,htmlFor,onClick,strokeWidth) and converts them. Withskruv/react,onChangelistens forinput, as in React.- Attributes, event handlers and component props are type-checked, and JSX
expressions are typed as skruv content (
JSX.Element). Children are checked to be renderable (no plain objects or symbols), but not against the element's content model: every JSX expression has the same type, whatever its tag. Type a component'schildrenprop asJSXChildren(fromskruv/utilityTypes) to pass it on to an element. - Function components are called with
(props, children). - Build with
skruv-bundle index.tsx index.min.js(skruv-bundle-reactfor React names). Thetsconfig.jsonsetting takes precedence over the bundler's and over esbuild's--jsx-import-source.- Requires
esbuild-wasm
- Requires
@skruv/jsxand@skruv/jsx-reactare deprecated: switchjsxImportSourcetoskruvorskruv/react.
Server-side rendering
skruv-ssr app.min.jsruns an HTTP server that renders the app for each request;skruv-ssr-dev app.ts app.min.jsalso rebuilds on changes and reloads the page.skruv-ssg https://example.com/ app.min.js index.htmlrenders one page to a file.- The app must
await hydrationPromisebeforerenderandexport defaulta function that does so. See examples/ssr/index.js and the SSR walkthrough. - Each render runs in a new
node:vmcontext: the app, skruv and the document are fresh for every request, nothing is shared between concurrent requests, and the context is garbage collected afterwards (timers it left are cleared). An error in one render fails that request (500), not the server. - A render that has not finished after 10 seconds fails (a 500 from
skruv-ssr, an error fromskruv-ssg) and its context is released. Change it with--render-timeout=<duration>on any of the three commands, e.g.--render-timeout=30sor500ms;0turns it off. - Each render's context has minidom's DOM plus the server's own
console,fetch,Headers,Request,Response,URLSearchParams,TextEncoder,TextDecoder,AbortController,AbortSignal, timers,queueMicrotask,structuredClone,atob,btoa,cryptoandperformance. Objects these return belong to the server's realm, not the page's, so on the server they fail checks against the page's own built-ins:(await res.json()).constructor === Objectandnew TextEncoder().encode(s) instanceof Uint8Arrayarefalse.res instanceof Responseworks, becauseResponseis the server's too.createStateaccepts such objects and arrays like any other. Where your own code checks identity, copy the data into the page's realm first, e.g.JSON.parse(JSON.stringify(data)). - The bundle must be self-contained (built with
skruv-bundle) and must not use top-level await. These commands needesbuild-wasm(an optional peer dependency), which turns the bundle into a script once at startup. - Dynamic imports (
import()) are not run on the server. A lazy part that depends on one, e.g.div(() => import("./chart.js").then((m) => m.default())), is left empty and hydration does not wait for it; the browser loads it after hydration. Code that awaits a dynamic import itself can checkglobalThis.isSkruvSSRfirst. On the server such an import fails with an error that hasskruvSSRSkipped: true, whichsyncifytreats as "no result". utils/renderBundle.jsexportscompileBundleandrenderBundle(bundle, url, { timeout }), to render a bundle from your own server.
minidom (utils/minidom.js)
The DOM used for SSR and for tests in Node. Importing it installs its globals
(document, Element, FormData, …) and sets globalThis.isSkruvSSR, so only
import it in Node.
- Exports
toHTML(element, "", headers)to serialize (headers fromskruvHeaderare collected inheaders),getDocumentElement(),reset()for a new document andLocation. - It is minimal:
querySelectoralways returnsnull, elements have no.click()(usedispatchEvent, which passes the event itself to handlers and always bubbles), andFormDataand formreset()cover inputs, textareas and selects only.
Testing
minidom runs the real app in Node with node --test, without a browser or
jsdom:
// counter.test.js: run with `node --test`
import "skruv/utils/minidom.js" // first: installs document, Event, … in Node
import assert from "node:assert/strict"
import { test } from "node:test"
import { elementFactory, render } from "skruv"
import { createState } from "skruv/utils/state.js"
import { hydrationPromise, syncify } from "skruv/utils/syncify.js"
// The app (in a real project, import its tree and state from your module)
const { html, body, button, p } = elementFactory
const state = createState({ count: 0 })
const tree = html(
body(
p(async function* () {
for await (const s of state) {
yield `Clicked ${s.count} times`
}
}),
button({ onclick: () => state.count++ }, "Click"),
),
)
// A change re-renders after a chain of microtasks; one macrotask waits for all
const settle = () => new Promise((resolve) => setTimeout(resolve))
test("clicking the button updates the text", async () => {
render(syncify(tree))
await hydrationPromise
await settle()
const [text, btn] = document.documentElement.childNodes[0].childNodes
assert.equal(text.textContent, "Clicked 0 times")
btn.dispatchEvent(new Event("click")) // minidom elements have no .click()
await settle()
assert.equal(text.textContent, "Clicked 1 times")
assert.equal(state.count, 1)
})
- Import minidom before the app, so the app's module code runs against it.
- Find elements by walking
childNodes(querySelectorreturnsnull), or check the whole page withtoHTML(getDocumentElement()). - Comparing elements with
===before and after a change shows whether skruv patched a node in place or replaced it. node --testruns each file in its own process. Within a file,reset()from minidom and fromsyncify.jsstart a fresh document and hydration.- More examples:
tests/render.test.js,tests/syncify.test.jsandtests/keys.test.js.
TypeScript
The package ships .d.ts files, so tsc --checkJs and editors check your code
without a build step. Element types, State and Syncified can be imported
from skruv/utilityTypes. Custom events can be typed for all elements:
// custom-events.d.ts
export {}
declare module "skruv/utilityTypes" {
interface SkruvCustomEventMap {
"todo-added": CustomEvent<{ id: number }>
}
}
liten (skruv/liten)
A separate, smaller (about 0.5 kB) renderer with its own API and no async
components or SSR. See liten/README.md. It was previously
published as @skruv/liten, which is now deprecated.
Contributing
See CONTRIBUTING.md. npm run pre-release builds, tests,
lints and type-checks everything; commit the files it regenerates.
Linting and type-checking without native binaries
skruv lints and type-checks with WebAssembly builds of Biome and TypeScript, so
no platform-specific binaries are installed. Two small scripts drive them; copy
them into a scripts/ folder in your project if you want the same (both treat
the folder above the script as the project root):
scripts/tsc.jsrunstscfrom@typescript/typescript-wasip1-wasmunder Node's WASI.scripts/biome.jsdoes whatbiome ci(and with--write,biome check --write) does, using@biomejs/wasm-nodejsand yourbiome.json. It reports unformatted files without a diff.
They are stopgaps until Biome and TypeScript ship WebAssembly CLIs, and are not part of the package's API.
Explorar proyectos relacionados
Cargando…