AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix(frontend): close the mobile nav on navigation and speed up its slide (#15692)
Ubbe9bfe0c618b5a
diff --git a/autogpt_platform/frontend/src/app/(public)/tour/chat/components/TourSidebar/TourSidebar.tsx b/autogpt_platform/frontend/src/app/(public)/tour/chat/components/TourSidebar/TourSidebar.tsxindex f81f42fa41..213b768aa9 100644--- a/autogpt_platform/frontend/src/app/(public)/tour/chat/components/TourSidebar/TourSidebar.tsx+++ b/autogpt_platform/frontend/src/app/(public)/tour/chat/components/TourSidebar/TourSidebar.tsx@@ -65,8 +65,9 @@ interface Props {variant?: "tour" | "marketplace";}-// Matches the sheet's closing animation (`data-[state=closed]:duration-300`).-const SHEET_CLOSE_MS = 300;+// Matches the mobile sidebar sheet's closing animation+// (`data-[state=closed]:duration-200` in `@/components/ui/sidebar`).+const SHEET_CLOSE_MS = 200;export function TourSidebar({ variant = "tour" }: Props) {const reduceMotion = useReducedMotion();diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/AppSidebar.tsx b/autogpt_platform/frontend/src/components/layout/AppSidebar/AppSidebar.tsxindex cbea4e42a5..5ebe2d9001 100644--- a/autogpt_platform/frontend/src/components/layout/AppSidebar/AppSidebar.tsx+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/AppSidebar.tsx@@ -9,6 +9,7 @@ import {SidebarMenuButton,SidebarMenuItem,SidebarRail,+ useSidebar,} from "@/components/ui/sidebar";import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";import { LoadingSpinner } from "@/components/atoms/LoadingSpinner/LoadingSpinner";@@ -165,6 +166,7 @@ type Props = ComponentProps<typeof Sidebar>;export function AppSidebar(props: Props) {const { isLoggedIn } = useAuth();const reduceMotion = useReducedMotion();+ const { isMobile } = useSidebar();const itemVariants = getSidebarItemVariants(!!reduceMotion);const router = useRouter();const isHireExpertsEnabled = useGetFlag(Flag.HIRE_EXPERTS);@@ -200,7 +202,9 @@ export function AppSidebar(props: Props) {<motion.divvariants={sidebarContainerVariants}- initial="hidden"+ // On mobile the sheet's slide is the entrance; a blurred stagger on+ // top of it delays the items and costs frames on phones.+ initial={isMobile ? false : "hidden"}animate="show"className="flex shrink-0 flex-col gap-2">diff --git a/autogpt_platform/frontend/src/components/layout/AppSidebar/__tests__/mobile-sheet.test.tsx b/autogpt_platform/frontend/src/components/layout/AppSidebar/__tests__/mobile-sheet.test.tsxnew file mode 100644index 0000000000..a0509af09d--- /dev/null+++ b/autogpt_platform/frontend/src/components/layout/AppSidebar/__tests__/mobile-sheet.test.tsx@@ -0,0 +1,139 @@+import { getGetV2ListSessionsMockHandler200 } from "@/app/api/__generated__/endpoints/chat/chat.msw";+import { SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar";+import { server } from "@/mocks/mock-server";+import {+ fireEvent,+ render,+ screen,+ waitFor,+} from "@/tests/integrations/test-utils";+import type { ReactNode } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { AppSidebar } from "../AppSidebar";++vi.mock("@/lib/auth/hooks/useAuth", () => ({+ useAuth: () => ({+ user: { id: "user-1", email: "[email protected]", role: "user" },+ isLoggedIn: true,+ isUserLoading: false,+ }),+}));++// The global next/link mock only exports `default`; AppSidebar also imports+// `useLinkStatus`, so re-mock here with a no-op pending status.+vi.mock("next/link", () => ({+ __esModule: true,+ default: ({+ children,+ href,+ ...props+ }: {+ children: ReactNode;+ href: string;+ }) => (+ <a href={href} {...props}>+ {children}+ </a>+ ),+ useLinkStatus: () => ({ pending: false }),+}));++vi.mock("next/navigation", async (importOriginal) => {+ const actual = await importOriginal<typeof import("next/navigation")>();+ return {+ ...actual,+ useRouter: () => ({ push: vi.fn(), replace: vi.fn(), prefetch: vi.fn() }),+ usePathname: () => "/home",+ useSearchParams: () => new URLSearchParams(),+ };+});++vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("@/services/feature-flags/use-get-flag")+ >();+ return { ...actual, useGetFlag: () => false };+});++vi.mock("@/hooks/use-mobile", () => ({ useIsMobile: () => true }));++function renderMobileSidebar() {+ render(+ <SidebarProvider>+ <SidebarTrigger />+ <AppSidebar />+ </SidebarProvider>,+ );+}++function openSheet() {+ fireEvent.click(screen.getByRole("button", { name: /toggle sidebar/i }));+ return screen.getByRole("dialog");+}++beforeEach(() => {+ server.use(+ getGetV2ListSessionsMockHandler200({+ sessions: [+ {+ id: "session-1",+ title: "Plan the launch",+ is_processing: false,+ is_pinned: false,+ created_at: new Date().toISOString(),+ updated_at: new Date().toISOString(),+ },+ ],+ total: 1,+ }),+ );+});++afterEach(() => {+ server.resetHandlers();+});++describe("AppSidebar on mobile", () => {+ it("closes the sheet when a chat is tapped", async () => {+ renderMobileSidebar();+ openSheet();++ fireEvent.click(+ await screen.findByRole("link", { name: /plan the launch/i }),+ );++ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());+ });++ it("closes the sheet when a nav link is tapped", async () => {+ renderMobileSidebar();+ openSheet();++ fireEvent.click(screen.getByRole("link", { name: /marketplace/i }));++ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());+ });++ it("keeps the sheet open when a tap opens a new tab", async () => {+ renderMobileSidebar();+ openSheet();++ fireEvent.click(screen.getByRole("link", { name: /marketplace/i }), {+ metaKey: true,+ });++ expect(screen.getByRole("dialog")).toBeDefined();+ });++ it("keeps the sheet open when a chat's actions menu opens", async () => {+ renderMobileSidebar();+ openSheet();++ await screen.findByRole("link", { name: /plan the launch/i });+ fireEvent.click(screen.getByRole("button", { name: /chat actions/i }));++ expect(screen.getByRole("dialog")).toBeDefined();+ });+});diff --git a/autogpt_platform/frontend/src/components/ui/sidebar.tsx b/autogpt_platform/frontend/src/components/ui/sidebar.tsxindex 0c1ecb23d6..dac52a7d92 100644--- a/autogpt_platform/frontend/src/components/ui/sidebar.tsx+++ b/autogpt_platform/frontend/src/components/ui/sidebar.tsx@@ -198,6 +198,21 @@ function getPersistedSidebarOpen(): boolean | undefined {);}+// next/link has already called preventDefault by the time this runs, so the+// modifier keys are what tell a same-tab navigation apart.+function isSameTabLinkClick(event: React.MouseEvent<HTMLElement>) {+ if (!(event.target instanceof Element)) return false;+ if (event.button !== 0) return false;+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {+ return false;+ }+ const link = event.target.closest("a[href]");+ if (!link) return false;+ return (+ link.getAttribute("target") !== "_blank" && !link.hasAttribute("download")+ );+}+const Sidebar = React.forwardRef<HTMLDivElement,React.ComponentProps<"div"> & {@@ -241,7 +256,9 @@ const Sidebar = React.forwardRef<data-sidebar="sidebar"data-mobile="true"tabIndex={-1}- className="w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground outline-none [&>button]:hidden"+ // The default sheet eases in over 500ms, which lags behind the+ // tap; a drawer curve that starts fast keeps up with the finger.+ className="w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground outline-none [animation-timing-function:cubic-bezier(0.32,0.72,0,1)] data-[state=closed]:duration-200 data-[state=open]:duration-300 [&>button]:hidden"style={{"--sidebar-width": SIDEBAR_WIDTH_MOBILE,@@ -255,6 +272,11 @@ const Sidebar = React.forwardRef<event.preventDefault();(event.currentTarget as HTMLElement).focus();}}+ // The sheet covers the page, so a link that navigates in this+ // tab closes it on the way.+ onClick={(event) => {+ if (isSameTabLinkClick(event)) setOpenMobile(false);+ }}><SheetHeader className="sr-only"><SheetTitle>Sidebar</SheetTitle>@@ -624,7 +646,9 @@ const SidebarMenuButton = React.forwardRef</>);- if (!tooltip) {+ // Tooltips never show on mobile, and mounting one per chat slows every+ // opening of the sheet.+ if (!tooltip || isMobile) {return button;}