-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
aspect-ratio-tool.js
100 lines (91 loc) · 2.67 KB
/
aspect-ratio-tool.js
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
/**
* WordPress dependencies
*/
import {
SelectControl,
__experimentalToolsPanelItem as ToolsPanelItem,
} from '@wordpress/components';
import { __, _x } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import { useSettings } from '../use-settings';
/**
* @typedef {import('@wordpress/components/build-types/select-control/types').SelectControlProps} SelectControlProps
*/
/**
* @callback AspectRatioToolPropsOnChange
* @param {string} [value] New aspect ratio value.
* @return {void} No return.
*/
/**
* @typedef {Object} AspectRatioToolProps
* @property {string} [panelId] ID of the panel this tool is associated with.
* @property {string} [value] Current aspect ratio value.
* @property {AspectRatioToolPropsOnChange} [onChange] Callback to update the aspect ratio value.
* @property {SelectControlProps[]} [options] Aspect ratio options.
* @property {string} [defaultValue] Default aspect ratio value.
* @property {boolean} [isShownByDefault] Whether the tool is shown by default.
*/
export default function AspectRatioTool( {
panelId,
value,
onChange = () => {},
options,
defaultValue = 'auto',
hasValue,
isShownByDefault = true,
} ) {
// Match the CSS default so if the value is used directly in CSS it will look correct in the control.
const displayValue = value ?? 'auto';
const [ defaultRatios, themeRatios, showDefaultRatios ] = useSettings(
'dimensions.aspectRatios.default',
'dimensions.aspectRatios.theme',
'dimensions.defaultAspectRatios'
);
const themeOptions = themeRatios?.map( ( { name, ratio } ) => ( {
label: name,
value: ratio,
} ) );
const defaultOptions = defaultRatios?.map( ( { name, ratio } ) => ( {
label: name,
value: ratio,
} ) );
const aspectRatioOptions = [
{
label: _x(
'Original',
'Aspect ratio option for dimensions control'
),
value: 'auto',
},
...( showDefaultRatios ? defaultOptions : [] ),
...( themeOptions ? themeOptions : [] ),
{
label: _x( 'Custom', 'Aspect ratio option for dimensions control' ),
value: 'custom',
disabled: true,
hidden: true,
},
];
return (
<ToolsPanelItem
hasValue={
hasValue ? hasValue : () => displayValue !== defaultValue
}
label={ __( 'Aspect ratio' ) }
onDeselect={ () => onChange( undefined ) }
isShownByDefault={ isShownByDefault }
panelId={ panelId }
>
<SelectControl
label={ __( 'Aspect ratio' ) }
value={ displayValue }
options={ options ?? aspectRatioOptions }
onChange={ onChange }
size="__unstable-large"
__nextHasNoMarginBottom
/>
</ToolsPanelItem>
);
}