html

package
v4.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 5, 2026 License: MIT Imports: 19 Imported by: 0

README

GWC | Html Library

GoWebComponents (GWC)

High-Level Overview

The html library exposes ergonomic HTML element constructors and helpers for building GWC component trees.

Public APIs

github.com/monstercameron/GoWebComponents/html (package html)
  • Functions: A, Aria, AriaSet, Article, Aside, Attr, Attrs, AutoFocus, Blockquote, Body, Br, Button, Case, Checked, Children, Class, ClassNames, Coalesce, Code, CustomElement, DNSPrefetch, Data, Dataset, Debounce, Default, Details, Dialog, Disabled, DisabledIf, Div, Em, Fieldset, FilterMap, FlatMap, Footer, For, Form, Fragment, H1, H2, H3, H4, H5, H6, Head, Header, HiddenInput, Hr, Href, Html, ID, If, IfElse, Img, Input, Join, Label, Legend, Li, Link, Main, Map, MapKeyed, Mark, Maybe, Meta, ModulePreload, Name, Nav, NoScript, OnBlur, OnChange, OnClick, OnFocus, OnInput, OnKeyDown, OnKeyUp, OnMouseUp, OnSubmit, Option, OrElse, P, Placeholder, Pre, Preconnect, Prefetch, Preload, Prevent, PropsOf, ReadOnly, ReadOnlyIf, RenderMarkdown, Required, ResolveMarkdownHref, Role, Rows, Script, Section, Select, Selected, SelectedIf, Small, Span, Src, Stop, Strong, Style, Summary, Switch, TabIndex, Table, Tag, Tbody, Td, Text, TextIf, Textarea, Textf, Th, Thead, Throttle, Time, Title, Tr, Type, Ul, Unless, Value, When, WithKey, WithProps
  • Types: CustomElementProps, MarkdownClasses, MarkdownRenderOptions, PropOption, Props, SwitchBranch
  • Variables: none
  • Constants: none
github.com/monstercameron/GoWebComponents/html/shorthand (package shorthand)
  • Functions: A, Aria, AriaSet, Article, Attr, Attrs, AutoFocus, Body, Br, Button, Case, Checked, Children, Class, ClassNames, Coalesce, Code, Data, Dataset, Debounce, Default, Details, Disabled, DisabledIf, Div, FilterMap, FlatMap, For, Form, Fragment, FromProps, H1, H2, H3, Head, Header, Hr, Href, Html, ID, If, IfElse, Img, Input, Join, Label, Li, Main, Map, MapKeyed, Mark, Maybe, Meta, Name, NoScript, OnBlur, OnChange, OnClick, OnFocus, OnInput, OnKeyDown, OnKeyUp, OnMouseUp, OnSubmit, Option, OrElse, P, Placeholder, Pre, Prevent, PropsOf, ReadOnly, ReadOnlyIf, Required, Role, Rows, Script, Section, Select, Selected, SelectedIf, Span, Src, Stop, Style, Summary, Switch, TabIndex, Table, Tag, Tbody, Td, Text, TextIf, Textf, Th, Thead, Throttle, Title, Tr, Type, Ul, Unless, Value, When, WithKey, WithProps
  • Types: PropOption, Props, SwitchBranch
  • Variables: none
  • Constants: none

Subfiles And Purpose

  • shorthand/ - Shorthand element helpers (4 files).
  • custom_elements_test.go - Tests for custom_elements behavior
  • doc.go - Package-level Go documentation
  • html.go - Core implementation for html
  • html_native_test.go - Tests for html_native behavior
  • html_wasm_test.go - Tests for html_wasm behavior
  • markdown.go - Core implementation for markdown
  • markdown_test.go - Tests for markdown behavior
  • sugar.go - Core implementation for sugar
  • sugar_test.go - Tests for sugar behavior

File Map

html/
|-- shorthand/
|   |-- doc.go
|   |-- shorthand.go
|   |-- shorthand_more_test.go
|   \-- shorthand_test.go
|-- custom_elements_test.go
|-- doc.go
|-- html.go
|-- html_native_test.go
|-- html_wasm_test.go
|-- markdown.go
|-- markdown_test.go
|-- sugar.go
\-- sugar_test.go

Documentation

Overview

Package html provides typed HTML element builders plus additive authoring sugar for GoWebComponents.

The package is designed to pair with the ui package:

func Counter() ui.Node {
    count := ui.UseState(0)
    increment := ui.UseEvent(func() {
        count.Update(func(v int) int { return v + 1 })
    })

    return html.Div(html.Props{},
        html.H1(html.Props{}, html.Text("Counter")),
        html.Button(html.Props{OnClick: increment}, html.Text("Increment")),
    )
}

html.Props keeps common DOM metadata explicit while still exposing Raw for escape-hatch attributes that do not need first-class fields yet. Use CustomElement when a browser-defined custom element needs explicit attribute-versus-property mapping instead of a single Raw map. Small convenience builders such as HiddenInput help with repetitive form markup without changing the underlying explicit props model. The package also exposes explicit markdown rendering helpers through RenderMarkdown(...) when applications want semantic ui.Node output without adding a second templating runtime.

The additive sugar layer also lives here rather than in ui. The current supported first pass is intentionally conservative:

  • existing typed builders such as Div, Button, P, Ul, and Input remain the stable host-element entrypoints
  • the companion html/shorthand package exposes mixed-argument host-tag wrappers such as shorthand.Div(...) without changing the typed html.Div(...) signatures
  • Children(...) handles mixed child normalization for shorthand composition
  • PropsOf(...), WithProps(...), plus Option helpers such as Class(...), ID(...), OnClick(...), Attr(...), and Data(...) reduce repetitive literal Props construction
  • Text(...), Textf(...), TextIf(...), When(...), ClassNames(...), If(...), IfElse(...), Unless(...), Map(...), MapKeyed(...), FlatMap(...), FilterMap(...), Join(...), Maybe(...), OrElse(...), Coalesce(...), Switch(...), Case(...), and Default(...) provide additive authoring sugar without introducing JSX, hidden reactivity, or a second runtime model

Children(...) currently accepts ui.Node, string, fmt.Stringer, func() string, nested []ui.Node, nested []string, nested []interface{}, and other slice or array values that recursively contain those forms. Nil values are skipped. Scalar fallbacks are stringified with fmt.Sprint(...).

False branches from If(...), IfElse(...), Unless(...), and TextIf(...) return nil rather than an empty fragment. ClassNames(...) recursively flattens nested class-part slices and drops empty fragments. Keyed list sugar is explicit: MapKeyed(...) writes the computed key onto each realized node rather than hiding reconciliation behavior behind cosmetic naming. Optional helpers stay pointer-based so zero values are not overloaded as absence.

The preferred happy-path import is an ordinary package import such as `html "github.com/monstercameron/GoWebComponents/v4/html"`. Dot-importing html is acceptable only in tiny example packages where collisions are tightly controlled. When one-call mixed props plus children is preferable, use the narrower companion package `github.com/monstercameron/GoWebComponents/html/shorthand`. Primitive DOM composition may use option-style helpers, but business components should continue to use explicit typed props structs.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func A

func A(parseProps Props, parseChildren ...ui.Node) ui.Node

A creates an anchor element.

func Abbr

func Abbr(parseProps Props, parseChildren ...ui.Node) ui.Node

Abbr creates an abbr element.

func ApplyPropOptions

func ApplyPropOptions(parseProps *Props, parseOptions ...PropOption)

ApplyPropOptions applies options to parseProps in place, without the defensive clone WithProps performs. Callers must own parseProps (and any maps it references): accumulation loops that build one fresh Props per element use this to avoid paying a full Props clone per option argument.

func Article

func Article(parseProps Props, parseChildren ...ui.Node) ui.Node

Article creates an article element.

func Aside

func Aside(parseProps Props, parseChildren ...ui.Node) ui.Node

Aside creates an aside element.

func Audio

func Audio(parseProps Props, parseChildren ...ui.Node) ui.Node

Audio creates an audio media element.

func B

func B(parseProps Props, parseChildren ...ui.Node) ui.Node

B creates a b element.

func Blockquote

func Blockquote(parseProps Props, parseChildren ...ui.Node) ui.Node

Blockquote creates a blockquote element.

func Body

func Body(parseProps Props, parseChildren ...ui.Node) ui.Node

Body creates a body element.

func Br

func Br(parseProps Props) ui.Node

Br creates a br line-break element.

func Button

func Button(parseProps Props, parseChildren ...ui.Node) ui.Node

Button creates a button element.

func Canvas

func Canvas(parseProps Props, parseChildren ...ui.Node) ui.Node

Canvas creates a canvas element.

func Caption

func Caption(parseProps Props, parseChildren ...ui.Node) ui.Node

Caption creates a table caption element.

func Children

func Children(parseValues ...any) []ui.Node

Children normalizes mixed shorthand child inputs into the existing []ui.Node builder contract.

func Circle

func Circle(parseProps Props) ui.Node

Circle creates an svg circle element.

func ClassMap

func ClassMap(parseValues map[string]bool) string

ClassMap returns a deterministic class string from true-valued map entries.

func ClassNames

func ClassNames(parseParts ...any) string

ClassNames joins class fragments while dropping empty values and normalizing whitespace.

func Coalesce

func Coalesce[T any](parseValues ...*T) *T

Coalesce returns the first non-nil pointer in order.

func Code

func Code(parseProps Props, parseChildren ...ui.Node) ui.Node

Code creates a code element.

func Col

func Col(parseProps Props) ui.Node

Col creates a col table element.

func Colgroup

func Colgroup(parseProps Props, parseChildren ...ui.Node) ui.Node

Colgroup creates a colgroup table element.

func Cond

func Cond(parseBranches ...CondBranch) ui.Node

Cond returns the node of the first branch whose condition is true, otherwise the Otherwise branch, otherwise nil. It fills the gap between IfElse (two-way) and Switch (value-equality) for three-or-more boolean conditions.

func CustomElement

func CustomElement(parseName string, parseProps CustomElementProps, parseChildren ...ui.Node) ui.Node

CustomElement creates a browser-defined custom element with explicit attribute and property channels.

func DNSPrefetch

func DNSPrefetch(parseHref string) ui.Node

DNSPrefetch creates a link[rel=dns-prefetch] element for the given href.

func Datalist

func Datalist(parseProps Props, parseChildren ...ui.Node) ui.Node

Datalist creates a datalist element.

func Debounce

func Debounce(parseDelay time.Duration, parseCallback any) any

Debounce delays callback execution until no newer event has arrived for delay.

func Defs

func Defs(parseProps Props, parseChildren ...ui.Node) ui.Node

Defs creates an svg defs element.

func Del

func Del(parseProps Props, parseChildren ...ui.Node) ui.Node

Del creates a del element.

func Details

func Details(parseProps Props, parseChildren ...ui.Node) ui.Node

Details creates a details disclosure element.

func Dialog

func Dialog(parseProps Props, parseChildren ...ui.Node) ui.Node

Dialog creates a dialog element.

func Div

func Div(parseProps Props, parseChildren ...ui.Node) ui.Node

Div creates a div element.

func Em

func Em(parseProps Props, parseChildren ...ui.Node) ui.Node

Em creates an em emphasis element.

func Fieldset

func Fieldset(parseProps Props, parseChildren ...ui.Node) ui.Node

Fieldset creates a fieldset element.

func Figcaption

func Figcaption(parseProps Props, parseChildren ...ui.Node) ui.Node

Figcaption creates a figcaption element.

func Figure

func Figure(parseProps Props, parseChildren ...ui.Node) ui.Node

Figure creates a figure element.

func FilterMap

func FilterMap[T any](parseItems []T, render func(T) (ui.Node, bool)) []ui.Node

FilterMap renders each item conditionally and preserves order for realized nodes.

func FlatMap

func FlatMap[T any](parseItems []T, render func(T) []ui.Node) []ui.Node

FlatMap renders each item into zero or more nodes and flattens the results.

