Documentation
¶
Index ¶
- func Append(parentID string, component Component) error
- func GetDocumentAttr(_ string) string
- func GetHash() string
- func Log(v ...any)
- func OnHashChange(handler func(hash string))
- func OnScrollCapture(handler func(scrollTop float64))
- func Render(parentID string, component Component) error
- func SetDevMode(on bool)
- func SetDocumentAttr(_, _ string)
- func SetHash(hash string)
- func SetLog(log func(v ...any))
- type Component
- type Ctx
- type DOM
- type Element
- func (b *Element) Attr(key, val string) *Element
- func (b *Element) Autofocus() *Element
- func (b *Element) Bind(s *SignalString) *Element
- func (b *Element) BindAttr(name string, s *SignalString) *Element
- func (b *Element) BindAttrBool(name string, on *SignalBool) *Element
- func (b *Element) BindAttrBoolFunc(name string, fn func() bool) *Element
- func (b *Element) BindAttrFunc(name string, fn func() string) *Element
- func (b *Element) BindChildren(s *SignalNodes) *Element
- func (b *Element) BindClass(class string, on *SignalBool) *Element
- func (b *Element) BindClassFunc(class string, fn func() bool) *Element
- func (b *Element) BindState(s StateAttr, on *SignalBool) *Element
- func (b *Element) BindStateFunc(s StateAttr, fn func() bool) *Element
- func (b *Element) BindText(s *SignalString) *Element
- func (b *Element) BindTextFunc(fn func() string) *Element
- func (b *Element) Child(c ...Component) *Element
- func (b *Element) Children() []Component
- func (b *Element) Class(class ...string) *Element
- func (b *Element) For(other *Element) *Element
- func (b *Element) GetID() string
- func (b *Element) ID(id string) *Element
- func (b *Element) Key(key string) *Element
- func (b *Element) NoCloseTag() *Element
- func (b *Element) On(t string, h func(Event)) *Element
- func (b *Element) Raw(h TrustedHTML) *Element
- func (b *Element) Ref() (Reference, bool)
- func (b *Element) Render(parentID string) error
- func (b *Element) Set(kv ...fmt.KeyValue) *Element
- func (b *Element) SetID(id string)
- func (b *Element) SetState(s StateAttr) *Element
- func (b *Element) String() string
- func (b *Element) Text(text string) *Element
- type Event
- type Reference
- type SignalBool
- type SignalNodes
- type SignalString
- type StateAttr
- type TrustedHTML
- type ViewRenderer
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func GetDocumentAttr ¶
GetDocumentAttr returns an empty string on the backend.
func OnHashChange ¶
func OnHashChange(handler func(hash string))
OnHashChange registers a hash change listener.
func OnScrollCapture ¶
func OnScrollCapture(handler func(scrollTop float64))
OnScrollCapture registra un listener de scroll en FASE DE CAPTURA sobre el documento, de modo que se dispara para CUALQUIER scroller de la página, no solo para la ventana.
Existe porque el evento scroll no burbujea: se dispara únicamente en el elemento que se desplazó. Un shell que quiere reaccionar al scroll de su contenido no puede saber qué descendiente de qué componente es el que realmente desborda, y registrar el listener elemento por elemento lo obligaría a conocer el interior de otros paquetes.
scrollTop es la posición vertical del elemento que disparó el evento. Con varios scrollers en pantalla los valores se intercalan: quien compare posiciones debe tolerarlo con un umbral, no asumir una serie continua.
No hay forma de darlo de baja: es un listener del documento que vive lo que vive la página.
func SetDevMode ¶
func SetDevMode(on bool)
SetDevMode enables or disables development mode features.
Types ¶
type Component ¶
Component is the minimal interface for components. All components must implement this for both SSR (backend) and WASM (frontend).
NOTE: If your struct embeds Element, embed it as a VALUE, not a pointer:
type MyComponent struct {
Element // ✅ Correct — never nil
// NOT: *Element // ❌ Wrong — nil pointer causes panic in renderToHTML
}
This is because renderToHTML calls GetID() on every Component child before checking ViewRenderer.
type Ctx ¶
type Ctx interface {
OnCleanup(fn func())
}
Ctx is handed to the Init hook. Register teardown for async resources (timers, websockets).
type DOM ¶
type DOM interface {
// Render injecta un componente en un elemento padre.
// 1. Llama a componente.Init(ctx) si existe (una sola vez)
// 2. Llama a componente.Render() para obtener el árbol de elementos
// 3. Inyecta el HTML resultante y enlaza bindings y eventos
Render(parentID string, component Component) error
// Append injecta un componente DESPUÉS del último hijo del elemento padre.
// Útil para listas dinámicas.
Append(parentID string, component Component) error
// OnHashChange registra un listener para cambios en el hash de la URL.
OnHashChange(handler func(hash string))
// OnScrollCapture registra un listener de scroll en fase de captura sobre el
// documento: se dispara para cualquier scroller de la página. Ver la función
// de paquete del mismo nombre.
OnScrollCapture(handler func(scrollTop float64))
// GetHash devuelve el hash actual de la URL (ej. "#help").
GetHash() string
// SetHash actualiza el hash de la URL.
SetHash(hash string)
// Get retrieves an element by ID.
Get(id string) (Reference, bool)
// Log provides logging functionality using the log function passed to New.
Log(v ...any)
}
DOM is the main entry point for interacting with the browser. It is designed to be injected into your components.
type Element ¶
type Element struct {
// contains filtered or unexported fields
}
Element represents a DOM element in the fluent Element API.
func NewElement ¶
NewElement creates an Element with the given HTML tag. Used by webtyp/html, webtyp/svg, webtyp/image to build elements.
func Show ¶
func Show(cond *SignalBool, content Component) *Element
Show is implemented for SSR: the child is always serialized; the container carries display:none when cond is false, matching the WASM initial markup.
func (*Element) Bind ¶
func (b *Element) Bind(s *SignalString) *Element
Bind provides two-way binding for <input> and <textarea>.
func (*Element) BindAttr ¶
func (b *Element) BindAttr(name string, s *SignalString) *Element
BindAttr links an attribute to a SignalString.
func (*Element) BindAttrBool ¶
func (b *Element) BindAttrBool(name string, on *SignalBool) *Element
BindAttrBool toggles a boolean attribute (disabled, checked, etc.) based on a SignalBool.
func (*Element) BindAttrBoolFunc ¶
BindAttrBoolFunc toggles a boolean attribute based on a computed boolean.
func (*Element) BindAttrFunc ¶
BindAttrFunc links an attribute to a computed string.
func (*Element) BindChildren ¶
func (b *Element) BindChildren(s *SignalNodes) *Element
BindChildren links a container's children to a SignalNodes.
func (*Element) BindClass ¶
func (b *Element) BindClass(class string, on *SignalBool) *Element
BindClass toggles a class based on a SignalBool.
func (*Element) BindClassFunc ¶
BindClassFunc toggles a class based on a computed boolean.
func (*Element) BindState ¶
func (b *Element) BindState(s StateAttr, on *SignalBool) *Element
BindState writes the state's attribute while on is true and removes it when false. This is the ONLY supported way to write a widget state: the value the stylesheet selects on comes from the state itself, so markup and CSS cannot disagree.
Not BindAttrBool: that writes the HTML boolean form (`data-x=""`), which no data-state selector matches. That mistake shipped once and was invisible.
func (*Element) BindStateFunc ¶
BindStateFunc is the computed form, for a state derived from more than one signal.
func (*Element) BindText ¶
func (b *Element) BindText(s *SignalString) *Element
BindText links the element's textContent to a SignalString.
func (*Element) BindTextFunc ¶
BindTextFunc links the element's textContent to a computed string.
func (*Element) For ¶
For sets the for= attribute pointing to other's ID, auto-generating other's ID if it has none. Use for label/input pairing and aria-* references.
func (*Element) NoCloseTag ¶
NoCloseTag marks the element as self-closing (no closing tag rendered). Use for void HTML elements: br, hr, img, input, link, meta, etc.
func (*Element) Raw ¶
func (b *Element) Raw(h TrustedHTML) *Element
Raw agrega marcado sin escapar. Exige un TrustedHTML, así que pasar datos de una petición no compila — ver Trust.
func (*Element) Ref ¶ added in v0.13.11
Ref returns the live DOM node this element was rendered into.
It is the typed alternative to inventing a global id and calling Get on it: the author keeps the *Element they built and asks it for its node, so no name is chosen, and two instances of one component cannot collide.
func (c *Comp) Render() *Element {
c.row = NewElement("span").Key("row")
return NewElement("div").Child(c.row)
}
func (c *Comp) onSomething() {
if row, ok := c.row.Ref(); ok { row.SetText("hi") }
}
ok is false before the element has been rendered, and for an element dom never gave an id — give it a Key to make it addressable. On the backend (SSR) there is no live DOM and Get's stub answer is returned unchanged.
func (*Element) SetState ¶
SetState writes the state unconditionally, for markup that is born in it.
type Event ¶
type Event interface {
// PreventDefault prevents the default action of the event.
PreventDefault()
// StopPropagation stops the event from bubbling up the DOM tree.
StopPropagation()
// TargetValue returns the value of the event's target element.
// Useful for input, textarea, and select elements.
TargetValue() string
// TargetID returns the ID of the event's target element.
TargetID() string
// TargetChecked returns the checked status of the event's target element.
// Useful for checkbox and radio input elements.
TargetChecked() bool
}
Event represents a DOM event.
type Reference ¶
type Reference interface {
// GetAttr retrieves an attribute value.
GetAttr(key string) string
// Value returns the current value of an input/textarea/select.
Value() string
// SetValue sets element.value (inputs, textarea, select).
SetValue(value string)
// SetAttr calls element.setAttribute(key, value).
// Use empty string for boolean attributes (e.g., SetAttr("disabled", "")).
SetAttr(key, value string)
// RemoveAttr calls element.removeAttribute(key).
RemoveAttr(key string)
// SetText sets element.textContent.
// Safe for plain text — does not parse HTML.
SetText(text string)
// Checked returns the current checked state of a checkbox or radio button.
Checked() bool
// On registers a generic event handler (e.g., "click", "change", "input", "keydown").
On(eventType string, handler func(event Event))
// Focus sets focus to the element.
Focus()
// ScrollIntoView smooth-scrolls the element into view (e.g. to jump a
// horizontal scroll-snap container to a different panel programmatically —
// the browser resolves the final resting position against any
// scroll-snap-align on this element and its container).
ScrollIntoView()
// ScrollIntoViewInstant jumps the element into view with no animation —
// e.g. a circular scroll-snap strip wrapping from its last panel back to
// its first, where a smooth scroll would visibly travel across every
// panel in between in the wrong apparent direction. Every other
// navigation should keep using ScrollIntoView; reach for this one only
// at the wrap boundary.
ScrollIntoViewInstant()
// ScrollsX reports whether the element can actually scroll along the inline
// axis — its content is wider than its box.
//
// It exists because ScrollIntoView walks EVERY scrollable ancestor, not just
// the one the caller had in mind. A component that drives a horizontal strip
// on narrow screens and lays the same panels out side by side on wide ones
// has to know which it is looking at: on the wide layout the nearest
// scroller is somebody else's, and scrolling it moves the whole application.
ScrollsX() bool
}
Reference represents a reference to a DOM node. It provides methods for reading and interaction.
type SignalBool ¶
type SignalBool struct {
// contains filtered or unexported fields
}
SignalBool — same shape for class/attr toggles and Show conditions.
func DeriveBool ¶
func DeriveBool(compute func() bool) *SignalBool
func NewBool ¶
func NewBool(v bool) *SignalBool
func (*SignalBool) Get ¶
func (s *SignalBool) Get() bool
func (*SignalBool) Set ¶
func (s *SignalBool) Set(v bool)
func (*SignalBool) Toggle ¶
func (s *SignalBool) Toggle()
type SignalNodes ¶
type SignalNodes struct {
// contains filtered or unexported fields
}
SignalNodes is an observable list of rendered rows. No generics; the component builds the Elements.
func NewNodes ¶
func NewNodes(v ...*Element) *SignalNodes
func (*SignalNodes) Get ¶
func (s *SignalNodes) Get() []*Element
func (*SignalNodes) Set ¶
func (s *SignalNodes) Set(v []*Element)
type SignalString ¶
type SignalString struct {
// contains filtered or unexported fields
}
SignalString is an observable string cell. UI text/attr/input state lives here. Explicit Get/Set.
func DeriveString ¶
func DeriveString(compute func() string) *SignalString
DeriveString / DeriveBool: read-only computed cells. Re-run automatically when any signal the closure READS changes — no deps argument.
func NewString ¶
func NewString(v string) *SignalString
func (*SignalString) Get ¶
func (s *SignalString) Get() string
func (*SignalString) Set ¶
func (s *SignalString) Set(v string)
func (*SignalString) Update ¶
func (s *SignalString) Update(fn func(string) string)
type StateAttr ¶
StateAttr is anything that names a data-state attribute and the value the stylesheet selects on. widget.State satisfies it; nothing else needs to.
Declared here rather than imported so that dom keeps no dependency on the widget vocabulary — the same seam Class.AsAttr already uses in the other direction.
type TrustedHTML ¶
type TrustedHTML string
TrustedHTML es marcado que el AUTOR del programa garantiza seguro. El tipo existe para que meter datos no confiables en el documento no compile: no hay conversión implícita desde string, y el único constructor obliga a escribir una línea que un grep encuentra.
Regla: sólo literales del propio código, o el resultado de un builder de este ecosistema. NUNCA una cadena que venga de una petición, de una base de datos, de un perfil de OAuth o de otro servicio.
func Trust ¶
func Trust(html string) TrustedHTML
Trust marca html como confiable. Es la ÚNICA forma de producir un TrustedHTML, y su nombre es lo que hace auditable el programa: buscar "dom.Trust(" enumera todos los puntos donde el escapado se saltea a propósito.
Si estás por escribir dom.Trust(algoQueVinoDeAfuera), el defecto está en el diseño del llamador, no acá.
type ViewRenderer ¶
type ViewRenderer interface {
Render() *Element
}
ViewRenderer returns a Node tree for declarative UI.