# Internal Types

How typed builders, View, Element, and the mounted runtime fit together.

<a id="relationships"></a>

## The relationship between the types

`View` is the trait for describing UI. `Text`, `Image`, `Container`, `Stack`, `Overlay`, `Spacer`, `Field`, and `ScrollView` implement that trait with capability-specific builder APIs. `Element` holds the portable properties of that primitive. The runtime evaluates these descriptions, retains their mounted identities, and sends changes to a host adapter.

There are three structures to keep track of: the Rust values used to describe views, the mounted tree retained by core, and the platform resources retained by the adapter. A composition boundary can exist in the first two without creating a DOM node or a native layout box.

| Type | Responsibility | Relationship |
| --- | --- | --- |
| `View` | The composition contract. | Implemented by application views, primitive builders, and modifier wrappers. |
| `Text`, `Image`, `Container`, `Stack`, `Overlay`, `Spacer` | Build a primitive using its supported operations. | Implement `View` and own their `Element` and optional handler directly. Only container builders store child views. |
| `Element` | Describe portable host properties. | Carries kind, style, content, and interaction semantics. Children and callbacks live outside it. |
| `AnyView` | Store different concrete view types together. | Shares an erased view through `Rc` while preserving access to its concrete type identity. |
| `Description` | Tell reconciliation what a view represents. | An element, group, environment provider, or memo boundary. |
| `Mounted` | Retain one composition boundary in core. | Holds the accepted view, child identities, state slots, effects, dependencies, and optional element and handler. |
| `App` | Own the mounted tree and reactive graph. | Evaluates changes, prepares patches, dispatches events, and commits accepted updates. |

<a id="view"></a>

## View describes composition

Application views normally implement `View::body`, which receives a `ViewContext` and returns another view. `view_fn` creates a `FunctionView<F>` around a closure with the same role. The `#[view]` macro generates the authoring machinery for a named reactive view.

`ViewContext` provides tracked reads, named state slots, environment lookup, and effect declarations. The runtime retains those slots and effects for the mounted boundary across body evaluations. The Rust view value carries the inputs used to describe that boundary; recreating the value does not by itself reset mounted state.

The hidden `View::describe` hook supplies an internal description directly. Primitive builders such as `Text` and `Stack` use this hook instead of evaluating a body. Application code should normally use `body` and the public builders; `describe` is the reconciliation protocol.

> The `View` trait and the `view()` constructor are different things. `view()` is a convenience function returning an empty `Container` with `ElementKind::Box`. See [`view`](/docs/view) and [Views](/docs/views).

<a id="node-element"></a>

## Typed builders configure; Element carries properties

Public builders expose only their relevant capabilities: `Image` has `fit`, `Text` has typography and headings, and `Stack` has children, direction, gap, alignment, and justification. `Container` and `Overlay` accept children without exposing row/column layout controls. Each builder owns its element and handler directly. Only containers store children; leaf builders produce an empty child list when describing themselves. Their `View` implementations produce `Description::Element` without adding another mounted boundary.

`Element` is plain, comparable data. It includes `ElementKind`, `Style`, text or input value, image source, accessibility properties, scroll options, interaction settings, and optional canvas content. It has no child list or DOM reference. CanvasContent retains an immutable drawing snapshot and callback; event callbacks stay in Handler. Its identity is supplied separately when core sends an `ElementId` with a patch.

Convenience constructors configure these same types. `text` creates a `Text` node. The stack constructors create `Box` nodes with row, column, or overlay layout. `.on_press(...)` adds activation semantics, a default button role, and a handler to a view. Buttons and checkboxes are application compositions rather than separate constructors or element kinds.

