Skip to content

Commit

Permalink
Handle hashless hex
Browse files Browse the repository at this point in the history
  • Loading branch information
jamesnw committed Nov 4, 2024
1 parent 92f04dc commit 01691c4
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/lib/components/colors/Header.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,17 @@
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 });
}
// 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 01691c4

Please sign in to comment.