Skip to content

A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!

15.2 KB
Raw Blame
import type { NewDocumentContext } from "@/features/documents/new-document-dialog";
import type { IconName } from "@reactive-resume/ui/components/icon";
import type { ReactNode } from "react";
import { i18n } from "@lingui/core";
import { t } from "@lingui/core/macro";
import { Trans, useLingui } from "@lingui/react/macro";
import { useHotkey } from "@tanstack/react-hotkeys";
import { useQuery } from "@tanstack/react-query";
import { Link, useMatchRoute, useNavigate, useRouterState } from "@tanstack/react-router";
import { useCallback } from "react";
import { Avatar, AvatarFallback, AvatarImage } from "@reactive-resume/ui/components/avatar";
import { BrandIcon } from "@reactive-resume/ui/components/brand-icon";
import { Button } from "@reactive-resume/ui/components/button";
import { Icon } from "@reactive-resume/ui/components/icon";
import { ariaShortcut, formatShortcut, Kbd } from "@reactive-resume/ui/components/kbd";
import { Tooltip, TooltipContent, TooltipTrigger } from "@reactive-resume/ui/components/tooltip";
import { useBreakpoint } from "@reactive-resume/ui/hooks/use-breakpoint";
import { getInitials } from "@reactive-resume/utils/string";
import { cn } from "@reactive-resume/utils/style";
import { MobileTabIndicator } from "@/components/layout/mobile-tab-indicator";
import { useDialogStore } from "@/dialogs/store";
import { GuestBanner } from "@/features/auth/components/guest-banner";
import { useCommandPaletteStore } from "@/features/command-palette/store";
import { DocumentLibraryProvider } from "@/features/documents/library-session";
import { shortcutOverlayOpen } from "@/features/keyboard-shortcuts/blocking";
import { useShortcutSettings } from "@/features/keyboard-shortcuts/settings";
import { isEditableElementFocused } from "@/features/resume/builder/draft";
import { UserDropdownMenu } from "@/features/user/dropdown-menu";
import { orpc } from "@/libs/orpc/client";

type NavItem = {
	to: "/dashboard" | "/dashboard/applications" | "/dashboard/career" | "/dashboard/trash" | "/dashboard/settings";
	icon: IconName;
	label: string;
	count?: number;
};

function useNavItems() {
	const matchRoute = useMatchRoute();
	const { data: counts } = useQuery(orpc.documents.counts.queryOptions());
	const { data: applicationStats } = useQuery(orpc.applications.stats.queryOptions({}));
	const { data: notifications } = useQuery(orpc.career.notifications.queryOptions({ input: {} }));

	const items: NavItem[] = [
		{
			to: "/dashboard",
			icon: "file-text",
			label: t`Documents`,
			...(counts ? { count: counts.resume + counts.letter } : {}),
		},
		{
			to: "/dashboard/applications",
			icon: "briefcase",
			label: t`Applications`,
			...(applicationStats
				? {
						count: applicationStats.byStage
							.filter((row) => row.status !== "closed")
							.reduce((total, row) => total + row.count, 0),
					}
				: {}),
		},
	];
	const unread = notifications?.filter((notification) => !notification.readAt).length ?? 0;
	// Career counts what's waiting for the user (unread notifications), so nothing shows at zero.
	items.push({ to: "/dashboard/career", icon: "compass", label: t`Career`, ...(unread ? { count: unread } : {}) });
	const settings: NavItem = { to: "/dashboard/settings", icon: "gear-six", label: t`Settings` };
	// Trash shows while it holds something, and stays while it's open, even once its last document is restored.
	const inTrash = Boolean(matchRoute({ to: "/dashboard/trash" }));
	const trash: NavItem | null =
		counts?.trash || inTrash
			? { to: "/dashboard/trash", icon: "trash", label: t`Trash`, ...(counts?.trash ? { count: counts.trash } : {}) }
			: null;

	return { items, settings, trash };
}

/** Whether the item is the current page: Documents is exact, the others match their section. */
function useIsCurrent() {
	const matchRoute = useMatchRoute();
	return (to: NavItem["to"]) => Boolean(matchRoute({ to, fuzzy: to !== "/dashboard" }));
}

