This repository has been archived by the owner on Apr 3, 2021. It is now read-only.
/
wordpress-post-list.js
296 lines (248 loc) · 7.49 KB
/
wordpress-post-list.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
/*
* WordPressPostList custom element module.
*
* This custom element extends PostList and represents a higher order
* variant specific to WordPress. It will automatically include posts
* from the WordPress database, queried via parameters defined as
* attributes. It automatically appends each post found as a PostListItem
* element.
*
* Web Components in Gutenberg, Copyright 2019 Google LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
import PostList from './post-list.js';
// Tries to determine the WordPress REST API root URL.
const restRoot = ( () => {
if ( window.wpRestRoot ) {
return window.wpRestRoot;
}
const apiLink = document.querySelector( 'link[rel="https://api.w.org/"]' );
if ( apiLink ) {
return apiLink.getAttribute( 'href' );
}
return document.location.origin + '/wp-json/';
} )();
// Formats a given date in the given dateFormat, if the respective WordPress API is loaded.
const formatDate = ( dateFormat, date ) => {
if ( ! window.wp || ! window.wp.date ) {
return date;
}
if ( 'c' === dateFormat ) {
return window.wp.date.format( 'c', date );
}
return window.wp.date.dateI18n( dateFormat, date );
};
// Returns a PostListItem element created for the given post object from the WordPress REST
// API. If dateFormat is passed, the PostListItem will also include the post date.
const getPostListItem = ( post, dateFormat ) => {
const item = document.createElement( 'wcig-post-list-item' );
if ( post.link ) {
item.setAttribute( 'href', post.link );
}
item.innerHTML = post.title.rendered;
if ( dateFormat ) {
const time = document.createElement( 'time' );
time.setAttribute( 'slot', 'extra' );
time.setAttribute( 'date-time', formatDate( 'c', post.date_gmt ) );
time.innerHTML = formatDate( dateFormat, post.date_gmt );
item.appendChild( time );
}
return item;
};
// Wraps the regular window.fetch function in a way which allows delaying the request.
const fetch = ( ...args ) => {
const context = this;
if ( ! args[1] || ! args[1].delay ) {
return window.fetch.apply( context, args );
}
const delay = args[1].delay;
return new Promise( ( resolve, reject ) => {
let timer = setTimeout( async () => {
timer = 0;
try {
resolve( await window.fetch.apply( context, args ) );
} catch ( err ) {
reject( err );
}
}, delay );
if ( args[1] && args[1].signal ) {
args[1].signal.addEventListener( 'abort', () => {
if ( timer ) {
clearTimeout( timer );
timer = 0;
// Use 'DOMException' since this is the default fetch rejection on abort too.
reject( 'DOMException' );
}
});
}
} );
};
const loaderTemplate = document.createElement( 'template' );
loaderTemplate.innerHTML = `
<span class="loader">Loading...</span>
`;
class WordPressPostList extends PostList {
constructor() {
super();
this._loading = false;
this._controller = undefined;
this._posts = [];
}
static get is() {
return 'wcig-wordpress-post-list';
}
static get observedAttributes() {
return [ 'display-date', 'order', 'orderby', 'categories', 'number' ];
}
attributeChangedCallback( name, oldValue, newValue ) {
switch ( name ) {
case 'display-date':
this.updateContent();
break;
case 'order':
case 'orderby':
case 'categories':
case 'number':
this.queryPosts();
break;
}
}
connectedCallback() {
super.connectedCallback();
this.queryPosts();
}
async queryPosts() {
let url = restRoot + `wp/v2/posts?per_page=${ this.getAttribute( 'number' ) || 10 }`;
if ( this.hasAttribute( 'categories' ) ) {
url += `&categories=${ this.getAttribute( 'categories' ) }`;
}
if ( this.hasAttribute( 'order' ) ) {
url += `&order=${ this.getAttribute( 'order' ) }`;
}
if ( this.hasAttribute( 'orderby' ) ) {
url += `&orderby=${ this.getAttribute( 'orderby' ) }`;
}
this._loading = true;
// If another API request already on the way, abort it through its controller as it's out of date.
if ( this._controller ) {
this._controller.abort();
}
// Instantiate an AbortController that allows to abort our new API request if needed (see above).
this._controller = new AbortController();
this._posts = [];
this.updateContent();
try {
const response = await fetch( url, {
// Allow aborting the API request when a new one is initiated that would override it anyway.
signal: this._controller.signal,
// Delay the API request by 50 milliseconds so that it doesn't unnecessarily fire if multiple attribute changes cause multiple updates.
delay: 50,
} );
if ( response.status !== 200 ) {
throw response.status;
}
this._loading = false;
this._controller = undefined;
this._posts = await response.json();
this.updateContent();
} catch ( err ) {
// If 'DOMException', the request was intentionally aborted, so it is not a real error.
if ( 'DOMException' !== err ) {
console.error( 'unable to fetch posts', err );
}
this._loading = false;
this._controller = undefined;
this.updateContent();
}
}
updateContent() {
this.innerHTML = '';
// If in loading state, display the loader and bail.
if ( this._loading ) {
if ( ! this.shadowRoot.querySelector( '.loader' ) ) {
this.shadowRoot.appendChild( loaderTemplate.content.cloneNode( true ) );
}
return;
}
// Remove the loader.
const loader = this.shadowRoot.querySelector( '.loader' );
if ( loader ) {
this.shadowRoot.removeChild( loader );
}
if ( ! this._posts || ! this._posts.length ) {
return;
}
// Determine whether to display post dates and which date format to use.
let dateFormat = undefined;
if ( this.hasAttribute( 'display-date' ) ) {
dateFormat = this.getAttribute( 'display-date' );
if ( ! dateFormat.length ) {
dateFormat = window.wp && window.wp.date && window.wp.date.__experimentalGetSettings ? window.wp.date.__experimentalGetSettings().formats.date : 'F m, Y';
}
}
// Append a PostListItem for each post.
this._posts.forEach( post => {
this.appendChild( getPostListItem( post, dateFormat ) );
} );
}
get displayDate() {
return this.getAttribute( 'display-date' );
}
set displayDate( val ) {
if ( null !== val ) {
this.setAttribute( 'display-date', val );
} else {
this.removeAttribute( 'display-date' );
}
}
get order() {
return this.getAttribute( 'order' );
}
set order( val ) {
if ( null !== val ) {
this.setAttribute( 'order', val );
} else {
this.removeAttribute( 'order' );
}
}
get orderby() {
return this.getAttribute( 'orderby' );
}
set orderby( val ) {
if ( null !== val ) {
this.setAttribute( 'orderby', val );
} else {
this.removeAttribute( 'orderby' );
}
}
get categories() {
return this.getAttribute( 'categories' );
}
set categories( val ) {
if ( null !== val ) {
this.setAttribute( 'categories', val );
} else {
this.removeAttribute( 'categories' );
}
}
get number() {
return this.getAttribute( 'number' );
}
set number( val ) {
if ( null !== val ) {
this.setAttribute( 'number', val );
} else {
this.removeAttribute( 'number' );
}
}
}
export default WordPressPostList;