func Footer(parseProps Props, parseChildren ...ui.Node) ui.Node

Footer creates a footer element.

func Form

func Form(parseProps Props, parseChildren ...ui.Node) ui.Node

Form creates a form element.

func Fragment

func Fragment(parseChildren ...ui.Node) ui.Node

Fragment groups children without introducing an extra host element.

func G

func G(parseProps Props, parseChildren ...ui.Node) ui.Node

G creates an svg group element.

func H1

func H1(parseProps Props, parseChildren ...ui.Node) ui.Node

H1 creates an h1 heading element.

func H2

func H2(parseProps Props, parseChildren ...ui.Node) ui.Node

H2 creates an h2 heading element.

func H3

func H3(parseProps Props, parseChildren ...ui.Node) ui.Node

H3 creates an h3 heading element.

func H4

func H4(parseProps Props, parseChildren ...ui.Node) ui.Node

H4 creates an h4 heading element.

func H5

func H5(parseProps Props, parseChildren ...ui.Node) ui.Node

H5 creates an h5 heading element.

func H6

func H6(parseProps Props, parseChildren ...ui.Node) ui.Node

H6 creates an h6 heading element.

func Head(parseProps Props, parseChildren ...ui.Node) ui.Node

Head creates a head element.

func Header(parseProps Props, parseChildren ...ui.Node) ui.Node

Header creates a header element.

func HiddenInput

func HiddenInput(parseName string, parseValue string) ui.Node

HiddenInput creates a hidden input element with the given name and value.

func Hr

func Hr(parseProps Props) ui.Node

Hr creates an hr horizontal rule element.

func Html

func Html(parseProps Props, parseChildren ...ui.Node) ui.Node

Html creates an html root element.

func I

func I(parseProps Props, parseChildren ...ui.Node) ui.Node

I creates an i element.

func If

func If(isCondition bool, parseNode ui.Node) ui.Node

If returns the node only when the condition is true.

func IfElse

func IfElse(isCondition bool, parseWhenTrue ui.Node, parseWhenFalse ui.Node) ui.Node

IfElse selects between two node branches inline.

func Iframe

func Iframe(parseProps Props, parseChildren ...ui.Node) ui.Node

Iframe creates an iframe element.

func Img

func Img(parseProps Props) ui.Node

Img creates an img image element.

func Input

func Input(parseProps Props) ui.Node

Input creates an input element.

func Ins

func Ins(parseProps Props, parseChildren ...ui.Node) ui.Node

Ins creates an ins element.

func Join

func Join(parseSeparator ui.Node, parseNodes ...ui.Node) []ui.Node

Join inserts a separator between realized nodes only.

func Kbd

func Kbd(parseProps Props, parseChildren ...ui.Node) ui.Node

Kbd creates a kbd element.

func Label

func Label(parseProps Props, parseChildren ...ui.Node) ui.Node

Label creates a label element.

func Legend

func Legend(parseProps Props, parseChildren ...ui.Node) ui.Node

Legend creates a legend element.

func Li

func Li(parseProps Props, parseChildren ...ui.Node) ui.Node

Li creates an li list-item element.

func Line

func Line(parseProps Props) ui.Node

Line creates an svg line element.

func Link(parseProps Props) ui.Node

Link creates a typed link element.

func Main

func Main(parseProps Props, parseChildren ...ui.Node) ui.Node

Main creates a main element.

func Map

func Map[T any](parseItems []T, render func(T) ui.Node) []ui.Node

Map renders a typed slice into ui.Node values while preserving order.

func MapIndexed

func MapIndexed[T any](parseItems []T, render func(parseIndex int, parseItem T) ui.Node) []ui.Node

MapIndexed renders a typed slice into ui.Node values with the element index, preserving order. It is Map with the index threaded into the render callback.

func MapKeyed

func MapKeyed[T any](parseItems []T, parseKey func(T) any, render func(T) ui.Node) []ui.Node

MapKeyed renders a typed slice into keyed ui.Node values while preserving order.

func MapKeyedComponent

func MapKeyedComponent[T any](parseItems []T, parseKey func(T) any, render func(T) ui.Node) []ui.Node

MapKeyedComponent renders each item as its own keyed component (its own fiber), so the render func may legally use hooks and On* event handlers directly — including UseState/UseEvent — without the "no hooks in a variable-length loop" gotcha (G1). It is the sanctioned alternative to hand-extracting a row component: per-row hook state is isolated and persists across renders by key.

MapKeyedComponent(rows, func(r Row) any { return r.ID }, func(r Row) ui.Node {
    open := ui.UseState(false)                       // legal: own fiber
    return Button(OnClick(func() { open.Set(!open.Get()) }), r.Name)
})

func MapKeyedIndexed

func MapKeyedIndexed[T any](parseItems []T, parseKey func(parseIndex int, parseItem T) any, render func(parseIndex int, parseItem T) ui.Node) []ui.Node

MapKeyedIndexed renders a typed slice into keyed ui.Node values with the element index threaded into both the key and the render callback.

func MapKeyedOr

func MapKeyedOr[T any](parseItems []T, parseKey func(T) any, render func(T) ui.Node, parseFallback ui.Node) ui.Node

MapKeyedOr renders the keyed mapped slice as a fragment when items exist, otherwise the fallback node. It is MapOr with per-item reconciliation keys, for empty-state lists whose rows must keep identity across reorders and removals.

func MapOr

func MapOr[T any](parseItems []T, render func(T) ui.Node, parseFallback ui.Node) ui.Node

MapOr renders the mapped slice as a fragment when items exist, otherwise the fallback node. It removes the hand-written IfElse(len==0, empty, Map(...)) empty-state idiom.

func Mark

func Mark(parseProps Props, parseChildren ...ui.Node) ui.Node

Mark creates a mark element.

func Markdown

func Markdown(parseSource string, parseOptions ...MarkdownRenderOptions) []ui.Node

Markdown renders Markdown source into nodes via RenderMarkdown, exposing it on the shorthand surface. Untrusted source is still scheme-sanitized; raw HTML is never emitted (route untrusted HTML through the sanitize package instead).

