webtyp/dom is a minimalist, dependency-free wrapper over the browser DOM, optimized for TinyGo/WASM. It provides a Go-native, type-safe API for building UIs without exposing syscall/js.
- Isomorphic Core: Same structs compile for server (
!wasm) and client (wasm). - No Virtual DOM: Fine-grained reactivity via typed Signals (
SignalString/SignalBool/SignalNodes). Signal changes patch only the bound DOM node — O(1), no diffing, no manualUpdate()calls. - DOM-Only Layer: Provides the
Elementstruct, lifecycle interfaces, and direct DOM manipulation. HTML element builders live inwebtyp/html, SVGs inwebtyp/svg, and images inwebtyp/image. - Zero StdLib: Uses
webtyp.com/fmtinstead offmt,strings,errorsto reduce WASM size. - Slices over Maps: Attributes and events use
[]fmt.KeyValueinstead ofmap[string]stringbecause maps are extremely heavy in TinyGo.
There are three primary layers/interfaces:
- Global
domAPI:Render(parentID, comp),Append(parentID, comp),SetDevMode(bool). (updateis unexported — authors never call it; signals patch the DOM directly.) ComponentInterface:GetID(),SetID(id),String(),Children().ReferenceInterface: Represents a live DOM node. Read:GetAttr,Value,Checked. Mutation:SetValue,SetAttr,RemoveAttr,SetText. Interaction:On,Focus.
Render(parentID, comp) clears parent with replaceChildren() and mounts the component's DOM tree, replacing ALL existing children of the
target element. Using "body" as the mount point overwrites the whole body instead of #app.
The webtyp/sitec HTML template already injects <div id="app"></div> before the <script>
tag. Always mount the root component there:
// ✅ CORRECT — sprite SVG stays intact in <body> alongside <div id="app">
Render("app", &App{})
// ❌ WRONG — overwrites body.innerHTML, removes the SVG sprite
Render("body", &App{})| Concern | Package |
|---|---|
| HTML element builders | webtyp/html |
| SVG builders + sprite | webtyp/svg |
| Image builders | webtyp/image |
| DOM manipulation, Element type, interfaces | webtyp/dom (this package) |
Elements are constructed declaratively using builders from sibling packages:
import (
. "webtyp.com/html"
. "webtyp.com/dom"
)
Div(
H1("Welcome"),
P("This is a minimalist UI."),
Div(
Strong("Ready to start?"),
).Class("header-box"),
Button("Get Started").Class("primary").OnClick(func(e Event) {
Log("Button clicked!")
}),
).Class("container")A component is a Go struct that embeds dom.Element as a value (never as a pointer) and implements Render() *dom.Element.
// ✅ CORRECT — value embed: 1 allocation, no nil-panic risk, better GC in TinyGo.
type Counter struct {
dom.Element
count *dom.SignalString
}
func (c *Counter) Init(ctx dom.Ctx) {
c.count = dom.NewString("0")
}
func (c *Counter) Render() *dom.Element {
return html.Div().Child(
html.Span().BindText(c.count).Class("count"),
html.Button().Text("Increment").OnClick(func(e dom.Event) {
c.count.Update(func(v string) string {
i, _ := strconv.Atoi(v)
return strconv.Itoa(i + 1)
})
}),
).Class("counter")
}Reactivity is achieved through Signals. When a signal changes, only the bound DOM nodes are updated. No Update() calls are needed.
The canonical way to build components is to describe the entire UI and its behavior inside Render().
- Events in Render: Attach event listeners directly to elements using the typed methods (
.OnClick(handler),.OnKeyDown(handler), …). - Bindings in Render: Use
.BindText(),.BindClass(), etc., to link signals to DOM attributes or content. - Type-safe Pairing: Use
.For(other *Element)for<label for>pairing. Use.DescribedBy(help, errSpan)foraria-describedby: it references the minted IDs of the describing elements (help text, error message), never a hand-composed id. - Autofocus: Use
.Autofocus()to focus an element when it first appears.
func (c *MyComponent) Render() *dom.Element {
toggle := html.Input("checkbox").Class("toggle")
return html.Div(
html.Label().For(toggle).Text("Click me"),
toggle,
)
}Why value embed? TinyGo has a simple GC — value embedding keeps the struct and its Element identity in a single allocation.
The component lifecycle proceeds in a deterministic sequence of hooks and engine operations:
Init(ctx dom.Ctx)(Optional): Called once when the component is first mounted. Use it to initialize signals or register cleanups viactx.OnCleanup(fn).Render() *dom.Element: Called to build the initial DOM tree or when subtrees are re-rendered.- Insertion: The markup produced by
Render()is inserted into the document. - Wire Bindings & Events: The reactive engine binds signals and registers event handlers to the actual DOM elements.
- Children's
Mounted(): Child components'Mounted()hooks are fired recursively from the deepest level up. - Own
Mounted(): Fired after the component's markup is fully in the document, all bindings are wired, and all children have been mounted. This is the first safe moment where imperative DOM operations (e.g.,Get(id), focusing, measuring, scrolling) can be performed.
On every re-render (update), the component's root elements and markup are replaced wholesale in the DOM. Because any attributes or event listeners attached to the old DOM nodes are lost, Mounted() is triggered again on every re-render (update) after the new nodes have been inserted and wired. This ensures any imperative DOM attachments can be re-established.
- Signal Patches: When a signal changes, the engine surgically updates the bound DOM node.
- Cleanup: When a component is unmounted, all its signal subscriptions and
OnCleanupfunctions are automatically executed.
An element id names a node globally, so it can only be chosen by whoever sees the whole page — the application or the chassis. A component cannot know how many copies of itself are on screen, so any id it invents is a collision waiting for the second instance: two calendarsliders on one page both wrote id="cs-m-2026-09" and claimID panicked.
The component therefore never names a node. It keeps the *Element it built, marks it with Key, and asks it for its live node:
Key(string)— the author's identity contract (BindChildrenalready reconciles on it). It also makes the element addressable: during the WASM passdomassigns it a generated id. SSR emits none, so(*Element).String()stays byte-identical across renders.Ref() (Reference, bool)— the live DOM handle for that element.falsebefore it has been rendered, and on the backend where there is no live DOM. It never mints an id (that would produce one no node carries, and a silent miss), so an element without aKeyand without events or bindings simply answersfalse.
ID() remains correct for elements the application or chassis declares outside any component — page roots like "app" / "body", and hooks for externally-authored CSS.
Worked example: see the Key + Ref section of README.md.
To bundle styles/icons, implement these interfaces:
CSSProvider:RenderCSS() any(Expected to return*css.Stylesheetfor SSR)
The dom.Event interface provides safe access to the JS Event without syscall/js:
PreventDefault(),StopPropagation()TargetValue() stringTargetID() string
OnScrollCapture(handler func(scrollTop float64)): Registers ascrolllistener ondocumentin capture phase, so it fires for any scroller in the page. This exists because thescrollevent does not bubble — it fires only on the element that actually scrolled. A shell that wants to react to the scroll of its content cannot know which descendant of which component overflows, and per-element bubble-phase handlers (.OnClick(), …) would force it to know other packages' internals. Capture phase sees the event descend to any descendant.scrollTopis the vertical position of the element that fired the event. With several scrollers on screen, values interleave — compare with a threshold, never assume a continuous series. There is no way to unregister it: it is a document listener that lives as long as the page. (Backend: no-op — SSR has no scroll.)OnUserActivity(handler func()): Registers the presence event set (pointermove,pointerdown,keydown,wheel,scroll) ondocumentin capture phase, so the handler is called when the user does anything anywhere in the page. This exists because presence is a document-level fact, not an element-level fact. Registering presence listeners on a component's root element fails in three ways:mouseenterfires only once upon crossing the boundary and does not repeat with movement,keydownonly arrives if focus is inside that subtree, and elements mounted outside the subtree (portals, overlays, toasts) emit no events to it. All three failure modes disappear with capture-phase document listeners. The handler receives no arguments (the only fact is that activity occurred) and is throttled to at most ~1 call/second.domowns no timer, threshold, or concept of "idle". Register once; there is no way to unregister it. (Backend: no-op.)
Bindings link a Signal to a DOM property. When the signal's value changes, the DOM is patched automatically.
.BindText(s *SignalString):textContenttracks the signal..BindAttr(name string, s *SignalString): Attribute tracks the signal..BindClass(class string, on *SignalBool): Class is toggled based on the signal..BindAttrBool(name string, on *SignalBool): Boolean attribute (e.g.,disabled,checked) tracks the signal..BindState(s StateAttr, on *SignalBool)/.BindStateFunc(s StateAttr, fn func() bool)/.SetState(s StateAttr): write a widget state (data-x="true"). The only way to write one —widget.StatesatisfiesStateAttr; the value the stylesheet selects on comes from the state itself. NotBindAttrBool: that writesdata-x="", which no data-state selector matches..Bind(s *SignalString): Two-way binding for<input>and<textarea>.
Show(cond *SignalBool, build func() *Element): mounts the subtreebuildreturns only while cond is true (built lazily, unmounted when false). The container is a<slot>: outside a shadow tree it isdisplay: contents, so it adds no box — no stray gap in a flex/grid parent, and the child lays out as the parent's own item.BindChildren(s *SignalNodes): A container whose children track a list of nodes. Use.Key(string)on child elements for stable identity during reconciliation.
The library handles self-closing tags correctly for:
Input(type),Img(src, alt),Br(),Hr()(when using builders fromwebtyp/htmlorwebtyp/image). These return elements with thevoidflag set, preventing the rendering of a closing tag.
dom_wasm.go&element_wasm.go: Implementation usingsyscall/js.dom_backend.go&dom_stub.go(!wasm): No-op / server-side logic for compilation safety.- WASM Memory Safety:
Unmountautomatically releases all savedjs.FuncOfevent listeners.
The dom package provides a type-safe wrapper for the browser's localStorage with built-in quota management.
LocalStorageAvailable() bool: Checks if storage is accessible (handles iframe sandboxes and private modes).LocalStorageGet(key) (string, error): Retrieves a value. Returns("", nil)if the key is absent.LocalStorageSet(key, value) error: Persists a value. Enforces a 64KB per-value limit and a 4MB total budget to prevent crashes.LocalStorageDel(key) error: Removes a specific key.LocalStorageClear() error: Wipes all storage for the origin.
Note
Quota tracking is done in-memory for performance. It assumes dom is the only writer for the origin during the session.
Used to manipulate attributes on document.documentElement (the <html> tag), which is typically used for theme switching or language settings.
SetDocumentAttr(attr, value string): Sets an attribute. Passing""as value removes the attribute.GetDocumentAttr(attr string) string: Reads an attribute. Returns""if absent.
On the backend (!wasm), these are no-ops and return "", ensuring SSR safety and consistency with GetHash().
dom/ssr.go ships the default :root { … } theme of the framework via a single static function:
//go:build !wasm
package dom
import (
"webtyp.com/css"
_ "embed"
)
//go:embed theme.css
var rootCSS string
func RootCSS() *css.Stylesheet { return css.New(css.Raw(rootCSS)) }theme.css is the single source of truth for the default tokens — colors, spacing, layout heights, dark-mode media query. There is no CssVars struct, no DefaultCssVars() constructor, no programmatic builder; the theme is plain CSS.
dom does not import sitec. The contract is the RootCSSProvider interface and the free function RootCSS. webtyp/sitec discovers it via AST extraction during LoadSSRModules() and routes the result to the open slot of <head>.
Apps override the default by exposing their own RootCSS() from the project root's ssr.go. The single-override rule lives in sitec (root project wins, dom is fallback, third-party modules are ignored with a warning). See sitec/docs/ASSETMIN_SSR.md.
RootCSS()(free function inssr.go) → document-level:roottokens, single winner. Returnsany(expected*css.Stylesheet).CSSProvider.RenderCSS()(component method) → per-component scoped styles, accumulate normally. Returnsany(expected*css.Stylesheet).
These are intentionally separate: theme tokens are global and must not stack, while component styles are local and naturally compose.
El serializador de HTML de dom aplica escapado por defecto a todos los nodos de texto y valores de atributos para prevenir vulnerabilidades de XSS almacenado y reflejado.
Text(string): escapa siempre los caracteres especiales HTML (&,<,>,",').Raw(TrustedHTML): agrega marcado crudo sin escapar. Exige explícitamente una instancia deTrustedHTML.Trust(html string) TrustedHTML: es la ÚNICA forma de producir unTrustedHTML. Su presencia en el código fuente hace que cualquier exención al escapado sea inmediatamente auditable mediantegrep -rn "dom.Trust(" ..- Bindings (
BindText,BindTextFunc, etc.): el valor de las señales se escapa automáticamente al serializar.
Regla de uso: Trust se debe utilizar ÚNICAMENTE con literales del propio código o con el resultado de builders confiables del ecosistema, NUNCA con datos provenientes de peticiones, bases de datos o servicios externos.
dom.Get(id) returns a Reference — a live handle to a DOM node. Use its mutation methods to update the element in-place without re-rendering.
Important
dom.Render(parentID, comp) calls cleanupChildren() before writing new innerHTML, which destroys all event listeners registered via the typed ref.On*() methods. Always prefer in-place mutation over re-rendering when you only need to change a value, attribute, or text.
| Method | JS equivalent | Use case |
|---|---|---|
ref.SetValue(v string) |
element.value = v |
Reset input / textarea / select |
ref.SetAttr(key, value string) |
element.setAttribute(key, value) |
Add/set attribute. Pass "" for boolean attrs ("disabled") |
ref.RemoveAttr(key string) |
element.removeAttribute(key) |
Remove attribute |
ref.SetText(text string) |
element.textContent = text |
Update visible text safely (no HTML parsing — XSS-safe) |
ref, _ := dom.Get("submit-btn")
// Show loading (in-place — listener survives)
ref.SetAttr("disabled", "")
ref.SetText("Enviando…")
// Restore (in-place — listener still alive)
ref.RemoveAttr("disabled")
ref.SetText("Enviar")SetText maps to element.textContent, which treats the string as plain text — safe for user-supplied content. innerHTML interprets HTML and would require the caller to sanitize input. If controlled HTML injection is ever needed, a separate SetInnerHTML should be added with explicit XSS risk documentation.
On !wasm builds, all mutation methods are no-ops in elementStub. This is intentional — SSR never holds live DOM handles.