Debian Codegraph @

js/feathergrid.ts

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 import { CommandRegistry } from '@lumino/commands';
2 import {
3 BasicSelectionModel,
4 CellRenderer,
5 DataGrid,
6 DataModel,
7 RendererMap,
8 TextRenderer,
9 } from '@lumino/datagrid';
10 import { IMessageHandler, Message, MessageLoop } from '@lumino/messaging';
11 import { ISignal, Signal } from '@lumino/signaling';
12 import { PanelLayout, Widget } from '@lumino/widgets';
13 import { InteractiveFilterDialog } from './core/filterMenu';
14 import { FeatherGridContextMenu } from './core/gridContextMenu';
15 import { HeaderRenderer } from './core/headerRenderer';
16 import { Transform } from './core/transform';
17 import { ViewBasedJSONModel } from './core/viewbasedjsonmodel';
18 import { KeyHandler } from './keyhandler';
19 import { MouseHandler as FeatherGridMouseHandler } from './mousehandler';
20 import { Theme } from './utils';
21
22 import { DataGridModel as BackBoneModel } from './datagrid';
23
24 import '@lumino/default-theme/style/datagrid.css';
25 import '../style/feathergrid.css';
26
27 // Shorthand for a string->T mapping
28 type Dict<T> = { [keys: string]: T };
29
30 /*
31 This type has some of the properties of the ResizeColumnRequest Message which
32 is what is being intercepted in the Message Hook. Because the original Message
33 is in a Private namespace and we cannot access it, we are using this type.
34 */
35 type FeatherGridColumnResizeMessage = {
36 region: DataModel.ColumnRegion;
37 index: number;
38 size: number;
39 };
40
41 // var name: [light theme value, dark theme value]
42 const themeVariables: Map<string, string[]> = new Map([
43 [
44 '--ipydatagrid-filter-icon',
45 [
46 'var(--ipydatagrid-filter-icon-light)',
47 'var(--ipydatagrid-filter-icon-dark)',
48 ],
49 ],
50 [
51 '--ipydatagrid-sort-asc-icon',
52 [
53 'var(--ipydatagrid-sort-asc-icon-light)',
54 'var(--ipydatagrid-sort-asc-icon-dark)',
55 ],
56 ],
57 [
58 '--ipydatagrid-sort-desc-icon',
59 [
60 'var(--ipydatagrid-sort-desc-icon-light)',
61 'var(--ipydatagrid-sort-desc-icon-dark)',
62 ],
63 ],
64
65 ['--ipydatagrid-layout-color0', ['white', '#111111']],
66 ['--ipydatagrid-layout-color1', ['white', '#212121']],
67 ['--ipydatagrid-layout-color2', ['#eeeeee', '#424242']],
68 ['--ipydatagrid-layout-color3', ['#bdbdbd', '#616161']],
69 ['--ipydatagrid-layout-color4', ['#757575', '#757575']],
70
71 [
72 '--ipydatagrid-ui-font-color0',
73 ['rgba(0, 0, 0, 1)', 'rgba(255, 255, 255, 1)'],
74 ],
75 [
76 '--ipydatagrid-ui-font-color1',
77 ['rgba(0, 0, 0, 0.87)', 'rgba(255, 255, 255, 0.87)'],
78 ],
79 [
80 '--ipydatagrid-ui-font-color2',
81 ['rgba(0, 0, 0, 0.54)', 'rgba(255, 255, 255, 0.54)'],
82 ],
83 [
84 '--ipydatagrid-ui-font-color3',
85 ['rgba(0, 0, 0, 0.38)', 'rgba(255, 255, 255, 0.38)'],
86 ],
87
88 ['--ipydatagrid-border-color0', ['#bdbdbd', '#616161']],
89 ['--ipydatagrid-border-color1', ['#bdbdbd', '#616161']],
90 ['--ipydatagrid-border-color2', ['#e0e0e0', '#424242']],
91 ['--ipydatagrid-border-color3', ['#eeeeee', '#212121']],
92
93 ['--ipydatagrid-brand-color0', ['#1976d2', '#1976d2']],
94 ['--ipydatagrid-brand-color1', ['#2196f3', '#2196f3']],
95 ['--ipydatagrid-brand-color2', ['#64b5f6', '#64b5f6']],
96 ['--ipydatagrid-brand-color3', ['#bbdefb', '#bbdefb']],
97 ['--ipydatagrid-brand-color4', ['#e3f2fd', '#e3f2fd']],
98 ['--ipydatagrid-brand-color5', ['#00e6ff', '#00e6ff']],
99 ['--ipydatagrid-brand-color6', ['#ffe100', '#ffe100']],
100 ['--ipydatagrid-brand-color7', ['#009eb0', '#009eb0']],
101 ['--ipydatagrid-brand-color8', ['#b09b00', '#b09b00']],
102
103 ['--ipydatagrid-menu-bgcolor', ['white', 'black']],
104 ['--ipydatagrid-menu-border-color', ['#bdbdbd', '#616161']],
105 ['--ipydatagrid-filter-dlg-textcolor', ['black', 'white']],
106 ['--ipydatagrid-filter-dlg-bgcolor', ['white', 'black']],
107 ]);
108
109 export class FeatherGrid extends Widget {
110 constructor(options: DataGrid.IOptions = {}) {
111 super();
112 this.addClass('ipydatagrid-widget');
113
114 if (options.defaultSizes) {
115 this._baseRowSize = options.defaultSizes.rowHeight || this._baseRowSize;
116 this._baseColumnSize =
117 options.defaultSizes.columnWidth || this._baseColumnSize;
118 this._baseRowHeaderSize =
119 options.defaultSizes.rowHeaderWidth || this._baseRowHeaderSize;
120 this._baseColumnHeaderSize =
121 options.defaultSizes.columnHeaderHeight || this._baseColumnHeaderSize;
122 }
123 this._headerVisibility = options.headerVisibility || this._headerVisibility;
124
125 this._createGrid(options);
126
127 if (this.backboneModel) {
128 this.grid.copyConfig = this.backboneModel.get('copy_config');
129 }
130
131 this._defaultRenderer = new TextRenderer({
132 font: '12px sans-serif',
133 textColor: Theme.getFontColor(),
134 backgroundColor:
135 this.grid.style.backgroundColor || Theme.getBackgroundColor(),
136 horizontalAlignment: 'center',
137 verticalAlignment: 'center',
138 });
139
140 this._rowHeaderRenderer = new TextRenderer({
141 textColor: Theme.getFontColor(1),
142 backgroundColor:
143 this.grid.style.headerBackgroundColor || Theme.getBackgroundColor(2),
144 horizontalAlignment: 'center',
145 verticalAlignment: 'center',
146 });
147
148 const layout = (this.layout = new PanelLayout());
149 layout.addWidget(this.grid);
150 }
151
152 /**
153 * Intercepts the column-resize-request message sent to a message handler
154 * and updates the data model to have the correct column widths
155 *
156 * @param handler - The target handler of the message.
157 *
158 * @param msg - The message to be sent to the handler.
159 *
160 * @returns `true` if the message should continue to be processed
161 * as normal, or `false` if processing should cease immediately.
162 */
163 messageHook(handler: IMessageHandler, msg: Message): boolean {
164 if (handler === this.grid.viewport) {
165 const mouseHandler = this.grid
166 .mouseHandler as unknown as FeatherGridMouseHandler;
167
168 if (msg.type === 'column-resize-request' && mouseHandler.mouseIsDown) {
169 const resizeMsg = msg as unknown as FeatherGridColumnResizeMessage;
170 const columnName: string = this.dataModel.columnIndexToName(
171 resizeMsg.index,
172 resizeMsg.region,
173 );
174 this._columnWidths[columnName] = resizeMsg.size;
175 this._columnsResized.emit();
176 return true;
177 }
178 }
179 return true;
180 }
181
182 set dataModel(model: ViewBasedJSONModel) {
183 this._dataModel = model;
184
185 if (!this.grid) {
186 return;
187 }
188
189 this.grid.dataModel = this._dataModel;
190 this._updateHeaderRenderer();
191 this._filterDialog.model = this._dataModel;
192 this._updateColumnWidths();
193 }
194
195 get dataModel(): ViewBasedJSONModel {
196 return this._dataModel;
197 }
198
199 set baseRowSize(size: number) {
200 this._baseRowSize = size;
201
202 if (!this.grid) {
203 return;
204 }
205
206 this.grid.defaultSizes = { ...this.grid.defaultSizes, rowHeight: size };
207 }
208
209 get baseRowSize(): number {
210 return this._baseRowSize;
211 }
212
213 set baseColumnSize(size: number) {
214 this._baseColumnSize = size;
215
216 if (!this.grid) {
217 return;
218 }
219
220 this.grid.defaultSizes = { ...this.grid.defaultSizes, columnWidth: size };
221 this._updateColumnWidths();
222 }
223
224 get baseColumnSize(): number {
225 return this._baseColumnSize;
226 }
227
228 set columnWidths(widths: Dict<number>) {
229 this._columnWidths = widths;
230
231 if (!this.grid) {
232 return;
233 }
234
235 this._updateColumnWidths();
236 }
237
238 get columnWidths(): Dict<number> {
239 return this._columnWidths;
240 }
241
242 set baseRowHeaderSize(size: number) {
243 this._baseRowHeaderSize = size;
244
245 if (!this.grid) {
246 return;
247 }
248
249 this.grid.defaultSizes = {
250 ...this.grid.defaultSizes,
251 rowHeaderWidth: size,
252 };
253 this._updateColumnWidths();
254 }
255
256 get baseRowHeaderSize(): number {
257 return this._baseRowHeaderSize;
258 }
259
260 set baseColumnHeaderSize(size: number) {
261 this._baseColumnHeaderSize = size;
262
263 if (!this.grid) {
264 return;
265 }
266
267 this.grid.defaultSizes = {
268 ...this.grid.defaultSizes,
269 columnHeaderHeight: size,
270 };
271 }
272
273 get baseColumnHeaderSize(): number {
274 return this._baseColumnHeaderSize;
275 }
276
277 set headerVisibility(visibility: DataGrid.HeaderVisibility) {
278 this._headerVisibility = visibility;
279
280 if (!this.grid) {
281 return;
282 }
283
284 this.grid.headerVisibility = visibility;
285 this._updateColumnWidths();
286 }
287
288 get headerVisibility(): DataGrid.HeaderVisibility {
289 return this._headerVisibility;
290 }
291
292 set defaultRenderer(renderer: CellRenderer) {
293 this._defaultRenderer = renderer;
294 this._defaultRendererSet = true;
295
296 if (!this.grid) {
297 return;
298 }
299
300 this._updateGridRenderers();
301 }
302
303 get defaultRenderer(): CellRenderer {
304 return this._defaultRenderer;
305 }
306
307 set columnHeaderRenderer(renderer: CellRenderer) {
308 const textRenderer = renderer as TextRenderer;
309
310 // HeaderRenderer adds the filter dialogue box overlay
311 this._columnHeaderRenderer = new HeaderRenderer({
312 textOptions: {
313 font: textRenderer.font,
314 wrapText: textRenderer.wrapText,
315 elideDirection: textRenderer.elideDirection,
316 textColor: textRenderer.textColor,
317 backgroundColor:
318 this.grid.style.headerBackgroundColor ||
319 textRenderer.backgroundColor ||
320 Theme.getBackgroundColor(),
321 verticalAlignment: textRenderer.verticalAlignment,
322 horizontalAlignment: textRenderer.horizontalAlignment,
323 format: textRenderer.format,
324 },
325 isLightTheme: this._isLightTheme,
326 grid: this.grid,
327 });
328
329 if (!this.grid) {
330 return;
331 }
332
333 this._updateHeaderRenderer();
334 }
335
336 get columnHeaderRenderer(): CellRenderer {
337 return this._columnHeaderRenderer;
338 }
339
340 set cornerHeaderRenderer(renderer: CellRenderer) {
341 const textRenderer = renderer as TextRenderer;
342
343 // HeaderRenderer adds the filter dialogue box overlay
344 this._cornerHeaderRenderer = new HeaderRenderer({
345 textOptions: {
346 font: textRenderer.font,
347 wrapText: textRenderer.wrapText,
348 elideDirection: textRenderer.elideDirection,
349 textColor: textRenderer.textColor,
350 backgroundColor:
351 this.grid.style.headerBackgroundColor ||
352 textRenderer.backgroundColor ||
353 Theme.getBackgroundColor(),
354 verticalAlignment: textRenderer.verticalAlignment,
355 horizontalAlignment: textRenderer.horizontalAlignment,
356 format: textRenderer.format,
357 },
358 isLightTheme: this._isLightTheme,
359 grid: this.grid,
360 });
361
362 if (!this.grid) {
363 return;
364 }
365
366 this._updateHeaderRenderer();
367 }
368
369 get cornerHeaderRenderer(): CellRenderer {
370 return this._cornerHeaderRenderer;
371 }
372
373 set renderers(renderers: Dict<CellRenderer>) {
374 this._renderers = renderers;
375
376 if (!this.grid) {
377 return;
378 }
379
380 this._updateGridRenderers();
381 }
382
383 get renderers(): Dict<CellRenderer> {
384 return this._renderers;
385 }
386
387 set selectionModel(model: BasicSelectionModel | null) {
388 this._selectionModel = model;
389
390 if (!this.grid) {
391 return;
392 }
393
394 this.grid.selectionModel = this._selectionModel;
395 }
396
397 set editable(value: boolean) {
398 this._editable = value;
399
400 if (!this.grid) {
401 return;
402 }
403
404 this.grid.editingEnabled = value;
405 }
406
407 get editable(): boolean {
408 return this._editable;
409 }
410
411 get cellRenderers(): RendererMap {
412 return this.grid.cellRenderers;
413 }
414
415 private _createGrid(options: DataGrid.IOptions = {}) {
416 this.grid = new DataGrid({
417 ...options,
418 ...{
419 defaultSizes: {
420 rowHeight: this._baseRowSize,
421 columnWidth: this._baseColumnSize,
422 rowHeaderWidth: this._baseRowHeaderSize,
423 columnHeaderHeight: this._baseColumnHeaderSize,
424 },
425 headerVisibility: this._headerVisibility,
426 },
427 });
428
429 MessageLoop.installMessageHook(this.grid.viewport, this);
430
431 this._filterDialog = new InteractiveFilterDialog({
432 model: this._dataModel,
433 });
434
435 this.contextMenu = new FeatherGridContextMenu({
436 grid: this.grid,
437 commands: this._createCommandRegistry(),
438 });
439
440 this.grid.dataModel = this._dataModel;
441 this.grid.keyHandler = new KeyHandler();
442 const mouseHandler = new FeatherGridMouseHandler(this);
443 mouseHandler.cellClicked.connect(
444 (sender: FeatherGridMouseHandler, hit: DataGrid.HitTestResult) => {
445 if (!this.grid.dataModel) {
446 return;
447 }
448 const dataModel = this.grid.dataModel as ViewBasedJSONModel;
449 const region = hit.region as DataModel.CellRegion;
450 this._cellClicked.emit({
451 region: region as DataModel.CellRegion,
452 column: dataModel.metadata(region, hit.row, hit.column)['name'],
453 columnIndex: hit.column,
454 row: hit.row,
455 primaryKeyRow: dataModel.getDatasetRowFromView(region, hit.row),
456 cellValue: dataModel.data(region, hit.row, hit.column),
457 });
458 },
459 );
460
461 this.grid.mouseHandler = mouseHandler;
462 this.grid.selectionModel = this._selectionModel;
463 this.grid.editingEnabled = this._editable;
464
465 this.updateGridStyle();
466 this._updateGridRenderers();
467 this._updateColumnWidths();
468 }
469
470 public setGridStyle(): void {
471 // Setting up theme.
472 const scrollShadow = {
473 size: 4,
474 color1: Theme.getBorderColor(1, 1.0),
475 color2: Theme.getBorderColor(1, 0.5),
476 color3: Theme.getBorderColor(1, 0.0),
477 };
478
479 // Resetting grid style if theme changes.
480 if (this.backboneModel) {
481 this.grid.style = this.backboneModel.get('grid_style');
482 }
483 // Always apply FeatherGrid Theme
484 // if not rendered in ipydatagrid.
485 else {
486 this.grid.style = {
487 voidColor: Theme.getBackgroundColor(),
488 backgroundColor: Theme.getBackgroundColor(),
489 gridLineColor: Theme.getBorderColor(),
490 headerGridLineColor: Theme.getBorderColor(1),
491 selectionFillColor: Theme.getBrandColor(2, 0.4),
492 selectionBorderColor: Theme.getBrandColor(1),
493 headerSelectionFillColor: Theme.getBackgroundColor(3, 0.4),
494 headerSelectionBorderColor: Theme.getBorderColor(1),
495 cursorFillColor: Theme.getBrandColor(3, 0.4),
496 cursorBorderColor: Theme.getBrandColor(1),
497 scrollShadow,
498 };
499 // Terminate call here if rendering outside ipydatagrid.
500 return;
501 }
502
503 this.grid.style = {
504 voidColor: this.grid.style.voidColor || Theme.getBackgroundColor(),
505 backgroundColor:
506 this.grid.style.backgroundColor || Theme.getBackgroundColor(),
507 rowBackgroundColor: this.grid.style.rowBackgroundColor || undefined,
508 columnBackgroundColor: this.grid.style.columnBackgroundColor || undefined,
509 gridLineColor: this.grid.style.gridLineColor || Theme.getBorderColor(),
510 verticalGridLineColor: this.grid.style.verticalGridLineColor || undefined,
511 horizontalGridLineColor:
512 this.grid.style.horizontalGridLineColor || undefined,
513 headerBackgroundColor: this.grid.style.headerBackgroundColor || undefined,
514 headerGridLineColor:
515 this.grid.style.headerGridLineColor || Theme.getBorderColor(1),
516 headerVerticalGridLineColor:
517 this.grid.style.headerVerticalGridLineColor || undefined,
518 headerHorizontalGridLineColor:
519 this.grid.style.headerHorizontalGridLineColor || undefined,
520 selectionFillColor:
521 this.grid.style.selectionFillColor || Theme.getBrandColor(2, 0.4),
522 selectionBorderColor:
523 this.grid.style.selectionBorderColor || Theme.getBrandColor(1),
524 headerSelectionFillColor:
525 this.grid.style.headerSelectionFillColor ||
526 Theme.getBackgroundColor(3, 0.4),
527 headerSelectionBorderColor:
528 this.grid.style.headerSelectionBorderColor || Theme.getBorderColor(1),
529 cursorFillColor:
530 this.grid.style.cursorFillColor || Theme.getBrandColor(3, 0.4),
531 cursorBorderColor:
532 this.grid.style.cursorBorderColor || Theme.getBrandColor(1),
533 scrollShadow: this.grid.style.scrollShadow || scrollShadow,
534 };
535 }
536
537 public updateGridStyle(): void {
538 this.setGridStyle();
539
540 // If we are not rendering with ipydatagrid,
541 // defaultRenderer needs to be set each time.
542 if (!this._defaultRendererSet || !this.backboneModel) {
543 this.defaultRenderer = new TextRenderer({
544 font: '12px sans-serif',
545 textColor: Theme.getFontColor(),
546 backgroundColor:
547 this.grid.style.backgroundColor || Theme.getBackgroundColor(),
548 horizontalAlignment: 'left',
549 verticalAlignment: 'center',
550 });
551 }
552
553 this._rowHeaderRenderer = new TextRenderer({
554 textColor: Theme.getFontColor(1),
555 backgroundColor:
556 this.grid.style.headerBackgroundColor || Theme.getBackgroundColor(2),
557 horizontalAlignment: 'center',
558 verticalAlignment: 'center',
559 });
560
561 this._columnHeaderRenderer = new HeaderRenderer({
562 textOptions: {
563 textColor: Theme.getFontColor(1),
564 backgroundColor:
565 this.grid.style.headerBackgroundColor || Theme.getBackgroundColor(2),
566 horizontalAlignment: 'left',
567 verticalAlignment: 'center',
568 },
569 isLightTheme: this._isLightTheme,
570 grid: this.grid,
571 });
572
573 this._cornerHeaderRenderer = new HeaderRenderer({
574 textOptions: {
575 textColor: Theme.getFontColor(1),
576 backgroundColor:
577 this.grid.style.headerBackgroundColor || Theme.getBackgroundColor(2),
578 horizontalAlignment: 'left',
579 verticalAlignment: 'center',
580 },
581 isLightTheme: this._isLightTheme,
582 grid: this.grid,
583 });
584
585 this._updateHeaderRenderer();
586 }
587
588 downloadAsCsv(isSelection: boolean): void {
589 let rowCount, colCount;
590 let r1 = 0,
591 c1 = 0,
592 r2,
593 c2;
594
595 const grid = this.grid;
596 // Fetch the data model.
597 const dataModel = grid.dataModel;
598
599 // Bail early if there is no data model.
600 if (!dataModel) {
601 return;
602 }
603
604 // Fetch the model counts.
605 const br = dataModel.rowCount('body');
606 const bc = dataModel.columnCount('body');
607
608 // Bail early if there is nothing to save.
609 if (br === 0 || bc === 0) {
610 return;
611 }
612
613 // Fetch the header counts.
614 let rhc = dataModel.columnCount('row-header');
615 let chr = dataModel.rowCount('column-header');
616
617 // Unpack the copy config.
618 const format = grid.copyConfig.format;
619 const headers = grid.copyConfig.headers;
620
621 if (isSelection) {
622 // Fetch the selection model.
623 const selectionModel = grid.selectionModel;
624
625 // Bail early if there is no selection model.
626 if (!selectionModel) {
627 return;
628 }
629
630 // Coerce the selections to an array.
631 const selections = Array.from(selectionModel.selections());
632
633 // Bail early if there are no selections.
634 if (selections.length === 0) {
635 return;
636 }
637
638 // Alert that multiple selections cannot be saved.
639 if (selections.length > 1) {
640 alert('Cannot save multiple grid selections.');
641 return;
642 }
643
644 // Unpack the selection.
645 ({ r1, c1, r2, c2 } = selections[0]);
646
647 // Clamp the selection to the model bounds.
648 r1 = Math.max(0, Math.min(r1, br - 1));
649 c1 = Math.max(0, Math.min(c1, bc - 1));
650 r2 = Math.max(0, Math.min(r2, br - 1));
651 c2 = Math.max(0, Math.min(c2, bc - 1));
652
653 // Ensure the limits are well-orderd.
654 if (r2 < r1) [r1, r2] = [r2, r1];
655 if (c2 < c1) [c1, c2] = [c2, c1];
656
657 // Compute the number of cells to be saved.
658 rowCount = r2 - r1 + 1;
659 colCount = c2 - c1 + 1;
660 switch (headers) {
661 case 'none':
662 rhc = 0;
663 chr = 0;
664 break;
665 case 'row':
666 chr = 0;
667 colCount += rhc;
668 break;
669 case 'column':
670 rhc = 0;
671 rowCount += chr;
672 break;
673 case 'all':
674 rowCount += chr;
675 colCount += rhc;
676 break;
677 default:
678 throw 'unreachable';
679 }
680 } else {
681 // Saving all the cells, headers included
682 rowCount = br + chr;
683 colCount = bc + rhc;
684 }
685
686 // Set up the format args.
687 const args = {
688 region: 'body' as DataModel.CellRegion,
689 row: 0,
690 column: 0,
691 value: null as any,
692 metadata: {} as DataModel.Metadata,
693 };
694
695 // Allocate the array of rows.
696 const rows = new Array<string[]>(rowCount);
697
698 // Iterate over the rows.
699 for (let j = 0; j < rowCount; ++j) {
700 // Allocate the array of cells.
701 const cells = new Array<string>(colCount);
702
703 // Iterate over the columns.
704 for (let i = 0; i < colCount; ++i) {
705 // Set up the format variables.
706 let region: DataModel.CellRegion;
707 let row: number;
708 let column: number;
709
710 // Populate the format variables.
711 if (j < chr && i < rhc) {
712 region = 'corner-header';
713 row = j;
714 column = i;
715 } else if (j < chr) {
716 region = 'column-header';
717 row = j;
718 column = i - rhc + c1;
719 } else if (i < rhc) {
720 region = 'row-header';
721 row = j - chr + r1;
722 column = i;
723 } else {
724 region = 'body';
725 row = j - chr + r1;
726 column = i - rhc + c1;
727 }
728
729 // Populate the format args.
730 args.region = region;
731 args.row = row;
732 args.column = column;
733 args.value = dataModel.data(region, row, column);
734 args.metadata = dataModel.metadata(region, row, column);
735
736 // Format the cell.
737 cells[i] = format(args);
738 }
739
740 // Save the row of cells.
741 rows[j] = cells;
742 }
743
744 // Convert the cells into lines.
745 const lines = rows.map((cells) => cells.join(','));
746
747 // Convert the lines into text.
748 const text = lines.join('\n');
749
750 const blob = new Blob([text], { type: 'text/csv' });
751
752 // Create a link element, simulate a click, and remove link element
753 const a = document.createElement('a');
754 a.download = 'out.csv';
755 a.href = window.URL.createObjectURL(blob);
756 document.body.appendChild(a);
757 a.click();
758 document.body.removeChild(a);
759 }
760
761 /**
762 * A signal emitted when a grid cell is clicked.
763 */
764 get cellClicked(): ISignal<this, FeatherGrid.ICellClickedEvent> {
765 return this._cellClicked;
766 }
767
768 /**
769 * A signal emitted when a grid column is resized.
770 */
771 get columnsResized(): ISignal<this, void> {
772 return this._columnsResized;
773 }
774
775 set isLightTheme(value: boolean) {
776 this._isLightTheme = value;
777
778 let themeIndex = 0;
779 if (value) {
780 this.removeClass('dark');
781 } else {
782 this.addClass('dark');
783 themeIndex = 1;
784 }
785
786 const root = document.documentElement;
787 themeVariables.forEach((options: string[], name: string) => {
788 root.style.setProperty(name, options[themeIndex]);
789 });
790
791 this.updateGridStyle();
792 }
793
794 get isLightTheme(): boolean {
795 return this._isLightTheme;
796 }
797
798 /**
799 *
800 * RendererMap.Resolver function to select a CellRenderer based on the
801 * provided cell metadata.
802 *
803 * @param config - CellConfig for the cell to be rendered.
804 */
805 private _rendererResolver(config: CellRenderer.CellConfig): CellRenderer {
806 const columnName: string = config.metadata['name'];
807 const cellRegion: string = config['region'];
808 return this._renderers.hasOwnProperty(columnName)
809 ? this._renderers[columnName]
810 : cellRegion === 'row-header'
811 ? this._rowHeaderRenderer
812 : this._defaultRenderer;
813 }
814
815 private _updateGridRenderers() {
816 this.grid.cellRenderers.update({ body: this._rendererResolver.bind(this) });
817 this.grid.cellRenderers.update({
818 'row-header': this._rendererResolver.bind(this),
819 });
820 }
821
822 private _updateColumnWidths() {
823 const columnWidths = this._columnWidths;
824 const mouseHandler = this.grid
825 .mouseHandler as FeatherGridMouseHandler | null;
826
827 // Check we have a mouse handler
828 if (mouseHandler && mouseHandler.isResizing) {
829 // Do not want this callback to be executed when user resizes using the mouse
830 return;
831 }
832
833 // Resizing columns from row header region
834 if (this._headerVisibility === 'row' || this._headerVisibility === 'all') {
835 const baseRowHeaderSize = this._baseRowHeaderSize;
836 const rowHeaderColCount = this.grid.columnCount('row-header');
837 for (let i = 0; i < rowHeaderColCount; i++) {
838 const colName = this.dataModel.columnIndexToName(i, 'row-header');
839 const colSize = columnWidths.hasOwnProperty(colName)
840 ? columnWidths[colName]
841 : baseRowHeaderSize;
842
843 this.grid.resizeColumn('row-header', i, colSize);
844 }
845 }
846
847 // Resizing columns from body region
848 const baseColumnSize = this._baseColumnSize;
849 const bodyColCount = this.grid.columnCount('body');
850 for (let i = 0; i < bodyColCount; i++) {
851 const colName = this.dataModel.columnIndexToName(i, 'body');
852 const colSize = columnWidths.hasOwnProperty(colName)
853 ? columnWidths[colName]
854 : baseColumnSize;
855
856 this.grid.resizeColumn('body', i, colSize);
857 }
858 }
859
860 private _updateHeaderRenderer() {
861 this.grid.cellRenderers.update({
862 'column-header': this._columnHeaderRenderer,
863 });
864 // Treating corner-header as column-header if a value has not
865 // been passed for the former.
866 let hasCornerRenderer = false;
867 if (this.backboneModel) {
868 hasCornerRenderer = this.backboneModel.get('corner_renderer') !== null;
869 }
870
871 this.grid.cellRenderers.update({
872 'corner-header': hasCornerRenderer
873 ? this._cornerHeaderRenderer
874 : this._columnHeaderRenderer,
875 });
876 }
877
878 private _createCommandRegistry(): CommandRegistry {
879 const commands = new CommandRegistry();
880 commands.addCommand(FeatherGridContextMenu.CommandID.SortAscending, {
881 label: 'Sort Ascending',
882 mnemonic: 1,
883 iconClass:
884 'ipydatagrid-filterMenuIcon ipydatagrid-filterMenuIcon-sortAsc',
885 execute: (args): void => {
886 const command: FeatherGridContextMenu.CommandArgs =
887 args as FeatherGridContextMenu.CommandArgs;
888
889 const colIndex = this._dataModel.getSchemaIndex(
890 command.region,
891 command.columnIndex,
892 );
893
894 const column = this.dataModel.currentView.dataset.columns[colIndex];
895
896 this._dataModel.addTransform({
897 type: 'sort',
898 column,
899 columnIndex: colIndex,
900 desc: false,
901 });
902 },
903 });
904 commands.addCommand(FeatherGridContextMenu.CommandID.SortDescending, {
905 label: 'Sort Descending',
906 mnemonic: 1,
907 iconClass:
908 'ipydatagrid-filterMenuIcon ipydatagrid-filterMenuIcon-sortDesc',
909 execute: (args) => {
910 const command: FeatherGridContextMenu.CommandArgs =
911 args as FeatherGridContextMenu.CommandArgs;
912
913 const colIndex = this._dataModel.getSchemaIndex(
914 command.region,
915 command.columnIndex,
916 );
917
918 const column = this.dataModel.currentView.dataset.columns[colIndex];
919
920 this._dataModel.addTransform({
921 type: 'sort',
922 column,
923 columnIndex: colIndex,
924 desc: true,
925 });
926 },
927 });
928 commands.addCommand(FeatherGridContextMenu.CommandID.ClearThisFilter, {
929 label: 'Clear This Filter',
930 mnemonic: -1,
931 execute: (args) => {
932 const command = <FeatherGridContextMenu.CommandArgs>args;
933
934 const colIndex = this._dataModel.getSchemaIndex(
935 command.region,
936 command.columnIndex,
937 );
938
939 const column = this.dataModel.currentView.dataset.columns[colIndex];
940
941 this._dataModel.removeTransform(column, 'filter');
942 },
943 });
944 commands.addCommand(
945 FeatherGridContextMenu.CommandID.ClearFiltersInAllColumns,
946 {
947 label: 'Clear Filters in All Columns',
948 mnemonic: -1,
949 execute: (args) => {
950 const activeTransforms: Transform.TransformSpec[] =
951 this._dataModel.activeTransforms;
952 const newTransforms = activeTransforms.filter(
953 (val) => val.type !== 'filter',
954 );
955 this._dataModel.replaceTransforms(newTransforms);
956 },
957 },
958 );
959 commands.addCommand(
960 FeatherGridContextMenu.CommandID.OpenFilterByConditionDialog,
961 {
962 label: 'Filter by condition...',
963 mnemonic: 4,
964 iconClass:
965 'ipydatagrid-filterMenuIcon ipydatagrid-filterMenuIcon-filter',
966 execute: (args) => {
967 const commandArgs = <FeatherGridContextMenu.CommandArgs>args;
968
969 const colIndex = this._dataModel.getSchemaIndex(
970 commandArgs.region,
971 commandArgs.columnIndex,
972 );
973
974 const column = this.dataModel.currentView.dataset.columns[colIndex];
975
976 this._filterDialog.open({
977 x: commandArgs.clientX,
978 y: commandArgs.clientY,
979 region: commandArgs.region,
980 column,
981 columnIndex: commandArgs.columnIndex,
982 forceX: false,
983 forceY: false,
984 mode: 'condition',
985 });
986 },
987 },
988 );
989 commands.addCommand(
990 FeatherGridContextMenu.CommandID.OpenFilterByValueDialog,
991 {
992 label: 'Filter by value...',
993 mnemonic: 4,
994 iconClass:
995 'ipydatagrid-filterMenuIcon ipydatagrid-filterMenuIcon-filter',
996 execute: (args) => {
997 const commandArgs = <FeatherGridContextMenu.CommandArgs>args;
998
999 const colIndex = this._dataModel.getSchemaIndex(
1000 commandArgs.region,
1001 commandArgs.columnIndex,
1002 );
1003
1004 const column = this.dataModel.currentView.dataset.columns[colIndex];
1005
1006 this._filterDialog.open({
1007 x: commandArgs.clientX,
1008 y: commandArgs.clientY,
1009 region: commandArgs.region,
1010 column,
1011 columnIndex: commandArgs.columnIndex,
1012 forceX: false,
1013 forceY: false,
1014 mode: 'value',
1015 });
1016 },
1017 },
1018 );
1019 commands.addCommand(
1020 FeatherGridContextMenu.CommandID.CopySelectionToClipboard,
1021 {
1022 label: 'Copy Selection to Clipboard',
1023 mnemonic: -1,
1024 isEnabled: () => {
1025 return (
1026 this.grid.selectionModel !== null &&
1027 !this.grid.selectionModel.isEmpty
1028 );
1029 },
1030 execute: () => {
1031 this.grid.copyToClipboard();
1032 },
1033 },
1034 );
1035 commands.addCommand(FeatherGridContextMenu.CommandID.SaveSelectionAsCsv, {
1036 label: 'Download Selection as CSV',
1037 mnemonic: -1,
1038 isEnabled: () => {
1039 return (
1040 this.grid.selectionModel !== null && !this.grid.selectionModel.isEmpty
1041 );
1042 },
1043 execute: () => {
1044 this.downloadAsCsv(true);
1045 },
1046 });
1047 commands.addCommand(FeatherGridContextMenu.CommandID.SaveAllAsCsv, {
1048 label: 'Download All as CSV',
1049 mnemonic: -1,
1050 execute: () => {
1051 this.downloadAsCsv(false);
1052 },
1053 });
1054 commands.addCommand(FeatherGridContextMenu.CommandID.SortClear, {
1055 label: 'No Sort',
1056 mnemonic: 1,
1057 execute: (args) => {
1058 const commandArgs = <FeatherGridContextMenu.CommandArgs>args;
1059
1060 const colIndex = this._dataModel.getSchemaIndex(
1061 commandArgs.region,
1062 commandArgs.columnIndex,
1063 );
1064
1065 const column = this.dataModel.currentView.dataset.columns[colIndex];
1066
1067 this._dataModel.removeTransform(column, 'sort');
1068 },
1069 });
1070 commands.addCommand(FeatherGridContextMenu.CommandID.ClearSelection, {
1071 label: 'Clear Selection',
1072 mnemonic: -1,
1073 execute: () => {
1074 this.grid.selectionModel?.clear();
1075 },
1076 });
1077
1078 return commands;
1079 }
1080
1081 grid: DataGrid;
1082 backboneModel: BackBoneModel;
1083 contextMenu: FeatherGridContextMenu;
1084 private _filterDialog: InteractiveFilterDialog;
1085 private _baseRowSize = 20;
1086 private _baseColumnSize = 64;
1087 private _baseRowHeaderSize = 64;
1088 private _baseColumnHeaderSize = 20;
1089 private _columnWidths: Dict<number> = {};
1090 private _headerVisibility: DataGrid.HeaderVisibility = 'all';
1091 private _dataModel: ViewBasedJSONModel;
1092 private _selectionModel: BasicSelectionModel | null;
1093 private _editable: boolean;
1094 private _renderers: Dict<CellRenderer> = {};
1095 private _defaultRenderer: CellRenderer;
1096 private _columnHeaderRenderer: CellRenderer;
1097 private _cornerHeaderRenderer: CellRenderer;
1098 private _rowHeaderRenderer: CellRenderer;
1099 private _defaultRendererSet = false;
1100 private _cellClicked = new Signal<this, FeatherGrid.ICellClickedEvent>(this);
1101 private _columnsResized = new Signal<this, void>(this);
1102 private _isLightTheme = true;
1103 }
1104
1105 /**
1106 * The namespace for the `FeatherGrid` class statics.
1107 */
1108 export namespace FeatherGrid {
1109 export interface ICellClickedEvent {
1110 readonly region: DataModel.CellRegion;
1111 column: string;
1112 columnIndex: number;
1113 row: number;
1114 primaryKeyRow: number;
1115 cellValue: any;
1116 }
1117 }