fix: make switch labels properly clickable (#25898)

This commit is contained in:
Michel Heusschen
2026-02-05 12:09:27 +01:00
committed by GitHub
parent fdf06a91cc
commit e97030a7ae
4 changed files with 53 additions and 13 deletions

View File

@@ -0,0 +1,23 @@
import { render } from '@testing-library/svelte';
import SettingSwitch from './setting-switch.svelte';
describe('SettingSwitch component', () => {
it('links switch and subtitle ids on the switch', () => {
const { getByText } = render(SettingSwitch, {
props: {
title: 'Enable feature',
subtitle: 'Controls the feature state.',
},
});
const label = getByText('Enable feature') as HTMLLabelElement;
const subtitle = getByText('Controls the feature state.');
const subtitleId = subtitle.getAttribute('id');
const switchElement = document.querySelector(`#${label.htmlFor}`);
expect(subtitleId).not.toBeNull();
expect(label.htmlFor).not.toBe('');
expect(switchElement).not.toBeNull();
expect(switchElement?.getAttribute('aria-describedby')).toBe(subtitleId);
});
});

View File

@@ -28,14 +28,14 @@
let id: string = generateId();
let sliderId = $derived(`${id}-slider`);
let switchId = $derived(`input-${id}`);
let subtitleId = $derived(subtitle ? `${id}-subtitle` : undefined);
</script>
<div class="flex place-items-center justify-between">
<div class="me-2">
<div class="flex h-6.5 place-items-center gap-1">
<label class="font-medium text-primary text-sm" for={sliderId}>
<label class="font-medium text-primary text-sm" for={switchId}>
{title}
</label>
{#if isEdited}
@@ -54,5 +54,5 @@
{@render children?.()}
</div>
<Switch id={sliderId} bind:checked {disabled} onCheckedChange={onToggle} aria-describedby={subtitleId} />
<Switch {id} bind:checked {disabled} onCheckedChange={onToggle} aria-describedby={subtitleId} />
</div>