Skip to main content

vector_core/
start_menu.rs

1//! The widescreen Main Menu's pins: what a user keeps one click away, in the
2//! rail's shape ([`RailLayout`]) and synced the same way, as its own document
3//! (`vector/start`, [`crate::synced_prefs::Pref::Start`]).
4//!
5//! A pin's key names what it opens, in the grammar links already use, so a key
6//! means the same thing on every device and needs nothing stored beside it:
7//!
8//! ```text
9//!   app/<nexus app id>                 a Mini App from the Nexus, launched
10//!   dm/<npub>                          a conversation
11//!   c/<community>[/<channel>]          a community, or one of its channels
12//!   settings[/<category>[/<section>]]  a place in Settings
13//!   nexus | requests                   the Nexus, the Requests list
14//! ```
15//!
16//! What a key shows (a name, an icon) is resolved on the device from what it
17//! holds; a key it cannot resolve keeps its place, as the rail keeps a community
18//! it has not synced.
19
20use crate::rail_layout::RailLayout;
21
22/// Enough for any launcher, few enough that a malformed document stays small.
23pub const MAX_PINS: usize = 120;
24
25/// Whether `key` is a pin this build can open.
26pub fn is_pin_key(key: &str) -> bool {
27    if key.len() > 160 {
28        return false;
29    }
30    let parts: Vec<&str> = key.split('/').collect();
31    match parts.as_slice() {
32        ["app", id] => crate::webxdc::is_safe_app_id(id),
33        ["dm", npub] => npub.starts_with("npub1") && npub.len() == 63 && npub.bytes().all(|b| b.is_ascii_alphanumeric()),
34        ["c", ids @ ..] => (1..=2).contains(&ids.len()) && ids.iter().all(|id| is_hex_id(id)),
35        ["settings", rest @ ..] => rest.len() <= 2 && rest.iter().all(|s| is_settings_id(s)),
36        ["nexus"] | ["requests"] => true,
37        _ => false,
38    }
39}
40
41fn is_hex_id(s: &str) -> bool {
42    s.len() == 64 && s.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
43}
44
45fn is_settings_id(s: &str) -> bool {
46    !s.is_empty() && s.len() <= 32 && s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
47}
48
49/// Pin `key` at the end. `Ok(false)` when it is pinned already.
50pub fn pin(layout: &mut RailLayout, key: &str) -> Result<bool, String> {
51    if !is_pin_key(key) {
52        return Err("That can't be pinned".to_string());
53    }
54    if !layout.is_editable() {
55        return Err("Your pins were arranged by a newer Vector; update to change them".to_string());
56    }
57    if layout.contains(key) {
58        return Ok(false);
59    }
60    if layout.flatten().len() >= MAX_PINS {
61        return Err(format!("Start holds up to {MAX_PINS} pins"));
62    }
63    layout.nodes.push(crate::rail_layout::RailNode::item(key));
64    Ok(true)
65}
66
67/// Take `key` off Start, out of whichever folder holds it. `false` when it wasn't pinned.
68pub fn unpin(layout: &mut RailLayout, key: &str) -> bool {
69    if !layout.contains(key) {
70        return false;
71    }
72    layout.remove_key(key);
73    true
74}
75
76#[cfg(test)]
77mod tests {
78    use super::*;
79
80    const A: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
81
82    fn npub() -> String {
83        format!("npub1{}", "q".repeat(58))
84    }
85
86    #[test]
87    fn a_pin_names_what_it_opens_in_the_link_grammar() {
88        for key in [
89            "app/chess.v2_beta".to_string(),
90            format!("dm/{}", npub()),
91            format!("c/{A}"),
92            format!("c/{A}/{A}"),
93            "settings".to_string(),
94            "settings/privacy/streamer".to_string(),
95            "nexus".to_string(),
96            "requests".to_string(),
97        ] {
98            assert!(is_pin_key(&key), "{key}");
99        }
100        for key in [
101            "app/../etc".to_string(),
102            "dm/notanpub".to_string(),
103            format!("c/{A}/{A}/{A}"),
104            format!("c/{}", A.to_uppercase()),
105            "settings/Privacy".to_string(),
106            "settings/a/b/c".to_string(),
107            "nexus/chess".to_string(),
108            "profile".to_string(),
109            String::new(),
110        ] {
111            assert!(!is_pin_key(&key), "{key}");
112        }
113    }
114
115    #[test]
116    fn pinning_appends_once_and_unpinning_finds_it_in_a_folder() {
117        let mut l = RailLayout::default();
118        assert_eq!(pin(&mut l, "nexus"), Ok(true));
119        assert_eq!(pin(&mut l, "nexus"), Ok(false), "pinned twice is pinned once");
120        assert_eq!(pin(&mut l, "requests"), Ok(true));
121        assert!(pin(&mut l, "nope").is_err());
122        assert_eq!(l.flatten(), vec!["nexus".to_string(), "requests".to_string()]);
123
124        let drop = crate::rail_layout::RailDrop::Combine { with_key: "nexus".into() };
125        l.apply_drop(&crate::rail_layout::RailDrag::Item { key: "requests".into() }, &drop, "f1").unwrap();
126        assert!(matches!(l.nodes.as_slice(), [crate::rail_layout::RailNode::Folder { .. }]));
127        assert!(unpin(&mut l, "requests"));
128        assert!(!unpin(&mut l, "requests"));
129        assert_eq!(l.flatten(), vec!["nexus".to_string()]);
130    }
131
132    #[test]
133    fn start_holds_a_bounded_number_of_pins() {
134        let mut l = RailLayout::default();
135        for i in 0..MAX_PINS {
136            pin(&mut l, &format!("app/app{i}")).unwrap();
137        }
138        assert!(pin(&mut l, "app/one-more").is_err());
139    }
140}