# santoku-web: component authoring > 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 This file is one tab of the santoku reference, at https://santoku.dev/santoku-web/components/llms.txt. https://santoku.dev/santoku-web/components is the same tab in a browser, https://santoku.dev/llms.txt indexes every tab, and https://santoku.dev/llms-small.txt summarizes them all on one page. 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. - The component API is on the santoku-web tab: https://santoku.dev/santoku-web#santoku-web--components-with-app-define - santoku-web's behaviour uses only what is Baseline widely available, plus the editor's Selection.getComposedRanges. A component needs no feature detection, no polyfill and no fallback. - The later examples reuse app, dom, async and tpl from the first card. async is the app's santoku.async module: https://santoku.dev/santoku#santoku--santoku-async ## Lifecycle ### Connect and disconnect spec.state and then spec.start run on each connect, and the c.on_stop steps run on each disconnect. - 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". ```lua 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, }) ``` ### Attributes at connect spec.state gets the element's attributes as they are at connect. No hook runs when an attribute changes after that. - Set every attribute before the element enters the page. | Attributes on the element | attrs | |---|---| | 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 compact | sales = "" 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. Page: ```text ``` Client: ```lua 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, }) ``` ### The open shadow root 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. - 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. Since santoku-web 6.0.0 Page code: ```lua 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: ```lua 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() ``` ## 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. - Put a click action on a Skip to the results

{{q}}

``` Client: ```lua 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, }, }) ``` ### Focus dom.focus(target) calls the element's focus(). The root sets no delegatesFocus, so focus a control inside the root by target. - 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. Template: ```text

{{job}}

``` Client: ```lua 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, }, }) ``` ### Slots and parts A 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. - takes a child with slot="title". A with no name takes the rest, whitespace text between elements included. - Content inside a 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. Page: ```text Chef

Full time

``` Template: ```text
Untitled
``` Client: ```lua 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, }, }) ``` ### The state and the handle The framework writes no field on a component's state. Every handler but state gets the component handle c after s. | Field | Result | |---|---| | c.commit() | renders the component and flushes | | c.emit(name, detail) | sends a component event | | c.root | the shadow root's dom handle | | c.scope | the 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 Since santoku-web 9.0.0 ```lua 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, }, }) ``` ### Component events 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. - 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. | Listener | Code | Detail | |---|---|---| | page JavaScript | document.addEventListener("job-title", fn) | ev.detail | | another component, in start | c.on_stop(dom.listen("document", "job-title", fn)) | val.unpack(ev.detail) | | a parent component | events = { "job-title" } and data-action="job-title:NAME" on the child's tag | val.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. Since santoku-web 9.0.0 Child: ```lua 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: ```text

{{title}}

``` Parent: ```lua 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, }, }) ``` ### State attributes 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. - Since santoku-web 12.0.0, a state is the host attribute state-, 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. Since santoku-web 7.0.0 Template: ```text
{{{html}}}
``` Client: ```lua 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 = "

fresh

" s.stale = false end, }, }) ``` ### Modal dialogs A modal is a in the template. dom.modal_show(target) calls the dialog's showModal(), and dom.modal_close(target) calls its close(). - 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
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

Export as CSV

``` Client: ```lua 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, }, }) ``` ## Styles ### Component styles The

{{title}}

``` Page CSS: ```text job-list { --job-accent: teal; } ``` ## 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. - 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 ```lua 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, }, }) ```