canvas-datagrid 0.25.4 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2663 @@
1
+ /*jslint browser: true, unparam: true, todo: true, plusplus: true*/
2
+ /*globals define: true, MutationObserver: false, requestAnimationFrame: false, performance: false, btoa: false*/
3
+ 'use strict';
4
+
5
+ import isPrintableKeyEvent from 'is-printable-key-event';
6
+ import { isSupportedHtml, parseData, deduceColTypeFromData } from './util';
7
+
8
+ export default function (self) {
9
+ var wheeling;
10
+ self.stopPropagation = function (e) {
11
+ e.stopPropagation();
12
+ };
13
+ /**
14
+ * Adds an event listener to the given event.
15
+ * @memberof canvasDatagrid
16
+ * @name addEventListener
17
+ * @method
18
+ * @param {string} ev The name of the event to subscribe to.
19
+ * @param {function} fn The event procedure to execute when the event is raised.
20
+ */
21
+ self.addEventListener = function (ev, fn) {
22
+ self.events[ev] = self.events[ev] || [];
23
+ self.events[ev].unshift(fn);
24
+ };
25
+ /**
26
+ * Removes the given listener function from the given event. Must be an actual reference to the function that was bound.
27
+ * @memberof canvasDatagrid
28
+ * @name removeEventListener
29
+ * @method
30
+ * @param {string} ev The name of the event to unsubscribe from.
31
+ * @param {function} fn The event procedure to execute when the event is raised.
32
+ */
33
+ self.removeEventListener = function (ev, fn) {
34
+ (self.events[ev] || []).forEach(function removeEachListener(sfn, idx) {
35
+ if (fn === sfn) {
36
+ self.events[ev].splice(idx, 1);
37
+ }
38
+ });
39
+ };
40
+ /**
41
+ * Fires the given event, passing an event object to the event subscribers.
42
+ * @memberof canvasDatagrid
43
+ * @name dispatchEvent
44
+ * @method
45
+ * @param {number} ev The name of the event to dispatch.
46
+ * @param {number} e The event object.
47
+ */
48
+ self.dispatchEvent = function (ev, e) {
49
+ e = ev.type ? ev : e || {};
50
+ ev = ev.type || ev;
51
+ var defaultPrevented;
52
+ function preventDefault() {
53
+ defaultPrevented = true;
54
+ }
55
+ if (!self.events[ev]) {
56
+ return;
57
+ }
58
+ self.events[ev].forEach(function dispatchEachEvent(fn) {
59
+ e.ctx = self.ctx;
60
+ e.preventDefault = preventDefault;
61
+ fn.apply(self.intf, [e]);
62
+ });
63
+ return defaultPrevented;
64
+ };
65
+ self.getRatio = function () {
66
+ return Math.min(
67
+ self.attributes.maxPixelRatio,
68
+ (window.devicePixelRatio || 1) /
69
+ (self.ctx.webkitBackingStorePixelRatio ||
70
+ self.ctx.mozBackingStorePixelRatio ||
71
+ self.ctx.msBackingStorePixelRatio ||
72
+ self.ctx.oBackingStorePixelRatio ||
73
+ self.ctx.backingStorePixelRatio ||
74
+ 1),
75
+ );
76
+ };
77
+ /**
78
+ * @returns {number} dataWidth
79
+ */
80
+ self.refreshScrollCacheX = function () {
81
+ const s = self.getSchema();
82
+ self.scrollCache.x = [];
83
+
84
+ /** @type {number} it will be used in `reduceSchema` only */
85
+ let frozenWidth = 0;
86
+
87
+ const collapsedColumnGroups = self.getCollapsedColumnGroups();
88
+ const isColumnCollapsed = (columnIndex) =>
89
+ collapsedColumnGroups.findIndex(
90
+ (group) => columnIndex >= group.from && columnIndex <= group.to,
91
+ ) >= 0;
92
+
93
+ const dataWidth =
94
+ s.reduce(function reduceSchema(accumulator, column, columnIndex) {
95
+ // intentional redefintion of column. This causes scrollCache to be in the correct order
96
+ const schemaIndex = self.orders.columns[columnIndex];
97
+ const columnWidth = self.getColumnWidth(schemaIndex);
98
+ column = s[schemaIndex];
99
+ if (!column.hidden && !isColumnCollapsed(columnIndex))
100
+ accumulator += columnWidth;
101
+ if (columnIndex < self.frozenColumn) {
102
+ self.scrollCache.x[columnIndex] = accumulator;
103
+ frozenWidth = accumulator;
104
+ } else {
105
+ self.scrollCache.x[columnIndex] = Math.max(
106
+ frozenWidth + columnWidth,
107
+ accumulator,
108
+ );
109
+ }
110
+ return accumulator;
111
+ }, 0) || 0;
112
+ return dataWidth;
113
+ };
114
+ self.resize = function (drawAfterResize) {
115
+ if (!self.canvas) {
116
+ return;
117
+ }
118
+ var x,
119
+ v = {
120
+ x: 0,
121
+ y: 0,
122
+ height: 0,
123
+ width: 0,
124
+ style: 'vertical-scroll-bar',
125
+ },
126
+ n = {
127
+ x: 0,
128
+ y: 0,
129
+ height: 0,
130
+ width: 0,
131
+ style: 'horizontal-scroll-bar',
132
+ },
133
+ vb = {
134
+ x: 0,
135
+ y: 0,
136
+ height: 0,
137
+ width: 0,
138
+ style: 'vertical-scroll-box',
139
+ },
140
+ nb = {
141
+ x: 0,
142
+ y: 0,
143
+ height: 0,
144
+ width: 0,
145
+ style: 'horizontal-scroll-box',
146
+ },
147
+ co = {
148
+ x: 0,
149
+ y: 0,
150
+ height: 0,
151
+ width: 0,
152
+ isCorner: true,
153
+ isScrollBoxCorner: true,
154
+ style: 'scroll-box-corner',
155
+ },
156
+ m = self.style.scrollBarBoxMargin * 2,
157
+ b = self.style.scrollBarBorderWidth * 2,
158
+ d = self.style.scrollBarBoxMargin * 0.5,
159
+ sbw = self.style.scrollBarWidth + self.style.scrollBarBorderWidth * 2,
160
+ ratio = self.getRatio(),
161
+ bm = self.style.gridBorderCollapse === 'collapse' ? 1 : 2,
162
+ cellBorder = self.style.cellBorderWidth * bm,
163
+ columnHeaderCellBorder = self.style.columnHeaderCellBorderWidth * bm,
164
+ dataHeight = 0,
165
+ dataWidth = 0,
166
+ dims,
167
+ l = (self.viewData || []).length,
168
+ columnHeaderCellHeight = self.getColumnHeaderCellHeight(),
169
+ rowHeaderCellWidth = self.getRowHeaderCellWidth(),
170
+ topGroupAreaHeight = self.getColumnGroupAreaHeight(),
171
+ leftGroupAreaWidth = self.getRowGroupAreaWidth(),
172
+ ch = self.style.cellHeight,
173
+ containerSpace = self.isChildGrid ? {} : self.measureContainerSpace();
174
+ function isAutoSize(value) {
175
+ return value === undefined || value === 'auto' || value === '';
176
+ }
177
+ function checkScrollBoxVisibility() {
178
+ // an auto-sized grid shows a scroll bar only when it could not grow to
179
+ // its content (container, viewport or canvas limit); a child grid is
180
+ // always bounded by the tree row or cell that holds it
181
+ var constrained = self.autoSizeConstrained || {};
182
+ self.scrollBox.horizontalBarVisible =
183
+ ((!isAutoSize(self.style.width) || constrained.width) &&
184
+ dataWidth > self.scrollBox.width &&
185
+ self.style.overflowX !== 'hidden') ||
186
+ self.style.overflowX === 'scroll';
187
+ self.scrollBox.horizontalBoxVisible = dataWidth > self.scrollBox.width;
188
+ self.scrollBox.verticalBarVisible =
189
+ ((!isAutoSize(self.style.height) || constrained.height) &&
190
+ dataHeight > self.scrollBox.height &&
191
+ self.style.overflowY !== 'hidden') ||
192
+ self.style.overflowY === 'scroll';
193
+ self.scrollBox.verticalBoxVisible = dataHeight > self.scrollBox.height;
194
+ }
195
+ function setScrollBoxSize() {
196
+ self.scrollBox.width =
197
+ self.width - rowHeaderCellWidth - leftGroupAreaWidth;
198
+ self.scrollBox.height =
199
+ self.height - columnHeaderCellHeight - topGroupAreaHeight;
200
+ }
201
+ // sizes the DOM canvas element and reads back the size the grid got
202
+ function setCanvasSize() {
203
+ if (self.isChildGrid) {
204
+ // a child grid fills the tree row or cell that holds it
205
+ self.autoSizeConstrained = { width: true, height: true };
206
+ self.width = self.parentNode.offsetWidth;
207
+ self.height = self.parentNode.offsetHeight;
208
+ return;
209
+ }
210
+ dims = {
211
+ // HACK +1 ? maybe it's a magic cell border? Required to line up properly in auto height mode.
212
+ height:
213
+ columnHeaderCellHeight +
214
+ topGroupAreaHeight +
215
+ dataHeight +
216
+ cellBorder +
217
+ 1,
218
+ width: dataWidth + rowHeaderCellWidth + cellBorder + leftGroupAreaWidth,
219
+ };
220
+ var maxCanvasSize = self.attributes.maxCanvasSize;
221
+ self.autoSizeConstrained = { width: false, height: false };
222
+ ['width', 'height'].forEach(function (dim) {
223
+ var styleIsAuto = isAutoSize(self.style[dim]),
224
+ inlineIsAuto = isAutoSize(self.appliedInlineStyles[dim]),
225
+ size;
226
+ //TODO: support inherit
227
+ if (styleIsAuto && inlineIsAuto) {
228
+ // No explicit size: fill the container when it has a size of its
229
+ // own in this dimension, otherwise fit the content but never grow
230
+ // past the viewport. Browsers also refuse to paint canvases beyond
231
+ // roughly 16k px per side (#254), so cap the element there too and
232
+ // let the grid scroll for the remainder.
233
+ size = dims[dim];
234
+ if (containerSpace[dim] !== undefined) {
235
+ size = containerSpace[dim];
236
+ } else {
237
+ size = Math.min(
238
+ size,
239
+ dim === 'height' ? window.innerHeight : window.innerWidth,
240
+ );
241
+ }
242
+ size = Math.max(0, Math.min(size, maxCanvasSize));
243
+ self.autoSizeConstrained[dim] = size < dims[dim];
244
+ self.parentNodeStyle[dim] = size + 'px';
245
+ } else if (!styleIsAuto && !inlineIsAuto) {
246
+ self.parentNodeStyle[dim] = self.style[dim];
247
+ }
248
+ });
249
+ self.width = self.canvas.offsetWidth;
250
+ self.height = self.canvas.offsetHeight;
251
+ self.canvasOffsetLeft = self.args.canvasOffsetLeft || 0;
252
+ self.canvasOffsetTop = self.args.canvasOffsetTop || 0;
253
+ }
254
+ self.autoLastColumnWidth = undefined;
255
+ dataWidth = self.refreshScrollCacheX();
256
+ self.scrollCache.y = [];
257
+ for (x = 0; x < l; x += 1) {
258
+ self.scrollCache.y[x] = dataHeight;
259
+ dataHeight +=
260
+ ((self.sizes.rows[x] || ch) + (self.sizes.trees[x] || 0)) * self.scale +
261
+ // HACK? if an expanded tree row is frozen it is necessary to add the tree row's height a second time.
262
+ (self.frozenRow > x ? self.sizes.trees[x] || 0 : 0);
263
+ }
264
+ if (l > 1) {
265
+ self.scrollCache.y[x] = dataHeight;
266
+ }
267
+ if (self.attributes.showNewRow) {
268
+ dataHeight += ch;
269
+ }
270
+ if (self.attributes.snapToRow) {
271
+ dataHeight += self.style.cellHeight;
272
+ }
273
+ setCanvasSize();
274
+ /// calculate scroll bar dimensions
275
+ // non-controversial
276
+ self.scrollBox.top =
277
+ columnHeaderCellHeight + topGroupAreaHeight + columnHeaderCellBorder;
278
+ self.scrollBox.left = rowHeaderCellWidth + leftGroupAreaWidth;
279
+ // width and height of scroll box
280
+ setScrollBoxSize();
281
+ // is the data larger than the scroll box
282
+ checkScrollBoxVisibility();
283
+ // if the scroll box is visible, make room for it by expanding the size of the element
284
+ // if the other dimension is set to auto
285
+ if (self.scrollBox.horizontalBarVisible) {
286
+ dataHeight += sbw;
287
+ setCanvasSize();
288
+ setScrollBoxSize();
289
+ checkScrollBoxVisibility();
290
+ }
291
+ if (self.scrollBox.verticalBarVisible) {
292
+ dataWidth += sbw;
293
+ setCanvasSize();
294
+ setScrollBoxSize();
295
+ checkScrollBoxVisibility();
296
+ }
297
+ // set again after bar visibility checks
298
+ setScrollBoxSize();
299
+ if (self.attributes.fillLastColumn) {
300
+ const lastColumnIndex = self.getLastVisibleColumnIndex();
301
+ const availableWidth =
302
+ self.scrollBox.width -
303
+ (self.scrollBox.verticalBarVisible ? sbw : 0) -
304
+ cellBorder;
305
+ if (lastColumnIndex >= 0 && dataWidth < availableWidth) {
306
+ self.autoLastColumnWidth = {
307
+ index: lastColumnIndex,
308
+ width:
309
+ self.getColumnWidth(lastColumnIndex) + availableWidth - dataWidth,
310
+ };
311
+ dataWidth = self.refreshScrollCacheX();
312
+ checkScrollBoxVisibility();
313
+ }
314
+ }
315
+ self.scrollBox.scrollWidth = dataWidth - self.scrollBox.width;
316
+ self.scrollBox.scrollHeight = dataHeight - self.scrollBox.height;
317
+ if (self.frozenColumn > 0) {
318
+ self.scrollBox.widthBoxRatio =
319
+ (self.scrollBox.width - self.scrollCache.x[self.frozenColumn - 1]) /
320
+ dataWidth;
321
+ } else {
322
+ self.scrollBox.widthBoxRatio = self.scrollBox.width / dataWidth;
323
+ }
324
+ self.scrollBox.scrollBoxWidth =
325
+ self.scrollBox.width * self.scrollBox.widthBoxRatio -
326
+ self.style.scrollBarWidth -
327
+ b -
328
+ d;
329
+ // TODO: This heightBoxRatio number is terribly wrong.
330
+ // They should be a result of the size of the grid/canvas?
331
+ // it being off causes the scroll bar to "slide" under
332
+ // the dragged mouse.
333
+ // https://github.com/TonyGermaneri/canvas-datagrid/issues/97
334
+ self.scrollBox.heightBoxRatio =
335
+ (self.scrollBox.height -
336
+ columnHeaderCellHeight -
337
+ topGroupAreaHeight -
338
+ self.scrollCache.y[self.frozenRow]) /
339
+ dataHeight;
340
+ self.scrollBox.scrollBoxHeight =
341
+ self.scrollBox.height * self.scrollBox.heightBoxRatio -
342
+ self.style.scrollBarWidth -
343
+ b -
344
+ d;
345
+ self.scrollBox.scrollBoxWidth = Math.max(
346
+ self.scrollBox.scrollBoxWidth,
347
+ self.style.scrollBarBoxMinSize,
348
+ );
349
+ self.scrollBox.scrollBoxHeight = Math.max(
350
+ self.scrollBox.scrollBoxHeight,
351
+ self.style.scrollBarBoxMinSize,
352
+ );
353
+ // horizontal
354
+ n.x += rowHeaderCellWidth;
355
+ n.y += self.height - self.style.scrollBarWidth - d - topGroupAreaHeight;
356
+ n.width =
357
+ self.width -
358
+ self.style.scrollBarWidth -
359
+ rowHeaderCellWidth -
360
+ leftGroupAreaWidth -
361
+ d -
362
+ m;
363
+ n.height = self.style.scrollBarWidth + self.style.scrollBarBorderWidth + d;
364
+ // horizontal box
365
+ nb.y = n.y + self.style.scrollBarBoxMargin;
366
+ nb.width = self.scrollBox.scrollBoxWidth;
367
+ nb.height = self.style.scrollBarBoxWidth;
368
+ // vertical
369
+ v.x +=
370
+ self.width -
371
+ leftGroupAreaWidth -
372
+ self.style.scrollBarWidth -
373
+ self.style.scrollBarBorderWidth -
374
+ d;
375
+ v.y += columnHeaderCellHeight + self.scrollCache.y[self.frozenRow];
376
+ v.width = self.style.scrollBarWidth + self.style.scrollBarBorderWidth + d;
377
+ v.height =
378
+ self.height -
379
+ columnHeaderCellHeight -
380
+ topGroupAreaHeight -
381
+ self.style.scrollBarWidth -
382
+ d -
383
+ m;
384
+ // vertical box
385
+ vb.x = v.x + self.style.scrollBarBoxMargin;
386
+ vb.y += self.scrollCache.y[self.frozenRow];
387
+ vb.width = self.style.scrollBarBoxWidth;
388
+ vb.height = self.scrollBox.scrollBoxHeight;
389
+ // corner
390
+ co.x = n.x + n.width + m;
391
+ co.y = v.y + v.height + m;
392
+ co.width = self.style.scrollBarWidth + self.style.scrollBarBorderWidth;
393
+ co.height = self.style.scrollBarWidth + self.style.scrollBarBorderWidth;
394
+ self.scrollBox.entities = {
395
+ horizontalBar: n,
396
+ horizontalBox: nb,
397
+ verticalBar: v,
398
+ verticalBox: vb,
399
+ corner: co,
400
+ };
401
+ self.scrollBox.bar = {
402
+ v: v,
403
+ h: n,
404
+ };
405
+ self.scrollBox.box = {
406
+ v: vb,
407
+ h: nb,
408
+ };
409
+ /// calculate page and dom elements
410
+ self.page = Math.max(
411
+ 1,
412
+ self.visibleRows.length - 3 - self.attributes.pageUpDownOverlap,
413
+ );
414
+ // set canvas drawing related items
415
+ if (!self.isChildGrid) {
416
+ const newWidth = self.width * ratio;
417
+ const newHeight = self.height * ratio;
418
+ // We need to check is settings size to canvas necessary,
419
+ // because settings the canvas'size will cause the canvas and its state be cleared
420
+ // even if the size is the same.
421
+ // Notes: Please don't call `self.resize()` without a subsequent call to `self.draw()`
422
+ if (self.canvas.width !== newWidth || self.canvas.height !== newHeight) {
423
+ self.canvas.width = newWidth;
424
+ self.canvas.height = newHeight;
425
+ self.ctx.scale(ratio, ratio);
426
+ }
427
+ }
428
+ // resize any open dom elements (input/textarea)
429
+ self.resizeEditInput();
430
+ self.scroll(true);
431
+ if (drawAfterResize) {
432
+ self.draw(true);
433
+ }
434
+ self.dispatchEvent('resize', {});
435
+ return true;
436
+ };
437
+ self.scroll = function (dontDraw) {
438
+ var s = self.getSchema(),
439
+ l = (self.viewData || []).length,
440
+ ch = self.style.cellHeight;
441
+ // go too far in leaps, then get focused
442
+ self.scrollIndexTop = Math.floor(
443
+ l * (self.scrollBox.scrollTop / self.scrollBox.scrollHeight) - 100,
444
+ );
445
+ self.scrollIndexTop = Math.max(self.scrollIndexTop, 0);
446
+ self.scrollPixelTop = self.scrollCache.y[self.scrollIndexTop];
447
+ // sometimes the grid is rendered but the height is zero
448
+ if (self.scrollBox.scrollHeight === 0) {
449
+ self.scrollIndexTop = 0;
450
+ }
451
+ self.scrollPixelTop = 0;
452
+ self.scrollIndexLeft = self.frozenColumn;
453
+ self.scrollPixelLeft = 0;
454
+ while (
455
+ self.scrollPixelTop < self.scrollBox.scrollTop &&
456
+ self.scrollIndexTop < self.viewData.length
457
+ ) {
458
+ // start on index +1 since index 0 was used in "go too far" section above
459
+ self.scrollIndexTop += 1;
460
+ self.scrollPixelTop = self.scrollCache.y[self.scrollIndexTop];
461
+ }
462
+ while (
463
+ self.scrollPixelLeft < self.scrollBox.scrollLeft + 1 &&
464
+ self.scrollIndexLeft < s.length
465
+ ) {
466
+ self.scrollPixelLeft = self.scrollCache.x[self.scrollIndexLeft];
467
+ self.scrollIndexLeft += 1;
468
+ }
469
+ if (s.length > 0) {
470
+ self.scrollIndexLeft = Math.max(self.scrollIndexLeft - 1, 0);
471
+ self.scrollPixelLeft -= self.getColumnWidth(
472
+ self.orders.columns[self.scrollIndexLeft],
473
+ );
474
+ }
475
+ if ((self.viewData || []).length > 0) {
476
+ self.scrollIndexTop = Math.max(self.scrollIndexTop - 1, 0);
477
+ self.scrollPixelTop = Math.max(
478
+ self.scrollPixelTop -
479
+ (self.viewData[self.scrollIndexTop]
480
+ ? (self.sizes.rows[self.scrollIndexTop] || ch) +
481
+ (self.sizes.trees[self.scrollIndexTop] || 0)
482
+ : ch) *
483
+ self.scale,
484
+ 0,
485
+ );
486
+ }
487
+ self.ellipsisCache = {};
488
+ if (!dontDraw) {
489
+ self.draw(true);
490
+ }
491
+ //TODO: figure out why this has to be delayed for child grids
492
+ //BUG: wheeling event on 3rd level hierarchy fails to move input box
493
+ requestAnimationFrame(self.resizeEditInput);
494
+ self.dispatchEvent('scroll', {
495
+ top: self.scrollBox.scrollTop,
496
+ left: self.scrollBox.scrollLeft,
497
+ });
498
+ };
499
+ self.mousemove = function (e, overridePos) {
500
+ if (self.contextMenu || self.input) {
501
+ return;
502
+ }
503
+
504
+ // Cancel dragging action if user ventures outside grid
505
+ if (self.draggingItem && e.which === 0) {
506
+ self.stopFreezeMove(e);
507
+ self.mouseup(e);
508
+ return;
509
+ }
510
+
511
+ self.mouse = overridePos || self.getLayerPos(e);
512
+ var ctrl =
513
+ (e.ctrlKey || e.metaKey || self.attributes.persistantSelectionMode) &&
514
+ !self.attributes.singleSelectionMode,
515
+ i,
516
+ s = self.getSchema(),
517
+ dragBounds,
518
+ sBounds,
519
+ x = self.mouse.x,
520
+ y = self.mouse.y,
521
+ cell = self.getCellAt(x, y),
522
+ delta,
523
+ disallowVerticalAutoScroll = false,
524
+ disallowHorizontalAutoScroll = false,
525
+ ev = { NativeEvent: e, cell: cell, x: x, y: y },
526
+ previousCell = self.currentCell;
527
+ clearTimeout(self.scrollTimer);
528
+ if (!self.isInGrid({ x: x, y: y })) {
529
+ self.hasFocus = false;
530
+ }
531
+ if (self.dispatchEvent('mousemove', ev)) {
532
+ return;
533
+ }
534
+ if (cell && self.currentCell) {
535
+ self.rowBoundaryCrossed = self.currentCell.rowIndex !== cell.rowIndex;
536
+ self.columnBoundaryCrossed =
537
+ self.currentCell.columnIndex !== cell.columnIndex;
538
+ self.cellBoundaryCrossed =
539
+ self.rowBoundaryCrossed || self.columnBoundaryCrossed;
540
+ ['row', 'column', 'cell'].forEach(function (prefix) {
541
+ if (self[prefix + 'BoundaryCrossed']) {
542
+ ev.cell = previousCell;
543
+ self.dispatchEvent(prefix + 'mouseout', ev);
544
+ ev.cell = cell;
545
+ self.dispatchEvent(prefix + 'mouseover', ev);
546
+ }
547
+ });
548
+ }
549
+ self.currentCell = cell;
550
+
551
+ if (
552
+ !self.draggingItem && // It is not in dragging mode (avoid changing hovers frequent)
553
+ cell &&
554
+ (cell.context === 'cell' || cell.context === self.cursorGrab)
555
+ ) {
556
+ const indicator = self.getUnhideIndicator(self.mouse.x, self.mouse.y);
557
+ if (indicator) {
558
+ self.cursor = 'pointer';
559
+ self.hovers = { unhideIndicator: indicator };
560
+ self.draw();
561
+ return;
562
+ }
563
+ }
564
+
565
+ self.hovers = {};
566
+ if (!self.draggingItem && cell) {
567
+ self.dragItem = cell;
568
+ self.dragMode = cell.dragContext;
569
+ self.cursor = cell.context;
570
+ if (cell.context === 'cell') {
571
+ self.cursor = 'default';
572
+ self.hovers = {
573
+ rowIndex: cell.rowIndex,
574
+ columnIndex: cell.columnIndex,
575
+ onFilterButton: false,
576
+ onCellTreeIcon: false,
577
+ };
578
+ if (
579
+ cell.isFilterable &&
580
+ x >
581
+ cell.x +
582
+ cell.width +
583
+ self.canvasOffsetLeft -
584
+ self.style.filterButtonWidth &&
585
+ x < cell.x + cell.width + self.canvasOffsetLeft &&
586
+ y >
587
+ cell.y +
588
+ cell.height +
589
+ self.canvasOffsetTop -
590
+ self.style.filterButtonHeight &&
591
+ y < cell.y + cell.height + self.canvasOffsetTop
592
+ ) {
593
+ self.hovers.onFilterButton = true;
594
+ self.draw();
595
+ }
596
+ if (cell.isRowTree || cell.isColumnTree) {
597
+ const pc = cell.isRowTree
598
+ ? self.cellTree.rows[cell.rowIndex].parentCount
599
+ : 0;
600
+ const rc = self.style.cellTreeIconWidth * self.scale,
601
+ rx =
602
+ cell.x +
603
+ cell.paddingLeft +
604
+ self.canvasOffsetLeft +
605
+ self.style.cellTreeIconMarginLeft +
606
+ pc * (rc + cell.paddingLeft),
607
+ ry =
608
+ cell.y +
609
+ self.canvasOffsetTop +
610
+ self.style.cellTreeIconMarginTop * self.scale;
611
+ if (x >= rx && x <= rx + rc && y >= ry && y < ry + rc) {
612
+ self.hovers.onCellTreeIcon = true;
613
+ self.draw();
614
+ }
615
+ }
616
+ }
617
+ if (self.selecting || self.reorderObject) {
618
+ delta = {
619
+ x: Math.abs(self.dragStart.x - x),
620
+ y: Math.abs(self.dragStart.y - y),
621
+ };
622
+ if (
623
+ self.dragStartObject.columnIndex !== -1 &&
624
+ e.shiftKey &&
625
+ !self.attributes.singleSelectionMode
626
+ ) {
627
+ self.dragStartObject = {
628
+ rowIndex: self.activeCell.rowIndex,
629
+ columnIndex: self.activeCell.columnIndex,
630
+ };
631
+ }
632
+ dragBounds = {
633
+ top: Math.min(self.dragStartObject.rowIndex, cell.rowIndex),
634
+ left: Math.min(self.dragStartObject.columnIndex, cell.columnIndex),
635
+ bottom: Math.max(self.dragStartObject.rowIndex, cell.rowIndex),
636
+ right: Math.max(self.dragStartObject.columnIndex, cell.columnIndex),
637
+ };
638
+ if (self.dragStartObject.columnIndex === -1) {
639
+ sBounds = self.getSelectionBounds();
640
+ dragBounds.left = -1;
641
+ dragBounds.right = s.length - 1;
642
+ dragBounds.top = Math.min(sBounds.top, cell.rowIndex);
643
+ dragBounds.bottom = Math.max(sBounds.bottom, cell.rowIndex);
644
+ if (dragBounds.top < 0) dragBounds.top = 0;
645
+ }
646
+
647
+ if (self.dragStartObject.rowIndex === -1) {
648
+ sBounds = self.getSelectionBounds();
649
+ dragBounds.left =
650
+ cell.columnIndex === undefined
651
+ ? sBounds.left
652
+ : Math.min(sBounds.left, cell.columnIndex);
653
+ dragBounds.right =
654
+ cell.columnIndex === undefined
655
+ ? sBounds.right
656
+ : Math.max(sBounds.right, cell.columnIndex);
657
+ dragBounds.top = -1;
658
+ dragBounds.bottom = self.viewData.length - 1;
659
+ if (dragBounds.left < 0) dragBounds.left = 0;
660
+ if (dragBounds.left != dragBounds.right)
661
+ self.isMultiColumnsSelected = true;
662
+ else self.isMultiRowsSelected = false;
663
+ }
664
+
665
+ if (
666
+ self.dragStartObject.rowIndex !== cell.rowIndex ||
667
+ self.dragStartObject.columnIndex !== cell.columnIndex
668
+ ) {
669
+ self.ignoreNextClick = true;
670
+ }
671
+ if (
672
+ self.cellBoundaryCrossed ||
673
+ (delta.x === 0 && delta.y === 0) ||
674
+ self.attributes.selectionMode === 'row'
675
+ ) {
676
+ if (
677
+ cell.rowIndex !== undefined &&
678
+ (self.attributes.selectionMode === 'row' ||
679
+ self.dragStartObject.columnIndex === -1) &&
680
+ self.rowBoundaryCrossed
681
+ ) {
682
+ if (self.dragStartObject.rowIndex < cell.rowIndex) {
683
+ dragBounds.top = self.dragStartObject.rowIndex;
684
+ dragBounds.bottom = cell.rowIndex;
685
+ } else {
686
+ dragBounds.top = cell.rowIndex;
687
+ dragBounds.bottom = self.dragStartObject.rowIndex;
688
+ }
689
+ } else if (
690
+ cell.rowIndex !== undefined &&
691
+ (self.attributes.selectionMode === 'column' ||
692
+ self.dragStartObject.rowIndex === -1) &&
693
+ self.columnBoundaryCrossed
694
+ ) {
695
+ if (self.dragStartObject.columnIndex < cell.columnIndex) {
696
+ dragBounds.left = self.dragStartObject.columnIndex;
697
+ dragBounds.right = cell.columnIndex;
698
+ } else {
699
+ dragBounds.left = cell.columnIndex;
700
+ dragBounds.right = self.dragStartObject.columnIndex;
701
+ }
702
+ } else if (self.attributes.selectionMode !== 'row') {
703
+ if (cell.hovered && self.hovers.onFilterButton) {
704
+ if (cell.openedFilter) {
705
+ cell.openedFilter = false;
706
+ self.selectedFilterButton = {
707
+ columnIndex: -1,
708
+ rowIndex: -1,
709
+ };
710
+ } else {
711
+ self.selectedFilterButton.rowIndex = cell.rowIndex;
712
+ self.selectedFilterButton.columnIndex = cell.columnIndex;
713
+ self.contextmenuEvent(e, {
714
+ x: cell.x + cell.width - self.style.filterButtonWidth,
715
+ y: cell.y + cell.height,
716
+ rect: { left: 0, top: 0 },
717
+ });
718
+ }
719
+ self.draw();
720
+ return;
721
+ } else if (
722
+ cell.hovered &&
723
+ self.hovers.onCellTreeIcon &&
724
+ e.type == 'mousedown'
725
+ ) {
726
+ self.toggleCollapseTree(cell.rowIndex, cell.columnIndex);
727
+ return;
728
+ } else {
729
+ self.selectedFilterButton = {
730
+ columnIndex: -1,
731
+ rowIndex: -1,
732
+ };
733
+ if (self.hovers.onFilterButton) return;
734
+ if (self.hovers.onCellTreeIcon) return;
735
+ if (!self.dragAddToSelection && cell.rowIndex !== undefined) {
736
+ if (self.isCellSelected(cell)) self.unselectCell(cell);
737
+ } else {
738
+ if (!self.isCellSelected(cell)) self.selectCell(cell);
739
+ }
740
+ }
741
+ }
742
+ }
743
+ if (self.attributes.singleSelectionMode) {
744
+ // only one row (row mode) or one cell may be selected at a time, so
745
+ // a drag follows the pointer instead of growing a range (#472)
746
+ if (
747
+ self.dragStartObject.rowIndex !== -1 &&
748
+ cell.rowIndex !== undefined &&
749
+ cell.rowIndex > -1
750
+ ) {
751
+ dragBounds.top = cell.rowIndex;
752
+ dragBounds.bottom = cell.rowIndex;
753
+ }
754
+ if (
755
+ self.attributes.selectionMode !== 'row' &&
756
+ self.dragStartObject.columnIndex !== -1 &&
757
+ cell.columnIndex !== undefined &&
758
+ cell.columnIndex > -1
759
+ ) {
760
+ dragBounds.left = cell.columnIndex;
761
+ dragBounds.right = cell.columnIndex;
762
+ }
763
+ }
764
+ if (
765
+ (!self.selectionBounds ||
766
+ dragBounds.top !== self.selectionBounds.top ||
767
+ dragBounds.left !== self.selectionBounds.left ||
768
+ dragBounds.bottom !== self.selectionBounds.bottom ||
769
+ dragBounds.right !== self.selectionBounds.right) &&
770
+ !ctrl
771
+ ) {
772
+ if (!(cell.hovered && self.hovers.onFilterButton))
773
+ self.clearSelections();
774
+ if (dragBounds.top === -1) {
775
+ dragBounds.top = 0;
776
+ }
777
+ sBounds = dragBounds;
778
+ if (self.attributes.selectionMode === 'row') {
779
+ for (i = sBounds.top; i <= sBounds.bottom; i += 1) {
780
+ self.selectRow(i, true, null, true);
781
+ }
782
+ } else {
783
+ self.selectArea(sBounds, true);
784
+ self.activeCell.rowIndex = sBounds.top;
785
+ self.activeCell.columnIndex = sBounds.left;
786
+ if (sBounds.left == -1 && sBounds.top !== sBounds.bottom) {
787
+ self.activeCell.columnIndex = 0;
788
+ self.isMultiRowsSelected = true;
789
+ self.isMultiColumnsSelected = false;
790
+ }
791
+ }
792
+ }
793
+ } else if (self.movingSelectionHandle) {
794
+ delta = {
795
+ x: Math.abs(self.dragStart.x - x),
796
+ y: Math.abs(self.dragStart.y - y),
797
+ };
798
+
799
+ // Disallow auto-scroll to the direction that overlay is not
800
+ // moving towards.
801
+ if (self.fillOverlay.direction === 'y') {
802
+ disallowHorizontalAutoScroll = true;
803
+ } else if (self.fillOverlay.direction === 'x') {
804
+ disallowVerticalAutoScroll = true;
805
+ }
806
+ }
807
+
808
+ if (delta) {
809
+ if (
810
+ self.attributes.autoScrollOnMousemove ||
811
+ disallowVerticalAutoScroll ||
812
+ disallowHorizontalAutoScroll
813
+ ) {
814
+ var movedVertically =
815
+ !disallowVerticalAutoScroll &&
816
+ delta.y > self.attributes.autoScrollMargin;
817
+ var movedHorizontally =
818
+ !disallowHorizontalAutoScroll &&
819
+ delta.x > self.attributes.autoScrollMargin;
820
+
821
+ if (movedVertically && !movedHorizontally)
822
+ self.autoScrollZone(e, -1, y, ctrl);
823
+ else if (movedHorizontally && !movedVertically)
824
+ self.autoScrollZone(e, x, -1, ctrl);
825
+ else if (movedHorizontally && movedVertically)
826
+ self.autoScrollZone(e, x, y, ctrl);
827
+ } else {
828
+ self.autoScrollZone(e, x, y, ctrl);
829
+ }
830
+ }
831
+ }
832
+ const columnGroup = self.getColumnGroupAt(self.mouse.x, self.mouse.y);
833
+ if (columnGroup) self.cursor = 'pointer';
834
+
835
+ const rowGroup = self.getRowGroupAt(self.mouse.x, self.mouse.y);
836
+ if (rowGroup) self.cursor = 'pointer';
837
+
838
+ self.cellBoundaryCrossed = false;
839
+ self.rowBoundaryCrossed = false;
840
+ self.columnBoundaryCrossed = false;
841
+ self.draw(true);
842
+ };
843
+ self.click = function (e, overridePos) {
844
+ var i,
845
+ startingBounds = JSON.stringify(self.getSelectionBounds()),
846
+ ctrl =
847
+ (e.ctrlKey || e.metaKey || self.attributes.persistantSelectionMode) &&
848
+ !self.attributes.singleSelectionMode,
849
+ pos = overridePos || self.getLayerPos(e);
850
+ self.currentCell = self.getCellAt(pos.x, pos.y);
851
+ if (self.currentCell.grid !== undefined) {
852
+ return;
853
+ }
854
+ function checkSelectionChange() {
855
+ var ev,
856
+ sb = self.getSelectionBounds();
857
+
858
+ if (startingBounds === JSON.stringify(sb)) {
859
+ return;
860
+ }
861
+ self.dispatchEvent('selectionchanged', self.getContextOfSelectionEvent());
862
+ }
863
+ if (self.input) {
864
+ self.endEdit();
865
+ }
866
+ if (self.ignoreNextClick) {
867
+ self.ignoreNextClick = false;
868
+ return;
869
+ }
870
+ i = self.currentCell;
871
+ if (
872
+ self.dispatchEvent('click', { NativeEvent: e, cell: self.currentCell })
873
+ ) {
874
+ return;
875
+ }
876
+
877
+ const unhideIndicator = self.getUnhideIndicator(pos.x, pos.y);
878
+ if (unhideIndicator) {
879
+ const { dir, orderIndex0, orderIndex1 } = unhideIndicator;
880
+ if (dir === 'l' || dir === 'r')
881
+ self.unhideColumns(orderIndex0, orderIndex1);
882
+ else self.unhideRows(orderIndex0, orderIndex1);
883
+ return;
884
+ }
885
+
886
+ let group = self.getColumnGroupAt(pos.x, pos.y);
887
+ if (!group) group = self.getRowGroupAt(pos.x, pos.y);
888
+ if (group) {
889
+ if (self.toggleGroup(group)) {
890
+ self.setStorageData();
891
+ self.refresh();
892
+ return;
893
+ }
894
+ }
895
+
896
+ if (!self.hasFocus) {
897
+ return;
898
+ }
899
+
900
+ const leftOffset = self.getRowGroupAreaWidth();
901
+ const topOffset = self.getColumnGroupAreaHeight();
902
+ const xInGrid = pos.x - leftOffset;
903
+ const yInGrid = pos.y - topOffset;
904
+ if (
905
+ ['rowHeaderCell', 'columnHeaderCell'].indexOf(self.currentCell.style) ===
906
+ -1 &&
907
+ !ctrl
908
+ ) {
909
+ if (!self.hovers.onFilterButton) {
910
+ self.setActiveCell(i.columnIndex, i.rowIndex);
911
+ }
912
+ }
913
+ if (
914
+ self.currentCell.style === 'columnHeaderCell' &&
915
+ self.attributes.columnHeaderClickBehavior === 'sort' &&
916
+ // a header is also a reorder grab zone when column reordering is on;
917
+ // a plain click (no drag, which sets ignoreNextClick) still sorts (#514)
918
+ (self.currentCell.context === 'cell' ||
919
+ self.currentCell.dragContext === 'column-reorder')
920
+ ) {
921
+ if (self.orderBy === i.header.name) {
922
+ self.orderDirection = self.orderDirection === 'asc' ? 'desc' : 'asc';
923
+ } else {
924
+ self.orderDirection = 'asc';
925
+ }
926
+ self.order(i.header.name, self.orderDirection);
927
+ checkSelectionChange();
928
+ return;
929
+ }
930
+ if (self.currentCell.context === 'cell') {
931
+ if (self.currentCell.style === 'cornerCell') {
932
+ self.selectAll();
933
+ self.draw();
934
+ checkSelectionChange();
935
+ return;
936
+ }
937
+ if (
938
+ self.attributes.selectionMode === 'row' ||
939
+ self.currentCell.style === 'rowHeaderCell'
940
+ ) {
941
+ if (
942
+ self.currentCell.style === 'rowHeaderCell' &&
943
+ self.attributes.tree &&
944
+ xInGrid > 0 &&
945
+ xInGrid - self.currentCell.x <
946
+ self.style.treeArrowWidth +
947
+ self.style.treeArrowMarginLeft +
948
+ self.style.treeArrowMarginRight +
949
+ self.style.treeArrowClickRadius &&
950
+ yInGrid - self.currentCell.y <
951
+ self.style.treeArrowHeight +
952
+ self.style.treeArrowMarginTop +
953
+ self.style.treeArrowClickRadius &&
954
+ yInGrid > 0
955
+ ) {
956
+ self.toggleTree(i.rowIndex);
957
+ return;
958
+ }
959
+ }
960
+ if (e.shiftKey && !ctrl && !self.attributes.singleSelectionMode) {
961
+ self.selectionBounds = self.getSelectionBounds();
962
+ self.selectArea(undefined, false);
963
+ }
964
+ }
965
+ checkSelectionChange();
966
+ self.draw(true);
967
+ };
968
+ self.dragResizeColumn = function (e) {
969
+ const resizingColumn = self.dragMode === 'ew-resize';
970
+ var pos, x, y;
971
+ pos = self.getLayerPos(e);
972
+ x = self.resizingStartingWidth + pos.x - self.dragStart.x;
973
+ y = self.resizingStartingHeight + pos.y - self.dragStart.y;
974
+ if (x < self.style.minColumnWidth) {
975
+ x = self.style.minColumnWidth;
976
+ }
977
+ if (y < self.style.minRowHeight) {
978
+ y = self.style.minRowHeight;
979
+ }
980
+ const resizeEventDetails = {
981
+ x: x,
982
+ y: y,
983
+ width: x,
984
+ height: y,
985
+ columnIndex: resizingColumn ? self.draggingItem.columnIndex : undefined,
986
+ rowIndex: resizingColumn ? undefined : self.draggingItem.rowIndex,
987
+ draggingItem: self.draggingItem,
988
+ NativeEvent: e,
989
+ };
990
+ if (
991
+ resizingColumn
992
+ ? self.dispatchEvent('resizecolumn', resizeEventDetails)
993
+ : self.dispatchResizeRow(resizeEventDetails)
994
+ ) {
995
+ return false;
996
+ }
997
+ if (self.attributes.resizeAfterDragged) {
998
+ self.pendingDragResize = {
999
+ item: self.draggingItem,
1000
+ width: x,
1001
+ height: y,
1002
+ x: e.clientX,
1003
+ y: e.clientY,
1004
+ };
1005
+ } else {
1006
+ self.dragResizeApply(self.draggingItem, x, y);
1007
+ }
1008
+ };
1009
+ self.dragResizeApply = function (draggingItem, width, height) {
1010
+ if (
1011
+ self.scrollBox.scrollLeft >
1012
+ self.scrollBox.scrollWidth - self.attributes.resizeScrollZone &&
1013
+ self.dragMode === 'ew-resize'
1014
+ ) {
1015
+ self.resize(true);
1016
+ }
1017
+ if (self.dragMode === 'ew-resize') {
1018
+ self.sizes.columns[
1019
+ draggingItem.header.style === 'rowHeaderCell'
1020
+ ? 'cornerCell'
1021
+ : draggingItem.sortColumnIndex
1022
+ ] = width;
1023
+ if (
1024
+ ['rowHeaderCell', 'cornerCell'].indexOf(draggingItem.header.style) !==
1025
+ -1
1026
+ ) {
1027
+ self.resize(true);
1028
+ }
1029
+ self.resizeChildGrids();
1030
+ return;
1031
+ } else if (self.dragMode === 'ns-resize') {
1032
+ if (draggingItem.rowOpen) {
1033
+ self.sizes.trees[draggingItem.rowIndex] = height;
1034
+ } else if (self.attributes.globalRowResize) {
1035
+ self.style.cellHeight = height;
1036
+ } else {
1037
+ self.sizes.rows[draggingItem.rowIndex] = height;
1038
+ }
1039
+ self.dispatchResizeRow({
1040
+ height: height,
1041
+ rowIndex: draggingItem.rowIndex,
1042
+ draggingItem: draggingItem,
1043
+ });
1044
+ self.resizeChildGrids();
1045
+ return;
1046
+ }
1047
+ self.ellipsisCache = {};
1048
+ };
1049
+ self.stopDragResize = function (event) {
1050
+ const pos = self.getLayerPos(event);
1051
+
1052
+ if (self.attributes.resizeAfterDragged) {
1053
+ self.dragResizeApply(
1054
+ self.pendingDragResize.item,
1055
+ self.pendingDragResize.width,
1056
+ self.pendingDragResize.height,
1057
+ );
1058
+ self.pendingDragResize = undefined;
1059
+ }
1060
+
1061
+ if (self.dragMode === 'ew-resize') {
1062
+ const hasMoved = !!(pos.x - self.dragStart.x);
1063
+ // Check that dragItem is selected or part of selection.
1064
+ const dragItemIsSelected = self.isColumnSelected(
1065
+ self.dragItem.columnIndex,
1066
+ );
1067
+
1068
+ if (hasMoved && dragItemIsSelected) {
1069
+ const width = Math.max(
1070
+ self.resizingStartingWidth + pos.x - self.dragStart.x,
1071
+ self.style.minColumnWidth,
1072
+ );
1073
+ // If the column is selected, resize it to width plus any other selected columns.
1074
+ self.fitSelectedColumns(width);
1075
+ }
1076
+ } else if (self.dragMode === 'ns-resize') {
1077
+ // Do the above for rows.
1078
+ const hasMoved = !!(pos.y - self.dragStart.y);
1079
+ const dragItemIsSelected = self.isRowSelected(self.dragItem.rowIndex);
1080
+
1081
+ if (hasMoved && dragItemIsSelected) {
1082
+ const height = Math.max(
1083
+ self.resizingStartingHeight + pos.y - self.dragStart.y,
1084
+ self.style.minRowHeight,
1085
+ );
1086
+ self.fitSelectedRows(height);
1087
+ }
1088
+ }
1089
+
1090
+ self.resize();
1091
+ window.removeEventListener('mousemove', self.dragResizeColumn, false);
1092
+ window.removeEventListener('mouseup', self.stopDragResize, false);
1093
+ self.setStorageData();
1094
+ self.draw(true);
1095
+ self.ignoreNextClick = true;
1096
+ };
1097
+ self.scrollGrid = function (e) {
1098
+ var pos = self.getLayerPos(e);
1099
+ if (
1100
+ self.attributes.scrollPointerLock &&
1101
+ self.pointerLockPosition &&
1102
+ ['horizontal-scroll-box', 'vertical-scroll-box'].indexOf(
1103
+ self.scrollStartMode,
1104
+ ) !== -1
1105
+ ) {
1106
+ self.pointerLockPosition.x += e.movementX;
1107
+ self.pointerLockPosition.y += e.movementY;
1108
+ self.pointerLockPosition.x = Math.min(
1109
+ self.width - self.style.scrollBarWidth,
1110
+ Math.max(0, self.pointerLockPosition.x),
1111
+ );
1112
+ self.pointerLockPosition.y = Math.min(
1113
+ self.height - self.style.scrollBarWidth,
1114
+ Math.max(0, self.pointerLockPosition.y),
1115
+ );
1116
+ pos = self.pointerLockPosition;
1117
+ }
1118
+ self.scrollMode = self.getCellAt(pos.x, pos.y).context;
1119
+ if (
1120
+ self.scrollMode === 'horizontal-scroll-box' &&
1121
+ self.scrollStartMode !== 'horizontal-scroll-box'
1122
+ ) {
1123
+ self.scrollStartMode = 'horizontal-scroll-box';
1124
+ self.dragStart = pos;
1125
+ self.scrollStart.left = self.scrollBox.scrollLeft;
1126
+ clearTimeout(self.scrollTimer);
1127
+ return;
1128
+ }
1129
+ if (
1130
+ self.scrollMode === 'vertical-scroll-box' &&
1131
+ self.scrollStartMode !== 'vertical-scroll-box'
1132
+ ) {
1133
+ self.scrollStartMode = 'vertical-scroll-box';
1134
+ self.dragStart = pos;
1135
+ self.scrollStart.top = self.scrollBox.scrollTop;
1136
+ clearTimeout(self.scrollTimer);
1137
+ return;
1138
+ }
1139
+ if (
1140
+ self.scrollStartMode === 'vertical-scroll-box' &&
1141
+ self.scrollMode !== 'vertical-scroll-box'
1142
+ ) {
1143
+ self.scrollMode = 'vertical-scroll-box';
1144
+ }
1145
+ if (
1146
+ self.scrollStartMode === 'horizontal-scroll-box' &&
1147
+ self.scrollMode !== 'horizontal-scroll-box'
1148
+ ) {
1149
+ self.scrollMode = 'horizontal-scroll-box';
1150
+ }
1151
+ clearTimeout(self.scrollTimer);
1152
+ if (self.scrollModes.indexOf(self.scrollMode) === -1) {
1153
+ return;
1154
+ }
1155
+ if (self.scrollMode === 'vertical-scroll-box') {
1156
+ self.scrollBox.scrollTop =
1157
+ self.scrollStart.top +
1158
+ (pos.y - self.dragStart.y) / self.scrollBox.heightBoxRatio;
1159
+ } else if (self.scrollMode === 'vertical-scroll-top') {
1160
+ self.scrollBox.scrollTop -= self.page * self.style.cellHeight;
1161
+ self.scrollTimer = setTimeout(
1162
+ self.scrollGrid,
1163
+ self.attributes.scrollRepeatRate,
1164
+ e,
1165
+ );
1166
+ } else if (self.scrollMode === 'vertical-scroll-bottom') {
1167
+ self.scrollBox.scrollTop += self.page * self.style.cellHeight;
1168
+ self.scrollTimer = setTimeout(
1169
+ self.scrollGrid,
1170
+ self.attributes.scrollRepeatRate,
1171
+ e,
1172
+ );
1173
+ }
1174
+ if (self.scrollMode === 'horizontal-scroll-box') {
1175
+ self.scrollBox.scrollLeft =
1176
+ self.scrollStart.left +
1177
+ (pos.x - self.dragStart.x) / self.scrollBox.widthBoxRatio;
1178
+ } else if (self.scrollMode === 'horizontal-scroll-right') {
1179
+ self.scrollBox.scrollLeft += self.attributes.selectionScrollIncrement;
1180
+ self.scrollTimer = setTimeout(
1181
+ self.scrollGrid,
1182
+ self.attributes.scrollRepeatRate,
1183
+ e,
1184
+ );
1185
+ } else if (self.scrollMode === 'horizontal-scroll-left') {
1186
+ self.scrollBox.scrollLeft -= self.attributes.selectionScrollIncrement;
1187
+ self.scrollTimer = setTimeout(
1188
+ self.scrollGrid,
1189
+ self.attributes.scrollRepeatRate,
1190
+ e,
1191
+ );
1192
+ }
1193
+ };
1194
+ self.stopScrollGrid = function () {
1195
+ clearTimeout(self.scrollTimer);
1196
+ if (document.exitPointerLock) {
1197
+ document.exitPointerLock();
1198
+ }
1199
+ window.removeEventListener('mousemove', self.scrollGrid, false);
1200
+ };
1201
+ self.dragReorder = function (e) {
1202
+ var pos,
1203
+ x,
1204
+ y,
1205
+ columReorder = self.dragMode === 'column-reorder',
1206
+ rowReorder = self.dragMode === 'row-reorder';
1207
+ pos = self.getLayerPos(e);
1208
+ x = pos.x - self.dragStart.x;
1209
+ y = pos.y - self.dragStart.y;
1210
+ if (!self.attributes.allowColumnReordering && columReorder) {
1211
+ return;
1212
+ }
1213
+ if (!self.attributes.allowRowReordering && rowReorder) {
1214
+ return;
1215
+ }
1216
+ if ((e.ctrlKey || e.metaKey || e.shiftKey) && self.reorderObject) {
1217
+ if (self.dragMode === 'column-reorder' && !self.isMultiColumnsSelected) {
1218
+ self.selectColumn(self.draggingItem.header.index, false, false);
1219
+ }
1220
+ }
1221
+ if (
1222
+ self.dispatchEvent('reordering', {
1223
+ NativeEvent: e,
1224
+ source: self.dragStartObject,
1225
+ target: self.currentCell,
1226
+ dragMode: self.dragMode,
1227
+ })
1228
+ ) {
1229
+ return;
1230
+ }
1231
+ if (
1232
+ Math.abs(x) > self.attributes.reorderDeadZone ||
1233
+ Math.abs(y) > self.attributes.reorderDeadZone
1234
+ ) {
1235
+ self.reorderObject = self.draggingItem;
1236
+ if (self.isMultiRowsSelected)
1237
+ self.reorderObject = self.getVisibleCellByIndex(
1238
+ -1,
1239
+ self.activeCell.rowIndex,
1240
+ );
1241
+ if (self.isMultiColumnsSelected)
1242
+ self.reorderObject = self.getVisibleCellByIndex(
1243
+ self.activeCell.columnIndex,
1244
+ -1,
1245
+ );
1246
+ if (!self.reorderObject) return;
1247
+ self.reorderTarget = self.currentCell;
1248
+ self.reorderObject.dragOffset = {
1249
+ x: x,
1250
+ y: y,
1251
+ };
1252
+ self.autoScrollZone(
1253
+ e,
1254
+ columReorder ? pos.x : -1,
1255
+ rowReorder ? pos.y : -1,
1256
+ false,
1257
+ );
1258
+ }
1259
+ };
1260
+ self.stopDragReorder = function (e) {
1261
+ let originalIndex;
1262
+ let targetIndex;
1263
+ const orderLists = {
1264
+ 'row-reorder': self.orders.rows,
1265
+ 'column-reorder': self.orders.columns,
1266
+ };
1267
+ const indexName = {
1268
+ 'row-reorder': 'rowIndex',
1269
+ 'column-reorder': 'sortColumnIndex',
1270
+ }[self.dragMode];
1271
+ window.removeEventListener('mousemove', self.dragReorder, false);
1272
+ window.removeEventListener('mouseup', self.stopDragReorder, false);
1273
+ if (
1274
+ self.reorderObject &&
1275
+ self.reorderTarget &&
1276
+ ((self.dragMode === 'column-reorder' &&
1277
+ self.reorderTarget.sortColumnIndex > -1 &&
1278
+ self.reorderTarget.sortColumnIndex < self.getSchema().length) ||
1279
+ (self.dragMode === 'row-reorder' &&
1280
+ self.reorderTarget.rowIndex > -1 &&
1281
+ self.reorderTarget.rowIndex < self.viewData.length)) &&
1282
+ self.reorderObject[indexName] !== self.reorderTarget[indexName] &&
1283
+ !self.dispatchEvent('reorder', {
1284
+ NativeEvent: e,
1285
+ source: self.reorderObject,
1286
+ target: self.reorderTarget,
1287
+ dragMode: self.dragMode,
1288
+ })
1289
+ ) {
1290
+ self.ignoreNextClick = true;
1291
+ originalIndex = orderLists[self.dragMode].indexOf(
1292
+ self.reorderObject[indexName],
1293
+ );
1294
+ targetIndex = orderLists[self.dragMode].indexOf(
1295
+ self.reorderTarget[indexName],
1296
+ );
1297
+ if (self.dragMode === 'column-reorder') {
1298
+ /** Select column view indexes in the first row */
1299
+ const selectedIndexes = self.getRowSelectionStates(0);
1300
+ const sortColumnIndices = [];
1301
+ const selectedColumnIndices = [];
1302
+ if (selectedIndexes) {
1303
+ originalIndex = selectedIndexes[0];
1304
+ selectedIndexes.forEach(function (value) {
1305
+ sortColumnIndices.push(self.orders.columns[value]);
1306
+ });
1307
+ }
1308
+ const deleteCount = sortColumnIndices.length;
1309
+ if (
1310
+ targetIndex < originalIndex ||
1311
+ (targetIndex > originalIndex &&
1312
+ Math.abs(targetIndex - originalIndex) >= deleteCount)
1313
+ ) {
1314
+ orderLists[self.dragMode].splice(originalIndex, deleteCount);
1315
+ if (targetIndex > originalIndex)
1316
+ targetIndex = targetIndex - (deleteCount - 1);
1317
+
1318
+ for (let i = 0; i < sortColumnIndices.length; i++) {
1319
+ if (i === 0) self.activeCell.columnIndex = targetIndex;
1320
+ selectedColumnIndices.push(targetIndex + i);
1321
+ orderLists[self.dragMode].splice(
1322
+ targetIndex + i,
1323
+ 0,
1324
+ sortColumnIndices[i],
1325
+ );
1326
+ }
1327
+
1328
+ self.orders.columns = orderLists[self.dragMode];
1329
+ self.selectColumnViewIndexes(selectedColumnIndices);
1330
+ }
1331
+ } else {
1332
+ /** The original name of this variable is `odata` */
1333
+ const rowIndexes = self.getRowViewIndexesFromSelection();
1334
+ const originalData = rowIndexes.map(
1335
+ (rowIndex) => self.viewData[rowIndex],
1336
+ );
1337
+ if (
1338
+ targetIndex < originalIndex ||
1339
+ (targetIndex > originalIndex &&
1340
+ Math.abs(targetIndex - originalIndex) >= originalData.length)
1341
+ ) {
1342
+ self.viewData.splice(originalIndex, originalData.length);
1343
+ if (targetIndex > originalIndex)
1344
+ targetIndex = targetIndex - (originalData.length - 1);
1345
+ self.activeCell.rowIndex = targetIndex;
1346
+ for (let i = 0; i < originalData.length; i++)
1347
+ self.viewData.splice(targetIndex + i, 0, originalData[i]);
1348
+ self.moveSelection(0, targetIndex);
1349
+ }
1350
+ }
1351
+ self.resize();
1352
+ self.setStorageData();
1353
+ }
1354
+ self.reorderObject = undefined;
1355
+ self.reorderTarget = undefined;
1356
+ self.draw(true);
1357
+ };
1358
+ self.dragMove = function (e) {
1359
+ if (
1360
+ self.dispatchEvent('moving', { NativeEvent: e, cell: self.currentCell })
1361
+ ) {
1362
+ return;
1363
+ }
1364
+ var pos = self.getLayerPos(e);
1365
+ self.moveOffset = {
1366
+ x: self.currentCell.columnIndex - self.dragStartObject.columnIndex,
1367
+ y: self.currentCell.rowIndex - self.dragStartObject.rowIndex,
1368
+ };
1369
+ if (
1370
+ Math.abs(pos.x) > self.attributes.reorderDeadZone ||
1371
+ Math.abs(pos.y) > self.attributes.reorderDeadZone
1372
+ ) {
1373
+ setTimeout(function () {
1374
+ self.autoScrollZone(e, pos.x, pos.y, false);
1375
+ }, 1);
1376
+ }
1377
+ };
1378
+ self.stopDragMove = function (e) {
1379
+ window.removeEventListener('mousemove', self.dragMove, false);
1380
+ window.removeEventListener('mouseup', self.stopDragMove, false);
1381
+ var b = self.getSelectionBounds();
1382
+ if (
1383
+ self.dispatchEvent('endmove', { NativeEvent: e, cell: self.currentCell })
1384
+ ) {
1385
+ self.movingSelection = undefined;
1386
+ self.moveOffset = undefined;
1387
+ self.draw(true);
1388
+ return;
1389
+ }
1390
+ if (self.moveOffset) {
1391
+ self.moveTo(
1392
+ self.movingSelection,
1393
+ b.left + self.moveOffset.x,
1394
+ b.top + self.moveOffset.y,
1395
+ );
1396
+ self.moveSelection(self.moveOffset.x, self.moveOffset.y);
1397
+ }
1398
+ self.movingSelection = undefined;
1399
+ self.moveOffset = undefined;
1400
+ self.draw(true);
1401
+ };
1402
+ self.freezeMove = function (e) {
1403
+ if (
1404
+ self.dispatchEvent('freezemoving', {
1405
+ NativeEvent: e,
1406
+ cell: self.currentCell,
1407
+ })
1408
+ ) {
1409
+ return;
1410
+ }
1411
+ var pos = self.getLayerPos(e);
1412
+
1413
+ self.ignoreNextClick = true;
1414
+ self.freezeMarkerPosition = pos;
1415
+ pos.x -= self.getRowGroupAreaWidth();
1416
+ pos.y -= self.getColumnGroupAreaHeight();
1417
+ if (
1418
+ Math.abs(pos.x) > self.attributes.reorderDeadZone ||
1419
+ Math.abs(pos.y) > self.attributes.reorderDeadZone
1420
+ ) {
1421
+ setTimeout(function () {
1422
+ self.autoScrollZone(e, pos.x, pos.y, false);
1423
+ }, 1);
1424
+ }
1425
+ };
1426
+ self.stopFreezeMove = function (e) {
1427
+ let pos = self.getLayerPos(e),
1428
+ bm = self.style.gridBorderCollapse === 'collapse' ? 1 : 2,
1429
+ columnHeaderCellBorder = self.style.columnHeaderCellBorderWidth * bm,
1430
+ columnHeaderCellHeight = self.getColumnHeaderCellHeight(),
1431
+ rowHeaderCellWidth = self.getRowHeaderCellWidth();
1432
+ pos.x -= self.getRowGroupAreaWidth();
1433
+ pos.y -= self.getColumnGroupAreaHeight();
1434
+
1435
+ if (
1436
+ self.currentCell &&
1437
+ self.currentCell.rowIndex !== undefined &&
1438
+ self.dragMode === 'frozen-row-marker'
1439
+ ) {
1440
+ self.scrollBox.scrollTop = 0;
1441
+ self.frozenRow = self.currentCell.rowIndex + 1;
1442
+ self.scrollBox.bar.v.y =
1443
+ columnHeaderCellHeight +
1444
+ columnHeaderCellBorder +
1445
+ self.scrollCache.y[self.frozenRow];
1446
+ self.scrollBox.box.v.y =
1447
+ columnHeaderCellHeight +
1448
+ columnHeaderCellBorder +
1449
+ self.scrollCache.y[self.frozenRow];
1450
+ var dataHeight = self.scrollCache.y[self.scrollCache.y.length - 1];
1451
+ self.scrollBox.heightBoxRatio =
1452
+ (self.scrollBox.height -
1453
+ columnHeaderCellHeight -
1454
+ self.scrollCache.y[self.frozenRow]) /
1455
+ dataHeight;
1456
+ self.scrollBox.scrollBoxHeight =
1457
+ self.scrollBox.height * self.scrollBox.heightBoxRatio -
1458
+ self.style.scrollBarWidth;
1459
+ self.scrollBox.scrollBoxHeight = Math.max(
1460
+ self.scrollBox.scrollBoxHeight,
1461
+ self.style.scrollBarBoxMinSize,
1462
+ );
1463
+ self.scrollBox.box.v.height = self.scrollBox.scrollBoxHeight;
1464
+ }
1465
+ if (
1466
+ self.currentCell &&
1467
+ self.currentCell.columnIndex !== undefined &&
1468
+ self.dragMode === 'frozen-column-marker'
1469
+ ) {
1470
+ const dataWidth = self.refreshScrollCacheX();
1471
+ self.scrollBox.scrollLeft = 0;
1472
+ let x =
1473
+ self.currentCell.x -
1474
+ self.style.frozenMarkerWidth -
1475
+ self.style.frozenMarkerBorderWidth;
1476
+ if (pos.x > x + self.currentCell.width / 2)
1477
+ self.frozenColumn = self.currentCell.columnIndex + 1;
1478
+ else if (self.currentCell.columnIndex >= 0)
1479
+ self.frozenColumn = self.currentCell.columnIndex;
1480
+ self.scrollBox.bar.h.x =
1481
+ rowHeaderCellWidth + self.scrollCache.x[self.frozenColumn];
1482
+ self.scrollBox.widthBoxRatio =
1483
+ (self.scrollBox.width - self.scrollCache.x[self.frozenColumn]) /
1484
+ dataWidth;
1485
+ self.scrollBox.scrollBoxWidth =
1486
+ self.scrollBox.width * self.scrollBox.widthBoxRatio -
1487
+ self.style.scrollBarWidth;
1488
+ self.scrollBox.scrollBoxWidth = Math.max(
1489
+ self.scrollBox.scrollBoxWidth,
1490
+ self.style.scrollBarBoxMinSize,
1491
+ );
1492
+ self.scrollBox.box.h.width = self.scrollBox.scrollBoxWidth;
1493
+ }
1494
+ if (
1495
+ Math.abs(pos.x) > self.attributes.reorderDeadZone ||
1496
+ Math.abs(pos.y) > self.attributes.reorderDeadZone
1497
+ ) {
1498
+ setTimeout(function () {
1499
+ self.autoScrollZone(e, pos.x, pos.y, false);
1500
+ }, 1);
1501
+ }
1502
+
1503
+ window.removeEventListener('mousemove', self.freezeMove, false);
1504
+ window.removeEventListener('mouseup', self.stopFreezeMove, false);
1505
+ self.freezeMarkerPosition = undefined;
1506
+ if (
1507
+ self.dispatchEvent('endfreezemove', {
1508
+ NativeEvent: e,
1509
+ cell: self.currentCell,
1510
+ })
1511
+ ) {
1512
+ self.frozenRow = self.startFreezeMove.x;
1513
+ self.frozenColumn = self.startFreezeMove.y;
1514
+ self.draw(true);
1515
+ return;
1516
+ }
1517
+ self.draw(true);
1518
+ self.resize();
1519
+ };
1520
+ self.mousedown = function (e, overridePos) {
1521
+ self.lastMouseDownTarget = e.target;
1522
+ if (
1523
+ self.dispatchEvent('mousedown', {
1524
+ NativeEvent: e,
1525
+ cell: self.currentCell,
1526
+ })
1527
+ ) {
1528
+ return;
1529
+ }
1530
+ if (!self.hasFocus) {
1531
+ return;
1532
+ }
1533
+ if (e.button === 2 || self.input) {
1534
+ return;
1535
+ }
1536
+ var ctrl = (e.ctrlKey || e.metaKey) && !self.attributes.singleSelectionMode,
1537
+ shift = e.shiftKey && !self.attributes.singleSelectionMode,
1538
+ move = /-move/.test(self.dragMode),
1539
+ freeze = /frozen-row-marker|frozen-column-marker/.test(self.dragMode),
1540
+ resize = /-resize/.test(self.dragMode),
1541
+ selectionHandleMove = /selection-handle-br/.test(self.dragMode);
1542
+ const onUnhideIndicator = self.hovers && self.hovers.unhideIndicator;
1543
+ self.dragStart = overridePos || self.getLayerPos(e);
1544
+ self.scrollStart = {
1545
+ left: self.scrollBox.scrollLeft,
1546
+ top: self.scrollBox.scrollTop,
1547
+ };
1548
+ self.dragStartObject = self.getCellAt(self.dragStart.x, self.dragStart.y);
1549
+ self.dragAddToSelection = !self.dragStartObject.selected;
1550
+ if (
1551
+ !ctrl &&
1552
+ !shift &&
1553
+ !/(vertical|horizontal)-scroll-(bar|box)/.test(
1554
+ self.dragStartObject.context,
1555
+ ) &&
1556
+ self.currentCell &&
1557
+ !self.currentCell.isColumnHeader &&
1558
+ !move &&
1559
+ !freeze &&
1560
+ !resize &&
1561
+ !selectionHandleMove
1562
+ ) {
1563
+ if (
1564
+ !(self.dragMode == 'row-reorder' && self.isMultiRowsSelected) &&
1565
+ !(self.currentCell.hovered && self.hovers.onFilterButton)
1566
+ ) {
1567
+ self.clearSelections();
1568
+ }
1569
+ }
1570
+ if (self.dragStartObject.isGrid) {
1571
+ return;
1572
+ }
1573
+ if (
1574
+ self.scrollModes.indexOf(self.dragStartObject.context) !== -1 &&
1575
+ !onUnhideIndicator
1576
+ ) {
1577
+ self.scrollMode = self.dragStartObject.context;
1578
+ self.scrollStartMode = self.dragStartObject.context;
1579
+ self.scrollGrid(e);
1580
+ if (
1581
+ self.attributes.scrollPointerLock &&
1582
+ ['horizontal-scroll-box', 'vertical-scroll-box'].indexOf(
1583
+ self.scrollStartMode,
1584
+ ) !== -1
1585
+ ) {
1586
+ self.pointerLockPosition = {
1587
+ x: self.dragStart.x,
1588
+ y: self.dragStart.y,
1589
+ };
1590
+ self.canvas.requestPointerLock();
1591
+ }
1592
+ window.addEventListener('mousemove', self.scrollGrid, false);
1593
+ window.addEventListener('mouseup', self.stopScrollGrid, false);
1594
+ self.ignoreNextClick = true;
1595
+ return;
1596
+ }
1597
+ if (self.dragMode === 'cell') {
1598
+ self.selecting = true;
1599
+ if (
1600
+ (self.attributes.selectionMode === 'row' ||
1601
+ self.dragStartObject.columnIndex === -1) &&
1602
+ self.dragStartObject.rowIndex > -1
1603
+ ) {
1604
+ self.selectRow(self.dragStartObject.rowIndex, ctrl, null);
1605
+ } else if (
1606
+ (self.attributes.selectionMode === 'column' ||
1607
+ self.dragStartObject.rowIndex === -1) &&
1608
+ self.dragStartObject.columnIndex > -1
1609
+ ) {
1610
+ if (self.attributes.allowColumnSelection) {
1611
+ self.selectColumn(self.currentCell.header.index, ctrl, shift);
1612
+ }
1613
+ return;
1614
+ }
1615
+ if (self.attributes.selectionMode !== 'row') {
1616
+ self.mousemove(e);
1617
+ }
1618
+ return;
1619
+ }
1620
+ if (selectionHandleMove && self.attributes.editable) {
1621
+ self.movingSelectionHandle = true;
1622
+ self.fillOverlay = {
1623
+ handle: {
1624
+ x: self.dragStartObject.x + self.dragStartObject.width / 2,
1625
+ y: self.dragStartObject.y + self.dragStartObject.height / 2,
1626
+ },
1627
+ snapTo: { x: -1, y: -1 },
1628
+ selection: self.getSelectionBounds(),
1629
+ };
1630
+ if (self.dispatchEvent('beginselectionhandlemove', { NativeEvent: e })) {
1631
+ return;
1632
+ }
1633
+ window.addEventListener('mousemove', self.selectionHandleMove, false);
1634
+ window.addEventListener('mouseup', self.stopSelectionHandleMove, false);
1635
+ return self.selectionHandleMove(e);
1636
+ }
1637
+ if (move) {
1638
+ self.draggingItem = self.dragItem;
1639
+ self.movingSelection = self.cloneSelections();
1640
+ self.dragging = self.dragStartObject;
1641
+ if (
1642
+ self.dispatchEvent('beginmove', {
1643
+ NativeEvent: e,
1644
+ cell: self.currentCell,
1645
+ })
1646
+ ) {
1647
+ return;
1648
+ }
1649
+ window.addEventListener('mousemove', self.dragMove, false);
1650
+ window.addEventListener('mouseup', self.stopDragMove, false);
1651
+ return self.mousemove(e);
1652
+ }
1653
+ if (freeze) {
1654
+ self.draggingItem = self.dragItem;
1655
+ self.startFreezeMove = {
1656
+ x: self.frozenRow,
1657
+ y: self.frozenColumn,
1658
+ };
1659
+ if (self.dispatchEvent('beginfreezemove', { NativeEvent: e })) {
1660
+ return;
1661
+ }
1662
+
1663
+ self.freezeMarkerPosition = self.getLayerPos(e);
1664
+ self.freezeMarkerPosition.isGrab = true;
1665
+
1666
+ window.addEventListener('mousemove', self.freezeMove, false);
1667
+ window.addEventListener('mouseup', self.stopFreezeMove, false);
1668
+ return self.mousemove(e);
1669
+ }
1670
+ if (resize && !onUnhideIndicator) {
1671
+ self.draggingItem = self.dragItem;
1672
+ if (self.draggingItem.rowOpen) {
1673
+ self.resizingStartingHeight =
1674
+ self.sizes.trees[self.draggingItem.rowIndex];
1675
+ } else {
1676
+ self.resizingStartingHeight =
1677
+ self.sizes.rows[self.draggingItem.rowIndex] || self.style.cellHeight;
1678
+ }
1679
+ self.resizingStartingWidth =
1680
+ self.sizes.columns[
1681
+ self.draggingItem.header.style === 'rowHeaderCell'
1682
+ ? 'cornerCell'
1683
+ : self.draggingItem.sortColumnIndex
1684
+ ] || self.draggingItem.width;
1685
+ window.addEventListener('mousemove', self.dragResizeColumn, false);
1686
+ window.addEventListener('mouseup', self.stopDragResize, false);
1687
+ return;
1688
+ }
1689
+ if (['row-reorder', 'column-reorder'].indexOf(self.dragMode) !== -1) {
1690
+ self.draggingItem = self.dragStartObject;
1691
+ if (
1692
+ self.dragMode === 'column-reorder' &&
1693
+ !self.isMultiColumnsSelected &&
1694
+ self.attributes.allowColumnSelection
1695
+ ) {
1696
+ self.selectColumn(self.currentCell.header.index, ctrl, shift);
1697
+ } else if (self.dragMode === 'row-reorder' && !self.isMultiRowsSelected) {
1698
+ self.selectRow(self.dragStartObject.rowIndex, ctrl, null);
1699
+ }
1700
+ window.addEventListener('mousemove', self.dragReorder, false);
1701
+ window.addEventListener('mouseup', self.stopDragReorder, false);
1702
+ return;
1703
+ }
1704
+ };
1705
+ /**
1706
+ * A mouseup anywhere ends a selection drag. Only the canvas receives the
1707
+ * full mouseup handler, so releasing the button outside the grid used to
1708
+ * leave it in "selecting" mode and the next mousemove kept extending the
1709
+ * selection.
1710
+ */
1711
+ self.mouseupOutsideGrid = function (e) {
1712
+ if (e.target === self.canvas) {
1713
+ return; // handled by mouseup
1714
+ }
1715
+ self.selecting = undefined;
1716
+ self.cellBoundaryCrossed = true;
1717
+ self.rowBoundaryCrossed = true;
1718
+ self.columnBoundaryCrossed = true;
1719
+ };
1720
+ self.mouseup = function (e) {
1721
+ clearTimeout(self.scrollTimer);
1722
+ self.cellBoundaryCrossed = true;
1723
+ self.rowBoundaryCrossed = true;
1724
+ self.columnBoundaryCrossed = true;
1725
+ self.selecting = undefined;
1726
+ self.draggingItem = undefined;
1727
+ self.dragStartObject = undefined;
1728
+ if (
1729
+ self.dispatchEvent('mouseup', { NativeEvent: e, cell: self.currentCell })
1730
+ ) {
1731
+ return;
1732
+ }
1733
+ if (!self.hasFocus && e.target !== self.canvas) {
1734
+ return;
1735
+ }
1736
+ if (self.currentCell && self.currentCell.grid !== undefined) {
1737
+ return;
1738
+ }
1739
+ if (self.contextMenu || self.input) {
1740
+ return;
1741
+ }
1742
+ if (self.dragStart && self.isInGrid(self.dragStart)) {
1743
+ self.controlInput.focus();
1744
+ }
1745
+ e.preventDefault();
1746
+ };
1747
+ // gets the horizontal adjacent cells as well as first/last based on column visibility
1748
+ self.getAdjacentCells = function () {
1749
+ var x,
1750
+ i,
1751
+ s = self.getSchema(),
1752
+ o = {};
1753
+ for (x = 0; x < s.length; x += 1) {
1754
+ i = self.orders.columns[x];
1755
+ if (!s[i].hidden) {
1756
+ if (o.first === undefined) {
1757
+ o.first = x;
1758
+ o.left = x;
1759
+ }
1760
+ o.last = x;
1761
+ if (x > self.activeCell.columnIndex && o.right === undefined) {
1762
+ o.right = x;
1763
+ }
1764
+ if (x < self.activeCell.columnIndex) {
1765
+ o.left = x;
1766
+ }
1767
+ }
1768
+ }
1769
+ if (o.right === undefined) {
1770
+ o.right = o.last;
1771
+ }
1772
+ return o;
1773
+ };
1774
+ self.keydown = function (e) {
1775
+ var i,
1776
+ ev,
1777
+ adjacentCells = self.getAdjacentCells(),
1778
+ x = Math.max(self.activeCell.columnIndex, 0),
1779
+ y = Math.max(self.activeCell.rowIndex, 0),
1780
+ ctrl = e.ctrlKey || e.metaKey,
1781
+ last = self.viewData.length - 1,
1782
+ s = self.getSchema(),
1783
+ cols = s.length - 1;
1784
+
1785
+ var defaultPrevented = self.dispatchEvent('keydown', {
1786
+ NativeEvent: e,
1787
+ cell: self.currentCell,
1788
+ });
1789
+
1790
+ if (defaultPrevented) {
1791
+ return;
1792
+ }
1793
+
1794
+ if (!self.attributes.keepFocusOnMouseOut && !self.hasFocus) {
1795
+ return;
1796
+ }
1797
+
1798
+ // If a user starts typing content, switch to "Enter" mode
1799
+ if (isPrintableKeyEvent(e) && !ctrl) {
1800
+ return self.beginEditAt(x, y, e, true);
1801
+ }
1802
+
1803
+ if (self.attributes.showNewRow) {
1804
+ last += 1;
1805
+ }
1806
+
1807
+ if (e.key === 'Tab') {
1808
+ e.preventDefault();
1809
+ }
1810
+
1811
+ if (e.key === 'Escape') {
1812
+ self.selectNone();
1813
+ } else if (ctrl && e.key === 'a') {
1814
+ self.selectAll();
1815
+ } else if (['Backspace', 'Delete'].includes(e.key)) {
1816
+ // read-only grids must not lose data on Delete/Backspace (#587, #458)
1817
+ if (self.attributes.editable) {
1818
+ self.deleteSelectedData();
1819
+ }
1820
+ } else if (e.key === 'ArrowDown') {
1821
+ y += 1;
1822
+ } else if (e.key === 'ArrowUp') {
1823
+ y -= 1;
1824
+ } else if (
1825
+ (e.key === 'ArrowLeft' && !ctrl) ||
1826
+ (e.shiftKey && e.key === 'Tab')
1827
+ ) {
1828
+ x = adjacentCells.left;
1829
+ } else if (
1830
+ (e.key === 'ArrowRight' && !ctrl) ||
1831
+ (!e.shiftKey && e.key === 'Tab')
1832
+ ) {
1833
+ x = adjacentCells.right;
1834
+ } else if (e.key === 'PageUp') {
1835
+ y -= self.page;
1836
+ e.preventDefault();
1837
+ } else if (e.key === 'PageDown') {
1838
+ y += self.page;
1839
+ e.preventDefault();
1840
+ } else if (e.key === 'Home' || (ctrl && e.key === 'ArrowUp')) {
1841
+ y = 0;
1842
+ } else if (e.key === 'End' || (ctrl && e.key === 'ArrowDown')) {
1843
+ y = self.viewData.length - 1;
1844
+ } else if (ctrl && e.key === 'ArrowRight') {
1845
+ x = adjacentCells.last;
1846
+ } else if (ctrl && e.key === 'ArrowLeft') {
1847
+ x = adjacentCells.first;
1848
+ }
1849
+
1850
+ if (e.key === 'Enter') {
1851
+ e.preventDefault();
1852
+ return self.beginEditAt(x, y, e);
1853
+ }
1854
+ if (x < 0 || Number.isNaN(x)) {
1855
+ x = adjacentCells.first;
1856
+ }
1857
+ if (y > last) {
1858
+ y = last;
1859
+ }
1860
+ if (y < 0 || Number.isNaN(y)) {
1861
+ y = 0;
1862
+ }
1863
+ if (x > cols) {
1864
+ x = adjacentCells.last;
1865
+ }
1866
+
1867
+ // TODO - most likely some column order related bugs in key based selection
1868
+ // Arrows
1869
+ const isArrowKey = [
1870
+ 'ArrowLeft',
1871
+ 'ArrowUp',
1872
+ 'ArrowRight',
1873
+ 'ArrowDown',
1874
+ ].includes(e.key);
1875
+
1876
+ // Shrinking and expanding selection using shift and arrow keys
1877
+ if (e.shiftKey && isArrowKey && !self.attributes.singleSelectionMode) {
1878
+ const changed = self.shrinkOrExpandSelections(
1879
+ { rowIndex: y, columnIndex: x },
1880
+ e,
1881
+ true,
1882
+ );
1883
+ if (changed) self.draw(true);
1884
+ }
1885
+
1886
+ if (x !== self.activeCell.columnIndex || y !== self.activeCell.rowIndex) {
1887
+ self.scrollIntoView(
1888
+ x !== self.activeCell.columnIndex ? x : undefined,
1889
+ y !== self.activeCell.rowIndex && !Number.isNaN(y) ? y : undefined,
1890
+ );
1891
+
1892
+ self.setActiveCell(x, y);
1893
+ if (!e.shiftKey && self.attributes.selectionFollowsActiveCell) {
1894
+ if (!ctrl) self.clearSelections();
1895
+ self.selectCell({ rowIndex: y, viewColumnIndex: x });
1896
+ }
1897
+ self.draw(true);
1898
+ }
1899
+ };
1900
+ self.keyup = function (e) {
1901
+ if (
1902
+ self.dispatchEvent('keyup', { NativeEvent: e, cell: self.currentCell })
1903
+ ) {
1904
+ return;
1905
+ }
1906
+ if (!self.hasFocus) {
1907
+ return;
1908
+ }
1909
+ };
1910
+ self.keypress = function (e) {
1911
+ if (!self.hasFocus) {
1912
+ return;
1913
+ }
1914
+ if (
1915
+ self.dispatchEvent('keypress', { NativeEvent: e, cell: self.currentCell })
1916
+ ) {
1917
+ return;
1918
+ }
1919
+ };
1920
+ self.dblclick = function (e) {
1921
+ if (
1922
+ self.dispatchEvent('dblclick', { NativeEvent: e, cell: self.currentCell })
1923
+ ) {
1924
+ return;
1925
+ }
1926
+ if (!self.hasFocus) {
1927
+ return;
1928
+ }
1929
+ if (
1930
+ self.currentCell.context === 'ew-resize' &&
1931
+ self.currentCell.style === 'columnHeaderCell'
1932
+ ) {
1933
+ // Check that double-clicked cell is selected or part of selection.
1934
+ const currentCellIsSelected = self.isColumnSelected(
1935
+ self.currentCell.columnIndex,
1936
+ );
1937
+
1938
+ if (currentCellIsSelected) {
1939
+ // There might be more
1940
+ self.fitSelectedColumns();
1941
+ } else {
1942
+ self.fitColumnToValues(self.currentCell.header.name);
1943
+ }
1944
+ } else if (
1945
+ self.currentCell.context === 'ew-resize' &&
1946
+ self.currentCell.style === 'cornerCell'
1947
+ ) {
1948
+ self.autosize();
1949
+ } else if (
1950
+ ['cell', 'activeCell'].includes(self.currentCell.style) &&
1951
+ !self.hovers.onFilterButton &&
1952
+ !self.hovers.onCellTreeIcon
1953
+ ) {
1954
+ if (self.currentCell.isRowTree || self.currentCell.isColumnTree) {
1955
+ self.cellTreeExpandCollapse(
1956
+ self.currentCell.rowIndex,
1957
+ self.currentCell.columnIndex,
1958
+ );
1959
+ self.draw();
1960
+ } else {
1961
+ self.beginEditAt(
1962
+ self.currentCell.columnIndex,
1963
+ self.currentCell.rowIndex,
1964
+ );
1965
+ }
1966
+ }
1967
+ };
1968
+ self.scrollWheel = function (e) {
1969
+ var l,
1970
+ t,
1971
+ ev = e,
1972
+ childEvent,
1973
+ deltaX = e.deltaX === undefined ? e.NativeEvent.deltaX : e.deltaX,
1974
+ deltaY = e.deltaY === undefined ? e.NativeEvent.deltaY : e.deltaY,
1975
+ deltaMode =
1976
+ e.deltaMode === undefined ? e.NativeEvent.deltaMode : e.deltaMode;
1977
+ if (e.NativeEvent) e = e.NativeEvent;
1978
+ if (self.disposed) {
1979
+ return;
1980
+ }
1981
+ // A child grid receives the wheel through its parent's `wheel` grid
1982
+ // event (`ev`), not from the DOM. Cancelling and marking that event tells
1983
+ // every ancestor that the grid under the pointer owns this wheel, so only
1984
+ // the hovered grid scrolls, even when it has nothing left to scroll.
1985
+ function claim() {
1986
+ if (ev !== e) {
1987
+ ev.claimedByChildGrid = true;
1988
+ ev.preventDefault();
1989
+ }
1990
+ }
1991
+ if (wheeling) {
1992
+ if (ev === e) {
1993
+ e.preventDefault();
1994
+ } else {
1995
+ claim();
1996
+ }
1997
+ return;
1998
+ }
1999
+ if (self.hasFocus) {
2000
+ claim();
2001
+ }
2002
+ childEvent = { NativeEvent: e };
2003
+ if (self.dispatchEvent('wheel', childEvent)) {
2004
+ if (childEvent.claimedByChildGrid) {
2005
+ claim();
2006
+ }
2007
+ return;
2008
+ }
2009
+ self.touchHaltAnimation = true;
2010
+ l = self.scrollBox.scrollLeft;
2011
+ t = self.scrollBox.scrollTop;
2012
+ if (self.hasFocus) {
2013
+ //BUG Issue 42: https://github.com/TonyGermaneri/canvas-datagrid/issues/42
2014
+ //https://stackoverflow.com/questions/20110224/what-is-the-height-of-a-line-in-a-wheel-event-deltamode-dom-delta-line
2015
+ if (deltaMode === 1) {
2016
+ // line mode = 17 pixels per line
2017
+ deltaY = deltaY * 17;
2018
+ }
2019
+ if (
2020
+ (self.scrollBox.scrollTop < self.scrollBox.scrollHeight &&
2021
+ deltaY > 0) ||
2022
+ (self.scrollBox.scrollLeft < self.scrollBox.scrollWidth &&
2023
+ deltaX > 0) ||
2024
+ (self.scrollBox.scrollTop > 0 && deltaY < 0) ||
2025
+ (self.scrollBox.scrollLeft > 0 && deltaX < 0)
2026
+ ) {
2027
+ ev.preventDefault(e);
2028
+ }
2029
+ wheeling = setTimeout(function () {
2030
+ wheeling = undefined;
2031
+ self.scrollBox.scrollTo(deltaX + l, deltaY + t);
2032
+ }, 1);
2033
+ }
2034
+ };
2035
+ self.pasteData = function (
2036
+ pasteValue,
2037
+ mimeType,
2038
+ startRowIndex,
2039
+ startColIndex,
2040
+ minRowsLength = 0,
2041
+ minColumnsLength = 0,
2042
+ ) {
2043
+ if (mimeType === 'text/html' && !isSupportedHtml(pasteValue)) {
2044
+ console.warn(
2045
+ 'Unrecognized HTML format. HTML must be a simple table, e.g.: <table><tr><td>data</td></tr></table>.',
2046
+ );
2047
+ console.warn(
2048
+ 'Data with the mime type text/html not in this format will not be imported as row data.',
2049
+ );
2050
+
2051
+ return;
2052
+ }
2053
+
2054
+ const rows = parseData(pasteValue, mimeType);
2055
+ const columnsLength = rows[0].length;
2056
+
2057
+ // selected cell. This mimics Excel's paste functionality, and works
2058
+ // as a poor-man's fill-down.
2059
+ if (
2060
+ rows.length === 1 &&
2061
+ columnsLength === 1 &&
2062
+ minRowsLength <= 1 &&
2063
+ minColumnsLength <= 1
2064
+ ) {
2065
+ var cellData = rows[0][0].value.map((item) => item.value).join();
2066
+
2067
+ self.forEachSelectedCell(function (data, rowIndex, colName) {
2068
+ data[rowIndex][colName] = cellData;
2069
+ });
2070
+ } else {
2071
+ let direction = null;
2072
+
2073
+ if (minRowsLength > rows.length && minColumnsLength > columnsLength) {
2074
+ direction = 'both';
2075
+ } else if (minRowsLength > rows.length) {
2076
+ direction = 'vertical';
2077
+ } else if (minColumnsLength > columnsLength) {
2078
+ direction = 'horizontal';
2079
+ }
2080
+
2081
+ self.insert({
2082
+ rows: rows,
2083
+ startRowIndex: startRowIndex,
2084
+ startColumnIndex: startColIndex,
2085
+ minRowsLength: minRowsLength,
2086
+ minColumnsLength: minColumnsLength,
2087
+ reverseRows: false,
2088
+ reverseColumns: false,
2089
+ clearSelections: true,
2090
+ alwaysFilling: false,
2091
+ direction: direction,
2092
+ });
2093
+ }
2094
+
2095
+ // selections is a sparse array, so we condense:
2096
+ const affectedCells = [];
2097
+ self.forEachSelectedCell((viewData, viewRowIndex, columnName, cell) => {
2098
+ affectedCells.push([
2099
+ viewRowIndex,
2100
+ cell.viewColumnIndex,
2101
+ cell.boundRowIndex,
2102
+ cell.boundColumnIndex,
2103
+ // the pasted value, so listeners need not look it up (#549)
2104
+ viewData[viewRowIndex] ? viewData[viewRowIndex][columnName] : undefined,
2105
+ ]);
2106
+ });
2107
+
2108
+ self.dispatchEvent('afterpaste', {
2109
+ cells: affectedCells,
2110
+ });
2111
+ self.dispatchDataChanged('paste', { cells: affectedCells });
2112
+
2113
+ return rows.length;
2114
+ };
2115
+ /**
2116
+ * Grows the data set and the schema so that `insert` can write every pasted
2117
+ * cell, adding all missing rows and columns in one pass with a single
2118
+ * refresh instead of calling `addRow`/`addColumn` per cell.
2119
+ * @param {Array} rows Parsed clipboard rows (see `parseData`).
2120
+ * @param {number} requiredRowCount Number of rows the grid needs to have.
2121
+ * @param {number} requiredColumnCount Number of columns the grid needs to have.
2122
+ */
2123
+ self.expandGridForInsert = function (
2124
+ rows,
2125
+ requiredRowCount,
2126
+ requiredColumnCount,
2127
+ ) {
2128
+ const schema = self.getSchema();
2129
+ let changed = false;
2130
+ const missingColumns = requiredColumnCount - schema.length;
2131
+ if (missingColumns > 0) {
2132
+ const lastColumn = schema[self.orders.columns[schema.length - 1]] || {};
2133
+ for (let i = 0; i < missingColumns; i += 1) {
2134
+ const column = {
2135
+ name: `col${schema.length + 1}:${Date.now()}${i}`,
2136
+ type: deduceColTypeFromData(rows, i),
2137
+ title: ' ',
2138
+ width: lastColumn.width,
2139
+ };
2140
+ self.validateColumn(column, schema);
2141
+ schema.push(column);
2142
+ self.originalData.forEach(function (row, rowIndex) {
2143
+ self.applyDefaultValue(row, column, rowIndex);
2144
+ });
2145
+ }
2146
+ self.intf.schema = schema;
2147
+ changed = true;
2148
+ }
2149
+ const missingRows = requiredRowCount - self.originalData.length;
2150
+ if (missingRows > 0) {
2151
+ for (let i = 0; i < missingRows; i += 1) {
2152
+ const row = {};
2153
+ self.originalData.push(row);
2154
+ self.getSchema().forEach(function (c) {
2155
+ self.applyDefaultValue(row, c, self.originalData.length - 1);
2156
+ });
2157
+ }
2158
+ changed = true;
2159
+ }
2160
+ if (changed) {
2161
+ // setFilter re-applies filters and sorting and calls refresh() once
2162
+ self.setFilter();
2163
+ self.resize(true);
2164
+ }
2165
+ return changed;
2166
+ };
2167
+ self.insert = function ({
2168
+ rows = [],
2169
+ startRowIndex = 0,
2170
+ startColumnIndex = 0,
2171
+ minRowsLength = 0,
2172
+ minColumnsLength = 0,
2173
+ reverseRows = false,
2174
+ reverseColumns = false,
2175
+ clearSelections = false,
2176
+ alwaysFilling = false,
2177
+ direction = 'both',
2178
+ }) {
2179
+ const rowsLength = Math.max(rows.length, minRowsLength);
2180
+ const fillCellCallback = self.fillCellCallback;
2181
+ const filledCells = [];
2182
+
2183
+ if (self.attributes.allowGridExpandOnPaste) {
2184
+ self.expandGridForInsert(
2185
+ rows,
2186
+ startRowIndex + rowsLength,
2187
+ startColumnIndex +
2188
+ Math.max(minColumnsLength, ...rows.map((cells) => cells.length)),
2189
+ );
2190
+ }
2191
+
2192
+ if (clearSelections) self.selections = [];
2193
+
2194
+ for (
2195
+ let rowPosReal = 0, rowDataPos = 0;
2196
+ rowPosReal < rowsLength;
2197
+ rowPosReal++, rowDataPos++
2198
+ ) {
2199
+ if (rowDataPos >= rows.length) {
2200
+ rowDataPos = 0;
2201
+ }
2202
+
2203
+ const fillingRow = rowPosReal >= rows.length;
2204
+ const rowPosition = reverseRows
2205
+ ? rowsLength - rowPosReal - 1
2206
+ : rowPosReal;
2207
+ // Rows may have been moved by user, so get the actual row index
2208
+ // (instead of the row index at which the row is rendered):
2209
+ if (self.originalData[startRowIndex + rowPosition] === undefined) {
2210
+ console.warn('Paste data exceeded grid bounds. Skipping.');
2211
+ break;
2212
+ }
2213
+ const realRowIndex = self.orders.rows[startRowIndex + rowPosition];
2214
+
2215
+ const cells = rows[rowDataPos];
2216
+ const cellsLength = Math.max(cells.length, minColumnsLength);
2217
+
2218
+ const existingRowData = self.viewData[realRowIndex];
2219
+ const newRowData = Object.assign({}, existingRowData);
2220
+ const fillArgs = fillCellCallback
2221
+ ? {
2222
+ rows: rows,
2223
+ direction: direction,
2224
+ rowData: newRowData,
2225
+ existingRowData: existingRowData,
2226
+ rowIndex: realRowIndex,
2227
+ rowOffset: rowDataPos,
2228
+ cells: cells,
2229
+ reversed: direction === 'horizontal' ? reverseColumns : reverseRows,
2230
+ isFillingRow: fillingRow || alwaysFilling,
2231
+ fillingRowPosition: alwaysFilling
2232
+ ? rowPosReal
2233
+ : fillingRow
2234
+ ? rowPosReal - rows.length
2235
+ : -1,
2236
+ fillingRowLength: alwaysFilling
2237
+ ? rowsLength
2238
+ : fillingRow
2239
+ ? rowsLength - rows.length
2240
+ : -1,
2241
+ }
2242
+ : undefined;
2243
+
2244
+ for (
2245
+ let colPosReal = 0, cellDataPos = 0;
2246
+ colPosReal < cellsLength;
2247
+ colPosReal++, cellDataPos++
2248
+ ) {
2249
+ if (cellDataPos >= cells.length) {
2250
+ cellDataPos = 0;
2251
+ }
2252
+
2253
+ const fillingColumn = colPosReal >= cells.length;
2254
+ const colPosition = reverseColumns
2255
+ ? cellsLength - colPosReal - 1
2256
+ : colPosReal;
2257
+ const columnIndex = startColumnIndex + colPosition;
2258
+ if (!self.getSchema()[columnIndex]) {
2259
+ console.warn('Paste data exceeded grid bounds. Skipping.');
2260
+ continue;
2261
+ }
2262
+ const column = self.getSchema()[self.orders.columns[columnIndex]];
2263
+ const columnName = column.name;
2264
+ let cellData = cells[cellDataPos];
2265
+ if (cellData && cellData.value) {
2266
+ cellData = cellData.value.map((item) => item.value).join('');
2267
+ }
2268
+
2269
+ const existingCellData = existingRowData[columnName];
2270
+
2271
+ if (
2272
+ fillCellCallback &&
2273
+ (fillingColumn || fillingRow || alwaysFilling)
2274
+ ) {
2275
+ newRowData[columnName] = fillCellCallback({
2276
+ ...fillArgs,
2277
+ column: column,
2278
+ columnIndex: columnIndex,
2279
+ columnOffset: cellDataPos,
2280
+ newCellData: cellData,
2281
+ existingCellData: existingCellData,
2282
+ isFillingColumn: fillingColumn || alwaysFilling,
2283
+ fillingColumnPosition: alwaysFilling
2284
+ ? colPosReal
2285
+ : fillingColumn
2286
+ ? colPosReal - cells.length
2287
+ : -1,
2288
+ fillingColumnLength: alwaysFilling
2289
+ ? cellsLength
2290
+ : fillingColumn
2291
+ ? cellsLength - cells.length
2292
+ : -1,
2293
+ });
2294
+ } else {
2295
+ newRowData[columnName] =
2296
+ cellData === undefined || cellData === null
2297
+ ? existingCellData
2298
+ : cellData;
2299
+ }
2300
+
2301
+ self.selectCell(
2302
+ { rowIndex: realRowIndex, viewColumnIndex: columnIndex },
2303
+ true,
2304
+ );
2305
+
2306
+ if (alwaysFilling || fillingRow || fillingColumn) {
2307
+ filledCells.push([
2308
+ realRowIndex,
2309
+ columnIndex,
2310
+ self.getBoundRowIndexFromViewRowIndex(realRowIndex),
2311
+ self.getBoundColumnIndexFromViewColumnIndex(columnIndex),
2312
+ ]);
2313
+ }
2314
+ }
2315
+
2316
+ self.originalData[self.boundRowIndexMap.get(realRowIndex)] = newRowData;
2317
+ // Update view date here to avoid a full refresh of `viewData`.
2318
+ // To stay in line with Excel and Google Sheet behaviour,
2319
+ // don't perform a full refresh (and filter/sort results)
2320
+ // as this would make any pasted values disappear and/or suddenly change position.
2321
+ self.viewData[realRowIndex] = newRowData;
2322
+ }
2323
+
2324
+ if (filledCells.length > 0 || alwaysFilling) {
2325
+ self.dispatchEvent('afterfill', {
2326
+ filledCells: filledCells,
2327
+ });
2328
+ }
2329
+ };
2330
+ self.getNextVisibleColumnIndex = function (visibleColumnIndex) {
2331
+ var x,
2332
+ s = self.getVisibleSchema();
2333
+ for (x = 0; x < s.length; x += 1) {
2334
+ if (s[x].columnIndex === visibleColumnIndex) {
2335
+ return s[x + 1].columnIndex;
2336
+ }
2337
+ }
2338
+ return -1;
2339
+ };
2340
+ self.getVisibleColumnIndexOf = function (columnIndex) {
2341
+ var x,
2342
+ s = self.getVisibleSchema();
2343
+ for (x = 0; x < s.length; x += 1) {
2344
+ if (s[x].columnIndex === columnIndex) {
2345
+ return x;
2346
+ }
2347
+ }
2348
+ return -1;
2349
+ };
2350
+ self.getSelectionIndex = function () {
2351
+ const bounds = self.getSelectionBounds(true);
2352
+ if (!bounds) return;
2353
+ const { top, bottom } = bounds;
2354
+ for (let rowIndex = top; rowIndex <= bottom; rowIndex++) {
2355
+ const row = self.getRowSelectionStates(rowIndex);
2356
+ if (row) {
2357
+ if (row[0] === undefined) break;
2358
+
2359
+ return {
2360
+ row: rowIndex,
2361
+ column: row[0] < 0 ? row[1] : row[0],
2362
+ rowLength: bottom - rowIndex + 1,
2363
+ columnLength: row.length - (row[0] < 0 ? 1 : 0),
2364
+ };
2365
+ }
2366
+ }
2367
+
2368
+ return null;
2369
+ };
2370
+ self.paste = function (event) {
2371
+ if (!self.attributes.editable) {
2372
+ return;
2373
+ }
2374
+
2375
+ var defaultPrevented = self.dispatchEvent('beforepaste', {
2376
+ NativeEvent: event,
2377
+ });
2378
+
2379
+ if (defaultPrevented) {
2380
+ return;
2381
+ }
2382
+
2383
+ var clipboardItems = new Map(
2384
+ Array.from(event.clipboardData.items).map((item) => [item.type, item]),
2385
+ );
2386
+
2387
+ // Supported MIME types, in order of preference:
2388
+ var supportedMimeTypes = ['text/html', 'text/csv', 'text/plain'];
2389
+
2390
+ // The clipboard will often contain the same data in multiple formats,
2391
+ // which can be used depending on the context in which it's pasted. Here
2392
+ // we'll prefere more structured (HTML/CSV) over less structured, when
2393
+ // available, so we try to find those first:
2394
+ var pasteableItems = supportedMimeTypes
2395
+ .map((mimeType) => clipboardItems.get(mimeType))
2396
+ .filter((item) => !!item); // filter out not-found MIME types (= undefined)
2397
+
2398
+ if (pasteableItems.length === 0) {
2399
+ console.warn(
2400
+ 'Cannot find supported clipboard data type. Supported types are:',
2401
+ supportedMimeTypes.join(', '),
2402
+ );
2403
+ return;
2404
+ }
2405
+
2406
+ const selectionIndex = self.getSelectionIndex();
2407
+ if (!selectionIndex) return;
2408
+
2409
+ var itemToPaste = pasteableItems[0];
2410
+
2411
+ // itemToPaste is cleared once accessed (getData or getAsString),
2412
+ // so we need to store the type here, before reading its value:
2413
+ var pasteType = itemToPaste.type;
2414
+
2415
+ itemToPaste.getAsString(function (pasteValue) {
2416
+ self.pasteData(
2417
+ pasteValue,
2418
+ pasteType,
2419
+ selectionIndex.row,
2420
+ selectionIndex.column,
2421
+ selectionIndex.rowLength,
2422
+ selectionIndex.columnLength,
2423
+ );
2424
+
2425
+ self.draw();
2426
+ });
2427
+ };
2428
+ self.cut = function (event) {
2429
+ if (self.dispatchEvent('cut', { NativeEvent: event })) {
2430
+ return;
2431
+ }
2432
+
2433
+ // Expecting instance of `ClipboardEvent` with `clipboardData` attribute
2434
+ if (!self.hasFocus || !event.clipboardData) {
2435
+ return;
2436
+ }
2437
+
2438
+ if (!self.attributes.editable) {
2439
+ // A read-only grid can still put the selection on the clipboard,
2440
+ // but nothing is removed from the data (#587).
2441
+ self.copySelectedCellsToClipboard(event.clipboardData);
2442
+ event.preventDefault();
2443
+ return;
2444
+ }
2445
+
2446
+ self.copySelectedCellsToClipboard(event.clipboardData);
2447
+
2448
+ const affectedCells = self.clearSelectedCells();
2449
+ const apiCompatibleCells = affectedCells.map((cell) => {
2450
+ return [
2451
+ cell.viewRowIndex,
2452
+ cell.viewColumnIndex,
2453
+ cell.boundRowIndex,
2454
+ cell.boundColumnIndex,
2455
+ ];
2456
+ });
2457
+
2458
+ self.dispatchEvent('aftercut', {
2459
+ cells: apiCompatibleCells,
2460
+ });
2461
+ self.dispatchDataChanged('cut', { cells: apiCompatibleCells });
2462
+
2463
+ requestAnimationFrame(() => self.draw());
2464
+ event.preventDefault();
2465
+ };
2466
+ self.copy = function (event) {
2467
+ if (self.dispatchEvent('copy', { NativeEvent: event })) {
2468
+ return;
2469
+ }
2470
+
2471
+ // Expecting instance of `ClipboardEvent` with `clipboardData` attribute
2472
+ if (!self.hasFocus || !event.clipboardData) {
2473
+ return;
2474
+ }
2475
+
2476
+ self.copySelectedCellsToClipboard(event.clipboardData);
2477
+
2478
+ event.preventDefault();
2479
+ };
2480
+ self.selectionHandleMove = function (e) {
2481
+ if (!self.movingSelectionHandle) {
2482
+ return;
2483
+ }
2484
+
2485
+ const clippingRect = self.getClippingRect(e);
2486
+ const rowIndex = self.currentCell.rowIndex;
2487
+ const columnIndex = self.currentCell.columnIndex;
2488
+ const isInSelectionBounds =
2489
+ rowIndex >= -1 &&
2490
+ columnIndex >= -1 &&
2491
+ self.fillOverlay.selection.left <= columnIndex &&
2492
+ self.fillOverlay.selection.right >= columnIndex &&
2493
+ self.fillOverlay.selection.top <= rowIndex &&
2494
+ self.fillOverlay.selection.bottom >= rowIndex;
2495
+
2496
+ self.fillOverlay.minX = clippingRect.x;
2497
+ self.fillOverlay.minY = clippingRect.y;
2498
+ self.fillOverlay.x = Math.max(clippingRect.x, e.clientX);
2499
+ self.fillOverlay.y = Math.max(clippingRect.y, e.clientY);
2500
+
2501
+ // If we are in the selection bounds, allow user to change directions.
2502
+ if (isInSelectionBounds) {
2503
+ self.fillOverlay.lastInBoundsLocation = {
2504
+ x: e.clientX,
2505
+ y: e.clientY,
2506
+ };
2507
+ } else if (
2508
+ self.fillOverlay.lastInBoundsLocation ||
2509
+ !self.fillOverlay.direction
2510
+ ) {
2511
+ const lastInBoundsLocation = self.fillOverlay.lastInBoundsLocation;
2512
+ self.fillOverlay.lastInBoundsLocation = undefined;
2513
+
2514
+ const x = lastInBoundsLocation
2515
+ ? lastInBoundsLocation.x
2516
+ : self.fillOverlay.handle.x;
2517
+ const y = lastInBoundsLocation
2518
+ ? lastInBoundsLocation.y
2519
+ : self.fillOverlay.handle.y;
2520
+ const dx = Math.abs(e.clientX - x);
2521
+ const dy = Math.abs(e.clientY - y);
2522
+
2523
+ if (dx > 5 || dy > 5) {
2524
+ self.fillOverlay.direction = dx > dy ? 'x' : 'y';
2525
+ }
2526
+ }
2527
+
2528
+ if (rowIndex >= 0) {
2529
+ self.fillOverlay.rowIndex = rowIndex;
2530
+ }
2531
+ if (columnIndex >= 0) {
2532
+ self.fillOverlay.columnIndex = columnIndex;
2533
+ if (rowIndex === -1 && self.visibleRows.length) {
2534
+ self.fillOverlay.rowIndex = self.visibleRows[0];
2535
+ }
2536
+ }
2537
+
2538
+ if (rowIndex >= -1 && columnIndex >= -1) {
2539
+ self.fillOverlay.snap = self.currentCell;
2540
+ } else {
2541
+ self.fillOverlay.snap = undefined;
2542
+ }
2543
+ };
2544
+ self.stopSelectionHandleMove = function (e) {
2545
+ if (!self.fillOverlay.handle) {
2546
+ return false;
2547
+ }
2548
+
2549
+ self.ignoreNextClick = true;
2550
+
2551
+ window.removeEventListener('mousemove', self.selectionHandleMove, false);
2552
+ window.removeEventListener('mouseup', self.stopSelectionHandleMove, false);
2553
+
2554
+ const overlay = self.fillOverlay;
2555
+ const selectionIndex = self.getSelectionIndex();
2556
+ const bounds = overlay.selection;
2557
+ if (!selectionIndex) return;
2558
+
2559
+ self.movingSelectionHandle = undefined;
2560
+ self.fillOverlay = {};
2561
+
2562
+ if (overlay.rowIndex >= 0 && overlay.columnIndex >= 0) {
2563
+ const boundsOld = { ...bounds };
2564
+ const isVertical = overlay.direction === 'y';
2565
+ const isHorizontal = overlay.direction === 'x';
2566
+
2567
+ let startRow,
2568
+ rowLength,
2569
+ startColumn,
2570
+ columnLength,
2571
+ reverseVertically = false,
2572
+ reverseHorizontally = false;
2573
+
2574
+ if (isVertical) {
2575
+ if (overlay.rowIndex < bounds.top) {
2576
+ bounds.top = overlay.rowIndex;
2577
+ reverseVertically = true;
2578
+ } else if (overlay.rowIndex > bounds.bottom) {
2579
+ bounds.bottom = overlay.rowIndex;
2580
+ }
2581
+
2582
+ startRow =
2583
+ bounds.top < boundsOld.top ? bounds.top : boundsOld.bottom + 1;
2584
+ rowLength =
2585
+ bounds.top < boundsOld.top
2586
+ ? boundsOld.top - bounds.top
2587
+ : bounds.bottom - boundsOld.bottom;
2588
+ startColumn = selectionIndex.column;
2589
+ columnLength = selectionIndex.columnLength;
2590
+ } else if (isHorizontal) {
2591
+ if (overlay.columnIndex < bounds.left) {
2592
+ bounds.left = overlay.columnIndex;
2593
+ reverseHorizontally = true;
2594
+ } else if (overlay.columnIndex > bounds.right) {
2595
+ bounds.right = overlay.columnIndex;
2596
+ }
2597
+
2598
+ startColumn =
2599
+ bounds.left < boundsOld.left ? bounds.left : boundsOld.right + 1;
2600
+ columnLength =
2601
+ bounds.left < boundsOld.left
2602
+ ? boundsOld.left - bounds.left
2603
+ : bounds.right - boundsOld.right;
2604
+ startRow = selectionIndex.row;
2605
+ rowLength = selectionIndex.rowLength;
2606
+ }
2607
+
2608
+ if (
2609
+ bounds.left <= bounds.right &&
2610
+ bounds.top <= bounds.bottom &&
2611
+ (bounds.left < boundsOld.left ||
2612
+ bounds.top < boundsOld.top ||
2613
+ bounds.right > boundsOld.right ||
2614
+ bounds.bottom > boundsOld.bottom)
2615
+ ) {
2616
+ const schema = self.getSchema();
2617
+ const rows = [];
2618
+
2619
+ for (
2620
+ let rowIndex = 0;
2621
+ rowIndex < Math.min(rowLength, selectionIndex.rowLength);
2622
+ rowIndex++
2623
+ ) {
2624
+ const rowData = self.viewData[selectionIndex.row + rowIndex];
2625
+
2626
+ rows[rowIndex] = [];
2627
+
2628
+ for (
2629
+ let columnIndex = 0;
2630
+ columnIndex < Math.min(columnLength, selectionIndex.columnLength);
2631
+ columnIndex++
2632
+ ) {
2633
+ const column = schema[selectionIndex.column + columnIndex];
2634
+ if (!column) continue;
2635
+
2636
+ const cellData = rowData[column.name];
2637
+
2638
+ rows[rowIndex][columnIndex] = cellData;
2639
+ }
2640
+ }
2641
+
2642
+ self.insert({
2643
+ rows: rows,
2644
+ startRowIndex: startRow,
2645
+ startColumnIndex: startColumn,
2646
+ minRowsLength: rowLength,
2647
+ minColumnsLength: columnLength,
2648
+ reverseRows: reverseVertically,
2649
+ reverseColumns: reverseHorizontally,
2650
+ clearSelections: false,
2651
+ alwaysFilling: true,
2652
+ direction: isHorizontal ? 'horizontal' : 'vertical',
2653
+ });
2654
+ self.dispatchDataChanged('fill');
2655
+
2656
+ self.draw();
2657
+ }
2658
+ }
2659
+
2660
+ return true;
2661
+ };
2662
+ return;
2663
+ }