import type { Component } from 'react' // React DOM's findDOMNode only returns the first host node. The React 18 // instance Fiber carries ownership across Fragment roots without guessing // from DOM siblings (which can belong to other components). interface ReactDOMFiber { tag: number stateNode: unknown child: ReactDOMFiber | null sibling: ReactDOMFiber | null return: ReactDOMFiber | null alternate: ReactDOMFiber | null } const HOST_ROOT = 3 const HOST_PORTAL = 4 export function getReactComponentDOMRoots (instance: Component): Element[] | undefined { const fiber = (instance as Component & { _reactInternals?: ReactDOMFiber })._reactInternals if (!fiber) return undefined if (fiber.stateNode !== instance) return [] // The class points to its initial Fiber, not necessarily the committed one. // Retrace its ancestry through the root's current child lists, matching // either alternate at each level. Detached and uncommitted instances fail. const path: ReactDOMFiber[] = [] let ancestor = fiber while (ancestor.return) { path.push(ancestor) ancestor = ancestor.return } if (ancestor.tag !== HOST_ROOT) return [] let current = (ancestor.stateNode as { current?: ReactDOMFiber } | null)?.current while (current && path.length) { const target = path.pop()! let child = current.child while (child && child !== target && child !== target.alternate) child = child.sibling current = child ?? undefined } if (!current) return [] const roots: Element[] = [] const visit = (first: ReactDOMFiber | null) => { for (let node = first; node; node = node.sibling) { // Portals render outside the instance's DOM scope. if (node.tag === HOST_PORTAL) continue if (node.stateNode instanceof Element) { roots.push(node.stateNode) } else { visit(node.child) } } } visit(current.child) return roots }