santoku
santoku

santoku

A Lua framework for building applications end to end

Lua 5.1 from the build system to the server to the browser. Every example on this site runs in your browser. Edit one and run it.


santoku targets Lua 5.1, because 5.1 is the version its platforms actually share. LuaJIT implements 5.1 and OpenResty embeds LuaJIT, so server code, client code and the build harness all run the same language. Compiled to WebAssembly, the 5.1 core is smaller to embed, and its single number type sidesteps the integer and float split introduced in 5.3, which keeps numeric values crossing the JavaScript boundary simple. Support for newer versions is meant to come from compatibility shims layered over the 5.1 core rather than version branches in the tree; contributions and design ideas for that layer are welcome.

santoku-web: component authoring

View on LuaRocks

rules for the author of a santoku.web.app component: connect and disconnect, attributes, markup, focus, slots and parts, modal dialogs, styles and main-thread work

A santoku.web.app component is a custom element with a shadow root. The library runs its setup, teardown and rendering. These cards give the rules that the author of the spec and the template follows for attributes, markup, focus and styles.

Details

Lifecycle

Connect and disconnect

spec.state and then spec.start run on each connect, and the c.on_stop steps run on each disconnect.

local app = require("santoku.web.app")
local dom = require("santoku.web.dom")
local async = require("myapp.async")
local tpl = require("myapp.templates")

app.define({
  tag = "job-clock",
  template = tpl.job_clock,
  state = function (attrs)
    return { zone = attrs.zone, width = 0, late = false }
  end,
  start = function (s, c)
    c.on_stop(dom.listen("window", "resize", function ()
      s.width = dom.read({ "scroll" })[3]
      c.commit()
    end))
    async.sleep(60000)
    s.late = true
  end,
})
Illustrative: runs outside the browser.
Details
  • A move in the page is a disconnect and a connect. A moved element keeps its shadow root and gets a new state table.
  • Build the state table from attrs and scope in spec.state. A value that changed after the connect, such as text the user typed, is gone after a move.
  • Since santoku-web 9.0.0, on disconnect every task the component started (start, route, actions, and the tasks they spawned, debounced calls included) stops for good. It never resumes, and its sleeps are cleared.
  • Since santoku-web 11.0.0, the c.on_stop steps then run in order as one task, while the view is still in the root. A step can await, and c still works. When the task ends, the library releases its own listeners, the view and a scope without a name.
  • Register each stop function that dom.listen returns with c.on_stop instead of keeping it on s. spec.stop is gone, and define raises when a spec sets it.
  • Since santoku-web 10.0.0, the disconnect also aborts every fetch those tasks await, including those inside a latest call, so no request needs a c.on_stop.
  • Define each tag once. Since santoku-web 6.0.0, a second define of one tag raises "define: TAG is already defined".

Attributes at connect

spec.state gets the element's attributes as they are at connect. No hook runs when an attribute changes after that.

Page
<job-list data-title="Open jobs" limit="20" compact></job-list>
Client
app.define({
  tag = "job-list",
  template = tpl.job_list,
  state = function (attrs)
    return {
      title = attrs.title,
      limit = tonumber(attrs.limit),
      compact = attrs.compact ~= nil,
    }
  end,
})
Illustrative: runs outside the browser.
Details
  • Set every attribute before the element enters the page.
Attributes on the elementattrs
context-path="/ctx"context_path = "/ctx", with each - turned to _
data-list-style="grid"list_style = "grid", with the leading data- dropped
sales="", or a naked attribute such as compactsales = "" and compact = ""
q="plain" data-q="chef"q = "chef", since data-q wins over q
  • An absent attribute reads as nil. So test presence with attrs.compact ~= nil, since attrs.compact or default keeps "".
  • The attributes arrive with the connect event, so spec.state reads them with no crossing of its own.
  • A parent template that changes an attribute of a nested component after connect changes nothing in that component. Components that show one state share a scope or call each other's c.commit(): https://santoku.dev/santoku-web#santoku-web--components-with-app-define
  • Every value is a string. Convert a number with tonumber(attrs.limit).
  • Write a boolean attribute naked, such as compact. compact="false" is still present, so attrs.compact ~= nil is true for it.
  • Don't give a component an attribute of its own with a global attribute's name, such as title, hidden, lang, dir, class, id, style, slot, part or tabindex. The browser acts on those names.
  • Use a data- name for such an attribute: data-title reads as attrs.title.
  • Since santoku-web 7.0.0, an attribute named for one of the spec's keys seeds the scope and wins over the URL: https://santoku.dev/santoku-web#santoku-web--components-with-app-define
  • A key named like a global attribute reads that attribute, so name such a key another way.

