Documentation / Internals

Architecture

How the reactive graph, mounted view tree, and platform hosts turn shared Rust views into incremental UI updates.

One core, separate platform hosts

Refract separates application descriptions from the resources that display them. Shared Rust views describe semantic elements and read reactive state. The portable core retains mounted identity, tracks which views need reevaluation, and produces patches. A platform host owns scheduling, input translation, and the resources those patches update.

Dependencies point inward: the native, web, and test adapters depend on refract-core, which depends on refract-graph. The graph has no view or platform dependency. Core has no DOM, window-system, text-engine, GPU, or async-executor dependency. This lets the same application views and state run under different hosts.

LayerOwnsProduces or exposes
refract and refract-macrosPublic facade, prelude, and optional authoring macros.Typed views and declarations that use the ordinary core APIs.
refract-graphAttribute values, dependencies, derived computations, observers, and message channels.Settled derived values and notifications identifying dirty observers.
refract-coreApp, mounted views, environment scopes, state slots, effects, and reconciliation.Portable Element, Event, Update, and Patch contracts.
refract-webDOM nodes, CSS, browser event integration, and flush scheduling.A browser UI backed by native browser layout and painting.
refract-nativeWinit lifecycle, retained layout, text, images, editing, and renderer coordination.Drawing commands for a replaceable renderer; Vello is the default.
refract-testAn in-memory element tree and explicit flushes.Deterministic inspection of semantic updates without a window or DOM.

Three retained structures with different jobs

A Rust view value is a description of inputs and composition. Recreating that value does not itself recreate the mounted state or the host element. Core evaluates it into an internal Description, then reconciles it with the accepted mounted tree.

The graph records data dependencies; the mounted tree records composition and lifetime; the host retains platform resources. They are connected by identities and subscriptions, but their shapes are different. A provider, group, or memo boundary can exist in the mounted tree without creating a DOM node or a native layout box.

StructureRetained dataConnection to the next layer
Attribute graphState, cached Derived values, observer dependencies, and invalidation work.Core maps dirty observer IDs to mounted views.
Mounted view treeAccepted view descriptions, parent/child identities, named slots, handlers, environment scopes, and effects.Core emits element patches keyed by ElementId. Only element-producing mounts become host elements.
Host resourcesDOM elements on web; retained elements, layout nodes, text, image resources, and editor state in native apps.Hosts translate input back to semantic events and present the accepted elements.
i

Element describes portable properties such as kind, style, text, and semantics. Child ordering and event handlers are managed separately. Read Internal Types for the builder, type-erasure, and description machinery.

Follow one update through the system

Suppose a button updates a shared model’s count while a label deeper in the tree reads a derived total. The button’s event handler writes graph state. That write starts propagation; it does not synchronously rebuild or paint the UI.

StageWhat happens
1. Input or completionThe host translates native input and calls App::dispatch_event, or drains a channel result into its registered UI-thread callback.
2. Graph mutationThe callback writes a State or Binding inside a mutation batch. Equal writes can be suppressed with set_if_changed.
3. PropagationThe graph settles dependent derived computations and marks affected observers dirty. Its waker requests a host flush.
4. PreparationApp::prepare maps dirty observers to mounts, reevaluates affected view bodies, and creates a Pending candidate with semantic patches.
5. Host applicationThe host applies the candidate’s patches to retained platform elements. A text change can update an existing element without replacing its identity.
6. Commit and presentationApp::commit accepts the tree and dependencies, then runs effect cleanup and setup. The host presents the resulting UI; in native apps, drawing is a separate phase.
i

For graph-driven updates, core records paths to dirty descendants so it can reach a leaf without reevaluating unrelated ancestor bodies or sibling subtrees. New parent descriptions, changed identity, and provider changes can still require additional evaluation.

Prepare, apply, then commit

Preparation stages changed mounts, child relationships, view subscriptions, and effect declarations. Unaffected mounts remain shared with the accepted tree. Pending carries the patch batch and the candidate metadata required to publish the result. Core does not advance its accepted baseline merely because preparation succeeded.

The patch protocol consists of Create, Update, Children, and Remove. The host applies the entire batch, then passes the same candidate to App::commit. Commit checks app identity, root-input revision, graph mutation epoch, and the batch’s base revision. Keep prepare, apply, and commit together without intervening model writes.

Dropping an uncommitted candidate leaves accepted view subscriptions and effect lifecycles intact. This is not a transaction that rolls back arbitrary state writes or external side effects during evaluation. View evaluation should describe work; external operations belong in committed effects.

A partially applied host update is also not rolled back automatically. The web adapter stops and disposes the affected app after a DOM application failure; native stops the app on a flush failure. A successful empty patch batch still needs committing because handlers, subscriptions, or effects may have changed without a visible property change.

Identity determines what survives

Reconciliation matches children by their sibling-local key, or by position when unkeyed, together with view type and element identity. Reusing a mount preserves its named state slots and effect lifetime. Changing identity creates a new mount; a committed removal tears down the old one. Host element IDs are stable for retained mounts and are not reused for later mounts in the same app.

Reactive dependencies are captured from actual reads during body evaluation. Commit publishes those dependencies, so a discarded candidate cannot replace the accepted view’s subscriptions. Conditional reads can change which attributes a view observes. Derived computations maintain their own dependency edges and run during graph propagation rather than host rendering.

memo(props) can skip work caused by a new parent description when props compare equal and the environment scope matches. It cannot suppress a dirty body observer. Derived::distinct handles a different boundary: it can stop downstream propagation when a computed output stays equal. These mechanisms reduce different kinds of work.

