perspective-viewer 5.6.1

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
// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
// ┃ ██████ ██████ ██████       █      █      █      █      █ █▄  ▀███ █       ┃
// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█  ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄  ▀█ █ ▀▀▀▀▀ ┃
// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄   █ ▄▄▄▄▄ ┃
// ┃ █      ██████ █  ▀█▄       █ ██████      █      ███▌▐███ ███████▄ █       ┃
// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
// ┃ 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). ┃
// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

use std::collections::{HashMap, HashSet};
use std::iter::IntoIterator;
use std::ops::{Deref, DerefMut};
use std::rc::Rc;

use perspective_client::config::*;
use perspective_js::apierror;

use crate::presentation::ColumnLocator;
use crate::utils::PtrEqRc;
use crate::*;

#[derive(Clone, PartialEq)]
struct SessionViewExpressionMetadata {
    edited: HashMap<String, String>,
    expressions: perspective_client::ExprValidationResult,
}

/// Metadata state reflects data we could fetch from a `View`, but would like to
/// do so without `async`.  It must be recreated by any `async` method which
/// changes the `View` and may temporarily be out-of-sync with the
/// `View`/`ViewConfig`.
#[derive(Clone, Default, PartialEq)]
pub struct SessionMetadata(Option<SessionMetadataState>);

pub type SessionMetadataRc = PtrEqRc<SessionMetadata>;

impl std::fmt::Debug for SessionMetadata {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("SessionMetadata { .. }")
    }
}

