Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

Fix mobile community navigation history (#474)

Generb2f0d1a9c5b8
diff --git a/src/web/src/app/c/channels/[serverId]/page.tsx b/src/web/src/app/c/channels/[serverId]/page.tsx
index 0dd2f2567..bb87ede02 100644
--- a/src/web/src/app/c/channels/[serverId]/page.tsx
+++ b/src/web/src/app/c/channels/[serverId]/page.tsx
@@ -1,7 +1,7 @@
"use client"
import { useEffect } from "react"
-import { useParams, useRouter } from "next/navigation"
+import { useParams, useRouter, useSearchParams } from "next/navigation"
import { MessageList } from "@/components/community/messages/message-list"
import { Skeleton } from "@/components/ui/skeleton"
import { useServer } from "@/hooks/community/use-servers"
@@ -18,6 +18,7 @@ import { getLastChannel, pickServerLandingChannel } from "@/lib/community/last-c
export default function ServerDefaultPage() {
const params = useParams<{ serverId: string }>()
const router = useRouter()
+ const searchParams = useSearchParams()
const serverId = decodeURIComponent(params.serverId)
const { server: currentServer } = useServer(serverId)
@@ -31,9 +32,10 @@ export default function ServerDefaultPage() {
getLastChannel(serverId),
)
if (target) {
- router.replace(`/c/channels/${serverId}/${target}`)
+ const search = searchParams.toString()
+ router.replace(`/c/channels/${serverId}/${target}${search ? `?${search}` : ""}`)
}
- }, [currentServer, serverId, router])
+ }, [currentServer, serverId, router, searchParams])
const allChannels = currentServer?.categories.flatMap((cat) => cat.channels) ?? []
if (currentServer && allChannels.length === 0) {
diff --git a/src/web/src/app/c/channels/[serverId]/settings/page.tsx b/src/web/src/app/c/channels/[serverId]/settings/page.tsx
index 06f567377..f9d59a09a 100644
--- a/src/web/src/app/c/channels/[serverId]/settings/page.tsx
+++ b/src/web/src/app/c/channels/[serverId]/settings/page.tsx
@@ -1,13 +1,16 @@
"use client"
import { useEffect } from "react"
-import { useParams, useRouter } from "next/navigation"
+import { useParams, useRouter, useSearchParams } from "next/navigation"
export default function ServerSettingsRedirect() {
const params = useParams<{ serverId: string }>()
const router = useRouter()
+ const searchParams = useSearchParams()
useEffect(() => {
- router.replace(`/c/channels/${params.serverId}?settings=1`)
- }, [params.serverId, router])
+ const nextSearchParams = new URLSearchParams(searchParams.toString())
+ nextSearchParams.set("settings", "1")
+ router.replace(`/c/channels/${params.serverId}?${nextSearchParams.toString()}`)
+ }, [params.serverId, router, searchParams])
return null
}
diff --git a/src/web/src/app/c/channels/layout.tsx b/src/web/src/app/c/channels/layout.tsx
index 4173a5dac..9109e6368 100644
--- a/src/web/src/app/c/channels/layout.tsx
+++ b/src/web/src/app/c/channels/layout.tsx
@@ -1,23 +1,26 @@
"use client"
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react"
-import { useParams, useRouter, useSearchParams } from "next/navigation"
+import { useParams, usePathname, useRouter, useSearchParams } from "next/navigation"
import { useQueryClient } from "@tanstack/react-query"
import { toast } from "sonner"
import { apiFetch, toastApiError } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import { markSwitch } from "@/lib/perf/switch-mark"
import { Dialog, DialogContent } from "@/components/ui/dialog"
-import { useBreakpoint } from "@/hooks/use-mobile"
import { useChannelTree } from "@/components/community/channels/use-channel-tree"
import { patchChannelUnread } from "@/hooks/community/server-detail-cache"
import type { ServerDetail } from "@/hooks/community/use-servers"
import { ShellFrame } from "@/components/community/shell/shell-frame"
+import {
+ removeCommunityParam,
+ resolveMobileZone,
+ withMobileZone,
+} from "@/components/community/shell/mobile-zone"
import { ChannelSidebar } from "@/components/community/channels/channel-sidebar"
import { ServerSettings } from "@/components/community/settings/server-settings"
import { ImageCropDialog } from "@/components/community/image-crop-dialog"
import { validateIconSourceFile } from "@/lib/community/image-crop"
-import type { MobileZone } from "@/components/community/shell/mobile-zone"
import type { SettingsSection } from "@/components/community/settings/settings-types"
import { canManageServer, isForum, notifLevelDisplay, type ChannelType } from "@alook/shared"
import { resolveRowPresence } from "@/lib/community/presence"
@@ -34,7 +37,6 @@ import {
runAuthoritativeServerEject,
} from "@/lib/community/eject-server"
import { clearLastChannel } from "@/lib/community/last-channel"
-import { getLastMeLeaf, pickMeLandingLocation } from "@/lib/community/last-me-location"
import { usePresence } from "@/hooks/community/use-server-panels"
import {
patchForumSidebarUnreadExact,
@@ -67,12 +69,12 @@ import {
export default function ServerLayout({ children }: { children: ReactNode }) {
const params = useParams<{ serverId: string; channelId?: string }>()
const searchParams = useSearchParams()
+ const pathname = usePathname()
const serverId = decodeURIComponent(params.serverId)
const routeChannelId = params.channelId ? decodeURIComponent(params.channelId) : null
const hasChannel = !!params.channelId
const router = useRouter()
- const bp = useBreakpoint()
const queryClient = useQueryClient()
const cancelPendingNavigation = useCallback(() => {
useCommunityStore.getState().uiHandlers.cancelPendingNavigation?.()
@@ -182,10 +184,10 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
toast,
replace: (destination) => {
cancelPendingNavigation()
- router.replace(destination)
+ router.replace(withMobileZone(destination, resolveMobileZone(searchParams)))
},
})
- }, [cancelPendingNavigation, serverId, serversList.isSuccess, serversList.isFetching, serversList.servers, router])
+ }, [cancelPendingNavigation, serverId, serversList.isSuccess, serversList.isFetching, serversList.servers, router, searchParams])
// Reset the guard when the URL changes to a NEW server id — otherwise
// navigating server → dangling-server → server would leave the ref
// latched and skip the eject.
@@ -210,7 +212,6 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
useCommunityWsStore.getState().hydratePresence(initialOnline)
}, [presence.isFetching, presence.data, initialOnline])
- const [mobileZone, setMobileZone] = useState<MobileZone>(() => hasChannel ? "messages" : "nav")
const [serverSettingsOpen, setServerSettingsOpen] = useState(false)
const [settingsSection, setSettingsSection] = useState<SettingsSection>("overview")
const [invitePopoverOpen, setInvitePopoverOpen] = useState(false)
@@ -239,7 +240,14 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
useEffect(() => {
const wantsSettings = searchParams.get("settings") === "1"
const wantsInvite = searchParams.get("invite") === "1"
- if (!wantsSettings && !wantsInvite) return
+ // The message controller is intentionally unmounted while mobile nav is
+ // visible, so it cannot consume its own `seq` command in that pane. Clean
+ // the one-shot command at the persistent layout boundary instead. Content
+ // routes leave it alone so the mounted controller can still open the
+ // requested message context before removing the parameter itself.
+ const wantsNavSeq =
+ resolveMobileZone(searchParams) === "nav" && searchParams.has("seq")
+ if (!wantsSettings && !wantsInvite && !wantsNavSeq) return
// These flags land on the bare `/c/channels/:serverId` URL
// (e.g. right-click a rail server → "Server settings"/"Invite to
@@ -258,10 +266,14 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
if (stillRedirecting) return
cancelPendingNavigation()
+ const search = searchParams.toString()
+ const currentHref = `${pathname}${search ? `?${search}` : ""}`
+ const withoutSettings = removeCommunityParam(currentHref, "settings")
+ const withoutInvite = removeCommunityParam(withoutSettings, "invite")
router.replace(
- hasChannel ? `/c/channels/${serverId}/${params.channelId}` : `/c/channels/${serverId}`,
+ wantsNavSeq ? removeCommunityParam(withoutInvite, "seq") : withoutInvite,
)
- }, [cancelPendingNavigation, searchParams, serverId, router, hasChannel, currentServer, params.channelId])
+ }, [cancelPendingNavigation, searchParams, pathname, router, hasChannel, currentServer])
const categories = useMemo(() => (currentServer?.categories ?? []).map((category) => ({
...category,
@@ -273,13 +285,6 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
})), [currentServer?.categories, forumSidebar.parentUnread])
const channelTree = useChannelTree(categories)
- const goHome = useCallback(() => {
- setMobileZone("nav")
- cancelPendingNavigation()
- router.push(pickMeLandingLocation(getLastMeLeaf()))
- }, [cancelPendingNavigation, router])
- const goServer = useCallback(() => { setMobileZone("nav") }, [])
-
const setActiveChannel = useCallback((id: string) => {
// Only navigate — do NOT eagerly set the store's currentChannelId here.
// The currently-mounted ChannelView is still keyed to the old channelId;
@@ -325,8 +330,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
(cache) => patchChannelUnread(cache, id, false),
)
}
- if (bp === "mobile") setMobileZone("messages")
- }, [bp, cancelPendingNavigation, channelTree, queryClient, router, serverId])
+ }, [cancelPendingNavigation, channelTree, queryClient, router, serverId])
const setActiveForumThread = useCallback((id: string) => {
markSwitch("channel", id)
@@ -334,8 +338,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
router.push(`/c/channels/${serverId}/${id}`)
removeForumSidebarUnreadChild(queryClient, serverId, id)
patchForumSidebarUnreadExact(queryClient, serverId, id, false)
- if (bp === "mobile") setMobileZone("messages")
- }, [bp, cancelPendingNavigation, queryClient, router, serverId])
+ }, [cancelPendingNavigation, queryClient, router, serverId])
const prefetchChannel = useCallback(
(id: string) => router.prefetch(`/c/channels/${serverId}/${id}`),
@@ -568,14 +571,10 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
<ShellFrame
view="server"
activeServerId={serverId}
- mobileZone={mobileZone}
- setMobileZone={setMobileZone}
sidebar={sidebar}
extraDialogs={<>{serverSettingsDialog}{iconCropDialog}</>}
onOpenActiveServerSettings={onSidebarOpenSettings}
onOpenActiveServerInvite={onRailOpenActiveInvite}
- goHome={goHome}
- goServer={goServer}
>
{children}
</ShellFrame>
diff --git a/src/web/src/app/c/me/layout.tsx b/src/web/src/app/c/me/layout.tsx
index d26907e62..e333b317f 100644
--- a/src/web/src/app/c/me/layout.tsx
+++ b/src/web/src/app/c/me/layout.tsx
@@ -1,12 +1,11 @@
"use client"
-import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react"
+import { useCallback, useEffect, useMemo, type ReactNode } from "react"
import { useQueryClient } from "@tanstack/react-query"
-import { usePathname, useRouter, useParams } from "next/navigation"
-import { useBreakpoint } from "@/hooks/use-mobile"
+import { usePathname, useRouter, useParams, useSearchParams } from "next/navigation"
import { ShellFrame } from "@/components/community/shell/shell-frame"
+import { resolveMobileZone, withMobileZone } from "@/components/community/shell/mobile-zone"
import { DmSidebar } from "@/components/community/channels/dm-sidebar"
-import type { MobileZone } from "@/components/community/shell/mobile-zone"
import { useCommunityStore, useCurrentChannelId } from "@/stores/community"
import { useDms } from "@/hooks/community/use-dms"
import { useFriends, useFriendsPresence } from "@/hooks/community/use-friends"
@@ -18,7 +17,6 @@ import {
getLastMeLeaf,
ME_ROOT,
meLeafFromPathname,
- pickMeLandingLocation,
resolveMeLocationStatus,
setLastMeLocation,
} from "@/lib/community/last-me-location"
@@ -27,8 +25,8 @@ import {
// and no `[serverId]` param — everything is scoped to the current user.
export default function MeLayout({ children }: { children: ReactNode }) {
const router = useRouter()
- const bp = useBreakpoint()
const pathname = usePathname()
+ const searchParams = useSearchParams()
const params = useParams<{ dmId?: string }>()
const { dms: rawDms, isLoading: dmsLoading, isSuccess: dmsReady } = useDms()
const onlineUserIds = useOnlineUserIds()
@@ -86,10 +84,8 @@ export default function MeLayout({ children }: { children: ReactNode }) {
if (meLocationStatus !== "stale") return
if (getLastMeLeaf() === meLeafFromPathname(pathname)) clearLastMeLocation()
cancelPendingNavigation()
- router.replace(ME_ROOT)
- }, [cancelPendingNavigation, meLocationStatus, pathname, router])
-
- const [mobileZone, setMobileZone] = useState<MobileZone>(() => (hasDm ? "messages" : "nav"))
+ router.replace(withMobileZone(ME_ROOT, resolveMobileZone(searchParams)))
+ }, [cancelPendingNavigation, meLocationStatus, pathname, router, searchParams])
// Mirror channel sidebar-click behavior (channels/layout.tsx:226-236): do
// NOT eagerly mark the DM read on click. That fires a bodyless
@@ -114,42 +110,31 @@ export default function MeLayout({ children }: { children: ReactNode }) {
)
cancelPendingNavigation()
router.push(`/c/me/${id}`)
- if (bp === "mobile") setMobileZone("messages")
- }, [bp, cancelPendingNavigation, queryClient, router])
+ }, [cancelPendingNavigation, queryClient, router])
const onShowFriends = useCallback(() => {
useCommunityStore.getState().setCurrentChannelId(null)
cancelPendingNavigation()
router.push("/c/me")
- if (bp === "mobile") setMobileZone("messages")
- }, [bp, cancelPendingNavigation, router])
+ }, [cancelPendingNavigation, router])
const onShowMachines = useCallback(() => {
useCommunityStore.getState().setCurrentChannelId(null)
cancelPendingNavigation()
router.push("/c/me/machines")
- if (bp === "mobile") setMobileZone("messages")
- }, [bp, cancelPendingNavigation, router])
+ }, [cancelPendingNavigation, router])
const onShowBots = useCallback(() => {
useCommunityStore.getState().setCurrentChannelId(null)
cancelPendingNavigation()
router.push("/c/me/bots")
- if (bp === "mobile") setMobileZone("messages")
- }, [bp, cancelPendingNavigation, router])
+ }, [cancelPendingNavigation, router])
const prefetchDm = useCallback((id: string) => router.prefetch(`/c/me/${id}`), [router])
const prefetchFriends = useCallback(() => router.prefetch("/c/me"), [router])
const prefetchMachines = useCallback(() => router.prefetch("/c/me/machines"), [router])
const prefetchBots = useCallback(() => router.prefetch("/c/me/bots"), [router])
- const goHome = useCallback(() => {
- setMobileZone("nav")
- cancelPendingNavigation()
- router.push(pickMeLandingLocation(getLastMeLeaf()))
- }, [cancelPendingNavigation, router])
- const goServer = useCallback(() => { setMobileZone("nav") }, [])
-
const blockedUserIds = useMemo(
() => new Set(blocked.map((b) => b.userId ?? b.id)),
[blocked],
@@ -179,11 +164,7 @@ export default function MeLayout({ children }: { children: ReactNode }) {
<ShellFrame
view="dm"
activeServerId={undefined}
- mobileZone={mobileZone}
- setMobileZone={setMobileZone}
sidebar={sidebar}
- goHome={goHome}
- goServer={goServer}
>
{children}
</ShellFrame>
diff --git a/src/web/src/components/community/channels/channel-route.text-scroll-target.test.ts b/src/web/src/components/community/channels/channel-route.text-scroll-target.test.ts
index 61065615a..05b1879b8 100644
--- a/src/web/src/components/community/channels/channel-route.text-scroll-target.test.ts
+++ b/src/web/src/components/community/channels/channel-route.text-scroll-target.test.ts
@@ -7,7 +7,8 @@ import { MessageList } from "../messages/message-list"
import { useChannelMemberViewModel } from "../members/channel-member-view-model"
import { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"
-const { mockRouteModel, mockMemberViewModel } = vi.hoisted(() => ({
+const { mockRouteModel, mockMemberViewModel, mockRouter } = vi.hoisted(() => ({
+ mockRouter: { push: vi.fn(), replace: vi.fn(), back: vi.fn() },
mockRouteModel: {
server: {
id: "server_1",
@@ -41,8 +42,8 @@ const { mockRouteModel, mockMemberViewModel } = vi.hoisted(() => ({
}))
vi.mock("next/navigation", () => ({
- useRouter: () => ({ push: vi.fn(), replace: vi.fn(), back: vi.fn() }),
- useSearchParams: () => ({ get: (key: string) => key === "msg" ? "m_target" : null }),
+ useRouter: () => mockRouter,
+ useSearchParams: () => new URLSearchParams("msg=m_target&pane=nav&keep=1"),
}))
vi.mock("sonner", () => ({ toast: vi.fn() }))
vi.mock("@/lib/api/client", () => ({ apiFetch: vi.fn(), toastApiError: vi.fn() }))
@@ -251,6 +252,10 @@ describe("ChannelRoute message surface ownership", () => {
})
expect(mockedUseChannelMessageFeed).toHaveBeenCalledTimes(1)
+ expect(mockRouter.replace).toHaveBeenCalledWith(
+ "/c/channels/server_1/channel_1?pane=nav&keep=1",
+ { scroll: false },
+ )
expect(mockedUseChannelMessageFeed).toHaveBeenCalledWith(expect.objectContaining({ channelId: "channel_1" }))
expect(mockedMessageList.mock.calls.at(-1)?.[0].scrollToMessageId).toBe("m_target")
diff --git a/src/web/src/components/community/channels/channel-route.tsx b/src/web/src/components/community/channels/channel-route.tsx
index d8b67d502..a8e320074 100644
--- a/src/web/src/components/community/channels/channel-route.tsx
+++ b/src/web/src/components/community/channels/channel-route.tsx
@@ -25,6 +25,7 @@ import { useChannelRouteModel } from "@/hooks/community/use-channel-route-model"
import { useForumOpenerHint } from "@/hooks/community/use-forum-opener-hint"
import { useNotificationSettings } from "@/hooks/community/use-notification-settings"
import { useSetChannelNotif } from "@/hooks/community/mutations"
+import { removeCommunityParam } from "@/components/community/shell/mobile-zone"
/**
* /c/channels/:serverId/:channelId
@@ -114,7 +115,6 @@ export function ChannelRoute({ serverParam, channelId }: { serverParam: string;
const { mutate: setChannelNotif } = useSetChannelNotif()
const goBack = useCallback(() => { uiHandlers.goBackMobile?.() }, [uiHandlers])
- const goRouteBack = useCallback(() => { router.back() }, [router])
const setNotificationLevel = useCallback((level: ChannelNotifLevel) => {
setChannelNotif({ channelId, level }, {
onError: (error) => toastApiError(error, "Failed to update notification level"),
@@ -126,7 +126,9 @@ export function ChannelRoute({ serverParam, channelId }: { serverParam: string;
// message controller for this mount; this only cleans the address.
useEffect(() => {
if (!jumpTargetId) return
- router.replace(`/c/channels/${serverParam}/${channelId}`, { scroll: false })
+ const search = searchParams.toString()
+ const href = `/c/channels/${serverParam}/${channelId}${search ? `?${search}` : ""}`
+ router.replace(removeCommunityParam(href, "msg"), { scroll: false })
// eslint-disable-next-line react-hooks/exhaustive-deps -- run once for this mount's jump
}, [])
@@ -200,8 +202,7 @@ export function ChannelRoute({ serverParam, channelId }: { serverParam: string;
: undefined}
notificationLevel={(channelNotif[channelId] as ChannelNotifLevel) ?? USE_SERVER_DEFAULT}
onSetNotificationLevel={setNotificationLevel}
- onBack={bp === "mobile" ? goRouteBack : undefined}
- onLoadingBack={bp === "mobile" ? goBack : undefined}
+ onBack={bp === "mobile" ? goBack : undefined}
composerMembers={composerMembers}
onSearchComposerMembers={onSearchComposerMembers}
channelRefCandidates={channelRefCandidates}
diff --git a/src/web/src/components/community/channels/thread-channel-surface.test.ts b/src/web/src/components/community/channels/thread-channel-surface.test.ts
index 2f15b0d42..3becb9dd7 100644
--- a/src/web/src/components/community/channels/thread-channel-surface.test.ts
+++ b/src/web/src/components/community/channels/thread-channel-surface.test.ts
@@ -2,7 +2,7 @@ import React from "react"
import TestRenderer, { act } from "react-test-renderer"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { ThreadChannelSurface } from "./thread-channel-surface"
-import { ChannelHeader } from "./channel-header"
+import { ChannelHeader, ChannelHeaderSkeleton } from "./channel-header"
import { CommunityPanelSheet } from "../shell/community-panel-sheet"
import { Composer } from "../messages/composer"
import { MessageContextSheet } from "../messages/message-context-sheet"
@@ -125,6 +125,7 @@ vi.mock("@/components/community/messages/message-channel-controller", () => ({
}))
const mockedChannelHeader = vi.mocked(ChannelHeader)
+const mockedChannelHeaderSkeleton = vi.mocked(ChannelHeaderSkeleton)
const mockedCommunityPanelSheet = vi.mocked(CommunityPanelSheet)
const mockedComposer = vi.mocked(Composer)
const mockedMessageContextSheet = vi.mocked(MessageContextSheet)
@@ -173,7 +174,6 @@ function surfaceProps(overrides: Record<string, unknown> = {}) {
notificationLevel: "default" as const,
onSetNotificationLevel: vi.fn(),
onBack: vi.fn(),
- onLoadingBack: vi.fn(),
composerMembers: [{ id: "member_1", userId: "member_1", name: "Alice" }],
onSearchComposerMembers: vi.fn(),
channelRefCandidates: [{ id: "parent_1", name: "general", serverId: "server_1", serverName: "Server" }],
@@ -270,6 +270,25 @@ describe("ThreadChannelSurface ownership", () => {
expect(mocks.setReplyTo).toHaveBeenCalledWith(null)
})
+ it("uses the same mobile Back handler while loading and after hydration", () => {
+ const onBack = vi.fn()
+ mockedUseChannelMessageFeed.mockReturnValue(feed({ isLoading: true }))
+ let renderer!: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(renderSurface({ onBack }))
+ })
+ const loadingBack = mockedChannelHeaderSkeleton.mock.calls.at(-1)![0].onBack
+ expect(loadingBack).toBe(onBack)
+ act(() => loadingBack?.())
+
+ mockedUseChannelMessageFeed.mockReturnValue(feed({ isLoading: false }))
+ act(() => renderer.update(renderSurface({ onBack })))
+ const hydratedBack = mockedChannelHeader.mock.calls.at(-1)![0].onBack
+ expect(hydratedBack).toBe(onBack)
+ act(() => hydratedBack?.())
+ expect(onBack).toHaveBeenCalledTimes(2)
+ })
+
it("preserves regular-thread breadcrumb, rename, panel, and dialog wiring", async () => {
const props = surfaceProps()
let renderer: TestRenderer.ReactTestRenderer
diff --git a/src/web/src/components/community/channels/thread-channel-surface.tsx b/src/web/src/components/community/channels/thread-channel-surface.tsx
index 4fcfe19f6..024400011 100644
--- a/src/web/src/components/community/channels/thread-channel-surface.tsx
+++ b/src/web/src/components/community/channels/thread-channel-surface.tsx
@@ -38,7 +38,6 @@ export function ThreadChannelSurface({
notificationLevel,
onSetNotificationLevel,
onBack,
- onLoadingBack,
composerMembers,
onSearchComposerMembers,
channelRefCandidates,
@@ -65,7 +64,6 @@ export function ThreadChannelSurface({
notificationLevel: ChannelNotifLevel
onSetNotificationLevel: (level: ChannelNotifLevel) => void
onBack?: () => void
- onLoadingBack?: () => void
composerMembers: ComponentProps<typeof Composer>["members"]
onSearchComposerMembers: ComponentProps<typeof Composer>["onSearchMembers"]
channelRefCandidates: ComponentProps<typeof Composer>["channelRefCandidates"]
@@ -108,8 +106,8 @@ export function ThreadChannelSurface({
router.push(`/c/channels/${serverParam}/${parentChannelId}`)
return
}
- router.back()
- }, [parentChannelId, router, serverParam])
+ onBack?.()
+ }, [onBack, parentChannelId, router, serverParam])
const rename = parentIsForum && parentChannelId && parentMessageId && childCreatorId === viewer.id
? async (name: string) => {
try {
@@ -144,7 +142,7 @@ export function ThreadChannelSurface({
if (feed.isLoading) {
return (
<>
- <ChannelHeaderSkeleton onBack={onLoadingBack} />
+ <ChannelHeaderSkeleton onBack={onBack} />
<main className="flex min-h-0 min-w-0 flex-1 flex-col">
<MessageList key={channelId} channel="" messages={[]} loading onOpenThread={ignoreNestedThread} />
<ComposerSkeleton />
diff --git a/src/web/src/components/community/machines/machine-list.tsx b/src/web/src/components/community/machines/machine-list.tsx
index 41c840fa1..1a6117ec0 100644
--- a/src/web/src/components/community/machines/machine-list.tsx
+++ b/src/web/src/components/community/machines/machine-list.tsx
@@ -44,6 +44,7 @@ import {
updateCommunityOnboardingResources,
useCommunityOnboarding,
} from "@/lib/community-onboarding"
+import { removeCommunityParam } from "@/components/community/shell/mobile-zone"
// Loading placeholder shaped like a real MachineCard (size-10 rounded-xl icon +
// name row + meta lines + trailing kebab slot) so the list doesn't reflow when
@@ -227,7 +228,9 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {
handledReconnectRef.current = reconnectId
const machine = machines.find((m) => m.id === reconnectId)
if (machine) openReconnect(machine)
- router.replace("/c/me/machines")
+ const search = searchParams.toString()
+ const href = `/c/me/machines${search ? `?${search}` : ""}`
+ router.replace(removeCommunityParam(href, "reconnect"))
}, [searchParams, machines, machinesLoading, openReconnect, router])
const closePair = useCallback((open: boolean) => {
diff --git a/src/web/src/components/community/messages/message-channel-controller-state.test.ts b/src/web/src/components/community/messages/message-channel-controller-state.test.ts
index 3bd23aaac..8c6141246 100644
--- a/src/web/src/components/community/messages/message-channel-controller-state.test.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-state.test.ts
@@ -50,7 +50,9 @@ const mocks = vi.hoisted(() => {
vi.mock("next/navigation", () => ({
useRouter: () => mocks.router,
- useSearchParams: () => ({ get: (key: string) => key === "seq" ? mocks.seq : null }),
+ useSearchParams: () => new URLSearchParams(
+ mocks.seq ? `seq=${mocks.seq}&pane=nav&keep=1` : "",
+ ),
}))
vi.mock("@/lib/api/client", () => ({
apiFetch: mocks.apiFetch,
@@ -314,7 +316,7 @@ describe("useMessageChannelController", () => {
serverId: "server_1", channelId: "channel_1", label: "general", seq: 7,
})
expect(mocks.router.replace).toHaveBeenCalledWith(
- "/c/channels/server_1/channel_1", { scroll: false },
+ "/c/channels/server_1/channel_1?pane=nav&keep=1", { scroll: false },
)
expect(mocks.storeState.registerUiHandlers).toHaveBeenCalledWith({
jumpToSeq: expect.any(Function), openMessageContext: expect.any(Function),
diff --git a/src/web/src/components/community/messages/message-channel-controller-state.ts b/src/web/src/components/community/messages/message-channel-controller-state.ts
index 0d59d2844..252ed2410 100644
--- a/src/web/src/components/community/messages/message-channel-controller-state.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-state.ts
@@ -31,6 +31,7 @@ import {
acceptChannelMessage,
runAcceptedMessageIntent,
} from "./message-channel-controller-send"
+import { removeCommunityParam } from "@/components/community/shell/mobile-zone"
import type {
MessageChannelControllerProps,
MessageChannelControllerValue,
@@ -182,13 +183,15 @@ export function useMessageChannelController({
}, [jumpToSeq, openMessageContext])
const seqParam = searchParams.get("seq")
+ const searchParamsString = searchParams.toString()
useEffect(() => {
if (!seqParam) return
const seq = Number(seqParam)
if (!Number.isFinite(seq)) return
setContextTarget({ serverId, channelId, label: channelName, seq })
- router.replace(`/c/channels/${serverParam}/${channelId}`, { scroll: false })
- }, [seqParam, serverId, channelId, channelName, router, serverParam])
+ const href = `/c/channels/${serverParam}/${channelId}${searchParamsString ? `?${searchParamsString}` : ""}`
+ router.replace(removeCommunityParam(href, "seq"), { scroll: false })
+ }, [seqParam, serverId, channelId, channelName, router, searchParamsString, serverParam])
const messageScope = useMemo(
() => ({ kind: "channel" as const, id: channelId, serverId }),
diff --git a/src/web/src/components/community/shell/mobile-zone.test.ts b/src/web/src/components/community/shell/mobile-zone.test.ts
index cb5a27f30..d2513d84b 100644
--- a/src/web/src/components/community/shell/mobile-zone.test.ts
+++ b/src/web/src/components/community/shell/mobile-zone.test.ts
@@ -1,45 +1,58 @@
-import { describe, it, expect } from "vitest"
-import { initialMobileZone, nextMobileZone } from "./mobile-zone"
-import type { MobileZone } from "@/components/community/shell/mobile-zone"
-
-describe("initialMobileZone", () => {
- it("returns 'nav' when no channel is in the URL", () => {
- expect(initialMobileZone(false)).toBe("nav")
- })
-
- it("returns 'messages' when a channel is in the URL (deep link)", () => {
- expect(initialMobileZone(true)).toBe("messages")
- })
+import { describe, expect, it } from "vitest"
+import {
+ removeCommunityParam,
+ resolveMobileZone,
+ withMobileZone,
+ type MobileZone,
+} from "./mobile-zone"
+
+describe("resolveMobileZone", () => {
+ it.each([
+ ["", "messages"],
+ ["pane=nav", "nav"],
+ ["pane=messages", "messages"],
+ ["pane=content", "messages"],
+ ["pane=", "messages"],
+ ["pane=NAV", "messages"],
+ ["seq=12&pane=nav", "nav"],
+ ] satisfies Array<[string, MobileZone]>)(
+ "maps %j to %s",
+ (query, expected) => {
+ expect(resolveMobileZone(new URLSearchParams(query))).toBe(expected)
+ },
+ )
})
-describe("nextMobileZone", () => {
- const zones: MobileZone[] = ["nav", "messages"]
-
- it("setActiveChannel → 'messages'", () => {
- for (const z of zones) expect(nextMobileZone(z, { type: "setActiveChannel" })).toBe("messages")
- })
-
- it("enterDm → 'messages'", () => {
- for (const z of zones) expect(nextMobileZone(z, { type: "enterDm" })).toBe("messages")
- })
-
- it("onShowFriends → 'messages'", () => {
- for (const z of zones) expect(nextMobileZone(z, { type: "onShowFriends" })).toBe("messages")
- })
-
- it("onShowMachines → 'messages'", () => {
- for (const z of zones) expect(nextMobileZone(z, { type: "onShowMachines" })).toBe("messages")
- })
-
- it("goBackMobile from 'messages' → 'nav'", () => {
- expect(nextMobileZone("messages", { type: "goBackMobile" })).toBe("nav")
- })
-
- it("goHome from any zone → 'nav'", () => {
- for (const z of zones) expect(nextMobileZone(z, { type: "goHome" })).toBe("nav")
- })
+describe("withMobileZone", () => {
+ it.each([
+ ["/c/me/dm-1", "nav", "/c/me/dm-1?pane=nav"],
+ ["/c/me/dm-1?seq=12#message", "nav", "/c/me/dm-1?seq=12&pane=nav#message"],
+ ["/c/me/dm-1?pane=messages&seq=12", "nav", "/c/me/dm-1?pane=nav&seq=12"],
+ ["/c/me/dm-1?pane=nav&seq=12#message", "messages", "/c/me/dm-1?seq=12#message"],
+ ["/c/me/dm-1?seq=12#message", "messages", "/c/me/dm-1?seq=12#message"],
+ ["/c/me/dm-1?pane=nav#message", "messages", "/c/me/dm-1#message"],
+ ["?invite=1#dialog", "nav", "?invite=1&pane=nav#dialog"],
+ ["#message", "nav", "?pane=nav#message"],
+ ] satisfies Array<[string, MobileZone, string]>)(
+ "updates %j to the %s zone without dropping other URL state",
+ (href, zone, expected) => {
+ expect(withMobileZone(href, zone)).toBe(expected)
+ },
+ )
+})
- it("goServer from any zone → 'nav'", () => {
- for (const z of zones) expect(nextMobileZone(z, { type: "goServer" })).toBe("nav")
- })
+describe("removeCommunityParam", () => {
+ it.each([
+ ["/c/channels/s-1/c-1?msg=m-1&pane=nav#message", "msg", "/c/channels/s-1/c-1?pane=nav#message"],
+ ["/c/me/machines?pane=nav&reconnect=machine-1&invite=1", "reconnect", "/c/me/machines?pane=nav&invite=1"],
+ ["/c/me/dm-1?seq=12&seq=13&pane=nav", "seq", "/c/me/dm-1?pane=nav"],
+ ["/c/me/dm-1?pane=nav#message", "missing", "/c/me/dm-1?pane=nav#message"],
+ ["/c/me/dm-1?msg=m-1#message", "msg", "/c/me/dm-1#message"],
+ ["/c/me/dm-1#message", "msg", "/c/me/dm-1#message"],
+ ])(
+ "removes only %j from %j",
+ (href, key, expected) => {
+ expect(removeCommunityParam(href, key)).toBe(expected)
+ },
+ )
})
diff --git a/src/web/src/components/community/shell/mobile-zone.ts b/src/web/src/components/community/shell/mobile-zone.ts
index 69a24a619..5c5780b55 100644
--- a/src/web/src/components/community/shell/mobile-zone.ts
+++ b/src/web/src/components/community/shell/mobile-zone.ts
@@ -1,28 +1,44 @@
export type MobileZone = "nav" | "messages"
-export type MobileZoneAction =
- | { type: "setActiveChannel" }
- | { type: "enterDm" }
- | { type: "onShowFriends" }
- | { type: "onShowMachines" }
- | { type: "goBackMobile" }
- | { type: "goHome" }
- | { type: "goServer" }
-
-export function initialMobileZone(hasChannel: boolean): MobileZone {
- return hasChannel ? "messages" : "nav"
+const MOBILE_ZONE_QUERY_KEY = "pane"
+
+type SearchParamsReader = {
+ get: (name: string) => string | null
+}
+
+export function resolveMobileZone(searchParams: SearchParamsReader): MobileZone {
+ return searchParams.get(MOBILE_ZONE_QUERY_KEY) === "nav" ? "nav" : "messages"
+}
+
+export function withMobileZone(href: string, zone: MobileZone): string {
+ return updateHrefSearchParams(href, (searchParams) => {
+ if (zone === "nav") searchParams.set(MOBILE_ZONE_QUERY_KEY, "nav")
+ else searchParams.delete(MOBILE_ZONE_QUERY_KEY)
+ })
}
-export function nextMobileZone(_state: MobileZone, action: MobileZoneAction): MobileZone {
- switch (action.type) {
- case "setActiveChannel":
- case "enterDm":
- case "onShowFriends":
- case "onShowMachines":
- return "messages"
- case "goBackMobile":
- case "goHome":
- case "goServer":
- return "nav"
- }
+export function removeCommunityParam(href: string, key: string): string {
+ return updateHrefSearchParams(href, (searchParams) => {
+ searchParams.delete(key)
+ })
+}
+
+function updateHrefSearchParams(
+ href: string,
+ update: (searchParams: URLSearchParams) => void,
+): string {
+ const hashIndex = href.indexOf("#")
+ const hash = hashIndex === -1 ? "" : href.slice(hashIndex)
+ const hrefWithoutHash = hashIndex === -1 ? href : href.slice(0, hashIndex)
+ const queryIndex = hrefWithoutHash.indexOf("?")
+ const pathname = queryIndex === -1
+ ? hrefWithoutHash
+ : hrefWithoutHash.slice(0, queryIndex)
+ const query = queryIndex === -1 ? "" : hrefWithoutHash.slice(queryIndex + 1)
+ const searchParams = new URLSearchParams(query)
+
+ update(searchParams)
+
+ const nextQuery = searchParams.toString()
+ return `${pathname}${nextQuery ? `?${nextQuery}` : ""}${hash}`
}
diff --git a/src/web/src/components/community/shell/server-rail.tsx b/src/web/src/components/community/shell/server-rail.tsx
index 5e767ad58..a2b9210b9 100644
--- a/src/web/src/components/community/shell/server-rail.tsx
+++ b/src/web/src/components/community/shell/server-rail.tsx
@@ -18,7 +18,6 @@ import { CreateServerDialog } from "../settings/create-server-dialog"
import { useRailOrder, isFolderKey, extractFolderId } from "./use-rail-order"
import { SeededBackdrop } from "@/components/avatar"
import type { Server, CommunityFolder } from "@/lib/community/models/navigation"
-import type { MobileZone } from "@/components/community/shell/mobile-zone"
import type { View } from "@/components/community/shell/shell-types"
import {
completeCommunityOnboarding,
@@ -26,7 +25,7 @@ import {
} from "@/lib/community-onboarding"
export const ServerRail = memo(function ServerRail({
- servers, folders, activeServerId: activeServerIdProp, serversLoading, setMobileZone, view, bottomInset,
+ servers, folders, activeServerId: activeServerIdProp, serversLoading, view, bottomInset,
onHome, onHomePrefetch, onServer, onServerNavigate, onServerPrefetch, onCreateServer, onLeaveServer,
onOpenSettings, onOpenInvitePopover, onUngroupFolder, onReorderRail, onReorderFolders, onFolderItemsChange, onDragCreateFolder,
}: {
@@ -34,12 +33,11 @@ export const ServerRail = memo(function ServerRail({
folders: CommunityFolder[]
activeServerId?: string
serversLoading?: boolean
- setMobileZone?: (z: MobileZone) => void
view: View
bottomInset?: number
onHome: () => void
onHomePrefetch?: () => void
- onServer: () => void
+ onServer?: () => void
onServerNavigate?: (id: string) => void
onServerPrefetch?: (id: string) => void
onCreateServer?: (name: string, icon?: File) => void
@@ -78,7 +76,7 @@ export const ServerRail = memo(function ServerRail({
const [createOpen, setCreateOpen] = useState(false)
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }))
- const pickServer = (id: string) => { setActiveId(id); onServer(); onServerNavigate?.(id); setMobileZone?.("nav") }
+ const pickServer = (id: string) => { setActiveId(id); onServer?.(); onServerNavigate?.(id) }
const serverById = useMemo(() => new Map(servers.map((s) => [s.id, s])), [servers])
const folderById = useMemo(() => new Map(folders.map((f) => [f.id, f])), [folders])
diff --git a/src/web/src/components/community/shell/shell-frame-contract.test.ts b/src/web/src/components/community/shell/shell-frame-contract.test.ts
index fe9d2bc2a..a79e1dfb2 100644
--- a/src/web/src/components/community/shell/shell-frame-contract.test.ts
+++ b/src/web/src/components/community/shell/shell-frame-contract.test.ts
@@ -24,11 +24,10 @@ describe("ShellFrame public contract", () => {
'import { ShellFrame } from "@/components/community/shell/shell-frame"',
)
expect(source).toContain("<ShellFrame")
- expect(source).toContain("mobileZone={mobileZone}")
- expect(source).toContain("setMobileZone={setMobileZone}")
expect(source).toContain("sidebar={sidebar}")
- expect(source).toContain("goHome={goHome}")
- expect(source).toContain("goServer={goServer}")
+ expect(source).not.toContain("mobileZone={mobileZone}")
+ expect(source).not.toContain("setMobileZone={setMobileZone}")
+ expect(source).not.toContain("useState<MobileZone>")
}
expect(channels).toContain('view="server"')
expect(channels).toContain("activeServerId={serverId}")
@@ -43,6 +42,7 @@ describe("ShellFrame public contract", () => {
expect(source).toContain("useShellRailController")
expect(source).toContain("useShellProfileController")
expect(source).toContain("useShellInboxController")
+ expect(source).toContain("resolveMobileZone(searchParams)")
expect(source).toContain("<ShellFrameView")
expect(source).not.toContain("<ServerRail")
expect(source).not.toContain("<ProfileCard")
diff --git a/src/web/src/components/community/shell/shell-frame-types.ts b/src/web/src/components/community/shell/shell-frame-types.ts
index 521fc7c07..ebb850f89 100644
--- a/src/web/src/components/community/shell/shell-frame-types.ts
+++ b/src/web/src/components/community/shell/shell-frame-types.ts
@@ -1,19 +1,14 @@
import type { ReactNode } from "react"
-import type { MobileZone } from "./mobile-zone"
import type { View } from "./shell-types"
export type ShellFrameProps = {
view: View
activeServerId: string | undefined
- mobileZone: MobileZone
- setMobileZone: (zone: MobileZone) => void
sidebar: (opts?: { noHeader?: boolean }) => ReactNode
children: ReactNode
extraDialogs?: ReactNode
onOpenActiveServerSettings?: () => void
onOpenActiveServerInvite?: () => void
- goHome: () => void
- goServer: () => void
}
export type ShellRouter = {
diff --git a/src/web/src/components/community/shell/shell-frame-view.tsx b/src/web/src/components/community/shell/shell-frame-view.tsx
index 875661d29..9d5f5ec70 100644
--- a/src/web/src/components/community/shell/shell-frame-view.tsx
+++ b/src/web/src/components/community/shell/shell-frame-view.tsx
@@ -14,13 +14,15 @@ import {
desktopUserBarOverlayWidth,
} from "./shell-frame-geometry"
import type { Breakpoint } from "@/hooks/use-mobile"
+import type { MobileZone } from "./mobile-zone"
import type { ShellFrameProps } from "./shell-frame-types"
import type { useShellRailController } from "./use-shell-rail-controller"
import type { useShellProfileController } from "./use-shell-profile-controller"
import type { useShellInboxController } from "./use-shell-inbox-controller"
-type Props = Pick<ShellFrameProps, "mobileZone" | "sidebar" | "children" | "extraDialogs"> & {
+type Props = Pick<ShellFrameProps, "sidebar" | "children" | "extraDialogs"> & {
breakpoint: Breakpoint
+ mobileZone: MobileZone
cancelPendingNavigation: () => void
rail: ReturnType<typeof useShellRailController>
profile: ReturnType<typeof useShellProfileController>
diff --git a/src/web/src/components/community/shell/shell-frame.test.ts b/src/web/src/components/community/shell/shell-frame.test.ts
index 518eb0960..eeebdfa0c 100644
--- a/src/web/src/components/community/shell/shell-frame.test.ts
+++ b/src/web/src/components/community/shell/shell-frame.test.ts
@@ -1,6 +1,6 @@
import { createElement } from "react"
import TestRenderer, { act } from "react-test-renderer"
-import { beforeEach, describe, expect, it, vi } from "vitest"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { ShellFrame } from "./shell-frame"
const mocks = vi.hoisted(() => {
@@ -14,8 +14,10 @@ const mocks = vi.hoisted(() => {
return {
onboarding: { current: { status: "active", stage: "server" } as unknown },
pathname: { current: "/c/channels/s1" },
+ searchParams: { current: new URLSearchParams() },
+ breakpoint: { current: "desktop" },
+ replaceState: vi.fn(),
registerUiHandlers: vi.fn(),
- setMobileZone: vi.fn(),
handlers,
rail: {
railProps: {},
@@ -34,9 +36,10 @@ const mocks = vi.hoisted(() => {
vi.mock("next/navigation", () => ({
useRouter: () => ({ push: vi.fn(), replace: vi.fn(), prefetch: vi.fn() }),
usePathname: () => mocks.pathname.current,
+ useSearchParams: () => mocks.searchParams.current,
}))
vi.mock("@tanstack/react-query", () => ({ useQueryClient: () => ({}) }))
-vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "desktop" }))
+vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => mocks.breakpoint.current }))
vi.mock("@/lib/community-onboarding", () => ({
useCommunityOnboarding: () => mocks.onboarding.current,
}))
@@ -61,40 +64,56 @@ vi.mock("./shell-frame-view", () => ({
const baseProps = {
view: "server" as const,
activeServerId: "s1",
- mobileZone: "messages" as const,
- setMobileZone: mocks.setMobileZone,
sidebar: () => createElement("sidebar"),
- goHome: vi.fn(),
- goServer: vi.fn(),
}
describe("ShellFrame orchestration", () => {
beforeEach(() => {
mocks.onboarding.current = { status: "active", stage: "server" }
mocks.pathname.current = "/c/channels/s1"
+ mocks.searchParams.current = new URLSearchParams()
+ mocks.breakpoint.current = "desktop"
mocks.registerUiHandlers.mockClear()
- mocks.setMobileZone.mockClear()
+ mocks.replaceState.mockClear()
+ vi.stubGlobal("window", {
+ history: { replaceState: mocks.replaceState },
+ location: { hash: "" },
+ })
})
- it("maps active onboarding stages to the existing mobile zones", async () => {
+ afterEach(() => vi.unstubAllGlobals())
+
+ it("derives the pane from the current URL and tracks search-param updates", async () => {
+ mocks.searchParams.current = new URLSearchParams("pane=nav")
let renderer!: TestRenderer.ReactTestRenderer
await act(async () => {
renderer = TestRenderer.create(createElement(ShellFrame, baseProps))
})
- expect(mocks.setMobileZone).toHaveBeenLastCalledWith("nav")
+ expect(renderer.root.findByType("shell-frame-view").props.mobileZone).toBe("nav")
- mocks.onboarding.current = { status: "active", stage: "channel" }
+ mocks.searchParams.current = new URLSearchParams()
await act(async () => {
renderer.update(createElement(ShellFrame, baseProps, "next"))
})
- expect(mocks.setMobileZone).toHaveBeenLastCalledWith("messages")
+ expect(renderer.root.findByType("shell-frame-view").props.mobileZone).toBe("messages")
+ })
- mocks.onboarding.current = { status: "complete" }
- mocks.setMobileZone.mockClear()
+ it("commits onboarding pane changes through native history on mobile", async () => {
+ mocks.breakpoint.current = "mobile"
+ let renderer!: TestRenderer.ReactTestRenderer
await act(async () => {
- renderer.update(createElement(ShellFrame, baseProps, "done"))
+ renderer = TestRenderer.create(createElement(ShellFrame, baseProps))
})
- expect(mocks.setMobileZone).not.toHaveBeenCalled()
+ expect(mocks.replaceState).toHaveBeenLastCalledWith(
+ null, "", "/c/channels/s1?pane=nav",
+ )
+
+ mocks.searchParams.current = new URLSearchParams("pane=nav")
+ mocks.onboarding.current = { status: "active", stage: "channel" }
+ await act(async () => {
+ renderer.update(createElement(ShellFrame, baseProps, "channel"))
+ })
+ expect(mocks.replaceState).toHaveBeenLastCalledWith(null, "", "/c/channels/s1")
})
it("registers exactly six stable UI handlers", async () => {
@@ -112,10 +131,21 @@ describe("ShellFrame orchestration", () => {
"previewImage",
])
+ mocks.searchParams.current = new URLSearchParams("msg=m1")
+ Object.assign(window.location, { hash: "#anchor" })
+ await act(async () => {
+ renderer.update(createElement(ShellFrame, baseProps, "message"))
+ })
+ const withMessage = mocks.registerUiHandlers.mock.calls.at(-1)?.[0]
+ withMessage.goBackMobile()
+ expect(mocks.replaceState).toHaveBeenLastCalledWith(
+ null, "", "/c/channels/s1?msg=m1&pane=nav#anchor",
+ )
+
await act(async () => {
renderer.update(createElement(ShellFrame, baseProps, "rerender"))
})
const second = mocks.registerUiHandlers.mock.calls.at(-1)?.[0]
- for (const key of Object.keys(first)) expect(second[key]).toBe(first[key])
+ for (const key of Object.keys(withMessage)) expect(second[key]).toBe(withMessage[key])
})
})
diff --git a/src/web/src/components/community/shell/shell-frame.tsx b/src/web/src/components/community/shell/shell-frame.tsx
index ed0d4e6a6..50f3c5a2f 100644
--- a/src/web/src/components/community/shell/shell-frame.tsx
+++ b/src/web/src/components/community/shell/shell-frame.tsx
@@ -1,7 +1,7 @@
"use client"
import { useCallback, useEffect } from "react"
-import { usePathname, useRouter } from "next/navigation"
+import { usePathname, useRouter, useSearchParams } from "next/navigation"
import { useQueryClient } from "@tanstack/react-query"
import { useBreakpoint } from "@/hooks/use-mobile"
import { useCommunityOnboarding } from "@/lib/community-onboarding"
@@ -10,6 +10,7 @@ import { ShellFrameView } from "./shell-frame-view"
import { useShellRailController } from "./use-shell-rail-controller"
import { useShellProfileController } from "./use-shell-profile-controller"
import { useShellInboxController } from "./use-shell-inbox-controller"
+import { resolveMobileZone, withMobileZone } from "./mobile-zone"
import type { ShellFrameProps } from "./shell-frame-types"
/** Shared community shell orchestration for the server and DM layouts. */
@@ -17,39 +18,41 @@ export function ShellFrame(props: ShellFrameProps) {
const {
view,
activeServerId,
- mobileZone,
- setMobileZone,
sidebar,
children,
extraDialogs,
onOpenActiveServerSettings,
onOpenActiveServerInvite,
- goHome,
- goServer,
} = props
const router = useRouter()
const pathname = usePathname()
+ const searchParams = useSearchParams()
const queryClient = useQueryClient()
const breakpoint = useBreakpoint()
const onboardingState = useCommunityOnboarding()
+ const search = searchParams.toString()
+ const currentHref = search ? `${pathname}?${search}` : pathname
+ const mobileZone = resolveMobileZone(searchParams)
useEffect(() => {
- if (onboardingState?.status === "active") {
- setMobileZone(onboardingState.stage === "server" ? "nav" : "messages")
- }
- }, [onboardingState, setMobileZone])
+ if (breakpoint !== "mobile" || onboardingState?.status !== "active") return
+ const browserHref = `${currentHref}${window.location.hash}`
+ const nextHref = withMobileZone(
+ browserHref,
+ onboardingState.stage === "server" ? "nav" : "messages",
+ )
+ if (nextHref !== browserHref) window.history.replaceState(null, "", nextHref)
+ }, [breakpoint, currentHref, onboardingState])
const rail = useShellRailController({
router,
- pathname,
queryClient,
+ breakpoint,
+ currentHref,
view,
activeServerId,
- setMobileZone,
onOpenActiveServerSettings,
onOpenActiveServerInvite,
- goHome,
- goServer,
})
const profile = useShellProfileController({
router,
@@ -63,10 +66,11 @@ export function ShellFrame(props: ShellFrameProps) {
queryClient,
cancelPendingNavigation: rail.cancelPendingNavigation,
})
- const goBackMobile = useCallback(
- () => setMobileZone("nav"),
- [setMobileZone],
- )
+ const goBackMobile = useCallback(() => {
+ const browserHref = `${currentHref}${window.location.hash}`
+ const nextHref = withMobileZone(browserHref, "nav")
+ if (nextHref !== browserHref) window.history.replaceState(null, "", nextHref)
+ }, [currentHref])
useEffect(() => {
useCommunityStore.getState().registerUiHandlers({
diff --git a/src/web/src/components/community/shell/use-shell-rail-controller.test.ts b/src/web/src/components/community/shell/use-shell-rail-controller.test.ts
index f7260ad13..c7495a597 100644
--- a/src/web/src/components/community/shell/use-shell-rail-controller.test.ts
+++ b/src/web/src/components/community/shell/use-shell-rail-controller.test.ts
@@ -91,13 +91,11 @@ async function renderController(overrides: Record<string, unknown> = {}) {
}
const options = {
router,
- pathname: "/c/channels/s1",
+ currentHref: "/c/channels/s1",
+ breakpoint: "desktop",
queryClient,
view: "server",
activeServerId: "s1",
- setMobileZone: vi.fn(),
- goHome: vi.fn(),
- goServer: vi.fn(),
...overrides,
} as never
let current!: Result
@@ -157,14 +155,14 @@ describe("useShellRailController", () => {
expect(mocks.markSwitch).toHaveBeenNthCalledWith(2, "server", "s2")
})
- it("supersedes pending navigation on pathname changes and direct channel navigation", async () => {
+ it("supersedes pending navigation on URL changes and direct channel navigation", async () => {
const pathnamePending = deferred()
const channelPending = deferred()
const hook = await renderController()
hook.queryClient.fetchQuery.mockReturnValueOnce(pathnamePending.promise)
await act(async () => hook.current.railProps.onServerNavigate("s2"))
- hook.options.pathname = "/c/me"
+ hook.options.currentHref = "/c/me"
await hook.rerender()
hook.cache.set("s2", { categories: [{ channels: [{ id: "late", pending: false }] }] })
await act(async () => pathnamePending.resolve())
@@ -228,20 +226,37 @@ describe("useShellRailController", () => {
expect(hook.pushed).toEqual([])
})
- it("cancels pending navigation before invoking the home callback", async () => {
+ it("cancels pending navigation before committing Home", async () => {
const pending = deferred()
- const goHome = vi.fn()
- const hook = await renderController({ goHome })
+ const hook = await renderController()
hook.queryClient.fetchQuery.mockReturnValue(pending.promise)
await act(async () => {
hook.current.railProps.onServerNavigate("s2")
hook.current.railProps.onHome()
})
- expect(goHome).toHaveBeenCalledTimes(1)
+ expect(hook.pushed).toEqual(["/c/me"])
hook.cache.set("s2", { categories: [{ channels: [{ id: "late", pending: false }] }] })
await act(async () => pending.resolve())
+ expect(hook.pushed).toEqual(["/c/me"])
+ })
+
+ it("adds the nav pane on mobile and skips an exact current rail target", async () => {
+ const hook = await renderController({
+ breakpoint: "mobile",
+ currentHref: "/c/channels/s1/cached?pane=nav",
+ })
+ hook.cache.set("s1", {
+ categories: [{ channels: [{ id: "cached", pending: false }] }],
+ })
+
+ await act(async () => hook.current.railProps.onServerNavigate("s1"))
expect(hook.pushed).toEqual([])
+
+ hook.options.currentHref = "/c/channels/s2/other"
+ await hook.rerender()
+ await act(async () => hook.current.railProps.onServerNavigate("s1"))
+ expect(hook.pushed).toEqual(["/c/channels/s1/cached?pane=nav"])
})
it("uses cached and fetched destinations for navigation and prefetch fallbacks", async () => {
diff --git a/src/web/src/components/community/shell/use-shell-rail-controller.ts b/src/web/src/components/community/shell/use-shell-rail-controller.ts
index c6ec30aaa..1cd88e620 100644
--- a/src/web/src/components/community/shell/use-shell-rail-controller.ts
+++ b/src/web/src/components/community/shell/use-shell-rail-controller.ts
@@ -26,6 +26,8 @@ import {
supersedeNavigationIntent,
} from "@/lib/community/navigation-intent"
import { useCommunityStore } from "@/stores/community"
+import type { Breakpoint } from "@/hooks/use-mobile"
+import { withMobileZone, type MobileZone } from "./mobile-zone"
import { resolveServerRailOverlayAction } from "./server-rail-actions"
import type { ShellFrameProps, ShellRouter } from "./shell-frame-types"
import type { QueryClient } from "@tanstack/react-query"
@@ -34,28 +36,24 @@ type Options = Pick<
ShellFrameProps,
| "view"
| "activeServerId"
- | "setMobileZone"
| "onOpenActiveServerSettings"
| "onOpenActiveServerInvite"
- | "goHome"
- | "goServer"
> & {
router: ShellRouter
- pathname: string
+ currentHref: string
+ breakpoint: Breakpoint
queryClient: QueryClient
}
export function useShellRailController({
router,
- pathname,
+ currentHref,
+ breakpoint,
queryClient,
view,
activeServerId,
- setMobileZone,
onOpenActiveServerSettings,
onOpenActiveServerInvite,
- goHome,
- goServer,
}: Options) {
const serversQuery = useServers()
const { servers } = serversQuery
@@ -88,7 +86,7 @@ export function useShellRailController({
}, [])
useEffect(() => {
cancelPendingNavigation()
- }, [cancelPendingNavigation, pathname])
+ }, [cancelPendingNavigation, currentHref])
const serverDestination = useCallback((id: string) => {
const detail = queryClient.getQueryData<ServerDetail>(communityKeys.server(id))
@@ -113,18 +111,25 @@ export function useShellRailController({
return serverDestination(id)
}, [queryClient, serverDestination])
+ const paneHref = useCallback((destination: string, mobileZone: MobileZone) =>
+ withMobileZone(destination, breakpoint === "mobile" ? mobileZone : "messages"),
+ [breakpoint])
+ const pushIfChanged = useCallback((destination: string) => {
+ if (destination !== currentHref) router.push(destination)
+ }, [currentHref, router])
+
const onServerNavigate = useCallback((id: string) => {
markSwitch("server", id)
void commitLatestNavigationIntent(
navigationGateRef.current,
() => resolveServerDestination(id),
- (destination) => router.push(destination),
+ (destination) => pushIfChanged(paneHref(destination, "nav")),
)
- }, [resolveServerDestination, router])
+ }, [paneHref, pushIfChanged, resolveServerDestination])
const onHome = useCallback(() => {
cancelPendingNavigation()
- goHome()
- }, [cancelPendingNavigation, goHome])
+ pushIfChanged(paneHref(pickMeLandingLocation(getLastMeLeaf()), "nav"))
+ }, [cancelPendingNavigation, paneHref, pushIfChanged])
const onServerPrefetch = useCallback((id: string) => {
void resolveServerDestination(id).then((destination) => router.prefetch(destination))
}, [resolveServerDestination, router])
@@ -144,11 +149,11 @@ export function useShellRailController({
)
}
cancelPendingNavigation()
- router.push(`/c/channels/${newId}`)
+ pushIfChanged(paneHref(`/c/channels/${newId}`, "nav"))
} catch (error) {
toastApiError(error, "Failed to create server")
}
- }, [cancelPendingNavigation, createServerAsync, router, uploadServerIconMutate])
+ }, [cancelPendingNavigation, createServerAsync, paneHref, pushIfChanged, uploadServerIconMutate])
const onLeaveServer = useCallback((id: string) => {
markVoluntaryLeave(id)
leaveServerMutate(
@@ -158,13 +163,13 @@ export function useShellRailController({
toast("Left server")
if (currentServerId === id) {
cancelPendingNavigation()
- router.replace(pickPostEjectDestination(servers, id))
+ router.replace(paneHref(pickPostEjectDestination(servers, id), "nav"))
}
},
onError: (error) => toastApiError(error, "Failed to leave server"),
},
)
- }, [cancelPendingNavigation, currentServerId, leaveServerMutate, router, servers])
+ }, [cancelPendingNavigation, currentServerId, leaveServerMutate, paneHref, router, servers])
const onOpenSettings = useCallback((id?: string) => {
if (!id) return
cancelPendingNavigation()
@@ -175,8 +180,8 @@ export function useShellRailController({
hasActiveOpener: !!onOpenActiveServerSettings,
})
if (action.kind === "open-active") onOpenActiveServerSettings?.()
- else router.push(action.href)
- }, [activeServerId, cancelPendingNavigation, onOpenActiveServerSettings, router])
+ else pushIfChanged(paneHref(action.href, "nav"))
+ }, [activeServerId, cancelPendingNavigation, onOpenActiveServerSettings, paneHref, pushIfChanged])
const onOpenInvitePopover = useCallback((id?: string) => {
if (!id) return
cancelPendingNavigation()
@@ -187,8 +192,8 @@ export function useShellRailController({
hasActiveOpener: !!onOpenActiveServerInvite,
})
if (action.kind === "open-active") onOpenActiveServerInvite?.()
- else router.push(action.href)
- }, [activeServerId, cancelPendingNavigation, onOpenActiveServerInvite, router])
+ else pushIfChanged(paneHref(action.href, "nav"))
+ }, [activeServerId, cancelPendingNavigation, onOpenActiveServerInvite, paneHref, pushIfChanged])
const onUngroupFolder = useCallback((folderId: string) => {
deleteFolderMutate(
{ folderId },
@@ -224,15 +229,15 @@ export function useShellRailController({
markSwitch(channelId ? "channel" : "server", channelId ?? serverId)
if (channelId) {
cancelPendingNavigation()
- router.push(`/c/channels/${serverId}/${channelId}`)
+ pushIfChanged(paneHref(`/c/channels/${serverId}/${channelId}`, "messages"))
return
}
void commitLatestNavigationIntent(
navigationGateRef.current,
() => resolveServerDestination(serverId),
- (destination) => router.push(destination),
+ (destination) => pushIfChanged(paneHref(destination, "messages")),
)
- }, [cancelPendingNavigation, resolveServerDestination, router])
+ }, [cancelPendingNavigation, paneHref, pushIfChanged, resolveServerDestination])
return {
railProps: {
@@ -240,11 +245,9 @@ export function useShellRailController({
folders,
activeServerId,
serversLoading: serversQuery.isLoading,
- setMobileZone,
view,
onHome,
onHomePrefetch,
- onServer: goServer,
onServerNavigate,
onServerPrefetch,
onCreateServer,
diff --git a/src/web/src/test/e2e-ui/08-mobile.spec.ts b/src/web/src/test/e2e-ui/08-mobile.spec.ts
index 618977c77..a06793a24 100644
--- a/src/web/src/test/e2e-ui/08-mobile.spec.ts
+++ b/src/web/src/test/e2e-ui/08-mobile.spec.ts
@@ -1,6 +1,6 @@
-import { test, expect } from "./_fixtures/community-fixture"
+import { test, expect, userId } from "./_fixtures/community-fixture"
import { tid } from "./_fixtures/testids"
-import { seedServer, seedChannel } from "./_fixtures/seed"
+import { seedServer, seedChannel, seedDm, seedMessage } from "./_fixtures/seed"
// Journey 8 — mobile layout. At <640px the community shell switches zones
// (nav ↔ messages). Opening a channel enters the messages zone; the header
@@ -10,13 +10,16 @@ test.use({ viewport: { width: 390, height: 844 } })
test.describe.serial("mobile layout", () => {
let serverId: string
let channelId: string
+ let dmId: string
test.beforeAll(async () => {
serverId = await seedServer("alice", `Mobile ${Date.now()}`)
channelId = await seedChannel("alice", serverId, "mobile-chan")
+ await seedMessage("alice", channelId, "mobile seq command target")
+ dmId = await seedDm("alice", userId("bob"))
})
- test("opening a channel shows the messages zone with a back button", async ({ asUser }) => {
+ test("a direct channel opens content and Header Back replaces it with nav", async ({ asUser }) => {
const { page } = await asUser("alice")
await page.goto(`/c/channels/${serverId}/${channelId}`)
await page.waitForURL(new RegExp(channelId), { timeout: 20_000 , waitUntil: "commit" })
@@ -24,6 +27,104 @@ test.describe.serial("mobile layout", () => {
// Composer (messages zone) is present.
await expect(page.getByTestId(tid.composerInput)).toBeVisible()
// Mobile header exposes a Back control.
- await expect(page.getByRole("button", { name: "Back" })).toBeVisible()
+ const back = page.getByRole("button", { name: "Back" })
+ await expect(back).toBeVisible()
+
+ const historyLength = await page.evaluate(() => history.length)
+ await back.click()
+ await expect.poll(() => page.url()).toContain("pane=nav")
+ await expect(page.getByTestId(tid.serverIcon(serverId))).toBeVisible()
+ await expect(page.getByTestId(tid.composerInput)).toBeHidden()
+ expect(await page.evaluate(() => history.length)).toBe(historyLength)
+
+ await page.reload()
+ await expect(page.getByTestId(tid.serverIcon(serverId))).toBeVisible()
+ await expect(page.getByTestId(tid.composerInput)).toBeHidden()
+ })
+
+ test("browser Back and Forward restore nav and content from the URL", async ({ asUser }) => {
+ const { page } = await asUser("alice")
+ await page.goto(`/c/channels/${serverId}/${channelId}?pane=nav`)
+ const channelRow = page.getByTestId(tid.channelRow(channelId))
+ await expect(channelRow).toBeVisible()
+
+ await channelRow.click()
+ await expect.poll(() => new URL(page.url()).searchParams.has("pane")).toBe(false)
+ await expect(page.getByTestId(tid.composerInput)).toBeVisible()
+
+ await page.goBack()
+ await expect.poll(() => new URL(page.url()).searchParams.get("pane")).toBe("nav")
+ await expect(channelRow).toBeVisible()
+ await expect(page.getByTestId(tid.composerInput)).toBeHidden()
+
+ await page.goForward()
+ await expect.poll(() => new URL(page.url()).searchParams.has("pane")).toBe(false)
+ await expect(page.getByTestId(tid.composerInput)).toBeVisible()
+ })
+
+ test("Friends, Machines, and Bots deep links all default to content", async ({ asUser }) => {
+ const { page } = await asUser("alice")
+
+ for (const pathname of ["/c/me", "/c/me/machines", "/c/me/bots"]) {
+ await page.goto(pathname)
+ const back = page.getByRole("button", { name: "Back" })
+ await expect(back).toBeVisible()
+ await expect(page.getByTestId(tid.homeButton)).toBeHidden()
+
+ await back.click()
+ await expect.poll(() => new URL(page.url()).pathname).toBe(pathname)
+ await expect.poll(() => new URL(page.url()).searchParams.get("pane")).toBe("nav")
+ await expect(page.getByTestId(tid.homeButton)).toBeVisible()
+ }
+ })
+
+ test("the persistent nav layout consumes seq without dropping other URL state", async ({ asUser }) => {
+ const { page } = await asUser("alice")
+ await page.goto(`/c/channels/${serverId}/${channelId}?seq=1&keep=nav-seq&pane=nav`)
+
+ await expect.poll(() => new URL(page.url()).searchParams.has("seq")).toBe(false)
+ expect(new URL(page.url()).searchParams.get("keep")).toBe("nav-seq")
+ expect(new URL(page.url()).searchParams.get("pane")).toBe("nav")
+ await expect(page.getByTestId(tid.channelRow(channelId))).toBeVisible()
+ })
+
+ test("a direct DM opens content and Header Back preserves the resource", async ({ asUser }) => {
+ const { page } = await asUser("alice")
+ await page.goto(`/c/me/${dmId}`)
+ await expect(page.getByTestId(tid.composerInput)).toBeVisible()
+
+ await page.getByRole("button", { name: "Back" }).click()
+ await expect.poll(() => new URL(page.url()).searchParams.get("pane")).toBe("nav")
+ expect(new URL(page.url()).pathname).toBe(`/c/me/${dmId}`)
+ await expect(page.getByTestId(tid.dmRow(dmId))).toBeVisible()
+ await expect(page.getByTestId(tid.composerInput)).toBeHidden()
+ })
+
+ test("cross-layout Back and Forward restore each URL-owned pane", async ({ asUser }) => {
+ const { page } = await asUser("alice")
+ await page.goto(`/c/channels/${serverId}/${channelId}?pane=nav`)
+ await expect(page.getByTestId(tid.homeButton)).toBeVisible()
+
+ await page.getByTestId(tid.homeButton).click()
+ await expect.poll(() => new URL(page.url()).pathname.startsWith("/c/me")).toBe(true)
+ await expect.poll(() => new URL(page.url()).searchParams.get("pane")).toBe("nav")
+ await page.getByTestId(tid.dmRow(dmId)).click()
+ await expect.poll(() => new URL(page.url()).pathname).toBe(`/c/me/${dmId}`)
+ await expect(page.getByTestId(tid.composerInput)).toBeVisible()
+
+ await page.goBack()
+ await expect.poll(() => new URL(page.url()).pathname.startsWith("/c/me")).toBe(true)
+ await expect.poll(() => new URL(page.url()).searchParams.get("pane")).toBe("nav")
+ await expect(page.getByTestId(tid.dmRow(dmId))).toBeVisible()
+
+ await page.goBack()
+ await expect.poll(() => new URL(page.url()).pathname).toBe(`/c/channels/${serverId}/${channelId}`)
+ await expect.poll(() => new URL(page.url()).searchParams.get("pane")).toBe("nav")
+ await expect(page.getByTestId(tid.channelRow(channelId))).toBeVisible()
+
+ await page.goForward()
+ await page.goForward()
+ await expect.poll(() => new URL(page.url()).pathname).toBe(`/c/me/${dmId}`)
+ await expect(page.getByTestId(tid.composerInput)).toBeVisible()
})
})