Skip to content

fix(oklab, oklch, gl): default alpha to 1 when it is omitted - #404

Open
abhu85 wants to merge 1 commit into
gka:mainfrom
abhu85:fix/opaque-alpha-without-channel
Open

abhu85 wants to merge 1 commit into
gka:mainfrom
abhu85:fix/opaque-alpha-without-channel

Conversation

@abhu85

@abhu85 abhu85 commented Sep 30, 2026

Copy link
Copy Markdown

Colors built through the oklab, oklch or gl constructors without an explicit alpha end up with an alpha of NaN:

chroma.oklch(0.5, 0.1, 20).alpha()       // NaN
chroma.oklch(0.5, 0.1, 20).hex('rgba')   // '#944a4baN'
chroma.mix(chroma.oklch(0.5, 0.1, 20), 'red')
// on main, since #399: Error: invalid rgb color

oklab2rgb and oklch2rgb (like the gl input) return only [r, g, b] for opaque colors. clip_rgb then always clamped index 3, which turned the missing value into NaN before the Color constructor could default it to 1. The if (me._rgb.length === 3) me._rgb.push(1) fallback therefore never ran for these inputs.

This PR makes clip_rgb clamp alpha only when it is present, so the constructor's default applies. The other clip_rgb callers (average, cubehelix) always pass four values and are unaffected, and _unclipped is copied before the loop, so it is unchanged.

Tests: added two cases to test/alpha.test.js for the alpha default and for mixing/scaling such a color; both fail without the change. Full vitest suite: 2534 passing. A changeset is included.

`oklab2rgb` and `oklch2rgb` (like the `gl` input) return no alpha
channel for opaque colors, but `clip_rgb` always clamped index 3, turning
the missing value into `NaN` before the constructor could default it to
1. `chroma.oklch(0.5, 0.1, 20).alpha()` returned `NaN` and
`.hex('rgba')` returned `#944a4baN`; since gka#399, mixing or scaling such
a color throws `invalid rgb color`.

Only clamp alpha when it is present.
@changeset-bot

changeset-bot Bot commented Sep 30, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 64a8897

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

@abhu85
abhu85 requested a review from gka as a code owner September 30, 2026 16:49

This branch has not been deployed

No deployments
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