Skip to content

armgit / memos

Public Imported from GitHub
0

Memos is an open-source, self-hosted note-taking app that brings your everyday thoughts together in a personal timeline. Your data stays yours, and you choose what to keep private or share.

chore: open calendar and map to guests, simplify navigation

boojack153625210baa
diff --git a/web/src/components/AppSidebar/AppSidebar.tsx b/web/src/components/AppSidebar/AppSidebar.tsx
index e466317b6..bededb803 100644
--- a/web/src/components/AppSidebar/AppSidebar.tsx
+++ b/web/src/components/AppSidebar/AppSidebar.tsx
@@ -7,7 +7,6 @@ import {
FileAudioIcon,
FileTextIcon,
ImageIcon,
- InfoIcon,
LibraryIcon,
ListIcon,
type LucideIcon,
@@ -20,7 +19,7 @@ import {
UserRoundIcon,
} from "lucide-react";
import { useRef } from "react";
-import { Link, matchPath, useLocation } from "react-router-dom";
+import { Link, useLocation } from "react-router-dom";
import { MAP_MEMO_FILTER } from "@/components/MapView/useMapMemos";
import { MemoDetailSidebar } from "@/components/MemoDetailSidebar";
import MemoDisplaySettingMenu from "@/components/MemoDisplaySettingMenu";
@@ -41,7 +40,7 @@ import useMediaQuery from "@/hooks/useMediaQuery";
import { useNotifications } from "@/hooks/useUserQueries";
import { combineCELFilters } from "@/lib/cel-filter";
import { cn } from "@/lib/utils";
-import { collectionNavigationPath, ROUTES, resolveCollectionRoute } from "@/router/routes";
+import { collectionNavigationPath, ROUTES } from "@/router/routes";
import { User_Role, UserNotification_Status } from "@/types/proto/api/v1/user_service_pb";
import { useTranslate } from "@/utils/i18n";
import CommonSidebarContent from "./CommonSidebarContent";
@@ -268,12 +267,22 @@ const RouteSidebarContent = () => {
return null;
};
-interface GlobalNavItem {
- id: string;
+/** Collection views beside Timeline. Attachments is a library of the user's own files, so guests get the reading views only. */
+const NAV_DESTINATIONS = [
+ { kind: "calendar", labelKey: "common.calendar", pathname: ROUTES.CALENDAR, icon: CalendarDaysIcon, signedInOnly: false },
+ { kind: "map", labelKey: "common.map", pathname: ROUTES.MAP, icon: MapIcon, signedInOnly: false },
+ { kind: "attachments", labelKey: "common.attachments", pathname: ROUTES.ATTACHMENTS, icon: PaperclipIcon, signedInOnly: true },
+] as const;
+
+interface NavPillProps {
label: string;
- path: string;
icon: LucideIcon;
- active: boolean;
+ /** A link when set; otherwise a button that runs `onClick`. */
+ to?: string;
+ onClick?: () => void;
+ active?: boolean;
+ expanded?: boolean;
+ className?: string;
}
/**
@@ -286,143 +295,86 @@ interface GlobalNavItem {
* page stays a filled square with its tooltip, leaving room for the other actions.
* Timeline's trailing arrow shares its surface, with a separate click target.
*/
-const navPillClasses = (active: boolean) =>
- cn(sidebarSurfaceVariants({ role: "navPill" }), SIDEBAR_ROW_FOCUS_CLASSES, sidebarRowStateClasses(active ? "current" : "idle"));
-
-const NavPillLabel = ({ expanded, label }: { expanded: boolean; label: string }) => (
- // The control carries its own aria-label; this text is decoration whether or not it is open.
- <span
- aria-hidden="true"
- className={cn(
- "grid min-w-0 grid-cols-[0fr] ps-0 transition-[grid-template-columns,padding] duration-200 ease-out motion-reduce:transition-none",
- expanded && "@min-[230px]:grid-cols-[1fr] @min-[230px]:ps-1.5",
- )}
- >
- <span className="flex min-w-0 items-center overflow-hidden">
- <span data-sidebar-label className="shrink-0 truncate text-[12px] leading-5">
- {label}
- </span>
- </span>
- </span>
-);
+const NavPill = ({ label, icon: Icon, to, onClick, active = false, expanded = false, className }: NavPillProps) => {
+ const { setMobileOpen } = useAppSidebar();
+ const props = {
+ onClick: () => {
+ setMobileOpen(false);
+ onClick?.();
+ },
+ "aria-label": label,
+ "aria-current": active ? ("page" as const) : undefined,
+ className: cn(
+ sidebarSurfaceVariants({ role: "navPill" }),
+ SIDEBAR_ROW_FOCUS_CLASSES,
+ sidebarRowStateClasses(active ? "current" : "idle"),
+ className,
+ ),
+ };
+ return (
+ <Tooltip disabled={expanded}>
+ <TooltipTrigger render={to ? <Link to={to} {...props} /> : <button type="button" {...props} />}>
+ <span className={SIDEBAR_NAV_LEADING_SLOT_CLASSES} aria-hidden="true">
+ <Icon className="size-4 opacity-75" strokeWidth={1.8} />
+ </span>
+ {/* The control carries its own aria-label; this text is decoration whether or not it is open. */}
+ <span
+ aria-hidden="true"
+ className={cn(
+ "grid min-w-0 grid-cols-[0fr] ps-0 transition-[grid-template-columns,padding] duration-200 ease-out motion-reduce:transition-none",
+ expanded && "@min-[230px]:grid-cols-[1fr] @min-[230px]:ps-1.5",
+ )}
+ >
+ <span className="flex min-w-0 items-center overflow-hidden">
+ <span data-sidebar-label className="shrink-0 truncate text-[12px] leading-5">
+ {label}
+ </span>
+ </span>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent side="bottom">{label}</TooltipContent>
+ </Tooltip>
+ );
+};
const GlobalNavigation = () => {
const t = useTranslate();
const timelineRef = useRef<HTMLDivElement>(null);
const location = useLocation();
const currentUser = useCurrentUser();
- const { setMobileOpen, setQuickFindOpen } = useAppSidebar();
+ const { setQuickFindOpen } = useAppSidebar();
const routeKind = getSidebarRouteKind(location.pathname);
- const homeActive = routeKind === "home" || routeKind === "explore";
- const homePath =
- !currentUser && !resolveCollectionRoute(location.pathname).isCollection
- ? ROUTES.EXPLORE
- : collectionNavigationPath(ROUTES.HOME, location, currentUser?.username);
- const items: GlobalNavItem[] = currentUser
- ? [
- {
- id: "calendar",
- label: t("common.calendar"),
- path: collectionNavigationPath(ROUTES.CALENDAR, location, currentUser.username),
- icon: CalendarDaysIcon,
- active: routeKind === "calendar",
- },
- {
- id: "map",
- label: t("common.map"),
- path: collectionNavigationPath(ROUTES.MAP, location, currentUser.username),
- icon: MapIcon,
- active: routeKind === "map",
- },
- {
- id: "attachments",
- label: t("common.attachments"),
- path: collectionNavigationPath(ROUTES.ATTACHMENTS, location, currentUser.username),
- icon: PaperclipIcon,
- active: routeKind === "attachments",
- },
- ]
- : [
- {
- id: "about",
- label: t("common.about"),
- path: ROUTES.ABOUT,
- icon: InfoIcon,
- active: Boolean(matchPath(ROUTES.ABOUT, location.pathname)),
- },
- ];
- const expandedItemId = homeActive ? "home" : (items.find((item) => item.active)?.id ?? "home");
+ const timelineActive = routeKind === "home" || routeKind === "explore";
+ const destinations = NAV_DESTINATIONS.filter((destination) => currentUser || !destination.signedInOnly);
+ // The current page shows its label; anywhere else, Timeline does.
+ const expandedKind = destinations.find((destination) => destination.kind === routeKind)?.kind ?? "timeline";
+ const navigationPath = (pathname: string) => collectionNavigationPath(pathname, location, currentUser?.username);
return (
<TooltipProvider>
<nav className={cn("@container flex h-7 items-center gap-1", SIDEBAR_RAIL_CLASSES)} aria-label="Primary">
- <div ref={timelineRef} className={cn("flex shrink-0 items-center rounded-md", homeActive && sidebarRowStateClasses("current"))}>
- <Tooltip disabled={expandedItemId === "home"}>
- <TooltipTrigger
- render={
- <Link
- to={homePath}
- onClick={() => setMobileOpen(false)}
- aria-label={t("common.timeline")}
- aria-current={homeActive ? "page" : undefined}
- className={cn(navPillClasses(homeActive), homeActive && "rounded-e-none pe-0")}
- />
- }
- >
- <span className={SIDEBAR_NAV_LEADING_SLOT_CLASSES} aria-hidden="true">
- <LibraryIcon className="size-4 opacity-75" strokeWidth={1.8} />
- </span>
- <NavPillLabel expanded={expandedItemId === "home"} label={t("common.timeline")} />
- </TooltipTrigger>
- <TooltipContent side="bottom">{t("common.timeline")}</TooltipContent>
- </Tooltip>
- {homeActive && <MemoDisplaySettingMenu anchor={timelineRef} />}
+ <div ref={timelineRef} className={cn("flex shrink-0 items-center rounded-md", timelineActive && sidebarRowStateClasses("current"))}>
+ <NavPill
+ to={navigationPath(ROUTES.HOME)}
+ label={t("common.timeline")}
+ icon={LibraryIcon}
+ active={timelineActive}
+ expanded={expandedKind === "timeline"}
+ className={cn(timelineActive && "rounded-e-none pe-0")}
+ />
+ {timelineActive && <MemoDisplaySettingMenu anchor={timelineRef} />}
</div>
- {items.map((item) => {
- const Icon = item.icon;
- const expanded = item.id === expandedItemId;
- return (
- <Tooltip key={item.id} disabled={expanded}>
- <TooltipTrigger
- render={
- <Link
- to={item.path}
- onClick={() => setMobileOpen(false)}
- aria-label={item.label}
- aria-current={item.active ? "page" : undefined}
- className={navPillClasses(item.active)}
- />
- }
- >
- <span className={SIDEBAR_NAV_LEADING_SLOT_CLASSES} aria-hidden="true">
- <Icon className="size-4 opacity-75" strokeWidth={1.8} />
- </span>
- <NavPillLabel expanded={expanded} label={item.label} />
- </TooltipTrigger>
- <TooltipContent side="bottom">{item.label}</TooltipContent>
- </Tooltip>
- );
- })}
- <Tooltip>
- <TooltipTrigger
- render={
- <button
- type="button"
- aria-label={t("common.search")}
- className={cn("ms-auto", navPillClasses(false))}
- onClick={() => {
- setMobileOpen(false);
- setQuickFindOpen(true);
- }}
- />
- }
- >
- <span className={SIDEBAR_NAV_LEADING_SLOT_CLASSES} aria-hidden="true">
- <SearchIcon className="size-4 opacity-75" strokeWidth={1.8} />
- </span>
- </TooltipTrigger>
- <TooltipContent side="bottom">{t("common.search")}</TooltipContent>
- </Tooltip>
+ {destinations.map((destination) => (
+ <NavPill
+ key={destination.kind}
+ to={navigationPath(destination.pathname)}
+ label={t(destination.labelKey)}
+ icon={destination.icon}
+ active={destination.kind === routeKind}
+ expanded={destination.kind === expandedKind}
+ />
+ ))}
+ <NavPill label={t("common.search")} icon={SearchIcon} onClick={() => setQuickFindOpen(true)} className="ms-auto" />
</nav>
</TooltipProvider>
);
diff --git a/web/src/components/AppSidebar/CommonSidebarContent.tsx b/web/src/components/AppSidebar/CommonSidebarContent.tsx
index d227cb0f2..021fde25b 100644
--- a/web/src/components/AppSidebar/CommonSidebarContent.tsx
+++ b/web/src/components/AppSidebar/CommonSidebarContent.tsx
@@ -1,7 +1,6 @@
import { BookOpenIcon, BracesIcon, ExternalLinkIcon, GitForkIcon, InfoIcon, type LucideIcon } from "lucide-react";
import { Link, matchPath, useLocation } from "react-router-dom";
import { useAppSidebar } from "@/contexts/AppSidebarContext";
-import useCurrentUser from "@/hooks/useCurrentUser";
import { MEMOS_API_DOCUMENTATION_URL, MEMOS_DOCUMENTATION_URL, MEMOS_GITHUB_URL } from "@/lib/constants";
import { cn } from "@/lib/utils";
import { ROUTES } from "@/router/routes";
@@ -24,25 +23,22 @@ const RESOURCE_LINKS: ResourceLink[] = [
const CommonSidebarContent = () => {
const t = useTranslate();
const location = useLocation();
- const currentUser = useCurrentUser();
const { setMobileOpen } = useAppSidebar();
const aboutActive = Boolean(matchPath(ROUTES.ABOUT, location.pathname));
return (
<div className={SIDEBAR_SECTION_STACK_CLASSES}>
- {currentUser && (
- <SidebarSection ariaLabel={t("common.about")}>
- <Link
- to={ROUTES.ABOUT}
- aria-current={aboutActive ? "page" : undefined}
- onClick={() => setMobileOpen(false)}
- className={cn(SIDEBAR_ROW_CLASSES, sidebarRowStateClasses(aboutActive ? "current" : "idle"))}
- >
- <SidebarRowIconSlot icon={InfoIcon} />
- <span className="min-w-0 flex-1 truncate">{t("common.about")}</span>
- </Link>
- </SidebarSection>
- )}
+ <SidebarSection ariaLabel={t("common.about")}>
+ <Link
+ to={ROUTES.ABOUT}
+ aria-current={aboutActive ? "page" : undefined}
+ onClick={() => setMobileOpen(false)}
+ className={cn(SIDEBAR_ROW_CLASSES, sidebarRowStateClasses(aboutActive ? "current" : "idle"))}
+ >
+ <SidebarRowIconSlot icon={InfoIcon} />
+ <span className="min-w-0 flex-1 truncate">{t("common.about")}</span>
+ </Link>
+ </SidebarSection>
<SidebarSection label={t("common.resources")}>
{RESOURCE_LINKS.map((resource) => (
diff --git a/web/src/components/AppSidebar/SpaceSwitcher.tsx b/web/src/components/AppSidebar/SpaceSwitcher.tsx
index 3a6d31a06..f2206ed1b 100644
--- a/web/src/components/AppSidebar/SpaceSwitcher.tsx
+++ b/web/src/components/AppSidebar/SpaceSwitcher.tsx
@@ -4,9 +4,8 @@ import {
ChevronsUpDownIcon,
CompassIcon,
HouseIcon,
- InfoIcon,
LoaderCircleIcon,
- LogInIcon,
+ type LucideIcon,
PlusIcon,
} from "lucide-react";
import { useRef, useState } from "react";
@@ -15,11 +14,10 @@ import CreateSpaceDialog from "@/components/CreateSpaceDialog";
import MemosLogo from "@/components/MemosLogo";
import SpaceMark from "@/components/SpaceMark";
import UserAvatar from "@/components/UserAvatar";
-import UserMenu, { type UserPreference, UserPreferenceDialog } from "@/components/UserMenu";
+import UserMenu from "@/components/UserMenu";
import { Button } from "@/components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Select, SelectContent, SelectItem, SelectTrigger } from "@/components/ui/select";
-import { useAppSidebar } from "@/contexts/AppSidebarContext";
import { useSpaceContext } from "@/contexts/SpaceContext";
import useCurrentUser from "@/hooks/useCurrentUser";
import { useUser } from "@/hooks/useUserQueries";
@@ -29,12 +27,28 @@ import { buildCollectionPath, getCreatorSwitchPath, getSpaceSwitchPath, ROUTES }
import { useTranslate } from "@/utils/i18n";
import { sidebarSurfaceVariants } from "./sidebar-layout";
+/** One half of the Home/Explore segmented control; the current half is raised. */
+const BrowseLink = ({ to, current, icon: Icon, label }: { to: string; current: boolean; icon: LucideIcon; label: string }) => (
+ <Link
+ to={to}
+ aria-current={current ? "page" : undefined}
+ className={cn(
+ "flex h-8 min-w-0 items-center gap-1.5 rounded-sm px-1.5 text-xs font-medium hover:bg-background/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40",
+ current && "bg-background ring-1 ring-border shadow-sm hover:bg-background",
+ )}
+ >
+ <span className="flex size-5 shrink-0 items-center justify-center">
+ <Icon aria-hidden="true" className="size-4" strokeWidth={1.8} />
+ </span>
+ <span className="min-w-0 truncate">{label}</span>
+ </Link>
+);
+
function SpaceSwitcher({ className, size = "md" }: { className?: string; size?: "md" | "header" }) {
const t = useTranslate();
const location = useLocation();
const navigate = useNavigate();
const currentUser = useCurrentUser();
- const { setMobileOpen } = useAppSidebar();
const { spaces, duplicateSpaceTitles, selectedSpace, selectedSpaceName, creatorUsername, isLoadingSpaces, isSpacesError, selectSpace } =
useSpaceContext();
const { data: otherCreator } = useUser(`users/${creatorUsername ?? ""}`, {
@@ -42,7 +56,6 @@ function SpaceSwitcher({ className, size = "md" }: { className?: string; size?:
});
const [createOpen, setCreateOpen] = useState(false);
const [open, setOpen] = useState(false);
- const [preference, setPreference] = useState<UserPreference | null>(null);
const [menuWidth, setMenuWidth] = useState<number>();
const triggerRef = useRef<HTMLButtonElement>(null);
const selectedCreator = creatorUsername ? (creatorUsername === currentUser?.username ? currentUser : otherCreator) : undefined;
@@ -55,11 +68,6 @@ function SpaceSwitcher({ className, size = "md" }: { className?: string; size?:
const triggerLabel = showBrand ? t("common.memos") : contextLabel;
const allSpacesLabel = t("space.all-spaces");
- const navigateTo = (path: string) => {
- setOpen(false);
- setMobileOpen(false);
- navigate(path);
- };
const handleOpenChange = (next: boolean) => {
setOpen(next);
if (!next) return;
@@ -72,10 +80,6 @@ function SpaceSwitcher({ className, size = "md" }: { className?: string; size?:
const width = Math.floor(sidebarRect.width - inlineInset * 2);
if (width > 0) setMenuWidth(width);
};
- const openPreference = (nextPreference: UserPreference) => {
- setOpen(false);
- setPreference(nextPreference);
- };
return (
<>
@@ -123,149 +127,116 @@ function SpaceSwitcher({ className, size = "md" }: { className?: string; size?:
className="w-[min(15rem,calc(100vw-1rem))] max-h-[min(27rem,calc(100dvh-5rem))] overflow-y-auto p-0"
style={menuWidth ? { width: `${menuWidth}px` } : undefined}
>
- <div className="px-2 pb-1.5 pt-2">
- {isOtherCreator ? (
- <Link
- to={returnPath}
- className="flex h-8 items-center gap-2 rounded-sm px-2 text-xs font-medium hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40"
- >
- <ArrowLeftIcon aria-hidden="true" className="size-3.5 rtl:rotate-180" strokeWidth={1.8} />
- {t("memo.back-to", { source: t(currentUser ? "common.home" : "common.explore") })}
- </Link>
- ) : (
- <>
- <div className="mb-1.5 px-1 text-[10px] font-semibold tracking-[0.08em] text-muted-foreground uppercase">
- {t("common.browse")}
- </div>
- <nav aria-label={t("common.browse")} className={cn("grid gap-0.5 rounded-md bg-muted p-0.5", currentUser && "grid-cols-2")}>
- {currentUser && (
- <Link
- to={getCreatorSwitchPath(location, currentUser.username, currentUser.username)}
- aria-current={creatorUsername ? "page" : undefined}
- className={cn(
- "flex h-8 min-w-0 items-center gap-1.5 rounded-sm px-1.5 text-xs font-medium hover:bg-background/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40",
- creatorUsername && "bg-background ring-1 ring-border shadow-sm hover:bg-background",
- )}
- >
- <span className="flex size-5 shrink-0 items-center justify-center">
- <HouseIcon aria-hidden="true" className="size-4" strokeWidth={1.8} />
- </span>
- <span className="min-w-0 truncate">{t("common.home")}</span>
- </Link>
- )}
- <Link
- to={getCreatorSwitchPath(location, undefined, currentUser?.username)}
- aria-current={!creatorUsername ? "page" : undefined}
- className={cn(
- "flex h-8 min-w-0 items-center gap-1.5 rounded-sm px-1.5 text-xs font-medium hover:bg-background/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40",
- !creatorUsername && "bg-background ring-1 ring-border shadow-sm hover:bg-background",
- )}
- >
- <span className="flex size-5 shrink-0 items-center justify-center">
- <CompassIcon aria-hidden="true" className="size-4" strokeWidth={1.8} />
- </span>
- <span className="min-w-0 truncate">{t("common.explore")}</span>
- </Link>
- </nav>
- </>
- )}
- {currentUser && (
- <>
- <div className="mb-1 mt-2 flex h-6 items-center justify-between ps-0.5">
- <span className="text-[10px] font-semibold tracking-[0.08em] text-muted-foreground uppercase">{t("space.spaces")}</span>
- {!isOtherCreator && (
- <Button
- variant="ghost"
- size="icon"
- aria-label={t("space.create")}
- title={t("space.create")}
- onClick={() => {
- setOpen(false);
- setCreateOpen(true);
- }}
- className="size-6 text-muted-foreground hover:text-foreground"
- >
- <PlusIcon className="size-3.5" strokeWidth={1.8} />
- </Button>
- )}
- </div>
- <Select
- value={selectedSpaceName ?? "all"}
- onValueChange={(value) => {
- if (value !== null) navigate(getSpaceSwitchPath(location, value === "all" ? undefined : value));
- }}
+ {/* Guests have one collection, Explore, so they only get a way back to it from a creator. */}
+ {(currentUser || isOtherCreator) && (
+ <div className="px-2 pb-1.5 pt-2">
+ {isOtherCreator ? (
+ <Link
+ to={returnPath}
+ className="flex h-8 items-center gap-2 rounded-sm px-2 text-xs font-medium hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40"
>
- <SelectTrigger aria-label={t("space.switch")} className="h-8 w-full px-2 text-xs font-medium shadow-none">
- {selectedSpaceName ? (
- <SpaceMark icon={selectedSpace?.icon} size="sm" />
- ) : (
- <AstroidIcon className="size-4 text-muted-foreground" />
+ <ArrowLeftIcon aria-hidden="true" className="size-3.5 rtl:rotate-180" strokeWidth={1.8} />
+ {t("memo.back-to", { source: t(currentUser ? "common.home" : "common.explore") })}
+ </Link>
+ ) : (
+ currentUser && (
+ <>
+ <div className="mb-1.5 px-1 text-[10px] font-semibold tracking-[0.08em] text-muted-foreground uppercase">
+ {t("common.browse")}
+ </div>
+ <nav aria-label={t("common.browse")} className="grid grid-cols-2 gap-0.5 rounded-md bg-muted p-0.5">
+ <BrowseLink
+ to={getCreatorSwitchPath(location, currentUser.username, currentUser.username)}
+ current={Boolean(creatorUsername)}
+ icon={HouseIcon}
+ label={t("common.home")}
+ />
+ <BrowseLink
+ to={getCreatorSwitchPath(location, undefined, currentUser.username)}
+ current={!creatorUsername}
+ icon={CompassIcon}
+ label={t("common.explore")}
+ />
+ </nav>
+ </>
+ )
+ )}
+ {currentUser && (
+ <>
+ <div className="mb-1 mt-2 flex h-6 items-center justify-between ps-0.5">
+ <span className="text-[10px] font-semibold tracking-[0.08em] text-muted-foreground uppercase">{t("space.spaces")}</span>
+ {!isOtherCreator && (
+ <Button
+ variant="ghost"
+ size="icon"
+ aria-label={t("space.create")}
+ title={t("space.create")}
+ onClick={() => {
+ setOpen(false);
+ setCreateOpen(true);
+ }}
+ className="size-6 text-muted-foreground hover:text-foreground"
+ >
+ <PlusIcon className="size-3.5" strokeWidth={1.8} />
+ </Button>
)}
- <span className="min-w-0 flex-1 truncate text-start">{selectedSpaceName ? spaceLabel : allSpacesLabel}</span>
- </SelectTrigger>
- <SelectContent className="max-h-64" align="start">
- <SelectItem value="all">
- <span className="flex items-center gap-2">
- <AstroidIcon className="size-4" />
- {allSpacesLabel}
- </span>
- </SelectItem>
- {spaces.map((space) => {
- const uid = extractSpaceUidFromName(space.name);
- return (
- <SelectItem key={space.name} value={space.name}>
- <span className="flex items-center gap-2">
- <SpaceMark icon={space.icon} size="sm" />
- <span className="truncate">
- {space.title}
- {duplicateSpaceTitles.has(space.title) ? ` (${uid})` : ""}
+ </div>
+ <Select
+ value={selectedSpaceName ?? "all"}
+ onValueChange={(value) => {
+ if (value !== null) navigate(getSpaceSwitchPath(location, value === "all" ? undefined : value));
+ }}
+ >
+ <SelectTrigger aria-label={t("space.switch")} className="h-8 w-full px-2 text-xs font-medium shadow-none">
+ {selectedSpaceName ? (
+ <SpaceMark icon={selectedSpace?.icon} size="sm" />
+ ) : (
+ <AstroidIcon className="size-4 text-muted-foreground" />
+ )}
+ <span className="min-w-0 flex-1 truncate text-start">{selectedSpaceName ? spaceLabel : allSpacesLabel}</span>
+ </SelectTrigger>
+ <SelectContent className="max-h-64" align="start">
+ <SelectItem value="all">
+ <span className="flex items-center gap-2">
+ <AstroidIcon className="size-4" />
+ {allSpacesLabel}
+ </span>
+ </SelectItem>
+ {spaces.map((space) => {
+ const uid = extractSpaceUidFromName(space.name);
+ return (
+ <SelectItem key={space.name} value={space.name}>
+ <span className="flex items-center gap-2">
+ <SpaceMark icon={space.icon} size="sm" />
+ <span className="truncate">
+ {space.title}
+ {duplicateSpaceTitles.has(space.title) ? ` (${uid})` : ""}
+ </span>
</span>
- </span>
+ </SelectItem>
+ );
+ })}
+ {isLoadingSpaces && (
+ <SelectItem value="loading" disabled>
+ <LoaderCircleIcon className="size-4 animate-spin" />
+ {t("space.loading")}
</SelectItem>
- );
- })}
- {isLoadingSpaces && (
- <SelectItem value="loading" disabled>
- <LoaderCircleIcon className="size-4 animate-spin" />
- {t("space.loading")}
- </SelectItem>
- )}
- {isSpacesError && spaces.length === 0 && (
- <SelectItem value="error" disabled>
- {t("space.load-error")}
- </SelectItem>
- )}
- </SelectContent>
- </Select>
- </>
- )}
- </div>
- {currentUser ? (
- <UserMenu onClose={() => setOpen(false)} onSelectPreference={openPreference} />
- ) : (
- <div className="border-t border-border/70 px-2 py-1">
- <Button
- variant="ghost"
- className="h-8 w-full justify-start gap-2 rounded-sm px-2 text-xs font-normal"
- onClick={() => navigateTo(ROUTES.ABOUT)}
- >
- <InfoIcon className="size-3.5 text-muted-foreground" />
- {t("common.about")}
- </Button>
- <Button
- variant="ghost"
- className="h-8 w-full justify-start gap-2 rounded-sm px-2 text-xs font-normal"
- onClick={() => navigateTo(ROUTES.AUTH)}
- >
- <LogInIcon className="size-3.5 text-muted-foreground" />
- {t("common.sign-in")}
- </Button>
+ )}
+ {isSpacesError && spaces.length === 0 && (
+ <SelectItem value="error" disabled>
+ {t("space.load-error")}
+ </SelectItem>
+ )}
+ </SelectContent>
+ </Select>
+ </>
+ )}
</div>
)}
+ <UserMenu onClose={() => setOpen(false)} />
</PopoverContent>
</Popover>
<CreateSpaceDialog open={createOpen} onOpenChange={setCreateOpen} onCreated={selectSpace} />
- {preference && <UserPreferenceDialog preference={preference} onClose={() => setPreference(null)} />}
</>
);
}
diff --git a/web/src/components/CalendarView/CalendarView.tsx b/web/src/components/CalendarView/CalendarView.tsx
index b2aa01d1e..9bd4f678f 100644
--- a/web/src/components/CalendarView/CalendarView.tsx
+++ b/web/src/components/CalendarView/CalendarView.tsx
@@ -78,7 +78,7 @@ export const CalendarView = ({ month, date }: CalendarViewProps) => {
month,
filter: monthFilter,
isRedacted,
- enabled: Boolean(user) && isUserSettingsInitialized,
+ enabled: isUserSettingsInitialized,
});
const monthLabel = useMemo(() => formatMonthLabel(month, i18n.language), [month, i18n.language]);
diff --git a/web/src/components/MapView/useMapMemos.ts b/web/src/components/MapView/useMapMemos.ts
index d86c35470..49f7a5c22 100644
--- a/web/src/components/MapView/useMapMemos.ts
+++ b/web/src/components/MapView/useMapMemos.ts
@@ -2,7 +2,6 @@ import { useEffect, useMemo } from "react";
import { useAuth } from "@/contexts/AuthContext";
import { useSpaceContext } from "@/contexts/SpaceContext";
import { useView } from "@/contexts/ViewContext";
-import useCurrentUser from "@/hooks/useCurrentUser";
import { useMemoFilters } from "@/hooks/useMemoFilters";
import { useInfiniteMemos } from "@/hooks/useMemoQueries";
import { combineCELFilters } from "@/lib/cel-filter";
@@ -13,7 +12,6 @@ import { mapMemos } from "./model";
export const MAP_MEMO_FILTER = "has_location";
export function useMapMemos() {
- const user = useCurrentUser();
const { isUserSettingsInitialized } = useAuth();
const { memoFilter } = useSpaceContext();
const { timeBasis } = useView();
@@ -21,15 +19,15 @@ export function useMapMemos() {
const filter = combineCELFilters(memoFilter, viewFilter, MAP_MEMO_FILTER);
const query = useInfiniteMemos(
{ filter, state: State.NORMAL, pageSize: 500, orderBy: `${timeBasis} desc, name desc` },
- { enabled: Boolean(user) && isUserSettingsInitialized },
+ { enabled: isUserSettingsInitialized },
);
const { hasNextPage, isFetching, isError, fetchNextPage } = query;
useEffect(() => {
if (hasNextPage && !isFetching && !isError) void fetchNextPage().catch(() => {});
}, [hasNextPage, isFetching, isError, fetchNextPage, query.data?.pages.length]);
const memos = useMemo(
- () => mapMemos(isUserSettingsInitialized && user ? query.data?.pages : undefined, timeBasis),
- [query.data, timeBasis, isUserSettingsInitialized, user],
+ () => mapMemos(isUserSettingsInitialized ? query.data?.pages : undefined, timeBasis),
+ [query.data, timeBasis, isUserSettingsInitialized],
);
const complete = isUserSettingsInitialized && query.isSuccess && !query.hasNextPage && !query.isFetching;
return { ...query, memos, complete, retry: () => (query.isFetchNextPageError ? query.fetchNextPage() : query.refetch()) };
diff --git a/web/src/components/MemoDisplaySettingMenu.tsx b/web/src/components/MemoDisplaySettingMenu.tsx
index 31ad22bc1..08414388c 100644
--- a/web/src/components/MemoDisplaySettingMenu.tsx
+++ b/web/src/components/MemoDisplaySettingMenu.tsx
@@ -32,9 +32,9 @@ const LAYOUT_OPTIONS: Record<MemoMaxColumns, { icon: LucideIcon; key: "layout-li
};
const SettingRow = ({ label, description, children }: SettingRowProps) => (
- <div className="flex min-h-7 items-center justify-between gap-3">
+ <div className="flex min-h-6 items-center justify-between gap-2">
<div className="min-w-0">
- <p className="text-[13px] leading-5 text-foreground">{label}</p>
+ <p className="text-xs leading-4 text-foreground">{label}</p>
{description && <p className="text-[11px] leading-4 text-muted-foreground">{description}</p>}
</div>
{children}
@@ -71,7 +71,7 @@ function MemoDisplaySettingsContent() {
return (
<div>
- <section className="px-3 py-2.5">
+ <section className="p-1.5">
<div
role="radiogroup"
aria-label={t("memo.layout")}
@@ -117,7 +117,7 @@ function MemoDisplaySettingsContent() {
data-value={value}
onClick={() => setMaxColumns(value)}
className={cn(
- "flex h-7 min-w-0 items-center justify-center gap-1 rounded-md px-1 text-[11px] transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50",
+ "flex h-6 min-w-0 items-center justify-center gap-1 rounded-sm px-1 text-[11px] transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50",
active ? "bg-accent text-accent-foreground" : "text-muted-foreground hover:bg-accent/50 hover:text-foreground",
)}
>
@@ -129,14 +129,14 @@ function MemoDisplaySettingsContent() {
</div>
</section>
- <section className="space-y-2 border-t border-border/60 px-3 py-2.5">
+ <section className="space-y-1 border-t border-border/60 px-2.5 py-2">
<SettingRow label={t("memo.order-by")}>
<Select
value={timeBasis}
items={timeBasisOptions}
onValueChange={(value) => setTimeBasis(value === "update_time" ? "update_time" : "create_time")}
>
- <SelectTrigger size="sm" className="w-32" aria-label={t("memo.order-by")}>
+ <SelectTrigger size="xs" className="w-32" aria-label={t("memo.order-by")}>
<SelectValue />
</SelectTrigger>
<SelectContent>
@@ -154,7 +154,7 @@ function MemoDisplaySettingsContent() {
items={sortOrderOptions}
onValueChange={(value) => setOrderByTimeAsc(value === "asc")}
>
- <SelectTrigger size="sm" className="w-32" aria-label={t("memo.direction")}>
+ <SelectTrigger size="xs" className="w-32" aria-label={t("memo.direction")}>
<SelectValue />
</SelectTrigger>
<SelectContent>
@@ -168,7 +168,7 @@ function MemoDisplaySettingsContent() {
</SettingRow>
</section>
- <section className="space-y-2 border-t border-border/60 px-3 py-2.5">
+ <section className="space-y-1 border-t border-border/60 px-2.5 py-2">
<SettingRow label={t("memo.compact-mode")} description={compactLocked ? t("memo.grid-compact-hint") : undefined}>
<Switch
aria-label={t("memo.compact-mode")}
@@ -207,7 +207,7 @@ function MemoDisplaySettingMenu({ anchor }: Props) {
</TooltipTrigger>
<TooltipContent side="bottom">{label}</TooltipContent>
</Tooltip>
- <PopoverContent anchor={anchor} align="start" sideOffset={6} aria-label={label} className="w-64 p-0">
+ <PopoverContent anchor={anchor} align="start" sideOffset={6} aria-label={label} className="w-56 p-0">
<MemoDisplaySettingsContent />
</PopoverContent>
</Popover>
diff --git a/web/src/components/UserMenu.tsx b/web/src/components/UserMenu.tsx
index 418ce5a84..3bb696c6b 100644
--- a/web/src/components/UserMenu.tsx
+++ b/web/src/components/UserMenu.tsx
@@ -1,48 +1,132 @@
import {
ArchiveIcon,
BellIcon,
- CheckIcon,
ChevronRightIcon,
GlobeIcon,
InfoIcon,
LogOutIcon,
+ type LucideIcon,
PaletteIcon,
SettingsIcon,
} from "lucide-react";
+import { useState } from "react";
import { matchPath, useLocation } from "react-router-dom";
-import { LocaleSearchList } from "@/components/LocalePicker";
import UserAvatar from "@/components/UserAvatar";
import { Button } from "@/components/ui/button";
-import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
import { useAppSidebar } from "@/contexts/AppSidebarContext";
import { useAuth } from "@/contexts/AuthContext";
import useCurrentUser from "@/hooks/useCurrentUser";
import { useSSEConnectionStatus } from "@/hooks/useLiveMemoRefresh";
import useNavigateTo from "@/hooks/useNavigateTo";
import { useNotifications, useUpdateUserGeneralSetting } from "@/hooks/useUserQueries";
+import { locales } from "@/i18n";
import { cn } from "@/lib/utils";
import { Routes } from "@/router";
import { UserNotification_Status } from "@/types/proto/api/v1/user_service_pb";
import { getLocaleDisplayName, getLocaleWithFallback, loadLocale, useTranslate } from "@/utils/i18n";
import { getThemeWithFallback, loadTheme, THEME_OPTIONS } from "@/utils/theme";
-export type UserPreference = "theme" | "language";
-
const rowClass = "h-8 w-full justify-start gap-2 rounded-sm px-2 text-xs font-normal shadow-none hover:bg-accent";
const iconClass = "size-3.5 shrink-0 text-muted-foreground";
-const UserMenu = ({ onClose, onSelectPreference }: { onClose: () => void; onSelectPreference: (preference: UserPreference) => void }) => {
+interface PreferenceSubmenuProps {
+ icon: LucideIcon;
+ label: string;
+ value: string;
+ options: Array<{ value: string; label: string }>;
+ onChange: (value: string) => void;
+ /** Long lists scroll; typing jumps to a match. */
+ className?: string;
+}
+
+/** A row that opens its choices beside the panel, like a submenu, and applies one on select. */
+const PreferenceSubmenu = ({ icon: Icon, label, value, options, onChange, className }: PreferenceSubmenuProps) => (
+ <DropdownMenu>
+ <DropdownMenuTrigger openOnHover render={<Button variant="ghost" className={cn(rowClass, "data-popup-open:bg-accent")} />}>
+ <Icon className={iconClass} />
+ <span className="min-w-0 flex-1 text-start">{label}</span>
+ <span className="max-w-28 truncate text-muted-foreground">{options.find((option) => option.value === value)?.label ?? value}</span>
+ <ChevronRightIcon className={cn(iconClass, "rtl:rotate-180")} />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent side="inline-end" align="start" sideOffset={8} alignOffset={-4} size="sm" className={className}>
+ <DropdownMenuRadioGroup value={value} onValueChange={onChange}>
+ {options.map((option) => (
+ <DropdownMenuRadioItem key={option.value} value={option.value} closeOnClick>
+ {option.label}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+);
+
+const LOCALE_OPTIONS = locales.map((locale) => ({ value: locale, label: getLocaleDisplayName(locale) }));
+
+/** Theme and language apply at once: saved to the account when signed in, otherwise kept in this browser. */
+const UserPreferenceMenu = () => {
+ const t = useTranslate();
+ const currentUser = useCurrentUser();
+ const { userGeneralSetting, refetchSettings } = useAuth();
+ const { mutate: updateUserGeneralSetting } = useUpdateUserGeneralSetting(currentUser?.name);
+ // The chosen value shows immediately, before a signed-in save round-trips.
+ const [theme, setTheme] = useState<string>();
+ const [locale, setLocale] = useState<string>();
+ const currentTheme = theme ?? getThemeWithFallback(userGeneralSetting?.theme);
+ const currentLocale = locale ?? getLocaleWithFallback(userGeneralSetting?.locale);
+
+ const handleThemeChange = (value: string) => {
+ setTheme(value);
+ loadTheme(value);
+ if (currentUser) {
+ updateUserGeneralSetting({ generalSetting: { theme: value }, updateMask: ["theme"] }, { onSuccess: () => refetchSettings() });
+ }
+ };
+
+ const handleLocaleChange = (value: string) => {
+ setLocale(loadLocale(value));
+ if (currentUser) {
+ updateUserGeneralSetting({ generalSetting: { locale: value }, updateMask: ["locale"] }, { onSuccess: () => refetchSettings() });
+ }
+ };
+
+ return (
+ <section aria-label={t("setting.preference.label")} className="border-border/70 px-2 py-1 not-first:border-t">
+ <PreferenceSubmenu
+ icon={PaletteIcon}
+ label={t("setting.preference.theme")}
+ value={currentTheme}
+ options={THEME_OPTIONS}
+ onChange={handleThemeChange}
+ />
+ <PreferenceSubmenu
+ icon={GlobeIcon}
+ label={t("common.language")}
+ value={currentLocale}
+ options={LOCALE_OPTIONS}
+ onChange={handleLocaleChange}
+ className="max-h-72"
+ />
+ </section>
+ );
+};
+
+/** The account half of the scope menu: preferences for everyone, then the user's own pages. */
+const UserMenu = ({ onClose }: { onClose: () => void }) => {
const t = useTranslate();
const location = useLocation();
const navigateTo = useNavigateTo();
const { setMobileOpen } = useAppSidebar();
const currentUser = useCurrentUser();
const sseStatus = useSSEConnectionStatus();
- const { userGeneralSetting, logout } = useAuth();
+ const { logout } = useAuth();
const { data: notifications = [] } = useNotifications();
- const currentLocale = getLocaleWithFallback(userGeneralSetting?.locale);
- const currentTheme = getThemeWithFallback(userGeneralSetting?.theme);
- const themeLabel = THEME_OPTIONS.find((option) => option.value === currentTheme)?.label ?? currentTheme;
const unreadCount = notifications.filter((notification) => notification.status === UserNotification_Status.UNREAD).length;
const inboxLabel = unreadCount > 0 ? `${t("common.inbox")}, ${unreadCount} ${t("inbox.unread")}` : t("common.inbox");
const accountLabel = currentUser?.displayName || currentUser?.username || t("common.profile");
@@ -73,129 +157,69 @@ const UserMenu = ({ onClose, onSelectPreference }: { onClose: () => void; onSele
return (
<>
- <section aria-label={t("setting.preference.label")} className="border-t border-border/70 px-2 py-1">
- <Button variant="ghost" className={rowClass} onClick={() => onSelectPreference("theme")}>
- <PaletteIcon className={iconClass} />
- <span className="min-w-0 flex-1 text-start">{t("setting.preference.theme")}</span>
- <span className="max-w-28 truncate text-muted-foreground">{themeLabel}</span>
- <ChevronRightIcon className={iconClass} />
- </Button>
- <Button variant="ghost" className={rowClass} onClick={() => onSelectPreference("language")}>
- <GlobeIcon className={iconClass} />
- <span className="min-w-0 flex-1 text-start">{t("common.language")}</span>
- <span className="max-w-24 truncate text-muted-foreground">{getLocaleDisplayName(currentLocale)}</span>
- <ChevronRightIcon className={iconClass} />
- </Button>
- </section>
+ <UserPreferenceMenu />
<section aria-label={t("setting.sso.account")} className="border-t border-border/70 px-2 py-1">
- <div className="flex h-8 items-center gap-2 px-2">
- <span className="relative flex size-5 shrink-0 items-center justify-center">
- <UserAvatar avatarUrl={currentUser?.avatarUrl} name={accountLabel} className="size-5 rounded-[5px]" />
- {sseStatus !== "connected" && (
- <span
- role="img"
- aria-label={t(`live-update.${sseStatus}` as Parameters<typeof t>[0])}
+ {currentUser && (
+ <>
+ <div className="flex h-8 items-center gap-2 px-2">
+ <span className="relative flex size-5 shrink-0 items-center justify-center">
+ <UserAvatar avatarUrl={currentUser.avatarUrl} name={accountLabel} className="size-5 rounded-[5px]" />
+ {sseStatus !== "connected" && (
+ <span
+ role="img"
+ aria-label={t(`live-update.${sseStatus}` as Parameters<typeof t>[0])}
+ className={cn(
+ "absolute -bottom-0.5 -end-0.5 size-2.5 rounded-full border-2 border-popover",
+ sseStatus === "connecting" ? "animate-pulse bg-muted-foreground" : "bg-destructive",
+ )}
+ />
+ )}
+ </span>
+ <span className="min-w-0 flex-1 truncate text-xs font-medium">{accountLabel}</span>
+ <Button
+ variant="ghost"
+ aria-label={inboxLabel}
+ aria-current={inboxActive ? "page" : undefined}
className={cn(
- "absolute -bottom-0.5 -end-0.5 size-2.5 rounded-full border-2 border-popover",
- sseStatus === "connecting" ? "animate-pulse bg-muted-foreground" : "bg-destructive",
+ "h-5 gap-1 rounded-sm bg-muted/60 px-1.5 text-[10px] font-medium text-muted-foreground shadow-none hover:bg-accent hover:text-foreground",
+ inboxActive && "bg-accent text-foreground",
)}
- />
- )}
- </span>
- <span className="min-w-0 flex-1 truncate text-xs font-medium">{accountLabel}</span>
- <Button
- variant="ghost"
- aria-label={inboxLabel}
- aria-current={inboxActive ? "page" : undefined}
- className={cn(
- "h-5 gap-1 rounded-sm bg-muted/60 px-1.5 text-[10px] font-medium text-muted-foreground shadow-none hover:bg-accent hover:text-foreground",
- inboxActive && "bg-accent text-foreground",
- )}
- onClick={() => navigateFromMenu(Routes.INBOX)}
- >
- <BellIcon className="size-3" />
- {t("common.inbox")}
- {unreadCount > 0 && <span className="tabular-nums text-primary">{unreadCount > 99 ? "99+" : unreadCount}</span>}
- </Button>
- </div>
- <Button
- variant="ghost"
- aria-current={archivedActive ? "page" : undefined}
- className={cn(rowClass, archivedActive && "bg-accent")}
- onClick={() => navigateFromMenu(Routes.ARCHIVED)}
- >
- <ArchiveIcon className={iconClass} />
- {t("common.archived")}
- </Button>
- <Button variant="ghost" className={rowClass} onClick={() => navigateFromMenu(Routes.SETTING)}>
- <SettingsIcon className={iconClass} />
- {t("common.settings")}
- </Button>
+ onClick={() => navigateFromMenu(Routes.INBOX)}
+ >
+ <BellIcon className="size-3" />
+ {t("common.inbox")}
+ {unreadCount > 0 && <span className="tabular-nums text-primary">{unreadCount > 99 ? "99+" : unreadCount}</span>}
+ </Button>
+ </div>
+ <Button
+ variant="ghost"
+ aria-current={archivedActive ? "page" : undefined}
+ className={cn(rowClass, archivedActive && "bg-accent")}
+ onClick={() => navigateFromMenu(Routes.ARCHIVED)}
+ >
+ <ArchiveIcon className={iconClass} />
+ {t("common.archived")}
+ </Button>
+ <Button variant="ghost" className={rowClass} onClick={() => navigateFromMenu(Routes.SETTING)}>
+ <SettingsIcon className={iconClass} />
+ {t("common.settings")}
+ </Button>
+ </>
+ )}
<Button variant="ghost" className={rowClass} onClick={() => navigateFromMenu(Routes.ABOUT)}>
<InfoIcon className={iconClass} />
{t("common.about")}
</Button>
- <Button variant="ghost" className={cn(rowClass, "text-muted-foreground")} onClick={() => void handleSignOut()}>
- <LogOutIcon className={iconClass} />
- {t("common.sign-out")}
- </Button>
+ {/* Guests sign in from the sidebar footer, which is always in view. */}
+ {currentUser && (
+ <Button variant="ghost" className={cn(rowClass, "text-muted-foreground")} onClick={() => void handleSignOut()}>
+ <LogOutIcon className={iconClass} />
+ {t("common.sign-out")}
+ </Button>
+ )}
</section>
</>
);
};
-export const UserPreferenceDialog = ({ preference, onClose }: { preference: UserPreference; onClose: () => void }) => {
- const t = useTranslate();
- const currentUser = useCurrentUser();
- const { userGeneralSetting, refetchSettings } = useAuth();
- const { mutate: updateUserGeneralSetting } = useUpdateUserGeneralSetting(currentUser?.name);
- const currentLocale = getLocaleWithFallback(userGeneralSetting?.locale);
- const currentTheme = getThemeWithFallback(userGeneralSetting?.theme);
-
- const handleLocaleChange = (locale: Locale) => {
- if (!currentUser) return;
- loadLocale(locale);
- updateUserGeneralSetting({ generalSetting: { locale }, updateMask: ["locale"] }, { onSuccess: () => refetchSettings() });
- onClose();
- };
-
- const handleThemeChange = (theme: string) => {
- if (!currentUser) return;
- loadTheme(theme);
- updateUserGeneralSetting({ generalSetting: { theme }, updateMask: ["theme"] }, { onSuccess: () => refetchSettings() });
- onClose();
- };
-
- return (
- <Dialog open onOpenChange={(open) => !open && onClose()}>
- <DialogContent size="sm">
- <DialogHeader>
- <DialogTitle>{preference === "theme" ? t("setting.preference.theme") : t("common.language")}</DialogTitle>
- <DialogDescription>
- {preference === "theme" ? t("setting.preference.theme-description") : t("setting.preference.language-description")}
- </DialogDescription>
- </DialogHeader>
- {preference === "theme" ? (
- <div className="rounded-md border p-1">
- {THEME_OPTIONS.map((option) => (
- <Button
- key={option.value}
- variant="ghost"
- aria-pressed={currentTheme === option.value}
- className={rowClass}
- onClick={() => handleThemeChange(option.value)}
- >
- <span className="min-w-0 flex-1 text-start">{option.label}</span>
- {currentTheme === option.value && <CheckIcon className="size-3.5 shrink-0" />}
- </Button>
- ))}
- </div>
- ) : (
- <LocaleSearchList value={currentLocale} onChange={handleLocaleChange} className="w-full max-w-none" />
- )}
- </DialogContent>
- </Dialog>
- );
-};
-
export default UserMenu;
diff --git a/web/src/hooks/useUserTheme.ts b/web/src/hooks/useUserTheme.ts
index bfc6fd9b9..a34558d26 100644
--- a/web/src/hooks/useUserTheme.ts
+++ b/web/src/hooks/useUserTheme.ts
@@ -18,20 +18,12 @@ export const useUserTheme = () => {
loadTheme(theme);
}, [userGeneralSetting?.theme]);
- // Listen for system theme changes when using "system" theme
+ // Read the latest preference on each change, including local-only guest choices.
useEffect(() => {
- const theme = getThemeWithFallback(userGeneralSetting?.theme);
-
- // Only set up listener if theme is "system"
- if (theme !== "system") {
- return;
- }
-
- // Set up listener for OS theme preference changes
- const cleanup = setupSystemThemeListener(() => {
- loadTheme(theme);
+ return setupSystemThemeListener(() => {
+ if (getThemeWithFallback(userGeneralSetting?.theme) === "system") {
+ loadTheme("system");
+ }
});
-
- return cleanup;
}, [userGeneralSetting?.theme]);
};
diff --git a/web/src/router/index.tsx b/web/src/router/index.tsx
index e8eb44504..ff2433ea9 100644
--- a/web/src/router/index.tsx
+++ b/web/src/router/index.tsx
@@ -97,12 +97,13 @@ export const routeConfig: RouteObject[] = [
children: [{ path: Routes.ABOUT, element: <About /> }],
},
{ path: Routes.EXPLORE, element: <ExploreRoute /> },
+ // Like Timeline, the calendar is public: guests see the memos readable to them.
+ { path: CALENDAR_ROUTE_PATTERN, element: <Calendar /> },
{ path: Routes.USER_PROFILE, element: <LegacyProfileRedirect /> },
{
element: <RequireAuthRoute />,
children: [
{ path: Routes.ARCHIVED, element: <Archived /> },
- { path: CALENDAR_ROUTE_PATTERN, element: <Calendar /> },
{
element: <RequireFullInitializationRoute />,
children: [{ path: Routes.VIEWS, element: <MemoViews /> }],
@@ -113,6 +114,10 @@ export const routeConfig: RouteObject[] = [
},
{ path: "memos/:uid", element: <MemoDetail /> },
{ path: "memos/shares/:token", element: <MemoDetail /> },
+ {
+ element: <RequireFullInitializationRoute />,
+ children: [{ path: Routes.MAP, element: <MemoMap /> }],
+ },
{
element: <RequireAuthRoute />,
children: [
@@ -141,7 +146,6 @@ export const routeConfig: RouteObject[] = [
],
},
{ path: Routes.ATTACHMENTS, element: <Attachments /> },
- { path: Routes.MAP, element: <MemoMap /> },
{ path: Routes.INBOX, element: <Inboxes /> },
{ path: Routes.SETTING, element: <Setting /> },
],
diff --git a/web/src/router/routes.ts b/web/src/router/routes.ts
index a8cf74eb0..cad2f91d0 100644
--- a/web/src/router/routes.ts
+++ b/web/src/router/routes.ts
@@ -107,8 +107,10 @@ export const collectionNavigationPath = (
(!route.isCollection || route.pathname === ROUTES.HOME ? currentUsername : undefined));
const filter = route.isCollection ? new URLSearchParams(location.search).get("filter") : null;
const search = filter ? new URLSearchParams({ filter }).toString() : "";
+ // A memo list without a creator is Explore; this also sends guests there from any page.
if (pathname === ROUTES.HOME) {
- return `${getCollectionHomePath(location)}${withCollectionCreator(search, creator === currentUsername ? undefined : creator)}`;
+ const home = buildCollectionPath(creator ? ROUTES.HOME : ROUTES.EXPLORE, route.spaceName);
+ return `${home}${withCollectionCreator(search, creator === currentUsername ? undefined : creator)}`;
}
return `${collectionPathForLocation(pathname, location.pathname)}${withCollectionCreator(search, creator)}`;
};
diff --git a/web/tests/app-sidebar-logo.test.tsx b/web/tests/app-sidebar-logo.test.tsx
index ca90ede36..b678b40a8 100644
--- a/web/tests/app-sidebar-logo.test.tsx
+++ b/web/tests/app-sidebar-logo.test.tsx
@@ -8,7 +8,7 @@ import { type MemoFilter } from "@/contexts/MemoFilterContext";
import { getCollectionCreator, resolveCollectionRoute } from "@/router/routes";
const authState = vi.hoisted(() => ({
- currentUser: { name: "users/test" } as { name: string } | undefined,
+ currentUser: { name: "users/test" } as { name: string; username?: string } | undefined,
memoViews: [] as Array<{ name: string; title: string }>,
notifications: [] as Array<{ status: number }>,
guestCreator: undefined as { username: string; displayName: string; avatarUrl: string } | undefined,
@@ -45,7 +45,6 @@ vi.mock("@/components/UserMenu", () => ({
User menu
</button>
),
- UserPreferenceDialog: () => null,
}));
vi.mock("@/components/CreateSpaceDialog", () => ({
@@ -396,9 +395,14 @@ describe("App sidebar logo", () => {
const navigation = within(primaryNavigation);
expect(navigation.getByRole("button", { name: "common.search" })).toHaveClass("ms-auto", "h-7", "px-1.5");
expectActiveNavPill(navigation.getByRole("link", { name: "common.timeline" }), "common.timeline");
- const about = navigation.getByRole("link", { name: "common.about" });
- expect(about).toHaveAttribute("href", "/about");
- expectCollapsedNavPill(about, "common.about");
+ const calendar = navigation.getByRole("link", { name: "common.calendar" });
+ expect(calendar).toHaveAttribute("href", "/calendar");
+ expectCollapsedNavPill(calendar, "common.calendar");
+ const map = navigation.getByRole("link", { name: "common.map" });
+ expect(map).toHaveAttribute("href", "/map");
+ expectCollapsedNavPill(map, "common.map");
+ expect(navigation.queryByRole("link", { name: "common.about" })).not.toBeInTheDocument();
+ expect(navigation.queryByRole("link", { name: "common.attachments" })).not.toBeInTheDocument();
const signIn = screen.getByRole("link", { name: "common.sign-in-to-memos" });
expect(signIn).toHaveClass("w-full", "px-5");
expect(signIn).not.toHaveClass("rounded-md");
@@ -500,13 +504,14 @@ describe("App sidebar logo", () => {
expectDefaultNavPill(home, "common.timeline");
expect(screen.queryByRole("link", { name: "common.attachments" })).not.toBeInTheDocument();
expect(screen.queryByRole("link", { name: "common.inbox" })).not.toBeInTheDocument();
- const about = navigation.getByRole("link", { name: "common.about" });
- expect(about).toHaveAttribute("href", "/about");
- expectCollapsedNavPill(about, "common.about");
+ expect(navigation.queryByRole("link", { name: "common.about" })).not.toBeInTheDocument();
expect(screen.getByRole("link", { name: "common.sign-in-to-memos" }).closest("footer")).not.toBeNull();
});
- it.each(["/about", "/About/"])("marks About active for a guest on %s", (path) => {
+ it.each([
+ ["/calendar/2026/09", "common.calendar"],
+ ["/map", "common.map"],
+ ])("marks the reading view active for a guest on %s", (path, label) => {
authState.currentUser = undefined;
render(
<MemoryRouter initialEntries={[path]}>
@@ -516,7 +521,7 @@ describe("App sidebar logo", () => {
const navigation = within(screen.getByRole("navigation", { name: "Primary" }));
expectCollapsedNavPill(navigation.getByRole("link", { name: "common.timeline" }), "common.timeline");
- expectActiveNavPill(navigation.getByRole("link", { name: "common.about" }), "common.about");
+ expectActiveNavPill(navigation.getByRole("link", { name: label }), label);
expect(screen.queryByText("Calendar")).not.toBeInTheDocument();
});
@@ -631,6 +636,7 @@ describe("App sidebar logo", () => {
});
it.each(["/inbox", "/archived"])("shows Home as the direct destination from %s", (path) => {
+ authState.currentUser = { name: "users/test", username: "test" };
render(
<MemoryRouter initialEntries={[path]}>
<AppSidebar />
diff --git a/web/tests/router-config.test.tsx b/web/tests/router-config.test.tsx
index 1d5d56012..60b3d82d6 100644
--- a/web/tests/router-config.test.tsx
+++ b/web/tests/router-config.test.tsx
@@ -72,13 +72,13 @@ describe("router configuration", () => {
});
it("wraps authenticated-only pages in RequireAuthRoute", () => {
- for (const path of [ROUTES.ARCHIVED, CALENDAR_ROUTE_PATTERN, ROUTES.VIEWS, ROUTES.ATTACHMENTS, ROUTES.INBOX, ROUTES.SETTING]) {
+ for (const path of [ROUTES.ARCHIVED, ROUTES.VIEWS, ROUTES.ATTACHMENTS, ROUTES.INBOX, ROUTES.SETTING]) {
expect(hasAncestorOfType(routeConfig, path, RequireAuthRoute)).toBe(true);
}
});
it("keeps non-feed pages behind their full initialization requirements", () => {
- for (const path of [ROUTES.VIEWS, ROUTES.ATTACHMENTS, ROUTES.INBOX, ROUTES.SETTING]) {
+ for (const path of [ROUTES.VIEWS, ROUTES.ATTACHMENTS, ROUTES.MAP, ROUTES.INBOX, ROUTES.SETTING]) {
expect(hasAncestorOfType(routeConfig, path, RequireFullInitializationRoute)).toBe(true);
}
expect(hasAncestorOfType(routeConfig, ROUTES.ABOUT, RequireInstanceInitializationRoute)).toBe(true);
@@ -95,7 +95,15 @@ describe("router configuration", () => {
});
it("leaves public pages outside RequireAuthRoute", () => {
- for (const path of [ROUTES.ABOUT, ROUTES.EXPLORE, "memos/:uid", "memos/shares/:token", "u/:username"]) {
+ for (const path of [
+ ROUTES.ABOUT,
+ ROUTES.EXPLORE,
+ CALENDAR_ROUTE_PATTERN,
+ ROUTES.MAP,
+ "memos/:uid",
+ "memos/shares/:token",
+ "u/:username",
+ ]) {
expect(hasAncestorOfType(routeConfig, path, RequireAuthRoute)).toBe(false);
}
});
diff --git a/web/tests/space-routes.test.tsx b/web/tests/space-routes.test.tsx
index aee84d93e..ab7ce278f 100644
--- a/web/tests/space-routes.test.tsx
+++ b/web/tests/space-routes.test.tsx
@@ -74,6 +74,12 @@ describe("Space route contract", () => {
expect(collectionNavigationPath("/", { pathname: "/calendar", search: "" }, "alice")).toBe("/explore");
expect(collectionNavigationPath("/", { pathname: "/calendar", search: "?creator=alice" }, "alice")).toBe("/");
});
+ it("sends guests to Explore unless a creator is selected", () => {
+ expect(collectionNavigationPath("/", { pathname: "/about", search: "" })).toBe("/explore");
+ expect(collectionNavigationPath("/", { pathname: "/calendar/2026/09", search: "" })).toBe("/explore");
+ expect(collectionNavigationPath("/", { pathname: "/map", search: "?creator=alice" })).toBe("/?creator=alice");
+ expect(collectionNavigationPath("/", { pathname: "/setting", search: "" }, "alice")).toBe("/");
+ });
it.each(["/", "/calendar", "/map", "/attachments"])("preserves collection filters when navigating to %s", (destination) => {
const filter = "tagSearch:work,contentSearch:a%26b,celSearch:visibility%20%3D%3D%20%22PUBLIC%22";
const search = `?${new URLSearchParams({ creator: "alice", filter, lat: "31", lng: "121", zoom: "12", memo: "memos/a" })}`;
diff --git a/web/tests/space-switcher.test.tsx b/web/tests/space-switcher.test.tsx
index 621571bb4..cc0a69e51 100644
--- a/web/tests/space-switcher.test.tsx
+++ b/web/tests/space-switcher.test.tsx
@@ -21,7 +21,6 @@ const state = vi.hoisted(() => ({
vi.mock("@/components/MemosLogo", () => ({ default: () => <span>Memos</span> }));
vi.mock("@/components/UserMenu", () => ({
default: () => <button type="button">Steven account</button>,
- UserPreferenceDialog: () => null,
}));
vi.mock("@/hooks/useCurrentUser", () => ({
default: () => state.currentUser,
@@ -198,14 +197,11 @@ describe("SpaceSwitcher", () => {
expect(screen.getByRole("link", { name: "Back to common.explore" })).toHaveAttribute("href", "/explore");
expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "space.create" })).not.toBeInTheDocument();
- expect(screen.queryByRole("button", { name: "Steven account" })).not.toBeInTheDocument();
- expect(screen.getByRole("button", { name: "common.sign-in" })).toBeInTheDocument();
fireEvent.click(screen.getByRole("link", { name: "Back to common.explore" }));
expect(router.state.location.pathname).toBe("/explore");
expect(router.state.location.search).toBe("");
expect(screen.getByRole("dialog")).toBeInTheDocument();
- expect(screen.queryByRole("link", { name: "common.home" })).not.toBeInTheDocument();
- expect(screen.getByRole("link", { name: "common.explore" })).toHaveAttribute("aria-current", "page");
+ expect(screen.queryByRole("navigation", { name: "common.browse" })).not.toBeInTheDocument();
});
it("keeps the popup aligned to the sidebar rail and opens Space creation", () => {
@@ -220,4 +216,14 @@ describe("SpaceSwitcher", () => {
fireEvent.click(screen.getByRole("button", { name: "Complete create" }));
expect(state.selectSpace).toHaveBeenCalledWith(state.spaces[0]);
});
+
+ it("gives guests on Explore only the account panel, with no single-choice Browse control", () => {
+ state.currentUser = undefined;
+ renderAt("/explore");
+ openSwitcher();
+ expect(screen.queryByRole("navigation", { name: "common.browse" })).not.toBeInTheDocument();
+ expect(screen.queryByRole("link", { name: /Back to/ })).not.toBeInTheDocument();
+ expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Steven account" })).toBeInTheDocument();
+ });
});
diff --git a/web/tests/user-menu.test.tsx b/web/tests/user-menu.test.tsx
index c406c0d1c..e6ef97562 100644
--- a/web/tests/user-menu.test.tsx
+++ b/web/tests/user-menu.test.tsx
@@ -1,18 +1,20 @@
import { fireEvent, render, screen, within } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { beforeEach, describe, expect, it, vi } from "vitest";
-import UserMenu, { UserPreferenceDialog } from "@/components/UserMenu";
+import UserMenu from "@/components/UserMenu";
import { loadLocale } from "@/utils/i18n";
import { loadTheme } from "@/utils/theme";
const mocks = vi.hoisted(() => ({
navigateTo: vi.fn(),
setMobileOpen: vi.fn(),
- onSelectPreference: vi.fn(),
onClose: vi.fn(),
logout: vi.fn(),
updateGeneralSetting: vi.fn(),
refetchSettings: vi.fn(),
+ currentUser: { name: "users/steven", username: "steven", displayName: "Steven" } as
+ | { name: string; username: string; displayName: string }
+ | undefined,
notifications: [] as Array<{ status: number }>,
}));
@@ -22,44 +24,40 @@ vi.mock("@/contexts/AuthContext", () => ({
}));
vi.mock("@/hooks/useLiveMemoRefresh", () => ({ useSSEConnectionStatus: () => "connected" }));
vi.mock("@/hooks/useCurrentUser", () => ({
- default: () => ({ name: "users/steven", username: "steven", displayName: "Steven" }),
+ default: () => mocks.currentUser,
}));
vi.mock("@/hooks/useNavigateTo", () => ({ default: () => mocks.navigateTo }));
vi.mock("@/hooks/useUserQueries", () => ({
useNotifications: () => ({ data: mocks.notifications }),
useUpdateUserGeneralSetting: () => ({ mutate: mocks.updateGeneralSetting }),
}));
-vi.mock("@/components/LocalePicker", () => ({
- LocaleSearchList: ({ onChange }: { onChange: (locale: string) => void }) => (
- <button type="button" onClick={() => onChange("fr")}>
- Choose French
- </button>
- ),
-}));
vi.mock("@/utils/i18n", async (importOriginal) => ({
...(await importOriginal<typeof import("@/utils/i18n")>()),
- getLocaleWithFallback: () => "en",
- loadLocale: vi.fn(),
+ loadLocale: vi.fn((await importOriginal<typeof import("@/utils/i18n")>()).loadLocale),
useTranslate: () => (key: string) => key,
}));
vi.mock("@/utils/theme", async (importOriginal) => ({
...(await importOriginal<typeof import("@/utils/theme")>()),
- getThemeWithFallback: () => "system",
- loadTheme: vi.fn(),
+ loadTheme: vi.fn((await importOriginal<typeof import("@/utils/theme")>()).loadTheme),
}));
const renderMenu = (path = "/") =>
render(
<MemoryRouter initialEntries={[path]}>
- <UserMenu onSelectPreference={mocks.onSelectPreference} onClose={mocks.onClose} />
+ <UserMenu onClose={mocks.onClose} />
</MemoryRouter>,
);
describe("User menu panel", () => {
beforeEach(() => {
+ mocks.currentUser = { name: "users/steven", username: "steven", displayName: "Steven" };
+ localStorage.clear();
+ localStorage.setItem("memos-locale", "en");
+ localStorage.setItem("memos-theme", "system");
+ vi.mocked(loadTheme).mockClear();
+ vi.mocked(loadLocale).mockClear();
mocks.navigateTo.mockReset();
mocks.setMobileOpen.mockReset();
- mocks.onSelectPreference.mockReset();
mocks.onClose.mockReset();
mocks.logout.mockReset();
mocks.updateGeneralSetting.mockReset();
@@ -93,41 +91,80 @@ describe("User menu panel", () => {
expect(mocks.navigateTo).toHaveBeenCalledWith("/inbox");
});
- it("shows current preferences as direct rows", () => {
+ it("offers guests preferences and About without account pages or a second sign-in", () => {
+ mocks.currentUser = undefined;
+ renderMenu("/explore");
+ expect(screen.getByRole("button", { name: /setting.preference.theme/ })).toBeInTheDocument();
+ for (const name of ["common.inbox", "common.archived", "common.settings", "common.sign-out", "common.sign-in"]) {
+ expect(screen.queryByRole("button", { name })).not.toBeInTheDocument();
+ }
+ fireEvent.click(screen.getByRole("button", { name: "common.about" }));
+ expect(mocks.onClose).toHaveBeenCalledOnce();
+ expect(mocks.setMobileOpen).toHaveBeenCalledWith(false);
+ expect(mocks.navigateTo).toHaveBeenCalledWith("/about");
+ });
+
+ it("shows current preferences on rows that open their choices as submenus", async () => {
renderMenu();
fireEvent.click(screen.getByRole("button", { name: /setting.preference.theme.*Sync with system/ }));
- fireEvent.click(screen.getByRole("button", { name: /common.language.*English/ }));
- expect(mocks.onSelectPreference.mock.calls).toEqual([["theme"], ["language"]]);
- expect(screen.getByRole("button", { name: "common.settings" })).toBeInTheDocument();
+ const themes = await screen.findByRole("menu");
+ expect(within(themes).getByRole("menuitemradio", { name: "Sync with system" })).toHaveAttribute("aria-checked", "true");
+ expect(
+ within(themes)
+ .getAllByRole("menuitemradio")
+ .map((item) => item.textContent),
+ ).toEqual(["Sync with system", "Light", "Dark", "Paper"]);
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
});
- it("applies a theme from a separate dialog", () => {
- render(
- <MemoryRouter>
- <UserPreferenceDialog preference="theme" onClose={mocks.onClose} />
- </MemoryRouter>,
- );
- fireEvent.click(screen.getByRole("button", { name: "Dark" }));
- expect(loadTheme).toHaveBeenCalledWith("default-dark");
+ it.each([
+ {
+ row: /setting.preference.theme/,
+ choice: "Dark",
+ load: loadTheme,
+ value: "default-dark",
+ field: "theme",
+ label: /setting.preference.theme.*Dark/,
+ },
+ { row: /common.language/, choice: "Français", load: loadLocale, value: "fr", field: "locale", label: /common.language.*Français/ },
+ ] as const)("applies and saves $field from its submenu", async ({ row, choice, load, value, field, label }) => {
+ renderMenu();
+ fireEvent.click(screen.getByRole("button", { name: row }));
+ fireEvent.click(await screen.findByRole("menuitemradio", { name: choice }));
+ expect(load).toHaveBeenCalledWith(value);
expect(mocks.updateGeneralSetting).toHaveBeenCalledWith(
- { generalSetting: { theme: "default-dark" }, updateMask: ["theme"] },
+ { generalSetting: { [field]: value }, updateMask: [field] },
expect.objectContaining({ onSuccess: expect.any(Function) }),
);
- expect(mocks.onClose).toHaveBeenCalledOnce();
+ expect(screen.getByRole("button", { name: label })).toBeInTheDocument();
+ expect(mocks.onClose).not.toHaveBeenCalled();
});
- it("applies a locale from a separate dialog", () => {
- render(
- <MemoryRouter>
- <UserPreferenceDialog preference="language" onClose={mocks.onClose} />
- </MemoryRouter>,
- );
- fireEvent.click(screen.getByRole("button", { name: "Choose French" }));
- expect(loadLocale).toHaveBeenCalledWith("fr");
- expect(mocks.updateGeneralSetting).toHaveBeenCalledWith(
- { generalSetting: { locale: "fr" }, updateMask: ["locale"] },
- expect.objectContaining({ onSuccess: expect.any(Function) }),
- );
- expect(mocks.onClose).toHaveBeenCalledOnce();
+ it.each([
+ {
+ row: /setting.preference.theme/,
+ choice: "Dark",
+ storageKey: "memos-theme",
+ value: "default-dark",
+ label: /setting.preference.theme.*Dark/,
+ },
+ { row: /common.language/, choice: "Français", storageKey: "memos-locale", value: "fr", label: /common.language.*Français/ },
+ ] as const)("persists a guest's choice of $storageKey locally without updating an account", async ({
+ row,
+ choice,
+ storageKey,
+ value,
+ label,
+ }) => {
+ mocks.currentUser = undefined;
+ const menu = renderMenu("/explore");
+ fireEvent.click(screen.getByRole("button", { name: row }));
+ fireEvent.click(await screen.findByRole("menuitemradio", { name: choice }));
+ expect(localStorage.getItem(storageKey)).toBe(value);
+ expect(mocks.updateGeneralSetting).not.toHaveBeenCalled();
+ expect(mocks.refetchSettings).not.toHaveBeenCalled();
+ menu.unmount();
+ renderMenu("/explore");
+ expect(screen.getByRole("button", { name: label })).toBeInTheDocument();
});
});
diff --git a/web/tests/user-theme.test.tsx b/web/tests/user-theme.test.tsx
new file mode 100644
index 000000000..cef9a9c95
--- /dev/null
+++ b/web/tests/user-theme.test.tsx
@@ -0,0 +1,42 @@
+import { renderHook } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { useUserTheme } from "@/hooks/useUserTheme";
+import { loadTheme } from "@/utils/theme";
+
+vi.mock("@/contexts/AuthContext", () => ({
+ useAuth: () => ({ userGeneralSetting: undefined }),
+}));
+
+describe("guest theme preferences", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ localStorage.clear();
+ });
+
+ it.each(["system", "default-dark"])("respects local changes after starting with %s", (initialTheme) => {
+ let dark = false;
+ const changes = new EventTarget();
+ vi.stubGlobal("matchMedia", () => ({
+ get matches() {
+ return dark;
+ },
+ addEventListener: changes.addEventListener.bind(changes),
+ removeEventListener: changes.removeEventListener.bind(changes),
+ }));
+ loadTheme(initialTheme);
+ renderHook(() => useUserTheme());
+
+ loadTheme("paper");
+ dark = true;
+ changes.dispatchEvent(new Event("change"));
+ expect(document.documentElement).toHaveAttribute("data-theme", "paper");
+ expect(localStorage.getItem("memos-theme")).toBe("paper");
+
+ loadTheme("system");
+ expect(document.documentElement).toHaveAttribute("data-theme", "default-dark");
+ dark = false;
+ changes.dispatchEvent(new Event("change"));
+ expect(document.documentElement).toHaveAttribute("data-theme", "default");
+ expect(localStorage.getItem("memos-theme")).toBe("system");
+ });
+});