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

Wisp

Server Values and Client Blocks

Server Values in the Browser

Wisp sends any Rust value that client code mentions, and only the mentioned parts.

<script lang="ts">
  let guess = data.guess          // the script's `guess`, from the server's
  const total = items.length      // the page's `let items` (or `data.items`)
</script>
{#each keys as key}<button on:click="type(key.letter)">${key.letter}</button>{/each}   <!-- sends key.letter only -->
  • Sent: a page's or layout's Rust names (block lets, route params, Data fields) by name or data.x.y, component props, and loop, if let and {@const} values used in a directive.
  • A name the script declares is the script's. A browser global (document, location, event, fetch) stays the browser's (the Rust one is data.location).
  • Values go as JSON via wisp::Json (numbers, strings, bool, Option, Vec, arrays, tuples, maps). For your own types, use #[derive(Json)]. An unsendable value is a compile error naming wisp::Json. A prop that is also a script variable is a build error.
  • matches(text, q) (no import) is a case-insensitive contains.
  • {:#each list as x if cond} (and {#each} on the server) keeps the items where cond holds. On the server it loops over a variable or field by reference, as plain {#each} does, so xs is still there after the loop and cond sees the same item the body does (&T); over another expression (a range, a call) cond sees &Item.
<input bind:value="q">
{:#each items as item if matches(item.name, q)}<p>{:item.name}</p>{/each}

{:expr} Holes

A live JS expression anywhere in markup: <p>Hi {:name}</p>, <p class="card {:mood}" data-id={:item.id}>, <a href={:url}>. Mixing ${…} and {:…} in one attribute value is a build error.

Client Blocks

{:#if open}<p>Open</p>{:else if name}<p>{:name}</p>{:else}<p>Closed</p>{:/if}

{:#each items as item, i (item.id)}
  <li animate:flip>{:i}: {:item.text}</li>
{:else}
  <li>Nothing</li>
{:/each}

{:#key user.id}<Profile id={:user.id} />{:/key}      <!-- redrawn when it changes -->

{:#await results}<p>Loading…</p>{:then list}{:list.length}{:catch error}{:error.message}{:/await}
{:#await p then v}{:v}{:/await}                       <!-- no pending branch -->

{:#try}<Chart data={:points} />{:catch error}
  <p>{:error.message}</p><button on:click="reset()">Retry</button>
{:/try}
  • (item.id) is the key (else by position). {:#each list} alone draws once per item. {:#each 3 as i} counts.
  • animate:flip goes on an element directly inside a keyed {:#each} (elsewhere it is a build error). Reordered items slide to their new place with the Web Animations API. animate:flip="{ duration: (d) => d * 2, delay: 50, easing: (t) => t * t }": duration is ms or a function of the distance in px (default Math.sqrt(d) * 120), delay is ms, easing is a CSS easing or a function of t (default cubic out). Reduced motion plays nothing.
  • Also <template each="item, i in list"> and <template if="cond">.

Error boundaries

{:#try}…{:catch error}…{:/try} is the browser's error boundary. When something inside throws, its body goes away and {:catch} shows in its place.

  • It catches what its body draws (holes, attributes, blocks, components and their scripts), effects, on: handlers, and the timers and listeners a component inside starts (setTimeout, setInterval, requestAnimationFrame, addEventListener, listen). A rejected promise needs .catch() or {:#await}.
  • error is what was thrown (any name). reset() in the {:catch} part draws the body again; fix the cause first (on:click="items = []; reset()").
  • onError listeners hear every caught error. Outside any {:#try}, an error goes to onError and the console. Boundaries nest, and a throw in {:catch} goes to the next one out.
  • The code is in /_app/c/extra.js, loaded only on a page that uses a {:#try}, {:#await} or another of its features.

Pending boundaries

{:#try}…{:await}…{:catch error}…{:/try} shows {:await} while an {:#await} in its body waits on the first draw. When each one settles, the body shows in its place.

{:#try}
  {:#await user then u}<p>{:u.name}</p>{:/await}
  {:#await posts then list}<p>{:list.length} posts</p>{:/await}
{:await}
  <p>Loading…</p>
{:catch error}
  <p>{:error.message}</p>
{:/try}
  • Only the first draw waits. A later {:#await} (a new promise) shows its own pending branch, not {:await}.
  • The body draws out of the page while it waits, so its awaits start. An {:#await} in an {:#each} or a nested {:#try} counts too.
  • In the browser, a body with no waiting {:#await} shows at once. The server markup still shows {:await} until that first draw.
  • Without browser code (a crawler, scripts off), the page shows only the {:await} branch, never the body.
  • Only a {:#await} in the body's own markup counts. An {:#await} in a component whose module loads later does not keep the try waiting.
  • A rejected promise settles its {:#await}, whose own {:catch} shows. A throw in the body shows the try's {:catch}.
  • A nested {:#try} with its own {:await} waits for its own awaits only. A try that goes away while it waits does not show its body later.
  • The server draws {:await}, not the body, as it draws the pending branch of an {:#await}. The browser then draws the body.
  • {:await} goes once in a {:#try}, after the body and before {:catch}. Elsewhere it is build error W0120.
  • The code is in /_app/c/boundary.js, loaded only on a page that has {:await} in a {:#try}.

Special Elements

Each takes directives for its target and closes itself:

<wisp:window on:keydown.escape="open = false" bind:innerWidth="w" />
<wisp:document on:visibilitychange="save()" bind:visibilityState="seen" />
<wisp:body on:click="menu = false" />
<wisp:element this={:level > 1 ? 'h3' : 'h2'} class="title">{:text}</wisp:element>

<wisp:element> takes a tag name. An unsafe one (script, style, iframe, frame, frameset, object, embed, base, meta, link, template, noscript, noembed, noframes, textarea, title, xmp, plaintext) becomes wisp-element.

Snippets

{:@render name(args)} draws a file's {#snippet} in the browser (args are JS). {@render} still works on the server.

{#snippet chip(tag)}<b class="chip">{:tag}</b>{/snippet}
{:#each tags as tag (tag)}{:@render chip(tag)}{:/each}

A component the browser draws takes snippets as props, by name (<List items={:xs} ${row} />, row=${other}) or among its children, and draws one with {:@render row(x)} where row is one of its props ({@props row: Snippet<&Item>} or $props()). It loads extra.js.

<!-- src/components/List.wisp -->
{@props items: Vec<String>, row: Snippet<&String, usize>}
<ul>{:#each items as item, i}<li>{:@render row(item, i)}</li>{:/each}</ul>
<List items={:fruits}>{#snippet row(name, i)}<b>{:i}</b> {:name}{/snippet}</List>

{:@const} and {:@html}

{:@const name = expr} names a value for the rest of its block. It goes directly in a block ({:#if}, {:#each}, {:#key}, {:#await}, {:#try}), a snippet, or an element in one, where it ends with that element. Outside a block it is a build error. {:@html expr} inserts markup unescaped (trusted markup only) and draws again when the value changes. It loads extra.js.

{:#each items as item}{:@const total = item.price * item.qty}<li>{:total}</li>{:/each}
<div>{:@html post.body}</div>

First Paint

The server renders what it can know into the page, so it works before JS and without it. The browser then adopts those nodes and keeps them live. This covers wisp build --spa and --static too.

  • The server knows server values, props, Rust loop values, literals (0 'text' true null [1,2] {id:1}), script variables first set to those (let todos = data.todos), the item and index of a painted {:#each}, a component's $props() literal default, and a boolean directive like :hidden="!open" with let open = false.
  • It works out !, &&, ||, ??, a ? b : c, .length, x[i], + of strings and numbers, ===/!== against a literal, and the string and array methods split, join, slice, trim, trimStart, trimEnd, toUpperCase, toLowerCase, startsWith, endsWith, includes and indexOf.
  • Everything else is left to the browser: your functions, window, document, Date, Math, fetch, other methods, and a +page.js page's data. That spot paints nothing and the browser draws it.
  • {:@html} is painted only in a build's pages (--spa, --static, PRERENDER), from build-time data. At request time the browser draws it.
  • Icons: a use: action runs only in the browser. To get markup into a built page, draw it with {:@html} from an object-literal map in the component's script: {:@html icons[name]} with let icons = { home: '<svg …>' }. For no JavaScript, use a server component with a Rust function: {@props name: &str} <span>{@html icon(name)}</span>.
  • Held until bound: an element whose class, style or hidden the browser sets (:hidden, class:x, style:x) and the server could not paint gets data-wisp-p. One rule in the head (204 bytes, once per page) keeps it visibility: hidden until live.js binds it, so a frame never shows its wrong look first. With scripts off, or if live.js never comes (3 s), it shows anyway.

Next: components, custom elements and state helpers.

Is This Page Useful?

View This Page's Source

Type to search every docs page and heading.