laterite-admin 0.9.12

Laterite CMF admin surface: the Axum router, session middleware, and login shell
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
//! The admin's menu: a registry of items that modules, resources and screens
//! contribute as data, resolved once at boot into a tree and filtered per
//! request by what the operator may see.
//!
//! A top-level item is a tab in the top bar. An item placed under another
//! makes that one a section: the tab leads to the section's first visible
//! entry and the entries show in the context sidebar. Every item carries the
//! permission its target requires, so an operator never sees a tab that would
//! refuse them.

use laterite_core::Text;
use serde::{Deserialize, Serialize};

use crate::settings::{CategoryView, ItemView};

/// One menu entry: a tab, or an entry under a section.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
#[non_exhaustive]
pub struct NavItem {
    /// Unique among every item (`acme.posts`): what another item names in
    /// `under`.
    pub key: String,
    pub label: Text,
    /// The path under the admin mount (`/posts`). A section may have none: its
    /// tab then leads to its first visible entry.
    pub path: Option<String>,
    /// An icon name from the icon set.
    pub icon: Option<String>,
    /// What the operator must hold to see the entry. `None` shows it to every
    /// signed-in operator; a section with no path shows when any entry does.
    pub permission: Option<String>,
    /// Sorts among siblings, lowest first; equal orders sort by label.
    pub order: i32,
    /// Sits right after the sibling with this key, whatever the orders say.
    pub after: Option<String>,
    /// Sits right before the sibling with this key, whatever the orders say.
    pub before: Option<String>,
    /// The key of the item this sits under; `None` is the top bar.
    pub under: Option<String>,
}

impl NavItem {
    /// An entry leading to `path`.
    pub fn new(key: impl Into<String>, label: impl Into<Text>, path: impl Into<String>) -> Self {
        Self {
            key: key.into(),
            label: label.into(),
            path: Some(path.into()),
            icon: None,
            permission: None,
            order: 0,
            after: None,
            before: None,
            under: None,
        }
    }

    /// A section: a tab that holds entries and leads to the first one.
    pub fn section(key: impl Into<String>, label: impl Into<Text>) -> Self {
        Self {
            key: key.into(),
            label: label.into(),
            path: None,
            icon: None,
            permission: None,
            order: 0,
            after: None,
            before: None,
            under: None,
        }
    }

    pub fn icon(mut self, icon: impl Into<String>) -> Self {
        self.icon = Some(icon.into());
        self
    }

    pub fn permission(mut self, permission: impl Into<String>) -> Self {
        self.permission = Some(permission.into());
        self
    }

    pub fn order(mut self, order: i32) -> Self {
        self.order = order;
        self
    }

    /// Places the entry under the section with this key.
    pub fn under(mut self, section: impl Into<String>) -> Self {
        self.under = Some(section.into());
        self
    }

    /// Sits right after the sibling with this key.
    pub fn after(mut self, key: impl Into<String>) -> Self {
        self.after = Some(key.into());
        self
    }

    /// Sits right before the sibling with this key.
    pub fn before(mut self, key: impl Into<String>) -> Self {
        self.before = Some(key.into());
        self
    }
}

impl Default for NavItem {
    fn default() -> Self {
        Self::section("", "")
    }
}

/// Where a resource or a screen sits in the menu: under which section, with
/// which icon, at which position; or out of the menu altogether.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
#[non_exhaustive]
pub struct Placement {
    /// The key of the section to sit under; `None` is the top bar.
    pub under: Option<String>,
    pub icon: Option<String>,
    pub order: i32,
    /// Sits right after the sibling with this key (a resource's key is
    /// `resource:` and its path, a screen's `screen:` and its path).
    pub after: Option<String>,
    /// Sits right before the sibling with this key.
    pub before: Option<String>,
    /// Mounted and reachable by link, with no menu entry.
    pub hidden: bool,
}

impl Placement {
    pub fn new() -> Self {
        Self::default()
    }

    /// Out of the menu: the routes mount, a link elsewhere reaches them.
    pub fn hidden() -> Self {
        Self {
            hidden: true,
            ..Self::default()
        }
    }

    pub fn under(mut self, section: impl Into<String>) -> Self {
        self.under = Some(section.into());
        self
    }

    pub fn icon(mut self, icon: impl Into<String>) -> Self {
        self.icon = Some(icon.into());
        self
    }

    pub fn order(mut self, order: i32) -> Self {
        self.order = order;
        self
    }

    /// Sits right after the sibling with this key.
    pub fn after(mut self, key: impl Into<String>) -> Self {
        self.after = Some(key.into());
        self
    }

