Skip to main content

perspective_viewer/components/
plugin_tab.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//! Plugin-scoped settings tab. Mirrors `style_tab` but operates on the
14//! active plugin's `save()`/`restore()` token rather than a per-column
15//! config map. The schema comes from `plugin.plugin_config_schema()`;
16//! field updates are dispatched through `tasks::send_plugin_config`.
17
18use itertools::Itertools;
19use perspective_client::config::ViewConfig;
20use yew::prelude::*;
21
22use crate::components::column_settings_sidebar::style_tab::alignment_field::AlignmentField;
23use crate::components::column_settings_sidebar::style_tab::font_field::FontField;
24use crate::components::column_settings_sidebar::style_tab::primitive_field::{
25    BoolField, ColorField, EnumField, NumberFieldPrimitive,
26};
27use crate::config::{Alignment, ControlSpec, FontToggle};
28use crate::presentation::Presentation;
29use crate::queries::get_plugin_config_schema;
30use crate::renderer::{ConfigDefaultsSlots, Renderer};
31use crate::session::Session;
32use crate::tasks::send_plugin_config;
33use crate::ui::ControlGroup;
34use crate::utils::PtrEqRc;
35
36#[derive(Clone, PartialEq, Properties)]
37pub struct PluginTabProps {
38    /// View config snapshot — passed to the plugin schema callback in
39    /// case the plugin wants to gate fields based on it.
40    pub view_config: PtrEqRc<ViewConfig>,
41
42    /// Active plugin's `plugin_config` bucket — threaded as a value
43    /// snapshot from `RendererProps`. Changes on every mutation path
44    /// that fires `plugin_config_changed` (in-tab edit,
45    /// `restore` JSON paste, `reset_all` with `all=true`)
46    /// AND on plugin switch (the active bucket is keyed by plugin
47    /// name, so `to_props()` produces a fresh `Rc` after
48    /// a restore or edit commit). PluginTab is a pure function of this
49    /// prop — no `Renderer::get_plugin_config()` reads against the
50    /// interior-mutable handle.
51    pub plugin_config: PtrEqRc<serde_json::Map<String, serde_json::Value>>,
52
53    /// The page-wide config defaults the schema applies.
54    pub config_defaults: PtrEqRc<ConfigDefaultsSlots>,
55
56    // State
57    pub presentation: Presentation,
58    pub renderer: Renderer,
59    pub session: Session,
60}
61
62#[function_component]
63pub fn PluginTab(props: &PluginTabProps) -> Html {
64    // Memoize the JS-side `plugin_config_schema` call. The schema is a
65    // function of (active plugin, current plugin_config values,
66    // view_config); each of those arrives as a prop so the deps tuple
67    // uses cheap pointer-equality / value-equality. Yew re-runs the
68    // closure only when one of them actually changed, so the JS
69    // round-trip doesn't fire on unrelated re-renders.
70    //
71    // The closure captures `renderer` to dispatch `_plugin_config_schema`
72    // through the active plugin handle, but resolves it via the props
73    // at call time so the schema query is bound to the same atomic
74    // snapshot the rendered controls read from. No race window between
75    // a plugin swap and the schema fetch — both observe the same
76    // `RendererProps` value.
77    let schema = {
78        let renderer = props.renderer.clone();
79        let view_config = props.view_config.clone();
80        let plugin_config = props.plugin_config.clone();
81        use_memo(
82            (
83                props.plugin_config.clone(),
84                props.view_config.clone(),
85                props.config_defaults.clone(),
86            ),
87            move |_| match get_plugin_config_schema(&renderer, &view_config, Some(&plugin_config)) {
88                Ok(schema) => schema.fields,
89                Err(error) => {
90                    tracing::error!("{}", error);
91                    vec![]
92                },
93            },
94        )
95    };
96
97    let on_change = {
98        let session = props.session.clone();
99        let renderer = props.renderer.clone();
100        yew::Callback::from(move |update: crate::config::ColumnConfigFieldUpdate| {
101            // `send_plugin_config` emits `plugin_config_changed`,
102            // which the root component's subscription
103            // (`create_active_subscriptions`) turns into an `UpdateRenderer`
104            // dispatch carrying a fresh `RendererProps`. Yew's prop
105            // diff propagates the new `plugin_config` into this
106            // component automatically — no manual revision bump.
107            send_plugin_config(&session, &renderer, update);
108        })
109    };
110
111    let on_group_toggle = {
112        let presentation = props.presentation.clone();
113        yew::Callback::from(move |(key, open): (String, bool)| {
114            presentation.set_control_group_collapsed(&key, !open);
115        })
116    };
117
118    let raw_config = &*props.plugin_config;
119    let components = render_specs(
120        &schema,
121        raw_config,
122        &on_change,
123        &props.presentation,
124        &on_group_toggle,
125    );
126    html! {
127        <div id="plugin-tab" class="sidebar_column scrollable">
128            <div id="plugin-config-container" class="tab-section">{ components }</div>
129        </div>
130    }
131}
132
133fn render_specs(
134    specs: &[ControlSpec],
135    raw_config: &serde_json::Map<String, serde_json::Value>,
136    on_change: &Callback<crate::config::ColumnConfigFieldUpdate>,
137    presentation: &Presentation,
138    on_group_toggle: &Callback<(String, bool)>,
139) -> Vec<Html> {
140    specs
141        .iter()
142        .filter_map(|spec| match spec {
143            ControlSpec::Group { key, fields } => {
144                let children =
145                    render_specs(fields, raw_config, on_change, presentation, on_group_toggle);
146
147                (!children.is_empty()).then(|| {
148                    html! {
149                        <ControlGroup
150                            key={format!("group::{key}")}
151                            group_key={key.clone()}
152                            open={!presentation.is_control_group_collapsed(key)}
153                            on_toggle={on_group_toggle.clone()}
154                        >
155                            { children }
156                        </ControlGroup>
157                    }
158                })
159            },
160            leaf => {
161                let key = leaf.serialized_keys().join("+");
162                let component = render_leaf(leaf, raw_config, on_change)?;
163                Some(html! { <fieldset class="style-control" {key}>{ component }</fieldset> })
164            },
165        })
166        .collect_vec()
167}
168
169fn render_leaf(
170    spec: &ControlSpec,
171    raw_config: &serde_json::Map<String, serde_json::Value>,
172    on_change: &Callback<crate::config::ColumnConfigFieldUpdate>,
173) -> Option<Html> {
174    match spec.clone() {
175        ControlSpec::Enum {
176            key,
177            variants,
178            default,
179        } => {
180            let current = raw_config
181                .get(&key)
182                .and_then(|v| v.as_str().map(|s| s.to_string()));
183            Some(html! {
184                <EnumField
185                    field_key={key}
186                    {variants}
187                    {default}
188                    {current}
189                    on_change={on_change.clone()}
190                />
191            })
192        },
193        ControlSpec::Font {
194            key,
195            default,
196            size,
197            bold,
198            italic,
199        } => {
200            let current = raw_config
201                .get(&key)
202                .and_then(|v| v.as_str().map(|s| s.to_string()));
203            let toggle = |t: &FontToggle| raw_config.get(&t.key).and_then(|v| v.as_bool());
204            let size_current = size
205                .as_ref()
206                .and_then(|s| raw_config.get(&s.key))
207                .and_then(|v| v.as_f64());
208            let bold_current = bold.as_ref().and_then(toggle);
209            let italic_current = italic.as_ref().and_then(toggle);
210            Some(html! {
211                <FontField
212                    field_key={key}
213                    {default}
214                    {current}
215                    {size}
216                    {size_current}
217                    {bold}
218                    {bold_current}
219                    {italic}
220                    {italic_current}
221                    on_change={on_change.clone()}
222                />
223            })
224        },
225        ControlSpec::Alignment {
226            key,
227            default,
228            corners,
229        } => {
230            let current = raw_config
231                .get(&key)
232                .and_then(|v| v.as_str())
233                .and_then(Alignment::parse);
234
235            Some(html! {
236                <AlignmentField
237                    field_key={key}
238                    {default}
239                    {corners}
240                    {current}
241                    on_change={on_change.clone()}
242                />
243            })
244        },
245        ControlSpec::Bool { key, default } => {
246            let current = raw_config.get(&key).and_then(|v| v.as_bool());
247            Some(html! {
248                <BoolField field_key={key} {default} {current} on_change={on_change.clone()} />
249            })
250        },
251        ControlSpec::Color { key, default } => {
252            let current = raw_config
253                .get(&key)
254                .and_then(|v| v.as_str().map(|s| s.to_string()));
255            Some(html! {
256                <ColorField field_key={key} {default} {current} on_change={on_change.clone()} />
257            })
258        },
259        ControlSpec::Number {
260            key,
261            default,
262            min,
263            max,
264            step,
265            include,
266            ..
267        } => {
268            let current = raw_config.get(&key).and_then(|v| v.as_f64());
269            Some(html! {
270                <NumberFieldPrimitive
271                    field_key={key}
272                    {default}
273                    {current}
274                    {min}
275                    {max}
276                    {step}
277                    {include}
278                    on_change={on_change.clone()}
279                />
280            })
281        },
282        ControlSpec::Group { .. }
283        | ControlSpec::AggregateDepth
284        | ControlSpec::NumberSeriesStyle { .. }
285        | ControlSpec::DatetimeFormat { .. }
286        | ControlSpec::Symbols { .. }
287        | ControlSpec::NumberFormat { .. }
288        | ControlSpec::String { .. }
289        | ControlSpec::Palette { .. }
290        | ControlSpec::GradientStops { .. } => None,
291    }
292}