Renderizar dos veces
Hito: Reconciliador
Lección 6 de 2425 min
En esta lección
El React que construí en el primer hito, First paint, sabía pintar y no sabía repintar.
Llamar a root.render(<App count={1} />) por segunda vez reconstruía todos los
fibers y todos los nodos del DOM, y añadía una segunda copia de la app debajo de la
primera. Había cambiado un solo carácter.
Para cambiar un carácter necesitaría tres cosas:
- Recordar qué hay en pantalla. La versión de First paint lo olvida todo en cuanto ha pintado.
- Comparar el render nuevo con el viejo. Eso es el diff con keys de la lección Diff con keys, que hasta ahora solo imprimía flags en una terminal.
- Aplicar la diferencia al DOM, y nada más.
Esta lección las junta. Al final, una página de demo imprime cada operación del DOM que cuesta un render, y los números son los que predijo la lección Diff con keys.
El punto de partida
src/mini-react/ es una copia de la biblioteca de First paint, los doce archivos, sin cambios. Seis de
ellos se quedan así: shared.ts, jsx-runtime.ts, jsx-dev-runtime.ts,
dom-host.ts, fiber-root.ts y root.ts. De Diff con keys tomo las diez
funciones de su child-fiber.ts.
Recordar: dos árboles
Hasta ahora había un solo árbol de fibers. A partir de aquí hay dos al mismo tiempo.
Cada fiber está enlazado con su gemelo por alternate, y los dos gemelos apuntan al
mismo nodo del DOM. Un render construye el árbol de la derecha mientras lee el de la
izquierda; un commit termina apuntando root.current al árbol que acaba de construir.
Avanza paso a paso por un árbol pequeño, HostRoot > App > div > (Header > h1,
Counter > button), con createWorkInProgress, la función que crea los gemelos,
al lado:
Paso 1 de 4
- Tras el First paint solo
HostRoottiene un gemelo enalternate: lo creó elcreateWorkInProgress(root.current, null)del primer render. Elalternatede todos los demás fibers es null. - Una actualización inicia un render. En
prepareFreshStack,createWorkInProgressreutiliza el gemelo queHostRootya tiene. Para cada uno de los demás fibers que el diff conserva (enuseFiber), crea un gemelo nuevo, copia los campos y enlazaalternateen ambos sentidos. commitRootaplica los cambios al DOM y luego haceroot.current = finishedWork. Solo se mueve un puntero: el árbol de la derecha pasa a ser el current.- El siguiente render se encuentra
current.alternateya creado: el fiber de hace dos renders.createWorkInProgressreutiliza ese objeto y borra sus flags antiguos en vez de reservar uno nuevo.
Líneas resaltadas: 10 a 16.
Líneas resaltadas: 11 a 29.
Líneas resaltadas: 17 a 23.
/**
* Create (or RECYCLE) the work-in-progress version of `current`.
*
* If `current.alternate` exists, it is the fiber from two renders ago. It is
* not on screen anymore, so the object is reused instead of allocating a new one.
* What describes "the last committed result" is copied from current; what the
* previous render left for the commit is wiped.
*/
export function createWorkInProgress(current: Fiber, pendingProps: any): Fiber {
let workInProgress = current.alternate;
if (workInProgress === null) {
workInProgress = createFiber(current.tag, pendingProps, current.key);
workInProgress.type = current.type;
workInProgress.stateNode = current.stateNode;
workInProgress.alternate = current;
current.alternate = workInProgress;
} else {
workInProgress.pendingProps = pendingProps;
// This fiber is starting a fresh render: forget the notes of an older one.
workInProgress.flags = NoFlags;
workInProgress.subtreeFlags = NoFlags;
workInProgress.deletions = null;
}
// `child` points at the CURRENT children: the old list the diff will compare against.
workInProgress.child = current.child;
workInProgress.memoizedProps = current.memoizedProps;
workInProgress.memoizedState = current.memoizedState;
workInProgress.sibling = current.sibling;
workInProgress.index = current.index;
return workInProgress;
}Línea resaltada: 1.
root.current = finishedWork;Nunca hay más de dos fibers por nodo. El gemelo de hace dos renders ya no está en
pantalla, así que se recupera el objeto y se borran sus notas viejas. child apunta
a propósito a los hijos current: es la lista vieja con la que va a comparar el diff,
y el diff la reemplaza un momento después.
Las notas que un render deja para el commit son flags, los mismos bits que en React real:
// Flags: "what the commit has to do with this fiber" (same bits as real React)
export const NoFlags = /* */ 0;
export const Placement = /* */ 1 << 1; // insert (or move) the DOM node
export const Update = /* */ 1 << 2; // change the props / the text of the DOM node
export const ChildDeletion = /* */ 1 << 4; // some children must be removed (see fiber.deletions)
/** Flags the mutation pass of the commit cares about. */
export const MutationMask = Placement | Update | ChildDeletion;Placement y ChildDeletion son los flags de Diff con keys. Update es nuevo:
el nodo se queda donde está, pero han cambiado sus props o su texto. La clase gana
siete campos:
index: la posición del fiber entre sus hermanos.memoizedProps: las props del último render de este fiber que terminó.pendingPropses lo que se le pide renderizar ahora; comparar las dos es como un render descubre un cambio.updateQueue: en un fiber del host, los nombres de las props que cambiaron, a la espera del commit.flags,subtreeFlagsydeletions: lo que el commit tiene que hacer con este fiber, la unión de todos los flags que hay por debajo, y los hijos viejos que hay que quitar.alternate: el gemelo.
Los cambios en src/mini-react/fiber.ts
El import pasa a ser import { REACT_FRAGMENT_TYPE, type Key, type ReactElement } from './shared';,
hay un tag nuevo, export const Fragment = 7;, y los flags de arriba van debajo de
los tags. La clase:
export class Fiber {
// --- identity ---
tag: WorkTag;
key: string | null;
/** The function for a component, the tag name ('div') for a host component. */
type: any = null;
/** The real thing this fiber stands for: the DOM node, or the FiberRoot for the HostRoot. */
stateNode: any = null;
// --- tree ---
return: Fiber | null = null;
child: Fiber | null = null;
sibling: Fiber | null = null;
/** Position among its siblings. */
index = 0;
// --- inputs / outputs ---
/** Props for the render that is about to happen. For a text fiber: the string. */
pendingProps: any;
/** Props used by the last render of this fiber that finished. */
memoizedProps: any = null;
/** The fiber's own state. Only the HostRoot has one so far: { element }, what render() was given. */
memoizedState: any = null;
/** HostComponent only: the names of the props that changed, waiting for the commit. */
updateQueue: any = null;
// --- effects ---
/** What the commit has to do with THIS fiber. */
flags = NoFlags;
/** Union of the flags of every fiber below this one. Lets the commit skip clean subtrees. */
subtreeFlags = NoFlags;
/** Old children to remove during commit. */
deletions: Fiber[] | null = null;
/** The other version of this fiber (current <-> workInProgress). null = it has only one. */
alternate: Fiber | null = null;
constructor(tag: WorkTag, pendingProps: any, key: string | null) {
this.tag = tag;
this.pendingProps = pendingProps;
this.key = key;
}
}La lección Diff con keys tenía un createWorkInProgress que hacía una copia simple.
Este es el de verdad, el código que acompaña al diagrama:
/**
* Create (or RECYCLE) the work-in-progress version of `current`.
*
* If `current.alternate` exists, it is the fiber from two renders ago. It is
* not on screen anymore, so the object is reused instead of allocating a new one.
* What describes "the last committed result" is copied from current; what the
* previous render left for the commit is wiped.
*/
export function createWorkInProgress(current: Fiber, pendingProps: any): Fiber {
let workInProgress = current.alternate;
if (workInProgress === null) {
workInProgress = createFiber(current.tag, pendingProps, current.key);
workInProgress.type = current.type;
workInProgress.stateNode = current.stateNode;
workInProgress.alternate = current;
current.alternate = workInProgress;
} else {
workInProgress.pendingProps = pendingProps;
// This fiber is starting a fresh render: forget the notes of an older one.
workInProgress.flags = NoFlags;
workInProgress.subtreeFlags = NoFlags;
workInProgress.deletions = null;
}
// `child` points at the CURRENT children: the old list the diff will compare against.
workInProgress.child = current.child;
workInProgress.memoizedProps = current.memoizedProps;
workInProgress.memoizedState = current.memoizedState;
workInProgress.sibling = current.sibling;
workInProgress.index = current.index;
return workInProgress;
}El bucle de trabajo tiene que usar el gemelo. En el hito First paint, prepareFreshStack
apuntaba el cursor a root.current, así que el recorrido escribía sobre el único
árbol que tenía. Ahora empieza por el gemelo, y cada fiber que visita recibe su gemelo
como current. Este es un segundo render del mismo árbol pequeño, una unidad de trabajo
cada vez, con el bucle de trabajo, createWorkInProgress y beginWork al lado:
Paso 1 de 9
- Un segundo
root.render().prepareFreshStackpide el gemelo deroot.current. ElHostRootya tiene uno (lo creócreateRoot), así quecreateWorkInProgresstoma la ramaelse: props nuevas, notas viejas borradas. El cursorworkInProgressapunta a él. performUnitOfWorksobre elHostRoot:currentes sualternate, el gemelo en pantalla.beginWorkrecibe los dos.updateHostRootreconcilia por el camino de actualización, y el diff reutilizaAppconuseFiber, que llama acreateWorkInProgress:Apptodavía no tiene gemelo, así que se crea uno y se enlazan en los dos sentidos. El cursor pasa a él.App:currentes elAppen pantalla.updateFunctionComponentlo llama, y el diff crea el gemelo dediv. Un gemelo nuevo empieza conchild,memoizedPropsy lo demás copiado decurrent: suchildes la lista vieja con la que comparará el diff. LuegomemoizedProps = pendingProps, y el cursor baja.dives un componente host:reconcileChildrencompara sus dos hijos,HeaderyCounter, con los de pantalla. Los dos se conservan, así que los dos reciben gemelo. El cursor va al primer hijo.Headerrenderiza y el diff crea el gemelo deh1. Cada llamada abeginWorkrecibe la pareja: el fiber que se construye y su gemelo en pantalla.- Bajo
h1solo está su texto, que no aparece en el dibujo. Cuando el recorrido se queda sin hijos, entracompleteUnitOfWork: completah1, luegoHeader, que tiene un hermano. El cursor pasa aCounter. Counterrenderiza, y subuttonrecibe gemelo igual: se crea una vez, se enlaza en los dos sentidos y se recicla en cada render siguiente.- El
button(su texto tampoco aparece) es el último fiber.completeUnitOfWorklo completa y sube porreturn:Counter,div,App,HostRoot. ElHostRootno tienereturn, así queworkInProgresspasa a null: el render terminó. commitRootaplica los cambios del DOM y luego apuntaroot.currental árbol terminado: ahora el de la derecha está en pantalla. El siguiente render vuelve a empezar en el de la izquierda, y cada fiber ya tiene allí su gemelo.
Línea resaltada: 3.
Líneas resaltadas: 8, 10.
Líneas resaltadas: 12, 14.
Líneas resaltadas: 8, 10.
Líneas resaltadas: 8, 10.
Líneas resaltadas: 13, 24 a 28.
Líneas resaltadas: 8, 10.
Líneas resaltadas: 29 a 31.
/** Start a walk: make the work-in-progress version of the HostRoot and point the cursor at it. */
export function prepareFreshStack(root: FiberRoot): void {
workInProgress = createWorkInProgress(root.current, null);
}
function performUnitOfWork(unitOfWork: Fiber): void {
// The same fiber in the tree that is on screen. null = this fiber is new.
const current = unitOfWork.alternate;
if (walkLog.enabled) console.log(`begin ${getFiberName(unitOfWork)}`);
const next = beginWork(current, unitOfWork);
// This fiber has rendered with these props: remember them for the next comparison.
unitOfWork.memoizedProps = unitOfWork.pendingProps;
if (next === null) completeUnitOfWork(unitOfWork);
else workInProgress = next;
}
/** Complete this fiber, then move to its sibling, or complete the parent. */
function completeUnitOfWork(unitOfWork: Fiber): void {
let completedWork: Fiber | null = unitOfWork;
do {
const current: Fiber | null = completedWork.alternate;
if (walkLog.enabled) console.log(`complete ${getFiberName(completedWork)}`);
completeWork(current, completedWork);
const sibling: Fiber | null = completedWork.sibling;
if (sibling !== null) {
workInProgress = sibling;
return;
}
completedWork = completedWork.return;
workInProgress = completedWork;
} while (completedWork !== null);
}Líneas resaltadas: 9 a 15.
Líneas resaltadas: 3 a 8, 17.
Líneas resaltadas: 17 a 21.
Líneas resaltadas: 3 a 8, 17.
export function createWorkInProgress(current: Fiber, pendingProps: any): Fiber {
let workInProgress = current.alternate;
if (workInProgress === null) {
workInProgress = createFiber(current.tag, pendingProps, current.key);
workInProgress.type = current.type;
workInProgress.stateNode = current.stateNode;
workInProgress.alternate = current;
current.alternate = workInProgress;
} else {
workInProgress.pendingProps = pendingProps;
// This fiber is starting a fresh render: forget the notes of an older one.
workInProgress.flags = NoFlags;
workInProgress.subtreeFlags = NoFlags;
workInProgress.deletions = null;
}
// `child` points at the CURRENT children: the old list the diff will compare against.
workInProgress.child = current.child;
workInProgress.memoizedProps = current.memoizedProps;
workInProgress.memoizedState = current.memoizedState;
workInProgress.sibling = current.sibling;
workInProgress.index = current.index;
return workInProgress;
}Líneas resaltadas: 21 a 23, 39 a 43.
Líneas resaltadas: 34 a 35.
Líneas resaltadas: 7 a 10.
Líneas resaltadas: 3 a 4.
export function beginWork(current: Fiber | null, workInProgress: Fiber): Fiber | null {
switch (workInProgress.tag) {
case FunctionComponent:
return updateFunctionComponent(current, workInProgress, workInProgress.type, workInProgress.pendingProps);
case HostRoot:
return updateHostRoot(current, workInProgress);
case HostComponent:
case Fragment:
reconcileChildren(current, workInProgress, workInProgress.pendingProps.children);
return workInProgress.child;
case HostText:
return null; // leaf
}
throw new Error(`Unknown fiber tag ${workInProgress.tag}`);
}
export function reconcileChildren(current: Fiber | null, workInProgress: Fiber, nextChildren: any): void {
if (current === null) {
// MOUNT: this fiber was never on screen. Create the children, leave no flags.
workInProgress.child = mountChildFibers(workInProgress, null, nextChildren);
} else {
// UPDATE: compare with the children that are on screen, and flag the differences.
workInProgress.child = reconcileChildFibers(workInProgress, current.child, nextChildren);
}
}
function updateFunctionComponent(
current: Fiber | null,
workInProgress: Fiber,
Component: (props: any) => any,
nextProps: any,
): Fiber | null {
// This is the line that calls your component.
const nextChildren = Component(nextProps);
reconcileChildren(current, workInProgress, nextChildren);
return workInProgress.child;
}
function updateHostRoot(current: Fiber | null, workInProgress: Fiber): Fiber | null {
const nextChildren = workInProgress.memoizedState.element;
reconcileChildren(current, workInProgress, nextChildren);
return workInProgress.child;
}Líneas resaltadas: 5, 7.
function commitRoot(root: FiberRoot): void {
// The tree the render phase just finished: the alternate of the tree on screen.
const finishedWork = root.current.alternate!;
// 1. Mutation: the only call in the library that changes what the user sees.
commitMutationEffects(finishedWork);
// 2. The swap: the work-in-progress tree is now the current tree.
root.current = finishedWork;
}current es null solo para un fiber que es nuevo en este render. root.ts no cambia:
render() sigue guardando { element } en root.current, y createWorkInProgress
copia memoizedState.
Los cambios en src/mini-react/work-loop.ts
Con createWorkInProgress añadido al import de ./fiber:
/** Start a walk: make the work-in-progress version of the HostRoot and point the cursor at it. */
export function prepareFreshStack(root: FiberRoot): void {
workInProgress = createWorkInProgress(root.current, null);
}
function performUnitOfWork(unitOfWork: Fiber): void {
// The same fiber in the tree that is on screen. null = this fiber is new.
const current = unitOfWork.alternate;
if (walkLog.enabled) console.log(`begin ${getFiberName(unitOfWork)}`);
const next = beginWork(current, unitOfWork);
// This fiber has rendered with these props: remember them for the next comparison.
unitOfWork.memoizedProps = unitOfWork.pendingProps;
if (next === null) completeUnitOfWork(unitOfWork);
else workInProgress = next;
}
/** Complete this fiber, then move to its sibling, or complete the parent. */
function completeUnitOfWork(unitOfWork: Fiber): void {
let completedWork: Fiber | null = unitOfWork;
do {
const current: Fiber | null = completedWork.alternate;
if (walkLog.enabled) console.log(`complete ${getFiberName(completedWork)}`);
completeWork(current, completedWork);
const sibling: Fiber | null = completedWork.sibling;
if (sibling !== null) {
workInProgress = sibling;
return;
}
completedWork = completedWork.return;
workInProgress = completedWork;
} while (completedWork !== null);
}Comparar: el diff con keys se muda aquí
El diff ya está escrito: es el código de Diff con keys. Aquella lección usaba un
fiber de relleno con los mismos nombres de campo que el de verdad, así que el código
funciona aquí tal cual. En child-fiber.ts, la versión de First paint (que solo sabía
crear fibers) se va y entra la de Diff con keys. Hay que añadir tres cosas que no
manejaba: un primer render, hijos que no son elementos y un hijo que no es una lista.
Mount frente a update. En la lección Diff con keys, un "primer render" ponía un Placement en
cada hijo. Para una lista nueva de mil filas serían mil inserciones en la página
viva, donde First paint necesitaba un solo append. Por eso las funciones
viven ahora en un closure sobre un booleano, shouldTrackSideEffects, y el
closure se crea dos veces. Con false, deleteChild no hace nada y
placeChild solo escribe el índice. reconcileChildren en begin-work.ts elige
una para cada fiber. Este es el primer render de la demo del final de esta lección,
con su árbol reducido al contador y la lista:
El árbol de fibers de la demo, reducido al contador y la lista: HostRoot, App, div, y bajo div Counter (un p con los textos "Count: ", "0" y " " y un button con "+1") y un ul con sus cuatro filas plegadas. HostRoot se reconcilió con su gemelo; todos los demás fibers son nuevos. Solo App lleva Placement, y los subtreeFlags del HostRoot guardan ese único Placement.
Paso 1 de 5
- El primer
root.render(<App />).createRootdejó unHostRootvacío en pantalla, así que elHostRootdel work-in-progress tiene gemelo: sucurrentno es null, yreconcileChildrentoma el camino de actualización. Appno tiene fiber viejo, así que el diff crea uno. Este padre registra efectos, yplaceSingleChildmarca al hijo nuevo conPlacement.- Ahora renderiza
App, yAppno tienecurrent: sus hijos pasan pormountChildFibers, dondeshouldTrackSideEffectses false. Ningún flag. Y así hasta abajo: todos los fibers de debajo son nuevos, así que todos se montan. - De subida,
completeWorkcrea cada nodo del DOM y le añade sus hijos. La tarjeta entera se construye en memoria, fuera de la página, y nada bajoApplleva flags. bubblePropertiessube el flag deApp: lossubtreeFlagsdelHostRootguardan unPlacement. El commit hará una sola llamada al DOM,appendChild(#root, <div>), con toda la tarjeta dentro.
Líneas resaltadas: 5 a 6, 21 a 23, 39 a 43.
Líneas resaltadas: 18 a 20, 34 a 35.
export function beginWork(current: Fiber | null, workInProgress: Fiber): Fiber | null {
switch (workInProgress.tag) {
case FunctionComponent:
return updateFunctionComponent(current, workInProgress, workInProgress.type, workInProgress.pendingProps);
case HostRoot:
return updateHostRoot(current, workInProgress);
case HostComponent:
case Fragment:
reconcileChildren(current, workInProgress, workInProgress.pendingProps.children);
return workInProgress.child;
case HostText:
return null; // leaf
}
throw new Error(`Unknown fiber tag ${workInProgress.tag}`);
}
export function reconcileChildren(current: Fiber | null, workInProgress: Fiber, nextChildren: any): void {
if (current === null) {
// MOUNT: this fiber was never on screen. Create the children, leave no flags.
workInProgress.child = mountChildFibers(workInProgress, null, nextChildren);
} else {
// UPDATE: compare with the children that are on screen, and flag the differences.
workInProgress.child = reconcileChildFibers(workInProgress, current.child, nextChildren);
}
}
function updateFunctionComponent(
current: Fiber | null,
workInProgress: Fiber,
Component: (props: any) => any,
nextProps: any,
): Fiber | null {
// This is the line that calls your component.
const nextChildren = Component(nextProps);
reconcileChildren(current, workInProgress, nextChildren);
return workInProgress.child;
}
function updateHostRoot(current: Fiber | null, workInProgress: Fiber): Fiber | null {
const nextChildren = workInProgress.memoizedState.element;
reconcileChildren(current, workInProgress, nextChildren);
return workInProgress.child;
}Líneas resaltadas: 2 a 4.
/** An only child cannot move. It needs a Placement only if it is new. */
function placeSingleChild(newFiber: Fiber): Fiber {
if (shouldTrackSideEffects && newFiber.alternate === null) newFiber.flags |= Placement;
return newFiber;
}Línea resaltada: 2.
Línea resaltada: 4.
/** The parent was on screen before: compare, and leave flags. */
export const reconcileChildFibers = createChildReconciler(true);
/** The parent is new: just create the fibers. */
export const mountChildFibers = createChildReconciler(false);Líneas resaltadas: 20 a 23.
Líneas resaltadas: 43 a 51.
export function completeWork(current: Fiber | null, workInProgress: Fiber): void {
const newProps = workInProgress.pendingProps;
switch (workInProgress.tag) {
case FunctionComponent:
case Fragment:
case HostRoot:
// No DOM node of their own.
bubbleProperties(workInProgress);
return;
case HostComponent: {
if (current !== null) {
// UPDATE: diff old props against new props. The DOM is changed later, in the commit.
const updatePayload = diffProperties(current.memoizedProps, newProps);
if (updatePayload !== null) {
workInProgress.updateQueue = updatePayload;
workInProgress.flags |= Update;
}
} else {
// MOUNT: create the DOM node and put the child DOM nodes inside it.
const instance = createInstance(workInProgress.type, newProps);
appendAllChildren(instance, workInProgress);
workInProgress.stateNode = instance;
}
bubbleProperties(workInProgress);
return;
}
case HostText: {
if (current !== null) {
if (current.memoizedProps !== newProps) workInProgress.flags |= Update;
} else {
workInProgress.stateNode = createTextInstance(newProps);
}
bubbleProperties(workInProgress);
return;
}
}
throw new Error(`Unknown fiber tag ${workInProgress.tag}`);
}
/** OR the flags of every child, and of everything below each child, into `subtreeFlags`. */
export function bubbleProperties(completedWork: Fiber): void {
let subtreeFlags = NoFlags;
let child = completedWork.child;
while (child !== null) {
subtreeFlags |= child.subtreeFlags | child.flags;
child = child.sibling;
}
completedWork.subtreeFlags |= subtreeFlags;
}Hijos que no son elementos.
- El texto no tiene key, así que se empareja por posición (
updateTextNode). falseynullno crean ningún fiber. Eso deja un hueco en los índices, y la comprobaciónoldFiber.index > newIdxdel primer bucle evita que un hueco que se llena desplace a todos los fibers que vienen detrás.- Un array dentro de un array se convierte en un fiber
Fragment, de modo que las keys de dos.map()vecinos no puedan colisionar. First paint los aplanaba, lo cual era suficiente mientras nadie leía las keys.
Un hijo que no es un array. La mayoría de los componentes devuelven un
elemento. reconcileSingleElement busca un fiber viejo con la misma key: mismo
tipo, lo reutiliza y borra los demás; tipo distinto, borra todo y crea.
El punto de entrada, reconcileChildFibers, envía cada tipo de hijo a su función:
- un elemento:
reconcileSingleElement, y despuésplaceSingleChild; - un array:
reconcileChildrenArray, los tres pasos de Diff con keys; - texto:
reconcileSingleTextNode; null,undefined, un booleano o'': no hay nada que dibujar, así que se borran todos los hijos viejos.
Un <>…</> sin key en la cima cuenta como sus hijos.
El src/mini-react/child-fiber.ts completo
Sin cambios respecto a Diff con keys: deleteRemainingChildren,
useFiber, mapRemainingChildren, el cuerpo de placeChild a partir de su segunda
línea, y la estructura en tres pasos de reconcileChildrenArray.
/**
* CHILD RECONCILIATION ("the diffing algorithm")
* ==============================================
*
* Input: the current child fibers of one parent (what is on screen)
* the new children (what the component just returned)
* Output: the work-in-progress child fibers, with flags:
* - Placement on fibers that are new or that MOVED
* - ChildDeletion on the parent, with the removed fibers in parent.deletions
*
* An old fiber is REUSED when key AND type match: its DOM node survives.
* Otherwise a new one is created.
*
* On MOUNT (the parent has no current fiber) side effects are not tracked: the
* whole new subtree is built off-screen, and only its top fiber gets one Placement.
*/
import {
type Fiber,
ChildDeletion,
Fragment,
HostText,
Placement,
createFiberFromElement,
createFiberFromFragment,
createFiberFromText,
createWorkInProgress,
} from './fiber';
import { REACT_ELEMENT_TYPE, REACT_FRAGMENT_TYPE, type ReactElement } from './shared';
function isElement(x: any): x is ReactElement {
return typeof x === 'object' && x !== null && x.$$typeof === REACT_ELEMENT_TYPE;
}
function isText(x: any): x is string | number {
return (typeof x === 'string' && x !== '') || typeof x === 'number';
}
function createChildReconciler(shouldTrackSideEffects: boolean) {
function deleteChild(returnFiber: Fiber, childToDelete: Fiber): void {
if (!shouldTrackSideEffects) return;
if (returnFiber.deletions === null) {
returnFiber.deletions = [childToDelete];
returnFiber.flags |= ChildDeletion;
} else {
returnFiber.deletions.push(childToDelete);
}
}
function deleteRemainingChildren(returnFiber: Fiber, currentFirstChild: Fiber | null): null {
let child = currentFirstChild;
while (child !== null) {
deleteChild(returnFiber, child);
child = child.sibling;
}
return null;
}
/** Reuse an existing fiber with new props. */
function useFiber(fiber: Fiber, pendingProps: any): Fiber {
const clone = createWorkInProgress(fiber, pendingProps);
clone.index = 0;
clone.sibling = null;
return clone;
}
/** Reuse `current` if it is a text fiber, otherwise create one. */
function updateTextNode(returnFiber: Fiber, current: Fiber | null, textContent: string): Fiber {
if (current === null || current.tag !== HostText) {
const created = createFiberFromText(textContent);
created.return = returnFiber;
return created;
}
const existing = useFiber(current, textContent);
existing.return = returnFiber;
return existing;
}
/** Reuse `current` if the type matches, otherwise create a new fiber. */
function updateElement(returnFiber: Fiber, current: Fiber | null, element: ReactElement): Fiber {
if (element.type === REACT_FRAGMENT_TYPE) {
return updateFragment(returnFiber, current, element.props.children, element.key);
}
if (current !== null && current.type === element.type) {
const existing = useFiber(current, element.props);
existing.return = returnFiber;
return existing;
}
const created = createFiberFromElement(element);
created.return = returnFiber;
return created;
}
/** Reuse `current` if it is a fragment fiber, otherwise create one. */
function updateFragment(returnFiber: Fiber, current: Fiber | null, fragment: any, key: string | null): Fiber {
if (current === null || current.tag !== Fragment) {
const created = createFiberFromFragment(fragment, key);
created.return = returnFiber;
return created;
}
const existing = useFiber(current, { children: fragment });
existing.return = returnFiber;
return existing;
}
/** One child -> one new fiber. null for the children that draw nothing. */
function createChild(returnFiber: Fiber, newChild: any): Fiber | null {
let created: Fiber;
if (isText(newChild)) created = createFiberFromText('' + newChild);
else if (isElement(newChild)) created = createFiberFromElement(newChild);
else if (Array.isArray(newChild)) created = createFiberFromFragment(newChild, null);
else return null; // null, undefined, true, false, ''
created.return = returnFiber;
return created;
}
/** Try to reuse `oldFiber` for `newChild` at the same position. null = keys don't match. */
function updateSlot(returnFiber: Fiber, oldFiber: Fiber | null, newChild: any): Fiber | null {
const key = oldFiber !== null ? oldFiber.key : null;
if (isText(newChild)) {
if (key !== null) return null; // text has no key, the old fiber has one
return updateTextNode(returnFiber, oldFiber, '' + newChild);
}
if (isElement(newChild)) {
return newChild.key === key ? updateElement(returnFiber, oldFiber, newChild) : null;
}
if (Array.isArray(newChild)) {
if (key !== null) return null;
return updateFragment(returnFiber, oldFiber, newChild, null);
}
return null; // a child that draws nothing never matches
}
/** The old fibers that are left, by key. Children without a key go in by index. */
function mapRemainingChildren(currentFirstChild: Fiber): Map<string | number, Fiber> {
const existingChildren = new Map<string | number, Fiber>();
let existingChild: Fiber | null = currentFirstChild;
while (existingChild !== null) {
existingChildren.set(existingChild.key !== null ? existingChild.key : existingChild.index, existingChild);
existingChild = existingChild.sibling;
}
return existingChildren;
}
function updateFromMap(existingChildren: Map<string | number, Fiber>, returnFiber: Fiber, newIdx: number, newChild: any): Fiber | null {
if (isText(newChild)) {
return updateTextNode(returnFiber, existingChildren.get(newIdx) ?? null, '' + newChild);
}
if (isElement(newChild)) {
const matchedFiber = existingChildren.get(newChild.key === null ? newIdx : newChild.key) ?? null;
return updateElement(returnFiber, matchedFiber, newChild);
}
if (Array.isArray(newChild)) {
return updateFragment(returnFiber, existingChildren.get(newIdx) ?? null, newChild, null);
}
return null;
}
/**
* Decide whether `newFiber` needs a Placement (insert or move).
*
* `lastPlacedIndex` is the largest OLD index among the children we have kept in
* place so far. A reused child whose old index is smaller than that used to be on
* the left of a child that is now before it, so it has to move.
*
* old: A(0) B(1) C(2) new: C A B
* C: oldIndex 2 >= 0 -> stays, lastPlacedIndex = 2
* A: oldIndex 0 < 2 -> MOVE
* B: oldIndex 1 < 2 -> MOVE
*/
function placeChild(newFiber: Fiber, lastPlacedIndex: number, newIndex: number): number {
newFiber.index = newIndex;
if (!shouldTrackSideEffects) return lastPlacedIndex;
const current = newFiber.alternate;
if (current !== null) {
const oldIndex = current.index;
if (oldIndex < lastPlacedIndex) {
newFiber.flags |= Placement; // reused, but it moved
return lastPlacedIndex;
}
return oldIndex; // reused and it can stay where it is
}
newFiber.flags |= Placement; // brand new: insert it
return lastPlacedIndex;
}
/** An only child cannot move. It needs a Placement only if it is new. */
function placeSingleChild(newFiber: Fiber): Fiber {
if (shouldTrackSideEffects && newFiber.alternate === null) newFiber.flags |= Placement;
return newFiber;
}
/**
* Real React's algorithm, in three steps:
* 1. Walk old and new in parallel while keys match (the common "nothing moved" case).
* 2. If new ran out: delete the rest of old. If old ran out: create the rest of new.
* 3. Otherwise put the remaining old fibers in a Map by key (or index) and look each
* new child up in it. Whatever is left in the map at the end gets deleted.
*/
function reconcileChildrenArray(returnFiber: Fiber, currentFirstChild: Fiber | null, newChildren: any[]): Fiber | null {
let resultingFirstChild: Fiber | null = null;
let previousNewFiber: Fiber | null = null;
let oldFiber = currentFirstChild;
let lastPlacedIndex = 0;
let newIdx = 0;
let nextOldFiber: Fiber | null = null;
const link = (fiber: Fiber) => {
if (previousNewFiber === null) resultingFirstChild = fiber;
else previousNewFiber.sibling = fiber;
previousNewFiber = fiber;
};
// Step 1: in-order matching.
for (; oldFiber !== null && newIdx < newChildren.length; newIdx++) {
if (oldFiber.index > newIdx) {
// The old list had a hole here (a `false` or a `null`): nothing to compare with.
nextOldFiber = oldFiber;
oldFiber = null;
} else {
nextOldFiber = oldFiber.sibling;
}
const newFiber = updateSlot(returnFiber, oldFiber, newChildren[newIdx]);
if (newFiber === null) {
if (oldFiber === null) oldFiber = nextOldFiber;
break; // keys differ: go to the slow path
}
if (shouldTrackSideEffects && oldFiber && newFiber.alternate === null) {
// Same key, but we couldn't reuse the fiber (type changed): delete the old one.
deleteChild(returnFiber, oldFiber);
}
lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
link(newFiber);
oldFiber = nextOldFiber;
}
// Step 2a: new children exhausted.
if (newIdx === newChildren.length) {
deleteRemainingChildren(returnFiber, oldFiber);
return resultingFirstChild;
}
// Step 2b: old children exhausted, the rest are insertions.
if (oldFiber === null) {
for (; newIdx < newChildren.length; newIdx++) {
const newFiber = createChild(returnFiber, newChildren[newIdx]);
if (newFiber === null) continue;
lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
link(newFiber);
}
return resultingFirstChild;
}
// Step 3: keyed lookup.
const existingChildren = mapRemainingChildren(oldFiber);
for (; newIdx < newChildren.length; newIdx++) {
const newFiber = updateFromMap(existingChildren, returnFiber, newIdx, newChildren[newIdx]);
if (newFiber === null) continue;
if (shouldTrackSideEffects && newFiber.alternate !== null) {
// It was reused: remove it from the map so it isn't deleted.
existingChildren.delete(newFiber.key === null ? newIdx : newFiber.key);
}
lastPlacedIndex = placeChild(newFiber, lastPlacedIndex, newIdx);
link(newFiber);
}
if (shouldTrackSideEffects) existingChildren.forEach((child) => deleteChild(returnFiber, child));
return resultingFirstChild;
}
/** The new child is ONE piece of text. Keep the first old fiber if it is text; delete the rest. */
function reconcileSingleTextNode(returnFiber: Fiber, currentFirstChild: Fiber | null, textContent: string): Fiber {
if (currentFirstChild !== null && currentFirstChild.tag === HostText) {
deleteRemainingChildren(returnFiber, currentFirstChild.sibling);
const existing = useFiber(currentFirstChild, textContent);
existing.return = returnFiber;
return existing;
}
deleteRemainingChildren(returnFiber, currentFirstChild);
const created = createFiberFromText(textContent);
created.return = returnFiber;
return created;
}
/** The new child is ONE element. Look for an old fiber with its key and type; delete all the others. */
function reconcileSingleElement(returnFiber: Fiber, currentFirstChild: Fiber | null, element: ReactElement): Fiber {
let child = currentFirstChild;
while (child !== null) {
if (child.key === element.key) {
const sameType = element.type === REACT_FRAGMENT_TYPE ? child.tag === Fragment : child.type === element.type;
if (sameType) {
// Match: delete its siblings, reuse this one.
deleteRemainingChildren(returnFiber, child.sibling);
const existing = useFiber(child, element.props);
existing.return = returnFiber;
return existing;
}
// Same key, different type: nothing can be reused.
deleteRemainingChildren(returnFiber, child);
break;
}
deleteChild(returnFiber, child);
child = child.sibling;
}
const created = createFiberFromElement(element);
created.return = returnFiber;
return created;
}
function reconcileChildFibers(returnFiber: Fiber, currentFirstChild: Fiber | null, newChild: any): Fiber | null {
// <>...</> without a key, at the top: the same as returning its children directly.
if (isElement(newChild) && newChild.type === REACT_FRAGMENT_TYPE && newChild.key === null) {
newChild = newChild.props.children;
}
if (isElement(newChild)) {
return placeSingleChild(reconcileSingleElement(returnFiber, currentFirstChild, newChild));
}
if (Array.isArray(newChild)) {
return reconcileChildrenArray(returnFiber, currentFirstChild, newChild);
}
if (isText(newChild)) {
return placeSingleChild(reconcileSingleTextNode(returnFiber, currentFirstChild, '' + newChild));
}
// null, undefined, true, false, '': nothing to draw. Whatever was there goes.
return deleteRemainingChildren(returnFiber, currentFirstChild);
}
return reconcileChildFibers;
}
/** The parent was on screen before: compare, and leave flags. */
export const reconcileChildFibers = createChildReconciler(true);
/** The parent is new: just create the fibers. */
export const mountChildFibers = createChildReconciler(false);El fiber de fragment en src/mini-react/fiber.ts, y src/mini-react/begin-work.ts
fiber.ts necesita el fiber de fragment que pide el reconciliador. getFiberName
gana un case Fragment: return 'Fragment';, y:
// Element -> fiber. The element says WHAT to render; its `type` decides the tag.
export function createFiberFromTypeAndProps(type: any, key: Key, pendingProps: any): Fiber {
let tag: WorkTag;
if (typeof type === 'function') {
tag = FunctionComponent;
} else if (typeof type === 'string') {
tag = HostComponent;
} else if (type === REACT_FRAGMENT_TYPE) {
return createFiberFromFragment(pendingProps.children, key);
} else {
throw new Error(`mini-react: unsupported element type: ${String(type)}`);
}
const fiber = createFiber(tag, pendingProps, key);
fiber.type = type;
return fiber;
}
/** A fragment has no DOM node and no function. It only groups children. */
export function createFiberFromFragment(children: any, key: Key): Fiber {
return createFiber(Fragment, { children }, key);
}beginWork pasa current hacia abajo, y reconcileChildren es donde se separan
mount y update:
import { type Fiber, Fragment, FunctionComponent, HostComponent, HostRoot, HostText } from './fiber';
import { mountChildFibers, reconcileChildFibers } from './child-fiber';
export function beginWork(current: Fiber | null, workInProgress: Fiber): Fiber | null {
switch (workInProgress.tag) {
case FunctionComponent:
return updateFunctionComponent(current, workInProgress, workInProgress.type, workInProgress.pendingProps);
case HostRoot:
return updateHostRoot(current, workInProgress);
case HostComponent:
case Fragment:
reconcileChildren(current, workInProgress, workInProgress.pendingProps.children);
return workInProgress.child;
case HostText:
return null; // leaf
}
throw new Error(`Unknown fiber tag ${workInProgress.tag}`);
}
export function reconcileChildren(current: Fiber | null, workInProgress: Fiber, nextChildren: any): void {
if (current === null) {
// MOUNT: this fiber was never on screen. Create the children, leave no flags.
workInProgress.child = mountChildFibers(workInProgress, null, nextChildren);
} else {
// UPDATE: compare with the children that are on screen, and flag the differences.
workInProgress.child = reconcileChildFibers(workInProgress, current.child, nextChildren);
}
}
function updateFunctionComponent(
current: Fiber | null,
workInProgress: Fiber,
Component: (props: any) => any,
nextProps: any,
): Fiber | null {
// This is the line that calls your component.
const nextChildren = Component(nextProps);
reconcileChildren(current, workInProgress, nextChildren);
return workInProgress.child;
}
function updateHostRoot(current: Fiber | null, workInProgress: Fiber): Fiber | null {
const nextChildren = workInProgress.memoizedState.element;
reconcileChildren(current, workInProgress, nextChildren);
return workInProgress.child;
}Component(nextProps) sigue siendo incondicional. Cada componente se vuelve a
llamar en cada root.render(), incluso con props idénticas. Saltarse un componente
con seguridad exige saber que nada de lo que hay dentro ha cambiado, y eso llega
con el estado. Por ahora, lo único mínimo es el trabajo sobre el DOM.
Tomar notas al subir
El completeWork de First paint creaba un nodo del DOM para cada fiber del host. En un segundo render
el nodo ya existe, así que hay una rama de update: compara las props con
diffProperties de Host del DOM, deja los nombres que cambiaron en updateQueue y activa
Update. Todavía no se toca el nodo. Después bubbleProperties pliega los flags de
los hijos en el subtreeFlags del padre. Este es el render tras un clic en el +1
de la demo, camino hacia arriba:
El árbol de fibers tras un clic en +1, reducido al contador y la lista. El texto "1" y el button llevan Update; p, Counter, div, App y HostRoot tienen Update en sus subtreeFlags; el ul y sus filas, nada.
Paso 1 de 8
- Un clic en
+1llama aroot.render()concount: 1. El render bajó por el árbol, ycompleteWorkcorre en cada fiber cuando sus hijos han terminado, así que las notas se toman de abajo arriba. Las dos filas de botones no están dibujadas. "Count: "tiene el mismo texto que la última vez: ningún flag. El siguiente fiber de texto tenía"0"y ahora tiene"1":Update. El nodo de texto del DOM todavía dice 0.- El
buttonrecibe unonClicknuevo en cada render, una arrow function nueva, ydiffPropertieslo reporta:updateQueue = ["onClick"], yUpdate. - El
pno tiene nada propio que cambiar (childrenno es una prop que el diff compare).bubblePropertiesune con OR los flags de sus hijos en sussubtreeFlags:Update. Counterno tiene nodo del DOM, así que solo propaga:Updateen sussubtreeFlags.- El
uly sus cuatro filas: las mismas props, el mismo texto. Ningún flag, y sussubtreeFlagsquedan vacíos. divune elUpdatedeCountercon la nada de la lista. Solo mira un nivel hacia abajo: cada hijo ya lleva el resumen de su propio subárbol.AppyHostRootpropagan al final. LossubtreeFlagsde la raíz dicen “hay unUpdateen algún sitio de abajo”, y los vacíos del camino dicen dónde no hay nada.
Líneas resaltadas: 1 a 3.
Líneas resaltadas: 29 a 31.
Líneas resaltadas: 14 a 18.
Líneas resaltadas: 14 a 15, 43 a 51.
Líneas resaltadas: 4 a 9.
Líneas resaltadas: 14 a 15.
Líneas resaltadas: 43 a 51.
Líneas resaltadas: 4 a 9.
export function completeWork(current: Fiber | null, workInProgress: Fiber): void {
const newProps = workInProgress.pendingProps;
switch (workInProgress.tag) {
case FunctionComponent:
case Fragment:
case HostRoot:
// No DOM node of their own.
bubbleProperties(workInProgress);
return;
case HostComponent: {
if (current !== null) {
// UPDATE: diff old props against new props. The DOM is changed later, in the commit.
const updatePayload = diffProperties(current.memoizedProps, newProps);
if (updatePayload !== null) {
workInProgress.updateQueue = updatePayload;
workInProgress.flags |= Update;
}
} else {
// MOUNT: create the DOM node and put the child DOM nodes inside it.
const instance = createInstance(workInProgress.type, newProps);
appendAllChildren(instance, workInProgress);
workInProgress.stateNode = instance;
}
bubbleProperties(workInProgress);
return;
}
case HostText: {
if (current !== null) {
if (current.memoizedProps !== newProps) workInProgress.flags |= Update;
} else {
workInProgress.stateNode = createTextInstance(newProps);
}
bubbleProperties(workInProgress);
return;
}
}
throw new Error(`Unknown fiber tag ${workInProgress.tag}`);
}
/** OR the flags of every child, and of everything below each child, into `subtreeFlags`. */
export function bubbleProperties(completedWork: Fiber): void {
let subtreeFlags = NoFlags;
let child = completedWork.child;
while (child !== null) {
subtreeFlags |= child.subtreeFlags | child.flags;
child = child.sibling;
}
completedWork.subtreeFlags |= subtreeFlags;
}bubbleProperties es la razón por la que el commit puede ser barato. Los hijos se
completan antes que los padres, así que cada fiber solo mira un nivel hacia abajo,
y cuando el recorrido llega a la raíz, root.subtreeFlags resume el árbol entero.
El nuevo completeWork y bubbleProperties en src/mini-react/complete-work.ts
Los imports ganan Fragment, NoFlags, Update y diffProperties, y
appendAllChildren deja de exportarse.
export function completeWork(current: Fiber | null, workInProgress: Fiber): void {
const newProps = workInProgress.pendingProps;
switch (workInProgress.tag) {
case FunctionComponent:
case Fragment:
case HostRoot:
// No DOM node of their own.
bubbleProperties(workInProgress);
return;
case HostComponent: {
if (current !== null) {
// UPDATE: diff old props against new props. The DOM is changed later, in the commit.
const updatePayload = diffProperties(current.memoizedProps, newProps);
if (updatePayload !== null) {
workInProgress.updateQueue = updatePayload;
workInProgress.flags |= Update;
}
} else {
// MOUNT: create the DOM node and put the child DOM nodes inside it.
const instance = createInstance(workInProgress.type, newProps);
appendAllChildren(instance, workInProgress);
workInProgress.stateNode = instance;
}
bubbleProperties(workInProgress);
return;
}
case HostText: {
if (current !== null) {
if (current.memoizedProps !== newProps) workInProgress.flags |= Update;
} else {
workInProgress.stateNode = createTextInstance(newProps);
}
bubbleProperties(workInProgress);
return;
}
}
throw new Error(`Unknown fiber tag ${workInProgress.tag}`);
}
/** OR the flags of every child, and of everything below each child, into `subtreeFlags`. */
export function bubbleProperties(completedWork: Fiber): void {
let subtreeFlags = NoFlags;
let child = completedWork.child;
while (child !== null) {
subtreeFlags |= child.subtreeFlags | child.flags;
child = child.sibling;
}
completedWork.subtreeFlags |= subtreeFlags;
}En este punto la fase de render está completa y el commit sigue siendo el
appendAllChildren de First paint. Ejecutar la demo de First paint es instructivo: un clic ya no añade una
segunda tarjeta (no se crearon nodos nuevos del DOM), pero la cuenta se queda en 0.
Un fiber de texto lleva un flag Update, y nadie lo lee.
Aplicar: la pasada de mutación
Un archivo nuevo, commit-work.ts, es el único que cambia la página. Recorre el
árbol terminado y convierte cada flag en llamadas al DOM: ChildDeletion quita los
nodos de los fibers de deletions, Placement inserta (o mueve) los nodos de un
fiber y Update aplica las props que cambiaron o el texto nuevo.
El recorrido. recursivelyTraverseMutationEffects solo baja por donde
subtreeFlags dice que hay trabajo. Para cada fiber: primero todo lo que tiene
debajo, luego su propio Placement y después su propio Update. El commit del
mismo clic en +1:
El mismo árbol tras el commit: el recorrido visitó HostRoot, App, div, Counter, p y sus hijos, y el ul; el texto "+1" y las filas del ul se saltaron. En la parte dibujada, dos llamadas al DOM: el nodeValue del nodo de texto pasa de "0" a "1", y luego commitUpdate en el button con ["onClick"]. Cada botón que no está dibujado recibe también su propio commitUpdate.
Llamadas al DOM
"0".nodeValue = "1"commitUpdate(<button>, ["onClick"])Paso 1 de 6
commitMutationEffectsrecibe el árbol terminado. Los flags están en los fibers; en la página todavía no ha cambiado nada. La tira muestra los hijos delpen el DOM.HostRoot,App,div,Counter,p: cada uno tieneUpdateen sussubtreeFlags, así que el recorrido entra en sus hijos."Count: "no tiene nada que hacer. El siguiente fiber de texto tieneUpdate: su nodo del DOM recibenodeValue = "1", el primer cambio que ve la página.- Primero los hijos: los
subtreeFlagsdelbuttonestán vacíos, así que"+1"no se visita. Luego su propioUpdate:commitUpdatecambia el listener deonClick. La página se ve igual. - Los
subtreeFlagsdelulestán vacíos: una comprobación, y ninguna de sus filas se visita. Dos llamadas al DOM en la parte dibujada. Los otros siete botones de la demo reciben cada uno unUpdatepor suonClicknuevo, así que el commit entero hace nueve llamadas, y el documento ve una: el texto. - La pasada de mutación terminó y la página coincide con el árbol nuevo. Solo ahora
commitRootapuntaroot.currenta él: durante la pasada,currenttodavía era el árbol viejo, de donde se leen las props viejas.
Líneas resaltadas: 16 a 22.
Líneas resaltadas: 7 a 12.
Línea resaltada: 33.
Líneas resaltadas: 7, 25 a 30.
Línea resaltada: 7.
function recursivelyTraverseMutationEffects(parentFiber: Fiber): void {
// Deletions first. They are stored on the parent: a deleted fiber is not in the new tree.
const deletions = parentFiber.deletions;
if (deletions !== null) {
for (const childToDelete of deletions) commitDeletionEffects(parentFiber, childToDelete);
}
if (parentFiber.subtreeFlags & MutationMask) {
let child = parentFiber.child;
while (child !== null) {
commitMutationEffectsOnFiber(child);
child = child.sibling;
}
}
}
function commitMutationEffectsOnFiber(finishedWork: Fiber): void {
const current = finishedWork.alternate;
const flags = finishedWork.flags;
// Everything below this fiber first, then its own Placement, then its own Update.
recursivelyTraverseMutationEffects(finishedWork);
commitReconciliationEffects(finishedWork);
switch (finishedWork.tag) {
case HostComponent:
if (flags & Update) {
const updatePayload: string[] = finishedWork.updateQueue;
finishedWork.updateQueue = null;
commitUpdate(finishedWork.stateNode, updatePayload, current!.memoizedProps, finishedWork.memoizedProps);
}
return;
case HostText:
if (flags & Update) finishedWork.stateNode.nodeValue = finishedWork.memoizedProps;
return;
}
}
function commitReconciliationEffects(finishedWork: Fiber): void {
if (finishedWork.flags & Placement) {
commitPlacement(finishedWork);
// Done. Clear the bit so nothing takes this fiber for one that still has to be inserted.
finishedWork.flags &= ~Placement;
}
}Líneas resaltadas: 5, 7.
function commitRoot(root: FiberRoot): void {
// The tree the render phase just finished: the alternate of the tree on screen.
const finishedWork = root.current.alternate!;
// 1. Mutation: the only call in the library that changes what the user sees.
commitMutationEffects(finishedWork);
// 2. The swap: the work-in-progress tree is now the current tree.
root.current = finishedWork;
}Update. Para un elemento, commitUpdate de Host del DOM recibe la lista de
props que cambiaron, las props viejas (de current, que es para lo que sirve el
segundo árbol) y las nuevas. Una función onClick nueva es una prop cambiada, así
que el atajo temporal de addEventListener sigue funcionando: se quita el listener
viejo y se añade el nuevo. Para el texto, el nodo recibe la cadena nueva.
Placement. Dos preguntas: qué padre del DOM, y en qué sitio dentro de él. El
padre es el ancestro más cercano con un nodo del DOM (getHostParentFiber); los
componentes y los fragments no tienen ninguno. El "dónde" es la parte difícil.
insertBefore necesita el nodo del DOM que viene justo después del nuestro, y ese
no es fiber.sibling.stateNode, por tres razones, todas resueltas por
getHostSibling:
- el fiber hermano puede ser un componente o un fragment, así que su nodo del DOM está en algún lugar de su interior;
- el hermano puede llevar él mismo un
Placement, en cuyo caso su nodo está a punto de moverse (o todavía no está en el documento) y no puede servir de ancla; - puede que no haya hermano en este nivel y aun así siga un nodo del DOM, junto a un padre que es un componente o un fragment.
Si la búsqueda no encuentra nada estable, el nodo se añade al final. Si el fiber
que se coloca es a su vez un componente o un fragment, insertOrAppendPlacementNode
coloca cada uno de sus nodos del DOM de primer nivel. Estas son las filas de la
lista después de last to front, el caso que Diff con keys marcó tres veces:
Los fibers de la lista con keys tras el último al principio: Row D, Row A, Row B y Row C bajo el ul, cada una con su li. Los hijos del ul en el DOM acaban en el orden D A B C, tras tres llamadas a appendChild, para el li de A, B y C. Row D no se tocó.
Llamadas al DOM
appendChild(<ul>, <li>A)appendChild(<ul>, <li>B)appendChild(<ul>, <li>C)Paso 1 de 6
- La lista tras
last to front; solo está dibujada la lista. El diff dejóPlacementen las filas A, B y C, y D se queda. El DOM todavía tiene el orden viejo. - Bajando hasta el
ul. Primero vieneRow D: sin flags,subtreeFlagsvacíos, nada que hacer. Row A: primero sus hijos (nada), luego suPlacement. UnRowno tiene nodo del DOM, así que el padre es el ancestro host más cercano, elul. ¿En qué posición?getHostSiblingpruebaRow ByRow C: los dos llevanPlacement, así que están a punto de moverse y no sirven de ancla. Luego no quedan hermanos, y el padre es un nodo host: después de A no viene nada estable.- Así que A se añade al final.
insertOrAppendPlacementNodeentra en elRowhasta suliy llama aappendChild: el nodo se mueve al final. El bit dePlacementse borra. Row B:Row Ctodavía tienePlacement, así que B también va al final.Row Cno tiene hermanos: al final. D A B C en tres movimientos, los tres flags de Keyed diff. D, la fila que “se movió”, no se tocó.
Líneas resaltadas: 39 a 43.
Líneas resaltadas: 7 a 12.
Línea resaltada: 42.
function recursivelyTraverseMutationEffects(parentFiber: Fiber): void {
// Deletions first. They are stored on the parent: a deleted fiber is not in the new tree.
const deletions = parentFiber.deletions;
if (deletions !== null) {
for (const childToDelete of deletions) commitDeletionEffects(parentFiber, childToDelete);
}
if (parentFiber.subtreeFlags & MutationMask) {
let child = parentFiber.child;
while (child !== null) {
commitMutationEffectsOnFiber(child);
child = child.sibling;
}
}
}
function commitMutationEffectsOnFiber(finishedWork: Fiber): void {
const current = finishedWork.alternate;
const flags = finishedWork.flags;
// Everything below this fiber first, then its own Placement, then its own Update.
recursivelyTraverseMutationEffects(finishedWork);
commitReconciliationEffects(finishedWork);
switch (finishedWork.tag) {
case HostComponent:
if (flags & Update) {
const updatePayload: string[] = finishedWork.updateQueue;
finishedWork.updateQueue = null;
commitUpdate(finishedWork.stateNode, updatePayload, current!.memoizedProps, finishedWork.memoizedProps);
}
return;
case HostText:
if (flags & Update) finishedWork.stateNode.nodeValue = finishedWork.memoizedProps;
return;
}
}
function commitReconciliationEffects(finishedWork: Fiber): void {
if (finishedWork.flags & Placement) {
commitPlacement(finishedWork);
// Done. Clear the bit so nothing takes this fiber for one that still has to be inserted.
finishedWork.flags &= ~Placement;
}
}Líneas resaltadas: 23, 26, 29.
Líneas resaltadas: 47, 51 a 55.
Líneas resaltadas: 47, 51 a 55.
Líneas resaltadas: 47, 51 a 55.
/** The nearest ancestor that has a DOM node: components and fragments have none. */
function getHostParentFiber(fiber: Fiber): Fiber {
let parent = fiber.return;
while (parent !== null) {
if (isHostParent(parent)) return parent;
parent = parent.return;
}
throw new Error('Expected to find a host parent.');
}
/**
* Find the DOM node we must insert BEFORE: the next host node to the right in
* the fiber tree that is already at its place, i.e. NOT flagged Placement itself.
* The search goes through siblings, down into components and fragments (they
* have no DOM node of their own) and up through parents that are not host nodes.
* null = nothing stable comes after us: append.
*/
function getHostSibling(fiber: Fiber): Node | null {
let node: Fiber = fiber;
siblings: while (true) {
// No sibling: climb. A host parent ends the search, nothing comes after us inside it.
while (node.sibling === null) {
if (node.return === null || isHostParent(node.return)) return null;
node = node.return;
}
node = node.sibling;
// Not a DOM node: look inside it for its first one.
while (node.tag !== HostComponent && node.tag !== HostText) {
if (node.flags & Placement) continue siblings; // it is being placed too: its nodes are not stable
if (node.child === null) continue siblings; // it renders nothing
node = node.child;
}
if (!(node.flags & Placement)) return node.stateNode;
}
}
function commitPlacement(finishedWork: Fiber): void {
const parentFiber = getHostParentFiber(finishedWork);
const parent: Node = parentFiber.tag === HostRoot ? parentFiber.stateNode.containerInfo : parentFiber.stateNode;
const before = getHostSibling(finishedWork);
insertOrAppendPlacementNode(finishedWork, before, parent);
}
function insertOrAppendPlacementNode(node: Fiber, before: Node | null, parent: Node): void {
if (node.tag === HostComponent || node.tag === HostText) {
if (before) insertBefore(parent, node.stateNode, before);
else appendChild(parent, node.stateNode);
return;
}
// A component or a fragment: insert each of its top-level host nodes.
let child = node.child;
while (child !== null) {
insertOrAppendPlacementNode(child, before, parent);
child = child.sibling;
}
}Deletion. Un fiber borrado no está en el árbol nuevo, y por eso Diff con keys
lo guardó en su padre: el commit llega al padre y ejecuta sus deletions antes de
entrar en los hijos. Un nodo del DOM borrado se quita con un solo removeChild y
todo lo que tiene dentro se va con él; un componente borrado no tiene nodo, así que
la búsqueda baja hasta los nodos que renderizó. Cambiar la lista de la demo de ul
a ol borra un fiber y coloca otro:
El árbol tras cambiar la lista de ul a ol, sin el contador ni el botón de keys y con la primera fila de botones plegada: div tiene ChildDeletion y el ul viejo en sus deletions, el ol nuevo lleva Placement, y el botón de la lista y su texto "ol" llevan Update. Los hijos de div en el DOM pasan de ul, p, p a ol, p, p.
Llamadas al DOM
removeChild(<div>, <ul>)insertBefore(<div>, <ol>, <p>1)"ul".nodeValue = "ol"commitUpdate(<button>, ["onClick"])Paso 1 de 7
- El botón de la lista cambió
ulporol(el contador y el botón de keys no están dibujados, y la primera fila de botones está plegada: esos botones también reciben unUpdate, sin dibujar). Misma posición, otro tipo: el diff puso elulviejo endiv.deletions, conChildDeletion, y creó unolconPlacement, construido fuera de pantalla con sus filas. - Bajando hasta el
div: unChildDeletionpropio, yPlacementyUpdateen sussubtreeFlags. - Primero las deletions. El
ulviejo es un nodo del DOM: unremoveChild, y sus filas, sus inputs y lo escrito en ellos se van con él. No se visita nada de dentro. - Luego los hijos. El subárbol del
olse construyó fuera de pantalla, sin flags: se salta. Luego su propioPlacement: el siguiente hermano es el primerp, la fila de botones: un nodo del DOM sinPlacement, así que es un ancla estable. insertBefore(<div>, <ol>, <p>1): la lista nueva, con todo lo que tiene dentro, entra con una sola llamada, justo donde estaba elul.- Se visita la fila de botones (sus cinco
commitUpdateno están dibujados), luego el segundopy la etiqueta del botón de la lista: el fiber de texto que decía"ul"tieneUpdate, y su nodo recibenodeValue = "ol". - Por último, el
Updatedel propio botón, suonClicknuevo. Cuatro llamadas al DOM en la parte dibujada. Con el botón del contador, los cinco plegados y el botón de keys (sin dibujar), cada uno cambiando suonClick, el commit entero hace once; el documento ve tres.
Líneas resaltadas: 3 a 6.
Líneas resaltadas: 7 a 12.
Líneas resaltadas: 3 a 6.
Línea resaltada: 33.
Líneas resaltadas: 25 a 30.
function recursivelyTraverseMutationEffects(parentFiber: Fiber): void {
// Deletions first. They are stored on the parent: a deleted fiber is not in the new tree.
const deletions = parentFiber.deletions;
if (deletions !== null) {
for (const childToDelete of deletions) commitDeletionEffects(parentFiber, childToDelete);
}
if (parentFiber.subtreeFlags & MutationMask) {
let child = parentFiber.child;
while (child !== null) {
commitMutationEffectsOnFiber(child);
child = child.sibling;
}
}
}
function commitMutationEffectsOnFiber(finishedWork: Fiber): void {
const current = finishedWork.alternate;
const flags = finishedWork.flags;
// Everything below this fiber first, then its own Placement, then its own Update.
recursivelyTraverseMutationEffects(finishedWork);
commitReconciliationEffects(finishedWork);
switch (finishedWork.tag) {
case HostComponent:
if (flags & Update) {
const updatePayload: string[] = finishedWork.updateQueue;
finishedWork.updateQueue = null;
commitUpdate(finishedWork.stateNode, updatePayload, current!.memoizedProps, finishedWork.memoizedProps);
}
return;
case HostText:
if (flags & Update) finishedWork.stateNode.nodeValue = finishedWork.memoizedProps;
return;
}
}
function commitReconciliationEffects(finishedWork: Fiber): void {
if (finishedWork.flags & Placement) {
commitPlacement(finishedWork);
// Done. Clear the bit so nothing takes this fiber for one that still has to be inserted.
finishedWork.flags &= ~Placement;
}
}Líneas resaltadas: 24 a 25.
/** The DOM node the deletion in progress removes from. */
let hostParent: Node | null = null;
function commitDeletionEffects(returnFiber: Fiber, deletedFiber: Fiber): void {
// `returnFiber` may be the host parent itself (a <ul> losing an <li>), so the search starts AT it.
const parentFiber = isHostParent(returnFiber) ? returnFiber : getHostParentFiber(returnFiber);
hostParent = parentFiber.tag === HostRoot ? parentFiber.stateNode.containerInfo : parentFiber.stateNode;
commitDeletionEffectsOnFiber(deletedFiber);
hostParent = null;
}
function recursivelyTraverseDeletionEffects(parent: Fiber): void {
let child = parent.child;
while (child !== null) {
commitDeletionEffectsOnFiber(child);
child = child.sibling;
}
}
function commitDeletionEffectsOnFiber(deletedFiber: Fiber): void {
switch (deletedFiber.tag) {
case HostComponent:
case HostText:
// One removal. Do NOT go below it: everything inside leaves the page with it.
if (hostParent !== null) removeChild(hostParent, deletedFiber.stateNode);
return;
default:
// A component or a fragment has no DOM node: its nodes are further down.
recursivelyTraverseDeletionEffects(deletedFiber);
}
}Líneas resaltadas: 26, 33.
Línea resaltada: 46.
/** The nearest ancestor that has a DOM node: components and fragments have none. */
function getHostParentFiber(fiber: Fiber): Fiber {
let parent = fiber.return;
while (parent !== null) {
if (isHostParent(parent)) return parent;
parent = parent.return;
}
throw new Error('Expected to find a host parent.');
}
/**
* Find the DOM node we must insert BEFORE: the next host node to the right in
* the fiber tree that is already at its place, i.e. NOT flagged Placement itself.
* The search goes through siblings, down into components and fragments (they
* have no DOM node of their own) and up through parents that are not host nodes.
* null = nothing stable comes after us: append.
*/
function getHostSibling(fiber: Fiber): Node | null {
let node: Fiber = fiber;
siblings: while (true) {
// No sibling: climb. A host parent ends the search, nothing comes after us inside it.
while (node.sibling === null) {
if (node.return === null || isHostParent(node.return)) return null;
node = node.return;
}
node = node.sibling;
// Not a DOM node: look inside it for its first one.
while (node.tag !== HostComponent && node.tag !== HostText) {
if (node.flags & Placement) continue siblings; // it is being placed too: its nodes are not stable
if (node.child === null) continue siblings; // it renders nothing
node = node.child;
}
if (!(node.flags & Placement)) return node.stateNode;
}
}
function commitPlacement(finishedWork: Fiber): void {
const parentFiber = getHostParentFiber(finishedWork);
const parent: Node = parentFiber.tag === HostRoot ? parentFiber.stateNode.containerInfo : parentFiber.stateNode;
const before = getHostSibling(finishedWork);
insertOrAppendPlacementNode(finishedWork, before, parent);
}
function insertOrAppendPlacementNode(node: Fiber, before: Node | null, parent: Node): void {
if (node.tag === HostComponent || node.tag === HostText) {
if (before) insertBefore(parent, node.stateNode, before);
else appendChild(parent, node.stateNode);
return;
}
// A component or a fragment: insert each of its top-level host nodes.
let child = node.child;
while (child !== null) {
insertOrAppendPlacementNode(child, before, parent);
child = child.sibling;
}
}El src/mini-react/commit-work.ts completo
/**
* COMMIT PHASE: the mutation pass
* ===============================
*
* The render phase produced a finished work-in-progress tree whose fibers carry
* flags. This file reads the flags and touches the DOM. Nothing else does.
*
* ChildDeletion remove the DOM nodes of the fibers in `fiber.deletions`
* Placement insert (or move) the fiber's DOM nodes at their place
* Update apply the changed props, or the new text
*
* The traversal uses `subtreeFlags` to skip every subtree with nothing to do.
* Children are handled before their parent.
*/
import { type Fiber, HostComponent, HostRoot, HostText, MutationMask, Placement, Update } from './fiber';
import { appendChild, commitUpdate, insertBefore, removeChild } from './dom-host';
export function commitMutationEffects(finishedWork: Fiber): void {
commitMutationEffectsOnFiber(finishedWork);
}
function recursivelyTraverseMutationEffects(parentFiber: Fiber): void {
// Deletions first. They are stored on the parent: a deleted fiber is not in the new tree.
const deletions = parentFiber.deletions;
if (deletions !== null) {
for (const childToDelete of deletions) commitDeletionEffects(parentFiber, childToDelete);
}
if (parentFiber.subtreeFlags & MutationMask) {
let child = parentFiber.child;
while (child !== null) {
commitMutationEffectsOnFiber(child);
child = child.sibling;
}
}
}
function commitMutationEffectsOnFiber(finishedWork: Fiber): void {
const current = finishedWork.alternate;
const flags = finishedWork.flags;
// Everything below this fiber first, then its own Placement, then its own Update.
recursivelyTraverseMutationEffects(finishedWork);
commitReconciliationEffects(finishedWork);
switch (finishedWork.tag) {
case HostComponent:
if (flags & Update) {
const updatePayload: string[] = finishedWork.updateQueue;
finishedWork.updateQueue = null;
commitUpdate(finishedWork.stateNode, updatePayload, current!.memoizedProps, finishedWork.memoizedProps);
}
return;
case HostText:
if (flags & Update) finishedWork.stateNode.nodeValue = finishedWork.memoizedProps;
return;
}
}
function commitReconciliationEffects(finishedWork: Fiber): void {
if (finishedWork.flags & Placement) {
commitPlacement(finishedWork);
// Done. Clear the bit so nothing takes this fiber for one that still has to be inserted.
finishedWork.flags &= ~Placement;
}
}
// ---------------------------------------------------------------------------
// Placement
// ---------------------------------------------------------------------------
function isHostParent(fiber: Fiber): boolean {
return fiber.tag === HostComponent || fiber.tag === HostRoot;
}
/** The nearest ancestor that has a DOM node: components and fragments have none. */
function getHostParentFiber(fiber: Fiber): Fiber {
let parent = fiber.return;
while (parent !== null) {
if (isHostParent(parent)) return parent;
parent = parent.return;
}
throw new Error('Expected to find a host parent.');
}
/**
* Find the DOM node we must insert BEFORE: the next host node to the right in
* the fiber tree that is already at its place, i.e. NOT flagged Placement itself.
* The search goes through siblings, down into components and fragments (they
* have no DOM node of their own) and up through parents that are not host nodes.
* null = nothing stable comes after us: append.
*/
function getHostSibling(fiber: Fiber): Node | null {
let node: Fiber = fiber;
siblings: while (true) {
// No sibling: climb. A host parent ends the search, nothing comes after us inside it.
while (node.sibling === null) {
if (node.return === null || isHostParent(node.return)) return null;
node = node.return;
}
node = node.sibling;
// Not a DOM node: look inside it for its first one.
while (node.tag !== HostComponent && node.tag !== HostText) {
if (node.flags & Placement) continue siblings; // it is being placed too: its nodes are not stable
if (node.child === null) continue siblings; // it renders nothing
node = node.child;
}
if (!(node.flags & Placement)) return node.stateNode;
}
}
function commitPlacement(finishedWork: Fiber): void {
const parentFiber = getHostParentFiber(finishedWork);
const parent: Node = parentFiber.tag === HostRoot ? parentFiber.stateNode.containerInfo : parentFiber.stateNode;
const before = getHostSibling(finishedWork);
insertOrAppendPlacementNode(finishedWork, before, parent);
}
function insertOrAppendPlacementNode(node: Fiber, before: Node | null, parent: Node): void {
if (node.tag === HostComponent || node.tag === HostText) {
if (before) insertBefore(parent, node.stateNode, before);
else appendChild(parent, node.stateNode);
return;
}
// A component or a fragment: insert each of its top-level host nodes.
let child = node.child;
while (child !== null) {
insertOrAppendPlacementNode(child, before, parent);
child = child.sibling;
}
}
// ---------------------------------------------------------------------------
// Deletion
// ---------------------------------------------------------------------------
/** The DOM node the deletion in progress removes from. */
let hostParent: Node | null = null;
function commitDeletionEffects(returnFiber: Fiber, deletedFiber: Fiber): void {
// `returnFiber` may be the host parent itself (a <ul> losing an <li>), so the search starts AT it.
const parentFiber = isHostParent(returnFiber) ? returnFiber : getHostParentFiber(returnFiber);
hostParent = parentFiber.tag === HostRoot ? parentFiber.stateNode.containerInfo : parentFiber.stateNode;
commitDeletionEffectsOnFiber(deletedFiber);
hostParent = null;
}
function recursivelyTraverseDeletionEffects(parent: Fiber): void {
let child = parent.child;
while (child !== null) {
commitDeletionEffectsOnFiber(child);
child = child.sibling;
}
}
function commitDeletionEffectsOnFiber(deletedFiber: Fiber): void {
switch (deletedFiber.tag) {
case HostComponent:
case HostText:
// One removal. Do NOT go below it: everything inside leaves the page with it.
if (hostParent !== null) removeChild(hostParent, deletedFiber.stateNode);
return;
default:
// A component or a fragment has no DOM node: its nodes are further down.
recursivelyTraverseDeletionEffects(deletedFiber);
}
}commitRoot pasa a tener dos pasos: la pasada de mutación y después el cambio de
root.current (el último paso del commit del +1 de arriba).
El nuevo commitRoot en src/mini-react/work-loop.ts
Los imports de work-loop.ts cambian appendAllChildren por commitMutationEffects de ./commit-work:
// ---------------------------------------------------------------------------
// Commit phase
// ---------------------------------------------------------------------------
function commitRoot(root: FiberRoot): void {
// The tree the render phase just finished: the alternate of the tree on screen.
const finishedWork = root.current.alternate!;
// 1. Mutation: the only call in the library that changes what the user sees.
commitMutationEffects(finishedWork);
// 2. The swap: the work-in-progress tree is now the current tree.
root.current = finishedWork;
}El orden importa. Durante la pasada de mutación current sigue significando el
árbol viejo, de donde se leen las props viejas. El puntero se mueve cuando el DOM
ya coincide con el árbol nuevo.
El commit de una línea de First paint es ahora un caso particular. En el primer render
la raíz work-in-progress ya tiene un current (el fiber raíz vacío de
createRoot), así que App se reconcilia en modo de seguimiento y recibe un
Placement. Todo lo que hay debajo de App se monta sin flags y se construye
fuera de pantalla. El commit encuentra un flag y añade un nodo.
La demo
Todavía no hay estado, así que la demo guarda un objeto normal fuera de React y
cada botón llama a root.render() con una versión nueva. Un MutationObserver
escribe lo que vio el documento en un <pre> debajo de la tarjeta. Cuando un nodo
se quita y se vuelve a añadir en el mismo lote, imprime una sola línea: "moved".
El observador ve la página, no las llamadas: un listener cambiado por commitUpdate
no deja rastro en el log.
El código de la demo
/**
* DEMO — the reconciler
* =====================
*
* There is no state yet: every button calls root.render() again with different
* props. The box under the card lists what the DOCUMENT saw during that render.
*/
import { createRoot, walkLog } from 'mini-react';
interface State {
count: number;
items: string[];
keyed: boolean;
ordered: boolean;
}
let state: State = { count: 0, items: ['A', 'B', 'C', 'D'], keyed: true, ordered: false };
let nextLetter = 69; // 'E'
function Counter(props: { count: number }) {
return (
<p>
Count: {props.count} <button onClick={() => update({ count: props.count + 1 })}>+1</button>
</p>
);
}
function Row(props: { name: string }) {
return (
<li>
<b>{props.name}</b> <input placeholder="type here" />
</li>
);
}
function App(props: State) {
const { items, keyed, ordered } = props;
const List = ordered ? 'ol' : 'ul';
return (
<div className="card" style={{ width: 420, padding: 16, border: '1px solid gray', borderRadius: 8 }}>
<Counter count={props.count} />
<List>{items.map((name) => (keyed ? <Row key={name} name={name} /> : <Row name={name} />))}</List>
<p>
<button onClick={() => update({ items: [...items.slice(-1), ...items.slice(0, -1)] })}>last to front</button>
<button onClick={() => update({ items: [...items.slice(1), ...items.slice(0, 1)] })}>first to back</button>
<button onClick={() => update({ items: [String.fromCharCode(nextLetter++), ...items] })}>add to front</button>
<button onClick={() => update({ items: items.slice(1) })}>remove first</button>
<button onClick={() => update({ items: ['A', 'B', 'C', 'D'] })}>reset</button>
</p>
<p>
<button onClick={() => update({ keyed: !keyed })}>keys: {keyed ? 'on' : 'off'}</button>
<button onClick={() => update({ ordered: !ordered })}>list: {ordered ? 'ol' : 'ul'}</button>
</p>
</div>
);
}
const container = document.getElementById('root')!;
// The log lives OUTSIDE the container, so writing to it is not seen by the observer.
const log = document.createElement('pre');
document.body.append(log);
function show(node: Node): string {
if (node.nodeType === Node.TEXT_NODE) return `"${node.nodeValue}"`;
const text = node.textContent!.trim();
return `<${(node as Element).localName}> ${text.length > 10 ? text.slice(0, 10) + '…' : text}`;
}
// Everything the DOCUMENT sees happening inside the container, however deep.
new MutationObserver((records) => {
const lines: string[] = [];
const removedAt = new Map<Node, number>(); // node -> the index of its "removed" line
for (const record of records) {
if (record.type === 'characterData') lines.push(`text "${record.oldValue}" -> "${record.target.nodeValue}"`);
if (record.type === 'attributes') lines.push(`attribute ${record.attributeName} on ${show(record.target)}`);
for (const node of record.removedNodes) {
removedAt.set(node, lines.length);
lines.push(`removed ${show(node)}`);
}
for (const node of record.addedNodes) {
// Taken out and put back in during the same commit: the node MOVED.
const at = removedAt.get(node);
if (at === undefined) lines.push(`inserted ${show(node)}`);
else lines[at] = `moved ${show(node)}`;
}
}
log.textContent = `${lines.length} DOM operation(s)\n` + lines.map((line) => ` ${line}\n`).join('');
}).observe(container, {
childList: true,
subtree: true,
characterData: true,
characterDataOldValue: true,
attributes: true,
});
walkLog.enabled = false; // true prints every begin / complete
const root = createRoot(container);
function update(patch: Partial<State>) {
state = { ...state, ...patch };
log.textContent = '0 DOM operation(s)\n'; // the observer overwrites this if the document saw anything
root.render(<App {...state} />);
}
update({});Aquí tienes la demo en marcha, clic a clic: los nodos del DOM de la página como dos
tiras (el <p> del contador y la lista), lo que imprimió la caja del log y la línea
de la demo que ejecuta cada clic:
La página de la demo como dos tiras de nodos del DOM, y su caja de log. El p del contador tiene "Count: ", "1", " " y un botón. La lista ahora es un ol con tres nodos li nuevos, B, C y D. La caja de log imprimió 3 operaciones del DOM: removed <ul> B C D, inserted <ol> B C D y text "ul" -> "ol".
Lo que imprimió la caja de log
1 DOM operation(s) inserted <div> Count: 0 +…1 DOM operation(s) text "0" -> "1"3 DOM operation(s) moved <li> A moved <li> B moved <li> C1 DOM operation(s) moved <li> D1 DOM operation(s) moved <li> A3 DOM operation(s) moved <li> B moved <li> C moved <li> D3 DOM operation(s) moved <li> A moved <li> B moved <li> C1 DOM operation(s) moved <li> D9 DOM operation(s) removed <li> A removed <li> B removed <li> C removed <li> D inserted <li> A inserted <li> B inserted <li> C inserted <li> D text "on" -> "off"4 DOM operation(s) text "A" -> "D" text "B" -> "A" text "C" -> "B" text "D" -> "C"3 DOM operation(s) removed <ul> B C D inserted <ol> B C D text "ul" -> "ol"Paso 1 de 10
- El primer
update({}). La página está vacía, y el commit hace una sola llamada: la tarjeta entera entra de una vez. El observer ve un único insert, eldivcon todo dentro. - Un clic en
+1. Se vuelve a llamar a cada componente y se visitan más de cincuenta fibers, pero el documento ve una sola escritura: el nodo de texto pasa de"0"a"1". El mismo nodo, con texto nuevo. last to frontcon keys:[A,B,C,D] → [D,A,B,C]. A, B y C se mueven y D no se toca: los tres flags de Keyed diff, como movimientos reales del DOM. Cadalies el mismo nodo que antes.resetvuelve a ponerA B C D. Eso también es un movimiento, D de vuelta al final. El siguiente caso empieza aquí.first to back:[B,C,D,A]. Un movimiento, el de A. Hacia el final es la dirección barata.- Otro
reset, desde[B,C,D,A]: esta vez A se queda y B, C y D se mueven detrás, tres movimientos. Luego escribehello Aen el input de la fila A. React no sabe nada de eso: el texto vive en el nodo del DOM. last to frontotra vez. Con keys, el texto sigue a la fila A: elli, su input y lo escrito son un subárbol, y el subárbol se movió.reset(un movimiento, como la primera vez), luego apaga las keys y vuelve a escribir en la fila A. Apagarlas cambia todas las keys, así que ninguna fila vieja coincide: se quitan los cuatroliviejos, se insertan cuatro nuevos, y la etiqueta del botón pasa deonaoff. El primer texto se fue con las filas viejas.last to frontsin keys. Nada se mueve: las filas se emparejan por posición, así que React reescribe cuatro letras y deja cada nodo en su sitio. El input conhello Aahora está junto a D. Una key no es una pista de rendimiento; le dice a React qué fila es cuál.- Por último, tras
resetyremove first(B C D),list: ul. Misma posición, otro tipo: una eliminación, un insert de unolconstruido fuera de pantalla, y la etiqueta del botón. Las filas se ven igual, pero son nodos nuevos: lo escrito se perdió.
Línea resaltada: 106.
Línea resaltada: 23.
Línea resaltada: 44.
Línea resaltada: 48.
Línea resaltada: 45.
Líneas resaltadas: 31, 48.
Línea resaltada: 44.
Líneas resaltadas: 48, 51.
Línea resaltada: 44.
Línea resaltada: 52.
/**
* DEMO — the reconciler
* =====================
*
* There is no state yet: every button calls root.render() again with different
* props. The box under the card lists what the DOCUMENT saw during that render.
*/
import { createRoot, walkLog } from 'mini-react';
interface State {
count: number;
items: string[];
keyed: boolean;
ordered: boolean;
}
let state: State = { count: 0, items: ['A', 'B', 'C', 'D'], keyed: true, ordered: false };
let nextLetter = 69; // 'E'
function Counter(props: { count: number }) {
return (
<p>
Count: {props.count} <button onClick={() => update({ count: props.count + 1 })}>+1</button>
</p>
);
}
function Row(props: { name: string }) {
return (
<li>
<b>{props.name}</b> <input placeholder="type here" />
</li>
);
}
function App(props: State) {
const { items, keyed, ordered } = props;
const List = ordered ? 'ol' : 'ul';
return (
<div className="card" style={{ width: 420, padding: 16, border: '1px solid gray', borderRadius: 8 }}>
<Counter count={props.count} />
<List>{items.map((name) => (keyed ? <Row key={name} name={name} /> : <Row name={name} />))}</List>
<p>
<button onClick={() => update({ items: [...items.slice(-1), ...items.slice(0, -1)] })}>last to front</button>
<button onClick={() => update({ items: [...items.slice(1), ...items.slice(0, 1)] })}>first to back</button>
<button onClick={() => update({ items: [String.fromCharCode(nextLetter++), ...items] })}>add to front</button>
<button onClick={() => update({ items: items.slice(1) })}>remove first</button>
<button onClick={() => update({ items: ['A', 'B', 'C', 'D'] })}>reset</button>
</p>
<p>
<button onClick={() => update({ keyed: !keyed })}>keys: {keyed ? 'on' : 'off'}</button>
<button onClick={() => update({ ordered: !ordered })}>list: {ordered ? 'ol' : 'ul'}</button>
</p>
</div>
);
}
const container = document.getElementById('root')!;
// The log lives OUTSIDE the container, so writing to it is not seen by the observer.
const log = document.createElement('pre');
document.body.append(log);
function show(node: Node): string {
if (node.nodeType === Node.TEXT_NODE) return `"${node.nodeValue}"`;
const text = node.textContent!.trim();
return `<${(node as Element).localName}> ${text.length > 10 ? text.slice(0, 10) + '…' : text}`;
}
// Everything the DOCUMENT sees happening inside the container, however deep.
new MutationObserver((records) => {
const lines: string[] = [];
const removedAt = new Map<Node, number>(); // node -> the index of its "removed" line
for (const record of records) {
if (record.type === 'characterData') lines.push(`text "${record.oldValue}" -> "${record.target.nodeValue}"`);
if (record.type === 'attributes') lines.push(`attribute ${record.attributeName} on ${show(record.target)}`);
for (const node of record.removedNodes) {
removedAt.set(node, lines.length);
lines.push(`removed ${show(node)}`);
}
for (const node of record.addedNodes) {
// Taken out and put back in during the same commit: the node MOVED.
const at = removedAt.get(node);
if (at === undefined) lines.push(`inserted ${show(node)}`);
else lines[at] = `moved ${show(node)}`;
}
}
log.textContent = `${lines.length} DOM operation(s)\n` + lines.map((line) => ` ${line}\n`).join('');
}).observe(container, {
childList: true,
subtree: true,
characterData: true,
characterDataOldValue: true,
attributes: true,
});
walkLog.enabled = false; // true prints every begin / complete
const root = createRoot(container);
function update(patch: Partial<State>) {
state = { ...state, ...patch };
log.textContent = '0 DOM operation(s)\n'; // the observer overwrites this if the document saw anything
root.render(<App {...state} />);
}
update({});En cada clic se visitan más de cincuenta fibers y se llama a todos los componentes,
pero el documento solo ve lo que cambió. El cliffhanger de
First paint está resuelto, y los
movimientos son los que predijo la tabla de Diff con keys. Sin keys,
remove first quita el último <li> y renombra los demás. Una key no es una pista
de rendimiento; le dice a React qué fila es cuál.
Lo que imprimió la caja del log, clic a clic
First paint:
1 DOM operation(s)
inserted <div> Count: 0 +…Un clic en +1:
1 DOM operation(s)
text "0" -> "1"last to front, [A,B,C,D] → [D,A,B,C], con keys:
3 DOM operation(s)
moved <li> A
moved <li> B
moved <li> Creset, de vuelta a [A,B,C,D]:
1 DOM operation(s)
moved <li> Dfirst to back, [B,C,D,A]:
1 DOM operation(s)
moved <li> Areset otra vez, desde [B,C,D,A]:
3 DOM operation(s)
moved <li> B
moved <li> C
moved <li> Dreset una vez más (el mismo movimiento que la primera vez), y luego keys: on, que las desactiva:
9 DOM operation(s)
removed <li> A
removed <li> B
removed <li> C
removed <li> D
inserted <li> A
inserted <li> B
inserted <li> C
inserted <li> D
text "on" -> "off"Con "hello A" escrito otra vez en la fila A, last to front sin keys:
4 DOM operation(s)
text "A" -> "D"
text "B" -> "A"
text "C" -> "B"
text "D" -> "C"Tras reset y remove first, list: ul:
3 DOM operation(s)
removed <ul> B C D
inserted <ol> B C D
text "ul" -> "ol"Lo que hemos simplificado
- Sin bailout. Cada componente se vuelve a renderizar en cada
root.render(). - Sin estado, sin hooks, sin effects, sin refs. El commit tiene una sola pasada. Como nada necesita limpieza, un nodo del DOM borrado se quita sin visitar lo que hay dentro.
- Sin cola de actualizaciones en la raíz, sin scheduling.
render()escribe el elemento en el fiber raíz y hace todo el trabajo antes de devolver el control. - Los eventos siguen enganchándose por nodo con
addEventListener. Updatesolo cuando algo cambió. El React real marca un fiber del host siempre que su objeto de props es nuevo, para que los handlers de eventos delegados vean las props más recientes. Eso vuelve con el sistema de eventos de verdad.- El texto se escribe directamente con
nodeValue; el React real pasa por una función del host para eso.
Dónde encaja esto
Esta biblioteca es el tronco del siguiente hito, React con estado. Las actualizaciones todavía vienen de
fuera, llamando otra vez a root.render(), y siempre empiezan por arriba.
Las tres lecciones siguientes construyen por separado la memoria propia de un componente: la
lista de hooks en Lista de hooks, la cola de actualizaciones en Cola de actualizaciones, y las dos combinadas en Motor de estado. Luego se encuentran con este reconciliador:
un setState marcará un fiber, el render se saltará lo que no cambió, y
este commit aplicará el resto.