All files / src/components/layout nav-rail.tsx

100% Statements 95/95
100% Branches 78/78
100% Functions 33/33
100% Lines 82/82

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451                                                            7x       7x                 7x                 1454x                                     70x                                                                     1388x 1388x   1388x   1388x 66x         3x 3x                 1322x 60x                                   1262x                             298x                               69x 69x 69x 69x   2x         74x 74x                 97x 97x 184x         1750x                     91x 91x 926x 321x   605x 926x       342x                                                                             91x 91x 91x 91x 69x         91x       91x 69x 19x 19x 1x 1x       91x 74x     91x 81x 11x 4x   11x 11x       91x 81x 11x     91x   91x 337x 337x     329x     91x 4x         91x 2711x       91x 1487x             3x       91x 342x 342x 342x 1224x     342x 342x       4x                                                                         1224x           91x                           926x 605x 263x                                                                                  
import { Link } from "@tanstack/react-router";
import { ChevronDown, ExternalLink, LogOut } from "lucide-react";
import { type ReactNode, useEffect, useRef, useState } from "react";
import { useIsMobile } from "../../hooks/useIsMobile";
import { cn } from "../../lib/utils";
import {
	type NavActionId,
	type NavBadges,
	groupForPath,
	type ResolvedEntry,
	type ResolvedGroup,
	type ResolvedItem,
	resolveActiveHref,
} from "./nav-config";
 
/**
 * THE INDEX RED RULE.
 *
 * Index red marks the current item as a 3px inset bar and essentially nothing
 * else — never a filled block, which spends its scarcity. It is never used for
 * state (a status is a printed code in status ink; see the status primitives).
 *
 * `w-0.75` is 3px on the spacing scale (0.25rem × 0.75) and `secondary-500`
 * is the index-red token — #D23A1F in `@interioring/design-system`, still the
 * legacy sage until `styles/earthy-legacy.css` is deleted, which is the
 * reskin. Both constants live here so a grep for `secondary-` under
 * `components/layout/` returns exactly these two lines: the rail/tile marker
 * and the bottom-nav slot marker.
 */
export const INDEX_MARK =
	"before:absolute before:inset-y-0 before:left-0 before:w-0.75 before:bg-secondary-500 before:content-['']";
 
/** The same 3px bar on the top edge, for the mobile bottom-nav slot. */
export const INDEX_MARK_TOP =
	"before:absolute before:inset-x-0 before:top-0 before:h-0.75 before:bg-secondary-500 before:content-['']";
 
/**
 * A `.label`: caps, tabular, tight. The Job Book's section heads and counts.
 * (The design world's 620 weight and 80% width are Anek Latin axes, which the
 * portal now ships — phase 2.6. This is still the Tailwind scale rather than
 * the `.label` ramp class: switching the rail onto the two axes moves every
 * row's metrics and wants its own visual pass.)
 */
const LABEL = "text-xs font-semibold uppercase tracking-wide tabular-nums";
 
/**
 * Rows are the dense 32px tier, with the 44px floor kept ONLY under
 * `@media (pointer: coarse)` — a mouse does not need a 44px nav row, and
 * spending 12px of vertical rhythm on one is how the old rail stopped fitting
 * on a screen.
 */
function rowClass(opts: { active: boolean; indent: boolean }): string {
	return cn(
		"group relative flex min-h-8 w-full items-center gap-2 px-3.5 text-left text-sm transition-colors",
		"pointer-coarse:min-h-11",
		"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500",
		// Rows TINT on hover: ink at low alpha, so one value is right on every
		// ground in both themes. The −3px lift is reserved for draggable things.
		"hover:bg-foreground-default/7 hover:text-foreground-default",
		opts.indent && "pl-6",
		opts.active
			? cn(
					"bg-foreground-default/7 font-semibold text-foreground-default",
					INDEX_MARK,
				)
			: "text-foreground-muted",
	);
}
 
/** A count: `.label` tabular, right-aligned, NO PILL. */
function RowCount({ count }: { count: number }) {
	return (
		<span className={cn(LABEL, "ml-auto text-inherit")}>
			{count > 99 ? "99+" : count}
		</span>
	);
}
 
type RailRowProps = {
	item: ResolvedItem;
	active: boolean;
	count?: number;
	indent: boolean;
	onNavigate: () => void;
	onAction: (action: NavActionId) => void;
};
 
/**
 * The ONE row renderer.
 *
 * `sidebar.tsx` rendered a nav row six times over — a data-driven map plus
 * five hand-written one-offs (Social Studio, Admin Panel, Marketplace,
 * Feedback, Notifications), each with its own copy of the active/hover/badge
 * classes, and `admin-sidebar.tsx` had two more. All of it is this function.
 * Three element shapes are unavoidable (an internal link, an external anchor
 * and a button are different elements) but there is one class function and one
 * index bar.
 */
function RailRow({
	item,
	active,
	count,
	indent,
	onNavigate,
	onAction,
}: RailRowProps) {
	const className = rowClass({ active, indent });
	const label = <span className="truncate">{item.name}</span>;
	const badge =
		count !== undefined && count > 0 ? <RowCount count={count} /> : null;
 
	if (item.kind === "action") {
		return (
			<button
				type="button"
				className={className}
				onClick={() => {
					onNavigate();
					onAction(item.action);
				}}
			>
				{label}
				{badge}
			</button>
		);
	}
 
	if (item.kind === "external") {
		return (
			<a
				href={item.href}
				target="_blank"
				rel="noopener noreferrer"
				className={className}
				onClick={onNavigate}
			>
				{label}
				<ExternalLink
					className="ml-auto size-3.5 flex-none text-foreground-subtle"
					aria-hidden="true"
				/>
				<span className="sr-only">(opens in a new tab)</span>
			</a>
		);
	}
 
	return (
		<Link
			to={item.href}
			onClick={onNavigate}
			aria-current={active ? "page" : undefined}
			className={className}
		>
			{label}
			{badge}
		</Link>
	);
}
 
/** A hairline. Not a box. */
function RailDivider() {
	return (
		<hr className="mx-3.5 my-1 h-0 border-0 border-t border-border-default" />
	);
}
 
/**
 * Which groups are folded is resolved in two layers: an explicit choice the
 * user made by clicking a head (remembered across visits), and underneath it
 * the group that owns the current page. Only the choices are stored — the
 * active group is DERIVED — so a week of browsing does not slowly re-expand
 * the whole rail. This is the one thing the old admin rail got right; it is
 * carried over verbatim in behaviour.
 */
type GroupChoices = Record<string, boolean>;
 
function readChoices(storageKey: string): GroupChoices {
	try {
		const raw = localStorage.getItem(storageKey);
		const parsed: unknown = raw ? JSON.parse(raw) : {};
		return parsed && typeof parsed === "object" ? (parsed as GroupChoices) : {};
	} catch {
		return {};
	}
}
 
function writeChoices(storageKey: string, choices: GroupChoices): void {
	try {
		localStorage.setItem(storageKey, JSON.stringify(choices));
	} catch {
		// Private mode or storage disabled: the rail still folds, it just stops
		// remembering.
	}
}
 
/** Initials for the footer identity block. Two words at most. */
export function initialsOf(name: string | null | undefined): string {
	const words = (name ?? "").trim().split(/\s+/).filter(Boolean).slice(0, 2);
	if (words.length === 0) return "?";
	return words.map((word) => word.charAt(0).toUpperCase()).join("");
}
 
/** A row's identity, for React keys. */
function itemKey(item: ResolvedItem): string {
	return item.kind === "action" ? item.action : item.href;
}
 
/**
 * Keys for a flat list that includes dividers, which have no identity of
 * their own: a divider is named after the row above it, so the key is stable
 * across re-renders and across role changes (an array index is neither).
 */
