forked from bloomberg/ipydatagrid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
feathergrid.ts
983 lines (845 loc) · 28 KB
/
feathergrid.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
import { PanelLayout, Widget } from '@lumino/widgets';
import { Message, IMessageHandler, MessageLoop } from '@lumino/messaging';
import {
BasicMouseHandler,
BasicKeyHandler,
TextRenderer,
DataModel,
BasicSelectionModel,
CellRenderer,
RendererMap,
} from '@lumino/datagrid';
import { CommandRegistry } from '@lumino/commands';
import { toArray } from '@lumino/algorithm';
import { Signal, ISignal } from '@lumino/signaling';
import { DataGrid } from './core/datagrid';
import { HeaderRenderer } from './core/headerRenderer';
import { InteractiveFilterDialog } from './core/filterMenu';
import { FeatherGridContextMenu } from './core/gridContextMenu';
import { ViewBasedJSONModel } from './core/viewbasedjsonmodel';
import { Transform } from './core/transform';
import { Theme } from './utils';
import '@lumino/default-theme/style/datagrid.css';
import '../style/feathergrid.css';
// Shorthand for a string->T mapping
type Dict<T> = { [keys: string]: T };
/*
This type has some of the properties of the ResizeColumnRequest Message which
is what is being intercepted in the Message Hook. Because the original Message
is in a Private namespace and we cannot access it, we are using this type.
*/
type FeatherGridColumnResizeMessage = {
region: DataModel.ColumnRegion;
index: number;
size: number;
};
// var name: [light theme value, dark theme value]
const themeVariables: Map<string, string[]> = new Map([
[
'--ipydatagrid-filter-icon',
[
'var(--ipydatagrid-filter-icon-light)',
'var(--ipydatagrid-filter-icon-dark)',
],
],
[
'--ipydatagrid-sort-asc-icon',
[
'var(--ipydatagrid-sort-asc-icon-light)',
'var(--ipydatagrid-sort-asc-icon-dark)',
],
],
[
'--ipydatagrid-sort-desc-icon',
[
'var(--ipydatagrid-sort-desc-icon-light)',
'var(--ipydatagrid-sort-desc-icon-dark)',
],
],
['--ipydatagrid-layout-color0', ['white', '#111111']],
['--ipydatagrid-layout-color1', ['white', '#212121']],
['--ipydatagrid-layout-color2', ['#eeeeee', '#424242']],
['--ipydatagrid-layout-color3', ['#bdbdbd', '#616161']],
['--ipydatagrid-layout-color4', ['#757575', '#757575']],
[
'--ipydatagrid-ui-font-color0',
['rgba(0, 0, 0, 1)', 'rgba(255, 255, 255, 1)'],
],
[
'--ipydatagrid-ui-font-color1',
['rgba(0, 0, 0, 0.87)', 'rgba(255, 255, 255, 0.87)'],
],
[
'--ipydatagrid-ui-font-color2',
['rgba(0, 0, 0, 0.54)', 'rgba(255, 255, 255, 0.54)'],
],
[
'--ipydatagrid-ui-font-color3',
['rgba(0, 0, 0, 0.38)', 'rgba(255, 255, 255, 0.38)'],
],
['--ipydatagrid-border-color0', ['#bdbdbd', '#616161']],
['--ipydatagrid-border-color1', ['#bdbdbd', '#616161']],
['--ipydatagrid-border-color2', ['#e0e0e0', '#424242']],
['--ipydatagrid-border-color3', ['#eeeeee', '#212121']],
['--ipydatagrid-brand-color0', ['#1976d2', '#1976d2']],
['--ipydatagrid-brand-color1', ['#2196f3', '#2196f3']],
['--ipydatagrid-brand-color2', ['#64b5f6', '#64b5f6']],
['--ipydatagrid-brand-color3', ['#bbdefb', '#bbdefb']],
['--ipydatagrid-brand-color4', ['#e3f2fd', '#e3f2fd']],
['--ipydatagrid-brand-color5', ['#00e6ff', '#00e6ff']],
['--ipydatagrid-brand-color6', ['#ffe100', '#ffe100']],
['--ipydatagrid-brand-color7', ['#009eb0', '#009eb0']],
['--ipydatagrid-brand-color8', ['#b09b00', '#b09b00']],
['--ipydatagrid-menu-bgcolor', ['white', 'black']],
['--ipydatagrid-menu-border-color', ['#bdbdbd', '#616161']],
['--ipydatagrid-filter-dlg-textcolor', ['black', 'white']],
['--ipydatagrid-filter-dlg-bgcolor', ['white', 'black']],
]);
class FeatherGridMouseHandler extends BasicMouseHandler {
/**
* Construct a new datagrid mouse handler.
*
* @param grid - The FeatherGrid object for which mouse events are handled.
*/
constructor(grid: FeatherGrid) {
super();
this._grid = grid;
}
/**
* Handle the mouse down event for the data grid.
*
* @param grid - The data grid of interest.
*
* @param event - The mouse down event of interest.
*/
//@ts-ignore added so we don't have to add basicmousehandler.ts fork
onMouseDown(grid: DataGrid, event: MouseEvent): void {
const hit = grid.hitTest(event.clientX, event.clientY);
const hitRegion = hit.region;
const buttonSize = HeaderRenderer.iconWidth * 1.5;
const buttonPadding = HeaderRenderer.buttonPadding;
this._mouseIsDown = true;
// Send cell clicked signal
if (hit.region !== 'void') {
this._cellClicked.emit(hit);
}
if (hitRegion === 'corner-header' || hitRegion === 'column-header') {
const columnWidth = grid.columnSize(
hitRegion === 'corner-header' ? 'row-header' : 'body',
hit.column,
);
const rowHeight = grid.rowSize('column-header', hit.row);
const isMenuRow =
(hit.region === 'column-header' &&
hit.row ==
this._grid.grid.dataModel!.rowCount('column-header') - 1) ||
(hit.region === 'corner-header' && hit.row === 0);
const isMenuClick =
hit.x > columnWidth - buttonSize - buttonPadding &&
hit.x < columnWidth - buttonPadding &&
hit.y > rowHeight - buttonSize - buttonPadding &&
hit.y < rowHeight - buttonPadding &&
isMenuRow;
if (isMenuClick) {
this._grid.contextMenu.open(grid, {
...hit,
x: event.clientX,
y: event.clientY,
});
return;
}
}
//@ts-ignore added so we don't have to add basicmousehandler.ts fork
super.onMouseDown(grid, event);
}
//@ts-ignore added so we don't have to add basicmousehandler.ts fork
onMouseUp(grid: DataGrid, event: MouseEvent): void {
this._mouseIsDown = false;
//@ts-ignore added so we don't have to add basicmousehandler.ts fork
super.onMouseUp(grid, event);
}
get mouseIsDown(): boolean {
return this._mouseIsDown;
}
/**
* A signal emitted when a grid cell is clicked.
*/
get cellClicked(): ISignal<this, DataGrid.HitTestResult> {
return this._cellClicked;
}
private _grid: FeatherGrid;
private _mouseIsDown = false;
private _cellClicked = new Signal<this, DataGrid.HitTestResult>(this);
}
export class FeatherGrid extends Widget {
constructor(options: DataGrid.IOptions = {}) {
super();
this.addClass('ipydatagrid-widget');
if (options.defaultSizes) {
this._baseRowSize = options.defaultSizes.rowHeight || this._baseRowSize;
this._baseColumnSize =
options.defaultSizes.columnWidth || this._baseColumnSize;
this._baseRowHeaderSize =
options.defaultSizes.rowHeaderWidth || this._baseRowHeaderSize;
this._baseColumnHeaderSize =
options.defaultSizes.columnHeaderHeight || this._baseColumnHeaderSize;
}
this._headerVisibility = options.headerVisibility || this._headerVisibility;
this._createGrid(options);
this._defaultRenderer = new TextRenderer({
font: '12px sans-serif',
textColor: Theme.getFontColor(),
backgroundColor: Theme.getBackgroundColor(),
horizontalAlignment: 'center',
verticalAlignment: 'center',
});
this._rowHeaderRenderer = new TextRenderer({
textColor: Theme.getFontColor(1),
backgroundColor: Theme.getBackgroundColor(2),
horizontalAlignment: 'center',
verticalAlignment: 'center',
});
const layout = (this.layout = new PanelLayout());
layout.addWidget(this.grid);
}
/**
* Intercepts the column-resize-request message sent to a message handler
* and updates the data model to have the correct column widths
*
* @param handler - The target handler of the message.
*
* @param msg - The message to be sent to the handler.
*
* @returns `true` if the message should continue to be processed
* as normal, or `false` if processing should cease immediately.
*/
messageHook(handler: IMessageHandler, msg: Message): boolean {
if (handler === this.grid.viewport) {
// //@ts-ignore added so we don't have to add basicmousehandler.ts fork
const mouseHandler = (this.grid
.mouseHandler as unknown) as FeatherGridMouseHandler;
if (msg.type === 'column-resize-request' && mouseHandler.mouseIsDown) {
const resizeMsg = (msg as unknown) as FeatherGridColumnResizeMessage;
const columnName: string = this.dataModel.columnIndexToName(
resizeMsg.index,
resizeMsg.region,
);
this._columnWidths[columnName] = resizeMsg.size;
this._columnsResized.emit();
return true;
}
}
return true;
}
set dataModel(model: ViewBasedJSONModel) {
this._dataModel = model;
if (!this.grid) {
return;
}
this.grid.dataModel = this._dataModel;
this._filterDialog.model = this._dataModel;
this._updateColumnWidths();
}
get dataModel(): ViewBasedJSONModel {
return this._dataModel;
}
set baseRowSize(size: number) {
this._baseRowSize = size;
if (!this.grid) {
return;
}
this.grid.defaultSizes = { ...this.grid.defaultSizes, rowHeight: size };
}
get baseRowSize(): number {
return this._baseRowSize;
}
set baseColumnSize(size: number) {
this._baseColumnSize = size;
if (!this.grid) {
return;
}
this.grid.defaultSizes = { ...this.grid.defaultSizes, columnWidth: size };
this._updateColumnWidths();
}
get baseColumnSize(): number {
return this._baseColumnSize;
}
set columnWidths(widths: Dict<number>) {
this._columnWidths = widths;
if (!this.grid) {
return;
}
this._updateColumnWidths();
}
get columnWidths(): Dict<number> {
return this._columnWidths;
}
set baseRowHeaderSize(size: number) {
this._baseRowHeaderSize = size;
if (!this.grid) {
return;
}
this.grid.defaultSizes = {
...this.grid.defaultSizes,
rowHeaderWidth: size,
};
this._updateColumnWidths();
}
get baseRowHeaderSize(): number {
return this._baseRowHeaderSize;
}
set baseColumnHeaderSize(size: number) {
this._baseColumnHeaderSize = size;
if (!this.grid) {
return;
}
this.grid.defaultSizes = {
...this.grid.defaultSizes,
columnHeaderHeight: size,
};
}
get baseColumnHeaderSize(): number {
return this._baseColumnHeaderSize;
}
set headerVisibility(visibility: DataGrid.HeaderVisibility) {
this._headerVisibility = visibility;
if (!this.grid) {
return;
}
this.grid.headerVisibility = visibility;
this._updateColumnWidths();
}
get headerVisibility(): DataGrid.HeaderVisibility {
return this._headerVisibility;
}
set defaultRenderer(renderer: CellRenderer) {
this._defaultRenderer = renderer;
this._defaultRendererSet = true;
if (!this.grid) {
return;
}
this._updateGridRenderers();
}
get defaultRenderer(): CellRenderer {
return this._defaultRenderer;
}
set columnHeaderRenderer(renderer: CellRenderer) {
this._columnHeaderRenderer = renderer;
if (!this.grid) {
return;
}
this._updateGridRenderers();
}
get columnHeaderRenderer(): CellRenderer {
return this._columnHeaderRenderer;
}
set renderers(renderers: Dict<CellRenderer>) {
this._renderers = renderers;
if (!this.grid) {
return;
}
this._updateGridRenderers();
}
get renderers(): Dict<CellRenderer> {
return this._renderers;
}
set selectionModel(model: BasicSelectionModel | null) {
this._selectionModel = model;
if (!this.grid) {
return;
}
this.grid.selectionModel = this._selectionModel;
}
set editable(value: boolean) {
this._editable = value;
if (!this.grid) {
return;
}
this.grid.editingEnabled = value;
}
get editable(): boolean {
return this._editable;
}
get cellRenderers(): RendererMap {
return this.grid.cellRenderers;
}
private _createGrid(options: DataGrid.IOptions = {}) {
this.grid = new DataGrid({
...options,
...{
defaultSizes: {
rowHeight: this._baseRowSize,
columnWidth: this._baseColumnSize,
rowHeaderWidth: this._baseRowHeaderSize,
columnHeaderHeight: this._baseColumnHeaderSize,
},
headerVisibility: this._headerVisibility,
},
});
MessageLoop.installMessageHook(this.grid.viewport, this);
this._filterDialog = new InteractiveFilterDialog({
model: this._dataModel,
});
this.contextMenu = new FeatherGridContextMenu({
grid: this.grid,
commands: this._createCommandRegistry(),
});
// Replace method of copying to clipboard with one that allows
// a ClipboardEvent to reach document.body
this.grid.copyToClipboard = this.copyToClipboard.bind(this.grid);
this.grid.dataModel = this._dataModel;
//@ts-ignore **added so we can remove basickeyhandler.ts from fork
this.grid.keyHandler = new BasicKeyHandler();
const mouseHandler = new FeatherGridMouseHandler(this);
mouseHandler.cellClicked.connect(
(sender: FeatherGridMouseHandler, hit: DataGrid.HitTestResult) => {
if (!this.grid.dataModel) {
return;
}
const dataModel = this.grid.dataModel as ViewBasedJSONModel;
const region = hit.region as DataModel.CellRegion;
this._cellClicked.emit({
region: region as DataModel.CellRegion,
column: dataModel.metadata(region, hit.row, hit.column)['name'],
columnIndex: hit.column,
row: hit.row,
primaryKeyRow: dataModel.getDatasetRowFromView(region, hit.row),
cellValue: dataModel.data(region, hit.row, hit.column),
});
},
);
//@ts-ignore added so we don't have to add basicmousehandler.ts fork
this.grid.mouseHandler = mouseHandler;
this.grid.selectionModel = this._selectionModel;
this.grid.editingEnabled = this._editable;
this.updateGridStyle();
this._updateGridRenderers();
this._updateColumnWidths();
}
public updateGridStyle() {
if (!this._defaultRendererSet) {
this._defaultRenderer = new TextRenderer({
font: '12px sans-serif',
textColor: Theme.getFontColor(),
backgroundColor: Theme.getBackgroundColor(),
horizontalAlignment: 'left',
verticalAlignment: 'center',
});
}
this._rowHeaderRenderer = new TextRenderer({
textColor: Theme.getFontColor(1),
backgroundColor: Theme.getBackgroundColor(2),
horizontalAlignment: 'center',
verticalAlignment: 'center',
});
this._columnHeaderRenderer = new TextRenderer({
textColor: Theme.getFontColor(1),
backgroundColor: Theme.getBackgroundColor(2),
horizontalAlignment: 'left',
verticalAlignment: 'center',
});
const scrollShadow = {
size: 4,
color1: Theme.getBorderColor(1, 1.0),
color2: Theme.getBorderColor(1, 0.5),
color3: Theme.getBorderColor(1, 0.0),
};
this.grid.style = {
voidColor: Theme.getBackgroundColor(),
backgroundColor: Theme.getBackgroundColor(),
gridLineColor: Theme.getBorderColor(),
headerGridLineColor: Theme.getBorderColor(1),
selectionFillColor: Theme.getBrandColor(2, 0.4),
selectionBorderColor: Theme.getBrandColor(1),
headerSelectionFillColor: Theme.getBackgroundColor(3, 0.4),
headerSelectionBorderColor: Theme.getBorderColor(1),
cursorFillColor: Theme.getBrandColor(3, 0.4),
cursorBorderColor: Theme.getBrandColor(1),
scrollShadow: scrollShadow,
};
}
copyToClipboard(): void {
const grid = <DataGrid>(<unknown>this);
// Fetch the data model.
const dataModel = grid.dataModel;
// Bail early if there is no data model.
if (!dataModel) {
return;
}
// Fetch the selection model.
const selectionModel = grid.selectionModel;
// Bail early if there is no selection model.
if (!selectionModel) {
return;
}
// Coerce the selections to an array.
const selections = toArray(selectionModel.selections());
// Bail early if there are no selections.
if (selections.length === 0) {
return;
}
// Alert that multiple selections cannot be copied.
if (selections.length > 1) {
alert('Cannot copy multiple grid selections.');
return;
}
// Fetch the model counts.
const br = dataModel.rowCount('body');
const bc = dataModel.columnCount('body');
// Bail early if there is nothing to copy.
if (br === 0 || bc === 0) {
return;
}
// Unpack the selection.
let { r1, c1, r2, c2 } = selections[0];
// Clamp the selection to the model bounds.
r1 = Math.max(0, Math.min(r1, br - 1));
c1 = Math.max(0, Math.min(c1, bc - 1));
r2 = Math.max(0, Math.min(r2, br - 1));
c2 = Math.max(0, Math.min(c2, bc - 1));
// Ensure the limits are well-orderd.
if (r2 < r1) [r1, r2] = [r2, r1];
if (c2 < c1) [c1, c2] = [c2, c1];
// Fetch the header counts.
let rhc = dataModel.columnCount('row-header');
let chr = dataModel.rowCount('column-header');
// Unpack the copy config.
const separator = grid.copyConfig.separator;
const format = grid.copyConfig.format;
const headers = grid.copyConfig.headers;
const warningThreshold = grid.copyConfig.warningThreshold;
// Compute the number of cells to be copied.
let rowCount = r2 - r1 + 1;
let colCount = c2 - c1 + 1;
switch (headers) {
case 'none':
rhc = 0;
chr = 0;
break;
case 'row':
chr = 0;
colCount += rhc;
break;
case 'column':
rhc = 0;
rowCount += chr;
break;
case 'all':
rowCount += chr;
colCount += rhc;
break;
default:
throw 'unreachable';
}
// Compute the total cell count.
const cellCount = rowCount * colCount;
// Allow the user to cancel a large copy request.
if (cellCount > warningThreshold) {
const msg = `Copying ${cellCount} cells may take a while. Continue?`;
if (!window.confirm(msg)) {
return;
}
}
// Set up the format args.
const args = {
region: 'body' as DataModel.CellRegion,
row: 0,
column: 0,
value: null as any,
metadata: {} as DataModel.Metadata,
};
// Allocate the array of rows.
const rows = new Array<string[]>(rowCount);
// Iterate over the rows.
for (let j = 0; j < rowCount; ++j) {
// Allocate the array of cells.
const cells = new Array<string>(colCount);
// Iterate over the columns.
for (let i = 0; i < colCount; ++i) {
// Set up the format variables.
let region: DataModel.CellRegion;
let row: number;
let column: number;
// Populate the format variables.
if (j < chr && i < rhc) {
region = 'corner-header';
row = j;
column = i;
} else if (j < chr) {
region = 'column-header';
row = j;
column = i - rhc + c1;
} else if (i < rhc) {
region = 'row-header';
row = j - chr + r1;
column = i;
} else {
region = 'body';
row = j - chr + r1;
column = i - rhc + c1;
}
// Populate the format args.
args.region = region;
args.row = row;
args.column = column;
args.value = dataModel.data(region, row, column);
args.metadata = dataModel.metadata(region, row, column);
// Format the cell.
cells[i] = format(args);
}
// Save the row of cells.
rows[j] = cells;
}
// Convert the cells into lines.
const lines = rows.map((cells) => cells.join(separator));
// Convert the lines into text.
const text = lines.join('\n');
// Copy the text to the clipboard.
const textArea = document.createElement('textarea');
textArea.innerHTML = text;
// Text area has to be visible on page for copy without Clipboard API,
// So we create an "invisible" element, add it to the body, then remove
// when no longer needed.
textArea.style.height = '0px';
textArea.style.width = '0px';
textArea.style.overflow = 'hidden';
textArea.id = 'ipydatagrid-textarea';
textArea.style.position = 'absolute';
document.body.appendChild(textArea);
textArea.select();
document.execCommand('copy');
document.body.removeChild(textArea);
}
/**
* A signal emitted when a grid cell is clicked.
*/
get cellClicked(): ISignal<this, FeatherGrid.ICellClickedEvent> {
return this._cellClicked;
}
/**
* A signal emitted when a grid column is resized.
*/
get columnsResized(): ISignal<this, void> {
return this._columnsResized;
}
set isLightTheme(value: boolean) {
this._isLightTheme = value;
let themeIndex = 0;
if (value) {
this.removeClass('dark');
} else {
this.addClass('dark');
themeIndex = 1;
}
const root = document.documentElement;
themeVariables.forEach((options: string[], name: string) => {
root.style.setProperty(name, options[themeIndex]);
});
this.updateGridStyle();
}
get isLightTheme(): boolean {
return this._isLightTheme;
}
/**
*
* RendererMap.Resolver function to select a CellRenderer based on the
* provided cell metadata.
*
* @param config - CellConfig for the cell to be rendered.
*/
private _rendererResolver(config: CellRenderer.CellConfig): CellRenderer {
const columnName: string = config.metadata['name'];
const cellRegion: string = config['region'];
return this._renderers.hasOwnProperty(columnName)
? this._renderers[columnName]
: cellRegion === 'row-header'
? this._rowHeaderRenderer
: this._defaultRenderer;
}
private _updateGridRenderers() {
this.grid.cellRenderers.update({ body: this._rendererResolver.bind(this) });
this.grid.cellRenderers.update({
'column-header': this._columnHeaderRenderer,
});
// Treating corner header as column header for rendering purposes
this.grid.cellRenderers.update({
'corner-header': this._columnHeaderRenderer,
});
this.grid.cellRenderers.update({
'row-header': this._rendererResolver.bind(this),
});
}
private _updateColumnWidths() {
const columnWidths = this._columnWidths;
// @ts-ignore added so we don't have to add basicmousehandler.ts fork
const mouseHandler = this.grid.mouseHandler as FeatherGridMouseHandler;
// Do not want this callback to be executed when user resizes using the mouse
if (mouseHandler.mouseIsDown) {
return;
}
// Resizing columns from row header region
if (this._headerVisibility === 'row' || this._headerVisibility === 'all') {
const baseRowHeaderSize = this._baseRowHeaderSize;
const rowHeaderColCount = this.grid.columnCount('row-header');
for (let i = 0; i < rowHeaderColCount; i++) {
const colName = this.dataModel.columnIndexToName(i, 'row-header');
const colSize = columnWidths.hasOwnProperty(colName)
? columnWidths[colName]
: baseRowHeaderSize;
this.grid.resizeColumn('row-header', i, colSize);
}
}
// Resizing columns from body region
const baseColumnSize = this._baseColumnSize;
const bodyColCount = this.grid.columnCount('body');
for (let i = 0; i < bodyColCount; i++) {
const colName = this.dataModel.columnIndexToName(i, 'body');
const colSize = columnWidths.hasOwnProperty(colName)
? columnWidths[colName]
: baseColumnSize;
this.grid.resizeColumn('body', i, colSize);
}
}
private _createCommandRegistry(): CommandRegistry {
const commands = new CommandRegistry();
commands.addCommand(FeatherGridContextMenu.CommandID.SortAscending, {
label: 'Sort Ascending',
mnemonic: 1,
iconClass:
'ipydatagrid-filterMenuIcon ipydatagrid-filterMenuIcon-sortAsc',
execute: (args): void => {
const cellClick: FeatherGridContextMenu.CommandArgs = args as FeatherGridContextMenu.CommandArgs;
const colIndex = this._dataModel.getSchemaIndex(
cellClick.region,
cellClick.columnIndex,
);
this._dataModel.addTransform({
type: 'sort',
columnIndex: colIndex,
desc: false,
});
},
});
commands.addCommand(FeatherGridContextMenu.CommandID.SortDescending, {
label: 'Sort Descending',
mnemonic: 1,
iconClass:
'ipydatagrid-filterMenuIcon ipydatagrid-filterMenuIcon-sortDesc',
execute: (args) => {
const cellClick: FeatherGridContextMenu.CommandArgs = args as FeatherGridContextMenu.CommandArgs;
const colIndex = this._dataModel.getSchemaIndex(
cellClick.region,
cellClick.columnIndex,
);
this._dataModel.addTransform({
type: 'sort',
columnIndex: colIndex,
desc: true,
});
},
});
commands.addCommand(FeatherGridContextMenu.CommandID.ClearThisFilter, {
label: 'Clear This Filter',
mnemonic: -1,
execute: (args) => {
const commandArgs = <FeatherGridContextMenu.CommandArgs>args;
const schemaIndex: number = this._dataModel.getSchemaIndex(
commandArgs.region,
commandArgs.columnIndex,
);
this._dataModel.removeTransform(schemaIndex, 'filter');
},
});
commands.addCommand(
FeatherGridContextMenu.CommandID.ClearFiltersInAllColumns,
{
label: 'Clear Filters in All Columns',
mnemonic: -1,
execute: (args) => {
const activeTransforms: Transform.TransformSpec[] = this._dataModel
.activeTransforms;
const newTransforms = activeTransforms.filter(
(val) => val.type !== 'filter',
);
this._dataModel.replaceTransforms(newTransforms);
},
},
);
commands.addCommand(
FeatherGridContextMenu.CommandID.OpenFilterByConditionDialog,
{
label: 'Filter by condition...',
mnemonic: 4,
iconClass:
'ipydatagrid-filterMenuIcon ipydatagrid-filterMenuIcon-filter',
execute: (args) => {
const commandArgs = <FeatherGridContextMenu.CommandArgs>args;
this._filterDialog.open({
x: commandArgs.clientX,
y: commandArgs.clientY,
region: commandArgs.region,
columnIndex: commandArgs.columnIndex,
forceX: false,
forceY: false,
mode: 'condition',
});
},
},
);
commands.addCommand(
FeatherGridContextMenu.CommandID.OpenFilterByValueDialog,
{
label: 'Filter by value...',
mnemonic: 4,
iconClass:
'ipydatagrid-filterMenuIcon ipydatagrid-filterMenuIcon-filter',
execute: (args) => {
const commandArgs = <FeatherGridContextMenu.CommandArgs>args;
this._filterDialog.open({
x: commandArgs.clientX,
y: commandArgs.clientY,
region: commandArgs.region,
columnIndex: commandArgs.columnIndex,
forceX: false,
forceY: false,
mode: 'value',
});
},
},
);
return commands;
}
grid: DataGrid;
contextMenu: FeatherGridContextMenu;
private _filterDialog: InteractiveFilterDialog;
private _baseRowSize = 20;
private _baseColumnSize = 64;
private _baseRowHeaderSize = 64;
private _baseColumnHeaderSize = 20;
private _columnWidths: Dict<number> = {};
private _headerVisibility: DataGrid.HeaderVisibility = 'all';
private _dataModel: ViewBasedJSONModel;
private _selectionModel: BasicSelectionModel | null;
private _editable: boolean;
private _renderers: Dict<CellRenderer> = {};
private _defaultRenderer: CellRenderer;
private _columnHeaderRenderer: CellRenderer;
private _rowHeaderRenderer: CellRenderer;
private _defaultRendererSet = false;
private _cellClicked = new Signal<this, FeatherGrid.ICellClickedEvent>(this);
private _columnsResized = new Signal<this, void>(this);
private _isLightTheme = true;
}
/**
* The namespace for the `FeatherGrid` class statics.
*/
export namespace FeatherGrid {
export interface ICellClickedEvent {
readonly region: DataModel.CellRegion;
column: string;
columnIndex: number;
row: number;
primaryKeyRow: number;
cellValue: any;
}
}