-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
server-side-render.js
233 lines (206 loc) · 5.78 KB
/
server-side-render.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
/**
* External dependencies
*/
import { isEqual } from 'lodash';
/**
* WordPress dependencies
*/
import { useDebounce, usePrevious } from '@wordpress/compose';
import { RawHTML, useEffect, useRef, useState } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';
import { addQueryArgs } from '@wordpress/url';
import { Placeholder, Spinner } from '@wordpress/components';
import { __experimentalSanitizeBlockAttributes } from '@wordpress/blocks';
const EMPTY_OBJECT = {};
export function rendererPath( block, attributes = null, urlQueryArgs = {} ) {
return addQueryArgs( `/wp/v2/block-renderer/${ block }`, {
context: 'edit',
...( null !== attributes ? { attributes } : {} ),
...urlQueryArgs,
} );
}
export function removeBlockSupportAttributes( attributes ) {
const {
backgroundColor,
borderColor,
fontFamily,
fontSize,
gradient,
textColor,
className,
...restAttributes
} = attributes;
const { border, color, elements, spacing, typography, ...restStyles } =
attributes?.style || EMPTY_OBJECT;
return {
...restAttributes,
style: restStyles,
};
}
function DefaultEmptyResponsePlaceholder( { className } ) {
return (
<Placeholder className={ className }>
{ __( 'Block rendered as empty.' ) }
</Placeholder>
);
}
function DefaultErrorResponsePlaceholder( { response, className } ) {
const errorMessage = sprintf(
// translators: %s: error message describing the problem
__( 'Error loading block: %s' ),
response.errorMsg
);
return <Placeholder className={ className }>{ errorMessage }</Placeholder>;
}
function DefaultLoadingResponsePlaceholder( { children, showLoader } ) {
return (
<div style={ { position: 'relative' } }>
{ showLoader && (
<div
style={ {
position: 'absolute',
top: '50%',
left: '50%',
marginTop: '-9px',
marginLeft: '-9px',
} }
>
<Spinner />
</div>
) }
<div style={ { opacity: showLoader ? '0.3' : 1 } }>
{ children }
</div>
</div>
);
}
export default function ServerSideRender( props ) {
const {
attributes,
block,
className,
httpMethod = 'GET',
urlQueryArgs,
skipBlockSupportAttributes = false,
EmptyResponsePlaceholder = DefaultEmptyResponsePlaceholder,
ErrorResponsePlaceholder = DefaultErrorResponsePlaceholder,
LoadingResponsePlaceholder = DefaultLoadingResponsePlaceholder,
} = props;
const isMountedRef = useRef( true );
const [ showLoader, setShowLoader ] = useState( false );
const fetchRequestRef = useRef();
const [ response, setResponse ] = useState( null );
const prevProps = usePrevious( props );
const [ isLoading, setIsLoading ] = useState( false );
function fetchData() {
if ( ! isMountedRef.current ) {
return;
}
setIsLoading( true );
let sanitizedAttributes =
attributes &&
__experimentalSanitizeBlockAttributes( block, attributes );
if ( skipBlockSupportAttributes ) {
sanitizedAttributes =
removeBlockSupportAttributes( sanitizedAttributes );
}
// If httpMethod is 'POST', send the attributes in the request body instead of the URL.
// This allows sending a larger attributes object than in a GET request, where the attributes are in the URL.
const isPostRequest = 'POST' === httpMethod;
const urlAttributes = isPostRequest
? null
: sanitizedAttributes ?? null;
const path = rendererPath( block, urlAttributes, urlQueryArgs );
const data = isPostRequest
? { attributes: sanitizedAttributes ?? null }
: null;
// Store the latest fetch request so that when we process it, we can
// check if it is the current request, to avoid race conditions on slow networks.
const fetchRequest = ( fetchRequestRef.current = apiFetch( {
path,
data,
method: isPostRequest ? 'POST' : 'GET',
} )
.then( ( fetchResponse ) => {
if (
isMountedRef.current &&
fetchRequest === fetchRequestRef.current &&
fetchResponse
) {
setResponse( fetchResponse.rendered );
}
} )
.catch( ( error ) => {
if (
isMountedRef.current &&
fetchRequest === fetchRequestRef.current
) {
setResponse( {
error: true,
errorMsg: error.message,
} );
}
} )
.finally( () => {
if (
isMountedRef.current &&
fetchRequest === fetchRequestRef.current
) {
setIsLoading( false );
}
} ) );
return fetchRequest;
}
const debouncedFetchData = useDebounce( fetchData, 500 );
// When the component unmounts, set isMountedRef to false. This will
// let the async fetch callbacks know when to stop.
useEffect(
() => () => {
isMountedRef.current = false;
},
[]
);
useEffect( () => {
// Don't debounce the first fetch. This ensures that the first render
// shows data as soon as possible.
if ( prevProps === undefined ) {
fetchData();
} else if ( ! isEqual( prevProps, props ) ) {
debouncedFetchData();
}
} );
/**
* Effect to handle showing the loading placeholder.
* Show it only if there is no previous response or
* the request takes more than one second.
*/
useEffect( () => {
if ( ! isLoading ) {
return;
}
const timeout = setTimeout( () => {
setShowLoader( true );
}, 1000 );
return () => clearTimeout( timeout );
}, [ isLoading ] );
const hasResponse = !! response;
const hasEmptyResponse = response === '';
const hasError = response?.error;
if ( isLoading ) {
return (
<LoadingResponsePlaceholder { ...props } showLoader={ showLoader }>
{ hasResponse && (
<RawHTML className={ className }>{ response }</RawHTML>
) }
</LoadingResponsePlaceholder>
);
}
if ( hasEmptyResponse || ! hasResponse ) {
return <EmptyResponsePlaceholder { ...props } />;
}
if ( hasError ) {
return <ErrorResponsePlaceholder response={ response } { ...props } />;
}
return <RawHTML className={ className }>{ response }</RawHTML>;
}