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

//! Panel-lifecycle handlers: the [`Workspace`] panel set (add / duplicate /
//! close) and active-panel targeting. INVARIANT: app-initiated layout changes
//! mutate the `Workspace` FIRST, synchronously — `regular-layout` is
//! reconciled as a downstream consequence of the re-render, never the source
//! of truth (see `ClosePanel`).
//!
//! [`Workspace`]: crate::workspace::Workspace

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

use super::PerspectiveViewer;
use super::msg::PerspectiveViewerMsg::*;
use super::wiring::{
    clear_active_callbacks, create_active_subscriptions, inject_active_callbacks,
    subscribe_panel_titles,
};
use crate::config::{DecodeConfig, ViewerConfigInitial};
use crate::derived::suggest_name;
use crate::queries::*;
use crate::renderer::Renderer;
use crate::session::*;
use crate::tasks::*;
use crate::utils::{Completion, PtrEqRc, spawn_owned};
use crate::workspace::{Panel, PanelId};

impl PerspectiveViewer {
    pub(super) fn on_layout_changed(&mut self, ctx: &Context<Self>) -> bool {
        self._title_subscriptions = subscribe_panel_titles(ctx);
        self.resync_active(ctx);
        true
    }

    /// Level-triggered binding sync: re-point the root's engine bindings at
    /// the model's *current* active panel (or the detached empty engines at
    /// zero panels) when they differ, by `Rc` identity. Catches model-side
    /// activations that never dispatch `SetActivePanel`.
    fn resync_active(&mut self, ctx: &Context<Self>) -> bool {
        let session = ctx
            .props()
            .workspace
            .active_session()
            .unwrap_or_else(|| self.empty_session.clone());
        let renderer = ctx
            .props()
            .workspace
            .active_renderer()
            .unwrap_or_else(|| self.empty_renderer.clone());

        if session == self.active_session && renderer == self.active_renderer {
            false
        } else {
            self.retarget_active(ctx, session, renderer);
            true
        }
    }

    pub(super) fn on_set_active_panel(
        &mut self,
        ctx: &Context<Self>,
        id: String,
        completion: Option<Completion>,
    ) -> bool {
        let id = PanelId::from(id);
        let prev = ctx.props().workspace.active_id();
        if prev.as_ref() != Some(&id) && ctx.props().workspace.panel(&id).is_some() {
            ctx.props().presentation.set_open_column_settings(None);
        }

        if prev.as_ref() == Some(&id) || !ctx.props().workspace.set_active(id.clone()) {
            let resynced = self.resync_active(ctx);
            if let Some(completion) = completion {
                completion.resolve_after(async { Ok(()) });
            }

            resynced
        } else {
            let new_session = ctx
                .props()
                .workspace
                .active_session()
                .unwrap_or_else(|| self.empty_session.clone());

            let new_renderer = ctx
                .props()
                .workspace
                .active_renderer()
                .unwrap_or_else(|| self.empty_renderer.clone());

            self.retarget_active(ctx, new_session, new_renderer);
            let mut nudges = Vec::new();
            for pid in prev.iter().chain(std::iter::once(&id)) {
                if let Some(panel) = ctx.props().workspace.panel(pid)
                    && panel.renderer.is_plugin_activated().unwrap_or(false)
                {
                    nudges.push(activation_render(
                        panel.session.clone(),
                        panel.renderer.clone(),
                    ));
                }
            }

            let run = async move {
                futures::future::join_all(nudges)
                    .await
                    .into_iter()
                    .collect::<ApiResult<Vec<_>>>()?;
                Ok(())
            };

            match completion {
                Some(completion) => completion.resolve_after(run),
                None => spawn_owned("set-active-panel", run),
            }

            true
        }
    }

    /// `restoreWorkspace`'s single commit: the `Workspace` already holds
    /// the final panel set (models inserted, olds ejected) and the staged
    /// layout. Re-subscribe the per-panel title wiring (the set changed
    /// wholesale), activate the restored panel, and re-render — `MainPanel`'s
    /// `rendered` pass applies the staged layout and mounts every cell in
    /// this one commit.
    pub(super) fn on_commit_workspace_restore(&mut self, ctx: &Context<Self>, id: String) -> bool {
        self._title_subscriptions = subscribe_panel_titles(ctx);
        self.on_set_active_panel(ctx, id, None);
        true
    }

    /// Remove `id` from the workspace and return the detached [`Panel`] with
    /// its engines still alive, or `None` for an unknown id.
    fn detach_panel(&mut self, ctx: &Context<Self>, id: &PanelId) -> Option<Panel> {
        let was_active = ctx.props().workspace.active_id().as_ref() == Some(id);
        if was_active {
            ctx.props().presentation.set_open_column_settings(None);
        }

        let removed = ctx.props().workspace.remove_panel(id)?;
        if was_active {
            if let Some(next) = ctx.props().workspace.panel_ids().first().cloned() {
                ctx.props().workspace.set_active(next);
            }

            let new_session = ctx
                .props()
                .workspace
                .active_session()
                .unwrap_or_else(|| self.empty_session.clone());
            let new_renderer = ctx
                .props()
                .workspace
                .active_renderer()
                .unwrap_or_else(|| self.empty_renderer.clone());
            self.retarget_active(ctx, new_session, new_renderer);
        }

        apply_global_filters(&ctx.props().workspace);
        self._title_subscriptions = subscribe_panel_titles(ctx);
        Some(removed)
    }

    pub(super) fn on_close_panel(
        &mut self,
        ctx: &Context<Self>,
        id: String,
        completion: Option<Completion>,
    ) -> bool {
        let id = PanelId::from(id);
        let Some(removed) = self.detach_panel(ctx, &id) else {
            if let Some(completion) = completion {
                completion.resolve_after(async { Ok(()) });
            }

            return false;
        };

        ctx.props().workspace.stash_closing(removed);
        if let Some(completion) = completion {
            self.pending_closes.insert(id, completion);
        }

        true
    }

    pub(super) fn on_panel_closed(&mut self, ctx: &Context<Self>, id: String) -> bool {
        let id = PanelId::from(id);
        if let Some(panel) = ctx.props().workspace.take_closing(&id) {
            let eject = eject_panel(panel, Disposal::Reject);
            match self.pending_closes.remove(&id) {
                Some(completion) => completion.resolve_after(eject),
                None => spawn_owned("close-panel", eject),
            }

            return false;
        }

        match self.detach_panel(ctx, &id) {
            Some(panel) => {
                spawn_owned("close-panel", eject_panel(panel, Disposal::Reject));
                true
            },
            None => false,
        }
    }

    pub(super) fn on_duplicate_panel(&mut self, ctx: &Context<Self>, id: String) -> bool {
        if let Some(panel) = ctx.props().workspace.panel(&PanelId::from(id)) {
            let elem = ctx.props().elem.clone();
            let presentation = ctx.props().presentation.clone();
            let workspace = ctx.props().workspace.clone();
            let notify = ctx.link().callback(|_: ()| LayoutChanged);
            let activate = ctx.link().callback(|id| SetActivePanel(id, None));
            let effect = workspace.effects().guard();
            ApiFuture::spawn(async move {
                let _effect = effect;
                let config = panel
                    .renderer
                    .clone()
                    .with_lock(async {
                        get_viewer_config(&panel.session, &panel.renderer, &presentation).await
                    })
                    .await?;

                // TODO(texodus): what the ****?
                let update = ViewerConfigInitial::decode(&JsValue::from_serde_ext(&config.panel)?)?;
                let client = panel.session.get_client();
                let new_id = create_panel(
                    &elem,
                    &presentation,
                    &workspace,
                    &notify,
                    None,
                    update,
                    client,
                    crate::session::MissingTable::Error,
                )
                .await?;

                activate.emit(new_id.to_string());
                Ok(())
            });
        }

        false
    }

    pub(super) fn on_derive_panel(&mut self, ctx: &Context<Self>, id: String) -> bool {
        if let Some(panel) = ctx.props().workspace.panel(&PanelId::from(id)) {
            let presentation = ctx.props().presentation.clone();
            let workspace = ctx.props().workspace.clone();
            let effect = workspace.effects().guard();
            ApiFuture::spawn(async move {
                let _effect = effect;
                let config = PtrEqRc::new(panel.session.get_view_config().clone());
                let table = panel.session.get_table().map(|x| x.get_name().to_owned());
                let name = suggest_name(
                    &fetch_hosted_tables(&workspace)
                        .await
                        .into_iter()
                        .flat_map(|(_, tables)| tables)
                        .collect(),
                    &config,
                    &table,
                );

                create_derived(
                    &panel.session,
                    &panel.renderer,
                    &presentation,
                    &workspace,
                    name,
                )
                .await
            });
        }

        false
    }

