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//! - [`frame_theme`] — the `rendered` frame-background mirror (each
23//!   `<regular-layout-frame>`'s panel-theme background var).
24//! - [`render`] — the `view` (status bar, cells, tabs, menu).
25
26mod frame_theme;
27mod presize;
28mod reconcile;
29mod render;
30mod update;
31
32pub mod msg;
33
34use std::collections::{HashMap, HashSet};
35
36use perspective_js::utils::JsValueSerdeExt;
37use wasm_bindgen::prelude::*;
38use yew::prelude::*;
39
40pub use self::msg::MainPanelMsg;
41use super::panel_menu::PanelCommand;
42use crate::presentation::{Presentation, PresentationProps};
43use crate::renderer::*;
44use crate::session::{Session, SessionProps};
45use crate::tasks::PanelResizeObserverHandle;
46use crate::workspace::{PanelId, Workspace};
47
48#[derive(Clone, Properties)]
49pub struct MainPanelProps {
50    /// Toggle the settings sidebar open. Fired by a `PanelTab`'s open-settings
51    /// button (after selecting + activating that panel) — the tabs are the
52    /// only open-settings affordance.
53    pub on_settings: Callback<()>,
54
55    /// Reset callback forwarded from the root component.  Fired when the user
56    /// clicks the reset button; `bool` is `true` for a full reset (expressions
57    /// + column configs), `false` for config-only.
58    pub on_reset: Callback<bool>,
59
60    /// Fired with a panel id when its frame titlebar is pressed, to make it the
61    /// active panel.
62    pub on_activate_panel: Callback<String>,
63
64    /// Fired with a panel id from a tab × (an app-initiated close): the root
65    /// removes it from the model at once and parks its engines.
66    pub on_close_panel: Callback<String>,
67
68    /// Fired with a panel id once the `regular-layout` tree no longer holds
69    /// it, so the root can eject the parked panel.
70    pub on_panel_closed: Callback<String>,
71
72    /// Fired with `(panel id, command)` when the panel context menu selects a
73    /// command the root executes (New/Duplicate/Reset/ToggleMaster/Close).
74    /// Maximize/Restore are handled HERE (this component owns the layout
75    /// element), and Export/Copy end-to-end by
76    /// [`PanelMenu`](super::panel_menu::PanelMenu) itself.
77    pub on_panel_command: Callback<(String, PanelCommand)>,
78
79    /// Snapshots threaded from root.  Read for `has_table`, `title` here in
80    /// the panel itself; threaded wholesale to `StatusBar`/`StatusIndicator`.
81    pub session_props: SessionProps,
82    pub renderer_props: RendererProps,
83    pub presentation_props: PresentationProps,
84
85    /// Derived from root: `settings_open && has_table_loaded`.
86    pub is_settings_open: bool,
87
88    /// Root-managed in-flight render counter (not engine state).
89    pub update_count: u32,
90
91    /// Ids of every layout panel, in order; one `<regular-layout>` cell is
92    /// rendered per id. Drives re-render when panels are added/removed.
93    pub panel_ids: Vec<PanelId>,
94
95    /// `(panel id, session title)` for every panel. Rendered into the
96    /// `<regular-layout>` `style` as `--regular-layout-<id>--title` custom
97    /// properties, which regular-layout's tabs display via `::before` content.
98    pub panel_titles: Vec<(String, Option<String>)>,
99
100    /// `(panel id, per-panel theme)` for every panel. A snapshot so a
101    /// per-panel theme change re-renders MainPanel — `renderer.theme()` is
102    /// interior-mutable and not otherwise observed by `eq`. Each frame inlines
103    /// its theme's `--psp-*` block only when it diverges from the host theme.
104    pub panel_themes: Vec<(String, Option<String>)>,
105
106    /// The master (filter-source) panel ids, sorted. A snapshot so a master
107    /// toggle re-renders MainPanel — the role set is interior-mutable on
108    /// `Workspace` and not otherwise observed by `eq`. Drives each tab's
109    /// broadcast badge.
110    pub panel_masters: Vec<PanelId>,
111
112    /// Element-level global filters (fed by master/detail selection), threaded
113    /// to the `StatusBar` where the global-filter chips are rendered.
114    pub global_filters: Vec<perspective_client::config::Filter>,
115
116    /// Remove the global filter at this index (a chip's × in the `StatusBar`).
117    pub on_remove_global_filter: Callback<usize>,
118
119    /// Clear all global filters (the "Clear" affordance in the `StatusBar`).
120    pub on_clear_global_filters: Callback<()>,
121
122    /// The multi-panel model, for per-panel `Renderer`/`Session` access when
123    /// reconciling `insertPanel`/`removePanel`.
124    pub workspace: Workspace,
125
126    /// State (the *active* panel's handles — for the shared status bar).
127    pub session: Session,
128    pub renderer: Renderer,
129    pub presentation: Presentation,
130}
131
132impl PartialEq for MainPanelProps {
133    fn eq(&self, rhs: &Self) -> bool {
134        self.session_props == rhs.session_props
135            && self.renderer_props == rhs.renderer_props
136            && self.presentation_props == rhs.presentation_props
137            && self.is_settings_open == rhs.is_settings_open
138            && self.update_count == rhs.update_count
139            && self.panel_ids == rhs.panel_ids
140            && self.panel_titles == rhs.panel_titles
141            && self.panel_themes == rhs.panel_themes
142            && self.panel_masters == rhs.panel_masters
143            && self.global_filters == rhs.global_filters
144            && self.workspace == rhs.workspace
145            && self.session == rhs.session
146            && self.renderer == rhs.renderer
147            && self.presentation == rhs.presentation
148    }
149}
150
151impl MainPanelProps {
152    fn is_title(&self) -> bool {
153        self.session_props.title.is_some()
154    }
155
156    pub(super) fn effective_panel_theme(&self, id: &str) -> Option<String> {
157        self.panel_themes
158            .iter()
159            .find(|(pid, _)| pid == id)
160            .and_then(|(_, theme)| theme.clone())
161            .or_else(|| self.presentation_props.available_themes.first().cloned())
162    }
163}
164
165pub struct MainPanel {
166    main_panel_ref: NodeRef,
167
168    /// Ref to the `<regular-layout>` element hosting the panel cells.
169    layout_ref: NodeRef,
170
171    /// Panel slots currently placed in `layout_ref`'s grid, reconciled against
172    /// `panel_ids` on each render so we `insertPanel`/`removePanel` exactly
173    /// once per add/remove.
174    inserted: Vec<String>,
175
176    /// `regular-layout-update` listener (close detection); kept alive here and
177    /// attached to the layout element once in `rendered`.
178    _layout_update_listener: Closure<dyn FnMut(web_sys::Event)>,
179
180    /// `regular-layout-select` listener (active-panel sync); kept alive here
181    /// and attached alongside the update listener.
182    _layout_select_listener: Closure<dyn FnMut(web_sys::Event)>,
183
184    /// `regular-layout-before-resize` listener (presize hook); kept alive here
185    /// and attached alongside the others.
186    _layout_before_resize_listener: Closure<dyn FnMut(web_sys::Event)>,
187
188    /// `contextmenu` listener on the panel *container* — one stable attach
189    /// point covering the whole stage, independent of the layout reconcile;
190    /// at zero panels it opens the stage menu. Kept alive here and attached
191    /// once in `rendered`. Imperative — not a Yew `oncontextmenu` — because
192    /// the plugin body is light-DOM attached by the renderer (its DOM parent
193    /// is the host, not the frame), so Yew's delegated handler never matches
194    /// a right-click there. A native listener catches it via composed
195    /// bubbling and resolves the panel from the path.
196    _contextmenu_listener: Closure<dyn FnMut(web_sys::Event)>,
197
198    /// The `<regular-layout>` ELEMENT the layout listeners are attached to.
199    /// Compared by identity in `reconcile` — if the element is ever a
200    /// different instance (it should never be: the render keys it into a
201    /// fully-keyed sibling list precisely so Yew reuses it), the listeners
202    /// are re-attached and `inserted` is reset so the fresh (empty) layout
203    /// is repopulated instead of silently orphaning every panel. A latched
204    /// `bool` here once turned an unkeyed-diff element replacement into
205    /// "Duplicate commits into an EMPTY tree with no `before-resize`
206    /// listener": the old element left the DOM with the committed tree and
207    /// every listener, and nothing ever noticed.
208    listener_target: Option<web_sys::HtmlElement>,
209
210    /// Ids gone from the model whose `removePanel` has been issued to the
211    /// layout and not yet committed.
212    pending_removals: HashSet<String>,
213
214    /// Per-panel `ResizeObserver`s, keyed by panel id, each observing that
215    /// panel's slotted plugin element and resizing only that panel's
216    /// `Renderer`. Bound in `BeforeResize` for the DRAGGED panel only (it is
217    /// excluded from the presize paths, and the `overlay` presize is disabled);
218    /// dropped on `LayoutUpdated` (the drop).
219    panel_resize_observers: HashMap<String, PanelResizeObserverHandle>,
220
221    /// Panels currently *hidden* behind an unselected index of a tab stack,
222    /// recomputed from the layout tree on every `regular-layout-update`.
223    /// Drives each tab's `visible` prop (`PanelTab` marks the front tab of
224    /// every stack, not just the active panel). Empty until the first layout
225    /// update — every panel starts visible.
226    hidden_tabs: HashSet<String>,
227
228    /// Open context menu as `(client x, client y, target panel id)`; outer
229    /// `None` when closed. A `None` *panel id* is the empty-stage menu (zero
230    /// panels — "New" only). Rendered as a cursor-anchored
231    /// [`PanelMenu`](super::panel_menu::PanelMenu) overlay.
232    context_menu: Option<(f64, f64, Option<String>)>,
233
234    /// Id of the currently maximized panel (via `regular-layout.maximize`), or
235    /// `None`. Transient (regular-layout doesn't persist it); drives the
236    /// Maximize/Restore menu label. Cleared when the panel leaves the layout.
237    maximized: Option<String>,
238
239    /// Theme-name-keyed cache of backgrounds read off stamped plugin
240    /// elements, the mirror source for frames whose own plugin is unreadable
241    /// (see [`frame_theme`]). Cleared when the theme registry changes.
242    theme_backgrounds: HashMap<String, String>,
243
244    /// The inputs `stamp_frame_themes` last mirrored from; unchanged inputs
245    /// skip the pass (and its forced style recalcs) on unrelated re-renders.
246    /// `None` until the first *fully-resolved* pass — an unresolved frame
247    /// leaves it unlatched so the mirror retries each render.
248    stamped_frame_themes: Option<frame_theme::FrameThemeSnapshot>,
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
255impl Component for MainPanel {
256    type Message = MainPanelMsg;
257    type Properties = MainPanelProps;
258
259    fn create(ctx: &Context<Self>) -> Self {
260        let cb = ctx.link().callback(|_: ()| MainPanelMsg::LayoutUpdated);
261        let listener = Closure::wrap(
262            Box::new(move |_: web_sys::Event| cb.emit(())) as Box<dyn FnMut(web_sys::Event)>
263        );
264
265        let select_cb = ctx.link().callback(MainPanelMsg::TabSelected);
266        let select_listener = Closure::wrap(Box::new(move |event: web_sys::Event| {
267            #[derive(serde::Deserialize)]
268            struct SelectDetail {
269                name: String,
270            }
271
272            if let Some(custom) = event.dyn_ref::<web_sys::CustomEvent>()
273                && let Ok(SelectDetail { name }) = custom.detail().into_serde_ext()
274            {
275                select_cb.emit(name);
276            }
277        }) as Box<dyn FnMut(web_sys::Event)>);
278
279        // `preventDefault()` synchronously suspends the layout's resize commit
280        // (the event is cancelable); the component then pre-sizes each panel and
281        // calls `resumeResize` to release it (see `MainPanelMsg::BeforeResize`).
282        let before_resize_cb = ctx.link().callback(MainPanelMsg::BeforeResize);
283        let before_resize_listener = Closure::wrap(Box::new(move |event: web_sys::Event| {
284            event.prevent_default();
285            before_resize_cb.emit(event);
286        }) as Box<dyn FnMut(web_sys::Event)>);
287
288        // Imperative `contextmenu` listener: a right-click anywhere in a panel
289        // (the plugin body included) opens the panel menu. The plugin body is
290        // light-DOM attached by the renderer, so a Yew `oncontextmenu` on the
291        // frame never matches it (Yew walks the vdom, not the composed path).
292        // This native listener resolves the panel from the
293        // `<regular-layout-frame name=…>` on the event's composed path, then
294        // suppresses the browser menu and emits. On the EMPTY stage (zero
295        // panels — the persistent `<regular-layout>` has no frame
296        // descendants), it opens the stage menu instead, whose "New" items
297        // create the first panel.
298        let contextmenu_cb = ctx
299            .link()
300            .callback(|(id, x, y)| MainPanelMsg::ContextMenu(id, x, y));
301        let contextmenu_listener = Closure::wrap(Box::new(move |event: web_sys::Event| {
302            // Shift+right-click passes through to the native browser menu.
303            if event.unchecked_ref::<web_sys::MouseEvent>().shift_key() {
304                return;
305            }
306
307            let path = event.composed_path();
308            let mut panel_id = None;
309            for i in 0..path.length() {
310                let node = path.get(i);
311                if let Some(el) = node.dyn_ref::<web_sys::Element>()
312                    && el.tag_name().eq_ignore_ascii_case("regular-layout-frame")
313                    && let Some(name) = el.get_attribute("name")
314                {
315                    panel_id = Some(name);
316                    break;
317                }
318            }
319
320            let is_empty_stage = || {
321                event
322                    .current_target()
323                    .and_then(|t| t.dyn_into::<web_sys::Element>().ok())
324                    .is_some_and(|el| {
325                        el.query_selector("regular-layout-frame")
326                            .ok()
327                            .flatten()
328                            .is_none()
329                    })
330            };
331
332            if let Some(id) = panel_id {
333                event.prevent_default();
334                let mouse = event.unchecked_ref::<web_sys::MouseEvent>();
335                contextmenu_cb.emit((Some(id), mouse.client_x() as f64, mouse.client_y() as f64));
336            } else if is_empty_stage() {
337                event.prevent_default();
338                let mouse = event.unchecked_ref::<web_sys::MouseEvent>();
339                contextmenu_cb.emit((None, mouse.client_x() as f64, mouse.client_y() as f64));
340            }
341            // With panels present, a click outside every frame lets the
342            // native menu through.
343        }) as Box<dyn FnMut(web_sys::Event)>);
344
345        let staged_sub = {
346            use crate::utils::AddListener;
347            let cb = ctx.link().callback(|_: ()| MainPanelMsg::StagedChanged);
348            ctx.props()
349                .workspace
350                .staged_changed()
351                .add_listener(move |()| cb.emit(()))
352        };
353
354        Self {
355            main_panel_ref: NodeRef::default(),
356            layout_ref: NodeRef::default(),
357            inserted: Vec::new(),
358            pending_removals: HashSet::new(),
359            _layout_update_listener: listener,
360            _layout_select_listener: select_listener,
361            _layout_before_resize_listener: before_resize_listener,
362            _contextmenu_listener: contextmenu_listener,
363            listener_target: None,
364            panel_resize_observers: HashMap::new(),
365            hidden_tabs: HashSet::new(),
366            context_menu: None,
367            maximized: None,
368            theme_backgrounds: HashMap::new(),
369            stamped_frame_themes: None,
370            _staged_sub: staged_sub,
371        }
372    }
373
374    fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
375        match msg {
376            MainPanelMsg::PointerEvent(event) => self.on_pointer_event(ctx, event),
377            MainPanelMsg::StagedChanged => true,
378            MainPanelMsg::LayoutUpdated => self.on_layout_updated(ctx),
379            MainPanelMsg::TabSelected(name) => self.on_tab_selected(ctx, name),
380            MainPanelMsg::ContextMenu(id, x, y) => self.on_context_menu(ctx, id, x, y),
381            MainPanelMsg::CloseContextMenu => self.on_close_context_menu(),
382            MainPanelMsg::Command(cmd) => self.on_command(ctx, cmd),
383            MainPanelMsg::BeforeResize(event) => self.on_before_resize(ctx, event),
384        }
385    }
386
387    fn changed(&mut self, ctx: &Context<Self>, old: &Self::Properties) -> bool {
388        self.close_unstaged_panels(ctx, old);
389        ctx.props() != old
390    }
391
392    fn rendered(&mut self, ctx: &Context<Self>, first_render: bool) {
393        // The `contextmenu` listener attaches to the panel CONTAINER — one
394        // stable attach point covering the whole stage, decoupled from the
395        // layout reconcile. Panel right-clicks bubble to it through the
396        // layout on the composed path; at zero panels it serves the stage
397        // menu.
398        if first_render && let Some(el) = self.main_panel_ref.cast::<web_sys::HtmlElement>() {
399            let _ = el.add_event_listener_with_callback(
400                "contextmenu",
401                self._contextmenu_listener.as_ref().unchecked_ref(),
402            );
403        }
404
405        self.size_staging_wrappers();
406        self.reconcile(ctx);
407        self.stamp_frame_themes(ctx);
408    }
409
410    fn view(&self, ctx: &Context<Self>) -> Html {
411        self.render(ctx)
412    }
413
414    fn destroy(&mut self, _ctx: &Context<Self>) {}
415}
416
417impl MainPanel {
418    /// Report closed every panel gone from the model that the layout never
419    /// held, since it has no commit to wait for.
420    fn close_unstaged_panels(&self, ctx: &Context<Self>, old: &MainPanelProps) {
421        for id in &old.panel_ids {
422            if !ctx.props().panel_ids.contains(id)
423                && !self.inserted.iter().any(|n| n == id.as_str())
424            {
425                ctx.props().on_panel_closed.emit(id.as_str().to_owned());
426            }
427        }
428    }
429}