gka / chroma.js

JavaScript library for all kinds of color manipulations
https://vis4.net/chromajs/
Other
9.94k stars 543 forks source link

Unhandled error with a decimal gamma value and input out of domain #331

Open tibotiber opened 4 months ago

tibotiber commented 4 months ago

Hello,

Before starting, let me say I love this library and have been relying on it for years. I'm even singing its praise in our own developer documentation: https://docs.smplrspace.com/api-reference/color/overview#a-little-context ;). So THANK YOU!

I've just come across what I think is a bug. If I use a scale with a decimal gamma value and pass it an out of domain input. It's crashing.

Code:

console.log(chroma.scale('YlGn').domain([5, 15]).gamma(1.2)(4).hex())

Error:

Uncaught Error: unknown format: 
    at new Color2 (chroma-js.js?v=8a5f8334:121:17)
    at chroma (chroma-js.js?v=8a5f8334:138:16)
    at f (chroma-js.js?v=8a5f8334:1998:19)

Happy to provide any additional details, testing, or help on a PR if given pointers of where to handle this.

Take care!

PS: this can be easily handled in userland by clamping the value before passing it in, so not a really bad one.

regorxxx commented 4 months ago

Your code doesn't really make sense, since you are trying to map a value of 4 in a scale which goes from 5 to 15. Test the same with a value of 5 and it works,

Now, it's not the decimal part the problem in fact. Because if you use other values outside the map (like 200) it works, it's the pow function used to get the colors. i.e. the gamma is applied fine, it's only when you make scale(x) that it fails.

Pow throws NAN whenever the base is negative (below the domain) and the exponent is not integer. I have fixed it on my fork, since in such cases the values are always at the extreme left of the scale and could be clamped.

tibotiber commented 4 months ago

Thanks for the detailed explanation 🙂.

In case that helps, I think it's completely fair to define a scale and provide a value out of the domain. For example, you want to chart temperatures and consider 19 to 24 degree Celsius to be the effective range of visualization. If you get data that's at 18 degrees, maybe an outlier, I'd expect a the scale to clamp the value, not throw an error. Is that reasonable?

That's also how it works like 95% of the time, which is why I interpreted this as a bug.