use std::sync::Arc;
use crate::error::Error;
use crate::expression::GlobalStateMap;
use crate::feature::Value;
use crate::filter::Filter;
use crate::image;
use crate::layer::Layer;
use crate::light::Light;
use crate::projection::Projection;
use crate::property::transition::TransitionOptions;
use crate::sky::Sky;
use crate::source::{ErasedDescription, Source, SourceCommon, SourceData, SourceInstance, StyleSourceType};
use crate::terrain::Terrain;
use crate::types::VisibilityType;
#[expect(clippy::large_enum_variant, reason = "an edit is made and applied at once, not stored")]
pub enum Edit {
AddLayer {
layer: Layer,
before: Option<String>,
},
RemoveLayer(String),
MoveLayer {
id: String,
before: Option<String>,
},
SetLayer(Layer),
SetLayerProperty {
layer: String,
name: String,
value: serde_json::Value,
},
SetLayerFilter {
layer: String,
filter: Filter,
},
SetLayerZoomRange {
layer: String,
min: f64,
max: f64,
},
SetLayerVisibility {
layer: String,
visibility: VisibilityType,
},
SetLight(Light),
SetLightProperty {
name: String,
value: serde_json::Value,
},
SetSky(Option<Sky>),
SetTerrain(Option<Terrain>),
SetProjection(Projection),
SetMember {
name: String,
value: serde_json::Value,
},
SetTransition(TransitionOptions),
SetGlobalState {
name: String,
value: Value,
},
SetGlobalStateDefaults(GlobalStateMap),
AddImage(Arc<image::StyleImage>),
RemoveImage(String),
AddImages(Vec<Arc<image::StyleImage>>),
AddSource(Source),
RemoveSource(String),
SetSourceDescription {
id: String,
instance: SourceInstance,
load: u64,
description: Option<ErasedDescription>,
},
SetSourceCommon {
id: String,
common: SourceCommon,
},
UpdateSource {
id: String,
update: SourceUpdate,
},
}
pub type SourceUpdate = Box<dyn FnOnce(&Source) -> Result<Option<Source>, Error> + Send>;
impl Edit {
pub fn update_source<T: StyleSourceType>(
id: impl Into<String>,
kind: &'static str,
change: impl FnOnce(&mut SourceData<T>) -> bool + Send + 'static,
) -> Edit {
let update = move |source: &Source| {
let Some(data) = SourceData::<T>::recover(source) else {
return Err(Error::invalid_argument(format!("source \"{}\" is not {kind}", source.id())));
};
let mut data = data.clone();
Ok(change(&mut data).then(|| source.with_data(data)))
};
Edit::UpdateSource { id: id.into(), update: Box::new(update) }
}
}