-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathdataviews-templates.js
360 lines (341 loc) · 9.03 KB
/
dataviews-templates.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
/**
* External dependencies
*/
import removeAccents from 'remove-accents';
/**
* WordPress dependencies
*/
import {
Icon,
__experimentalView as View,
__experimentalText as Text,
__experimentalHStack as HStack,
__experimentalVStack as VStack,
VisuallyHidden,
} from '@wordpress/components';
import { __, _x } from '@wordpress/i18n';
import { useState, useMemo, useCallback } 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 } from '@wordpress/dataviews';
/**
* Internal dependencies
*/
import Page from '../page';
import Link from '../routes/link';
import { useAddedBy, AvatarImage } from '../list/added-by';
import {
TEMPLATE_POST_TYPE,
ENUMERATION_TYPE,
OPERATOR_IN,
OPERATOR_NOT_IN,
LAYOUT_GRID,
LAYOUT_TABLE,
} from '../../utils/constants';
import {
useResetTemplateAction,
deleteTemplateAction,
renameTemplateAction,
} from './template-actions';
import usePatternSettings from '../page-patterns/use-pattern-settings';
import { unlock } from '../../lock-unlock';
const { ExperimentalBlockEditorProvider, useGlobalStyle } = unlock(
blockEditorPrivateApis
);
const EMPTY_ARRAY = [];
const defaultConfigPerViewType = {
[ LAYOUT_TABLE ]: {},
[ LAYOUT_GRID ]: {
mediaField: 'preview',
primaryField: 'title',
},
};
const DEFAULT_VIEW = {
type: LAYOUT_TABLE,
search: '',
page: 1,
perPage: 20,
// All fields are visible by default, so it's
// better to keep track of the hidden ones.
hiddenFields: [ 'preview' ],
layout: {},
filters: [],
};
function normalizeSearchInput( input = '' ) {
return removeAccents( input.trim().toLowerCase() );
}
// TODO: these are going to be reused in the template part list.
// That's the reason for leaving the template parts code for now.
function TemplateTitle( { item } ) {
const { isCustomized } = useAddedBy( item.type, item.id );
return (
<VStack spacing={ 1 }>
<View as="h3">
<Link
params={ {
postId: item.id,
postType: item.type,
canvas: 'edit',
} }
>
{ decodeEntities( item.title?.rendered || item.slug ) ||
__( '(no title)' ) }
</Link>
</View>
{ isCustomized && (
<span className="edit-site-list-added-by__customized-info">
{ item.type === TEMPLATE_POST_TYPE
? _x( 'Customized', 'template' )
: _x( 'Customized', 'template part' ) }
</span>
) }
</VStack>
);
}
function AuthorField( { item } ) {
const { text, icon, imageUrl } = useAddedBy( item.type, item.id );
return (
<HStack alignment="left" spacing={ 1 }>
{ imageUrl ? (
<AvatarImage imageUrl={ imageUrl } />
) : (
<div className="edit-site-list-added-by__icon">
<Icon icon={ icon } />
</div>
) }
<span>{ text }</span>
</HStack>
);
}
function TemplatePreview( { content, viewType } ) {
const settings = usePatternSettings();
const [ backgroundColor = 'white' ] = useGlobalStyle( 'color.background' );
const blocks = useMemo( () => {
return parse( content );
}, [ content ] );
if ( ! blocks?.length ) {
return null;
}
// 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 } }
>
<BlockPreview blocks={ blocks } />
</div>
</ExperimentalBlockEditorProvider>
);
}
export default function DataviewsTemplates() {
const [ view, setView ] = useState( DEFAULT_VIEW );
const { records: allTemplates, isResolving: isLoadingData } =
useEntityRecords( 'postType', TEMPLATE_POST_TYPE, {
per_page: -1,
} );
const authors = useMemo( () => {
if ( ! allTemplates ) {
return EMPTY_ARRAY;
}
const authorsSet = new Set();
allTemplates.forEach( ( template ) => {
authorsSet.add( template.author_text );
} );
return Array.from( authorsSet ).map( ( author ) => ( {
value: author,
label: author,
} ) );
}, [ allTemplates ] );
const fields = useMemo(
() => [
{
header: __( 'Preview' ),
id: 'preview',
render: ( { item } ) => {
return (
<TemplatePreview
content={ item.content.raw }
viewType={ view.type }
/>
);
},
minWidth: 120,
maxWidth: 120,
enableSorting: false,
},
{
header: __( 'Template' ),
id: 'title',
getValue: ( { item } ) => item.title?.rendered || item.slug,
render: ( { item } ) => <TemplateTitle item={ item } />,
maxWidth: 400,
enableHiding: false,
},
{
header: __( 'Description' ),
id: 'description',
getValue: ( { item } ) => item.description,
render: ( { item } ) => {
return item.description ? (
decodeEntities( item.description )
) : (
<>
<Text variant="muted" aria-hidden="true">
—
</Text>
<VisuallyHidden>
{ __( 'No description.' ) }
</VisuallyHidden>
</>
);
},
maxWidth: 200,
enableSorting: false,
},
{
header: __( 'Author' ),
id: 'author',
getValue: ( { item } ) => item.author_text,
render: ( { item } ) => {
return <AuthorField item={ item } />;
},
enableHiding: false,
type: ENUMERATION_TYPE,
elements: authors,
},
],
[ authors, view ]
);
const { shownTemplates, paginationInfo } = useMemo( () => {
if ( ! allTemplates ) {
return {
shownTemplates: EMPTY_ARRAY,
paginationInfo: { totalItems: 0, totalPages: 0 },
};
}
let filteredTemplates = [ ...allTemplates ];
// Handle global search.
if ( view.search ) {
const normalizedSearch = normalizeSearchInput( view.search );
filteredTemplates = filteredTemplates.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_IN &&
!! filter.value
) {
filteredTemplates = filteredTemplates.filter( ( item ) => {
return item.author_text === filter.value;
} );
} else if (
filter.field === 'author' &&
filter.operator === OPERATOR_NOT_IN &&
!! filter.value
) {
filteredTemplates = filteredTemplates.filter( ( item ) => {
return item.author_text !== filter.value;
} );
}
} );
}
// Handle sorting.
if ( view.sort ) {
const stringSortingFields = [ 'title', 'author' ];
const fieldId = view.sort.field;
if ( stringSortingFields.includes( fieldId ) ) {
const fieldToSort = fields.find( ( field ) => {
return field.id === fieldId;
} );
filteredTemplates.sort( ( a, b ) => {
const valueA = fieldToSort.getValue( { item: a } ) ?? '';
const valueB = fieldToSort.getValue( { item: b } ) ?? '';
return view.sort.direction === 'asc'
? valueA.localeCompare( valueB )
: valueB.localeCompare( valueA );
} );
}
}
// Handle pagination.
const start = ( view.page - 1 ) * view.perPage;
const totalItems = filteredTemplates?.length || 0;
filteredTemplates = filteredTemplates?.slice(
start,
start + view.perPage
);
return {
shownTemplates: filteredTemplates,
paginationInfo: {
totalItems,
totalPages: Math.ceil( totalItems / view.perPage ),
},
};
}, [ allTemplates, view, fields ] );
const resetTemplateAction = useResetTemplateAction();
const actions = useMemo(
() => [
resetTemplateAction,
deleteTemplateAction,
renameTemplateAction,
],
[ resetTemplateAction ]
);
const onChangeView = useCallback(
( viewUpdater ) => {
let updatedView =
typeof viewUpdater === 'function'
? viewUpdater( view )
: viewUpdater;
if ( updatedView.type !== view.type ) {
updatedView = {
...updatedView,
layout: {
...defaultConfigPerViewType[ updatedView.type ],
},
};
}
setView( updatedView );
},
[ view, setView ]
);
return (
<Page title={ __( 'Templates' ) }>
<DataViews
paginationInfo={ paginationInfo }
fields={ fields }
actions={ actions }
data={ shownTemplates }
getItemId={ ( item ) => item.id }
isLoading={ isLoadingData }
view={ view }
onChangeView={ onChangeView }
supportedLayouts={ [ LAYOUT_TABLE, LAYOUT_GRID ] }
deferredRendering={ ! view.hiddenFields?.includes( 'preview' ) }
/>
</Page>
);
}