color.js
color.js copied to clipboard
Would be good to have an isValid helper
Currently I call Color(string)
and treat it as valid if an exception was not thrown. It would be good to have an isValid
function exported in the module.
I wonder if we could feed two birds with one scone by making Color.get()
/ getColor()
not error (see #518 ). Then you can just check if the return value === null
.
Exceptions are not thrown for all invalid colors however. If using oklch("z" 100 230)
the returned .toString
value would be oklch(NaN 100 230)
. Obviously, "z" is not acceptable input and 100 is out of range as well, yet, no error is returned. I think a Color.isValid({format: 'oklch'})
would be a better api. I think it would be better to validate a known input, than having a validation that checked the input against ALL known color spaces.
ColorJS is amazing btw! Much resepct.
Exceptions are not thrown for all invalid colors however. If using
oklch("z" 100 230)
the returned.toString
value would beoklch(NaN 100 230)
. Obviously, "z" is not acceptable input and 100 is out of range as well, yet, no error is returned.
Interesting point. NaN
is a valid coordinate value (corresponds to the CSS calc(NaN)
), but perhaps we should not be treating all unparseable strings as equivalent to NaN
.
I think a
Color.isValid({format: 'oklch'})
would be a better api. I think it would be better to validate a known input, than having a validation that checked the input against ALL known color spaces.
There's a separate code path for functional formats and they zero in pretty quickly to the relevant color space. It would be helpful to know the use cases that prompted this. If it's just to facilitate fault tolerance, see #518, I wonder if that would be an acceptable solution?
ColorJS is amazing btw! Much resepct.
Thanks! <3
I was trying to validate colors strings within an input while a user types.
I'm curious why new Color("rgb(1000, 'echo', null)")
throws an exception but new Color("srgb", [-1000, "echo", null])
does not. If I have these values separately rather than as a CSS string, how can I get the exception throwing behavior?
(My hacky idea of new Color(new Color("srgb", [-1000, "echo", null]).toString())
doesn't work because the invalid values are set to 0 in the string output of the inner Color.)
(Also agree that the library is awesome!)