perspective_viewer/
lib.rs1#![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 format;
40mod js;
41mod plugin_utils;
42mod presentation;
43mod root;
44
45#[doc(hidden)]
46pub mod queries;
47mod renderer;
48mod session;
49
50#[doc(hidden)]
51pub mod tasks;
52pub mod ui;
53pub mod utils;
54mod workspace;
55
56use std::cell::RefCell;
57
58use perspective_js::utils::*;
59use wasm_bindgen::prelude::*;
60
61use crate::custom_elements::debug_plugin::PerspectiveDebugPluginElement;
62use crate::custom_elements::viewer::PerspectiveViewerElement;
63use crate::utils::define_web_component;
64
65#[wasm_bindgen(typescript_custom_section)]
66const TS_APPEND_CONTENT: &'static str = r#"
67import type {
68 ColumnType,
69 ColumnWindow,
70 DeleteOptions,
71 Features,
72 JoinOptions,
73 OnRemoveData,
74 OnUpdateData,
75 OnUpdateOptions,
76 Scalar,
77 SystemInfo,
78 TableInitOptions,
79 TypedArrayWindow,
80 UpdateOptions,
81 ViewConfig,
82 ViewConfigUpdate,
83 ViewWindow,
84} from "@perspective-dev/client";
85
86export type * from "../ts-rs/ViewerConfig.d.ts";
87export type * from "../ts-rs/ViewerConfigUpdate.d.ts";
88export type * from "../ts-rs/ViewerConfigInitial.d.ts";
89export type * from "../ts-rs/PluginStaticConfig.d.ts";
90export type * from "../ts-rs/WorkspaceConfig.d.ts";
91export type * from "../ts-rs/TableRef.d.ts";
92export type * from "../ts-rs/DerivedTableConfig.d.ts";
93export type * from "../ts-rs/WorkspaceConfigUpdate.d.ts";
94export type * from "../ts-rs/ExportMethod.d.ts";
95export type * from "../ts-rs/PanelOptions.d.ts";
96export type * from "../ts-rs/RestoreOptions.d.ts";
97export type * from "../ts-rs/RestoreWorkspaceOptions.d.ts";
98export type * from "../ts-rs/AddPanelOptions.d.ts";
99export type * from "../ts-rs/SaveWorkspaceOptions.d.ts";
100export type * from "../ts-rs/ClientOptions.d.ts";
101export type * from "../ts-rs/ExportOptions.d.ts";
102export type * from "../ts-rs/GetTableOptions.d.ts";
103export type * from "../ts-rs/GetClientOptions.d.ts";
104export type * from "../ts-rs/GetViewOptions.d.ts";
105export type * from "../ts-rs/GetViewMode.d.ts";
106export type * from "../ts-rs/CustomNumberFormatConfig.d.ts";
107export type * from "../ts-rs/NumberFormatStyle.d.ts";
108export type * from "../ts-rs/Notation.d.ts";
109export type * from "../ts-rs/DatetimeFormat.d.ts";
110export type * from "../ts-rs/ConfigDefaultsOptions.d.ts";
111export type * from "../ts-rs/ColumnConfigDefaultsOptions.d.ts";
112export type * from "../ts-rs/CommandSchema.d.ts";
113export type * from "../ts-rs/CommandSpec.d.ts";
114export type * from "../ts-rs/CommandLocation.d.ts";
115export type * from "../ts-rs/CommandSchemaOptions.d.ts";
116export type * from "../ts-rs/PerspectiveHit.d.ts";
117export type * from "../ts-rs/PerspectiveHitRef.d.ts";
118
119export type ExportData =
120 | string
121 | ArrayBuffer
122 | Blob
123 | Record<string, unknown[]>
124 | ViewerConfig;
125
126import type {CustomNumberFormatConfig} from "../ts-rs/CustomNumberFormatConfig.d.ts";
127import type {NumberFormatStyle} from "../ts-rs/NumberFormatStyle.d.ts";
128import type {Notation} from "../ts-rs/Notation.d.ts";
129import type {DatetimeFormat} from "../ts-rs/DatetimeFormat.d.ts";
130import type {GetTableOptions} from "../ts-rs/GetTableOptions.d.ts";
131import type {PanelOptions} from "../ts-rs/PanelOptions.d.ts";
132import type {RestoreOptions} from "../ts-rs/RestoreOptions.d.ts";
133import type {RestoreWorkspaceOptions} from "../ts-rs/RestoreWorkspaceOptions.d.ts";
134import type {AddPanelOptions} from "../ts-rs/AddPanelOptions.d.ts";
135import type {SaveWorkspaceOptions} from "../ts-rs/SaveWorkspaceOptions.d.ts";
136import type {ConfigDefaultsOptions} from "../ts-rs/ConfigDefaultsOptions.d.ts";
137import type {ColumnConfigDefaultsOptions} from "../ts-rs/ColumnConfigDefaultsOptions.d.ts";
138import type {ExportOptions} from "../ts-rs/ExportOptions.d.ts";
139import type {GetClientOptions} from "../ts-rs/GetClientOptions.d.ts";
140import type {GetViewOptions} from "../ts-rs/GetViewOptions.d.ts";
141import type {ClientOptions} from "../ts-rs/ClientOptions.d.ts";
142import type {ViewerConfig} from "../ts-rs/ViewerConfig.d.ts";
143import type {ViewerConfigUpdate} from "../ts-rs/ViewerConfigUpdate.d.ts";
144import type {ViewerConfigInitial} from "../ts-rs/ViewerConfigInitial.d.ts";
145import type {WorkspaceConfig} from "../ts-rs/WorkspaceConfig.d.ts";
146import type {WorkspaceConfigUpdate} from "../ts-rs/WorkspaceConfigUpdate.d.ts";
147import type {CommandSchema} from "../ts-rs/CommandSchema.d.ts";
148import type {CommandSpec} from "../ts-rs/CommandSpec.d.ts";
149import type {CommandLocation} from "../ts-rs/CommandLocation.d.ts";
150import type {CommandSchemaOptions} from "../ts-rs/CommandSchemaOptions.d.ts";
151import type {PerspectiveHit} from "../ts-rs/PerspectiveHit.d.ts";
152import type {PerspectiveHitRef} from "../ts-rs/PerspectiveHitRef.d.ts";
153
154/** A column of formatted values: one string and the UTF-16 end offset of each value in it. */
155export interface FormattedColumn {
156 text: string;
157 ends: Uint32Array;
158}
159
160/**
161 * A numeric column's `number_format`, as the Style tab writes it: the ts-rs
162 * `CustomNumberFormatConfig` with its flattened `style` and `notation`
163 * families, which ts-rs cannot flatten and exports separately.
164 */
165export type NumberFormatConfig = CustomNumberFormatConfig &
166 Partial<NumberFormatStyle> &
167 Partial<Notation>;
168
169/** A datetime column's `date_format`, a subset of `Intl.DateTimeFormatOptions`. */
170export type DateFormatConfig = DatetimeFormat;
171
172/** The `date_format` options that apply individually rather than as one group. */
173export type DateFormatModifiers = Pick<DateFormatConfig, "timeZone" | "hour12">;
174
175/**
176 * A formatter for the values of a column of `column_type`, or `undefined` for
177 * a type whose values are not formatted, given the column's `number_format`
178 * or `date_format` and the calling plugin's default for the same key.
179 *
180 * @example
181 * ```javascript
182 * const formatter = viewer.plugin_utils.formatter("float", { style: "percent" });
183 * console.log(formatter.format(0.25));
184 * ```
185 */
186export function formatter(
187 column_type: ColumnType,
188 format?: NumberFormatConfig | DateFormatConfig,
189 defaults?: NumberFormatConfig | DateFormatConfig,
190): Formatter | undefined;
191
192/**
193 * Whether the `date_format` `format` sets any of the keys that apply as one
194 * group (a preset or any date or time part), rather than only `timeZone` or
195 * `hour12`.
196 */
197export function has_date_format_shape(format?: DateFormatConfig): boolean;
198
199/**
200 * The keys of the `date_format` `format` that apply individually, `timeZone`
201 * and `hour12`, or `undefined` when it sets neither.
202 */
203export function date_format_modifiers(
204 format?: DateFormatConfig,
205): DateFormatModifiers | undefined;
206
207/** A color's red, green and blue channels, each in `[0, 255]`. */
208export type RGB = [number, number, number];
209
210/** One stop of a color scale: a color at `offset` in `[0, 1]`. */
211export interface GradientStopRgb {
212 rgb: RGB;
213 offset: number;
214}
215
216/** A surface a command schema is evaluated for. */
217export type PerspectiveCommandLocation = CommandLocation;
218
219/**
220 * A window of a plugin's viewport, in the shape of the parsed
221 * `to_columns_string({ id: true })` result and the `column_paths()` area.
222 */
223export interface PerspectiveViewFrame {
224 /** The view row index of `data`'s first entry. */
225 start_row: number;
226
227 /** The view column index of `paths[0]`. */
228 start_col: number;
229
230 /** The `data` key of each column from `start_col`. */
231 paths: string[];
232
233 /** One level per `split_by` plus the column name, each over `paths`. */
234 column_paths: Scalar[][];
235
236 /** Columns keyed by path, with `__ROW_PATH__` and `__ID__` when present. */
237 data: Record<string, unknown[]>;
238}
239
240/** What a plugin rendered at a viewport point, before the viewer resolves it. */
241export interface PerspectiveHitTest {
242 frame: PerspectiveViewFrame;
243 ref: PerspectiveHitRef;
244}
245
246/** One `queryCommands()` result: the context the schema saw and what it returned. */
247export interface PerspectiveCommands {
248 context: PerspectiveCommandContext;
249 commands: CommandSpec[];
250}
251
252/** What a command schema is evaluated against. */
253export interface PerspectiveCommandContext {
254 location: PerspectiveCommandLocation;
255
256 /** The targeted panel, absent only at zero panels. */
257 panel?: string;
258
259 /** The name of the panel's `Table`. */
260 table?: string;
261
262 /** The name of the panel's plugin. */
263 plugin?: string;
264
265 /** The panel's view config, as `getViewConfig()` reports it. */
266 view_config?: ViewConfig;
267
268 /** Viewport coordinates of the pointer that initiated the command, for the context menu. */
269 point?: { x: number; y: number };
270
271 /** What the plugin rendered at the location, absent over tabs and chrome. */
272 hit?: PerspectiveHit;
273}
274
275/** A synchronous, effect-free function declaring the commands for a context. */
276export type PerspectiveCommandSchema = (
277 context: PerspectiveCommandContext,
278) => CommandSchema;
279
280/** The `detail` of a `perspective-command` event. */
281export interface PerspectiveCommandEventDetail {
282 key: string;
283 context: PerspectiveCommandContext;
284}
285"#;
286
287#[wasm_bindgen]
289#[allow(non_snake_case)]
290pub fn registerPlugin(name: &str) {
291 use crate::renderer::*;
292 PLUGIN_REGISTRY.register_plugin(name);
293}
294
295#[wasm_bindgen]
296extern "C" {
297 #[wasm_bindgen(typescript_type = "Record<string, unknown> | null")]
298 pub type JsConfigDefaults;
299
300 #[wasm_bindgen(typescript_type = "ConfigDefaultsOptions")]
301 pub type JsConfigDefaultsOptions;
302
303 #[wasm_bindgen(typescript_type = "ColumnConfigDefaultsOptions")]
304 pub type JsColumnConfigDefaultsOptions;
305
306 #[wasm_bindgen(
307 typescript_type = "Array<{ plugin?: string; defaults: Record<string, unknown> }>"
308 )]
309 pub type JsPluginConfigDefaultsSlots;
310
311 #[wasm_bindgen(
312 typescript_type = "Array<{ plugin?: string; type?: ColumnType; defaults: Record<string, \
313 unknown> }>"
314 )]
315 pub type JsColumnConfigDefaultsSlots;
316}
317
318fn defaults_options<T: Default + serde::de::DeserializeOwned>(
319 options: Option<impl Into<JsValue>>,
320) -> ApiResult<T> {
321 match options {
322 None => Ok(T::default()),
323 Some(options) => Ok(options.into().into_serde_ext()?),
324 }
325}
326
327#[wasm_bindgen]
342#[allow(non_snake_case)]
343pub fn setPluginConfigDefaults(
344 defaults: JsConfigDefaults,
345 options: Option<JsConfigDefaultsOptions>,
346) -> ApiResult<()> {
347 let config::ConfigDefaultsOptions { plugin } = defaults_options(options)?;
348 renderer::set_plugin_config_defaults(&defaults, plugin.as_deref())
349}
350
351#[wasm_bindgen]
369#[allow(non_snake_case)]
370pub fn setColumnConfigDefaults(
371 defaults: JsConfigDefaults,
372 options: Option<JsColumnConfigDefaultsOptions>,
373) -> ApiResult<()> {
374 let config::ColumnConfigDefaultsOptions { plugin, ty } = defaults_options(options)?;
375 renderer::set_column_config_defaults(&defaults, plugin.as_deref(), ty.as_deref())
376}
377
378#[wasm_bindgen]
381#[allow(non_snake_case)]
382pub fn getPluginConfigDefaults() -> ApiResult<JsPluginConfigDefaultsSlots> {
383 Ok(renderer::get_plugin_config_defaults()?.unchecked_into())
384}
385
386#[wasm_bindgen]
389#[allow(non_snake_case)]
390pub fn getColumnConfigDefaults() -> ApiResult<JsColumnConfigDefaultsSlots> {
391 Ok(renderer::get_column_config_defaults()?.unchecked_into())
392}
393
394#[cfg(not(feature = "external-bootstrap"))]
401#[wasm_bindgen(js_name = "init")]
402pub fn js_init(
403 module: js_sys::WebAssembly::Module,
404 url: web_sys::Url,
405 #[wasm_bindgen(unchecked_param_type = "unknown")] plugin_utils: JsValue,
406) {
407 console_error_panic_hook::set_once();
408 perspective_js::utils::set_global_logging();
409 crate::plugin_utils::set_plugin_utils(plugin_utils);
410 define_web_components!("export * as psp from '../../perspective-viewer.js'");
411 MODULE.with_borrow_mut(|f| {
412 *f = Some((module, url));
413 });
414
415 tracing::info!("Perspective initialized.");
416}
417
418thread_local! {
419 static MODULE: RefCell<Option<(js_sys::WebAssembly::Module, web_sys::Url)>> = RefCell::default();
420}
421
422#[cfg(not(feature = "external-bootstrap"))]
423#[wasm_bindgen(js_name = "get_wasm_module")]
424pub fn js_get_module() -> Result<js_sys::WebAssembly::Module, JsValue> {
425 MODULE
426 .with_borrow(|f| f.clone().map(|x| x.0))
427 .ok_or_else(|| "Uninited module".into())
428}
429
430#[cfg(not(feature = "external-bootstrap"))]
431#[wasm_bindgen(js_name = "get_worker_url")]
432pub fn js_get_worker_url() -> Result<web_sys::Url, JsValue> {
433 MODULE
434 .with_borrow(|f| f.clone().map(|x| x.1))
435 .ok_or_else(|| "Uninited module".into())
436}
437
438pub fn bootstrap_web_components(psp: &JsValue) {
445 define_web_component::<PerspectiveViewerElement>(psp);
446 define_web_component::<PerspectiveDebugPluginElement>(psp);
447}
448
449#[macro_export]
454macro_rules! define_web_components {
455 ($x:expr) => {{
456 #[wasm_bindgen::prelude::wasm_bindgen(inline_js = $x)]
457 extern "C" {
458 #[wasm_bindgen::prelude::wasm_bindgen(js_name = "psp")]
459 #[wasm_bindgen::prelude::wasm_bindgen(thread_local_v2)]
460 pub static PSP: wasm_bindgen::prelude::JsValue;
461 }
462
463 PSP.with(|x| $crate::bootstrap_web_components(x));
464 }};
465}