返回 CodeWhale
session-frames.tsx
根目录 / web / components / route / session-frames.tsx
1 "use client";
2
3 import { useId, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
4
5 export interface SessionFrame {
6 key: string;
7 name: string;
8 wide: ReactNode;
9 narrow: ReactNode;
10 note: boolean;
11 }
12
13 export function SessionFrames({
14 frames,
15 initial,
16 label,
17 caption,
18 note,
19 }: {
20 frames: SessionFrame[];
21 initial: number;
22 label: string;
23 caption: string | null;
24 note: string;
25 }) {
26 const [selected, setSelected] = useState(initial);
27 const tabs = useRef<(HTMLButtonElement | null)[]>([]);
28 const id = useId();
29
30 const move = (event: KeyboardEvent<HTMLDivElement>) => {
31 const rtl = getComputedStyle(event.currentTarget).direction === "rtl";
32 const last = frames.length - 1;
33 const step: Record<string, number> = {
34 ArrowRight: rtl ? -1 : 1,
35 ArrowLeft: rtl ? 1 : -1,
36 ArrowDown: 1,
37 ArrowUp: -1,
38 };
39 let next: number;
40 if (event.key === "Home") next = 0;
41 else if (event.key === "End") next = last;
42 else if (event.key in step) next = (selected + step[event.key] + frames.length) % frames.length;
43 else return;
44 event.preventDefault();
45 setSelected(next);
46 tabs.current[next]?.focus();
47 };
48
49 return (
50 <figure className="home-session">
51 <div className="home-session-tabs" role="tablist" aria-label={label} onKeyDown={move}>
52 {frames.map((frame, index) => (
53 <button
54 key={frame.key}
55 ref={(node) => {
56 tabs.current[index] = node;
57 }}
58 type="button"
59 role="tab"
60 id={`${id}-tab-${index}`}
61 aria-selected={index === selected}
62 aria-controls={`${id}-panel-${index}`}
63 tabIndex={index === selected ? 0 : -1}
64 onClick={() => setSelected(index)}
65 >
66 {frame.name}
67 </button>
68 ))}
69 </div>
70 {frames.map((frame, index) => (
71 <div
72 key={frame.key}
73 className="home-frame home-session-panel"
74 role="tabpanel"
75 id={`${id}-panel-${index}`}
76 aria-labelledby={`${id}-tab-${index}`}
77 hidden={index !== selected}
78 >
79 <div className="home-only-wide">{frame.wide}</div>
80 <div className="home-only-narrow">{frame.narrow}</div>
81 </div>
82 ))}
83 <figcaption className="home-session-caption">
84 {caption ? <p className="home-caption">{caption}</p> : null}
85 <p className="home-caption" hidden={!frames[selected].note}>
86 {note}
87 </p>
88 </figcaption>
89 </figure>
90 );
91 }
92
92 lines Plain Text