Skip to content

Components

Declare UI with `component`, write its view as elements with children, and render it as HTML on the server.

A component declares a piece of UI: the props it takes, the statements that set it up, and the view it ends with. The view is written as elements, each a struct literal with its children after its fields. A component renders as HTML on the server, and a client program can take the page it rendered over (below); the client side (state that updates the page, hydration, server calls) is designed in UI-COMPONENTS.md.

import ui
import ui/html.{h1, p, section}

component Greeting(name string, times int = 1) {
    shout := name.to_upper_ascii()

    section {
        class: "greeting"
        h1 { "Hello, ${shout}" }
        for i in 0..times {
            p { "line ${i + 1}" }
        }
        if times > 3 {
            p { "that's plenty" }
        }
    }
}

fn page() string {
    return ui.render(Greeting { name: "ada", times: 2 })
}

page answers <section class="greeting"><h1>Hello, ADA</h1><p>line 1</p><p>line 2</p></section>.

An HTML element is a declaration of the module ui/html, one per tag, and a view names it as it names anything of a module: section once import ui/html.{section}, or html.section once import ui/html. A tag that is a keyword takes an as (import ui/html.{select as picker}) or the module’s name (html.select). A tag the file does not import is refused with ATOLL1128, saying which import it needs.

Declaring a component