The open shadow root since santoku-web 6.0.0

Every component renders into an open shadow root. Page code and a browser test reach the root as el.shadowRoot. Code in the component uses c.root, the root's dom handle.

Page code
local dom = require("santoku.web.dom")
local js = require("santoku.web.js")
local root = dom.root(js.document:querySelector("job-list").shadowRoot)
dom.text({ root, "h2" }, "Jobs")
dom.flush()
Browser test
local page = require("santoku.cdp.page")
local s = page.open({ port = 9333 })
page.navigate(s, "http://127.0.0.1:8080/")
local heading = "document.querySelector('job-list')?.shadowRoot?.querySelector('h2')?.textContent"
print(page.wait_until(s, heading, 10000))
s.close()
Illustrative: runs outside the browser.
Details
  • Before santoku-web 6.0.0 the root was closed, and el.shadowRoot was nil.
  • The root still scopes ids, selectors and styles. A page script can read and change what's inside.
  • A root runs data-action entries for its own tree only. When a nested component runs no action for an event, the outer root gets the event, and ev.target is a handle for that component's host.
  • santoku-cdp's wait, type and click selectors call document.querySelector, which doesn't look inside a shadow root. Go through the host, as the browser test below does.

Templates

Markup in a template

Every component is its own shadow root, so an id is private to its template and every action needs an element that takes focus and keys.

Template
<form data-action="search">
  <label for="q">Keyword</label>
  <input id="q" name="q">
  <button>Search</button>
  <button type="button" data-action="clear">Clear</button>
</form>
<a href="#results" data-action="jump">Skip to the results</a>
<p id="results">{{q}}</p>
Client
app.define({
  tag = "job-search",
  template = tpl.job_search,
  state = function ()
    return { q = "" }
  end,
  actions = {
    search = function (s, _, ev)
      s.q = ev.form.q
    end,
    clear = function (s, c)
      dom.prop({ c.root, "#q" }, "value", "")
      s.q = ""
    end,
    jump = function (_, c, ev)
      c.hash_jump(ev)
    end,
  },
})
Illustrative: runs outside the browser.
Details
  • Put a click action on a <button type="button"> and a navigation on an <a href>. data-action runs on any element, but a <div> takes no focus and no Enter or Space key.
  • Inside a form, give each action button type="button". A <button> with no type runs its click action and then submits the form, which runs the form's action too.
  • A form with no data-action submits natively, so the page navigates.
  • <label for>, aria-labelledby, aria-describedby, aria-controls, <input list> and form="id" find only an id in the same template. The browser ignores a reference from the page or from another component.
  • When the label sits outside the component, write aria-label text on the control.
  • A link to #name finds no element inside a component. Give the link data-action="jump" and call c.hash_jump(ev) from its action.

Focus

dom.focus(target) calls the element's focus(). The root sets no delegatesFocus, so focus a control inside the root by target.

Template
<input name="q" data-action="input:filter">
<button type="button" data-action="open" data-id="7">Open job 7</button>
<h2 tabindex="-1">{{job}}</h2>
Client
app.define({
  tag = "job-view",
  template = tpl.job_view,
  events = { "input" },
  state = function ()
    return { job = "", q = "" }
  end,
  start = function (_, c)
    dom.focus({ c.root, "input[name=q]" })
  end,
  actions = {
    filter = function (s, _, ev)
      s.q = ev.value
    end,
    open = function (s, c, ev)
      s.job = "Job " .. ev.data.id
      c.commit()
      dom.focus({ c.root, "h2" })
    end,
  },
})
Illustrative: runs outside the browser.
Details
  • An element that can't take focus ignores the call. Give a heading or a panel tabindex="-1" before you focus it.
  • Focus on the host element goes nowhere.
  • To style the host while a control inside holds focus, write :host(:focus-within).
  • After a route or a request replaces the view, focus the start of the new view. The selector that done returns only scrolls.
  • Leave focus alone when results update while the user types.
  • An update keeps every node it doesn't change, so focus stays on a kept node.
  • When an action hides the section that holds the focused element, focus the control that opened it.

