schemaui 0.7.2

A Rust library for generating TUI and Web UIs from JSON Schemas for configuration management.
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
use anyhow::{Result, anyhow};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use serde::Deserialize;
use std::sync::{Arc, LazyLock};

use super::input::KeyAction;

macro_rules! keymap_source {
    () => {
        include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/keymap/default.keymap.json"
        ))
    };
}

pub(super) use keymap_source;

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) enum KeymapContext {
    Default,
    Collection,
    Overlay,
    Help,
    TextInput,
    NumericInput,
}

impl KeymapContext {
    fn from_str(raw: &str) -> Option<Self> {
        match raw {
            "default" => Some(KeymapContext::Default),
            "collection" => Some(KeymapContext::Collection),
            "overlay" => Some(KeymapContext::Overlay),
            "help" => Some(KeymapContext::Help),
            "text" | "textInput" | "text-input" => Some(KeymapContext::TextInput),
            "numeric" | "numericInput" | "numeric-input" => Some(KeymapContext::NumericInput),
            _ => None,
        }
    }
}

#[derive(Deserialize)]
struct RawEntry {
    id: String,
    description: String,
    contexts: Vec<String>,
    #[serde(default = "default_dispatch")]
    dispatch: bool,
    action: RawAction,
    combos: Vec<String>,
}

#[derive(Deserialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
enum RawAction {
    Save,
    Quit,
    ResetStatus,
    TogglePopup,
    EditComposite,
    ShowHelp,
    HelpClose,
    HelpPageStep { delta: i32 },
    HelpShortcutScroll { delta: i32 },
    HelpShortcutPage { delta: i32 },
    HelpShortcutHome,
    HelpShortcutEnd,
    HelpErrorScroll { delta: i32 },
    FieldStep { delta: i32 },
    SectionStep { delta: i32 },
    RootStep { delta: i32 },
    ListAddEntry,
    ListRemoveEntry,
    ListMove { delta: i32 },
    ListSelect { delta: i32 },
    None,
}

#[derive(Clone, Debug)]
struct KeyBinding {
    action: KeyAction,
    contexts: Vec<KeymapContext>,
    combos: Vec<KeyPattern>,
    snippet: String,
    dispatch: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct HelpEntry {
    pub(crate) keys: String,
    pub(crate) action: String,
}

impl KeyBinding {
    fn from_raw(raw: RawEntry) -> Result<Self> {
        let contexts = raw
            .contexts
            .iter()
            .filter_map(|ctx| KeymapContext::from_str(ctx))
            .collect::<Vec<_>>();
        if contexts.is_empty() {
            return Err(anyhow!("keymap entry {} must declare contexts", raw.id));
        }
        let action = raw.action.into_action();
        let mut combos = Vec::with_capacity(raw.combos.len());
        for combo in raw.combos {
            let pattern = KeyPattern::parse(&combo)
                .map_err(|err| anyhow!("failed to parse combo '{combo}' for {}: {err}", raw.id))?;
            combos.push(pattern);
        }
        if combos.is_empty() {
            return Err(anyhow!("keymap entry {} must declare combos", raw.id));
        }
        let combos_display = combos
            .iter()
            .map(|pattern| pattern.display.clone())
            .collect::<Vec<_>>()
            .join("/");
        let snippet = format!("{combos_display} -> {}", raw.description);
        Ok(Self {
            action,
            contexts,
            combos,
            snippet,
            dispatch: raw.dispatch,
        })
    }

    fn classify(&self, key: &KeyEvent) -> Option<KeyAction> {
        if !self.dispatch {
            return None;
        }
        if self.contexts.contains(&KeymapContext::Help) {
            return None;
        }
        self.combos
            .iter()
            .find(|pattern| pattern.matches(key))
            .map(|_| self.action)
    }

