Skip to main content

perspective_viewer/components/
command_menu.rs

1// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
2// ┃ ██████ ██████ ██████       █      █      █      █      █ █▄  ▀███ █       ┃
3// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█  ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄  ▀█ █ ▀▀▀▀▀ ┃
4// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄   █ ▄▄▄▄▄ ┃
5// ┃ █      ██████ █  ▀█▄       █ ██████      █      ███▌▐███ ███████▄ █       ┃
6// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
7// ┃ Copyright (c) 2017, the Perspective Authors.                              ┃
8// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
9// ┃ This file is part of the Perspective library, distributed under the terms ┃
10// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃
11// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
12
13//! A plugin-opened menu of custom commands: the `showCommandMenu()` surface,
14//! a cursor-anchored [`ContextMenu`] in its own Yew app that resolves when it
15//! closes.
16
17use std::cell::RefCell;
18use std::rc::Rc;
19
20use perspective_js::utils::*;
21use wasm_bindgen::JsCast;
22use web_sys::HtmlElement;
23use yew::prelude::*;
24
25use crate::components::panel_menu::session_anchor;
26use crate::components::style::StyleSurface;
27use crate::config::CommandSpec;
28use crate::presentation::Presentation;
29use crate::ui::{ContextMenu, ContextMenuEntry, ContextMenuItem, MODAL_SLOT, PortalModal};
30use crate::utils::*;
31
32#[derive(Properties, PartialEq)]
33pub struct CommandMenuProps {
34    pub x: f64,
35    pub y: f64,
36    pub theme: Option<String>,
37    pub presentation: Presentation,
38    pub commands: Rc<Vec<CommandSpec>>,
39    pub on_pick: Callback<String>,
40    pub on_close: Callback<()>,
41}
42
43pub enum CommandMenuMsg {
44    Pick(String),
45    Closed,
46}
47
48pub struct CommandMenu {
49    anchor: HtmlElement,
50}
51
52impl Component for CommandMenu {
53    type Message = CommandMenuMsg;
54    type Properties = CommandMenuProps;
55
56    fn create(ctx: &Context<Self>) -> Self {
57        Self {
58            anchor: session_anchor(
59                ctx.props().presentation.viewer_elem(),
60                ctx.props().x,
61                ctx.props().y,
62            ),
63        }
64    }
65
66    fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
67        match msg {
68            CommandMenuMsg::Pick(key) => ctx.props().on_pick.emit(key),
69            CommandMenuMsg::Closed => ctx.props().on_close.emit(()),
70        }
71
72        false
73    }
74
75    fn view(&self, ctx: &Context<Self>) -> Html {
76        let on_close = ctx.link().callback(|_| CommandMenuMsg::Closed);
77        let entries = spec_entries(ctx.link(), &ctx.props().commands);
78        html! {
79            <PortalModal
80                key="perspective-command-menu"
81                tag_name="perspective-command-menu"
82                sheet={StyleSurface::ContextMenu.sheet()}
83                target={Some(self.anchor.clone())}
84                own_focus=true
85                on_close={&on_close}
86                theme={ctx.props().theme.clone().unwrap_or_default()}
87            >
88                <ContextMenu {entries} {on_close} />
89            </PortalModal>
90        }
91    }
92
93    fn destroy(&mut self, _ctx: &Context<Self>) {
94        self.anchor.remove();
95    }
96}
97
98fn spec_entries(link: &html::Scope<CommandMenu>, specs: &[CommandSpec]) -> Vec<ContextMenuEntry> {
99    specs
100        .iter()
101        .filter_map(|spec| match spec {
102            CommandSpec::Command {
103                key,
104                label,
105                disabled,
106                title,
107                ..
108            } => {
109                let key = key.clone();
110                Some(ContextMenuEntry::Item(ContextMenuItem {
111                    label: label.clone(),
112                    on_select: link.callback(move |_| CommandMenuMsg::Pick(key.clone())),
113                    disabled: disabled.unwrap_or_default(),
114                    title: title.clone(),
115                }))
116            },
117            CommandSpec::Group {
118                label, commands, ..
119            } => {
120                let entries = spec_entries(link, commands);
121                (!entries.is_empty()).then(|| ContextMenuEntry::Submenu {
122                    label: label.clone(),
123                    on_select: None,
124                    entries,
125                })
126            },
127        })
128        .collect()
129}
130
131/// Open a menu of `commands` at viewport `(x, y)`, emitting
132/// `Presentation::command_invoked` with `context` for a pick, and resolve
133/// when it closes.
134pub async fn show_command_menu(
135    presentation: &Presentation,
136    context: wasm_bindgen::JsValue,
137    commands: Vec<CommandSpec>,
138    x: f64,
139    y: f64,
140    theme: Option<String>,
141) -> ApiResult<()> {
142    let host: HtmlElement = global::document().create_element("div")?.unchecked_into();
143
144    host.set_attribute("slot", MODAL_SLOT)?;
145    presentation.viewer_elem().append_child(&host)?;
146    let (completion, receiver) = Completion::new();
147    let app: Rc<RefCell<Option<AppHandle<CommandMenu>>>> = Rc::default();
148    let completion = Rc::new(RefCell::new(Some(completion)));
149    let on_close = {
150        clone!(app, host, completion);
151        Callback::from(move |_| {
152            if let Some(app) = app.borrow_mut().take() {
153                app.destroy();
154            }
155
156            host.remove();
157            if let Some(completion) = completion.borrow_mut().take() {
158                completion.resolve_after(async { Ok(()) });
159            }
160        })
161    };
162
163    let on_pick = {
164        clone!(presentation);
165        Callback::from(move |key: String| {
166            presentation.command_invoked.emit((key, context.clone()));
167        })
168    };
169
170    let props = CommandMenuProps {
171        x,
172        y,
173        theme,
174        presentation: presentation.clone(),
175        commands: Rc::new(commands),
176        on_pick,
177        on_close,
178    };
179
180    *app.borrow_mut() =
181        Some(yew::Renderer::with_root_and_props(host.clone().into(), props).render());
182    receiver.await.map_err(|_| ApiError::new("Cancelled"))?
183}