diff --git a/README.md b/README.md index ce833bfe..6ff97623 100644 --- a/README.md +++ b/README.md @@ -311,8 +311,10 @@ axis shows more than the region asks for. Durations are in milliseconds, for `animateCamera` and `animateToRegion` alike, as in react-native-maps. Both default to `250`, and `0` moves the camera -without animating. Up to 1.2.1 `animateCamera` took seconds, so multiply a -duration passed to it by 1000 when upgrading. +without animating, as does a negative duration or one that is not a finite +number. Releases up to and including 1.2.1 take `animateCamera` durations in +seconds; 2.0.0 is the first release that takes milliseconds, so multiply a +duration passed to it by 1000 when upgrading from 1.2.1 or earlier. #### When the ref is usable @@ -367,8 +369,10 @@ read `getVisibleRegion()` or `getCamera()` after the `await` when that matters. (On Apple Maps a gesture cannot cut `animateCamera` or `animateToRegion` short: the map ignores touches until the animation ends.) -Pass `fitToCoordinates`' `animated` argument explicitly: left out, iOS animates -the fit and Android jumps to it. +`fitToCoordinates` animates unless `animated` is `false`, on every provider. + +> **Behavior change in 2.0.0:** on Android, `fitToCoordinates` without +> `animated` used to jump to the fit. It now animates, as on iOS. > **Behavior change after 1.2.1:** these promises used to resolve as soon as the > animation started, so `await` returned with the camera still at its old position. diff --git a/example/App.tsx b/example/App.tsx index 074f7562..98fb20fd 100644 --- a/example/App.tsx +++ b/example/App.tsx @@ -53,6 +53,7 @@ import { import { APPLE_POI_DETAILS_DEFAULT_PRESENTATION, APPLE_POI_DETAILS_SCENARIO_ID, + CAMERA_TIMING_SCENARIO_ID, MAP_SCENARIOS, type MapScenario, createApplePoiDetailsScenario, @@ -63,6 +64,7 @@ import { } from './examples'; const MAP_TYPES: MapType[] = ['standard', 'satellite', 'hybrid']; +const CAMERA_TIMING_DURATIONS = [250, 2000]; type SupportedExampleProvider = Extract; type AnimationOptionId = 'system' | 'fade' | 'fade-scale' | 'none'; @@ -318,6 +320,8 @@ type ScenarioDockProps = { onCycleCustomMarkerRotation: () => void; onToggleCustomMarkerFlat: () => void; onCycleApplePoiDetailMode: () => void; + onTimeAnimateCamera: (duration: number) => void; + onTimeDefaultFit: () => void; }; const ScenarioDock = memo(function ScenarioDock({ @@ -341,6 +345,8 @@ const ScenarioDock = memo(function ScenarioDock({ onCycleCustomMarkerRotation, onToggleCustomMarkerFlat, onCycleApplePoiDetailMode, + onTimeAnimateCamera, + onTimeDefaultFit, }: ScenarioDockProps) { const applePoiDetailPresentation = scenario.advanced?.applePoiDetailPresentation; @@ -483,6 +489,28 @@ const ScenarioDock = memo(function ScenarioDock({ ) : null} + {scenario.id === CAMERA_TIMING_SCENARIO_ID ? ( + + {CAMERA_TIMING_DURATIONS.map((duration) => ( + onTimeAnimateCamera(duration)} + style={styles.actionButton} + > + ↻ + {duration} ms + + ))} + + ⤢ + Fit + + + ) : null} + {applePoiDetailPresentation != null ? ( {}); }, [scenario]); + // A timing promise settles after the scene changed when the old map is + // released; its result belongs to that scene, not the one on screen. + const sceneKey = mapSceneKey(scenario, animationOption, provider); + const sceneKeyRef = useRef(sceneKey); + useEffect(() => { + sceneKeyRef.current = sceneKey; + }, [sceneKey]); + const timeCameraPromise = useCallback( + (label: string, move: () => Promise | undefined) => { + const startedIn = sceneKeyRef.current; + const startedAt = Date.now(); + const report = (result: string) => { + if (sceneKeyRef.current === startedIn) { + setStatus(`${label} · ${result}`); + } + }; + move() + ?.then(() => report(`${Date.now() - startedAt} ms`)) + .catch((error: unknown) => report(String(error))); + }, + [], + ); + + const handleTimeAnimateCamera = useCallback( + async (duration: number) => { + // Zoom away from wherever the camera is, so every press moves the map + // and no other button can turn it into a no-op. + const map = mapRef.current; + const startedIn = sceneKeyRef.current; + if (map == null) { + return; + } + let camera; + try { + camera = await map.getCamera(); + } catch { + return; + } + // The scene may have changed while the camera was read; the replacement + // map must not be moved to the old scenario. + if (mapRef.current !== map || sceneKeyRef.current !== startedIn) { + return; + } + timeCameraPromise(`animateCamera ${duration} ms`, () => + map.animateCamera( + { + center: { + latitude: scenario.region.latitude, + longitude: scenario.region.longitude, + }, + zoom: (camera.zoom ?? 0) >= 11 ? 9 : 13, + heading: 0, + pitch: 0, + }, + duration, + ), + ); + }, + [scenario, timeCameraPromise], + ); + + const handleTimeDefaultFit = useCallback(() => { + // No `animated` argument: the call under test is the default. + timeCameraPromise('fitToCoordinates', () => + mapRef.current?.fitToCoordinates( + (scenario.markers ?? []).map((marker) => marker.coordinate), + mapPadding, + ), + ); + }, [scenario, mapPadding, timeCameraPromise]); + const handleGetCamera = useCallback(async () => { try { const camera = await mapRef.current?.getCamera(); @@ -968,25 +1067,32 @@ export default function App() { ); }, []); + // The camera timing results are the point of that scenario; do not bury them. + const reportsRegionChanges = scenario.id !== CAMERA_TIMING_SCENARIO_ID; + const handleRegionChange = useCallback( (region: Region, details: RegionChangeDetails) => { - setStatus(`Region start · ${regionLabel(region, details)}`); + if (reportsRegionChanges) { + setStatus(`Region start · ${regionLabel(region, details)}`); + } }, - [], + [reportsRegionChanges], ); const handleRegionChangeComplete = useCallback( (region: Region, details: RegionChangeDetails) => { - setStatus(`Region complete · ${regionLabel(region, details)}`); + if (reportsRegionChanges) { + setStatus(`Region complete · ${regionLabel(region, details)}`); + } }, - [], + [reportsRegionChanges], ); return ( diff --git a/example/examples/cameraTiming.ts b/example/examples/cameraTiming.ts new file mode 100644 index 00000000..26f45402 --- /dev/null +++ b/example/examples/cameraTiming.ts @@ -0,0 +1,38 @@ +import type { MapScenario } from './types'; + +export const CAMERA_TIMING_SCENARIO_ID = 'camera-timing'; + +/** + * Buttons for `animateCamera` at 250 ms and 2000 ms and for `fitToCoordinates` + * without `animated`, so iOS and Android can be compared side by side. The + * status header reports how long each promise took to settle. + */ +export const cameraTimingScenario: MapScenario = { + id: CAMERA_TIMING_SCENARIO_ID, + name: 'Camera timing', + description: + 'animateCamera at 250 ms and 2000 ms, and fitToCoordinates without animated', + region: { + latitude: 52.2297, + longitude: 21.0122, + latitudeDelta: 0.06, + longitudeDelta: 0.06, + }, + markers: [ + { + id: 'gdansk', + coordinate: { latitude: 54.352, longitude: 18.6466 }, + title: 'Gdańsk', + }, + { + id: 'szczecin', + coordinate: { latitude: 53.4285, longitude: 14.5528 }, + title: 'Szczecin', + }, + { + id: 'rzeszow', + coordinate: { latitude: 50.0413, longitude: 21.999 }, + title: 'Rzeszów', + }, + ], +}; diff --git a/example/examples/index.ts b/example/examples/index.ts index 805827a8..28222883 100644 --- a/example/examples/index.ts +++ b/example/examples/index.ts @@ -1,5 +1,9 @@ import { advancedFeaturesScenario } from './advancedFeatures'; import { allOverlaysScenario } from './allOverlays'; +import { + CAMERA_TIMING_SCENARIO_ID, + cameraTimingScenario, +} from './cameraTiming'; import { APPLE_POI_DETAILS_DEFAULT_PRESENTATION, APPLE_POI_DETAILS_SCENARIO_ID, @@ -24,6 +28,7 @@ export type { MapScenario } from './types'; export { APPLE_POI_DETAILS_DEFAULT_PRESENTATION, APPLE_POI_DETAILS_SCENARIO_ID, + CAMERA_TIMING_SCENARIO_ID, createApplePoiDetailsScenario, createCustomMarkerImagesScenario, createScenarioOverlayProps, @@ -41,4 +46,5 @@ export const MAP_SCENARIOS: MapScenario[] = [ advancedFeaturesScenario, applePoiDetailsScenario, mountEffectCameraScenario, + cameraTimingScenario, ]; diff --git a/package/android/src/main/java/com/margelo/nitro/nitromaps/CameraAnimationDuration.kt b/package/android/src/main/java/com/margelo/nitro/nitromaps/CameraAnimationDuration.kt index bece3a56..daa6834f 100644 --- a/package/android/src/main/java/com/margelo/nitro/nitromaps/CameraAnimationDuration.kt +++ b/package/android/src/main/java/com/margelo/nitro/nitromaps/CameraAnimationDuration.kt @@ -5,7 +5,11 @@ internal const val DEFAULT_CAMERA_ANIMATION_DURATION_MS = 250.0 /** * The duration `MapViewRef` passes, in milliseconds, as the whole number the SDK takes. Anything - * under one millisecond - 0, a negative value or `NaN` - comes back as 0 or less, which callers - * treat as a jump: `GoogleMap.animateCamera` throws for a duration that is not positive. + * under one millisecond - 0, a negative value or `NaN` - and infinity come back as 0 or less, + * which callers treat as a jump: `GoogleMap.animateCamera` throws for a duration that is not + * positive. The Swift `cameraAnimationSeconds(fromMilliseconds:)` does the same for iOS. */ -internal fun cameraAnimationDurationMs(duration: Double?): Int = (duration ?: DEFAULT_CAMERA_ANIMATION_DURATION_MS).toInt() +internal fun cameraAnimationDurationMs(duration: Double?): Int { + val durationMs = duration ?: DEFAULT_CAMERA_ANIMATION_DURATION_MS + return if (durationMs.isFinite()) durationMs.toInt() else 0 +} diff --git a/package/android/src/main/java/com/margelo/nitro/nitromaps/GoogleMapProviderAdapter.kt b/package/android/src/main/java/com/margelo/nitro/nitromaps/GoogleMapProviderAdapter.kt index f106b08c..8c8e5da9 100644 --- a/package/android/src/main/java/com/margelo/nitro/nitromaps/GoogleMapProviderAdapter.kt +++ b/package/android/src/main/java/com/margelo/nitro/nitromaps/GoogleMapProviderAdapter.kt @@ -417,7 +417,7 @@ class GoogleMapProviderAdapter( view.height, ) ?: bounds val update = CameraUpdateFactory.newLatLngBounds(target, 0) - if (animated == true) { + if (animated ?: true) { map.animateCamera(update, cameraAnimations.callback(onEnd)) } else { map.moveCamera(update) diff --git a/package/android/src/test/java/com/margelo/nitro/nitromaps/CameraAnimationDurationTest.kt b/package/android/src/test/java/com/margelo/nitro/nitromaps/CameraAnimationDurationTest.kt index 9d0f106b..7dee38b5 100644 --- a/package/android/src/test/java/com/margelo/nitro/nitromaps/CameraAnimationDurationTest.kt +++ b/package/android/src/test/java/com/margelo/nitro/nitromaps/CameraAnimationDurationTest.kt @@ -23,4 +23,10 @@ class CameraAnimationDurationTest { assertEquals(0, cameraAnimationDurationMs(Double.NaN)) assertTrue(cameraAnimationDurationMs(-100.0) <= 0) } + + @Test + fun jumpsForAnInfiniteDuration() { + assertEquals(0, cameraAnimationDurationMs(Double.POSITIVE_INFINITY)) + assertEquals(0, cameraAnimationDurationMs(Double.NEGATIVE_INFINITY)) + } } diff --git a/package/ios/AppleMapProviderAdapter.swift b/package/ios/AppleMapProviderAdapter.swift index ccc31cd7..72d7496c 100644 --- a/package/ios/AppleMapProviderAdapter.swift +++ b/package/ios/AppleMapProviderAdapter.swift @@ -6,7 +6,6 @@ final class AppleMapProviderAdapter: MapProviderAdapter { /// MapKit animates `setVisibleMapRect` over a duration it does not publish. This is /// only the watchdog's guess at it, not a duration handed to MapKit. private static let fitAnimationDuration: TimeInterval = 0.3 - private static let defaultAnimationDuration: TimeInterval = 0.25 private let mapViewDelegate = HybridMapViewDelegate() private let cameraMoves = CameraMoveTracker() @@ -246,16 +245,15 @@ final class AppleMapProviderAdapter: MapProviderAdapter { return Promise.resolved() } - func animateCamera(camera: Camera, duration: TimeInterval?) throws -> Promise { - let animationDuration = duration ?? Self.defaultAnimationDuration + func animateCamera(camera: Camera, duration: TimeInterval) throws -> Promise { let promise = Promise() - trackAnimation(settling: promise, duration: animationDuration) { completion in - updateMapCamera(camera, animated: true, duration: animationDuration, completion: completion) + trackAnimation(settling: promise, duration: duration) { completion in + updateMapCamera(camera, animated: true, duration: duration, completion: completion) } return promise } - func animateToRegion(region: Region, duration: TimeInterval?) throws -> Promise { + func animateToRegion(region: Region, duration: TimeInterval) throws -> Promise { // `setRegion` raises an NSException Swift cannot catch - see `applyRegion`. guard region.isValid else { return Promise.resolved() @@ -267,17 +265,16 @@ final class AppleMapProviderAdapter: MapProviderAdapter { // honours the animation's duration at any distance, so the region goes in // as the camera `setRegion` would pick for it - which takes a map with a // size. - let animationDuration = duration ?? Self.defaultAnimationDuration let promise = Promise() whenLaidOut(rejecting: promise) { [weak self] in guard let self else { return } - self.trackAnimation(settling: promise, duration: animationDuration) { completion in + self.trackAnimation(settling: promise, duration: duration) { completion in self.moveMapCamera( to: self.view.camera(framing: region.toMKCoordinateRegion()), animated: true, - duration: animationDuration, + duration: duration, completion: completion ) } diff --git a/package/ios/Camera/CameraAnimationDuration.swift b/package/ios/Camera/CameraAnimationDuration.swift new file mode 100644 index 00000000..4561e272 --- /dev/null +++ b/package/ios/Camera/CameraAnimationDuration.swift @@ -0,0 +1,16 @@ +import Foundation + +/// The duration a camera animation takes when the caller passes none, in milliseconds. +let defaultCameraAnimationDurationMilliseconds: Double = 250 + +/// The duration `MapViewRef` passes, in milliseconds, as the seconds UIKit and Core +/// Animation take. Anything that is not a finite number greater than 0 - a negative +/// value, `NaN` or infinity - comes back as 0, which the adapters treat as a jump. The +/// Kotlin `cameraAnimationDurationMs` gives Android the same default. +func cameraAnimationSeconds(fromMilliseconds milliseconds: Double?) -> TimeInterval { + let milliseconds = milliseconds ?? defaultCameraAnimationDurationMilliseconds + guard milliseconds.isFinite, milliseconds > 0 else { + return 0 + } + return milliseconds / 1000 +} diff --git a/package/ios/GoogleMapProviderAdapter.swift b/package/ios/GoogleMapProviderAdapter.swift index 2fd8b189..18c2a133 100644 --- a/package/ios/GoogleMapProviderAdapter.swift +++ b/package/ios/GoogleMapProviderAdapter.swift @@ -260,24 +260,22 @@ final class GoogleMapProviderAdapter: NSObject, MapProviderAdapter { return Promise.resolved() } - func animateCamera(camera: Camera, duration: TimeInterval?) throws -> Promise { - let animationDuration = duration ?? Self.defaultAnimationDuration - let animated = animationDuration > 0 - guard updateMapCamera(camera, animated: animated, duration: animationDuration), animated else { + func animateCamera(camera: Camera, duration: TimeInterval) throws -> Promise { + let animated = duration > 0 + guard updateMapCamera(camera, animated: animated, duration: duration), animated else { return Promise.resolved() } - return trackCameraMove(duration: animationDuration) + return trackCameraMove(duration: duration) } - func animateToRegion(region: Region, duration: TimeInterval?) throws -> Promise { - let animationDuration = duration ?? Self.defaultAnimationDuration - let animated = animationDuration > 0 - guard applyRegion(region, animated: animated, duration: animationDuration), animated else { + func animateToRegion(region: Region, duration: TimeInterval) throws -> Promise { + let animated = duration > 0 + guard applyRegion(region, animated: animated, duration: duration), animated else { return Promise.resolved() } - return trackCameraMove(duration: animationDuration) + return trackCameraMove(duration: duration) } func getVisibleRegion() throws -> Promise { diff --git a/package/ios/HybridMapView.swift b/package/ios/HybridMapView.swift index 6232bae1..ebfa5e71 100644 --- a/package/ios/HybridMapView.swift +++ b/package/ios/HybridMapView.swift @@ -246,15 +246,14 @@ final class HybridMapView: HybridMapViewSpec { } func animateCamera(camera: Camera, duration: Double?) throws -> Promise { - // Milliseconds from JS, seconds for UIKit and Core Animation. - let seconds = duration.map { $0 / 1000 } + let seconds = cameraAnimationSeconds(fromMilliseconds: duration) return promiseOnMain { try $0.animateCamera(camera: camera, duration: seconds) } } func animateToRegion(region: Region, duration: Double?) throws -> Promise { - let seconds = duration.map { $0 / 1000 } + let seconds = cameraAnimationSeconds(fromMilliseconds: duration) return promiseOnMain { try $0.animateToRegion(region: region, duration: seconds) } diff --git a/package/ios/MapProviderAdapter.swift b/package/ios/MapProviderAdapter.swift index d9d85d3c..89e21f01 100644 --- a/package/ios/MapProviderAdapter.swift +++ b/package/ios/MapProviderAdapter.swift @@ -49,14 +49,14 @@ protocol MapProviderAdapter: AnyObject { /// cuts it short. func applyCamera(camera: Camera) throws -> Promise - /// `duration` is in seconds, here and in `animateToRegion`: `HybridMapView` - /// converts the milliseconds JS passes. + /// `duration` is in seconds, here and in `animateToRegion`, and 0 for a jump: + /// `HybridMapView` converts the milliseconds JS passes and fills in the default. /// /// - SeeAlso: ``applyCamera(camera:)`` for when the Promise settles. - func animateCamera(camera: Camera, duration: TimeInterval?) throws -> Promise + func animateCamera(camera: Camera, duration: TimeInterval) throws -> Promise /// - SeeAlso: ``applyCamera(camera:)`` for when the Promise settles. - func animateToRegion(region: Region, duration: TimeInterval?) throws -> Promise + func animateToRegion(region: Region, duration: TimeInterval) throws -> Promise func getVisibleRegion() throws -> Promise @@ -147,11 +147,11 @@ final class UnavailableMapProviderAdapter: MapProviderAdapter { throw error } - func animateCamera(camera: Camera, duration: TimeInterval?) throws -> Promise { + func animateCamera(camera: Camera, duration: TimeInterval) throws -> Promise { throw error } - func animateToRegion(region: Region, duration: TimeInterval?) throws -> Promise { + func animateToRegion(region: Region, duration: TimeInterval) throws -> Promise { throw error } diff --git a/package/ios/Tests/Camera/CameraAnimationDurationTests.swift b/package/ios/Tests/Camera/CameraAnimationDurationTests.swift new file mode 100644 index 00000000..2fe45b6f --- /dev/null +++ b/package/ios/Tests/Camera/CameraAnimationDurationTests.swift @@ -0,0 +1,26 @@ +import Testing + +@testable import NitroMapsCamera + +/// The Kotlin `CameraAnimationDurationTest` covers the same cases for Android. +@Test +func aMissingDurationTakesAQuarterOfASecond() { + #expect(cameraAnimationSeconds(fromMilliseconds: nil) == 0.25) +} + +@Test +func millisecondsBecomeSeconds() { + #expect(cameraAnimationSeconds(fromMilliseconds: 1000) == 1) + #expect(cameraAnimationSeconds(fromMilliseconds: 2000) == 2) + #expect(cameraAnimationSeconds(fromMilliseconds: 1) == 0.001) +} + +@Test +func zeroStaysAJump() { + #expect(cameraAnimationSeconds(fromMilliseconds: 0) == 0) +} + +@Test(arguments: [-1, -100, Double.nan, Double.infinity, -Double.infinity]) +func aDurationThatIsNotAFinitePositiveNumberIsAJump(milliseconds: Double) { + #expect(cameraAnimationSeconds(fromMilliseconds: milliseconds) == 0) +} diff --git a/package/src/types/ref.ts b/package/src/types/ref.ts index 57cf5aa3..ddc73334 100644 --- a/package/src/types/ref.ts +++ b/package/src/types/ref.ts @@ -54,7 +54,8 @@ export interface MapViewRef { * {@linkcode MapViewRef.setCamera} does. * * @param duration Animation duration in milliseconds. Defaults to `250`; - * `0` moves the camera without animating. + * `0`, a negative value or one that is not finite moves the camera without + * animating. */ animateCamera(camera: Camera, duration?: number): Promise; @@ -70,7 +71,8 @@ export interface MapViewRef { * not a finite number greater than 0. * * @param duration Animation duration in milliseconds. Defaults to `250`; - * `0` moves the camera without animating. + * `0`, a negative value or one that is not finite moves the camera without + * animating. */ animateToRegion(region: Region, duration?: number): Promise; @@ -84,7 +86,8 @@ export interface MapViewRef { * * {@linkcode padding} is added on top of {@linkcode MapViewProps.mapPadding}. * - * @param animated Pass it explicitly: omitted, iOS animates and Android jumps. + * @param animated Defaults to `true`; `false` moves the camera without + * animating. */ fitToCoordinates( coordinates: Coordinate[],