`Field` is a separate builder implementing `View::body`: it reads its text and optional selection bindings and returns a `TextInput` node with a binding-writing handler. Input-specific properties live in `Element.input`, an optional boxed `TextInputProperties` payload. Single-line, multiline, and styled editing share that element kind; their modes determine the host control. The live editor stays in the host. See [Text Editing](/docs/text-editing#core-flow) for that boundary. `ScrollView` similarly provides a dedicated configuration API for a scrolling box.

<a id="erasure-description"></a>

## AnyView and Description connect the layers

`Container`, `Stack`, and `Overlay` accept any concrete `View` through `child` and store it as `AnyView`. Child types do not become part of the container's Rust type. For mixed collections, configure each element first and call `into_any` before passing the collection to `children`. Internally, `AnyView` wraps `Rc<dyn Erased>`. The private `Erased` trait supplies an object-safe bridge for evaluation, concrete type identity, keys, host identity, and memo properties. Cloning an `AnyView` shares the view; it does not evaluate its body.

Evaluation first asks a view for its direct `Description`. If there is none, it evaluates `body` and represents the returned child inside a group. This lets reactive composition boundaries participate in the mounted tree without requiring an extra host element.

| Description variant | Contains | Host effect |
| --- | --- | --- |
| `Element` | A boxed `Element`, child `AnyView` values, and an optional handler. | Introduces a host element. |
| `Group` | Child `AnyView` values. | Exposes the children's host elements without adding a box. Used by fragments and composition boundaries. |
| `Provider` | A typed environment provider and one child. | Changes the child's inherited environment without adding a box. |
| `Memo` | Equality-comparable props and one child. | Lets reconciliation reuse a subtree when props and provider scope match; reactive reads can still invalidate it. |

> `Description` is public but hidden from generated API docs. `Erased` and `Mounted` are private implementation types. This page explains the current implementation rather than recommending these as application extension points.

<a id="example"></a>

## Follow a small view tree

This example combines a reactive composition boundary, two direct node builders, and a bound control. The outer closure owns the named state slot; the text field reads the binding in its own body.

| View value | Evaluated description | Browser representation |
| --- | --- | --- |
| `FunctionView` from `view_fn` | A group containing the returned stack. | No extra DOM element for the closure boundary. |
| `Stack` from `v_stack` | A `Box` element with `Layout::Column` and two children. | A `div` with column layout. |
| `Text` from `text` | A `Text` element holding the string “Profile”. | A `span` containing the text. |
| `Field` from `field` | Its body reads the binding and returns a `Described` element view with `TextInput` properties and a binding-writing handler. | An `input`; `.multiline(true)` would select a `textarea`. |

```rust
use refract::prelude::*;

let profile = view_fn(|cx| {
    let name = cx.state("name", String::new);

    Ok(v_stack()
        .child(text("Profile"))
        .child(field(name).label("Name")))
});
```

> Typing dispatches `Event::Input` to the retained handler, which writes the binding. The text field's tracked read makes it eligible for reevaluation. The outer closure does not read the string, so that edit alone does not require its body to run again.

<a id="modifiers"></a>

## Modifiers are views too

Concrete builders have type-preserving element modifiers generated from one shared definition. Dimensions, paint, labels, and disabled state configure the builder directly. `Text` and `Field` share typography methods; `Image` alone exposes image fitting. `Field` stores those properties until its body reads the binding and produces the editable element.

`ViewExt` provides the fallback for every sized `View`. Its `Modified` result can carry a directly modified element description or introduce a new box around a child. `padding` and `frame` always introduce a box. Other style methods modify a direct element description when one is available, otherwise they wrap the composed view. Modifier order therefore affects the host tree.

`KeyView` gives a child a sibling-local key and describes a group. `Provided` describes an environment provider. `MemoView` describes a memo boundary. These wrappers do not create host boxes on their own. See [View Modifiers](/docs/view-modifiers) for the authoring API.

<a id="mounted-state"></a>

## Mounted identity keeps resources alive

`App` retains private `Mounted` records. Each record holds its current `AnyView`, parent and children, environment, state slots, effects, observers, and lifetime token. Element and handler fields are optional because groups, providers, and memo boundaries also have mounted identities.

Reconciliation matches siblings using their key or position, concrete view type, and host identity when the view exposes a direct element. The private `ElementIdentity` includes kind, interaction, and multiline mode. A key does not override a change that requires a different view or host identity.

`ElementId` identifies an element within one app, and removed IDs are not reused. Internally, `MountId` is an alias of the same ID type, so composition-only mounts also have IDs; only element-bearing mounts become host patch targets. Graph attribute IDs identify state and derived values in a different structure. See [Graph](/docs/graph) for dependency tracking.

`ScopeToken` provides a weak lifetime check for work owned by a mounted view. `ViewContext::scope` produces it, and scoped update handles can reject a callback after its owning view has unmounted.

<a id="patches-events"></a>

## Patches go out; events come back

`App::prepare` evaluates affected views and returns an optional `Pending` candidate. Its `Update` contains a base revision, new revision, statistics, and an ordered list of `Patch` values. `Create` and `Update` carry element properties; `Children` carries ordered element IDs; `Remove` releases an element. Callbacks stay in core and are not part of these patches.

The adapter applies the update to its retained platform resources, then calls `App::commit`. Commit accepts the candidate tree and dependencies and runs effect lifecycle work. Dropping a pending candidate leaves the accepted mounted tree and effect lifecycles intact; it does not undo DOM mutations an adapter has already performed.

The browser adapter retains DOM nodes in its own `Entry` registry. The native adapter retains layout, text, image, and editor resources in `RetainedElement` records. Core's `Element` describes their desired portable properties; it does not contain those platform objects.

Input travels back as an `ElementId` and an `Event`. `App::dispatch` finds the retained `Handler` and invokes it with an `ActionContext`, which provides graph mutation and inherited environment access. A resulting state change starts another prepare/apply/commit cycle.

<a id="source"></a>

## Find the implementation

These paths are relative to the repository root. Start with the type you want to understand, then follow its descriptions into the runtime. [Architecture](/docs/architecture) covers the crate boundaries.

| Source | Types and behavior |
| --- | --- |
| `crates/core/src/view/mod.rs` | `View`, `AnyView`, `Erased`, `Description`, `FunctionView`, `Empty`, and fragments. |
| `crates/core/src/view/primitives.rs` | Typed primitive/layout builders and child composition. |
| `crates/core/src/element.rs` | `Element`, `ElementKind`, `ElementIdentity`, `Interaction`, `Event`, `Handler`, and `ActionContext`. |
| `crates/core/src/view/modifiers.rs` | `ViewExt` and its wrapper types. |
| `crates/core/src/view/field.rs` and `scroll.rs` | `Field` and `ScrollView`. |
| `crates/core/src/drawing/` | Paths, shapes, prepared canvas inputs, and portable drawing commands. |
| `crates/core/src/presentation/` | Animation timing, transactions, transforms, and sampled presentation values. |
| `crates/core/src/style.rs` | `Style` and portable layout, color, gradient, shadow, and blur properties. |
| `crates/core/src/runtime/mod.rs` | `ViewContext`, `Mounted`, `App`, identities, `Pending`, `Update`, and `Patch`. |
| `crates/web/src/dom.rs` and `crates/native/src/host/mod.rs` | Host registries, patch application, and event routing. |
