Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): align community loading geometry (#704)

Gener1118ab45b283
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjs
index 223aaf0e9..a83d41731 100644
--- a/scripts/ci/e2e-shards.mjs
+++ b/scripts/ci/e2e-shards.mjs
@@ -59,6 +59,7 @@ export const SPEC_SECONDS = {
"42-versioned-avatar-identity.spec.ts": 50,
"44-mobile-reaction-details.spec.ts": 70,
"45-desktop-thread-split-view.spec.ts": 60,
+ "46-community-loading-geometry-matrix.spec.ts": 150,
"50-daemon-update-notice.spec.ts": 35,
"51-mobile-forum-tag-editor.spec.ts": 60,
"51-share-image-assets.spec.ts": 20,
diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.ts
index 62fb13fdb..b08b31f1c 100644
--- a/scripts/ci/e2e-shards.test.ts
+++ b/scripts/ci/e2e-shards.test.ts
@@ -71,7 +71,7 @@ describe("planE2eShards", () => {
expect(first).toHaveLength(E2E_SHARD_COUNT)
expect([...assigned].sort()).toEqual(specs)
expect(new Set(assigned).size).toBe(specs.length)
- expect(totals.sort((left, right) => left - right)).toEqual([550, 551, 551, 553, 555])
+ expect(totals.sort((left, right) => left - right)).toEqual([579, 579, 584, 584, 584])
expect(Math.max(...totals) / Math.min(...totals)).toBeLessThanOrEqual(1.15)
})
diff --git a/src/web/src/app/c/channels/layout.tsx b/src/web/src/app/c/channels/layout.tsx
index 0906f172f..bd3cb1606 100644
--- a/src/web/src/app/c/channels/layout.tsx
+++ b/src/web/src/app/c/channels/layout.tsx
@@ -373,7 +373,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
activeChannel: currentChannelMeta?.parentChannelId ?? currentChannelId ?? "",
isAdmin,
currentUserId: currentUser.id,
- loading: !currentServer,
+ loading: !currentServer || forumSidebar.isLoading,
setActiveChannel,
prefetchChannel,
forumThreadsByParent,
@@ -398,7 +398,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
}), [
channelTree, currentServer, currentChannelMeta?.parentChannelId,
currentChannelId, isAdmin, currentUser.id, setActiveChannel, prefetchChannel,
- forumThreadsByParent, activeForumThreadId, setActiveForumThread,
+ forumThreadsByParent, forumSidebar.isLoading, activeForumThreadId, setActiveForumThread,
onSidebarOpenSettings, onBlockedCreate, mutedChannels,
onCreateChannelInSidebar, onCreateCategoryInSidebar, onRenameChannel,
onDeleteChannelInSidebar, onDeleteCategoryInSidebar, onUpdateCategoryInSidebar,
diff --git a/src/web/src/components/community/channels/channel-header.skeleton.test.ts b/src/web/src/components/community/channels/channel-header.skeleton.test.ts
index 3a35fd73c..15418eb30 100644
--- a/src/web/src/components/community/channels/channel-header.skeleton.test.ts
+++ b/src/web/src/components/community/channels/channel-header.skeleton.test.ts
@@ -18,4 +18,14 @@ describe("ChannelHeaderSkeleton", () => {
expect(html).not.toContain("<button")
expect(html).not.toContain('aria-label="Back"')
})
+
+ it.each([
+ [{}, 6],
+ [{ kind: "forum" as const }, 5],
+ [{ kind: "thread" as const, compactActions: true }, 5],
+ ])("reserves the authoritative action footprint for %o", (props, skeletonCount) => {
+ const html = renderToStaticMarkup(createElement(ChannelHeaderSkeleton, props))
+ expect(html.match(/data-slot="skeleton"/g)).toHaveLength(skeletonCount)
+ if (props.compactActions) expect(html).not.toContain("h-5 w-px")
+ })
})
diff --git a/src/web/src/components/community/channels/channel-header.tsx b/src/web/src/components/community/channels/channel-header.tsx
index e1f7b3d79..f8a675a3b 100644
--- a/src/web/src/components/community/channels/channel-header.tsx
+++ b/src/web/src/components/community/channels/channel-header.tsx
@@ -24,7 +24,14 @@ import { MessageHeader, MessageHeaderMobileBack } from "./message-header"
// Skeleton header for the loading frame between route change and channel
// metadata arriving. Same h-12 footprint as <ChannelHeader> so the body below
// doesn't shift when the real header lands.
-export function ChannelHeaderSkeleton() {
+export function ChannelHeaderSkeleton({
+ kind = "text",
+ compactActions = false,
+}: {
+ kind?: EntityKind
+ compactActions?: boolean
+} = {}) {
+ const actionCount = compactActions || kind === "forum" ? 2 : 3
return (
<MessageHeader
leading={(
@@ -45,10 +52,14 @@ export function ChannelHeaderSkeleton() {
)}
actions={(
<>
- <Skeleton className="size-7 rounded-md" />
- <span className="mx-1 h-5 w-px bg-border/60" aria-hidden />
- <Skeleton className="size-7 rounded-md" />
- <Skeleton className="ml-1 size-7 rounded-md" />
+ {Array.from({ length: actionCount }).map((_, index) => (
+ <span key={index} className="contents">
+ {!compactActions && index === 1 && (
+ <span className="mx-1 h-5 w-px bg-border/60" aria-hidden />
+ )}
+ <Skeleton className={index > 1 ? "ml-1 size-7 rounded-md" : "size-7 rounded-md"} />
+ </span>
+ ))}
</>
)}
/>
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 82c8342b8..56a27df81 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
@@ -20,6 +20,8 @@ const {
mockSplitMode,
mockSplitParentSurface,
mockCommitLastCommunityRoute,
+ mockNavigationGate,
+ mockCurrentChannelId,
} = vi.hoisted(() => ({
mockRouter: { push: vi.fn(), replace: vi.fn(), back: vi.fn() },
mockUiHandlers: { replacePath: vi.fn(), goBackMobile: vi.fn() },
@@ -31,6 +33,8 @@ const {
mockSplitMode: { value: "full" as "split" | "full" },
mockSplitParentSurface: vi.fn(() => null),
mockCommitLastCommunityRoute: vi.fn(),
+ mockNavigationGate: { allowed: true },
+ mockCurrentChannelId: { value: "channel_1" as string | null },
mockRouteModel: {
server: {
id: "server_1",
@@ -71,7 +75,7 @@ vi.mock("next/navigation", () => ({
}))
vi.mock("@tanstack/react-query", () => ({ useQueryClient: () => ({}) }))
vi.mock("@/lib/community/conversation-navigation-proof", () => ({
- useConversationNavigationGate: () => ({ required: false, allowed: true }),
+ useConversationNavigationGate: () => ({ required: false, allowed: mockNavigationGate.allowed }),
}))
vi.mock("sonner", () => ({ toast: vi.fn() }))
vi.mock("@/lib/api/client", () => ({ apiFetch: vi.fn(), toastApiError: vi.fn() }))
@@ -140,7 +144,7 @@ vi.mock("@/stores/community", () => {
)
return {
useCommunityStore,
- useCurrentChannelId: () => "channel_1",
+ useCurrentChannelId: () => mockCurrentChannelId.value,
useUiHandlers: () => mockUiHandlers,
useTypingUsersForScope: () => [],
useTypingNamesForScope: () => ({}),
@@ -283,6 +287,8 @@ describe("ChannelRoute message surface ownership", () => {
mockHeaderServerNavigate.current = undefined
mockHeaderParentNavigate.current = undefined
mockCommitLastCommunityRoute.mockClear()
+ mockNavigationGate.allowed = true
+ mockCurrentChannelId.value = "channel_1"
Object.assign(mockRouteModel, {
server: {
id: "server_1",
@@ -323,6 +329,56 @@ describe("ChannelRoute message surface ownership", () => {
expect(mockCommitLastCommunityRoute).not.toHaveBeenCalled()
})
+ it.each([
+ ["pending", true],
+ ["ready", false],
+ ] as const)("keeps %s metadata neutral while access=%s", (routeLifecycle, accessAllowed) => {
+ Object.assign(mockRouteModel, {
+ channel: { id: "channel_1", name: "cached-forum", type: "forum" },
+ isForum: true,
+ routeLifecycle,
+ })
+ mockNavigationGate.allowed = accessAllowed
+ mockedUseChannelMessageFeed.mockReturnValue(feed())
+
+ let renderer!: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(React.createElement(ChannelRoute, {
+ serverParam: "server_1",
+ channelId: "channel_1",
+ }))
+ })
+
+ expect(renderer.root.findByProps({
+ "data-community-conversation-subtype": "unknown",
+ })).toBeDefined()
+ expect(mockedForumChannelSurface).not.toHaveBeenCalled()
+ expect(mockedMessageList).not.toHaveBeenCalled()
+ })
+
+ it("mounts authoritative split geometry before a thread body is active", () => {
+ configureThreadRoute()
+ mockSplitMode.value = "split"
+ mockCurrentChannelId.value = null
+ mockedUseChannelMessageFeed.mockReturnValue(feed())
+
+ let renderer!: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(React.createElement(ChannelRoute, {
+ serverParam: "server_1",
+ channelId: "channel_1",
+ }))
+ })
+
+ expect(renderer.root.findByProps({ "data-testid": "community-thread-split" }).props["data-layout"])
+ .toBe("split")
+ expect(renderer.root.findByProps({ "data-testid": "community-thread-split-parent" }))
+ .toBeDefined()
+ expect(renderer.root.findByProps({ "data-testid": "community-thread-split-panel" }))
+ .toBeDefined()
+ expect(mockedUseChannelMessageFeed).not.toHaveBeenCalled()
+ })
+
it("commits only a ready channel route for the active account", () => {
mockedUseChannelMessageFeed.mockReturnValue(feed())
act(() => {
diff --git a/src/web/src/components/community/channels/channel-route.tsx b/src/web/src/components/community/channels/channel-route.tsx
index 7a58fd043..18bb242f9 100644
--- a/src/web/src/components/community/channels/channel-route.tsx
+++ b/src/web/src/components/community/channels/channel-route.tsx
@@ -12,6 +12,7 @@ import { ThreadChannelSurface } from "@/components/community/channels/thread-cha
import { ThreadSplitView } from "@/components/community/channels/thread-split-view"
import { ThreadSplitParentSurface } from "@/components/community/channels/thread-split-parent-surface"
import { ForumChannelSurface } from "@/components/community/channels/forum-channel-surface"
+import { ConversationResolutionPendingFrame } from "@/components/community/channels/conversation-resolution-pending-frame"
import { useChannelMemberViewModel } from "@/components/community/members/channel-member-view-model"
import type { OpenProfile } from "@/components/community/social/profile-types"
import { canManageServer, USE_SERVER_DEFAULT } from "@alook/shared"
@@ -38,6 +39,7 @@ import { useThreadSplitMode } from "@/hooks/community/use-thread-split-mode"
import { useQueryClient } from "@tanstack/react-query"
import { useCommunityWsStore } from "@/stores/community/ws"
import { useConversationNavigationGate } from "@/lib/community/conversation-navigation-proof"
+import { resolveConversationSubtype } from "@/lib/community/conversation-subtype"
const THREAD_VIEW_PARAM = "threadView"
@@ -198,11 +200,46 @@ export function ChannelRoute({ serverParam, channelId }: {
routeModel.routeHydrated &&
(!isForumPostChild || !forumPostOpener.isLoading) &&
navigationGate.allowed
+ const subtype = resolveConversationSubtype({
+ routeLifecycle: routeModel.routeLifecycle,
+ accessAllowed: navigationGate.allowed,
+ isChild: isChildChannel,
+ isForum,
+ })
+ if (subtype === "unknown") return <ConversationResolutionPendingFrame />
if (!channelHydrated) {
- if (isForum) {
+ if (subtype === "thread") {
+ const split = threadSplit.mode === "split" && !!currentServer && !!parentChannelInServer
+ return (
+ <ThreadSplitView
+ containerRef={threadSplit.containerRef}
+ split={split}
+ parent={split ? (
+ <>
+ <ChannelHeaderSkeleton kind={isForumPostChild ? "forum" : "text"} />
+ <main className="flex min-h-0 min-w-0 flex-1 flex-col">
+ {isForumPostChild
+ ? <ForumViewSkeleton />
+ : <MessageList channel="" messages={[]} loading onOpenThread={() => {}} />}
+ </main>
+ </>
+ ) : null}
+ thread={(
+ <>
+ <ChannelHeaderSkeleton kind="thread" compactActions={split} />
+ <div className="flex min-h-0 min-w-0 flex-1 flex-col">
+ <MessageList key={channelId} channel="" messages={[]} loading onOpenThread={() => {}} />
+ <ComposerSkeleton />
+ </div>
+ </>
+ )}
+ />
+ )
+ }
+ if (subtype === "forum") {
return (
<>
- <ChannelHeaderSkeleton />
+ <ChannelHeaderSkeleton kind="forum" />
<main className="flex min-h-0 min-w-0 flex-1 flex-col">
<ForumViewSkeleton />
</main>
diff --git a/src/web/src/components/community/channels/conversation-resolution-pending-frame.tsx b/src/web/src/components/community/channels/conversation-resolution-pending-frame.tsx
new file mode 100644
index 000000000..0e92664cd
--- /dev/null
+++ b/src/web/src/components/community/channels/conversation-resolution-pending-frame.tsx
@@ -0,0 +1,20 @@
+import { Skeleton } from "@/components/ui/skeleton"
+
+/** Inert main-area placeholder used until canonical route metadata proves the subtype. */
+export function ConversationResolutionPendingFrame() {
+ return (
+ <main
+ aria-busy="true"
+ aria-label="Resolving conversation"
+ data-community-conversation-subtype="unknown"
+ className="flex min-h-0 min-w-0 flex-1 items-center justify-center bg-background p-4"
+ >
+ <div aria-hidden className="flex w-full max-w-56 flex-col items-center gap-3">
+ <Skeleton className="size-10 rounded-xl" />
+ <Skeleton className="h-4 w-40 rounded" />
+ <Skeleton className="h-3 w-28 rounded" />
+ </div>
+ <span className="sr-only">Resolving conversation</span>
+ </main>
+ )
+}
diff --git a/src/web/src/components/community/channels/forum-view.test.ts b/src/web/src/components/community/channels/forum-view.test.ts
index 8be69fbf8..26f21eba4 100644
--- a/src/web/src/components/community/channels/forum-view.test.ts
+++ b/src/web/src/components/community/channels/forum-view.test.ts
@@ -426,8 +426,9 @@ describe("ForumView filter bar / composer swap", () => {
expect(html).toContain("flex-nowrap")
expect(html).toContain("overflow-x-auto")
expect(html).toContain("thin-scrollbar scrollbar-none")
- expect(html).toContain("sm:flex-wrap")
- expect(html).toContain("sm:overflow-x-visible")
+ expect(html).not.toContain("sm:flex-wrap")
+ expect(html).not.toContain("sm:overflow-x-visible")
+ expect(html.match(/rounded-lg/g)).toHaveLength(4)
expect(html).toContain("pointer-events-none")
expect(html).toContain("px-0 py-2 sm:px-4")
})
diff --git a/src/web/src/components/community/channels/forum-view.tsx b/src/web/src/components/community/channels/forum-view.tsx
index a5c5ddf94..ddb74f525 100644
--- a/src/web/src/components/community/channels/forum-view.tsx
+++ b/src/web/src/components/community/channels/forum-view.tsx
@@ -558,16 +558,19 @@ function ForumListSkeleton() {
export function ForumViewSkeleton() {
return (
<>
- <div className="flex min-w-0 shrink-0 items-center gap-2 overflow-hidden border-b border-border px-4 py-2">
+ <div
+ data-testid={tid.forumFilterBar}
+ className="flex min-w-0 shrink-0 items-center gap-2 overflow-hidden border-b border-border px-4 py-2"
+ >
<div className="relative min-w-0 flex-1">
<div
aria-hidden
- className="pointer-events-none flex w-full min-w-0 flex-nowrap items-center gap-2 overflow-x-auto overscroll-x-contain thin-scrollbar scrollbar-none sm:flex-wrap sm:overflow-x-visible"
+ className="pointer-events-none flex w-full min-w-0 flex-nowrap items-center gap-2 overflow-x-auto overscroll-x-contain thin-scrollbar scrollbar-none"
>
- <Skeleton className="h-7 w-10 shrink-0 rounded-full" />
- <Skeleton className="h-7 w-16 shrink-0 rounded-full" />
- <Skeleton className="h-7 w-14 shrink-0 rounded-full" />
- <Skeleton className="h-7 w-20 shrink-0 rounded-full" />
+ <Skeleton className="h-7 w-10 shrink-0 rounded-lg" />
+ <Skeleton className="h-7 w-16 shrink-0 rounded-lg" />
+ <Skeleton className="h-7 w-14 shrink-0 rounded-lg" />
+ <Skeleton className="h-7 w-20 shrink-0 rounded-lg" />
</div>
</div>
<div className="flex shrink-0 items-center gap-1">
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 5cf7d3a6f..4361d3db1 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
@@ -307,15 +307,24 @@ describe("ThreadChannelSurface ownership", () => {
expect(mocks.setReplyTo).toHaveBeenCalledWith(null)
})
- it("keeps loading inert and restores direct hierarchy controls on body error", () => {
+ it("keeps authoritative thread chrome mounted across body loading and error", () => {
const props = surfaceProps()
mockedUseChannelMessageFeed.mockReturnValue(feed({ isLoading: true }))
let renderer!: TestRenderer.ReactTestRenderer
act(() => {
renderer = TestRenderer.create(React.createElement(ThreadChannelSurface, props))
})
- expect(mockedChannelHeaderSkeleton.mock.calls.at(-1)![0]).not.toHaveProperty("onBack")
- expect(mockedChannelHeader).not.toHaveBeenCalled()
+ expect(mockedChannelHeaderSkeleton).not.toHaveBeenCalled()
+ expect(mockedChannelHeader).toHaveBeenCalledWith(expect.objectContaining({
+ channel: "Thread name",
+ kind: "thread",
+ mobileBack: props.onNavigateParent,
+ }), undefined)
+ expect(mockedMessageList).toHaveBeenCalledWith(expect.objectContaining({
+ channel: "Thread name",
+ loading: true,
+ }), undefined)
+ expect(mockedComposer).toHaveBeenCalled()
mockedUseChannelMessageFeed.mockReturnValue(feed({ isLoading: false, isError: true }))
act(() => renderer.update(React.createElement(ThreadChannelSurface, props)))
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 8116dc486..5ccc290be 100644
--- a/src/web/src/components/community/channels/thread-channel-surface.tsx
+++ b/src/web/src/components/community/channels/thread-channel-surface.tsx
@@ -6,10 +6,10 @@ import { toastApiError, apiFetch } from "@/lib/api/client"
import { useBreakpoint } from "@/hooks/use-mobile"
import { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"
import { useEditMessage, useToggleReactionApi } from "@/hooks/community/mutations"
-import { ChannelHeader, ChannelHeaderSkeleton, type ChannelNotifLevel } from "@/components/community/channels/channel-header"
+import { ChannelHeader, type ChannelNotifLevel } from "@/components/community/channels/channel-header"
import { ChannelShell } from "@/components/community/channels/channel-shell"
import { CommunityPanel } from "@/components/community/shell/community-panel"
-import { Composer, ComposerSkeleton } from "@/components/community/messages/composer"
+import { Composer } from "@/components/community/messages/composer"
import { MessageChannelController } from "@/components/community/messages/message-channel-controller"
import { MessagePaneNavigationProvider } from "@/components/community/messages/message-pane-navigation"
import { MessageContextSheet } from "@/components/community/messages/message-context-sheet"
@@ -161,18 +161,6 @@ export function ThreadChannelSurface({
}
: undefined
- if (feed.isLoading) {
- return (
- <>
- <ChannelHeaderSkeleton />
- <Body className="flex min-h-0 min-w-0 flex-1 flex-col">
- <MessageList key={channelId} channel="" messages={[]} loading onOpenThread={ignoreNestedThread} />
- <ComposerSkeleton />
- </Body>
- </>
- )
- }
-
const opener = parentMessageId && !parentIsForum ? (
<ThreadOpener
parentMessageId={parentMessageId}
diff --git a/src/web/src/components/community/machines/machine-card.tsx b/src/web/src/components/community/machines/machine-card.tsx
index bb230af1f..cfe0f0821 100644
--- a/src/web/src/components/community/machines/machine-card.tsx
+++ b/src/web/src/components/community/machines/machine-card.tsx
@@ -1,6 +1,6 @@
"use client"
-import { useMemo } from "react"
+import { useMemo, type ReactNode } from "react"
import { Monitor, MoreVertical } from "lucide-react"
import type { CommunityMachineSummary } from "@alook/shared"
import { isPresenceOnline } from "@alook/shared"
@@ -18,6 +18,10 @@ import { machineName } from "@/lib/community/machine-name"
import { tid } from "@/lib/community/testids"
import { MachineRuntimes } from "./machine-runtimes"
+export function MachineCardFrame({ children }: { children: ReactNode }) {
+ return <Card className="flex flex-col gap-3 p-4">{children}</Card>
+}
+
export function MachineCard({
machine,
onDelete,
@@ -35,7 +39,7 @@ export function MachineCard({
[machine.lastSeenAt]
)
return (
- <Card className="flex flex-col gap-3 p-4">
+ <MachineCardFrame>
<div className="flex items-start justify-between gap-3">
<div className="flex items-start gap-3">
<div className="grid size-10 place-items-center rounded-xl bg-secondary text-muted-foreground">
@@ -136,6 +140,6 @@ export function MachineCard({
</Button>
</div>
)}
- </Card>
+ </MachineCardFrame>
)
}
diff --git a/src/web/src/components/community/machines/machine-list.test.ts b/src/web/src/components/community/machines/machine-list.test.ts
index ed14103c4..66f7c4c76 100644
--- a/src/web/src/components/community/machines/machine-list.test.ts
+++ b/src/web/src/components/community/machines/machine-list.test.ts
@@ -62,7 +62,11 @@ vi.mock("./guide-me-avatar-motion", () => ({
GuideMeAvatarMotion: (props: Record<string, unknown>) =>
React.createElement("guide-avatar-motion", props),
}))
-vi.mock("./machine-card", () => ({ MachineCard: () => null }))
+vi.mock("./machine-card", () => ({
+ MachineCard: () => null,
+ MachineCardFrame: ({ children }: React.PropsWithChildren) =>
+ React.createElement("machine-card-frame", {}, children),
+}))
vi.mock("./pair-machine-sheet", () => ({ PairMachineSheet: () => null }))
vi.mock("@/components/community/onboarding-tiles/connect-tile", () => ({ ConnectTile: () => null }))
vi.mock("@/hooks/community/use-machines", () => ({
diff --git a/src/web/src/components/community/machines/machine-list.tsx b/src/web/src/components/community/machines/machine-list.tsx
index e8c479488..00a4196f7 100644
--- a/src/web/src/components/community/machines/machine-list.tsx
+++ b/src/web/src/components/community/machines/machine-list.tsx
@@ -1,6 +1,6 @@
"use client"
-import { useCallback, useEffect, useRef, useState } from "react"
+import { useCallback, useEffect, useRef, useState, type ReactNode } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { toast } from "sonner"
import { ChevronLeft } from "lucide-react"
@@ -12,7 +12,6 @@ import {
SELF_UPDATE_MIN_DAEMON_VERSION,
} from "@alook/shared"
import { Button } from "@/components/ui/button"
-import { Card } from "@/components/ui/card"
import { Skeleton } from "@/components/ui/skeleton"
import {
AlertDialog,
@@ -28,7 +27,7 @@ import { apiFetch, getErrorMessage } from "@/lib/api/client"
import { fetchLatestDaemonVersion } from "@/lib/api/config"
import { getAppMode } from "@/lib/utils"
import { machineName } from "@/lib/community/machine-name"
-import { MachineCard } from "./machine-card"
+import { MachineCard, MachineCardFrame } from "./machine-card"
import { PairMachineSheet, type PairMachineSheetMode } from "./pair-machine-sheet"
import { ConnectTile } from "@/components/community/onboarding-tiles/connect-tile"
import { useMachines, type MachinesResponse } from "@/hooks/community/use-machines"
@@ -51,19 +50,28 @@ import { GuideMeAvatarMotion } from "./guide-me-avatar-motion"
// data lands — replaces the old structureless muted box.
function MachineCardSkeleton() {
return (
- <Card className="flex flex-col gap-3 p-4">
+ <MachineCardFrame>
<div className="flex items-start justify-between gap-3">
<div className="flex items-start gap-3">
<Skeleton className="size-10 shrink-0 rounded-xl" />
- <div className="flex flex-col gap-2 py-0.5">
- <Skeleton className="h-3.5 w-32 rounded" />
- <Skeleton className="h-3 w-44 rounded" />
- <Skeleton className="h-3 w-24 rounded" />
+ <div className="flex flex-col gap-1">
+ <Skeleton className="h-6 w-32 rounded" />
+ <Skeleton className="h-4 w-44 rounded" />
+ <Skeleton className="h-4 w-24 rounded" />
</div>
</div>
<Skeleton className="size-8 shrink-0 rounded-md" />
</div>
- </Card>
+ </MachineCardFrame>
+ )
+}
+
+function MachineListContent({ heading, cards }: { heading: ReactNode; cards: ReactNode }) {
+ return (
+ <div className="flex flex-1 flex-col gap-6 overflow-y-auto p-6 thin-scrollbar">
+ {heading}
+ <div className="flex flex-col gap-3">{cards}</div>
+ </div>
)
}
@@ -97,20 +105,24 @@ export function MachineListSkeleton({
return (
<div className="flex min-h-0 flex-1 flex-col">
{machineBackBar(undefined, reserveBackSlot || Boolean(onBack))}
- <div className="flex flex-1 flex-col gap-6 overflow-y-auto p-6 thin-scrollbar">
- <header className="flex items-center justify-between">
- <div className="flex min-w-0 flex-1 flex-col gap-1">
- <Skeleton className="h-6 w-24 rounded" />
- <Skeleton className="h-4 w-full max-w-56 rounded" />
- </div>
- <Skeleton className="h-9 w-36 rounded-md" />
- </header>
- <div className="flex flex-col gap-3">
+ <MachineListContent
+ heading={(
+ <header className="flex items-center justify-between">
+ <div className="flex min-w-0 flex-1 flex-col gap-1">
+ <Skeleton className="h-7 w-24 rounded" />
+ <Skeleton className="h-5 w-full max-w-56 rounded" />
+ </div>
+ <Skeleton className="h-9 w-36 rounded-md" />
+ </header>
+ )}
+ cards={(
+ <>
<MachineCardSkeleton />
<MachineCardSkeleton />
<MachineCardSkeleton />
- </div>
- </div>
+ </>
+ )}
+ />
</div>
)
}
@@ -408,36 +420,36 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {
return (
<div className="flex min-h-0 flex-1 flex-col">
{backBar}
- <div className="flex flex-1 flex-col gap-6 overflow-y-auto p-6 thin-scrollbar">
- <header className="flex items-center justify-between">
- <div>
- <h1 className="text-xl font-medium text-foreground">Machines</h1>
- <p className="text-sm text-muted-foreground">
- Your computers running the alook daemon.
- </p>
- </div>
- <div data-onboarding-target="connect-machine" className="w-fit">
- <Button data-testid={tid.machinePairOpen} onClick={openPair}>
- Connect a machine
- </Button>
- </div>
- </header>
- <div className="flex flex-col gap-3">
- {machines.map((m) => (
- <MachineCard
- key={m.id}
- machine={m}
- onDelete={() => setConfirmDelete(m)}
- onReconnect={() => openReconnect(m)}
- onUpdate={
- canUpdateMachine(m, latestVersion, controllerMode)
- ? () => setConfirmUpdate(m)
- : undefined
- }
- />
- ))}
- </div>
- </div>
+ <MachineListContent
+ heading={(
+ <header className="flex items-center justify-between">
+ <div>
+ <h1 className="text-xl font-medium text-foreground">Machines</h1>
+ <p className="text-sm text-muted-foreground">
+ Your computers running the alook daemon.
+ </p>
+ </div>
+ <div data-onboarding-target="connect-machine" className="w-fit">
+ <Button data-testid={tid.machinePairOpen} onClick={openPair}>
+ Connect a machine
+ </Button>
+ </div>
+ </header>
+ )}
+ cards={machines.map((m) => (
+ <MachineCard
+ key={m.id}
+ machine={m}
+ onDelete={() => setConfirmDelete(m)}
+ onReconnect={() => openReconnect(m)}
+ onUpdate={
+ canUpdateMachine(m, latestVersion, controllerMode)
+ ? () => setConfirmUpdate(m)
+ : undefined
+ }
+ />
+ ))}
+ />
<PairMachineSheet
open={pairOpen}
onOpenChange={closePair}
diff --git a/src/web/src/components/community/messages/composer-view.test.ts b/src/web/src/components/community/messages/composer-view.test.ts
index 5da72e52c..81bbad0b1 100644
--- a/src/web/src/components/community/messages/composer-view.test.ts
+++ b/src/web/src/components/community/messages/composer-view.test.ts
@@ -477,7 +477,7 @@ describe("ComposerView", () => {
const skeletons = renderer.root.findAllByType("skeleton")
expect(skeletons).toHaveLength(4)
expect(skeletons.map((node) => node.props.className)).toEqual([
- "h-5 w-2/5 rounded",
+ "h-6 w-2/5 rounded",
"absolute left-2 bottom-2 size-8 rounded-full",
"absolute right-12 bottom-2 size-8 rounded-full sm:right-2",
"absolute right-2 bottom-2 size-8 rounded-full sm:hidden",
diff --git a/src/web/src/components/community/messages/composer-view.tsx b/src/web/src/components/community/messages/composer-view.tsx
index 7f4748668..94b43cf3e 100644
--- a/src/web/src/components/community/messages/composer-view.tsx
+++ b/src/web/src/components/community/messages/composer-view.tsx
@@ -243,7 +243,7 @@ export function ComposerSkeleton() {
return (
<div className="relative px-3 pb-3 pt-0">
<div className="relative rounded-xl bg-muted py-3 pl-12 pr-24 shadow-(--e1) ring-1 ring-border/40 sm:px-12">
- <Skeleton className="h-5 w-2/5 rounded" />
+ <Skeleton className="h-6 w-2/5 rounded" />
<Skeleton className="absolute left-2 bottom-2 size-8 rounded-full" />
<Skeleton className="absolute right-12 bottom-2 size-8 rounded-full sm:right-2" />
<Skeleton className="absolute right-2 bottom-2 size-8 rounded-full sm:hidden" />
diff --git a/src/web/src/components/community/messages/message-list-view.tsx b/src/web/src/components/community/messages/message-list-view.tsx
index 79cfc31b6..7e44f8ab3 100644
--- a/src/web/src/components/community/messages/message-list-view.tsx
+++ b/src/web/src/components/community/messages/message-list-view.tsx
@@ -103,14 +103,14 @@ function MessageListSkeletonContent({ variant }: { variant: "channel" | "dm" })
{variant === "dm" ? (
<>
<Skeleton className="mb-3 size-16 rounded-full" />
- <Skeleton className="h-7 w-48 rounded" />
- <Skeleton className="mt-2 h-3.5 w-72 rounded" />
+ <Skeleton className="h-8 w-48 rounded" />
+ <Skeleton className="mt-2 h-5 w-72 rounded" />
</>
) : (
<>
<Skeleton className="mb-2 size-12 rounded-full" />
- <Skeleton className="h-5 w-40 rounded" />
- <Skeleton className="mt-2 h-3.5 w-80 max-w-full rounded" />
+ <Skeleton className="h-7 w-40 rounded" />
+ <Skeleton className="mt-2 h-5 w-80 max-w-full rounded" />
</>
)}
</div>
diff --git a/src/web/src/components/community/shell/community-pending-frame.test.ts b/src/web/src/components/community/shell/community-pending-frame.test.ts
index c063e8e76..5d95231d3 100644
--- a/src/web/src/components/community/shell/community-pending-frame.test.ts
+++ b/src/web/src/components/community/shell/community-pending-frame.test.ts
@@ -11,8 +11,9 @@ vi.mock("@/components/community/bots/bot-list-view", () => ({
vi.mock("@/components/community/social/friends-page", () => ({
FriendsPage: (props: Record<string, unknown>) => createElement("friends-skeleton", props),
}))
-vi.mock("@/components/community/channels/channel-loading-frame", () => ({
- ChannelLoadingFrame: (props: Record<string, unknown>) => createElement("channel-skeleton", props),
+vi.mock("@/components/community/channels/conversation-resolution-pending-frame", () => ({
+ ConversationResolutionPendingFrame: (props: Record<string, unknown>) =>
+ createElement("conversation-resolution", props),
}))
vi.mock("@/components/community/channels/dm-loading-frame", () => ({
DmLoadingFrame: (props: Record<string, unknown>) => createElement("dm-skeleton", props),
@@ -62,7 +63,7 @@ describe("CommunityPendingFrame", () => {
expect(dm.root.findByType("dm-skeleton").props.reserveBackSlot).toBe(true)
const channel = render("/c/channels/s1/c1")
- expect(channel.root.findByType("channel-skeleton").props).toEqual({})
+ expect(channel.root.findByType("conversation-resolution").props).toEqual({})
const serverRoot = render("/c/channels/s1")
expect(serverRoot.root.findByProps({ "aria-label": "Loading server" }).props["aria-busy"])
@@ -73,7 +74,7 @@ describe("CommunityPendingFrame", () => {
const renderer = render(["/c/channels/s1/c1", "extra"].join("/"))
expect(renderer.root.findByProps({ "aria-label": "Resolving community route" }))
.toBeDefined()
- expect(renderer.root.findAllByType("channel-skeleton")).toHaveLength(0)
+ expect(renderer.root.findAllByType("conversation-resolution")).toHaveLength(0)
expect(renderer.root.findAllByType("dm-skeleton")).toHaveLength(0)
})
})
diff --git a/src/web/src/components/community/shell/community-pending-frame.tsx b/src/web/src/components/community/shell/community-pending-frame.tsx
index 8c10985d2..3592a5cb9 100644
--- a/src/web/src/components/community/shell/community-pending-frame.tsx
+++ b/src/web/src/components/community/shell/community-pending-frame.tsx
@@ -2,7 +2,7 @@
import type { ReactNode } from "react"
import { BotListSkeleton } from "@/components/community/bots/bot-list-view"
-import { ChannelLoadingFrame } from "@/components/community/channels/channel-loading-frame"
+import { ConversationResolutionPendingFrame } from "@/components/community/channels/conversation-resolution-pending-frame"
import { DmLoadingFrame } from "@/components/community/channels/dm-loading-frame"
import { MachineListSkeleton } from "@/components/community/machines/machine-list"
import { FriendsPage } from "@/components/community/social/friends-page"
@@ -94,7 +94,7 @@ export function CommunityPendingFrame({
content = <ServerLandingPendingFrame />
break
case "server-conversation":
- content = <ChannelLoadingFrame />
+ content = <ConversationResolutionPendingFrame />
break
case "route-resolution":
content = <RouteResolutionPendingFrame />
diff --git a/src/web/src/components/community/shell/community-session-pending-frame.test.ts b/src/web/src/components/community/shell/community-session-pending-frame.test.ts
index 9b2913ca9..f212e4cdb 100644
--- a/src/web/src/components/community/shell/community-session-pending-frame.test.ts
+++ b/src/web/src/components/community/shell/community-session-pending-frame.test.ts
@@ -7,9 +7,19 @@ vi.mock("@/components/ui/skeleton", () => ({
Skeleton: (props: Record<string, unknown>) => createElement("skeleton", props),
}))
vi.mock("@/components/ui/app-surface", () => ({
- AppBackground: (props: Record<string, unknown>) => createElement("app-background", props),
AppSurface: (props: Record<string, unknown>) => createElement("app-surface", props),
}))
+vi.mock("react-resizable-panels", () => ({
+ useDefaultLayout: () => ({ defaultLayout: { sidebar: 24, main: 76 }, onLayoutChanged: vi.fn() }),
+}))
+vi.mock("@/components/ui/resizable", () => ({
+ ResizablePanelGroup: (props: Record<string, unknown>) => createElement("panel-group", props),
+ ResizablePanel: (props: Record<string, unknown>) => createElement("panel", props),
+ ResizableHandle: (props: Record<string, unknown>) => createElement("panel-handle", props),
+}))
+vi.mock("@/hooks/use-mobile", () => ({
+ useBreakpoint: () => "unknown",
+}))
vi.mock("@/components/community/channels/channel-sidebar", () => ({
ChannelSidebarSkeleton: (props: Record<string, unknown>) => createElement("server-sidebar", props),
}))
@@ -17,7 +27,15 @@ vi.mock("@/components/community/channels/dm-sidebar", () => ({
DmSidebarSkeleton: (props: Record<string, unknown>) => createElement("me-sidebar", props),
}))
vi.mock("./server-rail", () => ({
- ServerRailSkeleton: (props: Record<string, unknown>) => createElement("rail-skeleton", props),
+ ServerRailPending: (props: Record<string, unknown>) => createElement(
+ "rail-skeleton",
+ props,
+ createElement("skeleton"),
+ createElement("skeleton"),
+ ),
+}))
+vi.mock("./shell", () => ({
+ Shell: (props: Record<string, unknown>) => createElement("shell-root", props),
}))
vi.mock("./user-bar", () => ({
UserBarSkeleton: (props: Record<string, unknown>) => createElement("user-bar-skeleton", props),
diff --git a/src/web/src/components/community/shell/community-session-pending-frame.tsx b/src/web/src/components/community/shell/community-session-pending-frame.tsx
index 23ee422ee..262867d70 100644
--- a/src/web/src/components/community/shell/community-session-pending-frame.tsx
+++ b/src/web/src/components/community/shell/community-session-pending-frame.tsx
@@ -1,122 +1,60 @@
-import type { CSSProperties } from "react"
+"use client"
+
import { ChannelSidebarSkeleton } from "@/components/community/channels/channel-sidebar"
import { DmSidebarSkeleton } from "@/components/community/channels/dm-sidebar"
-import { AppBackground, AppSurface } from "@/components/ui/app-surface"
-import { Skeleton } from "@/components/ui/skeleton"
+import { AppSurface } from "@/components/ui/app-surface"
+import { useBreakpoint } from "@/hooks/use-mobile"
import { resolveCommunityModulePlan } from "@/lib/community/community-route"
import { tid } from "@/lib/community/testids"
-import { cn } from "@/lib/utils"
import { CommunityPendingFrame } from "./community-pending-frame"
-import {
- COMMUNITY_RAIL_WIDTH,
- desktopUserBarOverlayWidth,
-} from "./shell-frame-geometry"
-import { ServerRailSkeleton } from "./server-rail"
+import { CommunityShellLayout } from "./community-shell-layout"
+import { ServerRailPending } from "./server-rail"
+import { Shell } from "./shell"
import { UserBarSkeleton } from "./user-bar"
-const SESSION_SIDEBAR_WIDTH = 240
-const SESSION_USER_BAR_WIDTH = desktopUserBarOverlayWidth(SESSION_SIDEBAR_WIDTH)
-
-function SessionRail() {
- return (
- <nav
- aria-hidden
- className="flex h-full w-14 shrink-0 flex-col items-center gap-2 pb-2 pt-1"
- >
- <Skeleton className="size-10 shrink-0 rounded-xl" />
- <div className="h-px w-8 shrink-0 bg-border/60" />
- <div className="min-h-0 w-full flex-1 overflow-hidden px-2">
- <ServerRailSkeleton />
- </div>
- <Skeleton className="mt-auto size-10 shrink-0 rounded-[20px]" />
- </nav>
- )
-}
-
/** Stable, inert viewport shown before authenticated community providers exist. */
export function CommunitySessionPendingFrame({ pathname }: { pathname: string }) {
+ const breakpoint = useBreakpoint()
const plan = resolveCommunityModulePlan(pathname)
const showCommunityShell = plan.rail === "community"
- const showSidebar = plan.sidebar.kind !== "none"
- const showMain = plan.main.kind !== "none"
- const isList = plan.surface === "list"
- const isDetail = plan.surface === "detail"
-
- return (
- <div
- data-testid={tid.initialFrame}
- data-community-route-kind={plan.route}
- aria-busy="true"
- aria-label="Loading community"
- className="fixed inset-0 flex overflow-hidden font-sans text-sm text-foreground"
- >
- <AppBackground />
- {showCommunityShell && (
- <div className={cn("flex min-h-0", isDetail && "max-sm:hidden")}>
- <SessionRail />
- </div>
- )}
- <div
- className={cn(
- "relative flex min-h-0 min-w-0 flex-1 flex-col",
- showCommunityShell && isList && "pt-2",
- showCommunityShell && isDetail && "pt-0 sm:pt-2",
- )}
+ if (!showCommunityShell) {
+ return (
+ <Shell
+ data-testid={tid.initialFrame}
+ data-community-route-kind={plan.route}
+ aria-busy="true"
+ aria-label="Loading community"
>
- <AppSurface
- className={cn(
- "rounded-bl-none rounded-br-none rounded-tl-xl rounded-tr-none border-l border-t border-border/40 shadow-none ring-0",
- isDetail && "max-sm:rounded-none max-sm:border-0 max-sm:bg-background",
- !showCommunityShell && "rounded-none border-0 bg-background",
- )}
- >
- <div className="flex min-h-0 min-w-0 flex-1">
- {showSidebar && (
- <div
- data-community-sidebar-kind={plan.sidebar.kind}
- className={cn(
- "min-h-0 shrink-0 flex-col border-r border-border/40 bg-sidebar pb-15 sm:flex",
- isList ? "flex w-full sm:w-60" : "hidden w-60 sm:flex",
- )}
- >
- {plan.sidebar.kind === "server"
- ? <ChannelSidebarSkeleton targetServerId={plan.sidebar.serverId} />
- : <DmSidebarSkeleton />}
- </div>
- )}
- {showMain && (
- <div
- className={cn(
- "min-h-0 min-w-0 flex-1 flex-col bg-background sm:flex",
- isList ? "hidden" : "flex",
- )}
- >
- <CommunityPendingFrame
- href={pathname}
- plan={plan}
- reserveBackSlot={isDetail}
- />
- </div>
+ <div className="relative flex min-h-0 min-w-0 flex-1 flex-col">
+ <AppSurface className="rounded-none border-0 bg-background">
+ {plan.main.kind !== "none" && (
+ <CommunityPendingFrame href={pathname} plan={plan} />
)}
- </div>
- </AppSurface>
+ </AppSurface>
+ </div>
+ </Shell>
+ )
+ }
- {showCommunityShell && (
- <div
- data-slot="community-user-bar-overlay"
- className={cn(
- "absolute bottom-0 left-0 z-10 w-[calc(100%+3.5rem)] sm:w-(--community-session-user-bar-width)",
- isDetail && "max-sm:hidden",
- )}
- style={{
- "--community-session-user-bar-width": `${SESSION_USER_BAR_WIDTH}px`,
- marginLeft: -COMMUNITY_RAIL_WIDTH,
- } as CSSProperties}
- >
- <UserBarSkeleton />
- </div>
- )}
- </div>
- </div>
+ return (
+ <CommunityShellLayout
+ breakpoint={breakpoint}
+ surface={plan.surface === "list" ? "list" : "detail"}
+ rail={<ServerRailPending bottomInset={60} />}
+ sidebar={plan.sidebar.kind === "server"
+ ? <ChannelSidebarSkeleton targetServerId={plan.sidebar.serverId} />
+ : <DmSidebarSkeleton />}
+ main={<CommunityPendingFrame
+ href={pathname}
+ plan={plan}
+ reserveBackSlot={plan.surface === "detail"}
+ />}
+ userBar={<UserBarSkeleton />}
+ testId={tid.initialFrame}
+ routeKind={plan.route}
+ busy
+ label="Loading community"
+ preserveHiddenMobileModules
+ />
)
}
diff --git a/src/web/src/components/community/shell/community-shell-layout.tsx b/src/web/src/components/community/shell/community-shell-layout.tsx
new file mode 100644
index 000000000..7ac3ba0fc
--- /dev/null
+++ b/src/web/src/components/community/shell/community-shell-layout.tsx
@@ -0,0 +1,250 @@
+"use client"
+
+import {
+ useEffect,
+ useRef,
+ useState,
+ type CSSProperties,
+ type ReactNode,
+} from "react"
+import { useDefaultLayout } from "react-resizable-panels"
+import { AppSurface } from "@/components/ui/app-surface"
+import {
+ ResizableHandle,
+ ResizablePanel,
+ ResizablePanelGroup,
+} from "@/components/ui/resizable"
+import type { Breakpoint } from "@/hooks/use-mobile"
+import type { CommunitySurface } from "@/lib/community/community-route"
+import { cn } from "@/lib/utils"
+import {
+ COMMUNITY_RAIL_WIDTH,
+ desktopUserBarOverlayWidth,
+} from "./shell-frame-geometry"
+import { Shell } from "./shell"
+
+const SHELL_SURFACE_CLASS = "rounded-tl-xl rounded-tr-none rounded-br-none rounded-bl-none ring-0 border-l border-t border-border/40 shadow-none"
+const MOBILE_SURFACE_TRANSITION_MS = 180
+const communityLayoutStorage: Pick<Storage, "getItem" | "setItem"> = {
+ getItem: (key) => typeof localStorage === "undefined" ? null : localStorage.getItem(key),
+ setItem: (key, value) => {
+ if (typeof localStorage !== "undefined") localStorage.setItem(key, value)
+ },
+}
+
+type CommunityShellLayoutProps = {
+ breakpoint: Breakpoint
+ surface: CommunitySurface
+ rail: ReactNode
+ sidebar: ReactNode
+ main: ReactNode
+ userBar: ReactNode
+ overlays?: ReactNode
+ onNavigationIntent?: () => void
+ transition?: {
+ mode: string
+ targetHref: string
+ }
+ busy?: boolean
+ label?: string
+ routeKind?: string
+ testId?: string
+ preserveHiddenMobileModules?: boolean
+}
+
+/** The single geometry owner for authenticated and session-pending community shells. */
+export function CommunityShellLayout({
+ breakpoint,
+ surface,
+ rail,
+ sidebar,
+ main,
+ userBar,
+ overlays,
+ onNavigationIntent,
+ transition,
+ busy,
+ label,
+ routeKind,
+ testId,
+ preserveHiddenMobileModules = false,
+}: CommunityShellLayoutProps) {
+ const { defaultLayout, onLayoutChanged } = useDefaultLayout({
+ id: "community-shell",
+ onlySaveAfterUserInteractions: true,
+ storage: communityLayoutStorage,
+ })
+ const sidebarPanelRef = useRef<HTMLDivElement>(null)
+ const mainPanelRef = useRef<HTMLDivElement>(null)
+ const previousCommittedHrefRef = useRef<string | null>(null)
+ const mobileSurfaceAnimationRef = useRef<Animation | null>(null)
+ const [sidebarWidth, setSidebarWidth] = useState(240)
+
+ useEffect(() => {
+ if (breakpoint !== "desktop") return
+ const element = sidebarPanelRef.current
+ if (!element) return
+ setSidebarWidth(element.offsetWidth)
+ const observer = new ResizeObserver(([entry]) => setSidebarWidth(entry!.contentRect.width))
+ observer.observe(element)
+ return () => observer.disconnect()
+ }, [breakpoint])
+
+ const isDesktop = breakpoint === "desktop"
+ const isMobileList = breakpoint === "mobile" && surface === "list"
+ const isMobileDetail = breakpoint === "mobile" && surface === "detail"
+ const isInitial = breakpoint === "unknown"
+ const isInitialDetail = isInitial && surface === "detail"
+ const showUserBar = isDesktop || isMobileList || isInitial || preserveHiddenMobileModules
+ const transitionMode = transition?.mode
+ const transitionTargetHref = transition?.targetHref
+
+ useEffect(() => {
+ if (transitionMode !== "committed" || !transitionTargetHref) return
+ const previousHref = previousCommittedHrefRef.current
+ previousCommittedHrefRef.current = transitionTargetHref
+ if (
+ breakpoint !== "mobile"
+ || !previousHref
+ || previousHref === transitionTargetHref
+ || globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches
+ ) return
+
+ const element = surface === "list" ? sidebarPanelRef.current : mainPanelRef.current
+ if (!element?.animate) return
+ mobileSurfaceAnimationRef.current?.cancel()
+ mobileSurfaceAnimationRef.current = element.animate([
+ {
+ opacity: 0.92,
+ transform: `translate3d(${surface === "list" ? -8 : 8}px, 0, 0)`,
+ },
+ { opacity: 1, transform: "translate3d(0, 0, 0)" },
+ ], {
+ duration: MOBILE_SURFACE_TRANSITION_MS,
+ easing: "cubic-bezier(0.22, 1, 0.36, 1)",
+ })
+ }, [breakpoint, surface, transitionMode, transitionTargetHref])
+ useEffect(() => () => mobileSurfaceAnimationRef.current?.cancel(), [])
+
+ const initialUserBarStyle = {
+ "--community-desktop-user-bar-width": `${desktopUserBarOverlayWidth(sidebarWidth)}px`,
+ marginLeft: -COMMUNITY_RAIL_WIDTH,
+ } as CSSProperties
+
+ return (
+ <Shell
+ onNavigationIntent={onNavigationIntent}
+ aria-busy={busy ? "true" : undefined}
+ aria-label={label}
+ data-community-route-kind={routeKind}
+ data-testid={testId}
+ data-slot="community-shell-root"
+ >
+ {(!isMobileDetail || preserveHiddenMobileModules) && (
+ <div className={cn(
+ "flex min-h-0",
+ isInitialDetail && "hidden sm:contents",
+ isMobileDetail && preserveHiddenMobileModules && "hidden",
+ )}>
+ {rail}
+ </div>
+ )}
+ <div
+ className={cn(
+ "relative flex min-h-0 min-w-0 flex-1 flex-col",
+ !isMobileDetail && !isInitialDetail && "pt-2",
+ isInitialDetail && "pt-0 sm:pt-2",
+ )}
+ >
+ <AppSurface
+ data-slot="community-app-surface"
+ className={cn(
+ SHELL_SURFACE_CLASS,
+ isMobileDetail && "rounded-none border-0 bg-background shadow-none ring-0",
+ isInitialDetail && "max-sm:rounded-none max-sm:border-0 max-sm:bg-background max-sm:shadow-none max-sm:ring-0",
+ )}
+ >
+ <ResizablePanelGroup
+ id="community-shell"
+ orientation="horizontal"
+ disabled={!isDesktop}
+ className={cn(
+ "min-h-0 flex-1",
+ !isDesktop && "*:data-[mobile-active=true]:flex-1!",
+ )}
+ defaultLayout={defaultLayout}
+ onLayoutChanged={onLayoutChanged}
+ >
+ <ResizablePanel
+ id="sidebar"
+ defaultSize="24%"
+ minSize={160}
+ maxSize={360}
+ hidden={isMobileDetail}
+ data-mobile-active={isMobileList || undefined}
+ className={cn(
+ "flex flex-col bg-sidebar",
+ (isDesktop || isMobileList || isInitial) && "pb-[calc(3.75rem+var(--app-safe-area-bottom))] sm:pb-15",
+ isInitial && surface === "list" && "max-sm:flex-1!",
+ isInitialDetail && "max-sm:hidden",
+ )}
+ >
+ <div
+ ref={sidebarPanelRef}
+ data-community-mobile-surface={isMobileList ? "list" : undefined}
+ className="flex min-h-0 min-w-0 flex-1 flex-col"
+ >
+ {sidebar}
+ </div>
+ </ResizablePanel>
+ <ResizableHandle className={cn("bg-transparent", !isDesktop && "hidden")} />
+ <ResizablePanel
+ id="main"
+ defaultSize="76%"
+ hidden={isMobileList}
+ data-mobile-active={isMobileDetail || undefined}
+ className={cn(
+ "flex min-w-0 flex-col bg-background",
+ isInitial && surface === "list" && "max-sm:hidden",
+ isInitialDetail && "max-sm:flex-1!",
+ )}
+ >
+ <div
+ ref={mainPanelRef}
+ data-community-mobile-surface={isMobileDetail ? "detail" : undefined}
+ className="flex min-h-0 flex-1 flex-col"
+ >
+ {main}
+ </div>
+ </ResizablePanel>
+ </ResizablePanelGroup>
+ </AppSurface>
+
+ {showUserBar && (
+ <div
+ data-slot="community-user-bar-overlay"
+ className={cn(
+ "absolute bottom-0 left-0 z-10",
+ isInitial && "w-[calc(100%+3.5rem)] sm:w-(--community-desktop-user-bar-width)",
+ isInitialDetail && "max-sm:hidden",
+ isMobileDetail && preserveHiddenMobileModules && "hidden",
+ )}
+ style={isDesktop
+ ? {
+ width: desktopUserBarOverlayWidth(sidebarWidth),
+ marginLeft: -COMMUNITY_RAIL_WIDTH,
+ }
+ : isMobileList ? {
+ width: `calc(100% + ${COMMUNITY_RAIL_WIDTH}px)`,
+ marginLeft: -COMMUNITY_RAIL_WIDTH,
+ }
+ : initialUserBarStyle}
+ >
+ {userBar}
+ </div>
+ )}
+ </div>
+ {overlays}
+ </Shell>
+ )
+}
diff --git a/src/web/src/components/community/shell/server-rail-brand.test.ts b/src/web/src/components/community/shell/server-rail-brand.test.ts
index ee3d98702..0994bb924 100644
--- a/src/web/src/components/community/shell/server-rail-brand.test.ts
+++ b/src/web/src/components/community/shell/server-rail-brand.test.ts
@@ -18,7 +18,7 @@ describe("ServerRail Home brand mark", () => {
expect(source).not.toContain("alook-dark.svg")
})
- it("lets Add follow short lists while only the server list shrinks on overflow", () => {
+ it("pins Add while the server list shrinks only when its content exceeds the remaining space", () => {
const source = readFileSync(new URL("./server-rail.tsx", import.meta.url), "utf8")
const scrollViewport =
@@ -31,6 +31,7 @@ describe("ServerRail Home brand mark", () => {
expect(source).toContain(addRegion)
expect(source).toContain('"--community-rail-bottom-inset": `${bottomInset ?? 8}px`')
expect(source.indexOf(scrollViewport)).toBeLessThan(source.indexOf(addRegion))
+ expect(scrollViewport).toContain("shrink")
expect(scrollViewport).not.toContain("flex-1")
expect(source).not.toContain("pb-2 overflow-y-auto overflow-x-clip thin-scrollbar")
})
diff --git a/src/web/src/components/community/shell/server-rail.pending.test.ts b/src/web/src/components/community/shell/server-rail.pending.test.ts
index 55e96030f..0207703b2 100644
--- a/src/web/src/components/community/shell/server-rail.pending.test.ts
+++ b/src/web/src/components/community/shell/server-rail.pending.test.ts
@@ -1,7 +1,7 @@
import { createElement, type ReactNode } from "react"
import TestRenderer, { act } from "react-test-renderer"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
-import { ServerRail, ServerRailSkeleton } from "./server-rail"
+import { ServerRail, ServerRailPending, ServerRailSkeleton } from "./server-rail"
import { tid } from "@/lib/community/testids"
import type { RailInstruction } from "@/lib/community/server-rail-model"
@@ -132,10 +132,96 @@ describe("ServerRail one-in-flight structural guard", () => {
})
expect(renderer.root.findByProps({ "data-testid": tid.initialRailPending }))
.toBeDefined()
- expect(renderer.root.findAllByType("skeleton")).toHaveLength(4)
+ expect(renderer.root.findAllByType("skeleton")).toHaveLength(1)
expect(renderer.root.findAllByType("button")).toHaveLength(0)
})
+ it("uses the canonical rail frame for pending home, list, and add geometry", async () => {
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(ServerRailPending, { bottomInset: 60 }))
+ })
+ const nav = renderer.root.findByType("nav")
+ expect(nav.props.className).toBe(
+ "flex min-h-0 w-14 shrink-0 flex-col items-center overflow-hidden pt-2",
+ )
+ expect(nav.props["aria-hidden"]).toBe(true)
+ expect(renderer.root.findAllByType("skeleton")).toHaveLength(2)
+ expect(renderer.root.findAllByType("button")).toHaveLength(0)
+ const home = renderer.root.findByProps({ "data-slot": "community-home-logo-pending" })
+ expect(home.props.className).toContain("size-10")
+ expect(home.props.className).toContain("rounded-[9px]")
+ expect(home.props.className).not.toContain("rounded-[20px]")
+ expect(renderer.root.findByProps({ "data-slot": "community-server-rail-viewport" }).props.className)
+ .toContain("min-h-0 w-full flex-1")
+ expect(renderer.root.findByProps({ "data-testid": tid.serverRailScroll }).props.className)
+ .toContain("shrink overflow-y-auto")
+ expect(renderer.root.findAllByProps({ "data-slot": "community-server-rail-add" }))
+ .toHaveLength(0)
+ })
+
+ it.each([
+ ["empty", 0],
+ ["one", 1],
+ ["multiple", 6],
+ ["overflow", 48],
+ ] as const)("keeps one count-independent viewport around a %s server list", async (_label, count) => {
+ const cardinalityServers = Array.from({ length: count }, (_, index) => ({
+ id: `server-${index}`,
+ name: `Server ${index}`,
+ initial: "S",
+ active: index === 0,
+ unread: false,
+ mentions: 0,
+ }))
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(ServerRail, {
+ servers: cardinalityServers,
+ folders: [],
+ view: "server",
+ onHome: vi.fn(),
+ }))
+ })
+
+ expect(renderer.root.findAllByProps({ "data-slot": "community-server-rail-viewport" }))
+ .toHaveLength(1)
+ expect(renderer.root.findByProps({ "data-slot": "community-server-rail-viewport" }).props.className)
+ .toBe("flex min-h-0 w-full flex-1 flex-col items-center")
+ expect(renderer.root.findAllByType("sortable-server")).toHaveLength(count)
+ expect(renderer.root.findByProps({ "data-testid": tid.serverRailScroll }).props.className)
+ .toContain("min-h-0 w-full shrink overflow-y-auto")
+ expect(renderer.root.findAllByProps({ "data-slot": "community-server-rail-add" }))
+ .toHaveLength(1)
+ })
+
+ it("omits Add for unresolved empty data and keeps it for nonempty revalidation", async () => {
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(ServerRail, {
+ servers: [],
+ folders: [],
+ serversLoading: true,
+ view: "dm",
+ onHome: vi.fn(),
+ }))
+ })
+ expect(renderer.root.findAllByProps({ "data-slot": "community-server-rail-add" }))
+ .toHaveLength(0)
+
+ await act(async () => {
+ renderer.update(createElement(ServerRail, {
+ servers: [servers[0]],
+ folders: [],
+ serversLoading: true,
+ view: "dm",
+ onHome: vi.fn(),
+ }))
+ })
+ expect(renderer.root.findAllByProps({ "data-slot": "community-server-rail-add" }))
+ .toHaveLength(1)
+ })
+
it("aggregates unread only while collapsed and preserves it on the expanded child", async () => {
let renderer!: TestRenderer.ReactTestRenderer
const unreadServers = servers.map((server) => ({
diff --git a/src/web/src/components/community/shell/server-rail.tsx b/src/web/src/components/community/shell/server-rail.tsx
index 9922ea61b..04bad68b8 100644
--- a/src/web/src/components/community/shell/server-rail.tsx
+++ b/src/web/src/components/community/shell/server-rail.tsx
@@ -4,10 +4,13 @@ import {
memo,
useCallback,
useEffect,
+ useLayoutEffect,
useMemo,
useRef,
useState,
type CSSProperties,
+ type ReactNode,
+ type Ref,
} from "react"
import { Plus } from "lucide-react"
import { announce, cleanup as cleanupLiveRegion } from "@atlaskit/pragmatic-drag-and-drop-live-region"
@@ -41,6 +44,65 @@ import {
const DRAG_INSTRUCTIONS_ID = "server-rail-drag-instructions"
+function ServerRailFrame({
+ home,
+ items,
+ add,
+ bottomInset,
+ scrollRef,
+ ariaLabel,
+ ariaHidden,
+ children,
+}: {
+ home: ReactNode
+ items: ReactNode
+ add?: ReactNode
+ bottomInset?: number
+ scrollRef?: Ref<HTMLDivElement>
+ ariaLabel?: string
+ ariaHidden?: boolean
+ children?: ReactNode
+}) {
+ return (
+ <nav
+ aria-label={ariaLabel}
+ aria-hidden={ariaHidden || undefined}
+ className="flex min-h-0 w-14 shrink-0 flex-col items-center overflow-hidden pt-2"
+ >
+ <div className="flex w-full shrink-0 flex-col items-center gap-2">
+ {home}
+ <div className="my-1 w-6 border-t border-border/50" />
+ </div>
+
+ <div
+ data-slot="community-server-rail-viewport"
+ className="flex min-h-0 w-full flex-1 flex-col items-center"
+ >
+ <div
+ ref={scrollRef}
+ data-testid={tid.serverRailScroll}
+ className="min-h-0 w-full shrink overflow-y-auto overflow-x-clip py-2 thin-scrollbar scrollbar-none"
+ >
+ {items}
+ </div>
+
+ {add && (
+ <div
+ data-slot="community-server-rail-add"
+ className="flex w-full shrink-0 justify-center pb-[calc(var(--community-rail-bottom-inset)+var(--app-safe-area-bottom))] sm:pb-(--community-rail-bottom-inset)"
+ style={{
+ "--community-rail-bottom-inset": `${bottomInset ?? 8}px`,
+ } as CSSProperties}
+ >
+ {add}
+ </div>
+ )}
+ </div>
+ {children}
+ </nav>
+ )
+}
+
function reconcileCreatedFolders(
state: RailState,
createdFolderIds: Record<string, string>,
@@ -114,6 +176,21 @@ export const ServerRail = memo(function ServerRail({
() => serverIdentityOrder ? serverIdentityOrder.split("\0") : [],
[serverIdentityOrder],
)
+ const railDataIdentity = useMemo(
+ () => JSON.stringify([
+ serverIds,
+ folders.map((folder) => [
+ folder.id,
+ folder.position,
+ folder.servers.map((server) => server.id),
+ ]),
+ ]),
+ [folders, serverIds],
+ )
+ const [stateDataIdentity, setStateDataIdentity] = useState(railDataIdentity)
+ const renderState = stateDataIdentity === railDataIdentity
+ ? state
+ : railStateFromData(serverIds, folders, state.expanded)
const claimMutation = useCallback(() => {
if (mutationPendingRef.current) {
@@ -144,13 +221,10 @@ export const ServerRail = memo(function ServerRail({
} catch {}
}, [])
- useEffect(() => {
- setState((current) => railStateFromData(
- serverIds,
- folders,
- current.expanded,
- ))
- }, [folders, serverIds])
+ useLayoutEffect(() => {
+ setState((current) => railStateFromData(serverIds, folders, current.expanded))
+ setStateDataIdentity(railDataIdentity)
+ }, [folders, railDataIdentity, serverIds])
useEffect(() => {
sessionStorage.setItem("rail-open-folders", JSON.stringify(state.expanded))
@@ -309,134 +383,123 @@ export const ServerRail = memo(function ServerRail({
: null
const dragging = (entity: RailEntity) => dragSource?.kind === entity.kind
&& dragSource.id === entity.id
- const folderServers = (folderId: string): Server[] => (state.folders[folderId] ?? [])
+ const folderServers = (folderId: string): Server[] => (renderState.folders[folderId] ?? [])
.map((serverId) => serverById.get(serverId))
.filter((server): server is Server => !!server)
- return (
- <nav aria-label="Server navigation" className="flex min-h-0 w-14 shrink-0 flex-col items-center overflow-hidden pt-2">
- <span id={DRAG_INSTRUCTIONS_ID} className="sr-only">
- Press Space to pick up a server or group. Use the arrow keys to choose a position,
- Space or Enter to drop, and Escape to cancel.
- </span>
- <div className="flex w-full shrink-0 flex-col items-center gap-2">
- <Tooltip>
- <TooltipTrigger render={<div className="group relative flex w-full justify-center" />}>
- <span className={[
- "absolute left-0 top-1/2 w-1 -translate-y-1/2 rounded-r-full bg-foreground transition-all duration-150",
- view === "dm" ? "h-8" : "h-0 group-hover:h-5",
- ].join(" ")} />
- <button
- onClick={onHome}
- onPointerEnter={onHomePrefetch}
- onFocus={onHomePrefetch}
- aria-label="Home"
- data-testid={tid.homeButton}
- className="group/alook grid size-10 shrink-0 place-items-center rounded-[20px] focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
- >
- <AnimatedAlookLogo className="size-10" />
- </button>
- </TooltipTrigger>
- <TooltipContent side="right" sideOffset={8}>Home</TooltipContent>
- </Tooltip>
- <div className="my-1 w-6 border-t border-border/50" />
- </div>
-
- <div
- ref={scrollRef}
- data-testid={tid.serverRailScroll}
- className="min-h-0 w-full shrink overflow-y-auto overflow-x-clip py-2 thin-scrollbar scrollbar-none"
- >
- {serversLoading && servers.length === 0 && folders.length === 0 ? (
- <ServerRailSkeleton />
- ) : (
- <div className="flex w-full flex-col items-center gap-2">
- {visibleTopLevelServers(state).map((serverId) => {
- const server = serverById.get(serverId)
- if (!server) return null
- return (
- <SortableServer
- key={serverId}
- server={server}
- active={view !== "dm" && activeId === serverId}
- onClick={() => pickServer(serverId)}
- onPrefetch={() => onServerPrefetch?.(serverId)}
- onLeave={() => onLeaveServer?.(serverId)}
- onOpenSettings={() => onOpenSettings?.(serverId)}
- onOpenInvitePopover={onOpenInvitePopover ? () => onOpenInvitePopover(serverId) : undefined}
- dragging={dragging({ kind: "server", id: serverId })}
- preview={previewFor({ kind: "server", id: serverId })}
- registerItem={registerItem}
- dragDescriptionId={DRAG_INSTRUCTIONS_ID}
- />
- )
- })}
- {state.folderOrder.map((folderId) => {
- const serversInFolder = folderServers(folderId)
- const open = state.expanded.includes(folderId)
- && !(dragSource?.kind === "folder" && dragSource.id === folderId)
- return (
- <div key={folderId} className="flex w-full flex-col items-center gap-2">
- <RailFolder
- folderId={folderId}
- name={folderNames.get(folderId) ?? "Group"}
- open={open}
- active={!open && serversInFolder.some((server) => server.id === activeId)}
- unread={!open && serversInFolder.some((server) => server.unread)}
- onToggle={() => setState((current) => {
- const collapsing = current.expanded.includes(folderId)
- if (mutationPendingRef.current) {
- if (collapsing) collapsedPendingFolderIdsRef.current.add(folderId)
- else collapsedPendingFolderIdsRef.current.delete(folderId)
- }
- return {
- ...current,
- expanded: collapsing
- ? current.expanded.filter((id) => id !== folderId)
- : [...current.expanded, folderId],
- }
- })}
- folderServers={serversInFolder}
- onUngroup={() => ungroupFolder(folderId)}
- dragging={dragging({ kind: "folder", id: folderId })}
- preview={previewFor({ kind: "folder", id: folderId })}
+ const home = (
+ <Tooltip>
+ <TooltipTrigger render={<div className="group relative flex w-full justify-center" />}>
+ <span className={[
+ "absolute left-0 top-1/2 w-1 -translate-y-1/2 rounded-r-full bg-foreground transition-all duration-150",
+ view === "dm" ? "h-8" : "h-0 group-hover:h-5",
+ ].join(" ")} />
+ <button
+ onClick={onHome}
+ onPointerEnter={onHomePrefetch}
+ onFocus={onHomePrefetch}
+ aria-label="Home"
+ data-testid={tid.homeButton}
+ className="group/alook grid size-10 shrink-0 place-items-center rounded-[20px] focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
+ >
+ <AnimatedAlookLogo className="size-10" />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="right" sideOffset={8}>Home</TooltipContent>
+ </Tooltip>
+ )
+ const serverListPending = serversLoading && servers.length === 0 && folders.length === 0
+ const items = serverListPending ? (
+ <ServerRailSkeleton />
+ ) : (
+ <div className="flex w-full flex-col items-center gap-2">
+ {visibleTopLevelServers(renderState).map((serverId) => {
+ const server = serverById.get(serverId)
+ if (!server) return null
+ return (
+ <SortableServer
+ key={serverId}
+ server={server}
+ active={view !== "dm" && activeId === serverId}
+ onClick={() => pickServer(serverId)}
+ onPrefetch={() => onServerPrefetch?.(serverId)}
+ onLeave={() => onLeaveServer?.(serverId)}
+ onOpenSettings={() => onOpenSettings?.(serverId)}
+ onOpenInvitePopover={onOpenInvitePopover ? () => onOpenInvitePopover(serverId) : undefined}
+ dragging={dragging({ kind: "server", id: serverId })}
+ preview={previewFor({ kind: "server", id: serverId })}
+ registerItem={registerItem}
+ dragDescriptionId={DRAG_INSTRUCTIONS_ID}
+ />
+ )
+ })}
+ {renderState.folderOrder.map((folderId) => {
+ const serversInFolder = folderServers(folderId)
+ const open = renderState.expanded.includes(folderId)
+ && !(dragSource?.kind === "folder" && dragSource.id === folderId)
+ return (
+ <div key={folderId} className="flex w-full flex-col items-center gap-2">
+ <RailFolder
+ folderId={folderId}
+ name={folderNames.get(folderId) ?? "Group"}
+ open={open}
+ active={!open && serversInFolder.some((server) => server.id === activeId)}
+ unread={!open && serversInFolder.some((server) => server.unread)}
+ onToggle={() => setState((current) => {
+ const collapsing = current.expanded.includes(folderId)
+ if (mutationPendingRef.current) {
+ if (collapsing) collapsedPendingFolderIdsRef.current.add(folderId)
+ else collapsedPendingFolderIdsRef.current.delete(folderId)
+ }
+ return {
+ ...current,
+ expanded: collapsing
+ ? current.expanded.filter((id) => id !== folderId)
+ : [...current.expanded, folderId],
+ }
+ })}
+ folderServers={serversInFolder}
+ onUngroup={() => ungroupFolder(folderId)}
+ dragging={dragging({ kind: "folder", id: folderId })}
+ preview={previewFor({ kind: "folder", id: folderId })}
+ registerItem={registerItem}
+ dragDescriptionId={DRAG_INSTRUCTIONS_ID}
+ />
+ {open && serversInFolder.length > 0 && (
+ <div className="relative flex w-full flex-col items-center gap-2 py-1">
+ <span className="pointer-events-none absolute inset-y-0 left-1/2 w-12 -translate-x-1/2 rounded-[20px] bg-primary/10" />
+ {serversInFolder.map((server) => (
+ <SortableServer
+ key={server.id}
+ server={server}
+ active={view !== "dm" && activeId === server.id}
+ onClick={() => pickServer(server.id)}
+ onPrefetch={() => onServerPrefetch?.(server.id)}
+ onOpenSettings={() => onOpenSettings?.(server.id)}
+ onOpenInvitePopover={onOpenInvitePopover ? () => onOpenInvitePopover(server.id) : undefined}
+ inFolder
+ dragging={dragging({ kind: "server", id: server.id })}
+ preview={previewFor({ kind: "server", id: server.id })}
registerItem={registerItem}
dragDescriptionId={DRAG_INSTRUCTIONS_ID}
/>
- {open && serversInFolder.length > 0 && (
- <div className="relative flex w-full flex-col items-center gap-2 py-1">
- <span className="pointer-events-none absolute inset-y-0 left-1/2 w-12 -translate-x-1/2 rounded-[20px] bg-primary/10" />
- {serversInFolder.map((server) => (
- <SortableServer
- key={server.id}
- server={server}
- active={view !== "dm" && activeId === server.id}
- onClick={() => pickServer(server.id)}
- onPrefetch={() => onServerPrefetch?.(server.id)}
- onOpenSettings={() => onOpenSettings?.(server.id)}
- onOpenInvitePopover={onOpenInvitePopover ? () => onOpenInvitePopover(server.id) : undefined}
- inFolder
- dragging={dragging({ kind: "server", id: server.id })}
- preview={previewFor({ kind: "server", id: server.id })}
- registerItem={registerItem}
- dragDescriptionId={DRAG_INSTRUCTIONS_ID}
- />
- ))}
- </div>
- )}
- </div>
- )
- })}
+ ))}
+ </div>
+ )}
</div>
- )}
- </div>
+ )
+ })}
+ </div>
+ )
- <div
- className="flex w-full shrink-0 justify-center pb-[calc(var(--community-rail-bottom-inset)+var(--app-safe-area-bottom))] sm:pb-(--community-rail-bottom-inset)"
- style={{
- "--community-rail-bottom-inset": `${bottomInset ?? 8}px`,
- } as CSSProperties}
- >
+ return (
+ <ServerRailFrame
+ ariaLabel="Server navigation"
+ home={home}
+ items={items}
+ bottomInset={bottomInset}
+ scrollRef={scrollRef}
+ add={serverListPending ? undefined : (
<RailIcon
label={<Plus className="size-6" />}
round
@@ -450,18 +513,38 @@ export const ServerRail = memo(function ServerRail({
if (guided) completeCommunityOnboarding()
}}
/>
- </div>
-
+ )}
+ >
+ <span id={DRAG_INSTRUCTIONS_ID} className="sr-only">
+ Press Space to pick up a server or group. Use the arrow keys to choose a position,
+ Space or Enter to drop, and Escape to cancel.
+ </span>
{createOpen && (
<CreateServerDialog
onClose={() => setCreateOpen(false)}
onCreateServer={(name, icon) => { onCreateServer?.(name, icon) }}
/>
)}
- </nav>
+ </ServerRailFrame>
)
})
+export function ServerRailPending({ bottomInset }: { bottomInset?: number }) {
+ return (
+ <ServerRailFrame
+ ariaHidden
+ bottomInset={bottomInset}
+ home={(
+ <Skeleton
+ data-slot="community-home-logo-pending"
+ className="size-10 shrink-0 rounded-[9px]"
+ />
+ )}
+ items={<ServerRailSkeleton />}
+ />
+ )
+}
+
export function ServerRailSkeleton() {
return (
<div
@@ -469,7 +552,7 @@ export function ServerRailSkeleton() {
aria-hidden
className="flex w-full flex-col items-center gap-2"
>
- {Array.from({ length: 4 }).map((_, index) => (
+ {Array.from({ length: 1 }).map((_, index) => (
<Skeleton key={index} className="size-10 rounded-[20px]" />
))}
</div>
diff --git a/src/web/src/components/community/shell/shell-frame-view.test.ts b/src/web/src/components/community/shell/shell-frame-view.test.ts
index 34e25ef3e..409ac632e 100644
--- a/src/web/src/components/community/shell/shell-frame-view.test.ts
+++ b/src/web/src/components/community/shell/shell-frame-view.test.ts
@@ -16,7 +16,10 @@ vi.mock("react-resizable-panels", () => ({
}))
vi.mock("@/components/ui/resizable", () => ({
ResizablePanelGroup: (props: Record<string, unknown>) => createElement("panel-group", props),
- ResizablePanel: (props: Record<string, unknown>) => createElement("panel", props),
+ ResizablePanel: (props: Record<string, unknown>) => createElement(
+ "panel",
+ { "data-slot": "resizable-panel", "data-testid": props.id, ...props },
+ ),
ResizableHandle: (props: Record<string, unknown>) => createElement("panel-handle", props),
}))
vi.mock("@/components/ui/app-surface", () => ({
@@ -249,6 +252,12 @@ describe("ShellFrameView", () => {
expect(renderer.root.findAllByType("server-rail")).toHaveLength(1)
expect(renderer.root.findAllByType("user-bar")).toHaveLength(1)
const mobileSidebarPanel = renderer.root.findAllByType("panel")[0]!
+ expect(mobileSidebarPanel.props["data-slot"]).toBe("resizable-panel")
+ expect(mobileSidebarPanel.props["data-testid"]).toBe("sidebar")
+ expect(renderer.root.findAllByType("panel")[1]!.props).toMatchObject({
+ "data-slot": "resizable-panel",
+ "data-testid": "main",
+ })
expect(mobileSidebarPanel.props.className).toContain("pb-15")
const mobileUserBarOverlay = renderer.root.findByProps({
"data-slot": "community-user-bar-overlay",
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 6b4a22b3a..d4a16ebc7 100644
--- a/src/web/src/components/community/shell/shell-frame-view.tsx
+++ b/src/web/src/components/community/shell/shell-frame-view.tsx
@@ -1,22 +1,13 @@
"use client"
-import { useEffect, useRef, useState, type CSSProperties } from "react"
-import { useDefaultLayout } from "react-resizable-panels"
-import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from "@/components/ui/resizable"
-import { AppSurface } from "@/components/ui/app-surface"
import { ChannelSidebarSkeleton } from "@/components/community/channels/channel-sidebar"
import { DmSidebarSkeleton } from "@/components/community/channels/dm-sidebar"
import { CommunityPendingFrame } from "./community-pending-frame"
-import { Shell } from "./shell"
import { ServerRail } from "./server-rail"
import { UserBar } from "./user-bar"
import { InboxPopover } from "./community-inbox-popover"
import { ShellFrameOverlays } from "./shell-frame-overlays"
-import { cn } from "@/lib/utils"
-import {
- COMMUNITY_RAIL_WIDTH,
- desktopUserBarOverlayWidth,
-} from "./shell-frame-geometry"
+import { CommunityShellLayout } from "./community-shell-layout"
import type { Breakpoint } from "@/hooks/use-mobile"
import type { CommunityCheckpointPlan } from "@/lib/community/community-route"
import type { ShellFrameProps } from "./shell-frame-types"
@@ -33,9 +24,6 @@ type Props = Pick<ShellFrameProps, "sidebar" | "children" | "extraDialogs"> & {
inbox: ReturnType<typeof useShellInboxController>
}
-const SHELL_SURFACE_CLASS = "rounded-tl-xl rounded-tr-none rounded-br-none rounded-bl-none ring-0 border-l border-t border-border/40 shadow-none"
-const MOBILE_SURFACE_TRANSITION_MS = 180
-
export function ShellFrameView({
breakpoint,
checkpoint,
@@ -48,25 +36,6 @@ export function ShellFrameView({
inbox,
}: Props) {
const { surface } = checkpoint
- const { defaultLayout, onLayoutChanged } = useDefaultLayout({
- id: "community-shell",
- onlySaveAfterUserInteractions: true,
- })
- const sidebarPanelRef = useRef<HTMLDivElement>(null)
- const mainPanelRef = useRef<HTMLDivElement>(null)
- const previousCommittedHrefRef = useRef<string | null>(null)
- const mobileSurfaceAnimationRef = useRef<Animation | null>(null)
- const [sidebarWidth, setSidebarWidth] = useState(240)
- useEffect(() => {
- if (breakpoint !== "desktop") return
- const element = sidebarPanelRef.current
- if (!element) return
- setSidebarWidth(element.offsetWidth)
- const observer = new ResizeObserver(([entry]) => setSidebarWidth(entry!.contentRect.width))
- observer.observe(element)
- return () => observer.disconnect()
- }, [breakpoint])
-
const inboxElement = (
<InboxPopover
{...inbox.popoverProps}
@@ -78,172 +47,47 @@ export function ShellFrameView({
name: profile.currentUser.name,
avatar: profile.currentUser.avatar,
}
-
- const isDesktop = breakpoint === "desktop"
- const isMobileList = breakpoint === "mobile" && surface === "list"
- const isMobileDetail = breakpoint === "mobile" && surface === "detail"
const isInitial = breakpoint === "unknown"
- const isInitialDetail = isInitial && surface === "detail"
- const showUserBar = isDesktop || isMobileList || isInitial
- useEffect(() => {
- if (checkpoint.mode !== "committed") return
- const previousHref = previousCommittedHrefRef.current
- previousCommittedHrefRef.current = checkpoint.targetHref
- if (
- breakpoint !== "mobile"
- || !previousHref
- || previousHref === checkpoint.targetHref
- || globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches
- ) return
-
- const element = surface === "list" ? sidebarPanelRef.current : mainPanelRef.current
- if (!element?.animate) return
- mobileSurfaceAnimationRef.current?.cancel()
- mobileSurfaceAnimationRef.current = element.animate([
- {
- opacity: 0.92,
- transform: `translate3d(${surface === "list" ? -8 : 8}px, 0, 0)`,
- },
- { opacity: 1, transform: "translate3d(0, 0, 0)" },
- ], {
- duration: MOBILE_SURFACE_TRANSITION_MS,
- easing: "cubic-bezier(0.22, 1, 0.36, 1)",
- })
- }, [breakpoint, checkpoint.mode, checkpoint.targetHref, surface])
- useEffect(() => () => mobileSurfaceAnimationRef.current?.cancel(), [])
- const initialUserBarStyle = {
- "--community-desktop-user-bar-width": `${desktopUserBarOverlayWidth(sidebarWidth)}px`,
- marginLeft: -COMMUNITY_RAIL_WIDTH,
- } as CSSProperties
return (
- <Shell onNavigationIntent={cancelPendingNavigation}>
- {!isMobileDetail && (
- <div className={cn("flex min-h-0", isInitialDetail && "hidden sm:contents")}>
- <ServerRail {...rail.railProps} bottomInset={60} />
- </div>
+ <CommunityShellLayout
+ breakpoint={breakpoint}
+ surface={surface}
+ onNavigationIntent={cancelPendingNavigation}
+ transition={{ mode: checkpoint.mode, targetHref: checkpoint.targetHref }}
+ rail={<ServerRail {...rail.railProps} bottomInset={60} />}
+ sidebar={breakpoint === "mobile" && surface === "detail"
+ ? null
+ : checkpoint.sidebar.kind === "server-skeleton"
+ ? <ChannelSidebarSkeleton targetServerId={checkpoint.sidebar.serverId} />
+ : checkpoint.sidebar.kind === "me-skeleton"
+ ? <DmSidebarSkeleton />
+ : breakpoint === "desktop" ? sidebar() : sidebar({ noHeader: false })}
+ main={checkpoint.main.kind === "target-skeleton" || isInitial ? (
+ <CommunityPendingFrame
+ href={checkpoint.targetHref}
+ reserveBackSlot={surface === "detail"}
+ />
+ ) : children}
+ userBar={(
+ <UserBar
+ breakpoint={breakpoint}
+ user={user}
+ onOpenProfile={profile.openProfile}
+ onEditProfile={profile.openUserSettings}
+ inbox={inboxElement}
+ hasUnread={inbox.hasUnread}
+ inboxOpen={inbox.open}
+ onInboxOpenChange={inbox.onOpenChange}
+ />
)}
- <div
- className={cn(
- "relative flex min-h-0 min-w-0 flex-1 flex-col",
- !isMobileDetail && !isInitialDetail && "pt-2",
- isInitialDetail && "pt-0 sm:pt-2",
- )}
- >
- <AppSurface
- className={cn(
- SHELL_SURFACE_CLASS,
- isMobileDetail && "rounded-none border-0 bg-background shadow-none ring-0",
- isInitialDetail && "max-sm:rounded-none max-sm:border-0 max-sm:bg-background max-sm:shadow-none max-sm:ring-0",
- )}
- >
- <ResizablePanelGroup
- id="community-shell"
- orientation="horizontal"
- disabled={!isDesktop}
- className={cn(
- "min-h-0 flex-1",
- !isDesktop && "*:data-[mobile-active=true]:flex-1!",
- )}
- defaultLayout={defaultLayout}
- onLayoutChanged={onLayoutChanged}
- >
- <ResizablePanel
- id="sidebar"
- defaultSize="24%"
- minSize={160}
- maxSize={360}
- hidden={isMobileDetail}
- data-mobile-active={isMobileList || undefined}
- className={cn(
- "flex flex-col bg-sidebar",
- (isDesktop || isMobileList || isInitial) && "pb-[calc(3.75rem+var(--app-safe-area-bottom))] sm:pb-15",
- isInitial && surface === "list" && "max-sm:flex-1!",
- isInitialDetail && "max-sm:hidden",
- )}
- >
- <div
- ref={sidebarPanelRef}
- data-community-mobile-surface={isMobileList ? "list" : undefined}
- className="flex min-h-0 min-w-0 flex-1 flex-col"
- >
- {!isMobileDetail && (
- checkpoint.sidebar.kind === "server-skeleton"
- ? <ChannelSidebarSkeleton targetServerId={checkpoint.sidebar.serverId} />
- : checkpoint.sidebar.kind === "me-skeleton"
- ? <DmSidebarSkeleton />
- : isDesktop ? sidebar() : sidebar({ noHeader: false })
- )}
- </div>
- </ResizablePanel>
- <ResizableHandle className={cn("bg-transparent", !isDesktop && "hidden")} />
- <ResizablePanel
- id="main"
- defaultSize="76%"
- hidden={isMobileList}
- data-mobile-active={isMobileDetail || undefined}
- className={cn(
- "flex min-w-0 flex-col bg-background",
- isInitial && surface === "list" && "max-sm:hidden",
- isInitialDetail && "max-sm:flex-1!",
- )}
- >
- <div
- ref={mainPanelRef}
- data-community-mobile-surface={isMobileDetail ? "detail" : undefined}
- className="flex min-h-0 flex-1 flex-col"
- >
- {checkpoint.main.kind === "target-skeleton" || isInitial ? (
- <CommunityPendingFrame
- href={checkpoint.targetHref}
- reserveBackSlot={surface === "detail"}
- />
- ) : children}
- </div>
- </ResizablePanel>
- </ResizablePanelGroup>
- </AppSurface>
-
- {showUserBar && (
- <div
- data-slot="community-user-bar-overlay"
- className={cn(
- "absolute bottom-0 left-0 z-10",
- isInitial && "w-[calc(100%+3.5rem)] sm:w-(--community-desktop-user-bar-width)",
- isInitialDetail && "max-sm:hidden",
- )}
- style={isDesktop
- ? {
- width: desktopUserBarOverlayWidth(sidebarWidth),
- marginLeft: -COMMUNITY_RAIL_WIDTH,
- }
- : isMobileList ? {
- width: `calc(100% + ${COMMUNITY_RAIL_WIDTH}px)`,
- marginLeft: -COMMUNITY_RAIL_WIDTH,
- }
- : initialUserBarStyle}
- >
- <UserBar
- breakpoint={breakpoint}
- user={user}
- onOpenProfile={profile.openProfile}
- onEditProfile={profile.openUserSettings}
- inbox={inboxElement}
- hasUnread={inbox.hasUnread}
- inboxOpen={inbox.open}
- onInboxOpenChange={inbox.onOpenChange}
- />
- </div>
- )}
-
- </div>
- {!isInitial && (
+ overlays={!isInitial && (
<ShellFrameOverlays
controller={profile}
breakpoint={breakpoint}
extraDialogs={extraDialogs}
/>
)}
- </Shell>
+ />
)
}
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 68f639bf3..293677e0b 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
@@ -171,7 +171,7 @@ export function useShellRailController({
servers: railServers,
folders,
activeServerId: projectedActiveServerId,
- serversLoading: serversQuery.isLoading,
+ serversLoading: serversQuery.isPending,
view: projectedView,
onHome,
onHomePrefetch,
diff --git a/src/web/src/lib/community/conversation-subtype.test.ts b/src/web/src/lib/community/conversation-subtype.test.ts
new file mode 100644
index 000000000..d628c662c
--- /dev/null
+++ b/src/web/src/lib/community/conversation-subtype.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vitest"
+import { resolveConversationSubtype } from "./conversation-subtype"
+
+describe("resolveConversationSubtype", () => {
+ it.each([
+ ["pending", true],
+ ["terminal-error", true],
+ ["ready", false],
+ ] as const)("keeps stale or unproved metadata neutral: %s / access=%s", (routeLifecycle, accessAllowed) => {
+ expect(resolveConversationSubtype({
+ routeLifecycle,
+ accessAllowed,
+ isChild: false,
+ isForum: true,
+ })).toBe("unknown")
+ })
+
+ it.each([
+ [{ isChild: false, isForum: false }, "text"],
+ [{ isChild: false, isForum: true }, "forum"],
+ [{ isChild: true, isForum: false }, "thread"],
+ [{ isChild: true, isForum: true }, "thread"],
+ ] as const)("selects $1 only after canonical readiness", (metadata, expected) => {
+ expect(resolveConversationSubtype({
+ routeLifecycle: "ready",
+ accessAllowed: true,
+ ...metadata,
+ })).toBe(expected)
+ })
+})
diff --git a/src/web/src/lib/community/conversation-subtype.ts b/src/web/src/lib/community/conversation-subtype.ts
new file mode 100644
index 000000000..667eb5582
--- /dev/null
+++ b/src/web/src/lib/community/conversation-subtype.ts
@@ -0,0 +1,22 @@
+export type ConversationSubtype = "unknown" | "text" | "forum" | "thread"
+
+/**
+ * Persisted route data may describe a subtype, but it cannot authorize showing
+ * that subtype. Canonical metadata and the current navigation access proof must
+ * both be ready first.
+ */
+export function resolveConversationSubtype({
+ routeLifecycle,
+ accessAllowed,
+ isChild,
+ isForum,
+}: {
+ routeLifecycle: "pending" | "ready" | "terminal-error"
+ accessAllowed: boolean
+ isChild: boolean
+ isForum: boolean
+}): ConversationSubtype {
+ if (routeLifecycle !== "ready" || !accessAllowed) return "unknown"
+ if (isChild) return "thread"
+ return isForum ? "forum" : "text"
+}
diff --git a/src/web/src/test/e2e-ui/38-community-navigation-checkpoint-matrix.spec.ts b/src/web/src/test/e2e-ui/38-community-navigation-checkpoint-matrix.spec.ts
index fe4ed5f50..128135536 100644
--- a/src/web/src/test/e2e-ui/38-community-navigation-checkpoint-matrix.spec.ts
+++ b/src/web/src/test/e2e-ui/38-community-navigation-checkpoint-matrix.spec.ts
@@ -59,10 +59,10 @@ test("community checkpoint shows target pending for detail and keeps list surfac
const leafGate = await holdRoute(page, `/c/channels/${serverId}/${channelB}`)
await page.getByTestId(tid.channelRow(channelB)).click({ noWaitAfter: true })
await expect.poll(leafGate.held).toBeGreaterThan(0)
- await expect(page.getByLabel("Loading conversation")).toBeVisible()
+ await expect(page.getByLabel("Resolving conversation")).toBeVisible()
await expect(channelHeader(page, channelAName)).toHaveCount(0)
await page.waitForTimeout(150)
- await expect(page.getByLabel("Loading conversation")).toBeVisible()
+ await expect(page.getByLabel("Resolving conversation")).toBeVisible()
await expect(channelHeader(page, channelAName)).toHaveCount(0)
await leafGate.release()
await expect(channelHeader(page, channelBName)).toBeVisible({ timeout: 30_000 })
@@ -72,10 +72,10 @@ test("community checkpoint shows target pending for detail and keeps list surfac
await page.getByRole("banner").getByRole("button", { name: "Back" }).click({ noWaitAfter: true })
await expect.poll(rootGate.held).toBeGreaterThan(0)
await page.setViewportSize({ width: 1280, height: 900 })
- await expect(page.getByLabel("Loading conversation")).toHaveCount(0)
+ await expect(page.getByLabel("Resolving conversation")).toHaveCount(0)
await expect(channelHeader(page, channelBName)).toBeVisible()
await page.waitForTimeout(150)
- await expect(page.getByLabel("Loading conversation")).toHaveCount(0)
+ await expect(page.getByLabel("Resolving conversation")).toHaveCount(0)
await expect(channelHeader(page, channelBName)).toBeVisible()
await rootGate.release()
await expect(channelHeader(page, channelBName)).toBeVisible({ timeout: 30_000 })
@@ -85,7 +85,7 @@ test("community checkpoint shows target pending for detail and keeps list surfac
const machinesGate = await holdRoute(page, "/c/me/machines")
await page.getByRole("button", { name: "Machines", exact: true }).click({ noWaitAfter: true })
await expect.poll(machinesGate.held).toBeGreaterThan(0)
- await expect(page.getByLabel("Loading conversation")).toHaveCount(0)
+ await expect(page.getByLabel("Resolving conversation")).toHaveCount(0)
await expect(page.getByPlaceholder("Search friends")).toBeVisible()
await page.waitForTimeout(150)
await expect(page.getByPlaceholder("Search friends")).toBeVisible()
diff --git a/src/web/src/test/e2e-ui/41-community-initial-load-module-skeletons.spec.ts b/src/web/src/test/e2e-ui/41-community-initial-load-module-skeletons.spec.ts
index e5ee2cb33..cd09ebc38 100644
--- a/src/web/src/test/e2e-ui/41-community-initial-load-module-skeletons.spec.ts
+++ b/src/web/src/test/e2e-ui/41-community-initial-load-module-skeletons.spec.ts
@@ -178,7 +178,9 @@ test.describe.serial("community initial-load module skeletons", () => {
expect(traffic.requests).toEqual([])
expect(traffic.sockets()).toBe(0)
if (expected.main === "server-conversation") {
- await expect(page.getByTestId(tid.messageHeaderLeadingLoading)).toBeVisible()
+ await expect(page.getByLabel("Resolving conversation")).toBeVisible()
+ await expect(page.getByTestId(tid.messageHeaderLeadingLoading)).toHaveCount(0)
+ await expect(page.getByTestId(tid.channelComposerShell)).toHaveCount(0)
await expect(page.getByRole("button", { name: "Back" })).toHaveCount(0)
}
await closeHeldContext(context, gate)
diff --git a/src/web/src/test/e2e-ui/46-community-loading-geometry-matrix.spec.ts b/src/web/src/test/e2e-ui/46-community-loading-geometry-matrix.spec.ts
new file mode 100644
index 000000000..853f97ecf
--- /dev/null
+++ b/src/web/src/test/e2e-ui/46-community-loading-geometry-matrix.spec.ts
@@ -0,0 +1,293 @@
+import type { Locator, Page, Route } from "@playwright/test"
+import { expect, test, userId } from "./_fixtures/community-fixture"
+import {
+ seedChannel,
+ seedDm,
+ seedForumThread,
+ seedMessage,
+ seedServer,
+ seedThread,
+} from "./_fixtures/seed"
+import { tid } from "./_fixtures/testids"
+
+type Theme = "light" | "dark"
+const RAIL_OVERFLOW_SERVER_COUNT = 20
+type Geometry = Record<string, { x: number; y: number; width: number; height: number }>
+type MatrixCase = {
+ name: string
+ pathname: string
+ width: 390 | 1280
+ mobileRail?: boolean
+ ready: (page: Page) => Locator
+ intermediate?: {
+ requestPattern: string
+ ready: (page: Page) => Locator
+ }
+}
+
+async function holdSession(page: Page) {
+ let release!: () => void
+ const gate = new Promise<void>((resolve) => { release = resolve })
+ let hits = 0
+ const handler = async (route: Route) => {
+ hits += 1
+ await gate
+ await route.continue()
+ }
+ await page.route("**/api/auth/get-session**", handler)
+ return { hits: () => hits, release }
+}
+
+async function holdRequest(page: Page, pattern: string) {
+ let release!: () => void
+ const gate = new Promise<void>((resolve) => { release = resolve })
+ let hits = 0
+ await page.route(pattern, async (route) => {
+ hits += 1
+ await gate
+ await route.continue()
+ })
+ return { hits: () => hits, release }
+}
+
+const shellPanel = (page: Page, id: "sidebar" | "main") => (
+ page.locator(`[data-slot="resizable-panel"][data-testid="${id}"]`)
+)
+
+async function visibleGeometry(page: Page): Promise<Geometry> {
+ const landmarks = {
+ shell: page.locator('[data-slot="community-shell-root"]'),
+ surface: page.locator('[data-slot="community-app-surface"]'),
+ rail: page.locator('[data-slot="community-server-rail-viewport"]'),
+ sidebar: shellPanel(page, "sidebar"),
+ main: shellPanel(page, "main"),
+ userBar: page.locator('[data-slot="community-user-bar-overlay"]'),
+ }
+ const result: Geometry = {}
+ for (const [name, locator] of Object.entries(landmarks)) {
+ if (await locator.count() !== 1 || !await locator.isVisible()) continue
+ const box = await locator.boundingBox()
+ if (box) result[name] = box
+ }
+ return result
+}
+
+function expectSameGeometry(before: Geometry, after: Geometry) {
+ expect(Object.keys(after).sort()).toEqual(Object.keys(before).sort())
+ for (const name of Object.keys(before)) {
+ const pending = before[name]!
+ const loaded = after[name]!
+ for (const coordinate of ["x", "y", "width", "height"] as const) {
+ expect(
+ Math.abs(pending[coordinate] - loaded[coordinate]),
+ `${name}.${coordinate}`,
+ ).toBeLessThanOrEqual(1)
+ }
+ }
+}
+
+async function startClsObserver(page: Page) {
+ await page.addInitScript(() => {
+ Reflect.set(window, "__communityLoadingCls", 0)
+ Reflect.set(window, "__communityLoadingClsSources", [])
+ new PerformanceObserver((list) => {
+ for (const entry of list.getEntries()) {
+ const shift = entry as PerformanceEntry & { hadRecentInput?: boolean; value?: number }
+ if (!shift.hadRecentInput) {
+ Reflect.set(
+ window,
+ "__communityLoadingCls",
+ (Reflect.get(window, "__communityLoadingCls") as number) + (shift.value ?? 0),
+ )
+ const sources = (entry as PerformanceEntry & {
+ sources?: Array<{
+ node?: Node
+ previousRect?: DOMRectReadOnly
+ currentRect?: DOMRectReadOnly
+ }>
+ }).sources ?? []
+ const recorded = Reflect.get(window, "__communityLoadingClsSources") as unknown[]
+ recorded.push(...sources.map((source) => ({
+ node: source.node instanceof Element
+ ? `${source.node.tagName.toLowerCase()}${source.node.getAttribute("data-slot") ? `[data-slot=${source.node.getAttribute("data-slot")}]` : ""}`
+ : "unknown",
+ previous: source.previousRect,
+ current: source.currentRect,
+ })))
+ }
+ }
+ }).observe({ type: "layout-shift", buffered: true })
+ })
+}
+
+async function resetCls(page: Page) {
+ await page.evaluate(() => {
+ Reflect.set(window, "__communityLoadingCls", 0)
+ Reflect.set(window, "__communityLoadingClsSources", [])
+ })
+}
+
+async function readCls(page: Page) {
+ await page.evaluate(() => new Promise<void>((resolve) => {
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()))
+ }))
+ return page.evaluate(() => ({
+ value: Reflect.get(window, "__communityLoadingCls") as number,
+ sources: Reflect.get(window, "__communityLoadingClsSources") as unknown[],
+ }))
+}
+
+test.describe.serial("community pending-to-loaded geometry matrix", () => {
+ let routes!: Omit<MatrixCase, "width">[]
+
+ test.beforeAll(async () => {
+ test.setTimeout(120_000)
+ const stamp = Date.now()
+ const serverId = await seedServer("alice", `Geometry ${stamp}`)
+ for (let index = 1; index < RAIL_OVERFLOW_SERVER_COUNT; index += 1) {
+ await seedServer("alice", `Geometry rail ${stamp}-${index}`)
+ }
+ const textId = await seedChannel("alice", serverId, `geometry-text-${stamp}`)
+ const forumId = await seedChannel("alice", serverId, `geometry-forum-${stamp}`, "forum")
+ const textMessage = `geometry opener ${stamp}`
+ const threadMessage = `geometry reply ${stamp}`
+ const forumTitle = `Geometry forum post ${stamp}`
+ const forumMessage = `geometry forum reply ${stamp}`
+ const dmMessage = `geometry dm ${stamp}`
+ const openerId = await seedMessage("alice", textId, textMessage)
+ const threadId = await seedThread("alice", openerId, `geometry-thread-${stamp}`)
+ await seedMessage("alice", threadId, threadMessage)
+ const forumPostId = await seedForumThread(
+ "alice",
+ forumId,
+ forumTitle,
+ forumMessage,
+ )
+ const dmId = await seedDm("alice", userId("bob"))
+ await seedMessage("alice", dmId, dmMessage)
+
+ const main = (page: Page) => shellPanel(page, "main")
+ const messageReady = (content: string) => (page: Page) =>
+ main(page).getByText(content, { exact: true }).first()
+ const threadComposerReady = (page: Page) => page
+ .getByTestId(tid.threadSplitPanel)
+ .getByTestId(tid.composerInput)
+ routes = [
+ { name: "root-machines", pathname: "/c", ready: (page) => page.getByTestId(tid.machinePairOpen) },
+ { name: "me-list", pathname: "/c/me", mobileRail: true, ready: (page) => page.getByRole("button", { name: "Friends", exact: true }) },
+ { name: "friends", pathname: "/c/me/friends", ready: (page) => page.getByPlaceholder("Search friends") },
+ { name: "machines", pathname: "/c/me/machines", ready: (page) => page.getByTestId(tid.machinePairOpen) },
+ { name: "bots", pathname: "/c/me/bots", ready: (page) => page.getByRole("button", { name: /Create a bot|Connect a machine/ }) },
+ { name: "dm", pathname: `/c/me/${dmId}`, ready: messageReady(dmMessage) },
+ { name: "text", pathname: `/c/channels/${serverId}/${textId}`, ready: messageReady(textMessage) },
+ {
+ name: "forum",
+ pathname: `/c/channels/${serverId}/${forumId}`,
+ ready: messageReady(forumTitle),
+ intermediate: {
+ requestPattern: `**/api/community/channels/${forumId}/threads?**`,
+ ready: (page) => page.getByTestId(tid.forumFilterBar),
+ },
+ },
+ {
+ name: "thread",
+ pathname: `/c/channels/${serverId}/${threadId}`,
+ ready: messageReady(threadMessage),
+ intermediate: {
+ requestPattern: `**/api/community/channels/${threadId}/messages**`,
+ ready: threadComposerReady,
+ },
+ },
+ {
+ name: "forum-post",
+ pathname: `/c/channels/${serverId}/${forumPostId}`,
+ ready: messageReady(forumMessage),
+ intermediate: {
+ requestPattern: `**/api/community/channels/${forumPostId}/messages**`,
+ ready: threadComposerReady,
+ },
+ },
+ ]
+ })
+
+ for (const theme of ["light", "dark"] as const satisfies readonly Theme[]) {
+ test(`${theme}: 20 route × viewport pending→loaded pairs keep shell CLS at zero`, async ({ asUser }, testInfo) => {
+ test.setTimeout(600_000)
+ const cases: MatrixCase[] = routes.flatMap((route) => ([
+ { ...route, width: 390 },
+ { ...route, width: 1280 },
+ ]))
+ expect(cases).toHaveLength(20)
+
+ for (const entry of cases) {
+ const { context, page } = await asUser("alice")
+ await page.setViewportSize({ width: entry.width, height: entry.width === 390 ? 844 : 900 })
+ await page.emulateMedia({ colorScheme: theme })
+ await startClsObserver(page)
+ const session = await holdSession(page)
+ const intermediate = entry.intermediate
+ ? await holdRequest(page, entry.intermediate.requestPattern)
+ : null
+ await page.goto(entry.pathname, { waitUntil: "commit" })
+ await expect.poll(session.hits).toBeGreaterThan(0)
+ await expect(page.getByTestId(tid.initialFrame)).toBeVisible()
+ await expect(page.locator('[data-slot="community-shell-root"]')).toHaveCount(1)
+ await expect(page.locator('[data-slot="community-shell-root"] button')).toHaveCount(0)
+ const pendingAdd = page.locator('[data-slot="community-server-rail-add"]')
+ await expect(pendingAdd).toHaveCount(0)
+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth))
+ .toBe(true)
+ const pendingGeometry = await visibleGeometry(page)
+ const pendingPath = testInfo.outputPath(`${theme}-${entry.width}-${entry.name}-pending.png`)
+ await page.screenshot({ path: pendingPath })
+ await testInfo.attach(`${theme}-${entry.width}-${entry.name}-pending`, {
+ path: pendingPath,
+ contentType: "image/png",
+ })
+
+ await resetCls(page)
+ session.release()
+ await expect(page.getByTestId(tid.initialFrame)).toHaveCount(0, { timeout: 30_000 })
+ if (entry.intermediate && intermediate) {
+ await expect.poll(intermediate.hits).toBeGreaterThan(0)
+ await expect(entry.intermediate.ready(page)).toBeVisible({ timeout: 30_000 })
+ const intermediatePath = testInfo.outputPath(
+ `${theme}-${entry.width}-${entry.name}-intermediate.png`,
+ )
+ await page.screenshot({ path: intermediatePath })
+ await testInfo.attach(`${theme}-${entry.width}-${entry.name}-intermediate`, {
+ path: intermediatePath,
+ contentType: "image/png",
+ })
+ intermediate.release()
+ }
+ await expect(entry.ready(page)).toBeVisible({ timeout: 30_000 })
+ await expect(page.locator('[data-slot="community-shell-root"]')).toHaveCount(1)
+ const loadedAdd = page.getByTestId(tid.serverAdd)
+ if (entry.width === 1280 || entry.mobileRail) {
+ await expect(loadedAdd).toBeVisible()
+ const railScroll = page.getByTestId(tid.serverRailScroll)
+ await expect(railScroll).toBeVisible()
+ expect(await railScroll.evaluate((element) => element.scrollHeight > element.clientHeight))
+ .toBe(true)
+ } else {
+ await expect(loadedAdd).toHaveCount(0)
+ }
+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth))
+ .toBe(true)
+ const loadedGeometry = await visibleGeometry(page)
+ expectSameGeometry(pendingGeometry, loadedGeometry)
+ const cls = await readCls(page)
+ expect(cls.value, JSON.stringify(cls.sources)).toBe(0)
+
+ const loadedPath = testInfo.outputPath(`${theme}-${entry.width}-${entry.name}-loaded.png`)
+ await page.screenshot({ path: loadedPath })
+ await testInfo.attach(`${theme}-${entry.width}-${entry.name}-loaded`, {
+ path: loadedPath,
+ contentType: "image/png",
+ })
+ await context.close()
+ }
+ })
+ }
+})