Skip to content

Components and reactivity ​

A component is its code, then a line ---, then its markup. The code declares the component's state and logic; the markup says what to draw. Weft's markup is markup-kit's: tags, attributes and {expressions}, with control flow written like the code's, behind @: @if, @for, @match.

Counter.weft
weft
prop start = 0
prop step = 1

let mut count = start
derived double = count * 2

fn reset() {
  count = start
}
---
<Box class="flex items-center gap-3">
  <Pressable onpress={count += step}>
    <Text>Add {step}</Text>
  </Pressable>
  <Text>{count} (twice: {double})</Text>
  <Pressable onpress={reset}>
    <Text>Reset</Text>
  </Pressable>
</Box>

Capitalized tags are primitives (Box, Text, Pressable, TextField…) or components in scope. The class attribute takes style tokens.

What the code declares ​

At the top level of a component's code:

declarationwhat it is
let mut x = estate: the instance's own, reactive
let x = ea constant, computed once per instance
prop x: T = d, prop x?: Ta prop: read-only, follows what the parent passes
prop bind x: T = da two-way prop: writing it writes the parent's bound place
derived x = e, derived x { … return v }a value computed from others, recomputed when they change
effect { … }code that runs after the screen updates, when what it read changed
fn f() { … }functions; the ones that write state are handlers
query fn f() { … }, mutation fn, action fna function that runs on the server (The server)

A prop's type comes from its annotation, or from its default (prop step = 1 is a number). Statements at the top level run once, in order, when the instance is created.

A component has no caller to give an error to, so its top level, its handlers, its effects and its markup handle every error where it occurs (let v, err = try …, try … else). Its functions can still pass errors on to the code that calls them (Errors).

Reactivity the compiler proves ​

Todos.weft
weft
import { uuid } from "std/random"
import { plural } from "std/format"

type Todo = { id: string, title: string, done: boolean }

let mut todos: Todo[] = []
let mut draft = ""
derived left = todos.count(t => !t.done)

fn add() {
  let title = draft.trim()
  if title == "" { return }
  todos.push(Todo { id: uuid(), title, done: false })
  draft = ""
}
---
<Box class="flex flex-col gap-2">
  <TextField bind:value={draft} onsubmit={add} placeholder="What next?" />
  @for mut todo of todos key todo.id {
    <Checkbox bind:checked={todo.done} label={todo.title} />
  }
  <Text>{plural(left, "item")} left</Text>
</Box>

Weft has no reactive wrappers, no signals and no dependency tracking at run time. The compiler reads the code and lists, for every derived value, effect and markup expression, the state it reads, and for every handler the state it writes. It can do this because values are copies: state changes only where code assigns to it, calls a changing method on it, or passes it with &.

Here the compiler knows that add writes todos and draft; that the check boxes write todos[*].done; and that left reads todos. Typing in the field writes only draft, so left and the list are left alone. Checking a box updates left and that one box.

@for mut todo of todos makes each todo a place in todos, so bind:checked={todo.done} writes the item itself. Without mut, the items are read-only. The list of a @for mut must be state, not a derived value.

The unit of work is a turn: one handler, timer callback, effect run, or the code after an await. After a turn:

  1. derived values that read what the turn wrote are recomputed; one whose value comes out equal changes nothing further;
  2. markup that reads a changed path updates, and the screen is drawn;
  3. effects that read a changed path run, each as its own turn.

Derived values and markup are pure ​

A derived value, and every expression in the markup, may read anything but write no state and make no effectful call (a lib call with effects, std/log, timers, std/random, a server function). This is what lets the compiler recompute them freely:

Bad.weftrejected by the compiler (E4001)
weft
let mut count = 0
let mut reads = 0
derived double {
  reads += 1
  return count * 2
}
---
<Text>{double}</Text>

Work that has effects goes in a handler or an effect.

Async derived values ​

weft
import { debounce } from "std/reactive"

prop query = ""

action fn search(q: string): string[] {
  return [q, `${q}!`]
}

derived results = await search(debounce(query, 300))
---
@await results {
  <Text>Searching…</Text>
} @then found {
  <Text>{found.length} results</Text>
} @catch e {
  <Text>{e.message}</Text>
}

