-
Notifications
You must be signed in to change notification settings - Fork 134
/
WordPressTemplate.tsx
306 lines (252 loc) · 7.77 KB
/
WordPressTemplate.tsx
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
import { QueryOptions } from '@apollo/client';
// eslint-disable-next-line import/extensions
import { print } from '@apollo/client/utilities';
import { sha256 } from 'js-sha256';
import React, {
PropsWithChildren,
useContext,
useEffect,
useState,
} from 'react';
import { getApolloAuthClient, getApolloClient } from '../client.js';
import { getConfig } from '../config/index.js';
import { getTemplate } from '../getTemplate.js';
import { useAuth } from '../hooks/useAuth.js';
import { SEED_QUERY, SeedNode } from '../queries/seedQuery.js';
import { FaustContext, FaustQueries } from '../store/FaustContext.js';
import { getQueryParam } from '../utils/convert.js';
import { isWordPressPreview } from '../utils/isWordPressPreview.js';
export type FaustProps = {
__SEED_NODE__?: SeedNode | null;
__FAUST_QUERIES__?: FaustQueries | null;
__TEMPLATE_QUERY_DATA__?: any | null;
__TEMPLATE_VARIABLES__?: { [key: string]: any } | null;
};
export type WordPressTemplateProps = PropsWithChildren<FaustProps>;
/**
* This is an external type for end users.
* @external
*/
export type FaustTemplateProps<Data, Props = Record<string, never>> = Props & {
data?: Data;
loading?: boolean;
__SEED_NODE__?: SeedNode | null;
__TEMPLATE_QUERY_DATA__?: any | null;
__TEMPLATE_VARIABLES__?: { [key: string]: any };
};
export function WordPressTemplateInternal(
props: WordPressTemplateProps & {
seedNode: SeedNode;
isPreview: boolean;
isAuthenticated: boolean | null;
loading: boolean;
setLoading: (loading: boolean) => void;
},
) {
const { templates } = getConfig();
if (!templates) {
throw new Error('Templates are required. Please add them to your config.');
}
const {
seedNode,
isAuthenticated,
isPreview,
__TEMPLATE_QUERY_DATA__: templateQueryDataProp,
loading,
setLoading,
...wordpressTemplateProps
} = props;
const template = getTemplate(seedNode, templates);
const [data, setData] = useState<any | null>(templateQueryDataProp);
const { setQueries } = useContext(FaustContext) || {};
if (template && template.queries && template.query) {
throw new Error(
'`Only either `Component.query` or `Component.queries` can be provided, but not both.',
);
}
/**
* Fetch the template's queries if defined.
*/
useEffect(() => {
void (async () => {
const client = isPreview ? getApolloAuthClient() : getApolloClient();
if (!template) {
return;
}
if (template.query) {
return;
}
if (!template.queries) {
return;
}
if (!setQueries) {
return;
}
let queries: FaustQueries | null = null;
const queryCalls = template.queries.map(({ query, variables }) => {
const queryVariables = variables
? variables(seedNode, { asPreview: isPreview })
: undefined;
return client.query({
query,
variables: queryVariables,
});
});
const queriesRes = await Promise.all(queryCalls);
queries = {};
queriesRes.forEach((queryRes, index) => {
if (queries && template.queries) {
queries[sha256(print(template.queries[index].query))] = queryRes.data;
}
});
setQueries(queries);
setLoading(false);
})();
}, [isAuthenticated, isPreview, seedNode, template, setQueries, setLoading]);
/**
* Fetch the template's query if defined.
*/
useEffect(() => {
void (async () => {
const client = isPreview ? getApolloAuthClient() : getApolloClient();
if (!template || !template?.query || template?.queries || !seedNode) {
return;
}
if (data) {
return;
}
setLoading(true);
const queryArgs: QueryOptions = {
query: template?.query,
variables: template?.variables
? template?.variables(seedNode, { asPreview: isPreview })
: undefined,
};
const templateQueryRes = await client.query(queryArgs);
setData(templateQueryRes.data);
setLoading(false);
})();
}, [data, template, seedNode, isPreview, isAuthenticated, setLoading]);
if (!template) {
return null;
}
const Component = template as React.FC<{ [key: string]: any }>;
const newProps = {
...wordpressTemplateProps,
__TEMPLATE_QUERY_DATA__: templateQueryDataProp,
data,
loading,
};
return React.createElement(Component, newProps, null);
}
export function WordPressTemplate(props: WordPressTemplateProps) {
const { basePath, templates } = getConfig();
if (!templates) {
throw new Error('Templates are required. Please add them to your config.');
}
const {
__SEED_NODE__: seedNodeProp,
__TEMPLATE_QUERY_DATA__: templateQueryDataProp,
} = props;
const [seedNode, setSeedNode] = useState<SeedNode | null>(
seedNodeProp ?? null,
);
const template = getTemplate(seedNode, templates);
const [loading, setLoading] = useState(template === null);
const [isPreview, setIsPreview] = useState<boolean | null>(
templateQueryDataProp ? false : null,
);
const { isAuthenticated, loginUrl } = useAuth({
strategy: 'redirect',
shouldRedirect: false,
skip: !isPreview,
});
/**
* Determine if the URL we are on is for previews
*/
useEffect(() => {
if (!window) {
return;
}
setIsPreview(isWordPressPreview(window.location.search));
}, []);
/**
* If we are on a preview route and there is no authenticated user, redirect
* them to the login page
*/
useEffect(() => {
if (!window) {
return;
}
if (isPreview && isAuthenticated === false && loginUrl) {
window.location.assign(loginUrl);
}
}, [isAuthenticated, isPreview, loginUrl]);
/**
* Execute the seed query.
*
* If the seed query was not available via a prop, it was not executed on the
* server, meaning we are either dealing with a CSR page, or a preview page.
*/
useEffect(() => {
if (isPreview === null) {
return;
}
if (isPreview && !isAuthenticated) {
return;
}
if (seedNode) {
return;
}
void (async () => {
const client = isPreview ? getApolloAuthClient() : getApolloClient();
let seedQueryUri = window.location.href.replace(
window.location.origin,
'',
);
let databaseId = '';
if (isPreview) {
seedQueryUri = getQueryParam(window.location.href, 'previewPathname');
databaseId = getQueryParam(window.location.href, 'p');
// If a user includes a base path, it will be part of the uri query that we need to filter out
if (basePath) {
seedQueryUri = seedQueryUri.replace(basePath, '');
}
if (seedQueryUri === '') {
throw new Error(
'The URL must contain the proper "previewPathname" query param for previews.',
);
}
}
const queryArgs: QueryOptions = {
query: SEED_QUERY,
variables: {
// Conditionally add relevant query args.
...(!isPreview && { uri: seedQueryUri }),
...(isPreview && { id: databaseId }),
...(isPreview && { asPreview: true }),
},
};
setLoading(true);
const seedQueryRes = await client.query(queryArgs);
const node = isPreview
? (seedQueryRes?.data?.contentNode as SeedNode)
: (seedQueryRes?.data?.nodeByUri as SeedNode);
setSeedNode(node);
})();
}, [seedNode, isPreview, isAuthenticated, basePath]);
if (!seedNode || (isPreview && !isAuthenticated)) {
return null;
}
return (
<WordPressTemplateInternal
// eslint-disable-next-line react/jsx-props-no-spreading
{...props}
seedNode={seedNode}
isPreview={isPreview === true}
isAuthenticated={isAuthenticated === true}
loading={loading}
setLoading={setLoading}
/>
);
}