-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathblocks.js
More file actions
629 lines (560 loc) · 18.5 KB
/
blocks.js
File metadata and controls
629 lines (560 loc) · 18.5 KB
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
/**
* Internal dependncies
*/
import { loadGoogleFontInAttributes } from './font'
import { moveArrayIndex } from '.'
import { SVGStackableCategoryIcon } from '~stackable/icons'
/**
* External dependencies
*/
import {
omit,
orderBy,
last,
isEqual,
cloneDeep,
} from 'lodash'
import {
blockCategoryIndex,
i18n,
settings as stackableSettings,
} from 'stackable'
/**
* WordPress dependencies
*/
import { applyFilters } from '@wordpress/hooks'
import {
createBlock,
createBlocksFromInnerBlocksTemplate,
getCategories,
setCategories,
registerBlockType as _registerBlockType,
} from '@wordpress/blocks'
import {
dispatch, select, useSelect,
} from '@wordpress/data'
import { useMemo } from '@wordpress/element'
import { BlockIcon } from '@wordpress/block-editor'
import { __ } from '@wordpress/i18n'
export const STACKABLE_FILTERS = {
'stackable/card-group': [],
'stackable/card': [ 'imageUrl', 'imageId', 'imageAlt' ],
'stackable/button-group': [],
'stackable/button': [ 'text', 'icon', 'linkHasLink', 'linkUrl', 'linkNewTab', 'linkRel', 'linkHasTitle', 'linkTitle' ],
'stackable/text': [ 'text' ],
'stackable/subtitle': [ 'text' ],
'stackable/heading': [ 'text' ],
'stackable/number-box': [ 'text' ],
'stackable/image': [ 'imageUrl', 'imageId', 'imageAlt' ],
'stackable/icon': [ 'icon' ],
'stackable/icon-button': [ 'icon', 'linkHasLink', 'linkUrl', 'linkNewTab', 'linkRel', 'linkHasTitle', 'linkTitle' ],
'stackable/icon-list': [ 'icon', 'text' ],
'stackable/icon-list-item': [ 'text' ],
'stackable/progress-bar': [ 'text', 'progressValue', 'progressValuePrefix', 'progressValueSuffix', 'progressInnerText', 'progressMax' ],
'stackable/progress-circle': [ 'progressValue', 'progressValuePrefix', 'progressValueSuffix', 'progressMax' ],
'stackable/countdown': [ 'countdownType', 'date', 'restartInterval', 'actionOnExpiration', 'timezone', 'dayText', 'hourText', 'minuteText', 'secondText', 'daysLeft', 'hoursLeft', 'minutesLeft', 'secondsLeft', 'messageText' ],
'stackable/tab-labels': [ 'tabLabels' ],
'stackable/timeline': [ 'text' ],
}
/**
* Enum for disabling and hiding blocks.
*/
export const BLOCK_STATE = Object.freeze( {
ENABLED: 1,
HIDDEN: 2,
DISABLED: 3,
} )
/**
* Converts the registered block name into a block name string that can be used in hook names or ids.
*
* @param {string} name The block name
*/
export const getBlockName = name => {
return name.replace( /\//g, '-' )
}
const ignoreAttributes = [
'uniqueClass',
]
// DEPRECATED: Not used anymore since calls to this can be pretty expensive.
// Checks whether a block is modified or not.
const cachedDefaultAttributes = {}
export function isUnmodifiedBlock( block ) {
if ( ! cachedDefaultAttributes[ block.name ] ) {
cachedDefaultAttributes[ block.name ] = createBlock( block.name ).attributes
}
return Object.keys( cachedDefaultAttributes[ block.name ] ).every( attrName => {
if ( ignoreAttributes.includes( attrName ) ) {
return true
}
return cachedDefaultAttributes[ block.name ][ attrName ] === block.attributes[ attrName ]
} )
}
export const applyBlockDesign = ( attributes, clientId = null ) => {
const {
getBlockName, getSelectedBlockClientId, getBlockAttributes, hasMultiSelection, getMultiSelectedBlockClientIds,
} = select( 'core/block-editor' )
const { updateBlockAttributes } = dispatch( 'core/block-editor' )
const { getBlockType } = select( 'core/blocks' )
// If multiple blocks are selected, apply the block design to them all.
if ( ! clientId && hasMultiSelection() ) {
getMultiSelectedBlockClientIds().forEach( clientId => {
applyBlockDesign( attributes, clientId )
} )
return
}
const blockClientId = clientId ? clientId : getSelectedBlockClientId()
if ( ! blockClientId ) {
return
}
const currentBlockAttributes = getBlockAttributes( blockClientId )
const blockName = getBlockName( blockClientId ).replace( /^\w+\//g, '' )
const attributeDefinition = getBlockType( getBlockName( blockClientId ) ).attributes
const defaultAttributes = Object.keys( attributeDefinition ).reduce( ( attrs, attrName ) => {
return {
...attrs,
[ attrName ]: attributeDefinition[ attrName ] ? attributeDefinition[ attrName ].default : '',
}
}, {} )
// Omit the attributes which should not be overridden, for example: urls,
// media ids, open in new tabs, etc.
const blockAttributesFiltered = applyFilters( `stackable.${ blockName }.design.filtered-block-attributes`, { ...defaultAttributes, ...attributes }, currentBlockAttributes )
// When applying attributes to a block, we assume that there's already text
// inputted in the block, so we shouldn't apply all the text attributes of
// the design.
const blockAttributes = applyFilters( `stackable.${ blockName }.design.no-text-attributes`, blockAttributesFiltered, currentBlockAttributes )
// Check for any Fonts that we need to load.
loadGoogleFontInAttributes( blockAttributes )
updateBlockAttributes( blockClientId, omit( blockAttributes, [ 'uniqueClass' ] ) ) // eslint-disable-line stackable/no-update-block-attributes
}
/**
* Moves an innerBlock to a new index.
*
* @param {string} clientId The block to modify
* @param {number} fromIndex innerBlock old index
* @param {number} toIndex innerBlock new index
*/
export const moveInnerBlock = ( clientId, fromIndex, toIndex ) => {
const { getBlock } = select( 'core/block-editor' )
const { replaceInnerBlocks } = dispatch( 'core/block-editor' )
const currentBlock = getBlock( clientId )
const newInnerBlocks = moveArrayIndex( currentBlock.innerBlocks, fromIndex, toIndex )
replaceInnerBlocks( clientId, newInnerBlocks, false )
}
const SHOWN_BLOCK_TYPES = 9
/**
* When adding a stackable block, typing
* '/' can now trigger the block appender dropdown.
*
* This function generates a `autocompleters` object which will
* be passed iniside the block editor's `AutoComplete` component.
*
* We can then access the `editor.Autocomplete.completers` filter to
* add these options.
*
* @since 3.0.0
*
* @see https://github.com/WordPress/gutenberg/blob/3da717b8d0ac7d7821fc6d0475695ccf3ae2829f/packages/block-editor/src/components/autocomplete/index.js
* @see https://github.com/WordPress/gutenberg/blob/3da717b8d0ac7d7821fc6d0475695ccf3ae2829f/packages/block-editor/src/autocompleters/block.js
*/
export const createBlockCompleter = () => {
return {
name: 'blocks',
className: 'block-editor-autocompleters__block',
triggerPrefix: '/',
useItems( filterValue ) {
const { rootClientId, selectedBlockName } = useSelect(
select => {
const {
getSelectedBlockClientId,
getBlockName,
getBlockInsertionPoint,
} = select( 'core/block-editor' )
const selectedBlockClientId = getSelectedBlockClientId()
return {
selectedBlockName: selectedBlockClientId
? getBlockName( selectedBlockClientId )
: null,
rootClientId: getBlockInsertionPoint().rootClientId,
}
},
[]
)
const {
categories, collections, items,
} = useSelect(
select => {
const { getInserterItems } = select( 'core/block-editor' )
const { getCategories, getCollections } = select( 'core/blocks' )
return {
categories: getCategories(),
collections: getCollections(),
items: getInserterItems( rootClientId ),
}
},
[ rootClientId ]
)
const filteredItems = useMemo( () => {
let initialFilteredItems = orderBy( items, [ 'frecency' ], [ 'desc' ] )
// Only include stackable and ugb blocks.
// initialFilteredItems = initialFilteredItems
// .filter( item => item.name !== selectedBlockName )
// .filter( item => item.name.startsWith( 'stackable/' ) || item.name.startsWith( 'ugb/' ) )
// Filter based on keyword.
initialFilteredItems = initialFilteredItems
.filter( item => item.name.toLowerCase().includes( filterValue?.toLowerCase() ) || item.title.toLowerCase().includes( filterValue?.toLowerCase() ) )
// Only show certain number of items.
return initialFilteredItems
.slice( 0, SHOWN_BLOCK_TYPES )
}, [
filterValue,
selectedBlockName,
items,
categories,
collections,
] )
const options = useMemo(
() =>
filteredItems.map( blockItem => {
const {
title, icon, isDisabled,
} = blockItem
return {
key: `block-${ blockItem.id }`,
value: blockItem,
label: (
<>
<BlockIcon
key="icon"
icon={ icon }
showColors
/>
{ title }
</>
),
isDisabled,
}
} ),
[ filteredItems ]
)
return [ options ]
},
allowContext( before, after ) {
return ! ( /\S/.test( before ) || /\S/.test( after ) )
},
getOptionCompletion( inserterItem ) {
const {
name, initialAttributes, innerBlocks,
} = inserterItem
return {
action: 'replace',
value: createBlock(
name,
initialAttributes,
createBlocksFromInnerBlocksTemplate( innerBlocks )
),
}
},
}
}
/**
* Generates a structure object based on the clientId (up to the parent clientId).
* Used by Block Linking.
*
* A structure object looks like this:
* [
* {
* type: 'stackable/card',
* },
* {
* type: 'stackable/columns',
* nthOfType: 1,
* numOfType: 1,
* },
* {
* type: 'stackable/column',
* nthOfType: 1,
* numOfType: 2,
* },
* {
* type: 'stackable/heading',
* nthOfType: 1,
* numOfType: 1,
* attributes: {
* color: red,
* },
* }
* ]
*
* @param {string} clientId The main block
* @param {string} rootClientId The root parent block
*/
export const extractBlockStyleStructure = ( clientId, rootClientId ) => {
let currentClientId = clientId
const structureArray = []
while ( currentClientId !== null ) {
const { getBlock, getBlockParents } = select( 'core/block-editor' )
const block = getBlock( currentClientId )
const currentBlockName = block.name
const parentClientId = last( getBlockParents( currentClientId ) ) // eslint-disable-line stackable/no-get-block-parents
if ( ! parentClientId || parentClientId === currentClientId ) {
structureArray.unshift( {
type: block.name,
nthOfType: 1,
numOfType: 1,
} )
break
}
// Get nthOfType and numOfType
const childBlocks = getBlock( parentClientId ).innerBlocks
const { nthOfType, numOfType } = childBlocks.reduce( ( blockData, { name, clientId } ) => {
if ( name === currentBlockName ) {
blockData.numOfType++
if ( ! blockData.foundClientId ) {
blockData.nthOfType++
if ( clientId === currentClientId ) {
blockData.foundClientId = true
}
}
}
return blockData
}, {
nthOfType: 0, numOfType: 0, foundClientId: false,
} )
structureArray.unshift( {
type: block.name,
nthOfType,
numOfType,
} )
// Go back one parent.
if ( currentClientId === rootClientId ) {
currentClientId = null
} else {
currentClientId = last( select( 'core/block-editor' ).getBlockParents( currentClientId ) ) // eslint-disable-line stackable/no-get-block-parents
}
}
return structureArray
}
/**
* Gets the list of blocks which the styleStructure is applicable to.
*
* This method tries to match/paste to a block and its nested contents.
*
* The styleStructure explains the attributes to be applied, the styles can be
* applied to multiple nested blocks. Here's an example styleStructure:
*
* [
* {
* type: 'stackable/card',
* },
* {
* type: 'stackable/columns',
* nthOfType: 1,
* numOfType: 1,
* },
* {
* type: 'stackable/column',
* nthOfType: 1,
* numOfType: 2,
* },
* {
* type: 'stackable/heading',
* nthOfType: 1,
* numOfType: 1,
* attributes: {
* color: red,
* },
* }
* ]
*
* @param {number} clientId The block to apply the styles to
* @param {Object} styleStructure An object explaining the style/attributes to
* apply
*
* @return {Array} Array of block client Ids which the styleStructure should be
* applied to.
*/
export const getBlocksToStyle = ( clientId, styleStructure ) => {
const clientIds = []
if ( ! styleStructure.length ) {
return clientIds
}
// Don't match the type of the very first entry since it's the main one.
styleStructure[ 0 ].nthOfType = 1
styleStructure[ 0 ].numOfType = 1
let currentBlocks = [ select( 'core/block-editor' ).getBlock( clientId ) ]
styleStructure.forEach( ( currentStructure, i ) => {
const matchingBlocks = currentBlocks.filter( block => {
if ( currentStructure.type !== block.name ) {
return false
}
// The first block should always match.
if ( i === 0 ) {
return true
}
// Match if it's the same child type.
const nthOfType = getNthTypeOfBlock( block.clientId )
if ( nthOfType === currentStructure.nthOfType ) {
return true
}
const lastInStructure = currentStructure.nthOfType === currentStructure.numOfType
if ( lastInStructure && nthOfType > currentStructure.nthOfType && nthOfType >= currentStructure.numOfType ) {
return true
}
return false
} )
// All the client Id for updating.
if ( currentStructure.attributes ) {
matchingBlocks.forEach( ( { clientId } ) => {
clientIds.push( clientId )
} )
}
// Go through the next level of inner blocks.
currentBlocks = matchingBlocks.reduce( ( allInnerBlocks, matchingBlock ) => {
return [
...allInnerBlocks,
...matchingBlock.innerBlocks,
]
}, [] )
} )
return clientIds
}
const getNthTypeOfBlock = currentClientId => {
const { getBlock, getBlockParents } = select( 'core/block-editor' )
const block = getBlock( currentClientId )
const currentBlockName = block.name
const parentClientId = last( getBlockParents( currentClientId ) ) // eslint-disable-line stackable/no-get-block-parents
if ( ! parentClientId || parentClientId === currentClientId ) {
return 1
}
// Get nthOfType and numOfType
const childBlocks = getBlock( parentClientId ).innerBlocks
let nthOfType = 0
childBlocks.some( ( { name, clientId } ) => {
if ( name === currentBlockName ) {
nthOfType++
return clientId === currentClientId
}
return false
} )
return nthOfType
}
// Register our block category. Not a collection since our blocks would appear
// as "Uncategorized"
export const addStackableBlockCategory = () => {
if ( ! getCategories().some( category => category.slug === 'stackable' ) ) {
const stackableCategory = {
slug: 'stackable',
title: __( 'Stackable', i18n ),
icon: SVGStackableCategoryIcon,
}
const categoryIndex = blockCategoryIndex || 0
// Add our category based on the categoryIndex
const newCategories = [ ...getCategories() ]
newCategories.splice( categoryIndex, 0, stackableCategory )
setCategories( newCategories )
}
}
/**
* Registers a block. Use this instead of the registerBlockType found in @wordpress/blocks
*
* @param {string} name The namespaced name of the block
* @param {Object} _settings The block properties to register
*/
export const registerBlockType = ( name, _settings ) => {
let settings = applyFilters( `stackable.block.metadata`, _settings || {} )
// If there is no variation title, then some labels in the editor will show
// up as "undefined", add a default title for all variations.
if ( settings.variations ) {
settings.variations.forEach( variation => {
if ( ! variation.title ) {
variation.title = settings.title
}
} )
}
// Workaround to remove the .wp-block[data-align] div wrapper for wide and full
// width alignments. Since we removed this, we add our own data-align attribute
// in the BlockWrapper in src/components/block-wrapper (this is used by all our
// blocks)
settings.getEditWrapperProps = () => {
return {
'data-align': undefined,
}
}
// Add HOCs here that are present for all our blocks.
settings.edit = applyFilters( 'stackable.registerBlockType.edit', settings.edit )
settings = applyFilters( `stackable.${ name.replace( 'stackable/', '' ) }.settings`, settings )
_registerBlockType( name, settings )
}
/**
* Substitutes a stackable block with an equivalent core block if the block is disabled.
*
* @param {string} blockName The block name
* @param {Object} blockAttributes The block attributes
* @param {Array} innerBlocks The children blocks
* @param {Object} substitutionRules The substitution rules for transforming from stackable to core blocks
*
* @return {Array} The resulting block definition
*/
export const substituteCoreIfDisabled = ( blockName, blockAttributes, innerBlocks, substitutionRules ) => {
const disabledBlocks = stackableSettings.stackable_block_states || {} // eslint-disable-line camelcase
if ( substitutionRules && blockName in substitutionRules ) {
const substitutionRule = substitutionRules[ blockName ]
// If a block have variants, let the the transform handle checking for disabled
if ( 'variants' in substitutionRule ) {
return substitutionRule.transform( blockAttributes, innerBlocks, disabledBlocks )
}
if ( blockName in disabledBlocks && disabledBlocks[ blockName ] === BLOCK_STATE.DISABLED ) { // eslint-disable-line camelcase
return substitutionRule.transform( blockAttributes, innerBlocks )
}
}
if ( innerBlocks ) {
return [ blockName, blockAttributes, innerBlocks ]
}
return [ blockName, blockAttributes, [] ]
}
// Remove attributes which remain as the default.
export const getCleanAttributes = ( attributes, blockName ) => {
const { getBlockType } = select( 'core/blocks' )
const defaultAttributes = getBlockType( blockName ).attributes
const cleanedAttributes = Object.keys( attributes ).reduce( ( attrs, attrName ) => {
const defaultValue = defaultAttributes[ attrName ] ? defaultAttributes[ attrName ].default : ''
if ( ! isEqual( attributes[ attrName ], defaultValue ) ) {
attrs[ attrName ] = attributes[ attrName ]
}
return attrs
}, {} )
return cleanedAttributes
}
// Filter out specified attributes from the block attributes
export const getFilteredAttributes = ( attributes, filter ) => {
const filteredAttributes = {}
const blockAttrs = cloneDeep( attributes )
filter.forEach( attr => {
if ( attr in blockAttrs ) {
delete blockAttrs[ attr ]
}
} )
Object.entries( blockAttrs ).forEach( ( [ key, value ] ) => {
if ( value && typeof value === 'object' && 'default' in value ) {
filteredAttributes[ key ] = value.default
} else {
filteredAttributes[ key ] = undefined
}
} )
return filteredAttributes
}
// removes comment from serialized block string
export const cleanSerializedBlock = ( serialized, cb, attributes = {} ) => {
let cleanSerialized = serialized.replace( /<!--[\s\S]*?-->/g, '' )
if ( cb ) {
cleanSerialized = cb( cleanSerialized, attributes )
}
return cleanSerialized
}
export const META_SEPARATORS = {
dot: '·',
space: ' ',
comma: ',',
dash: '—',
pipe: '|',
}