Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): keep forum sequence inline with clamped titles (#979)

Generab0a2f83f81d
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 5de599452..ad52edcf6 100644
--- a/src/web/src/components/community/channels/forum-view.test.ts
+++ b/src/web/src/components/community/channels/forum-view.test.ts
@@ -142,6 +142,16 @@ describe("ForumView post card header", () => {
expect(paragraph?.[2]).toBe(preview)
})
+ it("keeps the full title and complete sequence accessible in the server-rendered fallback", () => {
+ const name = "完整标题👩‍👩‍👧‍👦 é ".repeat(12)
+ const html = render([makePost({ name, parentSeq: 9007199254740991 })])
+ expect(html).toContain(`aria-label="${name} #9007199254740991"`)
+ expect(html).toContain(`title="${name}"`)
+ expect(html).toContain(`<span class="opacity-60">#</span>9007199254740991`)
+ expect(html).toContain(name)
+ expect(html).toContain("-webkit-line-clamp:2")
+ })
+
it("uses a flat hairline row instead of the old bordered card", () => {
const html = render([makePost()])
const testIdIndex = html.indexOf(tid.forumThreadCard("p1"))
@@ -287,7 +297,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("flex w-full min-w-0 max-w-full items-end gap-1.5")
+ expect(html).toContain("w-full min-w-0 max-w-full text-[15px] font-semibold leading-tight")
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 94d9c27c7..2e8ba2adb 100644
--- a/src/web/src/components/community/channels/forum-view.tsx
+++ b/src/web/src/components/community/channels/forum-view.tsx
@@ -8,6 +8,7 @@ import { useVirtualizer } from "@tanstack/react-virtual"
import { COMMUNITY_VIRTUALIZER_REACT_OPTIONS } from "@/hooks/community/virtualizer-react-options"
import { Archive, ArchiveRestore, MessagesSquare, ListChevronsUpDown, Plus, Tag, Trash2 } from "lucide-react"
import { Button } from "@/components/ui/button"
+import { LineClamp } from "@/components/ui/line-clamp"
import { formatRelativeTime } from "@/lib/community/format-time"
import { Skeleton } from "@/components/ui/skeleton"
import { Avatar } from "../avatar"
@@ -103,22 +104,21 @@ function ForumPostTitle({ name, postId, seq }: { name: string; postId: string; s
data-testid={tid.forumThreadTitle(postId)}
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"
+ className="w-full min-w-0 max-w-full text-[15px] font-semibold leading-tight"
>
- <span
- data-testid={tid.forumThreadTitleText(postId)}
- className="line-clamp-2 min-w-0 wrap-break-word"
- >
- {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>
- )}
+ <LineClamp
+ text={name}
+ maxLines={2}
+ textTestId={tid.forumThreadTitleText(postId)}
+ after={seq === undefined ? undefined : (
+ <span
+ data-testid={tid.forumThreadSeq(postId)}
+ className="font-mono text-[13px] font-medium text-muted-foreground"
+ >
+ <span className="opacity-60">#</span>{seq}
+ </span>
+ )}
+ />
</h3>
)
}
diff --git a/src/web/src/components/ui/line-clamp.dom.test.tsx b/src/web/src/components/ui/line-clamp.dom.test.tsx
new file mode 100644
index 000000000..32e22fe31
--- /dev/null
+++ b/src/web/src/components/ui/line-clamp.dom.test.tsx
@@ -0,0 +1,207 @@
+import { StrictMode } from "react"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { act, render, screen } from "@/test/react-dom-harness"
+import { LineClamp } from "./line-clamp"
+
+let views: Array<ReturnType<typeof render>>
+let width = 10
+let glyphWidth = 1
+let callbacks: ResizeObserverCallback[]
+let disconnects: Array<ReturnType<typeof vi.fn>>
+let frames: Map<number, FrameRequestCallback>
+let fonts: EventTarget
+let settleFonts: () => void
+let originalFonts: PropertyDescriptor | undefined
+
+beforeEach(() => {
+ views = []
+ width = 10
+ glyphWidth = 1
+ callbacks = []
+ disconnects = []
+ frames = new Map()
+ let nextFrame = 0
+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
+ frames.set(++nextFrame, callback)
+ return nextFrame
+ })
+ vi.stubGlobal("cancelAnimationFrame", (frame: number) => frames.delete(frame))
+ vi.stubGlobal("ResizeObserver", class {
+ observe = vi.fn()
+ disconnect = vi.fn()
+ constructor(callback: ResizeObserverCallback) {
+ callbacks.push(callback)
+ disconnects.push(this.disconnect)
+ }
+ })
+ fonts = Object.assign(new EventTarget(), { ready: new Promise<void>((resolve) => { settleFonts = resolve }) })
+ originalFonts = Object.getOwnPropertyDescriptor(document, "fonts")
+ Object.defineProperty(document, "fonts", { configurable: true, value: fonts })
+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {
+ const suffix = this.querySelector('[data-slot="line-clamp-after"]')?.textContent ?? ""
+ const measuredWidth = this.dataset.slot === "line-clamp-content" ? Math.max(width, suffix.length * glyphWidth) : width
+ return new DOMRect(0, 0, measuredWidth, 1)
+ })
+ vi.spyOn(HTMLElement.prototype, "getClientRects").mockImplementation(function (this: HTMLElement) {
+ const cells = Array.from(this.textContent ?? "").length * glyphWidth
+ const count = Math.ceil(cells / width)
+ return Object.assign(Array.from({ length: count }, (_, index) => new DOMRect(0, index * 2, width, 1)), { item: () => null }) as unknown as DOMRectList
+ })
+})
+
+afterEach(() => {
+ views.forEach((view) => view.unmount())
+ if (originalFonts) Object.defineProperty(document, "fonts", originalFonts)
+ else Reflect.deleteProperty(document, "fonts")
+ vi.restoreAllMocks()
+ vi.unstubAllGlobals()
+})
+
+function flushLayout() {
+ act(() => {
+ const pending = [...frames.values()]
+ frames.clear()
+ pending.forEach((callback) => callback(0))
+ })
+}
+
+function triggerResize() {
+ act(() => { callbacks.at(-1)?.([], {} as ResizeObserver) })
+ flushLayout()
+}
+
+function mount(text: string, options: { maxLines?: number; location?: "end" | "middle" } = {}) {
+ const view = render(<LineClamp text={text} textTestId="text" after={<span data-testid="seq">#9</span>} {...options} />)
+ views.push(view)
+ return view
+}
+
+describe("LineClamp", () => {
+ it("keeps full short and naturally wrapped two-line text with one intact suffix", () => {
+ const rendered = mount("ABC")
+ expect(screen.getByTestId("text")).toHaveTextContent("ABC")
+ rendered.rerender(<LineClamp text="ABCDEFGHIJKLMNO" textTestId="text" after={<span data-testid="seq">#9</span>} />)
+ expect(screen.getByTestId("text")).toHaveTextContent("ABCDEFGHIJKLMNO")
+ expect(screen.getAllByTestId("seq")).toHaveLength(1)
+ expect(rendered.container.querySelector('[data-clamped="false"]')).not.toBeNull()
+ rendered.unmount()
+ })
+
+ it("reserves the entire suffix when truncating and exposes the full text to assistive technology", () => {
+ const name = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ const rendered = mount(name, { maxLines: 1 })
+ expect(screen.getByTestId("text")).toHaveTextContent("ABCDEFG…")
+ expect(screen.getByTestId("text")).toHaveAttribute("aria-hidden", "true")
+ expect(rendered.container.querySelector(".sr-only")).toHaveTextContent(name)
+ expect(screen.getByTestId("seq")).toHaveTextContent("#9")
+ expect(document.querySelector('[inert]')).toBeNull()
+ rendered.unmount()
+ })
+
+ it("keeps both ends in middle mode for one or several lines", () => {
+ const rendered = mount("ABCDEFGHIJKLMNO", { maxLines: 1, location: "middle" })
+ expect(screen.getByTestId("text")).toHaveTextContent("ABCD…MNO")
+ rendered.rerender(<LineClamp text="ABCDEFGHIJKLMNOPQRSTUVWXYZ" textTestId="text" location="middle" maxLines={2} after="#9" />)
+ expect(screen.getByTestId("text")).toHaveTextContent("ABCDEFGHI…STUVWXYZ")
+ rendered.unmount()
+ })
+
+ it.each([
+ { budget: 3, after: "#9" },
+ { budget: 4, after: "#9" },
+ { budget: 1, after: undefined },
+ { budget: 2, after: undefined },
+ ])("uses an explicit middle fallback when width $budget cannot preserve both ends with $after", ({ budget, after }) => {
+ width = budget
+ const text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ const rendered = render(<LineClamp data-testid="clamp" text={text} textTestId="text" maxLines={1} location="middle" after={after} />)
+ views.push(rendered)
+ expect(screen.getByTestId("text")).toBeEmptyDOMElement()
+ expect(screen.getByTestId("clamp")).toHaveAttribute("data-clamp-fallback", "insufficient-space")
+ expect(rendered.container.querySelector(".sr-only")).toHaveTextContent(text)
+ if (after) expect(rendered.container.querySelector('[data-slot="line-clamp-after"]')).toHaveTextContent(after)
+ rendered.unmount()
+ })
+
+ it("retains at least one complete grapheme on each end at the exact minimum middle budget", () => {
+ width = 5
+ const rendered = mount("ABCDEFGHIJKLMNOPQRSTUVWXYZ", { maxLines: 1, location: "middle" })
+ expect(screen.getByTestId("text")).toHaveTextContent("A…Z")
+ expect(rendered.container.querySelector("[data-clamp-fallback]")).toBeNull()
+ width = 3
+ rendered.rerender(<LineClamp text="ABCDEFGHIJKLMNOPQRSTUVWXYZ" textTestId="text" maxLines={2} location="middle" after="#9" />)
+ expect(screen.getByTestId("text")).toHaveTextContent("AB…Z")
+ expect(rendered.container.querySelector("[data-clamp-fallback]")).toBeNull()
+ rendered.unmount()
+ })
+
+ it("cuts on whole grapheme boundaries rather than inside emoji or combining marks", () => {
+ width = 30
+ const name = "🧑🏽‍💻é🇨🇳👩‍👩‍👧‍👦".repeat(4)
+ const rendered = mount(name, { maxLines: 1, location: "middle" })
+ const [prefix, suffix] = screen.getByTestId("text").textContent!.split("…")
+ expect(prefix.length).toBeGreaterThan(0)
+ expect(suffix.length).toBeGreaterThan(0)
+ const boundaries = [...new Intl.Segmenter(undefined, { granularity: "grapheme" }).segment(name)].map(({ index }) => index)
+ expect(boundaries).toContain(prefix.length)
+ expect([...boundaries, name.length]).toContain(name.length - suffix.length)
+ rendered.unmount()
+ })
+
+ it("reflows after container, suffix and font changes and after a zero-width mount becomes visible", async () => {
+ width = 0
+ const rendered = mount("ABCDEFGHIJKLMNOPQRSTUVWXY")
+ expect(screen.getByTestId("text")).toHaveTextContent("ABCDEFGHIJKLMNOPQRSTUVWXY")
+ width = 10
+ triggerResize()
+ expect(screen.getByTestId("text")).toHaveTextContent("ABCDEFGHIJKLMNOPQ…")
+ width = 20
+ triggerResize()
+ expect(screen.getByTestId("text")).toHaveTextContent("ABCDEFGHIJKLMNOPQRSTUVWXY")
+ glyphWidth = 2
+ act(() => { fonts.dispatchEvent(new Event("loadingdone")) })
+ flushLayout()
+ expect(screen.getByTestId("text")).toHaveTextContent("ABCDEFGHIJKLMNOPQ…")
+ rendered.rerender(<LineClamp text="ABCDEFGHIJKLMNOPQRSTUVWXY" textTestId="text" after="#12345" />)
+ expect(screen.getByTestId("text")).toHaveTextContent("ABCDEFGHIJKLM…")
+ rendered.unmount()
+ await act(async () => { settleFonts() })
+ expect(frames.size).toBe(0)
+ expect(disconnects.every((disconnect) => disconnect.mock.calls.length === 1)).toBe(true)
+ })
+
+ it("omits an ellipsis that cannot fit and explicitly exposes an impossible suffix width", () => {
+ width = 2
+ const rendered = mount("ABCDEFGHIJKLMNO", { maxLines: 1 })
+ expect(screen.getByTestId("text")).toBeEmptyDOMElement()
+ expect(screen.getByTestId("seq")).toHaveTextContent("#9")
+ expect(rendered.container.querySelector("[data-clamp-overflow]")).toBeNull()
+ width = 1
+ triggerResize()
+ expect(rendered.container.querySelector('[data-clamp-overflow="true"]')).not.toBeNull()
+ expect(screen.getByTestId("seq")).toHaveTextContent("#9")
+ rendered.unmount()
+ })
+
+ it("keeps full text and the native bounded fallback when Intl.Segmenter is unavailable", () => {
+ vi.stubGlobal("Intl", Object.assign(Object.create(Intl), { Segmenter: undefined }))
+ const rendered = mount("👩‍👩‍👧‍👦é".repeat(4), { maxLines: 1 })
+ expect(screen.getByTestId("text")).toHaveTextContent("👩‍👩‍👧‍👦é".repeat(4))
+ expect(screen.getByTestId("text").style.webkitLineClamp).toBe("1")
+ expect(screen.getByTestId("seq")).toHaveTextContent("#9")
+ expect(disconnects).toHaveLength(0)
+ rendered.unmount()
+ })
+
+ it("cleans up repeated StrictMode mounts and pending resize work", () => {
+ const rendered = render(<StrictMode><LineClamp text="ABCDEFGHIJKLMNOPQRSTUVWXYZ" after="#9" /></StrictMode>)
+ views.push(rendered)
+ act(() => { callbacks.at(-1)?.([], {} as ResizeObserver) })
+ expect(frames.size).toBeGreaterThan(0)
+ rendered.unmount()
+ act(() => { callbacks.at(-1)?.([], {} as ResizeObserver) })
+ expect(frames.size).toBe(0)
+ expect(disconnects.every((disconnect) => disconnect.mock.calls.length === 1)).toBe(true)
+ expect(document.querySelector('[inert]')).toBeNull()
+ })
+})
diff --git a/src/web/src/components/ui/line-clamp.tsx b/src/web/src/components/ui/line-clamp.tsx
new file mode 100644
index 000000000..50581902b
--- /dev/null
+++ b/src/web/src/components/ui/line-clamp.tsx
@@ -0,0 +1,142 @@
+"use client"
+
+import { useLayoutEffect, useMemo, useRef, useState, type ComponentProps, type ReactNode } from "react"
+import { cn } from "@/lib/utils"
+
+type LineClampProps = Omit<ComponentProps<"span">, "children" | "ref"> & {
+ text: string
+ maxLines?: number
+ ellipsis?: string
+ location?: "end" | "middle"
+ after?: ReactNode
+ textTestId?: string
+}
+
+export function LineClamp({
+ text,
+ maxLines = 2,
+ ellipsis = "…",
+ location = "end",
+ after,
+ textTestId,
+ className,
+ ...props
+}: LineClampProps) {
+ const rootRef = useRef<HTMLSpanElement>(null)
+ const afterRef = useRef<HTMLSpanElement>(null)
+ const lines = Number.isFinite(maxLines) ? Math.max(1, Math.floor(maxLines)) : 2
+ const offsets = useMemo(() => typeof Intl.Segmenter === "function" ? [0, ...Array.from(
+ new Intl.Segmenter(undefined, { granularity: "grapheme" }).segment(text),
+ ({ index, segment }) => index + segment.length,
+ )] : null, [text])
+ const [fit, setFit] = useState<{ input: string; lines: number; location: string; ellipsis: string; value: string; clamped: boolean; overflow: boolean; fallback: boolean }>()
+ const current = fit?.input === text && fit.lines === lines && fit.location === location && fit.ellipsis === ellipsis ? fit : undefined
+
+ useLayoutEffect(() => {
+ const root = rootRef.current
+ if (!root || !offsets) return
+ let active = true
+ let frame = 0
+ const measure = () => {
+ const width = root.getBoundingClientRect().width
+ const parent = root.parentNode
+ if (!active || !parent || width <= 0) return
+ const clone = root.cloneNode(true) as HTMLSpanElement
+ clone.removeAttribute("id")
+ clone.removeAttribute("data-testid")
+ clone.setAttribute("aria-hidden", "true")
+ clone.inert = true
+ Object.assign(clone.style, {
+ position: "absolute", visibility: "hidden", pointerEvents: "none",
+ left: "0", top: "0", width: `${width}px`, maxWidth: "none",
+ height: "auto", maxHeight: "none", display: "block", overflow: "visible",
+ })
+ const content = clone.querySelector<HTMLElement>('[data-slot="line-clamp-content"]')!
+ const body = clone.querySelector<HTMLElement>('[data-slot="line-clamp-text"]')!
+ content.style.display = "inline"
+ Object.assign(body.style, { display: "inline", overflow: "visible", WebkitLineClamp: "unset" })
+ for (const node of clone.querySelectorAll("[id], [data-testid]")) {
+ node.removeAttribute("id")
+ node.removeAttribute("data-testid")
+ }
+ parent.insertBefore(clone, root.nextSibling)
+ const fits = (value: string) => {
+ body.textContent = value
+ const tops: number[] = []
+ for (const rect of content.getClientRects()) {
+ if (rect.width <= 0 || rect.height <= 0) continue
+ if (!tops.some((top) => Math.abs(top - rect.top) < 1)) tops.push(rect.top)
+ }
+ return tops.length <= lines && content.getBoundingClientRect().width <= width + 0.5
+ }
+ try {
+ let value = text
+ const clamped = !fits(text)
+ let overflow = false
+ let fallback = false
+ if (clamped) {
+ const candidate = (count: number) => {
+ const prefix = location === "middle" ? Math.ceil(count / 2) : count
+ const suffix = count - prefix
+ return text.slice(0, offsets[prefix]) + ellipsis + (suffix ? text.slice(offsets[offsets.length - 1 - suffix]) : "")
+ }
+ let low = location === "middle" ? 2 : 0
+ let high = offsets.length - 2
+ let best: number | undefined
+ while (low <= high) {
+ const count = Math.floor((low + high) / 2)
+ if (fits(candidate(count))) {
+ best = count
+ low = count + 1
+ } else {
+ high = count - 1
+ }
+ }
+ fallback = best === undefined
+ value = fallback ? "" : candidate(best!)
+ overflow = best === undefined && !fits("")
+ }
+ setFit((previous) => previous?.input === text && previous.lines === lines && previous.location === location && previous.ellipsis === ellipsis && previous.value === value && previous.clamped === clamped && previous.overflow === overflow && previous.fallback === fallback
+ ? previous : { input: text, lines, location, ellipsis, value, clamped, overflow, fallback })
+ } finally {
+ clone.remove()
+ }
+ }
+ const schedule = () => {
+ if (!active) return
+ cancelAnimationFrame(frame)
+ frame = requestAnimationFrame(measure)
+ }
+ measure()
+ const observer = typeof ResizeObserver === "undefined" ? undefined : new ResizeObserver(schedule)
+ observer?.observe(root)
+ if (afterRef.current) observer?.observe(afterRef.current)
+ const fonts = document.fonts
+ void fonts?.ready.then(() => { if (active) schedule() })
+ fonts?.addEventListener("loadingdone", schedule)
+ return () => {
+ active = false
+ cancelAnimationFrame(frame)
+ observer?.disconnect()
+ fonts?.removeEventListener("loadingdone", schedule)
+ }
+ }, [text, lines, ellipsis, location, after, offsets])
+
+ return (
+ <span {...props} ref={rootRef} className={cn("block min-w-0 max-w-full", className)} data-clamped={current?.clamped} data-clamp-overflow={current?.overflow || undefined} data-clamp-fallback={current?.fallback ? "insufficient-space" : undefined}>
+ {current?.clamped && <span className="sr-only">{text}</span>}
+ <span data-slot="line-clamp-content" className={current ? "inline" : "flex items-end"}>
+ <span
+ aria-hidden={current?.clamped || undefined}
+ data-slot="line-clamp-text"
+ data-testid={textTestId}
+ className="min-w-0 wrap-anywhere"
+ style={current ? undefined : { display: "-webkit-box", WebkitBoxOrient: "vertical", WebkitLineClamp: lines, overflow: "hidden" }}
+ >
+ {current?.value ?? text}
+ </span>
+ {after != null && <span ref={afterRef} data-slot="line-clamp-after" className="ml-1.5 inline-block shrink-0 whitespace-nowrap">{after}</span>}
+ </span>
+ </span>
+ )
+}
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 aac7e0424..41a4d619b 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
@@ -190,7 +190,15 @@ 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(titleText).toHaveText(expectedTitle)
+ await expect(title.locator("[data-clamped]")).toHaveAttribute("data-clamped", String(titleState === "truncated"))
+ if (titleState === "truncated") {
+ await expect(titleText).toHaveText(/…$/)
+ const visible = await titleText.innerText()
+ expect(expectedTitle.startsWith(visible.slice(0, -1))).toBe(true)
+ expect(visible.length).toBeLessThan(expectedTitle.length)
+ } else {
+ await expect(titleText).toHaveText(expectedTitle)
+ }
await expect(title).toHaveAttribute("title", expectedTitle)
await expect(sequence).toHaveText(/^#\d+$/)
const fullSequence = await sequence.innerText()
@@ -211,34 +219,38 @@ async function expectMobileGeometry(
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 titleText.evaluate((element) => {
- const bounds = element.getBoundingClientRect()
- const lineHeight = Number.parseFloat(getComputedStyle(element).lineHeight)
- return {
- top: bounds.top, bottom: bounds.bottom, right: bounds.right,
- height: bounds.height, lineHeight,
- scrollHeight: element.scrollHeight, clientHeight: element.clientHeight,
+ const range = document.createRange()
+ range.selectNodeContents(element)
+ const fragments = [...range.getClientRects()].filter((fragment) => fragment.width > 0 && fragment.height > 0)
+ const last = fragments.at(-1)!
+ const content = element.closest('[data-slot="line-clamp-content"]')!
+ const lineTops: number[] = []
+ for (const fragment of content.getClientRects()) {
+ if (!lineTops.some((top) => Math.abs(top - fragment.top) < 1)) lineTops.push(fragment.top)
}
+ return { lines: lineTops.length, last: { top: last.top, bottom: last.bottom, right: last.right } }
})
const expectedLines = titleState === "single" ? 1 : 2
- 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)
- if (titleState === "truncated") {
- expect(titleMetrics.scrollHeight, `${role}/${postId}@${width}: native title overflow`).toBeGreaterThan(titleMetrics.clientHeight)
+ expect(titleMetrics.lines, `${role}/${postId}@${width}: actual inline lines`).toBe(expectedLines)
+ const sequenceMetrics = await sequence.evaluate((element, titleId) => {
+ const bounds = element.getBoundingClientRect()
+ return {
+ width: bounds.width,
+ scrollWidth: element.scrollWidth,
+ insideTitleText: document.querySelector(`[data-testid="${titleId}"]`)?.contains(element),
+ }
+ }, tid.forumThreadTitleText(postId))
+ expect(sequenceMetrics.insideTitleText, `${role}/${postId}@${width}: complete sequence outside cut text`).toBe(false)
+ expect(sequenceMetrics.scrollWidth, `${role}/${postId}@${width}: complete sequence width`).toBeLessThanOrEqual(sequenceMetrics.width + 1)
+ const sameLine = Math.abs(sequenceRect!.bottom - titleMetrics.last.bottom) <= 3
+ if (sameLine) {
+ const gap = sequenceRect!.left - titleMetrics.last.right
+ expect(gap, `${role}/${postId}@${width}: last visible character to seq gap`).toBeGreaterThanOrEqual(4)
+ expect(gap, `${role}/${postId}@${width}: last visible character to seq gap`).toBeLessThanOrEqual(8)
} else {
- expect(Math.abs(titleMetrics.scrollHeight - titleMetrics.clientHeight), `${role}/${postId}@${width}: title fits`).toBeLessThanOrEqual(1)
+ expect(sequenceRect!.top, `${role}/${postId}@${width}: whole sequence naturally wraps`).toBeGreaterThan(titleMetrics.last.top)
+ expect(sequenceRect!.left - titleRect!.left, `${role}/${postId}@${width}: wrapped sequence starts at inline inset`).toBeLessThanOrEqual(8)
}
- 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) {