A derived value whose body awaits is an Async<T, E>: { pending, value, error }. It runs when the instance mounts and again whenever something it reads changes; starting again cancels the run in progress, so a slow old answer never replaces a newer one. While a run is pending, value keeps the last result. An await in its body passes its error on by itself: a run that fails sets error, typed by what it awaited (a server function's call adds NetworkError, and @catch e shows it).

debounce(query, 300) (from std/reactive) follows query once it has stopped changing for 300 ms, so the search runs once the typing pauses; throttle(x, ms) follows x at most once per ms. Both work only in derived values and markup expressions. Apart from its awaited server functions and lib calls, an async derived value is pure like any other.

A shortcut or gesture is enabled while its when holds. when is a pure closure, and the compiler tracks what it reads like a derived value's:

weft
let mut editing = false
fn save() {}
shortcut("save", { label: "Save", keys: ["ctrl+s"], when: () => !editing }, save)
---
<Pressable onpress={editing = !editing}><Text>{editing ? "Done" : "Edit"}</Text></Pressable>

Effects ​

An effect runs after the first paint, then again after every turn that wrote something it read. It may return a cleanup function, which runs before the next run and when the instance goes away:

Clock.weft
weft
import { now, setInterval, clearInterval } from "std/time"
import { date } from "std/format"

let mut time = now()
let mut saved = 0

effect {
  let id = setInterval(() => {
    time = now()
  }, 1000)
  return () => clearInterval(id)
}

effect {
  lib.store.set("saved-at", saved)
}
---
<Text>{date(time)}</Text>

The interval's callback writes time directly: closures reach state by name, so this is allowed even though the callback runs later. Effects that keep changing what they read are stopped after 100 rounds, with an error naming them.

Markup ​

{expr}shows a value: strings as they are, numbers, booleans, null as nothing
attr={expr}, attr="text {expr}"sets a prop or attribute
onpress={handler}, onpress={count += 1}an event: a function, or a statement that runs as the handler
bind:value={place}, bind:valuea two-way binding to a place (bind:value alone binds the place named value)
@if c { … } @else if d { … } @else { … }conditionals
@for item of list key item.id { … } @empty { … }a list, keyed; @empty shows when it has no items; (item, i) gives the index; @for mut makes each item a place
@match e { Pattern => <El />, … }one arm per case, exhaustive as match is
@await task { … } @then v { … } @catch e { … }a task's states; @catch gets its error
@key e { … }rebuilds what's inside when e changes
@try { … } @catch e { … }shows the @catch part when what's inside panics (Errors)
@snippet row(t: Todo) { … }, @render row(t)reusable markup
@let x = enames a value for the rest of the block

@ starts a block only before one of those words; anywhere else it is text (mail@example.com). @@ writes a literal @ before such a word.

Inbox.weft
weft
type Message = { id: number, from: string, subject: string, read: boolean }

prop messages: Message[] = []
let mut showRead = false
derived shown = messages.filter(m => showRead || !m.read)
---
@snippet line(m: Message) {
  <Text class="font-medium">{m.from}</Text>
  <Text>{m.subject}</Text>
}

<Box class="flex flex-col gap-2">
  <Switch bind:checked={showRead} label="Show read" />
  @for (m, i) of shown key m.id {
    <Box class="flex gap-2">
      <Text>{i + 1}.</Text>
      @render line(m)
    </Box>
  } @empty {
    <Text>Nothing new.</Text>
  }
</Box>

@match draws one arm per case of a union, and the compiler checks that every case has one. An arm is one element, { … } for several, or {} for nothing:

Status.weft
weft
type Load = Idle | Loading { percent: number } | Failed { message: string }

prop state: Load = Idle
---
@match state {
  Idle => {},
  Loading { percent } => <Text>Loading… {percent}%</Text>,
  Failed { message } => {
    <Text class="font-medium">It didn't work</Text>
    <Text>{message}</Text>
  },
}

Event attributes ​

An event attribute takes a function (onpress={reset}, onpress={() => count += 1}) or, shorter, a statement: an assignment, ++ or -- (onpress={count += 1}, onpress={open = !open}) is a handler that runs it. A call is an expression, not a statement, so onpress={reset()} would pass what reset() returns. Unless that is a function, it is an error, and the compiler suggests onpress={reset} or onpress={() => reset()}:

Toggle.weftrejected by the compiler (E2001)
weft
let mut open = false

fn toggle() {
  open = !open
}
---
<Pressable onpress={toggle()}>
  <Text>{open ? "Close" : "Open"}</Text>
</Pressable>

Props, children and two-way props ​

A parent passes props as attributes. Whatever markup a tag wraps becomes the child's children snippet. A prop bind lets the child write back to the parent's place:

Stepper.weft
weft
prop bind value: number = 0
prop step = 1
---
<Box class="flex items-center gap-2">
  <Pressable onpress={value -= step}><Text>−</Text></Pressable>
  <Text>{value}</Text>
  <Pressable onpress={value += step}><Text>+</Text></Pressable>
  @render children?.()
</Box>
Order.weft
weft
import Stepper from "./Stepper"

let mut quantity = 1
---
<Stepper bind:value={quantity}>
  <Text>items</Text>
</Stepper>
<Text>Total: {quantity * 4} €</Text>

bind:value={quantity} needs quantity to be a place of exactly the prop's type, and an unannotated let mut takes that type from the binding: quantity is a number. Writing a plain prop is an error whose fix-it makes it prop bind (and, in an editor, turns the parents' value={…} into bind:value={…}); binding an item of a @for offers @for mut.

Context and globals ​

lib/prefs.weft
weft
export type Density = "compact" | "comfortable"

/// One value for every instance that imports it.
export global unread: number = 0

/// Provided by a component for the instances below it.
export context density: Density = "comfortable"
components/Inbox.weft
weft
import { unread, density } from "lib/prefs"
---
<Box class={density == "compact" ? "gap-1" : "gap-3"}>
  <Text>{unread} unread</Text>
  <Pressable onpress={unread = 0}><Text>Mark all read</Text></Pressable>
</Box>
routes/page.weft
weft
import { density } from "lib/prefs"
provide density = "compact"
---
<Inbox />

Two kinds of shared state are declared in modules (Modules):

  • a global is one value shared by every instance that imports it, reactive and writable;
  • a context is provided by a component for the instances below it (provide theme = …); readers get the nearest provider's value, and can't write it.

Both belong to components. Server code has neither: per-request values there, such as the signed-in user, come from std/http.

Weft is in development. The reference is the spec as it stands today.