impl Deref for SessionMetadata {
    type Target = Option<SessionMetadataState>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for SessionMetadata {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

/// An OWNED read guard over a panel's [`SessionMetadata`]: a snapshot that
/// borrows nothing, so holding one can never make a later state write panic.
pub struct MetadataRef(pub(super) Rc<SessionMetadata>);

impl Deref for MetadataRef {
    type Target = SessionMetadata;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

pub type MetadataMutRef<'a> = std::cell::RefMut<'a, SessionMetadata>;

/// TODO the multiple `Option` types could probably be merged since they are
/// populated within an async lock
#[derive(Clone, Default, PartialEq)]
pub struct SessionMetadataState {
    features: perspective_client::Features,
    column_names: Vec<String>,
    table_schema: HashMap<String, ColumnType>,
    edit_port: f64,
    view_schema: Option<HashMap<String, ColumnType>>,
    expr_meta: Option<SessionViewExpressionMetadata>,
    window_schema: HashMap<String, ColumnType>,
}

impl SessionMetadata {
    /// Creates a new `SessionMetadata` from a `JsPerspectiveTable`.
    pub(super) async fn from_table(table: &perspective_client::Table) -> ApiResult<Self> {
        let (features, column_names, table_schema, edit_port) = futures::join!(
            table.get_features(),
            table.columns(),
            table.schema(),
            table.make_port()
        );

        Ok(Self(Some(SessionMetadataState {
            features: features?,
            column_names: column_names?,
            table_schema: table_schema?,
            edit_port: edit_port? as f64,
            ..SessionMetadataState::default()
        })))
    }

    pub(super) fn update_view_schema(
        &mut self,
        view_schema: &HashMap<String, ColumnType>,
    ) -> ApiResult<()> {
        self.as_mut().ok_or("No `Table` set")?.view_schema = Some(view_schema.clone());
        Ok(())
    }

    /// Records the pre-aggregation types of the config's window columns, so
    /// `get_column_table_type` resolves them like any other derived column.
    pub(super) fn update_windows(
        &mut self,
        windows: &perspective_client::config::Windows,
    ) -> ApiResult<()> {
        let window_schema = windows
            .iter()
            .filter_map(|(name, w)| {
                let source = self.get_column_table_type(&w.column)?;
                let dtype = self
                    .get_window_aggregate(source, &w.aggregate)
                    .and_then(|spec| spec.result_type)
                    .and_then(|ty| ColumnType::try_from(ty).ok())
                    .unwrap_or(source);

                Some((name.clone(), dtype))
            })
            .collect();
        self.as_mut().ok_or("No `Table` set")?.window_schema = window_schema;
        Ok(())
    }

    /// The declaration for one window aggregate over a `source` column type.
    pub fn get_window_aggregate(
        &self,
        source: ColumnType,
        name: &str,
    ) -> Option<perspective_client::proto::WindowAggregateArgs> {
        self.get_features()?
            .get_window_aggregates(source)
            .into_iter()
            .find(|x| x.name == name)
    }

    /// Whether `view_schema` has been populated by a prior successful
    /// `create_view`. Used by `Session::create_view` to force a full
    /// build on first run even when `is_clean` happens to be true, so
    /// that downstream consumers (`query_column_config_schema`,
    /// strip-on-write in `update_columns_configs`) always see a real
    /// view schema rather than `None`.
    pub fn has_view_schema(&self) -> bool {
        self.as_ref().and_then(|s| s.view_schema.as_ref()).is_some()
    }

    pub(super) fn update_expressions(
        &mut self,
        valid_recs: &perspective_client::ExprValidationResult,
    ) -> ApiResult<HashSet<String>> {
        if !valid_recs.errors.is_empty() {
            return Err(apierror!(InvalidViewerConfigExpressionsError(
                valid_recs.clone().into(),
            )));
        }

        let state = self.as_mut().ok_or("No `Table` set")?;
        let mut edited = state.expr_meta.take().map(|x| x.edited).unwrap_or_default();

        edited.retain(|k, _| valid_recs.expression_alias.contains_key(k));
        state.expr_meta = Some(SessionViewExpressionMetadata {
            expressions: valid_recs.clone(),
            edited,
        });

        Ok(valid_recs.expression_schema.keys().cloned().collect())
    }

    /// Get the `Table`'s supported features.
    pub fn get_features(&self) -> Option<&'_ perspective_client::Features> {
        Some(&self.as_ref()?.features)
    }

    /// Returns the unique column names in this session that are expression
    /// columns.
    pub fn get_expression_schema(&self) -> Option<&HashMap<String, ColumnType>> {
        Some(
            &self
                .as_ref()?
                .expr_meta
                .as_ref()?
                .expressions
                .expression_schema,
        )
    }

    pub fn get_expression_columns(&self) -> impl Iterator<Item = &'_ String> {
        let mut columns = try {
            self.as_ref()?
                .expr_meta
                .as_ref()?
                .expressions
                .expression_schema
                .keys()
        }
        .into_iter()
        .flatten()
        .collect::<Vec<_>>();

        columns.sort_unstable();
        columns.into_iter()
    }

    /// Returns the full original expression `String` for an expression alias.
    /// TODO should expressions be `Rc`?
    ///
    /// # Arguments
    /// - `alias` An alias name for an expression column in this `Session`.
    pub fn get_expression_by_alias(&self, alias: &str) -> Option<String> {
        self.as_ref()?
            .expr_meta
            .as_ref()?
            .expressions
            .expression_alias
            .get(alias)
            .cloned()
    }

    /// Returns the edited expression `String` (e.g. the not-yet-saved, edited
    /// expression state of a column, if any) for an expression alias.
    ///
    /// # Arguments
    /// - `alias` An alias name for an expression column in this `Session`.
    pub fn get_edit_by_alias(&self, alias: &str) -> Option<String> {
        try {
            self.as_ref()?
                .expr_meta
                .as_ref()?
                .edited
                .get(alias)
                .cloned()?
        }
    }

    pub fn set_edit_by_alias(&mut self, alias: &str, edit: String) {
        let _: Option<_> = try {
            self.as_mut()?
                .expr_meta
                .as_mut()?
                .edited
                .insert(alias.to_owned(), edit)
        };
    }

    pub fn clear_edit_by_alias(&mut self, alias: &str) {
        let _: Option<_> = try { self.as_mut()?.expr_meta.as_mut()?.edited.remove(alias) };
    }

    pub fn get_table_columns(&self) -> Option<&'_ Vec<String>> {
        self.as_ref().map(|meta| &meta.column_names)
    }

    pub fn is_column_window(&self, name: &str) -> bool {
        self.as_ref()
            .map(|meta| meta.window_schema.contains_key(name))
            .unwrap_or_default()
    }

