forked from mui/base-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSwitchRoot.tsx
More file actions
357 lines (326 loc) · 10 KB
/
SwitchRoot.tsx
File metadata and controls
357 lines (326 loc) · 10 KB
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
'use client';
import * as React from 'react';
import { useControlled } from '@base-ui/utils/useControlled';
import { useStableCallback } from '@base-ui/utils/useStableCallback';
import { useMergedRefs } from '@base-ui/utils/useMergedRefs';
import { useIsoLayoutEffect } from '@base-ui/utils/useIsoLayoutEffect';
import { visuallyHidden, visuallyHiddenInput } from '@base-ui/utils/visuallyHidden';
import { EMPTY_OBJECT } from '@base-ui/utils/empty';
import { useRenderElement } from '../../utils/useRenderElement';
import type { BaseUIComponentProps, NonNativeButtonProps } from '../../utils/types';
import { mergeProps } from '../../merge-props';
import { useBaseUiId } from '../../utils/useBaseUiId';
import { useButton } from '../../use-button';
import { SwitchRootContext } from './SwitchRootContext';
import { stateAttributesMapping } from '../stateAttributesMapping';
import type { FieldRootState } from '../../field/root/FieldRoot';
import { useFieldRootContext } from '../../field/root/FieldRootContext';
import { useRegisterFieldControl } from '../../field/root/useRegisterFieldControl';
import { useFormContext } from '../../form/FormContext';
import { useLabelableContext } from '../../labelable-provider/LabelableContext';
import { useAriaLabelledBy } from '../../labelable-provider/useAriaLabelledBy';
import { useLabelableId } from '../../labelable-provider/useLabelableId';
import { createChangeEventDetails } from '../../utils/createBaseUIEventDetails';
import { REASONS } from '../../utils/reasons';
import type { BaseUIChangeEventDetails } from '../../types';
import { useValueChanged } from '../../utils/useValueChanged';
/**
* Represents the switch itself.
* Renders a `<span>` element and a hidden `<input>` beside.
*
* Documentation: [Base UI Switch](https://base-ui.com/react/components/switch)
*/
export const SwitchRoot = React.forwardRef(function SwitchRoot(
componentProps: SwitchRoot.Props,
forwardedRef: React.ForwardedRef<HTMLElement>,
) {
const {
checked: checkedProp,
className,
defaultChecked,
'aria-labelledby': ariaLabelledByProp,
form,
id: idProp,
inputRef: externalInputRef,
name: nameProp,
nativeButton = false,
onCheckedChange: onCheckedChangeProp,
readOnly = false,
required = false,
disabled: disabledProp = false,
render,
uncheckedValue,
value,
style,
...elementProps
} = componentProps;
const { clearErrors } = useFormContext();
const {
state: fieldState,
setTouched,
setDirty,
validityData,
setFilled,
setFocused,
shouldValidateOnChange,
validationMode,
disabled: fieldDisabled,
name: fieldName,
validation,
} = useFieldRootContext();
const { labelId } = useLabelableContext();
const disabled = fieldDisabled || disabledProp;
const name = fieldName ?? nameProp;
const onCheckedChange = useStableCallback(onCheckedChangeProp);
const inputRef = React.useRef<HTMLInputElement>(null);
const handleInputRef = useMergedRefs(inputRef, externalInputRef, validation.inputRef);
const switchRef = React.useRef<HTMLButtonElement | null>(null);
const id = useBaseUiId();
const controlId = useLabelableId({
id: idProp,
implicit: false,
controlRef: switchRef,
});
const hiddenInputId = nativeButton ? undefined : controlId;
const [checked, setCheckedState] = useControlled({
controlled: checkedProp,
default: Boolean(defaultChecked),
name: 'Switch',
state: 'checked',
});
useRegisterFieldControl(switchRef, {
id,
value: checked,
});
useIsoLayoutEffect(() => {
if (inputRef.current) {
setFilled(inputRef.current.checked);
}
}, [inputRef, setFilled]);
useValueChanged(checked, () => {
clearErrors(name);
setDirty(checked !== validityData.initialValue);
setFilled(checked);
if (shouldValidateOnChange()) {
validation.commit(checked);
} else {
validation.commit(checked, true);
}
});
const { getButtonProps, buttonRef } = useButton({
disabled,
native: nativeButton,
});
const ariaLabelledBy = useAriaLabelledBy(
ariaLabelledByProp,
labelId,
inputRef,
!nativeButton,
hiddenInputId,
);
const rootProps: React.ComponentPropsWithRef<'span'> = {
id: nativeButton ? controlId : id,
role: 'switch',
'aria-checked': checked,
'aria-readonly': readOnly || undefined,
'aria-required': required || undefined,
'aria-labelledby': ariaLabelledBy,
onFocus() {
if (!disabled) {
setFocused(true);
}
},
onBlur() {
const element = inputRef.current;
if (!element || disabled) {
return;
}
setTouched(true);
setFocused(false);
if (validationMode === 'onBlur') {
validation.commit(element.checked);
}
},
onClick(event) {
if (readOnly || disabled) {
return;
}
event.preventDefault();
inputRef.current?.dispatchEvent(
new PointerEvent('click', {
bubbles: true,
shiftKey: event.shiftKey,
ctrlKey: event.ctrlKey,
altKey: event.altKey,
metaKey: event.metaKey,
}),
);
},
};
const inputProps: React.ComponentPropsWithRef<'input'> = React.useMemo(
() =>
mergeProps<'input'>(
{
checked,
disabled,
form,
id: hiddenInputId,
name,
required,
style: name ? visuallyHiddenInput : visuallyHidden,
tabIndex: -1,
type: 'checkbox',
'aria-hidden': true,
ref: handleInputRef,
onChange(event) {
// Workaround for https://github.com/facebook/react/issues/9023
if (event.nativeEvent.defaultPrevented) {
return;
}
const nextChecked = event.currentTarget.checked;
const eventDetails = createChangeEventDetails(REASONS.none, event.nativeEvent);
onCheckedChange?.(nextChecked, eventDetails);
if (eventDetails.isCanceled) {
return;
}
setCheckedState(nextChecked);
},
onFocus() {
switchRef.current?.focus();
},
},
validation.getInputValidationProps,
// React <19 sets an empty value if `undefined` is passed explicitly
// To avoid this, we only set the value if it's defined
value !== undefined ? { value } : EMPTY_OBJECT,
),
[
checked,
disabled,
form,
handleInputRef,
hiddenInputId,
name,
onCheckedChange,
required,
setCheckedState,
validation,
value,
],
);
const state: SwitchRootState = React.useMemo(
() => ({
...fieldState,
checked,
disabled,
readOnly,
required,
}),
[fieldState, checked, disabled, readOnly, required],
);
const element = useRenderElement('span', componentProps, {
state,
ref: [forwardedRef, switchRef, buttonRef],
props: [rootProps, validation.getValidationProps, elementProps, getButtonProps],
stateAttributesMapping,
});
return (
<SwitchRootContext.Provider value={state}>
{element}
{!checked && name && uncheckedValue !== undefined && (
<input type="hidden" form={form} name={name} value={uncheckedValue} />
)}
<input {...inputProps} suppressHydrationWarning />
</SwitchRootContext.Provider>
);
});
export interface SwitchRootState extends FieldRootState {
/**
* Whether the switch is currently active.
*/
checked: boolean;
/**
* Whether the component should ignore user interaction.
*/
disabled: boolean;
/**
* Whether the user should be unable to activate or deactivate the switch.
*/
readOnly: boolean;
/**
* Whether the user must activate the switch before submitting a form.
*/
required: boolean;
}
export interface SwitchRootProps
extends NonNativeButtonProps, Omit<BaseUIComponentProps<'span', SwitchRootState>, 'onChange'> {
/**
* The id of the switch element.
*/
id?: string | undefined;
/**
* Whether the switch is currently active.
*
* To render an uncontrolled switch, use the `defaultChecked` prop instead.
*/
checked?: boolean | undefined;
/**
* Whether the switch is initially active.
*
* To render a controlled switch, use the `checked` prop instead.
* @default false
*/
defaultChecked?: boolean | undefined;
/**
* Whether the component should ignore user interaction.
* @default false
*/
disabled?: boolean | undefined;
/**
* A ref to access the hidden `<input>` element.
*/
inputRef?: React.Ref<HTMLInputElement> | undefined;
/**
* Identifies the field when a form is submitted.
*/
name?: string | undefined;
/**
* Identifies the form that owns the hidden input.
* Useful when the switch is rendered outside the form.
*/
form?: string | undefined;
/**
* Event handler called when the switch is activated or deactivated.
*/
onCheckedChange?:
| ((checked: boolean, eventDetails: SwitchRoot.ChangeEventDetails) => void)
| undefined;
/**
* Whether the user should be unable to activate or deactivate the switch.
* @default false
*/
readOnly?: boolean | undefined;
/**
* Whether the user must activate the switch before submitting a form.
* @default false
*/
required?: boolean | undefined;
/**
* The value submitted with the form when the switch is on.
* By default, switch submits the "on" value, matching native checkbox behavior.
*/
value?: string | undefined;
/**
* The value submitted with the form when the switch is off.
* By default, unchecked switches do not submit any value, matching native checkbox behavior.
*/
uncheckedValue?: string | undefined;
}
export type SwitchRootChangeEventReason = typeof REASONS.none;
export type SwitchRootChangeEventDetails = BaseUIChangeEventDetails<SwitchRoot.ChangeEventReason>;
export namespace SwitchRoot {
export type State = SwitchRootState;
export type Props = SwitchRootProps;
export type ChangeEventReason = SwitchRootChangeEventReason;
export type ChangeEventDetails = SwitchRootChangeEventDetails;
}