func Maybe

func Maybe[T any](parseValue *T, render func(T) ui.Node) ui.Node

Maybe renders a node only when a pointer value is present.

func MaybeOr

func MaybeOr[T any](parseValue *T, render func(T) ui.Node, parseFallback ui.Node) ui.Node

MaybeOr renders from the pointed value when present, otherwise the fallback node. It is Maybe with an else branch.

func Meta

func Meta(parseProps Props) ui.Node

Meta creates a meta element.

func Meter

func Meter(parseProps Props, parseChildren ...ui.Node) ui.Node

Meter creates a meter element.

func ModulePreload

func ModulePreload(parseHref string) ui.Node

ModulePreload creates a link[rel=modulepreload] element for module scripts.

func Nav(parseProps Props, parseChildren ...ui.Node) ui.Node

Nav creates a nav element.

func NoScript

func NoScript(parseProps Props, parseChildren ...ui.Node) ui.Node

NoScript creates a noscript element.

func Ol

func Ol(parseProps Props, parseChildren ...ui.Node) ui.Node

Ol creates an ol ordered-list element.

func Optgroup

func Optgroup(parseProps Props, parseChildren ...ui.Node) ui.Node

Optgroup creates an optgroup element.

func Option

func Option(parseProps Props, parseChildren ...ui.Node) ui.Node

Option creates an option element.

func OrElse

func OrElse[T any](parseValue *T, parseFallback T) T

OrElse returns the pointed value when present, otherwise the fallback.

func Output

func Output(parseProps Props, parseChildren ...ui.Node) ui.Node

Output creates an output element.

func P

func P(parseProps Props, parseChildren ...ui.Node) ui.Node

P creates a p paragraph element.

func Passive

func Passive(parseCallback any) any

Passive marks an event callback to be attached as a passive listener when the runtime adapter supports listener options.

func Path

func Path(parseProps Props) ui.Node

Path creates an svg path element.

func Picture

func Picture(parseProps Props, parseChildren ...ui.Node) ui.Node

Picture creates a picture element.

func Polygon

func Polygon(parseProps Props) ui.Node

Polygon creates an svg polygon element.

func Polyline

func Polyline(parseProps Props) ui.Node

Polyline creates an svg polyline element.

func Pre

func Pre(parseProps Props, parseChildren ...ui.Node) ui.Node

Pre creates a pre preformatted element.

func Preconnect

func Preconnect(parseHref string) ui.Node

Preconnect creates a link[rel=preconnect] element for the given href.

func Prefetch

func Prefetch(parseHref string) ui.Node

Prefetch creates a link[rel=prefetch] element for the given href.

func Preload

func Preload(parseHref, parseAs string) ui.Node

Preload creates a link[rel=preload] element for the given href and as type.

func Prevent

func Prevent(parseCallback any) any

Prevent wraps a callback so the event default is prevented before callback execution.

func Progress

func Progress(parseProps Props, parseChildren ...ui.Node) ui.Node

Progress creates a progress element.

func Range

func Range(parseCount int, render func(parseIndex int) ui.Node) []ui.Node

Range renders parseCount nodes, invoking render with each index from 0 to parseCount-1. A non-positive count renders nothing.

func RawHTML

func RawHTML(parseMarkup string) []ui.Node

RawHTML parses sanitized markup into nodes. Safe for untrusted input.

Div(html.RawHTML(userSuppliedMarkdownHTML)...)

func RawHTMLUnsafe

func RawHTMLUnsafe(parseMarkup string) []ui.Node

RawHTMLUnsafe parses markup WITHOUT sanitization. The content is still built as a real node tree (no innerHTML), but nothing is stripped — only pass markup you fully control (e.g. a bundled SVG icon). The name is intentionally alarming so its use is greppable in review.

func RawHTMLWith

func RawHTMLWith(parseMarkup string, parsePolicy sanitize.Policy) []ui.Node

RawHTMLWith parses markup sanitized under a caller-provided policy.

func Rect

func Rect(parseProps Props) ui.Node

Rect creates an svg rect element.

func RenderMarkdown

func RenderMarkdown(parseMarkdown string, parseOptions ...MarkdownRenderOptions) []ui.Node

RenderMarkdown parses markdown text and returns semantic ui.Node values.

func Repeat

func Repeat(parseCount int, parseNode ui.Node) []ui.Node

Repeat renders the same node parseCount times. A non-positive count renders nothing. Use Range when each instance must differ or carry a distinct key.

func ResolveMarkdownHref

func ResolveMarkdownHref(parseSourcePath, parseDestination string) string

ResolveMarkdownHref resolves a markdown destination against the source document path.

func SanitizeMarkdownHref

func SanitizeMarkdownHref(parseDestination string, parseAllowed []string) string

SanitizeMarkdownHref returns destination unchanged when it carries no scheme (relative, absolute-path, or fragment) or an allowed scheme, and returns "" otherwise. The allowed argument lists schemes without the trailing colon; a nil or empty list uses the default allowlist (http, https, mailto). Scheme detection tolerates the usual obfuscations - leading/embedded whitespace and control characters (java\tscript:), mixed case (JavaScript:), and a leading space ( javascript:) - by normalizing the scheme token before the check.

Example

ExampleSanitizeMarkdownHref shows the URL-scheme allowlist used by RenderMarkdown: safe schemes pass through, dangerous ones are dropped to "".

package main

import (
	"fmt"

	"github.com/monstercameron/GoWebComponents/v4/html"
)

func main() {
	fmt.Printf("%q\n", html.SanitizeMarkdownHref("https://example.test", nil))
	fmt.Printf("%q\n", html.SanitizeMarkdownHref("guide.md#section", nil))
	fmt.Printf("%q\n", html.SanitizeMarkdownHref("javascript:alert(1)", nil))
}
Output:
"https://example.test"
"guide.md#section"
""

func Script

func Script(parseProps Props, parseChildren ...ui.Node) ui.Node

Script creates a script element.

func Section

func Section(parseProps Props, parseChildren ...ui.Node) ui.Node

