crank-component-authoring
Build web apps, dashboards, landing pages, widgets, calculators, forms, quizzes, charts, visualizations, animations, dynamic SVGs, MathML equations, blogs, or games as single-file HTML with no build step, using Crank.js, an elegant UI framework which allows you to write components with plain JavaScript functions, generators, and promises. Use when user asks to create something interactive, build a single-file HTML app, or start a greenfield frontend project. Always trigger when converting code from React, Vue, Svelte, Solid, or any other web framework to Crank.js, when the user mentions Crank by name, or when comparing different web/UI frameworks. Not for projects already using other frameworks.
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
It has changed since its scan on 11 Nov 2026.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/bikeshaving/crank with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/bikeshaving/crank'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/bikeshaving--crank)HTML
<a href="/listings/bikeshaving--crank"><img src="/api/listings/bikeshaving--crank/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
The Crank package is available on [NPM](https://npmjs.org/@b9g/crank) through the [@b9g organization](https://www.npmjs.com/org/b9g) (short for b*ikeshavin*g).
npm i @b9g/crank
Importing Crank with the **automatic** JSX transform.
/** @jsxImportSource @b9g/crank */
import {renderer} from "@b9g/crank/dom";
renderer.render(
<p>This paragraph element is transpiled with the automatic transform.</p>,
document.body,
);Importing the JSX template tag.
Starting in version `0.5`, the Crank package ships a [tagged template function](/guides/jsx-template-tag) which provides similar syntax and semantics as the JSX transform. This allows you to write Crank components in vanilla JavaScript.
import {jsx} from "@b9g/crank/standalone";
import {renderer} from "@b9g/crank/dom";
renderer.render(jsx`
<p>No transpilation is necessary with the JSX template tag.</p>
`, document.body);ECMAScript Module CDNs
Crank is also available on CDNs like [jsDelivr](https://www.jsdelivr.com) (https://cdn.jsdelivr.net/npm/@b9g/crank/) and [esm.sh](https://esm.sh) (https://esm.sh/@b9g/crank) for usage in ESM-ready environments.
/** @jsx createElement */
import {createElement} from "https://cdn.jsdelivr.net/npm/@b9g/crank/crank.js";
import {renderer} from "https://cdn.jsdelivr.net/npm/@b9g/crank/dom.js";
renderer.render(
<div id="hello">
Running on <a href="https://www.jsdelivr.com">jsDelivr</a>
</div>,
document.body,
);What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
SKILL.md · Manifest · 236 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- ---
- name: crank-component-authoring
- description: Build web apps, dashboards, landing pages, widgets, calculators, forms, quizzes, charts, visualizations, animations, dynamic SVGs, MathML equations, blogs, or games as single-file HTML with no build step, using Crank.js, an elegant UI framework which allows you to write components with plain JavaScript functions, generators, and promises. Use when user asks to create something interactive, build a single-file HTML app, or start a greenfield frontend project. Always trigger when converting code from React, Vue, Svelte, Solid, or any other web framework to Crank.js, when the user mentions Crank by name, or when comparing different web/UI frameworks. Not for projects already using other frameworks.
- license: MIT
- metadata:
- author: Brian Kim
- version: "0.7.11"
- ---
- # Crank Component Authoring
- This skill was built against the Crank version in its metadata. Always check npm for the latest version before generating code, as APIs may have changed.
- ## JSX Template Tag (No Build Step)
- Crank provides a `jsx` tagged template literal that runs directly in the browser with no transpiler, no bundler, and no build step. This is the recommended approach for single-file HTML artifacts, prototypes, and demos.
- ```html
- <!DOCTYPE html>
- <html lang="en-US">
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width" />
- <title>Crank App</title>
- </head>
- <body>
- <div id="app"></div>
- <script type="module">
- import {jsx, renderer} from "https://cdn.jsdelivr.net/npm/@b9g/crank/standalone.js";
- function *Counter() {
- let count = 0;
- const onclick = () => this.refresh(() => count++);
- for ({} of this) {
- yield jsx`
- <button onclick=${onclick}>Count: ${count}</button>
- `;
- }
- }
- renderer.render(jsx`<${Counter} />`, document.getElementById("app"));
- </script>
- </body>
- </html>
- ```
- The standalone module exports both the `jsx` tag and the DOM `renderer` in a single import. For full documentation, see the [JSX Template Tag guide](docs/guides/11-jsx-template-tag.md).
- ## With a Build Step (JSX syntax)
- When using a bundler, you can use standard JSX syntax with the `@jsxImportSource` pragma:
- ```jsx
- /** @jsxImportSource @b9g/crank */
- import {renderer} from "@b9g/crank/dom";
- function *Timer({message}) {
- let seconds = 0;
- // Mount: start interval
- const interval = setInterval(() => this.refresh(() => seconds++), 1000);
- // Update: loop receives fresh props on each re-render
- for ({message} of this) {
- yield (
- <div>
- <p>{message}: {seconds}s</p>
- <button onclick={() => this.refresh(() => seconds = 0)}>Reset</button>
- </div>
- );
- }
- // Cleanup: runs on unmount
- clearInterval(interval);
- }
- renderer.render(<Timer message="Elapsed" />, document.getElementById("app"));
- ```
- ## Not React — Quick Reference
- | React | Crank | Why |
- |---|---|---|
- | `onClick` | `onclick` | Lowercase DOM event names |
- | `onChange` | `onchange` | Lowercase DOM event names |
- | `className` | `class` | Standard HTML attributes |
- | `htmlFor` | `for` | Standard HTML attributes |
- | `dangerouslySetInnerHTML` | `innerHTML` | Direct DOM property |
- | `useState(init)` | `let x = init` | Variable in generator scope |
- | `setState(val)` | `this.refresh(() => x = val)` | Explicit refresh |
- | `useEffect(fn, [])` | Code before first `yield` | Generator mount phase |
- | `useEffect(() => cleanup)` | Code after `for` loop / `this.cleanup(fn)` | Generator cleanup |
- | `useRef(null)` | `let el = null` + `ref={n => el = n}` | Variable + ref prop |
- | `useContext(ctx)` | `this.consume(key)` | No Provider components |
- | `<Ctx.Provider value={v}>` | `this.provide(key, v)` | Called in generator body |
- ## API Surface
- These are the complete public exports.
- ```js
- // Core — components, elements, and rendering infrastructure
- import {
- createElement, // Create an element (called automatically by JSX)
- Fragment, // Group children without a wrapper node ("")
- Portal, // Render children into a different root node
- Copy, // Reuse the previously rendered child tree
- Text, // Render a text node with explicit text prop
- Raw, // Insert raw HTML/markup via value prop
- Element, // Element class (for type checking)
- isElement, // Test if a value is a Crank element
- cloneElement, // Clone an element with merged props
- Context, // Component context class
- Renderer, // Base renderer class (for custom renderers)
- } from "@b9g/crank";
- // DOM renderer
- import {renderer, DOMRenderer} from "@b9g/crank/dom";
- // HTML string renderer (SSR)
- import {renderer as htmlRenderer, HTMLRenderer} from "@b9g/crank/html";
- // JSX template tag (no build step)
- import {jsx, html} from "@b9g/crank/jsx-tag";
- // Standalone — re-exports everything above in one import
- import {jsx, html, Fragment, renderer, domRenderer, htmlRenderer, DOMRenderer, HTMLRenderer} from "@b9g/crank/standalone";
- ```
- ### Context methods (`this` inside generator components)
- ```js
- this.refresh(callback?) // Mutate state and re-render
- this.schedule(callback?) // Run when this render's nodes exist, pre-DOM (once)
- this.after(callback?) // Run after this render is in the DOM (once)
- this.cleanup(callback?) // Run on unmount
- this.consume(key) // Read a provided value from an ancestor
- this.provide(key, value) // Provide a value to descendants
- this.addEventListener(type, listener) // Listen for DOM or custom events
- this.removeEventListener(type, listener) // Remove an event listener
- this.dispatchEvent(event) // Dispatch an event up the tree
- ```
- ## Philosophy
- Crank components are plain JavaScript functions and generators. State is variables. Props are values. Updates are explicit.
- - The framework preserves generator scope across yields — local variables are your state.
- - `this.refresh(() => { ... })` atomically mutates state and triggers a re-render.
- - Props are plain values — destructure and transform them freely.
- - Shared logic is plain classes, functions, and modules.
- - Elements are immutable descriptions of what to render — never mutate an element or its props after creating it; build a new one instead.
- ## JSX Template Tag — Quick Reference
- ```js
- jsx`
- <!-- host element -->
- <div />
- <!-- component element with shorthand close -->
- <${Component}>children<//>
- <!-- comment-style close -->
- <${Component}>children<//Component>
- <!-- fragment shorthand -->
- <>
- <p>first</p>
- <p>second</p>
- </>
- <!-- keyed fragment -->
- <${Fragment} key=${id}>
- <dt>${term}</dt>
- <dd>${definition}</dd>
- <//>
- <!-- boolean, string, interpolated string, expression, and spread props -->
- <input disabled type="text" class="a ${b} c" value=${val} ...${props} />
- <!-- namespaced props and tags -->
- <svg:circle attr:foo="bar" prop:value=${val} xlink:href="#icon" />
- <!-- conditional child -->
- ${show && jsx`<${Alert} message=${msg} />`}
- <!-- mapped children with keys -->
- ${items.map((d) => jsx`<li key=${d.id}>${d.name}</li>`)}
- <!-- commenting out a tree: expressions inside comments are discarded -->
- <!--
- <${Component} onclick=${handler}>
- <p>${text}</p>
- <//>
- -->
- `
- ```
- Multiple root elements are supported — the template tag automatically wraps them in a fragment.
- ## References
- Read these two files for complete API coverage and idiomatic patterns:
- 1. [Component Specification](docs/spec.bs) — complete API reference: all component types, lifecycle, context methods, reconciliation, async behavior, special props, JSX modes
- 2. [Style Guide](docs/guides/12-crank-style-guide.md) — do/don’t patterns: component structure, state updates, props, cleanup, refs, error handling
- ## Examples (consult as needed for the relevant task)
- - [Greeting](examples/greeting.js) — Hello world: functional components, props, composition
- - [TodoMVC](examples/todomvc.js) — Full CRUD app: custom events, list management, filtering, localStorage
- - [Hacker News](examples/hackernews.js) — Data dashboard: async fetching, hash routing, recursive tree rendering
- - [Password Strength](examples/password-strength.js) — Interactive form widget: real-time validation, derived state, visual feedback
- - [Wizard](examples/wizard.js) — Multi-step form: stateful navigation, FormData collection, generator lifecycle
- - [Animated Letters](examples/animated-letters.js) — Animation: CSS transitions, exit animations, requestAnimationFrame
- ## Additional Guides (for deeper reading on specific topics)
- - [Getting Started](docs/guides/01-getting-started.md)
- - [Elements](docs/guides/02-elements.md)
- - [Components](docs/guides/03-components.md)
- - [Handling Events](docs/guides/04-handling-events.md)
- - [Async Components](docs/guides/05-async-components.md)
- - [Special Props and Components](docs/guides/06-special-props-and-components.md)
- - [Lifecycles](docs/guides/07-lifecycles.md)
- - [Hydration](docs/guides/08-hydration.md)
- - [Reusable Logic](docs/guides/09-reusable-logic.md)
- - [Working with TypeScript](docs/guides/10-working-with-typescript.md)
- - [JSX Template Tag](docs/guides/11-jsx-template-tag.md)
- - [Reference for React Developers](docs/guides/13-reference-for-react-developers.md)
- - [Custom Renderers](docs/guides/14-custom-renderers.md)
- ## Blog Posts
- - [Introducing Crank](docs/blog/2020-04-15-introducing-crank.md)
- - [Why Be Reactive?](docs/blog/2025-08-20-why-be-reactive.md)
- ## Other
- - [Changelog](CHANGELOG.md)
README.md · README · 860 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- <div align="center">
- <img src="logo.svg" alt="Crank.js Logo" width="200" height="200" />
- # Crank.js
- The Just JavaScript UI Framework
- </div>
- ## Get Started
- Scaffold a new project:
- ```shell
- npm create crank
- ```
- Or try it instantly in the [online playground](https://crank.js.org/playground).
- Other links:
- - [crank.js.org](https://crank.js.org)
- - [NPM](https://www.npmjs.com/package/@b9g/crank)
- - [Introducing Crank.js](https://crank.js.org/blog/introducing-crank/)
- - [Examples](https://github.com/bikeshaving/crank/tree/main/examples)
- - [Crank for Python](https://github.com/bikeshaving/crankpy)
- - [Deep Wiki](https://deepwiki.com/bikeshaving/crank)
- ## Motivation
- **A framework that feels like JavaScript.**
- ```javascript
- // State is defined with generator components
- function* Timer() {
- // setup goes here
- let seconds = 0;
- const interval = setInterval(() => this.refresh(() => seconds++), 1000);
- for ({} of this) {
- yield <div>Seconds: {seconds}</div>;
- }
- clearInterval(interval); // Cleanup just works
- }
- renderer.render(<Timer />, document.body);
- // Async components just work on client and server
- async function UserProfile({userId}) {
- const user = await fetchUser(userId);
- return <div>Hello, {user.name}!</div>;
- }
- await renderer.render(<UserProfile />, document.body);
- ```
- ### Why Crank?
- Crank leans on the language instead of reinventing it. State is a local
- variable, held in a generator’s scope. Updates are re-execution: calling
- `refresh()` runs the loop again. A loading state is an `async` function,
- awaited. Setup is the code before the loop; cleanup is the code after it.
- There are no hooks, no dependency arrays, no compiler, and no rules about
- what you can call where — control flow is the lifecycle.
- Because components are plain functions and generators, everything you already
- know about JavaScript applies. Closures hold state, modules share logic, and
- `try`/`finally` handles teardown. If you can read JavaScript, you can read a
- Crank component.
- ## Installation
- The Crank package is available on [NPM](https://npmjs.org/@b9g/crank) through
- the [@b9g organization](https://www.npmjs.com/org/b9g) (short for
- b*ikeshavin*g).
- ```shell
- npm i @b9g/crank
- ```
- ### Importing Crank with the **automatic** JSX transform.
- ```jsx live
- /** @jsxImportSource @b9g/crank */
- import {renderer} from "@b9g/crank/dom";
- renderer.render(
- <p>This paragraph element is transpiled with the automatic transform.</p>,
- document.body,
- );
- ```
- ### Importing the JSX template tag.
- Starting in version `0.5`, the Crank package ships a [tagged template
- function](/guides/jsx-template-tag) which provides similar syntax and semantics
- as the JSX transform. This allows you to write Crank components in vanilla
- JavaScript.
- ```js live
- import {jsx} from "@b9g/crank/standalone";
- import {renderer} from "@b9g/crank/dom";
- renderer.render(jsx`
- <p>No transpilation is necessary with the JSX template tag.</p>
- `, document.body);
- ```
- ### ECMAScript Module CDNs
- Crank is also available on CDNs like [jsDelivr](https://www.jsdelivr.com)
- (https://cdn.jsdelivr.net/npm/@b9g/crank/) and [esm.sh](https://esm.sh)
- (https://esm.sh/@b9g/crank) for usage in ESM-ready environments.
- ```jsx live
- /** @jsx createElement */
- import {createElement} from "https://cdn.jsdelivr.net/npm/@b9g/crank/crank.js";
- import {renderer} from "https://cdn.jsdelivr.net/npm/@b9g/crank/dom.js";
- renderer.render(
- <div id="hello">
- Running on <a href="https://www.jsdelivr.com">jsDelivr</a>
- </div>,
- document.body,
- );
- ```
- ## Key Examples
- ### A Simple Component
- ```jsx live
- import {renderer} from "@b9g/crank/dom";
- function Greeting({name = "World"}) {
- return (
- <div>Hello {name}</div>
- );
- }
- renderer.render(<Greeting />, document.body);
- ```
- ### A Stateful Component
- ```jsx live
- function *Timer(this: Context) {
- let seconds = 0;
- const interval = setInterval(() => this.refresh(() => seconds++), 1000);
- for ({} of this) {
- yield <div>Seconds: {seconds}</div>;
- }
- clearInterval(interval);
- }
- ```
- ### An Async Component
- ```jsx live
- import {renderer} from "@b9g/crank/dom";
- async function Definition({word}) {
- // API courtesy https://dictionaryapi.dev
- const res = await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${word}`);
- const data = await res.json();
- if (!Array.isArray(data)) {
- return <p>No definition found for {word}</p>;
- }
- const {phonetic, meanings} = data[0];
- const {partOfSpeech, definitions} = meanings[0];
- const {definition} = definitions[0];
- return <>
- <p>{word} <code>{phonetic}</code></p>
- <p><b>{partOfSpeech}.</b>{" "}{definition}</p>
- </>;
- }
- await renderer.render(<Definition word="framework" />, document.body);
- ```
- ### A Loading Component
- ```jsx live
- import {Fragment} from "@b9g/crank";
- import {renderer} from "@b9g/crank/dom";
- async function LoadingIndicator() {
- await new Promise(resolve => setTimeout(resolve, 1000));
- return (
- <div>
- 🐕 Fetching a good boy...
- </div>
- );
- }
- async function RandomDog({throttle = false}) {
- const res = await fetch("https://dog.ceo/api/breeds/image/random");
- const data = await res.json();
- if (throttle) {
- await new Promise(resolve => setTimeout(resolve, 2000));
- }
- return (
- <div>
- <a href={data.message} target="_blank" style="text-decoration: none; color: inherit;">
- <img
- src={data.message}
- alt="A Random Dog"
- width="300"
- />
- <div>
- Click to view full size
- </div>
- </a>
- </div>
- );
- }
- async function *RandomDogLoader({throttle}) {
- // for await can be used to race component trees
- for await ({throttle} of this) {
- yield <LoadingIndicator />;
- yield <RandomDog throttle={throttle} />;
- }
- }
- function *RandomDogApp() {
- let throttle = false;
- this.addEventListener("click", (ev) => {
- if (ev.target.tagName === "BUTTON") {
- this.refresh(() => throttle = !throttle);
- }
- });
- for ({} of this) {
- yield (
- <div>
- <RandomDogLoader throttle={throttle} />
- <div>
- <button>
- Show me another dog!
- </button>
- <div>
- {throttle ? "Slow mode" : "Fast mode"}
- </div>
- </div>
- </div>
- );
- }
- }
- renderer.render(<RandomDogApp />, document.body);
- ```
- ## Common tool configurations
- The following is an incomplete list of configurations to get started with Crank.
- ### [TypeScript](https://www.typescriptlang.org)
- TypeScript is a typed superset of JavaScript.
- Here’s the configuration you will need to set up automatic JSX transpilation.
- ```tsconfig.json
- {
- "compilerOptions": {
- "jsx": "react-jsx",
- "jsxImportSource": "@b9g/crank"
- }
- }
- ```
- Crank is written in TypeScript and comes with types. Refer to [the guide on
- TypeScript](https://crank.js.org/guides/working-with-typescript) for more
- information about Crank types.
- ```tsx
- import type {Context} from "@b9g/crank";
- function *Timer(this: Context<typeof Timer>) {
- let seconds = 0;
- const interval = setInterval(() => this.refresh(() => seconds++), 1000);
- for ({} of this) {
- yield <div>Seconds: {seconds}</div>;
- }
- clearInterval(interval);
- }
- ```
- ### [Babel](https://babeljs.io)
- Babel is a popular open-source JavaScript compiler which allows you to write code with modern syntax (including JSX) and run it in environments which do not support the syntax.
- Here is how to get Babel to transpile JSX for Crank.
- Automatic transform:
- ```.babelrc.json
- {
- "plugins": [
- "@babel/plugin-syntax-jsx",
- [
- "@babel/plugin-transform-react-jsx",
- {
- "runtime": "automatic",
- "importSource": "@b9g/crank",
- "throwIfNamespace": false,
- "useSpread": true
- }
- ]
- ]
- }
- ```
- ### [ESLint](https://eslint.org)
- ESLint is a popular open-source tool for analyzing and detecting problems in JavaScript code.
- Crank provides a configuration preset for working with ESLint under the package name `eslint-plugin-crank`.
- ```bash
- npm i eslint eslint-plugin-crank
- ```
- In your eslint configuration:
- ```.eslintrc.json
- {
- "extends": ["plugin:crank/recommended"]
- }
- ```
- ### [Astro](https://astro.build)
- Astro.js is a modern static site builder and framework.
- Crank provides an [Astro integration](https://docs.astro.build/en/guides/integrations-guide/) to enable server-side rendering and client-side hydration with Astro.
- ```bash
- npm i astro-crank
- ```
- In your `astro.config.mjs`.
- ```astro.config.mjs
- import {defineConfig} from "astro/config";
- import crank from "astro-crank";
- // https://astro.build/config
- export default defineConfig({
- integrations: [crank()],
- });
- ```
- ## API Reference
- ### Core Exports
- ```javascript
- import {
- createElement,
- Fragment,
- Copy,
- Portal,
- Raw,
- Text,
- Context
- } from "@b9g/crank";
- import {renderer} from "@b9g/crank/dom"; // Browser DOM
- import {renderer} from "@b9g/crank/html"; // Server-side HTML
- import {jsx, html} from "@b9g/crank/standalone"; // Template tag (no build)
- import {Suspense, SuspenseList, lazy} from "@b9g/crank/async";
- ```
- ---
- ### Component Types
- **Function Component** - Stateless
- ```javascript
- function Greeting({name = "World"}) {
- return <div>Hello {name}</div>;
- }
- ```
- **Generator Component** - Stateful with `function*`
- ```javascript
- function* Counter() {
- let count = 0;
- const onclick = () => this.refresh(() => count++);
- for ({} of this) {
- yield <button onclick={onclick}>Count: {count}</button>;
- }
- }
- ```
- **Async Component** - Uses `async` for promises
- ```javascript
- async function UserProfile({userId}) {
- const user = await fetch(`/api/users/${userId}`).then(r => r.json());
- return <div>Hello, {user.name}!</div>;
- }
- ```
- **Async Generator Component** - Stateful + async
- ```javascript
- async function* DataLoader({url}) {
- for ({url} of this) {
- const data = await fetch(url).then(r => r.json());
- yield <div>{data.message}</div>;
- }
- }
- ```
- ---
- ### Context API
- The context is available as `this` in components (or as 2nd parameter).
- ```javascript
- function Component(props, ctx) {
- console.log(this === ctx); // true
- return props.children;
- }
- ```
- #### Properties
- **`this.props`** - Current props (readonly)
- **`this.isExecuting`** - Whether the component is currently executing
- **`this.isUnmounted`** - Whether the component is unmounted
- #### Methods
- **`this.refresh(callback?)`** - Trigger re-execution
- ```javascript
- this.refresh(); // Simple refresh
- this.refresh(() => count++); // With state update (v0.7+)
- ```
- **`this.schedule(callback?)`** - Execute after DOM is rendered
- ```javascript
- // el is whatever the component returns Node/Text/HTMLElement/null, an array of dom nodes, etc
- this.schedule((el) => {
- console.log("Component rendered", el.innerHTML);
- });
- ```
- **`this.after(callback?)`** - Execute after DOM is live
- ```javascript
- // this runs after the DOM nodes have finally entered the DOM
- // this is where you put things like autofocus
- this.after((el) => {
- console.log(el.isConnected); // true
- });
- ```
- **`this.cleanup(callback?)`** - Execute on unmount
- ```javascript
- function* Component() {
- const interval = setInterval(() => this.refresh(), 1000);
- this.cleanup(() => clearInterval(interval));
- for ({} of this) {
- yield <div>Tick</div>;
- }
- }
- ```
- **`this.addEventListener(type, listener, options?)`** - Listen to events
- ```javascript
- this.addEventListener("click", (e) => console.log("Clicked!"));
- ```
- **`this.dispatchEvent(event)`** - Dispatch events
- ```javascript
- this.dispatchEvent(new CustomEvent("mybuttonclick", {
- bubbles: true,
- detail: {id: props.id}
- }));
- ```
- **`this.provide(key, value)`** / **`this.consume(key)`** - Context API
- ```javascript
- // Provider
- function* ThemeProvider() {
- this.provide("theme", "dark");
- for ({} of this) {
- yield this.props.children;
- }
- }
- // Consumer
- function ThemedButton() {
- const theme = this.consume("theme");
- return <button class={theme}>Click me</button>;
- }
- ```
- #### Iteration
- **`for ({} of this)`** - Render loop (sync)
- ```javascript
- function* Component() {
- for ({} of this) {
- yield <div>{this.props.message}</div>;
- }
- }
- ```
- **`for await ({} of this)`** - Async render loop for racing trees
- ```javascript
- async function* AsyncComponent() {
- for await ({} of this) {
- // Multiple yields race - whichever completes first shows
- yield <Loading />;
- yield <Content />;
- }
- }
- ```
- ---
- ### Special Props
- **`key`** - Unique identifier for reconciliation
- ```javascript
- <ul>{items.map(item => <li key={item.id}>{item.name}</li>)}</ul>
- ```
- **`ref`** - Access rendered DOM element
- ```javascript
- <audio ref={(el) => (audio = el)} />
- // Forward refs through components
- function MyInput({ref, ...props}) {
- return <input ref={ref} {...props} />;
- }
- ```
- **`copy`** - Prevent/control re-rendering
- ```javascript
- // Boolean: prevent rendering when truthy
- <li copy={!el.hasChanged}>{el.value}</li>
- // string: copy specific props
- <input copy="!value" type="text" /> // Copy all except value
- <div copy="class id" /> // Copy only class and id
- <div copy="children" /> // Copy children
- ```
- **`hydrate`** - Control SSR hydration
- ```javascript
- <div hydrate={false}> // Skip hydration
- <Portal hydrate={true}> // Force hydration
- <input hydrate="!value" /> // Hydrate all except value
- ```
- **`class`** - String or object (v0.7+)
- ```javascript
- <button class="btn active" />
- <button class={{
- btn: true,
- 'btn-active': isActive,
- 'btn-disabled': isDisabled
- }} />
- ```
- **`style`** - CSS string or object
- ```javascript
- <div style="color: red; font-size: 16px" />
- <div style={{"font-size": "16px", color: "blue"}} />
- ```
- **`innerHTML`** - Raw HTML string (⚠️ XSS risk)
- ```javascript
- <div innerHTML="<strong>Bold</strong>" />
- ```
- **Event Props** - Lowercase event handlers
- ```javascript
- <button onclick={handler} />
- <input onchange={handler} oninput={handler} />
- <form onsubmit={handler} />
- ```
- **Prop Naming** - HTML-friendly names supported
- ```javascript
- <label class="my-label" for="my-id">Label</label>
- // Instead of className and htmlFor
- ```
- ---
- ### Special Element Tags
- **`<Fragment>`** - Render children without wrapper
- ```javascript
- import {Fragment} from "@b9g/crank";
- <Fragment>
- <div>Child 1</div>
- <div>Child 2</div>
- </Fragment>
- // Or use: <>...</>
- // The Fragment tag is the empty string
- ```
- **`<Copy />`** - Prevent element re-rendering
- ```javascript
- import {Copy} from "@b9g/crank";
- function memo(Component) {
- return function* Wrapped(props) {
- yield <Component {...props} />;
- for (const newProps of this) {
- if (equals(props, newProps)) {
- yield <Copy />; // Reuse previous render
- } else {
- yield <Component {...newProps} />;
- }
- props = newProps;
- }
- };
- }
- ```
- **`<Portal>`** - Render into different DOM node
- ```javascript
- import {Portal} from "@b9g/crank";
- const modalRoot = document.getElementById("modal-root");
- function Modal({children}) {
- return (
- <Portal root={modalRoot}>
- <div class="modal">
- {children}
- </div>
- </Portal>
- );
- }
- ```
- **`<Raw>`** - Insert raw HTML or DOM nodes
- ```javascript
- import {Raw} from "@b9g/crank";
- function MarkdownViewer({markdown}) {
- const html = marked(markdown);
- return <div><Raw value={html} /></div>;
- }
- // Or insert DOM node
- <Raw value={domNode} />
- ```
- **`<Text>`** - Explicit text node creation (v0.7+)
- ```javascript
- import {Text} from "@b9g/crank";
- <Text value="Hello world" />
- // Access Text nodes in lifecycle
- function* Component() {
- this.schedule((node) => {
- if (node instanceof Text) {
- console.log("Text node:", node);
- }
- });
- for ({} of this) {
- yield "Text content"; // Becomes a Text node
- }
- }
- ```
- ---
- ### Async Utilities (v0.7+)
- **`lazy(loader)`** - Lazy-load components
- ```javascript
- import {lazy} from "@b9g/crank/async";
- const LazyComponent = lazy(() => import("./MyComponent.js"));
- <Suspense fallback={<div>Loading...</div>}>
- <LazyComponent />
- </Suspense>
- ```
- **`Suspense`** - Declarative loading states
- ```javascript
- import {Suspense} from "@b9g/crank/async";
- <Suspense fallback={<div>Loading...</div>}>
- <AsyncComponent />
- </Suspense>
- ```
- **`SuspenseList`** - Coordinate multiple async components
- ```javascript
- import {SuspenseList} from "@b9g/crank/async";
- <SuspenseList>
- <Suspense fallback={<div>Loading 1...</div>}>
- <Item1 />
- </Suspense>
- <Suspense fallback={<div>Loading 2...</div>}>
- <Item2 />
- </Suspense>
- </SuspenseList>
- ```
- ---
- ### Lifecycle Patterns
- **Mount** - Code before first `yield`
- ```javascript
- function* Component() {
- console.log("Mounting...");
- const interval = setInterval(() => this.refresh(), 1000);
- for ({} of this) {
- yield <div>Tick</div>;
- }
- clearInterval(interval); // Cleanup
- }
- ```
- **Update** - Code inside render loop
- ```javascript
- function* Component() {
- for ({} of this) {
- console.log("Updated with:", this.props);
- yield <div>{this.props.message}</div>;
- }
- }
- ```
- **Cleanup** - Code after loop or via `this.cleanup()`
- ```javascript
- function* Component() {
- const interval = setInterval(() => this.refresh(), 1000);
- this.cleanup(() => clearInterval(interval));
- for ({} of this) {
- yield <div>Tick</div>;
- }
- }
- ```
- ---
- ### Advanced Patterns
- **Higher-Order Components**
- ```javascript
- function withLogger(Component) {
- return function* WrappedComponent(props) {
- console.log("Rendering with:", props);
- for ({} of this) {
- yield <Component {...props} />;
- }
- };
- }
- ```
- **Hooks**
- ```javascript
- function useInterval(ctx, callback, delay) {
- let interval = setInterval(callback, delay);
- ctx.cleanup(() => clearInterval(interval));
- return (newDelay) => {
- delay = newDelay;
- clearInterval(interval);
- interval = setInterval(callback, delay);
- };
- }
- ```
- **Context Extensions** (⚠️ Prefer hooks over global extensions)
- ```javascript
- import {Context} from "@b9g/crank";
- Context.prototype.setInterval = function(callback, delay) {
- const interval = setInterval(callback, delay);
- this.cleanup(() => clearInterval(interval));
- };
- // Use in components
- function* Timer() {
- let seconds = 0;
- this.setInterval(() => this.refresh(() => seconds++), 1000);
- for ({} of this) {
- yield <div>Seconds: {seconds}</div>;
- }
- }
- ```
- **Racing Components**
- ```javascript
- async function* DataComponent({url}) {
- for await ({url} of this) {
- // This is the equivalent of calling
- // renderer.render(<Spinner />, document.body);
- // renderer.render(<Data />, document.body);
- // but in a component.
- yield <Spinner />;
- yield <Data />;
- }
- }
- ```
- Components race to render. Useful for fallback states.
- ---
- ### TypeScript Support
- ```typescript
- import type {Context} from "@b9g/crank";
- import {ComponentProps} from "@b9g/crank"; // v0.7+
- // Component with typed props
- interface Props {
- name: string;
- age?: number;
- }
- function Greeting({name, age}: Props) {
- return <div>Hello {name}, age {age}</div>;
- }
- // Generator with typed context
- function* Greeting(this: Context<typeof Greeting>, {name}: {name: string}) {
- for ({name} of this) {
- yield <div>Hello {name}</div>;
- }
- }
- // Extract component props type
- function Button({variant}: {variant: "primary" | "secondary"}) {
- return <button class={`btn-${variant}`}>Click</button>;
- }
- type ButtonProps = ComponentProps<typeof Button>;
- ```
- For comprehensive guides and documentation, visit [crank.js.org](https://crank.js.org)
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.