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
use std::collections::HashMap;

use serde_derive::{Deserialize, Serialize};

/// An identifier for menus in the graph.
#[derive(Debug, PartialEq, Eq, Hash, Clone, Deserialize, Serialize)]
#[serde(transparent)]
pub struct MenuId(String);

pub type Graph = HashMap<MenuId, Menu>;

#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
pub struct Data {
    pub root: Root,
    pub graph: Graph,
}

impl Data {
    /// The source data, extracted from <https://xkcd.com/s/f9dfe4.js>.
    const JSON: &'static str = include_str!("data.json");

    /// Load the data from source.
    pub fn load() -> Self {
        serde_json::from_str(Self::JSON).unwrap()
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
pub struct Root {
    #[serde(rename = "State")]
    pub state: State,
    #[serde(rename = "Menu")]
    pub menu: Menu,
}

#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
pub struct State {
    #[serde(rename = "Tags")]
    tags: HashMap<MenuId, String>,
}

impl State {
    pub fn update(&mut self, action: &Action) {
        // Explicitly set tags before unsetting; this is the same order as in the original source
        self.tags.extend(action.set_tags.clone());
        self.tags.retain(|k, _| !action.unset_tags.contains(k));
        if !action.set_tags.is_empty() || !action.unset_tags.is_empty() {
            eprintln!(
                "Updated tags: {:#?}",
                self.tags.keys().map(|tag| &tag.0).collect::<Vec<_>>()
            );
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize, Default)]
pub struct Action {
    #[serde(rename = "setTags")]
    set_tags: HashMap<MenuId, String>,
    #[serde(rename = "unsetTags")]
    unset_tags: Vec<MenuId>,
}

#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
pub struct MenuItem {
    /// Unused.
    icon: Option<String>,
    /// The string shown on the menu item.
    pub label: String,
    /// Whether the menu item should be shown.
    pub display: Conditional,
    /// Whether the menu item should be clickable / not disabled.
    pub active: Conditional,
    /// What should be done when the user hovers and/or clicks on the menu item.
    pub reaction: Reaction,
}

#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(tag = "tag")]
pub enum Conditional {
    Always,
    TagSet { contents: MenuId },
    TagUnset { contents: MenuId },
    TLNot { contents: Box<Conditional> },
    TLAnd { contents: Vec<Conditional> },
    TLOr { contents: Vec<Conditional> },
}

impl Conditional {
    pub fn evaluate(&self, state: &State) -> bool {
        match self {
            Self::Always => true,
            Self::TagSet { contents } => state.tags.contains_key(contents),
            Self::TagUnset { contents } => !state.tags.contains_key(contents),
            Self::TLNot { contents } => !contents.evaluate(state),
            Self::TLAnd { contents } => contents.iter().all(|item| item.evaluate(state)),
            Self::TLOr { contents } => contents.iter().any(|item| item.evaluate(state)),
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(tag = "tag")]
pub enum Reaction {
    SubMenu {
        #[serde(rename = "onAction")]
        on_hover: Action,
        #[serde(flatten)]
        submenu: SubMenu,
    },
    #[serde(rename = "Action")]
    ClickAction {
        #[serde(rename = "onAction")]
        on_action: Action,
        act: Option<ClickAction>,
    },
}

#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
pub struct SubMenu {
    #[serde(rename = "subMenu")]
    sub_menu: MenuId,
    #[serde(rename = "subIdPostfix")]
    sub_id_postfix: Option<MenuId>,
}

impl SubMenu {
    pub fn id(&self, state: &State) -> MenuId {
        if let Some(postfix_id) = &self.sub_id_postfix {
            if let Some(postfix) = state.tags.get(postfix_id) {
                MenuId(format!("{}{}", self.sub_menu.0, postfix))
            } else {
                // Fall back to no postfix if no tag with that ID was set.
                self.sub_menu.clone()
            }
        } else {
            self.sub_menu.clone()
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(tag = "tag")]
pub enum ClickAction {
    ColapseMenu,
    Nav {
        url: String,
    },
    Download {
        url: String,
        filename: String,
    },
    JSCall {
        #[serde(rename = "jsCall")]
        js_call: String,
    },
}

#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
pub struct Menu {
    pub id: MenuId,
    #[serde(rename = "onLeave")]
    pub on_leave: Action,
    pub entries: Vec<MenuItem>,
}

/// If any of these tests fail, then we may have to rewrite things.
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn everything_is_parsed() {
        let expected: serde_json::Value = serde_json::from_str(Data::JSON).unwrap();

        let parsed = Data::load();
        let after_roundtrip = serde_json::to_value(parsed).unwrap();

        assert_eq!(expected, after_roundtrip);
    }

    #[test]
    fn no_icons() {
        let data = Data::load();

        assert!(data
            .graph
            .values()
            .flat_map(|menu| &menu.entries)
            .all(|entry| entry.icon.is_none()));
    }

    #[test]
    fn root_menu_is_same_as_in_graph() {
        let data = Data::load();

        assert_eq!(data.root.menu, data.graph[&data.root.menu.id]);
    }

    #[test]
    fn root_menu_has_no_on_leave() {
        let data = Data::load();

        assert_eq!(data.root.menu.on_leave, Action::default());
    }

    #[test]
    fn root_menu_entries_has_no_active() {
        let data = Data::load();

        assert!(data
            .root
            .menu
            .entries
            .iter()
            .all(|entry| entry.active == Conditional::Always));
    }

    #[test]
    fn root_menu_entries_is_submenu_and_has_no_hover() {
        let data = Data::load();

        assert!(data.root.menu.entries.iter().all(|entry| matches!(
            &entry.reaction,
            Reaction::SubMenu {
                on_hover,
                ..
            } if on_hover == &Action::default()
        )));
    }
}