Skip to main content

perspective_viewer/
lib.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//! The API for the [`@perspective-dev/viewer`](https://perspective-dev.github.io)
14//! JavaScript library.
15
16// Required by yew's `html` macro.
17#![recursion_limit = "1024"]
18#![feature(const_type_name)]
19#![feature(iter_intersperse)]
20#![feature(stmt_expr_attributes)]
21#![feature(try_blocks)]
22#![allow(async_fn_in_trait)]
23#![warn(
24    clippy::all,
25    clippy::panic_in_result_fn,
26    clippy::fallible_impl_from,
27    clippy::unneeded_field_pattern
28)]
29#![deny(clippy::await_holding_refcell_ref)]
30
31#[cfg(feature = "llm-agent")]
32mod agent;
33pub mod components;
34pub mod config;
35pub mod custom_elements;
36mod custom_events;
37mod derived;
38pub mod exprtk;
39mod js;
40mod presentation;
41mod root;
42
43#[doc(hidden)]
44pub mod queries;
45mod renderer;
46mod session;
47
48#[doc(hidden)]
49pub mod tasks;
50pub mod ui;
51pub mod utils;
52mod workspace;
53
54#[macro_use]
55extern crate macro_rules_attribute;
56extern crate alloc;
57
58use std::cell::RefCell;
59
60use perspective_js::utils::*;
61use wasm_bindgen::prelude::*;
62
63use crate::custom_elements::debug_plugin::PerspectiveDebugPluginElement;
64use crate::custom_elements::viewer::PerspectiveViewerElement;
65use crate::utils::define_web_component;
66
67#[wasm_bindgen(typescript_custom_section)]
68const TS_APPEND_CONTENT: &'static str = r#"
69import type {
70    ColumnType,
71    ColumnWindow,
72    DeleteOptions,
73    Features,
74    JoinOptions,
75    OnRemoveData,
76    OnUpdateData,
77    OnUpdateOptions,
78    Scalar,
79    SystemInfo,
80    TableInitOptions,
81    TypedArrayWindow,
82    UpdateOptions,
83    ViewConfig,
84    ViewConfigUpdate,
85    ViewWindow,
86} from "@perspective-dev/client";
87
88export type * from "../ts-rs/ViewerConfig.d.ts";
89export type * from "../ts-rs/ViewerConfigUpdate.d.ts";
90export type * from "../ts-rs/ViewerConfigInitial.d.ts";
91export type * from "../ts-rs/PluginStaticConfig.d.ts";
92export type * from "../ts-rs/WorkspaceConfig.d.ts";
93export type * from "../ts-rs/TableRef.d.ts";
94export type * from "../ts-rs/DerivedTableConfig.d.ts";
95export type * from "../ts-rs/WorkspaceConfigUpdate.d.ts";
96export type * from "../ts-rs/ExportMethod.d.ts";
97export type * from "../ts-rs/PanelOptions.d.ts";
98export type * from "../ts-rs/RestoreOptions.d.ts";
99export type * from "../ts-rs/RestoreWorkspaceOptions.d.ts";
100export type * from "../ts-rs/AddPanelOptions.d.ts";
101export type * from "../ts-rs/SaveWorkspaceOptions.d.ts";
102export type * from "../ts-rs/ClientOptions.d.ts";
103export type * from "../ts-rs/ExportOptions.d.ts";
104export type * from "../ts-rs/GetTableOptions.d.ts";
105export type * from "../ts-rs/GetClientOptions.d.ts";
106export type * from "../ts-rs/GetViewOptions.d.ts";
107export type * from "../ts-rs/GetViewMode.d.ts";
108export type * from "../ts-rs/CustomNumberFormatConfig.d.ts";
109export type * from "../ts-rs/NumberFormatStyle.d.ts";
110export type * from "../ts-rs/Notation.d.ts";
111export type * from "../ts-rs/DatetimeFormat.d.ts";
112export type * from "../ts-rs/ConfigDefaultsOptions.d.ts";
113export type * from "../ts-rs/ColumnConfigDefaultsOptions.d.ts";
114export type * from "../ts-rs/CommandSchema.d.ts";
115export type * from "../ts-rs/CommandSpec.d.ts";
116export type * from "../ts-rs/CommandLocation.d.ts";
117export type * from "../ts-rs/CommandSchemaOptions.d.ts";
118export type * from "../ts-rs/PerspectiveHit.d.ts";
119export type * from "../ts-rs/PerspectiveHitRef.d.ts";
120
121export type ExportData =
122    | string
123    | ArrayBuffer
124    | Blob
125    | Record<string, unknown[]>
126    | ViewerConfig;
127
128import type {GetTableOptions} from "../ts-rs/GetTableOptions.d.ts";
129import type {PanelOptions} from "../ts-rs/PanelOptions.d.ts";
130import type {RestoreOptions} from "../ts-rs/RestoreOptions.d.ts";
131import type {RestoreWorkspaceOptions} from "../ts-rs/RestoreWorkspaceOptions.d.ts";
132import type {AddPanelOptions} from "../ts-rs/AddPanelOptions.d.ts";
133import type {SaveWorkspaceOptions} from "../ts-rs/SaveWorkspaceOptions.d.ts";
134import type {ConfigDefaultsOptions} from "../ts-rs/ConfigDefaultsOptions.d.ts";
135import type {ColumnConfigDefaultsOptions} from "../ts-rs/ColumnConfigDefaultsOptions.d.ts";
136import type {ExportOptions} from "../ts-rs/ExportOptions.d.ts";
137import type {GetClientOptions} from "../ts-rs/GetClientOptions.d.ts";
138import type {GetViewOptions} from "../ts-rs/GetViewOptions.d.ts";
139import type {ClientOptions} from "../ts-rs/ClientOptions.d.ts";
140import type {ViewerConfig} from "../ts-rs/ViewerConfig.d.ts";
141import type {ViewerConfigUpdate} from "../ts-rs/ViewerConfigUpdate.d.ts";
142import type {ViewerConfigInitial} from "../ts-rs/ViewerConfigInitial.d.ts";
143import type {WorkspaceConfig} from "../ts-rs/WorkspaceConfig.d.ts";
144import type {WorkspaceConfigUpdate} from "../ts-rs/WorkspaceConfigUpdate.d.ts";
145import type {CommandSchema} from "../ts-rs/CommandSchema.d.ts";
146import type {CommandSpec} from "../ts-rs/CommandSpec.d.ts";
147import type {CommandLocation} from "../ts-rs/CommandLocation.d.ts";
148import type {CommandSchemaOptions} from "../ts-rs/CommandSchemaOptions.d.ts";
149import type {PerspectiveHit} from "../ts-rs/PerspectiveHit.d.ts";
150import type {PerspectiveHitRef} from "../ts-rs/PerspectiveHitRef.d.ts";
151
152/** A surface a command schema is evaluated for. */
153export type PerspectiveCommandLocation = CommandLocation;
154
155/**
156 * A window of a plugin's viewport, in the shape of the parsed
157 * `to_columns_string({ id: true })` result and the `column_paths()` area.
158 */
159export interface PerspectiveViewFrame {
160    /** The view row index of `data`'s first entry. */
161    start_row: number;
162
163    /** The view column index of `paths[0]`. */
164    start_col: number;
165
166    /** The `data` key of each column from `start_col`. */
167    paths: string[];
168
169    /** One level per `split_by` plus the column name, each over `paths`. */
170    column_paths: Scalar[][];
171
172    /** Columns keyed by path, with `__ROW_PATH__` and `__ID__` when present. */
173    data: Record<string, unknown[]>;
174}
175
176/** What a plugin rendered at a viewport point, before the viewer resolves it. */
177export interface PerspectiveHitTest {
178    frame: PerspectiveViewFrame;
179    ref: PerspectiveHitRef;
180}
181
182/** One `queryCommands()` result: the context the schema saw and what it returned. */
183export interface PerspectiveCommands {
184    context: PerspectiveCommandContext;
185    commands: CommandSpec[];
186}
187
188/** What a command schema is evaluated against. */
189export interface PerspectiveCommandContext {
190    location: PerspectiveCommandLocation;
191
192    /** The targeted panel, absent only at zero panels. */
193    panel?: string;
194
195    /** The name of the panel's `Table`. */
196    table?: string;
197
198    /** The name of the panel's plugin. */
199    plugin?: string;
200
201    /** The panel's view config, as `getViewConfig()` reports it. */
202    view_config?: ViewConfig;
203
204    /** Viewport coordinates of the pointer that initiated the command, for the context menu. */
205    point?: { x: number; y: number };
206
207    /** What the plugin rendered at the location, absent over tabs and chrome. */
208    hit?: PerspectiveHit;
209}
210
211/** A synchronous, effect-free function declaring the commands for a context. */
212export type PerspectiveCommandSchema = (
213    context: PerspectiveCommandContext,
214) => CommandSchema;
215
216/** The `detail` of a `perspective-command` event. */
217export interface PerspectiveCommandEventDetail {
218    key: string;
219    context: PerspectiveCommandContext;
220}
221"#;
222
223/// Register a plugin globally.
224#[wasm_bindgen]
225#[allow(non_snake_case)]
226pub fn registerPlugin(name: &str) {
227    use crate::renderer::*;
228    PLUGIN_REGISTRY.register_plugin(name);
229}
230
231#[wasm_bindgen]
232extern "C" {
233    #[wasm_bindgen(typescript_type = "Record<string, unknown> | null")]
234    pub type JsConfigDefaults;
235
236    #[wasm_bindgen(typescript_type = "ConfigDefaultsOptions")]
237    pub type JsConfigDefaultsOptions;
238
239    #[wasm_bindgen(typescript_type = "ColumnConfigDefaultsOptions")]
240    pub type JsColumnConfigDefaultsOptions;
241
242    #[wasm_bindgen(
243        typescript_type = "Array<{ plugin?: string; defaults: Record<string, unknown> }>"
244    )]
245    pub type JsPluginConfigDefaultsSlots;
246
247    #[wasm_bindgen(
248        typescript_type = "Array<{ plugin?: string; type?: ColumnType; defaults: Record<string, \
249                           unknown> }>"
250    )]
251    pub type JsColumnConfigDefaultsSlots;
252}
253
254fn defaults_options<T: Default + serde::de::DeserializeOwned>(
255    options: Option<impl Into<JsValue>>,
256) -> ApiResult<T> {
257    match options {
258        None => Ok(T::default()),
259        Some(options) => Ok(options.into().into_serde_ext()?),
260    }
261}
262
263/// Merge `defaults` into the `plugin_config` defaults every
264/// `<perspective-viewer>` on the page applies, where a `null` value removes a
265/// default and a `null` `defaults` clears the slot.
266///
267/// # Arguments
268///
269/// - `defaults` - Values keyed like `plugin_config`, or `null`.
270/// - `options.plugin` - Limits the defaults to the named plugin.
271///
272/// # JavaScript Examples
273///
274/// ```javascript
275/// customElements.get("perspective-viewer").setPluginConfigDefaults({group_pad: 10});
276/// ```
277#[wasm_bindgen]
278#[allow(non_snake_case)]
279pub fn setPluginConfigDefaults(
280    defaults: JsConfigDefaults,
281    options: Option<JsConfigDefaultsOptions>,
282) -> ApiResult<()> {
283    let config::ConfigDefaultsOptions { plugin } = defaults_options(options)?;
284    renderer::set_plugin_config_defaults(&defaults, plugin.as_deref())
285}
286
287/// Merge `defaults` into the `columns_config` defaults every
288/// `<perspective-viewer>` on the page applies, where a `null` value removes a
289/// default and a `null` `defaults` clears the slot.
290///
291/// # Arguments
292///
293/// - `defaults` - Values keyed like one `columns_config` entry, or `null`.
294/// - `options.plugin` - Limits the defaults to the named plugin.
295/// - `options.type` - Limits the defaults to columns of this view type.
296///
297/// # JavaScript Examples
298///
299/// ```javascript
300/// customElements
301///     .get("perspective-viewer")
302///     .setColumnConfigDefaults({date_format: {timeZone: "UTC"}}, {type: "datetime"});
303/// ```
304#[wasm_bindgen]
305#[allow(non_snake_case)]
306pub fn setColumnConfigDefaults(
307    defaults: JsConfigDefaults,
308    options: Option<JsColumnConfigDefaultsOptions>,
309) -> ApiResult<()> {
310    let config::ColumnConfigDefaultsOptions { plugin, ty } = defaults_options(options)?;
311    renderer::set_column_config_defaults(&defaults, plugin.as_deref(), ty.as_deref())
312}
313
314/// The `plugin_config` defaults set by [`setPluginConfigDefaults`], one entry
315/// per slot.
316#[wasm_bindgen]
317#[allow(non_snake_case)]
318pub fn getPluginConfigDefaults() -> ApiResult<JsPluginConfigDefaultsSlots> {
319    Ok(renderer::get_plugin_config_defaults()?.unchecked_into())
320}
321
322/// The `columns_config` defaults set by [`setColumnConfigDefaults`], one entry
323/// per slot.
324#[wasm_bindgen]
325#[allow(non_snake_case)]
326pub fn getColumnConfigDefaults() -> ApiResult<JsColumnConfigDefaultsSlots> {
327    Ok(renderer::get_column_config_defaults()?.unchecked_into())
328}
329
330/// Register this crate's Custom Elements in the browser's current session.
331///
332/// This must occur before calling any public API methods on these Custom
333/// Elements from JavaScript, as the methods themselves won't be defined yet.
334/// By default, this crate does not register `PerspectiveViewerElement` (as to
335/// preserve backwards-compatible synchronous API).
336#[cfg(not(feature = "external-bootstrap"))]
337#[wasm_bindgen(js_name = "init")]
338pub fn js_init(module: js_sys::WebAssembly::Module, url: web_sys::Url) {
339    console_error_panic_hook::set_once();
340    perspective_js::utils::set_global_logging();
341    define_web_components!("export * as psp from '../../perspective-viewer.js'");
342    MODULE.with_borrow_mut(|f| {
343        *f = Some((module, url));
344    });
345
346    tracing::info!("Perspective initialized.");
347}
348
349thread_local! {
350    static MODULE: RefCell<Option<(js_sys::WebAssembly::Module, web_sys::Url)>> = RefCell::default();
351}
352
353#[cfg(not(feature = "external-bootstrap"))]
354#[wasm_bindgen(js_name = "get_wasm_module")]
355pub fn js_get_module() -> Result<js_sys::WebAssembly::Module, JsValue> {
356    MODULE
357        .with_borrow(|f| f.clone().map(|x| x.0))
358        .ok_or_else(|| "Uninited module".into())
359}
360
361#[cfg(not(feature = "external-bootstrap"))]
362#[wasm_bindgen(js_name = "get_worker_url")]
363pub fn js_get_worker_url() -> Result<web_sys::Url, JsValue> {
364    MODULE
365        .with_borrow(|f| f.clone().map(|x| x.1))
366        .ok_or_else(|| "Uninited module".into())
367}
368
369/// Register Web Components with the global registry, given a Perspective
370/// module.
371///
372/// This function shouldn't be called directly;  instead, use the
373/// `define_web_components!` macro to both call this method and hook the
374/// wasm_bindgen module object.
375pub fn bootstrap_web_components(psp: &JsValue) {
376    define_web_component::<PerspectiveViewerElement>(psp);
377    define_web_component::<PerspectiveDebugPluginElement>(psp);
378}
379
380/// Defining the web components needs an extern struct to reference the
381/// generated JavaSript glue. This is parameterized by an attribute macro which
382/// needs to be determined by the top-level compiled module - the JavaScript
383/// glue code emitted by `wasm-bindgen-cli`.
384#[macro_export]
385macro_rules! define_web_components {
386    ($x:expr) => {{
387        #[wasm_bindgen::prelude::wasm_bindgen(inline_js = $x)]
388        extern "C" {
389            #[wasm_bindgen::prelude::wasm_bindgen(js_name = "psp")]
390            #[wasm_bindgen::prelude::wasm_bindgen(thread_local_v2)]
391            pub static PSP: wasm_bindgen::prelude::JsValue;
392        }
393
394        PSP.with(|x| $crate::bootstrap_web_components(x));
395    }};
396}