-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
index.ts
435 lines (376 loc) · 12.1 KB
/
index.ts
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
import { finder } from '@medv/finder';
import type { DevToolbarApp, DevToolbarMetadata } from '../../../../../@types/astro.js';
import type { DevToolbarHighlight } from '../../ui-library/highlight.js';
import {
attachTooltipToHighlight,
createHighlight,
getElementsPositionInDocument,
positionHighlight,
} from '../utils/highlight.js';
import { closeOnOutsideClick, createWindowElement } from '../utils/window.js';
import { a11y } from './a11y.js';
import { perf } from './perf.js';
import { settings } from '../../settings.js';
const icon =
'<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 1 20 16"><path fill="#fff" d="M.6 2A1.1 1.1 0 0 1 1.7.9h16.6a1.1 1.1 0 1 1 0 2.2H1.6A1.1 1.1 0 0 1 .8 2Zm1.1 7.1h6a1.1 1.1 0 0 0 0-2.2h-6a1.1 1.1 0 0 0 0 2.2ZM9.3 13H1.8a1.1 1.1 0 1 0 0 2.2h7.5a1.1 1.1 0 1 0 0-2.2Zm11.3 1.9a1.1 1.1 0 0 1-1.5 0l-1.7-1.7a4.1 4.1 0 1 1 1.6-1.6l1.6 1.7a1.1 1.1 0 0 1 0 1.6Zm-5.3-3.4a1.9 1.9 0 1 0 0-3.8 1.9 1.9 0 0 0 0 3.8Z"/></svg>';
type DynamicString = string | ((element: Element) => string);
export interface AuditRule {
code: string;
title: DynamicString;
message: DynamicString;
}
export interface ResolvedAuditRule {
code: string;
title: string;
message: string;
}
export interface AuditRuleWithSelector extends AuditRule {
selector: string;
match?: (
element: Element
) =>
| boolean
| null
| undefined
| void
| Promise<boolean>
| Promise<void>
| Promise<null>
| Promise<undefined>;
}
const rules = [...a11y, ...perf];
const dynamicAuditRuleKeys: Array<keyof AuditRule> = ['title', 'message'];
function resolveAuditRule(rule: AuditRule, element: Element): ResolvedAuditRule {
let resolved: ResolvedAuditRule = { ...rule } as any;
for (const key of dynamicAuditRuleKeys) {
const value = rule[key];
if (typeof value === 'string') continue;
resolved[key] = value(element);
}
return resolved;
}
export default {
id: 'astro:audit',
name: 'Audit',
icon: icon,
async init(canvas, eventTarget) {
let audits: {
highlightElement: DevToolbarHighlight;
auditedElement: HTMLElement;
rule: AuditRule;
}[] = [];
await lint();
let mutationDebounce: ReturnType<typeof setTimeout>;
const observer = new MutationObserver(() => {
// We don't want to rerun the audit lints on every single mutation, so we'll debounce it.
if (mutationDebounce) {
clearTimeout(mutationDebounce);
}
mutationDebounce = setTimeout(() => {
settings.logger.verboseLog('Rerunning audit lints because the DOM has been updated.');
// Even though we're ready to run the lints, we'll wait for the next idle period to do so, as it is less likely
// to interfere with any other work the browser is doing post-mutation. For instance, the page or the user might
// be interacting with the newly added elements, or the browser might be doing some work (layout, paint, etc.)
if ('requestIdleCallback' in window) {
window.requestIdleCallback(
async () => {
lint();
},
{ timeout: 300 }
);
} else {
// Fallback for old versions of Safari, we'll assume that things are less likely to be busy after 150ms.
setTimeout(() => {
lint();
}, 150);
}
}, 250);
});
setupObserver();
document.addEventListener('astro:before-preparation', () => {
observer.disconnect();
});
document.addEventListener('astro:after-swap', async () => {
lint();
});
document.addEventListener('astro:page-load', async () => {
refreshLintPositions();
// HACK: View transitions add a route announcer after this event, so we need to wait for it to be added
setTimeout(() => {
setupObserver();
}, 100);
});
closeOnOutsideClick(eventTarget);
async function lint() {
audits.forEach(({ highlightElement }) => {
highlightElement.remove();
});
audits = [];
canvas.getElementById('no-audit')?.remove();
const selectorCache = new Map<string, NodeListOf<Element>>();
for (const rule of rules) {
const elements =
selectorCache.get(rule.selector) ?? document.querySelectorAll(rule.selector);
let matches: Element[] = [];
if (typeof rule.match === 'undefined') {
matches = Array.from(elements);
} else {
for (const element of elements) {
if (await rule.match(element)) {
matches.push(element);
}
}
}
for (const element of matches) {
// Don't audit elements that already have an audit on them
// TODO: This is a naive implementation, it'd be good to show all the audits for an element at the same time.
if (audits.some((audit) => audit.auditedElement === element)) continue;
await createAuditProblem(rule, element);
}
}
if (audits.length > 0) {
eventTarget.dispatchEvent(
new CustomEvent('toggle-notification', {
detail: {
state: true,
},
})
);
const auditListWindow = createWindowElement(
`
<style>
astro-dev-toolbar-window {
left: initial;
top: 8px;
right: 8px;
transform: none;
width: 320px;
max-height: 320px;
padding: 0;
overflow: hidden;
}
hr {
margin: 0;
}
header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 18px;
}
h1 {
font-size: 22px;
font-weight: 600;
color: #fff;
}
ul, li {
margin: 0;
padding: 0;
list-style: none;
}
h1, h2 {
margin: 0;
}
h3 {
margin: 0;
margin-bottom: 8px;
color: white;
white-space: nowrap;
}
.audit-title {
font-weight: bold;
color: white;
margin-right: 1ch;
}
#audit-list {
display: flex;
flex-direction: column;
overflow: auto;
}
</style>
<header>
<h1>Audits</h1>
<astro-dev-toolbar-badge size="large">${audits.length} problem${
audits.length > 1 ? 's' : ''
} found</astro-dev-toolbar-badge>
</header>
<hr />`
);
const auditListUl = document.createElement('ul');
auditListUl.id = 'audit-list';
audits.forEach((audit, index) => {
const resolvedRule = resolveAuditRule(audit.rule, audit.auditedElement);
const card = document.createElement('astro-dev-toolbar-card');
card.shadowRoot.innerHTML = `
<style>
:host>button {
text-align: left;
box-shadow: none !important;
${
index + 1 < audits.length
? 'border-radius: 0 !important;'
: 'border-radius: 0 0 8px 8px !important;'
}
}
:host>button:hover {
cursor: pointer;
}
</style>`;
card.clickAction = () => {
audit.highlightElement.scrollIntoView();
audit.highlightElement.focus();
};
const h3 = document.createElement('h3');
h3.innerText = finder(audit.auditedElement);
card.appendChild(h3);
const div = document.createElement('div');
const title = document.createElement('span');
title.classList.add('audit-title');
title.innerHTML = resolvedRule.title;
div.appendChild(title);
card.appendChild(div);
auditListUl.appendChild(card);
});
auditListWindow.appendChild(auditListUl);
canvas.append(auditListWindow);
} else {
eventTarget.dispatchEvent(
new CustomEvent('toggle-notification', {
detail: {
state: false,
},
})
);
const window = createWindowElement(
`<style>
header {
display: flex;
}
h1 {
display: flex;
align-items: center;
gap: 8px;
font-weight: 600;
color: #fff;
margin: 0;
font-size: 22px;
}
astro-dev-toolbar-icon {
width: 1em;
height: 1em;
padding: 8px;
display: block;
background: green;
border-radius: 9999px;
}
</style>
<header>
<h1><astro-dev-toolbar-icon icon="check-circle"></astro-dev-toolbar-icon>No accessibility or performance issues detected.</h1>
</header>
<p>
Nice work! This app scans the page and highlights common accessibility and performance issues for you, like a missing "alt" attribute on an image, or a image not using performant attributes.
</p>
`
);
canvas.append(window);
}
(['scroll', 'resize'] as const).forEach((event) => {
window.addEventListener(event, refreshLintPositions);
});
}
function refreshLintPositions() {
const noAuditBlock = canvas.getElementById('no-audit');
if (noAuditBlock) {
const devOverlayRect = document
.querySelector('astro-dev-toolbar')
?.shadowRoot.querySelector('#dev-toolbar-root')
?.getBoundingClientRect();
noAuditBlock.style.top = `${
(devOverlayRect?.top ?? 0) - (devOverlayRect?.height ?? 0) - 16
}px`;
}
audits.forEach(({ highlightElement, auditedElement }) => {
const rect = auditedElement.getBoundingClientRect();
positionHighlight(highlightElement, rect);
});
}
async function createAuditProblem(rule: AuditRule, originalElement: Element) {
const computedStyle = window.getComputedStyle(originalElement);
const targetedElement = (originalElement.children[0] as HTMLElement) || originalElement;
// If the element is hidden, don't do anything
if (targetedElement.offsetParent === null || computedStyle.display === 'none') {
return;
}
// If the element is an image but not yet loaded, ignore it
// TODO: We shouldn't ignore this, because it is valid for an image to not be loaded at start (e.g. lazy loading)
if (originalElement.nodeName === 'IMG' && !(originalElement as HTMLImageElement).complete) {
return;
}
const rect = originalElement.getBoundingClientRect();
const highlight = createHighlight(rect, 'warning', { 'data-audit-code': rule.code });
const tooltip = buildAuditTooltip(rule, originalElement);
// Set the highlight/tooltip as being fixed position the highlighted element
// is fixed. We do this so that we don't mistakenly take scroll position
// into account when setting the tooltip/highlight positioning.
//
// We only do this once due to how expensive computed styles are to calculate,
// and are unlikely to change. If that turns out to be wrong, reconsider this.
const { isFixed } = getElementsPositionInDocument(originalElement);
if (isFixed) {
tooltip.style.position = highlight.style.position = 'fixed';
}
attachTooltipToHighlight(highlight, tooltip, originalElement);
canvas.append(highlight);
audits.push({
highlightElement: highlight,
auditedElement: originalElement as HTMLElement,
rule: rule,
});
}
function buildAuditTooltip(rule: AuditRule, element: Element) {
const tooltip = document.createElement('astro-dev-toolbar-tooltip');
const { title, message } = resolveAuditRule(rule, element);
tooltip.sections = [
{
icon: 'warning',
title: escapeHtml(title),
},
{
content: escapeHtml(message),
},
];
const elementFile = element.getAttribute('data-astro-source-file');
const elementPosition = element.getAttribute('data-astro-source-loc');
if (elementFile) {
const elementFileWithPosition =
elementFile + (elementPosition ? ':' + elementPosition : '');
tooltip.sections.push({
content: elementFileWithPosition.slice(
(window as DevToolbarMetadata).__astro_dev_toolbar__.root.length - 1 // We want to keep the final slash, so minus one.
),
clickDescription: 'Click to go to file',
async clickAction() {
// NOTE: The path here has to be absolute and without any errors (no double slashes etc)
// or Vite will silently fail to open the file. Quite annoying.
await fetch('/__open-in-editor?file=' + encodeURIComponent(elementFileWithPosition));
},
});
}
return tooltip;
}
function escapeHtml(unsafe: string) {
return unsafe
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function setupObserver() {
observer.observe(document.body, {
childList: true,
subtree: true,
});
}
},
} satisfies DevToolbarApp;