Debian Codegraph @

js/feathergrid.ts

raw ◀ ▶
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 // @ts-ignore
482 this.grid.style = this.backboneModel.get('grid_style');
483 }
484 // Always apply FeatherGrid Theme
485 // if not rendered in ipydatagrid.
486 else {
487 this.grid.style = {
488 voidColor: Theme.getBackgroundColor(),
489 backgroundColor: Theme.getBackgroundColor(),
490 gridLineColor: Theme.getBorderColor(),
491 headerGridLineColor: Theme.getBorderColor(1),
492 selectionFillColor: Theme.getBrandColor(2, 0.4),
493 selectionBorderColor: Theme.getBrandColor(1),
494 headerSelectionFillColor: Theme.getBackgroundColor(3, 0.4),
495 headerSelectionBorderColor: Theme.getBorderColor(1),
496 cursorFillColor: Theme.getBrandColor(3, 0.4),
497 cursorBorderColor: Theme.getBrandColor(1),
498 scrollShadow,
499 };
500 // Terminate call here if rendering outside ipydatagrid.
501 return;
502 }
503
504 this.grid.style = {
505 voidColor: this.grid.style.voidColor || Theme.getBackgroundColor(),
506 backgroundColor:
507 this.grid.style.backgroundColor || Theme.getBackgroundColor(),
508 rowBackgroundColor: this.grid.style.rowBackgroundColor || undefined,
509 columnBackgroundColor: this.grid.style.columnBackgroundColor || undefined,
510 gridLineColor: this.grid.style.gridLineColor || Theme.getBorderColor(),
511 verticalGridLineColor: this.grid.style.verticalGridLineColor || undefined,
512 horizontalGridLineColor:
513 this.grid.style.horizontalGridLineColor || undefined,
514 headerBackgroundColor: this.grid.style.headerBackgroundColor || undefined,
515 headerGridLineColor:
516 this.grid.style.headerGridLineColor || Theme.getBorderColor(1),
517 headerVerticalGridLineColor:
518 this.grid.style.headerVerticalGridLineColor || undefined,
519 headerHorizontalGridLineColor:
520 this.grid.style.headerHorizontalGridLineColor || undefined,
521 selectionFillColor:
522 this.grid.style.selectionFillColor || Theme.getBrandColor(2, 0.4),
523 selectionBorderColor:
524 this.grid.style.selectionBorderColor || Theme.getBrandColor(1),
525 headerSelectionFillColor:
526 this.grid.style.headerSelectionFillColor ||
527 Theme.getBackgroundColor(3, 0.4),
528 headerSelectionBorderColor:
529 this.grid.style.headerSelectionBorderColor || Theme.getBorderColor(1),
530 cursorFillColor:
531 this.grid.style.cursorFillColor || Theme.getBrandColor(3, 0.4),
532 cursorBorderColor:
533 this.grid.style.cursorBorderColor || Theme.getBrandColor(1),
534 scrollShadow: this.grid.style.scrollShadow || scrollShadow,
535 };
536 }
537
538 public updateGridStyle(): void {
539 this.setGridStyle();
540
541 // If we are not rendering with ipydatagrid,
542 // defaultRenderer needs to be set each time.
543 if (!this._defaultRendererSet || !this.backboneModel) {
544 this.defaultRenderer = new TextRenderer({
545 font: '12px sans-serif',
546 textColor: Theme.getFontColor(),
547 backgroundColor:
548 this.grid.style.backgroundColor || Theme.getBackgroundColor(),
549 horizontalAlignment: 'left',
550 verticalAlignment: 'center',
551 });
552 }
553
554 this._rowHeaderRenderer = new TextRenderer({
555 textColor: Theme.getFontColor(1),
556 backgroundColor:
557 this.grid.style.headerBackgroundColor || Theme.getBackgroundColor(2),
558 horizontalAlignment: 'center',
559 verticalAlignment: 'center',
560 });
561
562 this._columnHeaderRenderer = new HeaderRenderer({
563 textOptions: {
564 textColor: Theme.getFontColor(1),
565 backgroundColor:
566 this.grid.style.headerBackgroundColor || Theme.getBackgroundColor(2),
567 horizontalAlignment: 'left',
568 verticalAlignment: 'center',
569 },
570 isLightTheme: this._isLightTheme,
571 grid: this.grid,
572 });
573
574 this._cornerHeaderRenderer = new HeaderRenderer({
575 textOptions: {
576 textColor: Theme.getFontColor(1),
577 backgroundColor:
578 this.grid.style.headerBackgroundColor || Theme.getBackgroundColor(2),
579 horizontalAlignment: 'left',
580 verticalAlignment: 'center',
581 },
582 isLightTheme: this._isLightTheme,
583 grid: this.grid,
584 });
585
586 this._updateHeaderRenderer();
587 }
588
589 downloadAsCsv(isSelection: boolean): void {
590 let rowCount, colCount;
591 let r1 = 0,
592 c1 = 0,
593 r2,
594 c2;
595
596 const grid = this.grid;
597 // Fetch the data model.
598 const dataModel = grid.dataModel;
599
600 // Bail early if there is no data model.
601 if (!dataModel) {
602 return;
603 }
604
605 // Fetch the model counts.
606 const br = dataModel.rowCount('body');
607 const bc = dataModel.columnCount('body');
608
609 // Bail early if there is nothing to save.
610 if (br === 0 || bc === 0) {
611 return;
612 }
613
614 // Fetch the header counts.
615 let rhc = dataModel.columnCount('row-header');
616 let chr = dataModel.rowCount('column-header');
617
618 // Unpack the copy config.
619 const format = grid.copyConfig.format;
620 const headers = grid.copyConfig.headers;
621
622 if (isSelection) {
623 // Fetch the selection model.
624 const selectionModel = grid.selectionModel;
625
626 // Bail early if there is no selection model.
627 if (!selectionModel) {
628 return;
629 }
630
631 // Coerce the selections to an array.
632 const selections = Array.from(selectionModel.selections());
633
634 // Bail early if there are no selections.
635 if (selections.length === 0) {
636 return;
637 }
638
639 // Alert that multiple selections cannot be saved.
640 if (selections.length > 1) {
641 alert('Cannot save multiple grid selections.');
642 return;
643 }
644
645 // Unpack the selection.
646 ({ r1, c1, r2, c2 } = selections[0]);
647
648 // Clamp the selection to the model bounds.
649 r1 = Math.max(0, Math.min(r1, br - 1));
650 c1 = Math.max(0, Math.min(c1, bc - 1));
651 r2 = Math.max(0, Math.min(r2, br - 1));
652 c2 = Math.max(0, Math.min(c2, bc - 1));
653
654 // Ensure the limits are well-orderd.
655 if (r2 < r1) [r1, r2] = [r2, r1];
656 if (c2 < c1) [c1, c2] = [c2, c1];
657
658 // Compute the number of cells to be saved.
659 rowCount = r2 - r1 + 1;
660 colCount = c2 - c1 + 1;
661 switch (headers) {
662 case 'none':
663 rhc = 0;
664 chr = 0;
665 break;
666 case 'row':
667 chr = 0;
668 colCount += rhc;
669 break;
670 case 'column':
671 rhc = 0;
672 rowCount += chr;
673 break;
674 case 'all':
675 rowCount += chr;
676 colCount += rhc;
677 break;
678 default:
679 throw 'unreachable';
680 }
681 } else {
682 // Saving all the cells, headers included
683 rowCount = br + chr;
684 colCount = bc + rhc;
685 }
686
687 // Set up the format args.
688 const args = {
689 region: 'body' as DataModel.CellRegion,
690 row: 0,
691 column: 0,
692 value: null as any,
693 metadata: {} as DataModel.Metadata,
694 };
695
696 // Allocate the array of rows.
697 const rows = new Array<string[]>(rowCount);
698
699 // Iterate over the rows.
700 for (let j = 0; j < rowCount; ++j) {
701 // Allocate the array of cells.
702 const cells = new Array<string>(colCount);
703
704 // Iterate over the columns.
705 for (let i = 0; i < colCount; ++i) {
706 // Set up the format variables.
707 let region: DataModel.CellRegion;
708 let row: number;
709 let column: number;
710
711 // Populate the format variables.
712 if (j < chr && i < rhc) {
713 region = 'corner-header';
714 row = j;
715 column = i;
716 } else if (j < chr) {
717 region = 'column-header';
718 row = j;
719 column = i - rhc + c1;
720 } else if (i < rhc) {
721 region = 'row-header';
722 row = j - chr + r1;
723 column = i;
724 } else {
725 region = 'body';
726 row = j - chr + r1;
727 column = i - rhc + c1;
728 }
729
730 // Populate the format args.
731 args.region = region;
732 args.row = row;
733 args.column = column;
734 args.value = dataModel.data(region, row, column);
735 args.metadata = dataModel.metadata(region, row, column);
736
737 // Format the cell.
738 cells[i] = format(args);
739 }
740
741 // Save the row of cells.
742 rows[j] = cells;
743 }
744
745 // Convert the cells into lines.
746 const lines = rows.map((cells) => cells.join(','));
747
748 // Convert the lines into text.
749 const text = lines.join('\n');
750
751 const blob = new Blob([text], { type: 'text/csv' });
752
753 // Create a link element, simulate a click, and remove link element
754 const a = document.createElement('a');
755 a.download = 'out.csv';
756 a.href = window.URL.createObjectURL(blob);
757 document.body.appendChild(a);
758 a.click();
759 document.body.removeChild(a);
760 }
761
762 /**
763 * A signal emitted when a grid cell is clicked.
764 */
765 get cellClicked(): ISignal<this, FeatherGrid.ICellClickedEvent> {
766 return this._cellClicked;
767 }
768
769 /**
770 * A signal emitted when a grid column is resized.
771 */
772 get columnsResized(): ISignal<this, void> {
773 return this._columnsResized;
774 }
775
776 set isLightTheme(value: boolean) {
777 this._isLightTheme = value;
778
779 let themeIndex = 0;
780 if (value) {
781 this.removeClass('dark');
782 } else {
783 this.addClass('dark');
784 themeIndex = 1;
785 }
786
787 const root = document.documentElement;
788 themeVariables.forEach((options: string[], name: string) => {
789 root.style.setProperty(name, options[themeIndex]);
790 });
791
792 this.updateGridStyle();
793 }
794
795 get isLightTheme(): boolean {
796 return this._isLightTheme;
797 }
798
799 /**
800 *
801 * RendererMap.Resolver function to select a CellRenderer based on the
802 * provided cell metadata.
803 *
804 * @param config - CellConfig for the cell to be rendered.
805 */
806 private _rendererResolver(config: CellRenderer.CellConfig): CellRenderer {
807 const columnName: string = config.metadata['name'];
808 const cellRegion: string = config['region'];
809 return this._renderers.hasOwnProperty(columnName)
810 ? this._renderers[columnName]
811 : cellRegion === 'row-header'
812 ? this._rowHeaderRenderer
813 : this._defaultRenderer;
814 }
815
816 private _updateGridRenderers() {
817 this.grid.cellRenderers.update({ body: this._rendererResolver.bind(this) });
818 this.grid.cellRenderers.update({
819 'row-header': this._rendererResolver.bind(this),
820 });
821 }
822
823 private _updateColumnWidths() {
824 const columnWidths = this._columnWidths;
825 const mouseHandler = this.grid
826 .mouseHandler as FeatherGridMouseHandler | null;
827
828 // Check we have a mouse handler
829 if (mouseHandler && mouseHandler.isResizing) {
830 // Do not want this callback to be executed when user resizes using the mouse
831 return;
832 }
833
834 // Resizing columns from row header region
835 if (this._headerVisibility === 'row' || this._headerVisibility === 'all') {
836 const baseRowHeaderSize = this._baseRowHeaderSize;
837 const rowHeaderColCount = this.grid.columnCount('row-header');
838 for (let i = 0; i < rowHeaderColCount; i++) {
839 const colName = this.dataModel.columnIndexToName(i, 'row-header');
840 const colSize = columnWidths.hasOwnProperty(colName)
841 ? columnWidths[colName]
842 : baseRowHeaderSize;
843
844 this.grid.resizeColumn('row-header', i, colSize);
845 }
846 }
847
848 // Resizing columns from body region
849 const baseColumnSize = this._baseColumnSize;
850 const bodyColCount = this.grid.columnCount('body');
851 for (let i = 0; i < bodyColCount; i++) {
852 const colName = this.dataModel.columnIndexToName(i, 'body');
853 const colSize = columnWidths.hasOwnProperty(colName)
854 ? columnWidths[colName]
855 : baseColumnSize;
856
857 this.grid.resizeColumn('body', i, colSize);
858 }
859 }
860
861 private _updateHeaderRenderer() {
862 this.grid.cellRenderers.update({
863 'column-header': this._columnHeaderRenderer,
864 });
865 // Treating corner-header as column-header if a value has not
866 // been passed for the former.
867 let hasCornerRenderer = false;
868 if (this.backboneModel) {
•869 // @ts-ignore
870 hasCornerRenderer = this.backboneModel.get('corner_renderer') !== null;
871 }
872
873 this.grid.cellRenderers.update({
874 'corner-header': hasCornerRenderer
875 ? this._cornerHeaderRenderer
876 : this._columnHeaderRenderer,
877 });
878 }
879
880 private _createCommandRegistry(): CommandRegistry {
881 const commands = new CommandRegistry();
882 commands.addCommand(FeatherGridContextMenu.CommandID.SortAscending, {
883 label: 'Sort Ascending',
884 mnemonic: 1,
885 iconClass:
886 'ipydatagrid-filterMenuIcon ipydatagrid-filterMenuIcon-sortAsc',
887 execute: (args): void => {
888 const command: FeatherGridContextMenu.CommandArgs =
889 args as FeatherGridContextMenu.CommandArgs;
890
891 const colIndex = this._dataModel.getSchemaIndex(
892 command.region,
893 command.columnIndex,
894 );
895
896 const column = this.dataModel.currentView.dataset.columns[colIndex];
897
898 this._dataModel.addTransform({
899 type: 'sort',
900 column,
901 columnIndex: colIndex,
902 desc: false,
903 });
904 },
905 });
906 commands.addCommand(FeatherGridContextMenu.CommandID.SortDescending, {
907 label: 'Sort Descending',
908 mnemonic: 1,
909 iconClass:
910 'ipydatagrid-filterMenuIcon ipydatagrid-filterMenuIcon-sortDesc',
911 execute: (args) => {
912 const command: FeatherGridContextMenu.CommandArgs =
913 args as FeatherGridContextMenu.CommandArgs;
914
915 const colIndex = this._dataModel.getSchemaIndex(
916 command.region,
917 command.columnIndex,
918 );
919
920 const column = this.dataModel.currentView.dataset.columns[colIndex];
921
922 this._dataModel.addTransform({
923 type: 'sort',
924 column,
925 columnIndex: colIndex,
926 desc: true,
927 });
928 },
929 });
930 commands.addCommand(FeatherGridContextMenu.CommandID.ClearThisFilter, {
931 label: 'Clear This Filter',
932 mnemonic: -1,
933 execute: (args) => {
934 const command = <FeatherGridContextMenu.CommandArgs>args;
935
936 const colIndex = this._dataModel.getSchemaIndex(
937 command.region,
938 command.columnIndex,
939 );
940
941 const column = this.dataModel.currentView.dataset.columns[colIndex];
942
943 this._dataModel.removeTransform(column, 'filter');
944 },
945 });
946 commands.addCommand(
947 FeatherGridContextMenu.CommandID.ClearFiltersInAllColumns,
948 {
949 label: 'Clear Filters in All Columns',
950 mnemonic: -1,
951 execute: (args) => {
952 const activeTransforms: Transform.TransformSpec[] =
953 this._dataModel.activeTransforms;
954 const newTransforms = activeTransforms.filter(
955 (val) => val.type !== 'filter',
956 );
957 this._dataModel.replaceTransforms(newTransforms);
958 },
959 },
960 );
961 commands.addCommand(
962 FeatherGridContextMenu.CommandID.OpenFilterByConditionDialog,
963 {
964 label: 'Filter by condition...',
965 mnemonic: 4,
966 iconClass:
967 'ipydatagrid-filterMenuIcon ipydatagrid-filterMenuIcon-filter',
968 execute: (args) => {
969 const commandArgs = <FeatherGridContextMenu.CommandArgs>args;
970
971 const colIndex = this._dataModel.getSchemaIndex(
972 commandArgs.region,
973 commandArgs.columnIndex,
974 );
975
976 const column = this.dataModel.currentView.dataset.columns[colIndex];
977
978 this._filterDialog.open({
979 x: commandArgs.clientX,
980 y: commandArgs.clientY,
981 region: commandArgs.region,
982 column,
983 columnIndex: commandArgs.columnIndex,
984 forceX: false,
985 forceY: false,
986 mode: 'condition',
987 });
988 },
989 },
990 );
991 commands.addCommand(
992 FeatherGridContextMenu.CommandID.OpenFilterByValueDialog,
993 {
994 label: 'Filter by value...',
995 mnemonic: 4,
996 iconClass:
997 'ipydatagrid-filterMenuIcon ipydatagrid-filterMenuIcon-filter',
998 execute: (args) => {
999 const commandArgs = <FeatherGridContextMenu.CommandArgs>args;
1000
1001 const colIndex = this._dataModel.getSchemaIndex(
1002 commandArgs.region,
1003 commandArgs.columnIndex,
1004 );
1005
1006 const column = this.dataModel.currentView.dataset.columns[colIndex];
1007
1008 this._filterDialog.open({
1009 x: commandArgs.clientX,
1010 y: commandArgs.clientY,
1011 region: commandArgs.region,
1012 column,
1013 columnIndex: commandArgs.columnIndex,
1014 forceX: false,
1015 forceY: false,
1016 mode: 'value',
1017 });
1018 },
1019 },
1020 );
1021 commands.addCommand(
1022 FeatherGridContextMenu.CommandID.CopySelectionToClipboard,
1023 {
1024 label: 'Copy Selection to Clipboard',
1025 mnemonic: -1,
1026 isEnabled: () => {
1027 return (
1028 this.grid.selectionModel !== null &&
1029 !this.grid.selectionModel.isEmpty
1030 );
1031 },
1032 execute: () => {
1033 this.grid.copyToClipboard();
1034 },
1035 },
1036 );
1037 commands.addCommand(FeatherGridContextMenu.CommandID.SaveSelectionAsCsv, {
1038 label: 'Download Selection as CSV',
1039 mnemonic: -1,
1040 isEnabled: () => {
1041 return (
1042 this.grid.selectionModel !== null && !this.grid.selectionModel.isEmpty
1043 );
1044 },
1045 execute: () => {
1046 this.downloadAsCsv(true);
1047 },
1048 });
1049 commands.addCommand(FeatherGridContextMenu.CommandID.SaveAllAsCsv, {
1050 label: 'Download All as CSV',
1051 mnemonic: -1,
1052 execute: () => {
1053 this.downloadAsCsv(false);
1054 },
1055 });
1056 commands.addCommand(FeatherGridContextMenu.CommandID.SortClear, {
1057 label: 'No Sort',
1058 mnemonic: 1,
1059 execute: (args) => {
1060 const commandArgs = <FeatherGridContextMenu.CommandArgs>args;
1061
1062 const colIndex = this._dataModel.getSchemaIndex(
1063 commandArgs.region,
1064 commandArgs.columnIndex,
1065 );
1066
1067 const column = this.dataModel.currentView.dataset.columns[colIndex];
1068
1069 this._dataModel.removeTransform(column, 'sort');
1070 },
1071 });
1072 commands.addCommand(FeatherGridContextMenu.CommandID.ClearSelection, {
1073 label: 'Clear Selection',
1074 mnemonic: -1,
1075 execute: () => {
1076 this.grid.selectionModel?.clear();
1077 },
1078 });
1079
1080 return commands;
1081 }
1082
1083 grid: DataGrid;
1084 backboneModel: BackBoneModel;
1085 contextMenu: FeatherGridContextMenu;
1086 private _filterDialog: InteractiveFilterDialog;
1087 private _baseRowSize = 20;
1088 private _baseColumnSize = 64;
1089 private _baseRowHeaderSize = 64;
1090 private _baseColumnHeaderSize = 20;
1091 private _columnWidths: Dict<number> = {};
1092 private _headerVisibility: DataGrid.HeaderVisibility = 'all';
1093 private _dataModel: ViewBasedJSONModel;
1094 private _selectionModel: BasicSelectionModel | null;
1095 private _editable: boolean;
1096 private _renderers: Dict<CellRenderer> = {};
1097 private _defaultRenderer: CellRenderer;
1098 private _columnHeaderRenderer: CellRenderer;
1099 private _cornerHeaderRenderer: CellRenderer;
1100 private _rowHeaderRenderer: CellRenderer;
1101 private _defaultRendererSet = false;
1102 private _cellClicked = new Signal<this, FeatherGrid.ICellClickedEvent>(this);
1103 private _columnsResized = new Signal<this, void>(this);
1104 private _isLightTheme = true;
1105 }
1106
1107 /**
1108 * The namespace for the `FeatherGrid` class statics.
1109 */
1110 export namespace FeatherGrid {
1111 export interface ICellClickedEvent {
1112 readonly region: DataModel.CellRegion;
1113 column: string;
1114 columnIndex: number;
1115 row: number;
1116 primaryKeyRow: number;
1117 cellValue: any;
1118 }
1119 }