Wisp is in pre-release, self-hosted since GitHub suspended us. Install it, or see the changelog.

Wisp

Client Components and State

Client Components

The browser draws a component inside a client block, or given {:…}, bind: or on:.

{:#each names as name (name)}
  <Item label={:name} bind:count="counts[name]" on:bump="bumped = event">
    <b>{:name}!</b>
  </Item>
{:/each}
<!-- src/components/Item.wisp -->
{@props label: &str, count: i32 = 0}
<button on:click="count++; emit('bump', label)">{:label}: {:count}</button>
  • Props are browser values (a ${…} Rust prop is an error). {:...props} spreads an object (label wins if also given).
  • bind:count writes back to the parent. emit('bump', x) fires the parent's on:bump, and the handler sees x as event.
  • Such a component holds only text, directives, {:…}, client blocks and {@render children()}. Server code in it is a build error.
  • A component can render itself (tree view) inside an {:#if}/{:#each}.
  • setContext(key, value)/getContext(key) share with descendants. const [getUser, setUser] = context() makes a keyed pair.
  • A Rust-keyword prop (type, match) is r#type in a Rust hole. A JavaScript-keyword prop (class, for) must be renamed: let { class: klass } = $props().
  • With $props() every prop is optional. Declare it in {@props} to use it in Rust.

Extra attributes (title, aria-label, data-id=${id}) go to a ...rest prop (let { label, ...rest } = $props(), <span {:...rest}>).

Custom Elements

Put {@element "x-card"} first in a component. It also builds the component as a custom element at /_app/c/el/x-card.js (AGENTS.md has the form). The element uses the names i, c, v and put itself, so a prop with one of them stops the build (W0105): "put is a name that the custom element uses: give the prop a different name. The names i, c, v and put are not available". On any site:

<script type="module" src="https://app.example/_app/c/el/x-card.js"></script>
<x-card title="Hi" count="3" featured>Kids</x-card>
  • Each prop is an attribute (snake_case as snake-case) and a property, read as its Rust type: number, bool, text, else JSON (tags='["a"]').
  • The element has an open shadow root. {@render children()} is a <slot>.
  • The module sends access-control-allow-origin: * and loads live.js, not wisp.js.

State Helpers

Use these in any client script, with no imports:

watch(() => data.id, (id) => { load(id) })         // when data.id changes
effect(() => { load(id) }, () => [id])             // at start and when id changes (return cleanup)
onMount(() => { ready = true })                    // may return a cleanup
onDestroy(() => socket.close())
setInterval(() => n++, 1000)                       // also setTimeout, requestAnimationFrame,
                                                   // addEventListener: stopped for you
listen('/events', (data) => { last = data })       // server-sent events; reopens after an error answer
await tick()                                       // after the redraw
flushSync()                                        // redraw now, not at the end of the task
onError((e) => report(e))                          // each error the page's code throws ({:#try}'s too), uncaught error and rejection
const w = tweened(0, { duration: 400 })            // w.value = 5 runs there; numbers, arrays, objects of numbers
const s = spring({ x: 0, y: 0 })                   // s.set({ x: 9, y: 4 }) with momentum; { hard: true } jumps
const [send, receive] = crossfade({ duration: 400 })   // out:send={{ key: id }} in:receive={{ key: id }}
announce('Saved')                                  // screen readers say it

tweened, spring and crossfade are in /_app/c/motion.js. Only a module that names one loads it.

swr(key, fetcher) is a cache of fetched data with revalidation. See Fetching data in the browser.

optimistic(list, item) puts item in the $state list now and returns the function use:enhance calls with the result. A failed action removes it again:

<form method="post" action="?/add" use:enhance="() => optimistic(todos, text)">…</form>

Shared State

A store outlives components and navigation. Put it in src/lib/:

// src/lib/cart.js
import { store, persisted, derived } from 'wisp'
export const cart = store([])
export const theme = persisted('theme', 'light')       // localStorage
export const count = derived(() => cart.value.length)

import { cart } from '$lib/cart.js' in a script, then cart.value = [...] or $cart. A store has .value, set(v), update(fn), subscribe(fn) and is deep. 'wisp' and '$lib/…' imports work in src/lib/**/*.js, scripts and +page.js.

Is This Page Useful?

View This Page's Source

Type to search every docs page and heading.