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
|
// -*- coding: utf-8 -*-
//
// Simple CMS
//
// Copyright (C) 2011-2024 Michael Büsch <m@bues.ch>
//
// Licensed under the Apache License version 2.0
// or the MIT license, at your option.
// SPDX-License-Identifier: Apache-2.0 OR MIT
use crate::comm::{CmsComm, CommSubPages};
use cms_ident::CheckedIdent;
use std::cmp::Ordering;
const MAX_DEPTH: usize = 64;
fn elem_sort_cmp(a: &NavElem, b: &NavElem) -> Ordering {
// compare a(prio|nav_label.lower) to b(prio|nav_label.lower)
if a.prio() == b.prio() {
let a = a.nav_label().trim().to_lowercase();
let b = b.nav_label().trim().to_lowercase();
a.cmp(&b)
} else {
a.prio().cmp(&b.prio())
}
}
#[derive(Clone, Debug)]
pub struct NavElem {
name: String,
nav_label: String,
path: CheckedIdent,
prio: u64,
active: bool,
children: Vec<NavElem>,
}
impl NavElem {
#[allow(dead_code)]
pub fn name(&self) -> &str {
&self.name
}
pub fn nav_label(&self) -> &str {
&self.nav_label
}
pub fn path(&self) -> &CheckedIdent {
&self.path
}
pub fn prio(&self) -> u64 {
self.prio
}
pub fn active(&self) -> bool {
self.active
}
pub fn children(&self) -> &[NavElem] {
&self.children
}
}
#[derive(Clone, Debug)]
pub struct NavTree {
tree: Vec<NavElem>,
}
impl NavTree {
pub async fn build(
comm: &mut CmsComm,
root_page: &CheckedIdent,
active_page: Option<&CheckedIdent>,
) -> Self {
let tree = Self::build_sub(comm, root_page, active_page, 0).await;
Self { tree }
}
async fn build_sub(
comm: &mut CmsComm,
base: &CheckedIdent,
active: Option<&CheckedIdent>,
depth: usize,
) -> Vec<NavElem> {
if depth >= MAX_DEPTH {
return vec![];
}
let Ok(CommSubPages {
names,
nav_labels,
nav_stops,
prios,
..
}) = comm.get_db_sub_pages(base).await
else {
return vec![];
};
let count = names.len();
let mut ret = Vec::with_capacity(count);
for i in 0..count {
let sub_nav_label = &nav_labels[i];
if sub_nav_label.trim().is_empty() {
continue;
}
let sub_name = &names[i];
let Ok(sub_ident) = base.clone_append(sub_name).into_checked() else {
continue;
};
let sub_prio = prios[i];
let sub_nav_stop = nav_stops[i];
let sub_active = active
.map(|a| a.starts_with(sub_ident.as_downgrade_ref()))
.unwrap_or(false);
let sub_children = if sub_nav_stop {
vec![]
} else {
Box::pin(Self::build_sub(comm, &sub_ident, active, depth + 1)).await
};
ret.push(NavElem {
name: sub_name.clone(),
nav_label: sub_nav_label.clone(),
path: sub_ident,
prio: sub_prio,
active: sub_active,
children: sub_children,
});
}
ret.sort_unstable_by(elem_sort_cmp);
ret
}
pub fn elems(&self) -> &[NavElem] {
&self.tree
}
}
// vim: ts=4 sw=4 expandtab
|