perspective-viewer 5.10.0

The `<perspective-viewer>` Custom Element: a WebAssembly data grid, pivot table and charting UI for large, real-time and streaming datasets.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
// ┃ ██████ ██████ ██████       █      █      █      █      █ █▄  ▀███ █       ┃
// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█  ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄  ▀█ █ ▀▀▀▀▀ ┃
// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄   █ ▄▄▄▄▄ ┃
// ┃ █      ██████ █  ▀█▄       █ ██████      █      ███▌▐███ ███████▄ █       ┃
// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
// ┃ Copyright (c) 2017, the Perspective Authors.                              ┃
// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
// ┃ This file is part of the Perspective library, distributed under the terms ┃
// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃
// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

//! The API for the [`@perspective-dev/viewer`](https://perspective-dev.github.io)
//! JavaScript library.

// Required by yew's `html` macro.
#![recursion_limit = "1024"]
#![feature(const_type_name)]
#![feature(iter_intersperse)]
#![feature(stmt_expr_attributes)]
#![feature(try_blocks)]
#![allow(async_fn_in_trait)]
#![warn(
    clippy::all,
    clippy::panic_in_result_fn,
    clippy::fallible_impl_from,
    clippy::unneeded_field_pattern
)]
#![deny(clippy::await_holding_refcell_ref)]

#[cfg(feature = "llm-agent")]
mod agent;
pub mod components;
pub mod config;
pub mod custom_elements;
mod custom_events;
mod derived;
pub mod exprtk;
mod format;
mod js;
mod plugin_utils;
mod presentation;
mod root;

#[doc(hidden)]
pub mod queries;
mod renderer;
mod session;

#[doc(hidden)]
pub mod tasks;
pub mod ui;
pub mod utils;
mod workspace;

use std::cell::RefCell;

use perspective_js::utils::*;
use wasm_bindgen::prelude::*;

use crate::custom_elements::debug_plugin::PerspectiveDebugPluginElement;
use crate::custom_elements::viewer::PerspectiveViewerElement;
use crate::utils::define_web_component;

#[wasm_bindgen(typescript_custom_section)]
const TS_APPEND_CONTENT: &'static str = r#"
import type {
    ColumnType,
    ColumnWindow,
    DeleteOptions,
    Features,
    JoinOptions,
    OnRemoveData,
    OnUpdateData,
    OnUpdateOptions,
    Scalar,
    SystemInfo,
    TableInitOptions,
    TypedArrayWindow,
    UpdateOptions,
    ViewConfig,
    ViewConfigUpdate,
    ViewWindow,
} from "@perspective-dev/client";

export type * from "../ts-rs/ViewerConfig.d.ts";
export type * from "../ts-rs/ViewerConfigUpdate.d.ts";
export type * from "../ts-rs/ViewerConfigInitial.d.ts";
export type * from "../ts-rs/PluginStaticConfig.d.ts";
export type * from "../ts-rs/WorkspaceConfig.d.ts";
export type * from "../ts-rs/TableRef.d.ts";
export type * from "../ts-rs/DerivedTableConfig.d.ts";
export type * from "../ts-rs/WorkspaceConfigUpdate.d.ts";
export type * from "../ts-rs/ExportMethod.d.ts";
export type * from "../ts-rs/PanelOptions.d.ts";
export type * from "../ts-rs/RestoreOptions.d.ts";
export type * from "../ts-rs/RestoreWorkspaceOptions.d.ts";
export type * from "../ts-rs/AddPanelOptions.d.ts";
export type * from "../ts-rs/SaveWorkspaceOptions.d.ts";
export type * from "../ts-rs/ClientOptions.d.ts";
export type * from "../ts-rs/ExportOptions.d.ts";
export type * from "../ts-rs/GetTableOptions.d.ts";
export type * from "../ts-rs/GetClientOptions.d.ts";
export type * from "../ts-rs/GetViewOptions.d.ts";
export type * from "../ts-rs/GetViewMode.d.ts";
export type * from "../ts-rs/CustomNumberFormatConfig.d.ts";
export type * from "../ts-rs/NumberFormatStyle.d.ts";
export type * from "../ts-rs/Notation.d.ts";
export type * from "../ts-rs/DatetimeFormat.d.ts";
export type * from "../ts-rs/ConfigDefaultsOptions.d.ts";
export type * from "../ts-rs/ColumnConfigDefaultsOptions.d.ts";
export type * from "../ts-rs/CommandSchema.d.ts";
export type * from "../ts-rs/CommandSpec.d.ts";
export type * from "../ts-rs/CommandLocation.d.ts";
export type * from "../ts-rs/CommandSchemaOptions.d.ts";
export type * from "../ts-rs/PerspectiveHit.d.ts";
export type * from "../ts-rs/PerspectiveHitRef.d.ts";

export type ExportData =
    | string
    | ArrayBuffer
    | Blob
    | Record<string, unknown[]>
    | ViewerConfig;

import type {CustomNumberFormatConfig} from "../ts-rs/CustomNumberFormatConfig.d.ts";
import type {NumberFormatStyle} from "../ts-rs/NumberFormatStyle.d.ts";
import type {Notation} from "../ts-rs/Notation.d.ts";
import type {DatetimeFormat} from "../ts-rs/DatetimeFormat.d.ts";
import type {GetTableOptions} from "../ts-rs/GetTableOptions.d.ts";
import type {PanelOptions} from "../ts-rs/PanelOptions.d.ts";
import type {RestoreOptions} from "../ts-rs/RestoreOptions.d.ts";
import type {RestoreWorkspaceOptions} from "../ts-rs/RestoreWorkspaceOptions.d.ts";
import type {AddPanelOptions} from "../ts-rs/AddPanelOptions.d.ts";
import type {SaveWorkspaceOptions} from "../ts-rs/SaveWorkspaceOptions.d.ts";
import type {ConfigDefaultsOptions} from "../ts-rs/ConfigDefaultsOptions.d.ts";
import type {ColumnConfigDefaultsOptions} from "../ts-rs/ColumnConfigDefaultsOptions.d.ts";
import type {ExportOptions} from "../ts-rs/ExportOptions.d.ts";
import type {GetClientOptions} from "../ts-rs/GetClientOptions.d.ts";
import type {GetViewOptions} from "../ts-rs/GetViewOptions.d.ts";
import type {ClientOptions} from "../ts-rs/ClientOptions.d.ts";
import type {ViewerConfig} from "../ts-rs/ViewerConfig.d.ts";
import type {ViewerConfigUpdate} from "../ts-rs/ViewerConfigUpdate.d.ts";
import type {ViewerConfigInitial} from "../ts-rs/ViewerConfigInitial.d.ts";
import type {WorkspaceConfig} from "../ts-rs/WorkspaceConfig.d.ts";
import type {WorkspaceConfigUpdate} from "../ts-rs/WorkspaceConfigUpdate.d.ts";
import type {CommandSchema} from "../ts-rs/CommandSchema.d.ts";
import type {CommandSpec} from "../ts-rs/CommandSpec.d.ts";
import type {CommandLocation} from "../ts-rs/CommandLocation.d.ts";
import type {CommandSchemaOptions} from "../ts-rs/CommandSchemaOptions.d.ts";
import type {PerspectiveHit} from "../ts-rs/PerspectiveHit.d.ts";
import type {PerspectiveHitRef} from "../ts-rs/PerspectiveHitRef.d.ts";

/** A column of formatted values: one string and the UTF-16 end offset of each value in it. */
export interface FormattedColumn {
    text: string;
    ends: Uint32Array;
}

/**
 * A numeric column's `number_format`, as the Style tab writes it: the ts-rs
 * `CustomNumberFormatConfig` with its flattened `style` and `notation`
 * families, which ts-rs cannot flatten and exports separately.
 */
export type NumberFormatConfig = CustomNumberFormatConfig &
    Partial<NumberFormatStyle> &
    Partial<Notation>;

/** A datetime column's `date_format`, a subset of `Intl.DateTimeFormatOptions`. */
export type DateFormatConfig = DatetimeFormat;

/** The `date_format` options that apply individually rather than as one group. */
export type DateFormatModifiers = Pick<DateFormatConfig, "timeZone" | "hour12">;

/**
 * A formatter for the values of a column of `column_type`, or `undefined` for
 * a type whose values are not formatted, given the column's `number_format`
 * or `date_format` and the calling plugin's default for the same key.
 *
 * @example
 * ```javascript
 * const formatter = viewer.plugin_utils.formatter("float", { style: "percent" });
 * console.log(formatter.format(0.25));
 * ```
 */
export function formatter(
    column_type: ColumnType,
    format?: NumberFormatConfig | DateFormatConfig,
    defaults?: NumberFormatConfig | DateFormatConfig,
): Formatter | undefined;

/**
 * Whether the `date_format` `format` sets any of the keys that apply as one
 * group (a preset or any date or time part), rather than only `timeZone` or
 * `hour12`.
 */
export function has_date_format_shape(format?: DateFormatConfig): boolean;

/**
 * The keys of the `date_format` `format` that apply individually, `timeZone`
 * and `hour12`, or `undefined` when it sets neither.
 */
export function date_format_modifiers(
    format?: DateFormatConfig,
): DateFormatModifiers | undefined;

