Lesson 45 of 56 · Web pages

State, the DOM and timers

The last three lessons showed single events. A real page puts them together: it remembers something, reacts to a click or a key, and then updates what the reader sees. This lesson teaches that loop with small complete pages, a counter, a todo list, tabs, a stopwatch, a quiz, and the dom functions each one needs.

State lives in variables

An interactive page is a loop of three steps: something happens, the program changes what it remembers, and the page is redrawn from what the program remembers. What the program remembers is its state. In Salam the state of a page is a handful of top level mut variables above the page: block. Handlers change them, and one function, usually called draw or show, copies them into the page.

web-dom-counter.salam
import dom

mut count := 0

func draw:
    shown := dom.ById("value")
    dom.SetText(shown, "" + count)
    if count < 0:
        dom.SetStyle(shown, "color", "#dc2626")
    else:
        dom.SetStyle(shown, "color", "#0f172a")
    end
end

func more:
    count++
    draw()
end

func fewer:
    count--
    draw()
end

func start_over:
    count = 0
    draw()
end

page:
    title = "Counter"
    font = "system", "sans"
    margin = 1.5rem
    box:
        max width = 16rem
        margin = 0, "auto"
        padding = 20
        text align = "center"
        border = 1px, "solid", "#e2e8f0"
        radius = 14
        heading:
            id = "value"
            size = 1
            content = "0"
            font size = 4rem
            margin = 0, 0, 12px, 0
        end
        button:
            padding = 8px, 18px
            hover background = "#e0e7ff"
            font size = 1.1rem
            border = 1px, "solid", "#cbd5e1"
            radius = 8
            background = "#f8fafc"
            cursor = "pointer"
            id = "minus"
            click = fewer
            content = "-1"
        end
        button:
            padding = 8px, 18px
            hover background = "#e0e7ff"
            font size = 1.1rem
            border = 1px, "solid", "#cbd5e1"
            radius = 8
            background = "#f8fafc"
            cursor = "pointer"
            id = "plus"
            click = more
            content = "+1"
            margin = 0, 8px
        end
        button:
            padding = 8px, 18px
            hover background = "#e0e7ff"
            font size = 1.1rem
            border = 1px, "solid", "#cbd5e1"
            radius = 8
            background = "#f8fafc"
            cursor = "pointer"
            id = "zero"
            click = start_over
            content = "Reset"
        end
    end
end
Result

Look at how the example is split. count is the only place that knows the number. fewer, more and start_over change it and call draw, and draw is the only function that touches the page. When something looks wrong on screen you know where to look: either the state is wrong or the drawing is. The red colour of a negative number is a rule inside draw, so it is applied every time, whichever handler ran.

The helpers come from import dom, and the whole list is on the dom package page. This lesson teaches the page side: which helper to reach for and how the parts fit together.

A page program does not need a main and nothing calls one. If you add one, the compiler starts counting only what main calls, and your handlers are reported as unused functions (error E066). Put the work in handlers, and see the storage section for code that must run when the page opens.

Finding elements, reading and writing them

To change an element you first need a handle on it. dom.ById("value") returns the element with that id, and the compiler checks the id for you: if no element of the same page has it, the build stops with error E138, so a typing mistake is found before the page ever runs.

E138: no element with id 'result2' in this file's layout

The check only sees ids written as plain text. An id built while the page runs, such as dom.ById("votes-" + name), is not checked, so a typing mistake there shows up as an error in the browser console instead. When there is no id to use, dom.Query(".note") returns the first element that matches a CSS selector, and dom.QueryAll("#books li") returns all of them as a list. Read a list with dom.CountOf(list) and dom.ItemAt(list, i), counting from 0.

With a handle you can read and write. dom.SetText(el, "...") and dom.GetText(el) deal with text, and dom.SetValue(el, "...") and dom.GetValue(el) with what is typed in a field. The character counter below reads the box on every input event, shows the count and the share of the limit, and switches the button off while the note is empty or too long.

web-dom-charcount.salam
import dom

const LIMIT := 80

func measure:
    used := dom.GetNum(dom.ById("note"), "textLength") as i64
    dom.SetText(dom.ById("used"), "" + used + " / " + LIMIT)
    if used > LIMIT:
        dom.SetStyle(dom.ById("used"), "color", "#dc2626")
        dom.SetStyle(dom.ById("bar"), "width", "100%")
        dom.SetStyle(dom.ById("bar"), "background", "#dc2626")
    else:
        dom.SetStyle(dom.ById("used"), "color", "#475569")
        dom.SetStyle(dom.ById("bar"), "width", "" + used * 100 / LIMIT + "%")
        dom.SetStyle(dom.ById("bar"), "background", "#4f46e5")
    end
    dom.SetBool(dom.ById("post"), "disabled", used == 0 or used > LIMIT)
end

