-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathpartial-syncing-controls.js
108 lines (97 loc) · 2.53 KB
/
partial-syncing-controls.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 { nanoid } from 'nanoid';
/**
* WordPress dependencies
*/
import { InspectorControls } from '@wordpress/block-editor';
import { BaseControl, CheckboxControl } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import { PARTIAL_SYNCING_SUPPORTED_BLOCKS } from '../constants';
function PartialSyncingControls( { name, attributes, setAttributes } ) {
const syncedAttributes = PARTIAL_SYNCING_SUPPORTED_BLOCKS[ name ];
const attributeSources = Object.keys( syncedAttributes ).map(
( attributeName ) =>
attributes.metadata?.bindings?.[ attributeName ]?.source
);
const isConnectedToOtherSources = attributeSources.every(
( source ) => source && source !== 'core/pattern-overrides'
);
// Render nothing if all supported attributes are connected to other sources.
if ( isConnectedToOtherSources ) {
return null;
}
function updateBindings( isChecked ) {
let updatedBindings = {
...attributes?.metadata?.bindings,
};
if ( ! isChecked ) {
for ( const attributeName of Object.keys( syncedAttributes ) ) {
if (
updatedBindings[ attributeName ]?.source ===
'core/pattern-overrides'
) {
delete updatedBindings[ attributeName ];
}
}
if ( ! Object.keys( updatedBindings ).length ) {
updatedBindings = undefined;
}
setAttributes( {
metadata: {
...attributes.metadata,
bindings: updatedBindings,
},
} );
return;
}
for ( const attributeName of Object.keys( syncedAttributes ) ) {
if ( ! updatedBindings[ attributeName ] ) {
updatedBindings[ attributeName ] = {
source: 'core/pattern-overrides',
};
}
}
if ( typeof attributes.metadata?.id === 'string' ) {
setAttributes( {
metadata: {
...attributes.metadata,
bindings: updatedBindings,
},
} );
return;
}
const id = nanoid( 6 );
setAttributes( {
metadata: {
...attributes.metadata,
id,
bindings: updatedBindings,
},
} );
}
return (
<InspectorControls group="advanced">
<BaseControl __nextHasNoMarginBottom>
<BaseControl.VisualLabel>
{ __( 'Pattern overrides' ) }
</BaseControl.VisualLabel>
<CheckboxControl
__nextHasNoMarginBottom
label={ __( 'Allow instance overrides' ) }
checked={ attributeSources.some(
( source ) => source === 'core/pattern-overrides'
) }
onChange={ ( isChecked ) => {
updateBindings( isChecked );
} }
/>
</BaseControl>
</InspectorControls>
);
}
export default PartialSyncingControls;