Skip to content

Commit

Permalink
Ensure clampChroma() returns a displayable color, fixes #129
Browse files Browse the repository at this point in the history
  • Loading branch information
danburzo committed Jul 23, 2021
1 parent dd70cf0 commit 36dddbf
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 8 deletions.
12 changes: 8 additions & 4 deletions src/clamp.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,20 +48,24 @@ const clampChroma = color => {

// By this time we know chroma = 0 is displayable and our current chroma is not.
// Find the displayable chroma through the bisection method.
let start = 0,
end = color.c,
delta = 0.01;
let start = 0;
let end = color.c;
let delta = 0.01;
let _last_good_c;

while (end - start > delta) {
clamped.c = start + (end - start) * 0.5;
if (displayable(clamped)) {
_last_good_c = clamped.c;
start = clamped.c;
} else {
end = clamped.c;
}
}

return conv(clamped);
return conv(
displayable(clamped) ? clamped : { ...clamped, c: _last_good_c }
);
};

// Deprecated / no longer documented
Expand Down
21 changes: 17 additions & 4 deletions test/clamp.test.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,39 @@
import tape from 'tape';
import { clampChroma } from '../src/index';
import { clampChroma, displayable } from '../src/index';

tape('RGB', function (test) {
test.deepEqual(clampChroma('red'), { mode: 'rgb', r: 1, g: 0, b: 0 });

test.deepEqual(clampChroma('rgb(300, 255, 255)'), {
mode: 'rgb',
r: 1,
g: 1,
b: 1
});

test.end();
});

tape('LCh', function (test) {
test.deepEqual(clampChroma('lch(50 120 5)'), {
mode: 'lch',
l: 50,
c: 77.48291015625,
c: 77.4755859375,
h: 5
});
test.equal(displayable(clampChroma('lch(50 120 5)')), true);
test.end();
});

tape('Issue #129', function (test) {
let color = {
mode: 'lch',
l: 44.01740616147086,
c: 58.743630227529145,
h: 180.30393476177233
};
test.equal(displayable(clampChroma(color)), true);
test.equal(
displayable(clampChroma({ mode: 'oklch', l: 0.5, c: 0.161, h: 180 })),
true
);
test.end();
});

0 comments on commit 36dddbf

Please sign in to comment.