diff --git a/packages/react-native/src/private/renderer/core/__tests__/EventTargetDispatching-itest.js b/packages/react-native/src/private/renderer/core/__tests__/EventTargetDispatching-itest.js index fb9300cfc3fd..8cbccf54a072 100644 --- a/packages/react-native/src/private/renderer/core/__tests__/EventTargetDispatching-itest.js +++ b/packages/react-native/src/private/renderer/core/__tests__/EventTargetDispatching-itest.js @@ -1324,6 +1324,46 @@ describe('EventTarget-based Event Dispatching', () => { expect(order).toEqual(['parent-capture']); }); + (ReactNativeFeatureFlags.enableImperativeEvents() === true + ? describe + : describe.skip)('events dispatched from JavaScript', () => { + it('invokes handler props along the path', () => { + const root = Fantom.createRoot(); + const ref = React.createRef>(); + const order: Array = []; + + Fantom.runTask(() => { + root.render( + { + order.push('parent capture prop'); + }} + onPointerUp={() => { + order.push('parent bubble prop'); + }}> + { + order.push('target bubble prop'); + }} + /> + , + ); + }); + + // Temporary: ReadOnlyNode extends EventTarget at runtime behind feature flag + asEventTarget(ref.current).dispatchEvent( + new Event('pointerup', {bubbles: true}), + ); + + expect(order).toEqual([ + 'parent capture prop', + 'target bubble prop', + 'parent bubble prop', + ]); + }); + }); + describe('error handling', () => { it('error in event handler does not break dispatch to subsequent listeners', () => { const root = Fantom.createRoot(); diff --git a/packages/react-native/src/private/renderer/events/dispatchNativeEvent.js b/packages/react-native/src/private/renderer/events/dispatchNativeEvent.js index 77ec770750a0..228fa0b700fb 100644 --- a/packages/react-native/src/private/renderer/events/dispatchNativeEvent.js +++ b/packages/react-native/src/private/renderer/events/dispatchNativeEvent.js @@ -15,9 +15,9 @@ import { customDirectEventTypes, } from '../../../../Libraries/Renderer/shims/ReactNativeViewConfigRegistry'; import { + EVENT_INIT_TIMESTAMP_KEY, setBubbledPropName, setCapturedPropName, - setEventInitTimeStamp, } from '../../webapis/dom/events/internals/EventInternals'; import {dispatchTrustedEvent} from '../../webapis/dom/events/internals/EventTargetInternals'; import LegacySyntheticEvent from './LegacySyntheticEvent'; @@ -55,7 +55,8 @@ export default function dispatchNativeEvent( // Normal EventTarget dispatch const bubbleConfig = customBubblingEventTypes[type]; - const directConfig = customDirectEventTypes[type]; + const directConfig = + bubbleConfig == null ? customDirectEventTypes[type] : null; // Skip events that are not registered in the view config if (bubbleConfig != null || directConfig != null) { @@ -76,33 +77,25 @@ export default function dispatchNativeEvent( const isDirect = bubbleConfig == null && directConfig != null; const eventType = topLevelTypeToEventType(type); - const options: { - bubbles: boolean, - cancelable: boolean, - rnIsDirect?: boolean, - } = { - bubbles, - cancelable: true, - rnIsDirect: isDirect, - }; - // Preserve the native event timestamp for backwards compatibility. const nativeTimestamp = payload.timeStamp ?? payload.timestamp; - if (typeof nativeTimestamp === 'number') { - setEventInitTimeStamp(options, nativeTimestamp); - } const syntheticEvent = new LegacySyntheticEvent( eventType, - options, + { + bubbles, + cancelable: true, + rnIsDirect: isDirect, + [EVENT_INIT_TIMESTAMP_KEY]: + typeof nativeTimestamp === 'number' ? nativeTimestamp : undefined, + }, payload, bubbleConfig ?? directConfig, ); - // Pre-resolve the React prop names ("onFoo" / "onFooCapture") once per - // dispatch and stash them on the event so per-ancestor - // `EVENT_TARGET_GET_DECLARATIVE_LISTENER_KEY` lookups can read them - // directly, avoiding the per-call `getEventTypePropName` hash lookup. + // Store the React prop names ("onFoo" / "onFooCapture") on the event. + // `EventTarget` dispatch reads them once and passes them to each target, + // avoiding a `getEventTypePropName` hash lookup per target per phase. if (bubbleConfig != null) { const phasedRegistrationNames = bubbleConfig.phasedRegistrationNames; setBubbledPropName( diff --git a/packages/react-native/src/private/webapis/dom/events/Event.js b/packages/react-native/src/private/webapis/dom/events/Event.js index 7cd4f12b6d5f..12c15f823fe2 100644 --- a/packages/react-native/src/private/webapis/dom/events/Event.js +++ b/packages/react-native/src/private/webapis/dom/events/Event.js @@ -22,6 +22,7 @@ import { CAPTURED_PROP_NAME_KEY, COMPOSED_PATH_KEY, CURRENT_TARGET_KEY, + EMPTY_COMPOSED_PATH, EVENT_INIT_TIMESTAMP_KEY, EVENT_PHASE_KEY, IN_PASSIVE_LISTENER_FLAG_KEY, @@ -71,7 +72,7 @@ export default class Event { _defaultPrevented: boolean = false; _timeStamp: number; - [COMPOSED_PATH_KEY]: ReadonlyArray = []; + [COMPOSED_PATH_KEY]: ReadonlyArray = EMPTY_COMPOSED_PATH; [CURRENT_TARGET_KEY]: EventTarget | null = null; [EVENT_PHASE_KEY]: EventPhase = Event.NONE; [IN_PASSIVE_LISTENER_FLAG_KEY]: boolean = false; diff --git a/packages/react-native/src/private/webapis/dom/events/EventTarget.js b/packages/react-native/src/private/webapis/dom/events/EventTarget.js index 73920f62d022..6d66d7bc89ef 100644 --- a/packages/react-native/src/private/webapis/dom/events/EventTarget.js +++ b/packages/react-native/src/private/webapis/dom/events/EventTarget.js @@ -19,6 +19,9 @@ import type {EventPhase} from './Event'; import {setPlatformObject} from '../../webidl/PlatformObjects'; import Event from './Event'; import { + EMPTY_COMPOSED_PATH, + getBubbledPropName, + getCapturedPropName, getStopImmediatePropagationFlag, getStopPropagationFlag, setComposedPath, @@ -225,11 +228,15 @@ export default class EventTarget { * `event.type` is the event type. `isCapture` distinguishes the capture pass * from the bubble pass — it cannot be derived from `event.eventPhase`, * which is `AT_TARGET` during both passes through the target node. + * `propName` is the name of the prop that holds the listener for this pass, + * read from the event once per dispatch: `null` if the event type has no + * prop for this pass, or `undefined` if the event does not name one. */ // $FlowFixMe[illegal-key] [EVENT_TARGET_GET_DECLARATIVE_LISTENER_KEY]( event: Event, isCapture: boolean, + propName: string | null | void, ): EventCallback | null { return null; } @@ -310,6 +317,8 @@ function dispatch( const errorState: ListenerErrorState | null = rethrowErrors ? {hasError: false, error: undefined} : null; + const capturedPropName = getCapturedPropName(event); + const bubbledPropName = getBubbledPropName(event); for (let i = eventPath.length - 1; i >= 0; i--) { if (getStopPropagationFlag(event)) { @@ -321,7 +330,7 @@ function dispatch( event, target === eventTarget ? Event.AT_TARGET : Event.CAPTURING_PHASE, ); - invoke(target, event, Event.CAPTURING_PHASE, errorState); + invoke(target, event, Event.CAPTURING_PHASE, capturedPropName, errorState); } for (const target of eventPath) { @@ -339,12 +348,12 @@ function dispatch( event, target === eventTarget ? Event.AT_TARGET : Event.BUBBLING_PHASE, ); - invoke(target, event, Event.BUBBLING_PHASE, errorState); + invoke(target, event, Event.BUBBLING_PHASE, bubbledPropName, errorState); } setEventPhase(event, Event.NONE); setCurrentTarget(event, null); - setComposedPath(event, []); + setComposedPath(event, EMPTY_COMPOSED_PATH); setEventDispatchFlag(event, false); setStopImmediatePropagationFlag(event, false); @@ -395,20 +404,20 @@ function invoke( eventTarget: EventTarget, event: Event, eventPhase: EventPhase, + propName: string | null | void, errorState: ListenerErrorState | null, ) { const isCapture = eventPhase === Event.CAPTURING_PHASE; setCurrentTarget(event, eventTarget); - // Resolve the prop-based listener. Pass the event so subclasses can read - // its `type` and any pre-resolved internal slots; pass `isCapture` - // separately because it can't be derived from `event.eventPhase` (which - // is `AT_TARGET` during both passes through the target node). + // Resolve the prop-based listener. Pass `isCapture` separately because it + // can't be derived from `event.eventPhase` (which is `AT_TARGET` during both + // passes through the target node). // $FlowExpectedError[prop-missing] const propListener: EventCallback | null = eventTarget[ EVENT_TARGET_GET_DECLARATIVE_LISTENER_KEY - ](event, isCapture); + ](event, isCapture, propName); const listenersByType = getListenersForPhase(eventTarget, isCapture); const maybeListeners = listenersByType?.get(event.type); diff --git a/packages/react-native/src/private/webapis/dom/events/internals/EventInternals.js b/packages/react-native/src/private/webapis/dom/events/internals/EventInternals.js index f902996844a0..8310d08b72e6 100644 --- a/packages/react-native/src/private/webapis/dom/events/internals/EventInternals.js +++ b/packages/react-native/src/private/webapis/dom/events/internals/EventInternals.js @@ -28,6 +28,10 @@ export const STOP_IMMEDIATE_PROPAGATION_FLAG_KEY = Symbol( export const STOP_PROPAGATION_FLAG_KEY = Symbol('stopPropagationFlag'); export const TARGET_KEY = Symbol('target'); +export const EMPTY_COMPOSED_PATH: ReadonlyArray = Object.freeze( + [], +); + // For internal construction of events using a custom timestamp (instead of // event object creation), for use cases like dispatching events from the host // platform using the original timestamps. @@ -37,11 +41,12 @@ export interface EventInitWithTimestamp extends EventInit { [EVENT_INIT_TIMESTAMP_KEY]?: number; } -// Internal slots used by the React Native renderer to pass pre-resolved -// React prop names ("onPointerUp" / "onPointerUpCapture") through the event -// to subclasses of `EventTarget` (i.e. `ReactNativeElement`). This avoids -// recomputing `getEventTypePropName(event.type, isCapture)` per ancestor per -// phase during dispatch, which is hot. +// Internal slots used by the React Native renderer to store the React prop +// names ("onPointerUp" / "onPointerUpCapture") on the event. `EventTarget` +// dispatch reads them once and passes them to the declarative listener lookup +// of each target (i.e. `ReactNativeElement`). This avoids recomputing +// `getEventTypePropName(event.type, isCapture)` per target per phase during +// dispatch, which is hot. export const BUBBLED_PROP_NAME_KEY = Symbol('bubbledPropName'); export const CAPTURED_PROP_NAME_KEY = Symbol('capturedPropName'); diff --git a/packages/react-native/src/private/webapis/dom/nodes/ReactNativeElement.js b/packages/react-native/src/private/webapis/dom/nodes/ReactNativeElement.js index 613b8980d2a1..9c4a00afe475 100644 --- a/packages/react-native/src/private/webapis/dom/nodes/ReactNativeElement.js +++ b/packages/react-native/src/private/webapis/dom/nodes/ReactNativeElement.js @@ -28,13 +28,8 @@ import {create as createAttributePayload} from '../../../../../Libraries/ReactNa import warnForStyleProps from '../../../../../Libraries/ReactNative/ReactFabricPublicInstance/warnForStyleProps'; import * as ReactNativeFeatureFlags from '../../../featureflags/ReactNativeFeatureFlags'; import {getEventTypePropName} from '../../../renderer/events/ReactNativeEventTypeMapping'; -import { - getBubbledPropName, - getCapturedPropName, -} from '../events/internals/EventInternals'; import {EVENT_TARGET_GET_DECLARATIVE_LISTENER_KEY} from '../events/internals/EventTargetInternals'; import { - getCurrentProps, getNativeElementReference, getPublicInstanceFromInstanceHandle, setInstanceHandle, @@ -283,32 +278,35 @@ class ReactNativeElement extends ReadOnlyElement { // listeners, allowing prop-based handlers to be resolved at dispatch time // without registering them via addEventListener during commit. // - // Fast path: when `event` is a `LegacySyntheticEvent` (always the case for - // events created by `dispatchNativeEvent`), the React prop names have been - // pre-resolved on the event during construction. Reading them directly - // avoids the `getEventTypePropName(eventType, isCapture)` hash lookup per - // ancestor per phase. + // `propName` is the prop name for this phase that the dispatcher read from + // the event once for the whole dispatch. Events created by + // `dispatchNativeEvent` carry it. For other events, such as ones dispatched + // from JavaScript, it is `undefined` and the name comes from the mapping + // table. // $FlowFixMe[illegal-key] [EVENT_TARGET_GET_DECLARATIVE_LISTENER_KEY]( event: Event, isCapture: boolean, + propName: string | null | void, ): ((event: Event) => void) | null { - const currentProps = getCurrentProps(this); + // Read the props inline instead of calling `getCurrentProps`, which reads + // the same React internals. This runs for every target in both phases of a + // dispatch, and in a Fantom benchmark of pointer events through 20 levels + // the call adds about 10% to the instructions per event. + const currentProps = + // $FlowExpectedError[incompatible-use] instanceHandle is opaque + this.__internalInstanceHandle?.stateNode?.canonical?.currentProps; if (currentProps == null) { return null; } - let propName = isCapture - ? getCapturedPropName(event) - : getBubbledPropName(event); - if (propName === undefined) { - // The event wasn't created via `dispatchNativeEvent` (e.g., - // user-dispatched). Fall back to the mapping table. - propName = getEventTypePropName(event.type, isCapture); - } - if (propName == null) { + const resolvedPropName = + propName !== undefined + ? propName + : getEventTypePropName(event.type, isCapture); + if (resolvedPropName == null) { return null; } - const handler = currentProps[propName]; + const handler = currentProps[resolvedPropName]; return typeof handler === 'function' ? handler : null; } } diff --git a/packages/react-native/src/private/webapis/dom/nodes/internals/NodeInternals.js b/packages/react-native/src/private/webapis/dom/nodes/internals/NodeInternals.js index a987949873cf..d154318b353c 100644 --- a/packages/react-native/src/private/webapis/dom/nodes/internals/NodeInternals.js +++ b/packages/react-native/src/private/webapis/dom/nodes/internals/NodeInternals.js @@ -160,6 +160,8 @@ export function getNativeElementReference( /** * Returns the current props for a node managed by React. * This accesses React internals (fiber.stateNode.canonical.currentProps). + * `ReactNativeElement` reads the same path inline when it looks up handler + * props during event dispatch. */ export function getCurrentProps(node: ReadOnlyNode): {[key: string]: unknown} { const instanceHandle = getInstanceHandle(node);