aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/nodes/DataVizBox/components/TableBox.tsx
blob: 3e7d3af8c27f71884685475f4be0eebf3e920eb4 (plain)
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
import { Button, Type } from 'browndash-components';
import { action, computed, IReactionDisposer, observable, reaction, trace } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import { Doc, Field, NumListCast } from '../../../../../fields/Doc';
import { List } from '../../../../../fields/List';
import { listSpec } from '../../../../../fields/Schema';
import { Cast, DocCast } from '../../../../../fields/Types';
import { emptyFunction, setupMoveUpEvents, Utils } from '../../../../../Utils';
import { DragManager } from '../../../../util/DragManager';
import { DocumentView } from '../../DocumentView';
import { DataVizView } from '../DataVizBox';
import './Chart.scss';
const {  default: { DATA_VIZ_TABLE_ROW_HEIGHT } } = require('../../../global/globalCssVariables.module.scss'); // prettier-ignore
interface TableBoxProps {
    Document: Doc;
    layoutDoc: Doc;
    records: { [key: string]: any }[];
    selectAxes: (axes: string[]) => void;
    axes: string[];
    width: number;
    height: number;
    margin: {
        top: number;
        right: number;
        bottom: number;
        left: number;
    };
    docView?: () => DocumentView | undefined;
}

@observer
export class TableBox extends React.Component<TableBoxProps> {
    _inputChangedDisposer?: IReactionDisposer;
    _containerRef: HTMLDivElement | null = null;

    @observable _scrollTop = -1;
    @observable _tableHeight = 0;
    @observable _tableContainerHeight = 0;

    componentDidMount() {
        // if the tableData changes (ie., when records are selected by the parent (input) visulization),
        // then we need to remove any selected rows that are no longer part of the visualized dataset.
        this._inputChangedDisposer = reaction(() => this._tableData.slice(), this.filterSelectedRowsDown, { fireImmediately: true });
        this.handleScroll();
    }
    componentWillUnmount() {
        this._inputChangedDisposer?.();
    }
    @computed get _tableDataIds() {
        return !this.parentViz ? this.props.records.map((rec, i) => i) : NumListCast(this.parentViz.dataViz_selectedRows);
    }
    // returns all the data records that will be rendered by only returning those records that have been selected by the parent visualization (or all records if there is no parent)
    @computed get _tableData() {
        return !this.parentViz ? this.props.records : this._tableDataIds.map(rowId => this.props.records[rowId]);
    }

    @computed get parentViz() {
        return DocCast(this.props.Document.dataViz_parentViz);
        // return LinkManager.Instance.getAllRelatedLinks(this.props.Document) // out of all links
        //     .filter(link => link.link_anchor_1 == this.props.Document.dataViz_parentViz) // get links where this chart doc is the target of the link
        //     .map(link => DocCast(link.link_anchor_1)); // then return the source of the link
    }

    @computed get columns() {
        return this._tableData.length ? Array.from(Object.keys(this._tableData[0])).filter(header => header != '' && header != undefined) : [];
    }

    // updates the 'dataViz_selectedRows' and 'dataViz_highlightedRows' fields to no longer include rows that aren't in the table
    filterSelectedRowsDown = () => {
        const selected = NumListCast(this.props.layoutDoc.dataViz_selectedRows);
        this.props.layoutDoc.dataViz_selectedRows = new List<number>(selected.filter(rowId => this._tableDataIds.includes(rowId))); // filters through selected to remove guids that were removed in the incoming data
        const highlighted = NumListCast(this.props.layoutDoc.dataViz_highlitedRows);
        this.props.layoutDoc.dataViz_highlitedRows = new List<number>(highlighted.filter(rowId => this._tableDataIds.includes(rowId))); // filters through highlighted to remove guids that were removed in the incoming data
    };

