Skip to content
Back to search

crank-component-authoring

SkillWorks with Claude CodeGitHub

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.

Checked today

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
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/bikeshaving--crank/badge.svg)](/listings/bikeshaving--crank)

HTML

<a href="/listings/bikeshaving--crank"><img src="/api/listings/bikeshaving--crank/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

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)

  1. ---
  2. name: crank-component-authoring
  3. 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.
  4. license: MIT
  5. metadata:
  6. author: Brian Kim
  7. version: "0.7.11"
  8. ---
  9. # Crank Component Authoring
  10. 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.
  11. ## JSX Template Tag (No Build Step)
  12. 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.
  13. ```html
  14. <!DOCTYPE html>
  15. <html lang="en-US">
  16. <head>
  17. <meta charset="utf-8" />
  18. <meta name="viewport" content="width=device-width" />
  19. <title>Crank App</title>
  20. </head>
  21. <body>
  22. <div id="app"></div>
  23. <script type="module">
  24. import {jsx, renderer} from "https://cdn.jsdelivr.net/npm/@b9g/crank/standalone.js";
  25. function *Counter() {
  26. let count = 0;
  27. const onclick = () => this.refresh(() => count++);
  28. for ({} of this) {
  29. yield jsx`
  30. <button onclick=${onclick}>Count: ${count}</button>
  31. `;
  32. }
  33. }
  34. renderer.render(jsx`<${Counter} />`, document.getElementById("app"));
  35. </script>
  36. </body>
  37. </html>
  38. ```
  39. 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).
  40. ## With a Build Step (JSX syntax)
  41. When using a bundler, you can use standard JSX syntax with the `@jsxImportSource` pragma:
  42. ```jsx
  43. /** @jsxImportSource @b9g/crank */
  44. import {renderer} from "@b9g/crank/dom";
  45. function *Timer({message}) {
  46. let seconds = 0;
  47. // Mount: start interval
  48. const interval = setInterval(() => this.refresh(() => seconds++), 1000);
  49. // Update: loop receives fresh props on each re-render
  50. for ({message} of this) {
  51. yield (
  52. <div>
  53. <p>{message}: {seconds}s</p>
  54. <button onclick={() => this.refresh(() => seconds = 0)}>Reset</button>
  55. </div>
  56. );
  57. }
  58. // Cleanup: runs on unmount
  59. clearInterval(interval);
  60. }
  61. renderer.render(<Timer message="Elapsed" />, document.getElementById("app"));
  62. ```
  63. ## Not React — Quick Reference
  64. | React | Crank | Why |
  65. |---|---|---|
  66. | `onClick` | `onclick` | Lowercase DOM event names |
  67. | `onChange` | `onchange` | Lowercase DOM event names |
  68. | `className` | `class` | Standard HTML attributes |
  69. | `htmlFor` | `for` | Standard HTML attributes |
  70. | `dangerouslySetInnerHTML` | `innerHTML` | Direct DOM property |
  71. | `useState(init)` | `let x = init` | Variable in generator scope |
  72. | `setState(val)` | `this.refresh(() => x = val)` | Explicit refresh |
  73. | `useEffect(fn, [])` | Code before first `yield` | Generator mount phase |
  74. | `useEffect(() => cleanup)` | Code after `for` loop / `this.cleanup(fn)` | Generator cleanup |
  75. | `useRef(null)` | `let el = null` + `ref={n => el = n}` | Variable + ref prop |
  76. | `useContext(ctx)` | `this.consume(key)` | No Provider components |
  77. | `<Ctx.Provider value={v}>` | `this.provide(key, v)` | Called in generator body |
  78. ## API Surface
  79. These are the complete public exports.
  80. ```js
  81. // Core — components, elements, and rendering infrastructure
  82. import {
  83. createElement, // Create an element (called automatically by JSX)
  84. Fragment, // Group children without a wrapper node ("")
  85. Portal, // Render children into a different root node
  86. Copy, // Reuse the previously rendered child tree
  87. Text, // Render a text node with explicit text prop
  88. Raw, // Insert raw HTML/markup via value prop
  89. Element, // Element class (for type checking)
  90. isElement, // Test if a value is a Crank element
  91. cloneElement, // Clone an element with merged props
  92. Context, // Component context class
  93. Renderer, // Base renderer class (for custom renderers)
  94. } from "@b9g/crank";
  95. // DOM renderer
  96. import {renderer, DOMRenderer} from "@b9g/crank/dom";
  97. // HTML string renderer (SSR)
  98. import {renderer as htmlRenderer, HTMLRenderer} from "@b9g/crank/html";
  99. // JSX template tag (no build step)
  100. import {jsx, html} from "@b9g/crank/jsx-tag";
  101. // Standalone — re-exports everything above in one import
  102. import {jsx, html, Fragment, renderer, domRenderer, htmlRenderer, DOMRenderer, HTMLRenderer} from "@b9g/crank/standalone";
  103. ```
  104. ### Context methods (`this` inside generator components)
  105. ```js
  106. this.refresh(callback?) // Mutate state and re-render
  107. this.schedule(callback?) // Run when this render's nodes exist, pre-DOM (once)
  108. this.after(callback?) // Run after this render is in the DOM (once)
  109. this.cleanup(callback?) // Run on unmount
  110. this.consume(key) // Read a provided value from an ancestor
  111. this.provide(key, value) // Provide a value to descendants
  112. this.addEventListener(type, listener) // Listen for DOM or custom events
  113. this.removeEventListener(type, listener) // Remove an event listener
  114. this.dispatchEvent(event) // Dispatch an event up the tree
  115. ```
  116. ## Philosophy
  117. Crank components are plain JavaScript functions and generators. State is variables. Props are values. Updates are explicit.
  118. - The framework preserves generator scope across yields — local variables are your state.
  119. - `this.refresh(() => { ... })` atomically mutates state and triggers a re-render.
  120. - Props are plain values — destructure and transform them freely.
  121. - Shared logic is plain classes, functions, and modules.
  122. - Elements are immutable descriptions of what to render — never mutate an element or its props after creating it; build a new one instead.
  123. ## JSX Template Tag — Quick Reference
  124. ```js
  125. jsx`
  126. <!-- host element -->
  127. <div />
  128. <!-- component element with shorthand close -->
  129. <${Component}>children<//>
  130. <!-- comment-style close -->
  131. <${Component}>children<//Component>
  132. <!-- fragment shorthand -->
  133. <>
  134. <p>first</p>
  135. <p>second</p>
  136. </>
  137. <!-- keyed fragment -->
  138. <${Fragment} key=${id}>
  139. <dt>${term}</dt>
  140. <dd>${definition}</dd>
  141. <//>
  142. <!-- boolean, string, interpolated string, expression, and spread props -->
  143. <input disabled type="text" class="a ${b} c" value=${val} ...${props} />
  144. <!-- namespaced props and tags -->
  145. <svg:circle attr:foo="bar" prop:value=${val} xlink:href="#icon" />
  146. <!-- conditional child -->
  147. ${show && jsx`<${Alert} message=${msg} />`}
  148. <!-- mapped children with keys -->
  149. ${items.map((d) => jsx`<li key=${d.id}>${d.name}</li>`)}
  150. <!-- commenting out a tree: expressions inside comments are discarded -->
  151. <!--
  152. <${Component} onclick=${handler}>
  153. <p>${text}</p>
  154. <//>
  155. -->
  156. `
  157. ```
  158. Multiple root elements are supported — the template tag automatically wraps them in a fragment.
  159. ## References
  160. Read these two files for complete API coverage and idiomatic patterns:
  161. 1. [Component Specification](docs/spec.bs) — complete API reference: all component types, lifecycle, context methods, reconciliation, async behavior, special props, JSX modes
  162. 2. [Style Guide](docs/guides/12-crank-style-guide.md) — do/don’t patterns: component structure, state updates, props, cleanup, refs, error handling
  163. ## Examples (consult as needed for the relevant task)
  164. - [Greeting](examples/greeting.js) — Hello world: functional components, props, composition
  165. - [TodoMVC](examples/todomvc.js) — Full CRUD app: custom events, list management, filtering, localStorage
  166. - [Hacker News](examples/hackernews.js) — Data dashboard: async fetching, hash routing, recursive tree rendering
  167. - [Password Strength](examples/password-strength.js) — Interactive form widget: real-time validation, derived state, visual feedback
  168. - [Wizard](examples/wizard.js) — Multi-step form: stateful navigation, FormData collection, generator lifecycle
  169. - [Animated Letters](examples/animated-letters.js) — Animation: CSS transitions, exit animations, requestAnimationFrame
  170. ## Additional Guides (for deeper reading on specific topics)
  171. - [Getting Started](docs/guides/01-getting-started.md)
  172. - [Elements](docs/guides/02-elements.md)
  173. - [Components](docs/guides/03-components.md)
  174. - [Handling Events](docs/guides/04-handling-events.md)
  175. - [Async Components](docs/guides/05-async-components.md)
  176. - [Special Props and Components](docs/guides/06-special-props-and-components.md)
  177. - [Lifecycles](docs/guides/07-lifecycles.md)
  178. - [Hydration](docs/guides/08-hydration.md)
  179. - [Reusable Logic](docs/guides/09-reusable-logic.md)
  180. - [Working with TypeScript](docs/guides/10-working-with-typescript.md)
  181. - [JSX Template Tag](docs/guides/11-jsx-template-tag.md)
  182. - [Reference for React Developers](docs/guides/13-reference-for-react-developers.md)
  183. - [Custom Renderers](docs/guides/14-custom-renderers.md)
  184. ## Blog Posts
  185. - [Introducing Crank](docs/blog/2020-04-15-introducing-crank.md)
  186. - [Why Be Reactive?](docs/blog/2025-08-20-why-be-reactive.md)
  187. ## Other
  188. - [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)

  1. <div align="center">
  2. <img src="logo.svg" alt="Crank.js Logo" width="200" height="200" />
  3. # Crank.js
  4. The Just JavaScript UI Framework
  5. </div>
  6. ## Get Started
  7. Scaffold a new project:
  8. ```shell
  9. npm create crank
  10. ```
  11. Or try it instantly in the [online playground](https://crank.js.org/playground).
  12. Other links:
  13. - [crank.js.org](https://crank.js.org)
  14. - [NPM](https://www.npmjs.com/package/@b9g/crank)
  15. - [Introducing Crank.js](https://crank.js.org/blog/introducing-crank/)
  16. - [Examples](https://github.com/bikeshaving/crank/tree/main/examples)
  17. - [Crank for Python](https://github.com/bikeshaving/crankpy)
  18. - [Deep Wiki](https://deepwiki.com/bikeshaving/crank)
  19. ## Motivation
  20. **A framework that feels like JavaScript.**
  21. ```javascript
  22. // State is defined with generator components
  23. function* Timer() {
  24. // setup goes here
  25. let seconds = 0;
  26. const interval = setInterval(() => this.refresh(() => seconds++), 1000);
  27. for ({} of this) {
  28. yield <div>Seconds: {seconds}</div>;
  29. }
  30. clearInterval(interval); // Cleanup just works
  31. }
  32. renderer.render(<Timer />, document.body);
  33. // Async components just work on client and server
  34. async function UserProfile({userId}) {
  35. const user = await fetchUser(userId);
  36. return <div>Hello, {user.name}!</div>;
  37. }
  38. await renderer.render(<UserProfile />, document.body);
  39. ```
  40. ### Why Crank?
  41. Crank leans on the language instead of reinventing it. State is a local
  42. variable, held in a generator’s scope. Updates are re-execution: calling
  43. `refresh()` runs the loop again. A loading state is an `async` function,
  44. awaited. Setup is the code before the loop; cleanup is the code after it.
  45. There are no hooks, no dependency arrays, no compiler, and no rules about
  46. what you can call where — control flow is the lifecycle.
  47. Because components are plain functions and generators, everything you already
  48. know about JavaScript applies. Closures hold state, modules share logic, and
  49. `try`/`finally` handles teardown. If you can read JavaScript, you can read a
  50. Crank component.
  51. ## Installation
  52. The Crank package is available on [NPM](https://npmjs.org/@b9g/crank) through
  53. the [@b9g organization](https://www.npmjs.com/org/b9g) (short for
  54. b*ikeshavin*g).
  55. ```shell
  56. npm i @b9g/crank
  57. ```
  58. ### Importing Crank with the **automatic** JSX transform.
  59. ```jsx live
  60. /** @jsxImportSource @b9g/crank */
  61. import {renderer} from "@b9g/crank/dom";
  62. renderer.render(
  63. <p>This paragraph element is transpiled with the automatic transform.</p>,
  64. document.body,
  65. );
  66. ```
  67. ### Importing the JSX template tag.
  68. Starting in version `0.5`, the Crank package ships a [tagged template
  69. function](/guides/jsx-template-tag) which provides similar syntax and semantics
  70. as the JSX transform. This allows you to write Crank components in vanilla
  71. JavaScript.
  72. ```js live
  73. import {jsx} from "@b9g/crank/standalone";
  74. import {renderer} from "@b9g/crank/dom";
  75. renderer.render(jsx`
  76. <p>No transpilation is necessary with the JSX template tag.</p>
  77. `, document.body);
  78. ```
  79. ### ECMAScript Module CDNs
  80. Crank is also available on CDNs like [jsDelivr](https://www.jsdelivr.com)
  81. (https://cdn.jsdelivr.net/npm/@b9g/crank/) and [esm.sh](https://esm.sh)
  82. (https://esm.sh/@b9g/crank) for usage in ESM-ready environments.
  83. ```jsx live
  84. /** @jsx createElement */
  85. import {createElement} from "https://cdn.jsdelivr.net/npm/@b9g/crank/crank.js";
  86. import {renderer} from "https://cdn.jsdelivr.net/npm/@b9g/crank/dom.js";
  87. renderer.render(
  88. <div id="hello">
  89. Running on <a href="https://www.jsdelivr.com">jsDelivr</a>
  90. </div>,
  91. document.body,
  92. );
  93. ```
  94. ## Key Examples
  95. ### A Simple Component
  96. ```jsx live
  97. import {renderer} from "@b9g/crank/dom";
  98. function Greeting({name = "World"}) {
  99. return (
  100. <div>Hello {name}</div>
  101. );
  102. }
  103. renderer.render(<Greeting />, document.body);
  104. ```
  105. ### A Stateful Component
  106. ```jsx live
  107. function *Timer(this: Context) {
  108. let seconds = 0;
  109. const interval = setInterval(() => this.refresh(() => seconds++), 1000);
  110. for ({} of this) {
  111. yield <div>Seconds: {seconds}</div>;
  112. }
  113. clearInterval(interval);
  114. }
  115. ```
  116. ### An Async Component
  117. ```jsx live
  118. import {renderer} from "@b9g/crank/dom";
  119. async function Definition({word}) {
  120. // API courtesy https://dictionaryapi.dev
  121. const res = await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${word}`);
  122. const data = await res.json();
  123. if (!Array.isArray(data)) {
  124. return <p>No definition found for {word}</p>;
  125. }
  126. const {phonetic, meanings} = data[0];
  127. const {partOfSpeech, definitions} = meanings[0];
  128. const {definition} = definitions[0];
  129. return <>
  130. <p>{word} <code>{phonetic}</code></p>
  131. <p><b>{partOfSpeech}.</b>{" "}{definition}</p>
  132. </>;
  133. }
  134. await renderer.render(<Definition word="framework" />, document.body);
  135. ```
  136. ### A Loading Component
  137. ```jsx live
  138. import {Fragment} from "@b9g/crank";
  139. import {renderer} from "@b9g/crank/dom";
  140. async function LoadingIndicator() {
  141. await new Promise(resolve => setTimeout(resolve, 1000));
  142. return (
  143. <div>
  144. 🐕 Fetching a good boy...
  145. </div>
  146. );
  147. }
  148. async function RandomDog({throttle = false}) {
  149. const res = await fetch("https://dog.ceo/api/breeds/image/random");
  150. const data = await res.json();
  151. if (throttle) {
  152. await new Promise(resolve => setTimeout(resolve, 2000));
  153. }
  154. return (
  155. <div>
  156. <a href={data.message} target="_blank" style="text-decoration: none; color: inherit;">
  157. <img
  158. src={data.message}
  159. alt="A Random Dog"
  160. width="300"
  161. />
  162. <div>
  163. Click to view full size
  164. </div>
  165. </a>
  166. </div>
  167. );
  168. }
  169. async function *RandomDogLoader({throttle}) {
  170. // for await can be used to race component trees
  171. for await ({throttle} of this) {
  172. yield <LoadingIndicator />;
  173. yield <RandomDog throttle={throttle} />;
  174. }
  175. }
  176. function *RandomDogApp() {
  177. let throttle = false;
  178. this.addEventListener("click", (ev) => {
  179. if (ev.target.tagName === "BUTTON") {
  180. this.refresh(() => throttle = !throttle);
  181. }
  182. });
  183. for ({} of this) {
  184. yield (
  185. <div>
  186. <RandomDogLoader throttle={throttle} />
  187. <div>
  188. <button>
  189. Show me another dog!
  190. </button>
  191. <div>
  192. {throttle ? "Slow mode" : "Fast mode"}
  193. </div>
  194. </div>
  195. </div>
  196. );
  197. }
  198. }
  199. renderer.render(<RandomDogApp />, document.body);
  200. ```
  201. ## Common tool configurations
  202. The following is an incomplete list of configurations to get started with Crank.
  203. ### [TypeScript](https://www.typescriptlang.org)
  204. TypeScript is a typed superset of JavaScript.
  205. Here’s the configuration you will need to set up automatic JSX transpilation.
  206. ```tsconfig.json
  207. {
  208. "compilerOptions": {
  209. "jsx": "react-jsx",
  210. "jsxImportSource": "@b9g/crank"
  211. }
  212. }
  213. ```
  214. Crank is written in TypeScript and comes with types. Refer to [the guide on
  215. TypeScript](https://crank.js.org/guides/working-with-typescript) for more
  216. information about Crank types.
  217. ```tsx
  218. import type {Context} from "@b9g/crank";
  219. function *Timer(this: Context<typeof Timer>) {
  220. let seconds = 0;
  221. const interval = setInterval(() => this.refresh(() => seconds++), 1000);
  222. for ({} of this) {
  223. yield <div>Seconds: {seconds}</div>;
  224. }
  225. clearInterval(interval);
  226. }
  227. ```
  228. ### [Babel](https://babeljs.io)
  229. 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.
  230. Here is how to get Babel to transpile JSX for Crank.
  231. Automatic transform:
  232. ```.babelrc.json
  233. {
  234. "plugins": [
  235. "@babel/plugin-syntax-jsx",
  236. [
  237. "@babel/plugin-transform-react-jsx",
  238. {
  239. "runtime": "automatic",
  240. "importSource": "@b9g/crank",
  241. "throwIfNamespace": false,
  242. "useSpread": true
  243. }
  244. ]
  245. ]
  246. }
  247. ```
  248. ### [ESLint](https://eslint.org)
  249. ESLint is a popular open-source tool for analyzing and detecting problems in JavaScript code.
  250. Crank provides a configuration preset for working with ESLint under the package name `eslint-plugin-crank`.
  251. ```bash
  252. npm i eslint eslint-plugin-crank
  253. ```
  254. In your eslint configuration:
  255. ```.eslintrc.json
  256. {
  257. "extends": ["plugin:crank/recommended"]
  258. }
  259. ```
  260. ### [Astro](https://astro.build)
  261. Astro.js is a modern static site builder and framework.
  262. Crank provides an [Astro integration](https://docs.astro.build/en/guides/integrations-guide/) to enable server-side rendering and client-side hydration with Astro.
  263. ```bash
  264. npm i astro-crank
  265. ```
  266. In your `astro.config.mjs`.
  267. ```astro.config.mjs
  268. import {defineConfig} from "astro/config";
  269. import crank from "astro-crank";
  270. // https://astro.build/config
  271. export default defineConfig({
  272. integrations: [crank()],
  273. });
  274. ```
  275. ## API Reference
  276. ### Core Exports
  277. ```javascript
  278. import {
  279. createElement,
  280. Fragment,
  281. Copy,
  282. Portal,
  283. Raw,
  284. Text,
  285. Context
  286. } from "@b9g/crank";
  287. import {renderer} from "@b9g/crank/dom"; // Browser DOM
  288. import {renderer} from "@b9g/crank/html"; // Server-side HTML
  289. import {jsx, html} from "@b9g/crank/standalone"; // Template tag (no build)
  290. import {Suspense, SuspenseList, lazy} from "@b9g/crank/async";
  291. ```
  292. ---
  293. ### Component Types
  294. **Function Component** - Stateless
  295. ```javascript
  296. function Greeting({name = "World"}) {
  297. return <div>Hello {name}</div>;
  298. }
  299. ```
  300. **Generator Component** - Stateful with `function*`
  301. ```javascript
  302. function* Counter() {
  303. let count = 0;
  304. const onclick = () => this.refresh(() => count++);
  305. for ({} of this) {
  306. yield <button onclick={onclick}>Count: {count}</button>;
  307. }
  308. }
  309. ```
  310. **Async Component** - Uses `async` for promises
  311. ```javascript
  312. async function UserProfile({userId}) {
  313. const user = await fetch(`/api/users/${userId}`).then(r => r.json());
  314. return <div>Hello, {user.name}!</div>;
  315. }
  316. ```
  317. **Async Generator Component** - Stateful + async
  318. ```javascript
  319. async function* DataLoader({url}) {
  320. for ({url} of this) {
  321. const data = await fetch(url).then(r => r.json());
  322. yield <div>{data.message}</div>;
  323. }
  324. }
  325. ```
  326. ---
  327. ### Context API
  328. The context is available as `this` in components (or as 2nd parameter).
  329. ```javascript
  330. function Component(props, ctx) {
  331. console.log(this === ctx); // true
  332. return props.children;
  333. }
  334. ```
  335. #### Properties
  336. **`this.props`** - Current props (readonly)
  337. **`this.isExecuting`** - Whether the component is currently executing
  338. **`this.isUnmounted`** - Whether the component is unmounted
  339. #### Methods
  340. **`this.refresh(callback?)`** - Trigger re-execution
  341. ```javascript
  342. this.refresh(); // Simple refresh
  343. this.refresh(() => count++); // With state update (v0.7+)
  344. ```
  345. **`this.schedule(callback?)`** - Execute after DOM is rendered
  346. ```javascript
  347. // el is whatever the component returns Node/Text/HTMLElement/null, an array of dom nodes, etc
  348. this.schedule((el) => {
  349. console.log("Component rendered", el.innerHTML);
  350. });
  351. ```
  352. **`this.after(callback?)`** - Execute after DOM is live
  353. ```javascript
  354. // this runs after the DOM nodes have finally entered the DOM
  355. // this is where you put things like autofocus
  356. this.after((el) => {
  357. console.log(el.isConnected); // true
  358. });
  359. ```
  360. **`this.cleanup(callback?)`** - Execute on unmount
  361. ```javascript
  362. function* Component() {
  363. const interval = setInterval(() => this.refresh(), 1000);
  364. this.cleanup(() => clearInterval(interval));
  365. for ({} of this) {
  366. yield <div>Tick</div>;
  367. }
  368. }
  369. ```
  370. **`this.addEventListener(type, listener, options?)`** - Listen to events
  371. ```javascript
  372. this.addEventListener("click", (e) => console.log("Clicked!"));
  373. ```
  374. **`this.dispatchEvent(event)`** - Dispatch events
  375. ```javascript
  376. this.dispatchEvent(new CustomEvent("mybuttonclick", {
  377. bubbles: true,
  378. detail: {id: props.id}
  379. }));
  380. ```
  381. **`this.provide(key, value)`** / **`this.consume(key)`** - Context API
  382. ```javascript
  383. // Provider
  384. function* ThemeProvider() {
  385. this.provide("theme", "dark");
  386. for ({} of this) {
  387. yield this.props.children;
  388. }
  389. }
  390. // Consumer
  391. function ThemedButton() {
  392. const theme = this.consume("theme");
  393. return <button class={theme}>Click me</button>;
  394. }
  395. ```
  396. #### Iteration
  397. **`for ({} of this)`** - Render loop (sync)
  398. ```javascript
  399. function* Component() {
  400. for ({} of this) {
  401. yield <div>{this.props.message}</div>;
  402. }
  403. }
  404. ```
  405. **`for await ({} of this)`** - Async render loop for racing trees
  406. ```javascript
  407. async function* AsyncComponent() {
  408. for await ({} of this) {
  409. // Multiple yields race - whichever completes first shows
  410. yield <Loading />;
  411. yield <Content />;
  412. }
  413. }
  414. ```
  415. ---
  416. ### Special Props
  417. **`key`** - Unique identifier for reconciliation
  418. ```javascript
  419. <ul>{items.map(item => <li key={item.id}>{item.name}</li>)}</ul>
  420. ```
  421. **`ref`** - Access rendered DOM element
  422. ```javascript
  423. <audio ref={(el) => (audio = el)} />
  424. // Forward refs through components
  425. function MyInput({ref, ...props}) {
  426. return <input ref={ref} {...props} />;
  427. }
  428. ```
  429. **`copy`** - Prevent/control re-rendering
  430. ```javascript
  431. // Boolean: prevent rendering when truthy
  432. <li copy={!el.hasChanged}>{el.value}</li>
  433. // string: copy specific props
  434. <input copy="!value" type="text" /> // Copy all except value
  435. <div copy="class id" /> // Copy only class and id
  436. <div copy="children" /> // Copy children
  437. ```
  438. **`hydrate`** - Control SSR hydration
  439. ```javascript
  440. <div hydrate={false}> // Skip hydration
  441. <Portal hydrate={true}> // Force hydration
  442. <input hydrate="!value" /> // Hydrate all except value
  443. ```
  444. **`class`** - String or object (v0.7+)
  445. ```javascript
  446. <button class="btn active" />
  447. <button class={{
  448. btn: true,
  449. 'btn-active': isActive,
  450. 'btn-disabled': isDisabled
  451. }} />
  452. ```
  453. **`style`** - CSS string or object
  454. ```javascript
  455. <div style="color: red; font-size: 16px" />
  456. <div style={{"font-size": "16px", color: "blue"}} />
  457. ```
  458. **`innerHTML`** - Raw HTML string (⚠️ XSS risk)
  459. ```javascript
  460. <div innerHTML="<strong>Bold</strong>" />
  461. ```
  462. **Event Props** - Lowercase event handlers
  463. ```javascript
  464. <button onclick={handler} />
  465. <input onchange={handler} oninput={handler} />
  466. <form onsubmit={handler} />
  467. ```
  468. **Prop Naming** - HTML-friendly names supported
  469. ```javascript
  470. <label class="my-label" for="my-id">Label</label>
  471. // Instead of className and htmlFor
  472. ```
  473. ---
  474. ### Special Element Tags
  475. **`<Fragment>`** - Render children without wrapper
  476. ```javascript
  477. import {Fragment} from "@b9g/crank";
  478. <Fragment>
  479. <div>Child 1</div>
  480. <div>Child 2</div>
  481. </Fragment>
  482. // Or use: <>...</>
  483. // The Fragment tag is the empty string
  484. ```
  485. **`<Copy />`** - Prevent element re-rendering
  486. ```javascript
  487. import {Copy} from "@b9g/crank";
  488. function memo(Component) {
  489. return function* Wrapped(props) {
  490. yield <Component {...props} />;
  491. for (const newProps of this) {
  492. if (equals(props, newProps)) {
  493. yield <Copy />; // Reuse previous render
  494. } else {
  495. yield <Component {...newProps} />;
  496. }
  497. props = newProps;
  498. }
  499. };
  500. }
  501. ```
  502. **`<Portal>`** - Render into different DOM node
  503. ```javascript
  504. import {Portal} from "@b9g/crank";
  505. const modalRoot = document.getElementById("modal-root");
  506. function Modal({children}) {
  507. return (
  508. <Portal root={modalRoot}>
  509. <div class="modal">
  510. {children}
  511. </div>
  512. </Portal>
  513. );
  514. }
  515. ```
  516. **`<Raw>`** - Insert raw HTML or DOM nodes
  517. ```javascript
  518. import {Raw} from "@b9g/crank";
  519. function MarkdownViewer({markdown}) {
  520. const html = marked(markdown);
  521. return <div><Raw value={html} /></div>;
  522. }
  523. // Or insert DOM node
  524. <Raw value={domNode} />
  525. ```
  526. **`<Text>`** - Explicit text node creation (v0.7+)
  527. ```javascript
  528. import {Text} from "@b9g/crank";
  529. <Text value="Hello world" />
  530. // Access Text nodes in lifecycle
  531. function* Component() {
  532. this.schedule((node) => {
  533. if (node instanceof Text) {
  534. console.log("Text node:", node);
  535. }
  536. });
  537. for ({} of this) {
  538. yield "Text content"; // Becomes a Text node
  539. }
  540. }
  541. ```
  542. ---
  543. ### Async Utilities (v0.7+)
  544. **`lazy(loader)`** - Lazy-load components
  545. ```javascript
  546. import {lazy} from "@b9g/crank/async";
  547. const LazyComponent = lazy(() => import("./MyComponent.js"));
  548. <Suspense fallback={<div>Loading...</div>}>
  549. <LazyComponent />
  550. </Suspense>
  551. ```
  552. **`Suspense`** - Declarative loading states
  553. ```javascript
  554. import {Suspense} from "@b9g/crank/async";
  555. <Suspense fallback={<div>Loading...</div>}>
  556. <AsyncComponent />
  557. </Suspense>
  558. ```
  559. **`SuspenseList`** - Coordinate multiple async components
  560. ```javascript
  561. import {SuspenseList} from "@b9g/crank/async";
  562. <SuspenseList>
  563. <Suspense fallback={<div>Loading 1...</div>}>
  564. <Item1 />
  565. </Suspense>
  566. <Suspense fallback={<div>Loading 2...</div>}>
  567. <Item2 />
  568. </Suspense>
  569. </SuspenseList>
  570. ```
  571. ---
  572. ### Lifecycle Patterns
  573. **Mount** - Code before first `yield`
  574. ```javascript
  575. function* Component() {
  576. console.log("Mounting...");
  577. const interval = setInterval(() => this.refresh(), 1000);
  578. for ({} of this) {
  579. yield <div>Tick</div>;
  580. }
  581. clearInterval(interval); // Cleanup
  582. }
  583. ```
  584. **Update** - Code inside render loop
  585. ```javascript
  586. function* Component() {
  587. for ({} of this) {
  588. console.log("Updated with:", this.props);
  589. yield <div>{this.props.message}</div>;
  590. }
  591. }
  592. ```
  593. **Cleanup** - Code after loop or via `this.cleanup()`
  594. ```javascript
  595. function* Component() {
  596. const interval = setInterval(() => this.refresh(), 1000);
  597. this.cleanup(() => clearInterval(interval));
  598. for ({} of this) {
  599. yield <div>Tick</div>;
  600. }
  601. }
  602. ```
  603. ---
  604. ### Advanced Patterns
  605. **Higher-Order Components**
  606. ```javascript
  607. function withLogger(Component) {
  608. return function* WrappedComponent(props) {
  609. console.log("Rendering with:", props);
  610. for ({} of this) {
  611. yield <Component {...props} />;
  612. }
  613. };
  614. }
  615. ```
  616. **Hooks**
  617. ```javascript
  618. function useInterval(ctx, callback, delay) {
  619. let interval = setInterval(callback, delay);
  620. ctx.cleanup(() => clearInterval(interval));
  621. return (newDelay) => {
  622. delay = newDelay;
  623. clearInterval(interval);
  624. interval = setInterval(callback, delay);
  625. };
  626. }
  627. ```
  628. **Context Extensions** (⚠️ Prefer hooks over global extensions)
  629. ```javascript
  630. import {Context} from "@b9g/crank";
  631. Context.prototype.setInterval = function(callback, delay) {
  632. const interval = setInterval(callback, delay);
  633. this.cleanup(() => clearInterval(interval));
  634. };
  635. // Use in components
  636. function* Timer() {
  637. let seconds = 0;
  638. this.setInterval(() => this.refresh(() => seconds++), 1000);
  639. for ({} of this) {
  640. yield <div>Seconds: {seconds}</div>;
  641. }
  642. }
  643. ```
  644. **Racing Components**
  645. ```javascript
  646. async function* DataComponent({url}) {
  647. for await ({url} of this) {
  648. // This is the equivalent of calling
  649. // renderer.render(<Spinner />, document.body);
  650. // renderer.render(<Data />, document.body);
  651. // but in a component.
  652. yield <Spinner />;
  653. yield <Data />;
  654. }
  655. }
  656. ```
  657. Components race to render. Useful for fallback states.
  658. ---
  659. ### TypeScript Support
  660. ```typescript
  661. import type {Context} from "@b9g/crank";
  662. import {ComponentProps} from "@b9g/crank"; // v0.7+
  663. // Component with typed props
  664. interface Props {
  665. name: string;
  666. age?: number;
  667. }
  668. function Greeting({name, age}: Props) {
  669. return <div>Hello {name}, age {age}</div>;
  670. }
  671. // Generator with typed context
  672. function* Greeting(this: Context<typeof Greeting>, {name}: {name: string}) {
  673. for ({name} of this) {
  674. yield <div>Hello {name}</div>;
  675. }
  676. }
  677. // Extract component props type
  678. function Button({variant}: {variant: "primary" | "secondary"}) {
  679. return <button class={`btn-${variant}`}>Click</button>;
  680. }
  681. type ButtonProps = ComponentProps<typeof Button>;
  682. ```
  683. For comprehensive guides and documentation, visit [crank.js.org](https://crank.js.org)

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.