### Install Build Dependencies on macOS Source: https://github.com/harfbuzz/harfrust/blob/main/docs/ragel.md Installs necessary build tools for Ragel and its dependencies on macOS using Homebrew. ```sh brew install automake autoconf libtool ``` -------------------------------- ### Build Ragel Source: https://github.com/harfbuzz/harfrust/blob/main/docs/ragel.md Clones, configures, builds, and installs Ragel. Ensure to specify the installation path for colm using the --with-colm flag. ```sh cd .. git clone https://github.com/adrian-thurston/ragel ./autogen.sh # --with-colm takes the same path we used above ./configure --prefix=/path/to/ragel/install --with-colm=/path/to/colm/install make make install ``` -------------------------------- ### Build colm Dependency Source: https://github.com/harfbuzz/harfrust/blob/main/docs/ragel.md Clones, configures, builds, and installs the colm dependency, a prerequisite for Ragel. It's recommended to install to a custom path. ```sh git clone https://github.com/adrian-thurston/colm cd colm ./autogen.sh ./configure --prefix=/path/to/colm/install # prefer a custom path to /usr/local make make install ``` -------------------------------- ### Mark Render Started Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Logs the start of a render. This hook is called when the injected profiling hooks are available and the corresponding function is defined, passing the lanes. ```javascript function markRenderStarted(lanes) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markRenderStarted === 'function') { injectedProfilingHooks.markRenderStarted(lanes); } } } ``` -------------------------------- ### Start Profiler Timer Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Starts the profiler timer for a given fiber. Initializes actualStartTime if it's negative. ```javascript function startProfilerTimer(fiber) { profilerStartTime = now$1(); if (fiber.actualStartTime < 0) { fiber.actualStartTime = now$1(); } } ``` -------------------------------- ### Start Layout Effect Timer Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Starts the timer for measuring layout effect duration. ```javascript function startLayoutEffectTimer() { layoutEffectStartTime = now$1(); } ``` -------------------------------- ### Install hr-shape Source: https://github.com/harfbuzz/harfrust/blob/main/hr-shape/README.md Installs the hr-shape utility using Cargo. Ensure you have Rust and Cargo installed. ```bash cargo install hr-shape ``` -------------------------------- ### Start Transition Hook Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Initiates a React transition. It manages the pending state of the transition and updates React's batch configuration. ```javascript function startTransition(setPending, callback, options) { var previousPriority = getCurrentUpdatePriority(); setCurrentUpdatePriority(higherEventPriority(previousPriority, ContinuousEventPriority)); setPending(true); var prevTransition = ReactCurrentBatchConfig$2.transition; ReactCurrentBatchConfig$2.transition = {}; var currentTransition = ReactCurrentBatchConfig$2.transition; { ReactCurrentBatchConfig$2.transition._updatedFibers = new Set(); } try { setPending(false); callback(); } finally { setCurrentUpdatePriority(previousPriority); ReactCurrentBatchConfig$2.transition = prevTransition; { if (prevTransition === null && currentTransition._updatedFibers) { ``` -------------------------------- ### Check for Fallback Composition Start Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Identifies if a 'keydown' event, using a specific key code, signifies the start of a composition in a fallback scenario. ```javascript function isFallbackCompositionStart(domEventName, nativeEvent) { return domEventName === 'keydown' && nativeEvent.keyCode === START_KEYCODE; } ``` -------------------------------- ### Mark Component Layout Effect Mount Started Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Logs when a component's layout effect mount has started. This hook is called when the injected profiling hooks are available and the corresponding function is defined. ```javascript function markComponentLayoutEffectMountStarted(fiber) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectMountStarted === 'function') { injectedProfilingHooks.markComponentLayoutEffectMountStarted(fiber); } } } ``` -------------------------------- ### DOM Nesting Validation Setup Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Initializes the `validateDOMNesting` and `updatedAncestorInfo` functions. In a production environment, these are typically no-op functions. ```javascript var validateDOMNesting = function () {}; var updatedAncestorInfo = function () {}; ``` -------------------------------- ### React Instance Mapping Utilities Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Provides functions to get, check for, and set internal React instance data associated with a public-facing instance. ```javascript function get(key) { return key._reactInternals; } function has(key) { return key._reactInternals !== undefined; } function set(key, value) { key._reactInternals = value; } ``` -------------------------------- ### Prepare Portal Mount Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Prepares a portal instance for mounting by initiating the listening to all supported events. This is a setup step for portals within React DOM. ```javascript function preparePortalMount(portalInstance) { listenToAllSupportedEvents(portalInstance); } ``` -------------------------------- ### Get text selection start and end offsets Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Retrieves the selection start and end points for input, textarea, or contentEditable elements. Handles both modern browser APIs and older IE methods. ```javascript function getSelection(input) { var selection; if ('selectionStart' in input) { // Modern browser with input or textarea. selection = { start: input.selectionStart, end: input.selectionEnd }; } else { // Content editable or old IE textarea. selection = getOffsets(input); } return selection || { start: 0, end: 0 }; } ``` -------------------------------- ### Get First Hydratable Child Within Suspense Instance Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Finds the first hydratable child node within a suspense instance, starting from its next sibling. ```javascript function getFirstHydratableChildWithinSuspenseInstance(parentInstance) { return getNextHydratable(parentInstance.nextSibling); } ``` -------------------------------- ### Get Leaf Node in DOM Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Finds the first leaf node (a node without children) starting from a given DOM node. Traverses down the DOM tree via firstChild. ```javascript function getLeafNode(node) { while (node && node.firstChild) { node = node.firstChild; } return node; } ``` -------------------------------- ### Prepare Fresh Stack for Rendering Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Initializes the state for a new rendering pass, clearing previous work and setting up the root and work-in-progress fiber. It also handles cancellation of any pending timeouts. ```javascript function prepareFreshStack(root, lanes) { root.finishedWork = null; root.finishedLanes = NoLanes; var timeoutHandle = root.timeoutHandle; if (timeoutHandle !== noTimeout) { // The root previous suspended and scheduled a timeout to commit a fallback // state. Now that we have additional work, cancel the timeout. root.timeoutHandle = noTimeout; // $FlowFixMe Complains noTimeout is not a TimeoutID, despite the check above cancelTimeout(timeoutHandle); } if (workInProgress !== null) { var interruptedWork = workInProgress.return; while (interruptedWork !== null) { var current = interruptedWork.alternate; unwindInterruptedWork(current, interruptedWork); interruptedWork = interruptedWork.return; } } workInProgressRoot = root; var rootWorkInProgress = createWorkInProgress(root.current, null); workInProgress = rootWorkInProgress; workInProgressRootRenderLanes = subtreeRenderLanes = workInProgressRootIncludedLanes = lanes; workInProgressRootExitStatus = RootInProgress; workInProgressRootFatalError = null; workInProgressRootSkippedLanes = NoLanes; workInProgressRootInterleavedUpdatedLanes = NoLanes; workInProgressRootPingedLanes = NoLanes; workInProgressRootConcurrentErrors = null; workInProgressRootRecoverableErrors = null; finishQueueingConcurrentUpdates(); { ReactStrictModeWarnings.discardPendingWarnings(); } return rootWorkInProgress; } ``` -------------------------------- ### Get Next Hydratable Node Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Iterates through sibling nodes starting from the given node to find the next hydratable element or text node. It skips over non-hydratable nodes and specific comment nodes. ```javascript function getNextHydratable(node) { // Skip non-hydratable nodes. for (; node != null; node = node.nextSibling) { var nodeType = node.nodeType; if (nodeType === ELEMENT_NODE || nodeType === TEXT_NODE) { break; } if (nodeType === COMMENT_NODE) { var nodeData = node.data; if (nodeData === SUSPENSE_START_DATA || nodeData === SUSPENSE_FALLBACK_START_DATA || nodeData === SUSPENSE_PENDING_START_DATA) { break; } if (nodeData === SUSPENSE_END_DATA) { return null; } } } return node; } ``` -------------------------------- ### Mounting a Transition Hook Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Initializes and returns the pending state and the startTransition function for a transition hook. ```javascript function mountTransition() { var _mountState = mountState(false), isPending = _mountState[0], setPending = _mountState[1]; // The `start` method never changes. var start = startTransition.bind(null, setPending); var hook = mountWorkInProgressHook(); hook.memoizedState = start; return [isPending, start]; } ``` -------------------------------- ### Get Selection Offsets from Points Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Calculates the start and end character offsets of a text selection within a given outer DOM node. It handles cross-window selections and potential errors from accessing properties of anonymous DOM nodes. ```javascript function getOffsets(outerNode) { var ownerDocument = outerNode.ownerDocument; var win = ownerDocument && ownerDocument.defaultView || window; var selection = win.getSelection && win.getSelection(); if (!selection || selection.rangeCount === 0) { return null; } var anchorNode = selection.anchorNode, anchorOffset = selection.anchorOffset, focusNode = selection.focusNode, focusOffset = selection.focusOffset; // In Firefox, anchorNode and focusNode can be "anonymous divs", e.g. the // up/down buttons on an . Anonymous divs do not seem to // expose properties, triggering a "Permission denied error" if any of its // properties are accessed. The only seemingly possible way to avoid erroring // is to access a property that typically works for non-anonymous divs and // catch any error that may otherwise arise. See // https://bugzilla.mozilla.org/show_bug.cgi?id=208427 try { /* eslint-disable no-unused-expressions */ anchorNode.nodeType; focusNode.nodeType; /* eslint-enable no-unused-expressions */ } catch (e) { return null; } return getModernOffsetsFromPoints(outerNode, anchorNode, anchorOffset, focusNode, focusOffset); } ``` -------------------------------- ### Mounting Class Instance Logic Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Handles the initial mounting of a class component instance, including context, state initialization, and invoking lifecycle methods like componentWillMount and componentDidMount. ```javascript function mountClassInstance(workInProgress, ctor, newProps, renderLanes) { var instance = workInProgress.stateNode; var oldProps = workInProgress.memoizedProps; instance.props = oldProps; var oldContext = instance.context; var contextType = ctor.contextType; var nextContext = emptyContextObject; if (typeof contextType === 'object' && contextType !== null) { instance.context = readContext(contextType); } else { var unmaskedContext = getUnmaskedContext(workInProgress, ctor, true); instance.context = getMaskedContext(workInProgress, unmaskedContext); } { if (instance.state === newProps) { var componentName = getComponentNameFromType(ctor) || 'Component'; if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) { didWarnAboutDirectlyAssigningPropsToState.add(componentName); error('%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName); } } if (workInProgress.mode & StrictLegacyMode) { ReactStrictModeWarnings.recordLegacyContextWarning(workInProgress, instance); } { ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(workInProgress, instance); } } instance.state = workInProgress.memoizedState; var getDerivedStateFromProps = ctor.getDerivedStateFromProps; if (typeof getDerivedStateFromProps === 'function') { applyDerivedStateFromProps(workInProgress, ctor, getDerivedStateFromProps, newProps); instance.state = workInProgress.memoizedState; } // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) { callComponentWillMount(workInProgress, instance); // If we had additional state updates during this life-cycle, let's // process them now. processUpdateQueue(workInProgress, newProps, instance, renderLanes); instance.state = workInProgress.memoizedState; } if (typeof instance.componentDidMount === 'function') { var fiberFlags = Update; { fiberFlags |= LayoutStatic; } if ( (workInProgress.mode & StrictEffectsMode) !== NoMode) { fiberFlags |= MountLayoutDev; } workInProgress.flags |= fiberFlags; } } ``` -------------------------------- ### Start Passive Effect Timer Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Starts the timer for measuring passive effect duration. ```javascript function startPassiveEffectTimer() { passiveEffectStartTime = now$1(); } ``` -------------------------------- ### Compare Benchmark Results Source: https://github.com/harfbuzz/harfrust/blob/main/HARFBUZZ.md Use the `compare.py` script provided by the benchmark framework to compare benchmark results stored in JSON files. This is useful for tracking performance changes across runs. ```bash $ subprojects/benchmark-1.8.4/tools/compare.py benchmarks BEFORE.json AFTER.json ``` -------------------------------- ### React Profiling and Timing Variables Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt This snippet defines variables used for tracking commit times, layout effect start times, profiler start times, and passive effect start times. It is part of React's internal performance monitoring and profiling mechanisms. ```javascript var now$1 = unstable_now; var commitTime = 0; var layoutEffectStartTime = -1; var profilerStartTime = -1; var passiveEffectStartTime = -1; ``` -------------------------------- ### Track and Post-Mount for Input Elements Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Tracks input elements for potential cleanup and applies post-mount wrappers. This is part of the hydration process for input elements. ```javascript switch (tag) { case 'input': // TODO: Make sure we check if this is still unmounted or do any clean // up necessary since we never stop tracking anymore. track(domElement); postMountWrapper(domElement, rawProps, true); break; case 'textarea': // TODO: Make sure we check if this is still unmounted or do any clean // up necessary since we never stop tracking anymore. track(domElement); ``` -------------------------------- ### React DOM Profiler Commit Start Hook Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Marks the start of a commit phase in the profiler. It calls the `markCommitStarted` hook if available. ```javascript function markCommitStarted(lanes) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markCommitStarted === 'function') { injectedProfilingHooks.markCommitStarted(lanes); } } } ``` -------------------------------- ### Create Fiber Root Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Initializes a new Fiber root, which includes creating a FiberRootNode and an uninitialized host root Fiber. This is the entry point for creating a React root. ```javascript function createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, // TODO: We have several of these arguments that are conceptually part of the // host config, but because they are passed in at runtime, we have to thread // them through the root constructor. Perhaps we should put them all into a // single type, like a DynamicHostConfig that is defined by the renderer. identifierPrefix, onRecoverableError, transitionCallbacks) { var root = new FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onRecoverableError); // stateNode is any. var uninitializedFiber = createHostRootFiber(tag, isStrictMode); root.current = uninitializedFiber; uninitializedFiber.stateNode = root; { ``` -------------------------------- ### Begin Work Function Entry Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt The main entry point for the beginWork function, which initiates the render phase. ```javascript function beginWork(current, workInProgress, renderLanes) { { if (workInProgress._debugNeedsRemount && current !== null) { // This will restart the begin phase with a new fiber. return remountFiber(current, workInProgress, createFiberFromTypeAndProps(workInProgress.type, workInProgress.key, workInProgress.pendingProps, workInProgress._debugOwner || null, workInProgress.mode, workInProgress.lanes)); } } if (current !== null) { var oldProps = current.memoizedProps; var newProps = workInProgress.pendingProps; if (oldProps !== newProps || hasContextChanged() || ( // Force a re-render if the implementation changed due to hot reload: workInProgress.type !== current.type )) { // If props or context changed, mark the fiber as having performed work. // This may be unset if the props are determined to be equal later (memo). didReceiveUpdate = true; } else { // Neither props nor legacy context changes. Check if there's a pending // update or context change. var hasScheduledUpdateOrContext = checkScheduledUpdateOrContext(current, renderLanes); if (!hasScheduledUpdateOrContext && // If this is the second pass of an error or suspense boundary, there // may not be work scheduled on `current`, so we check for this flag. (workInProgress.flags & DidCapture) === NoFlags) { // No pending updates or context. Bail out now. didReceiveUpdate = false; return attemptEarlyBailoutIfNoScheduledUpdate(current, workInProgress, renderLanes); } if ((current.flags & ForceUpdateForLegacySuspense) !== NoFlags) { // This is a special case that only exists for legacy mode. ``` -------------------------------- ### Initialize Replayable Event Queues Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Initializes various queues and maps used for replaying events during hydration. This includes queues for discrete events, focus, drag, mouse, and pointer events. ```javascript var hasScheduledReplayAttempt = false; var queuedDiscreteEvents = []; var queuedFocus = null; var queuedDrag = null; var queuedMouse = null; var queuedPointers = new Map(); var queuedPointerCaptures = new Map(); var queuedExplicitHydrationTargets = []; ``` -------------------------------- ### Mounting Effect Implementation Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Internal implementation for mounting effects, setting up the effect hook with flags, create function, and dependencies. ```javascript function mountEffectImpl(fiberFlags, hookFlags, create, deps) { var hook = mountWorkInProgressHook(); var nextDeps = deps === undefined ? null : deps; currentlyRenderingFiber$1.flags |= fiberFlags; hook.memoizedState = pushEffect(HasEffect | hookFlags, create, undefined, nextDeps); } ``` -------------------------------- ### React DOM Profiler Component Render Start Hook Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Marks the start of a component render in the profiler. It calls the `markComponentRenderStarted` hook if available. ```javascript function markComponentRenderStarted(fiber) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentRenderStarted === 'function') { injectedProfilingHooks.markComponentRenderStarted(fiber); } } } ``` -------------------------------- ### Prepare Host Text Instance for Hydration Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Prepares a host text instance for hydration. It attempts to hydrate the text content and logs a mismatch error if hydration fails. ```javascript function prepareToHydrateHostTextInstance(fiber) { var textInstance = fiber.stateNode; var textContent = fiber.memoizedProps; var shouldUpdate = hydrateTextInstance(textInstance, textContent, fiber); if (shouldUpdate) { // We assume that prepareToHydrateHostTextInstance is called in a context where the // hydration parent is the parent host component of this host text. var returnFiber = hydrationParentFiber; if (returnFiber !== null) { switch (returnFiber.tag) { case HostRoot: { var parentContainer = returnFiber.stateNode.containerInfo; var isConcurrentMode = (returnFiber.mode & ConcurrentMode) !== NoMode; didNotMatchHydratedContainerTextInstance(parentContainer, textInstance, textContent, // TODO: Delete this argument when we remove the legacy root API. isConcurrentMode); break; } case HostComponent: { var parentType = returnFiber.type; var parentProps = returnFiber.memoizedProps; var parentInstance = returnFiber.stateNode; var _isConcurrentMode2 = (returnFiber.mode & ConcurrentMode) !== NoMode; didNotMatchHydratedTextInstance(parentType, parentProps, parentInstance, textInstance, textContent, // TODO: Delete this argument when we remove the legacy root API. _isConcurrentMode2); break; } } } } return shouldUpdate; } ``` -------------------------------- ### Mark Passive Effects Started Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Logs the start of passive effects. This hook is called when the injected profiling hooks are available and the corresponding function is defined, passing the lanes. ```javascript function markPassiveEffectsStarted(lanes) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markPassiveEffectsStarted === 'function') { injectedProfilingHooks.markPassiveEffectsStarted(lanes); } } } ``` -------------------------------- ### Mounting a Class Component in React DOM Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Handles the initial mounting of a class component, including context provider logic and state initialization. It ensures proper setup before the component is rendered. ```javascript workInProgress.updateQueue = null; // Push context providers early to prevent context stack mismatches. // During mounting we don't know the child context yet as the instance doesn't exist. // We will invalidate the child context in finishClassComponent() right after rendering. var hasContext = false; if (isContextProvider(Component)) { hasContext = true; pushContextProvider(workInProgress); } else { hasContext = false; } workInProgress.memoizedState = value.state !== null && value.state !== undefined ? value.state : null; initializeUpdateQueue(workInProgress); adoptClassInstance(workInProgress, value); mountClassInstance(workInProgress, Component, props, renderLanes); return finishClassComponent(null, workInProgress, Component, true, hasContext, renderLanes); } ``` -------------------------------- ### Mark Layout Effects Started Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Logs the start of layout effects. This hook is called when the injected profiling hooks are available and the corresponding function is defined, passing the lanes. ```javascript function markLayoutEffectsStarted(lanes) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markLayoutEffectsStarted === 'function') { injectedProfilingHooks.markLayoutEffectsStarted(lanes); } } } ``` -------------------------------- ### Prepare Rust Toolchain and Bindgen Source: https://github.com/harfbuzz/harfrust/blob/main/HARFBUZZ.md Ensures the nightly Rust toolchain is set as default, includes the Rust source component, and installs the bindgen-cli for building HarfBuzz with HarfRust support. ```sh $ rustup default nightly $ rustup component add rust-src $ cargo install bindgen-cli ``` -------------------------------- ### Mounting a Sync External Store in React Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt This function handles the initial mounting of a synchronous external store. It reads the initial snapshot, schedules subscription and consistency checks, and sets up effects for store updates. ```javascript function mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { var fiber = currentlyRenderingFiber$1; var hook = mountWorkInProgressHook(); var nextSnapshot; var isHydrating = getIsHydrating(); if (isHydrating) { if (getServerSnapshot === undefined) { throw new Error('Missing getServerSnapshot, which is required for ' + 'server-rendered content. Will revert to client rendering.'); } nextSnapshot = getServerSnapshot(); { if (!didWarnUncachedGetSnapshot) { if (nextSnapshot !== getServerSnapshot()) { error('The result of getServerSnapshot should be cached to avoid an infinite loop'); didWarnUncachedGetSnapshot = true; } } } } else { nextSnapshot = getSnapshot(); { if (!didWarnUncachedGetSnapshot) { var cachedSnapshot = getSnapshot(); if (!objectIs(nextSnapshot, cachedSnapshot)) { error('The result of getSnapshot should be cached to avoid an infinite loop'); didWarnUncachedGetSnapshot = true; } } } // Unless we're rendering a blocking lane, schedule a consistency check. // Right before committing, we will walk the tree and check if any of the // stores were mutated. // // We won't do this if we're hydrating server-rendered content, because if // the content is stale, it's already visible anyway. Instead we'll patch // it up in a passive effect. var root = getWorkInProgressRoot(); if (root === null) { throw new Error('Expected a work-in-progress root. This is a bug in React. Please file an issue.'); } if (!includesBlockingLane(root, renderLanes)) { pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot); } } // Read the current snapshot from the store on every render. This breaks the // normal rules of React, and only works because store updates are // always synchronous. hook.memoizedState = nextSnapshot; var inst = { value: nextSnapshot, getSnapshot: getSnapshot }; hook.queue = inst; // Schedule an effect to subscribe to the store. mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [subscribe]); // Schedule an effect to update the mutable instance fields. We will update // this whenever subscribe, getSnapshot, or value changes. Because there's no // clean-up function, and we track the deps correctly, we can call pushEffect // directly, without storing any additional state. For the same reason, we // don't need to set a static flag, either. // TODO: We can move this to the passive phase once we add a pre-commit // consistency check. See the next comment. fiber.flags |= Passive; pushEffect(HasEffect | Passive$1, updateStoreInstance.bind(null, fiber, inst, nextSnapshot, getSnapshot), undefined, null); return nextSnapshot; } ``` -------------------------------- ### Set text selection start and end offsets Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Sets the selection start and end points for an input or textarea element and focuses it. Adapts to different browser selection APIs. ```javascript function setSelection(input, offsets) { var start = offsets.start; var end = offsets.end; if (end === undefined) { end = start; } if ('selectionStart' in input) { input.selectionStart = start; input.selectionEnd = Math.min(end, input.value.length); } else { setOffsets(input, offsets); } } ``` -------------------------------- ### Prepare Host Instance for Hydration Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Prepares a host instance for hydration by attempting to match it with the current fiber. It returns true if an update payload is generated, indicating a change or a new ref. ```javascript function prepareToHydrateHostInstance(fiber, rootContainerInstance, hostContext) { var instance = fiber.stateNode; var shouldWarnIfMismatchDev = !didSuspendOrErrorDEV; var updatePayload = hydrateInstance(instance, fiber.type, fiber.memoizedProps, rootContainerInstance, hostContext, fiber, shouldWarnIfMismatchDev); // TODO: Type this specific to this type of component. fiber.updateQueue = updatePayload; // If the update payload indicates that there is a change or if there // is a new ref we mark this as an update. if (updatePayload !== null) { return true; } return false; } ``` -------------------------------- ### React DOM Profiler Component Passive Effect Mount Start Hook Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Marks the start of a passive effect mount for a component in the profiler. It calls the `markComponentPassiveEffectMountStarted` hook if available. ```javascript function markComponentPassiveEffectMountStarted(fiber) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectMountStarted === 'function') { injectedProfilingHooks.markComponentPassiveEffectMountStarted(fiber); } } } ``` -------------------------------- ### Mark Component Layout Effect Unmount Started Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Logs when a component's layout effect unmount has started. This hook is called when the injected profiling hooks are available and the corresponding function is defined. ```javascript function markComponentLayoutEffectUnmountStarted(fiber) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentLayoutEffectUnmountStarted === 'function') { injectedProfilingHooks.markComponentLayoutEffectUnmountStarted(fiber); } } } ``` -------------------------------- ### Initiate Commit Layout Effects Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Sets up and begins the process of committing layout effects for a given fiber root. ```javascript function commitLayoutEffects(finishedWork, root, committedLanes) { inProgressLanes = committedLanes; inProgressRoot = root; nextEffect = finishedWork; commitLayoutEffects_begin(finishedWork, root, committedLanes); inProgressLanes = null; inProgressRoot = null; } ``` -------------------------------- ### Schedule Initial Hydration on Root Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Schedules the initial hydration for a root, distinguishing it from subsequent updates and ensuring the initial render matches server output. ```javascript function scheduleInitialHydrationOnRoot(root, lane, eventTime) { // This is a special fork of scheduleUpdateOnFiber that is only used to // schedule the initial hydration of a root that has just been created. Most // of the stuff in scheduleUpdateOnFiber can be skipped. // // The main reason for this separate path, though, is to distinguish the // initial children from subsequent updates. In fully client-rendered roots // (createRoot instead of hydrateRoot), all top-level renders are modeled as // updates, but hydration roots are special because the initial render must // match what was rendered on the server. var current = root.current; current.lanes = lane; markRootUpdated(root, lane, eventTime); ensureRootIsScheduled(root, eventTime); } ``` -------------------------------- ### Mark Component Passive Effect Unmount Started Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Logs when a component's passive effect unmount has started. This hook is called when the injected profiling hooks are available and the corresponding function is defined. ```javascript function markComponentPassiveEffectUnmountStarted(fiber) { { if (injectedProfilingHooks !== null && typeof injectedProfilingHooks.markComponentPassiveEffectUnmountStarted === 'function') { injectedProfilingHooks.markComponentPassiveEffectUnmountStarted(fiber); } } } ``` -------------------------------- ### Legacy Root Creation (Hydration) Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Creates a legacy React root for hydration. It handles initial children, callbacks, and container setup for existing DOM structures. ```javascript function legacyCreateRootFromDOMContainer(container, initialChildren, parentComponent, callback, isHydrationContainer) { if (isHydrationContainer) { if (typeof callback === 'function') { var originalCallback = callback; callback = function () { var instance = getPublicRootInstance(root); originalCallback.call(instance); }; } var root = createHydrationContainer(initialChildren, callback, container, LegacyRoot, null, // hydrationCallbacks false, // isStrictMode false, // concurrentUpdatesByDefaultOverride, '', // identifierPrefix noopOnRecoverableError); container._reactRootContainer = root; markContainerAsRoot(root.current, container); var rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container; listenToAllSupportedEvents(rootContainerElement); flushSync(); return root; } else { // First clear any existing content. var rootSibling; while (rootSibling = container.lastChild) { container.removeChild(rootSibling); } if (typeof callback === 'function') { var _originalCallback = callback; callback = function () { var instance = getPublicRootInstance(_root); _originalCallback.call(instance); }; } var _root = createContainer(container, LegacyRoot, null, // hydrationCallbacks false, // isStrictMode false, // concurrentUpdatesByDefaultOverride, '', // identifierPrefix noopOnRecoverableError); container._reactRootContainer = _root; markContainerAsRoot(_root.current, container); var _rootContainerElement = container.nodeType === COMMENT_NODE ? container.parentNode : container; listenToAllSupportedEvents(_rootContainerElement); // Initial mount should not be batched. flushSync(function () { updateContainer(initialChildren, _root, parentComponent, callback); }); return _root; } } ``` -------------------------------- ### Get Context Name Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Retrieves the display name for a React context, defaulting to 'Context'. ```javascript function getContextName(type) { return type.displayName || 'Context'; } ``` -------------------------------- ### Create React Portal Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Creates a React Portal, which allows rendering children into a different DOM subtree. Supports an optional key. ```javascript function createPortal(children, containerInfo, // TODO: figure out the API for cross-renderer implementation. implementation) { var key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; { checkKeyStringCoercion(key); } return { // This tag allow us to uniquely identify this as a React Portal $$typeof: REACT_PORTAL_TYPE, key: key == null ? null : '' + key, children: children, containerInfo: containerInfo, implementation: implementation }; } ``` -------------------------------- ### createRoot Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Creates a React root for a given DOM container. This is the entry point for concurrent React applications. ```APIDOC ## createRoot ### Description Creates a React root for a given DOM container. This is the entry point for concurrent React applications. ### Method `createRoot(container, [options])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **container** (DOMElement) - Required - The DOM element to which the React application will be rendered. - **options** (object) - Optional - Configuration options for the root. - **unstable_strictMode** (boolean) - Optional - Enables React Strict Mode. - **identifierPrefix** (string) - Optional - Prefix for component instance identifiers. - **onRecoverableError** (function) - Optional - Callback for recoverable errors. - **transitionCallbacks** (object) - Optional - Callbacks for transitions. ``` -------------------------------- ### Numeric HTML Attributes Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Configures HTML attributes that must be numbers. This includes 'rowSpan' and 'start'. ```javascript ['rowSpan', 'start'].forEach(function (name) { properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty name.toLowerCase(), // attributeName null, // attributeNamespace false, // sanitizeURL false); }); ``` -------------------------------- ### Get Next Hydratable Sibling Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Finds the next hydratable sibling node of a given instance. ```javascript function getNextHydratableSibling(instance) { return getNextHydratable(instance.nextSibling); } ``` -------------------------------- ### Create Container for React Root Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Creates a container for a React root, used for initializing the application. It sets up hydration and other root-specific properties. ```javascript function createContainer(containerInfo, tag, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError, transitionCallbacks) { var hydrate = false; var initialChildren = null; return createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, concurrentUpdatesByDefaultOverride, identifierPrefix, onRecoverableError); } ``` -------------------------------- ### React Transition Request Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Retrieves the current transition configuration, if any. ```javascript var ReactCurrentBatchConfig$1 = ReactSharedInternals.ReactCurrentBatchConfig; var NoTransition = null; function requestCurrentTransition() { return ReactCurrentBatchConfig$1.transition; } ``` -------------------------------- ### Get Event Listener Set Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Retrieves or initializes the Set of event listeners for a given DOM node. ```javascript function getEventListenerSet(node) { var elementListenerSet = node[internalEventHandlersKey]; if (elementListenerSet === undefined) { elementListenerSet = node[internalEventHandlersKey] = new Set(); } return elementListenerSet; } ``` -------------------------------- ### Get First Hydratable Child Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Finds the first hydratable child node within a parent instance. ```javascript function getFirstHydratableChild(parentInstance) { return getNextHydratable(parentInstance.firstChild); } ``` -------------------------------- ### Mount Class Instance Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Initializes a class component instance by setting its props, state, refs, and update queue. This function is called during the mounting phase of a component's lifecycle. ```javascript // Invokes the mount life-cycles on a previously never rendered instance. function mountClassInstance(workInProgress, ctor, newProps, renderLanes) { { checkClassInstance(workInProgress, ctor, newProps); } var instance = workInProgress.stateNode; instance.props = newProps; instance.state = workInProgress.memoizedState; instance.refs = emptyRefsObject; initializeUpdateQueue(workInProgress); } ``` -------------------------------- ### Get Container from Fiber Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Extracts the DOM container information from a fiber if it is a HostRoot. Returns null otherwise. ```javascript function getContainerFromFiber(fiber) { return fiber.tag === HostRoot ? fiber.stateNode.containerInfo : null; } ``` -------------------------------- ### Prepare to Read Context Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Initializes the context reading process for a given fiber. It resets dependency tracking and checks for pending context updates. ```javascript function prepareToReadContext(workInProgress, renderLanes) { currentlyRenderingFiber = workInProgress; lastContextDependency = null; lastFullyObservedContext = null; var dependencies = workInProgress.dependencies; if (dependencies !== null) { { var firstContext = dependencies.firstContext; if (firstContext !== null) { if (includesSomeLane(dependencies.lanes, renderLanes)) { // Context list has a pending update. Mark that this fiber performed work. markWorkInProgressReceivedUpdate(); } // Reset the work-in-progress list dependencies.firstContext = null; } } } } ``` -------------------------------- ### Get Current Fiber for DevTools Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Returns the current fiber being processed, which is essential for DevTools to inspect the component tree. ```javascript getCurrentFiberForDevTools = function () { return current; }; ``` -------------------------------- ### Updating Class Instance Props, State, and Context Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt This snippet demonstrates the process of updating a class component's instance with new props, state, and context. It includes logic for handling context changes and scheduling effects. ```javascript function updateClassInstance(current, workInProgress, ctor, newProps, renderLanes) { var instance = workInProgress.stateNode; cloneUpdateQueue(current, workInProgress); var unresolvedOldProps = workInProgress.memoizedProps; var oldProps = workInProgress.type === workInProgress.elementType ? unresolvedOldProps : resolveDefaultProps(workInProgress.type, unresolvedOldProps); instance.props = oldProps; var unresolvedNewProps = workInProgress.pendingProps; var oldContext = instance.context; var contextType = ctor.contextType; var nextContext = emptyContextObject; if (typeof contextType === 'object' && contextType !== null) { nextContext = readContext(contextType); } else { var nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true); nextContext = getMaskedContext(workInProgress, nextUnmaskedContext); } var getDerivedStateFromProps = ctor.getDerivedStateFromProps; var hasNewLifecycles = typeof getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function'; // Note: During these life-cycles, instance.props/instance.state are what // ever the previously attempted to render - not the "current". However, // during componentDidUpdate we pass the "current" props. // In order to support react-lifecycles-compat polyfilled components, // Unsafe lifecycles should not be invoked for components using the new APIs. if (!hasNewLifecycles && (typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function')) { if (unresolvedOldProps !== unresolvedNewProps || oldContext !== nextContext) { callComponentWillReceiveProps(workInProgress, instance, newProps, nextContext); } } resetHasForceUpdateBeforeProcessing(); var oldState = workInProgress.memoizedState; var newState = instance.state = oldState; processUpdateQueue(workInProgress, newProps, instance, renderLanes); newState = workInProgress.memoizedState; if (unresolvedOldProps === unresolvedNewProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing() && !(enableLazyContextPropagation )) { // If an update was already in progress, we should schedule an Update // effect even though we're bailing out, so that cWU/cDU are called. if (typeof instance.componentDidUpdate === 'function') { if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) { workInProgress.flags |= Update; } } if (typeof instance.getSnapshotBeforeUpdate === 'function') { if (unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState) { ``` -------------------------------- ### Get Parent Suspense Instance Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Recursively searches for the nearest parent suspense instance by traversing up the DOM tree. ```javascript function getParentSuspenseInstance(node) { var suspenseInstance = null; do { // Skip suspense components that have already been rendered. We're only // interested in ones that are still pending. if (node.pendingSuspenseBoundaries !== undefined) { // We found a suspense boundary. If it's already been rendered, we'll // skip it. Otherwise, we'll return it. var pendingSuspenseBoundaries = node.pendingSuspenseBoundaries; if (pendingSuspenseBoundaries !== null) { suspenseInstance = node; } } else { // This is not a suspense boundary. Skip it. } node = node.parentNode; } while (node !== null && suspenseInstance === null); return suspenseInstance; } ``` -------------------------------- ### Get Parent Suspense Instance Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Identifies the parent suspense boundary comment node for a given DOM node. ```javascript function getParentSuspenseInstance(targetInstance) { var node = targetInstance.previousSibling; // Skip past all nodes within this suspense boundary. // There might be nested nodes so we need to keep track of how // deep we are and only break out when we're back on top. var depth = 0; while (node) { if (node.nodeType === COMMENT_NODE) { var data = node.data; if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA) { if (depth === 0) { return node; } else { depth--; } } else if (data === SUSPENSE_END_DATA) { depth++; } } node = node.previousSibling; } return null; } ``` -------------------------------- ### Get Highest Priority Pending Lanes Source: https://github.com/harfbuzz/harfrust/blob/main/harfrust/benches/texts/react-dom.txt Retrieves the highest priority lanes from a root's pending lanes. ```javascript function getHighestPriorityPendingLanes(root) { return getHighestPriorityLanes(root.pendingLanes); } ```