    pub fn get_window_columns(&self) -> impl Iterator<Item = &'_ String> {
        self.as_ref()
            .map(|meta| meta.window_schema.keys())
            .into_iter()
            .flatten()
    }

    pub fn is_column_expression(&self, name: &str) -> bool {
        let is_expr: Option<bool> = try {
            self.as_ref()?
                .expr_meta
                .as_ref()?
                .expressions
                .expression_schema
                .contains_key(name)
        };

        is_expr.unwrap_or_default()
    }

    /// Creates a new column name by appending a numeral corresponding to the
    /// number of columns with that name.
    pub fn make_new_column_name(&self, col: Option<&str>) -> String {
        let mut i = 0;
        loop {
            i += 1;
            let name = format!("{} {i}", col.unwrap_or("New Column"));
            if self.get_column_table_type(&name).is_none() {
                return name;
            }
        }
    }

    pub fn get_edit_port(&self) -> Option<f64> {
        self.as_ref().map(|meta| meta.edit_port)
    }

    /// The type of a column of the `Table` itself — expression and window
    /// columns, which belong to a config, excluded.
    pub fn get_table_schema_type(&self, name: &str) -> Option<ColumnType> {
        self.as_ref()?.table_schema.get(name).copied()
    }

    /// Returns the type of a column name relative to the `Table`.  Despite the
    /// name, `get_column_table_type()` also returns the `Table` type for
    /// Expressions, which despite living on the `View` still have a `table`
    /// type associated with them pre-aggregation.
    ///
    /// # Arguments
    /// - `name` The column name (or expresison alias) to retrieve a principal
    ///   type.
    pub fn get_column_table_type(&self, name: &str) -> Option<ColumnType> {
        try {
            let meta = self.as_ref()?;
            meta.table_schema
                .get(name)
                .cloned()
                .or_else(|| {
                    meta.expr_meta
                        .as_ref()?
                        .expressions
                        .expression_schema
                        .get(name)
                        .cloned()
                })
                .or_else(|| meta.window_schema.get(name).cloned())?
        }
    }

    /// Returns the type of a column name relative to the `View`, including
    /// expression columns which were part of the `ViewConfig`.  Types
    /// returned from the `View` incorporate the type transform applied by
    /// their aggregate if applicable, so may differ from the type returned
    /// by `get_column_table_type()`.
    ///
    /// # Arguments
    /// - `name` The column name (or expresison alias) to retrieve a `View`
    ///   type.
    pub fn get_column_view_type(&self, name: &str) -> Option<ColumnType> {
        let r: Option<&ColumnType> = try { self.as_ref()?.view_schema.as_ref()?.get(name)? };
        r.cloned()
    }

    /// Returns the column name for a locator, generating a default for new
    /// expressions.
    pub fn locator_name_or_default(&self, locator: &ColumnLocator) -> String {
        match locator {
            ColumnLocator::Table(s) | ColumnLocator::Expression(s) | ColumnLocator::Window(s) => {
                s.clone()
            },
            ColumnLocator::NewExpression => self.make_new_column_name(None),
        }
    }

    /// Returns the view type for a locator's column, if available.
    pub fn locator_view_type(&self, locator: &ColumnLocator) -> Option<ColumnType> {
        let name = locator.name().cloned().unwrap_or_default();
        self.get_column_view_type(name.as_str())
    }

    pub fn get_column_aggregates<'a>(
        &'a self,
        name: &str,
    ) -> Option<Box<dyn Iterator<Item = Aggregate> + 'a>> {
        let coltype = self.get_column_table_type(name)?;
        let f = self.get_features()?.aggregates.get(&(coltype as u32))?;

        let aggregates = f
            .aggregates
            .iter()
            .flat_map(move |x| {
                if x.args.is_empty() {
                    Some(vec![Aggregate::SingleAggregate(x.name.to_string())])
                } else {
                    // todo: handle multi args
                    let dtype = x.args.first().unwrap();
                    Some(
                        self.get_expression_columns()
                            .cloned()
                            .chain(self.get_table_columns()?.clone())
                            .map(move |name| {
                                self.get_column_table_type(&name)
                                    .map(|coltype| (name, coltype))
                            })
                            .collect::<Option<Vec<_>>>()?
                            .into_iter()
                            .filter(move |(_, coltype)| {
                                *coltype as i32 == *dtype
                                    || (coltype == &ColumnType::Integer
                                        && *dtype == ColumnType::Float as i32)
                                    || (coltype == &ColumnType::Float
                                        && *dtype == ColumnType::Integer as i32)
                            })
                            .map(|(name, _)| {
                                Aggregate::MultiAggregate(x.name.to_string(), vec![name])
                            })
                            .collect(),
                    )
                }
            })
            .flatten();

        Some(Box::new(aggregates))
    }
}