返回 CodeWhale
hero-surface-preview.tsx
根目录 / web / components / hero-surface-preview.tsx
1 "use client";
2
3 import { useId, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
4
5 export interface HeroSurfacePreviewProps {
6 label: string;
7 terminalLabel: string;
8 desktopLabel: string;
9 terminal: ReactNode;
10 desktop: ReactNode;
11 }
12
13 const SURFACES = ["terminal", "desktop"] as const;
14 type SurfaceKey = (typeof SURFACES)[number];
15
16 export function HeroSurfacePreview({
17 label,
18 terminalLabel,
19 desktopLabel,
20 terminal,
21 desktop,
22 }: HeroSurfacePreviewProps) {
23 const [active, setActive] = useState<SurfaceKey>("terminal");
24 const tabs = useRef<(HTMLButtonElement | null)[]>([]);
25 const id = useId();
26 const labels: Record<SurfaceKey, string> = {
27 terminal: terminalLabel,
28 desktop: desktopLabel,
29 };
30
31 const move = (event: KeyboardEvent<HTMLDivElement>) => {
32 const rtl = getComputedStyle(event.currentTarget).direction === "rtl";
33 const current = SURFACES.indexOf(active);
34 const step: Record<string, number> = {
35 ArrowRight: rtl ? -1 : 1,
36 ArrowLeft: rtl ? 1 : -1,
37 ArrowDown: 1,
38 ArrowUp: -1,
39 };
40 let next: number;
41 if (event.key === "Home") next = 0;
42 else if (event.key === "End") next = SURFACES.length - 1;
43 else if (event.key in step) next = (current + step[event.key] + SURFACES.length) % SURFACES.length;
44 else return;
45 event.preventDefault();
46 setActive(SURFACES[next]);
47 tabs.current[next]?.focus();
48 };
49
50 return (
51 <div className="home-session" data-hero-surface-preview="">
52 <div className="home-session-tabs" role="tablist" aria-label={label} onKeyDown={move}>
53 {SURFACES.map((surface, index) => (
54 <button
55 key={surface}
56 ref={(node) => {
57 tabs.current[index] = node;
58 }}
59 type="button"
60 role="tab"
61 id={`${id}-tab-${surface}`}
62 aria-selected={active === surface}
63 aria-controls={`${id}-panel-${surface}`}
64 tabIndex={active === surface ? 0 : -1}
65 onClick={() => setActive(surface)}
66 >
67 {labels[surface]}
68 </button>
69 ))}
70 </div>
71 <div
72 role="tabpanel"
73 id={`${id}-panel-${active}`}
74 aria-labelledby={`${id}-tab-${active}`}
75 >
76 {active === "terminal" ? terminal : desktop}
77 </div>
78 </div>
79 );
80 }
81
81 lines Plain Text