    @computed get viewScale() {
        return this.props.docView?.()?._props.ScreenToLocalTransform().Scale || 1;
    }
    @computed get rowHeight() {
        console.log('scale = ' + this.viewScale + '  table = ' + this._tableHeight + ' ids = ' + this._tableDataIds.length);
        return (this.viewScale * this._tableHeight) / this._tableDataIds.length;
    }
    @computed get startID() {
        return this.rowHeight ? Math.floor(this._scrollTop / this.rowHeight) : 0;
    }
    @computed get endID() {
        console.log('start = ' + this.startID + '  container = ' + this._tableContainerHeight + ' scale = ' + this.viewScale + ' row = ' + this.rowHeight);
        return Math.ceil(this.startID + (this._tableContainerHeight * this.viewScale) / (this.rowHeight || 1));
    }
    @action handleScroll = () => {
        if (!this.props.docView?.()?.ContentDiv?.hidden) {
            this._scrollTop = this._containerRef?.scrollTop ?? 0;
        }
    };
    @action
    tableRowClick = (e: React.MouseEvent, rowId: number) => {
        const highlited = Cast(this.props.layoutDoc.dataViz_highlitedRows, listSpec('number'), null);
        const selected = Cast(this.props.layoutDoc.dataViz_selectedRows, listSpec('number'), null);
        if (e.metaKey) {
            // highlighting a row
            if (highlited?.includes(rowId)) highlited.splice(highlited.indexOf(rowId), 1);
            else highlited?.push(rowId);
            if (!selected?.includes(rowId)) selected?.push(rowId);
        } else {
            // selecting a row
            if (selected?.includes(rowId)) {
                if (highlited?.includes(rowId)) highlited.splice(highlited.indexOf(rowId), 1);
                selected.splice(selected.indexOf(rowId), 1);
            } else selected?.push(rowId);
        }
        e.stopPropagation();
    };

    columnPointerDown = (e: React.PointerEvent, col: string) => {
        const downX = e.clientX;
        const downY = e.clientY;
        setupMoveUpEvents(
            {},
            e,
            e => {
                // dragging off a column to create a brushed DataVizBox
                const sourceAnchorCreator = () => this.props.docView?.()!.Document!;
                const targetCreator = (annotationOn: Doc | undefined) => {
                    const embedding = Doc.MakeEmbedding(this.props.docView?.()!.Document!);
                    embedding._dataViz = DataVizView.TABLE;
                    embedding._dataViz_axes = new List<string>([col, col]);
                    embedding._dataViz_parentViz = this.props.Document;
                    embedding.annotationOn = annotationOn;
                    embedding.histogramBarColors = Field.Copy(this.props.layoutDoc.histogramBarColors);
                    embedding.defaultHistogramColor = this.props.layoutDoc.defaultHistogramColor;
                    embedding.pieSliceColors = Field.Copy(this.props.layoutDoc.pieSliceColors);
                    return embedding;
                };
                if (this.props.docView?.() && !Utils.isClick(e.clientX, e.clientY, downX, downY, Date.now())) {
                    DragManager.StartAnchorAnnoDrag(e.target instanceof HTMLElement ? [e.target] : [], new DragManager.AnchorAnnoDragData(this.props.docView()!, sourceAnchorCreator, targetCreator), downX, downY, {
                        dragComplete: e => {
                            if (!e.aborted && e.annoDragData && e.annoDragData.linkSourceDoc && e.annoDragData.dropDocument && e.linkDocument) {
                                e.linkDocument.link_displayLine = true;
                                e.linkDocument.link_matchEmbeddings = true;
                                e.linkDocument.link_displayArrow = true;
                                // e.annoDragData.linkSourceDoc.followLinkToggle = e.annoDragData.dropDocument.annotationOn === this.props.Document;
                                // e.annoDragData.linkSourceDoc.followLinkZoom = false;
                            }
                        },
                    });
                    return true;
                }
                return false;
            },
            emptyFunction,
            action(e => {
                const newAxes = this.props.axes;
                if (newAxes.includes(col)) newAxes.splice(newAxes.indexOf(col), 1);
                else if (newAxes.length > 1) newAxes[1] = col;
                else newAxes.push(col);
                this.props.selectAxes(newAxes);
            })
        );
    };