page:
    title = "Character counter"
    font = "system", "sans"
    margin = 1.5rem
    max width = 28rem
    input:
        type = "textarea"
        id = "note"
        input = measure
        rows = 3
        placeholder = "Write a short note"
        width = 100%
        padding = 10
        font size = 1rem
        font = "inherit"
        radius = 8
        border = 1px, "solid", "#cbd5e1"
    end
    box:
        height = 6
        background = "#e2e8f0"
        radius = 3
        margin = 6px, 0
        box:
            id = "bar"
            height = 100%
            width = 0%
            background = "#4f46e5"
            radius = 3
            transition = 0.15s
        end
    end
    box:
        layout = "row"
        justify = "between"
        align = "center"
        span:
            id = "used"
            content = "0 / 80"
            color = "#475569"
        end
        button:
            id = "post"
            disabled = true
            content = "Post"
            padding = 6px, 16px
        end
    end
end
Result

The count comes from dom.GetNum(field, "textLength"), a property the browser keeps for a text area, and not from text.len(). In the browser a Salam string counts UTF-8 bytes, so the Persian word سلام would count as 8. GetNum, GetStr, GetBool and GetProp read any property of an element, and they are how you reach whatever the other helpers do not cover.

A live filter needs no loop over elements, because the list is drawn from a vector and the search text, so the rows that match are the rows that exist. The input handler writes the text into a variable. An each over the books, with an if inside it, lets through only the titles that contain the text, a small function counts them, and a message appears when the count is zero.

web-dom-filter.salam
func shelf(): Vector<str>:
    mut books := Vector {} as Vector<str>
    books.Push("The Little Prince")
    books.Push("Pride and Prejudice")
    books.Push("The Hobbit")
    books.Push("Little Women")
    books.Push("Moby Dick")
    books.Push("Great Expectations")
    ret books
end

func matches(title: str, needle: str): bool:
    ret title.Lower().Includes(needle.Lower())
end

func found(books: Vector<str>, needle: str): int:
    mut count := 0
    repeat books.Len() in i:
        if matches(books.Get(i), needle):
            count++
        end
    end
    ret count
end

func total(books: Vector<str>): int:
    ret books.Len()
end

component Filter:
    books := shelf() as Vector<str>
    query := ""
    box:
        font = "system", "sans"
        margin = 24
        max width = 416
        input:
            id = "q"
            type = "search"
            width = "fill"
            padding = 10
            font size = 16
            radius = 8
            border = 1, "solid", "#cbd5e1"
            placeholder = "Search the shelf"
            input = (v: str): query = v end
        end
        paragraph:
            id = "found"
            color = "#475569"
            margin = 6, 0
            content = found(books, query) + " of " + total(books)
        end
        list:
            id = "books"
            padding = 0
            each _, title in books:
                if matches(title, query):
                    item:
                        key = title
                        padding = 10, 12
                        margin = 6, 0
                        background = "#f1f5f9"
                        radius = 8
                        content = title
                    end
                end
            end
        end
        if found(books, query) == 0:
            paragraph:
                id = "none"
                color = "#b45309"
                content = "Nothing on the shelf matches."
            end
        end
    end
end

page:
    title = "Filter"
    Filter: end
end
Result

When the rows are made by hand, a list from QueryAll is a snapshot. Rows added later are not in it, so ask again each time.

One more way to write is dom.SetHtml(el, "..."). It makes the browser read the string as HTML, so it can build a whole fragment in one call, and dom.SetHtml(el, "") empties an element. That is also the danger. A name typed by a visitor and put in with SetHtml is run as HTML, and a name such as <img src=x onerror=...> becomes a program. Text that came from outside always goes in with SetText, which shows every character as it is:

salam
func echo:
    dom.SetText(dom.ById("shown"), dom.GetValue(dom.ById("name")))
end

page:
    input: id = "name" input = "echo" placeholder = "Your name" end
    paragraph: id = "shown" end
end

A missing element is not an empty value. dom.ById and dom.Query give JavaScript null for an element that is not there, and using it stops the handler with an error in the console. When an element may be absent, ask first with dom.Exists("banner"), as in if dom.Exists("banner"): dom.Remove(dom.ById("banner")) end.

State, styles and attributes

There are three ways to change how an element looks or behaves, and the order of preference is the order below. First, state: declare a variable with := in a component, change it in a handler, and write the style that goes with it in an if inside the element. The page says what each state looks like, the handler only says which state it is, and the two stay apart. The theme switch below holds one variable, night, and every colour on the page follows it.

web-dom-theme.salam
component Theme:
    night := false
    box:
        font = "system", "sans"
        padding = 24
        min height = 192
        background = "#f8fafc"
        color = "#0f172a"
        transition = 300ms
        if night:
            background = "#0f172a"
            color = "#e2e8f0"
        end
        box:
            max width = 416
            padding = 20
            background = "white"
            border = 1, "solid", "#e2e8f0"
            radius = 14
            if night:
                background = "#1e293b"
                border = 1, "solid", "#334155"
            end
            heading:
                size = 2
                content = "Good evening"
                margin = 0, 0, 8, 0
            end
            paragraph:
                content = "One state variable changes every colour on the page."
            end
            button:
                id = "flip"
                padding = 8, 16
                radius = 8
                border = 1, "solid", "#6366f1"
                background = "#6366f1"
                color = "white"
                cursor = "pointer"
                click = (): night = not night end
                content = night ? "Use the day theme" : "Use the night theme"
            end
        end
    end
end

page:
    title = "Theme"
    Theme: end
end
Result

