Skip to content

Commit 266c571

Browse files
rubennortefacebook-github-bot
authored andcommitted
Add direct-event fast path to EventTarget dispatch (rnIsDirect)
Summary: Direct events (those that neither bubble nor capture, such as `onLayout`) were still dispatched through the full W3C event-path algorithm when using the EventTarget-based dispatcher: the path was built by walking every ancestor up to the root, and the capture phase then iterated over all of them, even though a direct event only ever fires on its target. This made direct-event dispatch scale with tree depth (O(depth)). This introduces a "direct" event mode on `Event`: - A new RN-specific `rnIsDirect` option on `EventInit` (with a matching `rnIsDirect` getter). A direct event has only an `AT_TARGET` phase and an event path containing just the target node. - Construction validation: an event cannot be both `rnIsDirect` and `bubbles`; the constructor throws a `TypeError` for that combination. - When `rnIsDirect` is set, the event path is restricted to the target, so dispatch skips the ancestor walk and capture-phase traversal (O(1)). The renderer opts native direct events into this fast path (behind a runtime gate) by tagging them with `rnIsDirect` at the dispatch site. Bubbling events that merely skip bubbling (e.g. `onPointerEnter`) still have a capture phase and are intentionally not treated as direct. This is gated and defaults off, so there is no behavior change by default. Benchmark results (median dispatch latency for the new `onLayout` direct-event benchmarks; all use the same stable-tree setup so depth is directly comparable): | onLayout dispatch | EventTarget off (baseline) | EventTarget on, direct off | EventTarget on, direct on | | --- | --- | --- | --- | | flat (1 handler) | 12.7us | 20.7us | 18.2us | | nested 10 deep | 12.7us | 33.4us | 18.1us | | nested 50 deep | 12.7us | 82.2us | 18.2us | Without the fast path, EventTarget dispatch of a direct event scales with tree depth (20.7us -> 33.4us -> 82.2us). The fast path restores O(1): dispatch cost is flat across depth (~18us) and the nested-50-deep case drops from ~82.2us to ~18.2us (~4.5x faster), approaching the legacy baseline (~12.7us). The EventTarget-off numbers are unchanged by the direct-events flag, confirming the flag is correctly gated. Changelog: [Internal] Differential Revision: D110759162
1 parent 2e36e63 commit 266c571

7 files changed

Lines changed: 374 additions & 2 deletions

File tree

packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1014,6 +1014,17 @@ const definitions: FeatureFlagDefinitions = {
10141014
},
10151015
ossReleaseStage: 'none',
10161016
},
1017+
enableDirectEventsInEventTarget: {
1018+
defaultValue: false,
1019+
metadata: {
1020+
dateAdded: '2026-07-06',
1021+
description:
1022+
'When enabled (together with enableNativeEventTargetEventDispatching), direct events (those that neither bubble nor capture, such as onLayout) are dispatched only to the target node via a fast path that skips construction and traversal of the ancestor event path.',
1023+
expectedReleaseValue: true,
1024+
purpose: 'experimentation',
1025+
},
1026+
ossReleaseStage: 'none',
1027+
},
10171028
enableImperativeEvents: {
10181029
defaultValue: false,
10191030
metadata: {

packages/react-native/src/private/featureflags/ReactNativeFeatureFlags.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
* This source code is licensed under the MIT license found in the
55
* LICENSE file in the root directory of this source tree.
66
*
7-
* @generated SignedSource<<2be1f76084eb85288987229421d7585f>>
7+
* @generated SignedSource<<ff39edecf287d3fe3638da2f71e6bd1c>>
88
* @flow strict
99
* @noformat
1010
*/
@@ -33,6 +33,7 @@ export type ReactNativeFeatureFlagsJsOnly = Readonly<{
3333
animatedForceNativeDriver: Getter<boolean>,
3434
animatedShouldSyncValueBeforeStartCallback: Getter<boolean>,
3535
deferFlatListFocusChangeRenderUpdate: Getter<boolean>,
36+
enableDirectEventsInEventTarget: Getter<boolean>,
3637
enableImperativeEvents: Getter<boolean>,
3738
enableNativeEventTargetEventDispatching: Getter<boolean>,
3839
externalElementInspectionEnabled: Getter<boolean>,
@@ -161,6 +162,11 @@ export const animatedShouldSyncValueBeforeStartCallback: Getter<boolean> = creat
161162
*/
162163
export const deferFlatListFocusChangeRenderUpdate: Getter<boolean> = createJavaScriptFlagGetter('deferFlatListFocusChangeRenderUpdate', false);
163164

165+
/**
166+
* When enabled (together with enableNativeEventTargetEventDispatching), direct events (those that neither bubble nor capture, such as onLayout) are dispatched only to the target node via a fast path that skips construction and traversal of the ancestor event path.
167+
*/
168+
export const enableDirectEventsInEventTarget: Getter<boolean> = createJavaScriptFlagGetter('enableDirectEventsInEventTarget', false);
169+
164170
/**
165171
* When enabled, ReactNativeElement and ReadOnlyText expose the public EventTarget API (addEventListener, removeEventListener, dispatchEvent). When disabled, those methods are removed from those final classes.
166172
*/

packages/react-native/src/private/renderer/core/__tests__/EventDispatching-benchmark-itest.js

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
* LICENSE file in the root directory of this source tree.
66
*
77
* @fantom_flags enableNativeEventTargetEventDispatching:*
8+
* @fantom_flags enableDirectEventsInEventTarget:*
89
* @flow strict-local
910
* @format
1011
*/
@@ -39,6 +40,29 @@ function createNestedViews(
3940
);
4041
}
4142

43+
// `onLayout` is a direct (non-bubbling) event, so only the leaf needs a
44+
// handler; ancestors never receive the layout event.
45+
function createNestedViewsWithLayout(
46+
depth: number,
47+
innerRef: {current: React.ElementRef<typeof View> | null},
48+
): React.MixedElement {
49+
if (depth === 0) {
50+
return (
51+
<View
52+
ref={innerRef}
53+
collapsable={false}
54+
onLayout={() => {}}
55+
style={{width: 10, height: 10}}
56+
/>
57+
);
58+
}
59+
return (
60+
<View collapsable={false}>
61+
{createNestedViewsWithLayout(depth - 1, innerRef)}
62+
</View>
63+
);
64+
}
65+
4266
const {isOSS} = Fantom.getConstants();
4367

4468
if (isOSS) {
@@ -322,5 +346,92 @@ if (isOSS) {
322346
root.destroy();
323347
},
324348
},
349+
)
350+
.test(
351+
'dispatch onLayout event, flat (1 handler)',
352+
() => {
353+
Fantom.dispatchNativeEvent(
354+
ref,
355+
'onLayout',
356+
{layout: {x: 0, y: 0, width: 100, height: 50}},
357+
{
358+
category: Fantom.NativeEventCategory.Discrete,
359+
},
360+
);
361+
},
362+
{
363+
beforeAll: () => {
364+
ref = React.createRef();
365+
root = Fantom.createRoot();
366+
Fantom.runTask(() => {
367+
root.render(
368+
<View
369+
ref={ref}
370+
collapsable={false}
371+
onLayout={() => {}}
372+
style={{width: 10, height: 10}}
373+
/>,
374+
);
375+
});
376+
// Flush the layout events emitted during the initial layout pass so
377+
// they are not measured as part of the dispatched event below.
378+
Fantom.flushAllNativeEvents();
379+
},
380+
afterAll: () => {
381+
root.destroy();
382+
},
383+
},
384+
)
385+
.test(
386+
'dispatch onLayout event, nested 10 deep (direct, no bubbling)',
387+
() => {
388+
Fantom.dispatchNativeEvent(
389+
ref,
390+
'onLayout',
391+
{layout: {x: 0, y: 0, width: 100, height: 50}},
392+
{
393+
category: Fantom.NativeEventCategory.Discrete,
394+
},
395+
);
396+
},
397+
{
398+
beforeAll: () => {
399+
ref = React.createRef();
400+
root = Fantom.createRoot();
401+
Fantom.runTask(() => {
402+
root.render(createNestedViewsWithLayout(10, ref));
403+
});
404+
Fantom.flushAllNativeEvents();
405+
},
406+
afterAll: () => {
407+
root.destroy();
408+
},
409+
},
410+
)
411+
.test(
412+
'dispatch onLayout event, nested 50 deep (direct, no bubbling)',
413+
() => {
414+
Fantom.dispatchNativeEvent(
415+
ref,
416+
'onLayout',
417+
{layout: {x: 0, y: 0, width: 100, height: 50}},
418+
{
419+
category: Fantom.NativeEventCategory.Discrete,
420+
},
421+
);
422+
},
423+
{
424+
beforeAll: () => {
425+
ref = React.createRef();
426+
root = Fantom.createRoot();
427+
Fantom.runTask(() => {
428+
root.render(createNestedViewsWithLayout(50, ref));
429+
});
430+
Fantom.flushAllNativeEvents();
431+
},
432+
afterAll: () => {
433+
root.destroy();
434+
},
435+
},
325436
);
326437
}

