切り替え
2〜5 つの選択肢から 1 つを選び、その場で見え方を切り替える部品です。選んだ印が 1 つの要素で動きます。
見本で種類と状態を確かめる
外は surface-2、選んだ項目の下に surface の印を敷きます(Dark は surface-3)。台の上の切り替えは、押すか ←→ で選べます。
4 つ
3 つ
2 つ
コードを写す
HTML
<div class="mz-seg" role="radiogroup" aria-label="見通しの期間" data-seg>
<span class="mz-seg__thumb" aria-hidden="true"></span>
<button class="mz-seg__item" type="button" role="radio" aria-checked="false" tabindex="-1">3か月</button>
<button class="mz-seg__item" type="button" role="radio" aria-checked="true" tabindex="0">1年</button>
<button class="mz-seg__item" type="button" role="radio" aria-checked="false" tabindex="-1">5年</button>
<button class="mz-seg__item" type="button" role="radio" aria-checked="false" tabindex="-1">10年</button>
</div>React の呼び出し方
const [span, setSpan] = useState<'3m' | '1y' | '5y' | '10y'>('1y');
return (
<Segmented
aria-label="見通しの期間"
options={[
{ value: '3m', label: '3か月' },
{ value: '1y', label: '1年' },
{ value: '5y', label: '5年' },
{ value: '10y', label: '10年' },
]}
value={span}
onChange={setSpan}
/>
);実装を見る(react/Segmented.tsx)
React の実装(react/Segmented.tsx)
/**
* Segmented — 切り替え(docs/spec/components.md「segmented」・css/components/segmented.css)
* 2〜5 項目。6 つ以上は Select か tabs を使う。
* ←→(↑↓)で移動して選ぶ(roving tabindex。tabindex は 0 と -1 だけ)。
* 選択の印は 1 つの要素で、位置と幅を --x と --w で渡す(見た目のロジックは CSS が持つ)。
*/
import {
forwardRef,
useEffect,
useImperativeHandle,
useLayoutEffect,
useRef,
useState,
type ForwardedRef,
type HTMLAttributes,
type KeyboardEvent,
type Ref,
type ReactNode,
} from 'react';
export interface SegmentedOption<V extends string> {
value: V;
label: ReactNode;
}
export interface SegmentedProps<V extends string>
extends Omit<HTMLAttributes<HTMLDivElement>, 'onChange' | 'role' | 'children'> {
options: SegmentedOption<V>[];
value: V;
onChange: (value: V) => void;
}
const steps: Record<string, number> = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 };
function SegmentedInner<V extends string>(
{ options, value, onChange, className, style, onKeyDown: onKeyDownProp, ...rest }: SegmentedProps<V>,
ref: ForwardedRef<HTMLDivElement>,
) {
const root = useRef<HTMLDivElement>(null);
const items = useRef<(HTMLButtonElement | null)[]>([]);
const [ready, setReady] = useState(false);
useImperativeHandle(ref, () => root.current as HTMLDivElement);
const place = () => {
const i = options.findIndex((o) => o.value === value);
const el = items.current[i];
if (!root.current || !el) return;
root.current.style.setProperty('--x', `${el.offsetLeft}px`);
root.current.style.setProperty('--w', `${el.offsetWidth}px`);
};
const latestPlace = useRef(place);
latestPlace.current = place;
useLayoutEffect(place);
// 大きさが変わったら置き直す(value と options が変わったときは、上の useLayoutEffect が描画のたびに置き直す)
useEffect(() => {
if (!root.current) return;
const ro = new ResizeObserver(() => latestPlace.current());
ro.observe(root.current);
const id = requestAnimationFrame(() => setReady(true));
return () => {
ro.disconnect();
cancelAnimationFrame(id);
};
}, []);
const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
// 使う側の処理を先に呼ぶ。preventDefault されたら、←→ の移動をしない
onKeyDownProp?.(event);
if (event.defaultPrevented) return;
const step = steps[event.key];
if (!step) return;
event.preventDefault();
const i = options.findIndex((o) => o.value === value);
const next = (i + step + options.length) % options.length;
onChange(options[next].value);
items.current[next]?.focus();
};
return (
<div
ref={root}
role="radiogroup"
className={className ? `mz-seg ${className}` : 'mz-seg'}
data-ready={ready ? '' : undefined}
style={style}
{...rest}
onKeyDown={onKeyDown}
>
<span className="mz-seg__thumb" aria-hidden="true" />
{options.map((o, i) => {
const on = o.value === value;
return (
<button
key={o.value}
ref={(el) => {
items.current[i] = el;
}}
type="button"
role="radio"
aria-checked={on}
tabIndex={on ? 0 : -1}
className="mz-seg__item"
onClick={() => onChange(o.value)}
>
{o.label}
</button>
);
})}
</div>
);
}
export const Segmented = forwardRef(SegmentedInner) as <V extends string>(
props: SegmentedProps<V> & { ref?: Ref<HTMLDivElement> },
) => ReturnType<typeof SegmentedInner>;印の位置と幅は、JS が --x と --w で渡します。React の Segmented はこれを持っています。
いつ使うか
読み上げとキーボードにどう応えるか
role="radiogroup"とrole="radio"・aria-checkedで、「1年、ラジオボタン、選択済み、4 個中 2 個目」のように伝わります。- Tab で届くのは選んだ項目だけで、←→ で移って選びます(roving tabindex。
tabindexは 0 と -1 だけ)。 - 全体の名前を
aria-labelかaria-labelledbyで付けます。
よい例と悪い例
更新日