type ApplicationsSearch = {
	q: string;
	view: "list" | "board" | "insights" | "calendar";
	closed: boolean;
	create: boolean;
	applicationId?: string;
};

/** New follows the section: Applications saves a job, Letters starts a letter, and the rest offers every object. */
function useNewAction() {
	const navigate = useNavigate();
	const matchRoute = useMatchRoute();
	const location = useRouterState({ select: (state) => state.location });
	const openDialog = useDialogStore((state) => state.openDialog);

	const context: NewDocumentContext = matchRoute({ to: "/dashboard/applications", fuzzy: true })
		? "applications"
		: matchRoute({ to: "/dashboard/career", fuzzy: true })
			? "career"
			: new URLSearchParams(location.searchStr).get("type") === "letter"
				? "letters"
				: "documents";

	return useCallback(() => {
		// The application page owns Save job; its one-shot ?create link opens that dialog.
		if (context === "applications") {
			if (location.pathname === "/dashboard/applications") {
				// Keep the current view, search and closed filter when the page is already open.
				void navigate({
					to: "/dashboard/applications",
					search: (previous: ApplicationsSearch) => ({ ...previous, create: true }),
				});
			} else {
				void navigate({ to: "/dashboard/applications", search: { create: true } });
			}
			return;
		}
		openDialog("document.new", context === "documents" ? undefined : { context });
	}, [context, location.pathname, navigate, openDialog]);
}

/**
 * The app shell for Documents, Trash, Applications and Settings: a 240px sidebar at ≥1024, an icon rail at
 * 640–1023 and a bottom tab bar below 640. An application's workspace is full screen on phones, with its own back
 * link and action bar, so it has no tab bar. N opens New anywhere outside a field.
 */
type AppShellProps = { children: ReactNode };

export function AppShell({ children }: AppShellProps) {
	const { t } = useLingui();
	const breakpoint = useBreakpoint();
	const openNew = useNewAction();
	const characterShortcuts = useShortcutSettings((state) => state.characterShortcuts);
	const matchRoute = useMatchRoute();
	const tabs =
		breakpoint === "mobile" && !matchRoute({ to: "/dashboard/applications/$applicationId/{-$tab}", fuzzy: true });

	useHotkey(
		"N",
		() => {
			if (isEditableElementFocused() || shortcutOverlayOpen()) return;
			openNew();
		},
		{ enabled: characterShortcuts, meta: { name: t`New` } },
	);

	return (
		<div
			className={cn(
				"grid min-h-svh bg-bg",
				breakpoint === "mobile"
					? tabs
						? "grid-rows-[minmax(0,1fr)_auto]"
						: ""
					: breakpoint === "tablet"
						? "grid-cols-[64px_minmax(0,1fr)]"
						: "grid-cols-[240px_minmax(0,1fr)]",
			)}
		>
			<a
				href="#main-content"
				className="sr-only rounded-md bg-raised px-4 py-2 text-sm focus:not-sr-only focus:absolute focus:inset-s-2 focus:top-2 focus:z-[100]"
			>
				<Trans>Skip to main content</Trans>
			</a>
			{breakpoint !== "mobile" && (breakpoint === "tablet" ? <Rail /> : <Sidebar />)}
			<main id="main-content" className="min-w-0">
				<GuestBanner />
				<DocumentLibraryProvider>{children}</DocumentLibraryProvider>
			</main>
			{tabs && <MobileTabs />}
		</div>
	);
}