    fn classify_for_contexts(
        &self,
        key: &KeyEvent,
        contexts: &[KeymapContext],
    ) -> Option<KeyAction> {
        if !self.dispatch
            || !self
                .contexts
                .iter()
                .any(|context| contexts.contains(context))
        {
            return None;
        }
        self.combos
            .iter()
            .find(|pattern| pattern.matches(key))
            .map(|_| self.action)
    }
}

#[derive(Clone, Debug)]
struct KeyPattern {
    matcher: CodeMatcher,
    required: KeyModifiers,
    allow_shift: bool,
    display: String,
}

impl KeyPattern {
    fn parse(spec: &str) -> Result<Self, String> {
        let display = spec.trim().to_string();
        if display.is_empty() {
            return Err("combo cannot be empty".into());
        }
        let mut tokens = display
            .split('+')
            .map(|t| t.trim())
            .filter(|t| !t.is_empty())
            .collect::<Vec<_>>();
        if tokens.is_empty() {
            return Err("combo must contain key".into());
        }
        let key_token = tokens.pop().unwrap();
        let matcher = CodeMatcher::from_token(key_token)?;
        let mut required = KeyModifiers::empty();
        for token in tokens {
            match token.to_lowercase().as_str() {
                "ctrl" | "control" => required |= KeyModifiers::CONTROL,
                "shift" => required |= KeyModifiers::SHIFT,
                "alt" => required |= KeyModifiers::ALT,
                other => {
                    return Err(format!("unsupported modifier '{other}'"));
                }
            }
        }
        let allow_shift = matcher.allows_extra_shift() && !required.contains(KeyModifiers::SHIFT);
        Ok(Self {
            matcher,
            required,
            allow_shift,
            display,
        })
    }

    fn matches(&self, key: &KeyEvent) -> bool {
        if !self.matcher.matches(&key.code) {
            return false;
        }
        if !modifiers_include(key.modifiers, self.required) {
            return false;
        }
        let extra = remove_modifiers(key.modifiers, self.required);
        if self.allow_shift {
            let tolerated = extra & !KeyModifiers::SHIFT;
            tolerated.is_empty()
        } else {
            extra.is_empty()
        }
    }
}

#[derive(Clone, Debug)]
enum CodeMatcher {
    Literal(KeyCode),
    Alpha(char),
}

impl CodeMatcher {
    fn from_token(token: &str) -> Result<Self, String> {
        let normalized = token.to_lowercase();
        let matcher = match normalized.as_str() {
            "tab" => CodeMatcher::Literal(KeyCode::Tab),
            "backtab" | "shift+tab" => CodeMatcher::Literal(KeyCode::BackTab),
            "enter" => CodeMatcher::Literal(KeyCode::Enter),
            "esc" | "escape" => CodeMatcher::Literal(KeyCode::Esc),
            "left" => CodeMatcher::Literal(KeyCode::Left),
            "right" => CodeMatcher::Literal(KeyCode::Right),
            "up" => CodeMatcher::Literal(KeyCode::Up),
            "down" => CodeMatcher::Literal(KeyCode::Down),
            "home" => CodeMatcher::Literal(KeyCode::Home),
            "end" => CodeMatcher::Literal(KeyCode::End),
            "pageup" => CodeMatcher::Literal(KeyCode::PageUp),
            "pagedown" => CodeMatcher::Literal(KeyCode::PageDown),
            "delete" | "del" => CodeMatcher::Literal(KeyCode::Delete),
            "backspace" => CodeMatcher::Literal(KeyCode::Backspace),
            other => {
                if other.len() == 1 {
                    CodeMatcher::Alpha(other.chars().next().unwrap())
                } else {
                    return Err(format!("unsupported key '{token}'"));
                }
            }
        };
        Ok(matcher)
    }

    fn matches(&self, code: &KeyCode) -> bool {
        match (self, code) {
            (CodeMatcher::Literal(expected), actual) => actual == expected,
            (CodeMatcher::Alpha(expected), KeyCode::Char(actual)) => {
                actual.to_ascii_lowercase() == *expected
            }
            _ => false,
        }
    }

