File size: 1,781 Bytes
9e15897
 
 
 
b2aa446
9e15897
 
 
 
 
 
 
 
 
 
 
b2aa446
 
9e15897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useId, useState } from "react";
import "../styles/sdlc81/dashboard-kit.css";

export interface AppTab { id: string; label: string; count?: number | null }
/** value and active are controlled aliases. Without either, the first tab is selected. */
export interface AppTabsProps {
  tabs: AppTab[];
  value?: string;
  active?: string;
  onChange?: (id: string) => void;
  ariaLabel?: string;
  "aria-label"?: string;
  label?: string;
}
export function AppTabs(props: AppTabsProps) {
  const uid = useId();
  const [local, setLocal] = useState(() => props.tabs[0]?.id);
  const tabs = props.tabs;
  const selected = props.value ?? props.active ?? local;
  const choose = (id: string) => { setLocal(id); props.onChange?.(id); };
  return <div className="lp-app-tabs" role="tablist" aria-label={props["aria-label"] ?? props.ariaLabel ?? props.label ?? "App views"}>
    {tabs.map((tab, index) => <button type="button" role="tab" key={tab.id} id={`${uid}-${tab.id}`}
      data-tab={tab.id} aria-selected={selected === tab.id} tabIndex={selected === tab.id ? 0 : -1}
      onClick={() => choose(tab.id)} onKeyDown={event => {
        const next = event.key === "Home" ? 0 : event.key === "End" ? tabs.length - 1
          : event.key === "ArrowRight" ? (index + 1) % tabs.length
          : event.key === "ArrowLeft" ? (index + tabs.length - 1) % tabs.length : null;
        if (next === null) return;
        event.preventDefault(); choose(tabs[next].id);
        event.currentTarget.parentElement?.querySelectorAll<HTMLButtonElement>("[role=tab]")[next]?.focus();
      }}>{tab.label}{typeof tab.count === "number" && Number.isFinite(tab.count)
        && <span className="lp-app-tab-count">{tab.count.toLocaleString()}</span>}</button>)}
  </div>;
}
export default AppTabs;