-
-
Notifications
You must be signed in to change notification settings - Fork 31.7k
/
useButton.ts
226 lines (189 loc) · 6.43 KB
/
useButton.ts
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
import * as React from 'react';
import {
unstable_useForkRef as useForkRef,
unstable_useIsFocusVisible as useIsFocusVisible,
} from '@mui/utils';
import { UseButtonParameters, UseButtonRootSlotProps } from './useButton.types';
import extractEventHandlers from '../utils/extractEventHandlers';
import { EventHandlers } from '../utils/types';
export default function useButton(parameters: UseButtonParameters) {
const {
disabled = false,
focusableWhenDisabled,
href,
ref: externalRef,
tabIndex,
to,
type,
} = parameters;
const buttonRef = React.useRef<HTMLButtonElement | HTMLAnchorElement | HTMLElement>();
const [active, setActive] = React.useState<boolean>(false);
const {
isFocusVisibleRef,
onFocus: handleFocusVisible,
onBlur: handleBlurVisible,
ref: focusVisibleRef,
} = useIsFocusVisible();
const [focusVisible, setFocusVisible] = React.useState(false);
if (disabled && !focusableWhenDisabled && focusVisible) {
setFocusVisible(false);
}
React.useEffect(() => {
isFocusVisibleRef.current = focusVisible;
}, [focusVisible, isFocusVisibleRef]);
const [hostElementName, setHostElementName] = React.useState<string>('');
const createHandleMouseLeave = (otherHandlers: EventHandlers) => (event: React.MouseEvent) => {
if (focusVisible) {
event.preventDefault();
}
otherHandlers.onMouseLeave?.(event);
};
const createHandleBlur = (otherHandlers: EventHandlers) => (event: React.FocusEvent) => {
handleBlurVisible(event);
if (isFocusVisibleRef.current === false) {
setFocusVisible(false);
}
otherHandlers.onBlur?.(event);
};
const createHandleFocus =
(otherHandlers: EventHandlers) => (event: React.FocusEvent<HTMLButtonElement>) => {
// Fix for https://github.com/facebook/react/issues/7769
if (!buttonRef.current) {
buttonRef.current = event.currentTarget;
}
handleFocusVisible(event);
if (isFocusVisibleRef.current === true) {
setFocusVisible(true);
otherHandlers.onFocusVisible?.(event);
}
otherHandlers.onFocus?.(event);
};
const isNativeButton = () => {
const button = buttonRef.current;
return (
hostElementName === 'BUTTON' ||
(hostElementName === 'INPUT' &&
['button', 'submit', 'reset'].includes((button as HTMLInputElement)?.type)) ||
(hostElementName === 'A' && (button as HTMLAnchorElement)?.href)
);
};
const createHandleClick = (otherHandlers: EventHandlers) => (event: React.MouseEvent) => {
if (!disabled) {
otherHandlers.onClick?.(event);
}
};
const createHandleMouseDown = (otherHandlers: EventHandlers) => (event: React.MouseEvent) => {
if (!disabled) {
setActive(true);
document.addEventListener(
'mouseup',
() => {
setActive(false);
},
{ once: true },
);
}
otherHandlers.onMouseDown?.(event);
};
const createHandleKeyDown = (otherHandlers: EventHandlers) => (event: React.KeyboardEvent) => {
otherHandlers.onKeyDown?.(event);
if (event.defaultPrevented) {
return;
}
if (event.target === event.currentTarget && !isNativeButton() && event.key === ' ') {
event.preventDefault();
}
if (event.target === event.currentTarget && event.key === ' ' && !disabled) {
setActive(true);
}
// Keyboard accessibility for non interactive elements
if (
event.target === event.currentTarget &&
!isNativeButton() &&
event.key === 'Enter' &&
!disabled
) {
otherHandlers.onClick?.(event);
event.preventDefault();
}
};
const createHandleKeyUp = (otherHandlers: EventHandlers) => (event: React.KeyboardEvent) => {
// calling preventDefault in keyUp on a <button> will not dispatch a click event if Space is pressed
// https://codesandbox.io/s/button-keyup-preventdefault-dn7f0
if (event.target === event.currentTarget) {
setActive(false);
}
otherHandlers.onKeyUp?.(event);
// Keyboard accessibility for non interactive elements
if (
event.target === event.currentTarget &&
!isNativeButton() &&
!disabled &&
event.key === ' ' &&
!event.defaultPrevented
) {
otherHandlers.onClick?.(event);
}
};
const updateHostElementName = React.useCallback((instance: HTMLElement | null) => {
setHostElementName(instance?.tagName ?? '');
}, []);
const handleRef = useForkRef(updateHostElementName, externalRef, focusVisibleRef, buttonRef);
interface AdditionalButtonProps {
type?: React.ButtonHTMLAttributes<HTMLButtonElement>['type'];
disabled?: boolean;
role?: React.AriaRole;
'aria-disabled'?: React.AriaAttributes['aria-disabled'];
tabIndex?: number;
}
const buttonProps: AdditionalButtonProps = {};
if (hostElementName === 'BUTTON') {
buttonProps.type = type ?? 'button';
if (focusableWhenDisabled) {
buttonProps['aria-disabled'] = disabled;
} else {
buttonProps.disabled = disabled;
}
} else if (hostElementName !== '') {
if (!href && !to) {
buttonProps.role = 'button';
buttonProps.tabIndex = tabIndex ?? 0;
}
if (disabled) {
buttonProps['aria-disabled'] = disabled as boolean;
buttonProps.tabIndex = focusableWhenDisabled ? tabIndex ?? 0 : -1;
}
}
const getRootProps = <TOther extends EventHandlers = {}>(
otherHandlers: TOther = {} as TOther,
): UseButtonRootSlotProps<TOther> => {
const propsEventHandlers = extractEventHandlers(parameters) as Partial<UseButtonParameters>;
const externalEventHandlers = {
...propsEventHandlers,
...otherHandlers,
};
// onFocusVisible can be present on the props, but since it's not a valid React event handler,
// it must not be forwarded to the inner component.
delete externalEventHandlers.onFocusVisible;
return {
type,
...externalEventHandlers,
...buttonProps,
onBlur: createHandleBlur(externalEventHandlers),
onClick: createHandleClick(externalEventHandlers),
onFocus: createHandleFocus(externalEventHandlers),
onKeyDown: createHandleKeyDown(externalEventHandlers),
onKeyUp: createHandleKeyUp(externalEventHandlers),
onMouseDown: createHandleMouseDown(externalEventHandlers),
onMouseLeave: createHandleMouseLeave(externalEventHandlers),
ref: handleRef,
};
};
return {
getRootProps,
focusVisible,
setFocusVisible,
disabled,
active,
};
}