-
Notifications
You must be signed in to change notification settings - Fork 3k
/
hiddenColumns.js
529 lines (458 loc) · 14.8 KB
/
hiddenColumns.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
import { BasePlugin } from '../base';
import { addClass } from '../../helpers/dom/element';
import { rangeEach } from '../../helpers/number';
import { arrayEach, arrayMap, arrayReduce } from '../../helpers/array';
import { isObject } from '../../helpers/object';
import { isUndefined } from '../../helpers/mixed';
import { SEPARATOR } from '../contextMenu/predefinedItems';
import Hooks from '../../pluginHooks';
import hideColumnItem from './contextMenuItem/hideColumn';
import showColumnItem from './contextMenuItem/showColumn';
import { HidingMap } from '../../translations';
import './hiddenColumns.scss';
Hooks.getSingleton().register('beforeHideColumns');
Hooks.getSingleton().register('afterHideColumns');
Hooks.getSingleton().register('beforeUnhideColumns');
Hooks.getSingleton().register('afterUnhideColumns');
export const PLUGIN_KEY = 'hiddenColumns';
export const PLUGIN_PRIORITY = 310;
/* eslint-disable jsdoc/require-description-complete-sentence */
/**
* @plugin HiddenColumns
* @class HiddenColumns
*
* @description
* The `HiddenColumns` plugin lets you [hide specified columns](@/guides/columns/column-hiding.md).
*
* "Hiding a column" means that the hidden column doesn't get rendered as a DOM element.
*
* The `HiddenColumns` plugin doesn't modify the source data,
* and doesn't participate in data transformation
* (the shape of the data returned by the [`getData*()` methods](@/api/core.md#getdata) stays intact).
*
* You can set the following configuration options:
*
* | Option | Required | Type | Default | Description |
* |---|---|---|---|---|
* | `columns` | No | Array | - | [Hides specified columns by default](@/guides/columns/column-hiding.md#step-1-specify-columns-hidden-by-default) |
* | `indicators` | No | Boolean | `false` | [Shows UI indicators](@/guides/columns/column-hiding.md#step-2-show-ui-indicators) |
* | `copyPasteEnabled` | No | Boolean | `true` | [Sets up copy/paste behavior](@/guides/columns/column-hiding.md#step-4-set-up-copy-and-paste-behavior) |
*
* @example
*
* ::: only-for javascript
* ```js
* const container = document.getElementById('example');
* const hot = new Handsontable(container, {
* data: getData(),
* hiddenColumns: {
* copyPasteEnabled: true,
* indicators: true,
* columns: [1, 2, 5]
* }
* });
*
* // access the `HiddenColumns` plugin's instance
* const hiddenColumnsPlugin = hot.getPlugin('hiddenColumns');
*
* // hide a single column
* hiddenColumnsPlugin.hideColumn(1);
*
* // hide multiple columns
* hiddenColumnsPlugin.hideColumn(1, 2, 9);
*
* // hide multiple columns as an array
* hiddenColumnsPlugin.hideColumns([1, 2, 9]);
*
* // unhide a single column
* hiddenColumnsPlugin.showColumn(1);
*
* // unhide multiple columns
* hiddenColumnsPlugin.showColumn(1, 2, 9);
*
* // unhide multiple columns as an array
* hiddenColumnsPlugin.showColumns([1, 2, 9]);
*
* // to see your changes, re-render your Handsontable instance
* hot.render();
* ```
* :::
*
* ::: only-for react
* ```jsx
* const hotRef = useRef(null);
*
* ...
*
* <HotTable
* ref={hotRef}
* data={getData()}
* hiddenColumns={{
* copyPasteEnabled: true,
* indicators: true,
* columns: [1, 2, 5]
* }}
* />
*
* // access the `HiddenColumns` plugin's instance
* const hot = hotRef.current.hotInstance;
* const hiddenColumnsPlugin = hot.getPlugin('hiddenColumns');
*
* // hide a single column
* hiddenColumnsPlugin.hideColumn(1);
*
* // hide multiple columns
* hiddenColumnsPlugin.hideColumn(1, 2, 9);
*
* // hide multiple columns as an array
* hiddenColumnsPlugin.hideColumns([1, 2, 9]);
*
* // unhide a single column
* hiddenColumnsPlugin.showColumn(1);
*
* // unhide multiple columns
* hiddenColumnsPlugin.showColumn(1, 2, 9);
*
* // unhide multiple columns as an array
* hiddenColumnsPlugin.showColumns([1, 2, 9]);
*
* // to see your changes, re-render your Handsontable instance
* hot.render();
* ```
* :::
*/
export class HiddenColumns extends BasePlugin {
static get PLUGIN_KEY() {
return PLUGIN_KEY;
}
static get PLUGIN_PRIORITY() {
return PLUGIN_PRIORITY;
}
/**
* Cached plugin settings.
*
* @private
* @type {object}
*/
#settings = {};
/**
* Map of hidden columns by the plugin.
*
* @private
* @type {null|HidingMap}
*/
#hiddenColumnsMap = null;
/**
* 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 HiddenColumns#enablePlugin} method is called.
*
* @returns {boolean}
*/
isEnabled() {
return !!this.hot.getSettings()[PLUGIN_KEY];
}
/**
* Enables the plugin functionality for this Handsontable instance.
*/
enablePlugin() {
if (this.enabled) {
return;
}
const pluginSettings = this.hot.getSettings()[PLUGIN_KEY];
if (isObject(pluginSettings)) {
this.#settings = pluginSettings;
if (isUndefined(pluginSettings.copyPasteEnabled)) {
pluginSettings.copyPasteEnabled = true;
}
}
this.#hiddenColumnsMap = new HidingMap();
this.#hiddenColumnsMap.addLocalHook('init', () => this.#onMapInit());
this.hot.columnIndexMapper.registerMap(this.pluginName, this.#hiddenColumnsMap);
this.addHook('afterContextMenuDefaultOptions', (...args) => this.#onAfterContextMenuDefaultOptions(...args));
this.addHook('afterGetCellMeta', (row, col, cellProperties) => this.#onAfterGetCellMeta(row, col, cellProperties));
this.addHook('modifyColWidth', (width, col) => this.#onModifyColWidth(width, col));
this.addHook('afterGetColHeader', (...args) => this.#onAfterGetColHeader(...args));
this.addHook('modifyCopyableRange', ranges => this.#onModifyCopyableRange(ranges));
super.enablePlugin();
}
/**
* Updates the plugin's state.
*
* This method is executed when [`updateSettings()`](@/api/core.md#updatesettings) is invoked with any of the following configuration options:
* - [`hiddenColumns`](@/api/options.md#hiddencolumns)
*/
updatePlugin() {
this.disablePlugin();
this.enablePlugin();
super.updatePlugin();
}
/**
* Disables the plugin functionality for this Handsontable instance.
*/
disablePlugin() {
this.hot.columnIndexMapper.unregisterMap(this.pluginName);
this.#settings = {};
super.disablePlugin();
this.resetCellsMeta();
}
/**
* Shows the provided columns.
*
* @param {number[]} columns Array of visual column indexes.
*/
showColumns(columns) {
const currentHideConfig = this.getHiddenColumns();
const isValidConfig = this.isValidConfig(columns);
let destinationHideConfig = currentHideConfig;
const hidingMapValues = this.#hiddenColumnsMap.getValues().slice();
const isAnyColumnShowed = columns.length > 0;
if (isValidConfig && isAnyColumnShowed) {
const physicalColumns = columns.map(visualColumn => this.hot.toPhysicalColumn(visualColumn));
// Preparing new values for hiding map.
arrayEach(physicalColumns, (physicalColumn) => {
hidingMapValues[physicalColumn] = false;
});
// Preparing new hiding config.
destinationHideConfig = arrayReduce(hidingMapValues, (hiddenIndexes, isHidden, physicalIndex) => {
if (isHidden) {
hiddenIndexes.push(this.hot.toVisualColumn(physicalIndex));
}
return hiddenIndexes;
}, []);
}
const continueHiding = this.hot
.runHooks('beforeUnhideColumns', currentHideConfig, destinationHideConfig, isValidConfig && isAnyColumnShowed);
if (continueHiding === false) {
return;
}
if (isValidConfig && isAnyColumnShowed) {
this.#hiddenColumnsMap.setValues(hidingMapValues);
}
// @TODO Should call once per render cycle, currently fired separately in different plugins
this.hot.view.adjustElementsSize();
this.hot.runHooks('afterUnhideColumns', currentHideConfig, destinationHideConfig,
isValidConfig && isAnyColumnShowed, isValidConfig && destinationHideConfig.length < currentHideConfig.length);
}
/**
* Shows a single column.
*
* @param {...number} column Visual column index.
*/
showColumn(...column) {
this.showColumns(column);
}
/**
* Hides the columns provided in the array.
*
* @param {number[]} columns Array of visual column indexes.
*/
hideColumns(columns) {
const currentHideConfig = this.getHiddenColumns();
const isConfigValid = this.isValidConfig(columns);
let destinationHideConfig = currentHideConfig;
if (isConfigValid) {
destinationHideConfig = Array.from(new Set(currentHideConfig.concat(columns)));
}
const continueHiding = this.hot
.runHooks('beforeHideColumns', currentHideConfig, destinationHideConfig, isConfigValid);
if (continueHiding === false) {
return;
}
if (isConfigValid) {
this.hot.batchExecution(() => {
arrayEach(columns, (visualColumn) => {
this.#hiddenColumnsMap.setValueAtIndex(this.hot.toPhysicalColumn(visualColumn), true);
});
}, true);
}
this.hot.runHooks('afterHideColumns', currentHideConfig, destinationHideConfig, isConfigValid,
isConfigValid && destinationHideConfig.length > currentHideConfig.length);
}
/**
* Hides a single column.
*
* @param {...number} column Visual column index.
*/
hideColumn(...column) {
this.hideColumns(column);
}
/**
* Returns an array of visual indexes of hidden columns.
*
* @returns {number[]}
*/
getHiddenColumns() {
return arrayMap(this.#hiddenColumnsMap.getHiddenIndexes(), (physicalColumnIndex) => {
return this.hot.toVisualColumn(physicalColumnIndex);
});
}
/**
* Checks if the provided column is hidden.
*
* @param {number} column Visual column index.
* @returns {boolean}
*/
isHidden(column) {
return this.#hiddenColumnsMap.getValueAtIndex(this.hot.toPhysicalColumn(column)) || false;
}
/**
* Get if trim config is valid. Check whether all of the provided column indexes are within the bounds of the table.
*
* @param {Array} hiddenColumns List of hidden column indexes.
* @returns {boolean}
*/
isValidConfig(hiddenColumns) {
const nrOfColumns = this.hot.countCols();
if (Array.isArray(hiddenColumns) && hiddenColumns.length > 0) {
return hiddenColumns
.every(visualColumn => Number.isInteger(visualColumn) && visualColumn >= 0 && visualColumn < nrOfColumns);
}
return false;
}
/**
* Reset all rendered cells meta.
*
* @private
*/
resetCellsMeta() {
arrayEach(this.hot.getCellsMeta(), (meta) => {
if (meta) {
meta.skipColumnOnPaste = false;
}
});
}
/**
* Adds the additional column width for the hidden column indicators.
*
* @param {number|undefined} width Column width.
* @param {number} column Visual column index.
* @returns {number}
*/
#onModifyColWidth(width, column) {
// Hook is triggered internally only for the visible columns. Conditional will be handled for the API
// calls of the `getColWidth` function on not visible indexes.
if (this.isHidden(column)) {
return 0;
}
if (this.#settings.indicators && (this.isHidden(column + 1) || this.isHidden(column - 1))) {
// Add additional space for hidden column indicator.
if (typeof width === 'number' && this.hot.hasColHeaders()) {
return width + 15;
}
}
}
/**
* Sets the copy-related cell meta.
*
* @param {number} row Visual row index.
* @param {number} column Visual column index.
* @param {object} cellProperties Object containing the cell properties.
*/
#onAfterGetCellMeta(row, column, cellProperties) {
if (this.#settings.copyPasteEnabled === false && this.isHidden(column)) {
// Cell property handled by the `Autofill` and the `CopyPaste` plugins.
cellProperties.skipColumnOnPaste = true;
}
if (this.isHidden(column - 1)) {
cellProperties.className = cellProperties.className || '';
if (cellProperties.className.indexOf('afterHiddenColumn') === -1) {
cellProperties.className += ' afterHiddenColumn';
}
} else if (cellProperties.className) {
const classArr = cellProperties.className.split(' ');
if (classArr.length > 0) {
const containAfterHiddenColumn = classArr.indexOf('afterHiddenColumn');
if (containAfterHiddenColumn > -1) {
classArr.splice(containAfterHiddenColumn, 1);
}
cellProperties.className = classArr.join(' ');
}
}
}
/**
* Modifies the copyable range, accordingly to the provided config.
*
* @param {Array} ranges An array of objects defining copyable cells.
* @returns {Array}
*/
#onModifyCopyableRange(ranges) {
// Ranges shouldn't be modified when `copyPasteEnabled` option is set to `true` (by default).
if (this.#settings.copyPasteEnabled) {
return ranges;
}
const newRanges = [];
const pushRange = (startRow, endRow, startCol, endCol) => {
newRanges.push({ startRow, endRow, startCol, endCol });
};
arrayEach(ranges, (range) => {
let isHidden = true;
let rangeStart = 0;
rangeEach(range.startCol, range.endCol, (visualColumn) => {
if (this.isHidden(visualColumn)) {
if (!isHidden) {
pushRange(range.startRow, range.endRow, rangeStart, visualColumn - 1);
}
isHidden = true;
} else {
if (isHidden) {
rangeStart = visualColumn;
}
if (visualColumn === range.endCol) {
pushRange(range.startRow, range.endRow, rangeStart, visualColumn);
}
isHidden = false;
}
});
});
return newRanges;
}
/**
* Adds the needed classes to the headers.
*
* @param {number} column Visual column index.
* @param {HTMLElement} TH Header's TH element.
*/
#onAfterGetColHeader(column, TH) {
if (!this.#settings.indicators || column < 0) {
return;
}
const classList = [];
if (column >= 1 && this.isHidden(column - 1)) {
classList.push('afterHiddenColumn');
}
if (column < this.hot.countCols() - 1 && this.isHidden(column + 1)) {
classList.push('beforeHiddenColumn');
}
addClass(TH, classList);
}
/**
* Add Show-hide columns to context menu.
*
* @param {object} options An array of objects containing information about the pre-defined Context Menu items.
*/
#onAfterContextMenuDefaultOptions(options) {
options.items.push(
{
name: SEPARATOR
},
hideColumnItem(this),
showColumnItem(this)
);
}
/**
* On map initialized hook callback.
*/
#onMapInit() {
if (Array.isArray(this.#settings.columns)) {
this.hideColumns(this.#settings.columns);
}
}
/**
* Destroys the plugin instance.
*/
destroy() {
this.#settings = null;
this.#hiddenColumnsMap = null;
super.destroy();
}
}