-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathedit.js
424 lines (384 loc) · 11.2 KB
/
edit.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
/**
* External dependencies
*/
import classnames from 'classnames';
/**
* WordPress dependencies
*/
import { useRegistry, useSelect, useDispatch } from '@wordpress/data';
import { useRef, useMemo, useEffect } from '@wordpress/element';
import { useEntityRecord, store as coreStore } from '@wordpress/core-data';
import {
Placeholder,
Spinner,
ToolbarButton,
ToolbarGroup,
} from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import {
useInnerBlocksProps,
RecursionProvider,
useHasRecursion,
InnerBlocks,
useBlockProps,
Warning,
privateApis as blockEditorPrivateApis,
store as blockEditorStore,
BlockControls,
} from '@wordpress/block-editor';
import { privateApis as patternsPrivateApis } from '@wordpress/patterns';
import { parse, cloneBlock } from '@wordpress/blocks';
/**
* Internal dependencies
*/
import { unlock } from '../lock-unlock';
const { useLayoutClasses } = unlock( blockEditorPrivateApis );
const { PARTIAL_SYNCING_SUPPORTED_BLOCKS } = unlock( patternsPrivateApis );
function isPartiallySynced( block ) {
return (
Object.keys( PARTIAL_SYNCING_SUPPORTED_BLOCKS ).includes(
block.name
) &&
!! block.attributes.metadata?.bindings &&
Object.values( block.attributes.metadata.bindings ).some(
( binding ) => binding.source === 'core/pattern-overrides'
)
);
}
function getPartiallySyncedAttributes( block ) {
return Object.entries( block.attributes.metadata.bindings )
.filter(
( [ , binding ] ) => binding.source === 'core/pattern-overrides'
)
.map( ( [ attributeKey ] ) => attributeKey );
}
const fullAlignments = [ 'full', 'wide', 'left', 'right' ];
const useInferredLayout = ( blocks, parentLayout ) => {
const initialInferredAlignmentRef = useRef();
return useMemo( () => {
// Exit early if the pattern's blocks haven't loaded yet.
if ( ! blocks?.length ) {
return {};
}
let alignment = initialInferredAlignmentRef.current;
// Only track the initial alignment so that temporarily removed
// alignments can be reapplied.
if ( alignment === undefined ) {
const isConstrained = parentLayout?.type === 'constrained';
const hasFullAlignment = blocks.some( ( block ) =>
fullAlignments.includes( block.attributes.align )
);
alignment = isConstrained && hasFullAlignment ? 'full' : null;
initialInferredAlignmentRef.current = alignment;
}
const layout = alignment ? parentLayout : undefined;
return { alignment, layout };
}, [ blocks, parentLayout ] );
};
/**
* Enum for patch operations.
* We use integers here to minimize the size of the serialized data.
* This has to be deserialized accordingly on the server side.
* See block-bindings/sources/pattern.php
*/
const PATCH_OPERATIONS = {
/** @type {0} */
Remove: 0,
/** @type {1} */
Replace: 1,
// Other operations are reserved for future use. (e.g. Add)
};
/**
* @typedef {[typeof PATCH_OPERATIONS.Remove]} RemovePatch
* @typedef {[typeof PATCH_OPERATIONS.Replace, unknown]} ReplacePatch
* @typedef {RemovePatch | ReplacePatch} OverridePatch
*/
function applyInitialOverrides( blocks, overrides = {}, defaultValues ) {
return blocks.map( ( block ) => {
const innerBlocks = applyInitialOverrides(
block.innerBlocks,
overrides,
defaultValues
);
const blockId = block.attributes.metadata?.id;
if ( ! isPartiallySynced( block ) || ! blockId )
return { ...block, innerBlocks };
const attributes = getPartiallySyncedAttributes( block );
const newAttributes = { ...block.attributes };
for ( const attributeKey of attributes ) {
defaultValues[ blockId ] ??= {};
defaultValues[ blockId ][ attributeKey ] =
block.attributes[ attributeKey ];
/** @type {OverridePatch} */
const overrideAttribute = overrides[ blockId ]?.[ attributeKey ];
if ( ! overrideAttribute ) {
continue;
}
if ( overrideAttribute[ 0 ] === PATCH_OPERATIONS.Remove ) {
delete newAttributes[ attributeKey ];
} else if ( overrideAttribute[ 0 ] === PATCH_OPERATIONS.Replace ) {
newAttributes[ attributeKey ] = overrideAttribute[ 1 ];
}
}
return {
...block,
attributes: newAttributes,
innerBlocks,
};
} );
}
function getOverridesFromBlocks( blocks, defaultValues ) {
/** @type {Record<string, Record<string, OverridePatch>>} */
const overrides = {};
for ( const block of blocks ) {
Object.assign(
overrides,
getOverridesFromBlocks( block.innerBlocks, defaultValues )
);
/** @type {string} */
const blockId = block.attributes.metadata?.id;
if ( ! isPartiallySynced( block ) || ! blockId ) continue;
const attributes = getPartiallySyncedAttributes( block );
for ( const attributeKey of attributes ) {
if (
block.attributes[ attributeKey ] !==
defaultValues[ blockId ][ attributeKey ]
) {
overrides[ blockId ] ??= {};
/**
* Create a patch operation for the binding attribute.
* We use a tuple here to minimize the size of the serialized data.
* The first item is the operation type, the second item is the value if any.
*/
if ( block.attributes[ attributeKey ] === undefined ) {
/** @type {RemovePatch} */
overrides[ blockId ][ attributeKey ] = [
PATCH_OPERATIONS.Remove,
];
} else {
/** @type {ReplacePatch} */
overrides[ blockId ][ attributeKey ] = [
PATCH_OPERATIONS.Replace,
block.attributes[ attributeKey ],
];
}
}
}
}
return Object.keys( overrides ).length > 0 ? overrides : undefined;
}
function setBlockEditMode( setEditMode, blocks, mode ) {
blocks.forEach( ( block ) => {
const editMode =
mode || ( isPartiallySynced( block ) ? 'contentOnly' : 'disabled' );
setEditMode( block.clientId, editMode );
setBlockEditMode( setEditMode, block.innerBlocks, mode );
} );
}
function getHasOverridableBlocks( blocks ) {
return blocks.some( ( block ) => {
if ( isPartiallySynced( block ) ) return true;
return getHasOverridableBlocks( block.innerBlocks );
} );
}
export default function ReusableBlockEdit( {
name,
attributes: { ref, overrides },
__unstableParentLayout: parentLayout,
clientId: patternClientId,
setAttributes,
} ) {
const registry = useRegistry();
const hasAlreadyRendered = useHasRecursion( ref );
const { record, editedRecord, hasResolved } = useEntityRecord(
'postType',
'wp_block',
ref
);
const isMissing = hasResolved && ! record;
const initialOverrides = useRef( overrides );
const defaultValuesRef = useRef( {} );
const {
replaceInnerBlocks,
__unstableMarkNextChangeAsNotPersistent,
setBlockEditingMode,
} = useDispatch( blockEditorStore );
const { syncDerivedUpdates } = unlock( useDispatch( blockEditorStore ) );
const { innerBlocks, userCanEdit, getBlockEditingMode, getPostLinkProps } =
useSelect(
( select ) => {
const { canUser } = select( coreStore );
const {
getBlocks,
getBlockEditingMode: editingMode,
getSettings,
} = select( blockEditorStore );
const blocks = getBlocks( patternClientId );
const canEdit = canUser( 'update', 'blocks', ref );
// For editing link to the site editor if the theme and user permissions support it.
return {
innerBlocks: blocks,
userCanEdit: canEdit,
getBlockEditingMode: editingMode,
getPostLinkProps: getSettings().getPostLinkProps,
};
},
[ patternClientId, ref ]
);
const editOriginalProps = getPostLinkProps
? getPostLinkProps( {
postId: ref,
postType: 'wp_block',
} )
: {};
useEffect(
() => setBlockEditMode( setBlockEditingMode, innerBlocks ),
[ innerBlocks, setBlockEditingMode ]
);
const hasOverridableBlocks = useMemo(
() => getHasOverridableBlocks( innerBlocks ),
[ innerBlocks ]
);
const initialBlocks = useMemo(
() =>
// Clone the blocks to generate new client IDs.
editedRecord.blocks?.map( ( block ) => cloneBlock( block ) ) ??
( editedRecord.content && typeof editedRecord.content !== 'function'
? parse( editedRecord.content )
: [] ),
[ editedRecord.blocks, editedRecord.content ]
);
// Apply the initial overrides from the pattern block to the inner blocks.
useEffect( () => {
defaultValuesRef.current = {};
const editingMode = getBlockEditingMode( patternClientId );
// Replace the contents of the blocks with the overrides.
registry.batch( () => {
setBlockEditingMode( patternClientId, 'default' );
syncDerivedUpdates( () => {
replaceInnerBlocks(
patternClientId,
applyInitialOverrides(
initialBlocks,
initialOverrides.current,
defaultValuesRef.current
)
);
} );
setBlockEditingMode( patternClientId, editingMode );
} );
}, [
__unstableMarkNextChangeAsNotPersistent,
patternClientId,
initialBlocks,
replaceInnerBlocks,
registry,
getBlockEditingMode,
setBlockEditingMode,
syncDerivedUpdates,
] );
const { alignment, layout } = useInferredLayout(
innerBlocks,
parentLayout
);
const layoutClasses = useLayoutClasses( { layout }, name );
const blockProps = useBlockProps( {
className: classnames(
'block-library-block__reusable-block-container',
layout && layoutClasses,
{ [ `align${ alignment }` ]: alignment }
),
} );
const innerBlocksProps = useInnerBlocksProps( blockProps, {
templateLock: 'all',
layout,
renderAppender: innerBlocks?.length
? undefined
: InnerBlocks.ButtonBlockAppender,
} );
// Sync the `overrides` attribute from the updated blocks to the pattern block.
// `syncDerivedUpdates` is used here to avoid creating an additional undo level.
useEffect( () => {
const { getBlocks } = registry.select( blockEditorStore );
let prevBlocks = getBlocks( patternClientId );
return registry.subscribe( () => {
const blocks = getBlocks( patternClientId );
if ( blocks !== prevBlocks ) {
prevBlocks = blocks;
syncDerivedUpdates( () => {
setAttributes( {
overrides: getOverridesFromBlocks(
blocks,
defaultValuesRef.current
),
} );
} );
}
}, blockEditorStore );
}, [ syncDerivedUpdates, patternClientId, registry, setAttributes ] );
const handleEditOriginal = ( event ) => {
setBlockEditMode( setBlockEditingMode, innerBlocks, 'default' );
editOriginalProps.onClick( event );
};
const resetOverrides = () => {
if ( overrides ) {
replaceInnerBlocks( patternClientId, initialBlocks );
}
};
let children = null;
if ( hasAlreadyRendered ) {
children = (
<Warning>
{ __( 'Block cannot be rendered inside itself.' ) }
</Warning>
);
}
if ( isMissing ) {
children = (
<Warning>
{ __( 'Block has been deleted or is unavailable.' ) }
</Warning>
);
}
if ( ! hasResolved ) {
children = (
<Placeholder>
<Spinner />
</Placeholder>
);
}
return (
<RecursionProvider uniqueId={ ref }>
{ userCanEdit && editOriginalProps && (
<BlockControls>
<ToolbarGroup>
<ToolbarButton
href={ editOriginalProps.href }
onClick={ handleEditOriginal }
>
{ __( 'Edit original' ) }
</ToolbarButton>
</ToolbarGroup>
</BlockControls>
) }
{ hasOverridableBlocks && (
<BlockControls>
<ToolbarGroup>
<ToolbarButton
onClick={ resetOverrides }
disabled={ ! overrides }
__experimentalIsFocusable
>
{ __( 'Reset' ) }
</ToolbarButton>
</ToolbarGroup>
</BlockControls>
) }
{ children === null ? (
<div { ...innerBlocksProps } />
) : (
<div { ...blockProps }>{ children }</div>
) }
</RecursionProvider>
);
}