-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
edit.js
307 lines (291 loc) · 7.76 KB
/
edit.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
/**
* External dependencies
*/
import clsx from 'clsx';
/**
* WordPress dependencies
*/
import { memo, useMemo, useState } from '@wordpress/element';
import { useSelect } from '@wordpress/data';
import { __, _x } from '@wordpress/i18n';
import {
BlockControls,
BlockContextProvider,
__experimentalUseBlockPreview as useBlockPreview,
useBlockProps,
useInnerBlocksProps,
store as blockEditorStore,
} from '@wordpress/block-editor';
import { Spinner, ToolbarGroup } from '@wordpress/components';
import { store as coreStore } from '@wordpress/core-data';
import { list, grid } from '@wordpress/icons';
const TEMPLATE = [
[ 'core/post-title' ],
[ 'core/post-date' ],
[ 'core/post-excerpt' ],
];
function PostTemplateInnerBlocks( { classList } ) {
const innerBlocksProps = useInnerBlocksProps(
{ className: clsx( 'wp-block-post', classList ) },
{ template: TEMPLATE, __unstableDisableLayoutClassNames: true }
);
return <li { ...innerBlocksProps } />;
}
function PostTemplateBlockPreview( {
blocks,
blockContextId,
classList,
isHidden,
setActiveBlockContextId,
} ) {
const blockPreviewProps = useBlockPreview( {
blocks,
props: {
className: clsx( 'wp-block-post', classList ),
},
} );
const handleOnClick = () => {
setActiveBlockContextId( blockContextId );
};
const style = {
display: isHidden ? 'none' : undefined,
};
return (
<li
{ ...blockPreviewProps }
tabIndex={ 0 }
// eslint-disable-next-line jsx-a11y/no-noninteractive-element-to-interactive-role
role="button"
onClick={ handleOnClick }
onKeyPress={ handleOnClick }
style={ style }
/>
);
}
const MemoizedPostTemplateBlockPreview = memo( PostTemplateBlockPreview );
export default function PostTemplateEdit( {
setAttributes,
clientId,
context: {
query: {
perPage,
offset = 0,
postType,
order,
orderBy,
author,
search,
exclude,
sticky,
inherit,
taxQuery,
parents,
pages,
// We gather extra query args to pass to the REST API call.
// This way extenders of Query Loop can add their own query args,
// and have accurate previews in the editor.
// Noting though that these args should either be supported by the
// REST API or be handled by custom REST filters like `rest_{$this->post_type}_query`.
...restQueryArgs
} = {},
templateSlug,
previewPostType,
},
attributes: { layout },
__unstableLayoutClassNames,
} ) {
const { type: layoutType, columnCount = 3 } = layout || {};
const [ activeBlockContextId, setActiveBlockContextId ] = useState();
const { posts, blocks } = useSelect(
( select ) => {
const { getEntityRecords, getTaxonomies } = select( coreStore );
const { getBlocks } = select( blockEditorStore );
const templateCategory =
inherit &&
templateSlug?.startsWith( 'category-' ) &&
getEntityRecords( 'taxonomy', 'category', {
context: 'view',
per_page: 1,
_fields: [ 'id' ],
slug: templateSlug.replace( 'category-', '' ),
} );
const query = {
offset: offset || 0,
order,
orderby: orderBy,
};
// There is no need to build the taxQuery if we inherit.
if ( taxQuery && ! inherit ) {
const taxonomies = getTaxonomies( {
type: postType,
per_page: -1,
context: 'view',
} );
// We have to build the tax query for the REST API and use as
// keys the taxonomies `rest_base` with the `term ids` as values.
const builtTaxQuery = Object.entries( taxQuery ).reduce(
( accumulator, [ taxonomySlug, terms ] ) => {
const taxonomy = taxonomies?.find(
( { slug } ) => slug === taxonomySlug
);
if ( taxonomy?.rest_base ) {
accumulator[ taxonomy?.rest_base ] = terms;
}
return accumulator;
},
{}
);
if ( !! Object.keys( builtTaxQuery ).length ) {
Object.assign( query, builtTaxQuery );
}
}
if ( perPage ) {
query.per_page = perPage;
}
if ( author ) {
query.author = author;
}
if ( search ) {
query.search = search;
}
if ( exclude?.length ) {
query.exclude = exclude;
}
if ( parents?.length ) {
query.parent = parents;
}
// If sticky is not set, it will return all posts in the results.
// If sticky is set to `only`, it will limit the results to sticky posts only.
// If it is anything else, it will exclude sticky posts from results. For the record the value stored is `exclude`.
if ( sticky ) {
query.sticky = sticky === 'only';
}
// If `inherit` is truthy, adjust conditionally the query to create a better preview.
if ( inherit ) {
// Change the post-type if needed.
if ( templateSlug?.startsWith( 'archive-' ) ) {
query.postType = templateSlug.replace( 'archive-', '' );
postType = query.postType;
} else if ( templateCategory ) {
query.categories = templateCategory[ 0 ]?.id;
}
}
// When we preview Query Loop blocks we should prefer the current
// block's postType, which is passed through block context.
const usedPostType = previewPostType || postType;
return {
posts: getEntityRecords( 'postType', usedPostType, {
...query,
...restQueryArgs,
} ),
blocks: getBlocks( clientId ),
};
},
[
perPage,
offset,
order,
orderBy,
clientId,
author,
search,
postType,
exclude,
sticky,
inherit,
templateSlug,
taxQuery,
parents,
restQueryArgs,
previewPostType,
]
);
const blockContexts = useMemo(
() =>
posts?.map( ( post ) => ( {
postType: post.type,
postId: post.id,
classList: post.class_list ?? '',
} ) ),
[ posts ]
);
const blockProps = useBlockProps( {
className: clsx( __unstableLayoutClassNames, {
[ `columns-${ columnCount }` ]:
layoutType === 'grid' && columnCount, // Ensure column count is flagged via classname for backwards compatibility.
} ),
} );
if ( ! posts ) {
return (
<p { ...blockProps }>
<Spinner />
</p>
);
}
if ( ! posts.length ) {
return <p { ...blockProps }> { __( 'No results found.' ) }</p>;
}
const setDisplayLayout = ( newDisplayLayout ) =>
setAttributes( {
layout: { ...layout, ...newDisplayLayout },
} );
const displayLayoutControls = [
{
icon: list,
title: _x( 'List view', 'Post template block display setting' ),
onClick: () => setDisplayLayout( { type: 'default' } ),
isActive: layoutType === 'default' || layoutType === 'constrained',
},
{
icon: grid,
title: _x( 'Grid view', 'Post template block display setting' ),
onClick: () =>
setDisplayLayout( {
type: 'grid',
columnCount,
} ),
isActive: layoutType === 'grid',
},
];
// To avoid flicker when switching active block contexts, a preview is rendered
// for each block context, but the preview for the active block context is hidden.
// This ensures that when it is displayed again, the cached rendering of the
// block preview is used, instead of having to re-render the preview from scratch.
return (
<>
<BlockControls>
<ToolbarGroup controls={ displayLayoutControls } />
</BlockControls>
<ul { ...blockProps }>
{ blockContexts &&
blockContexts.map( ( blockContext ) => (
<BlockContextProvider
key={ blockContext.postId }
value={ blockContext }
>
{ blockContext.postId ===
( activeBlockContextId ||
blockContexts[ 0 ]?.postId ) ? (
<PostTemplateInnerBlocks
classList={ blockContext.classList }
/>
) : null }
<MemoizedPostTemplateBlockPreview
blocks={ blocks }
blockContextId={ blockContext.postId }
classList={ blockContext.classList }
setActiveBlockContextId={
setActiveBlockContextId
}
isHidden={
blockContext.postId ===
( activeBlockContextId ||
blockContexts[ 0 ]?.postId )
}
/>
</BlockContextProvider>
) ) }
</ul>
</>
);
}