-
Notifications
You must be signed in to change notification settings - Fork 278
Expand file tree
/
Copy pathevent-handler.ts
More file actions
39 lines (31 loc) · 1.1 KB
/
event-handler.ts
File metadata and controls
39 lines (31 loc) · 1.1 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
export type EventHandler = (...args: unknown[]) => unknown;
export type EventHandlerOptions = {
/** Include check for event handler named without adding `on*` prefix. */
loose?: boolean;
};
export function getEventHandlerFromProps(
props: Record<string, unknown>,
eventName: string,
options?: EventHandlerOptions,
): EventHandler | undefined {
const handlerName = getEventHandlerName(eventName);
if (typeof props[handlerName] === 'function') {
return props[handlerName] as EventHandler;
}
if (options?.loose && typeof props[eventName] === 'function') {
return props[eventName] as EventHandler;
}
if (typeof props[`testOnly_${handlerName}`] === 'function') {
return props[`testOnly_${handlerName}`] as EventHandler;
}
if (options?.loose && typeof props[`testOnly_${eventName}`] === 'function') {
return props[`testOnly_${eventName}`] as EventHandler;
}
return undefined;
}
function getEventHandlerName(eventName: string) {
return `on${capitalizeFirstLetter(eventName)}`;
}
function capitalizeFirstLetter(str: string) {
return str.charAt(0).toUpperCase() + str.slice(1);
}