-
Notifications
You must be signed in to change notification settings - Fork 4k
/
index.tsx
108 lines (101 loc) · 2.49 KB
/
index.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
/**
* External dependencies
*/
import type { ChangeEvent } from 'react';
import { css } from '@emotion/react';
/**
* WordPress dependencies
*/
import { useInstanceId } from '@wordpress/compose';
/**
* Internal dependencies
*/
import FormToggle from '../form-toggle';
import BaseControl from '../base-control';
import type { WordPressComponentProps } from '../ui/context/wordpress-component';
import type { ToggleControlProps } from './types';
import { HStack } from '../h-stack';
import { useCx } from '../utils';
import { space } from '../ui/utils/space';
/**
* ToggleControl is used to generate a toggle user interface.
*
* ```jsx
* import { ToggleControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const MyToggleControl = () => {
* const [ value, setValue ] = useState( false );
*
* return (
* <ToggleControl
* label="Fixed Background"
* checked={ value }
* onChange={ () => setValue( ( state ) => ! state ) }
* />
* );
* };
* ```
*/
export function ToggleControl( {
__nextHasNoMarginBottom,
label,
checked,
help,
className,
onChange,
disabled,
}: WordPressComponentProps< ToggleControlProps, 'input', false > ) {
function onChangeToggle( event: ChangeEvent< HTMLInputElement > ) {
onChange( event.target.checked );
}
const instanceId = useInstanceId( ToggleControl );
const id = `inspector-toggle-control-${ instanceId }`;
const cx = useCx();
const classes = cx(
'components-toggle-control',
className,
! __nextHasNoMarginBottom && css( { marginBottom: space( 3 ) } )
);
let describedBy, helpLabel;
if ( help ) {
if ( typeof help === 'function' ) {
// `help` as a function works only for controlled components where
// `checked` is passed down from parent component. Uncontrolled
// component can show only a static help label.
if ( checked !== undefined ) {
helpLabel = help( checked );
}
} else {
helpLabel = help;
}
if ( helpLabel ) {
describedBy = id + '__help';
}
}
return (
<BaseControl
id={ id }
help={ helpLabel }
className={ classes }
__nextHasNoMarginBottom
>
<HStack justify="flex-start" spacing={ 3 }>
<FormToggle
id={ id }
checked={ checked }
onChange={ onChangeToggle }
aria-describedby={ describedBy }
disabled={ disabled }
/>
<label
htmlFor={ id }
className="components-toggle-control__label"
>
{ label }
</label>
</HStack>
</BaseControl>
);
}
export default ToggleControl;