Tutorial
The language
Events
Handlers on elements, keyboard shortcuts, the events components fire, the overlays a page opens, and drag and drop.
This chapter covers events in WebFluent. An event handler is the code that runs when something happens: a click, a key, a drop, a component saying it changed. You write it as on <event> { … } inside the block of the element it listens to, and its body can change state, call actions and navigate.
In this chapter:
- handlers and the event object
- keys, and shortcuts for a whole app
- the events your own components fire
- overlays: modals, sheets, toasts, menus, popovers and tooltips, what closes them, and how they stack
- gestures: drag and drop, long-press, swipe and the splitter
- listening to the window and the document
Handlers
A handler is written inside an element's block: on <event> { … }, or on <event>(name) { … } when the body reads the event object. This page counts clicks and logs what happens in a text field:
page Clicks(path: "/", title: "Clicks", description: "Handlers on a button and a field.") {
state n = 0
state last = ""
Heading("Clicks").h1
Button("+1") { on click { n = n + 1 } }
Input(bind: last, placeholder: "Type here") {
on input { log(last) }
on keydown(e) { if e.key == "Enter" { log("submitted {last}") } }
on focus { log("in") }
on blur { log("out") }
}
Text("{n}")
}
A handler may name any DOM event. The common ones are click, input, change, submit, focus, blur, keydown, keyup, mouseenter and mouseleave. The rest — dblclick, contextmenu, pointerdown, pointermove, touchstart, wheel, scroll, paste, drop, dragover, animationend, ended and the others — work the same way. The components reference lists every one. On a call of your own component, the events it declares (Components) join them.
A handler's body is an imperative block, so it may assign state, call actions, await and navigate.
Note
Coming from React or Svelte? A handler is not a prop: there is no onClick={…} and no on:click={…}. Write on click { … } inside the element's block. onclick: as an argument is an inline handler, and the compiler refuses it (E106). See Coming from React.
A handler on a component call — UserCard("Sam") { on click { … } } — attaches to the component's root element, so a styled button component is clickable wherever it is used.
The event object
To read the event, name a parameter: on keydown(e) { … }. It is the browser's own event object, typed by the event: on keydown(e) is a KeyboardEvent (e.key, e.shiftKey), on click(e) a MouseEvent (e.clientX), and e.target an Element (e.target.value), with e.preventDefault() and e.stopPropagation() on every one. A member the event does not have, e.kye, is T30, with the nearest name.
Without a parameter, the event is still in scope as event — unless the program has an event of its own (a loop's item, a state, an action), which wins. Name the parameter to read the event there.
A DOM event sends one value, the event, so a handler names one name at most: on click(e, x) is an error (T22). Read what you want from the event, e.clientX. Several names are for a component's own events, which send what they declare (below).
This drop zone uses the event object twice — to allow the drop, and to read the dropped files:
page Drop(path: "/", title: "Drop", description: "A place to drop files.") {
state names: [String] = []
Heading("Drop files here").h1
Card {
on dragover(e) { e.preventDefault() }
on drop(e) {
e.preventDefault()
names = (e.dataTransfer?.files ?? []).map(f => f.name)
}
Text(if names.length == 0 { "Nothing yet" } else { names.join(", ") })
}
}
How often a handler runs
An event can come far more often than its handler needs to run: a key per letter, a scroll per pixel. Say how often in the handler's parentheses:
page Reader(path: "/", title: "Reader", description: "A search box and a long page.") {
state typed = ""
state q = ""
state read = 0
state loads = 0
Heading("Reader").h1
Input(bind: typed, label: "Search") {
on input(debounce: 300.ms) { q = typed }
}
Stack {
style { height: 300px; overflow-y: auto }
on scroll(e, throttle: 100.ms) { read = e.target.scrollTop }
Stack { style { height: 2000px; flex-shrink: 0 } Text("A long article") }
}
Text("Searching for {q}, scrolled {read}px")
Text("End of the list") { on visible { loads = loads + 1 } }
}
debounce: 300.msruns the handler once the events have stopped coming for that long, with the last of them: a search asked when the reader stops typing.throttle: 100.msruns it at once, then at most once in that long, and once more where the events stopped: a scroll position followed without running on every pixel.- A wait still pending when the page, branch or item leaves is dropped.
on visibleruns each time the element comes into view: scrolled to, or drawn where the reader is looking. A "load more" row is an element withon visible { feed.loadMore() }at the end of the list.
Keys
on key("…") answers to one key, with modifiers. On an element it fires while that element has focus; at the top of a page or component it fires anywhere on the page:
page Keys(path: "/", title: "Keys", description: "Keys on a field and on the page.") {
state open = false
state q = ""
Heading("Keys").h1
Input(bind: q, ref: box, placeholder: "Search") {
on key("Escape") { q = "" } // on the element: while it has focus
on key("Enter", e) { log(e.target.value) }
}
on key("mod+k") { box.focus() } // on the page: anywhere on the page
on key("?") { open = !open }
if open { Alert("Shortcuts: {keyLabel("mod+k")} to search, ? for this.").info }
}
How a combination is spelled:
- Modifiers are
mod,ctrl,shift,altandmeta(orcmd), joined with+.modis ⌘ on a Mac and Ctrl everywhere else, so one shortcut works on both; writectrlorcmdonly when you mean exactly that key. - Then comes the key as the browser names it:
k,Enter,Escape(oresc),Tab,ArrowDown(ordown),space,F2. on key("Enter", e)names the event too.
How it listens:
- On an element, the handler listens on that element.
- At the top of a page or component, it listens on the document for as long as the page shows.
- Every modifier must match exactly, so
ctrl+kdoes not fire onctrl+shift+k.
A combination no keyboard sends — an unknown modifier, no key — is an error (E117).
Shortcuts for an app
To give an app shortcuts that work on every page, write them with mod and declare them on app:
modis ⌘ on a Mac and Ctrl everywhere else.- On
app, a shortcut is heard on every page for as long as the app runs. - A chord is its steps with a space between:
mod+k mod+s. The second step must come within a second and a half of the first, and on its own it does not fire a shortcut of its own.
This app drives its shortcuts and its View menu from one table of commands:
store Commands {
state said = ""
state table: [Command] = [
{ id: "palette", keys: "mod+shift+p", title: "Commands" },
{ id: "sidebar", keys: "mod+b", title: "Toggle sidebar" },
]
action run(e: KeyboardEvent) {
for c in table {
if keyIs(e, c.keys) {
e.preventDefault()
said = c.id
}
}
}
}
type Command { id: String, keys: String, title: String }
app {
on key("mod+s") { Commands.said = "saved" }
on key("mod+k mod+s") { Commands.said = "shortcut help" }
on keydown(e) { Commands.run(e) }
Menu(trigger: "View") {
for c in Commands.table {
Menu.Item(shortcut: c.keys) { Text(c.title) }
}
}
Text("Commands: {keyLabel("mod+shift+p")}")
Router
}
The helpers and rules it relies on:
keyIs(e, "mod+s")is whether a key event is that combination — a chord's too — so one table of commands can drive the shortcuts, the menus and a palette.keyLabel("mod+shift+p")is how this system writes it:⇧⌘Pon a Mac,Ctrl+Shift+Pelsewhere. AMenu.Item's and aTooltip'sshortcut:are written the same way, and the item — or the tooltip's control — tells assistive technology witharia-keyshortcuts.- Events outside any element. A page, a component or
appmay handlekeydownandkeyup, and the window'sresize,scroll,hashchange,popstate,online,offline,message,storageandvisibilitychange, and the window losing and gaining focus (blur,focus— an editor saves on leaving, for example). Each listens for as long as its owner shows. - A letter is also the key in its place. On a Mac
⌥⌘Psendsπ, andmod+alt+pstill matches it.
Moving through a group with the arrow keys
A tab strip, a toolbar or a row of choices is one stop for Tab: Tab enters it and leaves it, and the arrow keys move inside it. Tabs and Menu work that way already. roving: gives any element of yours the same:
page Editor(path: "/", title: "Editor", description: "Format the text.") {
state bold = false
state italic = false
Heading("Editor").h1
Row(roving: .x, role: "toolbar", aria-label: "Format") {
Button("Bold", aria-pressed: bold) { on click { bold = !bold } }
Button("Italic", aria-pressed: italic) { on click { italic = !italic } }
}
}
roving: .xmoves with ArrowLeft and ArrowRight,.ywith ArrowUp and ArrowDown,.bothwith either.- Across a right-to-left page the next item is to the left, so ArrowLeft moves forward there.
- Home and End go to the ends, and a letter goes to the next item whose name starts with it.
- Tab enters at the chosen item, the one marked
aria-selected,aria-checkedoraria-pressed, or the first. A disabled item is passed over, and a key held with Alt, Ctrl or ⌘ is left to the browser.
For a key of your own that follows the direction of the text, write on key("inline-start") or on key("inline-end"): ArrowLeft and ArrowRight in a left-to-right box, the other way round in a right-to-left one.
Emitting events from components
A component declares the events it fires with event, and fires them with emit. The caller handles them like DOM events, with a name for each value the event sends — on change(v), on menu(key, x, y). Components covers the details. This counter tells its page every time it changes:
component Counter(_ start: Number) {
event change(value: Number)
state n = start
Row(gap: .sm) {
Button("−") { on click { n = n - 1 emit change(n) } }
Text("{n}")
Button("+") { on click { n = n + 1 emit change(n) } }
}
}
page Tally(path: "/", title: "Tally", description: "A component that reports its count.") {
state total = 0
Heading("Tally").h1
Counter(10) { on change(v) { total = v } }
Text("Now {total}")
}
Overlays: modals, dialogs, toasts and menus
An overlay is something a page opens over itself: a modal that asks a question, a toast that confirms, a menu of actions, a tooltip. Most are opened by a state, so the page decides when they show. This page has one of each:
page Overlays(path: "/", title: "Overlays", description: "What a page opens.") {
state confirm = false
state deleted = false
Heading("Overlays").h1
Button("Delete").danger { on click { confirm = true } }
Modal(visible: confirm, title: "Delete this?") {
Text("This cannot be undone.")
Modal.Footer {
Button("Cancel") { on click { confirm = false } }
Button("Delete").danger { on click { confirm = false deleted = true } }
}
}
if deleted { Toast("Deleted").success }
Menu(trigger: "More") {
Menu.Item { Text("Rename") }
Menu.Divider
Menu.Item { Text("Archive") }
}
Tooltip("Copies the link") { IconButton(icon: "copy", label: "Copy link") }
}
ModalandDialogare real<dialog>elements, open while theirvisible:state is true.- The browser traps focus and makes the rest of the page inert. Escape or a press on the backdrop closes it, and the state is set back to
false, so it never disagrees with what is on screen. - When it opens, the focus goes to what says
autofocus, else its first control; when it closes, the focus goes back to what had it. - It fades out before it goes, however it was closed.
on closeruns when it closes, however it was closed.title:is its heading, which names it (A08without one).Modal.Footeris the row of actions, and.closableadds a close button.Modallists the rest.Toastshows the moment it is rendered and leaves after three seconds. It is announced politely to screen readers. Put it under a condition that turns true, or calltoast(…)from a handler (below).MenuandDropdownopen a list from a button. Arrow keys move between items, Home and End jump to the ends, a letter jumps to the next item that starts with it, Enter and Space choose, Escape closes with focus back on the button, and a click outside closes it.Tooltipshows its text when its child is hovered or focused, and is linked to it witharia-describedby.
What closes an overlay, and where the focus goes
dismiss: says what closes a Modal, a Dialog, a Sheet or a Popover besides the page's own button: .any (Escape or a press outside, the default), .escape, or .none, for a form that must be answered. initialFocus: names, by its ref:, what takes the focus when it opens:
page Profile(path: "/", title: "Profile", description: "A modal that starts in a field.") {
state editing = false
state name = ""
Heading("Profile").h1
Button("Edit profile") { on click { editing = true } }
Modal(visible: editing, title: "Edit profile", dismiss: .escape, initialFocus: nameField) {
Input(bind: name, label: "Name", ref: nameField)
Modal.Footer { Button("Save").primary { on click { editing = false } } }
}
}
An AlertDialog asks before something that cannot be undone. A screen reader hears an alert dialog, read with its body; Escape answers it, and a press beside it does not. Put the answer that loses nothing first in its footer.
A Sheet is a modal that comes in from an edge: side: .bottom (the default), .start or .end, which swap in a right-to-left page. Dragged by its handle or heading toward that edge, past 30% of its size, it closes; a bottom sheet with snap: points opens at the first and settles at the nearest one it is let go near:
page Shop(path: "/", title: "Shop", description: "Filters in a bottom sheet.") {
state filters = false
state sort = "new"
Heading("Shop").h1
Button("Filters") { on click { filters = true } }
Sheet(visible: filters, title: "Filters", snap: [0.5, 1]).closable {
Radio(bind: sort, value: "new", label: "Newest")
Radio(bind: sort, value: "price", label: "Price")
Sheet.Footer { Button("Show results").primary { on click { filters = false } } }
}
}
On a narrow screen a Sidebar opens over the page as a drawer, which is a layer like these: the focus goes in and stays there, Escape or a press outside closes it, and the focus goes back to its toggle.
Toasts, questions and announcements from a handler
Three functions open an overlay from code rather than from state:
store Mail {
state archived: [String] = []
action archive(id: String) {
archived = archived.concat([id])
toast("Conversation archived", action: "Undo", onAction: restore)
}
action restore() { archived = archived.slice(0, -1) }
}
page Inbox(path: "/", title: "Inbox", description: "Toasts, a question, an announcement.") {
use Mail
state gone = false
Heading("Inbox").h1
Button("Archive") { on click { Mail.archive("m1") } }
Button("Delete everything").danger {
on click {
if await ask("Delete every message?", detail: "This cannot be undone.", yes: "Delete", danger: true) {
gone = true
announce("Every message deleted", .assertive)
}
}
}
if gone { Text("No messages.") }
}
toast(message, …)shows a toast above everything, a modal included, and says it to a screen reader. It takestone:(.success,.danger,.warning,.info),duration:in milliseconds, andaction:withonAction:for a button on it. It waits while the pointer is on it or the focus is in it, has a close button, and no more than three show at once.toast.promise(p, loading: …, done: …, failed: …)follows a promise.await ask(question, …)draws an alert dialog and istruefor yes,falsefor no or Escape. It takesdetail:,yes:,no:anddanger: true; the focus starts on no. (confirmis the browser's.)announce(text)says something to a screen reader with nothing on screen moving;announce(text, .assertive)interrupts, for what cannot wait.
A program that names something toast, ask or announce of its own keeps it; the function is then out of reach there.
Layers: popovers, menus and tooltips above everything
A Popover, a Menu's list and a Tooltip are drawn in the browser's top layer, above everything else on the page, so a box with overflow: hidden cannot clip them. Each is placed against its anchor, the element it belongs to, and flips or slides to stay on screen.
This page opens a popover at a button and a context menu at the pointer:
page Editor(path: "/", title: "Editor", description: "Layers at a control and at the pointer.") {
state branches = false
state asked = false
state point = { x: 0, y: 0 }
state said = ""
Heading("Editor").h1
Button("main", ref: branch) { on click { branches = !branches } }
Popover(visible: branches, anchor: branch, label: "Branches") {
on close(reason) { said = "closed by {reason}" }
Text("main")
Text("feature/layers")
}
Card {
on contextmenu(e) {
e.preventDefault()
point = { x: e.clientX, y: e.clientY }
asked = true
}
Text("Right-click for the context menu")
}
Menu(visible: asked, at: point) {
Menu.Item(shortcut: "F2") { Text("Rename") }
Menu.Divider
Menu.Item.danger { Text("Delete") }
}
Text(said)
}
Popoveris open while itsvisible:state is true, placed againstanchor:, an element'sref:. Escape or a press outside closes it (asdismiss:allows), setsvisible:back tofalse, andon close(reason)hears"escape"or"outside". Its anchor says what it opens and whether it is open (aria-controls,aria-expanded), the focus goes to its first control, andlabel:is its name (A18without one).Menuwithouttrigger:is a list that state opens, at ananchor:orat:a point. Choosing an item closes it.ContextMenudoes what the card above does by hand: what it wraps, and itsContextMenu.Itemsopened where a right-click or a long press happened — or, for a keyboard, at the focused element on the menu key or Shift+F10.ContextMenu { Text("Right-click here") ContextMenu.Items { Menu.Item { Text("Rename") } } }needs no state.HoverCardpreviews what a link points at —HoverCard { Link("@ada", to: "/u/ada") HoverCard.Content { … } }— after the pointer rests on it, or at once on focus;Tourwalks a reader through the page a step at a time, eachTour.Step(target:)lit through a cut-out in the dimmed page.Menubaris a desktop app's File, Edit and View:Menubar { Menubar.Menu("File") { Menu.Item(shortcut: "mod+n") { Text("New") } } }. It is one Tab stop; the arrow keys go along it, and with a menu open Left and Right open the one beside it.- The open layers form one stack, newest on top. Escape closes the newest layer that can be dismissed — a popover, a menu, an open
ModalorDialog— and nothing behind it hears that key. A modal opened from a popover takes the first Escape; the popover takes the next. - A tooltip keeps Escape only while focus is on its control. Otherwise the key goes on to the layer below, or to the element with focus.
- A layer takes the attributes and handlers any element takes —
role:,aria-*,ref:— on the element it draws. APopoveris adialogunless itsrole:says otherwise.
Every option of these — placement:, offset:, .arrow, a menu's checked:, disabled: and Menu.Sub, a tooltip's delay: and shortcut: — is listed under Popover, Menu and Tooltip. To ask before a destructive action, see Build a confirm dialog.
Gestures: drag, long-press, swipe and the splitter
The runtime turns what the pointer does over time into one event that says what it means. A mouse, a pen and a finger run the same code. A finger picks a drag up with a long press, so a plain swipe still scrolls the page.
This list reorders its items by drag and drop:
page Tabs(path: "/", title: "Tabs", description: "Drag to reorder.") {
state tabs = ["App.wf", "Home.wf", "Shell.wf"]
action move(what: String, near: String, position: String) {
let rest = tabs.filter((x) => x != what)
let at = rest.indexOf(near)
let i = if position == "after" { at + 1 } else { at }
tabs = [...rest.slice(0, i), what, ...rest.slice(i)]
}
Heading("Tabs").h1
Row {
for tab in tabs by tab {
Card(drag: tab, dragGroup: "tabs", dropAxis: .x) {
on receive(d) {
if let .string(what) = d.value { move(what, tab, d.position) }
}
Text(tab)
}
}
}
}
drag: valuepicks an element up: a mouse moved a few pixels, or a finger held still. Escape puts it back, and the click a drag ends with is not a click.on receive(d)takes a drop:d.valueis what was dropped — asJson, since any element may have carried it, so match it for the kind you dragged (if let .string(what) = d.value) — andd.positionis"before"or"after"alongdropAxis:(.y, down the page, unless you say.x), or"inside"on a target withdropInside: true.dragGroup:on a drag and its targets keeps groups apart, such as tabs and tree rows.on longpress(p)is half a second held still;on swipe(s)is a finger or a pen swept across, withs.direction.Splitter(bind: side, min: 160, max: 480, reset: 240, label: "Sidebar width")sizes the region beside it, by drag or by the arrow keys. A drag or a key starts from the region's size as it is drawn.
On every element lists the drag props and the gesture events in full, dropValue: and on dragmove(d) among them; Splitter lists its props.
On a call of your own component, the drag, the drop and the gestures apply to the one element it draws. A component whose body is an if, a for or several elements has no one element for them, and the build says so (C07): wrap what it draws in a Stack or a Row.
Important
A drag has no keyboard of its own. Give what it does a menu item or a command too (Move left, Move to…), as the platform's accessibility rules ask of every pointer action.
Listening outside the page's elements
A handler on an element hears that element. For the window, write the handler at the top of the page, a component or app, outside any element — resize, scroll, hashchange, popstate, online, offline, message, storage, visibilitychange, blur and focus are heard there (Shortcuts for an app). It listens for as long as its owner shows:
page Scrolled(path: "/", title: "Scrolled", description: "How far down the reader is.") {
state y = 0
on scroll { y = window.scrollY }
Heading("Scrolled").h1
Text("{y}px down")
}
For any other target or event, use an effect with a cleanup, which removes the listener when the page leaves. An action named without parentheses is the function itself, so you can hand it to the browser:
page Selection(path: "/", title: "Selection", description: "What the reader has selected.") {
state picked = ""
action track() { picked = document.getSelection()?.toString() ?? "" }
effect {
document.addEventListener("selectionchange", track)
cleanup { document.removeEventListener("selectionchange", track) }
}
Heading("Selection").h1
Text("Selected: {picked}")
}
For the viewport's size, the network and the URL, the language already keeps values current — viewport, network, query, hash — so no listener is needed (State).
Summary
| You write | It does | Section |
|---|---|---|
|
|
runs when the element fires the event | |
|
|
names the event object | |
|
|
runs once the events stop; at most once a while | |
|
|
runs when the element comes into view | |
|
|
answers to one key or combination | |
|
|
an app-wide shortcut, here a chord | |
|
|
test a key event; write a combination for this system | |
|
|
a component's own event | |
|
|
a dialog opened by state | |
|
|
layers placed at a control or a point | |
|
|
drag and drop | |
|
|
a held press; a sweep | |
|
|
a handle that sizes a region | |
|
|
a window event |
The components reference lists every event and prop of each built-in.
Common mistakes
Naming more values than a DOM event sends. A DOM event sends one value, the event, so a second name has nothing to hold:
page Spot(path: "/", title: "Spot", description: "Where the pointer clicked.") {
state at = ""
Heading("Spot").h1
Button("Click me") { on click(e, x) { at = "{x}" } }
Text(at)
}
Name the event alone and read from it: on click(e) { at = "{e.clientX}" } (T22).
A misspelled event. A handler for an event the element never fires never runs, so the compiler warns:
page Clicks(path: "/", title: "Clicks", description: "A misspelled event.") {
state n = 0
Heading("Clicks").h1
Button("+1") { on clik { n = n + 1 } }
Text("{n}")
}
Spell the event as the browser does, on click (V09).
A key combination no keyboard sends. Modifiers have fixed names, and a word that is not one stops the build:
page Search(path: "/", title: "Search", description: "A shortcut no keyboard sends.") {
state q = ""
Heading("Search").h1
Input(bind: q, ref: box, placeholder: "Search")
on key("command+k") { box.focus() }
}
Write cmd+k, or mod+k for ⌘ on a Mac and Ctrl elsewhere (E117).
What you learned
-
Handle a DOM event with
on click { }, and read the event withon keydown(e) { } -
Answer a key or a chord with
on key("mod+k"), on an element or for the whole app -
Fire your component's own events with
eventandemit -
Open modals, menus, popovers and tooltips from state, and know how they stack
-
Drag, drop, long-press, swipe and listen to the window