-
Notifications
You must be signed in to change notification settings - Fork 939
/
Copy pathswitch.tsx
202 lines (180 loc) · 6.65 KB
/
switch.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
import * as React from 'react';
import { composeEventHandlers } from '@radix-ui/primitive';
import { useComposedRefs } from '@radix-ui/react-compose-refs';
import { createContextScope } from '@radix-ui/react-context';
import { useControllableState } from '@radix-ui/react-use-controllable-state';
import { usePrevious } from '@radix-ui/react-use-previous';
import { useSize } from '@radix-ui/react-use-size';
import { Primitive } from '@radix-ui/react-primitive';
import type { Scope } from '@radix-ui/react-context';
/* -------------------------------------------------------------------------------------------------
* Switch
* -----------------------------------------------------------------------------------------------*/
const SWITCH_NAME = 'Switch';
type ScopedProps<P> = P & { __scopeSwitch?: Scope };
const [createSwitchContext, createSwitchScope] = createContextScope(SWITCH_NAME);
type SwitchContextValue = { checked: boolean; disabled?: boolean };
const [SwitchProvider, useSwitchContext] = createSwitchContext<SwitchContextValue>(SWITCH_NAME);
type SwitchElement = React.ElementRef<typeof Primitive.button>;
type PrimitiveButtonProps = React.ComponentPropsWithoutRef<typeof Primitive.button>;
interface SwitchProps extends PrimitiveButtonProps {
checked?: boolean;
defaultChecked?: boolean;
required?: boolean;
disableNativeInput?: boolean;
onCheckedChange?(checked: boolean): void;
}
const Switch = React.forwardRef<SwitchElement, SwitchProps>(
(props: ScopedProps<SwitchProps>, forwardedRef) => {
const {
__scopeSwitch,
name,
checked: checkedProp,
defaultChecked,
required,
disabled,
value = 'on',
onCheckedChange,
form,
disableNativeInput,
...switchProps
} = props;
const [button, setButton] = React.useState<HTMLButtonElement | null>(null);
const composedRefs = useComposedRefs(forwardedRef, (node) => setButton(node));
const hasConsumerStoppedPropagationRef = React.useRef(false);
// We set this to true by default so that events bubble to forms without JS (SSR)
const isFormControl = disableNativeInput
? false
: button
? form || !!button.closest('form')
: true;
const [checked = false, setChecked] = useControllableState({
prop: checkedProp,
defaultProp: defaultChecked,
onChange: onCheckedChange,
});
return (
<SwitchProvider scope={__scopeSwitch} checked={checked} disabled={disabled}>
<Primitive.button
type="button"
role="switch"
aria-checked={checked}
aria-required={required}
data-state={getState(checked)}
data-disabled={disabled ? '' : undefined}
disabled={disabled}
value={value}
{...switchProps}
ref={composedRefs}
onClick={composeEventHandlers(props.onClick, (event) => {
setChecked((prevChecked) => !prevChecked);
if (isFormControl) {
hasConsumerStoppedPropagationRef.current = event.isPropagationStopped();
// if switch is in a form, stop propagation from the button so that we only propagate
// one click event (from the input). We propagate changes from an input so that native
// form validation works and form events reflect switch updates.
if (!hasConsumerStoppedPropagationRef.current) event.stopPropagation();
}
})}
/>
{isFormControl && (
<BubbleInput
control={button}
bubbles={!hasConsumerStoppedPropagationRef.current}
name={name}
value={value}
checked={checked}
required={required}
disabled={disabled}
form={form}
// We transform because the input is absolutely positioned but we have
// rendered it **after** the button. This pulls it back to sit on top
// of the button.
style={{ transform: 'translateX(-100%)' }}
/>
)}
</SwitchProvider>
);
}
);
Switch.displayName = SWITCH_NAME;
/* -------------------------------------------------------------------------------------------------
* SwitchThumb
* -----------------------------------------------------------------------------------------------*/
const THUMB_NAME = 'SwitchThumb';
type SwitchThumbElement = React.ElementRef<typeof Primitive.span>;
type PrimitiveSpanProps = React.ComponentPropsWithoutRef<typeof Primitive.span>;
interface SwitchThumbProps extends PrimitiveSpanProps {}
const SwitchThumb = React.forwardRef<SwitchThumbElement, SwitchThumbProps>(
(props: ScopedProps<SwitchThumbProps>, forwardedRef) => {
const { __scopeSwitch, ...thumbProps } = props;
const context = useSwitchContext(THUMB_NAME, __scopeSwitch);
return (
<Primitive.span
data-state={getState(context.checked)}
data-disabled={context.disabled ? '' : undefined}
{...thumbProps}
ref={forwardedRef}
/>
);
}
);
SwitchThumb.displayName = THUMB_NAME;
/* ---------------------------------------------------------------------------------------------- */
type InputProps = React.ComponentPropsWithoutRef<'input'>;
interface BubbleInputProps extends Omit<InputProps, 'checked'> {
checked: boolean;
control: HTMLElement | null;
bubbles: boolean;
}
const BubbleInput = (props: BubbleInputProps) => {
const { control, checked, bubbles = true, ...inputProps } = props;
const ref = React.useRef<HTMLInputElement>(null);
const prevChecked = usePrevious(checked);
const controlSize = useSize(control);
// Bubble checked change to parents (e.g form change event)
React.useEffect(() => {
const input = ref.current!;
const inputProto = window.HTMLInputElement.prototype;
const descriptor = Object.getOwnPropertyDescriptor(inputProto, 'checked') as PropertyDescriptor;
const setChecked = descriptor.set;
if (prevChecked !== checked && setChecked) {
const event = new Event('click', { bubbles });
setChecked.call(input, checked);
input.dispatchEvent(event);
}
}, [prevChecked, checked, bubbles]);
return (
<input
type="checkbox"
aria-hidden
defaultChecked={checked}
{...inputProps}
tabIndex={-1}
ref={ref}
style={{
...props.style,
...controlSize,
position: 'absolute',
pointerEvents: 'none',
opacity: 0,
margin: 0,
}}
/>
);
};
function getState(checked: boolean) {
return checked ? 'checked' : 'unchecked';
}
const Root = Switch;
const Thumb = SwitchThumb;
export {
createSwitchScope,
//
Switch,
SwitchThumb,
//
Root,
Thumb,
};
export type { SwitchProps, SwitchThumbProps };