TinyColor icon indicating copy to clipboard operation
TinyColor copied to clipboard

setAlpha() maps negative values to fully opaque instead of clamping to 0

Open philppplik opened this issue 1 month ago • 0 comments

Summary

setAlpha() (and alpha values parsed from strings like rgba(..., -0.5)) treat any out-of-range value the same: boundAlpha() resets them all to 1. For values above 1 that is fine, but for negative values it means "less transparent than 0" silently becomes "fully opaque", which is the opposite end of the range.

CSS clamps negative alpha to 0, so the current behavior is surprising when computed values are passed in.

Reproduction

const tinycolor = require('tinycolor2');

tinycolor('#ffffff').setAlpha(0.5).toRgbString();
// "rgba(255, 255, 255, 0.5)"  OK

tinycolor('#ffffff').setAlpha(2).toRgbString();
// "rgb(255, 255, 255)"  OK, clamped to 1

tinycolor('#ffffff').setAlpha(-0.5).toRgbString();
// "rgb(255, 255, 255)"  alpha became 1 (fully opaque), expected rgba(255, 255, 255, 0)

tinycolor('#ffffff').setAlpha(-0.5).getAlpha();
// 1  expected 0

Expected behavior

Negative alpha values clamp to 0 (fully transparent), matching CSS:

tinycolor('#ffffff').setAlpha(-0.5).toRgbString();
// "rgba(255, 255, 255, 0)"

Cause

function boundAlpha(a) {
  a = parseFloat(a);
  if (isNaN(a) || a < 0 || a > 1) {
    a = 1;   // negative values land here and become fully opaque
  }
  return a;
}

Splitting the cases (a < 0 -> 0, a > 1 -> 1, NaN -> 1 to keep backwards compatibility) would fix it.

Environment

  • tinycolor2 1.6.0
  • Node.js v22.23.3

philppplik avatar Oct 17 '26 04:10 philppplik