Skip to main content

perspective_viewer/queries/
resolve_commands.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 js_sys::{Array, Object, Reflect};
14use perspective_client::config::ViewConfig;
15use perspective_js::utils::*;
16use wasm_bindgen::prelude::*;
17
18use super::resolve_hit::{ViewFrame, resolve_hit};
19use crate::config::{CommandLocation, CommandSchema, CommandSpec, PerspectiveHitRef};
20use crate::presentation::Presentation;
21use crate::workspace::{Panel, Workspace};
22
23impl CommandLocation {
24    pub fn as_str(self) -> &'static str {
25        match self {
26            Self::ContextMenu => "context-menu",
27            Self::DatagridRow => "datagrid-row",
28            Self::DatagridCell => "datagrid-cell",
29            Self::ChartTooltip => "chart-tooltip",
30        }
31    }
32}
33
34/// The app's commands resolved for one gesture, with the context the schema
35/// was evaluated against.
36#[derive(Debug, Default)]
37pub struct ResolvedCommands {
38    pub context: JsValue,
39    pub commands: Vec<CommandSpec>,
40}
41
42/// The panel whose active plugin element is `plugin`.
43pub fn panel_for_plugin(workspace: &Workspace, plugin: &JsValue) -> Option<Panel> {
44    workspace.panels().into_iter().find(|panel| {
45        panel
46            .renderer
47            .active_plugin()
48            .is_some_and(|active| AsRef::<JsValue>::as_ref(&active) == plugin)
49    })
50}
51
52/// The view config `panel` is rendering, as `getViewConfig()` reports it.
53pub fn panel_view_config(panel: &Panel) -> ViewConfig {
54    if let Some(ctx) = panel.renderer.render_context() {
55        (*ctx.view_config).clone()
56    } else if let Some(rendered) = panel.session.get_rendered_view_config() {
57        (*rendered).clone()
58    } else {
59        panel.session.get_view_config().clone()
60    }
61}
62
63/// Build the command context for `panel` and evaluate the app's command
64/// schema against it.
65pub async fn resolve_commands(
66    presentation: &Presentation,
67    panel: Option<&Panel>,
68    location: CommandLocation,
69    point: (f64, f64),
70    hit_test: bool,
71) -> ResolvedCommands {
72    let hit = match panel {
73        Some(panel) if hit_test => plugin_hit(panel, point).await,
74        _ => None,
75    };
76
77    let context = match command_context(panel, location, Some(point), hit) {
78        Ok(context) => context,
79        Err(err) => {
80            tracing::error!("Failed to build command context: {err}");
81            return ResolvedCommands::default();
82        },
83    };
84
85    let commands = presentation
86        .command_schema_for(location)
87        .map(
88            |schema| match call_schema(&schema, &context).and_then(parse_schema) {
89                Ok(schema) => schema.commands,
90                Err(err) => {
91                    tracing::error!("Ignoring the command schema of the app: {err}");
92                    vec![]
93                },
94            },
95        )
96        .unwrap_or_default();
97
98    ResolvedCommands { context, commands }
99}
100
101/// Evaluate the app's schema at `location` for every ref in `refs` against
102/// `frame`, or `None` when `location` is out of the schema's scopes.
103pub fn query_commands(
104    presentation: &Presentation,
105    panel: &Panel,
106    location: CommandLocation,
107    frame: &JsValue,
108    refs: &JsValue,
109) -> ApiResult<Option<Array>> {
110    let Some(schema) = presentation.command_schema_for(location) else {
111        return Ok(None);
112    };
113
114    let frame = ViewFrame::new(frame)?;
115    let refs: Vec<PerspectiveHitRef> = refs.into_serde_ext()?;
116    let config = panel_view_config(panel);
117    let index = panel
118        .session
119        .get_table()
120        .and_then(|table| table.get_index());
121    let base = command_context(Some(panel), location, None, None)?;
122    let results = Array::new();
123    let mut failed = false;
124    for hit_ref in refs {
125        let hit =
126            JsValue::from_serde_ext(&resolve_hit(&config, index.as_ref(), &frame, &hit_ref)?)?;
127        let context = Object::assign(&Object::new(), base.unchecked_ref::<Object>());
128        Reflect::set(&context, &"hit".into(), &hit)?;
129        let commands = if failed {
130            Array::new().into()
131        } else {
132            match call_schema(&schema, &context).and_then(validate_schema) {
133                Ok(commands) => commands,
134                Err(err) => {
135                    tracing::error!("Ignoring the command schema of the app: {err}");
136                    failed = true;
137                    Array::new().into()
138                },
139            }
140        };
141
142        let entry = Object::new();
143        Reflect::set(&entry, &"context".into(), &context)?;
144        Reflect::set(&entry, &"commands".into(), &commands)?;
145        results.push(&entry);
146    }
147
148    Ok(Some(results))
149}
150
151fn call_schema(schema: &js_sys::Function, context: &JsValue) -> ApiResult<JsValue> {
152    Ok(schema.call1(&JsValue::UNDEFINED, context)?)
153}
154
155fn parse_schema(value: JsValue) -> ApiResult<CommandSchema> {
156    Ok(value.into_serde_ext()?)
157}
158
159/// Validate a schema's return and hand back its own `commands` array.
160fn validate_schema(value: JsValue) -> ApiResult<JsValue> {
161    parse_schema(value.clone())?;
162    Ok(Reflect::get(&value, &"commands".into())?)
163}
164
165async fn plugin_hit(panel: &Panel, (x, y): (f64, f64)) -> Option<JsValue> {
166    let plugin = panel.renderer.active_plugin()?;
167    let result = panel
168        .renderer
169        .clone()
170        .with_lock(async { plugin.hit_test(x, y).await })
171        .await;
172
173    let hit_test = match result {
174        Ok(hit_test) => hit_test?,
175        Err(err) => {
176            tracing::error!(
177                "Ignoring the `hit_test` of plugin \"{}\": {err}",
178                panel.renderer.metadata().name
179            );
180
181            return None;
182        },
183    };
184
185    match resolve_hit_test(panel, &hit_test) {
186        Ok(hit) => Some(hit),
187        Err(err) => {
188            tracing::error!(
189                "Ignoring the `hit_test` of plugin \"{}\": {err}",
190                panel.renderer.metadata().name
191            );
192
193            None
194        },
195    }
196}
197
198/// Resolve a plugin's `{ frame, ref }` hit test against `panel`'s config.
199fn resolve_hit_test(panel: &Panel, hit_test: &JsValue) -> ApiResult<JsValue> {
200    let frame = ViewFrame::new(&Reflect::get(hit_test, &"frame".into())?)?;
201    let hit_ref: PerspectiveHitRef = Reflect::get(hit_test, &"ref".into())?.into_serde_ext()?;
202    let index = panel
203        .session
204        .get_table()
205        .and_then(|table| table.get_index());
206    let hit = resolve_hit(&panel_view_config(panel), index.as_ref(), &frame, &hit_ref)?;
207    Ok(JsValue::from_serde_ext(&hit)?)
208}
209
210/// The context a command schema is evaluated against, without a `hit`.
211pub fn command_context(
212    panel: Option<&Panel>,
213    location: CommandLocation,
214    point: Option<(f64, f64)>,
215    hit: Option<JsValue>,
216) -> ApiResult<JsValue> {
217    let context = Object::new();
218    let set = |key: &str, value: &JsValue| Reflect::set(&context, &key.into(), value);
219    set("location", &location.as_str().into())?;
220    if let Some(panel) = panel {
221        set("panel", &panel.id.as_str().into())?;
222        if let Some(table) = panel.session.get_table() {
223            set("table", &table.get_name().into())?;
224        }
225
226        if panel.renderer.active_plugin().is_some() {
227            set("plugin", &panel.renderer.metadata().name.as_str().into())?;
228        }
229
230        set(
231            "view_config",
232            &JsValue::from_serde_ext(&panel_view_config(panel))?,
233        )?;
234    }
235
236    if let Some((x, y)) = point {
237        let point = Object::new();
238        Reflect::set(&point, &"x".into(), &x.into())?;
239        Reflect::set(&point, &"y".into(), &y.into())?;
240        set("point", &point)?;
241    }
242
243    if let Some(hit) = hit {
244        set("hit", &hit)?;
245    }
246
247    Ok(context.into())
248}