    /// Sits right before the sibling with this key.
    pub fn before(mut self, key: impl Into<String>) -> Self {
        self.before = Some(key.into());
        self
    }
}

/// `menu: false` hides; `menu: { under, icon, order, after, before }` places.
pub(crate) fn deserialize_placement<'de, D>(deserializer: D) -> Result<Placement, D::Error>
where
    D: serde::Deserializer<'de>,
{
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum Key {
        Flag(bool),
        Config(Placement),
    }
    Ok(match Option::<Key>::deserialize(deserializer)? {
        Some(Key::Flag(false)) => Placement::hidden(),
        Some(Key::Flag(true)) | None => Placement::default(),
        Some(Key::Config(placement)) => placement,
    })
}

/// One resolved item: its entries beneath it, paths under the admin mount.
#[derive(Clone, Debug)]
pub(crate) struct NavNode {
    pub item: NavItem,
    pub children: Vec<NavNode>,
}

/// The menu as a tree, built once at boot.
#[derive(Debug, Default)]
pub(crate) struct NavTree {
    pub top: Vec<NavNode>,
}

impl NavTree {
    /// Resolves `items` into a tree under `admin_path`. Refuses a duplicate
    /// key, an entry under a key nobody declared, and an entry under an entry
    /// (one level of sections).
    pub(crate) fn build(items: Vec<NavItem>, admin_path: &str) -> Result<Self, String> {
        let mut seen = std::collections::HashSet::new();
        for item in &items {
            if item.key.is_empty() {
                return Err(format!("menu item `{}` has no key", item.label.source()));
            }
            if !seen.insert(item.key.clone()) {
                return Err(format!("duplicate menu key `{}`", item.key));
            }
        }
        let prefixed = |item: &NavItem| {
            let mut item = item.clone();
            item.path = item.path.map(|p| format!("{admin_path}{p}"));
            item
        };
        let mut top: Vec<NavNode> = items
            .iter()
            .filter(|i| i.under.is_none())
            .map(|i| NavNode {
                item: prefixed(i),
                children: Vec::new(),
            })
            .collect();
        for item in items.iter().filter(|i| i.under.is_some()) {
            let under = item.under.as_deref().unwrap_or_default();
            let parent = top
                .iter_mut()
                .find(|n| n.item.key == under)
                .ok_or_else(|| {
                    format!(
                        "menu item `{}` sits under `{under}`, which is no top-level item",
                        item.key
                    )
                })?;
            parent.children.push(NavNode {
                item: prefixed(item),
                children: Vec::new(),
            });
        }
        let by_order = |a: &NavNode, b: &NavNode| {
            a.item
                .order
                .cmp(&b.item.order)
                .then_with(|| a.item.label.source().cmp(b.item.label.source()))
        };
        top.sort_by(by_order);
        anchor(&mut top)?;
        for node in &mut top {
            node.children.sort_by(by_order);
            anchor(&mut node.children)?;
        }
        Ok(Self { top })
    }

    /// The tree as one operator sees it: entries they may not open are gone,
    /// and a section with nothing left beneath it and no page of its own goes
    /// too.
    pub(crate) fn visible(&self, allows: &dyn Fn(&str) -> bool) -> Vec<NavNode> {
        let allowed = |item: &NavItem| item.permission.as_deref().is_none_or(allows);
        self.top
            .iter()
            .filter_map(|node| {
                let children: Vec<NavNode> = node
                    .children
                    .iter()
                    .filter(|c| allowed(&c.item))
                    .cloned()
                    .collect();
                let own = node.item.path.is_some() && allowed(&node.item);
                if !own && children.is_empty() {
                    return None;
                }
                if node.item.path.is_some() && !allowed(&node.item) {
                    return None;
                }
                Some(NavNode {
                    item: node.item.clone(),
                    children,
                })
            })
            .collect()
    }
}

/// Moves each anchored sibling next to its anchor, in order of appearance,
/// so `after: acme.posts` holds whatever the orders say. An anchor that is
/// no sibling is refused.
fn anchor(nodes: &mut Vec<NavNode>) -> Result<(), String> {
    let keys: Vec<String> = nodes.iter().map(|n| n.item.key.clone()).collect();
    for key in keys {
        let at = nodes.iter().position(|n| n.item.key == key).unwrap_or(0);
        let (anchor_key, after) = match (&nodes[at].item.after, &nodes[at].item.before) {
            (Some(a), _) => (a.clone(), true),
            (None, Some(b)) => (b.clone(), false),
            (None, None) => continue,
        };
        let target = nodes
            .iter()
            .position(|n| n.item.key == anchor_key)
            .ok_or_else(|| {
                format!(
                    "menu item `{key}` is placed {} `{anchor_key}`, which is no sibling of it",
                    if after { "after" } else { "before" }
                )
            })?;
        if target == at {
            return Err(format!("menu item `{key}` is placed next to itself"));
        }
        let node = nodes.remove(at);
        let target = nodes
            .iter()
            .position(|n| n.item.key == anchor_key)
            .unwrap_or(0);
        nodes.insert(if after { target + 1 } else { target }, node);
    }
    Ok(())
}

/// The preference key holding an operator's own order for the top bar.
pub(crate) const ORDER_PREFERENCE: &str = "menu.order";

/// Puts the top-level nodes in the operator's own order: the keys in `order`
/// (comma-separated) first, as listed, then the rest as they were. Dashboard
/// stays first and Settings last whatever the order says, and a key that is
/// no tab is ignored, so a stale preference never hides anything.
pub(crate) fn apply_order(nodes: &mut Vec<NavNode>, order: &str) {
    let wanted: Vec<&str> = order
        .split(',')
        .map(str::trim)
        .filter(|k| !k.is_empty())
        .collect();
    if wanted.is_empty() {
        return;
    }
    let fixed = |key: &str| key == "dashboard" || key == "settings";
    let mut rest: Vec<NavNode> = std::mem::take(nodes);
    let mut ordered: Vec<NavNode> = Vec::with_capacity(rest.len());
    for key in wanted {
        if fixed(key) {
            continue;
        }
        if let Some(at) = rest.iter().position(|n| n.item.key == key) {
            ordered.push(rest.remove(at));
        }
    }
    let mut tail: Vec<NavNode> = Vec::new();
    for node in rest {
        if node.item.key == "dashboard" {
            ordered.insert(0, node);
        } else if node.item.key == "settings" {
            tail.push(node);
        } else {
            ordered.push(node);
        }
    }
    ordered.extend(tail);
    *nodes = ordered;
}

/// The path a top-level node's tab leads to: its own, or its first entry's.
pub(crate) fn tab_path(node: &NavNode) -> Option<&str> {
    node.item
        .path
        .as_deref()
        .or_else(|| node.children.first().and_then(|c| c.item.path.as_deref()))
}

/// Whether `path` is on `target` or beneath it.
fn within(path: &str, target: &str, admin_path: &str) -> bool {
    path == target || (target != admin_path && path.starts_with(&format!("{target}/")))
}

/// The key of the top-level node `path` falls under, by the longest match
/// over its own path and its entries' paths.
pub(crate) fn active_top<'a>(
    visible: &'a [NavNode],
    admin_path: &str,
    path: &str,
) -> Option<&'a NavNode> {
    let mut best: Option<(&NavNode, usize)> = None;
    for node in visible {
        let candidates = node
            .item
            .path
            .iter()
            .chain(node.children.iter().filter_map(|c| c.item.path.as_ref()));
        for target in candidates {
            if within(path, target, admin_path) && best.is_none_or(|(_, len)| target.len() > len) {
                best = Some((node, target.len()));
            }
        }
    }
    best.map(|(node, _)| node)
}

