Skip to content

Commit 70e3a04

Browse files
authored
clamp HSL format (#101)
1 parent 994d8fd commit 70e3a04

2 files changed

Lines changed: 15 additions & 4 deletions

File tree

src/color.js

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -353,11 +353,15 @@ define(Hsl, hsl, extend(Color, {
353353
&& (0 <= this.opacity && this.opacity <= 1);
354354
},
355355
formatHsl: function() {
356-
var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
356+
var a = this.opacity,
357+
h = (this.h || 0) % 360,
358+
s = Math.max(0, Math.min(1, this.s || 0)),
359+
l = Math.max(0, Math.min(1, this.l || 0));
360+
a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
357361
return (a === 1 ? "hsl(" : "hsla(")
358-
+ (this.h || 0) + ", "
359-
+ (this.s || 0) * 100 + "%, "
360-
+ (this.l || 0) * 100 + "%"
362+
+ (h < 0 ? h + 360 : h) + ", "
363+
+ s * 100 + "%, "
364+
+ l * 100 + "%"
361365
+ (a === 1 ? ")" : ", " + a + ")");
362366
}
363367
}));

test/hsl-test.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,13 @@ it("hsl.formatHsl() formats as hsl(…) or hsla(…)", () => {
3838
assert.strictEqual(hsl("hsla(60, 100%, 20%, 0.4)").formatHsl(), "hsla(60, 100%, 20%, 0.4)");
3939
});
4040

41+
it("hsl.formatHsl() clamps to the expected range", () => {
42+
assert.strictEqual(hsl(180, -100, -50).formatHsl(), "hsl(180, 0%, 0%)");
43+
assert.strictEqual(hsl(180, 150, 200).formatHsl(), "hsl(180, 100%, 100%)");
44+
assert.strictEqual(hsl(-90, 50, 50).formatHsl(), "hsl(270, 100%, 100%)");
45+
assert.strictEqual(hsl(420, 50, 50).formatHsl(), "hsl(60, 100%, 100%)");
46+
});
47+
4148
it("hsl.formatHex() formats as #rrggbb", () => {
4249
assert.strictEqual(hsl("#abcdef").formatHex(), "#abcdef");
4350
assert.strictEqual(hsl("hsl(60, 100%, 20%)").formatHex(), "#666600");

0 commit comments

Comments
 (0)