Second, styles: dom.SetStyle(el, "width", "40%") sets one CSS property of one element, with its CSS name (background-color, not backgroundColor), and an empty value removes it again. It is the right tool for a value you work out while running, such as the width of the bar in the character counter. dom.GetStyle(el, "display") returns the value the browser is using now, for example none for a hidden element.

Third, attributes: dom.SetAttr(el, "aria-expanded", "true") and dom.GetAttr(el, "aria-expanded") read and write HTML attributes as text. They matter most for the accessibility attributes, because a screen reader reads aria-expanded and ignores the style. In a component you write the attribute from the same variable: this accordion keeps both in step, because open shows or hides the panel and also sets aria expanded.

web-dom-accordion.salam
component Fold(name: str, title: str):
    open := false
    box:
        border = 1, "solid", "#e2e8f0"
        radius = 10
        overflow = "hidden"
        margin = 0, 0, 8, 0
        button:
            id = "h-" + name
            width = "fill"
            text align = "start"
            padding = 12, 14
            font size = 16
            font weight = 400
            border = 0
            background = "#f1f5f9"
            cursor = "pointer"
            hover:
                background = "#e0e7ff"
            end
            if open:
                font weight = 700
            end
            aria expanded = open ? "true" : "false"
            click = (): open = not open end
            content = title
        end
        if open:
            box:
                padding = 0, 14, 12, 14
                content: end
            end
        end
    end
end

page:
    title = "Accordion"
    box:
        font = "system", "sans"
        margin = 24
        max width = 480
        Fold:
            name = "ship"
            title = "How long does delivery take?"
            paragraph:
                content = "Two to four working days inside the country."
            end
        end
        Fold:
            name = "back"
            title = "Can I return an item?"
            paragraph:
                content = "Yes, within thirty days, if it is unused."
            end
        end
        Fold:
            name = "pay"
            title = "Which payment methods do you accept?"
            paragraph:
                content = "Cards and bank transfer."
            end
        end
    end
end
Result

The accordion is a component, and every fold keeps its own open. The section on reuse comes back to that. The browser also has the details element for exactly this job, with no script at all (see the lesson on page structure). The accordion is here because it shows state, styles and attributes working together.

Some things are not attributes but properties of the element: checked, disabled, value. The attribute only gives the starting value, and the property is the live one. Read and write those with dom.GetBool and dom.SetBool:

salam
func agree_changed:
    ticked := dom.GetBool(dom.ById("agree"), "checked")
    dom.SetBool(dom.ById("join"), "disabled", not ticked)
end

page:
    input: id = "agree" type = "checkbox" change = "agree_changed" end
    label: for = "agree" content = "I accept the rules" end
    button: id = "join" disabled = true content = "Join" end
end

Tabs put state and attributes together. One variable, sel, says which tab is chosen. Every tab gets a flag from it, styles itself with an if and sets aria selected, and one if chain shows the panel that goes with it.

web-dom-tabs.salam
component Tab(label: str, active: bool, pick):
    button:
        padding = 10, 18
        border bottom = 3, "solid", "transparent"
        background = "white"
        font size = 16
        font weight = 400
        cursor = "pointer"
        hover:
            background = "#f1f5f9"
        end
        if active:
            border bottom = 3, "solid", "#4f46e5"
            font weight = 700
        end
        aria selected = active ? "true" : "false"
        click = pick
        content = label
    end
end

component Tabs:
    sel := 0
    box:
        font = "system", "sans"
        margin = 24
        max width = 512
        box:
            layout = "row"
            role = "tablist"
            border bottom = 1, "solid", "#e2e8f0"
            Tab:
                label = "Overview"
                active = sel == 0
                pick = (): sel = 0 end
            end
            Tab:
                label = "Recipe"
                active = sel == 1
                pick = (): sel = 1 end
            end
            Tab:
                label = "Reviews"
                active = sel == 2
                pick = (): sel = 2 end
            end
        end
        if sel == 0:
            box:
                padding = 14, 4
                content = "A flat bread baked on a hot stone in about four minutes."
            end
        else if sel == 1:
            box:
                padding = 14, 4
                content = "Flour, water, salt and a spoon of yeast. Rest the dough for an hour."
            end
        else:
            box:
                padding = 14, 4
                content = "Four and a half stars from 212 readers."
            end
        end
    end
end

page:
    title = "Tabs"
    Tabs: end
end
Result

When two things have to change together, derive both from one variable, as the tabs and the panel do. If the tab buttons and the panels were updated in different places, sooner or later one of them would be forgotten.

Making and removing elements

A page often has to grow: a new row in a list, a new message. In a component you do not make the element yourself: the list is a vector, items.Push(text) adds a task and the each over items draws its row, and taking the task out of the vector takes the row away. The todo list below does both.

web-dom-todo.salam
import dom

func total(items: Vector<str>): int:
    ret items.Len()
end

component Task(label: str):
    held := label
    box:
        layout = "row"
        justify = "between"
        align = "center"
        padding = 8, 12
        margin = 6, 0
        background = "#f1f5f9"
        radius = 8
        paragraph:
            margin = 0
            content = label
        end
        button:
            border = 0
            background = "#e0e7ff"
            radius = 6
            padding = 4, 10
            cursor = "pointer"
            click = (): emit("finish", held) end
            content = "Done"
        end
    end
