/
widgets.ts
2304 lines (1791 loc) · 70.2 KB
/
widgets.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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {toDart, toJs} from "./wrappers";
import {__obs, _sub, observeStream, StreamSubscription} from "./events";
import * as rxjs from "rxjs";
import {fromEvent, Observable, Subject, Subscription} from "rxjs";
import {Func, Property, PropertyOptions} from "./entities";
import {Cell, Column, DataFrame} from "./dataframe";
import {ColorType, LegendPosition, Type} from "./const";
import {filter, map} from 'rxjs/operators';
import $ from "cash-dom";
import {MapProxy} from "./utils";
import dayjs from "dayjs";
import typeahead from 'typeahead-standalone';
import {Dictionary, typeaheadConfig} from 'typeahead-standalone/dist/types';
import * as d4 from './../src/api/d4.api.g';
import '../css/breadcrumbs.css';
import '../css/drop-down.css';
import '../css/typeahead-input.css';
import '../css/tags-input.css';
import {FuncCall} from "./functions";
import {IDartApi} from "./api/grok_api.g";
declare let grok: any;
declare let DG: any;
declare let ui: any;
const api: IDartApi = <any>window;
export type RangeSliderStyle = 'barbell' | 'lines' | 'thin_barbell';
export type SliderOptions = {
style?: RangeSliderStyle
}
export type TypeAheadConfig = Omit<typeaheadConfig<Dictionary>, 'input' | 'className'>;
export type CodeConfig = {
script?: string;
mode?: string;
placeholder?: string;
};
export type TagsInputConfig = {
tags?: string[];
showButton?: boolean;
};
export class ObjectPropertyBag {
source: any;
constructor(source: any, x: any = null) {
/** @member {Object} */
this.source = source;
if (x == null)
x = source;
let props = this;
const handler = {
ownKeys(target: any) {
return props.getProperties().map((p: Property) => p.name);
},
has(target: any, name: string) {
return props.getProperties().find((p: Property) => p.name === name) !== null;
},
getOwnPropertyDescriptor(target: any, key: any) {
return {
enumerable: true,
configurable: true
};
},
set(target: any, name: string, value: any) {
if (<any>x instanceof DartWidget)
x = toDart(x);
target.getProperty(name).set(x, value);
return true;
},
get(target: any, name: any) {
const own = ['__proto__', 'hasProperty', 'getProperty', 'getProperties',
'get', 'set', 'setAll', 'apply', 'setDefault', 'resetDefault'];
if (own.includes(name) || props.hasOwnProperty(name))
// @ts-ignore
return props[name];
if (<any>x instanceof DartWidget)
x = toDart(x);
return target.getProperty(name)?.get(x);
}
}
return new Proxy(this, handler);
}
/**
* Gets the value of the specified property
* @param {string} propertyName
* @returns {object}
* */
get(propertyName: string): object {
return this.getProperty(propertyName).get(this.source);
}
/**
* Sets the value of the specified property
* @param {string} propertyName
* @param {object} propertyValue
* */
set(propertyName: string, propertyValue: object) {
this.getProperty(propertyName).set(this.source, propertyValue);
}
/** Sets all properties according to the passed object containing key-value pairs */
setAll(params: object) {
for (const [k, v] of Object.entries(params))
this.set(k, v);
}
/** @returns {Property[]} */
getProperties(): Property[] {
return this.source.getProperties();
}
/** Gets property by name (case-sensitive).
* @param {string} name
* @returns {Property} */
getProperty(name: string): Property {
let property = this.getProperties().find((p) => p.name === name);
if (typeof property == 'undefined')
throw `Property not found: ${name}`;
return property;
}
/**
* @param {string} name
* @returns {boolean} */
hasProperty(name: string): boolean {
return this.getProperties().findIndex((p) => p.name === name) !== -1;
}
/** Sets the current state of viewer properties as the default configuration used to create new viewer
* instances of this type. Equivalent to the "Pick Up / Apply | Set as Default" context menu command.
* Read more about viewer commands: https://datagrok.ai/help/visualize/viewers/#common-actions
* @param data indicates if data settings should be copied.
* @param style indicates if style (non-data) settings should be copied. */
setDefault(data: boolean = false, style: boolean = true) {
if (this.source instanceof DG.Viewer)
api.grok_Viewer_Props_SetDefault(this.source.dart, data, style);
else
throw 'Call failed: object is not Viewer instance';
}
static setDefaultProperty(viewerType: string, propertyName: string, propertyValue: any) {
api.grok_Viewer_Props_SetDefaultProperty(viewerType, propertyName, propertyValue);
}
/** Clears the previously remembered default settings for viewers of this type. See also: [setDefault] */
resetDefault() {
if (this.source instanceof DG.Viewer)
api.grok_Viewer_Props_ResetDefault(this.source.dart);
else
throw 'Call failed: object is not Viewer instance';
}
}
/** Base class for controls that have a visual root and a set of properties. */
export class Widget<TSettings = any> {
public get type(): string { return 'Unknown'; }
/** Contains auxiliary information */
public temp: any;
/** Constructor function. No parameters, returns [Widget]. */
factory: Func | null = null;
protected _root: HTMLElement;
protected _properties: Property[];
props: TSettings & ObjectPropertyBag; //ObjectPropertyBag;
subs: Subscription[];
dart: any;
isDetached: boolean = false;
/** @constructs Widget and initializes its root. */
constructor(widgetRoot: HTMLElement) {
/** @member {HTMLElement} */
this._root = widgetRoot;
/** @member {Property[]}*/
this._properties = [];
/** @member {ObjectPropertyBag} */
// @ts-ignore
this.props = new ObjectPropertyBag(this);
/** @member {StreamSubscription[]} */
this.subs = [];
this.getProperties = this.getProperties.bind(this);
this.temp = {};
}
/** Returns all currently active widgets. */
static getAll(): Widget[] {
return api.grok_Widget_GetAll();
}
/** Finds existing widget from its visual root. */
static find(root: Element): Widget | null {
return api.grok_Widget_FromRoot(root);
}
toDart() {
if (this.dart == null)
this.dart = api.grok_Widget_Wrap(this);
return this.dart;
}
/** Registers a subscription to an external event.
* @param {Subscription} subscription */
sub(subscription: Subscription): void {
this.subs.push(subscription);
}
/**
* @param {Object} properties
* @returns {Widget} */
apply(properties: object): Widget {
for (let name of Object.keys(properties))
if (typeof name !== 'undefined')
// @ts-ignore
this.props[name] = properties[name];
//this.props.apply(properties);
return this;
}
getProperties(): Property[] { return this._properties; }
/** Gets called when viewer's property is changed.
* @param {Property} property - or null, if multiple properties were changed. */
onPropertyChanged(property: Property | null): void {}
getDartProperties(): any[] {
return this.getProperties().map((p) => p.dart);
}
sourceRowsChanged(): void {};
onFrameAttached(dataFrame: DataFrame): void {
if (this.props.hasProperty('dataFrame'))
this.props.set('dataFrame', dataFrame);
}
/** Widget's visual root.
* @type {HTMLElement} */
get root(): HTMLElement { return this._root; }
set root(r: HTMLElement) { this._root = r; }
/** Gets called when a widget is detached and will no longer be used. Typically used for unsubscribing from events.
* Be sure to call super.detach() if this method is overridden. */
detach(): void {
this.subs.forEach((s) => s.unsubscribe());
this.isDetached = true;
}
/** Registers an property with the specified type, name, and defaultValue.
* Registered property gets added to {@see properties}.
* Returns default value, thus allowing to combine registering a property with the initialization
*
* @param {string} propertyName
* @param {TYPE} propertyType
* @param defaultValue
* @param {Object} options
* @returns {*}
* @private
*/
addProperty(propertyName: string, propertyType: Type, defaultValue: any = null, options: { [key: string]: any } & PropertyOptions | null = null): any {
const fieldName = options?.fieldName ?? propertyName;
let obj = this;
// @ts-ignore
let p = Property.create(propertyName, propertyType, (_) => obj[fieldName], null, defaultValue);
p.set = function (_: any, x: any) {
// @ts-ignore
obj[fieldName] = x;
obj.onPropertyChanged(p);
};
if (options !== null) {
for (let key of Object.keys(options))
if (key != 'fieldName')
api.grok_PropMixin_SetPropertyValue(p.dart, key, options[key]);
}
this._properties.push(p);
return p.defaultValue;
}
/** Creates a new widget from the root element. */
static fromRoot(root: HTMLElement): Widget {
return new Widget(root);
}
// /** Creates a {@see Widget} from the specified React component. */
// // @ts-ignore
// static react(reactComponent: React.DOMElement<any, any> | Array<React.DOMElement<any, any>> | React.CElement<any, any> | Array<React.CElement<any, any>> | React.ReactElement | Array<React.ReactElement>): Widget {
// let widget = Widget.fromRoot(ui.div());
// // @ts-ignore
// ReactDOM.render(reactComponent, widget.root);
// return widget;
// }
}
/** Base class for DataFrame-bound filtering controls.
* Supports collaborative filtering by efficiently working together with
* other filters. */
export abstract class Filter extends Widget {
/** An indicator icon on the left of the filter header, before the name.
* A filter is responsible for hiding or showing it, depending on its state. */
indicator: HTMLDivElement;
/** Group of control icons on the right of the filter header, after the name.
* FilterGroup takes care of its visibility. */
controls: HTMLDivElement;
/** A DataFrame this filter is associated with. */
dataFrame: DataFrame | null;
/** A column this filter is associated with. */
column: Column | null = null;
columnName?: string;
/** Caption to be shown in the filter group. */
get caption(): string { return this.columnName ?? ''}
constructor() {
super(ui.div());
this.dataFrame = null;
this.indicator = ui.div([], 'd4-filter-indicator');
this.controls = ui.div([], 'd4-flex-row');
$(this.indicator).hide();
}
// static create(type: FILTER_TYPE | null, column: Column): Filter {
// return api.grok_Filter_ForColumn(column, type);
// }
//
// static forColumn(column: Column) { return Filter.create(null, column); }
//
// static histogram(column: Column) { return Filter.create(FILTER_TYPE.HISTOGRAM, column); }
// static categorical(column: Column) { return Filter.create(FILTER_TYPE.CATEGORICAL, column); }
// static multiValue(column: Column) { return Filter.create(FILTER_TYPE.MULTI_VALUE, column); }
// static freeText(column: Column) { return Filter.create(FILTER_TYPE.FREE_TEXT, column); }
/** Override to indicate whether the filter actually filters something (most don't in the initial state).
* This is used to minimize the number of unnecessary computations.
* Make sure to call super.isFiltering to check whether the filter has been disabled by the user */
get isFiltering(): boolean {
return !(this.root.parentElement?.classList?.contains('d4-filter-disabled') == true) &&
!(this.root.parentElement?.parentElement?.parentElement?.classList?.contains('d4-filters-disabled') == true);
}
/** Whether a filter is ready to apply the filtering mask synchronously. */
get isReadyToApplyFilter(): boolean { return true; }
/** Override to provide short filter summary that might be shown on viewers or in the context panel. */
abstract get filterSummary(): string;
/** Override to filter the dataframe.
* The method should work with `this.dataFrame.filter`, should disregard
* false values (these are filtered out already by other filters), and should
* filter out corresponding indexes. */
abstract applyFilter(): void;
/** Override to save filter state. */
saveState(): any {
console.log('save state');
return {
column: this.columnName,
columnName: this.columnName
};
}
/** Override to load filter state. */
applyState(state: any): void {
this.columnName = state.columnName;
this.column = this.columnName && this.dataFrame ? this.dataFrame.col(this.columnName) : null;
console.log('apply state');
}
/** Gets called when a data frame is attached.
* Make sure to call super.attach(dataFrame) when overriding.
* @param {DataFrame} dataFrame*/
attach(dataFrame: DataFrame): void {
this.dataFrame = dataFrame;
this.subs.push(this.dataFrame.onRowsFiltering
.pipe(filter((_) => this.isFiltering && this.isReadyToApplyFilter))
.subscribe((_) => {
this.applyFilter();
this.dataFrame!.rows.filters.push(`${this.columnName}: ${this.filterSummary}`);
})
);
}
/** Gets called when a previously used filter gets moved in the DOM tree.
* Normally, you don't need to do anything, but this might be handy for
* the iframe-based filters. */
refresh() {}
detach(): void {
super.detach();
if (this.isFiltering)
this.dataFrame?.rows?.requestFilter();
}
}
export class DartWidget extends Widget {
constructor(dart: any) {
super(api.grok_Widget_Get_Root(dart));
this.dart = dart;
this.temp = new MapProxy(api.grok_Widget_Get_Temp(this.dart));
}
get type(): string {
return api.grok_Widget_Get_Type(this.dart);
}
get root(): HTMLElement {
return api.grok_Widget_Get_Root(this.dart);
}
getProperties(): Property[] {
return toJs(api.grok_PropMixin_GetProperties(this.dart));
}
}
/**
* Accordion control with collapsible/expandable panes.
* Samples: {@link https://public.datagrok.ai/js/samples/ui/accordion}
* @extends {DartWidget}
* */
export class Accordion extends DartWidget {
/** @constructs Accordion */
constructor(dart: any) {
super(dart);
}
/** An object this accordion is associated with */
get context(): any {
return toJs(api.grok_Accordion_Get_Context(this.dart));
}
set context(x: any) {
api.grok_Accordion_Set_Context(this.dart, toDart(x));
}
/** Creates a new instance of Accordion */
static create(key: any = null): Accordion {
return toJs(api.grok_Accordion(key));
}
/** @type {AccordionPane[]} */
get panes(): AccordionPane[] {
return api.grok_TabControlBase_Get_Panes(this.dart).map(toJs);
}
/** Header element on top of the accordion */
get header(): HTMLElement { return api.grok_Accordion_Get_Header(this.dart); }
set header(header) { api.grok_Accordion_Set_Header(this.dart, header); }
/** Whether tab header should be hidden if there is only one tab */
get autoHideTabHeader(): boolean { return api.grok_Accordion_Get_AutoHideTabHeader(this.dart); }
set autoHideTabHeader(x) { api.grok_Accordion_Set_AutoHideTabHeader(this.dart, x); }
/** Returns a pane with the specified name.
* @param {string} name
* @returns {AccordionPane} */
getPane(name: string): AccordionPane {
return toJs(api.grok_TabControlBase_GetPane(this.dart, name));
}
/** Adds a title element. */
addTitle(element: HTMLElement): void {
return api.grok_Accordion_AddTitle(this.dart, element);
}
/** Adds a pane */
addPane(name: string, getContent: () => HTMLElement, expanded: boolean = false, before: AccordionPane | null = null,
allowDragOut: boolean = true): AccordionPane {
return toJs(api.grok_Accordion_AddPane(this.dart, name, getContent, expanded, before !== null ? before.dart : null, null, allowDragOut));
}
/** Adds a pane with the count indicator next to the title.
* getCount() is executed immediately. */
addCountPane(name: string, getContent: () => HTMLElement, getCount: () => number, expanded: boolean = false, before: AccordionPane | null = null,
allowDragOut: boolean = true): AccordionPane {
return toJs(api.grok_Accordion_AddPane(this.dart, name, getContent, expanded, before !== null ? before.dart : null, getCount, allowDragOut));
}
/** Removed the specified pane. */
removePane(pane: AccordionPane) {
api.grok_Accordion_RemovePane(this.dart, pane.dart);
}
/** Finalizes accordion construction */
end() {
api.grok_Accordion_End(this.dart);
}
}
/** A pane in the {@link Accordion} control. */
export class AccordionPane extends DartWidget {
dart: any;
constructor(dart: any) {
super(dart);
}
/** Expanded state
* @type {boolean} */
get expanded(): boolean {
return api.grok_AccordionPane_Get_Expanded(this.dart);
}
set expanded(v: boolean) {
api.grok_AccordionPane_Set_Expanded(this.dart, v);
}
/** @type {string} */
get name(): string {
return api.grok_AccordionPane_Get_Name(this.dart);
}
set name(name: string) {
api.grok_AccordionPane_Set_Name(this.dart, name);
}
}
/** Tab control that hosts panes inside. See also {@link TabPane} */
export class TabControl {
dart: any;
constructor(dart: any) {
this.dart = dart;
}
/** Creates a new TabControl */
static create(vertical: boolean = false): TabControl {
return toJs(api.grok_TabControl(vertical));
}
/** Visual root */
get root(): HTMLDivElement {
return api.grok_Widget_Get_Root(this.dart);
}
/** Header shown on top of the control */
get header(): HTMLDivElement {
return api.grok_TabControlBase_Get_Header(this.dart);
}
/** Panes currently present in the pane control.
* Do not change the array, use {@link addPane} instead */
get panes(): TabPane[] {
return api.grok_TabControlBase_Get_Panes(this.dart).map(toJs);
}
/** Gets the pane with the specified name */
getPane(name: string): TabPane {
return toJs(api.grok_TabControlBase_GetPane(this.dart, name));
}
/** Adds a new pane with the specified name */
addPane(name: string, getContent: () => HTMLElement, icon: any = null, options?: {allowClose: boolean}): TabPane {
return toJs(api.grok_TabControlBase_AddPane(this.dart, name, getContent, icon, options?.allowClose ?? false));
}
/** Removes all panes */
clear(): void {
api.grok_TabControlBase_Clear(this.dart);
}
/** Currently visible pane */
get currentPane(): TabPane { return api.grok_TabControlBase_Get_CurrentPane(this.dart); }
set currentPane(v: TabPane) { api.grok_TabControlBase_Set_CurrentPane(this.dart, v.dart); }
/** Occurs before the active pane is changed */
get onBeforeTabChanged(): Observable<any> { return __obs('d4-tabcontrol-before-tab-changed', this.dart); }
/** Occurs after the active pane is changed */
get onTabChanged(): Observable<any> { return __obs('d4-tabcontrol-tab-changed', this.dart); }
get onTabAdded(): Observable<any> { return __obs('d4-tabcontrol-tab-added', this.dart); }
get onTabRemoved(): Observable<any> { return __obs('d4-tabcontrol-tab-removed', this.dart); }
}
/** Represents a pane of either {@link TabControl} or {@link Accordion} */
export class TabPane {
dart: any;
/** Creates TabPane from the Dart handle */
constructor(dart: any) {
this.dart = dart;
}
/** {@link TabControl} this pane belongs to */
get parent(): TabControl {
return toJs(api.grok_TabPane_Get_Parent(this.dart));
}
/** A control shown on top of the pane */
get header(): HTMLDivElement {
return api.grok_TabPane_Get_Header(this.dart);
}
/** Content */
get content(): HTMLDivElement {
return api.grok_TabPane_Get_Content(this.dart);
}
/** Whether the pane is expanded. Applicable to Accordion's panes only. */
get expanded(): boolean { return api.grok_AccordionPane_Get_Expanded(this.dart); }
set expanded(v: boolean) { api.grok_AccordionPane_Set_Expanded(this.dart, v); }
/** Tab pane name */
get name(): string { return api.grok_AccordionPane_Get_Name(this.dart); }
set name(name: string) { api.grok_AccordionPane_Set_Name(this.dart, name); }
}
export class ToolboxPage {
dart: any;
constructor(dart: any) {
this.dart = dart;
}
get accordion(): Accordion {
return toJs(api.grok_ToolboxPage_Get_Accordion(this.dart));
}
}
/**
* A non-modal dialog.
* Sample: https://public.datagrok.ai/js/samples/ui/dialogs
*
* @example
* ui.dialog('Windows')
* .add(ui.)
* .add(ui.span(['People of Earth, your attention, please… ']))
* .onOK(() => { grok.shell.info('OK!'); })
* .show();
* */
export class Dialog extends DartWidget {
constructor(dart: any) {
super(dart);
}
/** Creates a new dialog with the specified options. */
static create(options?: { title?: string, helpUrl?: string, showHeader?: boolean, showFooter?: boolean } | string): Dialog {
if (typeof options === 'string')
return Dialog.create({ title: options });
else
return new Dialog(api.grok_Dialog(options?.title ?? '', options?.helpUrl, options?.showHeader ?? true, options?.showFooter ?? true));
}
/** When provided, adds a "?" icon to the dialog header on the right. */
get helpUrl(): string { return api.grok_Dialog_Get_HelpUrl(this.dart); };
set helpUrl(url: string) { api.grok_Dialog_Set_HelpUrl(this.dart, url); };
/** Returns the title of a dialog. */
get title(): string { return api.grok_Dialog_Get_Title(this.dart); };
set title(t: string) { api.grok_Dialog_Set_Title(this.dart, t); };
/** Returns a list of the dialog's inputs. */
get inputs(): InputBase[] { return api.grok_Dialog_Get_Inputs(this.dart); }
/** Returns an input with the specified caption, or throws an exception. */
input(caption: string): InputBase {
const input = this.inputs.find((f) => f.caption == caption);
if (!input)
throw `Input "${caption}" not found.`;
return input;
}
/**
* Sets the OK button handler, and shows the OK button
* @param {Function} handler
* @returns {Dialog} */
onOK(handler: Function): Dialog {
api.grok_Dialog_OnOK(this.dart, handler);
return this;
}
/**
* Sets the CANCEL button handler
* @param {Function} handler
* @returns {Dialog} */
onCancel(handler: Function): Dialog {
api.grok_Dialog_OnCancel(this.dart, handler);
return this;
}
/** @returns {Observable} */
get onClose(): Observable<any> {
return __obs('d4-dialog-closed', this.dart);
}
// Using __obs is a recommended method. The below are obsolete and shall not be used:
// onClose(handler) { api.grok_Dialog_OnClose(this.dart, handler); return this; }
// onClose(handler) { let s = _sub(api.grok_Dialog_OnClose(this.dart, () => { handler(); s.cancel(); })); return this; }
/** @returns {Dialog}
* @param {{modal: boolean, fullScreen: boolean, center: boolean, centerAt: Element, x: number, y: number, width: number, height: number}|{}} options
* */
show(options?: { modal?: boolean; resizable?: boolean; fullScreen?: boolean; center?: boolean; centerAt?: Element; x?: number; y?: number; width?: number; height?: number; backgroundColor?: string; showNextTo?: HTMLElement}): Dialog {
api.grok_Dialog_Show(this.dart, options?.modal, options?.resizable, options?.fullScreen, options?.center, options?.centerAt, options?.x, options?.y, options?.width, options?.height, options?.backgroundColor, options?.showNextTo);
return this;
}
/** @returns {Dialog}
* @param {boolean} fullScreen */
showModal(fullScreen: boolean): Dialog {
api.grok_Dialog_Show(this.dart, true, null, fullScreen, false, null, null, null, null, null, null, null);
return this;
}
/** Adds content to the dialog.
* @param {HTMLElement | Widget | InputBase} content
* @returns {Dialog} */
add(content: HTMLElement | Widget | InputBase): Dialog {
api.grok_Dialog_Add(this.dart, toDart(content));
return this;
}
/** Closes the dialog. */
close(): void {
api.grok_Dialog_Close(this.dart);
}
/** Returns command button with the specified text.
* @param {string} text
* @returns {HTMLButtonElement}
* */
getButton(text: string): HTMLButtonElement {
return api.grok_Dialog_GetButton(this.dart, text);
}
/** Adds command button with the specified text.
* @param {string} text
* @param {Function} action
* @param index
* @param tooltip
* @returns {Dialog}
* */
addButton(text: string, action: Function, index: number = 0, tooltip: any = null): Dialog {
api.grok_Dialog_AddButton(this.dart, text, action, index, tooltip);
return this;
}
/** Adds context action with the specified text.
* @param {string} text
* @param {Function} action
* @returns {Dialog}
* */
addContextAction(text: string, action: Function): Dialog {
api.grok_Dialog_AddContextAction(this.dart, text, action);
return this;
}
/** Initializes the 'history' feature.
* @param {Function} getInput - collects the input from UI into JSON-serializable object
* @param {Function} applyInput - refreshes the UI according to input
* */
history(getInput: () => any, applyInput: (x: any) => void): void {
api.grok_Dialog_History(this.dart, getInput, applyInput);
}
/** Initializes default history. */
initDefaultHistory(): Dialog {
api.grok_Dialog_InitDefaultHistory(this.dart);
return this;
}
/** Clears the content. */
clear() {
api.grok_Dialog_Clear(this.dart);
}
/** Returns currently open dialogs. */
static getOpenDialogs(): Dialog[] {
return api.grok_Dialog_GetOpenDialogs();
}
}
/** See {@link Menu.items} */
export interface IMenuItemsOptions<T = any> {
/** Whether a check box appears before the item */
isChecked?: (item: T) => boolean;
/** If result is not null, the item is grayed out and the result is shown in the tooltip */
isValid?: (item: T) => string | null;
/** Text to be shown on the menu item */
toString?: (item: T) => string;
/** Tooltip */
getTooltip?: (item: T) => string;
/** Gets invoked when the mouse enters the item */
onMouseEnter?: (item: T) => void;
/** Identifies a group of items where only one can be checked at a time. */
radioGroup?: string;
}
export interface IMenuItemOptions {
/** Identifies a group of items where only one can be checked at a time. */
radioGroup?: string;
/** Position in the menu */
order?: number;
/** Shortcut to be shown on the item. NOTE: it does not handle the keypress, just shows the shortcut*/
shortcut?: string;
/** Whether the menu is visible; if false, the menu is not added. Might be handy in for-loops and fluent API. */
visible?: boolean;
/** A function that gets called each time an item is shown.
* Should return null if the item is enabled, otherwise the reason why it's disabled.
* The reason for being disabled is shown in a tooltip. */
isEnabled?: () => (string | null);
/** For items preceded by checkboxes, indicates if the item is checked. */
check?: boolean;
/** Tooltip to be shown on the menu item */
description?: string;
}
export interface IShowMenuOptions {
element?: HTMLElement,
causedBy?: MouseEvent,
x?: number,
y?: number,
nextToElement?: boolean
}
/**
* Menu (either top menu or popup menu).
* Top menu sample: {@link https://public.datagrok.ai/js/samples/ui/menu}
* Popup menu sample: {@link https://public.datagrok.ai/js/samples/ui/popup-menu}
*
* @example
* DG.Menu.popup()
* .item('Show info', () => grok.shell.info('Info'))
* .separator()
* .items(['First', 'Second'], (s) => grok.shell.info(s))
* .show();
* */
export class Menu {
dart: any;
_check: HTMLDivElement = ui.div('d4-menu-item-check');
constructor(dart: any) {
this.dart = dart;
}
static create(): Menu {
return toJs(api.grok_Menu());
}
/** Creates a popup menu. */
static popup(): Menu {
return toJs(api.grok_Menu_Context());
}
get root(): HTMLElement { return api.grok_Menu_Get_Root(this.dart); }
/** Finds a child menu item with the specified text. */
find(text: string): Menu {
return toJs(api.grok_Menu_Find(this.dart, text));
}
/** Executes the onClick function for that menu item.
* Only works for items, not groups. */
click(): void {
api.grok_Menu_Click(this.dart);
}
/** Removes a child menu item with the specified text. */
remove(text: string): void {
api.grok_Menu_Remove(this.dart, text);
}
/** Removes all child menu items. */
clear(): void {
api.grok_Menu_Clear(this.dart);
}
/** Returns an existing menu group or adds a new group with the specified text. */
group(text: string, order: number | null = null): Menu {
return toJs(api.grok_Menu_Group(this.dart, text, order));
}
/** Ends a group of menu items and returns to the higher menu level.
* @returns {Menu} */
endGroup(): Menu {
return toJs(api.grok_Menu_EndGroup(this.dart));
}
/** Adds a menu group with the specified text and handler. */
item(text: string, onClick: () => void, order: number | null = null, options: IMenuItemOptions | null = null): Menu {
return toJs(api.grok_Menu_Item(this.dart, text, onClick, order, options));
}
/** For each item in items, adds a menu group with the specified text and handler. */
items<T = any>(items: T[], onClick: (item: T) => void, options: IMenuItemsOptions<T> | null = null): Menu {
return toJs(api.grok_Menu_Items(this.dart, items, onClick, options?.isValid, options?.isChecked,
options?.hasOwnProperty('toString') ? options.toString : null,
options?.getTooltip, options?.onMouseEnter, options?.radioGroup));
}
/** Adds a separator line.
* @returns {Menu} */
separator(): Menu {
return toJs(api.grok_Menu_Separator(this.dart));
}
/** Shows the menu.
* @returns {Menu} */
show(options?: IShowMenuOptions): Menu {
return toJs(api.grok_Menu_Show(this.dart, options?.element, options?.causedBy, options?.x, options?.y, options?.nextToElement));
}
/** Binds the menu to the specified {@link options.element} */
bind(element: HTMLElement): Menu {
element.oncontextmenu = (ev) => {
ev.preventDefault();
this.show({causedBy: ev});
}
return this;
}
get onContextMenuItemClick() {
return __obs('d4-menu-item-click', this.dart);
}
toString(): string {
return api.grok_MenuItem_ToString(this.dart);
}
}
/** Balloon-style visual notifications. */
export class Balloon {
/** Shows information message (green background) */
info(s: string | HTMLElement): void {
api.grok_Balloon(s, 'info');
}
/** Shows information message (red background) */
error(s: string | HTMLElement): void {
api.grok_Balloon(s, 'error');
}
/** Closes all balloons currently shown */
static closeAll(): void {
api.grok_Balloon_CloseAll();
}
}
/** Class for code input editor. */
export class CodeEditor {
dart: any;
constructor(dart: any) {
this.dart = dart;
}
static create(script = '', mode = 'javascript', placeholder = ''): CodeEditor {