Read page as text

NIB / DOCUMENTATION

Runtime and state — NibGenUI

Apply atomic mutations, observe affected nodes, and end a session cleanly.

Open interactive view

Validate before commit

NibRuntime.applyJson parses a frame; apply takes a decoded envelope; applyMutation takes typed Nib mutations. Each route validates before replacing a surface. Check accepted and diagnostics. On rejection, the last committed surface remains available.

NibSurface holds an ID map of NibNode definitions and a data model. root is the root node ID. A child can arrive in a later frame, so a temporary absent definition is not automatically a bad update.

final result = runtime.applyJson(frame);
if (!result.accepted) {
  for (final diagnostic in result.diagnostics) {
    print(diagnostic.code);
  }
}
final surface = runtime.surface('main');
APITypeDefaultBehavior
applyJson(json)NibApplyResult—Parses and applies one complete versioned JSON envelope.
apply(message)NibApplyResult—Applies one decoded envelope.
applyMutation(mutation)NibApplyResult—Applies a typed local mutation through the same validation path.
surface(id)NibSurface?null if absentReads the most recent committed immutable snapshot.

Read a snapshot without owning a second model

The runtime is the state owner for a generated surface. A frame is parsed, checked against its catalog and limits, and applied to a candidate state. Only a valid candidate replaces the committed snapshot. Your renderer reads that snapshot. Avoid keeping a second mutable copy of the same data in widget State unless you have a specific draft or conflict policy; two owners make it unclear which value an action should use.

After the getting-started fixture has created main and bound title to /title, run the function below from a local button callback. writeData uses the same value validation path as protocol data updates but needs no wire envelope. resolve reads through a NibValue such as NibBinding. The accepted write is visible immediately; it does not wait for a transport or a model response.

void changeTitle(NibRuntime runtime) {
  final result = runtime.writeData('main', '/title', 'Edited locally');
  if (!result.accepted) {
    for (final diagnostic in result.diagnostics) {
      debugPrint(diagnostic.code);
    }
    return;
  }
  final title = runtime.resolve('main', const NibBinding('/title'));
  debugPrint(title is String ? 'Title updated' : 'Title unresolved');
}

Observe only what changed

nodeChanges reports affected node IDs for each accepted mutation. watchNode(surfaceId, nodeId) filters that stream for a widget; cancel the subscription when its owner leaves. actionDecisions reports dispatch outcomes without event context or data values.

Detached node definitions stay available for later references. After a complete update, compactSurface removes definitions unreachable from root. Do not compact while prefetched children still need to be attached.

APITypeDefaultBehavior
nodeChangesStream<NibNodeChange>broadcast streamAffected node IDs and lifecycle flag.
watchNode(surfaceId, nodeId)Stream<NibNodeChange>filtered streamUpdates for one rendered node; caller cancels subscription.
compactSurface(id)NibApplyResulthost callDrops detached definitions once root reachability is complete.
actionDecisionsStream<NibActionDecision>broadcast streamAction acceptance or rejection without context values.

Test rollback and retained definitions

Now try writing the number 42 to /title while a Text expects a string there. The result should be rejected and the last valid title should remain visible. Treat this as recoverable input failure: record the diagnostic code, ask the sender for a corrected frame, or stop the session if your policy requires it. Clearing the entire runtime would throw away valid content and make diagnosis harder.

For subscriptions, use nodeChanges when several nodes matter, or watchNode when one view depends on a single node. The event identifies affected nodes; read their current values from the runtime. NibGeneratedSurface already manages its own subscriptions, so a normal host does not need to rebuild the entire page for every data change. Any extra subscription you create still needs cancellation when its owner ends.

Node limits include detached definitions. If a session repeatedly replaces children, its visible tree may stay small while its retained node map grows. After the sender finishes attaching all prefetched definitions, compactSurface removes nodes unreachable from root. Calling it too early can remove data the next frame intended to reference; calling it before root exists returns root_missing.

Protocol attempt limits belong to the runtime lifetime. Replacing an adapter during reconnect does not reset maxProtocolMessages, and rejected envelopes spend that budget too. Use a fresh runtime for a genuinely new session, not as an automatic way to evade an exhausted session budget. During shutdown, cancel incoming work, detach the view and dispose the runtime so late updates cannot target a closed owner.

Keep the session bounded

Defaults are 64 KiB per message and retained data model, 256 nodes per surface, 16 live surfaces, depth 32, and 8192 characters per string. maxProtocolMessages allows 4096 protocol attempts over the runtime lifetime, including rejected frames; local writes and dispatches do not spend that budget.

A new runtime starts a new budget. The host must still limit session duration, reconnections, and invalid physical frames across adapters. Dispose the runtime after cancelling its transport and removing the renderer.

APITypeDefaultBehavior
maxMessageBytes / maxDataModelBytesint65536 eachPer-envelope bytes and retained data-model bytes.
maxNodes / maxSurfacesint256 / 16Node capacity per surface and total live surfaces.
maxDepth / maxStringLengthint32 / 8192Nested value depth and string character limit.
maxProtocolMessagesint4096Lifetime envelope attempts, including rejected messages.