Section creates a section element.

func Select

func Select(parseProps Props, parseChildren ...ui.Node) ui.Node

Select creates a select element.

func Show

func Show(isCondition bool, parseNode ui.Node) ui.Node

Show returns the node when the condition is true; otherwise it returns the same node with the hidden attribute set so it stays mounted but is not displayed. Use If/Unless instead when the node should be removed from the tree.

func Small

func Small(parseProps Props, parseChildren ...ui.Node) ui.Node

Small creates a small element.

func Source

func Source(parseProps Props) ui.Node

Source creates a source media element.

func Span

func Span(parseProps Props, parseChildren ...ui.Node) ui.Node

Span creates a span element.

func Stop

func Stop(parseCallback any) any

Stop wraps a callback so propagation is stopped before callback execution.

func Strong

func Strong(parseProps Props, parseChildren ...ui.Node) ui.Node

Strong creates a strong element.

func Sub

func Sub(parseProps Props, parseChildren ...ui.Node) ui.Node

Sub creates a sub element.

func Summary

func Summary(parseProps Props, parseChildren ...ui.Node) ui.Node

Summary creates a summary element.

func Sup

func Sup(parseProps Props, parseChildren ...ui.Node) ui.Node

Sup creates a sup element.

func Svg

func Svg(parseProps Props, parseChildren ...ui.Node) ui.Node

Svg creates an svg element with the SVG namespace attribute set by default.

func Switch

func Switch(parseValue any, parseBranches ...SwitchBranch) ui.Node

Switch selects the first matching branch and otherwise falls back to Default.

func Table

func Table(parseProps Props, parseChildren ...ui.Node) ui.Node

Table creates a table element.

func Tag

func Tag(parseName string, parseProps Props, parseChildren ...ui.Node) ui.Node

Tag creates a node for an arbitrary HTML tag name.

func Tbody

func Tbody(parseProps Props, parseChildren ...ui.Node) ui.Node

Tbody creates a tbody element.

func Td

func Td(parseProps Props, parseChildren ...ui.Node) ui.Node

Td creates a td table-data element.

func Text

func Text(parseContent any) ui.Node

Text creates a text node from a string-like value.

func TextIf

func TextIf(isCondition bool, parseContent any) ui.Node

TextIf emits a text node only when the condition is true.

func TextLines

func TextLines(parseText string) []ui.Node

TextLines splits text on newlines into text nodes separated by <br> elements, preserving blank lines. A string with no newline yields a single text node.

func Textarea

func Textarea(parseProps Props, parseChildren ...ui.Node) ui.Node

Textarea creates a textarea element.

func Textf

func Textf(format string, parseArgs ...any) ui.Node

Textf formats a text node without requiring an explicit fmt.Sprintf call first.

func Tfoot

func Tfoot(parseProps Props, parseChildren ...ui.Node) ui.Node

Tfoot creates a tfoot table section.

func Th

func Th(parseProps Props, parseChildren ...ui.Node) ui.Node

Th creates a th table-header element.

func Thead

func Thead(parseProps Props, parseChildren ...ui.Node) ui.Node

Thead creates a thead element.

func Throttle

func Throttle(parseInterval time.Duration, parseCallback any) any

Throttle invokes immediately and then at most once per interval with the latest pending event.

func Time

func Time(parseProps Props, parseChildren ...ui.Node) ui.Node

Time creates a time element.

func Tr

func Tr(parseProps Props, parseChildren ...ui.Node) ui.Node

Tr creates a tr table-row element.

func Track

func Track(parseProps Props) ui.Node

Track creates a track media element.

func U

func U(parseProps Props, parseChildren ...ui.Node) ui.Node

U creates a u element.

func Ul

func Ul(parseProps Props, parseChildren ...ui.Node) ui.Node

Ul creates a ul unordered-list element.

func Unless

func Unless(isCondition bool, parseNode ui.Node) ui.Node

Unless returns the node only when the condition is false.

func Use

func Use(parseProps Props) ui.Node

Use creates an svg use element.

func Video

func Video(parseProps Props, parseChildren ...ui.Node) ui.Node

Video creates a video media element.

func When

func When(isCondition bool, parseClassName string) string

When returns a class fragment only when the condition is true.

func WithChildren

func WithChildren(parseNode ui.Node, parseChildren ...ui.Node) ui.Node

WithChildren appends children to an already-built node and returns it. Nil children are skipped.

func WithKey

func WithKey(parseNode ui.Node, parseKey any) ui.Node

WithKey applies a reconciliation key to an existing node explicitly.

Types

type Binding

type Binding interface {
	Get() string
	Set(string)
}

Binding is a two-way-bindable string value: any handle with Get() string and Set(string). It lets BindTo wire the V4 reactive handles — state.Signal[string], state.GlobalAtom[string], a state.Atom[string] handle — to a controlled input with the same one-call ergonomics as Bind for ui.State.

type CondBranch

type CondBranch struct {
	// contains filtered or unexported fields
}

CondBranch describes one boolean branch in a Cond expression helper.

func Match

func Match(isCondition bool, parseNode ui.Node) CondBranch

Match creates a boolean branch for Cond. The first branch whose condition is true wins.

func Otherwise

func Otherwise(parseNode ui.Node) CondBranch

Otherwise creates the fallback branch for Cond, taken only when no Match condition is true. It is the boolean-chain analogue of Switch's Default.

type CustomElementProps

type CustomElementProps struct {
	Props      Props
	Attributes map[string]string
	Presence   map[string]bool
	Properties map[string]any
}

CustomElementProps makes attribute-versus-property intent explicit for browser-defined custom elements and web components.

type DataAttribute added in v4.2.0

type DataAttribute struct {
	Name  string
	Value string
}

DataAttribute names one data-* attribute (Name is the suffix after "data-") for the zero-allocation Props.DataAttr field.

type MarkdownClasses

