perspective-viewer 5.2.0

A data visualization and analytics component, especially well-suited for large and/or 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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
// ┃ ██████ ██████ ██████       █      █      █      █      █ █▄  ▀███ █       ┃
// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█  ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄  ▀█ █ ▀▀▀▀▀ ┃
// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄   █ ▄▄▄▄▄ ┃
// ┃ █      ██████ █  ▀█▄       █ ██████      █      ███▌▐███ ███████▄ █       ┃
// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
// ┃ 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::HashSet;
use std::marker::PhantomData;

use derivative::Derivative;
use perspective_client::proto::ColumnType;
use web_sys::*;
use yew::html::Scope;
use yew::prelude::*;

use crate::components::column_dropdown::ColumnDropDownElement;
use crate::components::column_selector::{EmptyColumn, InPlaceColumn, InvalidColumn};
use crate::components::type_icon::TypeIcon;
use crate::presentation::{DragDropContainer, Presentation};
use crate::utils::DragTarget;

#[derive(Properties, Derivative)]
#[derivative(Clone(bound = ""))]
pub struct DragDropListProps<T, U>
where
    T: Component,
    U: Component,
    <U as Component>::Properties: DragDropListItemProps,
{
    pub parent: Scope<T>,

    pub presentation: Presentation,
    pub name: &'static str,
    pub column_dropdown: ColumnDropDownElement,
    pub exclude: HashSet<String>,
    pub children: ChildrenWithProps<U>,

    #[prop_or_default]
    pub disabled: bool,

    #[prop_or_default]
    pub is_dragover: Option<(
        usize,
        <<U as Component>::Properties as DragDropListItemProps>::Item,
    )>,

    #[prop_or_default]
    pub allow_duplicates: bool,

    /// Single-slot mode: the list holds at most one item, a dragover
    /// preview REPLACES the current item rather than inserting beside it,
    /// and the trailing `EmptyColumn` autocomplete renders only while the
    /// slot is empty.
    #[prop_or_default]
    pub single_slot: bool,

    /// The plugin-declared visual role this slot fills, e.g. `"X Axis"`
    /// for a `Y Line`'s `group_by` (see `PluginStaticConfig`). Rendered
    /// as the slot's label THROUGH the intl indirection: the role is a
    /// key, not display text, so `--psp-label--role--x-axis--content`
    /// supplies the words and a language variant can override them. A
    /// role with no such label falls back to the declared English, and
    /// no role at all falls back to the slot's own generic label.
    #[prop_or_default]
    pub role_label: Option<AttrValue>,

    /// The in-flight drag is INVALID for this list (a parent-defined rule,
    /// e.g. the window editor's Table-columns-only slots): the dragover
    /// preview is suppressed and the invalid-X overlay renders instead,
    /// like a duplicate drag over `group_by`/`split_by`. The parent's drop
    /// handler is still responsible for ignoring the drop itself.
    #[prop_or_default]
    pub is_invalid: bool,
}

impl<T, U> PartialEq for DragDropListProps<T, U>
where
    T: Component,
    U: Component,
    <U as Component>::Properties: DragDropListItemProps,
{
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
            && self.children == other.children
            && self.allow_duplicates == other.allow_duplicates
            && self.is_dragover == other.is_dragover
            && self.disabled == other.disabled
            && self.single_slot == other.single_slot
            && self.is_invalid == other.is_invalid
            && self.role_label == other.role_label
    }
}

pub enum DragDropListMsg {
    Freeze(bool),
}

/// A sub-selector for a list-like component of a `JsViewConfig`, such as
/// `filters` and `sort`.  
///
/// `DragDropList` is parameterized by two `Component`
/// types, the parent component `T` and the inner item compnent `U`, which must
/// additionally implement `DragDropListItemProps` trait on its own `Properties`
/// associated type.
///
/// Before you ask:  yes, `frozen_size` needs to be a float64 since `flex`
/// containers can have fractional dimensions.
pub struct DragDropList<T, U, V>
where
    T: Component,
    U: Component,
    <U as Component>::Properties: DragDropListItemProps,
    V: DragContext<T::Message> + 'static,
{
    parent_type: PhantomData<T>,
    item_type: PhantomData<U>,
    draggable_type: PhantomData<V>,
    elem: NodeRef,
    frozen_size: Option<f64>,
}

impl<T, U, V> Component for DragDropList<T, U, V>
where
    T: Component,
    U: Component,
    <U as Component>::Properties: DragDropListItemProps,
    V: DragContext<T::Message> + 'static,
{
    type Message = DragDropListMsg;
    type Properties = DragDropListProps<T, U>;

    fn create(_ctx: &Context<Self>) -> Self {
        Self {
            parent_type: PhantomData,
            item_type: PhantomData,
            draggable_type: PhantomData,
            elem: NodeRef::default(),
            frozen_size: None,
        }
    }

    fn changed(&mut self, _ctx: &Context<Self>, _old: &Self::Properties) -> bool {
        true
    }

    fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
        match msg {
            // When a dragover occurs and a new Column is inserted into the selector,
            // the geometry of the selector may expand and cause a parent reflow,
            // which annoyingly changes the drag status and glitchiness occurs.
            // By using `Freeze` when a dragenter occurs, the element's width will be
            // frozen until `drop` or `dragleave`.
            DragDropListMsg::Freeze(freeze) => {
                if freeze && self.frozen_size.is_none() {
                    let elem = self.elem.cast::<HtmlElement>().unwrap();
                    self.frozen_size = Some({
                        // `offset_width` and family are `i32`, but Chrome _really_
                        // uses fractional pixel widths for these which can only be
                        // recovered by parsing the generated stylesheet ...
                        let txt = window()
                            .unwrap()
                            .get_computed_style(&elem)
                            .unwrap()
                            .unwrap()
                            .get_property_value("width")
                            .unwrap();

                        // Strip "px" suffix, e.g. "24.876px".
                        let px = &txt[..txt.len() - 2];
                        px.parse::<f64>().unwrap()
                    });
                    true
                } else if !freeze {
                    // Don't render because the invoker will do so through `dragdrop`.
                    self.frozen_size = None;
                    false
                } else {
                    false
                }
            },
        }
    }

    fn view(&self, ctx: &Context<Self>) -> Html {
        let dragover = Callback::from(|_event: DragEvent| _event.prevent_default());

        // On dragleave, signal the parent but no need to redraw as parent will call
        // `change()` when resetting props.
        let drag_container = DragDropContainer::new(
            {
                let total = ctx.props().children.len();
                let parent = ctx.props().parent.clone();
                let link = ctx.link().clone();
                move || {
                    link.send_message(DragDropListMsg::Freeze(true));
                    parent.send_message(V::dragenter(total))
                }
            },
            {
                let parent = ctx.props().parent.clone();
                let link = ctx.link().clone();
                move || {
                    link.send_message(DragDropListMsg::Freeze(false));
                    parent.send_message(V::dragleave())
                }
            },
        );

        let drop = Callback::from({
            let presentation = ctx.props().presentation.clone();
            let link = ctx.link().clone();
            move |event| {
                link.send_message(DragDropListMsg::Freeze(false));
                presentation.notify_drop(&event);
            }
        });

        // Held by per-row `ondragenter` closures below so they can re-arm
        // the `safaridragleave` flag on the container element when the
        // row stops dragenter from bubbling. See the comment inside the
        // closure for why this matters.
        let container_noderef = drag_container.noderef.clone();

        let invalid_drag: bool;
        let mut valid_duplicate_drag = false;

        let columns_html = if ctx.props().single_slot {
            invalid_drag = ctx.props().is_invalid && ctx.props().is_dragover.is_some();

            // Dragging the slot's own pill over its own slot is a no-op
            // move - keep showing the pill instead of the drop preview
            // (mirrors the multi-column branch's `is_self_move` handling).
            let is_self_move = ctx
                .props()
                .presentation
                .get_drag_target()
                .map(|x| V::is_self_move(x))
                .unwrap_or_default();

            let close = ctx.props().parent.callback(|_| V::close(0));
            let dragenter = ctx.props().parent.callback({
                let container_noderef = container_noderef.clone();
                move |event: DragEvent| {
                    event.stop_propagation();
                    event.prevent_default();
                    if event.related_target().is_none()
                        && let Some(elem) = container_noderef.cast::<HtmlElement>()
                    {
                        let _ = elem.dataset().set("safaridragleave", "true");
                    }
                    V::dragenter(0)
                }
            });

            if ctx.props().is_dragover.is_some() && !is_self_move && !invalid_drag {
                html! {
                    <div class="pivot-column" ondragenter={dragenter}>
                        <div class="config-drop" />
                    </div>
                }
            } else if let Some(column) = ctx.props().children.iter().next() {
                html! {
                    <div class="pivot-column" ondragenter={dragenter}>
                        { Html::from(column) }
                        <span class="row_close" onmousedown={close} />
                    </div>
                }
            } else {
                html! {}
            }
        } else {
            let mut columns = ctx
                .props()
                .children
                .iter()
                .map(|x| (true, Some(x)))
                .enumerate()
                .collect::<Vec<_>>();

            invalid_drag = if ctx.props().is_invalid && ctx.props().is_dragover.is_some() {
                // Parent-defined invalidity: no preview, X overlay only.
                true
            } else if let Some((x, column)) = &ctx.props().is_dragover {
                let index = *x;
                let is_append = index == columns.len();
                let is_self_move = ctx
                    .props()
                    .presentation
                    .get_drag_target()
                    .map(|x| V::is_self_move(x))
                    .unwrap_or_default();

                let is_duplicate = columns
                    .iter()
                    .position(|x| x.1.1.as_ref().unwrap().props.get_item() == *column);

                valid_duplicate_drag = is_duplicate.is_some() && !ctx.props().allow_duplicates;
                if let Some(duplicate) = is_duplicate
                    && !is_append
                    && (!ctx.props().allow_duplicates || is_self_move)
                {
                    columns.remove(duplicate);
                }

                // If inserting into the middle of the list, use
                // the length of the existing element to prevent
                // jitter as the underlying dragover zone moves.
                if index < columns.len() {
                    columns.insert(index, (usize::MAX, (false, None)));
                    false
                } else if (!is_append && !ctx.props().allow_duplicates)
                    || ((!is_append || !is_self_move)
                        && (is_duplicate.is_none() || ctx.props().allow_duplicates))
                {
                    columns.push((usize::MAX, (false, None)));
                    false
                } else {
                    true
                }
            } else {
                false
            };

            columns
                .into_iter()
                .enumerate()
                .map(|(idx, column)| {
                    let close = ctx.props().parent.callback(move |_| V::close(idx));
                    let dragenter = ctx.props().parent.callback({
                        let link = ctx.link().clone();
                        let container_noderef = container_noderef.clone();
                        move |event: DragEvent| {
                            event.stop_propagation();
                            event.prevent_default();
                            // Safari: `relatedTarget` is always null on
                            // dragleave, so `dragleave_helper` uses a
                            // `data-safaridragleave` flag set by the
                            // container's own dragenter to distinguish
                            // child-crossing leaves (consume the flag)
                            // from real leaves (no flag → fire callback).
                            // The `stop_propagation` above blocks the
                            // container's dragenter, so the flag would
                            // never be re-armed after the first consume —
                            // any further internal boundary crossing
                            // would demote the state out of
                            // `DragOverInProgress` and the next drop
                            // would be silently rejected. Set the flag
                            // here so each row-targeted dragenter
                            // refills the pool.
                            if event.related_target().is_none()
                                && let Some(elem) = container_noderef.cast::<HtmlElement>()
                            {
                                let _ = elem.dataset().set("safaridragleave", "true");
                            }
                            link.send_message(DragDropListMsg::Freeze(true));
                            V::dragenter(idx)
                        }
                    });

                    if let (key, (true, Some(column))) = column {
                        html! {
                            <div {key} class="pivot-column" ondragenter={dragenter}>
                                { Html::from(column) }
                                <span class="row_close" onmousedown={close} />
                            </div>
                        }
                    } else if let (key, (_, Some(column))) = column {
                        html! {
                            <div {key} class="pivot-column" ondragenter={dragenter}>
                                { Html::from(column) }
                                <span class="row_close" style="opacity: 0.3" />
                            </div>
                        }
                    } else {
                        let (key, _) = column;
                        html! {
                            <div {key} class="pivot-column" ondragenter={dragenter}>
                                <div class="config-drop" />
                            </div>
                        }
                    }
                })
                .collect::<Html>()
        };

        let show_empty = if ctx.props().single_slot {
            ctx.props().children.is_empty() && ctx.props().is_dragover.is_none()
        } else {
            ctx.props().is_dragover.is_none() | (!invalid_drag && valid_duplicate_drag)
        };

        let column_dropdown = ctx.props().column_dropdown.clone();
        let exclude = ctx.props().exclude.clone();
        let on_select = ctx.props().parent.callback(V::create);
        let class = classes!("rrow");
        let is_enabled = true;

        // The role is data from the plugin, so the var NAME is built
        // here while the var VALUE stays in the stylesheets - custom
        // properties inherit, so the label's `:before` picks it up.
        let role_style = ctx.props().role_label.as_ref().map(|role| {
            let slug = role
                .chars()
                .map(|x| {
                    if x.is_ascii_alphanumeric() {
                        x.to_ascii_lowercase()
                    } else {
                        '-'
                    }
                })
                .collect::<String>();

            // The second var is a PRESENCE FLAG: CSS cannot ask whether a
            // custom property is set, so the slot's stylesheet reads it as
            // the secondary label's `display` and gets `none` by fallback
            // when no role was declared.
            format!(
                "--psp-label--pivot--content: var(--psp-label--role--{slug}--content, \
                 \"{role}\"); --psp-label--pivot-secondary--display: inline-block"
            )
        });

        html! {
            <div ref={&self.elem} {class}>
                <div
                    id={ctx.props().name}
                    style={role_style}
                    ondragover={is_enabled.then_some(dragover)}
                    ondragenter={is_enabled.then_some(drag_container.dragenter)}
                    ondragleave={is_enabled.then_some(drag_container.dragleave)}
                    ref={drag_container.noderef}
                    ondrop={is_enabled.then_some(drop)}
                >
                    <div class="psp-text-field">
                        <ul class="psp-text-field__input" for={ctx.props().name}>
                            { columns_html }
                            if ctx.props().disabled && ctx.props().is_dragover.is_none() {
                                <div class="pivot-column">
                                    <div class="pivot-column-border pivot-column-total">
                                        <span class="drag-handle icon" />
                                        <TypeIcon ty={ColumnType::Integer} />
                                        <span class="column_name">{ "TOTAL" }</span>
                                    </div>
                                    <span
                                        class="toggle-mode is_column_active"
                                        onmousedown={ctx.props().parent.callback(move |_| V::close(0))}
                                    />
                                </div>
                            } else if show_empty {
                                <EmptyColumn {column_dropdown} {exclude} {on_select} />
                            } else if invalid_drag {
                                <InvalidColumn />
                            }
                        </ul>
                        <label class="pivot-selector-label" for={ctx.props().name} />
                    </div>
                </div>
            </div>
        }
    }
}

/// Must be implemented by `Properties` of children of `DragDropList`, returning
/// the value a DragDropItem represents.
pub trait DragDropListItemProps: Properties {
    type Item: Clone + PartialEq;
    fn get_item(&self) -> Self::Item;
}

pub trait DragContext<T> {
    fn close(index: usize) -> T;
    fn dragleave() -> T;
    fn dragenter(index: usize) -> T;
    fn create(col: InPlaceColumn) -> T;
    fn is_self_move(effect: DragTarget) -> bool;
}