-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
selectors.js
815 lines (779 loc) · 22.8 KB
/
selectors.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
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
/**
* External dependencies
*/
import createSelector from 'rememo';
import removeAccents from 'remove-accents';
/**
* WordPress dependencies
*/
import { pipe } from '@wordpress/compose';
/**
* Internal dependencies
*/
import { getValueFromObjectPath } from './utils';
/** @typedef {import('../api/registration').WPBlockVariation} WPBlockVariation */
/** @typedef {import('../api/registration').WPBlockVariationScope} WPBlockVariationScope */
/** @typedef {import('./reducer').WPBlockCategory} WPBlockCategory */
/**
* Given a block name or block type object, returns the corresponding
* normalized block type object.
*
* @param {Object} state Blocks state.
* @param {(string|Object)} nameOrType Block name or type object
*
* @return {Object} Block type object.
*/
const getNormalizedBlockType = ( state, nameOrType ) =>
'string' === typeof nameOrType
? getBlockType( state, nameOrType )
: nameOrType;
/**
* Returns all the available block types.
*
* @param {Object} state Data state.
*
* @example
* ```js
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const blockTypes = useSelect(
* ( select ) => select( blocksStore ).getBlockTypes(),
* []
* );
*
* return (
* <ul>
* { blockTypes.map( ( block ) => (
* <li key={ block.name }>{ block.title }</li>
* ) ) }
* </ul>
* );
* };
* ```
*
* @return {Array} Block Types.
*/
export const getBlockTypes = createSelector(
( state ) => Object.values( state.blockTypes ),
( state ) => [ state.blockTypes ]
);
/**
* Returns a block type by name.
*
* @param {Object} state Data state.
* @param {string} name Block type name.
*
* @example
* ```js
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const paragraphBlock = useSelect( ( select ) =>
* ( select ) => select( blocksStore ).getBlockType( 'core/paragraph' ),
* []
* );
*
* return (
* <ul>
* { paragraphBlock &&
* Object.entries( paragraphBlock.supports ).map(
* ( blockSupportsEntry ) => {
* const [ propertyName, value ] = blockSupportsEntry;
* return (
* <li
* key={ propertyName }
* >{ `${ propertyName } : ${ value }` }</li>
* );
* }
* ) }
* </ul>
* );
* };
* ```
*
* @return {Object?} Block Type.
*/
export function getBlockType( state, name ) {
return state.blockTypes[ name ];
}
/**
* Returns block styles by block name.
*
* @param {Object} state Data state.
* @param {string} name Block type name.
*
* @example
* ```js
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const buttonBlockStyles = useSelect( ( select ) =>
* select( blocksStore ).getBlockStyles( 'core/button' ),
* []
* );
*
* return (
* <ul>
* { buttonBlockStyles &&
* buttonBlockStyles.map( ( style ) => (
* <li key={ style.name }>{ style.label }</li>
* ) ) }
* </ul>
* );
* };
* ```
*
* @return {Array?} Block Styles.
*/
export function getBlockStyles( state, name ) {
return state.blockStyles[ name ];
}
/**
* Returns block variations by block name.
*
* @param {Object} state Data state.
* @param {string} blockName Block type name.
* @param {WPBlockVariationScope} [scope] Block variation scope name.
*
* @example
* ```js
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const socialLinkVariations = useSelect( ( select ) =>
* select( blocksStore ).getBlockVariations( 'core/social-link' ),
* []
* );
*
* return (
* <ul>
* { socialLinkVariations &&
* socialLinkVariations.map( ( variation ) => (
* <li key={ variation.name }>{ variation.title }</li>
* ) ) }
* </ul>
* );
* };
* ```
*
* @return {(WPBlockVariation[]|void)} Block variations.
*/
export const getBlockVariations = createSelector(
( state, blockName, scope ) => {
const variations = state.blockVariations[ blockName ];
if ( ! variations || ! scope ) {
return variations;
}
return variations.filter( ( variation ) => {
// For backward compatibility reasons, variation's scope defaults to
// `block` and `inserter` when not set.
return ( variation.scope || [ 'block', 'inserter' ] ).includes(
scope
);
} );
},
( state, blockName ) => [ state.blockVariations[ blockName ] ]
);
/**
* Returns the active block variation for a given block based on its attributes.
* Variations are determined by their `isActive` property.
* Which is either an array of block attribute keys or a function.
*
* In case of an array of block attribute keys, the `attributes` are compared
* to the variation's attributes using strict equality check.
*
* In case of function type, the function should accept a block's attributes
* and the variation's attributes and determines if a variation is active.
* A function that accepts a block's attributes and the variation's attributes and determines if a variation is active.
*
* @param {Object} state Data state.
* @param {string} blockName Name of block (example: “core/columns”).
* @param {Object} attributes Block attributes used to determine active variation.
* @param {WPBlockVariationScope} [scope] Block variation scope name.
*
* @example
* ```js
* import { __ } from '@wordpress/i18n';
* import { store as blocksStore } from '@wordpress/blocks';
* import { store as blockEditorStore } from '@wordpress/block-editor';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* // This example assumes that a core/embed block is the first block in the Block Editor.
* const activeBlockVariation = useSelect( ( select ) => {
* // Retrieve the list of blocks.
* const [ firstBlock ] = select( blockEditorStore ).getBlocks()
*
* // Return the active block variation for the first block.
* return select( blocksStore ).getActiveBlockVariation(
* firstBlock.name,
* firstBlock.attributes
* );
* }, [] );
*
* return activeBlockVariation && activeBlockVariation.name === 'spotify' ? (
* <p>{ __( 'Spotify variation' ) }</p>
* ) : (
* <p>{ __( 'Other variation' ) }</p>
* );
* };
* ```
*
* @return {(WPBlockVariation|undefined)} Active block variation.
*/
export function getActiveBlockVariation( state, blockName, attributes, scope ) {
const variations = getBlockVariations( state, blockName, scope );
const match = variations?.find( ( variation ) => {
if ( Array.isArray( variation.isActive ) ) {
const blockType = getBlockType( state, blockName );
const attributeKeys = Object.keys( blockType?.attributes || {} );
const definedAttributes = variation.isActive.filter(
( attribute ) => attributeKeys.includes( attribute )
);
if ( definedAttributes.length === 0 ) {
return false;
}
return definedAttributes.every(
( attribute ) =>
attributes[ attribute ] ===
variation.attributes[ attribute ]
);
}
return variation.isActive?.( attributes, variation.attributes );
} );
return match;
}
/**
* Returns the default block variation for the given block type.
* When there are multiple variations annotated as the default one,
* the last added item is picked. This simplifies registering overrides.
* When there is no default variation set, it returns the first item.
*
* @param {Object} state Data state.
* @param {string} blockName Block type name.
* @param {WPBlockVariationScope} [scope] Block variation scope name.
*
* @example
* ```js
* import { __, sprintf } from '@wordpress/i18n';
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const defaultEmbedBlockVariation = useSelect( ( select ) =>
* select( blocksStore ).getDefaultBlockVariation( 'core/embed' ),
* []
* );
*
* return (
* defaultEmbedBlockVariation && (
* <p>
* { sprintf(
* __( 'core/embed default variation: %s' ),
* defaultEmbedBlockVariation.title
* ) }
* </p>
* )
* );
* };
* ```
*
* @return {?WPBlockVariation} The default block variation.
*/
export function getDefaultBlockVariation( state, blockName, scope ) {
const variations = getBlockVariations( state, blockName, scope );
const defaultVariation = [ ...variations ]
.reverse()
.find( ( { isDefault } ) => !! isDefault );
return defaultVariation || variations[ 0 ];
}
/**
* Returns all the available block categories.
*
* @param {Object} state Data state.
*
* @example
* ```js
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect, } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const blockCategories = useSelect( ( select ) =>
* select( blocksStore ).getCategories(),
* []
* );
*
* return (
* <ul>
* { blockCategories.map( ( category ) => (
* <li key={ category.slug }>{ category.title }</li>
* ) ) }
* </ul>
* );
* };
* ```
*
* @return {WPBlockCategory[]} Categories list.
*/
export function getCategories( state ) {
return state.categories;
}
/**
* Returns all the available collections.
*
* @param {Object} state Data state.
*
* @example
* ```js
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const blockCollections = useSelect( ( select ) =>
* select( blocksStore ).getCollections(),
* []
* );
*
* return (
* <ul>
* { Object.values( blockCollections ).length > 0 &&
* Object.values( blockCollections ).map( ( collection ) => (
* <li key={ collection.title }>{ collection.title }</li>
* ) ) }
* </ul>
* );
* };
* ```
*
* @return {Object} Collections list.
*/
export function getCollections( state ) {
return state.collections;
}
/**
* Returns the name of the default block name.
*
* @param {Object} state Data state.
*
* @example
* ```js
* import { __, sprintf } from '@wordpress/i18n';
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const defaultBlockName = useSelect( ( select ) =>
* select( blocksStore ).getDefaultBlockName(),
* []
* );
*
* return (
* defaultBlockName && (
* <p>
* { sprintf( __( 'Default block name: %s' ), defaultBlockName ) }
* </p>
* )
* );
* };
* ```
*
* @return {string?} Default block name.
*/
export function getDefaultBlockName( state ) {
return state.defaultBlockName;
}
/**
* Returns the name of the block for handling non-block content.
*
* @param {Object} state Data state.
*
* @example
* ```js
* import { __, sprintf } from '@wordpress/i18n';
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const freeformFallbackBlockName = useSelect( ( select ) =>
* select( blocksStore ).getFreeformFallbackBlockName(),
* []
* );
*
* return (
* freeformFallbackBlockName && (
* <p>
* { sprintf( __(
* 'Freeform fallback block name: %s' ),
* freeformFallbackBlockName
* ) }
* </p>
* )
* );
* };
* ```
*
* @return {string?} Name of the block for handling non-block content.
*/
export function getFreeformFallbackBlockName( state ) {
return state.freeformFallbackBlockName;
}
/**
* Returns the name of the block for handling unregistered blocks.
*
* @param {Object} state Data state.
*
* @example
* ```js
* import { __, sprintf } from '@wordpress/i18n';
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const unregisteredFallbackBlockName = useSelect( ( select ) =>
* select( blocksStore ).getUnregisteredFallbackBlockName(),
* []
* );
*
* return (
* unregisteredFallbackBlockName && (
* <p>
* { sprintf( __(
* 'Unregistered fallback block name: %s' ),
* unregisteredFallbackBlockName
* ) }
* </p>
* )
* );
* };
* ```
*
* @return {string?} Name of the block for handling unregistered blocks.
*/
export function getUnregisteredFallbackBlockName( state ) {
return state.unregisteredFallbackBlockName;
}
/**
* Returns the name of the block for handling the grouping of blocks.
*
* @param {Object} state Data state.
*
* @example
* ```js
* import { __, sprintf } from '@wordpress/i18n';
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const groupingBlockName = useSelect( ( select ) =>
* select( blocksStore ).getGroupingBlockName(),
* []
* );
*
* return (
* groupingBlockName && (
* <p>
* { sprintf(
* __( 'Default grouping block name: %s' ),
* groupingBlockName
* ) }
* </p>
* )
* );
* };
* ```
*
* @return {string?} Name of the block for handling the grouping of blocks.
*/
export function getGroupingBlockName( state ) {
return state.groupingBlockName;
}
/**
* Returns an array with the child blocks of a given block.
*
* @param {Object} state Data state.
* @param {string} blockName Block type name.
*
* @example
* ```js
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const childBlockNames = useSelect( ( select ) =>
* select( blocksStore ).getChildBlockNames( 'core/navigation' ),
* []
* );
*
* return (
* <ul>
* { childBlockNames &&
* childBlockNames.map( ( child ) => (
* <li key={ child }>{ child }</li>
* ) ) }
* </ul>
* );
* };
* ```
*
* @return {Array} Array of child block names.
*/
export const getChildBlockNames = createSelector(
( state, blockName ) => {
return getBlockTypes( state )
.filter( ( blockType ) => {
return blockType.parent?.includes( blockName );
} )
.map( ( { name } ) => name );
},
( state ) => [ state.blockTypes ]
);
/**
* Returns the block support value for a feature, if defined.
*
* @param {Object} state Data state.
* @param {(string|Object)} nameOrType Block name or type object
* @param {Array|string} feature Feature to retrieve
* @param {*} defaultSupports Default value to return if not
* explicitly defined
*
* @example
* ```js
* import { __, sprintf } from '@wordpress/i18n';
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const paragraphBlockSupportValue = useSelect( ( select ) =>
* select( blocksStore ).getBlockSupport( 'core/paragraph', 'anchor' ),
* []
* );
*
* return (
* <p>
* { sprintf(
* __( 'core/paragraph supports.anchor value: %s' ),
* paragraphBlockSupportValue
* ) }
* </p>
* );
* };
* ```
*
* @return {?*} Block support value
*/
export const getBlockSupport = (
state,
nameOrType,
feature,
defaultSupports
) => {
const blockType = getNormalizedBlockType( state, nameOrType );
if ( ! blockType?.supports ) {
return defaultSupports;
}
return getValueFromObjectPath(
blockType.supports,
feature,
defaultSupports
);
};
/**
* Returns true if the block defines support for a feature, or false otherwise.
*
* @param {Object} state Data state.
* @param {(string|Object)} nameOrType Block name or type object.
* @param {string} feature Feature to test.
* @param {boolean} defaultSupports Whether feature is supported by
* default if not explicitly defined.
*
* @example
* ```js
* import { __, sprintf } from '@wordpress/i18n';
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const paragraphBlockSupportClassName = useSelect( ( select ) =>
* select( blocksStore ).hasBlockSupport( 'core/paragraph', 'className' ),
* []
* );
*
* return (
* <p>
* { sprintf(
* __( 'core/paragraph supports custom class name?: %s' ),
* paragraphBlockSupportClassName
* ) }
* /p>
* );
* };
* ```
*
* @return {boolean} Whether block supports feature.
*/
export function hasBlockSupport( state, nameOrType, feature, defaultSupports ) {
return !! getBlockSupport( state, nameOrType, feature, defaultSupports );
}
/**
* Returns true if the block type by the given name or object value matches a
* search term, or false otherwise.
*
* @param {Object} state Blocks state.
* @param {(string|Object)} nameOrType Block name or type object.
* @param {string} searchTerm Search term by which to filter.
*
* @example
* ```js
* import { __, sprintf } from '@wordpress/i18n';
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const termFound = useSelect(
* ( select ) =>
* select( blocksStore ).isMatchingSearchTerm(
* 'core/navigation',
* 'theme'
* ),
* []
* );
*
* return (
* <p>
* { sprintf(
* __(
* 'Search term was found in the title, keywords, category or description in block.json: %s'
* ),
* termFound
* ) }
* </p>
* );
* };
* ```
*
* @return {Object[]} Whether block type matches search term.
*/
export function isMatchingSearchTerm( state, nameOrType, searchTerm ) {
const blockType = getNormalizedBlockType( state, nameOrType );
const getNormalizedSearchTerm = pipe( [
// Disregard diacritics.
// Input: "média"
( term ) => removeAccents( term ?? '' ),
// Lowercase.
// Input: "MEDIA"
( term ) => term.toLowerCase(),
// Strip leading and trailing whitespace.
// Input: " media "
( term ) => term.trim(),
] );
const normalizedSearchTerm = getNormalizedSearchTerm( searchTerm );
const isSearchMatch = pipe( [
getNormalizedSearchTerm,
( normalizedCandidate ) =>
normalizedCandidate.includes( normalizedSearchTerm ),
] );
return (
isSearchMatch( blockType.title ) ||
blockType.keywords?.some( isSearchMatch ) ||
isSearchMatch( blockType.category ) ||
( typeof blockType.description === 'string' &&
isSearchMatch( blockType.description ) )
);
}
/**
* Returns a boolean indicating if a block has child blocks or not.
*
* @param {Object} state Data state.
* @param {string} blockName Block type name.
*
* @example
* ```js
* import { __, sprintf } from '@wordpress/i18n';
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const navigationBlockHasChildBlocks = useSelect( ( select ) =>
* select( blocksStore ).hasChildBlocks( 'core/navigation' ),
* []
* );
*
* return (
* <p>
* { sprintf(
* __( 'core/navigation has child blocks: %s' ),
* navigationBlockHasChildBlocks
* ) }
* </p>
* );
* };
* ```
*
* @return {boolean} True if a block contains child blocks and false otherwise.
*/
export const hasChildBlocks = ( state, blockName ) => {
return getChildBlockNames( state, blockName ).length > 0;
};
/**
* Returns a boolean indicating if a block has at least one child block with inserter support.
*
* @param {Object} state Data state.
* @param {string} blockName Block type name.
*
* @example
* ```js
* import { __, sprintf } from '@wordpress/i18n';
* import { store as blocksStore } from '@wordpress/blocks';
* import { useSelect } from '@wordpress/data';
*
* const ExampleComponent = () => {
* const navigationBlockHasChildBlocksWithInserterSupport = useSelect( ( select ) =>
* select( blocksStore ).hasChildBlocksWithInserterSupport(
* 'core/navigation'
* ),
* []
* );
*
* return (
* <p>
* { sprintf(
* __( 'core/navigation has child blocks with inserter support: %s' ),
* navigationBlockHasChildBlocksWithInserterSupport
* ) }
* </p>
* );
* };
* ```
*
* @return {boolean} True if a block contains at least one child blocks with inserter support
* and false otherwise.
*/
export const hasChildBlocksWithInserterSupport = ( state, blockName ) => {
return getChildBlockNames( state, blockName ).some( ( childBlockName ) => {
return hasBlockSupport( state, childBlockName, 'inserter', true );
} );
};
/**
* DO-NOT-USE in production.
* This selector is created for internal/experimental only usage and may be
* removed anytime without any warning, causing breakage on any plugin or theme invoking it.
*/
export const __experimentalHasContentRoleAttribute = createSelector(
( state, blockTypeName ) => {
const blockType = getBlockType( state, blockTypeName );
if ( ! blockType ) {
return false;
}
return Object.entries( blockType.attributes ).some(
( [ , { __experimentalRole } ] ) => __experimentalRole === 'content'
);
},
( state, blockTypeName ) => [
state.blockTypes[ blockTypeName ]?.attributes,
]
);