summaryrefslogtreecommitdiff
path: root/src/components/shared/SegmentedControl.tsx
blob: 93ff64e4cd6f1ada32892fbd0c2a9696aaad385a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import cx from 'clsx';
import * as React from 'react';

import s from './SegmentedControl.module.scss';

export type SegmentedOption<T extends string | number> = {
  value: T;
  label: React.ReactNode;
  title?: string;
};

type Props<T extends string | number> = {
  options: SegmentedOption<T>[];
  value: T;
  onChange: (value: T) => void;
  label?: string;
  className?: string;
};

/** 分段选择器:一条轨道内若干选项,选中项以白色药丸高亮 */
export function SegmentedControl<T extends string | number>({
  options,
  value,
  onChange,
  label,
  className,
}: Props<T>) {
  return (
    <div className={cx(s.track, className)} role="radiogroup" aria-label={label}>
      {options.map((o) => {
        const selected = o.value === value;
        return (
          <button
            key={o.value}
            type="button"
            role="radio"
            aria-checked={selected}
            title={o.title}
            className={cx(s.segment, { [s.selected]: selected })}
            onClick={() => onChange(o.value)}
          >
            {o.label}
          </button>
        );
      })}
    </div>
  );
}