end

component Tasks:
    items := Vector {} as Vector<str>
    draft := ""
    box:
        font = "system", "sans"
        margin = 24
        max width = 416
        form:
            id = "new"
            layout = "row"
            gap = 8
            submit = (e: i64):
                dom.PreventDefault(e)
                if draft.Len() > 0:
                    items.Push("" + draft)
                    draft = ""
                end
            end
            input:
                id = "name"
                grow = 1
                padding = 8
                font size = 16
                value = draft
                placeholder = "What needs doing?"
                input = (v: str): draft = v end
            end
            button:
                id = "add"
                type = "submit"
                padding = 8, 16
                border = 0
                background = "#4f46e5"
                color = "white"
                radius = 8
                cursor = "pointer"
                content = "Add"
            end
        end
        list:
            padding = 0
            each _, task in items:
                item:
                    key = task
                    Task:
                        label = task
                        on finish = (who: str):
                            repeat items.Len() in i:
                                if items.Get(i) == who:
                                    items.RemoveAt(i)
                                    break
                                end
                            end
                        end
                    end
                end
            end
        end
        paragraph:
            id = "left"
            color = "#475569"
            content = total(items) + " to do"
        end
    end
end

page:
    title = "To do"
    Tasks: end
end
Result

Read the submit handler first. It checks the text, pushes it on items and clears the field, and that is all: the each over items draws the row. The count is not a variable either: total is a function of items, so it can never disagree with the rows.

Each row is a small component with its own Done button. A row cannot change the list it is part of, so the page passes it a function, finish, and the row calls it with its text. The function finds the task in items and removes it, and the row goes with it. dom.Create, dom.Append and dom.Remove still exist, for an element that no component can make, and dom.OnEvent(el, "click", handler) adds a handler to an element made that way; when the handler must see the event, use dom.OnEventE and a lambda with an i64 parameter, such as (e: i64): hello(e) end.

The form of the example matters too. The field and the button sit in a form with a submit handler, so the Enter key adds a task as well as the button, with no key handling written. The handler calls dom.PreventDefault(e), because otherwise the browser would send the form and reload the page.

Text from a user goes into a row as its content, which is always shown as text. If you do build an element by hand, put the text in with dom.SetText, never SetHtml, for the reason given above.

What an event tells you

A handler declared with an i64 parameter receives the event, and a few helpers read it. dom.EventTarget(e) is the element that was hit, dom.EventX(e) and dom.EventY(e) the position of the pointer, dom.EventKey(e) the key, dom.PreventDefault(e) cancels what the browser would do next and dom.StopPropagation(e) stops the event reaching the elements above. Each has its lesson: mouse events, keyboard and forms, drag, drop and touch and media and the rest.

EventTarget is what lets one handler serve many elements that have no state of their own, for example rows made with dom.Create. When each element can be a component, give it its own state instead, as the seat picker below does: eight seats, each with its own taken, and a function that the page passes down so that every seat can say whether it was taken or given up. The page adds the answers up.

web-dom-seats.salam
component Seat(change):
    taken := false
    button:
        width = 44
        height = 44
        border = 2, "solid", "#94a3b8"
        radius = 8, 8, 14, 14
        background = "white"
        cursor = "pointer"
        hover:
            border = 2, "solid", "#4f46e5"
        end
        if taken:
            background = "#4f46e5"
            border = 2, "solid", "#4f46e5"
        end
        aria label = "Seat"
        click = ():
            taken = not taken
            change(taken ? 1 : -1)
        end
    end
end

component Seats:
    chosen := 0
    box:
        font = "system", "sans"
        margin = 24
        box:
            layout = "grid"
            columns = 44, 44, 44, 44
            gap = 10
            Seat:
                change = (d: int): chosen += d end
            end
            Seat:
                change = (d: int): chosen += d end
            end
            Seat:
                change = (d: int): chosen += d end
            end
            Seat:
                change = (d: int): chosen += d end
            end
            Seat:
                change = (d: int): chosen += d end
            end
            Seat:
                change = (d: int): chosen += d end
            end
            Seat:
                change = (d: int): chosen += d end
            end
            Seat:
                change = (d: int): chosen += d end
            end
        end
        paragraph:
            id = "summary"
            color = "#475569"
            content = chosen + " of 8 seats chosen"
        end
    end
end

page:
    title = "Seats"
    Seats: end
end
Result

Timers and frames

Three helpers run a function later. dom.SetTimeout(fn, ms) runs it once after that many milliseconds. dom.SetInterval(fn, ms) runs it again and again. Both return a number, and dom.ClearTimeout(id) and dom.ClearInterval(id) cancel the timer with that number. Keep the number in a top level variable declared mut id := 0 as i64, because a timer you cannot cancel keeps running for as long as the page is open. The functions take a function without parameters, so pass a lambda: (): tick() end.

The stopwatch starts an interval of 100 milliseconds when you press Start, adds one tenth of a second on every tick, and clears the interval when you press Stop. The toast does it with a timeout: it shows a message, and a second click first cancels the waiting timeout so that the message stays for a full two seconds from the last click.

web-dom-stopwatch.salam
import dom

mut tenths := 0
mut ticking := 0 as i64
mut running := false