type MarkdownClasses struct {
	Heading1           string
	Heading2           string
	Heading3           string
	Heading4           string
	Heading5           string
	Heading6           string
	Paragraph          string
	Blockquote         string
	List               string
	OrderedList        string
	UnorderedList      string
	ListItem           string
	CodeBlockContainer string
	CodeBlockLabel     string
	CodeBlockPre       string
	InlineCode         string
	Strong             string
	Emphasis           string
	Link               string
	HorizontalRule     string
}

MarkdownClasses configures optional class names applied to rendered markdown nodes.

type MarkdownRenderOptions

type MarkdownRenderOptions struct {
	SourcePath     string
	ResolveHref    func(sourcePath, destination string) string
	Classes        MarkdownClasses
	CodeBlockLabel string
	LinkTarget     string
	LinkRel        string
	// AllowedURLSchemes overrides the scheme allowlist applied to link, image,
	// and autolink destinations. When nil the default allowlist is used
	// (http, https, mailto); relative paths, absolute paths, and fragments
	// carry no scheme and are always allowed. Any other scheme - notably
	// javascript:, data:, and vbscript: - is dropped so user-supplied markdown
	// cannot smuggle an executable URL into an href or src sink. Supply schemes
	// without the trailing colon (for example []string{"http", "https",
	// "mailto", "data"} to additionally permit inline data: images).
	AllowedURLSchemes []string
}

MarkdownRenderOptions configures markdown rendering into ui.Node values.

type PropOption

type PropOption interface {
	// contains filtered or unexported methods
}

PropOption mutates Props through an explicit additive helper.

func Accept

func Accept(parseValue string) PropOption

Accept sets the accept attribute on a Props.

func Alt

func Alt(parseValue string) PropOption

Alt sets the alt attribute on a Props.

func Aria

func Aria(parseName string, parseValue string) PropOption

Aria sets a single aria-* attribute on the Props.

func AriaSet

func AriaSet(parseValues map[string]string) PropOption

AriaSet merges multiple aria-* attributes into the Props.

func Attr

func Attr(parseKey string, parseValue any) PropOption

Attr sets a single raw HTML attribute on the Props.

func AttrIf

func AttrIf(isCondition bool, parseKey string, parseValue any) PropOption

AttrIf applies a raw attribute only when the condition is true, otherwise it is a no-op option (nil, which PropsOf/WithProps skip).

func Attrs

func Attrs(parseValues map[string]any) PropOption

Attrs merges multiple raw HTML attributes into the Props.

func AutoComplete

func AutoComplete(parseValue string) PropOption

AutoComplete sets the autocomplete attribute on a Props.

func AutoFocus

func AutoFocus(parseValues ...bool) PropOption

AutoFocus sets the autofocus boolean on a Props; passes true when no argument is given.

func Bind

func Bind(parseState ui.State[string]) PropOption

Bind wires a controlled input to a string State in one call (U6): it sets the element's value from the state and updates the state on input. Replaces the manual Value(s.Get()) + OnInput(func(v){ s.Set(v) }) pairing.

name := ui.UseState("")
html.Input(html.Bind(name))

func BindFunc

func BindFunc(parseGet func() string, parseSet func(string)) PropOption

BindFunc is the general two-way binding: it sets the input value to get() and registers an oninput handler that calls set(value). Use it when the source is not a single handle (e.g. a struct field reached through a closure). A nil getter leaves the value unset; a nil setter makes input a no-op.

func BindTo

func BindTo(parseTarget Binding) PropOption

BindTo two-way binds a text input to any Binding (e.g. a state.Signal[string]): it sets the input value to target.Get() and registers an oninput handler that writes target.Set(value). Like Bind, call it at a stable render position. A nil target is a no-op.

name := state.NewSignal("")
h.Input(h.Type("text"), h.BindTo(name))

func Checked

func Checked(parseValues ...bool) PropOption

Checked sets the checked boolean on a Props; passes true when no argument is given.

func Class

func Class(parseValue string) PropOption

Class sets the class attribute on a Props.

func ClassIf

func ClassIf(isCondition bool, parseClass string) PropOption

ClassIf sets the class attribute only when the condition is true, otherwise it is a no-op option. For composing one class string from many conditions use ClassNames with When instead.

func ColSpan

func ColSpan(parseValue int) PropOption

ColSpan sets the colSpan property on a Props.

func Cols

func Cols(parseValue int) PropOption

Cols sets the cols attribute on a Props.

func Data

func Data(parseName string, parseValue string) PropOption

Data sets a single data-* attribute on the Props.

func Dataset

func Dataset(parseValues map[string]string) PropOption

Dataset merges multiple data-* attributes into the Props.

func Dir

func Dir(parseValue string) PropOption

Dir sets the dir attribute on a Props.

func Disabled

func Disabled(parseValues ...bool) PropOption

Disabled sets the disabled boolean on a Props; passes true when no argument is given.

func DisabledIf

func DisabledIf(isCondition bool) PropOption

DisabledIf sets the disabled boolean conditionally on a Props.

func For

func For(parseValue string) PropOption

For sets the for attribute on a Props.

func Height

func Height(parseValue string) PropOption

Height sets the height attribute on a Props.

func Hidden

func Hidden(parseValues ...bool) PropOption

Hidden sets the hidden boolean on a Props; passes true when no argument is given.

func Href

func Href(parseValue string) PropOption

Href sets the href attribute on a Props.

func ID

func ID(parseValue string) PropOption

ID sets the id attribute on a Props.

func Lang

func Lang(parseValue string) PropOption

Lang sets the lang attribute on a Props.

func Loading

func Loading(parseValue string) PropOption

Loading sets the loading attribute on a Props.

func Max

func Max(parseValue string) PropOption

Max sets the max attribute on a Props.

func MaxLength

func MaxLength(parseValue int) PropOption

MaxLength sets the maxLength property on a Props.

func Min

func Min(parseValue string) PropOption

Min sets the min attribute on a Props.

func MinLength

func MinLength(parseValue int) PropOption

MinLength sets the minLength property on a Props.

func Multiple

func Multiple(parseValues ...bool) PropOption

Multiple sets the multiple boolean on a Props; passes true when no argument is given.

func Name

func Name(parseValue string) PropOption

Name sets the name attribute on a Props.

