Measure the text the way an eye reads it, not the way a ratio scores it

The sweep has checked WCAG AA contrast for a long time and the page passed. That
result was worth less than it looked.

WCAG 2's ratio is a luminance gap, and a luminance gap overstates readability once
one colour is near black — which is every reading on a page whose ground is #141414.
Tuning a colour until it clears 4.5:1 there lands on text that passes the audit and
still reads as a smudge across a table in a dim room. Several rules in this
stylesheet said as much in their own comments, one of them "measured 4.5:1 at
#a5a5a5 exactly, so it sits above that": the right instinct through the wrong lens.

The check also could not see half the backgrounds it scored against. It reads
background-color and takes the best contrast of any candidate ancestor, so text on
the felt was scored against the dark page behind the felt. Two plain AA failures sat
in a clean report for as long as the check has existed — the chair number on the
brown rim at 2.65:1, and the pot's own label, gold on green, at 2.66:1.

runContrastAudit.js scores with APCA and gets the background by screenshotting the
page with its text made transparent and reading the pixels, which no gradient or
shadow can fool. The first version walked the DOM and called the gold dealer button
black-on-black at Lc 0.4; that false positive is why it works this way.

Found: 65 of 92 pieces of text below their level, 54 passing AA at the same moment,
worst Lc 28. Now nothing is below Lc 60, nothing fails AA, and the worst is Lc 60.4.

Three fixes worth naming, none of them "make the grey lighter":

- A player's stack was secondary text at Lc 44, under a name in --text at a heavier
  weight. That says a dealer needs the name more than the number; during a hand the
  opposite is true. Hierarchy comes from size and weight now, which is free, rather
  than from fading, which on a dark ground is the most expensive way to say it.
- An empty seat had no background of its own, so the felt decided how readable its
  number was: Lc 28 on the rim, 30 on the green, 33 further in. It has a ground now,
  at 0.62 and not the 0.82 first written — contrast is nearly flat across that range
  and the heavier wash put four dark rectangles on the felt like holes.
- The pot's label sat on the one green in the design. The disc is deeper rather than
  the label bleached, because gold on dark green is the pairing this page is built
  on. Deepening only its outer stop moved it two points: the highlight is at 32%/28%
  and that is exactly where the label sits.

apca.js is checked against the eight published reference pairs, png.js against
round-tripped fixtures for every filter. Four fault injections caught; a fifth
turned out to be a no-op — the Paeth predictor is symmetric in its first two
arguments over all 16,777,216 byte triples, so that swap is untestable, which is
written down rather than papered over with a fixture that appears to catch it.

Still below the strict APCA level: 55, all of them 10-12px labels that would need
white type or a bigger seat puck. Reported, not chased, and said out loud in the
sweep's own notes.

