Skip to content

fix(hex2rgb): preserve full alpha precision when parsing hex colors - #392

Open
spokodev wants to merge 2 commits into
gka:mainfrom
spokodev:fix-hex-alpha-precision
Open

fix(hex2rgb): preserve full alpha precision when parsing hex colors#392
spokodev wants to merge 2 commits into
gka:mainfrom
spokodev:fix-hex-alpha-precision

Conversation

@spokodev

Copy link
Copy Markdown

When parsing #rrggbbaa / #rgba colors, hex2rgb rounds the alpha channel to two decimals:

// src/io/hex/hex2rgb.js
const a = Math.round(((u & 0xff) / 0xff) * 100) / 100;

The RGB channels are parsed exactly (& 0xff), so only alpha is degraded. As a result alpha bytes do not round-trip and the channels disagree:

chroma("#ff000088").alpha()  // 0.53, exact is 136/255 = 0.5333…
chroma("#ff000088").hex()    // "#ff000087", expected "#ff000088"

136 of 256 alpha bytes fail to round-trip. CSS Color 4 §5.2 defines the hex alpha as aa / 255 exactly.

The fix parses alpha as the exact (u & 0xff) / 0xff, matching how the RGB channels are handled. As a side effect it also aligns the APCA contrast of colors with alpha with the values the contrast test already noted in comments (// 36.7, // -68.6), so that todo is removed. The hex2rgb, alpha, and contrast fixtures that encoded the rounded values are updated. Full suite passes (2519).

hex2rgb rounded the parsed alpha of #rrggbbaa / #rgba colors to two
decimals, so alpha bytes did not round-trip and the (exactly parsed)
RGB channels disagreed with alpha:

    chroma('#ff000088').alpha()  // 0.53, exact is 136/255 = 0.5333…
    chroma('#ff000088').hex()    // '#ff000087', not '#ff000088'

Parse alpha as the exact byte / 255, matching the RGB channels. This also
brings the APCA contrast of colors with alpha in line with the APCA demo
values the test already noted (36.7, -68.6), so that todo is resolved.
Updated the hex2rgb / alpha / contrast fixtures that encoded the rounded
values; full suite green (2519).
@spokodev
spokodev requested a review from gka as a code owner June 22, 2026 18:24
@changeset-bot

changeset-bot Bot commented Jun 22, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: eb4d107

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
chroma-js Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant