Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): align forum spacing and post interactions (#1149)

Generc48c65efd01f
diff --git a/DESIGN.md b/DESIGN.md
index 4ef28403b..10332d9c6 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -113,7 +113,7 @@ Two stages, not three. The split lives at **`640px`** — Tailwind's default `sm
| **Mobile** | `< 640px` | Single column with pathname-owned list/detail routing. Back button in detail headers. Popovers may promote to sheets when they'd overflow. |
| **Desktop** | `≥ 640px` | Multi-column shells — server rail + channel/DM sidebar + main (in community), or app sidebar + workspace (elsewhere). No back button in headers. |
-Forum post actions use the client platform independently of these layout checkpoints. Mobile native and mobile Web, including tablet browsers, keep actions visible at every width. Desktop native and desktop Web reveal actions on row hover, row focus or while the corresponding popup is open, including in narrow windows. Unknown/initial hydration keeps actions visible. Actions retain their 32px buttons and layout space; permissions determine which buttons and columns exist. This is the Forum-specific exception to the general touch-target sizing rule below. The first title row is at least 32px even without actions, and grows with content; summaries start below it. Forum lists use horizontal 0 / vertical 8px padding, rows use 16px, and preview margins plus metadata/tag gaps use 8px. Preserve the narrow tag row's 28px author-name alignment and the existing footer order. Selected ordinary filter chips use an inset ring without enlarging the horizontal rail.
+Forum post actions use the client platform independently of these layout checkpoints. Mobile native and mobile Web, including tablet browsers, keep actions visible at every width. Desktop native and desktop Web reveal actions on row hover, row focus or while the corresponding popup is open, including in narrow windows. Unknown/initial hydration keeps actions visible. Actions retain their 32px buttons and layout space; permissions determine which buttons and columns exist. This is the Forum-specific exception to the general touch-target sizing rule below. The first title row is at least 32px even without actions, and grows with content; summaries start immediately below it. Forum lists have zero padding; posts retain 16px horizontal and zero vertical padding. An independent 1px separator spans the original row width with the original half-opacity border color, 6.6px above and below; omit it before the first post and after the last, and give the first item 6.6px of top space. Author names stay on one line with ellipsis, capped at the smaller of 12rem or 40% of the metadata width; retain their full text and hover title. Preview-to-author spacing and metadata/tag gaps remain 8px. Both skeletons and measured virtual items share the same composition, including fractional separator spacing. A loaded post's full measured item owns continuous hover background and desktop action visibility across its separator and spacing; pointer activation covers the same item and assigns its separator/prefix to the following post. Original content keyboard and action-event guards remain, and placeholders have no interactive hover or activation. Preserve the narrow tag row's 28px author-name alignment and the existing footer order. Selected ordinary filter chips use an inset ring without enlarging the horizontal rail.
For Community server routes, the URL owns selection and the checkpoint owns composition:
diff --git a/src/web/src/components/community/channels/forum-post-list.tsx b/src/web/src/components/community/channels/forum-post-list.tsx
index 3196be650..f924d3ed0 100644
--- a/src/web/src/components/community/channels/forum-post-list.tsx
+++ b/src/web/src/components/community/channels/forum-post-list.tsx
@@ -11,12 +11,14 @@ import { useObservedRegion, type ResourceObservation } from "@/lib/observability
import { visibleVirtualItems } from "@/lib/observability/virtual-window"
import type { ForumThread } from "@/lib/community/models/message"
import { tid } from "@/lib/community/testids"
+import { cn } from "@/lib/utils"
import { EmptyState } from "../empty-state"
+import { Separator } from "@/components/ui/separator"
import { VirtualRows } from "../messages/virtual-cursor-list"
import { useInitialPositionTransition } from "../messages/initial-position-transition"
const OVERSCAN = 5
-export const FORUM_LIST_SPACING_CLASS = "px-0 py-2"
+export const FORUM_LIST_SPACING_CLASS = "p-0"
const forumRangeExtractor = (range: Range) => defaultRangeExtractor({ ...range, overscan: range.overscan + range.endIndex - range.startIndex + 1 })
type Props = {
posts: ForumThread[]
@@ -30,9 +32,23 @@ type Props = {
onLoadMore?: () => void
onScrollRoot?: (node: HTMLDivElement | null) => void
loadingContent: ReactNode
+ onOpenPost?: (postId: string) => void
renderPost: (post: ForumThread, index: number) => ReactNode
}
+export function ForumPostListItem({ first, children, onActivate }: { first: boolean; children: ReactNode; onActivate?: () => void }) {
+ return <div data-slot="community-forum-list-item" className={cn("group/card flow-root rounded transition-colors has-data-page-swipe-navigation-row:cursor-pointer has-data-page-swipe-navigation-row:hover:bg-accent/45", first && "pt-[6.6px]")}
+ role={onActivate ? "presentation" : undefined}
+ onClick={onActivate ? event => {
+ const post = event.currentTarget.querySelector(":scope > [data-page-swipe-navigation-row]")
+ if (!post || (event.target instanceof Node && post.contains(event.target))) return
+ onActivate()
+ } : undefined}>
+ {!first && <Separator aria-hidden="true" className="my-[6.6px] bg-border/50" />}
+ {children}
+ </div>
+}
+
export function ForumPostList(props: Props) {
return <ForumPostListEntry key={props.positionScope ? hashKey(conversationListScopeKey(props.positionScope)) : undefined} {...props} />
}
@@ -44,7 +60,7 @@ function ForumPostListEntry(props: Props) {
return <ForumPostListOwner {...props} />
}
-function ForumPostListOwner({ posts, loading, observation, hasMore, loadingMore, isFetching, isError, onLoadMore, onScrollRoot, renderPost, loadingContent }: Props) {
+function ForumPostListOwner({ posts, loading, observation, hasMore, loadingMore, isFetching, isError, onLoadMore, onScrollRoot, onOpenPost, renderPost, loadingContent }: Props) {
const scrollRef = useRef<HTMLDivElement>(null)
const initialized = useRef(false)
const [positionReady, setPositionReady] = useState(false)
@@ -87,10 +103,12 @@ function ForumPostListOwner({ posts, loading, observation, hasMore, loadingMore,
getScrollElement: () => scrollRef.current,
estimateSize: () => 128,
measureElement: (element, entry, instance) => {
- const size = measureElement(element, entry, instance)
- if (size > 0) return size
const index = instance.indexFromElement(element)
const cached = instance.itemSizeCache.get(instance.options.getItemKey(index))
+ const size = instance.options.useCachedMeasurements || (!entry && cached !== undefined)
+ ? measureElement(element, entry, instance)
+ : entry?.borderBoxSize?.[0]?.blockSize ?? element.getBoundingClientRect().height
+ if (size > 0) return size
return cached && cached > 0 ? cached : instance.options.estimateSize(index)
},
getItemKey,
@@ -122,7 +140,8 @@ function ForumPostListOwner({ posts, loading, observation, hasMore, loadingMore,
className={`flex-1 overflow-y-auto thin-scrollbar [overflow-anchor:none] ${FORUM_LIST_SPACING_CLASS}`}>
{!posts.length && loading ? <div data-message-list-content aria-hidden="true" inert data-read-position-ready="false" />
: !posts.length ? <div data-message-list-content aria-hidden="false" data-read-position-ready="true"><EmptyState icon={ListChevronsUpDown} label="No posts with this tag yet. Start one with New Post." /></div>
- : <VirtualRows directDomUpdatesMode="position" items={posts} virtualizer={virtualizer} renderItem={renderPost}
+ : <VirtualRows directDomUpdatesMode="position" items={posts} virtualizer={virtualizer}
+ renderItem={(post, index) => <ForumPostListItem first={index === 0} onActivate={onOpenPost ? () => onOpenPost(post.id) : undefined}>{renderPost(post, index)}</ForumPostListItem>}
containerAttributes={{ "data-message-list-content": "", "aria-hidden": !presentation.contentVisible, inert: !presentation.contentInteractive,
"data-read-position-ready": positionReady ? "true" : "false" }} />}
</div>
diff --git a/src/web/src/components/community/channels/forum-view.native-layout.dom.test.tsx b/src/web/src/components/community/channels/forum-view.native-layout.dom.test.tsx
index 4675c8972..eaf1a9868 100644
--- a/src/web/src/components/community/channels/forum-view.native-layout.dom.test.tsx
+++ b/src/web/src/components/community/channels/forum-view.native-layout.dom.test.tsx
@@ -78,6 +78,23 @@ it.each([{ kind: "short", name: "Short title" }, { kind: "long", name: "Long tit
expect(remove).not.toHaveBeenCalled()
})
+it("activates the highlighted item from prefix or separator and opens content only once", () => {
+ const open = vi.fn()
+ const cards = posts.slice(0, 3)
+ const view = render(createElement(ForumView, {
+ forumChannelId: "forum-item-activation", members: [], posts: cards, tag: "All",
+ onTagChange: () => {}, onOpenPost: open,
+ onScrollRoot: (root: HTMLDivElement | null) => {
+ if (root) mockElementGeometry(root, { clientHeight: 751, clientWidth: 390 })
+ },
+ }))
+ const items = view.getByTestId(tid.forumPostList).querySelectorAll('[data-slot="community-forum-list-item"]')
+ fireEvent.click(items[0])
+ fireEvent.click(items[1].querySelector('[data-slot="separator"]')!)
+ fireEvent.click(view.getByTestId(tid.forumThreadCard(cards[1].id)))
+ expect(open.mock.calls).toEqual([[cards[0].id], [cards[1].id], [cards[1].id]])
+})
+
it("reveals each card only after its own action decisions settle", () => {
const cards = posts.slice(0, 3)
const decisions = new Map<string, boolean | undefined>([[cards[0].id, true], [cards[1].id, undefined], [cards[2].id, undefined]])
@@ -93,6 +110,11 @@ it("reveals each card only after its own action decisions settle", () => {
},
})
const view = render(node())
+ const list = view.getByTestId(tid.forumPostList)
+ const items = Array.from(list.querySelectorAll('[data-slot="community-forum-list-item"]'))
+ expect(items.map(item => item.querySelectorAll('[data-slot="separator"]').length)).toEqual([0, 1, 1])
+ for (const separator of list.querySelectorAll('[data-slot="separator"]')) fireEvent.click(separator)
+ expect(open).not.toHaveBeenCalled()
const readyPeer = view.getByTestId(tid.forumThreadCard(cards[0].id))
for (const post of cards.slice(1)) {
const pending = view.getByTestId(tid.forumThreadCard(post.id))
@@ -268,7 +290,7 @@ it("keeps a new Forum instance at the start through hidden mounting and positive
Object.defineProperties(node, {
clientWidth: { configurable: true, get: () => visible ? 390 : 0 },
clientHeight: { configurable: true, get: () => visible ? 751 : 0 },
- scrollHeight: { configurable: true, get: () => visible ? Math.max(node.clientHeight, (Number.parseFloat((node.firstElementChild as HTMLElement)?.style.height ?? "0") || 0) + 16) : 0 },
+ scrollHeight: { configurable: true, get: () => visible ? Math.max(node.clientHeight, Number.parseFloat((node.firstElementChild as HTMLElement)?.style.height ?? "0") || 0) : 0 },
scrollTo: { configurable: true, value: ({ top = 0 }: ScrollToOptions) => {
node.scrollTop = Math.max(0, Math.min(top, node.scrollHeight - node.clientHeight))
writes.push(node.scrollTop)
@@ -319,3 +341,45 @@ it("keeps a new Forum instance at the start through hidden mounting and positive
expect(returned.root).not.toBe(first.root)
returned.view.unmount()
})
+
+it("retains fractional measured items across append and temporarily unmeasurable rows", () => {
+ rowHeight = index => index === 0 ? 98.6 : 106.2
+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {
+ return new DOMRect(0, Number.parseFloat(this.style.top) || 0, 390,
+ this.hasAttribute("data-index") ? rowHeight(Number(this.dataset.index)) : this.clientHeight)
+ })
+ const props = {
+ forumChannelId: "forum-fractional", members: [], posts: posts.slice(0, 20), tag: "All",
+ onTagChange: () => {}, onOpenPost: () => {},
+ onScrollRoot: (node: HTMLDivElement | null) => {
+ if (node) mockElementGeometry(node, { clientHeight: 500, clientWidth: 390, scrollHeight: 2100 })
+ },
+ }
+ const view = render(createElement(ForumView, props))
+ const root = view.getByTestId(tid.forumPostList)
+ const deliver = () => act(() => {
+ for (const [callback, nodes] of observers) {
+ const entries = [...nodes].filter(node => node.hasAttribute("data-index")).map<ResizeObserverEntry>(node => {
+ const size = rowHeight(Number((node as HTMLElement).dataset.index))
+ return { target: node, borderBoxSize: [{ blockSize: size, inlineSize: 390 }],
+ contentBoxSize: [{ blockSize: size, inlineSize: 390 }], devicePixelContentBoxSize: [],
+ contentRect: new DOMRect(0, 0, 390, size) }
+ })
+ if (entries.length) callback(entries, {} as ResizeObserver)
+ }
+ })
+ deliver()
+ const rows = Array.from(root.querySelectorAll<HTMLElement>("[data-index]"))
+ expect(rows.length).toBeGreaterThan(8)
+ for (const row of rows) {
+ const index = Number(row.dataset.index)
+ expect(Number.parseFloat(row.style.top)).toBeCloseTo(index === 0 ? 0 : 98.6 + (index - 1) * 106.2, 6)
+ }
+ const positions = rows.map(row => row.style.top)
+ view.rerender(createElement(ForumView, { ...props, posts: posts.slice(0, 21) }))
+ deliver()
+ expect(rows.map(row => row.style.top)).toEqual(positions)
+ rowHeight = () => 0
+ deliver()
+ expect(rows.map(row => row.style.top)).toEqual(positions)
+})
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 cf8153aa1..35b974a6b 100644
--- a/src/web/src/components/community/channels/forum-view.test.ts
+++ b/src/web/src/components/community/channels/forum-view.test.ts
@@ -162,15 +162,38 @@ describe("ForumView post card header", () => {
expect(html).toContain("-webkit-line-clamp:1")
})
- it("uses a flat hairline row instead of the old bordered card", () => {
+ it("keeps post padding separate from the independent divider", () => {
const html = render([makePost()])
const testIdIndex = html.indexOf(tid.forumThreadCard("p1"))
const rowMarkup = html.slice(Math.max(0, testIdIndex - 250), testIdIndex + 350)
- expect(rowMarkup).toContain("border-border/50")
+ expect(rowMarkup).toContain("px-4 py-0")
+ expect(rowMarkup).not.toContain("border-b")
expect(rowMarkup).not.toContain("bg-card")
expect(rowMarkup).not.toContain("rounded-lg border")
})
+ it.each([0, 1, 3])("renders only between-post separators for %i posts", count => {
+ const html = render(Array.from({ length: count }, (_, index) => makePost({ id: `p${index}` })))
+ const [actual, positioning] = html.split("data-forum-positioning-skeleton")
+ expect(actual.match(/data-slot="separator"/g) ?? []).toHaveLength(Math.max(0, count - 1))
+ expect(actual.match(/data-slot="community-forum-list-item"/g) ?? []).toHaveLength(count)
+ if (positioning) {
+ expect(positioning.match(/data-slot="separator"/g)).toHaveLength(2)
+ expect(positioning.match(/data-slot="community-forum-list-item"/g)).toHaveLength(3)
+ }
+ if (count > 0) expect(actual.match(/data-slot="community-forum-list-item" class="[^"]*pt-\[6\.6px\]/g)).toHaveLength(1)
+ if (count > 1) expect(html).toContain("my-[6.6px] bg-border/50")
+ })
+
+ it.each(["Alice", "VeryLongAuthorName".repeat(8), "很长的作者名称".repeat(12)])("preserves the full author name behind its single-line width limit: %s", authorName => {
+ const html = render([makePost({ parent: { authorName, text: "root" }, participants: [{ id: "usr_alice", name: authorName, avatar: "A" }] })])
+ const label = html.match(/<span data-slot="community-forum-post-author"[^>]*>([^<]*)<\/span>/)
+ expect(label?.[1]).toBe(authorName)
+ expect(label?.[0]).toContain('title="' + authorName + '"')
+ expect(label?.[0]).toContain("max-w-[min(12rem,40%)]")
+ expect(label?.[0]).toContain("truncate")
+ })
+
it("solo post renders the creator name and no participant AvatarGroup", () => {
const html = render([makePost()])
expect(html).toContain(">Alice<")
@@ -428,7 +451,7 @@ describe("ForumView filter bar / composer swap", () => {
expect(railMarkup).toContain('tabindex="0"')
expect(html).not.toContain(tid.forumTagFadeLeft)
expect(html).not.toContain(tid.forumTagFadeRight)
- expect(listMarkup).toContain("px-0")
+ expect(listMarkup).toContain("p-0")
expect(listMarkup).not.toContain("sm:px-4")
})
@@ -484,7 +507,8 @@ describe("ForumView filter bar / composer swap", () => {
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")
+ expect(html).toContain("p-0")
+ expect(html.match(/data-slot="separator"/g)).toHaveLength(2)
expect(html).not.toContain("sm:px-4")
expect(html.match(/min-h-8/g)).toHaveLength(3)
})
diff --git a/src/web/src/components/community/channels/forum-view.tsx b/src/web/src/components/community/channels/forum-view.tsx
index 5a2989304..ef8d350ae 100644
--- a/src/web/src/components/community/channels/forum-view.tsx
+++ b/src/web/src/components/community/channels/forum-view.tsx
@@ -20,7 +20,7 @@ import type { Member } from "@/lib/community/models/people"
import { tagColorClassName, tagColorStyle } from "@/lib/community/tag-color"
import { cn } from "@/lib/utils"
import { FORUM_ARCHIVE_TAG, getClientPlatform } from "@alook/shared"
-import { FORUM_LIST_SPACING_CLASS, ForumPostList } from "./forum-post-list"
+import { FORUM_LIST_SPACING_CLASS, ForumPostList, ForumPostListItem } from "./forum-post-list"
import { useHydratedClient } from "@/hooks/use-hydrated-client"
import type { ConversationListScope } from "@/lib/community/conversation-qualification"
import { useCanonicalProfilesByUserId } from "@/lib/community-db/projections"
@@ -34,7 +34,7 @@ import {
const MAX_AVATARS = 5
const MAX_VISIBLE_TAGS = 2
const POST_ACTION_CLASS = "grid size-8 shrink-0 place-items-center rounded-md text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50"
-const POST_ROW_CLASS = "border-b border-border/50 px-4 py-4"
+const POST_ROW_CLASS = "px-4 py-0"
export function shouldActivateForumRow(event: {
key: string
@@ -294,11 +294,11 @@ export function ForumView({
key={JSON.stringify([forumChannelId, tag])}
posts={posts} loading={loading} observation={observation} positionScope={positionScope}
hasMore={hasMore} loadingMore={loadingMore} isFetching={isFetching} isError={isError}
- onLoadMore={onLoadMore} onScrollRoot={onScrollRoot} loadingContent={<ForumListSkeleton />}
- renderPost={(p, index) => {
+ onLoadMore={onLoadMore} onScrollRoot={onScrollRoot} onOpenPost={onOpenPost} loadingContent={<ForumListSkeleton />}
+ renderPost={(p) => {
const canEdit = onEditPostTags && canEditPostTags ? canEditPostTags(p) : false
const canDelete = onDeletePost && canDeletePost ? canDeletePost(p) : false
- if (canEdit === undefined || canDelete === undefined) return <ForumPostSkeleton key={p.id} postId={p.id} last={index === posts.length - 1} />
+ if (canEdit === undefined || canDelete === undefined) return <ForumPostSkeleton key={p.id} postId={p.id} />
const archived = p.tags.includes(FORUM_ARCHIVE_TAG)
const hasOrdinaryTags = p.tags.some((postTag) => postTag !== FORUM_ARCHIVE_TAG)
const savingTags = savingTagsFor === p.id
@@ -326,9 +326,8 @@ export function ForumView({
onOpenPost(p.id)
}}
className={cn(
- "group/card relative cursor-pointer rounded text-left transition-colors hover:bg-accent/45",
+ "relative cursor-pointer rounded text-left",
POST_ROW_CLASS,
- index === posts.length - 1 && "border-b-0",
)}
>
<div className={cn("grid grid-rows-[minmax(2rem,max-content)_auto] gap-x-2", actionCount > 0 ? "grid-cols-[minmax(0,1fr)_auto]" : "grid-cols-1")}>
@@ -394,11 +393,11 @@ export function ForumView({
</div>
)}
- <p data-slot="community-forum-post-preview" className="col-span-full row-start-2 my-2 line-clamp-2 text-[13.5px] text-muted-foreground">{p.preview}</p>
+ <p data-slot="community-forum-post-preview" className="col-span-full row-start-2 mb-2 line-clamp-2 text-[13.5px] text-muted-foreground">{p.preview}</p>
</div>
<div className="flex min-w-0 flex-wrap items-center gap-2 text-xs text-muted-foreground">
<Avatar label={author.avatar} seed={p.authorId} size={20} />
- <span className="shrink-0 font-medium text-foreground" suppressHydrationWarning>{author.name}</span>
+ <span data-slot="community-forum-post-author" title={author.name} className="min-w-0 max-w-[min(12rem,40%)] shrink-0 truncate font-medium text-foreground" suppressHydrationWarning>{author.name}</span>
<span className="shrink-0" aria-hidden>·</span>
<span className="shrink-0" suppressHydrationWarning>Active {formatRelativeTime(p.lastMessageAt)}</span>
{hasOrdinaryTags && <span className="shrink-0 max-sm:hidden" aria-hidden>·</span>}
@@ -444,17 +443,17 @@ export function ForumView({
// Loading placeholder for the forum post list. It mirrors the flat rows so the
// page does not flash back to the old card treatment while data is loading.
-function ForumPostSkeleton({ postId, last = false }: { postId?: string; last?: boolean }) {
+function ForumPostSkeleton({ postId }: { postId?: string }) {
return (
<div
data-slot="community-forum-post-skeleton"
data-testid={postId === undefined ? undefined : tid.forumThreadCard(postId)}
aria-busy="true"
aria-label="Loading post"
- className={cn("flex flex-col", POST_ROW_CLASS, last && "border-b-0")}
+ className={cn("flex flex-col", POST_ROW_CLASS)}
>
<div className="flex min-h-8 items-center"><Skeleton className="h-4 w-2/3 rounded" /></div>
- <div className="my-2 space-y-2">
+ <div className="mb-2 space-y-2">
<Skeleton className="h-3 w-full rounded" />
<Skeleton className="h-3 w-4/5 rounded" />
</div>
@@ -470,7 +469,7 @@ function ForumPostSkeleton({ postId, last = false }: { postId?: string; last?: b
function ForumListSkeleton() {
return (
<div className="flex flex-col">
- {Array.from({ length: 3 }).map((_, i) => <ForumPostSkeleton key={i} last={i === 2} />)}
+ {Array.from({ length: 3 }).map((_, i) => <ForumPostListItem key={i} first={i === 0}><ForumPostSkeleton /></ForumPostListItem>)}
</div>
)
}
diff --git a/src/web/src/test/e2e-ui/26-mobile-forum-post-actions.spec.ts b/src/web/src/test/e2e-ui/26-mobile-forum-post-actions.spec.ts
index 74580de3b..0d92a7d46 100644
--- a/src/web/src/test/e2e-ui/26-mobile-forum-post-actions.spec.ts
+++ b/src/web/src/test/e2e-ui/26-mobile-forum-post-actions.spec.ts
@@ -70,7 +70,8 @@ async function rect(locator: Locator): Promise<Rect | null> {
}
async function postActionGeometry(card: Locator, postId: string) {
- return card.evaluate((element, titleId) => {
+ const spacing = await expectForumPostSpacing(card, postId)
+ const geometry = await card.evaluate((element, titleId) => {
const readRect = (target: Element | null) => {
if (!target) throw new Error("Missing Forum geometry target")
const box = target.getBoundingClientRect()
@@ -85,6 +86,135 @@ async function postActionGeometry(card: Locator, postId: string) {
virtualHeight: readRect(row?.parentElement ?? null).height,
}
}, tid.forumThreadTitle(postId))
+ return { ...geometry, spacing }
+}
+
+async function expectContinuousForumHover(page: Page, card: Locator, actions: Locator, testInfo: TestInfo, width: number) {
+ const item = card.locator("..")
+ await expect(item).toHaveAttribute("data-slot", "community-forum-list-item")
+ const settle = () => item.evaluate(async element => {
+ await Promise.all(element.getAnimations().map(animation => animation.finished))
+ })
+ await settle()
+ const background = await item.evaluate(element => getComputedStyle(element).backgroundColor)
+ expect(background).not.toBe("rgba(0, 0, 0, 0)")
+ const points = await item.evaluate(element => {
+ const bounds = element.getBoundingClientRect()
+ const post = element.querySelector('[data-page-swipe-navigation-row]')!.getBoundingClientRect()
+ const line = element.querySelector(':scope > [data-slot="separator"]')?.getBoundingClientRect()
+ const x = bounds.left + bounds.width / 2
+ return line ? [
+ { label: "above-separator", x, y: (bounds.top + line.top) / 2 },
+ { label: "separator", x, y: (line.top + line.bottom) / 2 },
+ { label: "below-separator", x, y: (line.bottom + post.top) / 2 },
+ ] : [{ label: "first-prefix", x, y: (bounds.top + post.top) / 2 }]
+ })
+ const samples: Array<{ label: string; x: number; y: number; background: string }> = []
+ for (const point of points) {
+ await page.mouse.move(point.x, point.y)
+ await settle()
+ await expect(actions).toHaveCSS("opacity", "1")
+ await expect(item).toHaveCSS("background-color", background)
+ samples.push({ ...point, background: await item.evaluate(element => getComputedStyle(element).backgroundColor) })
+ }
+ await testInfo.attach(`continuous-forum-hover-${width}.json`, {
+ body: JSON.stringify({ width, background, samples }), contentType: "application/json",
+ })
+ await card.hover()
+}
+
+async function expectForumPostSpacing(card: Locator, postId: string) {
+ await expect(card).toHaveCSS("padding-top", "0px")
+ await expect(card).toHaveCSS("padding-bottom", "0px")
+ const geometry = await card.evaluate((element, ids) => {
+ const item = element.closest('[data-slot="community-forum-list-item"]')!
+ const virtual = item.closest<HTMLElement>("[data-index]")!
+ const index = Number(virtual.dataset.index)
+ const separator = item.querySelector(':scope > [data-slot="separator"]')
+ const preview = element.querySelector('[data-slot="community-forum-post-preview"]')!
+ const title = element.querySelector(`[data-testid="${ids.title}"]`)!
+ const titleGrid = title.parentElement!
+ const titleGridStyle = getComputedStyle(titleGrid)
+ const firstRowHeight = Number.parseFloat(titleGridStyle.gridTemplateRows)
+ const firstRowTop = titleGrid.getBoundingClientRect().top
+ + Number.parseFloat(titleGridStyle.borderTopWidth) + Number.parseFloat(titleGridStyle.paddingTop)
+ const firstRowBottom = firstRowTop + firstRowHeight
+ const metadata = element.lastElementChild!
+ const author = metadata.querySelector('[data-slot="community-forum-post-author"]')!
+ const authorStyle = getComputedStyle(author)
+ const authorBox = author.getBoundingClientRect()
+ const titleBox = title.getBoundingClientRect()
+ const previewBox = preview.getBoundingClientRect()
+ const previous = virtual.parentElement?.querySelector(`[data-index="${index - 1}"] [data-page-swipe-navigation-row]`)
+ const box = element.getBoundingClientRect()
+ const line = separator?.getBoundingClientRect()
+ const style = getComputedStyle(element)
+ const listStyle = getComputedStyle(element.closest(`[data-testid="${ids.list}"]`)!)
+ const lineStyle = separator && getComputedStyle(separator)
+ return {
+ index,
+ listPadding: [listStyle.paddingTop, listStyle.paddingRight, listStyle.paddingBottom, listStyle.paddingLeft],
+ postPadding: [style.paddingTop, style.paddingRight, style.paddingBottom, style.paddingLeft],
+ postBorder: style.borderBottomWidth,
+ firstRowHeight,
+ firstItemTopGap: box.top - item.getBoundingClientRect().top,
+ firstRowToPreview: previewBox.top - firstRowBottom,
+ previewToMetadata: metadata.getBoundingClientRect().top - previewBox.bottom,
+ layout: {
+ firstRow: { top: firstRowTop, bottom: firstRowBottom, height: firstRowHeight },
+ title: { top: titleBox.top, bottom: titleBox.bottom, height: titleBox.height, lineHeight: getComputedStyle(title).lineHeight },
+ preview: { top: previewBox.top, bottom: previewBox.bottom, height: previewBox.height, lineHeight: getComputedStyle(preview).lineHeight },
+ },
+ author: {
+ width: authorBox.width, height: authorBox.height,
+ cap: Math.min(Number.parseFloat(getComputedStyle(document.documentElement).fontSize) * 12, metadata.getBoundingClientRect().width * 0.4),
+ whiteSpace: authorStyle.whiteSpace, overflow: authorStyle.overflow, textOverflow: authorStyle.textOverflow,
+ lineHeight: Number.parseFloat(authorStyle.lineHeight), text: author.textContent, title: author.getAttribute("title"),
+ },
+ itemHeight: item.getBoundingClientRect().height,
+ virtualHeight: virtual.getBoundingClientRect().height,
+ endsWithPost: item.lastElementChild === element,
+ separator: line && lineStyle ? {
+ height: line.height, leftDifference: line.left - box.left, rightDifference: line.right - box.right,
+ marginTop: Number.parseFloat(lineStyle.marginTop), marginBottom: Number.parseFloat(lineStyle.marginBottom),
+ afterGap: box.top - line.bottom,
+ previousGap: previous ? line.top - previous.getBoundingClientRect().bottom : null,
+ sameColorToken: separator!.classList.contains("bg-border/50"),
+ outsidePost: !element.contains(separator),
+ } : null,
+ }
+ }, { title: tid.forumThreadTitle(postId), list: tid.forumPostList })
+ expect(geometry.listPadding).toEqual(["0px", "0px", "0px", "0px"])
+ expect(geometry.postPadding).toEqual(["0px", "16px", "0px", "16px"])
+ expect(geometry.postBorder).toBe("0px")
+ expect(geometry.firstRowHeight).toBeGreaterThanOrEqual(32)
+ expect(geometry.firstRowToPreview).toBeCloseTo(0, 1)
+ expect(geometry.previewToMetadata).toBeCloseTo(8, 1)
+ expect(geometry.virtualHeight).toBeCloseTo(geometry.itemHeight, 1)
+ expect(geometry.endsWithPost).toBe(true)
+ expect(geometry.author.width).toBeLessThanOrEqual(geometry.author.cap + 0.05)
+ expect(geometry.author.whiteSpace).toBe("nowrap")
+ expect(geometry.author.overflow).toBe("hidden")
+ expect(geometry.author.textOverflow).toBe("ellipsis")
+ expect(geometry.author.height).toBeLessThanOrEqual(geometry.author.lineHeight + 0.05)
+ expect(geometry.author.title).toBe(geometry.author.text)
+ if (geometry.index === 0) {
+ expect(geometry.separator).toBeNull()
+ expect(geometry.firstItemTopGap).toBeCloseTo(6.6, 1)
+ } else {
+ expect(geometry.separator).not.toBeNull()
+ const line = geometry.separator!
+ expect(line.height).toBe(1)
+ expect(line.leftDifference).toBeCloseTo(0, 1)
+ expect(line.rightDifference).toBeCloseTo(0, 1)
+ expect(line.marginTop).toBeCloseTo(6.6, 1)
+ expect(line.marginBottom).toBeCloseTo(6.6, 1)
+ expect(line.afterGap).toBeCloseTo(6.6, 1)
+ if (line.previousGap !== null) expect(line.previousGap).toBeCloseTo(6.6, 1)
+ expect(line.sameColorToken).toBe(true)
+ expect(line.outsidePost).toBe(true)
+ }
+ return geometry
}
async function expectNewPostGeometry(
@@ -307,6 +437,10 @@ async function expectNarrowGeometry(
scroll: document.documentElement.scrollWidth,
}))
expect(documentWidth.scroll, `${role}@${width}: horizontal overflow`).toBe(documentWidth.client)
+ const spacing = await expectForumPostSpacing(card, postId)
+ await test.info().attach(`forum-spacing-${role}-${postId}-${width}.json`, {
+ body: JSON.stringify({ role, width, spacing }), contentType: "application/json",
+ })
}
async function expectFilterRail(
@@ -714,6 +848,7 @@ test("forum post actions stay discoverable on mobile without changing permission
expect(Math.abs(baseline.card.right - actionsRect!.right - 16), `desktop internal action inset@${width}`).toBeLessThanOrEqual(0.5)
await managerCard.hover()
await expect(managerActions).toHaveCSS("opacity", "1")
+ await expectContinuousForumHover(manager.page, managerCard, managerActions, testInfo, width)
const hover = await postActionGeometry(managerCard, primaryPostId)
expect(hover, `hover geometry@${width}`).toEqual(baseline)
await manager.page.mouse.move(0, 0)
@@ -826,6 +961,14 @@ test("forum post actions stay discoverable on mobile without changing permission
contentType: "image/png",
})
+ const unauthorizedSeparator = unauthorizedCard.locator("..").locator(':scope > [data-slot="separator"]')
+ await expect(unauthorizedSeparator).toHaveCount(1)
+ await unauthorizedSeparator.click()
+ await expect(unauthorized.page).toHaveURL(new RegExp(`/channels/${serverId}/${primaryPostId}$`))
+ await unauthorized.page.goBack()
+ await expect(unauthorized.page).toHaveURL(new RegExp(`${route}$`))
+ await expect(unauthorizedCard).toBeVisible()
+
await authorCard.click()
await expect(author.page).toHaveURL(new RegExp(`/channels/${serverId}/${primaryPostId}$`))
await managerCard.focus()