-
Notifications
You must be signed in to change notification settings - Fork 278
Expand file tree
/
Copy pathfire-event.ts
More file actions
253 lines (212 loc) · 7.02 KB
/
fire-event.ts
File metadata and controls
253 lines (212 loc) · 7.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
import type {
PressableProps,
ScrollViewProps,
TextInputProps,
TextProps,
ViewProps,
} from 'react-native';
import type { ReactTestInstance } from 'react-test-renderer';
import act from './act';
import { getEventHandler } from './event-handler';
import { isElementMounted, isHostElement } from './helpers/component-tree';
import { formatElement } from './helpers/format-element';
import { isHostScrollView, isHostTextInput } from './helpers/host-component-names';
import { logger } from './helpers/logger';
import { isPointerEventEnabled } from './helpers/pointer-events';
import { isEditableTextInput } from './helpers/text-input';
import { nativeState } from './native-state';
import type { Point, StringWithAutocomplete } from './types';
type EventHandler = (...args: unknown[]) => unknown;
export function isTouchResponder(element: ReactTestInstance) {
if (!isHostElement(element)) {
return false;
}
return Boolean(element.props.onStartShouldSetResponder) || isHostTextInput(element);
}
/**
* List of events affected by `pointerEvents` prop.
*
* Note: `fireEvent` is accepting both `press` and `onPress` for event names,
* so we need cover both forms.
*/
const eventsAffectedByPointerEventsProp = new Set(['press', 'onPress']);
/**
* List of `TextInput` events not affected by `editable` prop.
*
* Note: `fireEvent` is accepting both `press` and `onPress` for event names,
* so we need cover both forms.
*/
const textInputEventsIgnoringEditableProp = new Set([
'contentSizeChange',
'onContentSizeChange',
'layout',
'onLayout',
'scroll',
'onScroll',
]);
export function isEventEnabled(
element: ReactTestInstance,
eventName: string,
nearestTouchResponder?: ReactTestInstance,
) {
if (nearestTouchResponder != null && isHostTextInput(nearestTouchResponder)) {
return (
isEditableTextInput(nearestTouchResponder) ||
textInputEventsIgnoringEditableProp.has(eventName)
);
}
if (eventsAffectedByPointerEventsProp.has(eventName) && !isPointerEventEnabled(element)) {
return false;
}
const touchStart = nearestTouchResponder?.props.onStartShouldSetResponder?.();
const touchMove = nearestTouchResponder?.props.onMoveShouldSetResponder?.();
if (touchStart || touchMove) {
return true;
}
return touchStart === undefined && touchMove === undefined;
}
type FindEventHandlerState = {
nearestTouchResponder?: ReactTestInstance;
disabledElements: ReactTestInstance[];
targetElement: ReactTestInstance;
};
function findEventHandler(
element: ReactTestInstance,
eventName: string,
state: FindEventHandlerState = {
disabledElements: [],
targetElement: element,
},
): EventHandler | null {
const touchResponder = isTouchResponder(element) ? element : state.nearestTouchResponder;
const handler = getEventHandler(element, eventName, { loose: true });
if (handler) {
const isEnabled = isEventEnabled(element, eventName, touchResponder);
if (isEnabled) {
return handler;
} else {
state.disabledElements.push(element);
}
}
if (element.parent === null) {
logger.warn(formatEnabledEventHandlerNotFound(eventName, state));
return null;
}
return findEventHandler(element.parent, eventName, {
...state,
nearestTouchResponder: touchResponder,
});
}
// String union type of keys of T that start with on, stripped of 'on'
type EventNameExtractor<T> = keyof {
[K in keyof T as K extends `on${infer Rest}` ? Uncapitalize<Rest> : never]: T[K];
};
type EventName = StringWithAutocomplete<
| EventNameExtractor<ViewProps>
| EventNameExtractor<TextProps>
| EventNameExtractor<TextInputProps>
| EventNameExtractor<PressableProps>
| EventNameExtractor<ScrollViewProps>
>;
function fireEvent(element: ReactTestInstance, eventName: EventName, ...data: unknown[]) {
if (!isElementMounted(element)) {
return;
}
setNativeStateIfNeeded(element, eventName, data[0]);
const handler = findEventHandler(element, eventName);
if (!handler) {
return;
}
let returnValue;
void act(() => {
returnValue = handler(...data);
});
return returnValue;
}
fireEvent.press = (element: ReactTestInstance, ...data: unknown[]) =>
fireEvent(element, 'press', ...data);
fireEvent.changeText = (element: ReactTestInstance, ...data: unknown[]) =>
fireEvent(element, 'changeText', ...data);
fireEvent.scroll = (element: ReactTestInstance, ...data: unknown[]) =>
fireEvent(element, 'scroll', ...data);
async function fireEventAsync(
element: ReactTestInstance,
eventName: EventName,
...data: unknown[]
) {
if (!isElementMounted(element)) {
return;
}
setNativeStateIfNeeded(element, eventName, data[0]);
const handler = findEventHandler(element, eventName);
if (!handler) {
return;
}
let returnValue;
// eslint-disable-next-line require-await
await act(async () => {
returnValue = handler(...data);
});
return returnValue;
}
fireEventAsync.press = async (element: ReactTestInstance, ...data: unknown[]) =>
await fireEventAsync(element, 'press', ...data);
fireEventAsync.changeText = async (element: ReactTestInstance, ...data: unknown[]) =>
await fireEventAsync(element, 'changeText', ...data);
fireEventAsync.scroll = async (element: ReactTestInstance, ...data: unknown[]) =>
await fireEventAsync(element, 'scroll', ...data);
export { fireEventAsync };
export default fireEvent;
const scrollEventNames = new Set([
'scroll',
'scrollBeginDrag',
'scrollEndDrag',
'momentumScrollBegin',
'momentumScrollEnd',
]);
function setNativeStateIfNeeded(element: ReactTestInstance, eventName: string, value: unknown) {
if (eventName === 'changeText' && typeof value === 'string' && isEditableTextInput(element)) {
nativeState.valueForElement.set(element, value);
}
if (scrollEventNames.has(eventName) && isHostScrollView(element)) {
const contentOffset = tryGetContentOffset(value);
if (contentOffset) {
nativeState.contentOffsetForElement.set(element, contentOffset);
}
}
}
function tryGetContentOffset(event: unknown): Point | null {
try {
// @ts-expect-error: try to extract contentOffset from the event value
const contentOffset = event?.nativeEvent?.contentOffset;
const x = contentOffset?.x;
const y = contentOffset?.y;
if (typeof x === 'number' || typeof y === 'number') {
return {
x: Number.isFinite(x) ? x : 0,
y: Number.isFinite(y) ? y : 0,
};
}
} catch {
// Do nothing
}
return null;
}
function formatEnabledEventHandlerNotFound(eventName: string, state: FindEventHandlerState) {
if (state.disabledElements.length === 0) {
return `Fire Event: no event handler for "${eventName}" event found on ${formatElement(
state.targetElement,
{
compact: true,
},
)} or any of its ancestors.`;
}
return `Fire Event: no enabled event handler for "${eventName}" event found. Found disabled event handler(s) on:\n${state.disabledElements
.map(
(e) =>
` - ${formatElement(e, { compact: true })}${
typeof e.type === 'string' ? '' : ' (composite element)'
}`,
)
.join('\n')}`;
}