Skip to main content

egui_pop_model/admin/
generate.rs

1//! The pages of today's settings, generated from their declarations: a
2//! scope from the setting id's prefix (`appearance.*` to Interface,
3//! `input.*` to Input, `developer.*` to Developer, the rest to General),
4//! a section per settings section (the owner's title, or an alter hook's),
5//! a field per setting. No hand-written page.
6
7use super::{FORMAT, Field, Group, Item, Manifest, Meta, Scope, Section};
8
9/// The default scopes: id, title, icon, order. The orders leave room
10/// between them, so an application's scopes take their place in the
11/// note's order (section 6: Library 30, Storage 40, Backup 50, Import and
12/// export 60, Hardware 70, Plugins 80, Health 90, Jobs 100), Developer
13/// last.
14pub const SCOPES: [(&str, &str, &str, i32); 4] = [
15    ("general", "General", "settings", 0),
16    ("interface", "Interface", "palette", 10),
17    ("input", "Input", "keyboard", 20),
18    ("developer", "Developer", "code", 110),
19];
20
21/// A setting as the generator takes it: its id and its section's title.
22#[derive(Clone, Debug, PartialEq)]
23pub struct Entry<'a> {
24    pub id: &'a str,
25    pub section: &'a str,
26}
27
28/// The scope a setting goes to by default.
29pub fn scope_of(id: &str) -> &'static str {
30    let prefix = id.split('.').next().unwrap_or("");
31    match prefix {
32        "appearance" | "window" | "menus" | "dialogs" | "workbench" | "palettes" | "theme" => {
33            "interface"
34        }
35        "input" | "keys" | "pointer" => "input",
36        "developer" | "debug" => "developer",
37        _ => "general",
38    }
39}
40
41/// A section id from its title: lower case, words joined by `-`.
42pub fn slug(title: &str) -> String {
43    let mut out = String::new();
44    for w in title
45        .split(|c: char| !c.is_alphanumeric())
46        .filter(|w| !w.is_empty())
47    {
48        if !out.is_empty() {
49            out.push('-');
50        }
51        out.push_str(&w.to_lowercase());
52    }
53    if out.is_empty() {
54        "settings".into()
55    } else {
56        out
57    }
58}
59
60/// The manifest of the settings: the default scopes, a section per
61/// (scope, section title) in the settings' order.
62pub fn settings<'a>(entries: impl IntoIterator<Item = Entry<'a>>) -> Manifest {
63    let mut m = Manifest::new(FORMAT);
64    for (id, title, icon, order) in SCOPES {
65        m.scopes.push(Scope {
66            meta: Meta {
67                icon: Some(icon.into()),
68                order,
69                ..Meta::new(id, title)
70            },
71        });
72    }
73    for e in entries {
74        let scope = scope_of(e.id);
75        let id = slug(e.section);
76        let section = match m
77            .sections
78            .iter_mut()
79            .position(|s| s.scope == scope && s.meta.id == id)
80        {
81            Some(i) => &mut m.sections[i],
82            None => {
83                // An explicit order: the generated pages keep their
84                // place among the manifests' (docs/design/admin-forms.md,
85                // "Ordering").
86                let order = m.sections.len() as i32;
87                m.sections.push(Section {
88                    meta: Meta {
89                        order,
90                        ..Meta::new(&id, e.section)
91                    },
92                    scope: scope.into(),
93                    groups: vec![Group {
94                        meta: Meta::new("main", ""),
95                        items: Vec::new(),
96                    }],
97                    ..Section::default()
98                });
99                m.sections.last_mut().expect("just pushed")
100            }
101        };
102        section.groups[0]
103            .items
104            .push(Item::Field(Field::setting(e.id)));
105    }
106    m
107}
108
109#[cfg(test)]
110mod tests {
111    use super::*;
112    use crate::admin::Tree;
113
114    #[test]
115    fn settings_are_placed_by_prefix_and_section() {
116        let m = settings([
117            Entry {
118                id: "appearance.theme_preference",
119                section: "Appearance",
120            },
121            Entry {
122                id: "input.wheel_speed",
123                section: "Input",
124            },
125            Entry {
126                id: "appearance.text_size",
127                section: "Appearance",
128            },
129            Entry {
130                id: "gallery.size",
131                section: "Gallery settings",
132            },
133            Entry {
134                id: "developer.devtools",
135                section: "Developer tools",
136            },
137        ]);
138        let mut t = Tree::default();
139        t.merge(m.clone());
140        let paths: Vec<String> = t.sections.iter().map(|s| s.path()).collect();
141        assert_eq!(
142            paths,
143            [
144                "interface/appearance",
145                "input/input",
146                "general/gallery-settings",
147                "developer/developer-tools"
148            ]
149        );
150        assert_eq!(t.sections[0].groups[0].items.len(), 2);
151        assert_eq!(t.shown_scopes().len(), 4);
152        // Generated manifests round-trip like any other.
153        assert_eq!(Manifest::from_json(&m.to_json()).unwrap(), m);
154    }
155
156    #[test]
157    fn an_application_scope_takes_its_place_by_order() {
158        let mut t = Tree::default();
159        t.merge(settings([]));
160        t.merge(Manifest::new(FORMAT).scope_at("library", "Library", "book", 30));
161        let ids: Vec<&str> = t.scopes.iter().map(|s| s.meta.id.as_str()).collect();
162        assert_eq!(
163            ids,
164            ["general", "interface", "input", "library", "developer"]
165        );
166    }
167
168    #[test]
169    fn slugs_are_stable() {
170        assert_eq!(slug("Gallery settings"), "gallery-settings");
171        assert_eq!(slug("  "), "settings");
172        assert_eq!(slug("Files & folders"), "files-folders");
173    }
174}