import { useDirection } from "@base-ui/react/direction-provider"; import { useQueryClient } from "@tanstack/react-query"; import { ArchiveIcon, ArrowRightIcon, BellIcon, ChevronDownIcon, EarthIcon, FileAudioIcon, FileTextIcon, HouseIcon, ImageIcon, InfoIcon, LayoutListIcon, ListIcon, type LucideIcon, MapIcon, MenuIcon, MoreHorizontalIcon, PaperclipIcon, PlusIcon, SearchIcon, SquarePenIcon, Trash2Icon, UserRoundIcon, } from "lucide-react"; import { type ReactNode, useEffect, useState } from "react"; import toast from "react-hot-toast"; import { Link, matchPath, useLocation, useNavigate, useSearchParams } from "react-router-dom"; import ConfirmDialog from "@/components/ConfirmDialog"; import { MemoDetailSidebar } from "@/components/MemoDetailSidebar"; import MemoDisplaySettingMenu from "@/components/MemoDisplaySettingMenu"; 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 { memoViewServiceClient } from "@/connect"; 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 { useMemoViews, useNotifications, userKeys, useUser } from "@/hooks/useUserQueries"; import { handleError } from "@/lib/error"; import { BUILTIN_TASKS_VIEW_ID, getMemoScopePath, getMemoViewId, 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 type { MemoView } from "@/types/proto/api/v1/memo_view_service_pb"; import { User_Role, UserNotification_Status } from "@/types/proto/api/v1/user_service_pb"; import { useTranslate } from "@/utils/i18n"; import MemosLogo from "../MemosLogo"; import { getSidebarRouteKind, routeSupportsCollectionScope } from "./routes"; import SidebarRow, { SIDEBAR_ROW_CLASSES, SIDEBAR_ROW_FOCUS_CLASSES, SIDEBAR_ROW_ICON_CLASSES, sidebarRowStateClasses } from "./SidebarRow"; import SidebarSection, { SIDEBAR_SECTION_ACTION_BUTTON_CLASSES, SIDEBAR_SECTION_ACTION_ICON_CLASSES, SIDEBAR_SECTION_STACK_CLASSES, } from "./SidebarSection"; import SpaceSwitcher from "./SpaceSwitcher"; import TagsSection from "./TagsSection"; 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 ViewsSection = ({ manageActive = false }: { manageActive?: boolean }) => { const t = useTranslate(); const navigate = useNavigate(); const currentUser = useCurrentUser(); const queryClient = useQueryClient(); const { data: memoViews = [] } = useMemoViews(currentUser?.name); const { memoView: selectedMemoView, setMemoView } = useMemoFilterContext(); const { setMobileOpen } = useAppSidebar(); const [deleteTarget, setDeleteTarget] = useState(); const location = useLocation(); const handleView = (viewId: string) => { setMemoView(selectedMemoView === viewId ? undefined : viewId); if (!isMemoScopeRoute(location.pathname)) navigate(ROUTES.HOME); setMobileOpen(false); }; const handleCreate = () => { navigate(ROUTES.VIEWS, { state: { openCreate: true } }); setMobileOpen(false); }; const handleDelete = async () => { if (!deleteTarget) return; try { await memoViewServiceClient.deleteMemoView({ name: deleteTarget.name }); await queryClient.invalidateQueries({ queryKey: userKeys.memoViews(currentUser?.name) }); if (selectedMemoView === getMemoViewId(deleteTarget.name)) setMemoView(undefined); toast.success(t("setting.memo-view.delete-success", { title: deleteTarget.title })); } catch (error: unknown) { handleError(error, toast.error, { context: "Delete memo view" }); } finally { setDeleteTarget(undefined); } }; return ( ) } > handleView(BUILTIN_TASKS_VIEW_ID)} /> {memoViews.map((memoView) => { const id = getMemoViewId(memoView.name); const active = !manageActive && selectedMemoView === id; return (
} > { navigate(ROUTES.VIEWS, { state: { memoView } }); setMobileOpen(false); }} > {t("common.edit")} setDeleteTarget(memoView)}> {t("common.delete")}
); })} {manageActive && } !open && setDeleteTarget(undefined)} title={t("setting.memo-view.delete-confirm", { title: deleteTarget?.title ?? "" })} confirmLabel={t("common.delete")} cancelLabel={t("common.cancel")} onConfirm={handleDelete} confirmVariant="destructive" />
); }; 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 ; return null; }; interface GlobalNavItem { id: string; label: string; path: string; icon: LucideIcon; active: boolean; count?: number; alwaysExpanded?: boolean; } /** * 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", alwaysExpanded: true, }, { id: "about", label: t("common.about"), path: ROUTES.ABOUT, icon: InfoIcon, active: Boolean(matchPath(ROUTES.ABOUT, location.pathname)), }, ]; 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;