Skip to content

Commit

Permalink
Merge pull request #211 from oddbird/hashless-hex
Browse files Browse the repository at this point in the history
Handle hashless hex
  • Loading branch information
jgerigmeyer authored Nov 7, 2024
2 parents 92f04dc + 81d1b6a commit 9143bb8
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
15 changes: 13 additions & 2 deletions src/lib/components/colors/Header.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,19 @@
try {
newColor = to(value, targetSpace, { inGamut: true });
} catch (error) {
hasError = true;
console.error(error);
try {
// If it's possibly hex without a hash, add a hash and try again.
if ([3, 4, 6, 8].includes(value.length)) {
newColor = to(`#${value}`, targetSpace, { inGamut: true });
} else {
throw error;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (errorWithHash) {
hasError = true;
// Log original error
console.error(error);
}
}
if (newColor) {
$color = newColor;
Expand Down
34 changes: 34 additions & 0 deletions test/lib/components/colors/Header.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,40 @@ describe('Header', () => {
expect(actual.coords).toEqual([0, 100, 50]);
});

it('handles hex with a preceding hash', async () => {
const color = writable(HSL_WHITE);
const { getByLabelText } = render(Header, {
type: 'bg',
color,
format: 'hsl',
});
const input = getByLabelText('Background Color');
await fireEvent.focus(input);
await fireEvent.input(input, { target: { value: '#f00' } });
await fireEvent.blur(input);
const actual = get(color);

expect(actual.space).toEqual(HSL);
expect(actual.coords).toEqual([0, 100, 50]);
});

it('handles hex without a preceding hash', async () => {
const color = writable(HSL_WHITE);
const { getByLabelText } = render(Header, {
type: 'bg',
color,
format: 'hsl',
});
const input = getByLabelText('Background Color');
await fireEvent.focus(input);
await fireEvent.input(input, { target: { value: 'f00' } });
await fireEvent.blur(input);
const actual = get(color);

expect(actual.space).toEqual(HSL);
expect(actual.coords).toEqual([0, 100, 50]);
});

it('shows error on invalid color', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {
/* do nothing */
Expand Down

0 comments on commit 9143bb8

Please sign in to comment.