Skip to main content

oino_ui/extras/
toggle.rs

1//! `Toggle` node (§4.5.2).
2
3use serde::{Deserialize, Serialize};
4
5use crate::node::{ActionId, Common, IntoNode, Key, Node};
6use crate::text::Line;
7
8/// A boolean switch (§4.5.2).
9#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
10#[serde(rename_all = "camelCase")]
11pub struct Toggle {
12    /// Common node props (`key` is required for `Toggle`).
13    #[serde(flatten)]
14    pub common: Common,
15    /// Switch label.
16    pub label: Line,
17    /// Current value (wins when it changes, §4.6).
18    pub value: bool,
19    /// Greyed out.
20    #[serde(default, skip_serializing_if = "Option::is_none")]
21    pub disabled: Option<bool>,
22    /// Action on change (the new bool).
23    #[serde(default, skip_serializing_if = "Option::is_none")]
24    pub on_change: Option<ActionId>,
25}
26
27impl Toggle {
28    /// A toggle with `key`, label and value.
29    #[must_use]
30    pub fn new(key: impl Into<Key>, label: impl Into<Line>, value: bool) -> Self {
31        let mut common = Common::new();
32        common.key = Some(key.into());
33        Self {
34            common,
35            label: label.into(),
36            value,
37            disabled: None,
38            on_change: None,
39        }
40    }
41
42    /// Greys the toggle out.
43    #[must_use]
44    pub fn disabled(mut self, disabled: bool) -> Self {
45        self.disabled = Some(disabled);
46        self
47    }
48
49    /// Sets the change action.
50    #[must_use]
51    pub fn on_change(mut self, action: impl Into<ActionId>) -> Self {
52        self.on_change = Some(action.into());
53        self
54    }
55}
56
57impl IntoNode for Toggle {}
58impl From<Toggle> for Node {
59    fn from(t: Toggle) -> Self {
60        Node::Toggle(t)
61    }
62}