-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
variation.js
108 lines (97 loc) · 2.59 KB
/
variation.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
101
102
103
104
105
106
107
108
/**
* External dependencies
*/
import clsx from 'clsx';
/**
* WordPress dependencies
*/
import { Tooltip } from '@wordpress/components';
import { useMemo, useContext, useState } from '@wordpress/element';
import { ENTER } from '@wordpress/keycodes';
import { __, sprintf } from '@wordpress/i18n';
import { privateApis as blockEditorPrivateApis } from '@wordpress/block-editor';
import { privateApis as editorPrivateApis } from '@wordpress/editor';
/**
* Internal dependencies
*/
import { filterObjectByProperties } from '../../../hooks/use-theme-style-variations/use-theme-style-variations-by-property';
import { unlock } from '../../../lock-unlock';
const { mergeBaseAndUserConfigs } = unlock( editorPrivateApis );
const { GlobalStylesContext, areGlobalStyleConfigsEqual } = unlock(
blockEditorPrivateApis
);
export default function Variation( {
variation,
children,
isPill,
properties,
showTooltip,
} ) {
const [ isFocused, setIsFocused ] = useState( false );
const { base, user, setUserConfig } = useContext( GlobalStylesContext );
const context = useMemo( () => {
let merged = mergeBaseAndUserConfigs( base, variation );
if ( properties ) {
merged = filterObjectByProperties( merged, properties );
}
return {
user: variation,
base,
merged,
setUserConfig: () => {},
};
}, [ variation, base, properties ] );
const selectVariation = () => setUserConfig( variation );
const selectOnEnter = ( event ) => {
if ( event.keyCode === ENTER ) {
event.preventDefault();
selectVariation();
}
};
const isActive = useMemo(
() => areGlobalStyleConfigsEqual( user, variation ),
[ user, variation ]
);
let label = variation?.title;
if ( variation?.description ) {
label = sprintf(
/* translators: %1$s: variation title. %2$s variation description. */
__( '%1$s (%2$s)' ),
variation?.title,
variation?.description
);
}
const content = (
<div
className={ clsx( 'edit-site-global-styles-variations_item', {
'is-active': isActive,
} ) }
role="button"
onClick={ selectVariation }
onKeyDown={ selectOnEnter }
tabIndex="0"
aria-label={ label }
aria-current={ isActive }
onFocus={ () => setIsFocused( true ) }
onBlur={ () => setIsFocused( false ) }
>
<div
className={ clsx(
'edit-site-global-styles-variations_item-preview',
{ 'is-pill': isPill }
) }
>
{ children( isFocused ) }
</div>
</div>
);
return (
<GlobalStylesContext.Provider value={ context }>
{ showTooltip ? (
<Tooltip text={ variation?.title }>{ content }</Tooltip>
) : (
content
) }
</GlobalStylesContext.Provider>
);
}