func draw:
    dom.SetText(
        dom.ById("time"),
        "" + tenths / 600 + ":" + tenths / 10 % 60 / 10 + tenths / 10 % 60 % 10 + "." + tenths % 10
    )
end

func tick:
    tenths++
    draw()
end

func start_stop:
    if running:
        dom.ClearInterval(ticking)
        running = false
        dom.SetText(dom.ById("go"), "Start")
    else:
        ticking = dom.SetInterval((): tick() end, 100)
        running = true
        dom.SetText(dom.ById("go"), "Stop")
    end
end

func zero:
    tenths = 0
    draw()
end

page:
    title = "Stopwatch"
    font = "system", "sans"
    margin = 1.5rem
    box:
        max width = 16rem
        margin = 0, "auto"
        padding = 20
        text align = "center"
        border = 1px, "solid", "#e2e8f0"
        radius = 14
        paragraph:
            id = "time"
            content = "0:00.0"
            font size = 3rem
            font = "ui-monospace", "mono"
            margin = 0, 0, 12px, 0
        end
        button:
            padding = 8px, 20px
            font size = 1.05rem
            border = 1px, "solid", "#cbd5e1"
            radius = 8
            background = "#f8fafc"
            cursor = "pointer"
            id = "go"
            click = start_stop
            content = "Start"
        end
        button:
            padding = 8px, 20px
            font size = 1.05rem
            border = 1px, "solid", "#cbd5e1"
            radius = 8
            background = "#f8fafc"
            cursor = "pointer"
            id = "clear"
            click = zero
            content = "Reset"
            margin = 0, 0, 0, 8px
        end
    end
end
Result
web-dom-toast.salam
import dom

mut waiting := 0 as i64

component Toast:
    shown := false
    box:
        font = "system", "sans"
        margin = 24
        button:
            id = "copy"
            padding = 10, 20
            font size = 16
            radius = 8
            border = 1, "solid", "#4f46e5"
            background = "#4f46e5"
            color = "white"
            cursor = "pointer"
            click = ():
                dom.ClearTimeout(waiting)
                shown = true
                waiting = dom.SetTimeout((): shown = false end, 2000)
            end
            content = "Copy the link"
        end
        box:
            id = "toast"
            role = "status"
            margin = 14, 0, 0, 0
            padding = 10, 14
            background = "#0f172a"
            color = "white"
            radius = 8
            max width = 320
            opacity = 0
            translate = 0, 8
            interactive = false
            transition = 250ms
            if shown:
                opacity = 1
                translate = 0, 0
            end
            content = "Link copied. This message goes away in two seconds."
        end
    end
end

page:
    title = "Toast"
    Toast: end
end
Result

A browser does not promise that an interval is exact. It can run late, and a tab in the background runs it a lot less often. The stopwatch counts ticks, which is simple and good enough to show the idea. For a clock that must be right, remember the start with dom.Now() (milliseconds since the page opened) and show the difference on every tick.

For movement use dom.RequestFrame(fn). It runs the function once, just before the browser draws the next picture, and passes the time in milliseconds. To keep going, the function asks for the next frame itself. This is smoother than an interval because it follows the screen. The ball below is placed from the time that has passed, and not by adding a fixed step, so it takes the same time on a slow screen and on a fast one.

web-dom-slide.salam
import dom

mut began := 0.0

func slide(t: f64):
    mut left := (t - began) / 4.0
    if left < 240.0:
        dom.RequestFrame((next: f64): slide(next) end)
    else:
        left = 240.0
    end
    dom.SetStyle(dom.ById("ball"), "left", "" + left + "px")
end

func launch:
    began = dom.Now()
    dom.RequestFrame((t: f64): slide(t) end)
end

page:
    title = "Slide"
    font = "system", "sans"
    margin = 1.5rem
    box:
        width = 280
        height = 44
        background = "#e0e7ff"
        radius = 22
        box:
            id = "ball"
            position = "absolute"
            top = 4
            left = 0
            width = 36
            height = 36
            background = "#4f46e5"
            radius = 50%
        end
    end
    button:
        id = "go"
        click = launch
        content = "Slide"
        margin = 14px, 0, 0, 0
        padding = 8px, 18px
        border = 0
        background = "#4f46e5"
        color = "white"
        radius = 8
        cursor = "pointer"
    end
end
Result

If you want a loop that never stops, such as a game, dom.EveryFrame does the asking for you. The CSS lesson on transitions and animations comes first, though: when CSS can do the movement, let it.

Remembering after the page closes

Variables vanish when the page is closed. dom.StoreSetStr("note", text) keeps a string in the browser's localStorage, dom.StoreGetStr("note") gives it back (an empty string when nothing is stored), and StoreSetInt and StoreGetInt do the same for whole numbers. The data stays on the reader's device, for that site only, until it is cleared. Never store a password or anything private there, and never trust what you read back: it is only a convenience, and the visitor can change it.

Storage can be unavailable. A private window, a blocked setting or an embedded frame like the preview below can refuse it. The helpers do not stop the page when that happens: a write is dropped and a read gives an empty string, with a warning in the console. Your code should still behave. This note saves as you type and reads the value back to check it, so it can tell the reader when the browser would not keep it. Press the button, or reload a real page, to load the saved note.

