Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

clamp HSL format #101

Merged
merged 1 commit into from
Mar 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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