Skip to main content

mln_builtins/sources/geojson/
mod.rs

1//! GeoJSON sources: features from GeoJSON data that the style or the API
2//! gives, or that the source's URL points to, cut into tiles or clustered.
3//! A source's description is its data, indexed for tiling or clustered as it
4//! loads; its tiles take their features from it, cut off the tiles' thread
5//! unless the source updates synchronously. [`tile`] cuts features into
6//! vector tiles, as geojson-vt does, and [`cluster`] groups a clustered
7//! source's points into clusters for each zoom, as supercluster does.
8//!
9//! The data is tiled and clustered in the world square of the map that
10//! draws the source, Mercator's or a registered projection's. Data tiled for
11//! another projection than the map's draws nothing until the map has tiled
12//! the source's GeoJSON again in its own, as it does when the projection
13//! changes from the source's URL or the style; data set on the source warns
14//! once that it must be set again.
15
16pub mod cluster;
17pub mod tile;
18
19use std::sync::{Arc, Weak};
20
21use geojson::GeoJson;
22use mln_engine::MapMode;
23use mln_engine::exec::pool::TaskGroup;
24use mln_engine::query::FeatureExtensionValue;
25use mln_engine::source::{
26    Cover, DataOrigin, Described, Fetch, GeometryTiles, Load, LoadContext, OfflineResources, OriginUpdate, Replier,
27    Respond, SourceSummary, SourceType, Supply, WorldCopy,
28};
29use mln_engine::storage::Data;
30use mln_engine::tile::TileData;
31use mln_style::crs::WorldMapping;
32use mln_style::error::Error;
33use mln_style::expression::{
34    EvaluationContext, Expr, evaluate_accumulated, from_expression_value, with_geojson_feature,
35};
36use mln_style::feature::{Feature, Identifier, PropertyMap, Value};
37use mln_style::source::SourceData;
38use mln_style::sources::GeoJsonSourceType;
39use mln_style::sources::geojson::{ClusterProperties, GeoJSONOptions, GeoJsonSourceOptions, features_to_world};
40use mln_style::tile_id::CanonicalTileID;
41use mln_style::{Edit, Source, constants};
42use parking_lot::Mutex;
43
44/// The `tracing` targets of this module's events, which name the event that
45/// `mln_c` reports them under (`mln_c::logging`).
46const PARSE_STYLE: &str = "mln_builtins::parse_style";
47const GENERAL: &str = "mln_builtins::general";
48
49/// The engine half of the GeoJSON source type, whose style half is
50/// `mln_style`'s [`GeoJsonSourceType`].
51pub struct GeoJsonSource;
52
53impl SourceType for GeoJsonSource {
54    type Style = GeoJsonSourceType;
55    type Data = GeometryTiles;
56    type Description = Arc<dyn GeoJSONData>;
57
58    const DESCRIBES_IN_BACKGROUND: bool = true;
59
60    const DESCRIBES_IN_WORLD: bool = true;
61
62    /// The GeoJSON at the source's URL, or the GeoJSON the style gives,
63    /// which the source indexes as it describes it.
64    fn load(source: &SourceData<GeoJsonSourceType>) -> Load<Arc<dyn GeoJSONData>> {
65        match (&source.options.url, &source.options.inline) {
66            (Some(url), _) => Load::Fetch(Fetch::Source(url.clone())),
67            (None, Some(_)) => Load::Describe,
68            (None, None) => Load::Done,
69        }
70    }
71
72    /// Builds the fetched GeoJSON, or the GeoJSON the style gives, in the
73    /// world square of `world`. Data that doesn't build is logged and
74    /// describes an empty source, so that its tiles don't wait for data.
75    fn describe(
76        options: &GeoJsonSourceOptions,
77        world: &WorldMapping,
78        data: Option<Data>,
79        respond: Respond<Described<Arc<dyn GeoJSONData>>>,
80    ) {
81        respond(match (data, &options.inline) {
82            (Some(data), _) => Ok(build_geojson(&data, options, world)),
83            (None, Some(inline)) => Ok(build_inline(inline, options, world)),
84            (None, None) => Err(Error::failed("unexpectedly empty GeoJSON")),
85        });
86    }
87
88    fn attribution(source: &SourceData<GeoJsonSourceType>) -> Option<String> {
89        source.options.options.attribution.clone()
90    }
91
92    fn summary(source: &SourceData<GeoJsonSourceType>) -> SourceSummary {
93        SourceSummary {
94            url: source.options.url.clone(),
95            geojson: Some(Arc::clone(&source.options.options)),
96            ..SourceSummary::default()
97        }
98    }
99
100    fn offline(source: &SourceData<GeoJsonSourceType>) -> OfflineResources {
101        match &source.options.url {
102            Some(url) => OfflineResources::Source { url: url.clone() },
103            None => OfflineResources::None,
104        }
105    }
106
107    fn supply(_source: &Source) -> Supply<GeometryTiles> {
108        Supply::tiles(GeoJsonOrigin { data: None, synchronous: false, warned: None })
109    }
110
111    /// The "supercluster" extension: a cluster feature's "children",
112    /// "leaves" (`args` "limit", default 10, and "offset", default 0) or
113    /// "expansion-zoom". Anything else is a null value.
114    fn query_feature_extension(
115        source: &Source,
116        feature: &mln_engine::tile::feature::Feature,
117        extension: &str,
118        field: &str,
119        args: Option<&PropertyMap>,
120    ) -> Result<FeatureExtensionValue, Error> {
121        query_feature_extension(source, feature, extension, field, args)
122    }
123}
124
125/// The features of tile `id`. A tile past the maximum zoom or the last row
126/// is logged, and empty.
127fn tile_features(index: &tile::TileIndex, id: &CanonicalTileID) -> Arc<TileFeatures> {
128    index.tile(id.z, id.x, id.y).unwrap_or_else(|e| {
129        tracing::error!(target: GENERAL, tile = %id, error = %e, "Failed to build GeoJSON tile data");
130        Arc::default()
131    })
132}
133
134/// A `TileIndex`'s tiles, which it cuts as they are asked for.
135struct IndexData {
136    index: tile::TileIndex,
137    /// How lng/lat maps to the world square the data is tiled in.
138    world: WorldMapping,
139}
140
141impl std::fmt::Debug for IndexData {
142    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
143        f.write_str("IndexData")
144    }
145}
146
147impl GeoJSONData for IndexData {
148    fn tile(&self, id: &CanonicalTileID) -> Arc<TileFeatures> {
149        tile_features(&self.index, id)
150    }
151
152    fn cuts_on_demand(&self) -> bool {
153        true
154    }
155
156    fn children(&self, _cluster_id: u32) -> Result<Features, Error> {
157        Ok(Features::new())
158    }
159
160    fn leaves(&self, _cluster_id: u32, _limit: u32, _offset: u32) -> Result<Features, Error> {
161        Ok(Features::new())
162    }
163
164    fn cluster_expansion_zoom(&self, _cluster_id: u32) -> Result<u8, Error> {
165        Ok(0)
166    }
167
168    fn world(&self) -> &WorldMapping {
169        &self.world
170    }
171}
172
173struct ClusterData {
174    clusters: cluster::Clusters,
175    /// How lng/lat maps to the world square the points were clustered in.
176    world: WorldMapping,
177}
178
179impl std::fmt::Debug for ClusterData {
180    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
181        f.write_str("ClusterData")
182    }
183}
184
185impl GeoJSONData for ClusterData {
186    fn tile(&self, id: &CanonicalTileID) -> Arc<TileFeatures> {
187        Arc::new(self.clusters.tile(id.z, id.x, id.y))
188    }
189
190    fn children(&self, cluster_id: u32) -> Result<Features, Error> {
191        self.clusters.children(cluster_id).map_err(|e| Error::not_found(e.to_string()))
192    }
193
194    fn leaves(&self, cluster_id: u32, limit: u32, offset: u32) -> Result<Features, Error> {
195        self.clusters.leaves(cluster_id, limit as usize, offset as usize).map_err(|e| Error::not_found(e.to_string()))
196    }
197
198    fn cluster_expansion_zoom(&self, cluster_id: u32) -> Result<u8, Error> {
199        self.clusters.expansion_zoom(cluster_id).map_err(|e| Error::not_found(e.to_string()))
200    }
201
202    fn world(&self) -> &WorldMapping {
203        &self.world
204    }
205}
206
207fn evaluate_feature(f: &Feature<f64>, expression: &Arc<Expr>, accumulated: Option<&Value>) -> Value {
208    if let Ok(result) = evaluate_accumulated(expression.as_ref(), accumulated, f)
209        && let Some(typed) = from_expression_value::<Value>(&result)
210    {
211        return typed;
212    }
213    Value::default()
214}
215
216/// A source's `clusterProperties`: each property's map expression evaluated
217/// on a point, folded with its reduce expression.
218struct ClusterExpressions<'a>(&'a ClusterProperties);
219
220impl cluster::Aggregate for ClusterExpressions<'_> {
221    fn map(&self, properties: &PropertyMap) -> PropertyMap {
222        let mut mapped = PropertyMap::new();
223        let feature = Feature { properties: properties.clone(), ..Feature::default() };
224        for (key, (map_expression, _)) in self.0 {
225            mapped.insert(key.clone(), evaluate_feature(&feature, map_expression, None));
226        }
227        mapped
228    }
229
230    fn reduce(&self, accumulated: &mut PropertyMap, other: &PropertyMap) {
231        let feature = Feature { properties: other.clone(), ..Feature::default() };
232        for (key, (_, reduce_expression)) in self.0 {
233            if !other.contains_key(key) {
234                continue;
235            }
236            let value =
237                evaluate_feature(&feature, reduce_expression, Some(accumulated.get(key).unwrap_or(&Value::Null)));
238            accumulated.insert(key.clone(), value);
239        }
240    }
241}
242
243/// The data of `features`, in lng/lat, tiled or clustered at their places
244/// in the world square of `world`. Only the features of a feature
245/// collection (`collection`) cluster.
246fn create(
247    features: Features,
248    collection: bool,
249    options: &Arc<GeoJSONOptions>,
250    world: &WorldMapping,
251) -> Result<Arc<dyn GeoJSONData>, Error> {
252    let scale: f64 = f64::from(constants::EXTENT) / constants::TILE_SIZE_D;
253    if options.cluster && collection && !features.is_empty() {
254        let cluster_options = cluster::Options {
255            max_zoom: options.cluster_max_zoom,
256            extent: constants::EXTENT as u16,
257            radius: scale * f64::from(options.cluster_radius),
258            min_points: options.cluster_min_points,
259            generate_id: options.generate_id && options.promote_id.is_none(),
260        };
261        let expressions = ClusterExpressions(&options.cluster_properties);
262        let aggregate: Option<&dyn cluster::Aggregate> =
263            (!options.cluster_properties.is_empty()).then_some(&expressions);
264        let clusters = cluster::Clusters::new(features, world, cluster_options, aggregate)
265            .map_err(|e| Error::invalid_argument(e.to_string()))?;
266        return Ok(Arc::new(ClusterData { clusters, world: world.clone() }));
267    }
268
269    let tile_options = tile::Options {
270        max_zoom: options.maxzoom,
271        tile: tile::TileOptions {
272            extent: constants::EXTENT as u16,
273            buffer: (scale * f64::from(options.buffer)).round() as u16,
274            tolerance: scale * options.tolerance,
275            line_metrics: options.line_metrics,
276        },
277        wrap: world.wraps(),
278        ..Default::default()
279    };
280    let index = tile::TileIndex::new(&features_to_world(features, world), tile_options);
281    Ok(Arc::new(IndexData { index, world: world.clone() }))
282}
283
284/// A tile's features, in tile coordinates. Features that come from one
285/// source feature share its property map.
286pub type TileFeatures = Vec<Feature<i16, Arc<PropertyMap>>>;
287pub type Features = Vec<Feature<f64>>;
288
289pub trait GeoJSONData: Send + Sync {
290    /// The features of tile `id`, made on the calling thread. The data may
291    /// keep them, and hand them out again.
292    fn tile(&self, id: &CanonicalTileID) -> Arc<TileFeatures>;
293
294    /// Whether [`tile`](Self::tile) cuts the tile from the features
295    /// as it is asked, work worth taking off the caller's thread, rather
296    /// than reading it from an index made with the data, as clusters do.
297    fn cuts_on_demand(&self) -> bool {
298        false
299    }
300
301    // Data that isn't clustered has no clusters, and
302    // gives empty results. A cluster ID the data doesn't have fails with
303    // `ErrorKind::NotFound`.
304    fn children(&self, cluster_id: u32) -> Result<Features, Error>;
305    fn leaves(&self, cluster_id: u32, limit: u32, offset: u32) -> Result<Features, Error>;
306    fn cluster_expansion_zoom(&self, cluster_id: u32) -> Result<u8, Error>;
307
308    /// How lng/lat maps to the world square the data is tiled in, where it
309    /// draws.
310    fn world(&self) -> &WorldMapping;
311}
312
313/// Prepares GeoJSON for tiling in Mercator's world square, where a map in a
314/// built-in projection draws it, keeping only the features that pass the
315/// source's filter, evaluated at zoom 0. GeoJSON whose geometry `geo_types`
316/// can't hold (a position of fewer than two numbers), or that can't be
317/// clustered, such as a non-point feature, fails with
318/// [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind).
319pub fn create_geojson_data(geojson: GeoJson, options: &Arc<GeoJSONOptions>) -> Result<Arc<dyn GeoJSONData>, Error> {
320    create_geojson_data_in(geojson, options, &WorldMapping::default())
321}
322
323/// [`create_geojson_data`], tiled or clustered in the world square of
324/// `world`: in that of the map that draws a source
325/// ([`View::world`](mln_engine::camera::View::world)), the data draws
326/// there. Cluster children and leaves come back in lng/lat.
327pub fn create_geojson_data_in(
328    geojson: GeoJson,
329    options: &Arc<GeoJSONOptions>,
330    world: &WorldMapping,
331) -> Result<Arc<dyn GeoJSONData>, Error> {
332    let collection = matches!(geojson, GeoJson::FeatureCollection(_));
333    let mut features =
334        mln_style::feature::geojson::features(geojson).map_err(|e| Error::invalid_argument(e.to_string()))?;
335    if let Some(filter) = &options.filter {
336        features.retain(|feature| with_geojson_feature(feature, EvaluationContext::new(0.0), |cx| filter.evaluate(cx)));
337    }
338    assign_ids(&mut features, options);
339    create(features, collection, options, world)
340}
341
342/// Gives `features` the ids that `options` asks for: their index for
343/// `generateId`, the value of their `promoteId` property for that.
344fn assign_ids(features: &mut Features, options: &GeoJSONOptions) {
345    if let Some(property) = &options.promote_id {
346        for feature in features {
347            feature.id = Identifier::promoted(feature.properties.get(property));
348        }
349    } else if options.generate_id {
350        for (index, feature) in features.iter_mut().enumerate() {
351            feature.id = Identifier::Uint(index as u64);
352        }
353    }
354}
355
356/// The data of GeoJSON text `data`, built with `options`. Text that isn't
357/// GeoJSON, or GeoJSON that can't be built, is logged and builds nothing.
358fn build_geojson(data: &[u8], options: &GeoJsonSourceOptions, world: &WorldMapping) -> Option<Arc<dyn GeoJSONData>> {
359    match serde_json::from_slice(data) {
360        Ok(geojson) => build_logged(geojson, options, world),
361        Err(e) => {
362            tracing::error!(target: PARSE_STYLE, error = %e, "Failed to parse GeoJSON data");
363            None
364        }
365    }
366}
367
368/// The data of `inline`, the GeoJSON a style gives, built with `options` in
369/// `world`, as [`build_geojson`] builds fetched GeoJSON.
370fn build_inline(
371    inline: &Result<GeoJson, String>,
372    options: &GeoJsonSourceOptions,
373    world: &WorldMapping,
374) -> Option<Arc<dyn GeoJSONData>> {
375    match inline {
376        Ok(geojson) => build_logged(geojson.clone(), options, world),
377        Err(e) => {
378            tracing::error!(target: PARSE_STYLE, error = %e, "Failed to parse GeoJSON data");
379            None
380        }
381    }
382}
383
384/// The data of `geojson` built with `options` in the world square of
385/// `world`, or `None`, logged, for GeoJSON that can't be built.
386fn build_logged(
387    geojson: GeoJson,
388    options: &GeoJsonSourceOptions,
389    world: &WorldMapping,
390) -> Option<Arc<dyn GeoJSONData>> {
391    match create_geojson_data_in(geojson, &options.options, world) {
392        Ok(data) => Some(data),
393        Err(e) => {
394            tracing::error!(target: PARSE_STYLE, error = %e, "Failed to parse GeoJSON data");
395            None
396        }
397    }
398}
399
400/// A GeoJSON source's tiles: the data they were made from, and whether they
401/// were made with synchronous updates.
402struct GeoJsonOrigin {
403    /// The data, and where tiles of data that cuts them on demand are cut,
404    /// off the tiles' thread: a lane of its own, which takes turns with the
405    /// workers' other work.
406    data: Option<(Arc<dyn GeoJSONData>, TaskGroup)>,
407    synchronous: bool,
408    /// The data tiled for another projection that the origin warned about.
409    warned: Option<Weak<dyn GeoJSONData>>,
410}
411
412impl GeoJsonOrigin {
413    /// Whether `data`, the data of the source `id` of `options`, is tiled in
414    /// `world`, the map's, where it draws. Data tiled for another one would
415    /// draw in the wrong place; when the source has no GeoJSON to tile in the
416    /// map's, the origin warns once that the data must be set again.
417    fn draws(
418        &mut self,
419        id: &str,
420        options: &GeoJsonSourceOptions,
421        world: &WorldMapping,
422        data: &Arc<dyn GeoJSONData>,
423    ) -> bool {
424        if data.world() == world {
425            return true;
426        }
427        let warned = self.warned.as_ref().is_some_and(|warned| std::ptr::addr_eq(warned.as_ptr(), Arc::as_ptr(data)));
428        if !options.tiles_again() && !warned {
429            tracing::warn!(
430                target: GENERAL,
431                source_id = %id,
432                "GeoJSON source has data tiled for another projection and draws nothing; set its data again after \
433                 changing the projection."
434            );
435            self.warned = Some(Arc::downgrade(data));
436        }
437        false
438    }
439
440    /// Loads the tile from the source's data: cut on the pool unless the
441    /// source updates synchronously. With `relayout`, the tile first drops
442    /// its data and style.
443    fn load(&self, cx: &mut LoadContext<'_, '_, Self>, relayout: bool) {
444        let Some((data, cuts)) = &self.data else {
445            return;
446        };
447        if relayout {
448            cx.reset();
449        }
450        let replier = cx.begin_load();
451        let cuts = (!self.synchronous).then_some(cuts);
452        if let Some(features) = request_tile(data, cx.id().canonical, replier, cuts) {
453            cx.deliver(Some(features));
454        }
455    }
456}
457
458impl DataOrigin for GeoJsonOrigin {
459    type Data = GeometryTiles;
460    type Tile = ();
461    type Reply = TileData;
462
463    fn update(&mut self, update: &mut OriginUpdate<'_, Self>) -> Option<Cover> {
464        let source = SourceData::<GeoJsonSourceType>::recover(update.source())?;
465        // A tile lays out in the mode it was created with, so a mode change
466        // recreates the tiles.
467        let synchronous = source.options.synchronous_update;
468        if synchronous != self.synchronous {
469            self.synchronous = synchronous;
470            update.clear_tiles();
471        }
472        let id = update.source().id();
473        let described = source.description::<Arc<dyn GeoJSONData>>();
474        let world = &update.map().world;
475        let data = described.filter(|data| self.draws(id, &source.options, world, data));
476        let same = match (self.data.as_ref().map(|(data, _)| data), data) {
477            (None, None) => true,
478            (Some(a), Some(b)) => std::ptr::addr_eq(Arc::as_ptr(a), Arc::as_ptr(b)),
479            _ => false,
480        };
481        if !same {
482            self.data = data.map(|data| (Arc::clone(data), TaskGroup::new(update.pool())));
483            // Tiles of data tiled for another projection would draw in the
484            // wrong place, unlike those of data that went.
485            let tiled_elsewhere = data.is_none() && described.is_some();
486            if update.map().mode != MapMode::Continuous || tiled_elsewhere {
487                // Clearing the tiles in order to avoid render tests being
488                // flaky.
489                update.clear_tiles();
490            } else if data.is_some() {
491                update.clear_cache();
492                let max_z = source.options.zoom_range().max;
493                let relayout = update.needs_relayout();
494                update.update_tiles(|id| id.canonical.z <= max_z, |(), cx| self.load(cx, relayout));
495            }
496        }
497        data?;
498        Some(Cover {
499            tile_size: constants::TILE_SIZE_I,
500            zoom_range: source.options.zoom_range(),
501            bounds: None,
502            round_zoom: false,
503            overscale: true,
504            prefetch: false,
505            synchronous,
506        })
507    }
508
509    fn start(&mut self, cx: &mut LoadContext<'_, '_, Self>, _copy: Option<WorldCopy<'_, ()>>) {
510        self.load(cx, false);
511    }
512
513    fn receive(&mut self, (): &mut (), features: TileData, cx: &mut LoadContext<'_, '_, Self>) {
514        cx.deliver(Some(features));
515    }
516}
517
518/// Asks GeoJSON `data` for tile `id`'s features, cut in `cuts` if there is
519/// one and the data cuts its tiles on demand: returns them if they answer
520/// before this returns, else `replier` sends them.
521fn request_tile(
522    data: &Arc<dyn GeoJSONData>,
523    id: CanonicalTileID,
524    replier: Replier<TileData>,
525    cuts: Option<&TaskGroup>,
526) -> Option<TileData> {
527    let Some(cuts) = cuts.filter(|_| data.cuts_on_demand()) else {
528        return Some(TileData::Features(data.tile(&id)));
529    };
530    let slot: Arc<Mutex<Answered>> = Arc::default();
531    let task_slot = Arc::clone(&slot);
532    let data_for_task = Arc::clone(data);
533    cuts.spawn(move || {
534        let data = TileData::Features(data_for_task.tile(&id));
535        let mut slot = task_slot.lock();
536        if matches!(*slot, Answered::Later) {
537            drop(slot);
538            replier.send(data);
539        } else {
540            *slot = Answered::Now(data);
541        }
542    });
543    let answered = std::mem::replace(&mut *slot.lock(), Answered::Later);
544    match answered {
545        Answered::Now(data) => Some(data),
546        Answered::Pending | Answered::Later => None,
547    }
548}
549
550/// When a tile cut off the tiles' thread answered: before its request
551/// returned, or after.
552#[derive(Default)]
553enum Answered {
554    #[default]
555    Pending,
556    Now(TileData),
557    Later,
558}
559
560/// [`GeoJsonSource::query_feature_extension`]: a null value for a source of
561/// another type.
562fn query_feature_extension(
563    source: &Source,
564    feature: &mln_engine::tile::feature::Feature,
565    extension: &str,
566    extension_field: &str,
567    args: Option<&PropertyMap>,
568) -> Result<FeatureExtensionValue, Error> {
569    if extension != "supercluster" {
570        return Ok(FeatureExtensionValue::default());
571    }
572    let Some(cluster_id) = uint_property(&feature.properties, "cluster_id") else {
573        return Ok(FeatureExtensionValue::default());
574    };
575    let Some(json_data) = geojson_data(source) else {
576        return Ok(FeatureExtensionValue::default());
577    };
578    supercluster_extension(&**json_data, extension_field, cluster_id as u32, args)
579        .unwrap_or_else(|| Ok(FeatureExtensionValue::default()))
580}
581
582/// The property `name`, if it is an unsigned integer.
583fn uint_property(properties: &PropertyMap, name: &str) -> Option<u64> {
584    match properties.get(name) {
585        Some(Value::Uint(value)) => Some(*value),
586        _ => None,
587    }
588}
589
590/// The supercluster `extensionGetters`: the `extension_field` of cluster
591/// `cluster_id`, or `None` for a field it doesn't have.
592fn supercluster_extension(
593    cluster_data: &dyn GeoJSONData,
594    extension_field: &str,
595    cluster_id: u32,
596    args: Option<&PropertyMap>,
597) -> Option<Result<FeatureExtensionValue, Error>> {
598    Some(match extension_field {
599        "children" => cluster_data.children(cluster_id).map(FeatureExtensionValue::FeatureCollection),
600        "leaves" => {
601            // Offset cannot be set without limit.
602            let (limit, offset) = match args.and_then(|args| Some((uint_property(args, "limit")?, args))) {
603                Some((limit, args)) => (limit as u32, uint_property(args, "offset").map_or(0, |offset| offset as u32)),
604                None => (10, 0),
605            };
606            cluster_data.leaves(cluster_id, limit, offset).map(FeatureExtensionValue::FeatureCollection)
607        }
608        "expansion-zoom" => cluster_data
609            .cluster_expansion_zoom(cluster_id)
610            .map(|zoom| FeatureExtensionValue::Value(Value::Uint(u64::from(zoom)))),
611        _ => return None,
612    })
613}
614
615/// The data of `source`, if it's a GeoJSON source with data.
616#[must_use]
617pub fn geojson_data(source: &Source) -> Option<&Arc<dyn GeoJSONData>> {
618    SourceData::<GeoJsonSourceType>::recover(source)?.description::<Arc<dyn GeoJSONData>>()
619}
620
621/// The edit that replaces the data of the GeoJSON source `id`, which no
622/// longer loads it from a URL or the style. The data draws in the world
623/// square it was tiled in alone ([`create_geojson_data_in`]).
624pub fn set_data(id: impl Into<String>, geojson: Option<Arc<dyn GeoJSONData>>) -> Edit {
625    Edit::update_source::<GeoJsonSourceType>(id, "a GeoJSON source", |data| {
626        data.options.url = None;
627        data.options.inline = None;
628        data.description = geojson.map(|geojson| -> mln_style::source::ErasedDescription { Arc::new(geojson) });
629        data.load += 1;
630        true
631    })
632}
633
634// Debug is not a supertrait, for the reason at mln_style's
635// `impl Debug for dyn ErasedLayerStyle`.
636impl std::fmt::Debug for dyn GeoJSONData {
637    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
638        f.debug_struct("GeoJSONData").finish_non_exhaustive()
639    }
640}
641
642#[cfg(test)]
643mod crs_test;