packages/react-native/src/private/renderer/core/__tests__/EventTargetDispatching-itest.js

Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
*
77
* @fantom_flags enableNativeEventTargetEventDispatching:*
88
* @fantom_flags enableImperativeEvents:*
9+
* @fantom_flags enableDirectEventsInEventTarget:*
910
* @flow strict-local
1011
* @format
1112
*/
@@ -22,6 +23,7 @@ import * as Fantom from '@react-native/fantom';
2223
import * as React from 'react';
2324
import {View} from 'react-native';
2425
import * as ReactNativeFeatureFlags from 'react-native/src/private/featureflags/ReactNativeFeatureFlags';
26+
import Event from 'react-native/src/private/webapis/dom/events/Event';
2527

2628
// Temporary cast until ReadOnlyNode extends EventTarget ungated.
2729
function asEventTarget(node: ?interface {}): ReadOnlyNodeWithEventTarget {
@@ -33,6 +35,28 @@ function asEventTarget(node: ?interface {}): ReadOnlyNodeWithEventTarget {
3335
return node;
3436
}
3537

38+
function createNestedViewsWithLayout(
39+
depth: number,
40+
innerRef: {current: React.ElementRef<typeof View> | null},
41+
onLayout: () => void,
42+
): React.MixedElement {
43+
if (depth === 0) {
44+
return (
45+
<View
46+
ref={innerRef}
47+
collapsable={false}
48+
onLayout={onLayout}
49+
style={{width: 10, height: 10}}
50+
/>
51+
);
52+
}
53+
return (
54+
<View collapsable={false}>
55+
{createNestedViewsWithLayout(depth - 1, innerRef, onLayout)}
56+
</View>
57+
);
58+
}
59+
3660
const {isOSS} = Fantom.getConstants();
3761

3862
(isOSS ? describe.skip : describe)(
@@ -1626,5 +1650,174 @@ const {isOSS} = Fantom.getConstants();
16261650
expect(parentSpy.mock.calls.length - parentCallsBefore).toBe(0);
16271651
});
16281652
});
1653+
1654+
describe('direct events (rnIsDirect) — Event construction validation', () => {
1655+
it('allows constructing a direct event that does not bubble', () => {
1656+
const event = new Event('layout', {rnIsDirect: true});
1657+
expect(event.rnIsDirect).toBe(true);
1658+
expect(event.bubbles).toBe(false);
1659+
});
1660+
1661+
it('defaults rnIsDirect to false', () => {
1662+
const event = new Event('layout');
1663+
expect(event.rnIsDirect).toBe(false);
1664+
});
1665+
1666+
it('throws when rnIsDirect and bubbles are both true', () => {
1667+
expect(() => {
1668+
// eslint-disable-next-line no-new
1669+
new Event('layout', {rnIsDirect: true, bubbles: true});
1670+
}).toThrow(
1671+
"Failed to construct 'Event': 'rnIsDirect' cannot be true when 'bubbles' is also true.",
1672+
);
1673+
});
1674+
});
1675+
1676+
// The dispatch-behavior tests use `addEventListener` on refs and the
1677+
// document element, which is only available when both
1678+
// `enableNativeEventTargetEventDispatching` and `enableImperativeEvents`
1679+
// are enabled.
1680+
(ReactNativeFeatureFlags.enableNativeEventTargetEventDispatching() &&
1681+
ReactNativeFeatureFlags.enableImperativeEvents()
1682+
? describe
1683+
: describe.skip)('direct events (rnIsDirect) — dispatch behavior', () => {
1684+
it('dispatches onLayout to the target but never to ancestor onLayout props or bubble listeners', () => {
1685+
const root = Fantom.createRoot();
1686+
const childRef = React.createRef<React.ElementRef<typeof View>>();
1687+
const childHandler = jest.fn();
1688+
const parentPropHandler = jest.fn();
1689+
const parentImperativeBubble = jest.fn();
1690+
1691+
Fantom.runTask(() => {
1692+
root.render(
1693+
<View onLayout={parentPropHandler}>
1694+
<View>
1695+
<View>
1696+
<View ref={childRef} onLayout={childHandler} />
1697+
</View>
1698+
</View>
1699+
</View>,
1700+
);
1701+
});
1702+
1703+
asEventTarget(root.document.documentElement).addEventListener(
1704+
'layout',
1705+
parentImperativeBubble,
1706+
);
1707+
1708+
// Drain mount-time layout events.
1709+
Fantom.flushAllNativeEvents();
1710+
1711+
const childBefore = childHandler.mock.calls.length;
1712+
const parentBefore = parentPropHandler.mock.calls.length;
1713+
const parentBubbleBefore = parentImperativeBubble.mock.calls.length;
1714+
1715+
Fantom.dispatchNativeEvent(
1716+
childRef,
1717+
'onLayout',
1718+
{layout: {x: 0, y: 0, width: 100, height: 50}},
1719+
{category: Fantom.NativeEventCategory.Discrete},
1720+
);
1721+
1722+
// The target's own onLayout fires exactly once.
1723+
expect(childHandler.mock.calls.length - childBefore).toBe(1);
1724+
// A direct (non-bubbling) event never reaches an ancestor's onLayout
1725+
// prop or an ancestor's bubble-phase listener, regardless of the fast
1726+
// path.
1727+
expect(parentPropHandler.mock.calls.length - parentBefore).toBe(0);
1728+
expect(
1729+
parentImperativeBubble.mock.calls.length - parentBubbleBefore,
1730+
).toBe(0);
1731+
});
1732+
1733+
(ReactNativeFeatureFlags.enableDirectEventsInEventTarget()
1734+
? it
1735+
: it.skip)(
1736+
'restricts the event path to the target (AT_TARGET only, no ancestor capture listeners)',
1737+
() => {
1738+
const root = Fantom.createRoot();
1739+
const childRef = React.createRef<React.ElementRef<typeof View>>();
1740+
const ancestorCapture = jest.fn();
1741+
let observedPhase: number | null = null;
1742+
let observedPathLength: number | null = null;
1743+
let observedCurrentIsTarget: boolean | null = null;
1744+
1745+
const handler = jest.fn((e: $FlowFixMe) => {
1746+
observedPhase = e.eventPhase;
1747+
observedPathLength = e.composedPath().length;
1748+
observedCurrentIsTarget = e.currentTarget === childRef.current;
1749+
});
1750+
1751+
Fantom.runTask(() => {
1752+
root.render(createNestedViewsWithLayout(5, childRef, () => {}));
1753+
});
1754+
1755+
asEventTarget(childRef.current).addEventListener('layout', handler);
1756+
asEventTarget(root.document.documentElement).addEventListener(
1757+
'layout',
1758+
ancestorCapture,
1759+
{capture: true},
1760+
);
1761+
Fantom.flushAllNativeEvents();
1762+
1763+
const ancestorCaptureBefore = ancestorCapture.mock.calls.length;
1764+
1765+
Fantom.dispatchNativeEvent(
1766+
childRef,
1767+
'onLayout',
1768+
{layout: {x: 0, y: 0, width: 100, height: 50}},
1769+
{category: Fantom.NativeEventCategory.Discrete},
1770+
);
1771+
1772+
expect(handler).toHaveBeenCalled();
1773+
expect(observedPhase).toBe(Event.AT_TARGET);
1774+
// Event path is just the target node.
1775+
expect(observedPathLength).toBe(1);
1776+
expect(observedCurrentIsTarget).toBe(true);
1777+
// With the fast path, the capture phase does not traverse ancestors.
1778+
expect(
1779+
ancestorCapture.mock.calls.length - ancestorCaptureBefore,
1780+
).toBe(0);
1781+
},
1782+
);
1783+
1784+
(ReactNativeFeatureFlags.enableDirectEventsInEventTarget()
1785+
? it.skip
1786+
: it)(
1787+
'without the fast path, the capture phase still traverses ancestors for direct events',
1788+
() => {
1789+
const root = Fantom.createRoot();
1790+
const childRef = React.createRef<React.ElementRef<typeof View>>();
1791+
const ancestorCapture = jest.fn();
1792+
1793+
Fantom.runTask(() => {
1794+
root.render(createNestedViewsWithLayout(5, childRef, () => {}));
1795+
});
1796+
1797+
asEventTarget(root.document.documentElement).addEventListener(
1798+
'layout',
1799+
ancestorCapture,
1800+
{capture: true},
1801+
);
1802+
Fantom.flushAllNativeEvents();
1803+
1804+
const ancestorCaptureBefore = ancestorCapture.mock.calls.length;
1805+
1806+
Fantom.dispatchNativeEvent(
1807+
childRef,
1808+
'onLayout',
1809+
{layout: {x: 0, y: 0, width: 100, height: 50}},
1810+
{category: Fantom.NativeEventCategory.Discrete},
1811+
);
1812+
1813+
// The DOM dispatch algorithm runs the capture phase over every
1814+
// ancestor even for non-bubbling events, so the ancestor capture
1815+
// listener fires.
1816+
expect(
1817+
ancestorCapture.mock.calls.length - ancestorCaptureBefore,
1818+
).toBe(1);
1819+
},
1820+
);
1821+
});
16291822
},
16301823
);

0 commit comments

Comments
 (0)