返回 CodeWhale
mobile-menu.tsx
根目录 / web / components / mobile-menu.tsx
1 "use client";
2
3 import Link from "next/link";
4 import { usePathname } from "next/navigation";
5 import { useCallback, useEffect, useRef, useState } from "react";
6 import { createPortal } from "react-dom";
7 import { currentNavHref, type ChromeLink } from "@/lib/i18n/links";
8 import { Icon } from "./icon";
9 import { ArrowLabel } from "./arrow-label";
10
11 export function MobileMenu({
12 links,
13 github,
14 signIn,
15 installHref,
16 installLabel,
17 openLabel,
18 closeLabel,
19 navAria,
20 }: {
21 links: ChromeLink[];
22 github: { href: string; label: string; count: string | null; aria: string };
23 signIn: ChromeLink | null;
24 installHref: string;
25 installLabel: string;
26 openLabel: string;
27 closeLabel: string;
28 /** Accessible name for the dialog's navigation landmark. */
29 navAria: string;
30 }) {
31 const [openPathname, setOpenPathname] = useState<string | null>(null);
32 // `closing` holds the panel mounted for a short exit fade; the unmount —
33 // and the focus hand-back in the effect below — then happens on the
34 // timeout, not on the click.
35 const [closing, setClosing] = useState(false);
36 const closeTimer = useRef<number | null>(null);
37 const pathname = usePathname();
38 const open = openPathname !== null && openPathname === pathname;
39 const currentHref = currentNavHref(signIn ? [...links, signIn] : links, pathname);
40 const toggleRef = useRef<HTMLButtonElement>(null);
41 const menuRef = useRef<HTMLDivElement>(null);
42
43 const closeImmediately = useCallback(() => {
44 if (closeTimer.current !== null) window.clearTimeout(closeTimer.current);
45 closeTimer.current = null;
46 setOpenPathname(null);
47 setClosing(false);
48 }, []);
49
50 const close = useCallback(() => {
51 // Reduced motion keeps the original instant mount/unmount.
52 if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
53 closeImmediately();
54 return;
55 }
56 if (closeTimer.current !== null) window.clearTimeout(closeTimer.current);
57 setClosing(true);
58 closeTimer.current = window.setTimeout(() => {
59 closeTimer.current = null;
60 setOpenPathname(null);
61 setClosing(false);
62 }, 180);
63 }, [closeImmediately]);
64
65 const onToggle = () => {
66 if (!open) {
67 setClosing(false);
68 setOpenPathname(pathname);
69 return;
70 }
71 if (closing) {
72 // Re-open mid-exit: cancel the pending unmount and stay open.
73 window.clearTimeout(closeTimer.current ?? undefined);
74 closeTimer.current = null;
75 setClosing(false);
76 return;
77 }
78 close();
79 };
80
81 useEffect(() => {
82 if (!open) return;
83 const prev = document.body.style.overflow;
84 document.body.style.overflow = "hidden";
85 // aria-modal promises the dialog owns interaction. Keep background roots
86 // inert, contain keyboard focus, and hand it back to the toggle on close.
87 const dialog = menuRef.current;
88 const backgroundRoots = Array.from(document.body.children)
89 .filter((element): element is HTMLElement =>
90 element instanceof HTMLElement && element !== dialog)
91 .map((element) => ({ element, wasInert: element.inert }));
92 for (const { element } of backgroundRoots) element.inert = true;
93
94 // The toggle node is captured now: reading toggleRef.current inside the
95 // cleanup would race React clearing the ref.
96 const toggle = toggleRef.current;
97 const focusable = () => Array.from(dialog?.querySelectorAll<HTMLElement>(
98 'a[href], button:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])',
99 ) ?? []).filter((element) => element.getClientRects().length > 0);
100 focusable()[0]?.focus();
101
102 const onKey = (e: KeyboardEvent) => {
103 if (e.key === "Escape") {
104 e.preventDefault();
105 close();
106 return;
107 }
108 if (e.key !== "Tab") return;
109 const candidates = focusable();
110 const first = candidates[0];
111 const last = candidates[candidates.length - 1];
112 if (!first || !last) {
113 e.preventDefault();
114 return;
115 }
116 const active = document.activeElement;
117 if (e.shiftKey && (active === first || !dialog?.contains(active))) {
118 e.preventDefault();
119 last.focus();
120 } else if (!e.shiftKey && (active === last || !dialog?.contains(active))) {
121 e.preventDefault();
122 first.focus();
123 }
124 };
125
126 // Tailwind's lg boundary hides the compact controls. Close immediately
127 // when a live resize crosses it so an invisible sheet cannot retain the
128 // body's scroll lock.
129 const desktop = window.matchMedia("(min-width: 1024px)");
130 const onDesktop = (event: MediaQueryListEvent | MediaQueryList) => {
131 if (event.matches) closeImmediately();
132 };
133 window.addEventListener("keydown", onKey);
134 desktop.addEventListener("change", onDesktop);
135 if (desktop.matches) closeImmediately();
136
137 return () => {
138 document.body.style.overflow = prev;
139 window.removeEventListener("keydown", onKey);
140 desktop.removeEventListener("change", onDesktop);
141 for (const { element, wasInert } of backgroundRoots) element.inert = wasInert;
142 if (toggle?.getClientRects().length) toggle.focus();
143 };
144 }, [close, closeImmediately, open]);
145
146 // A pending exit timer must not outlive the component (locale switches
147 // remount the nav).
148 useEffect(() => {
149 return () => {
150 if (closeTimer.current !== null) window.clearTimeout(closeTimer.current);
151 };
152 }, []);
153
154 return (
155 <>
156 <button
157 ref={toggleRef}
158 type="button"
159 onClick={onToggle}
160 className="nav-icon-button lg:hidden"
161 aria-label={open ? closeLabel : openLabel}
162 aria-expanded={open}
163 aria-controls="mobile-menu"
164 >
165 <Icon name={open ? "x" : "menu"} className="nav-icon" />
166 </button>
167
168 {open && typeof document !== "undefined" &&
169 createPortal(<div
170 ref={menuRef}
171 id="mobile-menu"
172 className={`mm-panel lg:hidden fixed inset-0 z-40 bg-canvas overflow-y-auto${closing ? " mm-closing" : ""}`}
173 role="dialog"
174 aria-modal="true"
175 aria-label={navAria}
176 >
177 <div className="flex min-h-[3.85rem] items-center justify-end px-4 hairline-b">
178 <button type="button" onClick={close} className="nav-icon-button" aria-label={closeLabel}>
179 <Icon name="x" className="nav-icon" />
180 </button>
181 </div>
182 {/* Only one nav landmark is exposed at a time (the desktop nav is
183 display:none at these widths), so the named dialog carries the
184 landmark name and the inner nav stays unlabeled — two nested
185 "Primary" landmarks would read as duplication. */}
186 <nav className="px-6 py-4">
187 <ul className="mm-list">
188 {links.map((l) => {
189 const isActive = l.href === currentHref;
190 return (
191 <li key={l.href}>
192 <Link
193 href={l.href}
194 onClick={closeImmediately}
195 className="mm-link"
196 aria-current={isActive ? "page" : undefined}
197 >
198 <span>{l.label}</span>
199 <Icon name="chevron-right" className="nav-icon mm-link-chevron icon-flip" />
200 </Link>
201 </li>
202 );
203 })}
204 <li>
205 <a
206 href={github.href}
207 className="mm-link"
208 aria-label={github.aria}
209 data-funnel="star_exit"
210 onClick={closeImmediately}
211 >
212 <span>{github.label}{github.count !== null && <span className="tabular"> · {github.count}</span>}</span>
213 <Icon name="chevron-right" className="nav-icon mm-link-chevron icon-flip" />
214 </a>
215 </li>
216 {signIn ? (
217 <li>
218 <Link
219 href={signIn.href}
220 onClick={closeImmediately}
221 className="mm-link"
222 aria-current={signIn.href === currentHref ? "page" : undefined}
223 >
224 <span>{signIn.label}</span>
225 <Icon name="chevron-right" className="nav-icon mm-link-chevron icon-flip" />
226 </Link>
227 </li>
228 ) : null}
229 </ul>
230
231 <Link
232 href={installHref}
233 onClick={closeImmediately}
234 className="mm-action paper-install-cta"
235 >
236 <ArrowLabel text={installLabel} />
237 </Link>
238 </nav>
239 </div>, document.body)}
240 </>
241 );
242 }
243
243 lines Plain Text