function Sidebar() {
	const characterShortcuts = useShortcutSettings((state) => state.characterShortcuts);
	const { items, settings, trash } = useNavItems();
	const isCurrent = useIsCurrent();
	const openPalette = useCommandPaletteStore((state) => state.setOpen);
	const openNew = useNewAction();

	return (
		<aside
			aria-label={t`App navigation`}
			className="sticky top-0 flex h-svh flex-col gap-3 border-e border-line bg-surface p-3 [view-transition-name:app-nav]"
		>
			<Link to="/" className="flex h-9 items-center gap-2.5 px-1.5">
				<BrandIcon variant="icon" alt="" className="size-6 shrink-0" />
				<span className="text-sm font-semibold">Reactive Resume</span>
			</Link>

			<button
				type="button"
				aria-label={t`Search or run a command…`}
				aria-keyshortcuts={ariaShortcut("⌘K")}
				onClick={() => openPalette(true)}
				className="flex h-[34px] items-center gap-2 rounded-lg border border-line bg-bg px-2.5 text-sm text-ink-3 transition-colors duration-quick hover:text-ink-2"
			>
				<Icon name="magnifying-glass" size={18} />
				<span className="flex-1 text-start">
					<Trans>Search or run a command…</Trans>
				</span>
				<Kbd>{formatShortcut("⌘K")}</Kbd>
			</button>

			<nav aria-label={t`App`} className="grid gap-0.5">
				{items.map((item) => (
					<NavLink key={item.to} item={item} current={isCurrent(item.to)} />
				))}
				<div className="mt-2 border-t border-line pt-2">
					<NavLink item={settings} current={isCurrent(settings.to)} />
				</div>
			</nav>

			<div className="mt-auto grid gap-2">
				{trash && <NavLink item={trash} current={isCurrent(trash.to)} />}
				{/* Secondary, so each view's own primary action is the one accent button on screen. */}
				<Button
					data-document-new-trigger=""
					variant="secondary"
					aria-label={t`New`}
					aria-keyshortcuts={characterShortcuts ? "N" : undefined}
					className="h-9 justify-between"
					onClick={openNew}
				>
					<span className="flex items-center gap-1.5">
						<Icon name="plus" />
						<Trans>New</Trans>
					</span>
					{characterShortcuts && <Kbd>N</Kbd>}
				</Button>
				<UserDropdownMenu>
					{({ session }) => (
						<button
							type="button"
							className="flex h-11 items-center gap-2.5 rounded-lg px-1.5 text-start transition-colors duration-quick hover:bg-hover"
						>
							<Avatar className="size-7">
								<AvatarImage src={session.user.image ?? undefined} />
								<AvatarFallback>{getInitials(session.user.name)}</AvatarFallback>
							</Avatar>
							<span className="grid min-w-0">
								<span className="truncate text-sm font-medium">{session.user.name}</span>
								<span className="text-xs text-ink-3">
									<Trans>Account</Trans>
								</span>
							</span>
						</button>
					)}
				</UserDropdownMenu>
			</div>
		</aside>
	);
}

function NavLink({ item, current }: { item: NavItem; current: boolean }) {
	return (
		<Link
			to={item.to}
			aria-current={current ? "page" : undefined}
			className={cn(
				"flex h-[34px] items-center gap-2.5 rounded-lg px-2.5 text-sm transition-[background-color,color,scale] duration-quick ease-enter active:scale-[0.97]",
				current ? "bg-sunken font-medium text-ink" : "text-ink-2 hover:bg-hover hover:text-ink",
			)}
		>
			<Icon name={item.icon} filled={current} />
			<span className="flex-1">{item.label}</span>
			{item.count ? <span className="font-mono text-xs text-ink-3">{i18n.number(item.count)}</span> : null}
		</Link>
	);
}

