Documentation
¶
Overview ¶
Package decl is the declarative authoring layer for Silk widget trees.
The package centres on a small AST type — *Node — that is the canonical representation of a UI design. Both the on-disk TDoc format read by the designer (.silkui files) and the in-memory Go DSL used by code-first authors are projections of the same Node tree:
Go DSL (.silk.go) ←→ *decl.Node ←→ TDoc (.silkui)
↓
factory.New()
↓
IWidget
Why a custom AST and not go/ast?
We need round-tripping between two formats with very different shapes (Go function calls vs a tree of name/value pairs). Re-using go/ast as the canonical type would force every TDoc node to carry Go syntactic fluff, and force every Go author to write only the subset of Go we can translate back. A purpose-built AST sidesteps both: TDoc and Go both project to the same minimal Node shape, and the projection rules are explicit instead of "everything go/ast would let you write minus a surprise blocklist".
Layered responsibilities
- node.go — Node, Prop, Value sealed interface (Lit / Ref / Bind / Expr)
- builder.go — Go DSL: New / Form / VBox / Button / etc. with Attr options
- codec_tdoc.go — ToTDoc / FromTDoc round-trip
- runtime.go — Node.Build() instantiates IWidget tree via core/factory
What is NOT in this package ¶
Importing arbitrary hand-written Go source is intentionally deferred. ToGo emits builder expressions from the AST, and cmd/silkgen wraps them in a compilable Go file. Build does not evaluate Expr or attach Ref/Bind event handlers: the host application wires those explicitly through BuildWithIndex.
Index ¶
- func ApplyPersistedProperties(obj core.IEnumProperties, values map[string]string)
- func AvailableShortcuts() []string
- func ToGo(n *Node) string
- func ToTDoc(n *Node) *core.TDoc
- type Attr
- type Bind
- type Expr
- type Lit
- type Node
- func Button(attrs ...Attr) *Node
- func Card(attrs ...Attr) *Node
- func CheckBox(attrs ...Attr) *Node
- func ComboBox(attrs ...Attr) *Node
- func Edit(attrs ...Attr) *Node
- func Form(attrs ...Attr) *Node
- func FromTDoc(doc *core.TDoc) (*Node, error)
- func GridLayout(attrs ...Attr) *Node
- func GroupBox(attrs ...Attr) *Node
- func HBox(attrs ...Attr) *Node
- func Label(attrs ...Attr) *Node
- func New(typeName string, attrs ...Attr) *Node
- func ProgressBar(attrs ...Attr) *Node
- func RadioButton(attrs ...Attr) *Node
- func Slider(attrs ...Attr) *Node
- func TabWidget(attrs ...Attr) *Node
- func VBox(attrs ...Attr) *Node
- type Persisted
- type Prop
- type Ref
- type TrKey
- type Value
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ApplyPersistedProperties ¶
func ApplyPersistedProperties(obj core.IEnumProperties, values map[string]string)
ApplyPersistedProperties restores a designer props block through the same data-only codec and dependency ordering used by Node.Build. Only writable properties explicitly enumerated by obj are accepted; unknown or malformed values are ignored. Item lists precede selection, ranges precede values, and date components are committed together. The input map is not modified.
func AvailableShortcuts ¶
func AvailableShortcuts() []string
AvailableShortcuts returns the sorted list of factory names that have a builder shortcut. Used by docs / tests.
func ToGo ¶
ToGo pretty-prints n as Go source using this package's builder DSL. The result is a single expression like
decl.Form(decl.ID("Main"), decl.P("title", "Hello"),
decl.Children(
decl.Button(decl.ID("ok"), decl.P("text", "OK")),
decl.Label(decl.ID("msg"), decl.P("text", "Hi")),
),
)
suitable for embedding in a hand-written .silk.go file. The generator picks pre-baked builder helpers when the node's Type matches one of the entries in builderShortcuts; otherwise it emits decl.New("<type>", ...).
Output is run through go/format before return so callers can drop it straight into a source file. ToGo never returns an error in practice — go/format failure on its own output would signal a bug in the generator and is reported via panic.
nil input returns the empty string.
func ToTDoc ¶
ToTDoc serialises n into a *core.TDoc rooted at the returned doc. The returned doc has no parent and can be directly fed to TDocFile.WriteTo or further nested under a parent designer document.
nil n returns nil. Internal nil children are skipped silently — the builder allows passing nil into Children(...), and we don't want every emitter to defensively filter.
Types ¶
type Attr ¶
type Attr interface {
// contains filtered or unexported methods
}
Attr is anything that mutates a Node during construction.
We use this functional-options pattern instead of a typed struct of optional fields so the builder reads naturally (one Attr per English concept) and so users can extend with their own attrs without forking the package. The pattern also lets the type-specific helpers (Button, VBox, etc.) compose: a single helper just calls New with a cascade of attrs.
func Children ¶
Children appends multiple child nodes. Convenience wrapper around repeated Child(...) calls.
func ID ¶
ID sets the designer index key on the node — the name the designer uses to locate it in the property panel and the form designer.
type Bind ¶
type Bind struct {
Path string
}
Bind names a reactive binding source — e.g. "@bind:user.name". Used by the data-binding runtime to subscribe a widget property to a reactive value. Decl stores the path verbatim; subscription is done at Build time by the data-binding glue.
type Expr ¶
type Expr struct {
Source string
}
Expr carries an opaque Go expression source — for properties whose value cannot be reduced to a literal at design time. The designer renders these as "code only" placeholders; ToGo preserves the source as quoted data in decl.Expr, never executable Go. Build skips the expression; only an explicit host integration may resolve it.
type Lit ¶
type Lit struct {
V interface{}
}
Lit wraps a Go primitive (string, int, float, bool, etc.) that needs no further interpretation. This is the dominant case — most props are constants known at design time.
type Node ¶
Node is the canonical declarative representation of a single widget instance. It maps 1:1 to a TDoc subtree and to a single constructor call in the Go DSL. The renderer / designer / code-emitter all read the same Node shape.
Field semantics:
- Type factory name (e.g. "gui.Button"). Required. Must match a core.RegisterFactory registration before Build() will succeed.
- ID optional designer index key. When set, written to the TDoc "name" attribute so designer overlays can locate the widget. Empty string means "anonymous".
- Props ordered list of (name, value) pairs. We use a slice instead of a map so the author's writing order is preserved across round-trips — the designer's diff view reads better when properties aren't reshuffled by hash iteration.
- Children child nodes whose widgets become sub-widgets of this node's widget at Build time.
Loc is intentionally *not* a field today. When the Go-source parser arrives in a follow-up, it will populate a separate parallel structure (Loc map keyed by *Node identity) so that adding source positions does not perturb the Node value semantics — equality, JSON, etc.
func FromTDoc ¶
FromTDoc reads both the declarative dialect (gui.Form/widget) and the designer's persisted dialect (form/children/props). Designer bounds are in millimetres and become logical pixels at 96 DPI, independent of the machine running codegen. Property-sheet values retain their exact serialized form. Unknown factories survive parsing and fail explicitly when Build is called.
func New ¶
New constructs a Node of an arbitrary factory type. This is the foundation of every type-specific helper below: each one is just New(typeName, ...).
Use New directly when:
- The widget type is not in this package's pre-baked helper set.
- You're authoring a generator that emits AST programmatically and wants to stay agnostic about widget identity.
func ProgressBar ¶
ProgressBar is a determinate progress indicator. Its value range is fixed at 0..1.
func RadioButton ¶
RadioButton is a mutually-exclusive choice. Common props: text, checked.
func (*Node) Build ¶
Build instantiates the widget tree rooted at n. The returned object is the concrete value produced by the registered factory; callers that know the type can type-assert (e.g. *gui.Form). The runtime makes no assumption beyond "the factory returns a value with at least the prop setters the props request" — passing a decl tree with a wrong factory name surfaces as an error here, but a wrong prop name silently no-ops (matches formloader.go's behaviour).
Children are attached via SetParent. The runtime does NOT require a concrete IWidget interface; any object that implements SetParent (with a single argument matching the parent's static type) is assembled into the tree. When SetParent is missing, children are still Built — they just don't get auto-parented.
For applications that need to wire event handlers after construction, see BuildWithIndex which additionally returns a map from Node.ID to the corresponding widget instance.
func (*Node) BuildWithIndex ¶
BuildWithIndex behaves like Build but additionally collects every Node with a non-empty ID into a flat map keyed by that ID. Apps can then look up specific widgets by their declared name and bind event handlers, install reactive bindings, or imperatively mutate state without walking the widget tree.
Duplicate IDs in a single tree silently overwrite the earlier entry — designer-authored docs already enforce uniqueness at the index layer so this is the right policy for runtime users too. If your tooling is generating decl trees programmatically and may emit duplicates, validate before calling Build().
func (*Node) PropValue ¶
PropValue looks up a property's value by name. Returns (nil, false) when the prop is not present. Callers that expect Lit can type-assert:
if v, ok := n.PropValue("text"); ok {
if lit, ok := v.(decl.Lit); ok {
text, _ := lit.V.(string)
}
}
type Persisted ¶
type Persisted struct {
Source string
}
Persisted carries a designer property encoded with core.PersistString. Unlike Lit, its target type is obtained from core.IEnumProperties at Build time. This preserves empty strings, named scalar types and exact RGBA colors without guessing types or treating user text as an executable expression.
type Prop ¶
Prop is a named value attached to a Node.
We keep the Value interface sealed (the implementations live in this file) so unknown value variants can never sneak through serialisation — a future Bind type, for example, has to add an explicit codec branch rather than silently ride along as an opaque blob.
type Ref ¶
type Ref struct {
Name string
}
Ref names another Go identifier — typically an event handler bound by the host code at runtime. The serialised form is "@ref:<name>". Decl itself does no resolution; consumers (the runtime widget builder, code emitter) are responsible for resolving the name in the right scope.
type TrKey ¶
type TrKey struct {
Source string
}
TrKey marks a property value as a translation source string. The runtime resolves it via i18n.T at Build time, so a designer-authored .silkui carrying TrKey values renders in the user's locale without the designer needing to know which language is active.
Example:
decl.Button(decl.P("text", decl.TrKey{Source: "OK"}))
On a host with i18n.SetLocale("zh-CN") active, the button's text becomes "确定". With no locale set or no matching entry, it falls back to the source string "OK" — same fallback policy as i18n.T.