01 Getting Started

Note: These tutorials were written and checked using Gleam 1.19.2.

Let’s get started with your very first Lily app! Start with first creating your project and adding Lily and Lustre as dependencies. Lustre will be used for HTML templating, which should be familiar to those with experience with Lustre already.

We’re going to start with making simple Gleam applications that compile to JS so that we can compile and serve it to view in browser:

gleam new counter --template javascript
cd counter
gleam add lustre
gleam add lily

Let’s modify the imports list to add everything we need:

import gleam/int

import lily/client
import lily/component
import lily/event
import lily/store
import lustre/element
import lustre/element/html

For the project to now build, you might need to remove the existing pub fn main().

We’re going to create a simple counter application with a number that we can increase by the click of a button. We can think of the store of our application as having two parts: a model consisting of the current number of the counter; and an update function that increments when receiving the Increment message.

Let’s add our model and message as types underneath the imports:

pub type Message {
  Increment
}

pub type Model =
  Int

Now, we can add our update function which takes a certain Message and modify the Model in some way. Typically, update functions will pattern match on possible Message constructors and return the appropriate value.

fn update(model: Model, message: Message) -> Model {
  case message {
    Increment -> model + 1
  }
}

Now, we can add a pub fn main() back in and create our new store. store.new takes the initial model and the update function that we just created above. In this case, since we have defined Model to just be Int, we can put our initial counter number of zero in:

pub fn main() {
  store.new(init: 0, update: update)
}

What we can do next is to pipe client.start after creating our store, which starts the client runtime which allows each individual Lily component to listen to any changes in the store. Lily components are more lightweight than a Lustre component or a Phoenix LiveComponent. This means that they’re designed to be more composable and we encourage creating multiple, smaller components much more.

pub fn main() {
  store.new(init: 0, update: update)
  |> client.start
}

Now, we can mount our components onto the client runtime using component.mount. What this does is to first render our component tree once with the current model, and sets up individual listeners each component need to listen to changes in the store. As soon as a relevant part of the store changes, the component would then render if necessary. Apart from taking the client runtime we have just created as its first argument, component.mount takes the arguments selector, to_html, to_placeholder, and view. selector tells where you want to mount these child components in the HTML, making sure anything outside of this selector is unaffected. This also means that one runtime can drive different roots if you call component.mount again with a different selector, allowing multiple roots to share the same model and update loop to be in sync. to_html is the function that takes whatever way you choose to write HTML, whether Lustre or raw strings, and prints them out as HTML strings. In our case, since we’re writing using Lustre’s element library, we will be calling element.to_string. to_placeholder builds the placeholder Lily swaps out when one component is nested inside another (that’s what the _nest argument in render is for). We’re not nesting anything yet, so you can ignore both for now. view is essentially what to show on the initial mount. The components inside it are created and this is only run once based on the current state of the model. Thereafter, all the components inside view will be able to update themselves based on the store listeners that have been setup. With that in mind, let’s look at our component.mount:

pub fn main() {
  store.new(init: 0, update: update)
  |> client.start
  |> component.mount(
    selector: "#app",
    to_html: element.to_string,
    to_placeholder: fn() { element.element("lily-nest", [], []) },
    view: fn(_model) {
      component.dynamic(
        slice: fn(model: Model) { model },
        render: fn(count, _nest) {
          html.button([], [
            html.text(int.to_string(count)),
          ])
        },
      )
      |> event.on_click(message: Increment)
    },
  )
}

Here, we’ve used a dynamic component. This is our default component type that re-renders itself when the slice of the store that it listens to changes. In this case, our slice is the entire model, so it re-renders itself on every Increment. We’ve also attached an event.on_click onto it so that whenever it is clicked, the counter sends an Increment message which triggers an update to the store.

All we’re missing now is an HTML file and a way to serve it. For now, let’s just create an index.html file as such, with the main div matching our selector above.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Lily</title>
  </head>
  <body>
    <div id="app"></div>
    <script type="module">
      import { main } from "./build/dev/javascript/counter/counter.mjs";
      main();
    </script>
  </body>
</html>

To serve the file, you can run the following script commands. In general, don’t trust anything the Internet tells you to run – make sure you understand every line of these scripts before you run them! What we’re essentially doing is setting up a simple Erlang server that serves the index.html file on port 1234. Remember to run chmod on the Bash file once you’re happy with what every line does.

Bash (.sh):

#!/bin/bash
set -e
cd "$(dirname "$0")"
gleam build
echo "Serving on http://localhost:1234"
exec erl -noshell -eval '
  Root = filename:absname("."),
  inets:start(),
  {ok, _} = inets:start(httpd, [
    {port, 1234}, {server_name, "localhost"},
    {server_root, Root}, {document_root, Root},
    {directory_index, ["index.html"]},
    {re_write, {"/[^.]*$", Root ++ "/index.html"}},
    {mime_types, [{"html", "text/html"}, {"mjs", "text/javascript"},
                  {"js", "text/javascript"}, {"css", "text/css"}]}
  ]),
  receive stop -> ok end.'

Windows command (.cmd):

@echo off
cd /d "%~dp0"
call gleam build || exit /b 1
echo Serving on http://localhost:1234
erl -noshell -eval "S = fun erlang:atom_to_list/1, Root = filename:absname(S('.')), inets:start(), {ok, _} = inets:start(httpd, [{port, 1234}, {server_name, S(localhost)}, {server_root, Root}, {document_root, Root}, {directory_index, [S('index.html')]}, {re_write, {S('/[^.]*$'), Root ++ S('/index.html')}}, {mime_types, [{S(html), S('text/html')}, {S(mjs), S('text/javascript')}, {S(js), S('text/javascript')}, {S(css), S('text/css')}]}]), receive stop -> ok end."

After running the script you should be able to see the button on your screen when you navigate to localhost:1234! Try clicking on it and you should see its label increase.

Check out the /examples folder in the GitHub repo for a copy of this example under /examples/01-intro.

✨ Search Document