/
Checkbox.tsx
430 lines (411 loc) · 13.1 KB
/
Checkbox.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
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { OverridableComponent } from '@mui/types';
import { unstable_useId as useId, unstable_capitalize as capitalize } from '@mui/utils';
import { unstable_composeClasses as composeClasses } from '@mui/base';
import { useSwitch } from '@mui/base/SwitchUnstyled';
import { styled, useThemeProps } from '../styles';
import checkboxClasses, { getCheckboxUtilityClass } from './checkboxClasses';
import { CheckboxProps, CheckboxTypeMap } from './CheckboxProps';
import CheckIcon from '../internal/svg-icons/Check';
import IndeterminateIcon from '../internal/svg-icons/HorizontalRule';
import { TypographyContext } from '../Typography/Typography';
const useUtilityClasses = (ownerState: CheckboxProps & { focusVisible: boolean }) => {
const { checked, disabled, disableIcon, focusVisible, color, variant, size } = ownerState;
const slots = {
root: [
'root',
checked && 'checked',
disabled && 'disabled',
focusVisible && 'focusVisible',
variant && `variant${capitalize(variant)}`,
color && `color${capitalize(color)}`,
size && `size${capitalize(size)}`,
],
checkbox: ['checkbox', disabled && 'disabled'], // disabled class is necessary for displaying global variant
action: ['action', disableIcon && disabled && 'disabled', focusVisible && 'focusVisible'], // add disabled class to action element for displaying global variant
input: ['input'],
label: ['label'],
};
return composeClasses(slots, getCheckboxUtilityClass, {});
};
const CheckboxRoot = styled('span', {
name: 'JoyCheckbox',
slot: 'Root',
overridesResolver: (props, styles) => styles.root,
})<{ ownerState: CheckboxProps }>(({ ownerState, theme }) => ({
'--Icon-fontSize': 'var(--Checkbox-size)',
...(ownerState.size === 'sm' && {
'--Checkbox-size': '1rem',
'--Checkbox-gap': '0.375rem',
fontSize: theme.vars.fontSize.sm,
}),
...(ownerState.size === 'md' && {
'--Checkbox-size': '1.25rem',
'--Checkbox-gap': '0.5rem',
fontSize: theme.vars.fontSize.md,
}),
...(ownerState.size === 'lg' && {
'--Checkbox-size': '1.5rem',
'--Checkbox-gap': '0.625rem',
fontSize: theme.vars.fontSize.lg,
}),
position: ownerState.overlay ? 'initial' : 'relative',
display: 'inline-flex',
fontFamily: theme.vars.fontFamily.body,
lineHeight: 'var(--Checkbox-size)', // prevent label from having larger height than the checkbox
[`&.${checkboxClasses.disabled}`]: {
color: theme.vars.palette[ownerState.color!]?.plainDisabledColor,
},
...(ownerState.disableIcon && {
color: theme.vars.palette[ownerState.color!]?.[`${ownerState.variant!}Color`],
[`&.${checkboxClasses.disabled}`]: {
color: theme.vars.palette[ownerState.color!]?.[`${ownerState.variant!}DisabledColor`],
},
}),
}));
const CheckboxCheckbox = styled('span', {
name: 'JoyCheckbox',
slot: 'Checkbox',
overridesResolver: (props, styles) => styles.checkbox,
})<{ ownerState: CheckboxProps }>(({ theme, ownerState }) => [
{
boxSizing: 'border-box',
borderRadius: theme.vars.radius.xs,
width: 'var(--Checkbox-size)',
height: 'var(--Checkbox-size)',
display: 'inline-flex',
justifyContent: 'center',
alignItems: 'center',
flexShrink: 0,
// TODO: discuss the transition approach in a separate PR. This value is copied from mui-material Button.
transition:
'background-color 250ms cubic-bezier(0.4, 0, 0.2, 1) 0ms, box-shadow 250ms cubic-bezier(0.4, 0, 0.2, 1) 0ms',
...(ownerState.disableIcon && {
display: 'contents',
}),
},
...(!ownerState.disableIcon
? [
theme.variants[ownerState.variant!]?.[ownerState.color!],
{ '&:hover': theme.variants[`${ownerState.variant!}Hover`]?.[ownerState.color!] },
{ '&:active': theme.variants[`${ownerState.variant!}Active`]?.[ownerState.color!] },
{
[`&.${checkboxClasses.disabled}`]:
theme.variants[`${ownerState.variant!}Disabled`]?.[ownerState.color!],
},
]
: []),
]);
const CheckboxAction = styled('span', {
name: 'JoyCheckbox',
slot: 'Action',
overridesResolver: (props, styles) => styles.action,
})<{ ownerState: CheckboxProps }>(({ theme, ownerState }) => [
{
borderRadius: `var(--Checkbox-action-radius, ${
ownerState.overlay ? 'var(--internal-action-radius, inherit)' : 'inherit'
})`,
position: 'absolute',
top: 0,
left: 0,
bottom: 0,
right: 0,
zIndex: 1, // The action element usually cover the area of nearest positioned parent
// TODO: discuss the transition approach in a separate PR. This value is copied from mui-material Button.
transition:
'background-color 250ms cubic-bezier(0.4, 0, 0.2, 1) 0ms, box-shadow 250ms cubic-bezier(0.4, 0, 0.2, 1) 0ms',
[theme.focus.selector]: theme.focus.default,
},
...(ownerState.disableIcon
? [
theme.variants[ownerState.variant!]?.[ownerState.color!],
{ '&:hover': theme.variants[`${ownerState.variant!}Hover`]?.[ownerState.color!] },
{ '&:active': theme.variants[`${ownerState.variant!}Active`]?.[ownerState.color!] },
{
[`&.${checkboxClasses.disabled}`]:
theme.variants[`${ownerState.variant!}Disabled`]?.[ownerState.color!],
},
]
: []),
]);
const CheckboxInput = styled('input', {
name: 'JoyCheckbox',
slot: 'Input',
overridesResolver: (props, styles) => styles.input,
})<{ ownerState: CheckboxProps }>(() => ({
margin: 0,
opacity: 0,
position: 'absolute',
width: '100%',
height: '100%',
cursor: 'pointer',
}));
const CheckboxLabel = styled('label', {
name: 'JoyCheckbox',
slot: 'Label',
overridesResolver: (props, styles) => styles.label,
})<{ ownerState: CheckboxProps }>(({ ownerState }) => ({
flex: 1,
minWidth: 0,
...(ownerState.disableIcon
? {
zIndex: 1, // label should stay on top of the action.
pointerEvents: 'none', // makes hover ineffect.
}
: {
marginInlineStart: 'var(--Checkbox-gap)',
}),
}));
const defaultCheckedIcon = <CheckIcon />;
const defaultIndeterminateIcon = <IndeterminateIcon />;
const Checkbox = React.forwardRef(function Checkbox(inProps, ref) {
const props = useThemeProps<typeof inProps & { component?: React.ElementType }>({
props: inProps,
name: 'JoyCheckbox',
});
const {
checked: checkedProp,
uncheckedIcon,
checkedIcon = defaultCheckedIcon,
label,
className,
component,
componentsProps = {},
defaultChecked,
disabled: disabledProp,
disableIcon = false,
overlay,
id: idOverride,
indeterminate = false,
indeterminateIcon = defaultIndeterminateIcon,
name,
onBlur,
onChange,
onFocus,
onFocusVisible,
required,
color,
variant,
size = 'md',
...otherProps
} = props;
const id = useId(idOverride);
const useCheckboxProps = {
checked: checkedProp,
defaultChecked,
disabled: disabledProp,
onBlur,
onChange,
onFocus,
onFocusVisible,
};
const { getInputProps, checked, disabled, focusVisible } = useSwitch(useCheckboxProps);
const isCheckboxActive = checked || indeterminate;
const activeColor = color || 'primary';
const inactiveColor = color || 'neutral';
const activeVariant = variant || 'solid';
const inactiveVariant = variant || 'outlined';
const ownerState = {
...props,
checked,
disabled,
disableIcon,
overlay,
focusVisible,
color: isCheckboxActive ? activeColor : inactiveColor,
variant: isCheckboxActive ? activeVariant : inactiveVariant,
size,
};
const classes = useUtilityClasses(ownerState);
return (
<CheckboxRoot
ref={ref}
{...otherProps}
as={component}
ownerState={ownerState}
className={clsx(classes.root, className)}
>
<CheckboxCheckbox
{...componentsProps?.checkbox}
ownerState={ownerState}
className={clsx(classes.checkbox, componentsProps.checkbox?.className)}
>
<CheckboxAction
{...componentsProps?.action}
ownerState={ownerState}
className={clsx(classes.action, componentsProps.action?.className)}
>
<CheckboxInput
{...componentsProps?.input}
ownerState={ownerState}
{...getInputProps(componentsProps.input)}
id={id}
name={name}
className={clsx(classes.input, componentsProps.input?.className)}
/>
</CheckboxAction>
{indeterminate && !checked && !disableIcon && indeterminateIcon}
{checked && !disableIcon && checkedIcon}
{!checked && !disableIcon && !indeterminate && uncheckedIcon}
</CheckboxCheckbox>
{label && (
<TypographyContext.Provider value>
<CheckboxLabel
{...componentsProps?.label}
htmlFor={id}
ownerState={ownerState}
className={clsx(classes.label, componentsProps.label?.className)}
>
{label}
</CheckboxLabel>
</TypographyContext.Provider>
)}
</CheckboxRoot>
);
}) as OverridableComponent<CheckboxTypeMap>;
Checkbox.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit TypeScript types and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* If `true`, the component is checked.
*/
checked: PropTypes.bool,
/**
* The icon to display when the component is checked.
* @default <CheckIcon />
*/
checkedIcon: PropTypes.node,
/**
* @ignore
*/
children: PropTypes.node,
/**
* Class name applied to the root element.
*/
className: PropTypes.string,
/**
* The color of the component. It supports those theme colors that make sense for this component.
* @default 'neutral'
*/
color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([
PropTypes.oneOf(['danger', 'info', 'primary', 'success', 'warning']),
PropTypes.string,
]),
/**
* The component used for the root node.
* Either a string to use a HTML element or a component.
*/
component: PropTypes.elementType,
/**
* The props used for each slot inside the Input.
* @default {}
*/
componentsProps: PropTypes.shape({
action: PropTypes.object,
checkbox: PropTypes.object,
input: PropTypes.object,
label: PropTypes.object,
root: PropTypes.object,
}),
/**
* The default checked state. Use when the component is not controlled.
*/
defaultChecked: PropTypes.bool,
/**
* If `true`, the component is disabled.
*/
disabled: PropTypes.bool,
/**
* If `true`, the checked icon is removed and the selected variant is applied on the `action` element instead.
* @default false
*/
disableIcon: PropTypes.bool,
/**
* @ignore
*/
id: PropTypes.string,
/**
* If `true`, the component appears indeterminate.
* This does not set the native input element to indeterminate due
* to inconsistent behavior across browsers.
* However, we set a `data-indeterminate` attribute on the `input`.
* @default false
*/
indeterminate: PropTypes.bool,
/**
* The icon to display when the component is indeterminate.
* @default <IndeterminateCheckBoxIcon />
*/
indeterminateIcon: PropTypes.node,
/**
* The label element next to the checkbox.
*/
label: PropTypes.node,
/**
* The `name` attribute of the input.
*/
name: PropTypes.string,
/**
* @ignore
*/
onBlur: PropTypes.func,
/**
* Callback fired when the state is changed.
*
* @param {React.ChangeEvent<HTMLInputElement>} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (string).
* You can pull out the new checked state by accessing `event.target.checked` (boolean).
*/
onChange: PropTypes.func,
/**
* @ignore
*/
onFocus: PropTypes.func,
/**
* @ignore
*/
onFocusVisible: PropTypes.func,
/**
* If `true`, the root element's position is set to initial which allows the action area to fill the nearest positioned parent.
* This prop is useful for composing Checkbox with ListItem component.
* @default false
*/
overlay: PropTypes.bool,
/**
* If `true`, the `input` element is required.
*/
required: PropTypes.bool,
/**
* The size of the component.
* @default 'md'
*/
size: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([
PropTypes.oneOf(['sm', 'md', 'lg']),
PropTypes.string,
]),
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])),
PropTypes.func,
PropTypes.object,
]),
/**
* The icon when `checked` is false.
*/
uncheckedIcon: PropTypes.node,
/**
* The variant to use.
* @default 'solid'
*/
variant: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([
PropTypes.oneOf(['outlined', 'plain', 'soft', 'solid']),
PropTypes.string,
]),
} as any;
export default Checkbox;