web-dom-notes.salam
import dom

func save_note:
    text := dom.GetValue(dom.ById("text"))
    dom.StoreSetStr("note", text)
    if dom.StoreGetStr("note") == text:
        dom.SetText(dom.ById("state"), "Saved on this device.")
    else:
        dom.SetText(dom.ById("state"), "This browser would not keep it.")
    end
end

func load_note:
    saved := dom.StoreGetStr("note")
    if saved.Len() > 0:
        dom.SetValue(dom.ById("text"), saved)
        dom.SetText(dom.ById("state"), "Loaded your saved note.")
    else:
        dom.SetText(dom.ById("state"), "Nothing saved yet.")
    end
end

page:
    title = "Notes"
    font = "system", "sans"
    margin = 1.5rem
    max width = 28rem
    input:
        type = "textarea"
        id = "text"
        input = save_note
        rows = 4
        placeholder = "Your note"
        width = 100%
        padding = 10
        font size = 1rem
        radius = 8
        border = 1px, "solid", "#cbd5e1"
    end
    box:
        layout = "row"
        justify = "between"
        align = "center"
        margin = 6px, 0
        span:
            id = "state"
            content = "Nothing saved yet."
            color = "#475569"
        end
        button:
            id = "again"
            click = load_note
            content = "Load saved note"
            padding = 6px, 14px
        end
    end
    script:
        content = "window.addEventListener('DOMContentLoaded', function () { load_note(); });"
    end
end
Result

