Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

refactor(web): remove page navigation swipes (#1021)

Gener1a60ca51a64c
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 8d28cb78a..ba6c4c498 100644
--- a/src/desktop/src-tauri/gen/android/app/build.gradle.kts
+++ b/src/desktop/src-tauri/gen/android/app/build.gradle.kts
@@ -45,10 +45,6 @@ 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")
@@ -80,11 +76,10 @@ 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) + source.occurrencesOf(scopedPageStartedCallback) != 1) {
+ if (source.occurrencesOf(originalPageStartedCallback) + source.occurrencesOf(exclusivePageStartedCallback) != 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")
@@ -104,7 +99,7 @@ fun wireGeneratedWebViewRecovery(sourceFile: File) {
fun verifyGeneratedWebViewRecovery(sourceFile: File) {
val source = sourceFile.readText()
val required = listOf(
- "exclusive remote initialization callback" to scopedPageStartedCallback,
+ "exclusive remote initialization callback" to exclusivePageStartedCallback,
"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/java/ai/alook/android/MainActivity.kt b/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/MainActivity.kt
index 2ab23dc11..1c78027bb 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,14 +3,10 @@ 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
@@ -23,29 +19,6 @@ 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
@@ -109,40 +82,7 @@ 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()
@@ -153,8 +93,6 @@ 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
deleted file mode 100644
index 844cf8cef..000000000
--- a/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/NativeBackProgress.kt
+++ /dev/null
@@ -1,43 +0,0 @@
-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
deleted file mode 100644
index a9b0c4409..000000000
--- a/src/desktop/src-tauri/gen/android/app/src/test/java/ai/alook/android/NativeBackProgressTest.kt
+++ /dev/null
@@ -1,91 +0,0 @@
-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 0d0b594ff..8681dd23a 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
@@ -56,7 +56,7 @@ const {
mockSearchParams: { value: "msg=m_target&keep=1" },
mockSplitMode: { value: "full" as "pending" | "split" | "full" },
mockSplitContainerRef: vi.fn(),
- mockUseThreadSplitMode: vi.fn(),
+ mockUseThreadSplitMode: vi.fn<typeof import("@/hooks/community/use-thread-split-mode").useThreadSplitMode>(),
mockSplitParentSurface: vi.fn((_props: Record<string, unknown>): React.ReactNode => null),
mockCommitLastCommunityRoute: vi.fn(),
mockSetLastChannel: vi.fn(),
@@ -154,7 +154,7 @@ vi.mock("@/components/community/channels/channel-header", () => ({
}) => {
mockHeaderServerNavigate.current = kind === "thread" ? undefined : mobileBack
mockHeaderParentNavigate.current = kind === "thread" ? mobileBack : undefined
- return React.createElement(React.Fragment, null, endActions)
+ return React.createElement("header", { "data-header-kind": kind }, endActions)
},
ChannelHeaderSkeleton: ({ kind = "text" }: { kind?: string }) =>
React.createElement("div", { "data-testid": "channel-header-skeleton", "data-kind": kind }),
@@ -164,7 +164,7 @@ vi.mock("@/components/community/channels/conversation-message-skeleton", () => (
ConversationMessageSkeleton: () => React.createElement("div", { "data-message-list-skeleton": true }),
}))
vi.mock("@/components/community/messages/composer", () => ({
- Composer: () => null,
+ Composer: ({ draftKey }: { draftKey: string }) => React.createElement("textarea", { "data-draft-key": draftKey }),
ComposerSkeleton: () => null,
}))
vi.mock("@/components/community/channels/forum-view", () => ({
@@ -232,10 +232,8 @@ vi.mock("@/hooks/community/use-native-system-notifications", () => ({
mockDismissConversation(...args),
}))
vi.mock("@/hooks/community/use-thread-split-mode", () => ({
- useThreadSplitMode: (options: unknown) => {
- mockUseThreadSplitMode(options)
- return { containerRef: mockSplitContainerRef, mode: mockSplitMode.value }
- },
+ useThreadSplitMode: (options: Parameters<typeof mockUseThreadSplitMode>[0]) =>
+ mockUseThreadSplitMode(options) ?? { containerRef: mockSplitContainerRef, mode: mockSplitMode.value },
}))
vi.mock("@/components/community/channels/thread-split-parent-surface", () => ({
ThreadSplitParentSurface: mockSplitParentSurface,
@@ -244,8 +242,6 @@ vi.mock("@/components/community/channels/thread-split-view", () => ({
ThreadSplitView: ({
split,
layoutPending = false,
- mobileBack = false,
- preserveParent = false,
parent,
thread,
conversationSubtype,
@@ -253,8 +249,6 @@ vi.mock("@/components/community/channels/thread-split-view", () => ({
}: {
split: boolean
layoutPending?: boolean
- mobileBack?: boolean
- preserveParent?: boolean
parent: React.ReactNode
thread: React.ReactNode
conversationSubtype?: string
@@ -263,15 +257,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": layoutPending || resolvingParent ? "pending" : split ? "split" : "full",
"data-layout-pending": layoutPending || undefined,
"data-community-conversation-subtype": conversationSubtype === "unknown" ? undefined : conversationSubtype,
},
resolvingParent && React.createElement("main", { "aria-label": "Resolving conversation", "data-community-conversation-subtype": "unknown" }),
- (split || layoutPending || mobileBack || preserveParent) && React.createElement(
+ (split || layoutPending) && React.createElement(
"section",
- { "data-testid": "community-thread-split-parent", "data-mobile-back-parent": "", inert: !split },
+ { "data-testid": "community-thread-split-parent", "data-thread-parent": "", inert: !split },
parent,
),
React.createElement(
@@ -438,7 +431,7 @@ describe("ChannelRoute message surface ownership", () => {
mockSearchParams.value = "msg=m_target&keep=1"
mockSplitMode.value = "full"
mockSplitContainerRef.mockClear()
- mockUseThreadSplitMode.mockClear()
+ mockUseThreadSplitMode.mockReset()
mockClaimSecondary.mockClear()
mockReleaseSecondary.mockClear()
mockUseChannelMetadata.mockClear()
@@ -814,53 +807,99 @@ describe("ChannelRoute message surface ownership", () => {
expect(mockReleaseSecondary).toHaveBeenLastCalledWith(runtime, nextOwner)
})
- it("loads the verified mobile parent underlay without claiming it until access is ready", async () => {
+ it("does not load a mobile parent underlay or keep its owner through narrow desktop", 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")
+ const node = () => React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_1" })
+ const renderer = render(node())
+ for (const breakpoint of ["mobile", "desktop", "mobile"] as const) {
+ mockBreakpoint.value = breakpoint
+ renderer.rerender(node())
+ expect(screen.queryByTestId("community-thread-split-parent")).not.toBeInTheDocument()
+ expect(mockUseChannelMetadata).not.toHaveBeenCalled()
+ expect(mockClaimSecondary).not.toHaveBeenCalled()
+ }
+ mockBreakpoint.value = "desktop"
+ mockSplitMode.value = "split"
+ renderer.rerender(node())
+ expect(screen.getByTestId("community-thread-split-parent")).toBeInTheDocument()
+ const [runtime, owner] = mockClaimSecondary.mock.calls.at(-1)!
+ mockBreakpoint.value = "mobile"
+ mockSplitMode.value = "full"
+ renderer.rerender(node())
+ expect(screen.queryByTestId("community-thread-split-parent")).not.toBeInTheDocument()
+ expect(mockReleaseSecondary).toHaveBeenCalledWith(runtime, owner)
renderer.unmount()
- expect(mockReleaseSecondary).toHaveBeenCalled()
})
- it("retains the mobile parent owner through a narrow desktop round trip", async () => {
+ it("starts no transient parent resources through measured mobile639 to desktop640 transitions", async () => {
await observeSecondary()
const { ThreadSplitParentSurface } = await vi.importActual<typeof import("./thread-split-parent-surface")>("./thread-split-parent-surface")
+ const { useThreadSplitMode } = await vi.importActual<typeof import("@/hooks/community/use-thread-split-mode")>("@/hooks/community/use-thread-split-mode")
+ const modes: string[] = []
+ mockUseThreadSplitMode.mockImplementation(function useMeasuredMode(options) {
+ const result = useThreadSplitMode(options)
+ modes.push(result.mode)
+ return result
+ })
+ let width = 639
+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(() => ({
+ width, height: 800, top: 0, right: width, bottom: 800, left: 0, x: 0, y: 0, toJSON: () => ({}),
+ }))
+ vi.stubGlobal("ResizeObserver", undefined)
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) {
+ const outer = renderer.container.firstElementChild
+ const panel = screen.getByTestId("community-thread-split-panel")
+ const header = panel.querySelector('[data-header-kind="thread"]')
+ const composer = panel.querySelector<HTMLTextAreaElement>('[data-draft-key="server_1/channel_1"]')!
+ expect(header).not.toBeNull()
+ expect(composer).not.toBeNull()
+ fireEvent.change(composer, { target: { value: "Keep this draft" } })
+ for (const breakpoint of ["desktop", "mobile", "desktop"] as const) {
mockBreakpoint.value = breakpoint
+ width = breakpoint === "desktop" ? 640 : 639
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()
+ expect(screen.getByTestId("community-thread-split")).toHaveAttribute("data-layout", "full")
+ expect(screen.queryByTestId("community-thread-split-parent")).not.toBeInTheDocument()
+ expect({
+ parentRenders: mockSplitParentSurface.mock.calls.length,
+ metadataReads: mockUseChannelMetadata.mock.calls.length,
+ secondaryClaims: mockClaimSecondary.mock.calls.length,
+ parentFeeds: mockedUseChannelMessageFeed.mock.calls.filter(([options]) => options.channelId === "parent_1").length,
+ }).toEqual({ parentRenders: 0, metadataReads: 0, secondaryClaims: 0, parentFeeds: 0 })
+ expect(renderer.container.firstElementChild).toBe(outer)
+ expect(screen.getByTestId("community-thread-split-panel")).toBe(panel)
+ expect(panel.querySelector('[data-header-kind="thread"]')).toBe(header)
+ expect(panel.querySelector('[data-draft-key="server_1/channel_1"]')).toBe(composer)
+ expect(composer).toHaveValue("Keep this draft")
}
+ expect(modes).toContain("pending")
+ width = 880
+ act(() => window.dispatchEvent(new Event("resize")))
+ expect(screen.getByTestId("community-thread-split")).toHaveAttribute("data-layout", "split")
+ expect(mockUseChannelMetadata).toHaveBeenCalled()
+ expect(mockedUseChannelMessageFeed).toHaveBeenCalledWith(expect.objectContaining({ channelId: "parent_1" }))
+ const [runtime, owner] = mockClaimSecondary.mock.calls.at(-1)!
+ expect(owner).toBeDefined()
+ mockBreakpoint.value = "mobile"
+ width = 639
+ renderer.rerender(node())
+ expect(screen.queryByTestId("community-thread-split-parent")).not.toBeInTheDocument()
+ expect(mockReleaseSecondary).toHaveBeenCalledWith(runtime, owner)
+ expect(panel.querySelector('[data-header-kind="thread"]')).toBe(header)
+ expect(panel.querySelector('[data-draft-key="server_1/channel_1"]')).toBe(composer)
+ expect(composer).toHaveValue("Keep this draft")
renderer.unmount()
- expect(mockReleaseSecondary).toHaveBeenCalledOnce()
})
it.each(["full", "non-thread"] as const)("starts no parent resources for a ready %s target", (kind) => {
@@ -1028,8 +1067,10 @@ describe("ChannelRoute message surface ownership", () => {
const renderer = render(React.createElement(ChannelRoute, props))
expect(screen.getByTestId("community-thread-split")).toHaveAttribute("data-layout", "pending")
expect(screen.getByTestId("community-thread-split")).toHaveAttribute("data-layout-pending", "true")
- expect(mockSplitParentSurface).toHaveBeenCalledWith(expect.objectContaining({ channel: expect.objectContaining({ id: "parent_1" }) }), undefined)
- mockSplitParentSurface.mockClear()
+ const reservation = screen.getByTestId("community-thread-split-parent")
+ expect(reservation).toBeEmptyDOMElement()
+ expect(reservation).toHaveAttribute("inert")
+ expect(mockSplitParentSurface).not.toHaveBeenCalled()
expect(renderer.container.querySelector('[data-community-conversation-subtype="unknown"]')).toBeNull()
expect(mockedUseChannelMessageFeed).toHaveBeenCalledWith(expect.objectContaining({ channelId: "channel_1" }))
Object.assign(mockRouteModel, {
@@ -1469,6 +1510,7 @@ describe("ChannelRoute message surface ownership", () => {
afterEach(() => {
vi.useRealTimers()
+ vi.unstubAllGlobals()
vi.clearAllMocks()
vi.restoreAllMocks()
})
diff --git a/src/web/src/components/community/channels/channel-route.tsx b/src/web/src/components/community/channels/channel-route.tsx
index 5a6c4b5eb..a050f00d8 100644
--- a/src/web/src/components/community/channels/channel-route.tsx
+++ b/src/web/src/components/community/channels/channel-route.tsx
@@ -101,15 +101,10 @@ function ChannelRouteFrame(target: RouteTarget) {
const uiHandlers = useUiHandlers()
const split = isThread && mode === "split"
const layoutPending = isThread && mode === "pending"
- const [parentIdentity, setParentIdentity] = useAtom(useCreateAtom<{ id: string; confirmed: boolean; keepMounted: boolean } | null>(null))
+ const [parentIdentity, setParentIdentity] = useAtom(useCreateAtom<{ id: string; confirmed: boolean } | null>(null))
const onParentIdentity = useCallback((id: string, confirmed: boolean) => {
- 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
+ setParentIdentity((current) => current?.id === id && current.confirmed === confirmed ? current : { id, confirmed })
+ }, [setParentIdentity])
const resolvingParent = split && routeModel.routeLifecycle !== "ready" &&
(!parent || parentIdentity?.id !== parent.id || !parentIdentity.confirmed)
const channelRefCandidates = useMemo(() => server?.categories
@@ -130,8 +125,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} layoutPending={layoutPending} mobileBack={breakpoint === "mobile" && isThread && !!parent} preserveParent={preserveParent} resolvingParent={resolvingParent} conversationSubtype={isThread ? "thread" : routeModel.skeletonSubtype}
- parent={(split || layoutPending || breakpoint === "mobile" && isThread || preserveParent) && parent ? <ThreadSplitParentSurface
+ split={split} layoutPending={layoutPending} resolvingParent={resolvingParent} conversationSubtype={isThread ? "thread" : routeModel.skeletonSubtype}
+ parent={split && 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 e585f4285..e63b45ee6 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
@@ -100,26 +100,14 @@ describe("ThreadSplitView", () => {
renderer.unmount()
})
- 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"),
+ it("does not mount a hidden parent for a full-screen thread", () => {
+ const parent = createElement("input", { "data-testid": "hidden-parent-draft", defaultValue: "keep me" })
+ render(createElement(ThreadSplitView, {
+ split: false, 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.queryByTestId("hidden-parent-draft")).not.toBeInTheDocument()
+ expect(screen.getByText("Child")).toBeInTheDocument()
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", () => {
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 bcc5455d1..58e6376b3 100644
--- a/src/web/src/components/community/channels/thread-split-view.tsx
+++ b/src/web/src/components/community/channels/thread-split-view.tsx
@@ -30,8 +30,6 @@ const threadSplitLayoutStorage = {
export function ThreadSplitView({
split,
layoutPending = false,
- mobileBack = false,
- preserveParent = false,
parent,
thread,
conversationSubtype = "thread",
@@ -39,8 +37,6 @@ export function ThreadSplitView({
}: {
split: boolean
layoutPending?: boolean
- mobileBack?: boolean
- preserveParent?: boolean
parent: ReactNode
thread: ReactNode
conversationSubtype?: "unknown" | "text" | "forum" | "thread"
@@ -71,7 +67,6 @@ export function ThreadSplitView({
return (
<main
data-testid={isThread ? tid.threadSplit : undefined}
- data-mobile-back-thread={mobileBack || undefined}
data-layout={layoutPending || resolvingParent ? "pending" : split ? "split" : "full"}
data-layout-pending={layoutPending || undefined}
data-community-conversation-subtype={conversationSubtype === "unknown" ? undefined : conversationSubtype}
@@ -91,7 +86,7 @@ export function ThreadSplitView({
disabled={!split || resolvingParent}
aria-hidden={resolvingParent || undefined}
inert={resolvingParent || undefined}
- className={cn("min-h-0 flex-1", resolvingParent && "invisible", !split && !mobileBack && !layoutPending && [
+ className={cn("min-h-0 flex-1", resolvingParent && "invisible", !split && !layoutPending && [
"*:data-[layout-hidden=true]:flex-none!",
"*:data-[layout-hidden=true]:w-0!",
"*:data-[layout-hidden=true]:min-w-0!",
@@ -110,9 +105,9 @@ export function ThreadSplitView({
data-layout-hidden={!split && !layoutPending || undefined}
className="flex min-h-0 min-w-0 flex-col"
>
- {(split || layoutPending || mobileBack || preserveParent) && <section
+ {(split || layoutPending) && <section
data-testid={tid.threadSplitParent}
- data-mobile-back-parent
+ data-thread-parent
inert={!split}
aria-hidden={!split || undefined}
aria-label="Parent conversation"
diff --git a/src/web/src/components/community/messages/mobile-message-gesture.ts b/src/web/src/components/community/messages/mobile-message-gesture.ts
index b38ef0db9..e967608f9 100644
--- a/src/web/src/components/community/messages/mobile-message-gesture.ts
+++ b/src/web/src/components/community/messages/mobile-message-gesture.ts
@@ -1,4 +1,4 @@
-import { MOBILE_BACK_EDGE_PX } from "@/hooks/community/use-native-mobile-back"
+const MOBILE_REPLY_EDGE_PX = 24
const MOBILE_REPLY_INTENT_PX = 8
const MOBILE_REPLY_THRESHOLD_PX = 64
export const MOBILE_REPLY_MAX_OFFSET_PX = 88
@@ -17,7 +17,7 @@ export function beginMobileReplyGesture(
clientX: number,
clientY: number,
): MobileReplyGesture | null {
- if (clientX <= MOBILE_BACK_EDGE_PX) return null
+ if (clientX <= MOBILE_REPLY_EDGE_PX) return null
return {
startX: clientX,
startY: clientY,
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 3f2f3f4fb..3863de207 100644
--- a/src/web/src/components/community/shell/community-shell-layout.tsx
+++ b/src/web/src/components/community/shell/community-shell-layout.tsx
@@ -39,7 +39,6 @@ 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"
@@ -386,11 +385,9 @@ 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 data-mobile-back-rail inert={isMobileDetail} aria-hidden={isMobileDetail || undefined} className={cn(
+ <div data-community-rail inert={isMobileDetail} aria-hidden={isMobileDetail || undefined} className={cn(
"flex min-h-0",
isInitialDetail && "hidden sm:contents",
isMobileDetail && preserveHiddenMobileModules && "hidden",
@@ -399,7 +396,6 @@ 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",
@@ -421,7 +417,7 @@ export function CommunityShellLayout({
disabled={!isDesktop}
className={cn(
"min-h-0 flex-1",
- !isDesktop && !(isMobileDetail && preserveHiddenMobileModules) && [
+ !isDesktop && [
"max-sm:*:data-[mobile-active=true]:flex-1!",
"max-sm:*:data-[mobile-hidden=true]:flex-none!",
"max-sm:*:data-[mobile-hidden=true]:w-0!",
@@ -453,7 +449,7 @@ export function CommunityShellLayout({
ref={sidebarPanelRef}
data-slot="community-sidebar-panel-content"
data-community-mobile-surface={isMobileList ? "list" : undefined}
- hidden={isMobileDetail && !preserveHiddenMobileModules}
+ hidden={isMobileDetail}
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
deleted file mode 100644
index a2c4bf3fd..000000000
--- a/src/web/src/components/community/shell/mobile-back-motion.module.css
+++ /dev/null
@@ -1,26 +0,0 @@
-@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 f38ebf117..f50825576 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
@@ -793,10 +793,10 @@ describe("ShellFrameView", () => {
const detailSidebar = renderer.container.querySelector(
'[data-slot="community-sidebar-panel-content"]',
)!
- expect(detailSidebar).not.toHaveAttribute("hidden")
+ expect(detailSidebar).toHaveAttribute("hidden")
expect(detailSidebar).toHaveAttribute("inert")
expect(detailSidebar).toHaveAttribute("aria-hidden", "true")
- expect(renderer.container.querySelector('[data-mobile-back-surface="detail"]'))
+ expect(renderer.container.querySelector('[data-slot="community-shell-root"]'))
.not.toHaveAttribute("data-mobile-back-phase")
})
diff --git a/src/web/src/components/community/shell/shell-frame.tsx b/src/web/src/components/community/shell/shell-frame.tsx
index e348280b1..bc254128d 100644
--- a/src/web/src/components/community/shell/shell-frame.tsx
+++ b/src/web/src/components/community/shell/shell-frame.tsx
@@ -315,9 +315,6 @@ const [committedFrame, setCommittedFrame] = useAtom(useCreateAtom(initialCommitt
}, [navigation, route.parentPath])
useNativeMobileBack({
- mobile: breakpoint === "mobile",
- 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 56a63fd5b..d847be477 100644
--- a/src/web/src/components/ui/native-back-layer.tsx
+++ b/src/web/src/components/ui/native-back-layer.tsx
@@ -21,18 +21,11 @@ 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, eligible = () => true) {
@@ -51,7 +44,6 @@ 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) {
@@ -68,7 +60,6 @@ function startClosing(owner: BackOwner, element: HTMLElement) {
}
current.element = element
current.phase = "closing"
- changed(element.ownerDocument)
}
function isDescendant(owner: BackOwner, parent: BackOwner) {
@@ -98,10 +89,6 @@ function topNativeBackOwner(document: Document) {
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"
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
deleted file mode 100644
index 75306a559..000000000
--- a/src/web/src/hooks/community/use-native-mobile-back-motion-owners.dom.test.tsx
+++ /dev/null
@@ -1,176 +0,0 @@
-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 })) })
-}
-
-function transition(root: HTMLElement) {
- const target = root.querySelector<HTMLElement>('[data-panel][id="main"]')!
- const event = new Event("transitionend", { bubbles: true })
- Object.defineProperty(event, "propertyName", { value: "transform" })
- act(() => { target.dispatchEvent(event) })
-}
-
-const roots: HTMLElement[] = []
-function setup() {
- vi.useFakeTimers()
- const root = document.createElement("div")
- root.dataset.mobileBackSurface = "detail"
- Object.defineProperty(root, "clientWidth", { value: 390 })
- const foreground = document.createElement("div")
- foreground.dataset.panel = "true"
- foreground.id = "main"
- root.appendChild(foreground)
- 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(kind === "touch" ? undefined : "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) })
- transition(root)
- expect(props.request).not.toHaveBeenCalled()
- expect(props.replace).not.toHaveBeenCalled()
- expect(root.hasAttribute("data-mobile-back-phase")).toBe(false)
- back()
- act(() => { vi.advanceTimersByTime(200) })
- transition(root)
- expect(props.replace).toHaveBeenCalledExactlyOnceWith("/c/me")
- view.unmount()
- })
-
- it("does not use the settling timer to close a new real popup", () => {
- const { root, props, view } = setup()
- touch("touchstart", 10); touch("touchmove", 200); touch("touchend", 200)
- view.rerender(<Fixture {...props} owner />)
- act(() => { vi.advanceTimersByTime(300) })
- transition(root)
- 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 bb8767396..31d45be91 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,7 +4,6 @@ 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"
@@ -281,398 +280,26 @@ describe("useNativeMobileBack", () => {
})
})
-function touch(type: string, x: number, y = 100, count = 1, cancelable = true) {
- const points = Array.from({ length: count }, (_, identifier) => ({ identifier, clientX: x, clientY: y }))
- const event = new Event(type, { bubbles: true, cancelable })
- Object.defineProperties(event, {
- touches: { value: type === "touchend" ? [] : points },
- changedTouches: { value: points },
- })
- document.dispatchEvent(event)
- return event
-}
-
-function mobileHarness(parentPath: string | null = "/c/channels/s1") {
- const props = { mobile: true, gestureKey: "channel-1", parentPath, replacePath: vi.fn(), dismissShellOverlay: vi.fn(() => false) }
- return { props, renderer: render(createElement(Harness, props)) }
-}
-
-function transition(target: HTMLElement, type = "transitionend", propertyName = "transform") {
- const event = new Event(type, { bubbles: true })
- Object.defineProperty(event, "propertyName", { value: propertyName })
- act(() => { target.dispatchEvent(event) })
-}
-
-describe("mobile edge parent gesture", () => {
- it("replaces the parent once at the shared edge boundary, on release only", () => {
- const { props, renderer } = mobileHarness()
- touch("touchstart", 24)
- expect(touch("touchmove", 100).defaultPrevented).toBe(true)
- expect(props.replacePath).not.toHaveBeenCalled()
- touch("touchend", 100)
- touch("touchend", 100)
- expect(props.replacePath).toHaveBeenCalledExactlyOnceWith("/c/channels/s1")
- renderer.unmount()
- })
-
- it.each([
- [25, 110, 100, 110, 100],
- [0, 63, 100, 63, 100],
- [12, 8, 125, 100, 130],
- [12, 0, 100, 100, 100],
- [12, 100, 100, 20, 100],
- [12, 100, 100, 100, 220],
- ])("rejects outside/short/vertical/left/reversed/diagonal (%s,%s,%s,%s,%s)", (start, moveX, moveY, endX, endY) => {
- const { props, renderer } = mobileHarness()
- touch("touchstart", start)
- touch("touchmove", moveX, moveY)
- touch("touchend", endX, endY)
- expect(props.replacePath).not.toHaveBeenCalled()
- renderer.unmount()
- })
-
- it("leaves vertical edge scrolling and taps uncancelled", () => {
- const { props, renderer } = mobileHarness()
- expect(touch("touchstart", 10).defaultPrevented).toBe(false)
- expect(touch("touchmove", 12, 130).defaultPrevented).toBe(false)
- expect(touch("touchend", 12, 150).defaultPrevented).toBe(false)
- expect(props.replacePath).not.toHaveBeenCalled()
- renderer.unmount()
- })
-
- it.each(["touchcancel", "multitouch", "browser-scroll", "route", "desktop", "unmount"])("cancels on %s", (reason) => {
- const { props, renderer } = mobileHarness()
- touch("touchstart", 10)
- touch("touchmove", 100)
- if (reason === "touchcancel") touch("touchcancel", 100)
- if (reason === "browser-scroll") touch("touchmove", 110, 100, 1, false)
- if (reason === "multitouch") touch("touchmove", 100, 100, 2)
- if (reason === "route") renderer.rerender(createElement(Harness, { ...props, gestureKey: "channel-2" }))
- if (reason === "desktop") renderer.rerender(createElement(Harness, { ...props, mobile: false }))
- if (reason === "unmount") renderer.unmount()
- touch("touchend", 120)
- expect(props.replacePath).not.toHaveBeenCalled()
- if (reason !== "unmount") renderer.unmount()
- })
-
- it("rejects a multi-finger start and consumes native back at the picker", () => {
- const { props, renderer } = mobileHarness(null)
- touch("touchstart", 10, 100, 2)
- expect(touch("touchmove", 100).defaultPrevented).toBe(false)
- touch("touchend", 100)
- touch("touchstart", 10)
- touch("touchmove", 100)
- touch("touchend", 100)
- expect(dispatchBack().defaultPrevented).toBe(true)
- expect(props.replacePath).not.toHaveBeenCalled()
- renderer.unmount()
- })
-
- it("dismisses overlays before a parent navigation", () => {
- const { props, renderer } = mobileHarness()
- props.dismissShellOverlay.mockReturnValue(true)
- touch("touchstart", 10)
- touch("touchmove", 100)
- touch("touchend", 100)
- expect(props.dismissShellOverlay).toHaveBeenCalledOnce()
- expect(props.replacePath).not.toHaveBeenCalled()
- 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 })
- const foreground = document.createElement("div")
- foreground.dataset.panel = "true"
- foreground.id = "main"
- root.appendChild(foreground)
- document.body.append(root)
- roots.push(root)
- return { ...mobileHarness(), root, foreground }
- }
- afterEach(() => {
- roots.splice(0).forEach((root) => root.remove())
- vi.useRealTimers()
- vi.unstubAllGlobals()
- vi.restoreAllMocks()
- })
-
- it.each(["Web", "Native"])("keeps iOS %s touch painting and completes once after release", (platform) => {
- vi.useFakeTimers()
- vi.spyOn(navigator, "userAgent", "get").mockReturnValue("Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X)")
- if (platform === "Native") vi.stubGlobal("__TAURI__", {})
- const { root, foreground, props, renderer } = mounted()
- touch("touchstart", 10)
- touch("touchmove", 70)
- expect(root.style.getPropertyValue("--mobile-back-x")).toBe(platform === "Native" ? "60px" : "")
- expect(root.dataset.mobileBackPhase).toBe(platform === "Native" ? "dragging" : undefined)
- touch("touchmove", 180)
- expect(root.style.getPropertyValue("--mobile-back-x")).toBe(platform === "Native" ? "170px" : "")
- expect(root.style.getPropertyValue("--mobile-back-progress")).toBe(platform === "Native" ? `${170 / 390}` : "")
- expect(root.dataset.mobileBackPhase).toBe(platform === "Native" ? "dragging" : undefined)
- expect(props.replacePath).not.toHaveBeenCalled()
- touch("touchend", 180)
- expect(root.style.getPropertyValue("--mobile-back-x")).toBe("390px")
- expect(root.dataset.mobileBackPhase).toBe("settling")
- if (platform === "Native") transition(foreground)
- touch("touchstart", 10)
- touch("touchend", 180)
- vi.advanceTimersByTime(199)
- expect(props.replacePath).not.toHaveBeenCalled()
- vi.advanceTimersByTime(1)
- if (platform === "Web") {
- expect(props.replacePath).not.toHaveBeenCalled()
- transition(foreground)
- }
- expect(props.replacePath).toHaveBeenCalledExactlyOnceWith("/c/channels/s1")
- expect(root.dataset.mobileBackPhase).toBe("committing")
- renderer.unmount()
- expect(root.style.getPropertyValue("--mobile-back-x")).toBe("")
- })
-
- it.each(["Web", "Native"])("leaves Android %s edge touch to the platform while retaining public Back", (platform) => {
- vi.useFakeTimers()
- vi.spyOn(navigator, "userAgent", "get").mockReturnValue("Mozilla/5.0 (Linux; Android 16)")
- if (platform === "Native") vi.stubGlobal("__TAURI__", {})
- const { root, foreground, props } = mounted()
- touch("touchstart", 10)
- expect(touch("touchmove", 200).defaultPrevented).toBe(false)
- expect(touch("touchend", 200).defaultPrevented).toBe(false)
- touch("touchcancel", 200)
- expect(root.hasAttribute("data-mobile-back-phase")).toBe(false)
- expect(root.style.getPropertyValue("--mobile-back-x")).toBe("")
- expect(props.dismissShellOverlay).not.toHaveBeenCalled()
- expect(props.replacePath).not.toHaveBeenCalled()
-
- props.dismissShellOverlay.mockReturnValueOnce(true)
- dispatchBack()
- expect(props.dismissShellOverlay).toHaveBeenCalledOnce()
- expect(props.replacePath).not.toHaveBeenCalled()
- if (platform === "Native") {
- window.dispatchEvent(new CustomEvent(NATIVE_MOBILE_BACK_PROGRESS_EVENT, { detail: { progress: 0, started: true } }))
- window.dispatchEvent(new CustomEvent(NATIVE_MOBILE_BACK_PROGRESS_EVENT, { detail: { progress: 0.5 } }))
- expect(root.style.getPropertyValue("--mobile-back-x")).toBe("195px")
- }
- dispatchBack()
- expect(root.dataset.mobileBackPhase).toBe("settling")
- vi.advanceTimersByTime(200)
- if (platform === "Web") {
- expect(props.replacePath).not.toHaveBeenCalled()
- transition(foreground)
- }
- expect(props.replacePath).toHaveBeenCalledExactlyOnceWith("/c/channels/s1")
- })
-
- it("keeps settling across callback changes on the same committed route", () => {
- vi.useFakeTimers()
- const { foreground, props, renderer } = mounted()
- touch("touchstart", 10)
- touch("touchmove", 200)
- touch("touchend", 200)
+describe("removed page swipes", () => {
+ it.each(["iPhone", "Android WebView"])("leaves touch movements and old progress inert on %s while Back uses the latest parent", (userAgent) => {
+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue(userAgent)
const replacePath = vi.fn()
- renderer.rerender(createElement(Harness, { ...props, replacePath, dismissShellOverlay: () => false }))
- vi.advanceTimersByTime(200)
- expect(props.replacePath).not.toHaveBeenCalled()
- expect(replacePath).not.toHaveBeenCalled()
- transition(foreground)
- 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()
- vi.stubGlobal("__TAURI__", {})
- 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.each(["Web", "Native"])("cancels a short held %s drag without navigating", (platform) => {
- vi.useFakeTimers()
- if (platform === "Native") vi.stubGlobal("__TAURI__", {})
- 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(platform === "Native" ? "0px" : "")
- expect(root.dataset.mobileBackPhase).toBe(platform === "Native" ? "settling" : undefined)
- vi.advanceTimersByTime(200)
- expect(root.hasAttribute("data-mobile-back-phase")).toBe(false)
- expect(props.replacePath).not.toHaveBeenCalled()
- renderer.unmount()
- })
-
- it("accepts a new Web gesture immediately after touch cancellation", () => {
- vi.useFakeTimers()
- const { root, foreground, props } = mounted()
- touch("touchstart", 10)
- touch("touchmove", 200)
- touch("touchcancel", 200)
- expect(root.hasAttribute("data-mobile-back-phase")).toBe(false)
- touch("touchstart", 10)
- touch("touchmove", 200)
- touch("touchend", 200)
- expect(root.dataset.mobileBackPhase).toBe("settling")
- vi.advanceTimersByTime(200)
- expect(props.replacePath).not.toHaveBeenCalled()
- transition(foreground)
- expect(props.replacePath).toHaveBeenCalledExactlyOnceWith("/c/channels/s1")
- })
-
- it("waits for the foreground transform completion instead of elapsed timers or other transitions", () => {
- vi.useFakeTimers()
- const { root, foreground, props } = mounted()
- const child = document.createElement("button")
- foreground.appendChild(child)
- touch("touchstart", 10)
- touch("touchmove", 200)
- touch("touchend", 200)
- vi.advanceTimersByTime(1000)
- transition(foreground, "transitionend", "opacity")
- transition(child)
- window.dispatchEvent(new CustomEvent(NATIVE_MOBILE_BACK_PROGRESS_EVENT, { detail: { progress: 0, started: true } }))
- dispatchBack()
- touch("touchstart", 10)
- touch("touchmove", 200)
- touch("touchend", 200)
- expect(root.dataset.mobileBackPhase).toBe("settling")
- expect(props.replacePath).not.toHaveBeenCalled()
- transition(foreground)
- transition(foreground)
- expect(props.replacePath).toHaveBeenCalledExactlyOnceWith("/c/channels/s1")
- })
-
- it("uses the thread foreground completion instead of the containing main panel", () => {
- const { foreground, props } = mounted()
- const split = document.createElement("div")
- split.dataset.mobileBackThread = "true"
- const thread = document.createElement("div")
- thread.dataset.panel = "true"
- thread.id = "thread"
- split.appendChild(thread)
- foreground.appendChild(split)
- touch("touchstart", 10)
- touch("touchmove", 200)
- touch("touchend", 200)
- transition(foreground)
- expect(props.replacePath).not.toHaveBeenCalled()
- transition(thread)
- expect(props.replacePath).toHaveBeenCalledExactlyOnceWith("/c/channels/s1")
- })
-
- it("retires a cancelled Web transition and permits a new confirmed gesture", () => {
- const { root, foreground, props } = mounted()
- touch("touchstart", 10)
- touch("touchmove", 200)
- touch("touchend", 200)
- transition(foreground, "transitioncancel")
- transition(foreground)
- expect(root.hasAttribute("data-mobile-back-phase")).toBe(false)
- expect(props.replacePath).not.toHaveBeenCalled()
- touch("touchstart", 10)
- touch("touchmove", 200)
- touch("touchend", 200)
- transition(foreground)
- expect(props.replacePath).toHaveBeenCalledExactlyOnceWith("/c/channels/s1")
- })
-
- it("retains direct Back when no animatable foreground exists", () => {
- const { root, foreground, props } = mounted()
- foreground.remove()
- 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")
- })
-
- it.each(["touchcancel", "route", "resize", "background", "unmount"])("cancels queued navigation on %s", (reason) => {
- vi.useFakeTimers()
- const { root, foreground, 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()
+ const props = { parentPath: "/c/me", replacePath, dismissShellOverlay: () => false }
+ const renderer = render(createElement(Harness, props))
+ for (const [type, x, y] of [["touchstart", 8, 100], ["touchmove", 180, 102], ["touchend", 180, 102],
+ ["touchstart", 8, 100], ["touchmove", 10, 220], ["touchend", 10, 220]] as const) {
+ const points = [{ identifier: 1, clientX: x, clientY: y }]
+ const event = new Event(type, { bubbles: true, cancelable: true })
+ Object.defineProperties(event, { touches: { value: type === "touchend" ? [] : points }, changedTouches: { value: points } })
+ act(() => { document.dispatchEvent(event) })
+ expect(event.defaultPrevented).toBe(false)
}
- vi.advanceTimersByTime(300)
- transition(foreground)
- 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)
+ act(() => { window.dispatchEvent(new CustomEvent("alook:native-back-progress", { detail: { progress: 1, started: true } })) })
+ expect(replacePath).not.toHaveBeenCalled()
+ renderer.rerender(createElement(Harness, { ...props, parentPath: "/c/channels/new-parent" }))
+ act(() => { dispatchBack() })
+ expect(replacePath).toHaveBeenCalledExactlyOnceWith("/c/channels/new-parent")
renderer.unmount()
+ vi.restoreAllMocks()
})
})
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 082459d93..66cb71490 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,8 @@
import { useEffect, useLayoutEffect, useRef } from "react"
-import { isMobile, isTauri } from "@alook/shared"
-import { hasNativeBackOwner, NATIVE_BACK_OWNER_CHANGE_EVENT, requestNativeBack } from "@/components/ui/native-back-layer"
+import { isMobile } from "@alook/shared"
+import { 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,23 +12,17 @@ type TauriBackWindow = Window & {
}
export function useNativeMobileBack({
- mobile = false, gestureKey, dismissShellOverlay, parentPath, replacePath, animate = true,
+ dismissShellOverlay, parentPath, replacePath,
}: {
- 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 actions = useRef({ dismissShellOverlay, parentPath, replacePath })
const composing = useRef<EventTarget | null>(null)
- const interruptMotion = useRef<() => void>(() => {})
useLayoutEffect(() => {
- actions.current = { dismissShellOverlay, replacePath, animate }
- if (!animate) interruptMotion.current()
- }, [dismissShellOverlay, replacePath, animate])
+ actions.current = { dismissShellOverlay, parentPath, replacePath }
+ }, [dismissShellOverlay, parentPath, replacePath])
useEffect(() => {
if (!isMobile() || !/android/i.test(navigator.userAgent)) return
const app = (window as TauriBackWindow).__TAURI__?.app
@@ -80,201 +72,16 @@ export function useNativeMobileBack({
document.removeEventListener("focusout", end)
}
}, [])
- useLayoutEffect(() => {
- let root: HTMLElement | null = null
- let pageBlocked = false
- let nativeProgress = false
- let timer: ReturnType<typeof setTimeout> | undefined
- let stopSettling: (() => void) | 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
- stopSettling?.()
- stopSettling = 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) => {
- const waitForTransition = commit && !isTauri() && !nativeProgress
- gesture = null
- nativeProgress = false
- if (commit && (pageBlocked || occupied())) { reset(); return }
- const foreground = waitForTransition
- ? root?.querySelector<HTMLElement>('[data-mobile-back-thread] [data-panel][id="thread"]')
- ?? root?.querySelector<HTMLElement>('[data-panel][id="main"]')
- : null
- if (!root || reduced() || waitForTransition && !foreground) {
- 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")
- const finish = () => {
- timer = undefined
- stopSettling?.()
- stopSettling = undefined
- if (commit && parentPath && !pageBlocked && !occupied() && actions.current.animate) {
- root?.setAttribute("data-mobile-back-phase", "committing")
- actions.current.replacePath(parentPath)
- } else reset()
- }
- if (foreground) {
- const complete = (event: TransitionEvent) => {
- if (event.target !== foreground || event.propertyName !== "transform") return
- if (event.type === "transitionend") finish()
- else reset()
- }
- foreground.addEventListener("transitionend", complete)
- foreground.addEventListener("transitioncancel", complete)
- stopSettling = () => {
- foreground.removeEventListener("transitionend", complete)
- foreground.removeEventListener("transitioncancel", complete)
- }
- } else timer = setTimeout(finish, 200)
- }
- const paint = (x: number, follow = true) => {
- if (occupied() || !actions.current.animate) interrupt()
- if (!root || pageBlocked || !follow) 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)}`)
- }
+ useEffect(() => {
const handleBack = (event: Event) => {
if (!event.cancelable) return
event.preventDefault()
- const stale = nativeGesture.current === "stale"
- nativeGesture.current = null
- if (stale) { pageBlocked = false; return reset() }
- if (timer !== undefined || stopSettling || 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 || stopSettling || 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 && isTauri()) settle(false)
- else reset()
- }
- const start = (event: TouchEvent) => {
- if (timer !== undefined || stopSettling || 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
- 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
- if (!event.cancelable) return cancel()
- const touch = event.touches[0]
- if (event.touches.length !== 1 || touch.identifier !== gesture.id) return cancel()
- const dx = touch.clientX - gesture.x
- const dy = Math.abs(touch.clientY - gesture.y)
- if (!gesture.horizontal && Math.max(Math.abs(dx), dy) >= 8) {
- if (dx <= dy) return cancel()
- gesture.horizontal = true
- }
- 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)), isTauri())
- }
- const end = (event: TouchEvent) => {
- const current = gesture
- 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 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(); cancel() }
+ if (composing.current === document.activeElement) return
+ const { dismissShellOverlay, parentPath, replacePath } = actions.current
+ if (requestNativeBack(document) !== "none" || dismissShellOverlay()) return
+ if (parentPath) replacePath(parentPath)
}
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)
- if (!/android/i.test(navigator.userAgent)) {
- 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, parentPath])
+ return () => window.removeEventListener(NATIVE_MOBILE_BACK_EVENT, handleBack)
+ }, [])
}
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 d03754f3f..b36a99ac6 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
@@ -446,7 +446,7 @@ describe("useTimelineReadObserver", () => {
const row = makeRow("message-4")
const root = makeRoot([row])
const parent = document.createElement("section")
- parent.setAttribute("data-mobile-back-parent", "")
+ parent.setAttribute("data-thread-parent", "")
parent.setAttribute("inert", "")
parent.append(root)
useTestRender({ scrollRootEl: root })
diff --git a/src/web/src/hooks/community/use-read-observer.ts b/src/web/src/hooks/community/use-read-observer.ts
index abf57bc40..764495747 100644
--- a/src/web/src/hooks/community/use-read-observer.ts
+++ b/src/web/src/hooks/community/use-read-observer.ts
@@ -27,7 +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
+ if (scrollRootEl.closest("[data-thread-parent][inert]")) return false
const content = scrollRootEl.querySelector<HTMLElement>(MESSAGE_LIST_CONTENT_SELECTOR)
if (!content) return true
return content.getAttribute("aria-hidden") === "false"
@@ -291,7 +291,7 @@ export function useTimelineReadObserver({
childList: true,
subtree: true,
})
- const parentLayer = scrollRootEl.closest("[data-mobile-back-parent]")
+ const parentLayer = scrollRootEl.closest("[data-thread-parent]")
if (parentLayer) mutations?.observe(parentLayer, {
attributes: true, attributeFilter: ["inert"], attributeOldValue: true,
})
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 df7772030..eaa2827c0 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
@@ -104,7 +104,7 @@ async function expectHoverKeyboardSend({
async function expectExplicitTouchSend({
page,
root = page,
- backgroundRoot,
+ parentRoot,
route,
channelId,
label,
@@ -114,7 +114,7 @@ async function expectExplicitTouchSend({
}: {
page: Page
root?: Page | Locator
- backgroundRoot?: Locator
+ parentRoot?: Locator
route: string
channelId: string
label: string
@@ -172,11 +172,10 @@ async function expectExplicitTouchSend({
await expect(send).toBeVisible()
}
- if (backgroundRoot) {
- await expect(backgroundRoot).toHaveAttribute("inert", "")
- await expect(backgroundRoot.getByTestId(tid.composerFileInput)).toHaveCount(1)
+ if (parentRoot) {
+ await expect(parentRoot).toHaveCount(0)
await expect(root.getByTestId(tid.composerFileInput)).toHaveCount(1)
- await expect(page.getByTestId(tid.composerFileInput)).toHaveCount(2)
+ await expect(page.getByTestId(tid.composerFileInput)).toHaveCount(1)
}
await root.getByTestId(tid.composerFileInput).setInputFiles({
@@ -301,7 +300,7 @@ test.describe("composer send by input capability", () => {
await expectExplicitTouchSend({
page,
root: page.getByTestId(tid.threadSplitPanel),
- backgroundRoot: page.getByTestId(tid.threadSplitParent),
+ parentRoot: page.getByTestId(tid.threadSplitParent),
route: `/c/channels/${serverId}/${threadId}`,
channelId: threadId,
label: "thread",
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 09166ba49..f7a02c81e 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,7 +301,7 @@ 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("visibility", "hidden")
+ await expect(railContainer).toBeHidden()
await expect(railContainer).toHaveAttribute("inert", "")
await expect(railContainer).toHaveAttribute("aria-hidden", "true")
let lastMessageId = await sendMention(`Hidden Server digit ${stamp}`)
@@ -315,7 +315,7 @@ 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("visibility", "hidden")
+ await expect(railContainer).toBeHidden()
await expect(railContainer).toHaveAttribute("inert", "")
await expect(railContainer).toHaveAttribute("aria-hidden", "true")
lastMessageId = await sendMention(`Repeated hidden Server ${stamp} ${cycle}`)
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 0766c615f..f71cc44cd 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,7 @@ 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("visibility", "hidden")
+ await expect(overlay).toBeHidden()
await expect(overlay).toHaveAttribute("inert", "")
await expect(overlay).toHaveAttribute("aria-hidden", "true")
await send(hiddenId, `Hidden Inbox digit ${stamp}`)
@@ -367,7 +367,7 @@ 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("visibility", "hidden")
+ await expect(overlay).toBeHidden()
await expect(overlay).toHaveAttribute("inert", "")
await expect(overlay).toHaveAttribute("aria-hidden", "true")
await send(hiddenId, `Repeated hidden Inbox ${stamp} ${cycle}`)
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 b6fc4420d..3b1d664ce 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
@@ -317,7 +317,7 @@ async function installSsrLifecycleProbe(page: Page, surface: "list" | "detail")
}).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]'],
+ rail: ['[data-community-rail]', '[data-community-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]]) => {