Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle hashless hex #211

Merged
merged 2 commits into from
Nov 7, 2024
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
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