-
Notifications
You must be signed in to change notification settings - Fork 3k
/
autoRowSize.js
611 lines (537 loc) · 17.6 KB
/
autoRowSize.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
import { BasePlugin } from '../base';
import { arrayEach, arrayFilter } from '../../helpers/array';
import { cancelAnimationFrame, requestAnimationFrame } from '../../helpers/feature';
import { isVisible } from '../../helpers/dom/element';
import GhostTable from '../../utils/ghostTable';
import { isObject, hasOwnProperty } from '../../helpers/object';
import { valueAccordingPercent, rangeEach } from '../../helpers/number';
import SamplesGenerator from '../../utils/samplesGenerator';
import { isPercentValue } from '../../helpers/string';
import { PhysicalIndexToValueMap as IndexToValueMap } from '../../translations';
export const PLUGIN_KEY = 'autoRowSize';
export const PLUGIN_PRIORITY = 40;
const ROW_WIDTHS_MAP_NAME = 'autoRowSize';
/* eslint-disable jsdoc/require-description-complete-sentence */
/**
* @plugin AutoRowSize
* @class AutoRowSize
* @description
* The `AutoRowSize` plugin allows you to set row heights based on their highest cells.
*
* By default, the plugin is declared as `undefined`, which makes it disabled (same as if it was declared as `false`).
* Enabling this plugin may decrease the overall table performance, as it needs to calculate the heights of all cells to
* resize the rows accordingly.
* If you experience problems with the performance, try turning this feature off and declaring the row heights manually.
*
* But, to display Handsontable's [scrollbar](https://handsontable.com/docs/8.0.0/demo-scrolling.html)
* in a proper size, you need to enable the `AutoRowSize` plugin,
* by setting the [`autoRowSize`](@/api/options.md#autoRowSize) option to `true`.
*
* Row height calculations are divided into sync and async part. Each of this parts has their own advantages and
* disadvantages. Synchronous calculations are faster but they block the browser UI, while the slower asynchronous
* operations don't block the browser UI.
*
* To configure the sync/async distribution, you can pass an absolute value (number of rows) or a percentage value to a config object:
* ```js
* // as a number (300 rows in sync, rest async)
* autoRowSize: {syncLimit: 300},
*
* // as a string (percent)
* autoRowSize: {syncLimit: '40%'},
*
* // allow sample duplication
* autoRowSize: {syncLimit: '40%', allowSampleDuplicates: true},
* ```
*
* You can also use the `allowSampleDuplicates` option to allow sampling duplicate values when calculating the row
* height. __Note__, that this might have a negative impact on performance.
*
* To configure this plugin see {@link Options#autoRowSize}.
*
* @example
*
* ::: only-for javascript
* ```js
* const hot = new Handsontable(document.getElementById('example'), {
* data: getData(),
* autoRowSize: true
* });
* // Access to plugin instance:
* const plugin = hot.getPlugin('autoRowSize');
*
* plugin.getRowHeight(4);
*
* if (plugin.isEnabled()) {
* // code...
* }
* ```
* :::
*
* ::: only-for react
* ```jsx
* const hotRef = useRef(null);
*
* ...
*
* // First, let's contruct Handsontable
* <HotTable
* ref={hotRef}
* data={getData()}
* autoRowSize={true}
* />
*
* ...
*
* // Access to plugin instance:
* const hot = hotRef.current.hotInstance;
* const plugin = hot.getPlugin('autoRowSize');
*
* plugin.getRowHeight(4);
*
* if (plugin.isEnabled()) {
* // code...
* }
* ```
* :::
*/
/* eslint-enable jsdoc/require-description-complete-sentence */
export class AutoRowSize extends BasePlugin {
static get PLUGIN_KEY() {
return PLUGIN_KEY;
}
static get PLUGIN_PRIORITY() {
return PLUGIN_PRIORITY;
}
static get SETTING_KEYS() {
return true;
}
static get CALCULATION_STEP() {
return 50;
}
static get SYNC_CALCULATION_LIMIT() {
return 500;
}
constructor(hotInstance) {
super(hotInstance);
/**
* PhysicalIndexToValueMap to keep and track heights for physical row indexes.
*
* @private
* @type {PhysicalIndexToValueMap}
*/
this.rowHeightsMap = void 0;
/**
* Columns header's height cache.
*
* @private
* @type {number}
*/
this.headerHeight = null;
/**
* Instance of {@link GhostTable} for rows and columns size calculations.
*
* @private
* @type {GhostTable}
*/
this.ghostTable = new GhostTable(this.hot);
/**
* Instance of {@link SamplesGenerator} for generating samples necessary for rows height calculations.
*
* @private
* @type {SamplesGenerator}
*/
this.samplesGenerator = new SamplesGenerator((row, col) => {
let cellValue;
if (row >= 0) {
cellValue = this.hot.getDataAtCell(row, col);
} else if (row === -1) {
cellValue = this.hot.getColHeader(col);
}
return { value: cellValue };
});
/**
* `true` if only the first calculation was performed.
*
* @private
* @type {boolean}
*/
this.firstCalculation = true;
/**
* `true` if the size calculation is in progress.
*
* @type {boolean}
*/
this.inProgress = false;
/**
* Number of already measured rows (we already know their sizes).
*
* @type {number}
*/
this.measuredRows = 0;
/**
* PhysicalIndexToValueMap to keep and track heights for physical row indexes.
*
* @private
* @type {PhysicalIndexToValueMap}
*/
this.rowHeightsMap = new IndexToValueMap();
this.hot.rowIndexMapper.registerMap(ROW_WIDTHS_MAP_NAME, this.rowHeightsMap);
// Leave the listener active to allow auto-sizing the rows when the plugin is disabled.
// This is necesseary for height recalculation for resize handler doubleclick (ManualRowResize).
this.addHook('beforeRowResize', (size, row, isDblClick) => this.onBeforeRowResize(size, row, isDblClick));
}
/**
* Checks if the plugin is enabled in the handsontable settings. This method is executed in {@link Hooks#beforeInit}
* hook and if it returns `true` then the {@link AutoRowSize#enablePlugin} method is called.
*
* @returns {boolean}
*/
isEnabled() {
const settings = this.hot.getSettings()[PLUGIN_KEY];
return settings === true || isObject(settings);
}
/**
* Enables the plugin functionality for this Handsontable instance.
*/
enablePlugin() {
if (this.enabled) {
return;
}
this.setSamplingOptions();
this.addHook('afterLoadData', (...args) => this.onAfterLoadData(...args));
this.addHook('beforeChangeRender', changes => this.onBeforeChange(changes));
this.addHook('beforeColumnResize', () => this.recalculateAllRowsHeight());
this.addHook('beforeViewRender', force => this.onBeforeViewRender(force));
this.addHook('modifyRowHeight', (height, row) => this.getRowHeight(row, height));
this.addHook('modifyColumnHeaderHeight', () => this.getColumnHeaderHeight());
super.enablePlugin();
}
/**
* Disables the plugin functionality for this Handsontable instance.
*/
disablePlugin() {
this.headerHeight = null;
super.disablePlugin();
// Leave the listener active to allow auto-sizing the rows when the plugin is disabled.
// This is necesseary for height recalculation for resize handler doubleclick (ManualRowResize).
this.addHook('beforeRowResize', (size, row, isDblClick) => this.onBeforeRowResize(size, row, isDblClick));
}
/**
* Calculate a given rows height.
*
* @param {number|object} rowRange Row index or an object with `from` and `to` indexes as a range.
* @param {number|object} colRange Column index or an object with `from` and `to` indexes as a range.
* @param {boolean} [force=false] If `true` the calculation will be processed regardless of whether the width exists in the cache.
*/
calculateRowsHeight(rowRange = { from: 0, to: this.hot.countRows() - 1 }, colRange = { from: 0, to: this.hot.countCols() - 1 }, force = false) { // eslint-disable-line max-len
const rowsRange = typeof rowRange === 'number' ? { from: rowRange, to: rowRange } : rowRange;
const columnsRange = typeof colRange === 'number' ? { from: colRange, to: colRange } : colRange;
if (this.hot.getColHeader(0) !== null) {
const samples = this.samplesGenerator.generateRowSamples(-1, columnsRange);
this.ghostTable.addColumnHeadersRow(samples.get(-1));
}
rangeEach(rowsRange.from, rowsRange.to, (row) => {
// For rows we must calculate row height even when user had set height value manually.
// We can shrink column but cannot shrink rows!
if (force || this.rowHeightsMap.getValueAtIndex(row) === null) {
const samples = this.samplesGenerator.generateRowSamples(row, columnsRange);
arrayEach(samples, ([rowIndex, sample]) => this.ghostTable.addRow(rowIndex, sample));
}
});
if (this.ghostTable.rows.length) {
this.hot.batchExecution(() => {
this.ghostTable.getHeights((row, height) => {
if (row < 0) {
this.headerHeight = height;
} else {
this.rowHeightsMap.setValueAtIndex(this.hot.toPhysicalRow(row), height);
}
});
}, true);
this.measuredRows = rowsRange.to + 1;
this.ghostTable.clean();
}
}
/**
* Calculate all rows heights. The calculated row will be cached in the {@link AutoRowSize#heights} property.
* To retrieve height for specified row use {@link AutoRowSize#getRowHeight} method.
*
* @param {object|number} colRange Row index or an object with `from` and `to` properties which define row range.
*/
calculateAllRowsHeight(colRange = { from: 0, to: this.hot.countCols() - 1 }) {
let current = 0;
const length = this.hot.countRows() - 1;
let timer = null;
this.inProgress = true;
const loop = () => {
// When hot was destroyed after calculating finished cancel frame
if (!this.hot) {
cancelAnimationFrame(timer);
this.inProgress = false;
return;
}
this.calculateRowsHeight({
from: current,
to: Math.min(current + AutoRowSize.CALCULATION_STEP, length)
}, colRange);
current = current + AutoRowSize.CALCULATION_STEP + 1;
if (current < length) {
timer = requestAnimationFrame(loop);
} else {
cancelAnimationFrame(timer);
this.inProgress = false;
// @TODO Should call once per render cycle, currently fired separately in different plugins
this.hot.view.adjustElementsSize(true);
// tmp
if (this.hot.view._wt.wtOverlays.inlineStartOverlay.needFullRender) {
this.hot.view._wt.wtOverlays.inlineStartOverlay.clone.draw();
}
}
};
const syncLimit = this.getSyncCalculationLimit();
// sync
if (this.firstCalculation && syncLimit >= 0) {
this.calculateRowsHeight({ from: 0, to: syncLimit }, colRange);
this.firstCalculation = false;
current = syncLimit + 1;
}
// async
if (current < length) {
loop();
} else {
this.inProgress = false;
this.hot.view.adjustElementsSize(false);
}
}
/**
* Sets the sampling options.
*
* @private
*/
setSamplingOptions() {
const setting = this.hot.getSettings()[PLUGIN_KEY];
const samplingRatio = setting && hasOwnProperty(setting, 'samplingRatio') ?
setting.samplingRatio : void 0;
const allowSampleDuplicates = setting && hasOwnProperty(setting, 'allowSampleDuplicates') ?
setting.allowSampleDuplicates : void 0;
if (samplingRatio && !isNaN(samplingRatio)) {
this.samplesGenerator.setSampleCount(parseInt(samplingRatio, 10));
}
if (allowSampleDuplicates) {
this.samplesGenerator.setAllowDuplicates(allowSampleDuplicates);
}
}
/**
* Recalculates all rows height (overwrite cache values).
*/
recalculateAllRowsHeight() {
if (isVisible(this.hot.view._wt.wtTable.TABLE)) {
this.clearCache();
this.calculateAllRowsHeight();
}
}
/**
* Gets value which tells how many rows should be calculated synchronously (rest of the rows will be calculated
* asynchronously). The limit is calculated based on `syncLimit` set to autoRowSize option (see {@link Options#autoRowSize}).
*
* @returns {number}
*/
getSyncCalculationLimit() {
const settings = this.hot.getSettings()[PLUGIN_KEY];
/* eslint-disable no-bitwise */
let limit = AutoRowSize.SYNC_CALCULATION_LIMIT;
const rowsLimit = this.hot.countRows() - 1;
if (isObject(settings)) {
limit = settings.syncLimit;
if (isPercentValue(limit)) {
limit = valueAccordingPercent(rowsLimit, limit);
} else {
// Force to Number
limit >>= 0;
}
}
return Math.min(limit, rowsLimit);
}
/**
* Get a row's height, as measured in the DOM.
*
* The height returned includes 1 px of the row's bottom border.
*
* Mind that this method is different from the
* [`getRowHeight()`](@/api/core.md#getrowheight) method
* of Handsontable's [Core](@/api/core.md).
*
* @param {number} row A visual row index.
* @param {number} [defaultHeight] If no height is found, `defaultHeight` is returned instead.
* @returns {number} The height of the specified row, in pixels.
*/
getRowHeight(row, defaultHeight = void 0) {
const cachedHeight = row < 0 ? this.headerHeight : this.rowHeightsMap.getValueAtIndex(this.hot.toPhysicalRow(row));
let height = defaultHeight;
if (cachedHeight !== null && cachedHeight > (defaultHeight || 0)) {
height = cachedHeight;
}
return height;
}
/**
* Get the calculated column header height.
*
* @returns {number|undefined}
*/
getColumnHeaderHeight() {
return this.headerHeight;
}
/**
* Get the first visible row.
*
* @returns {number} Returns row index, -1 if table is not rendered or if there are no rows to base the the calculations on.
*/
getFirstVisibleRow() {
const wot = this.hot.view._wt;
if (wot.wtViewport.rowsVisibleCalculator) {
return wot.wtTable.getFirstVisibleRow();
}
if (wot.wtViewport.rowsRenderCalculator) {
return wot.wtTable.getFirstRenderedRow();
}
return -1;
}
/**
* Gets the last visible row.
*
* @returns {number} Returns row index or -1 if table is not rendered.
*/
getLastVisibleRow() {
const wot = this.hot.view._wt;
if (wot.wtViewport.rowsVisibleCalculator) {
return wot.wtTable.getLastVisibleRow();
}
if (wot.wtViewport.rowsRenderCalculator) {
return wot.wtTable.getLastRenderedRow();
}
return -1;
}
/**
* Clears cached heights.
*/
clearCache() {
this.headerHeight = null;
this.rowHeightsMap.init();
}
/**
* Clears cache by range.
*
* @param {object|number} range Row index or an object with `from` and `to` properties which define row range.
*/
clearCacheByRange(range) {
const { from, to } = typeof range === 'number' ? { from: range, to: range } : range;
this.hot.batchExecution(() => {
rangeEach(Math.min(from, to), Math.max(from, to), (row) => {
this.rowHeightsMap.setValueAtIndex(row, null);
});
}, true);
}
/**
* Checks if all heights were calculated. If not then return `true` (need recalculate).
*
* @returns {boolean}
*/
isNeedRecalculate() {
return !!arrayFilter(this.rowHeightsMap.getValues().slice(0, this.measuredRows), item => (item === null)).length;
}
/**
* On before view render listener.
*
* @private
*/
onBeforeViewRender() {
const force = this.hot.renderCall;
const fixedRowsBottom = this.hot.getSettings().fixedRowsBottom;
const firstVisibleRow = this.getFirstVisibleRow();
const lastVisibleRow = this.getLastVisibleRow();
if (firstVisibleRow === -1 || lastVisibleRow === -1) {
return;
}
this.calculateRowsHeight({ from: firstVisibleRow, to: lastVisibleRow }, void 0, force);
// Calculate rows height synchronously for bottom overlay
if (fixedRowsBottom) {
const totalRows = this.hot.countRows() - 1;
this.calculateRowsHeight({ from: totalRows - fixedRowsBottom, to: totalRows });
}
if (this.isNeedRecalculate() && !this.inProgress) {
this.calculateAllRowsHeight();
}
}
/**
* On before row move listener.
*
* @private
* @param {number} from Row index where was grabbed.
* @param {number} to Destination row index.
*/
onBeforeRowMove(from, to) {
this.clearCacheByRange({ from, to });
this.calculateAllRowsHeight();
}
/**
* On before row resize listener.
*
* @private
* @param {number} size The size of the current row index.
* @param {number} row Current row index.
* @param {boolean} isDblClick Indicates if the resize was triggered by doubleclick.
* @returns {number}
*/
onBeforeRowResize(size, row, isDblClick) {
let newSize = size;
if (isDblClick) {
this.calculateRowsHeight(row, void 0, true);
newSize = this.getRowHeight(row);
}
return newSize;
}
/**
* On after load data listener.
*
* @private
*/
onAfterLoadData() {
if (this.hot.view) {
this.recalculateAllRowsHeight();
} else {
// first load - initialization
setTimeout(() => {
if (this.hot) {
this.recalculateAllRowsHeight();
}
}, 0);
}
}
/**
* On before change listener.
*
* @private
* @param {Array} changes 2D array containing information about each of the edited cells.
*/
onBeforeChange(changes) {
let range = null;
if (changes.length === 1) {
range = changes[0][0];
} else if (changes.length > 1) {
range = {
from: changes[0][0],
to: changes[changes.length - 1][0],
};
}
if (range !== null) {
this.clearCacheByRange(range);
}
}
/**
* Destroys the plugin instance.
*/
destroy() {
this.ghostTable.clean();
super.destroy();
}
}