Skip to main content

day_piece_map/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Shared state for interchangeable map providers. This crate loads no map SDK.
5//! Use `day-piece-map-canvas`, `day-piece-map-apple`, or `day-piece-map-google` to render it.
6//! A view belongs to one mounted provider at a time. Keep it outside the provider-switch scope
7//! to preserve camera and annotations. Provider-specific options live in the provider crates.
8
9mod coordinates;
10pub use coordinates::{LngLat, MAX_LATITUDE, MAX_ZOOM, wrap_bearing};
11#[doc(hidden)]
12#[cfg(feature = "native-bridge")]
13#[path = "native.rs"]
14pub mod __native;
15use day_geometry::{Color, Point};
16use day_reactive::Signal;
17
18/// Normalize a zoom, including non-finite input, to the shared range.
19pub fn clamp_zoom(zoom: f64) -> f64 {
20    if zoom.is_finite() {
21        zoom.clamp(0.0, MAX_ZOOM)
22    } else {
23        0.0
24    }
25}
26
27/// Initialization state reported by the active provider.
28#[derive(Clone, Debug, PartialEq, Eq)]
29pub enum MapStatus {
30    /// The provider is initializing or loading its map.
31    Loading,
32    /// The map is usable; additional tiles can still be loading.
33    Ready,
34    /// Initialization or a map operation failed. The detail is diagnostic, not localized UI.
35    Failed(String),
36}
37
38/// A marker's handle, from [`MapView::add_marker`].
39#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
40pub struct MarkerId(u64);
41
42impl MarkerId {
43    /// Stable numeric identity for provider bridges.
44    pub const fn value(self) -> u64 {
45        self.0
46    }
47}
48
49/// A pin on the map at a position, with an optional title shown beside it and a tag the app
50/// uses to know it again when it is tapped.
51#[derive(Clone, Debug, PartialEq)]
52#[must_use]
53pub struct Marker {
54    pub position: LngLat,
55    pub title: String,
56    pub color: Color,
57    /// Secondary annotation text, supplied by the app.
58    pub subtitle: String,
59    /// The app's own key for this marker (an item id, a route key), handed back through
60    /// [`MapView::marker`] when [`MapView::tap`] names it; not shown.
61    pub tag: String,
62}
63
64impl Marker {
65    pub fn new(position: LngLat) -> Marker {
66        Marker {
67            position,
68            title: String::new(),
69            subtitle: String::new(),
70            color: Color::rgb(0.86, 0.2, 0.18),
71            tag: String::new(),
72        }
73    }
74
75    pub fn title(mut self, title: impl Into<String>) -> Marker {
76        self.title = title.into();
77        self
78    }
79
80    pub fn subtitle(mut self, text: impl Into<String>) -> Self {
81        self.subtitle = text.into();
82        self
83    }
84
85    pub fn tag(mut self, tag: impl Into<String>) -> Marker {
86        self.tag = tag.into();
87        self
88    }
89
90    pub fn color(mut self, color: Color) -> Marker {
91        self.color = color;
92        self
93    }
94}
95
96/// Where the user tapped ([`MapView::tap`]): the point, the position under it, the marker
97/// hit if any. Provider-specific basemap feature queries live in provider crates.
98#[derive(Clone, Debug, PartialEq)]
99pub struct MapTap {
100    pub point: Point,
101    pub location: LngLat,
102    pub marker: Option<MarkerId>,
103}
104
105/// A move the app asked for, carried out by the piece over `duration` seconds.
106#[derive(Clone, Copy, Debug, PartialEq)]
107pub struct CameraRequest {
108    pub target: CameraTarget,
109    pub duration: f64,
110    /// Distinguishes one request from the next identical one.
111    pub serial: u64,
112}
113
114#[derive(Clone, Copy, Debug, PartialEq)]
115pub enum CameraTarget {
116    /// A view: `None` keeps the current bearing.
117    View {
118        center: LngLat,
119        zoom: f64,
120        bearing: Option<f64>,
121    },
122    /// The north-up view that shows a box whole, `padding` points clear around it.
123    Bounds {
124        sw: LngLat,
125        ne: LngLat,
126        padding: f64,
127    },
128}
129
130/// How long [`MapView::fly_to`] takes, in seconds.
131const FLY_SECS: f64 = 1.0;
132/// How long [`MapView::rotate_to`] takes, in seconds.
133const TURN_SECS: f64 = 0.5;
134
135/// The state of a map, shared between the piece and the app: where it looks and how close,
136/// which the app sets to move the map and reads to learn where the user took it, plus what
137/// the piece reports back about loading and drawing.
138#[derive(Clone, Copy)]
139pub struct MapView {
140    /// Center in WGS84 degrees; longitude comes first.
141    pub center: Signal<LngLat>,
142    /// Web Mercator zoom with a 512-point world at zoom zero. Providers clamp to their limits.
143    pub zoom: Signal<f64>,
144    /// Clockwise heading in degrees; zero is north.
145    pub bearing: Signal<f64>,
146    /// Provider loading state. Failure details are diagnostic, not localized UI text.
147    pub status: Signal<MapStatus>,
148    /// Provider credits, when supplied as text. Native SDKs retain their attribution controls.
149    pub attribution: Signal<String>,
150    /// Ordered annotations. Prefer the marker methods to preserve stable identities.
151    pub markers: Signal<Vec<(MarkerId, Marker)>>,
152    /// Last map or marker tap. Native SDKs may reserve double taps for zooming.
153    pub tap: Signal<Option<MapTap>>,
154    /// Geometry drawn above the basemap and below annotations, in list order.
155    pub overlays: Signal<Vec<Overlay>>,
156    /// Which user camera gestures are enabled; programmatic moves remain available.
157    pub interaction: Signal<Interaction>,
158    /// Provider-facing command stream. Observe serial numbers; do not replay on remount.
159    pub request: Signal<Option<CameraRequest>>,
160    next_marker: Signal<u64>,
161}
162
163impl MapView {
164    pub fn new(center: LngLat, zoom: f64) -> MapView {
165        MapView {
166            center: Signal::new(center.wrapped()),
167            zoom: Signal::new(clamp_zoom(zoom)),
168            status: Signal::new(MapStatus::Loading),
169            attribution: Signal::new(String::new()),
170            bearing: Signal::new(0.0),
171            markers: Signal::new(Vec::new()),
172            overlays: Signal::new(Vec::new()),
173            interaction: Signal::new(Interaction::default()),
174            tap: Signal::new(None),
175            request: Signal::new(None),
176            next_marker: Signal::new(1),
177        }
178    }
179
180    /// Put a marker on the map.
181    pub fn add_marker(&self, marker: Marker) -> MarkerId {
182        let id = MarkerId(self.next_marker.get_untracked());
183        self.next_marker.set(id.0 + 1);
184        let mut markers = self.markers.get_untracked();
185        markers.push((id, marker));
186        self.markers.set(markers);
187        id
188    }
189
190    /// Replace a marker in place, keeping its id: a new title or position. `false` when `id`
191    /// is no longer on the map.
192    pub fn update_marker(&self, id: MarkerId, marker: Marker) -> bool {
193        let mut markers = self.markers.get_untracked();
194        let Some(slot) = markers.iter_mut().find(|(m, _)| *m == id) else {
195            return false;
196        };
197        slot.1 = marker;
198        self.markers.set(markers);
199        true
200    }
201
202    /// Take a marker off the map.
203    pub fn remove_marker(&self, id: MarkerId) {
204        let mut markers = self.markers.get_untracked();
205        markers.retain(|(m, _)| *m != id);
206        self.markers.set(markers);
207    }
208
209    pub fn clear_markers(&self) {
210        self.markers.set(Vec::new());
211    }
212
213    /// The marker with `id`, if it is still on the map.
214    pub fn marker(&self, id: MarkerId) -> Option<Marker> {
215        self.markers
216            .get_untracked()
217            .into_iter()
218            .find(|(m, _)| *m == id)
219            .map(|(_, marker)| marker)
220    }
221
222    /// Animate to `center` at `zoom`. The canvas renderer uses a one-second flight; native SDKs
223    /// choose their own trajectory and may approximate the requested duration.
224    pub fn fly_to(&self, center: LngLat, zoom: f64) {
225        self.fly_to_with(center, zoom, None, FLY_SECS);
226    }
227
228    /// [`MapView::fly_to`] with the bearing to arrive at (`None` keeps the current one) and
229    /// the requested duration in seconds; `0.0` jumps. MapKit uses its standard animation
230    /// timing for positive durations.
231    pub fn fly_to_with(&self, center: LngLat, zoom: f64, bearing: Option<f64>, duration: f64) {
232        self.request_move(
233            CameraTarget::View {
234                center: center.wrapped(),
235                zoom: clamp_zoom(zoom),
236                bearing,
237            },
238            duration,
239        );
240    }
241
242    /// Glide to the north-up view that shows the box from `sw` to `ne` whole, with `padding`
243    /// points kept clear on every side.
244    pub fn fit_bounds(&self, sw: LngLat, ne: LngLat, padding: f64) {
245        self.request_move(
246            CameraTarget::Bounds {
247                sw: sw.wrapped(),
248                ne: ne.wrapped(),
249                padding: if padding.is_finite() {
250                    padding.max(0.0)
251                } else {
252                    0.0
253                },
254            },
255            FLY_SECS,
256        );
257    }
258
259    /// Turn to `bearing` degrees (clockwise, `0.0` north up) over half a second, the position
260    /// at the center held.
261    pub fn rotate_to(&self, bearing: f64) {
262        self.request_move(
263            CameraTarget::View {
264                center: self.center.get_untracked(),
265                zoom: self.zoom.get_untracked(),
266                bearing: Some(bearing),
267            },
268            TURN_SECS,
269        );
270    }
271
272    /// Turn back to north up.
273    pub fn reset_north(&self) {
274        self.rotate_to(0.0);
275    }
276
277    fn request_move(&self, target: CameraTarget, duration: f64) {
278        let serial = self
279            .request
280            .get_untracked()
281            .map_or(1, |r| r.serial.wrapping_add(1));
282        self.request.set(Some(CameraRequest {
283            target,
284            duration: if duration.is_finite() {
285                duration.clamp(0.0, 60.0)
286            } else {
287                0.0
288            },
289            serial,
290        }));
291    }
292
293    /// Zoom by `levels` (negative zooms out), keeping the center.
294    pub fn zoom_by(&self, levels: f64) {
295        let z = clamp_zoom(self.zoom.get_untracked() + levels);
296        self.zoom.set(z);
297    }
298
299    /// Look at `center` from `zoom`, at once.
300    pub fn jump_to(&self, center: LngLat, zoom: f64) {
301        self.center.set(center.wrapped());
302        self.zoom.set(clamp_zoom(zoom));
303    }
304
305    /// [`MapView::jump_to`] with the bearing too (`0.0` is north up).
306    pub fn jump_to_with(&self, center: LngLat, zoom: f64, bearing: f64) {
307        self.jump_to(center, zoom);
308        self.bearing.set(wrap_bearing(bearing));
309    }
310}
311
312/// Gesture controls shared by all providers.
313#[derive(Clone, Copy, Debug, PartialEq, Eq)]
314pub struct Interaction {
315    pub pan: bool,
316    pub zoom: bool,
317    pub rotate: bool,
318}
319impl Default for Interaction {
320    fn default() -> Self {
321        Self {
322            pan: true,
323            zoom: true,
324            rotate: true,
325        }
326    }
327}
328
329/// Geographic geometry in WGS84. Widths are logical points; circle radii are meters.
330/// Coordinates are normalized by the provider; empty lines/rings are ignored.
331#[derive(Clone, Debug, PartialEq)]
332#[non_exhaustive]
333pub enum Overlay {
334    Polyline {
335        points: Vec<LngLat>,
336        color: Color,
337        width: f64,
338    },
339    Polygon {
340        points: Vec<LngLat>,
341        fill: Color,
342        stroke: Color,
343        width: f64,
344    },
345    Circle {
346        center: LngLat,
347        radius: f64,
348        fill: Color,
349        stroke: Color,
350        width: f64,
351    },
352}