Debian Codegraph @

packages/datagrid/src/celleditor.ts

raw
1 /*
2 * Copyright (c) Jupyter Development Team.
3 * Distributed under the terms of the Modified BSD License.
4 */
5
6 /*-----------------------------------------------------------------------------
7 | Copyright (c) 2014-2019, PhosphorJS Contributors
8 |
9 | Distributed under the terms of the BSD 3-Clause License.
10 |
11 | The full license is in the file LICENSE, distributed with this software.
12 |----------------------------------------------------------------------------*/
13 import { IDisposable } from '@lumino/disposable';
14
15 import { Message } from '@lumino/messaging';
16
17 import { Widget } from '@lumino/widgets';
18
19 import { DataGrid } from './datagrid';
20
21 import { SelectionModel } from './selectionmodel';
22
23 import { getKeyboardLayout } from '@lumino/keyboard';
24
25 import { Signal } from '@lumino/signaling';
26
27 import { CellGroup } from './cellgroup';
28
29 /**
30 * A response object returned from cell input validator
31 */
32 export interface ICellInputValidatorResponse {
33 /**
34 * Flag indicating cell input is valid or not
35 */
36 valid: boolean;
37 /**
38 * Validation error message. Set only when input is invalid
39 */
40 message?: string;
41 }
42
43 /**
44 * An object which validates cell input values.
45 */
46 export interface ICellInputValidator {
47 /**
48 * Validate cell input.
49 *
50 * @param cell - The object holding cell configuration data.
51 *
52 * @param value - The cell value input.
53 *
54 * @returns An object with validation result.
55 */
56 validate(
57 cell: CellEditor.CellConfig,
58 value: any
59 ): ICellInputValidatorResponse;
60 }
61
62 /**
63 * An object returned from cell editor after a successful edit.
64 */
65 export interface ICellEditResponse {
66 /**
67 * An object which holds the configuration data for a cell.
68 */
69 cell: CellEditor.CellConfig;
70 /**
71 * Value input.
72 */
73 value: any;
74 /**
75 * Cursor move direction based on keys pressed to end the edit.
76 */
77 cursorMovement: SelectionModel.CursorMoveDirection;
78 }
79
80 /**
81 * An object implementing cell editing.
82 */
83 export interface ICellEditor {
84 /**
85 * Start editing the cell.
86 *
87 * @param cell - The object holding cell configuration data.
88 *
89 * @param options - The cell editing options.
90 */
91 edit(cell: CellEditor.CellConfig, options?: ICellEditOptions): void;
92 /**
93 * Cancel editing the cell.
94 */
95 cancel(): void;
96 }
97
98 // default validation error message
99 const DEFAULT_INVALID_INPUT_MESSAGE = 'Invalid input!';
100
101 // A type alias for available cell data types
102 export type CellDataType =
103 | 'string'
104 | 'number'
105 | 'integer'
106 | 'boolean'
107 | 'date'
108 | 'string:option'
109 | 'number:option'
110 | 'integer:option'
111 | 'date:option'
112 | 'string:dynamic-option'
113 | 'number:dynamic-option'
114 | 'integer:dynamic-option'
115 | 'date:dynamic-option';
116
117 /**
118 * An object containing cell editing options.
119 */
120 export interface ICellEditOptions {
121 /**
122 * Cell editor to use for editing.
123 *
124 * #### Notes
125 * This object is only used by cell editor controller.
126 * If not set, controller picks the most suitable editor
127 * for the particular cell configuration.
128 */
129 editor?: ICellEditor;
130 /**
131 * Cell input validator to use for value validation.
132 */
133 validator?: ICellInputValidator;
134 /**
135 * Callback method to call on cell edit commit.
136 */
137 onCommit?: (response: ICellEditResponse) => void;
138 /**
139 * Callback method to call on cell edit cancel.
140 */
141 onCancel?: () => void;
142 }
143
144 /**
145 * A cell input validator object which always returns valid.
146 */
147 export class PassInputValidator implements ICellInputValidator {
148 /**
149 * Validate cell input.
150 *
151 * @param cell - The object holding cell configuration data.
152 *
153 * @param value - The cell value input.
154 *
155 * @returns An object with validation result.
156 */
157 validate(
158 cell: CellEditor.CellConfig,
159 value: unknown
160 ): ICellInputValidatorResponse {
161 return { valid: true };
162 }
163 }
164
165 /**
166 * Text cell input validator.
167 */
168 export class TextInputValidator implements ICellInputValidator {
169 /**
170 * Validate cell input.
171 *
172 * @param cell - The object holding cell configuration data.
173 *
174 * @param value - The cell value input.
175 *
176 * @returns An object with validation result.
177 */
178 validate(
179 cell: CellEditor.CellConfig,
180 value: string
181 ): ICellInputValidatorResponse {
182 if (value === null) {
183 return { valid: true };
184 }
185
186 if (typeof value !== 'string') {
187 return {
188 valid: false,
189 message: 'Input must be valid text'
190 };
191 }
192
193 if (!isNaN(this.minLength) && value.length < this.minLength) {
194 return {
195 valid: false,
196 message: `Text length must be greater than ${this.minLength}`
197 };
198 }
199
200 if (!isNaN(this.maxLength) && value.length > this.maxLength) {
201 return {
202 valid: false,
203 message: `Text length must be less than ${this.maxLength}`
204 };
205 }
206
207 if (this.pattern && !this.pattern.test(value)) {
208 return {
209 valid: false,
210 message: `Text doesn't match the required pattern`
211 };
212 }
213
214 return { valid: true };
215 }
216
217 /**
218 * Minimum text length
219 *
220 * The default is Number.NaN, meaning no minimum constraint
221 */
222 minLength: number = Number.NaN;
223 /**
224 * Maximum text length
225 *
226 * The default is Number.NaN, meaning no maximum constraint
227 */
228 maxLength: number = Number.NaN;
229 /**
230 * Required text pattern as regular expression
231 *
232 * The default is null, meaning no pattern constraint
233 */
234 pattern: RegExp | null = null;
235 }
236
237 /**
238 * Integer cell input validator.
239 */
240 export class IntegerInputValidator implements ICellInputValidator {
241 /**
242 * Validate cell input.
243 *
244 * @param cell - The object holding cell configuration data.
245 *
246 * @param value - The cell value input.
247 *
248 * @returns An object with validation result.
249 */
250 validate(
251 cell: CellEditor.CellConfig,
252 value: number
253 ): ICellInputValidatorResponse {
254 if (value === null) {
255 return { valid: true };
256 }
257
258 if (isNaN(value) || value % 1 !== 0) {
259 return {
260 valid: false,
261 message: 'Input must be valid integer'
262 };
263 }
264
265 if (!isNaN(this.min) && value < this.min) {
266 return {
267 valid: false,
268 message: `Input must be greater than ${this.min}`
269 };
270 }
271
272 if (!isNaN(this.max) && value > this.max) {
273 return {
274 valid: false,
275 message: `Input must be less than ${this.max}`
276 };
277 }
278
279 return { valid: true };
280 }
281
282 /**
283 * Minimum value
284 *
285 * The default is Number.NaN, meaning no minimum constraint
286 */
287 min: number = Number.NaN;
288 /**
289 * Maximum value
290 *
291 * The default is Number.NaN, meaning no maximum constraint
292 */
293 max: number = Number.NaN;
294 }
295
296 /**
297 * Real number cell input validator.
298 */
299 export class NumberInputValidator implements ICellInputValidator {
300 /**
301 * Validate cell input.
302 *
303 * @param cell - The object holding cell configuration data.
304 *
305 * @param value - The cell value input.
306 *
307 * @returns An object with validation result.
308 */
309 validate(
310 cell: CellEditor.CellConfig,
311 value: number
312 ): ICellInputValidatorResponse {
313 if (value === null) {
314 return { valid: true };
315 }
316
317 if (isNaN(value)) {
318 return {
319 valid: false,
320 message: 'Input must be valid number'
321 };
322 }
323
324 if (!isNaN(this.min) && value < this.min) {
325 return {
326 valid: false,
327 message: `Input must be greater than ${this.min}`
328 };
329 }
330
331 if (!isNaN(this.max) && value > this.max) {
332 return {
333 valid: false,
334 message: `Input must be less than ${this.max}`
335 };
336 }
337
338 return { valid: true };
339 }
340
341 /**
342 * Minimum value
343 *
344 * The default is Number.NaN, meaning no minimum constraint
345 */
346 min: number = Number.NaN;
347 /**
348 * Maximum value
349 *
350 * The default is Number.NaN, meaning no maximum constraint
351 */
352 max: number = Number.NaN;
353 }
354
355 /**
356 * An abstract base class that provides the most of the functionality
357 * needed by a cell editor. All of the built-in cell editors
358 * for various cell types are derived from this base class. Custom cell editors
359 * can be easily implemented by extending this class.
360 */
361 export abstract class CellEditor implements ICellEditor, IDisposable {
362 /**
363 * Construct a new cell editor.
364 */
365 constructor() {
366 this.inputChanged.connect(() => {
367 this.validate();
368 });
369 }
370
371 /**
372 * Whether the cell editor is disposed.
373 */
374 get isDisposed(): boolean {
375 return this._disposed;
376 }
377
378 /**
379 * Dispose of the resources held by cell editor.
380 */
381 dispose(): void {
382 if (this._disposed) {
383 return;
384 }
385
386 if (this._gridWheelEventHandler) {
387 this.cell.grid.node.removeEventListener(
388 'wheel',
389 this._gridWheelEventHandler
390 );
391 this._gridWheelEventHandler = null;
392 }
393
394 this._closeValidityNotification();
395
396 this._disposed = true;
397 this.cell.grid.node.removeChild(this.viewportOccluder);
398 }
399
400 /**
401 * Start editing the cell.
402 *
403 * @param cell - The object holding cell configuration data.
404 *
405 * @param options - The cell editing options.
406 */
407 edit(cell: CellEditor.CellConfig, options?: ICellEditOptions): void {
408 this.cell = cell;
409 this.onCommit = options && options.onCommit;
410 this.onCancel = options && options.onCancel;
411
412 this.validator =
413 options && options.validator
414 ? options.validator
415 : this.createValidatorBasedOnType();
416
417 this._gridWheelEventHandler = () => {
418 this._closeValidityNotification();
419 this.updatePosition();
420 };
421
422 cell.grid.node.addEventListener('wheel', this._gridWheelEventHandler);
423
424 this._addContainer();
425
426 this.updatePosition();
427 this.startEditing();
428 }
429
430 /**
431 * Cancel editing the cell.
432 */
433 cancel(): void {
434 if (this._disposed) {
435 return;
436 }
437
438 this.dispose();
439 if (this.onCancel) {
440 this.onCancel();
441 }
442 }
443
444 /**
445 * Start editing the cell. Usually an editor widget is created and
446 * added to `editorContainer`
447 */
448 protected abstract startEditing(): void;
449 /**
450 * Return the current input entered. This method throws exceptions
451 * if input is invalid. Error message in exception is shown as notification.
452 */
453 protected abstract getInput(): any;
454
455 /**
456 * Whether the value input is valid.
457 */
458 protected get validInput(): boolean {
459 return this._validInput;
460 }
461
462 /**
463 * Validate the cell input. Shows validation error notification when input is invalid.
464 */
465 protected validate(): void {
466 let value;
467 try {
468 value = this.getInput();
469 } catch (error) {
470 console.log(`Input error: ${error.message}`);
471 this.setValidity(false, error.message || DEFAULT_INVALID_INPUT_MESSAGE);
472 return;
473 }
474
475 if (this.validator) {
476 const result = this.validator.validate(this.cell, value);
477 if (result.valid) {
478 this.setValidity(true);
479 } else {
480 this.setValidity(
481 false,
482 result.message || DEFAULT_INVALID_INPUT_MESSAGE
483 );
484 }
485 } else {
486 this.setValidity(true);
487 }
488 }
489
490 /**
491 * Set validity flag.
492 *
493 * @param valid - Whether the input is valid.
494 *
495 * @param message - Notification message to show.
496 *
497 * If message is set to empty string (which is the default)
498 * existing notification popup is removed if any.
499 */
500 protected setValidity(valid: boolean, message: string = ''): void {
501 this._validInput = valid;
502
503 this._closeValidityNotification();
504
505 if (valid) {
506 this.editorContainer.classList.remove('lm-mod-invalid');
507 } else {
508 this.editorContainer.classList.add('lm-mod-invalid');
509
510 // show a notification popup
511 if (message !== '') {
512 this.validityNotification = new CellEditor.Notification({
513 target: this.editorContainer,
514 message: message,
515 placement: 'bottom',
516 timeout: 5000
517 });
518 this.validityNotification.show();
519 }
520 }
521 }
522
523 /**
524 * Create and return a cell input validator based on configuration of the
525 * cell being edited. If no suitable validator can be found, it returns undefined.
526 */
527 protected createValidatorBasedOnType(): ICellInputValidator | undefined {
528 const cell = this.cell;
529 const metadata = cell.grid.dataModel!.metadata(
530 'body',
531 cell.row,
532 cell.column
533 );
534
535 switch (metadata && metadata.type) {
536 case 'string':
537 {
538 const validator = new TextInputValidator();
539 if (typeof metadata!.format === 'string') {
540 const format = metadata!.format;
541 switch (format) {
542 case 'email':
543 validator.pattern = new RegExp(
544 '^([a-z0-9_.-]+)@([da-z.-]+).([a-z.]{2,6})$'
545 );
546 break;
547 case 'uuid':
548 validator.pattern = new RegExp(
549 '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}'
550 );
551 break;
552 case 'uri':
553 // TODO
554 break;
555 case 'binary':
556 // TODO
557 break;
558 }
559 }
560
561 if (metadata!.constraint) {
562 if (metadata!.constraint.minLength !== undefined) {
563 validator.minLength = metadata!.constraint.minLength;
564 }
565 if (metadata!.constraint.maxLength !== undefined) {
566 validator.maxLength = metadata!.constraint.maxLength;
567 }
568 if (typeof metadata!.constraint.pattern === 'string') {
569 validator.pattern = new RegExp(metadata!.constraint.pattern);
570 }
571 }
572 return validator;
573 }
574 break;
575 case 'number':
576 {
577 const validator = new NumberInputValidator();
578 if (metadata!.constraint) {
579 if (metadata!.constraint.minimum !== undefined) {
580 validator.min = metadata!.constraint.minimum;
581 }
582 if (metadata!.constraint.maximum !== undefined) {
583 validator.max = metadata!.constraint.maximum;
584 }
585 }
586 return validator;
587 }
588 break;
589 case 'integer':
590 {
591 const validator = new IntegerInputValidator();
592 if (metadata!.constraint) {
593 if (metadata!.constraint.minimum !== undefined) {
594 validator.min = metadata!.constraint.minimum;
595 }
596 if (metadata!.constraint.maximum !== undefined) {
597 validator.max = metadata!.constraint.maximum;
598 }
599 }
600 return validator;
601 }
602 break;
603 }
604
605 return undefined;
606 }
607
608 /**
609 * Compute cell rectangle and return with other cell properties.
610 */
611 protected getCellInfo(cell: CellEditor.CellConfig): Private.ICellInfo {
612 const { grid, row, column } = cell;
613 let data, columnX, rowY, width, height;
614 const cellGroup = CellGroup.getGroup(grid.dataModel!, 'body', row, column);
615
616 if (cellGroup) {
617 columnX =
618 grid.headerWidth -
619 grid.scrollX +
620 grid.columnOffset('body', cellGroup.c1);
621 rowY =
622 grid.headerHeight - grid.scrollY + grid.rowOffset('body', cellGroup.r1);
623 width = 0;
624 height = 0;
625
626 for (let r = cellGroup.r1; r <= cellGroup.r2; r++) {
627 height += grid.rowSize('body', r);
628 }
629
630 for (let c = cellGroup.c1; c <= cellGroup.c2; c++) {
631 width += grid.columnSize('body', c);
632 }
633
634 data = grid.dataModel!.data('body', cellGroup.r1, cellGroup.c1);
635 } else {
636 columnX =
637 grid.headerWidth - grid.scrollX + grid.columnOffset('body', column);
638 rowY = grid.headerHeight - grid.scrollY + grid.rowOffset('body', row);
639 width = grid.columnSize('body', column);
640 height = grid.rowSize('body', row);
641 data = grid.dataModel!.data('body', row, column);
642 }
643
644 return {
645 grid: grid,
646 row: row,
647 column: column,
648 data: data,
649 x: columnX,
650 y: rowY,
651 width: width,
652 height: height
653 };
654 }
655
656 /**
657 * Reposition cell editor by moving viewport occluder and cell editor container.
658 */
659 protected updatePosition(): void {
660 const grid = this.cell.grid;
661 const cellInfo = this.getCellInfo(this.cell);
662 const headerHeight = grid.headerHeight;
663 const headerWidth = grid.headerWidth;
664
665 this.viewportOccluder.style.top = headerHeight + 'px';
666 this.viewportOccluder.style.left = headerWidth + 'px';
667 this.viewportOccluder.style.width = grid.viewportWidth - headerWidth + 'px';
668 this.viewportOccluder.style.height =
669 grid.viewportHeight - headerHeight + 'px';
670 this.viewportOccluder.style.position = 'absolute';
671
672 this.editorContainer.style.left = cellInfo.x - 1 - headerWidth + 'px';
673 this.editorContainer.style.top = cellInfo.y - 1 - headerHeight + 'px';
674 this.editorContainer.style.width = cellInfo.width + 1 + 'px';
675 this.editorContainer.style.height = cellInfo.height + 1 + 'px';
676 this.editorContainer.style.visibility = 'visible';
677 this.editorContainer.style.position = 'absolute';
678 }
679
680 /**
681 * Commit the edited value.
682 *
683 * @param cursorMovement - Cursor move direction based on keys pressed to end the edit.
684 *
685 * @returns true on valid input, false otherwise.
686 */
687 protected commit(
688 cursorMovement: SelectionModel.CursorMoveDirection = 'none'
689 ): boolean {
690 this.validate();
691
692 if (!this._validInput) {
693 return false;
694 }
695
696 let value;
697 try {
698 value = this.getInput();
699 } catch (error) {
700 console.log(`Input error: ${error.message}`);
701 return false;
702 }
703
704 this.dispose();
705
706 if (this.onCommit) {
707 this.onCommit({
708 cell: this.cell,
709 value: value,
710 cursorMovement: cursorMovement
711 });
712 }
713
714 return true;
715 }
716
717 /**
718 * Create container elements needed to prevent editor widget overflow
719 * beyond viewport and to position cell editor widget.
720 */
721 private _addContainer() {
722 this.viewportOccluder = document.createElement('div');
723 this.viewportOccluder.className = 'lm-DataGrid-cellEditorOccluder';
724 this.cell.grid.node.appendChild(this.viewportOccluder);
725
726 this.editorContainer = document.createElement('div');
727 this.editorContainer.className = 'lm-DataGrid-cellEditorContainer';
728 this.viewportOccluder.appendChild(this.editorContainer);
729
730 // update mouse event pass-through state based on input validity
731 this.editorContainer.addEventListener('mouseleave', (event: MouseEvent) => {
732 this.viewportOccluder.style.pointerEvents = this._validInput
733 ? 'none'
734 : 'auto';
735 });
736 this.editorContainer.addEventListener('mouseenter', (event: MouseEvent) => {
737 this.viewportOccluder.style.pointerEvents = 'none';
738 });
739 }
740
741 /**
742 * Remove validity notification popup.
743 */
744 private _closeValidityNotification() {
745 if (this.validityNotification) {
746 this.validityNotification.close();
747 this.validityNotification = null;
748 }
749 }
750
751 /**
752 * A signal emitted when input changes.
753 */
754 protected inputChanged = new Signal<this, void>(this);
755 /**
756 * Callback method to call on cell edit commit.
757 */
758 protected onCommit?: (response: ICellEditResponse) => void;
759 /**
760 * Callback method to call on cell edit cancel.
761 */
762 protected onCancel?: () => void;
763 /**
764 * Cell configuration data for the cell being edited.
765 */
766 protected cell: CellEditor.CellConfig;
767 /**
768 * Cell input validator to use for the cell being edited.
769 */
770 protected validator: ICellInputValidator | undefined;
771 /**
772 * The div element used to prevent editor widget overflow beyond grid viewport.
773 */
774 protected viewportOccluder: HTMLDivElement;
775 /**
776 * The div element used to contain and position editor widget.
777 */
778 protected editorContainer: HTMLDivElement;
779 /**
780 * Notification popup used to show validation error messages.
781 */
782 protected validityNotification: CellEditor.Notification | null = null;
783 /**
784 * Whether the cell editor is disposed.
785 */
786 private _disposed = false;
787 /**
788 * Whether the value input is valid.
789 */
790 private _validInput: boolean = true;
791 /**
792 * Grid wheel event handler.
793 */
794 private _gridWheelEventHandler:
795 | ((this: HTMLElement, ev: WheelEvent) => any)
796 | null = null;
797 }
798
799 /**
800 * Abstract base class with shared functionality
801 * for cell editors which use HTML Input widget as editor.
802 */
803 export abstract class InputCellEditor extends CellEditor {
804 /**
805 * Handle the DOM events for the editor.
806 *
807 * @param event - The DOM event sent to the editor.
808 */
809 handleEvent(event: Event): void {
810 switch (event.type) {
811 case 'keydown':
812 this._onKeyDown(event as KeyboardEvent);
813 break;
814 case 'blur':
815 this._onBlur(event as FocusEvent);
816 break;
817 case 'input':
818 this._onInput(event);
819 break;
820 }
821 }
822
823 /**
824 * Dispose of the resources held by cell editor.
825 */
826 dispose(): void {
827 if (this.isDisposed) {
828 return;
829 }
830
831 this._unbindEvents();
832
833 super.dispose();
834 }
835
836 /**
837 * Start editing the cell.
838 */
839 protected startEditing(): void {
840 this.createWidget();
841
842 const cell = this.cell;
843 const cellInfo = this.getCellInfo(cell);
844 this.input.value = this.deserialize(cellInfo.data);
845 this.editorContainer.appendChild(this.input);
846 this.input.focus();
847 this.input.select();
848
849 this.bindEvents();
850 }
851
852 protected deserialize(value: unknown): any {
853 if (value === null || value === undefined) {
854 return '';
855 }
856
857 return (value as any).toString();
858 }
859
860 protected createWidget(): void {
861 const input = document.createElement('input');
862 input.classList.add('lm-DataGrid-cellEditorWidget');
863 input.classList.add('lm-DataGrid-cellEditorInput');
864 input.spellcheck = false;
865 input.type = this.inputType;
866
867 this.input = input;
868 }
869
870 protected bindEvents(): void {
871 this.input.addEventListener('keydown', this);
872 this.input.addEventListener('blur', this);
873 this.input.addEventListener('input', this);
874 }
875
876 private _unbindEvents() {
877 this.input.removeEventListener('keydown', this);
878 this.input.removeEventListener('blur', this);
879 this.input.removeEventListener('input', this);
880 }
881
882 private _onKeyDown(event: KeyboardEvent) {
883 switch (getKeyboardLayout().keyForKeydownEvent(event)) {
884 case 'Enter':
885 this.commit(event.shiftKey ? 'up' : 'down');
886 break;
887 case 'Tab':
888 this.commit(event.shiftKey ? 'left' : 'right');
889 event.stopPropagation();
890 event.preventDefault();
891 break;
892 case 'Escape':
893 this.cancel();
894 break;
895 default:
896 break;
897 }
898 }
899
900 private _onBlur(event: FocusEvent) {
901 if (this.isDisposed) {
902 return;
903 }
904
905 if (!this.commit()) {
906 event.preventDefault();
907 event.stopPropagation();
908 this.input.focus();
909 }
910 }
911
912 private _onInput(event: Event) {
913 this.inputChanged.emit(void 0);
914 }
915
916 protected input: HTMLInputElement;
917 protected abstract inputType: string;
918 }
919
920 /**
921 * Cell editor for text cells.
922 */
923 export class TextCellEditor extends InputCellEditor {
924 /**
925 * Return the current text input entered.
926 */
927 protected getInput(): string | null {
928 return this.input.value;
929 }
930
931 protected inputType: string = 'text';
932 }
933
934 /**
935 * Cell editor for real number cells.
936 */
937 export class NumberCellEditor extends InputCellEditor {
938 /**
939 * Start editing the cell.
940 */
941 protected startEditing(): void {
942 super.startEditing();
943
944 this.input.step = 'any';
945
946 const cell = this.cell;
947
948 const metadata = cell.grid.dataModel!.metadata(
949 'body',
950 cell.row,
951 cell.column
952 );
953 const constraint = metadata.constraint;
954 if (constraint) {
955 if (constraint.minimum) {
956 this.input.min = constraint.minimum;
957 }
958 if (constraint.maximum) {
959 this.input.max = constraint.maximum;
960 }
961 }
962 }
963
964 /**
965 * Return the current number input entered. This method throws exception
966 * if input is invalid.
967 */
968 protected getInput(): number | null {
969 let value = this.input.value;
970 if (value.trim() === '') {
971 return null;
972 }
973
974 const floatValue = parseFloat(value);
975 if (isNaN(floatValue)) {
976 throw new Error('Invalid input');
977 }
978
979 return floatValue;
980 }
981
982 protected inputType: string = 'number';
983 }
984
985 /**
986 * Cell editor for integer cells.
987 */
988 export class IntegerCellEditor extends InputCellEditor {
989 /**
990 * Start editing the cell.
991 */
992 protected startEditing(): void {
993 super.startEditing();
994
995 this.input.step = '1';
996
997 const cell = this.cell;
998
999 const metadata = cell.grid.dataModel!.metadata(
1000 'body',
1001 cell.row,
1002 cell.column
1003 );
1004 const constraint = metadata.constraint;
1005 if (constraint) {
1006 if (constraint.minimum) {
1007 this.input.min = constraint.minimum;
1008 }
1009 if (constraint.maximum) {
1010 this.input.max = constraint.maximum;
1011 }
1012 }
1013 }
1014
1015 /**
1016 * Return the current integer input entered. This method throws exception
1017 * if input is invalid.
1018 */
1019 protected getInput(): number | null {
1020 let value = this.input.value;
1021 if (value.trim() === '') {
1022 return null;
1023 }
1024
1025 let intValue = parseInt(value);
1026 if (isNaN(intValue)) {
1027 throw new Error('Invalid input');
1028 }
1029
1030 return intValue;
1031 }
1032
1033 protected inputType: string = 'number';
1034 }
1035
1036 /**
1037 * Cell editor for date cells.
1038 */
1039 export class DateCellEditor extends CellEditor {
1040 /**
1041 * Handle the DOM events for the editor.
1042 *
1043 * @param event - The DOM event sent to the editor.
1044 */
1045 handleEvent(event: Event): void {
1046 switch (event.type) {
1047 case 'keydown':
1048 this._onKeyDown(event as KeyboardEvent);
1049 break;
1050 case 'blur':
1051 this._onBlur(event as FocusEvent);
1052 break;
1053 }
1054 }
1055
1056 /**
1057 * Dispose of the resources held by cell editor.
1058 */
1059 dispose(): void {
1060 if (this.isDisposed) {
1061 return;
1062 }
1063
1064 this._unbindEvents();
1065
1066 super.dispose();
1067 }
1068
1069 /**
1070 * Start editing the cell.
1071 */
1072 protected startEditing(): void {
1073 this._createWidget();
1074
1075 const cell = this.cell;
1076 const cellInfo = this.getCellInfo(cell);
1077 this._input.value = this._deserialize(cellInfo.data);
1078 this.editorContainer.appendChild(this._input);
1079 this._input.focus();
1080
1081 this._bindEvents();
1082 }
1083
1084 /**
1085 * Return the current date input entered.
1086 */
1087 protected getInput(): string | null {
1088 return this._input.value;
1089 }
1090
1091 private _deserialize(value: any): any {
1092 if (value === null || value === undefined) {
1093 return '';
1094 }
1095
1096 return value.toString();
1097 }
1098
1099 private _createWidget() {
1100 const input = document.createElement('input');
1101 input.type = 'date';
1102 input.pattern = 'd{4}-d{2}-d{2}';
1103 input.classList.add('lm-DataGrid-cellEditorWidget');
1104 input.classList.add('lm-DataGrid-cellEditorInput');
1105
1106 this._input = input;
1107 }
1108
1109 private _bindEvents() {
1110 this._input.addEventListener('keydown', this);
1111 this._input.addEventListener('blur', this);
1112 }
1113
1114 private _unbindEvents() {
1115 this._input.removeEventListener('keydown', this);
1116 this._input.removeEventListener('blur', this);
1117 }
1118
1119 private _onKeyDown(event: KeyboardEvent) {
1120 switch (getKeyboardLayout().keyForKeydownEvent(event)) {
1121 case 'Enter':
1122 this.commit(event.shiftKey ? 'up' : 'down');
1123 break;
1124 case 'Tab':
1125 this.commit(event.shiftKey ? 'left' : 'right');
1126 event.stopPropagation();
1127 event.preventDefault();
1128 break;
1129 case 'Escape':
1130 this.cancel();
1131 break;
1132 default:
1133 break;
1134 }
1135 }
1136
1137 private _onBlur(event: FocusEvent) {
1138 if (this.isDisposed) {
1139 return;
1140 }
1141
1142 if (!this.commit()) {
1143 event.preventDefault();
1144 event.stopPropagation();
1145 this._input.focus();
1146 }
1147 }
1148
1149 private _input: HTMLInputElement;
1150 }
1151
1152 /**
1153 * Cell editor for boolean cells.
1154 */
1155 export class BooleanCellEditor extends CellEditor {
1156 /**
1157 * Handle the DOM events for the editor.
1158 *
1159 * @param event - The DOM event sent to the editor.
1160 */
1161 handleEvent(event: Event): void {
1162 switch (event.type) {
1163 case 'keydown':
1164 this._onKeyDown(event as KeyboardEvent);
1165 break;
1166 case 'mousedown':
1167 // fix focus loss problem in Safari and Firefox
1168 this._input.focus();
1169 event.stopPropagation();
1170 event.preventDefault();
1171 break;
1172 case 'blur':
1173 this._onBlur(event as FocusEvent);
1174 break;
1175 }
1176 }
1177
1178 /**
1179 * Dispose of the resources held by cell editor.
1180 */
1181 dispose(): void {
1182 if (this.isDisposed) {
1183 return;
1184 }
1185
1186 this._unbindEvents();
1187
1188 super.dispose();
1189 }
1190
1191 /**
1192 * Start editing the cell.
1193 */
1194 protected startEditing(): void {
1195 this._createWidget();
1196
1197 const cell = this.cell;
1198 const cellInfo = this.getCellInfo(cell);
1199 this._input.checked = this._deserialize(cellInfo.data);
1200 this.editorContainer.appendChild(this._input);
1201 this._input.focus();
1202
1203 this._bindEvents();
1204 }
1205
1206 /**
1207 * Return the current boolean input entered.
1208 */
1209 protected getInput(): boolean | null {
1210 return this._input.checked;
1211 }
1212
1213 private _deserialize(value: any): any {
1214 if (value === null || value === undefined) {
1215 return false;
1216 }
1217
1218 return value == true;
1219 }
1220
1221 private _createWidget() {
1222 const input = document.createElement('input');
1223 input.classList.add('lm-DataGrid-cellEditorWidget');
1224 input.classList.add('lm-DataGrid-cellEditorCheckbox');
1225 input.type = 'checkbox';
1226 input.spellcheck = false;
1227
1228 this._input = input;
1229 }
1230
1231 private _bindEvents() {
1232 this._input.addEventListener('keydown', this);
1233 this._input.addEventListener('mousedown', this);
1234 this._input.addEventListener('blur', this);
1235 }
1236
1237 private _unbindEvents() {
1238 this._input.removeEventListener('keydown', this);
1239 this._input.removeEventListener('mousedown', this);
1240 this._input.removeEventListener('blur', this);
1241 }
1242
1243 private _onKeyDown(event: KeyboardEvent) {
1244 switch (getKeyboardLayout().keyForKeydownEvent(event)) {
1245 case 'Enter':
1246 this.commit(event.shiftKey ? 'up' : 'down');
1247 break;
1248 case 'Tab':
1249 this.commit(event.shiftKey ? 'left' : 'right');
1250 event.stopPropagation();
1251 event.preventDefault();
1252 break;
1253 case 'Escape':
1254 this.cancel();
1255 break;
1256 default:
1257 break;
1258 }
1259 }
1260
1261 private _onBlur(event: FocusEvent) {
1262 if (this.isDisposed) {
1263 return;
1264 }
1265
1266 if (!this.commit()) {
1267 event.preventDefault();
1268 event.stopPropagation();
1269 this._input.focus();
1270 }
1271 }
1272
1273 private _input: HTMLInputElement;
1274 }
1275
1276 /**
1277 * Cell editor for option cells.
1278 *
1279 * It supports multiple option selection. If cell metadata contains
1280 * type attribute 'array', then it behaves as a multi select.
1281 * In that case cell data is expected to be list of string values.
1282 */
1283 export class OptionCellEditor extends CellEditor {
1284 /**
1285 * Dispose of the resources held by cell editor.
1286 */
1287 dispose(): void {
1288 if (this.isDisposed) {
1289 return;
1290 }
1291
1292 super.dispose();
1293
1294 if (this._isMultiSelect) {
1295 document.body.removeChild(this._select);
1296 }
1297 }
1298
1299 /**
1300 * Start editing the cell.
1301 */
1302 protected startEditing(): void {
1303 const cell = this.cell;
1304 const cellInfo = this.getCellInfo(cell);
1305 const metadata = cell.grid.dataModel!.metadata(
1306 'body',
1307 cell.row,
1308 cell.column
1309 );
1310 this._isMultiSelect = metadata.type === 'array';
1311 this._createWidget();
1312
1313 if (this._isMultiSelect) {
1314 this._select.multiple = true;
1315 const values = this._deserialize(cellInfo.data) as string[];
1316 for (let i = 0; i < this._select.options.length; ++i) {
1317 const option = this._select.options.item(i);
1318 option!.selected = values.indexOf(option!.value) !== -1;
1319 }
1320 document.body.appendChild(this._select);
1321 } else {
1322 this._select.value = this._deserialize(cellInfo.data) as string;
1323 this.editorContainer.appendChild(this._select);
1324 }
1325
1326 this._select.focus();
1327
1328 this._bindEvents();
1329
1330 this.updatePosition();
1331 }
1332
1333 /**
1334 * Return the current option input.
1335 */
1336 protected getInput(): string | string[] | null {
1337 if (this._isMultiSelect) {
1338 const input: string[] = [];
1339 for (let i = 0; i < this._select.selectedOptions.length; ++i) {
1340 input.push(this._select.selectedOptions.item(i)!.value);
1341 }
1342 return input;
1343 } else {
1344 return this._select.value;
1345 }
1346 }
1347
1348 /**
1349 * Reposition cell editor.
1350 */
1351 protected updatePosition(): void {
1352 super.updatePosition();
1353
1354 if (!this._isMultiSelect) {
1355 return;
1356 }
1357
1358 const cellInfo = this.getCellInfo(this.cell);
1359
1360 this._select.style.position = 'absolute';
1361 const editorContainerRect = this.editorContainer.getBoundingClientRect();
1362
1363 this._select.style.left = editorContainerRect.left + 'px';
1364 this._select.style.top = editorContainerRect.top + cellInfo.height + 'px';
1365 this._select.style.width = editorContainerRect.width + 'px';
1366 this._select.style.maxHeight = '60px';
1367
1368 this.editorContainer.style.visibility = 'hidden';
1369 }
1370
1371 private _deserialize(value: any): string | string[] {
1372 if (value === null || value === undefined) {
1373 return '';
1374 }
1375
1376 if (this._isMultiSelect) {
1377 const values: string[] = [];
1378 if (Array.isArray(value)) {
1379 for (let item of value) {
1380 values.push(item.toString());
1381 }
1382 }
1383 return values;
1384 } else {
1385 return value.toString();
1386 }
1387 }
1388
1389 private _createWidget() {
1390 const cell = this.cell;
1391 const metadata = cell.grid.dataModel!.metadata(
1392 'body',
1393 cell.row,
1394 cell.column
1395 );
1396 const items = metadata.constraint.enum;
1397
1398 const select = document.createElement('select');
1399 select.classList.add('lm-DataGrid-cellEditorWidget');
1400 for (let item of items) {
1401 const option = document.createElement('option');
1402 option.value = item;
1403 option.text = item;
1404 select.appendChild(option);
1405 }
1406
1407 this._select = select;
1408 }
1409
1410 private _bindEvents() {
1411 this._select.addEventListener('keydown', this._onKeyDown.bind(this));
1412 this._select.addEventListener('blur', this._onBlur.bind(this));
1413 }
1414
1415 private _onKeyDown(event: KeyboardEvent) {
1416 switch (getKeyboardLayout().keyForKeydownEvent(event)) {
1417 case 'Enter':
1418 this.commit(event.shiftKey ? 'up' : 'down');
1419 break;
1420 case 'Tab':
1421 this.commit(event.shiftKey ? 'left' : 'right');
1422 event.stopPropagation();
1423 event.preventDefault();
1424 break;
1425 case 'Escape':
1426 this.cancel();
1427 break;
1428 default:
1429 break;
1430 }
1431 }
1432
1433 private _onBlur(event: FocusEvent) {
1434 if (this.isDisposed) {
1435 return;
1436 }
1437
1438 if (!this.commit()) {
1439 event.preventDefault();
1440 event.stopPropagation();
1441 this._select.focus();
1442 }
1443 }
1444
1445 private _select: HTMLSelectElement;
1446 private _isMultiSelect: boolean = false;
1447 }
1448
1449 /**
1450 * Cell editor for option cells whose value can be any value
1451 * from set of pre-defined options or values that can be input by user.
1452 */
1453 export class DynamicOptionCellEditor extends CellEditor {
1454 /**
1455 * Handle the DOM events for the editor.
1456 *
1457 * @param event - The DOM event sent to the editor.
1458 */
1459 handleEvent(event: Event): void {
1460 switch (event.type) {
1461 case 'keydown':
1462 this._onKeyDown(event as KeyboardEvent);
1463 break;
1464 case 'blur':
1465 this._onBlur(event as FocusEvent);
1466 break;
1467 }
1468 }
1469
1470 /**
1471 * Dispose of the resources held by cell editor.
1472 */
1473 dispose(): void {
1474 if (this.isDisposed) {
1475 return;
1476 }
1477
1478 this._unbindEvents();
1479
1480 super.dispose();
1481 }
1482
1483 /**
1484 * Start editing the cell.
1485 */
1486 protected startEditing(): void {
1487 this._createWidget();
1488
1489 const cell = this.cell;
1490 const cellInfo = this.getCellInfo(cell);
1491 this._input.value = this._deserialize(cellInfo.data);
1492 this.editorContainer.appendChild(this._input);
1493 this._input.focus();
1494 this._input.select();
1495
1496 this._bindEvents();
1497 }
1498
1499 /**
1500 * Return the current option input.
1501 */
1502 protected getInput(): string | null {
1503 return this._input.value;
1504 }
1505
1506 private _deserialize(value: any): any {
1507 if (value === null || value === undefined) {
1508 return '';
1509 }
1510
1511 return value.toString();
1512 }
1513
1514 private _createWidget() {
1515 const cell = this.cell;
1516 const grid = cell.grid;
1517 const dataModel = grid.dataModel!;
1518 const rowCount = dataModel.rowCount('body');
1519
1520 const listId = 'cell-editor-list';
1521 const list = document.createElement('datalist');
1522 list.id = listId;
1523 const input = document.createElement('input');
1524 input.classList.add('lm-DataGrid-cellEditorWidget');
1525 input.classList.add('lm-DataGrid-cellEditorInput');
1526 const valueSet = new Set<string>();
1527 for (let r = 0; r < rowCount; ++r) {
1528 const data = dataModel.data('body', r, cell.column);
1529 if (data) {
1530 valueSet.add(data);
1531 }
1532 }
1533 valueSet.forEach((value: string) => {
1534 const option = document.createElement('option');
1535 option.value = value;
1536 option.text = value;
1537 list.appendChild(option);
1538 });
1539 this.editorContainer.appendChild(list);
1540 input.setAttribute('list', listId);
1541
1542 this._input = input;
1543 }
1544
1545 private _bindEvents() {
1546 this._input.addEventListener('keydown', this);
1547 this._input.addEventListener('blur', this);
1548 }
1549
1550 private _unbindEvents() {
1551 this._input.removeEventListener('keydown', this);
1552 this._input.removeEventListener('blur', this);
1553 }
1554
1555 private _onKeyDown(event: KeyboardEvent) {
1556 switch (getKeyboardLayout().keyForKeydownEvent(event)) {
1557 case 'Enter':
1558 this.commit(event.shiftKey ? 'up' : 'down');
1559 break;
1560 case 'Tab':
1561 this.commit(event.shiftKey ? 'left' : 'right');
1562 event.stopPropagation();
1563 event.preventDefault();
1564 break;
1565 case 'Escape':
1566 this.cancel();
1567 break;
1568 default:
1569 break;
1570 }
1571 }
1572
1573 private _onBlur(event: FocusEvent) {
1574 if (this.isDisposed) {
1575 return;
1576 }
1577
1578 if (!this.commit()) {
1579 event.preventDefault();
1580 event.stopPropagation();
1581 this._input.focus();
1582 }
1583 }
1584
1585 private _input: HTMLInputElement;
1586 }
1587
1588 /**
1589 * The namespace for the `CellEditor` class statics.
1590 */
1591 export namespace CellEditor {
1592 /**
1593 * An object which holds the configuration data for a cell.
1594 */
1595 export type CellConfig = {
1596 /**
1597 * The grid containing the cell.
1598 */
1599 readonly grid: DataGrid;
1600 /**
1601 * The row index of the cell.
1602 */
1603 readonly row: number;
1604
1605 /**
1606 * The column index of the cell.
1607 */
1608 readonly column: number;
1609 };
1610
1611 /**
1612 * A widget which implements a notification popup.
1613 */
1614 export class Notification extends Widget {
1615 /**
1616 * Construct a new notification.
1617 *
1618 * @param options - The options for initializing the notification.
1619 */
1620 constructor(options: Notification.IOptions) {
1621 super({ node: Notification.createNode() });
1622 this.addClass('lm-DataGrid-notification');
1623 this.setFlag(Widget.Flag.DisallowLayout);
1624
1625 this._target = options.target;
1626 this._message = options.message || '';
1627 this._placement = options.placement || 'bottom';
1628
1629 Widget.attach(this, document.body);
1630
1631 if (options.timeout && options.timeout > 0) {
1632 setTimeout(() => {
1633 this.close();
1634 }, options.timeout);
1635 }
1636 }
1637
1638 /**
1639 * Handle the DOM events for the notification.
1640 *
1641 * @param event - The DOM event sent to the notification.
1642 *
1643 * #### Notes
1644 * This method implements the DOM `EventListener` interface and is
1645 * called in response to events on the notification's DOM node.
1646 *
1647 * This should not be called directly by user code.
1648 */
1649 handleEvent(event: Event): void {
1650 switch (event.type) {
1651 case 'mousedown':
1652 this._evtMouseDown(event as MouseEvent);
1653 break;
1654 case 'contextmenu':
1655 event.preventDefault();
1656 event.stopPropagation();
1657 break;
1658 }
1659 }
1660
1661 /**
1662 * Get the placement of the notification.
1663 */
1664 get placement(): Notification.Placement {
1665 return this._placement;
1666 }
1667
1668 /**
1669 * Set the placement of the notification.
1670 */
1671 set placement(value: Notification.Placement) {
1672 // Do nothing if the placement does not change.
1673 if (this._placement === value) {
1674 return;
1675 }
1676
1677 // Update the internal placement.
1678 this._placement = value;
1679
1680 // Schedule an update for notification.
1681 this.update();
1682 }
1683
1684 /**
1685 * Get the current value of the message.
1686 */
1687 get message(): string {
1688 return this._message;
1689 }
1690
1691 /**
1692 * Set the current value of the message.
1693 *
1694 */
1695 set message(value: string) {
1696 // Do nothing if the value does not change.
1697 if (this._message === value) {
1698 return;
1699 }
1700
1701 // Update the internal value.
1702 this._message = value;
1703
1704 // Schedule an update for notification.
1705 this.update();
1706 }
1707
1708 /**
1709 * Get the node presenting the message.
1710 */
1711 get messageNode(): HTMLSpanElement {
1712 return this.node.getElementsByClassName(
1713 'lm-DataGrid-notificationMessage'
1714 )[0] as HTMLSpanElement;
1715 }
1716
1717 /**
1718 * A method invoked on a 'before-attach' message.
1719 */
1720 protected onBeforeAttach(msg: Message): void {
1721 this.node.addEventListener('mousedown', this);
1722 this.update();
1723 }
1724
1725 /**
1726 * A method invoked on an 'after-detach' message.
1727 */
1728 protected onAfterDetach(msg: Message): void {
1729 this.node.removeEventListener('mousedown', this);
1730 }
1731
1732 /**
1733 * A method invoked on an 'update-request' message.
1734 */
1735 protected onUpdateRequest(msg: Message): void {
1736 const targetRect = this._target.getBoundingClientRect();
1737 const style = this.node.style;
1738
1739 switch (this._placement) {
1740 case 'bottom':
1741 style.left = targetRect.left + 'px';
1742 style.top = targetRect.bottom + 'px';
1743 break;
1744 case 'top':
1745 style.left = targetRect.left + 'px';
1746 style.height = targetRect.top + 'px';
1747 style.top = '0';
1748 style.alignItems = 'flex-end';
1749 style.justifyContent = 'flex-end';
1750 break;
1751 case 'left':
1752 style.left = '0';
1753 style.width = targetRect.left + 'px';
1754 style.top = targetRect.top + 'px';
1755 style.alignItems = 'flex-end';
1756 style.justifyContent = 'flex-end';
1757 break;
1758 case 'right':
1759 style.left = targetRect.right + 'px';
1760 style.top = targetRect.top + 'px';
1761 break;
1762 }
1763
1764 this.messageNode.innerHTML = this._message;
1765 }
1766
1767 /**
1768 * Handle the `'mousedown'` event for the notification.
1769 */
1770 private _evtMouseDown(event: MouseEvent): void {
1771 // Do nothing if it's not a left mouse press.
1772 if (event.button !== 0) {
1773 return;
1774 }
1775
1776 event.preventDefault();
1777 event.stopPropagation();
1778 this.close();
1779 }
1780
1781 private _target: HTMLElement;
1782 private _message: string = '';
1783 private _placement: Notification.Placement;
1784 }
1785
1786 /**
1787 * The namespace for the `Notification` class statics.
1788 */
1789 export namespace Notification {
1790 /**
1791 * A type alias for a notification placement.
1792 */
1793 export type Placement = 'top' | 'bottom' | 'left' | 'right';
1794
1795 /**
1796 * An options object for creating a notification.
1797 */
1798 export interface IOptions {
1799 /**
1800 * Target element to attach notification to.
1801 *
1802 */
1803 target: HTMLElement;
1804
1805 /**
1806 * The message to show on notification.
1807 */
1808 message?: string;
1809
1810 /**
1811 * The placement of the notification.
1812 *
1813 * The default is `'bottom'`.
1814 */
1815 placement?: Placement;
1816
1817 /**
1818 * Duration in ms after which to close notification popup.
1819 *
1820 * The default is undefined, and notification is kept visible
1821 * Timeout value needs to be greater than zero
1822 */
1823 timeout?: number;
1824 }
1825
1826 /**
1827 * Create the DOM node for notification.
1828 */
1829 export function createNode(): HTMLElement {
1830 const node = document.createElement('div');
1831 const container = document.createElement('div');
1832 container.className = 'lm-DataGrid-notificationContainer';
1833 const message = document.createElement('span');
1834 message.className = 'lm-DataGrid-notificationMessage';
1835 container.appendChild(message);
1836 node.appendChild(container);
1837
1838 return node;
1839 }
1840 }
1841 }
1842
1843 /**
1844 * A namespace for module-private functionality.
1845 */
1846 namespace Private {
1847 /**
1848 * A type alias for cell properties.
1849 */
1850 export type ICellInfo = {
1851 grid: DataGrid;
1852 row: number;
1853 column: number;
1854 data: any;
1855 x: number;
1856 y: number;
1857 width: number;
1858 height: number;
1859 };
1860 }