-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathToggleButton.tsx
128 lines (108 loc) · 2.62 KB
/
ToggleButton.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
import './ToggleButton.less';
import React, {
MouseEvent
} from 'react';
import {
Button,
Tooltip
} from 'antd';
import {
AbstractTooltipProps,
TooltipPlacement
} from 'antd/lib/tooltip';
import { CSS_PREFIX } from '../../constants';
import { SimpleButtonProps } from '../SimpleButton/SimpleButton';
interface OwnProps {
/**
* Additional [antd tooltip](https://ant.design/components/tooltip/)
* properties to pass to the tooltip component. Note: The props `title`
* and `placement` will override the props `tooltip` and `tooltipPlacement`
* of this component!
*/
tooltipProps?: AbstractTooltipProps;
/**
* The initial pressed state of the ToggleButton
* Note: If a ToggleButton is inside a ToggleGroup, the pressed state will be controlled by the selectedName property
* of the ToggleGroup and this property will be ignored.
*/
pressed?: boolean;
/**
* The value associated with this button.
*/
value?: string;
/**
* The icon to render for the pressed state.
*/
pressedIcon?: React.ReactNode;
/**
* The tooltip to be shown on hover.
*/
tooltip?: string;
/**
* The position of the tooltip.
*/
tooltipPlacement?: TooltipPlacement;
/**
* The onChange callback.
*/
onChange?: (evt: MouseEvent<HTMLButtonElement>, value?: string) => void;
}
export type ToggleButtonProps = OwnProps & Omit<SimpleButtonProps, 'onChange' | 'value'>;
export const ToggleButton: React.FC<ToggleButtonProps> = ({
type = 'primary',
pressed = false,
tooltipProps = {
mouseEnterDelay: 1.5
},
className,
tooltip,
tooltipPlacement,
pressedIcon,
icon,
children,
value,
onClick,
onChange = () => undefined,
...passThroughProps
}) => {
const handleChange = (evt: React.MouseEvent<HTMLButtonElement>) => {
if (onClick) {
onClick(evt);
if (evt.defaultPrevented) {
return;
}
}
onChange(evt, value);
};
const internalClassName = `${CSS_PREFIX}togglebutton`;
const finalClassName = className
? `${className} ${internalClassName}`
: internalClassName;
let pressedClass = '';
if (pressed) {
pressedClass = ' btn-pressed';
}
return (
<Tooltip
title={tooltip}
placement={tooltipPlacement}
{...tooltipProps}
>
<Button
type={type}
onClick={handleChange}
onChange={onChange}
className={`${finalClassName}${pressedClass}`}
aria-pressed={pressed}
icon={pressed ?
pressedIcon :
icon
}
{...passThroughProps}
>
{children}
</Button>
</Tooltip>
);
};
export default ToggleButton;