Skip to main content

perspective_viewer/ui/
context_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
13use wasm_bindgen::JsCast;
14use wasm_bindgen::prelude::*;
15use web_sys::{Element, Event, HtmlElement, MouseEvent, Node, ShadowRoot};
16use yew::prelude::*;
17
18use crate::utils::{Bounds, ModalSide, apply_placement};
19
20/// A single command row in a `ContextMenu`.
21#[derive(Clone, PartialEq)]
22pub struct ContextMenuItem {
23    pub label: String,
24    pub on_select: Callback<()>,
25    pub disabled: bool,
26
27    /// Tooltip text, when the command declares one.
28    pub title: Option<String>,
29}
30
31/// A row in a `ContextMenu`: a plain command `ContextMenuItem`, a
32/// non-interactive group label, or a row with a hover-opened sub-menu flyout.
33#[derive(Clone, PartialEq)]
34pub enum ContextMenuEntry {
35    Item(ContextMenuItem),
36    Header(String),
37
38    /// A rule dividing two sections of the menu.
39    Separator,
40
41    /// Arbitrary content rendered in place, whose own handlers must close
42    /// the menu.
43    Custom(Html),
44    Submenu {
45        label: String,
46
47        on_select: Option<Callback<()>>,
48        entries: Vec<ContextMenuEntry>,
49    },
50}
51
52#[derive(Properties, PartialEq)]
53pub struct ContextMenuProps {
54    pub entries: Vec<ContextMenuEntry>,
55
56    #[prop_or_default]
57    pub on_close: Callback<()>,
58}
59
60/// The command-item list of a panel context menu.
61pub struct ContextMenu;
62
63impl Component for ContextMenu {
64    type Message = ();
65    type Properties = ContextMenuProps;
66
67    fn create(_ctx: &Context<Self>) -> Self {
68        Self
69    }
70
71    fn view(&self, ctx: &Context<Self>) -> Html {
72        let props = ctx.props();
73        let entries = props
74            .entries
75            .iter()
76            .map(|entry| render_entry(entry, &props.on_close));
77
78        html! { <div class="context-menu">{ for entries }</div> }
79    }
80}
81
82fn render_entry(entry: &ContextMenuEntry, on_close: &Callback<()>) -> Html {
83    match entry {
84        ContextMenuEntry::Item(item) => {
85            let disabled = item.disabled;
86            let onclick = {
87                let on_select = item.on_select.clone();
88                let on_close = on_close.clone();
89                Callback::from(move |e: MouseEvent| {
90                    e.stop_propagation();
91                    if !disabled {
92                        on_select.emit(());
93                        on_close.emit(());
94                    }
95                })
96            };
97
98            let mut class = classes!("context-menu-item");
99            if disabled {
100                class.push("disabled");
101            }
102
103            let title = item.title.clone();
104            let label_title = title.is_none().then(|| item.label.clone());
105            html! {
106                <span {class} {onclick} {title}>
107                    <span class="context-menu-label" title={label_title}>
108                        { item.label.clone() }
109                    </span>
110                </span>
111            }
112        },
113        ContextMenuEntry::Header(label) => {
114            html! { <span class="context-menu-header">{ label.clone() }</span> }
115        },
116        ContextMenuEntry::Separator => {
117            html! { <span class="context-menu-separator" /> }
118        },
119        ContextMenuEntry::Custom(content) => content.clone(),
120        ContextMenuEntry::Submenu {
121            label,
122            on_select,
123            entries,
124        } => {
125            html! {
126                <Submenu
127                    label={label.clone()}
128                    on_select={on_select.clone()}
129                    entries={entries.clone()}
130                    on_close={on_close.clone()}
131                />
132            }
133        },
134    }
135}
136
137#[derive(Properties, PartialEq)]
138pub struct SubmenuProps {
139    pub label: String,
140    pub on_select: Option<Callback<()>>,
141    pub entries: Vec<ContextMenuEntry>,
142    pub on_close: Callback<()>,
143}
144
145pub enum SubmenuMsg {
146    Enter,
147    Leave,
148}
149
150/// A hover-opened flyout row placed beside its row inside the viewport,
151/// tracked through the bubbling `mouseover`/`mouseout` pair because Chrome
152/// withholds `mouseenter` from listeners on a shadow root.
153pub struct Submenu {
154    flyout: NodeRef,
155    open: bool,
156
157    /// Re-places the open flyout when the menu its row belongs to scrolls.
158    scroll: Option<ScrollWatch>,
159}
160
161struct ScrollWatch {
162    menu: Element,
163    listener: Closure<dyn FnMut(Event)>,
164}
165
166fn place_flyout(flyout: &NodeRef) -> Option<()> {
167    let flyout = flyout.cast::<HtmlElement>()?;
168    let row = flyout.parent_element()?;
169    let anchor = Bounds::from(&row.get_bounding_client_rect());
170    apply_placement(&flyout, &anchor, ModalSide::Beside);
171    Some(())
172}
173
174fn scrolling_menu(flyout: &NodeRef) -> Option<Element> {
175    let row = flyout.cast::<HtmlElement>()?.parent_element()?;
176    match row.closest(".context-menu-submenu").ok()? {
177        Some(parent) => Some(parent),
178        None => Some(row.get_root_node().dyn_into::<ShadowRoot>().ok()?.host()),
179    }
180}
181
182impl Submenu {
183    fn watch_scroll(&mut self) {
184        if self.scroll.is_none()
185            && let Some(menu) = scrolling_menu(&self.flyout)
186        {
187            let flyout = self.flyout.clone();
188            let listener = Closure::wrap(Box::new(move |_: Event| {
189                place_flyout(&flyout);
190            }) as Box<dyn FnMut(Event)>);
191
192            let _ =
193                menu.add_event_listener_with_callback("scroll", listener.as_ref().unchecked_ref());
194
195            self.scroll = Some(ScrollWatch { menu, listener });
196        }
197    }
198
199    fn unwatch_scroll(&mut self) {
200        if let Some(ScrollWatch { menu, listener }) = self.scroll.take() {
201            let _ = menu
202                .remove_event_listener_with_callback("scroll", listener.as_ref().unchecked_ref());
203        }
204    }
205}
206
207impl Component for Submenu {
208    type Message = SubmenuMsg;
209    type Properties = SubmenuProps;
210
211    fn create(_ctx: &Context<Self>) -> Self {
212        Self {
213            flyout: NodeRef::default(),
214            open: false,
215            scroll: None,
216        }
217    }
218
219    fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
220        match msg {
221            SubmenuMsg::Enter => {
222                let changed = !self.open;
223                self.open = true;
224                changed
225            },
226            SubmenuMsg::Leave => {
227                let changed = self.open;
228                self.open = false;
229                self.unwatch_scroll();
230                changed
231            },
232        }
233    }
234
235    fn rendered(&mut self, _ctx: &Context<Self>, _first_render: bool) {
236        if self.open {
237            place_flyout(&self.flyout);
238            self.watch_scroll();
239        }
240    }
241
242    fn destroy(&mut self, _ctx: &Context<Self>) {
243        self.unwatch_scroll();
244    }
245
246    fn view(&self, ctx: &Context<Self>) -> Html {
247        let props = ctx.props();
248        let onclick = {
249            let on_select = props.on_select.clone();
250            let on_close = props.on_close.clone();
251            Callback::from(move |e: MouseEvent| {
252                e.stop_propagation();
253                if let Some(on_select) = &on_select {
254                    on_select.emit(());
255                    on_close.emit(());
256                }
257            })
258        };
259
260        let onmouseover = ctx.link().callback(|_: MouseEvent| SubmenuMsg::Enter);
261        let onmouseout = ctx.link().batch_callback({
262            let flyout = self.flyout.clone();
263            move |event: MouseEvent| {
264                let item = flyout.cast::<HtmlElement>()?.parent_element()?;
265                let related = event
266                    .related_target()
267                    .and_then(|target| target.dyn_into::<Node>().ok());
268
269                let stays = related.is_some_and(|node| item.contains(Some(&node)));
270                (!stays).then_some(SubmenuMsg::Leave)
271            }
272        });
273        let mut class = classes!("context-menu", "context-menu-submenu");
274        if self.open {
275            class.push("open");
276        }
277
278        let children = props
279            .entries
280            .iter()
281            .map(|entry| render_entry(entry, &props.on_close));
282
283        html! {
284            <span class="context-menu-item has-submenu" {onclick} {onmouseover} {onmouseout}>
285                <span class="context-menu-label" title={props.label.clone()}>
286                    { props.label.clone() }
287                </span>
288                <div {class} ref={self.flyout.clone()}>{ for children }</div>
289            </span>
290        }
291    }
292}