import { createContext, type Component, type ReactNode } from "react"; import createReconciler from "react-reconciler"; import { ConcurrentRoot, NoEventPriority } from "react-reconciler/constants"; import type { AppNode, BurokkuElement, BurokkuNode, BurokkuTagName, TextNode, } from "@burokku/runtime"; import { currentEventPriority, currentEventType } from "./events"; import { updateProps, type Props } from "./props"; // LLRT's globals, which the ES2022 library this package compiles against lacks. declare function setTimeout(callback: () => void, delay?: number): number; declare function clearTimeout(id: number): void; declare function queueMicrotask(callback: () => void): void; declare const console: Record void>; /** What a root renders into: the app, or an element already in the UI tree. */ export type Container = AppNode | BurokkuElement; type Instance = BurokkuElement; type TextInstance = TextNode; /** Whether text nodes may be created here: only inside a `text` or an `input`. */ interface HostContext { readonly insideText: boolean; } /** * A parent's tree methods without their content models, which the UI tree * enforces itself by throwing. */ interface Parent { readonly firstChild: Instance | TextInstance | null; appendChild(child: Instance | TextInstance): unknown; insertBefore(child: Instance | TextInstance, reference: Instance | TextInstance): unknown; removeChild(child: Instance | TextInstance): unknown; } type BurokkuHostConfig = createReconciler.HostConfig< BurokkuTagName, Props, Container, Instance, TextInstance, never, // ActivityInstance: no hydration. never, // SuspenseInstance: no hydration. never, // HydratableInstance never, // FormInstance: no forms. Instance | TextInstance, // PublicInstance HostContext, never, // ChildSet: mutation mode. number, // TimeoutHandle -1, // NoTimeout null, // TransitionStatus null, // SuspendedState: commits never suspend. null, // RendererInspectionConfig never, // FormStateMarkerInstance never, // HoistableRoot: no resources. never // Resource >; /** Where in the component tree an error happened. */ export interface ErrorInfo { componentStack?: string | null; } /** Where an error happened, and the error boundary that caught it. */ export interface CaughtErrorInfo extends ErrorInfo { errorBoundary?: Component | null; } /** Options for {@link createRoot}, as React DOM takes them. */ export interface RootOptions { /** Called for an error no error boundary caught; logs it by default. */ onUncaughtError?: (error: unknown, errorInfo: ErrorInfo) => void; /** Called for an error an error boundary caught; logs it by default. */ onCaughtError?: (error: unknown, errorInfo: CaughtErrorInfo) => void; /** Called for an error React recovered from on its own; logs it by default. */ onRecoverableError?: (error: unknown, errorInfo: ErrorInfo) => void; } export interface Root { /** * Renders `children` into the container on React's schedule. The first * render replaces whatever the container already holds. */ render(children: ReactNode): void; /** Removes everything the root rendered, synchronously. */ unmount(): void; } const outsideText: HostContext = { insideText: false }; const insideText: HostContext = { insideText: true }; let currentUpdatePriority: number = NoEventPriority; const asParent = (node: Container): Parent => node as unknown as Parent; /** Whether an element of `type` holds text nodes: a `text` or an `input`. */ const holdsText = (type: string): boolean => type === "text" || type === "input"; // The UI tree has no `display: none`, so hiding a subtree, as // `` and a Suspense boundary that suspends again do, // hides the text in it: each text node shows nothing and keeps its own text // here until nothing hides it. Elements stay visible. React hides only the // outermost elements under the boundary, and text directly under it, so the // text inside those elements is found by walking them, and text that goes // into a hidden subtree later hides as it goes in. /** The elements React hid, and the text nodes it hid itself. */ const hidden = new WeakSet(); /** The text each hidden text node shows once nothing hides it. */ const hiddenText = new WeakMap(); const isText = (node: Instance | TextInstance): node is TextInstance => "data" in node; /** Whether React hid `node` or a node around it. */ function isHidden(node: BurokkuNode | null): boolean { for (let current = node; current !== null; current = current.parentNode) { if (hidden.has(current as Instance | TextInstance)) return true; } return false; } /** * Hides each text node in `node`'s subtree if `hide`, or if React hid a node * between, and shows it otherwise. */ function hideText(node: Instance | TextInstance, hide: boolean): void { const hides = hide || hidden.has(node); if (isText(node)) { const text = hiddenText.get(node); if (hides && text === undefined) { hiddenText.set(node, node.data); node.data = ""; } else if (!hides && text !== undefined) { hiddenText.delete(node); node.data = text; } return; } for (let child = node.firstChild; child !== null; child = child.nextSibling as typeof child) { hideText(child as Instance | TextInstance, hides); } } /** Hides the text in `child`, which went into `parent`, if React hid that. */ function hideInserted(parent: Container, child: Instance | TextInstance): void { if (isHidden(parent)) hideText(child, true); } const hostConfig: BurokkuHostConfig = { rendererPackageName: "@burokku/react", rendererVersion: "0.1.0", extraDevToolsConfig: null, supportsMutation: true, supportsPersistence: false, supportsHydration: false, isPrimaryRenderer: true, noTimeout: -1, scheduleTimeout: (callback, delay) => setTimeout(callback, delay), cancelTimeout: id => clearTimeout(id), supportsMicrotasks: true, scheduleMicrotask: callback => queueMicrotask(callback), getRootHostContext: container => "localName" in container && holdsText(container.localName) ? insideText : outsideText, getChildHostContext: (_parentContext, type) => (holdsText(type) ? insideText : outsideText), getPublicInstance: instance => instance, prepareForCommit: () => null, resetAfterCommit: () => {}, preparePortalMount: () => {}, createInstance: type => app.createElement(type), createTextInstance: (text, _rootContainer, hostContext) => { if (!hostContext.insideText) { throw new Error(`Text must be inside a or element: "${text}"`); } return app.createTextNode(text); }, appendInitialChild: (parent, child) => { asParent(parent).appendChild(child); }, finalizeInitialChildren: (instance, _type, props) => { updateProps(instance, {}, props); return false; }, shouldSetTextContent: () => false, appendChild: (parent, child) => { asParent(parent).appendChild(child); hideInserted(parent, child); }, appendChildToContainer: (container, child) => { asParent(container).appendChild(child); hideInserted(container, child); }, insertBefore: (parent, child, before) => { asParent(parent).insertBefore(child, before); hideInserted(parent, child); }, insertInContainerBefore: (container, child, before) => { asParent(container).insertBefore(child, before); hideInserted(container, child); }, removeChild: (parent, child) => { asParent(parent).removeChild(child); }, removeChildFromContainer: (container, child) => { asParent(container).removeChild(child); }, clearContainer: container => { const parent = asParent(container); while (parent.firstChild !== null) parent.removeChild(parent.firstChild); }, commitTextUpdate: (textInstance, _oldText, newText) => { if (hiddenText.has(textInstance)) { hiddenText.set(textInstance, newText); } else { textInstance.data = newText; } }, commitUpdate: (instance, _type, oldProps, newProps) => { updateProps(instance, oldProps, newProps); }, resetTextContent: () => {}, commitMount: () => {}, // `` and a Suspense boundary that suspends again // hide the text inside; elements stay visible. See `hideText`. hideInstance: instance => { hidden.add(instance); hideText(instance, true); }, unhideInstance: instance => { hidden.delete(instance); hideText(instance, isHidden(instance.parentNode)); }, hideTextInstance: textInstance => { hidden.add(textInstance); hideText(textInstance, true); }, unhideTextInstance: (textInstance, text) => { hidden.delete(textInstance); hiddenText.set(textInstance, text); hideText(textInstance, isHidden(textInstance.parentNode)); }, detachDeletedInstance: () => {}, getInstanceFromNode: () => null, beforeActiveInstanceBlur: () => {}, afterActiveInstanceBlur: () => {}, prepareScopeUpdate: () => {}, getInstanceFromScope: () => null, bindToConsole: (methodName, args) => console[methodName].bind(console, ...args), NotPendingTransition: null, // A context object has the fields the reconciler reads; its public type // hides them. HostTransitionContext: createContext(null) as unknown as createReconciler.ReactContext, setCurrentUpdatePriority: priority => { currentUpdatePriority = priority; }, getCurrentUpdatePriority: () => currentUpdatePriority, resolveUpdatePriority: () => currentUpdatePriority === NoEventPriority ? currentEventPriority() : currentUpdatePriority, resetFormInstance: () => {}, requestPostPaintCallback: () => {}, shouldAttemptEagerTransition: () => false, trackSchedulerEvent: () => {}, resolveEventType: currentEventType, resolveEventTimeStamp: () => -1.1, maySuspendCommit: () => false, maySuspendCommitOnUpdate: () => false, maySuspendCommitInSyncRender: () => false, preloadInstance: () => true, startSuspendingCommit: () => null, suspendInstance: () => {}, suspendOnActiveViewTransition: () => {}, waitForCommitToBeReady: () => null, getSuspendedCommitReason: () => null, }; const reconciler = createReconciler(hostConfig); /** * Creates a root that renders React elements into `container`, the app by * default. The app holds only `window` elements, so render windows into it. */ export function createRoot(container: Container = app, options: RootOptions = {}): Root { const root = reconciler.createContainer( container, ConcurrentRoot, null, false, null, "", options.onUncaughtError ?? reconciler.defaultOnUncaughtError, options.onCaughtError ?? reconciler.defaultOnCaughtError, options.onRecoverableError ?? reconciler.defaultOnRecoverableError, () => {}, null, ); let unmounted = false; return { render(children) { if (unmounted) throw new Error("Cannot render into an unmounted root."); reconciler.updateContainer(children, root, null, null); }, unmount() { if (unmounted) return; unmounted = true; reconciler.updateContainerSync(null, root, null, null); reconciler.flushSyncWork(); }, }; } /** * Runs `callback` and commits the updates it schedules before returning, as * React DOM's `flushSync` does. */ export function flushSync(callback: () => Result): Result { return reconciler.flushSyncFromReconciler(callback); }