    fn allows_extra_shift(&self) -> bool {
        matches!(
            self,
            CodeMatcher::Alpha(_) | CodeMatcher::Literal(KeyCode::BackTab)
        )
    }
}

impl RawAction {
    fn into_action(self) -> KeyAction {
        match self {
            RawAction::Save => KeyAction::Save,
            RawAction::Quit => KeyAction::Quit,
            RawAction::ResetStatus => KeyAction::ResetStatus,
            RawAction::TogglePopup => KeyAction::TogglePopup,
            RawAction::EditComposite => KeyAction::EditComposite,
            RawAction::ShowHelp => KeyAction::ShowHelp,
            RawAction::HelpClose => KeyAction::HelpClose,
            RawAction::HelpPageStep { delta } => KeyAction::HelpPageStep(delta),
            RawAction::HelpShortcutScroll { delta } => KeyAction::HelpShortcutScroll(delta),
            RawAction::HelpShortcutPage { delta } => KeyAction::HelpShortcutPage(delta),
            RawAction::HelpShortcutHome => KeyAction::HelpShortcutHome,
            RawAction::HelpShortcutEnd => KeyAction::HelpShortcutEnd,
            RawAction::HelpErrorScroll { delta } => KeyAction::HelpErrorScroll(delta),
            RawAction::FieldStep { delta } => KeyAction::FieldStep(delta),
            RawAction::SectionStep { delta } => KeyAction::SectionStep(delta),
            RawAction::RootStep { delta } => KeyAction::RootStep(delta),
            RawAction::ListAddEntry => KeyAction::ListAddEntry,
            RawAction::ListRemoveEntry => KeyAction::ListRemoveEntry,
            RawAction::ListMove { delta } => KeyAction::ListMove(delta),
            RawAction::ListSelect { delta } => KeyAction::ListSelect(delta),
            RawAction::None => KeyAction::None,
        }
    }
}

#[derive(Debug, Clone)]
pub(crate) struct KeymapStore {
    bindings: Arc<Vec<KeyBinding>>,
}

impl KeymapStore {
    pub fn from_json(raw: &str) -> Result<Self> {
        let entries: Vec<RawEntry> = serde_json::from_str(raw)?;
        Self::from_entries(entries)
    }

    pub fn builtin() -> Self {
        Self::from_json(keymap_source!()).expect("invalid keymap/default.keymap.json")
    }

    fn from_entries(entries: Vec<RawEntry>) -> Result<Self> {
        let mut bindings = Vec::with_capacity(entries.len());
        for entry in entries {
            bindings.push(KeyBinding::from_raw(entry)?);
        }
        Ok(Self {
            bindings: Arc::new(bindings),
        })
    }

    pub fn classify(&self, key: &KeyEvent) -> Option<KeyAction> {
        self.bindings
            .iter()
            .find_map(|binding| binding.classify(key))
    }

    pub fn classify_for_contexts(
        &self,
        key: &KeyEvent,
        contexts: &[KeymapContext],
    ) -> Option<KeyAction> {
        self.bindings
            .iter()
            .find_map(|binding| binding.classify_for_contexts(key, contexts))
    }

    pub fn help_text(&self, context: KeymapContext) -> Option<String> {
        self.help_text_for_contexts(&[context])
    }

    pub fn help_text_for_contexts(&self, contexts: &[KeymapContext]) -> Option<String> {
        let snippets = self
            .bindings
            .iter()
            .filter(|binding| {
                contexts
                    .iter()
                    .any(|context| binding.contexts.contains(context))
            })
            .map(|binding| binding.snippet.clone())
            .collect::<Vec<_>>();
        if snippets.is_empty() {
            None
        } else {
            Some(snippets.join(""))
        }
    }

    pub(crate) fn help_entries(&self, context: KeymapContext) -> Vec<HelpEntry> {
        self.help_entries_for_contexts(&[context])
    }

    pub(crate) fn help_entries_for_contexts(&self, contexts: &[KeymapContext]) -> Vec<HelpEntry> {
        self.bindings
            .iter()
            .filter(|binding| {
                contexts
                    .iter()
                    .any(|context| binding.contexts.contains(context))
            })
            .map(|binding| {
                let (keys, action) = match binding.snippet.split_once("->") {
                    Some((keys, action)) => (keys.trim().to_string(), action.trim().to_string()),
                    None => (binding.snippet.clone(), String::new()),
                };
                HelpEntry { keys, action }
            })
            .collect()
    }
}

static DEFAULT_STORE: LazyLock<Arc<KeymapStore>> =
    LazyLock::new(|| Arc::new(KeymapStore::builtin()));

pub(crate) fn default_store() -> Arc<KeymapStore> {
    DEFAULT_STORE.clone()
}

fn modifiers_include(actual: KeyModifiers, required: KeyModifiers) -> bool {
    actual.contains(required)
}

fn remove_modifiers(actual: KeyModifiers, required: KeyModifiers) -> KeyModifiers {
    KeyModifiers::from_bits_truncate(actual.bits() & !required.bits())
}

fn default_dispatch() -> bool {
    true
}