i

Read Graph for dependency propagation and Views for application-level identity rules. Traversing a mount, reevaluating its body, emitting a patch, and drawing a frame are distinct operations.

State, environment, and effect ownership

App owns the graph runtime and accepted mounted tree. A mounted state slot retains its graph handle; cloned handles share ownership. Dropping the last handle queues retirement, and Runtime::collect removes the attribute and its edges at a safe point. Reconstructing a view description does not reset a matching mounted slot.

Environment scopes carry graph-backed values with inherited overrides. Typed environment reads participate in dependency tracking. An environment_object shares an Rc model by identity, while consumers track the model fields they actually read through bindings. A root provider can therefore share data with deep consumers without intermediate layouts forwarding it or observing every field.

Effects declare resource lifetimes separately from reactive reads. Setup runs after commit; changed explicit dependencies trigger old cleanup before replacement setup. Effect setup writes are batched and can schedule a subsequent update. App disposal closes channels, invalidates mounted scopes, runs cleanup, and releases mounted ownership; the host also releases its platform resources.

Hosts own layout, interaction state, and presentation

The portable patch contract describes what elements should exist and their properties. Each host decides how to represent them, when to flush pending work, and how to translate platform input. Retaining host resources preserves state such as focus, selection, and composition where element identity remains compatible.

Native rendering is a boundary inside the adapter: a renderer receives logical geometry, positioned glyphs, and image/drawing resources, not application views or graph state. run_with_renderer can replace Vello while retaining reconciliation, input, layout, and shaping. Browser layout remains a separate implementation; shared view semantics do not imply identical pixels or native widgets. See Native Rendering for the drawing pipeline and retained pixels.

Blur stays in the paint pipeline. Core validates Style::blur and Style::backdrop_blur; web maps them to CSS filters. Native emits a DrawCommand::PushEffects subtree paired with PopLayer, carrying content blur, backdrop blur, and group opacity. A custom renderer must implement those operations too. The default Vello encoder captures previously painted content for a backdrop, renders filtered groups into intermediate textures, and applies GPU Gaussian passes before compositing.

A host can redraw without a graph update—for example, while resizing or changing hover paint. A graph update can also commit without a visible patch. Native retains text and layout resources so a paint-only change does not inherently require reshaping text, while geometry changes can require a layout pass.

HostLayout and renderingPlatform responsibilities
WebMap semantic elements to DOM nodes and style properties to CSS. The browser performs layout, text rendering, and painting.DOM/Shadow DOM ownership, event delegation, native input behavior, scrolling, and coalesced flush scheduling.
NativeMaintain Taffy layout nodes and Parley text resources, then generate positioned drawing commands for the renderer.Winit events and deadlines, hit testing, focus, editing and IME integration, image loading, scrolling, surface lifecycle, and presentation.
TestApply semantic patches to an in-memory element tree. No platform layout or rendering is performed.Explicit flushing, event dispatch, and inspection of accepted text, identities, and patch batches.

Input and async work converge at state writes

Input enters through semantic Event payloads and the currently accepted handlers. Core routes bubbling events through mounted ancestors inside a mutation batch. EventResponse carries synchronous controls such as default prevention and pointer capture back to the adapter. Event callbacks do not dirty views unless they write observed state.

Background work reaches the same mutation path through channels. The sender admits owned results to a bounded inbox and wakes the host; a UI-local callback updates graph-backed state when the inbox drains. Graph handles and shared models remain on the UI thread. The channel notification is separate from the graph waker, because a newly arrived result must wake the host before any state write occurs.

The framework does not choose an HTTP client or executor. Shared application logic can use platform-specific transport and spawning adapters. Browser Workers require postMessage before their results enter the main-thread channel. See Async Work for scheduling and ownership internals, or Channels for usage.

Verify each boundary independently

Graph tests verify propagation, equality suppression, dependency changes, and ownership. TestHost checks reconciliation, keyed identity, environment behavior, effects, and semantic patches. Native host tests and browser fixtures cover the platform behavior that an in-memory tree cannot validate.

Use GraphStats to inspect graph size and propagation counts, UpdateStats to distinguish visited and evaluated mounts from emitted patches, and native HostStats to inspect shaping, decoding, layout passes, and applied patches. Native diagnostics also report commits and presentation. These counters help locate work at the layer that owns it.

Repository checks
cargo test --workspace --all-features --locked
cargo clippy --workspace --all-targets --all-features --locked -- -D warnings

Where to read or change the implementation

Start with the layer that owns the behavior, then follow its input and output contracts. The paths below are relative to the repository root.

ConcernSourceDeeper guide
Tracked reads and propagationcrates/graph/src/runtime.rsGraph
View descriptions and type erasurecrates/core/src/view/mod.rsInternal Types
Mounted identity, reconciliation, and commitcrates/core/src/runtime/mod.rsViews and Effects
Providers and shared modelscrates/core/src/runtime/environment.rsReactivity
Message admission and deliverycrates/graph/src/channel.rsAsync Work
Host observations and ordered requestscrates/core/src/runtime/surface.rsSurface
Portable vector drawingcrates/core/src/drawing/Canvas
Presentation animationcrates/core/src/presentation/Animation
DOM application and schedulingcrates/web/src/dom.rsBrowser & Native
Native lifecycle, retained elements, and drawingcrates/native/src/app/mod.rs, host/, and renderer/Browser & Native
Deterministic semantic checkscrates/test/src/lib.rs and crates/test/tests/Input & Focus