forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits

mobile-nav-sheet.tsx312 lines, 13.4 KiBHistoryRawDownload
1import { For, Show, createEffect, createSignal, onCleanup } from "solid-js";
2import { Link, useRouterState } from "@tanstack/solid-router";
3import { routeNavItem, visibleNavGroups, type NavItem } from "@/components/layout/nav-items";
4import { accountDisplayName, createAccountMenu } from "@/components/layout/account-menu";
5import { MobileAccountPanel } from "@/components/layout/mobile-account-panel";
6import { IconChevronLeft, IconChevronRight, IconX } from "@/components/ui/icons";
7import { UserAvatar } from "@/components/users/user-avatar";
8import type { MessageKey } from "@/i18n/messages";
9import { cn } from "@/lib/cn";
10import { useAuth } from "@/stores/auth-context";
11import { useModules } from "@/stores/modules-context";
12import { useShellFeed } from "@/stores/shell-feed-context";
13import { useT } from "@/stores/preferences-context";
14
15/**
16 * The phone-sized navigation menu: a sheet that rises from the bottom of the
17 * screen, where a thumb already is, instead of the side drawer this replaces.
18 *
19 * It stays mounted and is moved off-screen when closed, so opening and closing
20 * both animate; a `<Show>` around it would make it appear and disappear in one
21 * frame.
22 *
23 * It closes by tapping the X, tapping outside, or dragging it down past
24 * DISMISS_PX — the gesture people expect from a sheet.
25 */
26
27/** How far the sheet has to be pulled down before letting go dismisses it. */
28const DISMISS_PX = 96;
29export function MobileNavSheet(props: {
30 open: boolean;
31 onClose: () => void;
32 onLogout: () => void | Promise<void>;
33 onOpenCelebi?: () => void;
34 onOpenProfile?: () => void;
35}) {
36 const auth = useAuth();
37 const t = useT();
38 const feed = useShellFeed();
39 const modules = useModules();
40 const pathname = useRouterState({ select: (state) => state.location.pathname });
41 const search = useRouterState({ select: (state) => state.location.search as Record<string, unknown> });
42
43 // The primary destinations are already one tap away in the tab bar, so the
44 // sheet lists everything else.
45 const groups = () => visibleNavGroups(auth.user()?.role, modules.enabled());
46 const current = () => routeNavItem(pathname(), auth.user()?.role, search());
47 const badgeFor = (item: NavItem) => (item.id === "messages" ? feed.unreadMessages().total : 0);
48 // The account row drills into an account view inside this same sheet —
49 // a back arrow returns — instead of a dropdown stacked on top of the sheet.
50 const [view, setView] = createSignal<"nav" | "account">("nav");
51 createEffect(() => {
52 if (!props.open) setView("nav");
53 });
54 const menu = createAccountMenu({
55 onLogout: props.onLogout,
56 onLeave: props.onClose,
57 onOpenSettings: () => {
58 props.onClose();
59 props.onOpenProfile?.();
60 },
61 });
62
63 const runAction = (item: NavItem) => {
64 props.onClose();
65 if (item.action === "celebi") props.onOpenCelebi?.();
66 if (item.action === "profile") props.onOpenProfile?.();
67 };
68
69 // Drag-to-dismiss. Only the grab area drives it, so a flick inside the list
70 // still scrolls the list. While dragging, the sheet follows the finger with
71 // its transition off; on release it either closes or springs back.
72 const [dragY, setDragY] = createSignal(0);
73 const [dragging, setDragging] = createSignal(false);
74 let startY = 0;
75 // Keyboard users arrive here through the Menü tab control. Park focus on
76 // the close button while the sheet is up (Escape closes it too) and hand
77 // focus back to the Menü trigger on dismiss, so focus never strands on
78 // the body or inside an off-screen panel.
79 let closeBtn: HTMLButtonElement | undefined;
80 let wasOpen = false;
81 createEffect(() => {
82 if (props.open) {
83 wasOpen = true;
84 closeBtn?.focus();
85 const onKey = (event: KeyboardEvent) => {
86 if (event.key === "Escape") props.onClose();
87 };
88 window.addEventListener("keydown", onKey);
89 onCleanup(() => window.removeEventListener("keydown", onKey));
90 } else if (wasOpen) {
91 wasOpen = false;
92 document.getElementById("mobile-menu-trigger")?.focus();
93 }
94 });
95 const startDrag = (event: PointerEvent) => {
96 if (event.pointerType === "mouse" && event.button !== 0) return;
97 // Buttons inside a drag surface (the sheet's X) must keep their own
98 // gesture — setPointerCapture on this parent otherwise eats the click on
99 // touch devices, so the sheet looks stuck open.
100 const target = event.target;
101 if (target instanceof Element && target.closest("button, a, input, textarea, select, [role='button']")) {
102 return;
103 }
104 startY = event.clientY;
105 setDragging(true);
106 (event.currentTarget as HTMLElement).setPointerCapture(event.pointerId);
107 };
108
109 const moveDrag = (event: PointerEvent) => {
110 if (!dragging()) return;
111 // Downward only: dragging up must not lift the sheet past its own top.
112 setDragY(Math.max(0, event.clientY - startY));
113 };
114
115 const endDrag = () => {
116 if (!dragging()) return;
117 const travelled = dragY();
118 setDragging(false);
119 setDragY(0);
120 if (travelled > DISMISS_PX) props.onClose();
121 };
122
123 return (
124 <div
125 // Closed: invisible + pointer-events-none. visibility:hidden alone still
126 // leaves pointer-events:auto, and on some mobile WebViews that full-screen
127 // z-60 layer swallows taps meant for dialogs/side panels underneath (z-50
128 // historically, now z-70). Open sheet stays above the tab bar (z-40).
129 class={cn(
130 "fixed inset-0 z-[60] lg:hidden",
131 props.open ? "pointer-events-auto visible" : "pointer-events-none invisible",
132 )}
133 aria-hidden={props.open ? undefined : "true"}
134 >
135 <button
136 type="button"
137 aria-label={t("nav.close")}
138 onClick={props.onClose}
139 class={cn(
140 "absolute inset-0 h-full w-full cursor-default bg-black/45 transition-opacity duration-300",
141 props.open ? "opacity-100" : "opacity-0",
142 )}
143 />
144
145 <div
146 // Only a dialog while it is actually up: left on permanently, this
147 // off-screen panel would answer every [role=dialog] query and sit in
148 // the accessibility tree next to whatever modal is really open.
149 role={props.open ? "dialog" : undefined}
150 aria-modal={props.open ? "true" : undefined}
151 aria-label={t("nav.menu")}
152 class={cn(
153 "absolute inset-x-0 bottom-0 flex max-h-[75vh] flex-col rounded-t-3xl border-t border-border bg-background",
154 "pb-[max(env(safe-area-inset-bottom),var(--android-nav-inset,0px))]",
155 "transition-transform duration-300 ease-out",
156 props.open ? "translate-y-0" : "translate-y-full",
157 )}
158 style={dragging() ? { transform: `translateY(${dragY()}px)`, transition: "none" } : undefined}
159 >
160 {/* Drag only on the handle — keeping the title/close row outside this
161 surface so the X receives taps on mobile (pointer capture on a
162 parent eats button clicks). touch-none keeps the browser from
163 claiming the vertical gesture for scrolling. */}
164 <div
165 class="shrink-0 touch-none"
166 onPointerDown={startDrag}
167 onPointerMove={moveDrag}
168 onPointerUp={endDrag}
169 onPointerCancel={endDrag}
170 >
171 <div class="flex justify-center pt-2.5 pb-1">
172 <span class="h-1 w-9 rounded-full bg-border" />
173 </div>
174 </div>
175
176 <div class="flex shrink-0 items-center justify-between px-4 pb-2 pt-1">
177 <Show
178 when={view() === "account"}
179 fallback={<h2 class="text-base font-semibold">{t("nav.menu")}</h2>}
180 >
181 <button
182 type="button"
183 onClick={() => setView("nav")}
184 class="-ml-2 flex h-10 items-center gap-1 rounded-md pl-1 pr-2 text-base font-semibold outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
185 aria-label={`${t("common.back")} — ${t("nav.menu")}`}
186 >
187 <IconChevronLeft class="h-5 w-5" />
188 {t("nav.account")}
189 </button>
190 </Show>
191 <button
192 type="button"
193 ref={(el) => {
194 closeBtn = el;
195 }}
196 onClick={props.onClose}
197 aria-label={t("nav.close")}
198 class="topbar-control flex h-8 w-8 items-center justify-center rounded-md outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
199 >
200 <IconX class="h-4 w-4" />
201 </button>
202 </div>
203
204 {/* Both views share one grid cell and slide past each other; the
205 cell takes the taller view's height, so the sheet does not jump
206 when drilling in. `inert` keeps the off-screen view out of reach. */}
207 <div class="grid min-h-0 flex-1 overflow-hidden">
208 <div
209 inert={view() !== "nav"}
210 class={cn(
211 "flex min-h-0 flex-col transition-transform duration-300 ease-out [grid-area:1/1]",
212 view() === "nav" ? "translate-x-0" : "-translate-x-full",
213 )}
214 >
215 <div class="no-scrollbar min-h-0 flex-1 overflow-y-auto overscroll-contain px-2 pb-1">
216 <For each={groups()}>
217 {(group) => (
218 <div class="mt-1.5 border-t border-border/60 pt-1.5 first:mt-0 first:border-t-0 first:pt-0">
219 <p class="px-3 pb-0.5 pt-1 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
220 {t(group.labelKey)}
221 </p>
222 <div class="flex flex-col">
223 <For each={group.items}>
224 {(item) => {
225 const active = () => current()?.id === item.id;
226 const rowClass = () => cn(
227 "flex w-full items-center gap-2.5 rounded-md px-3 py-1.5 text-left transition-colors active:bg-muted",
228 active() ? "text-primary-text" : "text-foreground",
229 );
230 const content = (
231 <>
232 <span
233 class={cn(
234 "inline-flex size-7 shrink-0 items-center justify-center rounded-md",
235 active() ? "bg-primary/10 text-primary-text" : "bg-muted text-muted-foreground",
236 )}
237 >
238 <item.Icon class="h-4 w-4" />
239 </span>
240 <span class="min-w-0 flex-1 truncate text-[13px] font-medium">
241 {t(item.labelKey)}
242 </span>
243 <Show when={item.soon}>
244 <span class="shrink-0 rounded-full bg-muted px-1.5 py-0.5 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">
245 {t("nav.soon")}
246 </span>
247 </Show>
248 <Show when={badgeFor(item) > 0}>
249 <span class="flex h-5 min-w-5 items-center justify-center rounded-full bg-rose-500 px-1.5 text-[11px] font-bold text-white">
250 {badgeFor(item) > 99 ? "99+" : badgeFor(item)}
251 </span>
252 </Show>
253 </>
254 );
255 return (
256 <Show
257 when={!item.action}
258 fallback={
259 <button type="button" onClick={() => runAction(item)} class={rowClass()}>
260 {content}
261 </button>
262 }
263 >
264 <Link to={item.to} search={item.search as never} onClick={props.onClose} aria-current={active() ? "page" : undefined} class={rowClass()}>
265 {content}
266 </Link>
267 </Show>
268 );
269 }}
270 </For>
271 </div>
272 </div>
273 )}
274 </For>
275 </div>
276
277 <Show when={menu.user()}>
278 {(u) => (
279 <div class="shrink-0 border-t border-border/80 p-2">
280 <button
281 type="button"
282 class="flex h-12 w-full items-center gap-2.5 rounded-md px-2 text-left outline-hidden transition-colors active:bg-muted focus-visible:ring-2 focus-visible:ring-ring"
283 aria-label={t("nav.account")}
284 onClick={() => setView("account")}
285 >
286 <UserAvatar userId={u().id} name={accountDisplayName(u())} hasAvatar={menu.hasAvatar()} size="sm" />
287 <span class="min-w-0 flex-1">
288 <span class="block truncate text-[13px] font-semibold leading-4">{accountDisplayName(u())}</span>
289 <span class="block truncate text-[11px] font-medium text-muted-foreground">
290 {t(`role.${u().role}` as MessageKey)}
291 </span>
292 </span>
293 <IconChevronRight class="h-4 w-4 shrink-0 text-muted-foreground" />
294 </button>
295 </div>
296 )}
297 </Show>
298 </div>
299 <div
300 inert={view() !== "account"}
301 class={cn(
302 "no-scrollbar min-h-0 overflow-y-auto overscroll-contain transition-transform duration-300 ease-out [grid-area:1/1]",
303 view() === "account" ? "translate-x-0" : "translate-x-full",
304 )}
305 >
306 <MobileAccountPanel menu={menu} />
307 </div>
308 </div>
309 </div>
310 </div>
311 );
312}