/
baseEditor.js
648 lines (564 loc) · 19.7 KB
/
baseEditor.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
import { isDefined, stringify } from '../../helpers/mixed';
import { mixin } from '../../helpers/object';
import { SHORTCUTS_GROUP_NAVIGATION } from '../../editorManager';
import hooksRefRegisterer from '../../mixins/hooksRefRegisterer';
import {
getScrollbarWidth,
offset,
hasVerticalScrollbar,
hasHorizontalScrollbar,
outerWidth,
outerHeight,
getComputedStyle,
} from '../../helpers/dom/element';
export const EDITOR_TYPE = 'base';
export const EDITOR_STATE = Object.freeze({
VIRGIN: 'STATE_VIRGIN', // before editing
EDITING: 'STATE_EDITING',
WAITING: 'STATE_WAITING', // waiting for async validation
FINISHED: 'STATE_FINISHED'
});
export const SHORTCUTS_GROUP_EDITOR = 'baseEditor';
/**
* @class BaseEditor
*/
export class BaseEditor {
static get EDITOR_TYPE() {
return EDITOR_TYPE;
}
/**
* A reference to the source instance of the Handsontable.
*
* @type {Handsontable}
*/
hot;
/**
* Editor's state.
*
* @type {string}
*/
state = EDITOR_STATE.VIRGIN;
/**
* Flag to store information about editor's opening status.
*
* @private
*
* @type {boolean}
*/
_opened = false;
/**
* Defines the editor's editing mode. When false, then an editor works in fast editing mode.
*
* @private
*
* @type {boolean}
*/
_fullEditMode = false;
/**
* Callback to call after closing editor.
*
* @type {Function}
*/
_closeCallback = null;
/**
* Currently rendered cell's TD element.
*
* @type {HTMLTableCellElement}
*/
TD = null;
/**
* Visual row index.
*
* @type {number}
*/
row = null;
/**
* Visual column index.
*
* @type {number}
*/
col = null;
/**
* Column property name or a column index, if datasource is an array of arrays.
*
* @type {number|string}
*/
prop = null;
/**
* Original cell's value.
*
* @type {*}
*/
originalValue = null;
/**
* Object containing the cell's properties.
*
* @type {object}
*/
cellProperties = null;
/**
* @param {Handsontable} hotInstance A reference to the source instance of the Handsontable.
*/
constructor(hotInstance) {
this.hot = hotInstance;
this.init();
}
/**
* Fires callback after closing editor.
*
* @private
* @param {boolean} result The editor value.
*/
_fireCallbacks(result) {
if (this._closeCallback) {
this._closeCallback(result);
this._closeCallback = null;
}
}
/**
* Initializes an editor's intance.
*/
init() {}
/**
* Required method to get current value from editable element.
*/
getValue() {
throw Error('Editor getValue() method unimplemented');
}
/**
* Required method to set new value into editable element.
*/
setValue() {
throw Error('Editor setValue() method unimplemented');
}
/**
* Required method to open editor.
*/
open() {
throw Error('Editor open() method unimplemented');
}
/**
* Required method to close editor.
*/
close() {
throw Error('Editor close() method unimplemented');
}
/**
* Prepares editor's meta data.
*
* @param {number} row The visual row index.
* @param {number} col The visual column index.
* @param {number|string} prop The column property (passed when datasource is an array of objects).
* @param {HTMLTableCellElement} td The rendered cell element.
* @param {*} value The rendered value.
* @param {object} cellProperties The cell meta object (see {@link Core#getCellMeta}).
*/
prepare(row, col, prop, td, value, cellProperties) {
this.TD = td;
this.row = row;
this.col = col;
this.prop = prop;
this.originalValue = value;
this.cellProperties = cellProperties;
this.state = EDITOR_STATE.VIRGIN;
}
/**
* Fallback method to provide extendable editors in ES5.
*
* @returns {Function}
*/
extend() {
return (class Editor extends this.constructor {});
}
/**
* Saves value from editor into data storage.
*
* @param {*} value The editor value.
* @param {boolean} ctrlDown If `true`, applies value to each cell in the last selected range.
*/
saveValue(value, ctrlDown) {
let visualRowFrom;
let visualColumnFrom;
let visualRowTo;
let visualColumnTo;
// if ctrl+enter and multiple cells selected, behave like Excel (finish editing and apply to all cells)
if (ctrlDown) {
const selectedLast = this.hot.getSelectedLast();
visualRowFrom = Math.max(Math.min(selectedLast[0], selectedLast[2]), 0); // Math.max eliminate headers coords.
visualColumnFrom = Math.max(Math.min(selectedLast[1], selectedLast[3]), 0); // Math.max eliminate headers coords.
visualRowTo = Math.max(selectedLast[0], selectedLast[2]);
visualColumnTo = Math.max(selectedLast[1], selectedLast[3]);
} else {
[visualRowFrom, visualColumnFrom, visualRowTo, visualColumnTo] = [this.row, this.col, null, null];
}
const modifiedCellCoords = this.hot.runHooks('modifyGetCellCoords', visualRowFrom, visualColumnFrom);
if (Array.isArray(modifiedCellCoords)) {
[visualRowFrom, visualColumnFrom] = modifiedCellCoords;
}
const shortcutManager = this.hot.getShortcutManager();
const editorContext = shortcutManager.getContext('editor');
const contextConfig = {
runOnlyIf: () => isDefined(this.hot.getSelected()),
group: SHORTCUTS_GROUP_EDITOR,
};
if (this.isInFullEditMode()) {
editorContext.addShortcuts([{
keys: [['ArrowUp']],
callback: () => {
this.hot.selection.transformStart(-1, 0);
},
}, {
keys: [['ArrowDown']],
callback: () => {
this.hot.selection.transformStart(1, 0);
},
}, {
keys: [['ArrowLeft']],
callback: () => {
this.hot.selection.transformStart(0, -1 * this.hot.getDirectionFactor());
},
}, {
keys: [['ArrowRight']],
callback: () => {
this.hot.selection.transformStart(0, this.hot.getDirectionFactor());
},
}], contextConfig);
}
// Saving values using the modified coordinates.
this.hot.populateFromArray(visualRowFrom, visualColumnFrom, value, visualRowTo, visualColumnTo, 'edit');
}
/**
* Begins editing on a highlighted cell and hides fillHandle corner if was present.
*
* @param {*} newInitialValue The initial editor value.
* @param {Event} event The keyboard event object.
*/
beginEditing(newInitialValue, event) {
if (this.state !== EDITOR_STATE.VIRGIN) {
return;
}
const hotInstance = this.hot;
// We have to convert visual indexes into renderable indexes
// due to hidden columns don't participate in the rendering process
const renderableRowIndex = hotInstance.rowIndexMapper.getRenderableFromVisualIndex(this.row);
const renderableColumnIndex = hotInstance.columnIndexMapper.getRenderableFromVisualIndex(this.col);
hotInstance.view.scrollViewport(hotInstance._createCellCoords(renderableRowIndex, renderableColumnIndex));
this.state = EDITOR_STATE.EDITING;
// Set the editor value only in the full edit mode. In other mode the focusable element has to be empty,
// otherwise IME (editor for Asia users) doesn't work.
if (this.isInFullEditMode()) {
const stringifiedInitialValue = typeof newInitialValue === 'string' ?
newInitialValue : stringify(this.originalValue);
this.setValue(stringifiedInitialValue);
}
this.open(event);
this._opened = true;
this.focus();
// only rerender the selections (FillHandle should disappear when beginEditing is triggered)
hotInstance.view.render();
hotInstance.runHooks('afterBeginEditing', this.row, this.col);
}
/**
* Finishes editing and start saving or restoring process for editing cell or last selected range.
*
* @param {boolean} restoreOriginalValue If true, then closes editor without saving value from the editor into a cell.
* @param {boolean} ctrlDown If true, then saveValue will save editor's value to each cell in the last selected range.
* @param {Function} callback The callback function, fired after editor closing.
*/
finishEditing(restoreOriginalValue, ctrlDown, callback) {
let val;
if (callback) {
const previousCloseCallback = this._closeCallback;
this._closeCallback = (result) => {
if (previousCloseCallback) {
previousCloseCallback(result);
}
callback(result);
this.hot.view.render();
};
}
if (this.isWaiting()) {
return;
}
const shortcutManager = this.hot.getShortcutManager();
const editorContext = shortcutManager.getContext('editor');
editorContext.removeShortcutsByGroup(SHORTCUTS_GROUP_EDITOR);
editorContext.removeShortcutsByGroup(SHORTCUTS_GROUP_NAVIGATION);
if (this.state === EDITOR_STATE.VIRGIN) {
this.hot._registerTimeout(() => {
this._fireCallbacks(true);
});
return;
}
if (this.state === EDITOR_STATE.EDITING) {
if (restoreOriginalValue) {
this.cancelChanges();
this.hot.view.render();
return;
}
const value = this.getValue();
if (this.cellProperties.trimWhitespace) {
// We trim only string values
val = [
[typeof value === 'string' ? String.prototype.trim.call(value || '') : value]
];
} else {
val = [
[value]
];
}
this.state = EDITOR_STATE.WAITING;
this.saveValue(val, ctrlDown);
if (this.hot.getCellValidator(this.cellProperties)) {
this.hot.addHookOnce('postAfterValidate', (result) => {
this.state = EDITOR_STATE.FINISHED;
this.discardEditor(result);
});
} else {
this.state = EDITOR_STATE.FINISHED;
this.discardEditor(true);
}
}
}
/**
* Finishes editing without singout saving value.
*/
cancelChanges() {
this.state = EDITOR_STATE.FINISHED;
this.discardEditor();
}
/**
* Verifies result of validation or closes editor if user's cancelled changes.
*
* @param {boolean|undefined} result If `false` and the cell using allowInvalid option,
* then an editor won't be closed until validation is passed.
*/
discardEditor(result) {
if (this.state !== EDITOR_STATE.FINISHED) {
return;
}
// validator was defined and failed
if (result === false && this.cellProperties.allowInvalid !== true) {
this.hot.selectCell(this.row, this.col);
this.focus();
this.state = EDITOR_STATE.EDITING;
this._fireCallbacks(false);
} else {
this.close();
this._opened = false;
this._fullEditMode = false;
this.state = EDITOR_STATE.VIRGIN;
this._fireCallbacks(true);
const shortcutManager = this.hot.getShortcutManager();
shortcutManager.setActiveContextName('grid');
}
}
/**
* Switch editor into full edit mode. In this state navigation keys don't close editor. This mode is activated
* automatically after hit ENTER or F2 key on the cell or while editing cell press F2 key.
*/
enableFullEditMode() {
this._fullEditMode = true;
}
/**
* Checks if editor is in full edit mode.
*
* @returns {boolean}
*/
isInFullEditMode() {
return this._fullEditMode;
}
/**
* Returns information whether the editor is open.
*
* @returns {boolean}
*/
isOpened() {
return this._opened;
}
/**
* Returns information whether the editor is waiting, eg.: for async validation.
*
* @returns {boolean}
*/
isWaiting() {
return this.state === EDITOR_STATE.WAITING;
}
/* eslint-disable jsdoc/require-description-complete-sentence */
/**
* Gets the object that provides information about the edited cell size and its position
* relative to the table viewport.
*
* The rectangle has six integer properties:
* - `top` The top position relative to the table viewport
* - `start` The left (or right in RTL) position relative to the table viewport
* - `width` The cell's current width;
* - `maxWidth` The maximum cell's width after which the editor goes out of the table viewport
* - `height` The cell's current height;
* - `maxHeight` The maximum cell's height after which the editor goes out of the table viewport
*
* @returns {{top: number, start: number, width: number, maxWidth: number, height: number, maxHeight: number} | undefined}
*/
getEditedCellRect() {
const TD = this.getEditedCell();
// TD is outside of the viewport.
if (!TD) {
return;
}
const { wtOverlays, wtViewport } = this.hot.view._wt;
const rootWindow = this.hot.rootWindow;
const currentOffset = offset(TD);
const cellWidth = outerWidth(TD);
const containerOffset = offset(this.hot.rootElement);
const containerWidth = outerWidth(this.hot.rootElement);
const scrollableContainerTop = wtOverlays.topOverlay.holder;
const scrollableContainerLeft = wtOverlays.inlineStartOverlay.holder;
const containerScrollTop = scrollableContainerTop !== rootWindow ?
scrollableContainerTop.scrollTop : 0;
const containerScrollLeft = scrollableContainerLeft !== rootWindow ?
scrollableContainerLeft.scrollLeft : 0;
const gridMostRightPos = rootWindow.innerWidth - containerOffset.left - containerWidth;
const { wtTable: overlayTable } = wtOverlays.getParentOverlay(TD) ?? this.hot.view._wt;
const overlayName = overlayTable.name;
const scrollTop = ['master', 'inline_start'].includes(overlayName) ? containerScrollTop : 0;
const scrollLeft = ['master', 'top', 'bottom'].includes(overlayName) ? containerScrollLeft : 0;
// If colHeaders is disabled, cells in the first row have border-top
const editTopModifier = currentOffset.top === containerOffset.top ? 0 : 1;
let topPos = currentOffset.top - containerOffset.top - editTopModifier - scrollTop;
let inlineStartPos = 0;
if (this.hot.isRtl()) {
inlineStartPos = rootWindow.innerWidth - currentOffset.left - cellWidth - gridMostRightPos - 1 + scrollLeft;
} else {
inlineStartPos = currentOffset.left - containerOffset.left - 1 - scrollLeft;
}
// When the scrollable element is Window object then the editor position needs to be compensated
// by the overlays' position (position relative to the table viewport). In other cases, the overlay's
// position always returns 0.
if (['top', 'top_inline_start_corner'].includes(overlayName)) {
topPos += wtOverlays.topOverlay.getOverlayOffset();
}
if (['inline_start', 'top_inline_start_corner'].includes(overlayName)) {
inlineStartPos += Math.abs(wtOverlays.inlineStartOverlay.getOverlayOffset());
}
const hasColumnHeaders = this.hot.hasColHeaders();
const renderableRow = this.hot.rowIndexMapper.getRenderableFromVisualIndex(this.row);
const renderableColumn = this.hot.columnIndexMapper.getRenderableFromVisualIndex(this.col);
const nrOfRenderableRowIndexes = this.hot.rowIndexMapper.getRenderableIndexesLength();
const firstRowIndexOfTheBottomOverlay = nrOfRenderableRowIndexes - this.hot.view._wt.getSetting('fixedRowsBottom');
if (hasColumnHeaders && renderableRow <= 0 || renderableRow === firstRowIndexOfTheBottomOverlay) {
topPos += 1;
}
if (renderableColumn <= 0) {
inlineStartPos += 1;
}
const firstRowOffset = wtViewport.rowsRenderCalculator.startPosition;
const firstColumnOffset = wtViewport.columnsRenderCalculator.startPosition;
const horizontalScrollPosition = Math.abs(wtOverlays.inlineStartOverlay.getScrollPosition());
const verticalScrollPosition = wtOverlays.topOverlay.getScrollPosition();
const scrollbarWidth = getScrollbarWidth(this.hot.rootDocument);
let cellTopOffset = TD.offsetTop;
if (['inline_start', 'master'].includes(overlayName)) {
cellTopOffset += firstRowOffset - verticalScrollPosition;
}
if (['bottom', 'bottom_inline_start_corner'].includes(overlayName)) {
const {
wtViewport: bottomWtViewport,
wtTable: bottomWtTable,
} = wtOverlays.bottomOverlay.clone;
cellTopOffset += bottomWtViewport.getWorkspaceHeight() - bottomWtTable.getHeight() - scrollbarWidth;
}
let cellStartOffset = TD.offsetLeft;
if (this.hot.isRtl()) {
if (cellStartOffset >= 0) {
cellStartOffset = overlayTable.getWidth() - TD.offsetLeft;
} else {
// The `offsetLeft` returns negative values when the parent offset element has position relative
// (it happens when on the cell the selection is applied - the `area` CSS class).
// When it happens the `offsetLeft` value is calculated from the right edge of the parent element.
cellStartOffset = Math.abs(cellStartOffset);
}
cellStartOffset += firstColumnOffset - horizontalScrollPosition - cellWidth;
} else if (['top', 'master', 'bottom'].includes(overlayName)) {
cellStartOffset += firstColumnOffset - horizontalScrollPosition;
}
const cellComputedStyle = getComputedStyle(this.TD, this.hot.rootWindow);
const borderPhysicalWidthProp = this.hot.isRtl() ? 'borderRightWidth' : 'borderLeftWidth';
const inlineStartBorderCompensation = parseInt(cellComputedStyle[borderPhysicalWidthProp], 10) > 0 ? 0 : 1;
const topBorderCompensation = parseInt(cellComputedStyle.borderTopWidth, 10) > 0 ? 0 : 1;
const width = outerWidth(TD) + inlineStartBorderCompensation;
const height = outerHeight(TD) + topBorderCompensation;
const actualVerticalScrollbarWidth = hasVerticalScrollbar(scrollableContainerTop) ? scrollbarWidth : 0;
const actualHorizontalScrollbarWidth = hasHorizontalScrollbar(scrollableContainerLeft) ? scrollbarWidth : 0;
const maxWidth = this.hot.view.maximumVisibleElementWidth(cellStartOffset) -
actualVerticalScrollbarWidth + inlineStartBorderCompensation;
const maxHeight = Math.max(this.hot.view.maximumVisibleElementHeight(cellTopOffset) -
actualHorizontalScrollbarWidth + topBorderCompensation, 23);
return {
top: topPos,
start: inlineStartPos,
height,
maxHeight,
width,
maxWidth,
};
}
/* eslint-enable jsdoc/require-description-complete-sentence */
/**
* Gets className of the edited cell if exist.
*
* @returns {string}
*/
getEditedCellsLayerClass() {
const editorSection = this.checkEditorSection();
switch (editorSection) {
case 'inline-start':
return 'ht_clone_left ht_clone_inline_start';
case 'bottom':
return 'ht_clone_bottom';
case 'bottom-inline-start-corner':
return 'ht_clone_bottom_left_corner ht_clone_bottom_inline_start_corner';
case 'top':
return 'ht_clone_top';
case 'top-inline-start-corner':
return 'ht_clone_top_left_corner ht_clone_top_inline_start_corner';
default:
return 'ht_clone_master';
}
}
/**
* Gets HTMLTableCellElement of the edited cell if exist.
*
* @returns {HTMLTableCellElement|null}
*/
getEditedCell() {
return this.hot.getCell(this.row, this.col, true);
}
/**
* Returns name of the overlay, where editor is placed.
*
* @private
* @returns {string}
*/
checkEditorSection() {
const totalRows = this.hot.countRows();
let section = '';
if (this.row < this.hot.getSettings().fixedRowsTop) {
if (this.col < this.hot.getSettings().fixedColumnsStart) {
section = 'top-inline-start-corner';
} else {
section = 'top';
}
} else if (this.hot.getSettings().fixedRowsBottom &&
this.row >= totalRows - this.hot.getSettings().fixedRowsBottom) {
if (this.col < this.hot.getSettings().fixedColumnsStart) {
section = 'bottom-inline-start-corner';
} else {
section = 'bottom';
}
} else if (this.col < this.hot.getSettings().fixedColumnsStart) {
section = 'inline-start';
}
return section;
}
}
mixin(BaseEditor, hooksRefRegisterer);