nsh-core 0.8.1

Platform-independent core: shadow tree, styles, layout and mount instructions.
Documentation
//! Keyboard shortcuts of views ([`super::on_key`]; TS: `keymap.bind`).
//!
//! The platform matches keys against the surface's one table (the root's
//! `Prop::Keymap`) and reports a match with the root's `KeyCommand` event.
//! The core makes that table of JS's bindings and the views', and runs a
//! view's handler itself; the others go to JS. Views' binding ids start at
//! [`FIRST_ID`], above any JS gives, so the two never meet.

use std::rc::Rc;

use crate::keymap::KeyBinding;

/// A view's shortcut handler: it gets the keystroke as written.
pub(crate) type KeyHandler = Rc<dyn Fn(&str)>;

/// The first id of a view's binding.
pub(crate) const FIRST_ID: u32 = 1 << 31;

/// A view's binding: what the platform matches, the keystroke as written
/// (what the handler gets), the handler and the window it was bound in.
pub(crate) struct ViewKey {
    pub(crate) binding: KeyBinding,
    /// The dialog root of the window of the app's own whose tree bound
    /// it; `None` outside one (the window is then where its owner's
    /// component is: [`ViewKeys::bindings`]).
    pub(crate) window: Option<super::ElementRef>,
    /// It is the app's (`KeyScope::App`): every window's, wherever it is
    /// bound; `window` is not resolved.
    pub(crate) app: bool,
    /// The owner it was bound under.
    pub(crate) owner: super::Owner,
    pub(crate) text: Rc<str>,
    pub(crate) handler: KeyHandler,
}

/// The views' bindings, oldest first (the newest that may fire wins).
#[derive(Default)]
pub(crate) struct ViewKeys {
    next: u32,
    pub(crate) list: Vec<ViewKey>,
    /// The list changed since the core last made the table.
    pub(crate) changed: bool,
    /// The last table left out a binding whose window was not mounted
    /// yet: the core makes it again once it is.
    pub(crate) unplaced: bool,
}

impl ViewKeys {
    /// Adds a binding; its id.
    pub(crate) fn add(
        &mut self,
        make: impl FnOnce(u32) -> KeyBinding,
        text: Rc<str>,
        handler: KeyHandler,
        window: Option<super::ElementRef>,
        app: bool,
        owner: super::Owner,
    ) -> u32 {
        let id = FIRST_ID + self.next;
        self.next += 1;
        self.list.push(ViewKey {
            binding: make(id),
            text,
            handler,
            window,
            app,
            owner,
        });
        self.changed = true;
        id
    }

    /// Removes binding `id`; returns it so it is dropped outside the borrow
    /// (its handler may own what removes others).
    pub(crate) fn remove(&mut self, id: u32) -> Option<ViewKey> {
        let i = self.list.iter().position(|k| k.binding.id == id)?;
        self.changed = true;
        Some(self.list.remove(i))
    }

    /// The bindings as the platform matches them, each in its window's
    /// root node; those of a window not mounted yet are left out (and
    /// [`Self::unplaced`] set). One bound outside a window's own context
    /// is in the window `window_of` gives for its owner: a component JS
    /// placed in a window of its own sees no such context, yet its keys
    /// are that window's. One made in the app root (its owner resolves to
    /// no window) is app-wide, as a binding made there in JS is.
    pub(crate) fn bindings(
        &mut self,
        mut window_of: impl FnMut(super::Owner) -> crate::NodeId,
    ) -> Vec<KeyBinding> {
        let mut unplaced = false;
        let bindings = self
            .list
            .iter()
            .filter_map(|k| {
                if k.app {
                    return Some(k.binding);
                }
                let window = match k.window {
                    None => window_of(k.owner),
                    Some(element) => match element.node() {
                        Some(node) => node,
                        None => {
                            unplaced = true;
                            return None;
                        }
                    },
                };
                if window == crate::ROOT_ID {
                    return Some(k.binding);
                }
                Some(k.binding.in_window(window))
            })
            .collect();
        self.unplaced = unplaced;
        bindings
    }

    /// Binding `id`'s keystroke as written and its handler.
    pub(crate) fn handler(&self, id: u32) -> Option<(Rc<str>, KeyHandler)> {
        self.list
            .iter()
            .find(|k| k.binding.id == id)
            .map(|k| (k.text.clone(), k.handler.clone()))
    }
}