function keyedEntries(
	entries: ResolvedEntry[],
): { key: string; entry: ResolvedEntry }[] {
	let previous = "top";
	return entries.map((entry) => {
		if (entry.kind === "divider") {
			return { key: `divider-after-${previous}`, entry };
		}
		previous = entry.kind === "group" ? entry.name : itemKey(entry);
		return { key: previous, entry };
	});
}
 
const slug = (value: string) => value.toLowerCase().replace(/[^a-z0-9]+/g, "-");
 
export type NavRailIdentity = {
	name: string;
	/** The second line: `Owner · Live`, `Platform admin`. */
	meta: string;
};
 
export type NavRailProps = {
	/** Already role-resolved — see `resolveNav`. */
	entries: ResolvedEntry[];
	currentPath: string;
	badges?: NavBadges;
	/** Where the folds are remembered. One key per rail. */
	storageKey: string;
	ariaLabel: string;
	identity: NavRailIdentity;
	onSignOut: () => void;
	onAction?: (action: NavActionId) => void;
	/** Drawer state. On `lg` and up the rail is static and always visible. */
	isOpen: boolean;
	onClose: () => void;
	/** Rendered above the footer — push/install prompts, and nothing else. */
	children?: ReactNode;
};
 
export function NavRail({
	entries,
	currentPath,
	badges,
	storageKey,
	ariaLabel,
	identity,
	onSignOut,
	onAction,
	isOpen,
	onClose,
	children,
}: NavRailProps) {
	const railRef = useRef<HTMLDivElement>(null);
	const activeHref = resolveActiveHref(entries, currentPath);
	const activeGroup = groupForPath(entries, currentPath);
	const [choices, setChoices] = useState<GroupChoices>(() =>
		readChoices(storageKey),
	);
	// Folding exists to make the DESKTOP rail fit on one screen. On a phone the
	// drawer covers the screen anyway, and a fold there only adds a tap before
	// every destination — so the drawer always shows everything.
	const isMobile = useIsMobile();
 
	// Arriving in a group you had folded drops that one choice, so the page you
	// are on is never hidden. Other choices are untouched.
	useEffect(() => {
		if (!activeGroup) return;
		setChoices((previous) => {
			if (previous[activeGroup] !== false) return previous;
			const { [activeGroup]: _dropped, ...rest } = previous;
			return rest;
		});
	}, [activeGroup]);
 
	useEffect(() => {
		writeChoices(storageKey, choices);
	}, [storageKey, choices]);
 
	useEffect(() => {
		if (!isOpen) return;
		const onKeyDown = (event: KeyboardEvent) => {
			if (event.key === "Escape") onClose();
		};
		document.addEventListener("keydown", onKeyDown);
		return () => document.removeEventListener("keydown", onKeyDown);
	}, [isOpen, onClose]);
 
	// Focus the first destination when the drawer opens.
	useEffect(() => {
		if (!isOpen) return;
		railRef.current?.querySelector<HTMLAnchorElement>("nav a")?.focus();
	}, [isOpen]);
 
	const counts: NavBadges = badges ?? {};
 
	const isGroupOpen = (group: ResolvedGroup): boolean => {
		const choice = choices[group.name];
		if (choice !== undefined) return choice;
		// Sections stand open; a submenu (`Settings ▾`) stays shut until it owns
		// the page, because its five rows are not the daily work.
		return group.style === "section" || group.name === activeGroup;
	};
 
	const toggleGroup = (group: ResolvedGroup) =>
		setChoices((previous) => ({
			...previous,
			[group.name]: !isGroupOpen(group),
		}));
 
	const countFor = (item: ResolvedItem): number | undefined =>
		item.kind === "action" || item.kind === "external" || !item.badge
			? undefined
			: counts[item.badge];
 
	const renderItem = (item: ResolvedItem, indent: boolean) => (
		<RailRow
			key={itemKey(item)}
			item={item}
			active={item.kind === "link" && item.href === activeHref}
			count={countFor(item)}
			indent={indent}
			onNavigate={onClose}
			onAction={(action) => onAction?.(action)}
		/>
	);
 
	const renderGroup = (group: ResolvedGroup) => {
		const open = isMobile || isGroupOpen(group);
		const listId = `nav-rail-group-${slug(group.name)}`;
		const rolledUp = group.items.reduce(
			(total, item) => total + (countFor(item) ?? 0),
			0,
		);
		const isSection = group.style === "section";
		return (
			<div key={group.name}>
				<button
					type="button"
					onClick={() => toggleGroup(group)}
					aria-expanded={open}
					aria-controls={listId}
					data-testid={`nav-rail-group-${group.name}`}
					className={
						isSection
							? cn(
									LABEL,
									"flex min-h-8 w-full items-center gap-1.5 px-3.5 pt-1.5 pb-0.5 text-left text-foreground-subtle transition-colors",
									"pointer-coarse:min-h-11",
									"hover:text-foreground-default focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500",
									group.name === activeGroup && "text-foreground-default",
								)
							: rowClass({ active: false, indent: false })
					}
				>
					<span className="truncate">{group.name}</span>
					<span className="ml-auto flex items-center gap-1.5">
						{/* Folded, the group's counts roll up to its head, so a fold
						    never hides the fact that something needs attention. */}
						{!open && rolledUp > 0 && <span className={LABEL}>{rolledUp}</span>}
						<ChevronDown
							aria-hidden="true"
							className={cn(
								"size-3.5 flex-none text-foreground-subtle transition-transform duration-200",
								!open && "-rotate-90",
							)}
						/>
					</span>
					{!open && (
						<span className="sr-only">
							collapsed, {group.items.length} items
							{rolledUp > 0 ? `, ${rolledUp} need attention` : ""}
						</span>
					)}
				</button>
				<div id={listId} hidden={!open}>
					{group.items.map((item) => renderItem(item, isSection))}
				</div>
			</div>
		);
	};
 
	return (
		<div
			ref={railRef}
			className={cn(
				// 232px — the rail width in the mockup (`--rail-w`).
				"fixed inset-y-0 left-0 z-50 flex w-58 flex-col border-r border-border-default bg-background-subtle transition-transform duration-300 ease-in-out lg:static lg:translate-x-0",
				isOpen ? "translate-x-0" : "-translate-x-full",
			)}
		>
			<nav
				aria-label={ariaLabel}
				className="flex flex-1 flex-col overflow-y-auto py-2"
			>
				{keyedEntries(entries).map(({ key, entry }) => {
					if (entry.kind === "divider") return <RailDivider key={key} />;
					if (entry.kind === "group") return renderGroup(entry);
					return renderItem(entry, false);
				})}
 
				<div className="flex-1" />
				{children}
			</nav>
 
			{/* The footer identity block: initials, name, `Owner · Live`. */}
			<div className="border-t border-border-default px-3.5 py-3">
				<div className="flex items-center gap-2">
					<span
						aria-hidden="true"
						className={cn(
							LABEL,
							"flex size-8 flex-none items-center justify-center rounded-full bg-primary-100 text-primary-700",
						)}
					>
						{initialsOf(identity.name)}
					</span>
					<span className="min-w-0 flex-1">
						<span className="block truncate text-sm font-medium text-foreground-default">
							{identity.name}
						</span>
						<span className={cn(LABEL, "block truncate text-foreground-muted")}>
							{identity.meta}
						</span>
					</span>
					<button
						type="button"
						onClick={onSignOut}
						title="Sign out"
						className="flex size-6 flex-none items-center justify-center text-foreground-subtle transition-colors hover:text-foreground-default pointer-coarse:size-11"
					>
						<LogOut className="size-4" aria-hidden="true" />
						<span className="sr-only">Sign out</span>
					</button>
				</div>
			</div>
		</div>
	);
}