Skip to content

Commit

Permalink
clamp HSL format (#101)
Browse files Browse the repository at this point in the history
  • Loading branch information
mbostock authored Mar 28, 2022
1 parent 994d8fd commit 70e3a04
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
12 changes: 8 additions & 4 deletions src/color.js
Original file line number Diff line number Diff line change
Expand Up @@ -353,11 +353,15 @@ define(Hsl, hsl, extend(Color, {
&& (0 <= this.opacity && this.opacity <= 1);
},
formatHsl: function() {
var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
var a = this.opacity,
h = (this.h || 0) % 360,
s = Math.max(0, Math.min(1, this.s || 0)),
l = Math.max(0, Math.min(1, this.l || 0));
a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
return (a === 1 ? "hsl(" : "hsla(")
+ (this.h || 0) + ", "
+ (this.s || 0) * 100 + "%, "
+ (this.l || 0) * 100 + "%"
+ (h < 0 ? h + 360 : h) + ", "
+ s * 100 + "%, "
+ l * 100 + "%"
+ (a === 1 ? ")" : ", " + a + ")");
}
}));
Expand Down
7 changes: 7 additions & 0 deletions test/hsl-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,13 @@ it("hsl.formatHsl() formats as hsl(…) or hsla(…)", () => {
assert.strictEqual(hsl("hsla(60, 100%, 20%, 0.4)").formatHsl(), "hsla(60, 100%, 20%, 0.4)");
});

it("hsl.formatHsl() clamps to the expected range", () => {
assert.strictEqual(hsl(180, -100, -50).formatHsl(), "hsl(180, 0%, 0%)");
assert.strictEqual(hsl(180, 150, 200).formatHsl(), "hsl(180, 100%, 100%)");
assert.strictEqual(hsl(-90, 50, 50).formatHsl(), "hsl(270, 100%, 100%)");
assert.strictEqual(hsl(420, 50, 50).formatHsl(), "hsl(60, 100%, 100%)");
});

it("hsl.formatHex() formats as #rrggbb", () => {
assert.strictEqual(hsl("#abcdef").formatHex(), "#abcdef");
assert.strictEqual(hsl("hsl(60, 100%, 20%)").formatHex(), "#666600");
Expand Down

0 comments on commit 70e3a04

Please sign in to comment.