Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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<React.ElementRef<typeof View>>();
const order: Array<string> = [];

Fantom.runTask(() => {
root.render(
<View
onPointerUpCapture={() => {
order.push('parent capture prop');
}}
onPointerUp={() => {
order.push('parent bubble prop');
}}>
<View
ref={ref}
onPointerUp={() => {
order.push('target bubble prop');
}}
/>
</View>,
);
});

// 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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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) {
Expand All @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -71,7 +72,7 @@ export default class Event {
_defaultPrevented: boolean = false;
_timeStamp: number;

[COMPOSED_PATH_KEY]: ReadonlyArray<EventTarget> = [];
[COMPOSED_PATH_KEY]: ReadonlyArray<EventTarget> = EMPTY_COMPOSED_PATH;
[CURRENT_TARGET_KEY]: EventTarget | null = null;
[EVENT_PHASE_KEY]: EventPhase = Event.NONE;
[IN_PASSIVE_LISTENER_FLAG_KEY]: boolean = false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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)) {
Expand All @@ -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) {
Expand All @@ -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);
Expand Down Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<EventTarget> = 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.
Expand All @@ -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');

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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;
Comment thread
chrfalch marked this conversation as resolved.
Resolved
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;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading