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