Files
Rosea/packages/domi-ui/src/components/Segmented.svelte
T

63 lines
2.1 KiB
Svelte

<script lang="ts">
import Icon from './Icon.svelte';
import { strike } from '../lib/strike';
import type { DomiOption } from '../types';
interface Props {
value?: string;
/** Names the group for a screen reader: "View". */
label: string;
options: DomiOption[];
disabled?: boolean;
onchange?: (value: string) => void;
/** Showcase only: value → forced state for that segment. */
force?: Record<string, string>;
class?: string;
}
let { value = $bindable(''), label, options, disabled = false, onchange, force = {}, class: cls = '' }: Props = $props();
let group: HTMLDivElement | undefined = $state();
const enabled = $derived(options.filter((o) => !o.disabled && !disabled));
function choose(v: string) {
if (v === value) return;
value = v;
onchange?.(v);
}
// A radio group: one tab stop; arrows move the choice and the focus, Home and End jump.
function keydown(e: KeyboardEvent) {
const i = enabled.findIndex((o) => o.value === value);
let j = i;
if (e.key === 'ArrowRight' || e.key === 'ArrowDown') j = (i + 1) % enabled.length;
else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') j = (i - 1 + enabled.length) % enabled.length;
else if (e.key === 'Home') j = 0;
else if (e.key === 'End') j = enabled.length - 1;
else return;
e.preventDefault();
const next = enabled[j];
if (!next) return;
choose(next.value);
group?.querySelector<HTMLButtonElement>(`[data-value="${CSS.escape(next.value)}"]`)?.focus();
}
</script>
<div bind:this={group} class={['domi-segmented', cls]} role="radiogroup" aria-label={label} tabindex="-1" onkeydown={keydown}>
{#each options as o (o.value)}
<button
type="button"
role="radio"
class="domi-segmented__item"
data-value={o.value}
data-force={force[o.value]}
aria-checked={o.value === value}
tabindex={o.value === value || (!value && o === enabled[0]) ? 0 : -1}
disabled={disabled || o.disabled}
onclick={() => choose(o.value)}
use:strike
>
{#if o.icon}<Icon name={o.icon} />{/if}{o.label}
</button>
{/each}
</div>