lily/event
Events are how the DOM talks back to your update function. You pipe a
binder onto the Component the event
belongs to, hand it a function from the event’s payload to one of your
messages, and Lily dispatches that message when the event fires inside the
component.
Giving each common event a typed helper with one payload shape makes the usual case a single line:
component.dynamic(slice: ..., render: ...)
|> event.on_input(handler: Search)
Events that report data hand your function their payload and always
dispatch: on_input and on_change the value,
on_check the checked state, on_submit a
form’s fields, on_files the picked files,
on_paste and on_drop a
DataTransfer, on_media a player’s
MediaState, on_resize the component’s
size and on_visible whether it is on screen.
Fixed-message binders such as on_click,
on_double_click and on_focus_in
take the message itself.
on_key_down and on_key_up return a
Result, since most keys aren’t for you, and Error(Nil) skips one.
Frequent events, the on_pointer_* binders with a
PointerEvent, on_wheel and
on_scroll, always dispatch, pipe throttle
after them.
For anything else there is on, which takes the event’s name and a
gleam/dynamic/decode decoder that reads the browser’s own event object.
Any package can use it for events of its own, a CustomEvent included:
event.on(
component,
event: "lily-markdown-change",
decoder: decode.at(["detail", "value"], decode.string)
|> decode.map(EditorChanged),
)
Three decoders read what only Lily knows. from_element
runs a decoder on the element the binding matched,
data_attribute reads one of its data-* attributes
and form_fields reads the fields of its form. A decoder
that can fail decodes to a type of your own and the message comes from
mapping it, meaning a bad event is skipped rather than dispatched. The
first time that happens for a binding, Lily logs why.
A binding fires for events inside the component it is piped onto, meaning a
component should get the narrowest scope that works. Pipe
bind_to after the binder for a listener that belongs to the
page instead, a document keydown, a window resize, or something outside
the component. The other modifiers, debounce,
throttle, once,
prevent_default,
stop_propagation and reset_form,
pipe the same way. Each one changes the listener piped just before it,
skipping a transition in between, and does nothing without one:
component.dynamic(slice: ..., render: ...)
|> event.on_input(handler: Search)
|> event.debounce(milliseconds: 200)
A few events don’t bubble, focus, blur, scroll, mouseenter,
mouseleave, pointerenter, pointerleave, toggle, load, error and
the media events. Lily still hears them, but a binding fires only for its
own component’s element or its direct child, and a bind_to
selector must match the target itself. To react to focus anywhere inside,
use on_focus_in.
Clicks on an element carrying data-lily-message need no binder at all.
encode_message turns a message into an attribute-safe
string, component.mount listens for clicks on
such elements and dispatches the message back:
html.button(
[attribute.data("lily-message", event.encode_message(SaveDraft))],
[html.text("Save")],
)
To validate a form submission with the
formal library, decode the submitted fields
with form_fields, add them to the form and call
form.run. Map the result to a message of your own, the error branch can
carry the whole Form(model) back so the view can render field errors.
A listener is scoped to the element of the component it is piped onto,
static and
fragment included.
Binders are dual-target. On the browser a binder registers a listener, on
the server it only records one, letting a shared view pipe them directly
and still render server-side.
Types
A file the user picked, pasted or dropped. handle is the browser’s own
File, for your FFI or a fetch library to read or upload.
pub type File {
File(
name: String,
size: Int,
mime_type: String,
handle: FileHandle,
)
}
Constructors
-
File( name: String, size: Int, mime_type: String, handle: FileHandle, )
The browser’s File object behind a File, passed as it is to
an FFI function of yours.
pub type FileHandle
A key press. key is what the key types, such as "Enter" or "a",
code the physical key, such as "KeyA", the same on every keyboard
layout.
repeat is set while a key is held down, and is_composing while an input
method is still composing a character, when Enter confirms it rather than
submitting.
pub type KeyEvent {
KeyEvent(
key: String,
code: String,
ctrl: Bool,
shift: Bool,
alt: Bool,
meta: Bool,
repeat: Bool,
is_composing: Bool,
)
}
Constructors
-
KeyEvent( key: String, code: String, ctrl: Bool, shift: Bool, alt: Bool, meta: Bool, repeat: Bool, is_composing: Bool, )
The state of an <audio> or <video> element when one of its events
fired. duration is 0.0 until it is known.
pub type MediaState {
MediaState(
current_time: Float,
duration: Float,
paused: Bool,
ended: Bool,
muted: Bool,
volume: Float,
playback_rate: Float,
)
}
Constructors
-
MediaState( current_time: Float, duration: Float, paused: Bool, ended: Bool, muted: Bool, volume: Float, playback_rate: Float, )
A pointer event, at x and y in the viewport. button is 0 for the
main button, 1 the middle and 2 the secondary. pointer_type is
"mouse", "pen" or "touch", and pointer_id tells apart the fingers of
a multi-touch gesture.
pub type PointerEvent {
PointerEvent(
x: Float,
y: Float,
button: Int,
pointer_id: Int,
pointer_type: String,
ctrl: Bool,
shift: Bool,
alt: Bool,
meta: Bool,
)
}
Constructors
-
PointerEvent( x: Float, y: Float, button: Int, pointer_id: Int, pointer_type: String, ctrl: Bool, shift: Bool, alt: Bool, meta: Bool, )
A wheel or trackpad scroll, in pixels. A trackpad pinch arrives with ctrl
set.
pub type WheelEvent {
WheelEvent(
delta_x: Float,
delta_y: Float,
ctrl: Bool,
shift: Bool,
alt: Bool,
meta: Bool,
)
}
Constructors
-
WheelEvent( delta_x: Float, delta_y: Float, ctrl: Bool, shift: Bool, alt: Bool, meta: Bool, )
Values
pub fn bind_to(
component: component.Component(model, message, html),
selector selector: String,
) -> component.Component(model, message, html)
Binds the listener to elements matching a CSS selector anywhere on the
page rather than its component, or to "document" or "window". Pipe it
after the binder it applies to.
event.on_key_down(component, handler: fn(key) { Ok(KeyPressed(key)) })
|> event.bind_to("document")
pub fn data_attribute(name: String) -> decode.Decoder(String)
Reads a data-* attribute of the element the binding matched, by its
kebab-case name, meaning data-card-id is data_attribute("card-id").
event.on(
component,
event: "dragstart",
decoder: event.data_attribute("card-id") |> decode.map(DragStarted),
)
pub fn debounce(
component: component.Component(model, message, html),
milliseconds milliseconds: Int,
) -> component.Component(model, message, html)
Waits for a pause before dispatching, for a search box or anything else that fires in bursts. Pipe it after the binder it applies to.
The message comes from the last event of the burst, read when it fired.
event.on_input(component, handler: Search)
|> event.debounce(milliseconds: 200)
pub fn decode_message(encoded: String) -> Result(message, Nil)
Recovers a message encoded by encode_message, or
Error(Nil) for any other string.
You rarely need it, component.mount already
does this for clicks. This one doesn’t check the store’s
schema, the mount’s decoding does.
pub fn dispatch_on(
component: component.Component(model, message, html),
event event: String,
) -> component.Component(model, message, html)
Dispatches the message in the closest data-lily-message around the event’s
target, for an event other than a click. Only one inside the component,
held to the store’s schema and at most 16 KiB, the
same as a click.
event.dispatch_on(component, event: "focusin")
pub fn encode_message(message: a) -> String
Serialises a message into a string for a data-lily-message attribute,
which component.mount dispatches when the
element is clicked.
html.button(
[attribute.data("lily-message", event.encode_message(SaveDraft))],
[html.text("Save")],
)
pub fn form_fields() -> decode.Decoder(List(#(String, String)))
Reads the fields of the form around the element the binding matched, as name and value pairs. Files are left out.
pub fn from_element(
decoder: decode.Decoder(a),
) -> decode.Decoder(a)
Runs a decoder on the element the binding matched rather than on the event,
to read a property such as value.
Under bind_to that’s the closest match to the event’s
target, otherwise the target itself.
event.from_element(decode.at(["value"], decode.string))
pub fn on(
component: component.Component(model, message, html),
event event: String,
decoder decoder: decode.Decoder(message),
) -> component.Component(model, message, html)
Binds an event by name, reading the browser’s event object with a decoder. An event the decoder fails on is skipped, and the reason is logged once.
Prefer a helper such as on_input where one fits.
Non-bubbling events such as focus or scroll fire only for the
component’s own element, and a bind_to selector must match
the target itself.
event.on(
component,
event: "toggle",
decoder: decode.at(["newState"], decode.string)
|> decode.map(Toggled),
)
pub fn on_blur(
component: component.Component(model, message, html),
message message: message,
) -> component.Component(model, message, html)
Dispatches a fixed message when the element loses focus, not when its children do.
pub fn on_change(
component: component.Component(model, message, html),
handler handler: fn(String) -> message,
) -> component.Component(model, message, html)
Dispatches a message built from the target’s value when it is committed, on blur or Enter for a text field.
pub fn on_check(
component: component.Component(model, message, html),
handler handler: fn(Bool) -> message,
) -> component.Component(model, message, html)
Dispatches a message built from the target’s checked state when a checkbox or radio changes.
pub fn on_click(
component: component.Component(model, message, html),
message message: message,
) -> component.Component(model, message, html)
Dispatches a fixed message when the component is clicked.
component.static(fn(_) { save_button() })
|> event.on_click(message: Save)
pub fn on_context_menu(
component: component.Component(model, message, html),
handler handler: fn(PointerEvent) -> message,
) -> component.Component(model, message, html)
Dispatches a message built from the pointer on a right-click or a long
press. Pipe prevent_default after it to replace the
browser’s menu with your own.
pub fn on_copy(
component: component.Component(model, message, html),
message message: message,
) -> component.Component(model, message, html)
Dispatches a fixed message when the user copies from inside the component.
pub fn on_cut(
component: component.Component(model, message, html),
message message: message,
) -> component.Component(model, message, html)
Dispatches a fixed message when the user cuts from inside the component.
pub fn on_double_click(
component: component.Component(model, message, html),
message message: message,
) -> component.Component(model, message, html)
Dispatches a fixed message on a double click.
pub fn on_drag_end(
component: component.Component(model, message, html),
message message: message,
) -> component.Component(model, message, html)
Dispatches a fixed message when a drag started here ends, dropped or cancelled.
pub fn on_drag_enter(
component: component.Component(model, message, html),
message message: message,
) -> component.Component(model, message, html)
Dispatches a fixed message when a drag enters the component, for highlighting a drop zone.
pub fn on_drag_leave(
component: component.Component(model, message, html),
message message: message,
) -> component.Component(model, message, html)
Dispatches a fixed message when a drag leaves the component.
pub fn on_drag_over(
component: component.Component(model, message, html),
handler handler: fn(PointerEvent) -> message,
) -> component.Component(model, message, html)
pub fn on_drag_start(
component: component.Component(model, message, html),
message message: message,
) -> component.Component(model, message, html)
Dispatches a fixed message when the user starts dragging the element. Give
it draggable="true" in your markup.
pub fn on_drop(
component: component.Component(model, message, html),
handler handler: fn(DataTransfer) -> message,
) -> component.Component(model, message, html)
Dispatches a message built from what was dropped on the component, accepting the drop and stopping the browser from opening a dropped file.
event.on_drop(component, handler: fn(transfer) {
FilesDropped(transfer.files)
})
pub fn on_files(
component: component.Component(model, message, html),
handler handler: fn(List(File)) -> message,
) -> component.Component(model, message, html)
Dispatches a message built from the files picked in an
<input type="file">.
pub fn on_focus(
component: component.Component(model, message, html),
message message: message,
) -> component.Component(model, message, html)
Dispatches a fixed message when the element gains focus, not when its
children do, see on_focus_in.
pub fn on_focus_in(
component: component.Component(model, message, html),
message message: message,
) -> component.Component(model, message, html)
Dispatches a fixed message when focus moves to the component or anything inside it.
pub fn on_focus_out(
component: component.Component(model, message, html),
message message: message,
) -> component.Component(model, message, html)
Dispatches a fixed message when focus leaves the component or anything inside it.
pub fn on_input(
component: component.Component(model, message, html),
handler handler: fn(String) -> message,
) -> component.Component(model, message, html)
Dispatches a message built from the target’s value on every keystroke.
Pipe debounce after it to wait for a pause in typing.
pub fn on_key_down(
component: component.Component(model, message, html),
handler handler: fn(KeyEvent) -> Result(message, Nil),
) -> component.Component(model, message, html)
Dispatches a message built from a key press, with the key and its
modifiers. Return Error(Nil) for keys you don’t handle.
event.on_key_down(component, handler: fn(key) {
case key {
event.KeyEvent(key: "k", meta: True, ..)
| event.KeyEvent(key: "k", ctrl: True, ..) -> Ok(OpenSearch)
_ -> Error(Nil)
}
})
|> event.bind_to("document")
|> event.prevent_default
pub fn on_key_up(
component: component.Component(model, message, html),
handler handler: fn(KeyEvent) -> Result(message, Nil),
) -> component.Component(model, message, html)
Like on_key_down, for a key release.
pub fn on_media(
component: component.Component(model, message, html),
event event: String,
handler handler: fn(MediaState) -> message,
) -> component.Component(model, message, html)
Dispatches a message built from an <audio> or <video> element’s state
when event fires on it, such as "play", "pause", "ended" or
"timeupdate". Pipe it onto the component whose element is the player.
pub fn on_paste(
component: component.Component(model, message, html),
handler handler: fn(DataTransfer) -> message,
) -> component.Component(model, message, html)
Dispatches a message built from what the user pastes inside the component.
pub fn on_pointer_down(
component: component.Component(model, message, html),
handler handler: fn(PointerEvent) -> message,
) -> component.Component(model, message, html)
Dispatches a message built from the pointer when a button goes down.
pub fn on_pointer_enter(
component: component.Component(model, message, html),
handler handler: fn(PointerEvent) -> message,
) -> component.Component(model, message, html)
Dispatches a message built from the pointer as it enters the component’s element, not its children.
pub fn on_pointer_leave(
component: component.Component(model, message, html),
handler handler: fn(PointerEvent) -> message,
) -> component.Component(model, message, html)
Dispatches a message built from the pointer as it leaves the component’s element.
pub fn on_pointer_move(
component: component.Component(model, message, html),
handler handler: fn(PointerEvent) -> message,
) -> component.Component(model, message, html)
Dispatches a message built from the pointer as it moves.
pub fn on_pointer_up(
component: component.Component(model, message, html),
handler handler: fn(PointerEvent) -> message,
) -> component.Component(model, message, html)
Dispatches a message built from the pointer when a button is released.
pub fn on_resize(
component: component.Component(model, message, html),
handler handler: fn(#(Float, Float)) -> message,
) -> component.Component(model, message, html)
Dispatches a message built from the component’s width and height, once
when it mounts and whenever its size changes, for charts and panes that
lay themselves out. It always watches the component’s own element, a
bind_to piped after it doesn’t apply. For the window’s
size see browser.viewport.
pub fn on_scroll(
component: component.Component(model, message, html),
handler handler: fn(#(Int, Int)) -> message,
) -> component.Component(model, message, html)
Dispatches a message built from the scroll position, as rounded scrollTop
and scrollLeft of the element that scrolled.
pub fn on_submit(
component: component.Component(model, message, html),
handler handler: fn(List(#(String, String))) -> message,
) -> component.Component(model, message, html)
Dispatches a message built from a form’s fields when it is submitted, always preventing the browser’s own submit.
Pipe reset_form after it to clear the form afterwards.
event.on_submit(component, handler: SubmitRoom)
|> event.reset_form
pub fn on_visible(
component: component.Component(model, message, html),
handler handler: fn(Bool) -> message,
) -> component.Component(model, message, html)
Dispatches a message built from whether the component is on screen, once
when it mounts and whenever that changes, for loading the next page when a
list’s last row shows, lazy content or marking something as seen. Like
on_resize it watches the component’s own element.
event.on_visible(component, handler: fn(visible) {
case visible {
True -> LoadNextPage
False -> Ignored
}
})
pub fn on_wheel(
component: component.Component(model, message, html),
handler handler: fn(WheelEvent) -> message,
) -> component.Component(model, message, html)
Dispatches a message built from a wheel or trackpad scroll. Pipe
prevent_default after it to zoom or pan instead of
scrolling the page.
pub fn once(
component: component.Component(model, message, html),
) -> component.Component(model, message, html)
Fires only for the first event, for a one-off such as a first interaction hint. Pipe it after the binder it applies to.
event.on_click(component, message: DismissHint) |> event.once
pub fn prevent_default(
component: component.Component(model, message, html),
) -> component.Component(model, message, html)
Calls the browser’s preventDefault on events the binder dispatches a
message for, for a link or key the page handles itself. Pipe it after the
binder it applies to.
on_submit already does this.
event.on_click(component, message: OpenRow) |> event.prevent_default
pub fn reset_form(
component: component.Component(model, message, html),
) -> component.Component(model, message, html)
Resets the form around the matched element once the message is dispatched, for a form that starts empty again. Pipe it after the binder it applies to.
event.on_submit(component, handler: SendMessage) |> event.reset_form
pub fn stop_propagation(
component: component.Component(model, message, html),
) -> component.Component(model, message, html)
Calls the browser’s stopPropagation and stops Lily running bindings
further out for the same event. Pipe it after the binder it applies to.
event.on_click(component, message: Delete) |> event.stop_propagation
pub fn throttle(
component: component.Component(model, message, html),
milliseconds milliseconds: Int,
) -> component.Component(model, message, html)
Allows one dispatch per interval and drops the events in between, for a scroll or pointer move. Pipe it after the binder it applies to.
event.on_scroll(component, handler: Scrolled)
|> event.throttle(milliseconds: 100)