    render() {
        if (this._tableData.length > 0) {
            return (
                <div
                    className="tableBox"
                    tabIndex={0}
                    onKeyDown={e => {
                        if (this.props.layoutDoc && e.key === 'a' && (e.ctrlKey || e.metaKey)) {
                            e.stopPropagation();
                            this.props.layoutDoc.dataViz_selectedRows = new List<number>(this._tableDataIds);
                        }
                    }}>
                    <div className="selectAll-buttons">
                        <Button onClick={action(() => (this.props.layoutDoc.dataViz_selectedRows = new List<number>(this._tableDataIds)))} text="Select All" type={Type.SEC} color={'black'} />
                        <Button onClick={action(() => (this.props.layoutDoc.dataViz_selectedRows = new List<number>()))} text="Deselect All" type={Type.SEC} color={'black'} />
                    </div>
                    <div
                        className={`tableBox-container ${this.columns[0]}`}
                        style={{ height: '100%', overflow: 'auto' }}
                        onScroll={this.handleScroll}
                        ref={action((r: HTMLDivElement | null) => {
                            this._containerRef = r;
                            if (!this.props.docView?.()?.ContentDiv?.hidden && r) {
                                this._tableContainerHeight = r.getBoundingClientRect().height ?? 0;
                                r.addEventListener(
                                    'wheel', // if scrollTop is 0, then don't let wheel trigger scroll on any container (which it would since onScroll won't be triggered on this)
                                    (e: WheelEvent) => {
                                        if (!r.scrollTop && e.deltaY <= 0) e.preventDefault();
                                        e.stopPropagation();
                                    },
                                    { passive: false }
                                );
                            }
                        })}>
                        <table
                            className="tableBox-table"
                            ref={action((r: HTMLTableElement | null) => {
                                if (!this.props.docView?.()?.ContentDiv?.hidden && r) {
                                    this._tableHeight = r?.getBoundingClientRect().height ?? 0;
                                }
                            })}>
                            <div style={{ height: this.startID * Number(DATA_VIZ_TABLE_ROW_HEIGHT) }} />
                            <thead>
                                <tr>
                                    {this.columns.map(col => (
                                        <th
                                            key={this.columns.indexOf(col)}
                                            style={{
                                                color: this.props.axes.slice().reverse().lastElement() === col ? 'darkgreen' : this.props.axes.lastElement() === col ? 'darkred' : undefined,
                                                background: this.props.axes.slice().reverse().lastElement() === col ? '#E3fbdb' : this.props.axes.lastElement() === col ? '#Fbdbdb' : undefined,
                                                fontWeight: 'bolder',
                                                border: '3px solid black',
                                            }}
                                            onPointerDown={e => this.columnPointerDown(e, col)}>
                                            {col}
                                        </th>
                                    ))}
                                </tr>
                            </thead>
                            <tbody>
                                {this._tableDataIds
                                    .filter((rowId, i) => this.startID <= i && i <= this.endID)
                                    ?.map(rowId => (
                                        <tr
                                            key={rowId}
                                            className={`tableBox-row ${this.columns[0]}`}
                                            onClick={e => this.tableRowClick(e, rowId)}
                                            style={{
                                                background: NumListCast(this.props.layoutDoc.dataViz_highlitedRows).includes(rowId) ? 'lightYellow' : NumListCast(this.props.layoutDoc.dataViz_selectedRows).includes(rowId) ? 'lightgrey' : '',
                                            }}>
                                            {this.columns.map(col => {
                                                const colSelected = this.props.axes.length > 1 ? this.props.axes[0] == col || this.props.axes[1] == col : this.props.axes.length > 0 ? this.props.axes[0] == col : false;
                                                return (
                                                    <td key={this.columns.indexOf(col)} style={{ border: colSelected ? '3px solid black' : '1px solid black', fontWeight: colSelected ? 'bolder' : 'normal' }}>
                                                        <div className="tableBox-cell">{this.props.records[rowId][col]}</div>
                                                    </td>
                                                );
                                            })}
                                        </tr>
                                    ))}
                            </tbody>
                            <div style={{ height: (this._tableDataIds.length - this.endID) * Number(DATA_VIZ_TABLE_ROW_HEIGHT) }} />
                        </table>
                    </div>
                </div>
            );
        } else
            return (
                // when it is a brushed table and the incoming table doesn't have any rows selected
                <div className="chart-container">Selected rows of data from the incoming DataVizBox to display.</div>
            );
    }
}