Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pterodactyl
GitHub Repository: pterodactyl/panel
Path: blob/1.0-develop/resources/scripts/components/elements/Switch.tsx
7461 views
1
import React, { useMemo } from 'react';
2
import styled from 'styled-components/macro';
3
import { v4 } from 'uuid';
4
import tw from 'twin.macro';
5
import Label from '@/components/elements/Label';
6
import Input from '@/components/elements/Input';
7
8
const ToggleContainer = styled.div`
9
${tw`relative select-none w-12 leading-normal`};
10
11
& > input[type='checkbox'] {
12
${tw`hidden`};
13
14
&:checked + label {
15
${tw`bg-primary-500 border-primary-700 shadow-none`};
16
}
17
18
&:checked + label:before {
19
right: 0.125rem;
20
}
21
}
22
23
& > label {
24
${tw`mb-0 block overflow-hidden cursor-pointer bg-neutral-400 border border-neutral-700 rounded-full h-6 shadow-inner`};
25
transition: all 75ms linear;
26
27
&::before {
28
${tw`absolute block bg-white border h-5 w-5 rounded-full`};
29
top: 0.125rem;
30
right: calc(50% + 0.125rem);
31
//width: 1.25rem;
32
//height: 1.25rem;
33
content: '';
34
transition: all 75ms ease-in;
35
}
36
}
37
`;
38
39
export interface SwitchProps {
40
name: string;
41
label?: string;
42
description?: string;
43
defaultChecked?: boolean;
44
readOnly?: boolean;
45
onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
46
children?: React.ReactNode;
47
}
48
49
const Switch = ({ name, label, description, defaultChecked, readOnly, onChange, children }: SwitchProps) => {
50
const uuid = useMemo(() => v4(), []);
51
52
return (
53
<div css={tw`flex items-center`}>
54
<ToggleContainer css={tw`flex-none`}>
55
{children || (
56
<Input
57
id={uuid}
58
name={name}
59
type={'checkbox'}
60
onChange={(e) => onChange && onChange(e)}
61
defaultChecked={defaultChecked}
62
disabled={readOnly}
63
/>
64
)}
65
<Label htmlFor={uuid} />
66
</ToggleContainer>
67
{(label || description) && (
68
<div css={tw`ml-4 w-full`}>
69
{label && (
70
<Label css={[tw`cursor-pointer`, !!description && tw`mb-0`]} htmlFor={uuid}>
71
{label}
72
</Label>
73
)}
74
{description && <p css={tw`text-neutral-400 text-sm mt-2`}>{description}</p>}
75
</div>
76
)}
77
</div>
78
);
79
};
80
81
export default Switch;
82
83