To maintain state across render calls (e.g., a counter or a button's toggle state), a node must be "mounted".
- Mounting: Use
getMounted(node, ctx) to retrieve the persistent version of the node. If it hasn't been mounted, NIMWAVE stores it in the context. - State Access: Use the object returned by
getMounted (often called mnode) to read/write persistent state. Use the original node argument to read transient data like mouse input. - Lifecycle: You can define
mount and unmount methods (matching the render signature) to run custom setup/teardown code. - Uniqueness: Every mounted node must have a unique
id. It is recommended to use hierarchical IDs (e.g., node.id & "/child_id").
type
Counter = ref object of nw.Node
mouse: iw.MouseInfo
count: int
method render*(node: Counter, ctx: var nw.Context[State]) =
let mnode = getMounted(node, ctx) # mnode holds the persistent state
ctx = nw.slice(ctx, 0, 0, 15, 3)
proc incCount() =
mnode.count += 1
render(
nw.Box(
direction: nw.Direction.Horizontal,
border: nw.Border.None,
children: nw.seq(
nw.Box(
direction: nw.Direction.Horizontal,
border: nw.Border.Hidden,
children: nw.seq($mnode.count),
),
Button(str: "Count", mouse: node.mouse, action: incCount),
),
),
ctx
)
# Rendering the stateful node
render(Counter(id: "counter", mouse: mouse), ctx)