crisol-ui-kit 1.14.0

Crisol UI kit: themes, style tokens, icon caches, fonts, localization, base components, and widgets.
Documentation
//! Settings forms generated from a small schema.

use std::collections::BTreeMap;

use egui::Ui;

/// The type and constraints of one setting.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum SettingKind {
    /// On/off.
    Bool,
    /// A bounded number.
    Number {
        /// Minimum.
        min: f64,
        /// Maximum.
        max: f64,
    },
    /// Free text.
    Text,
    /// One of a fixed list.
    Choice(Vec<String>),
}

/// One setting in a schema.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct Setting {
    /// Stable key.
    pub key: String,
    /// Visible label.
    pub label: String,
    /// Optional help text.
    pub description: Option<String>,
    /// The control.
    pub kind: SettingKind,
}

impl Setting {
    /// A setting.
    pub fn new(key: impl Into<String>, label: impl Into<String>, kind: SettingKind) -> Self {
        Self {
            key: key.into(),
            label: label.into(),
            description: None,
            kind,
        }
    }

    /// Add help text.
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }
}

/// A current setting value.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum SettingValue {
    /// Boolean.
    Bool(bool),
    /// Number.
    Number(f64),
    /// Text or a selected choice.
    Text(String),
}

impl Default for SettingValue {
    fn default() -> Self {
        Self::Bool(false)
    }
}

/// A form definition and its current values.
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct SettingsSchema {
    /// Settings in display order.
    pub settings: Vec<Setting>,
    /// Values by key.
    pub values: BTreeMap<String, SettingValue>,
}

impl SettingsSchema {
    /// An empty schema.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a setting and its default value.
    pub fn add(mut self, setting: Setting, value: SettingValue) -> Self {
        self.values.insert(setting.key.clone(), value);
        self.settings.push(setting);
        self
    }

    /// A boolean value.
    pub fn bool(&self, key: &str) -> bool {
        matches!(self.values.get(key), Some(SettingValue::Bool(true)))
    }

    /// A numeric value.
    pub fn number(&self, key: &str) -> f64 {
        match self.values.get(key) {
            Some(SettingValue::Number(value)) => *value,
            _ => 0.0,
        }
    }

    /// A text value.
    pub fn text(&self, key: &str) -> &str {
        match self.values.get(key) {
            Some(SettingValue::Text(value)) => value,
            _ => "",
        }
    }

    /// Build from a JSON Schema object with `properties` of boolean, number, string, or
    /// enum types.
    ///
    /// # Errors
    /// When the value is not an object or a property has an unsupported type.
    #[cfg(feature = "serde")]
    pub fn from_schema(schema: &serde_json::Value) -> Result<Self, String> {
        let properties = schema
            .get("properties")
            .and_then(serde_json::Value::as_object)
            .ok_or_else(|| "the schema has no properties".to_owned())?;
        let mut form = Self::new();
        for (key, definition) in properties {
            let label = definition
                .get("title")
                .and_then(serde_json::Value::as_str)
                .unwrap_or(key);
            let description = definition.get("description").and_then(serde_json::Value::as_str);
            let kind = if definition.get("type").and_then(serde_json::Value::as_str) == Some("boolean") {
                SettingKind::Bool
            } else if definition.get("type").and_then(serde_json::Value::as_str) == Some("number")
                || definition.get("type").and_then(serde_json::Value::as_str) == Some("integer")
            {
                SettingKind::Number {
                    min: definition
                        .get("minimum")
                        .and_then(serde_json::Value::as_f64)
                        .unwrap_or(0.0),
                    max: definition
                        .get("maximum")
                        .and_then(serde_json::Value::as_f64)
                        .unwrap_or(100.0),
                }
            } else if let Some(values) = definition.get("enum").and_then(serde_json::Value::as_array) {
                SettingKind::Choice(
                    values
                        .iter()
                        .filter_map(serde_json::Value::as_str)
                        .map(str::to_owned)
                        .collect(),
                )
            } else {
                SettingKind::Text
            };
            let value = match &kind {
                SettingKind::Bool => SettingValue::Bool(
                    definition
                        .get("default")
                        .and_then(serde_json::Value::as_bool)
                        .unwrap_or(false),
                ),
                SettingKind::Number { .. } => SettingValue::Number(
                    definition
                        .get("default")
                        .and_then(serde_json::Value::as_f64)
                        .unwrap_or(0.0),
                ),
                SettingKind::Choice(values) => SettingValue::Text(
                    definition
                        .get("default")
                        .and_then(serde_json::Value::as_str)
                        .or_else(|| values.first().map(String::as_str))
                        .unwrap_or("")
                        .to_owned(),
                ),
                SettingKind::Text => SettingValue::Text(
                    definition
                        .get("default")
                        .and_then(serde_json::Value::as_str)
                        .unwrap_or("")
                        .to_owned(),
                ),
            };
            let mut setting = Setting::new(key, label, kind);
            if let Some(description) = description {
                setting = setting.description(description);
            }
            form = form.add(setting, value);
        }
        Ok(form)
    }

