diff --git a/src/lib/components/colors/Header.svelte b/src/lib/components/colors/Header.svelte index 11b96c5f..77d3c363 100644 --- a/src/lib/components/colors/Header.svelte +++ b/src/lib/components/colors/Header.svelte @@ -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; diff --git a/test/lib/components/colors/Header.spec.ts b/test/lib/components/colors/Header.spec.ts index 7849c24f..aed32aab 100644 --- a/test/lib/components/colors/Header.spec.ts +++ b/test/lib/components/colors/Header.spec.ts @@ -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 */