-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Button.tsx
430 lines (368 loc) · 10.7 KB
/
Button.tsx
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
/**
* Copyright IBM Corp. 2016, 2023
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import PropTypes from 'prop-types';
import React, { useRef } from 'react';
import classNames from 'classnames';
import { IconButton, IconButtonKind } from '../IconButton';
import { composeEventHandlers } from '../../tools/events';
import { usePrefix } from '../../internal/usePrefix';
import { useId } from '../../internal/useId';
import { PolymorphicProps } from '../../types/common';
import { PopoverAlignment } from '../Popover';
export const ButtonKinds = [
'primary',
'secondary',
'danger',
'ghost',
'danger--primary',
'danger--ghost',
'danger--tertiary',
'tertiary',
] as const;
export type ButtonKind = (typeof ButtonKinds)[number];
export const ButtonSizes = ['sm', 'md', 'lg', 'xl', '2xl'] as const;
export type ButtonSize = (typeof ButtonSizes)[number];
export const ButtonTooltipAlignments = ['start', 'center', 'end'] as const;
export type ButtonTooltipAlignment = (typeof ButtonTooltipAlignments)[number];
export const ButtonTooltipPositions = ['top', 'right', 'bottom', 'left'];
export type ButtonTooltipPosition = (typeof ButtonTooltipPositions)[number];
interface ButtonBaseProps
extends React.ButtonHTMLAttributes<HTMLButtonElement> {
/**
* Specify the message read by screen readers for the danger button variant
*/
dangerDescription?: string;
/**
* Specify if the button is an icon-only button
*/
hasIconOnly?: boolean;
/**
* Optionally specify an href for your Button to become an `<a>` element
*/
href?: string;
/**
* If specifying the `renderIcon` prop, provide a description for that icon that can
* be read by screen readers
*/
iconDescription?: string;
/**
* Specify whether the Button is expressive, or not. Only applies to the large/default button size.
*/
isExpressive?: boolean;
/**
* Specify whether the Button is currently selected. Only applies to the Ghost variant.
*/
isSelected?: boolean;
/**
* Specify the kind of Button you want to create
*/
kind?: ButtonKind;
/**
* Optional prop to allow overriding the icon rendering.
* Can be a React component class
*/
renderIcon?: React.ElementType;
/**
* Specify the size of the button, from the following list of sizes:
*/
size?: ButtonSize;
/**
* Specify the alignment of the tooltip to the icon-only button.
* Can be one of: start, center, or end.
*/
tooltipAlignment?: ButtonTooltipAlignment;
/**
* Specify the direction of the tooltip for icon-only buttons.
* Can be either top, right, bottom, or left.
*/
tooltipPosition?: ButtonTooltipPosition;
}
export type ButtonProps<T extends React.ElementType> = PolymorphicProps<
T,
ButtonBaseProps
>;
export type ButtonComponent = <T extends React.ElementType>(
props: ButtonProps<T>,
context?: any
) => React.ReactElement<any, any> | null;
function isIconOnlyButton(
hasIconOnly: ButtonBaseProps['hasIconOnly'],
_kind: ButtonBaseProps['kind']
): _kind is IconButtonKind {
if (hasIconOnly === true) {
return true;
}
return false;
}
const Button = React.forwardRef(function Button<T extends React.ElementType>(
{
as,
children,
className,
dangerDescription = 'danger',
disabled = false,
hasIconOnly = false,
href,
iconDescription,
isExpressive = false,
isSelected,
kind = 'primary',
onBlur,
onClick,
onFocus,
onMouseEnter,
onMouseLeave,
renderIcon: ButtonImageElement,
size,
tabIndex,
tooltipAlignment = 'center',
tooltipPosition = 'top',
type = 'button',
...rest
}: ButtonProps<T>,
ref: React.Ref<unknown>
) {
const tooltipRef = useRef(null);
const prefix = usePrefix();
const handleClick = (evt: React.MouseEvent) => {
// Prevent clicks on the tooltip from triggering the button click event
if (evt.target === tooltipRef.current) {
evt.preventDefault();
}
};
const buttonClasses = classNames(className, {
[`${prefix}--btn`]: true,
[`${prefix}--btn--sm`]: size === 'sm' && !isExpressive, // TODO: V12 - Remove this class
[`${prefix}--btn--md`]: size === 'md' && !isExpressive, // TODO: V12 - Remove this class
[`${prefix}--btn--xl`]: size === 'xl', // TODO: V12 - Remove this class
[`${prefix}--btn--2xl`]: size === '2xl', // TODO: V12 - Remove this class
[`${prefix}--layout--size-${size}`]: size,
[`${prefix}--btn--${kind}`]: kind,
[`${prefix}--btn--disabled`]: disabled,
[`${prefix}--btn--expressive`]: isExpressive,
[`${prefix}--btn--icon-only`]: hasIconOnly,
[`${prefix}--btn--selected`]: hasIconOnly && isSelected && kind === 'ghost',
});
const commonProps = {
tabIndex,
className: buttonClasses,
ref,
};
const buttonImage = !ButtonImageElement ? null : (
<ButtonImageElement
aria-label={iconDescription}
className={`${prefix}--btn__icon`}
aria-hidden="true"
/>
);
const iconOnlyImage = !ButtonImageElement ? null : <ButtonImageElement />;
const dangerButtonVariants = ['danger', 'danger--tertiary', 'danger--ghost'];
let component: React.ElementType = 'button';
const assistiveId = useId('danger-description');
const { 'aria-pressed': ariaPressed, 'aria-describedby': ariaDescribedBy } =
rest;
let otherProps: Partial<ButtonBaseProps> = {
disabled,
type,
'aria-describedby': dangerButtonVariants.includes(kind)
? assistiveId
: ariaDescribedBy || undefined,
'aria-pressed':
ariaPressed ?? (hasIconOnly && kind === 'ghost' ? isSelected : undefined),
};
const anchorProps = {
href,
};
let assistiveText: JSX.Element | null = null;
if (dangerButtonVariants.includes(kind)) {
assistiveText = (
<span id={assistiveId} className={`${prefix}--visually-hidden`}>
{dangerDescription}
</span>
);
}
if (as) {
component = as;
otherProps = {
...otherProps,
...anchorProps,
};
} else if (href && !disabled) {
component = 'a';
otherProps = anchorProps;
}
if (!isIconOnlyButton(hasIconOnly, kind)) {
return React.createElement(
component,
{
onMouseEnter,
onMouseLeave,
onFocus,
onBlur,
onClick,
...rest,
...commonProps,
...otherProps,
},
assistiveText,
children,
buttonImage
);
} else {
let align: PopoverAlignment | undefined = undefined;
if (tooltipPosition === 'top' || tooltipPosition === 'bottom') {
if (tooltipAlignment === 'center') {
align = tooltipPosition;
}
if (tooltipAlignment === 'end') {
align = `${tooltipPosition}-right`;
}
if (tooltipAlignment === 'start') {
align = `${tooltipPosition}-left`;
}
}
if (tooltipPosition === 'right' || tooltipPosition === 'left') {
align = tooltipPosition;
}
return (
<IconButton
as={as}
align={align}
label={iconDescription}
kind={kind}
size={size}
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
onFocus={onFocus}
onBlur={onBlur}
onClick={composeEventHandlers([onClick, handleClick])}
{...rest}
{...commonProps}
{...otherProps}>
{iconOnlyImage ?? children}
</IconButton>
);
}
});
Button.displayName = 'Button';
Button.propTypes = {
/**
* Specify how the button itself should be rendered.
* Make sure to apply all props to the root node and render children appropriately
*/
as: PropTypes.oneOfType([
PropTypes.func,
PropTypes.string,
PropTypes.elementType,
]),
/**
* Specify the content of your Button
*/
children: PropTypes.node,
/**
* Specify an optional className to be added to your Button
*/
className: PropTypes.string,
/**
* Specify the message read by screen readers for the danger button variant
*/
dangerDescription: PropTypes.string,
/**
* Specify whether the Button should be disabled, or not
*/
disabled: PropTypes.bool,
/**
* Specify if the button is an icon-only button
*/
hasIconOnly: PropTypes.bool,
/**
* Optionally specify an href for your Button to become an `<a>` element
*/
href: PropTypes.string,
/**
* If specifying the `renderIcon` prop, provide a description for that icon that can
* be read by screen readers
*/
iconDescription: (props) => {
if (props.renderIcon && !props.children && !props.iconDescription) {
return new Error(
'renderIcon property specified without also providing an iconDescription property.'
);
}
return null;
},
/**
* Specify whether the Button is expressive, or not
*/
isExpressive: PropTypes.bool,
/**
* Specify whether the Button is currently selected. Only applies to the Ghost variant.
*/
isSelected: PropTypes.bool,
/**
* Specify the kind of Button you want to create
*/
// TODO: this should be either ButtonKinds or IconButtonKinds based on the value of "hasIconOnly"
kind: PropTypes.oneOf(ButtonKinds),
/**
* Provide an optional function to be called when the button element
* loses focus
*/
onBlur: PropTypes.func,
/**
* Provide an optional function to be called when the button element
* is clicked
*/
onClick: PropTypes.func,
/**
* Provide an optional function to be called when the button element
* receives focus
*/
onFocus: PropTypes.func,
/**
* Provide an optional function to be called when the mouse
* enters the button element
*/
onMouseEnter: PropTypes.func,
/**
* Provide an optional function to be called when the mouse
* leaves the button element
*/
onMouseLeave: PropTypes.func,
/**
* Optional prop to allow overriding the icon rendering.
* Can be a React component class
*/
renderIcon: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
/**
* Optional prop to specify the role of the Button
*/
role: PropTypes.string,
/**
* Specify the size of the button, from the following list of sizes:
*/
size: PropTypes.oneOf(['sm', 'md', 'lg', 'xl', '2xl']),
/**
* Optional prop to specify the tabIndex of the Button
*/
tabIndex: PropTypes.number,
/**
* Specify the alignment of the tooltip to the icon-only button.
* Can be one of: start, center, or end.
*/
tooltipAlignment: PropTypes.oneOf(['start', 'center', 'end']),
/**
* Specify the direction of the tooltip for icon-only buttons.
* Can be either top, right, bottom, or left.
*/
tooltipPosition: PropTypes.oneOf(['top', 'right', 'bottom', 'left']),
/**
* Optional prop to specify the type of the Button
*/
type: PropTypes.oneOf(['button', 'reset', 'submit']),
};
export default Button as ButtonComponent;