component Name(props) { … } is a declaration. component is a word, not a keyword: it begins a declaration only where one can begin, followed by a name and (, so a program’s own component identifier still works.

  • Props are parameters, with a function’s types and defaults (times int = 1). At a use they are written as fields: Greeting { name: "ada" }, with a prop that has a default left out.
  • The body is statements, then one element: the view. The statements run once per render, and each prop is a local in them.
  • A component is a struct of its props, so a value of it is an ordinary value: built, passed and rendered.

Elements and their children

An element is written Name { fields children }: its fields first, then its children, one per line. Fields are separated as a struct literal’s are: a line break between fields on lines of their own, and a comma between those that share a line (Badge { label: "inbox", count: 3 }), and after the last of them where children follow on the same line (p { class: "note", "hi" }). A child is one of:

  • an element;
  • a string, or a template whose ${…} holes are written where they are;
  • if, for and match, whose bodies and arms are children;
  • a value in braces, { total }. A bare name is always a field’s shorthand, so braces are how a value is put somewhere as a child.
import ui
import ui/html.{a, li, ul}

enum Load {
    Pending
    Ready([]string)
    Failed(string)
}

component Users(load Load) {
    ul {
        match load {
            Load.Pending => li { "loading" }
            Load.Ready(names) => for name in names {
                li { a { href: "/users/${name}", { name } } }
            }
            Load.Failed(why) => li { class: "error", "failed: ${why}" }
        }
    }
}

A name in a view is one of three things:

  • An HTML element, by its lowercase name (div, a, input, …). Each field is an attribute: an underscore is a hyphen (aria_label is aria-label), and a keyword names a field as any word does (type:, for:). A boolean attribute (disabled, required, checked, …) is written where its value is true. An element that holds no children (img, input, br, …) is written without an end tag.
  • A portable element of std/ui: View, Text, Button, Image, Input and Scroll, which a native build will render through its platform. On the server each is the HTML element that stands for it (View is a flex column div, Text a span), and its typed style fields (below) are its style. Each is a declaration of std/ui, named as anything of a module is: import ui.{View, Text} brings the names in, and ui.View names one through the module. A name the file does not import is free, so a library’s own Button sits beside ui.Button.
  • A component, by any other name, rendered in place.
import ui
import ui.{Button, Text, View}

component Badge(label string, count int = 0) {
    Text { padding: 4, "${label}: ${count}" }
}

component Toolbar(title string) {
    View {
        direction: .row
        gap: 8
        Badge { label: title }
        Badge { label: "inbox", count: 3 }
        Button { on_press: () => { println("pressed") }, "refresh" }
    }
}

Children and named slots

A component takes children by declaring a prop children ui.Children, and its view places them with { children }. The elements after a use’s fields are that prop’s value. A prop typed ui.Slot takes markup as its value too: a named slot, placed the same way.

import ui
import ui/html.{div, h1, h2, header, main, p, section}

component Card(title string, children ui.Children) {
    section {
        h2 { "${title}" }
        { children }
    }
}

component Layout(header ui.Slot, children ui.Children) {
    div {
        header { { header } }
        main { { children } }
    }
}

component Home() {
    Layout {
        header: h1 { "Site" },
        Card { title: "Welcome", p { "Hello." } }
        Card { title: "Empty" }
    }
}

What the children read, mark and handle is their owner’s: a hole in them changes with the owner’s state, and a handler in them is the owner’s. A use that hands no children hands none (Card { title: "Empty" }), in another file too; a component that declares no children refuses them at the first one. A named slot’s value may be a component (header: Logo {}), which is then what it writes. A document prints children where a component places them, as a page writes them.

A component with state of its own may place what it is handed inside a branch it writes again itself, as a modal does:

import ui
import ui/html.{button, div, section}

component Modal(children ui.Children) {
    mut open := false
    div {
        button { on_click: () => { open = !open }, "toggle" }
        if open {
            section { { children } }
        }
    }
}

The markup is then handed as what it writes, and handed again when what it reads changes, so the branch shows it fresh each time it opens; a click inside it is still the owner’s. A component with state of its own in that markup (Modal { Counter {} }) is the owner’s child: it keeps its state while the branch shows it, is handed again what the owner hands it, and goes with the branch, to come back new when the branch shows it again. The same holds where the use that hands the markup is inside an if of the owner’s: the child goes with the component it was handed to. Not built yet: such markup handed by a use that is a row of a for (ATOLL1128).

Pages and addresses

A site’s pages are one root component that takes the page’s address, ui.Url, and picks its page by it. url.route(patterns) answers which pattern the path is (at, -1 for none) and what its captures took: a segment to match, {name} for one segment, {*name} for the rest.

import ui
import ui/html.{h1, main, p}

component Home() {
    h1 { "Home" }
}

component User(id string) {
    h1 { "User ${id}" }
}

component App(url ui.Url) {
    r := url.route(["/", "/users/{id}"])
    main {
        match r.at {
            0 => Home {}
            1 => User { id: r.param("id") ?? "" }
            _ => p { "No page at ${url.path()}" }
        }
    }
}

url.query("tab") reads the query. The server renders each request with its own address, ui_rpc.site("out", "app", (r) => ui.hydrated(App { url: r.url() })), serving the build’s files beside the pages, and one client program takes over whichever page it is.

One project is both halves of a site. Its main is the server, and a function that calls ui.client[App]() is what the pages run:

import http
import ui
import ui_rpc
import ui/html.{h1, main}

component App(url ui.Url) {
    main { h1 { "At ${url.path()}" } }
}

fn entry_client() void ! ui.Unsnapped {
    ui.client[App]()?
}

fn page(r &ui_rpc.Request) string {
    return ui.hydrated(App { url: r.url() })
}

fn main() int {
    site := ui_rpc.site("target/web", "app", page).ok() ?? return 1
    mut s := http.server("127.0.0.1:8080")
    s.serve(site, &[http.Protocol.Rest])
    l := s.listen().ok() ?? return 1
    _ran := s.run(l)
    return 0
}

atoll build --target web -o target/web builds what the pages run, and none of the server; atoll run runs the server, and leaves out what only a page can run. atoll new --web <name> makes a site laid out this way, and atoll dev serves it: it builds both halves again on every change, and an open page loads itself again once the new server is up.

A handler (a field named on_…) and a key are the client’s. On the server they are checked, so a handler that does not type is still an error, and never run: rendering on the server writes no handler.

Styles

A portable element’s look is said with typed style fields, which every host lays out the same way: flexbox (direction, wrap, grow, shrink, basis, align, align_self, align_content, justify), grid (columns, rows, column_span, row_span, column_start, …), the box (padding, margin and their sides and axes, width, height and their minimums and maximums, border and its sides, border_color, radius, box_sizing), position and inset, overflow, display, text (font_size, font_weight, line_height, text_align, color), background and opacity. Each value is a typed Atoll value, never a string, checked when the program is built:

  • a continuous quantity is a number: padding: 16, radius: 8, font_weight: 500, opacity: 0.5; a length may be an int computed at run time, in pixels, or .percent(50) or .auto;
  • a closed set is one of its members, written with a leading dot: direction: .row, align: .center, justify: .between;
  • a colour is one of the theme’s (.primary, .muted_foreground, .border, …), .white, .black, .transparent, or .hex(0x336699), any of them with .alpha(0.9).

The theme’s colours (shadcn/ui’s neutral ones by default) each have a light and a dark colour, and the host picks by the colour scheme: a component never says dark. A style that holds while the host’s own state holds (the pointer over the element, pressed, focused, disabled, or a screen at least the theme’s breakpoint wide) is a when block of style fields:

import ui
import ui.{Text, View}

component Plan(name string, price int) {
    View {
        padding: 16
        gap: 8
        radius: 10
        border: 1
        border_color: .border
        when hovered { background: .accent }
        when wide { padding: 32 }
        Text { font_size: 18, font_weight: 600, "${name}" }
        Text { color: .muted_foreground, "${price} a month" }
    }
}

On the web, a style is classes of the stylesheet atoll build --target web writes beside the module (NAME.css): what holds with no condition is one class, and what holds under a when block, and a theme colour’s dark one, another each. Each rule is written once, however many elements use it, and in a fixed order. Only a value computed at run time is the element’s inline style. Natively, nsh lowers the same values to its own styles; there are no stylesheets or selectors in the language.

A value not of its field’s type is refused where it is, with the closest one:

import ui
import ui.{Text, View}

component Row() {
    View { direction: .col, Text { "x" } }
}

Rendering

ui.render(c) answers the HTML of c’s view, and ui.document(c) the same after a doctype, for a component whose view is the page’s html element:

import ui
import ui/html.{body, h1, head, html, title}

component Page(title string) {
    html {
        head { title { "${title}" } }
        body { h1 { "${title}" } }
    }
}

fn home() string {
    return ui.document(Page { title: "Home & away" })
}

Every hole is escaped as it is written, and every string the view spells out is escaped when the program is compiled: Home & away is written Home &amp; away, and a " in an attribute’s value &quot;.

A style or script element’s text is CSS or JavaScript rather than markup, so it is written as it is: style { "ul > li { margin: 0 }" } keeps its >. What would end the element early is not: a string the view spells that holds </style (or </script, and in a script <!--) is refused, and a value is written with a \ after each such < (<\/style), which CSS and JavaScript read as the same text. A value in such text that can change on the page is refused, since the text holds no marks to write it again by.

What rendering costs. The view is not a tree built and then printed. A component’s render writes its view’s static runs as the constant strings they were folded into, and each hole where it is reached, onto one ui.Html page. A hole that is not a string is written into one scratch string the page keeps and escaped from there, so a render allocates nothing per element or per hole.

A component is std/ui’s Component, whose render(self, out &mut ui.Html) writes its view; a type that implements it by hand renders as a component does.

A page a client takes over

ui.hydrated(c) renders c as a whole document that a client program takes over (its main says ui.client[C](), UI-COMPONENTS.md section 11): the doctype, the view with each hole that can change marked, and each component’s state after it. It also writes ui.EARLY_EVENTS, an inline script that keeps each event the page hears until the program’s shim is in, as the first child of the page’s head, ahead of any stylesheet the head links or holds; where the view has no head, as early (right after the html start tag, or after the doctype).

A page that writes its own head around the view embeds ui.hydrated_fragment(c), the same view and states with no doctype and no early script, and puts ui.EARLY_EVENTS first in that head:

import ui
import ui/html.{button}

component Counter() {
    mut n := 0

    button { on_click: () => { n += 1 }, "${n}" }
}

fn shell(css string) string {
    early := ui.EARLY_EVENTS
    view := ui.hydrated_fragment(Counter {})
    return "<!doctype html><html><head>${early}<link rel=\"stylesheet\" href=\"${css}\"></head><body><main>${view}</main></body></html>"
}

First, because a classic script waits on the stylesheets before it and holds the parse of everything after it, whatever it does. A second copy after a stylesheet (what ui.hydrated’s output embedded in such a page carries) does nothing, since the first has already set itself up, and still waits. On the js-framework-benchmark page, the view was in the DOM 16 ms after the navigation with the script first in the head, and about 30 ms after it with a copy after the stylesheet, alone or second, and the page painted 8 to 12 ms later (UI-COMPONENTS.md section 11).

A page no server rendered mounts a root its project names in atoll.toml ([ui] mount = ["App"], or atoll build --target web --mount App for a lone file): the build writes App.mount.mjs, whose mount({ target }) puts the root’s first render (what ui.hydrated_fragment(App {}) writes, rendered by the build where it reads nothing only the page can give) into the element and takes it over. A root with a prop that has no default is refused there (ATOLL1128), since such a page has no props to hand it.

What is refused

A declaration that is not a component’s shape is refused with ATOLL1128:

component Viewless(n int) {
    total := n + 1
}

The body ends with no element, so there is no view. So is an HTML element the file does not import, a lowercase name that is no HTML element, a field a portable element does not have, children of an element that holds none, a child on the line of its element’s last field with no comma before it (p { class: "note" "hi" }), and a child that is not one of the forms above (div { 3 + 4 } is written div { { 3 + 4 } }).

Type to search…

↑↓ navigate↵ selectEsc close