Skip to main content

perspective_viewer/components/
settings_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
13use std::rc::Rc;
14
15use perspective_client::config::{ViewConfig, ViewConfigUpdate};
16use perspective_js::utils::ApiFuture;
17use yew::prelude::*;
18
19use super::column_selector::ColumnSelector;
20use super::plugin_selector::PluginSelector;
21use super::plugin_tab::PluginTab;
22use crate::components::debug_panel::DebugPanel;
23use crate::config::{PluginStaticConfig, PluginUpdate};
24use crate::presentation::{ColumnLocator, ColumnSettingsTarget, OpenColumnSettings, Presentation};
25use crate::queries::{classify_column, is_pivot_column};
26use crate::renderer::*;
27use crate::session::column_defaults_update::*;
28use crate::session::*;
29use crate::tasks::update_plugin_and_render;
30use crate::ui::SidebarCloseButton;
31use crate::utils::*;
32use crate::workspace::Workspace;
33
34#[derive(Clone, Properties)]
35pub struct SettingsPanelProps {
36    pub on_close: Callback<()>,
37    pub on_resize: Rc<PubSub<()>>,
38    pub on_select_column: Callback<Option<ColumnSettingsTarget>>,
39    pub on_debug: Callback<()>,
40    pub is_debug: bool,
41
42    /// Value props threaded from the root's `RendererProps` / `SessionProps`.
43    pub plugin_name: Option<String>,
44    pub available_plugins: PtrEqRc<Vec<String>>,
45    pub has_table: Option<TableLoadState>,
46    pub named_column_count: usize,
47
48    /// The ACTIVE plugin's declared contract, threaded as a value prop so
49    /// that switching plugins re-renders the panes that read it. The
50    /// renderer handle cannot serve this: it is excluded from prop
51    /// equality (it is a handle, not a value), so a plugin swap that
52    /// leaves the view config untouched — Y Line back to Datagrid, both
53    /// of which name one column slot — would otherwise change nothing any
54    /// component compares.
55    pub plugin_static_config: Rc<PluginStaticConfig>,
56    pub view_config: PtrEqRc<ViewConfig>,
57
58    /// Snapshot of the active plugin's `plugin_config` bucket, threaded
59    /// from `RendererProps`. Forwarded into `PluginTab` so the tab is
60    /// prop-driven instead of reading `Renderer` directly.
61    pub plugin_config: PtrEqRc<serde_json::Map<String, serde_json::Value>>,
62
63    /// Snapshot of the active plugin's `columns_config` bucket, threaded
64    /// from `RendererProps` into `ColumnSelector`.
65    pub columns_config: PtrEqRc<ColumnConfigMap>,
66
67    /// The page-wide config defaults, forwarded into `PluginTab`.
68    pub config_defaults: PtrEqRc<ConfigDefaultsSlots>,
69
70    /// Column currently being dragged (if any) — threaded to show drag
71    /// highlights without per-component `DragDrop` PubSub subscriptions.
72    pub drag_column: Option<String>,
73
74    /// Cloned session metadata snapshot — threaded from `SessionProps`
75    /// so that metadata changes trigger re-renders via prop diffing.
76    pub metadata: SessionMetadataRc,
77
78    /// Snapshot of the column-settings sidebar state — threaded from
79    /// `PresentationProps` so that open/close triggers re-renders.
80    pub open_column_settings: OpenColumnSettings,
81
82    /// Selected theme name, threaded for PortalModal consumers.
83    pub selected_theme: Option<String>,
84
85    /// Controlled: the currently selected tab. Lifted to `PerspectiveViewer`
86    /// so that messages like `OpenColumnSettings` can revert the tab without
87    /// the panel owning the state.
88    pub selected_tab: SelectedTab,
89
90    /// Controlled: the running max of measured tab widths. Lifted so that
91    /// `SettingsPanelSizeUpdate(None)` (divider reset) can clear it.
92    pub auto_width: f64,
93
94    /// Callback invoked when the user clicks a tab.
95    pub on_select_tab: Callback<SelectedTab>,
96
97    /// Callback invoked by tab subtrees reporting their natural width.
98    pub on_auto_width: Callback<f64>,
99
100    /// Fires when the outer split-panel divider is reset; threaded into
101    /// `ColumnSelector` so its inner `ScrollPanel` can drop its persistent
102    /// `viewport_width` and re-measure honestly. Without this, the
103    /// `auto_width` reset in `PerspectiveViewer` rebounds immediately as
104    /// the ScrollPanel republishes its stale cached width.
105    pub on_dimensions_reset: Rc<PubSub<()>>,
106
107    /// State
108    pub session: Session,
109    pub renderer: Renderer,
110    pub presentation: Presentation,
111    pub workspace: Workspace,
112}
113
114impl PartialEq for SettingsPanelProps {
115    fn eq(&self, rhs: &Self) -> bool {
116        self.is_debug == rhs.is_debug
117            && self.plugin_name == rhs.plugin_name
118            && self.available_plugins == rhs.available_plugins
119            && self.has_table == rhs.has_table
120            && self.named_column_count == rhs.named_column_count
121            && self.plugin_static_config == rhs.plugin_static_config
122            && self.view_config == rhs.view_config
123            && self.plugin_config == rhs.plugin_config
124            && self.columns_config == rhs.columns_config
125            && self.config_defaults == rhs.config_defaults
126            && self.drag_column == rhs.drag_column
127            && self.metadata == rhs.metadata
128            && self.open_column_settings == rhs.open_column_settings
129            && self.selected_theme == rhs.selected_theme
130            && self.selected_tab == rhs.selected_tab
131            && self.auto_width == rhs.auto_width
132    }
133}
134
135#[derive(Debug, PartialEq, Clone, Copy, Default)]
136pub enum SelectedTab {
137    #[default]
138    Query,
139    Plugin,
140    Debug,
141
142    /// The embedded LLM agent's chat panel. The variant exists in every
143    /// build; its tab button and body render only under the `llm-agent`
144    /// feature, and only once `agentConfig()` has been called.
145    Chat,
146}
147
148#[function_component]
149pub fn SettingsPanel(props: &SettingsPanelProps) -> Html {
150    let SettingsPanelProps {
151        presentation,
152        renderer,
153        session,
154        ..
155    } = &props;
156
157    let selected_column = {
158        let config = &props.view_config;
159        props
160            .open_column_settings
161            .target
162            .as_ref()
163            .and_then(|target| match target {
164                ColumnSettingsTarget::NewExpression => Some(ColumnLocator::NewExpression),
165                ColumnSettingsTarget::Column(n) => {
166                    let locator = classify_column(n, config, &props.metadata)?;
167                    if !matches!(locator, ColumnLocator::Table(_)) {
168                        return Some(locator);
169                    }
170
171                    let used = config.columns.iter().any(|maybe_col| {
172                        maybe_col.as_ref().map(|col| col == n).unwrap_or_default()
173                    }) || is_pivot_column(n, config)
174                        || config.filter.iter().any(|col| col.column() == n)
175                        || config.sort.iter().any(|col| &col.0 == n);
176                    (used && props.renderer.can_render_column_styles()).then_some(locator)
177                },
178            })
179    };
180
181    let plugin_name = props.plugin_name.clone();
182    let available_plugins = props.available_plugins.clone();
183    let selected = props.selected_tab;
184
185    // Shared trap-door width across tabs. Each tab subtree measures its
186    // natural width and feeds the result back through `on_auto_width`;
187    // the parent keeps the running max so a tab switch never shrinks the
188    // panel, and clears it on divider reset.
189    let width = props.auto_width;
190    let on_auto_width = props.on_auto_width.clone();
191
192    // Dispatch callback: captures engine handles, constructs config update,
193    // hands the apply+draw work to `tasks::pipeline`.
194    let on_select_plugin = {
195        clone!(renderer, session, presentation);
196        let session_metadata = props.metadata.clone();
197        let view_config = props.view_config.clone();
198        Callback::from(move |plugin_name: String| {
199            if session.is_errored() || renderer.failure().is_some() {
200                return;
201            }
202            // Pure resolve — the swap itself is committed inside the locked
203            // draw task by `update_plugin_and_render`, never staged on the
204            // `Renderer` where a concurrent draw could observe it.
205            let resolved_plugin =
206                renderer.resolve_plugin_update(&PluginUpdate::Update(plugin_name));
207            let prev_metadata = renderer.metadata();
208            let plugin_config = resolved_plugin
209                .as_ref()
210                .map(|(_, metadata)| &**metadata)
211                .unwrap_or(&*prev_metadata);
212            let rollup_features = session_metadata
213                .get_features()
214                .map(|x| x.get_group_rollup_modes())
215                .unwrap();
216
217            let group_rollups = plugin_config.get_group_rollups(&rollup_features);
218            let split_rollup_features = session_metadata
219                .get_features()
220                .map(|x| x.get_split_rollup_modes())
221                .unwrap();
222
223            let split_rollups = plugin_config.get_split_rollups(&split_rollup_features);
224            let mut update = ViewConfigUpdate {
225                group_rollup_mode: group_rollups.first().cloned(),
226                split_rollup_mode: split_rollups.first().cloned(),
227                ..ViewConfigUpdate::default()
228            };
229
230            update.set_update_column_defaults(
231                &session_metadata,
232                &view_config,
233                &view_config.columns,
234                plugin_config,
235            );
236
237            let plugin_idx = resolved_plugin.map(|(idx, _)| idx);
238            if let Ok(task) = update_plugin_and_render(&session, &renderer, update, plugin_idx) {
239                ApiFuture::spawn(task);
240            }
241
242            presentation.set_open_column_settings(None);
243        })
244    };
245
246    let cb1 = props.on_select_column.clone();
247    let set_debug = use_callback(
248        props.on_select_tab.clone(),
249        move |_: PointerEvent, on_select_tab| {
250            on_select_tab.emit(SelectedTab::Debug);
251            cb1.emit(None)
252        },
253    );
254
255    let cb2 = props.on_select_column.clone();
256    let set_plugin = use_callback(
257        props.on_select_tab.clone(),
258        move |_: PointerEvent, on_select_tab| {
259            on_select_tab.emit(SelectedTab::Plugin);
260            cb2.emit(None)
261        },
262    );
263
264    let set_query = use_callback(
265        props.on_select_tab.clone(),
266        |_: PointerEvent, on_select_tab| on_select_tab.emit(SelectedTab::Query),
267    );
268
269    let tab_class = |l_tab: SelectedTab, r_tab: SelectedTab| {
270        if l_tab == r_tab {
271            "settings_tab selected_tab"
272        } else {
273            "settings_tab"
274        }
275    };
276
277    // The chat tab is zero-affordance until `agentConfig()` is called; the
278    // subscription re-renders this panel when that happens (and as the
279    // transcript updates while the chat body is mounted).
280    #[cfg(feature = "llm-agent")]
281    let (chat_tab_button, chat_body) = {
282        let update = use_force_update();
283        let agent = presentation.agent.clone();
284        use_effect_with((), move |_| {
285            let sub = agent
286                .on_update
287                .add_notify_listener(&Callback::from(move |_| update.force_update()));
288
289            move || drop(sub)
290        });
291
292        let button = if presentation.agent.is_configured() {
293            let on_select_column = props.on_select_column.clone();
294            let set_chat = {
295                let on_select_tab = props.on_select_tab.clone();
296                Callback::from(move |_: PointerEvent| {
297                    on_select_tab.emit(SelectedTab::Chat);
298                    on_select_column.emit(None)
299                })
300            };
301
302            html! {
303                <div
304                    id="chat_tabbar_tab"
305                    class={tab_class(selected, SelectedTab::Chat)}
306                    onpointerdown={set_chat}
307                />
308            }
309        } else {
310            html! {}
311        };
312
313        let body = html! {
314            <crate::components::chat_panel::ChatPanel agent={presentation.agent.clone()} />
315        };
316
317        (button, body)
318    };
319
320    #[cfg(not(feature = "llm-agent"))]
321    let (chat_tab_button, chat_body) = (html! {}, html! {});
322
323    let on_open_expr_panel = use_callback(props.on_select_column.clone(), |c, on_select| {
324        on_select.emit(Some(c))
325    });
326
327    html! {
328        <div id="settings_panel" class="sidebar_column noselect split-panel orient-vertical">
329            if selected_column.is_none() {
330                <SidebarCloseButton
331                    id="settings_close_button"
332                    on_close_sidebar={&props.on_close.clone()}
333                />
334            }
335            <PluginSelector
336                {plugin_name}
337                {available_plugins}
338                {on_select_plugin}
339            />
340            <div id="settings_tab_bar" class="settings_tab_bar_scroll_offset">
341                <div
342                    id="query_tabbar_tab"
343                    class={tab_class(selected, SelectedTab::Query)}
344                    onpointerdown={set_query}
345                />
346                <div
347                    id="plugin_tabbar_tab"
348                    class={tab_class(selected, SelectedTab::Plugin)}
349                    onpointerdown={set_plugin}
350                />
351                <div
352                    id="debug_tabbar_tab"
353                    class={tab_class(selected, SelectedTab::Debug)}
354                    onpointerdown={set_debug}
355                />
356                { chat_tab_button }
357            </div>
358            if selected == SelectedTab::Query {
359                <ColumnSelector
360                    on_resize={&props.on_resize}
361                    {on_open_expr_panel}
362                    {selected_column}
363                    has_table={props.has_table.clone()}
364                    named_column_count={props.named_column_count}
365                    plugin_static_config={props.plugin_static_config.clone()}
366                    view_config={props.view_config.clone()}
367                    columns_config={props.columns_config.clone()}
368                    drag_column={props.drag_column.clone()}
369                    metadata={props.metadata.clone()}
370                    selected_theme={props.selected_theme.clone()}
371                    presentation={presentation.clone()}
372                    renderer={renderer.clone()}
373                    session={session.clone()}
374                    workspace={props.workspace.clone()}
375                    initial_width={width}
376                    on_auto_width={on_auto_width.clone()}
377                    on_dimensions_reset={&props.on_dimensions_reset}
378                />
379            } else if selected == SelectedTab::Plugin {
380                <PluginTab
381                    view_config={props.view_config.clone()}
382                    plugin_config={props.plugin_config.clone()}
383                    config_defaults={props.config_defaults.clone()}
384                    presentation={presentation.clone()}
385                    renderer={renderer.clone()}
386                    session={session.clone()}
387                // initial_width={width}
388                // on_auto_width={on_auto_width.clone()}
389                />
390            } else if selected == SelectedTab::Chat {
391                { chat_body }
392            } else {
393                <DebugPanel
394                    {presentation}
395                    {renderer}
396                    {session}
397                    workspace={props.workspace.clone()}
398                    initial_width={width}
399                    on_auto_width={on_auto_width.clone()}
400                />
401            }
402            // Sibling sizer keeps the panel width pinned across tab
403            // switches; lives outside the tab-body so it survives the
404            // tab subtree's unmount.
405            <div
406                class="scroll-panel-auto-width"
407                style={format!("width:{}px", width)}
408            />
409        </div>
410    }
411}