func OnAnimationEnd

func OnAnimationEnd(parseCallback any) PropOption

OnAnimationEnd registers an onanimationend event handler on the Props.

func OnBlur

func OnBlur(parseCallback any) PropOption

OnBlur registers an onblur event handler on the Props.

func OnChange

func OnChange(parseCallback any) PropOption

OnChange registers an onchange event handler on the Props.

func OnClick

func OnClick(parseCallback any) PropOption

OnClick registers an onclick event handler on the Props.

func OnClickParallel

func OnClickParallel(parseSlotID string, parseCallback any) PropOption

OnClickParallel registers one local click handler and marks the node as a public parallel-region click slot.

func OnContextMenu

func OnContextMenu(parseCallback any) PropOption

OnContextMenu registers an oncontextmenu event handler on the Props.

func OnDoubleClick

func OnDoubleClick(parseCallback any) PropOption

OnDoubleClick registers an ondblclick event handler on the Props.

func OnDragEnd

func OnDragEnd(parseCallback any) PropOption

OnDragEnd registers an ondragend event handler on the Props.

func OnDragOver

func OnDragOver(parseCallback any) PropOption

OnDragOver registers an ondragover event handler on the Props.

func OnDragStart

func OnDragStart(parseCallback any) PropOption

OnDragStart registers an ondragstart event handler on the Props.

func OnDrop

func OnDrop(parseCallback any) PropOption

OnDrop registers an ondrop event handler on the Props.

func OnError

func OnError(parseCallback any) PropOption

OnError registers an onerror event handler on the Props.

func OnFocus

func OnFocus(parseCallback any) PropOption

OnFocus registers an onfocus event handler on the Props.

func OnInput

func OnInput(parseCallback any) PropOption

OnInput registers an oninput event handler on the Props.

func OnKeyDown

func OnKeyDown(parseCallback any) PropOption

OnKeyDown registers an onkeydown event handler on the Props.

func OnKeyUp

func OnKeyUp(parseCallback any) PropOption

OnKeyUp registers an onkeyup event handler on the Props.

func OnLoad

func OnLoad(parseCallback any) PropOption

OnLoad registers an onload event handler on the Props.

func OnMouseDown

func OnMouseDown(parseCallback any) PropOption

OnMouseDown registers an onmousedown event handler on the Props.

func OnMouseEnter

func OnMouseEnter(parseCallback any) PropOption

OnMouseEnter registers an onmouseenter event handler on the Props.

func OnMouseLeave

func OnMouseLeave(parseCallback any) PropOption

OnMouseLeave registers an onmouseleave event handler on the Props.

func OnMouseUp

func OnMouseUp(parseCallback any) PropOption

OnMouseUp registers an onmouseup event handler on the Props.

func OnPointerDown

func OnPointerDown(parseCallback any) PropOption

OnPointerDown registers an onpointerdown event handler on the Props.

func OnPointerMove

func OnPointerMove(parseCallback any) PropOption

OnPointerMove registers an onpointermove event handler on the Props.

func OnPointerUp

func OnPointerUp(parseCallback any) PropOption

OnPointerUp registers an onpointerup event handler on the Props.

func OnScroll

func OnScroll(parseCallback any) PropOption

OnScroll registers an onscroll event handler on the Props.

func OnSubmit

func OnSubmit(parseCallback any) PropOption

OnSubmit registers an onsubmit event handler on the Props.

func OnTouchEnd

func OnTouchEnd(parseCallback any) PropOption

OnTouchEnd registers an ontouchend event handler on the Props.

func OnTouchMove

func OnTouchMove(parseCallback any) PropOption

OnTouchMove registers an ontouchmove event handler on the Props.

func OnTouchStart

func OnTouchStart(parseCallback any) PropOption

OnTouchStart registers an ontouchstart event handler on the Props.

func OnTransitionEnd

func OnTransitionEnd(parseCallback any) PropOption

OnTransitionEnd registers an ontransitionend event handler on the Props.

func OnWheel

func OnWheel(parseCallback any) PropOption

OnWheel registers an onwheel event handler on the Props.

func Open

func Open(parseValues ...bool) PropOption

Open sets the open boolean on a Props; passes true when no argument is given.

func Pattern

func Pattern(parseValue string) PropOption

Pattern sets the pattern attribute on a Props.

func Placeholder

func Placeholder(parseValue string) PropOption

Placeholder sets the placeholder attribute on a Props.

func ReadOnly

func ReadOnly(parseValues ...bool) PropOption

ReadOnly sets the readonly boolean on a Props; passes true when no argument is given.

func ReadOnlyIf

func ReadOnlyIf(isCondition bool) PropOption

ReadOnlyIf sets the readonly boolean conditionally on a Props.

func Ref

func Ref(parseRef ui.DOMRef) PropOption

Ref binds a ui.DOMRef to the element so its live DOM node is published into the ref on mount (and cleared on unmount). It carries the ref's sink through the reserved props key, which the reconciler skips as a DOM attribute. Attach at most one Ref per element, and attach it at mount time.

r := ui.UseDOMRef()
html.Input(html.Ref(r))

A zero-value DOMRef (not produced by UseDOMRef) yields a no-op.

func Rel

func Rel(parseValue string) PropOption

Rel sets the rel attribute on a Props.

func Required

func Required(parseValues ...bool) PropOption

Required sets the required boolean on a Props; passes true when no argument is given.

func Role

func Role(parseValue string) PropOption

Role sets the role attribute on a Props.

func RowSpan

func RowSpan(parseValue int) PropOption

RowSpan sets the rowSpan property on a Props.

func Rows

func Rows(parseValue int) PropOption

Rows sets the rows attribute on a Props.

func Selected

func Selected(parseValues ...bool) PropOption

Selected sets the selected boolean on a Props; passes true when no argument is given.

func SelectedIf

func SelectedIf(isCondition bool) PropOption

SelectedIf sets the selected boolean conditionally on a Props.

func Src

func Src(parseValue string) PropOption

Src sets the src attribute on a Props.

func Step

func Step(parseValue string) PropOption

