Skip to content
Proyectos

Acerca de

No-dependency, no-build, small JS view-library/framework-ish-thing.

Herramientas de desarrollo

Cómo se miden estas cifras

Crecimiento 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

Original

skruv

skruv

No-dependency, no-build, small JS view-library/framework-ish-thing.

Quick start • Examples • Docs • Upgrading • Contributing

Github • NPM

  • 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.js and the skruv-ssr/skruv-ssg commands)
    • scoped CSS (utils/css.js)
    • JSX (skruv/jsx-runtime, skruv/react/jsx-runtime)
    • a bundler (skruv-bundle, needs esbuild-wasm)
  • 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 0 and "") become text; booleans, null and undefined render nothing, so cond && el works for boolean conditions; arrays are flattened. With syncify, children can also be async generators, promises and functions.
  • svg, math, feed, urlset and sitemapindex switch the namespace of their content; foreignObject switches 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 a robots.txt) and skruvHeader({ name, value }) (an HTTP response header; the name status sets 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. Any on<name> listens for <name>, so custom events work too.
  • Boolean attributes (disabled, checked, open, …): true adds the attribute and false removes it. Any other value also adds it, because in HTML a boolean attribute is on whenever it is present, even as disabled="false".
  • null, undefined and false remove an attribute, as they render nothing as children, so class: active && "active" works. Attributes where "false" is a real value (aria-*, data-*, contenteditable, draggable, spellcheck, writingsuggestions, preserveAlpha) get false as the text "false" instead.
  • checked, selected, value, muted are also set as DOM properties, because the attribute only holds the initial value. Leaving the key out keeps what the user changed. value: undefined sets 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 with skruvAfterCreate). 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), so hydrationPromise waits 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 createState item 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 a TypeError. 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 createState item 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 had skruvOnRemove called, and skruvAfterCreate does 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 to fetch, and iterate state with untilAborted(state, signal) (utils/generators/untilAborted.js), so the for await loop ends, and try { … } 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 with return().

  • 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 with return() 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 break out 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 fetch during 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.toJSON is a plain copy, and JSON.stringify(state) works.
  • Limits: getGenerator and toJSON can'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 or getGenerator(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, skruvAfterCreate and skruvOnRemove are kept as functions; other functions are components. Async ones are called with an AbortSignal (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.
  • hydrationPromise resolves when the first results are in. In the browser you can render right away; async parts fill in as they resolve. Await it before render only 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 callback is yielded, in order; values that arrive while the consumer is busy are queued, not dropped;
  • done() ends the iteration after the queued values, and done(error) then throws error to the consumer;
  • signal aborts when the iteration ends (by done, break, return() or untilAborted), so listeners and requests given it are removed. setup may 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" } }
  • skruv uses HTML names (class, for, onclick); skruv/react uses React names (className, htmlFor, onClick, strokeWidth) and converts them. With skruv/react, onChange listens for input, 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's children prop as JSXChildren (from skruv/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-react for React names). The tsconfig.json setting takes precedence over the bundler's and over esbuild's --jsx-import-source.
    • Requires esbuild-wasm
  • @skruv/jsx and @skruv/jsx-react are deprecated: switch jsxImportSource to skruv or skruv/react.

Server-side rendering

  • skruv-ssr app.min.js runs an HTTP server that renders the app for each request; skruv-ssr-dev app.ts app.min.js also rebuilds on changes and reloads the page.
  • skruv-ssg https://example.com/ app.min.js index.html renders one page to a file.
  • The app must await hydrationPromise before render and export default a function that does so. See examples/ssr/index.js and the SSR walkthrough.
  • Each render runs in a new node:vm context: 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 from skruv-ssg) and its context is released. Change it with --render-timeout=<duration> on any of the three commands, e.g. --render-timeout=30s or 500ms; 0 turns 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, crypto and performance. 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 === Object and new TextEncoder().encode(s) instanceof Uint8Array are false. res instanceof Response works, because Response is the server's too. createState accepts 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 need esbuild-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 check globalThis.isSkruvSSR first. On the server such an import fails with an error that has skruvSSRSkipped: true, which syncify treats as "no result".
  • utils/renderBundle.js exports compileBundle and renderBundle(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 from skruvHeader are collected in headers), getDocumentElement(), reset() for a new document and Location.
  • It is minimal: querySelector always returns null, elements have no .click() (use dispatchEvent, which passes the event itself to handlers and always bubbles), and FormData and form reset() 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 (querySelector returns null), or check the whole page with toHTML(getDocumentElement()).
  • Comparing elements with === before and after a change shows whether skruv patched a node in place or replaced it.
  • node --test runs each file in its own process. Within a file, reset() from minidom and from syncify.js start a fresh document and hydration.
  • More examples: tests/render.test.js, tests/syncify.test.js and tests/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.js runs tsc from @typescript/typescript-wasip1-wasm under Node's WASI.
  • scripts/biome.js does what biome ci (and with --write, biome check --write) does, using @biomejs/wasm-nodejs and your biome.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…