-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
factory.js
399 lines (350 loc) · 11.8 KB
/
factory.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
/**
* External dependencies
*/
import uuid from 'uuid/v4';
import {
every,
reduce,
castArray,
findIndex,
isObjectLike,
filter,
first,
flatMap,
uniq,
isFunction,
isEmpty,
} from 'lodash';
/**
* WordPress dependencies
*/
import { createHooks, applyFilters } from '@wordpress/hooks';
/**
* Internal dependencies
*/
import { getBlockType, getBlockTypes } from './registration';
import { normalizeBlockType } from './utils';
/**
* Returns a block object given its type and attributes.
*
* @param {string} name Block name.
* @param {Object} attributes Block attributes.
* @param {?Array} innerBlocks Nested blocks.
*
* @return {Object} Block object.
*/
export function createBlock( name, attributes = {}, innerBlocks = [] ) {
// Get the type definition associated with a registered block.
const blockType = getBlockType( name );
// Ensure attributes contains only values defined by block type, and merge
// default values for missing attributes.
const sanitizedAttributes = reduce( blockType.attributes, ( result, schema, key ) => {
const value = attributes[ key ];
if ( undefined !== value ) {
result[ key ] = value;
} else if ( schema.hasOwnProperty( 'default' ) ) {
result[ key ] = schema.default;
}
if ( [ 'node', 'children' ].indexOf( schema.source ) !== -1 ) {
// Ensure value passed is always an array, which we're expecting in
// the RichText component to handle the deprecated value.
if ( typeof result[ key ] === 'string' ) {
result[ key ] = [ result[ key ] ];
} else if ( ! Array.isArray( result[ key ] ) ) {
result[ key ] = [];
}
}
return result;
}, {} );
const clientId = uuid();
// Blocks are stored with a unique ID, the assigned type name, the block
// attributes, and their inner blocks.
return {
clientId,
name,
isValid: true,
attributes: sanitizedAttributes,
innerBlocks,
};
}
/**
* Given a block object, returns a copy of the block object, optionally merging
* new attributes and/or replacing its inner blocks.
*
* @param {Object} block Block instance.
* @param {Object} mergeAttributes Block attributes.
* @param {?Array} newInnerBlocks Nested blocks.
*
* @return {Object} A cloned block.
*/
export function cloneBlock( block, mergeAttributes = {}, newInnerBlocks ) {
const clientId = uuid();
return {
...block,
clientId,
attributes: {
...block.attributes,
...mergeAttributes,
},
innerBlocks: newInnerBlocks ||
block.innerBlocks.map( ( innerBlock ) => cloneBlock( innerBlock ) ),
};
}
/**
* Returns a boolean indicating whether a transform is possible based on
* various bits of context.
*
* @param {Object} transform The transform object to validate.
* @param {string} direction Is this a 'from' or 'to' transform.
* @param {Array} blocks The blocks to transform from.
*
* @return {boolean} Is the transform possible?
*/
const isPossibleTransformForSource = ( transform, direction, blocks ) => {
if ( isEmpty( blocks ) ) {
return false;
}
// If multiple blocks are selected, only multi block transforms are allowed.
const isMultiBlock = blocks.length > 1;
const isValidForMultiBlocks = ! isMultiBlock || transform.isMultiBlock;
if ( ! isValidForMultiBlocks ) {
return false;
}
// Only consider 'block' type transforms as valid.
const isBlockType = transform.type === 'block';
if ( ! isBlockType ) {
return false;
}
// Check if the transform's block name matches the source block only if this is a transform 'from'.
const sourceBlock = first( blocks );
const hasMatchingName = direction !== 'from' || transform.blocks.indexOf( sourceBlock.name ) !== -1;
if ( ! hasMatchingName ) {
return false;
}
// If the transform has a `isMatch` function specified, check that it returns true.
if ( isFunction( transform.isMatch ) ) {
const attributes = transform.isMultiBlock ? blocks.map( ( block ) => block.attributes ) : sourceBlock.attributes;
if ( ! transform.isMatch( attributes ) ) {
return false;
}
}
return true;
};
/**
* Returns block types that the 'blocks' can be transformed into, based on
* 'from' transforms on other blocks.
*
* @param {Array} blocks The blocks to transform from.
*
* @return {Array} Block types that the blocks can be transformed into.
*/
const getBlockTypesForPossibleFromTransforms = ( blocks ) => {
if ( isEmpty( blocks ) ) {
return [];
}
const allBlockTypes = getBlockTypes();
// filter all blocks to find those with a 'from' transform.
const blockTypesWithPossibleFromTransforms = filter(
allBlockTypes,
( blockType ) => {
const fromTransforms = getBlockTransforms( 'from', blockType.name );
return !! findTransform(
fromTransforms,
( transform ) => isPossibleTransformForSource( transform, 'from', blocks )
);
},
);
return blockTypesWithPossibleFromTransforms;
};
/**
* Returns block types that the 'blocks' can be transformed into, based on
* the source block's own 'to' transforms.
*
* @param {Array} blocks The blocks to transform from.
*
* @return {Array} Block types that the source can be transformed into.
*/
const getBlockTypesForPossibleToTransforms = ( blocks ) => {
if ( isEmpty( blocks ) ) {
return [];
}
const sourceBlock = first( blocks );
const blockType = getBlockType( sourceBlock.name );
const transformsTo = getBlockTransforms( 'to', blockType.name );
// filter all 'to' transforms to find those that are possible.
const possibleTransforms = filter(
transformsTo,
( transform ) => isPossibleTransformForSource( transform, 'to', blocks )
);
// Build a list of block names using the possible 'to' transforms.
const blockNames = flatMap(
possibleTransforms,
( transformation ) => transformation.blocks
);
// Map block names to block types.
return blockNames.map( ( name ) => getBlockType( name ) );
};
/**
* Returns an array of block types that the set of blocks received as argument
* can be transformed into.
*
* @param {Array} blocks Blocks array.
*
* @return {Array} Block types that the blocks argument can be transformed to.
*/
export function getPossibleBlockTransformations( blocks ) {
if ( isEmpty( blocks ) ) {
return [];
}
const sourceBlock = first( blocks );
const isMultiBlock = blocks.length > 1;
if ( isMultiBlock && ! every( blocks, { name: sourceBlock.name } ) ) {
return [];
}
const blockTypesForFromTransforms = getBlockTypesForPossibleFromTransforms( blocks );
const blockTypesForToTransforms = getBlockTypesForPossibleToTransforms( blocks );
return uniq( [
...blockTypesForFromTransforms,
...blockTypesForToTransforms,
] );
}
/**
* Given an array of transforms, returns the highest-priority transform where
* the predicate function returns a truthy value. A higher-priority transform
* is one with a lower priority value (i.e. first in priority order). Returns
* null if the transforms set is empty or the predicate function returns a
* falsey value for all entries.
*
* @param {Object[]} transforms Transforms to search.
* @param {Function} predicate Function returning true on matching transform.
*
* @return {?Object} Highest-priority transform candidate.
*/
export function findTransform( transforms, predicate ) {
// The hooks library already has built-in mechanisms for managing priority
// queue, so leverage via locally-defined instance.
const hooks = createHooks();
for ( let i = 0; i < transforms.length; i++ ) {
const candidate = transforms[ i ];
if ( predicate( candidate ) ) {
hooks.addFilter(
'transform',
'transform/' + i.toString(),
( result ) => result ? result : candidate,
candidate.priority
);
}
}
// Filter name is arbitrarily chosen but consistent with above aggregation.
return hooks.applyFilters( 'transform', null );
}
/**
* Returns normal block transforms for a given transform direction, optionally
* for a specific block by name, or an empty array if there are no transforms.
* If no block name is provided, returns transforms for all blocks. A normal
* transform object includes `blockName` as a property.
*
* @param {string} direction Transform direction ("to", "from").
* @param {string|Object} blockTypeOrName Block type or name.
*
* @return {Array} Block transforms for direction.
*/
export function getBlockTransforms( direction, blockTypeOrName ) {
// When retrieving transforms for all block types, recurse into self.
if ( blockTypeOrName === undefined ) {
return flatMap(
getBlockTypes(),
( { name } ) => getBlockTransforms( direction, name )
);
}
// Validate that block type exists and has array of direction.
const blockType = normalizeBlockType( blockTypeOrName );
const { name: blockName, transforms } = blockType || {};
if ( ! transforms || ! Array.isArray( transforms[ direction ] ) ) {
return [];
}
// Map transforms to normal form.
return transforms[ direction ].map( ( transform ) => ( {
...transform,
blockName,
} ) );
}
/**
* Switch one or more blocks into one or more blocks of the new block type.
*
* @param {Array|Object} blocks Blocks array or block object.
* @param {string} name Block name.
*
* @return {Array} Array of blocks.
*/
export function switchToBlockType( blocks, name ) {
const blocksArray = castArray( blocks );
const isMultiBlock = blocksArray.length > 1;
const firstBlock = blocksArray[ 0 ];
const sourceName = firstBlock.name;
if ( isMultiBlock && ! every( blocksArray, ( block ) => ( block.name === sourceName ) ) ) {
return null;
}
// Find the right transformation by giving priority to the "to"
// transformation.
const transformationsFrom = getBlockTransforms( 'from', name );
const transformationsTo = getBlockTransforms( 'to', sourceName );
const transformation =
findTransform(
transformationsTo,
( t ) => t.type === 'block' && t.blocks.indexOf( name ) !== -1 && ( ! isMultiBlock || t.isMultiBlock )
) ||
findTransform(
transformationsFrom,
( t ) => t.type === 'block' && t.blocks.indexOf( sourceName ) !== -1 && ( ! isMultiBlock || t.isMultiBlock )
);
// Stop if there is no valid transformation.
if ( ! transformation ) {
return null;
}
let transformationResults;
if ( transformation.isMultiBlock ) {
transformationResults = transformation.transform(
blocksArray.map( ( currentBlock ) => currentBlock.attributes ),
blocksArray.map( ( currentBlock ) => currentBlock.innerBlocks )
);
} else {
transformationResults = transformation.transform( firstBlock.attributes, firstBlock.innerBlocks );
}
// Ensure that the transformation function returned an object or an array
// of objects.
if ( ! isObjectLike( transformationResults ) ) {
return null;
}
// If the transformation function returned a single object, we want to work
// with an array instead.
transformationResults = castArray( transformationResults );
// Ensure that every block object returned by the transformation has a
// valid block type.
if ( transformationResults.some( ( result ) => ! getBlockType( result.name ) ) ) {
return null;
}
const firstSwitchedBlock = findIndex( transformationResults, ( result ) => result.name === name );
// Ensure that at least one block object returned by the transformation has
// the expected "destination" block type.
if ( firstSwitchedBlock < 0 ) {
return null;
}
return transformationResults.map( ( result, index ) => {
const transformedBlock = {
...result,
// The first transformed block whose type matches the "destination"
// type gets to keep the existing client ID of the first block.
clientId: index === firstSwitchedBlock ? firstBlock.clientId : result.clientId,
};
/**
* Filters an individual transform result from block transformation.
* All of the original blocks are passed, since transformations are
* many-to-many, not one-to-one.
*
* @param {Object} transformedBlock The transformed block.
* @param {Object[]} blocks Original blocks transformed.
*/
return applyFilters( 'blocks.switchToBlockType.transformedBlock', transformedBlock, blocks );
} );
}