โณ This skill is pending AI review.
Scores will appear once the review pipeline completes.
oxfords
Use when building, changing, redesigning, reviewing or auditing any interface a person operates - dashboard, admin panel, table, form, settings, modal, onboarding, mobile app screen, landing page, website - or choosing its colours, palette or dark theme. Also use when a UI looks AI-generated, cluttered, generic, "vibe coded", over-decorated, unfinished or hard to scan, when asked to remove AI slop, make a UI clean, plain, polished or professional, fix the UX, or check a build before shipping, and when asked to audit or score a website or page for AI slop ("how AI-generated does my site look", "audit my landing page").
Choose how to use this skill
You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.
1. Native installer
This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.
Do not guess an installer command or replace an existing version without reviewing the diff.
2. Complete package recommended
Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.
No complete ProSkills package is published for this listing yet.3. Prompt-only
Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.
Need only the instruction file?
Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.
No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.
// RATINGS
Not yet listed on ClawHub or SkillsMP
// README
Oxfords, not brogues. An Oxford is the plain shoe, and a brogue is the same shoe with a bunch of decoration punched into it.
So this skill won't make your site look insane, and it won't give you crazy animations. There are good skills for that already. What I wanted was the boring part done properly: a screen that's clear, that's finished, and that doesn't have the stuff on it that tells everyone an AI made it.
What you get
The half that gets skipped. AI builds the happy path and then stops. Oxfords makes it keep going, so you get the button states, the feedback when you click something, the empty screen, the error screen, what happens with a really long name or 10,000 rows, keyboard focus, and tap targets that work on a phone.
A screen you can actually scan. Nobody reads a UI. You land on it with one question and you hunt for the answer. So Oxfords lines things up on edges, lets the data decide what component to use, and makes one thing on the screen important instead of all of it.
No AI slop. I kept seeing the same tells in everything AI builds, even with good design skills loaded, so there's a strict list of them and what to use instead:
| Out | In |
|---|---|
| A coloured bar down the side of the active nav item | A full-row fill |
| A card around everything, cards inside cards, a divider under every row | Space, alignment, one hairline |
| Tags and pills on everything | Plain labels, and a pill only for a real status |
| A small uppercase label above every heading | The heading |
| Inter, Geist, Poppins, Instrument Serif, Playfair | The system font, or a face you can give a reason for |
| An italic word in every headline, monospace labels, ALL CAPS subtitles | One face, upright, in sentence case |
| Emoji as icons, the stock icon set at default stroke | One icon set, one weight, matched to the text |
| Bone and orange, white and blue, gradient backgrounds | A palette chosen for the product, with a reason |
| Gradient text, glows | Flat colour, and each colour does one job |
| A tinted pill on every status | Colour only where something needs attention |
| Bounce, fade-up on everything, pulsing dots | Short ease-out transitions that explain a change |
| "Seamless", "Get started", Acme, 99.9% | The plain sentence and believable data |
Headings that end in a full stop, // features code breadcrumbs | A heading that's just a name |
Colours somebody actually picked. You've probably noticed Claude goes for the same bone background with an orange accent on pretty much everything now. Before that it was purple gradients, and if you tell it to be "clean" you get white, grey and one blue button. They're all the same problem, the colour got picked by default. So Oxfords comes with 26 palettes, three colours each, and the agent has to choose one for your product and say why. The palette goes on top of proper neutrals though, white, black and greys still do most of the work, so you don't end up with a page that's cream from edge to edge.
And the agent doesn't type colours by hand anymore. A script turns the palette into every colour the page needs: the hover and pressed shades, a version of each colour that's actually readable as text, three levels of grey for text, red for delete that never gets mixed up with your brand, and a dark mode that's designed instead of just flipped. Every pair is contrast checked before it's written. Got a client colour? Give it that and it builds the rest around it.
node skills/oxfords/scripts/palette.mjs Tideline --mode both
node skills/oxfords/scripts/palette.mjs --brand "#FF8A3D"
Checkers, so it's not just vibes. The first one reads your code, no dependencies:
node skills/oxfords/scripts/check.mjs ./src
src/components/Sidebar.tsx
FAIL accent-rail coloured bar on the side of an element; use a full fill or nothing (line 42)
border-left: 3px solid
FAIL default-font default font nobody chose; use the system stack or a face with a stated reason (line 7)
WARN viewport-100vh 100vh jumps on phones; use dvh or svh (line 18)
1 file, 2 fail, 1 warn
It exits with an error when something fails, so you can put it in CI or a pre-commit hook.
The second one actually opens the page. It renders it on a phone width and a desktop width, in light and dark, saves the screenshots, and measures the stuff you can't see in code: text that fails contrast, text that's clipped or overlapping, sideways scrolling, focus you can't see, buttons too small to tap, and how much of the screen is colour. It needs Playwright, and if you don't have it, it tells you and gets out of the way.
node skills/oxfords/scripts/shoot.mjs ./dist/index.html
Audit any site for AI slop. Point it at a URL (yours, a client's, a competitor's) and you get a score out of 100, a bar for type, colour, layout, copy and finish, and the site's own screenshots with every tell boxed and numbered, ranked by what it costs. It's one HTML file you can send to someone. The agent also looks at the screenshots itself and adds what a script can't see, like copy that says the same thing twice, and it can mark something as kept when it's actually the brand's thing and not slop.
node skills/oxfords/scripts/audit.mjs https://yoursite.com
Install
Claude Code, Codex and other agents that read skills
npx skills add arhamhi/oxfords
Or copy skills/oxfords into your skills folder (~/.claude/skills/ for Claude Code,
~/.agents/skills/ for Codex and others).
Cursor
Copy skills/oxfords into your project and adapters/cursor/oxfords.mdc into
.cursor/rules/.
Anything that reads AGENTS.md
Copy skills/oxfords into your project and paste adapters/AGENTS.md into your AGENTS.md.
Use
You don't have to do anything special. Ask for UI work the way you already do and the skill loads when the task is a UI.
Build the orders dashboard.
Review this settings page with oxfords.
Audit https://yoursite.com for AI slop.
This looks AI-generated. Fix it.
It has five commands. You can name one, or just ask and it picks:
| Command | What happens |
|---|---|
| Build | Reads the brief, works a twelve-step build order from intent to finished states, measures the result and fills a done gate |
| Redesign | Writes down what has to stay first (links, labels, field |
// HOW IT'S BUILT
// FILES
31 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.
skills/oxfords/SKILL.md17 KB4d675937c0c7upstream โ
--- name: oxfords description: Use when building, changing, redesigning, reviewing or auditing any interface a person operates - dashboard, admin panel, table, form, settings, modal, onboarding, mobile app screen, landing page, website - or choosing its colours, palette or dark theme. Also use when a UI looks AI-generated, cluttered, generic, "vibe coded", over-decorated, unfinished or hard to scan, when asked to remove AI slop, make a UI clean, plain, polished or professional, fix the UX, or check a build before shipping, and when asked to audit or score a website or page for AI slop ("how AI-generated does my site look", "audit my landing page"). license: MIT --- # Oxfords Oxfords, not brogues. An Oxford is the plain shoe. A brogue is the same shoe with decoration punched into it. This skill makes interfaces that are polished, plain and finished, and removes the decoration that marks a screen as machine-made. It does not make a product look striking or give it a brand. It decides what goes on the screen, where, how visible, how it responds, and what must not be there. **The test behind every rule:** nobody reads a screen. They arrive with one question and hunt for the answer. A choice either makes that hunt faster or it is decoration. **Plain is not generic, and it is not colourless.** Stripping slop and stopping leaves a white page with grey text and one blue button. That is a default too. Plain is about structure: every element there for a reason, and finished. Colour is where the product gets its character. Build on neutrals and put a real palette on top of them. **Measured, not assumed.** Contrast, clipping, overflow, focus and how much of the screen is colour are measured by the scripts in this skill. A screen is done when the measurements pass and you have looked at the screenshots, not when the code looks right. ## Commands Pick the command from the request. Each one has its reference; read it before starting. | Command | When | Do this | Reference | |---|---|---|---| | `build` | A new screen, page or component | Work the Build order, read the reference for your surface, fill the Done gate | the surface table below | | `redesign` | An existing screen gets a new look | Write the Keep list first, then work the Build order, then prove nothing went missing | `references/redesign.md` | | `review` | "Review this", "is this good", before shipping | Look pass first, then measure. Report `symptom -> fix -> why` with severity | `references/review.md` | | `audit` | "Audit my site for AI slop", "score this page", a URL to judge | Run `audit.mjs`, add a look pass, hand over the report: a score out of 100, five bars, every tell boxed on the page's own screenshots | `references/audit.md` | | `fix` | After a review or audit | Change only what the finding names, most costly first. Keep existing copy, names and identity. Re-run what found it | the finding's reference | No command named and none clearly implied: a URL or a finished page to judge is `audit`, code to change is `build` or `fix`. Ask only when two fit equally. Precedence, highest first: 1. The project's own `DESIGN.md`, design system, tokens or brand rules. 2. A published design system the product already lives in (Material, Fluent, Carbon, Polaris, Primer, Apple's HIG, a shadcn/ui theme): build with its components and tokens. 3. Oxfords, for everything those leave open. In a redesign, the existing styles are part of what is being redesigned, not a design system to obey. Keep what the brand owns (its hue, its chosen typeface, its names) and replace its defaults. `references/redesign.md` draws the line. | Surface | Read first | |---|---| | Dashboard, admin, table, chart, settings (including on a phone browser) | `references/app-ui.md` | | Native mobile app screen | `references/mobile.md` | | Landing page, marketing site | `references/landing.md` | | Redesign of an existing screen | `references/redesign.md` | | States, forms, errors, UX copy | `references/states-forms-copy.md` | | Colour: palettes, tokens, states, dark mode, a client's colours | `references/colour.md` (read this for every build) | | Fonts, icons, the full ban list | `references/slop-floor.md` | | Motion, gestures, reduced motion | `references/motion.md` | | Reviewing a finished screen | `references/review.md` | | Auditing a live page or site for slop | `references/audit.md` | The scripts live in this skill's `scripts/` folder. They have no dependencies. Commands in this skill are written relative to the skill folder; from a project, use the full path: `node <path to skill>/scripts/<name>.mjs`. | Script | What it does | |---|---| | `palette.mjs` | Lists the palettes and generates every colour token for a palette, a mode and a ground. Takes a client's colour with `--brand`. | | `check.mjs` | Fast pass over source files for the mechanical tells. | | `shoot.mjs` | Renders the page at 390 and 1440 wide, light and dark. Saves screenshots and measures contrast, clipped and overlapping text, sideways scroll, focus, target size, names and colour share. Uses Playwright when it is installed and exits with code 3 when it is not. | | `keep.mjs` | Compares a redesign with the original: link targets, navigation labels, form fields, Keep-list lines and numbers. Reports changed headings. | | `audit.mjs` | Scores a URL or page for AI slop out of 100 and writes one self-contained HTML report with the screenshots marked up. Runs the render check and `check.mjs` inside it. Needs Playwright, like `shoot.mjs`. | ## Build order 1. **Read.** Write one line before anything else: "Reading this as: [product] for [who], used [where and when], so [light / dark / both], [dense / roomy]." Light or dark is decided here, by who uses it and where, not by the product's category. A native app is both: the system decides. Where the brief is open, choose and say so in that line. Ask only when a wrong guess would waste the build. 2. **Intent.** Name what the user came to do. Start with the control that does it. For each thing you add, ask whether it does anything the plain version did not. Add function only as intent grows. 3. **Content first.** Write every label, number and name before laying anything out. Use uneven, believable data: real-looking names, odd totals, one long value. Show only what a person scans for; detail lives one step in. One surface does one job. 4. **Let the data pick the component.** A fixed set of values is a chip. Numbers in columns are right-aligned with tabular figures. Time-based data is a timeline or a roll-up chart, not a time-sorted table. Inactive items stay in place, greyed. Do not reach for a table or a row of tiles by reflex. 5. **Layout on edges.** Left-align labels, right-align values, centre only what is not meant to be read. Every element locks to an edge and creates the edge for the next. Fill empty space by moving content onto edges, not by adding content. Use the layout people expect (top to bottom, left to right, navigation on top or left) before anything distinctive. 6. **Colour.** Generate it; write no colour values by hand. Pick a palette with `palette.mjs list --mode <mode>` as `references/colour.md` describes, or pass the project's own colour with `--brand`. Then paste the output of `palette.mjs <Name> --mode <mode>` into the stylesheet. Every colour on the page is one of those tokens: - neutrals cover most of the screen - lead, support and pop go on content, each with one job - controls stay neutral - errors and destructive actions use `--danger` Write one line on why the palette fits. 7. **Hierarchy.** Size, position, weight, then colour. Most important goes top-left and largest. Group, rank, stack, then delete every label the layout already implies. Emphasis is relative: quiet the neighbours instead of colouring the hero. Text has three levels: `--text`, `--text-2`, `--text-3`. 8. **Disclosure.** Primary action always visible with a label. Secondary actions in a menu, or revealed on hover with a visible equivalent on touch. Rare ones in a popover. Never put a primary item behind a click. 9. **Container.** Inline first, if it fits. Then: simple and non-blocking is a popover; complex but same page is a modal followed by a confirmation; large or permanent is a new page with a way back; on mobile, picking without leaving is a bottom sheet. 10. **The invisible layer.** States, feedback, focus, empty and broken content. This is the half that gets skipped. The Done gate lists it. 11. **Check.** Run `check.mjs` on the source, then `shoot.mjs` on the page (add `--schemes light` or `--schemes dark` for a single-theme page). Open every screenshot yourself: both widths, and both themes if you ship both. - Fix every FAIL. A FAIL on something the project owns (its chosen font, its brand colour) gets `oxfords-ignore` on that line in the source, with the reason in the report. - Fix each WARN, or write one line on why it stays. - Compare the colour share with `references/colour.md`: product UI at least 75% neutral, a landing page at least 60%. Outside that, fix it or give the reason. - Fill the Done gate. If `shoot.mjs` exits 3 (no browser), take screenshots another way. Failing that, say plainly in the report that contrast and layout were not measured. 12. **Record.** In a real project (not a one-off mock), write or update `DESIGN.md` at the project root in ten to twenty lines: - the `palette.mjs` command that made the tokens - mode and ground - type family and scale - radius tiers and spacing steps - icon set and weight - each deliberate exception, with its reason The next session reads it first. ## Done gate Answer every line for the screen you built. "None" needs a reason. | Slot | Must exist | |---|---| | Buttons | default, hover, focus-visible, pressed, disabled with the reason in text beside it, each from the state tokens; loading only where the user waits | | Inputs | a persistent label above (a table toolbar's search and filters may carry their label inside the control), focus, error below the field that says how to fix it, input kept after an error | | Every action | a response where the user is looking, within 100ms: the control changes in place, or a toast with undo | | Destructive actions | `--danger`, never a palette colour; undo where possible, otherwise a confirm that names the object and labels the button with the action | | Icon-only controls | an accessible name and a tooltip; anything not universally known gets a text label instead | | Empty | first run (one sentence and the one action that fills it) and no results (quote the query, offer to clear it) | | Loading and failure | where data loads, a skeleton shaped like the result after about 300ms; error says what failed and how to recover; offline and no-permission handled | | Messy content | long names truncate with the full value available, 0 / 1 / 10,000 rows work, a missing image is handled | | Tables | search, filter or sort; numbers right-aligned; one primary action per row; selection reveals a bulk action in the existing toolbar | | Charts | plain line or bar from the series tokens; a full chart has axis values, grid lines, labels, a value on hover or focus, and a range or metric control when more than one range or metric exists; a small chart may label each bar or point directly instead; more than three series are labelled directly | | Navigation | current location shown, items named for their contents, grouped, rare items last, about five top-level items | | Keyboard and contrast | everything reachable by Tab with visible focus, Esc closes overlays; `shoot.mjs` reports no contrast, focus or target FAIL; state never by colour alone | | Touch | 44px targets, nothing that works only on hover, 16px inputs, safe areas respected | | Motion | under 250ms for feedback, never blocks input, a reduced-motion version that keeps the feedback | | Colour | every colour is a token: the project's or its design system's when it has them, else `palette.mjs`; neutrals cover most of the screen; each role on screen does one job, and no content was invented to give a role one; controls neutral; no bone or cream page | | Themes | the mode chosen in step 1 is the one shipped; when both ship, each was generated with `--mode both`, measured and looked at | | Consistency | one type family, one palette, one icon set with one weight per text size, one radius per tier, same thing looks and behaves the same everywhere | | Slop floor | `check.mjs` passes, or every warning has a one-line reason | | Redesign | `keep.mjs` shows nothing from the Keep list missing, or each change is named with its reason | ## Slop floor The marks of a generated interface. Remove them and put the plain replacement in their place. The full list, with replacements, is in `references/slop-floor.md`. - **Structure:** a coloured bar down the side of the active nav item or a card; a card around everything; cards inside cards; a divider between everything; tags and pills everywhere; a small uppercase label above every heading; numbered section labels; a greeting header; a row of icon-and-number tiles; an over-detailed mock UI or fake window chrome in the hero; the same figures repeated on several pages; controls that do nothing. - **Type and icons:** a default font nobody chose, such as Inter, Geist, Roboto, Poppins, Instrument Serif or Playfair Display (the full list is in `references/slop-floor.md`); a serif word dropped into a sans headline; an italic word in every heading; monospace as a costume on labels and headings; ALL CAPS subtitles; emoji as icons; icons whose stroke does not match the text beside them; an icon in a tinted square above every heading. - **Colour:** a bone or cream page with an orange or red accent; a neutral page whose only colour is one blue button; a whole interface tinted in palette colours with no neutrals; gradient backgrounds, purple or indigo above all; gradient text; glows and blurred colour blobs; a tinted pill on every status; the brand colour on a delete button; translucent text for hierarchy; colour values written by hand outside the tokens. - **Motion:** bounce; everything fading up on scroll; pulsing dots; marquees; content hidden until a script reveals it. - **Copy:** seamless, effortless, unlock, elevate, supercharge; "Get started" and "Submit"; Acme and Jane Doe; round invented numbers; exclamation marks and em dashes; full stops at the end of headings; code syntax as decoration (`// features`, `~/work`); subtitles that repeat their heading. ## Numbers | Thing | Value | |---|---| | Spacing | multiples of 4; unequal by role: 4-12 inside a group, 24-40 between groups; more space above a heading than below it | | Radius | one per tier (controls, cards); nested inner = outer minus the gap | | Button padding | horizontal about twice vertical | | Icon size | the text line height; stroke matched to the text weight | | Type scale | about six steps, plus at most one hero figure or headline outside the scale. Web app 13-14px body, rarely above 24px. Native app 17pt body, 15 minimum for primary content, 13 for metadata. Marketing 16px body and up. Nothing under 11px | | Line length and leading | 45-75 characters; body leading about 1.5, display 1.05-1.2 | | Heading tracking | -2% to -4% on large display type only; body 0 | | Targets | 44px touch; 24px absolute floor on desktop | | Feedback timing | press 100-150ms; routine transitions 150-250ms; overlays up to 400ms; exits faster than entrances | | Easing | ease-out with no overshoot | | State colour | hover a step lighter, pressed a step darker, disabled grey with its reason in text; all from the tokens | | Shadows | two layers, a short darker one and a long soft one (`--shadow-1`, `--shadow-2`); if you notice the shadow it is wrong | | Dark mode depth | each layer up is lighter; borders brighter than in light mode; a shadow only under a floating layer | | Native app ground | pure black `#000` or pure white `#FFF`; navigation layer in Liquid Glass (native apps only; a web page on a phone follows `app-ui.md`) | | Figures | tabular figures in columns and tables where digits must line up; proportional figures in prose | | Contrast | 4.5:1 text, 3:1 large text, icons, input borders and focus rings; measured by `shoot.mjs` | ## Four tests before you call it done - **Squint.** Blur your eyes. One thing should land first, and it should be the right thing. - **Subtract.** Remove an element. If nothing got worse, it stays out. - **Swap.** Put a competitor's logo on it. If it still fits, the content is too generic. - **Defend.** Point at any value. You should be able to say why it is that and not the default. ## Credits Oxfords stands on other people's work. See `CREDITS.md` in the repository.skills/oxfords/scripts/audit.mjs13 KBc2b1a5a33f69upstream โ
#!/usr/bin/env node // Oxfords audit. Scores a live page or a local file for AI slop out of 100 and writes one // self-contained HTML report: the score, a bar per area, and the page's own screenshots with // every tell boxed and numbered, ranked by what it costs. // // node audit.mjs <url|file.html> [--out dir] [--notes notes.json] [--quick] [--json] // node audit.mjs --from <dir>/oxfords-audit.json [--notes notes.json] [--json] // // --out where the report, JSON and screenshots go (default ./oxfords-audit) // --notes look-pass findings to add to the score (see references/audit.md for the shape) // --quick skip the render check (contrast, focus, targets); Finish is then not measured // --from rebuild the report from an earlier run, with new notes, without a browser // --json print the result as JSON // Exit 0 done, 2 bad usage, 3 no browser. import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import { dirname, join, resolve } from 'node:path'; import { pathToFileURL } from 'node:url'; import { check } from './check.mjs'; import { openBrowser, resolveInput, shoot } from './shoot.mjs'; import { install } from './lib/inpage.mjs'; import { installSlop } from './lib/slop-inpage.mjs'; import { judgeSlop, score, TELLS, FROM_CHECK, CATS } from './lib/slop.mjs'; import { renderReport } from './lib/report.mjs'; const USAGE = `usage: node audit.mjs <url|file.html> [--out dir] [--notes notes.json] [--quick] [--json] node audit.mjs --from <dir>/oxfords-audit.json [--notes notes.json] [--json]`; const NO_BROWSER = `oxfords: no browser, so nothing was rendered. Get one with npm i -D playwright && npx playwright install chromium or set OXFORDS_PLAYWRIGHT to the directory of a playwright or playwright-core package.`; const CALM = `*,*::before,*::after{animation-duration:0s!important;animation-delay:0s!important; animation-iteration-count:1!important;transition-duration:0s!important;transition-delay:0s!important; scroll-behavior:auto!important}`; const VIEWS = [['desktop', 1440, 900], ['phone', 390, 844]]; const esc = s => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); // ---------- one look at the page per width ---------- async function look(browser, input, key, width, height, out, paths) { const ctx = await browser.newContext({ deviceScaleFactor: 1, reducedMotion: 'reduce', bypassCSP: true, viewport: { width, height } }); const page = await ctx.newPage(); try { await page.emulateMedia({ colorScheme: 'light', reducedMotion: 'reduce' }); await page.goto(input.url, { waitUntil: 'load', timeout: 45000 }); await page.addStyleTag({ content: CALM }); await page.evaluate(install); await page.evaluate(() => window.__oxf.settle()); await page.evaluate(installSlop); const data = await page.evaluate(() => window.__oxs.collect()); const boxes = paths.length ? await page.evaluate(p => window.__oxs.locate(p), paths) : []; const file = join(out, `${key}.jpg`); const buf = await page.screenshot({ fullPage: true, type: 'jpeg', quality: 72 }); writeFileSync(file, buf); let css = null; if (key === 'desktop') { const sh = await page.evaluate(() => window.__oxs.sheets()); const fetched = []; for (const href of sh.hrefs.slice(0, 20)) { try { const res = await ctx.request.get(href, { timeout: 10000 }); if (res.ok()) fetched.push((await res.text()).slice(0, 2_000_000)); } catch { /* skip it */ } } css = { own: sh.css, fetched, missed: sh.hrefs.length - fetched.length }; } // The real screenshot size: the page may be wider than the viewport. const dims = await page.evaluate(() => [document.documentElement.scrollWidth, Math.max(document.documentElement.scrollHeight, document.body?.scrollHeight || 0)]); return { data, boxes, css, shot: { file, w: Math.max(width, dims[0]), h: dims[1], width } }; } finally { await ctx.close(); } } // The page's copy and stylesheets as one document, so check.mjs can read them. function asSource(data, css) { const sheet = [...css.own, ...css.fetched.map(s => s.replace(/}/g, '}\n'))].join('\n'); const copy = data.copy.map(c => `<${c.tag}>${esc(c.t)}</${c.tag}>`); const imgs = data.imgs.map(i => (i.alt == null ? '<img src="x">' : `<img src="x" alt="${esc(i.alt).replace(/"/g, '"')}">`)); return `<style>\n${sheet}\n</style>\n${copy.join('\n')}\n${imgs.join('\n')}\n`; } // Merge findings from both widths into instances with a box per view. The nth instance of a // rule, path and text at one width is the nth at the other. function merge(lists) { const out = new Map(); for (const [key, fs] of lists) { const nth = new Map(); for (const f of fs) { const base = `${f.rule}|${f.path}|${f.text}`, k = nth.get(base) ?? 0; nth.set(base, k + 1); const id = `${base}|${k}`; let m = out.get(id); if (!m) out.set(id, m = { rule: f.rule, level: f.level, text: f.text, path: f.path, boxes: {} }); if (f.level === 'fail') m.level = 'fail'; if (f.box && !m.boxes[key]) m.boxes[key] = f.box; } } return [...out.values()]; } // Look-pass notes: findings only eyes can make, and measured tells the brand owns. // { "rule": "verbose-copy", "text": "..." } a known tell // { "cat": "layout", "title": "...", "fix": "...", "why": "..." } a new one // { "rule": "purple-gradient", "keep": "the brand's own colour" } kept on purpose, costs nothing export function readNotes(file) { if (!file) return []; let notes; try { notes = JSON.parse(readFileSync(file, 'utf8')); } catch (e) { throw new Error(`cannot read notes ${file}: ${e.message}`); } return parseNotes(notes); } export function parseNotes(notes) { if (!Array.isArray(notes)) throw new Error('notes must be a JSON array of findings'); const cats = new Set(CATS.map(c => c.id)); return notes.map((n, i) => { if (n.keep) { if (!n.rule) throw new Error(`note ${i + 1}: keep needs the rule it keeps`); return { rule: n.rule, keep: String(n.keep) }; } const known = TELLS[n.rule]; const cat = n.cat ?? known?.[0]; if (!known && (!cat || !cats.has(cat) || !n.title)) throw new Error(`note ${i + 1}: give a known rule, or cat (${[...cats].join(', ')}) and title`); if (n.level && !['fail', 'warn'].includes(n.level)) throw new Error(`note ${i + 1}: level is fail or warn`); return { rule: n.rule ?? `look-${i + 1}`, cat, title: n.title, fix: n.fix, why: n.why, level: n.level ?? 'warn', text: n.text ?? '', path: n.path ?? '', boxes: {}, judged: true }; }); } export function build(raw, notes) { const keep = new Map(notes.filter(n => n.keep).map(n => [n.rule, n.keep])); const findings = [...raw.findings.filter(f => !keep.has(f.rule)), ...notes.filter(n => !n.keep)]; const kept = [...keep].map(([rule, reason]) => ({ rule, reason, title: TELLS[rule]?.[1] ?? rule, count: raw.findings.filter(f => f.rule === rule).length })); return { ...raw, notes, kept, score: score(findings) }; } function write(result, out) { const json = join(out, 'oxfords-audit.json'), html = join(out, 'oxfords-audit.html'); writeFileSync(json, JSON.stringify(result, null, 2)); writeFileSync(html, renderReport(result)); return { json, html }; } function print(result, files) { const s = result.score; console.log(`\n${result.input}\n ${s.total}/100 ${s.band}\n`); for (const c of s.cats) console.log(` ${c.label.padEnd(8)} ${String(c.score).padStart(2)}/${c.max} ${c.tells ? `${c.tells} tell${c.tells === 1 ? '' : 's'}` : 'clean'}`); if (s.tells.length) { console.log('\n ranked by cost'); s.tells.forEach((t, i) => console.log(` ${String(i + 1).padStart(2)}. ${t.level.toUpperCase().padEnd(4)} ${t.title} (${t.items.length}, -${t.cost})${t.judged ? ' look pass' : ''}`)); } console.log(`\n report ${files.html}\n data ${files.json}`); for (const k of result.kept ?? []) console.log(` kept ${k.title}: ${k.reason}`); if (!result.notes.length) console.log(' next do the look pass in references/audit.md, then rebuild with --from and --notes'); } export async function audit(browser, input, o) { mkdirSync(o.out, { recursive: true }); // 1. The render check: contrast, clipping, focus, targets. Skipped with --quick. let renderFindings = [], shootPaths = { desktop: [], phone: [] }; if (!o.quick) { const [entry] = await shoot(browser, [input], { out: join(o.out, 'render-check'), widths: [1440, 390], schemes: ['light', 'dark'] }); const keyOf = w => (w <= 480 ? 'phone' : 'desktop'); renderFindings = [...entry.findings.map(f => ({ ...f, key: 'desktop' })), ...entry.renders.flatMap(r => r.findings.map(f => ({ ...f, key: keyOf(r.width) })))] .filter(f => f.level !== 'info' && TELLS[f.rule]); for (const f of renderFindings) if (f.path && !shootPaths[f.key].includes(f.path)) shootPaths[f.key].push(f.path); } // 2. The slop pass at each width. const looks = {}; for (const [key, w, h] of VIEWS) looks[key] = await look(browser, input, key, w, h, o.out, shootPaths[key]); // 3. Pin render-check findings to boxes on the screenshot they came from. const pinned = renderFindings.map(f => { const i = shootPaths[f.key].indexOf(f.path); return { rule: f.rule, level: f.level, text: f.text ? `${f.msg}: ${f.text}` : f.msg, path: f.path, box: i >= 0 ? looks[f.key].boxes[i] : null, key: f.key }; }); // 4. check.mjs over the page's own copy and stylesheets. const fromCheck = check(asSource(looks.desktop.data, looks.desktop.css)) .filter(f => FROM_CHECK.has(f.id)) .map(f => ({ rule: f.id, level: f.level, text: f.text, path: '' })); const findings = merge([ ['desktop', judgeSlop(looks.desktop.data)], ['phone', judgeSlop(looks.phone.data)], ['desktop', pinned.filter(f => f.key === 'desktop')], ['phone', pinned.filter(f => f.key === 'phone')], ['desktop', fromCheck], ]); const css = looks.desktop.css; return { input: input.label, url: input.url, date: new Date().toISOString().slice(0, 10), shots: { desktop: looks.desktop.shot, phone: looks.phone.shot }, findings, measured: `rendered in Chromium at 1440 and 390 wide${o.quick ? '' : ', light and dark, with the render check (contrast, clipping, focus, targets, names)'}; ` + `the page copy and ${css.own.length + css.fetched.length} stylesheets read${css.missed ? `, ${css.missed} could not be fetched` : ''}`, notChecked: [o.quick ? 'contrast, focus and targets (run without --quick)' : null, 'other pages of the site, states behind clicks or logins, other browsers and real devices, a screen reader'].filter(Boolean).join('; '), }; } // ---------- CLI ---------- function parseArgs(argv) { const o = { json: false, quick: false, inputs: [] }; for (let i = 0; i < argv.length; i++) { let a = argv[i], v; if (a.startsWith('--') && a.includes('=')) [a, v] = [a.slice(0, a.indexOf('=')), a.slice(a.indexOf('=') + 1)]; if (a === '--json') o.json = true; else if (a === '--quick') o.quick = true; else if (a === '--help' || a === '-h') o.help = true; else if (['--out', '--notes', '--from'].includes(a)) { v ??= argv[++i]; if (!v) return { error: `${a} needs a value` }; o[a.slice(2)] = resolve(v); } else if (a.startsWith('-')) return { error: `unknown flag ${a}` }; else o.inputs.push(a); } return o; } async function main() { const o = parseArgs(process.argv.slice(2)); if (o.help) { console.log(USAGE); return; } if (o.error || (!o.from && o.inputs.length !== 1)) { console.error(o.error ? `oxfords: ${o.error}\n${USAGE}` : USAGE); process.exitCode = 2; return; } let notes; try { notes = readNotes(o.notes); } catch (e) { console.error(`oxfords: ${e.message}`); process.exitCode = 2; return; } let raw, out; if (o.from) { if (!existsSync(o.from)) { console.error(`oxfords: cannot read ${o.from}`); process.exitCode = 2; return; } const prev = JSON.parse(readFileSync(o.from, 'utf8')); raw = { ...prev, notes: undefined, score: undefined }; if (!o.notes) notes = prev.notes ?? []; out = dirname(o.from); } else { const input = resolveInput(o.inputs[0]); if (!input) { console.error(`oxfords: cannot read ${o.inputs[0]}`); process.exitCode = 2; return; } out = o.out ?? resolve('oxfords-audit'); const browser = await openBrowser(); if (!browser) { console.error(NO_BROWSER); process.exitCode = 3; return; } try { raw = await audit(browser, input, { ...o, out }); } finally { await browser.close(); } } const result = build(raw, notes); const files = write(result, out); if (o.json) console.log(JSON.stringify({ score: result.score.total, band: result.score.band, cats: result.score.cats, tells: result.score.tells.map(t => ({ rule: t.rule, level: t.level, title: t.title, count: t.items.length, cost: t.cost })), ...files }, null, 2)); else print(result, files); } if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) main();skills/oxfords/scripts/audit.test.mjs8.6 KBc90225e79fa1upstream โ
// Run: node audit.test.mjs // Scoring, notes and the rendered-page judge are always tested. The full audit runs on // fixtures/ when a browser loads (see shoot.mjs for how Playwright is found). import assert from 'node:assert'; import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { audit, build, parseNotes } from './audit.mjs'; import { check } from './check.mjs'; import { openBrowser, resolveInput } from './shoot.mjs'; import { judgeSlop, score, band } from './lib/slop.mjs'; import { renderReport } from './lib/report.mjs'; const here = dirname(fileURLToPath(import.meta.url)); // ---------- scoring ---------- assert.equal(score([]).total, 100); assert.equal(band(100), 'Reads as designed'); assert.equal(band(80), 'A few tells'); assert.equal(band(60), 'Generated in places'); assert.equal(band(40), 'Reads as generated'); assert.equal(band(10), 'Template'); { const s = score([ { rule: 'default-font', level: 'fail', text: 'Inter' }, ...Array.from({ length: 6 }, (_, i) => ({ rule: 'period-title', level: 'warn', text: `Title ${i}.` })), { rule: 'colour-share', level: 'info', text: '' }, ]); const type = s.cats.find(c => c.id === 'type'), copy = s.cats.find(c => c.id === 'copy'); assert.equal(type.score, 13, 'one fail costs 7'); assert.equal(copy.score, 13, 'a warn costs 4, extra places cost 1 each up to 3'); assert.equal(s.total, 86); assert.equal(s.tells.length, 2, 'info findings cost nothing'); assert.equal(score(Array.from({ length: 9 }, () => ({ rule: 'tiny-text', level: 'fail' }))).cats[0].score, 10); } // ---------- notes ---------- { const notes = parseNotes([ { rule: 'verbose-copy', text: 'Hero paragraph is 80 words' }, { cat: 'layout', title: 'Logo wall of nine fake brands', fix: 'Show real customers or none', level: 'fail' }, { rule: 'purple-gradient', keep: 'the brand colour since 2014' }, ]); const raw = { findings: [{ rule: 'purple-gradient', level: 'fail', text: '', path: '', boxes: {} }, { rule: 'em-dash', level: 'warn', text: 'โ', path: '', boxes: {} }] }; const r = build(raw, notes); assert(!r.score.tells.some(t => t.rule === 'purple-gradient'), 'a kept tell costs nothing'); assert.equal(r.kept[0].count, 1); assert(r.score.tells.some(t => t.rule === 'verbose-copy' && t.judged)); assert(r.score.tells.some(t => t.title === 'Logo wall of nine fake brands' && t.level === 'fail')); assert.throws(() => parseNotes([{ title: 'no category' }]), /known rule, or cat/); assert.throws(() => parseNotes([{ keep: 'why' }]), /keep needs the rule/); assert.throws(() => parseNotes({}), /JSON array/); } // ---------- the rendered-page judge, on collected facts ---------- { const page = { w: 1440, h: 2700, vw: 1440, vh: 900 }; const t = (o) => ({ tag: 'p', t: 'Plain sentence about invoices', len: 28, words: 4, box: [0, 1000, 400, 20], fam: 'system-ui', mono: false, code: false, act: false, italic: false, tt: 'none', ls: 0, fs: 16, fw: 400, inHead: false, path: 'p', ...o }); const head = (o) => ({ tag: 'h2', level: 2, t: 'Invoices', box: [0, 500, 600, 40], fs: 32, fam: 'system-ui', italic: false, italicKids: 0, famKids: [], path: 'h2', ...o }); const base = { page, fonts: { body: 'system-ui' }, texts: [t({})], heads: [head({})], boxes: [], lines: [], pills: [], grads: [], dots: [], rails: [], copy: [], imgs: [] }; const rules = d => new Set(judgeSlop({ ...base, ...d }).map(f => f.rule)); assert.deepEqual([...rules({})], [], 'a plain page is clean'); assert(rules({ fonts: { body: 'Inter' } }).has('default-font')); assert(rules({ heads: [head({ t: 'Built for teams.' })] }).has('period-title')); assert(!rules({ heads: [head({ t: 'Loading...' }), head({ t: 'Why now?' })] }).has('period-title')); assert(rules({ heads: [head({ italicKids: 1 }), head({ italicKids: 2, t: 'Ship' })] }).has('italic-heading')); assert(!rules({ heads: [head({ italicKids: 1 })] }).has('italic-heading'), 'one italic accent is a choice'); assert(rules({ texts: [t({ t: 'THE FINANCE TOOL FOR SMALL STUDIOS', tt: 'none', words: 6 })] }).has('caps-subtitle')); assert(rules({ texts: [t({ t: '// features', words: 1 })] }).has('code-breadcrumb')); assert(!rules({ texts: [t({ t: '// features', words: 1, code: true })] }).has('code-breadcrumb')); assert(rules({ texts: [t({ t: 'Our process and our team', mono: true, len: 400 })] }).has('mono-costume')); assert(!rules({ texts: [t({ t: '$48,200.00', mono: true, len: 400 }), t({})] }).has('mono-costume'), 'figures in mono are fine'); const pills = n => Array.from({ length: n }, (_, i) => ({ box: [i * 80, 300, 70, 24], t: `Tag ${i}`, act: false, path: 'span.pill' })); assert(rules({ pills: pills(5) }).has('pill-overuse')); assert(!rules({ pills: pills(4) }).has('pill-overuse')); assert(!rules({ pills: pills(8).map(p => ({ ...p, act: true })) }).has('pill-overuse'), 'pill-shaped buttons are controls'); const lines = n => Array.from({ length: n }, (_, i) => ({ box: [0, 100 + i * 40, 600, 1], path: 'div.row', menu: false })); assert(rules({ lines: lines(9) }).has('divider-overuse')); assert(!rules({ lines: lines(5) }).has('divider-overuse')); assert(rules({ grads: [{ stops: ['rgba(14,165,233,1)', 'rgba(34,197,94,1)'], box: [0, 0, 1440, 600], path: 'section' }] }).has('gradient-bg')); assert(rules({ grads: [{ stops: ['rgba(99,102,241,1)', 'rgba(168,85,247,1)'], box: [0, 0, 1440, 600], path: 'section' }] }).has('purple-gradient')); assert(!rules({ grads: [{ stops: ['rgba(0,0,0,0.6)', 'rgba(0,0,0,0)'], box: [0, 0, 1440, 600], path: 'figure' }] }).size, 'a neutral scrim is fine'); const dot = (x, bg) => ({ box: [x, 40, 12, 12], bg }); assert(rules({ dots: [dot(20, 'rgba(255,95,87,1)'), dot(38, 'rgba(254,188,46,1)'), dot(56, 'rgba(40,200,64,1)')] }).has('fake-chrome')); assert(rules({ rails: [{ box: [0, 0, 300, 40], path: 'a.active', colour: 'rgba(37,99,235,1)' }] }).has('accent-rail')); assert(!rules({ rails: [{ box: [0, 0, 300, 40], path: 'blockquote', colour: 'rgba(180,180,180,1)' }] }).has('accent-rail')); assert(rules({ texts: [t({ fs: 10, t: 'tiny' })] }).has('tiny-text')); assert(rules({ heads: [head({ t: 'Invoices that send themselves' })], texts: [t({ t: 'Your invoices send themselves on time', box: [0, 550, 500, 20], words: 6 })] }).has('redundant-sub')); } // ---------- the full audit, when a browser is available ---------- const browser = await openBrowser(); if (!browser) console.log('skipped: no browser (scoring, notes and the judge passed)'); else { const out = mkdtempSync(join(tmpdir(), 'oxfords-audit-')); try { const t0 = Date.now(); const slop = build(await audit(browser, resolveInput(join(here, 'fixtures/slop.html')), { out: join(out, 'slop'), quick: true }), []); const found = new Set(slop.score.tells.map(t => t.rule)); const want = ['default-font', 'bone-page', 'period-title', 'pill-overuse', 'divider-overuse', 'bordered-boxes', 'nested-boxes', 'mono-costume', 'eyebrow', 'italic-heading', 'gradient-bg', 'code-breadcrumb', 'caps-subtitle', 'fake-chrome', 'dense-mock', 'em-dash', 'vague-button', 'tiny-text']; for (const r of want) assert(found.has(r), `slop.html: expected ${r}, got ${[...found].join(', ')}`); assert(slop.score.total < 40, `slop.html scored ${slop.score.total}`); assert(slop.findings.some(f => f.boxes.desktop) && slop.findings.some(f => f.boxes.phone), 'findings are pinned at both widths'); const good = build(await audit(browser, resolveInput(join(here, 'fixtures/good.html')), { out: join(out, 'good'), quick: false }), []); assert.equal(good.score.total, 100, `good.html: ${good.score.tells.map(t => t.rule).join(', ')}`); // The report holds itself to the same rules, and loads nothing from outside. const html = renderReport(slop); // Quotes from the audited page are its copy, not the report's. const own = html.replace(/<ul class="quotes">[\s\S]*?<\/ul>/g, m => m.replace(/[^\n]/g, ' ')); const self = check(own).filter(f => f.level !== 'info' && f.id !== 'raw-colour'); assert.deepEqual(self.map(f => `${f.id}:${f.line}`), [], 'the report fails its own check'); assert(!/(?:src|href)="https?:/.test(html.replace(/<a href="[^"]*"/g, '')), 'the report loads an outside file'); assert(/<title>[^<]+ audit<\/title>/.test(html)); console.log(`ok: slop.html ${slop.score.total}/100 with all ${want.length} tells, good.html 100/100, report passes its own check, ${((Date.now() - t0) / 1000).toFixed(1)}s`); } finally { await browser.close(); rmSync(out, { recursive: true, force: true }); } } console.log('ok: scoring, notes and the rendered-page judge');skills/oxfords/scripts/check.mjs36 KB70ea8b2cf7b0upstream โ
Contents are not inlined in the catalog. Open the upstream file.
skills/oxfords/scripts/check.test.mjs14 KBff88a713f154upstream โ
// Run: node check.test.mjs (the smallest thing that fails if a rule breaks) import assert from 'node:assert'; import { check } from './check.mjs'; const ids = s => new Set(check(s).map(f => f.id)); const find = (s, id) => check(s).find(f => f.id === id); // Every rule fires on its fixture. const bad = [ ['default-font', `body{font-family: "Inter", sans-serif}`], ['default-font', `:root{--font: "Inter", system-ui, sans-serif}`], ['emoji', `<h2>๐ Launch</h2>`], ['gradient-text', `h1{-webkit-background-clip:text;background-clip: text}`], ['purple-gradient', `.hero{background:linear-gradient(90deg,#6366f1,#a855f7)}`], ['purple-gradient', `.hero{background:linear-gradient(90deg, oklch(55% 0.2 285), #3b82f6)}`], ['purple-gradient', `:root{--brand:#7a5cff}\n.hero{background-image:radial-gradient(circle, var(--brand), transparent 70%)}`], ['accent-rail', `.nav a.active{border-left: 3px solid #17644a}`], ['accent-rail', `:root{--lead:#075431}\n.nav a.active{border-left:3px solid var(--lead)}`], ['bounce', `.b{transition:transform .3s cubic-bezier(0.34, 1.56, 0.64, 1)}`], ['greeting-header', `<h1>Good evening, Maya</h1>`], ['tiny-text', `.meta{font-size:10px}`], ['img-no-alt', `<img src="a.png">`], ['em-dash', `<p>Fast โ and simple</p>`], ['buzzword', `<p>A seamless way to work</p>`], ['vague-button', `<button>Get started</button>`], ['placeholder-content', `<td>Jane Doe</td>`], ['glow', `.card{box-shadow:0 0 40px rgba(99,102,241,.5)}`], ['viewport-100vh', `.app{min-height:100vh}`], ['eyebrow', `.eyebrow{text-transform:uppercase;letter-spacing:.08em}`], ['no-focus-style', `button{outline:none}`], ['no-reduced-motion', `.a{transition: opacity .2s}`], ['bone-page', `:root{--bg:#FBF1E3}\nbody{margin:0;background:var(--bg)}`], ['bone-page', `:root{--page:oklch(96% 0.02 85)}\nbody{background:var(--page)}`], ['bone-page', `:root{--cream:#FBF1E3;--paper:var(--cream);--page:var(--paper)}\nbody{background:var(--page)}`], ['bone-page', `html{background:#f5f1e8 url(grain.png) repeat}`], ['bone-page', `body{background-color:hsl(40 60% 95%)}`], ['bone-page', `<html><body class="bg-[#FBF1E3] text-stone-900"><h1>Ledger</h1></body></html>`], ['tinted-page', `body{background:oklch(96% 0.03 250)}`], ['tinted-page', `:root{--page:#fff}\n@media (prefers-color-scheme: dark){:root{--page:#0f172a}}\nbody{background:var(--page)}`], ['warm-dark-page', `:root{--page:#fff}\n[data-theme="dark"]{--page:#2b2118}\nbody{background:var(--page)}`], ['raw-colour', `.a{color:#111}.b{color:#222}.c{background:#f63434}.d{border-color:rgb(0 128 0)}\n.e{fill:hsl(200 50% 40%)}.f{color:oklch(60% .1 30)}.g{background:#fafafa}`], ['hue-sprawl', `:root{--a:#E14543;--b:#FF8A3D;--c:#28B467;--d:#028397;--e:#224D95}`], ['alpha-text', `.meta{color:rgba(17,17,17,.6)}`], ['alpha-text', `:root{--text-2:rgb(0 0 0 / 60%)}\np{color:var(--text-2)}`], ['alpha-text', `.card-caption{opacity:.7}`], ['alpha-text', `<p class="text-white/70">Paid in full</p>`], ['one-blue-button', `:root{--page:#fff;--text:#111;--accent:#2563EB}\nbody{background:var(--page);color:var(--text)}\n.btn{background:var(--accent);color:#fff}\na{color:var(--accent)}`], ['danger-as-brand', `:root{--lead:#075431;--danger:#C92A2A}\n.btn-delete{background:var(--lead);color:var(--lead-ink)}`], ['danger-as-brand', `[data-action="remove"]:hover{background:var(--support-hover);color:var(--on-support)}`], ['one-blue-button', `:root{--page:#fff;--lead:#2360E8;--support:#1E40AF;--pop:#DBEAFE;--info:#006DBD;--danger:#CC2827;--focus:#2360E8;--series-1:#2360E8}\nbody{background:var(--page)}\n:focus-visible{outline:2px solid var(--focus)}\n.btn.primary{background:var(--lead)}\na{color:var(--lead)}`], // From the 2026 tells list: pills, italics, dividers, code breadcrumbs, caps, gradients, full stops. ['period-title', `<h1>Built for teams.</h1>`], ['period-title', `<h2 class="t">Ship it <em>today</em>.</h2>`], ['code-breadcrumb', `<span class="label">// features</span>`], ['code-breadcrumb', `<p>~/work/clients</p>`], ['caps-subtitle', `<p class="text-sm uppercase text-gray-600">The finance tool for small studios that bill by the hour</p>`], ['caps-subtitle', `.hero-subtitle{text-transform:uppercase;font-size:18px}`], ['gradient-bg', `.hero{background:linear-gradient(135deg,#0ea5e9,#22c55e)}`], ['gradient-bg', `<section class="bg-gradient-to-b from-sky-50 to-white">`], ['fake-chrome', `.dot.red{background:#ff5f57}.dot.yellow{background:#febc2e}`], ['italic-heading', `<h2>Plan <em>less</em></h2>\n<h2>Ship <i>more</i></h2>`], ['pill-overuse', `<span class="badge">New</span><span class="badge">AI</span><span class="tag">Beta</span><span class="tag">Pro</span><span class="chip">Fast</span><span class="pill">Free</span>`], ['mono-costume', `.eyebrow{font-family:"JetBrains Mono",monospace}.nav a{font-family:ui-monospace}h2{font-family:"Geist Mono"}.stat-label{font:12px "IBM Plex Mono"}`], ['divider-overuse', `<hr><p>a</p><hr><p>b</p><hr><p>c</p><hr><p>d</p><hr><p>e</p><hr>`], ]; for (const [id, src] of bad) assert(ids(src).has(id), `expected ${id} on: ${src}`); // Levels and the detail each finding carries. assert.equal(find(bad.find(b => b[0] === 'bone-page')[1], 'bone-page').level, 'fail'); assert.equal(find(`:root{--page:#fff}\n[data-theme="dark"]{--page:#2b2118}\nbody{background:var(--page)}`, 'warm-dark-page').level, 'info'); assert.match(find(`:root{--a:#E14543;--b:#FF8A3D;--c:#28B467;--d:#028397;--e:#224D95}`, 'hue-sprawl').text, /5 families: red, orange, green, teal, blue/); assert.match(find(bad.find(b => b[0] === 'raw-colour')[1], 'raw-colour').text, /^7 distinct: #111, #222, #f63434/); // Each clean case stays clean of the rule it names: thresholds, and the false positives fixed. const quiet = [ ['raw-colour', `.a{color:#111}.b{color:#222}.c{background:#f63434}.d{border-color:rgb(0 128 0)}.e{fill:hsl(200 50% 40%)}.f{color:#fafafa}`], ['raw-colour', `.a{color:#111;box-shadow:0 1px 2px rgba(0,0,0,.1),0 8px 24px rgba(17,17,17,.14);background:transparent;border-color:currentColor}\n.b{color:var(--x, #333)}.c{color:inherit}.d{color:#222}.e{color:#333}.f{color:#444}.g{color:#555}`], ['raw-colour', `<style>.a{color:#111}</style><svg viewBox="0 0 4 4"><rect fill="#E14543"/><rect fill="#FF8A3D"/><rect fill="#28B467"/><rect fill="#028397"/><rect fill="#224D95"/><rect fill="#7C3AED"/><rect style="fill:#D93D7F"/></svg>`], ['hue-sprawl', `:root{--lead:#28B467;--support:#FF8A3D;--pop:#F7EB49;--chart-4:#224D95;--danger:#E14543;--info:#7C3AED;--success:#28B467;--warning:#C2410C;--accent-soft:#fdeee4;--support-soft:oklch(95% 0.04 330);--wash:rgb(124 58 237 / 6%)}`], ['bone-page', `body{background:#F4F4F5}`], ['bone-page', `body{background:#f6f4ef}`], ['bone-page', `body{background:#eff6ff}`], ['tinted-page', `body{background:#eff6ff}`], ['tinted-page', `:root{--page:#fff}\n@media (prefers-color-scheme: dark){:root{--page:#0a0a0a}}\nbody{background:var(--page)}`], ['alpha-text', `.hint{opacity:0;transition:opacity .2s}.hint.on{opacity:1}`], ['alpha-text', `label:has(input:disabled),label.disabled{opacity:.5}\n.label:hover{opacity:.8}\n.card.done{opacity:.6}\n.chart{background:rgba(0,0,0,.4)}\nli::marker{color:rgb(0 0 0 / 50%)}`], ['alpha-text', `<style>.submit{opacity:.8}.texture{opacity:.4}</style><p class="text-sm/6 text-gray-900">Paid</p>`], ['one-blue-button', `:root{--accent:#2563EB}\nbody{background:#fff}\n.btn{background:var(--accent)}\n.chart .bar{fill:var(--accent)}`], ['one-blue-button', `body{background:#fff}\nbutton:focus-visible{outline:2px solid #246}`], ['danger-as-brand', `:root{--lead:#075431;--danger:#C92A2A}\n.btn-delete{background:var(--danger);color:var(--danger-ink)}\n.delete-dialog p{color:var(--lead)}`], ['purple-gradient', `.top{background:linear-gradient(#000,rgba(0,0,0,0))}\n.a{background:linear-gradient(#fff,#eee)}.b{color:purple}`], // accent-rail: a 1px rule and a neutral 2px line are dividers, not rails. ['accent-rail', `.fig+.fig{padding-left:20px;border-left:1px solid var(--line)}`], ['accent-rail', `:root{--line:#E5E5E5}\n.tl{border-left:2px solid var(--line)}`], // layout-transition: colour transitions, and a layout word in the next rule on the same line. ['layout-transition', `.btn{transition:background-color .12s ease-out,transform .1s ease-out}`], ['layout-transition', `.a{transition:border-top-color .2s}`], ['layout-transition', `.a{transition:opacity .2s}.b{width:10px;left:0}`], // glow: a neutral ambient shadow, and a later rule's margin on the same line. ['glow', `.card{box-shadow:0 0 0 1px var(--line),0 0 24px rgba(0,0,0,.08)}`], ['glow', `.a{box-shadow:none}.b{margin:0 0 24px}`], // tiny-text: font-size:0 is the inline-block whitespace fix, not text. ['tiny-text', `.row{font-size:0px}`], ['tiny-text', `:root{--text-underline-offset:3px}`], // viewport-100vh: a 100vh fallback before 100dvh is deliberate. ['viewport-100vh', `.app{min-height:100vh;min-height:100dvh}`], // default-font: Roboto inside the system stack is a fallback, not a choice. ['default-font', `body{font-family:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}`], ['default-font', `body{font:15px/1.45 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}`], // em-dash and buzzwords in comments or code are not visible copy. ['em-dash', `<style>/* Poppy on white โ chrome stays neutral */</style><!-- draft โ v2 --><p>Orders</p>`], ['buzzword', `<script>\nconst unlock = () => audio.resume();\n</script><p>Orders</p>`], // period-title: an ellipsis, a question, and a full stop in body copy are fine. ['period-title', `<h1>Loading...</h1><h2>Why now?</h2><p>Paid in full.</p>`], // code-breadcrumb: real code samples and URLs in prose are not decoration. ['code-breadcrumb', `<pre>// set up the client</pre><code>~/projects</code><p>See https://example.com/docs</p>`], // caps-subtitle: a short letter-spaced eyebrow is the eyebrow rule's job; uppercase on a button is not a subtitle. ['caps-subtitle', `.kicker{text-transform:uppercase;letter-spacing:.08em}\n.btn{text-transform:uppercase}`], ['caps-subtitle', `<p class="uppercase tracking-wider text-xs">New</p>`], // gradient-bg: a neutral scrim over a photo is not a gradient background; a purple one is the purple rule's. ['gradient-bg', `.cover::after{background:linear-gradient(to top,rgba(0,0,0,.6),transparent)}`], ['gradient-bg', `.hero{background:linear-gradient(90deg,#6366f1,#a855f7)}`], // italic-heading: one italic accent is a choice, and italic body copy is not a heading. ['italic-heading', `<h1>Plan <em>less</em></h1><p>A <em>very</em> long <i>essay</i></p>`], // pill-overuse: a few status chips are fine. ['pill-overuse', `<span class="badge">Paid</span><span class="badge">Late</span><span class="badge">Draft</span>`], // mono-costume: monospace on code and figures is its job. ['mono-costume', `code,pre,kbd{font-family:ui-monospace,monospace}.num{font-family:"Commit Mono"}.figure{font-family:monospace}td.code{font-family:monospace}`], // divider-overuse: menu separators and a couple of section rules are fine. ['divider-overuse', `<hr><p>a</p><hr><div role="menu"><a>x</a><hr><a>y</a></div>`], ]; for (const [id, src] of quiet) assert(!ids(src).has(id), `did not expect ${id} on: ${src}`); // The old clean page: neutral, nothing flashy. const clean = `<!doctype html><style> body{font-family:system-ui,sans-serif;font-size:14px;background:#FAFAFA} .nav a[aria-current]{background:#eee} .b{transition:opacity .15s cubic-bezier(0.16, 1, 0.3, 1)} button:focus-visible{outline:2px solid #246} @media (prefers-reduced-motion: reduce){.b{transition:none}} </style><h1>Orders</h1><img src="a.png" alt="Kitchen pass"><button>Add order</button>`; assert.deepEqual([...ids(clean)], [], `clean fixture flagged: ${[...ids(clean)]}`); // A page written the new way: tokens in :root and a dark block, neutral controls, the palette // on a chart panel, --danger on the delete button, text hierarchy in solid greys. const tokens = `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Orders</title><style> :root{ --page:#FFFFFF; --surface:#F5F5F5; --line:#E5E5E5; --text:#111111; --text-2:#555555; --text-3:#767676; --lead:oklch(45% 0.11 160); --lead-ink:#FFFFFF; --lead-ink-2:#D3E8DE; --support:#D9480F; --pop:#FFD43B; --danger:#C92A2A; --danger-hover:#A61E1E; --danger-ink:#FFFFFF; --warning:#B35C00; --success:#2B8A3E; --info:#1971C2; --scrim:rgb(0 0 0 / 45%); --shadow:0 1px 2px rgba(0,0,0,.08), 0 8px 24px rgba(0,0,0,.06); } @media (prefers-color-scheme: dark){:root:not([data-theme="light"]){ --page:#000000; --surface:#161616; --line:#2A2A2A; --text:#F5F5F5; --text-2:#B3B3B3; --text-3:#8C8C8C; --lead:oklch(72% 0.12 160); --lead-ink:#000000; --lead-ink-2:#1F3A2D; --danger:#FF6B6B; --danger-ink:#000000; }} [data-theme="dark"]{--page:#0A0A0A; --surface:#161616; --text:#F5F5F5} *{box-sizing:border-box} html{color-scheme:light dark} body{margin:0;font:14px/1.5 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;background:var(--page);color:var(--text);min-height:100dvh} .meta{color:var(--text-2)} .hint{color:var(--text-3);font-size:13px} .btn{min-height:36px;padding:0 16px;border:1px solid var(--line);border-radius:6px;background:var(--surface);color:var(--text);transition:background-color .12s ease-out} .btn:hover{background:var(--line)} .btn:focus-visible{outline:2px solid var(--text);outline-offset:2px} .btn-delete{background:var(--danger);color:var(--danger-ink);border-color:var(--danger)} .btn-delete:hover{background:var(--danger-hover)} .chart{background:var(--lead);color:var(--lead-ink);border-radius:10px;padding:20px;box-shadow:var(--shadow)} .chart .legend{color:var(--lead-ink-2)} .chart .bar{fill:var(--pop)} .chart .late{fill:var(--support)} .figs{display:grid;grid-template-columns:repeat(4,1fr)} .fig+.fig{border-left:1px solid var(--line)} dialog::backdrop{background:var(--scrim)} @media (prefers-reduced-motion: reduce){.btn{transition:none}} </style></head><body> <h1>Orders</h1><p class="meta">Updated 4 minutes ago</p> <section class="chart"><h2>Takings this week</h2><p class="legend">This week against last</p> <svg viewBox="0 0 100 40" role="img" aria-label="Takings by day"><rect class="bar" x="0" y="10" width="8" height="30" fill="#FFD43B"/></svg></section> <button class="btn">Add order</button> <button class="btn btn-delete">Delete order 1043</button> </body></html>`; assert.deepEqual(check(tokens).map(f => `${f.id}:${f.line}`), [], 'token-model page flagged'); console.log(`ok: ${bad.length} fixtures fire, ${quiet.length} clean cases stay clean, both clean pages pass`);skills/oxfords/scripts/keep.mjs5.7 KB85647993b568upstream โ
#!/usr/bin/env node // Oxfords keep check. Zero dependencies. Compares a redesign with the page it replaces and // reports what went missing: link targets, navigation labels, form fields, data values, and // any line of a Keep list. Regex over HTML, so it reads what the markup says, not what a // script renders later. Run it on the built HTML when the page is assembled by JavaScript. // // node keep.mjs <original.html> <redesign.html> [--keep keep.txt] [--json] // // FAIL a link target, navigation label, form field name or Keep line is missing // WARN a number shown on the original is missing (data the redesign may have dropped) // INFO the title or a heading changed; new link targets import { readFileSync } from 'node:fs'; const strip = s => s .replace(/<!--[\s\S]*?-->/g, ' ') .replace(/<(script|style|template)\b[\s\S]*?<\/\1>/gi, ' '); const decode = s => s.replace(/ /g, ' ').replace(/&/g, '&').replace(/</g, '<') .replace(/>/g, '>').replace(/"/g, '"').replace(/'|'/g, "'") .replace(/·/g, 'ยท').replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(+n)); const text = s => decode(s.replace(/<[^>]+>/g, ' ')).replace(/\s+/g, ' ').trim(); const attrs = (html, tag, attr) => [...html.matchAll(new RegExp(`<${tag}\\b[^>]*\\b${attr}\\s*=\\s*(["'])(.*?)\\1`, 'gi'))] .map(m => decode(m[2]).trim()); export function extract(raw) { const html = strip(raw); const navs = [...html.matchAll(/<nav\b[\s\S]*?<\/nav>/gi)].map(m => m[0]); const navLabels = navs.flatMap(n => [...n.matchAll(/<(a|button)\b[^>]*>([\s\S]*?)<\/\1>/gi)] .map(m => text(m[2]) || (/aria-label\s*=\s*(["'])(.*?)\1/i.exec(m[0]) || [])[2] || '')).filter(Boolean); const body = text(html); return { title: text((/<title\b[^>]*>([\s\S]*?)<\/title>/i.exec(html) || [])[1] || ''), headings: [...html.matchAll(/<h([1-3])\b[^>]*>([\s\S]*?)<\/h\1>/gi)].map(m => text(m[2])).filter(Boolean), links: [...new Set([...attrs(html, 'a', 'href'), ...attrs(html, 'form', 'action')].filter(h => h && h !== '#'))], navLabels: [...new Set(navLabels)], fields: [...new Set(['input', 'select', 'textarea'].flatMap(t => attrs(html, t, 'name')))], // Numbers people read: times, money, counts. Single digits are too common to mean anything. numbers: [...new Set(body.match(/(?:[$ยฃโฌ]\s?)?\d[\d,.:]*\d%?|\d+%/g) || [])], body: body.toLowerCase(), }; } export function compare(oldHtml, newHtml, keepLines = []) { const a = extract(oldHtml), b = extract(newHtml); const findings = []; const add = (level, id, msg, items) => items.length && findings.push({ level, id, msg, items }); const lower = xs => new Set(xs.map(x => x.toLowerCase())); const bLinks = new Set(b.links), bNav = lower(b.navLabels), bFields = new Set(b.fields); add('fail', 'link-missing', 'link target on the original is gone', a.links.filter(h => !bLinks.has(h))); add('fail', 'nav-label-missing', 'navigation label on the original is gone or renamed', a.navLabels.filter(l => !bNav.has(l.toLowerCase()))); add('fail', 'field-missing', 'form field name on the original is gone', a.fields.filter(f => !bFields.has(f))); add('fail', 'keep-missing', 'line from the Keep list does not appear on the redesign', keepLines.filter(k => !b.body.includes(k.toLowerCase()))); const bNums = new Set(b.numbers); add('warn', 'number-missing', 'number shown on the original is not on the redesign', a.numbers.filter(n => !bNums.has(n) && !b.body.includes(n.toLowerCase()))); if (a.title && a.title !== b.title) add('info', 'title-changed', 'title changed', [`${a.title} -> ${b.title}`]); const bHeads = lower(b.headings); add('info', 'heading-changed', 'heading on the original is not on the redesign', a.headings.filter(h => !bHeads.has(h.toLowerCase()))); add('info', 'link-added', 'new link target', b.links.filter(h => !a.links.includes(h))); return { findings, counts: { links: a.links.length, navLabels: a.navLabels.length, fields: a.fields.length, numbers: a.numbers.length } }; } function main() { const args = process.argv.slice(2); const files = args.filter(x => !x.startsWith('--')); const keepAt = args.indexOf('--keep'); const keepFile = keepAt >= 0 ? args[keepAt + 1] : null; const paths = files.filter(f => f !== keepFile); if (paths.length !== 2 || args.includes('--help')) { console.log('usage: node keep.mjs <original.html> <redesign.html> [--keep keep.txt] [--json]'); process.exit(args.includes('--help') ? 0 : 2); } let oldHtml, newHtml, keep = []; try { oldHtml = readFileSync(paths[0], 'utf8'); newHtml = readFileSync(paths[1], 'utf8'); if (keepFile) keep = readFileSync(keepFile, 'utf8').split('\n').map(l => l.replace(/^[-*]\s+/, '').trim()).filter(l => l && !l.startsWith('#')); } catch (e) { console.error(`oxfords keep: ${e.message}`); process.exit(2); } const { findings, counts } = compare(oldHtml, newHtml, keep); if (args.includes('--json')) console.log(JSON.stringify({ counts, findings }, null, 2)); else { console.log(`original: ${counts.links} links, ${counts.navLabels} nav labels, ${counts.fields} fields, ${counts.numbers} numbers${keep.length ? `, ${keep.length} Keep lines` : ''}`); for (const f of findings) { console.log(` ${f.level.toUpperCase().padEnd(4)} ${f.id.padEnd(18)} ${f.msg} (${f.items.length})`); for (const i of f.items.slice(0, 8)) console.log(` ${i}`); if (f.items.length > 8) console.log(` +${f.items.length - 8} more`); } const fails = findings.filter(f => f.level === 'fail').length; console.log(fails ? `\n${fails} kind${fails > 1 ? 's' : ''} of thing missing` : '\nnothing from the original is missing'); } if (findings.some(f => f.level === 'fail')) process.exitCode = 1; } if (process.argv[1]?.endsWith('keep.mjs')) main();skills/oxfords/scripts/keep.test.mjs2.2 KB5038a631ae56upstream โ
// Run: node keep.test.mjs import assert from 'node:assert'; import { compare, extract } from './keep.mjs'; const original = `<!doctype html><title>Tablewise ยท Today</title> <style>.x{color:red}</style><script>const fake = '<a href="/script-only">x</a>';</script> <nav><a href="/today" aria-current="page">Today</a><a href="/bookings">Bookings</a> <a href="/guests"><svg></svg>Guests</a><button aria-label="Settings"></button></nav> <h1>Good evening, Maya</h1><h2>Covers by hour</h2> <p>142 covers booked, $3,240 in deposits, next table at 18:30, 92% full.</p> <form action="/search"><input name="q"><select name="party"></select></form> <a href="#">dead link</a>`; const kept = `<!doctype html><title>Today ยท Tablewise</title> <nav><a href="/today">Today</a><a href="/bookings">Bookings</a><a href="/guests">Guests</a> <button aria-label="Settings"></button></nav> <h1>Today</h1><h2>Covers by hour</h2> <p>142 covers, $3,240 deposits, next at 18:30, 92% full.</p> <form action="/search"><input name="q"><select name="party"></select></form> <a href="/waitlist">Waitlist</a>`; const e = extract(original); assert.deepEqual(e.navLabels, ['Today', 'Bookings', 'Guests', 'Settings']); assert(!e.links.includes('/script-only'), 'script content is ignored'); assert(!e.links.includes('#'), 'a bare # is not a target'); assert(e.numbers.includes('$3,240') && e.numbers.includes('18:30') && e.numbers.includes('92%')); const ok = compare(original, kept, ['Covers by hour']); assert.equal(ok.findings.filter(f => f.level === 'fail').length, 0, JSON.stringify(ok.findings)); assert(ok.findings.some(f => f.id === 'title-changed')); assert(ok.findings.some(f => f.id === 'link-added' && f.items.includes('/waitlist'))); const broken = kept.replace('href="/guests"', 'href="/people"').replace('>Bookings<', '>Reservations<') .replace('name="party"', 'name="size"').replace('$3,240', '$3.2k'); const ids = new Set(compare(original, broken, ['Covers by hour', 'Deposits held']).findings.map(f => f.id)); for (const id of ['link-missing', 'nav-label-missing', 'field-missing', 'keep-missing', 'number-missing']) assert(ids.has(id), `expected ${id}`); console.log('ok: keep check finds missing links, labels, fields, Keep lines and numbers');skills/oxfords/scripts/lib/colour.mjs7.9 KBbb999fb1d491upstream โ
// Oxfords colour maths. Zero dependencies. One source of truth for every script: // parsing CSS colours, sRGB <-> OKLab/OKLCH, gamut mapping, WCAG contrast, hue families. // Colours are plain objects: rgb = { r, g, b, a } with channels 0..1; oklch = { l, c, h, a }. const clamp01 = x => Math.min(1, Math.max(0, x)); const toLinear = c => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4); const toGamma = c => (c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055); // ---------- parsing ---------- const NAMED = { white: '#ffffff', black: '#000000', transparent: '#00000000' }; function num(s, scale = 1) { s = s.trim(); if (s === 'none') return 0; if (s.endsWith('%')) return (parseFloat(s) / 100) * scale; return parseFloat(s); } function hslToRgb(h, s, l) { h = ((h % 360) + 360) % 360; const k = n => (n + h / 30) % 12; const a = s * Math.min(l, 1 - l); const f = n => l - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1))); return { r: f(0), g: f(8), b: f(4) }; } // parse('#ff8a3d'), parse('rgb(255 138 61 / .5)'), parse('hsl(24 100% 62%)'), parse('oklch(72% 0.17 50)') export function parse(input) { if (typeof input !== 'string') return null; let s = input.trim().toLowerCase(); if (NAMED[s]) s = NAMED[s]; let m = /^#([0-9a-f]{3,8})$/.exec(s); if (m) { let h = m[1]; if (h.length === 3 || h.length === 4) h = [...h].map(c => c + c).join(''); if (h.length !== 6 && h.length !== 8) return null; const v = i => parseInt(h.slice(i, i + 2), 16) / 255; return { r: v(0), g: v(2), b: v(4), a: h.length === 8 ? v(6) : 1 }; } m = /^(rgba?|hsla?|oklch)\(\s*([^)]*)\)$/.exec(s); if (!m) return null; const [body, alphaPart] = m[2].includes('/') ? m[2].split('/') : [m[2], null]; const parts = body.split(/[\s,]+/).filter(Boolean); let alpha = alphaPart != null ? num(alphaPart) : parts.length === 4 ? num(parts.pop()) : 1; if (parts.length !== 3) return null; let rgb; if (m[1].startsWith('rgb')) { rgb = Object.fromEntries(['r', 'g', 'b'].map((k, i) => [k, parts[i].endsWith('%') ? num(parts[i]) : num(parts[i]) / 255])); } else if (m[1].startsWith('hsl')) { rgb = hslToRgb(parseFloat(parts[0]), num(parts[1].endsWith('%') ? parts[1] : parts[1] + '%'), num(parts[2].endsWith('%') ? parts[2] : parts[2] + '%')); } else { const l = parts[0].endsWith('%') ? num(parts[0]) : parseFloat(parts[0]); const c = parts[1].endsWith('%') ? num(parts[1], 0.4) : parseFloat(parts[1]); rgb = fromOklch({ l, c, h: parseFloat(parts[2]) || 0 }); } if ([rgb.r, rgb.g, rgb.b, alpha].some(Number.isNaN)) return null; return { r: clamp01(rgb.r), g: clamp01(rgb.g), b: clamp01(rgb.b), a: clamp01(alpha) }; } // ---------- conversions ---------- export function toOklab({ r, g, b }) { const [R, G, B] = [r, g, b].map(toLinear); const l = Math.cbrt(0.4122214708 * R + 0.5363325363 * G + 0.0514459929 * B); const m = Math.cbrt(0.2119034982 * R + 0.6806995451 * G + 0.1073969566 * B); const s = Math.cbrt(0.0883024619 * R + 0.2817188376 * G + 0.6299787005 * B); return { L: 0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s, A: 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s, B: 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s, }; } // Returns unclamped channels so callers can test the gamut. export function fromOklab({ L, A, B }) { const l = (L + 0.3963377774 * A + 0.2158037573 * B) ** 3; const m = (L - 0.1055613458 * A - 0.0638541728 * B) ** 3; const s = (L - 0.0894841775 * A - 1.2914855480 * B) ** 3; const lin = [ 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s, -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s, -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s, ]; const [r, g, b] = lin.map(v => (v < 0 ? -toGamma(-v) : toGamma(v))); return { r, g, b, a: 1 }; } export function toOklch(rgb) { const { L, A, B } = toOklab(rgb); const c = Math.hypot(A, B); let h = (Math.atan2(B, A) * 180) / Math.PI; if (h < 0) h += 360; return { l: L, c, h: c < 1e-4 ? 0 : h, a: rgb.a ?? 1 }; } export function fromOklch({ l, c, h }) { const rad = (h * Math.PI) / 180; return fromOklab({ L: l, A: c * Math.cos(rad), B: c * Math.sin(rad) }); } export const inGamut = ({ r, g, b }, eps = 1e-4) => [r, g, b].every(v => v >= -eps && v <= 1 + eps); // Keep lightness and hue, lower chroma until the colour fits in sRGB. export function toGamut(lch) { const l = clamp01(lch.l); if (inGamut(fromOklch({ ...lch, l }))) return { ...lch, l }; let lo = 0, hi = lch.c; for (let i = 0; i < 24; i++) { const mid = (lo + hi) / 2; if (inGamut(fromOklch({ l, c: mid, h: lch.h }))) lo = mid; else hi = mid; } return { l, c: lo, h: lch.h, a: lch.a ?? 1 }; } // OKLCH -> in-gamut rgb with clamped channels. export function rgbFromOklch(lch) { const { r, g, b } = fromOklch(toGamut(lch)); return { r: clamp01(r), g: clamp01(g), b: clamp01(b), a: lch.a ?? 1 }; } // ---------- formatting ---------- export function toHex({ r, g, b, a = 1 }) { const h = v => Math.round(clamp01(v) * 255).toString(16).padStart(2, '0'); return `#${h(r)}${h(g)}${h(b)}${a < 1 ? h(a) : ''}`.toUpperCase(); } export function oklchCss(lch) { const { l, c, h, a = 1 } = lch; const L = +(l * 100).toFixed(1), C = +c.toFixed(3), H = +(c < 1e-4 ? 0 : h).toFixed(1); return `oklch(${L}% ${C} ${H}${a < 1 ? ` / ${+a.toFixed(3)}` : ''})`; } // ---------- contrast ---------- export function luminance({ r, g, b }) { const [R, G, B] = [r, g, b].map(toLinear); return 0.2126 * R + 0.7152 * G + 0.0722 * B; } // Paint fg (with its alpha) over an opaque bg. export function blend(fg, bg) { const a = fg.a ?? 1; return { r: fg.r * a + bg.r * (1 - a), g: fg.g * a + bg.g * (1 - a), b: fg.b * a + bg.b * (1 - a), a: 1 }; } // Porter-Duff "over": paint `top` onto `bottom` when both may be translucent. export function over(top, bottom) { const ta = top.a ?? 1, ba = bottom.a ?? 1; const a = ta + ba * (1 - ta); if (a <= 0) return { r: 0, g: 0, b: 0, a: 0 }; const mix = k => (top[k] * ta + bottom[k] * ba * (1 - ta)) / a; return { r: mix('r'), g: mix('g'), b: mix('b'), a }; } // WCAG 2 contrast ratio. Accepts rgb objects or CSS strings. A translucent fg is blended onto bg. export function contrast(fg, bg) { const B = typeof bg === 'string' ? parse(bg) : bg; let F = typeof fg === 'string' ? parse(fg) : fg; if (!F || !B) return NaN; if ((F.a ?? 1) < 1) F = blend(F, B); const [x, y] = [luminance(F), luminance(B)].sort((p, q) => q - p); return (x + 0.05) / (y + 0.05); } // ---------- hue families ---------- // Chroma below this reads as a neutral grey; at or above SATURATED it counts as a real hue. export const NEUTRAL_C = 0.025; export const SATURATED_C = 0.06; // OKLCH hue ranges, in degrees. Pink wraps through 0. Indigo is its own family because // Tailwind's default indigo (#6366F1, h 277) is the most common generated accent. const FAMILIES = [ ['pink', 330, 10], ['red', 10, 36], ['orange', 36, 75], ['yellow', 75, 120], ['green', 120, 175], ['teal', 175, 225], ['blue', 225, 270], ['indigo', 270, 290], ['purple', 290, 330], ]; export function hueFamily(color) { const rgb = typeof color === 'string' ? parse(color) : color; if (!rgb) return null; const { c, h } = toOklch(rgb); if (c < NEUTRAL_C) return 'neutral'; for (const [name, from, to] of FAMILIES) if (from < to ? h >= from && h < to : h >= from || h < to) return name; return 'pink'; } export const isNeutral = color => hueFamily(color) === 'neutral'; // Shortest distance between two hues, 0..180. export const hueDistance = (h1, h2) => { const d = Math.abs(h1 - h2) % 360; return d > 180 ? 360 - d : d; }; // Perceptual difference in OKLab (deltaE OK). About 0.02 is just noticeable; 0.1 is clearly different. export function deltaE(x, y) { const a = toOklab(typeof x === 'string' ? parse(x) : x), b = toOklab(typeof y === 'string' ? parse(y) : y); return Math.hypot(a.L - b.L, a.A - b.A, a.B - b.B); }skills/oxfords/scripts/lib/colour.test.mjs3.2 KB4c1970d6d295upstream โ
// Run: node scripts/lib/colour.test.mjs import assert from 'node:assert'; import { blend, over, parse, toOklch, rgbFromOklch, toHex, contrast, hueFamily, inGamut, fromOklch, toGamut, oklchCss, deltaE } from './colour.mjs'; const near = (a, b, eps, msg) => assert(Math.abs(a - b) <= eps, `${msg}: ${a} vs ${b}`); // Parsing: every syntax lands on the same orange. const forms = ['#ff8a3d', '#FF8A3D', 'rgb(255, 138, 61)', 'rgb(255 138 61)', 'rgba(255,138,61,1)', 'hsl(23.8 100% 62%)', 'hsla(23.8, 100%, 62%, 1)']; for (const f of forms) assert.equal(toHex(parse(f)), '#FF8A3D', f); assert.equal(parse('#fff').r, 1); assert.equal(parse('#0000').a, 0); near(parse('rgb(0 0 0 / 50%)').a, 0.5, 1e-9, 'slash alpha'); assert.equal(parse('white').g, 1); assert.equal(parse('nonsense'), null); assert.equal(parse('rgb(1,2)'), null); // OKLCH reference values (Ottosson): sRGB red = oklch(0.628 0.2577 29.23). const red = toOklch(parse('#ff0000')); near(red.l, 0.6280, 0.001, 'red L'); near(red.c, 0.2577, 0.001, 'red C'); near(red.h, 29.23, 0.1, 'red H'); near(toOklch(parse('#ffffff')).l, 1, 1e-4, 'white L'); near(toOklch(parse('#000000')).l, 0, 1e-4, 'black L'); assert.equal(toOklch(parse('#808080')).c < 1e-4, true, 'grey has no chroma'); // Round trip through OKLCH for a spread of colours. for (const hex of ['#FF8A3D', '#326E6E', '#001B8C', '#FEEEC3', '#111111', '#7EA288']) { assert.equal(toHex(rgbFromOklch(toOklch(parse(hex)))), hex, `round trip ${hex}`); assert.equal(toHex(parse(oklchCss(toOklch(parse(hex))))), hex, `css round trip ${hex}`); } // Gamut mapping keeps L and H and lowers C. const wild = { l: 0.7, c: 0.4, h: 145 }; assert.equal(inGamut(fromOklch(wild)), false); const mapped = toGamut(wild); assert.equal(inGamut(fromOklch(mapped)), true); near(mapped.l, 0.7, 1e-9, 'gamut keeps L'); assert(mapped.c < 0.4 && mapped.c > 0.1, 'gamut lowers C'); // WCAG contrast reference values. near(contrast('#000', '#fff'), 21, 1e-9, 'black on white'); near(contrast('#777777', '#ffffff'), 4.48, 0.01, '#777 on white'); near(contrast('#767676', '#ffffff'), 4.54, 0.01, '#767676 on white'); near(contrast('rgba(0,0,0,0.5)', '#ffffff'), contrast('#808080', '#ffffff'), 0.05, 'alpha is blended'); // Hue families. const fam = { '#E14543': 'red', '#FF8A3D': 'orange', '#F7EB49': 'yellow', '#28B467': 'green', '#028397': 'teal', '#224D95': 'blue', '#7778DE': 'indigo', '#6366F1': 'indigo', '#7C3AED': 'purple', '#C2410C': 'orange', '#8B2E47': 'pink', '#D93D7F': 'pink', '#6B6B6B': 'neutral', '#FAFAFA': 'neutral', '#9333EA': 'purple' }; for (const [hex, f] of Object.entries(fam)) assert.equal(hueFamily(hex), f, `${hex} family`); // over(): translucent on translucent, then onto white, equals blending the stack directly. const half = { r: 0, g: 0, b: 0, a: 0.5 }, quarterRed = { r: 1, g: 0, b: 0, a: 0.25 }; const stacked = blend(over(half, quarterRed), parse('#fff')); const direct = blend(half, blend(quarterRed, parse('#fff'))); for (const k of ['r', 'g', 'b']) near(stacked[k], direct[k], 1e-9, `over ${k}`); assert.equal(over({ r: 0, g: 0, b: 0, a: 0 }, { r: 0, g: 0, b: 0, a: 0 }).a, 0, 'clear over clear'); near(deltaE('#ffffff', '#ffffff'), 0, 1e-9, 'deltaE same'); assert(deltaE('#ff0000', '#00ff00') > 0.3, 'deltaE far'); console.log('ok: colour maths');skills/oxfords/scripts/lib/inpage.mjs25 KB9f163519cc9eupstream โ
// Oxfords render check, the half that runs inside the page. Zero dependencies. // Playwright serialises install() with toString(), so nothing in here may reach module scope. // It collects raw facts only: colours as sRGB bytes, boxes in page pixels, names as strings. // Every threshold and every verdict lives in judge.mjs, on the Node side. // // await page.evaluate(install); await page.evaluate(() => window.__oxf.collect()); export function install() { if (window.__oxf) return; const NOT_TEXT = 'script,style,noscript,template,title,head,select,option,optgroup,textarea,svg,math'; const TARGET = 'a[href],button,input:not([type="hidden"]),select,textarea,[role="button"],summary,[tabindex]'; const NATIVE = 'a[href],button,input,select,textarea,summary,[role="button"]'; // Things that activate. Target size (WCAG 2.5.8) is about these, not about a truncated cell // made focusable so its full value can show: that stays in the focus walk only. const ACTIVATES = 'a[href],button,input:not([type="hidden"]),select,textarea,summary,[onclick],' + ['button', 'link', 'checkbox', 'radio', 'switch', 'tab', 'menuitem', 'option'].map(r => `[role="${r}"]`).join(','); const FOCUSABLE = TARGET + ',[contenteditable=""],[contenteditable="true"],iframe'; // Hidden on purpose until opened: closed dialogs, menus, popovers, tooltips, [hidden]. const OVERLAY = 'dialog:not([open]),[popover],[role="menu"],[role="listbox"],[role="tooltip"],' + '[role="dialog"],[role="alertdialog"],[hidden],[aria-hidden="true"],[inert]'; const r1 = v => Math.round(v * 10) / 10; const range = document.createRange(); // ---------- colour: any computed colour -> [r, g, b, a] on a 0-255 scale ---------- // Computed styles come back as rgb(), oklch(), lab(), color(srgb ...). Legacy rgb() is read // exactly; everything else is painted on a 1x1 sRGB canvas and read back. const cv = document.createElement('canvas'); cv.width = cv.height = 1; const cx = cv.getContext('2d', { willReadFrequently: true }); const memo = new Map(); function bytes(css) { if (!css || css === 'transparent') return [0, 0, 0, 0]; let v = memo.get(css); if (v) return v; const m = /^rgba?\(([\d.]+),\s*([\d.]+),\s*([\d.]+)(?:,\s*([\d.]+))?\)$/.exec(css); if (m) v = [+m[1], +m[2], +m[3], m[4] == null ? 255 : +m[4] * 255]; else { cx.clearRect(0, 0, 1, 1); cx.fillStyle = '#000'; cx.fillStyle = css; cx.fillRect(0, 0, 1, 1); v = [...cx.getImageData(0, 0, 1, 1).data]; } memo.set(css, v); return v; } // The colour the browser paints under everything: Canvas, for the root's color-scheme. function canvasColour() { const d = document.createElement('div'); d.style.cssText = 'position:absolute;width:0;height:0;background-color:Canvas'; document.documentElement.appendChild(d); const v = bytes(getComputedStyle(d).backgroundColor); d.remove(); return v; } // ---------- element tables ---------- const css = new Map(); const st = el => { let s = css.get(el); if (!s) css.set(el, s = getComputedStyle(el)); return s; }; // nodes[i] = { bg, op, img, p }: background bytes, opacity, has a background-image, parent index. // Node walks p up to -1 to composite a colour through every ancestor. const ids = new Map(), nodes = []; function node(el) { if (!el || el.nodeType !== 1) return -1; let i = ids.get(el); if (i !== undefined) return i; const p = node(el.parentElement), s = st(el); i = nodes.length; ids.set(el, i); nodes.push({ bg: bytes(s.backgroundColor), op: +s.opacity, img: s.backgroundImage !== 'none' ? 1 : 0, p }); return i; } // Short CSS path: up to four levels, stopping at an id. function path(el) { const parts = []; for (let n = el; n && n.nodeType === 1 && parts.length < 4; n = n.parentElement) { if (n === document.body || n === document.documentElement) break; let s = n.localName; if (n.id && /^[a-z][\w-]*$/i.test(n.id)) { parts.unshift(`${s}#${n.id}`); break; } const c = [...n.classList].find(k => /^[a-z][\w-]{0,24}$/i.test(k) && !/\d{3,}/.test(k)); if (c) s += '.' + c; parts.unshift(s); } return parts.join(' > ') || el.localName; } // Visually hidden for screen readers: clip, clip-path inset(50%), or a 1px clipped box. function srOnly(el) { for (let n = el, k = 0; n && k < 3; n = n.parentElement, k++) { const s = st(n); if (/inset\(\s*(50|100)%/.test(s.clipPath)) return true; if (s.position !== 'absolute' && s.position !== 'fixed') continue; if (s.clip && s.clip !== 'auto') return true; const r = n.getBoundingClientRect(); if ((r.width <= 1 || r.height <= 1) && s.overflow !== 'visible') return true; } return false; } // The outermost element that makes el invisible, or null. function hiderOf(el) { let h = null; for (let n = el; n && n !== document.documentElement; n = n.parentElement) if (+st(n).opacity < 0.01) h = n; if (h) return { el: h, why: 'opacity 0' }; if (st(el).visibility === 'visible') return null; let n = el; while (n.parentElement && st(n.parentElement).visibility !== 'visible') n = n.parentElement; return { el: n, why: 'visibility hidden' }; } // Nearest ancestor-or-self that clips text on each axis (overflow hidden or clip). A scroll // container on the way stops the search: text inside it can still be reached. function clipOf(el) { const out = {}; for (let n = el; n && (out.x === undefined || out.y === undefined); n = n.parentElement) { const s = st(n), root = n === document.documentElement || n === document.body; for (const [ax, o] of [['x', s.overflowX], ['y', s.overflowY]]) { if (out[ax] !== undefined || o === 'visible') continue; if (o !== 'hidden' && o !== 'clip') { out[ax] = null; continue; } let b; if (root) b = [0, 0, innerWidth, innerHeight]; else { const r = n.getBoundingClientRect(), L = r.left + n.clientLeft + scrollX, T = r.top + n.clientTop + scrollY; b = [L, T, L + n.clientWidth, T + n.clientHeight].map(r1); } const clamp = s.webkitLineClamp && s.webkitLineClamp !== 'none'; out[ax] = { b, e: s.textOverflow === 'ellipsis' ? 1 : 0, c: clamp ? 1 : 0, path: n === el ? '' : path(n) }; } } return [out.x || null, out.y || null]; } // ---------- accessible names (a plain subset of accname) ---------- function subtreeText(el) { let s = ''; for (const n of el.childNodes) { if (n.nodeType === 3) { s += n.data; continue; } if (n.nodeType !== 1 || n.getAttribute('aria-hidden') === 'true' || st(n).display === 'none') continue; if (n.localName === 'img') s += ' ' + (n.getAttribute('alt') || ''); else if (n.localName === 'svg') s += ' ' + (n.getAttribute('aria-label') || n.querySelector('title')?.textContent || ''); else s += ' ' + (n.getAttribute('aria-label') || subtreeText(n)); } return s.replace(/\s+/g, ' ').trim(); } function nameOf(el) { const by = el.getAttribute('aria-labelledby'); if (by) { const t = by.split(/\s+/).map(i => document.getElementById(i)?.textContent || '').join(' ').trim(); if (t) return [t, 'labelledby']; } const al = el.getAttribute('aria-label')?.trim(); if (al) return [al, 'aria-label']; const tag = el.localName, type = (el.getAttribute('type') || '').toLowerCase(); if (tag === 'input' && /^(submit|reset)$/.test(type)) return [el.value || type, 'value']; if (tag === 'input' && type === 'button' && el.value) return [el.value, 'value']; if (tag === 'input' && type === 'image' && el.alt) return [el.alt, 'alt']; if (/^(input|select|textarea)$/.test(tag)) { const l = [...(el.labels || [])].map(x => x.textContent).join(' ').replace(/\s+/g, ' ').trim(); if (l) return [l, 'label']; } else { const t = subtreeText(el); if (t) return [t, 'text']; } const ti = el.getAttribute('title')?.trim(); if (ti) return [ti, 'title']; const ph = el.getAttribute('placeholder')?.trim(); if (ph && /^(input|textarea)$/.test(tag)) return [ph, 'placeholder']; return ['', '']; } // A link inside running text: inline, and its block holds at least two words that are not // themselves links or buttons. Those are exempt from target size (WCAG 2.5.8 inline case). const running = new Map(); function inRunningText(a) { if (a.localName !== 'a' || st(a).display !== 'inline') return false; let b = a.parentElement; while (b && st(b).display.startsWith('inline')) b = b.parentElement; if (!b) return false; if (running.has(b)) return running.get(b); let other = ''; const w = document.createTreeWalker(b, NodeFilter.SHOW_TEXT); while (w.nextNode() && other.length < 300) { const c = w.currentNode.parentElement.closest(TARGET); if (!c || !b.contains(c)) other += ' ' + w.currentNode.data; } const yes = /\p{L}{2,}\P{L}+\p{L}{2,}/u.test(other); running.set(b, yes); return yes; } // The layer text moves with: its nearest fixed ancestor or real scroll container, else the page. // Text in one layer can scroll out from under text in another, so the judge treats those apart. function layerOf(el) { for (let n = el; n && n !== document.body && n !== document.documentElement; n = n.parentElement) { const s = st(n); if (s.position === 'fixed') return node(n); if ((/auto|scroll/.test(s.overflowY) && n.scrollHeight > n.clientHeight + 1) || (/auto|scroll/.test(s.overflowX) && n.scrollWidth > n.clientWidth + 1)) return node(n); } return -1; } const opacityOf = el => { let o = 1; for (let n = el; n; n = n.parentElement) o *= +st(n).opacity; return o; }; // Rendered at all: not display none, not inside a content-visibility: hidden subtree such as a // closed <details>, whose content Chrome still lays out and so still has boxes. const shown = el => { while (el && st(el).display === 'contents') el = el.parentElement; return !el || !el.checkVisibility || el.checkVisibility(); }; const box = (r, X, Y) => [r.left + X, r.top + Y, r.right + X, r.bottom + Y].map(r1); // An open modal: a <dialog> shown with showModal(), or a visible [aria-modal="true"]. While one // is open, everything outside it is inert behind a scrim, so only the modal is measured. function activeModal() { try { const d = document.querySelector('dialog:modal'); if (d) return d; } catch { /* no :modal */ } for (const el of document.querySelectorAll('[aria-modal="true"]')) if (el.getClientRects().length && shown(el) && st(el).visibility === 'visible' && opacityOf(el) >= 0.01) return el; return null; } // ---------- collect: one pass over the settled page, scrolled to the top ---------- function collect() { css.clear(); ids.clear(); nodes.length = 0; running.clear(); const X = scrollX, Y = scrollY, out = { iw: innerWidth, ih: innerHeight, canvas: canvasColour() }; const modal = activeModal(), inScope = el => !modal || modal.contains(el); out.modal = modal ? path(modal) : ''; // Media that text might sit on. Overlap means the background must be read from pixels. const media = [...document.querySelectorAll('img,video,canvas,svg,iframe,object,embed')] .filter(m => !m.parentElement?.closest('svg')) .map(m => [m, box(m.getBoundingClientRect(), X, Y)]) .filter(([, b]) => b[2] - b[0] > 1 && b[3] - b[1] > 1).slice(0, 400); const hits = (q, b) => Math.min(q[0] + q[2], b[2]) - Math.max(q[0], b[0]) > 1 && Math.min(q[1] + q[3], b[3]) - Math.max(q[1], b[1]) > 1; const overMedia = (el, rects) => media.some(([m, b]) => !el.contains(m) && !m.contains(el) && rects.some(q => hits(q, b))); // Regions an aria-expanded="false" control says are closed. const closed = []; for (const c of document.querySelectorAll('[aria-expanded="false"][aria-controls]')) for (const i of c.getAttribute('aria-controls').split(/\s+/)) { const t = document.getElementById(i); if (t) closed.push(t); } const onPurpose = h => h.closest(OVERLAY) || closed.some(c => c.contains(h)) || [h, h.parentElement, h.parentElement?.parentElement].some(n => n && /^(absolute|fixed)$/.test(st(n).position)); // Text-bearing elements: any element with a direct, non-blank text node. const owners = new Map(); const tw = document.createTreeWalker(modal || document.body || document.documentElement, NodeFilter.SHOW_TEXT); while (tw.nextNode() && owners.size < 4000) { const t = tw.currentNode, el = t.parentElement; if (!/\S/.test(t.data) || !el || el.closest(NOT_TEXT)) continue; if (!owners.has(el) && !shown(el)) continue; (owners.get(el) || owners.set(el, []).get(el)).push(t); } out.text = []; const hidden = new Map(); for (const [el, tn] of owners) { const rects = []; for (const t of tn) { range.selectNodeContents(t); for (const q of range.getClientRects()) if (q.width >= 1 && q.height >= 1 && rects.length < 40) rects.push([q.left + X, q.top + Y, q.width, q.height].map(r1)); } if (!rects.length) continue; const words = tn.map(t => t.data).join(' ').replace(/\s+/g, ' ').trim(); const h = hiderOf(el); if (h) { if (!onPurpose(h.el)) { const g = hidden.get(h.el) || hidden.set(h.el, { path: path(h.el), why: h.why, text: words.slice(0, 50), n: 0 }).get(h.el); g.n++; } continue; } const s = st(el), [clipX, clipY] = clipOf(el); out.text.push({ id: node(el), path: path(el), text: words.slice(0, 50), rects, fg: bytes(s.webkitTextFillColor || s.color), size: parseFloat(s.fontSize), weight: parseInt(s.fontWeight, 10) || 400, sr: srOnly(el) ? 1 : 0, dis: el.closest('[disabled],[aria-disabled="true"]') ? 1 : 0, clipText: /text/.test(s.backgroundClip + s.webkitBackgroundClip) ? 1 : 0, over: overMedia(el, rects) ? 1 : 0, ell: s.textOverflow === 'ellipsis' ? 1 : 0, clipX, clipY, layer: layerOf(el), }); } out.hidden = [...hidden.values()].slice(0, 30); // Form fields: their typed value is text too, and their border is the non-text contrast case. out.fields = []; for (const el of document.querySelectorAll('input,select,textarea')) { const type = (el.type || '').toLowerCase(), r = el.getBoundingClientRect(), s = st(el); if (!inScope(el) || type === 'hidden' || r.width < 1 || r.height < 1 || s.visibility !== 'visible' || opacityOf(el) < 0.01 || !shown(el)) continue; const value = el.localName === 'select' ? el.selectedOptions?.[0]?.textContent?.trim() || '' : el.value || ''; if (value && !/^(checkbox|radio|range|color|file|image)$/.test(type) && !el.disabled) out.text.push({ id: node(el), path: path(el), text: value.slice(0, 50), ctl: 1, rects: [[r.left + X, r.top + Y, r.width, r.height].map(r1)], fg: bytes(s.color), size: parseFloat(s.fontSize), weight: parseInt(s.fontWeight, 10) || 400, sr: 0, dis: 0, clipText: 0, over: 0, }); if (/^(checkbox|radio|range|color|file|submit|reset|button|image)$/.test(type)) continue; // Disabled fields are exempt from WCAG 1.4.11, as their text is from 1.4.3. if (el.disabled || el.closest('[aria-disabled="true"],fieldset:disabled')) continue; // The visible edge may belong to a wrapper that hugs the field (an icon search box, a // :focus-within frame): within 16px above and below, within 48px at the sides. const sides = n => ['Top', 'Right', 'Bottom', 'Left'].map(k => [parseFloat(st(n)[`border${k}Width`]) || 0, bytes(st(n)[`border${k}Color`])]); const wraps = []; for (let n = el.parentElement, k = 0; n && n !== document.body && k < 2; n = n.parentElement, k++) { const q = n.getBoundingClientRect(); if (r.top - q.top > 16 || q.bottom - r.bottom > 16 || r.left - q.left > 48 || q.right - r.right > 48) break; wraps.push({ id: node(n), sides: sides(n) }); } out.fields.push({ id: node(el), path: path(el), sides: sides(el), wraps }); } // Accessible names for everything focusable or interactive; sizes only for what activates. out.targets = []; out.names = []; const index = new Map(); const clickable = [...(document.body || document.documentElement).getElementsByTagName('*')].slice(0, 8000) .filter(el => typeof el.onclick === 'function' && !el.matches(TARGET)); // onclick set from script for (const el of [...document.querySelectorAll(TARGET), ...clickable]) { if (index.size >= 800) break; const byScript = !el.matches(TARGET); if (!inScope(el) || (!byScript && !el.matches(NATIVE) && el.tabIndex < 0)) continue; if (!el.getClientRects().length || !shown(el) || el.closest('[aria-hidden="true"],[inert]')) continue; const [name, via] = nameOf(el); const kind = el.localName === 'a' ? 'link' : el.getAttribute('role') || el.localName; if (!byScript) out.names.push({ path: path(el), kind, name: name.slice(0, 40), via }); const s = st(el); if (!byScript && !el.matches(ACTIVATES) && typeof el.onclick !== 'function') continue; if (el.matches(':disabled') || el.closest('[aria-disabled="true"]') || s.visibility !== 'visible' || opacityOf(el) < 0.01 || srOnly(el)) continue; let b = box(el.getBoundingClientRect(), X, Y); if (/^(checkbox|radio)$/.test(el.type)) // a label is part of the click area for (const l of el.labels || []) { const q = box(l.getBoundingClientRect(), X, Y); b = [Math.min(b[0], q[0]), Math.min(b[1], q[1]), Math.max(b[2], q[2]), Math.max(b[3], q[3])]; } if (b[2] - b[0] < 1 || b[3] - b[1] < 1) continue; // Parked off-screen at load (a skip link) is not a target until focus brings it in; the // focus walk checks that it does. if (b[3] <= 0 || b[2] <= 0 || b[0] >= innerWidth) continue; index.set(el, out.targets.length); out.targets.push({ path: path(el), kind, name: name.slice(0, 40), box: b, inline: inRunningText(el) ? 1 : 0, up: -1 }); } for (const [el, i] of index) { const a = el.parentElement?.closest(TARGET); if (index.has(a)) out.targets[i].up = index.get(a); } // Sideways scroll: who sticks out past the right edge, outside any scroll container. const de = document.documentElement, iw = innerWidth; out.wide = { sw: de.scrollWidth, rootClips: [de, document.body].some(n => n && /hidden|clip/.test(st(n).overflowX)) ? 1 : 0, offenders: [] }; const inScroller = el => { for (let n = el.parentElement; n && n !== document.body && n !== de; n = n.parentElement) if (st(n).overflowX !== 'visible') return true; return false; }; if (out.wide.sw > iw || out.wide.rootClips) { const all = (document.body || de).getElementsByTagName('*'); for (let i = 0; i < all.length && i < 8000; i++) { const el = all[i], r = el.getBoundingClientRect(); if (r.right + X <= iw + 1 || r.width < 1 || st(el).position === 'fixed' || inScroller(el)) continue; const p = el.parentElement, pr = p && p.getBoundingClientRect(); if (p && p !== document.body && pr.right + X > iw + 1 && r.right <= pr.right + 1) continue; // blame the parent out.wide.offenders.push({ path: path(el), right: r1(r.right + X), w: r1(r.width) }); } out.wide.offenders.sort((a, b) => b.right - a.right || b.w - a.w).splice(5); } out.nodes = nodes; return out; } // ---------- page look, for "is there a dark theme" ---------- function theme() { const b = document.body || document.documentElement; return { canvas: canvasColour(), html: bytes(getComputedStyle(document.documentElement).backgroundColor), body: bytes(getComputedStyle(b).backgroundColor), text: bytes(getComputedStyle(b).color) }; } // ---------- settle: fonts loaded, animations at their end, scroll-reveal given its chance ---------- async function settle() { const wait = ms => new Promise(r => setTimeout(r, ms)); const frame = () => Promise.race([new Promise(r => requestAnimationFrame(() => r())), wait(50)]); const finish = () => { for (const a of document.getAnimations?.() || []) try { a.finish(); } catch { /* infinite */ } }; await Promise.race([document.fonts.ready, wait(5000)]); finish(); const se = document.scrollingElement || document.documentElement; for (let y = 0, i = 0; i < 80 && y < se.scrollHeight; i++, y += innerHeight * 0.8) { scrollTo(0, y); await frame(); await frame(); } scrollTo(0, se.scrollHeight); await frame(); await frame(); scrollTo(0, 0); await wait(500); await frame(); finish(); await Promise.race([document.fonts.ready, wait(5000)]); } // ---------- focus: snapshot every focusable unfocused, then read each one as Tab lands ---------- // The look of a control can change on itself, its parent or grandparent (:focus-within), its // next sibling (input + span), or its label. All of those are watched. const watchOf = el => [...new Set([el, el.parentElement, el.parentElement?.parentElement, el.nextElementSibling, ...(el.labels || [])])].filter(n => n && n !== document.body && n !== document.documentElement); function shadows(v) { if (!v || v === 'none') return []; return v.split(/,(?![^(]*\))/).map(p => { const m = /(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\([^)]*\)|#[0-9a-f]{3,8}\b/i.exec(p); return { c: m ? bytes(m[0]) : [0, 0, 0, 255], n: (p.replace(m ? m[0] : '', '').match(/-?[\d.]+px/g) || []).map(parseFloat), inset: /\binset\b/.test(p) ? 1 : 0 }; }); } function look(n) { const s = getComputedStyle(n); const pseudo = p => { const q = getComputedStyle(n, p); return q.content === 'none' ? '' : [q.content, q.backgroundColor, q.boxShadow, q.borderColor, q.outlineStyle, q.outlineColor, q.opacity, q.transform, q.width, q.height, q.color].join('|'); }; return { ol: [s.outlineStyle, parseFloat(s.outlineWidth) || 0, bytes(s.outlineColor), parseFloat(s.outlineOffset) || 0], sh: s.boxShadow, rings: shadows(s.boxShadow), bg: bytes(s.backgroundColor), bi: s.backgroundImage, fg: bytes(s.color), bc: ['Top', 'Right', 'Bottom', 'Left'].map(k => bytes(s[`border${k}Color`])), bw: ['Top', 'Right', 'Bottom', 'Left'].map(k => parseFloat(s[`border${k}Width`]) || 0), td: s.textDecorationLine, tdc: bytes(s.textDecorationColor), op: +s.opacity, tf: s.transform, svg: n instanceof SVGElement ? [s.fill, s.stroke, s.strokeWidth].join('|') : '', // SVG shows focus with paint at: n instanceof HTMLElement ? [n.offsetLeft, n.offsetTop, n.offsetWidth, n.offsetHeight] : [], ps: pseudo('::before') + '/' + pseudo('::after'), }; } let before = new Map(), seen = new Set(), trap = null; // With a modal open, the walk starts inside it: focus the modal itself, then blur it, which // leaves the place Tab starts from at the top of the modal with nothing focused. function focusSetup() { document.activeElement?.blur?.(); scrollTo(0, 0); before = new Map(); seen = new Set(); trap = activeModal(); if (trap) { if (!trap.hasAttribute('tabindex')) trap.setAttribute('tabindex', '-1'); trap.focus({ preventScroll: true }); trap.blur(); } for (const el of document.querySelectorAll(FOCUSABLE)) { if (before.size >= 1000) break; const w = watchOf(el); before.set(el, { w, looks: w.map(look) }); } return { modal: trap ? path(trap) : '' }; } function focusProbe() { let a = document.activeElement; while (a && a.shadowRoot && a.shadowRoot.activeElement) a = a.shadowRoot.activeElement; if (!a || a === document.body || a === document.documentElement) return { end: 1 }; if (trap && !trap.contains(a)) return { escaped: 1, path: path(a), name: nameOf(a)[0].slice(0, 40), modal: path(trap) }; if (seen.has(a)) return { end: 1 }; seen.add(a); last = a; const b = before.get(a), w = b ? b.w : watchOf(a), r = a.getBoundingClientRect(); // [background, opacity] from an element up to the root, read fresh (focus may change them). const chain = el => { const c = []; for (let n = el; n; n = n.parentElement) { const s = getComputedStyle(n); c.push([bytes(s.backgroundColor), +s.opacity]); } return c; }; return { path: path(a), name: nameOf(a)[0].slice(0, 40), before: b ? b.looks : null, now: w.map(look), own: w.map(chain), outside: w.map(n => chain(n.parentElement)), box: [r.left, r.top, r.right, r.bottom].map(r1), vw: innerWidth, vh: innerHeight }; // box in the viewport } // For the pixel check: take focus off the last element, then give it back so the next Tab // carries on from the same place. let last = null; const focusBlur = () => { last?.blur(); }; const focusRestore = () => { last?.focus({ preventScroll: true }); }; window.__oxf = { collect, theme, settle, focusSetup, focusProbe, focusBlur, focusRestore }; }skills/oxfords/scripts/lib/judge.mjs17 KB45d7fe323813upstream โ
// Oxfords render check: verdicts. Takes the raw facts lib/inpage.mjs collected, plus the decoded // screenshots, and turns them into findings. Every threshold lives in T below, and every colour // sum goes through lib/colour.mjs, so the source checker and the render check agree on colour. import { contrast, blend, over, toOklch, hueFamily, luminance, deltaE, NEUTRAL_C, SATURATED_C } from './colour.mjs'; export const T = { text: 4.5, large: 3, // WCAG 1.4.3; large = 24px, or 18.66px at weight 600 and up nonText: 3, ring: 3, // WCAG 1.4.11: field edges and focus rings target: 24, touch: 44, // WCAG 2.5.8 floor everywhere; 44 is the touch size on phones touchWidth: 480, // widths at or under this are phones overlap: 2, clip: 1, // px of intersection or cut-off before it counts hueShare: 0.005, hues: 4, // a hue family over 0.5% of the page counts; more than 4 warns noticeable: 0.02, // deltaE OK below which a focus colour change is invisible focusPixels: 16, // pixels that must change by `noticeable` when no style changed: a // 1px line 16px long is the smallest indicator anyone sees, and two // renders of the same state differ by none }; const CLEAR = { r: 0, g: 0, b: 0, a: 0 }; const col = b => ({ r: b[0] / 255, g: b[1] / 255, b: b[2] / 255, a: b[3] / 255 }); // What you see when `top` is painted inside an element: composite it through the element's own // background and opacity, then each ancestor's, then onto the page canvas. // chain = [[backgroundBytes, opacity], ...], innermost first. function through(top, chain, canvas) { let c = top; for (const [bg, op] of chain) { c = over(c, col(bg)); c.a *= op; } return blend(c, canvas); } const chainOf = (i, nodes) => { const c = []; for (; i >= 0; i = nodes[i].p) c.push([nodes[i].bg, nodes[i].op]); return c; }; // A background-image (gradient or url) shows under the text before any opaque colour hides it. const paintsImage = (i, nodes) => { for (; i >= 0; i = nodes[i].p) { if (nodes[i].img) return true; if (nodes[i].bg[3] >= 254.5) return false; } return false; }; export const needsPixels = data => data.text.some(t => !t.sr && (t.over || paintsImage(t.id, data.nodes))); // "4.47" rather than "4.5" when rounding would hide a fail. const fmt = (r, need) => { const s = r.toFixed(1); return String(+s >= need ? Math.floor(r * 100) / 100 : +s); }; const pct = s => { const v = s * 100; return (v < 0.05 ? '<0.1' : v < 0.95 ? v.toFixed(1) : Math.round(v)) + '%'; }; // Darkest and lightest few percent of the pixels under the text boxes, from a render with the // text made transparent. The worse of the two is the honest contrast on an image or gradient. function sample(png, rects) { const area = rects.reduce((s, q) => s + q[2] * q[3], 0); const step = Math.max(1, Math.round(Math.sqrt(area / 20000))); const px = []; for (const [x, y, w, h] of rects) { const x0 = Math.max(0, Math.floor(x)), x1 = Math.min(png.width, Math.ceil(x + w)); const y0 = Math.max(0, Math.floor(y)), y1 = Math.min(png.height, Math.ceil(y + h)); for (let j = y0; j < y1; j += step) for (let i = x0; i < x1; i += step) { const k = (j * png.width + i) * 4, c = { r: png.data[k] / 255, g: png.data[k + 1] / 255, b: png.data[k + 2] / 255, a: 1 }; px.push([luminance(c), c]); } } if (!px.length) return null; px.sort((p, q) => p[0] - q[0]); const at = f => px[Math.min(px.length - 1, Math.floor(f * px.length))][1]; return { dark: at(0.05), light: at(0.95) }; } // The middle 0.8em of a text line box, so the ascender and descender room in a line box never // counts as overlap or clipping. Returns [left, top, right, bottom]. const core = (q, size) => { const mid = q[1] + q[3] / 2, half = Math.min(q[3], size * 0.8) / 2; return [q[0], mid - half, q[0] + q[2], mid + half]; }; // Is the text cut off by an overflow: hidden box, or scrolled out of it entirely (a closed // accordion, a carousel slide), which is hiding rather than clipping? function clipState(t) { const cores = t.rects.map(q => core(q, t.size)); let gone = false, cut = null; for (const [ax, c] of [['x', t.clipX], ['y', t.clipY]]) { if (!c) continue; const [lo, hi] = ax === 'x' ? [0, 2] : [1, 3]; if (!cores.some(q => q[hi] > c.b[lo] + T.clip && q[lo] < c.b[hi] - T.clip)) { gone = true; continue; } if (c.e || c.c || t.ell) continue; // ellipsis and line-clamp are truncation on purpose const before = Math.max(...cores.map(q => c.b[lo] - q[lo])), after = Math.max(...cores.map(q => q[hi] - c.b[hi])); const px = Math.max(before, after), side = ax === 'x' ? (after >= before ? 'right' : 'left') : (after >= before ? 'bottom' : 'top'); if (px > T.clip && !cut) cut = { side, px, by: c.path }; } return { gone, cut }; } // ---------- colour share ---------- export function colourShare(png) { const counts = new Map(), d = png.data; for (let i = 0; i < d.length; i += 4) { const k = (d[i] << 16) | (d[i + 1] << 8) | d[i + 2]; counts.set(k, (counts.get(k) || 0) + 1); } const total = d.length / 4, fam = {}, sat = {}; let neutral = 0; for (const [k, n] of counts) { const rgb = { r: (k >> 16) / 255, g: ((k >> 8) & 255) / 255, b: (k & 255) / 255, a: 1 }; const { c } = toOklch(rgb); if (c < NEUTRAL_C) { neutral += n; continue; } const f = hueFamily(rgb); fam[f] = (fam[f] || 0) + n; if (c >= SATURATED_C) sat[f] = (sat[f] || 0) + n; } const share = o => Object.entries(o).map(([f, n]) => [f, n / total]).sort((a, b) => b[1] - a[1]); return { neutral: neutral / total, top: share(fam).slice(0, 4), saturated: share(sat).filter(([, s]) => s > T.hueShare).map(([f]) => f) }; } // ---------- focus ---------- const differs = (p, q) => (p[3] > 2 || q[3] > 2) && (Math.abs(p[3] - q[3]) > 25 || deltaE(col(p), col(q)) >= T.noticeable); const moved = (x, y, tol) => x.length !== y.length || x.some((v, i) => Math.abs(v - y[i]) > tol); const outlineOn = x => x.ol[0] !== 'none' && x.ol[1] > 0 && (x.ol[0] === 'auto' || x.ol[2][3] > 25); const outlineChanged = (b, n) => outlineOn(b) !== outlineOn(n) || (outlineOn(n) && (b.ol[0] !== n.ol[0] || Math.abs(b.ol[1] - n.ol[1]) > 0.5 || Math.abs(b.ol[3] - n.ol[3]) > 0.5 || differs(b.ol[2], n.ol[2]))); const shadowSig = x => x.rings.filter(r => r.c[3] > 25).map(r => `${r.c.map(Math.round)} ${r.n} ${r.inset}`).join(';'); function looksDifferent(b, n) { return outlineChanged(b, n) || shadowSig(b) !== shadowSig(n) || differs(b.bg, n.bg) || differs(b.fg, n.fg) || b.bi !== n.bi || moved(b.bw, n.bw, 0.5) || b.bc.some((c, i) => (b.bw[i] > 0 || n.bw[i] > 0) && differs(c, n.bc[i])) || b.td !== n.td || (n.td !== 'none' && differs(b.tdc, n.tdc)) || Math.abs(b.op - n.op) > 0.05 || b.tf !== n.tf || moved(b.at, n.at, 1) || b.ps !== n.ps || b.svg !== n.svg; } // Contrast of each outline or ring that focus drew, against what sits behind it. An outline // with style auto is the browser's own two-tone ring, which is visible on anything. function ringRatios(b, n, own, outside, canvas) { const out = [], bgOut = through(CLEAR, outside, canvas), bgIn = through(CLEAR, own, canvas); if (outlineOn(n) && outlineChanged(b, n)) out.push(n.ol[0] === 'auto' ? Infinity : contrast(col(n.ol[2]), n.ol[3] < 0 ? bgIn : bgOut)); if (shadowSig(b) !== shadowSig(n)) for (const r of n.rings) { const [x = 0, y = 0, , spread = 0] = r.n; if (r.c[3] > 25 && Math.abs(x) <= 1 && Math.abs(y) <= 1 && spread >= 1) out.push(contrast(col(r.c), r.inset ? bgIn : bgOut)); } return out; } // Did any watched element's computed look change? The cheap test, run during the Tab walk. export const focusChanged = f => !!f.before && f.now.some((n, i) => looksDifferent(f.before[i], n)); // A focused element that is still outside the viewport, like a skip link that never moves in. export const offScreen = ({ box: [l, t, r, b], vw, vh }) => r - l >= 1 && b - t >= 1 && (r <= 0 || b <= 0 || l >= vw || t >= vh); // Pixels that differ noticeably between two same-size clips (focused and blurred). export function pixelChange(a, b) { let n = 0; for (let i = 0; i < a.data.length; i += 4) { if (a.data[i] === b.data[i] && a.data[i + 1] === b.data[i + 1] && a.data[i + 2] === b.data[i + 2]) continue; const p = { r: a.data[i] / 255, g: a.data[i + 1] / 255, b: a.data[i + 2] / 255, a: 1 }; const q = { r: b.data[i] / 255, g: b.data[i + 1] / 255, b: b.data[i + 2] / 255, a: 1 }; if (deltaE(p, q) >= T.noticeable) n++; } return n; } // ---------- all verdicts for one render ---------- export function judge({ data, shot, bare, focus, width }) { const out = [], canvas = col(data.canvas), nodes = data.nodes; const add = (level, rule, msg, text = '', path = '') => out.push({ level, rule, msg, text, path }); let pixelCount = 0; // Text: clipping, contrast, and the boxes that go into the overlap sweep. const visible = []; for (const t of data.text) { if (t.sr) continue; const { gone, cut } = t.ctl ? {} : clipState(t); if (gone) continue; if (!t.ctl) visible.push(t); if (cut) add('fail', 'clipped-text', `${Math.round(cut.px)}px cut off the ${cut.side} by overflow${cut.by ? ` on ${cut.by}` : ''}`, t.text, t.path); if (t.dis || t.clipText) continue; // disabled controls are exempt; gradient text is check.mjs's job const chain = chainOf(t.id, nodes), op = chain.reduce((o, c) => o * c[1], 1), fg = col(t.fg); const need = t.size >= 24 || (t.size >= 18.66 && t.weight >= 600) ? T.large : T.text; let ratio = null, pixels = false; if (bare && (t.over || paintsImage(t.id, nodes))) { const s = sample(bare, t.rects); if (s) { const f = { ...fg, a: fg.a * op }; ratio = Math.min(contrast(f, s.dark), contrast(f, s.light)); pixels = true; pixelCount++; } } if (ratio == null) ratio = contrast(through(fg, chain, canvas), through(CLEAR, chain, canvas)); if (ratio < need) add('fail', 'text-contrast', `${fmt(ratio, need)}:1 needs ${need}${pixels ? ', measured on pixels' : ''}`, t.text, t.path); } // Overlapping text: sweep the line cores top to bottom, compare only boxes that share rows. // Each core is first cut to its overflow box, so text that is clipped away cannot overlap. const boxes = []; for (const t of visible) for (const q of t.rects) { const b = core(q, t.size); if (t.clipX) { b[0] = Math.max(b[0], t.clipX.b[0]); b[2] = Math.min(b[2], t.clipX.b[2]); } if (t.clipY) { b[1] = Math.max(b[1], t.clipY.b[1]); b[3] = Math.min(b[3], t.clipY.b[3]); } if (b[2] - b[0] > T.overlap && b[3] - b[1] > T.overlap) boxes.push([...b, t]); } boxes.sort((a, b) => a[1] - b[1]); const pairs = new Set(); for (let i = 0; i < boxes.length && pairs.size < 50; i++) { const A = boxes[i]; for (let j = i + 1; j < boxes.length && boxes[j][1] < A[3] - T.overlap; j++) { const B = boxes[j], key = [A[4].id, B[4].id].sort().join(':'); if (A[4] === B[4] || pairs.has(key)) continue; // A fixed bar or a scroll container over other text: the lower half of the view can be // scrolled clear (content under a bottom tab bar). The top half, at scroll 0, cannot. if (A[4].layer !== B[4].layer && Math.max(A[1], B[1]) > data.ih / 2) continue; const ox = Math.min(A[2], B[2]) - Math.max(A[0], B[0]), oy = Math.min(A[3], B[3]) - Math.max(A[1], B[1]); if (ox <= T.overlap || oy <= T.overlap) continue; pairs.add(key); add('fail', 'overlapping-text', `runs into "${B[4].text.slice(0, 30)}" (${B[4].path})`, A[4].text, A[4].path); } } // Form field edges against what is around them. A fill that contrasts is an edge too, and so // is the edge of a wrapper that hugs the field. The best of them is what a user sees. const edge = (id, sides) => { const own = chainOf(id, nodes), outside = through(CLEAR, own.slice(1), canvas); const s = sides.filter(([w]) => w >= 0.5).map(([, c]) => contrast(through(col(c), own, canvas), outside)); return [s.length ? Math.max(...s) : 1, contrast(through(CLEAR, own, canvas), outside)]; }; for (const f of data.fields) { let [border, fill] = edge(f.id, f.sides); for (const w of f.wraps) { const [b, l] = edge(w.id, w.sides); border = Math.max(border, b); fill = Math.max(fill, l); } if (Math.max(border, fill) < T.nonText) add('warn', 'field-border', `border ${fmt(border, 3)}:1, fill ${fmt(fill, 3)}:1, needs 3`, '', f.path); } // Sideways scroll. const wd = data.wide, who = wd.offenders.slice(0, 3).map(o => `${o.path} to ${Math.round(o.right)}px`).join(', '); if (!wd.rootClips && wd.sw > data.iw) add('fail', 'sideways-scroll', `page is ${wd.sw}px wide in a ${data.iw}px viewport`, '', who); else if (wd.rootClips && wd.offenders.length) add('warn', 'hidden-overflow', `overflow-x hidden on the page cuts content past ${data.iw}px`, '', who); // Targets. Under 24px fails unless a 24px circle around it touches nothing (the WCAG 2.5.8 // spacing exception). Inline links in running text are exempt from both sizes. const tg = data.targets; const dims = t => [t.box[2] - t.box[0], t.box[3] - t.box[1]]; const small = tg.map(t => !t.inline && dims(t).some(v => v < T.target)); const centre = t => [(t.box[0] + t.box[2]) / 2, (t.box[1] + t.box[3]) / 2]; const toBox = ([x, y], b) => Math.hypot(Math.max(b[0] - x, 0, x - b[2]), Math.max(b[1] - y, 0, y - b[3])); const nested = (i, j) => { for (let k = tg[i].up; k >= 0; k = tg[k].up) if (k === j) return true; return false; }; tg.forEach((t, i) => { const [w, h] = dims(t), size = `${Math.round(w)}ร${Math.round(h)}`, label = t.name || t.kind, c = centre(t); if (small[i] && tg.some((u, j) => j !== i && !nested(i, j) && !nested(j, i) && (toBox(c, u.box) < T.target / 2 || (small[j] && Math.hypot(c[0] - centre(u)[0], c[1] - centre(u)[1]) < T.target)))) return add('fail', 'target-size', `${size} needs 24ร24 or more room around it`, label, t.path); if (width <= T.touchWidth && !t.inline && (w < T.touch || h < T.touch)) add('warn', 'small-target', `${size} needs 44ร44 on touch`, label, t.path); }); // Accessible names. for (const n of data.names) { if (!n.via) add('fail', 'no-name', `${n.kind} has no accessible name`, '', n.path); else if (n.via === 'placeholder') add('warn', 'placeholder-label', `${n.kind} is named only by its placeholder`, n.name, n.path); } // Keyboard focus, one Tab press at a time. // When no computed style changed, shoot.mjs compared pixels around the element (f.pixels): a // ring drawn by a separate element, by script, still counts. if (data.modal) add('info', 'modal-open', 'a modal is open, so only the modal is measured', '', data.modal); for (const f of focus) { if (f.escaped) { add('fail', 'focus-escapes-modal', `Tab left the open modal (${f.modal}) for the page behind it`, f.name, f.path); continue; } if (offScreen(f)) { add('fail', 'focus-offscreen', 'focused but still outside the screen', f.name, f.path); continue; } if (!f.before) continue; let changed = false; const rings = []; f.now.forEach((n, i) => { if (!looksDifferent(f.before[i], n)) return; changed = true; rings.push(...ringRatios(f.before[i], n, f.own[i], f.outside[i], canvas)); }); if (!changed && !(f.pixels >= T.focusPixels)) add('fail', 'focus-invisible', `nothing visible changes on keyboard focus${f.pixels != null ? `, ${f.pixels} pixels differ` : ''}`, f.name, f.path); else if (rings.length && Math.max(...rings) < T.ring) add('fail', 'focus-ring', `ring ${fmt(Math.max(...rings), T.ring)}:1 needs 3`, f.name, f.path); } // Content still invisible after scrolling to the bottom and back and waiting. for (const h of data.hidden) add('fail', 'hidden-content', `still at ${h.why} after scrolling and 500ms${h.n > 1 ? `, ${h.n} text blocks` : ''}`, h.text, h.path); // Colour share, from the pixels. const share = colourShare(shot); const fams = share.top.map(([f, s]) => `${f} ${pct(s)}`).join(', ') || 'no colour'; add('info', 'colour-share', `${pct(share.neutral)} neutral; ${fams}; ${share.saturated.length} saturated hue${share.saturated.length === 1 ? '' : 's'} over 0.5%`); if (share.saturated.length > T.hues) add('warn', 'too-many-hues', `${share.saturated.length} saturated hue families over 0.5% each: ${share.saturated.join(', ')}`); const rank = { fail: 0, warn: 1, info: 2 }; out.sort((a, b) => rank[a.level] - rank[b.level]); return { findings: out, stats: { colour: share, text: data.text.length, pixels: pixelCount, targets: tg.length, tabbed: focus.length, focused: focus.map(f => f.path), pixelChecked: focus.filter(f => f.pixels != null).length } }; } // Same page background and text colour in two renders means the page has no dark theme. export function sameLook(a, b) { const page = l => blend(over(col(l.body), col(l.html)), col(l.canvas)); return deltaE(page(a), page(b)) < 0.005 && deltaE(blend(col(a.text), page(a)), blend(col(b.text), page(b))) < 0.005; }skills/oxfords/scripts/lib/png.mjs3.1 KBc6cbcc001210upstream โ
// Oxfords PNG decoder. Zero dependencies (node:zlib). Enough for browser screenshots: // 8-bit greyscale, grey + alpha, RGB and RGBA, non-interlaced, all five row filters. // Returns { width, height, data } where data is RGBA bytes, row by row, top to bottom. import { inflateSync } from 'node:zlib'; const SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10]; const CHANNELS = { 0: 1, 2: 3, 4: 2, 6: 4 }; // colour type -> bytes per pixel at 8 bits export function decodePng(buf) { if (!SIGNATURE.every((b, i) => buf[i] === b)) throw new Error('not a PNG'); let pos = 8, width = 0, height = 0, depth = 0, type = -1, interlace = 0; const idat = []; while (pos + 8 <= buf.length) { const len = buf.readUInt32BE(pos); const kind = buf.toString('latin1', pos + 4, pos + 8); const body = buf.subarray(pos + 8, pos + 8 + len); if (kind === 'IHDR') { width = body.readUInt32BE(0); height = body.readUInt32BE(4); depth = body[8]; type = body[9]; interlace = body[12]; } else if (kind === 'IDAT') idat.push(body); else if (kind === 'IEND') break; pos += 12 + len; // length, type, body, crc } const ch = CHANNELS[type]; if (depth !== 8 || !ch || interlace) throw new Error(`unsupported PNG: depth ${depth}, colour type ${type}, interlace ${interlace}`); const raw = inflateSync(Buffer.concat(idat)); const stride = width * ch; if (raw.length < (stride + 1) * height) throw new Error('PNG data is short'); const px = Buffer.alloc(stride * height); // Undo the filter on each row. a = byte to the left, b = byte above, c = above-left. for (let y = 0; y < height; y++) { const filter = raw[y * (stride + 1)]; const src = y * (stride + 1) + 1, dst = y * stride, up = dst - stride; const above = x => (y ? px[up + x] : 0); switch (filter) { case 0: raw.copy(px, dst, src, src + stride); break; case 1: for (let x = 0; x < stride; x++) px[dst + x] = raw[src + x] + (x >= ch ? px[dst + x - ch] : 0); break; case 2: for (let x = 0; x < stride; x++) px[dst + x] = raw[src + x] + above(x); break; case 3: for (let x = 0; x < stride; x++) px[dst + x] = raw[src + x] + (((x >= ch ? px[dst + x - ch] : 0) + above(x)) >> 1); break; case 4: for (let x = 0; x < stride; x++) { const a = x >= ch ? px[dst + x - ch] : 0, b = above(x), c = x >= ch ? above(x - ch) : 0; const p = a + b - c, pa = Math.abs(p - a), pb = Math.abs(p - b), pc = Math.abs(p - c); px[dst + x] = raw[src + x] + (pa <= pb && pa <= pc ? a : pb <= pc ? b : c); } break; default: throw new Error(`bad PNG filter ${filter} on row ${y}`); } } // Buffer stores bytes mod 256, which is exactly the wrap-around the filters need. if (ch === 4) return { width, height, data: px }; const out = Buffer.alloc(width * height * 4); for (let i = 0, j = 0; j < out.length; i += ch, j += 4) { if (ch === 3) { out[j] = px[i]; out[j + 1] = px[i + 1]; out[j + 2] = px[i + 2]; out[j + 3] = 255; } else { out[j] = out[j + 1] = out[j + 2] = px[i]; out[j + 3] = ch === 2 ? px[i + 1] : 255; } } return { width, height, data: out }; }skills/oxfords/scripts/lib/report.mjs14 KB7fa977783111upstream โ
Contents are not inlined in the catalog. Open the upstream file.
skills/oxfords/scripts/lib/slop-inpage.mjs11 KB1880ee908be0upstream โ
// Oxfords audit, the half that runs inside the page. Zero dependencies. // Playwright serialises installSlop() with toString(), so nothing in here may reach module scope. // It collects raw facts about the rendered page: text and how it is set, headings, bordered // boxes, divider lines, pills, gradients, small dots. Every threshold lives in slop.mjs. // // await page.evaluate(installSlop); await page.evaluate(() => window.__oxs.collect()); export function installSlop() { if (window.__oxs) return; const SKIP = new Set(['script', 'style', 'noscript', 'template', 'svg', 'math', 'head', 'title', 'select', 'option', 'textarea', 'iframe', 'canvas', 'video', 'audio', 'picture', 'img']); const CODE = 'code,pre,kbd,samp,var,tt'; const HEAD = 'h1,h2,h3,[role="heading"]'; const ACT = 'a[href],button,[role="button"],[role="tab"],input,label,summary,select'; const MONO = /mono|courier|consolas|menlo|monaco|fira code|source code|jetbrains|monospace/i; const MAX = 12000; const r0 = Math.round; const fam = ff => (ff || '').split(',')[0].replace(/["']/g, '').trim(); const words = t => (t.match(/[\p{L}\p{N}][\p{L}\p{N}'โ-]*/gu) || []).length; const squash = t => (t || '').replace(/\s+/g, ' ').trim(); function pageBox(el) { const r = el.getBoundingClientRect(); return [r0(r.left + scrollX), r0(r.top + scrollY), r0(r.width), r0(r.height)]; } function alpha(c) { if (!c || c === 'transparent') return 0; const m = /\/\s*([\d.]+%?)\s*\)$/.exec(c) || /^rgba\([^,]+,[^,]+,[^,]+,\s*([\d.]+%?)\)$/.exec(c); if (!m) return 1; return m[1].endsWith('%') ? parseFloat(m[1]) / 100 : parseFloat(m[1]); } // Any computed colour as an rgba() string: legacy rgb() is read as is, everything else (oklch, // lab, color()) is painted on a 1x1 canvas and read back. const cv = document.createElement('canvas'); cv.width = cv.height = 1; const cx = cv.getContext('2d', { willReadFrequently: true }); function rgba(css) { if (/^rgba?\(/.test(css)) return css; cx.clearRect(0, 0, 1, 1); cx.fillStyle = '#000'; cx.fillStyle = css; cx.fillRect(0, 0, 1, 1); const [r, g, b, a] = cx.getImageData(0, 0, 1, 1).data; return `rgba(${r},${g},${b},${(a / 255).toFixed(3)})`; } const stops = img => (img.match(/(?:rgba?|oklch|oklab|lab|lch|hsla?|hwb|color)\((?:[^()]|\([^()]*\))*\)|#[0-9a-f]{3,8}\b/gi) || []).slice(0, 12).map(rgba); function side(s, k) { const w = parseFloat(s[`border${k}Width`]) || 0; return w >= 1 && s[`border${k}Style`] !== 'none' && s[`border${k}Style`] !== 'hidden' && alpha(s[`border${k}Color`]) >= 0.15; } function ownText(el) { let t = ''; for (const n of el.childNodes) if (n.nodeType === 3) t += n.nodeValue; return squash(t); } // Short CSS path: up to four levels, stopping at an id. Same shape as inpage.mjs. function path(el) { const parts = []; for (let n = el; n && n.nodeType === 1 && parts.length < 4; n = n.parentElement) { if (n === document.body || n === document.documentElement) break; let s = n.localName; if (n.id && /^[a-z][\w-]*$/i.test(n.id)) { parts.unshift(`${s}#${n.id}`); break; } const c = [...n.classList].find(k => /^[a-z][\w-]{0,24}$/i.test(k) && !/\d{3,}/.test(k)); if (c) s += '.' + c; parts.unshift(s); } return parts.join(' > ') || el.localName; } function collect() { const de = document.documentElement, body = document.body; const out = { page: { w: de.scrollWidth, h: Math.max(de.scrollHeight, body ? body.scrollHeight : 0), vw: innerWidth, vh: innerHeight }, fonts: {}, texts: [], heads: [], boxes: [], lines: [], pills: [], grads: [], dots: [], rails: [], copy: [], imgs: [], }; if (!body) return out; out.fonts.body = fam(getComputedStyle(body).fontFamily); const h1 = document.querySelector('h1'); if (h1) out.fonts.heading = fam(getComputedStyle(h1).fontFamily); for (const el of [de, body]) { const s = getComputedStyle(el); if (/gradient\(/.test(s.backgroundImage)) out.grads.push({ stops: stops(s.backgroundImage), box: [0, 0, out.page.w, out.page.h], path: el.localName, page: true }); } const bordered = new Set(), pills = new Set(), seenAct = new Set(); const area = out.page.vw * out.page.vh; const walker = document.createTreeWalker(body, NodeFilter.SHOW_ELEMENT, { acceptNode(el) { if (SKIP.has(el.localName)) return NodeFilter.FILTER_REJECT; const s = getComputedStyle(el); if (s.display === 'none') return NodeFilter.FILTER_REJECT; if (+s.opacity < 0.05) return NodeFilter.FILTER_REJECT; return NodeFilter.FILTER_ACCEPT; }, }); let n = 0; for (let el = walker.nextNode(); el && n < MAX; el = walker.nextNode(), n++) { const s = getComputedStyle(el); if (s.visibility === 'hidden') continue; const b = pageBox(el); if (b[2] <= 1 || b[3] <= 1) continue; // nothing, or a screen-reader-only 1px box const tag = el.localName; const inCode = !!el.closest(CODE), act = !!el.closest(ACT); // Text set on this element. const t = ownText(el); if (t) { const ff = fam(s.fontFamily); out.texts.push({ tag, t: t.slice(0, 200), len: t.length, words: words(t), box: b, fam: ff, mono: MONO.test(s.fontFamily), code: inCode, act, italic: s.fontStyle !== 'normal', tt: s.textTransform, ls: parseFloat(s.letterSpacing) || 0, fs: parseFloat(s.fontSize) || 16, fw: +s.fontWeight || 400, inHead: !!el.closest(HEAD), path: path(el), }); if (out.texts.length < 4000) out.copy.push({ tag: /^h[1-6]$/.test(tag) ? tag : act ? 'button' : 'p', t: t.slice(0, 300) }); } // Buttons and links by their full label, for the copy rules. if (el.matches('a[href],button,[role="button"]')) { const label = squash(el.innerText).slice(0, 80); if (label && !seenAct.has(label)) { seenAct.add(label); out.copy.push({ tag: 'button', t: label }); } } // Headings, and display text set like a heading without the tag. const fs = parseFloat(s.fontSize) || 16; const isHead = el.matches(HEAD) || (fs >= 32 && t && t.length <= 140 && !el.closest(HEAD)); if (isHead) { const text = squash(el.innerText); if (text) { const baseFam = fam(s.fontFamily), baseItalic = s.fontStyle !== 'normal'; let italicKids = 0, famKids = []; for (const k of el.querySelectorAll('*')) { if (!squash(k.textContent)) continue; const ks = getComputedStyle(k); if (!baseItalic && ks.fontStyle !== 'normal') italicKids++; const kf = fam(ks.fontFamily); if (kf && kf !== baseFam && !famKids.includes(kf)) famKids.push(kf); } out.heads.push({ tag, level: /^h[1-6]$/.test(tag) ? +tag[1] : 2, t: text.slice(0, 200), box: b, fs, fam: baseFam, italic: baseItalic, italicKids, famKids, path: path(el) }); } } // Bordered boxes: all four sides drawn, big enough to hold content, holding text. const sides = ['Top', 'Right', 'Bottom', 'Left'].map(k => side(s, k)); const formy = /^(?:input|button|a|table|thead|tbody|tr|td|th|hr|fieldset|li)$/.test(tag); if (sides.every(Boolean) && b[2] >= 120 && b[3] >= 48 && !formy && squash(el.textContent)) { let depth = 0; for (let p = el.parentElement; p; p = p.parentElement) if (bordered.has(p)) depth++; bordered.add(el); out.boxes.push({ box: b, depth, path: path(el) }); } // Side rails: one thick border on the left or right and nothing else. const lw = parseFloat(s.borderLeftWidth) || 0, rw = parseFloat(s.borderRightWidth) || 0; if (b[3] >= 16 && !sides[0] && !sides[2] && ((lw >= 2 && sides[3] && !sides[1]) || (rw >= 2 && sides[1] && !sides[3]))) out.rails.push({ box: b, path: path(el), colour: rgba(lw >= 2 ? s.borderLeftColor : s.borderRightColor) }); // Divider lines: an <hr>, a one-sided rule across a row, or a thin filled strip. const inTable = !!el.closest('table'); if (tag === 'hr') out.lines.push({ box: b, path: path(el), menu: !!el.closest('[role="menu"],[role="listbox"]') }); else if (!inTable && !formy && b[2] >= 160 && !sides.every(Boolean) && ((sides[0] && !sides[1] && !sides[3]) || (sides[2] && !sides[1] && !sides[3]))) out.lines.push({ box: b, path: path(el), menu: !!el.closest('[role="menu"],[role="listbox"],nav') }); else if (!inTable && b[3] <= 2 && b[2] >= 160 && alpha(s.backgroundColor) >= 0.15 && !squash(el.textContent)) out.lines.push({ box: b, path: path(el), menu: false }); // Pills: fully rounded ends, short label, a fill or a border. const rad = s.borderTopLeftRadius, rv = parseFloat(rad) || 0; const round = rad.includes('%') ? rv >= 50 : rv >= b[3] / 2 - 1; if (round && b[3] >= 14 && b[3] <= 40 && b[2] > b[3] * 1.3 && b[2] <= 280 && (alpha(s.backgroundColor) >= 0.06 || sides.some(Boolean))) { const label = squash(el.innerText); let inside = false; for (let p = el.parentElement; p && !inside; p = p.parentElement) inside = pills.has(p); if (label && label.length <= 32 && words(label) <= 4 && !inside && tag !== 'input') { pills.add(el); out.pills.push({ box: b, t: label, act: el.matches(ACT) || act, path: path(el) }); } } // Gradient backgrounds on anything large. if (/gradient\(/.test(s.backgroundImage) && b[2] * b[3] >= 0.15 * area) out.grads.push({ stops: stops(s.backgroundImage), box: b, path: path(el) }); // Small round dots: the raw material of fake window chrome. if (b[2] >= 6 && b[2] <= 18 && Math.abs(b[2] - b[3]) <= 1 && rv >= b[2] / 2 - 1 && alpha(s.backgroundColor) >= 0.5) out.dots.push({ box: b, bg: rgba(s.backgroundColor) }); } for (const img of document.images) { if (!img.getClientRects().length) continue; out.imgs.push({ alt: img.hasAttribute('alt') ? img.getAttribute('alt') : null }); if (out.imgs.length > 300) break; } return out; } // Page boxes for the short paths the render check reports, so its findings can be pinned too. function locate(paths) { return paths.map(p => { try { const el = document.querySelector(p); return el ? pageBox(el) : null; } catch { return null; } }); } // Every stylesheet the page can read. Cross-origin sheets come back as their href. function sheets() { const css = [], hrefs = []; for (const sh of document.styleSheets) { try { css.push([...sh.cssRules].map(r => r.cssText).join('\n')); } catch { if (sh.href) hrefs.push(sh.href); } } return { css, hrefs }; } window.__oxs = { collect, locate, sheets }; }skills/oxfords/scripts/lib/slop.mjs20 KB0d40446f6ca6upstream โ
Contents are not inlined in the catalog. Open the upstream file.
skills/oxfords/scripts/palette.mjs36 KBa29a48e93808upstream โ
Contents are not inlined in the catalog. Open the upstream file.
skills/oxfords/scripts/palette.test.mjs13 KBd651483569abupstream โ
Contents are not inlined in the catalog. Open the upstream file.
skills/oxfords/scripts/palettes.json3.9 KBd77aa0d0f784upstream โ
Contents are not inlined in the catalog. Open the upstream file.
skills/oxfords/scripts/shoot.mjs13 KBafedaa476676upstream โ
Contents are not inlined in the catalog. Open the upstream file.
skills/oxfords/scripts/shoot.test.mjs9.7 KBc1136b8eed6dupstream โ
Contents are not inlined in the catalog. Open the upstream file.
skills/oxfords/references/app-ui.md11 KB0578b14be04eupstream โ
Contents are not inlined in the catalog. Open the upstream file.
skills/oxfords/references/audit.md4.5 KBfb396073fcd1upstream โ
Contents are not inlined in the catalog. Open the upstream file.
skills/oxfords/references/colour.md11 KBa65a6d12002fupstream โ
Contents are not inlined in the catalog. Open the upstream file.
skills/oxfords/references/landing.md6.9 KB83bb7884fc09upstream โ
Contents are not inlined in the catalog. Open the upstream file.
skills/oxfords/references/mobile.md6.5 KB44df0db74115upstream โ
Contents are not inlined in the catalog. Open the upstream file.
skills/oxfords/references/motion.md3.5 KBc410df14a453upstream โ
Contents are not inlined in the catalog. Open the upstream file.
skills/oxfords/references/redesign.md3.9 KB19f9cc3076ebupstream โ
Contents are not inlined in the catalog. Open the upstream file.
skills/oxfords/references/review.md5.0 KB6eea2ad7f697upstream โ
Contents are not inlined in the catalog. Open the upstream file.
skills/oxfords/references/slop-floor.md9.9 KB08d3d7e717acupstream โ
Contents are not inlined in the catalog. Open the upstream file.
skills/oxfords/references/states-forms-copy.md7.2 KB666768f58731upstream โ
Contents are not inlined in the catalog. Open the upstream file.
README.mdupstream โ
Contents are not inlined in the catalog. Open the upstream file.
Plain-text copy, no login: /skill-bundles/arhamhi-oxfords-skills-oxfords.md