-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
557 lines (451 loc) · 17.1 KB
/
content.js
File metadata and controls
557 lines (451 loc) · 17.1 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
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === "HIGHLIGHT_ISSUE") {
highlightIssueElement(message.issueId);
sendResponse({ ok: true });
return;
}
if (message.type !== "SCAN_UI") {
return;
}
const settings = message.settings || getDefaultSettings();
const textElements = getVisibleElements("p, span, li, a, button, label, h1, h2, h3");
const buttons = getVisibleElements("button, input[type='button'], input[type='submit'], a[role='button']");
clearStoredIssues();
const allIssues = [
...findTinyTextIssues(settings),
...findContrastIssues(),
...findButtonConsistencyIssues(),
...findHeadingIssues(),
...findTooManyColorsIssues(settings),
...findSpacingIssues(settings),
...findMissingAltTextIssues(),
...findMobileOverflowIssues()
].sort((a, b) => a.priority - b.priority);
const issues = settings.hideLowConfidence
? allIssues.filter((issue) => issue.confidence >= 80)
: allIssues;
const visibleIssues = issues.slice(0, settings.showAllIssues ? 12 : 6);
if (visibleIssues.length > 0) {
highlightIssueElement(visibleIssues[0].id);
}
sendResponse({
issues: visibleIssues,
summary: {
pageTitle: document.title || "Untitled page",
pageHost: window.location.host,
pageUrl: window.location.href,
scannedAt: new Date().toISOString(),
textCount: textElements.length,
buttonCount: buttons.length,
issueCount: visibleIssues.length,
totalIssueCount: issues.length,
score: getAuditScore(issues),
grade: getAuditGrade(getAuditScore(issues))
}
});
});
let lastHighlightedElement = null;
let issueCounter = 0;
const issueElements = {};
function getDefaultSettings() {
return {
mode: "beginner",
showAllIssues: false,
minimumFontSize: 14
};
}
function findTinyTextIssues(settings) {
const textElements = getVisibleElements("p, span, li, a, button, label");
const tinyTextIssues = [];
for (const element of textElements) {
const style = window.getComputedStyle(element);
const fontSize = parseFloat(style.fontSize);
if (fontSize > 0 && fontSize < settings.minimumFontSize && element.innerText.trim().length > 12) {
const suggestedFontSize = Math.max(settings.minimumFontSize, Math.ceil(fontSize + 2));
tinyTextIssues.push({
id: saveIssueElement(element),
category: "Readability",
confidence: fontSize < 12 ? 96 : 84,
severity: "Medium",
priority: 2,
title: `Text is clearly too small (${fontSize}px)`,
meaning: "Some text is small enough that users may need to zoom in to read it.",
selector: getSimpleSelector(element),
whyWrong: `"${getTextPreview(element)}" is ${fontSize}px. Your current minimum is ${settings.minimumFontSize}px.`,
fix: `${getSimpleSelector(element)} {\n font-size: ${suggestedFontSize}px;\n}`,
test: "Refresh the webpage, look at this text again, and check that it feels readable without zooming."
});
}
}
tinyTextIssues.sort((a, b) => getNumberFromText(a.whyWrong) - getNumberFromText(b.whyWrong));
return tinyTextIssues.slice(0, 1);
}
function findContrastIssues() {
const textElements = getVisibleElements("p, span, li, a, button, label, h1, h2, h3");
const contrastIssues = [];
for (const element of textElements) {
const style = window.getComputedStyle(element);
const fontSize = parseFloat(style.fontSize);
const textColor = parseColor(style.color);
const backgroundColor = getVisibleBackgroundColor(element);
if (!textColor || !backgroundColor || fontSize < 12) {
continue;
}
const ratio = getContrastRatio(textColor, backgroundColor);
const requiredRatio = isLargeText(element, fontSize) ? 3 : 4.5;
if (ratio < requiredRatio && element.innerText.trim().length > 8) {
const suggestedTextColor = getBetterTextColor(backgroundColor);
contrastIssues.push({
id: saveIssueElement(element),
category: "Accessibility",
confidence: ratio < requiredRatio - 1 ? 98 : 88,
severity: "High",
priority: 1,
title: `Weak contrast (${ratio.toFixed(2)})`,
meaning: "The text color and background color are too similar, so the text can be hard to read.",
selector: getSimpleSelector(element),
whyWrong: `"${getTextPreview(element)}" has contrast ratio ${ratio.toFixed(2)}. This text should usually be at least ${requiredRatio}.`,
fix: `${getSimpleSelector(element)} {\n color: ${suggestedTextColor};\n}`,
test: "Refresh the webpage and check that this text is clearly readable against its background."
});
}
}
contrastIssues.sort((a, b) => getNumberFromText(a.whyWrong) - getNumberFromText(b.whyWrong));
return contrastIssues.slice(0, 1);
}
function findButtonConsistencyIssues() {
const buttons = getVisibleElements("button, input[type='button'], input[type='submit'], a[role='button']");
if (buttons.length < 4) {
return [];
}
const commonButtonStyle = getMostCommonButtonStyle(buttons);
const inconsistentButtons = [];
if (commonButtonStyle.count < 2) {
return [];
}
for (const button of buttons) {
const style = window.getComputedStyle(button);
const padding = `${style.paddingTop} ${style.paddingRight} ${style.paddingBottom} ${style.paddingLeft}`;
const paddingGap = getPaddingDifference(padding, commonButtonStyle.padding);
const radiusGap = Math.abs(parseFloat(style.borderRadius) - parseFloat(commonButtonStyle.radius));
if (paddingGap > 24 || radiusGap > 16) {
inconsistentButtons.push({
id: saveIssueElement(button),
category: "Consistency",
confidence: paddingGap > 36 || radiusGap > 24 ? 86 : 72,
severity: "Low",
priority: 3,
title: "Button style does not match the page",
meaning: "Buttons on the same page should usually feel like they belong to the same design system.",
selector: getSimpleSelector(button),
whyWrong: `"${getTextPreview(button)}" uses padding ${padding} and radius ${style.borderRadius}. Most similar buttons here use padding ${commonButtonStyle.padding} and radius ${commonButtonStyle.radius}.`,
fix: `${getSimpleSelector(button)} {\n padding: ${commonButtonStyle.padding};\n border-radius: ${commonButtonStyle.radius};\n}`,
test: "Refresh the webpage and compare the buttons. They should now feel more visually consistent."
});
}
}
return inconsistentButtons.slice(0, 1);
}
function findHeadingIssues() {
const headings = getVisibleElements("h1, h2, h3, h4, h5, h6");
const issues = [];
let lastLevel = 0;
for (const heading of headings) {
const level = Number(heading.tagName.slice(1));
if (lastLevel > 0 && level > lastLevel + 1) {
issues.push({
id: saveIssueElement(heading),
category: "Structure",
confidence: 90,
severity: "Medium",
priority: 4,
title: "Heading level is skipped",
meaning: "Headings should move in order so users and screen readers understand the page structure.",
selector: getSimpleSelector(heading),
whyWrong: `"${getTextPreview(heading)}" jumps from H${lastLevel} to H${level}. That can make the page outline confusing.`,
fix: `<!-- Change this heading to h${lastLevel + 1} if it belongs under the previous section. -->\n<h${lastLevel + 1}>${getTextPreview(heading)}</h${lastLevel + 1}>`,
test: "Refresh the page and scan again. The heading warning should disappear if the heading order is now correct."
});
break;
}
lastLevel = level;
}
return issues;
}
function findTooManyColorsIssues(settings) {
if (settings.mode !== "strict") {
return [];
}
const elements = getVisibleElements("body *").slice(0, 250);
const colors = new Set();
for (const element of elements) {
const style = window.getComputedStyle(element);
colors.add(style.color);
colors.add(style.backgroundColor);
}
colors.delete("rgba(0, 0, 0, 0)");
colors.delete("transparent");
if (colors.size <= 32) {
return [];
}
return [{
id: saveIssueElement(document.body),
category: "Visual System",
confidence: colors.size > 42 ? 82 : 70,
severity: "Low",
priority: 7,
title: "Too many colors are used",
meaning: "Too many different colors can make a page feel noisy or less professional.",
selector: "body",
whyWrong: `This quick scan found about ${colors.size} text/background colors in the first 250 visible elements.`,
fix: `:root {\n --color-text: #111827;\n --color-muted: #64748b;\n --color-brand: #2563eb;\n --color-surface: #ffffff;\n}`,
test: "Group similar colors into a small palette, refresh the page, and scan again."
}];
}
function findSpacingIssues(settings) {
if (settings.mode !== "strict") {
return [];
}
const elements = getVisibleElements("section, article, div, button, a, input").slice(0, 200);
const spacingValues = new Set();
for (const element of elements) {
const style = window.getComputedStyle(element);
spacingValues.add(style.marginTop);
spacingValues.add(style.marginBottom);
spacingValues.add(style.paddingTop);
spacingValues.add(style.paddingBottom);
}
spacingValues.delete("0px");
if (spacingValues.size <= 28) {
return [];
}
return [{
id: saveIssueElement(document.body),
category: "Layout",
confidence: spacingValues.size > 40 ? 82 : 70,
severity: "Low",
priority: 6,
title: "Spacing looks inconsistent",
meaning: "A clean UI usually repeats a small spacing scale instead of using many random spacing values.",
selector: "body",
whyWrong: `This quick scan found ${spacingValues.size} different vertical spacing values.`,
fix: `:root {\n --space-1: 4px;\n --space-2: 8px;\n --space-3: 16px;\n --space-4: 24px;\n}`,
test: "Replace random spacing with a small spacing scale, refresh, and scan again."
}];
}
function findMissingAltTextIssues() {
const images = getVisibleElements("img");
for (const image of images) {
if (!image.hasAttribute("alt")) {
return [{
id: saveIssueElement(image),
category: "Accessibility",
confidence: 99,
severity: "High",
priority: 1,
title: "Image is missing alt text",
meaning: "Alt text helps screen reader users understand what an image means.",
selector: getSimpleSelector(image),
whyWrong: "This image has no alt attribute, so assistive tools may not know how to describe it.",
fix: `${getSimpleSelector(image)}\n<!-- Add a useful alt attribute in HTML: -->\n<img src=\"...\" alt=\"Short description of the image\">`,
test: "Add alt text, refresh the page, and scan again. Decorative images can use alt=\"\"."
}];
}
}
return [];
}
function findMobileOverflowIssues() {
const overflowingElements = getVisibleElements("body *").filter((element) => {
const rect = element.getBoundingClientRect();
return rect.width > window.innerWidth + 20 || rect.right > window.innerWidth + 20;
});
if (overflowingElements.length === 0) {
return [];
}
const element = overflowingElements[0];
return [{
id: saveIssueElement(element),
category: "Responsive",
confidence: 95,
severity: "High",
priority: 1,
title: "Element overflows the screen",
meaning: "Something is wider than the visible browser area, which can cause horizontal scrolling on mobile.",
selector: getSimpleSelector(element),
whyWrong: `"${getTextPreview(element) || element.tagName.toLowerCase()}" extends past the right side of the viewport.`,
fix: `${getSimpleSelector(element)} {\n max-width: 100%;\n overflow-wrap: break-word;\n}`,
test: "Resize the browser narrow, refresh the page, and check that horizontal scrolling is gone."
}];
}
function getAuditScore(issues) {
let score = 100;
for (const issue of issues) {
if (issue.severity === "High") {
score -= 18;
} else if (issue.severity === "Medium") {
score -= 10;
} else {
score -= 5;
}
}
return Math.max(0, score);
}
function getAuditGrade(score) {
if (score >= 95) {
return "Excellent";
}
if (score >= 85) {
return "Good";
}
if (score >= 70) {
return "Needs work";
}
return "Critical";
}
function getVisibleElements(selector) {
return Array.from(document.querySelectorAll(selector)).filter((element) => {
const rect = element.getBoundingClientRect();
const style = window.getComputedStyle(element);
return (
rect.width > 0 &&
rect.height > 0 &&
style.visibility !== "hidden" &&
style.display !== "none"
);
});
}
function saveIssueElement(element) {
const id = `issue-${Date.now()}-${issueCounter}`;
issueCounter += 1;
issueElements[id] = element;
return id;
}
function clearStoredIssues() {
clearLastHighlight();
issueCounter = 0;
for (const key of Object.keys(issueElements)) {
delete issueElements[key];
}
}
function highlightIssueElement(issueId) {
const element = issueElements[issueId];
if (!element) {
return;
}
clearLastHighlight();
lastHighlightedElement = element;
element.dataset.uiDebugTeacherOutline = element.style.outline;
element.dataset.uiDebugTeacherOutlineOffset = element.style.outlineOffset;
element.style.outline = "3px solid #f59e0b";
element.style.outlineOffset = "3px";
element.scrollIntoView({ behavior: "smooth", block: "center", inline: "nearest" });
}
function clearLastHighlight() {
if (!lastHighlightedElement) {
return;
}
lastHighlightedElement.style.outline = lastHighlightedElement.dataset.uiDebugTeacherOutline || "";
lastHighlightedElement.style.outlineOffset = lastHighlightedElement.dataset.uiDebugTeacherOutlineOffset || "";
delete lastHighlightedElement.dataset.uiDebugTeacherOutline;
delete lastHighlightedElement.dataset.uiDebugTeacherOutlineOffset;
lastHighlightedElement = null;
}
function getVisibleBackgroundColor(element) {
let current = element;
while (current && current !== document.documentElement) {
const color = parseColor(window.getComputedStyle(current).backgroundColor);
if (color && color.a !== 0) {
return color;
}
current = current.parentElement;
}
return { r: 255, g: 255, b: 255, a: 1 };
}
function parseColor(colorText) {
const match = colorText.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([0-9.]+))?\)/);
if (!match) {
return null;
}
return {
r: Number(match[1]),
g: Number(match[2]),
b: Number(match[3]),
a: match[4] === undefined ? 1 : Number(match[4])
};
}
function getContrastRatio(colorA, colorB) {
const lightA = getRelativeLuminance(colorA);
const lightB = getRelativeLuminance(colorB);
const lighter = Math.max(lightA, lightB);
const darker = Math.min(lightA, lightB);
return (lighter + 0.05) / (darker + 0.05);
}
function getBetterTextColor(backgroundColor) {
const darkText = { r: 17, g: 24, b: 39, a: 1 };
const lightText = { r: 255, g: 255, b: 255, a: 1 };
const darkRatio = getContrastRatio(darkText, backgroundColor);
const lightRatio = getContrastRatio(lightText, backgroundColor);
if (darkRatio >= lightRatio) {
return "#111827";
}
return "#ffffff";
}
function isLargeText(element, fontSize) {
const style = window.getComputedStyle(element);
const fontWeight = Number(style.fontWeight);
return fontSize >= 24 || (fontSize >= 18.66 && fontWeight >= 700);
}
function getRelativeLuminance(color) {
const red = convertToLinearColor(color.r / 255);
const green = convertToLinearColor(color.g / 255);
const blue = convertToLinearColor(color.b / 255);
return 0.2126 * red + 0.7152 * green + 0.0722 * blue;
}
function convertToLinearColor(value) {
if (value <= 0.03928) {
return value / 12.92;
}
return Math.pow((value + 0.055) / 1.055, 2.4);
}
function getSimpleSelector(element) {
if (element.id) {
return `#${element.id}`;
}
if (element.classList.length > 0) {
return `${element.tagName.toLowerCase()}.${element.classList[0]}`;
}
return element.tagName.toLowerCase();
}
function getTextPreview(element) {
const text = element.innerText.trim().replace(/\s+/g, " ");
if (text.length <= 40) {
return text;
}
return `${text.slice(0, 40)}...`;
}
function getMostCommonButtonStyle(buttons) {
const counts = {};
for (const button of buttons) {
const style = window.getComputedStyle(button);
const padding = `${style.paddingTop} ${style.paddingRight} ${style.paddingBottom} ${style.paddingLeft}`;
const key = `${padding}|${style.borderRadius}`;
counts[key] = (counts[key] || 0) + 1;
}
const mostCommonKey = Object.keys(counts).sort((a, b) => counts[b] - counts[a])[0];
const [padding, radius] = mostCommonKey.split("|");
return { padding, radius, count: counts[mostCommonKey] };
}
function getPaddingDifference(paddingA, paddingB) {
const valuesA = paddingA.split(" ").map((value) => parseFloat(value));
const valuesB = paddingB.split(" ").map((value) => parseFloat(value));
return valuesA.reduce((total, value, index) => {
return total + Math.abs(value - valuesB[index]);
}, 0);
}
function getNumberFromText(text) {
const match = text.match(/[0-9]+(?:\.[0-9]+)?/);
if (!match) {
return 0;
}
return Number(match[0]);
}