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