Reference
Reference
Built-ins
Every function, browser value, method and global the language gives a program, in one place.
This page lists everything a program can call or read without declaring it: the functions the language adds, the browser values it keeps current, the methods of strings, lists and numbers, the built-in types, and the browser's own globals. Expressions explains how to use them; this page is for looking one up.
Each function and value has an entry in the same order: what it is, its signature, its parameters and what it returns, where it may be written, and an example. An example of one line is a fragment of a page; the names it reads are assumed to be declared.
Functions
The functions, in alphabetical order:
| Function | Does |
|---|---|
| Runs a block once, after a delay | |
| The distance from now, in words | |
| Plays an animation on an element handle | |
| Says something to a screen reader | |
| Asks a yes-or-no question in an alert dialog | |
| Sends a small post that survives the page unloading | |
| Opens a channel the site's other tabs hear | |
| Runs a block repeatedly | |
| A number, date or money as text, in the locale | |
|
Sends a request through the same engine as |
|
| Whether a key event is a shortcut | |
| A shortcut as this system writes it | |
| Prints a value to the console | |
| Moves to a route | |
| Shows a change now, and takes it back if the action throws | |
| Plays an element's animation again | |
| Opens a data channel to another reader's page | |
| Markup through an allow-list | |
| Switches the locale, and the direction with it | |
| Switches between light, dark and the system's choice | |
|
Starts a script of |
|
| Opens a stream of server-sent events | |
| A translation | |
| Shows a short message above everything | |
|
A fresh |
|
| Opens a WebSocket |
Every name in this list but announce, ask, http, spawn and toast belongs to the language: a state, prop, parameter, loop item or const with one of these names is an E118. A program's own announce, ask, http or toast keeps its name, and the function is out of reach where it is declared; spawn means something only after worker name =.
after
Runs a block once, after a delay, unless its scope leaves first.
Signature: after(interval) { statements }
| Parameter | Type | Meaning |
|---|---|---|
|
|
|
How long to wait |
Returns nothing. Where: a render block — a page, a component, a branch, a list item. The timer is cancelled when the block that holds it leaves. See Timers.
after(3000) { banner = null }
ago
The distance between a date and now, in words, in the reader's locale.
Signature: ago(date), ago(date, moment) → String
| Parameter | Type | Meaning |
|---|---|---|
|
|
|
The moment to describe |
|
|
the same, optional | What to measure from, in place of now |
Returns now under 45 seconds, then 5 minutes ago, yesterday, in 2 weeks, and so on. An unreadable date gives "". Where: anywhere. It is the same as format(date, .relative).
Text("Posted {ago(post.published)}").muted
animate
Plays a named animation on an element you hold a handle on.
Signature: animate(element, name, duration) → a handle
| Parameter | Type | Meaning |
|---|---|---|
|
|
a |
The element to animate |
|
|
|
A built-in animation ( |
|
|
|
How long it plays |
Returns a handle with play(), cancel() and finished (a promise). It plays as soon as it is made. Where: handlers and actions. See Motion.
Card(ref: panel) { on mouseenter { animate(panel, "pulse", "400ms") } }
announce
Says something to a screen reader, with nothing on screen moving.
Signature: announce(text), announce(text, .assertive)
| Parameter | Type | Meaning |
|---|---|---|
|
|
|
What to say |
|
|
optional | Interrupts what the reader is hearing, for what cannot wait; unset, it waits its turn |
Returns nothing. Where: actions, handlers and effects. See Toasts, questions and announcements.
announce("{results.length} results")
ask
Draws an alert dialog with a question, and waits for the answer.
Signature: ask(question, detail: …, yes: …, no: …, danger: Bool) → a promise of Bool
| Parameter | Type | Meaning |
|---|---|---|
|
|
|
The dialog's heading |
|
|
|
A sentence under it |
|
|
|
The two buttons' words |
|
|
|
Draws yes in the danger colour |
Returns true for yes, and false for no or Escape. The focus starts on no. Where: await in an action or a handler. confirm is the browser's own.
Button("Delete") { on click { if await ask("Delete the project?", yes: "Delete", danger: true) { remove() } } }
beacon
Sends a small POST that the browser delivers even while the page is unloading.
Signature: beacon(url, data) → Bool
| Parameter | Type | Meaning |
|---|---|---|
|
|
|
Where to send it |
|
|
|
The body; a record or a map is sent as JSON |
Returns whether the browser accepted the send. Where: anywhere, usually a handler. See Send a message as the page unloads.
beacon("/analytics", { event: "checkout", value: total })
broadcast
Opens a channel that every tab and window of the site on this browser hears.
Signature: channel name = broadcast(channelName) { on message(m) { … } }
| Parameter | Type | Meaning |
|---|---|---|
|
|
|
The channel; tabs that open the same name hear each other |
Returns a channel handle with .post(value), .messages, .last(kind), .state and .close(). Where: only after channel name =, in a page, a component or a store. The channel closes when its scope leaves. See Talk to the site's other tabs.
channel cart = broadcast("cart") { on message(m) { Cart.merge(m) } }
every
Runs a block repeatedly until its scope leaves.
Signature: every(interval) { statements }
| Parameter | Type | Meaning |
|---|---|---|
|
|
|
The time between runs |
Returns nothing. Where: a render block. The timer stops when its page, branch or list item leaves. See Timers.
every(1000) { elapsed = elapsed + 1 }
format
Writes a number, a date or money as text, in the reader's locale.
Signature: format(value), format(value, .style), format(value, .style, option), format(value, "pattern") → String
| Parameter | Type | Meaning |
|---|---|---|
|
|
|
What to write |
|
|
|
How to write it |
|
|
depends on the style |
Places for |
|
|
|
A date pattern of |
Returns the text. The locale is the i18n locale when the project has one, and the document's language otherwise; a change of locale redraws it. A Money value needs no style. In a string, {value:.style(option)} is the same call. Where: anywhere. See format and ago.
Text(format(price, .currency, "EUR"))
http
The built-in service for a request no api describes: the same engine an api uses — retries, caching and cancelling come with it — and an answer that is a result, never a throw.
Signature: http.get(url, options) → a promise of T!; http.post, http.put, http.patch and http.delete take the same
| Parameter | Type | Meaning |
|---|---|---|
|
|
|
The address; a value spliced into it is encoded |
|
|
|
What is sent; a record or a map is sent as JSON |
|
|
|
Headers of this request |
|
|
|
How the answer is read; |
|
|
as on an |
This request's own |
T is named where the answer goes — let rows: [Row] = try await http.get(url), let got: [Row]! = await http.get(url), resource rows: [Row] = http.get(url); a get with nowhere that says is N11. The error is an HttpError. Where: await in an action or a handler, or as a resource, which adds refresh:, placeholder: and the other options of a resource. fetch is gone (N08); window.fetch is the browser's own, untouched. See Ask on demand with http.
let rows: [Row] = try await http.get("/api/rows?page={page}")
keyIs
Whether a key event is a given combination — for a table of shortcuts held as data.
Signature: keyIs(event, combination) → Bool
| Parameter | Type | Meaning |
|---|---|---|
|
|
a key event |
The event a |
|
|
|
Modifiers and a key, as |
Returns true when the event is that combination. mod is ⌘ on a Mac and Ctrl elsewhere. Where: handlers. See Keys.
Input(bind: draft, label: "Note") { on keydown(e) { if keyIs(e, "mod+s") { save() } } }
keyLabel
A combination as this system writes it, for a menu or a tooltip.
Signature: keyLabel(combination) → String
| Parameter | Type | Meaning |
|---|---|---|
|
|
|
As |
Returns ⇧⌘P on a Mac and Ctrl+Shift+P elsewhere for "mod+shift+p". Where: anywhere. A Menu.Item's or a Tooltip's shortcut: is written this way for you.
Text("Search: {keyLabel("mod+k")}").muted
log
Prints a value to the browser's console.
Signature: log(value)
| Parameter | Type | Meaning |
|---|---|---|
|
|
any value but a |
The value to print. For several, splice them into one string, |
Returns nothing. Where: actions, handlers, effects and timers. A Secret passed to it is a T12.
log("saved {items.length} items")
navigate
Moves to a route, as a click on a Link would.
Signature: navigate(path)
| Parameter | Type | Meaning |
|---|---|---|
|
|
|
A site-relative path; a value spliced into it is encoded |
Returns nothing. In a single-page build the router draws the new page; in a static build it loads the page's own HTML file. A literal path no page matches is an R01, and a scheme a browser would run is refused. Where: actions and handlers. See Links and navigation.
Button("Open") { on click { navigate("/orders/{order.id}") } }
optimistic
Shows a change at once, before the server agrees. If anything later in the action fails — a try passing its error up, or a throw — the change is taken back.
Signature: optimistic(holder, change)
| Parameter | Type | Meaning |
|---|---|---|
|
|
a state, or a store's state | What to change |
|
|
a lambda from the old value to the new one | The change to show |
Returns a handle with rollback(). Where: actions. See Show a change before the server agrees.
optimistic(Todos.items, items => items.filter(i => i.id != id))
replayAnimation
Plays again an animation the element already has, such as its enter animation.
Signature: replayAnimation(element, name)
| Parameter | Type | Meaning |
|---|---|---|
|
|
an element, such as |
The element to animate |
|
|
|
The animation, such as |
Returns nothing. Where: handlers. See Motion.
Card.outlined.fadeIn { on mouseenter(e) { replayAnimation(e.currentTarget, "fadeIn") } }
rtc
Opens a WebRTC data channel straight to another reader's page.
Signature: peer name = rtc(signal: send, initiator: Bool, ice: [servers]) { send T receive T on message(m) { … } }
| Option | Type | Meaning |
|---|---|---|
|
|
a lambda, required | How what this side must tell the other reaches it |
|
|
|
Whether this side makes the offer; one side must |
|
|
|
The servers that help readers on different networks connect; none by default |
Returns a peer handle with .send(value), .signal(message) (hand it what the other side sent), .state, .messages and .close(). Where: only after peer name =. See Connect two readers' pages.
peer link = rtc(signal: m => lobby.post(m), initiator: query.host == "1") { receive Wave on message(m) { heard = m.text } }
sanitize
Passes markup through an allow-list of elements and attributes, for Unsafe.Html.
Signature: sanitize(html) → String
| Parameter | Type | Meaning |
|---|---|---|
|
|
|
Markup from outside the project |
Returns the markup without scripts, styles, frames, forms, on* attributes, or an href or src a browser would run. It runs at build time and in the browser from the same list. Where: anywhere. See Show markup you did not write.
Unsafe.Html(sanitize(post.body))
setLocale
Switches the page to another locale, and its direction with it.
Signature: setLocale(locale)
| Parameter | Type | Meaning |
|---|---|---|
|
|
|
A locale |
Returns nothing. Every t(…), format and ago redraws, and an RTL locale sets dir="rtl". A literal locale the config does not list is an I04. Where: actions, handlers and effects. See i18n.
Button("العربية") { on click { setLocale("ar") } }
setTheme
Switches between the light theme, the dark one, and whatever the system asks for, and keeps the choice across visits.
Signature: setTheme(choice)
| Parameter | Type | Meaning |
|---|---|---|
|
|
|
|
Returns nothing. The browser value theme reads the choice. Any other number of arguments is a T10. Where: actions and handlers. See Dark mode.
Button("Dark") { on click { setTheme("dark") } }
spawn
Starts a script of public/ in a worker beside the page.
Signature: worker name = spawn(path, restart: n, timeout: ms, type: .module) { receive T on message(m) { … } }
| Parameter | Type | Meaning |
|---|---|---|
|
|
|
The script's site-relative address; a missing file is a |
|
|
|
How many times a crash starts it again |
|
|
|
How long a request waits, in milliseconds (10 s unset) |
|
|
|
Starts a module worker |
Returns a worker handle with .request(method, params, options), .send(value), .last(kind), .pending, .state and .restart(). Where: only after worker name =, in a page, a component or a store. See Run a script in a worker.
worker css = spawn("/workers/css.js", restart: 1) { receive CssMessage on message(m) { problems = m.items } }
sse
Opens a stream of server-sent events, which resumes where it was after a drop.
Signature: stream name = sse(url, events: [names])
| Parameter | Type | Meaning |
|---|---|---|
|
|
|
The stream's address |
|
|
|
The named events to listen for |
Returns a stream handle with .messages, .last(kind), .state, .error and .close(). Where: only after stream name =. See Listen to server-sent events.
stream ticks = sse("/events", events: ["price", "status"])
t
A translation of a key, in the reader's locale.
Signature: t(key), t(key, values) → String
| Parameter | Type | Meaning |
|---|---|---|
|
|
|
A key of the translation files |
|
|
a map, optional |
Values for the message's |
Returns the message. A literal key no locale has is an I01; a value the message does not use, or a placeholder the call does not pass, is an I02. Where: anywhere. See t("key").
Text(t("cart.items", { count: Cart.count }))
toast
Shows a short message above everything, a modal included, and says it to a screen reader.
Signature: toast(message, tone: …, duration: …, action: …, onAction: …, closable: Bool); toast.promise(promise, loading: …, done: …, failed: …)
| Parameter | Type | Meaning |
|---|---|---|
|
|
|
What it says |
|
|
|
Its colour and icon |
|
|
|
How long it stays |
|
|
|
A button on it, and what pressing it runs |
|
|
|
Whether it has a close button |
Returns a handle with close() and update(…). It waits while the pointer is on it or the focus is in it, and no more than three show at once (a fourth closes the oldest). toast.promise shows loading: while the promise runs, then done: or failed:. Where: actions and handlers.
toast("Conversation archived", action: "Undo", onAction: restore)
uuid
A fresh random identifier.
Signature: uuid() → Uuid
It takes no parameters. Where: anywhere, usually an action that makes a record.
items = items.concat([Todo(id: uuid(), title: draft)])
ws
Opens a WebSocket, which reconnects with backoff and keeps itself alive.
Signature: socket name = ws(url, protocols: [names], heartbeat: duration) { send T receive T on message(m) { … } }
| Parameter | Type | Meaning |
|---|---|---|
|
|
|
A |
|
|
|
The subprotocols to offer |
|
|
|
How often to ping a quiet line |
Returns a socket handle with .send(value), .messages, .last(kind), .state, .error, .closure and .close(). send T is what .send takes and receive T what .messages holds and on message(m) is given; a socket, stream, channel, peer or worker that declares neither sends and hears Json, which is matched or decoded rather than read as a record (T28). Where: only after socket name =. See Open a socket.
socket chat = ws("wss://example.com/chat", heartbeat: 20.seconds) { send Outgoing receive Incoming on message(m) { Feed.add(m) } }
Browser values
The language keeps these values current and lets every page, component and store read them. Each is a name the language owns: declaring a state, prop or parameter with one of these names is an E118.
| Value | Holds |
|---|---|
| The window's size and breakpoints | |
| The address's query string | |
| The address's fragment | |
| The reader's light or dark choice | |
| The current moment | |
| The connection's state | |
| A new version of an offline site | |
| The reader's language and its direction | |
| The route's parameters |
viewport
The window's size, and which breakpoints it is past.
| Field | Type | Meaning |
|---|---|---|
|
|
|
The size in CSS pixels |
|
|
|
Whether the width is at least that breakpoint's token |
It follows matchMedia, so a breakpoint field changes once when its answer changes, not on every pixel of a resize.
if viewport.md { Sidebar { Sidebar.Item(to: "/", icon: "home") { Text("Home") } } }
query
The address's query string, a [String: String] from each key to its value.
A key the address lacks reads as null, so query.tab ?? "all" gives a default.
Text("Showing {query.tab ?? "all"}")
hash
The address's fragment, without the #. It is "" when there is none.
if hash == "pricing" { Text("You followed a link to pricing.") }
theme
The reader's choice: "light", "dark" or "system". setTheme changes it.
Button("Light", outlined: theme != "light") { on click { setTheme("light") } }
now
The current moment, as a DateTime that keeps itself current — every minute by default.
Signature: now, now(every: interval) → DateTime
Read it where it is shown or in a derived value. A state takes it once, so state opened = now keeps the moment the page opened (X06). See now.
Text("It is {now(every: 1.seconds).time()}")
network
The state of the reader's connection.
| Field | Type | Meaning |
|---|---|---|
|
|
|
Whether the browser has a connection |
|
|
|
|
|
|
|
Whether the reader asked to save data |
|
|
|
The estimated bandwidth, in megabits a second |
|
|
|
Writes waiting for the connection, with |
if !network.online { Alert("You are offline — changes are queued.").warning }
update
A new version of a site that has offline in its config.
| Field | Type | Meaning |
|---|---|---|
|
|
|
Whether a new version has installed and is waiting |
|
|
— | Takes the new version and reloads the page once |
if update.available { Button("Reload for the new version") { on click { update.apply() } } }
locale and dir
The reader's current locale ("en", "ar") and its direction ("ltr" or "rtl"). Both follow setLocale.
Text("Reading in {locale}, {dir}")
params
The current route's parameters, by name. A page also receives each one as a typed parameter of its own, which is usually the better way to read it.
Text("Order {params.id}")
String methods
A string has the browser's methods and five of WebFluent's own. A method it has neither of is a T16, with the nearest one it has.
WebFluent's own:
| Method | Returns |
|---|---|
|
|
The text with its first letter in upper case |
|
|
The first |
|
|
The text without the indentation its lines share, and without blank first and last lines |
|
|
A list of its lines, however they end |
|
|
A list of its words, split on runs of whitespace |
The browser's: length, trim(), trimStart(), trimEnd(), toLowerCase(), toUpperCase(), toLocaleLowerCase(), toLocaleUpperCase(), includes(s), startsWith(s), endsWith(s), indexOf(s), lastIndexOf(s), search(re), slice(a, b), substring(a, b), substr(a, n), charAt(i), charCodeAt(i), codePointAt(i), at(i), replace(a, b), replaceAll(a, b), split(sep), match(re), matchAll(re), concat(s), padStart(n, c), padEnd(n, c), repeat(n), normalize(), localeCompare(other), isWellFormed(), toWellFormed(), toString(), valueOf().
contains(s) is accepted for includes(s), and toUpper() and toLower() for toUpperCase() and toLowerCase().
derived preview = post.body.dedent().lines().first() ?? ""
List methods
A list has the browser's array methods and eight of WebFluent's own.
WebFluent's own:
| Method | Returns |
|---|---|
|
|
A sorted copy, ordered by what |
|
|
A map from what |
|
|
A copy without repeats; records are compared by their contents |
|
|
The first |
|
|
The first or last item, or |
|
|
The total of a list of numbers |
|
|
The list without the item at index |
The browser's: length, map(f), filter(f), find(f), findIndex(f), findLast(f), findLastIndex(f), some(f), every(f), includes(x), indexOf(x), lastIndexOf(x), join(sep), slice(a, b), concat(other), reverse(), sort(f), reduce(f, init), reduceRight(f, init), forEach(f), flat(), flatMap(f), fill(x), copyWithin(t, a, b), entries(), keys(), values(), at(i), with(i, x), toReversed(), toSorted(f), toSpliced(…), toString(), toLocaleString(); and, in an action or a handler, push(x), pop(), shift(), unshift(x) and splice(i, n). contains(x) is accepted for includes(x).
How the methods treat a state:
sortandreverseread in an expression work on a copy, so reading a sorted list never changes it.push(x),remove(i)andsort(f)as a statement give the state a new list, so whatever reads it repaints and apersistwrites it.
derived leaders = players.sortBy(p => -p.score).take(3)
Every one of WebFluent's own helpers also runs at build time, so the pre-rendered page shows its result. A member something declares wins over a helper of its name: a store's own action first(n: Number) or action preview(path: String) is the store's, called with its arguments, and a worker's css.last(kind) is the worker's.
Number methods
toFixed(n), toPrecision(n), toExponential(n), toLocaleString(), toString(), valueOf().
To convert, use Number("12") and String(n), or "{n}". To round, use Math.round, Math.floor, Math.ceil, Math.max and the rest of Math. For text a reader sees, prefer format.
derived share = (part / whole * 100).toFixed(1)
The built-in types
Eleven types come with the language. Each is a plain JSON value at run time.
| Type | Written | Methods and fields |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
the above, |
|
|
|
|
|
|
|
|
|
|
a string |
|
|
|
a string |
|
|
|
|
|
|
|
|
a string's |
|
|
from |
|
|
|
— | none: it may not be shown, spliced, logged or persisted |
.plus and .minus take years, months, weeks, days, hours, minutes, seconds and ms. A duration is written with ms, seconds, minutes, hours, days or weeks. What the language computes is a call (due.year()); what the value already carries is a field (price.amount). Types has the rest.
derived checkout = arrival.plus(days: nights)
Browser globals
The browser's names compile to themselves, with no prefix, and a table of the browser's types says what each is: window, document, console, localStorage, sessionStorage, JSON, Math, Date (Date.now()), Object (Object.keys), Array (Array.isArray), Number (Number.isInteger, …), navigator and its clipboard, location, history, performance, screen, Infinity, NaN, undefined, and the functions setTimeout, setInterval, clearTimeout, clearInterval, requestAnimationFrame, cancelAnimationFrame, queueMicrotask, structuredClone, matchMedia, getComputedStyle, parseInt, parseFloat, isNaN, isFinite, encodeURIComponent, decodeURIComponent, encodeURI, decodeURI, atob, btoa, alert, confirm and prompt. JSON.parse hands back Json; getItem a String?; an element's getBoundingClientRect() a Rect.
A handler's event, an element a ref: names and the value catch binds are typed by the same table: a KeyboardEvent, an Element, an Error. A global or a member it does not list — crypto, navigator.bluetooth, e.kye — is T30, with the nearest name; reach it from a project script whose JSDoc says its types. A name the program declares itself wins over a global, and unlike the language's own names, a global may be the name of a state, a prop or a parameter.
localStorage.setItem("last-seen", "{now.date()}")