Skip to main content

perspective_viewer/components/
main_panel.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//! `MainPanel`: the multi-panel layout host. Owns the `<regular-layout>`
14//! element, the per-panel `<PanelTab>`s, the shared status bar, and the panel
15//! context menu. The `Component` impl below is thin — its handlers live in the
16//! submodules:
17//!
18//! - [`update`] — the small `MainPanelMsg` handlers (pointer, close detection,
19//!   tab/active sync, context menu).
20//! - [`presize`] — the `BeforeResize` pre-size-every-plugin algorithm.
21//! - [`reconcile`] — the `rendered` layout reconcile + per-panel theme stamp.
22//! - [`render`] — the `view` (status bar, cells, tabs, menu).
23
24mod presize;
25mod reconcile;
26mod render;
27mod update;
28
29pub mod msg;
30
31use std::collections::HashSet;
32use std::rc::Rc;
33
34use perspective_js::utils::JsValueSerdeExt;
35use wasm_bindgen::prelude::*;
36use yew::prelude::*;
37
38pub use self::msg::{MainPanelMsg, MenuOrigin, MenuRequest};
39use super::panel_menu::PanelCommand;
40use crate::presentation::{Presentation, PresentationProps};
41use crate::queries::ResolvedCommands;
42use crate::renderer::*;
43use crate::session::{Session, SessionProps};
44use crate::utils::PtrEqRc;
45use crate::workspace::{PanelId, Workspace};
46
47#[derive(Clone, Properties)]
48pub struct MainPanelProps {
49    /// Toggle the settings sidebar open. Fired by a `PanelTab`'s open-settings
50    /// button (after selecting + activating that panel) — the tabs are the
51    /// only open-settings affordance.
52    pub on_settings: Callback<()>,
53
54    /// Reset callback forwarded from the root component.  Fired when the user
55    /// clicks the reset button; `bool` is `true` for a full reset (expressions
56    /// + column configs), `false` for config-only.
57    pub on_reset: Callback<bool>,
58
59    /// Fired with a panel id when its frame titlebar is pressed, to make it the
60    /// active panel.
61    pub on_activate_panel: Callback<String>,
62
63    /// Fired with a panel id from a tab × (an app-initiated close): the root
64    /// removes it from the model at once and parks its engines.
65    pub on_close_panel: Callback<String>,
66
67    /// Fired with a panel id once the `regular-layout` tree no longer holds
68    /// it, so the root can eject the parked panel.
69    pub on_panel_closed: Callback<String>,
70
71    /// Fired with `(panel id, command)` when the panel context menu selects a
72    /// command the root executes (New/Duplicate/Reset/ToggleMaster/Close).
73    /// Maximize/Restore are handled HERE (this component owns the layout
74    /// element), and Export/Copy end-to-end by
75    /// [`PanelMenu`](super::panel_menu::PanelMenu) itself.
76    pub on_panel_command: Callback<(String, PanelCommand)>,
77
78    /// Snapshots threaded from root.  Read for `has_table`, `title` here in
79    /// the panel itself; threaded wholesale to `StatusBar`/`StatusIndicator`.
80    pub session_props: SessionProps,
81    pub renderer_props: RendererProps,
82    pub presentation_props: PresentationProps,
83
84    /// Derived from root: `settings_open && has_table_loaded`.
85    pub is_settings_open: bool,
86
87    /// Root-managed in-flight render counter (not engine state).
88    pub update_count: u32,
89
90    /// Ids of every layout panel, in order; one `<regular-layout>` cell is
91    /// rendered per id. Drives re-render when panels are added/removed.
92    pub panel_ids: Vec<PanelId>,
93
94    /// `(panel id, session title)` for every panel. Rendered into the
95    /// `<regular-layout>` `style` as `--regular-layout-<id>--title` custom
96    /// properties, which regular-layout's tabs display via `::before` content.
97    pub panel_titles: Vec<(String, Option<String>)>,
98
99    /// `(panel id, per-panel theme)` for every panel. A snapshot so a
100    /// per-panel theme change re-renders MainPanel — `renderer.theme()` is
101    /// interior-mutable and not otherwise observed by `eq`. Each frame inlines
102    /// its theme's `--psp-*` block only when it diverges from the host theme.
103    pub panel_themes: Vec<(String, Option<String>)>,
104
105    /// The master (filter-source) panel ids, sorted. A snapshot so a master
106    /// toggle re-renders MainPanel — the role set is interior-mutable on
107    /// `Workspace` and not otherwise observed by `eq`. Drives each tab's
108    /// broadcast badge.
109    pub panel_masters: Vec<PanelId>,
110
111    /// Element-level global filters (fed by master/detail selection), threaded
112    /// to the `StatusBar` where the global-filter chips are rendered.
113    pub global_filters: Vec<perspective_client::config::Filter>,
114
115    /// Remove the global filter at this index (a chip's × in the `StatusBar`).
116    pub on_remove_global_filter: Callback<usize>,
117
118    /// Clear all global filters (the "Clear" affordance in the `StatusBar`).
119    pub on_clear_global_filters: Callback<()>,
120
121    /// The multi-panel model, for per-panel `Renderer`/`Session` access when
122    /// reconciling `insertPanel`/`removePanel`.
123    pub workspace: Workspace,
124
125    /// State (the *active* panel's handles — for the shared status bar).
126    pub session: Session,
127    pub renderer: Renderer,
128    pub presentation: Presentation,
129}
130
131impl PartialEq for MainPanelProps {
132    fn eq(&self, rhs: &Self) -> bool {
133        self.session_props == rhs.session_props
134            && self.renderer_props == rhs.renderer_props
135            && self.presentation_props == rhs.presentation_props
136            && self.is_settings_open == rhs.is_settings_open
137            && self.update_count == rhs.update_count
138            && self.panel_ids == rhs.panel_ids
139            && self.panel_titles == rhs.panel_titles
140            && self.panel_themes == rhs.panel_themes
141            && self.panel_masters == rhs.panel_masters
142            && self.global_filters == rhs.global_filters
143            && self.workspace == rhs.workspace
144            && self.session == rhs.session
145            && self.renderer == rhs.renderer
146            && self.presentation == rhs.presentation
147    }
148}
149
150impl MainPanelProps {
151    fn is_title(&self) -> bool {
152        self.session_props.title.is_some()
153    }
154
155    pub(super) fn effective_panel_theme(&self, id: &str) -> Option<String> {
156        self.panel_themes
157            .iter()
158            .find(|(pid, _)| pid == id)
159            .and_then(|(_, theme)| theme.clone())
160            .or_else(|| self.presentation_props.available_themes.first().cloned())
161    }
162}
163
164pub struct MainPanel {
165    main_panel_ref: NodeRef,
166
167    /// Ref to the `<regular-layout>` element hosting the panel cells.
168    layout_ref: NodeRef,
169
170    /// Panel slots currently placed in `layout_ref`'s grid, reconciled against
171    /// `panel_ids` on each render so we `insertPanel`/`removePanel` exactly
172    /// once per add/remove.
173    inserted: Vec<String>,
174
175    /// `regular-layout-update` listener (close detection); kept alive here and
176    /// attached to the layout element once in `rendered`.
177    _layout_update_listener: Closure<dyn FnMut(web_sys::Event)>,
178
179    /// `regular-layout-select` listener (active-panel sync); kept alive here
180    /// and attached alongside the update listener.
181    _layout_select_listener: Closure<dyn FnMut(web_sys::Event)>,
182
183    /// `regular-layout-before-resize` listener (presize hook); kept alive here
184    /// and attached alongside the others.
185    _layout_before_resize_listener: Closure<dyn FnMut(web_sys::Event)>,
186
187    /// `contextmenu` listener on the viewer HOST element — one stable attach
188    /// point covering every surface (panels, status bar, sidebars),
189    /// independent of the layout reconcile; attached once in `rendered` and
190    /// REMOVED in `destroy`, since the host outlives this component's Yew
191    /// app. Imperative — not a Yew `oncontextmenu` — because the plugin body
192    /// is light-DOM attached by the renderer (its DOM parent is the host,
193    /// not the frame), so Yew's delegated handler never matches a
194    /// right-click there; a native listener sees every surface — shadow
195    /// chrome and slotted light DOM alike — on the composed path.
196    _contextmenu_listener: Closure<dyn FnMut(web_sys::Event)>,
197
198    /// Bubble-phase `pointerdown` listener on the viewer host that activates
199    /// the panel whose frame is on the event's composed path.
200    _pointerdown_listener: Closure<dyn FnMut(web_sys::Event)>,
201
202    /// The `<regular-layout>` ELEMENT the layout listeners are attached to.
203    /// Compared by identity in `reconcile` — if the element is ever a
204    /// different instance (it should never be: the render keys it into a
205    /// fully-keyed sibling list precisely so Yew reuses it), the listeners
206    /// are re-attached and `inserted` is reset so the fresh (empty) layout
207    /// is repopulated instead of silently orphaning every panel. A latched
208    /// `bool` here once turned an unkeyed-diff element replacement into
209    /// "Duplicate commits into an EMPTY tree with no `before-resize`
210    /// listener": the old element left the DOM with the committed tree and
211    /// every listener, and nothing ever noticed.
212    listener_target: Option<web_sys::HtmlElement>,
213
214    /// Ids gone from the model whose `removePanel` has been issued to the
215    /// layout and not yet committed.
216    pending_removals: HashSet<String>,
217
218    /// Ids observed in a committed layout tree, the only model-held panels a
219    /// later commit can report closed.
220    on_screen: HashSet<String>,
221
222    /// The in-flight panel drag, from its first `BeforeResize` until it is
223    /// dropped on `LayoutUpdated` (the drop).
224    drag: Option<presize::DragSession>,
225
226    /// Panels currently *hidden* behind an unselected index of a tab stack,
227    /// recomputed from the layout tree on every `regular-layout-update`.
228    /// Drives each tab's `visible` prop (`PanelTab` marks the front tab of
229    /// every stack, not just the active panel). Empty until the first layout
230    /// update — every panel starts visible.
231    hidden_tabs: HashSet<String>,
232
233    /// Open context menu as `(client x, client y, target panel id)`; outer
234    /// `None` when closed. A `None` *panel id* is the target-less menu (no
235    /// active panel to resolve to — "New" only). Rendered as a
236    /// cursor-anchored [`PanelMenu`](super::panel_menu::PanelMenu) overlay.
237    context_menu: Option<(f64, f64, Option<String>)>,
238
239    /// The custom commands of the open context menu.
240    context_menu_commands: PtrEqRc<ResolvedCommands>,
241
242    /// The context-menu gesture whose custom commands are still resolving.
243    pending_menu: Option<Rc<MenuRequest>>,
244
245    /// Id of the currently maximized panel (via `regular-layout.maximize`), or
246    /// `None`. Transient (regular-layout doesn't persist it); drives the
247    /// Maximize/Restore menu label. Cleared when the panel leaves the layout.
248    maximized: Option<String>,
249
250    /// `Workspace::staged_changed` → [`MainPanelMsg::StagedChanged`] on THIS
251    /// component's scope (see the message doc for why not the root's).
252    _staged_sub: crate::utils::Subscription,
253
254    /// `Workspace::layout_staged` → [`MainPanelMsg::LayoutStaged`].
255    _layout_staged_sub: crate::utils::Subscription,
256}
257
258impl Component for MainPanel {
259    type Message = MainPanelMsg;
260    type Properties = MainPanelProps;
261
262    fn create(ctx: &Context<Self>) -> Self {
263        let cb = ctx.link().callback(|_: ()| MainPanelMsg::LayoutUpdated);
264        let listener = Closure::wrap(
265            Box::new(move |_: web_sys::Event| cb.emit(())) as Box<dyn FnMut(web_sys::Event)>
266        );
267
268        let select_cb = ctx.link().callback(MainPanelMsg::TabSelected);
269        let select_listener = Closure::wrap(Box::new(move |event: web_sys::Event| {
270            #[derive(serde::Deserialize)]
271            struct SelectDetail {
272                name: String,
273            }
274
275            if let Some(custom) = event.dyn_ref::<web_sys::CustomEvent>()
276                && let Ok(SelectDetail { name }) = custom.detail().into_serde_ext()
277            {
278                select_cb.emit(name);
279            }
280        }) as Box<dyn FnMut(web_sys::Event)>);
281
282        // `preventDefault()` synchronously suspends the layout's resize commit
283        // (the event is cancelable); the component then pre-sizes each panel
284        // and calls `resumeResize` to release it (see
285        // `MainPanelMsg::BeforeResize`).
286        let before_resize_cb = ctx.link().callback(MainPanelMsg::BeforeResize);
287        let before_resize_listener = Closure::wrap(Box::new(move |event: web_sys::Event| {
288            event.prevent_default();
289            before_resize_cb.emit(event);
290        }) as Box<dyn FnMut(web_sys::Event)>);
291
292        // Imperative `contextmenu` listener: a right-click anywhere in the
293        // element opens the panel menu — targeting the frame on the event's
294        // composed path, or `None` (resolved to the ACTIVE panel, else the
295        // stage menu, in `on_context_menu`, where props live) from any
296        // other surface. Two pass-throughs keep the NATIVE menu: editable
297        // targets (inputs, textareas, contenteditable — cut/copy/paste),
298        // and anything inside an open `PortalModal` (every modal host is a
299        // light-DOM viewer child in the modal slot — this menu included, so
300        // without the carve-out a right-click in any open dropdown would
301        // re-open the menu underneath it).
302        let contextmenu_cb = ctx
303            .link()
304            .callback(|(id, x, y, origin)| MainPanelMsg::ContextMenu(id, x, y, origin));
305        let viewer_elem = ctx.props().presentation.viewer_elem().clone();
306        let contextmenu_listener = Closure::wrap(Box::new(move |event: web_sys::Event| {
307            // Shift+right-click passes through to the native browser menu.
308            if event.unchecked_ref::<web_sys::MouseEvent>().shift_key() {
309                return;
310            }
311
312            let path = event.composed_path();
313            let is_editable = path.get(0).dyn_ref::<web_sys::HtmlElement>().is_some_and(
314                |el: &web_sys::HtmlElement| {
315                    el.tag_name().eq_ignore_ascii_case("input")
316                        || el.tag_name().eq_ignore_ascii_case("textarea")
317                        || el.is_content_editable()
318                },
319            );
320
321            if is_editable {
322                return;
323            }
324
325            let mut panel_id = None;
326            for i in 0..path.length() {
327                let node = path.get(i);
328                let Some(el) = node.dyn_ref::<web_sys::Element>() else {
329                    continue;
330                };
331
332                if el == viewer_elem.unchecked_ref::<web_sys::Element>() {
333                    break;
334                }
335
336                if el.slot() == crate::ui::MODAL_SLOT {
337                    return;
338                }
339
340                if el.tag_name().eq_ignore_ascii_case("regular-layout-frame")
341                    && let Some(name) = el.get_attribute("name")
342                {
343                    panel_id = Some(name);
344                    break;
345                }
346            }
347
348            event.prevent_default();
349            let mouse = event.unchecked_ref::<web_sys::MouseEvent>();
350            let origin = if panel_id.is_some() {
351                MenuOrigin::Body
352            } else {
353                MenuOrigin::Chrome
354            };
355
356            contextmenu_cb.emit((
357                panel_id,
358                mouse.client_x() as f64,
359                mouse.client_y() as f64,
360                origin,
361            ));
362        }) as Box<dyn FnMut(web_sys::Event)>);
363
364        let pointerdown_cb = ctx.link().callback(MainPanelMsg::PanelPointerDown);
365        let viewer_elem = ctx.props().presentation.viewer_elem().clone();
366        let pointerdown_listener = Closure::wrap(Box::new(move |event: web_sys::Event| {
367            if let Some(frame) = panel_frame_on_path(&event, viewer_elem.unchecked_ref())
368                && !frame.class_list().contains("closing")
369                && let Some(name) = frame.get_attribute("name")
370            {
371                pointerdown_cb.emit(name);
372            }
373        }) as Box<dyn FnMut(web_sys::Event)>);
374
375        let staged_sub = {
376            use crate::utils::AddListener;
377            let cb = ctx.link().callback(|_: ()| MainPanelMsg::StagedChanged);
378            ctx.props()
379                .workspace
380                .staged_changed()
381                .add_listener(move |()| cb.emit(()))
382        };
383
384        let layout_staged_sub = {
385            use crate::utils::AddListener;
386            let cb = ctx.link().callback(|_: ()| MainPanelMsg::LayoutStaged);
387            ctx.props()
388                .workspace
389                .layout_staged()
390                .add_listener(move |()| cb.emit(()))
391        };
392
393        Self {
394            main_panel_ref: NodeRef::default(),
395            layout_ref: NodeRef::default(),
396            inserted: Vec::new(),
397            pending_removals: HashSet::new(),
398            on_screen: HashSet::new(),
399            _layout_update_listener: listener,
400            _layout_select_listener: select_listener,
401            _layout_before_resize_listener: before_resize_listener,
402            _contextmenu_listener: contextmenu_listener,
403            _pointerdown_listener: pointerdown_listener,
404            listener_target: None,
405            drag: None,
406            hidden_tabs: HashSet::new(),
407            context_menu: None,
408            context_menu_commands: PtrEqRc::default(),
409            pending_menu: None,
410            maximized: None,
411            _staged_sub: staged_sub,
412            _layout_staged_sub: layout_staged_sub,
413        }
414    }
415
416    fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
417        match msg {
418            MainPanelMsg::PointerEvent(event) => self.on_pointer_event(ctx, event),
419            MainPanelMsg::StagedChanged => true,
420            MainPanelMsg::LayoutStaged => true,
421            MainPanelMsg::LayoutUpdated => self.on_layout_updated(ctx),
422            MainPanelMsg::TabSelected(name) => self.on_tab_selected(ctx, name),
423            MainPanelMsg::PanelPointerDown(name) => self.on_panel_pointer_down(ctx, name),
424            MainPanelMsg::ContextMenu(id, x, y, origin) => {
425                self.on_context_menu(ctx, id, x, y, origin)
426            },
427            MainPanelMsg::ContextMenuResolved(request, commands) => {
428                self.on_context_menu_resolved(ctx, request, commands)
429            },
430            MainPanelMsg::CustomCommand(key) => self.on_custom_command(ctx, key),
431            MainPanelMsg::CloseContextMenu => self.on_close_context_menu(),
432            MainPanelMsg::Command(cmd) => self.on_command(ctx, cmd),
433            MainPanelMsg::BeforeResize(event) => self.on_before_resize(ctx, event),
434        }
435    }
436
437    fn changed(&mut self, ctx: &Context<Self>, old: &Self::Properties) -> bool {
438        self.close_unstaged_panels(ctx, old);
439        ctx.props() != old
440    }
441
442    fn rendered(&mut self, ctx: &Context<Self>, first_render: bool) {
443        // The `contextmenu` listener attaches to the viewer HOST element —
444        // one stable attach point covering every surface (panels, status
445        // bar, sidebars), decoupled from the layout reconcile. Panel
446        // right-clicks reach it through their frames on the composed path;
447        // everything else resolves to the active panel (or the stage menu).
448        if first_render {
449            let viewer_elem = ctx.props().presentation.viewer_elem();
450            let _ = viewer_elem.add_event_listener_with_callback(
451                "contextmenu",
452                self._contextmenu_listener.as_ref().unchecked_ref(),
453            );
454
455            let _ = viewer_elem.add_event_listener_with_callback(
456                "pointerdown",
457                self._pointerdown_listener.as_ref().unchecked_ref(),
458            );
459        }
460
461        self.size_staging_wrappers(ctx);
462        self.reconcile(ctx);
463    }
464
465    fn view(&self, ctx: &Context<Self>) -> Html {
466        self.render(ctx)
467    }
468
469    fn destroy(&mut self, ctx: &Context<Self>) {
470        // The host element outlives this component (`delete()` tears down
471        // the Yew app, not the custom element), so the listeners must not
472        // dangle into dropped `Closure`s.
473        let viewer_elem = ctx.props().presentation.viewer_elem();
474        let _ = viewer_elem.remove_event_listener_with_callback(
475            "contextmenu",
476            self._contextmenu_listener.as_ref().unchecked_ref(),
477        );
478
479        let _ = viewer_elem.remove_event_listener_with_callback(
480            "pointerdown",
481            self._pointerdown_listener.as_ref().unchecked_ref(),
482        );
483    }
484}
485
486/// The innermost `regular-layout-frame` on `event`'s composed path below
487/// `viewer_elem`.
488fn panel_frame_on_path(
489    event: &web_sys::Event,
490    viewer_elem: &web_sys::Element,
491) -> Option<web_sys::Element> {
492    event
493        .composed_path()
494        .iter()
495        .filter_map(|node| node.dyn_into::<web_sys::Element>().ok())
496        .take_while(|el| el != viewer_elem)
497        .find(|el| el.tag_name().eq_ignore_ascii_case("regular-layout-frame"))
498}
499
500impl MainPanel {
501    /// Report closed every panel gone from the model that the layout never
502    /// held, since it has no commit to wait for.
503    fn close_unstaged_panels(&self, ctx: &Context<Self>, old: &MainPanelProps) {
504        for id in &old.panel_ids {
505            if !ctx.props().panel_ids.contains(id)
506                && !self.inserted.iter().any(|n| n == id.as_str())
507            {
508                ctx.props().on_panel_closed.emit(id.as_str().to_owned());
509            }
510        }
511    }
512}