/
viewer.ts
579 lines (461 loc) · 20.4 KB
/
viewer.ts
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
/** A viewer that is typically docked inside a [TableView]. */
import {FILTER_TYPE, TYPE, VIEWER, ViewerPropertyType, ViewerType} from "./const";
import {BitSet, DataFrame} from "./dataframe.js";
import {Property, PropertyOptions} from "./entities";
import {Menu, ObjectPropertyBag, Widget, Filter} from "./widgets";
import {_toJson, MapProxy} from "./utils";
import {toJs, toDart} from "./wrappers";
import {__obs, StreamSubscription} from "./events";
import * as rxjs from "rxjs";
import {Subscription} from "rxjs";
import {filter, map} from 'rxjs/operators';
import {Grid, Point, Rect} from "./grid";
import {FormulaLinesHelper} from "./helpers";
import * as interfaces from "./interfaces/d4";
import dayjs from "dayjs";
import {TableView, View} from "./views/view";
import {ViewerEvent} from './api/d4.api.g';
declare let DG: any;
declare let ui: any;
let api = <any>window;
export class TypedEventArgs<TData> {
dart: any;
constructor(dart: any) {
this.dart = dart;
}
/** Event type id */
get type(): string {
return api.grok_TypedEventArgs_Get_Type(this.dart);
}
get data(): TData {
let data = api.grok_TypedEventArgs_Get_Data(this.dart);
return toJs(data);
}
/** Event arguments. Only applies when data is EventData */
get args(): {[key: string]: any} | null {
// @ts-ignore
if (!this.data?.dart)
return null;
// @ts-ignore
return api.grok_EventData_Get_Args(this.data.dart);
}
}
/**
* Represents a {@link https://datagrok.ai/help/visualize/viewers | viewer}.
* See also {@link https://datagrok.ai/help/develop/how-to/manipulate-viewers}
*
* Use Viewer to control the viewers. To develop a custom viewer, {@see JsViewer}.
*
* @example
* let view = grok.shell.addTableView(grok.data.demo.demog());
* view.scatterPlot({
x: 'height',
y: 'weight',
size: 'age',
color: 'race',
});
**/
export class Viewer<TSettings = any> extends Widget<TSettings> {
public tags: any;
private _meta: ViewerMetaHelper | undefined;
filter: BitSet = BitSet.create(0);
/** @constructs Viewer */
constructor(dart: any, root?: HTMLElement) {
super(root ?? api.grok_Viewer_Root(dart));
this.initDartObject(dart);
}
get onDataEvent(): rxjs.Observable<ViewerEvent> { return this.onEvent('d4-data-event'); }
get onDataHovered(): rxjs.Observable<ViewerEvent> { return this.onEvent('d4-data-event').pipe(filter((e) => e.type == 'd4-hover-event')); }
get onDataSelected(): rxjs.Observable<ViewerEvent> { return this.onEvent('d4-data-event').pipe(filter((e) => e.type == 'd4-select-event')); }
/// current row clicked
get onDataRowClicked(): rxjs.Observable<ViewerEvent> { return this.onEvent('d4-data-event').pipe(filter((e) => e.type == 'd4-click-event')); }
initDartObject(dart: any) {
this.dart = dart;
if (dart != null) {
/** @member {ObjectPropertyBag} */
// @ts-ignore
this.props = new ObjectPropertyBag(this, api.grok_Viewer_Get_Look(this.dart));
this.tags = new MapProxy(api.grok_Viewer_Get_Tags(this.dart), 'tags', 'string');
}
}
/** Creates a new viewer of the specified type.
* @param {ViewerType} viewerType
* @param {DataFrame} table
* @param options
* @returns {Viewer} */
static fromType(viewerType: ViewerType, table: DataFrame, options: object | null = null): Viewer {
return toJs(api.grok_Viewer_FromType(viewerType, table.dart, _toJson(options)));
}
static getViewerTypes(): ViewerType[] {
return api.grok_Viewer_GetViewerTypes();
}
/**
* Sets viewer options. See also {@link getOptions}
* Sample: {@link https://public.datagrok.ai/js/samples/ui/viewers/types/scatter-plot}
* @param {object} map */
// add tsettings
setOptions(map: { type?: ViewerType, [key: string]: any }): void {
api.grok_Viewer_Options(this.dart, JSON.stringify(map));
}
/**
* Gets the serialized viewer options. [includeDefaults] flag specifies whether the
* properties with the default values should be returned. Not including default
* properties makes it more clean and efficient for serialization purposes.
*
* See also {@link setOptions}
* Sample: https://public.datagrok.ai/js/samples/ui/viewers/types/scatter-plot
* @returns {object} */
getOptions(includeDefaults: boolean = false): {id: string, type: ViewerType, look: {[key: string]: any}} {
return JSON.parse(api.grok_Viewer_Serialize(this.dart, includeDefaults));
}
getInfo(): { [index: string]: any } {
return api.grok_Viewer_GetInfo(this.dart);
}
getProperties(): Property[] {
return api.grok_Viewer_Get_Properties(this.dart);
}
/** Closes and detaches the viewer. */
close(): void {
api.grok_Viewer_Close(this.dart);
}
/** Visual root.
* @type {HTMLElement} */
get root(): HTMLElement {
return api.grok_Viewer_Root(this.dart);
}
get meta(): ViewerMetaHelper {
if (this._meta == undefined)
this._meta = new ViewerMetaHelper(this);
return this._meta;
}
/** Returns viewer type (see VIEWER constants)
* @returns {string} */
get type(): ViewerType {
return api.grok_Viewer_Get_Type(this.dart);
}
get table(): DataFrame {
return toJs(api.grok_Viewer_Get_DataFrame(this.dart));
}
/** Returns a view this viewer is associated with, or null */
get view(): View | null {
return toJs(api.grok_Viewer_Get_View(this.dart));
}
/** Returns a view this viewer is associated with, or null */
get tableView(): TableView | null {
return toJs(api.grok_Viewer_Get_View(this.dart));
}
/** @type {DataFrame} */
get dataFrame(): DataFrame {
return toJs(api.grok_Viewer_Get_DataFrame(this.dart));
}
set dataFrame(t: DataFrame) {
api.grok_Viewer_Set_DataFrame(this.dart, t == null ? null : t.dart);
}
get helpUrl(): string {
return api.grok_Viewer_Get_HelpUrl(this.dart);
}
set helpUrl(s: string) {
api.grok_Viewer_Set_HelpUrl(this.dart, s);
}
static grid(t: DataFrame, options: object | null = null): Grid {
return new DG.Grid(api.grok_Viewer_Grid(t.dart, _toJson(options)));
}
static histogram(t: DataFrame, options: object | null = null): Viewer<interfaces.IHistogramLookSettings> {
return new Viewer(api.grok_Viewer_Histogram(t.dart, _toJson(options)));
}
static barChart(t: DataFrame, options: object | null = null): Viewer<interfaces.IBarChartLookSettings> {
return <Viewer>Viewer.fromType(VIEWER.BAR_CHART, t, options);
}
static heatMap(t: DataFrame, options: object | null = null): Viewer<interfaces.IGridLookSettings> {
return <Viewer>Viewer.fromType(VIEWER.HEAT_MAP, t, options);
}
static boxPlot(t: DataFrame, options: object | null = null): Viewer<interfaces.IBoxPlotLookSettings> {
return new Viewer(api.grok_Viewer_BoxPlot(t.dart, _toJson(options)));
}
static filters(t: DataFrame, options: object | null = null): Viewer<interfaces.IFiltersLookSettings> {
return new Viewer(api.grok_Viewer_Filters(t.dart, _toJson(options)));
}
static scatterPlot(t: DataFrame, options: object | null = null): ScatterPlotViewer {
return new ScatterPlotViewer(api.grok_Viewer_ScatterPlot(t.dart, _toJson(options)));
}
static lineChart(t: DataFrame, options: object | null = null): Viewer<interfaces.ILineChartLookSettings> {
return new Viewer(api.grok_Viewer_LineChart(t.dart, _toJson(options)));
}
static network(t: DataFrame, options: object | null = null): Viewer<interfaces.INetworkDiagramLookSettings> {
return <Viewer>Viewer.fromType(VIEWER.NETWORK_DIAGRAM, t, options);
}
static calendar(t: DataFrame, options: object | null = null): Viewer<interfaces.ICalendarLookSettings> {
return <Viewer>Viewer.fromType(VIEWER.CALENDAR, t, options);
}
static correlationPlot(t: DataFrame, options: object | null = null): Viewer<interfaces.ICorrelationPlotLookSettings> {
return <Viewer>Viewer.fromType(VIEWER.CORR_PLOT, t, options);
}
static densityPlot(t: DataFrame, options: object | null = null): Viewer<interfaces.IDensityPlotLookSettings> {
return <Viewer>Viewer.fromType(VIEWER.DENSITY_PLOT, t, options);
}
static form(t: DataFrame, options: object | null = null): Viewer<interfaces.IFormLookSettings> {
return <Viewer>Viewer.fromType(VIEWER.FORM, t, options);
}
static markup(t: DataFrame, options: object | null = null): Viewer<interfaces.IMarkupViewerLookSettings> {
return <Viewer>Viewer.fromType(VIEWER.MARKUP, t, options);
}
static matrixPlot(t: DataFrame, options: object | null = null): Viewer<interfaces.IMatrixPlotLookSettings> {
return <Viewer>Viewer.fromType(VIEWER.MATRIX_PLOT, t, options);
}
static pcPlot(t: DataFrame, options: object | null = null): Viewer<interfaces.IPcPlotLookSettings> {
return <Viewer>Viewer.fromType(VIEWER.PC_PLOT, t, options);
}
static pieChart(t: DataFrame, options: object | null = null): Viewer<interfaces.IPieChartLookSettings> {
return <Viewer>Viewer.fromType(VIEWER.PIE_CHART, t, options);
}
static scatterPlot3d(t: DataFrame, options: object | null = null): Viewer<interfaces.IScatterPlot3dLookSettings> {
return <Viewer>Viewer.fromType(VIEWER.SCATTER_PLOT_3D, t, options);
}
static statistics(t: DataFrame, options: object | null = null): Viewer<interfaces.IStatsViewerLookSettings> {
return <Viewer>Viewer.fromType(VIEWER.STATISTICS, t, options);
}
static tile(t: DataFrame, options: object | null = null): Viewer<interfaces.ITileViewerLookSettings> {
return <Viewer>Viewer.fromType(VIEWER.TILE_VIEWER, t, options);
}
static treeMap(t: DataFrame, options: object | null = null): Viewer<interfaces.ITreeMapLookSettings> {
return <Viewer>Viewer.fromType(VIEWER.TREE_MAP, t, options);
}
static trellisPlot(t: DataFrame, options: object | null = null): Viewer<interfaces.ITrellisPlotLookSettings> {
return <Viewer>Viewer.fromType(VIEWER.TRELLIS_PLOT, t, options);
}
/** @deprecated */
static wordCloud(t: DataFrame, options: object | null = null): Viewer {
return <Viewer>Viewer.fromType(VIEWER.WORD_CLOUD, t, options);
}
get onContextMenu(): rxjs.Observable<Menu> {
return this.onEvent('d4-context-menu').pipe(map(x => x.args.menu));
}
/** Observes platform events with the specified eventId. */
onEvent(eventId: string | null = null): rxjs.Observable<any> {
if (eventId !== null)
return __obs(eventId, this.dart);
let dartStream = api.grok_Viewer_Get_EventBus_Events(this.dart);
return rxjs.fromEventPattern(
function (handler) {
return api.grok_Stream_Listen(dartStream, function (x: any) {
handler(new TypedEventArgs(x));
});
},
function (handler, dart) {
new StreamSubscription(dart).cancel();
}
);
}
toCompactLook() {
api.grok_Viewer_To_Trellis_Look(this.dart);
}
get onDartPropertyChanged(): rxjs.Observable<null> {
let dartStream = api.grok_Viewer_Get_PropertyChanged_Events(this.dart);
return rxjs.fromEventPattern(
function (handler) {
return api.grok_Stream_Listen(dartStream, function (x: any) {
handler(new TypedEventArgs(x));
});
},
function (handler, dart) {
new StreamSubscription(dart).cancel();
}
);
}
copyViewersLook(other: Viewer) {
api.grok_Viewer_Copy_Viewers_Look(this.dart, other.dart);
}
removeFromView() {
return toJs(api.grok_Viewer_Remove_From_View(this.dart));
}
}
/** Subclass JsViewer to implement a DataFrame-bound Datagrok viewer in JavaScript.
* See an example on github: {@link https://github.com/datagrok-ai/public/tree/master/packages/Leaflet}
* */
export class JsViewer extends Viewer {
public dart: any;
subs: Subscription[];
obs: rxjs.Observable<any>[];
props: ObjectPropertyBag;
rowSource: string | undefined;
formulaFilter: string | undefined;
/** @constructs JsViewer */
constructor() {
let _root = ui.box();
super(null, _root);
this.dart = api.grok_Viewer_FromJsViewer(this);
this.initDartObject(this.dart);
this._root = _root;
/** @type {StreamSubscription[]} */
this.subs = []; // stream subscriptions - will be canceled when the viewer is detached
this.obs = [];
/** @member {ObjectPropertyBag} */
this.props = new ObjectPropertyBag(this);
}
addRowSourceAndFormula() {
this.rowSource = this.string('rowSource', 'Filtered',
{ choices: ['All', 'Filtered', 'Selected', 'SelectedOrCurrent', 'FilteredSelected', 'MouseOverGroup', 'CurrentRow', 'MouseOverRow']});
this.formulaFilter = this.string('filter', '', {fieldName: 'formulaFilter'});
}
onFrameAttached(dataFrame: DataFrame): void {
this.onTableAttached();
}
sourceRowsChanged(): void {
this.filter = toJs(api.grok_Viewer_Get_Filter(this.dart));
this.onSourceRowsChanged();
}
onSourceRowsChanged(): void {}
get root(): HTMLElement { return this._root; }
set root(r: HTMLElement) { this._root = r; }
/** Gets called when a table is attached to the viewer. */
onTableAttached(): void { }
/** Gets called when this viewer is detached. */
detach(): void {
this.subs.forEach((sub) => sub.unsubscribe());
}
/** Gets property by name (case-sensitive).
* @param {string} name
* @returns {Property} */
getProperty(name: string): Property | undefined {
return this.getProperties().find((p) => p.name === name);
}
getProperties(): Property[] {
return this._properties;
}
/** cleanup() will get called when the viewer is disposed */
protected registerCleanup(cleanup: Function): void {
api.grok_Widget_RegisterCleanup(this.root, cleanup);
}
protected _obs(observable: rxjs.Observable<any>): rxjs.Observable<any> {
this.obs.push(observable);
return observable;
}
/** Returns the column bound to the specified data property.
* Note that "ColumnName" suffix (this determines whether this is a data property) should be omitted. */
protected column(dataPropertyName: string, options: { [key: string]: any } & PropertyOptions | null = null): string {
return this.addProperty(`${dataPropertyName}ColumnName`, TYPE.STRING, null, options);
}
protected columnList(propertyName: ViewerPropertyType, defaultValue: string[] | null = null, options: { [key: string]: any } & PropertyOptions | null = null): string[] {
return this.addProperty(propertyName, DG.TYPE.COLUMN_LIST, defaultValue, options);
}
/** Registers an integer property with the specified name and defaultValue */
protected int(propertyName: ViewerPropertyType, defaultValue: number | null = null, options: { [key: string]: any } & PropertyOptions | null = null): number {
return this.addProperty(propertyName, TYPE.INT, defaultValue, options);
}
/** Registers a floating point property with the specified name and defaultValue */
protected float(propertyName: ViewerPropertyType, defaultValue: number | null = null, options: { [key: string]: any } & PropertyOptions | null = null): number {
return this.addProperty(propertyName, TYPE.FLOAT, defaultValue, options);
}
/** Registers a string property with the specified name and defaultValue */
protected string(propertyName: ViewerPropertyType, defaultValue: string | null = null, options: { [key: string]: any } & PropertyOptions | null = null): string {
return this.addProperty(propertyName, TYPE.STRING, defaultValue, options);
}
/** Registers a string list property with the specified name and defaultValue */
protected stringList(propertyName: ViewerPropertyType, defaultValue: string[] | null = null, options: { [key: string]: any } & PropertyOptions | null = null): string[] {
return this.addProperty(propertyName, TYPE.STRING_LIST, defaultValue, options);
}
/** Registers a boolean property with the specified name and defaultValue */
protected bool(propertyName: ViewerPropertyType, defaultValue: boolean | null = null, options: { [key: string]: any } & PropertyOptions | null = null): boolean {
return this.addProperty(propertyName, TYPE.BOOL, defaultValue, options);
}
/** Registers a datetime property with the specified name and defaultValue */
protected dateTime(propertyName: ViewerPropertyType, defaultValue: dayjs.Dayjs | null = null, options: { [key: string]: any } & PropertyOptions | null = null): dayjs.Dayjs {
return this.addProperty(propertyName, TYPE.DATE_TIME, defaultValue, options);
}
}
export interface FilterState {
type: FILTER_TYPE | string;
column?: string;
}
/** Represents a group of filters that are located together. */
export class FilterGroup extends Viewer {
dart: any;
constructor(dart: any) {
super(dart);
}
getStates(columnName: string, filterType: String): Array<Object> {
return api.grok_FilterGroup_GetStates(this.dart, columnName, filterType);
}
add<T extends FilterState>(state: T) {
api.grok_FilterGroup_Add(this.dart, state);
}
updateOrAdd<T extends FilterState>(state: T, requestFilter?: boolean) {
api.grok_FilterGroup_UpdateOrAdd(this.dart, state, requestFilter);
}
getFilterSummary(): Element {
return api.grok_FilterGroup_GetFilterSummary(this.dart);
}
/** Returns array of filters in FilterGroup. Filter if js filter and dart object if dart filter */
get filters(): Array<Filter | Widget> {
return toJs(api.grok_FilterGroup_Get_Filters(this.dart));
}
setEnabled(filter: Filter | Widget | FilterState, active: boolean) {
api.grok_FilterGroup_SetEnabled(this.dart, filter, active);
}
setExpanded(filter: Filter | Widget, active: boolean) {
api.grok_FilterGroup_SetExpanded(this.dart, filter, active);
}
remove(filter: Filter | Widget) {
api.grok_FilterGroup_Remove(this.dart, filter);
}
}
export class LineChartViewer extends Viewer<interfaces.ILineChartLookSettings> {
constructor(dart: any) {
super(dart);
}
get activeFrame(): DataFrame {
return api.grok_LineChartViewer_activeFrame(this.dart);
}
}
/** 2D scatter plot */
export class ScatterPlotViewer extends Viewer<interfaces.IScatterPlotLookSettings> {
constructor(dart: any) {
super(dart);
}
/** Rerender plot */
invalidateCanvas(): void{
api.grok_ScatterPlotViewer_InvalidateCanvas(this.dart);
}
/** Row hit test using canvas coords */
hitTest(x: number, y: number): number {
return api.grok_ScatterPlotViewer_HitTest(this.dart, x, y);
}
/** Zoom using world coords */
zoom(x1: number, y1: number, x2: number, y2: number) {
api.grok_ScatterPlotViewer_Zoom(this.dart, x1, y1, x2, y2);
}
get viewBox(): Rect { return toJs(api.grok_ScatterPlotViewer_Get_ViewBox(this.dart)); }
get xAxisBox(): Rect { return toJs(api.grok_ScatterPlotViewer_Get_XAxisBox(this.dart)); }
get yAxisBox(): Rect { return toJs(api.grok_ScatterPlotViewer_Get_YAxisBox(this.dart)); }
get viewport(): Rect { return toJs(api.grok_ScatterPlotViewer_Get_Viewport(this.dart)); }
set viewport(viewport: Rect) { api.grok_ScatterPlotViewer_Set_Viewport(this.dart, viewport.x, viewport.y, viewport.width, viewport.height); }
/** Convert coords */
worldToScreen(x: number, y: number): Point { return Point.fromXY(api.grok_ScatterPlotViewer_WorldToScreen(this.dart, x, y)); }
screenToWorld(x: number, y: number): Point { return Point.fromXY(api.grok_ScatterPlotViewer_ScreenToWorld(this.dart, x, y)); }
/// 32-bit integer with X in the hi 16 bits, and Y in the lo 16 bits
pointToScreen(index: number): Point { return Point.fromXY(api.grok_ScatterPlotViewer_PointToScreen(this.dart, index)); }
render(g: CanvasRenderingContext2D): void { api.grok_ScatterPlotViewer_Render(this.dart, g); }
getRowTooltip(rowIdx: number): HTMLDivElement { return api.grok_ScatterPlotViewer_GetRowTooltip(this.dart, rowIdx); }
get onZoomed(): rxjs.Observable<Rect> { return this.onEvent('d4-scatterplot-zoomed'); }
get onResetView(): rxjs.Observable<null> { return this.onEvent('d4-scatterplot-reset-view'); }
get onViewportChanged(): rxjs.Observable<Rect> { return this.onEvent('d4-viewport-changed'); }
get onAfterDrawScene(): rxjs.Observable<null> { return this.onEvent('d4-after-draw-scene'); }
get onBeforeDrawScene(): rxjs.Observable<null> { return this.onEvent('d4-before-draw-scene'); }
}
export class ViewerMetaHelper {
private readonly _viewer: Viewer;
readonly formulaLines: ViewerFormulaLinesHelper;
constructor(viewer: Viewer) {
this._viewer = viewer;
this.formulaLines = new ViewerFormulaLinesHelper(this._viewer);
}
}
export class ViewerFormulaLinesHelper extends FormulaLinesHelper {
readonly viewer: Viewer;
get storage(): string { return this.viewer.props['formulaLines']; }
set storage(value: string) { this.viewer.props['formulaLines'] = value; }
constructor(viewer: Viewer) {
super();
this.viewer = viewer;
}
}