Tooling, Images and Translations
Recipes: wisp recipe add <name>
A recipe is a folder of your own in add/<name>/. Wisp ships none. wisp recipe list lists them and wisp recipe add sqlite applies one. Nothing runs or downloads, and an existing file stays unless you pass --force.
The add/<name>/recipe file has one command per line (# comments): dep (a [dependencies] line), env (a .env.example line), file <path> (copies add/<name>/<path> to <path>) and note (text printed after).
# add/sqlite/recipe
dep sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio", "sqlite"] }
env DATABASE_URL=sqlite://app.db?mode=rwc
file src/db.rs
file src/routes/api/time/+server.rs
note Call crate::db::open().await? in init (src/hooks.rs), then GET /api/time.
// add/sqlite/src/db.rs: `pub` items of src/db.rs are in every route
pub type Pool = sqlx::SqlitePool;
pub async fn open() -> Result {
let url = wisp::env("DATABASE_URL").or_status(500)?;
wisp::provide(Pool::connect(&url).await?);
Ok(())
}
pub fn pool() -> Result<&'static Pool> {
wisp::state::<Pool>()
}
// add/sqlite/src/routes/api/time/+server.rs
async fn get() -> Result<Response> {
let (now,): (String,) = sqlx::query_as("select datetime('now')")
.fetch_one(pool()?)
.await?;
Ok(Response::text(now))
}
Component Kit: wisp ui add
wisp ui list # what there is
wisp ui add button dialog tabs # into src/components
It copies components into src/components. The copy is yours to change.
| Component | Use | Browser code |
|---|---|---|
Button | <Button variant="secondary" kind="submit">Save</Button>; href makes it a link, and with disabled the link has no href and sets aria-disabled | none |
Badge | <Badge tone="success">Paid</Badge> | none |
Card | <Card title="Tea">…</Card> | none |
Input, Textarea | <Input label="Email" name="email" kind="email" hint="…" problem=${p} /> | none |
Checkbox, Switch | <Switch label="Dark" name="dark" checked /> | none |
Select | <Select label="Drink" name="drink"><option>Tea</option></Select>: the hint is outside the label | none |
Accordion | <Accordion title="Q" group="faq">A</Accordion> | none |
ClientOnly | <ClientOnly fallback="Loading…"><Chart /></ClientOnly>: the server sends the fallback, the children are drawn on mount | onMount |
Dialog | <Dialog id="d" title="Sure?" trigger="Delete">…</Dialog>: a popover, so it is not modal (Tab can leave it); focus starts on the dialog and comes back on close; a tall one scrolls inside | none |
Menu | <Menu id="m" label="Actions"><button role="menuitem">Edit</button></Menu> | arrow keys |
Tabs | <Tabs id="t" labels=${["A", "B"]}><div>…</div><div>…</div></Tabs> (up to 12) | none |
Theme | <Theme theme=${cx.theme()} next=${cx.url()} /> first in the layout. wisp ui add theme also writes src/routes/theme/+server.rs. Light, dark or the browser's, by a form and a cookie | none |
Skeleton | <Skeleton shape="circle" />, <Skeleton lines=${3} /> (1 to 50 lines), <Skeleton shape="rect" --w="12rem" --h="6rem" /> | none |
Table | <Table caption="Orders" sticky><thead>…</thead><tbody>…</tbody></Table>; class="num" right-aligns | none |
DataTable | <DataTable columns=${cols} path="/users" sort=${sort} dir=${dir} page=${n} pages=${total} numeric=${["age"]}><tr>…</tr></DataTable>: sortable heads and Previous/Next are plain links (?sort=col&dir=asc&page=2), keep=${[("q", q)]} carries other query values. The server sorts and pages (Page::of, cx.query). wisp ui add datatable writes Table too | none |
Empty | <Empty title="No orders yet" text="…" icon="+"><Button href="/new">New order</Button></Empty> | none |
Kbd | <Kbd keys=${["Ctrl", "K"]} /> | none |
Scroll | <Scroll label="Log" max_height="16rem" horizontal>…</Scroll> | none |
Radio | <Radio legend="Size" name="size" options=${[("s", "Small"), ("l", "Large")]} value="s" hint="…" problem=${p} /> | none |
Progress | <Progress id="up" label="Upload" value=${40.0} />; meter makes it a <meter> | none |
Alert | <Alert tone="warning" title="Careful">…</Alert> (neutral, info, success, warning, danger) | none |
Tooltip | <Tooltip id="tip" text="Saves it"><button>Save</button></Tooltip>: shows on hover and focus, stays while the pointer is on it, flips to stay on screen and is not cut off by a parent with overflow: hidden | aria-describedby (on the first focusable child, or on the wrapper without script), Escape |
Toast | <Toast message=${flash.unwrap_or_default()} /> in the layout. Scripts send dispatchEvent(new CustomEvent('toast', { detail: 'Saved' })) | closing early |
Props are typed and styles are scoped. They read the demo's tokens with fallbacks (var(--accent, #896ce0), --panel, --inset, --panel-hover, --line, --line-strong, --ink, --ink-muted, --ink-subtle, --radius, --danger, --success, --warning), so your :root restyles them all. A token you leave out falls back to one set of colours that follows color-scheme (light-dark()), so the components read in light and dark without any token file. --success-ink, --warning-ink and --danger-ink (text on the page) and --shadow (the shadow under a menu, dialog, toast or tip) are optional too. They also follow prefers-reduced-motion, forced colors, a coarse pointer (44px targets), right-to-left text and print. They use native elements (<dialog>, popover, <details>, <select>), and all but ClientOnly work with JavaScript off (With JavaScript off).
Images
An <img src="$lib/photo.jpg" alt="…"> (a file of src/lib) or src="/photo.jpg" (from static/), a JPEG, PNG or WebP with a quoted src, is rewritten at build time:
- Always:
widthandheightfrom the file header, unless the tag sets them. No layout shift. wisp buildwrites WebP at up to three widths (640, 1280, 1920, never wider than the image) to.wisp/img/<hash>-<w>.webpand addssrcset,sizes="100vw",loading="lazy"anddecoding="async". Your ownsizesor other attributes are kept. Release serves the files under/_app/img/as immutable.- The encoder is a pinned cwebp (libwebp 1.6.0, downloaded once to
~/.wisp/bin, SHA-256 checked).$WISP_CWEBPoverrides it. Without it the build warns and the server serves the original, sized. A missing$lib/file is a build error. - Dev serves the original with only
widthandheight. <img priority …>is above the fold: it getsfetchpriority="high"and is not lazy.<img blur …>shows a blurred copy of the image while it loads.wisp buildwrites a WebP of at most 16 pixels on its longest side to.wisp/img/<hash>-blur1.webp. A release build puts it instyleas abackgrounddata URI of at most 300 characters (a longer one is left out, with a warning). Your ownstylecomes after it. The request does no work for it, and the page gets no script. The copy stays behind the image, so usebluron images with no transparency. The copy is adata:image, soimg-srcmust allowdata:(the default does) andstyle-srcmust allow'unsafe-inline'. A turned image (EXIF orientation) gets no blur placeholder, with a warning. Dev shows no copy. Ablurtag with nostatic/orsrc/libfile to read is a build error:<img blur> needs a src of a JPEG, PNG or WebP file in static/ or src/lib.<img data-wisp-raw …>stays as written. Asrcwith a hole, or another site's, is left alone.
avif feature (wisp-cli, wisp-build, off by default): wisp build also writes AVIF widths and the tag becomes a <picture>. It is pure Rust and slow.
img feature (wisp): resizes on request. Add src/routes/_img/+server.rs with wisp::img::serve::<crate::App>(cx).await, then use /_img?src=/photo.jpg&w=640&q=75.
- It serves only
static/files.wcomes from a fixed list (next/image's), and Wisp changesqto the next one of 25, 50, 75, 90 or 100 at or above it. It refuses..and files over 10 MB, pictures over 40 megapixels and pictures that decode to more than 160 MB (40 megapixels at 4 bytes). It refuses a resize that needs more than 320 MB of scratch memory: 16 bytes for each pixel of the source width by the new height. A 4000 by 3000 picture atw=3840needs 184 MB and passes./_imgnever sends the query or the fragment of a remote src to the origin, so a signed URL does not work through it. A remote picture has one cache entry for each URL without them, for eachwandq, with the host in lower case. Results are cached in memory (64 MB, the keys count too). A matchingIf-None-Matchgets a 304. - A JPEG or an opaque WebP comes out a JPEG. A PNG or a WebP with transparency comes out a lossless PNG.
wisp buildmakes AVIF and WebP forstatic/instead. - For remote pictures, like Next's
remotePatterns, writeimages = ["https://cdn.example.com/photos/**"]in[package.metadata.wisp]. A match needs the same scheme, host (*.for any name below one), port and path (/**for any path below). The fetch goes to public addresses only, follows no redirect, and takes a 200image/*of at most 10 MB within 10 s.httpsneeds thetlsfeature. With noimages, anhttpsrc is a 400. The edge build fetches none.
Translations
One JSON file per locale in src/locales, flat or nested keys:
{ "cart": { "title": "Your cart",
"items": "{count, plural, =0 {No items} one {# item} other {# items}}" },
"hi": "Hello, {name}!" }
<h1>${t("cart.title")}</h1>
<p>${t("cart.items", count)} ${t("hi", name = user.name)}</p>
<button on:click="n++">{:t('cart.items', n)}</button>
- Messages use a subset of ICU:
${name}, and{n, plural, …}with=Nand the locale's CLDR cases.otheris required,#is the count,'{'is a brace. - Pass one value for a message with one placeholder, else by name (
name = expr, or a variable of that name). In a script: one value, or an object,t('hi', { name }). - The build checks keys and placeholders across locales and reports file and line.
t("cart.title")is a&'static strlooked up in a table at build time, with none at run time. - The locale comes from the route's
[[lang=locale]], thelangcookie,Accept-Language, then the default (the first file, orwisp::default_locale("fr")?ininit).cx.locale()returns it. Wisp sets<html lang>and keeps aCACHEd page per locale. - A page's scripts get only the messages they use.
src/libmodules cannot callt, so pass them text. - The browser code of
tis in/_app/c/i18n.js. Only a browser module that sayst(…), in an app withsrc/locales, loads it. {@html wisp::switcher(cx)}is a<nav class="wisp-locales">of links to the page in each locale. For your own, loop overwisp::locales()and linkwisp::localize(cx.path(), l).
Routing is set in [package.metadata.wisp], each string name value:
i18n = ["default en", "prefix as-needed", "domain example.fr fr", "missing warn"]
| Setting | Behavior |
|---|---|
prefix optional | The default. /about and /fr/about both answer |
prefix always | /about redirects (307) to the visitor's locale (cookie, then Accept-Language): /fr/about |
prefix as-needed | The default locale has no prefix. /en/about redirects (308) to /about |
domain example.fr fr | One per locale. The request's locale is its Host's, and redirects are off |
default fr | Locale for a request naming none, instead of the first file |
missing warn | A locale lacking a key uses the default's message and the build warns. missing error is the default |
{@html wisp::alternates(cx)}in a head writes<link rel="canonical">and analternatewithhreflangper locale plusx-default. Addresses start withSITE_URL./sitemap.xmllists every page in every locale withxhtml:linkalternates.wisp build --staticwrites each locale's pages. Pages under[[lang=locale]]are not baked.diris set for right-to-left languages, andwisp::dir("ar")saysrtlfor your own elements. A script subtag decides first:sd-Devaandug-Latnareltr,az-Arabisrtl. A subtag after a singleton (ar-u-nu-latn) is no script.ks,prs,azb,pnb,arzandaryarertltoo.- Formatting (small tables, no dependency):
wisp::format_number(n, l),format_money(n, "EUR", l),format_date(d, l),format_date_long(d, l).dis Unix seconds,"2026-10-04"or(2026, 10, 4), andliscx.locale(). - Text helpers (English):
wisp::plural(n, "post")(1 post,3 posts;plural(n, "person|people"))time_ago(unix_secs)(5 minutes ago)wisp::now_ms()(Unix milliseconds, the same on the built-in server and edge hosts)slugify(s)(Héllo World!→hello-world)truncate(s, n)format_bytes(n)(1.5 KB)format_datetime(secs, "%b %e, %Y %H:%M")(UTC)strip_tags(html)andexcerpt(html, 160)initials("Ada Lovelace")(AL)query_string(&[("q", q), ("page", "2")])(?q=…&page=2)random_id(16)percent(part, whole)(33%)csv_row(&cells): one RFC 4180 line, with a'before a cell that starts with=,+,-,@, a tab or a carriage return (a plain negative number such as-12or-1.5is left as is)cx.query_with("page", "2"): this page's query with one value set
Example: examples/i18n.
Is This Page Useful?