Slots and parts

A <slot> in a template shows the host element's children, which stay children of the host. A part attribute lets page CSS style one template element.

Page
<style>job-card::part(more) { color: teal; }</style>
<job-card><span slot="title">Chef</span><p>Full time</p></job-card>
Template
<style>::slotted(p) { margin: 0; }</style>
<header><slot name="title">Untitled</slot></header>
<slot data-action="slotchange:changed"></slot>
<button type="button" part="more" data-action="more">More ({{count}})</button>
Client
app.define({
  tag = "job-card",
  template = tpl.job_card,
  events = { "slotchange" },
  state = function ()
    return { count = 0, open = false }
  end,
  actions = {
    changed = function (s, _, ev)
      s.count = dom.node(ev.el):assignedElements().length
    end,
    more = function (s)
      s.open = true
    end,
  },
})
Illustrative: runs outside the browser.
Details
  • <slot name="title"> takes a child with slot="title". A <slot> with no name takes the rest, whitespace text between elements included.
  • Content inside a <slot> shows while the slot has no child assigned.
  • To act when the children change, list "slotchange" in events and put data-action="slotchange:NAME" on the slot.
  • ::slotted(p) in the component's style reaches a child of the host, and no element nested inside that child.
  • job-card::part(more) in page CSS styles the template element that carries part="more". Without app.page in sheets, a page selector matches no other element inside the root.

The state and the handle since santoku-web 9.0.0

The framework writes no field on a component's state. Every handler but state gets the component handle c after s.

app.define({
  tag = "job-find",
  template = tpl.job_find,
  scope = { "q" },
  state = function (_, scope)
    return { q = scope.read().q or "" }
  end,
  start = function (_, c)
    dom.focus({ c.root, "#q" })
  end,
  route = function (s, c)
    s.q = c.scope.read().q or ""
  end,
  actions = {
    search = function (_, c, ev)
      c.scope.push({ q = ev.form.q })
    end,
  },
})
Illustrative: runs outside the browser.
Details
FieldResult
c.commit()renders the component and flushes
c.emit(name, detail)sends a component event
c.rootthe shadow root's dom handle
c.scopethe router scope of a spec with scope, and nil otherwise
c.enter(undim)commits, waits for the paint, undims and commits
c.hash_jump(ev)scrolls to a hash link's target under c.root
c.on_stop(fn)registers a disconnect step, run once in order with the others
  • A field named commit, root, scope or emit belongs to the app, and the template reads it like any other field. Keep no function, handle or request on s. App handles such as a latest go on c: c.search = async.latest(fn) in start.
  • After the element leaves the page, c.commit() renders nothing and c.emit sends nothing.
  • spec.state(attrs, scope) gets no c, and still gets the scope as its second argument.
  • latest: https://santoku.dev/santoku-web#santoku-web--latest-in-components

Component events since santoku-web 9.0.0

c.emit(name, detail) dispatches a CustomEvent from the component's root at the next flush. The event bubbles, is composed and can't be canceled.

