Documentation / For Agents

Porting to Refract

Copyable instructions for migrating an existing application while preserving its behavior and platform requirements.

Port an existing application

Copy this Markdown into the migration agent’s prompt or project instructions. Fill in the source application, target platforms, and migration scope before starting.

porting-to-refract.md
# Porting an existing application to Refract

Port the specified application to Refract within the user's scope. Preserve its observable behavior, domain rules, data contracts, and intended interaction design. Treat the source application as the behavioral reference and the checked-out Refract source and documentation as the API reference. Do not combine the migration with an unrelated redesign.

## Establish the migration scope

Record the source application's location, language and UI framework, required target platforms (web, native, or both), and the screens or workflows being ported. Read repository instructions, build scripts, existing tests, and any design references before editing. Resolve missing information from the repository first; ask only about decisions that materially affect the migration and cannot be inferred.

Inventory:

- Entry points, screens, navigation, route parameters, deep links, and Back behavior.
- User actions, keyboard shortcuts, focus order, editing behavior, and accessibility requirements.
- Domain models, validation, state ownership, derived values, and persistence formats.
- HTTP calls, authentication/session handling, subscriptions, timers, file access, and background computations.
- Loading, empty, error, offline, retry, and cancellation states.
- Layout constraints, typography, images, scrolling behavior, and responsive layouts.

Create a migration map with a row for each workflow: source implementation, required behavior, proposed Refract owner, platform services, and acceptance checks. Preserve existing API and storage contracts unless the user has explicitly requested changes.

## Check platform fit before a full rewrite