/// The context sidebar for a section: its entries as one group, the one
/// `path` falls under marked active.
pub(crate) fn section_sidebar(
    node: &NavNode,
    admin_path: &str,
    path: &str,
    tr: &laterite_core::Translator,
    icons: crate::icons::Icons<'_>,
) -> Vec<CategoryView> {
    if node.children.is_empty() {
        return Vec::new();
    }
    let active = node
        .children
        .iter()
        .filter(|c| {
            c.item
                .path
                .as_deref()
                .is_some_and(|p| within(path, p, admin_path))
        })
        .max_by_key(|c| c.item.path.as_deref().map(str::len).unwrap_or(0))
        .map(|c| c.item.key.clone());
    vec![CategoryView::new(
        tr.t(&node.item.label),
        node.children
            .iter()
            .map(|c| ItemView {
                label: tr.t(&c.item.label),
                description: String::new(),
                path: c.item.path.clone().unwrap_or_default(),
                icon: icons.render(c.item.icon.as_deref()),
                active: active.as_deref() == Some(c.item.key.as_str()),
            })
            .collect(),
    )]
}

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

    fn items() -> Vec<NavItem> {
        vec![
            NavItem::new("dashboard", "Dashboard", "").order(i32::MIN),
            NavItem::section("content", "Content").order(10),
            NavItem::new("acme.posts", "Posts", "/posts")
                .under("content")
                .permission("acme.posts")
                .order(2),
            NavItem::new("acme.pages", "Pages", "/pages")
                .under("content")
                .permission("acme.pages")
                .order(1),
            NavItem::new("acme.shop", "Shop", "/shop")
                .permission("acme.shop")
                .order(20),
            NavItem::new("settings", "Settings", "/settings").order(i32::MAX),
        ]
    }

    #[test]
    fn a_tree_sorts_and_prefixes() {
        let tree = NavTree::build(items(), "/admin").unwrap();
        let keys: Vec<&str> = tree.top.iter().map(|n| n.item.key.as_str()).collect();
        assert_eq!(keys, ["dashboard", "content", "acme.shop", "settings"]);
        let content = &tree.top[1];
        let entries: Vec<&str> = content
            .children
            .iter()
            .map(|n| n.item.key.as_str())
            .collect();
        assert_eq!(
            entries,
            ["acme.pages", "acme.posts"],
            "by order, then label"
        );
        assert_eq!(
            content.children[0].item.path.as_deref(),
            Some("/admin/pages")
        );
        assert_eq!(tab_path(content), Some("/admin/pages"));
    }

    #[test]
    fn an_anchor_holds_whatever_the_orders_say() {
        let mut items = items();
        items.push(
            NavItem::new("acme.help", "Help", "/help")
                .order(0)
                .after("acme.shop"),
        );
        items.push(
            NavItem::new("acme.tags", "Tags", "/tags")
                .under("content")
                .order(99)
                .before("acme.pages"),
        );
        let tree = NavTree::build(items, "/admin").unwrap();
        let keys: Vec<&str> = tree.top.iter().map(|n| n.item.key.as_str()).collect();
        assert_eq!(
            keys,
            ["dashboard", "content", "acme.shop", "acme.help", "settings"]
        );
        let entries: Vec<&str> = tree.top[1]
            .children
            .iter()
            .map(|n| n.item.key.as_str())
            .collect();
        assert_eq!(entries, ["acme.tags", "acme.pages", "acme.posts"]);

        let mut lost = self::items();
        lost.push(NavItem::new("acme.help", "Help", "/help").after("acme.pages"));
        assert!(
            NavTree::build(lost, "/admin").is_err(),
            "an anchor must be a sibling"
        );
    }

    #[test]
    fn an_operators_order_moves_tabs_but_never_the_ends() {
        let tree = NavTree::build(items(), "/admin").unwrap();
        let mut visible = tree.visible(&|_| true);
        apply_order(&mut visible, "settings,acme.shop,gone,dashboard");
        let keys: Vec<&str> = visible.iter().map(|n| n.item.key.as_str()).collect();
        assert_eq!(keys, ["dashboard", "acme.shop", "content", "settings"]);
        apply_order(&mut visible, "");
        let keys: Vec<&str> = visible.iter().map(|n| n.item.key.as_str()).collect();
        assert_eq!(
            keys,
            ["dashboard", "acme.shop", "content", "settings"],
            "blank changes nothing"
        );
    }

    #[test]
    fn a_duplicate_key_and_an_unknown_section_are_refused() {
        let mut dup = items();
        dup.push(NavItem::new("acme.shop", "Again", "/again"));
        assert!(NavTree::build(dup, "/admin").is_err());
        let mut orphan = items();
        orphan.push(NavItem::new("acme.lost", "Lost", "/lost").under("nowhere"));
        assert!(NavTree::build(orphan, "/admin").is_err());
    }

    #[test]
    fn an_operator_sees_only_what_they_may_open() {
        let tree = NavTree::build(items(), "/admin").unwrap();
        let visible = tree.visible(&|code| code == "acme.posts");
        let keys: Vec<&str> = visible.iter().map(|n| n.item.key.as_str()).collect();
        assert_eq!(keys, ["dashboard", "content", "settings"], "no shop");
        assert_eq!(visible[1].children.len(), 1, "only posts under content");
        assert_eq!(tab_path(&visible[1]), Some("/admin/posts"));
        let none = tree.visible(&|_| false);
        let keys: Vec<&str> = none.iter().map(|n| n.item.key.as_str()).collect();
        assert_eq!(keys, ["dashboard", "settings"], "an empty section goes");
    }

    #[test]
    fn the_active_tab_is_the_longest_match() {
        let tree = NavTree::build(items(), "/admin").unwrap();
        let visible = tree.visible(&|_| true);
        let at = |path: &str| active_top(&visible, "/admin", path).map(|n| n.item.key.clone());
        assert_eq!(at("/admin/posts/3/edit").as_deref(), Some("content"));
        assert_eq!(at("/admin/shop").as_deref(), Some("acme.shop"));
        assert_eq!(at("/admin/settings/users").as_deref(), Some("settings"));
        assert_eq!(at("/admin").as_deref(), Some("dashboard"));
        assert_eq!(at("/admin/elsewhere"), None);
    }
}