-
Notifications
You must be signed in to change notification settings - Fork 3k
/
filters.js
928 lines (809 loc) · 28.4 KB
/
filters.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
import { BasePlugin } from '../base';
import { arrayEach, arrayMap } from '../../helpers/array';
import { toSingleLine } from '../../helpers/templateLiteralTag';
import { warn } from '../../helpers/console';
import { rangeEach } from '../../helpers/number';
import EventManager from '../../eventManager';
import { addClass, removeClass } from '../../helpers/dom/element';
import { SEPARATOR } from '../contextMenu/predefinedItems';
import * as constants from '../../i18n/constants';
import ConditionComponent from './component/condition';
import OperatorsComponent from './component/operators';
import ValueComponent from './component/value';
import ActionBarComponent from './component/actionBar';
import ConditionCollection from './conditionCollection';
import DataFilter from './dataFilter';
import ConditionUpdateObserver from './conditionUpdateObserver';
import { createArrayAssertion, toEmptyString, unifyColumnValues } from './utils';
import {
CONDITION_NONE,
CONDITION_BY_VALUE,
OPERATION_AND,
OPERATION_OR,
OPERATION_OR_THEN_VARIABLE
} from './constants';
import { TrimmingMap } from '../../translations';
import './filters.scss';
export const PLUGIN_KEY = 'filters';
export const PLUGIN_PRIORITY = 250;
/**
* @plugin Filters
* @class Filters
*
* @description
* The plugin allows filtering the table data either by the built-in component or with the API.
*
* See [the filtering demo](@/guides/columns/column-filter.md) for examples.
*
* @example
* ::: only-for javascript
* ```js
* const container = document.getElementById('example');
* const hot = new Handsontable(container, {
* data: getData(),
* colHeaders: true,
* rowHeaders: true,
* dropdownMenu: true,
* filters: true
* });
* ```
* :::
*
* ::: only-for react
* ```jsx
* <HotTable
* data={getData()}
* colHeaders={true}
* rowHeaders={true}
* dropdownMenu={true}
* filters={true}
* />
* ```
* :::
*/
export class Filters extends BasePlugin {
static get PLUGIN_KEY() {
return PLUGIN_KEY;
}
static get PLUGIN_PRIORITY() {
return PLUGIN_PRIORITY;
}
static get PLUGIN_DEPS() {
return [
'plugin:DropdownMenu',
'plugin:HiddenRows',
'cell-type:checkbox',
];
}
constructor(hotInstance) {
super(hotInstance);
/**
* Instance of {@link EventManager}.
*
* @private
* @type {EventManager}
*/
this.eventManager = new EventManager(this);
/**
* Instance of {@link DropdownMenu}.
*
* @private
* @type {DropdownMenu}
*/
this.dropdownMenuPlugin = null;
/**
* Instance of {@link ConditionCollection}.
*
* @private
* @type {ConditionCollection}
*/
this.conditionCollection = null;
/**
* Instance of {@link ConditionUpdateObserver}.
*
* @private
* @type {ConditionUpdateObserver}
*/
this.conditionUpdateObserver = null;
/**
* Map, where key is component identifier and value represent `BaseComponent` element or it derivatives.
*
* @private
* @type {Map}
*/
this.components = new Map([
['filter_by_condition', null],
['filter_operators', null],
['filter_by_condition2', null],
['filter_by_value', null],
['filter_action_bar', null]
]);
/**
* Map of skipped rows by plugin.
*
* @private
* @type {null|TrimmingMap}
*/
this.filtersRowsMap = null;
// One listener for the enable/disable functionality
this.hot.addHook('afterGetColHeader', (col, TH) => this.onAfterGetColHeader(col, TH));
}
/**
* 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 Filters#enablePlugin} method is called.
*
* @returns {boolean}
*/
isEnabled() {
/* eslint-disable no-unneeded-ternary */
return this.hot.getSettings()[PLUGIN_KEY] ? true : false;
}
/**
* Enables the plugin functionality for this Handsontable instance.
*/
enablePlugin() {
if (this.enabled) {
return;
}
this.filtersRowsMap = this.hot.rowIndexMapper.registerMap(this.pluginName, new TrimmingMap());
this.dropdownMenuPlugin = this.hot.getPlugin('dropdownMenu');
const dropdownSettings = this.hot.getSettings().dropdownMenu;
const menuContainer = (dropdownSettings && dropdownSettings.uiContainer) || this.hot.rootDocument.body;
const addConfirmationHooks = (component) => {
component.addLocalHook('accept', () => this.onActionBarSubmit('accept'));
component.addLocalHook('cancel', () => this.onActionBarSubmit('cancel'));
component.addLocalHook('change', command => this.onComponentChange(component, command));
return component;
};
const filterByConditionLabel = () => `${this.hot.getTranslatedPhrase(constants.FILTERS_DIVS_FILTER_BY_CONDITION)}:`;
const filterValueLabel = () => `${this.hot.getTranslatedPhrase(constants.FILTERS_DIVS_FILTER_BY_VALUE)}:`;
if (!this.components.get('filter_by_condition')) {
const conditionComponent = new ConditionComponent(this.hot, {
id: 'filter_by_condition',
name: filterByConditionLabel,
addSeparator: false,
menuContainer
});
conditionComponent.addLocalHook('afterClose', () => this.onSelectUIClosed());
this.components.set('filter_by_condition', addConfirmationHooks(conditionComponent));
}
if (!this.components.get('filter_operators')) {
this.components.set('filter_operators', new OperatorsComponent(this.hot, {
id: 'filter_operators',
name: 'Operators'
}));
}
if (!this.components.get('filter_by_condition2')) {
const conditionComponent = new ConditionComponent(this.hot, {
id: 'filter_by_condition2',
name: '',
addSeparator: true,
menuContainer
});
conditionComponent.addLocalHook('afterClose', () => this.onSelectUIClosed());
this.components.set('filter_by_condition2', addConfirmationHooks(conditionComponent));
}
if (!this.components.get('filter_by_value')) {
this.components.set('filter_by_value', addConfirmationHooks(new ValueComponent(this.hot, {
id: 'filter_by_value',
name: filterValueLabel
})));
}
if (!this.components.get('filter_action_bar')) {
this.components.set('filter_action_bar', addConfirmationHooks(new ActionBarComponent(this.hot, {
id: 'filter_action_bar',
name: 'Action bar'
})));
}
if (!this.conditionCollection) {
this.conditionCollection = new ConditionCollection(this.hot);
}
if (!this.conditionUpdateObserver) {
this.conditionUpdateObserver = new ConditionUpdateObserver(
this.hot,
this.conditionCollection,
physicalColumn => this.getDataMapAtColumn(physicalColumn),
);
this.conditionUpdateObserver.addLocalHook('update', conditionState => this.updateComponents(conditionState));
}
this.components.forEach(component => component.show());
this.addHook('beforeDropdownMenuSetItems', items => this.onBeforeDropdownMenuSetItems(items));
this.addHook('afterDropdownMenuDefaultOptions',
defaultOptions => this.onAfterDropdownMenuDefaultOptions(defaultOptions));
this.addHook('afterDropdownMenuShow', () => this.onAfterDropdownMenuShow());
this.addHook('afterDropdownMenuHide', () => this.onAfterDropdownMenuHide());
this.addHook('afterChange', changes => this.onAfterChange(changes));
// Temp. solution (extending menu items bug in contextMenu/dropdownMenu)
if (this.hot.getSettings().dropdownMenu && this.dropdownMenuPlugin) {
this.dropdownMenuPlugin.disablePlugin();
this.dropdownMenuPlugin.enablePlugin();
}
super.enablePlugin();
}
/**
* Disables the plugin functionality for this Handsontable instance.
*/
disablePlugin() {
if (this.enabled) {
if (this.dropdownMenuPlugin?.enabled) {
this.dropdownMenuPlugin.menu.clearLocalHooks();
}
this.components.forEach((component, key) => {
component.destroy();
this.components.set(key, null);
});
this.conditionCollection.destroy();
this.conditionCollection = null;
this.hot.rowIndexMapper.unregisterMap(this.pluginName);
}
super.disablePlugin();
}
/* eslint-disable jsdoc/require-description-complete-sentence */
/**
* @memberof Filters#
* @function addCondition
* @description
* Adds condition to the conditions collection at specified column index.
*
* Possible predefined conditions:
* * `begins_with` - Begins with
* * `between` - Between
* * `by_value` - By value
* * `contains` - Contains
* * `date_after` - After a date
* * `date_before` - Before a date
* * `date_today` - Today
* * `date_tomorrow` - Tomorrow
* * `date_yesterday` - Yesterday
* * `empty` - Empty
* * `ends_with` - Ends with
* * `eq` - Equal
* * `gt` - Greater than
* * `gte` - Greater than or equal
* * `lt` - Less than
* * `lte` - Less than or equal
* * `none` - None (no filter)
* * `not_between` - Not between
* * `not_contains` - Not contains
* * `not_empty` - Not empty
* * `neq` - Not equal.
*
* Possible operations on collection of conditions:
* * `conjunction` - [**Conjunction**](https://en.wikipedia.org/wiki/Logical_conjunction) on conditions collection (by default), i.e. for such operation: <br/> c1 AND c2 AND c3 AND c4 ... AND cn === TRUE, where c1 ... cn are conditions.
* * `disjunction` - [**Disjunction**](https://en.wikipedia.org/wiki/Logical_disjunction) on conditions collection, i.e. for such operation: <br/> c1 OR c2 OR c3 OR c4 ... OR cn === TRUE, where c1, c2, c3, c4 ... cn are conditions.
* * `disjunctionWithExtraCondition` - **Disjunction** on first `n - 1`\* conditions from collection with an extra requirement computed from the last condition, i.e. for such operation: <br/> c1 OR c2 OR c3 OR c4 ... OR cn-1 AND cn === TRUE, where c1, c2, c3, c4 ... cn are conditions.
*
* \* when `n` is collection size; it's used i.e. for one operation introduced from UI (when choosing from filter's drop-down menu two conditions with OR operator between them, mixed with choosing values from the multiple choice select)
*
* **Note**: Mind that you cannot mix different types of operations (for instance, if you use `conjunction`, use it consequently for a particular column).
*
* @example
* ::: only-for javascript
* ```js
* const container = document.getElementById('example');
* const hot = new Handsontable(container, {
* data: getData(),
* filters: true
* });
*
* // access to filters plugin instance
* const filtersPlugin = hot.getPlugin('filters');
*
* // add filter "Greater than" 95 to column at index 1
* filtersPlugin.addCondition(1, 'gt', [95]);
* filtersPlugin.filter();
*
* // add filter "By value" to column at index 1
* // in this case all value's that don't match will be filtered.
* filtersPlugin.addCondition(1, 'by_value', [['ing', 'ed', 'as', 'on']]);
* filtersPlugin.filter();
*
* // add filter "Begins with" with value "de" AND "Not contains" with value "ing"
* filtersPlugin.addCondition(1, 'begins_with', ['de'], 'conjunction');
* filtersPlugin.addCondition(1, 'not_contains', ['ing'], 'conjunction');
* filtersPlugin.filter();
*
* // add filter "Begins with" with value "de" OR "Not contains" with value "ing"
* filtersPlugin.addCondition(1, 'begins_with', ['de'], 'disjunction');
* filtersPlugin.addCondition(1, 'not_contains', ['ing'], 'disjunction');
* filtersPlugin.filter();
* ```
* :::
*
* ::: only-for react
* ```jsx
* const hotRef = useRef(null);
*
* ...
*
* <HotTable
* ref={hotRef}
* data={getData()}
* filters={true}
* />
*
* // access to filters plugin instance
* const hot = hotRef.current.hotInstance;
* const filtersPlugin = hot.getPlugin('filters');
*
* // add filter "Greater than" 95 to column at index 1
* filtersPlugin.addCondition(1, 'gt', [95]);
* filtersPlugin.filter();
*
* // add filter "By value" to column at index 1
* // in this case all value's that don't match will be filtered.
* filtersPlugin.addCondition(1, 'by_value', [['ing', 'ed', 'as', 'on']]);
* filtersPlugin.filter();
*
* // add filter "Begins with" with value "de" AND "Not contains" with value "ing"
* filtersPlugin.addCondition(1, 'begins_with', ['de'], 'conjunction');
* filtersPlugin.addCondition(1, 'not_contains', ['ing'], 'conjunction');
* filtersPlugin.filter();
*
* // add filter "Begins with" with value "de" OR "Not contains" with value "ing"
* filtersPlugin.addCondition(1, 'begins_with', ['de'], 'disjunction');
* filtersPlugin.addCondition(1, 'not_contains', ['ing'], 'disjunction');
* filtersPlugin.filter();
* ```
* :::
*
* @param {number} column Visual column index.
* @param {string} name Condition short name.
* @param {Array} args Condition arguments.
* @param {string} [operationId=conjunction] `id` of operation which is performed on the column.
*/
/* eslint-enable jsdoc/require-description-complete-sentence */
addCondition(column, name, args, operationId = OPERATION_AND) {
const physicalColumn = this.hot.toPhysicalColumn(column);
this.conditionCollection.addCondition(physicalColumn, { command: { key: name }, args }, operationId);
}
/**
* Removes conditions at specified column index.
*
* @param {number} column Visual column index.
*/
removeConditions(column) {
const physicalColumn = this.hot.toPhysicalColumn(column);
this.conditionCollection.removeConditions(physicalColumn);
}
/**
* Clears all conditions previously added to the collection for the specified column index or, if the column index
* was not passed, clear the conditions for all columns.
*
* @param {number} [column] Visual column index.
*/
clearConditions(column) {
if (column === void 0) {
this.conditionCollection.clean();
} else {
const physicalColumn = this.hot.toPhysicalColumn(column);
this.conditionCollection.removeConditions(physicalColumn);
}
}
/**
* Filters data based on added filter conditions.
*
* @fires Hooks#beforeFilter
* @fires Hooks#afterFilter
*/
filter() {
const dataFilter = this._createDataFilter();
const needToFilter = !this.conditionCollection.isEmpty();
let visibleVisualRows = [];
const conditions = this.conditionCollection.exportAllConditions();
const allowFiltering = this.hot.runHooks('beforeFilter', conditions);
if (allowFiltering !== false) {
if (needToFilter) {
const trimmedRows = [];
this.hot.batchExecution(() => {
this.filtersRowsMap.clear();
visibleVisualRows = arrayMap(dataFilter.filter(), rowData => rowData.meta.visualRow);
const visibleVisualRowsAssertion = createArrayAssertion(visibleVisualRows);
rangeEach(this.hot.countSourceRows() - 1, (row) => {
if (!visibleVisualRowsAssertion(row)) {
trimmedRows.push(row);
}
});
arrayEach(trimmedRows, (physicalRow) => {
this.filtersRowsMap.setValueAtIndex(physicalRow, true);
});
}, true);
if (!visibleVisualRows.length) {
this.hot.deselectCell();
}
} else {
this.filtersRowsMap.clear();
}
}
this.hot.runHooks('afterFilter', conditions);
this.hot.view.adjustElementsSize(true);
this.hot.render();
this.clearColumnSelection();
}
/**
* Gets last selected column index.
*
* @returns {{visualIndex: number, physicalIndex: number} | null} Returns `null` when a column is
* not selected. Otherwise, returns an object with `visualIndex` and `physicalIndex` properties containing
* the index of the column.
*/
getSelectedColumn() {
const highlight = this.hot.getSelectedRangeLast()?.highlight;
if (!highlight) {
return null;
}
return {
visualIndex: highlight.col,
physicalIndex: this.hot.toPhysicalColumn(highlight.col),
};
}
/**
* Clears column selection.
*
* @private
*/
clearColumnSelection() {
const selectedColumn = this.getSelectedColumn();
if (selectedColumn !== null) {
this.hot.selectCell(0, selectedColumn.visualIndex);
}
}
/**
* Returns handsontable source data with cell meta based on current selection.
*
* @param {number} [column] The physical column index. By default column index accept the value of the selected column.
* @returns {Array} Returns array of objects where keys as row index.
*/
getDataMapAtColumn(column) {
const visualColumn = this.hot.toVisualColumn(column);
const data = [];
arrayEach(this.hot.getSourceDataAtCol(visualColumn), (value, rowIndex) => {
const { row, col, visualCol, visualRow, type, instance, dateFormat, locale } = this.hot
.getCellMeta(rowIndex, visualColumn);
const dataValue = this.hot.getDataAtCell(this.hot.toVisualRow(rowIndex), visualColumn) ?? value;
data.push({
meta: { row, col, visualCol, visualRow, type, instance, dateFormat, locale },
value: toEmptyString(dataValue),
});
});
return data;
}
/**
* `afterChange` listener.
*
* @private
* @param {Array} changes Array of changes.
*/
onAfterChange(changes) {
if (changes) {
arrayEach(changes, (change) => {
const [, prop] = change;
const columnIndex = this.hot.propToCol(prop);
if (this.conditionCollection.hasConditions(columnIndex)) {
this.updateValueComponentCondition(columnIndex);
}
});
}
}
/**
* Update the condition of ValueComponent, based on the handled changes.
*
* @private
* @param {number} columnIndex Column index of handled ValueComponent condition.
*/
updateValueComponentCondition(columnIndex) {
const dataAtCol = this.hot.getDataAtCol(columnIndex);
const selectedValues = unifyColumnValues(dataAtCol);
this.conditionUpdateObserver.updateStatesAtColumn(columnIndex, selectedValues);
}
/**
* Restores components to its saved state.
*
* @private
* @param {Array} components List of components.
*/
restoreComponents(components) {
const physicalIndex = this.getSelectedColumn()?.physicalIndex;
components.forEach((component) => {
if (component.isHidden()) {
return;
}
component.restoreState(physicalIndex);
});
this.updateDependentComponentsVisibility();
}
/**
* After dropdown menu show listener.
*
* @private
*/
onAfterDropdownMenuShow() {
this.restoreComponents(Array.from(this.components.values()));
}
/**
* After dropdown menu hide listener.
*
* @private
*/
onAfterDropdownMenuHide() {
this.components.get('filter_by_condition').getSelectElement().closeOptions();
this.components.get('filter_by_condition2').getSelectElement().closeOptions();
}
/**
* Before dropdown menu set menu items listener.
*
* @private
*/
onBeforeDropdownMenuSetItems() {
if (this.dropdownMenuPlugin) {
this.dropdownMenuPlugin.menu.addLocalHook('afterOpen', () => {
this.dropdownMenuPlugin.menu.hotMenu.updateSettings({ hiddenRows: true });
});
}
}
/**
* After dropdown menu default options listener.
*
* @private
* @param {object} defaultOptions ContextMenu default item options.
*/
onAfterDropdownMenuDefaultOptions(defaultOptions) {
defaultOptions.items.push({ name: SEPARATOR });
this.components.forEach((component) => {
defaultOptions.items.push(component.getMenuItemDescriptor());
});
}
/**
* Get an operation, based on the number and types of arguments (where arguments are states of components).
*
* @param {string} suggestedOperation Operation which was chosen by user from UI.
* @param {object} byConditionState1 State of first condition component.
* @param {object} byConditionState2 State of second condition component.
* @param {object} byValueState State of value component.
* @private
* @returns {string}
*/
getOperationBasedOnArguments(suggestedOperation, byConditionState1, byConditionState2, byValueState) {
let operation = suggestedOperation;
if (operation === OPERATION_OR && byConditionState1.command.key !== CONDITION_NONE &&
byConditionState2.command.key !== CONDITION_NONE && byValueState.command.key !== CONDITION_NONE) {
operation = OPERATION_OR_THEN_VARIABLE;
} else if (byValueState.command.key !== CONDITION_NONE) {
if (byConditionState1.command.key === CONDITION_NONE || byConditionState2.command.key === CONDITION_NONE) {
operation = OPERATION_AND;
}
}
return operation;
}
/**
* On action bar submit listener.
*
* @private
* @param {string} submitType The submit type.
*/
onActionBarSubmit(submitType) {
if (submitType === 'accept') {
const selectedColumn = this.getSelectedColumn();
if (selectedColumn === null) {
this.dropdownMenuPlugin?.close();
return;
}
const { physicalIndex } = selectedColumn;
const byConditionState1 = this.components.get('filter_by_condition').getState();
const byConditionState2 = this.components.get('filter_by_condition2').getState();
const byValueState = this.components.get('filter_by_value').getState();
const operation = this.getOperationBasedOnArguments(
this.components.get('filter_operators').getActiveOperationId(),
byConditionState1,
byConditionState2,
byValueState
);
this.conditionUpdateObserver.groupChanges();
let columnStackPosition = this.conditionCollection.getColumnStackPosition(physicalIndex);
if (columnStackPosition === -1) {
columnStackPosition = void 0;
}
this.conditionCollection.removeConditions(physicalIndex);
if (byConditionState1.command.key !== CONDITION_NONE) {
this.conditionCollection.addCondition(physicalIndex, byConditionState1, operation, columnStackPosition);
if (byConditionState2.command.key !== CONDITION_NONE) {
this.conditionCollection.addCondition(physicalIndex, byConditionState2, operation, columnStackPosition);
}
}
if (byValueState.command.key !== CONDITION_NONE) {
this.conditionCollection.addCondition(physicalIndex, byValueState, operation, columnStackPosition);
}
this.conditionUpdateObserver.flush();
this.components.forEach(component => component.saveState(physicalIndex));
this.filtersRowsMap.clear();
this.filter();
}
this.dropdownMenuPlugin?.close();
}
/**
* On component change listener.
*
* @private
* @param {BaseComponent} component Component inheriting BaseComponent.
* @param {object} command Menu item object (command).
*/
onComponentChange(component, command) {
this.updateDependentComponentsVisibility();
if (component.constructor === ConditionComponent && !command.inputsCount) {
this.setListeningDropdownMenu();
}
}
/**
* On component SelectUI closed listener.
*
* @private
*/
onSelectUIClosed() {
this.setListeningDropdownMenu();
}
/**
* Listen to the keyboard input on document body and forward events to instance of Handsontable
* created by DropdownMenu plugin.
*
* @private
*/
setListeningDropdownMenu() {
if (this.dropdownMenuPlugin) {
this.dropdownMenuPlugin.setListening();
}
}
/**
* Updates visibility of some of the components, based on the state of the parent component.
*
* @private
*/
updateDependentComponentsVisibility() {
const component = this.components.get('filter_by_condition');
const { command } = component.getState();
const componentsToShow = [
this.components.get('filter_by_condition2'),
this.components.get('filter_operators')
];
if (command.showOperators) {
this.showComponents(...componentsToShow);
} else {
this.hideComponents(...componentsToShow);
}
}
/**
* On after get column header listener.
*
* @private
* @param {number} col Visual column index.
* @param {HTMLTableCellElement} TH Header's TH element.
*/
onAfterGetColHeader(col, TH) {
const physicalColumn = this.hot.toPhysicalColumn(col);
if (this.enabled && this.conditionCollection.hasConditions(physicalColumn)) {
addClass(TH, 'htFiltersActive');
} else {
removeClass(TH, 'htFiltersActive');
}
}
/**
* Creates DataFilter instance based on condition collection.
*
* @private
* @param {ConditionCollection} conditionCollection Condition collection object.
* @returns {DataFilter}
*/
_createDataFilter(conditionCollection = this.conditionCollection) {
return new DataFilter(conditionCollection, physicalColumn => this.getDataMapAtColumn(physicalColumn));
}
/**
* It updates the components state. The state is triggered by ConditionUpdateObserver, which
* reacts to any condition added to the condition collection. It may be added through the UI
* components or by API call.
*
* @private
* @param {object} conditionsState An object with the state generated by UI components.
*/
updateComponents(conditionsState) {
if (!this.dropdownMenuPlugin?.enabled) {
return;
}
const {
editedConditionStack: {
conditions,
column,
}
} = conditionsState;
const conditionsByValue = conditions.filter(condition => condition.name === CONDITION_BY_VALUE);
const conditionsWithoutByValue = conditions.filter(condition => condition.name !== CONDITION_BY_VALUE);
if (conditionsByValue.length >= 2 || conditionsWithoutByValue.length >= 3) {
warn(toSingleLine`The filter conditions have been applied properly, but couldn’t be displayed visually.\x20
The overall amount of conditions exceed the capability of the dropdown menu.\x20
For more details see the documentation.`);
} else {
const operationType = this.conditionCollection.getOperation(column);
this.components.get('filter_by_condition').updateState(conditionsWithoutByValue[0], column);
this.components.get('filter_by_condition2').updateState(conditionsWithoutByValue[1], column);
this.components.get('filter_operators').updateState(operationType, column);
this.components.get('filter_by_value').updateState(conditionsState);
}
}
/**
* Returns indexes of passed components inside list of `dropdownMenu` items.
*
* @private
* @param {...BaseComponent} components List of components.
* @returns {Array}
*/
getIndexesOfComponents(...components) {
const indexes = [];
if (!this.dropdownMenuPlugin) {
return indexes;
}
const menu = this.dropdownMenuPlugin.menu;
arrayEach(components, (component) => {
arrayEach(menu.menuItems, (item, index) => {
if (item.key === component.getMenuItemDescriptor().key) {
indexes.push(index);
}
});
});
return indexes;
}
/**
* Changes visibility of component.
*
* @private
* @param {boolean} visible Determine if components should be visible.
* @param {...BaseComponent} components List of components.
*/
changeComponentsVisibility(visible = true, ...components) {
if (!this.dropdownMenuPlugin) {
return;
}
const menu = this.dropdownMenuPlugin.menu;
const hotMenu = menu.hotMenu;
const hiddenRows = hotMenu.getPlugin('hiddenRows');
const indexes = this.getIndexesOfComponents(...components);
if (visible) {
hiddenRows.showRows(indexes);
} else {
hiddenRows.hideRows(indexes);
}
hotMenu.render();
}
/**
* Hides components of filters `dropdownMenu`.
*
* @private
* @param {...BaseComponent} components List of components.
*/
hideComponents(...components) {
this.changeComponentsVisibility(false, ...components);
}
/**
* Shows components of filters `dropdownMenu`.
*
* @private
* @param {...BaseComponent} components List of components.
*/
showComponents(...components) {
this.changeComponentsVisibility(true, ...components);
}
/**
* Destroys the plugin instance.
*/
destroy() {
if (this.enabled) {
this.components.forEach((component, key) => {
if (component !== null) {
component.destroy();
this.components.set(key, null);
}
});
this.conditionCollection.destroy();
this.conditionUpdateObserver.destroy();
this.hot.rowIndexMapper.unregisterMap(this.pluginName);
}
super.destroy();
}
}