Read the current [Overview](https://refract.rs/docs/for-agents-overview), [Architecture](https://refract.rs/docs/architecture), [component reference](https://refract.rs/docs/reference-overview), and [Browser & Native](https://refract.rs/docs/browser-native) guides. Confirm capabilities against the actual dependency version or checkout. Do not invent widgets, router APIs, persistence APIs, or task-spawning helpers from another UI framework.

Prove difficult requirements with a small vertical slice early: text editing and IME, native file access, large lists, platform accessibility, drag interactions, or third-party integrations. Refract's browser and native hosts share view semantics, but their layout, input, rendering, and platform support differ. Native accessibility and virtualized lists are not complete built-in solutions; do not silently treat them as supported if the source app depends on them.

Record each capability gap and an explicit implementation or scope decision. Continue work that does not depend on an unresolved gap. Do not remove an existing behavior merely to make the port compile.

## Create a working shell and preserve reusable logic

Keep the original application runnable while establishing the Refract entry points. Use a separate target, package, or clearly bounded screen migration as appropriate to the repository. Preserve the existing dependency setup and lockfile conventions.

For a new app, the CLI provides the supported starting structure:

```sh
cargo install refract --features cli --locked
refract new ported-app
cd ported-app
refract dev --open
```

Use the generated Cargo configuration and browser/native entry points rather than guessing adapter dependencies. For a local framework checkout, use the CLI's documented `--framework-path` option. For an existing Rust workspace, add the appropriate Refract dependencies and integrate the host entry points without replacing unrelated manifests.

Extract or reuse domain logic, parsing, validation, network contracts, and persistence code independently of the new views. Existing Rust code can often remain unchanged. Code in another language needs an explicit retained-service or rewrite boundary; Refract does not automatically translate it. Port and test pure transformations before rebuilding complex UI behavior around them.

## Map source concepts to Refract ownership

| Source concept | Refract destination | Migration rule |
| --- | --- | --- |
| Component props | Struct fields for `View::body`, parameters to `#[view]`, or owned `view_fn` captures | Use ordinary values for snapshots and `Binding<T>` for a live editable value owned elsewhere. |
| Component-local state | `cx.state` or `#[state]` | Keep declarations unconditional, with stable names and types. Initializers seed new mounts; changed props do not reset existing state. |
| Shared store/context | An `Rc<Model>` supplied with `environment_object` | Put observable fields in graph-backed `State` or `Binding`; read them in the consumers that should react. |
| Theme or scoped configuration | `EnvironmentKey` and `environment::<K>` | Use typed values, equality, defaults, and subtree overrides. |
| Computed selector | A pure body calculation or retained `Derived` attribute | Track real reads; use `Derived::distinct` when equality should suppress downstream work. Avoid duplicating derived values into mutable state unnecessarily. |
| Event callback | `on_press`, typed event handlers, or field/scroll callbacks | Write through the action context's runtime; preserve semantic activation and input behavior. |
| Subscription or lifecycle hook | `cx.effect` or `#[effect]` | Start external work after commit, declare restart dependencies explicitly, and return cleanup. |
| Async result delivery | `Runtime::channel` | Send owned results to a UI-local callback that updates bindings. |
| Reorderable item identity | `.key(stable_id)` | Use persistent domain IDs, not list positions or freshly generated values. |
| Navigation state | Application-owned state plus a platform navigation adapter where needed | Model screens and transitions explicitly; preserve history, URLs, parameters, and Back behavior without assuming a built-in router. |

Choose a coherent authoring style for the application. `#[view]`, handwritten `View::body`, and `view_fn` share the same runtime; macros are optional. Read [Views](https://refract.rs/docs/views), [Reactivity](https://refract.rs/docs/reactivity), and [Effects](https://refract.rs/docs/effects) for their lifecycle rules.

## Place reactive reads deliberately

The body that reads a binding through `cx.read` subscribes to it. Passing a value already read by a parent does not give a child an independent dependency. Pass bindings or shared models into reactive children and read the relevant fields there when updates should remain local.

Retain shared models with mounted storage such as `cx.remember`, or create and own them at an explicit application boundary. Do not recreate a graph-backed model on every evaluation. An `environment_object` provides the model by identity; arbitrary fields or `RefCell` mutations inside it do not notify the graph.

Preserve stable tree shape and keys where user state must survive. Changing wrappers, view type, or element identity can remount a subtree. Verify state retention during list insertion, removal, sorting, screen transitions, and provider changes. Use `memo` only after its props include every nonreactive input that affects output; it is not a substitute for correct ownership or tracked reads.

## Port UI behavior, then refine presentation

Build one end-to-end workflow before expanding to the rest of the application. Include its data loading, editing, validation, submission, failure state, and cleanup—not just its initial screen.

Translate layout intent into `h_stack`, `v_stack`, `z_stack`, `spacer`, and constrained `scroll_view` composition. Map supported styling through typed modifiers. Do not paste arbitrary source CSS into Refract or expect pixel-identical rendering between browser and native. Read modifier chains from the primitive outward: `padding` and `frame` introduce wrappers, so modifier order affects paint and hit areas.

Use `field(Binding<String>)` for editable text. Preserve single-line versus multiline behavior, submission keys, focus, selection, composition, labels, disabled states, and validation feedback. Do not implement editing by replacing a text label on every keystroke. Use `on_press` for semantic pointer and keyboard activation, and add lower-level events only where the workflow requires them. Do not nest interactive controls inside an activation target.

Read the [View Modifiers](https://refract.rs/docs/view-modifiers), [Input & Focus](https://refract.rs/docs/input-focus), and individual component pages for supported methods. Compare the port against the source at representative viewport sizes and with real keyboard and pointer interactions.

## Move async work behind services and channels

Keep request construction, response decoding, and domain transformations shared where their dependencies support the target platforms. Isolate transport, file access, persistence, and task spawning behind small application services. Native code may use a thread or async runtime; browser code uses browser APIs and compatible async scheduling. CPU-heavy browser work needs an actual Worker or another off-main-thread mechanism.

At the owner of an operation, create its channel inside committed effect setup. Send `Result<Data, Error>` or another explicit result type from the operation. The receive callback may capture local bindings or an `Rc` model; only the sender and owned messages move into native background work. Set loading state at setup and model success, failure, and cancellation distinctly.

The following is an effect-setup pattern. `start_request` is an application-defined service, and `result_state` is an existing binding whose value type matches the message:

```rust
let result_state = result_state.clone();
let (sender, subscription) = rt.channel(move |rt, result| {
    result_state.set(rt, result);
});
start_request(sender);
subscription.into_cleanup()
```

Return `subscription.into_cleanup()` from setup to close result delivery when the effect is replaced or unmounted. If the producer also requires cancellation, return an explicit cleanup closure that drops the subscription and cancels the producer. Closing a channel alone does not abort a request or computation.

Use the actual request inputs as effect dependencies. When the query, account, document, or other relevant input changes, close the old operation's channel before starting its replacement. Multiple overlapping requests within one effect require their own request-identity policy. Handle `SendError::Full(value)` and `SendError::Closed(value)`; never spin on the UI thread waiting for queue capacity.

For app-wide incoming updates, a root or provider-level effect can own the subscription and update an environment model. Descendants react through normal binding reads. For view-specific work, keep the subscription at that view's lifetime boundary.

Browser Worker messages must cross `postMessage` before being decoded and sent through the main-thread channel. A Rust sender is not automatically transferable to a Worker. Read [Channels](https://refract.rs/docs/channels) and [Async Work](https://refract.rs/docs/async-work) before adapting the source app's background architecture.

## Validate each migrated workflow

Keep baseline tests and fixtures for domain logic, request/response shapes, and persisted data. Add focused behavior checks for the new UI boundaries rather than snapshots that merely repeat the implementation.

Use `refract-test::TestHost` for initial render, actions, state updates, environment consumers, keyed identity, and effect cleanup. It does not simulate browser or native layout, focus, editing, or accessibility; verify those through the actual required hosts. Synchronize background producers before asserting async results, and drain additional batches when `has_pending_messages` reports pending work.

For each migrated workflow, verify:

- Initial, loading, populated, empty, and error states.
- User edits, validation, submission, retry, and rapid repeated actions.
- Late results after request replacement, navigation, unmount, and app disposal.
- Stable state during collection changes and expected resets when identity changes.
- Required keyboard, pointer, focus, text-composition, and scrolling behavior.
- Persistence and server contracts, including existing saved-data compatibility.
- Both web and native if both are in scope; a WASM compile alone is not a browser interaction check.

Use the repository's formatting and test commands. For a generated app, exercise the browser with `refract dev --open`, native with `refract dev --platform desktop`, and produce the required artifacts with `refract build --release` and `refract build --release --platform desktop`.

## Finish with a reviewable port

Complete the agreed workflow before replacing its original implementation. Keep a clear way to run the reference app until behavior is verified, and remove obsolete code only within the authorized migration scope.

Deliver the migrated code, run/build instructions, a summary of retained versus rewritten services, verification results, and any remaining capability gaps. State where behavior intentionally differs from the source and why. Do not describe the application as fully ported while required flows, data compatibility, or target-platform behavior remain unverified.