    pub(super) fn on_new_panel(&mut self, ctx: &Context<Self>, id: String) -> bool {
        if let Some(panel) = ctx.props().workspace.panel(&PanelId::from(id)) {
            let Some(table_name) = panel.session.get_table().map(|t| t.get_name().to_owned())
            else {
                tracing::warn!("Source panel has no `Table` to create a new panel from");
                return false;
            };

            let elem = ctx.props().elem.clone();
            let presentation = ctx.props().presentation.clone();
            let workspace = ctx.props().workspace.clone();
            let notify = ctx.link().callback(|_: ()| LayoutChanged);
            let activate = ctx.link().callback(|id| SetActivePanel(id, None));
            let effect = workspace.effects().guard();
            ApiFuture::spawn(async move {
                let _effect = effect;
                let client = panel.session.get_client();
                let new_id = create_panel(
                    &elem,
                    &presentation,
                    &workspace,
                    &notify,
                    None,
                    ViewerConfigInitial::new(table_name),
                    client,
                    crate::session::MissingTable::Error,
                )
                .await?;

                activate.emit(new_id.to_string());
                Ok(())
            });
        }
        false
    }

    /// `NewPanelFrom` — the context menu's "New" sub-menu: a fresh
    /// (default-config) panel bound to the named `Table` on the named
    /// `Client`, resolved from the `Workspace` loaded-clients registry.
    pub(super) fn on_new_panel_from(
        &mut self,
        ctx: &Context<Self>,
        client_name: String,
        table: String,
    ) -> bool {
        let Some(client) = ctx
            .props()
            .workspace
            .clients()
            .into_iter()
            .find(|c| c.get_name() == client_name)
        else {
            tracing::warn!("No loaded `Client` named \"{client_name}\"");
            return false;
        };

        let elem = ctx.props().elem.clone();
        let presentation = ctx.props().presentation.clone();
        let workspace = ctx.props().workspace.clone();
        let notify = ctx.link().callback(|_: ()| LayoutChanged);
        let activate = ctx.link().callback(|id| SetActivePanel(id, None));
        let effect = workspace.effects().guard();
        ApiFuture::spawn(async move {
            let _effect = effect;
            let new_id = create_panel(
                &elem,
                &presentation,
                &workspace,
                &notify,
                None,
                ViewerConfigInitial::new(table),
                Some(client),
                crate::session::MissingTable::Error,
            )
            .await?;

            activate.emit(new_id.to_string());
            Ok(())
        });

        false
    }

    /// Re-point the root's per-active engine wiring + snapshots from the
    /// current active panel to a new one: clear the old panel's direct
    /// callbacks, set up the new panel's callbacks + subscriptions, refresh
    /// the snapshots, and reset the in-flight render counter (which tracked
    /// the old panel).
    fn retarget_active(&mut self, ctx: &Context<Self>, session: Session, renderer: Renderer) {
        clear_active_callbacks(&self.active_session, &self.active_renderer);
        inject_active_callbacks(ctx, &session, &renderer);
        self._active_subscriptions = create_active_subscriptions(ctx, &session, &renderer);
        self.session_props = session.to_props();
        self.renderer_props = renderer.to_props(None);
        self.update_count = session.config_runs.count();
        self.active_session = session;
        self.active_renderer = renderer;
        let presentation = ctx.props().presentation.clone();
        let workspace = ctx.props().workspace.clone();
        ApiFuture::spawn(async move {
            // Only an EXPLICITLY themed panel mirrors onto the host; an
            // unpinned one inherits whatever the host already shows, so
            // activating it must not restate (and thereby pin) that value.
            if let Some(theme) = workspace.active_renderer().and_then(|x| x.theme()) {
                presentation.set_theme_name(Some(&theme)).await?;
                presentation.publish_theme_config().await?;
            }

            Ok(())
        });
    }
}