An open source design system that's fully customizable and agent ready
TypeScript
docs: define React component runtime architecture (#6122)
Cindy Zhang32e06af848ef
diff --git a/docs/architecture/react-component-runtime.md b/docs/architecture/react-component-runtime.mdnew file mode 100644index 0000000000..29f9c3440a--- /dev/null+++ b/docs/architecture/react-component-runtime.md@@ -0,0 +1,245 @@+---+schema_version: 1+template_version: 1+kind: architecture+id: architecture:react-component-runtime+authority: current+archive_reason: null+superseded_by: null+approved_by: cixzhang+approved_at: 2026-09-07+owners: [cixzhang]+applies_to: [packages/core/src/, packages/lab/src/]+verified_by:+ [+ packages/core/src/Layer/useLayer.test.tsx,+ packages/core/src/utils/sharedResizeObserver.test.ts,+ ]+deciding_specs: []+---++# React component runtime architecture++## Purpose++Astryx components should preserve their documented behavior through render,+interaction, node replacement, lifecycle replay, and unmount. This record assigns+shared runtime roles to render, handlers, refs, Effects, external resources, and+private behavior seams.++It defines correctness and ownership boundaries. It does not ban React features or+require one implementation pattern whenever several preserve the same contract.++## System model++A component runtime has four distinct roles:++1. **Render derives output.** Props, state, and context determine current rendered+ semantics.+2. **Handlers process discrete intent.** Pointer, keyboard, handle, and other+ commands perform the work caused by one action.+3. **Refs retain non-rendering mutable data.** Refs may hold DOM nodes, resources,+ latest values, or other coordination data that does not itself drive output.+4. **Effects synchronize external systems.** Effects connect React state to+ browser APIs, subscriptions, timers, observers, network activity, and other+ systems whose lifetimes are outside render.++Component and family contracts continue to own public state semantics, controlled+and optimistic behavior, focus, announcements, gestures, and other user-facing+outcomes. This record owns only the shared React lifecycle boundary used to fulfill+those contracts.++## Boundaries and invariants++- **INV1 — Render starts from a valid state.** Rendered output MUST derive from+ current props, state, and context. A component MUST NOT render a known-wrong+ initial state and repair it in a follow-up Effect. State stores information that+ cannot be derived during render or directly from the current interaction. DOM+ nodes and whole DOM collections MUST NOT be stored in React state; store only the+ minimal rendering key or own the node through a ref.+- **INV2 — Discrete intent stays discrete.** Work caused by one user or imperative+ action MUST NOT be deferred to an Effect when the originating handler can perform+ it. Using the same state for rendered output does not make an Effect-owned copy of+ the action valid. Deferral MUST NOT delay, repeat, or couple the action to+ unrelated rendering.+- **INV3 — Effects synchronize external systems.** A new or changed Effect MUST+ name the external system it synchronizes. When setup acquires, installs, or+ starts a resource, cleanup MUST release that resource. Synchronization that+ acquires no resource MUST instead be idempotent and safe under dependency+ changes, node replacement, unmount, and StrictMode replay. Ordinary rerender+ synchronization MUST NOT duplicate consumer-visible callbacks or other one-time+ work.+- **INV4 — Mutable refs do not become hidden rendered state.** Refs MAY hold general+ non-rendering mutable data. A ref mutation MUST NOT be the sole source for a value+ later read to produce React-rendered output. A callback ref MAY synchronously+ update an owned DOM node when that DOM update is itself the observable operation+ and attach, detach, replacement, and consumer override behavior preserve the+ current contract. Ref-backed coordination MUST preserve the current component,+ family, accessibility, and API contracts.+- **INV5 — Resource ownership is complete.** Every listener, timer, animation frame,+ observer, request, subscription, and imperative browser resource has one declared+ lifecycle owner. Component- or node-owned resources are removed, aborted, or+ released when disabled, replaced, or unmounted. A document-owned singleton MAY+ persist across consumer gaps when current authority names that lifetime and+ tests prove one shared installation. A persistent singleton without current+ authority is an authority gap, not by itself proof of an implementation leak.+ Optional behavior SHOULD acquire local resources only while enabled.+- **INV6 — Node replacement is a lifecycle event.** A callback ref or other node+ owner handles attachment, `null` detachment, and replacement with another node.+ Cleanup for the old node completes before the new node becomes the active owner.+- **INV7 — Observation preserves one semantic owner.** When JavaScript behavior+ genuinely needs browser geometry, observation stores only the minimal React+ state needed for that behavior and follows INV5–INV6. A repeated row, item, or+ cell path MUST NOT create unbounded observer fan-out when one shared owner can+ provide the same browser fact.+- **INV8 — Behavior stays with its stable lifecycle owner.** Current component,+ family, interaction, and layer authority identifies the behavior owner and the+ documented replacement/composition seams; this record does not choose a new+ owner. A state machine, gesture, timing protocol, or interaction algorithm is+ owned by the component or primitive whose lifetime spans every documented+ replacement and composition seam. Replacing a render prop, slot, child, or+ visual subpart MUST NOT silently remove owner behavior. Internal hook or utility+ extraction is not required by this invariant.+- **INV9 — Broadcast identity follows the broadcast contract.** Context values and+ external-store snapshots MUST NOT change identity while the semantic broadcast+ payload is unchanged when that change would broadcast work to consumers. Public+ hook-result identity remains owned by `architecture:public-component-api` and+ the hook's current contract. Ordinary local objects and callbacks have no shared+ identity promise.++## Authoring guidance++The following are preferred techniques, not independent compatibility promises:++- Use an Effect Event when an external-system Effect needs a stable callback that+ reads the latest props or state without making those reads reactive. Do not use+ an Effect Event to hide a value whose change should resynchronize the system.+- Keep callback refs reference-stable when practical so React does not detach and+ reattach an unchanged node solely because the callback identity changed.+- Prefer CSS for presentational responsiveness. Style authoring owns when container+ queries, media queries, structural selectors, and other CSS mechanisms replace+ JavaScript observation.+- Reuse Astryx's shared observer owner when it supplies the required browser fact.+ Tooling owns the required import and enforcement; INV7 owns the runtime outcome.+- Give a separately nameable state machine, gesture, timing protocol, or+ interaction algorithm a private hook or pure utility when that creates a useful+ focused test seam. Small behavior inseparable from rendering may remain inline;+ do not extract a hook per callback.+- Do not add memoization ceremony without a measured broadcast boundary or a+ current identity contract.++Violating guidance becomes an architecture violation only when it crosses an+invariant above or another current owner.++## Controlled and optimistic state++`architecture:public-component-api`, component records, and family records own+controlled, uncontrolled, and optimistic semantics.++The runtime implementation MUST preserve that current owner:++- a controlled prop is not casually mirrored into a second source of truth;+- a separately named optimistic or pending value follows its current owner's+ applicable settlement and lifetime contract; undefined branches remain with that+ owner;+- callbacks distinguish requested intent from owner-accepted state; and+- whether controlled and uncontrolled ownership may switch after mount remains+ component-owned unless current shared authority says otherwise.++## DOM and imperative API boundary++React state owns rendered semantics. DOM reads are limited to browser-owned facts+such as geometry, focus, selection, event boundaries, native dialog or popover+state, and pointer capture, plus imperative browser operations on an owned node.+Component and API authority owns any narrower composition or introspection rule.++`architecture:public-component-api` also owns public ref admission and naming. A+component may expose both of these distinct surfaces when that authority admits+them:++- `ref` for the documented primary DOM element and its native capabilities; and+- `handleRef` for a component-defined semantic imperative API implemented with+ `useImperativeHandle`.++This runtime record requires only that either surface preserve lifecycle ownership+and current controlled-state semantics. It does not admit a handle, require handle+identity, or decide its members.++## Audit-row routing++This record supplies shared authority for:++- **C5, C6:** derived state and ref-backed hidden state through INV1 and INV4;+- **C19:** complete external-resource cleanup through INV5–INV6; and+- durable runtime outcomes from **C1, C9, C10, C16, C22** through INV1–INV3,+ INV5, and INV8.++It supplies a narrow runtime mechanism boundary informed by **C7–C8** through+INV7, while style authoring and tooling own CSS preference, the shared observer+API, and mechanical enforcement.++Other rows keep their canonical owners:++- **C2, C13:** public API, controlled semantics, public hook identity, and public+ ref/handle contracts belong to `architecture:public-component-api`, families,+ and component records;+- **C3, C17:** focus, announcements, analytics semantics, and focus-preserving+ visibility belong to accessibility, interaction, family, and component records;+- **C4, C11, C18, C21:** callback-ref preference, ref-read purity,+ presentational-component classification, and comment quality remain lint or+ contributor guidance unless a concrete invariant above is violated;+- **C12:** the applicable accessibility, layer, interaction, family, or component+ owner decides which existing primitive must be composed;+- **C14:** this record defines the React/DOM state boundary, while public+ composition and child introspection remain API/component-owned;+- **C15:** each registry or data source keeps its own canonical owner; and+- **C20:** numeric provenance belongs to style, token, component, or interaction+ authority according to the value's purpose.++## Change coupling++Focused runtime review triggers when a change adds or alters:++- an Effect, state mirror, ref mutation, or callback ref;+- a listener, timer, observer, request, subscription, or imperative browser+ resource;+- controlled or optimistic reconciliation mechanics;+- context or external-store broadcast identity; or+- ownership, lifetime, or observable behavior of a state machine, gesture, timing+ protocol, or interaction algorithm.++Review covers initial render, update, interruption, cleanup, node replacement,+unmount, and StrictMode replay where applicable. It also verifies representative+unchanged behavior through the current component, family, API, and accessibility+contracts.++## Owning code++- `packages/core/src/` — stable Core component and hook runtimes.+- `packages/lab/src/` — experimental component runtimes using the same lifecycle+ correctness boundary without receiving stable public API status.+- `packages/core/src/utils/sharedResizeObserver.ts` — current shared Core resize+ observation mechanism; tooling and utility tests own its concrete API.++## Deciding specs++None. Component, family, API, accessibility, layer, interaction, and style records+remain authoritative for the user-facing outcomes delegated above.++## Verification++Lint and focused tests are one-way evidence. A lint failure means the construct+violates the invariant that rule enforces. A passing lint run does not prove the+full runtime contract because many ownership, lifecycle, composition, and+observable-behavior predicates require review or runtime evidence. Likewise, a+focused test proves only its named behavior and mutation expectation; a green+component suite is not blanket conformance with every invariant.++| Invariant | Evidence | Failure signal |+| ---------------- | -------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |+| INV1–INV2 | Initial-render and interaction tests | Output flashes a known-wrong state, or one action is delayed or repeated through an Effect |+| INV3, INV5 | StrictMode setup/cleanup and dependency-change tests | Duplicate callback, leaked work, stale subscription, or missing resynchronization |+| INV1, INV4, INV6 | Ref attach/null/replacement, DOM-in-state rejection, and old-node cleanup-before-new-attach mutations | A DOM node or collection enters state, old node remains active, cleanup misses replacement, or ref mutation changes semantics silently |+| INV7 | Real-browser geometry plus N-consumer observer-instance/subscription mutations | Geometry is invalid, observer instances grow with repeated consumers, one unsubscribe silences peers, or cleanup removes another subscriber |+| INV8 | Owner-observable behavior across documented composition replacement; optional focused internal mechanism tests | Behavior disappears or changes owner when a documented subpart is replaced |+| INV9 | Provider/external-store identity and render-count tests | Unchanged semantic payload changes identity, or snapshot identity creates a render loop |