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 js_sys::{Array, JsString};
20use perspective_client::config::ViewConfigUpdate;
21use perspective_client::utils::PerspectiveResultExt;
22use perspective_js::{JsViewConfig, JsViewWindow, Table, View, apierror};
23use wasm_bindgen::JsCast;
24use wasm_bindgen::prelude::*;
25use wasm_bindgen_derive::try_from_js_option;
26use wasm_bindgen_futures::JsFuture;
27use web_sys::HtmlElement;
28
29use crate::components::viewer::{PerspectiveViewerMsg, PerspectiveViewerProps};
30use crate::config::*;
31use crate::custom_events::*;
32use crate::dragdrop::*;
33use crate::js::*;
34use crate::presentation::*;
35use crate::renderer::*;
36use crate::root::Root;
37use crate::session::{ResetOptions, Session, TableLoadState};
38use crate::tasks::*;
39use crate::utils::*;
40use crate::*;
41
42#[derive(serde::Deserialize, Default)]
43struct ResizeOptions {
44 dimensions: Option<ResizeDimensions>,
45}
46
47#[derive(serde::Deserialize, Clone, Copy)]
48struct ResizeDimensions {
49 width: f64,
50 height: f64,
51}
52
53/// The `<perspective-viewer>` custom element.
54///
55/// # JavaScript Examples
56///
57/// Create a new `<perspective-viewer>`:
58///
59/// ```javascript
60/// const viewer = document.createElement("perspective-viewer");
61/// window.body.appendChild(viewer);
62/// ```
63///
64/// Complete example including loading and restoring the [`Table`]:
65///
66/// ```javascript
67/// import perspective from "@perspective-dev/viewer";
68/// import perspective from "@perspective-dev/client";
69///
70/// const viewer = document.createElement("perspective-viewer");
71/// const worker = await perspective.worker();
72///
73/// await worker.table("x\n1", {name: "table_one"});
74/// await viewer.load(worker);
75/// await viewer.restore({table: "table_one"});
76/// ```
77#[derive(Clone)]
78#[wasm_bindgen]
79pub struct PerspectiveViewerElement {
80 elem: HtmlElement,
81 root: Root<components::viewer::PerspectiveViewer>,
82 resize_handle: Rc<RefCell<Option<ResizeObserverHandle>>>,
83 intersection_handle: Rc<RefCell<Option<IntersectionObserverHandle>>>,
84 session: Session,
85 renderer: Renderer,
86 presentation: Presentation,
87 custom_events: CustomEvents,
88 _subscriptions: Rc<[Subscription; 2]>,
89}
90
91impl HasCustomEvents for PerspectiveViewerElement {
92 fn custom_events(&self) -> &CustomEvents {
93 &self.custom_events
94 }
95}
96
97impl HasPresentation for PerspectiveViewerElement {
98 fn presentation(&self) -> &Presentation {
99 &self.presentation
100 }
101}
102
103impl HasRenderer for PerspectiveViewerElement {
104 fn renderer(&self) -> &Renderer {
105 &self.renderer
106 }
107}
108
109impl HasSession for PerspectiveViewerElement {
110 fn session(&self) -> &Session {
111 &self.session
112 }
113}
114
115impl StateProvider for PerspectiveViewerElement {
116 type State = PerspectiveViewerElement;
117
118 fn clone_state(&self) -> Self::State {
119 self.clone()
120 }
121}
122
123impl CustomElementMetadata for PerspectiveViewerElement {
124 const CUSTOM_ELEMENT_NAME: &'static str = "perspective-viewer";
125 const STATICS: &'static [&'static str] = ["registerPlugin"].as_slice();
126}
127
128#[wasm_bindgen]
129impl PerspectiveViewerElement {
130 #[doc(hidden)]
131 #[wasm_bindgen(constructor)]
132 pub fn new(elem: web_sys::HtmlElement) -> Self {
133 let init = web_sys::ShadowRootInit::new(web_sys::ShadowRootMode::Open);
134 let shadow_root = elem
135 .attach_shadow(&init)
136 .unwrap()
137 .unchecked_into::<web_sys::Element>();
138
139 Self::new_from_shadow(elem, shadow_root)
140 }
141
142 fn new_from_shadow(elem: web_sys::HtmlElement, shadow_root: web_sys::Element) -> Self {
143 // Application State
144 let session = Session::new();
145 let renderer = Renderer::new(&elem);
146 let presentation = Presentation::new(&elem);
147 let custom_events = CustomEvents::new(&elem, &session, &renderer, &presentation);
148
149 // Create Yew App
150 let props = yew::props!(PerspectiveViewerProps {
151 elem: elem.clone(),
152 session: session.clone(),
153 renderer: renderer.clone(),
154 presentation: presentation.clone(),
155 dragdrop: DragDrop::new(&elem),
156 custom_events: custom_events.clone(),
157 });
158
159 let state = props.clone_state();
160 let root = Root::new(shadow_root, props);
161
162 // Create callbacks
163 let update_sub = session.table_updated.add_listener({
164 clone!(renderer, session);
165 move |_| {
166 clone!(renderer, session);
167 ApiFuture::spawn(async move {
168 renderer
169 .update(session.get_view())
170 .await
171 .ignore_view_delete()
172 .map(|_| ())
173 })
174 }
175 });
176
177 let eject_sub = presentation.on_eject.add_listener({
178 let root = root.clone();
179 move |_| ApiFuture::spawn(state.delete_all(&root))
180 });
181
182 let resize_handle =
183 ResizeObserverHandle::new(&elem, &renderer, &session, &presentation, &root);
184
185 let intersect_handle =
186 IntersectionObserverHandle::new(&elem, &presentation, &session, &renderer);
187
188 Self {
189 elem,
190 root,
191 session,
192 renderer,
193 presentation,
194 resize_handle: Rc::new(RefCell::new(Some(resize_handle))),
195 intersection_handle: Rc::new(RefCell::new(Some(intersect_handle))),
196 custom_events,
197 _subscriptions: Rc::new([update_sub, eject_sub]),
198 }
199 }
200
201 #[doc(hidden)]
202 #[wasm_bindgen(js_name = "connectedCallback")]
203 pub fn connected_callback(&self) -> ApiResult<()> {
204 tracing::debug!("Connected <perspective-viewer>");
205 Ok(())
206 }
207
208 /// Loads a [`Client`], or optionally [`Table`], or optionally a Javascript
209 /// `Promise` which returns a [`Client`] or [`Table`], in this viewer.
210 ///
211 /// Loading a [`Client`] does not render, but subsequent calls to
212 /// [`PerspectiveViewerElement::restore`] will use this [`Client`] to look
213 /// up the proviced `table` name field for the provided
214 /// [`ViewerConfigUpdate`].
215 ///
216 /// Loading a [`Table`] is equivalent to subsequently calling
217 /// [`Self::restore`] with the `table` field set to [`Table::get_name`], and
218 /// will render the UI in its default state when [`Self::load`] resolves.
219 /// If you plan to call [`Self::restore`] anyway, prefer passing a
220 /// [`Client`] argument to [`Self::load`] as it will conserve one render.
221 ///
222 /// When [`PerspectiveViewerElement::load`] resolves, the first frame of the
223 /// UI + visualization is guaranteed to have been drawn. Awaiting the result
224 /// of this method in a `try`/`catch` block will capture any errors
225 /// thrown during the loading process, or from the [`Client`] `Promise`
226 /// itself.
227 ///
228 /// [`PerspectiveViewerElement::load`] may also be called with a [`Table`],
229 /// which is equivalent to:
230 ///
231 /// ```javascript
232 /// await viewer.load(await table.get_client());
233 /// await viewer.restore({name: await table.get_name()})
234 /// ```
235 ///
236 /// If you plan to call [`PerspectiveViewerElement::restore`] immediately
237 /// after [`PerspectiveViewerElement::load`] yourself, as is commonly
238 /// done when loading and configuring a new `<perspective-viewer>`, you
239 /// should use a [`Client`] as an argument and set the `table` field in the
240 /// restore call as
241 ///
242 /// A [`Table`] can be created using the
243 /// [`@perspective-dev/client`](https://www.npmjs.com/package/@perspective-dev/client)
244 /// library from NPM (see [`perspective_js`] documentation for details).
245 ///
246 /// # JavaScript Examples
247 ///
248 /// ```javascript
249 /// import perspective from "@perspective-dev/client";
250 ///
251 /// const worker = await perspective.worker();
252 /// viewer.load(worker);
253 /// ```
254 ///
255 /// ... or
256 ///
257 /// ```javascript
258 /// const table = await worker.table(data, {name: "superstore"});
259 /// viewer.load(table);
260 /// ```
261 ///
262 /// Complete example:
263 ///
264 /// ```javascript
265 /// const viewer = document.createElement("perspective-viewer");
266 /// const worker = await perspective.worker();
267 ///
268 /// await worker.table("x\n1", {name: "table_one"});
269 /// await viewer.load(worker);
270 /// await viewer.restore({table: "table_one", columns: ["x"]});
271 /// ```
272 ///
273 /// ... or, if you don't want to pass your own arguments to `restore`:
274 ///
275 /// ```javascript
276 /// const viewer = document.createElement("perspective-viewer");
277 /// const worker = await perspective.worker();
278 ///
279 /// const table = await worker.table("x\n1", {name: "table_one"});
280 /// await viewer.load(table);
281 /// ```
282 pub fn load(&self, table: JsValue) -> ApiResult<ApiFuture<()>> {
283 let promise = table
284 .clone()
285 .dyn_into::<js_sys::Promise>()
286 .unwrap_or_else(|_| js_sys::Promise::resolve(&table));
287
288 let _plugin = self.renderer.get_active_plugin()?;
289 let reset_task = self.session.reset(ResetOptions {
290 config: true,
291 expressions: true,
292 stats: true,
293 table: Some(session::TableIntermediateState::Reloaded),
294 });
295
296 clone!(self.renderer, self.session);
297 Ok(ApiFuture::new_throttled(async move {
298 let task = async {
299 // Ignore this error, which is blown away by the table anyway.
300 let _ = reset_task.await;
301 let jstable = JsFuture::from(promise)
302 .await
303 .map_err(|x| apierror!(TableError(x)))?;
304
305 if let Ok(Some(table)) =
306 try_from_js_option::<perspective_js::Table>(jstable.clone())
307 {
308 let client = table.get_client().await;
309 session.set_client(client.get_client().clone());
310 let name = table.get_name().await;
311 tracing::debug!(
312 "Loading {:.0} rows from `Table` {}",
313 table.size().await?,
314 name
315 );
316
317 if session.set_table(name).await? {
318 session.validate().await?.create_view().await?;
319 }
320
321 Ok(session.get_view())
322 } else if let Ok(Some(client)) =
323 wasm_bindgen_derive::try_from_js_option::<perspective_js::Client>(jstable)
324 {
325 session.set_client(client.get_client().clone());
326 Ok(session.get_view())
327 } else {
328 Err(ApiError::new("Invalid argument"))
329 }
330 };
331
332 renderer.set_throttle(None);
333 let result = renderer.draw(task).await;
334 if let Err(e) = &result {
335 session.set_error(false, e.clone()).await?;
336 }
337
338 result
339 }))
340 }
341
342 /// Delete the internal [`View`] and all associated state, rendering this
343 /// `<perspective-viewer>` unusable and freeing all associated resources.
344 /// Does not delete the supplied [`Table`] (as this is constructed by the
345 /// callee).
346 ///
347 /// Calling _any_ method on a `<perspective-viewer>` after [`Self::delete`]
348 /// will throw.
349 ///
350 /// <div class="warning">
351 ///
352 /// Allowing a `<perspective-viewer>` to be garbage-collected
353 /// without calling [`PerspectiveViewerElement::delete`] will leak WASM
354 /// memory!
355 ///
356 /// </div>
357 ///
358 /// # JavaScript Examples
359 ///
360 /// ```javascript
361 /// await viewer.delete();
362 /// ```
363 pub fn delete(self) -> ApiFuture<()> {
364 self.delete_all(&self.root)
365 }
366
367 /// Restart this `<perspective-viewer>` to its initial state, before
368 /// `load()`.
369 ///
370 /// Use `Self::restart` if you plan to call `Self::load` on this viewer
371 /// again, or alternatively `Self::delete` if this viewer is no longer
372 /// needed.
373 pub fn eject(&mut self) -> ApiFuture<()> {
374 if matches!(self.session.has_table(), Some(TableLoadState::Loaded)) {
375 let mut state = Self::new_from_shadow(
376 self.elem.clone(),
377 self.elem.shadow_root().unwrap().unchecked_into(),
378 );
379
380 std::mem::swap(self, &mut state);
381 ApiFuture::new_throttled(state.delete())
382 } else {
383 ApiFuture::new_throttled(async move { Ok(()) })
384 }
385 }
386
387 /// Get the underlying [`View`] for this viewer.
388 ///
389 /// Use this method to get promgrammatic access to the [`View`] as currently
390 /// configured by the user, for e.g. serializing as an
391 /// [Apache Arrow](https://arrow.apache.org/) before passing to another
392 /// library.
393 ///
394 /// The [`View`] returned by this method is owned by the
395 /// [`PerspectiveViewerElement`] and may be _invalidated_ by
396 /// [`View::delete`] at any time. Plugins which rely on this [`View`] for
397 /// their [`HTMLPerspectiveViewerPluginElement::draw`] implementations
398 /// should treat this condition as a _cancellation_ by silently aborting on
399 /// "View already deleted" errors from method calls.
400 ///
401 /// # JavaScript Examples
402 ///
403 /// ```javascript
404 /// const view = await viewer.getView();
405 /// ```
406 #[wasm_bindgen]
407 pub fn getView(&self) -> ApiFuture<View> {
408 let session = self.session.clone();
409 ApiFuture::new(async move { Ok(session.get_view().ok_or("No table set")?.into()) })
410 }
411
412 /// Get a copy of the [`ViewConfig`] for the current [`View`]. This is
413 /// non-blocking as it does not need to access the plugin (unlike
414 /// [`PerspectiveViewerElement::save`]), and also makes no API calls to the
415 /// server (unlike [`PerspectiveViewerElement::getView`] followed by
416 /// [`View::get_config`])
417 #[wasm_bindgen]
418 pub fn getViewConfig(&self) -> ApiFuture<JsViewConfig> {
419 let session = self.session.clone();
420 ApiFuture::new(async move {
421 let config = session.get_view_config();
422 Ok(JsValue::from_serde_ext(&*config)?.unchecked_into())
423 })
424 }
425
426 /// Get the underlying [`Table`] for this viewer (as passed to
427 /// [`PerspectiveViewerElement::load`] or as the `table` field to
428 /// [`PerspectiveViewerElement::restore`]).
429 ///
430 /// # Arguments
431 ///
432 /// - `wait_for_table` - whether to wait for
433 /// [`PerspectiveViewerElement::load`] to be called, or fail immediately
434 /// if [`PerspectiveViewerElement::load`] has not yet been called.
435 ///
436 /// # JavaScript Examples
437 ///
438 /// ```javascript
439 /// const table = await viewer.getTable();
440 /// ```
441 #[wasm_bindgen]
442 pub fn getTable(&self, wait_for_table: Option<bool>) -> ApiFuture<Table> {
443 let session = self.session.clone();
444 ApiFuture::new(async move {
445 match session.get_table() {
446 Some(table) => Ok(table.into()),
447 None if !wait_for_table.unwrap_or_default() => Err("No `Table` set".into()),
448 None => {
449 session.table_loaded.read_next().await?;
450 Ok(session.get_table().ok_or("No `Table` set")?.into())
451 },
452 }
453 })
454 }
455
456 /// Get the underlying [`Client`] for this viewer (as passed to, or
457 /// associated with the [`Table`] passed to,
458 /// [`PerspectiveViewerElement::load`]).
459 ///
460 /// # Arguments
461 ///
462 /// - `wait_for_client` - whether to wait for
463 /// [`PerspectiveViewerElement::load`] to be called, or fail immediately
464 /// if [`PerspectiveViewerElement::load`] has not yet been called.
465 ///
466 /// # JavaScript Examples
467 ///
468 /// ```javascript
469 /// const client = await viewer.getClient();
470 /// ```
471 #[wasm_bindgen]
472 pub fn getClient(&self, wait_for_client: Option<bool>) -> ApiFuture<perspective_js::Client> {
473 let session = self.session.clone();
474 ApiFuture::new(async move {
475 match session.get_client() {
476 Some(client) => Ok(client.into()),
477 None if !wait_for_client.unwrap_or_default() => Err("No `Client` set".into()),
478 None => {
479 session.table_loaded.read_next().await?;
480 Ok(session.get_client().ok_or("No `Client` set")?.into())
481 },
482 }
483 })
484 }
485
486 /// Get render statistics. Some fields of the returned stats object are
487 /// relative to the last time [`PerspectiveViewerElement::getRenderStats`]
488 /// was called, ergo calling this method resets these fields.
489 ///
490 /// # JavaScript Examples
491 ///
492 /// ```javascript
493 /// const {virtual_fps, actual_fps} = await viewer.getRenderStats();
494 /// ```
495 #[wasm_bindgen]
496 pub fn getRenderStats(&self) -> ApiResult<JsValue> {
497 Ok(JsValue::from_serde_ext(
498 &self.renderer.render_timer().get_stats(),
499 )?)
500 }
501
502 /// Flush any pending modifications to this `<perspective-viewer>`. Since
503 /// `<perspective-viewer>`'s API is almost entirely `async`, it may take
504 /// some milliseconds before any user-initiated changes to the [`View`]
505 /// affects the rendered element. If you want to make sure all pending
506 /// actions have been rendered, call and await [`Self::flush`].
507 ///
508 /// [`Self::flush`] will resolve immediately if there is no [`Table`] set.
509 ///
510 /// # JavaScript Examples
511 ///
512 /// In this example, [`Self::restore`] is called without `await`, but the
513 /// eventual render which results from this call can still be awaited by
514 /// immediately awaiting [`Self::flush`] instead.
515 ///
516 /// ```javascript
517 /// viewer.restore(config);
518 /// await viewer.flush();
519 /// ```
520 pub fn flush(&self) -> ApiFuture<()> {
521 clone!(self.renderer);
522 ApiFuture::new_throttled(async move {
523 // We must let two AFs pass to guarantee listeners to the DOM state
524 // have themselves triggered, or else `request_animation_frame`
525 // may finish before a `ResizeObserver` triggered before is
526 // notifiedd.
527 //
528 // https://github.com/w3c/csswg-drafts/issues/9560
529 // https://html.spec.whatwg.org/multipage/webappapis.html#update-the-rendering
530 request_animation_frame().await;
531 request_animation_frame().await;
532 renderer.clone().with_lock(async { Ok(()) }).await?;
533 renderer.with_lock(async { Ok(()) }).await
534 })
535 }
536
537 /// Restores this element from a full/partial
538 /// [`perspective_js::JsViewConfig`] (this element's user-configurable
539 /// state, including the `Table` name).
540 ///
541 /// One of the best ways to use [`Self::restore`] is by first configuring
542 /// a `<perspective-viewer>` as you wish, then using either the `Debug`
543 /// panel or "Copy" -> "config.json" from the toolbar menu to snapshot
544 /// the [`Self::restore`] argument as JSON.
545 ///
546 /// # Arguments
547 ///
548 /// - `update` - The config to restore to, as returned by [`Self::save`] in
549 /// either "json", "string" or "arraybuffer" format.
550 ///
551 /// # JavaScript Examples
552 ///
553 /// Loads a default plugin for the table named `"superstore"`:
554 ///
555 /// ```javascript
556 /// await viewer.restore({table: "superstore"});
557 /// ```
558 ///
559 /// Apply a `group_by` to the same `viewer` element, without
560 /// modifying/resetting other fields - you can omit the `table` field,
561 /// this has already been set once and is not modified:
562 ///
563 /// ```javascript
564 /// await viewer.restore({group_by: ["State"]});
565 /// ```
566 pub fn restore(&self, update: JsValue) -> ApiFuture<()> {
567 let this = self.clone();
568 ApiFuture::new_throttled(async move {
569 let decoded_update = ViewerConfigUpdate::decode(&update)?;
570 tracing::info!("Restoring {}", decoded_update);
571 let root = this.root.clone();
572 let settings = decoded_update.settings.clone();
573 let (sender, receiver) = channel::<()>();
574 root.borrow().as_ref().into_apierror()?.send_message(
575 PerspectiveViewerMsg::ToggleSettingsComplete(settings, sender),
576 );
577
578 let task = if let OptionalUpdate::Update(_) = &decoded_update.table {
579 Some(this.session.reset(ResetOptions {
580 config: true,
581 expressions: true,
582 stats: true,
583 ..ResetOptions::default()
584 }))
585 } else {
586 None
587 };
588
589 let result = this
590 .restore_and_render(decoded_update.clone(), {
591 clone!(this, decoded_update.table);
592 async move {
593 if let OptionalUpdate::Update(name) = table {
594 if let Some(task) = task {
595 task.await?;
596 }
597
598 this.session.set_table(name).await?;
599 this.session
600 .update_column_defaults(&this.renderer.metadata());
601 };
602
603 // Something abnormal in the DOM happened, e.g. the
604 // element was disconnected while rendering.
605 receiver.await.unwrap_or_log();
606 Ok(())
607 }
608 })
609 .await;
610
611 if let Err(e) = &result {
612 this.session().set_error(false, e.clone()).await?;
613 }
614 result
615 })
616 }
617
618 /// If this element is in an _errored_ state, this method will clear it and
619 /// re-render. Calling this method is equivalent to clicking the error reset
620 /// button in the UI.
621 pub fn resetError(&self) -> ApiFuture<()> {
622 ApiFuture::spawn(self.session.reset(ResetOptions::default()));
623 let this = self.clone();
624 ApiFuture::new_throttled(async move {
625 this.update_and_render(ViewConfigUpdate::default())?.await?;
626 Ok(())
627 })
628 }
629
630 /// Save this element's user-configurable state to a serialized state
631 /// object, one which can be restored via the [`Self::restore`] method.
632 ///
633 /// # JavaScript Examples
634 ///
635 /// Get the current `group_by` setting:
636 ///
637 /// ```javascript
638 /// const {group_by} = await viewer.restore();
639 /// ```
640 ///
641 /// Reset workflow attached to an external button `myResetButton`:
642 ///
643 /// ```javascript
644 /// const token = await viewer.save();
645 /// myResetButton.addEventListener("clien", async () => {
646 /// await viewer.restore(token);
647 /// });
648 /// ```
649 pub fn save(&self) -> ApiFuture<JsValue> {
650 let this = self.clone();
651 ApiFuture::new(async move {
652 let viewer_config = this
653 .renderer
654 .clone()
655 .with_lock(async { this.get_viewer_config().await })
656 .await?;
657
658 viewer_config.encode()
659 })
660 }
661
662 /// Download this viewer's internal [`View`] data via a browser download
663 /// event.
664 ///
665 /// # Arguments
666 ///
667 /// - `method` - The `ExportMethod` to use to render the data to download.
668 ///
669 /// # JavaScript Examples
670 ///
671 /// ```javascript
672 /// myDownloadButton.addEventListener("click", async () => {
673 /// await viewer.download();
674 /// })
675 /// ```
676 pub fn download(&self, method: Option<JsString>) -> ApiFuture<()> {
677 let this = self.clone();
678 ApiFuture::new_throttled(async move {
679 let method = if let Some(method) = method
680 .map(|x| x.unchecked_into())
681 .map(serde_wasm_bindgen::from_value)
682 {
683 method?
684 } else {
685 ExportMethod::Csv
686 };
687
688 let blob = this.export_method_to_blob(method).await?;
689 let is_chart = this.renderer.is_chart();
690 download(
691 format!("untitled{}", method.as_filename(is_chart)).as_ref(),
692 &blob,
693 )
694 })
695 }
696
697 /// Exports this viewer's internal [`View`] as a JavaSript data, the
698 /// exact type of which depends on the `method` but defaults to `String`
699 /// in CSV format.
700 ///
701 /// This method is only really useful for the `"plugin"` method, which
702 /// will use the configured plugin's export (e.g. PNG for
703 /// `@perspective-dev/viewer-d3fc`). Otherwise, prefer to call the
704 /// equivalent method on the underlying [`View`] directly.
705 ///
706 /// # Arguments
707 ///
708 /// - `method` - The `ExportMethod` to use to render the data to download.
709 ///
710 /// # JavaScript Examples
711 ///
712 /// ```javascript
713 /// const data = await viewer.export("plugin");
714 /// ```
715 pub fn export(&self, method: Option<JsString>) -> ApiFuture<JsValue> {
716 let this = self.clone();
717 ApiFuture::new(async move {
718 let method = if let Some(method) = method
719 .map(|x| x.unchecked_into())
720 .map(serde_wasm_bindgen::from_value)
721 {
722 method?
723 } else {
724 ExportMethod::Csv
725 };
726
727 this.export_method_to_jsvalue(method).await
728 })
729 }
730
731 /// Copy this viewer's `View` or `Table` data as CSV to the system
732 /// clipboard.
733 ///
734 /// # Arguments
735 ///
736 /// - `method` - The `ExportMethod` (serialized as a `String`) to use to
737 /// render the data to the Clipboard.
738 ///
739 /// # JavaScript Examples
740 ///
741 /// ```javascript
742 /// myDownloadButton.addEventListener("click", async () => {
743 /// await viewer.copy();
744 /// })
745 /// ```
746 pub fn copy(&self, method: Option<JsString>) -> ApiFuture<()> {
747 let this = self.clone();
748 ApiFuture::new_throttled(async move {
749 let method = if let Some(method) = method
750 .map(|x| x.unchecked_into())
751 .map(serde_wasm_bindgen::from_value)
752 {
753 method?
754 } else {
755 ExportMethod::Csv
756 };
757
758 let js_task = this.export_method_to_blob(method);
759 copy_to_clipboard(js_task, MimeType::TextPlain).await
760 })
761 }
762
763 /// Reset the viewer's `ViewerConfig` to the default.
764 ///
765 /// # Arguments
766 ///
767 /// - `reset_all` - If set, will clear expressions and column settings as
768 /// well.
769 ///
770 /// # JavaScript Examples
771 ///
772 /// ```javascript
773 /// await viewer.reset();
774 /// ```
775 pub fn reset(&self, reset_all: Option<bool>) -> ApiFuture<()> {
776 tracing::debug!("Resetting config");
777 let root = self.root.clone();
778 let all = reset_all.unwrap_or_default();
779 ApiFuture::new_throttled(async move {
780 let (sender, receiver) = channel::<()>();
781 root.borrow()
782 .as_ref()
783 .ok_or("Already deleted")?
784 .send_message(PerspectiveViewerMsg::Reset(all, Some(sender)));
785
786 Ok(receiver.await?)
787 })
788 }
789
790 /// Recalculate the viewer's dimensions and redraw.
791 ///
792 /// Use this method to tell `<perspective-viewer>` its dimensions have
793 /// changed when auto-size mode has been disabled via [`Self::setAutoSize`].
794 /// [`Self::resize`] resolves when the resize-initiated redraw of this
795 /// element has completed.
796 ///
797 /// # Arguments
798 ///
799 /// - `options` - An optional object with the following fields:
800 /// - `dimensions` - An optional object `{width, height}` providing
801 /// explicit size hints (in pixels) for the plugin container. When
802 /// provided, the plugin element will be temporarily sized to these
803 /// dimensions during resize, then reset.
804 ///
805 /// # JavaScript Examples
806 ///
807 /// ```javascript
808 /// await viewer.resize()
809 /// await viewer.resize({dimensions: {width: 800, height: 600}})
810 /// ```
811 #[wasm_bindgen]
812 pub fn resize(&self, options: Option<JsValue>) -> ApiFuture<()> {
813 let opts: ResizeOptions = options
814 .map(|v| v.into_serde_ext())
815 .transpose()
816 .unwrap_or_default()
817 .unwrap_or_default();
818
819 let state = self.clone_state();
820 ApiFuture::new_throttled(async move {
821 if !state.renderer().is_plugin_activated()? {
822 state
823 .update_and_render(ViewConfigUpdate::default())?
824 .await?;
825 } else if let Some(dims) = opts.dimensions {
826 state
827 .renderer()
828 .resize_with_dimensions(dims.width, dims.height)
829 .await?;
830 } else {
831 state.renderer().resize().await?;
832 }
833
834 Ok(())
835 })
836 }
837
838 /// Sets the auto-size behavior of this component.
839 ///
840 /// When `true`, this `<perspective-viewer>` will register a
841 /// `ResizeObserver` on itself and call [`Self::resize`] whenever its own
842 /// dimensions change. However, when embedded in a larger application
843 /// context, you may want to call [`Self::resize`] manually to avoid
844 /// over-rendering; in this case auto-sizing can be disabled via this
845 /// method. Auto-size behavior is enabled by default.
846 ///
847 /// # Arguments
848 ///
849 /// - `autosize` - Whether to enable `auto-size` behavior or not.
850 ///
851 /// # JavaScript Examples
852 ///
853 /// Disable auto-size behavior:
854 ///
855 /// ```javascript
856 /// viewer.setAutoSize(false);
857 /// ```
858 #[wasm_bindgen]
859 pub fn setAutoSize(&self, autosize: bool) {
860 if autosize {
861 let handle = Some(ResizeObserverHandle::new(
862 &self.elem,
863 &self.renderer,
864 &self.session,
865 &self.presentation,
866 &self.root,
867 ));
868 *self.resize_handle.borrow_mut() = handle;
869 } else {
870 *self.resize_handle.borrow_mut() = None;
871 }
872 }
873
874 /// Sets the auto-pause behavior of this component.
875 ///
876 /// When `true`, this `<perspective-viewer>` will register an
877 /// `IntersectionObserver` on itself and subsequently skip rendering
878 /// whenever its viewport visibility changes. Auto-pause is enabled by
879 /// default.
880 ///
881 /// # Arguments
882 ///
883 /// - `autopause` Whether to enable `auto-pause` behavior or not.
884 ///
885 /// # JavaScript Examples
886 ///
887 /// Disable auto-size behavior:
888 ///
889 /// ```javascript
890 /// viewer.setAutoPause(false);
891 /// ```
892 #[wasm_bindgen]
893 pub fn setAutoPause(&self, autopause: bool) -> ApiFuture<()> {
894 if autopause {
895 let handle = Some(IntersectionObserverHandle::new(
896 &self.elem,
897 &self.presentation,
898 &self.session,
899 &self.renderer,
900 ));
901
902 *self.intersection_handle.borrow_mut() = handle;
903 } else {
904 *self.intersection_handle.borrow_mut() = None;
905 if self.session.set_pause(false) {
906 return ApiFuture::new(
907 self.restore_and_render(ViewerConfigUpdate::default(), async move { Ok(()) }),
908 );
909 }
910 }
911
912 ApiFuture::new(async move { Ok(()) })
913 }
914
915 /// Return a [`perspective_js::JsViewWindow`] for the currently selected
916 /// region.
917 #[wasm_bindgen]
918 pub fn getSelection(&self) -> Option<JsViewWindow> {
919 self.renderer.get_selection().map(|x| x.into())
920 }
921
922 /// Set the selection [`perspective_js::JsViewWindow`] for this element.
923 #[wasm_bindgen]
924 pub fn setSelection(&self, window: Option<JsViewWindow>) -> ApiResult<()> {
925 let window = window.map(|x| x.into_serde_ext()).transpose()?;
926 if self.renderer.get_selection() != window {
927 self.custom_events.dispatch_select(window.as_ref())?;
928 }
929
930 self.renderer.set_selection(window);
931 Ok(())
932 }
933
934 /// Get this viewer's edit port for the currently loaded [`Table`] (see
935 /// [`Table::update`] for details on ports).
936 #[wasm_bindgen]
937 pub fn getEditPort(&self) -> Result<f64, JsValue> {
938 self.session
939 .metadata()
940 .get_edit_port()
941 .ok_or_else(|| "No `Table` loaded".into())
942 }
943
944 /// Restyle all plugins from current document.
945 ///
946 /// <div class="warning">
947 ///
948 /// [`Self::restyleElement`] _must_ be called for many runtime changes to
949 /// CSS properties to be reflected in an already-rendered
950 /// `<perspective-viewer>`.
951 ///
952 /// </div>
953 ///
954 /// # JavaScript Examples
955 ///
956 /// ```javascript
957 /// viewer.style = "--psp--color: red";
958 /// await viewer.restyleElement();
959 /// ```
960 #[wasm_bindgen]
961 pub fn restyleElement(&self) -> ApiFuture<JsValue> {
962 clone!(self.renderer, self.session);
963 ApiFuture::new(async move {
964 let view = session.get_view().into_apierror()?;
965 renderer.restyle_all(&view).await
966 })
967 }
968
969 /// Set the available theme names available in the status bar UI.
970 ///
971 /// Calling [`Self::resetThemes`] may cause the current theme to switch,
972 /// if e.g. the new theme set does not contain the current theme.
973 ///
974 /// # JavaScript Examples
975 ///
976 /// Restrict `<perspective-viewer>` theme options to _only_ default light
977 /// and dark themes, regardless of what is auto-detected from the page's
978 /// CSS:
979 ///
980 /// ```javascript
981 /// viewer.resetThemes(["Pro Light", "Pro Dark"])
982 /// ```
983 #[wasm_bindgen]
984 pub fn resetThemes(&self, themes: Option<Box<[JsValue]>>) -> ApiFuture<JsValue> {
985 clone!(self.renderer, self.session, self.presentation);
986 ApiFuture::new(async move {
987 let themes: Option<Vec<String>> = themes
988 .unwrap_or_default()
989 .iter()
990 .map(|x| x.as_string())
991 .collect();
992
993 let theme_name = presentation.get_selected_theme_name().await;
994 let mut changed = presentation.reset_available_themes(themes).await;
995 let reset_theme = presentation
996 .get_available_themes()
997 .await?
998 .iter()
999 .find(|y| theme_name.as_ref() == Some(y))
1000 .cloned();
1001
1002 changed = presentation.set_theme_name(reset_theme.as_deref()).await? || changed;
1003 if changed && let Some(view) = session.get_view() {
1004 return renderer.restyle_all(&view).await;
1005 }
1006
1007 Ok(JsValue::UNDEFINED)
1008 })
1009 }
1010
1011 /// Determines the render throttling behavior. Can be an integer, for
1012 /// millisecond window to throttle render event; or, if `None`, adaptive
1013 /// throttling will be calculated from the measured render time of the
1014 /// last 5 frames.
1015 ///
1016 /// # Arguments
1017 ///
1018 /// - `throttle` - The throttle rate in milliseconds (f64), or `None` for
1019 /// adaptive throttling.
1020 ///
1021 /// # JavaScript Examples
1022 ///
1023 /// Only draws at most 1 frame/sec:
1024 ///
1025 /// ```rust
1026 /// viewer.setThrottle(1000);
1027 /// ```
1028 #[wasm_bindgen]
1029 pub fn setThrottle(&self, val: Option<f64>) {
1030 self.renderer.set_throttle(val);
1031 }
1032
1033 /// Toggle (or force) the config panel open/closed.
1034 ///
1035 /// # Arguments
1036 ///
1037 /// - `force` - Force the state of the panel open or closed, or `None` to
1038 /// toggle.
1039 ///
1040 /// # JavaScript Examples
1041 ///
1042 /// ```javascript
1043 /// await viewer.toggleConfig();
1044 /// ```
1045 #[wasm_bindgen]
1046 pub fn toggleConfig(&self, force: Option<bool>) -> ApiFuture<JsValue> {
1047 let root = self.root.clone();
1048 ApiFuture::new(async move {
1049 let force = force.map(SettingsUpdate::Update);
1050 let (sender, receiver) = channel::<ApiResult<wasm_bindgen::JsValue>>();
1051 root.borrow().as_ref().into_apierror()?.send_message(
1052 PerspectiveViewerMsg::ToggleSettingsInit(force, Some(sender)),
1053 );
1054
1055 receiver.await.map_err(|_| JsValue::from("Cancelled"))?
1056 })
1057 }
1058
1059 /// Get an `Array` of all of the plugin custom elements registered for this
1060 /// element. This may not include plugins which called
1061 /// [`registerPlugin`] after the host has rendered for the first time.
1062 #[wasm_bindgen]
1063 pub fn getAllPlugins(&self) -> Array {
1064 self.renderer.get_all_plugins().iter().collect::<Array>()
1065 }
1066
1067 /// Gets a plugin Custom Element with the `name` field, or get the active
1068 /// plugin if no `name` is provided.
1069 ///
1070 /// # Arguments
1071 ///
1072 /// - `name` - The `name` property of a perspective plugin Custom Element,
1073 /// or `None` for the active plugin's Custom Element.
1074 #[wasm_bindgen]
1075 pub fn getPlugin(&self, name: Option<String>) -> ApiResult<JsPerspectiveViewerPlugin> {
1076 match name {
1077 None => self.renderer.get_active_plugin(),
1078 Some(name) => self.renderer.get_plugin(&name),
1079 }
1080 }
1081
1082 /// Create a new JavaScript Heap reference for this model instance.
1083 #[doc(hidden)]
1084 #[allow(clippy::use_self)]
1085 #[wasm_bindgen]
1086 pub fn __get_model(&self) -> PerspectiveViewerElement {
1087 self.clone()
1088 }
1089
1090 /// Asynchronously opens the column settings for a specific column.
1091 /// When finished, the `<perspective-viewer>` element will emit a
1092 /// "perspective-toggle-column-settings" CustomEvent.
1093 /// The event's details property has two fields: `{open: bool, column_name?:
1094 /// string}`. The CustomEvent is also fired whenever the user toggles the
1095 /// sidebar manually.
1096 #[wasm_bindgen]
1097 pub fn toggleColumnSettings(&self, column_name: String) -> ApiFuture<()> {
1098 clone!(self.session, self.root);
1099 ApiFuture::new_throttled(async move {
1100 let locator = session.get_column_locator(Some(column_name));
1101 let (sender, receiver) = channel::<()>();
1102 root.borrow().as_ref().into_apierror()?.send_message(
1103 PerspectiveViewerMsg::OpenColumnSettings {
1104 locator,
1105 sender: Some(sender),
1106 toggle: true,
1107 },
1108 );
1109
1110 receiver.await.map_err(|_| ApiError::from("Cancelled"))
1111 })
1112 }
1113
1114 /// Force open the settings for a particular column. Pass `null` to close
1115 /// the column settings panel. See [`Self::toggleColumnSettings`] for more.
1116 #[wasm_bindgen]
1117 pub fn openColumnSettings(
1118 &self,
1119 column_name: Option<String>,
1120 toggle: Option<bool>,
1121 ) -> ApiFuture<()> {
1122 let locator = self.get_column_locator(column_name);
1123 clone!(self.root);
1124 ApiFuture::new_throttled(async move {
1125 let (sender, receiver) = channel::<()>();
1126 root.borrow().as_ref().into_apierror()?.send_message(
1127 PerspectiveViewerMsg::OpenColumnSettings {
1128 locator,
1129 sender: Some(sender),
1130 toggle: toggle.unwrap_or_default(),
1131 },
1132 );
1133
1134 receiver.await.map_err(|_| ApiError::from("Cancelled"))
1135 })
1136 }
1137}