/** Tablets: the same destinations as icons, with their names in tooltips. */
function Rail() {
	const { items, settings, trash } = useNavItems();
	const isCurrent = useIsCurrent();
	const openPalette = useCommandPaletteStore((state) => state.setOpen);
	const openNew = useNewAction();

	return (
		<aside
			aria-label={t`App navigation`}
			className="sticky top-0 flex h-svh flex-col items-center gap-2 border-e border-line bg-surface py-3 [view-transition-name:app-nav]"
		>
			<Link to="/" aria-label="Reactive Resume" className="mb-1 grid size-8 place-items-center rounded-md">
				<BrandIcon variant="icon" alt="" className="size-6" />
			</Link>
			<RailTip label={t`Search`} icon="magnifying-glass">
				<button
					type="button"
					aria-label={t`Search or run a command…`}
					onClick={() => openPalette(true)}
					className="grid size-10 place-items-center rounded-lg text-ink-2 transition-[background-color,scale] duration-quick ease-enter hover:bg-hover active:scale-[0.97]"
				/>
			</RailTip>
			<nav aria-label={t`App`} className="grid gap-1">
				{[...items, settings].map((item) => (
					<RailTip key={item.to} label={item.label} icon={item.icon} filled={isCurrent(item.to)}>
						<Link
							to={item.to}
							aria-label={item.label}
							aria-current={isCurrent(item.to) ? "page" : undefined}
							className={cn(
								"grid size-10 place-items-center rounded-lg transition-[background-color,color,scale] duration-quick ease-enter active:scale-[0.97]",
								isCurrent(item.to) ? "bg-sunken text-ink" : "text-ink-2 hover:bg-hover",
							)}
						/>
					</RailTip>
				))}
			</nav>
			<div className="mt-auto grid justify-items-center gap-2">
				{trash && (
					<RailTip label={trash.label} icon={trash.icon}>
						<Link
							to={trash.to}
							aria-label={t`Trash`}
							className="grid size-10 place-items-center rounded-lg text-ink-2 transition-[background-color,scale] duration-quick ease-enter hover:bg-hover active:scale-[0.97]"
						/>
					</RailTip>
				)}
				<RailTip label={t`New`} icon="plus">
					<Button data-document-new-trigger="" size="icon" aria-label={t`New`} onClick={openNew} />
				</RailTip>
				<UserDropdownMenu>
					{({ session }) => (
						<button type="button" aria-label={t`Account`} className="rounded-sm">
							<Avatar className="size-8">
								<AvatarImage src={session.user.image ?? undefined} />
								<AvatarFallback>{getInitials(session.user.name)}</AvatarFallback>
							</Avatar>
						</button>
					)}
				</UserDropdownMenu>
			</div>
		</aside>
	);
}

/** A rail button: its icon inside the given trigger, and its name in a tooltip. */
function RailTip({
	label,
	icon,
	filled = false,
	children,
}: {
	label: string;
	icon: IconName;
	filled?: boolean;
	children: React.ReactElement;
}) {
	return (
		<Tooltip>
			<TooltipTrigger render={children}>
				<Icon name={icon} filled={filled} />
			</TooltipTrigger>
			<TooltipContent side="right">{label}</TooltipContent>
		</Tooltip>
	);
}

/** Phones: Documents · Applications · New · Career · Settings, with New as an accent pill in the middle. */
function MobileTabs() {
	const isCurrent = useIsCurrent();
	const openNew = useNewAction();
	const tabs: Pick<NavItem, "to" | "icon" | "label">[] = [
		{ to: "/dashboard", icon: "file-text", label: t`Documents` },
		{ to: "/dashboard/applications", icon: "briefcase", label: t`Applications` },
		{ to: "/dashboard/career", icon: "compass", label: t`Career` },
		{ to: "/dashboard/settings", icon: "gear-six", label: t`Settings` },
	];

	const link = ({ to, icon, label }: (typeof tabs)[number]) => {
		const current = isCurrent(to);

		return (
			<Link
				key={to}
				to={to}
				aria-current={current ? "page" : undefined}
				viewTransition={false}
				className="relative flex min-h-[52px] flex-col items-center justify-center gap-0.5 transition-[scale] duration-quick ease-enter active:scale-[0.97]"
			>
				{current && <MobileTabIndicator />}
				<Icon name={icon} size={24} filled={current} />
				<span
					className={cn(
						"text-center text-xs [overflow-wrap:anywhere]",
						current ? "font-semibold text-ink" : "text-ink-2",
					)}
				>
					{label}
				</span>
			</Link>
		);
	};

	return (
		<nav
			aria-label={t`App`}
			className="sticky bottom-0 z-30 grid grid-cols-5 border-t border-line bg-surface pb-[env(safe-area-inset-bottom)] [view-transition-name:app-nav]"
		>
			{tabs.slice(0, 2).map(link)}
			<button
				type="button"
				data-document-new-trigger=""
				onClick={openNew}
				className="flex min-h-[52px] flex-col items-center justify-center gap-0.5 transition-[scale] duration-quick ease-enter active:scale-[0.97]"
			>
				<span className="grid h-[26px] w-[34px] place-items-center rounded-sm bg-accent text-on-accent">
					<Icon name="plus" size={20} />
				</span>
				<span className="text-center text-xs [overflow-wrap:anywhere] text-ink-2">
					<Trans>New</Trans>
				</span>
			</button>
			{tabs.slice(2).map(link)}
		</nav>
	);
}