-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathCheckbox.js
322 lines (265 loc) · 8.46 KB
/
Checkbox.js
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
import cx from 'clsx'
import _ from 'lodash'
import PropTypes from 'prop-types'
import * as React from 'react'
import {
createHTMLLabel,
customPropTypes,
getComponentType,
getUnhandledProps,
htmlInputAttrs,
makeDebugger,
partitionHTMLProps,
getKeyOnly,
useAutoControlledValue,
useMergedRefs,
useIsomorphicLayoutEffect,
} from '../../lib'
const debug = makeDebugger('checkbox')
/**
* A checkbox allows a user to select a value from a small set of options, often binary.
* @see Form
* @see Radio
*/
const Checkbox = React.forwardRef(function (props, ref) {
const {
className,
disabled,
label,
id,
name,
radio,
readOnly,
slider,
tabIndex,
toggle,
type = 'checkbox',
value,
} = props
const [checked, setChecked] = useAutoControlledValue({
state: props.checked,
defaultState: props.defaultChecked,
initialState: false,
})
const [indeterminate, setIndeterminate] = useAutoControlledValue({
state: props.indeterminate,
defaultState: props.defaultIndeterminate,
initialState: false,
})
const inputRef = useMergedRefs(React.useRef(), ref)
const labelRef = React.useRef()
const isClickFromMouse = React.useRef()
// ----------------------------------------
// Effects
// ----------------------------------------
useIsomorphicLayoutEffect(() => {
// Note: You can't directly set the indeterminate prop on the input, so we
// need to maintain a ref to the input and set it manually whenever the
// component updates.
if (inputRef.current) {
inputRef.current.indeterminate = !!indeterminate
}
})
// ----------------------------------------
// Helpers
// ----------------------------------------
const canToggle = () => {
return !disabled && !readOnly && !(radio && checked)
}
const computeTabIndex = () => {
if (!_.isNil(tabIndex)) {
return tabIndex
}
return disabled ? -1 : 0
}
// ----------------------------------------
// Handlers
// ----------------------------------------
const handleChange = (e) => {
if (!canToggle()) {
return
}
debug('handleChange()', _.get(e, 'target.tagName'))
_.invoke(props, 'onChange', e, {
...props,
checked: !checked,
indeterminate: false,
})
setChecked(!checked)
setIndeterminate(false)
}
const handleClick = (e) => {
debug('handleClick()', _.get(e, 'target.tagName'))
const isInputClick = _.invoke(inputRef.current, 'contains', e.target)
const isLabelClick = _.invoke(labelRef.current, 'contains', e.target)
const isRootClick = !isLabelClick && !isInputClick
const hasId = !_.isNil(id)
const isLabelClickAndForwardedToInput = isLabelClick && hasId
// https://github.com/Semantic-Org/Semantic-UI-React/pull/3351
if (!isLabelClickAndForwardedToInput) {
_.invoke(props, 'onClick', e, {
...props,
checked: !checked,
indeterminate: !!indeterminate,
})
}
if (isClickFromMouse.current) {
isClickFromMouse.current = false
if (isLabelClick && !hasId) {
handleChange(e)
}
// Changes should be triggered for the slider variation
if (isRootClick) {
handleChange(e)
}
if (isLabelClick && hasId) {
// To prevent two clicks from being fired from the component we have to stop the propagation
// from the "input" click: https://github.com/Semantic-Org/Semantic-UI-React/issues/3433
e.stopPropagation()
}
}
}
const handleMouseDown = (e) => {
debug('handleMouseDown()')
_.invoke(props, 'onMouseDown', e, {
...props,
checked: !!checked,
indeterminate: !!indeterminate,
})
if (!e.defaultPrevented) {
_.invoke(inputRef.current, 'focus')
}
// Heads up!
// We need to call "preventDefault" to keep element focused.
e.preventDefault()
}
const handleMouseUp = (e) => {
debug('handleMouseUp()')
isClickFromMouse.current = true
_.invoke(props, 'onMouseUp', e, {
...props,
checked: !!checked,
indeterminate: !!indeterminate,
})
}
// ----------------------------------------
// Render
// ----------------------------------------
const classes = cx(
'ui',
getKeyOnly(checked, 'checked'),
getKeyOnly(disabled, 'disabled'),
getKeyOnly(indeterminate, 'indeterminate'),
// auto apply fitted class to compact white space when there is no label
// https://semantic-ui.com/modules/checkbox.html#fitted
getKeyOnly(_.isNil(label), 'fitted'),
getKeyOnly(radio, 'radio'),
getKeyOnly(readOnly, 'read-only'),
getKeyOnly(slider, 'slider'),
getKeyOnly(toggle, 'toggle'),
'checkbox',
className,
)
const unhandled = getUnhandledProps(Checkbox, props)
const ElementType = getComponentType(props)
const [htmlInputProps, rest] = partitionHTMLProps(unhandled, { htmlProps: htmlInputAttrs })
// Heads Up!
// Do not remove empty labels, they are required by SUI CSS
const labelElement = createHTMLLabel(label, {
defaultProps: { htmlFor: id },
autoGenerateKey: false,
}) || <label htmlFor={id} />
return (
<ElementType
{...rest}
className={classes}
onClick={handleClick}
onChange={handleChange}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
>
<input
{...htmlInputProps}
checked={checked}
className='hidden'
disabled={disabled}
id={id}
name={name}
readOnly
ref={inputRef}
tabIndex={computeTabIndex()}
type={type}
value={value}
/>
{React.cloneElement(labelElement, { ref: labelRef })}
</ElementType>
)
})
Checkbox.displayName = 'Checkbox'
Checkbox.propTypes = {
/** An element type to render as (string or function). */
as: PropTypes.elementType,
/** Whether or not checkbox is checked. */
checked: PropTypes.bool,
/** Additional classes. */
className: PropTypes.string,
/** The initial value of checked. */
defaultChecked: PropTypes.bool,
/** Whether or not checkbox is indeterminate. */
defaultIndeterminate: PropTypes.bool,
/** A checkbox can appear disabled and be unable to change states */
disabled: PropTypes.bool,
/** Removes padding for a label. Auto applied when there is no label. */
fitted: PropTypes.bool,
/** A unique identifier. */
id: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/** Whether or not checkbox is indeterminate. */
indeterminate: PropTypes.bool,
/** The text of the associated label element. */
label: customPropTypes.itemShorthand,
/** The HTML input name. */
name: PropTypes.string,
/**
* Called when the user attempts to change the checked state.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props and proposed checked/indeterminate state.
*/
onChange: PropTypes.func,
/**
* Called when the checkbox or label is clicked.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props and current checked/indeterminate state.
*/
onClick: PropTypes.func,
/**
* Called when the user presses down on the mouse.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props and current checked/indeterminate state.
*/
onMouseDown: PropTypes.func,
/**
* Called when the user releases the mouse.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props and current checked/indeterminate state.
*/
onMouseUp: PropTypes.func,
/** Format as a radio element. This means it is an exclusive option. */
radio: customPropTypes.every([PropTypes.bool, customPropTypes.disallow(['slider', 'toggle'])]),
/** A checkbox can be read-only and unable to change states. */
readOnly: PropTypes.bool,
/** Format to emphasize the current selection state. */
slider: customPropTypes.every([PropTypes.bool, customPropTypes.disallow(['radio', 'toggle'])]),
/** A checkbox can receive focus. */
tabIndex: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/** Format to show an on or off choice. */
toggle: customPropTypes.every([PropTypes.bool, customPropTypes.disallow(['radio', 'slider'])]),
/** HTML input type, either checkbox or radio. */
type: PropTypes.oneOf(['checkbox', 'radio']),
/** The HTML input value. */
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
}
export default Checkbox