Skip to content
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
10 changes: 10 additions & 0 deletions src/io/rgb/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,17 @@ Color.prototype.rgba = function (rnd = true) {
const rgb = (...args) => new Color(...args, 'rgb');
Object.assign(chroma, { rgb });

const isValidChannel = (value) =>
type(value) === 'number' && !Number.isNaN(value);

input.format.rgb = (...args) => {
const rgba = unpack(args, 'rgba');
if (!rgba.slice(0, 3).every(isValidChannel)) {
throw new Error('invalid rgb color');
}
if (rgba[3] !== undefined && !isValidChannel(rgba[3])) {
throw new Error('invalid rgb color');
}
if (rgba[3] === undefined) rgba[3] = 1;
return rgba;
};
Expand All @@ -30,6 +39,7 @@ input.autodetect.push({
args = unpack(args, 'rgba');
if (
type(args) === 'array' &&
args.slice(0, 3).every(isValidChannel) &&
(args.length === 3 ||
(args.length === 4 &&
type(args[3]) == 'number' &&
Expand Down
10 changes: 10 additions & 0 deletions test/autodetect.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,16 @@ describe('autodetect color', () => {
expect(result.hex()).toBe('#0000ff');
});

it('rejects non-numeric RGB channels', () => {
expect(() => chroma('nonsense', 0, 255, 'rgb')).toThrow('invalid rgb color');
expect(() => chroma(null, 0, 255, 'rgb')).toThrow('invalid rgb color');
});

it('still clips out-of-range numeric RGB channels', () => {
expect(chroma(-1000, 0, 255, 'rgb').hex()).toBe('#0000ff');
expect(chroma(1000, 0, 255, 'rgb').hex()).toBe('#ff00ff');
});

it('autodetect rgba color', () => {
const result = chroma(255, 0, 0, 0.5);
expect(result.css()).toBe('rgb(255 0 0 / 0.5)');
Expand Down