Repository navigation
fix: send the current camera when onCameraChanged is registered - #4430
Conversation
mfazekas
left a comment
There was a problem hiding this comment.
Thanks, this reproduces cleanly. On main (iOS sim, RN 0.84.1, new arch), attaching onCameraChanged after the map settled gave no event until the camera moved, and with 3 s of JS busy work during mount 10 of 10 runs got no camera at all. With this PR the late attach gets exactly one event with the current camera (zoom 12.00, isGestureActive: false, same payload keys as a normal event). The busy mount gets exactly one event in 10 of 10 runs. Five re-renders with an inline callback send nothing extra, normal camera changes are unaffected, and with onRegionIsChanging registered no one-shot is sent.
A few requests before merging:
- Please move the event construction into a small helper (e.g.
sendCameraChanged()) and use it from bothapplyOnMapChangeand here, so the one-shot can't drift from the regularcameraChangedpayload. withMapViewdoesn't wait here:RNMBXMapViewModule.setHandledMapChangedEventsalready rejects when the view has no map, and it runs on the main thread with_mapViewset, so the callback always runs synchronously. Either call it directly or keepwithMapViewas a guard, but the "waits for the map view" part of the description isn't accurate.- The comment can be one sentence, e.g.
// Camera changes before JS registers for them are never sent, so send the current camera when it first does.The "as applyOnMapChange would" part goes away with the helper. - Android parity: the late-attach case has the same gap there (
setHandledMapChangedEventsonly stores the set). I'd prefer both platforms in this PR, since the change is small. Treat the initialnullset as already containingCAMERA_CHANGED, so the first registration doesn't resend the startup camera, which Android already delivers. Then emithandleMapChangedEvent(CAMERA_CHANGED)when it is newly added andREGION_IS_CHANGINGisn't registered.
Reproducer used (Late / Busy / Late+Region, Attach, Detach, Re-render x5, setCamera)
import React, { useLayoutEffect, useRef, useState } from 'react';
import { Button, Text, View } from 'react-native';
import { Camera, MapView } from '@rnmapbox/maps';
// Repro for rnmapbox/maps#4430: onCameraChanged gets no camera when it is registered after the
// start camera. The map is never touched unless "setCamera" is pressed.
const START = { centerCoordinate: [-74.00597, 40.71427], zoomLevel: 12 };
const BusyOnMount = () => {
// Delays MapView.componentDidMount (which registers the handled events) by 3 s of JS busy work.
useLayoutEffect(() => {
const end = Date.now() + 3000;
while (Date.now() < end) {}
}, []);
return null;
};
const fmt = (s) =>
s
? `z ${s.properties.zoom.toFixed(2)} c ${s.properties.center
.map((v) => v.toFixed(3))
.join(',')} gest ${s.gestures?.isGestureActive}`
: '-';
const Repro = ({ mode, onRegion }) => {
const t0 = useRef(Date.now());
const camera = useRef(null);
const [listening, setListening] = useState(mode === 'busy');
const [, setTick] = useState(0);
const [cam, setCam] = useState({ calls: 0, first: null, last: null, firstAt: 0 });
const [region, setRegion] = useState(0);
const [idle, setIdle] = useState(null);
const log = (kind, payload) =>
console.log(`[R4430] ${mode} +${Date.now() - t0.current}ms ${kind} ${JSON.stringify(payload)}`);
return (
<View style={{ flex: 1 }}>
<MapView
style={{ flex: 1 }}
// inline on purpose: a new function every render, so MapView re-registers events each render
onCameraChanged={
listening
? (s) => {
log('onCameraChanged', s);
setCam((c) => ({
calls: c.calls + 1,
first: c.first ?? s,
firstAt: c.first ? c.firstAt : Date.now() - t0.current,
last: s,
}));
}
: undefined
}
onRegionIsChanging={
onRegion
? (f) => {
log('onRegionIsChanging', f.properties);
setRegion((n) => n + 1);
}
: undefined
}
onMapIdle={(s) => {
log('onMapIdle', s);
setIdle(s);
}}
>
<Camera ref={camera} defaultSettings={START} />
{mode === 'busy' && <BusyOnMount />}
</MapView>
{/* fixed height: a map resize would itself be a camera change */}
<View style={{ height: 170 }}>
<Text testID="r-cam">{`${mode} listening=${listening} calls=${cam.calls} first@+${cam.firstAt}ms`}</Text>
<Text testID="r-first">{`first: ${fmt(cam.first)}`}</Text>
<Text testID="r-last">{`last: ${fmt(cam.last)}`}</Text>
<Text testID="r-idle">{`idle: ${fmt(idle)} region=${region}`}</Text>
<View style={{ flexDirection: 'row', flexWrap: 'wrap' }}>
<Button testID="r-attach" title="Attach" onPress={() => setListening(true)} />
<Button testID="r-detach" title="Detach" onPress={() => setListening(false)} />
<Button testID="r-rerender" title="Re-render x5" onPress={() => [1, 2, 3, 4, 5].forEach((i) => setTimeout(() => setTick((n) => n + 1), i * 100))} />
<Button testID="r-move" title="setCamera z14" onPress={() => camera.current?.setCamera({ zoomLevel: 14, animationDuration: 0 })} />
</View>
</View>
</View>
);
};
const CameraOnRegisterRepro = () => {
const [run, setRun] = useState({ key: 0, mode: 'late', onRegion: false });
const start = (mode, onRegion = false) => setRun((r) => ({ key: r.key + 1, mode, onRegion }));
return (
<View style={{ flex: 1 }}>
<View style={{ flexDirection: 'row', flexWrap: 'wrap', paddingTop: 4 }}>
<Button testID="r-late" title="Late" onPress={() => start('late')} />
<Button testID="r-busy" title="Busy" onPress={() => start('busy')} />
<Button testID="r-late-region" title="Late+Region" onPress={() => start('late', true)} />
</View>
<Repro key={run.key} mode={run.mode} onRegion={run.onRegion} />
</View>
);
};
export default CameraOnRegisterRepro;|
Pushed ec0dd93 (same base as before; merged with
Your reproducer in the example app (
Android emulator (API 33); iOS 26.5 simulator, with the same steps run by timers instead of taps. The iOS busy run with 2 calls is the case from the description: the registration came before the start camera, so the one-shot carried the map's first camera (zoom 0.32) and the start camera (zoom 12.00) followed as a normal change.
|
mfazekas
left a comment
There was a problem hiding this comment.
Thanks, all four points are addressed. Re-tested ec0dd93 on the iOS simulator and the Android emulator with the reproducer from the review. Late attach now gets exactly one event with the current camera on both platforms, the busy mount gets one in 10 of 10 runs, and Android doesn't resend the startup camera. Re-renders, normal camera changes and onRegionIsChanging behave as before.
Description
MapViewsends camera changes to JS only after JS has asked for them (setHandledMapChangedEvents, whichMapViewcalls fromcomponentDidMountand again when a callback prop changes). A camera change before that is never sent, and nothing sends the camera afterwards. So when JS asks late,onCameraChangedgets no camera until the map moves:componentDidMount(timing-dependent; we hit it every time in our app's map screen, which mounts many layers);onCameraChangedis set after the map has settled (always).onMapIdlestill reports the right camera, so an app that keeps the camera fromonCameraChangeddisagrees with the map until the user touches it.This PR: when
cameraChangedis newly in the handled set, send the current camera once (not whenregionIsChangingis registered, which takes precedence on iOS). Registering the same set again (MapViewdoes that on every render with an inline callback) sends nothing.sendCameraChanged()builds the event for bothapplyOnMapChangeand the one-shot.null, which sends every event, so the first registration counts as already havingCAMERA_CHANGEDand does not send the startup camera again.Checklist
CONTRIBUTING.mdyarn generatein the root folder (no changes)/exampleapp./example)Screenshot OR Video
The reproducer from the review in the example app (
mainat bd1dd98, React Native 0.84.1, New Architecture),onCameraChangedcalls:mainAndroid emulator (API 33); iOS 26.5 simulator, the same steps run by timers instead of taps. In the iOS busy run with 2 calls the registration came before the start camera: the one-shot carried the map's first camera (zoom 0.32) and the start camera (zoom 12.00) followed as a normal change.
First version, iOS only: the reproducer below in the example app (
mainat 47a736a, React Native 0.84.1, New Architecture, Mapbox 11.33.0), iOS 26.5 simulator (iPhone 16). The map opens at zoom 12 and is never touched; each run is a fresh app launch.main'busy'(JS busy 3 s while the map mounts), 10 runs: noonCameraChangedat all'late'(onCameraChangedset at the first idle), 3 runs:onCameraChangedcallsIn every run
onMapIdlereported zoom 12.00. Without the busy child the start camera usually comes aftercomponentDidMount, which is why the'busy'case is timing-dependent; in one run with this PR the one-shot carried the map's first camera (zoom 0.47) and the start camera followed as a normal change. The text area has a fixed height: text that grows would resize the map, and a resize is a camera change of its own.Component to reproduce the issue you're fixing
BugReportExample.js — 'busy' and 'late' modes, counts onCameraChanged for a map that is never moved
🤖 Generated with Claude Code