Skip to main content

egui_pop_model/admin/
hooks.rs

1//! Form hooks: Rust functions registered by name and named by a manifest
2//! ([`super::FieldHooks`], [`super::Action::confirm`],
3//! [`super::StatusSource::Hook`]). They compute; they never draw.
4
5use std::collections::BTreeMap;
6use std::fmt;
7
8use serde::Serialize;
9use serde_json::Value as Json;
10
11use super::Tone;
12
13/// A form's values, by field id.
14pub type Values = BTreeMap<String, Json>;
15
16/// What a `validate` hook says of a field (or of the form, key `""`).
17#[derive(Clone, Debug, PartialEq, Serialize)]
18pub struct Problem {
19    pub field: String,
20    pub tone: Tone,
21    pub message: String,
22}
23
24/// A choice a `choices` hook offers: its value, label and hint.
25#[derive(Clone, Debug, PartialEq, Serialize)]
26pub struct Choice {
27    pub value: String,
28    pub label: String,
29    pub hint: String,
30}
31
32/// A confirmation a `confirm` hook asks for.
33#[derive(Clone, Debug, PartialEq, Serialize)]
34pub struct Confirm {
35    pub message: String,
36    pub verb: String,
37    pub danger: bool,
38}
39
40pub type ValidateFn = Box<dyn Fn(&Values) -> Vec<Problem> + Send + Sync>;
41pub type ChoicesFn = Box<dyn Fn(&Values) -> Vec<Choice> + Send + Sync>;
42pub type PreviewFn = Box<dyn Fn(&Values) -> String + Send + Sync>;
43/// Stored to shown (`false`) or shown to stored (`true`).
44pub type TransformFn = Box<dyn Fn(&Json, bool) -> Json + Send + Sync>;
45pub type ConfirmFn = Box<dyn Fn(&Values) -> Option<Confirm> + Send + Sync>;
46pub type StatusFn = Box<dyn Fn() -> (String, Tone) + Send + Sync>;
47/// The records of a list or table, each an object.
48pub type RecordsFn = Box<dyn Fn() -> Vec<Json> + Send + Sync>;
49
50/// A hook of one of the kinds the note lists.
51pub enum Hook {
52    Validate(ValidateFn),
53    Choices(ChoicesFn),
54    Preview(PreviewFn),
55    Transform(TransformFn),
56    Confirm(ConfirmFn),
57    Status(StatusFn),
58    Records(RecordsFn),
59}
60
61impl Hook {
62    pub fn kind(&self) -> &'static str {
63        match self {
64            Hook::Validate(_) => "validate",
65            Hook::Choices(_) => "choices",
66            Hook::Preview(_) => "preview",
67            Hook::Transform(_) => "transform",
68            Hook::Confirm(_) => "confirm",
69            Hook::Status(_) => "status",
70            Hook::Records(_) => "records",
71        }
72    }
73}
74
75impl fmt::Debug for Hook {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        write!(f, "Hook::{}", self.kind())
78    }
79}
80
81/// The registered hooks, by name.
82#[derive(Debug, Default)]
83pub struct Hooks(BTreeMap<String, Hook>);
84
85impl Hooks {
86    pub fn new() -> Hooks {
87        Hooks::default()
88    }
89
90    /// Registers a hook; `false` when the name is taken (the first
91    /// stays).
92    pub fn register(&mut self, name: &str, hook: Hook) -> bool {
93        if self.0.contains_key(name) {
94            return false;
95        }
96        self.0.insert(name.into(), hook);
97        true
98    }
99
100    pub fn get(&self, name: &str) -> Option<&Hook> {
101        self.0.get(name)
102    }
103
104    /// The names and kinds, for agents.
105    pub fn list(&self) -> Vec<(&str, &'static str)> {
106        self.0.iter().map(|(k, h)| (k.as_str(), h.kind())).collect()
107    }
108
109    /// Runs a `validate` hook; nothing when it is missing or of another
110    /// kind.
111    pub fn validate(&self, name: &str, values: &Values) -> Vec<Problem> {
112        match self.get(name) {
113            Some(Hook::Validate(f)) => f(values),
114            _ => Vec::new(),
115        }
116    }
117
118    pub fn choices(&self, name: &str, values: &Values) -> Option<Vec<Choice>> {
119        match self.get(name) {
120            Some(Hook::Choices(f)) => Some(f(values)),
121            _ => None,
122        }
123    }
124
125    pub fn preview(&self, name: &str, values: &Values) -> Option<String> {
126        match self.get(name) {
127            Some(Hook::Preview(f)) => Some(f(values)),
128            _ => None,
129        }
130    }
131
132    pub fn records(&self, name: &str) -> Option<Vec<Json>> {
133        match self.get(name) {
134            Some(Hook::Records(f)) => Some(f()),
135            _ => None,
136        }
137    }
138
139    /// Runs a `confirm` hook: the confirmation it asks for, if any.
140    pub fn confirm(&self, name: &str, values: &Values) -> Option<Confirm> {
141        match self.get(name) {
142            Some(Hook::Confirm(f)) => f(values),
143            _ => None,
144        }
145    }
146
147    pub fn status(&self, name: &str) -> Option<(String, Tone)> {
148        match self.get(name) {
149            Some(Hook::Status(f)) => Some(f()),
150            _ => None,
151        }
152    }
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158    use serde_json::json;
159
160    #[test]
161    fn hooks_compute_by_name() {
162        let mut h = Hooks::new();
163        assert!(h.register(
164            "positive",
165            Hook::Validate(Box::new(|v| {
166                v.iter()
167                    .filter(|(_, x)| x.as_f64().is_some_and(|n| n < 0.0))
168                    .map(|(k, _)| Problem {
169                        field: k.clone(),
170                        tone: Tone::Danger,
171                        message: "Must be positive.".into(),
172                    })
173                    .collect()
174            }))
175        ));
176        assert!(!h.register("positive", Hook::Preview(Box::new(|_| String::new()))));
177        let mut v = Values::new();
178        v.insert("a".into(), json!(-1));
179        v.insert("b".into(), json!(2));
180        let p = h.validate("positive", &v);
181        assert_eq!(p.len(), 1);
182        assert_eq!(p[0].field, "a");
183        assert!(h.validate("missing", &v).is_empty());
184        assert_eq!(h.list(), vec![("positive", "validate")]);
185    }
186}