forked from mui/material-ui
/
Radio.tsx
462 lines (442 loc) · 14.1 KB
/
Radio.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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { OverridableComponent } from '@mui/types';
import { unstable_capitalize as capitalize, unstable_useId as useId } from '@mui/utils';
import { unstable_composeClasses as composeClasses } from '@mui/base';
import { useSwitch } from '@mui/base/SwitchUnstyled';
import { styled, useThemeProps } from '../styles';
import radioClasses, { getRadioUtilityClass } from './radioClasses';
import { RadioProps, RadioTypeMap } from './RadioProps';
import RadioGroupContext from '../RadioGroup/RadioGroupContext';
import { TypographyContext } from '../Typography/Typography';
const useUtilityClasses = (ownerState: RadioProps & { 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)}`,
],
radio: ['radio', 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, getRadioUtilityClass, {});
};
function areEqualValues(a: unknown, b: unknown) {
if (typeof b === 'object' && b !== null) {
return a === b;
}
// The value could be a number, the DOM will stringify it anyway.
return String(a) === String(b);
}
const RadioRoot = styled('span', {
name: 'JoyRadio',
slot: 'Root',
overridesResolver: (props, styles) => styles.root,
})<{ ownerState: RadioProps }>(({ ownerState, theme }) => {
return [
{
'--Icon-fontSize': 'var(--Radio-size)',
...(ownerState.size === 'sm' && {
'--Radio-size': '1rem',
'--Radio-gap': '0.375rem',
fontSize: theme.vars.fontSize.sm,
}),
...(ownerState.size === 'md' && {
'--Radio-size': '1.25rem',
'--Radio-gap': '0.5rem',
fontSize: theme.vars.fontSize.md,
}),
...(ownerState.size === 'lg' && {
'--Radio-size': '1.5rem',
'--Radio-gap': '0.625rem',
fontSize: theme.vars.fontSize.lg,
}),
...(ownerState.label &&
!ownerState.disableIcon && {
// add some space at the end to not have focus overlapping the label
paddingInlineEnd: 'var(--Radio-gap)',
}),
position: ownerState.overlay ? 'initial' : 'relative',
display: 'inline-flex',
boxSizing: 'border-box',
minWidth: 0,
fontFamily: theme.vars.fontFamily.body,
lineHeight: 'var(--Radio-size)', // prevent label from having larger height than the checkbox
[`&.${radioClasses.disabled}`]: {
color: theme.vars.palette[ownerState.color!]?.plainDisabledColor,
},
...(ownerState.disableIcon && {
color: theme.vars.palette[ownerState.color!]?.[`${ownerState.variant!}Color`],
[`&.${radioClasses.disabled}`]: {
color: theme.vars.palette[ownerState.color!]?.[`${ownerState.variant!}DisabledColor`],
},
}),
},
];
});
const RadioRadio = styled('span', {
name: 'JoyRadio',
slot: 'Radio',
overridesResolver: (props, styles) => styles.radio,
})<{ ownerState: RadioProps }>(({ ownerState, theme }) => [
{
margin: 0,
boxSizing: 'border-box',
width: 'var(--Radio-size)',
height: 'var(--Radio-size)',
borderRadius: 'var(--Radio-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!] },
{
[radioClasses.disabled]:
theme.variants[`${ownerState.variant!}Disabled`]?.[ownerState.color!],
},
]
: []),
]);
const RadioAction = styled('span', {
name: 'JoyRadio',
slot: 'Action',
overridesResolver: (props, styles) => styles.action,
})<{ ownerState: RadioProps }>(({ theme, ownerState }) => [
{
position: 'absolute',
borderRadius: `var(--Radio-action-radius, ${
// Automatic radius adjustment when composing with ListItem
ownerState.overlay ? 'var(--internal-action-radius, inherit)' : 'inherit'
})`,
top: 0,
left: 0,
right: 0,
bottom: 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!] },
{
[radioClasses.disabled]:
theme.variants[`${ownerState.variant!}Disabled`]?.[ownerState.color!],
},
]
: []),
]);
const RadioInput = styled('input', {
name: 'JoyRadio',
slot: 'Input',
overridesResolver: (props, styles) => styles.input,
})<{ ownerState: RadioProps }>(() => ({
margin: 0,
opacity: 0,
position: 'absolute',
height: '100%',
width: '100%',
cursor: 'pointer',
}));
const RadioLabel = styled('label', {
name: 'JoyRadio',
slot: 'Label',
overridesResolver: (props, styles) => styles.label,
})<{ ownerState: RadioProps }>(({ ownerState }) => ({
flex: 1,
minWidth: 0,
...(ownerState.disableIcon
? {
zIndex: 1, // label should stay on top of the action.
pointerEvents: 'none', // makes hover ineffect.
}
: {
marginInlineStart: 'var(--Radio-gap)',
}),
}));
/**
* internal component
*/
const RadioIcon = styled('span', {
name: 'JoyRadio',
slot: 'Icon',
overridesResolver: (props, styles) => styles.icon,
})<{ ownerState: RadioProps }>(({ ownerState }) => ({
width: '50%',
height: '50%',
borderRadius: 'inherit',
color: 'inherit',
backgroundColor: 'currentColor',
// TODO: discuss the transition approach in a separate PR. This value is copied from mui-material Button.
transition: 'transform 150ms cubic-bezier(0.4, 0, 0.2, 1) 0ms',
transform: ownerState.checked ? 'scale(1)' : 'scale(0)',
}));
const Radio = React.forwardRef(function Radio(inProps, ref) {
const props = useThemeProps<typeof inProps & { component?: React.ElementType }>({
props: inProps,
name: 'JoyRadio',
});
const {
checked: checkedProp,
checkedIcon,
className,
component,
componentsProps = {},
defaultChecked,
disabled: disabledProp,
disableIcon: disableIconProp = false,
overlay: overlayProp = false,
label,
id: idOverride,
name: nameProp,
onBlur,
onChange,
onFocus,
onFocusVisible,
required,
color: colorProp,
variant: variantProp = 'outlined',
size: sizeProp = 'md',
uncheckedIcon,
value,
...otherProps
} = props;
const id = useId(idOverride);
const radioGroup = React.useContext(RadioGroupContext);
const color = inProps.color || radioGroup.color || colorProp;
const activeColor = color || 'primary';
const inactiveColor = color || 'neutral';
const variant = inProps.variant || radioGroup.variant || variantProp;
const size = inProps.size || radioGroup.size || sizeProp;
const name = inProps.name || radioGroup.name || nameProp;
const disableIcon = inProps.disableIcon || radioGroup.disableIcon || disableIconProp;
const overlay = inProps.overlay || radioGroup.overlay || overlayProp;
const radioChecked =
typeof checkedProp === 'undefined' && !!value
? areEqualValues(radioGroup.value, value)
: checkedProp;
const useRadioProps = {
checked: radioChecked,
defaultChecked,
disabled: disabledProp,
onBlur,
onChange,
onFocus,
onFocusVisible,
};
const { getInputProps, checked, disabled, focusVisible } = useSwitch(useRadioProps);
const ownerState = {
...props,
checked,
disabled,
focusVisible,
color: checked ? activeColor : inactiveColor,
variant,
size,
disableIcon,
overlay,
};
const classes = useUtilityClasses(ownerState);
return (
<RadioRoot
ref={ref}
{...otherProps}
as={component}
ownerState={ownerState}
className={clsx(classes.root, className)}
>
<RadioRadio
{...componentsProps?.radio}
ownerState={ownerState}
className={clsx(classes.radio, componentsProps?.radio?.className)}
>
{checked && !disableIcon && checkedIcon}
{!checked && !disableIcon && uncheckedIcon}
{!checkedIcon && !uncheckedIcon && !disableIcon && <RadioIcon ownerState={ownerState} />}
<RadioAction
{...componentsProps?.action}
ownerState={ownerState}
className={clsx(classes.action, componentsProps?.action?.className)}
>
<RadioInput
ownerState={ownerState}
{...getInputProps({ ...componentsProps.input, onChange: radioGroup.onChange })}
type="radio"
id={id}
name={name}
value={String(value)}
className={clsx(classes.input, componentsProps.input?.className)}
/>
</RadioAction>
</RadioRadio>
{label && (
<RadioLabel
{...componentsProps?.label}
htmlFor={id}
ownerState={ownerState}
className={clsx(classes.label, componentsProps?.label?.className)}
>
{/* Automatically adjust the Typography to render `span` */}
<TypographyContext.Provider value>{label}</TypographyContext.Provider>
</RadioLabel>
)}
</RadioRoot>
);
}) as OverridableComponent<RadioTypeMap>;
Radio.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.
*/
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,
input: PropTypes.object,
label: PropTypes.object,
radio: 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,
/**
* The label element at the end the radio.
*/
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 Radio 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 to display when the component is not checked.
*/
uncheckedIcon: PropTypes.node,
/**
* The value of the component. The DOM API casts this to a string.
*/
value: PropTypes.any,
/**
* The variant to use.
* @default 'outlined'
*/
variant: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([
PropTypes.oneOf(['outlined', 'plain', 'soft', 'solid']),
PropTypes.string,
]),
} as any;
export default Radio;