Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): anchor mobile inbox above user bar

Gener80032e59a1ed
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjs
index c58f099be..60943452d 100644
--- a/scripts/ci/e2e-shards.mjs
+++ b/scripts/ci/e2e-shards.mjs
@@ -63,6 +63,7 @@ export const SPEC_SECONDS = {
"51-mobile-forum-tag-editor.spec.ts": 60,
"51-share-image-assets.spec.ts": 20,
"52-chat-composer-ordered-list.spec.ts": 90,
+ "53-mobile-inbox-surface.spec.ts": 45,
}
function walk(directory) {
diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.ts
index 88e77fa58..f63d31ae7 100644
--- a/scripts/ci/e2e-shards.test.ts
+++ b/scripts/ci/e2e-shards.test.ts
@@ -70,7 +70,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([483, 483, 483, 484, 487])
+ expect(totals.sort((left, right) => left - right)).toEqual([491, 492, 493, 494, 495])
expect(Math.max(...totals) / Math.min(...totals)).toBeLessThanOrEqual(1.15)
})
diff --git a/src/web/src/app/globals.css b/src/web/src/app/globals.css
index bb64712ac..39834bbe7 100644
--- a/src/web/src/app/globals.css
+++ b/src/web/src/app/globals.css
@@ -611,6 +611,10 @@ body.community-onboarding-active.driver-active :is(
}
:root {
+ --app-safe-area-top: env(safe-area-inset-top, 0px);
+ --app-safe-area-right: env(safe-area-inset-right, 0px);
+ --app-safe-area-bottom: env(safe-area-inset-bottom, 0px);
+ --app-safe-area-left: env(safe-area-inset-left, 0px);
--guide-flight-ease: cubic-bezier(0.45, 0, 0.2, 1);
--ease-out: cubic-bezier(0.2, 0.8, 0.2, 1);
--ease-in: cubic-bezier(0.8, 0, 0.8, 0.2);
diff --git a/src/web/src/components/community/shell/community-inbox-popover.test.ts b/src/web/src/components/community/shell/community-inbox-popover.test.ts
index 3ae1cad27..e8bf8966e 100644
--- a/src/web/src/components/community/shell/community-inbox-popover.test.ts
+++ b/src/web/src/components/community/shell/community-inbox-popover.test.ts
@@ -6,10 +6,10 @@ import type { UnreadDm, UnreadServer } from "@/lib/community/models/inbox"
import { tid } from "@/lib/community/testids"
vi.mock("@/components/ui/tabs", () => ({
- Tabs: ({ children }: { children: React.ReactNode }) => React.createElement("div", null, children),
- TabsList: ({ children }: { children: React.ReactNode }) => React.createElement("div", null, children),
- TabsTrigger: ({ children }: { children: React.ReactNode }) => React.createElement("button", null, children),
- TabsContent: ({ children }: { children: React.ReactNode }) => React.createElement("div", null, children),
+ Tabs: ({ children, ...props }: React.PropsWithChildren<Record<string, unknown>>) => React.createElement("tabs-root", props, children),
+ TabsList: ({ children, ...props }: React.PropsWithChildren<Record<string, unknown>>) => React.createElement("tabs-list", props, children),
+ TabsTrigger: ({ children, ...props }: React.PropsWithChildren<Record<string, unknown>>) => React.createElement("tabs-trigger", props, children),
+ TabsContent: ({ children, ...props }: React.PropsWithChildren<Record<string, unknown>>) => React.createElement("tabs-content", props, children),
}))
function textOf(node: TestRenderer.ReactTestInstance | string | number): string {
@@ -269,3 +269,58 @@ describe("InboxPopover DM rows", () => {
expect(onOpenDm).toHaveBeenCalledWith(dm)
})
})
+
+describe("InboxPopover responsive continuity", () => {
+ it("keeps active tab controlled and reports independent scroll offsets", async () => {
+ const onActiveTabChange = vi.fn()
+ const onMarkedTabSelected = vi.fn()
+ let mentionsOffset = 73
+ const onScrollOffsetChange = vi.fn((tab: string, scrollTop: number) => {
+ if (tab === "mentions") mentionsOffset = scrollTop
+ })
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(InboxPopover, {
+ unreads: [],
+ unreadDms: [],
+ mentions: [],
+ marked: [],
+ activeTab: "mentions",
+ onActiveTabChange,
+ onMarkedTabSelected,
+ getScrollOffset: (tab) => tab === "mentions" ? mentionsOffset : 0,
+ onScrollOffsetChange,
+ surface: "mobile",
+ }))
+ })
+
+ const tabs = renderer.root.findByType("tabs-root")
+ expect(tabs.props.value).toBe("mentions")
+ expect(tabs.props.className).toContain("h-full")
+ await act(async () => tabs.props.onValueChange("marked"))
+ expect(onActiveTabChange).toHaveBeenCalledWith("marked")
+ expect(onMarkedTabSelected).toHaveBeenCalledOnce()
+
+ const mentionsScroll = renderer.root.findByProps({
+ "data-testid": tid.inboxTabScroll("mentions"),
+ })
+ await act(async () => mentionsScroll.props.onScroll({
+ currentTarget: { scrollTop: 91 },
+ }))
+ expect(onScrollOffsetChange).toHaveBeenCalledWith("mentions", 91)
+ onScrollOffsetChange.mockClear()
+ await act(async () => mentionsScroll.props.onScroll({
+ currentTarget: { scrollTop: 42 },
+ }))
+ expect(onScrollOffsetChange).not.toHaveBeenCalled()
+ await act(async () => mentionsScroll.props.onWheel())
+ await act(async () => mentionsScroll.props.onScroll({
+ currentTarget: { scrollTop: 42 },
+ }))
+ expect(onScrollOffsetChange).toHaveBeenCalledWith("mentions", 42)
+ expect(renderer.root.findByType("tabs-list").props["data-testid"])
+ .toBe(tid.inboxTabList)
+ expect(renderer.root.findByType("h2").parent?.props.className)
+ .toBe("flex items-center gap-2 px-3 pt-4")
+ })
+})
diff --git a/src/web/src/components/community/shell/community-inbox-popover.tsx b/src/web/src/components/community/shell/community-inbox-popover.tsx
index 4072895cc..b0c80e796 100644
--- a/src/web/src/components/community/shell/community-inbox-popover.tsx
+++ b/src/web/src/components/community/shell/community-inbox-popover.tsx
@@ -20,9 +20,91 @@ import { tid } from "@/lib/community/testids"
import type { CommunityProfile } from "@/lib/community/models/people"
import { useProfilesByUserId } from "@/stores/community/ws"
import { readCommunityProfile } from "@/lib/community/profile-read"
+import {
+ useLayoutEffect,
+ useRef,
+ type KeyboardEvent,
+ type ReactNode,
+ type UIEvent,
+} from "react"
type UnreadChannel = UnreadServer["channels"][number]
type UnreadChild = UnreadChannel["children"][number]
+export type InboxTab = "unreads" | "mentions" | "marked"
+
+function InboxScrollBody({
+ tab,
+ getScrollOffset,
+ onScrollOffsetChange,
+ children,
+}: {
+ tab: InboxTab
+ getScrollOffset?: (tab: InboxTab) => number
+ onScrollOffsetChange?: (tab: InboxTab, scrollTop: number) => void
+ children: ReactNode
+}) {
+ const ref = useRef<HTMLDivElement>(null)
+ const contentRef = useRef<HTMLDivElement>(null)
+ const pointerScrollRef = useRef(false)
+ const transientScrollRef = useRef(false)
+ useLayoutEffect(() => {
+ const element = ref.current
+ if (!element || !getScrollOffset) return
+ const restore = () => {
+ element.scrollTop = getScrollOffset(tab)
+ }
+ restore()
+ const window = element.ownerDocument.defaultView
+ const ResizeObserverConstructor = window?.ResizeObserver
+ const observer = ResizeObserverConstructor
+ ? new ResizeObserverConstructor(restore)
+ : null
+ observer?.observe(element)
+ if (contentRef.current) observer?.observe(contentRef.current)
+ let secondFrame: number | null = null
+ const firstFrame = window?.requestAnimationFrame(() => {
+ restore()
+ secondFrame = window.requestAnimationFrame(restore)
+ }) ?? null
+ return () => {
+ observer?.disconnect()
+ if (firstFrame !== null) window?.cancelAnimationFrame(firstFrame)
+ if (secondFrame !== null) window?.cancelAnimationFrame(secondFrame)
+ }
+ }, [getScrollOffset, tab])
+ const onScroll = (event: UIEvent<HTMLDivElement>) => {
+ const next = event.currentTarget.scrollTop
+ const previous = getScrollOffset?.(tab) ?? 0
+ if (
+ next >= previous
+ || pointerScrollRef.current
+ || transientScrollRef.current
+ ) {
+ onScrollOffsetChange?.(tab, next)
+ }
+ transientScrollRef.current = false
+ }
+ const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
+ if (["ArrowDown", "ArrowUp", "End", "Home", "PageDown", "PageUp", " "].includes(event.key)) {
+ transientScrollRef.current = true
+ }
+ }
+ return (
+ <div
+ ref={ref}
+ data-testid={tid.inboxTabScroll(tab)}
+ className="h-full overflow-y-auto thin-scrollbar p-3"
+ onScroll={onScroll}
+ onWheel={() => { transientScrollRef.current = true }}
+ onKeyDown={onKeyDown}
+ onPointerDown={() => { pointerScrollRef.current = true }}
+ onPointerUp={() => { pointerScrollRef.current = false }}
+ onPointerCancel={() => { pointerScrollRef.current = false }}
+ >
+ <div ref={contentRef}>{children}</div>
+ </div>
+ )
+}
function MentionBadge({ count }: { count: number }) {
if (count <= 0) return null
@@ -33,7 +115,7 @@ function MentionBadge({ count }: { count: number }) {
)
}
-function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenThread, onOpenDm, isProjected, profilesByUserId }: {
+function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenThread, onOpenDm, isProjected, profilesByUserId, getScrollOffset, onScrollOffsetChange }: {
servers: UnreadServer[]
dms: UnreadDm[]
loading?: boolean
@@ -46,6 +128,8 @@ function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenThread, onOpen
onOpenDm?: (dm: UnreadDm) => void
isProjected: (target: InboxRowTarget | null) => boolean
profilesByUserId: ReadonlyMap<string, CommunityProfile>
+ getScrollOffset?: (tab: InboxTab) => number
+ onScrollOffsetChange?: (tab: InboxTab, scrollTop: number) => void
}) {
const visibleDms = dms.filter((dm) => !isProjected(inboxDmRowTarget(dm)))
const visibleServers = servers.map((server) => ({
@@ -63,7 +147,7 @@ function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenThread, onOpen
})).filter((group) => group.channels.length > 0)
const nothingUnread = visibleServers.length === 0 && visibleDms.length === 0
return (
- <div className="h-full overflow-y-auto thin-scrollbar p-3">
+ <InboxScrollBody tab="unreads" getScrollOffset={getScrollOffset} onScrollOffsetChange={onScrollOffsetChange}>
{loading && nothingUnread && <InboxUnreadsSkeleton />}
{!loading && nothingUnread && <EmptyState icon={Inbox} label="Caught up" />}
{visibleDms.length > 0 && (
@@ -121,23 +205,25 @@ function UnreadsTab({ servers, dms, loading, onOpenChannel, onOpenThread, onOpen
))}
</div>
))}
- </div>
+ </InboxScrollBody>
)
}
-function MentionsTab({ mentions, loading, onOpenMention, onDeleteMention, isProjected, profilesByUserId }: {
+function MentionsTab({ mentions, loading, onOpenMention, onDeleteMention, isProjected, profilesByUserId, getScrollOffset, onScrollOffsetChange }: {
mentions: Mention[]
loading?: boolean
onOpenMention?: (m: Mention) => void
onDeleteMention?: (id: string) => void
isProjected: (target: InboxRowTarget | null) => boolean
profilesByUserId: ReadonlyMap<string, CommunityProfile>
+ getScrollOffset?: (tab: InboxTab) => number
+ onScrollOffsetChange?: (tab: InboxTab, scrollTop: number) => void
}) {
const visibleMentions = mentions.filter((mention) => (
!isProjected(inboxMentionRowTarget(mention))
))
return (
- <div className="h-full overflow-y-auto thin-scrollbar p-3">
+ <InboxScrollBody tab="mentions" getScrollOffset={getScrollOffset} onScrollOffsetChange={onScrollOffsetChange}>
{loading && visibleMentions.length === 0 && <InboxRowsSkeleton />}
{!loading && visibleMentions.length === 0 && <EmptyState icon={Inbox} label="No mentions" />}
{visibleMentions.map((mn) => {
@@ -175,19 +261,21 @@ function MentionsTab({ mentions, loading, onOpenMention, onDeleteMention, isProj
</div>
)
})}
- </div>
+ </InboxScrollBody>
)
}
-function MarkedTab({ marked, loading, onOpenMarked, onUnmark, profilesByUserId }: {
+function MarkedTab({ marked, loading, onOpenMarked, onUnmark, profilesByUserId, getScrollOffset, onScrollOffsetChange }: {
marked: Marked[]
loading?: boolean
onOpenMarked?: (m: Marked) => void
onUnmark?: (messageId: string) => void
profilesByUserId: ReadonlyMap<string, CommunityProfile>
+ getScrollOffset?: (tab: InboxTab) => number
+ onScrollOffsetChange?: (tab: InboxTab, scrollTop: number) => void
}) {
return (
- <div className="h-full overflow-y-auto thin-scrollbar p-3">
+ <InboxScrollBody tab="marked" getScrollOffset={getScrollOffset} onScrollOffsetChange={onScrollOffsetChange}>
{loading && marked.length === 0 && <InboxRowsSkeleton />}
{!loading && marked.length === 0 && <EmptyState icon={Bookmark} label="No marked messages" />}
{marked.map((mk) => {
@@ -229,7 +317,7 @@ function MarkedTab({ marked, loading, onOpenMarked, onUnmark, profilesByUserId }
</div>
)
})}
- </div>
+ </InboxScrollBody>
)
}
@@ -253,6 +341,11 @@ export function InboxPopover({
onMarkedTabSelected,
onMarkAllRead,
isProjected = () => false,
+ activeTab,
+ onActiveTabChange,
+ getScrollOffset,
+ onScrollOffsetChange,
+ surface = "desktop",
}: {
unreads: UnreadServer[]
unreadDms: UnreadDm[]
@@ -284,6 +377,11 @@ export function InboxPopover({
onMarkedTabSelected?: () => void
onMarkAllRead?: () => void
isProjected?: (target: InboxRowTarget | null) => boolean
+ activeTab?: InboxTab
+ onActiveTabChange?: (tab: InboxTab) => void
+ getScrollOffset?: (tab: InboxTab) => number
+ onScrollOffsetChange?: (tab: InboxTab, scrollTop: number) => void
+ surface?: "desktop" | "mobile"
}) {
const profilesByUserId = useProfilesByUserId()
const hasUnreads = hasProjectedUnreads ?? (unreads.length > 0 || unreadDms.length > 0)
@@ -292,8 +390,13 @@ export function InboxPopover({
return (
<Tabs
defaultValue="unreads"
- onValueChange={(v) => { if (v === "marked") onMarkedTabSelected?.() }}
- className="flex h-112 flex-col"
+ value={activeTab}
+ onValueChange={(value) => {
+ const tab = value as InboxTab
+ onActiveTabChange?.(tab)
+ if (tab === "marked") onMarkedTabSelected?.()
+ }}
+ className={surface === "mobile" ? "flex h-full min-h-0 flex-col" : "flex h-112 flex-col"}
>
<div className="flex items-center gap-2 px-3 pt-4">
<Inbox className="size-5" />
@@ -308,7 +411,7 @@ export function InboxPopover({
</button>
)}
</div>
- <TabsList variant="line" className="mt-3 w-full border-b border-border px-3">
+ <TabsList data-testid={tid.inboxTabList} variant="line" className="mt-3 w-full border-b border-border px-3">
<TabsTrigger value="unreads">
<span className="inline-flex items-center gap-2">
Unreads
@@ -333,13 +436,15 @@ export function InboxPopover({
onOpenDm={onOpenDm}
isProjected={isProjected}
profilesByUserId={profilesByUserId}
+ getScrollOffset={getScrollOffset}
+ onScrollOffsetChange={onScrollOffsetChange}
/>
</TabsContent>
<TabsContent value="mentions" className="min-h-0 flex-1">
- <MentionsTab mentions={mentions} loading={loading} onOpenMention={onOpenMention} onDeleteMention={onDeleteMention} isProjected={isProjected} profilesByUserId={profilesByUserId} />
+ <MentionsTab mentions={mentions} loading={loading} onOpenMention={onOpenMention} onDeleteMention={onDeleteMention} isProjected={isProjected} profilesByUserId={profilesByUserId} getScrollOffset={getScrollOffset} onScrollOffsetChange={onScrollOffsetChange} />
</TabsContent>
<TabsContent value="marked" className="min-h-0 flex-1">
- <MarkedTab marked={marked} loading={markedLoading} onOpenMarked={onOpenMarked} onUnmark={onUnmark} profilesByUserId={profilesByUserId} />
+ <MarkedTab marked={marked} loading={markedLoading} onOpenMarked={onOpenMarked} onUnmark={onUnmark} profilesByUserId={profilesByUserId} getScrollOffset={getScrollOffset} onScrollOffsetChange={onScrollOffsetChange} />
</TabsContent>
</Tabs>
)
diff --git a/src/web/src/components/community/shell/community-inbox-surface.test.ts b/src/web/src/components/community/shell/community-inbox-surface.test.ts
new file mode 100644
index 000000000..78c4ccb0b
--- /dev/null
+++ b/src/web/src/components/community/shell/community-inbox-surface.test.ts
@@ -0,0 +1,122 @@
+import { createElement, createRef, type PropsWithChildren } from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { describe, expect, it, vi } from "vitest"
+import { CommunityInboxSurface } from "./community-inbox-surface"
+import { tid } from "@/lib/community/testids"
+
+vi.mock("@/components/ui/popover", () => {
+ const pass = (type: string) =>
+ function Pass({ children, ...props }: PropsWithChildren<Record<string, unknown>>) {
+ return createElement(type, props, children)
+ }
+ return {
+ Popover: pass("popover-root"),
+ PopoverBackdrop: pass("popover-backdrop"),
+ PopoverContent: pass("popover-content"),
+ PopoverPopup: pass("popover-popup"),
+ PopoverPortal: pass("popover-portal"),
+ PopoverPositioner: pass("popover-positioner"),
+ PopoverTitle: pass("popover-title"),
+ PopoverTrigger: pass("popover-trigger"),
+ }
+})
+
+async function renderSurface(breakpoint: "mobile" | "desktop", open = true) {
+ const anchorRef = createRef<HTMLDivElement>()
+ const suppressFocusReturnRef = { current: false }
+ const onOpenChange = vi.fn()
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(CommunityInboxSurface, {
+ breakpoint,
+ open,
+ onOpenChange,
+ hasUnread: true,
+ anchorRef,
+ suppressFocusReturnRef,
+ }, createElement("inbox-content")))
+ })
+ return { renderer, anchorRef, suppressFocusReturnRef, onOpenChange }
+}
+
+describe("CommunityInboxSurface", () => {
+ it("uses a scoped real nonmodal Popover surface on mobile", async () => {
+ const { renderer, anchorRef, suppressFocusReturnRef } = await renderSurface("mobile")
+ expect(renderer.root.findByType("popover-root").props.modal).toBe(false)
+ const trigger = renderer.root.findByType("popover-trigger").props.render
+ expect(trigger.props["data-testid"]).toBe(tid.inboxTrigger)
+ expect(trigger.props["aria-label"]).toBe("Close Inbox")
+ expect(trigger.props["aria-pressed"]).toBe(true)
+ expect(trigger.props.className).toContain("aria-expanded:text-foreground")
+ expect(renderer.root.findByType("svg").props.className).not.toContain("fill-current")
+ expect(renderer.root.findByType("svg").props.fill).toBe("none")
+
+ const backdrop = renderer.root.findByType("popover-backdrop")
+ expect(backdrop.props["data-testid"]).toBe(tid.inboxMobileBackdrop)
+ expect(backdrop.props.style).toEqual({
+ top: "var(--app-safe-area-top)",
+ bottom: "calc(60px + var(--app-safe-area-bottom))",
+ })
+
+ const positioner = renderer.root.findByType("popover-positioner")
+ expect(positioner.props).toMatchObject({
+ anchor: anchorRef,
+ positionMethod: "fixed",
+ side: "top",
+ align: "start",
+ sideOffset: 0,
+ collisionAvoidance: { side: "none", align: "none", fallbackAxisSide: "none" },
+ })
+ const popup = renderer.root.findByType("popover-popup")
+ expect(popup.props["data-testid"]).toBe(tid.inboxMobileSurface)
+ expect(popup.props.initialFocus).toBe(false)
+ expect(popup.props.className).toContain("w-(--anchor-width)")
+ expect(renderer.root.findByType("popover-title").children).toEqual(["Inbox"])
+ expect(renderer.root.findAllByType("popover-close")).toHaveLength(0)
+ const card = renderer.root.findByProps({ "data-testid": tid.inboxMobileCard })
+ expect(card.props.className).toContain("rounded-t-xl")
+ expect(card.props.className).not.toContain("rounded-xl")
+ expect(card.props.style.height)
+ .toContain("100dvh")
+
+ suppressFocusReturnRef.current = true
+ expect(popup.props.finalFocus()).toBe(false)
+ })
+
+ it("keeps the mobile trigger outlined while closed", async () => {
+ const { renderer } = await renderSurface("mobile", false)
+ const trigger = renderer.root.findByType("popover-trigger").props.render
+ expect(trigger.props["aria-label"]).toBe("Open Inbox")
+ expect(trigger.props["aria-pressed"]).toBe(false)
+ expect(trigger.props.className).toContain("aria-expanded:text-foreground")
+ expect(renderer.root.findByType("svg").props.className).not.toContain("fill-current")
+ expect(renderer.root.findByType("svg").props.fill).toBe("none")
+ })
+
+ it("keeps the exact anchored desktop Popover path", async () => {
+ const { renderer } = await renderSurface("desktop")
+ const content = renderer.root.findByType("popover-content")
+ expect(content.props).toMatchObject({ side: "top", align: "end" })
+ expect(content.props.className).toBe(
+ "w-90 max-w-[calc(100vw-1rem)] overflow-hidden p-0",
+ )
+ const trigger = renderer.root.findByType("popover-trigger").props.render
+ expect(trigger.props["aria-label"]).toBe("Inbox")
+ expect(trigger.props["aria-pressed"]).toBeUndefined()
+ expect(trigger.props.className).not.toContain("aria-expanded:text-foreground")
+ expect(renderer.root.findByType("svg").props.className).not.toContain("fill-current")
+ expect(renderer.root.findAllByType("popover-backdrop")).toHaveLength(0)
+ expect(renderer.root.findAllByType("popover-popup")).toHaveLength(0)
+ })
+
+ it("keeps open ownership controlled and resets focus suppression on reopen", async () => {
+ const { renderer, suppressFocusReturnRef, onOpenChange } = await renderSurface("mobile")
+ suppressFocusReturnRef.current = true
+ await act(async () => renderer.root.findByType("popover-root").props.onOpenChange(true, {
+ reason: "trigger-press",
+ event: new Event("click"),
+ }))
+ expect(suppressFocusReturnRef.current).toBe(false)
+ expect(onOpenChange).toHaveBeenCalledWith(true)
+ })
+})
diff --git a/src/web/src/components/community/shell/community-inbox-surface.tsx b/src/web/src/components/community/shell/community-inbox-surface.tsx
new file mode 100644
index 000000000..b5b8f75ab
--- /dev/null
+++ b/src/web/src/components/community/shell/community-inbox-surface.tsx
@@ -0,0 +1,133 @@
+"use client"
+
+import { useRef, type MutableRefObject, type ReactNode, type RefObject } from "react"
+import { Inbox } from "lucide-react"
+import {
+ Popover,
+ PopoverBackdrop,
+ PopoverContent,
+ PopoverPopup,
+ PopoverPortal,
+ PopoverPositioner,
+ PopoverTitle,
+ PopoverTrigger,
+} from "@/components/ui/popover"
+import type { Breakpoint } from "@/hooks/use-mobile"
+import { tid } from "@/lib/community/testids"
+import { cn } from "@/lib/utils"
+import { COMMUNITY_USER_BAR_HEIGHT_CSS } from "./shell-frame-geometry"
+
+type Props = {
+ breakpoint: Breakpoint
+ open?: boolean
+ onOpenChange?: (open: boolean) => void
+ hasUnread?: boolean
+ anchorRef: RefObject<HTMLDivElement | null>
+ suppressFocusReturnRef: MutableRefObject<boolean>
+ children: ReactNode
+}
+
+export function CommunityInboxSurface({
+ breakpoint,
+ open,
+ onOpenChange,
+ hasUnread,
+ anchorRef,
+ suppressFocusReturnRef,
+ children,
+}: Props) {
+ const triggerRef = useRef<HTMLButtonElement>(null)
+ const mobile = breakpoint === "mobile"
+
+ return (
+ <Popover
+ open={open}
+ modal={false}
+ onOpenChange={(nextOpen, details) => {
+ if (nextOpen) suppressFocusReturnRef.current = false
+ else if (
+ details.reason === "outside-press"
+ && typeof Element !== "undefined"
+ && details.event.target instanceof Element
+ && details.event.target.closest(`[data-testid='${tid.userBar}']`)
+ ) {
+ suppressFocusReturnRef.current = true
+ }
+ onOpenChange?.(nextOpen)
+ }}
+ >
+ <PopoverTrigger
+ render={
+ <button
+ ref={triggerRef}
+ data-testid={tid.inboxTrigger}
+ className={cn(
+ "relative grid size-11 place-items-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none sm:size-7",
+ mobile && "aria-expanded:text-foreground",
+ )}
+ aria-label={mobile ? (open ? "Close Inbox" : "Open Inbox") : "Inbox"}
+ aria-pressed={mobile ? open : undefined}
+ />
+ }
+ >
+ <Inbox className="size-4" />
+ {hasUnread && (
+ <span className="absolute right-1 top-1 size-2 rounded-full bg-primary" />
+ )}
+ </PopoverTrigger>
+
+ {mobile ? (
+ <PopoverPortal>
+ <PopoverBackdrop
+ data-testid={tid.inboxMobileBackdrop}
+ className="fixed inset-x-0"
+ style={{
+ top: "var(--app-safe-area-top)",
+ bottom: COMMUNITY_USER_BAR_HEIGHT_CSS,
+ }}
+ />
+ <PopoverPositioner
+ anchor={anchorRef}
+ positionMethod="fixed"
+ side="top"
+ align="start"
+ sideOffset={0}
+ collisionAvoidance={{
+ side: "none",
+ align: "none",
+ fallbackAxisSide: "none",
+ }}
+ >
+ <PopoverPopup
+ data-testid={tid.inboxMobileSurface}
+ initialFocus={false}
+ finalFocus={() => (
+ suppressFocusReturnRef.current ? false : triggerRef.current
+ )}
+ className="w-(--anchor-width) origin-bottom border-0 bg-transparent p-0 shadow-none"
+ >
+ <PopoverTitle className="sr-only">Inbox</PopoverTitle>
+ <div
+ data-testid={tid.inboxMobileCard}
+ className="relative min-h-0 overflow-hidden rounded-t-xl border border-border bg-popover text-popover-foreground shadow-(--e2)"
+ style={{
+ height: `min(28rem, max(0px, calc(100dvh - ${COMMUNITY_USER_BAR_HEIGHT_CSS} - var(--app-safe-area-top))))`,
+ }}
+ >
+ {children}
+ </div>
+ </PopoverPopup>
+ </PopoverPositioner>
+ </PopoverPortal>
+ ) : (
+ <PopoverContent
+ side="top"
+ align="end"
+ className="w-90 max-w-[calc(100vw-1rem)] overflow-hidden p-0"
+ >
+ {children}
+ </PopoverContent>
+ )}
+ </Popover>
+ )
+}
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 1b889c3ac..ee3d98702 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
@@ -24,11 +24,12 @@ describe("ServerRail Home brand mark", () => {
const scrollViewport =
'className="min-h-0 w-full shrink overflow-y-auto overflow-x-clip py-2 thin-scrollbar scrollbar-none"'
const addRegion =
- 'className="flex w-full shrink-0 justify-center" style={{ paddingBottom: bottomInset ?? 8 }}'
+ '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)"'
expect(source).toContain("data-testid={tid.serverRailScroll}")
expect(source).toContain(scrollViewport)
expect(source).toContain(addRegion)
+ expect(source).toContain('"--community-rail-bottom-inset": `${bottomInset ?? 8}px`')
expect(source.indexOf(scrollViewport)).toBeLessThan(source.indexOf(addRegion))
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.tsx b/src/web/src/components/community/shell/server-rail.tsx
index bcfd0154c..9922ea61b 100644
--- a/src/web/src/components/community/shell/server-rail.tsx
+++ b/src/web/src/components/community/shell/server-rail.tsx
@@ -1,6 +1,14 @@
"use client"
-import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react"
+import {
+ memo,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type CSSProperties,
+} from "react"
import { Plus } from "lucide-react"
import { announce, cleanup as cleanupLiveRegion } from "@atlaskit/pragmatic-drag-and-drop-live-region"
import { RailIcon } from "./rail-icon"
@@ -423,7 +431,12 @@ export const ServerRail = memo(function ServerRail({
)}
</div>
- <div className="flex w-full shrink-0 justify-center" style={{ paddingBottom: bottomInset ?? 8 }}>
+ <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}
+ >
<RailIcon
label={<Plus className="size-6" />}
round
diff --git a/src/web/src/components/community/shell/shell-frame-geometry.test.ts b/src/web/src/components/community/shell/shell-frame-geometry.test.ts
index 5a41a95d6..d144e6955 100644
--- a/src/web/src/components/community/shell/shell-frame-geometry.test.ts
+++ b/src/web/src/components/community/shell/shell-frame-geometry.test.ts
@@ -3,7 +3,10 @@ import {
COMMUNITY_RAIL_WIDTH,
COMMUNITY_SEPARATOR_WIDTH,
COMMUNITY_SHELL_INSET,
+ COMMUNITY_USER_BAR_BASE_HEIGHT,
+ COMMUNITY_USER_BAR_HEIGHT_CSS,
desktopUserBarOverlayWidth,
+ mobileInboxAvailableHeight,
} from "./shell-frame-geometry"
describe("desktop community shell geometry", () => {
@@ -19,3 +22,29 @@ describe("desktop community shell geometry", () => {
expect(composerLeft - mainStart).toBe(COMMUNITY_SHELL_INSET)
})
})
+
+describe("mobile Inbox shell geometry", () => {
+ it("uses one safe-area-aware user-bar expression across body portals", () => {
+ expect(COMMUNITY_USER_BAR_BASE_HEIGHT).toBe(60)
+ expect(COMMUNITY_USER_BAR_HEIGHT_CSS).toBe(
+ "calc(60px + var(--app-safe-area-bottom))",
+ )
+ })
+
+ it("defaults both safe areas to zero", () => {
+ expect(mobileInboxAvailableHeight(568)).toBe(508)
+ })
+
+ it.each([
+ [568, 0, 0, 508],
+ [844, 0, 0, 784],
+ [844, 20, 34, 730],
+ [320, 30, 40, 190],
+ [80, 30, 40, 0],
+ ])(
+ "caps a %ipx viewport with %ipx top and %ipx bottom safe areas",
+ (height, top, bottom, expected) => {
+ expect(mobileInboxAvailableHeight(height, top, bottom)).toBe(expected)
+ },
+ )
+})
diff --git a/src/web/src/components/community/shell/shell-frame-geometry.ts b/src/web/src/components/community/shell/shell-frame-geometry.ts
index 1d91c340e..20ad93a3f 100644
--- a/src/web/src/components/community/shell/shell-frame-geometry.ts
+++ b/src/web/src/components/community/shell/shell-frame-geometry.ts
@@ -1,6 +1,23 @@
export const COMMUNITY_RAIL_WIDTH = 56
export const COMMUNITY_SEPARATOR_WIDTH = 1
export const COMMUNITY_SHELL_INSET = 12
+export const COMMUNITY_USER_BAR_BASE_HEIGHT = 60
+export const COMMUNITY_USER_BAR_HEIGHT_CSS =
+ `calc(${COMMUNITY_USER_BAR_BASE_HEIGHT}px + var(--app-safe-area-bottom))`
+
+export function mobileInboxAvailableHeight(
+ viewportHeight: number,
+ safeAreaTop = 0,
+ safeAreaBottom = 0,
+) {
+ return Math.max(
+ 0,
+ viewportHeight
+ - COMMUNITY_USER_BAR_BASE_HEIGHT
+ - safeAreaTop
+ - safeAreaBottom,
+ )
+}
export function desktopUserBarOverlayWidth(sidebarWidth: number) {
return sidebarWidth + COMMUNITY_RAIL_WIDTH + COMMUNITY_SEPARATOR_WIDTH
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 057fbfb72..6b4a22b3a 100644
--- a/src/web/src/components/community/shell/shell-frame-view.tsx
+++ b/src/web/src/components/community/shell/shell-frame-view.tsx
@@ -67,7 +67,12 @@ export function ShellFrameView({
return () => observer.disconnect()
}, [breakpoint])
- const inboxElement = <InboxPopover {...inbox.popoverProps} />
+ const inboxElement = (
+ <InboxPopover
+ {...inbox.popoverProps}
+ surface={breakpoint === "mobile" ? "mobile" : "desktop"}
+ />
+ )
const user = {
id: profile.currentUser.id,
name: profile.currentUser.name,
@@ -152,7 +157,7 @@ export function ShellFrameView({
data-mobile-active={isMobileList || undefined}
className={cn(
"flex flex-col bg-sidebar",
- (isDesktop || isMobileList || isInitial) && "pb-15",
+ (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",
)}
@@ -219,6 +224,7 @@ export function ShellFrameView({
: initialUserBarStyle}
>
<UserBar
+ breakpoint={breakpoint}
user={user}
onOpenProfile={profile.openProfile}
onEditProfile={profile.openUserSettings}
diff --git a/src/web/src/components/community/shell/use-shell-inbox-controller.test.ts b/src/web/src/components/community/shell/use-shell-inbox-controller.test.ts
index df0b5a4a0..b134b51a3 100644
--- a/src/web/src/components/community/shell/use-shell-inbox-controller.test.ts
+++ b/src/web/src/components/community/shell/use-shell-inbox-controller.test.ts
@@ -206,6 +206,23 @@ describe("useShellInboxController", () => {
expect(mocks.markedEnabled.at(-1)).toBe(true)
})
+ it("retains controlled tab and per-tab scroll offsets without data work", async () => {
+ const hook = await renderController()
+ expect(hook.current.popoverProps.activeTab).toBe("unreads")
+
+ await act(async () => {
+ hook.current.popoverProps.onScrollOffsetChange?.("unreads", 42)
+ hook.current.popoverProps.onActiveTabChange?.("marked")
+ })
+
+ expect(hook.current.popoverProps.activeTab).toBe("marked")
+ expect(hook.current.popoverProps.getScrollOffset?.("unreads")).toBe(42)
+ expect(hook.current.popoverProps.getScrollOffset?.("marked")).toBe(0)
+ expect(mocks.markedEnabled.at(-1)).toBe(true)
+ expect(mocks.markAll).not.toHaveBeenCalled()
+ expect(mocks.begin).not.toHaveBeenCalled()
+ })
+
it("closes/projects before cancel and pushes a direct channel without data work", async () => {
const hook = await renderController()
order.length = 0
diff --git a/src/web/src/components/community/shell/use-shell-inbox-controller.ts b/src/web/src/components/community/shell/use-shell-inbox-controller.ts
index f26201443..93f72d689 100644
--- a/src/web/src/components/community/shell/use-shell-inbox-controller.ts
+++ b/src/web/src/components/community/shell/use-shell-inbox-controller.ts
@@ -1,6 +1,6 @@
"use client"
-import { useCallback, useState, type ComponentProps } from "react"
+import { useCallback, useRef, useState, type ComponentProps } from "react"
import { communityKeys } from "@/lib/query-keys"
import { channelHref } from "@/lib/community/community-route"
import type { Marked, Mention, UnreadDm, UnreadServer } from "@/lib/community/models/inbox"
@@ -22,6 +22,7 @@ import {
useUnmarkMessage,
} from "@/hooks/community/mutations"
import type { InboxPopover } from "./community-inbox-popover"
+import type { InboxTab } from "./community-inbox-popover"
import type { QueryClient } from "@tanstack/react-query"
import type { ShellRouter } from "./shell-frame-types"
import {
@@ -56,6 +57,12 @@ export function useShellInboxController({
const mentions = inboxMentions.mentions
const loading = inboxUnreads.isLoading || inboxMentions.isLoading
const [markedTabOpened, setMarkedTabOpened] = useState(false)
+ const [activeTab, setActiveTab] = useState<InboxTab>("unreads")
+ const scrollOffsetsRef = useRef<Record<InboxTab, number>>({
+ unreads: 0,
+ mentions: 0,
+ marked: 0,
+ })
const inboxMarked = useInboxMarked(markedTabOpened)
const { mutate: unmarkMessageMutate } = useUnmarkMessage()
const markAllInboxRead = useMarkAllInboxRead()
@@ -66,6 +73,16 @@ export function useShellInboxController({
navigationPending,
pendingHref,
})
+ const changeActiveTab = useCallback((tab: InboxTab) => {
+ setActiveTab(tab)
+ if (tab === "marked") setMarkedTabOpened(true)
+ }, [])
+ const getScrollOffset = useCallback((tab: InboxTab) => (
+ scrollOffsetsRef.current[tab]
+ ), [])
+ const setScrollOffset = useCallback((tab: InboxTab, scrollTop: number) => {
+ scrollOffsetsRef.current[tab] = scrollTop
+ }, [])
const pushProjected = useCallback((
target: InboxRowTarget,
@@ -196,7 +213,11 @@ export function useShellInboxController({
onOpenDm: openDm,
onOpenMention: openMention,
onOpenMarked: openMarked,
+ activeTab,
+ onActiveTabChange: changeActiveTab,
onMarkedTabSelected: () => setMarkedTabOpened(true),
+ getScrollOffset,
+ onScrollOffsetChange: setScrollOffset,
onMarkAllRead: () => { markAllInboxRead.mutate() },
onDeleteMention: (id) => deleteMention.mutate({ mentionId: id }),
onUnmark: (messageId) => unmarkMessageMutate({ messageId }),
diff --git a/src/web/src/components/community/shell/user-bar.interaction.test.ts b/src/web/src/components/community/shell/user-bar.interaction.test.ts
new file mode 100644
index 000000000..e543f2cda
--- /dev/null
+++ b/src/web/src/components/community/shell/user-bar.interaction.test.ts
@@ -0,0 +1,58 @@
+import { createElement, type PropsWithChildren } from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { describe, expect, it, vi } from "vitest"
+import { UserBar } from "./user-bar"
+import { tid } from "@/lib/community/testids"
+
+vi.mock("./community-inbox-surface", () => ({
+ CommunityInboxSurface: ({ children, ...props }: PropsWithChildren<Record<string, unknown>>) =>
+ createElement("inbox-surface", props, children),
+}))
+vi.mock("../avatar", () => ({
+ Avatar: () => createElement("avatar"),
+}))
+
+async function renderBar() {
+ const order: string[] = []
+ const onInboxOpenChange = vi.fn(() => order.push("close"))
+ const onOpenProfile = vi.fn(() => order.push("profile"))
+ const onEditProfile = vi.fn(() => order.push("settings"))
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(UserBar, {
+ breakpoint: "mobile",
+ user: { id: "u1", name: "User", avatar: "U" },
+ onOpenProfile,
+ onEditProfile,
+ inbox: createElement("inbox-content"),
+ inboxOpen: true,
+ onInboxOpenChange,
+ }))
+ })
+ return { renderer, order, onInboxOpenChange, onOpenProfile, onEditProfile }
+}
+
+describe("UserBar Inbox switching", () => {
+ it.each(["avatar", "name"])("closes before the %s profile action exactly once", async (kind) => {
+ const { renderer, order, onInboxOpenChange, onOpenProfile } = await renderBar()
+ const buttons = renderer.root.findAllByType("button")
+ const button = kind === "avatar" ? buttons[0]! : buttons[1]!
+
+ await act(async () => button.props.onClick({ type: "click" }))
+
+ expect(order).toEqual(["close", "profile"])
+ expect(onInboxOpenChange).toHaveBeenCalledOnce()
+ expect(onOpenProfile).toHaveBeenCalledOnce()
+ })
+
+ it("closes before Settings exactly once", async () => {
+ const { renderer, order, onInboxOpenChange, onEditProfile } = await renderBar()
+ const settings = renderer.root.findByProps({ "data-testid": tid.userSettingsOpen })
+
+ await act(async () => settings.props.onClick())
+
+ expect(order).toEqual(["close", "settings"])
+ expect(onInboxOpenChange).toHaveBeenCalledOnce()
+ expect(onEditProfile).toHaveBeenCalledOnce()
+ })
+})
diff --git a/src/web/src/components/community/shell/user-bar.test.ts b/src/web/src/components/community/shell/user-bar.test.ts
index b03f94a82..bf0d7d807 100644
--- a/src/web/src/components/community/shell/user-bar.test.ts
+++ b/src/web/src/components/community/shell/user-bar.test.ts
@@ -7,6 +7,7 @@ import { tid } from "@/lib/community/testids"
describe("UserBar", () => {
it("keeps the name shrinkable and truncated while the action group stays fixed", () => {
const html = renderToStaticMarkup(createElement(UserBar, {
+ breakpoint: "desktop",
user: {
id: "u1",
name: "A display name that is intentionally much longer than the available sidebar width",
@@ -14,8 +15,11 @@ describe("UserBar", () => {
},
}))
- expect(html).toContain('data-testid="community-user-bar"')
- expect(html).toContain('class="w-full min-w-0 max-w-full shrink-0 overflow-hidden px-3 pb-3 pt-0"')
+ expect(html).toContain(`data-testid="${tid.userBar}"`)
+ expect(html).toContain("var(--app-safe-area-left)")
+ expect(html).toContain("var(--app-safe-area-right)")
+ expect(html).toContain("var(--app-safe-area-bottom)")
+ expect(html).toContain("sm:px-3 sm:pb-3")
expect(html).toContain('class="flex min-w-0 flex-1 items-center gap-2"')
expect(html).toContain('data-testid="community-user-bar-name"')
expect(html).toContain('class="truncate text-sm font-medium leading-tight"')
@@ -26,8 +30,30 @@ describe("UserBar", () => {
const html = renderToStaticMarkup(createElement(UserBarSkeleton))
expect(html).toContain(`data-testid="${tid.initialUserBarPending}"`)
expect(html).toContain("aria-hidden=\"true\"")
- expect(html).toContain('class="w-full min-w-0 max-w-full shrink-0 overflow-hidden px-3 pb-3 pt-0"')
+ expect(html).toContain("var(--app-safe-area-left)")
+ expect(html).toContain("var(--app-safe-area-right)")
+ expect(html).toContain("var(--app-safe-area-bottom)")
expect(html).not.toContain("<button")
expect(html).not.toContain("<a")
})
+
+ it("joins the mobile Inbox to the user bar without seam radii", () => {
+ const openHtml = renderToStaticMarkup(createElement(UserBar, {
+ breakpoint: "mobile",
+ user: { id: "u1", name: "User", avatar: "U" },
+ inboxOpen: true,
+ }))
+ expect(openHtml).toContain(
+ 'class="flex h-12 items-center gap-3 bg-muted px-4 ring-1 ring-border/40 rounded-b-xl"',
+ )
+
+ const closedHtml = renderToStaticMarkup(createElement(UserBar, {
+ breakpoint: "mobile",
+ user: { id: "u1", name: "User", avatar: "U" },
+ inboxOpen: false,
+ }))
+ expect(closedHtml).toContain(
+ 'class="flex h-12 items-center gap-3 bg-muted px-4 ring-1 ring-border/40 rounded-xl"',
+ )
+ })
})
diff --git a/src/web/src/components/community/shell/user-bar.tsx b/src/web/src/components/community/shell/user-bar.tsx
index 71f99022d..395bcb1a5 100644
--- a/src/web/src/components/community/shell/user-bar.tsx
+++ b/src/web/src/components/community/shell/user-bar.tsx
@@ -1,27 +1,62 @@
"use client"
-import type React from "react"
-import { Inbox, Settings } from "lucide-react"
-import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover"
+import {
+ useRef,
+ type MutableRefObject,
+ type ReactNode,
+ type RefObject,
+} from "react"
+import { Settings } from "lucide-react"
import { Avatar } from "../avatar"
import { Skeleton } from "@/components/ui/skeleton"
import type { OpenProfile } from "@/components/community/social/profile-types"
import type { Presence } from "@/lib/community/models/people"
+import type { Breakpoint } from "@/hooks/use-mobile"
import { tid } from "@/lib/community/testids"
+import { cn } from "@/lib/utils"
+import { CommunityInboxSurface } from "./community-inbox-surface"
-export function UserBar({ user, onOpenProfile, onEditProfile, inbox, hasUnread, inboxOpen, onInboxOpenChange }: {
+export function UserBar({ breakpoint, user, onOpenProfile, onEditProfile, inbox, hasUnread, inboxOpen, onInboxOpenChange }: {
+ breakpoint: Breakpoint
user: { id: string; name: string; avatar: string; presence?: Presence }
onOpenProfile?: OpenProfile
onEditProfile?: () => void
- inbox?: React.ReactNode
+ inbox?: ReactNode
hasUnread?: boolean
inboxOpen?: boolean
onInboxOpenChange?: (open: boolean) => void
}) {
+ const inboxAnchorRef = useRef<HTMLDivElement>(null)
+ const suppressInboxFocusReturnRef = useRef(false)
+ const closeInboxForAction = () => {
+ suppressInboxFocusReturnRef.current = true
+ if (inboxOpen) onInboxOpenChange?.(false)
+ }
return (
- <div data-testid="community-user-bar" className="w-full min-w-0 max-w-full shrink-0 overflow-hidden px-3 pb-3 pt-0">
- <div className="flex h-12 items-center gap-3 rounded-xl bg-muted px-4 ring-1 ring-border/40">
- <Inner user={user} onOpenProfile={onOpenProfile} onEditProfile={onEditProfile} inbox={inbox} hasUnread={hasUnread} inboxOpen={inboxOpen} onInboxOpenChange={onInboxOpenChange} />
+ <div
+ data-testid={tid.userBar}
+ className="w-full min-w-0 max-w-full shrink-0 overflow-hidden pl-[max(0.75rem,var(--app-safe-area-left))] pr-[max(0.75rem,var(--app-safe-area-right))] pb-[calc(0.75rem+var(--app-safe-area-bottom))] pt-0 sm:px-3 sm:pb-3"
+ >
+ <div
+ ref={inboxAnchorRef}
+ className={cn(
+ "flex h-12 items-center gap-3 bg-muted px-4 ring-1 ring-border/40",
+ breakpoint === "mobile" && inboxOpen ? "rounded-b-xl" : "rounded-xl",
+ )}
+ >
+ <Inner
+ breakpoint={breakpoint}
+ user={user}
+ onOpenProfile={onOpenProfile}
+ onEditProfile={onEditProfile}
+ inbox={inbox}
+ hasUnread={hasUnread}
+ inboxOpen={inboxOpen}
+ onInboxOpenChange={onInboxOpenChange}
+ inboxAnchorRef={inboxAnchorRef}
+ suppressInboxFocusReturnRef={suppressInboxFocusReturnRef}
+ closeInboxForAction={closeInboxForAction}
+ />
</div>
</div>
)
@@ -32,7 +67,7 @@ export function UserBarSkeleton() {
<div
data-testid={tid.initialUserBarPending}
aria-hidden
- className="w-full min-w-0 max-w-full shrink-0 overflow-hidden px-3 pb-3 pt-0"
+ className="w-full min-w-0 max-w-full shrink-0 overflow-hidden pl-[max(0.75rem,var(--app-safe-area-left))] pr-[max(0.75rem,var(--app-safe-area-right))] pb-[calc(0.75rem+var(--app-safe-area-bottom))] pt-0 sm:px-3 sm:pb-3"
>
<div className="flex h-12 items-center gap-3 rounded-xl bg-muted px-4 ring-1 ring-border/40">
<Skeleton className="size-7 shrink-0 rounded-full" />
@@ -44,41 +79,51 @@ export function UserBarSkeleton() {
)
}
-function Inner({ user, onOpenProfile, onEditProfile, inbox, hasUnread, inboxOpen, onInboxOpenChange }: {
+function Inner({ breakpoint, user, onOpenProfile, onEditProfile, inbox, hasUnread, inboxOpen, onInboxOpenChange, inboxAnchorRef, suppressInboxFocusReturnRef, closeInboxForAction }: {
+ breakpoint: Breakpoint
user: { id: string; name: string; avatar: string; presence?: Presence }
onOpenProfile?: OpenProfile
onEditProfile?: () => void
- inbox?: React.ReactNode
+ inbox?: ReactNode
hasUnread?: boolean
inboxOpen?: boolean
onInboxOpenChange?: (open: boolean) => void
+ inboxAnchorRef: RefObject<HTMLDivElement | null>
+ suppressInboxFocusReturnRef: MutableRefObject<boolean>
+ closeInboxForAction: () => void
}) {
return (
<div className="flex min-w-0 flex-1 items-center gap-2">
- <button onClick={(e) => onOpenProfile?.(user.name, e, undefined, user.id)} className="shrink-0 rounded-full focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">
+ <button onClick={(e) => {
+ closeInboxForAction()
+ onOpenProfile?.(user.name, e, undefined, user.id)
+ }} className="shrink-0 rounded-full focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">
<Avatar label={user.avatar} seed={user.id} size={28} presence={user.presence} ringColor="var(--muted)" />
</button>
- <button onClick={(e) => onOpenProfile?.(user.name, e, undefined, user.id)} className="min-w-0 flex-1 text-left rounded focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">
+ <button onClick={(e) => {
+ closeInboxForAction()
+ onOpenProfile?.(user.name, e, undefined, user.id)
+ }} className="min-w-0 flex-1 text-left rounded focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">
<div data-testid="community-user-bar-name" className="truncate text-sm font-medium leading-tight">{user.name}</div>
</button>
<div className="flex shrink-0 items-center gap-1">
{inbox && (
- <Popover open={inboxOpen} onOpenChange={onInboxOpenChange}>
- <PopoverTrigger
- render={
- <button className="relative grid size-7 place-items-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none" aria-label="Inbox" />
- }
- >
- <Inbox className="size-4" />
- {hasUnread && <span className="absolute right-1 top-1 size-2 rounded-full bg-primary" />}
- </PopoverTrigger>
- <PopoverContent side="top" align="end" className="w-90 max-w-[calc(100vw-1rem)] overflow-hidden p-0">
- {inbox}
- </PopoverContent>
- </Popover>
+ <CommunityInboxSurface
+ breakpoint={breakpoint}
+ open={inboxOpen}
+ onOpenChange={onInboxOpenChange}
+ hasUnread={hasUnread}
+ anchorRef={inboxAnchorRef}
+ suppressFocusReturnRef={suppressInboxFocusReturnRef}
+ >
+ {inbox}
+ </CommunityInboxSurface>
)}
<button
- onClick={onEditProfile}
+ onClick={() => {
+ closeInboxForAction()
+ onEditProfile?.()
+ }}
className="grid size-11 place-items-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none sm:size-7"
aria-label="User settings"
data-testid={tid.userSettingsOpen}
diff --git a/src/web/src/components/home/landing-shell-motion.tsx b/src/web/src/components/home/landing-shell-motion.tsx
index 3ffd9663b..83bde650d 100644
--- a/src/web/src/components/home/landing-shell-motion.tsx
+++ b/src/web/src/components/home/landing-shell-motion.tsx
@@ -931,6 +931,7 @@ function PrototypeUserBar({
</div>
)}
<UserBar
+ breakpoint="desktop"
user={{ id: "gus", name: "Gus", avatar: "avatar:beam:gus" }}
onEditProfile={() => {}}
inbox={scene === "continuity" || scene === "server" || scene === "machine" ? <span /> : undefined}
diff --git a/src/web/src/components/ui/popover.test.ts b/src/web/src/components/ui/popover.test.ts
new file mode 100644
index 000000000..c517f66a2
--- /dev/null
+++ b/src/web/src/components/ui/popover.test.ts
@@ -0,0 +1,31 @@
+import { readFileSync } from "node:fs"
+import { describe, expect, it } from "vitest"
+
+describe("Popover primitive surface", () => {
+ const source = readFileSync(new URL("./popover.tsx", import.meta.url), "utf8")
+
+ it("exposes Base UI's real nonmodal composition parts", () => {
+ for (const part of [
+ "PopoverBackdrop",
+ "PopoverClose",
+ "PopoverPopup",
+ "PopoverPortal",
+ "PopoverPositioner",
+ "PopoverTitle",
+ ]) {
+ expect(source).toContain(`function ${part}`)
+ expect(source).toContain(` ${part},`)
+ }
+ expect(source).toContain("<PopoverPrimitive.Backdrop")
+ expect(source).not.toContain("pointer-events-none fixed z-50")
+ })
+
+ it("keeps existing PopoverContent positioning and portal behavior", () => {
+ expect(source).toContain("function PopoverContent")
+ expect(source).toContain("typeof document !== \"undefined\" ? document.body : null")
+ expect(source).toContain("sideOffset = 6")
+ expect(source).toContain("align = \"start\"")
+ expect(source).toContain('style={{ zIndex: 60 }}')
+ expect(source).toContain("w-72 origin-(--transform-origin) rounded-lg border")
+ })
+})
diff --git a/src/web/src/components/ui/popover.tsx b/src/web/src/components/ui/popover.tsx
index 6f3e3f4e1..66546fd14 100644
--- a/src/web/src/components/ui/popover.tsx
+++ b/src/web/src/components/ui/popover.tsx
@@ -13,6 +13,82 @@ function PopoverTrigger({ ...props }: PopoverPrimitive.Trigger.Props) {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
}
+function PopoverPortal({ container, ...props }: PopoverPrimitive.Portal.Props) {
+ const resolvedContainer = container
+ ?? (typeof document !== "undefined" ? document.body : null)
+ return (
+ <PopoverPrimitive.Portal
+ data-slot="popover-portal"
+ container={resolvedContainer}
+ {...props}
+ />
+ )
+}
+
+function PopoverBackdrop({
+ className,
+ ...props
+}: PopoverPrimitive.Backdrop.Props) {
+ return (
+ <PopoverPrimitive.Backdrop
+ data-slot="popover-backdrop"
+ className={cn(
+ "fixed z-50 bg-black/20 backdrop-blur-[2px] transition-[opacity,backdrop-filter] duration-200 ease-out data-ending-style:opacity-0 data-ending-style:backdrop-blur-none data-starting-style:opacity-0 data-starting-style:backdrop-blur-none",
+ className,
+ )}
+ {...props}
+ />
+ )
+}
+
+function PopoverPositioner({
+ style,
+ ...props
+}: PopoverPrimitive.Positioner.Props) {
+ return (
+ <PopoverPrimitive.Positioner
+ data-slot="popover-positioner"
+ style={{ zIndex: 60, ...style }}
+ {...props}
+ />
+ )
+}
+
+function PopoverPopup({
+ className,
+ ...props
+}: PopoverPrimitive.Popup.Props) {
+ return (
+ <PopoverPrimitive.Popup
+ data-slot="popover-content"
+ className={cn(
+ "rounded-lg border bg-popover text-popover-foreground shadow-md outline-none",
+ "data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95",
+ "data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
+ className,
+ )}
+ {...props}
+ />
+ )
+}
+
+function PopoverClose({ ...props }: PopoverPrimitive.Close.Props) {
+ return <PopoverPrimitive.Close data-slot="popover-close" {...props} />
+}
+
+function PopoverTitle({
+ className,
+ ...props
+}: PopoverPrimitive.Title.Props) {
+ return (
+ <PopoverPrimitive.Title
+ data-slot="popover-title"
+ className={cn("font-heading font-semibold", className)}
+ {...props}
+ />
+ )
+}
+
function PopoverContent({
className,
children,
@@ -56,4 +132,14 @@ function PopoverContent({
)
}
-export { Popover, PopoverTrigger, PopoverContent }
+export {
+ Popover,
+ PopoverBackdrop,
+ PopoverClose,
+ PopoverContent,
+ PopoverPopup,
+ PopoverPortal,
+ PopoverPositioner,
+ PopoverTitle,
+ PopoverTrigger,
+}
diff --git a/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts b/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts
index 11f1d483e..85cc9c2e9 100644
--- a/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts
+++ b/src/web/src/hooks/community/use-inbox-auto-collapse.test.ts
@@ -111,6 +111,18 @@ describe("useInboxAutoCollapse", () => {
expect(hook.current.isProjected(target())).toBe(true)
})
+ it("closes an open Inbox when an unrelated destination publishes", async () => {
+ const hook = await renderHook()
+ await hook.call(() => hook.current.onOpenChange(true))
+ expect(hook.current.open).toBe(true)
+
+ await hook.rerender({ publishedHref: "/c/me" })
+
+ expect(hook.current.open).toBe(false)
+ expect(mocks.activate).not.toHaveBeenCalled()
+ expect(mocks.cancel).not.toHaveBeenCalled()
+ })
+
it("preserves the latest lease across a shell controller remount", async () => {
const queryClient = {} as Options["queryClient"]
const href = "/c/channels/s1/c1"
diff --git a/src/web/src/hooks/community/use-inbox-auto-collapse.ts b/src/web/src/hooks/community/use-inbox-auto-collapse.ts
index d2ff73446..d574e093f 100644
--- a/src/web/src/hooks/community/use-inbox-auto-collapse.ts
+++ b/src/web/src/hooks/community/use-inbox-auto-collapse.ts
@@ -84,6 +84,7 @@ export function useInboxAutoCollapse({
() => store.current,
)
const openRef = useRef(open)
+ const previousPublishedHrefRef = useRef(publishedHref)
const commitLease = useCallback((lease: ProjectionLease) => {
if (store.current?.epoch !== lease.epoch) return
@@ -184,6 +185,14 @@ export function useInboxAutoCollapse({
rollbackProjection(lease.epoch)
}, [commitLease, navigationPending, pendingHref, projection, publishedHref, rollbackProjection, store])
+ useEffect(() => {
+ const previousHref = previousPublishedHrefRef.current
+ previousPublishedHrefRef.current = publishedHref
+ if (previousHref === publishedHref || !openRef.current) return
+ openRef.current = false
+ setOpen(false)
+ }, [publishedHref])
+
return {
open,
onOpenChange,
diff --git a/src/web/src/hooks/community/use-inbox.test.ts b/src/web/src/hooks/community/use-inbox.test.ts
index b2102725a..cc2078028 100644
--- a/src/web/src/hooks/community/use-inbox.test.ts
+++ b/src/web/src/hooks/community/use-inbox.test.ts
@@ -272,6 +272,10 @@ describe("useInboxUnreads / inboxUnreadsQueryFn", () => {
React.createElement(Harness),
))
})
+ await qc.invalidateQueries({
+ queryKey: communityKeys.inboxUnreads(),
+ exact: true,
+ })
await vi.waitFor(() => expect(latest?.servers).toEqual([]))
expect(latest?.servers).toEqual([])
expect(latest?.dms).toEqual([])
@@ -369,6 +373,10 @@ describe("useInboxMentions / inboxMentionsQueryFn", () => {
React.createElement(Harness),
))
})
+ await qc.invalidateQueries({
+ queryKey: communityKeys.inboxMentions(),
+ exact: true,
+ })
await vi.waitFor(() => expect(latest?.mentions).toEqual([]))
expect(latest?.mentions).toEqual([])
expect(latest?.hasProjectedMention).toBe(true)
@@ -376,6 +384,50 @@ describe("useInboxMentions / inboxMentionsQueryFn", () => {
})
})
+describe("eager Inbox query ownership", () => {
+ it("keeps WS-live feeds fresh across observer remounts without duplicate reads", async () => {
+ apiFetchMock.mockImplementation((url: string) => Promise.resolve(
+ url.endsWith("/unreads")
+ ? { servers: [], dms: [] }
+ : { mentions: [] },
+ ))
+ const { useInboxMentions, useInboxUnreads } = await import("./use-inbox")
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ function Harness() {
+ useInboxUnreads()
+ useInboxMentions()
+ return null
+ }
+ const tree = React.createElement(
+ QueryClientProvider,
+ { client: qc },
+ React.createElement(Harness),
+ )
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(tree)
+ })
+ await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(2))
+ await act(async () => renderer.unmount())
+ await act(async () => {
+ renderer = TestRenderer.create(tree)
+ })
+
+ expect(apiFetchMock).toHaveBeenCalledTimes(2)
+ for (const queryKey of [
+ communityKeys.inboxUnreads(),
+ communityKeys.inboxMentions(),
+ ]) {
+ const options = qc.getQueryCache().find({ queryKey })?.options
+ expect(options?.staleTime).toBe(Infinity)
+ expect(options?.refetchOnReconnect).toBe(true)
+ }
+ await qc.invalidateQueries({ queryKey: communityKeys.inbox() })
+ await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledTimes(4))
+ await act(async () => renderer.unmount())
+ })
+})
+
describe("useInboxMarked", () => {
it("fetches the identity-aware marked feed only when enabled", async () => {
apiFetchMock.mockResolvedValue({ marked: [] })
diff --git a/src/web/src/hooks/community/use-inbox.ts b/src/web/src/hooks/community/use-inbox.ts
index 95572e257..a75a71d5f 100644
--- a/src/web/src/hooks/community/use-inbox.ts
+++ b/src/web/src/hooks/community/use-inbox.ts
@@ -89,6 +89,8 @@ export function useInboxUnreads(): UseQueryResult<UnreadsResponse> & {
queryKey: communityKeys.inboxUnreads(),
queryFn,
placeholderData: keepPreviousData,
+ staleTime: Infinity,
+ refetchOnReconnect: true,
})
useEffect(() => {
if (!query.data) return
@@ -232,6 +234,8 @@ export function useInboxMentions(): UseQueryResult<MentionsResponse> & {
queryKey: communityKeys.inboxMentions(),
queryFn: inboxMentionsQueryFn,
placeholderData: keepPreviousData,
+ staleTime: Infinity,
+ refetchOnReconnect: true,
})
useEffect(() => {
if (!query.data) return
diff --git a/src/web/src/lib/community/testids.test.ts b/src/web/src/lib/community/testids.test.ts
index 159fee1d3..7f4c6dcf8 100644
--- a/src/web/src/lib/community/testids.test.ts
+++ b/src/web/src/lib/community/testids.test.ts
@@ -7,6 +7,16 @@ describe("community QA selectors", () => {
expect(tid.wsRetry).toBe("community-ws-retry")
})
+ it("exposes the adaptive Inbox surface from the canonical registry", () => {
+ expect(tid.userBar).toBe("community-user-bar")
+ expect(tid.inboxTrigger).toBe("community-inbox-trigger")
+ expect(tid.inboxMobileBackdrop).toBe("community-inbox-mobile-backdrop")
+ expect(tid.inboxMobileSurface).toBe("community-inbox-mobile-surface")
+ expect(tid.inboxMobileCard).toBe("community-inbox-mobile-card")
+ expect(tid.inboxTabList).toBe("community-inbox-tab-list")
+ expect(tid.inboxTabScroll("marked")).toBe("community-inbox-marked-scroll")
+ })
+
it("keys forum-title read models by their stable child identity", () => {
expect(tid.inboxUnreadChild("post_1")).toBe("community-inbox-unread-child-post_1")
expect(tid.inboxUnreadChannel("channel_1")).toBe("community-inbox-unread-channel-channel_1")
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index 8ba629bc8..429d8a026 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -187,5 +187,13 @@ export const tid = {
inboxUnreadChannel: (id: string) => `community-inbox-unread-channel-${id}`,
inboxUnreadChild: (id: string) => `community-inbox-unread-child-${id}`,
inboxUnreadDm: (id: string) => `community-inbox-unread-dm-${id}`,
+ userBar: "community-user-bar",
+ inboxTrigger: "community-inbox-trigger",
+ inboxMobileBackdrop: "community-inbox-mobile-backdrop",
+ inboxMobileSurface: "community-inbox-mobile-surface",
+ inboxMobileCard: "community-inbox-mobile-card",
+ inboxTabList: "community-inbox-tab-list",
+ inboxTabScroll: (tab: "unreads" | "mentions" | "marked") =>
+ `community-inbox-${tab}-scroll`,
channelRefPill: (id: string) => `community-channel-ref-pill-${id}`,
} as const
diff --git a/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts b/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts
index 28d67835e..4003cbf67 100644
--- a/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts
+++ b/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts
@@ -125,7 +125,7 @@ test.describe.serial("Inbox/read refresh ownership", () => {
await seedMessage("alice", channelB, `Unrelated B ${stamp}`)
const { page } = await asUser("bob")
- await gotoAfterUserWsAuth(page, "/c/me")
+ await gotoAfterUserWsAuth(page, "/c/me/friends")
await page.getByRole("button", { name: "Inbox", exact: true }).click()
await expect(page.getByTestId(tid.inboxUnreadChannel(channelA))).toBeVisible()
await expect(page.getByTestId(tid.inboxUnreadChannel(channelB))).toBeVisible()
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 b51e672f3..a120c26b4 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
@@ -90,7 +90,7 @@ test("community checkpoint keeps the committed frame live until navigation commi
await page.waitForTimeout(150)
await expect(page.getByPlaceholder("Search friends")).toBeVisible()
await machinesGate.release()
- await expect(page.getByRole("heading", { name: "No machines yet", exact: true }))
+ await expect(page.getByTestId(tid.machinePairOpen))
.toBeVisible({ timeout: 30_000 })
expect(mutations).toEqual([])
diff --git a/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts b/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts
index 7c4a5d53c..09b75095b 100644
--- a/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts
+++ b/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts
@@ -171,7 +171,7 @@ async function expectRailReplacementDoesNotBlockMessages({
try {
const latestId = await triggerUnread()
await railHeld
- await page.getByRole("button", { name: "Inbox", exact: true }).click()
+ await page.getByTestId(tid.inboxTrigger).click()
const inboxRow = page.getByTestId(inboxRowTestId)
await expect(inboxRow).toBeVisible({ timeout: 30_000 })
const messagesResponse = page.waitForResponse((response) => (
@@ -310,7 +310,7 @@ test.describe.serial("account unread projection", () => {
await page.setViewportSize({ width: 390, height: 844 })
await gotoAfterUserWsAuth(page, "/c/me")
- await page.getByRole("button", { name: "Inbox", exact: true }).click()
+ await page.getByTestId(tid.inboxTrigger).click()
await expect(page.getByTestId(tid.inboxUnreadChannel(unreadChannel))).toHaveCount(0)
await expect(page.getByTestId(tid.inboxUnreadChild(forumChild))).toBeVisible()
await expect(page.getByTestId(tid.inboxUnreadDm(dmId))).toBeVisible()
@@ -436,7 +436,7 @@ test.describe.serial("account unread projection", () => {
await seedDmMessage("alice", dmId, `DM mark all ${stamp}`)
const { page } = await asUser("bob")
- await gotoAfterUserWsAuth(page, "/c/me")
+ await gotoAfterUserWsAuth(page, "/c/me/friends")
await page.getByRole("button", { name: "Inbox", exact: true }).click()
await expect(page.getByTestId(tid.inboxUnreadChannel(channelId))).toBeVisible()
await expect(page.getByTestId(tid.inboxUnreadDm(dmId))).toBeVisible()
diff --git a/src/web/src/test/e2e-ui/53-mobile-inbox-surface.spec.ts b/src/web/src/test/e2e-ui/53-mobile-inbox-surface.spec.ts
new file mode 100644
index 000000000..71a1dd2cb
--- /dev/null
+++ b/src/web/src/test/e2e-ui/53-mobile-inbox-surface.spec.ts
@@ -0,0 +1,337 @@
+import type { Page, Request } from "@playwright/test"
+import { expect, sessionCookie, test } from "./_fixtures/community-fixture"
+import { gotoAfterUserWsAuth } from "./_fixtures/actions"
+import { proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"
+import { WEB_URL } from "./_setup/paths"
+import {
+ seedChannel,
+ seedJoinServer,
+ seedMark,
+ seedMessage,
+ seedServer,
+} from "./_fixtures/seed"
+import { tid } from "./_fixtures/testids"
+
+type SurfaceGeometry = {
+ viewport: { width: number; height: number }
+ userBar: { top: number; bottom: number; left: number; right: number }
+ card: { top: number; bottom: number; left: number; right: number; height: number }
+ backdrop: { top: number; bottom: number }
+ seam: {
+ cardTopLeft: string
+ cardTopRight: string
+ cardBottomLeft: string
+ cardBottomRight: string
+ userBarTopLeft: string
+ userBarTopRight: string
+ userBarBottomLeft: string
+ userBarBottomRight: string
+ }
+ userBarOwnsCenter: boolean
+ rootScrollTop: number
+}
+
+async function removeServerChannels(serverId: string) {
+ const headers = { Cookie: sessionCookie("alice"), Origin: WEB_URL }
+ const response = await fetch(`${WEB_URL}/api/community/servers/${serverId}/channels`, { headers })
+ if (!response.ok) throw new Error(`list server channels failed (${response.status})`)
+ const body = await response.json() as { channels: Array<{ id: string }> }
+ for (const channel of body.channels) {
+ const deleted = await fetch(`${WEB_URL}/api/community/channels/${channel.id}`, {
+ method: "DELETE",
+ headers,
+ })
+ if (!deleted.ok) throw new Error(`delete server channel failed (${deleted.status})`)
+ }
+}
+
+async function surfaceGeometry(page: Page): Promise<SurfaceGeometry> {
+ return page.getByTestId(tid.inboxMobileCard).evaluate((card, ids) => {
+ const userBar = document.querySelector<HTMLElement>(
+ `[data-testid='${ids.userBar}']`,
+ )
+ const backdrop = document.querySelector<HTMLElement>(
+ `[data-testid='${ids.backdrop}']`,
+ )
+ const userBarSurface = userBar?.firstElementChild as HTMLElement | null
+ if (!userBar || !userBarSurface || !backdrop) {
+ throw new Error("missing mobile Inbox geometry")
+ }
+ const userRect = userBar.getBoundingClientRect()
+ const cardRect = card.getBoundingClientRect()
+ const backdropRect = backdrop.getBoundingClientRect()
+ const cardStyle = getComputedStyle(card)
+ const userBarStyle = getComputedStyle(userBarSurface)
+ const hit = document.elementFromPoint(
+ userRect.left + userRect.width / 2,
+ userRect.top + userRect.height / 2,
+ )
+ return {
+ viewport: { width: innerWidth, height: innerHeight },
+ userBar: {
+ top: userRect.top,
+ bottom: userRect.bottom,
+ left: userRect.left,
+ right: userRect.right,
+ },
+ card: {
+ top: cardRect.top,
+ bottom: cardRect.bottom,
+ left: cardRect.left,
+ right: cardRect.right,
+ height: cardRect.height,
+ },
+ backdrop: { top: backdropRect.top, bottom: backdropRect.bottom },
+ seam: {
+ cardTopLeft: cardStyle.borderTopLeftRadius,
+ cardTopRight: cardStyle.borderTopRightRadius,
+ cardBottomLeft: cardStyle.borderBottomLeftRadius,
+ cardBottomRight: cardStyle.borderBottomRightRadius,
+ userBarTopLeft: userBarStyle.borderTopLeftRadius,
+ userBarTopRight: userBarStyle.borderTopRightRadius,
+ userBarBottomLeft: userBarStyle.borderBottomLeftRadius,
+ userBarBottomRight: userBarStyle.borderBottomRightRadius,
+ },
+ userBarOwnsCenter: !!hit && userBar.contains(hit),
+ rootScrollTop: document.scrollingElement?.scrollTop ?? 0,
+ }
+ }, {
+ userBar: tid.userBar,
+ backdrop: tid.inboxMobileBackdrop,
+ })
+}
+
+function observeWrites(page: Page) {
+ const writes: string[] = []
+ const listener = (request: Request) => {
+ if (!["GET", "HEAD", "OPTIONS"].includes(request.method())) {
+ writes.push(`${request.method()} ${new URL(request.url()).pathname}`)
+ }
+ }
+ page.on("request", listener)
+ return { writes, stop: () => page.off("request", listener) }
+}
+
+test.describe.serial("mobile Inbox interactive user-bar base", () => {
+ test.setTimeout(180_000)
+
+ test("scopes the real backdrop above the safe-area user bar and dismisses without writes", async ({ asUser }) => {
+ const stamp = Date.now()
+ const serverId = await seedServer("alice", `Inbox surface ${stamp}`)
+ const channelId = await seedChannel("alice", serverId, `inbox-${stamp}`)
+ await seedJoinServer("alice", "bob", serverId)
+ await seedMessage("alice", channelId, `Inbox unread ${stamp}`)
+
+ const bob = await asUser("bob")
+ const ws = await proxyCommunityWebSockets(bob.context)
+ await bob.page.setViewportSize({ width: 390, height: 844 })
+ await gotoAfterUserWsAuth(bob.page, `/c/channels/${serverId}`)
+ await expect(bob.page.getByTestId(tid.inboxTrigger)).toBeVisible()
+
+ await bob.page.evaluate(() => {
+ const style = document.documentElement.style
+ style.setProperty("--app-safe-area-top", "20px")
+ style.setProperty("--app-safe-area-right", "16px")
+ style.setProperty("--app-safe-area-bottom", "34px")
+ style.setProperty("--app-safe-area-left", "18px")
+ })
+ const writes = observeWrites(bob.page)
+ const wsBefore = ws.frames.length
+
+ const inboxTrigger = bob.page.getByTestId(tid.inboxTrigger)
+ const inboxIcon = inboxTrigger.locator("svg")
+ await expect(inboxTrigger).toHaveAttribute("aria-label", "Open Inbox")
+ await expect(inboxTrigger).toHaveAttribute("aria-pressed", "false")
+ await expect(inboxIcon).toHaveAttribute("fill", "none")
+ await expect(inboxIcon).not.toHaveClass(/fill-current/)
+ const closedInboxIconColor = await inboxIcon.evaluate((element) => (
+ getComputedStyle(element).color
+ ))
+ await inboxTrigger.click()
+ await bob.page.mouse.move(0, 0)
+ const mobileSurface = bob.page.getByTestId(tid.inboxMobileSurface)
+ await expect(mobileSurface).toBeVisible()
+ await expect(mobileSurface).toHaveAttribute("role", "dialog")
+ await expect(mobileSurface).not.toHaveAttribute("aria-modal", "true")
+ await expect(inboxTrigger).toHaveAttribute("aria-expanded", "true")
+ await expect(inboxTrigger).toHaveAttribute("aria-controls", await mobileSurface.getAttribute("id") ?? "")
+ await expect(inboxTrigger).toHaveAttribute("aria-label", "Close Inbox")
+ await expect(inboxTrigger).toHaveAttribute("aria-pressed", "true")
+ await expect(inboxIcon).toHaveAttribute("fill", "none")
+ await expect(inboxIcon).not.toHaveClass(/fill-current/)
+ await expect.poll(() => inboxIcon.evaluate((element) => (
+ getComputedStyle(element).color
+ ))).not.toBe(closedInboxIconColor)
+ await expect(bob.page.getByRole("button", { name: "Close Inbox" })).toHaveCount(1)
+ await expect(inboxTrigger).toBeFocused()
+ const geometry = await surfaceGeometry(bob.page)
+ expect(Math.abs(geometry.card.bottom - geometry.userBar.top)).toBeLessThanOrEqual(1)
+ expect(Math.abs(geometry.backdrop.bottom - geometry.userBar.top)).toBeLessThanOrEqual(1)
+ expect(geometry.backdrop.top).toBe(20)
+ expect(geometry.userBar.bottom).toBe(844)
+ expect(geometry.userBarOwnsCenter).toBe(true)
+ expect(geometry.card.height).toBeLessThanOrEqual(448)
+ expect(geometry.card.top).toBeGreaterThanOrEqual(20)
+ expect(geometry.seam.cardTopLeft).not.toBe("0px")
+ expect(geometry.seam.cardTopRight).not.toBe("0px")
+ expect(geometry.seam.cardBottomLeft).toBe("0px")
+ expect(geometry.seam.cardBottomRight).toBe("0px")
+ expect(geometry.seam.userBarTopLeft).toBe("0px")
+ expect(geometry.seam.userBarTopRight).toBe("0px")
+ expect(geometry.seam.userBarBottomLeft).not.toBe("0px")
+ expect(geometry.seam.userBarBottomRight).not.toBe("0px")
+ expect(geometry.rootScrollTop).toBe(0)
+
+ await bob.page.mouse.click(8, 100)
+ await expect(bob.page.getByTestId(tid.inboxMobileSurface)).toHaveCount(0)
+ await expect(inboxTrigger).toBeFocused()
+ await expect(inboxTrigger).toHaveAttribute("aria-label", "Open Inbox")
+ await expect(inboxTrigger).toHaveAttribute("aria-pressed", "false")
+ await expect(inboxIcon).toHaveAttribute("fill", "none")
+ await expect(inboxIcon).not.toHaveClass(/fill-current/)
+ await expect.poll(() => inboxIcon.evaluate((element) => (
+ getComputedStyle(element).color
+ ))).toBe(closedInboxIconColor)
+ await expect(bob.page).toHaveURL(new RegExp(`/c/channels/${serverId}$`))
+ expect(writes.writes).toEqual([])
+ expect(ws.frames).toHaveLength(wsBefore)
+
+ await inboxTrigger.click()
+ await inboxTrigger.click()
+ await expect(bob.page.getByTestId(tid.inboxMobileSurface)).toHaveCount(0)
+ await expect(inboxTrigger).toBeFocused()
+
+ await inboxTrigger.click()
+ await bob.page.keyboard.press("Escape")
+ await expect(bob.page.getByTestId(tid.inboxMobileSurface)).toHaveCount(0)
+ await expect(inboxTrigger).toBeFocused()
+
+ await inboxTrigger.click()
+ await bob.page.getByTestId(tid.userSettingsOpen).click()
+ await expect(bob.page.getByTestId(tid.inboxMobileSurface)).toHaveCount(0)
+ await expect(bob.page.getByTestId(tid.settingsShell)).toHaveCount(1)
+ await expect(inboxTrigger).not.toBeFocused()
+ await bob.page.getByTestId(tid.settingsClose).click()
+
+ await inboxTrigger.click()
+ await bob.page.getByTestId(tid.userBar).locator("button").first().click()
+ await expect(bob.page.getByTestId(tid.inboxMobileSurface)).toHaveCount(0)
+ await expect(bob.page.getByTestId(tid.profileCard)).toHaveCount(1)
+ await expect(inboxTrigger).not.toBeFocused()
+ await bob.page.keyboard.press("Escape")
+
+ await bob.page.setViewportSize({ width: 320, height: 568 })
+ await inboxTrigger.click()
+ const compact = await surfaceGeometry(bob.page)
+ expect(Math.abs(compact.card.bottom - compact.userBar.top)).toBeLessThanOrEqual(1)
+ expect(compact.card.top).toBeGreaterThanOrEqual(20)
+ expect(compact.card.left).toBeGreaterThanOrEqual(18)
+ expect(compact.card.right).toBeLessThanOrEqual(320 - 16)
+ await inboxTrigger.click()
+
+ expect(writes.writes).toEqual([])
+ expect(ws.frames).toHaveLength(wsBefore)
+ writes.stop()
+ })
+
+ test("preserves Marked tab, scroll, and request ownership across 639↔640", async ({ asUser }) => {
+ const stamp = Date.now()
+ const serverId = await seedServer("alice", `Inbox continuity ${stamp}`)
+ const channelId = await seedChannel("alice", serverId, `continuity-${stamp}`)
+ const emptyServerId = await seedServer("alice", `Inbox continuity empty ${stamp}`)
+ await removeServerChannels(emptyServerId)
+ await seedJoinServer("alice", "bob", serverId)
+ await seedJoinServer("alice", "bob", emptyServerId)
+ for (let index = 0; index < 14; index += 1) {
+ const messageId = await seedMessage("alice", channelId, `Marked ${stamp} ${index}`)
+ await seedMark("bob", channelId, messageId)
+ }
+
+ const bob = await asUser("bob")
+ let heldFirstAuthOk = false
+ const ws = await proxyCommunityWebSockets(bob.context, {
+ decideConnectionFrame: (frame) => {
+ if (frame.type !== "auth.ok" || heldFirstAuthOk) return "forward"
+ heldFirstAuthOk = true
+ return "hold"
+ },
+ })
+ const inboxGets: string[] = []
+ const completedInboxGets: string[] = []
+ const eagerInboxPaths = [
+ "/api/community/users/me/inbox/unreads",
+ "/api/community/users/me/inbox/mentions",
+ ]
+ bob.page.on("request", (request) => {
+ const path = new URL(request.url()).pathname
+ if (request.method() === "GET" && path.includes("/users/me/inbox/")) {
+ inboxGets.push(path)
+ }
+ })
+ bob.page.on("requestfinished", (request) => {
+ const path = new URL(request.url()).pathname
+ if (request.method() === "GET" && path.includes("/users/me/inbox/")) {
+ completedInboxGets.push(path)
+ }
+ })
+ await bob.page.setViewportSize({ width: 639, height: 844 })
+ await bob.page.goto(`/c/channels/${emptyServerId}`, { waitUntil: "commit" })
+ await expect.poll(() => eagerInboxPaths.every((path) => (
+ completedInboxGets.filter((completed) => completed === path).length >= 1
+ )), { timeout: 30_000 }).toBe(true)
+ await expect.poll(ws.heldConnectionCount).toBe(1)
+ expect(ws.releaseHeldConnections((frame) => frame.type === "auth.ok")).toBe(1)
+ await expect.poll(() => eagerInboxPaths.every((path) => (
+ completedInboxGets.filter((completed) => completed === path).length >= 2
+ ))).toBe(true)
+ const writes = observeWrites(bob.page)
+ const wsBefore = ws.frames.length
+
+ await bob.page.getByTestId(tid.inboxTrigger).click()
+ await bob.page.getByRole("tab", { name: "Marked" }).click()
+ const markedScroll = bob.page.getByTestId(tid.inboxTabScroll("marked"))
+ await expect(markedScroll.getByText(`Marked ${stamp} 13`, { exact: true })).toBeAttached()
+ const priorScroll = await markedScroll.evaluate((element) => {
+ element.scrollTop = element.scrollHeight
+ return element.scrollTop
+ })
+ expect(priorScroll).toBeGreaterThan(0)
+ const getsBeforeResize = inboxGets.length
+
+ await bob.page.setViewportSize({ width: 640, height: 844 })
+ await expect(bob.page.getByTestId(tid.inboxMobileSurface)).toHaveCount(0)
+ await expect(bob.page.locator("[data-slot='popover-content']")).toBeVisible()
+ await expect(bob.page.getByRole("tab", { name: "Marked" })).toHaveAttribute("aria-selected", "true")
+ const desktopScroll = bob.page.getByTestId(tid.inboxTabScroll("marked"))
+ await expect.poll(() => desktopScroll.evaluate((element) => element.scrollTop))
+ .toBeGreaterThanOrEqual(priorScroll - 1)
+
+ await bob.page.setViewportSize({ width: 639, height: 844 })
+ await expect(bob.page.getByTestId(tid.inboxMobileSurface)).toBeVisible()
+ await expect(bob.page.getByRole("tab", { name: "Marked" })).toHaveAttribute("aria-selected", "true")
+ const mobileScroll = bob.page.getByTestId(tid.inboxTabScroll("marked"))
+ const restoredMobileScroll = await mobileScroll.evaluate((element) => ({
+ scrollTop: element.scrollTop,
+ maxScrollTop: element.scrollHeight - element.clientHeight,
+ }))
+ expect(Math.abs(
+ restoredMobileScroll.scrollTop
+ - Math.min(priorScroll, restoredMobileScroll.maxScrollTop),
+ )).toBeLessThanOrEqual(1)
+
+ await bob.page.setViewportSize({ width: 1280, height: 900 })
+ const desktopContent = bob.page.locator("[data-slot='popover-content']")
+ await expect(desktopContent).toBeVisible()
+ await expect.poll(async () => (await desktopContent.boundingBox())?.width ?? 0)
+ .toBeGreaterThanOrEqual(359)
+ const desktopBox = await desktopContent.boundingBox()
+ expect(desktopBox?.width).toBeLessThanOrEqual(361)
+ await expect(bob.page.getByTestId(tid.inboxMobileBackdrop)).toHaveCount(0)
+ await expect(bob.page.getByRole("tab", { name: "Marked" })).toHaveAttribute("aria-selected", "true")
+
+ expect(inboxGets).toHaveLength(getsBeforeResize)
+ expect(writes.writes).toEqual([])
+ expect(ws.frames).toHaveLength(wsBefore)
+ writes.stop()
+ })
+})