/
AsyncSwitch.tsx
78 lines (72 loc) · 2.02 KB
/
AsyncSwitch.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
import type { CSSProperties } from "react";
import { forwardRef } from "react";
import cn from "classnames";
import { CircularProgress, getProgressA11y } from "@react-md/progress";
import type { SwitchProps } from "./Switch";
import { Switch } from "./Switch";
export interface AsyncSwitchProps extends SwitchProps {
/**
* Boolean if the switch is still loading. This will "disable" the switch and
* add the circular progress indicator in the switch's ball until it is set
* back to false.
*/
loading: boolean;
/**
* An optional style to apply to the progress bar while the loading state is
* enabled.
*/
progressStyle?: CSSProperties;
/**
* An optional class name to apply to the progress bar while the loading state
* is enabled.
*/
progressClassName?: string;
}
// this is used while the loading state is enabled to "disable" the switch
// toggle. If we disable the entire switch, keyboard focus is lost which is not
// desired.
const noop = (): void => {
// do nothing
};
/**
* This component will create an async switch that will show a loading indicator
* and prevent the switch from being toggled while the loading state is true.
*/
export const AsyncSwitch = forwardRef<HTMLInputElement, AsyncSwitchProps>(
function AsyncSwitch(
{
id,
disabled,
className,
progressStyle,
progressClassName,
loading,
onChange,
...props
},
ref
) {
const progressId = `${id}-loading`;
return (
<Switch
{...props}
{...getProgressA11y(progressId, loading)}
id={id}
ref={ref}
disabled={disabled}
className={cn("rmd-switch--async", className)}
labelDisabled={disabled || false}
onChange={loading ? noop : onChange}
>
{loading && (
<CircularProgress
id={progressId}
style={progressStyle}
className={cn("rmd-switch__progress", progressClassName)}
centered={false}
/>
)}
</Switch>
);
}
);