Skip to main content

perspective_viewer/components/
panel_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//! The per-panel command menu: a cursor-anchored [`ContextMenu`] plus the
14//! Export/Copy format-picker dropdowns it can spawn in place of itself. The
15//! Export/Copy flows are handled end-to-end HERE (the target panel's engines
16//! resolve from the `workspace` prop, like `StatusBar`'s own dropdowns);
17//! every other command is emitted as a [`PanelCommand`] for the parent.
18//!
19//! Both stages are body-mounted [`PortalModal`]s positioned against a shared
20//! session-long cursor anchor, so the menu is themed exactly like the pickers:
21//! the host (`<perspective-context-menu theme="X">`) is matched by the
22//! document theme rules' modal selector groups, with `X` = the TARGET panel's
23//! effective theme (not the active/host theme).
24//!
25//! One menu "session" spans right-click → (menu | picker) → dismissal:
26//! `on_close` fires exactly once, when the session ends (blur dismissal, a
27//! command selection, or the picker closing).
28
29use std::rc::Rc;
30
31use perspective_js::utils::*;
32use wasm_bindgen::JsCast;
33use web_sys::HtmlElement;
34use yew::html::Scope;
35use yew::prelude::*;
36
37use crate::components::copy_dropdown::CopyDropDownMenu;
38use crate::components::export_dropdown::ExportDropDownMenu;
39use crate::components::new_panel_menu::{HostedTables, NewPanelMenu, NewPanelPick, derived_counts};
40use crate::components::style::StyleSurface;
41use crate::config::*;
42use crate::presentation::Presentation;
43use crate::queries::{ResolvedCommands, fetch_hosted_tables};
44use crate::tasks::{can_derive, copy_method_to_clipboard, delete_derived, export_method_to_blob};
45use crate::ui::{ContextMenu, ContextMenuEntry, ContextMenuItem, MODAL_SLOT, PortalModal};
46use crate::utils::*;
47use crate::workspace::{PanelId, Workspace};
48
49/// A panel command the menu delegates to its parent. Export/Copy are absent —
50/// they're handled internally by the picker flow.
51#[derive(Clone, Debug, PartialEq, Eq)]
52pub enum PanelCommand {
53    New,
54    NewFrom {
55        client: String,
56        table: String,
57    },
58
59    /// A fresh panel copied from the named panel.
60    NewFromPanel(String),
61    Duplicate,
62
63    /// Promote the panel's current `View` to a derived `Table` under a
64    /// generated name, and rebind the panel to it.
65    Derive,
66    Reset,
67    Maximize,
68    Restore,
69    ToggleMaster,
70    Close,
71}
72
73/// Which format-picker dropdown the context menu spawned in place of itself.
74#[derive(Clone, Copy, PartialEq)]
75pub enum PickerKind {
76    Export,
77    Copy,
78}
79
80#[derive(Properties)]
81pub struct PanelMenuProps {
82    /// Viewport (client) coordinates the menu (and any spawned picker) anchors
83    /// at.
84    pub x: f64,
85    pub y: f64,
86
87    /// The right-clicked panel this menu targets — or `None` for the
88    /// EMPTY-stage menu (zero panels), which offers only the "New" sub-menu
89    /// (its `NewFrom` items resolve from the loaded-clients registry, no
90    /// panel required).
91    pub panel_id: Option<String>,
92
93    /// For per-panel command context (`is_master`, pivot state, panel count)
94    /// and resolving the target panel's engines for Export/Copy.
95    pub workspace: Workspace,
96
97    /// For `export_method_to_blob`.
98    pub presentation: Presentation,
99
100    /// The TARGET panel's effective theme (its own, else the registry
101    /// default), stamped on both stages' `PortalModal` hosts.
102    pub theme: Option<String>,
103
104    /// Whether the target panel is currently maximized (drives the
105    /// Maximize/Restore item).
106    pub maximized: bool,
107
108    /// The custom commands rendered above the built-in items.
109    #[prop_or_default]
110    pub commands: PtrEqRc<ResolvedCommands>,
111
112    /// A custom command was selected, by key.
113    #[prop_or_default]
114    pub on_custom: Callback<String>,
115
116    /// A command was selected — the parent executes it (and ends the session
117    /// via the `on_close` that follows every selection).
118    pub on_command: Callback<PanelCommand>,
119
120    /// The menu session ended (backdrop dismissal, command selection, or
121    /// picker close); the parent unmounts this component.
122    pub on_close: Callback<()>,
123}
124
125impl PartialEq for PanelMenuProps {
126    fn eq(&self, rhs: &Self) -> bool {
127        self.x == rhs.x
128            && self.y == rhs.y
129            && self.panel_id == rhs.panel_id
130            && self.theme == rhs.theme
131            && self.maximized == rhs.maximized
132            && self.commands == rhs.commands
133    }
134}
135
136pub enum PanelMenuMsg {
137    /// A parent-executed command was selected.
138    Command(PanelCommand),
139
140    /// A custom command was selected, by key.
141    Custom(String),
142
143    /// Export/Copy was selected: swap the menu for the format picker.
144    OpenPicker(PickerKind),
145
146    /// The `ContextMenu` closed. Fired on backdrop dismissal AND after every
147    /// item selection — swallowed when a picker was just opened (the session
148    /// continues in the picker).
149    MenuClosed,
150
151    /// The picker closed (blur, or a completed export/copy).
152    ClosePicker,
153
154    /// The per-client hosted-table-name fetch (spawned at menu open, feeding
155    /// the "New" sub-menu) resolved: `(client name, its table names)` per
156    /// loaded client.
157    TablesLoaded(Vec<(String, Vec<String>)>),
158}
159
160pub struct PanelMenu {
161    /// The session-long 0×0 cursor anchor element (a viewer light-DOM child)
162    /// both stages' `PortalModal`s position against; removed on destroy.
163    anchor: HtmlElement,
164
165    /// The open format picker, if the session is in its picker stage.
166    picker: Option<PickerKind>,
167
168    /// The "New" sub-menu's data: `(client name, its hosted table names)` per
169    /// loaded client, in registration order. `None` while the fetch spawned at
170    /// menu open is still in flight.
171    tables: Option<HostedTables>,
172
173    /// Keeps the [`Workspace::hosted_tables_changed`] listener attached for
174    /// the menu session, so the open listing tracks table creates/deletes.
175    _tables_sub: Subscription,
176}
177
178impl Component for PanelMenu {
179    type Message = PanelMenuMsg;
180    type Properties = PanelMenuProps;
181
182    fn create(ctx: &Context<Self>) -> Self {
183        let fetch = {
184            let workspace = ctx.props().workspace.clone();
185            let link = ctx.link().clone();
186            move || {
187                clone!(workspace, link);
188                ApiFuture::spawn(async move {
189                    let tables = fetch_hosted_tables(&workspace).await;
190                    link.send_message(PanelMenuMsg::TablesLoaded(tables));
191                    Ok(())
192                });
193            }
194        };
195
196        fetch();
197        let _tables_sub = ctx
198            .props()
199            .workspace
200            .hosted_tables_changed()
201            .add_listener(move |_| fetch());
202
203        Self {
204            anchor: session_anchor(
205                ctx.props().presentation.viewer_elem(),
206                ctx.props().x,
207                ctx.props().y,
208            ),
209            picker: None,
210            tables: None,
211            _tables_sub,
212        }
213    }
214
215    fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
216        match msg {
217            PanelMenuMsg::Command(cmd) => {
218                ctx.props().on_command.emit(cmd);
219                false
220            },
221            PanelMenuMsg::Custom(key) => {
222                ctx.props().on_custom.emit(key);
223                false
224            },
225            PanelMenuMsg::OpenPicker(kind) => {
226                self.picker = Some(kind);
227                true
228            },
229            PanelMenuMsg::MenuClosed => {
230                // The menu's `PortalModal` closes (blur) after every item
231                // selection; when that selection just opened a picker, the
232                // session continues — only a plain dismissal/selection ends
233                // it.
234                if self.picker.is_none() {
235                    ctx.props().on_close.emit(());
236                }
237
238                false
239            },
240            PanelMenuMsg::ClosePicker => {
241                ctx.props().on_close.emit(());
242                false
243            },
244            PanelMenuMsg::TablesLoaded(tables) => {
245                self.tables = Some(Rc::new(tables));
246                self.picker.is_none()
247            },
248        }
249    }
250
251    fn view(&self, ctx: &Context<Self>) -> Html {
252        match &self.picker {
253            Some(kind) => self.picker_html(ctx, *kind),
254            None => self.menu_html(ctx),
255        }
256    }
257
258    fn destroy(&mut self, _ctx: &Context<Self>) {
259        // The session ended (or the parent unmounted mid-session, e.g. the
260        // target panel closed); don't leak the cursor anchor.
261        self.anchor.remove();
262    }
263}
264
265impl PanelMenu {
266    fn menu_html(&self, ctx: &Context<Self>) -> Html {
267        let on_close = ctx.link().callback(|_| PanelMenuMsg::MenuClosed);
268        let item = |label: &str, on_select: Callback<()>, disabled: bool| {
269            ContextMenuEntry::Item(ContextMenuItem {
270                label: label.to_owned(),
271                on_select,
272                disabled,
273                title: None,
274            })
275        };
276        let cmd = |cmd: PanelCommand| {
277            ctx.link()
278                .callback(move |_| PanelMenuMsg::Command(cmd.clone()))
279        };
280        let builtin = match ctx.props().panel_id.as_deref() {
281            // The empty-stage menu: no target panel, so only the "New"
282            // sub-menu. Hover-only (`on_select: None`) — plain "New" copies
283            // its source panel's table binding, which doesn't exist here.
284            None => vec![ContextMenuEntry::Submenu {
285                label: "New".to_owned(),
286                on_select: None,
287                entries: vec![ContextMenuEntry::Custom(self.new_submenu_body(ctx))],
288            }],
289            Some(panel_id) => {
290                let can_close = ctx.props().workspace.len() > 1;
291                let is_master = ctx.props().workspace.is_master(&PanelId::from(panel_id));
292                let panel = ctx.props().workspace.panel(&PanelId::from(panel_id));
293                let can_derive_view = panel.as_ref().is_some_and(|x| {
294                    let config = x.session.get_view_config();
295                    let is_pivoted = !config.group_by.is_empty() || !config.split_by.is_empty();
296                    is_pivoted && can_derive(&x.session)
297                });
298
299                vec![
300                    ContextMenuEntry::Submenu {
301                        label: "New".to_owned(),
302                        on_select: Some(cmd(PanelCommand::New)),
303                        entries: vec![ContextMenuEntry::Custom(self.new_submenu_body(ctx))],
304                    },
305                    item("Duplicate", cmd(PanelCommand::Duplicate), false),
306                    item("Derive Table", cmd(PanelCommand::Derive), !can_derive_view),
307                    item("Reset", cmd(PanelCommand::Reset), false),
308                    item(
309                        "Export",
310                        ctx.link()
311                            .callback(|_| PanelMenuMsg::OpenPicker(PickerKind::Export)),
312                        false,
313                    ),
314                    item(
315                        "Copy",
316                        ctx.link()
317                            .callback(|_| PanelMenuMsg::OpenPicker(PickerKind::Copy)),
318                        false,
319                    ),
320                    if ctx.props().maximized {
321                        item("Restore", cmd(PanelCommand::Restore), false)
322                    } else {
323                        item("Maximize", cmd(PanelCommand::Maximize), false)
324                    },
325                    // Never gated: masters broadcast from ANY select/click event
326                    // (flat grids fall back to the clicked cell's `==` clause), not
327                    // just a grouped row tree.
328                    item(
329                        if is_master { "Detail" } else { "Master" },
330                        cmd(PanelCommand::ToggleMaster),
331                        false,
332                    ),
333                    item("Close", cmd(PanelCommand::Close), !can_close),
334                ]
335            },
336        };
337
338        let entries = custom_entries(ctx.link(), &ctx.props().commands)
339            .into_iter()
340            .chain(builtin)
341            .collect::<Vec<_>>();
342
343        html! {
344            <PortalModal
345                key="perspective-context-menu"
346                tag_name="perspective-context-menu"
347                sheet={StyleSurface::ContextMenu.sheet()}
348                target={Some(self.anchor.clone())}
349                own_focus=true
350                on_close={&on_close}
351                theme={ctx.props().theme.clone().unwrap_or_default()}
352            >
353                // Selection-end and blur-dismissal both route to `MenuClosed`;
354                // duplicates are harmless (the first ends the session or is
355                // swallowed by an open picker).
356                <ContextMenu {entries} {on_close} />
357            </PortalModal>
358        }
359    }
360
361    /// The "New" hover sub-menu's body, the shared [`NewPanelMenu`].
362    fn new_submenu_body(&self, ctx: &Context<Self>) -> Html {
363        let panels = Rc::new(
364            ctx.props()
365                .workspace
366                .panel_ids()
367                .into_iter()
368                .filter_map(|id| {
369                    let panel = ctx.props().workspace.panel(&id)?;
370                    let title = panel.session.get_title().filter(|t| !t.is_empty());
371                    Some((id.as_str().to_owned(), title))
372                })
373                .collect::<Vec<_>>(),
374        );
375
376        let callback = ctx.link().batch_callback(|pick: NewPanelPick| {
377            let cmd = match pick {
378                NewPanelPick::FromTable { client, table } => {
379                    PanelMenuMsg::Command(PanelCommand::NewFrom { client, table })
380                },
381                NewPanelPick::FromPanel(id) => {
382                    PanelMenuMsg::Command(PanelCommand::NewFromPanel(id))
383                },
384            };
385
386            vec![cmd, PanelMenuMsg::MenuClosed]
387        });
388
389        let workspace = ctx.props().workspace.clone();
390        let on_delete = Callback::from(move |name: String| {
391            let workspace = workspace.clone();
392            let effect = workspace.effects().guard();
393            ApiFuture::spawn(async move {
394                let _effect = effect;
395                delete_derived(&workspace, &name).await
396            });
397        });
398
399        html! {
400            <NewPanelMenu
401                tables={self.tables.clone()}
402                {panels}
403                {callback}
404                derived={derived_counts(&ctx.props().workspace)}
405                {on_delete}
406            />
407        }
408    }
409
410    /// Export/Copy format-picker spawned in place of the context menu, anchored
411    /// at the same cursor anchor and reusing the status bar's dropdown
412    /// components.
413    fn picker_html(&self, ctx: &Context<Self>, kind: PickerKind) -> Html {
414        // Export/Copy are absent from the target-less stage menu, so
415        // `panel_id` is always `Some` here in practice.
416        let Some(panel) = ctx
417            .props()
418            .panel_id
419            .as_deref()
420            .and_then(|id| ctx.props().workspace.panel(&PanelId::from(id)))
421        else {
422            return Html::default();
423        };
424
425        let on_close = ctx.link().callback(|_| PanelMenuMsg::ClosePicker);
426        let theme = ctx.props().theme.clone().unwrap_or_default();
427        let target = Some(self.anchor.clone());
428        let presentation = ctx.props().presentation.clone();
429
430        let inner = match kind {
431            PickerKind::Export => {
432                let callback = {
433                    clone!(presentation);
434                    let session = panel.session.clone();
435                    let renderer = panel.renderer.clone();
436                    let workspace = ctx.props().workspace.clone();
437                    let link = ctx.link().clone();
438                    Callback::from(move |file: ExportFile| {
439                        if file.name.is_empty() {
440                            return;
441                        }
442
443                        clone!(session, renderer, presentation, workspace, link);
444                        ApiFuture::spawn(async move {
445                            let blob = export_method_to_blob(
446                                &session,
447                                &renderer,
448                                &presentation,
449                                &workspace,
450                                file.method,
451                            )
452                            .await?;
453
454                            download(&file.as_filename(renderer.is_chart()), &blob)?;
455                            link.send_message(PanelMenuMsg::ClosePicker);
456                            Ok(())
457                        });
458                    })
459                };
460
461                html! {
462                    <ExportDropDownMenu
463                        renderer={panel.renderer.clone()}
464                        session={panel.session.clone()}
465                        {callback}
466                    />
467                }
468            },
469            PickerKind::Copy => {
470                let callback = {
471                    clone!(presentation);
472                    let session = panel.session.clone();
473                    let renderer = panel.renderer.clone();
474                    let workspace = ctx.props().workspace.clone();
475                    let link = ctx.link().clone();
476                    Callback::from(move |file: ExportFile| {
477                        let task = copy_method_to_clipboard(
478                            &session,
479                            &renderer,
480                            &presentation,
481                            &workspace,
482                            file.method,
483                        );
484
485                        clone!(link);
486                        ApiFuture::spawn(async move {
487                            task.await?;
488                            link.send_message(PanelMenuMsg::ClosePicker);
489                            Ok(())
490                        });
491                    })
492                };
493
494                html! { <CopyDropDownMenu renderer={panel.renderer.clone()} {callback} /> }
495            },
496        };
497
498        let tag_name = match kind {
499            PickerKind::Export => "perspective-export-menu",
500            PickerKind::Copy => "perspective-copy-menu",
501        };
502
503        html! {
504            // Keyed by host tag: the menu→picker swap happens at the same
505            // vdom position, and `PortalModal`'s host element + adopted
506            // surface sheet are create-time-only — unkeyed reuse would leave
507            // the picker inside the `<perspective-context-menu>` host with
508            // the context-menu sheet.
509            <PortalModal
510                key={tag_name}
511                {tag_name}
512                sheet={StyleSurface::DropdownMenu.sheet()}
513                {target}
514                own_focus=true
515                {on_close}
516                {theme}
517            >
518                { inner }
519            </PortalModal>
520        }
521    }
522}
523
524/// The menu rows for the app's custom commands, closed by a separator when
525/// there are any.
526fn custom_entries(link: &Scope<PanelMenu>, commands: &ResolvedCommands) -> Vec<ContextMenuEntry> {
527    let mut entries = spec_entries(link, &commands.commands);
528    if !entries.is_empty() {
529        entries.push(ContextMenuEntry::Separator);
530    }
531
532    entries
533}
534
535fn spec_entries(link: &Scope<PanelMenu>, specs: &[CommandSpec]) -> Vec<ContextMenuEntry> {
536    specs
537        .iter()
538        .filter_map(|spec| match spec {
539            CommandSpec::Command {
540                key,
541                label,
542                disabled,
543                title,
544                ..
545            } => {
546                let key = key.clone();
547                Some(ContextMenuEntry::Item(ContextMenuItem {
548                    label: label.clone(),
549                    on_select: link.callback(move |_| PanelMenuMsg::Custom(key.clone())),
550                    disabled: disabled.unwrap_or_default(),
551                    title: title.clone(),
552                }))
553            },
554            CommandSpec::Group {
555                label, commands, ..
556            } => {
557                let entries = spec_entries(link, commands);
558                (!entries.is_empty()).then(|| ContextMenuEntry::Submenu {
559                    label: label.clone(),
560                    on_select: None,
561                    entries,
562                })
563            },
564        })
565        .collect()
566}
567
568/// Create the session-long 0×0 cursor anchor at viewport `(x, y)` as a
569/// light-DOM child of `viewer` in the modal slot.
570pub(crate) fn session_anchor(viewer: &HtmlElement, x: f64, y: f64) -> HtmlElement {
571    let anchor: HtmlElement = global::document()
572        .create_element("div")
573        .unwrap()
574        .unchecked_into();
575
576    let _ = anchor.set_attribute("slot", MODAL_SLOT);
577    let style = anchor.style();
578    let _ = style.set_property("position", "fixed");
579    let _ = style.set_property("left", &format!("{x}px"));
580    let _ = style.set_property("top", &format!("{y}px"));
581    let _ = style.set_property("width", "0px");
582    let _ = style.set_property("height", "0px");
583    let _ = viewer.append_child(&anchor);
584    anchor
585}