Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(web): add mobile swipe navigation and dismissals

Gener77c9eed2a13e
diff --git a/package.json b/package.json
index 30c99e6ab..06f5c822f 100644
--- a/package.json
+++ b/package.json
@@ -64,7 +64,8 @@
"@vitest/snapshot": "4.1.11"
},
"patchedDependencies": {
- "@opennextjs/[email protected]": "patches/@[email protected]"
+ "@opennextjs/[email protected]": "patches/@[email protected]",
+ "@base-ui/[email protected]": "patches/@[email protected]"
},
"onlyBuiltDependencies": [
"better-sqlite3",
diff --git a/patches/@[email protected] b/patches/@[email protected]
new file mode 100644
index 000000000..25a425962
--- /dev/null
+++ b/patches/@[email protected]
@@ -0,0 +1,110 @@
+diff --git a/dialog/portal/DialogPortal.d.mts b/dialog/portal/DialogPortal.d.mts
+index 299ffafd74f728fd83b5400ee8125649c4ba8ad7..4cc3ae5ae3e86b7a11a63b6ed2c957a4fbc15596 100644
+--- a/dialog/portal/DialogPortal.d.mts
++++ b/dialog/portal/DialogPortal.d.mts
+@@ -15,6 +15,12 @@ export interface DialogPortalProps extends BaseUIComponentProps<'div', DialogPor
+ * @default false
+ */
+ keepMounted?: boolean | undefined;
++ /**
++ * Render children in place without a portal or portal element.
++ * Only applies to non-modal roots.
++ * @default false
++ */
++ inline?: boolean | undefined;
+ /**
+ * A parent element to render the portal element into.
+ */
+diff --git a/dialog/portal/DialogPortal.d.ts b/dialog/portal/DialogPortal.d.ts
+index 0e6ff01c744b9377705b8e9a7a5e6780fb14aa8f..dc457ee4e9175bf4941ae562168b49b75d6ae753 100644
+--- a/dialog/portal/DialogPortal.d.ts
++++ b/dialog/portal/DialogPortal.d.ts
+@@ -15,6 +15,12 @@ export interface DialogPortalProps extends BaseUIComponentProps<'div', DialogPor
+ * @default false
+ */
+ keepMounted?: boolean | undefined;
++ /**
++ * Render children in place without a portal or portal element.
++ * Only applies to non-modal roots.
++ * @default false
++ */
++ inline?: boolean | undefined;
+ /**
+ * A parent element to render the portal element into.
+ */
+diff --git a/dialog/portal/DialogPortal.js b/dialog/portal/DialogPortal.js
+index 9ffd479ee89beb4e0f7140174e4b1b15cc28a5f9..ad8fa8995bc5c0fb9a2846e8534e5e7f3c26f3f8 100644
+--- a/dialog/portal/DialogPortal.js
++++ b/dialog/portal/DialogPortal.js
+@@ -22,6 +22,7 @@ var _jsxRuntime = require("react/jsx-runtime");
+ */const DialogPortal = exports.DialogPortal = /*#__PURE__*/React.forwardRef(function DialogPortal(props, forwardedRef) {
+ const {
+ keepMounted = false,
++ inline = false,
+ ...portalProps
+ } = props;
+ const store = (0, _DialogRootContext.useDialogRootContext)();
+@@ -34,7 +35,7 @@ var _jsxRuntime = require("react/jsx-runtime");
+ }
+ return /*#__PURE__*/(0, _jsxRuntime.jsx)(_DialogPortalContext.DialogPortalContext.Provider, {
+ value: keepMounted,
+- children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_floatingUiReact.FloatingPortal, {
++ children: inline && modal === false ? props.children : /*#__PURE__*/(0, _jsxRuntime.jsxs)(_floatingUiReact.FloatingPortal, {
+ ref: forwardedRef,
+ ...portalProps,
+ children: [mounted && modal === true && /*#__PURE__*/(0, _jsxRuntime.jsx)(_InternalBackdrop.InternalBackdrop, {
+diff --git a/dialog/portal/DialogPortal.mjs b/dialog/portal/DialogPortal.mjs
+index 014516e7ea01c271ee3c8806d79a5b89b03bd2eb..256c75dde42b05b7a16be5c980aacd7589389938 100644
+--- a/dialog/portal/DialogPortal.mjs
++++ b/dialog/portal/DialogPortal.mjs
+@@ -18,6 +18,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
+ export const DialogPortal = /*#__PURE__*/React.forwardRef(function DialogPortal(props, forwardedRef) {
+ const {
+ keepMounted = false,
++ inline = false,
+ ...portalProps
+ } = props;
+ const store = useDialogRootContext();
+@@ -30,7 +31,7 @@ export const DialogPortal = /*#__PURE__*/React.forwardRef(function DialogPortal(
+ }
+ return /*#__PURE__*/_jsx(DialogPortalContext.Provider, {
+ value: keepMounted,
+- children: /*#__PURE__*/_jsxs(FloatingPortal, {
++ children: inline && modal === false ? props.children : /*#__PURE__*/_jsxs(FloatingPortal, {
+ ref: forwardedRef,
+ ...portalProps,
+ children: [mounted && modal === true && /*#__PURE__*/_jsx(InternalBackdrop, {
+diff --git a/drawer/portal/DrawerPortal.d.mts b/drawer/portal/DrawerPortal.d.mts
+index a0b67c78622dbbcf5ac27d9e83a0cf82a8ddf95d..653a7c74f510614d2815596e486e574a84367cab 100644
+--- a/drawer/portal/DrawerPortal.d.mts
++++ b/drawer/portal/DrawerPortal.d.mts
+@@ -15,6 +15,12 @@ export interface DrawerPortalProps extends BaseUIComponentProps<'div', DrawerPor
+ * @default false
+ */
+ keepMounted?: boolean | undefined;
++ /**
++ * Render children in place without a portal or portal element.
++ * Only applies to non-modal roots.
++ * @default false
++ */
++ inline?: boolean | undefined;
+ /**
+ * A parent element to render the portal element into.
+ */
+diff --git a/drawer/portal/DrawerPortal.d.ts b/drawer/portal/DrawerPortal.d.ts
+index e30194f7cbd0d0760df06f4e2893c0830f595fb4..b7a92f62266ba8b19226ad5ee3f327eed91a5c10 100644
+--- a/drawer/portal/DrawerPortal.d.ts
++++ b/drawer/portal/DrawerPortal.d.ts
+@@ -15,6 +15,12 @@ export interface DrawerPortalProps extends BaseUIComponentProps<'div', DrawerPor
+ * @default false
+ */
+ keepMounted?: boolean | undefined;
++ /**
++ * Render children in place without a portal or portal element.
++ * Only applies to non-modal roots.
++ * @default false
++ */
++ inline?: boolean | undefined;
+ /**
+ * A parent element to render the portal element into.
+ */
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index cf4c23d8b..af82ba222 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -9,6 +9,9 @@ overrides:
'@vitest/snapshot': 4.1.11
patchedDependencies:
+ '@base-ui/[email protected]':
+ hash: 51d33f6e4f128a90fe02d40ba5c0f2cd5614eabbab780845f28186dc473cab0a
+ path: patches/@[email protected]
'@opennextjs/[email protected]':
hash: cb9094d9ddd1702fff24915cbb952868b0a9f30762cf972213ec5fc02a98f07f
path: patches/@[email protected]
@@ -270,7 +273,7 @@ importers:
version: 2.1.0
'@base-ui/react':
specifier: ^1.9.0
+ version: 1.9.0(patch_hash=51d33f6e4f128a90fe02d40ba5c0f2cd5614eabbab780845f28186dc473cab0a)(@date-fns/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])
'@dnd-kit/core':
specifier: ^6.3.1
@@ -10483,7 +10486,7 @@ snapshots:
'@babel/helper-string-parser': 7.29.7
'@babel/helper-validator-identifier': 7.29.7
+ '@base-ui/[email protected](patch_hash=51d33f6e4f128a90fe02d40ba5c0f2cd5614eabbab780845f28186dc473cab0a)(@date-fns/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])':
dependencies:
'@babel/runtime': 8.0.7
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..d8f15c4eb 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
@@ -21,6 +21,11 @@ class MainActivity : TauriActivity() {
private var isReady = false
private var mainWebView: WebView? = null
+ private var systemGestureInsets: Insets? = null
+ @Volatile private var systemGestureRegionJson = "null"
+ private val gestureLayoutListener = View.OnLayoutChangeListener { _, _, _, _, _, _, _, _, _ ->
+ syncSystemGestureRegion()
+ }
private var startupAttachListener: View.OnAttachStateChangeListener? = null
private val mobileShareImageDocumentOwner = MobileShareImageDocumentOwner(this)
@@ -69,7 +74,9 @@ class MainActivity : TauriActivity() {
val imeInsets = insets.getInsets(imeType)
val imeVisible = insets.isVisible(imeType)
val bottomPadding = if (imeVisible) imeInsets.bottom else chromeInsets.bottom
+ systemGestureInsets = insets.getInsets(WindowInsetsCompat.Type.systemGestures())
v.setPadding(chromeInsets.left, chromeInsets.top, chromeInsets.right, bottomPadding)
+ syncSystemGestureRegion()
WindowInsetsCompat.Builder(insets)
.setInsets(chromeTypes, Insets.NONE)
.setInsets(imeType, Insets.of(imeInsets.left, imeInsets.top, imeInsets.right, 0))
@@ -84,7 +91,9 @@ class MainActivity : TauriActivity() {
override fun onDestroy() {
clearStartupAttachListener()
+ mainWebView?.removeOnLayoutChangeListener(gestureLayoutListener)
mainWebView = null
+ systemGestureRegionJson = "null"
mobileShareImageDocumentOwner.detach()
super.onDestroy()
}
@@ -92,12 +101,16 @@ class MainActivity : TauriActivity() {
override fun onWebViewCreate(webView: WebView) {
super.onWebViewCreate(webView)
clearStartupAttachListener()
+ mainWebView?.removeOnLayoutChangeListener(gestureLayoutListener)
mainWebView = webView
+ webView.addOnLayoutChangeListener(gestureLayoutListener)
+ syncSystemGestureRegion()
if (!isReady && !isDestroyed && !isFinishing) {
val listener = object : View.OnAttachStateChangeListener {
override fun onViewAttachedToWindow(view: View) {
if (view !== mainWebView || isDestroyed || isFinishing) return
isReady = true
+ syncSystemGestureRegion()
clearStartupAttachListener()
}
override fun onViewDetachedFromWindow(view: View) {}
@@ -113,6 +126,20 @@ class MainActivity : TauriActivity() {
}
}
+ private fun syncSystemGestureRegion() {
+ val webView = mainWebView ?: return
+ val insets = systemGestureInsets ?: ViewCompat.getRootWindowInsets(webView)
+ ?.getInsets(WindowInsetsCompat.Type.systemGestures()) ?: return
+ val root = webView.rootView
+ val location = IntArray(2)
+ val rootLocation = IntArray(2)
+ webView.getLocationInWindow(location)
+ root.getLocationInWindow(rootLocation)
+ systemGestureRegionJson = SystemGestureRegion.fromWindow(
+ root.width, location[0] - rootLocation[0], webView.width, insets.left, insets.right,
+ )?.toJson() ?: "null"
+ }
+
private fun clearStartupAttachListener() {
startupAttachListener?.let { mainWebView?.removeOnAttachStateChangeListener(it) }
startupAttachListener = null
@@ -133,6 +160,9 @@ class MainActivity : TauriActivity() {
}
class ThemeBridge(private val activity: MainActivity) {
+ @JavascriptInterface
+ fun getSystemGestureRegion(): String = activity.systemGestureRegionJson
+
@JavascriptInterface
fun setWindowTheme(dark: Boolean) {
activity.applyWindowTheme(dark)
diff --git a/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/SystemGestureRegion.kt b/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/SystemGestureRegion.kt
new file mode 100644
index 000000000..2245a7d09
--- /dev/null
+++ b/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/SystemGestureRegion.kt
@@ -0,0 +1,16 @@
+package ai.alook.android
+
+data class SystemGestureRegion(val left: Int, val right: Int, val width: Int) {
+ fun toJson(): String = "{\"left\":$left,\"right\":$right,\"width\":$width}"
+
+ companion object {
+ fun fromWindow(windowWidth: Int, viewLeft: Int, viewWidth: Int, left: Int, right: Int): SystemGestureRegion? {
+ if (windowWidth <= 0 || viewWidth <= 0) return null
+ return SystemGestureRegion(
+ (left - viewLeft).coerceIn(0, viewWidth),
+ (viewLeft + viewWidth - (windowWidth - right)).coerceIn(0, viewWidth),
+ viewWidth,
+ )
+ }
+ }
+}
diff --git a/src/desktop/src-tauri/gen/android/app/src/test/java/ai/alook/android/SystemGestureRegionTest.kt b/src/desktop/src-tauri/gen/android/app/src/test/java/ai/alook/android/SystemGestureRegionTest.kt
new file mode 100644
index 000000000..5e60c6b5e
--- /dev/null
+++ b/src/desktop/src-tauri/gen/android/app/src/test/java/ai/alook/android/SystemGestureRegionTest.kt
@@ -0,0 +1,23 @@
+package ai.alook.android
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Test
+
+class SystemGestureRegionTest {
+ @Test
+ fun mapsWindowEdgesIntoTheActualWebView() {
+ assertEquals(SystemGestureRegion(24, 36, 1080), SystemGestureRegion.fromWindow(1080, 0, 1080, 24, 36))
+ assertEquals(SystemGestureRegion(0, 12, 1016), SystemGestureRegion.fromWindow(1080, 40, 1016, 24, 36))
+ assertEquals(SystemGestureRegion(48, 60, 2400), SystemGestureRegion.fromWindow(2400, 0, 2400, 48, 60))
+ assertEquals(SystemGestureRegion(0, 0, 1080), SystemGestureRegion.fromWindow(1080, 0, 1080, 0, 0))
+ }
+
+ @Test
+ fun rejectsUnlaidOutViewsAndClampsConsumedEdges() {
+ assertNull(SystemGestureRegion.fromWindow(0, 0, 1080, 24, 24))
+ assertNull(SystemGestureRegion.fromWindow(1080, 0, 0, 24, 24))
+ assertEquals(SystemGestureRegion(100, 0, 100), SystemGestureRegion.fromWindow(1080, 0, 100, 200, 24))
+ assertEquals("{\"left\":24,\"right\":36,\"width\":1080}", SystemGestureRegion(24, 36, 1080).toJson())
+ }
+}
diff --git a/src/web/scripts/opennext-wrangler-config.test.ts b/src/web/scripts/opennext-wrangler-config.test.ts
index 1ca2bf78e..36449ba03 100644
--- a/src/web/scripts/opennext-wrangler-config.test.ts
+++ b/src/web/scripts/opennext-wrangler-config.test.ts
@@ -50,6 +50,7 @@ describe("OpenNext and Wrangler refresh", () => {
const rootManifest = readPackage("package.json")
expect(rootManifest.pnpm?.patchedDependencies).toEqual({
+ "@base-ui/[email protected]": "patches/@[email protected]",
"@opennextjs/[email protected]": "patches/@[email protected]",
})
expect(existsSync(new URL("patches/@[email protected]", repositoryRoot))).toBe(false)
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 8681dd23a..dbb96c98d 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
@@ -15,6 +15,8 @@ import type { ConversationNavigationTarget } from "@/lib/community/conversation-
import { useCommunityRuntime } from "@/stores/community/runtime"
import { runAuthoritativeServerEject } from "@/lib/community/eject-server"
import ServerLayout from "@/app/c/channels/layout"
+import { channelSchema } from "@/lib/community-db/schema"
+import { conversationEntryFixture } from "@/test/conversation-entry-fixtures"
const {
mockRouteModel,
@@ -66,7 +68,7 @@ const {
mockCanManageServer: vi.fn((role?: string | null) => role === "owner" || role === "admin"),
mockDismissConversation: vi.fn(),
mockParentMetadata: { identityKnown: false, canRead: false, status: "pending", retrying: false, retry: vi.fn() },
- mockNavigation: { entryIntent: null as { href: string } | null, push: vi.fn(), navigationPending: false, pendingHref: null as string | null },
+ mockNavigation: { entryIntent: null as { href: string; resume?: boolean } | null, push: vi.fn(), navigationPending: false, pendingHref: null as string | null },
mockPathname: { value: "/c/channels/server_1/channel_1" },
mockViewerId: { value: "viewer_1" },
mockClaimSecondary: vi.fn(),
@@ -129,14 +131,15 @@ vi.mock("next/navigation", () => ({
}))
vi.mock("@/components/community/shell/community-route-context", async (importOriginal) => ({
...await importOriginal<typeof import("@/components/community/shell/community-route-context")>(),
- useCommunityRouteFrame: () => ({ navigation: mockNavigation, breakpoint: mockBreakpoint.value }),
+ useCommunityRouteFrame: () => ({ navigation: mockNavigation, breakpoint: mockBreakpoint.value, frame: { revision: 0 } }),
}))
vi.mock("@/hooks/community/use-channel-metadata", () => ({
useChannelMetadata: (...args: unknown[]) => { mockUseChannelMetadata(...args); return mockParentMetadata },
}))
vi.mock("sonner", () => ({ toast: vi.fn() }))
vi.mock("@/lib/api/client", () => ({ apiFetch: vi.fn(), toastApiError: vi.fn() }))
-vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => mockBreakpoint.value }))
+vi.mock("@/hooks/use-mobile", () => ({
+ useIsMobile: () => mockBreakpoint.value === "mobile", useBreakpoint: () => mockBreakpoint.value }))
vi.mock("@/hooks/community/thread-opener-read-handoff", () => ({
THREAD_OPENER_HANDOFF_PARAM: "inboxThreadOpener",
useClaimThreadOpenerReadHandoff: vi.fn(),
@@ -416,6 +419,7 @@ function useMockParentIdentity(props: Record<string, unknown>) {
describe("ChannelRoute message surface ownership", () => {
beforeEach(() => {
+ vi.mocked(useChannelRouteModel).mockImplementation(() => mockRouteModel)
mockUiHandlers.cancelPendingNavigation.mockClear()
mockNavigation.push.mockReset()
mockNavigation.navigationPending = false
@@ -474,6 +478,49 @@ describe("ChannelRoute message surface ownership", () => {
})
})
+ it("keeps the real mobile parent DOM, scroll and draft through child entry and pending resume", async () => {
+ const registry = renderCommunityHook(() => useOptionalCommunityDbRegistry()).result.current!
+ const parent = { ...mockRouteModel }
+ const child = { ...mockRouteModel, channel: null, parent: parent.channel,
+ currentChannelMeta: { id: "child_1", name: "Thread", parentChannelId: "channel_1", parentMessageId: "opener_1", creatorId: "viewer_1" },
+ isChild: true, isNotifyUnit: true, skeletonSubtype: "thread",
+ layoutHint: { subtype: "thread", parentChannelId: "channel_1", parentSubtype: "text" },
+ }
+ vi.mocked(useChannelRouteModel).mockImplementation((_server, _param, id) => (id === "channel_1" ? parent : child) as never)
+ const base = conversationEntryFixture().channel
+ registry.collections.channels.utils.writeUpsert([
+ channelSchema.parse({ ...base, id: "channel_1", serverId: "server_1", muted: false, unread: false, tags: [], pending: false, resourceComplete: true }),
+ channelSchema.parse({ ...base, id: "child_1", serverId: "server_1", type: "thread", parentChannelId: "channel_1", parentMessageId: "opener_1", muted: false, unread: false, tags: [], pending: false, resourceComplete: true }),
+ ])
+ mockBreakpoint.value = "mobile"
+ mockSearchParams.value = ""
+ mockedUseChannelMessageFeed.mockReturnValue(feed())
+ const node = (id: string, committed = true) => React.createElement(ChannelRoute, {
+ serverParam: "server_1", channelId: id, routeCommitted: committed,
+ })
+ const view = render(node("channel_1"))
+ await act(async () => { await vi.advanceTimersByTimeAsync(1) })
+ const composer = view.container.querySelector<HTMLTextAreaElement>('[data-draft-key="server_1/channel_1"]')!
+ const pane = composer.closest<HTMLElement>('[data-community-target-href]')!
+ pane.scrollTop = 184
+ fireEvent.change(composer, { target: { value: "Retained parent draft" } })
+ mockCurrentChannelId.value = "child_1"
+ view.rerender(node("child_1"))
+ await act(async () => { await vi.advanceTimersByTimeAsync(1) })
+ expect(view.container.querySelector('[data-draft-key="server_1/channel_1"]')).toBe(composer)
+ expect(composer.closest('[data-mobile-page-active="false"]')).toHaveAttribute("inert")
+ expect(pane.scrollTop).toBe(184)
+ mockNavigation.entryIntent = { href: "/c/channels/server_1/channel_1", resume: true }
+ view.rerender(node("channel_1", false))
+ expect(view.container.querySelector('[data-draft-key="server_1/channel_1"]')).toBe(composer)
+ expect(composer).toHaveValue("Retained parent draft")
+ expect(pane.scrollTop).toBe(184)
+ mockCurrentChannelId.value = "channel_1"
+ view.rerender(node("channel_1"))
+ expect(view.container.querySelector('[data-draft-key="server_1/channel_1"]')).toBe(composer)
+ expect(composer).toHaveValue("Retained parent draft")
+ })
+
it("keeps the operational opener gate outside pending child content", async () => {
configureThreadRoute()
mockRouteModel.routeLifecycle = "pending"
@@ -712,7 +759,7 @@ describe("ChannelRoute message surface ownership", () => {
renderer.unmount()
})
- it("keeps the same target slot through cold parent-hint and shared mobile resolution", () => {
+ it("keeps one cold loading target when mobile adopts its Drawer container", () => {
configureThreadRoute()
Object.assign(mockRouteModel, { currentChannelMeta: null, routeHydrated: false, routeLifecycle: "pending",
layoutHint: { subtype: "thread", parentChannelId: null, parentSubtype: "unknown" } })
@@ -720,7 +767,6 @@ describe("ChannelRoute message surface ownership", () => {
mockSplitMode.value = "pending"
const props = { serverParam: "server_1", channelId: "channel_1" }
const renderer = render(React.createElement(ChannelRoute, props))
- const outer = renderer.container.firstElementChild
const pane = screen.getByTestId("community-thread-split-panel")
const skeleton = pane.querySelector("[data-message-list-skeleton]")
expect(skeleton).not.toBeNull()
@@ -729,9 +775,10 @@ describe("ChannelRoute message surface ownership", () => {
mockBreakpoint.value = "mobile"
mockSplitMode.value = "full"
renderer.rerender(React.createElement(ChannelRoute, props))
- expect(renderer.container.firstElementChild).toBe(outer)
- expect(screen.getByTestId("community-thread-split-panel")).toBe(pane)
- expect(pane.querySelector("[data-message-list-skeleton]")).toBe(skeleton)
+ const mobilePane = screen.getByTestId("community-thread-split-panel")
+ expect(mobilePane.closest('[data-slot="mobile-page"]')).not.toBeNull()
+ expect(mobilePane.querySelector("[data-message-list-skeleton]")).not.toBeNull()
+ expect(screen.getAllByTestId("community-thread-split-panel")).toHaveLength(1)
expect(mockUseChannelMetadata).not.toHaveBeenCalled()
expect(mockClaimSecondary).not.toHaveBeenCalled()
expect(mockedUseChannelMessageFeed).not.toHaveBeenCalled()
@@ -1095,7 +1142,8 @@ describe("ChannelRoute message surface ownership", () => {
const renderer = render(React.createElement(ChannelRoute, props))
const outer = renderer.container.firstElementChild
expect(outer?.tagName).toBe("DIV")
- expect(mockSplitContainerRef).toHaveBeenCalledWith(outer)
+ const measurement = renderer.container.querySelector('[data-community-target-href]')
+ expect(mockSplitContainerRef).toHaveBeenCalledWith(measurement)
Object.assign(mockRouteModel, {
skeletonSubtype: "thread",
layoutHint: { subtype: "thread", parentChannelId: "parent_1", parentSubtype: "text" },
@@ -1483,7 +1531,7 @@ describe("ChannelRoute message surface ownership", () => {
)
fireEvent.click(screen.getByTestId("community-thread-split-close"))
- expect(mockUiHandlers.replacePath).toHaveBeenCalledWith("/c/channels/server_1/parent_1")
+ expect(mockUiHandlers.goBackMobile).toHaveBeenCalledWith("/c/channels/server_1/parent_1")
})
it("uses the same split parent contract for a forum post", async () => {
@@ -1665,7 +1713,7 @@ describe("ChannelRoute message surface ownership", () => {
)
})
- it("replaces directly to the verified parent from the child Back control", async () => {
+ it("requests the verified parent through the shared Back control", async () => {
configureThreadRoute()
mockBreakpoint.value = "mobile"
mockedUseChannelMessageFeed.mockImplementation(() => feed({ anchorInCache: true }))
@@ -1677,13 +1725,13 @@ describe("ChannelRoute message surface ownership", () => {
})
act(() => mockHeaderParentNavigate.current?.())
- expect(mockUiHandlers.replacePath).toHaveBeenCalledWith(
+ expect(mockUiHandlers.goBackMobile).toHaveBeenCalledWith(
"/c/channels/server_1/parent_1",
)
- expect(mockUiHandlers.goBackMobile).not.toHaveBeenCalled()
+ expect(mockUiHandlers.replacePath).not.toHaveBeenCalled()
})
- it("replaces directly to the canonical server root from a top-level channel", async () => {
+ it("requests the canonical server root through the shared Back control", async () => {
mockBreakpoint.value = "mobile"
mockedUseChannelMessageFeed.mockImplementation(() => feed())
@@ -1694,10 +1742,10 @@ describe("ChannelRoute message surface ownership", () => {
})
act(() => mockHeaderServerNavigate.current?.())
- expect(mockUiHandlers.replacePath).toHaveBeenCalledWith(
+ expect(mockUiHandlers.goBackMobile).toHaveBeenCalledWith(
"/c/channels/server_1",
)
- expect(mockUiHandlers.goBackMobile).not.toHaveBeenCalled()
+ expect(mockUiHandlers.replacePath).not.toHaveBeenCalled()
})
it("keeps a child target through warm cache and 5000ms until MessageList consumes it", async () => {
diff --git a/src/web/src/components/community/channels/channel-route.tsx b/src/web/src/components/community/channels/channel-route.tsx
index a050f00d8..72fba6503 100644
--- a/src/web/src/components/community/channels/channel-route.tsx
+++ b/src/web/src/components/community/channels/channel-route.tsx
@@ -2,7 +2,7 @@
import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, type ComponentProps } from "react"
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ComponentProps } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { toastApiError } from "@/lib/api/client"
import { ChannelHeaderSkeleton, type ChannelNotifLevel } from "@/components/community/channels/channel-header"
@@ -37,6 +37,9 @@ import { useThreadSplitMode } from "@/hooks/community/use-thread-split-mode"
import { useCommunityWsStore } from "@/stores/community/ws"
import { resolveConversationSubtype } from "@/lib/community/conversation-subtype"
import { isConversationAccessError } from "@/lib/community/conversation-read"
+import { MobilePage } from "@/components/community/shell/mobile-page"
+import { ConversationActivityContext, useConversationActivity } from "@/contexts/community/conversation-activity"
+import { useRouteChannelProjection } from "@/lib/community-db/projections"
import { useNativeSystemNotificationConversationDismissal } from "@/hooks/community/use-native-system-notifications"
const THREAD_VIEW_PARAM = "threadView"
@@ -48,15 +51,47 @@ type RouteTarget = {
searchParams: URLSearchParams
routeCommitted: boolean
anchorMessageId: string | null
+ resume: boolean
routeModel: ReturnType<typeof useChannelRouteModel>
currentUser: ReturnType<typeof useCurrentUser>
}
-export function ChannelRoute({ serverParam, channelId, targetHref, routeCommitted = true }: {
+type ChannelRouteProps = {
serverParam: string
channelId: string
targetHref?: string
routeCommitted?: boolean
+}
+
+export function ChannelRoute(props: ChannelRouteProps) {
+ return <MobileChannelRoutes {...props} />
+}
+
+function MobileChannelRoutes(props: ChannelRouteProps) {
+ const { breakpoint } = useCommunityRouteFrame()
+ const [mobileSeen, setMobileSeen] = useState(breakpoint === "mobile")
+ if (breakpoint === "mobile" && !mobileSeen) setMobileSeen(true)
+ const [initialId, setInitialId] = useState(props.channelId)
+ if (!mobileSeen && breakpoint !== "mobile" && initialId !== props.channelId) setInitialId(props.channelId)
+ const identity = useRouteChannelProjection(props.channelId)
+ const parentId = identity?.parentChannelId
+ const [retained, setRetained] = useState({ current: props.channelId, previous: null as string | null })
+ if (retained.current !== props.channelId) setRetained({ current: props.channelId, previous: retained.current })
+ const previous = retained.current !== props.channelId ? retained.current : retained.previous
+ const backgroundId = mobileSeen || breakpoint === "mobile" ? parentId ?? (identity === undefined ? previous : null) : null
+ const ids = backgroundId && backgroundId !== props.channelId ? [backgroundId, props.channelId] : [props.channelId]
+ return <>{ids.map(id => <ConversationActivityContext key={!mobileSeen && breakpoint !== "mobile" || id === initialId ? "initial" : id} value={id === props.channelId && (!mobileSeen && breakpoint !== "mobile" || props.routeCommitted !== false)}>
+ <ChannelRouteLayer {...props} channelId={id} foreground={id === props.channelId} backgroundVisible={id === parentId} routeCommitted={id === props.channelId ? props.routeCommitted : true} targetHref={id === props.channelId ? props.targetHref : channelHref(props.serverParam, id)} />
+ </ConversationActivityContext>)}</>
+}
+
+function ChannelRouteLayer({ serverParam, channelId, targetHref, routeCommitted = true, backgroundVisible = true, foreground = true }: {
+ serverParam: string
+ channelId: string
+ targetHref?: string
+ routeCommitted?: boolean
+ backgroundVisible?: boolean
+ foreground?: boolean
}) {
const committedSearch = useSearchParams()
const search = targetHref === undefined ? committedSearch.toString() : normalizeCommunityHref(targetHref).search
@@ -64,7 +99,9 @@ export function ChannelRoute({ serverParam, channelId, targetHref, routeCommitte
const serverId = decodeURIComponent(serverParam)
const currentUser = useCurrentUser()
const { navigation } = useCommunityRouteFrame()
- const entryIntent = navigation.entryIntent && normalizeCommunityHref(navigation.entryIntent.href).pathname === channelHref(serverParam, channelId) ? navigation.entryIntent : null
+ const matchingIntent = navigation.entryIntent && normalizeCommunityHref(navigation.entryIntent.href).pathname === channelHref(serverParam, channelId) ? navigation.entryIntent : null
+ const resume = matchingIntent?.resume === true
+ const entryIntent = resume ? null : matchingIntent
const routeAnchorMessageId = searchParams.get("msg")
const intentAnchorMessageId = entryIntent ? new URLSearchParams(normalizeCommunityHref(entryIntent.href).search).get("msg") : undefined
const scope = JSON.stringify([currentUser.id, serverId, channelId])
@@ -72,15 +109,20 @@ export function ChannelRoute({ serverParam, channelId, targetHref, routeCommitte
const anchorMessageId = intentAnchorMessageId !== undefined ? intentAnchorMessageId
: routeAnchorMessageId ?? (captured.scope === scope ? captured.anchorMessageId : null)
useLayoutEffect(() => {
+ if (resume && captured.scope === scope) return
if (!entryIntent && routeAnchorMessageId === null && routeCommitted && captured.scope === scope) return
const next = intentAnchorMessageId !== undefined ? intentAnchorMessageId : routeAnchorMessageId
setCaptured(current => current.scope === scope && current.anchorMessageId === next ? current : { scope, anchorMessageId: next })
- }, [scope, captured.scope, entryIntent, intentAnchorMessageId, routeAnchorMessageId, routeCommitted, setCaptured])
+ }, [resume, scope, captured.scope, entryIntent, intentAnchorMessageId, routeAnchorMessageId, routeCommitted, setCaptured])
const routeModel = useChannelRouteModel(serverId, serverParam, channelId, currentUser.id, anchorMessageId)
- return <ChannelRouteFrame key={JSON.stringify([currentUser.id, serverId])}
+ const content = <ChannelRouteFrame key={JSON.stringify([currentUser.id, serverId])}
serverId={serverId} serverParam={serverParam} channelId={channelId}
- searchParams={searchParams} routeCommitted={routeCommitted}
+ searchParams={searchParams} routeCommitted={routeCommitted} resume={resume}
routeModel={routeModel} anchorMessageId={anchorMessageId} currentUser={currentUser} />
+ return <MobilePage active={foreground} backgroundVisible={backgroundVisible}
+ parentPath={routeModel.layoutHint.parentChannelId ? channelHref(serverParam, routeModel.layoutHint.parentChannelId) : serverRootHref(serverParam)}>
+ {content}
+ </MobilePage>
}
function ChannelRouteFrame(target: RouteTarget) {
@@ -115,7 +157,7 @@ function ChannelRouteFrame(target: RouteTarget) {
else navigation.push(channelHref(serverParam, id))
}, [navigation, serverParam, split])
const navigateServerRoot = useCallback(() => {
- uiHandlers.replacePath?.(serverRootHref(serverParam))
+ uiHandlers.goBackMobile(serverRootHref(serverParam))
}, [serverParam, uiHandlers])
const openProfile = useCallback<OpenProfile>((name, event, discriminator, userId) => {
uiHandlers.openProfile?.(name, event, discriminator, userId)
@@ -123,7 +165,7 @@ function ChannelRouteFrame(target: RouteTarget) {
const pane = <ChannelTargetPane key={JSON.stringify([currentUser.id, serverId, channelId])}
{...target} split={split} layoutPending={layoutPending} resolvingParent={resolvingParent} onOpenChild={enterThread} />
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">
+ return <div ref={containerRef} data-community-target-href={targetHref} className="flex min-h-0 min-w-0 flex-1 flex-col max-sm:fixed max-sm:inset-0 max-sm:z-20 max-sm:bg-background">
<ThreadSplitView
split={split} layoutPending={layoutPending} resolvingParent={resolvingParent} conversationSubtype={isThread ? "thread" : routeModel.skeletonSubtype}
parent={split && parent ? <ThreadSplitParentSurface
@@ -149,13 +191,14 @@ function QualifiedThreadSurface({ routeLifecycle, ...props }: ComponentProps<typ
return <ThreadChannelSurface {...props} threadOpenerHandoff={threadOpenerHandoff} />
}
-function ChannelTargetPane({ serverId, serverParam, channelId, searchParams, routeCommitted,
+function ChannelTargetPane({ serverId, serverParam, channelId, searchParams, routeCommitted, resume,
routeModel, anchorMessageId, currentUser, split, layoutPending, resolvingParent, onOpenChild }: RouteTarget & {
split: boolean
layoutPending: boolean
resolvingParent: boolean
onOpenChild: (id: string) => void
}) {
+ const active = useConversationActivity()
const router = useRouter()
const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)
const currentAnchorMessageId = anchorMessageId
@@ -236,12 +279,12 @@ function ChannelTargetPane({ serverId, serverParam, channelId, searchParams, rou
const { mutate: setChannelNotif } = useSetChannelNotif()
const navigateServerRoot = useCallback(() => {
- uiHandlers.replacePath?.(serverRootHref(serverParam))
+ uiHandlers.goBackMobile(serverRootHref(serverParam))
}, [serverParam, uiHandlers])
const navigateParent = useCallback(() => {
const parentChannelId = currentChannelMeta?.parentChannelId
if (!parentChannelId) return
- uiHandlers.replacePath?.(channelHref(serverParam, parentChannelId))
+ uiHandlers.goBackMobile(channelHref(serverParam, parentChannelId))
}, [currentChannelMeta?.parentChannelId, serverParam, uiHandlers])
const setNotificationLevel = useCallback((level: ChannelNotifLevel) => {
setChannelNotif({ channelId, level }, {
@@ -250,7 +293,7 @@ function ChannelTargetPane({ serverId, serverParam, channelId, searchParams, rou
}, [channelId, setChannelNotif])
useEffect(() => {
- if (!routeCommitted || !anchorMessageId || !searchParams.has("msg") || searchParams.has(THREAD_OPENER_HANDOFF_PARAM)) return
+ if (!active || !routeCommitted || !anchorMessageId || !searchParams.has("msg") || searchParams.has(THREAD_OPENER_HANDOFF_PARAM)) return
const search = searchParams.toString()
const routePath = channelHref(serverParam, channelId)
const href = `${routePath}${search ? `?${search}` : ""}`
@@ -258,7 +301,7 @@ function ChannelTargetPane({ serverId, serverParam, channelId, searchParams, rou
removeCommunityParam(href, "msg"),
{ scroll: false },
)
- }, [channelId, anchorMessageId, routeCommitted, router, searchParams, serverParam])
+ }, [active, channelId, anchorMessageId, routeCommitted, router, searchParams, serverParam])
const openThreadFullscreen = useCallback(() => {
uiHandlers.cancelPendingNavigation?.()
const params = new URLSearchParams(searchParams.toString())
@@ -273,9 +316,9 @@ function ChannelTargetPane({ serverId, serverParam, channelId, searchParams, rou
const channelReadReady =
routeModel.routeLifecycle === "ready" &&
routeModel.routeHydrated
- const channelHydrated = !resolvingParent && routeCommitted && channelReadReady &&
+ const channelHydrated = !resolvingParent && (routeCommitted || resume) && channelReadReady &&
(!isForumPostChild || (!forumPostOpener.isLoading && !openerError))
- const clientReady = channelHydrated && currentChannelId === channelId
+ const clientReady = active && routeCommitted && channelHydrated && currentChannelId === channelId
useNativeSystemNotificationConversationDismissal(currentUser.id, {
kind: "server",
serverId,
diff --git a/src/web/src/components/community/channels/forum-channel-surface.dom.test.ts b/src/web/src/components/community/channels/forum-channel-surface.dom.test.ts
index 29f1bd6ae..307989c1a 100644
--- a/src/web/src/components/community/channels/forum-channel-surface.dom.test.ts
+++ b/src/web/src/components/community/channels/forum-channel-surface.dom.test.ts
@@ -209,6 +209,6 @@ describe("ForumChannelSurface ownership", () => {
})
expect(mockedChannelHeader.mock.calls.at(-1)![0].rightPanel).toBeNull()
- expect(renderer!.container.querySelectorAll("community-panel")).toHaveLength(0)
+ expect(mockedCommunityPanel.mock.calls.at(-1)![0]).toEqual(expect.objectContaining({ kind: null, open: false }))
})
})
diff --git a/src/web/src/components/community/channels/forum-channel-surface.tsx b/src/web/src/components/community/channels/forum-channel-surface.tsx
index 515d287fd..4786106cb 100644
--- a/src/web/src/components/community/channels/forum-channel-surface.tsx
+++ b/src/web/src/components/community/channels/forum-channel-surface.tsx
@@ -154,9 +154,9 @@ export function ForumChannelSurface({
/>
</Body>
)}
- panels={rightPanel && (
+ panels={(
<CommunityPanel
- open
+ open={rightPanel !== null}
onOpenChange={(open) => { if (!open) setPanelState({ channelId, panel: null }) }}
kind={rightPanel}
{...memberPanelProps}
diff --git a/src/web/src/components/community/channels/text-channel-surface.tsx b/src/web/src/components/community/channels/text-channel-surface.tsx
index afd6d577b..00faaf60c 100644
--- a/src/web/src/components/community/channels/text-channel-surface.tsx
+++ b/src/web/src/components/community/channels/text-channel-surface.tsx
@@ -194,9 +194,9 @@ export function TextChannelSurface({
</ConversationFooterSlotProvider>
</Body>
)}
- panels={rightPanel && (
+ panels={(
<CommunityPanel
- open
+ open={rightPanel !== null}
onOpenChange={(open) => { if (!open) setRightPanel(null) }}
kind={rightPanel}
{...memberPanelProps}
diff --git a/src/web/src/components/community/channels/thread-channel-surface.tsx b/src/web/src/components/community/channels/thread-channel-surface.tsx
index 45ee7dd18..852779e40 100644
--- a/src/web/src/components/community/channels/thread-channel-surface.tsx
+++ b/src/web/src/components/community/channels/thread-channel-surface.tsx
@@ -306,9 +306,9 @@ export function ThreadChannelSurface({
</ConversationFooterSlotProvider>
</Body>
)}
- panels={rightPanel && (
+ panels={(
<CommunityPanel
- open
+ open={rightPanel !== null}
onOpenChange={(open) => { if (!open) setRightPanel(null) }}
kind={rightPanel}
{...memberPanelProps}
diff --git a/src/web/src/components/community/image-crop-dialog.tsx b/src/web/src/components/community/image-crop-dialog.tsx
index 64f6cb2f4..4b7bc7c6d 100644
--- a/src/web/src/components/community/image-crop-dialog.tsx
+++ b/src/web/src/components/community/image-crop-dialog.tsx
@@ -1,7 +1,7 @@
"use client"
import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useCallback } from "react"
+import { useCallback, useRef, useState } from "react"
import Cropper, { type Area } from "react-easy-crop"
import { toast } from "sonner"
import { getErrorMessage } from "@/lib/api/client"
@@ -36,6 +36,8 @@ export function ImageCropDialog({
onCancel: () => void
onCropped: (file: File) => void
}) {
+ const [open, setOpen] = useState(true)
+ const cropped = useRef<File | null>(null)
const [crop, setCrop] = useAtom(useCreateAtom({ x: 0, y: 0 }))
const [zoom, setZoom] = useAtom(useCreateAtom(1))
const [cropPixels, setCropPixels] = useAtom(useCreateAtom<Area | null>(null))
@@ -54,7 +56,8 @@ export function ImageCropDialog({
toast.error("Failed to process image — please try again")
return
}
- onCropped(buildCroppedIconFile(blob, originalFileName))
+ cropped.current = buildCroppedIconFile(blob, originalFileName)
+ setOpen(false)
} catch (e) {
toast.error(getErrorMessage(e, "Failed to process image — please try again"))
} finally {
@@ -63,12 +66,18 @@ export function ImageCropDialog({
}
return (
- <Dialog open onOpenChange={(o) => { if (!o) onCancel() }}>
+ <Dialog open={open} onOpenChange={setOpen} onOpenChangeComplete={(next) => {
+ if (next) return
+ const file = cropped.current
+ cropped.current = null
+ if (file) onCropped(file)
+ else onCancel()
+ }}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Crop image</DialogTitle>
</DialogHeader>
- <div className="relative h-80 w-full overflow-hidden rounded-md bg-muted">
+ <div data-base-ui-swipe-ignore="" className="relative h-80 w-full overflow-hidden rounded-md bg-muted">
<Cropper
image={imageSrc}
crop={crop}
@@ -98,7 +107,7 @@ export function ImageCropDialog({
</SliderControl>
</Slider>
<DialogFooter>
- <Button variant="ghost" onClick={onCancel}>Cancel</Button>
+ <Button variant="ghost" onClick={() => setOpen(false)}>Cancel</Button>
<Button onClick={save} disabled={!cropPixels || saving}>
{saving ? "Saving…" : "Save"}
</Button>
diff --git a/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsx b/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsx
index 3bbef8212..26ba64916 100644
--- a/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsx
+++ b/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsx
@@ -5,6 +5,7 @@ import { USE_SERVER_DEFAULT } from "@alook/shared"
import { act, fireEvent, screen, setupUser, waitFor } from "@/test/react-dom-harness"
import { renderCommunity as render } from "@/test/community-owner-harness"
import { readComposerDraft, writeComposerDraft } from "@/lib/community/composer-draft"
+import { ConversationActivityContext } from "@/contexts/community/conversation-activity"
import type { Member } from "@/lib/community/models/people"
import { CommunityMentionList, ChannelRefList } from "./composer-suggestion-popups"
import type { ComposerHandle, ComposerProps } from "./composer-types"
@@ -114,6 +115,31 @@ function BackListener({ replacePath }: { replacePath: (path: string) => void })
}
describe("composer suggestion focus with installed TipTap", () => {
+ it("retains the editor and draft while background focus and submission are disabled", async () => {
+ const probeRef: Probe = { current: null }, handle = createRef<ComposerHandle>()
+ const accept = vi.fn(() => true)
+ const node = (active: boolean) => <ConversationActivityContext value={active}>
+ <Harness {...props} probeRef={probeRef} handle={handle} draftKey="background" onAcceptSend={accept} autoFocus />
+ </ConversationActivityContext>
+ const view = render(node(true))
+ const editor = await editorOf(probeRef)
+ await type(editor, "Keep parent draft")
+ const document = editor.getJSON()
+ view.rerender(node(false))
+ expect(probeRef.current!.editor).toBe(editor)
+ expect(editor.isEditable).toBe(false)
+ await act(async () => { handle.current!.focusEditor(); handle.current!.submitNow() })
+ await waitFor(() => expect(editor.isFocused).toBe(false))
+ expect(accept).not.toHaveBeenCalled()
+ expect(editor.getJSON()).toEqual(document)
+ view.rerender(node(true))
+ expect(probeRef.current!.editor).toBe(editor)
+ expect(editor.isEditable).toBe(true)
+ expect(editor.getJSON()).toEqual(document)
+ await act(async () => { handle.current!.submitNow() })
+ await waitFor(() => expect(accept).toHaveBeenCalledOnce())
+ })
+
beforeEach(() => {
localStorage.clear()
surfaces.breakpoint = "desktop"
diff --git a/src/web/src/components/community/messages/composer-view.dom.test.ts b/src/web/src/components/community/messages/composer-view.dom.test.ts
index 729600333..798535ef7 100644
--- a/src/web/src/components/community/messages/composer-view.dom.test.ts
+++ b/src/web/src/components/community/messages/composer-view.dom.test.ts
@@ -85,6 +85,33 @@ function baseProps(
}
describe("ComposerView", () => {
+ it.each([
+ { name: "native iPhone", native: true, ua: "iPhone", compact: true },
+ { name: "native Android", native: true, ua: "Android", compact: true },
+ { name: "mobile browser", native: false, ua: "iPhone", compact: false },
+ { name: "desktop Tauri", native: true, ua: "Macintosh", compact: false },
+ ])("keeps ordinary/live/loading padding aligned on $name", ({ native, ua, compact }) => {
+ const bridge = Object.getOwnPropertyDescriptor(window, "__TAURI__")
+ const userAgent = vi.spyOn(navigator, "userAgent", "get").mockReturnValue(ua)
+ if (native) Object.defineProperty(window, "__TAURI__", { configurable: true, value: {} })
+ else Reflect.deleteProperty(window, "__TAURI__")
+ try {
+ const view = render(createElement("div", null,
+ createElement(ComposerView, baseProps()),
+ createElement(ComposerSkeleton),
+ createElement(ComposerView, baseProps({ isForumThreadBody: true })),
+ ))
+ const wrappers = Array.from(view.container.firstElementChild!.children) as HTMLElement[]
+ expect(wrappers.map(element => element.style.paddingBottom)).toEqual([
+ compact ? "0.25rem" : "", compact ? "0.25rem" : "", "",
+ ])
+ } finally {
+ userAgent.mockRestore()
+ if (bridge) Object.defineProperty(window, "__TAURI__", bridge)
+ else Reflect.deleteProperty(window, "__TAURI__")
+ }
+ })
+
it("scopes single-line placeholder containment to chat composers", () => {
const css = readFileSync(
resolve(
diff --git a/src/web/src/components/community/messages/composer-view.tsx b/src/web/src/components/community/messages/composer-view.tsx
index 3b9e4d843..3e997ce62 100644
--- a/src/web/src/components/community/messages/composer-view.tsx
+++ b/src/web/src/components/community/messages/composer-view.tsx
@@ -11,7 +11,7 @@ import {
Smile,
X,
} from "lucide-react"
-import { stripInlineMarkup } from "@alook/shared"
+import { isMobile, stripInlineMarkup } from "@alook/shared"
import { Skeleton } from "@/components/ui/skeleton"
import type { PendingFile } from "@/hooks/use-file-attachments"
import type {
@@ -30,6 +30,7 @@ import {
} from "./composer-suggestion-popups"
import type { ComposerReplyTarget, MentionCandidateSource } from "./composer-types"
import { SendStrokeRoundedIcon } from "./send-stroke-rounded-icon"
+import { useHydratedClient } from "@/components/community/shell/use-hydrated-client"
const COMPOSER_OUTER_CLASS =
"relative pl-[var(--community-composer-inline-start)] pr-[var(--community-composer-inline-end)] pb-[calc(0.75rem+var(--app-safe-area-bottom))] pt-0 sm:pb-3"
@@ -89,6 +90,7 @@ export function ComposerView({
onUploadFile,
onEmojiPick,
}: ComposerViewProps) {
+ const nativeMobile = useHydratedClient() && isMobile()
const replyPreview = replyingTo
? stripInlineMarkup(replyingTo.text).replace(/\s+/g, " ").trim()
: null
@@ -99,6 +101,7 @@ export function ComposerView({
return (
<div
+ style={nativeMobile && !isForumThreadBody ? { paddingBottom: "0.25rem" } : undefined}
className={
isForumThreadBody
? "relative"
@@ -253,8 +256,9 @@ export function ComposerView({
}
export function ComposerSkeleton() {
+ const nativeMobile = useHydratedClient() && isMobile()
return (
- <div className={COMPOSER_OUTER_CLASS}>
+ <div className={COMPOSER_OUTER_CLASS} style={nativeMobile ? { paddingBottom: "0.25rem" } : undefined}>
<div className="relative rounded-(--community-composer-top-radius) bg-muted py-3 px-12 shadow-(--e1) ring-1 ring-border/40">
<Skeleton className="h-6 w-2/5 rounded" />
<Skeleton className="absolute left-2 bottom-2 size-8 rounded-full" />
diff --git a/src/web/src/components/community/messages/composer.send-lifecycle.dom.test.ts b/src/web/src/components/community/messages/composer.send-lifecycle.dom.test.ts
index 34d2075d6..5bc325f06 100644
--- a/src/web/src/components/community/messages/composer.send-lifecycle.dom.test.ts
+++ b/src/web/src/components/community/messages/composer.send-lifecycle.dom.test.ts
@@ -102,6 +102,7 @@ describe("Composer committed send lifecycle", () => {
isEmpty: false,
getText: vi.fn(() => "latest draft"),
getJSON: vi.fn(() => ({})),
+ setEditable: vi.fn(),
commands: {
clearContent,
focus: vi.fn(),
diff --git a/src/web/src/components/community/messages/image-lightbox.tsx b/src/web/src/components/community/messages/image-lightbox.tsx
index 4720f2936..18fab3f54 100644
--- a/src/web/src/components/community/messages/image-lightbox.tsx
+++ b/src/web/src/components/community/messages/image-lightbox.tsx
@@ -2,7 +2,7 @@
import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useLayoutEffect, useMemo } from "react"
+import { useLayoutEffect, useMemo, useState } from "react"
import { Dialog, DialogContent } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { MinusIcon, PlusIcon, RotateCcwIcon, XIcon } from "lucide-react"
@@ -69,6 +69,7 @@ function PreviewFrame({ image, onClose }: { image: ImagePreview; onClose: () =>
<div
ref={frameRef}
data-testid={tid.imageLightbox}
+ data-base-ui-swipe-ignore=""
data-zoom-scale={view.scale}
data-native-context-menu="true"
role="region"
@@ -141,17 +142,22 @@ function PreviewFrame({ image, onClose }: { image: ImagePreview; onClose: () =>
)
}
-export function ImageLightbox({ image, onClose }: { image: ImagePreview; onClose: () => void }) {
+export function ImageLightbox({ image, onClose }: { image: ImagePreview | null; onClose: () => void }) {
+ const [retained, setRetained] = useState(image)
+ useLayoutEffect(() => { if (image) setRetained(image) }, [image])
+ const displayed = image ?? retained
+ if (!displayed) return null
return (
- <Dialog open onOpenChange={(open) => { if (!open) onClose() }}>
+ <Dialog open={image !== null} onOpenChange={(open) => { if (!open) onClose() }}
+ onOpenChangeComplete={(open) => { if (!open) setRetained(null) }}>
<DialogContent
- aria-label={image.name}
+ aria-label={displayed.name}
className="top-[max(1rem,env(safe-area-inset-top))] right-[max(1rem,env(safe-area-inset-right))] left-[max(1rem,env(safe-area-inset-left))] flex h-[calc(100dvh_-_max(1rem,env(safe-area-inset-top))_-_max(1rem,env(safe-area-inset-bottom)))] w-auto max-w-none translate-x-0 translate-y-0 overflow-visible border-none bg-transparent p-0 shadow-none ring-0 sm:max-w-none"
showCloseButton={false}
>
<PreviewFrame
- key={`${image.originalUrl}\u0000${image.thumbnailUrl ?? ""}\u0000${image.width ?? ""}\u0000${image.height ?? ""}`}
- image={image}
+ key={`${displayed.originalUrl}\u0000${displayed.thumbnailUrl ?? ""}\u0000${displayed.width ?? ""}\u0000${displayed.height ?? ""}`}
+ image={displayed}
onClose={onClose}
/>
</DialogContent>
diff --git a/src/web/src/components/community/messages/message-channel-controller-state.ts b/src/web/src/components/community/messages/message-channel-controller-state.ts
index 2a69ac8ba..34d1fa135 100644
--- a/src/web/src/components/community/messages/message-channel-controller-state.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-state.ts
@@ -12,6 +12,7 @@ import { useCallback, useEffect, useLayoutEffect, useMemo } from "react"
import { materializeIntent } from "@/lib/community/message-stream"
import { presentCanonicalMessage } from "@/lib/community/message-wire"
import { messageScopeKey } from "@/stores/community/message-stream-store"
+import { useConversationActivity } from "@/contexts/community/conversation-activity"
import { useCommunityViewSource } from "@/hooks/community/use-community-view-source"
import { usePathname, useRouter, useSearchParams } from "next/navigation"
import type { MentionType } from "@alook/shared"
@@ -65,6 +66,7 @@ export function useMessageChannelController({
onOpenPinned,
resolveUserName,
}: Omit<MessageChannelControllerProps, "children">): MessageChannelControllerValue {
+ const active = useConversationActivity()
const profileQueryClient = useQueryClient()
const communityRuntime = useCommunityRuntime()
const source = useCommunityViewSource(`message-actions:${serverId}:${channelId}`)
@@ -126,10 +128,10 @@ export function useMessageChannelController({
const pendingReply = useCommunityStore((state) => state.pendingReply)
useEffect(() => {
- if (!pendingReply || pendingReply.channelId !== channelId) return
+ if (!active || !pendingReply || pendingReply.channelId !== channelId) return
setReplyTo(pendingReply.target)
communityRuntime.ui.actions.setPendingReply(null)
- }, [pendingReply, channelId, setReplyTo, communityRuntime.ui.actions])
+ }, [active, pendingReply, channelId, setReplyTo, communityRuntime.ui.actions])
const actionContext = useMemo(() => ({ scope: [communityRuntime, channelId], store: createStore<MessageActionContext>({
messageIds: [],
@@ -172,7 +174,7 @@ export function useMessageChannelController({
const seqParam = searchParams.get("seq")
const searchParamsString = searchParams.toString()
useEffect(() => {
- if (pathname !== channelHref(serverParam, channelId) || !seqParam) return
+ if (!active || pathname !== channelHref(serverParam, channelId) || !seqParam) return
const seq = Number(seqParam)
if (!Number.isSafeInteger(seq) || seq < 1) return
const message = actionContext.get().messageIds.map(getMessage).find((item) => item?.seq === seq)
@@ -180,7 +182,7 @@ export function useMessageChannelController({
setContextTarget({ serverId, channelId, label: channelName, seq })
const href = `${pathname}${searchParamsString ? `?${searchParamsString}` : ""}`
router.replace(removeCommunityParam(href, "seq"), { scroll: false })
- }, [seqParam, serverId, serverParam, channelId, channelName, pathname, router, searchParamsString, actionContext, getMessage, setContextTarget, setScrollTargetId])
+ }, [active, seqParam, serverId, serverParam, channelId, channelName, pathname, router, searchParamsString, actionContext, getMessage, setContextTarget, setScrollTargetId])
const messageScope = useMemo(
() => ({ kind: "channel" as const, id: channelId, serverId }),
diff --git a/src/web/src/components/community/messages/message-share-dialog.tsx b/src/web/src/components/community/messages/message-share-dialog.tsx
index 9942e8cee..d544a21bb 100644
--- a/src/web/src/components/community/messages/message-share-dialog.tsx
+++ b/src/web/src/components/community/messages/message-share-dialog.tsx
@@ -5,7 +5,7 @@ import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
import { useCommunityViewSource } from "@/hooks/community/use-community-view-source"
import { useCommunityRuntime } from "@/stores/community/runtime"
import { saveFile, fileSaveMessage, type FileSaveResult } from "@/lib/file-save"
-import { useCallback, useEffect, useMemo, useRef, type MouseEvent as ReactMouseEvent } from "react"
+import { useCallback, useEffect, useMemo, useRef, useState, type MouseEvent as ReactMouseEvent } from "react"
import { toBlob } from "html-to-image"
import { toast } from "sonner"
import { Check, Copy, Download, Highlighter, Loader2 } from "lucide-react"
@@ -112,6 +112,8 @@ export function MessageShareDialog({ m, open, onClose }: {
open: boolean
onClose: () => void
}) {
+ const [visible, setVisible] = useState(open)
+ useEffect(() => { setVisible(open) }, [open])
const messages = useMemo(() => (Array.isArray(m) ? m : [m]), [m])
const mobileNative = isTauri() && isMobile()
const runtime = useCommunityRuntime(), client = useQueryClient()
@@ -251,12 +253,12 @@ export function MessageShareDialog({ m, open, onClose }: {
setCopied(false)
try { await command.mutateAsync({ action, original }) } catch {}
}
- const close = () => { source.retire(); onClose() }
+ const close = () => { source.retire(); setVisible(false) }
const copy = () => startExport("copy")
const download = () => startExport("download")
return (
- <Dialog open={open} onOpenChange={(o) => !o && close()}>
+ <Dialog open={visible} onOpenChange={(o) => !o && close()} onOpenChangeComplete={(next) => { if (!next) onClose() }}>
{/* NOTE: DialogContent's base class carries `sm:max-w-sm` (384px). That's
a responsive variant, so it sorts AFTER a plain `max-w-[…]` in the
generated CSS and would silently cap the dialog at 384px — the reason a
diff --git a/src/web/src/components/community/messages/message.tsx b/src/web/src/components/community/messages/message.tsx
index b3ce5af1b..a707819e4 100644
--- a/src/web/src/components/community/messages/message.tsx
+++ b/src/web/src/components/community/messages/message.tsx
@@ -27,6 +27,7 @@ import { MessageContextItems, MessageDropdownItems, hasMessageMenu } from "./mes
import { formatMessageTime } from "@/lib/community/format-time"
import { tid } from "@/lib/community/testids"
import { cn } from "@/lib/utils"
+import { usePageSwipeStart } from "@/components/ui/swipe-container"
import { avatarInitial } from "@/lib/community/avatar"
import { stripInlineMarkup } from "@alook/shared"
import type { FileAttachment, ImagePreview, RenderMsg } from "@/lib/community/models/message"
@@ -36,6 +37,7 @@ import { AttachmentCard } from "./attachment-card"
import {
advanceMobileReplyGesture,
beginMobileReplyGesture,
+ movedBeyondLongPressTolerance,
shouldCommitMobileReply,
shouldSuppressClickAfterMobileReplyGesture,
type MobileReplyGesture,
@@ -231,6 +233,7 @@ function MessageImpl({
: (m.replyTo?.authorName ?? "Deleted user")
const visibleContent = m.content ?? ""
// keep the hover toolbar pinned open while its ⋯ dropdown is open
+ const pageSwipe = usePageSwipeStart()
const [toolbarOpen, setToolbarOpen] = useAtom(useCreateAtom(false))
// Right-click context-menu open state — tracked so the Mark/Unmark label's
// lazy read fires for the context menu too, not just the ⋯ dropdown.
@@ -249,6 +252,7 @@ function MessageImpl({
const touchStartedAt = useRef<number | null>(null)
const suppressLongPressClick = useRef(false)
const swipeGestureRef = useRef<MobileReplyGesture | null>(null)
+ const pageSwipeStartRef = useRef<{ x: number; y: number } | null>(null)
const [swipeVisual, setSwipeVisual] = useAtom(useCreateAtom({ offset: 0, active: false, crossed: false }))
const avatarMention = useMobileAvatarMention({
onMention: onMentionAuthor,
@@ -307,7 +311,8 @@ function MessageImpl({
|| (!desktopMenuInputActive && touchInputCapable)
// A hybrid device can alternate between mouse and touch. Switching the menu
// shell after a mouse gesture must not remove the row's touch swipe handler.
- const swipeReplyEnabled = interactive && touchInputCapable && !selectMode && !!onReply
+ const swipePointerEnabled = interactive && touchInputCapable && !selectMode
+ const swipeReplyEnabled = swipePointerEnabled && !!onReply
const activateOverlays = interactive && !selectMode && !activated
? (event: React.SyntheticEvent<HTMLElement>) => {
if (shouldActivateMessageOverlays(event.target)) setActivated(true)
@@ -387,6 +392,8 @@ function MessageImpl({
: reactionAddButton
const row = (
<div
+ data-base-ui-swipe-ignore={pageSwipe.page ? "y" : ""}
+ data-page-swipe-reply-row=""
className={[
"group relative -mx-2 flex gap-2 rounded px-2 transition-colors",
swipeReplyEnabled ? "z-10 touch-pan-y bg-background" : "",
@@ -421,10 +428,17 @@ function MessageImpl({
linkPointerRef.current = null
}
: undefined}
- onPointerDown={swipeReplyEnabled
+ onPointerDown={swipePointerEnabled
? (event) => {
if (!messageEventBelongsToRow(event.target, event.currentTarget)) return
if (event.pointerType !== "touch") return
+ pageSwipeStartRef.current = null
+ if (pageSwipe.reservesReply(event)) {
+ pageSwipeStartRef.current = { x: event.clientX, y: event.clientY }
+ suppressLongPressClick.current = false
+ return
+ }
+ if (!swipeReplyEnabled) return
const nested = (event.target as Element).closest?.(
"button, a, input, textarea, select, [role=button]",
)
@@ -435,11 +449,17 @@ function MessageImpl({
setSwipeVisual({ offset: 0, active: true, crossed: false })
}
: undefined}
- onPointerMove={swipeReplyEnabled
+ onPointerMove={swipePointerEnabled
? (event) => {
if (!messageEventBelongsToRow(event.target, event.currentTarget)) return
+ if (event.pointerType !== "touch") return
+ const pageStart = pageSwipeStartRef.current
+ if (pageStart) {
+ suppressLongPressClick.current ||= movedBeyondLongPressTolerance(pageStart.x, pageStart.y, event.clientX, event.clientY)
+ return
+ }
const current = swipeGestureRef.current
- if (!current || event.pointerType !== "touch") return
+ if (!current) return
if (selectionBelongsToRow(window.getSelection(), event.currentTarget)) {
swipeGestureRef.current = null
setSwipeVisual({ offset: 0, active: false, crossed: false })
@@ -461,11 +481,13 @@ function MessageImpl({
})
}
: undefined}
- onPointerUp={swipeReplyEnabled
+ onPointerUp={swipePointerEnabled
? (event) => {
if (!messageEventBelongsToRow(event.target, event.currentTarget)) return
+ if (event.pointerType !== "touch") return
+ pageSwipeStartRef.current = null
const gesture = swipeGestureRef.current
- if (!gesture || event.pointerType !== "touch") return
+ if (!gesture) return
const commit = shouldCommitMobileReply(gesture)
swipeGestureRef.current = null
suppressLongPressClick.current = suppressLongPressClick.current
@@ -474,10 +496,11 @@ function MessageImpl({
if (commit) onReply?.()
}
: undefined}
- onPointerCancel={swipeReplyEnabled
+ onPointerCancel={swipePointerEnabled
? (event) => {
if (!messageEventBelongsToRow(event.target, event.currentTarget)) return
swipeGestureRef.current = null
+ pageSwipeStartRef.current = null
suppressLongPressClick.current = true
setSwipeVisual({ offset: 0, active: false, crossed: false })
}
diff --git a/src/web/src/components/community/messages/use-composer-controller.dom.test.ts b/src/web/src/components/community/messages/use-composer-controller.dom.test.ts
index 59fb61367..b50bebce2 100644
--- a/src/web/src/components/community/messages/use-composer-controller.dom.test.ts
+++ b/src/web/src/components/community/messages/use-composer-controller.dom.test.ts
@@ -139,6 +139,7 @@ type TestEditor = {
setAttribute: ReturnType<typeof vi.fn>
}
}
+ setEditable: ReturnType<typeof vi.fn>
commands: {
clearContent: ReturnType<typeof vi.fn>
focus: ReturnType<typeof vi.fn>
@@ -218,6 +219,7 @@ describe("useComposerController", () => {
},
},
view: { dispatch, dom: { setAttribute: setDomAttribute } },
+ setEditable: vi.fn(),
commands: {
clearContent,
focus,
diff --git a/src/web/src/components/community/messages/use-composer-controller.ts b/src/web/src/components/community/messages/use-composer-controller.ts
index 343e0f6b1..4dc44b9b3 100644
--- a/src/web/src/components/community/messages/use-composer-controller.ts
+++ b/src/web/src/components/community/messages/use-composer-controller.ts
@@ -1,3 +1,4 @@
+import { useConversationActivity } from "@/contexts/community/conversation-activity"
import { useMutation, useIsMutating, useQueryClient } from "@tanstack/react-query";
import { useOptionalCommunityDbRegistry } from "@/lib/community-db/projections";
import { useAtom, useCreateAtom, useCreateStore } from "@tanstack/react-store";
@@ -63,6 +64,7 @@ export function useComposerController(
}: ComposerProps,
ref: ForwardedRef<ComposerHandle>,
): ComposerViewProps {
+ const active = useConversationActivity()
const registry = useOptionalCommunityDbRegistry()
const client = useQueryClient()
const draftKey = registry && requestedDraftKey ? `${registry.accountId}:${requestedDraftKey}` : undefined
@@ -70,7 +72,7 @@ export function useComposerController(
const hoverCapable = useHoverCapable()
const hoverCapableRef = useRef(hoverCapable)
const [editorHasContent, setEditorHasContent] = useAtom(useCreateAtom(false))
- const protocol = useCreateStore({ active: true, generation: 0, scope: "", scopeVersion: 0, draftKey, nextLongPasteIndex: 1, suppress: false, previousHasContent: false })
+ const protocol = useCreateStore({ active, generation: 0, scope: "", scopeVersion: 0, draftKey, nextLongPasteIndex: 1, suppress: false, previousHasContent: false })
const sendKey = ["community", "composer-accept", useCreateAtom(crypto.randomUUID()).get()]
const sendInFlight = useIsMutating({ mutationKey: sendKey, exact: true }) > 0
useLayoutEffect(() => {
@@ -127,7 +129,7 @@ export function useComposerController(
protocol.setState((state) => ({ ...state, draftKey, scope, ...(state.scope !== scope ? { scopeVersion: state.scopeVersion + 1, nextLongPasteIndex: 1 } : {}) }))
}, [scope, draftKey, protocol])
const fireTyping = () => {
- if (!onTyping || typingTimer.current) return
+ if (!protocol.get().active || !onTyping || typingTimer.current) return
onTyping()
typingTimer.current = setTimeout(() => {
typingTimer.current = null
@@ -217,7 +219,9 @@ export function useComposerController(
onBlur: ({ editor: blurredEditor }) => resetPopups(blurredEditor),
})
useLayoutEffect(() => {
- protocol.setState((state) => ({ ...state, active: true }))
+ protocol.setState((state) => ({ ...state, active }))
+ editor?.setEditable(active, false)
+ if (!active) { editor?.commands.blur(); resetPopups(editor) }
const onDestroy = () => {
if (editorRef.current !== editor) return
protocol.setState((state) => ({ ...state, active: false, generation: state.generation + 1 }))
@@ -229,7 +233,7 @@ export function useComposerController(
editor?.off("destroy", onDestroy)
resetPopups(editor)
}
- }, [editor, protocol, resetPopups])
+ }, [active, editor, protocol, resetPopups])
useLayoutEffect(() => {
editorRef.current = editor
return () => { if (editorRef.current === editor) editorRef.current = null }
@@ -316,21 +320,22 @@ export function useComposerController(
useImperativeHandle(ref, () => ({
focusEditor: () => {
+ if (!protocol.get().active) return
suppressSuggestions(() => editor?.commands.focus("end"))
},
insertTextAtCaret: (text) => {
- if (!editor || !text) return
+ if (!protocol.get().active || !editor || !text) return
const insertion = textNodeForCaretInsertion(text, editor.state)
editor.chain().focus().insertContent(insertion).run()
},
insertMentionAtCaret: (mention) => {
- if (editor && mention.id && mention.label) editor.chain().focus().insertContent(mentionNodesForCaretInsertion(mention, editor.state)).run()
+ if (protocol.get().active && editor && mention.id && mention.label) editor.chain().focus().insertContent(mentionNodesForCaretInsertion(mention, editor.state)).run()
},
submitNow: () => {
send()
},
resetAfterSubmit: () => {
- if (!editor) return
+ if (!protocol.get().active || !editor) return
editor.commands.clearContent()
setEditorHasContent(false)
setPendingFiles([])
@@ -339,15 +344,16 @@ export function useComposerController(
},
isEmpty: () => !editor || (editor.isEmpty && pendingFiles.length === 0),
openFilePicker: () => {
+ if (!protocol.get().active) return
fileInputRef.current?.click()
},
}))
useEffect(() => {
- if (!autoFocus || !editor || isForumThreadBody || editor.isFocused) return
+ if (!active || !autoFocus || !editor || isForumThreadBody || editor.isFocused) return
if (document.activeElement?.closest(`[data-testid="${tid.serverRailScroll}"]`)) return
suppressSuggestions(() => editor.commands.focus("end"))
- }, [autoFocus, editor, channel, isForumThreadBody, suppressSuggestions])
+ }, [active, autoFocus, editor, channel, isForumThreadBody, suppressSuggestions])
useComposerReplyMention({ editor, channelType, isForumThreadBody, replyingTo, members, suppressSuggestions })
diff --git a/src/web/src/components/community/settings/server-settings-channels-access.dom.test.tsx b/src/web/src/components/community/settings/server-settings-channels-access.dom.test.tsx
index 25e22ea20..952c91b30 100644
--- a/src/web/src/components/community/settings/server-settings-channels-access.dom.test.tsx
+++ b/src/web/src/components/community/settings/server-settings-channels-access.dom.test.tsx
@@ -8,7 +8,7 @@ import { tid } from "@/lib/community/testids"
vi.mock("./settings-shell.module.css", () => ({ default: { shell: "settings-shell" } }))
const apiFetchMock = vi.hoisted(() => vi.fn())
vi.mock("@/lib/api/client", () => ({ apiFetch: apiFetchMock, toastApiError: vi.fn() }))
-vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "desktop" }))
+vi.mock("@/hooks/use-mobile", () => ({ useIsMobile: () => false, useBreakpoint: () => "desktop" }))
vi.mock("@/hooks/community/use-server-panels", () => ({ useInvites: () => ({ invites: [], isLoading: false }) }))
vi.mock("@/hooks/community/use-bots", () => ({ useBots: () => ({ bots: [] }) }))
vi.mock("@/hooks/community/use-notification-settings", async (importOriginal) => ({
diff --git a/src/web/src/components/community/shell/community-panel.tsx b/src/web/src/components/community/shell/community-panel.tsx
index ef10b5797..b88ffd8a0 100644
--- a/src/web/src/components/community/shell/community-panel.tsx
+++ b/src/web/src/components/community/shell/community-panel.tsx
@@ -1,5 +1,6 @@
"use client"
+import { useLayoutEffect, useState } from "react"
import { MessagesSquare, Pin, Users } from "lucide-react"
import { stripInlineMarkup, type CommunityRole as Role } from "@alook/shared"
@@ -21,7 +22,7 @@ import { readCommunityProfile } from "@/lib/community/profile-read"
export type CommunityPanelProps = {
open: boolean
onOpenChange: (open: boolean) => void
- kind: Exclude<RightPanel, null>
+ kind: RightPanel
members: Member[]
memberScopeId?: string
membersLoading?: boolean
@@ -45,13 +46,18 @@ export type CommunityPanelProps = {
export function CommunityPanel(props: CommunityPanelProps) {
const { open, onOpenChange, kind } = props
- const { icon: Icon, label } = panelHeading(kind)
+ const [retained, setRetained] = useState(kind)
+ useLayoutEffect(() => { if (kind) setRetained(kind) }, [kind])
+ const displayed = kind ?? retained
const profilesByUserId = useCanonicalProfilesByUserId()
+ if (!displayed) return null
+ const { icon: Icon, label } = panelHeading(displayed)
return (
<CommunitySheet
open={open}
onOpenChange={onOpenChange}
+ onOpenChangeComplete={(open) => { if (!open) setRetained(null) }}
title={(
<span className="flex min-w-0 items-center gap-2">
<Icon className="size-4 shrink-0 text-muted-foreground" />
@@ -61,7 +67,7 @@ export function CommunityPanel(props: CommunityPanelProps) {
desktopWidth={kind === "members" ? 380 : undefined}
bodyClassName={kind === "members" ? "p-0 sm:p-0" : undefined}
>
- {renderCommunityPanelBody(props, profilesByUserId)}
+ {renderCommunityPanelBody({ ...props, kind: displayed }, profilesByUserId)}
</CommunitySheet>
)
}
diff --git a/src/web/src/components/community/shell/community-route-frame.dom.test.tsx b/src/web/src/components/community/shell/community-route-frame.dom.test.tsx
index 979bd7516..22a860a06 100644
--- a/src/web/src/components/community/shell/community-route-frame.dom.test.tsx
+++ b/src/web/src/components/community/shell/community-route-frame.dom.test.tsx
@@ -31,7 +31,7 @@ vi.mock("next/navigation", () => ({
vi.mock("@/contexts/community/current-user", () => ({
useCurrentUser: () => ({ id: mocks.userId }),
}))
-vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => mocks.breakpoint }))
+vi.mock("@/hooks/use-mobile", () => ({ useIsMobile: () => false, useBreakpoint: () => mocks.breakpoint }))
vi.mock("@/lib/community-onboarding", () => ({ useCommunityOnboarding: () => null }))
vi.mock("./use-shell-rail-controller", () => ({
useShellRailController: () => ({ railProps: {}, navigate: vi.fn() }),
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 3863de207..881ab6d4c 100644
--- a/src/web/src/components/community/shell/community-shell-layout.tsx
+++ b/src/web/src/components/community/shell/community-shell-layout.tsx
@@ -365,9 +365,9 @@ export function CommunityShellLayout({
const isMobileDetail = breakpoint === "mobile" && surface === "detail"
const isInitial = breakpoint === "unknown"
const isInitialDetail = isInitial && surface === "detail"
- const sidebarMobileActive = isMobileList || (isInitial && surface === "list")
- const sidebarMobileHidden = isMobileDetail || isInitialDetail
- const mainMobileActive = isMobileDetail || isInitialDetail
+ const sidebarMobileActive = breakpoint === "mobile" || (isInitial && surface === "list")
+ const sidebarMobileHidden = isInitialDetail
+ const mainMobileActive = isInitialDetail
const mainMobileHidden = isMobileList || (isInitial && surface === "list")
const showUserBar = isDesktop || isMobileList || isInitial || preserveHiddenMobileModules
@@ -387,28 +387,21 @@ export function CommunityShellLayout({
data-slot="community-shell-root"
>
{(!isMobileDetail || preserveHiddenMobileModules) && (
- <div data-community-rail inert={isMobileDetail} aria-hidden={isMobileDetail || undefined} className={cn(
+ <div data-community-rail inert={isMobileDetail || isInitialDetail} aria-hidden={isMobileDetail || isInitialDetail || undefined} className={cn(
"flex min-h-0",
- isInitialDetail && "hidden sm:contents",
- isMobileDetail && preserveHiddenMobileModules && "hidden",
+ isInitialDetail && "invisible sm:visible sm:contents",
+
)}>
{rail}
</div>
)}
<div
- className={cn(
- "relative flex min-h-0 min-w-0 flex-1 flex-col",
- !isMobileDetail && !isInitialDetail && "pt-2",
- isInitialDetail && "pt-0 sm:pt-2",
- )}
+ data-slot="community-shell-body"
+ className="relative flex min-h-0 min-w-0 flex-1 flex-col pt-2"
>
<AppSurface
data-slot="community-app-surface"
- className={cn(
- SHELL_SURFACE_CLASS,
- isMobileDetail && "rounded-none border-0 bg-background shadow-none ring-0",
- isInitialDetail && "max-sm:rounded-none max-sm:border-0 max-sm:bg-background max-sm:shadow-none max-sm:ring-0",
- )}
+ className={SHELL_SURFACE_CLASS}
>
<ResizablePanelGroup
id="community-shell"
@@ -417,7 +410,16 @@ export function CommunityShellLayout({
disabled={!isDesktop}
className={cn(
"min-h-0 flex-1",
- !isDesktop && [
+ [
+ "max-sm:*:data-[mobile-layer=true]:fixed!",
+ "max-sm:*:data-[mobile-layer=true]:z-20!",
+ "max-sm:*:data-[mobile-layer=true]:inset-0!",
+ "max-sm:*:data-[mobile-layer=true]:flex-none!",
+ "max-sm:*:data-[mobile-layer=true]:w-screen!",
+ "max-sm:*:data-[mobile-layer=true]:min-w-0!",
+ "max-sm:*:data-[mobile-layer=true]:max-w-none!",
+ "max-sm:*:data-[mobile-layer=true]:overflow-visible!",
+ "max-sm:*:data-[mobile-layer=true]:pointer-events-none!",
"max-sm:*:data-[mobile-active=true]:flex-1!",
"max-sm:*:data-[mobile-hidden=true]:flex-none!",
"max-sm:*:data-[mobile-hidden=true]:w-0!",
@@ -442,14 +444,13 @@ export function CommunityShellLayout({
data-mobile-hidden={sidebarMobileHidden || undefined}
className={cn(
"flex flex-col bg-sidebar",
- (isDesktop || isMobileList || isInitial) && "pb-[calc(3.75rem+var(--app-safe-area-bottom))] sm:pb-15",
+ (isDesktop || breakpoint === "mobile" || isInitial) && "pb-[calc(3.75rem+var(--app-safe-area-bottom))] sm:pb-15",
)}
>
<div
ref={sidebarPanelRef}
data-slot="community-sidebar-panel-content"
data-community-mobile-surface={isMobileList ? "list" : undefined}
- hidden={isMobileDetail}
inert={isMobileDetail}
aria-hidden={isMobileDetail || undefined}
className={cn(
@@ -475,7 +476,8 @@ export function CommunityShellLayout({
disabled={!isDesktop}
data-mobile-active={mainMobileActive || undefined}
data-mobile-hidden={mainMobileHidden || undefined}
- className="flex min-w-0 flex-col bg-background"
+ data-mobile-layer={surface === "detail" || undefined}
+ className={cn("flex min-w-0 flex-col sm:bg-background max-sm:absolute max-sm:inset-0 max-sm:pointer-events-none", isInitialDetail && "max-sm:bg-background", mainMobileHidden && "max-sm:hidden")}
>
<div
data-slot="community-main-panel-content"
@@ -484,7 +486,7 @@ export function CommunityShellLayout({
inert={isMobileList}
aria-hidden={isMobileList || undefined}
className={cn(
- "flex min-h-0 flex-1 flex-col",
+ "flex min-h-0 flex-1 flex-col max-sm:pointer-events-auto",
isInitial && surface === "list" && "max-sm:hidden",
)}
>
@@ -505,9 +507,9 @@ export function CommunityShellLayout({
isDesktop && "w-(--community-desktop-user-bar-width)",
isInitial && "w-[calc(100%+3.5rem)] sm:w-(--community-desktop-user-bar-width)",
isInitialDetail && "max-sm:hidden",
- isMobileDetail && preserveHiddenMobileModules && "hidden",
+
)}
- style={isMobileList ? {
+ style={breakpoint === "mobile" ? {
width: `calc(100% + ${COMMUNITY_RAIL_WIDTH}px)`,
marginLeft: -COMMUNITY_RAIL_WIDTH,
}
diff --git a/src/web/src/components/community/shell/mobile-page.dom.test.tsx b/src/web/src/components/community/shell/mobile-page.dom.test.tsx
new file mode 100644
index 000000000..a35c0249d
--- /dev/null
+++ b/src/web/src/components/community/shell/mobile-page.dom.test.tsx
@@ -0,0 +1,296 @@
+import { useMemo, type ReactNode } from "react"
+import { afterEach, describe, expect, it, vi } from "vitest"
+import { act, fireEvent, mockElementGeometry, screen, waitFor } from "@/test/react-dom-harness"
+import { renderCommunity as render } from "@/test/community-owner-harness"
+import { CommunityRouteContext, type CommunityNavigationController } from "@/contexts/community/route-frame"
+import { MobilePageBackContext, type MobilePageBack } from "@/contexts/community/mobile-page-back"
+import { normalizeCommunityHref } from "@/lib/community/community-route"
+import { requestNativeBack } from "@/components/ui/native-back-layer"
+import { MobilePage } from "./mobile-page"
+import { useCommunityRuntime } from "@/stores/community/runtime"
+import { Message } from "@/components/community/messages/message"
+
+vi.mock("@/hooks/use-mobile", () => ({ useIsMobile: () => true }))
+afterEach(() => vi.restoreAllMocks())
+
+function fixture() {
+ let current = true
+ let narrow = true
+ let breakpoint: "mobile" | "desktop" = "mobile"
+ let runtime!: ReturnType<typeof useCommunityRuntime>
+ vi.spyOn(window, "matchMedia").mockImplementation(media => ({
+ media, matches: media === "(max-width: 639px)" && narrow, onchange: null,
+ addListener() {}, removeListener() {}, addEventListener() {}, removeEventListener() {}, dispatchEvent: () => false,
+ }))
+ let request: MobilePageBack | null = null
+ const replace = vi.fn()
+ const navigation: CommunityNavigationController = {
+ publishedHref: "/c/me/friends", navigationPending: false, pendingHref: null,
+ captureIntent: () => () => current, replace, push: vi.fn(), pushImmediate: vi.fn(),
+ resolveAndPush: vi.fn(async () => true), cancelPendingNavigation: vi.fn(),
+ }
+ const frame = { ...normalizeCommunityHref(navigation.publishedHref), revision: 0 }
+ function Fixture({ active = true, children = <input aria-label="Page draft" /> }: { active?: boolean; children?: ReactNode }) {
+ runtime = useCommunityRuntime()
+ const registry = useMemo(() => ({ register: (next: MobilePageBack) => {
+ request = next
+ return () => { if (request === next) request = null }
+ } }), [])
+ return <CommunityRouteContext value={{ breakpoint, navigation, frame, ownerDeleteRouteScope: undefined }}>
+ <MobilePageBackContext value={registry}>
+ <MobilePage active={active} parentPath="/c/me">{children}</MobilePage>
+ </MobilePageBackContext>
+ </CommunityRouteContext>
+ }
+ return { Fixture, replace, navigation, invalidate: () => { current = false }, back: () => request?.("/c/me"),
+ widen: () => { narrow = false }, retire: () => runtime.lifecycle.setState(state => ({ ...state, active: false })),
+ desktop: () => { narrow = false; breakpoint = "desktop" },
+ }
+}
+
+function holdExit(popup: HTMLElement) {
+ let finish!: () => void
+ const finished = new Promise<void>(resolve => { finish = resolve })
+ const animations = vi.fn(() => [{ finished, effect: { getTiming: () => ({ duration: 220, iterations: 1 }) } }])
+ Object.defineProperty(popup, "getAnimations", { configurable: true, value: animations })
+ return { finish, animations }
+}
+
+describe("mobile page dismissal", () => {
+ it.each([{ userAgent: "iPhone", start: 8 }, { userAgent: "Android WebView", start: 80 }])("follows an inline $userAgent page touch inside a vertical scroller, cancels, then commits one parent Back", async ({ userAgent, start }) => {
+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue(userAgent)
+ const task = fixture()
+ render(<task.Fixture><div style={{ overflowY: "auto" }} data-testid="page-scroll"><div data-testid="page-touch">Page body</div></div></task.Fixture>)
+ const area = screen.getByTestId("page-touch")
+ const popup = area.closest<HTMLElement>('[data-slot="mobile-page"]')!
+ const scroller = screen.getByTestId("page-scroll")
+ const restorePopup = mockElementGeometry(popup, { width: 390, height: 600, offsetWidth: 390, offsetHeight: 600, clientWidth: 390, clientHeight: 600 })
+ const restoreScroll = mockElementGeometry(scroller, { width: 390, height: 600, clientWidth: 390, clientHeight: 600, scrollWidth: 390, scrollHeight: 1800 })
+ const hitTest = Object.getOwnPropertyDescriptor(document, "elementFromPoint")
+ Object.defineProperty(document, "elementFromPoint", { configurable: true, value: () => area })
+ const touch = (type: string, x: number, time: number) => {
+ const point = { clientX: x, clientY: 100, identifier: 0, target: area }
+ const event = new Event(type, { bubbles: true, cancelable: true })
+ Object.defineProperties(event, {
+ touches: { value: type === "touchend" || type === "touchcancel" ? [] : [point] },
+ changedTouches: { value: [point] }, timeStamp: { value: time },
+ })
+ fireEvent(area, event)
+ }
+ try {
+ touch("touchstart", start, 100)
+ touch("touchmove", 170, 300)
+ touch("touchmove", 220, 500)
+ expect(popup).toHaveAttribute("data-swiping")
+ expect(popup.style.transform).toContain("50px")
+ touch("touchcancel", 220, 700)
+ await waitFor(() => expect(popup).not.toHaveAttribute("data-swiping"))
+ expect(popup).toHaveAttribute("data-open")
+ expect(task.replace).not.toHaveBeenCalled()
+ const animation = holdExit(popup)
+ touch("touchstart", start, 1000)
+ touch("touchmove", 170, 1200)
+ touch("touchmove", 380, 1400)
+ touch("touchend", 380, 1600)
+ await waitFor(() => expect(popup).toHaveAttribute("data-closed"))
+ expect(task.replace).not.toHaveBeenCalled()
+ await waitFor(() => expect(animation.animations).toHaveBeenCalled())
+ await act(async () => animation.finish())
+ expect(task.replace).toHaveBeenCalledExactlyOnceWith("/c/me", { resume: true })
+ } finally {
+ restorePopup(); restoreScroll()
+ if (hitTest) Object.defineProperty(document, "elementFromPoint", hitTest)
+ else Reflect.deleteProperty(document, "elementFromPoint")
+ }
+ })
+
+ it.each(["iPhone", "Android WebView"])("gives the page strip and message Reply separate start ownership on %s", async (userAgent) => {
+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue(userAgent)
+ const task = fixture(), reply = vi.fn()
+ render(<task.Fixture><Message m={{ id: "m1", type: "chat", authorId: "author", content: "Swipe text", createdAt: new Date(0).toISOString(), grouped: false }} onOpenThread={vi.fn()} onReply={reply} hoverCapable={false} /></task.Fixture>)
+ const area = screen.getByText("Swipe text")
+ const row = area.closest<HTMLElement>("[data-page-swipe-reply-row]")!
+ const popup = area.closest<HTMLElement>('[data-slot="mobile-page"]')!
+ const restore = mockElementGeometry(popup, { width: 390, height: 600, offsetWidth: 390, offsetHeight: 600, clientWidth: 390, clientHeight: 600 })
+ const restoreWidth = mockElementGeometry(document.documentElement, { clientWidth: 390, clientHeight: 844 })
+ const originalHit = Object.getOwnPropertyDescriptor(document, "elementFromPoint")
+ const originalBridge = Object.getOwnPropertyDescriptor(window, "AlookNative")
+ Object.defineProperty(document, "elementFromPoint", { configurable: true, value: () => area })
+ Object.defineProperty(window, "AlookNative", { configurable: true, value: { getSystemGestureRegion: () => '{"left":48,"right":48,"width":780}' } })
+ const pointer = (type: "pointerDown" | "pointerMove" | "pointerUp", x: number) => fireEvent[type](area, { pointerType: "touch", pointerId: 1, clientX: x, clientY: 100 })
+ const touch = (type: "touchstart" | "touchmove" | "touchcancel", x: number) => {
+ const point = { clientX: x, clientY: 100, identifier: 0, target: area }
+ const event = new Event(type, { bubbles: true, cancelable: true })
+ Object.defineProperties(event, { touches: { value: type === "touchcancel" ? [] : [point] }, changedTouches: { value: [point] } })
+ fireEvent(area, event)
+ }
+ try {
+ if (userAgent === "Android WebView") {
+ pointer("pointerDown", 8)
+ touch("touchstart", 8)
+ pointer("pointerMove", 78)
+ touch("touchmove", 78)
+ pointer("pointerUp", 78)
+ touch("touchcancel", 78)
+ expect(reply).not.toHaveBeenCalled()
+ expect(popup).not.toHaveAttribute("data-swiping")
+ }
+ const start = userAgent === "iPhone" ? 8 : 24
+ pointer("pointerDown", start)
+ touch("touchstart", start)
+ pointer("pointerMove", start + 50)
+ touch("touchmove", start + 50)
+ pointer("pointerMove", start + 100)
+ touch("touchmove", start + 100)
+ expect(popup).toHaveAttribute("data-swiping")
+ expect(popup.style.transform).toContain("50px")
+ expect(row.style.transform).toBe("")
+ expect(reply).not.toHaveBeenCalled()
+ touch("touchcancel", start + 100)
+ pointer("pointerUp", start + 100)
+ await waitFor(() => expect(popup).not.toHaveAttribute("data-swiping"))
+ expect(task.replace).not.toHaveBeenCalled()
+ pointer("pointerDown", 220)
+ touch("touchstart", 220)
+ pointer("pointerMove", 290)
+ touch("touchmove", 290)
+ expect(row.style.transform).toContain("translate3d")
+ expect(popup).not.toHaveAttribute("data-swiping")
+ pointer("pointerUp", 290)
+ touch("touchcancel", 290)
+ expect(reply).toHaveBeenCalledOnce()
+ expect(task.replace).not.toHaveBeenCalled()
+ } finally {
+ restore(); restoreWidth()
+ if (originalHit) Object.defineProperty(document, "elementFromPoint", originalHit)
+ else Reflect.deleteProperty(document, "elementFromPoint")
+ if (originalBridge) Object.defineProperty(window, "AlookNative", originalBridge)
+ else Reflect.deleteProperty(window, "AlookNative")
+ }
+ })
+
+ it.each([true, false].flatMap(withReply => [{ withReply, deltas: [32] }, { withReply, deltas: [76, 0] }]))("keeps a page-zone drag ($deltas,reply=$withReply) from becoming a message menu tap", async ({ deltas, withReply }) => {
+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue("iPhone")
+ const task = fixture(), reply = vi.fn()
+ render(<task.Fixture><Message m={{ id: "m1", type: "chat", authorId: "author", content: "Page drag text", createdAt: new Date(0).toISOString(), grouped: false }} onOpenThread={vi.fn()} onReply={withReply ? reply : undefined} onCopy={vi.fn()} hoverCapable={false} /></task.Fixture>)
+ const area = screen.getByText("Page drag text")
+ const row = area.closest<HTMLElement>("[data-page-swipe-reply-row]")!
+ const capture = vi.fn()
+ Object.defineProperty(row, "setPointerCapture", { configurable: true, value: capture })
+ const width = mockElementGeometry(document.documentElement, { clientWidth: 390, clientHeight: 844 })
+ const pointer = (type: string, x: number) => fireEvent(row, new PointerEvent(type, { bubbles: true, pointerType: "touch", pointerId: 19, clientX: x, clientY: 100 }))
+ try {
+ pointer("pointerdown", 8)
+ for (const delta of deltas) pointer("pointermove", 8 + delta)
+ pointer("pointerup", 8 + deltas.at(-1)!)
+ fireEvent.click(row)
+ expect(screen.queryAllByRole("menuitem")).toHaveLength(0)
+ expect(reply).not.toHaveBeenCalled()
+ expect(capture).not.toHaveBeenCalled()
+ expect(row.style.transform).toBe("")
+ expect(task.replace).not.toHaveBeenCalled()
+ pointer("pointerdown", 8)
+ pointer("pointermove", 40)
+ pointer("pointercancel", 40)
+ fireEvent.click(row)
+ expect(screen.queryAllByRole("menuitem")).toHaveLength(0)
+ expect(reply).not.toHaveBeenCalled()
+ pointer("pointerdown", 8)
+ pointer("pointerup", 8)
+ fireEvent.click(row)
+ expect(screen.getAllByRole("menuitem").length).toBeGreaterThan(0)
+ } finally { width() }
+ })
+
+ it("retains message-body Reply outside the page strip at the original100px start", () => {
+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue("iPhone")
+ const task = fixture(), reply = vi.fn()
+ render(<task.Fixture><Message m={{ id: "m1", type: "chat", authorId: "author", content: "Body reply text", createdAt: new Date(0).toISOString(), grouped: false }} onOpenThread={vi.fn()} onReply={reply} hoverCapable={false} /></task.Fixture>)
+ const row = screen.getByText("Body reply text").closest<HTMLElement>("[data-page-swipe-reply-row]")!
+ const width = mockElementGeometry(document.documentElement, { clientWidth: 390, clientHeight: 844 })
+ const pointer = (type: string, x: number) => fireEvent(row, new PointerEvent(type, { bubbles: true, cancelable: true, pointerType: "touch", pointerId: 17, clientX: x, clientY: 100 }))
+ try {
+ pointer("pointerdown", 100)
+ pointer("pointermove", 172)
+ pointer("pointerup", 172)
+ expect(reply).toHaveBeenCalledOnce()
+ expect(task.replace).not.toHaveBeenCalled()
+ } finally { width() }
+ })
+
+ it("reopens the retained current page on desktop while a completed mobile Back still waits for parent publication", async () => {
+ const task = fixture()
+ const view = render(<task.Fixture />)
+ const input = screen.getByLabelText("Page draft")
+ const popup = input.closest<HTMLElement>('[data-slot="mobile-page"]')!
+ const animation = holdExit(popup)
+ act(() => { task.back() })
+ await waitFor(() => expect(animation.animations).toHaveBeenCalled())
+ await act(async () => animation.finish())
+ expect(task.replace).toHaveBeenCalledExactlyOnceWith("/c/me", { resume: true })
+ task.navigation.pendingHref = "/c/me"
+ view.rerender(<task.Fixture />)
+ expect(popup).toHaveAttribute("data-closed")
+ task.desktop()
+ view.rerender(<task.Fixture />)
+ expect(screen.getByLabelText("Page draft")).toBe(input)
+ expect(popup).toHaveAttribute("data-open")
+ expect(input.closest("[inert]")).toBeNull()
+ expect(task.replace).toHaveBeenCalledTimes(1)
+ })
+
+ it.each(["viewport", "owner"])("checks live %s authority before a queued completion", async (boundary) => {
+ const task = fixture()
+ render(<task.Fixture />)
+ const popup = screen.getByLabelText("Page draft").closest<HTMLElement>('[data-slot="mobile-page"]')!
+ const animation = holdExit(popup)
+ act(() => { task.back() })
+ await waitFor(() => expect(animation.animations).toHaveBeenCalled())
+ if (boundary === "viewport") task.widen()
+ else task.retire()
+ await act(async () => animation.finish())
+ expect(task.replace).not.toHaveBeenCalled()
+ })
+
+ it("accepts close first and commits exactly one Back after the real completion boundary", async () => {
+ const task = fixture()
+ render(<task.Fixture />)
+ const popup = screen.getByLabelText("Page draft").closest<HTMLElement>('[data-slot="mobile-page"]')!
+ await waitFor(() => expect(popup).toHaveAttribute("data-open"))
+ const animation = holdExit(popup)
+ act(() => { expect(task.back()).toBe(true); expect(task.back()).toBe(true) })
+ expect(popup).toHaveAttribute("data-closed")
+ expect(task.replace).not.toHaveBeenCalled()
+ await waitFor(() => expect(animation.animations).toHaveBeenCalled())
+ await act(async () => animation.finish())
+ await waitFor(() => expect(task.replace).toHaveBeenCalledExactlyOnceWith("/c/me", { resume: true }))
+ })
+
+ it("retires a closing callback when a newer navigation supersedes it", async () => {
+ const task = fixture()
+ const view = render(<task.Fixture />)
+ const popup = screen.getByLabelText("Page draft").closest<HTMLElement>('[data-slot="mobile-page"]')!
+ const animation = holdExit(popup)
+ act(() => { task.back() })
+ await waitFor(() => expect(animation.animations).toHaveBeenCalled())
+ task.invalidate()
+ task.navigation.publishedHref = "/c/me/bots"
+ view.rerender(<task.Fixture />)
+ await act(async () => animation.finish())
+ expect(task.replace).not.toHaveBeenCalled()
+ expect(popup).toHaveAttribute("data-open")
+ })
+
+ it("keeps page semantics and gives inactive background neither Back nor focus ownership", async () => {
+ const task = fixture()
+ const view = render(<task.Fixture />)
+ const input = screen.getByLabelText("Page draft")
+ const popup = input.closest('[data-slot="mobile-page"]')!
+ expect(popup).toHaveAttribute("role", "presentation")
+ expect(input).not.toHaveFocus()
+ expect(requestNativeBack(document)).toBe("none")
+ view.rerender(<task.Fixture active={false} />)
+ expect(popup.closest('[data-mobile-page-active="false"]')).toHaveAttribute("inert")
+ expect(task.back()).toBeUndefined()
+ })
+})
diff --git a/src/web/src/components/community/shell/mobile-page.scroll.dom.test.tsx b/src/web/src/components/community/shell/mobile-page.scroll.dom.test.tsx
new file mode 100644
index 000000000..41ae72cd2
--- /dev/null
+++ b/src/web/src/components/community/shell/mobile-page.scroll.dom.test.tsx
@@ -0,0 +1,124 @@
+import { beforeEach, afterEach, describe, expect, it, vi } from "vitest"
+import type { PropsWithChildren } from "react"
+import { act, screen } from "@/test/react-dom-harness"
+import { renderToString } from "react-dom/server"
+import { hydrateRoot } from "react-dom/client"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { CommunityTestProvider } from "@/test/community-owner-fixture"
+import { bodyTop, installMessageScrollFixture, restoreMessageScrollFixture, message, mount, resize, scrollFixture } from "@/test/message-scroll-fixture"
+import { CommunityRouteContext } from "@/contexts/community/route-frame"
+import { MobilePage } from "./mobile-page"
+
+const viewport = vi.hoisted(() => ({ breakpoint: "desktop" as "unknown" | "desktop" | "mobile" }))
+vi.mock("@/hooks/use-mobile", () => ({ useIsMobile: () => viewport.breakpoint === "mobile" }))
+beforeEach(() => { viewport.breakpoint = "desktop"; installMessageScrollFixture() })
+afterEach(restoreMessageScrollFixture)
+
+describe("first mobile Portal adoption with the native message virtualizer", () => {
+ it("hydrates the original SSR control and retains its draft, focus and selection through both breakpoint directions", async () => {
+ const owner = await createCommunityQueryOwner()
+ const navigation = { captureIntent: () => () => true, replace: vi.fn(), pendingHref: null, publishedHref: "/c/channels/s1/c1" }
+ let parentReady = false
+ function Page() {
+ return <CommunityTestProvider client={owner.client} registry={owner.registry} retainOwner>
+ <CommunityRouteContext value={{ breakpoint: viewport.breakpoint, navigation, frame: { revision: 0 } } as never}>
+ <div className="relative flex min-h-0 flex-1 flex-col">
+ {parentReady && <MobilePage key="parent" active={false} parentPath="/c/channels/s1"><span>Retained parent</span></MobilePage>}
+ <MobilePage key="foreground" parentPath="/c/channels/s1"><input aria-label="SSR draft" defaultValue="Initial" /></MobilePage>
+ </div>
+ </CommunityRouteContext>
+ </CommunityTestProvider>
+ }
+ viewport.breakpoint = "unknown"
+ const container = document.createElement("div")
+ container.innerHTML = renderToString(<Page />)
+ document.body.appendChild(container)
+ const input = container.querySelector("input")!
+ expect(input).not.toBeNull()
+ expect(input.closest('[data-slot="mobile-page"]')).toHaveAttribute("data-open")
+ expect(input.closest('[data-slot="mobile-page"]')).not.toHaveAttribute("data-starting-style")
+ input.value = "Typed before hydration"
+ input.focus()
+ input.setSelectionRange(2, 5)
+ let root!: ReturnType<typeof hydrateRoot>
+ await act(async () => { root = hydrateRoot(container, <Page />) })
+ try {
+ for (const breakpoint of ["desktop", "mobile", "desktop", "mobile"] as const) {
+ viewport.breakpoint = breakpoint
+ await act(async () => root.render(<Page />))
+ expect(container.querySelector("input")).toBe(input)
+ expect(input).toHaveValue("Typed before hydration")
+ expect(input).toHaveFocus()
+ expect([input.selectionStart, input.selectionEnd]).toEqual([2, 5])
+ }
+ for (const ready of [true, false]) {
+ parentReady = ready
+ await act(async () => root.render(<Page />))
+ expect(container.querySelector("input")).toBe(input)
+ expect(input).toHaveValue("Typed before hydration")
+ expect(input).toHaveFocus()
+ expect([input.selectionStart, input.selectionEnd]).toEqual([2, 5])
+ const pages = container.querySelectorAll("[data-mobile-page-active]")
+ expect(pages).toHaveLength(ready ? 2 : 1)
+ for (const page of pages) expect(page).toHaveClass("max-sm:absolute", "max-sm:inset-0")
+ const background = container.querySelector('[data-mobile-page-active="false"]')
+ if (ready) {
+ expect(background).toHaveAttribute("inert")
+ expect(background).toHaveAttribute("aria-hidden", "true")
+ }
+ }
+ expect(navigation.replace).not.toHaveBeenCalled()
+ } finally {
+ await act(async () => root.unmount())
+ container.remove()
+ }
+ })
+
+ it.each(["reader", "tail"])("retains the %s through the first mobile layout and width-dependent measurements", async position => {
+ const owner = await createCommunityQueryOwner()
+ const navigation = { captureIntent: () => () => true, replace: vi.fn(), pendingHref: null, publishedHref: "/c/channels/s1/c1" }
+ let parentReady = false
+ function Wrapper({ children }: PropsWithChildren) {
+ return <CommunityTestProvider client={owner.client} registry={owner.registry} retainOwner>
+ <CommunityRouteContext value={{ breakpoint: viewport.breakpoint, navigation, frame: { revision: 0 } } as never}>
+ <div className="relative flex min-h-0 flex-1 flex-col">
+ {parentReady && <MobilePage key="parent" active={false} parentPath="/c/channels/s1"><span>Retained parent</span></MobilePage>}
+ <MobilePage key="foreground" parentPath="/c/channels/s1">{children}</MobilePage>
+ </div>
+ </CommunityRouteContext>
+ </CommunityTestProvider>
+ }
+ const h = mount({ items: Array.from({ length: 50 }, (_, i) => message(`m${i}`)), hasMoreOlder: false }, false, undefined, Wrapper)
+ if (position === "reader") h.move(730)
+ const native = scrollFixture.latest.virtualizer
+ const fold = native.getVirtualItems().find(row => row.key.toString().startsWith("msg:") && row.end > h.root.scrollTop)!
+ const id = String(fold.key).slice(4)
+ const before = bodyTop(h.root, id)
+ viewport.breakpoint = "mobile"
+ scrollFixture.width = 390
+ for (let i = 0; i < 50; i++) scrollFixture.bodyHeights.set(`m${i}`, 130)
+ h.stage({})
+ resize()
+ const root = screen.getByTestId("scroll")
+ expect(root).toBe(h.root)
+ expect(root.closest('[data-slot="mobile-page"]')).not.toBeNull()
+ if (position === "reader") expect(bodyTop(root, id)).toBeCloseTo(before, 0)
+ else expect(root.scrollHeight - root.clientHeight - root.scrollTop).toBeLessThanOrEqual(1)
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
+ expect(navigation.replace).not.toHaveBeenCalled()
+ for (const ready of [true, false]) {
+ parentReady = ready
+ h.stage({})
+ resize()
+ expect(screen.getByTestId("scroll")).toBe(h.root)
+ expect(scrollFixture.latest.virtualizer).toBe(native)
+ if (position === "reader") expect(bodyTop(h.root, id)).toBeCloseTo(before, 0)
+ else expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
+ expect(navigation.replace).not.toHaveBeenCalled()
+ const page = h.root.closest("[data-mobile-page-active]")
+ expect(page).toHaveAttribute("data-mobile-page-active", "true")
+ expect(page).toHaveClass("max-sm:absolute", "max-sm:inset-0")
+ }
+ })
+})
diff --git a/src/web/src/components/community/shell/mobile-page.tsx b/src/web/src/components/community/shell/mobile-page.tsx
new file mode 100644
index 000000000..1c75ca454
--- /dev/null
+++ b/src/web/src/components/community/shell/mobile-page.tsx
@@ -0,0 +1,72 @@
+"use client"
+
+import { useCallback, useContext, useLayoutEffect, useRef, useState, type ReactNode } from "react"
+import { useCommunityRouteFrame } from "./community-route-context"
+import { MobilePageBackContext } from "@/contexts/community/mobile-page-back"
+import { useCommunityWsStore } from "@/stores/community/ws"
+import { useCommunityRuntime } from "@/stores/community/runtime"
+import { requestNativeBack } from "@/components/ui/native-back-layer"
+import { SwipeRoot, SwipePortal, SwipeViewport, SwipePopup } from "@/components/ui/swipe-container"
+
+export function MobilePage({ children, parentPath, active = true, backgroundVisible = true }: {
+ children: ReactNode
+ parentPath: string
+ active?: boolean
+ backgroundVisible?: boolean
+}) {
+ const { breakpoint, navigation, frame } = useCommunityRouteFrame()
+ const registry = useContext(MobilePageBackContext)
+ const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)
+ const runtime = useCommunityRuntime()
+ const [open, setOpen] = useState(breakpoint !== "mobile")
+ const pending = useRef<(() => boolean) | null>(null)
+ const departed = useRef(false)
+ const mobile = breakpoint === "mobile"
+ const request = useCallback((target: string) => {
+ if (!active || !mobile || target !== parentPath) return false
+ if (pending.current) return true
+ if (requestNativeBack(document) !== "none") return false
+ const current = navigation.captureIntent()
+ pending.current = () => runtime.lifecycle.get().active && runtime.ws.get().accessEpoch === accessEpoch
+ && window.matchMedia("(max-width: 639px)").matches && current()
+ setOpen(false)
+ return true
+ }, [accessEpoch, active, mobile, navigation, parentPath, runtime])
+ useLayoutEffect(() => {
+ if (mobile && departed.current && (navigation.pendingHref === parentPath || navigation.publishedHref === parentPath)) return
+ departed.current = false
+ pending.current = null
+ setOpen(true)
+ return () => { pending.current = null }
+ }, [mobile, active, frame.revision, navigation.pendingHref, navigation.publishedHref, accessEpoch, parentPath])
+ useLayoutEffect(() => {
+ if (!mobile || !active) return
+ return registry?.register(request)
+ }, [active, mobile, registry, request])
+ return <div inert={!active} aria-hidden={!active || undefined} data-mobile-page-active={active}
+ hidden={!active && (!mobile || !backgroundVisible)} className="flex min-h-0 min-w-0 flex-1 flex-col max-sm:absolute max-sm:inset-0">
+ <SwipeRoot kind="page" open={open} swipeEnabled={mobile && active && !navigation.navigationPending}
+ onOpenChange={(next, details) => {
+ if (next) return
+ if (details.reason !== "swipe" || !request(parentPath)) details.cancel()
+ }}
+ onOpenChangeComplete={(next) => {
+ if (next) return
+ const valid = pending.current
+ pending.current = null
+ if (valid?.()) {
+ departed.current = true
+ navigation.replace(parentPath, { resume: true })
+ }
+ }}>
+ <SwipePortal inline keepMounted>
+ <SwipeViewport className="flex min-h-0 flex-1 max-sm:fixed max-sm:inset-0 max-sm:z-20">
+ <SwipePopup data-slot="mobile-page" data-background={!active || undefined}
+ className="flex h-full w-full min-w-0 flex-col bg-background outline-none">
+ {children}
+ </SwipePopup>
+ </SwipeViewport>
+ </SwipePortal>
+ </SwipeRoot>
+ </div>
+}
diff --git a/src/web/src/components/community/shell/shell-frame-overlays.dom.test.ts b/src/web/src/components/community/shell/shell-frame-overlays.dom.test.ts
index 2017cdcf3..383b12ab4 100644
--- a/src/web/src/components/community/shell/shell-frame-overlays.dom.test.ts
+++ b/src/web/src/components/community/shell/shell-frame-overlays.dom.test.ts
@@ -144,7 +144,7 @@ describe("ShellFrameOverlays", () => {
}))
expect(renderer.container.querySelectorAll("profile-card")).toHaveLength(0)
- expect(renderer.container.querySelectorAll("image-lightbox")).toHaveLength(0)
+ expect(hostProps.get("image-lightbox")).toMatchObject({ image: null })
expect(renderer.container.querySelectorAll("crop-dialog")).toHaveLength(0)
expect(hostProps.get("attachment-sheet")).toMatchObject({
attachment: null,
diff --git a/src/web/src/components/community/shell/shell-frame-overlays.tsx b/src/web/src/components/community/shell/shell-frame-overlays.tsx
index 9fd40423f..d83e1340d 100644
--- a/src/web/src/components/community/shell/shell-frame-overlays.tsx
+++ b/src/web/src/components/community/shell/shell-frame-overlays.tsx
@@ -43,9 +43,7 @@ export function ShellFrameOverlays({
onOpenBotAudit={controller.openBotAudit}
/>
)}
- {controller.preview && (
- <ImageLightbox image={controller.preview} onClose={controller.closePreview} />
- )}
+ <ImageLightbox image={controller.preview} onClose={controller.closePreview} />
<AttachmentPreviewSheet
attachment={controller.attachmentPreview}
open={!!controller.attachmentPreview}
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 f50825576..133c2a5fa 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
@@ -9,6 +9,8 @@ import {
desktopUserBarInitialOverlayCssWidth,
} from "./shell-frame-geometry"
+vi.mock("./mobile-page", () => ({ MobilePage: ({ children }: { children: ReactNode }) => children }))
+
const mocks = vi.hoisted(() => ({
onLayoutChanged: vi.fn(),
dmMount: vi.fn(),
@@ -301,8 +303,15 @@ describe("ShellFrameView", () => {
inbox,
}, createElement("main-content")))
expect(renderer.container.querySelectorAll("[data-channel-loading-frame]")).toHaveLength(0)
- const initialRailWrapper = renderer.container.querySelector('[class*="hidden sm:contents"]')!
+ const initialRailWrapper = renderer.container.querySelector('[class*="invisible sm:visible sm:contents"]')!
expect(initialRailWrapper.className).toContain("min-h-0")
+ expect(initialRailWrapper.className).not.toContain("hidden")
+ expect(initialRailWrapper).toHaveAttribute("inert")
+ expect(initialRailWrapper).toHaveAttribute("aria-hidden", "true")
+ expect(renderer.container.querySelector('[data-slot="community-shell-body"]')?.className).toContain("pt-2")
+ expect(renderer.container.querySelector('[data-slot="community-shell-body"]')?.className).not.toContain("pt-0")
+ expect(renderer.container.querySelector('[data-app-surface]')?.className).not.toContain("max-sm:border-0")
+ expect(latestProps(mocks.panelProps, "main").className).toContain("max-sm:bg-background")
expect(renderer.container.querySelectorAll("sidebar-content")).toHaveLength(1)
expect(renderer.container.querySelectorAll("[data-user-bar]")).toHaveLength(1)
expect(renderer.container.querySelector('[data-slot="community-user-bar-overlay"]')?.className)
@@ -311,6 +320,8 @@ describe("ShellFrameView", () => {
expect(renderer.container.querySelectorAll("[data-shell-overlays]")).toHaveLength(0)
expect(latestProps(mocks.panelProps, "sidebar")["data-mobile-hidden"]).toBe(true)
expect(latestProps(mocks.panelProps, "main")["data-mobile-active"]).toBe(true)
+ expect(latestProps(mocks.panelProps, "main")["data-mobile-layer"]).toBe(true)
+ expect(latestProps(mocks.panelProps, "main")["data-mobile-hidden"]).toBeUndefined()
const initialGroup = latestProps(mocks.groupProps)
expect(initialGroup.className).toContain(
"max-sm:*:data-[mobile-active=true]:flex-1!",
@@ -407,6 +418,8 @@ describe("ShellFrameView", () => {
inbox,
}, createElement("main-content")))
expect(renderer.container.querySelectorAll("[data-server-rail]")).toHaveLength(1)
+ expect(renderer.container.querySelector("[data-community-rail]")).not.toHaveAttribute("inert")
+ expect(renderer.container.querySelector("[data-community-rail]")).not.toHaveAttribute("aria-hidden")
expect(renderer.container.querySelectorAll("sidebar-content")).toHaveLength(1)
expect(renderer.container.querySelectorAll("[data-user-bar]")).toHaveLength(1)
expect(renderer.container.querySelectorAll("[data-channel-loading-frame]")).toHaveLength(0)
@@ -432,6 +445,8 @@ describe("ShellFrameView", () => {
}, createElement("main-content")))
const shell = renderer.container.querySelector("[data-shell-root]")!
+ expect(shell.querySelector("[data-community-rail]")).not.toHaveAttribute("inert")
+ expect(shell.querySelector("[data-community-rail]")).not.toHaveAttribute("aria-hidden")
const hostTypes = [...shell.querySelectorAll("*")].map((node) => (
node.hasAttribute("data-server-rail") ? "server-rail"
: node.hasAttribute("data-app-surface") ? "app-surface"
@@ -750,6 +765,7 @@ describe("ShellFrameView", () => {
expect(mobileSidebarPanel["data-mobile-hidden"]).toBeUndefined()
expect(latestProps(mocks.panelProps, "main")["data-mobile-active"]).toBeUndefined()
expect(latestProps(mocks.panelProps, "main")["data-mobile-hidden"]).toBe(true)
+ expect(latestProps(mocks.panelProps, "main")["data-mobile-layer"]).toBeUndefined()
expect(latestProps(mocks.groupProps).disabled).toBe(true)
expect(latestProps(mocks.groupProps).className).toContain(
"max-sm:*:data-[mobile-active=true]:flex-1!",
@@ -778,14 +794,15 @@ describe("ShellFrameView", () => {
expect(renderer.container.querySelectorAll('[data-slot="community-user-bar-overlay"]')).toHaveLength(1)
expect(renderer.container.querySelectorAll('[data-slot="community-user-bar-underlay"]')).toHaveLength(1)
expect(renderer.container.querySelectorAll("[data-app-surface]")).toHaveLength(1)
- expect(renderer.container.querySelector("[data-app-surface]")?.className).toContain("rounded-none")
+ expect(renderer.container.querySelector("[data-app-surface]")?.className).toContain("rounded-tl-xl")
expect(renderer.container.querySelectorAll("main-content")).toHaveLength(1)
expect(latestProps(mocks.panelProps, "sidebar").hidden).toBeUndefined()
expect(latestProps(mocks.panelProps, "main").hidden).toBeUndefined()
- expect(latestProps(mocks.panelProps, "sidebar")["data-mobile-active"]).toBeUndefined()
- expect(latestProps(mocks.panelProps, "sidebar")["data-mobile-hidden"]).toBe(true)
- expect(latestProps(mocks.panelProps, "main")["data-mobile-active"]).toBe(true)
+ expect(latestProps(mocks.panelProps, "sidebar")["data-mobile-active"]).toBe(true)
+ expect(latestProps(mocks.panelProps, "sidebar")["data-mobile-hidden"]).toBeUndefined()
+ expect(latestProps(mocks.panelProps, "main")["data-mobile-active"]).toBeUndefined()
expect(latestProps(mocks.panelProps, "main")["data-mobile-hidden"]).toBeUndefined()
+ expect(latestProps(mocks.panelProps, "main")["data-mobile-layer"]).toBe(true)
expect(renderer.container.querySelectorAll("[data-shell-overlays]")).toHaveLength(1)
const detailMotion = renderer.container.querySelector('[data-community-mobile-surface="detail"]')!
expect(detailMotion.className).toContain("flex")
@@ -793,7 +810,7 @@ describe("ShellFrameView", () => {
const detailSidebar = renderer.container.querySelector(
'[data-slot="community-sidebar-panel-content"]',
)!
- expect(detailSidebar).toHaveAttribute("hidden")
+ expect(detailSidebar).not.toHaveAttribute("hidden")
expect(detailSidebar).toHaveAttribute("inert")
expect(detailSidebar).toHaveAttribute("aria-hidden", "true")
expect(renderer.container.querySelector('[data-slot="community-shell-root"]'))
diff --git a/src/web/src/components/community/shell/shell-frame-view.tsx b/src/web/src/components/community/shell/shell-frame-view.tsx
index cc1d01028..368ba9cc4 100644
--- a/src/web/src/components/community/shell/shell-frame-view.tsx
+++ b/src/web/src/components/community/shell/shell-frame-view.tsx
@@ -1,5 +1,6 @@
"use client"
+import { MobilePage } from "./mobile-page"
import { DmRoute } from "@/components/community/channels/dm-route"
import { ChannelSidebarSkeleton } from "@/components/community/channels/channel-sidebar"
import { DmSidebarSkeleton } from "@/components/community/channels/dm-sidebar"
@@ -97,6 +98,14 @@ export function ShellFrameView({
/>
) : null
+ const main = checkpoint.main.kind === "dm-route" ? (
+ <DmRoute key={`${profile.currentUser.id}/${checkpoint.main.dmId}`} dmId={checkpoint.main.dmId}
+ routeCommitted={routeCommitted} />
+ ) : checkpoint.main.kind === "keep" || checkpoint.main.kind === "server-route" ? children : (
+ <CommunityPendingFrame href={checkpoint.targetHref} reserveBackSlot={surface === "detail"}
+ conversationSubtype={checkpoint.main.conversationSubtype} />
+ )
+ const meDetail = surface === "detail" && checkpoint.targetHref.startsWith("/c/me/")
return (
<CommunityShellLayout
breakpoint={breakpoint}
@@ -117,16 +126,7 @@ export function ShellFrameView({
? <ChannelSidebarSkeleton targetServerId={checkpoint.sidebar.serverId} />
: checkpoint.sidebar.kind === "me-skeleton" ? <DmSidebarSkeleton /> : null}
</>}
- main={checkpoint.main.kind === "dm-route" ? (
- <DmRoute key={`${profile.currentUser.id}/${checkpoint.main.dmId}`} dmId={checkpoint.main.dmId}
- routeCommitted={routeCommitted} />
- ) : checkpoint.main.kind === "keep" || checkpoint.main.kind === "server-route" ? children : (
- <CommunityPendingFrame
- href={checkpoint.targetHref}
- reserveBackSlot={surface === "detail"}
- conversationSubtype={checkpoint.main.conversationSubtype}
- />
- )}
+ main={meDetail ? <MobilePage key={checkpoint.targetHref.split("?")[0]} parentPath="/c/me">{main}</MobilePage> : main}
userBar={(
<UserBar
breakpoint={breakpoint}
diff --git a/src/web/src/components/community/shell/shell-frame.dom.test.ts b/src/web/src/components/community/shell/shell-frame.dom.test.ts
index 1c34d2c4f..4c856871e 100644
--- a/src/web/src/components/community/shell/shell-frame.dom.test.ts
+++ b/src/web/src/components/community/shell/shell-frame.dom.test.ts
@@ -434,7 +434,7 @@ describe("ShellFrame orchestration", () => {
}))
const handlers = mocks.registerUiHandlers.mock.calls.at(-1)?.[0]
handlers.goBackMobile()
- expect(mocks.replace).toHaveBeenLastCalledWith("/c/channels/s1")
+ expect(mocks.replace).toHaveBeenLastCalledWith("/c/channels/s1", { resume: true })
})
it("returns mobile server onboarding to the semantic list surface", () => {
@@ -467,7 +467,7 @@ describe("ShellFrame orchestration", () => {
const event = new Event("alook:native-back", { cancelable: true })
act(() => { window.dispatchEvent(event) })
expect(event.defaultPrevented).toBe(true)
- if (expected) expect(mocks.replace).toHaveBeenCalledExactlyOnceWith(expected)
+ if (expected) expect(mocks.replace).toHaveBeenCalledExactlyOnceWith(expected, { resume: true })
else expect(mocks.replace).not.toHaveBeenCalled()
renderer.unmount()
})
@@ -667,7 +667,7 @@ describe("ShellFrame orchestration", () => {
const shell = renderInboxLifecycle()
const overlay = screen.getByTestId(tid.inboxTrigger).closest("[data-slot='community-user-bar-overlay']")!
expect(overlay).toHaveAttribute("inert")
- expect(overlay.classList.contains("hidden")).toBe(true)
+ expect(overlay.classList.contains("hidden")).toBe(false)
fireEvent.click(screen.getByRole("button", { name: "Open Inbox" }))
expect(mocks.push).toHaveBeenCalledExactlyOnceWith("/c/me")
expect(shell.context.navigation.navigationPending).toBe(true)
diff --git a/src/web/src/components/community/shell/shell-frame.tsx b/src/web/src/components/community/shell/shell-frame.tsx
index bc254128d..2e214e658 100644
--- a/src/web/src/components/community/shell/shell-frame.tsx
+++ b/src/web/src/components/community/shell/shell-frame.tsx
@@ -1,11 +1,13 @@
"use client"
+import { requestNativeBack } from "@/components/ui/native-back-layer"
+import { MobilePageBackContext, type MobilePageBack } from "@/contexts/community/mobile-page-back"
import { commitNavigation } from "@/lib/observability/context"
import { useAtom, useCreateAtom } from "@tanstack/react-store";
import { getCommunityRuntime } from "@/stores/community/runtime"
-import { useCallback, useEffect, useLayoutEffect, useRef } from "react"
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react"
import { useQueryClient } from "@tanstack/react-query"
import { useBreakpoint } from "@/hooks/use-mobile"
import { useCommunityOnboarding } from "@/lib/community-onboarding"
@@ -310,14 +312,24 @@ const [committedFrame, setCommittedFrame] = useAtom(useCreateAtom(initialCommitt
dismissUserBarExtension()
return true
}, [breakpoint, checkpoint.surface, committedFrame.href, dismissUserBarExtension, navigation.navigationPending, replacePath, userBarExtension.active])
- const goBackMobile = useCallback(() => {
- if (route.parentPath) navigation.replace(route.parentPath)
- }, [navigation, route.parentPath])
+ const pageBack = useRef<MobilePageBack | null>(null)
+ const pageBackRegistry = useMemo(() => ({ register: (request: MobilePageBack) => {
+ pageBack.current = request
+ return () => { if (pageBack.current === request) pageBack.current = null }
+ } }), [])
+ const goBackMobile = useCallback((target = mobileParentPath) => {
+ if (!target) return
+ if (breakpoint === "mobile") {
+ if (requestNativeBack(document) !== "none" || dismissNativeBackShellOverlay()) return
+ if (pageBack.current?.(target)) return
+ navigation.replace(target, { resume: true })
+ } else navigation.replace(target)
+ }, [breakpoint, dismissNativeBackShellOverlay, mobileParentPath, navigation])
useNativeMobileBack({
dismissShellOverlay: dismissNativeBackShellOverlay,
parentPath: mobileParentPath,
- replacePath,
+ replacePath: goBackMobile,
})
useEffect(() => {
@@ -358,6 +370,7 @@ const [committedFrame, setCommittedFrame] = useAtom(useCreateAtom(initialCommitt
return (
<CommunityRouteContext value={{ breakpoint, frame: committedFrame, navigation, ownerDeleteRouteScope, openInbox, notificationConsumer }}>
+ <MobilePageBackContext value={pageBackRegistry}>
<ShellFrameView
breakpoint={breakpoint}
checkpoint={checkpoint}
@@ -377,6 +390,7 @@ const [committedFrame, setCommittedFrame] = useAtom(useCreateAtom(initialCommitt
>
{children}
</ShellFrameView>
+ </MobilePageBackContext>
</CommunityRouteContext>
)
}
diff --git a/src/web/src/components/community/shell/shell.navigation-intent.dom.test.ts b/src/web/src/components/community/shell/shell.navigation-intent.dom.test.ts
index 7534e6484..829815427 100644
--- a/src/web/src/components/community/shell/shell.navigation-intent.dom.test.ts
+++ b/src/web/src/components/community/shell/shell.navigation-intent.dom.test.ts
@@ -164,7 +164,7 @@ beforeEach(() => {
mocks.search = ""
mocks.push.mockReset()
mocks.replace.mockReset()
- vi.stubGlobal("matchMedia", vi.fn(() => ({ matches: false })))
+ vi.stubGlobal("matchMedia", vi.fn(() => ({ matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() })))
})
describe("Shell input and explicit navigation ownership", () => {
diff --git a/src/web/src/components/community/shell/use-community-navigation-controller.dom.test.ts b/src/web/src/components/community/shell/use-community-navigation-controller.dom.test.ts
index 24bbe7221..1f4883e95 100644
--- a/src/web/src/components/community/shell/use-community-navigation-controller.dom.test.ts
+++ b/src/web/src/components/community/shell/use-community-navigation-controller.dom.test.ts
@@ -126,6 +126,14 @@ describe("useCommunityNavigationController", () => {
expect(hook.current.pendingHref).toBe("/c/channels/s1")
})
+ it("marks an explicit parent resume without adding browser history", async () => {
+ const hook = await renderController()
+ await act(async () => hook.current.replace("/c/channels/s1/c1", { resume: true }))
+ expect(hook.current.entryIntent).toEqual({ href: "/c/channels/s1/c1", resume: true })
+ expect(mocks.replace).toHaveBeenCalledExactlyOnceWith("/c/channels/s1/c1")
+ expect(mocks.push).not.toHaveBeenCalled()
+ })
+
it("forwards scroll:false without changing target publication or cancellation", async () => {
const hook = await renderController()
await act(async () => hook.current.push("/c/channels/s1/post2?msg=m2", { scroll: false }))
diff --git a/src/web/src/components/community/shell/use-community-navigation-controller.ts b/src/web/src/components/community/shell/use-community-navigation-controller.ts
index 1a0dbd5eb..8e633fa72 100644
--- a/src/web/src/components/community/shell/use-community-navigation-controller.ts
+++ b/src/web/src/components/community/shell/use-community-navigation-controller.ts
@@ -71,7 +71,7 @@ export function useCommunityNavigationController(
const pendingBaselineLeafRef = useRef(committedFrame.leafKey)
const [navigationPending, setNavigationPending] = useAtom(useCreateAtom(false))
const [pendingHref, setPendingHref] = useAtom(useCreateAtom<string | null>(null))
- const [entryIntent, setEntryIntent] = useAtom(useCreateAtom<{ href: string } | null>(null))
+ const [entryIntent, setEntryIntent] = useAtom(useCreateAtom<{ href: string; resume?: boolean } | null>(null))
const cancelPendingNavigation = useCallback(() => {
supersedeNavigationIntent(gateRef.current)
@@ -157,8 +157,8 @@ export function useCommunityNavigationController(
submitNavigation(() => router.push(href))
}, [committedFrame.leafKey, committedFrame.revision, navigationPending, publishedHref, queryClient, router, setEntryIntent, setNavigationPending, setPendingHref, submitNavigation])
- const replace = useCallback((href: string) => {
- setEntryIntent({ href })
+ const replace = useCallback((href: string, options?: { resume?: boolean }) => {
+ setEntryIntent({ href, ...(options?.resume ? { resume: true } : {}) })
if (href === publishedHref && !navigationPending) { settledIntentRef.current = null; navigationNoop(href); return }
beginNavigation(href)
void prepareNavigationMetadata(queryClient, href, "foreground")
diff --git a/src/web/src/components/community/shell/use-shell-rail-controller.native.dom.test.tsx b/src/web/src/components/community/shell/use-shell-rail-controller.native.dom.test.tsx
index 49eb12c52..973e07f21 100644
--- a/src/web/src/components/community/shell/use-shell-rail-controller.native.dom.test.tsx
+++ b/src/web/src/components/community/shell/use-shell-rail-controller.native.dom.test.tsx
@@ -29,7 +29,7 @@ vi.mock("@/lib/auth-client", () => { const sessionSDK = { useSession: () => ({ d
vi.mock("next/navigation", () => ({ usePathname: () => route.pathname, useSearchParams: () => new URLSearchParams(), useRouter: () => ({ refresh: vi.fn(), push: ui.push, replace: ui.replace }) }))
vi.mock("@tanstack/react-query-devtools", () => ({ ReactQueryDevtools: () => null }))
vi.mock("@/contexts/community/current-user", () => ({ useCurrentUser: () => ({ id: "A" }) }))
-vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "desktop" }))
+vi.mock("@/hooks/use-mobile", () => ({ useIsMobile: () => false, useBreakpoint: () => "desktop" }))
vi.mock("@/hooks/community/use-servers", async (original) => ({
...await original<typeof import("@/hooks/community/use-servers")>(),
useServer: (id: string | null) => ({ server: id ? { id, name: id, categories: [] } : null, data: undefined }),
diff --git a/src/web/src/components/community/shell/user-bar-extension-drawer.tsx b/src/web/src/components/community/shell/user-bar-extension-drawer.tsx
index 2b06cd74c..ea81798b4 100644
--- a/src/web/src/components/community/shell/user-bar-extension-drawer.tsx
+++ b/src/web/src/components/community/shell/user-bar-extension-drawer.tsx
@@ -2,24 +2,54 @@
import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { cloneElement, useLayoutEffect, type ReactElement } from "react"
-import { Collapsible } from "@base-ui/react/collapsible"
+import { cloneElement, useLayoutEffect, useRef, useState, type ReactElement } from "react"
+import { SwipeRoot, SwipePortal, SwipeViewport, SwipePopup } from "@/components/ui/swipe-container"
+import { tid } from "@/lib/community/testids"
+import type { UserBarExtensionKind } from "./user-bar-extension-state"
-type Content = ReactElement<{ interactive?: boolean; animate?: boolean }>
+type Content = ReactElement<{ active?: UserBarExtensionKind; interactive?: boolean; animate?: boolean; focusOnOpen?: boolean; onInitialFocus?: () => void }>
-export function UserBarExtensionDrawer({ children }: { children: Content | null }) {
+function focusPanel(host: HTMLDivElement | null, content: Content) {
+ const panel = host?.querySelector<HTMLElement>(`[data-testid="${tid.userBarExtension}"]`)
+ if (!panel) return
+ panel.focus({ preventScroll: true })
+ content.props.onInitialFocus?.()
+}
+
+export function UserBarExtensionDrawer({ children, onDismiss }: { children: Content | null; onDismiss: () => void }) {
+ const [host, setHost] = useState<HTMLDivElement | null>(null)
const [retained, setRetained] = useAtom(useCreateAtom(children))
+ const committedActive = useRef(children?.props.active)
useLayoutEffect(() => {
if (children) setRetained(children)
}, [children, setRetained])
+ useLayoutEffect(() => {
+ const previous = committedActive.current
+ const active = children?.props.active
+ committedActive.current = active
+ if (!children || previous === undefined || active === undefined || previous === active || !children.props.focusOnOpen) return
+ focusPanel(host, children)
+ }, [children, host])
const open = children !== null
const content = children ?? retained
return (
- <Collapsible.Root open={open} className="community-user-bar-drawer-viewport">
- <Collapsible.Panel className="community-user-bar-drawer" inert={!open}>
- {content && cloneElement(content, { interactive: open, animate: false })}
- </Collapsible.Panel>
- </Collapsible.Root>
+ <div ref={setHost} className="community-user-bar-drawer-viewport">
+ <SwipeRoot open={open} swipeDirection="down" modal={false} disablePointerDismissal
+ onOpenChange={(next) => { if (!next) onDismiss() }}
+ onOpenChangeComplete={(next) => { if (!next) setRetained(null) }}>
+ <SwipePortal container={host} keepMounted>
+ <SwipeViewport>
+ <SwipePopup role="presentation" initialFocus={() => {
+ if (children?.props.focusOnOpen) focusPanel(host, children)
+ return false
+ }} finalFocus={false}
+ data-slot="user-bar-swipe" className="community-user-bar-drawer" inert={!open}>
+ {content && cloneElement(content, { interactive: open, animate: false, focusOnOpen: false })}
+ </SwipePopup>
+ </SwipeViewport>
+ </SwipePortal>
+ </SwipeRoot>
+ </div>
)
}
diff --git a/src/web/src/components/community/shell/user-bar.interaction.dom.test.ts b/src/web/src/components/community/shell/user-bar.interaction.dom.test.ts
index 5a1c2129c..f14c0909f 100644
--- a/src/web/src/components/community/shell/user-bar.interaction.dom.test.ts
+++ b/src/web/src/components/community/shell/user-bar.interaction.dom.test.ts
@@ -1,10 +1,13 @@
import { createElement, startTransition, StrictMode, Suspense, useLayoutEffect, useRef, useState } from "react"
import { describe, expect, it, vi } from "vitest"
-import { act, render, screen, setupUser } from "@/test/react-dom-harness"
-import { UserBar } from "./user-bar"
+import { act, render, screen, setupUser, waitFor } from "@/test/react-dom-harness"
+import { UserBar, UserBarSkeleton } from "./user-bar"
import { UserBarExtensionDrawer } from "./user-bar-extension-drawer"
import { tid } from "@/lib/community/testids"
import type { UserBarExtensionKind } from "./user-bar-extension-state"
+import { requestNativeBack } from "@/components/ui/native-back-layer"
+
+vi.mock("@/hooks/use-mobile", () => ({ useIsMobile: () => true }))
vi.mock("../avatar", () => ({
Avatar: () => createElement("span", { "data-testid": "user-avatar" }),
@@ -28,9 +31,56 @@ function renderBar() {
return { order, onInboxOpenChange, onOpenProfile, onEditProfile }
}
+describe("UserBar native mobile spacing", () => {
+ it.each([
+ { name: "native iPhone", native: true, ua: "iPhone", breakpoint: "mobile", compact: true },
+ { name: "native Android", native: true, ua: "Android", breakpoint: "mobile", compact: true },
+ { name: "mobile browser", native: false, ua: "iPhone", breakpoint: "mobile", compact: false },
+ { name: "narrow desktop Tauri", native: true, ua: "Macintosh", breakpoint: "mobile", compact: false },
+ { name: "wide native iPhone", native: true, ua: "iPhone", breakpoint: "desktop", compact: true },
+ ] as const)("keeps live/loading padding aligned on $name", ({ native, ua, breakpoint, compact }) => {
+ const bridge = Object.getOwnPropertyDescriptor(window, "__TAURI__")
+ const userAgent = vi.spyOn(navigator, "userAgent", "get").mockReturnValue(ua)
+ if (native) Object.defineProperty(window, "__TAURI__", { configurable: true, value: {} })
+ else Reflect.deleteProperty(window, "__TAURI__")
+ try {
+ const view = render(createElement("div", null,
+ createElement(UserBar, { breakpoint, user: { id: "u1", name: "User", avatar: "U" }, hasUnread: false }),
+ createElement(UserBarSkeleton),
+ ))
+ for (const id of [tid.userBar, tid.initialUserBarPending]) {
+ expect(view.getByTestId(id).style.paddingBottom).toBe(compact ? "0.25rem" : "")
+ }
+ } finally {
+ userAgent.mockRestore()
+ if (bridge) Object.defineProperty(window, "__TAURI__", bridge)
+ else Reflect.deleteProperty(window, "__TAURI__")
+ }
+ })
+})
+
describe("UserBar Inbox switching", () => {
+ it("dismisses the real mobile extension once through native Back", async () => {
+ const dismissed = vi.fn()
+ function Harness() {
+ const [active, setActive] = useState<UserBarExtensionKind>("inbox")
+ const inbox = createElement("button", null, "Inbox item")
+ return createElement(UserBar, {
+ breakpoint: "mobile", user: { id: "u1", name: "User", avatar: "U" },
+ hasUnread: false, inboxOpen: active === "inbox",
+ extension: { active, inbox, profile: null, update: null, updateBadgePhase: null, eligibleMachines: [],
+ onOpenUpdate: vi.fn(), onRequestUpdate: vi.fn(), onDismiss: () => { dismissed(); setActive("none") },
+ },
+ })
+ }
+ render(createElement(Harness))
+ act(() => { expect(requestNativeBack(document)).toBe("requested") })
+ expect(dismissed).toHaveBeenCalledOnce()
+ })
+
it("keeps committed mobile extension switching outside render-phase updates", async () => {
const errors = vi.spyOn(console, "error")
+ const focus = vi.spyOn(HTMLElement.prototype, "focus")
function Harness() {
const [active, setActive] = useState<UserBarExtensionKind>("none")
const inbox = createElement("button", null, "Inbox item")
@@ -55,24 +105,42 @@ describe("UserBar Inbox switching", () => {
},
})
}
- const user = setupUser()
- render(createElement(StrictMode, null, createElement(Harness)))
- const trigger = screen.getByTestId(tid.inboxTrigger)
- await user.click(trigger)
- expect(trigger).toHaveAttribute("aria-expanded", "true")
- expect(screen.getByRole("dialog", { name: "Inbox" })).toBeVisible()
- await user.click(screen.getByRole("button", { name: "User", exact: true }))
- expect(screen.getByRole("dialog", { name: "Your profile" })).toBeVisible()
- expect(screen.queryByRole("dialog", { name: "Inbox" })).not.toBeInTheDocument()
- await user.click(trigger)
- expect(screen.getByRole("dialog", { name: "Inbox" })).toBeVisible()
- await user.click(trigger)
- expect(trigger).toHaveAttribute("aria-expanded", "false")
- expect(screen.queryByRole("dialog", { name: "Inbox" })).not.toBeInTheDocument()
- expect(errors.mock.calls.filter((args) => args.some((arg) => (
- typeof arg === "string" && /Cannot update a component|while rendering a different component/.test(arg)
- )))).toEqual([])
- errors.mockRestore()
+ try {
+ const user = setupUser()
+ render(createElement(StrictMode, null, createElement(Harness)))
+ const trigger = screen.getByTestId(tid.inboxTrigger)
+ await user.click(trigger)
+ expect(trigger).toHaveAttribute("aria-expanded", "true")
+ expect(screen.getByRole("dialog", { name: "Inbox" })).toBeVisible()
+ const dialog = screen.getByRole("dialog", { name: "Inbox" })
+ await waitFor(() => expect(dialog).toHaveFocus())
+ const panelFocusCalls = focus.mock.calls.filter((_, index) => focus.mock.contexts[index] === dialog)
+ expect(panelFocusCalls.length).toBeGreaterThan(0)
+ for (const args of panelFocusCalls) expect(args).toEqual([{ preventScroll: true }])
+ await user.click(screen.getByRole("button", { name: "User", exact: true }))
+ const profileDialog = screen.getByRole("dialog", { name: "Your profile" })
+ expect(profileDialog).toBeVisible()
+ expect(profileDialog).toBe(dialog)
+ await waitFor(() => expect(profileDialog).toHaveFocus())
+ expect(screen.queryByRole("dialog", { name: "Inbox" })).not.toBeInTheDocument()
+ await user.click(trigger)
+ const reopenedInbox = screen.getByRole("dialog", { name: "Inbox" })
+ expect(reopenedInbox).toBeVisible()
+ expect(reopenedInbox).toBe(dialog)
+ await waitFor(() => expect(reopenedInbox).toHaveFocus())
+ const allPanelFocusCalls = focus.mock.calls.filter((_, index) => focus.mock.contexts[index] === dialog)
+ expect(allPanelFocusCalls.length).toBeGreaterThanOrEqual(3)
+ for (const args of allPanelFocusCalls) expect(args).toEqual([{ preventScroll: true }])
+ await user.click(trigger)
+ expect(trigger).toHaveAttribute("aria-expanded", "false")
+ expect(screen.queryByRole("dialog", { name: "Inbox" })).not.toBeInTheDocument()
+ expect(errors.mock.calls.filter((args) => args.some((arg) => (
+ typeof arg === "string" && /Cannot update a component|while rendering a different component/.test(arg)
+ )))).toEqual([])
+ } finally {
+ focus.mockRestore()
+ errors.mockRestore()
+ }
})
it("keeps only committed content when a suspended extension render is abandoned", async () => {
@@ -97,7 +165,7 @@ describe("UserBar Inbox switching", () => {
}, "Start pending content"),
createElement("button", { onClick: () => setLabel(null) }, "Close drawer"),
createElement(Suspense, { fallback: createElement("span", null, "Pending") },
- createElement(UserBarExtensionDrawer, null,
+ createElement(UserBarExtensionDrawer, { onDismiss: () => setLabel(null) },
label === null ? null : createElement(Content, { label }),
),
),
@@ -172,6 +240,7 @@ describe("UserBar Inbox switching", () => {
expect(renderer.getAllByRole("button", { name: "Inbox item" })).toHaveLength(1)
if (breakpoint === "mobile") {
expect(dialog.closest(".community-user-bar-drawer")).not.toBeNull()
+ expect(dialog.closest(`[data-testid="${tid.userBar}"]`)).not.toBeNull()
expect(dialog.className).not.toContain("fade-in")
} else {
expect(dialog.closest(".community-user-bar-drawer")).toBeNull()
diff --git a/src/web/src/components/community/shell/user-bar.tsx b/src/web/src/components/community/shell/user-bar.tsx
index 55c8d48c6..162db6c52 100644
--- a/src/web/src/components/community/shell/user-bar.tsx
+++ b/src/web/src/components/community/shell/user-bar.tsx
@@ -8,6 +8,7 @@ import {
type ReactNode,
} from "react"
import { CircleAlert, Download, LoaderCircle, Settings } from "lucide-react"
+import { isMobile } from "@alook/shared"
import { InboxUnreadIndicator } from "./inbox-unread-indicator"
import { Avatar } from "../avatar"
import { Skeleton } from "@/components/ui/skeleton"
@@ -20,6 +21,7 @@ import { cn } from "@/lib/utils"
import { UserBarExtensionDrawer } from "./user-bar-extension-drawer"
import { UserBarExtensionSlot } from "./user-bar-extension-slot"
import { UserBarPopover } from "./user-bar-popover"
+import { useHydratedClient } from "./use-hydrated-client"
import type {
UserBarExtensionKind,
UserBarUpdatePhase,
@@ -53,6 +55,7 @@ export function UserBar({ breakpoint, user, onOpenProfile, onEditProfile, inbox,
onInboxOpenChange?: (open: boolean) => void
extension?: UserBarExtension
}) {
+ const nativeMobile = useHydratedClient() && isMobile()
const profileTriggerRef = useRef<HTMLButtonElement>(null)
const profileNameTriggerRef = useRef<HTMLButtonElement>(null)
const lastProfileTriggerRef = useRef<HTMLButtonElement | null>(null)
@@ -108,10 +111,11 @@ export function UserBar({ breakpoint, user, onOpenProfile, onEditProfile, inbox,
return (
<div
data-testid={tid.userBar}
+ style={nativeMobile ? { paddingBottom: "0.25rem" } : undefined}
className="@container/user-bar w-full min-w-0 max-w-full shrink-0 overflow-hidden pl-[max(0.75rem,var(--app-safe-area-left))] pr-[max(0.75rem,var(--app-safe-area-right))] pb-[calc(0.75rem+var(--app-safe-area-bottom))] pt-0 sm:px-2 sm:pb-3"
>
{mobile
- ? <UserBarExtensionDrawer>{extensionContent}</UserBarExtensionDrawer>
+ ? <UserBarExtensionDrawer onDismiss={dismissExtensionWithFocus}>{extensionContent}</UserBarExtensionDrawer>
: extensionContent && extension && (
<UserBarPopover
anchor={baseRef}
@@ -159,9 +163,11 @@ export function UserBar({ breakpoint, user, onOpenProfile, onEditProfile, inbox,
}
export function UserBarSkeleton() {
+ const nativeMobile = useHydratedClient() && isMobile()
return (
<div
data-testid={tid.initialUserBarPending}
+ style={nativeMobile ? { paddingBottom: "0.25rem" } : undefined}
aria-hidden
className="@container/user-bar w-full min-w-0 max-w-full shrink-0 overflow-hidden pl-[max(0.75rem,var(--app-safe-area-left))] pr-[max(0.75rem,var(--app-safe-area-right))] pb-[calc(0.75rem+var(--app-safe-area-bottom))] pt-0 sm:px-2 sm:pb-3"
>
diff --git a/src/web/src/components/community/social/profile-card-surface.dom.test.ts b/src/web/src/components/community/social/profile-card-surface.dom.test.ts
index f1e4321c2..985227d8b 100644
--- a/src/web/src/components/community/social/profile-card-surface.dom.test.ts
+++ b/src/web/src/components/community/social/profile-card-surface.dom.test.ts
@@ -226,8 +226,10 @@ describe("ProfileCard surface contracts", () => {
act(() => (root.onOpenChange as (open: boolean, details: unknown) => void)(false, details))
- expect(onClose).toHaveBeenCalledOnce()
+ expect(onClose).not.toHaveBeenCalled()
expect(mockProps.get("sheet-root")?.open).toBe(false)
+ act(() => (mockProps.get("sheet-root")!.onOpenChangeComplete as (open: boolean) => void)(false))
+ expect(onClose).toHaveBeenCalledOnce()
})
it("keeps the desktop profile on the anchored Popover path", () => {
diff --git a/src/web/src/components/community/social/profile-card.tsx b/src/web/src/components/community/social/profile-card.tsx
index 18810405b..890a390f5 100644
--- a/src/web/src/components/community/social/profile-card.tsx
+++ b/src/web/src/components/community/social/profile-card.tsx
@@ -176,7 +176,7 @@ function ProfileCardContent({ data, x, y, bp, onClose, onMessage, canMessage = f
if (!canSendMessage || !text || !data.userId) return
onMessage?.(data.userId, text)
setMsg("")
- if (mobile) onClose()
+ if (mobile && (embedded || extension)) onClose()
else close()
}
const interruptAgent = () => {
@@ -377,10 +377,8 @@ function ProfileCardContent({ data, x, y, bp, onClose, onMessage, canMessage = f
return (
<Sheet
open={open}
- onOpenChange={(nowOpen) => {
- setOpen(nowOpen)
- if (!nowOpen) onClose()
- }}
+ onOpenChange={setOpen}
+ onOpenChangeComplete={(nowOpen) => { if (!nowOpen) onClose() }}
modal
>
<SheetContent
diff --git a/src/web/src/components/ui/alert-dialog.tsx b/src/web/src/components/ui/alert-dialog.tsx
index 0bad2b100..abf167026 100644
--- a/src/web/src/components/ui/alert-dialog.tsx
+++ b/src/web/src/components/ui/alert-dialog.tsx
@@ -1,15 +1,14 @@
"use client"
import * as React from "react"
-import { AlertDialog as AlertDialogPrimitive } from "@base-ui/react/alert-dialog"
+import { Drawer as AlertDialogPrimitive } from "@base-ui/react/drawer"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
-import { NativeBackRoot, useNativeBackPopupRender, useNativeBackRoot } from "./native-back-layer"
+import { SwipeRoot, SwipeViewport, SwipePopup, SwipeBackdrop, type SwipeRootProps } from "./swipe-container"
-function AlertDialog({ ...props }: AlertDialogPrimitive.Root.Props) {
- const back = useNativeBackRoot(props.onOpenChangeComplete)
- return <NativeBackRoot value={back.owner}><AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} onOpenChangeComplete={back.complete} /></NativeBackRoot>
+function AlertDialog({ ...props }: SwipeRootProps) {
+ return <SwipeRoot data-slot="alert-dialog" {...props} modal disablePointerDismissal />
}
function AlertDialogTrigger({ ...props }: AlertDialogPrimitive.Trigger.Props) {
@@ -29,7 +28,7 @@ function AlertDialogOverlay({
...props
}: AlertDialogPrimitive.Backdrop.Props) {
return (
- <AlertDialogPrimitive.Backdrop
+ <SwipeBackdrop
data-slot="alert-dialog-overlay"
className={cn(
"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
@@ -48,11 +47,15 @@ function AlertDialogContent({
}: AlertDialogPrimitive.Popup.Props & {
size?: "default" | "sm"
}) {
- const renderPopup = useNativeBackPopupRender<AlertDialogPrimitive.Popup.State>(render)
+ const popup = React.useRef<HTMLDivElement>(null)
return (
<AlertDialogPortal>
- <AlertDialogOverlay />
- <AlertDialogPrimitive.Popup
+ <AlertDialogOverlay forceRender />
+ <SwipeViewport className="fixed inset-0 z-50">
+ <SwipePopup
+ ref={popup}
+ role="alertdialog"
+ initialFocus={() => popup.current?.querySelector<HTMLElement>('[data-slot="alert-dialog-cancel"]') ?? popup.current ?? false}
data-slot="alert-dialog-content"
data-size={size}
className={cn(
@@ -60,8 +63,9 @@ function AlertDialogContent({
className
)}
{...props}
- render={renderPopup}
+ render={render}
/>
+ </SwipeViewport>
</AlertDialogPortal>
)
}
diff --git a/src/web/src/components/ui/dialog.dom.test.ts b/src/web/src/components/ui/dialog.dom.test.ts
index 0c578af31..bdafa178c 100644
--- a/src/web/src/components/ui/dialog.dom.test.ts
+++ b/src/web/src/components/ui/dialog.dom.test.ts
@@ -1,41 +1,12 @@
import {
- Fragment,
- cloneElement,
createElement,
- type ComponentProps,
- type ReactElement,
- type ReactNode,
} from "react"
import { describe, expect, it, vi } from "vitest"
import { fireEvent, render, screen } from "@/test/react-dom-harness"
-vi.mock("@base-ui/react/dialog", () => ({
- Dialog: {
- Root: ({ children, ...props }: ComponentProps<"div">) =>
- createElement("div", props, children),
- Trigger: ({ children, ...props }: ComponentProps<"button">) =>
- createElement("button", props, children),
- Portal: ({ children }: { children: ReactNode }) =>
- createElement(Fragment, null, children),
- Backdrop: ({ forceRender: _forceRender, ...props }:
- ComponentProps<"div"> & { forceRender?: boolean }) => createElement("div", props),
- Popup: ({ children, ...props }: ComponentProps<"div">) =>
- createElement("div", { ...props, "data-testid": "dialog-popup" }, children),
- Close: ({
- children,
- render: control,
- ...props
- }: ComponentProps<"button"> & { render?: ReactElement }) => control
- ? cloneElement(control, props, children)
- : createElement("button", props, children),
- Title: ({ children, ...props }: ComponentProps<"h2">) =>
- createElement("h2", props, children),
- Description: ({ children, ...props }: ComponentProps<"p">) =>
- createElement("p", props, children),
- },
-}))
+vi.mock("@/hooks/use-mobile", () => ({ useIsMobile: () => false }))
-import { DialogContent } from "./dialog"
+import { Dialog, DialogContent, DialogTitle } from "./dialog"
const handlerNames = [
"onClick",
@@ -71,7 +42,7 @@ describe("DialogContent", () => {
const rendered = render(createElement(
"div",
{ [name]: parentHandler },
- createElement(DialogContent, { [name]: handler }, "Dialog body"),
+ createElement(Dialog, { defaultOpen: true }, createElement(DialogContent, { [name]: handler, "data-testid": "dialog-popup" }, createElement(DialogTitle, null, "Dialog body"))),
))
fire[name](rendered.getByTestId("dialog-popup"))
@@ -82,7 +53,7 @@ describe("DialogContent", () => {
})
it("keeps the close affordance touch-safe on mobile", () => {
- render(createElement(DialogContent, null, "Dialog body"))
+ render(createElement(Dialog, { defaultOpen: true }, createElement(DialogContent, null, createElement(DialogTitle, null, "Dialog body"))))
expect(screen.getByRole("button", { name: "Close" }))
.toHaveClass("size-11", "sm:size-7")
diff --git a/src/web/src/components/ui/dialog.tsx b/src/web/src/components/ui/dialog.tsx
index 1a80e753e..cb709a4b5 100644
--- a/src/web/src/components/ui/dialog.tsx
+++ b/src/web/src/components/ui/dialog.tsx
@@ -1,25 +1,15 @@
"use client"
import * as React from "react"
-import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"
+import { Drawer as DialogPrimitive } from "@base-ui/react/drawer"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { XIcon } from "lucide-react"
-import { NativeBackRoot, useNativeBackPopupRender, useNativeBackRoot } from "./native-back-layer"
+import { SwipeRoot, SwipeViewport, SwipePopup, SwipeBackdrop, type SwipeRootProps } from "./swipe-container"
-function stopPropagationAfter<Event extends React.SyntheticEvent>(
- handler: ((event: Event) => void) | undefined,
-) {
- return (event: Event) => {
- handler?.(event)
- event.stopPropagation()
- }
-}
-
-function Dialog({ ...props }: DialogPrimitive.Root.Props) {
- const back = useNativeBackRoot(props.onOpenChangeComplete)
- return <NativeBackRoot value={back.owner}><DialogPrimitive.Root data-slot="dialog" {...props} onOpenChangeComplete={back.complete} /></NativeBackRoot>
+function Dialog({ ...props }: SwipeRootProps) {
+ return <SwipeRoot data-slot="dialog" {...props} />
}
function DialogTrigger({ ...props }: DialogPrimitive.Trigger.Props) {
@@ -39,7 +29,7 @@ function DialogOverlay({
...props
}: DialogPrimitive.Backdrop.Props) {
return (
- <DialogPrimitive.Backdrop
+ <SwipeBackdrop
data-slot="dialog-overlay"
className={cn(
"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
@@ -71,28 +61,28 @@ function DialogContent({
showCloseButton?: boolean
overlayClassName?: string
}) {
- const renderPopup = useNativeBackPopupRender<DialogPrimitive.Popup.State>(render)
return (
<DialogPortal>
<DialogOverlay className={overlayClassName} forceRender />
- <DialogPrimitive.Popup
+ <SwipeViewport className="fixed inset-0 z-50">
+ <SwipePopup
data-slot="dialog-content"
className={cn(
"fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className
)}
{...props}
- render={renderPopup}
- onClick={stopPropagationAfter(onClick)}
- onContextMenu={stopPropagationAfter(onContextMenu)}
- onPointerCancel={stopPropagationAfter(onPointerCancel)}
- onPointerDown={stopPropagationAfter(onPointerDown)}
- onPointerMove={stopPropagationAfter(onPointerMove)}
- onPointerUp={stopPropagationAfter(onPointerUp)}
- onTouchCancel={stopPropagationAfter(onTouchCancel)}
- onTouchEnd={stopPropagationAfter(onTouchEnd)}
- onTouchMove={stopPropagationAfter(onTouchMove)}
- onTouchStart={stopPropagationAfter(onTouchStart)}
+ render={render}
+ onClick={onClick}
+ onContextMenu={onContextMenu}
+ onPointerCancel={onPointerCancel}
+ onPointerDown={onPointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={onPointerUp}
+ onTouchCancel={onTouchCancel}
+ onTouchEnd={onTouchEnd}
+ onTouchMove={onTouchMove}
+ onTouchStart={onTouchStart}
>
{children}
{showCloseButton && (
@@ -111,7 +101,8 @@ function DialogContent({
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
- </DialogPrimitive.Popup>
+ </SwipePopup>
+ </SwipeViewport>
</DialogPortal>
)
}
diff --git a/src/web/src/components/ui/native-back-layer.tsx b/src/web/src/components/ui/native-back-layer.tsx
index d847be477..cdd6e1753 100644
--- a/src/web/src/components/ui/native-back-layer.tsx
+++ b/src/web/src/components/ui/native-back-layer.tsx
@@ -130,7 +130,9 @@ function NativeBackPopup<State extends { open: boolean }>({ elementProps, state,
React.useLayoutEffect(() => {
const element = ref.current
if (!owner || !element) return
- if (state.open) activate(owner, element, () => requestEscape(element))
+ if (state.open) activate(owner, element, () => requestEscape(element), () => (
+ !element.hidden && !element.parentElement?.closest("[inert], [hidden]")
+ ))
else startClosing(owner, element)
})
React.useLayoutEffect(() => {
diff --git a/src/web/src/components/ui/sheet.tsx b/src/web/src/components/ui/sheet.tsx
index c0388481e..44ec3bfb4 100644
--- a/src/web/src/components/ui/sheet.tsx
+++ b/src/web/src/components/ui/sheet.tsx
@@ -1,16 +1,19 @@
"use client"
import * as React from "react"
-import { Dialog as SheetPrimitive } from "@base-ui/react/dialog"
+import { Drawer as SheetPrimitive } from "@base-ui/react/drawer"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { XIcon } from "lucide-react"
-import { NativeBackRoot, useNativeBackPopupRender, useNativeBackRoot } from "./native-back-layer"
+import { SwipeRoot, SwipeViewport, SwipePopup, SwipeBackdrop, type SwipeRootProps } from "./swipe-container"
+import type { SwipeDirection } from "./swipe-gesture-policy"
-function Sheet({ ...props }: SheetPrimitive.Root.Props) {
- const back = useNativeBackRoot(props.onOpenChangeComplete)
- return <NativeBackRoot value={back.owner}><SheetPrimitive.Root data-slot="sheet" {...props} onOpenChangeComplete={back.complete} /></NativeBackRoot>
+const SheetDirectionContext = React.createContext<React.Dispatch<React.SetStateAction<SwipeDirection>> | null>(null)
+
+function Sheet({ ...props }: SwipeRootProps) {
+ const [direction, setDirection] = React.useState<SwipeDirection>(props.swipeDirection ?? "right")
+ return <SheetDirectionContext value={setDirection}><SwipeRoot data-slot="sheet" {...props} swipeDirection={direction} /></SheetDirectionContext>
}
function SheetTrigger({ ...props }: SheetPrimitive.Trigger.Props) {
@@ -27,7 +30,7 @@ function SheetPortal({ ...props }: SheetPrimitive.Portal.Props) {
function SheetOverlay({ className, ...props }: SheetPrimitive.Backdrop.Props) {
return (
- <SheetPrimitive.Backdrop
+ <SwipeBackdrop
data-slot="sheet-overlay"
className={cn(
"fixed inset-0 z-50 bg-black/20 backdrop-blur-[2px] transition-[opacity,backdrop-filter] duration-200 ease-out data-ending-style:opacity-0 data-ending-style:backdrop-blur-none data-starting-style:opacity-0 data-starting-style:backdrop-blur-none",
@@ -51,11 +54,15 @@ function SheetContent({
showCloseButton?: boolean
showOverlay?: boolean
}) {
- const renderPopup = useNativeBackPopupRender<SheetPrimitive.Popup.State>(render)
+ const setDirection = React.useContext(SheetDirectionContext)
+ React.useLayoutEffect(() => {
+ setDirection?.(side === "bottom" ? "down" : side === "top" ? "up" : side)
+ }, [setDirection, side])
return (
<SheetPortal>
{showOverlay && <SheetOverlay forceRender />}
- <SheetPrimitive.Popup
+ <SwipeViewport className="fixed inset-0 z-50">
+ <SwipePopup
data-slot="sheet-content"
data-side={side}
className={cn(
@@ -67,7 +74,7 @@ function SheetContent({
className
)}
{...props}
- render={renderPopup}
+ render={render}
>
{children}
{showCloseButton && (
@@ -85,7 +92,8 @@ function SheetContent({
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
)}
- </SheetPrimitive.Popup>
+ </SwipePopup>
+ </SwipeViewport>
</SheetPortal>
)
}
diff --git a/src/web/src/components/ui/swipe-container.dom.test.tsx b/src/web/src/components/ui/swipe-container.dom.test.tsx
new file mode 100644
index 000000000..878fd1c2b
--- /dev/null
+++ b/src/web/src/components/ui/swipe-container.dom.test.tsx
@@ -0,0 +1,265 @@
+import { useState } from "react"
+import { afterEach, describe, expect, it, vi } from "vitest"
+import { fireEvent, mockElementGeometry, render, screen, waitFor } from "@/test/react-dom-harness"
+import { SwipeRoot, SwipePortal, SwipeViewport, SwipePopup, SwipeTitle } from "./swipe-container"
+import { canStartSwipe, isSystemSwipeStart } from "./swipe-gesture-policy"
+import { Dialog, DialogContent, DialogTitle } from "./dialog"
+import { ConversationActivityContext } from "@/contexts/community/conversation-activity"
+import { requestNativeBack } from "./native-back-layer"
+
+vi.mock("@/hooks/use-mobile", () => ({ useIsMobile: () => true }))
+
+const hitTest = Object.getOwnPropertyDescriptor(document, "elementFromPoint")
+const nativeBridge = Object.getOwnPropertyDescriptor(window, "AlookNative")
+const tauriBridge = Object.getOwnPropertyDescriptor(window, "__TAURI__")
+afterEach(() => {
+ vi.restoreAllMocks()
+ for (const [key, descriptor] of [["AlookNative", nativeBridge], ["__TAURI__", tauriBridge]] as const) {
+ if (descriptor) Object.defineProperty(window, key, descriptor)
+ else Reflect.deleteProperty(window, key)
+ }
+ if (hitTest) Object.defineProperty(document, "elementFromPoint", hitTest)
+ else Reflect.deleteProperty(document, "elementFromPoint")
+})
+
+function Fixture({ changed, accept = true, direction = "right" }: { changed: (open: boolean) => void; accept?: boolean; direction?: "right" | "down" }) {
+ const [open, setOpen] = useState(true)
+ return <SwipeRoot kind="page" open={open} swipeDirection={direction} onOpenChange={(next) => { changed(next); if (accept) setOpen(next) }}>
+ <SwipePortal><SwipeViewport><SwipePopup data-testid="swipe-popup">
+ <SwipeTitle>Detail</SwipeTitle>
+ <div data-testid="swipe-start">Drag here</div>
+ <button>Keep button</button><input aria-label="Draft" />
+ <div data-base-ui-swipe-ignore="" data-testid="reply-row">Reply gesture</div>
+ </SwipePopup></SwipeViewport></SwipePortal>
+ </SwipeRoot>
+}
+
+function touch(target: Element, type: "touchStart" | "touchMove" | "touchEnd" | "touchCancel", x: number, y = 100, timeStamp?: number) {
+ const point = { clientX: x, clientY: y, identifier: 0, target }
+ const event = new Event(type.toLowerCase(), { bubbles: true, cancelable: true })
+ Object.defineProperties(event, {
+ touches: { value: type === "touchEnd" || type === "touchCancel" ? [] : [point] },
+ changedTouches: { value: [point] },
+ ...(timeStamp === undefined ? {} : { timeStamp: { value: timeStamp } }),
+ })
+ fireEvent(target, event)
+}
+
+describe("shared Drawer interaction", () => {
+ it("preserves click and context-menu propagation to their existing owners", () => {
+ const click = vi.fn(), context = vi.fn()
+ document.addEventListener("click", click)
+ document.addEventListener("contextmenu", context)
+ try {
+ render(<Fixture changed={vi.fn()} />)
+ const button = screen.getByRole("button", { name: "Keep button" })
+ fireEvent.click(button)
+ fireEvent.contextMenu(button)
+ expect(click).toHaveBeenCalledOnce()
+ expect(context).toHaveBeenCalledOnce()
+ } finally {
+ document.removeEventListener("click", click)
+ document.removeEventListener("contextmenu", context)
+ }
+ })
+ it("retires background modal visibility and Back ownership while retaining its owner state", async () => {
+ const changed = vi.fn()
+ const node = (active: boolean) => <ConversationActivityContext value={active}>
+ <Dialog open onOpenChange={changed}><DialogContent data-testid="retained-dialog"><DialogTitle>Parent panel</DialogTitle></DialogContent></Dialog>
+ </ConversationActivityContext>
+ const view = render(node(true))
+ const popup = screen.getByTestId("retained-dialog")
+ expect(popup).toHaveAttribute("data-open")
+ view.rerender(node(false))
+ expect(popup).toHaveAttribute("hidden")
+ expect(popup).toHaveAttribute("data-closed")
+ expect(requestNativeBack(document)).toBe("none")
+ expect(changed).not.toHaveBeenCalled()
+ view.rerender(node(true))
+ await waitFor(() => expect(screen.getByTestId("retained-dialog")).toHaveAttribute("data-open"))
+ })
+ it("restores a slow below-threshold release without changing controlled state", async () => {
+ const changed = vi.fn()
+ render(<Fixture changed={changed} />)
+ const popup = screen.getByTestId("swipe-popup"), area = screen.getByTestId("swipe-start")
+ const restore = mockElementGeometry(popup, { width: 390, height: 600, offsetWidth: 390, offsetHeight: 600, clientWidth: 390, clientHeight: 600 })
+ Object.defineProperty(document, "elementFromPoint", { configurable: true, value: () => area })
+ touch(area, "touchStart", 80, 100, 100)
+ touch(area, "touchMove", 170, 100, 300)
+ touch(area, "touchMove", 190, 100, 1000)
+ touch(area, "touchEnd", 190, 100, 1400)
+ await waitFor(() => expect(popup).not.toHaveAttribute("data-swiping"))
+ expect(popup).toHaveAttribute("data-open")
+ expect(changed).not.toHaveBeenCalled()
+ restore()
+ })
+
+ it.each([true, false])("accepts one release or restores a rejected controlled close (accept=%s)", async (accept) => {
+ const changed = vi.fn()
+ render(<Fixture changed={changed} accept={accept} />)
+ const popup = screen.getByTestId("swipe-popup"), area = screen.getByTestId("swipe-start")
+ const restore = mockElementGeometry(popup, { width: 390, height: 600, offsetWidth: 390, offsetHeight: 600, clientWidth: 390, clientHeight: 600 })
+ Object.defineProperty(document, "elementFromPoint", { configurable: true, value: () => area })
+ touch(area, "touchStart", 80)
+ touch(area, "touchMove", 170)
+ touch(area, "touchMove", 360)
+ touch(area, "touchEnd", 360)
+ expect(changed).toHaveBeenCalledExactlyOnceWith(false)
+ await waitFor(() => expect(popup).toHaveAttribute(accept ? "data-closed" : "data-open"))
+ if (!accept) await waitFor(() => expect(popup).not.toHaveAttribute("data-ending-style"))
+ restore()
+ })
+
+ it("follows its vertical placement and cancels when a second touch takes ownership", async () => {
+ const changed = vi.fn()
+ render(<Fixture changed={changed} direction="down" />)
+ const popup = screen.getByTestId("swipe-popup"), area = screen.getByTestId("swipe-start")
+ const restore = mockElementGeometry(popup, { width: 390, height: 600, offsetWidth: 390, offsetHeight: 600, clientWidth: 390, clientHeight: 600 })
+ Object.defineProperty(document, "elementFromPoint", { configurable: true, value: () => area })
+ touch(area, "touchStart", 80, 120)
+ touch(area, "touchMove", 80, 170)
+ touch(area, "touchMove", 80, 220)
+ expect(popup.style.transform).toContain("50px")
+ fireEvent.touchMove(area, { touches: [
+ { clientX: 80, clientY: 260, identifier: 0, target: area },
+ { clientX: 170, clientY: 260, identifier: 1, target: area },
+ ] })
+ await waitFor(() => expect(popup).not.toHaveAttribute("data-swiping"))
+ expect(changed).not.toHaveBeenCalled()
+ expect(popup).toHaveAttribute("data-open")
+ restore()
+ })
+ it("follows a permitted touch and cancels without requesting close", async () => {
+ const changed = vi.fn()
+ render(<Fixture changed={changed} />)
+ const popup = await screen.findByTestId("swipe-popup")
+ const restore = mockElementGeometry(popup, { width: 390, height: 600, offsetWidth: 390, offsetHeight: 600, clientWidth: 390, clientHeight: 600 })
+ const area = screen.getByTestId("swipe-start")
+ Object.defineProperty(document, "elementFromPoint", { configurable: true, value: () => area })
+ touch(area, "touchStart", 80)
+ touch(area, "touchMove", 170)
+ await waitFor(() => { expect(popup).toHaveAttribute("data-swiping") })
+ touch(area, "touchMove", 220)
+ expect(popup.style.transform).toContain("50px")
+ touch(area, "touchCancel", 220)
+ await waitFor(() => { expect(popup).not.toHaveAttribute("data-swiping") })
+ expect(changed).not.toHaveBeenCalled()
+ expect(screen.getByTestId("swipe-popup")).toHaveAttribute("data-open")
+ restore()
+ })
+
+ it("leaves touch buttons, inputs, reply rows and reserved edges outside drawer admission", async () => {
+ const changed = vi.fn()
+ render(<Fixture changed={changed} />)
+ const popup = await screen.findByTestId("swipe-popup")
+ const restore = mockElementGeometry(popup, { width: 390, height: 600, offsetWidth: 390, offsetHeight: 600, clientWidth: 390, clientHeight: 600 })
+ for (const target of [screen.getByRole("button"), screen.getByRole("textbox"), screen.getByTestId("reply-row")]) {
+ touch(target, "touchStart", 120)
+ touch(target, "touchMove", 290)
+ touch(target, "touchEnd", 290)
+ expect(popup).not.toHaveAttribute("data-swiping")
+ }
+ const area = screen.getByTestId("swipe-start")
+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue("Android WebView")
+ Object.defineProperty(window, "AlookNative", { configurable: true, value: { getSystemGestureRegion: () => JSON.stringify({ left: 24, right: 24, width: 390 }) } })
+ touch(area, "touchStart", 8)
+ touch(area, "touchMove", 290)
+ touch(area, "touchEnd", 290)
+ expect(changed).not.toHaveBeenCalled()
+ fireEvent.change(screen.getByRole("textbox"), { target: { value: "retained draft" } })
+ expect(screen.getByRole("textbox")).toHaveValue("retained draft")
+ restore()
+ })
+
+ it("uses current native system edges in CSS pixels, with a separate application start strip", () => {
+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue("Android WebView")
+ let region = { left: 48, right: 72, width: 780 }
+ Object.defineProperty(window, "AlookNative", { configurable: true, value: { getSystemGestureRegion: () => JSON.stringify(region) } })
+ const root = document.createElement("div"), target = document.createElement("span")
+ root.appendChild(target); document.body.appendChild(root)
+ const restore = mockElementGeometry(document.documentElement, { clientWidth: 390, clientHeight: 844 })
+ const start = { target, root, enabled: true, kind: "page" as const, pointerType: "touch", y: 100 }
+ try {
+ expect(canStartSwipe({ ...start, x: 23 })).toBe(false)
+ expect(canStartSwipe({ ...start, x: 24 })).toBe(true)
+ expect(canStartSwipe({ ...start, x: 120 })).toBe(true)
+ expect(canStartSwipe({ ...start, x: 121 })).toBe(false)
+ region = { left: 96, right: 0, width: 780 }
+ expect(canStartSwipe({ ...start, x: 24 })).toBe(false)
+ expect(canStartSwipe({ ...start, x: 48 })).toBe(true)
+ region = { left: 0, right: 0, width: 780 }
+ expect(canStartSwipe({ ...start, x: 0 })).toBe(true)
+ expect(canStartSwipe({ ...start, x: 97 })).toBe(false)
+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue("iPhone")
+ region = { left: 96, right: 96, width: 780 }
+ expect(canStartSwipe({ ...start, x: 0 })).toBe(true)
+ expect(canStartSwipe({ ...start, x: 96 })).toBe(true)
+ expect(canStartSwipe({ ...start, x: 97 })).toBe(false)
+ } finally { restore(); root.remove() }
+ })
+
+ it("does not fabricate native measurements when the Android bridge is unavailable or invalid", () => {
+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue("Android WebView")
+ const root = document.createElement("div"), target = document.createElement("span")
+ root.appendChild(target); document.body.appendChild(root)
+ const start = { target, root, enabled: true, kind: "page" as const, pointerType: "touch", x: 80, y: 100 }
+ try {
+ expect(canStartSwipe(start)).toBe(true)
+ Object.defineProperty(window, "__TAURI__", { configurable: true, value: {} })
+ expect(canStartSwipe(start)).toBe(false)
+ for (const value of ["null", "bad json", '{"left":-1,"right":0,"width":390}', '{"left":200,"right":200,"width":390}']) {
+ Object.defineProperty(window, "AlookNative", { configurable: true, value: { getSystemGestureRegion: () => value } })
+ expect(canStartSwipe(start)).toBe(false)
+ }
+ Object.defineProperty(window, "AlookNative", { configurable: true, value: { getSystemGestureRegion: () => { throw new Error("bridge retired") } } })
+ expect(canStartSwipe(start)).toBe(false)
+ } finally { root.remove() }
+ })
+
+ it("yields zoomed content and top/bottom gesture space without borrowing an unhosted document", () => {
+ const root = document.createElement("div"), target = document.createElement("span")
+ root.appendChild(target); document.body.appendChild(root)
+ const restore = mockElementGeometry(document.documentElement, { clientHeight: 844 })
+ const viewport = Object.getOwnPropertyDescriptor(window, "visualViewport")
+ const scale = { scale: 1 }
+ Object.defineProperty(window, "visualViewport", { configurable: true, value: scale })
+ const start = { target, root, enabled: true, pointerType: "touch", x: 120 }
+ try {
+ expect(canStartSwipe({ ...start, y: 24 })).toBe(true)
+ expect(canStartSwipe({ ...start, y: 23 })).toBe(false)
+ expect(canStartSwipe({ ...start, y: 812 })).toBe(true)
+ expect(canStartSwipe({ ...start, y: 813 })).toBe(false)
+ scale.scale = 2
+ expect(canStartSwipe({ ...start, y: 100 })).toBe(false)
+ expect(isSystemSwipeStart(root, 120)).toBe(false)
+ expect(isSystemSwipeStart(document.implementation.createHTMLDocument().body, 120)).toBe(false)
+ } finally {
+ restore(); root.remove()
+ if (viewport) Object.defineProperty(window, "visualViewport", viewport)
+ else Reflect.deleteProperty(window, "visualViewport")
+ }
+ })
+
+ it("yields overflow scrollers, multi-touch, selection, and disabled surfaces", () => {
+ const root = document.createElement("div"), scroller = document.createElement("div"), target = document.createElement("span")
+ root.appendChild(scroller)
+ scroller.appendChild(target)
+ document.body.appendChild(root)
+ scroller.style.overflowX = "auto"
+ const restore = mockElementGeometry(scroller, { clientWidth: 100, scrollWidth: 300 })
+ const start = { target, root, x: 120, enabled: true, pointerType: "touch" }
+ expect(canStartSwipe(start)).toBe(false)
+ scroller.style.overflowX = "visible"
+ expect(canStartSwipe(start)).toBe(true)
+ expect(canStartSwipe({ ...start, touches: 2 })).toBe(false)
+ expect(canStartSwipe({ ...start, pointerType: "mouse" })).toBe(false)
+ expect(canStartSwipe({ ...start, enabled: false })).toBe(false)
+ const selection = document.getSelection()!
+ target.textContent = "selected content"
+ selection.removeAllRanges()
+ const range = document.createRange(); range.selectNodeContents(target); selection.addRange(range)
+ expect(selection.toString()).toBe("selected content")
+ expect(canStartSwipe(start)).toBe(false)
+ selection.removeAllRanges(); restore(); root.remove()
+ })
+})
diff --git a/src/web/src/components/ui/swipe-container.module.css b/src/web/src/components/ui/swipe-container.module.css
new file mode 100644
index 000000000..0d72696e2
--- /dev/null
+++ b/src/web/src/components/ui/swipe-container.module.css
@@ -0,0 +1,87 @@
+.viewport {
+ pointer-events: none;
+}
+
+.popup {
+ pointer-events: auto;
+}
+
+@layer components {
+ @media (max-width: 639px) {
+ .popup {
+ transition-property: transform, opacity;
+ }
+ }
+}
+
+@media (max-width: 639px) {
+ .popup {
+ animation: none !important;
+ transition-duration: 220ms;
+ transition-timing-function: cubic-bezier(0.2, 0.8, 0.2, 1);
+ transform: translate3d(var(--drawer-swipe-movement-x, 0px), var(--drawer-swipe-movement-y, 0px), 0);
+ }
+
+ .popup[data-background] {
+ transform: none !important;
+ transition: none;
+ pointer-events: none;
+ }
+
+ .popup[data-swiping] {
+ transition-duration: 0ms;
+ user-select: none;
+ }
+
+ .popup[data-ending-style] {
+ transition-duration: calc(var(--drawer-swipe-strength, 1) * 220ms);
+ }
+
+ .popup[data-starting-style][data-swipe-direction="right"],
+ .popup[data-ending-style][data-swipe-direction="right"] {
+ transform: translate3d(100vw, 0, 0);
+ }
+
+ .popup[data-starting-style][data-swipe-direction="left"],
+ .popup[data-ending-style][data-swipe-direction="left"] {
+ transform: translate3d(-100vw, 0, 0);
+ }
+
+ .popup[data-starting-style][data-swipe-direction="down"],
+ .popup[data-ending-style][data-swipe-direction="down"] {
+ transform: translate3d(0, 100%, 0);
+ }
+
+ .popup[data-starting-style][data-swipe-direction="up"],
+ .popup[data-ending-style][data-swipe-direction="up"] {
+ transform: translate3d(0, -100%, 0);
+ }
+
+ .popup[data-slot="user-bar-swipe"][data-starting-style],
+ .popup[data-slot="user-bar-swipe"][data-ending-style] {
+ transform: translate3d(0, 100%, 0);
+ }
+
+ .backdrop {
+ opacity: calc(1 - var(--drawer-swipe-progress, 0));
+ transition: opacity 220ms cubic-bezier(0.2, 0.8, 0.2, 1);
+ }
+
+ .backdrop[data-starting-style],
+ .backdrop[data-ending-style] {
+ opacity: 0;
+ }
+
+ .backdrop[data-swiping] {
+ transition-duration: 0ms;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .popup,
+ .backdrop {
+ transition-property: none !important;
+ transition-duration: 0ms !important;
+ animation: none !important;
+ }
+}
diff --git a/src/web/src/components/ui/swipe-container.tsx b/src/web/src/components/ui/swipe-container.tsx
new file mode 100644
index 000000000..bffa84ef6
--- /dev/null
+++ b/src/web/src/components/ui/swipe-container.tsx
@@ -0,0 +1,131 @@
+"use client"
+
+import * as React from "react"
+import { Drawer } from "@base-ui/react/drawer"
+import { useRender } from "@base-ui/react/use-render"
+import { useIsMobile } from "@/hooks/use-mobile"
+import { useConversationActivity } from "@/contexts/community/conversation-activity"
+import { cn } from "@/lib/utils"
+import { NativeBackRoot, useNativeBackPopupRender, useNativeBackRoot } from "./native-back-layer"
+import { canStartSwipe, isSystemSwipeStart } from "./swipe-gesture-policy"
+import styles from "./swipe-container.module.css"
+
+type SwipeKind = "page" | "overlay"
+const SwipeContext = React.createContext({ enabled: false, active: true, kind: "overlay" as SwipeKind, cancelledRef: { current: false } })
+
+export type SwipeRootProps = Drawer.Root.Props & {
+ kind?: SwipeKind
+ swipeEnabled?: boolean
+}
+
+export function SwipeRoot({
+ kind = "overlay", swipeEnabled = true, swipeDirection = "right",
+ onOpenChange, onOpenChangeComplete, ...props
+}: SwipeRootProps) {
+ const mobile = useIsMobile()
+ const conversationActive = useConversationActivity()
+ const active = kind === "page" || conversationActive
+ const [uncontrolledOpen, setUncontrolledOpen] = React.useState(props.defaultOpen ?? false)
+ const cancelledRef = React.useRef(false)
+ const back = useNativeBackRoot(onOpenChangeComplete)
+ const root = <SwipeContext value={{ enabled: mobile && swipeEnabled && active, active, kind, cancelledRef }}>
+ <Drawer.Root {...props} swipeDirection={swipeDirection}
+ open={active && (props.open ?? uncontrolledOpen)}
+ onOpenChange={(next, details) => {
+ if (!next && details.reason === "swipe" && (cancelledRef.current || details.event.type.endsWith("cancel"))) {
+ details.cancel()
+ return
+ }
+ onOpenChange?.(next, details)
+ if (!details.isCanceled && props.open === undefined) setUncontrolledOpen(next)
+ }}
+ {...(kind === "page" ? { modal: false, disablePointerDismissal: true } : {})}
+ onOpenChangeComplete={kind === "page" ? onOpenChangeComplete : back.complete} />
+ </SwipeContext>
+ return kind === "overlay" ? <NativeBackRoot value={back.owner}>{root}</NativeBackRoot> : root
+}
+
+const SwipeViewportElement = React.forwardRef<HTMLDivElement, React.ComponentProps<"div">>(function SwipeViewportElement({
+ onPointerDown, onPointerMove, onPointerUp, onPointerCancel,
+ onTouchStart, onTouchMove, onTouchEnd, onTouchCancel, onClick, onContextMenu, ...props
+}, ref) {
+ const { enabled, kind, cancelledRef } = React.useContext(SwipeContext)
+ const isolate = kind === "overlay" || enabled
+ return <div {...props} ref={ref} data-swipe-viewport={kind}
+ onPointerDown={(event) => {
+ cancelledRef.current = !canStartSwipe({ target: event.target, x: event.clientX, y: event.clientY, root: event.currentTarget,
+ enabled, kind, pointerType: event.pointerType })
+ if (!cancelledRef.current) onPointerDown?.(event)
+ if (isolate) event.stopPropagation()
+ }}
+ onTouchStart={(event) => {
+ const touch = event.touches[0]
+ cancelledRef.current = !touch || !canStartSwipe({ target: event.target, x: touch.clientX, y: touch.clientY, root: event.currentTarget,
+ enabled, kind, pointerType: "touch", touches: event.touches.length })
+ if (cancelledRef.current) onTouchCancel?.(event)
+ else onTouchStart?.(event)
+ if (isolate) event.stopPropagation()
+ }}
+ onPointerMove={(event) => { onPointerMove?.(event); if (isolate) event.stopPropagation() }}
+ onPointerUp={(event) => { onPointerUp?.(event); if (isolate) event.stopPropagation() }}
+ onPointerCancel={(event) => { onPointerCancel?.(event); if (isolate) event.stopPropagation() }}
+ onTouchMove={(event) => {
+ const selection = event.currentTarget.ownerDocument.getSelection()
+ if ((event.touches.length > 1 || selection && !selection.isCollapsed) && !cancelledRef.current) {
+ cancelledRef.current = true
+ onTouchCancel?.(event)
+ } else if (!cancelledRef.current) onTouchMove?.(event)
+ if (isolate) event.stopPropagation()
+ }}
+ onTouchEnd={(event) => { onTouchEnd?.(event); if (isolate) event.stopPropagation() }}
+ onTouchCancel={(event) => { onTouchCancel?.(event); if (isolate) event.stopPropagation() }}
+ onClick={(event) => { onClick?.(event); if (kind === "overlay") event.stopPropagation() }}
+ onContextMenu={(event) => { onContextMenu?.(event); if (kind === "overlay") event.stopPropagation() }} />
+})
+
+export function usePageSwipeStart() {
+ const { enabled, kind } = React.useContext(SwipeContext)
+ const page = enabled && kind === "page"
+ const reservesReply = React.useCallback((event: React.PointerEvent<HTMLElement>) => {
+ if (!page || !(event.target instanceof Element)) return false
+ const root = event.target.closest<HTMLElement>('[data-swipe-viewport="page"]')
+ return !!root && (isSystemSwipeStart(root, event.clientX) || canStartSwipe({ target: event.target, root, x: event.clientX, y: event.clientY,
+ enabled: true, kind: "page", pointerType: event.pointerType }))
+ }, [page])
+ return { page, reservesReply }
+}
+
+export function SwipeViewport({ className, ...props }: Omit<Drawer.Viewport.Props, "render">) {
+ return <Drawer.Viewport {...props} className={cn(styles.viewport, className)} render={<SwipeViewportElement />} />
+}
+
+function SwipePopupElement({ elementProps, state, render }: {
+ elementProps: React.ComponentPropsWithRef<"div">
+ state: Drawer.Popup.State
+ render: Drawer.Popup.Props["render"]
+}) {
+ return useRender<Drawer.Popup.State & Record<string, unknown>, HTMLDivElement>({ render, state: { ...state }, props: { ...elementProps, inert: !state.open || elementProps.inert }, ref: elementProps.ref })
+}
+
+export function SwipePopup({ className, render, ...props }: Drawer.Popup.Props) {
+ const { kind, active } = React.useContext(SwipeContext)
+ const inertRender = React.useCallback((elementProps: React.ComponentPropsWithRef<"div">, state: Drawer.Popup.State) => (
+ <SwipePopupElement elementProps={elementProps} state={state} render={render} />
+ ), [render])
+ const popupRender = useNativeBackPopupRender<Drawer.Popup.State>(inertRender)
+ return <Drawer.Popup {...props} className={cn(styles.popup, className)}
+ {...(!active ? { hidden: true } : {})}
+ {...(kind === "page" ? { role: "presentation", initialFocus: false, finalFocus: false } : {})}
+ render={kind === "page" ? inertRender : popupRender} />
+}
+
+export function SwipeBackdrop({ className, ...props }: Drawer.Backdrop.Props) {
+ const { active } = React.useContext(SwipeContext)
+ return <Drawer.Backdrop {...props} {...(!active ? { hidden: true } : {})} className={cn(styles.backdrop, className)} />
+}
+
+export const SwipePortal = Drawer.Portal
+export const SwipeTrigger = Drawer.Trigger
+export const SwipeClose = Drawer.Close
+export const SwipeTitle = Drawer.Title
+export const SwipeDescription = Drawer.Description
diff --git a/src/web/src/components/ui/swipe-gesture-policy.ts b/src/web/src/components/ui/swipe-gesture-policy.ts
new file mode 100644
index 000000000..078714408
--- /dev/null
+++ b/src/web/src/components/ui/swipe-gesture-policy.ts
@@ -0,0 +1,72 @@
+export type SwipeDirection = "left" | "right" | "up" | "down"
+
+const INTERACTIVE_START = [
+ "button", "a", "input", "textarea", "select", "label", "summary", "audio", "video", "canvas", "iframe",
+ "[contenteditable]:not([contenteditable='false'])",
+ "[role='button']", "[role='link']", "[role='slider']", "[role='textbox']",
+ "[role='spinbutton']", "[role='combobox']", "[role='tab']", "[role='option']", "[role='menuitem']",
+ "[draggable='true']", "[data-swipe-ignore]",
+ "[data-slot='resizable-handle']", "[data-dnd-handle]",
+].join(",")
+
+export function canStartSwipe({
+ target, x, y, root, enabled, pointerType, touches = 1, kind = "overlay",
+}: {
+ target: EventTarget | null
+ x: number
+ y?: number
+ root: HTMLElement
+ enabled: boolean
+ pointerType: string
+ touches?: number
+ kind?: "page" | "overlay"
+}) {
+ if (!enabled || pointerType !== "touch" || touches !== 1 || !(target instanceof Element)) return false
+ if (target.closest(INTERACTIVE_START)) return false
+ const document = root.ownerDocument
+ const view = document.defaultView
+ const selection = document.getSelection()
+ if (!view || selection && !selection.isCollapsed && selection.rangeCount > 0) return false
+ if (view.visualViewport && view.visualViewport.scale !== 1) return false
+ const width = document.documentElement.clientWidth || view.innerWidth
+ const edges = systemGestureEdges(view, width)
+ if (!edges || x < edges.left || x > width - edges.right) return false
+ if (kind === "page" && x > edges.left + Math.min(96, width / 4)) return false
+ const height = document.documentElement.clientHeight || view.innerHeight
+ if (y !== undefined && (y < 24 || y > height - 32)) return false
+ for (let element: Element | null = target; element && root.contains(element); element = element.parentElement) {
+ const ignore = element.getAttribute("data-base-ui-swipe-ignore")
+ if (ignore !== null && !(kind === "page" && ignore === "y" && element.hasAttribute("data-page-swipe-reply-row"))) return false
+ if (element instanceof HTMLElement && element.scrollWidth > element.clientWidth + 1) {
+ const overflow = view.getComputedStyle(element).overflowX
+ if (overflow === "auto" || overflow === "scroll") return false
+ }
+ if (element === root) break
+ }
+ return true
+}
+
+export function isSystemSwipeStart(root: HTMLElement, x: number) {
+ const view = root.ownerDocument.defaultView
+ if (!view) return false
+ const width = root.ownerDocument.documentElement.clientWidth || view.innerWidth
+ const edges = systemGestureEdges(view, width)
+ return edges !== null && (x < edges.left || x > width - edges.right)
+}
+
+function systemGestureEdges(view: Window, width: number): { left: number; right: number } | null {
+ if (!/android/i.test(view.navigator.userAgent)) return { left: 0, right: 0 }
+ const native = (view as Window & { AlookNative?: { getSystemGestureRegion?: () => string } }).AlookNative
+ if (!native?.getSystemGestureRegion) return "__TAURI__" in view ? null : { left: 0, right: 0 }
+ try {
+ const region: unknown = JSON.parse(native.getSystemGestureRegion())
+ if (!region || typeof region !== "object" || !("left" in region) || !("right" in region) || !("width" in region)) return null
+ const { left, right, width: nativeWidth } = region
+ if (typeof left !== "number" || typeof right !== "number" || typeof nativeWidth !== "number"
+ || !Number.isFinite(left) || !Number.isFinite(right) || !Number.isFinite(nativeWidth)
+ || left < 0 || right < 0 || nativeWidth <= 0 || left + right > nativeWidth) return null
+ return { left: left * width / nativeWidth, right: right * width / nativeWidth }
+ } catch {
+ return null
+ }
+}
diff --git a/src/web/src/contexts/community/conversation-activity.ts b/src/web/src/contexts/community/conversation-activity.ts
new file mode 100644
index 000000000..ede46718b
--- /dev/null
+++ b/src/web/src/contexts/community/conversation-activity.ts
@@ -0,0 +1,9 @@
+"use client"
+
+import { createContext, useContext } from "react"
+
+export const ConversationActivityContext = createContext(true)
+
+export function useConversationActivity() {
+ return useContext(ConversationActivityContext)
+}
diff --git a/src/web/src/contexts/community/mobile-page-back.ts b/src/web/src/contexts/community/mobile-page-back.ts
new file mode 100644
index 000000000..aedae5465
--- /dev/null
+++ b/src/web/src/contexts/community/mobile-page-back.ts
@@ -0,0 +1,8 @@
+"use client"
+
+import { createContext } from "react"
+
+export type MobilePageBack = (target: string) => boolean
+export const MobilePageBackContext = createContext<{
+ register: (request: MobilePageBack) => () => void
+} | null>(null)
diff --git a/src/web/src/contexts/community/route-frame.tsx b/src/web/src/contexts/community/route-frame.tsx
index e51c43aca..2ea25fc01 100644
--- a/src/web/src/contexts/community/route-frame.tsx
+++ b/src/web/src/contexts/community/route-frame.tsx
@@ -8,14 +8,14 @@ import type { CommunityCommittedFrame } from "@/lib/community/community-route"
import type { OwnerServerDeleteRouteToken } from "@/lib/community/eject-server"
export type CommunityNavigationController = {
- entryIntent?: { href: string } | null
+ entryIntent?: { href: string; resume?: boolean } | null
captureIntent: (options?: { nextCommitHref: string } | { pendingCommitHref: string }) => () => boolean
publishedHref: string
navigationPending: boolean
pendingHref: string | null
push: ReturnType<typeof useRouter>["push"]
pushImmediate: (href: string, prepare?: (action?: Action) => void) => void
- replace: (href: string) => void
+ replace: (href: string, options?: { resume?: boolean }) => void
resolveAndPush: (resolve: () => Promise<string>) => Promise<boolean>
cancelPendingNavigation: () => void
}
diff --git a/src/web/src/hooks/community/use-channel-message-feed.dom.test.ts b/src/web/src/hooks/community/use-channel-message-feed.dom.test.ts
index e9ebc2089..0b3afc1ca 100644
--- a/src/web/src/hooks/community/use-channel-message-feed.dom.test.ts
+++ b/src/web/src/hooks/community/use-channel-message-feed.dom.test.ts
@@ -2,6 +2,7 @@ import React from "react"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { renderHook } from "@/test/react-dom-harness"
import { useChannelMessageFeed } from "./use-channel-message-feed"
+import { ConversationActivityContext } from "@/contexts/community/conversation-activity"
const mocks = vi.hoisted(() => ({
messages: { messages: [{ id: "read", authorId: "viewer", seq: 1 }, { id: "peer", authorId: "peer", seq: 2 }],
@@ -23,6 +24,15 @@ beforeEach(() => {
})
describe("message feed consumes the entry snapshot", () => {
+ it("keeps the canonical feed visible while retiring the background watermark scope", () => {
+ function Wrapper({ children }: { children: React.ReactNode }) {
+ return React.createElement(ConversationActivityContext, { value: false }, children)
+ }
+ const hook = renderHook(() => useChannelMessageFeed(target), { wrapper: Wrapper })
+ expect(hook.result.current.messages).toBe(mocks.messages.messages)
+ expect(mocks.useMessages).toHaveBeenLastCalledWith("c1", expect.objectContaining({ serverId: "s1" }))
+ expect(mocks.watermark).toHaveBeenLastCalledWith(expect.objectContaining({ channelId: null }))
+ })
it("projects NEW and unread count independently of secondary pins and threads", () => {
const hook = renderHook(() => useChannelMessageFeed(target))
expect(hook.result.current.newDividerBefore).toBe("peer")
diff --git a/src/web/src/hooks/community/use-channel-message-feed.ts b/src/web/src/hooks/community/use-channel-message-feed.ts
index 9270d8761..8d7d50212 100644
--- a/src/web/src/hooks/community/use-channel-message-feed.ts
+++ b/src/web/src/hooks/community/use-channel-message-feed.ts
@@ -1,5 +1,6 @@
"use client"
+import { useConversationActivity } from "@/contexts/community/conversation-activity"
import { useAtom, useCreateAtom } from "@tanstack/react-store";
import { useMemo } from "react"
import { isConversationAccessError } from "@/lib/community/conversation-read"
@@ -21,6 +22,7 @@ export function useChannelMessageFeed({
isChildChannel: boolean
anchorMessageId: string | null
}) {
+ const active = useConversationActivity()
const messagesQuery = useMessages(channelId, {
serverId,
anchorMessageId,
@@ -39,7 +41,7 @@ export function useChannelMessageFeed({
const [scrollRootEl, setScrollRootEl] = useAtom(useCreateAtom<HTMLDivElement | null>(null))
/* istanbul ignore next -- retained Chromium covers the mounted observer integration */
useChannelWatermark({
- channelId,
+ channelId: active ? channelId : null,
messages: messagesQuery.messages,
scrollRootEl,
snapshotStatus: messagesQuery.entryDenied || isConversationAccessError(messagesQuery.initialLoadError)
diff --git a/src/web/src/hooks/community/use-channel-route-model.subscription.dom.test.ts b/src/web/src/hooks/community/use-channel-route-model.subscription.dom.test.ts
index 12871e6cc..5df8bb199 100644
--- a/src/web/src/hooks/community/use-channel-route-model.subscription.dom.test.ts
+++ b/src/web/src/hooks/community/use-channel-route-model.subscription.dom.test.ts
@@ -63,6 +63,7 @@ vi.mock("@/lib/community-db/sync", async (importOriginal) => ({ ...await importO
}))
import { buildChannelRouteModel, useChannelRouteModel } from "./use-channel-route-model"
+import { ConversationActivityContext } from "@/contexts/community/conversation-activity"
function Harness({ channelId = "post-1" }: { channelId?: string }) {
const result = useChannelRouteModel("server-1", "server-1", channelId, "viewer")
@@ -107,6 +108,25 @@ beforeEach(async () => {
describe("useChannelRouteModel subscription ownership", () => {
+ it("releases primary focus in the background and restores it on foreground return", () => {
+ const node = (active: boolean) => React.createElement(ConversationActivityContext, { value: active }, React.createElement(Harness))
+ const renderer = render(node(true))
+ expect(mocks.subscribe).toHaveBeenCalledOnce()
+ renderer.rerender(node(false))
+ expect(getCommunityRuntime(queryClient).ui.get().currentChannelId).toBeNull()
+ expect(mocks.unsubscribe).toHaveBeenCalledOnce()
+ renderer.rerender(node(true))
+ expect(mocks.subscribe).toHaveBeenCalledTimes(2)
+ expect(getCommunityRuntime(queryClient).ui.get().currentChannelId).toBe("post-1")
+ })
+
+ it("never subscribes or redirects an inactive denied parent", () => {
+ mocks.metaQuery.isArchived = true
+ render(React.createElement(ConversationActivityContext, { value: false }, React.createElement(Harness)))
+ expect(mocks.subscribe).not.toHaveBeenCalled()
+ expect(mocks.replace).not.toHaveBeenCalled()
+ expect(getCommunityRuntime(queryClient).ui.get().currentChannelId).toBeNull()
+ })
it("updates the primary child without clearing a real parent owner, then clears all on host exit", () => {
const runtime = getCommunityRuntime(queryClient)
mocks.subscribe.mockImplementation((owner, target) => owner.ui.actions.subscribe(target))
diff --git a/src/web/src/hooks/community/use-channel-route-model.ts b/src/web/src/hooks/community/use-channel-route-model.ts
index 6a5dd8ac4..b9c2187a7 100644
--- a/src/web/src/hooks/community/use-channel-route-model.ts
+++ b/src/web/src/hooks/community/use-channel-route-model.ts
@@ -1,9 +1,10 @@
"use client"
+import { useConversationActivity } from "@/contexts/community/conversation-activity"
import { useCommunityRuntime } from "@/stores/community/runtime"
-import { useEffect, useMemo, useRef } from "react"
+import { useEffect, useLayoutEffect, useMemo, useRef } from "react"
import { usePathname, useRouter } from "next/navigation"
import { useQueryClient } from "@tanstack/react-query"
import { isForum as isForumType, type CommunityChannelResource } from "@alook/shared"
@@ -63,6 +64,9 @@ export function useChannelRouteModel(
accountId: string,
anchorMessageId?: string | null,
) {
+ const active = useConversationActivity()
+ const ownedChannel = useRef(channelId)
+ useLayoutEffect(() => { ownedChannel.current = channelId }, [channelId])
const router = useRouter()
const pathname = usePathname()
const queryClient = useQueryClient()
@@ -109,16 +113,20 @@ export function useChannelRouteModel(
parentSubtype,
}), [skeletonSubtype, structuralParentId, parentSubtype])
useEffect(() => {
- runtime.ui.actions.setCurrentChannelId(channelId)
- }, [channelId, runtime])
+ if (active) runtime.ui.actions.setCurrentChannelId(channelId)
+ }, [active, channelId, runtime])
useEffect(() => {
- communityWsSubscribe(runtime, { channelId })
- }, [channelId, runtime])
+ if (active) communityWsSubscribe(runtime, { channelId })
+ }, [active, channelId, runtime])
useEffect(() => () => {
+ if (!active) return
+ const current = runtime.ui.get().currentChannelId
+ if (current !== null && current !== ownedChannel.current) return
runtime.ui.actions.setCurrentChannelId(null)
communityWsUnsubscribe(runtime)
- }, [runtime])
+ }, [active, runtime])
useEffect(() => {
+ if (!active) return
if (metaQuery.canRead) exited.current = null
if (metaQuery.denied || metaQuery.isArchived) {
if (exited.current?.client === queryClient && exited.current.scope === exitScope) return
@@ -130,7 +138,7 @@ export function useChannelRouteModel(
router.replace(consumeCommunityColdEntryFailure(accountId, `/c/channels/${serverParam}/${channelId}`)
? COMMUNITY_COLD_ENTRY_FALLBACK : `/c/channels/${serverParam}`)
} else if (metadataError && metaQuery.error) toastApiError(metaQuery.error, "Failed to load channel")
- }, [accountId, channelId, exitScope, metaQuery.canRead, metaQuery.denied, metaQuery.error, metaQuery.isArchived, metadataError, pathname, queryClient, router, runtime, serverId, serverParam])
+ }, [active, accountId, channelId, exitScope, metaQuery.canRead, metaQuery.denied, metaQuery.error, metaQuery.isArchived, metadataError, pathname, queryClient, router, runtime, serverId, serverParam])
return {
...model,
diff --git a/src/web/src/hooks/community/use-community-view-source.ts b/src/web/src/hooks/community/use-community-view-source.ts
index 09605ee19..db6c4c111 100644
--- a/src/web/src/hooks/community/use-community-view-source.ts
+++ b/src/web/src/hooks/community/use-community-view-source.ts
@@ -1,10 +1,12 @@
"use client"
+import { useConversationActivity } from "@/contexts/community/conversation-activity"
import { useLayoutEffect, useMemo } from "react"
import { createStore, useSelector } from "@tanstack/react-store"
import { useCommunityMutationOrigin } from "./community-origin"
export function useCommunityViewSource(identity: string, enabled = true) {
+ enabled = useConversationActivity() && enabled
const origin = useCommunityMutationOrigin()
const view = useMemo(() => createStore({ identity, owner: origin.registry, active: enabled, generation: 0, controller: new AbortController() }), [origin.registry, identity, enabled])
useLayoutEffect(() => {
diff --git a/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx b/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx
index 04cef2461..23de686ab 100644
--- a/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx
+++ b/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx
@@ -11,6 +11,7 @@ import { conversationEntryOptions, publishConversationEntry } from "@/lib/commun
import { communityKeys } from "@/lib/query-keys"
import { ConversationReadTimeoutError } from "@/lib/community/conversation-read"
import { CommunityRouteContext } from "@/contexts/community/route-frame"
+import { ConversationActivityContext } from "@/contexts/community/conversation-activity"
import { useConversationEntry } from "./use-conversation-entry"
import { useChannelMetadata } from "./use-channel-metadata"
import { useDmMessages } from "./use-messages"
@@ -39,6 +40,40 @@ async function setup() {
}
describe("conversation entry selection", () => {
+ it("retains a parent's window and NEW through background and semantic resume, while a fresh entry reselects", async () => {
+ const { wrapper: Owner, publish, registry } = await setup()
+ const value = fixture()
+ value.messages.push({ ...value.messages[0], id: "m2", seq: 2, content: "Second" })
+ value.page.latestSeq = 2
+ publish(value)
+ let active = true
+ const navigation = { entryIntent: { href: "/c/channels/s1/c1" } as { href: string; resume?: boolean } }
+ function Wrapper({ children }: PropsWithChildren) {
+ return createElement(Owner, null, createElement(CommunityRouteContext, { value: { navigation } as never },
+ createElement(ConversationActivityContext, { value: active }, children)))
+ }
+ const hook = renderHook(() => useConversationEntry(target), { wrapper: Wrapper })
+ const original = hook.result.current.window
+ expect(original).not.toBeNull()
+ expect(hook.result.current.snapshot?.lastReadMessageId).toBe("m1")
+ active = false
+ navigation.entryIntent = { href: "/c/channels/s1/child" }
+ hook.rerender()
+ await act(async () => ingestReadStateSnapshot(registry, { revision: 5, readStates: [
+ { channelId: "c1", lastReadMessageId: "m2", lastReadSeq: 2, lastReadAt: "later" },
+ ] }))
+ expect(hook.result.current.window).toBe(original)
+ active = true
+ navigation.entryIntent = { href: "/c/channels/s1/c1", resume: true }
+ hook.rerender()
+ expect(hook.result.current.window).toBe(original)
+ expect(hook.result.current.snapshot?.lastReadMessageId).toBe("m1")
+ navigation.entryIntent = { href: "/c/channels/s1/c1" }
+ hook.rerender()
+ expect(hook.result.current.snapshot?.lastReadMessageId).toBe("m2")
+ expect(load).not.toHaveBeenCalled()
+ })
+
it("shares one returned-DM read between metadata and the subsequently mounted body", async () => {
const { wrapper: Owner, registry, client } = await setup()
const dmTarget = { channelId: "c1", serverId: null }
diff --git a/src/web/src/hooks/community/use-conversation-entry.ts b/src/web/src/hooks/community/use-conversation-entry.ts
index b571bb649..16a599341 100644
--- a/src/web/src/hooks/community/use-conversation-entry.ts
+++ b/src/web/src/hooks/community/use-conversation-entry.ts
@@ -1,8 +1,9 @@
"use client"
-import { useCallback, useContext, useEffect, useLayoutEffect, useMemo } from "react"
+import { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useState } from "react"
import { createStore, useSelector } from "@tanstack/react-store"
import { hashKey, useQuery, useQueryClient } from "@tanstack/react-query"
+import { useConversationActivity } from "@/contexts/community/conversation-activity"
import { CommunityRouteContext } from "@/contexts/community/route-frame"
import { channelHref, normalizeCommunityHref } from "@/lib/community/community-route"
import type { CommunityReadStateResource } from "@alook/shared"
@@ -77,7 +78,15 @@ export function useConversationEntry(target: ConversationEntryTarget | null) {
const context = useContext(CommunityRouteContext)
const currentIntent = context?.navigation.entryIntent
const expectedPath = target ? target.serverId === null ? `/c/me/${encodeURIComponent(target.channelId)}` : channelHref(target.serverId, target.channelId) : null
- const intent = currentIntent && normalizeCommunityHref(currentIntent.href).pathname === expectedPath ? currentIntent : null
+ const active = useConversationActivity()
+ const incomingIntent = currentIntent && normalizeCommunityHref(currentIntent.href).pathname === expectedPath ? currentIntent : null
+ const [retainedIntent, setRetainedIntent] = useState({ path: expectedPath, intent: incomingIntent })
+ const resuming = incomingIntent?.resume === true
+ useLayoutEffect(() => {
+ if (active && !resuming) setRetainedIntent(current => current.path === expectedPath && current.intent === incomingIntent
+ ? current : { path: expectedPath, intent: incomingIntent })
+ }, [active, expectedPath, incomingIntent, resuming])
+ const intent = (active && !resuming) || retainedIntent.path !== expectedPath ? incomingIntent : retainedIntent.intent
const { client, input, options, query, canonical, resource, canRead, revoked, denied, anchorMissing } = useConversationResource(target, intent)
const entry = useMemo(() => {
const cached = client.getQueryData<ConversationEntryResource>(options.queryKey)
diff --git a/src/web/src/hooks/community/use-native-mobile-back-layers.dom.test.tsx b/src/web/src/hooks/community/use-native-mobile-back-layers.dom.test.tsx
index 182a50255..f484b2b74 100644
--- a/src/web/src/hooks/community/use-native-mobile-back-layers.dom.test.tsx
+++ b/src/web/src/hooks/community/use-native-mobile-back-layers.dom.test.tsx
@@ -1,6 +1,6 @@
import { createRef, useState } from "react"
import { describe, expect, it, vi } from "vitest"
-import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"
+import { Drawer as DialogPrimitive } from "@base-ui/react/drawer"
import { act, fireEvent, render, screen, setupUser, waitFor } from "@/test/react-dom-harness"
import { Dialog, DialogContent, DialogDescription, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
import { Popover, PopoverContent, PopoverPopup, PopoverPortal, PopoverPositioner, PopoverTitle, PopoverTrigger } from "@/components/ui/popover"
@@ -10,6 +10,8 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@
import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuTrigger } from "@/components/ui/context-menu"
import { NATIVE_MOBILE_BACK_EVENT, useNativeMobileBack } from "./use-native-mobile-back"
+vi.mock("@/hooks/use-mobile", async (load) => ({ ...await load<typeof import("@/hooks/use-mobile")>(), useIsMobile: () => false }))
+
function BackListener({ replacePath }: { replacePath: (path: string) => void }) {
useNativeMobileBack({ dismissShellOverlay: () => false, parentPath: "/c/me", replacePath })
return null
diff --git a/src/web/src/stores/community/index.ts b/src/web/src/stores/community/index.ts
index a116041f0..1dad4f32e 100644
--- a/src/web/src/stores/community/index.ts
+++ b/src/web/src/stores/community/index.ts
@@ -27,7 +27,7 @@ export function useUiHandlers() {
previewImage: (image: ImagePreview) => ui.get().uiHandlers.previewImage?.(image),
previewAttachment: (attachment: FileAttachment) => ui.get().uiHandlers.previewAttachment?.(attachment),
openProfile: (name: string, event: React.MouseEvent, discriminator?: string, userId?: string) => ui.get().uiHandlers.openProfile?.(name, event, discriminator, userId),
- goBackMobile: () => ui.get().uiHandlers.goBackMobile?.(),
+ goBackMobile: (parentPath?: string) => ui.get().uiHandlers.goBackMobile?.(parentPath),
navigatePath: (href: string) => ui.get().uiHandlers.navigatePath?.(href),
replacePath: (href: string) => ui.get().uiHandlers.replacePath?.(href),
jumpToSeq: (seq: number) => ui.get().uiHandlers.jumpToSeq?.(seq),
diff --git a/src/web/src/stores/community/ui-handlers.dom.test.tsx b/src/web/src/stores/community/ui-handlers.dom.test.tsx
new file mode 100644
index 000000000..b80e1fe35
--- /dev/null
+++ b/src/web/src/stores/community/ui-handlers.dom.test.tsx
@@ -0,0 +1,23 @@
+import { describe, expect, it, vi } from "vitest"
+import { act } from "@/test/react-dom-harness"
+import { renderCommunityHook } from "@/test/community-owner-harness"
+import { useCommunityRuntime } from "./runtime"
+import { useUiHandlers } from "./index"
+
+describe("community Back handler forwarding", () => {
+ it("uses the current handler and preserves the explicit parent and default request", () => {
+ const { result, rerender } = renderCommunityHook(() => ({ handlers: useUiHandlers(), ui: useCommunityRuntime().ui }))
+ const handlers = result.current.handlers
+ expect(() => handlers.goBackMobile("/c/me")).not.toThrow()
+ const first = vi.fn(), replacement = vi.fn()
+ act(() => result.current.ui.actions.registerUiHandlers({ goBackMobile: first }))
+ handlers.goBackMobile("/c/channels/server/parent")
+ expect(first).toHaveBeenCalledExactlyOnceWith("/c/channels/server/parent")
+ act(() => result.current.ui.actions.registerUiHandlers({ goBackMobile: replacement }))
+ rerender()
+ expect(result.current.handlers).toBe(handlers)
+ handlers.goBackMobile()
+ expect(replacement).toHaveBeenCalledExactlyOnceWith(undefined)
+ expect(first).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/src/web/src/stores/community/ui-store.ts b/src/web/src/stores/community/ui-store.ts
index 192693cfa..4d4fdd0d9 100644
--- a/src/web/src/stores/community/ui-store.ts
+++ b/src/web/src/stores/community/ui-store.ts
@@ -21,7 +21,7 @@ export type CommunityUiHandlers = {
previewImage?: (image: ImagePreview) => void
previewAttachment?: (attachment: FileAttachment) => void
openProfile?: (name: string, e: React.MouseEvent, discriminator?: string, userId?: string) => void
- goBackMobile?: () => void
+ goBackMobile?: (parentPath?: string) => void
navigatePath?: (href: string) => void
replacePath?: (href: string) => void
// Jump to message `seq` within the CURRENT DM. Channel surfaces provide the
diff --git a/src/web/src/test/community-ssr-geometry.test.ts b/src/web/src/test/community-ssr-geometry.test.ts
index e7d7056f2..9244e154d 100644
--- a/src/web/src/test/community-ssr-geometry.test.ts
+++ b/src/web/src/test/community-ssr-geometry.test.ts
@@ -63,13 +63,13 @@ describe("SSR lifecycle geometry boundary", () => {
])
})
- it("accepts retained detail underlays only when hidden, inert and aria-hidden", () => {
+ it("accepts retained detail underlays only when inert, aria-hidden and excluded from hit testing", () => {
const retainedBackground = ["rail", "sidebar", "userBar"].map((module) => ({
- module, visibility: "hidden", inert: true, ariaHidden: true,
+ module, visibility: "visible", inert: true, ariaHidden: true, hitTestBlocked: true,
}))
expect(ssrGeometryErrors([sample({ retainedBackground })], 390, "detail")).toEqual([])
for (const unsafe of [
- { visibility: "visible" }, { inert: false }, { ariaHidden: false },
+ { hitTestBlocked: false }, { inert: false }, { ariaHidden: false },
]) {
expect(ssrGeometryErrors([sample({ retainedBackground: [{ ...retainedBackground[0], ...unsafe }] })], 390, "detail"))
.toContain("sample 0 (ssr): unsafe retained module rail")
diff --git a/src/web/src/test/e2e-ui/08-mobile.spec.ts b/src/web/src/test/e2e-ui/08-mobile.spec.ts
index 5728fd905..a68d1f86c 100644
--- a/src/web/src/test/e2e-ui/08-mobile.spec.ts
+++ b/src/web/src/test/e2e-ui/08-mobile.spec.ts
@@ -1,3 +1,4 @@
+import { expectInertBackground } from "./_fixtures/inert-background"
import type { Page } from "@playwright/test"
import { test, expect } from "./_fixtures/case-fixture"
import { tid } from "./_fixtures/testids"
@@ -75,8 +76,9 @@ test.describe("mobile layout", () => {
await page.goto(`/c/channels/${serverId}/${channelId}`)
await expect(page.getByTestId(tid.composerInput)).toBeVisible()
- await expect(shellPanel(page, "sidebar")).toBeHidden()
- await expectPanelToFillGroup(page, "main")
+ await expectInertBackground(shellPanel(page, "sidebar"))
+ const detail = page.locator('[data-mobile-page-active="true"] [data-slot="mobile-page"]')
+ await expect.poll(() => detail.boundingBox()).toMatchObject({ x: 0, y: 0, width, height: 844 })
}
const mainPanel = shellPanel(page, "main")
@@ -175,7 +177,7 @@ test.describe("mobile layout", () => {
await page.goto(pathname)
const back = page.getByRole("button", { name: "Back" })
await expect(back).toBeVisible()
- await expect(page.getByTestId(tid.homeButton)).toBeHidden()
+ await expectInertBackground(page.getByTestId(tid.homeButton))
await expectNoWrongMeConversationLoading(page)
await back.click()
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 eaa2827c0..ef3afee89 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
@@ -175,7 +175,10 @@ async function expectExplicitTouchSend({
if (parentRoot) {
await expect(parentRoot).toHaveCount(0)
await expect(root.getByTestId(tid.composerFileInput)).toHaveCount(1)
- await expect(page.getByTestId(tid.composerFileInput)).toHaveCount(1)
+ await expect(page.getByTestId(tid.composerFileInput)).toHaveCount(2)
+ await expect.poll(() => page.getByTestId(tid.composerFileInput).evaluateAll(inputs => (
+ inputs.filter(input => input.closest('[data-mobile-page-active="false"][inert][aria-hidden="true"]')).length
+ ))).toBe(1)
}
await root.getByTestId(tid.composerFileInput).setInputFiles({
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 42386daf3..44d1cffcd 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
@@ -14,6 +14,59 @@ async function expectMobileBack(page: Page) {
return control
}
+async function expectRootListDuringCancelledSwipe(page: Page, channelId: string) {
+ const pathname = new URL(page.url()).pathname
+ const popup = page.locator('[data-slot="mobile-page"][data-open]')
+ await expect(popup).toHaveCount(1)
+ await expect(popup).not.toHaveAttribute("data-starting-style")
+ const session = await page.context().newCDPSession(page)
+ try {
+ const point = (x: number) => [{ x, y: 220, radiusX: 1, radiusY: 1, force: 1, id: 1 }]
+ await session.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: point(80) })
+ await session.send("Input.dispatchTouchEvent", { type: "touchMove", touchPoints: point(150) })
+ await session.send("Input.dispatchTouchEvent", { type: "touchMove", touchPoints: point(280) })
+ await expect(popup).toHaveAttribute("data-swiping")
+ await expect.poll(async () => (await popup.boundingBox())?.x ?? 0).toBeGreaterThan(100)
+ const sidebar = page.getByTestId(tid.channelSidebarScroll)
+ await expect(sidebar).toBeVisible()
+ expect((await sidebar.boundingBox())?.width).toBeGreaterThan(200)
+ const row = page.getByTestId(tid.channelRow(channelId))
+ await expect(row).toBeVisible()
+ await expect(row).toContainText("swipe-root-text")
+ expect((await row.boundingBox())?.width).toBeGreaterThan(200)
+ const mainLayer = page.locator('[data-slot="resizable-panel"][id="main"]')
+ await expect(mainLayer).toHaveCSS("position", "fixed")
+ expect(await mainLayer.boundingBox()).toEqual({ x: 0, y: 0, width: 390, height: 844 })
+ const foregroundLeft = (await popup.boundingBox())!.x
+ expect(await row.evaluate((element, edge) => {
+ let { left, right } = element.getBoundingClientRect()
+ for (let parent = element.parentElement; parent; parent = parent.parentElement) {
+ if (["auto", "scroll", "hidden", "clip"].includes(getComputedStyle(parent).overflowX)) {
+ const box = parent.getBoundingClientRect()
+ left = Math.max(left, box.left)
+ right = Math.min(right, box.right)
+ }
+ }
+ return Math.max(0, Math.min(right, edge) - Math.max(left, 0))
+ }, foregroundLeft)).toBeGreaterThan(40)
+ await expect(page.locator('[data-slot="community-sidebar-panel-content"]')).toHaveAttribute("inert")
+ const presentation = page.locator('[data-slot="community-main-panel-content"]').locator("..")
+ await expect(presentation).toHaveCSS("background-color", "rgba(0, 0, 0, 0)")
+ await expect(presentation).toHaveCSS("background-image", "none")
+ expect(new URL(page.url()).pathname).toBe(pathname)
+ await test.info().attach("root-list-during-swipe", { body: await page.screenshot(), contentType: "image/png" })
+ } finally {
+ try {
+ await session.send("Input.dispatchTouchEvent", { type: "touchCancel", touchPoints: [] })
+ } finally {
+ await session.detach()
+ }
+ }
+ await expect(popup).not.toHaveAttribute("data-swiping")
+ await expect.poll(async () => (await popup.boundingBox())?.x ?? Infinity).toBeLessThan(1)
+ expect(new URL(page.url()).pathname).toBe(pathname)
+}
+
test.describe("mobile server header direct hierarchy", () => {
async function prepareCase1(actors: CaseActors) {
const { seedChannel, seedForumThread, seedMessage, seedServer, seedThread } = actors.seed
@@ -42,9 +95,35 @@ test.describe("mobile server header direct hierarchy", () => {
await control.click()
await expect.poll(() => new URL(page.url()).pathname).toBe(`/c/channels/${serverId}`)
expect(await page.evaluate(() => history.length)).toBe(historyLength)
+ await expect(page.locator('[data-slot="community-main-panel-content"]').locator("..")).toBeHidden()
+ const sidebar = page.getByTestId(tid.channelSidebarScroll)
+ await expect(sidebar).toBeVisible()
+ expect(await sidebar.evaluate((element) => {
+ const rect = element.getBoundingClientRect()
+ const hit = document.elementFromPoint(rect.left + rect.width / 2, rect.top + Math.min(rect.height / 2, 100))
+ return hit !== null && element.contains(hit)
+ })).toBe(true)
}
})
+ test("reveals the retained channel list during a partial swipe and cancels without navigation", async ({ caseActors }) => {
+ const actors = await caseActors(["alice"])
+ const serverId = await actors.seed.seedServer("alice", `swipe-root-${Date.now()}`)
+ const channelId = await actors.seed.seedChannel("alice", serverId, "swipe-root-text")
+ await actors.seed.seedMessage("alice", channelId, "Root list reveal control")
+ const { page } = await actors.asUser("alice", { viewport: { width: 390, height: 844 }, hasTouch: true })
+ await page.goto(`/c/channels/${serverId}/${channelId}`, { waitUntil: "commit" })
+ const back = await expectMobileBack(page)
+ await expect(page.getByTestId(tid.composerInput)).toBeVisible()
+ await expectRootListDuringCancelledSwipe(page, channelId)
+ const historyLength = await page.evaluate(() => history.length)
+ await back.click()
+ await expect.poll(() => new URL(page.url()).pathname).toBe(`/c/channels/${serverId}`)
+ expect(await page.evaluate(() => history.length)).toBe(historyLength)
+ await expect(page.locator('[data-slot="community-main-panel-content"]').locator("..")).toBeHidden()
+ await expect(page.getByTestId(tid.channelSidebarScroll)).toBeVisible()
+ })
+
test("thread and forum post expose direct parent Back and inert current labels", async ({ caseActors }) => {
const actors = await caseActors(["alice"])
const { asUser } = actors
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 f7a02c81e..9cb33d2d9 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
@@ -1,3 +1,4 @@
+import { expectInertBackground } from "./_fixtures/inert-background"
import type { Locator, Page, Response } from "@playwright/test"
import { AccountAttentionSnapshotSchema } from "@alook/shared"
import { expect, test } from "./_fixtures/case-fixture"
@@ -301,7 +302,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).toBeHidden()
+ await expectInertBackground(railContainer)
await expect(railContainer).toHaveAttribute("inert", "")
await expect(railContainer).toHaveAttribute("aria-hidden", "true")
let lastMessageId = await sendMention(`Hidden Server digit ${stamp}`)
@@ -315,7 +316,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).toBeHidden()
+ await expectInertBackground(railContainer)
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 f71cc44cd..84000305e 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
@@ -1,3 +1,4 @@
+import { expectInertBackground } from "./_fixtures/inert-background"
import type { Page, Request, Route } from "@playwright/test"
import { expect, test, type CaseActors } from "./_fixtures/case-fixture"
import { GEOMETRY_EPSILON, composerEditable, gotoAfterUserWsAuth, ignoreNextDevToolsPointerCapture, waitForElementMotion } from "./_fixtures/actions"
@@ -354,7 +355,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).toBeHidden()
+ await expectInertBackground(overlay)
await expect(overlay).toHaveAttribute("inert", "")
await expect(overlay).toHaveAttribute("aria-hidden", "true")
await send(hiddenId, `Hidden Inbox digit ${stamp}`)
@@ -367,7 +368,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).toBeHidden()
+ await expectInertBackground(overlay)
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/60-desktop-default-user-bar-width.spec.ts b/src/web/src/test/e2e-ui/60-desktop-default-user-bar-width.spec.ts
index f87bbf7fa..5c8ee6eee 100644
--- a/src/web/src/test/e2e-ui/60-desktop-default-user-bar-width.spec.ts
+++ b/src/web/src/test/e2e-ui/60-desktop-default-user-bar-width.spec.ts
@@ -1,3 +1,4 @@
+import { expectInertBackground } from "./_fixtures/inert-background"
import type { Page, Request, Route, TestInfo } from "@playwright/test"
import { expect, test } from "./_fixtures/case-fixture"
import { gotoAfterUserWsAuth, waitForElementMotion } from "./_fixtures/actions"
@@ -498,7 +499,7 @@ test.describe("desktop default User Bar width", () => {
}
expectMainAbsorbsViewportDelta(unsavedResizeSequence)
await fresh.page.setViewportSize({ width: 639, height: 768 })
- await expect(shellPanel(fresh.page, "sidebar")).toBeHidden()
+ await expectInertBackground(shellPanel(fresh.page, "sidebar"))
await expect(shellPanel(fresh.page, "main")).toBeVisible()
await fresh.page.setViewportSize({ width: 640, height: 768 })
await expectDesktopGeometry(fresh.page, expectedDefaultSidebarWidth)
@@ -582,7 +583,7 @@ test.describe("desktop default User Bar width", () => {
}
expectMainAbsorbsViewportDelta(savedResizeSequence)
await saved.page.setViewportSize({ width: 639, height: 768 })
- await expect(shellPanel(saved.page, "sidebar")).toBeHidden()
+ await expectInertBackground(shellPanel(saved.page, "sidebar"))
await saved.page.setViewportSize({ width: 640, height: 768 })
await expectDesktopGeometry(saved.page, restoredWidth)
expect(await saved.page.evaluate((key) => localStorage.getItem(key), layoutStorageKey))
@@ -809,7 +810,7 @@ test.describe("desktop default User Bar width", () => {
).length)
await page.setViewportSize({ width, height: 844 })
if (width < 640) {
- await expect(shellPanel(page, "sidebar")).toBeHidden()
+ await expectInertBackground(shellPanel(page, "sidebar"))
previousWidth = width
continue
}
@@ -890,7 +891,7 @@ test.describe("desktop default User Bar width", () => {
))).toEqual([])
await saved.page.setViewportSize({ width: 639, height: 844 })
- await expect(shellPanel(saved.page, "sidebar")).toBeHidden()
+ await expectInertBackground(shellPanel(saved.page, "sidebar"))
await saved.page.goto("/c/me")
await expect(saved.page.getByRole("link", { name: "Friends", exact: true })).toBeVisible()
await expect(shellPanel(saved.page, "sidebar")).toBeVisible()
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 3b1d664ce..df22a985d 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
@@ -1,3 +1,4 @@
+import { expectInertBackground } from "./inert-background"
import type {
BrowserContext,
BrowserContextOptions,
@@ -20,6 +21,7 @@ import { WEB_URL } from "../_setup/paths"
import { ssrGeometryErrors, type SsrLifecycleSample } from "./community-ssr-geometry"
import { expectUniqueSsrCommunityFrame } from "./community-ssr-frame"
import type { UserKey } from "../_setup/users"
+import { waitForElementMotion } from "./actions"
type Theme = "light" | "dark"
type CommunityAsUser = (
@@ -194,14 +196,37 @@ const shellPanel = (page: Page, id: "sidebar" | "main") => (
)
async function visibleGeometry(page: Page): Promise<Geometry> {
+ const detail = page.locator('[data-mobile-page-active="true"] [data-slot="mobile-page"]')
+ if (await detail.count()) await waitForElementMotion(detail)
return page.evaluate(({ sidebarId, mainId }) => {
const visible = (element: Element) => { const box = element.getBoundingClientRect(); const style = getComputedStyle(element); return box.width > 0 && box.height > 0 && style.visibility !== "hidden" && style.visibility !== "collapse" }
const frames = Array.from(document.querySelectorAll('[data-slot="community-shell-root"]')).filter(visible)
if (frames.length !== 1) throw new Error(`Expected one actual geometry frame, got ${frames.length}`)
const frame = frames[0]
- const selectors = { shell: '[data-slot="community-shell-root"]', surface: '[data-slot="community-app-surface"]', rail: '[data-slot="community-server-rail-viewport"]', sidebar: `[data-slot="resizable-panel"][data-testid="${sidebarId}"]`, main: `[data-slot="resizable-panel"][data-testid="${mainId}"]`, userBar: '[data-slot="community-user-bar-overlay"]' }
+ const detailLayers = innerWidth < 640
+ ? Array.from(frame.querySelectorAll(`[data-slot="resizable-panel"][data-testid="${mainId}"][data-mobile-layer="true"]`)).filter(visible)
+ : []
+ if (detailLayers.length > 1) throw new Error(`Duplicate mobile detail layer: ${detailLayers.length}`)
+ const detailLayer = detailLayers[0]
+ const detail = detailLayer?.querySelector('[data-mobile-page-active="true"] [data-slot="mobile-page"]') ?? detailLayer
+ const selectors = { shell: '[data-slot="community-shell-root"]', body: '[data-slot="community-shell-body"]', surface: '[data-slot="community-app-surface"]', backgroundSurface: '[data-slot="community-app-surface"]', rail: '[data-slot="community-server-rail-viewport"]', sidebar: `[data-slot="resizable-panel"][data-testid="${sidebarId}"]`, main: `[data-slot="resizable-panel"][data-testid="${mainId}"]`, userBar: '[data-slot="community-user-bar-overlay"]' }
const result: Geometry = {}
for (const [name, selector] of Object.entries(selectors)) {
+ if (detail && ["rail", "sidebar", "userBar"].includes(name)) {
+ for (const element of Array.from(frame.querySelectorAll(selector)).filter(visible)) {
+ const guard = name === "sidebar" ? element.querySelector('[data-slot="community-sidebar-panel-content"]') : element.closest("[inert]")
+ if (!guard?.hasAttribute("inert") || guard.getAttribute("aria-hidden") !== "true") throw new Error(`Unsafe background geometry module ${name}`)
+ const box = element.getBoundingClientRect()
+ const hit = document.elementFromPoint(Math.max(0, Math.min(innerWidth - 1, box.x + box.width / 2)), Math.max(0, Math.min(innerHeight - 1, box.y + box.height / 2)))
+ if (hit && element.contains(hit)) throw new Error(`Interactive background geometry module ${name}`)
+ }
+ continue
+ }
+ if (detail && ["surface", "main"].includes(name)) {
+ const box = detail.getBoundingClientRect()
+ result[name] = { x: box.x, y: box.y, width: box.width, height: box.height }
+ continue
+ }
const nodes = (frame.matches(selector) ? [frame] : Array.from(frame.querySelectorAll(selector))).filter(visible)
if (nodes.length > 1) throw new Error(`Duplicate geometry module ${name}`)
if (nodes.length === 1) { const box = nodes[0].getBoundingClientRect(); result[name] = { x: box.x, y: box.y, width: box.width, height: box.height } }
@@ -291,8 +316,8 @@ async function installSsrLifecycleProbe(page: Page, surface: "list" | "detail")
document.addEventListener("readystatechange", () => { if (document.readyState !== "loading") parsed = true })
document.addEventListener("DOMContentLoaded", () => { parsed = true }, { once: true })
- const rect = (root: Element, selector: string) => {
- const element = root.matches(selector) ? root : root.querySelector<HTMLElement>(selector)
+ const rect = (root: Element, selector?: string) => {
+ const element = !selector || root.matches(selector) ? root : root.querySelector<HTMLElement>(selector)
if (!element) return null
const style = getComputedStyle(element)
if (style.display === "none" || style.visibility !== "visible") return null
@@ -307,18 +332,24 @@ async function installSsrLifecycleProbe(page: Page, surface: "list" | "detail")
if (shell) {
const activePanel = '[data-slot="resizable-panel"][data-mobile-active="true"]'
const hiddenPanel = '[data-slot="resizable-panel"][data-mobile-hidden="true"]'
+ const sidebarPanel = '[data-slot="resizable-panel"][id="sidebar"]'
+ const detailLayer = expectedSurface === "detail"
+ ? shell.querySelector('[data-slot="resizable-panel"][data-mobile-layer="true"]')
+ : null
+ const detail = detailLayer?.querySelector('[data-mobile-page-active="true"] [data-slot="mobile-page"]') ?? detailLayer
+ const detailGeometry = detail ? rect(detail) : null
const geometry = Object.fromEntries(Object.entries({
shell: rect(shell, '[data-slot="community-shell-root"]'),
- surface: rect(shell, '[data-slot="community-app-surface"]'),
- rail: rect(shell, '[data-slot="community-server-rail-viewport"]'),
- sidebar: rect(shell, expectedSurface === "list" ? activePanel : hiddenPanel),
- main: rect(shell, expectedSurface === "detail" ? activePanel : hiddenPanel),
- userBar: rect(shell, '[data-slot="community-user-bar-overlay"]'),
+ surface: expectedSurface === "detail" ? detailGeometry : rect(shell, '[data-slot="community-app-surface"]'),
+ rail: expectedSurface === "detail" ? null : rect(shell, '[data-slot="community-server-rail-viewport"]'),
+ sidebar: expectedSurface === "detail" ? null : rect(shell, activePanel),
+ main: expectedSurface === "detail" ? detailGeometry : rect(shell, hiddenPanel),
+ userBar: expectedSurface === "detail" ? null : rect(shell, '[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-community-rail]', '[data-community-rail]'],
- sidebar: [hiddenPanel, '[data-slot="community-sidebar-panel-content"]'],
+ sidebar: [sidebarPanel, '[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)
@@ -326,8 +357,10 @@ async function installSsrLifecycleProbe(page: Page, surface: "list" | "detail")
const box = element.getBoundingClientRect()
if (!box.width || !box.height) return []
const guard = document.querySelector<HTMLElement>(guardSelector)
+ const hit = document.elementFromPoint(Math.max(0, Math.min(innerWidth - 1, box.x + box.width / 2)), Math.max(0, Math.min(innerHeight - 1, box.y + box.height / 2)))
return [{ module, visibility: getComputedStyle(element).visibility,
- inert: guard?.inert === true, ariaHidden: guard?.getAttribute("aria-hidden") === "true" }]
+ inert: guard?.inert === true, ariaHidden: guard?.getAttribute("aria-hidden") === "true",
+ hitTestBlocked: !hit || !element.contains(hit) }]
})
: []
samples.push({
@@ -887,7 +920,7 @@ export async function runRouteLoadingGeometry(
.toBe(true)
} else {
await expect(loadedAdd).toHaveCount(1)
- await expect(loadedAdd).toBeHidden()
+ await expectInertBackground(loadedAdd)
expect(await loadedAdd.evaluate((element) => (
element.closest('[inert][aria-hidden="true"]') !== null
))).toBe(true)
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 e7aa4638a..36368d23d 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,7 +8,7 @@ export type SsrLifecycleSample = {
incompleteShellHtml?: string
overflow: number
geometry: SsrGeometry
- retainedBackground?: { module: string; visibility: string; inert: boolean; ariaHidden: boolean }[]
+ retainedBackground?: { module: string; visibility: string; inert: boolean; ariaHidden: boolean; hitTestBlocked: boolean }[]
}
export function ssrGeometryErrors(
@@ -29,7 +29,7 @@ export function ssrGeometryErrors(
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) {
+ if (!retained.inert || !retained.ariaHidden || !retained.hitTestBlocked) {
errors.push(`${label}: unsafe retained module ${retained.module}`)
}
}
diff --git a/src/web/src/test/e2e-ui/_fixtures/inert-background.ts b/src/web/src/test/e2e-ui/_fixtures/inert-background.ts
new file mode 100644
index 000000000..ef5581597
--- /dev/null
+++ b/src/web/src/test/e2e-ui/_fixtures/inert-background.ts
@@ -0,0 +1,10 @@
+import { expect, type Locator } from "@playwright/test"
+
+export async function expectInertBackground(target: Locator) {
+ await expect(target).toBeVisible()
+ await expect.poll(() => target.evaluate(element => {
+ const controls = element.matches("a,button,input,textarea,[contenteditable=true]") ? [element]
+ : [...element.querySelectorAll("a,button,input,textarea,[contenteditable=true]")]
+ return controls.length > 0 && controls.every(control => control.closest("[inert]") && control.closest('[aria-hidden="true"]'))
+ })).toBe(true)
+}
diff --git a/src/web/src/test/react-dom-harness.ts b/src/web/src/test/react-dom-harness.ts
index 6e4878106..58c0ab346 100644
--- a/src/web/src/test/react-dom-harness.ts
+++ b/src/web/src/test/react-dom-harness.ts
@@ -101,3 +101,13 @@ export function mockElementGeometry(
}
}
}
+
+if (typeof window.matchMedia !== "function") {
+ Object.defineProperty(window, "matchMedia", { configurable: true, writable: true,
+ value: (media: string) => ({
+ media, matches: media.includes("prefers-reduced-motion"), onchange: null,
+ addListener() {}, removeListener() {}, addEventListener() {}, removeEventListener() {},
+ dispatchEvent: () => false,
+ }),
+ })
+}