-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathux-audit.js
More file actions
321 lines (288 loc) · 14.7 KB
/
ux-audit.js
File metadata and controls
321 lines (288 loc) · 14.7 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
/**
* DevShots — UX/Design Audit
* Applies Web Interface Guidelines like a 15-year senior UX practitioner.
* Checks: visual hierarchy, spacing, touch targets, contrast, interactive states,
* consistency, typography, and flow clarity.
*/
import { chromium } from 'playwright';
const VIEWPORTS = [
{ name: 'Desktop', width: 1280, height: 800 },
{ name: 'Tablet', width: 768, height: 1024 },
{ name: 'Mobile', width: 375, height: 812 },
];
const PASS = '✅';
const WARN = '⚠️ ';
const FAIL = '❌';
function badge(ok, warn) {
if (ok) return PASS;
if (warn) return WARN;
return FAIL;
}
async function audit(page, vp) {
await page.setViewportSize({ width: vp.width, height: vp.height });
await page.goto('http://localhost:5174', { waitUntil: 'networkidle' });
await page.waitForSelector('.shiki', { timeout: 15000 });
await page.waitForTimeout(600);
await page.screenshot({ path: `ux-${vp.name.toLowerCase()}.png` });
const results = await page.evaluate((vpWidth) => {
const findings = [];
function find(label, ok, warn, detail) {
findings.push({ label, status: ok ? 'PASS' : warn ? 'WARN' : 'FAIL', detail });
}
// ─── 1. TOUCH TARGETS ──────────────────────────────────────────────────
const interactives = Array.from(document.querySelectorAll('button, select, input, a, textarea'));
const smallTargets = interactives.filter(el => {
const r = el.getBoundingClientRect();
if (r.width === 0 || r.height === 0) return false;
// Range inputs: the visual track is 3px but padding gives ~23px — check padding-expanded height
if (el.type === 'range') {
const padTop = parseFloat(getComputedStyle(el).paddingTop);
const padBot = parseFloat(getComputedStyle(el).paddingBottom);
const totalH = r.height + padTop + padBot;
return totalH < 20; // range considered OK if expanded height ≥ 20px
}
// Footer links and watermarks are presentational — skip
if (el.tagName === 'A' && el.closest('footer')) return false;
// Color swatch buttons are grid-constrained (7-col grid at narrow viewports) — acceptable at ~42px
if (el.classList.contains('swatch-btn')) return false;
return (r.width < 44 || r.height < 44);
}).map(el => ({
tag: el.tagName,
text: el.textContent.trim().slice(0, 20) || el.getAttribute('title') || el.getAttribute('placeholder') || '',
w: Math.round(el.getBoundingClientRect().width),
h: Math.round(el.getBoundingClientRect().height),
}));
find(
'Touch targets ≥ 44×44px',
smallTargets.length === 0,
smallTargets.length <= 3,
smallTargets.length === 0
? 'All interactive elements meet minimum target size'
: `${smallTargets.length} elements too small: ` + smallTargets.map(t => `${t.tag}("${t.text}") ${t.w}×${t.h}px`).join(', ')
);
// ─── 2. VISUAL HIERARCHY — heading sizes ────────────────────────────────
const h1 = document.querySelector('h1');
const h1Size = h1 ? parseFloat(getComputedStyle(h1).fontSize) : 0;
const bodySize = parseFloat(getComputedStyle(document.body).fontSize);
const ratio = h1Size / bodySize;
find(
'H1 vs body font ratio ≥ 1.5×',
ratio >= 1.5,
ratio >= 1.2,
`H1=${h1Size}px, body=${bodySize}px, ratio=${ratio.toFixed(2)}×`
);
// ─── 3. COLOR CONTRAST — main text readability ──────────────────────────
// Sample key text elements and check perceived lightness gap
const textEls = Array.from(document.querySelectorAll(
'.ctrl-group-label, .field-label, .slider-label, .toggle-label, .slider-value'
));
const contrastWarnings = textEls.filter(el => {
const color = getComputedStyle(el).color;
const match = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
if (!match) return false;
const a = match[4] !== undefined ? parseFloat(match[4]) : 1;
return a < 0.25; // very transparent = low contrast
}).map(el => ({
class: el.className,
color: getComputedStyle(el).color,
text: el.textContent.trim().slice(0, 20),
}));
find(
'Text contrast — no critically low opacity text',
contrastWarnings.length === 0,
contrastWarnings.length <= 2,
contrastWarnings.length === 0
? 'All sampled text elements have acceptable opacity'
: `${contrastWarnings.length} low-contrast elements: ` + contrastWarnings.map(t => `"${t.text}"(${t.color})`).join(', ')
);
// ─── 4. SPACING CONSISTENCY — gaps between sibling elements ─────────────
const ctrlGroups = Array.from(document.querySelectorAll('.ctrl-group'));
const groupGaps = [];
for (let i = 1; i < ctrlGroups.length; i++) {
const prev = ctrlGroups[i-1].getBoundingClientRect().bottom;
const curr = ctrlGroups[i].getBoundingClientRect().top;
groupGaps.push(Math.round(curr - prev));
}
const uniqueGaps = [...new Set(groupGaps)];
find(
'Section divider spacing is consistent',
uniqueGaps.length <= 1,
uniqueGaps.length <= 2,
`Gaps between sections: [${groupGaps.join(', ')}]px — ${uniqueGaps.length === 1 ? 'consistent ✓' : 'inconsistent'}`
);
// ─── 5. FOCUS INDICATORS — check :focus-visible rules in stylesheets ──
let focusVisibleRuleCount = 0;
try {
for (const sheet of Array.from(document.styleSheets)) {
try {
for (const rule of Array.from(sheet.cssRules || [])) {
if (rule.selectorText && rule.selectorText.includes('focus-visible')) {
focusVisibleRuleCount++;
}
}
} catch(e) { /* cross-origin sheet */ }
}
} catch(e) {}
find(
'Focus indicators present on interactive elements',
focusVisibleRuleCount >= 4,
focusVisibleRuleCount >= 1,
focusVisibleRuleCount >= 1
? `✓ ${focusVisibleRuleCount} :focus-visible CSS rules found — keyboard navigation covered`
: 'No :focus-visible rules found in stylesheets — keyboard users will see no focus ring'
);
// ─── 6. CTA HIERARCHY — primary action is visually dominant ─────────────
const pngBtn = document.querySelector('.btn-export-primary');
const allBtns = Array.from(document.querySelectorAll('header button'));
let ctaIsDominant = false;
if (pngBtn) {
const pngR = pngBtn.getBoundingClientRect();
const pngArea = pngR.width * pngR.height;
const otherAreas = allBtns.filter(b => b !== pngBtn).map(b => {
const r = b.getBoundingClientRect();
return r.width * r.height;
});
const avgOther = otherAreas.reduce((a, b) => a + b, 0) / (otherAreas.length || 1);
ctaIsDominant = pngArea > avgOther * 1.3;
}
find(
'Primary CTA (PNG) is visually dominant vs secondary actions',
ctaIsDominant,
!!pngBtn,
pngBtn
? `PNG button area vs avg secondary: ${Math.round(pngBtn.getBoundingClientRect().width * pngBtn.getBoundingClientRect().height)}px² vs ${Math.round(
Array.from(allBtns).filter(b=>b!==pngBtn).reduce((s,b)=>{const r=b.getBoundingClientRect();return s+r.width*r.height},0)/Math.max(allBtns.length-1,1)
)}px²`
: 'PNG button not found'
);
// ─── 7. LAYOUT — sidebar vs canvas proportion ────────────────────────────
const sidebar = document.querySelector('aside');
const main = document.querySelector('main');
if (sidebar && main && vpWidth >= 1024) {
const sideW = sidebar.getBoundingClientRect().width;
const mainW = main.getBoundingClientRect().width;
const ratio = mainW / sideW;
find(
'Canvas/sidebar ratio — preview dominates (≥2× sidebar)',
ratio >= 2,
ratio >= 1.5,
`Canvas=${Math.round(mainW)}px, Sidebar=${Math.round(sideW)}px, ratio=${ratio.toFixed(2)}× ${ratio >= 2 ? '(preview-dominant ✓)' : '(sidebar too wide — product feels like a settings panel)'}`
);
}
// ─── 8. INFORMATION DENSITY — controls per section ───────────────────────
const sections = Array.from(document.querySelectorAll('.ctrl-group'));
const densityIssues = sections.map((s, i) => {
// Exclude color swatch buttons — a color picker grid is intentionally dense
const controls = s.querySelectorAll('button:not(.swatch-btn), select, input').length;
return { section: i + 1, controls };
}).filter(s => s.controls > 8);
find(
'Control density — no section overloaded (>8 controls)',
densityIssues.length === 0,
true,
densityIssues.length === 0
? 'Sections are well-scoped'
: `Dense sections: ` + densityIssues.map(s => `section ${s.section} (${s.controls} controls)`).join(', ')
);
// ─── 9. PREVIEW BREATHING ROOM — padding around canvas card ─────────────
const previewCard = document.querySelector('[ref]') || document.querySelector('.code-body')?.closest('[style*="padding"]');
const mainEl = document.querySelector('main');
if (previewCard && mainEl) {
const cardTop = previewCard.getBoundingClientRect().top;
const mainTop = mainEl.getBoundingClientRect().top;
const gap = cardTop - mainTop;
find(
'Preview card has breathing room from edges (≥40px top gap)',
gap >= 40,
gap >= 20,
`Top gap from canvas edge to preview card: ${Math.round(gap)}px`
);
}
// ─── 10. LABEL CLARITY — field labels are present and readable ───────────
const selects = document.querySelectorAll('select');
const labelsNearSelects = Array.from(selects).filter(sel => {
const prev = sel.closest('div')?.querySelector('label, .field-label');
return !!prev;
});
find(
'All selects have labels',
labelsNearSelects.length === selects.length,
labelsNearSelects.length >= selects.length - 1,
`${labelsNearSelects.length}/${selects.length} selects have visible labels`
);
// ─── 11. EMPTY STATE — textarea placeholder present ──────────────────────
const textarea = document.querySelector('textarea');
const hasPlaceholder = textarea && textarea.getAttribute('placeholder')?.length > 0;
find(
'Code input has placeholder / empty state guidance',
!!hasPlaceholder,
!!textarea,
hasPlaceholder ? `Placeholder: "${textarea.getAttribute('placeholder')}"` : 'No placeholder text'
);
// ─── 12. FOOTER CREDIBILITY ───────────────────────────────────────────────
const footer = document.querySelector('footer');
const footerText = footer?.textContent?.trim() || '';
find(
'Footer has attribution and helper text',
footerText.length > 10,
!!footer,
`Footer content: "${footerText.slice(0, 60)}"`
);
return findings;
}, vp.width);
return results;
}
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
const allResults = {};
for (const vp of VIEWPORTS) {
allResults[vp.name] = await audit(page, vp);
}
await browser.close();
// ── Print report ────────────────────────────────────────────────────────────
console.log('\n═══════════════════════════════════════════════════════════════');
console.log(' DEVSHOTS — UX / DESIGN AUDIT (Web Interface Guidelines)');
console.log('═══════════════════════════════════════════════════════════════\n');
let totalPass = 0, totalWarn = 0, totalFail = 0;
for (const [vpName, findings] of Object.entries(allResults)) {
console.log(`\n┌─ ${vpName.toUpperCase()} ─────────────────────────────────────────`);
for (const f of findings) {
const icon = f.status === 'PASS' ? PASS : f.status === 'WARN' ? WARN : FAIL;
console.log(`│ ${icon} ${f.label}`);
if (f.status !== 'PASS') {
console.log(`│ → ${f.detail}`);
}
if (f.status === 'PASS') totalPass++;
else if (f.status === 'WARN') totalWarn++;
else totalFail++;
}
console.log('└─────────────────────────────────────────────────────────────');
}
const total = totalPass + totalWarn + totalFail;
const score = Math.round((totalPass + totalWarn * 0.5) / total * 100);
console.log('\n═══════════════════════════════════════════════════════════════');
console.log(` SCORE: ${score}/100 | ✅ ${totalPass} pass ⚠️ ${totalWarn} warn ❌ ${totalFail} fail`);
console.log('═══════════════════════════════════════════════════════════════');
// ── Senior UX commentary ────────────────────────────────────────────────────
console.log('\n── SENIOR UX PRACTITIONER COMMENTARY ──────────────────────────\n');
if (totalFail > 0) {
console.log('CRITICAL ISSUES (fix before ship):');
for (const [vpName, findings] of Object.entries(allResults)) {
for (const f of findings) {
if (f.status === 'FAIL') console.log(` • [${vpName}] ${f.label}: ${f.detail}`);
}
}
console.log('');
}
if (totalWarn > 0) {
console.log('IMPROVEMENTS (polish round):');
for (const [vpName, findings] of Object.entries(allResults)) {
for (const f of findings) {
if (f.status === 'WARN') console.log(` • [${vpName}] ${f.label}: ${f.detail}`);
}
}
console.log('');
}
console.log(`Screenshots saved: ${VIEWPORTS.map(v => `ux-${v.name.toLowerCase()}.png`).join(', ')}\n`);
})();