-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathindex.js
473 lines (449 loc) · 11.3 KB
/
index.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
/**
* External dependencies
*/
import classnames from 'classnames';
import removeAccents from 'remove-accents';
/**
* WordPress dependencies
*/
import {
Icon,
__experimentalText as Text,
__experimentalHStack as HStack,
VisuallyHidden,
} from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { useState, useMemo, useCallback, useEffect } from '@wordpress/element';
import { useEntityRecords } from '@wordpress/core-data';
import { decodeEntities } from '@wordpress/html-entities';
import { parse } from '@wordpress/blocks';
import {
BlockPreview,
privateApis as blockEditorPrivateApis,
} from '@wordpress/block-editor';
import {
DataViews,
sortByTextFields,
getPaginationResults,
} from '@wordpress/dataviews';
import { privateApis as routerPrivateApis } from '@wordpress/router';
/**
* Internal dependencies
*/
import Page from '../page';
import { default as Link, useLink } from '../routes/link';
import AddNewTemplate from '../add-new-template';
import { useAddedBy } from './hooks';
import {
TEMPLATE_POST_TYPE,
TEMPLATE_PART_POST_TYPE,
ENUMERATION_TYPE,
OPERATOR_IS_ANY,
OPERATOR_IS_NONE,
LAYOUT_GRID,
LAYOUT_TABLE,
LAYOUT_LIST,
} from '../../utils/constants';
import {
useResetTemplateAction,
deleteTemplateAction,
renameTemplateAction,
} from './actions';
import { postRevisionsAction } from '../actions';
import usePatternSettings from '../page-patterns/use-pattern-settings';
import { unlock } from '../../lock-unlock';
import AddNewTemplatePart from './add-new-template-part';
const { ExperimentalBlockEditorProvider, useGlobalStyle } = unlock(
blockEditorPrivateApis
);
const { useHistory, useLocation } = unlock( routerPrivateApis );
const EMPTY_ARRAY = [];
const defaultConfigPerViewType = {
[ LAYOUT_TABLE ]: {
primaryField: 'title',
},
[ LAYOUT_GRID ]: {
mediaField: 'preview',
primaryField: 'title',
},
[ LAYOUT_LIST ]: {
primaryField: 'title',
mediaField: 'preview',
},
};
const DEFAULT_VIEW = {
type: LAYOUT_TABLE,
search: '',
page: 1,
perPage: 20,
sort: {
field: 'title',
direction: 'asc',
},
// All fields are visible by default, so it's
// better to keep track of the hidden ones.
hiddenFields: [ 'preview' ],
layout: defaultConfigPerViewType[ LAYOUT_TABLE ],
filters: [],
};
function normalizeSearchInput( input = '' ) {
return removeAccents( input.trim().toLowerCase() );
}
function Title( { item, viewType } ) {
if ( viewType === LAYOUT_LIST ) {
return decodeEntities( item.title?.rendered ) || __( '(no title)' );
}
const linkProps = {
params: {
postId: item.id,
postType: item.type,
canvas: 'edit',
},
};
if ( item.type === TEMPLATE_PART_POST_TYPE ) {
linkProps.state = {
backPath: '/wp_template_part/all',
};
}
return (
<Link { ...linkProps }>
{ decodeEntities( item.title?.rendered ) || __( '(no title)' ) }
</Link>
);
}
function AuthorField( { item, viewType } ) {
const [ isImageLoaded, setIsImageLoaded ] = useState( false );
const { text, icon, imageUrl } = useAddedBy( item.type, item.id );
const withIcon = viewType !== LAYOUT_LIST;
return (
<HStack alignment="left" spacing={ 1 }>
{ withIcon && imageUrl && (
<div
className={ classnames(
'page-templates-author-field__avatar',
{
'is-loaded': isImageLoaded,
}
) }
>
<img
onLoad={ () => setIsImageLoaded( true ) }
alt=""
src={ imageUrl }
/>
</div>
) }
{ withIcon && ! imageUrl && (
<div className="page-templates-author-field__icon">
<Icon icon={ icon } />
</div>
) }
<span>{ text }</span>
</HStack>
);
}
function Preview( { item, viewType } ) {
const settings = usePatternSettings();
const [ backgroundColor = 'white' ] = useGlobalStyle( 'color.background' );
const blocks = useMemo( () => {
return parse( item.content.raw );
}, [ item.content.raw ] );
const { onClick } = useLink( {
postId: item.id,
postType: item.type,
canvas: 'edit',
} );
const isEmpty = ! blocks?.length;
// Wrap everything in a block editor provider to ensure 'styles' that are needed
// for the previews are synced between the site editor store and the block editor store.
// Additionally we need to have the `__experimentalBlockPatterns` setting in order to
// render patterns inside the previews.
// TODO: Same approach is used in the patterns list and it becomes obvious that some of
// the block editor settings are needed in context where we don't have the block editor.
// Explore how we can solve this in a better way.
return (
<ExperimentalBlockEditorProvider settings={ settings }>
<div
className={ `page-templates-preview-field is-viewtype-${ viewType }` }
style={ { backgroundColor } }
>
{ viewType === LAYOUT_LIST && ! isEmpty && (
<BlockPreview blocks={ blocks } />
) }
{ viewType !== LAYOUT_LIST && (
<button
className="page-templates-preview-field__button"
type="button"
onClick={ onClick }
aria-label={ item.title?.rendered || item.title }
>
{ isEmpty &&
( item.type === TEMPLATE_POST_TYPE
? __( 'Empty template' )
: __( 'Empty template part' ) ) }
{ ! isEmpty && <BlockPreview blocks={ blocks } /> }
</button>
) }
</div>
</ExperimentalBlockEditorProvider>
);
}
export default function PageTemplatesTemplateParts( { postType } ) {
const { params } = useLocation();
const { activeView = 'all', layout } = params;
const defaultView = useMemo( () => {
const usedType = layout ?? DEFAULT_VIEW.type;
return {
...DEFAULT_VIEW,
type: usedType,
layout: defaultConfigPerViewType[ usedType ],
filters:
activeView !== 'all'
? [
{
field: 'author',
operator: 'isAny',
value: [ activeView ],
},
]
: [],
};
}, [ layout, activeView ] );
const [ view, setView ] = useState( defaultView );
useEffect( () => {
setView( ( currentView ) => ( {
...currentView,
filters:
activeView !== 'all'
? [
{
field: 'author',
operator: OPERATOR_IS_ANY,
value: [ activeView ],
},
]
: [],
} ) );
}, [ activeView ] );
const { records, isResolving: isLoadingData } = useEntityRecords(
'postType',
postType,
{
per_page: -1,
}
);
const history = useHistory();
const onSelectionChange = useCallback(
( items ) => {
if ( view?.type === LAYOUT_LIST ) {
history.push( {
...params,
postId: items.length === 1 ? items[ 0 ].id : undefined,
} );
}
},
[ history, params, view?.type ]
);
const authors = useMemo( () => {
if ( ! records ) {
return EMPTY_ARRAY;
}
const authorsSet = new Set();
records.forEach( ( template ) => {
authorsSet.add( template.author_text );
} );
return Array.from( authorsSet ).map( ( author ) => ( {
value: author,
label: author,
} ) );
}, [ records ] );
const fields = useMemo( () => {
const _fields = [
{
header: __( 'Preview' ),
id: 'preview',
render: ( { item } ) => {
return <Preview item={ item } viewType={ view.type } />;
},
minWidth: 120,
maxWidth: 120,
enableSorting: false,
},
{
header:
postType === TEMPLATE_POST_TYPE
? __( 'Template' )
: __( 'Template Part' ),
id: 'title',
getValue: ( { item } ) => item.title?.rendered,
render: ( { item } ) => (
<Title item={ item } viewType={ view.type } />
),
maxWidth: 400,
enableHiding: false,
},
];
if ( postType === TEMPLATE_POST_TYPE ) {
_fields.push( {
header: __( 'Description' ),
id: 'description',
render: ( { item } ) => {
return item.description ? (
<span className="page-templates-description">
{ decodeEntities( item.description ) }
</span>
) : (
view.type === LAYOUT_TABLE && (
<>
<Text variant="muted" aria-hidden="true">
—
</Text>
<VisuallyHidden>
{ __( 'No description.' ) }
</VisuallyHidden>
</>
)
);
},
maxWidth: 400,
minWidth: 320,
enableSorting: false,
} );
}
// TODO: The plan is to support fields reordering, which would require an API like `order` or something
// similar. With the aforementioned API we wouldn't need to construct the fields array like this.
_fields.push( {
header: __( 'Author' ),
id: 'author',
getValue: ( { item } ) => item.author_text,
render: ( { item } ) => {
return <AuthorField viewType={ view.type } item={ item } />;
},
type: ENUMERATION_TYPE,
elements: authors,
width: '1%',
} );
return _fields;
}, [ postType, authors, view.type ] );
const { data, paginationInfo } = useMemo( () => {
if ( ! records ) {
return {
data: EMPTY_ARRAY,
paginationInfo: { totalItems: 0, totalPages: 0 },
};
}
let filteredData = [ ...records ];
// Handle global search.
if ( view.search ) {
const normalizedSearch = normalizeSearchInput( view.search );
filteredData = filteredData.filter( ( item ) => {
const title = item.title?.rendered || item.slug;
return (
normalizeSearchInput( title ).includes(
normalizedSearch
) ||
normalizeSearchInput( item.description ).includes(
normalizedSearch
)
);
} );
}
// Handle filters.
if ( view.filters.length > 0 ) {
view.filters.forEach( ( filter ) => {
if (
filter.field === 'author' &&
filter.operator === OPERATOR_IS_ANY &&
filter?.value?.length > 0
) {
filteredData = filteredData.filter( ( item ) => {
return filter.value.includes( item.author_text );
} );
} else if (
filter.field === 'author' &&
filter.operator === OPERATOR_IS_NONE &&
filter?.value?.length > 0
) {
filteredData = filteredData.filter( ( item ) => {
return ! filter.value.includes( item.author_text );
} );
}
} );
}
// Handle sorting.
if ( view.sort ) {
filteredData = sortByTextFields( {
data: filteredData,
view,
fields,
textFields: [ 'title', 'author' ],
} );
}
// Handle pagination.
return getPaginationResults( {
data: filteredData,
view,
} );
}, [ records, view, fields ] );
const resetTemplateAction = useResetTemplateAction();
const actions = useMemo(
() => [
resetTemplateAction,
renameTemplateAction,
postRevisionsAction,
deleteTemplateAction,
],
[ resetTemplateAction ]
);
const onChangeView = useCallback(
( newView ) => {
if ( newView.type !== view.type ) {
newView = {
...newView,
layout: {
...defaultConfigPerViewType[ newView.type ],
},
};
history.push( {
...params,
layout: newView.type,
} );
}
setView( newView );
},
[ view.type, setView, history, params ]
);
return (
<Page
className="edit-site-page-template-template-parts-dataviews"
title={
postType === TEMPLATE_POST_TYPE
? __( 'Templates' )
: __( 'Template Parts' )
}
actions={
postType === TEMPLATE_POST_TYPE ? (
<AddNewTemplate
templateType={ postType }
showIcon={ false }
toggleProps={ { variant: 'primary' } }
/>
) : (
<AddNewTemplatePart />
)
}
>
<DataViews
paginationInfo={ paginationInfo }
fields={ fields }
actions={ actions }
data={ data }
isLoading={ isLoadingData }
view={ view }
onChangeView={ onChangeView }
onSelectionChange={ onSelectionChange }
deferredRendering={ ! view.hiddenFields?.includes( 'preview' ) }
/>
</Page>
);
}