import type { ElementFunction, ElementProps, ElementType, Key, RemixNode, Renderable, TypedEventTarget, } from './vnode.ts' /** * Error event shape emitted by the component runtime. */ export type ComponentErrorEvent = ErrorEvent & { readonly error: unknown } /** * Task queued to run after a component update completes. */ export type Task = (signal: AbortSignal) => void /** * Runtime handle passed to component setup functions. */ export interface Handle, ContextValue = NoContext> { /** * Stable identifier per component instance. Useful for HTML APIs like * htmlFor, aria-owns, etc. so consumers don't have to supply an id. */ id: string /** * Stable props object for the component instance. The object identity does not * change across updates, but its values are updated before each render. */ props: Props /** * Set and get values in an element tree for indirect ancestor/descendant * communication. */ context: Context /** * Schedules an update for the component to render again. Returns a promise * that resolves with an AbortSignal after the update completes. Call this * from an event handler, queued task, or other work that runs after the * component commits. The signal is aborted when the component re-renders or * is removed. Calling this during setup warns and skips the extra render; * the promise resolves after the initial commit. * * @returns A promise that resolves with an AbortSignal after the update * @throws If called during rendering or before the initial commit outside setup */ update(): Promise /** * Schedules a task to run after the next update. * * @param task Work receiving a signal aborted on the next render or component removal. */ queueTask(task: Task): void /** * The component's closest frame */ frame: FrameHandle /** * Access named frames in the current runtime tree. */ frames: { /** * The root frame for the current runtime tree. */ readonly top: FrameHandle /** * Finds a mounted frame by name. * * @param name The `name` prop of the frame to find. * @returns The named frame, or `undefined` when it is not mounted. */ get(name: string): FrameHandle | undefined } /** * A signal indicating the connected status of the component. When the * component is disconnected from the tree the signal will be aborted. * Useful for setup scope cleanup. * * @example Clear a timer * ```ts * function Clock(handle: Handle) { * let interval = setInterval(() => { * if (handle.signal.aborted) { * clearInterval(interval) * return * } * handle.update() * }, 1000) * return () => {new Date().toString()} * } * ``` * * Because signals are event targets, you can also add an event instead. * ```ts * function Clock(handle: Handle) { * let interval = setInterval(handle.update) * handle.signal.addEventListener("abort", () => clearInterval(interval)) * return () => {new Date().toString()} * } * ``` * * You don't need to check both this.signal and a render/event signal as * render/event signals are aborted when the component disconnects. */ signal: AbortSignal } /** * Default Handle context so types must be declared explicitly. */ export type NoContext = Record /** * Component factory shape used by the Remix component runtime. */ export type Component = ( handle: Handle, ) => RenderFn /** * Infers the context provided by a component or handle-compatible function. */ export type ContextFrom = ComponentType extends Component ? Provided : ComponentType extends (handle: Handle, ...args: any[]) => any ? Provided : never /** * Context storage API exposed on component handles. * * Context values are keyed by provider component identity. `get(Component)` * reads the nearest ancestor instance whose component function is exactly * `Component`, so nested instances of the same provider shadow outer instances * while different component types remain independent. */ export interface Context { /** * Replaces this component's provided value without scheduling a render. * Call `handle.update()` when descendants should render with the new value. * * @param values Value to provide to descendants. */ set(values: C): void /** * Reads the nearest ancestor instance of the given component type. * Read during render to observe replacement values on later renders. * * @param component Provider component whose identity selects the context. * @returns The provider's current value. At runtime, a missing provider returns `undefined`. */ get(component: ComponentType): ContextFrom /** * Reads context without an inferred provider value type. * * @param component Provider component identity. * @returns The provider's current value, or `undefined` when no matching provider exists. */ get(component: ElementType | symbol): unknown | undefined } /** * Content that can be rendered into a frame. * * HTML strings and streams must contain trusted application content. Remix does not sanitize them * before parsing and reconciling them into the current document. */ export type FrameContent = ReadableStream | string | RemixNode /** * Value returned by a browser frame resolver. * * Response bodies are rendered as frame content regardless of status. The default browser resolver * accepts 2xx responses and 3xx or 4xx HTML responses. It rejects other 3xx or 4xx responses and all * 5xx responses. When `fetch()` followed a redirect, the response's final URL updates the frame source * and browser URL for a top-frame navigation. */ export type FrameResolution = FrameContent | Response /** Request and lifecycle details for a frame reload. */ export interface ReloadDetails { /** * Source of the initiating reload, including any GET submission query. Inherited reloads keep * their ancestor's source. Relative values use the document base URL. */ readonly src: string /** Effective HTTP method of the initiating reload, in lowercase. */ readonly method: string /** Form encoding of the initiating POST reload. `null` for GET reloads. */ readonly encType: string | null /** * Submitted form entries for a POST reload. `null` for GET reloads. * Shared with the initiating request; copy the entries before modifying them. */ readonly formData: FormData | null /** The actual submit button, or `null` when there is no submitter. */ readonly submitter: HTMLElement | null /** * Follows this reload like `frame.reload()`: resolves with its signal after rendering, or with * an aborted signal on cancellation, supersession, or frame removal. Rejects on failure. * On success, retained components have updated props. Descendant frame events track their * own reload completion. */ readonly finished: Promise } /** * Event dispatched when a direct or ancestor-driven reload of a frame starts. */ export type FrameReloadStartEvent = Event & ReloadDetails & { /** * The initiating HTML or SVG anchor, area, or owning form. `null` for programmatic reloads, * programmatic navigations, and history traversal. */ readonly element: HTMLAnchorElement | HTMLAreaElement | SVGAElement | HTMLFormElement | null } /** * What a `reloadStart` event describes: the navigation that started the reload, if any, and the * reload's outcome. */ export type FrameReloadStartEventInit = { src: string method: string encType: string | null formData?: FormData element?: HTMLAnchorElement | HTMLAreaElement | SVGAElement | HTMLFormElement submitter?: HTMLElement | null finished: ReloadDetails['finished'] } // The initiating request, inherited by frames that reload while rendering its response. export type ReloadOrigin = Omit /** * Events emitted by frame handles during reloads. */ export type FrameHandleEventMap = { /** A direct reload or an ancestor-driven reload has started. */ reloadStart: FrameReloadStartEvent /** Reload processing has ended, including cancellation or failure. Replaced requests omit it. */ reloadComplete: Event } /** * Options for reloading a frame's source. */ export interface FrameReloadOptions { /** Source to reload and retain for subsequent reloads. Defaults to the current source. */ src?: string /** Form request method: `GET` or `POST`, case-insensitive. Other values default to `GET`. */ method?: string /** * Form encoding: `application/x-www-form-urlencoded` (default), `multipart/form-data`, * or `text/plain`. Case-insensitive; invalid values use the default. Ignored for GET. */ encType?: string /** Form values to submit. GET encodes them into the source query instead of a request body. */ body?: FormData } /** * Public API for interacting with a frame instance. */ export type FrameHandle = TypedEventTarget & { /** Source used by the next reload. Assigning it alone does not load content or change history. */ src: string /** * Resolves a source and reconciles the frame with its returned content without changing history. * A newer reload cancels earlier reload work. Non-cancellation errors reject the promise. * * @param options Source and request settings. * @returns The reload's signal, which is aborted if that reload is superseded or disposed. */ reload(options?: FrameReloadOptions): Promise /** * Renders supplied trusted content directly without calling the resolver or changing the source. * HTML strings and streams are not sanitized. * This does not emit reload lifecycle events or change browser history. * * @param content HTML, a byte stream, or a Remix node to render into the frame. * @returns A promise that resolves when rendering the supplied content completes. */ replace(content: FrameContent): Promise /** Internal runtime context used by client-rendered frame reconciliation. */ $runtime?: unknown } /** * Props accepted by the built-in {@link Frame} component. */ export interface FrameProps { /** Optional frame name used for targeted navigation and lookups. */ name?: string /** Source URL used when the frame loads or reloads its content. */ src: string /** * When to load the initial content: `eager` loads immediately (default), while `lazy` renders * the fallback on the server and waits until the frame approaches the viewport in the browser. * Explicit reloads and navigations always load immediately. */ loading?: 'eager' | 'lazy' /** * Content to render while pending. Lazy loading observes elements rendered by the fallback. * If none are rendered, the browser warns and loads the frame immediately. */ fallback?: Renderable /** Event handlers invoked for events dispatched from the frame element. */ on?: Record void | Promise> } /** * Component factory function that receives a handle and returns a render function. */ export type ComponentFn, ContextValue = NoContext> = ( handle: Handle, ) => RenderFn /** * Zero-argument render function returned by a component factory. */ export type RenderFn = () => RemixNode export type { RemixNode } from './vnode.ts' // Handle is already exported as an interface above, no need to re-export /** * Props accepted by the built-in {@link Fragment} component. */ export interface FragmentProps { /** Child nodes to render without adding an extra host element. */ children?: RemixNode } /** * Mapping of built-in component names to their prop shapes. */ export interface BuiltinElements { /** Props accepted by the built-in fragment component. */ Fragment: FragmentProps /** Props accepted by the built-in frame component. */ Frame: FrameProps } /** * Key type used to stabilize host elements and components during reconciliation. */ export type { Key } from './vnode.ts' export type ComponentConfig = { id: string type: ElementFunction frame: FrameHandle getContext: (type: ElementFunction) => unknown frames: Handle['frames'] signal?: AbortSignal } /** * Minimal structural view of the scheduler used for handle.update() so this * module doesn't depend on the reconciler. */ export interface UpdateQueue { enqueue(vnode: object, domParent: ParentNode): void } /** * Runtime handle returned by {@link createComponent}. */ export interface ComponentHandle { frame: FrameHandle render(nextProps: ElementProps): [RemixNode, Array<() => void>] remove(): Array<() => void> setScheduleUpdate(queue: UpdateQueue, vnode: object, domParent: ParentNode): void getContextValue(): C | undefined isRemoved(): boolean } /** Props accepted by the built-in {@link Portal} component. */ export interface PortalProps { /** Children to render at the destination while retaining their component context and frame. */ children?: RemixNode /** * Destination in the same document as the portal. Defaults to that document's body when omitted. * Changing the destination element remounts the children and resets their local state. If the * destination is removed, children stay attached to that element until the container changes or * the portal is disposed. */ container?: HTMLElement }