Step sets the step attribute on a Props.

func Style

func Style(parseValues map[string]string) PropOption

Style merges the given CSS style map into the Props Style field.

func StyleIf

func StyleIf(isCondition bool, parseValues map[string]string) PropOption

StyleIf applies inline styles only when the condition is true, otherwise it is a no-op option.

func StyleVar

func StyleVar(parseName string, parseValue string) PropOption

StyleVar sets a single inline style property, typically a CSS custom property such as "--accent". It is Style with one entry.

func TabIndex

func TabIndex(parseValue int) PropOption

TabIndex sets the tabindex attribute on a Props.

When parseValue is 0 the key is written into Raw["tabIndex"] so that toRuntimeProps emits it explicitly. Props.TabIndex==0 is silently dropped by toRuntimeProps; prefer html.TabIndex(0) when tabindex=0 is intentional.

func Target

func Target(parseValue string) PropOption

Target sets the target attribute on a Props.

func Title

func Title(parseValue string) PropOption

Title sets the title attribute on a Props.

func Type

func Type(parseValue string) PropOption

Type sets the type attribute on a Props.

func Value

func Value(parseValue string) PropOption

Value sets the value attribute on a Props.

When parseValue is the empty string the key is written into Raw["value"] so that toRuntimeProps emits it even for an empty controlled input. Using Props.Value="" directly is silently dropped by toRuntimeProps; prefer html.Value("") or html.Attr("value","") when you need to clear a controlled input via the typed-builder path.

func Width

func Width(parseValue string) PropOption

Width sets the width attribute on a Props.

type Props

type Props struct {
	ID    string
	Class string
	Key   string
	Slot  string
	Title string
	Type  string
	Name  string
	// Value is the input/option value.  An empty string is silently omitted by
	// toRuntimeProps; use html.Value("") (the PropOption) or Raw["value"]="" to
	// explicitly emit an empty controlled-input value.
	Value        string
	Placeholder  string
	Accept       string
	Href         string
	Src          string
	Alt          string
	For          string
	Role         string
	Target       string
	Rel          string
	As           string
	Action       string
	Method       string
	EncType      string
	AutoComplete string
	Min          string
	Max          string
	Step         string
	Pattern      string
	Lang         string
	Dir          string
	Width        string
	Height       string
	Loading      string

	Rows int
	Cols int
	// TabIndex of 0 is silently omitted by toRuntimeProps; use html.TabIndex(0)
	// (the PropOption) or Raw["tabIndex"]=0 to make tabindex=0 explicit.
	TabIndex  int
	MaxLength int
	MinLength int
	ColSpan   int
	RowSpan   int

	Checked   bool
	Disabled  bool
	Selected  bool
	Required  bool
	ReadOnly  bool
	Hidden    bool
	Multiple  bool
	AutoFocus bool
	Open      bool

	Style map[string]string
	Data  map[string]string
	Aria  map[string]string
	Raw   map[string]any

	// DataAttr sets one data-* attribute without allocating a Data map — the
	// dominant single-attribute case (e.g. a per-row id) costs zero
	// allocations this way. Name is the part after "data-". Combine with the
	// Data map for additional attributes; both land in the same
	// deterministically sorted segment.
	DataAttr DataAttribute

	// Text sets the element's entire text content directly. The equivalent
	// html.Text(...) child form allocates a full throwaway Element that Tag
	// discards after extracting the string — one of the highest-frequency
	// allocation sites in text-heavy trees. Ignored when children are passed
	// or when empty (use a Text child for explicit empty text).
	Text string

	OnClick         ui.Handler
	OnInput         ui.Handler
	OnChange        ui.Handler
	OnSubmit        ui.Handler
	OnKeyDown       ui.Handler
	OnKeyUp         ui.Handler
	OnMouseUp       ui.Handler
	OnMouseDown     ui.Handler
	OnMouseEnter    ui.Handler
	OnMouseLeave    ui.Handler
	OnDoubleClick   ui.Handler
	OnContextMenu   ui.Handler
	OnWheel         ui.Handler
	OnTransitionEnd ui.Handler
	OnAnimationEnd  ui.Handler
	OnLoad          ui.Handler
	OnError         ui.Handler
	OnPointerDown   ui.Handler
	OnPointerMove   ui.Handler
	OnPointerUp     ui.Handler
	OnTouchStart    ui.Handler
	OnTouchMove     ui.Handler
	OnTouchEnd      ui.Handler
	OnDragStart     ui.Handler
	OnDragOver      ui.Handler
	OnDrop          ui.Handler
	OnDragEnd       ui.Handler
	OnFocus         ui.Handler
	OnBlur          ui.Handler
	OnScroll        ui.Handler
}

Props contains the common HTML attributes and event handlers supported by the typed builders.

func DefaultProps

func DefaultProps(parseProps Props, parseDefaults Props) Props

DefaultProps returns parseProps with parseDefaults filling only the fields parseProps leaves zero. Explicit values in parseProps always win.

func MergeProps

func MergeProps(parseBase Props, parseOverride Props) Props

MergeProps overlays parseOverride onto parseBase: each non-zero scalar field of parseOverride wins, and the Style/Data/Aria/Raw maps are unioned with parseOverride taking precedence per key. Neither input is mutated. Use it to forward and override props through a wrapper component.

func PropsOf

func PropsOf(parseOptions ...PropOption) Props

PropsOf builds Props from additive prop options using last-write-wins semantics.

func WithProps

func WithProps(parseBase Props, parseOptions ...PropOption) Props

WithProps applies additive prop options onto an existing Props value.

type SwitchBranch

type SwitchBranch struct {
	// contains filtered or unexported fields
}

SwitchBranch describes one branch in a Switch expression helper.

func Case

func Case(parseValue any, parseNode ui.Node) SwitchBranch

Case creates a value-matching branch for Switch.

func Default

func Default(parseNode ui.Node) SwitchBranch

Default creates the fallback branch for Switch.

Directories

Path Synopsis
Package shorthand provides a mixed-argument companion surface for html.
Package shorthand provides a mixed-argument companion surface for html.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL