Skip to main content

perspective_viewer/custom_elements/
viewer.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#![allow(non_snake_case)]
14
15use std::cell::RefCell;
16use std::rc::Rc;
17
18use futures::channel::oneshot::channel;
19use futures::future::join_all;
20use js_sys::{Array, JsString};
21use perspective_client::config::ViewConfigUpdate;
22use perspective_js::utils::global;
23use perspective_js::{JsResolvedViewConfig, JsViewWindow, Table, View, apierror, ts_promise};
24use wasm_bindgen::JsCast;
25use wasm_bindgen::prelude::*;
26use wasm_bindgen_derive::try_from_js_option;
27use wasm_bindgen_futures::JsFuture;
28use web_sys::HtmlElement;
29use yew::Callback;
30
31#[cfg(feature = "llm-agent")]
32use crate::agent::AgentRuntime;
33use crate::components::command_menu::show_command_menu;
34use crate::components::viewer::{PerspectiveViewerMsg, PerspectiveViewerProps};
35use crate::config::*;
36use crate::custom_events::*;
37use crate::js::*;
38use crate::presentation::*;
39use crate::queries::*;
40use crate::root::Root;
41use crate::session::{BindPlan, Disposal, MissingTable, OpKind, ResetOptions, TableLoadState};
42use crate::tasks::*;
43use crate::utils::*;
44use crate::workspace::{Panel, PanelId, Workspace};
45use crate::*;
46
47#[wasm_bindgen]
48extern "C" {
49    /// `load()` argument: a [`Client`], a (deprecated) [`Table`], or a
50    /// `Promise` resolving to either. Typed rather than `any` so callers get
51    /// completion; the `Table` forms remain runtime-deprecated.
52    #[wasm_bindgen(typescript_type = "Client | Table | Promise<Client | Table>")]
53    pub type JsClientLoad;
54
55    /// `eject()` argument dict (`{ client?: string }`).
56    #[wasm_bindgen(typescript_type = "ClientOptions")]
57    pub type JsClientOptions;
58
59    /// Panel-selector dict (`{ panel?: string }`) for the active/base
60    /// accessor methods.
61    #[wasm_bindgen(typescript_type = "PanelOptions")]
62    pub type JsPanelOptions;
63
64    /// The `restore()` options dict.
65    #[wasm_bindgen(typescript_type = "RestoreOptions")]
66    pub type JsRestoreOptions;
67
68    /// The `restoreWorkspace()` options dict.
69    #[wasm_bindgen(typescript_type = "RestoreWorkspaceOptions")]
70    pub type JsRestoreWorkspaceOptions;
71
72    /// The `addPanel()` options dict.
73    #[wasm_bindgen(typescript_type = "AddPanelOptions")]
74    pub type JsAddPanelOptions;
75
76    /// `addPanel()` argument: a new panel's initial config — `table`
77    /// REQUIRED.
78    #[wasm_bindgen(typescript_type = "ViewerConfigInitial")]
79    pub type JsViewerConfigInitial;
80
81    /// `download`/`export`/`copy` options dict
82    /// (`{ method?: ExportMethod, panel?: string }`).
83    #[wasm_bindgen(typescript_type = "ExportOptions")]
84    pub type JsExportOptions;
85
86    /// `getTable` options dict (`{ wait?: boolean, panel?: string }`).
87    #[wasm_bindgen(typescript_type = "GetTableOptions")]
88    pub type JsGetTableOptions;
89
90    /// `getClient` options dict (`{ wait?: boolean, panel?: string }`).
91    #[wasm_bindgen(typescript_type = "GetClientOptions")]
92    pub type JsGetClientOptions;
93
94    /// `getView` options dict (`{ mode?: GetViewMode, panel?: string }`).
95    #[wasm_bindgen(typescript_type = "GetViewOptions")]
96    pub type JsGetViewOptions;
97
98    /// `saveWorkspace()` options dict (`{ full_palette?: boolean }`).
99    #[wasm_bindgen(typescript_type = "SaveWorkspaceOptions")]
100    pub type JsSaveWorkspaceOptions;
101
102    /// `save()` return: a single-panel config.
103    #[wasm_bindgen(typescript_type = "ViewerConfig")]
104    pub type JsViewerConfig;
105
106    /// `saveWorkspace()` return: a workspace config.
107    #[wasm_bindgen(typescript_type = "WorkspaceConfig")]
108    pub type JsWorkspaceConfig;
109
110    /// `export()` return, whose shape follows the `ExportMethod`.
111    #[wasm_bindgen(typescript_type = "ExportData")]
112    pub type JsExportData;
113
114    /// `setCommandSchema()` argument: the app's command schema function.
115    #[wasm_bindgen(typescript_type = "PerspectiveCommandSchema")]
116    pub type JsCommandSchemaFn;
117
118    /// `setCommandSchema()` options dict (`{ scopes?: CommandLocation[] }`).
119    #[wasm_bindgen(typescript_type = "CommandSchemaOptions")]
120    pub type JsCommandSchemaOptions;
121
122    /// `queryCommands()` argument: the surface being rendered.
123    #[wasm_bindgen(typescript_type = "PerspectiveCommandLocation")]
124    pub type JsCommandLocation;
125
126    /// `queryCommands()` argument: a plugin's viewport read.
127    #[wasm_bindgen(typescript_type = "PerspectiveViewFrame")]
128    pub type JsViewFrame;
129
130    /// `queryCommands()` argument: the locations to resolve.
131    #[wasm_bindgen(typescript_type = "PerspectiveHitRef[]")]
132    pub type JsHitRefs;
133
134    /// `queryCommands()` return: one entry per ref, or `undefined`.
135    #[wasm_bindgen(typescript_type = "PerspectiveCommands[] | undefined")]
136    pub type JsPerspectiveCommands;
137
138    /// A command context, as `queryCommands()` returned it.
139    #[wasm_bindgen(typescript_type = "PerspectiveCommandContext")]
140    pub type JsCommandContext;
141
142    /// `showCommandMenu()` argument: the commands to offer.
143    #[wasm_bindgen(typescript_type = "CommandSpec[]")]
144    pub type JsCommandSpecs;
145
146    /// Viewport coordinates.
147    #[wasm_bindgen(typescript_type = "{ x: number; y: number }")]
148    pub type JsPoint;
149}
150
151ts_promise! {
152    JsViewerConfig => JsViewerConfigPromise = "Promise<ViewerConfig>";
153    JsWorkspaceConfig => JsWorkspaceConfigPromise = "Promise<WorkspaceConfig>";
154    JsExportData => JsExportDataPromise = "Promise<ExportData>";
155}
156
157#[derive(serde::Deserialize)]
158struct MenuPoint {
159    x: f64,
160    y: f64,
161}
162
163#[derive(serde::Deserialize, Default)]
164struct ResizeOptions {
165    dimensions: Option<ResizeDimensions>,
166}
167
168#[derive(serde::Deserialize, Clone, Copy)]
169struct ResizeDimensions {
170    width: f64,
171    height: f64,
172}
173
174/// Leniently deserialize an optional JS options dict into a serde struct,
175/// falling back to `Default` on absence or a malformed argument (matching the
176/// `ResizeOptions` precedent — an options bag is a best-effort convenience,
177/// not a hard-validated payload).
178fn parse_options<T, U>(options: Option<T>) -> ApiResult<U>
179where
180    T: Into<JsValue>,
181    U: Default + for<'a> serde::Deserialize<'a>,
182{
183    match options {
184        None => Ok(U::default()),
185        Some(x) => Ok(x.into_serde_ext()?),
186    }
187}
188
189/// The `<perspective-viewer>` custom element.
190///
191/// # JavaScript Examples
192///
193/// Create a new `<perspective-viewer>`:
194///
195/// ```javascript
196/// const viewer = document.createElement("perspective-viewer");
197/// window.body.appendChild(viewer);
198/// ```
199///
200/// Complete example including loading and restoring the [`Table`]:
201///
202/// ```javascript
203/// import perspective from "@perspective-dev/viewer";
204/// import perspective from "@perspective-dev/client";
205///
206/// const viewer = document.createElement("perspective-viewer");
207/// const worker = await perspective.worker();
208///
209/// await worker.table("x\n1", {name: "table_one"});
210/// await viewer.load(worker);
211/// await viewer.restore({table: "table_one"});
212/// ```
213#[derive(Clone)]
214#[wasm_bindgen]
215pub struct PerspectiveViewerElement {
216    pub(crate) presentation: Presentation,
217    pub(crate) workspace: Workspace,
218    pub(crate) elem: HtmlElement,
219    pub(crate) root: Root<components::viewer::PerspectiveViewer>,
220    resize_handle: Rc<RefCell<Option<ResizeObserverHandle>>>,
221    intersection_handle: Rc<RefCell<Option<AutoPauseHandle>>>,
222    hosted_table_subs: HostedTableSubs,
223    _subscriptions: Rc<[Subscription; 2]>,
224    _custom_event_subs: Rc<Vec<Subscription>>,
225}
226
227impl CustomElementMetadata for PerspectiveViewerElement {
228    const CUSTOM_ELEMENT_NAME: &'static str = "perspective-viewer";
229    const STATICS: &'static [&'static str] = [
230        "registerPlugin",
231        "get_wasm_module",
232        "get_worker_url",
233        "setPluginConfigDefaults",
234        "setColumnConfigDefaults",
235        "getPluginConfigDefaults",
236        "getColumnConfigDefaults",
237    ]
238    .as_slice();
239}
240
241impl PerspectiveViewerElement {
242    fn layout_changed_notify(&self) -> Callback<()> {
243        let root = self.root.clone();
244        Callback::from(move |_: ()| {
245            if let Some(app) = root.borrow().as_ref() {
246                app.send_message(PerspectiveViewerMsg::LayoutChanged);
247            }
248        })
249    }
250
251    fn resolve_panel(&self, name: Option<String>) -> ApiResult<Panel> {
252        let id = name.map(PanelId::from);
253        self.workspace.panel_or_active(id.as_ref()).ok_or_else(|| {
254            format!(
255                "No panel named \"{}\"",
256                id.as_ref().map(PanelId::as_str).unwrap_or_default()
257            )
258            .into()
259        })
260    }
261
262    /// Re-stamp the global-filter overlay on every panel not in `fresh` and
263    /// re-render those whose overlay changed.
264    async fn rerender_retained_overlays(&self, fresh: &[PanelId]) -> ApiResult<()> {
265        let retained = self
266            .workspace
267            .panels()
268            .into_iter()
269            .filter(|panel| !fresh.contains(&panel.id))
270            .collect::<Vec<_>>();
271
272        join_all(
273            retained
274                .iter()
275                .map(|panel| broadcast_overlay(&self.workspace, panel)),
276        )
277        .await
278        .into_iter()
279        .collect::<ApiResult<Vec<_>>>()?;
280
281        Ok(())
282    }
283
284    fn layout_element(&self) -> Option<RegularLayout> {
285        self.elem
286            .shadow_root()?
287            .query_selector(RegularLayout::TAG_NAME)
288            .ok()
289            .flatten()
290            .map(|el| el.unchecked_into())
291    }
292
293    async fn workspace_config(this: Self, full_palette: bool) -> ApiResult<JsValue> {
294        this.workspace.effects().settle().await;
295        let mut panels: std::collections::BTreeMap<String, PanelViewerConfig<String, String>> =
296            Default::default();
297        for id in &this.workspace.panel_ids() {
298            let panel = this.workspace.panel(id).into_apierror()?;
299            let config = panel
300                .renderer
301                .clone()
302                .with_lock(async {
303                    get_viewer_config(&panel.session, &panel.renderer, &this.presentation).await
304                })
305                .await?;
306
307            panels.insert(id.as_str().to_owned(), config.panel);
308        }
309
310        let mut palette = palette_set(&this.workspace, &this.presentation);
311        let mut referenced = std::collections::BTreeSet::new();
312        for (id, item) in styles_in_use(&this.workspace) {
313            let Some(name) = palette_name_for(&palette, item.kind, &item.literal) else {
314                continue;
315            };
316
317            if let Some(entry) = panels
318                .get_mut(id.as_str())
319                .and_then(|panel| panel.columns_config.get_mut(&item.column))
320            {
321                entry.insert(item.key, serde_json::Value::String(format_var_ref(&name)));
322                referenced.insert(name);
323            }
324        }
325
326        if !full_palette {
327            palette.retain(|name, _| referenced.contains(name));
328        }
329
330        let active = this
331            .presentation
332            .is_settings_open()
333            .then(|| this.workspace.active_id())
334            .flatten()
335            .map(|id| id.as_str().to_owned());
336
337        let layout = this
338            .layout_element()
339            .map(|l| l.save().into_serde_ext::<crate::js::Layout>())
340            .transpose()?;
341
342        Ok(JsValue::from_serde_ext(&WorkspaceConfig {
343            version: API_VERSION.to_string(),
344            active,
345            layout,
346            panels,
347            derived_tables: this.workspace.derived_configs(),
348            global_filters: this.workspace.global_filters(),
349            masters: this
350                .workspace
351                .masters()
352                .iter()
353                .map(|id| id.as_str().to_owned())
354                .collect(),
355            palette,
356            unknown: UnknownKeys,
357        })?)
358    }
359}
360
361fn eject_client_panels(
362    workspace: &Workspace,
363    root: &Root<crate::components::viewer::PerspectiveViewer>,
364    target: String,
365    ids: Vec<PanelId>,
366) -> ApiFuture<()> {
367    clone!(workspace, root);
368    let effect = workspace.effects().guard();
369    ApiFuture::new_throttled(async move {
370        let _effect = effect;
371        for id in ids {
372            let (completion, receiver) = Completion::new();
373            root.borrow()
374                .as_ref()
375                .into_apierror()?
376                .send_message(PerspectiveViewerMsg::ClosePanel(
377                    id.to_string(),
378                    Some(completion),
379                ));
380
381            receiver.await.map_err(|_| ApiError::new("Cancelled"))??;
382        }
383
384        workspace.remove_client(&target);
385        Ok(())
386    })
387}
388
389#[rustfmt::skip]
390const DEPRECATED_TABLE_MESSAGE: &str =
391    "`load(table)` is deprecated - use `load(client)` followed by `restore({table: \"name\"})` instead";
392
393#[wasm_bindgen]
394impl PerspectiveViewerElement {
395    #[doc(hidden)]
396    #[wasm_bindgen(constructor)]
397    pub fn new(elem: web_sys::HtmlElement) -> Self {
398        let init = web_sys::ShadowRootInit::new(web_sys::ShadowRootMode::Open);
399        let shadow_root = elem
400            .attach_shadow(&init)
401            .unwrap()
402            .unchecked_into::<web_sys::Element>();
403
404        Self::new_from_shadow(elem, shadow_root)
405    }
406
407    fn new_from_shadow(elem: web_sys::HtmlElement, shadow_root: web_sys::Element) -> Self {
408        // Application State.
409        let presentation = Presentation::new(&elem);
410
411        // Boot with ZERO panels — an unconfigured element is a blank stage. The
412        // first `load`/`restore`/`addPanel` creates the first panel, which
413        // adopts the element's `theme` attribute when set (see
414        // `create_panel_model`'s authored-theme boot).
415        let workspace = Workspace::new();
416        let custom_event_subs = wire_element_events(&elem, &presentation, &workspace);
417
418        // Create Yew App
419        let props = yew::props!(PerspectiveViewerProps {
420            elem: elem.clone(),
421            presentation: presentation.clone(),
422            workspace: workspace.clone(),
423        });
424
425        let state = props.clone();
426        let root = Root::new(shadow_root, props);
427
428        // Create callbacks
429        let eject_sub = presentation.on_eject.add_listener({
430            let root = root.clone();
431            move |_| {
432                clone!(state.workspace, root);
433                ApiFuture::spawn(async move {
434                    if let Some(target) = workspace.active_client().map(|c| c.get_name().to_owned())
435                    {
436                        let ids = workspace.panels_for_client(&target);
437                        if ids.len() < workspace.panel_ids().len() {
438                            return eject_client_panels(&workspace, &root, target, ids).await;
439                        }
440                    }
441
442                    delete_all(&workspace, &root).await
443                })
444            }
445        });
446
447        let resize_handle = ResizeObserverHandle::new(&elem, &workspace, &presentation, &root);
448        let intersect_handle = AutoPauseHandle::new(&elem, &presentation, &workspace);
449        let (lifecycle_sub, hosted_table_subs) = wire_table_lifecycle(&workspace, &presentation);
450
451        Self {
452            elem,
453            root,
454            presentation,
455            workspace,
456            resize_handle: Rc::new(RefCell::new(Some(resize_handle))),
457            intersection_handle: Rc::new(RefCell::new(Some(intersect_handle))),
458            hosted_table_subs,
459            _subscriptions: Rc::new([eject_sub, lifecycle_sub]),
460            _custom_event_subs: Rc::new(custom_event_subs),
461        }
462    }
463
464    #[doc(hidden)]
465    #[wasm_bindgen(js_name = "connectedCallback")]
466    pub fn connected_callback(&self) -> ApiResult<()> {
467        tracing::debug!("Connected <perspective-viewer>");
468        Ok(())
469    }
470
471    /// Loads a [`Client`], or optionally [`Table`], or optionally a Javascript
472    /// `Promise` which returns a [`Client`] or [`Table`], in this viewer.
473    ///
474    /// Loading a [`Client`] does not render, but subsequent calls to
475    /// [`PerspectiveViewerElement::restore`] will use this [`Client`] to look
476    /// up the proviced `table` name field for the provided
477    /// [`ViewerConfigUpdate`].
478    ///
479    /// Loading a [`Table`] is equivalent to subsequently calling
480    /// [`Self::restore`] with the `table` field set to [`Table::get_name`], and
481    /// will render the UI in its default state when [`Self::load`] resolves.
482    /// If you plan to call [`Self::restore`] anyway, prefer passing a
483    /// [`Client`] argument to [`Self::load`] as it will conserve one render.
484    ///
485    /// When [`PerspectiveViewerElement::load`] resolves, the first frame of the
486    /// UI + visualization is guaranteed to have been drawn. Awaiting the result
487    /// of this method in a `try`/`catch` block will capture any errors
488    /// thrown during the loading process, or from the [`Client`] `Promise`
489    /// itself.
490    ///
491    /// [`PerspectiveViewerElement::load`] may also be called with a [`Table`],
492    /// which is equivalent to:
493    ///
494    /// ```javascript
495    /// await viewer.load(await table.get_client());
496    /// await viewer.restore({name: await table.get_name()})
497    /// ```
498    ///
499    /// If you plan to call [`PerspectiveViewerElement::restore`] immediately
500    /// after [`PerspectiveViewerElement::load`] yourself, as is commonly
501    /// done when loading and configuring a new `<perspective-viewer>`, you
502    /// should use a [`Client`] as an argument and set the `table` field in the
503    /// restore call as
504    ///
505    /// A [`Table`] can be created using the
506    /// [`@perspective-dev/client`](https://www.npmjs.com/package/@perspective-dev/client)
507    /// library from NPM (see [`perspective_js`] documentation for details).
508    ///
509    /// # JavaScript Examples
510    ///
511    /// ```javascript
512    /// import perspective from "@perspective-dev/client";
513    ///
514    /// const worker = await perspective.worker();
515    /// viewer.load(worker);
516    /// ```
517    ///
518    /// ... or
519    ///
520    /// ```javascript
521    /// const table = await worker.table(data, {name: "superstore"});
522    /// viewer.load(table);
523    /// ```
524    ///
525    /// Complete example:
526    ///
527    /// ```javascript
528    /// const viewer = document.createElement("perspective-viewer");
529    /// const worker = await perspective.worker();
530    ///
531    /// await worker.table("x\n1", {name: "table_one"});
532    /// await viewer.load(worker);
533    /// await viewer.restore({table: "table_one", columns: ["x"]});
534    /// ```
535    ///
536    /// ... or, if you don't want to pass your own arguments to `restore`:
537    ///
538    /// ```javascript
539    /// const viewer = document.createElement("perspective-viewer");
540    /// const worker = await perspective.worker();
541    ///
542    /// const table = await worker.table("x\n1", {name: "table_one"});
543    /// await viewer.load(table);
544    /// ```
545    pub fn load(&self, client: JsClientLoad) -> ApiResult<ApiFuture<()>> {
546        let effect = self.workspace.effects().guard();
547        let table: JsValue = client.into();
548        let promise = table
549            .clone()
550            .dyn_into::<js_sys::Promise>()
551            .unwrap_or_else(|_| js_sys::Promise::resolve(&table));
552
553        let (panel, notify) = match self.workspace.active_panel() {
554            Some(panel) => (panel, None),
555            None => {
556                if let Ok(Some(client)) =
557                    try_from_js_option::<perspective_js::Client>(table.clone())
558                {
559                    self.workspace
560                        .set_default_client(client.get_client().clone());
561                    return Ok(ApiFuture::new(async { Ok(()) }));
562                }
563
564                let panel = self.workspace.reserved_panel().unwrap_or_else(|| {
565                    create_panel_model(
566                        &self.elem,
567                        &self.presentation,
568                        &self.workspace,
569                        None,
570                        ViewerConfigUpdate::default(),
571                        None,
572                        Placement::Reserved,
573                    );
574                    self.workspace
575                        .reserved_panel()
576                        .expect("just-reserved panel is present")
577                });
578
579                (panel, Some(self.layout_changed_notify()))
580            },
581        };
582
583        let session = panel.session;
584        let renderer = panel.renderer;
585        clone!(self.workspace, self.presentation);
586        enum Discard {
587            Unclaimed(Panel),
588            Evicted(Panel),
589        }
590
591        let table_known = matches!(
592            try_from_js_option::<perspective_js::Table>(table.clone()),
593            Ok(Some(_))
594        );
595
596        let ticket = session.submit(OpKind::Load { table_known }, {
597            clone!(session, renderer);
598            move |load| {
599                Box::pin(async move {
600                    let _effect = effect;
601                    renderer.set_throttle(None);
602                    let result = {
603                        clone!(session, renderer, workspace, notify, load);
604                        renderer
605                    .clone()
606                    .render_task(|guard| async move {
607                        renderer.stamp_theme(None);
608                        let jstable = JsFuture::from(promise)
609                            .await
610                            .map_err(|x| apierror!(TableError(x)))?;
611
612                        if let Ok(Some(table)) =
613                            try_from_js_option::<perspective_js::Table>(jstable.clone())
614                        {
615                            tracing::warn!("{}", DEPRECATED_TABLE_MESSAGE);
616                            if load.is_superseded() {
617                                return Ok(None);
618                            }
619
620                            if let Some(notify) = &notify {
621                                place_reserved(&workspace, notify, true);
622                            }
623
624                            let client = table.get_client().await;
625                            let inner_client = client.get_client().clone();
626                            workspace.set_default_client(inner_client.clone());
627                            let name = table.get_name().await;
628                            tracing::debug!(
629                                "Loading {:.0} rows from `Table` {}",
630                                table.size().await?,
631                                name
632                            );
633
634                            let plan = match session::probe_table(
635                                &inner_client,
636                                &name,
637                                MissingTable::Pend,
638                            )
639                            .await?
640                            {
641                                Some(table) => BindPlan::Bind {
642                                    client: inner_client,
643                                    table: Box::new(table),
644                                    reset: true,
645                                },
646                                None => BindPlan::Pend {
647                                    client: inner_client,
648                                    name,
649                                    reset: true,
650                                },
651                            };
652
653                            let prepared = crate::tasks::prepare(
654                                &session,
655                                &renderer,
656                                &presentation,
657                                false,
658                                plan,
659                                renderer
660                                    .slot_name()
661                                    .map(|id| overlay_for(&workspace, &PanelId::from(id))),
662                                ViewerConfigUpdate::default(),
663                            )
664                            .await?;
665
666                            crate::tasks::commit_and_render_locked(
667                                guard, &session, &renderer, prepared,
668                            )
669                            .await?;
670
671                            Ok(None)
672                        } else if let Ok(Some(client)) = wasm_bindgen_derive::try_from_js_option::<
673                            perspective_js::Client,
674                        >(jstable)
675                        {
676                            // INERT: register the client only — never rebind or
677                            // reset the active panel (its table is preserved).
678                            // Panels bind their client lazily at table-resolution
679                            // time (`Workspace::resolve_client_for_table`).
680                            let owned_window = !load.is_superseded();
681                            let discard = if owned_window && notify.is_some() {
682                                match workspace.take_reserved() {
683                                    Some(panel) => Some(Discard::Unclaimed(panel)),
684                                    // The one-shot claim read: a table-less
685                                    // `restore` claimed the reservation, and no
686                                    // table has bound nor is pending — evict the
687                                    // panel `CREATE_REQUIRES_TABLE` forbids.
688                                    None if workspace
689                                        .resolve_claim()
690                                        .is_some_and(|has_table| !has_table)
691                                        && session.get_table().is_none()
692                                        && session.pending_table().is_none() =>
693                                    {
694                                        let evicted = renderer
695                                            .slot_name()
696                                            .map(PanelId::from)
697                                            .and_then(|id| workspace.remove_panel(&id));
698
699                                        if evicted.is_some()
700                                            && let Some(notify) = &notify
701                                        {
702                                            notify.emit(());
703                                        }
704
705                                        evicted.map(Discard::Evicted)
706                                    },
707                                    None => None,
708                                }
709                            } else {
710                                None
711                            };
712
713                            workspace.set_default_client(client.get_client().clone());
714                            Ok(discard)
715                        } else {
716                            Err(ApiError::new("Invalid argument"))
717                        }
718                    })
719                    .await
720                    };
721
722                    match result {
723                        Err(e) => {
724                            if let Some(notify) = &notify {
725                                place_reserved(&workspace, notify, true);
726                            }
727
728                            session.set_error(false, e.clone()).await?;
729                            Err(e)
730                        },
731                        Ok(Some(Discard::Unclaimed(panel))) => {
732                            eject_panel(panel, Disposal::Reject).await?;
733                            Ok(None)
734                        },
735                        Ok(Some(Discard::Evicted(panel))) => {
736                            eject_panel(panel, Disposal::Resolve).await?;
737                            Err(ApiError::new(CREATE_REQUIRES_TABLE))
738                        },
739                        Ok(None) => Ok(None),
740                    }
741                })
742            }
743        });
744
745        Ok(ApiFuture::new_throttled(ticket.settle()))
746    }
747
748    /// Delete all internal [`View`]s and all associated state, rendering this
749    /// `<perspective-viewer>` unusable and freeing all associated resources.
750    /// Does not delete any supplied [`Table`] (as this is constructed by the
751    /// callee).
752    ///
753    /// Calling _any_ method on a `<perspective-viewer>` after [`Self::delete`]
754    /// will throw.
755    ///
756    /// <div class="warning">
757    ///
758    /// Allowing a `<perspective-viewer>` to be garbage-collected
759    /// without calling [`PerspectiveViewerElement::delete`] will leak WASM
760    /// memory!
761    ///
762    /// </div>
763    ///
764    /// # JavaScript Examples
765    ///
766    /// ```javascript
767    /// await viewer.delete();
768    /// ```
769    pub fn delete(self) -> ApiFuture<()> {
770        self.presentation.set_command_schema(None, vec![]);
771        #[cfg(feature = "llm-agent")]
772        self.presentation.agent.sandbox().stop_all();
773        let subs = std::mem::take(&mut *self.hosted_table_subs.borrow_mut());
774        let teardown = delete_all(&self.workspace, &self.root);
775        ApiFuture::new(async move {
776            for (client, id) in subs {
777                let _ = client.remove_hosted_tables_update(id).await;
778            }
779
780            teardown.await
781        })
782    }
783
784    /// Remove a [`Client`] from this `<perspective-viewer>` and dispose every
785    /// panel bound to it (each panel's `View` is deleted and its `Table`
786    /// reference released).
787    ///
788    /// # Arguments
789    ///
790    /// - `options` - An optional `{client?: string}` dict naming the client to
791    ///   eject; the active panel's client when omitted.
792    ///
793    /// # JavaScript Examples
794    ///
795    /// ```javascript
796    /// await viewer.eject();
797    /// await viewer.eject({client: "remote"});
798    /// ```
799    pub fn eject(&mut self, options: Option<JsClientOptions>) -> ApiFuture<()> {
800        let ClientOptions { client } = match parse_options(options) {
801            Ok(x) => x,
802            Err(x) => return ApiFuture::new_err(x),
803        };
804
805        // Default target: the active panel's client, or — when the active panel
806        // is unbound (`load(Client)` is now inert) — the default client.
807        let Some(target) = client
808            .or_else(|| {
809                self.workspace
810                    .active_client()
811                    .map(|c| c.get_name().to_owned())
812            })
813            .or_else(|| {
814                self.workspace
815                    .default_client()
816                    .map(|c| c.get_name().to_owned())
817            })
818        else {
819            return ApiFuture::new_throttled(async move { Ok(()) });
820        };
821
822        let ids = self.workspace.panels_for_client(&target);
823
824        // The target client backs EVERY panel — reset the element to its
825        // pre-`load` state (dropping the client with it), as a `Workspace`
826        // must always keep at least one panel.
827        if !ids.is_empty() && ids.len() == self.workspace.panel_ids().len() {
828            let mut state = Self::new_from_shadow(
829                self.elem.clone(),
830                self.elem.shadow_root().unwrap().unchecked_into(),
831            );
832
833            std::mem::swap(self, &mut state);
834            return ApiFuture::new_throttled(state.delete());
835        }
836
837        eject_client_panels(&self.workspace, &self.root, target, ids)
838    }
839
840    /// Get a [`View`] for a panel of this viewer, as currently configured by
841    /// the user.
842    ///
843    /// # Arguments
844    ///
845    /// - `mode` - which [`View`] to return:
846    ///   - `"live"` (default) - the panel's own [`View`], which the viewer
847    ///     replaces on every config change and deletes when auto-paused or
848    ///     [`PerspectiveViewerElement::delete`]d, so calls on it may fail with
849    ///     "View already deleted", it must never be deleted by the caller, and
850    ///     it rejects with `No View for panel "<name>"` while none is bound
851    ///     (auto-paused or not yet rendered).
852    ///   - `"clone"` - a new [`View`] built from the panel's effective config
853    ///     (global filter included), independent of the render lifecycle, which
854    ///     the caller owns and must [`View::delete`].
855    ///   - `"auto"` - `"live"` when the panel has a bound [`View`], else
856    ///     `"clone"`.
857    /// - `panel` - the target panel, or the active panel when omitted.
858    ///
859    /// Plugins which rely on the live [`View`] for their
860    /// [`HTMLPerspectiveViewerPluginElement::draw`] implementations should
861    /// treat "View already deleted" as a _cancellation_ by silently aborting.
862    ///
863    /// # JavaScript Examples
864    ///
865    /// ```javascript
866    /// const view = await viewer.getView();
867    /// ```
868    ///
869    /// Export every panel without borrowing the viewer's own [`View`]:
870    ///
871    /// ```javascript
872    /// for (const panel of viewer.getPanelNames()) {
873    ///     const view = await viewer.getView({ panel, mode: "clone" });
874    ///     const arrow = await view.to_arrow();
875    ///     await view.delete();
876    /// }
877    /// ```
878    #[wasm_bindgen]
879    pub fn getView(&self, options: Option<JsGetViewOptions>) -> ApiFuture<View> {
880        let this = self.clone();
881        ApiFuture::new(async move {
882            let GetViewOptions { mode, panel: name } = parse_options(options)?;
883            let panel = this.resolve_panel(name)?;
884            match (mode.unwrap_or_default(), panel.session.get_view()) {
885                (GetViewMode::Live | GetViewMode::Auto, Some(view)) => Ok(view.into()),
886                (GetViewMode::Live, None) => {
887                    Err(format!("No View for panel \"{}\"", panel.id.as_str()).into())
888                },
889                (GetViewMode::Clone, _) | (GetViewMode::Auto, None) => {
890                    Ok(panel.session.create_detached_view().await?.into())
891                },
892            }
893        })
894    }
895
896    /// Get a copy of the [`ViewConfig`] for the current [`View`]. This is
897    /// non-blocking as it does not need to access the plugin (unlike
898    /// [`PerspectiveViewerElement::save`]), and also makes no API calls to the
899    /// server (unlike [`PerspectiveViewerElement::getView`] followed by
900    /// [`View::get_config`])
901    #[wasm_bindgen]
902    pub fn getViewConfig(
903        &self,
904        options: Option<JsPanelOptions>,
905    ) -> ApiFuture<JsResolvedViewConfig> {
906        let this = self.clone();
907        ApiFuture::new(async move {
908            let PanelOptions { panel: name } = parse_options(options)?;
909            let panel = this.resolve_panel(name)?;
910            let config = if let Some(ctx) = panel.renderer.render_context() {
911                (*ctx.view_config).clone()
912            } else if let Some(rendered) = panel.session.get_rendered_view_config() {
913                (*rendered).clone()
914            } else {
915                panel.session.get_view_config().clone()
916            };
917
918            Ok(JsValue::from_serde_ext(&config)?.unchecked_into())
919        })
920    }
921
922    /// Get the underlying [`Table`] for this viewer (as passed to
923    /// [`PerspectiveViewerElement::load`] or as the `table` field to
924    /// [`PerspectiveViewerElement::restore`]).
925    ///
926    /// # Arguments
927    ///
928    /// - `wait_for_table` - whether to wait for
929    ///   [`PerspectiveViewerElement::load`] to be called, or fail immediately
930    ///   if [`PerspectiveViewerElement::load`] has not yet been called.
931    ///
932    /// # JavaScript Examples
933    ///
934    /// ```javascript
935    /// const table = await viewer.getTable();
936    /// ```
937    #[wasm_bindgen]
938    pub fn getTable(&self, options: Option<JsGetTableOptions>) -> ApiFuture<Table> {
939        let this = self.clone();
940        ApiFuture::new(async move {
941            let GetTableOptions {
942                wait: wait_for_table,
943                panel: name,
944            } = parse_options(options)?;
945            let panel = this.resolve_panel(name)?;
946            if !wait_for_table.unwrap_or_default()
947                && let Some(ctx) = panel.renderer.render_context()
948            {
949                return Ok(ctx.table.clone().into());
950            }
951
952            let session = panel.session;
953            match session.get_table() {
954                Some(table) => Ok(table.into()),
955                None if !wait_for_table.unwrap_or_default() => Err("No `Table` set".into()),
956                None => {
957                    session.table_loaded.read_next().await?;
958                    Ok(session.get_table().ok_or("No `Table` set")?.into())
959                },
960            }
961        })
962    }
963
964    /// Get the underlying [`Client`] for this viewer (as passed to, or
965    /// associated with the [`Table`] passed to,
966    /// [`PerspectiveViewerElement::load`]).
967    ///
968    /// # Arguments
969    ///
970    /// - `wait_for_client` - whether to wait for
971    ///   [`PerspectiveViewerElement::load`] to be called, or fail immediately
972    ///   if [`PerspectiveViewerElement::load`] has not yet been called.
973    ///
974    /// # JavaScript Examples
975    ///
976    /// ```javascript
977    /// const client = await viewer.getClient();
978    /// ```
979    #[wasm_bindgen]
980    pub fn getClient(
981        &self,
982        options: Option<JsGetClientOptions>,
983    ) -> ApiFuture<perspective_js::Client> {
984        let this = self.clone();
985        ApiFuture::new(async move {
986            let GetClientOptions {
987                wait: wait_for_client,
988                panel: name,
989            } = parse_options(options)?;
990            let panel = this.resolve_panel(name)?;
991            if !wait_for_client.unwrap_or_default()
992                && let Some(ctx) = panel.renderer.render_context()
993            {
994                return Ok(ctx.client.clone().into());
995            }
996
997            let session = panel.session;
998            match session.get_client() {
999                Some(client) => Ok(client.into()),
1000                None if !wait_for_client.unwrap_or_default() => Err("No `Client` set".into()),
1001                None => {
1002                    session.table_loaded.read_next().await?;
1003                    Ok(session.get_client().ok_or("No `Client` set")?.into())
1004                },
1005            }
1006        })
1007    }
1008
1009    /// Get render statistics. Some fields of the returned stats object are
1010    /// relative to the last time [`PerspectiveViewerElement::getRenderStats`]
1011    /// was called, ergo calling this method resets these fields.
1012    ///
1013    /// # JavaScript Examples
1014    ///
1015    /// ```javascript
1016    /// const {virtual_fps, actual_fps} = await viewer.getRenderStats();
1017    /// ```
1018    #[wasm_bindgen]
1019    pub fn getRenderStats(&self, options: Option<JsPanelOptions>) -> ApiResult<JsValue> {
1020        let PanelOptions { panel: name } = parse_options(options)?;
1021        let panel = self.resolve_panel(name)?;
1022        Ok(JsValue::from_serde_ext(
1023            &panel.renderer.render_timer().get_stats(),
1024        )?)
1025    }
1026
1027    /// Flush any pending modifications to this `<perspective-viewer>`.  Since
1028    /// `<perspective-viewer>`'s API is almost entirely `async`, it may take
1029    /// some milliseconds before any user-initiated changes to the [`View`]
1030    /// affects the rendered element.  If you want to make sure all pending
1031    /// actions have been rendered, call and await [`Self::flush`].
1032    ///
1033    /// [`Self::flush`] will resolve immediately if there is no [`Table`] set.
1034    ///
1035    /// # JavaScript Examples
1036    ///
1037    /// In this example, [`Self::restore`] is called without `await`, but the
1038    /// eventual render which results from this call can still be awaited by
1039    /// immediately awaiting [`Self::flush`] instead.
1040    ///
1041    /// ```javascript
1042    /// viewer.restore(config);
1043    /// await viewer.flush();
1044    /// ```
1045    pub fn flush(&self) -> ApiFuture<()> {
1046        let workspace = self.workspace.clone();
1047        let presentation = self.presentation.clone();
1048        ApiFuture::new_throttled(async move {
1049            loop {
1050                workspace.effects().settle().await;
1051                let panels = workspace
1052                    .reserved_panel()
1053                    .into_iter()
1054                    .chain(workspace.panels())
1055                    .collect::<Vec<_>>();
1056
1057                let mut fulfilled = false;
1058                for panel in &panels {
1059                    panel.session.settle_ops().await;
1060                    panel.renderer.clone().with_lock(async { Ok(()) }).await?;
1061                    panel.renderer.clone().with_lock(async { Ok(()) }).await?;
1062                    panel.session.settle_dispatches().await?;
1063                    if !global::document().hidden()
1064                        && presentation.is_visible()
1065                        && !panel.renderer.is_plugin_activated()?
1066                        && panel.session.get_error().is_none()
1067                        && panel.renderer.failure().is_none()
1068                        && matches!(panel.session.has_table(), Some(TableLoadState::Loaded))
1069                    {
1070                        set_panel_paused(&panel.session, &panel.renderer, &presentation, true)
1071                            .await?;
1072                        if !panel.renderer.is_plugin_activated()? {
1073                            just_render(&panel.session, &panel.renderer)?.await?;
1074                        }
1075
1076                        fulfilled = true;
1077                    }
1078                }
1079
1080                if !fulfilled && workspace.effects().is_empty() {
1081                    return Ok(());
1082                }
1083            }
1084        })
1085    }
1086
1087    /// Restore a single panel from a full/partial
1088    /// [`perspective_js::JsViewConfig`] (its user-configurable state, including
1089    /// the `Table` name) — the active panel, or a specific panel via the
1090    /// optional `{panel}` selector.
1091    ///
1092    /// If `panel` names no existing panel, a NEW panel is created with that id
1093    /// and the config restored into it (an upsert). Creation REQUIRES a
1094    /// `table` — the same rule [`Self::addPanel`] enforces in its argument
1095    /// type — and a would-create call without one REJECTS before any state
1096    /// (including `settings`) is applied: with no panel to target and no
1097    /// `table`, the patch has no data arrival path. In particular, on an
1098    /// element with zero panels every `restore` must carry a `table`.
1099    ///
1100    /// On an empty element with a pending [`Self::load`] whose payload is not
1101    /// yet classified, the active-target form (no `panel`) instead claims and
1102    /// restores into that load's reserved first panel — see [`Self::load`].
1103    ///
1104    /// This restores a SINGLE panel; a workspace config (with a `panels`
1105    /// map) must be applied via [`Self::restoreWorkspace`] — its `panels` /
1106    /// `layout` keys are rejected here, as is any key the config format does
1107    /// not define; a rejected config stamped by another release names that
1108    /// release in the error (upgrade those with `perspective-migrate`).
1109    ///
1110    /// One of the best ways to use [`Self::restore`] is by first configuring
1111    /// a `<perspective-viewer>` as you wish, then using either the `Debug`
1112    /// panel or "Copy" -> "config.json" from the toolbar menu to snapshot
1113    /// the [`Self::restore`] argument as JSON.
1114    ///
1115    /// # Arguments
1116    ///
1117    /// - `update` - The config to restore to, as returned by [`Self::save`].
1118    /// - `options.panel` - The panel to target, or the active panel when
1119    ///   omitted.
1120    /// - `options.suppress_errors` - when `true`, a config that was applied and
1121    ///   then failed to render only rejects the returned `Promise`, without
1122    ///   raising the panel's visible error state.
1123    /// - `options.wait_for_table` - when `true`, a `table` no loaded client
1124    ///   hosts yet leaves the panel empty and pending until the table is
1125    ///   created, instead of the default error.
1126    ///
1127    /// # JavaScript Examples
1128    ///
1129    /// Loads a default plugin for the table named `"superstore"`:
1130    ///
1131    /// ```javascript
1132    /// await viewer.restore({table: "superstore"});
1133    /// ```
1134    ///
1135    /// Apply a `group_by` to the same `viewer` element, without
1136    /// modifying/resetting other fields - you can omit the `table` field,
1137    /// this has already been set once and is not modified:
1138    ///
1139    /// ```javascript
1140    /// await viewer.restore({group_by: ["State"]});
1141    /// ```
1142    pub fn restore(
1143        &self,
1144        update: JsViewerConfigUpdate,
1145        options: Option<JsRestoreOptions>,
1146    ) -> ApiFuture<()> {
1147        let effect = self.workspace.effects().guard();
1148        let this = self.clone();
1149        let saved = saved_version(&update);
1150        ApiFuture::new_throttled(noting_saved_version(saved, async move {
1151            let RestoreOptions {
1152                panel: name,
1153                suppress_errors,
1154                wait_for_table,
1155            } = parse_options(options)?;
1156
1157            let errors = if suppress_errors.unwrap_or_default() {
1158                RestoreErrors::Suppress
1159            } else {
1160                RestoreErrors::Publish
1161            };
1162
1163            let missing = MissingTable::from_wait(wait_for_table);
1164
1165            let _effect = effect;
1166            let id = name.map(PanelId::from);
1167            let mut update = ViewerConfigUpdate::decode(&update)?;
1168            let settings = std::mem::replace(&mut update.settings, OptionalUpdate::Missing);
1169            enum Target {
1170                Existing { panel: Panel, active: bool },
1171                Claimed(Panel),
1172                Create(Box<ViewerConfigInitial>),
1173            }
1174
1175            crate::tasks::resolve_table_ref(&this.workspace, &mut update, missing).await?;
1176            let notify = this.layout_changed_notify();
1177            let target = match this.workspace.panel_or_active(id.as_ref()) {
1178                // An existing (or the active) panel — update it in place.
1179                Some(panel) => {
1180                    let active = this.workspace.active_id().as_ref() == Some(&panel.id);
1181                    Target::Existing { panel, active }
1182                },
1183                None => {
1184                    let has_table = matches!(&update.table, OptionalUpdate::Update(_));
1185                    match id
1186                        .is_none()
1187                        .then(|| place_reserved(&this.workspace, &notify, has_table))
1188                        .flatten()
1189                    {
1190                        Some(panel) => Target::Claimed(panel),
1191                        None => Target::Create(Box::new(
1192                            ViewerConfigInitial::try_from(std::mem::take(&mut update))
1193                                .map_err(ApiError::new)?,
1194                        )),
1195                    }
1196                },
1197            };
1198
1199            let settings_toggle: Option<futures::future::LocalBoxFuture<'static, ApiResult<()>>> =
1200                (!matches!(settings, OptionalUpdate::Missing)).then(|| {
1201                    let this = this.clone();
1202                    Box::pin(async move {
1203                        let (sender, receiver) = channel::<ApiResult<JsValue>>();
1204                        this.root.borrow().as_ref().into_apierror()?.send_message(
1205                            PerspectiveViewerMsg::ToggleSettingsInit(
1206                                Some(settings),
1207                                false,
1208                                Some(sender),
1209                            ),
1210                        );
1211
1212                        receiver.await.map_err(|_| ApiError::new("Cancelled"))??;
1213                        Ok(())
1214                    })
1215                        as futures::future::LocalBoxFuture<'static, ApiResult<()>>
1216                });
1217
1218            match target {
1219                Target::Existing { panel, active } => {
1220                    restore_panel(
1221                        &panel.session,
1222                        &panel.renderer,
1223                        &this.presentation,
1224                        &this.workspace,
1225                        RestoreMode::Existing { active },
1226                        update,
1227                        errors,
1228                        missing,
1229                        settings_toggle,
1230                    )
1231                    .await
1232                },
1233                Target::Claimed(panel) => {
1234                    restore_panel(
1235                        &panel.session,
1236                        &panel.renderer,
1237                        &this.presentation,
1238                        &this.workspace,
1239                        RestoreMode::Existing { active: true },
1240                        update,
1241                        errors,
1242                        missing,
1243                        settings_toggle,
1244                    )
1245                    .await
1246                },
1247                Target::Create(config) => {
1248                    if let Some(settings_toggle) = settings_toggle {
1249                        settings_toggle.await?;
1250                    }
1251
1252                    create_panel(
1253                        &this.elem,
1254                        &this.presentation,
1255                        &this.workspace,
1256                        &notify,
1257                        id,
1258                        *config,
1259                        None,
1260                        missing,
1261                    )
1262                    .await?;
1263                    Ok(())
1264                },
1265            }
1266        }))
1267    }
1268
1269    /// Apply a [`WorkspaceConfigUpdate`] to the element — the multi-panel
1270    /// counterpart of [`Self::restore`] and like it a field-wise update, where
1271    /// an absent field is unchanged, `null` resets and a value replaces.
1272    ///
1273    /// # Arguments
1274    ///
1275    /// - `update` - The workspace config update: a [`Self::saveWorkspace`]
1276    ///   token replaces every panel (`panels` is the whole set), while a token
1277    ///   without `panels` keeps them and `layout`, `active` and `masters` name
1278    ///   them by their existing ids.
1279    /// - `options.wait_for_table` - when `true`, a panel whose `table` no
1280    ///   loaded client hosts yet is created empty and pending until the table
1281    ///   is created, instead of the default error.
1282    ///
1283    /// # JavaScript Examples
1284    ///
1285    /// ```javascript
1286    /// await viewer.restoreWorkspace(await otherViewer.saveWorkspace());
1287    /// ```
1288    ///
1289    /// Cross-filter the current panels without re-creating them:
1290    ///
1291    /// ```javascript
1292    /// await viewer.restoreWorkspace({ global_filters: [["Region", "==", "West"]] });
1293    /// ```
1294    pub fn restoreWorkspace(
1295        &self,
1296        update: JsWorkspaceConfigUpdate,
1297        options: Option<JsRestoreWorkspaceOptions>,
1298    ) -> ApiFuture<()> {
1299        let effect = self.workspace.effects().guard();
1300        let this = self.clone();
1301        let saved = saved_version(&update);
1302        ApiFuture::new(noting_saved_version(saved, async move {
1303            let _effect = effect;
1304            let RestoreWorkspaceOptions { wait_for_table } = parse_options(options)?;
1305            let missing = MissingTable::from_wait(wait_for_table);
1306            let (contents, eject_tasks, derived_tables) = sync_update_panels(&this, update)?;
1307
1308            // The outgoing panels' ejects must settle BEFORE the derived
1309            // pass: a stale derivation is undeletable (and so cannot be
1310            // redefined or pruned) while an ejecting panel still holds a
1311            // `View` on it. Their errors are surfaced LAST, after the
1312            // replacement set is in place.
1313            let ejected = join_all(eject_tasks)
1314                .await
1315                .into_iter()
1316                .collect::<ApiResult<Vec<_>>>();
1317
1318            if let Some(derived_tables) = derived_tables.clone() {
1319                crate::tasks::apply_derived_tables(&this.workspace, derived_tables).await?;
1320            }
1321
1322            let fresh = contents
1323                .iter()
1324                .map(|(id, ..)| id.clone())
1325                .collect::<Vec<_>>();
1326            let results = join_all(contents.into_iter().map(|(id, session, renderer, config)| {
1327                let presentation = this.presentation.clone();
1328                let workspace = this.workspace.clone();
1329                let notify = this.layout_changed_notify();
1330                async move {
1331                    let result = restore_panel(
1332                        &session,
1333                        &renderer,
1334                        &presentation,
1335                        &workspace,
1336                        RestoreMode::Fresh,
1337                        config,
1338                        crate::tasks::RestoreErrors::Publish,
1339                        missing,
1340                        None,
1341                    )
1342                    .await;
1343
1344                    if discard_rejected(&workspace, &id, &session, &result).await? {
1345                        notify.emit(());
1346                    }
1347
1348                    result?;
1349                    if workspace.is_master(&id) {
1350                        set_edit_mode(&session, &renderer, "SELECT_ROW_TREE");
1351                    }
1352
1353                    Ok(())
1354                }
1355            }))
1356            .await;
1357
1358            results.into_iter().collect::<ApiResult<Vec<_>>>()?;
1359            this.rerender_retained_overlays(&fresh).await?;
1360            if let Some(derived_tables) = derived_tables {
1361                let keep = derived_tables.keys().cloned().collect();
1362                crate::tasks::prune_derived(&this.workspace, &keep).await?;
1363            }
1364
1365            ejected?;
1366            Ok(())
1367        }))
1368    }
1369
1370    /// If this element is in an _errored_ state, this method will clear it and
1371    /// re-render. Calling this method is equivalent to clicking the error reset
1372    /// button in the UI.
1373    pub fn resetError(&self) -> ApiFuture<()> {
1374        let Some(panel) = self.workspace.active_panel() else {
1375            return ApiFuture::new_throttled(async move { Ok(()) });
1376        };
1377
1378        let reset_effect = self.workspace.effects().guard();
1379        let reset = panel.session.submit(OpKind::Restore { update: None }, {
1380            let session = panel.session.clone();
1381            move |_ctx| {
1382                Box::pin(async move {
1383                    session.reset(ResetOptions::default()).await?;
1384                    Ok(None)
1385                })
1386            }
1387        });
1388
1389        ApiFuture::spawn(async move {
1390            let _effect = reset_effect;
1391            reset.settle().await
1392        });
1393
1394        let effect = self.workspace.effects().guard();
1395        ApiFuture::new_throttled(async move {
1396            let _effect = effect;
1397            apply_and_render(&panel.session, &panel.renderer, ViewConfigUpdate::default())?.await?;
1398            Ok(())
1399        })
1400    }
1401
1402    /// Save a single panel's user-configurable state as a [`ViewerConfig`], one
1403    /// which can be restored via [`Self::restore`] — the active panel, or a
1404    /// specific panel via the optional `{panel}` selector.
1405    ///
1406    /// This saves a SINGLE panel; to snapshot the ENTIRE element (every panel +
1407    /// layout + cross-filters) use [`Self::saveWorkspace`].
1408    ///
1409    /// # Arguments
1410    ///
1411    /// - `options` - An optional `{panel?: string}`; the panel to save, or the
1412    ///   active panel when omitted.
1413    ///
1414    /// # JavaScript Examples
1415    ///
1416    /// Get the current `group_by` setting:
1417    ///
1418    /// ```javascript
1419    /// const {group_by} = await viewer.save();
1420    /// ```
1421    ///
1422    /// Reset workflow attached to an external button `myResetButton`:
1423    ///
1424    /// ```javascript
1425    /// const token = await viewer.save();
1426    /// myResetButton.addEventListener("click", async () => {
1427    ///     await viewer.restore(token);
1428    /// });
1429    /// ```
1430    pub fn save(&self, options: Option<JsPanelOptions>) -> ApiFuture<JsViewerConfig> {
1431        let this = self.clone();
1432        ApiFuture::new(async move {
1433            let PanelOptions { panel: name } = parse_options(options)?;
1434            this.workspace.effects().settle().await;
1435            let panel = this.resolve_panel(name)?;
1436            let viewer_config = panel
1437                .renderer
1438                .clone()
1439                .with_lock(async {
1440                    get_viewer_config(&panel.session, &panel.renderer, &this.presentation).await
1441                })
1442                .await?;
1443
1444            Ok(viewer_config
1445                .map_table(|name| this.workspace.inline_table_ref(&name))
1446                .encode()?
1447                .unchecked_into())
1448        })
1449    }
1450
1451    /// Save the ENTIRE element to a [`WorkspaceConfig`]
1452    /// (`{version, active?, layout, panels, palette?, ...}`) — the
1453    /// multi-panel counterpart of [`Self::save`]. Unlike [`Self::save`]
1454    /// (which emits a single `ViewerConfig` for one panel), this ALWAYS
1455    /// emits the workspace format, restorable via
1456    /// [`Self::restoreWorkspace`].
1457    ///
1458    /// # JavaScript Examples
1459    ///
1460    /// ```javascript
1461    /// const token = await viewer.saveWorkspace();
1462    /// await viewer.restoreWorkspace(token);
1463    /// ```
1464    pub fn saveWorkspace(
1465        &self,
1466        options: Option<JsSaveWorkspaceOptions>,
1467    ) -> ApiFuture<JsWorkspaceConfig> {
1468        let this = self.clone();
1469        ApiFuture::new(async move {
1470            let SaveWorkspaceOptions { full_palette } = parse_options(options)?;
1471            Ok(Self::workspace_config(this, full_palette.unwrap_or(false))
1472                .await?
1473                .unchecked_into())
1474        })
1475    }
1476
1477    /// Download this viewer's internal [`View`] data via a browser download
1478    /// event.
1479    ///
1480    /// # Arguments
1481    ///
1482    /// - `method` - The `ExportMethod` to use to render the data to download.
1483    ///
1484    /// # JavaScript Examples
1485    ///
1486    /// ```javascript
1487    /// myDownloadButton.addEventListener("click", async () => {
1488    ///     await viewer.download();
1489    /// })
1490    /// ```
1491    pub fn download(&self, options: Option<JsExportOptions>) -> ApiFuture<()> {
1492        let this = self.clone();
1493        ApiFuture::new_throttled(async move {
1494            let ExportOptions {
1495                method,
1496                panel: name,
1497            } = parse_options(options)?;
1498            let method = method.map(|m| JsString::from(m.as_str()));
1499            let method = if let Some(method) = method
1500                .map(|x| x.unchecked_into())
1501                .map(serde_wasm_bindgen::from_value)
1502            {
1503                method?
1504            } else {
1505                ExportMethod::Csv
1506            };
1507
1508            let panel = this.resolve_panel(name)?;
1509            let blob = export_method_to_blob(
1510                &panel.session,
1511                &panel.renderer,
1512                &this.presentation,
1513                &this.workspace,
1514                method,
1515            )
1516            .await?;
1517            let is_chart = panel.renderer.is_chart();
1518            download(
1519                format!("untitled{}", method.as_filename(is_chart)).as_ref(),
1520                &blob,
1521            )
1522        })
1523    }
1524
1525    /// Exports this viewer's internal [`View`] as a JavaSript data, the
1526    /// exact type of which depends on the `method` but defaults to `String`
1527    /// in CSV format.
1528    ///
1529    /// This method is only really useful for the `"plugin"` method, which
1530    /// will use the configured plugin's export (e.g. PNG for
1531    /// `@perspective-dev/viewer-charts`). Otherwise, prefer to call the
1532    /// equivalent method on the underlying [`View`] directly.
1533    ///
1534    /// # Arguments
1535    ///
1536    /// - `method` - The `ExportMethod` to use to render the data to download.
1537    ///
1538    /// # JavaScript Examples
1539    ///
1540    /// ```javascript
1541    /// const data = await viewer.export("plugin");
1542    /// ```
1543    pub fn export(&self, options: Option<JsExportOptions>) -> ApiFuture<JsExportData> {
1544        let this = self.clone();
1545        ApiFuture::new(async move {
1546            let ExportOptions {
1547                method,
1548                panel: name,
1549            } = parse_options(options)?;
1550
1551            let method = method.map(|m| JsString::from(m.as_str()));
1552            let method = if let Some(method) = method
1553                .map(|x| x.unchecked_into())
1554                .map(serde_wasm_bindgen::from_value)
1555            {
1556                method?
1557            } else {
1558                ExportMethod::Csv
1559            };
1560
1561            let panel = this.resolve_panel(name)?;
1562            Ok(export_method_to_jsvalue(
1563                &panel.session,
1564                &panel.renderer,
1565                &this.presentation,
1566                &this.workspace,
1567                method,
1568            )
1569            .await?
1570            .unchecked_into())
1571        })
1572    }
1573
1574    /// Copy this viewer's `View` or `Table` data to the system clipboard from
1575    /// within a user gesture, rejecting if nothing could be written.
1576    ///
1577    /// # Arguments
1578    ///
1579    /// - `method` - The `ExportMethod` (serialized as a `String`) to use to
1580    ///   render the data to the Clipboard.
1581    ///
1582    /// # JavaScript Examples
1583    ///
1584    /// ```javascript
1585    /// myDownloadButton.addEventListener("click", async () => {
1586    ///     await viewer.copy();
1587    /// })
1588    /// ```
1589    pub fn copy(&self, options: Option<JsExportOptions>) -> ApiFuture<()> {
1590        let copied = (|| -> ApiResult<_> {
1591            let ExportOptions {
1592                method,
1593                panel: name,
1594            } = parse_options(options)?;
1595
1596            let method = method.map(|m| JsString::from(m.as_str()));
1597            let method = if let Some(method) = method
1598                .map(|x| x.unchecked_into())
1599                .map(serde_wasm_bindgen::from_value)
1600            {
1601                method?
1602            } else {
1603                ExportMethod::Csv
1604            };
1605
1606            let panel = self.resolve_panel(name)?;
1607            Ok(copy_method_to_clipboard(
1608                &panel.session,
1609                &panel.renderer,
1610                &self.presentation,
1611                &self.workspace,
1612                method,
1613            ))
1614        })();
1615
1616        ApiFuture::new(async move { copied?.await })
1617    }
1618
1619    /// Reset a panel's `ViewerConfig` to its data-relative default.
1620    ///
1621    /// Without a `panel`, this is ELEMENT-LEVEL: EVERY panel is reset and the
1622    /// cross-filter overlay cleared (symmetric with
1623    /// [`Self::saveWorkspace`] / [`Self::restoreWorkspace`]). With `{panel}`,
1624    /// only that panel is reset — the other panels and the overlay are left
1625    /// untouched.
1626    ///
1627    /// # Arguments
1628    ///
1629    /// - `reset_all` - If set, will clear expressions and column settings as
1630    ///   well, and tear down the element's ENTIRE derived-table state: every
1631    ///   panel bound to a derived `Table` is released to its root table, and
1632    ///   every derivation (pending ones included) is deleted.
1633    /// - `options` - An optional `{panel?: string}`; the panel to reset, or
1634    ///   every panel when omitted.
1635    ///
1636    /// # JavaScript Examples
1637    ///
1638    /// ```javascript
1639    /// await viewer.reset();                     // every panel
1640    /// await viewer.reset(true, {panel: "p1"});  // just "p1", + expressions
1641    /// ```
1642    pub fn reset(&self, reset_all: Option<bool>, options: Option<JsPanelOptions>) -> ApiFuture<()> {
1643        let effect = self.workspace.effects().guard();
1644        let this = self.clone();
1645        let all = reset_all.unwrap_or_default();
1646        ApiFuture::new_throttled(async move {
1647            let PanelOptions { panel: name } = parse_options(options)?;
1648            let _effect = effect;
1649            let (completion, receiver) = Completion::new();
1650            {
1651                let root = this.root.borrow();
1652                let app = root.as_ref().ok_or("Already deleted")?;
1653                match name {
1654                    // Element-level: reset every panel + the cross-filter overlay.
1655                    None => {
1656                        tracing::debug!("Resetting config");
1657                        app.send_message(PerspectiveViewerMsg::Reset(all, Some(completion)));
1658                    },
1659                    // A single named panel; errors if the panel doesn't exist.
1660                    Some(name) => {
1661                        let panel = this.resolve_panel(Some(name))?;
1662                        tracing::debug!("Resetting config ({})", panel.id);
1663                        app.send_message(PerspectiveViewerMsg::ResetPanel(
1664                            Some(panel.id.to_string()),
1665                            all,
1666                            Some(completion),
1667                        ));
1668                    },
1669                }
1670            }
1671
1672            receiver.await.map_err(|_| ApiError::new("Cancelled"))?
1673        })
1674    }
1675
1676    /// Recalculate the viewer's dimensions and redraw.
1677    ///
1678    /// Use this method to tell `<perspective-viewer>` its dimensions have
1679    /// changed when auto-size mode has been disabled via [`Self::setAutoSize`].
1680    /// [`Self::resize`] resolves when the resize-initiated redraw of this
1681    /// element has completed.
1682    ///
1683    /// # Arguments
1684    ///
1685    /// - `options` - An optional object with the following fields:
1686    ///   - `dimensions` - An optional object `{width, height}` providing
1687    ///     explicit size hints (in pixels) for the plugin container. When
1688    ///     provided, the plugin element will be temporarily sized to these
1689    ///     dimensions during resize, then reset.
1690    ///
1691    /// # JavaScript Examples
1692    ///
1693    /// ```javascript
1694    /// await viewer.resize()
1695    /// await viewer.resize({dimensions: {width: 800, height: 600}})
1696    /// ```
1697    #[wasm_bindgen]
1698    pub fn resize(&self, options: Option<JsValue>) -> ApiFuture<()> {
1699        let opts: ResizeOptions = options
1700            .map(|v| v.into_serde_ext())
1701            .transpose()
1702            .unwrap_or_default()
1703            .unwrap_or_default();
1704
1705        let effect = self.workspace.effects().guard();
1706        let workspace = self.workspace.clone();
1707        ApiFuture::new_throttled(async move {
1708            let _effect = effect;
1709            // With zero panels there is nothing to resize; fan out to whatever
1710            // panels exist otherwise.
1711            let Some(panel) = workspace.active_panel() else {
1712                resize_visible_panels(&workspace).await;
1713                return Ok(());
1714            };
1715
1716            if !panel.renderer.is_plugin_activated()? {
1717                apply_and_render(&panel.session, &panel.renderer, ViewConfigUpdate::default())?
1718                    .await?;
1719            } else if let Some(dims) = opts.dimensions {
1720                panel
1721                    .renderer
1722                    .resize_with_dimensions(dims.width, dims.height)
1723                    .await?;
1724            } else {
1725                resize_visible_panels(&workspace).await;
1726            }
1727
1728            Ok(())
1729        })
1730    }
1731
1732    /// Sets the auto-size behavior of this component.
1733    ///
1734    /// When `true`, this `<perspective-viewer>` will register a
1735    /// `ResizeObserver` on itself and call [`Self::resize`] whenever its own
1736    /// dimensions change. However, when embedded in a larger application
1737    /// context, you may want to call [`Self::resize`] manually to avoid
1738    /// over-rendering; in this case auto-sizing can be disabled via this
1739    /// method. Auto-size behavior is enabled by default.
1740    ///
1741    /// # Arguments
1742    ///
1743    /// - `autosize` - Whether to enable `auto-size` behavior or not.
1744    ///
1745    /// # JavaScript Examples
1746    ///
1747    /// Disable auto-size behavior:
1748    ///
1749    /// ```javascript
1750    /// viewer.setAutoSize(false);
1751    /// ```
1752    #[wasm_bindgen]
1753    pub fn setAutoSize(&self, autosize: bool) {
1754        if autosize {
1755            let handle = Some(ResizeObserverHandle::new(
1756                &self.elem,
1757                &self.workspace,
1758                &self.presentation,
1759                &self.root,
1760            ));
1761            *self.resize_handle.borrow_mut() = handle;
1762        } else {
1763            *self.resize_handle.borrow_mut() = None;
1764        }
1765    }
1766
1767    /// Sets the auto-pause behavior of this component.
1768    ///
1769    /// When `true`, this `<perspective-viewer>` will skip rendering
1770    /// whenever it cannot be seen — tracked via an `IntersectionObserver`
1771    /// on itself (scrolled out of the viewport, `display: none`) combined
1772    /// with the document's page visibility (backgrounded browser tab,
1773    /// minimized window). Auto-pause is enabled by default.
1774    ///
1775    /// # Arguments
1776    ///
1777    /// - `autopause` Whether to enable `auto-pause` behavior or not.
1778    ///
1779    /// # JavaScript Examples
1780    ///
1781    /// Disable auto-size behavior:
1782    ///
1783    /// ```javascript
1784    /// viewer.setAutoPause(false);
1785    /// ```
1786    #[wasm_bindgen]
1787    pub fn setAutoPause(&self, autopause: bool) -> ApiFuture<()> {
1788        if autopause {
1789            let handle = Some(AutoPauseHandle::new(
1790                &self.elem,
1791                &self.presentation,
1792                &self.workspace,
1793            ));
1794
1795            *self.intersection_handle.borrow_mut() = handle;
1796        } else {
1797            *self.intersection_handle.borrow_mut() = None;
1798            let effect = self.workspace.effects().guard();
1799            let workspace = self.workspace.clone();
1800            let presentation = self.presentation.clone();
1801            return ApiFuture::new(async move {
1802                let _effect = effect;
1803                for id in workspace.panel_ids() {
1804                    if let Some(panel) = workspace.panel(&id) {
1805                        // A failed resume is already surfaced as that
1806                        // panel's error state — don't let it abort the
1807                        // remaining panels' resumes.
1808                        let _ =
1809                            set_panel_paused(&panel.session, &panel.renderer, &presentation, true)
1810                                .await;
1811                    }
1812                }
1813
1814                Ok(())
1815            });
1816        }
1817
1818        ApiFuture::new(async move { Ok(()) })
1819    }
1820
1821    /// Return a [`perspective_js::JsViewWindow`] for the currently selected
1822    /// region of the named panel, or the active panel when `panel` is omitted.
1823    #[wasm_bindgen]
1824    pub fn getSelection(&self, options: Option<JsPanelOptions>) -> ApiResult<Option<JsViewWindow>> {
1825        let PanelOptions { panel: name } = parse_options(options)?;
1826        let panel = self.resolve_panel(name)?;
1827        Ok(panel.renderer.get_selection().map(|x| x.into()))
1828    }
1829
1830    /// Set the selection [`perspective_js::JsViewWindow`] for the named panel,
1831    /// or the active panel when `panel` is omitted.
1832    #[wasm_bindgen]
1833    pub fn setSelection(
1834        &self,
1835        window: Option<JsViewWindow>,
1836        options: Option<JsPanelOptions>,
1837    ) -> ApiResult<()> {
1838        let PanelOptions { panel: name } = parse_options(options)?;
1839        let window = window.map(|x| x.into_serde_ext()).transpose()?;
1840        self.resolve_panel(name)?.renderer.set_selection(window);
1841        Ok(())
1842    }
1843
1844    /// Get this viewer's edit port for the named panel's [`Table`] (see
1845    /// [`Table::update`] for details on ports), or the active panel when
1846    /// `panel` is omitted.
1847    #[wasm_bindgen]
1848    pub fn getEditPort(&self, options: Option<JsPanelOptions>) -> ApiResult<f64> {
1849        let PanelOptions { panel: name } = parse_options(options)?;
1850        let panel = self.resolve_panel(name)?;
1851        let edit_port = if let Some(ctx) = panel.renderer.render_context() {
1852            ctx.edit_port
1853        } else {
1854            panel.session.metadata().get_edit_port()
1855        };
1856
1857        Ok(edit_port.ok_or("No `Table` loaded")?)
1858    }
1859
1860    /// Restyle all plugins from current document.
1861    ///
1862    /// <div class="warning">
1863    ///
1864    /// [`Self::restyleElement`] _must_ be called for many runtime changes to
1865    /// CSS properties to be reflected in an already-rendered
1866    /// `<perspective-viewer>`, including a `prefers-color-scheme` change
1867    /// under a preference-aware theme such as `"Pro"`.
1868    ///
1869    /// </div>
1870    ///
1871    /// # JavaScript Examples
1872    ///
1873    /// ```javascript
1874    /// viewer.style = "--psp--color: red";
1875    /// await viewer.restyleElement();
1876    /// ```
1877    #[wasm_bindgen]
1878    pub fn restyleElement(&self) -> ApiFuture<()> {
1879        clone!(self.workspace);
1880        let effect = workspace.effects().guard();
1881        ApiFuture::new(async move {
1882            let _effect = effect;
1883            for panel in workspace
1884                .panel_ids()
1885                .into_iter()
1886                .filter_map(|id| workspace.panel(&id))
1887            {
1888                panel.renderer.restyle_all().await?;
1889            }
1890
1891            Ok(())
1892        })
1893    }
1894
1895    #[wasm_bindgen]
1896    pub fn getThemes(&self) -> ApiFuture<Vec<String>> {
1897        clone!(self.presentation);
1898        ApiFuture::new(async move { Ok(presentation.get_available_themes().await?.to_vec()) })
1899    }
1900
1901    /// Set the available theme names available in the status bar UI.
1902    ///
1903    /// Calling [`Self::resetThemes`] may cause the current theme to switch,
1904    /// if e.g. the new theme set does not contain the current theme.
1905    ///
1906    /// # JavaScript Examples
1907    ///
1908    /// Restrict `<perspective-viewer>` theme options to _only_ default light
1909    /// and dark themes, regardless of what is auto-detected from the page's
1910    /// CSS:
1911    ///
1912    /// ```javascript
1913    /// viewer.resetThemes(["Pro Light", "Pro Dark"])
1914    /// ```
1915    #[wasm_bindgen]
1916    pub fn resetThemes(&self, themes: Option<Box<[JsValue]>>) -> ApiFuture<()> {
1917        clone!(self.workspace, self.presentation);
1918        let effect = workspace.effects().guard();
1919        ApiFuture::new(async move {
1920            let _effect = effect;
1921            // `None` (re-parse the document) must survive the conversion —
1922            // mapping BEFORE defaulting is what keeps that branch reachable
1923            // from JavaScript at all.
1924            let themes: Option<Vec<String>> = match themes {
1925                None => None,
1926                Some(themes) => themes.iter().map(|x| x.as_string()).collect(),
1927            };
1928
1929            let previous = presentation.active_theme_name_sync();
1930            let active = presentation.reset_themes(themes).await?;
1931            let available = presentation.get_available_themes().await?;
1932            for panel in workspace
1933                .panel_ids()
1934                .into_iter()
1935                .filter_map(|id| workspace.panel(&id))
1936            {
1937                let theme = panel.renderer.theme();
1938
1939                // A panel follows the host only when it was TRACKING it (it
1940                // holds the host's previous theme, which is how every panel
1941                // born without an explicit one starts — and what keeps the
1942                // active panel and the host in agreement), or when its own
1943                // theme has left the registry. A panel explicitly set to a
1944                // different, still-available theme is untouched: re-ordering
1945                // alone must repaint nothing.
1946                let stale = theme.as_ref().is_none_or(|x| !available.contains(x));
1947                if (stale || theme == previous) && theme != active {
1948                    submit_theme(&panel.session, &panel.renderer, active.clone());
1949                    if panel.renderer.needs_restyle() {
1950                        panel.renderer.restyle_all().await?;
1951                    }
1952                }
1953            }
1954
1955            presentation.publish_theme_config().await?;
1956            Ok(())
1957        })
1958    }
1959
1960    /// Determines the render throttling behavior. Can be an integer, for
1961    /// millisecond window to throttle render event; or, if `None`, adaptive
1962    /// throttling will be calculated from the measured render time of the
1963    /// last 5 frames.
1964    ///
1965    /// # Arguments
1966    ///
1967    /// - `throttle` - The throttle rate in milliseconds (f64), or `None` for
1968    ///   adaptive throttling.
1969    ///
1970    /// # JavaScript Examples
1971    ///
1972    /// Only draws at most 1 frame/sec:
1973    ///
1974    /// ```rust
1975    /// viewer.setThrottle(1000);
1976    /// ```
1977    #[wasm_bindgen]
1978    pub fn setThrottle(&self, val: Option<f64>) {
1979        for panel in self
1980            .workspace
1981            .panel_ids()
1982            .into_iter()
1983            .filter_map(|id| self.workspace.panel(&id))
1984        {
1985            panel.renderer.set_throttle(val);
1986        }
1987    }
1988
1989    /// Toggle (or force) the config panel open/closed.
1990    ///
1991    /// # Arguments
1992    ///
1993    /// - `force` - Force the state of the panel open or closed, or `None` to
1994    ///   toggle.
1995    ///
1996    /// # JavaScript Examples
1997    ///
1998    /// ```javascript
1999    /// await viewer.toggleConfig();
2000    /// ```
2001    #[wasm_bindgen]
2002    pub fn toggleConfig(&self, force: Option<bool>) -> ApiFuture<()> {
2003        let effect = self.workspace.effects().guard();
2004        let root = self.root.clone();
2005        ApiFuture::new(async move {
2006            let _effect = effect;
2007            let force = force.map(SettingsUpdate::Update);
2008            let (sender, receiver) = channel::<ApiResult<wasm_bindgen::JsValue>>();
2009            root.borrow().as_ref().into_apierror()?.send_message(
2010                PerspectiveViewerMsg::ToggleSettingsInit(force, true, Some(sender)),
2011            );
2012
2013            receiver.await.map_err(|_| JsValue::from("Cancelled"))??;
2014            Ok(())
2015        })
2016    }
2017
2018    /// Get an `Array` of all of the plugin custom elements registered for this
2019    /// element. This may not include plugins which called
2020    /// [`registerPlugin`] after the host has rendered for the first time.
2021    #[wasm_bindgen]
2022    pub fn getAllPlugins(&self) -> Array {
2023        self.workspace
2024            .active_renderer()
2025            .map(|r| r.get_all_plugins().iter().collect::<Array>())
2026            .unwrap_or_default()
2027    }
2028
2029    /// Gets a plugin Custom Element with the `name` field, or get the active
2030    /// plugin if no `name` is provided.
2031    ///
2032    /// # Arguments
2033    ///
2034    /// - `name` - The `name` property of a perspective plugin Custom Element,
2035    ///   or `None` for the active plugin's Custom Element.
2036    #[wasm_bindgen]
2037    pub fn getPlugin(&self, name: Option<String>) -> ApiResult<JsPerspectiveViewerPlugin> {
2038        let renderer = self
2039            .workspace
2040            .active_renderer()
2041            .ok_or_else(|| ApiError::new("No active panel"))?;
2042        match name {
2043            None => renderer.ensure_plugin_selected(),
2044            Some(name) => renderer.get_plugin(&name),
2045        }
2046    }
2047
2048    /// Add a new, independent panel to this viewer's layout, rendering the
2049    /// supplied [`ViewerConfigInitial`] into it. Unlike [`Self::restore`]'s
2050    /// update-shaped argument, a new panel has no prior state, so `table`
2051    /// is REQUIRED — a table-less call rejects before the layout is
2052    /// touched. The panel uses the default [`perspective_client::Client`]
2053    /// (the first passed to [`Self::load`]) to resolve its `table`. Returns
2054    /// the generated panel id.
2055    ///
2056    /// The element-level `settings` field does not exist on the argument
2057    /// type (it is shared across the element, not per-panel).
2058    ///
2059    /// # Arguments
2060    ///
2061    /// - `config` - The new panel's initial config, whose `table` is required.
2062    /// - `options.wait_for_table` - when `true`, a `table` no loaded client
2063    ///   hosts yet creates the panel empty and pending until the table is
2064    ///   created, instead of the default rejection.
2065    #[wasm_bindgen]
2066    pub fn addPanel(
2067        &self,
2068        config: JsViewerConfigInitial,
2069        options: Option<JsAddPanelOptions>,
2070    ) -> ApiFuture<String> {
2071        clone!(self.elem, self.presentation, self.workspace);
2072        let effect = workspace.effects().guard();
2073        let notify = self.layout_changed_notify();
2074        let saved = saved_version(&config);
2075        ApiFuture::new(noting_saved_version(saved, async move {
2076            let _effect = effect;
2077            let AddPanelOptions { wait_for_table } = parse_options(options)?;
2078            let config = ViewerConfigInitial::decode(&config)?;
2079            let id = create_panel(
2080                &elem,
2081                &presentation,
2082                &workspace,
2083                &notify,
2084                None,
2085                config,
2086                None,
2087                MissingTable::from_wait(wait_for_table),
2088            )
2089            .await?;
2090            Ok(id.as_str().to_owned())
2091        }))
2092    }
2093
2094    /// Get the ids of all panels in this viewer's layout, in insertion order.
2095    #[wasm_bindgen]
2096    pub fn getPanelNames(&self) -> Array {
2097        self.workspace
2098            .panel_ids()
2099            .iter()
2100            .map(|id| JsValue::from_str(id.as_str()))
2101            .collect()
2102    }
2103
2104    /// The id of the active panel — the one the settings panel and status-bar
2105    /// toolbar target — or `null` when the element has zero panels.
2106    #[wasm_bindgen]
2107    pub fn getActivePanel(&self) -> JsValue {
2108        self.workspace
2109            .active_id()
2110            .map(|id| JsValue::from_str(id.as_str()))
2111            .unwrap_or(JsValue::NULL)
2112    }
2113
2114    /// Make the panel with id `name` the active panel, re-targeting the
2115    /// settings panel and status-bar toolbar (and the root's
2116    /// session/renderer subscriptions) to its engines. Resolves after the
2117    /// activation-chrome redraws on both sides of the switch have completed
2118    /// (invariant I6).
2119    #[wasm_bindgen]
2120    pub fn setActivePanel(&self, name: String) -> ApiFuture<()> {
2121        let effect = self.workspace.effects().guard();
2122        let root = self.root.clone();
2123        ApiFuture::new(async move {
2124            let _effect = effect;
2125            let (completion, receiver) = Completion::new();
2126            root.borrow()
2127                .as_ref()
2128                .into_apierror()?
2129                .send_message(PerspectiveViewerMsg::SetActivePanel(name, Some(completion)));
2130
2131            receiver.await.map_err(|_| ApiError::new("Cancelled"))?
2132        })
2133    }
2134
2135    /// Remove the panel with id `name` from the layout, disposing its engines
2136    /// (its `View` is deleted and its `Table` reference released). The last
2137    /// remaining panel cannot be removed (resolves as a no-op). Resolves
2138    /// after the panel's teardown run completes, carrying any teardown
2139    /// error — previously fire-and-forget and silently dropped (invariant
2140    /// I6). See also [`Self::addPanel`].
2141    #[wasm_bindgen]
2142    pub fn removePanel(&self, name: String) -> ApiFuture<()> {
2143        let effect = self.workspace.effects().guard();
2144        let root = self.root.clone();
2145        ApiFuture::new(async move {
2146            let _effect = effect;
2147            let (completion, receiver) = Completion::new();
2148            root.borrow()
2149                .as_ref()
2150                .into_apierror()?
2151                .send_message(PerspectiveViewerMsg::ClosePanel(name, Some(completion)));
2152
2153            receiver.await.map_err(|_| ApiError::new("Cancelled"))?
2154        })
2155    }
2156
2157    /// Set the function that declares this viewer's custom commands, replacing
2158    /// any previously set, and re-query every plugin's command buttons when it
2159    /// or its scopes changed.
2160    ///
2161    /// # Arguments
2162    ///
2163    /// - `schema` - A synchronous function from a command context to a `{
2164    ///   commands }` list, or `null` to remove the current one.
2165    /// - `options.scopes` - The surfaces the schema is evaluated for,
2166    ///   `["context-menu"]` when omitted.
2167    ///
2168    /// # JavaScript Examples
2169    ///
2170    /// ```javascript
2171    /// await viewer.setCommandSchema(
2172    ///     (ctx) => ({
2173    ///         commands: [{ kind: "Command", key: "hello", label: "Hello" }],
2174    ///     }),
2175    ///     { scopes: ["context-menu", "datagrid-row"] },
2176    /// );
2177    /// ```
2178    #[wasm_bindgen]
2179    pub fn setCommandSchema(
2180        &self,
2181        schema: Option<JsCommandSchemaFn>,
2182        options: Option<JsCommandSchemaOptions>,
2183    ) -> ApiResult<ApiFuture<()>> {
2184        let schema = schema
2185            .map(|schema| {
2186                schema
2187                    .dyn_into::<js_sys::Function>()
2188                    .map_err(|_| ApiError::new("`setCommandSchema` expects a function or `null`"))
2189            })
2190            .transpose()?;
2191
2192        let CommandSchemaOptions { scopes } = parse_options(options)?;
2193        let scopes = scopes.unwrap_or_else(|| vec![CommandLocation::ContextMenu]);
2194        if self.presentation.set_command_schema(schema, scopes) {
2195            Ok(self.invalidate_panels(None))
2196        } else {
2197            Ok(ApiFuture::new(async { Ok(()) }))
2198        }
2199    }
2200
2201    /// Evaluate the app's command schema at `location` for each of `refs`,
2202    /// resolved against `frame`, the viewport read of the panel plugin
2203    /// `plugin`; `undefined` when `location` is outside the schema's scopes
2204    /// or no schema is set.
2205    ///
2206    /// # Arguments
2207    ///
2208    /// - `plugin` - The calling plugin element, which identifies its panel.
2209    /// - `location` - The surface being rendered.
2210    /// - `frame` - The plugin's viewport read, as `to_columns_string({ id: true
2211    ///   })` and `column_paths()` returned it.
2212    /// - `refs` - One view row and/or column index per button.
2213    ///
2214    /// # JavaScript Examples
2215    ///
2216    /// ```javascript
2217    /// const results = viewer.queryCommands(this, "datagrid-row", frame, [{ y: 12 }]);
2218    /// ```
2219    #[wasm_bindgen]
2220    pub fn queryCommands(
2221        &self,
2222        plugin: HtmlElement,
2223        location: JsCommandLocation,
2224        frame: JsViewFrame,
2225        refs: JsHitRefs,
2226    ) -> ApiResult<JsPerspectiveCommands> {
2227        let location: CommandLocation = JsValue::from(location).into_serde_ext()?;
2228        let panel = panel_for_plugin(&self.workspace, plugin.as_ref())
2229            .ok_or_else(|| ApiError::new("`queryCommands` expects a panel's active plugin"))?;
2230
2231        let results = query_commands(
2232            &self.presentation,
2233            &panel,
2234            location,
2235            &frame.into(),
2236            &refs.into(),
2237        )?;
2238
2239        Ok(match results {
2240            Some(results) => JsValue::from(results).unchecked_into(),
2241            None => JsValue::UNDEFINED.unchecked_into(),
2242        })
2243    }
2244
2245    /// Dispatch `perspective-command` for the app command `key` picked against
2246    /// `context`, as the context menu does.
2247    ///
2248    /// # JavaScript Examples
2249    ///
2250    /// ```javascript
2251    /// viewer.invokeCommand("ticket", result.context);
2252    /// ```
2253    #[wasm_bindgen]
2254    pub fn invokeCommand(&self, key: String, context: JsCommandContext) -> ApiResult<()> {
2255        self.presentation
2256            .command_invoked
2257            .emit((key, context.into()));
2258        Ok(())
2259    }
2260
2261    /// Redraw each panel's plugin from its current `View` without re-creating
2262    /// the view, such as after a command changed state its buttons read; calls
2263    /// within one task run as one.
2264    ///
2265    /// # Arguments
2266    ///
2267    /// - `options.panel` - Limits the redraw to one panel.
2268    ///
2269    /// # JavaScript Examples
2270    ///
2271    /// ```javascript
2272    /// viewer.addEventListener("perspective-command", (e) => {
2273    ///     flagged.add(e.detail.context.hit.id);
2274    ///     viewer.invalidate({ panel: e.detail.context.panel });
2275    /// });
2276    /// ```
2277    #[wasm_bindgen]
2278    pub fn invalidate(&self, options: Option<JsPanelOptions>) -> ApiResult<ApiFuture<()>> {
2279        let PanelOptions { panel } = parse_options(options)?;
2280        if let Some(name) = &panel {
2281            self.resolve_panel(Some(name.clone()))?;
2282        }
2283
2284        Ok(self.invalidate_panels(panel))
2285    }
2286
2287    fn invalidate_panels(&self, panel: Option<String>) -> ApiFuture<()> {
2288        let (completion, receiver) = Completion::new();
2289        if self.presentation.queue_invalidation(panel, completion) {
2290            clone!(self.presentation, self.workspace);
2291            ApiFuture::spawn(async move {
2292                JsFuture::from(js_sys::Promise::resolve(&JsValue::UNDEFINED)).await?;
2293                let Some(batch) = presentation.take_invalidations() else {
2294                    return Ok(());
2295                };
2296
2297                let panels = if batch.all {
2298                    workspace.panels()
2299                } else {
2300                    batch
2301                        .panels
2302                        .iter()
2303                        .filter_map(|id| workspace.panel(&PanelId::from(id.as_str())))
2304                        .collect()
2305                };
2306
2307                let mut result = Ok(());
2308                for panel in panels {
2309                    if let Err(err) = panel.renderer.update().await {
2310                        result = Err(err);
2311                    }
2312                }
2313
2314                for completion in batch.completions {
2315                    let result = result.clone();
2316                    completion.resolve_after(async move { result });
2317                }
2318
2319                Ok(())
2320            });
2321        }
2322
2323        ApiFuture::new(async move { receiver.await.map_err(|_| ApiError::new("Cancelled"))? })
2324    }
2325
2326    /// Open a menu of `commands` at viewport `point`, dispatching
2327    /// `perspective-command` with `context` for a pick; resolves when the menu
2328    /// closes.
2329    ///
2330    /// # JavaScript Examples
2331    ///
2332    /// ```javascript
2333    /// await viewer.showCommandMenu(result.context, group.commands, { x: e.clientX, y: e.clientY });
2334    /// ```
2335    #[wasm_bindgen]
2336    pub fn showCommandMenu(
2337        &self,
2338        context: JsCommandContext,
2339        commands: JsCommandSpecs,
2340        point: JsPoint,
2341    ) -> ApiFuture<()> {
2342        let this = self.clone();
2343        ApiFuture::new(async move {
2344            let commands: Vec<CommandSpec> = JsValue::from(commands).into_serde_ext()?;
2345            let point: MenuPoint = JsValue::from(point).into_serde_ext()?;
2346            let context = JsValue::from(context);
2347            let theme = js_sys::Reflect::get(&context, &"panel".into())
2348                .ok()
2349                .and_then(|panel| panel.as_string())
2350                .and_then(|panel| this.workspace.panel(&PanelId::from(panel.as_str())))
2351                .and_then(|panel| panel.renderer.theme());
2352
2353            show_command_menu(
2354                &this.presentation,
2355                context,
2356                commands,
2357                point.x,
2358                point.y,
2359                theme,
2360            )
2361            .await
2362        })
2363    }
2364
2365    /// Create a new JavaScript Heap reference for this model instance.
2366    #[doc(hidden)]
2367    #[allow(clippy::use_self)]
2368    #[wasm_bindgen]
2369    pub fn __get_model(&self) -> PerspectiveViewerElement {
2370        self.clone()
2371    }
2372
2373    /// Asynchronously opens the column settings for a specific column.
2374    /// When finished, the `<perspective-viewer>` element will emit a
2375    /// "perspective-toggle-column-settings" CustomEvent.
2376    /// The event's details property has two fields: `{open: bool, column_name?:
2377    /// string}`. The CustomEvent is also fired whenever the user toggles the
2378    /// sidebar manually.
2379    #[wasm_bindgen]
2380    pub fn toggleColumnSettings(
2381        &self,
2382        column_name: String,
2383        options: Option<JsPanelOptions>,
2384    ) -> ApiFuture<()> {
2385        let effect = self.workspace.effects().guard();
2386        let this = self.clone();
2387        ApiFuture::new_throttled(async move {
2388            let PanelOptions { panel: name } = parse_options(options)?;
2389            let _effect = effect;
2390            let panel = this.resolve_panel(name)?;
2391            let was_active = this.workspace.active_id().as_ref() == Some(&panel.id);
2392            let target = {
2393                let config = panel.session.get_view_config();
2394                let metadata = panel.session.metadata();
2395                classify_column(&column_name, &config, &metadata)
2396                    .map(|_| crate::presentation::ColumnSettingsTarget::Column(column_name))
2397            };
2398            if !was_active {
2399                this.root.borrow().as_ref().into_apierror()?.send_message(
2400                    PerspectiveViewerMsg::SetActivePanel(panel.id.as_str().to_owned(), None),
2401                );
2402            }
2403
2404            let (sender, receiver) = channel::<()>();
2405            this.root.borrow().as_ref().into_apierror()?.send_message(
2406                PerspectiveViewerMsg::OpenColumnSettings {
2407                    target,
2408                    sender: Some(sender),
2409                    toggle: was_active,
2410                },
2411            );
2412
2413            receiver.await.map_err(|_| ApiError::from("Cancelled"))
2414        })
2415    }
2416}
2417
2418#[cfg(feature = "llm-agent")]
2419#[wasm_bindgen]
2420impl PerspectiveViewerElement {
2421    /// Configure the embedded LLM agent (see `prompt()`), replacing any prior
2422    /// configuration and conversation.
2423    ///
2424    /// The agent core is provider-agnostic: one OpenAI-chat-completions
2425    /// protocol over primitive connection fields. Exactly one of
2426    /// `config.url` or `config.engine` is required; the `providers` presets
2427    /// exported by this package are plain spreadable collections of these
2428    /// fields (`{...providers.anthropic, apiKey}`).
2429    ///
2430    /// - `config.url` - a full chat-completions endpoint URL (any
2431    ///   OpenAI-compatible service: Anthropic/Gemini compatibility endpoints,
2432    ///   LM Studio, Ollama, OpenRouter, a proxy...).
2433    /// - `config.engine` - an in-page engine object with an OpenAI-compatible
2434    ///   `chat.completions.create(request)` method (e.g. WebLLM's `MLCEngine`);
2435    ///   mutually exclusive with `url`.
2436    /// - `config.headers` - extra request headers, sent verbatim.
2437    /// - `config.apiKey` - sugar for the `Authorization: Bearer` header.
2438    /// - `config.model` - model id sent with each request; local servers and
2439    ///   engines generally answer with whatever model is loaded.
2440    /// - `config.name` - cosmetic label for the chat badge (presets set this).
2441    /// - `config.systemPrompt` - extra system-prompt context appended to the
2442    ///   agent's built-in instructions.
2443    /// - `config.maxTurns` - max model turns (tool-call rounds + the final
2444    ///   answer) per `prompt()` call. Defaults to 16.
2445    /// - `config.docs` - the agent metadata bundle, which supplies the
2446    ///   `search_docs` corpus and the rich tool parameter schemas: the packaged
2447    ///   `dist/docs/perspective-docs.json` asset as a parsed object (`import
2448    ///   docs from "…json" with { type: "json" }`), a `fetch()` `Response`, an
2449    ///   `ArrayBuffer`, a JSON string, or a `Promise` of any of those — and/or
2450    ///   an inline array of `{title?, text}` entries for host data definitions.
2451    ///   Omitted, `search_docs` searches an empty corpus and the parameter
2452    ///   schemas degrade to permissive objects.
2453    /// - `config.systemRole` - where the preamble (plus `systemPrompt`) is
2454    ///   placed: `"system"` (default) or `"user"`. Some engines refuse a system
2455    ///   message alongside `tools` because they substitute their own — WebLLM's
2456    ///   Hermes function calling throws `CustomSystemPromptError` on ANY system
2457    ///   message — and those need `"user"`, which folds the same text into the
2458    ///   opening user turn.
2459    /// - `config.entitlements` - access grants limiting which tools the agent
2460    ///   is offered (and may call): any of `"read_view"`, `"configure_view"`,
2461    ///   `"manage_layout"`, `"read_docs"`, `"execute_code"`, `"read_data"`.
2462    ///   Omitted, all but `"execute_code"` and `"read_data"` are granted;
2463    ///   `["read_view", "read_docs"]` yields a read-only agent. Users may
2464    ///   switch granted entitlements off from the chat panel, never on.
2465    ///
2466    /// # JavaScript Examples
2467    ///
2468    /// ```javascript
2469    /// import { providers } from "@perspective-dev/viewer";
2470    ///
2471    /// viewer.agentConfig({
2472    ///     ...providers.anthropic,
2473    ///     apiKey: "sk-ant-...",
2474    ///     docs: fetch(
2475    ///         "node_modules/@perspective-dev/viewer/dist/docs/perspective-docs.json",
2476    ///     ),
2477    /// });
2478    /// ```
2479    #[wasm_bindgen(js_name = "agentConfig")]
2480    pub fn agent_config(&self, config: JsValue) -> ApiResult<()> {
2481        let runtime = AgentRuntime::new(&config, self.clone())?;
2482        self.presentation.agent.configure(runtime);
2483        Ok(())
2484    }
2485
2486    /// Run one conversational turn of the embedded LLM agent (configured via
2487    /// `agentConfig()`), resolving with the agent's final text response after
2488    /// any tool calls have been applied to this element. Turns share a
2489    /// conversation history (and the chat sidebar's transcript) until
2490    /// `agentReset()`; a call made while a turn is already running rejects.
2491    /// Tool activity is emitted as `perspective-agent-tool` CustomEvents on
2492    /// this element. A failed turn rejects with an `Error` whose `retry()`
2493    /// method retries it, returning a `Promise` that settles like this one.
2494    ///
2495    /// # JavaScript Examples
2496    ///
2497    /// ```javascript
2498    /// await viewer.agentPrompt("Show me sales by region as a bar chart");
2499    /// ```
2500    #[wasm_bindgen(js_name = "agentPrompt")]
2501    pub fn agent_prompt(&self, prompt: String) -> js_sys::Promise {
2502        let presentation = self.presentation.clone();
2503        let fut = ApiFuture::new(async move {
2504            Ok(JsValue::from(presentation.agent.run_prompt(prompt).await?))
2505        });
2506
2507        js_sys::Promise::from(fut)
2508    }
2509
2510    /// Clear the agent's conversation (history and chat transcript), keeping
2511    /// its configuration. Cancels any in-flight turn.
2512    #[wasm_bindgen(js_name = "agentReset")]
2513    pub fn agent_reset(&self) -> js_sys::Promise {
2514        let presentation = self.presentation.clone();
2515        let fut = ApiFuture::new(async move {
2516            presentation.agent.reset().await;
2517            Ok(JsValue::UNDEFINED)
2518        });
2519
2520        js_sys::Promise::from(fut)
2521    }
2522}