diff --git a/client/ios/App/App/TrekShellPlugin.swift b/client/ios/App/App/TrekShellPlugin.swift index 30ac82d50..d5f79bad2 100644 --- a/client/ios/App/App/TrekShellPlugin.swift +++ b/client/ios/App/App/TrekShellPlugin.swift @@ -1,5 +1,6 @@ import AuthenticationServices import Capacitor +import CoreLocation import LocalAuthentication import UIKit import WebKit @@ -23,6 +24,8 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr CAPPluginMethod(name: "biometryInfo", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "authenticateBiometric", returnType: CAPPluginReturnPromise), CAPPluginMethod(name: "setPrivacyCover", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "startLocation", returnType: CAPPluginReturnPromise), + CAPPluginMethod(name: "stopLocation", returnType: CAPPluginReturnPromise), ] /// What this binary offers the server's UI, raised with every native feature @@ -30,7 +33,30 @@ 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", "edgeBack", "tileCache", "biometricLock"] + static let features: [String] = ["capabilities", "edgeBack", "tileCache", "biometricLock", "geolocation"] + + // MARK: - Location + + /// One CoreLocation stream for the UI's navigator.geolocation (native/geolocation.ts). + /// The WebView's own asks for every server origin, and again and again; this + /// is the one system prompt the app's location string describes. + private lazy var location = TrekLocation { [weak self] payload in + self?.notifyListeners("location", data: payload) + } + + @objc func startLocation(_ call: CAPPluginCall) { + DispatchQueue.main.async { + self.location.start(highAccuracy: call.getBool("highAccuracy") ?? false) + call.resolve() + } + } + + @objc func stopLocation(_ call: CAPPluginCall) { + DispatchQueue.main.async { + self.location.stop() + call.resolve() + } + } // MARK: - App lock @@ -76,7 +102,7 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr /// How much the stored map tiles take on disk, for the offline settings. @objc func getTileCacheUsage(_ call: CAPPluginCall) { TrekTileStore.shared.usage { bytes in - call.resolve(["bytes": bytes, "limit": TrekTileStore.maxBytes]) + call.resolve(["bytes": Int(bytes), "limit": Int(TrekTileStore.maxBytes)]) } } @@ -217,3 +243,72 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr } } } + +/// Positions and errors for the UI, shaped like the Geolocation API's, with the +/// When-In-Use permission asked the first time. +final class TrekLocation: NSObject, CLLocationManagerDelegate { + private let manager = CLLocationManager() + private let emit: ([String: Any]) -> Void + private var running = false + + init(emit: @escaping ([String: Any]) -> Void) { + self.emit = emit + super.init() + manager.delegate = self + } + + func start(highAccuracy: Bool) { + manager.desiredAccuracy = highAccuracy ? kCLLocationAccuracyBest : kCLLocationAccuracyHundredMeters + running = true + switch manager.authorizationStatus { + case .notDetermined: + manager.requestWhenInUseAuthorization() + case .denied, .restricted: + emitError(code: 1, message: "Location permission denied") + default: + manager.startUpdatingLocation() + manager.startUpdatingHeading() + } + } + + func stop() { + running = false + manager.stopUpdatingLocation() + manager.stopUpdatingHeading() + } + + func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { + guard running else { return } + switch manager.authorizationStatus { + case .authorizedWhenInUse, .authorizedAlways: + manager.startUpdatingLocation() + manager.startUpdatingHeading() + case .denied, .restricted: + emitError(code: 1, message: "Location permission denied") + default: + break + } + } + + func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { + guard let last = locations.last else { return } + emit([ + "latitude": last.coordinate.latitude, + "longitude": last.coordinate.longitude, + "accuracy": last.horizontalAccuracy, + "altitude": last.verticalAccuracy >= 0 ? last.altitude as Any : NSNull(), + "speed": last.speed >= 0 ? last.speed as Any : NSNull(), + "heading": last.course >= 0 ? last.course as Any : NSNull(), + "timestamp": last.timestamp.timeIntervalSince1970 * 1000, + ]) + } + + func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { + let code = (error as? CLError)?.code == .denied ? 1 : 2 + emitError(code: code, message: error.localizedDescription) + } + + private func emitError(code: Int, message: String) { + emit(["error": ["code": code, "message": message]]) + } +} diff --git a/client/src/native/geolocation.test.ts b/client/src/native/geolocation.test.ts new file mode 100644 index 000000000..60c942717 --- /dev/null +++ b/client/src/native/geolocation.test.ts @@ -0,0 +1,79 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { hasNativeFeature } from './capabilities'; +import { _resetNativeGeolocation, installNativeGeolocation } from './geolocation'; +import { isNativeIos } from './platform'; +import { TrekShell, type NativeLocationPayload } from './trekShell'; + +vi.mock('./platform', () => ({ isNativeIos: vi.fn() })); +vi.mock('./capabilities', () => ({ hasNativeFeature: vi.fn() })); +vi.mock('./trekShell', () => ({ + TrekShell: { startLocation: vi.fn(), stopLocation: vi.fn(), addListener: vi.fn() }, +})); + +let emit: (payload: NativeLocationPayload) => void = () => {}; +const original = navigator.geolocation; + +beforeEach(() => { + _resetNativeGeolocation(); + Object.defineProperty(navigator, 'geolocation', { configurable: true, value: original }); + vi.mocked(isNativeIos).mockReturnValue(true); + vi.mocked(hasNativeFeature).mockReturnValue(true); + vi.mocked(TrekShell.startLocation).mockReset().mockResolvedValue(); + vi.mocked(TrekShell.stopLocation).mockReset().mockResolvedValue(); + vi.mocked(TrekShell.addListener) + .mockReset() + .mockImplementation(async (_event, listener) => { + emit = listener; + return { remove: async () => {} }; + }); +}); + +const FIX: NativeLocationPayload = { + latitude: 35.68, + longitude: 139.76, + accuracy: 12, + altitude: null, + speed: null, + heading: 90, + timestamp: 1000, +}; + +describe('native geolocation', () => { + it('answers navigator.geolocation from the app, and stops the stream when nobody listens', async () => { + expect(installNativeGeolocation()).toBe(true); + const seen: number[] = []; + const id = navigator.geolocation.watchPosition((p) => seen.push(p.coords.latitude), undefined, { + enableHighAccuracy: true, + }); + expect(TrekShell.startLocation).toHaveBeenCalledWith({ highAccuracy: true }); + await Promise.resolve(); + emit(FIX); + emit({ ...FIX, latitude: 35.7 }); + expect(seen).toEqual([35.68, 35.7]); + + navigator.geolocation.clearWatch(id); + expect(TrekShell.stopLocation).toHaveBeenCalledTimes(1); + }); + + it('settles a one-off request with the first fix, and passes a denial on as the Geolocation error', async () => { + installNativeGeolocation(); + const once = vi.fn(); + navigator.geolocation.getCurrentPosition(once); + await Promise.resolve(); + emit(FIX); + emit(FIX); + expect(once).toHaveBeenCalledTimes(1); + expect(TrekShell.stopLocation).toHaveBeenCalledTimes(1); + + const failed = vi.fn(); + navigator.geolocation.getCurrentPosition(vi.fn(), failed); + emit({ error: { code: 1, message: 'denied' } }); + expect(failed.mock.calls[0][0]).toMatchObject({ code: 1, PERMISSION_DENIED: 1 }); + }); + + it('leaves the browser API alone outside an iOS binary with the feature', () => { + vi.mocked(hasNativeFeature).mockReturnValue(false); + expect(installNativeGeolocation()).toBe(false); + expect(navigator.geolocation).toBe(original); + }); +}); diff --git a/client/src/native/geolocation.ts b/client/src/native/geolocation.ts new file mode 100644 index 000000000..05188c789 --- /dev/null +++ b/client/src/native/geolocation.ts @@ -0,0 +1,110 @@ +import { hasNativeFeature } from './capabilities'; +import { isNativeIos } from './platform'; +import { reportNativeFailure } from './reportFailure'; +import { TrekShell, type NativeLocationPayload } from './trekShell'; + +/** + * navigator.geolocation, answered by the iOS app's CoreLocation where the binary + * has the geolocation feature. + * + * WKWebView asks for the location per server origin, under the server's name, + * and asks again across launches. The app asks once, as the app. Installing the + * shim over navigator.geolocation keeps every caller as it is (the locate + * button, the tour tracking, the nearby search): one code path, the browser's + * API, with the app underneath. + */ +type Success = PositionCallback; +type Failure = PositionErrorCallback | null | undefined; + +interface Watcher { + success: Success; + failure: Failure; + once: boolean; +} + +const watchers = new Map(); +let nextId = 1; +let running = false; +let highAccuracy = false; +let subscribed: Promise | null = null; + +function toPosition(p: Extract): GeolocationPosition { + const coords = { + latitude: p.latitude, + longitude: p.longitude, + accuracy: p.accuracy, + altitude: p.altitude, + altitudeAccuracy: null, + heading: p.heading, + speed: p.speed, + toJSON() { + return { ...this }; + }, + }; + return { coords, timestamp: p.timestamp, toJSON: () => ({ coords, timestamp: p.timestamp }) } as GeolocationPosition; +} + +function toError(e: { code: number; message: string }): GeolocationPositionError { + return { + code: e.code, + message: e.message, + PERMISSION_DENIED: 1, + POSITION_UNAVAILABLE: 2, + TIMEOUT: 3, + } as GeolocationPositionError; +} + +function dispatch(payload: NativeLocationPayload): void { + for (const [id, w] of [...watchers]) { + if (payload.error) w.failure?.(toError(payload.error)); + else w.success(toPosition(payload)); + if (w.once) watchers.delete(id); + } + syncStream(); +} + +/** Runs the native stream while anyone listens, at the accuracy the most demanding asked for. */ +function syncStream(): void { + if (watchers.size > 0 && !running) { + running = true; + subscribed ??= TrekShell.addListener('location', dispatch); + TrekShell.startLocation({ highAccuracy }).catch(reportNativeFailure); + } else if (watchers.size === 0 && running) { + running = false; + TrekShell.stopLocation().catch(reportNativeFailure); + } +} + +function add(success: Success, failure: Failure, options: PositionOptions | undefined, once: boolean): number { + if (options?.enableHighAccuracy) highAccuracy = true; + const id = nextId++; + watchers.set(id, { success, failure, once }); + syncStream(); + return id; +} + +/** Puts the app's location under navigator.geolocation. Once, inside a binary that has it. */ +export function installNativeGeolocation(): boolean { + if (!isNativeIos() || !hasNativeFeature('geolocation') || typeof navigator === 'undefined') return false; + const shim: Geolocation = { + getCurrentPosition: (success, failure, options) => { + add(success, failure, options, true); + }, + watchPosition: (success, failure, options) => add(success, failure, options, false), + clearWatch: (id) => { + watchers.delete(id); + syncStream(); + }, + }; + Object.defineProperty(navigator, 'geolocation', { configurable: true, value: shim }); + return true; +} + +/** Test helper. */ +export function _resetNativeGeolocation(): void { + watchers.clear(); + running = false; + highAccuracy = false; + subscribed = null; + nextId = 1; +} diff --git a/client/src/native/nativeApp.test.ts b/client/src/native/nativeApp.test.ts index 3d1afb3b7..ba0cae970 100644 --- a/client/src/native/nativeApp.test.ts +++ b/client/src/native/nativeApp.test.ts @@ -6,7 +6,8 @@ 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'; +import { installNativeGeolocation } from './geolocation'; +import { scrollToTop, startNativeApp } from './nativeApp'; import { keepOfflineShellFresh } from './offlineShell'; import { isNativeApp, isNativeIos } from './platform'; @@ -17,7 +18,11 @@ vi.mock('@capacitor/status-bar', () => ({ StatusBar: { setStyle: vi.fn() }, Styl 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('./capabilities', () => ({ + checkAppUpdate: vi.fn(async () => false), + loadNativeCapabilities: vi.fn(async () => ({})), +})); +vi.mock('./geolocation', () => ({ installNativeGeolocation: vi.fn() })); vi.mock('../mobile/overlayStack', () => ({ closeTopOverlay: vi.fn(() => false) })); function backButtonHandler(): (event: { canGoBack: boolean }) => void { @@ -59,6 +64,24 @@ describe('startNativeApp', () => { back.mockRestore(); }); + it('puts the app location under navigator.geolocation once the binary has answered', async () => { + vi.useRealTimers(); + startNativeApp(); + await vi.waitFor(() => expect(installNativeGeolocation).toHaveBeenCalled()); + }); + + it('a status bar tap scrolls the list in the middle of the screen back to the top', () => { + const list = document.createElement('div'); + list.style.overflowY = 'auto'; + Object.defineProperty(list, 'scrollTop', { configurable: true, value: 300 }); + list.scrollTo = vi.fn(); + document.body.appendChild(list); + document.elementFromPoint = vi.fn(() => list); + scrollToTop(); + expect(list.scrollTo).toHaveBeenCalledWith({ top: 0, behavior: 'smooth' }); + list.remove(); + }); + 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 c77333dba..efe7feff8 100644 --- a/client/src/native/nativeApp.ts +++ b/client/src/native/nativeApp.ts @@ -4,7 +4,8 @@ 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 { checkAppUpdate, loadNativeCapabilities } from './capabilities'; +import { installNativeGeolocation } from './geolocation'; import { keepOfflineShellFresh } from './offlineShell'; import { isNativeApp, isNativeIos } from './platform'; import { reportNativeFailure } from './reportFailure'; @@ -24,6 +25,12 @@ export function startNativeApp(): void { // What this binary can do, and whether this server's UI needs a newer one. void checkAppUpdate(fetchServerFeatures); + // The app's own location under navigator.geolocation, where the binary has it. + void loadNativeCapabilities().then(() => installNativeGeolocation()); + + // A tap on the status bar scrolls the list under it back to the top, as in + // every iOS app (the status-bar plugin fires statusTap on iOS). + window.addEventListener('statusTap', scrollToTop); // 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. @@ -72,3 +79,17 @@ async function fetchServerFeatures(): Promise<{ minNativeShellApi?: unknown }> { if (!res.ok) return {}; return (await res.json()) as { minNativeShellApi?: unknown }; } + +/** The scrolled list in the middle of the screen, else the page, back to its top. */ +export function scrollToTop(): void { + let el = document.elementFromPoint(window.innerWidth / 2, window.innerHeight / 2) as HTMLElement | null; + while (el && el !== document.body) { + const overflow = getComputedStyle(el).overflowY; + if ((overflow === 'auto' || overflow === 'scroll') && el.scrollTop > 0) { + el.scrollTo({ top: 0, behavior: 'smooth' }); + return; + } + el = el.parentElement; + } + window.scrollTo({ top: 0, behavior: 'smooth' }); +} diff --git a/client/src/native/trekShell.ts b/client/src/native/trekShell.ts index e1df837a3..afe9c0ad9 100644 --- a/client/src/native/trekShell.ts +++ b/client/src/native/trekShell.ts @@ -42,8 +42,29 @@ export interface TrekShellPlugin { authenticateBiometric(options: { reason: string }): Promise<{ ok: true }>; /** Feature biometricLock: a blurred cover in the app switcher while the lock is on. */ setPrivacyCover(options: { enabled: boolean }): Promise; + /** iOS, feature geolocation: starts the native location stream (the "location" event). */ + startLocation(options: { highAccuracy: boolean }): Promise; + stopLocation(): Promise; + addListener( + event: 'location', + listener: (payload: NativeLocationPayload) => void + ): Promise<{ remove: () => Promise }>; } +/** A position, or an error shaped like GeolocationPositionError (1 denied, 2 unavailable). */ +export type NativeLocationPayload = + | { + latitude: number; + longitude: number; + accuracy: number; + altitude: number | null; + speed: number | null; + heading: number | null; + timestamp: number; + error?: undefined; + } + | { error: { code: number; message: string } }; + export const TrekShell = registerPlugin('TrekShell'); export const APP_URL_SCHEME = 'com.liketrek.trek';