Child
app.define({
  tag = "job-results",
  template = tpl.job_results,
  state = function ()
    return { rows = {} }
  end,
  actions = {
    search = function (s, c, ev)
      s.rows = { ev.form.q }
      c.emit("job-title", { title = "Jobs", count = #s.rows })
    end,
  },
})
Parent template
<h1>{{title}}</h1>
<job-results data-action="job-title:retitle"></job-results>
Parent
local val = require("santoku.web.val")

app.define({
  tag = "job-page",
  template = tpl.job_page,
  events = { "job-title" },
  state = function ()
    return { title = "" }
  end,
  actions = {
    retitle = function (s, _, ev)
      s.title = val.unpack(ev.event.detail).title
    end,
  },
})
Illustrative: runs outside the browser.
Details
  • name is a string with no colon, such as job-title with the app's prefix. A colon raises "c.emit: name must not contain a colon", since data-action splits at it.
  • detail is nil or any value cjson.encode takes. The event carries it as JSON.
  • The event leaves from the shadow root, so a listener outside reads the host as ev.target.
  • The event fires at the next flush, in order with the dom writes queued around it. An action, start or route commits after it, so an emit there needs no flush.
ListenerCodeDetail
page JavaScriptdocument.addEventListener("job-title", fn)ev.detail
another component, in startc.on_stop(dom.listen("document", "job-title", fn))val.unpack(ev.detail)
a parent componentevents = { "job-title" } and data-action="job-title:NAME" on the child's tagval.unpack(ev.event.detail) in the action
  • An emit in an action adds no crossing. A Lua listener that unpacks the detail adds its own.

State attributes since santoku-web 7.0.0

spec.states lists state fields that show on the element as boolean attributes. Each commit sets the attribute when the field is truthy and removes it otherwise.

Template
<style>:host([state-stale]) #results { opacity: 0.5; }</style>
<div id="results">{{{html}}}</div>
Client
app.define({
  tag = "job-list",
  template = tpl.job_list,
  states = { "stale" },
  state = function ()
    return { stale = false, html = "" }
  end,
  actions = {
    refresh = function (s, c)
      s.stale = true
      c.commit()
      s.html = "<p>fresh</p>"
      s.stale = false
    end,
  },
})
Illustrative: runs outside the browser.
Details
  • Since santoku-web 12.0.0, a state is the host attribute state-<name>, and CSS custom states, :state() and attachInternals are gone.
  • The attribute name is state- and the field name as written: s.no_results is state-no_results.
  • Component CSS selects :host([state-stale]). Page CSS selects job-list[state-stale]. A browser test waits on el.matches("[state-stale]").
  • The state- prefix keeps a state off author attributes. A stale attribute on the tag stays the author's, and attrs never holds a declared state- attribute.
  • A states entry that isn't a string raises "app.define: a states entry must be a string". A name outside lowercase letters, digits, _ and - raises "app.define: a states entry must be lowercase letters, digits, _ and -".
  • Declare only the flags the page or the component CSS reads. Other fields stay private.
  • A changed state is one buffered op, so it adds no crossing to the commit.

Modal dialogs since santoku-web 6.0.0

A modal is a <dialog> in the template. dom.modal_show(target) calls the dialog's showModal(), and dom.modal_close(target) calls its close().

Template
<button type="button" data-action="export">Export</button>
<dialog>
  <h2>Export as CSV</h2>
  <form data-action="send">
    <input name="email" type="email" required>
    <button>Send</button>
    <button type="button" data-action="cancel">Cancel</button>
  </form>
</dialog>
Client
app.define({
  tag = "job-export",
  template = tpl.job_export,
  state = function ()
    return { email = "" }
  end,
  start = function (_, c)
    local dialog = dom.find(c.root, "dialog")
    c.on_stop(dom.listen(dialog, "close", function ()
      dom.reset({ c.root, "dialog form" })
    end))
    c.on_stop(function ()
      dom.release(dialog)
    end)
  end,
  actions = {
    export = function (_, c)
      dom.modal_show({ c.root, "dialog" })
    end,
    cancel = function (_, c)
      dom.modal_close({ c.root, "dialog" })
    end,
    send = function (s, c, ev)
      s.email = ev.form.email
      dom.modal_close({ c.root, "dialog" })
    end,
  },
})
Illustrative: runs outside the browser.
Details
  • The browser keeps focus inside an open modal, dims the page behind it and closes it on Esc. Since santoku-web 7.0.0, a click on the backdrop closes it too.
  • Since santoku-web 12.0.0, a backdrop close dispatches a cancelable cancel event and then calls close() unless a listener prevented it, so the dialog gets cancel and then close, as on Esc. A press that starts inside the dialog's box never closes it.
  • Don't open a modal with dom.prop(target, "open", true), which does none of those.
  • Give the dialog a visible close control.
  • A <form method="dialog"> with no data-action closes the dialog on submit. A form with a data-action has its submit prevented. Call dom.modal_close in that action.
  • The dialog's close event doesn't bubble, so a data-action="close:NAME" entry never runs. To act on every close, listen on the dialog in spec.start, and register the listener's stop and the handle's release with c.on_stop.
  • Style the dimmed page with dialog::backdrop in the component's style.
  • A menu is a popover panel. Write popover with no value on the panel, and open it with <button type="button" popovertarget="ID"> in the same template. A click outside and Esc close it.
Popover ruleReason
Never write popover="manual"neither a click outside nor Esc closes it
Open a menu with its popovertarget button, never a click action that calls dom.popover_showthe press closes the open panel and the action opens it again
Keep dom.popover_show for an open no toggle button starts, such as a typeahead that opens on inputno button owns the panel
Listen for toggle on the panel with dom.listen in spec.starttoggle doesn't bubble
Style the open panel with :popover-openthe state keeps no open flag

Styles

Component styles

The <style> block of a component's template file becomes one constructed sheet per tag, and every element of the tag adopts it.

job-list.html
<style>
  :host { display: block; }
  :host(:focus-within) { outline: 2px solid var(--job-accent, navy); }
  button, input, select, textarea { font: inherit; }
  h2 { color: var(--job-accent, navy); }
</style>
<h2>{{title}}</h2>
<button type="button" data-action="more">More</button>
Page CSS
job-list { --job-accent: teal; }
Illustrative: runs outside the browser.
Details
  • loader.templates names each entry from its file: job-list.html is tpl.job_list, and the spec names it with template = tpl.job_list.
  • Put no @import in that <style> block or in app.stylesheet(css). The browser drops an @import from a constructed sheet. Link that CSS in the page and put app.page first in sheets.
  • Sheets apply in this order: the page's cloned sheets when sheets starts with app.page, then the rest of sheets, then the tag's own style.
  • Since santoku-web 11.0.0, define raises when app.page comes anywhere but first in sheets, since the browser applies the cloned sheets before every adopted sheet.
  • The host is display: inline until a rule changes it. Write :host { display: block; } when the component is a box of its own.
  • Write :host { display: contents; } only when the template's top elements must be flex or grid items of the page's container.
  • A display: contents host has no box, and its rect reads as zeros.
  • A button, input, select or textarea shows in the browser's own font until a sheet in the root sets the font on controls.
  • Custom properties inherit through the root, so a page rule such as job-list { --job-accent: teal; } themes the component.
  • Don't set --job-accent on :host. A value set on an ancestor of the element, such as body, then never reaches the component.
  • Don't use :host-context(). Firefox and Safari don't ship it.

Main thread

Work on the main thread

An action runs on the main thread. Lua that runs for more than 50 ms without an await blocks input and paint.

local function score (row)
  return #row.title
end

app.define({
  tag = "job-table",
  template = tpl.job_table,
  state = function ()
    return { rows = {} }
  end,
  actions = {
    fit = function (_, c)
      local list, side = dom.read({ "rect", { c.root, "#list" } }, { "rect", { c.root, "#side" } })
      dom.style({ c.root, "#list" }, "minHeight", side[6] .. "px")
      dom.style({ c.root, "#side" }, "minHeight", list[6] .. "px")
    end,
    rank = function (s)
      for i = 1, #s.rows do
        s.rows[i].rank = score(s.rows[i])
        if i % 200 == 0 then
          async.sleep(0)
        end
      end
    end,
  },
})
Illustrative: runs outside the browser.
Details
  • Every js.* call, proxy method call and dom.node call crosses into JavaScript. A dom write crosses once per flush, and an event crosses once per dispatch.
  • Inside a loop, use dom ops and one dom.read with several queries.
  • Read before you write inside a loop. dom.read applies every queued write before it answers, so a read after a write forces a layout on each pass.
  • Call async.sleep(0) between slices of a long loop, or move the work to a worker behind santoku.web.rpc: https://santoku.dev/santoku-web#santoku-web--santoku-web-rpc