Skip to content

Commit

Permalink
fix: hue values over 255 are cut off
Browse files Browse the repository at this point in the history
root cause: every input value is assumed to be in the range 0 to 255
solution: use the appropriate range depending on the input
  • Loading branch information
Richard Petersen committed Jul 16, 2021
1 parent 894838e commit 7cd6cd5
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
12 changes: 8 additions & 4 deletions index.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/** @module color-rgba */
import parse from 'color-parse'
import rgb from 'color-space/rgb.js'
import hsl from 'color-space/hsl.js'

export default function rgba (color) {
Expand All @@ -13,13 +14,16 @@ export default function rgba (color) {

if (!parsed.space) return []

const minLimits = parsed.space[0] === 'h' ? hsl.min : rgb.min
const maxLimits = parsed.space[0] === 'h' ? hsl.max : rgb.max

values = Array(3)
values[0] = Math.min(Math.max(parsed.values[0], 0), 255)
values[1] = Math.min(Math.max(parsed.values[1], 0), 255)
values[2] = Math.min(Math.max(parsed.values[2], 0), 255)
values[0] = Math.min(Math.max(parsed.values[0], minLimits[0]), maxLimits[0])
values[1] = Math.min(Math.max(parsed.values[1], minLimits[1]), maxLimits[1])
values[2] = Math.min(Math.max(parsed.values[2], minLimits[2]), maxLimits[2])

if (parsed.space[0] === 'h') {
values = hsl.rgb(values)
values = hsl.rgb(values).map(Math.round)
}

values.push(Math.min(Math.max(parsed.alpha, 0), 1))
Expand Down
3 changes: 2 additions & 1 deletion test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ assert.deepEqual(rgba('red'), [255, 0, 0, 1])
assert.deepEqual(rgba('rgb(80, 120, 160)'), [80, 120, 160, 1])
assert.deepEqual(rgba('rgba(80, 120, 160, .5)'), [80, 120, 160, .5])
assert.deepEqual(rgba('rgba(80 120 160 / .5)'), [80, 120, 160, .5])
assert.deepEqual(rgba('hsla(109, 50%, 50%, .75)'), [87.125, 191.25, 63.75, .75])
assert.deepEqual(rgba('hsl(291 80% 50%)'), [199, 25, 230, 1])
assert.deepEqual(rgba('hsla(109, 50%, 50%, .75)'), [87, 191, 64, .75])
assert.deepEqual(rgba('#f00'), [255, 0, 0, 1])
assert.deepEqual(rgba`#f00`, [255, 0, 0, 1])

Expand Down

0 comments on commit 7cd6cd5

Please sign in to comment.