Layout sweep unchanged: 5 FAILs, 14 offender lines, no regressions. 950 tests pass.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_015bnp7xKUPFFSpwkYNFaPgb
This commit is contained in:
2026-09-09 06:40:28 -06:00
co-authored by Claude Opus 5
parent 295d9eff4a
commit 853fcedea0
8 changed files with 988 additions and 23 deletions
+98 -23
View File
@@ -57,11 +57,31 @@
--line: #3a3a3a;
--line-strong: #4a4a4a;
/* Text. */
/* Text.
These two were picked to clear WCAG AA — several rules in this file still say so
in their own comments, one of them "measured 4.5:1 at #a5a5a5 exactly, so it sits
above that". That was the right instinct with the wrong instrument. WCAG 2's
ratio is a luminance gap, and a luminance gap overstates readability once one of
the colours is near black, which every reading on this page is: the page is
#141414 and the panels are darker than the rows. Tuning to 4.5:1 against a
near-black ground lands on text that passes the audit and still reads as a smudge
across a table in a dim room.
Re-measured with APCA, which scores the pair for the size and weight it is
actually drawn at: #9a9a9a on a panel came out at Lc 46 and #8a8a8a at Lc 38,
against a floor of Lc 60 for a label and Lc 75 for anything read to make a
decision. Fifty-four separate pieces of text were below their level while passing
AA. These are the values that clear it — muted at Lc ~71, dim at Lc ~59.
They are lighter than they were, and the hierarchy did not come out of it: --text
is still Lc 95, so the three tiers are 95 / 71 / 59, which is a wider spread than
the 95 / 46 / 38 it replaces. Fading is not the only way to say "secondary", and
on a dark ground it is the most expensive one — size and weight say it without
spending contrast, which is what the seat puck does now. */
--text-bright: #f5f5f5;
--text: #eee;
--text-muted: #9a9a9a;
--text-dim: #8a8a8a;
--text-muted: #c8c8c8;
--text-dim: #b4b4b4;
/* The one accent. Desaturated against the dark ground — a fully saturated gold
vibrates on a near-black surface and stops reading as a highlight. */
@@ -711,9 +731,23 @@ button,
}
}
/* The disc is deeper than it was. Its bright stop left the label sitting on a mid green
that measured Lc 38 and — the reading that settles it — 3.79:1, which is a plain AA
failure the audit had never reported because it reads background-color and this is a
gradient over the felt.
Deepening the disc rather than bleaching the label is what keeps the accent: gold on
a dark green is the pairing this whole page is built on, and gold on a mid green is
the one place it wasn't. The pot is also the number read from furthest away, so a
disc that separates harder from the felt is the right answer twice over.
Both stops, not just the far one. Deepening only the outer stop moved the label by
two points of Lc and no more, because the highlight is at 32%/28% and that is exactly
where the label sits — the reading was being taken on the brightest part of the disc.
The highlight is still there, it is just a lift within a dark disc now rather than a
wash of white over a mid green. */
#potBadge {
position: relative;
background: radial-gradient(circle at 32% 28%, rgba(255, 255, 255, 0.08), rgba(0, 0, 0, 0.55));
background: radial-gradient(circle at 32% 28%, rgba(0, 0, 0, 0.34), rgba(0, 0, 0, 0.78));
border: 1px solid rgba(255, 255, 255, 0.14);
border-radius: var(--r-pill);
padding: var(--sp-3) var(--sp-5);
@@ -724,11 +758,16 @@ button,
box-shadow: inset 0 2px 6px rgba(0, 0, 0, 0.6), 0 4px 14px rgba(0, 0, 0, 0.45);
}
/* --gold is tuned to sit on the near-black of the panels and the bar. The pot badge is
the one place it lands on green instead, and green is the worst possible ground for
it: measured Lc 38 there against Lc 70-odd everywhere else the same token is used.
The brighter step of the same accent clears it without the badge losing the accent —
white would read as a second amount next to the one underneath it. */
#potBadgeLabel {
font-size: var(--fs-xs);
letter-spacing: 0.14em;
text-transform: uppercase;
color: var(--gold);
color: var(--gold-bright);
}
#potBadgeAmount {
@@ -935,14 +974,29 @@ button,
text-decoration-color: rgba(224, 123, 123, 0.75);
}
/* An empty seat used to be a 2%-white wash at 0.7 opacity, which is another way of
saying it had no background of its own and whatever the felt was doing behind it
decided how readable its label was. The felt is a gradient with a brown rim, so that
varied by chair: the same #aeaeae chair number measured Lc 28 on the rim, Lc 30 on
the dark green and Lc 33 further in. Text whose contrast depends on where the seat
happens to sit cannot be reasoned about, and the fade was making every part of it
worse at once.
A ground of its own fixes both. The dashed border and the EMPTY label are what say
"open" — they always were — so the fade was not carrying the meaning, only costing
contrast. It stays louder than seatInactive, which is what the old comment here was
protecting and is still true.
0.62 and not the 0.82 this was first written at. Contrast turns out to be almost flat
across that range — Lc 69.6 against the rim at 0.62 versus 71.7 at 0.82, because the
label is light and every ground in that range is dark — so the heavier wash bought
about two points of Lc and cost four dark rectangles sitting on the felt like holes.
Taking the lighter one is free. */
.seat.seatEmpty {
background: rgba(255, 255, 255, 0.02);
background: rgba(18, 18, 18, 0.62);
border-style: dashed;
border-color: rgba(255, 255, 255, 0.13);
border-color: rgba(255, 255, 255, 0.22);
box-shadow: none;
/* Deliberately louder than seatInactive: an open seat is information a
dealer wants, not something to squint at. */
opacity: 0.7;
}
.seatEmptyLabel {
@@ -957,16 +1011,17 @@ button,
box-shadow: 0 0 0 2px rgba(9, 255, 0, 0.4), 0 4px 14px rgba(0, 0, 0, 0.5);
}
/* The chair number is 9px, and on an empty seat it is 9px behind a 0.7 fade: var(--text-dim)
came out at 3.39:1 once the fade was composited, for the label a dealer reads to
answer "which seat is seat 6?". Lifted until it passes with a little to spare —
measured 4.5:1 at #a5a5a5 exactly, so it sits above that. */
/* The chair number answers "which seat is seat 6?", and it is the smallest text on the
felt. It was set to a hand-picked #aeaeae chosen for being a hair over 4.5:1 — see
the token block for why that bar was the wrong one, and the rule above for why the
fade behind it made the reading meaningless anyway. On the token now, so it moves
with the rest of the page instead of being pinned to a number from one measurement. */
.seatChairNumber {
position: absolute;
top: 2px;
left: 6px;
font-size: var(--fs-2xs);
color: #aeaeae;
color: var(--text-muted);
}
/* Two lines, not an ellipsis.
@@ -1318,9 +1373,13 @@ button,
color: #eaf3ff;
}
/* Lightened a step. Dark-on-gold was the right call and stays; the gold underneath it
was just too deep to carry 9px bold at its bottom stop, which measured Lc 46 while
the small blind's blue was already at Lc 84. Raising the gold is what closes the gap,
and it costs nothing — the badge reads as the same gold chip, only brighter. */
.bbBadge {
left: 2px;
background: linear-gradient(180deg, #e6ad4d, #c98a2a);
background: linear-gradient(180deg, #f0c069, #e2a845);
color: #241a05;
}
@@ -2931,7 +2990,7 @@ body.hasActionBar #holdemApp {
border-radius: var(--r-pill);
border: 1px solid #414141;
background: #262626;
color: #bdbdbd;
color: var(--text-muted);
font-family: inherit;
font-size: var(--fs-sm);
cursor: pointer;
@@ -2962,7 +3021,7 @@ body.hasActionBar #holdemApp {
}
.actionPlayers {
color: #9c9c9c;
color: var(--text-muted);
font-variant-numeric: tabular-nums;
}
@@ -2974,7 +3033,7 @@ body.hasActionBar #holdemApp {
.actionWho {
margin-left: auto;
color: #9c9c9c;
color: var(--text-muted);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
@@ -3286,7 +3345,7 @@ body.hasActionBar #holdemApp {
padding: 0 var(--sp-1);
border-radius: var(--r-sm);
border: 1px solid currentColor;
opacity: 0.75;
opacity: 0.9;
font-family: inherit;
font-size: var(--fs-2xs);
line-height: 1.4;
@@ -3297,7 +3356,12 @@ body.hasActionBar #holdemApp {
/* A key hint is small — 9.6px — so AA asks 4.5:1 of it, and at the opacity these used
to carry they measured 2.97 to 3.33 against their buttons. That's the same fault as
the folded seats above: a fade chosen for looks pushing text a dealer is meant to
read under the threshold. They're still quieter than the label they sit beside. */
read under the threshold. They're still quieter than the label they sit beside.
Raised again from 0.75 to 0.9 for the same reason the text tokens moved: clearing
4.5:1 was never the same thing as being readable on this ground, and a fade is the
most expensive way to say "quieter" when the ground is already near black. The
keycap's border and its size still say it, and both are free. */
.actionKey {
position: absolute;
top: 5px;
@@ -3305,7 +3369,7 @@ body.hasActionBar #holdemApp {
padding: 0 var(--sp-1);
border-radius: var(--r-sm);
border: 1px solid currentColor;
opacity: 0.75;
opacity: 0.9;
font-family: inherit;
font-size: var(--fs-2xs);
line-height: 1.4;
@@ -3487,9 +3551,20 @@ body.hasActionBar #holdemApp {
cleared, and settled for the narrowest, which is also the one that wraps hardest.
Two pixels, and every seat on the felt paid for them. */
/* The stack is not secondary text, and it had been styled as some for as long as this
file has existed: muted grey under a name set in --text at a heavier weight. Read
back the other way, that says a dealer needs the name more than the number — and
during a hand the opposite is true. The name is looked up once, to find the chair;
the stack is read on every single action, because it is what decides whether a player
can cover the bet. It measured Lc 44 on the puck, the dimmest thing on the felt that
anyone has to read.
Set in --text now. The name is still the louder of the two — it is bigger and it is
600 — so the hierarchy is intact; it is just carried by size and weight instead of by
fading the number underneath it. */
.seatPuckStack {
font-size: var(--fs-2xs);
color: var(--text-muted);
color: var(--text);
font-variant-numeric: tabular-nums;
margin-top: var(--sp-0);
white-space: nowrap;
+69
View File
@@ -837,6 +837,75 @@ the bet chips at extreme crowding the way the tight tier already drops the hole
capping the seat count by viewport, or letting the felt scroll. Each trades something a
dealer can see, so none of them should be picked by whoever is next holding a ruler.
## The contrast check was passing text nobody could read
The layout sweep has checked WCAG AA contrast for a long time and the page passed it.
That result was worth less than it looked, for two separate reasons.
The first is the instrument. WCAG 2's contrast ratio is a luminance gap, and a luminance
gap overstates readability once one of the two colours is near black — which is every
reading taken on this page, whose ground is `#141414` and whose panels are darker than
its rows. This is not a quibble about the spec; it is the spec's own working group's
position, and it is why APCA exists. Tuning a colour until it clears 4.5:1 on a
near-black ground lands on text that passes the audit and still reads as a smudge across
a table in a dim room. Several rules in the stylesheet said so in their own comments —
one of them "measured 4.5:1 at `#a5a5a5` exactly, so it sits above that" — which is the
right instinct aimed through the wrong lens.
The second is that the check could not see half the backgrounds it was scoring against.
It reads `background-color` and walks up the ancestors, so a background painted by a
gradient is invisible to it; and where several ancestors are candidates it takes *the
best* contrast of any of them. Put together, text on the felt was being scored against
the dark page behind the felt rather than the felt. Two plain AA failures had been
sitting in a clean report for as long as the check has existed: the chair number on an
empty seat, on the table's brown rim, at 2.65:1, and the pot's own label, gold on green,
at 2.66:1.
`runContrastAudit.js` is the answer to both. It scores with APCA, and it gets the
background by screenshotting the page with every piece of text made transparent and
reading the pixels underneath — which cannot be fooled by a gradient, a shadow or a
border, because it is looking at what was painted. The first version of it *did* walk the
DOM, and reported the gold dealer button as black-on-black at Lc 0.4; an element anyone
can see is legible. That false positive is why the tool works the way it does.
What it found, on 92 distinct pieces of text: 65 below the level APCA sets for the size
and weight they are drawn at, **54 of them passing WCAG AA at the same moment**. The
worst was Lc 28. After this round nothing on the page is below Lc 60, nothing fails AA,
and the worst reading is Lc 60.4.
Three of the fixes are worth naming, because none of them is "make the grey lighter":
- **A player's stack was styled as secondary text.** Muted grey at Lc 44, under a name
set in `--text` at a heavier weight. Read back the other way that says a dealer needs
the name more than the number, and during a hand the opposite is true — the name is
looked up once to find the chair, the stack is read on every action because it decides
whether a player can cover the bet. Hierarchy now comes from size and weight, which is
free, instead of from fading, which on a dark ground is the most expensive way to say
"secondary".
- **An empty seat had no background of its own**, just a 2%-white wash at 0.7 opacity, so
whatever the felt was doing behind it decided how readable its number was: Lc 28 on the
rim, 30 on the dark green, 33 further in. Contrast that depends on where a seat happens
to sit cannot be reasoned about. It has a ground now. The wash is 0.62 and not the 0.82
it was first written at, because contrast turns out to be nearly flat across that range
— two points of Lc — and the heavier one put four dark rectangles on the felt like
holes.
- **The pot's label sat on the one green in the design.** `--gold` is tuned for near-black
and measures Lc 70-odd everywhere else it is used; on the pot disc it was Lc 38. The
disc is deeper now rather than the label bleached, because gold on dark green is the
pairing the whole page is built on. Deepening only the disc's outer stop moved it two
points and no further — the highlight is at 32%/28% and that is exactly where the label
sits, so the reading was being taken on the brightest part of the disc.
### What is deliberately not fixed
APCA asks Lc 90 of anything at 12px/400 or below, and this page is full of 10px and 11px
labels that live inside a 58px seat puck. Fifty-five pieces of text are still below that
bar. Reaching it means white micro-labels and a flatter, shoutier page; the honest way to
clear it is bigger type, and bigger type is a layout change that would relitigate the
seat-crowding work above. So the sweep reports two numbers — the strict per-size level,
and the Lc 60 / Lc 75 floors this page actually holds itself to — and only the floors are
treated as pass/fail.
## The failures that only happen at the table
Everything above this line is about a tool being easy to read and quick to press. This
+98
View File
@@ -0,0 +1,98 @@
// Perceptual contrast (APCA), and how much of it each piece of text needs.
//
// The audit already had a contrast check and it passed, which is why this exists. That
// check measures WCAG 2 contrast ratio, and WCAG 2's own authors say it is the wrong
// instrument for this page: the ratio is a luminance gap, and a luminance gap
// systematically *overstates* readability once one of the two colours is near black.
// This table's page is #141414 and its panels are darker still, so every reading it
// takes is on the side of the algorithm where it is least reliable. Text can clear
// 4.5:1 and still read as a smudge.
//
// APCA asks the other question — can text of *this size and weight* be read on this
// background — and answers it on a scale where a given number means the same
// readability at either polarity. It replaces nothing: the WCAG check stays, because
// that is the number an accessibility audit will ask for. This is the one that says
// whether a dealer can read it in a dim room.
//
// Constants are 0.98G-4g, and the implementation is checked against the eight
// published reference pairs in apcaMath.test.js. An unverified contrast checker is
// worse than none, because it launders a guess into a number.
const MAIN_TRC = 2.4;
const R_CO = 0.2126729, G_CO = 0.7151522, B_CO = 0.0721750;
const NORM_BG = 0.56, NORM_TXT = 0.57, REV_TXT = 0.62, REV_BG = 0.65;
const BLK_THRS = 0.022, BLK_CLMP = 1.414;
const SCALE_BOW = 1.14, SCALE_WOB = 1.14;
const LO_BOW_OFFSET = 0.027, LO_WOB_OFFSET = 0.027;
const DELTA_Y_MIN = 0.0005, LO_CLIP = 0.001;
// Screen luminance. Note this is a straight exponent, not the sRGB piecewise curve —
// APCA specifies the simple 2.4 power and the two are not interchangeable here.
function sRGBtoY(rgb) {
const s = c => Math.pow(c / 255.0, MAIN_TRC);
return R_CO * s(rgb[0]) + G_CO * s(rgb[1]) + B_CO * s(rgb[2]);
}
// Signed: positive is dark text on light, negative is light text on dark. The sign
// carries the polarity, and polarity is not cosmetic — the same luminance pair reads
// differently each way round, which is the whole reason this exists.
function contrast(txtY, bgY) {
txtY = txtY > BLK_THRS ? txtY : txtY + Math.pow(BLK_THRS - txtY, BLK_CLMP);
bgY = bgY > BLK_THRS ? bgY : bgY + Math.pow(BLK_THRS - bgY, BLK_CLMP);
if (Math.abs(bgY - txtY) < DELTA_Y_MIN) return 0.0;
let sapc, out;
if (bgY > txtY) {
sapc = (Math.pow(bgY, NORM_BG) - Math.pow(txtY, NORM_TXT)) * SCALE_BOW;
out = sapc < LO_CLIP ? 0.0 : sapc - LO_BOW_OFFSET;
} else {
sapc = (Math.pow(bgY, REV_BG) - Math.pow(txtY, REV_TXT)) * SCALE_WOB;
out = sapc > -LO_CLIP ? 0.0 : sapc + LO_WOB_OFFSET;
}
return out * 100;
}
function lc(textRgb, bgRgb) {
return contrast(sRGBtoY(textRgb), sRGBtoY(bgRgb));
}
// How much contrast this text needs, from the published APCA levels:
//
// Lc 90 fluent body text; and the floor for anything at 14px/400 or 12px/400
// Lc 75 the minimum for a column of body text (18px/400, 16px/500, 14px/700)
// Lc 60 the minimum for content text that isn't a column or block
// Lc 45 larger, heavier text — headlines at 36px/400 or 24px/700
// Lc 30 the absolute floor, and only for genuinely spot-read text
//
// Interpolating between those anchors rather than inventing a curve. Weight is folded
// in as an effective size because that is how the published table behaves: bolder
// strokes buy roughly the same readability as bigger ones, and 14px/700 sitting at the
// same Lc 75 as 18px/400 is the anchor that fixes the exchange rate.
function requiredLc(px, weight = 400) {
const heavier = Math.max(0, (Number(weight) || 400) - 400) / 300; // 400..700 -> 0..1
const effective = px * (1 + 0.28 * heavier); // 14px/700 ~= 18px/400
const anchors = [
[12, 90],
[14, 90],
[15, 82],
[18, 75],
[24, 60],
[36, 45],
];
if (effective <= anchors[0][0]) return anchors[0][1];
const last = anchors[anchors.length - 1];
if (effective >= last[0]) return last[1];
for (let i = 1; i < anchors.length; i++) {
const [x0, y0] = anchors[i - 1];
const [x1, y1] = anchors[i];
if (effective <= x1) {
const t = (effective - x0) / (x1 - x0);
return y0 + t * (y1 - y0);
}
}
return last[1];
}
module.exports = { sRGBtoY, contrast, lc, requiredLc };
+141
View File
@@ -0,0 +1,141 @@
// The contrast arithmetic, checked against the numbers its authors publish.
//
// A contrast checker that is wrong is worse than not having one, because it launders a
// guess into a number and then a stylesheet gets tuned to it. The eight pairs below are
// the reference values published with APCA 0.98G-4g; if the implementation drifts from
// them by so much as a rounding change, these fail and nothing downstream is believed.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const { lc, contrast, sRGBtoY, requiredLc } = require("./apca");
const hex = h => {
h = h.replace("#", "");
if (h.length === 3) h = h.split("").map(c => c + c).join("");
return [0, 2, 4].map(i => parseInt(h.slice(i, i + 2), 16));
};
describe("the published reference pairs", () => {
// Text first, background second, exactly as the reference table lists them.
const CASES = [
["#888", "#fff", 63.056469930209424],
["#fff", "#888", -68.54146436644962],
["#000", "#aaa", 58.146262578561334],
["#aaa", "#000", -56.24113336839742],
["#123", "#def", 91.66830811481631],
["#def", "#123", -93.06770049484275],
["#123", "#444", 8.32326136957393],
["#444", "#123", -7.526878460278154],
];
CASES.forEach(([text, bg, expected]) => {
test(`${text} on ${bg} is Lc ${expected.toFixed(2)}`, () => {
assert.ok(Math.abs(lc(hex(text), hex(bg)) - expected) < 1e-9,
`got ${lc(hex(text), hex(bg))}, want ${expected}`);
});
});
});
describe("polarity", () => {
test("is signed, and the sign is not decoration", () => {
// Dark text on light is positive, light text on dark negative. The two are not
// mirror images — swapping them changes the magnitude as well as the sign,
// which is the entire reason this is used instead of a ratio.
const dark = lc(hex("#888"), hex("#fff"));
const light = lc(hex("#fff"), hex("#888"));
assert.ok(dark > 0 && light < 0);
assert.ok(Math.abs(Math.abs(dark) - Math.abs(light)) > 5,
"the same pair reads differently each way round");
});
test("a colour on itself is nothing at all", () => {
assert.equal(lc(hex("#2c2c2c"), hex("#2c2c2c")), 0);
});
test("and so is a difference too small to see", () => {
// Below deltaYmin the answer is zero rather than a tiny number, so a rounding
// artefact can never be reported as contrast.
assert.equal(lc([44, 44, 44], [44, 44, 45]), 0);
});
});
describe("luminance", () => {
test("is the straight 2.4 power, not the sRGB piecewise curve", () => {
// Worth pinning: the two are close enough to look right and different enough to
// move a borderline reading. Mid grey under the piecewise curve is ~0.2159.
assert.ok(Math.abs(sRGBtoY([128, 128, 128]) - Math.pow(128 / 255, 2.4)) < 1e-6);
});
test("white is as close to 1 as the published coefficients get", () => {
// 1.0000001, not 1. The three coefficients are given to seven places and sum to
// a hair over one, and that is the specification rather than a mistake to
// correct — the reference pairs above only come out exact with these values.
// Asserted loosely on purpose: tightening this to 1e-12 fails on correct code.
assert.ok(Math.abs(sRGBtoY([255, 255, 255]) - 1) < 1e-6);
assert.equal(sRGBtoY([0, 0, 0]), 0);
});
test("green carries most of it", () => {
// Not arbitrary: it's why gold on green was the worst pairing on the felt.
assert.ok(sRGBtoY([0, 255, 0]) > sRGBtoY([255, 0, 0]) + sRGBtoY([0, 0, 255]));
});
test("contrast() takes luminances, lc() takes colours", () => {
assert.equal(contrast(sRGBtoY(hex("#888")), sRGBtoY(hex("#fff"))), lc(hex("#888"), hex("#fff")));
});
});
describe("how much contrast a given piece of text needs", () => {
test("the published anchors land where they should", () => {
assert.equal(Math.round(requiredLc(12, 400)), 90);
assert.equal(Math.round(requiredLc(14, 400)), 90);
assert.equal(Math.round(requiredLc(18, 400)), 75);
assert.equal(Math.round(requiredLc(24, 400)), 60);
assert.equal(Math.round(requiredLc(36, 400)), 45);
});
test("smaller text asks for more, never less", () => {
for (let px = 9; px < 40; px++) {
assert.ok(requiredLc(px, 400) >= requiredLc(px + 1, 400),
`${px}px should ask for at least as much as ${px + 1}px`);
}
});
test("weight buys size, at the rate the published table sets", () => {
// 14px/700 and 18px/400 sit at the same Lc 75 in the table, and that pair is
// what fixes the exchange rate between weight and size here.
assert.ok(Math.abs(requiredLc(14, 700) - requiredLc(18, 400)) < 3);
assert.ok(requiredLc(14, 700) < requiredLc(14, 400), "bold asks for less than regular");
});
test("it never runs off either end", () => {
assert.equal(requiredLc(4, 400), 90);
assert.equal(requiredLc(200, 900), 45);
});
});
describe("what the page's own colours measure", () => {
// These are the readings the round was built on. Pinned so that a future change to
// the tokens has to look at them rather than move them by accident.
const PANEL = hex("#1a1a1a");
test("the greys these tokens replaced were below the floor", () => {
assert.ok(Math.abs(lc(hex("#9a9a9a"), PANEL)) < 50, "the old muted grey");
assert.ok(Math.abs(lc(hex("#8a8a8a"), PANEL)) < 40, "the old dim grey");
});
test("and the ones that replaced them clear it", () => {
assert.ok(Math.abs(lc(hex("#c8c8c8"), PANEL)) >= 60, "muted");
assert.ok(Math.abs(lc(hex("#b4b4b4"), PANEL)) >= 58, "dim");
});
test("the three tiers are still three tiers", () => {
// The worry with lifting muted and dim is that they collapse into --text and the
// page flattens. They don't: the spread is wider than it was.
const text = Math.abs(lc(hex("#eeeeee"), PANEL));
const muted = Math.abs(lc(hex("#c8c8c8"), PANEL));
const dim = Math.abs(lc(hex("#b4b4b4"), PANEL));
assert.ok(text > muted && muted > dim, "still ordered");
assert.ok(text - dim > 30, "and still a real spread");
});
});
+100
View File
@@ -0,0 +1,100 @@
// Just enough PNG to read pixels back out of a screenshot.
//
// The contrast audit needs to know what colour is actually behind a piece of text, and
// the only honest answer is the one the browser painted. Walking the DOM and
// compositing `background-color` up the ancestors gets it wrong wherever a gradient,
// a shadow or a border is doing the painting: tried that first, and it reported the
// gold dealer button as black-on-black at Lc 0.4 — a fault that does not exist, on an
// element anyone can see is legible. Sampling the screenshot cannot make that mistake.
//
// zlib is in Node, so this needs no dependency. Screenshots are 8-bit and
// non-interlaced; anything else throws rather than returning quietly wrong pixels.
const zlib = require("node:zlib");
const SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
function paeth(a, b, c) {
const p = a + b - c;
const pa = Math.abs(p - a), pb = Math.abs(p - b), pc = Math.abs(p - c);
if (pa <= pb && pa <= pc) return a;
return pb <= pc ? b : c;
}
function decode(buffer) {
if (!buffer.subarray(0, 8).equals(SIGNATURE)) throw new Error("not a PNG");
let width = 0, height = 0, depth = 0, colorType = 0, interlace = 0;
const idat = [];
let at = 8;
while (at < buffer.length) {
const length = buffer.readUInt32BE(at);
const type = buffer.toString("ascii", at + 4, at + 8);
const data = buffer.subarray(at + 8, at + 8 + length);
at += 12 + length;
if (type === "IHDR") {
width = data.readUInt32BE(0);
height = data.readUInt32BE(4);
depth = data[8];
colorType = data[9];
interlace = data[12];
} else if (type === "IDAT") {
idat.push(data);
} else if (type === "IEND") {
break;
}
}
if (depth !== 8) throw new Error(`unsupported bit depth ${depth}`);
if (interlace !== 0) throw new Error("interlaced PNG not supported");
if (colorType !== 2 && colorType !== 6) throw new Error(`unsupported colour type ${colorType}`);
const channels = colorType === 6 ? 4 : 3;
const raw = zlib.inflateSync(Buffer.concat(idat));
const stride = width * channels;
const out = Buffer.alloc(width * height * 4);
let prior = Buffer.alloc(stride);
for (let y = 0; y < height; y++) {
const filter = raw[y * (stride + 1)];
const line = Buffer.from(raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1)));
for (let i = 0; i < stride; i++) {
const left = i >= channels ? line[i - channels] : 0;
const up = prior[i];
const upLeft = i >= channels ? prior[i - channels] : 0;
switch (filter) {
case 0: break;
case 1: line[i] = (line[i] + left) & 0xff; break;
case 2: line[i] = (line[i] + up) & 0xff; break;
case 3: line[i] = (line[i] + ((left + up) >> 1)) & 0xff; break;
case 4: line[i] = (line[i] + paeth(left, up, upLeft)) & 0xff; break;
default: throw new Error(`unknown filter ${filter} on row ${y}`);
}
}
for (let x = 0; x < width; x++) {
const from = x * channels;
const to = (y * width + x) * 4;
out[to] = line[from];
out[to + 1] = line[from + 1];
out[to + 2] = line[from + 2];
out[to + 3] = channels === 4 ? line[from + 3] : 255;
}
prior = line;
}
return { width, height, data: out };
}
// Nearest pixel, clamped. A rect can sit a hair outside the shot after rounding, and
// clamping is the right answer there rather than an exception or a black pixel.
function pixelAt(image, x, y) {
const px = Math.min(image.width - 1, Math.max(0, Math.round(x)));
const py = Math.min(image.height - 1, Math.max(0, Math.round(y)));
const at = (py * image.width + px) * 4;
return [image.data[at], image.data[at + 1], image.data[at + 2]];
}
module.exports = { decode, pixelAt };
+178
View File
@@ -0,0 +1,178 @@
// The screenshot reader, tested by building PNGs whose pixels are already known.
//
// This matters more than it looks. If a filter is decoded wrong the pixels are still
// plausible colours — slightly off greys and greens, not obvious garbage — and the
// contrast audit would report confident, wrong numbers about a page nobody would think
// to re-check. So every filter type gets encoded here and read back.
const test = require("node:test");
const { describe } = require("node:test");
const assert = require("node:assert");
const zlib = require("node:zlib");
const { decode, pixelAt } = require("./png");
const CRC_TABLE = (() => {
const table = new Int32Array(256);
for (let n = 0; n < 256; n++) {
let c = n;
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
table[n] = c;
}
return table;
})();
function crc32(buf) {
let c = 0xffffffff;
for (const b of buf) c = CRC_TABLE[(c ^ b) & 0xff] ^ (c >>> 8);
return (c ^ 0xffffffff) >>> 0;
}
function chunk(type, data) {
const head = Buffer.alloc(8);
head.writeUInt32BE(data.length, 0);
head.write(type, 4, "ascii");
const crc = Buffer.alloc(4);
crc.writeUInt32BE(crc32(Buffer.concat([Buffer.from(type, "ascii"), data])), 0);
return Buffer.concat([head, data, crc]);
}
function paeth(a, b, c) {
const p = a + b - c;
const pa = Math.abs(p - a), pb = Math.abs(p - b), pc = Math.abs(p - c);
if (pa <= pb && pa <= pc) return a;
return pb <= pc ? b : c;
}
// pixels: [y][x] = [r,g,b(,a)]. filter is applied to every row, which is legal PNG and
// is exactly how each decoder branch gets exercised.
function encode(pixels, filter = 0, channels = 4) {
const height = pixels.length, width = pixels[0].length;
const stride = width * channels;
const rows = [];
let prior = Buffer.alloc(stride);
for (let y = 0; y < height; y++) {
const raw = Buffer.alloc(stride);
for (let x = 0; x < width; x++) {
for (let c = 0; c < channels; c++) {
raw[x * channels + c] = pixels[y][x][c] !== undefined ? pixels[y][x][c] : 255;
}
}
const filtered = Buffer.alloc(stride);
for (let i = 0; i < stride; i++) {
const left = i >= channels ? raw[i - channels] : 0;
const up = prior[i];
const upLeft = i >= channels ? prior[i - channels] : 0;
switch (filter) {
case 0: filtered[i] = raw[i]; break;
case 1: filtered[i] = (raw[i] - left) & 0xff; break;
case 2: filtered[i] = (raw[i] - up) & 0xff; break;
case 3: filtered[i] = (raw[i] - ((left + up) >> 1)) & 0xff; break;
case 4: filtered[i] = (raw[i] - paeth(left, up, upLeft)) & 0xff; break;
default: throw new Error("bad filter");
}
}
rows.push(Buffer.concat([Buffer.from([filter]), filtered]));
prior = raw;
}
const ihdr = Buffer.alloc(13);
ihdr.writeUInt32BE(width, 0);
ihdr.writeUInt32BE(height, 4);
ihdr[8] = 8;
ihdr[9] = channels === 4 ? 6 : 2;
return Buffer.concat([
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
chunk("IHDR", ihdr),
chunk("IDAT", zlib.deflateSync(Buffer.concat(rows))),
chunk("IEND", Buffer.alloc(0)),
]);
}
// Deliberately awkward: neighbouring values that differ, so a filter decoded with the
// wrong neighbour produces a different answer rather than the same one by luck.
const PIXELS = [
[[20, 30, 40], [200, 10, 90], [18, 18, 18], [255, 255, 255]],
[[0, 0, 0], [28, 108, 60], [108, 68, 39], [1, 2, 3]],
[[240, 217, 168], [47, 122, 77], [200, 200, 200], [17, 17, 17]],
];
describe("every filter type reads back exactly", () => {
[0, 1, 2, 3, 4].forEach(filter => {
test(`filter ${filter}`, () => {
const image = decode(encode(PIXELS, filter));
assert.equal(image.width, 4);
assert.equal(image.height, 3);
for (let y = 0; y < PIXELS.length; y++) {
for (let x = 0; x < PIXELS[y].length; x++) {
assert.deepEqual(pixelAt(image, x, y), PIXELS[y][x],
`pixel ${x},${y} under filter ${filter}`);
}
}
});
});
test("and a three-channel image reads back too", () => {
const image = decode(encode(PIXELS, 4, 3));
assert.deepEqual(pixelAt(image, 1, 2), [47, 122, 77]);
});
test("including where Paeth has to choose between close neighbours", () => {
// Written first to catch paeth(left, up, ...) decoded as paeth(up, left, ...),
// on the assumption that the two differ on a tie. They don't, anywhere: the
// predictor is symmetric in its first two arguments, checked over all 16,777,216
// byte triples. The reason is that a tie between pa and pb requires
// left + up == 2 * upLeft, and that is exactly the condition making pc zero — so
// every tie is resolved by returning upLeft, whichever order the other two
// arrived in. Swapping them is a no-op and no test can catch it, which is worth
// knowing rather than papering over with a fixture that appears to.
//
// What this does catch is the mistake that is actually available: reading the
// wrong neighbour. The values sit close together so a predictor that reaches one
// pixel off produces a different answer rather than the same one by luck.
const CLOSE = [
[[100, 10, 20], [110, 40, 25]],
[[90, 70, 30], [55, 95, 35]],
];
const image = decode(encode(CLOSE, 4));
assert.deepEqual(pixelAt(image, 1, 1), [55, 95, 35]);
assert.deepEqual(pixelAt(image, 0, 1), [90, 70, 30]);
assert.deepEqual(pixelAt(image, 1, 0), [110, 40, 25]);
});
});
describe("sampling", () => {
const image = decode(encode(PIXELS, 0));
test("rounds to the nearest pixel", () => {
assert.deepEqual(pixelAt(image, 0.4, 0.4), [20, 30, 40]);
assert.deepEqual(pixelAt(image, 0.6, 0.4), [200, 10, 90]);
});
test("clamps rather than throwing or reading black", () => {
// A rect can sit a hair outside the shot once it's been rounded, and a silent
// black pixel there would read as a contrast failure that isn't one.
assert.deepEqual(pixelAt(image, -5, -5), [20, 30, 40]);
assert.deepEqual(pixelAt(image, 999, 999), [17, 17, 17]);
});
});
describe("what it refuses", () => {
test("something that isn't a PNG at all", () => {
assert.throws(() => decode(Buffer.from("not a png at all, honestly")), /not a PNG/);
});
test("an interlaced one, rather than returning scrambled pixels", () => {
const png = encode(PIXELS, 0);
// Byte 12 of the IHDR data: 8 signature + 8 chunk header + 12 = interlace flag.
const broken = Buffer.from(png);
broken[8 + 8 + 12] = 1;
assert.throws(() => decode(broken), /interlaced/);
});
test("a colour type it cannot read", () => {
const broken = Buffer.from(encode(PIXELS, 0));
broken[8 + 8 + 9] = 3; // palette
assert.throws(() => decode(broken), /colour type/);
});
});
+287
View File
@@ -0,0 +1,287 @@
// Reads every piece of text on the dealer's page and asks whether it can actually be
// read, at the size and weight it is actually drawn.
//
// node tests/holdem/runContrastAudit.js [baseUrl]
//
// Needs Playwright and a running site, like runUiAudit.js, and is deliberately kept
// out of the unit suite for the same reason.
//
// Why this exists next to the contrast check already in uiAudit.js: that one measures
// WCAG 2 contrast ratio and the page passes it. WCAG 2's ratio is a luminance gap, and
// a luminance gap overstates readability once one colour is near black — which is
// every reading taken on a page whose background is #141414. APCA asks the question
// the ratio can't. Both numbers are reported, because "passes AA, fails APCA" is the
// interesting row and hiding either number would hide it.
//
// How the background is obtained matters more than the arithmetic. The first version
// walked the DOM compositing `background-color` up the ancestors, and reported the gold
// dealer button as black text on a black background at Lc 0.4 — a fault that does not
// exist on an element anyone can see is legible, because a gradient was doing the
// painting and `background-color` knew nothing about it. So: paint the page with its
// text made transparent, screenshot it, and read the background out of the pixels. The
// text's own client rects come from a Range, not the element box, so a label inside a
// wide row is sampled where the glyphs are rather than wherever the row happens to end.
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const { lc, requiredLc } = require("./apca");
const { decode, pixelAt } = require("./png");
const BASE = process.argv[2] || "http://localhost:5199";
const VIEWPORTS = [
[390, 844, "iPhone 14"],
[768, 1024, "iPad"],
[1280, 900, "desktop"],
];
// WCAG 2 relative luminance — the piecewise curve, which is not the one APCA uses.
function wcagLuminance([r, g, b]) {
const f = c => {
c /= 255;
return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
};
return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b);
}
function wcagRatio(fg, bg) {
const a = wcagLuminance(fg), b = wcagLuminance(bg);
return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
}
function seedTable() {
const state = HoldemState.createDefault();
HoldemState.resizeSeats(state, 9);
[["Christopher", 1200], ["Mike from work", 800], ["Alexandra", 1500],
["Bob", 250], ["Dee", 600]].forEach(([name, cash], i) => {
state.seats[i].name = name;
state.seats[i].inHand = true;
state.seats[i].buyIns = cash;
state.seats[i].stack = cash;
});
state.smallBlind = 5;
state.bigBlind = 10;
state.handNumber = 5;
state.handHistory.push({
handNumber: 4, timestamp: Date.now(), pot: 120,
payouts: [{ id: state.seats[0].id, label: "Christopher", amount: 120 }],
ledger: state.seats.slice(0, 5).map(p => ({ id: p.id, name: p.name, in: 30, won: 0 })),
});
HoldemState.save(state);
}
// Every text node that is actually painted, with the rect its glyphs occupy.
function collectText() {
const out = [];
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
let node;
while ((node = walker.nextNode())) {
const text = node.textContent.trim();
if (!text) continue;
const el = node.parentElement;
if (!el || el.closest("[hidden]")) continue;
const cs = getComputedStyle(el);
if (cs.visibility === "hidden" || cs.display === "none") continue;
// Anything faded is faded onto what is behind it, and the screenshot already
// shows that — but fully transparent text is not text.
let opacity = 1;
for (let n = el; n && n.nodeType === 1; n = n.parentElement) {
opacity *= parseFloat(getComputedStyle(n).opacity);
}
if (opacity < 0.05) continue;
const range = document.createRange();
range.selectNodeContents(node);
const rects = [...range.getClientRects()].filter(r => r.width > 1 && r.height > 1);
if (!rects.length) continue;
const r = rects[0];
if (r.bottom < 0 || r.top > innerHeight || r.right < 0 || r.left > innerWidth) continue;
const m = cs.color.match(/[\d.]+/g);
if (!m) continue;
out.push({
text: text.slice(0, 40),
color: [+m[0], +m[1], +m[2]],
alpha: m[3] !== undefined ? +m[3] : 1,
opacity,
px: parseFloat(cs.fontSize),
weight: +cs.fontWeight || 400,
cls: (el.className && el.className.toString().trim().split(/\s+/)[0]) || el.tagName.toLowerCase(),
tag: el.tagName.toLowerCase(),
disabled: !!el.closest(":disabled, [disabled], [aria-disabled='true']"),
// Sample points along the glyph run, avoiding the very edges where a
// border or the next box over would be sampled instead.
points: [0.25, 0.5, 0.75].map(t => [r.left + r.width * t, r.top + r.height / 2]),
});
}
return out;
}
const HIDE_TEXT = `*, *::before, *::after {
color: transparent !important;
text-shadow: none !important;
-webkit-text-stroke-color: transparent !important;
caret-color: transparent !important;
}`;
async function main() {
let chromium;
try {
({ chromium } = require("playwright"));
} catch {
console.error("This script needs Playwright: npm i -D playwright && npx playwright install chromium");
process.exit(2);
}
const shotDir = fs.mkdtempSync(path.join(os.tmpdir(), "holdem-contrast-"));
const browser = await chromium.launch();
const context = await browser.newContext({ deviceScaleFactor: 1 });
const page = await context.newPage();
const rows = [];
for (const [width, height, label] of VIEWPORTS) {
await page.setViewportSize({ width, height });
await page.goto(`${BASE}/casino/texasholdem`);
await page.evaluate(seedTable);
await page.goto(`${BASE}/casino/texasholdem`);
await page.click("#nextHandBtn");
await page.waitForTimeout(300);
await page.evaluate(() => {
const deal = [...document.querySelectorAll("#actionBar button")]
.find(b => /post blinds/i.test(b.textContent));
if (deal) deal.click();
});
await page.waitForTimeout(250);
// Open every panel, or the sidebar's hint text — the smallest, faintest text on
// the page, and so the most likely to be the thing worth finding — is never
// measured at all.
await page.evaluate(() => {
document.querySelectorAll("details").forEach(d => { d.open = true; });
});
await page.waitForTimeout(200);
const items = await page.evaluate(collectText);
const shot = path.join(shotDir, `${width}x${height}.png`);
await page.addStyleTag({ content: HIDE_TEXT });
await page.waitForTimeout(120);
await page.screenshot({ path: shot });
// Undo, so the next viewport starts from a page that still has its text.
await page.evaluate(() => {
const tags = [...document.querySelectorAll("style")];
const injected = tags[tags.length - 1];
if (injected && injected.textContent.includes("caret-color: transparent")) injected.remove();
});
const image = decode(fs.readFileSync(shot));
for (const item of items) {
// Most common sampled colour along the run: a median would invent a colour
// that is on no pixel, and the mode lands on the flat background wherever
// there is one.
const tally = new Map();
for (const [x, y] of item.points) {
const key = pixelAt(image, x, y).join(",");
tally.set(key, (tally.get(key) || 0) + 1);
}
const bg = [...tally.entries()].sort((a, b) => b[1] - a[1])[0][0]
.split(",").map(Number);
// The text's painted colour: its own alpha, and any inherited opacity, both
// land it on the background behind it.
const a = item.alpha * item.opacity;
const fg = item.color.map((c, i) => c * a + bg[i] * (1 - a));
const measured = Math.abs(lc(fg, bg));
const needed = requiredLc(item.px, item.weight);
rows.push({
viewport: label,
...item,
bg, fg: fg.map(Math.round),
lc: +measured.toFixed(1),
need: +needed.toFixed(0),
short: +(needed - measured).toFixed(1),
wcag: +wcagRatio(fg, bg).toFixed(2),
});
}
}
await browser.close();
fs.rmSync(shotDir, { recursive: true, force: true });
// One row per distinct piece of text, worst viewport kept.
const byKey = new Map();
for (const row of rows) {
const key = `${row.cls}|${row.px}|${row.weight}|${row.text}`;
const prev = byKey.get(key);
if (!prev || row.short > prev.short) byKey.set(key, row);
}
const all = [...byKey.values()].sort((a, b) => b.short - a.short);
const live = all.filter(r => !r.disabled);
const failing = live.filter(r => r.short > 0);
const passesAaFailsApca = failing.filter(r => r.wcag >= 4.5);
// Two numbers, because they answer different questions and only one of them is a
// target anyone can hit here.
//
// The strict count is every piece of text below the published level for the size and
// weight it is drawn at. APCA asks Lc 90 of anything at 12px/400 or below, and this
// page is full of 10px and 11px labels that live inside a 58px seat puck. Reaching
// Lc 90 there means white on black for micro-labels and a flat, shoutier page; the
// honest way to clear it is bigger type, and bigger type is a layout change that
// belongs to its own round. So the strict count is reported and not chased.
//
// The floors are what this page holds itself to: nothing below Lc 60, which is the
// published minimum for content text that is not a column, and Lc 75 for a column of
// body text. Those are checkable and they are the numbers that moved.
const FLOOR = 60, BODY_FLOOR = 75;
const belowFloor = live.filter(r => r.lc < FLOOR);
const belowBody = live.filter(r => r.lc < BODY_FLOOR);
const aaFails = live.filter(r => r.wcag < 4.5);
const worst = live.reduce((min, r) => Math.min(min, r.lc), Infinity);
console.log(`${rows.length} readings, ${all.length} distinct pieces of text`);
console.log(`worst contrast anywhere on the page: Lc ${worst.toFixed(1)}`);
console.log(`below the Lc ${FLOOR} floor: ${belowFloor.length}`);
console.log(`below Lc ${BODY_FLOOR}: ${belowBody.length}`);
console.log(`still failing WCAG AA 4.5:1: ${aaFails.length}`);
console.log(`below the strict APCA level for their size/weight: ${failing.length}`
+ ` (${passesAaFailsApca.length} of them pass AA)\n`);
if (belowFloor.length) {
console.log(`=== below the Lc ${FLOOR} floor ===`);
belowFloor.sort((a, b) => a.lc - b.lc).forEach(r =>
console.log(` Lc ${String(r.lc).padStart(5)} ${r.px}px/${r.weight} ${r.cls} "${r.text}"`));
console.log("");
}
if (aaFails.length) {
console.log("=== still failing WCAG AA ===");
aaFails.sort((a, b) => a.wcag - b.wcag).forEach(r =>
console.log(` ${String(r.wcag).padStart(5)}:1 ${r.px}px/${r.weight} ${r.cls} "${r.text}"`));
console.log("");
}
const show = r => ` Lc ${String(r.lc).padStart(5)} (needs ${String(r.need).padStart(2)},`
+ ` short ${String(r.short).padStart(5)}) WCAG ${String(r.wcag).padStart(5)}:1`
+ ` ${r.px}px/${r.weight} ${r.cls.padEnd(22)} rgb(${r.fg.join(",")}) on rgb(${r.bg.join(",")})`
+ ` "${r.text}"`;
console.log("=== worst 30 ===");
failing.slice(0, 30).forEach(r => console.log(show(r)));
const byClass = new Map();
failing.forEach(r => {
const cur = byClass.get(r.cls);
if (!cur || r.short > cur.short) byClass.set(r.cls, r);
});
console.log(`\n=== ${byClass.size} distinct classes below level ===`);
[...byClass.values()].sort((a, b) => b.short - a.short)
.forEach(r => console.log(` ${String(r.short).padStart(5)} short ${r.px}px/${r.weight} ${r.cls}`));
}
main().catch(err => { console.error(err); process.exit(1); });
+17
View File
@@ -652,6 +652,23 @@ const LayoutAudit = {
};
},
// Two things this check cannot do, both found by measuring against real pixels in
// runContrastAudit.js and neither of them fixable from inside a DOM walk:
//
// 1. It reads `background-color`, so anything painted by a gradient is invisible to
// it. The chair number on an empty seat sat on the felt's brown rim at 2.65:1 and
// the pot's label on green at 2.66:1 — two plain AA failures this reported clean,
// for years, because it never saw either background.
// 2. Where an element has several candidate ancestors it takes the best contrast of
// any of them ("the kindest reading available", below). That is the right instinct
// for a fade, and it is what let (1) through: the flattering candidate was the
// dark page behind the felt, which is not what the text is sitting on.
//
// Both are why the sibling audit screenshots the page with its text made transparent
// and samples the pixels instead. This one is kept because AA is the number an
// accessibility audit will ask for, and because it runs against a live DOM with no
// screenshot to decode — but a clean result here is not a claim that the page is
// readable. That claim belongs to the APCA sweep.
contrast({ minimum = 4.5, largeMinimum = 3, selector = null } = {}) {
const offenders = [];
const unmeasured = [];