diff --git a/client/ios/App/App/TrekBridgeViewController.swift b/client/ios/App/App/TrekBridgeViewController.swift index 9236553cb..65d6477b3 100644 --- a/client/ios/App/App/TrekBridgeViewController.swift +++ b/client/ios/App/App/TrekBridgeViewController.swift @@ -19,9 +19,11 @@ class TrekBridgeViewController: CAPBridgeViewController { override func capacitorDidLoad() { bridge?.registerPluginInstance(TrekShellPlugin()) - // The swipe from the left edge that goes back in every iOS app. It walks - // the SPA's history, the same entries Android's back button uses. - webView?.allowsBackForwardNavigationGestures = true + // WebKit's own swipe back slides away a screenshot of the whole page, + // closes no sheet and takes every drag near the edge from the UI. The UI + // draws its own (mobile/components/MEdgeBack.tsx, feature "edgeBack"): + // the page follows the finger and an open sheet closes first. + webView?.allowsBackForwardNavigationGestures = false } } diff --git a/client/ios/App/App/TrekShellPlugin.swift b/client/ios/App/App/TrekShellPlugin.swift index b5d944939..2cae368b1 100644 --- a/client/ios/App/App/TrekShellPlugin.swift +++ b/client/ios/App/App/TrekShellPlugin.swift @@ -24,7 +24,7 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr /// and a server can require a minimum (minNativeShellApi in /api/health/features). static let shellApi = 2 /// The native features by name, so the UI can turn each on by itself. - static let features: [String] = ["capabilities"] + static let features: [String] = ["capabilities", "edgeBack"] @objc func getCapabilities(_ call: CAPPluginCall) { let info = Bundle.main.infoDictionary diff --git a/client/src/mobile/MobileShell.tsx b/client/src/mobile/MobileShell.tsx index e04e2ca95..2b7cd3704 100644 --- a/client/src/mobile/MobileShell.tsx +++ b/client/src/mobile/MobileShell.tsx @@ -1,9 +1,12 @@ -import { ReactNode } from 'react' +import { ReactNode, useRef } from 'react' import { useMatch } from 'react-router' import BottomNav from '../components/Layout/BottomNav' import ErrorBoundary from '../components/shared/ErrorBoundary' import MBottomNav from './components/MBottomNav' import MToastHost from './components/MToastHost' +import MEdgeBack from './components/MEdgeBack' +import { useNativeCapabilities } from '../native/capabilities' +import { isNativeIos } from '../native/platform' import './mobile.css' interface MobileShellProps { @@ -32,6 +35,10 @@ export default function MobileShell({ isPhone, children }: MobileShellProps) { // on iOS Safari a position:fixed nav paints THROUGH the trip overlay's higher // stacking context, so the wrong (global) bar shows on top of the trip screen. const inTripPlanner = useMatch('/trips/:id') + // The app's own edge swipe back, where the binary has turned WebKit's off. + const { caps } = useNativeCapabilities() + const pageRef = useRef(null) + const edgeBack = isNativeIos() && caps.features.includes('edgeBack') if (!isPhone) { return ( @@ -59,7 +66,8 @@ export default function MobileShell({ isPhone, children }: MobileShellProps) { layer to be visible, body must not paint over it, which index.css handles for this breakpoint. */}
-
{children}
+
{children}
+ {!inTripPlanner && }
diff --git a/client/src/mobile/components/MEdgeBack.test.tsx b/client/src/mobile/components/MEdgeBack.test.tsx new file mode 100644 index 000000000..4963dc3a3 --- /dev/null +++ b/client/src/mobile/components/MEdgeBack.test.tsx @@ -0,0 +1,100 @@ +import { render } from '@testing-library/react'; +import { useRef } from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { tickHaptic } from '../../native/haptics'; +import { closeTopOverlay, hasOpenOverlay } from '../overlayStack'; +import MEdgeBack from './MEdgeBack'; + +vi.mock('../overlayStack', () => ({ closeTopOverlay: vi.fn(), hasOpenOverlay: vi.fn(() => false) })); +vi.mock('../../native/haptics', () => ({ tickHaptic: vi.fn() })); + +function Host({ enabled = true }: { enabled?: boolean }) { + const ref = useRef(null); + return ( + <> +
+ + + ); +} + +function touch(type: string, x: number, y = 300, t = 0) { + const e = new Event(type, { bubbles: true, cancelable: true }) as Event & Record; + Object.defineProperty(e, 'touches', { value: type === 'touchend' ? [] : [{ clientX: x, clientY: y }] }); + Object.defineProperty(e, 'changedTouches', { value: [{ clientX: x, clientY: y }] }); + Object.defineProperty(e, 'timeStamp', { value: t }); + document.dispatchEvent(e); +} + +beforeEach(() => { + vi.useFakeTimers(); + vi.mocked(hasOpenOverlay).mockReturnValue(false); + window.history.replaceState({ idx: 2 }, ''); + Object.defineProperty(window, 'innerWidth', { configurable: true, value: 400 }); +}); +afterEach(() => { + vi.useRealTimers(); + vi.clearAllMocks(); +}); + +describe('MEdgeBack', () => { + it('drags the page with a finger from the left edge, and goes back past a third', () => { + const back = vi.spyOn(window.history, 'back').mockImplementation(() => {}); + const { getByTestId } = render(); + touch('touchstart', 5, 300, 0); + touch('touchmove', 40, 302, 50); + touch('touchmove', 200, 304, 400); + expect(getByTestId('page').style.transform).toBe('translateX(195px)'); + touch('touchend', 200, 304, 900); + vi.advanceTimersByTime(250); + expect(back).toHaveBeenCalledTimes(1); + expect(tickHaptic).toHaveBeenCalled(); + }); + + it('springs back on a short, slow drag', () => { + const back = vi.spyOn(window.history, 'back').mockImplementation(() => {}); + const { getByTestId } = render(); + touch('touchstart', 5, 300, 0); + touch('touchmove', 30, 300, 200); + touch('touchmove', 60, 300, 800); + touch('touchend', 60, 300, 1600); + vi.advanceTimersByTime(300); + expect(back).not.toHaveBeenCalled(); + expect(getByTestId('page').style.transform).toBe(''); + }); + + it('closes an open sheet first and leaves the page where it is', () => { + vi.mocked(hasOpenOverlay).mockReturnValue(true); + const back = vi.spyOn(window.history, 'back').mockImplementation(() => {}); + const { getByTestId } = render(); + touch('touchstart', 5, 300, 0); + touch('touchmove', 200, 300, 100); + expect(getByTestId('page').style.transform).toBe(''); + touch('touchend', 200, 300, 200); + expect(closeTopOverlay).toHaveBeenCalledTimes(1); + expect(back).not.toHaveBeenCalled(); + }); + + it('ignores a touch away from the edge, a vertical scroll, the first page and a binary without the feature', () => { + const back = vi.spyOn(window.history, 'back').mockImplementation(() => {}); + const { unmount } = render(); + touch('touchstart', 120); + touch('touchmove', 300); + touch('touchend', 300, 300, 100); + touch('touchstart', 5, 300); + touch('touchmove', 8, 400); + touch('touchend', 8, 400, 100); + window.history.replaceState({ idx: 0 }, ''); + touch('touchstart', 5); + touch('touchmove', 300); + touch('touchend', 300, 300, 100); + unmount(); + window.history.replaceState({ idx: 2 }, ''); + render(); + touch('touchstart', 5); + touch('touchmove', 300); + touch('touchend', 300, 300, 100); + vi.advanceTimersByTime(300); + expect(back).not.toHaveBeenCalled(); + }); +}); diff --git a/client/src/mobile/components/MEdgeBack.tsx b/client/src/mobile/components/MEdgeBack.tsx new file mode 100644 index 000000000..abb43fa4f --- /dev/null +++ b/client/src/mobile/components/MEdgeBack.tsx @@ -0,0 +1,118 @@ +import type { RefObject } from 'react'; +import { useEffect } from 'react'; +import { tickHaptic } from '../../native/haptics'; +import { closeTopOverlay, hasOpenOverlay } from '../overlayStack'; + +/** + * The swipe from the left edge that goes back, the way every iOS app has it. + * + * WebKit's own version slides away a screenshot of the whole page, closes no + * sheet and fights every gesture near the edge (the day pager, swipe rows), so + * the app turns it off (TrekBridgeViewController) and this takes over: the + * page follows the finger, and a release past a third of the screen or a flick + * slides it off and goes back. An open sheet closes first instead, the same + * order Android's back gesture follows. Mounted only where the binary reports + * the `edgeBack` feature, so an older binary keeps WebKit's. + */ + +/** A touch has to start this close to the left edge. */ +const EDGE_PX = 22; +/** Sideways must clearly beat vertical before the gesture is claimed. */ +const CLAIM_PX = 10; +const AXIS_BIAS = 1.5; +const COMMIT_SHARE = 0.33; +const FLICK_V = 0.5; + +/** react-router keeps its position in the session history on history.state. */ +function canGoBack(): boolean { + const idx = (window.history.state as { idx?: number } | null)?.idx; + return typeof idx === 'number' && idx > 0; +} + +export default function MEdgeBack({ target, enabled }: { target: RefObject; enabled: boolean }) { + useEffect(() => { + if (!enabled) return; + let start: { x: number; y: number; t: number } | null = null; + let claimed = false; + let overlay = false; + let last = { x: 0, t: 0 }; + + const move = (x: number, transition: string) => { + const el = target.current; + if (!el) return; + el.style.transition = transition; + el.style.transform = x ? `translateX(${x}px)` : ''; + el.style.boxShadow = x ? '-16px 0 40px -12px rgba(0,0,0,.35)' : ''; + }; + + const onStart = (e: TouchEvent) => { + claimed = false; + start = null; + if (e.touches.length !== 1) return; + const t = e.touches[0]; + if (t.clientX > EDGE_PX) return; + overlay = hasOpenOverlay(); + if (!overlay && !canGoBack()) return; + start = { x: t.clientX, y: t.clientY, t: e.timeStamp }; + last = { x: t.clientX, t: e.timeStamp }; + }; + + const onMove = (e: TouchEvent) => { + if (!start || e.touches.length !== 1) return; + const t = e.touches[0]; + const dx = t.clientX - start.x; + const dy = t.clientY - start.y; + if (!claimed) { + if (Math.abs(dy) > CLAIM_PX && Math.abs(dy) > Math.abs(dx)) { + start = null; + return; + } + if (dx < CLAIM_PX || dx < Math.abs(dy) * AXIS_BIAS) return; + claimed = true; + } + if (e.cancelable) e.preventDefault(); + last = { x: t.clientX, t: e.timeStamp }; + // An open sheet closes on release; the page itself stays put under it. + if (!overlay) move(Math.max(0, dx), 'none'); + }; + + const onEnd = (e: TouchEvent) => { + const s = start; + start = null; + if (!s || !claimed) return; + const x = e.changedTouches[0]?.clientX ?? last.x; + const dx = Math.max(0, x - s.x); + const v = (x - last.x) / Math.max(1, e.timeStamp - last.t) || dx / Math.max(1, e.timeStamp - s.t); + const width = window.innerWidth; + const commit = dx > width * COMMIT_SHARE || v > FLICK_V; + if (!commit) { + move(0, 'transform 260ms var(--ease-drawer), box-shadow 260ms'); + return; + } + tickHaptic(); + if (overlay) { + closeTopOverlay(); + return; + } + move(width, 'transform 200ms cubic-bezier(0.2, 0.8, 0.2, 1)'); + window.setTimeout(() => { + window.history.back(); + // The page that comes back takes the place without a slide of its own. + requestAnimationFrame(() => move(0, 'none')); + }, 190); + }; + + document.addEventListener('touchstart', onStart, { passive: true }); + document.addEventListener('touchmove', onMove, { passive: false }); + document.addEventListener('touchend', onEnd, { passive: true }); + document.addEventListener('touchcancel', onEnd, { passive: true }); + return () => { + document.removeEventListener('touchstart', onStart); + document.removeEventListener('touchmove', onMove); + document.removeEventListener('touchend', onEnd); + document.removeEventListener('touchcancel', onEnd); + move(0, 'none'); + }; + }, [enabled, target]); + return null; +} diff --git a/client/src/mobile/components/MSheet.tsx b/client/src/mobile/components/MSheet.tsx index e1ebea5ce..cc76d23b4 100644 --- a/client/src/mobile/components/MSheet.tsx +++ b/client/src/mobile/components/MSheet.tsx @@ -5,6 +5,7 @@ import { useTranslation } from '../../i18n' import { useDiscardGuard } from '../../components/shared/useDiscardGuard' import { keepTabInside, useModalFocus } from './modalFocus' import { useSheetDrag } from './useSheetDrag' +import { useOverlay } from '../overlayStack' export type MSheetVariant = 'card' | 'bottom' | 'drawer' export type MSheetMaterial = 'glass' | 'bar-glass' | 'opaque' @@ -151,6 +152,10 @@ export default function MSheet({ return lockBodyScroll() }, [open]) + // A way back (the edge swipe, Android's back gesture) closes the sheet on top + // first, through the same path as the scrim, so unsaved changes still ask. + useOverlay(open && rendered, requestClose) + // Move focus into the dialog on open, hand it back on close. useModalFocus(panelRef, open && rendered) diff --git a/client/src/mobile/overlayStack.test.ts b/client/src/mobile/overlayStack.test.ts new file mode 100644 index 000000000..0824e16e9 --- /dev/null +++ b/client/src/mobile/overlayStack.test.ts @@ -0,0 +1,36 @@ +import { renderHook } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { _resetOverlayStack, closeTopOverlay, hasOpenOverlay, useOverlay } from './overlayStack'; + +beforeEach(() => _resetOverlayStack()); + +describe('overlayStack', () => { + it('closes the newest open overlay first, and reports when none is left', () => { + const first = vi.fn(); + const second = vi.fn(); + const a = renderHook(({ open }) => useOverlay(open, first), { initialProps: { open: true } }); + renderHook(({ open }) => useOverlay(open, second), { initialProps: { open: true } }); + expect(hasOpenOverlay()).toBe(true); + + expect(closeTopOverlay()).toBe(true); + expect(second).toHaveBeenCalledTimes(1); + expect(first).not.toHaveBeenCalled(); + + a.rerender({ open: false }); + a.unmount(); + }); + + it('forgets an overlay once it closes, and uses its latest close path', () => { + const old = vi.fn(); + const fresh = vi.fn(); + const h = renderHook(({ open, close }) => useOverlay(open, close), { initialProps: { open: true, close: old } }); + h.rerender({ open: true, close: fresh }); + closeTopOverlay(); + expect(fresh).toHaveBeenCalledTimes(1); + expect(old).not.toHaveBeenCalled(); + + h.rerender({ open: false, close: fresh }); + expect(hasOpenOverlay()).toBe(false); + expect(closeTopOverlay()).toBe(false); + }); +}); diff --git a/client/src/mobile/overlayStack.ts b/client/src/mobile/overlayStack.ts new file mode 100644 index 000000000..0703b2718 --- /dev/null +++ b/client/src/mobile/overlayStack.ts @@ -0,0 +1,43 @@ +import { useEffect, useRef } from 'react'; + +/** + * The overlays open on screen, newest last, so a way back closes the one on + * top before it leaves the page: the iOS edge swipe (MEdgeBack) and Android's + * back gesture (native/nativeApp.ts) both ask here first. Each entry is the + * overlay's own close path, so an unsaved-changes question still asks. + */ +type Close = () => void; +const stack: { id: number; close: () => void }[] = []; +let nextId = 1; + +/** Closes the overlay on top. False when none is open, so the caller goes back instead. */ +export function closeTopOverlay(): boolean { + const top = stack[stack.length - 1]; + if (!top) return false; + top.close(); + return true; +} + +export function hasOpenOverlay(): boolean { + return stack.length > 0; +} + +/** Registers an overlay while `open`, with the way it closes. */ +export function useOverlay(open: boolean, close: Close): void { + const closeRef = useRef(close); + closeRef.current = close; + useEffect(() => { + if (!open) return; + const entry = { id: nextId++, close: () => closeRef.current() }; + stack.push(entry); + return () => { + const i = stack.findIndex((e) => e.id === entry.id); + if (i >= 0) stack.splice(i, 1); + }; + }, [open]); +} + +/** Test helper. */ +export function _resetOverlayStack(): void { + stack.length = 0; +} diff --git a/client/src/native/nativeApp.test.ts b/client/src/native/nativeApp.test.ts index 1dbb85a58..3d1afb3b7 100644 --- a/client/src/native/nativeApp.test.ts +++ b/client/src/native/nativeApp.test.ts @@ -3,6 +3,7 @@ import { Keyboard } from '@capacitor/keyboard'; import { SplashScreen } from '@capacitor/splash-screen'; import { StatusBar, Style } from '@capacitor/status-bar'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { closeTopOverlay } from '../mobile/overlayStack'; import { isEffectivelyOffline } from '../sync/networkMode'; import { checkAppUpdate } from './capabilities'; import { startNativeApp } from './nativeApp'; @@ -17,6 +18,7 @@ vi.mock('./platform', () => ({ isNativeApp: vi.fn(), isNativeIos: vi.fn() })); vi.mock('./offlineShell', () => ({ keepOfflineShellFresh: vi.fn() })); vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: vi.fn() })); vi.mock('./capabilities', () => ({ checkAppUpdate: vi.fn(async () => false) })); +vi.mock('../mobile/overlayStack', () => ({ closeTopOverlay: vi.fn(() => false) })); function backButtonHandler(): (event: { canGoBack: boolean }) => void { const call = vi.mocked(App.addListener).mock.calls.find(([name]) => name === 'backButton'); @@ -46,6 +48,17 @@ describe('startNativeApp', () => { expect(StatusBar.setStyle).not.toHaveBeenCalled(); }); + it("Android's back gesture closes an open sheet before it leaves the page", () => { + const back = vi.spyOn(window.history, 'back').mockImplementation(() => {}); + vi.mocked(closeTopOverlay).mockReturnValueOnce(true); + startNativeApp(); + backButtonHandler()({ canGoBack: true }); + expect(back).not.toHaveBeenCalled(); + backButtonHandler()({ canGoBack: true }); + expect(back).toHaveBeenCalledTimes(1); + back.mockRestore(); + }); + it('asks the binary what it can do and the server which binary it needs', () => { startNativeApp(); expect(checkAppUpdate).toHaveBeenCalledWith(expect.any(Function)); diff --git a/client/src/native/nativeApp.ts b/client/src/native/nativeApp.ts index c4ead14a4..c77333dba 100644 --- a/client/src/native/nativeApp.ts +++ b/client/src/native/nativeApp.ts @@ -2,6 +2,7 @@ import { App } from '@capacitor/app'; import { Keyboard } from '@capacitor/keyboard'; import { SplashScreen } from '@capacitor/splash-screen'; import { StatusBar, Style } from '@capacitor/status-bar'; +import { closeTopOverlay } from '../mobile/overlayStack'; import { isEffectivelyOffline } from '../sync/networkMode'; import { checkAppUpdate } from './capabilities'; import { keepOfflineShellFresh } from './offlineShell'; @@ -27,6 +28,8 @@ export function startNativeApp(): void { // Android's back gesture: through the app's own history first, and only // then out of the app, the way a browser tab would behave. void App.addListener('backButton', ({ canGoBack }) => { + // An open sheet closes first, as on iOS's edge swipe. + if (closeTopOverlay()) return; if (canGoBack) window.history.back(); else void App.minimizeApp(); }); diff --git a/client/tests/unit/mobile/MSheet.test.tsx b/client/tests/unit/mobile/MSheet.test.tsx index 2ba3c0197..e7b1bf8c1 100644 --- a/client/tests/unit/mobile/MSheet.test.tsx +++ b/client/tests/unit/mobile/MSheet.test.tsx @@ -2,6 +2,7 @@ import React from 'react'; import { describe, it, expect, vi, afterEach } from 'vitest'; import { render, screen, fireEvent, act } from '@testing-library/react'; import MSheet from '../../../src/mobile/components/MSheet'; +import { closeTopOverlay } from '../../../src/mobile/overlayStack'; // FE-MOB-SHEET-001 onwards @@ -293,6 +294,23 @@ describe('MSheet', () => { expect(baseCalls).toEqual([]); }); + it('FE-MOB-SHEET-030: a way back (edge swipe, Android back) closes the open sheet first', () => { + const onClose = vi.fn(); + const { rerender } = render( + + Sheet content + , + ); + expect(closeTopOverlay()).toBe(true); + expect(onClose).toHaveBeenCalledTimes(1); + rerender( + + Sheet content + , + ); + expect(closeTopOverlay()).toBe(false); + }); + describe('dragging the docked sheet', () => { const touch = (y: number, x = 100) => ({ touches: [{ clientX: x, clientY: y }], changedTouches: [{ clientX: x, clientY: y }] });