1use serde::{Deserialize, Serialize};
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
20pub enum ItemKind {
21 Standard,
23 Separator,
25 Checkmark,
27}
28
29#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
37pub struct MenuItem {
38 pub id: i32,
39 pub label: String,
40 pub enabled: bool,
41 pub visible: bool,
42 pub kind: ItemKind,
43 pub toggle: Option<bool>,
45 pub action: Option<String>,
51 pub children: Vec<MenuItem>,
52}
53
54impl MenuItem {
55 pub fn standard(label: impl Into<String>, action: impl Into<String>) -> Self {
56 MenuItem {
57 id: 0,
58 label: label.into(),
59 enabled: true,
60 visible: true,
61 kind: ItemKind::Standard,
62 toggle: None,
63 action: Some(action.into()),
64 children: Vec::new(),
65 }
66 }
67
68 pub fn checkmark(label: impl Into<String>, on: bool, action: impl Into<String>) -> Self {
69 MenuItem {
70 toggle: Some(on),
71 kind: ItemKind::Checkmark,
72 ..MenuItem::standard(label, action)
73 }
74 }
75
76 pub fn separator() -> Self {
77 MenuItem {
78 id: 0,
79 label: String::new(),
80 enabled: false,
81 visible: true,
82 kind: ItemKind::Separator,
83 toggle: None,
84 action: None,
85 children: Vec::new(),
86 }
87 }
88
89 pub fn disabled(label: impl Into<String>) -> Self {
92 MenuItem {
93 enabled: false,
94 action: None,
95 ..MenuItem::standard(label, "")
96 }
97 }
98
99 pub fn disabled_checkmark(label: impl Into<String>, on: bool) -> Self {
105 MenuItem {
106 kind: ItemKind::Checkmark,
107 toggle: Some(on),
108 ..MenuItem::disabled(label)
109 }
110 }
111}
112
113pub fn radio_menu(top: Vec<MenuItem>, content: Vec<MenuItem>, settings: MenuItem) -> Menu {
135 let mut items = top;
136 if !content.is_empty() {
137 items.push(MenuItem::separator());
138 items.extend(content);
139 }
140 items.push(MenuItem::separator());
141 items.push(settings);
142 Menu::new(items)
143}
144
145#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
147pub struct Menu {
148 pub items: Vec<MenuItem>,
149}
150
151impl Menu {
152 pub fn new(items: Vec<MenuItem>) -> Self {
156 let mut menu = Menu { items };
157 let mut next = 1;
158 assign_ids(&mut menu.items, &mut next);
159 menu
160 }
161
162 pub fn action_for(&self, id: i32) -> Option<&str> {
164 find(&self.items, id).and_then(|item| item.action.as_deref())
165 }
166
167 pub fn find(&self, id: i32) -> Option<&MenuItem> {
168 find(&self.items, id)
169 }
170
171 pub fn flatten(&self) -> Vec<&MenuItem> {
173 let mut out = Vec::new();
174 collect(&self.items, &mut out);
175 out
176 }
177}
178
179fn assign_ids(items: &mut [MenuItem], next: &mut i32) {
180 for item in items {
181 item.id = *next;
182 *next += 1;
183 assign_ids(&mut item.children, next);
184 }
185}
186
187fn find(items: &[MenuItem], id: i32) -> Option<&MenuItem> {
188 for item in items {
189 if item.id == id {
190 return Some(item);
191 }
192 if let Some(found) = find(&item.children, id) {
193 return Some(found);
194 }
195 }
196 None
197}
198
199fn collect<'a>(items: &'a [MenuItem], out: &mut Vec<&'a MenuItem>) {
200 for item in items {
201 out.push(item);
202 collect(&item.children, out);
203 }
204}
205
206#[cfg(test)]
207mod tests {
208 use super::*;
209
210 fn sample() -> Menu {
211 Menu::new(vec![
212 MenuItem::checkmark("Wi-Fi", true, "radio:toggle"),
213 MenuItem::separator(),
214 MenuItem::standard("home", "connect:home"),
215 MenuItem::disabled("guest (enterprise)"),
216 MenuItem::separator(),
217 MenuItem::standard("Network settings…", "settings"),
218 ])
219 }
220
221 #[test]
224 fn rows_are_numbered_from_one_because_zero_is_the_root() {
225 let menu = sample();
226 assert!(menu.items.iter().all(|i| i.id > 0));
227 assert_eq!(menu.items[0].id, 1);
228 }
229
230 #[test]
231 fn every_row_has_its_own_id_including_nested_ones() {
232 let menu = Menu::new(vec![
233 MenuItem::standard("a", "a"),
234 MenuItem {
235 children: vec![MenuItem::standard("c", "c"), MenuItem::standard("d", "d")],
236 ..MenuItem::standard("b", "b")
237 },
238 ]);
239 let ids: Vec<i32> = menu.flatten().iter().map(|i| i.id).collect();
240 let mut unique = ids.clone();
241 unique.sort_unstable();
242 unique.dedup();
243 assert_eq!(ids.len(), unique.len(), "ids collide: {ids:?}");
244 assert_eq!(ids.len(), 4);
245 }
246
247 #[test]
250 fn a_click_id_resolves_to_the_action_that_row_stood_for() {
251 let menu = sample();
252 let home = menu.flatten().iter().find(|i| i.label == "home").unwrap().id;
253 assert_eq!(menu.action_for(home), Some("connect:home"));
254 }
255
256 #[test]
260 fn a_row_that_does_nothing_resolves_to_no_action_rather_than_the_next_one() {
261 let menu = sample();
262 let sep = menu.flatten().iter().find(|i| i.kind == ItemKind::Separator).unwrap().id;
263 assert_eq!(menu.action_for(sep), None);
264
265 let disabled = menu
266 .flatten()
267 .iter()
268 .find(|i| i.label.contains("enterprise"))
269 .unwrap()
270 .id;
271 assert_eq!(menu.action_for(disabled), None);
272 }
273
274 #[test]
275 fn an_unknown_id_resolves_to_nothing_rather_than_panicking() {
276 assert_eq!(sample().action_for(9999), None);
277 assert!(sample().find(9999).is_none());
278 }
279
280 #[test]
283 fn only_a_checkmark_carries_a_toggle_state() {
284 let menu = sample();
285 for item in menu.flatten() {
286 match item.kind {
287 ItemKind::Checkmark => assert!(item.toggle.is_some()),
288 _ => assert!(item.toggle.is_none(), "{} carries a toggle", item.label),
289 }
290 }
291 }
292
293 #[test]
296 fn a_disabled_checkmark_still_reports_its_state_but_cannot_be_clicked() {
297 let row = MenuItem::disabled_checkmark("Wi-Fi (blocked by hardware switch)", false);
298 assert_eq!(row.kind, ItemKind::Checkmark);
299 assert_eq!(row.toggle, Some(false));
300 assert!(!row.enabled);
301 assert!(row.action.is_none());
302 }
303
304 #[test]
307 fn radio_menu_with_content_is_toggle_then_content_then_settings_with_separators_between() {
308 let menu = radio_menu(
309 vec![MenuItem::checkmark("Wi-Fi", true, "wifi:radio:off")],
310 vec![MenuItem::standard("home", "wifi:connect:home")],
311 MenuItem::standard("Wi-Fi settings…", "wifi:settings"),
312 );
313 let kinds: Vec<ItemKind> = menu.items.iter().map(|i| i.kind).collect();
314 assert_eq!(
315 kinds,
316 vec![
317 ItemKind::Checkmark,
318 ItemKind::Separator,
319 ItemKind::Standard,
320 ItemKind::Separator,
321 ItemKind::Standard,
322 ]
323 );
324 assert_eq!(menu.items[0].label, "Wi-Fi");
325 assert_eq!(menu.items[2].label, "home");
326 assert_eq!(menu.items[4].label, "Wi-Fi settings…");
327 }
328
329 #[test]
333 fn radio_menu_with_no_content_has_exactly_one_separator() {
334 let menu = radio_menu(
335 vec![MenuItem::checkmark("Keep awake", false, "keepawake:on")],
336 Vec::new(),
337 MenuItem::standard("Keep awake settings…", "keepawake:settings"),
338 );
339 let kinds: Vec<ItemKind> = menu.items.iter().map(|i| i.kind).collect();
340 assert_eq!(kinds, vec![ItemKind::Checkmark, ItemKind::Separator, ItemKind::Standard]);
341 }
342
343 #[test]
346 fn radio_menu_unavailable_still_offers_the_settings_row() {
347 let menu = radio_menu(
348 vec![MenuItem::disabled("Wi-Fi unavailable")],
349 Vec::new(),
350 MenuItem::standard("Wi-Fi settings…", "wifi:settings"),
351 );
352 assert!(!menu.items[0].enabled);
353 assert_eq!(menu.items.last().unwrap().label, "Wi-Fi settings…");
354 assert!(menu.items.last().unwrap().enabled);
355 }
356
357 #[test]
364 fn rows_before_the_settings_row_keep_their_ids_whether_or_not_content_is_present() {
365 let toggle = || MenuItem::checkmark("Wi-Fi", true, "wifi:radio:off");
366 let settings = || MenuItem::standard("Wi-Fi settings…", "wifi:settings");
367
368 let short = radio_menu(vec![toggle()], Vec::new(), settings());
369 let long = radio_menu(
370 vec![toggle()],
371 vec![MenuItem::standard("home", "wifi:connect:home")],
372 settings(),
373 );
374 assert_eq!(short.items[0].id, long.items[0].id, "the toggle is row 1 in both");
375 }
376
377 #[test]
384 fn a_menu_built_for_an_icon_is_never_empty_even_with_nothing_to_toggle() {
385 let menu = radio_menu(vec![MenuItem::disabled("Unavailable")], Vec::new(), MenuItem::standard("Settings…", "settings"));
386 assert!(!menu.items.is_empty());
387 assert_eq!(menu.items.last().map(|i| i.label.as_str()), Some("Settings…"));
388 }
389
390 #[test]
397 fn a_menu_round_trips_through_json_including_a_nested_child() {
398 let menu = radio_menu(
399 vec![MenuItem::checkmark("Wi-Fi", true, "wifi:radio:off")],
400 vec![MenuItem {
401 children: vec![MenuItem::standard("child", "wifi:connect:686f6d65")],
402 ..MenuItem::standard("home", "wifi:connect:686f6d65")
403 }],
404 MenuItem::standard("Wi-Fi settings…", "wifi:settings"),
405 );
406 let json = serde_json::to_string(&menu).expect("a menu always serialises");
407 let restored: Menu = serde_json::from_str(&json).expect("what was serialised must deserialise");
408 assert_eq!(menu, restored);
409 }
410
411 #[test]
416 fn the_action_string_survives_the_round_trip() {
417 let menu = sample();
418 let json = serde_json::to_string(&menu).unwrap();
419 let restored: Menu = serde_json::from_str(&json).unwrap();
420 let home = restored.flatten().into_iter().find(|i| i.label == "home").unwrap();
421 assert_eq!(home.action.as_deref(), Some("connect:home"));
422 let sep = restored.flatten().into_iter().find(|i| i.kind == ItemKind::Separator).unwrap();
423 assert_eq!(sep.action, None);
424 }
425}