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.

feat(web): unify navigation in a route-aware sidebar (#6144)

Johnny4d2667983fd3
diff --git a/web/src/components/AboutDialog.tsx b/web/src/components/AboutDialog.tsx
new file mode 100644
index 000000000..fb12a783a
--- /dev/null
+++ b/web/src/components/AboutDialog.tsx
@@ -0,0 +1,140 @@
+import { ExternalLinkIcon, ScissorsIcon } from "lucide-react";
+import { Badge } from "@/components/ui/badge";
+import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
+import { useInstance } from "@/contexts/InstanceContext";
+import { WEB_CLIPPER_URL } from "@/lib/constants";
+import { useTranslate } from "@/utils/i18n";
+
+const GITHUB_COMMIT_URL_PREFIX = "https://github.com/usememos/memos/commit/";
+const GITHUB_RELEASE_URL_PREFIX = "https://github.com/usememos/memos/releases/tag/v";
+
+const DEFAULT_TITLE = "Memos";
+const DEFAULT_TAGLINE = "Capture first. Keep it yours.";
+const DEFAULT_LOGO = "/logo.webp";
+
+const isCommitSha = (commit: string) => /^[0-9a-f]{7,40}$/i.test(commit);
+const isSemver = (version: string) => /^\d+\.\d+\.\d+/.test(version);
+
+const Chip = ({ href, children }: { href?: string; children: React.ReactNode }) => {
+ const className = "inline-flex items-center rounded-full bg-muted px-2.5 py-0.5 font-mono text-xs text-muted-foreground";
+ if (href) {
+ return (
+ <a className={`${className} hover:bg-accent hover:text-foreground`} href={href} target="_blank" rel="noreferrer">
+ {children}
+ </a>
+ );
+ }
+ return <span className={className}>{children}</span>;
+};
+
+const SectionLabel = ({ children }: { children: React.ReactNode }) => (
+ <h3 className="text-[10px] font-semibold uppercase tracking-[0.09em] text-muted-foreground/55">{children}</h3>
+);
+
+interface Props {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}
+
+const AboutDialog = ({ open, onOpenChange }: Props) => {
+ const t = useTranslate();
+ const { profile, generalSetting } = useInstance();
+
+ const customProfile = generalSetting.customProfile;
+ const instanceTitle = customProfile?.title || DEFAULT_TITLE;
+ const instanceTagline = customProfile?.description || DEFAULT_TAGLINE;
+ const instanceLogo = customProfile?.logoUrl || DEFAULT_LOGO;
+ const isCustomBranded = instanceTitle !== DEFAULT_TITLE;
+
+ const hasSemver = isSemver(profile.version);
+ const releaseUrl = hasSemver ? `${GITHUB_RELEASE_URL_PREFIX}${profile.version}` : "";
+ const versionLabel = hasSemver ? `v${profile.version}` : profile.version;
+ const hasCommitSha = isCommitSha(profile.commit);
+ const commitUrl = hasCommitSha ? `${GITHUB_COMMIT_URL_PREFIX}${profile.commit}` : "";
+ const shortCommit = hasCommitSha ? profile.commit.slice(0, 7) : "";
+
+ const buildRows: { label: string; value: React.ReactNode }[] = [];
+ if (profile.version) {
+ buildRows.push({ label: t("common.version"), value: <Chip href={releaseUrl || undefined}>{versionLabel}</Chip> });
+ }
+ if (shortCommit) {
+ buildRows.push({ label: t("about.commit"), value: <Chip href={commitUrl}>{shortCommit}</Chip> });
+ }
+ buildRows.push({ label: t("about.license"), value: <Chip href="https://github.com/usememos/memos/blob/main/LICENSE">MIT</Chip> });
+ if (isCustomBranded) {
+ buildRows.push({
+ label: t("about.distribution"),
+ value: <span className="text-[13px] text-muted-foreground">{t("about.powered-by")}</span>,
+ });
+ }
+
+ const projectLinks = [
+ { label: t("about.official-website"), note: t("about.official-website-note"), href: "https://usememos.com/" },
+ { label: t("about.documents"), note: t("about.documents-note"), href: "https://usememos.com/docs" },
+ { label: t("about.api-docs"), note: t("about.api-docs-note"), href: "https://usememos.com/docs/api" },
+ {
+ label: t("about.github-repository"),
+ note: t("about.github-repository-note"),
+ href: "https://github.com/usememos/memos",
+ },
+ { label: t("about.web-clipper"), note: t("about.web-clipper-platforms"), href: WEB_CLIPPER_URL, icon: ScissorsIcon },
+ ];
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent size="xl" className="overflow-hidden border-border/70 p-0! shadow-xl">
+ <DialogTitle className="sr-only">{t("common.about")}</DialogTitle>
+ <div className="px-5 pb-5 pt-5 sm:px-6 sm:pb-6 sm:pt-6">
+ <header className="flex items-start gap-3 pr-8">
+ <img className="size-10 shrink-0 select-none rounded-md" src={instanceLogo} alt="" draggable={false} />
+ <div className="min-w-0 pt-0.5">
+ <div className="flex flex-wrap items-center gap-2">
+ <h2 className="truncate text-[16px] font-semibold tracking-[-0.01em] text-foreground">{instanceTitle}</h2>
+ {profile.demo && <Badge variant="warning">{t("about.demo")}</Badge>}
+ </div>
+ <p className="mt-0.5 text-[13px] leading-5 text-muted-foreground">{instanceTagline}</p>
+ </div>
+ </header>
+
+ <section className="mt-6">
+ <SectionLabel>{t("about.build")}</SectionLabel>
+ <dl className="mt-2 border-t border-border/70">
+ {buildRows.map((row) => (
+ <div key={row.label} className="grid grid-cols-[96px_1fr] items-center border-b border-border/60 py-2">
+ <dt className="text-[12px] text-muted-foreground">{row.label}</dt>
+ <dd className="m-0 flex min-w-0 items-center">{row.value}</dd>
+ </div>
+ ))}
+ </dl>
+ </section>
+
+ <section className="mt-6">
+ <SectionLabel>{t("about.project")}</SectionLabel>
+ <nav aria-label={t("about.project-links")} className="mt-2 border-t border-border/70">
+ {projectLinks.map((link) => (
+ <a
+ key={link.href}
+ className="group flex items-center justify-between gap-4 border-b border-border/60 py-2.5"
+ href={link.href}
+ target="_blank"
+ rel="noreferrer"
+ >
+ <span className="flex min-w-0 items-center gap-2">
+ {link.icon && <link.icon className="size-3.5 shrink-0 text-muted-foreground" />}
+ <span className="truncate text-[13px] font-medium text-foreground group-hover:underline group-hover:underline-offset-2">
+ {link.label}
+ </span>
+ <span className="hidden truncate text-xs text-muted-foreground sm:inline">{link.note}</span>
+ </span>
+ <ExternalLinkIcon className="size-3 shrink-0 text-muted-foreground group-hover:text-foreground" />
+ </a>
+ ))}
+ </nav>
+ </section>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+};
+
+export default AboutDialog;
diff --git a/web/src/components/ActivityCalendar/CalendarCell.tsx b/web/src/components/ActivityCalendar/CalendarCell.tsx
index 1b03d50b5..e3d1d426a 100644
--- a/web/src/components/ActivityCalendar/CalendarCell.tsx
+++ b/web/src/components/ActivityCalendar/CalendarCell.tsx
@@ -27,7 +27,7 @@ export const CalendarCell = memo((props: CalendarCellProps) => {
const smallExtraClasses = size === "small" ? `${SMALL_CELL_SIZE.dimensions} min-h-0` : "";
const baseClasses = cn(
- "aspect-square w-full flex items-center justify-center text-center transition-all duration-150 select-none border border-border/10 bg-muted/20",
+ "relative aspect-square w-full flex items-center justify-center text-center transition-[background-color,color,filter,box-shadow] duration-150 ease-out select-none",
sizeConfig.font,
sizeConfig.borderRadius,
smallExtraClasses,
@@ -36,7 +36,7 @@ export const CalendarCell = memo((props: CalendarCellProps) => {
const ariaLabel = day.isSelected ? `${tooltipText} (selected)` : tooltipText;
if (!day.isCurrentMonth) {
- return <div className={cn(baseClasses, "text-muted-foreground/30 bg-transparent border-transparent cursor-default")}>{day.label}</div>;
+ return <div className={cn(baseClasses, "text-muted-foreground/25 bg-transparent cursor-default")}>{day.label}</div>;
}
const intensityClass = getCellIntensityClass(day, maxCount);
@@ -46,7 +46,9 @@ export const CalendarCell = memo((props: CalendarCellProps) => {
baseClasses,
intensityClass,
getCalendarCellStateClass(day),
- isInteractive ? "cursor-pointer hover:bg-muted/40 hover:border-border/30" : "cursor-default",
+ isInteractive
+ ? "cursor-pointer hover:brightness-[0.97] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40 focus-visible:ring-inset"
+ : "cursor-default",
);
const button = (
@@ -60,6 +62,12 @@ export const CalendarCell = memo((props: CalendarCellProps) => {
className={buttonClasses}
>
{day.label}
+ {day.isToday && (
+ <span
+ aria-hidden="true"
+ className="absolute bottom-[3px] left-1/2 size-[3px] -translate-x-1/2 rounded-full bg-blue-600/80 dark:bg-blue-300/80"
+ />
+ )}
</button>
);
diff --git a/web/src/components/ActivityCalendar/MonthCalendar.tsx b/web/src/components/ActivityCalendar/MonthCalendar.tsx
index 7c114c316..d1ce6b0a0 100644
--- a/web/src/components/ActivityCalendar/MonthCalendar.tsx
+++ b/web/src/components/ActivityCalendar/MonthCalendar.tsx
@@ -9,8 +9,8 @@ import { useCalendarMatrix } from "./useCalendar";
import { getTooltipText } from "./utils";
const GRID_STYLES: Record<CalendarSize, { gap: string; headerText: string }> = {
- small: { gap: "gap-1.5", headerText: "text-[10px]" },
- default: { gap: "gap-2", headerText: "text-xs" },
+ small: { gap: "gap-1", headerText: "text-[9px]" },
+ default: { gap: "gap-1", headerText: "text-[10px]" },
};
interface WeekdayHeaderProps {
@@ -19,15 +19,15 @@ interface WeekdayHeaderProps {
}
const WeekdayHeader = memo(({ weekDays, size }: WeekdayHeaderProps) => (
- <div className={cn("grid grid-cols-7 mb-1", GRID_STYLES[size].gap, GRID_STYLES[size].headerText)} role="row">
+ <div className={cn("mb-1.5 grid grid-cols-7", GRID_STYLES[size].gap, GRID_STYLES[size].headerText)} role="row">
{weekDays.map((label, index) => (
<div
key={index}
- className="flex h-4 items-center justify-center uppercase tracking-wide text-muted-foreground/60"
+ className="flex h-5 items-center justify-center font-medium uppercase tracking-[0.04em] text-muted-foreground/50"
role="columnheader"
aria-label={label}
>
- {label}
+ {Array.from(label)[0]}
</div>
))}
</div>
diff --git a/web/src/components/ActivityCalendar/YearCalendar.tsx b/web/src/components/ActivityCalendar/YearCalendar.tsx
index 4e357f16e..c34b8f16e 100644
--- a/web/src/components/ActivityCalendar/YearCalendar.tsx
+++ b/web/src/components/ActivityCalendar/YearCalendar.tsx
@@ -25,18 +25,18 @@ const YearNavigation = memo(({ selectedYear, currentYear, onPrev, onNext, onToda
return (
<div className="flex items-center justify-between px-1">
- <h2 className="text-2xl font-semibold text-foreground tracking-tight">{selectedYear}</h2>
+ <h2 className="text-xl font-semibold tracking-[-0.02em] text-foreground/90">{selectedYear}</h2>
- <nav className="inline-flex items-center gap-0.5 rounded-lg border border-border/30 bg-muted/10 p-0.5" aria-label="Year navigation">
+ <nav className="inline-flex items-center gap-1" aria-label="Year navigation">
<Button
variant="ghost"
- size="sm"
+ size="icon-sm"
onClick={onPrev}
disabled={!canGoPrev}
aria-label="Previous year"
- className="h-7 w-7 p-0 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted/40"
+ className="size-7 rounded-md text-muted-foreground/65 hover:bg-muted/50 hover:text-foreground/90"
>
- <ChevronLeftIcon className="w-4 h-4" />
+ <ChevronLeftIcon className="size-[15px]" strokeWidth={1.75} />
</Button>
<Button
@@ -46,8 +46,10 @@ const YearNavigation = memo(({ selectedYear, currentYear, onPrev, onNext, onToda
disabled={isCurrentYear}
aria-label={t("common.today")}
className={cn(
- "h-7 px-2.5 rounded-md text-[10px] font-medium uppercase tracking-wider",
- isCurrentYear ? "text-muted-foreground/50 cursor-default" : "text-muted-foreground hover:text-foreground hover:bg-muted/40",
+ "h-7 rounded-md px-2.5 text-[11px] font-medium",
+ isCurrentYear
+ ? "cursor-default text-muted-foreground/40"
+ : "text-muted-foreground/65 hover:bg-muted/50 hover:text-foreground/90",
)}
>
{t("common.today")}
@@ -55,13 +57,13 @@ const YearNavigation = memo(({ selectedYear, currentYear, onPrev, onNext, onToda
<Button
variant="ghost"
- size="sm"
+ size="icon-sm"
onClick={onNext}
disabled={!canGoNext}
aria-label="Next year"
- className="h-7 w-7 p-0 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted/40"
+ className="size-7 rounded-md text-muted-foreground/65 hover:bg-muted/50 hover:text-foreground/90"
>
- <ChevronRightIcon className="w-4 h-4" />
+ <ChevronRightIcon className="size-[15px]" strokeWidth={1.75} />
</Button>
</nav>
</div>
@@ -78,8 +80,10 @@ interface MonthCardProps {
}
const MonthCard = memo(({ month, data, maxCount, onDateClick, timeBasis }: MonthCardProps) => (
- <article className="flex flex-col gap-2 rounded-xl border border-border/20 bg-muted/5 p-3 transition-colors hover:bg-muted/10">
- <header className="text-[10px] font-medium text-muted-foreground/80 uppercase tracking-widest">{getMonthLabel(month)}</header>
+ <article className="flex flex-col gap-2 rounded-lg bg-muted/10 p-3 transition-colors hover:bg-muted/20">
+ <header className="text-[10px] font-medium uppercase leading-4 tracking-[0.08em] text-muted-foreground/60">
+ {getMonthLabel(month)}
+ </header>
<MonthCalendar month={month} data={data} maxCount={maxCount} size="small" onClick={onDateClick} disableTooltips timeBasis={timeBasis} />
</article>
));
@@ -95,7 +99,7 @@ export const YearCalendar = memo(({ selectedYear, data, onYearChange, onDateClic
const canGoNext = selectedYear < getMaxYear();
return (
- <section className={cn("w-full flex flex-col gap-5 px-4 py-4 select-none", className)} aria-label={`Year ${selectedYear} calendar`}>
+ <section className={cn("flex w-full flex-col gap-4 px-5 py-5 select-none", className)} aria-label={`Year ${selectedYear} calendar`}>
<YearNavigation
selectedYear={selectedYear}
currentYear={currentYear}
@@ -106,7 +110,7 @@ export const YearCalendar = memo(({ selectedYear, data, onYearChange, onDateClic
canGoNext={canGoNext}
/>
- <div className="grid gap-4 grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 animate-fade-in">
+ <div className="grid grid-cols-1 gap-3.5 animate-fade-in sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4">
{months.map((month) => (
<MonthCard key={month} month={month} data={yearData} maxCount={yearMaxCount} onDateClick={onDateClick} timeBasis={timeBasis} />
))}
diff --git a/web/src/components/ActivityCalendar/constants.ts b/web/src/components/ActivityCalendar/constants.ts
index de457971b..f46c12289 100644
--- a/web/src/components/ActivityCalendar/constants.ts
+++ b/web/src/components/ActivityCalendar/constants.ts
@@ -13,22 +13,22 @@ export const INTENSITY_THRESHOLDS = {
} as const;
export const CELL_STYLES = {
- HIGH: "bg-primary text-primary-foreground shadow-sm border-transparent",
- MEDIUM: "bg-primary/85 text-primary-foreground shadow-sm border-transparent",
- LOW: "bg-primary/70 text-primary-foreground border-transparent",
- MINIMAL: "bg-primary/50 text-foreground border-transparent",
- EMPTY: "bg-muted/20 text-muted-foreground hover:bg-muted/30 border-border/10",
+ HIGH: "bg-blue-400/60 text-foreground/85",
+ MEDIUM: "bg-blue-400/45 text-foreground/80",
+ LOW: "bg-blue-400/30 text-foreground/80",
+ MINIMAL: "bg-blue-400/18 text-foreground/75",
+ EMPTY: "bg-transparent text-foreground/75 hover:bg-muted/40",
} as const;
export const SMALL_CELL_SIZE = {
- font: "text-[11px]",
+ font: "text-[10px] font-normal leading-none tracking-[-0.01em] tabular-nums",
dimensions: "w-full h-full",
- borderRadius: "rounded-lg",
- gap: "gap-1.5",
+ borderRadius: "rounded-md",
+ gap: "gap-1",
} as const;
export const DEFAULT_CELL_SIZE = {
- font: "text-xs",
- borderRadius: "rounded-lg",
- gap: "gap-2",
+ font: "text-xs font-normal leading-none tracking-[-0.01em] tabular-nums",
+ borderRadius: "rounded-md",
+ gap: "gap-1",
} as const;
diff --git a/web/src/components/ActivityCalendar/utils.ts b/web/src/components/ActivityCalendar/utils.ts
index 60f91b584..51d9b8fa0 100644
--- a/web/src/components/ActivityCalendar/utils.ts
+++ b/web/src/components/ActivityCalendar/utils.ts
@@ -2,7 +2,6 @@ import dayjs from "dayjs";
import isSameOrAfter from "dayjs/plugin/isSameOrAfter";
import isSameOrBefore from "dayjs/plugin/isSameOrBefore";
import type { MemoTimeBasis } from "@/contexts/ViewContext";
-import { cn } from "@/lib/utils";
import { useTranslate } from "@/utils/i18n";
import { CELL_STYLES, INTENSITY_THRESHOLDS, MIN_COUNT, MONTHS_IN_YEAR } from "./constants";
import type { CalendarData, CalendarDayCell } from "./types";
@@ -24,9 +23,8 @@ export const getCellIntensityClass = (day: CalendarDayCell, maxCount: number): s
return CELL_STYLES.MINIMAL;
};
-export const getCalendarCellStateClass = (day: Pick<CalendarDayCell, "isToday" | "isSelected">): string => {
- return cn(day.isToday && "font-semibold z-10", day.isSelected && "font-bold z-10");
-};
+export const getCalendarCellStateClass = (day: Pick<CalendarDayCell, "isSelected">): string =>
+ day.isSelected ? "z-10 ring-2 ring-blue-500/70 ring-inset" : "";
export const generateMonthsForYear = (year: number): string[] => {
return Array.from({ length: MONTHS_IN_YEAR }, (_, i) => dayjs(`${year}-01-01`).add(i, "month").format("YYYY-MM"));
diff --git a/web/src/components/AppSidebar/AppSidebar.tsx b/web/src/components/AppSidebar/AppSidebar.tsx
new file mode 100644
index 000000000..23c10436d
--- /dev/null
+++ b/web/src/components/AppSidebar/AppSidebar.tsx
@@ -0,0 +1,682 @@
+import {
+ ArchiveIcon,
+ ArrowRightIcon,
+ BellIcon,
+ ChevronDownIcon,
+ EarthIcon,
+ FileAudioIcon,
+ FileTextIcon,
+ HouseIcon,
+ ImageIcon,
+ InfoIcon,
+ LayoutListIcon,
+ ListIcon,
+ ListTodoIcon,
+ type LucideIcon,
+ MapIcon,
+ MenuIcon,
+ MoreHorizontalIcon,
+ PaperclipIcon,
+ PlusIcon,
+ SearchIcon,
+ SparklesIcon,
+ Trash2Icon,
+ UserRoundIcon,
+} from "lucide-react";
+import { 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 { 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 { shortcutServiceClient } from "@/connect";
+import { type AttachmentSection, type InboxFilter, useAppSidebar } from "@/contexts/AppSidebarContext";
+import { useAuth } from "@/contexts/AuthContext";
+import { useInstance } from "@/contexts/InstanceContext";
+import { stringifyFilters, useMemoFilterContext } from "@/contexts/MemoFilterContext";
+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 {
+ BUILTIN_TASKS_VIEW_ID,
+ getMemoScopePath,
+ getShortcutId,
+ isMemoScopeRoute,
+ type MemoScope,
+ 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 { Shortcut } from "@/types/proto/api/v1/shortcut_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 } from "./routes";
+import SidebarRow, { SIDEBAR_ROW_CLASSES, SIDEBAR_ROW_ICON_CLASSES } from "./SidebarRow";
+import SidebarSectionHeader from "./SidebarSectionHeader";
+import TagsSection from "./TagsSection";
+
+const SIDEBAR_HORIZONTAL_PADDING = "px-3";
+
+const ViewsSection = ({ manageActive = false }: { manageActive?: boolean }) => {
+ const t = useTranslate();
+ const navigate = useNavigate();
+ const { shortcuts, refetchSettings } = useAuth();
+ const { shortcut: selectedShortcut, setShortcut } = useMemoFilterContext();
+ const { setMobileOpen } = useAppSidebar();
+ const [deleteTarget, setDeleteTarget] = useState<Shortcut>();
+ const location = useLocation();
+
+ const handleView = (viewId: string) => {
+ setShortcut(selectedShortcut === viewId ? undefined : viewId);
+ if (!isMemoScopeRoute(location.pathname)) navigate(ROUTES.HOME);
+ setMobileOpen(false);
+ };
+
+ const handleCreate = () => {
+ navigate(ROUTES.SHORTCUTS, { state: { openCreate: true } });
+ setMobileOpen(false);
+ };
+
+ const handleDelete = async () => {
+ if (!deleteTarget) return;
+ await shortcutServiceClient.deleteShortcut({ name: deleteTarget.name });
+ await refetchSettings();
+ if (selectedShortcut === getShortcutId(deleteTarget.name)) setShortcut(undefined);
+ toast.success(t("setting.shortcut.delete-success", { title: deleteTarget.title }));
+ setDeleteTarget(undefined);
+ };
+
+ return (
+ <section>
+ <SidebarSectionHeader
+ action={
+ !manageActive && (
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ className="size-5 rounded text-muted-foreground"
+ onClick={handleCreate}
+ aria-label={t("common.create")}
+ >
+ <PlusIcon className="size-3.5" />
+ </Button>
+ )
+ }
+ >
+ {t("common.views")}
+ </SidebarSectionHeader>
+ <div className="space-y-0.5">
+ <SidebarRow
+ active={!manageActive && selectedShortcut === BUILTIN_TASKS_VIEW_ID}
+ icon={ListTodoIcon}
+ label={t("common.tasks")}
+ onClick={() => handleView(BUILTIN_TASKS_VIEW_ID)}
+ />
+ {shortcuts.map((shortcut) => {
+ const id = getShortcutId(shortcut.name);
+ const active = !manageActive && selectedShortcut === id;
+ return (
+ <div
+ key={shortcut.name}
+ className={cn(
+ SIDEBAR_ROW_CLASSES,
+ "group/view",
+ active
+ ? "bg-sidebar-accent font-medium text-sidebar-accent-foreground"
+ : "text-muted-foreground hover:bg-sidebar-accent/65 hover:text-foreground",
+ )}
+ >
+ <button
+ type="button"
+ onClick={() => handleView(id)}
+ aria-pressed={active || undefined}
+ className="flex h-full min-w-0 flex-1 items-center gap-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
+ >
+ <SparklesIcon className={SIDEBAR_ROW_ICON_CLASSES} strokeWidth={1.8} />
+ <span className="min-w-0 flex-1 truncate">{shortcut.title}</span>
+ </button>
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ nativeButton={false}
+ render={
+ <span
+ role="button"
+ tabIndex={0}
+ aria-label={`${t("common.edit")} ${shortcut.title}`}
+ className="-mr-1 flex size-6 shrink-0 items-center justify-center rounded text-muted-foreground transition-opacity hover:bg-background/70 md:opacity-0 md:group-hover/view:opacity-100 md:focus-visible:opacity-100 data-popup-open:opacity-100"
+ />
+ }
+ >
+ <MoreHorizontalIcon className="size-3.5" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ onClick={() => {
+ navigate(ROUTES.SHORTCUTS, { state: { shortcut } });
+ setMobileOpen(false);
+ }}
+ >
+ {t("common.edit")}
+ </DropdownMenuItem>
+ <DropdownMenuItem variant="destructive" onClick={() => setDeleteTarget(shortcut)}>
+ <Trash2Icon className="size-4" />
+ {t("common.delete")}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ );
+ })}
+ {manageActive && <SidebarRow active icon={MoreHorizontalIcon} label={t("common.shortcuts")} />}
+ </div>
+ <ConfirmDialog
+ open={!!deleteTarget}
+ onOpenChange={(open) => !open && setDeleteTarget(undefined)}
+ title={t("setting.shortcut.delete-confirm", { title: deleteTarget?.title ?? "" })}
+ confirmLabel={t("common.delete")}
+ cancelLabel={t("common.cancel")}
+ onConfirm={handleDelete}
+ confirmVariant="destructive"
+ />
+ </section>
+ );
+};
+
+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 (
+ <div className="space-y-0.5">
+ <SidebarRow active={active === "memos"} icon={LayoutListIcon} label={t("common.memos")} onClick={() => setMode("memos")} />
+ <SidebarRow active={active === "map"} icon={MapIcon} label={t("common.map")} onClick={() => setMode("map")} />
+ </div>
+ );
+};
+
+const CollectionSidebarContent = ({ context }: { context: MemoStatsContext }) => {
+ const location = useLocation();
+ const currentUser = useCurrentUser();
+ 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;
+ const { statistics, tags } = useFilteredMemoStats({
+ context,
+ userName: statsUserName,
+ enabled: authInitialized && instanceInitialized && (md || mobileOpen),
+ });
+
+ const showViews = !!currentUser && (context === "home" || context === "archived" || context === "explore");
+
+ return (
+ <div className="space-y-3.5">
+ {context === "profile" && <ProfileMode />}
+ <section>
+ <StatisticsView statisticsData={statistics} onDateSelect={() => setMobileOpen(false)} />
+ </section>
+ {showViews && <ViewsSection />}
+ <TagsSection tagCount={tags} onSelect={() => setMobileOpen(false)} />
+ </div>
+ );
+};
+
+const AttachmentsSidebarContent = () => {
+ const t = useTranslate();
+ const { attachmentSection, setAttachmentSection, setMobileOpen } = useAppSidebar();
+ const { isComplete, stats } = useAttachmentLibraryStats();
+ 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,
+ },
+ { value: "unused", icon: Trash2Icon, label: t("attachment-library.labels.unused"), count: isComplete ? stats.unused : undefined },
+ ];
+ return (
+ <div className="space-y-0.5">
+ {rows.map((row) => (
+ <SidebarRow
+ key={row.value}
+ active={attachmentSection === row.value}
+ icon={row.icon}
+ label={row.label}
+ count={row.count}
+ onClick={() => {
+ setAttachmentSection(row.value);
+ setMobileOpen(false);
+ }}
+ />
+ ))}
+ </div>
+ );
+};
+
+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 (
+ <div className="space-y-0.5">
+ {rows.map((row) => (
+ <SidebarRow
+ key={row.value}
+ active={inboxFilter === row.value}
+ icon={row.icon}
+ label={row.label}
+ count={row.count}
+ onClick={() => {
+ setInboxFilter(row.value);
+ setMobileOpen(false);
+ }}
+ />
+ ))}
+ </div>
+ );
+};
+
+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) || "my-account";
+ 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) => (
+ <Link
+ key={section.key}
+ to={`${ROUTES.SETTING}#${section.key}`}
+ onClick={() => setMobileOpen(false)}
+ className={cn(
+ SIDEBAR_ROW_CLASSES,
+ currentSection === section.key
+ ? "bg-sidebar-accent font-medium text-sidebar-accent-foreground"
+ : "text-muted-foreground hover:bg-sidebar-accent/65 hover:text-foreground",
+ )}
+ >
+ <section.icon className={SIDEBAR_ROW_ICON_CLASSES} strokeWidth={1.8} />
+ <span className="truncate">{t(section.labelKey)}</span>
+ </Link>
+ ));
+ return (
+ <div className="space-y-3.5">
+ <section>
+ <SidebarSectionHeader>{t("common.basic")}</SidebarSectionHeader>
+ <div className="space-y-0.5">{renderSections(basic)}</div>
+ </section>
+ {isHost && (
+ <section>
+ <SidebarSectionHeader>{t("common.admin")}</SidebarSectionHeader>
+ <div className="space-y-0.5">{renderSections(admin)}</div>
+ </section>
+ )}
+ </div>
+ );
+};
+
+const MemoDetailSidebarContent = () => {
+ const { memoDetail } = useAppSidebar();
+ if (!memoDetail) return null;
+ return (
+ <MemoDetailSidebar
+ memo={memoDetail.memo}
+ forceReadonly={memoDetail.readonly}
+ onShareImageOpen={memoDetail.onShareImageOpen}
+ className="pb-2"
+ />
+ );
+};
+
+const RouteSidebarContent = () => {
+ const location = useLocation();
+ const kind = getSidebarRouteKind(location.pathname);
+ if (kind === "home" || kind === "archived" || kind === "explore" || kind === "profile") {
+ return <CollectionSidebarContent context={kind} />;
+ }
+ if (kind === "shortcuts") return <ViewsSection manageActive />;
+ if (kind === "attachments") return <AttachmentsSidebarContent />;
+ if (kind === "inbox") return <InboxSidebarContent />;
+ if (kind === "settings") return <SettingsSidebarContent />;
+ if (kind === "memo") return <MemoDetailSidebarContent />;
+ return null;
+};
+
+interface GlobalNavItem {
+ id: string;
+ label: string;
+ path: string;
+ icon: LucideIcon;
+ active: boolean;
+ count?: number;
+ opensDialog?: boolean;
+}
+
+const GlobalNavigation = () => {
+ const t = useTranslate();
+ const location = useLocation();
+ const navigate = useNavigate();
+ const currentUser = useCurrentUser();
+ const { data: notifications = [] } = useNotifications();
+ const { memoDetail, memoScope, setAboutOpen, setMemoScope, setMobileOpen } = useAppSidebar();
+ const { filters } = useMemoFilterContext();
+ const unreadCount = notifications.filter((notification) => notification.status === UserNotification_Status.UNREAD).length;
+ 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 routeOwnsScope = isMemoScopeRoute(location.pathname) || routeKind === "profile" || routeKind === "memo";
+ const scopeRouteActive = isMemoScopeRoute(location.pathname);
+
+ useEffect(() => {
+ if (routeOwnsScope && resolvedScope !== memoScope) {
+ setMemoScope(resolvedScope);
+ }
+ }, [memoScope, resolvedScope, routeOwnsScope, setMemoScope]);
+
+ const scopeItems: Array<{ id: MemoScope; label: string; icon: LucideIcon }> = [
+ { id: "home", label: t("common.home"), icon: HouseIcon },
+ { id: "explore", label: t("common.explore"), icon: EarthIcon },
+ { id: "archived", label: t("common.archived"), icon: ArchiveIcon },
+ ];
+ const activeScopeItem = scopeItems.find((item) => item.id === resolvedScope) ?? scopeItems[0];
+ const ActiveScopeIcon = activeScopeItem.icon;
+
+ const navigateToScope = (scope: MemoScope) => {
+ 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: location.pathname === ROUTES.ATTACHMENTS,
+ },
+ {
+ id: "inbox",
+ label: t("common.inbox"),
+ path: ROUTES.INBOX,
+ icon: BellIcon,
+ active: location.pathname === ROUTES.INBOX,
+ count: unreadCount,
+ },
+ ]
+ : [
+ {
+ 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: false, opensDialog: true },
+ ];
+
+ const scopeTrigger = (
+ <DropdownMenuTrigger
+ render={
+ <button
+ type="button"
+ aria-label={activeScopeItem.label}
+ aria-current="page"
+ className="flex h-[30px] min-w-0 items-center gap-2 rounded-md bg-sidebar-accent px-2 font-medium text-sidebar-accent-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
+ />
+ }
+ >
+ <ActiveScopeIcon className="size-4 shrink-0" strokeWidth={1.8} />
+ <span className="max-w-[5.5rem] truncate text-[12px]">{activeScopeItem.label}</span>
+ <ChevronDownIcon className="size-3 shrink-0 opacity-55" strokeWidth={1.8} />
+ </DropdownMenuTrigger>
+ );
+
+ const scopeMenuContent = (
+ <DropdownMenuContent align="start" sideOffset={4} className="flex w-36 flex-col gap-0.5">
+ {scopeItems.map((item) => {
+ const Icon = item.icon;
+ return (
+ <DropdownMenuItem
+ key={item.id}
+ aria-current={item.id === resolvedScope ? "page" : undefined}
+ className={cn(
+ "h-[30px] shrink-0 py-0 text-[13px]",
+ item.id === resolvedScope && "bg-accent font-medium text-accent-foreground",
+ )}
+ onClick={() => navigateToScope(item.id)}
+ >
+ <Icon className="size-4" strokeWidth={1.8} />
+ <span className="truncate">{item.label}</span>
+ </DropdownMenuItem>
+ );
+ })}
+ </DropdownMenuContent>
+ );
+
+ return (
+ <TooltipProvider>
+ <nav className={cn("flex h-9 items-center gap-1", SIDEBAR_HORIZONTAL_PADDING)} aria-label="Primary">
+ {currentUser && (
+ <>
+ {scopeRouteActive ? (
+ <DropdownMenu>
+ {scopeTrigger}
+ {scopeMenuContent}
+ </DropdownMenu>
+ ) : (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <button
+ type="button"
+ aria-label={scopeItems[0].label}
+ className="flex size-[30px] items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-sidebar-accent/65 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
+ onClick={() => navigateToScope("home")}
+ />
+ }
+ >
+ <HouseIcon className="size-4" strokeWidth={1.8} />
+ </TooltipTrigger>
+ <TooltipContent side="bottom">{scopeItems[0].label}</TooltipContent>
+ </Tooltip>
+ )}
+ </>
+ )}
+ {items.map((item) => {
+ const Icon = item.icon;
+ const alwaysShowLabel = !currentUser && item.id === "explore";
+ const itemClassName = cn(
+ "relative flex min-w-0 items-center justify-center gap-2 rounded-md text-muted-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50",
+ item.active || alwaysShowLabel ? "h-[30px] px-2" : "size-[30px] px-0",
+ item.active
+ ? "bg-sidebar-accent font-medium text-sidebar-accent-foreground"
+ : "hover:bg-sidebar-accent/65 hover:text-foreground",
+ );
+ const itemContent = (
+ <>
+ <Icon className="size-4 shrink-0" strokeWidth={1.8} />
+ {(item.active || alwaysShowLabel) && <span className="max-w-[5.5rem] truncate text-[12px]">{item.label}</span>}
+ {!!item.count && item.count > 0 && (
+ <span className="absolute -right-0.5 -top-0.5 flex min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[9px] font-semibold leading-4 text-primary-foreground">
+ {item.count > 99 ? "99+" : item.count}
+ </span>
+ )}
+ </>
+ );
+ const content = item.opensDialog ? (
+ <button
+ key={item.id}
+ type="button"
+ aria-label={item.label}
+ className={itemClassName}
+ onClick={() => {
+ setMobileOpen(false);
+ setAboutOpen(true);
+ }}
+ >
+ {itemContent}
+ </button>
+ ) : (
+ <Link
+ key={item.id}
+ to={item.path}
+ onClick={() => setMobileOpen(false)}
+ aria-label={item.label}
+ aria-current={item.active ? "page" : undefined}
+ className={itemClassName}
+ >
+ {itemContent}
+ </Link>
+ );
+ if (item.active) return content;
+ return (
+ <Tooltip key={item.id}>
+ <TooltipTrigger render={<span />}>{content}</TooltipTrigger>
+ <TooltipContent side="bottom">{item.label}</TooltipContent>
+ </Tooltip>
+ );
+ })}
+ </nav>
+ </TooltipProvider>
+ );
+};
+
+const AppSidebar = ({ className }: { className?: string }) => {
+ const t = useTranslate();
+ const currentUser = useCurrentUser();
+ const { setMobileOpen, setQuickFindOpen } = useAppSidebar();
+ return (
+ <aside className={cn("flex h-full w-full select-none flex-col bg-sidebar text-sidebar-foreground", className)}>
+ <div className={cn("flex h-13 shrink-0 items-center justify-between gap-2", SIDEBAR_HORIZONTAL_PADDING)}>
+ <Link
+ to={currentUser ? ROUTES.HOME : ROUTES.EXPLORE}
+ className="min-w-0 flex-1 rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
+ >
+ <MemosLogo compact />
+ </Link>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ className="size-7 shrink-0 rounded-md text-muted-foreground hover:text-foreground"
+ onClick={() => {
+ setMobileOpen(false);
+ setQuickFindOpen(true);
+ }}
+ aria-label={t("common.search")}
+ >
+ <SearchIcon className="size-4" strokeWidth={1.8} />
+ </Button>
+ </div>
+ <GlobalNavigation />
+ <div className="mx-3 mt-2 border-t border-border/70" />
+ <div className={cn("min-h-0 flex-1 overflow-y-auto overflow-x-hidden pt-2 pb-3 [scrollbar-width:thin]", SIDEBAR_HORIZONTAL_PADDING)}>
+ <RouteSidebarContent />
+ </div>
+ <footer className="shrink-0 border-t border-border/70">
+ {currentUser ? (
+ <UserMenu />
+ ) : (
+ <Link
+ to={ROUTES.AUTH}
+ onClick={() => setMobileOpen(false)}
+ className="group flex h-10 w-full min-w-0 items-center justify-between gap-2 px-3 text-[13px] font-medium text-foreground transition-colors hover:bg-sidebar-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/50"
+ >
+ <span className="flex min-w-0 flex-1 items-center gap-2">
+ <UserRoundIcon className="size-5 shrink-0 text-muted-foreground" strokeWidth={1.8} />
+ <span className="truncate">{t("common.sign-in-to-memos")}</span>
+ </span>
+ <ArrowRightIcon
+ className="size-3.5 shrink-0 text-muted-foreground/60 transition-transform group-hover:translate-x-0.5"
+ strokeWidth={1.8}
+ />
+ </Link>
+ )}
+ </footer>
+ </aside>
+ );
+};
+
+export const MobileAppHeader = () => {
+ const currentUser = useCurrentUser();
+ const { setMobileOpen } = useAppSidebar();
+ return (
+ <header className="sticky top-0 z-20 flex h-12 w-full items-center justify-start gap-1 border-b border-border/70 bg-background/90 px-2 backdrop-blur-md md:hidden">
+ <Button variant="ghost" size="icon-sm" className="size-8" onClick={() => setMobileOpen(true)} aria-label="Open navigation">
+ <MenuIcon className="size-[18px]" />
+ </Button>
+ <Link
+ to={currentUser ? ROUTES.HOME : ROUTES.EXPLORE}
+ className="min-w-0 max-w-[12rem] rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
+ >
+ <MemosLogo compact />
+ </Link>
+ </header>
+ );
+};
+
+export const MobileAppSidebar = () => {
+ const { mobileOpen, setMobileOpen } = useAppSidebar();
+ return (
+ <Sheet open={mobileOpen} onOpenChange={setMobileOpen}>
+ <SheetContent side="left" className="w-[min(18rem,calc(100vw-2rem))] gap-0 border-border p-0 shadow-2xl [&>button]:hidden">
+ <SheetTitle className="sr-only">Navigation</SheetTitle>
+ <AppSidebar />
+ </SheetContent>
+ </Sheet>
+ );
+};
+
+export default AppSidebar;
diff --git a/web/src/components/AppSidebar/QuickFindDialog.tsx b/web/src/components/AppSidebar/QuickFindDialog.tsx
new file mode 100644
index 000000000..5b1c7e306
--- /dev/null
+++ b/web/src/components/AppSidebar/QuickFindDialog.tsx
@@ -0,0 +1,126 @@
+import { CornerDownLeftIcon, SearchIcon } from "lucide-react";
+import { FormEvent, useEffect, useState } from "react";
+import { useLocation, useNavigate } from "react-router-dom";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { useAppSidebar } from "@/contexts/AppSidebarContext";
+import { useAuth } from "@/contexts/AuthContext";
+import { type MemoFilter, replaceFiltersByFactor, stringifyFilters, useMemoFilterContext } from "@/contexts/MemoFilterContext";
+import { BUILTIN_TASKS_VIEW_ID, getShortcutId, isMemoScopeRoute } from "@/lib/memo-views";
+import { ROUTES } from "@/router/routes";
+import { useTranslate } from "@/utils/i18n";
+
+export const isQuickFindCollectionRoute = (pathname: string) => isMemoScopeRoute(pathname) || pathname.startsWith("/u/");
+
+export const buildQuickFindFilters = (query: string, currentFilters: MemoFilter[], preserveCurrentScope: boolean): MemoFilter[] => {
+ const words = Array.from(new Set(query.trim().split(/\s+/).filter(Boolean)));
+ const contentFilters: MemoFilter[] = words.map((value) => ({ factor: "contentSearch", value }));
+ return preserveCurrentScope ? replaceFiltersByFactor(currentFilters, "contentSearch", contentFilters) : contentFilters;
+};
+
+const getScopeLabel = (pathname: string, t: ReturnType<typeof useTranslate>) => {
+ if (pathname === ROUTES.ARCHIVED) return t("common.archived");
+ if (pathname === ROUTES.EXPLORE) return t("common.explore");
+ if (pathname.startsWith("/u/")) return t("common.profile");
+ return t("common.memos");
+};
+
+const QuickFindDialog = () => {
+ const t = useTranslate();
+ const location = useLocation();
+ const navigate = useNavigate();
+ const { shortcuts } = useAuth();
+ const { filters, setFilters, setShortcut, shortcut } = useMemoFilterContext();
+ const { quickFindOpen, setQuickFindOpen } = useAppSidebar();
+ const [query, setQuery] = useState("");
+ const collectionRoute = isQuickFindCollectionRoute(location.pathname);
+ const viewApplies = isMemoScopeRoute(location.pathname);
+ const selectedShortcut = viewApplies ? shortcuts.find((item) => getShortcutId(item.name) === shortcut) : undefined;
+ const scopeLabel =
+ viewApplies && shortcut === BUILTIN_TASKS_VIEW_ID ? t("common.tasks") : selectedShortcut?.title || getScopeLabel(location.pathname, t);
+
+ useEffect(() => {
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") {
+ event.preventDefault();
+ setQuickFindOpen(true);
+ }
+ };
+
+ window.addEventListener("keydown", handleKeyDown);
+ return () => window.removeEventListener("keydown", handleKeyDown);
+ }, [setQuickFindOpen]);
+
+ useEffect(() => {
+ if (!quickFindOpen) return;
+ setQuery(
+ filters
+ .filter((filter) => filter.factor === "contentSearch")
+ .map((filter) => filter.value)
+ .join(" "),
+ );
+ }, [filters, quickFindOpen]);
+
+ const submitQuery = () => {
+ const nextFilters = buildQuickFindFilters(query, filters, collectionRoute);
+
+ if (collectionRoute) {
+ setFilters(nextFilters);
+ } else {
+ const filterQuery = stringifyFilters(nextFilters);
+ setFilters(nextFilters);
+ setShortcut(undefined);
+ navigate(filterQuery ? `${ROUTES.HOME}?filter=${filterQuery}` : ROUTES.HOME);
+ }
+
+ setQuickFindOpen(false);
+ };
+
+ const handleSubmit = (event: FormEvent) => {
+ event.preventDefault();
+ submitQuery();
+ };
+
+ return (
+ <Dialog open={quickFindOpen} onOpenChange={setQuickFindOpen}>
+ <DialogContent
+ size="lg"
+ className="top-[12vh]! translate-y-0! overflow-hidden border-border/70 p-0! shadow-xl sm:top-[16vh]! [&>div:first-child]:gap-0!"
+ showCloseButton={false}
+ >
+ <DialogTitle className="sr-only">{t("common.search")}</DialogTitle>
+ <DialogDescription className="sr-only">
+ {t("common.search")} {scopeLabel}
+ </DialogDescription>
+ <form onSubmit={handleSubmit} className="flex h-[52px] shrink-0 items-center gap-2.5 px-4">
+ <SearchIcon className="size-[17px] shrink-0 text-muted-foreground" strokeWidth={1.8} />
+ <Input
+ autoFocus
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key !== "Enter") return;
+ event.preventDefault();
+ submitQuery();
+ }}
+ className="h-10 border-0 bg-transparent px-0 !text-[14px] shadow-none focus-visible:ring-0"
+ placeholder={`${t("common.search")} ${scopeLabel}`}
+ aria-label={`${t("common.search")} ${scopeLabel}`}
+ />
+ <Button
+ type="submit"
+ variant="ghost"
+ size="icon-sm"
+ className="size-7 shrink-0 rounded-md text-muted-foreground"
+ aria-label={t("common.search")}
+ >
+ <CornerDownLeftIcon className="size-3.5" />
+ </Button>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+};
+
+export default QuickFindDialog;
diff --git a/web/src/components/AppSidebar/SidebarRow.tsx b/web/src/components/AppSidebar/SidebarRow.tsx
new file mode 100644
index 000000000..247aa6e1a
--- /dev/null
+++ b/web/src/components/AppSidebar/SidebarRow.tsx
@@ -0,0 +1,39 @@
+import type { LucideIcon } from "lucide-react";
+import type { ReactNode } from "react";
+import { cn } from "@/lib/utils";
+
+export const SIDEBAR_ROW_CLASSES =
+ "group flex h-[30px] w-full min-w-0 items-center gap-2 rounded-md px-2 text-[13px] leading-none transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50";
+
+export const SIDEBAR_ROW_ICON_CLASSES = "size-[15px] shrink-0 opacity-75";
+export const SIDEBAR_ROW_COUNT_CLASSES = "text-[11px] tabular-nums text-muted-foreground/60";
+
+interface Props {
+ active?: boolean;
+ icon: LucideIcon;
+ label: ReactNode;
+ count?: number;
+ onClick?: () => void;
+ trailing?: ReactNode;
+}
+
+const SidebarRow = ({ active, icon: Icon, label, count, onClick, trailing }: Props) => (
+ <button
+ type="button"
+ onClick={onClick}
+ aria-pressed={active || undefined}
+ className={cn(
+ SIDEBAR_ROW_CLASSES,
+ active
+ ? "bg-sidebar-accent font-medium text-sidebar-accent-foreground"
+ : "text-muted-foreground hover:bg-sidebar-accent/65 hover:text-foreground",
+ )}
+ >
+ <Icon className={SIDEBAR_ROW_ICON_CLASSES} strokeWidth={1.8} />
+ <span className="min-w-0 flex-1 truncate text-left">{label}</span>
+ {count != null && count > 0 && <span className={SIDEBAR_ROW_COUNT_CLASSES}>{count}</span>}
+ {trailing}
+ </button>
+);
+
+export default SidebarRow;
diff --git a/web/src/components/AppSidebar/SidebarSectionHeader.tsx b/web/src/components/AppSidebar/SidebarSectionHeader.tsx
new file mode 100644
index 000000000..6dab49ccb
--- /dev/null
+++ b/web/src/components/AppSidebar/SidebarSectionHeader.tsx
@@ -0,0 +1,17 @@
+import type { ReactNode } from "react";
+
+interface Props {
+ children: ReactNode;
+ action?: ReactNode;
+}
+
+const SidebarSectionHeader = ({ children, action }: Props) => (
+ <div className="mb-0.5 flex h-5 min-w-0 items-center justify-between gap-2">
+ <span className="min-w-0 truncate ps-2 text-[10px] font-semibold uppercase tracking-[0.09em] text-muted-foreground/55 select-none">
+ {children}
+ </span>
+ {action}
+ </div>
+);
+
+export default SidebarSectionHeader;
diff --git a/web/src/components/AppSidebar/TagsSection.tsx b/web/src/components/AppSidebar/TagsSection.tsx
new file mode 100644
index 000000000..b8f3085e0
--- /dev/null
+++ b/web/src/components/AppSidebar/TagsSection.tsx
@@ -0,0 +1,85 @@
+import { HashIcon, MoreHorizontalIcon } from "lucide-react";
+import { useMemo } from "react";
+import { Switch } from "@/components/ui/switch";
+import { useMemoFilterContext } from "@/contexts/MemoFilterContext";
+import { useLocalStorage } from "@/hooks";
+import { useTranslate } from "@/utils/i18n";
+import TagTree from "../TagTree";
+import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
+import SidebarRow from "./SidebarRow";
+import SidebarSectionHeader from "./SidebarSectionHeader";
+
+interface Props {
+ tagCount: Record<string, number>;
+ onSelect?: () => void;
+}
+
+const TagsSection = ({ tagCount, onSelect }: Props) => {
+ const t = useTranslate();
+ const { getFiltersByFactor, addFilter, removeFilter } = useMemoFilterContext();
+ const [treeMode, setTreeMode] = useLocalStorage<boolean>("tag-view-as-tree", false);
+ const [treeAutoExpand, setTreeAutoExpand] = useLocalStorage<boolean>("tag-tree-auto-expand", false);
+ const activeTags = new Set(getFiltersByFactor("tagSearch").map((filter) => filter.value));
+ const tags = useMemo(() => Object.entries(tagCount).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])), [tagCount]);
+
+ if (tags.length === 0) {
+ return null;
+ }
+
+ const handleTagClick = (tag: string) => {
+ const active = activeTags.has(tag);
+ if (active) {
+ removeFilter((filter) => filter.factor === "tagSearch" && filter.value === tag);
+ } else {
+ removeFilter((filter) => filter.factor === "tagSearch");
+ addFilter({ factor: "tagSearch", value: tag });
+ }
+ onSelect?.();
+ };
+
+ return (
+ <section>
+ <SidebarSectionHeader
+ action={
+ <Popover>
+ <PopoverTrigger
+ render={
+ <button
+ type="button"
+ className="flex size-5 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-sidebar-accent hover:text-foreground"
+ aria-label={t("common.settings")}
+ />
+ }
+ >
+ <MoreHorizontalIcon className="size-3.5" />
+ </PopoverTrigger>
+ <PopoverContent align="end" alignOffset={-12} className="w-48">
+ <div className="flex items-center justify-between gap-2 p-1">
+ <span className="text-sm">{t("common.tree-mode")}</span>
+ <Switch checked={treeMode} onCheckedChange={setTreeMode} />
+ </div>
+ <div className="flex items-center justify-between gap-2 p-1">
+ <span className="text-sm">{t("common.auto-expand")}</span>
+ <Switch disabled={!treeMode} checked={treeAutoExpand} onCheckedChange={setTreeAutoExpand} />
+ </div>
+ </PopoverContent>
+ </Popover>
+ }
+ >
+ {t("common.tags")}
+ </SidebarSectionHeader>
+ {treeMode ? (
+ <TagTree tagAmounts={tags} expandSubTags={!!treeAutoExpand} />
+ ) : (
+ <div className="space-y-0.5">
+ {tags.map(([tag, amount]) => {
+ const active = activeTags.has(tag);
+ return <SidebarRow key={tag} active={active} icon={HashIcon} label={tag} count={amount} onClick={() => handleTagClick(tag)} />;
+ })}
+ </div>
+ )}
+ </section>
+ );
+};
+
+export default TagsSection;
diff --git a/web/src/components/AppSidebar/index.ts b/web/src/components/AppSidebar/index.ts
new file mode 100644
index 000000000..4c2e9b0fe
--- /dev/null
+++ b/web/src/components/AppSidebar/index.ts
@@ -0,0 +1,2 @@
+export { default, MobileAppHeader, MobileAppSidebar } from "./AppSidebar";
+export { default as QuickFindDialog } from "./QuickFindDialog";
diff --git a/web/src/components/AppSidebar/routes.ts b/web/src/components/AppSidebar/routes.ts
new file mode 100644
index 000000000..1a951cce0
--- /dev/null
+++ b/web/src/components/AppSidebar/routes.ts
@@ -0,0 +1,16 @@
+import { matchPath } from "react-router-dom";
+import { isMemoScopeRoute, type MemoScope, resolveMemoScope } from "@/lib/memo-views";
+import { ROUTES } from "@/router/routes";
+
+export type SidebarRouteKind = MemoScope | "profile" | "shortcuts" | "attachments" | "inbox" | "settings" | "memo" | "empty";
+
+export const getSidebarRouteKind = (path: string): SidebarRouteKind => {
+ if (isMemoScopeRoute(path)) return resolveMemoScope(path);
+ if (matchPath("/u/:username", path)) return "profile";
+ if (path === ROUTES.SHORTCUTS) return "shortcuts";
+ if (path === ROUTES.ATTACHMENTS) return "attachments";
+ if (path === ROUTES.INBOX) return "inbox";
+ if (path === ROUTES.SETTING) return "settings";
+ if (matchPath("/memos/:uid", path) || matchPath(`${ROUTES.SHARED_MEMO}/:token`, path)) return "memo";
+ return "empty";
+};
diff --git a/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsx b/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsx
index e85fbfe14..be299939a 100644
--- a/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsx
+++ b/web/src/components/MemoDetailSidebar/MemoDetailSidebar.tsx
@@ -1,31 +1,21 @@
-import { timestampDate } from "@bufbuild/protobuf/wkt";
import copy from "copy-to-clipboard";
-import { isEqual } from "lodash-es";
-import { BookmarkIcon, FileTextIcon, ImageIcon, LinkIcon, MapPinIcon, MilestoneIcon, Share2Icon } from "lucide-react";
+import { BookmarkCheckIcon, BookmarkIcon, ChevronDownIcon, ImageIcon, LinkIcon, Share2Icon } from "lucide-react";
import { useMemo, useState } from "react";
import toast from "react-hot-toast";
import { Link } from "react-router-dom";
-import VisibilitySelector from "@/components/MemoEditor/Toolbar/VisibilitySelector";
-import { getLocationDisplayText } from "@/components/MemoMetadata/Location/locationHelpers";
-import { getRelationBuckets, getRelationMemo, type RelationDirection } from "@/components/MemoMetadata/Relation/relationHelpers";
+import SidebarRow, { SIDEBAR_ROW_CLASSES, SIDEBAR_ROW_ICON_CLASSES } from "@/components/AppSidebar/SidebarRow";
+import SidebarSectionHeader from "@/components/AppSidebar/SidebarSectionHeader";
+import { getRelationBuckets, getRelationMemo } from "@/components/MemoMetadata/Relation/relationHelpers";
import { useResolvedRelationMemos } from "@/components/MemoMetadata/Relation/useResolvedRelationMemos";
-import UserAvatar from "@/components/UserAvatar";
-import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
-import VisibilityIcon from "@/components/VisibilityIcon";
+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { useInstance } from "@/contexts/InstanceContext";
import useCurrentUser from "@/hooks/useCurrentUser";
import { useUpdateMemo } from "@/hooks/useMemoQueries";
-import { useUser } from "@/hooks/useUserQueries";
-import i18n from "@/i18n";
import { cn } from "@/lib/utils";
-import type { Attachment } from "@/types/proto/api/v1/attachment_service_pb";
import { State } from "@/types/proto/api/v1/common_pb";
-import { Memo, MemoRelation, Visibility } from "@/types/proto/api/v1/memo_service_pb";
-import { getAttachmentUrl } from "@/utils/attachment";
-import { formatFileSize } from "@/utils/format";
+import { Memo, type MemoRelation } from "@/types/proto/api/v1/memo_service_pb";
import { useTranslate } from "@/utils/i18n";
import { extractHeadings } from "@/utils/markdown-manipulation";
-import { convertVisibilityToString } from "@/utils/memo";
import { isSuperUser } from "@/utils/user";
import MemoOutline from "./MemoOutline";
import MemoSharePanel from "./MemoSharePanel";
@@ -34,129 +24,62 @@ interface Props {
memo: Memo;
className?: string;
onShareImageOpen?: () => void;
+ forceReadonly?: boolean;
}
-const SectionLabel = ({ label, count }: { label: string; count?: number }) => (
- <p className="flex items-baseline gap-1.5 text-[11px] font-medium uppercase tracking-[0.08em] text-muted-foreground/55">
- {label}
- {count != null && <span className="tabular-nums text-muted-foreground/35">{count}</span>}
- </p>
+const Section = ({ label, children }: { label: string; children: React.ReactNode }) => (
+ <section className="w-full">
+ <SidebarSectionHeader>{label}</SidebarSectionHeader>
+ <div className="space-y-0.5">{children}</div>
+ </section>
);
-const Section = ({ label, count, children }: { label: string; count?: number; children: React.ReactNode }) => (
- <div className="w-full flex flex-col gap-1.5 border-t border-border/60 pt-3">
- <SectionLabel label={label} count={count} />
- {children}
- </div>
-);
-
-/** Quiet icon action for the cluster at the top of the rail. */
-const ActionButton = ({
- label,
- active,
- onClick,
- children,
-}: {
- label: string;
- active?: boolean;
- onClick?: () => void;
- children: React.ReactNode;
-}) => (
- <Tooltip>
- <TooltipTrigger
- render={
- <button
- aria-label={label}
- aria-pressed={active}
- onClick={onClick}
- className={cn(
- "inline-flex size-7 items-center justify-center rounded-md transition-colors",
- active ? "bg-primary/10 text-primary" : "text-muted-foreground/75 hover:bg-accent hover:text-foreground",
- )}
- />
- }
- >
- {children}
- </TooltipTrigger>
- <TooltipContent>{label}</TooltipContent>
- </Tooltip>
-);
-
-const PropertyLabel = ({ children }: { children: React.ReactNode }) => (
- <span className="min-h-7 flex items-center text-[12.5px] text-muted-foreground/70">{children}</span>
-);
-
-const PROPERTY_VALUE_CLASSES = "min-w-0 flex items-center text-[13px] leading-5 text-foreground/85";
-
-const RelationRow = ({ relation, direction, snippet }: { relation: MemoRelation; direction: RelationDirection; snippet: string }) => {
- const relatedMemo = getRelationMemo(relation, direction);
+const BacklinkRow = ({ relation, snippet }: { relation: MemoRelation; snippet: string }) => {
+ const relatedMemo = getRelationMemo(relation, "referenced");
if (!relatedMemo) {
return null;
}
- const Icon = direction === "referencing" ? LinkIcon : MilestoneIcon;
+
return (
<Link
- className="flex min-w-0 items-center gap-1.5 rounded-md px-1.5 py-1 -mx-1.5 text-[13px] leading-5 text-muted-foreground hover:bg-accent hover:text-foreground transition-colors"
+ className={cn(SIDEBAR_ROW_CLASSES, "text-muted-foreground hover:bg-sidebar-accent/65 hover:text-foreground")}
to={`/${relatedMemo.name}`}
title={snippet}
viewTransition
>
- <Icon className="size-3.5 shrink-0 opacity-60" />
- <span className="truncate">{snippet}</span>
+ <LinkIcon className={SIDEBAR_ROW_ICON_CLASSES} strokeWidth={1.8} />
+ <span className="min-w-0 flex-1 truncate text-left">{snippet}</span>
</Link>
);
};
-const AttachmentRow = ({ attachment }: { attachment: Attachment }) => {
- const isImage = attachment.type.startsWith("image");
- const Icon = isImage ? ImageIcon : FileTextIcon;
- const size = Number(attachment.size);
- return (
- <a
- className="flex min-w-0 items-center gap-1.5 rounded-md px-1.5 py-1 -mx-1.5 text-[13px] leading-5 text-muted-foreground hover:bg-accent hover:text-foreground transition-colors"
- href={getAttachmentUrl(attachment)}
- target="_blank"
- rel="noopener noreferrer"
- title={attachment.filename}
- >
- <Icon className="size-3.5 shrink-0 opacity-60" />
- <span className="truncate">{attachment.filename}</span>
- {size > 0 && <span className="ml-auto shrink-0 pl-2 text-[11px] tabular-nums text-muted-foreground/45">{formatFileSize(size)}</span>}
- </a>
- );
-};
-
-const MemoDetailSidebar = ({ memo, className, onShareImageOpen }: Props) => {
+const MemoDetailSidebar = ({ memo, className, onShareImageOpen, forceReadonly = false }: Props) => {
const t = useTranslate();
const currentUser = useCurrentUser();
const { profile } = useInstance();
const { mutateAsync: updateMemo } = useUpdateMemo();
const [sharePanelOpen, setSharePanelOpen] = useState(false);
- const readonly = memo.creator !== currentUser?.name && !isSuperUser(currentUser);
- const editable = !readonly && memo.state === State.NORMAL;
- const canManageShares = !memo.parent && (memo.creator === currentUser?.name || isSuperUser(currentUser));
- const hasUpdated = !isEqual(memo.createTime, memo.updateTime);
+ const readonly = forceReadonly || (memo.creator !== currentUser?.name && !isSuperUser(currentUser));
+ const canPin = !readonly && !memo.parent && memo.state === State.NORMAL;
+ const canManageShares = !forceReadonly && !memo.parent && (memo.creator === currentUser?.name || isSuperUser(currentUser));
- const { data: creator } = useUser(memo.creator, { enabled: !!memo.creator });
const headings = useMemo(() => extractHeadings(memo.content), [memo.content]);
- const { referencing, referenced } = useMemo(() => getRelationBuckets(memo.relations, memo.name), [memo.relations, memo.name]);
- const relationMemoNames = useMemo(
+ const { referenced } = useMemo(() => getRelationBuckets(memo.relations, memo.name), [memo.relations, memo.name]);
+ const backlinkMemoNames = useMemo(
() =>
- [
- ...referencing.map((relation) => getRelationMemo(relation, "referencing")),
- ...referenced.map((relation) => getRelationMemo(relation, "referenced")),
- ].flatMap((relatedMemo) => (relatedMemo?.name && !relatedMemo.snippet ? [relatedMemo.name] : [])),
- [referenced, referencing],
+ forceReadonly
+ ? []
+ : referenced.flatMap((relation) => {
+ const relatedMemo = getRelationMemo(relation, "referenced");
+ return relatedMemo?.name && !relatedMemo.snippet ? [relatedMemo.name] : [];
+ }),
+ [forceReadonly, referenced],
);
- const resolvedMemos = useResolvedRelationMemos(relationMemoNames);
+ const resolvedMemos = useResolvedRelationMemos(backlinkMemoNames);
- const createTime = memo.createTime ? timestampDate(memo.createTime) : undefined;
- const updateTime = memo.updateTime ? timestampDate(memo.updateTime) : undefined;
- const formatDate = (date: Date) => date.toLocaleDateString(i18n.language, { year: "numeric", month: "short", day: "numeric" });
-
- const relationSnippet = (relation: MemoRelation, direction: RelationDirection) => {
- const relatedMemo = getRelationMemo(relation, direction);
+ const backlinkSnippet = (relation: MemoRelation) => {
+ const relatedMemo = getRelationMemo(relation, "referenced");
if (!relatedMemo) {
return "";
}
@@ -167,13 +90,6 @@ const MemoDetailSidebar = ({ memo, className, onShareImageOpen }: Props) => {
await updateMemo({ update: { name: memo.name, pinned: !memo.pinned }, updateMask: ["pinned"] });
};
- const handleVisibilityChange = async (visibility: Visibility) => {
- if (visibility === memo.visibility) {
- return;
- }
- await updateMemo({ update: { name: memo.name, visibility }, updateMask: ["visibility"] });
- };
-
const handleCopyLink = () => {
const host = profile.instanceUrl || window.location.origin;
copy(`${host}/${memo.name}`);
@@ -181,149 +97,65 @@ const MemoDetailSidebar = ({ memo, className, onShareImageOpen }: Props) => {
};
return (
- <aside
- className={cn(
- "relative w-full h-auto max-h-screen overflow-y-auto overflow-x-hidden flex flex-col gap-4 px-1.5 select-none",
- className,
- )}
- >
- {/* actions */}
- <div className="flex items-center gap-0.5 -mx-1.5">
- {editable && (
- <ActionButton label={memo.pinned ? t("common.unpin") : t("common.pin")} active={memo.pinned} onClick={handleTogglePin}>
- <BookmarkIcon className={cn("size-[15px]", memo.pinned && "fill-current")} />
- </ActionButton>
- )}
- <ActionButton label={t("memo.copy-link")} onClick={handleCopyLink}>
- <LinkIcon className="size-[15px]" />
- </ActionButton>
- {onShareImageOpen && (
- <ActionButton label={t("memo.share.open-image")} onClick={onShareImageOpen}>
- <ImageIcon className="size-[15px]" />
- </ActionButton>
+ <div className={cn("relative flex w-full select-none flex-col gap-3.5", className)}>
+ <Section label={t("common.actions")}>
+ {canPin && (
+ <SidebarRow
+ icon={memo.pinned ? BookmarkCheckIcon : BookmarkIcon}
+ label={memo.pinned ? t("common.unpin") : t("common.pin")}
+ onClick={handleTogglePin}
+ />
)}
- {canManageShares && (
- <ActionButton label={t("memo.share.open-panel")} onClick={() => setSharePanelOpen(true)}>
- <Share2Icon className="size-[15px]" />
- </ActionButton>
- )}
- </div>
-
- {/* properties */}
- <div className="grid grid-cols-[auto_minmax(0,1fr)] items-center gap-x-3 border-t border-border/60 pt-3">
- <PropertyLabel>{t("common.visibility")}</PropertyLabel>
- {editable ? (
- <div className="-mx-1.5 min-w-0 justify-self-start">
- <VisibilitySelector size="compact" value={memo.visibility} onChange={handleVisibilityChange} />
- </div>
- ) : (
- <span className={PROPERTY_VALUE_CLASSES}>
- <VisibilityIcon visibility={memo.visibility} className="w-[13px] mr-1.5 shrink-0" />
- <span className="truncate">
- {t(`memo.visibility.${convertVisibilityToString(memo.visibility).toLowerCase()}` as Parameters<typeof t>[0])}
- </span>
- </span>
- )}
-
- <PropertyLabel>{t("common.created-at")}</PropertyLabel>
- <span className={cn(PROPERTY_VALUE_CLASSES, "tabular-nums")} title={createTime?.toLocaleString(i18n.language)}>
- {createTime ? formatDate(createTime) : "—"}
- </span>
-
- {hasUpdated && updateTime && (
- <>
- <PropertyLabel>{t("common.last-updated-at")}</PropertyLabel>
- <span className={cn(PROPERTY_VALUE_CLASSES, "tabular-nums")} title={updateTime.toLocaleString(i18n.language)}>
- {formatDate(updateTime)}
- </span>
- </>
- )}
-
- {creator && (
- <>
- <PropertyLabel>{t("common.author")}</PropertyLabel>
- <Link
- className={cn(
- PROPERTY_VALUE_CLASSES,
- "gap-1.5 rounded-md px-1.5 py-0.5 -mx-1.5 justify-self-start hover:bg-accent transition-colors",
- )}
- to={`/u/${encodeURIComponent(creator.username)}`}
- viewTransition
- >
- <UserAvatar className="size-4 shrink-0 rounded-full border-none" avatarUrl={creator.avatarUrl} />
- <span className="truncate">{creator.displayName || creator.username}</span>
- </Link>
- </>
- )}
-
- {memo.location && (
- <>
- <PropertyLabel>{t("common.location")}</PropertyLabel>
- <span className={PROPERTY_VALUE_CLASSES} title={getLocationDisplayText(memo.location)}>
- <MapPinIcon className="w-[13px] mr-1.5 shrink-0 text-muted-foreground" />
- <span className="truncate">{getLocationDisplayText(memo.location)}</span>
- </span>
- </>
- )}
- </div>
-
- {memo.tags.length > 0 && (
- <Section label={t("common.tags")} count={memo.tags.length}>
- <div className="flex flex-wrap gap-x-0.5 gap-y-1 -mx-1.5">
- {memo.tags.map((tag) => (
- <span
- key={tag}
- className="inline-flex min-w-0 items-center gap-0.5 rounded-md px-1.5 py-0.5 text-[13px] leading-5 text-muted-foreground hover:bg-accent hover:text-foreground transition-colors"
- >
- <span className="opacity-45">#</span>
- <span className="truncate">{tag}</span>
- </span>
- ))}
- </div>
- </Section>
- )}
-
- {memo.attachments.length > 0 && (
- <Section label={t("common.attachments")} count={memo.attachments.length}>
- <div className="flex flex-col">
- {memo.attachments.map((attachment) => (
- <AttachmentRow key={attachment.name} attachment={attachment as Attachment} />
- ))}
- </div>
- </Section>
- )}
-
- {(referencing.length > 0 || referenced.length > 0) && (
- <Section label={t("common.relations")} count={referencing.length + referenced.length}>
- <div className="flex flex-col">
- {referencing.map((relation) => (
- <RelationRow
- key={`referencing-${getRelationMemo(relation, "referencing")?.name}`}
- relation={relation}
- direction="referencing"
- snippet={relationSnippet(relation, "referencing")}
- />
- ))}
- {referenced.map((relation) => (
- <RelationRow
- key={`referenced-${getRelationMemo(relation, "referenced")?.name}`}
- relation={relation}
- direction="referenced"
- snippet={relationSnippet(relation, "referenced")}
- />
- ))}
- </div>
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ aria-label={t("common.share")}
+ className={cn(
+ SIDEBAR_ROW_CLASSES,
+ "text-muted-foreground hover:bg-sidebar-accent/65 hover:text-foreground data-popup-open:bg-sidebar-accent/65 data-popup-open:text-foreground",
+ )}
+ >
+ <Share2Icon className={SIDEBAR_ROW_ICON_CLASSES} strokeWidth={1.8} />
+ <span className="min-w-0 flex-1 truncate text-left">{t("common.share")}</span>
+ <ChevronDownIcon className="size-3.5 shrink-0 opacity-55" strokeWidth={1.8} />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" sideOffset={4} className="w-48">
+ <DropdownMenuItem onClick={handleCopyLink}>
+ <LinkIcon />
+ {t("memo.copy-link")}
+ </DropdownMenuItem>
+ {onShareImageOpen && (
+ <DropdownMenuItem onClick={onShareImageOpen}>
+ <ImageIcon />
+ {t("memo.share.open-image")}
+ </DropdownMenuItem>
+ )}
+ {canManageShares && (
+ <DropdownMenuItem onClick={() => setSharePanelOpen(true)}>
+ <Share2Icon />
+ {t("memo.share.open-panel")}
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </Section>
+
+ {headings.length > 1 && (
+ <Section label={t("memo.outline")}>
+ <MemoOutline headings={headings} />
</Section>
)}
- {headings.length > 0 && (
- <Section label={t("memo.outline")}>
- <MemoOutline headings={headings} />
+ {!forceReadonly && referenced.length > 0 && (
+ <Section label={t("common.referenced-by")}>
+ {referenced.map((relation) => {
+ const relatedMemo = getRelationMemo(relation, "referenced");
+ return <BacklinkRow key={`referenced-${relatedMemo?.name}`} relation={relation} snippet={backlinkSnippet(relation)} />;
+ })}
</Section>
)}
{sharePanelOpen && <MemoSharePanel memoName={memo.name} open={sharePanelOpen} onClose={() => setSharePanelOpen(false)} />}
- </aside>
+ </div>
);
};
diff --git a/web/src/components/MemoDetailSidebar/MemoDetailSidebarDrawer.tsx b/web/src/components/MemoDetailSidebar/MemoDetailSidebarDrawer.tsx
deleted file mode 100644
index d4616c3cb..000000000
--- a/web/src/components/MemoDetailSidebar/MemoDetailSidebarDrawer.tsx
+++ /dev/null
@@ -1,34 +0,0 @@
-import { GanttChartIcon } from "lucide-react";
-import { useEffect, useState } from "react";
-import { useLocation } from "react-router-dom";
-import { Button } from "@/components/ui/button";
-import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet";
-import { Memo } from "@/types/proto/api/v1/memo_service_pb";
-import MemoDetailSidebar from "./MemoDetailSidebar";
-
-interface Props {
- memo: Memo;
- onShareImageOpen?: () => void;
-}
-
-const MemoDetailSidebarDrawer = ({ memo, onShareImageOpen }: Props) => {
- const location = useLocation();
- const [open, setOpen] = useState(false);
-
- useEffect(() => {
- setOpen(false);
- }, [location.pathname]);
-
- return (
- <Sheet open={open} onOpenChange={setOpen}>
- <SheetTrigger render={<Button variant="ghost" size="sm" className="px-2" />}>
- <GanttChartIcon className="w-5 h-auto text-muted-foreground" />
- </SheetTrigger>
- <SheetContent side="right" className="w-full sm:w-80 px-4 bg-background">
- <MemoDetailSidebar className="py-4" memo={memo} onShareImageOpen={onShareImageOpen} />
- </SheetContent>
- </Sheet>
- );
-};
-
-export default MemoDetailSidebarDrawer;
diff --git a/web/src/components/MemoDetailSidebar/MemoOutline.tsx b/web/src/components/MemoDetailSidebar/MemoOutline.tsx
index 01b9cc716..052b7f0d6 100644
--- a/web/src/components/MemoDetailSidebar/MemoOutline.tsx
+++ b/web/src/components/MemoDetailSidebar/MemoOutline.tsx
@@ -67,19 +67,19 @@ const MemoOutline = ({ headings }: MemoOutlineProps) => {
onClick={(e) => handleClick(e, heading.slug)}
aria-current={active ? "location" : undefined}
className={cn(
- "relative block truncate rounded-md py-[3px] pr-1.5 -mx-1.5 text-[13px] leading-5 transition-colors",
+ "relative flex h-[30px] min-w-0 items-center rounded-md pr-2 text-[13px] leading-none transition-colors",
heading.level === minLevel && "font-medium",
- active ? "text-foreground" : "text-muted-foreground/70 hover:bg-accent hover:text-foreground",
+ active ? "text-foreground" : "text-muted-foreground/70 hover:bg-sidebar-accent/65 hover:text-foreground",
)}
- style={{ paddingLeft: 14 + (heading.level - minLevel) * 12 }}
+ style={{ paddingLeft: 8 + (heading.level - minLevel) * 12 }}
>
<span
className={cn(
- "absolute left-1.5 top-1/2 h-[13px] w-[2px] -translate-y-1/2 rounded-full transition-colors",
+ "absolute left-0.5 top-1/2 h-[13px] w-[2px] -translate-y-1/2 rounded-full transition-colors",
active ? "bg-primary" : "bg-border",
)}
/>
- {heading.text}
+ <span className="min-w-0 flex-1 truncate">{heading.text}</span>
</a>
);
})}
diff --git a/web/src/components/MemoDetailSidebar/index.ts b/web/src/components/MemoDetailSidebar/index.ts
index ccf9393ed..442ad1c11 100644
--- a/web/src/components/MemoDetailSidebar/index.ts
+++ b/web/src/components/MemoDetailSidebar/index.ts
@@ -1,4 +1,3 @@
import MemoDetailSidebar from "./MemoDetailSidebar";
-import MemoDetailSidebarDrawer from "./MemoDetailSidebarDrawer";
-export { MemoDetailSidebar, MemoDetailSidebarDrawer };
+export { MemoDetailSidebar };
diff --git a/web/src/components/MemoExplorer/MemoExplorer.tsx b/web/src/components/MemoExplorer/MemoExplorer.tsx
deleted file mode 100644
index 056352349..000000000
--- a/web/src/components/MemoExplorer/MemoExplorer.tsx
+++ /dev/null
@@ -1,87 +0,0 @@
-import SearchBar from "@/components/SearchBar";
-import useCurrentUser from "@/hooks/useCurrentUser";
-import { cn } from "@/lib/utils";
-import type { StatisticsData } from "@/types/statistics";
-import StatisticsView from "../StatisticsView";
-import ShortcutsSection from "./ShortcutsSection";
-import TagsSection from "./TagsSection";
-
-export type MemoExplorerContext = "home" | "explore" | "archived" | "profile";
-
-export interface MemoExplorerFeatures {
- search?: boolean;
- statistics?: boolean;
- shortcuts?: boolean;
- tags?: boolean;
-}
-
-interface Props {
- className?: string;
- context?: MemoExplorerContext;
- features?: MemoExplorerFeatures;
- statisticsData: StatisticsData;
- tagCount: Record<string, number>;
-}
-
-const getDefaultFeatures = (context: MemoExplorerContext): MemoExplorerFeatures => {
- switch (context) {
- case "explore":
- return {
- search: true,
- statistics: true,
- shortcuts: false, // Global explore doesn't use shortcuts
- tags: true,
- };
- case "archived":
- return {
- search: true,
- statistics: true,
- shortcuts: false, // Archived doesn't typically use shortcuts
- tags: true,
- };
- case "profile":
- return {
- search: true,
- statistics: true,
- shortcuts: false, // Profile view doesn't use shortcuts
- tags: true,
- };
- case "home":
- default:
- return {
- search: true,
- statistics: true,
- shortcuts: true,
- tags: true,
- };
- }
-};
-
-const MemoExplorer = (props: Props) => {
- const { className, context = "home", features: featureOverrides = {}, statisticsData, tagCount } = props;
- const currentUser = useCurrentUser();
-
- // Merge default features with overrides
- const features = {
- ...getDefaultFeatures(context),
- ...featureOverrides,
- };
-
- return (
- <aside
- className={cn(
- "relative w-full h-full overflow-auto flex flex-col justify-start items-start bg-background text-sidebar-foreground",
- className,
- )}
- >
- {features.search && <SearchBar />}
- <div className="mt-1 px-1 w-full">
- {features.statistics && <StatisticsView statisticsData={statisticsData} />}
- {features.shortcuts && currentUser && <ShortcutsSection />}
- {features.tags && <TagsSection readonly={context === "explore"} tagCount={tagCount} />}
- </div>
- </aside>
- );
-};
-
-export default MemoExplorer;
diff --git a/web/src/components/MemoExplorer/MemoExplorerDrawer.tsx b/web/src/components/MemoExplorer/MemoExplorerDrawer.tsx
deleted file mode 100644
index c7e42af54..000000000
--- a/web/src/components/MemoExplorer/MemoExplorerDrawer.tsx
+++ /dev/null
@@ -1,48 +0,0 @@
-import { MenuIcon } from "lucide-react";
-import { useEffect, useState } from "react";
-import { useLocation } from "react-router-dom";
-import { Button } from "@/components/ui/button";
-import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from "@/components/ui/sheet";
-import type { StatisticsData } from "@/types/statistics";
-import MemoExplorer, { MemoExplorerContext, MemoExplorerFeatures } from "./MemoExplorer";
-
-interface Props {
- context?: MemoExplorerContext;
- features?: MemoExplorerFeatures;
- statisticsData: StatisticsData;
- tagCount: Record<string, number>;
- onOpenChange?: (open: boolean) => void;
-}
-
-const MemoExplorerDrawer = (props: Props) => {
- const { context, features, statisticsData, tagCount, onOpenChange } = props;
- const location = useLocation();
- const [open, setOpen] = useState(false);
-
- useEffect(() => {
- setOpen(false);
- onOpenChange?.(false);
- }, [location.pathname, onOpenChange]);
-
- return (
- <Sheet
- open={open}
- onOpenChange={(nextOpen) => {
- setOpen(nextOpen);
- onOpenChange?.(nextOpen);
- }}
- >
- <SheetTrigger render={<Button variant="ghost" />}>
- <MenuIcon className="size-5 text-foreground" />
- </SheetTrigger>
- <SheetContent side="right" className="w-80 max-w-full bg-background">
- <SheetHeader>
- <SheetTitle />
- </SheetHeader>
- <MemoExplorer className="px-4" context={context} features={features} statisticsData={statisticsData} tagCount={tagCount} />
- </SheetContent>
- </Sheet>
- );
-};
-
-export default MemoExplorerDrawer;
diff --git a/web/src/components/MemoExplorer/ShortcutsSection.tsx b/web/src/components/MemoExplorer/ShortcutsSection.tsx
deleted file mode 100644
index 88f8e0c6e..000000000
--- a/web/src/components/MemoExplorer/ShortcutsSection.tsx
+++ /dev/null
@@ -1,117 +0,0 @@
-import { Edit3Icon, MoreVerticalIcon, PlusIcon, TrashIcon } from "lucide-react";
-import { useState } from "react";
-import toast from "react-hot-toast";
-import { useNavigate } from "react-router-dom";
-import ConfirmDialog from "@/components/ConfirmDialog";
-import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
-import { shortcutServiceClient } from "@/connect";
-import { useAuth } from "@/contexts/AuthContext";
-import { useMemoFilterContext } from "@/contexts/MemoFilterContext";
-import { cn } from "@/lib/utils";
-import { ROUTES } from "@/router";
-import { Shortcut } from "@/types/proto/api/v1/shortcut_service_pb";
-import { useTranslate } from "@/utils/i18n";
-import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "../ui/dropdown-menu";
-
-const emojiRegex = /^(\p{Emoji_Presentation}|\p{Emoji}\uFE0F)$/u;
-
-// Helper function to extract shortcut ID from resource name
-// Format: users/{user}/shortcuts/{shortcut}
-const getShortcutId = (name: string): string => {
- const parts = name.split("/");
- return parts.length === 4 ? parts[3] : "";
-};
-
-function ShortcutsSection() {
- const t = useTranslate();
- const navigate = useNavigate();
- const { shortcuts, refetchSettings } = useAuth();
- const { shortcut: selectedShortcut, setShortcut } = useMemoFilterContext();
- const [deleteTarget, setDeleteTarget] = useState<Shortcut | undefined>();
-
- const handleDeleteShortcut = async (shortcut: Shortcut) => {
- setDeleteTarget(shortcut);
- };
-
- const confirmDeleteShortcut = async () => {
- if (!deleteTarget) return;
- await shortcutServiceClient.deleteShortcut({ name: deleteTarget.name });
- await refetchSettings();
- toast.success(t("setting.shortcut.delete-success", { title: deleteTarget.title }));
- setDeleteTarget(undefined);
- };
-
- const handleCreateShortcut = () => {
- navigate(ROUTES.SHORTCUTS, { state: { openCreate: true } });
- };
-
- const handleEditShortcut = (shortcut: Shortcut) => {
- navigate(ROUTES.SHORTCUTS, { state: { shortcut } });
- };
-
- return (
- <div className="w-full flex flex-col justify-start items-start mt-3 px-1 h-auto shrink-0 flex-nowrap">
- <div className="flex flex-row justify-between items-center w-full gap-1 mb-1 text-sm leading-6 text-muted-foreground select-none">
- <span>{t("common.shortcuts")}</span>
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger render={<PlusIcon className="w-4 h-auto cursor-pointer" onClick={handleCreateShortcut} />} />
- <TooltipContent>
- <p>{t("common.create")}</p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </div>
- <div className="w-full flex flex-row justify-start items-center relative flex-wrap gap-x-2 gap-y-1">
- {shortcuts.map((shortcut) => {
- const shortcutId = getShortcutId(shortcut.name);
- const maybeEmoji = shortcut.title.split(" ")[0];
- const emoji = emojiRegex.test(maybeEmoji) ? maybeEmoji : undefined;
- const title = emoji ? shortcut.title.replace(emoji, "") : shortcut.title;
- const selected = selectedShortcut === shortcutId;
- return (
- <div
- key={shortcutId}
- className="shrink-0 w-full text-sm rounded-md leading-6 flex flex-row justify-between items-center select-none gap-2 text-muted-foreground"
- >
- <span
- className={cn("truncate cursor-pointer text-muted-foreground", selected && "text-primary font-medium")}
- onClick={() => (selected ? setShortcut(undefined) : setShortcut(shortcutId))}
- >
- {emoji && <span className="text-base mr-1">{emoji}</span>}
- {title.trim()}
- </span>
- <DropdownMenu>
- <DropdownMenuTrigger
- nativeButton={false}
- render={<MoreVerticalIcon className="w-4 h-auto shrink-0 text-muted-foreground cursor-pointer hover:text-foreground" />}
- />
- <DropdownMenuContent align="end" alignOffset={-12}>
- <DropdownMenuItem onClick={() => handleEditShortcut(shortcut)}>
- <Edit3Icon className="w-4 h-auto" />
- {t("common.edit")}
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => handleDeleteShortcut(shortcut)}>
- <TrashIcon className="w-4 h-auto" />
- {t("common.delete")}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- );
- })}
- </div>
- <ConfirmDialog
- open={!!deleteTarget}
- onOpenChange={(open) => !open && setDeleteTarget(undefined)}
- title={t("setting.shortcut.delete-confirm", { title: deleteTarget?.title ?? "" })}
- confirmLabel={t("common.delete")}
- cancelLabel={t("common.cancel")}
- onConfirm={confirmDeleteShortcut}
- confirmVariant="destructive"
- />
- </div>
- );
-}
-
-export default ShortcutsSection;
diff --git a/web/src/components/MemoExplorer/TagsSection.tsx b/web/src/components/MemoExplorer/TagsSection.tsx
deleted file mode 100644
index ac185a0c0..000000000
--- a/web/src/components/MemoExplorer/TagsSection.tsx
+++ /dev/null
@@ -1,100 +0,0 @@
-import { HashIcon, MoreVerticalIcon, TagsIcon } from "lucide-react";
-import { Switch } from "@/components/ui/switch";
-import { type MemoFilter, useMemoFilterContext } from "@/contexts/MemoFilterContext";
-import { useLocalStorage } from "@/hooks";
-import { cn } from "@/lib/utils";
-import { useTranslate } from "@/utils/i18n";
-import TagTree from "../TagTree";
-import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
-
-interface Props {
- readonly?: boolean;
- tagCount: Record<string, number>;
-}
-
-const TagsSection = (props: Props) => {
- const t = useTranslate();
- const { getFiltersByFactor, addFilter, removeFilter } = useMemoFilterContext();
- const [treeMode, setTreeMode] = useLocalStorage<boolean>("tag-view-as-tree", false);
- const [treeAutoExpand, setTreeAutoExpand] = useLocalStorage<boolean>("tag-tree-auto-expand", false);
-
- const tags = Object.entries(props.tagCount)
- .sort((a, b) => a[0].localeCompare(b[0]))
- .sort((a, b) => b[1] - a[1]);
-
- const handleTagClick = (tag: string) => {
- const isActive = getFiltersByFactor("tagSearch").some((filter: MemoFilter) => filter.value === tag);
- if (isActive) {
- removeFilter((f: MemoFilter) => f.factor === "tagSearch" && f.value === tag);
- } else {
- // Remove all existing tag filters first, then add the new one
- removeFilter((f: MemoFilter) => f.factor === "tagSearch");
- addFilter({
- factor: "tagSearch",
- value: tag,
- });
- }
- };
-
- return (
- <div className="w-full flex flex-col justify-start items-start mt-3 px-1 h-auto shrink-0 flex-nowrap">
- <div className="flex flex-row justify-between items-center w-full gap-1 mb-1 text-sm leading-6 text-muted-foreground select-none">
- <span>{t("common.tags")}</span>
- {tags.length > 0 && (
- <Popover>
- <PopoverTrigger>
- <MoreVerticalIcon className="w-4 h-auto shrink-0 text-muted-foreground cursor-pointer hover:text-foreground" />
- </PopoverTrigger>
- <PopoverContent align="end" alignOffset={-12}>
- <div className="w-auto flex flex-row justify-between items-center gap-2 p-1">
- <span className="text-sm shrink-0">{t("common.tree-mode")}</span>
- <Switch checked={treeMode} onCheckedChange={(checked) => setTreeMode(checked)} />
- </div>
- <div className="w-auto flex flex-row justify-between items-center gap-2 p-1">
- <span className="text-sm shrink-0">{t("common.auto-expand")}</span>
- <Switch disabled={!treeMode} checked={treeAutoExpand} onCheckedChange={(checked) => setTreeAutoExpand(checked)} />
- </div>
- </PopoverContent>
- </Popover>
- )}
- </div>
- {tags.length > 0 ? (
- treeMode ? (
- <TagTree tagAmounts={tags} expandSubTags={!!treeAutoExpand} />
- ) : (
- <div className="w-full flex flex-row justify-start items-center relative flex-wrap gap-x-2 gap-y-1.5">
- {tags.map(([tag, amount]) => {
- const isActive = getFiltersByFactor("tagSearch").some((filter: MemoFilter) => filter.value === tag);
- return (
- <div
- key={tag}
- className={cn(
- "shrink-0 w-auto max-w-full text-sm rounded-md leading-6 flex flex-row justify-start items-center select-none cursor-pointer transition-colors",
- "hover:opacity-80",
- isActive ? "text-primary" : "text-muted-foreground",
- )}
- onClick={() => handleTagClick(tag)}
- >
- <HashIcon className="w-4 h-auto shrink-0" />
- <div className="inline-flex flex-nowrap ml-0.5 gap-0.5 max-w-[calc(100%-16px)]">
- <span className={cn("truncate", isActive ? "font-medium" : "")}>{tag}</span>
- {amount > 1 && <span className="opacity-60 shrink-0">({amount})</span>}
- </div>
- </div>
- );
- })}
- </div>
- )
- ) : (
- !props.readonly && (
- <div className="p-2 border border-dashed rounded-md flex flex-row justify-start items-start gap-2 text-muted-foreground">
- <TagsIcon className="w-5 h-5 shrink-0" />
- <p className="text-sm leading-snug italic">{t("tag.create-tags-guide")}</p>
- </div>
- )
- )}
- </div>
- );
-};
-
-export default TagsSection;
diff --git a/web/src/components/MemoExplorer/index.ts b/web/src/components/MemoExplorer/index.ts
deleted file mode 100644
index a983ef615..000000000
--- a/web/src/components/MemoExplorer/index.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import MemoExplorer from "./MemoExplorer";
-import MemoExplorerDrawer from "./MemoExplorerDrawer";
-
-export type { MemoExplorerContext, MemoExplorerFeatures } from "./MemoExplorer";
-export { MemoExplorer, MemoExplorerDrawer };
diff --git a/web/src/components/MemosLogo.tsx b/web/src/components/MemosLogo.tsx
index 1552817a7..6c3a961db 100644
--- a/web/src/components/MemosLogo.tsx
+++ b/web/src/components/MemosLogo.tsx
@@ -5,19 +5,31 @@ import UserAvatar from "./UserAvatar";
interface Props {
className?: string;
collapsed?: boolean;
+ compact?: boolean;
}
function MemosLogo(props: Props) {
- const { collapsed } = props;
+ const { collapsed, compact } = props;
const { generalSetting: instanceGeneralSetting } = useInstance();
const title = instanceGeneralSetting.customProfile?.title || "Memos";
const avatarUrl = instanceGeneralSetting.customProfile?.logoUrl || "/full-logo.webp";
return (
<div className={cn("relative w-full h-auto shrink-0", props.className)}>
- <div className={cn("w-auto flex flex-row justify-start items-center text-foreground", collapsed ? "px-1" : "px-3")}>
- <UserAvatar className="shrink-0" avatarUrl={avatarUrl} />
- {!collapsed && <span className="ml-2 text-lg font-medium text-foreground shrink truncate">{title}</span>}
+ <div
+ className={cn("w-auto flex flex-row justify-start items-center text-foreground", compact ? "px-0" : collapsed ? "px-1" : "px-3")}
+ >
+ <UserAvatar className={cn("shrink-0", compact && "size-7 rounded-[7px]")} avatarUrl={avatarUrl} />
+ {!collapsed && (
+ <span
+ className={cn(
+ "font-medium text-foreground shrink truncate",
+ compact ? "ml-1.5 text-[14px] tracking-[-0.01em]" : "ml-2 text-lg",
+ )}
+ >
+ {title}
+ </span>
+ )}
</div>
</div>
);
diff --git a/web/src/components/MobileHeader.tsx b/web/src/components/MobileHeader.tsx
deleted file mode 100644
index e0556cf40..000000000
--- a/web/src/components/MobileHeader.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-import { useEffect, useState } from "react";
-import useMediaQuery from "@/hooks/useMediaQuery";
-import { cn } from "@/lib/utils";
-import NavigationDrawer from "./NavigationDrawer";
-
-interface Props {
- className?: string;
- children?: React.ReactNode;
-}
-
-const MobileHeader = (props: Props) => {
- const { className, children } = props;
- const [offsetTop, setOffsetTop] = useState(() => (typeof window === "undefined" ? 0 : window.scrollY));
- const md = useMediaQuery("md");
- const sm = useMediaQuery("sm");
-
- useEffect(() => {
- const handleScroll = () => {
- setOffsetTop(window.scrollY);
- };
-
- window.addEventListener("scroll", handleScroll, { passive: true });
- handleScroll();
-
- return () => {
- window.removeEventListener("scroll", handleScroll);
- };
- }, []);
-
- if (md) return null;
-
- return (
- <div
- className={cn(
- "sticky top-0 pt-3 pb-2 sm:pt-2 px-4 sm:px-6 sm:mb-1 bg-background bg-opacity-80 backdrop-blur-lg flex flex-row justify-between items-center w-full h-auto flex-nowrap shrink-0 z-1",
- offsetTop > 0 && "shadow-md",
- className,
- )}
- >
- {!sm && <NavigationDrawer />}
- <div className="w-full flex flex-row justify-end items-center">{children}</div>
- </div>
- );
-};
-
-export default MobileHeader;
diff --git a/web/src/components/Navigation.tsx b/web/src/components/Navigation.tsx
deleted file mode 100644
index 09d0ec32b..000000000
--- a/web/src/components/Navigation.tsx
+++ /dev/null
@@ -1,145 +0,0 @@
-import { BellIcon, EarthIcon, InfoIcon, LibraryIcon, PaperclipIcon, UserCircleIcon } from "lucide-react";
-import { NavLink } from "react-router-dom";
-import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
-import { useGlobalMemoEditor } from "@/contexts/GlobalMemoEditorContext";
-import useCurrentUser from "@/hooks/useCurrentUser";
-import { useNotifications } from "@/hooks/useUserQueries";
-import { cn } from "@/lib/utils";
-import { Routes } from "@/router";
-import { UserNotification_Status } from "@/types/proto/api/v1/user_service_pb";
-import { useTranslate } from "@/utils/i18n";
-import MemosLogo from "./MemosLogo";
-import UserMenu from "./UserMenu";
-
-interface NavLinkItem {
- id: string;
- path: string;
- title: string;
- icon: React.ReactNode;
-}
-
-interface Props {
- collapsed?: boolean;
- className?: string;
-}
-
-const Navigation = (props: Props) => {
- const { collapsed, className } = props;
- const t = useTranslate();
- const currentUser = useCurrentUser();
- const { openEditor } = useGlobalMemoEditor();
- const { data: notifications = [] } = useNotifications();
-
- const homeNavLink: NavLinkItem = {
- id: "header-memos",
- path: Routes.HOME,
- title: t("common.memos"),
- icon: <LibraryIcon className="w-6 h-auto shrink-0" />,
- };
- const exploreNavLink: NavLinkItem = {
- id: "header-explore",
- path: Routes.EXPLORE,
- title: t("common.explore"),
- icon: <EarthIcon className="w-6 h-auto shrink-0" />,
- };
- const aboutNavLink: NavLinkItem = {
- id: "header-about",
- path: Routes.ABOUT,
- title: t("common.about"),
- icon: <InfoIcon className="w-6 h-auto shrink-0" />,
- };
- const attachmentsNavLink: NavLinkItem = {
- id: "header-attachments",
- path: Routes.ATTACHMENTS,
- title: t("common.attachments"),
- icon: <PaperclipIcon className="w-6 h-auto shrink-0" />,
- };
- const unreadCount = notifications.filter((n) => n.status === UserNotification_Status.UNREAD).length;
- const inboxNavLink: NavLinkItem = {
- id: "header-inbox",
- path: Routes.INBOX,
- title: t("common.inbox"),
- icon: (
- <div className="relative">
- <BellIcon className="w-6 h-auto shrink-0" />
- {unreadCount > 0 && (
- <span className="absolute -top-1 -right-1 min-w-[18px] h-[18px] px-1 flex items-center justify-center bg-primary text-primary-foreground text-[10px] font-semibold rounded-full border-2 border-background">
- {unreadCount > 99 ? "99+" : unreadCount}
- </span>
- )}
- </div>
- ),
- };
- const signInNavLink: NavLinkItem = {
- id: "header-auth",
- path: Routes.AUTH,
- title: t("common.sign-in"),
- icon: <UserCircleIcon className="w-6 h-auto shrink-0" />,
- };
-
- const primaryNavLinks: NavLinkItem[] = currentUser
- ? [homeNavLink, exploreNavLink, attachmentsNavLink, inboxNavLink]
- : [exploreNavLink, aboutNavLink, signInNavLink];
- const inboxAriaLabel = unreadCount > 0 ? `${t("common.inbox")}, ${unreadCount} unread` : t("common.inbox");
-
- return (
- <header className={cn("w-full h-full overflow-auto flex flex-col justify-between items-start gap-4", className)}>
- <div className="w-full px-1 py-1 flex flex-col justify-start items-start space-y-2 overflow-auto overflow-x-hidden shrink">
- {currentUser ? (
- <button
- type="button"
- className="mb-3 cursor-default"
- aria-label={`${t("common.create")} ${t("common.memos")}`}
- onClick={openEditor}
- >
- <MemosLogo collapsed={collapsed} />
- </button>
- ) : (
- <NavLink className="mb-3 cursor-default" to={Routes.EXPLORE}>
- <MemosLogo collapsed={collapsed} />
- </NavLink>
- )}
- <TooltipProvider>
- {primaryNavLinks.map((navLink) => (
- <NavLink
- className={({ isActive }) =>
- cn(
- "px-2 py-2 rounded-2xl border flex flex-row items-center text-lg text-sidebar-foreground transition-colors",
- collapsed ? "" : "w-full px-4",
- isActive
- ? "bg-sidebar-accent text-sidebar-accent-foreground border-sidebar-accent-border drop-shadow"
- : "border-transparent hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:border-sidebar-accent-border opacity-80",
- )
- }
- key={navLink.id}
- to={navLink.path}
- end={navLink.path === Routes.HOME}
- id={navLink.id}
- aria-label={navLink.id === "header-inbox" ? inboxAriaLabel : undefined}
- viewTransition
- >
- {props.collapsed ? (
- <Tooltip>
- <TooltipTrigger render={<div />}>{navLink.icon}</TooltipTrigger>
- <TooltipContent side="right">
- <p>{navLink.title}</p>
- </TooltipContent>
- </Tooltip>
- ) : (
- navLink.icon
- )}
- {!props.collapsed && <span className="ml-3 truncate">{navLink.title}</span>}
- </NavLink>
- ))}
- </TooltipProvider>
- </div>
- {currentUser && (
- <div className={cn("w-full flex flex-col justify-end", props.collapsed ? "items-center" : "items-start pl-3")}>
- <UserMenu collapsed={collapsed} />
- </div>
- )}
- </header>
- );
-};
-
-export default Navigation;
diff --git a/web/src/components/NavigationDrawer.tsx b/web/src/components/NavigationDrawer.tsx
deleted file mode 100644
index b9fc63ab3..000000000
--- a/web/src/components/NavigationDrawer.tsx
+++ /dev/null
@@ -1,38 +0,0 @@
-import { useEffect, useState } from "react";
-import { useLocation } from "react-router-dom";
-import { Button } from "@/components/ui/button";
-import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from "@/components/ui/sheet";
-import { useGlobalMemoEditor } from "@/contexts/GlobalMemoEditorContext";
-import { useInstance } from "@/contexts/InstanceContext";
-import Navigation from "./Navigation";
-import UserAvatar from "./UserAvatar";
-
-const NavigationDrawer = () => {
- const location = useLocation();
- const [open, setOpen] = useState(false);
- const { isOpen: isGlobalMemoEditorOpen } = useGlobalMemoEditor();
- const { generalSetting } = useInstance();
- const title = generalSetting.customProfile?.title || "Memos";
- const avatarUrl = generalSetting.customProfile?.logoUrl || "/full-logo.webp";
-
- useEffect(() => {
- setOpen(false);
- }, [location.key, isGlobalMemoEditorOpen]);
-
- return (
- <Sheet open={open} onOpenChange={setOpen}>
- <SheetTrigger render={<Button variant="ghost" className="px-2" />}>
- <UserAvatar className="shrink-0 w-6 h-6 rounded-md" avatarUrl={avatarUrl} />
- <span className="font-bold text-lg leading-10 text-ellipsis overflow-hidden text-foreground">{title}</span>
- </SheetTrigger>
- <SheetContent side="left" className="w-80 max-w-full overflow-auto px-2 bg-background">
- <SheetHeader>
- <SheetTitle />
- </SheetHeader>
- <Navigation className="pb-4" />
- </SheetContent>
- </Sheet>
- );
-};
-
-export default NavigationDrawer;
diff --git a/web/src/components/SearchBar.tsx b/web/src/components/SearchBar.tsx
deleted file mode 100644
index 4a8684c13..000000000
--- a/web/src/components/SearchBar.tsx
+++ /dev/null
@@ -1,50 +0,0 @@
-import { SearchIcon } from "lucide-react";
-import { useRef, useState } from "react";
-import { useMemoFilterContext } from "@/contexts/MemoFilterContext";
-import { useTranslate } from "@/utils/i18n";
-import MemoDisplaySettingMenu from "./MemoDisplaySettingMenu";
-
-const SearchBar = () => {
- const t = useTranslate();
- const { addFilter } = useMemoFilterContext();
- const [queryText, setQueryText] = useState("");
- const inputRef = useRef<HTMLInputElement>(null);
-
- const onTextChange = (event: React.FormEvent<HTMLInputElement>) => {
- setQueryText(event.currentTarget.value);
- };
-
- const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
- if (e.key === "Enter") {
- e.preventDefault();
- const trimmedText = queryText.trim();
- if (trimmedText !== "") {
- const words = trimmedText.split(/\s+/);
- words.forEach((word) => {
- addFilter({
- factor: "contentSearch",
- value: word,
- });
- });
- setQueryText("");
- }
- }
- };
-
- return (
- <div className="relative w-full h-auto flex flex-row justify-start items-center">
- <SearchIcon className="absolute left-2 w-4 h-auto opacity-40 text-sidebar-foreground" />
- <input
- className="w-full text-sidebar-foreground leading-6 bg-sidebar border border-border text-sm rounded-lg p-1 pl-8 outline-0"
- placeholder={t("memo.search-placeholder")}
- value={queryText}
- onChange={onTextChange}
- onKeyDown={onKeyDown}
- ref={inputRef}
- />
- <MemoDisplaySettingMenu className="absolute right-2 top-2 text-sidebar-foreground" />
- </div>
- );
-};
-
-export default SearchBar;
diff --git a/web/src/components/StatisticsView/MonthNavigator.tsx b/web/src/components/StatisticsView/MonthNavigator.tsx
index 4bc8784a7..3230d5500 100644
--- a/web/src/components/StatisticsView/MonthNavigator.tsx
+++ b/web/src/components/StatisticsView/MonthNavigator.tsx
@@ -1,82 +1,42 @@
import dayjs from "dayjs";
import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";
-import { memo, useCallback, useMemo, useState } from "react";
+import { memo } from "react";
import { useTranslation } from "react-i18next";
-import { YearCalendar } from "@/components/ActivityCalendar";
import { Button } from "@/components/ui/button";
-import { Dialog, DialogContent, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
-import { addMonths, formatMonth, getMonthFromDate, getYearFromDate, setYearAndMonth } from "@/lib/calendar-utils";
+import { addMonths } from "@/lib/calendar-utils";
import type { MonthNavigatorProps } from "@/types/statistics";
-export const MonthNavigator = memo(({ visibleMonth, onMonthChange, activityStats, timeBasis }: MonthNavigatorProps) => {
- const { i18n } = useTranslation();
- const [isOpen, setIsOpen] = useState(false);
-
- const { currentMonth, currentYear, currentMonthNum } = useMemo(
- () => ({
- currentMonth: dayjs(visibleMonth).toDate(),
- currentYear: getYearFromDate(visibleMonth),
- currentMonthNum: getMonthFromDate(visibleMonth),
- }),
- [visibleMonth],
- );
-
- const monthLabel = useMemo(
- () => currentMonth.toLocaleString(i18n.language, { year: "numeric", month: "long" }),
- [currentMonth, i18n.language],
- );
-
- const handlePrevMonth = useCallback(() => onMonthChange(addMonths(visibleMonth, -1)), [visibleMonth, onMonthChange]);
- const handleNextMonth = useCallback(() => onMonthChange(addMonths(visibleMonth, 1)), [visibleMonth, onMonthChange]);
-
- const handleDateClick = useCallback(
- (date: string) => {
- onMonthChange(formatMonth(date));
- setIsOpen(false);
- },
- [onMonthChange],
- );
-
- const handleYearChange = useCallback(
- (year: number) => onMonthChange(setYearAndMonth(year, currentMonthNum)),
- [currentMonthNum, onMonthChange],
- );
+export const MonthNavigator = memo(({ visibleMonth, onMonthChange }: MonthNavigatorProps) => {
+ const { i18n, t } = useTranslation();
+ const monthLabel = dayjs(visibleMonth).toDate().toLocaleString(i18n.language, { year: "numeric", month: "long" });
+ const handlePrevMonth = () => onMonthChange(addMonths(visibleMonth, -1));
+ const handleNextMonth = () => onMonthChange(addMonths(visibleMonth, 1));
return (
- <header className="w-full mb-2 flex items-center justify-between gap-2">
- <Dialog open={isOpen} onOpenChange={setIsOpen}>
- <DialogTrigger
- render={
- <button
- type="button"
- className="py-0.5 text-sm text-foreground font-medium transition-colors hover:text-foreground/80 select-none"
- />
- }
- >
- {monthLabel}
- </DialogTrigger>
- <DialogContent
- className="p-0 border border-border/20 bg-background md:max-w-6xl w-[min(100vw-24px,1200px)] max-h-[85vh] overflow-y-auto rounded-xl shadow-xl"
- size="2xl"
- showCloseButton={false}
+ <header className="mb-1.5 flex w-full items-center justify-between gap-3">
+ <h2 className="min-w-0 truncate text-[15px] font-semibold leading-7 tracking-[-0.015em] text-foreground/90 select-none">
+ {monthLabel}
+ </h2>
+
+ <nav className="flex shrink-0 items-center gap-1" aria-label={t("common.month-navigation")}>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={handlePrevMonth}
+ aria-label={t("common.previous-month")}
+ className="size-7 rounded-md text-muted-foreground/65 hover:bg-muted/50 hover:text-foreground/90"
>
- <DialogTitle className="sr-only">Select Month</DialogTitle>
- <YearCalendar
- selectedYear={currentYear}
- data={activityStats}
- onYearChange={handleYearChange}
- onDateClick={handleDateClick}
- timeBasis={timeBasis}
- />
- </DialogContent>
- </Dialog>
-
- <nav className="flex items-center shrink-0" aria-label="Month navigation">
- <Button variant="ghost" size="icon-sm" onClick={handlePrevMonth} aria-label="Previous month">
- <ChevronLeftIcon className="w-4 h-4" />
+ <ChevronLeftIcon className="size-[15px]" strokeWidth={1.75} />
</Button>
- <Button variant="ghost" size="icon-sm" onClick={handleNextMonth} aria-label="Next month">
- <ChevronRightIcon className="w-4 h-4" />
+
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={handleNextMonth}
+ aria-label={t("common.next-month")}
+ className="size-7 rounded-md text-muted-foreground/65 hover:bg-muted/50 hover:text-foreground/90"
+ >
+ <ChevronRightIcon className="size-[15px]" strokeWidth={1.75} />
</Button>
</nav>
</header>
diff --git a/web/src/components/StatisticsView/StatisticsView.tsx b/web/src/components/StatisticsView/StatisticsView.tsx
index 7bea77c85..169f359e1 100644
--- a/web/src/components/StatisticsView/StatisticsView.tsx
+++ b/web/src/components/StatisticsView/StatisticsView.tsx
@@ -1,35 +1,38 @@
import dayjs from "dayjs";
import { useState } from "react";
import { calculateMaxCount, MonthCalendar } from "@/components/ActivityCalendar";
+import { useMemoFilterContext } from "@/contexts/MemoFilterContext";
import { useDateFilterNavigation } from "@/hooks";
import type { StatisticsData } from "@/types/statistics";
import { MonthNavigator } from "./MonthNavigator";
interface Props {
statisticsData: StatisticsData;
+ onDateSelect?: () => void;
}
const StatisticsView = (props: Props) => {
const { statisticsData } = props;
const { activityStats, timeBasis } = statisticsData;
+ const { filters } = useMemoFilterContext();
const navigateToDateFilter = useDateFilterNavigation();
const [visibleMonthString, setVisibleMonthString] = useState(dayjs().format("YYYY-MM"));
+ const selectedDate = filters.find((filter) => filter.factor === "displayTime")?.value;
return (
- <div className="group w-full mt-2 flex flex-col text-muted-foreground animate-fade-in">
- <MonthNavigator
- visibleMonth={visibleMonthString}
- onMonthChange={setVisibleMonthString}
- activityStats={activityStats}
- timeBasis={timeBasis}
- />
+ <div className="group mt-0.5 flex w-full flex-col text-muted-foreground animate-fade-in">
+ <MonthNavigator visibleMonth={visibleMonthString} onMonthChange={setVisibleMonthString} />
<div className="w-full animate-scale-in">
<MonthCalendar
month={visibleMonthString}
data={activityStats}
maxCount={calculateMaxCount(activityStats)}
- onClick={navigateToDateFilter}
+ selectedDate={selectedDate}
+ onClick={(date) => {
+ navigateToDateFilter(date);
+ props.onDateSelect?.();
+ }}
timeBasis={timeBasis}
/>
</div>
diff --git a/web/src/components/TagTree.tsx b/web/src/components/TagTree.tsx
index 5352a36f2..4157637fa 100644
--- a/web/src/components/TagTree.tsx
+++ b/web/src/components/TagTree.tsx
@@ -1,6 +1,9 @@
import { ChevronRightIcon, HashIcon } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
+import { SIDEBAR_ROW_CLASSES, SIDEBAR_ROW_COUNT_CLASSES, SIDEBAR_ROW_ICON_CLASSES } from "@/components/AppSidebar/SidebarRow";
import { type MemoFilter, useMemoFilterContext } from "@/contexts/MemoFilterContext";
+import { cn } from "@/lib/utils";
+import { useTranslate } from "@/utils/i18n";
interface Tag {
key: string;
@@ -71,7 +74,7 @@ const TagTree = ({ tagAmounts: rawTagAmounts, expandSubTags }: Props) => {
}, [rawTagAmounts]);
return (
- <div className="flex flex-col justify-start items-start relative w-full h-auto flex-nowrap gap-2 mt-1">
+ <div className="relative flex h-auto w-full flex-col flex-nowrap items-start justify-start gap-0.5">
{tags.map((t, idx) => (
<TagItemContainer key={t.text + "-" + idx} tag={t} expandSubTags={expandSubTags} />
))}
@@ -86,6 +89,7 @@ interface TagItemContainerProps {
const TagItemContainer = (props: TagItemContainerProps) => {
const { tag, expandSubTags } = props;
+ const t = useTranslate();
const { getFiltersByFactor, addFilter, removeFilter } = useMemoFilterContext();
const tagFilters = getFiltersByFactor("tagSearch");
const isActive = tagFilters.some((f: MemoFilter) => f.value === tag.text);
@@ -116,30 +120,39 @@ const TagItemContainer = (props: TagItemContainerProps) => {
return (
<>
- <div className="relative flex flex-row justify-between items-center w-full leading-6 py-0 mt-px text-sm select-none shrink-0">
- <div
- className={`flex flex-row justify-start items-center truncate shrink leading-5 mr-1 cursor-pointer transition-colors ${
- isActive ? "text-primary" : "text-muted-foreground"
- }`}
+ <div
+ className={cn(
+ SIDEBAR_ROW_CLASSES,
+ "shrink-0 select-none",
+ isActive
+ ? "bg-sidebar-accent font-medium text-sidebar-accent-foreground"
+ : "text-muted-foreground hover:bg-sidebar-accent/65 hover:text-foreground",
+ )}
+ >
+ <button
+ type="button"
+ aria-pressed={isActive || undefined}
+ className="flex h-full min-w-0 flex-1 items-center gap-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
onClick={handleTagClick}
>
- <HashIcon className="w-4 h-auto shrink-0 mr-1" />
- <span className={`truncate hover:opacity-80 ${isActive ? "font-medium" : ""}`}>
- {tag.key} {tag.amount > 1 && <span className="opacity-60">({tag.amount})</span>}
- </span>
- </div>
- <div className="flex flex-row justify-end items-center">
- {hasSubTags ? (
- <span
- className={`flex flex-row justify-center items-center w-6 h-6 shrink-0 transition-all rotate-0 cursor-pointer ${
- showSubTags && "rotate-90"
- }`}
- onClick={handleToggleBtnClick}
- >
- <ChevronRightIcon className="w-5 h-5 text-muted-foreground hover:text-foreground" />
- </span>
- ) : null}
- </div>
+ <HashIcon className={SIDEBAR_ROW_ICON_CLASSES} strokeWidth={1.8} />
+ <span className="min-w-0 flex-1 truncate">{tag.key}</span>
+ </button>
+ {tag.amount > 1 && <span className={SIDEBAR_ROW_COUNT_CLASSES}>{tag.amount}</span>}
+ {hasSubTags && (
+ <button
+ type="button"
+ aria-label={`${showSubTags ? t("common.collapse") : t("common.expand")} ${tag.key}`}
+ aria-expanded={showSubTags}
+ className={cn(
+ "-mr-1 flex size-6 shrink-0 items-center justify-center rounded transition-colors hover:bg-background/70",
+ showSubTags && "[&>svg]:rotate-90",
+ )}
+ onClick={handleToggleBtnClick}
+ >
+ <ChevronRightIcon className="size-3.5 transition-transform" />
+ </button>
+ )}
</div>
{hasSubTags ? (
<div
diff --git a/web/src/components/UserMenu.tsx b/web/src/components/UserMenu.tsx
index 183a3c9aa..c7c2255f8 100644
--- a/web/src/components/UserMenu.tsx
+++ b/web/src/components/UserMenu.tsx
@@ -1,6 +1,6 @@
import {
- ArchiveIcon,
CheckIcon,
+ ChevronsUpDownIcon,
GlobeIcon,
InfoIcon,
LogOutIcon,
@@ -9,6 +9,7 @@ import {
SquareUserIcon,
User2Icon,
} from "lucide-react";
+import { useAppSidebar } from "@/contexts/AppSidebarContext";
import { useAuth } from "@/contexts/AuthContext";
import useCurrentUser from "@/hooks/useCurrentUser";
import { useSSEConnectionStatus } from "@/hooks/useLiveMemoRefresh";
@@ -39,6 +40,7 @@ const UserMenu = (props: Props) => {
const { collapsed } = props;
const t = useTranslate();
const navigateTo = useNavigateTo();
+ const { setAboutOpen, setMobileOpen } = useAppSidebar();
const currentUser = useCurrentUser();
const { userGeneralSetting, refetchSettings, logout } = useAuth();
const { mutate: updateUserGeneralSetting } = useUpdateUserGeneralSetting(currentUser?.name);
@@ -102,58 +104,61 @@ const UserMenu = (props: Props) => {
window.location.replace(Routes.AUTH);
};
+ const navigateFromMenu = (path: string) => {
+ setMobileOpen(false);
+ navigateTo(path);
+ };
+
+ const handleAboutOpen = () => {
+ setMobileOpen(false);
+ setAboutOpen(true);
+ };
+
return (
<DropdownMenu>
<DropdownMenuTrigger
- nativeButton={false}
disabled={!currentUser}
- render={
- <div
- className={cn("w-auto flex flex-row justify-start items-center cursor-pointer text-foreground", collapsed ? "px-1" : "px-3")}
- />
- }
+ className={cn(
+ "flex h-10 w-full min-w-0 cursor-pointer items-center justify-between gap-2 px-3 text-left text-foreground transition-colors hover:bg-sidebar-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/50 data-popup-open:bg-sidebar-accent",
+ collapsed && "w-auto px-2",
+ )}
>
- <div className="relative shrink-0">
- {currentUser?.avatarUrl ? (
- <UserAvatar avatarUrl={currentUser?.avatarUrl} />
- ) : (
- <User2Icon className="w-6 mx-auto h-auto text-muted-foreground" />
- )}
- {sseStatus !== "connected" && (
- <Tooltip>
- <TooltipTrigger
- render={
- <span
- className={cn(
- "absolute -bottom-0.5 -right-0.5 size-2.5 rounded-full border-2 border-background",
- sseStatus === "connecting" ? "bg-muted-foreground animate-pulse" : "bg-destructive",
- )}
- />
- }
- />
- <TooltipContent side="right">{t(`live-update.${sseStatus}` as Parameters<typeof t>[0])}</TooltipContent>
- </Tooltip>
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ <div className="relative shrink-0">
+ {currentUser?.avatarUrl ? (
+ <UserAvatar className="size-6 rounded-md" avatarUrl={currentUser?.avatarUrl} />
+ ) : (
+ <User2Icon className="mx-auto size-5 text-muted-foreground" />
+ )}
+ {sseStatus !== "connected" && (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span
+ className={cn(
+ "absolute -bottom-0.5 -right-0.5 size-2.5 rounded-full border-2 border-background",
+ sseStatus === "connecting" ? "bg-muted-foreground animate-pulse" : "bg-destructive",
+ )}
+ />
+ }
+ />
+ <TooltipContent side="right">{t(`live-update.${sseStatus}` as Parameters<typeof t>[0])}</TooltipContent>
+ </Tooltip>
+ )}
+ </div>
+ {!collapsed && (
+ <span className="min-w-0 flex-1 truncate text-left text-[13px] font-medium text-foreground">
+ {currentUser?.displayName || currentUser?.username}
+ </span>
)}
</div>
- {!collapsed && (
- <span className="ml-2 text-lg font-medium text-foreground grow truncate">
- {currentUser?.displayName || currentUser?.username}
- </span>
- )}
+ {!collapsed && <ChevronsUpDownIcon className="size-3.5 shrink-0 text-muted-foreground/70" strokeWidth={1.8} />}
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
- <DropdownMenuItem onClick={() => navigateTo(`/u/${encodeURIComponent(currentUser?.username ?? "")}`)}>
+ <DropdownMenuItem onClick={() => navigateFromMenu(`/u/${encodeURIComponent(currentUser?.username ?? "")}`)}>
<SquareUserIcon className="size-4 text-muted-foreground" />
{t("common.profile")}
</DropdownMenuItem>
- <DropdownMenuItem onClick={() => navigateTo(Routes.ARCHIVED)}>
- <ArchiveIcon className="size-4 text-muted-foreground" />
- {t("common.archived")}
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => navigateTo(Routes.ABOUT)}>
- <InfoIcon className="size-4 text-muted-foreground" />
- {t("common.about")}
- </DropdownMenuItem>
<DropdownMenuSub>
<DropdownMenuSubTrigger>
<GlobeIcon className="size-4 text-muted-foreground" />
@@ -178,7 +183,11 @@ const UserMenu = (props: Props) => {
))}
</DropdownMenuSubContent>
</DropdownMenuSub>
- <DropdownMenuItem onClick={() => navigateTo(Routes.SETTING)}>
+ <DropdownMenuItem onClick={handleAboutOpen}>
+ <InfoIcon className="size-4 text-muted-foreground" />
+ {t("common.about")}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => navigateFromMenu(Routes.SETTING)}>
<SettingsIcon className="size-4 text-muted-foreground" />
{t("common.settings")}
</DropdownMenuItem>
diff --git a/web/src/contexts/AppSidebarContext.tsx b/web/src/contexts/AppSidebarContext.tsx
new file mode 100644
index 000000000..4c3a55c99
--- /dev/null
+++ b/web/src/contexts/AppSidebarContext.tsx
@@ -0,0 +1,84 @@
+import { createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useState } from "react";
+import { useLocation } from "react-router-dom";
+import type { MemoScope } from "@/lib/memo-views";
+import type { Memo } from "@/types/proto/api/v1/memo_service_pb";
+
+export type AttachmentSection = "all" | "media" | "audio" | "documents" | "unused";
+export type InboxFilter = "all" | "unread" | "archived";
+
+export interface MemoDetailSidebarDescriptor {
+ memo: Memo;
+ from?: string;
+ readonly?: boolean;
+ onShareImageOpen?: () => void;
+}
+
+interface AppSidebarContextValue {
+ aboutOpen: boolean;
+ setAboutOpen: (open: boolean) => void;
+ attachmentSection: AttachmentSection;
+ setAttachmentSection: (section: AttachmentSection) => void;
+ inboxFilter: InboxFilter;
+ setInboxFilter: (filter: InboxFilter) => void;
+ memoDetail: MemoDetailSidebarDescriptor | undefined;
+ setMemoDetail: (descriptor?: MemoDetailSidebarDescriptor) => void;
+ mobileOpen: boolean;
+ setMobileOpen: (open: boolean) => void;
+ quickFindOpen: boolean;
+ setQuickFindOpen: (open: boolean) => void;
+ memoScope: MemoScope;
+ setMemoScope: (scope: MemoScope) => void;
+}
+
+const AppSidebarContext = createContext<AppSidebarContextValue | null>(null);
+
+export const AppSidebarProvider = ({ children }: { children: ReactNode }) => {
+ const location = useLocation();
+ const [aboutOpen, setAboutOpen] = useState(false);
+ const [attachmentSection, setAttachmentSection] = useState<AttachmentSection>("all");
+ const [inboxFilter, setInboxFilter] = useState<InboxFilter>("all");
+ const [memoDetail, setMemoDetailState] = useState<MemoDetailSidebarDescriptor>();
+ const [mobileOpen, setMobileOpen] = useState(false);
+ const [quickFindOpen, setQuickFindOpen] = useState(false);
+ const [memoScope, setMemoScope] = useState<MemoScope>("home");
+
+ useEffect(() => {
+ setMobileOpen(false);
+ setAttachmentSection("all");
+ setInboxFilter("all");
+ }, [location.pathname]);
+
+ const setMemoDetail = useCallback((descriptor?: MemoDetailSidebarDescriptor) => {
+ setMemoDetailState(descriptor);
+ }, []);
+
+ const value = useMemo(
+ () => ({
+ aboutOpen,
+ setAboutOpen,
+ attachmentSection,
+ setAttachmentSection,
+ inboxFilter,
+ setInboxFilter,
+ memoDetail,
+ setMemoDetail,
+ mobileOpen,
+ setMobileOpen,
+ quickFindOpen,
+ setQuickFindOpen,
+ memoScope,
+ setMemoScope,
+ }),
+ [aboutOpen, attachmentSection, inboxFilter, memoDetail, setMemoDetail, mobileOpen, quickFindOpen, memoScope],
+ );
+
+ return <AppSidebarContext.Provider value={value}>{children}</AppSidebarContext.Provider>;
+};
+
+export const useAppSidebar = () => {
+ const context = useContext(AppSidebarContext);
+ if (!context) {
+ throw new Error("useAppSidebar must be used within AppSidebarProvider");
+ }
+ return context;
+};
diff --git a/web/src/contexts/GlobalMemoEditorContext.tsx b/web/src/contexts/GlobalMemoEditorContext.tsx
deleted file mode 100644
index 6c6d39089..000000000
--- a/web/src/contexts/GlobalMemoEditorContext.tsx
+++ /dev/null
@@ -1,62 +0,0 @@
-import { type ComponentType, createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useState } from "react";
-import { loadMemoEditor } from "@/components/MemoEditor/loader";
-import type { MemoEditorProps } from "@/components/MemoEditor/types";
-import useCurrentUser from "@/hooks/useCurrentUser";
-import { useTranslate } from "@/utils/i18n";
-
-interface GlobalMemoEditorContextValue {
- isOpen: boolean;
- openEditor: () => void;
-}
-
-const GlobalMemoEditorContext = createContext<GlobalMemoEditorContextValue | null>(null);
-
-export function GlobalMemoEditorProvider({ children }: { children: ReactNode }) {
- const t = useTranslate();
- const currentUserName = useCurrentUser()?.name;
- const [isOpen, setIsOpen] = useState(false);
- const [EditorComponent, setEditorComponent] = useState<ComponentType<MemoEditorProps>>();
-
- const openEditor = useCallback(() => {
- if (!currentUserName) {
- return;
- }
-
- setIsOpen(true);
- void loadMemoEditor()
- .then(({ default: MemoEditor }) => setEditorComponent(() => MemoEditor))
- .catch(() => setIsOpen(false));
- }, [currentUserName]);
- const closeEditor = useCallback(() => setIsOpen(false), []);
- const editorIsOpen = !!currentUserName && isOpen;
- const value = useMemo(() => ({ isOpen: editorIsOpen, openEditor }), [editorIsOpen, openEditor]);
-
- useEffect(() => {
- closeEditor();
- }, [currentUserName, closeEditor]);
-
- return (
- <GlobalMemoEditorContext.Provider value={value}>
- {children}
- {editorIsOpen && EditorComponent && (
- <EditorComponent
- autoFocus
- initialFocusMode
- cacheKey="global-memo-editor"
- placeholder={t("editor.any-thoughts")}
- onConfirm={closeEditor}
- onCancel={closeEditor}
- onFocusModeExit={closeEditor}
- />
- )}
- </GlobalMemoEditorContext.Provider>
- );
-}
-
-export function useGlobalMemoEditor() {
- const context = useContext(GlobalMemoEditorContext);
- if (!context) {
- throw new Error("useGlobalMemoEditor must be used within GlobalMemoEditorProvider");
- }
- return context;
-}
diff --git a/web/src/contexts/MemoFilterContext.tsx b/web/src/contexts/MemoFilterContext.tsx
index 519130812..357f6a409 100644
--- a/web/src/contexts/MemoFilterContext.tsx
+++ b/web/src/contexts/MemoFilterContext.tsx
@@ -23,7 +23,9 @@ export const parseFilterQuery = (query: string | null): MemoFilter[] => {
if (!query) return [];
try {
return query.split(",").map((filterStr) => {
- const [factor, value] = filterStr.split(":");
+ const separatorIndex = filterStr.indexOf(":");
+ const factor = separatorIndex === -1 ? filterStr : filterStr.slice(0, separatorIndex);
+ const value = separatorIndex === -1 ? "" : filterStr.slice(separatorIndex + 1);
return {
factor: factor as FilterFactor,
value: decodeURIComponent(value || ""),
@@ -38,6 +40,11 @@ export const stringifyFilters = (filters: MemoFilter[]): string => {
return filters.map((filter) => `${filter.factor}:${encodeURIComponent(filter.value)}`).join(",");
};
+export const replaceFiltersByFactor = (filters: MemoFilter[], factor: FilterFactor, replacements: MemoFilter[]): MemoFilter[] => [
+ ...filters.filter((filter) => filter.factor !== factor),
+ ...replacements,
+];
+
interface MemoFilterContextValue {
filters: MemoFilter[];
shortcut: string | undefined;
@@ -117,10 +124,6 @@ export function MemoFilterProvider({ children }: { children: ReactNode }) {
const setShortcut = useCallback((newShortcut?: string) => {
setShortcutState(newShortcut);
- // Clear content search filter when selecting a shortcut (issue #5462)
- if (newShortcut !== undefined) {
- setFiltersState((prev) => prev.filter((f) => f.factor !== "contentSearch"));
- }
}, []);
const hasFilter = useCallback((filter: MemoFilter) => filters.some((f) => getMemoFilterKey(f) === getMemoFilterKey(filter)), [filters]);
diff --git a/web/src/hooks/useAttachmentLibrary.ts b/web/src/hooks/useAttachmentLibrary.ts
index a9679c59d..dbaea7bbc 100644
--- a/web/src/hooks/useAttachmentLibrary.ts
+++ b/web/src/hooks/useAttachmentLibrary.ts
@@ -1,6 +1,6 @@
import { timestampDate } from "@bufbuild/protobuf/wkt";
import dayjs from "dayjs";
-import { useMemo } from "react";
+import { useEffect, useMemo } from "react";
import {
getAttachmentMetadata,
isAudioAttachment,
@@ -8,10 +8,10 @@ import {
isVideoAttachment,
} from "@/components/MemoMetadata/Attachment/attachmentHelpers";
import { useInfiniteAttachments } from "@/hooks/useAttachmentQueries";
-import type { Attachment } from "@/types/proto/api/v1/attachment_service_pb";
+import type { Attachment, ListAttachmentsRequest } from "@/types/proto/api/v1/attachment_service_pb";
import { isMotionAttachment } from "@/utils/attachment";
import { useTranslate } from "@/utils/i18n";
-import { type AttachmentVisualItem, buildAttachmentVisualItems } from "@/utils/media-item";
+import { type AttachmentVisualItem, buildAttachmentVisualItems, countLogicalAttachmentItems } from "@/utils/media-item";
export type AttachmentLibraryTab = "media" | "documents" | "audio";
@@ -47,6 +47,34 @@ export interface AttachmentLibraryMonthGroup {
}
const PAGE_SIZE = 50;
+const ATTACHMENT_LIBRARY_REQUEST = {
+ pageSize: PAGE_SIZE,
+ orderBy: "create_time desc",
+};
+const COMPLETE_ATTACHMENT_LIBRARY_REQUEST = {
+ pageSize: 1000,
+ orderBy: "create_time desc",
+};
+const UNUSED_ATTACHMENT_LIBRARY_REQUEST = {
+ filter: "memo_id == null",
+ pageSize: 1000,
+ orderBy: "create_time desc",
+};
+
+const useCompleteAttachments = (request: Partial<ListAttachmentsRequest>, enabled = true) => {
+ const query = useInfiniteAttachments(request, { enabled });
+
+ useEffect(() => {
+ if (enabled && query.isSuccess && query.hasNextPage && !query.isFetchingNextPage) {
+ void query.fetchNextPage();
+ }
+ }, [enabled, query.fetchNextPage, query.hasNextPage, query.isFetchingNextPage, query.isSuccess]);
+
+ return {
+ ...query,
+ isComplete: enabled && query.isSuccess && !query.hasNextPage && !query.isFetchingNextPage,
+ };
+};
const sortByNewest = (a?: Date, b?: Date) => (b?.getTime() ?? 0) - (a?.getTime() ?? 0);
@@ -55,6 +83,18 @@ const isLinkedAttachment = (attachment: Attachment) => Boolean(attachment.memo);
const isVisualAttachment = (attachment: Attachment) =>
isImageAttachment(attachment) || isVideoAttachment(attachment) || isMotionAttachment(attachment);
+export const buildAttachmentLibraryStats = (attachments: Attachment[]): AttachmentLibraryStats => {
+ const linkedAttachments = attachments.filter(isLinkedAttachment);
+ const visualAttachments = linkedAttachments.filter(isVisualAttachment);
+
+ return {
+ unused: attachments.length - linkedAttachments.length,
+ media: countLogicalAttachmentItems(visualAttachments),
+ documents: linkedAttachments.filter((attachment) => !isVisualAttachment(attachment) && !isAudioAttachment(attachment)).length,
+ audio: linkedAttachments.filter(isAudioAttachment).length,
+ };
+};
+
const toCreatedAt = (attachment: Attachment): Date | undefined => {
return attachment.createTime ? timestampDate(attachment.createTime) : undefined;
};
@@ -132,10 +172,7 @@ const groupMediaByMonth = (
export function useAttachmentLibrary(locale: string) {
const t = useTranslate();
- const query = useInfiniteAttachments({
- pageSize: PAGE_SIZE,
- orderBy: "create_time desc",
- });
+ const query = useInfiniteAttachments(ATTACHMENT_LIBRARY_REQUEST);
const attachments = useMemo(() => (query.data?.pages ?? []).flatMap((page) => page.attachments), [query.data?.pages]);
@@ -203,3 +240,25 @@ export function useAttachmentLibrary(locale: string) {
stats,
};
}
+
+export function useAttachmentLibraryStats() {
+ const query = useCompleteAttachments(COMPLETE_ATTACHMENT_LIBRARY_REQUEST);
+ const attachments = useMemo(() => (query.data?.pages ?? []).flatMap((page) => page.attachments), [query.data?.pages]);
+ const stats = useMemo(() => buildAttachmentLibraryStats(attachments), [attachments]);
+
+ return { ...query, stats };
+}
+
+export function useUnusedAttachmentLibrary(locale: string, enabled = true) {
+ const query = useCompleteAttachments(UNUSED_ATTACHMENT_LIBRARY_REQUEST, enabled);
+ const attachments = useMemo(() => (query.data?.pages ?? []).flatMap((page) => page.attachments), [query.data?.pages]);
+ const unusedItems = useMemo(
+ () => attachments.map((attachment) => toLibraryListItem(attachment, locale)).sort((a, b) => sortByNewest(a.createdAt, b.createdAt)),
+ [attachments, locale],
+ );
+
+ return {
+ ...query,
+ unusedItems,
+ };
+}
diff --git a/web/src/hooks/useDateFilterNavigation.ts b/web/src/hooks/useDateFilterNavigation.ts
index d04724da9..e1b969741 100644
--- a/web/src/hooks/useDateFilterNavigation.ts
+++ b/web/src/hooks/useDateFilterNavigation.ts
@@ -1,18 +1,23 @@
import { useCallback } from "react";
import { useLocation, useNavigate } from "react-router-dom";
-import { stringifyFilters } from "@/contexts/MemoFilterContext";
+import { replaceFiltersByFactor, stringifyFilters, useMemoFilterContext } from "@/contexts/MemoFilterContext";
export const useDateFilterNavigation = (targetPath?: string) => {
const navigate = useNavigate();
const location = useLocation();
+ const { filters, setFilters } = useMemoFilterContext();
const navigateToDateFilter = useCallback(
(date: string) => {
- const filterQuery = stringifyFilters([{ factor: "displayTime", value: date }]);
+ const nextFilters = replaceFiltersByFactor(filters, "displayTime", [{ factor: "displayTime", value: date }]);
+ const filterQuery = stringifyFilters(nextFilters);
const basePath = targetPath ?? location.pathname;
- navigate(`${basePath}?filter=${filterQuery}`);
+ const nextSearchParams = targetPath ? new URLSearchParams() : new URLSearchParams(location.search);
+ nextSearchParams.set("filter", filterQuery);
+ setFilters(nextFilters);
+ navigate({ pathname: basePath, search: nextSearchParams.toString() });
},
- [navigate, location.pathname, targetPath],
+ [filters, location.pathname, location.search, navigate, setFilters, targetPath],
);
return navigateToDateFilter;
diff --git a/web/src/hooks/useFilteredMemoStats.ts b/web/src/hooks/useFilteredMemoStats.ts
index 70d37becf..856d69a5c 100644
--- a/web/src/hooks/useFilteredMemoStats.ts
+++ b/web/src/hooks/useFilteredMemoStats.ts
@@ -2,7 +2,6 @@ import { timestampDate } from "@bufbuild/protobuf/wkt";
import dayjs from "dayjs";
import { countBy } from "lodash-es";
import { useMemo } from "react";
-import type { MemoExplorerContext } from "@/components/MemoExplorer";
import { type MemoTimeBasis, useView } from "@/contexts/ViewContext";
import useCurrentUser from "@/hooks/useCurrentUser";
import { useAllUserStats, useUserStats } from "@/hooks/useUserQueries";
@@ -17,9 +16,11 @@ export interface FilteredMemoStats {
loading: boolean;
}
+export type MemoStatsContext = "home" | "explore" | "archived" | "profile";
+
export interface UseFilteredMemoStatsOptions {
userName?: string;
- context?: MemoExplorerContext;
+ context?: MemoStatsContext;
enabled?: boolean;
}
diff --git a/web/src/hooks/useMemoFilters.ts b/web/src/hooks/useMemoFilters.ts
index d46a2d337..087fe32cd 100644
--- a/web/src/hooks/useMemoFilters.ts
+++ b/web/src/hooks/useMemoFilters.ts
@@ -1,6 +1,7 @@
import { useMemo } from "react";
import { useAuth } from "@/contexts/AuthContext";
-import { useMemoFilterContext } from "@/contexts/MemoFilterContext";
+import { type MemoFilter, useMemoFilterContext } from "@/contexts/MemoFilterContext";
+import { BUILTIN_TASKS_VIEW_FILTER, BUILTIN_TASKS_VIEW_ID, getShortcutId } from "@/lib/memo-views";
import { buildMemoCreatorFilter } from "@/lib/resource-names";
import { Visibility } from "@/types/proto/api/v1/memo_service_pb";
@@ -17,13 +18,26 @@ const getVisibilityName = (visibility: Visibility): string => {
}
};
-const getShortcutId = (name: string): string => {
- const parts = name.split("/");
- return parts.length === 4 ? parts[3] : "";
-};
-
const escapeFilterValue = (value: string): string => JSON.stringify(value);
+const getLocalDayTimestampRange = (value: string): { startTimestamp: number; endTimestamp: number } | undefined => {
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
+ if (!match) return undefined;
+
+ const year = Number(match[1]);
+ const month = Number(match[2]);
+ const day = Number(match[3]);
+ const startDate = new Date(year, month - 1, day);
+ if (startDate.getFullYear() !== year || startDate.getMonth() !== month - 1 || startDate.getDate() !== day) return undefined;
+
+ const endDate = new Date(startDate);
+ endDate.setDate(endDate.getDate() + 1);
+ return {
+ startTimestamp: Math.floor(startDate.getTime() / 1000),
+ endTimestamp: Math.floor(endDate.getTime() / 1000),
+ };
+};
+
export interface UseMemoFiltersOptions {
creatorName?: string;
includeShortcuts?: boolean;
@@ -31,67 +45,91 @@ export interface UseMemoFiltersOptions {
visibilities?: Visibility[];
}
-export const useMemoFilters = (options: UseMemoFiltersOptions = {}): string | undefined => {
- const { creatorName, includeShortcuts = false, includePinned = false, visibilities } = options;
+interface BuildMemoFilterOptions {
+ creatorName?: string;
+ currentShortcut?: string;
+ filters: MemoFilter[];
+ includePinned: boolean;
+ selectedShortcutFilter?: string;
+ visibilities?: Visibility[];
+}
- const { shortcuts } = useAuth();
- const { filters, shortcut: currentShortcut } = useMemoFilterContext();
+export const buildMemoFilter = ({
+ creatorName,
+ currentShortcut,
+ filters,
+ includePinned,
+ selectedShortcutFilter,
+ visibilities,
+}: BuildMemoFilterOptions): string | undefined => {
+ const conditions: string[] = [];
- // Get selected shortcut if needed
- const selectedShortcut = useMemo(() => {
- if (!includeShortcuts) return undefined;
- return shortcuts.find((shortcut) => getShortcutId(shortcut.name) === currentShortcut);
- }, [includeShortcuts, currentShortcut, shortcuts]);
+ if (creatorName) {
+ const creatorFilter = buildMemoCreatorFilter(creatorName);
+ if (creatorFilter) {
+ conditions.push(creatorFilter);
+ }
+ }
- // Build filter
- return useMemo(() => {
- const conditions: string[] = [];
+ if (currentShortcut === BUILTIN_TASKS_VIEW_ID) {
+ conditions.push(BUILTIN_TASKS_VIEW_FILTER);
+ } else if (selectedShortcutFilter) {
+ conditions.push(selectedShortcutFilter);
+ }
- // Add creator filter if provided
- if (creatorName) {
- const creatorFilter = buildMemoCreatorFilter(creatorName);
- if (creatorFilter) {
- conditions.push(creatorFilter);
+ for (const filter of filters) {
+ if (filter.factor === "contentSearch") {
+ conditions.push(`content.contains(${escapeFilterValue(filter.value)})`);
+ } else if (filter.factor === "tagSearch") {
+ conditions.push(`tag in [${escapeFilterValue(filter.value)}]`);
+ } else if (filter.factor === "pinned") {
+ if (includePinned) {
+ conditions.push(`pinned`);
+ }
+ } else if (filter.factor === "property.hasLink") {
+ conditions.push(`has_link`);
+ } else if (filter.factor === "property.hasTaskList") {
+ conditions.push(`has_task_list`);
+ } else if (filter.factor === "property.hasCode") {
+ conditions.push(`has_code`);
+ } else if (filter.factor === "displayTime") {
+ const range = getLocalDayTimestampRange(filter.value);
+ if (range) {
+ conditions.push(`created_ts >= timestamp(${range.startTimestamp}) && created_ts < timestamp(${range.endTimestamp})`);
}
}
+ }
- // Add shortcut filter if enabled and selected
- if (includeShortcuts && selectedShortcut?.filter) {
- conditions.push(selectedShortcut.filter);
- }
+ if (visibilities && visibilities.length > 0) {
+ const visibilityValues = visibilities.map((visibility) => `"${getVisibilityName(visibility)}"`).join(", ");
+ conditions.push(`visibility in [${visibilityValues}]`);
+ }
- // Add active filters from context
- for (const filter of filters) {
- if (filter.factor === "contentSearch") {
- conditions.push(`content.contains(${escapeFilterValue(filter.value)})`);
- } else if (filter.factor === "tagSearch") {
- conditions.push(`tag in [${escapeFilterValue(filter.value)}]`);
- } else if (filter.factor === "pinned") {
- if (includePinned) {
- conditions.push(`pinned`);
- }
- } else if (filter.factor === "property.hasLink") {
- conditions.push(`has_link`);
- } else if (filter.factor === "property.hasTaskList") {
- conditions.push(`has_task_list`);
- } else if (filter.factor === "property.hasCode") {
- conditions.push(`has_code`);
- } else if (filter.factor === "displayTime") {
- const filterDate = new Date(filter.value);
- const filterUtcTimestamp = filterDate.getTime() + filterDate.getTimezoneOffset() * 60 * 1000;
- const startTimestamp = Math.floor(filterUtcTimestamp / 1000);
- const endTimestamp = startTimestamp + 60 * 60 * 24;
-
- conditions.push(`created_ts >= timestamp(${startTimestamp}) && created_ts < timestamp(${endTimestamp})`);
- }
- }
+ return conditions.length > 0 ? conditions.join(" && ") : undefined;
+};
- // Add visibility filter if specified
- if (visibilities && visibilities.length > 0) {
- const visibilityValues = visibilities.map((v) => `"${getVisibilityName(v)}"`).join(", ");
- conditions.push(`visibility in [${visibilityValues}]`);
- }
+export const useMemoFilters = (options: UseMemoFiltersOptions = {}): string | undefined => {
+ const { creatorName, includeShortcuts = false, includePinned = false, visibilities } = options;
+
+ const { shortcuts } = useAuth();
+ const { filters, shortcut: currentShortcut } = useMemoFilterContext();
+
+ // Get selected shortcut if needed
+ const selectedShortcutFilter = useMemo(() => {
+ if (!includeShortcuts || currentShortcut === BUILTIN_TASKS_VIEW_ID) return undefined;
+ return shortcuts.find((shortcut) => getShortcutId(shortcut.name) === currentShortcut)?.filter;
+ }, [includeShortcuts, currentShortcut, shortcuts]);
- return conditions.length > 0 ? conditions.join(" && ") : undefined;
- }, [creatorName, includeShortcuts, includePinned, visibilities, selectedShortcut, filters]);
+ return useMemo(
+ () =>
+ buildMemoFilter({
+ creatorName,
+ currentShortcut: includeShortcuts ? currentShortcut : undefined,
+ filters,
+ includePinned,
+ selectedShortcutFilter,
+ visibilities,
+ }),
+ [creatorName, currentShortcut, filters, includePinned, includeShortcuts, selectedShortcutFilter, visibilities],
+ );
};
diff --git a/web/src/layouts/MainLayout.tsx b/web/src/layouts/MainLayout.tsx
index c7c73bb30..7b9bdd0b0 100644
--- a/web/src/layouts/MainLayout.tsx
+++ b/web/src/layouts/MainLayout.tsx
@@ -1,98 +1,10 @@
-import { useEffect, useMemo, useState } from "react";
-import { matchPath, Outlet, useLocation } from "react-router-dom";
-import type { MemoExplorerContext } from "@/components/MemoExplorer";
-import { MemoExplorer, MemoExplorerDrawer } from "@/components/MemoExplorer";
-import MobileHeader from "@/components/MobileHeader";
-import { userServiceClient } from "@/connect";
-import { useAuth } from "@/contexts/AuthContext";
-import { useInstance } from "@/contexts/InstanceContext";
-import useCurrentUser from "@/hooks/useCurrentUser";
-import { useFilteredMemoStats } from "@/hooks/useFilteredMemoStats";
-import useMediaQuery from "@/hooks/useMediaQuery";
-import { cn } from "@/lib/utils";
-import { Routes } from "@/router";
-
-const ARCHIVED_ROUTE = "/archived";
-const PROFILE_ROUTE = "/u/:username";
-const DESKTOP_EXPLORER_WIDTH_CLASS = "w-64";
-const DESKTOP_EXPLORER_CLASS_NAME = cn("sticky top-0 h-svh shrink-0 border-r border-border transition-all", DESKTOP_EXPLORER_WIDTH_CLASS);
-const MAIN_CONTENT_CLASS_NAME = "w-full min-h-full min-w-0 flex-1";
+import { Outlet } from "react-router-dom";
const MainLayout = () => {
- const md = useMediaQuery("md");
- const { isInitialized: authInitialized } = useAuth();
- const { isInitialized: instanceInitialized } = useInstance();
- const location = useLocation();
- const currentUser = useCurrentUser();
- const [profileUserName, setProfileUserName] = useState<string | undefined>();
- const [mobileExplorerOpen, setMobileExplorerOpen] = useState(false);
- const showMemoExplorer = location.pathname !== Routes.ABOUT;
-
- // Determine context based on current route
- const context: MemoExplorerContext = useMemo(() => {
- if (location.pathname === Routes.HOME) return "home";
- if (location.pathname === Routes.EXPLORE) return "explore";
- if (matchPath(ARCHIVED_ROUTE, location.pathname)) return "archived";
- if (matchPath(PROFILE_ROUTE, location.pathname)) return "profile";
- return "home"; // fallback
- }, [location.pathname]);
-
- // Extract username from URL for profile context
- useEffect(() => {
- const match = matchPath(PROFILE_ROUTE, location.pathname);
- if (match && context === "profile") {
- const username = match.params.username;
- if (username) {
- // Fetch or get user to obtain the canonical user name (e.g., "users/steven")
- // Note: User stats will be fetched by useFilteredMemoStats
- userServiceClient
- .getUser({ name: `users/${username}` })
- .then((user) => {
- setProfileUserName(user.name);
- })
- .catch((error) => {
- console.error("Failed to fetch profile user:", error);
- setProfileUserName(undefined);
- });
- }
- } else {
- setProfileUserName(undefined);
- }
- }, [location.pathname, context]);
-
- // Determine which user name to use for per-user stats.
- // - home: current user's stats
- // - profile: viewed user's stats
- // - archived/explore: no user scope (each handled differently inside the hook)
- const statsUserName = useMemo(() => {
- if (context === "home") return currentUser?.name;
- if (context === "profile") return profileUserName;
- return undefined;
- }, [context, currentUser, profileUserName]);
-
- // The feed query starts as soon as identity/profile routing is ready. Keep
- // auxiliary statistics behind full settings initialization, and do not fetch
- // mobile drawer data until the user actually opens it.
- const statsEnabled = showMemoExplorer && authInitialized && instanceInitialized && (md || mobileExplorerOpen);
- const { statistics, tags } = useFilteredMemoStats({ userName: statsUserName, context, enabled: statsEnabled });
- const memoExplorerProps = { context, statisticsData: statistics, tagCount: tags };
-
return (
- <section className="@container w-full min-h-full flex flex-col justify-start items-center md:flex-row md:items-start">
- {!md && (
- <MobileHeader>
- {showMemoExplorer && <MemoExplorerDrawer {...memoExplorerProps} onOpenChange={setMobileExplorerOpen} />}
- </MobileHeader>
- )}
- {md && showMemoExplorer && (
- <div className={DESKTOP_EXPLORER_CLASS_NAME}>
- <MemoExplorer className="px-3 py-6" {...memoExplorerProps} />
- </div>
- )}
- <div className={MAIN_CONTENT_CLASS_NAME}>
- <div className={cn("w-full mx-auto px-4 sm:px-6 pt-2 md:pt-6 pb-8")}>
- <Outlet />
- </div>
+ <section className="@container flex min-h-full w-full flex-col items-center">
+ <div className="mx-auto w-full px-4 pb-8 pt-3 sm:px-6 md:pt-6">
+ <Outlet />
</div>
</section>
);
diff --git a/web/src/layouts/RootLayout.tsx b/web/src/layouts/RootLayout.tsx
index 1f853ffa5..3e10f5e59 100644
--- a/web/src/layouts/RootLayout.tsx
+++ b/web/src/layouts/RootLayout.tsx
@@ -1,12 +1,12 @@
import { useEffect, useRef } from "react";
import { Navigate, Outlet, useLocation, useSearchParams } from "react-router-dom";
-import Navigation from "@/components/Navigation";
-import { GlobalMemoEditorProvider } from "@/contexts/GlobalMemoEditorContext";
+import AboutDialog from "@/components/AboutDialog";
+import AppSidebar, { MobileAppHeader, MobileAppSidebar, QuickFindDialog } from "@/components/AppSidebar";
+import { AppSidebarProvider, useAppSidebar } from "@/contexts/AppSidebarContext";
import { useInstance } from "@/contexts/InstanceContext";
import { MemoFilterProvider, useMemoFilterContext } from "@/contexts/MemoFilterContext";
import useCurrentUser from "@/hooks/useCurrentUser";
import useMediaQuery from "@/hooks/useMediaQuery";
-import { cn } from "@/lib/utils";
import { buildAuthRoute, shouldGatePrivateInstance } from "@/utils/auth-redirect";
import { useTranslate } from "@/utils/i18n";
@@ -28,11 +28,21 @@ const DemoBanner = () => {
);
};
+const AppDialogs = () => {
+ const { aboutOpen, setAboutOpen } = useAppSidebar();
+ return (
+ <>
+ <QuickFindDialog />
+ <AboutDialog open={aboutOpen} onOpenChange={setAboutOpen} />
+ </>
+ );
+};
+
const RootLayoutContent = () => {
const location = useLocation();
const [searchParams] = useSearchParams();
- const sm = useMediaQuery("sm");
const currentUser = useCurrentUser();
+ const md = useMediaQuery("md");
const { profile } = useInstance();
const { removeFilter } = useMemoFilterContext();
const { pathname } = location;
@@ -58,25 +68,22 @@ const RootLayoutContent = () => {
}
return (
- <GlobalMemoEditorProvider>
- <div className="w-full min-h-full flex flex-row justify-center items-start sm:pl-16">
- {sm && (
- <div
- className={cn(
- "group flex flex-col justify-start items-start fixed top-0 left-0 select-none h-full bg-sidebar",
- "w-16 px-2",
- "border-r border-border",
- )}
- >
- <Navigation className="py-4 md:pt-6" collapsed={true} />
+ <AppSidebarProvider>
+ <div className="min-h-full w-full bg-background">
+ {md && (
+ <div className="fixed inset-y-0 left-0 z-30 w-64 border-r border-border/70">
+ <AppSidebar />
</div>
)}
- <main className="w-full h-auto grow shrink flex flex-col justify-start items-center">
+ <MobileAppSidebar />
+ <main className="flex min-h-full w-full min-w-0 flex-col items-center md:pl-64">
+ <MobileAppHeader />
{profile.demo && <DemoBanner />}
<Outlet />
</main>
+ <AppDialogs />
</div>
- </GlobalMemoEditorProvider>
+ </AppSidebarProvider>
);
};
diff --git a/web/src/lib/memo-views.ts b/web/src/lib/memo-views.ts
new file mode 100644
index 000000000..fc3851066
--- /dev/null
+++ b/web/src/lib/memo-views.ts
@@ -0,0 +1,54 @@
+import { ROUTES } from "@/router/routes";
+
+export type MemoScope = "home" | "explore" | "archived";
+
+export const BUILTIN_TASKS_VIEW_ID = "__built_in_tasks__";
+export const BUILTIN_TASKS_VIEW_FILTER = "has_task_list && has_incomplete_tasks";
+
+export const getShortcutId = (name: string): string => {
+ const parts = name.split("/");
+ return parts.length === 4 ? parts[3] : name;
+};
+
+export const isMemoScopeRoute = (pathname: string): boolean =>
+ pathname === ROUTES.HOME || pathname === ROUTES.EXPLORE || pathname === ROUTES.ARCHIVED;
+
+export const getMemoScopePath = (scope: MemoScope): string => {
+ if (scope === "explore") return ROUTES.EXPLORE;
+ if (scope === "archived") return ROUTES.ARCHIVED;
+ return ROUTES.HOME;
+};
+
+const cleanPathname = (value: string): string => value.split(/[?#]/, 1)[0] || ROUTES.HOME;
+
+interface ResolveMemoScopeOptions {
+ currentUsername?: string;
+ detailFrom?: string;
+ memoArchived?: boolean;
+ fallback?: MemoScope;
+}
+
+export const resolveMemoScope = (pathname: string, options: ResolveMemoScopeOptions = {}): MemoScope => {
+ const cleanPath = cleanPathname(pathname);
+ if (cleanPath === ROUTES.EXPLORE) return "explore";
+ if (cleanPath === ROUTES.ARCHIVED) return "archived";
+ if (cleanPath === ROUTES.HOME) return "home";
+
+ const profileMatch = cleanPath.match(/^\/u\/([^/]+)$/);
+ if (profileMatch) {
+ return options.currentUsername && decodeURIComponent(profileMatch[1]) === options.currentUsername ? "home" : "explore";
+ }
+
+ if (cleanPath.startsWith("/memos/") && options.detailFrom) {
+ return resolveMemoScope(options.detailFrom, {
+ currentUsername: options.currentUsername,
+ fallback: options.fallback,
+ });
+ }
+
+ if (cleanPath.startsWith("/memos/") && options.memoArchived) {
+ return "archived";
+ }
+
+ return options.fallback ?? "home";
+};
diff --git a/web/src/locales/en.json b/web/src/locales/en.json
index a71566e86..bef1e0aae 100644
--- a/web/src/locales/en.json
+++ b/web/src/locales/en.json
@@ -1,17 +1,25 @@
{
"about": {
+ "api-docs": "API Docs",
+ "api-docs-note": "REST and gRPC reference",
"blogs": "Blogs",
"build": "Build",
"commit": "Commit",
+ "demo": "Demo",
"description": "A privacy-first, lightweight note-taking service. Easily capture and share your great thoughts.",
"distribution": "Distribution",
"documents": "Documents",
+ "documents-note": "Deploy, configure, and use Memos",
+ "github-repository": "GitHub Repo",
+ "github-repository-note": "Source, issues, and releases",
"license": "License",
"media": "Media",
- "github-repository": "GitHub Repo",
"official-website": "Official Website",
+ "official-website-note": "The project homepage",
"powered-by": "Powered by Memos",
"project": "Project",
+ "project-links": "Project links",
+ "web-clipper": "Web Clipper",
"web-clipper-platforms": "Chrome + Firefox"
},
"auth": {
@@ -51,6 +59,7 @@
"retry": "Retry"
},
"empty": {
+ "all": "No attachments yet.",
"audio": "No audio attachments yet.",
"documents": "No document attachments yet.",
"media": "No media attachments yet."
@@ -79,6 +88,7 @@
},
"common": {
"about": "About",
+ "actions": "Actions",
"add": "Add",
"admin": "Admin",
"all": "All",
@@ -134,15 +144,18 @@
"mark": "Mark",
"memo": "Memo",
"memos": "Memos",
+ "month-navigation": "Month navigation",
"more": "More",
"name": "Name",
"new": "New",
+ "next-month": "Next month",
"nickname": "Nickname",
"null": "Null",
"or": "or",
"password": "Password",
"pin": "Pin",
"pinned": "Pinned",
+ "previous-month": "Previous month",
"preview": "Preview",
"profile": "Profile",
"properties": "Properties",
@@ -163,10 +176,12 @@
"shortcut-filter": "Shortcut filter",
"shortcuts": "Shortcuts",
"sign-in": "Sign in",
+ "sign-in-to-memos": "Sign in to Memos",
"sign-out": "Sign out",
"sign-up": "Sign up",
"statistics": "Statistics",
"tags": "Tags",
+ "tasks": "Tasks",
"title": "Title",
"today": "Today",
"tree-mode": "Tree mode",
@@ -179,6 +194,7 @@
"username": "Username",
"version": "Version",
"visibility": "Visibility",
+ "views": "Views",
"yourself": "Yourself"
},
"locale-picker": {
diff --git a/web/src/locales/zh-Hans.json b/web/src/locales/zh-Hans.json
index a8c97d9eb..85ca0b66a 100644
--- a/web/src/locales/zh-Hans.json
+++ b/web/src/locales/zh-Hans.json
@@ -1,11 +1,26 @@
{
"about": {
+ "api-docs": "API 文档",
+ "api-docs-note": "REST 与 gRPC 参考",
"blogs": "博客",
+ "build": "构建信息",
+ "commit": "提交",
+ "demo": "演示",
"description": "Memos 是一个隐私优先、轻量级的笔记解决方案,可以轻松捕捉和分享您的想法。",
+ "distribution": "发行版本",
"documents": "文档",
+ "documents-note": "部署、配置和使用 Memos",
"github-repository": "GitHub 仓库",
+ "github-repository-note": "源代码、问题与版本发布",
+ "license": "许可证",
"official-website": "官网",
- "media": "媒体"
+ "official-website-note": "项目主页",
+ "media": "媒体",
+ "powered-by": "由 Memos 提供支持",
+ "project": "项目",
+ "project-links": "项目链接",
+ "web-clipper": "网页剪藏器",
+ "web-clipper-platforms": "Chrome + Firefox"
},
"auth": {
"admin-sign-in": "管理员登录",
@@ -40,6 +55,7 @@
},
"common": {
"about": "关于",
+ "actions": "操作",
"add": "增加",
"admin": "管理",
"all": "全部",
@@ -93,15 +109,18 @@
"mark": "引用",
"memo": "备忘录",
"memos": "备忘录",
+ "month-navigation": "月份导航",
"more": "更多",
"name": "名称",
"new": "新建",
+ "next-month": "下个月",
"nickname": "昵称",
"null": "空",
"or": "或者",
"password": "密码",
"pin": "置顶",
"pinned": "已置顶",
+ "previous-month": "上个月",
"preview": "预览",
"profile": "个人资料",
"properties": "属性",
@@ -122,10 +141,12 @@
"shortcut-filter": "捷径过滤器",
"shortcuts": "捷径",
"sign-in": "登录",
+ "sign-in-to-memos": "登录 Memos",
"sign-out": "退出登录",
"sign-up": "注册",
"statistics": "统计",
"tags": "标签",
+ "tasks": "任务",
"title": "标题",
"today": "今天",
"tree-mode": "树模式",
@@ -138,6 +159,7 @@
"username": "用户名",
"version": "版本",
"visibility": "可见性",
+ "views": "视图",
"yourself": "您自己"
},
"locale-picker": {
@@ -849,6 +871,7 @@
"retry": "重试"
},
"empty": {
+ "all": "暂无附件",
"audio": "暂无音频附件",
"documents": "暂无文档附件",
"media": "暂无媒体附件"
diff --git a/web/src/locales/zh-Hant.json b/web/src/locales/zh-Hant.json
index 2c5297d06..4a7f23699 100644
--- a/web/src/locales/zh-Hant.json
+++ b/web/src/locales/zh-Hant.json
@@ -1,11 +1,26 @@
{
"about": {
+ "api-docs": "API 文件",
+ "api-docs-note": "REST 與 gRPC 參考",
"blogs": "部落格",
+ "build": "建置資訊",
+ "commit": "提交",
+ "demo": "示範",
"description": "以隱私為核心的輕量化筆記服務,輕鬆記錄並分享您的好點子。",
+ "distribution": "發行版本",
"documents": "文件",
- "media": "媒體",
+ "documents-note": "部署、設定及使用 Memos",
"github-repository": "GitHub 儲存庫",
- "official-website": "官方網站"
+ "github-repository-note": "原始碼、問題與版本發佈",
+ "license": "授權條款",
+ "media": "媒體",
+ "official-website": "官方網站",
+ "official-website-note": "專案首頁",
+ "powered-by": "由 Memos 提供支援",
+ "project": "專案",
+ "project-links": "專案連結",
+ "web-clipper": "網頁剪藏器",
+ "web-clipper-platforms": "Chrome + Firefox"
},
"auth": {
"create-your-account": "建立您的帳號",
@@ -27,6 +42,7 @@
"retry": "重試"
},
"empty": {
+ "all": "尚無附件。",
"audio": "尚無音訊附件。",
"documents": "尚無文件附件。",
"media": "尚無媒體附件。"
@@ -55,6 +71,7 @@
},
"common": {
"about": "關於",
+ "actions": "操作",
"add": "新增",
"admin": "管理",
"all": "所有",
@@ -108,15 +125,18 @@
"mark": "標記",
"memo": "備忘錄",
"memos": "備忘錄",
+ "month-navigation": "月份導覽",
"more": "更多",
"name": "名稱",
"new": "新增",
+ "next-month": "下個月",
"nickname": "暱稱",
"null": "空",
"or": "或",
"password": "密碼",
"pin": "置頂",
"pinned": "已置頂",
+ "previous-month": "上個月",
"preview": "預覽",
"profile": "個人檔案",
"properties": "屬性",
@@ -137,11 +157,13 @@
"shortcut-filter": "篩選條件表達式",
"shortcuts": "快捷篩選",
"sign-in": "登入",
+ "sign-in-to-memos": "登入 Memos",
"sign-in-with": "使用 {{provider}} 登入",
"sign-out": "登出",
"sign-up": "註冊",
"statistics": "統計",
"tags": "標籤",
+ "tasks": "任務",
"title": "標題",
"today": "今天",
"tree-mode": "樹狀顯示",
@@ -154,6 +176,7 @@
"username": "帳號",
"version": "版本",
"visibility": "瀏覽權限",
+ "views": "檢視",
"yourself": "您自己"
},
"locale-picker": {
diff --git a/web/src/pages/About.tsx b/web/src/pages/About.tsx
index e06b0e0f0..c586df60c 100644
--- a/web/src/pages/About.tsx
+++ b/web/src/pages/About.tsx
@@ -1,132 +1,22 @@
-import { ExternalLinkIcon, ScissorsIcon } from "lucide-react";
-import { Badge } from "@/components/ui/badge";
-import { useInstance } from "@/contexts/InstanceContext";
-import { WEB_CLIPPER_URL } from "@/lib/constants";
-import { useTranslate } from "@/utils/i18n";
-
-const GITHUB_COMMIT_URL_PREFIX = "https://github.com/usememos/memos/commit/";
-const GITHUB_RELEASE_URL_PREFIX = "https://github.com/usememos/memos/releases/tag/v";
-
-const DEFAULT_TITLE = "Memos";
-const DEFAULT_TAGLINE = "Capture first. Keep it yours.";
-const DEFAULT_LOGO = "/logo.webp";
-
-const isCommitSha = (commit: string) => /^[0-9a-f]{7,40}$/i.test(commit);
-const isSemver = (version: string) => /^\d+\.\d+\.\d+/.test(version);
-
-const Chip = ({ href, children }: { href?: string; children: React.ReactNode }) => {
- const className = "inline-flex items-center rounded-full bg-muted px-2.5 py-0.5 font-mono text-xs text-muted-foreground";
- if (href) {
- return (
- <a className={`${className} hover:bg-accent hover:text-foreground`} href={href} target="_blank" rel="noreferrer">
- {children}
- </a>
- );
- }
- return <span className={className}>{children}</span>;
-};
-
-const SectionLabel = ({ children }: { children: React.ReactNode }) => (
- <h2 className="text-[11px] font-medium uppercase tracking-[0.08em] text-muted-foreground/55">{children}</h2>
-);
+import { useEffect } from "react";
+import { Navigate } from "react-router-dom";
+import { useAppSidebar } from "@/contexts/AppSidebarContext";
+import { useAuth } from "@/contexts/AuthContext";
+import useCurrentUser from "@/hooks/useCurrentUser";
+import { ROUTES } from "@/router/routes";
const About = () => {
- const t = useTranslate();
- const { profile, generalSetting } = useInstance();
-
- // Instance identity: custom branding when the admin has set it, Memos defaults otherwise.
- const customProfile = generalSetting.customProfile;
- const instanceTitle = customProfile?.title || DEFAULT_TITLE;
- const instanceTagline = customProfile?.description || DEFAULT_TAGLINE;
- const instanceLogo = customProfile?.logoUrl || DEFAULT_LOGO;
- const isCustomBranded = instanceTitle !== DEFAULT_TITLE;
-
- // Dev builds report version "dev" and commit "unknown"; show the raw version and skip the commit row.
- const hasSemver = isSemver(profile.version);
- const releaseUrl = hasSemver ? `${GITHUB_RELEASE_URL_PREFIX}${profile.version}` : "";
- const versionLabel = hasSemver ? `v${profile.version}` : profile.version;
- const hasCommitSha = isCommitSha(profile.commit);
- const commitUrl = hasCommitSha ? `${GITHUB_COMMIT_URL_PREFIX}${profile.commit}` : "";
- const shortCommit = hasCommitSha ? profile.commit.slice(0, 7) : "";
-
- const buildRows: { label: string; value: React.ReactNode }[] = [];
- if (profile.version) {
- buildRows.push({ label: t("common.version"), value: <Chip href={releaseUrl || undefined}>{versionLabel}</Chip> });
- }
- if (shortCommit) {
- buildRows.push({ label: t("about.commit"), value: <Chip href={commitUrl}>{shortCommit}</Chip> });
- }
- buildRows.push({ label: t("about.license"), value: <Chip href="https://github.com/usememos/memos/blob/main/LICENSE">MIT</Chip> });
- if (isCustomBranded) {
- buildRows.push({
- label: t("about.distribution"),
- value: <span className="text-[13px] text-muted-foreground">{t("about.powered-by")}</span>,
- });
- }
-
- const projectLinks = [
- { label: t("about.official-website"), note: "the project homepage", href: "https://usememos.com/" },
- { label: t("about.documents"), note: "deploy, configure, use", href: "https://usememos.com/docs" },
- { label: "API Docs", note: "REST + gRPC reference", href: "https://usememos.com/docs/api" },
- { label: t("about.github-repository"), note: "source, issues, releases", href: "https://github.com/usememos/memos" },
- { label: "Web Clipper", note: t("about.web-clipper-platforms"), href: WEB_CLIPPER_URL, icon: ScissorsIcon },
- ];
-
- return (
- <section className="mx-auto w-full max-w-5xl min-h-full flex flex-col justify-start items-start sm:pt-3 md:pt-6 pb-8">
- <div className="mx-auto w-full max-w-2xl px-1 py-6 sm:py-8">
- <header>
- <img className="size-10 shrink-0 select-none rounded-md" src={instanceLogo} alt="" draggable={false} />
- <div className="mt-4 flex flex-wrap items-center gap-2">
- <h1 className="text-lg font-semibold tracking-tight text-foreground">{instanceTitle}</h1>
- {profile.demo && <Badge variant="warning">Demo</Badge>}
- </div>
- <p className="mt-1 max-w-md text-[26px] font-light leading-snug tracking-[-0.015em] text-foreground">{instanceTagline}</p>
- </header>
+ const currentUser = useCurrentUser();
+ const { setAboutOpen } = useAppSidebar();
+ const { isInitialized } = useAuth();
- <section className="mt-9">
- <SectionLabel>{t("about.build")}</SectionLabel>
- <dl className="mt-2.5 border-t border-border">
- {buildRows.map((row) => (
- <div key={row.label} className="grid grid-cols-[110px_1fr] items-center border-b border-border/60 py-2">
- <dt className="text-[13px] text-muted-foreground">{row.label}</dt>
- <dd className="m-0 flex min-w-0 items-center">{row.value}</dd>
- </div>
- ))}
- </dl>
- </section>
+ useEffect(() => {
+ if (isInitialized) setAboutOpen(true);
+ }, [isInitialized, setAboutOpen]);
- <section className="mt-9">
- <SectionLabel>{t("about.project")}</SectionLabel>
- <nav aria-label="Project links" className="mt-2.5 border-t border-border">
- {projectLinks.map((link) => (
- <a
- key={link.href}
- className="group flex items-baseline justify-between gap-4 border-b border-border/60 py-2.5"
- href={link.href}
- target="_blank"
- rel="noreferrer"
- >
- <span className="flex min-w-0 items-baseline gap-2">
- {link.icon && <link.icon className="size-3.5 shrink-0 translate-y-0.5 text-muted-foreground" />}
- <span className="text-[13px] font-medium text-foreground group-hover:underline group-hover:underline-offset-2">
- {link.label}
- </span>
- <span className="hidden truncate text-xs text-muted-foreground sm:inline">{link.note}</span>
- </span>
- <span className="inline-flex shrink-0 items-center gap-1 font-mono text-xs text-muted-foreground group-hover:text-foreground">
- {link.href.replace("https://", "")}
- <ExternalLinkIcon className="size-3" />
- </span>
- </a>
- ))}
- </nav>
- </section>
+ if (!isInitialized) return null;
- <p className="mt-8 text-xs text-muted-foreground">Free and open source under the MIT license.</p>
- </div>
- </section>
- );
+ return <Navigate to={currentUser ? ROUTES.HOME : ROUTES.EXPLORE} replace />;
};
export default About;
diff --git a/web/src/pages/Archived.tsx b/web/src/pages/Archived.tsx
index 28046135f..52941c8e1 100644
--- a/web/src/pages/Archived.tsx
+++ b/web/src/pages/Archived.tsx
@@ -8,10 +8,9 @@ import { Memo } from "@/types/proto/api/v1/memo_service_pb";
const Archived = () => {
const user = useCurrentUser();
- // Build filter using unified hook (no shortcuts or pinned filter)
const memoFilter = useMemoFilters({
creatorName: user?.name,
- includeShortcuts: false,
+ includeShortcuts: true,
includePinned: false,
});
diff --git a/web/src/pages/Attachments.tsx b/web/src/pages/Attachments.tsx
index 1063efdf0..dbb412a74 100644
--- a/web/src/pages/Attachments.tsx
+++ b/web/src/pages/Attachments.tsx
@@ -1,6 +1,6 @@
import { create } from "@bufbuild/protobuf";
-import { LoaderCircleIcon } from "lucide-react";
-import { useEffect, useMemo, useState } from "react";
+import { LoaderCircleIcon, Trash2Icon } from "lucide-react";
+import { useState } from "react";
import { toast } from "react-hot-toast";
import {
AttachmentAudioRows,
@@ -8,20 +8,17 @@ import {
AttachmentLibraryEmptyState,
AttachmentLibraryErrorState,
AttachmentLibrarySkeletonGrid,
- AttachmentLibraryToolbar,
- AttachmentLibraryUnusedPanel,
AttachmentMediaGrid,
AttachmentUnusedRows,
} from "@/components/AttachmentLibrary";
import ConfirmDialog from "@/components/ConfirmDialog";
-import MobileHeader from "@/components/MobileHeader";
import PreviewImageDialog from "@/components/PreviewImageDialog";
import { Button } from "@/components/ui/button";
import { attachmentServiceClient } from "@/connect";
-import { type AttachmentLibraryStats, type AttachmentLibraryTab, useAttachmentLibrary } from "@/hooks/useAttachmentLibrary";
+import { useAppSidebar } from "@/contexts/AppSidebarContext";
+import { useAttachmentLibrary, useUnusedAttachmentLibrary } from "@/hooks/useAttachmentLibrary";
import { useBatchDeleteAttachments } from "@/hooks/useAttachmentQueries";
import useDialog from "@/hooks/useDialog";
-import useMediaQuery from "@/hooks/useMediaQuery";
import i18n from "@/i18n";
import { handleError } from "@/lib/error";
import { ListAttachmentsRequestSchema } from "@/types/proto/api/v1/attachment_service_pb";
@@ -30,12 +27,6 @@ import { useTranslate } from "@/utils/i18n";
const UNUSED_PAGE_SIZE = 1000;
const BATCH_DELETE_SIZE = 100;
-const TAB_COUNT_SELECTOR = {
- audio: (stats: AttachmentLibraryStats) => stats.audio,
- documents: (stats: AttachmentLibraryStats) => stats.documents,
- media: (stats: AttachmentLibraryStats) => stats.media,
-} as const;
-
const chunkNames = (names: string[], size: number) => {
const chunks: string[][] = [];
@@ -68,11 +59,9 @@ const listUnusedAttachmentNames = async () => {
const Attachments = () => {
const t = useTranslate();
- const md = useMediaQuery("md");
const deleteUnusedAttachmentsDialog = useDialog();
- const [activeTab, setActiveTab] = useState<AttachmentLibraryTab>("media");
+ const { attachmentSection } = useAppSidebar();
const [previewState, setPreviewState] = useState({ open: false, initialIndex: 0 });
- const [showUnusedSection, setShowUnusedSection] = useState(false);
const { mutateAsync: batchDeleteAttachments, isPending: isDeletingUnused } = useBatchDeleteAttachments();
const {
audioItems,
@@ -88,16 +77,15 @@ const Attachments = () => {
mediaPreviewItems,
refetch,
stats,
- unusedItems,
} = useAttachmentLibrary(i18n.language);
-
- const currentItemsCount = useMemo(() => TAB_COUNT_SELECTOR[activeTab](stats), [activeTab, stats]);
-
- useEffect(() => {
- if (stats.unused === 0) {
- setShowUnusedSection(false);
- }
- }, [stats.unused]);
+ const {
+ error: unusedError,
+ isComplete: unusedIsComplete,
+ isError: unusedIsError,
+ isLoading: unusedIsLoading,
+ refetch: refetchUnused,
+ unusedItems: completeUnusedItems,
+ } = useUnusedAttachmentLibrary(i18n.language, attachmentSection === "unused");
const handlePreview = (itemId: string) => {
const initialIndex = mediaPreviewItems.findIndex((item) => item.id === itemId);
@@ -109,7 +97,7 @@ const Attachments = () => {
const names = await listUnusedAttachmentNames();
if (names.length === 0) {
- await refetch();
+ await Promise.all([refetch(), refetchUnused()]);
return;
}
@@ -118,7 +106,7 @@ const Attachments = () => {
}
toast.success(t("resource.delete-all-unused-success"));
- await refetch();
+ await Promise.all([refetch(), refetchUnused()]);
} catch (deleteError) {
handleError(deleteError, toast.error, {
context: "Failed to delete unused attachments",
@@ -128,6 +116,41 @@ const Attachments = () => {
};
const renderContent = () => {
+ if (attachmentSection === "unused") {
+ if (unusedIsError) {
+ return (
+ <AttachmentLibraryErrorState error={unusedError instanceof Error ? unusedError : undefined} onRetry={() => refetchUnused()} />
+ );
+ }
+
+ if (unusedIsLoading || !unusedIsComplete) {
+ return <AttachmentLibrarySkeletonGrid />;
+ }
+
+ return completeUnusedItems.length === 0 ? (
+ <div className="py-12 text-center text-sm text-muted-foreground">{t("message.no-data")}</div>
+ ) : (
+ <div className="space-y-4">
+ <div className="flex flex-col gap-3 rounded-xl border border-warning/30 bg-warning/5 p-4 sm:flex-row sm:items-center sm:justify-between">
+ <div>
+ <h2 className="text-sm font-medium text-foreground">{t("attachment-library.unused.title")}</h2>
+ <p className="mt-1 text-sm text-muted-foreground">{t("attachment-library.unused.description")}</p>
+ </div>
+ <Button
+ variant="destructive"
+ className="shrink-0"
+ onClick={() => deleteUnusedAttachmentsDialog.open()}
+ disabled={isDeletingUnused}
+ >
+ {isDeletingUnused ? <LoaderCircleIcon className="size-4 animate-spin" /> : <Trash2Icon className="size-4" />}
+ {t("resource.delete-all-unused")}
+ </Button>
+ </div>
+ <AttachmentUnusedRows items={completeUnusedItems} />
+ </div>
+ );
+ }
+
if (isLoading) {
return <AttachmentLibrarySkeletonGrid />;
}
@@ -136,19 +159,45 @@ const Attachments = () => {
return <AttachmentLibraryErrorState error={error instanceof Error ? error : undefined} onRetry={() => refetch()} />;
}
- if (currentItemsCount === 0) {
- return <AttachmentLibraryEmptyState tab={activeTab} />;
+ if (attachmentSection === "all") {
+ const total = stats.media + stats.documents + stats.audio;
+ if (total === 0) return <div className="py-16 text-center text-sm text-muted-foreground">{t("attachment-library.empty.all")}</div>;
+ return (
+ <div className="space-y-9">
+ {stats.media > 0 && (
+ <section className="space-y-3">
+ <h2 className="text-sm font-medium text-foreground">{t("attachment-library.tabs.media")}</h2>
+ <AttachmentMediaGrid groups={mediaGroups} onPreview={handlePreview} />
+ </section>
+ )}
+ {stats.documents > 0 && (
+ <section className="space-y-3">
+ <h2 className="text-sm font-medium text-foreground">{t("attachment-library.tabs.documents")}</h2>
+ <AttachmentDocumentRows items={documentItems} />
+ </section>
+ )}
+ {stats.audio > 0 && (
+ <section className="space-y-3">
+ <h2 className="text-sm font-medium text-foreground">{t("attachment-library.tabs.audio")}</h2>
+ <AttachmentAudioRows items={audioItems} />
+ </section>
+ )}
+ </div>
+ );
}
- if (activeTab === "media") {
+ if (attachmentSection === "media") {
+ if (stats.media === 0) return <AttachmentLibraryEmptyState tab="media" />;
return <AttachmentMediaGrid groups={mediaGroups} onPreview={handlePreview} />;
}
- if (activeTab === "documents") {
+ if (attachmentSection === "documents") {
+ if (stats.documents === 0) return <AttachmentLibraryEmptyState tab="documents" />;
return <AttachmentDocumentRows items={documentItems} />;
}
- if (activeTab === "audio") {
+ if (attachmentSection === "audio") {
+ if (stats.audio === 0) return <AttachmentLibraryEmptyState tab="audio" />;
return <AttachmentAudioRows items={audioItems} />;
}
@@ -156,26 +205,12 @@ const Attachments = () => {
};
return (
- <section className="@container w-full min-h-full pb-10 sm:pt-3 md:pt-6">
- {!md && <MobileHeader />}
-
+ <section className="@container min-h-full w-full pb-10 pt-3 md:pt-6">
<div className="mx-auto flex w-full max-w-7xl flex-col gap-5 px-4 sm:gap-6 sm:px-6">
- <AttachmentLibraryToolbar activeTab={activeTab} onTabChange={setActiveTab} stats={stats} />
-
- {stats.unused > 0 && (
- <AttachmentLibraryUnusedPanel
- count={stats.unused}
- isDeleting={isDeletingUnused}
- isExpanded={showUnusedSection}
- onDelete={() => deleteUnusedAttachmentsDialog.open()}
- onToggle={() => setShowUnusedSection((state) => !state)}
- />
- )}
-
<div className="min-h-[16rem] pt-1">
{renderContent()}
- {hasNextPage && (
+ {attachmentSection !== "unused" && hasNextPage && (
<div className="mt-6 flex justify-center">
<Button variant="outline" className="rounded-full px-4" onClick={() => fetchNextPage()} disabled={isFetchingNextPage}>
{isFetchingNextPage ? <LoaderCircleIcon className="h-4 w-4 animate-spin" /> : null}
@@ -188,13 +223,6 @@ const Attachments = () => {
<div className="mt-4 text-center text-xs text-muted-foreground">{t("resource.fetching-data")}</div>
)}
</div>
-
- {showUnusedSection && stats.unused > 0 && (
- <div className="space-y-4 pt-1">
- <div className="text-sm font-medium text-foreground">{t("attachment-library.unused.title")}</div>
- <AttachmentUnusedRows items={unusedItems} />
- </div>
- )}
</div>
<ConfirmDialog
diff --git a/web/src/pages/Explore.tsx b/web/src/pages/Explore.tsx
index 0c927a6ca..3300505e1 100644
--- a/web/src/pages/Explore.tsx
+++ b/web/src/pages/Explore.tsx
@@ -14,9 +14,8 @@ const Explore = () => {
// Note: The backend is responsible for filtering stats based on visibility permissions.
const visibilities = currentUser ? [Visibility.PUBLIC, Visibility.PROTECTED] : [Visibility.PUBLIC];
- // Build filter using unified hook (no creator scoping for Explore)
const memoFilter = useMemoFilters({
- includeShortcuts: false,
+ includeShortcuts: true,
includePinned: false,
visibilities,
});
diff --git a/web/src/pages/Inboxes.tsx b/web/src/pages/Inboxes.tsx
index 6be94f8f0..3baff805b 100644
--- a/web/src/pages/Inboxes.tsx
+++ b/web/src/pages/Inboxes.tsx
@@ -1,21 +1,17 @@
import { timestampDate } from "@bufbuild/protobuf/wkt";
import { sortBy } from "lodash-es";
-import { ArchiveIcon, BellIcon, InboxIcon } from "lucide-react";
-import { useState } from "react";
+import { BellIcon } from "lucide-react";
import MemoCommentMessage from "@/components/Inbox/MemoCommentMessage";
import MemoMentionMessage from "@/components/Inbox/MemoMentionMessage";
-import MobileHeader from "@/components/MobileHeader";
import Placeholder from "@/components/Placeholder";
-import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
-import useMediaQuery from "@/hooks/useMediaQuery";
+import { useAppSidebar } from "@/contexts/AppSidebarContext";
import { useNotifications } from "@/hooks/useUserQueries";
import { UserNotification, UserNotification_Status, UserNotification_Type } from "@/types/proto/api/v1/user_service_pb";
import { useTranslate } from "@/utils/i18n";
const Inboxes = () => {
const t = useTranslate();
- const md = useMediaQuery("md");
- const [filter, setFilter] = useState<"all" | "unread" | "archived">("all");
+ const { inboxFilter: filter } = useAppSidebar();
// Fetch notifications with React Query
const { data: fetchedNotifications = [] } = useNotifications();
@@ -31,11 +27,8 @@ const Inboxes = () => {
});
const unreadCount = allNotifications.filter((n) => n.status === UserNotification_Status.UNREAD).length;
- const archivedCount = allNotifications.filter((n) => n.status === UserNotification_Status.ARCHIVED).length;
-
return (
<section className="@container w-full max-w-5xl min-h-full flex flex-col justify-start items-center sm:pt-3 md:pt-6 pb-8">
- {!md && <MobileHeader />}
<div className="w-full px-4 sm:px-6">
<div className="w-full border border-border flex flex-col justify-start items-start rounded-xl bg-background text-foreground overflow-hidden">
{/* Header */}
@@ -53,25 +46,6 @@ const Inboxes = () => {
</div>
</div>
- {/* Filter Tabs */}
- <div className="w-full px-4 py-2 border-b border-border bg-muted/30">
- <Tabs value={filter} onValueChange={(value) => setFilter(value as typeof filter)} variant="segmented">
- <TabsList>
- <TabsTrigger value="all">
- {t("common.all")} ({allNotifications.length})
- </TabsTrigger>
- <TabsTrigger value="unread">
- <InboxIcon className="w-3.5 h-auto" />
- {t("inbox.unread")} ({unreadCount})
- </TabsTrigger>
- <TabsTrigger value="archived">
- <ArchiveIcon className="w-3.5 h-auto" />
- {t("common.archived")} ({archivedCount})
- </TabsTrigger>
- </TabsList>
- </Tabs>
- </div>
-
{/* Notifications List */}
<div className="w-full">
{notifications.length === 0 ? (
diff --git a/web/src/pages/MemoDetail.tsx b/web/src/pages/MemoDetail.tsx
index b79fb2246..ea1532439 100644
--- a/web/src/pages/MemoDetail.tsx
+++ b/web/src/pages/MemoDetail.tsx
@@ -1,30 +1,51 @@
import { Code, ConnectError } from "@connectrpc/connect";
import { ArrowUpLeftFromCircleIcon } from "lucide-react";
-import { useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo as useReactMemo, useRef, useState } from "react";
import { Link, Navigate, useLocation, useParams } from "react-router-dom";
import MemoCommentSection from "@/components/MemoCommentSection";
import { MentionResolutionProvider } from "@/components/MemoContent/MentionResolutionContext";
-import { MemoDetailSidebar, MemoDetailSidebarDrawer } from "@/components/MemoDetailSidebar";
import MemoView from "@/components/MemoView";
-import MobileHeader from "@/components/MobileHeader";
+import { useAppSidebar } from "@/contexts/AppSidebarContext";
import { useAuth } from "@/contexts/AuthContext";
import { useInstance } from "@/contexts/InstanceContext";
-import useMediaQuery from "@/hooks/useMediaQuery";
import useMemoDetailError from "@/hooks/useMemoDetailError";
import { useInfiniteMemoComments, useMemo } from "@/hooks/useMemoQueries";
import { useSharedMemo, withShareAttachmentLinks } from "@/hooks/useMemoShareQueries";
import { memoNamePrefix } from "@/lib/resource-names";
-import { cn } from "@/lib/utils";
import type { Attachment } from "@/types/proto/api/v1/attachment_service_pb";
+import type { Memo } from "@/types/proto/api/v1/memo_service_pb";
+
+const MemoSidebarRegistration = ({
+ memo,
+ from,
+ readonly,
+ onShareImageOpen,
+}: {
+ memo: Memo;
+ from?: string;
+ readonly: boolean;
+ onShareImageOpen: () => void;
+}) => {
+ const { setMemoDetail } = useAppSidebar();
+
+ useEffect(() => {
+ setMemoDetail({ memo, from, readonly, onShareImageOpen });
+ }, [from, memo, onShareImageOpen, readonly, setMemoDetail]);
+
+ useEffect(() => () => setMemoDetail(undefined), [setMemoDetail]);
+
+ return null;
+};
const MemoDetail = () => {
- const md = useMediaQuery("md");
const { isInitialized: authInitialized } = useAuth();
const { isInitialized: instanceInitialized } = useInstance();
const [shareImageDialogOpen, setShareImageDialogOpen] = useState(false);
const params = useParams();
const location = useLocation();
const { state: locationState, hash } = location;
+ const parentPage = typeof locationState?.from === "string" ? locationState.from : undefined;
+ const handleShareImageOpen = useCallback(() => setShareImageDialogOpen(true), []);
// Detect share mode from the route parameter.
const shareToken = params.token;
@@ -43,6 +64,11 @@ const MemoDetail = () => {
const error = isShareMode ? shareError : directError;
const isLoading = isShareMode ? shareLoading : directLoading;
const memoName = memo?.name ?? memoNameFromParams;
+ const displayMemo = useReactMemo(() => {
+ if (!memo) return undefined;
+ if (!isShareMode) return memo;
+ return { ...memo, attachments: withShareAttachmentLinks(memo.attachments as Attachment[], shareToken!) };
+ }, [isShareMode, memo, shareToken]);
useMemoDetailError({
error: error as Error | null,
@@ -82,29 +108,19 @@ const MemoDetail = () => {
// Start the permitted requests as soon as routing is unlocked, but do not
// expose content before tag-blur and instance display settings settle.
- if (isLoading || !memo || !authInitialized || !instanceInitialized) {
+ if (isLoading || !memo || !displayMemo || !authInitialized || !instanceInitialized) {
return null;
}
-
- // In share mode, rewrite attachment URLs to include the share token for unauthenticated access.
- const displayMemo = isShareMode
- ? { ...memo, attachments: withShareAttachmentLinks(memo.attachments as Attachment[], shareToken!) }
- : memo;
const mentionResolutionContents = [displayMemo.content, ...comments.map((comment) => comment.content)];
const userResolutionNames = Array.from(
new Set([displayMemo, ...comments].flatMap((item) => [item.creator, ...(item.reactions ?? []).map((reaction) => reaction.creator)])),
);
-
return (
- <section className="@container w-full max-w-5xl min-h-full flex flex-col justify-start items-center sm:pt-3 md:pt-6 pb-8">
- {!md && (
- <MobileHeader>
- <MemoDetailSidebarDrawer memo={displayMemo} onShareImageOpen={() => setShareImageDialogOpen(true)} />
- </MobileHeader>
- )}
+ <section className="@container flex min-h-full w-full flex-col items-center pb-8 pt-3 md:pt-6">
<MentionResolutionProvider contents={mentionResolutionContents} userNames={userResolutionNames}>
- <div className={cn("w-full flex flex-row justify-start items-start px-4 sm:px-6 gap-6")}>
- <div className={cn("w-full md:w-[calc(100%-16.5rem)]")}>
+ <MemoSidebarRegistration memo={displayMemo} from={parentPage} readonly={isShareMode} onShareImageOpen={handleShareImageOpen} />
+ <div className="w-full max-w-2xl px-4 sm:px-6">
+ <div className="w-full">
{!isShareMode && parentMemo && (
<div className="w-auto inline-block mb-2">
<Link
@@ -122,7 +138,7 @@ const MemoDetail = () => {
key={`${displayMemo.name}-${displayMemo.updateTime}`}
memo={displayMemo}
compact={false}
- parentPage={locationState?.from}
+ parentPage={parentPage}
shareImageDialogOpen={shareImageDialogOpen}
showCreator
showVisibility
@@ -133,18 +149,13 @@ const MemoDetail = () => {
<MemoCommentSection
memo={displayMemo}
comments={comments}
- parentPage={locationState?.from}
+ parentPage={parentPage}
hasMoreComments={hasNextComments}
isFetchingMoreComments={isFetchingNextComments}
onLoadMoreComments={fetchNextComments}
/>
)}
</div>
- {md && (
- <div className="sticky top-0 left-0 shrink-0 -mt-6 w-60 h-full">
- <MemoDetailSidebar className="py-6" memo={displayMemo} onShareImageOpen={() => setShareImageDialogOpen(true)} />
- </div>
- )}
</div>
</MentionResolutionProvider>
</section>
diff --git a/web/src/pages/NotFound.tsx b/web/src/pages/NotFound.tsx
index e09dfc2e3..889103f4e 100644
--- a/web/src/pages/NotFound.tsx
+++ b/web/src/pages/NotFound.tsx
@@ -1,9 +1,6 @@
-import MobileHeader from "@/components/MobileHeader";
-
const NotFound = () => {
return (
<section className="@container w-full max-w-5xl min-h-svh flex flex-col justify-start items-center sm:pt-3 md:pt-6 pb-8">
- <MobileHeader />
<div className="w-full px-4 grow flex flex-col justify-center items-center sm:px-6">
<p className="font-medium">{"The page you are looking for can't be found."}</p>
<p className="mt-4 text-[8rem] font-mono text-foreground">404</p>
diff --git a/web/src/pages/PermissionDenied.tsx b/web/src/pages/PermissionDenied.tsx
index 8742d0bd0..da03fef37 100644
--- a/web/src/pages/PermissionDenied.tsx
+++ b/web/src/pages/PermissionDenied.tsx
@@ -1,9 +1,6 @@
-import MobileHeader from "@/components/MobileHeader";
-
const PermissionDenied = () => {
return (
<section className="@container w-full max-w-5xl min-h-svh flex flex-col justify-start items-center sm:pt-3 md:pt-6 pb-8">
- <MobileHeader />
<div className="w-full px-4 grow flex flex-col justify-center items-center sm:px-6">
<p className="font-medium">Permission denied</p>
<p className="mt-4 text-[8rem] font-mono text-foreground">403</p>
diff --git a/web/src/pages/Setting.tsx b/web/src/pages/Setting.tsx
index f5d2e879f..ffc6170e9 100644
--- a/web/src/pages/Setting.tsx
+++ b/web/src/pages/Setting.tsx
@@ -1,27 +1,16 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { useLocation } from "react-router-dom";
-import MobileHeader from "@/components/MobileHeader";
-import SectionChip from "@/components/Settings/SectionChip";
-import SectionMenuItem from "@/components/Settings/SectionMenuItem";
import {
DEFAULT_SETTING_SECTION,
isSettingSectionKey,
SETTINGS_SECTIONS,
- type SettingSectionDefinition,
type SettingSectionKey,
} from "@/components/Settings/settingSections";
import { useInstance } from "@/contexts/InstanceContext";
import useCurrentUser from "@/hooks/useCurrentUser";
-import useMediaQuery from "@/hooks/useMediaQuery";
import { User_Role } from "@/types/proto/api/v1/user_service_pb";
-import { useTranslate } from "@/utils/i18n";
-
-const NAV_GROUP_LABEL_CLASSES = "mb-1 px-2 text-[11px] font-medium uppercase tracking-[0.08em] text-muted-foreground/55 select-none";
const Setting = () => {
- const t = useTranslate();
- const sm = useMediaQuery("sm");
- const md = useMediaQuery("md");
const location = useLocation();
const user = useCurrentUser();
const { fetchSettings } = useInstance();
@@ -31,7 +20,6 @@ const Setting = () => {
const sectionGroups = useMemo(() => {
const visibleSections = SETTINGS_SECTIONS.filter((section) => section.scope === "basic" || isHost);
return {
- basic: visibleSections.filter((section) => section.scope === "basic"),
admin: visibleSections.filter((section) => section.scope === "admin"),
all: visibleSections,
};
@@ -69,59 +57,12 @@ const Setting = () => {
SETTINGS_SECTIONS[0];
const ActiveSection = selectedSectionDefinition.component;
- const renderSectionMenuItems = (sections: SettingSectionDefinition[]) =>
- sections.map((section) => (
- <SectionMenuItem
- key={section.key}
- text={t(section.labelKey)}
- icon={section.icon}
- href={`#${section.key}`}
- isSelected={selectedSection === section.key}
- />
- ));
-
- const renderSectionChips = (sections: SettingSectionDefinition[]) =>
- sections.map((section) => (
- <SectionChip key={section.key} text={t(section.labelKey)} href={`#${section.key}`} isSelected={selectedSection === section.key} />
- ));
-
return (
<section className="w-full min-h-full">
- {!sm && <MobileHeader />}
- <div className="mx-auto flex w-full max-w-6xl flex-row items-start gap-8 px-4 pt-2 pb-12 sm:px-6 sm:pt-4 md:pt-8 lg:gap-10">
- {md && (
- <aside className="sticky top-8 flex w-48 shrink-0 flex-col gap-4">
- <h1 className="px-2 text-base font-semibold tracking-tight text-foreground">{t("common.settings")}</h1>
- <nav className="flex flex-col gap-4">
- <div className="flex flex-col gap-0.5">
- {isHost && <p className={NAV_GROUP_LABEL_CLASSES}>{t("common.basic")}</p>}
- {renderSectionMenuItems(sectionGroups.basic)}
- </div>
- {isHost && (
- <div className="flex flex-col gap-0.5 border-t border-border/60 pt-3">
- <p className={NAV_GROUP_LABEL_CLASSES}>{t("common.admin")}</p>
- {renderSectionMenuItems(sectionGroups.admin)}
- </div>
- )}
- </nav>
- </aside>
- )}
- <main className="min-w-0 flex-1">
- {!md && (
- <header className="mb-5 flex flex-col gap-3">
- <h1 className="text-lg font-semibold tracking-tight text-foreground">{t("common.settings")}</h1>
- <nav
- className="-mx-4 flex items-center gap-1.5 overflow-x-auto px-4 pb-1 sm:-mx-6 sm:px-6 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
- aria-label={t("common.settings")}
- >
- {renderSectionChips(sectionGroups.basic)}
- {isHost && <span className="mx-1 h-4 w-px shrink-0 bg-border" aria-hidden="true" />}
- {isHost && renderSectionChips(sectionGroups.admin)}
- </nav>
- </header>
- )}
+ <div className="mx-auto w-full max-w-4xl px-4 pb-12 pt-4 sm:px-6 md:pt-8">
+ <div className="min-w-0">
<ActiveSection />
- </main>
+ </div>
</div>
</section>
);
diff --git a/web/src/pages/Shortcuts.tsx b/web/src/pages/Shortcuts.tsx
index 794329132..f30eb89c3 100644
--- a/web/src/pages/Shortcuts.tsx
+++ b/web/src/pages/Shortcuts.tsx
@@ -32,6 +32,7 @@ import { useAuth } from "@/contexts/AuthContext";
import useCurrentUser from "@/hooks/useCurrentUser";
import useLoading from "@/hooks/useLoading";
import { handleError } from "@/lib/error";
+import { getShortcutId } from "@/lib/memo-views";
import { cn } from "@/lib/utils";
import { Shortcut, ShortcutSchema } from "@/types/proto/api/v1/shortcut_service_pb";
import { useTranslate } from "@/utils/i18n";
@@ -176,11 +177,6 @@ const filterFields = [
'timestamp("2025-01-01T00:00:00Z")',
];
-const getShortcutId = (name: string): string => {
- const parts = name.split("/");
- return parts.length === 4 ? parts[3] : name;
-};
-
const createEmptyShortcut = () =>
create(ShortcutSchema, {
name: "",
diff --git a/web/src/pages/UserProfile.tsx b/web/src/pages/UserProfile.tsx
index 579fdf179..a8ed206cb 100644
--- a/web/src/pages/UserProfile.tsx
+++ b/web/src/pages/UserProfile.tsx
@@ -1,5 +1,5 @@
import copy from "copy-to-clipboard";
-import { ExternalLinkIcon, LayoutListIcon, MapIcon } from "lucide-react";
+import { ExternalLinkIcon } from "lucide-react";
import { Suspense } from "react";
import { toast } from "react-hot-toast";
import { useParams, useSearchParams } from "react-router-dom";
@@ -7,7 +7,6 @@ import MemoView from "@/components/MemoView";
import PagedMemoList, { getMemoKey } from "@/components/PagedMemoList";
import UserAvatar from "@/components/UserAvatar";
import { Button } from "@/components/ui/button";
-import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useMemoFilters, useMemoSorting } from "@/hooks";
import { useUser } from "@/hooks/useUserQueries";
import { State } from "@/types/proto/api/v1/common_pb";
@@ -49,7 +48,7 @@ const ProfileHeader = ({ user, onCopyProfileLink, shareLabel }: { user: User; on
const UserProfile = () => {
const t = useTranslate();
const username = useParams().username;
- const [searchParams, setSearchParams] = useSearchParams();
+ const [searchParams] = useSearchParams();
const activeTab = (searchParams.get("view") === "map" ? "map" : "memos") as TabView;
const { data: user, isLoading, error } = useUser(`users/${username}`, { enabled: !!username });
@@ -75,13 +74,6 @@ const UserProfile = () => {
toast.success(t("message.copied"));
};
- const toggleTab = (view: TabView) => {
- setSearchParams((prev) => {
- view === "map" ? prev.set("view", "map") : prev.delete("view");
- return prev;
- });
- };
-
if (isLoading) return null;
return (
@@ -90,24 +82,7 @@ const UserProfile = () => {
<>
<ProfileHeader user={user} onCopyProfileLink={handleCopyProfileLink} shareLabel={t("common.share")} />
- <div className="border-b border-border/10 mb-4">
- <div className="mx-auto flex max-w-2xl">
- <Tabs value={activeTab} onValueChange={(value) => toggleTab(value as TabView)} variant="underline">
- <TabsList>
- <TabsTrigger value="memos">
- <LayoutListIcon className="h-4 w-4" />
- {t("common.memos")}
- </TabsTrigger>
- <TabsTrigger value="map">
- <MapIcon className="h-4 w-4" />
- {t("common.map")}
- </TabsTrigger>
- </TabsList>
- </Tabs>
- </div>
- </div>
-
- <div className="flex-1">
+ <div className="mt-4 flex-1">
<div className="mx-auto w-full max-w-2xl">
{activeTab === "memos" ? (
<PagedMemoList
diff --git a/web/src/types/statistics.ts b/web/src/types/statistics.ts
index b8e92dc34..04e4a5ecb 100644
--- a/web/src/types/statistics.ts
+++ b/web/src/types/statistics.ts
@@ -7,8 +7,6 @@ export interface StatisticsViewProps {
export interface MonthNavigatorProps {
visibleMonth: string;
onMonthChange: (month: string) => void;
- activityStats: Record<string, number>;
- timeBasis: MemoTimeBasis;
}
export interface StatisticsData {
diff --git a/web/tests/about-page.test.tsx b/web/tests/about-page.test.tsx
index a0af2ce38..29f5fa529 100644
--- a/web/tests/about-page.test.tsx
+++ b/web/tests/about-page.test.tsx
@@ -1,5 +1,7 @@
-import { render, screen } from "@testing-library/react";
+import { render, screen, waitFor } from "@testing-library/react";
+import { MemoryRouter, Route, Routes } from "react-router-dom";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import AboutDialog from "@/components/AboutDialog";
import About from "@/pages/About";
const mockInstance = {
@@ -12,11 +14,28 @@ const mockInstance = {
},
generalSetting: {} as { customProfile?: { title: string; description: string; logoUrl: string } },
};
+const pageState = vi.hoisted(() => ({
+ authInitialized: false,
+ currentUser: { name: "users/test" } as { name: string } | undefined,
+ setAboutOpen: vi.fn(),
+}));
vi.mock("@/contexts/InstanceContext", () => ({
useInstance: () => mockInstance,
}));
+vi.mock("@/contexts/AppSidebarContext", () => ({
+ useAppSidebar: () => ({ setAboutOpen: pageState.setAboutOpen }),
+}));
+
+vi.mock("@/contexts/AuthContext", () => ({
+ useAuth: () => ({ isInitialized: pageState.authInitialized }),
+}));
+
+vi.mock("@/hooks/useCurrentUser", () => ({
+ default: () => pageState.currentUser,
+}));
+
vi.mock("@/utils/i18n", () => ({
useTranslate: () => (key: string) =>
(
@@ -27,8 +46,13 @@ vi.mock("@/utils/i18n", () => ({
)[key] ?? key,
}));
-describe("<About>", () => {
+const renderAbout = () => render(<AboutDialog open onOpenChange={vi.fn()} />);
+
+describe("<AboutDialog>", () => {
beforeEach(() => {
+ pageState.authInitialized = false;
+ pageState.currentUser = { name: "users/test" };
+ pageState.setAboutOpen.mockReset();
mockInstance.profile = {
version: "0.25.0",
commit: "0123456789abcdef0123456789abcdef01234567",
@@ -44,7 +68,7 @@ describe("<About>", () => {
});
it("renders the identity hero with linked version and commit chips", () => {
- render(<About />);
+ renderAbout();
expect(screen.getByRole("heading", { name: "Memos" })).toBeInTheDocument();
expect(screen.getByText(/Capture first/i)).toBeInTheDocument();
@@ -53,21 +77,21 @@ describe("<About>", () => {
"href",
"https://github.com/usememos/memos/commit/0123456789abcdef0123456789abcdef01234567",
);
- expect(screen.getByText(/MIT license/i)).toBeInTheDocument();
+ expect(screen.getByRole("link", { name: "MIT" })).toHaveAttribute("href", "https://github.com/usememos/memos/blob/main/LICENSE");
});
it("links to the usememos.com homepage, docs, API docs, and GitHub repo", () => {
- render(<About />);
+ renderAbout();
expect(screen.getByRole("link", { name: /about\.official-website/ })).toHaveAttribute("href", "https://usememos.com/");
expect(screen.getByRole("link", { name: /about\.documents/ })).toHaveAttribute("href", "https://usememos.com/docs");
- expect(screen.getByRole("link", { name: /API Docs/ })).toHaveAttribute("href", "https://usememos.com/docs/api");
- expect(screen.getByRole("link", { name: /Web Clipper/ })).toHaveAttribute("href", "https://github.com/usememos/web-clipper");
+ expect(screen.getByRole("link", { name: /about\.api-docs/ })).toHaveAttribute("href", "https://usememos.com/docs/api");
+ expect(screen.getByRole("link", { name: /about\.web-clipper/ })).toHaveAttribute("href", "https://github.com/usememos/web-clipper");
expect(screen.getByRole("link", { name: /about\.github-repository/ })).toHaveAttribute("href", "https://github.com/usememos/memos");
});
it("does not surface the instance URL, administrator, or birds", () => {
- render(<About />);
+ renderAbout();
expect(screen.queryByText("https://notes.example.com")).not.toBeInTheDocument();
expect(screen.queryByText("Administrator")).not.toBeInTheDocument();
@@ -80,7 +104,7 @@ describe("<About>", () => {
mockInstance.profile.version = "dev";
mockInstance.profile.commit = "unknown";
- render(<About />);
+ renderAbout();
expect(screen.getByText("dev")).toBeInTheDocument();
expect(screen.queryByText("vdev")).not.toBeInTheDocument();
@@ -90,9 +114,9 @@ describe("<About>", () => {
it("shows the demo badge on demo instances", () => {
mockInstance.profile.demo = true;
- render(<About />);
+ renderAbout();
- expect(screen.getByText("Demo")).toBeInTheDocument();
+ expect(screen.getByText("about.demo")).toBeInTheDocument();
});
it("uses custom branding for the identity hero and credits Memos", () => {
@@ -100,19 +124,47 @@ describe("<About>", () => {
customProfile: { title: "Team Notes", description: "Our shared scratchpad.", logoUrl: "/custom-logo.png" },
};
- render(<About />);
+ renderAbout();
expect(screen.getByRole("heading", { name: "Team Notes" })).toBeInTheDocument();
expect(screen.getByText("Our shared scratchpad.")).toBeInTheDocument();
expect(screen.getByText("Powered by Memos")).toBeInTheDocument();
});
- it("does not add nested horizontal page padding on mobile", () => {
- const { container } = render(<About />);
+ it("renders in a compact dialog instead of a page surface", () => {
+ renderAbout();
+
+ expect(screen.getByRole("dialog")).toHaveClass("p-0!");
+ expect(screen.getByRole("button", { name: "Close" })).toBeInTheDocument();
+ });
+
+ it("waits for auth initialization before redirecting the compatibility route", async () => {
+ const view = render(
+ <MemoryRouter initialEntries={["/about"]}>
+ <Routes>
+ <Route path="/about" element={<About />} />
+ <Route path="/" element={<div>Home route</div>} />
+ <Route path="/explore" element={<div>Explore route</div>} />
+ </Routes>
+ </MemoryRouter>,
+ );
- const contentWrapper = container.querySelector("section > div");
+ expect(screen.queryByText("Home route")).not.toBeInTheDocument();
+ expect(screen.queryByText("Explore route")).not.toBeInTheDocument();
+ expect(pageState.setAboutOpen).not.toHaveBeenCalled();
+
+ pageState.authInitialized = true;
+ view.rerender(
+ <MemoryRouter initialEntries={["/about"]}>
+ <Routes>
+ <Route path="/about" element={<About />} />
+ <Route path="/" element={<div>Home route</div>} />
+ <Route path="/explore" element={<div>Explore route</div>} />
+ </Routes>
+ </MemoryRouter>,
+ );
- expect(contentWrapper).toHaveClass("w-full");
- expect(contentWrapper).not.toHaveClass("px-4");
+ await waitFor(() => expect(screen.getByText("Home route")).toBeInTheDocument());
+ expect(pageState.setAboutOpen).toHaveBeenCalledWith(true);
});
});
diff --git a/web/tests/app-sidebar-context.test.tsx b/web/tests/app-sidebar-context.test.tsx
new file mode 100644
index 000000000..6904816c1
--- /dev/null
+++ b/web/tests/app-sidebar-context.test.tsx
@@ -0,0 +1,45 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { MemoryRouter, useNavigate } from "react-router-dom";
+import { describe, expect, it } from "vitest";
+import { AppSidebarProvider, useAppSidebar } from "@/contexts/AppSidebarContext";
+
+const Harness = () => {
+ const navigate = useNavigate();
+ const { attachmentSection, setAttachmentSection, inboxFilter, setInboxFilter } = useAppSidebar();
+ return (
+ <div>
+ <output data-testid="attachment-section">{attachmentSection}</output>
+ <output data-testid="inbox-filter">{inboxFilter}</output>
+ <button type="button" onClick={() => setAttachmentSection("media")}>
+ Select media
+ </button>
+ <button type="button" onClick={() => setInboxFilter("unread")}>
+ Select unread
+ </button>
+ <button type="button" onClick={() => navigate("/inbox")}>
+ Change route
+ </button>
+ </div>
+ );
+};
+
+describe("AppSidebarProvider", () => {
+ it("keeps page controls local and resets them after a route change", () => {
+ render(
+ <MemoryRouter initialEntries={["/attachments"]}>
+ <AppSidebarProvider>
+ <Harness />
+ </AppSidebarProvider>
+ </MemoryRouter>,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "Select media" }));
+ fireEvent.click(screen.getByRole("button", { name: "Select unread" }));
+ expect(screen.getByTestId("attachment-section")).toHaveTextContent("media");
+ expect(screen.getByTestId("inbox-filter")).toHaveTextContent("unread");
+
+ fireEvent.click(screen.getByRole("button", { name: "Change route" }));
+ expect(screen.getByTestId("attachment-section")).toHaveTextContent("all");
+ expect(screen.getByTestId("inbox-filter")).toHaveTextContent("all");
+ });
+});
diff --git a/web/tests/app-sidebar-logo.test.tsx b/web/tests/app-sidebar-logo.test.tsx
new file mode 100644
index 000000000..9d23a018a
--- /dev/null
+++ b/web/tests/app-sidebar-logo.test.tsx
@@ -0,0 +1,180 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { MemoryRouter } from "react-router-dom";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import AppSidebar, { MobileAppHeader } from "@/components/AppSidebar";
+
+const authState = vi.hoisted(() => ({ currentUser: { name: "users/test" } as { name: string } | undefined }));
+const sidebarState = vi.hoisted(() => ({ setAboutOpen: vi.fn() }));
+
+vi.mock("@/components/MemosLogo", () => ({
+ default: () => <span>Memos logo</span>,
+}));
+
+vi.mock("@/components/UserMenu", () => ({
+ default: () => <div>User menu</div>,
+}));
+
+vi.mock("@/components/StatisticsView", () => ({
+ default: () => <div>Calendar</div>,
+}));
+
+vi.mock("@/components/AppSidebar/TagsSection", () => ({
+ default: () => <div>Tags</div>,
+}));
+
+vi.mock("@/contexts/AppSidebarContext", () => ({
+ useAppSidebar: () => ({
+ aboutOpen: false,
+ setAboutOpen: sidebarState.setAboutOpen,
+ attachmentSection: "all",
+ setAttachmentSection: vi.fn(),
+ inboxFilter: "all",
+ setInboxFilter: vi.fn(),
+ memoDetail: undefined,
+ setMemoDetail: vi.fn(),
+ mobileOpen: false,
+ setMobileOpen: vi.fn(),
+ quickFindOpen: false,
+ setQuickFindOpen: vi.fn(),
+ memoScope: "home",
+ setMemoScope: vi.fn(),
+ }),
+}));
+
+vi.mock("@/contexts/AuthContext", () => ({
+ useAuth: () => ({ shortcuts: [], refetchSettings: vi.fn(), isInitialized: true }),
+}));
+
+vi.mock("@/contexts/InstanceContext", () => ({
+ useInstance: () => ({ isInitialized: true }),
+}));
+
+vi.mock("@/contexts/MemoFilterContext", () => ({
+ stringifyFilters: () => "",
+ useMemoFilterContext: () => ({
+ filters: [],
+ shortcut: undefined,
+ setShortcut: vi.fn(),
+ }),
+}));
+
+vi.mock("@/hooks/useCurrentUser", () => ({
+ default: () => authState.currentUser,
+}));
+
+vi.mock("@/hooks/useFilteredMemoStats", () => ({
+ useFilteredMemoStats: () => ({ statistics: { activityStats: {}, timeBasis: "create_time" }, tags: {} }),
+}));
+
+vi.mock("@/hooks/useAttachmentLibrary", () => ({
+ useAttachmentLibraryStats: () => ({ stats: { media: 0, documents: 0, audio: 0, unused: 0 } }),
+}));
+
+vi.mock("@/hooks/useMediaQuery", () => ({
+ default: () => true,
+}));
+
+vi.mock("@/hooks/useUserQueries", () => ({
+ useNotifications: () => ({ data: [] }),
+ useUser: () => ({ data: undefined }),
+}));
+
+vi.mock("@/i18n", () => ({
+ default: { language: "en" },
+}));
+
+vi.mock("@/utils/i18n", () => ({
+ useTranslate: () => (key: string) => key,
+}));
+
+describe("App sidebar logo", () => {
+ beforeEach(() => {
+ authState.currentUser = { name: "users/test" };
+ sidebarState.setAboutOpen.mockReset();
+ });
+
+ it("navigates home instead of opening a global editor", () => {
+ render(
+ <MemoryRouter initialEntries={["/"]}>
+ <AppSidebar />
+ </MemoryRouter>,
+ );
+
+ const logo = screen.getByRole("link", { name: "Memos logo" });
+ expect(logo).toHaveAttribute("href", "/");
+ expect(screen.queryByRole("button", { name: /create.*memos/i })).not.toBeInTheDocument();
+ expect(screen.queryByText("common.calendar")).not.toBeInTheDocument();
+ });
+
+ it("shows the compact public navigation for a guest", () => {
+ authState.currentUser = undefined;
+ render(
+ <MemoryRouter initialEntries={["/explore"]}>
+ <AppSidebar />
+ </MemoryRouter>,
+ );
+
+ expect(screen.getByRole("link", { name: "common.explore" })).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "common.about" }));
+ expect(sidebarState.setAboutOpen).toHaveBeenCalledWith(true);
+ expect(screen.getByRole("link", { name: "common.sign-in-to-memos" }).closest("footer")).not.toBeNull();
+ expect(screen.queryByRole("link", { name: "common.home" })).not.toBeInTheDocument();
+ });
+
+ it("uses a compact scope menu and places views below the calendar", async () => {
+ render(
+ <MemoryRouter initialEntries={["/"]}>
+ <AppSidebar />
+ </MemoryRouter>,
+ );
+
+ const calendar = screen.getByText("Calendar");
+ const views = screen.getByText("common.views");
+ expect(calendar.compareDocumentPosition(views) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ expect(screen.getByRole("button", { name: "common.tasks" })).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "common.all" })).not.toBeInTheDocument();
+
+ const scopeTrigger = screen.getByRole("button", { name: "common.home" });
+ fireEvent.click(scopeTrigger);
+ expect(await screen.findByRole("menuitem", { name: "common.home" })).toBeInTheDocument();
+ expect(screen.getByRole("menuitem", { name: "common.explore" })).toBeInTheDocument();
+ expect(screen.getByRole("menuitem", { name: "common.archived" })).toBeInTheDocument();
+ });
+
+ it("collapses inactive global destinations and sends the scope icon to Home", async () => {
+ render(
+ <MemoryRouter initialEntries={["/attachments"]}>
+ <AppSidebar />
+ </MemoryRouter>,
+ );
+
+ const scopeTrigger = screen.getByRole("button", { name: "common.home" });
+ expect(scopeTrigger).toHaveClass("size-[30px]");
+ expect(scopeTrigger).not.toHaveTextContent("common.home");
+
+ const inbox = screen.getByRole("link", { name: "common.inbox" });
+ expect(inbox).toHaveClass("size-[30px]");
+ expect(inbox).not.toHaveTextContent("common.inbox");
+
+ const attachments = screen.getByRole("link", { name: "common.attachments" });
+ expect(attachments).toHaveAttribute("aria-current", "page");
+ expect(attachments).toHaveTextContent("common.attachments");
+
+ fireEvent.click(scopeTrigger);
+ expect(await screen.findByText("Calendar")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "common.home" })).toHaveTextContent("common.home");
+ expect(screen.queryByRole("menuitem", { name: "common.explore" })).not.toBeInTheDocument();
+ });
+
+ it("keeps the mobile brand beside navigation without a duplicate search action", () => {
+ render(
+ <MemoryRouter initialEntries={["/"]}>
+ <MobileAppHeader />
+ </MemoryRouter>,
+ );
+
+ expect(screen.getByRole("button", { name: "Open navigation" })).toBeInTheDocument();
+ expect(screen.getByRole("link", { name: "Memos logo" })).toHaveAttribute("href", "/");
+ expect(screen.queryByRole("button", { name: "common.search" })).not.toBeInTheDocument();
+ });
+});
diff --git a/web/tests/app-sidebar-routes.test.ts b/web/tests/app-sidebar-routes.test.ts
new file mode 100644
index 000000000..36746f345
--- /dev/null
+++ b/web/tests/app-sidebar-routes.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from "vitest";
+import { getSidebarRouteKind } from "@/components/AppSidebar/routes";
+
+describe("sidebar route content", () => {
+ it.each([
+ ["/", "home"],
+ ["/archived", "archived"],
+ ["/explore", "explore"],
+ ["/u/steven", "profile"],
+ ["/shortcuts", "shortcuts"],
+ ["/attachments", "attachments"],
+ ["/inbox", "inbox"],
+ ["/setting", "settings"],
+ ["/memos/abc", "memo"],
+ ["/memos/shares/token", "memo"],
+ ["/about", "empty"],
+ ["/404", "empty"],
+ ])("maps %s to %s content", (path, kind) => {
+ expect(getSidebarRouteKind(path)).toBe(kind);
+ });
+});
diff --git a/web/tests/attachment-library-stats.test.ts b/web/tests/attachment-library-stats.test.ts
new file mode 100644
index 000000000..4632600a4
--- /dev/null
+++ b/web/tests/attachment-library-stats.test.ts
@@ -0,0 +1,76 @@
+import { create } from "@bufbuild/protobuf";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { renderHook, waitFor } from "@testing-library/react";
+import { createElement, type PropsWithChildren } from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { buildAttachmentLibraryStats, useAttachmentLibraryStats } from "@/hooks/useAttachmentLibrary";
+import {
+ AttachmentSchema,
+ MotionMediaFamily,
+ MotionMediaRole,
+ MotionMediaSchema,
+ type Attachment,
+} from "@/types/proto/api/v1/attachment_service_pb";
+
+const clients = vi.hoisted(() => ({ listAttachments: vi.fn() }));
+
+vi.mock("@/connect", () => ({
+ attachmentServiceClient: { listAttachments: clients.listAttachments },
+}));
+
+const attachment = (name: string, type: string, memo?: string): Attachment =>
+ create(AttachmentSchema, { name: `attachments/${name}`, filename: name, type, memo });
+
+describe("buildAttachmentLibraryStats", () => {
+ beforeEach(() => clients.listAttachments.mockReset());
+
+ it("counts linked attachment types without expanding live-photo pairs", () => {
+ const still = attachment("live.jpg", "image/jpeg", "memos/one");
+ still.motionMedia = create(MotionMediaSchema, {
+ family: MotionMediaFamily.APPLE_LIVE_PHOTO,
+ role: MotionMediaRole.STILL,
+ groupId: "live-photo",
+ });
+ const video = attachment("live.mov", "video/quicktime", "memos/one");
+ video.motionMedia = create(MotionMediaSchema, {
+ family: MotionMediaFamily.APPLE_LIVE_PHOTO,
+ role: MotionMediaRole.VIDEO,
+ groupId: "live-photo",
+ });
+
+ expect(
+ buildAttachmentLibraryStats([
+ still,
+ video,
+ attachment("photo.png", "image/png", "memos/one"),
+ attachment("recording.mp3", "audio/mpeg", "memos/one"),
+ attachment("notes.pdf", "application/pdf", "memos/one"),
+ attachment("unused.png", "image/png"),
+ ]),
+ ).toEqual({
+ unused: 1,
+ media: 2,
+ documents: 1,
+ audio: 1,
+ });
+ });
+
+ it("loads every page before exposing complete sidebar counts", async () => {
+ clients.listAttachments
+ .mockResolvedValueOnce({
+ attachments: [attachment("photo.png", "image/png", "memos/one")],
+ nextPageToken: "1000",
+ })
+ .mockResolvedValueOnce({
+ attachments: [attachment("unused.pdf", "application/pdf")],
+ nextPageToken: "",
+ });
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const wrapper = ({ children }: PropsWithChildren) => createElement(QueryClientProvider, { client: queryClient }, children);
+ const { result } = renderHook(() => useAttachmentLibraryStats(), { wrapper });
+
+ await waitFor(() => expect(result.current.isComplete).toBe(true));
+ expect(result.current.stats).toEqual({ media: 1, documents: 0, audio: 0, unused: 1 });
+ expect(clients.listAttachments).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/web/tests/calendar-cell-empty-clickable.test.tsx b/web/tests/calendar-cell-empty-clickable.test.tsx
index 6308e1d54..9b916db5b 100644
--- a/web/tests/calendar-cell-empty-clickable.test.tsx
+++ b/web/tests/calendar-cell-empty-clickable.test.tsx
@@ -30,6 +30,7 @@ describe("CalendarCell empty-day clickability", () => {
const button = screen.getByRole("button", { name: /May 1, 2025/ });
expect(button).toHaveAttribute("tabindex", "0");
expect(button).toHaveAttribute("aria-disabled", "false");
+ expect(button).toHaveClass("bg-transparent");
});
it("still renders a populated in-month day as interactive", () => {
@@ -40,6 +41,22 @@ describe("CalendarCell empty-day clickability", () => {
expect(onClick).toHaveBeenCalledWith("2025-05-01");
});
+ it("marks today with a dot without changing the numeral weight", () => {
+ render(<CalendarCell day={makeDay({ isToday: true })} maxCount={5} tooltipText="May 1, 2025" onClick={() => {}} />);
+
+ const button = screen.getByRole("button", { name: /May 1, 2025/ });
+ expect(button).not.toHaveClass("font-semibold", "font-bold");
+ expect(button.querySelector('[aria-hidden="true"]')).toHaveClass("rounded-full");
+ });
+
+ it("uses an inset ring for selection without changing the numeral weight", () => {
+ render(<CalendarCell day={makeDay({ isSelected: true })} maxCount={5} tooltipText="May 1, 2025" onClick={() => {}} />);
+
+ const button = screen.getByRole("button", { name: /selected/ });
+ expect(button).toHaveClass("ring-2", "ring-inset");
+ expect(button).not.toHaveClass("font-semibold", "font-bold");
+ });
+
it("does not render out-of-month days as interactive (no role=button)", () => {
render(
<CalendarCell day={makeDay({ isCurrentMonth: false })} maxCount={5} tooltipText="May 1, 2025" onClick={() => {}} />,
diff --git a/web/tests/date-filter-navigation.test.tsx b/web/tests/date-filter-navigation.test.tsx
new file mode 100644
index 000000000..a9b4e852b
--- /dev/null
+++ b/web/tests/date-filter-navigation.test.tsx
@@ -0,0 +1,39 @@
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { MemoryRouter, useLocation } from "react-router-dom";
+import { describe, expect, it } from "vitest";
+import { MemoFilterProvider } from "@/contexts/MemoFilterContext";
+import { useDateFilterNavigation } from "@/hooks/useDateFilterNavigation";
+
+const Harness = () => {
+ const location = useLocation();
+ const navigateToDate = useDateFilterNavigation();
+ return (
+ <>
+ <output data-testid="search">{location.search}</output>
+ <button type="button" onClick={() => navigateToDate("2026-08-02")}>
+ Select date
+ </button>
+ </>
+ );
+};
+
+describe("useDateFilterNavigation", () => {
+ it("preserves unrelated query parameters while replacing the date filter", async () => {
+ render(
+ <MemoryRouter initialEntries={["/u/steven?view=map&filter=tagSearch%3Awork"]}>
+ <MemoFilterProvider>
+ <Harness />
+ </MemoFilterProvider>
+ </MemoryRouter>,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "Select date" }));
+
+ await waitFor(() => {
+ const params = new URLSearchParams(screen.getByTestId("search").textContent ?? "");
+ expect(params.get("view")).toBe("map");
+ expect(params.get("filter")).toContain("tagSearch:work");
+ expect(params.get("filter")).toContain("displayTime:2026-08-02");
+ });
+ });
+});
diff --git a/web/tests/global-memo-editor.test.tsx b/web/tests/global-memo-editor.test.tsx
deleted file mode 100644
index 31425d37a..000000000
--- a/web/tests/global-memo-editor.test.tsx
+++ /dev/null
@@ -1,70 +0,0 @@
-import { fireEvent, render, screen } from "@testing-library/react";
-import { describe, expect, it, vi } from "vitest";
-import { loadMemoEditor } from "@/components/MemoEditor/loader";
-import { GlobalMemoEditorProvider, useGlobalMemoEditor } from "@/contexts/GlobalMemoEditorContext";
-
-const authState = vi.hoisted(() => ({
- currentUser: undefined as { name: string } | undefined,
-}));
-
-vi.mock("@/components/MemoEditor/loader", () => ({
- loadMemoEditor: vi.fn(async () => ({
- default: ({ initialFocusMode, onFocusModeExit }: { initialFocusMode?: boolean; onFocusModeExit?: () => void }) => (
- <div data-testid="global-editor" data-focus-mode={initialFocusMode}>
- <button type="button" onClick={onFocusModeExit}>
- Exit focus mode
- </button>
- </div>
- ),
- })),
-}));
-
-vi.mock("@/hooks/useCurrentUser", () => ({
- default: () => authState.currentUser,
-}));
-
-vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));
-
-function Trigger() {
- const { openEditor } = useGlobalMemoEditor();
- return (
- <button type="button" onClick={openEditor}>
- Open editor
- </button>
- );
-}
-
-describe("GlobalMemoEditorProvider", () => {
- it("opens the shared editor in focus mode and closes when focus mode exits", async () => {
- authState.currentUser = { name: "users/test" };
-
- render(
- <GlobalMemoEditorProvider>
- <Trigger />
- </GlobalMemoEditorProvider>,
- );
-
- fireEvent.click(screen.getByRole("button", { name: "Open editor" }));
-
- const editor = await screen.findByTestId("global-editor");
- expect(editor).toHaveAttribute("data-focus-mode", "true");
-
- fireEvent.click(screen.getByRole("button", { name: "Exit focus mode" }));
- expect(screen.queryByTestId("global-editor")).not.toBeInTheDocument();
- });
-
- it("does not load or open the editor for an unauthenticated user", () => {
- authState.currentUser = undefined;
-
- render(
- <GlobalMemoEditorProvider>
- <Trigger />
- </GlobalMemoEditorProvider>,
- );
-
- fireEvent.click(screen.getByRole("button", { name: "Open editor" }));
-
- expect(loadMemoEditor).not.toHaveBeenCalled();
- expect(screen.queryByTestId("global-editor")).not.toBeInTheDocument();
- });
-});
diff --git a/web/tests/memo-detail-sidebar.test.tsx b/web/tests/memo-detail-sidebar.test.tsx
index e35626f95..4623b2c6c 100644
--- a/web/tests/memo-detail-sidebar.test.tsx
+++ b/web/tests/memo-detail-sidebar.test.tsx
@@ -5,30 +5,20 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import MemoDetailSidebar from "@/components/MemoDetailSidebar/MemoDetailSidebar";
import { AttachmentSchema } from "@/types/proto/api/v1/attachment_service_pb";
import { State } from "@/types/proto/api/v1/common_pb";
-import { LocationSchema, MemoSchema, Visibility } from "@/types/proto/api/v1/memo_service_pb";
+import {
+ LocationSchema,
+ MemoRelation_MemoSchema,
+ MemoRelation_Type,
+ MemoRelationSchema,
+ MemoSchema,
+ Visibility,
+} from "@/types/proto/api/v1/memo_service_pb";
+const copyToClipboard = vi.hoisted(() => vi.fn());
const updateMemo = vi.hoisted(() => vi.fn());
-vi.mock("copy-to-clipboard", () => ({ default: vi.fn() }));
+vi.mock("copy-to-clipboard", () => ({ default: copyToClipboard }));
vi.mock("react-hot-toast", () => ({ default: { success: vi.fn() } }));
-vi.mock("@/components/ui/tooltip", () => ({
- Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- TooltipContent: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- TooltipTrigger: ({ children, render }: { children: React.ReactNode; render: React.ReactElement }) => (
- <>
- {render}
- {children}
- </>
- ),
-}));
-vi.mock("@/components/MemoEditor/Toolbar/VisibilitySelector", () => ({
- default: ({ onChange }: { onChange: (visibility: Visibility) => void }) => (
- <button type="button" onClick={() => onChange(Visibility.PRIVATE)}>
- visibility-selector
- </button>
- ),
-}));
-vi.mock("@/components/UserAvatar", () => ({ default: () => <div data-testid="avatar" /> }));
vi.mock("@/components/MemoDetailSidebar/MemoOutline", () => ({
default: ({ headings }: { headings: unknown[] }) => <div data-testid="outline">{headings.length}</div>,
}));
@@ -37,19 +27,16 @@ vi.mock("@/components/MemoMetadata/Relation/useResolvedRelationMemos", () => ({
vi.mock("@/contexts/InstanceContext", () => ({ useInstance: () => ({ profile: { instanceUrl: "https://memos.example" } }) }));
vi.mock("@/hooks/useCurrentUser", () => ({ default: () => ({ name: "users/alice" }) }));
vi.mock("@/hooks/useMemoQueries", () => ({ useUpdateMemo: () => ({ mutateAsync: updateMemo }) }));
-vi.mock("@/hooks/useUserQueries", () => ({
- useUser: () => ({ data: { username: "alice", displayName: "Alice", avatarUrl: "" } }),
-}));
vi.mock("@/utils/i18n", () => ({ useTranslate: () => (key: string) => key }));
-vi.mock("@/i18n", () => ({ default: { language: "en-US" } }));
describe("MemoDetailSidebar", () => {
beforeEach(() => {
+ copyToClipboard.mockReset();
updateMemo.mockReset();
updateMemo.mockResolvedValue(undefined);
});
- it("renders the property rail and wires editable quick actions", async () => {
+ it("renders concise actions, outline, and backlinks without repeating body metadata", async () => {
const memo = create(MemoSchema, {
name: "memos/detail",
creator: "users/alice",
@@ -66,6 +53,18 @@ describe("MemoDetailSidebar", () => {
size: 2048n,
}),
],
+ relations: [
+ create(MemoRelationSchema, {
+ type: MemoRelation_Type.REFERENCE,
+ memo: create(MemoRelation_MemoSchema, { name: "memos/detail" }),
+ relatedMemo: create(MemoRelation_MemoSchema, { name: "memos/outgoing", snippet: "Outgoing reference" }),
+ }),
+ create(MemoRelationSchema, {
+ type: MemoRelation_Type.REFERENCE,
+ memo: create(MemoRelation_MemoSchema, { name: "memos/incoming", snippet: "Incoming backlink" }),
+ relatedMemo: create(MemoRelation_MemoSchema, { name: "memos/detail" }),
+ }),
+ ],
});
const onShareImageOpen = vi.fn();
@@ -75,15 +74,17 @@ describe("MemoDetailSidebar", () => {
</MemoryRouter>,
);
- expect(screen.getByText("common.visibility")).toBeInTheDocument();
- expect(screen.getByText("common.created-at")).toBeInTheDocument();
- expect(screen.getByText("common.author")).toBeInTheDocument();
- expect(screen.getByText("common.location")).toBeInTheDocument();
- expect(screen.getByText("common.tags")).toBeInTheDocument();
- expect(screen.getByText("common.attachments")).toBeInTheDocument();
+ expect(screen.getByText("common.actions")).toBeInTheDocument();
expect(screen.getByText("memo.outline")).toBeInTheDocument();
- expect(screen.getByText("release/0.30")).toBeInTheDocument();
- expect(screen.getByRole("link", { name: /release-notes\.pdf/ })).toBeInTheDocument();
+ expect(screen.getByText("common.referenced-by")).toBeInTheDocument();
+ expect(screen.getByRole("link", { name: "Incoming backlink" })).toBeInTheDocument();
+ expect(screen.queryByText("Outgoing reference")).not.toBeInTheDocument();
+ expect(screen.queryByText("common.visibility")).not.toBeInTheDocument();
+ expect(screen.queryByText("common.created-at")).not.toBeInTheDocument();
+ expect(screen.queryByText("common.location")).not.toBeInTheDocument();
+ expect(screen.queryByText("common.attachments")).not.toBeInTheDocument();
+ expect(screen.queryByText("release-notes.pdf")).not.toBeInTheDocument();
+ expect(screen.queryByText("release/0.30")).not.toBeInTheDocument();
expect(screen.getByTestId("outline")).toHaveTextContent("2");
fireEvent.click(screen.getByRole("button", { name: "common.pin" }));
@@ -91,17 +92,64 @@ describe("MemoDetailSidebar", () => {
expect(updateMemo).toHaveBeenCalledWith({ update: { name: "memos/detail", pinned: true }, updateMask: ["pinned"] }),
);
- fireEvent.click(screen.getByRole("button", { name: "visibility-selector" }));
- await waitFor(() =>
- expect(updateMemo).toHaveBeenCalledWith({
- update: { name: "memos/detail", visibility: Visibility.PRIVATE },
- updateMask: ["visibility"],
- }),
- );
+ fireEvent.click(screen.getByRole("button", { name: "common.share" }));
+ fireEvent.click(await screen.findByRole("menuitem", { name: "memo.copy-link" }));
+ expect(copyToClipboard).toHaveBeenCalledWith("https://memos.example/memos/detail");
- fireEvent.click(screen.getByRole("button", { name: "memo.share.open-image" }));
+ fireEvent.click(screen.getByRole("button", { name: "common.share" }));
+ fireEvent.click(await screen.findByRole("menuitem", { name: "memo.share.open-image" }));
expect(onShareImageOpen).toHaveBeenCalledTimes(1);
- fireEvent.click(screen.getByRole("button", { name: "memo.share.open-panel" }));
+
+ fireEvent.click(screen.getByRole("button", { name: "common.share" }));
+ fireEvent.click(await screen.findByRole("menuitem", { name: "memo.share.open-panel" }));
expect(screen.getByTestId("share-panel")).toBeInTheDocument();
});
+
+ it("keeps a readonly simple memo useful with only the share action", () => {
+ const memo = create(MemoSchema, {
+ name: "memos/readonly",
+ creator: "users/alice",
+ state: State.NORMAL,
+ visibility: Visibility.PUBLIC,
+ content: "# Overview\n\nBody",
+ relations: [
+ create(MemoRelationSchema, {
+ type: MemoRelation_Type.REFERENCE,
+ memo: create(MemoRelation_MemoSchema, { name: "memos/incoming", snippet: "Private backlink" }),
+ relatedMemo: create(MemoRelation_MemoSchema, { name: "memos/readonly" }),
+ }),
+ ],
+ });
+
+ render(
+ <MemoryRouter>
+ <MemoDetailSidebar memo={memo} forceReadonly />
+ </MemoryRouter>,
+ );
+
+ expect(screen.getByRole("button", { name: "common.share" })).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "common.pin" })).not.toBeInTheDocument();
+ expect(screen.queryByText("memo.outline")).not.toBeInTheDocument();
+ expect(screen.queryByText("common.referenced-by")).not.toBeInTheDocument();
+ expect(screen.queryByText("Private backlink")).not.toBeInTheDocument();
+ });
+
+ it("keeps the outline available for readonly memos with multiple headings", () => {
+ const memo = create(MemoSchema, {
+ name: "memos/readonly-outline",
+ creator: "users/alice",
+ state: State.NORMAL,
+ visibility: Visibility.PUBLIC,
+ content: "# Overview\n\nBody\n\n## Details\n\nMore",
+ });
+
+ render(
+ <MemoryRouter>
+ <MemoDetailSidebar memo={memo} forceReadonly />
+ </MemoryRouter>,
+ );
+
+ expect(screen.getByText("memo.outline")).toBeInTheDocument();
+ expect(screen.getByTestId("outline")).toHaveTextContent("2");
+ });
});
diff --git a/web/tests/memo-filter-context.test.tsx b/web/tests/memo-filter-context.test.tsx
new file mode 100644
index 000000000..b004d0e91
--- /dev/null
+++ b/web/tests/memo-filter-context.test.tsx
@@ -0,0 +1,45 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { MemoryRouter } from "react-router-dom";
+import { describe, expect, it } from "vitest";
+import { MemoFilterProvider, parseFilterQuery, useMemoFilterContext } from "@/contexts/MemoFilterContext";
+import { BUILTIN_TASKS_VIEW_ID } from "@/lib/memo-views";
+
+const Harness = () => {
+ const { filters, setFilters, setShortcut, shortcut } = useMemoFilterContext();
+ return (
+ <div>
+ <output data-testid="filters">{JSON.stringify(filters)}</output>
+ <output data-testid="shortcut">{shortcut}</output>
+ <button type="button" onClick={() => setFilters([{ factor: "contentSearch", value: "plan" }])}>
+ Search plan
+ </button>
+ <button type="button" onClick={() => setShortcut(BUILTIN_TASKS_VIEW_ID)}>
+ Select Tasks
+ </button>
+ </div>
+ );
+};
+
+describe("MemoFilterProvider", () => {
+ it("keeps encoded values containing colons intact", () => {
+ expect(parseFilterQuery("contentSearch:https://example.com:8080/path")).toEqual([
+ { factor: "contentSearch", value: "https://example.com:8080/path" },
+ ]);
+ });
+
+ it("keeps search filters when selecting a view", () => {
+ render(
+ <MemoryRouter>
+ <MemoFilterProvider>
+ <Harness />
+ </MemoFilterProvider>
+ </MemoryRouter>,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "Search plan" }));
+ fireEvent.click(screen.getByRole("button", { name: "Select Tasks" }));
+
+ expect(screen.getByTestId("filters")).toHaveTextContent('[{"factor":"contentSearch","value":"plan"}]');
+ expect(screen.getByTestId("shortcut")).toHaveTextContent(BUILTIN_TASKS_VIEW_ID);
+ });
+});
diff --git a/web/tests/memo-views.test.ts b/web/tests/memo-views.test.ts
new file mode 100644
index 000000000..6ad3d653e
--- /dev/null
+++ b/web/tests/memo-views.test.ts
@@ -0,0 +1,93 @@
+import { describe, expect, it } from "vitest";
+import { buildMemoFilter } from "@/hooks/useMemoFilters";
+import {
+ BUILTIN_TASKS_VIEW_FILTER,
+ BUILTIN_TASKS_VIEW_ID,
+ getMemoScopePath,
+ getShortcutId,
+ isMemoScopeRoute,
+ resolveMemoScope,
+} from "@/lib/memo-views";
+import { Visibility } from "@/types/proto/api/v1/memo_service_pb";
+
+describe("memo scopes", () => {
+ it("resolves collection, profile, and detail routes", () => {
+ expect(resolveMemoScope("/archived")).toBe("archived");
+ expect(resolveMemoScope("/explore")).toBe("explore");
+ expect(resolveMemoScope("/u/steven", { currentUsername: "steven" })).toBe("home");
+ expect(resolveMemoScope("/u/maya", { currentUsername: "steven" })).toBe("explore");
+ expect(resolveMemoScope("/memos/123", { detailFrom: "/archived?filter=tagSearch%3Awork" })).toBe("archived");
+ expect(resolveMemoScope("/memos/123", { memoArchived: true })).toBe("archived");
+ expect(resolveMemoScope("/settings", { fallback: "explore" })).toBe("explore");
+ });
+
+ it("maps only the three collection routes to memo scopes", () => {
+ expect(isMemoScopeRoute("/")).toBe(true);
+ expect(isMemoScopeRoute("/explore")).toBe(true);
+ expect(isMemoScopeRoute("/archived")).toBe(true);
+ expect(isMemoScopeRoute("/attachments")).toBe(false);
+ expect(getMemoScopePath("home")).toBe("/");
+ expect(getMemoScopePath("explore")).toBe("/explore");
+ expect(getMemoScopePath("archived")).toBe("/archived");
+ });
+});
+
+describe("memo views", () => {
+ it("uses a collision-safe built-in Tasks view", () => {
+ expect(BUILTIN_TASKS_VIEW_ID).not.toBe("tasks");
+ expect(BUILTIN_TASKS_VIEW_FILTER).toBe("has_task_list && has_incomplete_tasks");
+ expect(getShortcutId("users/steven/shortcuts/work")).toBe("work");
+ });
+
+ it("composes Tasks with search, tags, creator, and visibility", () => {
+ expect(
+ buildMemoFilter({
+ creatorName: "users/steven",
+ currentShortcut: BUILTIN_TASKS_VIEW_ID,
+ filters: [
+ { factor: "contentSearch", value: "plan" },
+ { factor: "tagSearch", value: "work" },
+ ],
+ includePinned: false,
+ visibilities: [Visibility.PUBLIC],
+ }),
+ ).toBe(
+ 'creator == "users/steven" && has_task_list && has_incomplete_tasks && content.contains("plan") && tag in ["work"] && visibility in ["PUBLIC"]',
+ );
+ });
+
+ it("uses a custom shortcut filter when Tasks is not selected", () => {
+ expect(
+ buildMemoFilter({
+ currentShortcut: "work",
+ filters: [],
+ includePinned: false,
+ selectedShortcutFilter: 'tag in ["work"]',
+ }),
+ ).toBe('tag in ["work"]');
+ });
+
+ it("builds display-time filters from valid local calendar-day boundaries", () => {
+ const start = new Date(2026, 7, 2);
+ const end = new Date(start);
+ end.setDate(end.getDate() + 1);
+
+ expect(
+ buildMemoFilter({
+ filters: [{ factor: "displayTime", value: "2026-08-02" }],
+ includePinned: false,
+ }),
+ ).toBe(
+ `created_ts >= timestamp(${Math.floor(start.getTime() / 1000)}) && created_ts < timestamp(${Math.floor(end.getTime() / 1000)})`,
+ );
+ });
+
+ it("ignores invalid display-time filter values", () => {
+ expect(
+ buildMemoFilter({
+ filters: [{ factor: "displayTime", value: "2026-02-30" }],
+ includePinned: false,
+ }),
+ ).toBeUndefined();
+ });
+});
diff --git a/web/tests/month-navigator.test.tsx b/web/tests/month-navigator.test.tsx
new file mode 100644
index 000000000..759212835
--- /dev/null
+++ b/web/tests/month-navigator.test.tsx
@@ -0,0 +1,23 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { MonthNavigator } from "@/components/StatisticsView/MonthNavigator";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ i18n: { language: "en" }, t: (key: string) => key }),
+}));
+
+describe("MonthNavigator", () => {
+ it("keeps only previous and next month actions", () => {
+ const onMonthChange = vi.fn();
+ render(<MonthNavigator visibleMonth="2026-08" onMonthChange={onMonthChange} />);
+
+ expect(screen.getByRole("heading", { name: "August 2026" })).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Select month" })).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole("button", { name: "common.previous-month" }));
+ expect(onMonthChange).toHaveBeenCalledWith("2026-07");
+
+ fireEvent.click(screen.getByRole("button", { name: "common.next-month" }));
+ expect(onMonthChange).toHaveBeenCalledWith("2026-09");
+ });
+});
diff --git a/web/tests/navigation-logo-create.test.tsx b/web/tests/navigation-logo-create.test.tsx
deleted file mode 100644
index 2ffa4fac5..000000000
--- a/web/tests/navigation-logo-create.test.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-import { fireEvent, render, screen } from "@testing-library/react";
-import { MemoryRouter } from "react-router-dom";
-import { describe, expect, it, vi } from "vitest";
-import Navigation from "@/components/Navigation";
-
-const mocks = vi.hoisted(() => ({
- openEditor: vi.fn(),
-}));
-
-vi.mock("@/components/MemosLogo", () => ({
- default: () => <span>Memos logo</span>,
-}));
-
-vi.mock("@/components/UserMenu", () => ({
- default: () => <div>User menu</div>,
-}));
-
-vi.mock("@/contexts/GlobalMemoEditorContext", () => ({
- useGlobalMemoEditor: () => ({ isOpen: false, openEditor: mocks.openEditor }),
-}));
-
-vi.mock("@/hooks/useCurrentUser", () => ({
- default: () => ({ name: "users/test" }),
-}));
-
-vi.mock("@/hooks/useUserQueries", () => ({
- useNotifications: () => ({ data: [] }),
-}));
-
-vi.mock("@/utils/i18n", () => ({
- useTranslate: () => (key: string) => key,
-}));
-
-describe("Navigation logo", () => {
- it("opens the global memo editor for an authenticated user", () => {
- render(
- <MemoryRouter>
- <Navigation collapsed />
- </MemoryRouter>,
- );
-
- fireEvent.click(screen.getByRole("button", { name: "common.create common.memos" }));
-
- expect(mocks.openEditor).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/web/tests/quick-find.test.ts b/web/tests/quick-find.test.ts
new file mode 100644
index 000000000..ab23c02bd
--- /dev/null
+++ b/web/tests/quick-find.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from "vitest";
+import { buildQuickFindFilters, isQuickFindCollectionRoute } from "@/components/AppSidebar/QuickFindDialog";
+import { type MemoFilter, replaceFiltersByFactor } from "@/contexts/MemoFilterContext";
+
+describe("Quick Find", () => {
+ const scopedFilters: MemoFilter[] = [
+ { factor: "tagSearch", value: "work" },
+ { factor: "displayTime", value: "2026-08-03" },
+ { factor: "contentSearch", value: "old" },
+ ];
+
+ it("replaces search terms while preserving date and tag facets in a collection", () => {
+ expect(buildQuickFindFilters("project plan project", scopedFilters, true)).toEqual([
+ { factor: "tagSearch", value: "work" },
+ { factor: "displayTime", value: "2026-08-03" },
+ { factor: "contentSearch", value: "project" },
+ { factor: "contentSearch", value: "plan" },
+ ]);
+ });
+
+ it("starts a clean All search outside collection routes", () => {
+ expect(buildQuickFindFilters("project", scopedFilters, false)).toEqual([{ factor: "contentSearch", value: "project" }]);
+ expect(isQuickFindCollectionRoute("/attachments")).toBe(false);
+ expect(isQuickFindCollectionRoute("/archived")).toBe(true);
+ expect(isQuickFindCollectionRoute("/u/steven")).toBe(true);
+ });
+
+ it("replaces only the selected date facet", () => {
+ expect(replaceFiltersByFactor(scopedFilters, "displayTime", [{ factor: "displayTime", value: "2026-08-02" }])).toEqual([
+ { factor: "tagSearch", value: "work" },
+ { factor: "contentSearch", value: "old" },
+ { factor: "displayTime", value: "2026-08-02" },
+ ]);
+ });
+});