03 Text Inputs
We’ve seen the use of buttons to set up on_click events so far, but there’s other ways for us to handle inputs in Lily. As with last time, we’re going to re-use the generated project to create a trivial (and somewhat arbitrary) example that showcases various ways we can react to user text inputs. Begin with first by adding gleam_javascript to the project.
gleam add gleam_javascript
Then update our import list again:
import gleam/int
import gleam/javascript/promise
import lily/client
import lily/component.{type Component}
import lily/event.{type KeyEvent}
import lily/store
import lustre/attribute
import lustre/element.{type Element}
import lustre/element/html
Now let’s replace our Model and Message with the following:
pub type Model {
Model(
input: String,
settled_input: String,
last_key: String,
seconds: Int,
running: Bool,
)
}
pub type Message {
InputChanged(String)
InputSettled(String)
KeyPressed(KeyEvent)
Tick
SetRunning(Bool)
}
What we’re essentially going to do is to store the user input into a simple text input within input, and store the version when the input has stayed static for a certain while within settled_input. last_key will be the last key the user enters, whereas seconds and running will be a simple timer to show how you can asynchronously send messages out (in this case sending a Tick message every second). Our update function would then be fairly straightforward:
fn update(model: Model, message: Message) -> Model {
case message {
InputChanged(input) -> Model(..model, input: input)
InputSettled(input) -> Model(..model, settled_input: input)
KeyPressed(key) -> Model(..model, last_key: key.key)
Tick if model.running -> Model(..model, seconds: model.seconds + 1)
Tick -> model
SetRunning(running) -> Model(..model, running: running)
}
}
Let’s add our view function and more importantly, the text_input() within it:
fn view(_model: Model) -> Component(Model, Message, Element(Message)) {
component.fragment([text_input(), display(), clock_buttons()])
}
fn text_input() -> Component(Model, Message, Element(Message)) {
component.static(fn(_nest) {
html.input([attribute.placeholder("Input: ")])
})
|> event.on_input(handler: InputChanged)
|> event.on_input(handler: InputSettled)
|> event.debounce(milliseconds: 300)
|> event.on_key_down(handler: fn(key) { Ok(KeyPressed(key)) })
}
Here, we see our new event functions. We first have event.on_input that fires its handler whenever some form of input occurs. In most cases, this would typically be a message constructor, but it can also be any other function as long as it returns a message. This means that anytime the text is changed, it would immediately fire InputChanged(input). The handler: for on_input always takes a String, which should be the desired input. Now, we see that we’re piping another on_input event. You can attach multiple events onto a component, and any event modifiers, such as event.debounce here will attach to the last event added to the component. In this case, we’re debouncing the on_input event with the InputSettled message handler, allowing us to only fire InputSettled whenever the user input has settled onto a constant value for 300 milliseconds. The last event we add is an on_key_down event. Rather than sending a message, event.on_key_down expects a Result wrapping the message constructor. This is because it’s more common for key down events to want to skip over specific keys, in which case rather than returning an Ok, return an Error after pattern matching on the resulting key. For more information on other types of KeyEvent and other types of events you can add to a component, check out lily/event.
Now, let’s look at the rest of our view functions:
fn display() -> Component(Model, Message, Element(Message)) {
component.dynamic(slice: fn(model) { model }, render: fn(model: Model, _nest) {
html.ul([], [
html.li([], [html.text("Input: " <> model.input)]),
html.li([], [html.text("Settled Input: " <> model.settled_input)]),
html.li([], [html.text("Last Key: " <> model.last_key)]),
html.li([], [html.text("Seconds: " <> int.to_string(model.seconds))]),
])
})
}
fn clock_buttons() -> Component(Model, Message, Element(Message)) {
component.static(fn(_nest) {
html.div([], [
button("Pause", SetRunning(False)),
button("Resume", SetRunning(True)),
])
})
}
fn button(label: String, message: Message) -> Element(Message) {
html.button([attribute.data("lily-message", event.encode_message(message))], [
html.text(label),
])
}
They key difference here to how we’ve done the buttons for the clock this time is that instead of using event.on_click, we’ve used event.encode_message with the data-lily-message attribute on a button. event.encode_message is used to turn our message into something that can be put straight into the HTML markup. This is a good choice for simple clickable HTML buttons where you don’t need to add any event modifiers and just want to send out a simple message. Rather than creating a listener for every button, this allows a global event listener mounted at the root of component.mount to listen to all of its children and watch out for any of these messages sent. For most buttons, this is enough and prevents too many listeners running simultaneously on pages with a lot of buttons.
Now, let’s write a main function and dispatch a tick every second:
pub fn main() {
let runtime =
store.new(
init: Model(
input: "",
settled_input: "",
last_key: "",
seconds: 0,
running: True,
),
update: update,
)
|> client.start
|> component.mount(
selector: "#app",
to_html: element.to_string,
to_placeholder: fn() { element.element("lily-nest", [], []) },
view: view,
)
tick(client.dispatch(runtime))
}
fn tick(dispatch: fn(Message) -> Nil) {
use _ <- promise.await(promise.wait(1000))
dispatch(Tick)
tick(dispatch)
}
The main new here is by using client.dispatch to send a message. This is useful for async events (e.g. once a backend process is done) to send a certain message. Now, run the shell script again to serve and play around with the text input!
Check out the /examples folder in the GitHub repo for a copy of this example under /examples/03-inputs.