Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): preserve full forum previews and post numbers (#975)

Generb0cab4b04260
diff --git a/src/web/src/components/community/channels/forum-view.scroll.dom.test.ts b/src/web/src/components/community/channels/forum-view.scroll.dom.test.ts
index 081d5144f..9b9f49cfc 100644
--- a/src/web/src/components/community/channels/forum-view.scroll.dom.test.ts
+++ b/src/web/src/components/community/channels/forum-view.scroll.dom.test.ts
@@ -1,7 +1,8 @@
import { createElement } from "react"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
-import { act, render } from "@/test/react-dom-harness"
+import { act, fireEvent, render } from "@/test/react-dom-harness"
import type { ForumThread } from "@/lib/community/models/message"
+import { tid } from "@/lib/community/testids"
const scrollToIndex = vi.fn()
let requestOlder: (() => void) | undefined
@@ -106,4 +107,34 @@ describe("ForumView scroll anchoring", () => {
view.rerender(createElement(ForumView, { ...props([post("p3"), post("p2"), post("p1")]), onLoadMore }))
expect(root.scrollTop).toBe(20)
})
+
+ it("updates the full title and sequence without a measured duplicate and keeps row activation", () => {
+ const onOpenPost = vi.fn()
+ const initial: ForumThread = { ...post("p1"), name: "Short title", parentSeq: 205 }
+ const view = render(createElement(ForumView, { ...props([initial]), onOpenPost }))
+ const heading = view.getByTestId(tid.forumThreadTitle("p1"))
+ const title = view.getByTestId(tid.forumThreadTitleText("p1"))
+ const sequence = view.getByTestId(tid.forumThreadSeq("p1"))
+ expect(heading.textContent).toBe("Short title#205")
+ expect(heading.getAttribute("aria-label")).toBe("Short title #205")
+ expect(title.contains(sequence)).toBe(false)
+
+ const name = "移动端论坛标题需要独立截断".repeat(8)
+ view.rerender(createElement(ForumView, {
+ ...props([{ ...initial, name, parentSeq: 987654321012345 }]), onOpenPost,
+ }))
+ expect(title.textContent).toBe(name)
+ expect(sequence.textContent).toBe("#987654321012345")
+ expect(heading.textContent).toBe(`${name}#987654321012345`)
+ expect(heading.getAttribute("aria-label")).toBe(`${name} #987654321012345`)
+ expect(heading.getAttribute("title")).toBe(name)
+ fireEvent.click(title)
+ fireEvent.keyDown(view.getByTestId(tid.forumThreadCard("p1")), { key: "Enter" })
+ expect(onOpenPost.mock.calls).toEqual([["p1"], ["p1"]])
+
+ view.rerender(createElement(ForumView, { ...props([{ ...initial, name, parentSeq: undefined }]), onOpenPost }))
+ expect(view.queryByTestId(tid.forumThreadSeq("p1"))).toBeNull()
+ expect(heading.textContent).toBe(name)
+ expect(heading.getAttribute("aria-label")).toBe(name)
+ })
})
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 4b94ffa19..5de599452 100644
--- a/src/web/src/components/community/channels/forum-view.test.ts
+++ b/src/web/src/components/community/channels/forum-view.test.ts
@@ -133,9 +133,13 @@ describe("ForumView post card header", () => {
})
it("renders the title and opener seq before the creator metadata", () => {
- const html = render([makePost({ parentSeq: 42 })])
+ const preview = "Complete forum preview ".repeat(12)
+ const html = render([makePost({ parentSeq: 42, preview })])
expect(html.indexOf("A post title")).toBeLessThan(html.indexOf(">Alice<"))
expect(html).toContain('<span class="opacity-60">#</span>42')
+ const paragraph = html.match(/<p[^>]*class="([^"]+)"[^>]*>([^<]*)<\/p>/)
+ expect(paragraph?.[1]?.split(" ")).toContain("line-clamp-2")
+ expect(paragraph?.[2]).toBe(preview)
})
it("uses a flat hairline row instead of the old bordered card", () => {
@@ -283,7 +287,7 @@ describe("ForumView responsive post actions", () => {
expect(archiveButton).toContain("disabled:opacity-50")
expect(deleteButton).toContain("disabled:opacity-50")
expect(html).toContain("min-h-8 pr-28 sm:min-h-0 sm:pr-22")
- expect(html).toContain("relative line-clamp-2 w-full min-w-0 max-w-full wrap-break-word")
+ expect(html).toContain("flex w-full min-w-0 max-w-full items-end gap-1.5")
expect(html).toContain(tid.forumThreadTitle("p1"))
expect(html).toContain(tid.forumThreadTitleText("p1"))
expect(html).toContain(tid.forumThreadSeq("p1"))
diff --git a/src/web/src/components/community/channels/forum-view.tsx b/src/web/src/components/community/channels/forum-view.tsx
index c589f913d..94d9c27c7 100644
--- a/src/web/src/components/community/channels/forum-view.tsx
+++ b/src/web/src/components/community/channels/forum-view.tsx
@@ -98,84 +98,27 @@ export function toggleForumArchivedStatus(tags: string[]): string[] {
}
function ForumPostTitle({ name, postId, seq }: { name: string; postId: string; seq?: number }) {
- const hostRef = useRef<HTMLHeadingElement>(null)
- const measureRef = useRef<HTMLSpanElement>(null)
- const measureNameRef = useRef<HTMLSpanElement>(null)
-const [rendered, setRendered] = useAtom(useCreateAtom({ name, truncated: false }))
-
- useLayoutEffect(() => {
- const host = hostRef.current
- const measure = measureRef.current
- const measureName = measureNameRef.current
- if (!host || !measure || !measureName) return
-
- const characters = Array.from(name)
- const commit = (nextName: string, truncated: boolean) => {
- setRendered((current) => current.name === nextName && current.truncated === truncated
- ? current
- : { name: nextName, truncated })
- }
- const recompute = () => {
- if (host.clientWidth === 0) return
- const view = measure.ownerDocument?.defaultView
- if (!view) return
- const lineHeight = Number.parseFloat(view.getComputedStyle(measure).lineHeight)
- if (!Number.isFinite(lineHeight)) return
- const fits = (count: number, truncated: boolean) => {
- measureName.textContent = `${characters.slice(0, count).join("")}${truncated ? "…" : ""}`
- return measure.getBoundingClientRect().height <= lineHeight * 2 + 0.5
- }
-
- if (fits(characters.length, false)) {
- commit(name, false)
- return
- }
-
- let low = 0
- let high = characters.length
- while (low < high) {
- const midpoint = Math.ceil((low + high) / 2)
- if (fits(midpoint, true)) low = midpoint
- else high = midpoint - 1
- }
- commit(characters.slice(0, low).join(""), true)
- }
-
- recompute()
- if (typeof ResizeObserver === "undefined") return
- const observer = new ResizeObserver(recompute)
- observer.observe(host)
- return () => observer.disconnect()
- }, [name, seq, setRendered])
-
- const renderSequence = (measurement = false) => seq === undefined ? null : (
- <span
- data-testid={measurement ? undefined : tid.forumThreadSeq(postId)}
- className="ml-1.5 whitespace-nowrap font-mono text-[13px] font-medium text-muted-foreground"
- >
- <span className="opacity-60">#</span>{seq}
- </span>
- )
-
return (
<h3
- ref={hostRef}
data-testid={tid.forumThreadTitle(postId)}
- data-truncated={rendered.truncated ? "true" : "false"}
- aria-label={rendered.truncated ? `${name}${seq === undefined ? "" : ` #${seq}`}` : undefined}
- title={rendered.truncated ? name : undefined}
- className="relative line-clamp-2 w-full min-w-0 max-w-full wrap-break-word text-[15px] font-semibold leading-tight"
+ aria-label={`${name}${seq === undefined ? "" : ` #${seq}`}`}
+ title={name}
+ className="flex w-full min-w-0 max-w-full items-end gap-1.5 text-[15px] font-semibold leading-tight"
>
- <span data-testid={tid.forumThreadTitleText(postId)}>{rendered.name}{rendered.truncated ? "…" : ""}</span>
- {renderSequence()}
<span
- ref={measureRef}
- aria-hidden
- className="invisible absolute left-0 top-0 block w-full whitespace-normal wrap-break-word text-[15px] font-semibold leading-tight"
+ data-testid={tid.forumThreadTitleText(postId)}
+ className="line-clamp-2 min-w-0 wrap-break-word"
>
- <span ref={measureNameRef}>{name}</span>
- {renderSequence(true)}
+ {name}
</span>
+ {seq !== undefined && (
+ <span
+ data-testid={tid.forumThreadSeq(postId)}
+ className="shrink-0 whitespace-nowrap font-mono text-[13px] font-medium text-muted-foreground"
+ >
+ <span className="opacity-60">#</span>{seq}
+ </span>
+ )}
</h3>
)
}
diff --git a/src/web/src/hooks/community/forum-feed-window.ts b/src/web/src/hooks/community/forum-feed-window.ts
index 95c1c9036..1bd5a3ff3 100644
--- a/src/web/src/hooks/community/forum-feed-window.ts
+++ b/src/web/src/hooks/community/forum-feed-window.ts
@@ -35,7 +35,7 @@ export type ForumFeedTransportPage = Pick<CommunityThreadsRead["page"], "hasMore
export type CommunityThreadResources = {
channel: Pick<CommunityChannelResource, "id" | "serverId" | "type">
threads: Array<Pick<CommunityChannelResource, "id"> & Partial<Omit<CommunityChannelResource, "id">> & { resourceComplete?: boolean }>
- included: Omit<CommunityThreadsRead["included"], "messages" | "profiles"> & { profiles: Array<Pick<CommunityResourceProfile, "id"> & Partial<Omit<CommunityResourceProfile, "id">>>; messages: Array<MessageInput & { channelId: string }>; previews: Array<Pick<CommunityMessageResource, "channelId" | "content">> }
+ included: Omit<CommunityThreadsRead["included"], "messages" | "profiles"> & { profiles: Array<Pick<CommunityResourceProfile, "id"> & Partial<Omit<CommunityResourceProfile, "id">>>; messages: Array<MessageInput & { channelId: string }>; previews: Array<Pick<CommunityMessageResource, "channelId" | "content"> & Partial<Pick<CommunityMessageResource, "id">>> }
page: CommunityThreadsRead["page"]
}
diff --git a/src/web/src/hooks/community/forum-preview-live-edit.dom.test.ts b/src/web/src/hooks/community/forum-preview-live-edit.dom.test.ts
new file mode 100644
index 000000000..e03011294
--- /dev/null
+++ b/src/web/src/hooks/community/forum-preview-live-edit.dom.test.ts
@@ -0,0 +1,136 @@
+import { createElement, type PropsWithChildren } from "react"
+import { describe, expect, it, vi } from "vitest"
+import { act, renderHook, waitFor } from "@/test/react-dom-harness"
+import { CommunityTestProvider } from "@/test/community-owner-fixture"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { dispatchCommunityWsEvent } from "./community-ws/registry"
+import { captureCommunityLiveSnapshotToken, publishCommunityForumFeed, publishCommunityMessages } from "@/lib/community-db/sync"
+import { normalizeThreadResources } from "./forum-feed-window"
+
+const apiFetch = vi.hoisted(() => vi.fn())
+vi.mock("@/lib/api/client", () => ({ apiFetch }))
+vi.mock("./use-channel-panels", () => ({
+ useForumTags: () => ({ data: { tags: [] }, isSuccess: true }),
+}))
+import { useForumFeed } from "./use-forum-feed"
+
+const original = "original first body ".repeat(34)
+const edited = "edited first body with complete content ".repeat(29)
+const date = "2026-10-01T00:00:00.000Z"
+
+function channel(id: string, type: "forum" | "thread", parentMessageId: string | null = null) {
+ return { id, type, serverId: "server", categoryId: null, name: id, topic: "",
+ parentChannelId: type === "thread" ? "forum" : null, parentMessageId, creatorId: "author",
+ position: 0, archived: false, createdAt: date, lastMessageAt: date, messageCount: 2 }
+}
+function message(id: string, channelId: string, seq: number, content: string) {
+ return { id, channelId, seq, content, authorId: "author", authorName: "Ada",
+ authorAvatar: "A", authorAvatarVersion: 0, createdAt: date, type: "chat" as const,
+ replyToId: null, clientNonce: null, attachments: [] }
+}
+function page(contractVersion: 2 | 3, firstSeq = 1) {
+ return { contractVersion, channelId: "forum", channel: channel("forum", "forum"),
+ threads: [channel("post", "thread", "title"), channel("other", "thread", "other-title")],
+ included: { messages: [
+ message("title", "forum", 104, "Original title"),
+ message("first", "post", firstSeq, original),
+ message("other-title", "forum", 105, "Other title"),
+ message("other-first", "other", 1, "Other original"),
+ ], members: [], profiles: [], tags: [], participantCounts: [] },
+ page: { hasMore: false, nextCursor: null } }
+}
+async function mount(contractVersion: 2 | 3 = 2, firstSeq = 1) {
+ const owner = await createCommunityQueryOwner()
+ apiFetch.mockReset()
+ apiFetch.mockResolvedValue(page(contractVersion, firstSeq))
+ function Wrapper({ children }: PropsWithChildren) {
+ return createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry }, children)
+ }
+ const view = renderHook(() => useForumFeed("server", "forum"), { wrapper: Wrapper })
+ await waitFor(() => expect(view.result.current.posts.find((post) => post.id === "post")?.preview).toBe(original))
+ const context = { contract: contractVersion, deliveryMode: "single" as const,
+ queryClient: owner.client, communityStore: owner.runtime.ui, wsStore: owner.runtime.ws,
+ sub: { channelId: "forum" }, viewerUserIdRef: { current: "viewer" },
+ matchesFocus: () => false, scheduleInboxInvalidate: vi.fn() }
+ function edit(channelId: string, messageId: string, content: string, title = false) {
+ act(() => dispatchCommunityWsEvent({ type: "community:message.edited", serverId: "server",
+ channelId, messageId, content, ...(title ? { parentChannelId: "forum" } : {}) }, context))
+ }
+ return { ...owner, ...view, edit, preview: (id = "post") => view.result.current.posts.find((post) => post.id === id)?.preview }
+}
+
+describe("Forum first body through the actual edited dispatcher", () => {
+ it.each([{ contract: 2 as const, firstSeq: 1 }, { contract: 3 as const, firstSeq: 7 }])(
+ "updates the existing full preview from contract$contract first-body identity, not a sequence guess",
+ async ({ contract, firstSeq }) => {
+ const view = await mount(contract, firstSeq)
+ view.edit("post", "first", edited)
+ expect(view.registry.collections.messages.get("first")?.content).toBe(edited)
+ await waitFor(() => expect(view.preview()).toBe(edited))
+ expect(view.result.current.posts.find((post) => post.id === "post")?.parent.text).toBe(edited)
+ expect(view.registry.collections.messages.get("first")?.content).toBe(edited)
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+ },
+ )
+
+ it("keeps later reply and title edits out of the first-body preview", async () => {
+ const view = await mount()
+ act(() => publishCommunityMessages(view.client, { channelId: "post",
+ messages: [message("later-reply", "post", 2, "Original later reply")],
+ proof: { token: captureCommunityLiveSnapshotToken(view.client, "post"), signal: undefined } }))
+ view.edit("post", "later-reply", "later reply edit")
+ expect(view.registry.collections.messages.get("later-reply")?.content).toBe("later reply edit")
+ view.edit("post", "title", "New title", true)
+ await waitFor(() => expect(view.result.current.posts.find((post) => post.id === "post")?.name).toBe("New title"))
+ expect(view.preview()).toBe(original)
+ expect(view.preview("other")).toBe("Other original")
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+ })
+
+ it("updates another post only through that post's known first body", async () => {
+ const view = await mount()
+ view.edit("other", "other-first", edited)
+ expect(view.registry.collections.messages.get("other-first")?.content).toBe(edited)
+ await waitFor(() => expect(view.preview("other")).toBe(edited))
+ expect(view.preview()).toBe(original)
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+ })
+
+ it("retains an edited preview over the original older HTTP feed", async () => {
+ const view = await mount()
+ const token = captureCommunityLiveSnapshotToken(view.client, "forum")
+ view.edit("post", "first", edited)
+ expect(view.registry.collections.messages.get("first")?.content).toBe(edited)
+ act(() => publishCommunityForumFeed(view.client, "forum",
+ normalizeThreadResources("forum", page(2)), { token, signal: undefined }))
+ await waitFor(() => expect(view.preview()).toBe(edited))
+ expect(view.registry.collections.messages.get("first")?.content).toBe(edited)
+ })
+
+ it("rejects an old account response before it can rewrite preview ownership", async () => {
+ const view = await mount()
+ view.runtime.ws.actions.activateProfileAccount("old-account")
+ const token = captureCommunityLiveSnapshotToken(view.client, "forum")
+ view.runtime.ws.actions.activateProfileAccount("new-account")
+ expect(() => publishCommunityForumFeed(view.client, "forum",
+ normalizeThreadResources("forum", page(2)), { token, signal: undefined }))
+ .toThrow(expect.objectContaining({ name: "AbortError" }))
+ expect(view.preview()).toBe(original)
+ })
+
+ it("does not invent first-body identity from an unaddressed legacy preview", async () => {
+ const view = await mount()
+ act(() => publishCommunityForumFeed(view.client, "forum", normalizeThreadResources("forum", {
+ serverId: "server", parentType: "forum", threads: [
+ { id: "post", name: "Original title", creatorId: "author", parentMessageId: "title",
+ messageCount: 2, createdAt: date, lastMessageAt: date, activityAt: date },
+ ], included: { parentMessages: [{ ...message("title", "forum", 104, "Original title"), authorImage: null }],
+ firstMessages: [{ channelId: "post", content: original }], tags: [], participants: [] },
+ hasMore: false,
+ }), { token: captureCommunityLiveSnapshotToken(view.client, "forum"), signal: undefined }))
+ view.edit("post", "first", edited)
+ expect(view.registry.collections.messages.get("first")?.content).toBe(edited)
+ expect(view.preview()).toBe(original)
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/src/web/src/hooks/community/use-channel-panels.test.ts b/src/web/src/hooks/community/use-channel-panels.test.ts
index 3da87e323..482075849 100644
--- a/src/web/src/hooks/community/use-channel-panels.test.ts
+++ b/src/web/src/hooks/community/use-channel-panels.test.ts
@@ -146,7 +146,7 @@ describe("usePins / pinsQueryFn", () => {
})
describe("materializeThreadsResponse", () => {
- it("retains panel preview limits, created-time fallback and optional opener fields", () => {
+ it("retains full forum previews, text-panel limits, created-time fallback and optional opener fields", () => {
const preview = "preview".repeat(30), content = "content".repeat(30)
const base = { type: "thread", position: 0, archived: false, muted: false, unread: false, pending: false, tags: [] }
const channels = new Map([
@@ -158,8 +158,8 @@ describe("materializeThreadsResponse", () => {
const messages = new Map([["opener", { id: "opener", type: "chat" as const, content: " ", authorId: "u1", authorName: "A", seq: 0 }]])
const forum = materializeThreadsResponse(data, messages, channels)
expect(forum).toHaveLength(2)
- expect(forum[0]).toEqual({ id: "post", name: "Fallback", messageCount: 0, lastMessageAt: "created", parent: { authorId: "u1", authorName: "A", text: preview.slice(0, 100) }, parentSeq: 0, openerMessageId: "opener" })
- expect(forum[1]).toMatchObject({ name: "Post", lastMessageAt: "created", parent: { authorName: "", text: preview.slice(0, 100) } })
+ expect(forum[0]).toEqual({ id: "post", name: "Fallback", messageCount: 0, lastMessageAt: "created", parent: { authorId: "u1", authorName: "A", text: preview }, parentSeq: 0, openerMessageId: "opener" })
+ expect(forum[1]).toMatchObject({ name: "Post", lastMessageAt: "created", parent: { authorName: "", text: preview } })
expect(forum[1]).not.toHaveProperty("parentSeq")
expect(forum[1]).not.toHaveProperty("openerMessageId")
messages.set("opener", { ...messages.get("opener")!, content })
diff --git a/src/web/src/hooks/community/use-channel-panels.ts b/src/web/src/hooks/community/use-channel-panels.ts
index ebb7963e8..f453757ec 100644
--- a/src/web/src/hooks/community/use-channel-panels.ts
+++ b/src/web/src/hooks/community/use-channel-panels.ts
@@ -73,7 +73,7 @@ export function materializeThreadsResponse(data: ThreadsResponse | undefined, me
const thread = channels.get(window.id), opener = window.openerMessageId ? messages?.get(window.openerMessageId) : undefined
if (!thread || (window.openerMessageId && !opener) || thread.archived) return []
const core = projectThread(thread, opener, data.parentType)
- return [{ ...core, lastMessageAt: thread.lastMessageAt ?? thread.createdAt ?? "", parent: { ...core.parent, text: core.parent.text.slice(0, 100) }, ...(window.openerMessageId ? { openerMessageId: window.openerMessageId } : {}) }]
+ return [{ ...core, lastMessageAt: thread.lastMessageAt ?? thread.createdAt ?? "", parent: data.parentType === "forum" ? core.parent : { ...core.parent, text: core.parent.text.slice(0, 100) }, ...(window.openerMessageId ? { openerMessageId: window.openerMessageId } : {}) }]
})
}
diff --git a/src/web/src/hooks/community/use-forum-feed.dom.test.ts b/src/web/src/hooks/community/use-forum-feed.dom.test.ts
index 9853f973d..37974ffb6 100644
--- a/src/web/src/hooks/community/use-forum-feed.dom.test.ts
+++ b/src/web/src/hooks/community/use-forum-feed.dom.test.ts
@@ -175,11 +175,12 @@ describe("mapForumFeedPages", () => {
included: { ...emptyIncluded, parentMessages: [{ id: "opener", channelId: "forum_1", seq: 0, content: " ", authorId: "u1", authorName: "A", authorImage: null, authorAvatarVersion: 0 }], firstMessages: [{ channelId: "post", content: preview }] },
}])
expect(result).toHaveLength(1)
- expect(result[0]).toMatchObject({ name: "Fallback", messageCount: 0, lastMessageAt: "", parent: { authorId: "u1", authorName: "A", text: preview.slice(0, 100) }, parentSeq: 0, openerMessageId: "opener", preview: preview.slice(0, 100) })
- patchCanonicalCommunityChannel(client, "post", (row) => ({ ...row, preview, lastMessageAt: null }))
+ expect(result[0]).toMatchObject({ name: "Fallback", messageCount: 0, lastMessageAt: "", parent: { authorId: "u1", authorName: "A", text: preview }, parentSeq: 0, openerMessageId: "opener", preview })
+ const updatedPreview = "updated preview".repeat(30)
+ patchCanonicalCommunityChannel(client, "post", (row) => ({ ...row, preview: updatedPreview, lastMessageAt: null }))
const registry = getCommunityDbRegistry(client)!
const projected = mapForumFeedPages([{ serverId: "server_1", parentType: "forum", threads: [{ id: "post", openerMessageId: "opener", participantIds: [] }], hasMore: false }], new Map(getCanonicalCommunityMessages(client).map((row) => [row.id, row])), new Map(getCanonicalCommunityChannels(client).map((row) => [row.id, row])), new Map([...registry.collections.profiles.values()].map((row) => [row.id, row])))
- expect(projected[0]).toMatchObject({ lastMessageAt: "", parent: { text: preview }, preview, parentSeq: 0 })
+ expect(projected[0]).toMatchObject({ lastMessageAt: "", parent: { text: updatedPreview }, preview: updatedPreview, parentSeq: 0 })
})
it("keeps one operation baseline across pages and excludes duplicate profile publications", async () => {
const registry = getCommunityDbRegistry(client)!
diff --git a/src/web/src/lib/community-db/schema.ts b/src/web/src/lib/community-db/schema.ts
index 28ce9187d..1722e6378 100644
--- a/src/web/src/lib/community-db/schema.ts
+++ b/src/web/src/lib/community-db/schema.ts
@@ -42,6 +42,7 @@ export const channelLocalSchema = z.object({
openerSeq: z.number().int().nonnegative().optional(),
openerUnread: z.boolean().optional(),
preview: z.string().optional(),
+ firstMessageId: z.string().min(1).nullable().optional(),
lastUnreadSeq: z.number().int().nonnegative().optional(),
participantCount: z.number().int().nonnegative().optional(),
})
diff --git a/src/web/src/lib/community-db/sync.ts b/src/web/src/lib/community-db/sync.ts
index 04cd15bb5..2f77e92f1 100644
--- a/src/web/src/lib/community-db/sync.ts
+++ b/src/web/src/lib/community-db/sync.ts
@@ -2062,13 +2062,17 @@ export function publishCommunityMessageReaction(queryClient: QueryClient, messag
export function publishCommunityForumFeed(queryClient: QueryClient, forumChannelId: string, page: CommunityThreadResources, proof: CommunityFreshQueryProof) {
return withCommunityQueryProof(queryClient, proof, (registry) => notifyManager.batch(() => {
- const rows = page.threads.map((thread) => canonicalChannelRow({
- ...thread, type: "thread", serverId: page.channel.serverId, parentChannelId: forumChannelId,
- pending: false,
- tags: page.included.tags.filter((tag) => tag.messageId === thread.parentMessageId).map((tag) => tag.tag),
- preview: page.included.previews.find((message) => message.channelId === thread.id)?.content.slice(0, 100) ?? "",
- participantCount: page.included.participantCounts.find((row) => row.channelId === thread.id)?.count ?? 0,
- }, registry.collections.channels.get(thread.id)))
+ const rows = page.threads.map((thread) => {
+ const first = page.included.previews.find((message) => message.channelId === thread.id)
+ return canonicalChannelRow({
+ ...thread, type: "thread", serverId: page.channel.serverId, parentChannelId: forumChannelId,
+ pending: false,
+ tags: page.included.tags.filter((tag) => tag.messageId === thread.parentMessageId).map((tag) => tag.tag),
+ preview: first?.content ?? "",
+ firstMessageId: page.channel.type === "forum" ? first?.id || null : null,
+ participantCount: page.included.participantCounts.find((row) => row.channelId === thread.id)?.count ?? 0,
+ }, registry.collections.channels.get(thread.id))
+ })
upsertRows(registry, "channels", rows)
ingestResourceProfiles(registry, page.included.profiles, proof)
publishCommunityEmbeddedMessages(queryClient, { entries: page.included.messages.map((message) => ({ channelId: message.channelId, message })), proof })
@@ -2512,7 +2516,7 @@ export function projectCommunityWsEventToDb(
}
return projected
}
- case "community:message.edited":
+ case "community:message.edited": {
patchRows(
registry,
"messages",
@@ -2521,7 +2525,16 @@ export function projectCommunityWsEventToDb(
[event.messageId],
["content"],
)
+ const thread = registry.collections.channels.get(event.channelId)
+ if (thread?.type === "thread" && thread.firstMessageId === event.messageId) {
+ const ownsPreview = (row: ChannelRow) => row.id === event.channelId
+ && row.type === "thread" && row.firstMessageId === event.messageId
+ patchRows(registry, "channels",
+ (row) => ownsPreview(row) ? { ...row, preview: event.content } : row,
+ ownsPreview, [event.channelId], ["preview"])
+ }
return
+ }
case "community:message.updated":
patchRows(
registry,
diff --git a/src/web/src/lib/community/enrich-messages.test.ts b/src/web/src/lib/community/enrich-messages.test.ts
index 911c97d1d..f5eee34be 100644
--- a/src/web/src/lib/community/enrich-messages.test.ts
+++ b/src/web/src/lib/community/enrich-messages.test.ts
@@ -138,7 +138,8 @@ describe("enrichMessages attachment projection", () => {
])
})
- it("projects canonical versioned avatars for forum thread participants", async () => {
+ it("retains full forum previews and canonical versioned avatars for participants", async () => {
+ const preview = "Opening preview beyond the former character boundary. ".repeat(8)
mocks.listAttachments.mockResolvedValue([])
mocks.getReplies.mockResolvedValue([])
mocks.listForumChildren.mockResolvedValue([{
@@ -151,7 +152,7 @@ describe("enrichMessages attachment projection", () => {
}])
mocks.getFirstMessages.mockResolvedValue([{
channelId: "thread-1",
- content: "Opening preview",
+ content: preview,
}])
mocks.listParticipants.mockResolvedValue([{
channelId: "thread-1",
@@ -186,6 +187,7 @@ describe("enrichMessages attachment projection", () => {
expect(result.messages[0]).toMatchObject({
thread: {
id: "thread-1",
+ preview,
participants: [{
id: "u2",
avatar: "/api/community/users/u2/avatar?v=4",
diff --git a/src/web/src/lib/community/enrich-messages.ts b/src/web/src/lib/community/enrich-messages.ts
index c5823814f..fb634e79c 100644
--- a/src/web/src/lib/community/enrich-messages.ts
+++ b/src/web/src/lib/community/enrich-messages.ts
@@ -95,7 +95,7 @@ export async function enrichMessages(
lastReplyAt: scope.contract === 3 ? c.lastMessageAt : c.lastMessageAt ?? c.createdAt,
...(scope.isForum ? {
tags: tagsByMessage.get(c.parentMessageId!) ?? [],
- preview: (first?.content ?? "").slice(0, 100),
+ preview: first?.content ?? "",
participants: participantsByChannel.get(c.id) ?? [],
participantCount: participantCountByChannel.get(c.id) ?? 0,
} : {}),
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 41769ef4e..aac7e0424 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
@@ -176,6 +176,7 @@ async function expectMobileGeometry(
card: Locator,
postId: string,
visibleTags: string[],
+ expectedTitle: string,
titleState: "single" | "double" | "truncated",
role: "author" | "manager",
width: (typeof MOBILE_WIDTHS)[number],
@@ -189,7 +190,11 @@ async function expectMobileGeometry(
const title = page.getByTestId(tid.forumThreadTitle(postId))
const titleText = page.getByTestId(tid.forumThreadTitleText(postId))
const sequence = page.getByTestId(tid.forumThreadSeq(postId))
- await expect(title).toHaveAttribute("data-truncated", titleState === "truncated" ? "true" : "false")
+ await expect(titleText).toHaveText(expectedTitle)
+ await expect(title).toHaveAttribute("title", expectedTitle)
+ await expect(sequence).toHaveText(/^#\d+$/)
+ const fullSequence = await sequence.innerText()
+ await expect(title).toHaveAccessibleName(`${expectedTitle} ${fullSequence}`)
await expect(sequence).toBeVisible()
const [listRect, cardRect, titleRect, tagRect, deleteRect, sequenceRect] = await Promise.all([
rect(page.getByTestId(tid.forumPostList)),
@@ -205,32 +210,36 @@ async function expectMobileGeometry(
expect(Math.abs(cardRect!.left - listRect!.left), `${role}/${postId}@${width}: edge-to-edge left`).toBeLessThanOrEqual(0.5)
expect(Math.abs(cardRect!.right - listRect!.right), `${role}/${postId}@${width}: edge-to-edge right`).toBeLessThanOrEqual(0.5)
expect(titleRect!.left - cardRect!.left, `${role}/${postId}@${width}: internal title inset`).toBeGreaterThanOrEqual(16)
- const titleMetrics = await title.evaluate((element) => {
+ const titleMetrics = await titleText.evaluate((element) => {
+ const bounds = element.getBoundingClientRect()
const lineHeight = Number.parseFloat(getComputedStyle(element).lineHeight)
- return { height: element.getBoundingClientRect().height, lineHeight }
- })
- const textFragments = await titleText.evaluate((element) => Array.from(element.getClientRects())
- .filter((fragment) => fragment.width > 0 && fragment.height > 0)
- .map((fragment) => ({ left: fragment.left, right: fragment.right, top: fragment.top, bottom: fragment.bottom })))
- const textLines = textFragments.reduce<typeof textFragments>((lines, fragment) => {
- const line = lines.find((candidate) => Math.abs(candidate.top - fragment.top) <= 1)
- if (line) {
- line.left = Math.min(line.left, fragment.left)
- line.right = Math.max(line.right, fragment.right)
- line.bottom = Math.max(line.bottom, fragment.bottom)
- } else {
- lines.push({ ...fragment })
+ return {
+ top: bounds.top, bottom: bounds.bottom, right: bounds.right,
+ height: bounds.height, lineHeight,
+ scrollHeight: element.scrollHeight, clientHeight: element.clientHeight,
}
- return lines
- }, [])
+ })
const expectedLines = titleState === "single" ? 1 : 2
- expect(textLines, `${role}/${postId}@${width}: visible title lines`).toHaveLength(expectedLines)
+ expect(Math.abs(titleMetrics.height - titleMetrics.lineHeight * expectedLines), `${role}/${postId}@${width}: visible title lines`).toBeLessThanOrEqual(0.5)
expect(titleMetrics.height, `${role}/${postId}@${width}: two-line clamp`).toBeLessThanOrEqual(titleMetrics.lineHeight * 2 + 0.5)
- const lastTextLine = textLines.at(-1)!
- expect(Math.abs(sequenceRect!.top - lastTextLine.top), `${role}/${postId}@${width}: seq line`).toBeLessThanOrEqual(3)
- expect(Math.abs(sequenceRect!.bottom - lastTextLine.bottom), `${role}/${postId}@${width}: seq baseline`).toBeLessThanOrEqual(3)
- expect(sequenceRect!.left - lastTextLine.right, `${role}/${postId}@${width}: seq gap`).toBeGreaterThanOrEqual(4)
- expect(sequenceRect!.left - lastTextLine.right, `${role}/${postId}@${width}: seq gap`).toBeLessThanOrEqual(8)
+ if (titleState === "truncated") {
+ expect(titleMetrics.scrollHeight, `${role}/${postId}@${width}: native title overflow`).toBeGreaterThan(titleMetrics.clientHeight)
+ } else {
+ expect(Math.abs(titleMetrics.scrollHeight - titleMetrics.clientHeight), `${role}/${postId}@${width}: title fits`).toBeLessThanOrEqual(1)
+ }
+ const sequenceMetrics = await sequence.evaluate((element, titleId) => ({
+ clientWidth: element.clientWidth,
+ scrollWidth: element.scrollWidth,
+ separateFromTitle: element.parentElement?.querySelector(`[data-testid="${titleId}"]`)?.contains(element) === false,
+ }), tid.forumThreadTitleText(postId))
+ expect(sequenceMetrics.separateFromTitle, `${role}/${postId}@${width}: sequence outside title clamp`).toBe(true)
+ expect(sequenceMetrics.scrollWidth, `${role}/${postId}@${width}: complete sequence width`).toBeLessThanOrEqual(sequenceMetrics.clientWidth)
+ const lastLineTop = titleMetrics.top + titleMetrics.lineHeight * (expectedLines - 1)
+ expect(Math.abs(sequenceRect!.top - lastLineTop), `${role}/${postId}@${width}: seq line`).toBeLessThanOrEqual(3)
+ expect(Math.abs(sequenceRect!.bottom - titleMetrics.bottom), `${role}/${postId}@${width}: seq baseline`).toBeLessThanOrEqual(3)
+ expect(sequenceRect!.left - titleMetrics.right, `${role}/${postId}@${width}: seq block gap`).toBeGreaterThanOrEqual(4)
+ expect(sequenceRect!.left - titleMetrics.right, `${role}/${postId}@${width}: seq block gap`).toBeLessThanOrEqual(8)
+ expect(sequenceRect!.right, `${role}/${postId}@${width}: sequence containment`).toBeLessThanOrEqual(titleRect!.right + 0.5)
const controls = [tagRect!, deleteRect!]
for (const controlRect of controls) {
expect(controlRect.width, `${role}/${postId}@${width}: touch width`).toBe(32)
@@ -481,22 +490,25 @@ test("forum post actions stay discoverable on mobile without changing permission
const compactForumId = await seedChannel("alice", serverId, "compact-tags", "forum")
await seedJoinServer("alice", "bob", serverId)
await seedJoinServer("alice", "carol", serverId)
+ const primaryTitle = `UnbrokenForumTitle${Date.now()}${"abcdefghij".repeat(12)}`
+ const cjkTitle = `移动端论坛标题必须换到第二行展示${stamp}`
+ const noTagTitle = `One line ${stamp}`
const primaryPostId = await seedForumThread(
"bob",
forumId,
- `UnbrokenForumTitle${Date.now()}${"abcdefghij".repeat(12)}`,
+ primaryTitle,
"mobile action geometry",
)
const cjkPostId = await seedForumThread(
"bob",
forumId,
- `移动端论坛标题必须换到第二行展示${stamp}`,
+ cjkTitle,
"two tag geometry",
)
const noTagPostId = await seedForumThread(
"bob",
forumId,
- `One line ${stamp}`,
+ noTagTitle,
"zero tag geometry",
)
const compactPostId = await seedForumThread(
@@ -510,9 +522,9 @@ test("forum post actions stay discoverable on mobile without changing permission
await seedTags(forumId, cjkPostId, [...DESKTOP_OVERFLOW_TAGS])
await seedTags(compactForumId, compactPostId, ["solo"])
const postCases = [
- { id: primaryPostId, tags: TAGS.slice(0, 2), titleState: "truncated" as const },
- { id: cjkPostId, tags: [], titleState: "double" as const },
- { id: noTagPostId, tags: [], titleState: "single" as const },
+ { id: primaryPostId, title: primaryTitle, tags: TAGS.slice(0, 2), titleState: "truncated" as const },
+ { id: cjkPostId, title: cjkTitle, tags: [], titleState: "double" as const },
+ { id: noTagPostId, title: noTagTitle, tags: [], titleState: "single" as const },
]
const route = `/c/channels/${serverId}/${forumId}`
const compactRoute = `/c/channels/${serverId}/${compactForumId}`
@@ -537,6 +549,7 @@ test("forum post actions stay discoverable on mobile without changing permission
author.page.getByTestId(tid.forumThreadCard(post.id)),
post.id,
post.tags,
+ post.title,
post.titleState,
"author",
width,
@@ -583,6 +596,7 @@ test("forum post actions stay discoverable on mobile without changing permission
manager.page.getByTestId(tid.forumThreadCard(post.id)),
post.id,
post.tags,
+ post.title,
post.titleState,
"manager",
width,