/** A color's red, green and blue channels, each in `[0, 255]`. */
export type RGB = [number, number, number];

/** One stop of a color scale: a color at `offset` in `[0, 1]`. */
export interface GradientStopRgb {
    rgb: RGB;
    offset: number;
}

/** A surface a command schema is evaluated for. */
export type PerspectiveCommandLocation = CommandLocation;

/**
 * A window of a plugin's viewport, in the shape of the parsed
 * `to_columns_string({ id: true })` result and the `column_paths()` area.
 */
export interface PerspectiveViewFrame {
    /** The view row index of `data`'s first entry. */
    start_row: number;

    /** The view column index of `paths[0]`. */
    start_col: number;

    /** The `data` key of each column from `start_col`. */
    paths: string[];

    /** One level per `split_by` plus the column name, each over `paths`. */
    column_paths: Scalar[][];

    /** Columns keyed by path, with `__ROW_PATH__` and `__ID__` when present. */
    data: Record<string, unknown[]>;
}

/** What a plugin rendered at a viewport point, before the viewer resolves it. */
export interface PerspectiveHitTest {
    frame: PerspectiveViewFrame;
    ref: PerspectiveHitRef;
}

/** One `queryCommands()` result: the context the schema saw and what it returned. */
export interface PerspectiveCommands {
    context: PerspectiveCommandContext;
    commands: CommandSpec[];
}

/** What a command schema is evaluated against. */
export interface PerspectiveCommandContext {
    location: PerspectiveCommandLocation;

    /** The targeted panel, absent only at zero panels. */
    panel?: string;

    /** The name of the panel's `Table`. */
    table?: string;

    /** The name of the panel's plugin. */
    plugin?: string;

    /** The panel's view config, as `getViewConfig()` reports it. */
    view_config?: ViewConfig;

    /** Viewport coordinates of the pointer that initiated the command, for the context menu. */
    point?: { x: number; y: number };

    /** What the plugin rendered at the location, absent over tabs and chrome. */
    hit?: PerspectiveHit;
}

/** A synchronous, effect-free function declaring the commands for a context. */
export type PerspectiveCommandSchema = (
    context: PerspectiveCommandContext,
) => CommandSchema;

/** The `detail` of a `perspective-command` event. */
export interface PerspectiveCommandEventDetail {
    key: string;
    context: PerspectiveCommandContext;
}
"#;

/// Register a plugin globally.
#[wasm_bindgen]
#[allow(non_snake_case)]
pub fn registerPlugin(name: &str) {
    use crate::renderer::*;
    PLUGIN_REGISTRY.register_plugin(name);
}

#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(typescript_type = "Record<string, unknown> | null")]
    pub type JsConfigDefaults;

    #[wasm_bindgen(typescript_type = "ConfigDefaultsOptions")]
    pub type JsConfigDefaultsOptions;

    #[wasm_bindgen(typescript_type = "ColumnConfigDefaultsOptions")]
    pub type JsColumnConfigDefaultsOptions;

    #[wasm_bindgen(
        typescript_type = "Array<{ plugin?: string; defaults: Record<string, unknown> }>"
    )]
    pub type JsPluginConfigDefaultsSlots;

    #[wasm_bindgen(
        typescript_type = "Array<{ plugin?: string; type?: ColumnType; defaults: Record<string, \
                           unknown> }>"
    )]
    pub type JsColumnConfigDefaultsSlots;
}

fn defaults_options<T: Default + serde::de::DeserializeOwned>(
    options: Option<impl Into<JsValue>>,
) -> ApiResult<T> {
    match options {
        None => Ok(T::default()),
        Some(options) => Ok(options.into().into_serde_ext()?),
    }
}

/// Merge `defaults` into the `plugin_config` defaults every
/// `<perspective-viewer>` on the page applies, where a `null` value removes a
/// default and a `null` `defaults` clears the slot.
///
/// # Arguments
///
/// - `defaults` - Values keyed like `plugin_config`, or `null`.
/// - `options.plugin` - Limits the defaults to the named plugin.
///
/// # JavaScript Examples
///
/// ```javascript
/// customElements.get("perspective-viewer").setPluginConfigDefaults({group_pad: 10});
/// ```
#[wasm_bindgen]
#[allow(non_snake_case)]
pub fn setPluginConfigDefaults(
    defaults: JsConfigDefaults,
    options: Option<JsConfigDefaultsOptions>,
) -> ApiResult<()> {
    let config::ConfigDefaultsOptions { plugin } = defaults_options(options)?;
    renderer::set_plugin_config_defaults(&defaults, plugin.as_deref())
}