The last line of the page is a small script element. The page: block has no start-up hook, so this line asks the browser to run load_note once the page has been read. It can name the function because a function used as an event handler (here the button's click) is also placed where the browser can find it. Without this line the page would load the note only when you press the button.

Alerts, questions and prompts

Three helpers use the browser's own dialogs: dom.Alert(message) shows a message, dom.Confirm(question) gives true or false, and dom.Prompt(question) gives the text the reader typed, or an empty string when they cancelled.

salam
func wipe:
    if dom.Confirm("Delete all notes?"):
        dom.SetText(dom.ById("notes"), "")
    end
end

page:
    paragraph: id = "notes" content = "Three notes" end
    button: click = "wipe" content = "Delete all" end
end

They are quick to write and poor to live with. The page freezes until the reader answers, you cannot style them, the browser may offer to block them, and a page embedded in another page is often not allowed to show them, in which case Confirm quietly answers false. Use them for a first test of an idea, and in a finished page use a dialog element (page structure) or a message inside the page like the toast above.

Components, repeat and handlers

A component is a piece of page you can use more than once, and its handlers can use the component's parameters. In the poll below, the lambda in Choice calls vote(name) with the name its own copy was made with, and the counter has an id built from the same name, so each copy counts its own votes.

web-dom-poll.salam
import dom

func vote(name: str):
    total := dom.ById("votes-" + name)
    dom.SetText(total, "" + (dom.GetText(total).ToInt() + 1))
end

component Choice(name):
    box:
        class = "choice"
        layout = "row"
        justify = "between"
        align = "center"
        padding = 8px, 12px
        margin = 0, 0, 8px, 0
        background = "#f1f5f9"
        radius = 10
        button:
            padding = 6px, 14px
            border = 1px, "solid", "#6366f1"
            radius = 8
            background = "white"
            color = "#4338ca"
            cursor = "pointer"
            click = (): vote(name) end
            content = "Vote for " + name
        end
        span:
            font size = 1.4rem
            font weight = "bold"
            color = "#0f172a"
            id = "votes-" + name
            content = "0"
        end
    end
end

page:
    title = "Poll"
    font = "system", "sans"
    margin = 1.5rem
    max width = 26rem
    heading:
        size = 2
        content = "Your favourite drink?"
        margin = 0, 0, 12px, 0
    end
    Choice:
        name = "Tea"
    end
    Choice:
        name = "Coffee"
    end
    Choice:
        name = "Juice"
    end
end
Result

Two limits are worth knowing. A lambda in a page attribute takes no event parameter, so when a handler needs the event, name a function that has one, as the seat picker does. And a plain page is fixed: repeat = 8 makes eight identical copies, but each and if need runtime values and work only in a page with parameters, which the server fills in, inside a component that keeps variables, or when they read a mut variable (error E133 otherwise). That kind of page is covered in the first lesson of this part, and its ids must be different in every copy, so use a class or EventTarget there.

Components that remember: variables and state

The poll above keeps its numbers in the page and reads them back with dom. A component can instead keep a value of its own: a line votes := 0 at the top of its body gives every copy its own votes. There is no keyword to learn. The compiler looks at how each variable is used and decides what it is:

•

A variable that some code changes (an assignment, ++, a method such as push, a handler, a callback) is kept by each copy: it starts from its value once, when the copy is made, and keeps what the handlers did to it.

•

When the view also shows it (in an attribute, a text, an if or each, or a value passed to another component), it is state: after a handler changes it, the page redraws that copy by itself, its text, its attributes, and the if and each inside it. When nothing in the view reads it (a click counter only a handler looks at, a timer id), changing it redraws nothing.

•

A variable that nothing changes, such as label := "Votes for " + name, is derived: it is worked out again every time the copy is drawn, so it always follows the parameters and the state it is made from.

Nothing else on the page is touched, so the button keeps the focus and text typed into an input of the same copy stays where it is.

web-dom-state.salam
component Choice(name: str):
    votes := 0
    box:
        class = "choice"
        layout = "row"
        gap = 12px
        align = "center"
        padding = 8px, 12px
        margin = 0, 0, 8px, 0
        background = "#f1f5f9"
        radius = 10
        button:
            padding = 6px, 14px
            border = 1px, "solid", "#6366f1"
            radius = 8
            background = "white"
            color = "#4338ca"
            cursor = "pointer"
            click = (): votes++ end
            content = "Vote for " + name
        end
        span:
            font size = 1.4rem
            font weight = "bold"
            color = "#0f172a"
            content = "" + votes
        end
        if votes >= 3:
            span:
                class = "hot"
                font size = 0.9rem
                color = "#b45309"
                content = "popular"
            end
        end
    end
end

page:
    title = "Poll with variables"
    font = "system", "sans"
    margin = 1.5rem
    max width = 26rem
    heading:
        size = 2
        content = "Your favourite drink?"
        margin = 0, 0, 12px, 0
    end
    Choice:
        name = "Tea"
    end
    Choice:
        name = "Coffee"
    end
    Choice:
        name = "Juice"
    end
end
Result

A variable that changes starts from its declaration, which can use the component's parameters (count := start) and needs a type you can see: a literal, a typed parameter, or value as Type, as in items := Vector {} as Vector<str>. The page: block can declare variables the same way, at its top, instead of mut variables above it. Inside the component, if and each may read the state, and every row of an each must have a key built from the loop variable or its index (key = i or key = item.id, error E292 without it), on the row element or on the component use, so the row keeps its element when the rows move. A component with state can sit inside each: every row gets its own copy of the state, which follows the row's key when rows move. The page itself may also read a mut variable: every element, if or each that reads one is drawn again after any handler that changes it. One limit on the web: the copies, and the parts that read a mut variable, are drawn by the page script, so they appear only with JavaScript on. The same page runs in a native window with salam run page.salam --ui=native, where that limit is gone.

Components talking to each other

A component often needs to tell the one around it that something happened. There are two ways, and both work on the web and in a native window.

The first is a callback: the parent passes a function as a parameter and the child calls it from a handler. The lambda is written in the parent, so it changes the parent's state, and the parent is drawn again. A child whose parent passed nothing simply skips the call.

salam
component Counter(change):
    count := 0
    button: click = (): count++ change(count) end content = "+1" end
end

component Pair:
    sum := 0
    box:
        paragraph: content = "sum " + sum end
        Counter: change = (v: int): sum += v end end
    end
end

page:
    Pair: end
end

The second is an event that bubbles, for when the news should travel further than one level. The child writes emit("added", price), and the place where the component is used handles it with on added = (p: int): ... end. The event goes to the nearest handler, then to every level above it, up to an on added line at the top of the page block. A handler that calls stop() keeps it from going further. Here every shelf counts what was added to it and the page adds up the price, while the free sample stops at its shelf:

web-dom-events.salam
mut total := 0

component Item(name: str, price: int):
    box:
        class = "item"
        layout = "row"
        gap = 12px
        align = "center"
        margin = 6px, 0
        span:
            content = name + ", " + price + " coins"
        end
        button:
            padding = 4px, 12px
            border = 1px, "solid", "#6366f1"
            radius = 8
            background = "white"
            color = "#4338ca"
            cursor = "pointer"
            click = (): emit("added", price) end
            content = "Add"
        end
    end
end

component Shelf(title: str):
    count := 0
    box:
        class = "shelf"
        padding = 8px, 12px
        margin = 0, 0, 12px, 0
        background = "#f1f5f9"
        radius = 10
        heading:
            size = 3
            content = title + ": " + count + " added"
        end
        Item:
            name = "Tea"
            price = 3
            on added = (): count++ end
        end
        Item:
            name = "Cake"
            price = 5
            on added = (): count++ end
        end
        Item:
            name = "Sample"
            price = 0
            on added = ():
                count++
                stop()
            end
        end
    end
end

page:
    title = "Events that bubble"
    on added = (p: int): total += p end
    font = "system", "sans"
    margin = 1.5rem
    max width = 26rem
    heading:
        size = 2
        content = "Basket: " + total + " coins"
        margin = 0, 0, 12px, 0
    end
    Shelf:
        title = "Morning"
    end
    Shelf:
        title = "Evening"
    end
end
Result

A handler takes the value as one typed parameter, or none when it does not need it. The compiler works out the route while it builds the page, so an event costs no more than calling the handlers yourself, and only the components whose state changed are drawn again. Put the statements of a longer handler on separate lines, as the sample does: on one line, count = n stop() would read n stop as one name.

Putting it together: a quiz

Here is a bigger one with a little of everything. The state is three variables: which question is showing, the score, and which answer was picked (minus one while none was). The questions are not in the markup. One function returns the question and its answers as a single string, Split("|") cuts it into parts, and a small function turns the picked answer into a mark for each choice, which the choice turns into its colour with if. Adding a question means adding one line.

web-dom-quiz.salam
func question(n: int): str:
    switch n:
        0: ret "Which element is the largest heading?|h1|h6|header|0" end
        1: ret "Which attribute gives an image its text alternative?|alt|src|title|0" end
        else: ret "Which event fires when a field changes as you type?|click|input|load|1" end
    end
    ret ""
end

func part(n: int, k: int): str:
    ret question(n).Split("|").Get(k)
end

func right_answer(n: int): int:
    ret part(n, 4).ToInt()
end

func mark(n: int, picked: int, k: int): int:
    if picked < 0:
        ret 0
    end
    if k == right_answer(n):
        ret 1
    end
    if k == picked:
        ret 2
    end
    ret 0
end

component Choice(label: str, mark: int, pick):
    button:
        width = "fill"
        margin = 6, 0
        padding = 10, 14
        text align = "start"
        font size = 16
        border = 1, "solid", "#cbd5e1"
        radius = 8
        background = "white"
        cursor = "pointer"
        hover:
            background = "#eef2ff"
        end
        if mark == 1:
            background = "#dcfce7"
            border = 1, "solid", "#16a34a"
        end
        if mark == 2:
            background = "#fee2e2"
            border = 1, "solid", "#dc2626"
        end
        click = pick
        content = label
    end
end

component Quiz:
    asked := 0
    score := 0
    picked := -1
    box:
        font = "system", "sans"
        margin = 24
        max width = 448
        if asked < 3:
            heading:
                id = "ask"
                size = 3
                content = part(asked, 0)
            end
            Choice:
                label = part(asked, 1)
                mark = mark(asked, picked, 0)
                pick = ():
                    if picked < 0:
                        picked = 0
                        if right_answer(asked) == 0:
                            score++
                        end
                    end
                end
            end
            Choice:
                label = part(asked, 2)
                mark = mark(asked, picked, 1)
                pick = ():
                    if picked < 0:
                        picked = 1
                        if right_answer(asked) == 1:
                            score++
                        end
                    end
                end
            end
            Choice:
                label = part(asked, 3)
                mark = mark(asked, picked, 2)
                pick = ():
                    if picked < 0:
                        picked = 2
                        if right_answer(asked) == 2:
                            score++
                        end
                    end
                end
            end
            paragraph:
                id = "verdict"
                color = "#475569"
                content = picked < 0 ? "Pick an answer." : (picked == right_answer(asked) ? "Correct." : "Not this time.")
            end
        else:
            heading:
                size = 3
                content = "You scored " + score + " of 3."
            end
        end
        button:
            id = "next"
            padding = 8, 18
            border = 0
            background = "#4f46e5"
            color = "white"
            radius = 8
            cursor = "pointer"
            click = ():
                if asked == 3:
                    asked = 0
                    score = 0
                    picked = -1
                else picked >= 0:
                    asked++
                    picked = -1
                end
            end
            content = asked == 3 ? "Play again" : "Next"
        end
    end
end

page:
    title = "Quiz"
    Quiz: end
end
Result

Notice the guard in each choice: once an answer is picked, picked is no longer negative and further clicks do nothing, so nobody scores twice. Notice also that Next does nothing until an answer is chosen. Checks like these are state again, and they are cheaper than hiding and showing buttons.

The pattern for every page in this lesson is the same. Decide what the page must remember. Describe the page from that state. Make each handler change the state and nothing else.

When it does not work

•

Open the browser console (F12, then Console). An error in a handler appears there with its line, and nothing appears on the page. Most of the problems below are visible in it.

•

Print what you want to know. println "count is", count in a handler writes to the console, as console.log would. It is the simplest way to see whether a handler runs at all and what the state is.

•

Nothing happens on click. Check that the function name is not a name the browser already owns (reset, open, close, focus; see the note in the mouse lesson), and that there is no main in the file. A call written with parentheses, click = more(), is not a silent failure: the compiler rejects it with error E137, because the attribute wants the function itself.

•

"Cannot read properties of null". An id or selector matched nothing. Compare it with the page, and remember that ids built at run time are not checked by the compiler.

•

The page changes, then changes back. A form was sent. Call dom.PreventDefault(e) in its submit handler.

•

A list is out of date. A QueryAll result is a snapshot. Ask again after you add or remove elements.

•

Persian text is counted wrong. str.len() counts bytes in the browser. For what the reader sees use textLength as above.

salam
mut clicks := 0

func more:
    clicks++
    println "clicks:", clicks
end

page:
    button: click = "more" content = "Click and watch the console" end
end

Everything the page does in the browser can be seen and changed by the reader. Check anything that matters, such as prices, rights and limits, again on the server. The first lesson of this part shows how a Salam program serves a page, and the dom package page lists every helper with its signature.

Try it yourself

•

Make the todo list keep its tasks: save the text of every task with StoreSetStr when the list changes, and read it back when the page opens, as the notes example does.

•

Add a fourth question to the quiz, and under the final score a line that tells the reader how many answers were right in a row.

•

Turn the stopwatch into a countdown: start from 30 seconds, stop at zero, and use dom.SetTimeout or the interval to show a message when time is up.

•

Make the accordion close the other panels when one opens, so only one is open at a time. Use QueryAll to visit them all.