perspective_js/view.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
13use js_sys::{Array, ArrayBuffer, Function, Object};
14use perspective_client::{
15 ColumnWindow, OnRemoveData, OnUpdateData, OnUpdateOptions, TypedArrayWindow, ViewWindow,
16 assert_view_api,
17};
18use wasm_bindgen::prelude::*;
19use wasm_bindgen_futures::spawn_local;
20
21#[cfg(doc)]
22use crate::table::Table;
23use crate::typed_array::{JsTypedArrayWindow, call_with_typed_arrays};
24use crate::utils::{ApiFuture, ApiResult, JsValueSerdeExt, LocalPollLoop};
25
26#[wasm_bindgen]
27unsafe extern "C" {
28 #[wasm_bindgen(typescript_type = "ViewWindow")]
29 #[derive(Clone)]
30 pub type JsViewWindow;
31
32 #[wasm_bindgen(typescript_type = "ColumnWindow")]
33 #[derive(Clone)]
34 pub type JsColumnWindow;
35
36 #[wasm_bindgen(method, setter, js_name = "formatted")]
37 pub fn set_formatted(this: &JsViewWindow, x: bool);
38
39 #[wasm_bindgen(typescript_type = "OnUpdateOptions")]
40 pub type JsOnUpdateOptions;
41
42}
43
44impl From<ViewWindow> for JsViewWindow {
45 fn from(value: ViewWindow) -> Self {
46 JsViewWindow::from_serde_ext(&value)
47 .unwrap()
48 .unchecked_into()
49 }
50}
51
52fn scalar_to_jsvalue(scalar: &perspective_client::config::Scalar) -> JsValue {
53 match scalar {
54 perspective_client::config::Scalar::Float(x) => JsValue::from_f64(*x),
55 perspective_client::config::Scalar::String(x) => JsValue::from_str(x),
56 perspective_client::config::Scalar::Bool(x) => JsValue::from_bool(*x),
57 perspective_client::config::Scalar::Null => JsValue::NULL,
58 }
59}
60
61/// The [`View`] struct is Perspective's query and serialization interface. It
62/// represents a query on the `Table`'s dataset and is always created from an
63/// existing `Table` instance via the [`Table::view`] method.
64///
65/// [`View`]s are immutable with respect to the arguments provided to the
66/// [`Table::view`] method; to change these parameters, you must create a new
67/// [`View`] on the same [`Table`]. However, each [`View`] is _live_ with
68/// respect to the [`Table`]'s data, and will (within a conflation window)
69/// update with the latest state as its parent [`Table`] updates, including
70/// incrementally recalculating all aggregates, pivots, filters, etc. [`View`]
71/// query parameters are composable, in that each parameter works independently
72/// _and_ in conjunction with each other, and there is no limit to the number of
73/// pivots, filters, etc. which can be applied.
74#[wasm_bindgen]
75#[derive(Clone)]
76pub struct View(pub(crate) perspective_client::View);
77
78assert_view_api!(View);
79
80impl From<perspective_client::View> for View {
81 fn from(value: perspective_client::View) -> Self {
82 View(value)
83 }
84}
85
86#[wasm_bindgen]
87impl View {
88 #[doc(hidden)]
89 pub fn __get_model(&self) -> View {
90 self.clone()
91 }
92
93 #[wasm_bindgen]
94 #[doc(hidden)]
95 pub fn __unsafe_get_name(&self) -> String {
96 self.0.name.clone()
97 }
98
99 /// Returns this [`View`]'s column header area for `window`, transposed as
100 /// `area[level][column]`.
101 ///
102 /// A column path shows the columns that a given cell belongs to after
103 /// pivots are applied. The area is rectangular with one level per
104 /// `split_by` plus one: a column's split values occupy the leading levels
105 /// and its name always occupies the last, so a subtotal or grand total
106 /// under `split_rollup_mode: "rollup"` reads `null` at the levels it does
107 /// not pivot on. Values keep their column's type - a `datetime` split value
108 /// is epoch milliseconds, not text - so formatting them is the caller's
109 /// choice.
110 ///
111 /// `window` slices the *column* axis; the number of levels does not depend
112 /// on it.
113 #[wasm_bindgen(unchecked_return_type = "(string | number | boolean | null)[][]")]
114 pub async fn column_paths(&self, window: Option<JsColumnWindow>) -> ApiResult<JsValue> {
115 let window = window.into_serde_ext::<Option<ColumnWindow>>()?;
116 let columns = self.0.column_paths(window.unwrap_or_default()).await?;
117 Ok(JsValue::from_serde_ext(&columns)?)
118 }
119
120 /// Delete this [`View`] and clean up all resources associated with it.
121 /// [`View`] objects do not stop consuming resources or processing
122 /// updates when they are garbage collected - you must call this method
123 /// to reclaim these.
124 #[wasm_bindgen]
125 pub async fn delete(self) -> ApiResult<()> {
126 self.0.delete().await?;
127 Ok(())
128 }
129
130 /// Returns this [`View`]'s _dimensions_, row and column count, as well as
131 /// those of the [`crate::Table`] from which it was derived.
132 ///
133 /// - `num_table_rows` - The number of rows in the underlying
134 /// [`crate::Table`].
135 /// - `num_table_columns` - The number of columns in the underlying
136 /// [`crate::Table`] (including the `index` column if this
137 /// [`crate::Table`] was constructed with one).
138 /// - `num_view_rows` - The number of rows in this [`View`]. If this
139 /// [`View`] has a `group_by` clause, `num_view_rows` will also include
140 /// aggregated rows.
141 /// - `num_view_columns` - The number of columns in this [`View`]. If this
142 /// [`View`] has a `split_by` clause, `num_view_columns` will include all
143 /// _column paths_, e.g. the number of `columns` clause times the number
144 /// of `split_by` groups.
145 #[wasm_bindgen]
146 pub async fn dimensions(&self) -> ApiResult<JsValue> {
147 let dimensions = self.0.dimensions().await?;
148 Ok(JsValue::from_serde_ext(&dimensions)?)
149 }
150
151 /// The expression schema of this [`View`], which contains only the
152 /// expressions created on this [`View`]. See [`View::schema`] for
153 /// details.
154 #[wasm_bindgen]
155 pub async fn expression_schema(&self) -> ApiResult<JsValue> {
156 let schema = self.0.expression_schema().await?;
157 Ok(JsValue::from_serde_ext(&schema)?)
158 }
159
160 /// A copy of the config object passed to the [`Table::view`] method which
161 /// created this [`View`].
162 #[wasm_bindgen]
163 pub async fn get_config(&self) -> ApiResult<JsValue> {
164 let config = self.0.get_config().await?;
165 Ok(JsValue::from_serde_ext(&config)?)
166 }
167
168 /// Calculates the [min, max] of the leaf nodes of a column `column_name`.
169 ///
170 /// # Returns
171 ///
172 /// A tuple of [min, max], whose types are column and aggregate dependent.
173 #[wasm_bindgen]
174 pub async fn get_min_max(&self, name: String) -> ApiResult<Array> {
175 let result = self.0.get_min_max(name).await?;
176 let arr = Array::new();
177 arr.push(&scalar_to_jsvalue(&result.0));
178 arr.push(&scalar_to_jsvalue(&result.1));
179 Ok(arr)
180 }
181
182 /// The number of aggregated rows in this [`View`]. This is affected by the
183 /// "group_by" configuration parameter supplied to this view's contructor.
184 ///
185 /// # Returns
186 ///
187 /// The number of aggregated rows.
188 #[wasm_bindgen]
189 pub async fn num_rows(&self) -> ApiResult<i32> {
190 let size = self.0.num_rows().await?;
191 Ok(size as i32)
192 }
193
194 /// The schema of this [`View`].
195 ///
196 /// The [`View`] schema differs from the `schema` returned by
197 /// [`Table::schema`]; it may have different column names due to
198 /// `expressions` or `columns` configs, or it maye have _different
199 /// column types_ due to the application og `group_by` and `aggregates`
200 /// config. You can think of [`Table::schema`] as the _input_ schema and
201 /// [`View::schema`] as the _output_ schema of a Perspective pipeline.
202 #[wasm_bindgen]
203 pub async fn schema(&self) -> ApiResult<JsValue> {
204 let schema = self.0.schema().await?;
205 Ok(JsValue::from_serde_ext(&schema)?)
206 }
207
208 /// Serializes a [`View`] to the Apache Arrow data format.
209 ///
210 /// # Arguments
211 ///
212 /// - `window` - a [`ViewWindow`]; its `compression` key selects Arrow IPC
213 /// body compression, `"lz4"` or `"zstd"` (uncompressed when omitted).
214 ///
215 /// # JavaScript Examples
216 ///
217 /// ```javascript
218 /// const arrow = await view.to_arrow({ compression: "zstd" });
219 /// ```
220 #[wasm_bindgen]
221 pub async fn to_arrow(&self, window: Option<JsViewWindow>) -> ApiResult<ArrayBuffer> {
222 let window = window.into_serde_ext::<Option<ViewWindow>>()?;
223 let arrow = self.0.to_arrow(window.unwrap_or_default()).await?;
224 Ok(js_sys::Uint8Array::from(&arrow[..])
225 .buffer()
226 .unchecked_into())
227 }
228
229 /// Serializes this [`View`] to a string of JSON data. Useful if you want to
230 /// save additional round trip serialize/deserialize cycles.
231 #[wasm_bindgen]
232 pub async fn to_columns_string(&self, window: Option<JsViewWindow>) -> ApiResult<String> {
233 let window = window.into_serde_ext::<Option<ViewWindow>>()?;
234 let json = self.0.to_columns_string(window.unwrap_or_default()).await?;
235 Ok(json)
236 }
237
238 /// Serializes this [`View`] to JavaScript objects in a column-oriented
239 /// format.
240 #[wasm_bindgen]
241 pub async fn to_columns(&self, window: Option<JsViewWindow>) -> ApiResult<Object> {
242 let json = self.to_columns_string(window).await?;
243 Ok(js_sys::JSON::parse(&json)?.unchecked_into())
244 }
245
246 /// Render this `View` as a JSON string.
247 #[wasm_bindgen]
248 pub async fn to_json_string(&self, window: Option<JsViewWindow>) -> ApiResult<String> {
249 let window = window.into_serde_ext::<Option<ViewWindow>>()?;
250 let json = self.0.to_json_string(window.unwrap_or_default()).await?;
251 Ok(json)
252 }
253
254 /// Serializes this [`View`] to JavaScript objects in a row-oriented
255 /// format.
256 #[wasm_bindgen]
257 pub async fn to_json(&self, window: Option<JsViewWindow>) -> ApiResult<Array> {
258 let json = self.to_json_string(window).await?;
259 Ok(js_sys::JSON::parse(&json)?.unchecked_into())
260 }
261
262 /// Renders this [`View`] as an [NDJSON](https://github.com/ndjson/ndjson-spec)
263 /// formatted [`String`].
264 #[wasm_bindgen]
265 pub async fn to_ndjson(&self, window: Option<JsViewWindow>) -> ApiResult<String> {
266 let window = window.into_serde_ext::<Option<ViewWindow>>()?;
267 let ndjson = self.0.to_ndjson(window.unwrap_or_default()).await?;
268 Ok(ndjson)
269 }
270
271 /// Serializes this [`View`] to CSV data in a standard format.
272 #[wasm_bindgen]
273 pub async fn to_csv(&self, window: Option<JsViewWindow>) -> ApiResult<String> {
274 let window = window.into_serde_ext::<Option<ViewWindow>>()?;
275 Ok(self.0.to_csv(window.unwrap_or_default()).await?)
276 }
277
278 /// Fetches columns from the [`View`] in Arrow format, decodes them, and
279 /// passes typed array views to `callback`. All arrays are only valid for
280 /// the duration of the callback — if `callback` returns a `Promise`, it
281 /// is awaited before the backing Arrow buffer is released, so async
282 /// callbacks may use the views for the full duration of the awaited
283 /// work (e.g. across an `await requestAnimationFrame`-backed promise).
284 ///
285 /// # Arguments
286 ///
287 /// - `window` - Optional [`TypedArrayWindow`] controlling row/column
288 /// windowing and output options (e.g., `float32` mode).
289 /// - `callback` - A JS function called with `(names: string[], values:
290 /// TypedArray[], validities: (Uint8Array|null)[], dictionaries:
291 /// (string[]|null)[]) => void | Promise<void>`.
292 #[wasm_bindgen]
293 pub async fn with_typed_arrays(
294 &self,
295 window: Option<JsTypedArrayWindow>,
296 callback: Function,
297 ) -> ApiResult<()> {
298 let window = window
299 .into_serde_ext::<Option<TypedArrayWindow>>()?
300 .unwrap_or_default();
301
302 let columns = self.0.to_typed_arrays(window).await?;
303 call_with_typed_arrays(&columns, &callback).await
304 }
305
306 /// Register a callback with this [`View`]. Whenever the view's underlying
307 /// table emits an update, this callback will be invoked with an object
308 /// containing `port_id`, indicating which port the update fired on, and
309 /// optionally `delta`, which is the new data that was updated for each
310 /// cell or each row (as an Arrow).
311 ///
312 /// # Arguments
313 ///
314 /// - `on_update` - A callback function invoked on update, which receives an
315 /// object with two keys: `port_id`, indicating which port the update was
316 /// triggered on, and `delta`, whose value is dependent on the mode
317 /// parameter.
318 /// - `options` - If this is provided as `{mode: "row"}`, then `delta` is an
319 /// Arrow of the updated rows. Otherwise `delta` will be `null`.
320 ///
321 /// # JavaScript Examples
322 ///
323 /// ```javascript
324 /// view.on_update((updated) => console.log(updated.port_id));
325 /// ```
326 ///
327 /// ```javascript
328 /// view.on_update((updated) => console.log(updated.delta), { mode: "row" });
329 /// ```
330 #[wasm_bindgen]
331 pub fn on_update(
332 &self,
333 #[wasm_bindgen(unchecked_param_type = "(data: OnUpdateData) => void")]
334 on_update_js: Function,
335 options: Option<JsOnUpdateOptions>,
336 ) -> ApiFuture<u32> {
337 let poll_loop = LocalPollLoop::new(move |args: OnUpdateData| {
338 let js_obj = JsValue::from_serde_ext(&*args)?;
339 on_update_js.call1(&JsValue::UNDEFINED, &js_obj)
340 });
341
342 let on_update = Box::new(move |msg| poll_loop.poll(msg));
343 let view = self.0.clone();
344 ApiFuture::new(async move {
345 let on_update_opts = options
346 .into_serde_ext::<Option<OnUpdateOptions>>()?
347 .unwrap_or_default();
348
349 let id = view.on_update(on_update, on_update_opts).await?;
350 Ok(id)
351 })
352 }
353
354 /// Unregister a previously registered update callback with this [`View`].
355 ///
356 /// # Arguments
357 ///
358 /// - `id` - A callback `id` as returned by a recipricol call to
359 /// [`View::on_update`].
360 #[wasm_bindgen]
361 pub async fn remove_update(&self, callback_id: u32) -> ApiResult<()> {
362 Ok(self.0.remove_update(callback_id).await?)
363 }
364
365 /// Register a callback which is invoked whenever rows leave this
366 /// [`View`], with an object containing `port_id`, `indices` (their keys
367 /// as an Arrow of one column per key column named after it) and `cause`,
368 /// one of `"key"`, `"filter"` or `"group"`.
369 ///
370 /// For a [`View`] without `group_by` the keys are the `index` columns of
371 /// the [`Table`], which must have one: `"key"` when [`Table::remove`]
372 /// removed them ([`Table::replace`] reports the keys it does not
373 /// re-supply and [`Table::clear`] every key) and `"filter"` when
374 /// [`Table::update`] moved them outside the [`View`]'s `filter`. For a
375 /// [`View`] with `group_by` the keys are the `group_by` columns of each
376 /// group which no longer has any rows, `"group"`, `null` below the
377 /// group's depth. It fires once per cause per update step.
378 ///
379 /// # JavaScript Examples
380 ///
381 /// ```javascript
382 /// const id = await view.on_remove(({ indices, port_id, cause }) => {
383 /// replica.remove(indices);
384 /// });
385 /// ```
386 #[wasm_bindgen]
387 pub fn on_remove(
388 &self,
389 #[wasm_bindgen(unchecked_param_type = "(data: OnRemoveData) => void")]
390 on_remove_js: Function,
391 ) -> ApiFuture<u32> {
392 let poll_loop = LocalPollLoop::new(move |args: OnRemoveData| {
393 let js_obj = JsValue::from_serde_ext(&args)?;
394 on_remove_js.call1(&JsValue::UNDEFINED, &js_obj)
395 });
396
397 let on_remove = Box::new(move |msg| poll_loop.poll(msg));
398 let view = self.0.clone();
399 ApiFuture::new(async move { Ok(view.on_remove(on_remove).await?) })
400 }
401
402 /// Unregister a previously registered [`View::on_remove`] callback.
403 ///
404 /// # Arguments
405 ///
406 /// - `id` - A callback `id` as returned by a reciprocal call to
407 /// [`View::on_remove`].
408 #[wasm_bindgen]
409 pub async fn remove_remove(&self, callback_id: u32) -> ApiResult<()> {
410 Ok(self.0.remove_remove(callback_id).await?)
411 }
412
413 /// Register a callback with this [`View`]. Whenever the [`View`] is
414 /// deleted, this callback will be invoked.
415 #[wasm_bindgen]
416 pub fn on_delete(&self, on_delete: Function) -> ApiFuture<u32> {
417 let view = self.clone();
418 ApiFuture::new(async move {
419 let emit = LocalPollLoop::new(move |()| on_delete.call0(&JsValue::UNDEFINED));
420 let on_delete = Box::new(move || spawn_local(emit.poll(())));
421 Ok(view.0.on_delete(on_delete).await?)
422 })
423 }
424
425 /// The number of aggregated columns in this [`View`]. This is affected by
426 /// the "split_by" configuration parameter supplied to this view's
427 /// contructor.
428 ///
429 /// # Returns
430 ///
431 /// The number of aggregated columns.
432 #[wasm_bindgen]
433 pub async fn num_columns(&self) -> ApiResult<u32> {
434 // TODO: This is broken because of how split by creates a
435 // cartesian product of columns * unique values.
436 Ok(self.0.dimensions().await?.num_view_columns)
437 }
438
439 /// Unregister a previously registered [`View::on_delete`] callback.
440 #[wasm_bindgen]
441 pub fn remove_delete(&self, callback_id: u32) -> ApiFuture<()> {
442 let client = self.0.clone();
443 ApiFuture::new(async move {
444 client.remove_delete(callback_id).await?;
445 Ok(())
446 })
447 }
448
449 /// Collapses the `group_by` row at `row_index`.
450 #[wasm_bindgen]
451 pub async fn collapse(&self, row_index: u32) -> ApiResult<u32> {
452 Ok(self.0.collapse(row_index).await?)
453 }
454
455 /// Expand the `group_by` row at `row_index`.
456 #[wasm_bindgen]
457 pub async fn expand(&self, row_index: u32) -> ApiResult<u32> {
458 Ok(self.0.expand(row_index).await?)
459 }
460
461 /// Set expansion `depth` of the `group_by` tree.
462 #[wasm_bindgen]
463 pub async fn set_depth(&self, depth: u32) -> ApiResult<()> {
464 Ok(self.0.set_depth(depth).await?)
465 }
466}