/// Merge `defaults` into the `columns_config` defaults every
/// `<perspective-viewer>` on the page applies, where a `null` value removes a
/// default and a `null` `defaults` clears the slot.
///
/// # Arguments
///
/// - `defaults` - Values keyed like one `columns_config` entry, or `null`.
/// - `options.plugin` - Limits the defaults to the named plugin.
/// - `options.type` - Limits the defaults to columns of this view type.
///
/// # JavaScript Examples
///
/// ```javascript
/// customElements
///     .get("perspective-viewer")
///     .setColumnConfigDefaults({date_format: {timeZone: "UTC"}}, {type: "datetime"});
/// ```
#[wasm_bindgen]
#[allow(non_snake_case)]
pub fn setColumnConfigDefaults(
    defaults: JsConfigDefaults,
    options: Option<JsColumnConfigDefaultsOptions>,
) -> ApiResult<()> {
    let config::ColumnConfigDefaultsOptions { plugin, ty } = defaults_options(options)?;
    renderer::set_column_config_defaults(&defaults, plugin.as_deref(), ty.as_deref())
}

/// The `plugin_config` defaults set by [`setPluginConfigDefaults`], one entry
/// per slot.
#[wasm_bindgen]
#[allow(non_snake_case)]
pub fn getPluginConfigDefaults() -> ApiResult<JsPluginConfigDefaultsSlots> {
    Ok(renderer::get_plugin_config_defaults()?.unchecked_into())
}

/// The `columns_config` defaults set by [`setColumnConfigDefaults`], one entry
/// per slot.
#[wasm_bindgen]
#[allow(non_snake_case)]
pub fn getColumnConfigDefaults() -> ApiResult<JsColumnConfigDefaultsSlots> {
    Ok(renderer::get_column_config_defaults()?.unchecked_into())
}

/// Register this crate's Custom Elements in the browser's current session.
///
/// This must occur before calling any public API methods on these Custom
/// Elements from JavaScript, as the methods themselves won't be defined yet.
/// By default, this crate does not register `PerspectiveViewerElement` (as to
/// preserve backwards-compatible synchronous API).
#[cfg(not(feature = "external-bootstrap"))]
#[wasm_bindgen(js_name = "init")]
pub fn js_init(
    module: js_sys::WebAssembly::Module,
    url: web_sys::Url,
    #[wasm_bindgen(unchecked_param_type = "unknown")] plugin_utils: JsValue,
) {
    console_error_panic_hook::set_once();
    perspective_js::utils::set_global_logging();
    crate::plugin_utils::set_plugin_utils(plugin_utils);
    define_web_components!("export * as psp from '../../perspective-viewer.js'");
    MODULE.with_borrow_mut(|f| {
        *f = Some((module, url));
    });

    tracing::info!("Perspective initialized.");
}

thread_local! {
    static MODULE: RefCell<Option<(js_sys::WebAssembly::Module, web_sys::Url)>> = RefCell::default();
}

#[cfg(not(feature = "external-bootstrap"))]
#[wasm_bindgen(js_name = "get_wasm_module")]
pub fn js_get_module() -> Result<js_sys::WebAssembly::Module, JsValue> {
    MODULE
        .with_borrow(|f| f.clone().map(|x| x.0))
        .ok_or_else(|| "Uninited module".into())
}

#[cfg(not(feature = "external-bootstrap"))]
#[wasm_bindgen(js_name = "get_worker_url")]
pub fn js_get_worker_url() -> Result<web_sys::Url, JsValue> {
    MODULE
        .with_borrow(|f| f.clone().map(|x| x.1))
        .ok_or_else(|| "Uninited module".into())
}

/// Register Web Components with the global registry, given a Perspective
/// module.
///
/// This function shouldn't be called directly;  instead, use the
/// `define_web_components!` macro to both call this method and hook the
/// wasm_bindgen module object.
pub fn bootstrap_web_components(psp: &JsValue) {
    define_web_component::<PerspectiveViewerElement>(psp);
    define_web_component::<PerspectiveDebugPluginElement>(psp);
}

/// Defining the web components needs an extern struct to reference the
/// generated JavaSript glue. This is parameterized by an attribute macro which
/// needs to be determined by the top-level compiled module - the JavaScript
/// glue code emitted by `wasm-bindgen-cli`.
#[macro_export]
macro_rules! define_web_components {
    ($x:expr) => {{
        #[wasm_bindgen::prelude::wasm_bindgen(inline_js = $x)]
        extern "C" {
            #[wasm_bindgen::prelude::wasm_bindgen(js_name = "psp")]
            #[wasm_bindgen::prelude::wasm_bindgen(thread_local_v2)]
            pub static PSP: wasm_bindgen::prelude::JsValue;
        }

        PSP.with(|x| $crate::bootstrap_web_components(x));
    }};
}