-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
utils.js
662 lines (645 loc) · 20 KB
/
utils.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
/**
* WordPress dependencies
*/
import { useSelect } from '@wordpress/data';
import { store as coreStore } from '@wordpress/core-data';
import { store as editorStore } from '@wordpress/editor';
import { decodeEntities } from '@wordpress/html-entities';
import { useMemo, useCallback } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { blockMeta, post, archive } from '@wordpress/icons';
/**
* Internal dependencies
*/
import { TEMPLATE_POST_TYPE } from '../../utils/constants';
/**
* @typedef IHasNameAndId
* @property {string|number} id The entity's id.
* @property {string} name The entity's name.
*/
const getValueFromObjectPath = ( object, path ) => {
let value = object;
path.split( '.' ).forEach( ( fieldName ) => {
value = value?.[ fieldName ];
} );
return value;
};
/**
* Helper util to map records to add a `name` prop from a
* provided path, in order to handle all entities in the same
* fashion(implementing`IHasNameAndId` interface).
*
* @param {Object[]} entities The array of entities.
* @param {string} path The path to map a `name` property from the entity.
* @return {IHasNameAndId[]} An array of enitities that now implement the `IHasNameAndId` interface.
*/
export const mapToIHasNameAndId = ( entities, path ) => {
return ( entities || [] ).map( ( entity ) => ( {
...entity,
name: decodeEntities( getValueFromObjectPath( entity, path ) ),
} ) );
};
/**
* @typedef {Object} EntitiesInfo
* @property {boolean} hasEntities If an entity has available records(posts, terms, etc..).
* @property {number[]} existingEntitiesIds An array of the existing entities ids.
*/
export const useExistingTemplates = () => {
return useSelect(
( select ) =>
select( coreStore ).getEntityRecords(
'postType',
TEMPLATE_POST_TYPE,
{
per_page: -1,
}
),
[]
);
};
export const useDefaultTemplateTypes = () => {
return useSelect(
( select ) =>
select( editorStore ).__experimentalGetDefaultTemplateTypes(),
[]
);
};
const usePublicPostTypes = () => {
const postTypes = useSelect(
( select ) => select( coreStore ).getPostTypes( { per_page: -1 } ),
[]
);
return useMemo( () => {
const excludedPostTypes = [ 'attachment' ];
return postTypes?.filter(
( { viewable, slug } ) =>
viewable && ! excludedPostTypes.includes( slug )
);
}, [ postTypes ] );
};
const usePublicTaxonomies = () => {
const taxonomies = useSelect(
( select ) => select( coreStore ).getTaxonomies( { per_page: -1 } ),
[]
);
return useMemo( () => {
return taxonomies?.filter(
( { visibility } ) => visibility?.publicly_queryable
);
}, [ taxonomies ] );
};
function usePostTypeNeedsUniqueIdentifier( publicPostTypes ) {
const postTypeLabels = useMemo( () =>
publicPostTypes?.reduce( ( accumulator, { labels } ) => {
const singularName = labels.singular_name.toLowerCase();
accumulator[ singularName ] =
( accumulator[ singularName ] || 0 ) + 1;
return accumulator;
}, {} )
);
return useCallback(
( { labels, slug } ) => {
const singularName = labels.singular_name.toLowerCase();
return postTypeLabels[ singularName ] > 1 && singularName !== slug;
},
[ postTypeLabels ]
);
}
export function usePostTypeArchiveMenuItems() {
const publicPostTypes = usePublicPostTypes();
const postTypesWithArchives = useMemo(
() => publicPostTypes?.filter( ( postType ) => postType.has_archive ),
[ publicPostTypes ]
);
const existingTemplates = useExistingTemplates();
const needsUniqueIdentifier = usePostTypeNeedsUniqueIdentifier(
postTypesWithArchives
);
return useMemo(
() =>
postTypesWithArchives
?.filter(
( postType ) =>
! ( existingTemplates || [] ).some(
( existingTemplate ) =>
existingTemplate.slug ===
'archive-' + postType.slug
)
)
.map( ( postType ) => {
let title;
if ( needsUniqueIdentifier( postType ) ) {
title = sprintf(
// translators: %1s: Name of the post type e.g: "Post"; %2s: Slug of the post type e.g: "book".
__( 'Archive: %1$s (%2$s)' ),
postType.labels.singular_name,
postType.slug
);
} else {
title = sprintf(
// translators: %s: Name of the post type e.g: "Post".
__( 'Archive: %s' ),
postType.labels.singular_name
);
}
return {
slug: 'archive-' + postType.slug,
description: sprintf(
// translators: %s: Name of the post type e.g: "Post".
__(
'Displays an archive with the latest posts of type: %s.'
),
postType.labels.singular_name
),
title,
// `icon` is the `menu_icon` property of a post type. We
// only handle `dashicons` for now, even if the `menu_icon`
// also supports urls and svg as values.
icon: postType.icon?.startsWith( 'dashicons-' )
? postType.icon.slice( 10 )
: archive,
templatePrefix: 'archive',
};
} ) || [],
[ postTypesWithArchives, existingTemplates, needsUniqueIdentifier ]
);
}
export const usePostTypeMenuItems = ( onClickMenuItem ) => {
const publicPostTypes = usePublicPostTypes();
const existingTemplates = useExistingTemplates();
const defaultTemplateTypes = useDefaultTemplateTypes();
const needsUniqueIdentifier =
usePostTypeNeedsUniqueIdentifier( publicPostTypes );
// `page`is a special case in template hierarchy.
const templatePrefixes = useMemo(
() =>
publicPostTypes?.reduce( ( accumulator, { slug } ) => {
let suffix = slug;
if ( slug !== 'page' ) {
suffix = `single-${ suffix }`;
}
accumulator[ slug ] = suffix;
return accumulator;
}, {} ),
[ publicPostTypes ]
);
const postTypesInfo = useEntitiesInfo( 'postType', templatePrefixes );
const existingTemplateSlugs = ( existingTemplates || [] ).map(
( { slug } ) => slug
);
const menuItems = ( publicPostTypes || [] ).reduce(
( accumulator, postType ) => {
const { slug, labels, icon } = postType;
// We need to check if the general template is part of the
// defaultTemplateTypes. If it is, just use that info and
// augment it with the specific template functionality.
const generalTemplateSlug = templatePrefixes[ slug ];
const defaultTemplateType = defaultTemplateTypes?.find(
( { slug: _slug } ) => _slug === generalTemplateSlug
);
const hasGeneralTemplate =
existingTemplateSlugs?.includes( generalTemplateSlug );
const _needsUniqueIdentifier = needsUniqueIdentifier( postType );
let menuItemTitle = sprintf(
// translators: %s: Name of the post type e.g: "Post".
__( 'Single item: %s' ),
labels.singular_name
);
if ( _needsUniqueIdentifier ) {
menuItemTitle = sprintf(
// translators: %1s: Name of the post type e.g: "Post"; %2s: Slug of the post type e.g: "book".
__( 'Single item: %1$s (%2$s)' ),
labels.singular_name,
slug
);
}
const menuItem = defaultTemplateType
? {
...defaultTemplateType,
templatePrefix: templatePrefixes[ slug ],
}
: {
slug: generalTemplateSlug,
title: menuItemTitle,
description: sprintf(
// translators: %s: Name of the post type e.g: "Post".
__( 'Displays a single item: %s.' ),
labels.singular_name
),
// `icon` is the `menu_icon` property of a post type. We
// only handle `dashicons` for now, even if the `menu_icon`
// also supports urls and svg as values.
icon: icon?.startsWith( 'dashicons-' )
? icon.slice( 10 )
: post,
templatePrefix: templatePrefixes[ slug ],
};
const hasEntities = postTypesInfo?.[ slug ]?.hasEntities;
// We have a different template creation flow only if they have entities.
if ( hasEntities ) {
menuItem.onClick = ( template ) => {
onClickMenuItem( {
type: 'postType',
slug,
config: {
recordNamePath: 'title.rendered',
queryArgs: ( { search } ) => {
return {
_fields: 'id,title,slug,link',
orderBy: search ? 'relevance' : 'modified',
exclude:
postTypesInfo[ slug ]
.existingEntitiesIds,
};
},
getSpecificTemplate: ( suggestion ) => {
const templateSlug = `${ templatePrefixes[ slug ] }-${ suggestion.slug }`;
return {
title: templateSlug,
slug: templateSlug,
templatePrefix: templatePrefixes[ slug ],
};
},
},
labels,
hasGeneralTemplate,
template,
} );
};
}
// We don't need to add the menu item if there are no
// entities and the general template exists.
if ( ! hasGeneralTemplate || hasEntities ) {
accumulator.push( menuItem );
}
return accumulator;
},
[]
);
// Split menu items into two groups: one for the default post types
// and one for the rest.
const postTypesMenuItems = useMemo(
() =>
menuItems.reduce(
( accumulator, postType ) => {
const { slug } = postType;
let key = 'postTypesMenuItems';
if ( slug === 'page' ) {
key = 'defaultPostTypesMenuItems';
}
accumulator[ key ].push( postType );
return accumulator;
},
{ defaultPostTypesMenuItems: [], postTypesMenuItems: [] }
),
[ menuItems ]
);
return postTypesMenuItems;
};
export const useTaxonomiesMenuItems = ( onClickMenuItem ) => {
const publicTaxonomies = usePublicTaxonomies();
const existingTemplates = useExistingTemplates();
const defaultTemplateTypes = useDefaultTemplateTypes();
// `category` and `post_tag` are special cases in template hierarchy.
const templatePrefixes = useMemo(
() =>
publicTaxonomies?.reduce( ( accumulator, { slug } ) => {
let suffix = slug;
if ( ! [ 'category', 'post_tag' ].includes( slug ) ) {
suffix = `taxonomy-${ suffix }`;
}
if ( slug === 'post_tag' ) {
suffix = `tag`;
}
accumulator[ slug ] = suffix;
return accumulator;
}, {} ),
[ publicTaxonomies ]
);
// We need to keep track of naming conflicts. If a conflict
// occurs, we need to add slug.
const taxonomyLabels = publicTaxonomies?.reduce(
( accumulator, { labels } ) => {
const singularName = labels.singular_name.toLowerCase();
accumulator[ singularName ] =
( accumulator[ singularName ] || 0 ) + 1;
return accumulator;
},
{}
);
const needsUniqueIdentifier = ( labels, slug ) => {
if ( [ 'category', 'post_tag' ].includes( slug ) ) {
return false;
}
const singularName = labels.singular_name.toLowerCase();
return taxonomyLabels[ singularName ] > 1 && singularName !== slug;
};
const taxonomiesInfo = useEntitiesInfo( 'taxonomy', templatePrefixes );
const existingTemplateSlugs = ( existingTemplates || [] ).map(
( { slug } ) => slug
);
const menuItems = ( publicTaxonomies || [] ).reduce(
( accumulator, taxonomy ) => {
const { slug, labels } = taxonomy;
// We need to check if the general template is part of the
// defaultTemplateTypes. If it is, just use that info and
// augment it with the specific template functionality.
const generalTemplateSlug = templatePrefixes[ slug ];
const defaultTemplateType = defaultTemplateTypes?.find(
( { slug: _slug } ) => _slug === generalTemplateSlug
);
const hasGeneralTemplate =
existingTemplateSlugs?.includes( generalTemplateSlug );
const _needsUniqueIdentifier = needsUniqueIdentifier(
labels,
slug
);
let menuItemTitle = labels.singular_name;
if ( _needsUniqueIdentifier ) {
menuItemTitle = sprintf(
// translators: %1s: Name of the taxonomy e.g: "Category"; %2s: Slug of the taxonomy e.g: "product_cat".
__( '%1$s (%2$s)' ),
labels.singular_name,
slug
);
}
const menuItem = defaultTemplateType
? {
...defaultTemplateType,
templatePrefix: templatePrefixes[ slug ],
}
: {
slug: generalTemplateSlug,
title: menuItemTitle,
description: sprintf(
// translators: %s: Name of the taxonomy e.g: "Product Categories".
__( 'Displays taxonomy: %s.' ),
labels.singular_name
),
icon: blockMeta,
templatePrefix: templatePrefixes[ slug ],
};
const hasEntities = taxonomiesInfo?.[ slug ]?.hasEntities;
// We have a different template creation flow only if they have entities.
if ( hasEntities ) {
menuItem.onClick = ( template ) => {
onClickMenuItem( {
type: 'taxonomy',
slug,
config: {
queryArgs: ( { search } ) => {
return {
_fields: 'id,name,slug,link',
orderBy: search ? 'name' : 'count',
exclude:
taxonomiesInfo[ slug ]
.existingEntitiesIds,
};
},
getSpecificTemplate: ( suggestion ) => {
const templateSlug = `${ templatePrefixes[ slug ] }-${ suggestion.slug }`;
return {
title: templateSlug,
slug: templateSlug,
templatePrefix: templatePrefixes[ slug ],
};
},
},
labels,
hasGeneralTemplate,
template,
} );
};
}
// We don't need to add the menu item if there are no
// entities and the general template exists.
if ( ! hasGeneralTemplate || hasEntities ) {
accumulator.push( menuItem );
}
return accumulator;
},
[]
);
// Split menu items into two groups: one for the default taxonomies
// and one for the rest.
const taxonomiesMenuItems = useMemo(
() =>
menuItems.reduce(
( accumulator, taxonomy ) => {
const { slug } = taxonomy;
let key = 'taxonomiesMenuItems';
if ( [ 'category', 'tag' ].includes( slug ) ) {
key = 'defaultTaxonomiesMenuItems';
}
accumulator[ key ].push( taxonomy );
return accumulator;
},
{ defaultTaxonomiesMenuItems: [], taxonomiesMenuItems: [] }
),
[ menuItems ]
);
return taxonomiesMenuItems;
};
const USE_AUTHOR_MENU_ITEM_TEMPLATE_PREFIX = { user: 'author' };
const USE_AUTHOR_MENU_ITEM_QUERY_PARAMETERS = { user: { who: 'authors' } };
export function useAuthorMenuItem( onClickMenuItem ) {
const existingTemplates = useExistingTemplates();
const defaultTemplateTypes = useDefaultTemplateTypes();
const authorInfo = useEntitiesInfo(
'root',
USE_AUTHOR_MENU_ITEM_TEMPLATE_PREFIX,
USE_AUTHOR_MENU_ITEM_QUERY_PARAMETERS
);
let authorMenuItem = defaultTemplateTypes?.find(
( { slug } ) => slug === 'author'
);
if ( ! authorMenuItem ) {
authorMenuItem = {
description: __(
'Displays latest posts written by a single author.'
),
slug: 'author',
title: 'Author',
};
}
const hasGeneralTemplate = !! existingTemplates?.find(
( { slug } ) => slug === 'author'
);
if ( authorInfo.user?.hasEntities ) {
authorMenuItem = { ...authorMenuItem, templatePrefix: 'author' };
authorMenuItem.onClick = ( template ) => {
onClickMenuItem( {
type: 'root',
slug: 'user',
config: {
queryArgs: ( { search } ) => {
return {
_fields: 'id,name,slug,link',
orderBy: search ? 'name' : 'registered_date',
exclude: authorInfo.user.existingEntitiesIds,
who: 'authors',
};
},
getSpecificTemplate: ( suggestion ) => {
const templateSlug = `author-${ suggestion.slug }`;
return {
title: templateSlug,
slug: templateSlug,
templatePrefix: 'author',
};
},
},
labels: {
singular_name: __( 'Author' ),
search_items: __( 'Search Authors' ),
not_found: __( 'No authors found.' ),
all_items: __( 'All Authors' ),
},
hasGeneralTemplate,
template,
} );
};
}
if ( ! hasGeneralTemplate || authorInfo.user?.hasEntities ) {
return authorMenuItem;
}
}
/**
* Helper hook that filters all the existing templates by the given
* object with the entity's slug as key and the template prefix as value.
*
* Example:
* `existingTemplates` is: [ { slug: 'tag-apple' }, { slug: 'page-about' }, { slug: 'tag' } ]
* `templatePrefixes` is: { post_tag: 'tag' }
* It will return: { post_tag: ['apple'] }
*
* Note: We append the `-` to the given template prefix in this function for our checks.
*
* @param {Record<string,string>} templatePrefixes An object with the entity's slug as key and the template prefix as value.
* @return {Record<string,string[]>} An object with the entity's slug as key and an array with the existing template slugs as value.
*/
const useExistingTemplateSlugs = ( templatePrefixes ) => {
const existingTemplates = useExistingTemplates();
const existingSlugs = useMemo( () => {
return Object.entries( templatePrefixes || {} ).reduce(
( accumulator, [ slug, prefix ] ) => {
const slugsWithTemplates = ( existingTemplates || [] ).reduce(
( _accumulator, existingTemplate ) => {
const _prefix = `${ prefix }-`;
if ( existingTemplate.slug.startsWith( _prefix ) ) {
_accumulator.push(
existingTemplate.slug.substring(
_prefix.length
)
);
}
return _accumulator;
},
[]
);
if ( slugsWithTemplates.length ) {
accumulator[ slug ] = slugsWithTemplates;
}
return accumulator;
},
{}
);
}, [ templatePrefixes, existingTemplates ] );
return existingSlugs;
};
/**
* Helper hook that finds the existing records with an associated template,
* as they need to be excluded from the template suggestions.
*
* @param {string} entityName The entity's name.
* @param {Record<string,string>} templatePrefixes An object with the entity's slug as key and the template prefix as value.
* @param {Record<string,Object>} additionalQueryParameters An object with the entity's slug as key and additional query parameters as value.
* @return {Record<string,EntitiesInfo>} An object with the entity's slug as key and the existing records as value.
*/
const useTemplatesToExclude = (
entityName,
templatePrefixes,
additionalQueryParameters = {}
) => {
const slugsToExcludePerEntity =
useExistingTemplateSlugs( templatePrefixes );
const recordsToExcludePerEntity = useSelect(
( select ) => {
return Object.entries( slugsToExcludePerEntity || {} ).reduce(
( accumulator, [ slug, slugsWithTemplates ] ) => {
const entitiesWithTemplates = select(
coreStore
).getEntityRecords( entityName, slug, {
_fields: 'id',
context: 'view',
slug: slugsWithTemplates,
...additionalQueryParameters[ slug ],
} );
if ( entitiesWithTemplates?.length ) {
accumulator[ slug ] = entitiesWithTemplates;
}
return accumulator;
},
{}
);
},
[ slugsToExcludePerEntity ]
);
return recordsToExcludePerEntity;
};
/**
* Helper hook that returns information about an entity having
* records that we can create a specific template for.
*
* For example we can search for `terms` in `taxonomy` entity or
* `posts` in `postType` entity.
*
* First we need to find the existing records with an associated template,
* to query afterwards for any remaining record, by excluding them.
*
* @param {string} entityName The entity's name.
* @param {Record<string,string>} templatePrefixes An object with the entity's slug as key and the template prefix as value.
* @param {Record<string,Object>} additionalQueryParameters An object with the entity's slug as key and additional query parameters as value.
* @return {Record<string,EntitiesInfo>} An object with the entity's slug as key and the EntitiesInfo as value.
*/
const useEntitiesInfo = (
entityName,
templatePrefixes,
additionalQueryParameters = {}
) => {
const recordsToExcludePerEntity = useTemplatesToExclude(
entityName,
templatePrefixes,
additionalQueryParameters
);
const entitiesInfo = useSelect(
( select ) => {
return Object.keys( templatePrefixes || {} ).reduce(
( accumulator, slug ) => {
const existingEntitiesIds =
recordsToExcludePerEntity?.[ slug ]?.map(
( { id } ) => id
) || [];
accumulator[ slug ] = {
hasEntities: !! select( coreStore ).getEntityRecords(
entityName,
slug,
{
per_page: 1,
_fields: 'id',
context: 'view',
exclude: existingEntitiesIds,
...additionalQueryParameters[ slug ],
}
)?.length,
existingEntitiesIds,
};
return accumulator;
},
{}
);
},
[ templatePrefixes, recordsToExcludePerEntity ]
);
return entitiesInfo;
};