Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(mobile): reveal parent pages during back gestures (#990)

Gustavo Ye021081e4d294
diff --git a/src/desktop/src-tauri/gen/android/app/build.gradle.kts b/src/desktop/src-tauri/gen/android/app/build.gradle.kts
index ba6c4c498..8d28cb78a 100644
--- a/src/desktop/src-tauri/gen/android/app/build.gradle.kts
+++ b/src/desktop/src-tauri/gen/android/app/build.gradle.kts
@@ -45,6 +45,10 @@ val exclusivePageStartedCallback = originalPageStartedCallback.replace(
"if (interceptedState[url] == false)",
"if (interceptedState[url] == false && !(view as RustWebView).isDocumentStartScriptEnabled)",
)
+val scopedPageStartedCallback = exclusivePageStartedCallback.replace(
+ " currentUrl = url",
+ " (view.context as? ai.alook.android.MainActivity)?.onBackDocumentStarted(view)\n currentUrl = url",
+)
val pageLoadedCall = " Rust.onPageLoaded((view as RustWebView).id, url)"
val legacyAndSslRecoveryDispatch = "\n\n" + """
@Suppress("DEPRECATION")
@@ -76,10 +80,11 @@ fun wireGeneratedWebViewRecovery(sourceFile: File) {
if (listOf("handlePageCommitVisible", "handlePageStarted", "handlePageFinished").any(source::contains)) {
throw GradleException("Stale Wry page-ready callback; regenerate RustWebViewClient")
}
- if (source.occurrencesOf(originalPageStartedCallback) + source.occurrencesOf(exclusivePageStartedCallback) != 1) {
+ if (source.occurrencesOf(originalPageStartedCallback) + source.occurrencesOf(exclusivePageStartedCallback) + source.occurrencesOf(scopedPageStartedCallback) != 1) {
throw GradleException("Wry RustWebViewClient initialization callback changed")
}
source = source.replace(originalPageStartedCallback, exclusivePageStartedCallback)
+ .replace(exclusivePageStartedCallback, scopedPageStartedCallback)
if (!source.contains(modernRecoveryDispatch)) {
if (source.occurrencesOf(modernErrorMethod) != 1) {
throw GradleException("Wry RustWebViewClient modern error callback changed")
@@ -99,7 +104,7 @@ fun wireGeneratedWebViewRecovery(sourceFile: File) {
fun verifyGeneratedWebViewRecovery(sourceFile: File) {
val source = sourceFile.readText()
val required = listOf(
- "exclusive remote initialization callback" to exclusivePageStartedCallback,
+ "exclusive remote initialization callback" to scopedPageStartedCallback,
"modern main-frame recovery dispatch" to
(modernErrorMethod + "\n" + modernRecoveryDispatch),
"legacy recovery dispatch" to
diff --git a/src/desktop/src-tauri/gen/android/app/src/main/AndroidManifest.xml b/src/desktop/src-tauri/gen/android/app/src/main/AndroidManifest.xml
index 92f110be3..c910f267e 100644
--- a/src/desktop/src-tauri/gen/android/app/src/main/AndroidManifest.xml
+++ b/src/desktop/src-tauri/gen/android/app/src/main/AndroidManifest.xml
@@ -6,6 +6,7 @@
<uses-feature android:name="android.software.leanback" android:required="false" />
<application
+ android:enableOnBackInvokedCallback="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Theme.alook_desktop"
diff --git a/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/MainActivity.kt b/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/MainActivity.kt
index 1c78027bb..2ab23dc11 100644
--- a/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/MainActivity.kt
+++ b/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/MainActivity.kt
@@ -3,10 +3,14 @@ package ai.alook.android
import android.content.res.Configuration
import android.graphics.Color
import android.os.Bundle
+import android.net.Uri
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebView
+import androidx.activity.BackEventCompat
+import androidx.activity.OnBackPressedCallback
import androidx.activity.enableEdgeToEdge
+import org.json.JSONObject
import androidx.core.graphics.Insets
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.core.view.ViewCompat
@@ -19,6 +23,29 @@ import ai.alook.plugin.mobileshareimage.MobileShareImageDocumentOwner
class MainActivity : TauriActivity() {
override val handleBackNavigation: Boolean = false
+ private val nativeBackProgress = NativeBackProgress()
+ private val progressCallback = object : OnBackPressedCallback(true) {
+ override fun handleOnBackStarted(backEvent: BackEventCompat) {
+ sendBackProgress(0f, start = true)
+ }
+ override fun handleOnBackProgressed(backEvent: BackEventCompat) {
+ sendBackProgress(backEvent.progress)
+ }
+ override fun handleOnBackCancelled() {
+ sendBackProgress(null)
+ nativeBackProgress.reset()
+ }
+ override fun handleOnBackPressed() {
+ if (nativeBackProgress.consumeTerminal()) return
+ isEnabled = false
+ try {
+ onBackPressedDispatcher.onBackPressed()
+ } finally {
+ isEnabled = true
+ }
+ }
+ }
+
private var isReady = false
private var mainWebView: WebView? = null
private var startupAttachListener: View.OnAttachStateChangeListener? = null
@@ -82,7 +109,40 @@ class MainActivity : TauriActivity() {
super.onSaveInstanceState(outState)
}
+ override fun onResume() {
+ super.onResume()
+ attachBackProgress()
+ }
+
+ override fun onStop() {
+ nativeBackProgress.invalidate()
+ super.onStop()
+ }
+
+ fun onBackDocumentStarted(webView: WebView) {
+ if (webView === mainWebView) nativeBackProgress.invalidate()
+ }
+
+ private fun attachBackProgress() {
+ if (mainWebView == null || isDestroyed || isFinishing) return
+ progressCallback.remove()
+ onBackPressedDispatcher.addCallback(this, progressCallback)
+ }
+
+ private fun sendBackProgress(value: Float?, start: Boolean = false) {
+ val webView = mainWebView ?: return
+ val href = webView.url ?: return
+ val url = Uri.parse(href)
+ val trusted = url.scheme == "https" && url.host == "alook.ai" && (url.port == -1 || url.port == 443)
+ || BuildConfig.DEBUG && url.scheme == "http" && url.host == "localhost" && url.port == 3000
+ if (!trusted) { nativeBackProgress.invalidate(); return }
+ val script = if (start) nativeBackProgress.start(JSONObject.quote(href)) else nativeBackProgress.progress(value)
+ if (script != null) webView.evaluateJavascript(script, null)
+ }
+
override fun onDestroy() {
+ nativeBackProgress.reset()
+ progressCallback.remove()
clearStartupAttachListener()
mainWebView = null
mobileShareImageDocumentOwner.detach()
@@ -93,6 +153,8 @@ class MainActivity : TauriActivity() {
super.onWebViewCreate(webView)
clearStartupAttachListener()
mainWebView = webView
+ nativeBackProgress.reset()
+ webView.post { if (mainWebView === webView) attachBackProgress() }
if (!isReady && !isDestroyed && !isFinishing) {
val listener = object : View.OnAttachStateChangeListener {
override fun onViewAttachedToWindow(view: View) {
diff --git a/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/NativeBackProgress.kt b/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/NativeBackProgress.kt
new file mode 100644
index 000000000..844cf8cef
--- /dev/null
+++ b/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/NativeBackProgress.kt
@@ -0,0 +1,43 @@
+package ai.alook.android
+
+internal class NativeBackProgress {
+ private var generation = 0L
+ private var href: String? = null
+ private var stale = false
+
+ fun start(quotedHref: String): String {
+ stale = false
+ href = quotedHref
+ generation += 1
+ return "if (location.href === $quotedHref) { window.__alookNativeBackGesture = $generation; ${event("0", started = true)} }"
+ }
+
+ fun progress(value: Float?): String? {
+ val target = href ?: run { if (value == null) reset(); return null }
+ if (value != null && !value.isFinite()) return null
+ val script = "if (location.href === $target && window.__alookNativeBackGesture === $generation) { ${event(value?.coerceIn(0f, 1f)?.toString() ?: "null")} }"
+ if (value == null) reset()
+ return script
+ }
+
+ fun invalidate() {
+ if (href != null) stale = true
+ href = null
+ generation += 1
+ }
+
+ fun consumeTerminal(): Boolean {
+ val consume = stale
+ reset()
+ return consume
+ }
+
+ fun reset() {
+ stale = false
+ href = null
+ generation += 1
+ }
+
+ private fun event(value: String, started: Boolean = false) =
+ "window.dispatchEvent(new CustomEvent('alook:native-back-progress', { detail: { progress: $value, started: $started } }));"
+}
diff --git a/src/desktop/src-tauri/gen/android/app/src/test/java/ai/alook/android/NativeBackProgressTest.kt b/src/desktop/src-tauri/gen/android/app/src/test/java/ai/alook/android/NativeBackProgressTest.kt
new file mode 100644
index 000000000..a9b0c4409
--- /dev/null
+++ b/src/desktop/src-tauri/gen/android/app/src/test/java/ai/alook/android/NativeBackProgressTest.kt
@@ -0,0 +1,91 @@
+package ai.alook.android
+
+import org.junit.Assert.*
+import org.junit.Test
+
+class NativeBackProgressTest {
+ @Test fun ignoresProgressWithoutStart() {
+ val bridge = NativeBackProgress()
+ assertNull(bridge.progress(0.5f))
+ assertNull(bridge.progress(null))
+ }
+
+ @Test fun clampsProgressAndRejectsNonFiniteValues() {
+ val bridge = NativeBackProgress()
+ bridge.start("\"https://alook.ai/c/me/one\"")
+ val zero = bridge.progress(-1f)!!
+ assertTrue(zero.contains("progress: 0.0"))
+ assertTrue(zero.contains("started: false"))
+ assertTrue(bridge.progress(2f)!!.contains("progress: 1.0"))
+ assertNull(bridge.progress(Float.NaN))
+ assertNull(bridge.progress(Float.POSITIVE_INFINITY))
+ assertTrue(bridge.progress(0.5f)!!.contains("progress: 0.5"))
+ }
+
+ @Test fun cancellationRetiresTheCurrentGesture() {
+ val bridge = NativeBackProgress()
+ bridge.start("\"https://alook.ai/c/me/one\"")
+ assertTrue(bridge.progress(null)!!.contains("progress: null"))
+ assertNull(bridge.progress(0.8f))
+ assertNull(bridge.progress(null))
+ }
+
+ @Test fun terminalOrActivityResetRetiresLateProgress() {
+ val bridge = NativeBackProgress()
+ bridge.start("\"https://alook.ai/c/me/one\"")
+ bridge.reset()
+ assertFalse(bridge.consumeTerminal())
+ assertNull(bridge.progress(0.8f))
+ assertNull(bridge.progress(null))
+ }
+
+ @Test fun eachStartUsesAFreshDocumentMarkerAndExactHref() {
+ val bridge = NativeBackProgress()
+ val first = bridge.start("\"https://alook.ai/c/me/one\"")
+ val oldProgress = bridge.progress(0.5f)!!
+ bridge.reset()
+ val second = bridge.start("\"https://alook.ai/c/me/two?draft=1\"")
+ val newProgress = bridge.progress(0.5f)!!
+ assertTrue(first.contains("location.href === \"https://alook.ai/c/me/one\""))
+ assertTrue(second.contains("location.href === \"https://alook.ai/c/me/two?draft=1\""))
+ assertTrue(oldProgress.contains("window.__alookNativeBackGesture === 1"))
+ assertFalse(newProgress.contains("window.__alookNativeBackGesture === 1"))
+ assertTrue(second.contains("progress: 0"))
+ assertTrue(second.contains("started: true"))
+ }
+
+ @Test fun documentOrBackgroundChangeConsumesOnlyTheOldTerminal() {
+ val bridge = NativeBackProgress()
+ bridge.invalidate()
+ assertFalse(bridge.consumeTerminal())
+ bridge.start("\"https://alook.ai/c/me/one\"")
+ bridge.invalidate()
+ bridge.invalidate()
+ assertNull(bridge.progress(0.8f))
+ assertTrue(bridge.consumeTerminal())
+ assertFalse(bridge.consumeTerminal())
+ }
+
+ @Test fun freshStartOrCancellationRetiresTheStaleTerminalFence() {
+ val bridge = NativeBackProgress()
+ bridge.start("\"https://alook.ai/c/me/one\"")
+ bridge.invalidate()
+ bridge.start("\"https://alook.ai/c/me/two\"")
+ assertFalse(bridge.consumeTerminal())
+ bridge.start("\"https://alook.ai/c/me/two\"")
+ bridge.invalidate()
+ bridge.progress(null)
+ assertFalse(bridge.consumeTerminal())
+ }
+
+ @Test fun scriptsOnlyEmitProgressAndNeverNavigateOrDispatchTerminalBack() {
+ val bridge = NativeBackProgress()
+ val scripts = listOf(bridge.start("\"http://localhost:3000/c/me\""), bridge.progress(0.4f)!!, bridge.progress(null)!!)
+ scripts.forEach {
+ assertTrue(it.contains("'alook:native-back-progress'"))
+ assertFalse(it.contains("'alook:native-back'"))
+ assertFalse(it.contains("history.back"))
+ assertFalse(it.contains("goBack"))
+ }
+ }
+}
diff --git a/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts b/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts
index 038ec3a78..fea38626a 100644
--- a/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts
+++ b/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts
@@ -242,12 +242,16 @@ vi.mock("@/components/community/channels/thread-split-parent-surface", () => ({
vi.mock("@/components/community/channels/thread-split-view", () => ({
ThreadSplitView: ({
split,
+ mobileBack = false,
+ preserveParent = false,
parent,
thread,
conversationSubtype,
resolvingParent,
}: {
split: boolean
+ mobileBack?: boolean
+ preserveParent?: boolean
parent: React.ReactNode
thread: React.ReactNode
conversationSubtype?: string
@@ -256,13 +260,14 @@ vi.mock("@/components/community/channels/thread-split-view", () => ({
"main",
{
"data-testid": conversationSubtype === "thread" ? "community-thread-split" : undefined,
+ "data-mobile-back-thread": mobileBack || undefined,
"data-layout": split ? resolvingParent ? "pending" : "split" : "full",
"data-community-conversation-subtype": conversationSubtype === "unknown" ? undefined : conversationSubtype,
},
resolvingParent && React.createElement("main", { "aria-label": "Resolving conversation", "data-community-conversation-subtype": "unknown" }),
- split && React.createElement(
+ (split || mobileBack || preserveParent) && React.createElement(
"section",
- { "data-testid": "community-thread-split-parent" },
+ { "data-testid": "community-thread-split-parent", "data-mobile-back-parent": "", inert: !split },
parent,
),
React.createElement(
@@ -803,11 +808,59 @@ describe("ChannelRoute message surface ownership", () => {
expect(mockReleaseSecondary).toHaveBeenLastCalledWith(runtime, nextOwner)
})
- it.each(["mobile", "full", "non-thread"] as const)("starts no parent resources for a ready %s target", (kind) => {
+ it("loads the verified mobile parent underlay without claiming it until access is ready", async () => {
+ await observeSecondary()
+ const { ThreadSplitParentSurface } = await vi.importActual<typeof import("./thread-split-parent-surface")>("./thread-split-parent-surface")
+ mockSplitParentSurface.mockImplementation((props) => React.createElement(ThreadSplitParentSurface, props as never))
+ configureThreadRoute()
+ mockParentMetadata.canRead = false
+ mockParentMetadata.identityKnown = false
+ mockBreakpoint.value = "mobile"
+ mockSplitMode.value = "full"
+ mockedUseChannelMessageFeed.mockReturnValue(feed())
+ const renderer = render(React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_1" }))
+ expect(mockUseChannelMetadata).toHaveBeenCalled()
+ expect(mockClaimSecondary).not.toHaveBeenCalled()
+ expect(renderer.container.querySelector("[data-mobile-back-thread]")).toBeInTheDocument()
+ const parent = renderer.container.querySelector("[data-mobile-back-parent]")
+ expect(parent).toHaveAttribute("inert")
+ mockParentMetadata.canRead = true
+ mockParentMetadata.identityKnown = true
+ renderer.rerender(React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_1" }))
+ expect(mockClaimSecondary).toHaveBeenCalledWith(expect.anything(), expect.anything(), "parent_1")
+ renderer.unmount()
+ expect(mockReleaseSecondary).toHaveBeenCalled()
+ })
+
+ it("retains the mobile parent owner through a narrow desktop round trip", async () => {
+ await observeSecondary()
+ const { ThreadSplitParentSurface } = await vi.importActual<typeof import("./thread-split-parent-surface")>("./thread-split-parent-surface")
+ mockSplitParentSurface.mockImplementation((props) => React.createElement(ThreadSplitParentSurface, props as never))
+ configureThreadRoute()
+ mockBreakpoint.value = "mobile"
+ mockSplitMode.value = "full"
+ mockedUseChannelMessageFeed.mockReturnValue(feed())
+ const node = () => React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_1" })
+ const renderer = render(node())
+ const parent = screen.getByTestId("community-thread-split-parent")
+ const [, owner] = mockClaimSecondary.mock.calls.at(-1)!
+ for (const breakpoint of ["desktop", "mobile"] as const) {
+ mockBreakpoint.value = breakpoint
+ renderer.rerender(node())
+ expect(screen.getByTestId("community-thread-split-parent")).toBe(parent)
+ expect(parent).toHaveAttribute("inert")
+ expect(mockClaimSecondary).toHaveBeenCalledOnce()
+ expect(mockClaimSecondary.mock.lastCall?.[1]).toBe(owner)
+ expect(mockReleaseSecondary).not.toHaveBeenCalled()
+ }
+ renderer.unmount()
+ expect(mockReleaseSecondary).toHaveBeenCalledOnce()
+ })
+
+ it.each(["full", "non-thread"] as const)("starts no parent resources for a ready %s target", (kind) => {
configureThreadRoute()
mockSplitMode.value = "full"
mockedUseChannelMessageFeed.mockReturnValue(feed())
- if (kind === "mobile") mockBreakpoint.value = "mobile"
if (kind === "full") mockSearchParams.value = "threadView=full"
if (kind === "non-thread") Object.assign(mockRouteModel, {
isChild: false, currentChannelMeta: null, skeletonSubtype: "text",
diff --git a/src/web/src/components/community/channels/channel-route.tsx b/src/web/src/components/community/channels/channel-route.tsx
index 6f22d01d8..60dd3aebb 100644
--- a/src/web/src/components/community/channels/channel-route.tsx
+++ b/src/web/src/components/community/channels/channel-route.tsx
@@ -91,10 +91,15 @@ function ChannelRouteFrame(target: RouteTarget) {
})
const uiHandlers = useUiHandlers()
const split = isThread && mode === "split"
- const [parentIdentity, setParentIdentity] = useAtom(useCreateAtom<{ id: string; confirmed: boolean } | null>(null))
+ const [parentIdentity, setParentIdentity] = useAtom(useCreateAtom<{ id: string; confirmed: boolean; keepMounted: boolean } | null>(null))
const onParentIdentity = useCallback((id: string, confirmed: boolean) => {
- setParentIdentity((current) => current?.id === id && current.confirmed === confirmed ? current : { id, confirmed })
- }, [setParentIdentity])
+ setParentIdentity((current) => {
+ const keepMounted = breakpoint === "mobile" || current?.id === id && current.keepMounted
+ return current?.id === id && current.confirmed === confirmed && current.keepMounted === keepMounted
+ ? current : { id, confirmed, keepMounted }
+ })
+ }, [breakpoint, setParentIdentity])
+ const preserveParent = isThread && !!parent && parentIdentity?.id === parent.id && parentIdentity.keepMounted
const resolvingParent = split && (!parent || parentIdentity?.id !== parent.id || !parentIdentity.confirmed)
const channelRefCandidates = useMemo(() => server?.categories
.flatMap((category) => category.channels)
@@ -114,8 +119,8 @@ function ChannelRouteFrame(target: RouteTarget) {
const targetHref = `${channelHref(serverParam, channelId)}${searchParams.size ? `?${searchParams}` : ""}`
return <div ref={containerRef} data-community-target-href={targetHref} className="flex min-h-0 min-w-0 flex-1 flex-col">
<ThreadSplitView
- split={split} resolvingParent={resolvingParent} conversationSubtype={isThread ? "thread" : routeModel.skeletonSubtype}
- parent={split && server && parent ? <ThreadSplitParentSurface
+ split={split} mobileBack={breakpoint === "mobile" && isThread && !!parent} preserveParent={preserveParent} resolvingParent={resolvingParent} conversationSubtype={isThread ? "thread" : routeModel.skeletonSubtype}
+ parent={(split || breakpoint === "mobile" && isThread || preserveParent) && server && parent ? <ThreadSplitParentSurface
key={JSON.stringify([currentUser.id, serverId, parent.id])}
serverId={serverId} serverParam={serverParam} server={server} channel={parent}
viewer={currentUser} onNavigateParent={navigateServerRoot}
diff --git a/src/web/src/components/community/channels/thread-split-view.dom.test.ts b/src/web/src/components/community/channels/thread-split-view.dom.test.ts
index 5321ff6f1..e58e5310a 100644
--- a/src/web/src/components/community/channels/thread-split-view.dom.test.ts
+++ b/src/web/src/components/community/channels/thread-split-view.dom.test.ts
@@ -57,6 +57,28 @@ vi.mock("@/components/ui/resizable", () => ({
}))
describe("ThreadSplitView", () => {
+ it("keeps the actual parent mounted but inert beneath a mobile thread", () => {
+ const parent = createElement("input", { "data-testid": "back-parent-draft", defaultValue: "keep me" })
+ const renderer = render(createElement(ThreadSplitView, {
+ split: false, mobileBack: true, parent, thread: createElement("span", null, "Child"),
+ }))
+ const draft = screen.getByTestId("back-parent-draft")
+ expect(draft.closest("section")).toHaveAttribute("inert")
+ expect(draft.closest("section")).toHaveAttribute("aria-hidden", "true")
+ expect(screen.getByTestId("panel-group")).toHaveAttribute("data-persists-layout", "false")
+ renderer.rerender(createElement(ThreadSplitView, {
+ split: false, preserveParent: true, parent, thread: createElement("span", null, "Child"),
+ }))
+ expect(screen.getByTestId("back-parent-draft")).toBe(draft)
+ expect(draft.closest("section")).toHaveAttribute("inert")
+ expect(draft.closest("section")).toHaveAttribute("aria-hidden", "true")
+ renderer.rerender(createElement(ThreadSplitView, {
+ split: true, parent, thread: createElement("span", null, "Child"),
+ }))
+ expect(screen.getByTestId("back-parent-draft")).toBe(draft)
+ expect(draft.closest("section")).not.toHaveAttribute("inert")
+ })
+
it("keeps parent input, scroll node and group when the keyed right child changes", () => {
const parent = createElement("div", { "data-testid": "parent-scroll" },
createElement("input", { "data-testid": "parent-draft", defaultValue: "" }))
diff --git a/src/web/src/components/community/channels/thread-split-view.tsx b/src/web/src/components/community/channels/thread-split-view.tsx
index f1556f8ac..4029ca2f5 100644
--- a/src/web/src/components/community/channels/thread-split-view.tsx
+++ b/src/web/src/components/community/channels/thread-split-view.tsx
@@ -26,12 +26,16 @@ const threadSplitLayoutStorage = {
export function ThreadSplitView({
split,
+ mobileBack = false,
+ preserveParent = false,
parent,
thread,
conversationSubtype = "thread",
resolvingParent = false,
}: {
split: boolean
+ mobileBack?: boolean
+ preserveParent?: boolean
parent: ReactNode
thread: ReactNode
conversationSubtype?: "unknown" | "text" | "forum" | "thread"
@@ -47,6 +51,7 @@ export function ThreadSplitView({
return (
<main
data-testid={isThread ? tid.threadSplit : undefined}
+ data-mobile-back-thread={mobileBack || undefined}
data-layout={split ? resolvingParent ? "pending" : "split" : "full"}
data-community-conversation-subtype={conversationSubtype === "unknown" ? undefined : conversationSubtype}
className="relative flex min-h-0 min-w-0 flex-1"
@@ -59,7 +64,7 @@ export function ThreadSplitView({
disabled={!split || resolvingParent}
aria-hidden={resolvingParent || undefined}
inert={resolvingParent || undefined}
- className={cn("min-h-0 flex-1", resolvingParent && "invisible", !split && [
+ className={cn("min-h-0 flex-1", resolvingParent && "invisible", !split && !mobileBack && [
"*:data-[layout-hidden=true]:flex-none!",
"*:data-[layout-hidden=true]:w-0!",
"*:data-[layout-hidden=true]:min-w-0!",
@@ -78,8 +83,11 @@ export function ThreadSplitView({
data-layout-hidden={!split || undefined}
className="flex min-h-0 min-w-0 flex-col"
>
- {split && <section
+ {(split || mobileBack || preserveParent) && <section
data-testid={tid.threadSplitParent}
+ data-mobile-back-parent
+ inert={!split}
+ aria-hidden={!split || undefined}
aria-label="Parent conversation"
className="flex min-h-0 min-w-0 flex-1 flex-col"
>
diff --git a/src/web/src/components/community/shell/community-shell-layout.tsx b/src/web/src/components/community/shell/community-shell-layout.tsx
index 8612c1ca9..3f2f3f4fb 100644
--- a/src/web/src/components/community/shell/community-shell-layout.tsx
+++ b/src/web/src/components/community/shell/community-shell-layout.tsx
@@ -39,6 +39,7 @@ import {
desktopUserBarOverlayWidth,
} from "./shell-frame-geometry"
import { Shell } from "./shell"
+import styles from "./mobile-back-motion.module.css"
import { useHydratedClient } from "./use-hydrated-client"
const SHELL_SURFACE_CLASS = "rounded-tl-xl rounded-tr-none rounded-br-none rounded-bl-none ring-0 border-l border-t border-border/40 shadow-none"
@@ -385,9 +386,11 @@ export function CommunityShellLayout({
data-community-route-kind={routeKind}
data-testid={testId}
data-slot="community-shell-root"
+ data-mobile-back-surface={breakpoint === "mobile" && preserveHiddenMobileModules ? surface : undefined}
+ className={styles.pages}
>
{(!isMobileDetail || preserveHiddenMobileModules) && (
- <div inert={isMobileDetail} aria-hidden={isMobileDetail || undefined} className={cn(
+ <div data-mobile-back-rail inert={isMobileDetail} aria-hidden={isMobileDetail || undefined} className={cn(
"flex min-h-0",
isInitialDetail && "hidden sm:contents",
isMobileDetail && preserveHiddenMobileModules && "hidden",
@@ -396,6 +399,7 @@ export function CommunityShellLayout({
</div>
)}
<div
+ data-mobile-back-body
className={cn(
"relative flex min-h-0 min-w-0 flex-1 flex-col",
!isMobileDetail && !isInitialDetail && "pt-2",
@@ -417,7 +421,7 @@ export function CommunityShellLayout({
disabled={!isDesktop}
className={cn(
"min-h-0 flex-1",
- !isDesktop && [
+ !isDesktop && !(isMobileDetail && preserveHiddenMobileModules) && [
"max-sm:*:data-[mobile-active=true]:flex-1!",
"max-sm:*:data-[mobile-hidden=true]:flex-none!",
"max-sm:*:data-[mobile-hidden=true]:w-0!",
@@ -449,7 +453,7 @@ export function CommunityShellLayout({
ref={sidebarPanelRef}
data-slot="community-sidebar-panel-content"
data-community-mobile-surface={isMobileList ? "list" : undefined}
- hidden={isMobileDetail}
+ hidden={isMobileDetail && !preserveHiddenMobileModules}
inert={isMobileDetail}
aria-hidden={isMobileDetail || undefined}
className={cn(
diff --git a/src/web/src/components/community/shell/mobile-back-motion.module.css b/src/web/src/components/community/shell/mobile-back-motion.module.css
new file mode 100644
index 000000000..a2c4bf3fd
--- /dev/null
+++ b/src/web/src/components/community/shell/mobile-back-motion.module.css
@@ -0,0 +1,26 @@
+@media (max-width: 639px) {
+ .pages[data-mobile-back-surface="detail"] { --mobile-back-x: 0px; --mobile-back-progress: 0; }
+ .pages[data-mobile-back-surface="detail"]:not([data-mobile-back-phase]) :is([data-mobile-back-rail], [data-panel][id="sidebar"], [data-slot="community-user-bar-overlay"], [data-mobile-back-thread] [data-panel][id="parent"]) { visibility: hidden; }
+ .pages[data-mobile-back-surface="detail"] [data-mobile-back-body] { position: static; }
+ .pages[data-mobile-back-surface="detail"] [data-slot="community-app-surface"] { overflow: visible; }
+ .pages[data-mobile-back-surface="detail"] [data-slot="resizable-panel-group"]#community-shell { position: static; }
+ .pages[data-mobile-back-surface="detail"] [data-mobile-back-rail] { display: flex; position: absolute; inset: 0 auto 0 0; z-index: 1; padding-bottom: calc(60px + var(--app-safe-area-bottom)); background: var(--app-bg); }
+ .pages[data-mobile-back-surface="detail"] [data-panel][id="sidebar"] { position: absolute; inset: 8px 0 0 56px; width: calc(100% - 56px) !important; min-width: 0 !important; max-width: none !important; padding-bottom: calc(60px + var(--app-safe-area-bottom)); border-top: 1px solid var(--border); border-left: 1px solid var(--border); border-top-left-radius: 12px; overflow: hidden; }
+ .pages[data-mobile-back-surface="detail"] [data-slot="community-sidebar-panel-content"] { display: flex; }
+ .pages[data-mobile-back-surface="detail"] [data-slot="community-user-bar-overlay"] { display: block; width: 100% !important; margin-left: 0 !important; }
+ .pages[data-mobile-back-surface="detail"] [data-panel][id="main"] { position: absolute; inset: 0; width: 100% !important; min-width: 0 !important; max-width: none !important; z-index: 20; }
+ .pages[data-mobile-back-surface="detail"]:not(:has([data-mobile-back-thread])) [data-panel][id="main"],
+ .pages [data-mobile-back-thread] [data-panel][id="thread"] { transform: translate3d(var(--mobile-back-x), 0, 0); }
+ .pages[data-mobile-back-surface="detail"]:not(:has([data-mobile-back-thread])) :is([data-mobile-back-rail], [data-panel][id="sidebar"], [data-slot="community-user-bar-overlay"]),
+ .pages [data-mobile-back-thread] [data-panel][id="parent"] { transform: translate3d(calc((var(--mobile-back-x) - 100vw) * 0.25), 0, 0); opacity: calc(0.85 + var(--mobile-back-progress) * 0.15); }
+ .pages [data-mobile-back-thread] { overflow: hidden; }
+ .pages [data-mobile-back-thread] [data-panel][id="parent"],
+ .pages [data-mobile-back-thread] [data-panel][id="thread"] { position: absolute; inset: 0; width: 100% !important; min-width: 0 !important; max-width: none !important; }
+ .pages [data-mobile-back-thread] [data-panel][id="thread"] { z-index: 1; }
+ .pages[data-mobile-back-phase] :is([data-panel][id="main"], [data-mobile-back-thread] [data-panel][id="thread"]) { box-shadow: -8px 0 24px color-mix(in srgb, var(--foreground) 12%, transparent); }
+ .pages[data-mobile-back-phase="settling"] :is([data-mobile-back-rail], [data-panel], [data-slot="community-user-bar-overlay"]) { transition: transform 200ms cubic-bezier(0.16, 1, 0.3, 1), opacity 200ms ease-out; }
+ .pages[data-mobile-back-phase="dragging"] :is([data-mobile-back-rail], [data-panel], [data-slot="community-user-bar-overlay"]) { will-change: transform; }
+}
+@media (prefers-reduced-motion: reduce) {
+ .pages[data-mobile-back-phase] :is([data-mobile-back-rail], [data-panel], [data-slot="community-user-bar-overlay"]) { transform: none !important; transition: none !important; }
+}
diff --git a/src/web/src/components/community/shell/shell-frame-view.dom.test.ts b/src/web/src/components/community/shell/shell-frame-view.dom.test.ts
index 2a88fa130..3ea6d5104 100644
--- a/src/web/src/components/community/shell/shell-frame-view.dom.test.ts
+++ b/src/web/src/components/community/shell/shell-frame-view.dom.test.ts
@@ -755,9 +755,14 @@ describe("ShellFrameView", () => {
const detailMotion = renderer.container.querySelector('[data-community-mobile-surface="detail"]')!
expect(detailMotion.className).toContain("flex")
expect(detailMotion).not.toHaveAttribute("hidden")
- expect(renderer.container.querySelector(
+ const detailSidebar = renderer.container.querySelector(
'[data-slot="community-sidebar-panel-content"]',
- )).toHaveAttribute("hidden")
+ )!
+ expect(detailSidebar).not.toHaveAttribute("hidden")
+ expect(detailSidebar).toHaveAttribute("inert")
+ expect(detailSidebar).toHaveAttribute("aria-hidden", "true")
+ expect(renderer.container.querySelector('[data-mobile-back-surface="detail"]'))
+ .not.toHaveAttribute("data-mobile-back-phase")
})
it.each([false, true])("keeps every mobile route commit stationary when reduced motion is %s", async (reducedMotion) => {
diff --git a/src/web/src/components/community/shell/shell-frame.tsx b/src/web/src/components/community/shell/shell-frame.tsx
index 2b789d510..891ae157c 100644
--- a/src/web/src/components/community/shell/shell-frame.tsx
+++ b/src/web/src/components/community/shell/shell-frame.tsx
@@ -316,7 +316,8 @@ const [committedFrame, setCommittedFrame] = useAtom(useCreateAtom(initialCommitt
useNativeMobileBack({
mobile: breakpoint === "mobile",
- gestureKey: committedFrame.href,
+ animate: !navigation.navigationPending && userBarExtension.active === "none",
+ gestureKey: JSON.stringify([currentUser.id, committedFrame.href]),
dismissShellOverlay: dismissNativeBackShellOverlay,
parentPath: mobileParentPath,
replacePath,
diff --git a/src/web/src/components/ui/native-back-layer.tsx b/src/web/src/components/ui/native-back-layer.tsx
index faeca7d08..56a63fd5b 100644
--- a/src/web/src/components/ui/native-back-layer.tsx
+++ b/src/web/src/components/ui/native-back-layer.tsx
@@ -13,6 +13,7 @@ type Registration = {
phase: "open" | "closing"
order: number
request: () => BackResult
+ eligible: () => boolean
}
const NativeBackContext = React.createContext<BackOwner | null>(null)
@@ -20,21 +21,29 @@ const owners = new WeakMap<Document, Set<Registration>>()
const registrations = new WeakMap<BackOwner, Registration>()
let order = 0
+export const NATIVE_BACK_OWNER_CHANGE_EVENT = "alook:native-back-owner-change"
+
+function changed(document: Document) {
+ document.dispatchEvent(new Event(NATIVE_BACK_OWNER_CHANGE_EVENT))
+}
+
function release(owner: BackOwner, element?: HTMLElement) {
const current = registrations.get(owner)
if (!current || (element && current.element !== element)) return
owners.get(current.element.ownerDocument)?.delete(current)
registrations.delete(owner)
+ changed(current.element.ownerDocument)
}
-function activate(owner: BackOwner, element: HTMLElement, request: () => BackResult) {
+function activate(owner: BackOwner, element: HTMLElement, request: () => BackResult, eligible = () => true) {
const current = registrations.get(owner)
if (current?.element === element && current.phase === "open") {
current.request = request
+ current.eligible = eligible
return
}
release(owner)
- const registration: Registration = { owner, element, phase: "open", order: ++order, request }
+ const registration: Registration = { owner, element, phase: "open", order: ++order, request, eligible }
registrations.set(owner, registration)
let active = owners.get(element.ownerDocument)
if (!active) {
@@ -42,6 +51,7 @@ function activate(owner: BackOwner, element: HTMLElement, request: () => BackRes
owners.set(element.ownerDocument, active)
}
active.add(registration)
+ changed(element.ownerDocument)
}
function startClosing(owner: BackOwner, element: HTMLElement) {
@@ -58,6 +68,7 @@ function startClosing(owner: BackOwner, element: HTMLElement) {
}
current.element = element
current.phase = "closing"
+ changed(element.ownerDocument)
}
function isDescendant(owner: BackOwner, parent: BackOwner) {
@@ -67,12 +78,10 @@ function isDescendant(owner: BackOwner, parent: BackOwner) {
return false
}
-export function requestNativeBack(document: Document): BackResult {
- const active = Array.from(owners.get(document) ?? []).filter((current) => {
- if (current.element.isConnected) return true
- release(current.owner)
- return false
- })
+function topNativeBackOwner(document: Document) {
+ const active = Array.from(owners.get(document) ?? []).filter((current) => (
+ current.element.isConnected && current.eligible()
+ ))
let top: Registration | null = null
let topOrder = -1
for (const current of active) {
@@ -86,6 +95,15 @@ export function requestNativeBack(document: Document): BackResult {
topOrder = branchOrder
}
}
+ return top
+}
+
+export function hasNativeBackOwner(document: Document): boolean {
+ return topNativeBackOwner(document) !== null
+}
+
+export function requestNativeBack(document: Document): BackResult {
+ const top = topNativeBackOwner(document)
if (!top) return "none"
if (top.phase === "closing") return "blocked"
const result = top.request()
@@ -153,7 +171,7 @@ export function useNativeBackOwner(getElement: () => HTMLElement | null, request
release(owner)
return
}
- activate(owner, element, request)
+ activate(owner, element, request, () => getElement() === element)
}, [getElement, owner, request])
React.useLayoutEffect(() => { refresh() })
return refresh
diff --git a/src/web/src/hooks/community/use-native-mobile-back-motion-owners.dom.test.tsx b/src/web/src/hooks/community/use-native-mobile-back-motion-owners.dom.test.tsx
new file mode 100644
index 000000000..53d3f6078
--- /dev/null
+++ b/src/web/src/hooks/community/use-native-mobile-back-motion-owners.dom.test.tsx
@@ -0,0 +1,162 @@
+import { useRef } from "react"
+import { afterEach, describe, expect, it, vi } from "vitest"
+import { act, render } from "@/test/react-dom-harness"
+import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog"
+import { hasNativeBackOwner, useNativeBackOwner } from "@/components/ui/native-back-layer"
+import { NATIVE_MOBILE_BACK_EVENT, NATIVE_MOBILE_BACK_PROGRESS_EVENT, useNativeMobileBack } from "./use-native-mobile-back"
+
+function Owner({ eligible, request }: { eligible: boolean; request: () => "blocked" }) {
+ const ref = useRef<HTMLDivElement>(null)
+ useNativeBackOwner(() => eligible ? ref.current : null, request)
+ return <div ref={ref} />
+}
+
+function Fixture({ owner = false, editor = false, scope = "alice/detail", replace, close, request }: {
+ owner?: boolean
+ editor?: boolean
+ scope?: string
+ replace: (path: string) => void
+ close: () => void
+ request: () => "blocked"
+}) {
+ useNativeMobileBack({ mobile: true, gestureKey: scope, parentPath: "/c/me", replacePath: replace, dismissShellOverlay: () => false })
+ return <><Owner eligible={editor} request={request} />{owner && <Dialog open onOpenChange={close}>
+ <DialogContent><DialogTitle>Settings</DialogTitle><DialogDescription>Owned popup</DialogDescription></DialogContent>
+ </Dialog>}</>
+}
+
+function touch(type: string, x: number) {
+ const points = [{ identifier: 1, clientX: x, clientY: 100 }]
+ const event = new Event(type, { bubbles: true, cancelable: true })
+ Object.defineProperties(event, { touches: { value: type === "touchend" ? [] : points }, changedTouches: { value: points } })
+ act(() => { document.dispatchEvent(event) })
+}
+function progress(value: number | null, started = value === 0) {
+ act(() => { window.dispatchEvent(new CustomEvent(NATIVE_MOBILE_BACK_PROGRESS_EVENT, { detail: { progress: value, started } })) })
+}
+function back() {
+ act(() => { window.dispatchEvent(new Event(NATIVE_MOBILE_BACK_EVENT, { cancelable: true })) })
+}
+
+const roots: HTMLElement[] = []
+function setup() {
+ vi.useFakeTimers()
+ const root = document.createElement("div")
+ root.dataset.mobileBackSurface = "detail"
+ Object.defineProperty(root, "clientWidth", { value: 390 })
+ document.body.appendChild(root)
+ roots.push(root)
+ const props = { replace: vi.fn(), close: vi.fn(), request: vi.fn(() => "blocked" as const) }
+ const view = render(<Fixture {...props} />)
+ return { root, props, view }
+}
+
+afterEach(() => { roots.splice(0).forEach((root) => root.remove()); vi.useRealTimers() })
+
+describe("shared Back ownership during page motion", () => {
+ it.each(["account", "resize", "pagehide"])("ignores old zero progress after %s invalidates the gesture", (reason) => {
+ const { root, props, view } = setup()
+ progress(0); progress(0.6)
+ expect(root.dataset.mobileBackPhase).toBe("dragging")
+ if (reason === "account") view.rerender(<Fixture {...props} scope="bob/detail" />)
+ else act(() => { window.dispatchEvent(new Event(reason)) })
+ progress(0, false); progress(0.7)
+ expect(root.hasAttribute("data-mobile-back-phase")).toBe(false)
+ back()
+ act(() => { vi.advanceTimersByTime(300) })
+ expect(props.replace).not.toHaveBeenCalled()
+ progress(0); progress(0.7); back()
+ act(() => { vi.advanceTimersByTime(300) })
+ expect(props.replace).toHaveBeenCalledOnce()
+ view.unmount()
+ })
+
+ it.each(["popup", "editor"])("reads %s ownership during progress without requesting dismissal", (kind) => {
+ const { root, props, view } = setup()
+ view.rerender(<Fixture {...props} owner={kind === "popup"} editor={kind === "editor"} />)
+ expect(hasNativeBackOwner(document)).toBe(true)
+ progress(0); progress(0.7)
+ expect(root.hasAttribute("data-mobile-back-phase")).toBe(false)
+ expect(props.close).not.toHaveBeenCalled()
+ expect(props.request).not.toHaveBeenCalled()
+ back()
+ expect(kind === "popup" ? props.close : props.request).toHaveBeenCalledOnce()
+ expect(props.replace).not.toHaveBeenCalled()
+ view.unmount()
+ })
+
+ it.each(["touch", "native"])("keeps the current popup's terminal Back after interrupting %s movement", (kind) => {
+ const { root, props, view } = setup()
+ if (kind === "touch") { touch("touchstart", 10); touch("touchmove", 200) }
+ else { progress(0); progress(0.5) }
+ expect(root.dataset.mobileBackPhase).toBe("dragging")
+ view.rerender(<Fixture {...props} owner />)
+ expect(root.hasAttribute("data-mobile-back-phase")).toBe(false)
+ expect(props.close).not.toHaveBeenCalled()
+ if (kind === "touch") touch("touchend", 200)
+ else back()
+ act(() => { vi.advanceTimersByTime(300) })
+ expect(props.close).toHaveBeenCalledOnce()
+ expect(props.replace).not.toHaveBeenCalled()
+ view.unmount()
+ })
+
+ it.each(["touch", "native", "settling"])("never revives %s page commit after a transient owner exits", (kind) => {
+ const { root, props, view } = setup()
+ if (kind === "native") { progress(0); progress(0.5) }
+ else { touch("touchstart", 10); touch("touchmove", 200) }
+ if (kind === "settling") touch("touchend", 200)
+ view.rerender(<Fixture {...props} editor />)
+ view.rerender(<Fixture {...props} />)
+ expect(hasNativeBackOwner(document)).toBe(false)
+ if (kind === "touch") touch("touchend", 200)
+ if (kind === "native") back()
+ act(() => { vi.advanceTimersByTime(300) })
+ expect(props.request).not.toHaveBeenCalled()
+ expect(props.replace).not.toHaveBeenCalled()
+ expect(root.hasAttribute("data-mobile-back-phase")).toBe(false)
+ back()
+ act(() => { vi.advanceTimersByTime(200) })
+ expect(props.replace).toHaveBeenCalledExactlyOnceWith("/c/me")
+ view.unmount()
+ })
+
+ it("does not use the settling timer to close a new real popup", () => {
+ const { props, view } = setup()
+ touch("touchstart", 10); touch("touchmove", 200); touch("touchend", 200)
+ view.rerender(<Fixture {...props} owner />)
+ act(() => { vi.advanceTimersByTime(300) })
+ expect(props.close).not.toHaveBeenCalled()
+ expect(props.replace).not.toHaveBeenCalled()
+ back()
+ expect(props.close).toHaveBeenCalledOnce()
+ view.unmount()
+ })
+
+ it("consumes the old account's terminal before the new scope's popup", () => {
+ const { props, view } = setup()
+ progress(0); progress(0.6)
+ view.rerender(<Fixture {...props} scope="bob/detail" owner />)
+ progress(0.8); back()
+ expect(props.close).not.toHaveBeenCalled()
+ expect(props.replace).not.toHaveBeenCalled()
+ back()
+ expect(props.close).toHaveBeenCalledOnce()
+ view.unmount()
+ })
+
+ it("retires pagehide's settle and ignores old progress after BFCache return", () => {
+ const { root, props, view } = setup()
+ progress(0); progress(0.6)
+ act(() => { window.dispatchEvent(new PageTransitionEvent("pagehide", { persisted: true })) })
+ act(() => { window.dispatchEvent(new PageTransitionEvent("pageshow", { persisted: true })) })
+ progress(0.9); back()
+ act(() => { vi.advanceTimersByTime(300) })
+ expect(props.replace).not.toHaveBeenCalled()
+ expect(root.hasAttribute("data-mobile-back-phase")).toBe(false)
+ progress(0); progress(0.6); back()
+ act(() => { vi.advanceTimersByTime(200) })
+ expect(props.replace).toHaveBeenCalledExactlyOnceWith("/c/me")
+ view.unmount()
+ })
+})
diff --git a/src/web/src/hooks/community/use-native-mobile-back.dom.test.ts b/src/web/src/hooks/community/use-native-mobile-back.dom.test.ts
index d9ad044fc..decaaccd0 100644
--- a/src/web/src/hooks/community/use-native-mobile-back.dom.test.ts
+++ b/src/web/src/hooks/community/use-native-mobile-back.dom.test.ts
@@ -4,6 +4,7 @@ import { act, render, screen, waitFor } from "@/test/react-dom-harness"
import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog"
import {
NATIVE_MOBILE_BACK_EVENT,
+ NATIVE_MOBILE_BACK_PROGRESS_EVENT,
useNativeMobileBack,
} from "./use-native-mobile-back"
@@ -372,3 +373,161 @@ describe("mobile edge parent gesture", () => {
renderer.unmount()
})
})
+
+describe("layered mobile back motion", () => {
+ const roots: HTMLElement[] = []
+ function mounted() {
+ const root = document.createElement("div")
+ root.dataset.mobileBackSurface = "detail"
+ Object.defineProperty(root, "clientWidth", { value: 390 })
+ document.body.append(root)
+ roots.push(root)
+ return { ...mobileHarness(), root }
+ }
+ afterEach(() => {
+ roots.splice(0).forEach((root) => root.remove())
+ vi.useRealTimers()
+ vi.unstubAllGlobals()
+ })
+
+ it("tracks the finger, then completes once after the foreground settles", () => {
+ vi.useFakeTimers()
+ const { root, props, renderer } = mounted()
+ touch("touchstart", 10)
+ touch("touchmove", 180)
+ expect(root.style.getPropertyValue("--mobile-back-x")).toBe("170px")
+ expect(root.dataset.mobileBackPhase).toBe("dragging")
+ expect(props.replacePath).not.toHaveBeenCalled()
+ touch("touchend", 180)
+ expect(root.style.getPropertyValue("--mobile-back-x")).toBe("390px")
+ expect(root.dataset.mobileBackPhase).toBe("settling")
+ touch("touchstart", 10)
+ touch("touchend", 180)
+ vi.advanceTimersByTime(199)
+ expect(props.replacePath).not.toHaveBeenCalled()
+ vi.advanceTimersByTime(1)
+ expect(props.replacePath).toHaveBeenCalledExactlyOnceWith("/c/channels/s1")
+ expect(root.dataset.mobileBackPhase).toBe("committing")
+ renderer.unmount()
+ expect(root.style.getPropertyValue("--mobile-back-x")).toBe("")
+ })
+
+ it("keeps settling across callback changes on the same committed route", () => {
+ vi.useFakeTimers()
+ const { props, renderer } = mounted()
+ touch("touchstart", 10)
+ touch("touchmove", 200)
+ touch("touchend", 200)
+ const replacePath = vi.fn()
+ renderer.rerender(createElement(Harness, { ...props, replacePath, dismissShellOverlay: () => false }))
+ vi.advanceTimersByTime(200)
+ expect(props.replacePath).not.toHaveBeenCalled()
+ expect(replacePath).toHaveBeenCalledExactlyOnceWith("/c/channels/s1")
+ renderer.unmount()
+ })
+
+ it("tracks native system progress, cancels, then commits once through the shared settle", () => {
+ vi.useFakeTimers()
+ const { root, props, renderer } = mounted()
+ const progress = (value: number | null) => window.dispatchEvent(new CustomEvent(NATIVE_MOBILE_BACK_PROGRESS_EVENT, { detail: { progress: value, started: value === 0 } }))
+ progress(0)
+ progress(0.5)
+ expect(root.style.getPropertyValue("--mobile-back-x")).toBe("195px")
+ expect(props.replacePath).not.toHaveBeenCalled()
+ progress(null)
+ vi.advanceTimersByTime(200)
+ expect(root.hasAttribute("data-mobile-back-phase")).toBe(false)
+ expect(props.replacePath).not.toHaveBeenCalled()
+ progress(0)
+ progress(0.75)
+ dispatchBack()
+ dispatchBack()
+ vi.advanceTimersByTime(199)
+ expect(props.replacePath).not.toHaveBeenCalled()
+ vi.advanceTimersByTime(1)
+ expect(props.replacePath).toHaveBeenCalledExactlyOnceWith("/c/channels/s1")
+ renderer.unmount()
+ progress(0.5)
+ expect(root.hasAttribute("data-mobile-back-phase")).toBe(false)
+ })
+
+ it.each(["route", "resize", "background"])("ignores a late native commit after %s interrupts its gesture", (reason) => {
+ vi.useFakeTimers()
+ const { props, renderer } = mounted()
+ const progress = (value: number) => window.dispatchEvent(new CustomEvent(NATIVE_MOBILE_BACK_PROGRESS_EVENT, { detail: { progress: value, started: value === 0 } }))
+ progress(0)
+ progress(0.5)
+ if (reason === "route") renderer.rerender(createElement(Harness, { ...props, gestureKey: "new-route" }))
+ if (reason === "resize") window.dispatchEvent(new Event("resize"))
+ if (reason === "background") document.dispatchEvent(new Event("visibilitychange"))
+ progress(0.75)
+ dispatchBack()
+ vi.advanceTimersByTime(300)
+ expect(props.replacePath).not.toHaveBeenCalled()
+ dispatchBack()
+ vi.advanceTimersByTime(200)
+ expect(props.replacePath).toHaveBeenCalledOnce()
+ renderer.unmount()
+ })
+
+ it("returns a short held drag to the same page without navigating", () => {
+ vi.useFakeTimers()
+ const { root, props, renderer } = mounted()
+ touch("touchstart", 10)
+ touch("touchmove", 70)
+ vi.advanceTimersByTime(150)
+ touch("touchend", 70)
+ expect(root.style.getPropertyValue("--mobile-back-x")).toBe("0px")
+ vi.advanceTimersByTime(200)
+ expect(root.hasAttribute("data-mobile-back-phase")).toBe(false)
+ expect(props.replacePath).not.toHaveBeenCalled()
+ renderer.unmount()
+ })
+
+ it.each(["touchcancel", "route", "resize", "background", "unmount"])("cancels queued navigation on %s", (reason) => {
+ vi.useFakeTimers()
+ const { root, props, renderer } = mounted()
+ touch("touchstart", 10)
+ touch("touchmove", 200)
+ if (reason === "touchcancel") touch("touchcancel", 200)
+ else {
+ touch("touchend", 200)
+ if (reason === "route") renderer.rerender(createElement(Harness, { ...props, gestureKey: "new-route" }))
+ if (reason === "resize") window.dispatchEvent(new Event("resize"))
+ if (reason === "background") document.dispatchEvent(new Event("visibilitychange"))
+ if (reason === "unmount") renderer.unmount()
+ }
+ vi.advanceTimersByTime(300)
+ expect(props.replacePath).not.toHaveBeenCalled()
+ expect(root.hasAttribute("data-mobile-back-phase")).toBe(false)
+ if (reason !== "unmount") renderer.unmount()
+ })
+
+ it("keeps reduced motion navigation immediate with no spatial settle", () => {
+ vi.useFakeTimers()
+ vi.stubGlobal("matchMedia", () => ({ matches: true }))
+ const { root, props, renderer } = mounted()
+ touch("touchstart", 10)
+ touch("touchmove", 200)
+ touch("touchend", 200)
+ expect(root.hasAttribute("data-mobile-back-phase")).toBe(false)
+ expect(props.replacePath).toHaveBeenCalledExactlyOnceWith("/c/channels/s1")
+ vi.advanceTimersByTime(300)
+ expect(props.replacePath).toHaveBeenCalledOnce()
+ renderer.unmount()
+ })
+
+ it("dismisses an overlay without committing the moving page", () => {
+ vi.useFakeTimers()
+ const { root, props, renderer } = mounted()
+ props.dismissShellOverlay.mockReturnValue(true)
+ touch("touchstart", 10)
+ touch("touchmove", 200)
+ touch("touchend", 200)
+ vi.advanceTimersByTime(200)
+ expect(props.dismissShellOverlay).toHaveBeenCalledOnce()
+ expect(props.replacePath).not.toHaveBeenCalled()
+ expect(root.hasAttribute("data-mobile-back-phase")).toBe(false)
+ renderer.unmount()
+ })
+})
diff --git a/src/web/src/hooks/community/use-native-mobile-back.ts b/src/web/src/hooks/community/use-native-mobile-back.ts
index c222681ea..e3d60386f 100644
--- a/src/web/src/hooks/community/use-native-mobile-back.ts
+++ b/src/web/src/hooks/community/use-native-mobile-back.ts
@@ -1,10 +1,10 @@
-import { useEffect, useRef } from "react"
+import { useEffect, useLayoutEffect, useRef } from "react"
import { isMobile } from "@alook/shared"
-import { requestNativeBack } from "@/components/ui/native-back-layer"
+import { hasNativeBackOwner, NATIVE_BACK_OWNER_CHANGE_EVENT, requestNativeBack } from "@/components/ui/native-back-layer"
export const MOBILE_BACK_EDGE_PX = 24
-
export const NATIVE_MOBILE_BACK_EVENT = "alook:native-back"
+export const NATIVE_MOBILE_BACK_PROGRESS_EVENT = "alook:native-back-progress"
type NativeBackListener = { unregister: () => Promise<void> }
type TauriBackWindow = Window & {
@@ -14,19 +14,23 @@ type TauriBackWindow = Window & {
}
export function useNativeMobileBack({
- mobile = false,
- gestureKey,
- dismissShellOverlay,
- parentPath,
- replacePath,
+ mobile = false, gestureKey, dismissShellOverlay, parentPath, replacePath, animate = true,
}: {
mobile?: boolean
gestureKey?: string
dismissShellOverlay: () => boolean
parentPath: string | null
replacePath: (href: string) => void
+ animate?: boolean
}) {
+ const actions = useRef({ dismissShellOverlay, replacePath, animate })
+ const nativeGesture = useRef<"active" | "stale" | null>(null)
const composing = useRef<EventTarget | null>(null)
+ const interruptMotion = useRef<() => void>(() => {})
+ useLayoutEffect(() => {
+ actions.current = { dismissShellOverlay, replacePath, animate }
+ if (!animate) interruptMotion.current()
+ }, [dismissShellOverlay, replacePath, animate])
useEffect(() => {
if (!isMobile() || !/android/i.test(navigator.userAgent)) return
const app = (window as TauriBackWindow).__TAURI__?.app
@@ -76,23 +80,115 @@ export function useNativeMobileBack({
document.removeEventListener("focusout", end)
}
}, [])
- useEffect(() => {
+ useLayoutEffect(() => {
+ let root: HTMLElement | null = null
+ let pageBlocked = false
+ let nativeProgress = false
+ let timer: ReturnType<typeof setTimeout> | undefined
+ let gesture: { id: number; x: number; y: number; horizontal: boolean; lastX: number; at: number; velocity: number } | null = null
+ const reduced = () => window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false
+ const occupied = () => composing.current === document.activeElement || hasNativeBackOwner(document)
+ const clearMotion = () => {
+ clearTimeout(timer)
+ timer = undefined
+ root?.style.removeProperty("--mobile-back-x")
+ root?.style.removeProperty("--mobile-back-progress")
+ root?.removeAttribute("data-mobile-back-phase")
+ root = null
+ }
+ const reset = () => {
+ gesture = null
+ nativeProgress = false
+ clearMotion()
+ }
+ const interrupt = () => {
+ if (gesture || nativeProgress || root) pageBlocked = true
+ clearMotion()
+ }
+ interruptMotion.current = interrupt
+ const ownerChanged = () => { if (occupied()) interrupt() }
+ const invalidate = () => {
+ if (nativeGesture.current === "active") nativeGesture.current = "stale"
+ pageBlocked = true
+ reset()
+ }
+ const findRoot = () => actions.current.animate && parentPath && !occupied()
+ ? document.querySelector<HTMLElement>('[data-mobile-back-surface="detail"]') : null
+ const settle = (commit: boolean) => {
+ gesture = null
+ nativeProgress = false
+ if (commit && (pageBlocked || occupied())) { reset(); return }
+ if (!root || reduced()) {
+ reset()
+ if (commit && parentPath) actions.current.replacePath(parentPath)
+ return
+ }
+ root.dataset.mobileBackPhase = "settling"
+ root.style.setProperty("--mobile-back-x", commit ? `${root.clientWidth}px` : "0px")
+ root.style.setProperty("--mobile-back-progress", commit ? "1" : "0")
+ timer = setTimeout(() => {
+ timer = undefined
+ if (commit && parentPath && !pageBlocked && !occupied() && actions.current.animate) {
+ root?.setAttribute("data-mobile-back-phase", "committing")
+ actions.current.replacePath(parentPath)
+ } else reset()
+ }, 200)
+ }
+ const paint = (x: number) => {
+ if (occupied() || !actions.current.animate) interrupt()
+ if (!root || pageBlocked) return
+ root.dataset.mobileBackPhase = "dragging"
+ root.style.setProperty("--mobile-back-x", `${x}px`)
+ root.style.setProperty("--mobile-back-progress", `${x / Math.max(1, root.clientWidth)}`)
+ }
const handleBack = (event: Event) => {
if (!event.cancelable) return
event.preventDefault()
- if (composing.current === document.activeElement) return
- if (requestNativeBack(document) !== "none" || dismissShellOverlay()) return
- if (parentPath) replacePath(parentPath)
+ const stale = nativeGesture.current === "stale"
+ nativeGesture.current = null
+ if (stale) { pageBlocked = false; return reset() }
+ if (timer !== undefined || root?.dataset.mobileBackPhase === "committing") return
+ const blocked = (gesture !== null || nativeProgress) && pageBlocked
+ pageBlocked = false
+ if (composing.current === document.activeElement) return reset()
+ if (requestNativeBack(document) !== "none" || actions.current.dismissShellOverlay()) return reset()
+ if (blocked) return reset()
+ if (mobile) root ??= findRoot()
+ settle(Boolean(parentPath))
+ }
+ const progress = (event: Event) => {
+ const detail = (event as CustomEvent<{ progress: number | null; started?: boolean }>).detail
+ const value = detail?.progress
+ if (value === null) {
+ nativeGesture.current = null
+ if (nativeProgress) settle(false)
+ return
+ }
+ if (!Number.isFinite(value) || timer !== undefined || root?.dataset.mobileBackPhase === "committing") return
+ if (!nativeProgress) {
+ if (value !== 0 || detail?.started !== true) return
+ reset()
+ nativeGesture.current = "active"
+ nativeProgress = true
+ pageBlocked = occupied() || !actions.current.animate
+ if (!pageBlocked) root = findRoot()
+ }
+ if (root) paint(Math.max(0, Math.min(1, value!)) * root.clientWidth)
+ }
+ const cancel = () => {
+ if (gesture?.horizontal && root) settle(false)
+ else reset()
}
-
- let gesture: { id: number; x: number; y: number; horizontal: boolean } | null = null
- const cancel = () => { gesture = null }
const start = (event: TouchEvent) => {
- cancel()
- if (event.touches.length !== 1) return
+ if (timer !== undefined || root?.dataset.mobileBackPhase === "committing") return
+ reset()
+ if (event.touches.length !== 1 || event.defaultPrevented) return
const touch = event.touches[0]
if (touch.clientX < 0 || touch.clientX > MOBILE_BACK_EDGE_PX) return
- gesture = { id: touch.identifier, x: touch.clientX, y: touch.clientY, horizontal: false }
+ pageBlocked = occupied() || !actions.current.animate
+ gesture = { id: touch.identifier, x: touch.clientX, y: touch.clientY, horizontal: false,
+ lastX: touch.clientX, at: performance.now(), velocity: 0 }
+ if (!pageBlocked) root = findRoot()
}
const move = (event: TouchEvent) => {
if (!gesture) return
@@ -105,31 +201,55 @@ export function useNativeMobileBack({
if (dx <= dy) return cancel()
gesture.horizontal = true
}
- if (gesture.horizontal) event.preventDefault()
+ if (!gesture.horizontal) return
+ event.preventDefault()
+ const now = performance.now()
+ gesture.velocity = (touch.clientX - gesture.lastX) / Math.max(1, now - gesture.at)
+ gesture.lastX = touch.clientX
+ gesture.at = now
+ paint(Math.max(0, Math.min(root?.clientWidth ?? 0, dx)))
}
const end = (event: TouchEvent) => {
const current = gesture
- cancel()
- if (!current?.horizontal || event.touches.length !== 0) return
+ if (!current) return
+ if (!current.horizontal || event.touches.length !== 0) return cancel()
const touch = Array.from(event.changedTouches).find((item) => item.identifier === current.id)
- if (!touch) return
- event.preventDefault()
- if (touch.clientX - current.x < 64 || Math.abs(touch.clientY - current.y) >= touch.clientX - current.x) return
- handleBack(event)
+ if (!touch) return cancel()
+ const dx = touch.clientX - current.x
+ const horizontal = Math.abs(touch.clientY - current.y) < dx
+ const commit = horizontal && (root
+ ? dx >= root.clientWidth * 0.35 || dx >= 32 && current.velocity > 0.5 && performance.now() - current.at < 100
+ : dx >= 64)
+ if (commit) handleBack(event)
+ else { event.preventDefault(); settle(false) }
}
window.addEventListener(NATIVE_MOBILE_BACK_EVENT, handleBack)
+ document.addEventListener(NATIVE_BACK_OWNER_CHANGE_EVENT, ownerChanged)
+ document.addEventListener("compositionstart", interrupt)
+ window.addEventListener("pagehide", invalidate)
if (mobile) {
+ window.addEventListener(NATIVE_MOBILE_BACK_PROGRESS_EVENT, progress)
document.addEventListener("touchstart", start, { passive: true, capture: true })
document.addEventListener("touchmove", move, { passive: false, capture: true })
document.addEventListener("touchend", end, { passive: false, capture: true })
document.addEventListener("touchcancel", cancel, true)
+ document.addEventListener("visibilitychange", invalidate)
+ window.addEventListener("resize", invalidate)
}
return () => {
+ invalidate()
+ interruptMotion.current = () => {}
window.removeEventListener(NATIVE_MOBILE_BACK_EVENT, handleBack)
+ document.removeEventListener(NATIVE_BACK_OWNER_CHANGE_EVENT, ownerChanged)
+ document.removeEventListener("compositionstart", interrupt)
+ window.removeEventListener("pagehide", invalidate)
+ window.removeEventListener(NATIVE_MOBILE_BACK_PROGRESS_EVENT, progress)
document.removeEventListener("touchstart", start, true)
document.removeEventListener("touchmove", move, true)
document.removeEventListener("touchend", end, true)
document.removeEventListener("touchcancel", cancel, true)
+ document.removeEventListener("visibilitychange", invalidate)
+ window.removeEventListener("resize", invalidate)
}
- }, [mobile, gestureKey, dismissShellOverlay, parentPath, replacePath])
+ }, [mobile, gestureKey, parentPath])
}
diff --git a/src/web/src/hooks/community/use-read-observer.dom.test.ts b/src/web/src/hooks/community/use-read-observer.dom.test.ts
index 90da4144f..d03754f3f 100644
--- a/src/web/src/hooks/community/use-read-observer.dom.test.ts
+++ b/src/web/src/hooks/community/use-read-observer.dom.test.ts
@@ -442,6 +442,31 @@ describe("useTimelineReadObserver", () => {
expect(coordinator.submit).toHaveBeenCalledOnce()
})
+ it("keeps the mounted mobile parent silent until its inert layer becomes active", () => {
+ const row = makeRow("message-4")
+ const root = makeRoot([row])
+ const parent = document.createElement("section")
+ parent.setAttribute("data-mobile-back-parent", "")
+ parent.setAttribute("inert", "")
+ parent.append(root)
+ useTestRender({ scrollRootEl: root })
+ takeUnmounts()
+ trigger(observers[0]!, row)
+ for (const listener of pageShowListeners) listener()
+ expect(coordinator.submit).not.toHaveBeenCalled()
+ expect(projection.recordOptimisticRead).not.toHaveBeenCalled()
+ expect(coordinator.resume).not.toHaveBeenCalled()
+ parent.removeAttribute("inert")
+ act(() => mutationCallback!([{
+ type: "attributes", target: parent, attributeName: "inert", oldValue: "",
+ addedNodes: [], removedNodes: [],
+ } as unknown as MutationRecord], {} as MutationObserver))
+ trigger(observers[0]!, row)
+ expect(coordinator.submit).not.toHaveBeenCalled()
+ trigger(observers.at(-1)!, row)
+ expect(coordinator.submit).toHaveBeenCalledOnce()
+ })
+
it("keeps all read side effects silent while presentation is hidden and inert", () => {
hookState.candidate = {
channelId: "channel-1",
diff --git a/src/web/src/hooks/community/use-read-observer.ts b/src/web/src/hooks/community/use-read-observer.ts
index ab39af72b..abf57bc40 100644
--- a/src/web/src/hooks/community/use-read-observer.ts
+++ b/src/web/src/hooks/community/use-read-observer.ts
@@ -27,6 +27,7 @@ const READ_VISIBILITY_THRESHOLD = 0.2
const MESSAGE_LIST_CONTENT_SELECTOR = "[data-message-list-content]"
function readPresentationReadable(scrollRootEl: HTMLElement) {
+ if (scrollRootEl.closest("[data-mobile-back-parent][inert]")) return false
const content = scrollRootEl.querySelector<HTMLElement>(MESSAGE_LIST_CONTENT_SELECTOR)
if (!content) return true
return content.getAttribute("aria-hidden") === "false"
@@ -290,6 +291,10 @@ export function useTimelineReadObserver({
childList: true,
subtree: true,
})
+ const parentLayer = scrollRootEl.closest("[data-mobile-back-parent]")
+ if (parentLayer) mutations?.observe(parentLayer, {
+ attributes: true, attributeFilter: ["inert"], attributeOldValue: true,
+ })
document.addEventListener("visibilitychange", sample)
window.addEventListener("pageshow", sample)
return () => {
diff --git a/src/web/src/test/community-ssr-geometry.test.ts b/src/web/src/test/community-ssr-geometry.test.ts
index ce32ecfe9..e7d7056f2 100644
--- a/src/web/src/test/community-ssr-geometry.test.ts
+++ b/src/web/src/test/community-ssr-geometry.test.ts
@@ -63,6 +63,19 @@ describe("SSR lifecycle geometry boundary", () => {
])
})
+ it("accepts retained detail underlays only when hidden, inert and aria-hidden", () => {
+ const retainedBackground = ["rail", "sidebar", "userBar"].map((module) => ({
+ module, visibility: "hidden", inert: true, ariaHidden: true,
+ }))
+ expect(ssrGeometryErrors([sample({ retainedBackground })], 390, "detail")).toEqual([])
+ for (const unsafe of [
+ { visibility: "visible" }, { inert: false }, { ariaHidden: false },
+ ]) {
+ expect(ssrGeometryErrors([sample({ retainedBackground: [{ ...retainedBackground[0], ...unsafe }] })], 390, "detail"))
+ .toContain("sample 0 (ssr): unsafe retained module rail")
+ }
+ })
+
it("rejects an empty recording", () => {
expect(ssrGeometryErrors([], 390, "detail")).toEqual([
"no lifecycle samples", "no complete parsed-document sample",
diff --git a/src/web/src/test/e2e-ui/24-composer-overflow.spec.ts b/src/web/src/test/e2e-ui/24-composer-overflow.spec.ts
index 1be7ba09e..f8e1925af 100644
--- a/src/web/src/test/e2e-ui/24-composer-overflow.spec.ts
+++ b/src/web/src/test/e2e-ui/24-composer-overflow.spec.ts
@@ -289,7 +289,7 @@ test.describe("community composer text containment", () => {
await page.waitForURL(new RegExp(threadId), { timeout: 20_000, waitUntil: "commit" })
await expectChatPlaceholderAtWidths(
page,
- page.getByTestId(tid.composerInput),
+ page.getByTestId(tid.threadSplitPanel).getByTestId(tid.composerInput),
`Message ${LONG_CJK}`,
)
})
diff --git a/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts b/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts
index 16df5df59..810f81a67 100644
--- a/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts
+++ b/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts
@@ -906,10 +906,11 @@ let caseJourneyFailure2Present = false
await expect(sticker).toContainText(`Long marked task ${suffix}`)
await expect(sticker).not.toContainText("**Long marked task")
await expect(sticker.locator("time")).toHaveCount(3)
- const markedMessageBody = sticker.locator("p").filter({ hasText: `Long marked task ${suffix}` })
- await expect(markedMessageBody).toHaveText(`Long marked task ${suffix} ${"with enough detail to require a second line ".repeat(5).trim()}`)
- await expect(markedMessageBody.locator('[data-streamdown="strong"]')).toHaveText(`Long marked task ${suffix}`)
- await expect(markedMessageBody).toHaveCSS("-webkit-line-clamp", "none")
+ const markedBody = sticker.locator("[data-community-message-body]").filter({ hasText: `Long marked task ${suffix}` })
+ await expect(markedBody).toHaveCount(1)
+ await expect(markedBody.locator('[data-streamdown="strong"]')).toHaveText(`Long marked task ${suffix}`)
+ await expect(markedBody).toHaveText(`Long marked task ${suffix} ${"with enough detail to require a second line ".repeat(5)}`.trim())
+ await expect(markedBody.locator("p")).toHaveCSS("-webkit-line-clamp", "none")
expect(ownerMarkRequests.length).toBeGreaterThan(0)
machine.socket.send(JSON.stringify({ type: "agent_activity", agentId: botId, state: "running" }))
const stop = alice.page.getByTestId(tid.botMarkStickerStop)
@@ -961,7 +962,8 @@ let caseJourneyFailure2Present = false
.toHaveCount(3)
await attachPageScreenshot(testInfo, "bot-mark-sticker-marks-mobile-dark", alice.page)
await sticker.getByRole("tab", { name: "Thoughts" }).click()
- await sticker.getByText("Open activity log 11", { exact: true }).click()
+ await sticker.getByTestId(tid.botAuditPreviewRow(liveEventId))
+ .getByText("Open activity log 11", { exact: true }).click()
await expect(alice.page).toHaveURL(new RegExp(`/c/me/bots\\?audit=${botId}`))
await gotoAfterUserWsAuth(alice.page, route)
await openBotProfile(alice.page, botName)
@@ -988,7 +990,9 @@ let caseJourneyFailure2Present = false
"data-placement",
/^(right|left|top|bottom)$/,
)
- const openActivity = auditRows.filter({ hasText: "Open activity log 11" }).getByTitle("Open full audit log")
+ const openActivity = sticker.getByTestId(tid.botAuditPreviewRow(liveEventId))
+ .getByTitle("Open full audit log", { exact: true })
+ await expect(openActivity.locator("time")).toHaveCount(1)
await openActivity.focus()
await expect(openActivity).toBeFocused()
await openActivity.press("Enter")
diff --git a/src/web/src/test/e2e-ui/39-mobile-composer-send.spec.ts b/src/web/src/test/e2e-ui/39-mobile-composer-send.spec.ts
index b2211f925..df7772030 100644
--- a/src/web/src/test/e2e-ui/39-mobile-composer-send.spec.ts
+++ b/src/web/src/test/e2e-ui/39-mobile-composer-send.spec.ts
@@ -1,4 +1,4 @@
-import type { Page, TestInfo } from "@playwright/test"
+import type { Locator, Page, TestInfo } from "@playwright/test"
import { test, expect } from "./_fixtures/case-fixture"
import {
composerEditable,
@@ -103,6 +103,8 @@ async function expectHoverKeyboardSend({
async function expectExplicitTouchSend({
page,
+ root = page,
+ backgroundRoot,
route,
channelId,
label,
@@ -111,6 +113,8 @@ async function expectExplicitTouchSend({
testInfo,
}: {
page: Page
+ root?: Page | Locator
+ backgroundRoot?: Locator
route: string
channelId: string
label: string
@@ -128,8 +132,8 @@ async function expectExplicitTouchSend({
await gotoAfterUserWsAuth(page, route)
await ignoreNextDevToolsPointerCapture(page)
- const editable = composerEditable(page)
- const send = page.getByTestId(tid.composerSend)
+ const editable = composerEditable(page, root)
+ const send = root.getByTestId(tid.composerSend)
await expect(editable).toBeVisible({ timeout: 20_000 })
await expect(editable).toHaveAttribute("enterkeyhint", "enter")
await expect(send).toBeVisible()
@@ -140,7 +144,7 @@ async function expectExplicitTouchSend({
const size = button.getBoundingClientRect()
return Number.parseFloat(getComputedStyle(button).borderRadius) >= size.width / 2
})).toBe(true)
- const composer = page.getByTestId(tid.composerInput).locator("..")
+ const composer = root.getByTestId(tid.composerInput).locator("..")
await expect(composer).toHaveCSS("border-radius", "24px")
await expect(composer.getByRole("button", { name: "Emoji picker" })).toHaveCount(0)
const singleLineHeight = await composer.evaluate((element) => element.getBoundingClientRect().height)
@@ -168,14 +172,21 @@ async function expectExplicitTouchSend({
await expect(send).toBeVisible()
}
- await page.getByTestId(tid.composerFileInput).setInputFiles({
+ if (backgroundRoot) {
+ await expect(backgroundRoot).toHaveAttribute("inert", "")
+ await expect(backgroundRoot.getByTestId(tid.composerFileInput)).toHaveCount(1)
+ await expect(root.getByTestId(tid.composerFileInput)).toHaveCount(1)
+ await expect(page.getByTestId(tid.composerFileInput)).toHaveCount(2)
+ }
+
+ await root.getByTestId(tid.composerFileInput).setInputFiles({
name: `${label}.txt`,
mimeType: "text/plain",
buffer: Buffer.from("pending attachment eligibility"),
})
- await expect(page.getByRole("button", { name: "Remove file" })).toBeVisible()
+ await expect(root.getByRole("button", { name: "Remove file" })).toBeVisible()
await expect(send).toBeEnabled()
- await page.getByRole("button", { name: "Remove file" }).click()
+ await root.getByRole("button", { name: "Remove file" }).click()
await expect(send).toBeDisabled()
const firstLine = `${label} first ${Date.now()}`
@@ -227,7 +238,7 @@ async function expectExplicitTouchSend({
await expect.poll(() => hasMessageFrame(frames, channelId, payload.message.id)).toBe(true)
await page.reload({ waitUntil: "commit" })
- await expect(composerEditable(page)).toBeVisible({ timeout: 20_000 })
+ await expect(composerEditable(page, root)).toBeVisible({ timeout: 20_000 })
await expect(page.getByTestId(tid.message(payload.message.id))).toContainText(firstLine)
expect(messagePosts).toBe(1)
}
@@ -282,13 +293,15 @@ test.describe("composer send by input capability", () => {
test("touch child thread button targets the child", async ({ caseActors }) => {
const actors = await caseActors(["alice", "bob"])
const { asUser } = actors
- const { serverId, channelId, threadId } = await prepareCase1(actors)
+ const { serverId, threadId } = await prepareCase1(actors)
const { page, context } = await asUser("alice", { hasTouch: true })
await installInputCapability(page, false)
const proxy = await proxyCommunityWebSockets(context)
await expectExplicitTouchSend({
page,
+ root: page.getByTestId(tid.threadSplitPanel),
+ backgroundRoot: page.getByTestId(tid.threadSplitParent),
route: `/c/channels/${serverId}/${threadId}`,
channelId: threadId,
label: "thread",
@@ -299,7 +312,7 @@ test.describe("composer send by input capability", () => {
test("touch DM button targets the DM channel", async ({ caseActors }) => {
const actors = await caseActors(["alice", "bob"])
const { asUser } = actors
- const { channelId, dmId } = await prepareCase1(actors)
+ const { dmId } = await prepareCase1(actors)
const { page, context } = await asUser("alice", { hasTouch: true })
await installInputCapability(page, false)
diff --git a/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts b/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
index 5be0067f1..8b5cffd9b 100644
--- a/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
+++ b/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
@@ -216,8 +216,9 @@ async function typeReplyAfterAuthorMention(
authorId: string,
author: { name: string; discriminator: string },
body: string,
+ root: Page | Locator = page,
) {
- const editable = composerEditable(page)
+ const editable = composerEditable(page, root)
const mention = editable.locator(`[data-type="mention"][data-id="${authorId}"]`)
await expect(mention).toHaveCount(1)
await expect(mention).toHaveAttribute("data-label", `${author.name}#${author.discriminator}`)
@@ -562,13 +563,15 @@ test("mobile reply, avatar mention, and typing rail keep exact backend and WS id
await bob.page.goto(`/c/channels/${serverId}/${threadId}`, { waitUntil: "commit" })
await ignoreNextDevToolsPointerCapture(alice.page)
await ignoreNextDevToolsPointerCapture(bob.page)
- await expect(composerEditable(alice.page)).toBeVisible()
- await expect(composerEditable(bob.page)).toBeVisible()
+ const aliceThread = alice.page.getByTestId(tid.threadSplitPanel)
+ const bobThread = bob.page.getByTestId(tid.threadSplitPanel)
+ await expect(composerEditable(alice.page, aliceThread)).toBeVisible()
+ await expect(composerEditable(bob.page, bobThread)).toBeVisible()
const threadTarget = alice.page.getByTestId(tid.message(threadBobMessageId))
await expect(threadTarget).toBeVisible()
const restingThreadGap = await alice.page.evaluate(({ targetId, composerId }) => {
- const target = document.querySelector(`[data-testid="${targetId}"]`)?.getBoundingClientRect()
- const composer = document.querySelector(`[data-testid="${composerId}"]`)?.getBoundingClientRect()
+ const target = document.querySelector('[data-testid="community-thread-split-panel"]')?.querySelector(`[data-testid="${targetId}"]`)?.getBoundingClientRect()
+ const composer = document.querySelector('[data-testid="community-thread-split-panel"]')?.querySelector(`[data-testid="${composerId}"]`)?.getBoundingClientRect()
return target && composer ? composer.top - target.bottom : null
}, {
targetId: tid.message(threadBobMessageId),
@@ -581,7 +584,7 @@ test("mobile reply, avatar mention, and typing rail keep exact backend and WS id
await expect.poll(() => bobProxy.frames.some((frame) => (
frameHasMessage(frame, threadId, threadWsReadyId)
)), { timeout: 20_000 }).toBe(true)
- const editable = composerEditable(alice.page)
+ const editable = composerEditable(alice.page, aliceThread)
await editable.fill("openerhere")
await editable.click()
for (let index = 0; index < 4; index += 1) await alice.page.keyboard.press("ArrowLeft")
@@ -615,7 +618,7 @@ test("mobile reply, avatar mention, and typing rail keep exact backend and WS id
response.request().method() === "POST"
&& new URL(response.url()).pathname === `/api/community/channels/${threadId}/messages`
))
- await alice.page.getByTestId(tid.composerSend).click()
+ await aliceThread.getByTestId(tid.composerSend).click()
const mentionResponse = await mentionResponsePromise
expect(mentionResponse.status()).toBe(201)
const mentionPayload = await mentionResponse.json() as {
@@ -630,15 +633,15 @@ test("mobile reply, avatar mention, and typing rail keep exact backend and WS id
await dispatchSwipe(alice.page, threadBobMessageId, { x: 72, y: 1 })
await expect(replyPreview).toHaveText(`Replying to ${bobInfo.name} · thread target ${stamp}`)
- await expect(composerEditable(alice.page).locator(`[data-type="mention"][data-id="${userId("bob")}"]`)).toHaveCount(1)
+ await expect(composerEditable(alice.page, aliceThread).locator(`[data-type="mention"][data-id="${userId("bob")}"]`)).toHaveCount(1)
const threadReplyBody = `thread swipe reply ${stamp}`
const threadReplyContent = `${replyAuthorMention} ${threadReplyBody}`
const threadReplyResponsePromise = alice.page.waitForResponse((response) => (
response.request().method() === "POST"
&& new URL(response.url()).pathname === `/api/community/channels/${threadId}/messages`
))
- await typeReplyAfterAuthorMention(alice.page, userId("bob"), bobInfo, threadReplyBody)
- await alice.page.getByTestId(tid.composerSend).click()
+ await typeReplyAfterAuthorMention(alice.page, userId("bob"), bobInfo, threadReplyBody, aliceThread)
+ await aliceThread.getByTestId(tid.composerSend).click()
const threadReplyResponse = await threadReplyResponsePromise
expect(threadReplyResponse.status()).toBe(201)
const threadReplyPayload = await threadReplyResponse.json() as {
@@ -1076,7 +1079,7 @@ test("mobile thread return uses server read state instead of tab-local pixel mem
await threadIndicator.click()
await expect.poll(() => new URL(alice.page.url()).pathname).toBe(`/c/channels/${serverId}/${threadId}`)
await expect(alice.page.getByTestId(tid.message(threadReplyId))).toBeVisible()
- const threadScroller = alice.page.getByTestId(tid.messageScroller)
+ const threadScroller = alice.page.getByTestId(tid.threadSplitPanel).getByTestId(tid.messageScroller)
await expect.poll(() => threadScroller.evaluate((element) => (
element.scrollHeight - element.clientHeight
))).toBeGreaterThan(1600)
diff --git a/src/web/src/test/e2e-ui/40-mobile-server-header-hierarchy.spec.ts b/src/web/src/test/e2e-ui/40-mobile-server-header-hierarchy.spec.ts
index 00bbff325..acba1df50 100644
--- a/src/web/src/test/e2e-ui/40-mobile-server-header-hierarchy.spec.ts
+++ b/src/web/src/test/e2e-ui/40-mobile-server-header-hierarchy.spec.ts
@@ -92,7 +92,7 @@ test.describe("mobile server header direct hierarchy", () => {
page.on("response", observeStartupAttention)
await page.setViewportSize({ width: 639, height: 844 })
await page.goto(`/c/channels/${serverId}/${threadId}`, { waitUntil: "commit" })
- await expect(page.getByTestId(tid.composerInput)).toBeVisible({ timeout: 20_000 })
+ await expect(page.getByTestId(tid.threadSplitPanel).getByTestId(tid.composerInput)).toBeVisible({ timeout: 20_000 })
await expectMobileBack(page)
// The shell-owned attention query settles once on cold mount. Keep that
// generation outside the resize measurement window.
@@ -103,9 +103,9 @@ test.describe("mobile server header direct hierarchy", () => {
await page.waitForLoadState("networkidle")
await page.evaluate(({ composerTestId }) => {
- const backControl = document.querySelector('button[aria-label="Back"]')
+ const backControl = document.querySelector('[data-testid="community-thread-split-panel"]')?.querySelector('button[aria-label="Back"]')
Reflect.set(window, "__headerHierarchyBanner", backControl?.closest("header[role=banner]"))
- Reflect.set(window, "__headerHierarchyComposer", document.querySelector(`[data-testid="${composerTestId}"]`))
+ Reflect.set(window, "__headerHierarchyComposer", document.querySelector('[data-testid="community-thread-split-panel"]')?.querySelector(`[data-testid="${composerTestId}"]`))
}, {
composerTestId: tid.channelComposerShell,
})
@@ -119,10 +119,10 @@ test.describe("mobile server header direct hierarchy", () => {
await page.setViewportSize({ width: 640, height: 844 })
await expect(page.getByRole("button", { name: "Back" })).toBeVisible()
- await expect(page.getByTestId(tid.channelComposerShell)).toBeVisible()
+ await expect(page.getByTestId(tid.threadSplitPanel).getByTestId(tid.channelComposerShell)).toBeVisible()
expect(await page.evaluate(({ composerTestId }) => ({
- banner: Reflect.get(window, "__headerHierarchyBanner") === document.querySelector('button[aria-label="Back"]')?.closest("header[role=banner]"),
- composer: Reflect.get(window, "__headerHierarchyComposer") === document.querySelector(`[data-testid="${composerTestId}"]`),
+ banner: Reflect.get(window, "__headerHierarchyBanner") === document.querySelector('[data-testid="community-thread-split-panel"]')?.querySelector('button[aria-label="Back"]')?.closest("header[role=banner]"),
+ composer: Reflect.get(window, "__headerHierarchyComposer") === document.querySelector('[data-testid="community-thread-split-panel"]')?.querySelector(`[data-testid="${composerTestId}"]`),
}), {
composerTestId: tid.channelComposerShell,
})).toEqual({ banner: true, composer: true })
@@ -130,8 +130,8 @@ test.describe("mobile server header direct hierarchy", () => {
await page.setViewportSize({ width: 639, height: 844 })
await expect(page.getByRole("button", { name: "Back" })).toBeVisible()
expect(await page.evaluate(({ composerTestId }) => ({
- banner: Reflect.get(window, "__headerHierarchyBanner") === document.querySelector('button[aria-label="Back"]')?.closest("header[role=banner]"),
- composer: Reflect.get(window, "__headerHierarchyComposer") === document.querySelector(`[data-testid="${composerTestId}"]`),
+ banner: Reflect.get(window, "__headerHierarchyBanner") === document.querySelector('[data-testid="community-thread-split-panel"]')?.querySelector('button[aria-label="Back"]')?.closest("header[role=banner]"),
+ composer: Reflect.get(window, "__headerHierarchyComposer") === document.querySelector('[data-testid="community-thread-split-panel"]')?.querySelector(`[data-testid="${composerTestId}"]`),
}), {
composerTestId: tid.channelComposerShell,
})).toEqual({ banner: true, composer: true })
diff --git a/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts b/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts
index e775fb429..cae61c434 100644
--- a/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts
+++ b/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts
@@ -301,8 +301,9 @@ test("server unread owns exact rail geometry, folder aggregation, read clear, an
expect(retained).not.toBeNull()
await page.getByTestId(tid.channelRow(foregroundChannel)).click()
await expect(page).toHaveURL(`/c/channels/${foregroundServer}/${foregroundChannel}`)
- await expect(railContainer).toHaveCSS("display", "none")
+ await expect(railContainer).toHaveCSS("visibility", "hidden")
await expect(railContainer).toHaveAttribute("inert", "")
+ await expect(railContainer).toHaveAttribute("aria-hidden", "true")
let lastMessageId = await sendMention(`Hidden Server digit ${stamp}`)
await expect.poll(async () => (await readDigits()).text).toBe("10")
await expectPrimaryCount("hidden-update", 10)
@@ -314,7 +315,9 @@ test("server unread owns exact rail geometry, folder aggregation, read clear, an
for (let cycle = 0; cycle < 2; cycle += 1) {
await page.getByTestId(tid.channelRow(foregroundChannel)).click()
- await expect(railContainer).toHaveCSS("display", "none")
+ await expect(railContainer).toHaveCSS("visibility", "hidden")
+ await expect(railContainer).toHaveAttribute("inert", "")
+ await expect(railContainer).toHaveAttribute("aria-hidden", "true")
lastMessageId = await sendMention(`Repeated hidden Server ${stamp} ${cycle}`)
const count = 11 + cycle
await expect.poll(async () => (await readDigits()).text).toBe(String(count))
diff --git a/src/web/src/test/e2e-ui/44-mobile-reaction-details.spec.ts b/src/web/src/test/e2e-ui/44-mobile-reaction-details.spec.ts
index 7214dc9b7..0f4a9afad 100644
--- a/src/web/src/test/e2e-ui/44-mobile-reaction-details.spec.ts
+++ b/src/web/src/test/e2e-ui/44-mobile-reaction-details.spec.ts
@@ -357,7 +357,7 @@ test.describe("mobile reaction details", () => {
await alice.page.emulateMedia({ colorScheme: "light" })
await installInputCapability(alice.page, false)
await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${threadId}`)
- const chip = alice.page.getByTestId(tid.reactionChip(threadOpenerId, "👍"))
+ const chip = alice.page.getByTestId(tid.threadSplitPanel).getByTestId(tid.reactionChip(threadOpenerId, "👍"))
await expect(chip).toBeVisible()
await holdReaction(alice.page, chip)
await expectDialogInsideViewport(alice.page, threadOpenerId)
diff --git a/src/web/src/test/e2e-ui/53-mobile-inbox-surface.spec.ts b/src/web/src/test/e2e-ui/53-mobile-inbox-surface.spec.ts
index 10d457d76..0766c615f 100644
--- a/src/web/src/test/e2e-ui/53-mobile-inbox-surface.spec.ts
+++ b/src/web/src/test/e2e-ui/53-mobile-inbox-surface.spec.ts
@@ -354,7 +354,9 @@ test.describe("mobile Inbox interactive user-bar base", () => {
const hiddenId = await seedChannel("alice", serverId, `hidden-${stamp}`)
await bob.page.getByTestId(tid.channelRow(landingId)).click()
await expect(bob.page).toHaveURL(`/c/channels/${serverId}/${landingId}`)
- await expect(overlay).toHaveCSS("display", "none")
+ await expect(overlay).toHaveCSS("visibility", "hidden")
+ await expect(overlay).toHaveAttribute("inert", "")
+ await expect(overlay).toHaveAttribute("aria-hidden", "true")
await send(hiddenId, `Hidden Inbox digit ${stamp}`)
await expect(indicator).toHaveAttribute("data-count", String(targetCount))
await capture("hidden-update", targetCount)
@@ -365,7 +367,9 @@ test.describe("mobile Inbox interactive user-bar base", () => {
for (let cycle = 0; cycle < 2; cycle += 1) {
await bob.page.getByTestId(tid.channelRow(landingId)).click()
- await expect(overlay).toHaveCSS("display", "none")
+ await expect(overlay).toHaveCSS("visibility", "hidden")
+ await expect(overlay).toHaveAttribute("inert", "")
+ await expect(overlay).toHaveAttribute("aria-hidden", "true")
await send(hiddenId, `Repeated hidden Inbox ${stamp} ${cycle}`)
await expect(indicator).toHaveAttribute("data-count", String(targetCount))
await capture(`hidden-repeat-${cycle}`, targetCount)
diff --git a/src/web/src/test/e2e-ui/_fixtures/community-loading-geometry.ts b/src/web/src/test/e2e-ui/_fixtures/community-loading-geometry.ts
index 44e8f721e..761ae4967 100644
--- a/src/web/src/test/e2e-ui/_fixtures/community-loading-geometry.ts
+++ b/src/web/src/test/e2e-ui/_fixtures/community-loading-geometry.ts
@@ -288,7 +288,9 @@ async function installSsrLifecycleProbe(page: Page, surface: "list" | "detail")
const rect = (selector: string) => {
const element = document.querySelector<HTMLElement>(selector)
- if (!element || getComputedStyle(element).display === "none") return null
+ if (!element) return null
+ const style = getComputedStyle(element)
+ if (style.display === "none" || style.visibility !== "visible") return null
const box = element.getBoundingClientRect()
if (box.width === 0 || box.height === 0) return null
return { x: box.x, y: box.y, width: box.width, height: box.height }
@@ -306,6 +308,21 @@ async function installSsrLifecycleProbe(page: Page, surface: "list" | "detail")
main: rect(expectedSurface === "detail" ? activePanel : hiddenPanel),
userBar: rect('[data-slot="community-user-bar-overlay"]'),
}).filter((entry): entry is [string, NonNullable<typeof entry[1]>] => entry[1] !== null))
+ const retainedBackground = expectedSurface === "detail"
+ ? Object.entries({
+ rail: ['[data-mobile-back-rail]', '[data-mobile-back-rail]'],
+ sidebar: [hiddenPanel, '[data-slot="community-sidebar-panel-content"]'],
+ userBar: ['[data-slot="community-user-bar-overlay"]', '[data-slot="community-user-bar-overlay"]'],
+ }).flatMap(([module, [selector, guardSelector]]) => {
+ const element = document.querySelector<HTMLElement>(selector)
+ if (!element || getComputedStyle(element).display === "none") return []
+ const box = element.getBoundingClientRect()
+ if (!box.width || !box.height) return []
+ const guard = document.querySelector<HTMLElement>(guardSelector)
+ return [{ module, visibility: getComputedStyle(element).visibility,
+ inert: guard?.inert === true, ariaHidden: guard?.getAttribute("aria-hidden") === "true" }]
+ })
+ : []
samples.push({
timestamp: performance.now(),
phase: !parsed ? "parsing"
@@ -315,6 +332,7 @@ async function installSsrLifecycleProbe(page: Page, surface: "list" | "detail")
incompleteShellHtml: geometry.surface ? undefined : shell.outerHTML,
overflow: document.documentElement.scrollWidth - document.documentElement.clientWidth,
geometry,
+ retainedBackground,
})
}
if (!Reflect.get(window, "__communitySsrProbeStopped")) requestAnimationFrame(sample)
@@ -501,6 +519,8 @@ export async function seedGeometryRoutes(
const main = (page: Page) => shellPanel(page, "main")
const messageReady = (content: string) => (page: Page) =>
main(page).getByText(content, { exact: true }).first()
+ const threadMessageReady = (content: string) => (page: Page) => page
+ .getByTestId(tid.threadSplitPanel).getByText(content, { exact: true }).first()
const threadComposerReady = (page: Page) => page
.getByTestId(tid.threadSplitPanel)
.getByTestId(tid.composerInput)
@@ -523,7 +543,7 @@ export async function seedGeometryRoutes(
{
name: "thread",
pathname: `/c/channels/${serverId}/${threadId}`,
- ready: messageReady(threadMessage),
+ ready: threadMessageReady(threadMessage),
intermediate: {
requestPattern: `**/api/community/channels/${threadId}/messages**`,
ready: threadComposerReady,
@@ -532,7 +552,7 @@ export async function seedGeometryRoutes(
{
name: "forum-post",
pathname: `/c/channels/${serverId}/${forumPostId}`,
- ready: messageReady(forumMessage),
+ ready: threadMessageReady(forumMessage),
intermediate: {
requestPattern: `**/api/community/channels/${forumPostId}/messages**`,
ready: threadComposerReady,
diff --git a/src/web/src/test/e2e-ui/_fixtures/community-ssr-geometry.ts b/src/web/src/test/e2e-ui/_fixtures/community-ssr-geometry.ts
index ac94d70ed..e7aa4638a 100644
--- a/src/web/src/test/e2e-ui/_fixtures/community-ssr-geometry.ts
+++ b/src/web/src/test/e2e-ui/_fixtures/community-ssr-geometry.ts
@@ -8,6 +8,7 @@ export type SsrLifecycleSample = {
incompleteShellHtml?: string
overflow: number
geometry: SsrGeometry
+ retainedBackground?: { module: string; visibility: string; inert: boolean; ariaHidden: boolean }[]
}
export function ssrGeometryErrors(
@@ -24,6 +25,14 @@ export function ssrGeometryErrors(
if (samples.length === 0) errors.push("no lifecycle samples")
for (const [index, sample] of samples.entries()) {
const label = `sample ${index} (${sample.phase})`
+ for (const retained of sample.retainedBackground ?? []) {
+ if (surface !== "detail" || !["rail", "sidebar", "userBar"].includes(retained.module)) {
+ errors.push(`${label}: unexpected retained module ${retained.module}`)
+ }
+ if (retained.visibility !== "hidden" || !retained.inert || !retained.ariaHidden) {
+ errors.push(`${label}: unsafe retained module ${retained.module}`)
+ }
+ }
if (sample.overflow !== 0) errors.push(`${label}: horizontal overflow ${sample.overflow}`)
for (const [name, rect] of Object.entries(sample.geometry)) {
if (!(name in widths)) errors.push(`${label}: unexpected module ${name}`)