generated from adobe/aem-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 208
Expand file tree
/
Copy pathgeneral.js
More file actions
390 lines (351 loc) · 14 KB
/
general.js
File metadata and controls
390 lines (351 loc) · 14 KB
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
import { html, signal, useEffect } from '../../../deps/htm-preact.js';
import { STATUS_TO_ICON_MAP, STRUCTURE_TITLES } from '../checks/constants.js';
import { runChecks as runStructureChecks } from '../checks/structure.js';
import userCanPublishPage from '../../../tools/utils/publish.js';
import { runChecks as runLocalizationChecks } from '../checks/localization.js';
const DEF_NOT_FOUND = 'Not found';
const DEF_NEVER = 'Never';
const NOT_FOUND = {
preview: { lastModified: DEF_NOT_FOUND },
live: { lastModified: DEF_NOT_FOUND },
};
const DA_DOMAIN = 'da.live';
const nonEDSContent = 'Non AEM EDS Content';
const EXCLUDED_PATHS = ['/tools/caas'];
const content = signal({});
const navResult = signal({ icon: 'purple', title: STRUCTURE_TITLES.navigation, description: 'Checking...' });
const footerResult = signal({ icon: 'purple', title: STRUCTURE_TITLES.footer, description: 'Checking...' });
const regionSelectorResult = signal({ icon: 'purple', title: STRUCTURE_TITLES.regionSelector, description: 'Checking...' });
const georoutingResult = signal({ icon: 'purple', title: STRUCTURE_TITLES.georouting, description: 'Checking...' });
const breadcrumbsResult = signal({ icon: 'purple', title: STRUCTURE_TITLES.breadcrumbs, description: 'Checking...' });
const localizationResult = signal({ icon: 'purple', title: 'Links', description: 'Checking...' });
const localizationIssues = signal([]);
const localizationClosed = signal(false);
async function getStructureResults() {
const signals = [
navResult,
footerResult,
regionSelectorResult,
georoutingResult,
breadcrumbsResult,
];
const checks = runStructureChecks({ area: document });
await Promise.all(checks.map((result, index) => Promise.resolve(result)
.then((res) => {
const icon = STATUS_TO_ICON_MAP[res.status] || 'orange';
signals[index].value = {
icon,
title: res.title,
description: res.description,
};
})
.catch((error) => {
signals[index].value = {
icon: 'red',
title: 'Error',
description: `Error: ${error.message}`,
};
})));
}
async function getLocalizationResults() {
try {
const [res] = await runLocalizationChecks({ area: document });
localizationResult.value = {
icon: STATUS_TO_ICON_MAP[res.status] || 'orange',
title: res.title,
description: res.description,
};
localizationIssues.value = res.details?.violations || [];
} catch (error) {
localizationResult.value = {
icon: 'red',
title: 'Links',
description: `Error: ${error.message}`,
};
}
}
function getAdminUrl(url, type) {
if (!(/adobecom\.(hlx|aem)./.test(url.hostname))) return false;
const project = url.hostname === 'localhost' ? 'main--milo--adobecom' : url.hostname.split('.')[0];
const [branch, repo, owner] = project.split('--');
const base = `https://admin.hlx.page/${type}/${owner}/${repo}/${branch}${url.pathname}`;
return type === 'status' ? `${base}?editUrl=auto` : base;
}
async function getStatus(url) {
const adminUrl = getAdminUrl(url, 'status');
if (!adminUrl) {
return {
url,
edit: null,
preview: nonEDSContent,
live: nonEDSContent,
publish: nonEDSContent,
externalUrl: url,
};
}
const resp = await fetch(adminUrl);
if (!resp.ok) return {};
const json = await resp.json();
const preview = json.preview.lastModified || DEF_NEVER;
const live = json.live.lastModified || DEF_NEVER;
const publish = await userCanPublishPage(json, false);
const { sourceLocation } = json.preview;
const edit = json.edit?.url
|| (sourceLocation?.includes(DA_DOMAIN) && sourceLocation?.replace('markup:https://content.da.live', 'https://da.live/edit#'))
|| '';
return { url, edit, preview, live, publish };
}
async function getStatuses() {
Object.keys(content.value).forEach(async (key) => {
content.value[key].items.forEach(async (item, idx) => {
const status = await getStatus(item.url);
content.value[key].items[idx] = status;
content.value = { ...content.value };
});
});
}
function getUrl(el) {
const { modalPath, modalHash, path: fragmentPath } = el.dataset;
const dataPath = modalPath ? `${modalPath}${modalHash}` : fragmentPath;
try {
return new URL(dataPath);
} catch {
const isPdfIframe = el.src && el.nodeName === 'IFRAME' && el.parentElement?.dataset.pdfSrc;
const elPath = el.href || (isPdfIframe ? el.parentElement.dataset.pdfSrc : el.src);
const path = dataPath ? `${window.location.origin}${dataPath}` : elPath;
return new URL(path);
}
}
function findLinks(selector) {
const hrefs = new Set();
return [...document.body.querySelectorAll(selector)]
.reduce((links, el) => {
const url = getUrl(el);
const baseUrl = `${url.origin}${url.pathname}`;
if (EXCLUDED_PATHS.some((path) => url.pathname.includes(path))) return links;
if (!hrefs.has(baseUrl)) {
hrefs.add(baseUrl);
links.push({ url, edit: null, preview: 'Fetching', live: 'Fetching' });
}
return links;
}, []);
}
export function runGeneralChecks() {
const contentValue = {
page: { items: [{ url: new URL(window.location.href), edit: null, preview: 'Fetching', live: 'Fetching' }] },
fragments: { items: findLinks('main .fragment, a[data-modal-path], [data-path]') },
links: { items: findLinks('main a[href^="/"') },
svgs: { items: findLinks('img[src$=".svg"') },
pdfs: { items: findLinks('main iframe') },
nav: { items: findLinks('header a[href^="/"'), closed: true },
};
return contentValue;
}
async function setContent() {
if (content.value.page) return;
content.value = runGeneralChecks();
getStatuses();
const sk = document.querySelector('aem-sidekick, helix-sidekick');
sk?.addEventListener('statusfetched', async () => { // sidekick v6
getStatuses();
});
sk?.addEventListener('status-fetched', async () => { // sidekick v7
getStatuses();
});
}
async function handleAction(action) {
Object.keys(content.value).map(async (key) => {
content.value[key].items.forEach(async (item, idx) => {
const checkPublish = action === 'live' ? (item.publish && !item.publish.canPublish) : false;
if (!item.checked || checkPublish) return;
content.value[key].items[idx].action = action;
content.value = { ...content.value };
const adminUrl = getAdminUrl(item.url, action);
const resp = await fetch(adminUrl, { method: 'POST' });
const json = resp.ok ? await resp.json() : NOT_FOUND;
content.value[key].items[idx] = {
...item,
action: null,
preview: json.preview?.lastModified || item.preview,
live: json.live?.lastModified || item.live,
};
content.value = { ...content.value };
});
});
}
function toggleSelect(checked) {
const copy = { ...content.value };
Object.keys(copy).forEach((key) => {
if (copy[key].closed) return;
copy[key].items.forEach((item) => { item.checked = !checked; });
});
content.value = copy;
}
function handleChange(target, name, idx) {
if (target.nodeName === 'A') return;
content.value[name].items[idx].checked = !content.value[name].items[idx].checked;
content.value = { ...content.value };
}
function toggleGroup(name) {
content.value[name].closed = !content.value[name].closed;
content.value = { ...content.value };
}
function checkPublishing(item, isFetching) {
if ((item.preview === DEF_NEVER && item.live === DEF_NEVER)
|| (item.preview === DEF_NOT_FOUND && item.live === DEF_NOT_FOUND)) {
return ' not-found';
}
return isFetching;
}
function prettyDate(string) {
if (Number.isNaN(Date.parse(string))) return string;
const date = new Date(string);
const localeDate = date.toLocaleString();
const splitDate = localeDate.split(', ');
return html`
<span class=preflight-date>${splitDate[0]}</span>
<span class=preflight-time>${splitDate[1]}</span>
`;
}
function prettyPath(url) {
if (!url) return '';
if (url.pathname === window.location.pathname) return url.pathname;
return url.hash ? `${url.pathname} (${url.hash})` : url.pathname;
}
function usePublishProps(item) {
let disablePublish;
if (item.publish && !item.publish.canPublish) {
disablePublish = html`${item.publish.message}`;
}
return {
publishText: html`${item.action === 'live' ? 'Publishing' : prettyDate(item.live)}`,
disablePublish,
};
}
function Item({ name, item, idx }) {
const { publishText, disablePublish } = usePublishProps(item);
const isChecked = item.checked ? ' is-checked' : '';
const isFetching = item.edit || item.preview === nonEDSContent ? '' : ' is-fetching';
const editIcon = item.edit && item.edit.includes(DA_DOMAIN) ? 'da-icon' : 'sharepoint-icon';
const prettyUrl = item.externalUrl ? item.externalUrl.href : prettyPath(item.url);
if (!item.url) return undefined;
return html`
<div class="preflight-group-row preflight-group-detail${isChecked}${checkPublishing(item, isFetching)}"
onClick=${(e) => handleChange(e.target, name, idx)}>
<p><a href=${item.externalUrl || item.url.pathname} target=_blank>${prettyUrl}</a></p>
<p>${item.edit && html`<a href=${item.edit} class="preflight-edit ${editIcon}" target=_blank>EDIT</a>`}</p>
<p class=preflight-date-wrapper>${item.action === 'preview' ? 'Previewing' : prettyDate(item.preview)}</p>
<p class="preflight-date-wrapper">
${isChecked && disablePublish ? html`<span class=disabled-publish>${disablePublish}</span>` : publishText}
</p>
</div>`;
}
function ContentGroup({ name, group }) {
if (group.items.length === 0) return null;
const isClosed = group.closed ? ' is-closed' : '';
return html`
<div class="preflight-content-group${isClosed}">
<div class="preflight-group-row preflight-group-heading" onClick=${() => toggleGroup(name)}>
<div class="preflight-group-expand"></div>
<p class=preflight-content-heading>${name}</p>
${name === 'page' && html`
<p class="preflight-content-heading preflight-content-heading-edit">Edit</p>
<p class=preflight-content-heading>Previewed</p>
<p class=preflight-content-heading>Published</p>
`}
</div>
<div class=preflight-group-items>
${group.items.map((item, idx) => html`<${Item} name=${name} idx=${idx} item=${item} />`)}
</div>
</div>`;
}
function StructureItem({ icon, title, description }) {
return html`
<div class="preflight-item">
<div class="result-icon ${icon}"></div>
<div class="preflight-item-text">
<p class="preflight-item-title">${title}</p>
<p class="preflight-item-description">${description}</p>
</div>
</div>`;
}
function LocalizationIssuesList({ issues }) {
return html`
${issues.length > 0 && html`
<div class="preflight-content-group${localizationClosed.value ? ' is-closed' : ''}">
<div class="preflight-group-row preflight-group-heading" onClick=${() => { localizationClosed.value = !localizationClosed.value; }}>
<div class="preflight-group-expand"></div>
<p class=preflight-content-heading>Faulty links</p>
<p class="preflight-content-heading">Loc</p>
<p class="preflight-content-heading">US status</p>
<p class="preflight-content-heading">Loc status</p>
</div>
<div class=preflight-group-items>
${issues.map((v) => html`
<div class="preflight-group-row preflight-group-detail">
<p><a href=${v.url} target=_blank>${v.url}</a></p>
<p>${v.isLocalized ? 'Yes' : 'No'}</p>
<p>${v.usStatus}</p>
<p>${v.localizedStatus}</p>
</div>
`)}
</div>
</div>
`}
`;
}
export default function General() {
useEffect(() => { setContent(); getStructureResults(); getLocalizationResults(); }, []);
const allChecked = Object.values(content.value)
.flatMap((item) => item.items).filter((item) => item.checked);
const checked = !!allChecked.length;
const publishable = allChecked
.filter((item) => item.checked && !!item.publish?.canPublish).length;
const hasPage = content.value.page;
const selectStyle = checked ? 'Select none' : 'Select all';
const tooltip = allChecked.length !== publishable && 'Puplishing disabled pages will be ignored';
return html`
<div class=preflight-general-content>
<p class="preflight-structure-title">Structure</p>
<div class=preflight-structure-columns>
<div class=preflight-column>
<${StructureItem} ...${navResult.value} />
<${StructureItem} ...${footerResult.value} />
<${StructureItem} ...${regionSelectorResult.value} />
</div>
<div class=preflight-column>
<${StructureItem} ...${georoutingResult.value} />
<${StructureItem} ...${breadcrumbsResult.value} />
</div>
</div>
<p class="preflight-structure-title">Localization</p>
<div class=preflight-structure-columns>
<div class=preflight-column>
<${StructureItem} ...${localizationResult.value} />
</div>
</div>
<${LocalizationIssuesList} issues=${localizationIssues.value} />
<p class="preflight-structure-title">Content</p>
${Object.keys(content.value).map((key) => html`<${ContentGroup} name=${key} group=${content.value[key]} />`)}
</div>
<div class=preflight-actions>
${hasPage && html`
<div id=select-action class=preflight-action-wrapper>
<button class=preflight-action onClick=${() => toggleSelect(checked)}>${selectStyle}</button>
</div>
`}
${checked && html`
<div id=preview-action class=preflight-action-wrapper>
<button class=preflight-action onClick=${() => handleAction('preview')}>Preview</button>
</div>
${!!publishable && html`
<div id=publish-action class="preflight-action-wrapper${tooltip ? ' tooltip' : ''}" data-tooltip=${tooltip}>
<button class="preflight-action" onClick=${() => handleAction('live')}>
Publish
</button>
</div>
`}
`}
</div>
`;
}