    /// Paint the form and return whether any value changed.
    pub fn show(&mut self, ui: &mut Ui) -> bool {
        let mut changed = false;
        for setting in &self.settings {
            match setting.kind.clone() {
                SettingKind::Bool => {
                    let mut value = self.bool(&setting.key);
                    if ui.checkbox(&mut value, &setting.label).changed() {
                        self.values.insert(setting.key.clone(), SettingValue::Bool(value));
                        changed = true;
                    }
                }
                SettingKind::Number { min, max } => {
                    let mut value = self.number(&setting.key);
                    ui.horizontal(|ui| {
                        ui.label(&setting.label);
                        if ui.add(egui::DragValue::new(&mut value).range(min..=max)).changed() {
                            self.values.insert(setting.key.clone(), SettingValue::Number(value));
                            changed = true;
                        }
                    });
                }
                SettingKind::Text => {
                    let mut value = self.text(&setting.key).to_owned();
                    ui.horizontal(|ui| {
                        ui.label(&setting.label);
                        if ui.text_edit_singleline(&mut value).changed() {
                            self.values.insert(setting.key.clone(), SettingValue::Text(value));
                            changed = true;
                        }
                    });
                }
                SettingKind::Choice(options) => {
                    let current = self.text(&setting.key).to_owned();
                    let mut selected = options.iter().position(|option| *option == current).unwrap_or(0);
                    ui.horizontal(|ui| {
                        ui.label(&setting.label);
                        egui::ComboBox::from_id_salt(("settings", &setting.key))
                            .selected_text(options.get(selected).cloned().unwrap_or_default())
                            .show_ui(ui, |ui| {
                                for (index, option) in options.iter().enumerate() {
                                    if ui.selectable_value(&mut selected, index, option).clicked() {
                                        self.values
                                            .insert(setting.key.clone(), SettingValue::Text(option.clone()));
                                        changed = true;
                                    }
                                }
                            });
                    });
                }
            }
            if let Some(description) = &setting.description {
                ui.label(egui::RichText::new(description).small().weak());
            }
        }
        changed
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn values_are_typed() {
        let form = SettingsSchema::new()
            .add(Setting::new("on", "On", SettingKind::Bool), SettingValue::Bool(true))
            .add(
                Setting::new("size", "Size", SettingKind::Number { min: 0.0, max: 10.0 }),
                SettingValue::Number(4.0),
            );
        assert!(form.bool("on"));
        assert_eq!(form.number("size"), 4.0);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn a_json_schema_becomes_a_form() {
        let schema = serde_json::json!({
            "properties": {
                "enabled": {"type": "boolean", "title": "Enabled", "default": true},
                "count": {"type": "integer", "minimum": 1, "maximum": 5},
                "mode": {"type": "string", "enum": ["fast", "safe"]}
            }
        });
        let form = SettingsSchema::from_schema(&schema).expect("schema");
        assert_eq!(form.settings.len(), 3);
        assert!(form.bool("enabled"));
        assert_eq!(form.text("mode"), "fast");
    }
}