import { useDirection } from "@base-ui/react/direction-provider";
import {
ArchiveIcon,
ArrowRightIcon,
BellIcon,
ChevronDownIcon,
EarthIcon,
FileAudioIcon,
FileTextIcon,
HouseIcon,
ImageIcon,
InfoIcon,
LayoutListIcon,
ListIcon,
type LucideIcon,
MapIcon,
MenuIcon,
PaperclipIcon,
SearchIcon,
SquarePenIcon,
Trash2Icon,
UserRoundIcon,
} from "lucide-react";
import { type ReactNode, useEffect } from "react";
import { Link, matchPath, useLocation, useNavigate, useSearchParams } from "react-router-dom";
import { MemoDetailSidebar } from "@/components/MemoDetailSidebar";
import { DEFAULT_SETTING_SECTION, SETTINGS_SECTIONS } from "@/components/Settings/settingSections";
import StatisticsView from "@/components/StatisticsView";
import UserMenu from "@/components/UserMenu";
import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { type AttachmentSection, type InboxFilter, useAppSidebar } from "@/contexts/AppSidebarContext";
import { useAuth } from "@/contexts/AuthContext";
import { useGlobalMemoEditor } from "@/contexts/GlobalMemoEditorContext";
import { useInstance } from "@/contexts/InstanceContext";
import { stringifyFilters, useMemoFilterContext } from "@/contexts/MemoFilterContext";
import { useSpaceContext } from "@/contexts/SpaceContext";
import { useAttachmentLibraryStats } from "@/hooks/useAttachmentLibrary";
import useCurrentUser from "@/hooks/useCurrentUser";
import { type MemoStatsContext, useFilteredMemoStats } from "@/hooks/useFilteredMemoStats";
import useMediaQuery from "@/hooks/useMediaQuery";
import { useNotifications, useUser } from "@/hooks/useUserQueries";
import { getMemoScopePath, isMemoScopeRoute, type PrimaryMemoScope, resolveMemoScope } from "@/lib/memo-views";
import { cn } from "@/lib/utils";
import { ROUTES } from "@/router/routes";
import { State } from "@/types/proto/api/v1/common_pb";
import { User_Role, UserNotification_Status } from "@/types/proto/api/v1/user_service_pb";
import { useTranslate } from "@/utils/i18n";
import MemosLogo from "../MemosLogo";
import CommonSidebarContent from "./CommonSidebarContent";
import { getSidebarRouteKind, routeSupportsCollectionScope } from "./routes";
import SidebarRow, { SIDEBAR_ROW_CLASSES, SIDEBAR_ROW_FOCUS_CLASSES, SidebarRowIconSlot, sidebarRowStateClasses } from "./SidebarRow";
import SidebarSection, { SIDEBAR_SECTION_STACK_CLASSES } from "./SidebarSection";
import SpaceSwitcher from "./SpaceSwitcher";
import TagsSection from "./TagsSection";
import ViewsSection from "./ViewsSection";
const SIDEBAR_HORIZONTAL_PADDING = "px-3";
const SIDEBAR_HEADER_ACTION_CLASSES = "size-7 shrink-0 rounded-md text-muted-foreground hover:text-foreground";
const NewMemoAction = ({ onClick }: { onClick: () => void }) => {
const t = useTranslate();
const label = t("editor.new-memo");
return (
}
>
{label}
);
};
const ProfileMode = () => {
const t = useTranslate();
const [searchParams, setSearchParams] = useSearchParams();
const { setMobileOpen } = useAppSidebar();
const active = searchParams.get("view") === "map" ? "map" : "memos";
const setMode = (mode: "memos" | "map") => {
setSearchParams((params) => {
mode === "map" ? params.set("view", "map") : params.delete("view");
return params;
});
setMobileOpen(false);
};
return (
setMode("memos")} />
setMode("map")} />
);
};
const CollectionSidebarContent = ({ context }: { context: MemoStatsContext }) => {
const t = useTranslate();
const location = useLocation();
const currentUser = useCurrentUser();
const { memoFilter, selectedSpaceName } = useSpaceContext();
const md = useMediaQuery("md");
const { mobileOpen, setMobileOpen } = useAppSidebar();
const { isInitialized: authInitialized } = useAuth();
const { isInitialized: instanceInitialized } = useInstance();
const profileMatch = matchPath("/u/:username", location.pathname);
const { data: profileUser } = useUser(profileMatch?.params.username ? `users/${profileMatch.params.username}` : "", {
enabled: context === "profile" && !!profileMatch?.params.username,
});
const statsUserName = context === "home" ? currentUser?.name : context === "profile" ? profileUser?.name : undefined;
// User-level collections stay aligned with their unscoped feeds even when a Space is remembered.
const isUserLevelCollection = context === "profile" || context === "archived";
const statsFilter = isUserLevelCollection ? undefined : memoFilter;
const { statistics, tags } = useFilteredMemoStats({
context,
userName: statsUserName,
filter: statsFilter,
enabled: authInitialized && instanceInitialized && (md || mobileOpen),
});
const showViews = !!currentUser && (context === "home" || context === "archived" || context === "explore");
// Off the collection routes (the library shown as fallback content), calendar and tag
// clicks must land somewhere that renders the filtered feed.
const onCollectionRoute = isMemoScopeRoute(location.pathname) || !!profileMatch;
const filterTarget = onCollectionRoute ? undefined : context === "explore" ? ROUTES.EXPLORE : ROUTES.HOME;
const tagStateScope = isUserLevelCollection
? (statsUserName ?? context)
: `${statsUserName ?? context}${selectedSpaceName ? `:${selectedSpaceName}` : ""}`;
return (
{context === "profile" &&
}
setMobileOpen(false)} />
{showViews &&
}
setMobileOpen(false)} />
);
};
const AttachmentsSidebarContent = () => {
const t = useTranslate();
const { memoFilter, selectedSpaceName } = useSpaceContext();
const { attachmentSection, setAttachmentSection, setMobileOpen } = useAppSidebar();
const { isComplete, stats } = useAttachmentLibraryStats(memoFilter);
const total = stats.media + stats.documents + stats.audio;
const rows: Array<{ value: AttachmentSection; icon: LucideIcon; label: string; count?: number }> = [
{ value: "all", icon: ListIcon, label: t("common.all"), count: isComplete ? total : undefined },
{ value: "media", icon: ImageIcon, label: t("attachment-library.tabs.media"), count: isComplete ? stats.media : undefined },
{ value: "audio", icon: FileAudioIcon, label: t("attachment-library.tabs.audio"), count: isComplete ? stats.audio : undefined },
{
value: "documents",
icon: FileTextIcon,
label: t("attachment-library.tabs.documents"),
count: isComplete ? stats.documents : undefined,
},
];
// Unlinked uploads do not belong to any Space, so "Unused" is only a Memos-level collection.
if (!selectedSpaceName) {
rows.push({
value: "unused",
icon: Trash2Icon,
label: t("attachment-library.labels.unused"),
count: isComplete ? stats.unused : undefined,
});
}
return (
{rows.map((row) => (
{
setAttachmentSection(row.value);
setMobileOpen(false);
}}
/>
))}
);
};
const InboxSidebarContent = () => {
const t = useTranslate();
const { inboxFilter, setInboxFilter, setMobileOpen } = useAppSidebar();
const { data: notifications = [] } = useNotifications();
const rows: Array<{ value: InboxFilter; icon: LucideIcon; label: string; count: number }> = [
{ value: "all", icon: ListIcon, label: t("common.all"), count: notifications.length },
{
value: "unread",
icon: BellIcon,
label: t("inbox.unread"),
count: notifications.filter((item) => item.status === UserNotification_Status.UNREAD).length,
},
{
value: "archived",
icon: ArchiveIcon,
label: t("common.archived"),
count: notifications.filter((item) => item.status === UserNotification_Status.ARCHIVED).length,
},
];
return (
{rows.map((row) => (
{
setInboxFilter(row.value);
setMobileOpen(false);
}}
/>
))}
);
};
const SettingsSidebarContent = () => {
const t = useTranslate();
const location = useLocation();
const user = useCurrentUser();
const { setMobileOpen } = useAppSidebar();
const isHost = user?.role === User_Role.ADMIN;
const currentSection = location.hash.slice(1) || DEFAULT_SETTING_SECTION;
const basic = SETTINGS_SECTIONS.filter((section) => section.scope === "basic");
const admin = SETTINGS_SECTIONS.filter((section) => section.scope === "admin");
const renderSections = (sections: typeof SETTINGS_SECTIONS) =>
sections.map((section) => (
setMobileOpen(false)}
className={cn(SIDEBAR_ROW_CLASSES, sidebarRowStateClasses(currentSection === section.key))}
>
{t(section.labelKey)}
));
return (
{renderSections(basic)}
{isHost && {renderSections(admin)}}
);
};
const MemoDetailSidebarContent = () => {
const { memoDetail } = useAppSidebar();
if (!memoDetail) return null;
return (
);
};
const RouteSidebarContent = () => {
const location = useLocation();
const kind = getSidebarRouteKind(location.pathname);
if (kind === "home" || kind === "archived" || kind === "explore" || kind === "profile") {
return ;
}
if (kind === "views") return ;
if (kind === "attachments") return ;
if (kind === "inbox") return ;
if (kind === "settings") return ;
if (kind === "memo") return ;
if (kind === "common") return ;
return null;
};
interface GlobalNavItem {
id: string;
label: string;
path: string;
icon: LucideIcon;
active: boolean;
count?: number;
}
/**
* Pills keep a constant px so the icon sits exactly where it does in the collapsed 30px
* square; all width change comes from the label column, which animates 0fr -> 1fr. That
* keeps the expand/collapse a single smooth motion with no padding jump.
*/
const navPillClasses = (active: boolean) =>
cn(
"relative flex h-[30px] min-w-0 items-center rounded-md px-[7px] transition-colors",
SIDEBAR_ROW_FOCUS_CLASSES,
sidebarRowStateClasses(active),
);
const NavPillLabel = ({ expanded, label, children }: { expanded: boolean; label: ReactNode; children?: ReactNode }) => (
{/* Content is shrink-0 so the collapsing track clips it in place — a plain
left-to-right reveal instead of re-truncating the label on every frame. */}
{label}
{children}
);
const GlobalNavigation = () => {
const t = useTranslate();
const location = useLocation();
const navigate = useNavigate();
const currentUser = useCurrentUser();
const { memoDetail, memoScope, setMemoScope, setMobileOpen } = useAppSidebar();
const { filters } = useMemoFilterContext();
const routeKind = getSidebarRouteKind(location.pathname);
const resolvedScope = resolveMemoScope(location.pathname, {
currentUsername: currentUser?.username,
detailFrom: memoDetail?.from,
memoArchived: memoDetail?.memo.state === State.ARCHIVED,
fallback: memoScope,
});
const primaryScope: PrimaryMemoScope = resolvedScope === "archived" ? memoScope : resolvedScope;
const routeOwnsPrimaryScope =
resolvedScope !== "archived" && (routeKind === "home" || routeKind === "explore" || routeKind === "profile" || routeKind === "memo");
const scopeRouteActive = routeKind === "home" || routeKind === "explore";
useEffect(() => {
if (routeOwnsPrimaryScope && primaryScope !== memoScope) {
setMemoScope(primaryScope);
}
}, [memoScope, primaryScope, routeOwnsPrimaryScope, setMemoScope]);
const scopeItems: Array<{ id: PrimaryMemoScope; label: string; icon: LucideIcon }> = [
{ id: "home", label: t("common.home"), icon: HouseIcon },
{ id: "explore", label: t("common.explore"), icon: EarthIcon },
];
const activeScopeItem = scopeItems.find((item) => item.id === primaryScope) ?? scopeItems[0];
const ActiveScopeIcon = activeScopeItem.icon;
const navigateToScope = (scope: PrimaryMemoScope) => {
const filterQuery = stringifyFilters(filters);
setMemoScope(scope);
navigate({ pathname: getMemoScopePath(scope), search: filterQuery ? `?filter=${filterQuery}` : "" });
setMobileOpen(false);
};
const items: GlobalNavItem[] = currentUser
? [
{
id: "attachments",
label: t("common.attachments"),
path: ROUTES.ATTACHMENTS,
icon: PaperclipIcon,
active: routeKind === "attachments",
},
]
: [
{
id: "explore",
label: t("common.explore"),
path: ROUTES.EXPLORE,
icon: EarthIcon,
active: routeKind === "explore" || routeKind === "profile" || routeKind === "memo",
},
{
id: "about",
label: t("common.about"),
path: ROUTES.ABOUT,
icon: InfoIcon,
active: Boolean(matchPath(ROUTES.ABOUT, location.pathname)),
},
];
// Keep one textual anchor in the compact navigator. A real active destination
// takes precedence; routes outside this navigation default to its first item
// without presenting that fallback as the current page.
const activeNavigatorItemId = currentUser && scopeRouteActive ? "scope" : items.find((item) => item.active)?.id;
const expandedNavigatorItemId = activeNavigatorItemId ?? (currentUser ? "scope" : items[0]?.id);
const scopeExpanded = expandedNavigatorItemId === "scope";
const scopeMenuContent = (
{scopeItems.map((item) => {
const Icon = item.icon;
return (
navigateToScope(item.id)}
>
{item.label}
);
})}
);
return (
);
};
/** The sidebar/header brand slot: collection scope on collection routes, instance brand elsewhere. */
const SidebarBrand = ({ className }: { className?: string }) => {
const currentUser = useCurrentUser();
const location = useLocation();
if (currentUser && routeSupportsCollectionScope(location.pathname)) {
return ;
}
return (
);
};
const AppSidebar = ({ className }: { className?: string }) => {
const t = useTranslate();
const currentUser = useCurrentUser();
const { setMobileOpen, setQuickFindOpen } = useAppSidebar();
const { canOpen: canCompose, openEditor } = useGlobalMemoEditor();
return (
);
};
export const MobileAppHeader = () => {
const { setMobileOpen } = useAppSidebar();
return (
);
};
export const MobileAppSidebar = () => {
const direction = useDirection();
const { mobileOpen, setMobileOpen } = useAppSidebar();
return (
Navigation
);
};
export default AppSidebar;