Modules
import { readFileSync, writeFileSync as write } from "node:fs"
import * as path from "node:path"
import express from "express"
import "./setup.rk"
export func greet(name string) string {
return `Hello, ${name}`
}
export const VERSION = "0.1.0"
export class User { ... }
export interface Point {
x, y number
}
Imports and exports become ES modules one to one; export interface and export type disappear at
compile time.
- A name used only as a type (an imported interface, for example) is removed from the
import: there is no such value at runtime. rook build main.rkwritesmain.js(andmain.d.ts, see below) next to the source and compiles every.rkfile it imports the same way. In imports,.rkis replaced with.js:"./geom.rk"→"./geom.js".rook build src/builds every.rkfile of a folder, and--out-dir build/puts the.jsfiles into a separate folder with the same structure. If any file has errors, no file is written.rook runcompiles the imported.rkfiles on the fly.export { Row, Rows } from "./rows.rk"andexport * from "./rows.rk"pass on names of another module, as in JS, for a module that gathers the public API of a folder (index.rk). The names are not declared in the module itself. Types, components, decorators and state go with what they need; a component or a decorator keeps its name. A component is exported by its name, soexport const Rows = Innerof a component without a type is an error that shows this form.- Besides relative paths,
.rkmodules are found by the aliases that Vite and TypeScript know: subpath imports ofpackage.json,"imports": { "#ui/*": "./src/ui/*" }, and thepathsoftsconfig.json,"@/*": ["./src/*"]. Their imports are typed, androok buildwrites them with.js:"#ui/button.rk"→"#ui/button.js".
The runtime
const jobs = chan<number>(10)
jobs <- 1
import { $$channels } from 'rooklang/runtime'
const jobs = $$channels.make(10, 0)
await $$channels.send(jobs, 1)
What the code cannot do with JS alone, such as channels, goroutines, queues, defer inside a loop
and the blocks of markup, is done by functions of a small library, the runtime: rooklang/runtime
in the package. A module imports the ones its code uses, by their names, which start with $$
like all names of generated code; a module that needs none imports nothing. After $$ they start
with a small letter ($$channels, $$deque), and the functions of components with a capital one
($$Card), so a component may have any name.
- One runtime for all modules: a channel or a queue that one module makes works the same in another, which imports the same runtime. Each thread has its own copy; what threads share goes through messages (see "Goroutines").
rooklangis a dependency of the project: the code thatrook buildwrites imports the runtime when it runs, sonpm install rooklanginstalls it as a dependency, not only for the build. Vite puts the runtime into the bundle, androok runtakes the runtime of the compiler, wherever the program is.- What is the module's own stays in it: the start of its workers, whose URL a bundler needs to
see there (
$$startWorker), the$$gothat passes it to the runtime, and the CSS of its components ($$styles). - Inline:
compile(source, { runtime: "inline" })puts the parts of the runtime that the code uses into the module, for code that runs without imports; the playground of the site runs its programs so, while its JavaScript tab shows the code with the import.
Types from TypeScript
The types of imports that are not .rk modules come from TypeScript declarations: packages with
types in package.json or with @types/*, .ts files and Node modules (node:fs, node:http
from @types/node). The typescript package reads them during type checking, along with the
standard library. A module without declarations, such as a JS file without a .d.ts, stays any.
import { readFileSync } from "node:fs"
import { createServer, IncomingMessage, ServerResponse } from "node:http"
const text = readFileSync("a.txt", "utf8") // string
const bytes = readFileSync("a.txt") // Buffer
func handle(request IncomingMessage, response ServerResponse) {
const url string = request.url // error: url may be null (?string)
}
How TypeScript types become Rook types:
| TypeScript | Rook |
|---|---|
boolean, string, number, literals, unions |
bool, string, number, literals, unions |
T | undefined, T | null, x?: T |
?T |
T[], Array<T>; a tuple [A, B] |
T[]; (A | B)[] |
void as a result |
a function without a result |
| an interface, an object type, an intersection | an interface |
| a class | a class: new, extends, instanceof |
Box<T>, function first<T>(...) |
generics: Box<T>, inferred type arguments |
| overloads | a call picks the first signature that fits |
enum |
a union of literals |
[key: string]: T |
unknown members have the type T |
bigint; Uint8Array, Float64Array, ... |
bigint; byte[], float64[], the same types |
unknown |
unknown |
object, symbol |
any |
| conditional and mapped types TS did not reduce | any |
import x from "pkg"is the default export; for modules withexport =it is the value itself, and named imports are its properties:import { join } from "node:path".- A type parameter with a default may be left out:
BufferisBuffer<ArrayBufferLike>. Such a class can be extended:class Bus extends EventEmitter. - Constraints of type parameters from a
.d.tsare not checked. Iterable<T>takes whatforgoes over at once, with values ofT: an array, a string, aSet, a typed array;Array.from(new Set([1]))is anumber[]. An array is not anIterableIteratoror anAsyncIterable, as in TypeScript.- A tuple
[K, V]is a(K | V)[], but a call infersKandVby position, from an array literal or another tuple:new Map([["a", 1]])is aMap<string, number>, andnew Map(Object.entries(prices))aMap<string, number>too. - Types cannot reach a type inside a namespace (
http.Server): it is imported by name. - The playground on the site works in the browser without the
typescriptpackage, so such imports areanythere.
Declarations for TypeScript
rook build with type checking writes a .d.ts next to each .js, so TypeScript code imports a
Rook module with types. With --no-check there are no declarations: without checking, the
types are unknown.
The Vite plugin writes app.d.rk.ts next to app.rk for TypeScript imports.
TypeScript uses allowArbitraryExtensions to resolve those imports.
export type Filter "all" | "active" | "done"
export func divide(a, b number) (number, error) { ... }
export class Stack<T> {
private items T[]
push(item T) { ... }
pop() ?T { ... }
}
export type Filter = 'all' | 'active' | 'done'
export declare function divide(a: number, b: number): [number, Error | null]
export declare class Stack<T> {
private items
push(item: T): void
pop(): T | null
}
bool→boolean,?T→T | null,error→Error | null,T[]→T[]; a field of type?Tmay be left out:note?: string | null.- Several results → a tuple
[A, B]: in JS, too, the function returns an array. - Parameter names come from the code and types from the checking, so inferred types
(
const n = 1) get into the declarations too. - Interfaces,
types and classes are declared even when not exported: exported functions may use them. Components do not exist in JS, nor in the declarations; a value of typecomp(title string)is the function of a component,(title: string) => [Node, ...unknown[]]. - Imports are repeated with
.jsinstead of.rk, so that the imported names can be used in types.
Source maps
rook build writes a source map next to each .js, app.js.map (and app.worker.js.map for the
worker module), and the .js ends with //# sourceMappingURL=app.js.map: stack traces in Node
(node --enable-source-maps) and in browsers, and debuggers, show the lines of app.rk.
--no-source-map writes none. rook run puts the map into the code it runs and runs it with
--enable-source-maps, so the stack trace of an exception, in a goroutine too, points to the .rk
file. The Vite plugin gives Vite the map of each module.
- Each statement maps to where it starts in the source; a line of the JS without a statement of its
own, as the
}of a block, goes with the statement before it. The map has the source in it (sourcesContent). - Imports are not mapped, nor the code of components inlined from other modules: its places are in their files.
Debugging goroutines
On Node, rook run tracks pending channel operations. If the program is waiting on channels
and its event loops are idle, it exits with status 1 and reports the wait sites in the .rk
sources. Timers and I/O can still make progress while the check waits. With --trace an exit
also prints the goroutines that remain live. Worker names come from the functions of go.
Markup
Markup and components are off by default, so that Rook can be the language of the logic
of an app whose views are in React, Svelte or Vue. A package turns them on in its package.json:
{ "rook": { "markup": true } }
"markup": "html" makes markup strings of HTML and components those of a server, which return
any value: see server.md.
A file takes the setting of the nearest package.json above it, and so do the language server of
VS Code and the Vite plugin. rook build --markup and --no-markup set it for all files, and so
does rook({ markup: true }) in Vite. Where it is off, markup, comp, dec and decorators are
errors that say how to turn them on; state, ref and the like are keywords only inside a
component anyway. The browser compiler takes it as an option, compile(source, null, { markup: true }).
Markup in code creates real DOM elements, with no virtual DOM:
const name = "to the home page"
const link = <a href="/" class="nav">Link {name}</a> // HTMLAnchorElement
const link = document.createElement('a')
link.href = '/'
link.className = 'nav'
link.append('Link ', name)
Syntax as in JSX: attributes
href="/",href={url},disabled,{...attrs}; children are text,{expression}and elements; a fragment is<>...</>. Attribute names are the HTML ones:class,for.Types:
<input>is anHTMLInputElement,<a>anHTMLAnchorElementand so on. Attributes that match DOM properties are checked against the property's type. Children are strings, numbers, nodes, arrays of them or?T;nullshows nothing.Classes and ARIA:
classalso takes a list, whosenulls and empty strings are left out:class={[styles.tab, active ? styles.active : null]}. Aboolin an attribute without a property, such asaria-pressed={on}, is written as"true"or"false".SVG:
<svg>, the elements inside it and the tags that only SVG has (<path>,<circle>,<g>...) are created in the SVG namespace, withcreateElementNS, and their attributes are set withsetAttribute.<a>,<title>and the other tags HTML has too are SVG only inside<svg>; the children of<foreignObject>are HTML.Creating elements: an HTML node is created with
document.createElement. The generated code uses assignments for DOM properties andsetAttributefor other attributes. Initial values are evaluated before the node is created.Events: a function name,
obj.methodor a function literal is the handler. Anything else is code that runs on the event, with the variableevent:onClick={count++},onSubmit={event.preventDefault(); send()}. SoonClick={save()}callssaveon a click.Where markup can start.
<at the start of an expression starts markup; after a value it is a comparison. The opening tag goes on the same line asreturn.Conditions and loops are written inside
{...}as ordinaryif,forandswitch. The elements in their blocks become the content; besides elements, the blocks can hold only nestedif/for/switchandconst:<ul>{for i, product in products { if product != null { <Product {...product} /> } }}</ul>with key product.idafter the items finds the blocks of a list again by the key, so a list loaded again keeps its blocks (components.md).
Components
A component exists only at compile time: every use of it is replaced by its code.
comp Card(title string, kind string = "info", children Content) {
return <section class={kind}>
<h2>{title}</h2>
{children}
</section>
}
document.body.append(<Card title="Profile"><p>Text</p></Card>)
Declaration.
comp Name(properties) { ...; return <markup> }, only at the top level of a module. The name starts with a capital letter. The body ends with areturnof markup.An early
returnreturns markup too:if index > 2 { return <div>end</div> }. The body runs once, when the component is created, so the choice between thereturns is made once: if what the condition reads changes later, the component stays the same. For markup that changes with state, use{if ...}in the markup.Properties. These are parameters in Go syntax, with default values at the end. A property of type
?Tor with a default value may be left out. Attributes are checked like the arguments of a call: an extra attribute or a missing required property is an error.children Contentgets the markup between the tags.Spread
<Product {...product} />passes the object's fields named like the properties; other fields are ignored, and attributes after the spread override it.Function properties (
onPress func()) take code by the same rule ason*of elements.Properties are read-only, except bound ones. To change the parent's state, pass a function property, or declare the property with
bind,comp Drawer(bind open bool): the component changes it as its state, and<Drawer bind:open={menu} />writes the changes into the parent'smenu. Withoutbind:a bound property is the component's own state, starting from the value given (components.md)....attrs, the last property, takes the attributes of a use that are not properties;{...attrs}puts them on one element of the component's markup, created once, and the use is checked as if they were written on that element. A class or a style is added to the element's.There is no component in JS: its code is inlined as a block where it is used, and the values of the attributes are computed before that block. The exceptions are recursive and exported components and components used as values, see below, and large ones: a component whose copies would add more than 100 lines compared to a function and its calls is compiled to a function.
Recursive components (a tree, nested comments) are not inlined but compiled to a function. Some use on the cycle must be under a condition (
if,for, a branch of?:), or the recursion never ends: that is a compile error.Exported components (
export comp Card) are imported by name,import { Card } from "./card.rk", and used as tags. Their module compiles them to functions,export function $$Card(...). The module that uses one calls it, or inlines it by the same 100-line threshold, with the components of its module that it uses; the names of that module come through hidden exports,export { PREFIX as $$Card$PREFIX }. A component that assigns a variable of its module is always called, since another module can only read it.Components as values.
content: Introis a value of typecomp(), andcomp(title string, kind ?Kind)lists the properties with their names. A tag takes the component from a value:<section.content />, or<Page />with a variablePage. It passes the properties in the order of the type, so a component fits a type with the same names in the same order; it may have more at the end if they may be left out, and a property with a default value fits?T. Such a component is a function,$$Intro, and the tag calls it. When the value depends on state and changes, the component is created again;refand spread are not possible on such a tag.interface Section { title string content comp() } const SECTIONS Section[] = [{ title: "Introduction", content: Intro }] comp Guide() { return <main>{for section in SECTIONS { <section.content /> }}</main> }
State. state declares a variable that the markup depends on. It is declared like let, but
only at the top level of a component's body:
comp Counter(initialValue number) {
state count = initialValue
return <button onClick={count++}>Clicked {count} times</button>
}
let count = initialValue
const $$button3 = document.createElement('button')
$$button3.addEventListener('click', () => {
count++
$$text4.data = count
})
const $$text4 = document.createTextNode(count)
$$button3.append('Clicked ', $$text4, ' times')
- What updates. The markup that the component creates once: what it returns and the elements
declared at the top level of its body (
const input = <input />). Text and attributes that read the state are updated in place. Nodes that depend on it ({items.map(...)},{ok ? <b /> : null}) are created again. A property of a child component that gets the state is updated too. - What counts as a change: assignment and
++of the variable or its fields (user.name = "Ann"), the mutating methods of arrays (push,splice,sort…) and methods of objects, except known reading ones. Changes through variables that point into the state (for todo in todos,todos.map(todo => ...)) are seen too. Changes inside functions the state was passed to are not: then the assignmenttodos = todoshelps. - When. Changes in event handlers and in the component's functions update the markup right
away. Changes in the component's body itself, before
return, update nothing: there is no markup yet, and it will be created with the new values. Neither do changes in rendering code: in markup expressions and in the functions they call.
Inside a component, {if ...}, {for ...} and {switch ...} that depend on state update too: a
branch is created again only when the choice changes, and the blocks of a list are found by the
array item itself and moved on changes, not created again.
State of a module. state at the top level of a module is state that its components share:
the components that read it are updated when it changes anywhere in the module, in a function, a
handler or a timer. Other modules import it, import { items } from "./cart.rk", and read it;
changing it there is an error that says to call a function of its module. A component listens while
it is on the page, so its module keeps a set of the updates of the components that read the state,
$$listeners$items, and a change runs them (components.md).
Derived values. derived double = count * 2 at the top level of a component's body is a value
computed from state and properties. It is read like a constant, and assigning it is an error. When
what it reads changes, it is computed again, before the markup that reads it is updated:
comp Counter(initialValue number) {
state count = initialValue
derived double = count * 2
return <button onClick={count++}>{count} × 2 = {double}</button>
}
let count = initialValue
let double = count * 2
// ...creating the nodes...
function $$updateCount2() {
double = count * 2
$$text5.data = count
$$text6.data = double
}
- It is one name and one expression, or a block that computes it (below); its type may be
written:
derived left number = .... It is declared only in a component (or a decorator), likestate. - It is computed again also when the body of the component changes the state before the markup exists, so it is right wherever it is read. One that reads no state and no properties that get the parent's state is a constant.
A derived block. A value that takes several statements to compute is a block after the name,
which ends with a return of the value. In JS the block becomes a function, called first and by
the updates of what it reads:
comp Todos() {
state todos Todo[] = []
derived summary string {
const done = todos.filter(todo => todo.done).length
if done == 0 {
return "Nothing done"
}
return `${done} of ${todos.length} done`
}
return <p>{summary}</p>
}
const $$computeSummary3 = () => {
const done = todos.filter((todo) => todo.done).length
if (done === 0) {
return 'Nothing done'
}
return `${done} of ${todos.length} done`
}
let summary = $$computeSummary3()
// ...creating the nodes...
function $$updateTodos2() {
summary = $$computeSummary3()
$$text5.data = summary
}
- The block is the body of a function without parameters:
const,let,if,for,switchandreturn, but nostateor other declarations of a component. The type is inferred from thereturns, as for a function without results, or checked against the one written. An object type goes in parentheses, as after the parameters of a function:derived point ({ x, y number }) { ... }. - Every way through the block ends with a
returnof one value: otherwise it is an error. - What it reads is what its code reads, the local functions it calls included. One that reads no
state runs once, as
(() => { ... })(). - It computes and changes nothing: assigning state in it is an error, and it is computed while the markup is created and updated, so it calls no updates.
public derivedof a decorator may be a block too.
Effects. effect { ... } at the top level of a component's body runs once the markup is
created, and again after the updates whenever what it reads changes. What it reads is what its code
reads while it runs: not in the functions it creates (setInterval(() => ...)) or in its
defer, and not the variables it writes. It cleans up with defer: the deferred call runs before
the effect runs again, and when {if}, {switch} or {for} removes the component.
comp Todos() {
state todos string[] = load()
// Saved again on every change of the list.
effect {
localStorage.setItem("todos", JSON.stringify(todos))
}
// ...
}
- An effect returns nothing. Unlike
mount, it does not wait for the markup to be in the document, and it runs again. - An effect after an early
returnof the component may not be created, so, like the markup there, it does not run again on changes.
Two-way binding. bind:value={name} on <input>, <textarea> and <select> and
bind:checked={done} on <input> show the variable's value and write what the user entered into
it. Anything assignable can be bound: a variable or a field. The type is string, number (only
for <input type="number"> and type="range") or bool for checked.
Mounting. mount { ... } at the top level of a component's body runs once its markup is on
the page. What it defers with defer, as an effect does, runs when {if}, {switch}, {for} or
a branch of ?: in markup removes the markup:
comp Clock() {
state time = new Date().toLocaleTimeString()
mount {
const timer = setInterval(() => {
time = new Date().toLocaleTimeString()
}, 1000)
defer clearInterval(timer)
}
return <p>It is {time}</p>
}
- For every instance.
mountruns for every created component: twice for a list of two<Fruit />. To do something once for the whole list, writemountin the component that creates the list. - When. Only when the markup is in the document. That is checked in a microtask after the
code that created the component: by then
document.body.append(...)or an{if}branch has usually inserted the markup, and the browser has not drawn a frame yet, sofocus()and measuring sizes work. Markup created earlier and inserted later (const card = <Card />, thendocument.body.append(card)in a timer) mounts when it is inserted: while some markup waits, aMutationObserverwatches the document. If{if},{switch}or{for}removes the markup before that,mountdoes not run. - The body of
mountis a function that runs later, like an event handler: changes of state in it update the markup, andreturnbelongs to it, not to the component. - Cleaning up is
defer, as in an effect, andmountreturns nothing:mount returns nothing; clean up with defer, e.g. defer clearInterval(timer). As everywhere,defer f(x)takesxat thedefer;defer { ... }reads what it uses when it runs, which matters for a value that changes later:defer { editor?.dispose() }. Adeferinside anifcleans up only when it ran. - Who runs the cleanup.
{if},{switch}and{for}blocks know which components were created in them, nested blocks included, and run their cleanup when they remove them. Markup that the program inserted by itself (document.body.append) and removes by itself does not: its cleanup does not run. mountcan be written several times; they run in order.mountis a keyword only at the start of a statement in a component's body: a function namedmountelsewhere is an ordinary function.
const $$cleanups3 = [];
$$mount(() => $$mountNode2, () => {
const timer = setInterval(() => { ... }, 1000);
$$cleanups3.push(() => clearInterval(timer));
}, $$cleanups3);
References. ref name at the top level of the body of a component or a decorator names an
element of its markup, which ref={name} gives:
comp Search() {
ref input
mount {
input.focus()
}
return <form class="search">
<label for={input.id}>Find</label>
<input id="query" ref={input} />
</form>
}
const input = document.createElement('input')
input.id = 'query'
$$mount(
() => $$mountNode2,
() => {
input.focus()
},
)
// ...the markup fills the element in instead of creating it:
$$label3.htmlFor = input.id
- The element exists from the start. It is created where the ref is declared, with its
constant attributes: those written as a string or without a value, before any
{...spread}. The markup sets the rest where it is written: values in{...}, handlers,bind:and children. So a ref is nevernull, and markup can refer to an element written further down. - The type is that of the element (
HTMLInputElement), or the one written:ref input HTMLElement. A ref cannot be assigned, and it is not state. - Once. A ref is bound to one element, in markup created exactly once: what a
returngives,const x = <...>at the top level of the body, the children of components there, and the wrapper of a decorator, for the refs of the decorator. Inside{if},{for},{switch}, expressions and functions a ref is an error. If an earlyreturngives other markup, the element stays as it was declared, outside the document. - A ref to a component,
<Card ref={card} />, points to the element at the top of whatCardcreates, through the wrappers of its decorators. The ref creates that element, andCardfills it in: an inlined one directly, a function throughthis,{ $$root }. A component with severalreturns, one that returns a fragment, or a wrapper that returns some other expression cannot be pointed to: the element is not known in advance. A component cannot have a property namedref.
Styles. style { ... } at the top level of the body of a component or a decorator is CSS for
its own markup:
comp Badge(color string) {
style {
.badge { padding: 2px 8px; background: {color}; }
}
return <span class="badge">new</span>
}
- Scope. The elements of the component's own markup get the class
rook-badge-<hash>, and so does every compound selector, so the rules reach neither the rest of the page nor the markup ofchildrenand other components.:global(...)keeps a selector as it is. - Values from code.
{expr}in the value of a declaration (name:followed by a space or a value) is a string or a number. The value becomes a CSS variable that the compiler sets on the element the component returns, and again when what it reads changes. - The CSS is added to
<head>once by the code of the module, with$$style. A selector that matches no element of the markup is a warning, which does not stop compilation.
CSS modules. import styles from "./button.module.css" reads the file at compile time. Its
classes get names of their own, button_14zwdg2, and styles is an object of them: its type has a
string field for each class, so styles.buton is a compile error, and styles[kind] with
kind "primary" | "ghost" is checked too. Tags, :root and :global(...) stay global. The
import becomes the object, and the module adds the CSS to the page with $$style; the file is
not imported at runtime, so this works with rook build and with Vite. A class that the module
never names is a warning, unless it reads styles with a key that is not known.
Web components. @html-tag before comp makes a component a custom element as well, so it
works in plain HTML, in other frameworks and from JS. The tag is the component's name in kebab case,
or the one given in the decorator:
@html-tag comp mainPage() { ... } // <main-page>
@html-tag("app-card") comp Card(title string) { ... } // <app-card>
- The name follows the rules of HTML: lowercase letters, digits,
-,.and_, starting with a letter, with at least one hyphen, and not one of the names HTML reserves (font-face...). A name that breaks them, or a tag used by two components, is a compile error. Without a name in the decorator, the component may start with a lowercase letter:@html-tag comp mainPage(). - Rendering. The element creates the component's markup in its shadow root when it is connected
to the document. When it is disconnected and not inserted back in the same task, the markup is
removed and what
mountdeferred runs; moving the element keeps its markup and state.childrenis a<slot>. - Properties. Every property except
childrenis a JS property of the element; setting it updates the markup. Properties of typestring,numberorbool(also nullable, literal types and their unions) have attributes too:itemCountisitem-count. The attribute is converted by the type: a string as it is, a number withNumber(), a bool istruewhen the attribute is there. A removed attribute leaves the default value. Arrays, objects and functions are only JS properties. - Missing properties. An element written in HTML has no properties until they are set, so a
property without a default value gets its zero value (
"",0,false,[],null). A property whose type has no zero value needs a default value or a nullable type. Properties cannot have the names ofHTMLElementproperties that the element needs:id,style,hidden,className,slot... - In markup of the same module
<app-card title="Hi" item-count={2} />sets the properties directly, so they are checked like the properties of a component and may be objects or functions. - Definition.
customElements.defineis called at the end of the module, when the names the component uses have their values. Properties set on an element before that are kept.
class $$CardElement extends HTMLElement {
static observedAttributes = ['title']
connectedCallback() {
/* $$Card(...) into this.shadowRoot */
}
disconnectedCallback() {
/* the cleanup of mount */
}
attributeChangedCallback(name, old, value) {
/* this.title = value ?? undefined */
}
set title(value) {
/* updates the markup */
}
}
customElements.define('app-card', $$CardElement)
Decorators. dec name(parameters) { ... } declares logic that is added to the components it
is applied to: state, functions, mount and a wrapper around what the component returns. A
decorator is applied with @name(arguments)
before comp; like a component, it exists only at compile time, and its code is inlined into each
component.
dec counter(start number = 0) {
public state count = start
let clicks = 0
public func add() {
count++
clicks++
}
mount {
console.log("counting from", start)
}
}
@counter(5)
comp Clicker(label string) {
return <button onClick={@counter.add()}>{label}: {@counter.count}</button>
}
- Parameters are written as for functions, but may have default values at the end. The
arguments are positional; without arguments the parentheses can be left out:
@counter. They are evaluated for every instance with the component's properties in scope, so@counter(label.length)works; when a property changes, the argument is computed again. In the decorator its parameters are read-only. - The body may hold
state,const,let,ref,style, functions,mountand, at the end, thereturnof a wrapper; its refs are bound in the markup of the wrapper. Its own names are used in it as usual; the component does not see them unless they arepublic. - Public members are
public state,public derived,public constandpublic func; there is nopublic let. The component reads state, derived values and constants as@counter.count(in markup this updates like its own state) and calls functions as@counter.add(). Outside the decorator its members are read-only:@counter.count = 0or@counter.items.push(x)is an error, changes go through its public functions. - The decorator does not see the component, only its arguments, so it fits any component.
- The wrapper
return (content Element) => ...gets what the component returned, and what it returns is what the component gives in the end. It is a function literal with one parameter, whose type is written: it limits where the decorator can be applied ((form HTMLFormElement) => ...only fits components that return a form), and the type of<Clicker />is what the outermost wrapper returns. The wrapper is called once, when the component is created; to change what is shown later, its markup reads the decorator's state, and it updates like the component's own. A wrapper returns once, at the end of its body. - Dependencies. A public member read such as
@cart.countgives the compiler a dependency on@cart. A decorator can get it from context or from an earlier application on the same component. Decorators that depend on each other are an error. See explicit needs. - Including.
dec card(title string) includes framed(title), likes { ... }applies them with it, above its own body; their arguments see its parameters. The component reads their public members through it,@card.count, and@cardcounts as@likesapplied, for context requirements and for detecting repeated application. An exported decorator cannot include others yet. Apublic refof a decorator is read as@framed.box: the ref is read-only, its element is not. - Several decorators,
@a @b comp X: the bodies run from top to bottom, then the body of the component; the wrappers apply from the bottom up (the result of the component goes tob, the result ofbtoa);mountruns from the inside out (the component,b,a), the cleanup in the reverse order. A decorator applied twice is an error, and@html-tagmust be the first one. - The names of the module that a decorator and its arguments use must not be declared in the component: its code runs inside the component.
decis a keyword only at the start of a declaration at the top level of a module.- Modules.
export decexports a decorator; another module imports it by its name,import { counter } from "./counter.rk", and applies it as usual. Its code is inlined there, and the names of its own module that it uses come through hidden exports:export { log as $$counter$log }in its module,import { $$counter$log } from "./counter.js"where it is applied. So an exported decorator cannot assign the variables of its module (other modules can only read them), and the decorators it needs are exported too. The components of its module that its code uses go with it, like those of an inlined component of another module; they cannot use components or decorators that their module imports yet. - Not yet: renaming a decorator on import,
returninside theiforforof a wrapper, and combining decorators.
dec notFound() {
state missing = false
public func show() {
missing = true
}
return (page Element) => <div class="page">{missing ? <NotFoundPage /> : page}</div>
}
In JS the decorator's code goes into the component's block, with its names prefixed. A wrapper is
inlined where the component returns: its markup is created first, in the variable of the
parameter ($$notFound$page), then the wrapper's markup around it.
const $$counter$start = 5
let $$counter$count = $$counter$start
let $$counter$clicks = 0
function $$counter$add() {
$$counter$count++
$$updateCounter$count2()
$$counter$clicks++
}
The full design, reactivity included, is in docs/components.md.
Stores and context
store Cart() { ... } in a browser module declares both the type Cart and the
factory Cart(). The body declares state, derived, local variables and
functions. public exposes readable fields and callable methods. export store
exports the type and factory. Each factory call has its own state. Reading its
reactive fields in markup, derived or effect subscribes the dependent update to
that instance.
A read of @cartScope.cart resolves the closest @cartScope in the component
creation chain. Read public members as @cartScope.cart. The compiler checks known
trees and calls through a component value check their context at runtime. See
stores and context.
Hooks
A component can reuse logic from a module-local
hook useCounter(initial number) { ... }. A call takes the form
const counter = useCounter(initial) at the top level of a component or another hook.
Each call gets its own local bindings and takes positional arguments.
The declaration ends with a record of members, such as return { count, doubled, reset }.
Each field names a local value or a member of a nested hook, and may give it another name,
such as return { count: inner.value }. Reads and writes through counter.count access the
underlying binding. State can be written and derived values are read-only. Use direct member
access and pass individual members to functions. The compiler inlines the body at the call
site and resolves the member record at compile time. Use distinct names for component bindings
and module names referenced by the hook.
In the browser, arguments follow their reactive sources and each state initializer runs once.
mount, effect and their defer belong to the calling component. See the
component design for an example.
On the server, hooks follow the async body of the calling component. Use let and const,
await for data loading, and defer for cleanup at the end of the component. See
hooks on the server.