generated from adobe/aem-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathscripts.js
358 lines (315 loc) · 10.3 KB
/
scripts.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
import { initConfigField, updateConfig } from '../../utils/config/config.js';
function getFormData(form) {
const data = {};
[...form.elements].forEach((field) => {
const { name, type } = field;
const value = !field.value && field.dataset.defaultValue
? field.dataset.defaultValue : field.value;
if (name && type && value) {
switch (type) {
// parse number and range as floats
case 'number':
case 'range':
data[name] = parseFloat(value, 10);
break;
// convert date and datetime-local to date objects
case 'date':
case 'datetime-local':
data[name] = new Date(value);
break;
// store checked checkbox values in array
case 'checkbox':
if (field.checked) {
if (data[name]) data[name].push(value);
else data[name] = [value];
}
break;
// only store checked radio
case 'radio':
if (field.checked) data[name] = value;
break;
// convert url to url object
case 'url':
data[name] = new URL(value);
break;
// store file filelist objects
case 'file':
data[name] = field.files;
break;
default:
data[name] = value;
}
}
});
return data;
}
function disableForm(form) {
[...form.elements].forEach((el) => {
el.disabled = true;
});
}
function enableForm(form) {
[...form.elements].forEach((el) => {
el.disabled = false;
});
}
function clearResults(table) {
const tbody = table.querySelector('tbody.results');
tbody.replaceChildren();
const caption = table.querySelector('caption');
caption.setAttribute('aria-hidden', true);
}
function updateTableError(table, errCode, org, site) {
const { title, msg } = (() => {
switch (errCode) {
case 401:
return {
title: '401 Unauthorized Error',
msg: `Unable to display results. <a target="_blank" href="https://main--${site}--${org}.aem.page">Sign in to the ${site} project sidekick</a> to view the results.`,
};
case 404:
return {
title: '404 Not Found Error',
msg: 'Unable to display results. Ensure your sitemap/index path is correct.',
};
case 499:
return {
title: 'Initial Fetch Failed',
msg: 'This is likely due to CORS. Either use a CORS allow plugin or add a header <code>Access-Control-Allow-Origin: https://labs.aem.live</code> in your site config.',
};
default:
return {
title: 'Error',
msg: 'Unable to display results. Please check the console for more information.',
};
}
})();
table.querySelectorAll('tbody').forEach((tbody) => {
if (tbody.classList.contains('error')) {
tbody.setAttribute('aria-hidden', 'false');
tbody.querySelector('.error-title').textContent = title;
tbody.querySelector('.error-msg').innerHTML = msg;
} else {
tbody.setAttribute('aria-hidden', 'true');
}
});
}
function displayResult(url, matches, org, site) {
const tr = document.createElement('tr');
tr.innerHTML = `
<td><a href="${url.href}" target="_blank">${url.href}</a> (<a class="edit-link" href="#">Edit</a>)</td>
<td>${matches}</td>
`;
const editLink = tr.querySelector('a.edit-link');
editLink.addEventListener('click', async (e) => {
e.preventDefault();
if (editLink.classList.contains('disabled')) return;
if (editLink.getAttribute('href') !== '#') {
window.open(editLink.href);
return;
}
try {
const statusRes = await fetch(`https://admin.hlx.page/status/${org}/${site}/main${url.pathname}?editUrl=auto`);
const status = await statusRes.json();
const editUrl = status.edit && status.edit.url;
if (editUrl) {
editLink.href = editUrl;
window.open(editUrl);
} else {
throw new Error('admin did not return an edit url');
}
} catch (err) {
// eslint-disable-next-line no-console
console.error('failed to open edit link', err);
editLink.textContent = 'Error opening edit link';
editLink.classList.add('disabled');
}
});
return tr;
}
async function* fetchQueryIndex(queryIndexPath, liveHost) {
const limit = 512;
let offset = 0;
let more = true;
do {
let res;
try {
// eslint-disable-next-line no-await-in-loop
res = await fetch(`https://${liveHost}${queryIndexPath}?offset=${offset}&limit=${limit}`);
} catch (err) {
throw new Error('Failed on initial fetch of index.', err);
}
if (!res.ok) {
throw new Error(`Not found: ${queryIndexPath}`);
}
// eslint-disable-next-line no-await-in-loop
const json = await res.json();
offset += limit;
more = json.data.length > 0;
for (let i = 0; i < json.data.length; i += 1) {
const item = json.data[i];
const url = new URL(item.path, `https://${liveHost}`);
url.host = liveHost;
yield url;
}
} while (more);
}
async function* fetchSitemap(sitemapPath, liveHost) {
let res;
try {
res = await fetch(`https://${liveHost}${sitemapPath}`);
if (!res.ok) {
throw new Error(`Not found: ${sitemapPath}`);
}
} catch (err) {
throw new Error('Failed on initial fetch of sitemap.', err);
}
const xml = await res.text();
const parser = new DOMParser();
const doc = parser.parseFromString(xml, 'application/xml');
const sitemapLocs = doc.querySelectorAll('sitemap > loc');
for (let i = 0; i < sitemapLocs.length; i += 1) {
const loc = sitemapLocs[i];
const liveUrl = new URL(loc.textContent);
const resucrsiveResults = fetchSitemap(liveUrl.pathname, liveHost);
// eslint-disable-next-line no-restricted-syntax, no-await-in-loop
for await (const url of resucrsiveResults) {
yield url;
}
}
const urlLocs = doc.querySelectorAll('url > loc');
for (let i = 0; i < urlLocs.length; i += 1) {
const loc = urlLocs[i];
const url = new URL(loc.textContent, `https://${liveHost}`);
url.host = liveHost;
yield url;
}
}
/**
* query the page for matches
*
* @param {URL} url the url to query
* @param {string} query the query string
* @param {string} queryType the query type
*/
async function queryPage(url, query, queryType) {
const res = await fetch(url);
const html = await res.text();
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
if (queryType === 'selector') {
const elements = doc.querySelectorAll(query);
return elements.length;
}
const body = doc.querySelector('body');
const text = body.textContent;
const matches = text.match(new RegExp(query, 'gi'));
return matches ? matches.length : 0;
}
async function processUrl(sitemapUrl, query, queryType, org, site) {
const matches = await queryPage(sitemapUrl, query, queryType);
if (matches > 0) {
return displayResult(sitemapUrl, matches, org, site);
}
return null;
}
function updateCaption(caption, found, searched) {
caption.querySelector('.results-found').textContent = found;
caption.querySelector('.results-of').textContent = searched;
}
/**
* Fetches the live and preview host URLs for org/site.
* @param {string} org - Organization name.
* @param {string} site - Site name within org.
* @returns {Promise<>} Object with `live` and `preview` hostnames.
*/
async function fetchHosts(org, site) {
let status;
try {
const url = `https://admin.hlx.page/status/${org}/${site}/main`;
const res = await fetch(url);
status = res.status;
const json = await res.json();
return {
status,
live: new URL(json.live.url).host,
preview: new URL(json.preview.url).host,
};
} catch (error) {
return {
status,
live: null,
preview: null,
};
}
}
async function init(doc) {
doc.querySelector('.site-query').dataset.status = 'loading';
await initConfigField();
const form = doc.querySelector('#search-form');
const table = doc.querySelector('.table table');
const results = table.querySelector('tbody.results');
const error = table.querySelector('tbody.error');
const noResults = table.querySelector('tbody.no-results');
form.addEventListener('submit', async (e) => {
e.preventDefault();
results.setAttribute('aria-hidden', 'false');
error.setAttribute('aria-hidden', 'true');
noResults.setAttribute('aria-hidden', 'true');
const {
org, site, query, sitemap, queryType, path,
} = getFormData(form);
try {
clearResults(table);
disableForm(form);
// fetch host config
const { status, live } = await fetchHosts(org, site);
if (!live || status !== 200) {
updateTableError(table, status, org, site);
return;
}
updateConfig();
const sitemapUrls = sitemap.endsWith('.json') ? fetchQueryIndex(sitemap, live) : fetchSitemap(sitemap, live);
let searched = 0;
const caption = table.querySelector('caption');
caption.setAttribute('aria-hidden', false);
caption.querySelector('.term').textContent = query;
caption.querySelector('.results-found').textContent = 0;
caption.querySelector('.results-of').textContent = 0;
// eslint-disable-next-line no-restricted-syntax
for await (const sitemapUrl of sitemapUrls) {
if (sitemapUrl.pathname.startsWith(path)) {
searched += 1;
processUrl(sitemapUrl, query, queryType, org, site).then((tr) => {
if (tr) {
results.append(tr);
}
});
}
updateCaption(caption, results.children.length, searched);
}
updateCaption(caption, results.children.length, searched);
if (results.children.length === 0) {
noResults.setAttribute('aria-hidden', 'false');
results.setAttribute('aria-hidden', 'true');
}
} catch (err) {
// eslint-disable-next-line no-console
console.error(err);
if (err.message.startsWith('Failed on initial fetch')) {
updateTableError(table, 499, org, site);
} else if (err.message.startsWith('Not found')) {
updateTableError(table, 404, org, site);
} else {
updateTableError(table, 500, org, site);
}
} finally {
enableForm(form);
}
});
form.addEventListener('reset', () => {
clearResults(table);
});
doc.querySelector('.site-query').dataset.status = 'loaded';
}
init(document);