@revolist/revogrid 4.12.12 → 4.13.2

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.
Files changed (95) hide show
  1. package/dist/cjs/{column.drag.plugin-0ce0b39a.js → column.drag.plugin-0f367fe1.js} +2 -1
  2. package/dist/cjs/column.drag.plugin-0f367fe1.js.map +1 -0
  3. package/dist/cjs/column.service-b59380a3.js.map +1 -1
  4. package/dist/cjs/{sorting.sign-a1e9d97a.js → grouping.row.renderer-d6119ced.js} +6 -6
  5. package/dist/cjs/grouping.row.renderer-d6119ced.js.map +1 -0
  6. package/dist/cjs/index.cjs.js +7 -6
  7. package/dist/cjs/index.cjs.js.map +1 -1
  8. package/dist/cjs/revo-grid.cjs.entry.js +2 -2
  9. package/dist/cjs/revo-grid.cjs.entry.js.map +1 -1
  10. package/dist/cjs/revogr-data_4.cjs.entry.js +5 -5
  11. package/dist/cjs/revogr-data_4.cjs.entry.js.map +1 -1
  12. package/dist/cjs/revogr-filter-panel.cjs.entry.js +1 -1
  13. package/dist/cjs/revogr-filter-panel.cjs.entry.js.map +1 -1
  14. package/dist/collection/components/revoGrid/revo-grid-style.css +109 -197
  15. package/dist/collection/plugins/filter/filter.style.css +12 -25
  16. package/dist/collection/plugins/sorting/sorting.plugin.js +2 -0
  17. package/dist/collection/plugins/sorting/sorting.plugin.js.map +1 -1
  18. package/dist/collection/store/selection/selection.store.js.map +1 -1
  19. package/dist/esm/{column.drag.plugin-017c4fb3.js → column.drag.plugin-d201beb7.js} +2 -2
  20. package/dist/esm/{column.drag.plugin-017c4fb3.js.map → column.drag.plugin-d201beb7.js.map} +1 -1
  21. package/dist/esm/column.service-f39c0a1d.js.map +1 -1
  22. package/dist/esm/{sorting.sign-c02e3b12.js → grouping.row.renderer-95f32c6b.js} +6 -6
  23. package/dist/esm/grouping.row.renderer-95f32c6b.js.map +1 -0
  24. package/dist/esm/index.js +3 -3
  25. package/dist/esm/revo-grid.entry.js +2 -2
  26. package/dist/esm/revo-grid.entry.js.map +1 -1
  27. package/dist/esm/revogr-data_4.entry.js +1 -1
  28. package/dist/esm/revogr-filter-panel.entry.js +1 -1
  29. package/dist/esm/revogr-filter-panel.entry.js.map +1 -1
  30. package/dist/revo-grid/app-globals-6b929fd8.js +8 -1
  31. package/dist/revo-grid/app-globals-6b929fd8.js.map +1 -1
  32. package/dist/revo-grid/column.drag.plugin-d201beb7.js +2522 -0
  33. package/dist/revo-grid/column.drag.plugin-d201beb7.js.map +1 -0
  34. package/dist/revo-grid/column.service-f39c0a1d.js +1293 -1
  35. package/dist/revo-grid/column.service-f39c0a1d.js.map +1 -1
  36. package/dist/revo-grid/debounce-b3166f78.js +491 -1
  37. package/dist/revo-grid/debounce-b3166f78.js.map +1 -1
  38. package/dist/revo-grid/dimension.helpers-5567e424.js +3608 -1
  39. package/dist/revo-grid/dimension.helpers-5567e424.js.map +1 -1
  40. package/dist/revo-grid/edit.utils-b59306be.js +13 -1
  41. package/dist/revo-grid/edit.utils-b59306be.js.map +1 -1
  42. package/dist/revo-grid/events-cf0893a3.js +38 -1
  43. package/dist/revo-grid/events-cf0893a3.js.map +1 -1
  44. package/dist/revo-grid/filter.button-84396156.js +34 -1
  45. package/dist/revo-grid/filter.button-84396156.js.map +1 -1
  46. package/dist/revo-grid/grouping.row.renderer-95f32c6b.js +65 -0
  47. package/dist/revo-grid/grouping.row.renderer-95f32c6b.js.map +1 -0
  48. package/dist/revo-grid/header-cell-renderer-31f53644.js +335 -1
  49. package/dist/revo-grid/header-cell-renderer-31f53644.js.map +1 -1
  50. package/dist/revo-grid/index-f6fae858.js +2090 -2
  51. package/dist/revo-grid/index-f6fae858.js.map +1 -1
  52. package/dist/revo-grid/index.esm.js +160 -1
  53. package/dist/revo-grid/index.esm.js.map +1 -1
  54. package/dist/revo-grid/key.utils-3632161b.js +85 -1
  55. package/dist/revo-grid/key.utils-3632161b.js.map +1 -1
  56. package/dist/revo-grid/resize-observer-83c9e167.js +501 -1
  57. package/dist/revo-grid/resize-observer-83c9e167.js.map +1 -1
  58. package/dist/revo-grid/revo-grid.entry.js +1943 -1
  59. package/dist/revo-grid/revo-grid.entry.js.map +1 -1
  60. package/dist/revo-grid/revo-grid.esm.js +21 -1
  61. package/dist/revo-grid/revo-grid.esm.js.map +1 -1
  62. package/dist/revo-grid/revogr-attribution_7.entry.js +1446 -1
  63. package/dist/revo-grid/revogr-attribution_7.entry.js.map +1 -1
  64. package/dist/revo-grid/revogr-clipboard_3.entry.js +455 -1
  65. package/dist/revo-grid/revogr-clipboard_3.entry.js.map +1 -1
  66. package/dist/revo-grid/revogr-data_4.entry.js +960 -1
  67. package/dist/revo-grid/revogr-data_4.entry.js.map +1 -1
  68. package/dist/revo-grid/revogr-filter-panel.entry.js +340 -1
  69. package/dist/revo-grid/revogr-filter-panel.entry.js.map +1 -1
  70. package/dist/revo-grid/text-editor-e47e56c3.js +74 -1
  71. package/dist/revo-grid/text-editor-e47e56c3.js.map +1 -1
  72. package/dist/revo-grid/throttle-dec28f5b.js +229 -1
  73. package/dist/revo-grid/throttle-dec28f5b.js.map +1 -1
  74. package/dist/revo-grid/viewport.helpers-7e7f9dad.js +48 -1
  75. package/dist/revo-grid/viewport.helpers-7e7f9dad.js.map +1 -1
  76. package/dist/revo-grid/viewport.store-c18a25a6.js +402 -1
  77. package/dist/revo-grid/viewport.store-c18a25a6.js.map +1 -1
  78. package/dist/types/plugins/sorting/sorting.plugin.d.ts +2 -0
  79. package/dist/types/store/selection/selection.store.d.ts +1 -1
  80. package/hydrate/index.js +7 -7
  81. package/hydrate/index.mjs +7 -7
  82. package/package.json +1 -1
  83. package/standalone/column.service.js.map +1 -1
  84. package/standalone/index.js +1 -1
  85. package/standalone/revo-grid.js +2 -2
  86. package/standalone/revo-grid.js.map +1 -1
  87. package/standalone/revogr-filter-panel.js +1 -1
  88. package/standalone/revogr-filter-panel.js.map +1 -1
  89. package/dist/cjs/column.drag.plugin-0ce0b39a.js.map +0 -1
  90. package/dist/cjs/sorting.sign-a1e9d97a.js.map +0 -1
  91. package/dist/esm/sorting.sign-c02e3b12.js.map +0 -1
  92. package/dist/revo-grid/column.drag.plugin-017c4fb3.js +0 -5
  93. package/dist/revo-grid/column.drag.plugin-017c4fb3.js.map +0 -1
  94. package/dist/revo-grid/sorting.sign-c02e3b12.js +0 -5
  95. package/dist/revo-grid/sorting.sign-c02e3b12.js.map +0 -1
@@ -0,0 +1,2522 @@
1
+ /*!
2
+ * Built by Revolist OU ❤️
3
+ */
4
+ import { H as reduce, I as baseEach, A as getColumnType, s as isGrouping, r as getGroupingName, z as getCellDataParsed, F as getColumnByProp, y as getCellRaw, f as GROUP_EXPANDED, v as getParsedGroup, b as PSEUDO_GROUP_ITEM_ID, w as isSameGroup, G as GROUP_DEPTH, d as PSEUDO_GROUP_ITEM_VALUE, m as GROUPING_ROW_TYPE, o as getSource, e as PSEUDO_GROUP_COLUMN, q as gatherGrouping, t as isGroupingColumn, p as getExpanded, C as isColGrouping } from './column.service-f39c0a1d.js';
5
+ import { W as createStore, w as setStore, i as calculateDimensionData, X as identity, Y as isArray, b as getSourceItem, o as getScrollbarSize, Z as toInteger, _ as isIterateeCall, u as timeout, $ as baseProperty, a0 as isArrayLike, a1 as getTag, a2 as baseKeys, g as getPhysical, e as setItems, j as getItemByPosition } from './dimension.helpers-5567e424.js';
6
+ import { f as calculateRowHeaderSize } from './viewport.store-c18a25a6.js';
7
+ import { h } from './index-f6fae858.js';
8
+ import { b as FILTER_PROP, i as isFilterBtn } from './filter.button-84396156.js';
9
+ import { i as isObjectLike, b as baseGetTag, d as debounce } from './debounce-b3166f78.js';
10
+ import { d as dispatch, O as ON_COLUMN_CLICK } from './header-cell-renderer-31f53644.js';
11
+
12
+ /**
13
+ * Plugin which recalculates realSize on changes of sizes, originItemSize and count
14
+ */
15
+ const recalculateRealSizePlugin = (storeService) => {
16
+ /**
17
+ * Recalculates realSize if size, origin size or count changes
18
+ */
19
+ return {
20
+ /**
21
+ * Reacts on changes of count, sizes and originItemSize
22
+ */
23
+ set(k) {
24
+ switch (k) {
25
+ case 'count':
26
+ case 'sizes':
27
+ case 'originItemSize': {
28
+ // recalculate realSize
29
+ let realSize = 0;
30
+ const count = storeService.store.get('count');
31
+ for (let i = 0; i < count; i++) {
32
+ realSize +=
33
+ storeService.store.get('sizes')[i] ||
34
+ storeService.store.get('originItemSize');
35
+ }
36
+ storeService.setStore({ realSize });
37
+ break;
38
+ }
39
+ }
40
+ },
41
+ };
42
+ };
43
+
44
+ /**
45
+ * Plugin for trimming
46
+ *
47
+ * 1.a. Retrieves the previous sizes value. Saves the resulting trimmed data as a new sizes value.
48
+ * 1.b. Stores a reference to the trimmed data to prevent further changes.
49
+ * 2. Removes multiple and shifts the data based on the trimmed value.
50
+ */
51
+ const trimmedPlugin = (storeService) => {
52
+ let trimmingObject = null;
53
+ let trimmedPreviousSizes = null;
54
+ return {
55
+ set(key, val) {
56
+ switch (key) {
57
+ case 'sizes': {
58
+ // prevent changes after trimming
59
+ if (trimmingObject && trimmingObject === val) {
60
+ trimmingObject = null;
61
+ return;
62
+ }
63
+ trimmedPreviousSizes = null;
64
+ break;
65
+ }
66
+ case 'trimmed': {
67
+ const trim = val;
68
+ if (!trimmedPreviousSizes) {
69
+ trimmedPreviousSizes = storeService.store.get('sizes');
70
+ }
71
+ trimmingObject = removeMultipleAndShift(trimmedPreviousSizes, trim || {});
72
+ // save a reference to the trimmed object to prevent changes after trimming
73
+ storeService.setSizes(trimmingObject);
74
+ break;
75
+ }
76
+ }
77
+ },
78
+ };
79
+ };
80
+ function removeMultipleAndShift(items, toRemove) {
81
+ const newItems = {};
82
+ const sortedIndexes = Object.keys(items || {})
83
+ .map(Number)
84
+ .sort((a, b) => a - b);
85
+ const lastIndex = sortedIndexes[sortedIndexes.length - 1];
86
+ let shift = 0;
87
+ for (let i = 0; i <= lastIndex; i++) {
88
+ if (toRemove[i] !== undefined) {
89
+ shift++;
90
+ // skip already removed
91
+ if (items[i] !== undefined) {
92
+ continue;
93
+ }
94
+ }
95
+ if (items[i] !== undefined) {
96
+ newItems[i - shift] = items[i];
97
+ }
98
+ }
99
+ return newItems;
100
+ }
101
+
102
+ /**
103
+ * Storing pre-calculated
104
+ * Dimension information and sizes
105
+ */
106
+ function initialBase() {
107
+ return {
108
+ indexes: [],
109
+ count: 0,
110
+ // hidden items
111
+ trimmed: null,
112
+ // virtual item index to size
113
+ sizes: {},
114
+ // order in indexes[] to coordinate
115
+ positionIndexToItem: {},
116
+ // initial element to coordinate ^
117
+ indexToItem: {},
118
+ positionIndexes: [],
119
+ };
120
+ }
121
+ function initialState() {
122
+ return Object.assign(Object.assign({}, initialBase()), {
123
+ // size which all items can take
124
+ realSize: 0,
125
+ // initial item size if it wasn't changed
126
+ originItemSize: 0 });
127
+ }
128
+ class DimensionStore {
129
+ constructor(type) {
130
+ this.type = type;
131
+ this.store = createStore(initialState());
132
+ this.store.use(trimmedPlugin({
133
+ store: this.store,
134
+ setSizes: this.setDimensionSize.bind(this),
135
+ }));
136
+ this.store.use(recalculateRealSizePlugin({
137
+ store: this.store,
138
+ setStore: this.setStore.bind(this),
139
+ }));
140
+ }
141
+ getCurrentState() {
142
+ const state = initialState();
143
+ const keys = Object.keys(state);
144
+ return reduce(keys, (r, k) => {
145
+ const data = this.store.get(k);
146
+ r[k] = data;
147
+ return r;
148
+ }, state);
149
+ }
150
+ dispose() {
151
+ setStore(this.store, initialState());
152
+ }
153
+ setStore(data) {
154
+ setStore(this.store, data);
155
+ }
156
+ drop() {
157
+ setStore(this.store, initialBase());
158
+ }
159
+ /**
160
+ * Set custom dimension sizes and overwrite old
161
+ * Generates new indexes based on sizes
162
+ * @param sizes - sizes to set
163
+ */
164
+ setDimensionSize(sizes = {}) {
165
+ const dimensionData = calculateDimensionData(this.store.get('originItemSize'), sizes);
166
+ setStore(this.store, Object.assign(Object.assign({}, dimensionData), { sizes }));
167
+ }
168
+ updateSizesPositionByIndexes(newItemsOrder, prevItemsOrder = []) {
169
+ // Move custom sizes to new order
170
+ const customSizes = Object.assign({}, this.store.get('sizes'));
171
+ if (!Object.keys(customSizes).length) {
172
+ return;
173
+ }
174
+ // Step 1: Create a map of original indices, but allow duplicates by storing arrays of indices
175
+ const originalIndices = {};
176
+ prevItemsOrder.forEach((physIndex, virtIndex) => {
177
+ if (!originalIndices[physIndex]) {
178
+ originalIndices[physIndex] = [];
179
+ }
180
+ originalIndices[physIndex].push(virtIndex); // Store all indices for each value
181
+ });
182
+ // Step 2: Create new sizes based on new item order
183
+ const newSizes = {};
184
+ newItemsOrder.forEach((physIndex, virtIndex) => {
185
+ const indices = originalIndices[physIndex]; // Get all original indices for this value
186
+ if (indices && indices.length > 0) {
187
+ const originalIndex = indices.shift(); // Get the first available original index
188
+ if (originalIndex !== undefined && originalIndex !== virtIndex && customSizes[originalIndex]) {
189
+ newSizes[virtIndex] = customSizes[originalIndex];
190
+ delete customSizes[originalIndex];
191
+ }
192
+ }
193
+ });
194
+ // Step 3: Set new sizes if there are changes
195
+ if (Object.keys(newSizes).length) {
196
+ this.setDimensionSize(Object.assign(Object.assign({}, customSizes), newSizes));
197
+ }
198
+ }
199
+ }
200
+
201
+ const rowTypes = ['rowPinStart', 'rgRow', 'rowPinEnd'];
202
+ const columnTypes = [
203
+ 'colPinStart',
204
+ 'rgCol',
205
+ 'colPinEnd',
206
+ ];
207
+ function isRowType(type) {
208
+ return rowTypes.indexOf(type) > -1;
209
+ }
210
+
211
+ /**
212
+ * Base layer for plugins
213
+ * Provide minimal starting core for plugins to work
214
+ * Extend this class to create plugin
215
+ */
216
+ class BasePlugin {
217
+ constructor(revogrid, providers) {
218
+ this.revogrid = revogrid;
219
+ this.providers = providers;
220
+ this.h = h;
221
+ this.subscriptions = {};
222
+ }
223
+ /**
224
+ *
225
+ * @param eventName - event name to subscribe to in revo-grid component (e.g. 'beforeheaderclick')
226
+ * @param callback - callback function for event
227
+ */
228
+ addEventListener(eventName, callback) {
229
+ this.revogrid.addEventListener(eventName, callback);
230
+ this.subscriptions[eventName] = callback;
231
+ }
232
+ /**
233
+ * Subscribe to property change in revo-grid component
234
+ * You can return false in callback to prevent default value set
235
+ *
236
+ * @param prop - property name
237
+ * @param callback - callback function
238
+ * @param immediate - trigger callback immediately with current value
239
+ */
240
+ watch(prop, callback, { immediate } = { immediate: false }) {
241
+ const nativeValueDesc = Object.getOwnPropertyDescriptor(this.revogrid, prop) ||
242
+ Object.getOwnPropertyDescriptor(this.revogrid.constructor.prototype, prop);
243
+ // Overwrite property descriptor for this instance
244
+ Object.defineProperty(this.revogrid, prop, {
245
+ set(val) {
246
+ var _a;
247
+ const keepDefault = callback(val);
248
+ if (keepDefault === false) {
249
+ return;
250
+ }
251
+ // Continue with native behavior
252
+ return (_a = nativeValueDesc === null || nativeValueDesc === void 0 ? void 0 : nativeValueDesc.set) === null || _a === void 0 ? void 0 : _a.call(this, val);
253
+ },
254
+ get() {
255
+ var _a;
256
+ // Continue with native behavior
257
+ return (_a = nativeValueDesc === null || nativeValueDesc === void 0 ? void 0 : nativeValueDesc.get) === null || _a === void 0 ? void 0 : _a.call(this);
258
+ },
259
+ });
260
+ if (immediate) {
261
+ callback(nativeValueDesc === null || nativeValueDesc === void 0 ? void 0 : nativeValueDesc.value);
262
+ }
263
+ }
264
+ /**
265
+ * Remove event listener
266
+ * @param eventName
267
+ */
268
+ removeEventListener(eventName) {
269
+ this.revogrid.removeEventListener(eventName, this.subscriptions[eventName]);
270
+ delete this.subscriptions[eventName];
271
+ }
272
+ /**
273
+ * Emit event from revo-grid component
274
+ * Event can be cancelled by calling event.preventDefault() in callback
275
+ */
276
+ emit(eventName, detail) {
277
+ const event = new CustomEvent(eventName, { detail, cancelable: true });
278
+ this.revogrid.dispatchEvent(event);
279
+ return event;
280
+ }
281
+ /**
282
+ * Clear all subscriptions
283
+ */
284
+ clearSubscriptions() {
285
+ for (let type in this.subscriptions) {
286
+ this.removeEventListener(type);
287
+ }
288
+ }
289
+ /**
290
+ * Destroy plugin and clear all subscriptions
291
+ */
292
+ destroy() {
293
+ this.clearSubscriptions();
294
+ }
295
+ }
296
+
297
+ /**
298
+ * A specialized version of `_.forEach` for arrays without support for
299
+ * iteratee shorthands.
300
+ *
301
+ * @private
302
+ * @param {Array} [array] The array to iterate over.
303
+ * @param {Function} iteratee The function invoked per iteration.
304
+ * @returns {Array} Returns `array`.
305
+ */
306
+ function arrayEach(array, iteratee) {
307
+ var index = -1,
308
+ length = array == null ? 0 : array.length;
309
+
310
+ while (++index < length) {
311
+ if (iteratee(array[index], index, array) === false) {
312
+ break;
313
+ }
314
+ }
315
+ return array;
316
+ }
317
+
318
+ /**
319
+ * Casts `value` to `identity` if it's not a function.
320
+ *
321
+ * @private
322
+ * @param {*} value The value to inspect.
323
+ * @returns {Function} Returns cast function.
324
+ */
325
+ function castFunction(value) {
326
+ return typeof value == 'function' ? value : identity;
327
+ }
328
+
329
+ /**
330
+ * Iterates over elements of `collection` and invokes `iteratee` for each element.
331
+ * The iteratee is invoked with three arguments: (value, index|key, collection).
332
+ * Iteratee functions may exit iteration early by explicitly returning `false`.
333
+ *
334
+ * **Note:** As with other "Collections" methods, objects with a "length"
335
+ * property are iterated like arrays. To avoid this behavior use `_.forIn`
336
+ * or `_.forOwn` for object iteration.
337
+ *
338
+ * @static
339
+ * @memberOf _
340
+ * @since 0.1.0
341
+ * @alias each
342
+ * @category Collection
343
+ * @param {Array|Object} collection The collection to iterate over.
344
+ * @param {Function} [iteratee=_.identity] The function invoked per iteration.
345
+ * @returns {Array|Object} Returns `collection`.
346
+ * @see _.forEachRight
347
+ * @example
348
+ *
349
+ * _.forEach([1, 2], function(value) {
350
+ * console.log(value);
351
+ * });
352
+ * // => Logs `1` then `2`.
353
+ *
354
+ * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
355
+ * console.log(key);
356
+ * });
357
+ * // => Logs 'a' then 'b' (iteration order is not guaranteed).
358
+ */
359
+ function forEach(collection, iteratee) {
360
+ var func = isArray(collection) ? arrayEach : baseEach;
361
+ return func(collection, castFunction(iteratee));
362
+ }
363
+
364
+ /**
365
+ * Plugin module for revo-grid grid system
366
+ * Add support for automatic column resize
367
+ */
368
+ const LETTER_BLOCK_SIZE = 7;
369
+ class AutoSizeColumnPlugin extends BasePlugin {
370
+ constructor(revogrid, providers, config) {
371
+ super(revogrid, providers);
372
+ this.providers = providers;
373
+ this.config = config;
374
+ this.autoSizeColumns = null;
375
+ /** for edge case when no columns defined before data */
376
+ this.dataResolve = null;
377
+ this.dataReject = null;
378
+ this.letterBlockSize = (config === null || config === void 0 ? void 0 : config.letterBlockSize) || LETTER_BLOCK_SIZE;
379
+ // create test container to check text width
380
+ if (config === null || config === void 0 ? void 0 : config.preciseSize) {
381
+ this.precsizeCalculationArea = this.initiatePresizeElement();
382
+ revogrid.appendChild(this.precsizeCalculationArea);
383
+ }
384
+ const aftersourceset = ({ detail: { source }, }) => {
385
+ this.setSource(source);
386
+ };
387
+ const beforecolumnsset = ({ detail: { columns }, }) => {
388
+ this.columnSet(columns);
389
+ };
390
+ this.addEventListener('beforecolumnsset', beforecolumnsset);
391
+ switch (config === null || config === void 0 ? void 0 : config.mode) {
392
+ case "autoSizeOnTextOverlap" /* ColumnAutoSizeMode.autoSizeOnTextOverlap */:
393
+ this.addEventListener('aftersourceset', aftersourceset);
394
+ this.addEventListener('afteredit', ({ detail }) => {
395
+ this.afteredit(detail);
396
+ });
397
+ break;
398
+ case "autoSizeAll" /* ColumnAutoSizeMode.autoSizeAll */:
399
+ this.addEventListener('aftersourceset', aftersourceset);
400
+ this.addEventListener('afteredit', ({ detail }) => {
401
+ this.afterEditAll(detail);
402
+ });
403
+ break;
404
+ default:
405
+ this.addEventListener('headerdblclick', ({ detail }) => {
406
+ const type = getColumnType(detail.column);
407
+ const size = this.getColumnSize(detail.index, type);
408
+ if (size) {
409
+ this.providers.dimension.setCustomSizes(type, {
410
+ [detail.index]: size,
411
+ }, true);
412
+ }
413
+ });
414
+ break;
415
+ }
416
+ }
417
+ async setSource(source) {
418
+ let autoSize = this.autoSizeColumns;
419
+ if (this.dataReject) {
420
+ this.dataReject();
421
+ this.clearPromise();
422
+ }
423
+ /** If data set first and no column provided await until get one */
424
+ if (!autoSize) {
425
+ const request = new Promise((resolve, reject) => {
426
+ this.dataResolve = resolve;
427
+ this.dataReject = reject;
428
+ });
429
+ try {
430
+ autoSize = await request;
431
+ }
432
+ catch (e) {
433
+ return;
434
+ }
435
+ }
436
+ // calculate sizes
437
+ forEach(autoSize, (_v, type) => {
438
+ const sizes = {};
439
+ forEach(autoSize[type], rgCol => {
440
+ // calculate size
441
+ rgCol.size = sizes[rgCol.index] = source.reduce((prev, rgRow) => Math.max(prev, this.getLength(rgRow[rgCol.prop])), this.getLength(rgCol.name || ''));
442
+ });
443
+ this.providers.dimension.setCustomSizes(type, sizes, true);
444
+ });
445
+ }
446
+ getLength(len) {
447
+ var _a;
448
+ const padding = 15;
449
+ if (!len) {
450
+ return 0;
451
+ }
452
+ try {
453
+ const str = len.toString();
454
+ /**if exact calculation required proxy with html element, slow operation */
455
+ if ((_a = this.config) === null || _a === void 0 ? void 0 : _a.preciseSize) {
456
+ this.precsizeCalculationArea.innerText = str;
457
+ return this.precsizeCalculationArea.scrollWidth + padding * 2;
458
+ }
459
+ return str.length * this.letterBlockSize + padding * 2;
460
+ }
461
+ catch (e) {
462
+ return 0;
463
+ }
464
+ }
465
+ afteredit(e) {
466
+ let data;
467
+ if (this.isRangeEdit(e)) {
468
+ data = e.data;
469
+ }
470
+ else {
471
+ data = { 0: { [e.prop]: e.val } };
472
+ }
473
+ forEach(this.autoSizeColumns, (columns, type) => {
474
+ const sizes = {};
475
+ forEach(columns, rgCol => {
476
+ var _a;
477
+ // calculate size
478
+ const size = reduce(data, (prev, rgRow) => {
479
+ if (typeof rgRow[rgCol.prop] === 'undefined') {
480
+ return prev;
481
+ }
482
+ return Math.max(prev || 0, this.getLength(rgRow[rgCol.prop]));
483
+ }, undefined);
484
+ if (size && ((_a = rgCol.size) !== null && _a !== void 0 ? _a : 0) < size) {
485
+ rgCol.size = sizes[rgCol.index] = size;
486
+ }
487
+ });
488
+ this.providers.dimension.setCustomSizes(type, sizes, true);
489
+ });
490
+ }
491
+ afterEditAll(e) {
492
+ const props = {};
493
+ if (this.isRangeEdit(e)) {
494
+ forEach(e.data, r => forEach(r, (_v, p) => (props[p] = true)));
495
+ }
496
+ else {
497
+ props[e.prop] = true;
498
+ }
499
+ forEach(this.autoSizeColumns, (columns, type) => {
500
+ const sizes = {};
501
+ forEach(columns, rgCol => {
502
+ if (props[rgCol.prop]) {
503
+ const size = this.getColumnSize(rgCol.index, type);
504
+ if (size) {
505
+ sizes[rgCol.index] = size;
506
+ }
507
+ }
508
+ });
509
+ this.providers.dimension.setCustomSizes(type, sizes, true);
510
+ });
511
+ }
512
+ getColumnSize(index, type) {
513
+ var _a, _b;
514
+ const rgCol = (_b = (_a = this.autoSizeColumns) === null || _a === void 0 ? void 0 : _a[type]) === null || _b === void 0 ? void 0 : _b[index];
515
+ if (!rgCol) {
516
+ return 0;
517
+ }
518
+ return reduce(this.providers.data.stores, (r, s) => {
519
+ const perStore = reduce(s.store.get('items'), (prev, _row, i) => {
520
+ const item = getSourceItem(s.store, i);
521
+ return Math.max(prev || 0, this.getLength(item === null || item === void 0 ? void 0 : item[rgCol.prop]));
522
+ }, 0);
523
+ return Math.max(r, perStore);
524
+ }, rgCol.size || 0);
525
+ }
526
+ columnSet(columns) {
527
+ var _a;
528
+ for (let t of columnTypes) {
529
+ const type = t;
530
+ const cols = columns[type];
531
+ for (let i in cols) {
532
+ if (cols[i].autoSize || ((_a = this.config) === null || _a === void 0 ? void 0 : _a.allColumns)) {
533
+ if (!this.autoSizeColumns) {
534
+ this.autoSizeColumns = {};
535
+ }
536
+ if (!this.autoSizeColumns[type]) {
537
+ this.autoSizeColumns[type] = {};
538
+ }
539
+ this.autoSizeColumns[type][i] = Object.assign(Object.assign({}, cols[i]), { index: parseInt(i, 10) });
540
+ }
541
+ }
542
+ }
543
+ if (this.dataResolve) {
544
+ this.dataResolve(this.autoSizeColumns || {});
545
+ this.clearPromise();
546
+ }
547
+ }
548
+ clearPromise() {
549
+ this.dataResolve = null;
550
+ this.dataReject = null;
551
+ }
552
+ isRangeEdit(e) {
553
+ return !!e.data;
554
+ }
555
+ initiatePresizeElement() {
556
+ var _a;
557
+ const styleForFontTest = {
558
+ position: 'absolute',
559
+ fontSize: '14px',
560
+ height: '0',
561
+ width: '0',
562
+ whiteSpace: 'nowrap',
563
+ top: '0',
564
+ overflowX: 'scroll',
565
+ display: 'block',
566
+ };
567
+ const el = document.createElement('div');
568
+ for (let s in styleForFontTest) {
569
+ el.style[s] = (_a = styleForFontTest[s]) !== null && _a !== void 0 ? _a : '';
570
+ }
571
+ el.classList.add('revo-test-container');
572
+ return el;
573
+ }
574
+ destroy() {
575
+ var _a;
576
+ super.destroy();
577
+ (_a = this.precsizeCalculationArea) === null || _a === void 0 ? void 0 : _a.remove();
578
+ }
579
+ }
580
+
581
+ class StretchColumn extends BasePlugin {
582
+ constructor(revogrid, providers) {
583
+ super(revogrid, providers);
584
+ this.providers = providers;
585
+ this.stretchedColumn = null;
586
+ // calculate scroll bar size for current user session
587
+ this.scrollSize = getScrollbarSize(document);
588
+ // subscribe to column changes
589
+ const beforecolumnapplied = ({ detail: { columns }, }) => this.applyStretch(columns);
590
+ this.addEventListener('beforecolumnapplied', beforecolumnapplied);
591
+ }
592
+ setScroll({ type, hasScroll }) {
593
+ var _a;
594
+ if (type === 'rgRow' &&
595
+ this.stretchedColumn &&
596
+ ((_a = this.stretchedColumn) === null || _a === void 0 ? void 0 : _a.initialSize) === this.stretchedColumn.size) {
597
+ if (hasScroll) {
598
+ this.stretchedColumn.size -= this.scrollSize;
599
+ this.apply();
600
+ this.dropChanges();
601
+ }
602
+ }
603
+ }
604
+ activateChanges() {
605
+ const setScroll = ({ detail }) => this.setScroll(detail);
606
+ this.addEventListener('scrollchange', setScroll);
607
+ }
608
+ dropChanges() {
609
+ this.stretchedColumn = null;
610
+ this.removeEventListener('scrollchange');
611
+ }
612
+ apply() {
613
+ if (!this.stretchedColumn) {
614
+ return;
615
+ }
616
+ const type = 'rgCol';
617
+ const sizes = this.providers.dimension.stores[type].store.get('sizes');
618
+ this.providers.dimension.setCustomSizes(type, Object.assign(Object.assign({}, sizes), { [this.stretchedColumn.index]: this.stretchedColumn.size }), true);
619
+ }
620
+ /**
621
+ * Apply stretch changes
622
+ */
623
+ applyStretch(columns) {
624
+ // unsubscribe from all events
625
+ this.dropChanges();
626
+ // calculate grid size
627
+ let sizeDifference = this.revogrid.clientWidth - 1;
628
+ forEach(columns, (_, type) => {
629
+ const realSize = this.providers.dimension.stores[type].store.get('realSize');
630
+ sizeDifference -= realSize;
631
+ });
632
+ if (this.revogrid.rowHeaders) {
633
+ const itemsLength = this.providers.data.stores.rgRow.store.get('source').length;
634
+ const header = this.revogrid.rowHeaders;
635
+ const rowHeaderSize = calculateRowHeaderSize(itemsLength, typeof header === 'object' ? header : undefined);
636
+ if (rowHeaderSize) {
637
+ sizeDifference -= rowHeaderSize;
638
+ }
639
+ }
640
+ if (sizeDifference > 0) {
641
+ // currently plugin accepts last column only
642
+ const index = columns.rgCol.length - 1;
643
+ const last = columns.rgCol[index];
644
+ /**
645
+ * has column
646
+ * no auto size applied
647
+ * size for column shouldn't be defined
648
+ */
649
+ const colSize = (last === null || last === void 0 ? void 0 : last.size) || this.revogrid.colSize || 0;
650
+ const size = sizeDifference + colSize - 1;
651
+ if (last && !last.autoSize && colSize < size) {
652
+ this.stretchedColumn = {
653
+ initialSize: size,
654
+ index,
655
+ size,
656
+ };
657
+ this.apply();
658
+ this.activateChanges();
659
+ }
660
+ }
661
+ }
662
+ }
663
+ /**
664
+ * Check plugin type is Stretch
665
+ */
666
+ function isStretchPlugin(plugin) {
667
+ return !!plugin.applyStretch;
668
+ }
669
+
670
+ /**
671
+ * The base implementation of `_.clamp` which doesn't coerce arguments.
672
+ *
673
+ * @private
674
+ * @param {number} number The number to clamp.
675
+ * @param {number} [lower] The lower bound.
676
+ * @param {number} upper The upper bound.
677
+ * @returns {number} Returns the clamped number.
678
+ */
679
+ function baseClamp(number, lower, upper) {
680
+ if (number === number) {
681
+ if (upper !== undefined) {
682
+ number = number <= upper ? number : upper;
683
+ }
684
+ if (lower !== undefined) {
685
+ number = number >= lower ? number : lower;
686
+ }
687
+ }
688
+ return number;
689
+ }
690
+
691
+ /** Used as references for the maximum length and index of an array. */
692
+ var MAX_ARRAY_LENGTH = 4294967295;
693
+
694
+ /**
695
+ * Converts `value` to an integer suitable for use as the length of an
696
+ * array-like object.
697
+ *
698
+ * **Note:** This method is based on
699
+ * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
700
+ *
701
+ * @static
702
+ * @memberOf _
703
+ * @since 4.0.0
704
+ * @category Lang
705
+ * @param {*} value The value to convert.
706
+ * @returns {number} Returns the converted integer.
707
+ * @example
708
+ *
709
+ * _.toLength(3.2);
710
+ * // => 3
711
+ *
712
+ * _.toLength(Number.MIN_VALUE);
713
+ * // => 0
714
+ *
715
+ * _.toLength(Infinity);
716
+ * // => 4294967295
717
+ *
718
+ * _.toLength('3.2');
719
+ * // => 3
720
+ */
721
+ function toLength(value) {
722
+ return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;
723
+ }
724
+
725
+ /**
726
+ * The base implementation of `_.fill` without an iteratee call guard.
727
+ *
728
+ * @private
729
+ * @param {Array} array The array to fill.
730
+ * @param {*} value The value to fill `array` with.
731
+ * @param {number} [start=0] The start position.
732
+ * @param {number} [end=array.length] The end position.
733
+ * @returns {Array} Returns `array`.
734
+ */
735
+ function baseFill(array, value, start, end) {
736
+ var length = array.length;
737
+
738
+ start = toInteger(start);
739
+ if (start < 0) {
740
+ start = -start > length ? 0 : (length + start);
741
+ }
742
+ end = (end === undefined || end > length) ? length : toInteger(end);
743
+ if (end < 0) {
744
+ end += length;
745
+ }
746
+ end = start > end ? 0 : toLength(end);
747
+ while (start < end) {
748
+ array[start++] = value;
749
+ }
750
+ return array;
751
+ }
752
+
753
+ /**
754
+ * Fills elements of `array` with `value` from `start` up to, but not
755
+ * including, `end`.
756
+ *
757
+ * **Note:** This method mutates `array`.
758
+ *
759
+ * @static
760
+ * @memberOf _
761
+ * @since 3.2.0
762
+ * @category Array
763
+ * @param {Array} array The array to fill.
764
+ * @param {*} value The value to fill `array` with.
765
+ * @param {number} [start=0] The start position.
766
+ * @param {number} [end=array.length] The end position.
767
+ * @returns {Array} Returns `array`.
768
+ * @example
769
+ *
770
+ * var array = [1, 2, 3];
771
+ *
772
+ * _.fill(array, 'a');
773
+ * console.log(array);
774
+ * // => ['a', 'a', 'a']
775
+ *
776
+ * _.fill(Array(3), 2);
777
+ * // => [2, 2, 2]
778
+ *
779
+ * _.fill([4, 6, 8, 10], '*', 1, 3);
780
+ * // => [4, '*', '*', 10]
781
+ */
782
+ function fill(array, value, start, end) {
783
+ var length = array == null ? 0 : array.length;
784
+ if (!length) {
785
+ return [];
786
+ }
787
+ if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {
788
+ start = 0;
789
+ end = length;
790
+ }
791
+ return baseFill(array, value, start, end);
792
+ }
793
+
794
+ const INITIAL = {
795
+ mime: 'text/csv',
796
+ fileKind: 'csv',
797
+ // BOM signature
798
+ bom: true,
799
+ columnDelimiter: ',',
800
+ rowDelimiter: '\r\n',
801
+ encoding: '',
802
+ };
803
+ // The ASCII character code 13 is called a Carriage Return or CR.
804
+ const CARRIAGE_RETURN = String.fromCharCode(13);
805
+ // Chr(13) followed by a Chr(10) that compose a proper CRLF.
806
+ const LINE_FEED = String.fromCharCode(10);
807
+ const DOUBLE_QT = String.fromCharCode(34);
808
+ const NO_BREAK_SPACE = String.fromCharCode(0xfeff);
809
+ const escapeRegex = new RegExp('"', 'g');
810
+ class ExportCsv {
811
+ constructor(options = {}) {
812
+ this.options = Object.assign(Object.assign({}, INITIAL), options);
813
+ }
814
+ doExport({ data, headers, props }) {
815
+ let result = this.options.bom ? NO_BREAK_SPACE : '';
816
+ // any header
817
+ if ((headers === null || headers === void 0 ? void 0 : headers.length) > 0) {
818
+ headers.forEach(header => {
819
+ // ignore empty
820
+ if (!header.length) {
821
+ return;
822
+ }
823
+ result += this.prepareHeader(header, this.options.columnDelimiter);
824
+ result += this.options.rowDelimiter;
825
+ });
826
+ }
827
+ data.forEach((rgRow, index) => {
828
+ if (index > 0) {
829
+ result += this.options.rowDelimiter;
830
+ }
831
+ // support grouping
832
+ if (isGrouping(rgRow)) {
833
+ result += this.parseCell(getGroupingName(rgRow), this.options.columnDelimiter);
834
+ return;
835
+ }
836
+ result += props.map(p => this.parseCell(rgRow[p], this.options.columnDelimiter)).join(this.options.columnDelimiter);
837
+ });
838
+ return result;
839
+ }
840
+ prepareHeader(columnHeaders, columnDelimiter) {
841
+ let result = '';
842
+ const newColumnHeaders = columnHeaders.map(v => this.parseCell(v, columnDelimiter, true));
843
+ result += newColumnHeaders.join(columnDelimiter);
844
+ return result;
845
+ }
846
+ parseCell(value, columnDelimiter, force = false) {
847
+ let escape = value;
848
+ if (typeof value !== 'string') {
849
+ escape = JSON.stringify(value);
850
+ }
851
+ const toEscape = [CARRIAGE_RETURN, DOUBLE_QT, LINE_FEED, columnDelimiter];
852
+ if (typeof escape === 'undefined') {
853
+ return '';
854
+ }
855
+ if (escape !== '' && (force || toEscape.some(i => escape.indexOf(i) >= 0))) {
856
+ return `"${escape.replace(escapeRegex, '""')}"`;
857
+ }
858
+ return escape;
859
+ }
860
+ }
861
+
862
+ var ExportTypes;
863
+ (function (ExportTypes) {
864
+ ExportTypes["csv"] = "csv";
865
+ })(ExportTypes || (ExportTypes = {}));
866
+ class ExportFilePlugin extends BasePlugin {
867
+ /** Exports string */
868
+ async exportString(options = {}, t = ExportTypes.csv) {
869
+ const data = await this.beforeexport();
870
+ if (!data) {
871
+ return null;
872
+ }
873
+ return this.formatter(t, options).doExport(data);
874
+ }
875
+ /** Exports Blob */
876
+ async exportBlob(options = {}, t = ExportTypes.csv) {
877
+ return await this.getBlob(this.formatter(t, options));
878
+ }
879
+ /** Export file */
880
+ async exportFile(options = {}, t = ExportTypes.csv) {
881
+ const formatter = this.formatter(t, options);
882
+ // url
883
+ const URL = window.URL || window.webkitURL;
884
+ const a = document.createElement('a');
885
+ const { filename, fileKind } = formatter.options;
886
+ const name = `${filename}.${fileKind}`;
887
+ const blob = await this.getBlob(formatter);
888
+ const url = blob ? URL.createObjectURL(blob) : '';
889
+ a.style.display = 'none';
890
+ a.setAttribute('href', url);
891
+ a.setAttribute('download', name);
892
+ this.revogrid.appendChild(a);
893
+ a.dispatchEvent(new MouseEvent('click'));
894
+ this.revogrid.removeChild(a);
895
+ // delay for revoke, correct for some browsers
896
+ await timeout(120);
897
+ URL.revokeObjectURL(url);
898
+ }
899
+ /** Blob object */
900
+ async getBlob(formatter) {
901
+ const type = `${formatter.options.mime};charset=${formatter.options.encoding}`;
902
+ if (typeof Blob !== 'undefined') {
903
+ const data = await this.beforeexport();
904
+ if (!data) {
905
+ return null;
906
+ }
907
+ return new Blob([formatter.doExport(data)], { type });
908
+ }
909
+ return null;
910
+ }
911
+ // before event
912
+ async beforeexport() {
913
+ let data = await this.getData();
914
+ const event = this.emit('beforeexport', { data });
915
+ if (event.defaultPrevented) {
916
+ return null;
917
+ }
918
+ return event.detail.data;
919
+ }
920
+ async getData() {
921
+ const data = await this.getSource();
922
+ const colSource = [];
923
+ const colPromises = [];
924
+ columnTypes.forEach((t, i) => {
925
+ colPromises.push(this.getColPerSource(t).then(s => (colSource[i] = s)));
926
+ });
927
+ await Promise.all(colPromises);
928
+ const columns = {
929
+ headers: [],
930
+ props: [],
931
+ };
932
+ for (let source of colSource) {
933
+ source.headers.forEach((h, i) => {
934
+ if (!columns.headers[i]) {
935
+ columns.headers[i] = [];
936
+ }
937
+ columns.headers[i].push(...h);
938
+ });
939
+ columns.props.push(...source.props);
940
+ }
941
+ return Object.assign({ data }, columns);
942
+ }
943
+ async getColPerSource(t) {
944
+ const store = await this.revogrid.getColumnStore(t);
945
+ const source = store.get('source');
946
+ const virtualIndexes = store.get('items');
947
+ const depth = store.get('groupingDepth');
948
+ const groups = store.get('groups');
949
+ const colNames = [];
950
+ const colProps = [];
951
+ const visibleItems = virtualIndexes.reduce((r, v, virtualIndex) => {
952
+ const prop = source[v].prop;
953
+ colNames.push(source[v].name || '');
954
+ colProps.push(prop);
955
+ r[prop] = virtualIndex;
956
+ return r;
957
+ }, {});
958
+ const rows = this.getGroupHeaders(depth, groups, virtualIndexes, visibleItems);
959
+ rows.push(colNames);
960
+ return {
961
+ headers: rows,
962
+ props: colProps,
963
+ };
964
+ }
965
+ getGroupHeaders(depth, groups, items, visibleItems) {
966
+ const rows = [];
967
+ const template = fill(new Array(items.length), '');
968
+ for (let d = 0; d < depth; d++) {
969
+ const rgRow = [...template];
970
+ rows.push(rgRow);
971
+ if (!groups[d]) {
972
+ continue;
973
+ }
974
+ const levelGroups = groups[d];
975
+ // add names of groups
976
+ levelGroups.forEach((group) => {
977
+ const minIndex = this.findGroupStartIndex(group.ids, visibleItems);
978
+ if (typeof minIndex === 'number') {
979
+ rgRow[minIndex] = group.name;
980
+ }
981
+ });
982
+ }
983
+ return rows;
984
+ }
985
+ findGroupStartIndex(ids, visibleItems) {
986
+ let min;
987
+ ids.forEach(id => {
988
+ const current = visibleItems[id];
989
+ if (typeof current === 'number') {
990
+ if (typeof min !== 'number' || min > current) {
991
+ min = current;
992
+ }
993
+ }
994
+ });
995
+ return min;
996
+ }
997
+ async getSource() {
998
+ const data = [];
999
+ const promisesData = [];
1000
+ rowTypes.forEach(t => {
1001
+ const dataPart = [];
1002
+ data.push(dataPart);
1003
+ const promise = this.revogrid.getVisibleSource(t).then((d) => dataPart.push(...d));
1004
+ promisesData.push(promise);
1005
+ });
1006
+ await Promise.all(promisesData);
1007
+ return data.reduce((r, v) => {
1008
+ r.push(...v);
1009
+ return r;
1010
+ }, []);
1011
+ }
1012
+ // get correct class for future multiple types support
1013
+ formatter(type, options = {}) {
1014
+ switch (type) {
1015
+ case ExportTypes.csv:
1016
+ return new ExportCsv(options);
1017
+ default:
1018
+ throw new Error('Unknown format');
1019
+ }
1020
+ }
1021
+ }
1022
+
1023
+ const eq = (value, extra) => {
1024
+ if (typeof value === 'undefined' || (value === null && !extra)) {
1025
+ return true;
1026
+ }
1027
+ if (typeof value !== 'string') {
1028
+ value = JSON.stringify(value);
1029
+ }
1030
+ const filterVal = extra === null || extra === void 0 ? void 0 : extra.toString().toLocaleLowerCase();
1031
+ if ((filterVal === null || filterVal === void 0 ? void 0 : filterVal.length) === 0) {
1032
+ return true;
1033
+ }
1034
+ return value.toLocaleLowerCase() === filterVal;
1035
+ };
1036
+ const notEq = (value, extra) => !eq(value, extra);
1037
+ notEq.extra = 'input';
1038
+ eq.extra = 'input';
1039
+
1040
+ const gtThan = function (value, extra) {
1041
+ let conditionValue;
1042
+ if (typeof value === 'number' && typeof extra !== 'undefined' && extra !== null) {
1043
+ conditionValue = parseFloat(extra === null || extra === void 0 ? void 0 : extra.toString());
1044
+ return value > conditionValue;
1045
+ }
1046
+ return false;
1047
+ };
1048
+ gtThan.extra = 'input';
1049
+
1050
+ const gtThanEq = function (value, extra) {
1051
+ return eq(value, extra) || gtThan(value, extra);
1052
+ };
1053
+ gtThanEq.extra = 'input';
1054
+
1055
+ const lt = function (value, extra) {
1056
+ let conditionValue;
1057
+ if (typeof value === 'number' && typeof extra !== 'undefined' && extra !== null) {
1058
+ conditionValue = parseFloat(extra.toString());
1059
+ return value < conditionValue;
1060
+ }
1061
+ else {
1062
+ return false;
1063
+ }
1064
+ };
1065
+ lt.extra = 'input';
1066
+
1067
+ const lsEq = function (value, extra) {
1068
+ return eq(value, extra) || lt(value, extra);
1069
+ };
1070
+ lsEq.extra = 'input';
1071
+
1072
+ const set = (value) => !(value === '' || value === null || value === void 0);
1073
+ const notSet = (value) => !set(value);
1074
+
1075
+ const beginsWith = (value, extra) => {
1076
+ if (!value) {
1077
+ return false;
1078
+ }
1079
+ if (!extra) {
1080
+ return true;
1081
+ }
1082
+ if (typeof value !== 'string') {
1083
+ value = JSON.stringify(value);
1084
+ }
1085
+ if (typeof extra !== 'string') {
1086
+ extra = JSON.stringify(extra);
1087
+ }
1088
+ return value.toLocaleLowerCase().indexOf(extra.toLocaleLowerCase()) === 0;
1089
+ };
1090
+ beginsWith.extra = 'input';
1091
+
1092
+ const contains = (value, extra) => {
1093
+ if (!extra) {
1094
+ return true;
1095
+ }
1096
+ if (!value) {
1097
+ return false;
1098
+ }
1099
+ if (extra) {
1100
+ if (typeof value !== 'string') {
1101
+ value = JSON.stringify(value);
1102
+ }
1103
+ return value.toLocaleLowerCase().indexOf(extra.toString().toLowerCase()) > -1;
1104
+ }
1105
+ return true;
1106
+ };
1107
+ const notContains = (value, extra) => {
1108
+ return !contains(value, extra);
1109
+ };
1110
+ notContains.extra = 'input';
1111
+ contains.extra = 'input';
1112
+
1113
+ // filter.indexed.ts
1114
+ const filterCoreFunctionsIndexedByType = {
1115
+ none: () => true,
1116
+ empty: notSet,
1117
+ notEmpty: set,
1118
+ eq: eq,
1119
+ notEq: notEq,
1120
+ begins: beginsWith,
1121
+ contains: contains,
1122
+ notContains: notContains,
1123
+ eqN: eq,
1124
+ neqN: notEq,
1125
+ gt: gtThan,
1126
+ gte: gtThanEq,
1127
+ lt: lt,
1128
+ lte: lsEq,
1129
+ };
1130
+ const filterTypes = {
1131
+ string: ['notEmpty', 'empty', 'eq', 'notEq', 'begins', 'contains', 'notContains'],
1132
+ number: ['notEmpty', 'empty', 'eqN', 'neqN', 'gt', 'gte', 'lt', 'lte'],
1133
+ };
1134
+ const filterNames = {
1135
+ none: 'None',
1136
+ empty: 'Not set',
1137
+ notEmpty: 'Set',
1138
+ eq: 'Equal',
1139
+ notEq: 'Not equal',
1140
+ begins: 'Begins with',
1141
+ contains: 'Contains',
1142
+ notContains: 'Does not contain',
1143
+ eqN: '=',
1144
+ neqN: '!=',
1145
+ gt: '>',
1146
+ gte: '>=',
1147
+ lt: '<',
1148
+ lte: '<=',
1149
+ };
1150
+
1151
+ // filter.plugin.tsx
1152
+ const FILTER_TRIMMED_TYPE = 'filter';
1153
+ const FILTER_CONFIG_CHANGED_EVENT = 'filterconfigchanged';
1154
+ const FILTE_PANEL = 'revogr-filter-panel';
1155
+ /**
1156
+ * @typedef ColumnFilterConfig
1157
+ * @type {object}
1158
+ *
1159
+ * @property {MultiFilterItem|undefined} multiFilterItems - data for multi filtering with relation
1160
+ *
1161
+ * @property {Record<ColumnProp, FilterCollectionItem>|undefined} collection - preserved filter data, relation for filters will be applied as 'and'
1162
+ *
1163
+ * @property {string[]|undefined} include - filters to be included, if defined everything else out of scope will be ignored
1164
+ *
1165
+ * @property {Record<string, CustomFilter>|undefined} customFilters - hash map of {FilterType:CustomFilter}.
1166
+ *
1167
+ * @property {FilterLocalization|undefined} localization - translation for filter popup captions.
1168
+ *
1169
+ * @property {boolean|undefined} disableDynamicFiltering - disables dynamic filtering. A way to apply filters on Save only.
1170
+ */
1171
+ /**
1172
+ * @internal
1173
+ */
1174
+ class FilterPlugin extends BasePlugin {
1175
+ constructor(revogrid, providers, config) {
1176
+ var _a;
1177
+ super(revogrid, providers);
1178
+ this.revogrid = revogrid;
1179
+ this.config = config;
1180
+ this.filterCollection = {};
1181
+ this.multiFilterItems = {};
1182
+ /**
1183
+ * Filter types
1184
+ * @example
1185
+ * {
1186
+ * string: ['contains', 'beginswith'],
1187
+ * number: ['eqN', 'neqN', 'gt']
1188
+ * }
1189
+ */
1190
+ this.filterByType = Object.assign({}, filterTypes);
1191
+ this.filterNameIndexByType = Object.assign({}, filterNames);
1192
+ this.filterFunctionsIndexedByType = Object.assign({}, filterCoreFunctionsIndexedByType);
1193
+ this.filterProp = FILTER_PROP;
1194
+ if (config) {
1195
+ this.initConfig(config);
1196
+ }
1197
+ const existingNodes = this.revogrid.registerVNode.filter(n => typeof n === 'object' && n.$tag$ !== FILTE_PANEL);
1198
+ this.revogrid.registerVNode = [
1199
+ ...existingNodes,
1200
+ h("revogr-filter-panel", { filterNames: this.filterNameIndexByType, filterEntities: this.filterFunctionsIndexedByType, filterCaptions: (_a = config === null || config === void 0 ? void 0 : config.localization) === null || _a === void 0 ? void 0 : _a.captions, onFilterChange: e => this.onFilterChange(e.detail), onResetChange: e => this.onFilterReset(e.detail), disableDynamicFiltering: config === null || config === void 0 ? void 0 : config.disableDynamicFiltering, ref: e => (this.pop = e) },
1201
+ ' ',
1202
+ this.extraContent()),
1203
+ ];
1204
+ const aftersourceset = async () => {
1205
+ const filterCollectionProps = Object.keys(this.filterCollection);
1206
+ if (filterCollectionProps.length > 0) {
1207
+ // handle old way of filtering by reworking FilterCollection to new MultiFilterItem
1208
+ filterCollectionProps.forEach((prop, index) => {
1209
+ if (!this.multiFilterItems[prop]) {
1210
+ this.multiFilterItems[prop] = [
1211
+ {
1212
+ id: index,
1213
+ type: this.filterCollection[prop].type,
1214
+ value: this.filterCollection[prop].value,
1215
+ relation: 'and',
1216
+ },
1217
+ ];
1218
+ }
1219
+ });
1220
+ }
1221
+ if (Object.keys(this.multiFilterItems).length === 0) {
1222
+ return;
1223
+ }
1224
+ await this.runFiltering(this.multiFilterItems);
1225
+ };
1226
+ this.addEventListener('headerclick', e => this.headerclick(e));
1227
+ this.addEventListener(FILTER_CONFIG_CHANGED_EVENT, ({ detail }) => {
1228
+ if (!detail ||
1229
+ (typeof detail === 'object' &&
1230
+ (!detail.multiFilterItems ||
1231
+ !Object.keys(detail.multiFilterItems).length))) {
1232
+ this.clearFiltering();
1233
+ return;
1234
+ }
1235
+ if (typeof detail === 'object') {
1236
+ this.initConfig(detail);
1237
+ }
1238
+ aftersourceset();
1239
+ });
1240
+ this.addEventListener('aftersourceset', aftersourceset);
1241
+ this.addEventListener('filter', ({ detail }) => this.onFilterChange(detail));
1242
+ }
1243
+ beforeshow(_) {
1244
+ // used as hook for filter panel
1245
+ }
1246
+ extraContent() {
1247
+ return null;
1248
+ }
1249
+ initConfig(config) {
1250
+ if (config.multiFilterItems) {
1251
+ this.multiFilterItems = Object.assign({}, config.multiFilterItems);
1252
+ }
1253
+ else {
1254
+ this.multiFilterItems = {};
1255
+ }
1256
+ // Add custom filters
1257
+ if (config.customFilters) {
1258
+ for (let customFilterType in config.customFilters) {
1259
+ const cFilter = config.customFilters[customFilterType];
1260
+ if (!this.filterByType[cFilter.columnFilterType]) {
1261
+ this.filterByType[cFilter.columnFilterType] = [];
1262
+ }
1263
+ // add custom filter type
1264
+ this.filterByType[cFilter.columnFilterType].push(customFilterType);
1265
+ // add custom filter function
1266
+ this.filterFunctionsIndexedByType[customFilterType] = cFilter.func;
1267
+ // add custom filter name
1268
+ this.filterNameIndexByType[customFilterType] = cFilter.name;
1269
+ }
1270
+ }
1271
+ // Add filterProp if provided in config
1272
+ if (config.filterProp) {
1273
+ this.filterProp = config.filterProp;
1274
+ }
1275
+ /**
1276
+ * which filters has to be included/excluded
1277
+ * convenient way to exclude system filters
1278
+ */
1279
+ const cfgInlcude = config.include;
1280
+ if (cfgInlcude) {
1281
+ const filters = {};
1282
+ for (let t in this.filterByType) {
1283
+ // validate filters, if appropriate function present
1284
+ const newTypes = this.filterByType[t].filter(f => cfgInlcude.indexOf(f) > -1);
1285
+ if (newTypes.length) {
1286
+ filters[t] = newTypes;
1287
+ }
1288
+ }
1289
+ // if any valid filters provided show them
1290
+ if (Object.keys(filters).length > 0) {
1291
+ this.filterByType = filters;
1292
+ }
1293
+ }
1294
+ if (config.collection) {
1295
+ const filtersWithFilterFunctionPresent = Object.entries(config.collection).filter(([, item]) => this.filterFunctionsIndexedByType[item.type]);
1296
+ this.filterCollection = Object.fromEntries(filtersWithFilterFunctionPresent);
1297
+ }
1298
+ else {
1299
+ this.filterCollection = {};
1300
+ }
1301
+ if (config.localization) {
1302
+ if (config.localization.filterNames) {
1303
+ Object.entries(config.localization.filterNames).forEach(([k, v]) => {
1304
+ if (this.filterNameIndexByType[k] != void 0) {
1305
+ this.filterNameIndexByType[k] = v;
1306
+ }
1307
+ });
1308
+ }
1309
+ }
1310
+ }
1311
+ async headerclick(e) {
1312
+ var _a, _b;
1313
+ const el = (_a = e.detail.originalEvent) === null || _a === void 0 ? void 0 : _a.target;
1314
+ if (!isFilterBtn(el)) {
1315
+ return;
1316
+ }
1317
+ e.preventDefault();
1318
+ if (!this.pop) {
1319
+ return;
1320
+ }
1321
+ // filter button clicked, open filter dialog
1322
+ const gridPos = this.revogrid.getBoundingClientRect();
1323
+ const buttonPos = el.getBoundingClientRect();
1324
+ const prop = e.detail.prop;
1325
+ const data = Object.assign(Object.assign(Object.assign({}, e.detail), this.filterCollection[prop]), { x: buttonPos.x - gridPos.x, y: buttonPos.y - gridPos.y + buttonPos.height, autoCorrect: true, filterTypes: this.getColumnFilter(e.detail.filter), filterItems: this.multiFilterItems, extraContent: this.extraHyperContent });
1326
+ (_b = this.beforeshow) === null || _b === void 0 ? void 0 : _b.call(this, data);
1327
+ this.pop.show(data);
1328
+ }
1329
+ getColumnFilter(type) {
1330
+ let filterType = 'string';
1331
+ if (!type) {
1332
+ return { [filterType]: this.filterByType[filterType] };
1333
+ }
1334
+ // if custom column filter
1335
+ if (this.isValidType(type)) {
1336
+ filterType = type;
1337
+ // if multiple filters applied
1338
+ }
1339
+ else if (typeof type === 'object' && type.length) {
1340
+ return type.reduce((r, multiType) => {
1341
+ if (this.isValidType(multiType)) {
1342
+ r[multiType] = this.filterByType[multiType];
1343
+ }
1344
+ return r;
1345
+ }, {});
1346
+ }
1347
+ return { [filterType]: this.filterByType[filterType] };
1348
+ }
1349
+ isValidType(type) {
1350
+ return !!(typeof type === 'string' && this.filterByType[type]);
1351
+ }
1352
+ /**
1353
+ * Called on internal component change
1354
+ */
1355
+ async onFilterChange(filterItems) {
1356
+ // store the filter items
1357
+ this.multiFilterItems = filterItems;
1358
+ // run the filtering when the items change
1359
+ this.runFiltering(this.multiFilterItems);
1360
+ }
1361
+ onFilterReset(prop) {
1362
+ delete this.multiFilterItems[prop !== null && prop !== void 0 ? prop : ''];
1363
+ this.onFilterChange(this.multiFilterItems);
1364
+ }
1365
+ /**
1366
+ * Triggers grid filtering
1367
+ */
1368
+ async doFiltering(collection, source, columns, filterItems) {
1369
+ const columnsToUpdate = [];
1370
+ /**
1371
+ * Loop through the columns and update the columns that need to be updated with the `hasFilter` property.
1372
+ */
1373
+ const columnByProp = {};
1374
+ columns.forEach(rgCol => {
1375
+ const column = Object.assign({}, rgCol);
1376
+ const hasFilter = filterItems[column.prop];
1377
+ columnByProp[column.prop] = column;
1378
+ /**
1379
+ * If the column has a filter and it's not already marked as filtered, update the column.
1380
+ */
1381
+ if (column[this.filterProp] && !hasFilter) {
1382
+ delete column[this.filterProp];
1383
+ columnsToUpdate.push(column);
1384
+ }
1385
+ /**
1386
+ * If the column does not have a filter and it's marked as filtered, update the column.
1387
+ */
1388
+ if (!column[this.filterProp] && hasFilter) {
1389
+ columnsToUpdate.push(column);
1390
+ column[this.filterProp] = true;
1391
+ }
1392
+ });
1393
+ const itemsToTrim = this.getRowFilter(source, filterItems, columnByProp);
1394
+ // check is filter event prevented
1395
+ const { defaultPrevented, detail } = this.emit('beforefiltertrimmed', {
1396
+ collection,
1397
+ itemsToFilter: itemsToTrim,
1398
+ source,
1399
+ filterItems,
1400
+ });
1401
+ if (defaultPrevented) {
1402
+ return;
1403
+ }
1404
+ this.providers.data.setTrimmed({ [FILTER_TRIMMED_TYPE]: detail.itemsToFilter });
1405
+ // applies the hasFilter to the columns to show filter icon
1406
+ this.providers.column.updateColumns(columnsToUpdate);
1407
+ this.emit('afterfilterapply', {
1408
+ multiFilterItems: filterItems,
1409
+ source,
1410
+ collection,
1411
+ });
1412
+ }
1413
+ async clearFiltering() {
1414
+ this.multiFilterItems = {};
1415
+ await this.runFiltering(this.multiFilterItems);
1416
+ }
1417
+ async runFiltering(multiFilterItems) {
1418
+ const collection = {};
1419
+ // handle old filterCollection to return the first filter only (if any) from multiFilterItems
1420
+ const filterProps = Object.keys(multiFilterItems);
1421
+ for (const prop of filterProps) {
1422
+ // check if we have any filter for a column
1423
+ if (multiFilterItems[prop].length > 0) {
1424
+ const firstFilterItem = multiFilterItems[prop][0];
1425
+ collection[prop] = {
1426
+ type: firstFilterItem.type,
1427
+ value: firstFilterItem.value,
1428
+ };
1429
+ }
1430
+ }
1431
+ this.filterCollection = collection;
1432
+ const columns = this.providers.column.getColumns();
1433
+ // run the filtering on the main source only
1434
+ const source = this.providers.data.stores['rgRow'].store.get('source');
1435
+ const { defaultPrevented, detail } = this.emit('beforefilterapply', {
1436
+ collection: this.filterCollection,
1437
+ source,
1438
+ columns,
1439
+ filterItems: this.multiFilterItems,
1440
+ });
1441
+ if (defaultPrevented) {
1442
+ return;
1443
+ }
1444
+ this.doFiltering(detail.collection, detail.source, detail.columns, detail.filterItems);
1445
+ }
1446
+ /**
1447
+ * Get trimmed rows based on filter
1448
+ */
1449
+ getRowFilter(rows, filterItems, columnByProp) {
1450
+ const propKeys = Object.keys(filterItems);
1451
+ const trimmed = {};
1452
+ // each rows
1453
+ for (let rowIndex = 0; rowIndex < rows.length; rowIndex++) {
1454
+ // check filter by column properties
1455
+ for (const prop of propKeys) {
1456
+ // add to the list of removed/trimmed rows of filter condition is satisfied
1457
+ if (this.shouldTrimRow(filterItems[prop], prop, columnByProp[prop], rows[rowIndex])) {
1458
+ trimmed[rowIndex] = true;
1459
+ }
1460
+ } // end of for-of propKeys
1461
+ }
1462
+ return trimmed;
1463
+ }
1464
+ shouldTrimRow(propFilters, prop, column, model = {}) {
1465
+ // reset the count of satisfied filters
1466
+ let propFilterSatisfiedCount = 0;
1467
+ // reset the array of last filter results
1468
+ let lastFilterResults = [];
1469
+ // testing each filter for a prop
1470
+ for (const [filterIndex, filterData] of propFilters.entries()) {
1471
+ // the filter LogicFunction based on the type
1472
+ const filterFunc = this.filterFunctionsIndexedByType[filterData.type];
1473
+ // THE MAGIC OF FILTERING IS HERE
1474
+ // If there is no column but user wants to filter by a property
1475
+ const value = column ? getCellDataParsed(model, column) : model[prop];
1476
+ // OR relation
1477
+ if (filterData.relation === 'or') {
1478
+ // reset the array of last filter results
1479
+ lastFilterResults = [];
1480
+ // if the filter is satisfied, continue to the next filter
1481
+ if (filterFunc(value, filterData.value)) {
1482
+ continue;
1483
+ }
1484
+ // if the filter is not satisfied, count it
1485
+ propFilterSatisfiedCount++;
1486
+ // AND relation
1487
+ }
1488
+ else {
1489
+ // 'and' relation will need to know the next filter
1490
+ // so we save this current filter to include it in the next filter
1491
+ lastFilterResults.push(!filterFunc(value, filterData.value));
1492
+ if (isFinalAndFilter(filterIndex, propFilters)) {
1493
+ // let's just continue since for sure propFilterSatisfiedCount cannot be satisfied
1494
+ if (allAndConditionsSatisfied(lastFilterResults)) {
1495
+ // reset the array of last filter results
1496
+ lastFilterResults = [];
1497
+ continue;
1498
+ }
1499
+ // we need to add all of the lastFilterResults since we need to satisfy all
1500
+ propFilterSatisfiedCount += lastFilterResults.length;
1501
+ // reset the array of last filter results
1502
+ lastFilterResults = [];
1503
+ }
1504
+ }
1505
+ } // end of propFilters forEach
1506
+ return propFilterSatisfiedCount === propFilters.length;
1507
+ }
1508
+ }
1509
+ /**
1510
+ * Checks if the current filter is the final one in an AND sequence.
1511
+ * @param index - Current filter index in the list.
1512
+ * @param filters - Array of filters for the property.
1513
+ * @returns True if this is the last AND condition; false otherwise.
1514
+ */
1515
+ function isFinalAndFilter(index, filters) {
1516
+ const nextFilter = filters[index + 1]; // Get the next filter in the list.
1517
+ // Return true if there's no next filter or if the next filter defined and is not part of the AND sequence.
1518
+ return !nextFilter || (!!nextFilter.relation && nextFilter.relation !== 'and');
1519
+ }
1520
+ /**
1521
+ * Determines if all conditions in an AND sequence are satisfied.
1522
+ * @param pendingResults - An array of results from the AND conditions.
1523
+ * @returns True if all conditions are satisfied; false otherwise.
1524
+ */
1525
+ function allAndConditionsSatisfied(pendingResults) {
1526
+ // Check if there are any failed conditions in the pending results.
1527
+ return !pendingResults.includes(true);
1528
+ }
1529
+
1530
+ /** `Object#toString` result references. */
1531
+ var stringTag = '[object String]';
1532
+
1533
+ /**
1534
+ * Checks if `value` is classified as a `String` primitive or object.
1535
+ *
1536
+ * @static
1537
+ * @since 0.1.0
1538
+ * @memberOf _
1539
+ * @category Lang
1540
+ * @param {*} value The value to check.
1541
+ * @returns {boolean} Returns `true` if `value` is a string, else `false`.
1542
+ * @example
1543
+ *
1544
+ * _.isString('abc');
1545
+ * // => true
1546
+ *
1547
+ * _.isString(1);
1548
+ * // => false
1549
+ */
1550
+ function isString(value) {
1551
+ return typeof value == 'string' ||
1552
+ (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);
1553
+ }
1554
+
1555
+ /**
1556
+ * Gets the size of an ASCII `string`.
1557
+ *
1558
+ * @private
1559
+ * @param {string} string The string inspect.
1560
+ * @returns {number} Returns the string size.
1561
+ */
1562
+ var asciiSize = baseProperty('length');
1563
+
1564
+ const asciiSize$1 = asciiSize;
1565
+
1566
+ /** Used to compose unicode character classes. */
1567
+ var rsAstralRange$1 = '\\ud800-\\udfff',
1568
+ rsComboMarksRange$1 = '\\u0300-\\u036f',
1569
+ reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f',
1570
+ rsComboSymbolsRange$1 = '\\u20d0-\\u20ff',
1571
+ rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1,
1572
+ rsVarRange$1 = '\\ufe0e\\ufe0f';
1573
+
1574
+ /** Used to compose unicode capture groups. */
1575
+ var rsZWJ$1 = '\\u200d';
1576
+
1577
+ /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
1578
+ var reHasUnicode = RegExp('[' + rsZWJ$1 + rsAstralRange$1 + rsComboRange$1 + rsVarRange$1 + ']');
1579
+
1580
+ /**
1581
+ * Checks if `string` contains Unicode symbols.
1582
+ *
1583
+ * @private
1584
+ * @param {string} string The string to inspect.
1585
+ * @returns {boolean} Returns `true` if a symbol is found, else `false`.
1586
+ */
1587
+ function hasUnicode(string) {
1588
+ return reHasUnicode.test(string);
1589
+ }
1590
+
1591
+ /** Used to compose unicode character classes. */
1592
+ var rsAstralRange = '\\ud800-\\udfff',
1593
+ rsComboMarksRange = '\\u0300-\\u036f',
1594
+ reComboHalfMarksRange = '\\ufe20-\\ufe2f',
1595
+ rsComboSymbolsRange = '\\u20d0-\\u20ff',
1596
+ rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
1597
+ rsVarRange = '\\ufe0e\\ufe0f';
1598
+
1599
+ /** Used to compose unicode capture groups. */
1600
+ var rsAstral = '[' + rsAstralRange + ']',
1601
+ rsCombo = '[' + rsComboRange + ']',
1602
+ rsFitz = '\\ud83c[\\udffb-\\udfff]',
1603
+ rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
1604
+ rsNonAstral = '[^' + rsAstralRange + ']',
1605
+ rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
1606
+ rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
1607
+ rsZWJ = '\\u200d';
1608
+
1609
+ /** Used to compose unicode regexes. */
1610
+ var reOptMod = rsModifier + '?',
1611
+ rsOptVar = '[' + rsVarRange + ']?',
1612
+ rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
1613
+ rsSeq = rsOptVar + reOptMod + rsOptJoin,
1614
+ rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
1615
+
1616
+ /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
1617
+ var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
1618
+
1619
+ /**
1620
+ * Gets the size of a Unicode `string`.
1621
+ *
1622
+ * @private
1623
+ * @param {string} string The string inspect.
1624
+ * @returns {number} Returns the string size.
1625
+ */
1626
+ function unicodeSize(string) {
1627
+ var result = reUnicode.lastIndex = 0;
1628
+ while (reUnicode.test(string)) {
1629
+ ++result;
1630
+ }
1631
+ return result;
1632
+ }
1633
+
1634
+ /**
1635
+ * Gets the number of symbols in `string`.
1636
+ *
1637
+ * @private
1638
+ * @param {string} string The string to inspect.
1639
+ * @returns {number} Returns the string size.
1640
+ */
1641
+ function stringSize(string) {
1642
+ return hasUnicode(string)
1643
+ ? unicodeSize(string)
1644
+ : asciiSize$1(string);
1645
+ }
1646
+
1647
+ /** `Object#toString` result references. */
1648
+ var mapTag = '[object Map]',
1649
+ setTag = '[object Set]';
1650
+
1651
+ /**
1652
+ * Gets the size of `collection` by returning its length for array-like
1653
+ * values or the number of own enumerable string keyed properties for objects.
1654
+ *
1655
+ * @static
1656
+ * @memberOf _
1657
+ * @since 0.1.0
1658
+ * @category Collection
1659
+ * @param {Array|Object|string} collection The collection to inspect.
1660
+ * @returns {number} Returns the collection size.
1661
+ * @example
1662
+ *
1663
+ * _.size([1, 2, 3]);
1664
+ * // => 3
1665
+ *
1666
+ * _.size({ 'a': 1, 'b': 2 });
1667
+ * // => 2
1668
+ *
1669
+ * _.size('pebbles');
1670
+ * // => 7
1671
+ */
1672
+ function size(collection) {
1673
+ if (collection == null) {
1674
+ return 0;
1675
+ }
1676
+ if (isArrayLike(collection)) {
1677
+ return isString(collection) ? stringSize(collection) : collection.length;
1678
+ }
1679
+ var tag = getTag(collection);
1680
+ if (tag == mapTag || tag == setTag) {
1681
+ return collection.size;
1682
+ }
1683
+ return baseKeys(collection).length;
1684
+ }
1685
+
1686
+ function sortIndexByItems(indexes, source, sortingFunc = {}) {
1687
+ // if no sorting - return unsorted indexes
1688
+ if (Object.entries(sortingFunc).length === 0) {
1689
+ // Unsorted indexes
1690
+ return [...Array(indexes.length).keys()];
1691
+ }
1692
+ //
1693
+ /**
1694
+ * go through all indexes and align in new order
1695
+ * performs a multi-level sorting by applying multiple comparison functions to determine the order of the items based on different properties.
1696
+ */
1697
+ return indexes.sort((a, b) => {
1698
+ const itemA = source[a];
1699
+ const itemB = source[b];
1700
+ for (const [prop, cmp] of Object.entries(sortingFunc)) {
1701
+ if (isGrouping(itemA)) {
1702
+ if (itemA['__rvgr-prop'] !== prop) {
1703
+ return 0;
1704
+ }
1705
+ }
1706
+ if (isGrouping(itemB)) {
1707
+ if (itemB['__rvgr-prop'] !== prop) {
1708
+ return 0;
1709
+ }
1710
+ }
1711
+ /**
1712
+ * If the comparison function returns a non-zero value (sorted), it means that the items should be sorted based on the given property. In such a case, the function immediately returns the sorted value, indicating the order in which the items should be arranged.
1713
+ * If none of the comparison functions result in a non-zero value, indicating that the items are equal or should remain in the same order, the function eventually returns 0.
1714
+ */
1715
+ const sorted = cmp === null || cmp === void 0 ? void 0 : cmp(prop, itemA, itemB);
1716
+ if (sorted) {
1717
+ return sorted;
1718
+ }
1719
+ }
1720
+ return 0;
1721
+ });
1722
+ }
1723
+
1724
+ /**
1725
+ * Lifecycle
1726
+ * 1. @event `beforesorting` - Triggered when sorting just starts. Nothing has happened yet. This can be triggered from a column or from the source. If the type is from rows, the column will be undefined.
1727
+ * 1.1. @event `beforesourcesortingapply` - Triggered before the sorting data is applied to the data source. You can prevent this event, and the data will not be sorted.
1728
+ * 2. Method `updateColumnSorting` - Updates the column sorting icon on the grid and the column itself, but the data remains untouched.
1729
+ * 3. @event `beforesortingapply` - Triggered before the sorting data is applied to the data source. You can prevent this event, and the data will not be sorted. This event is only called from a column sorting click.
1730
+ * 4. @event `aftersortingapply` - Triggered after sorting has been applied and completed. This event occurs for both row and column sorting.
1731
+ *
1732
+ * Note: If you prevent an event, it will not proceed to the subsequent steps.
1733
+ */
1734
+ class SortingPlugin extends BasePlugin {
1735
+ runSorting(order, comparison, ignoreViewportUpdate) {
1736
+ var _a;
1737
+ this.sort(order, comparison, undefined, ignoreViewportUpdate);
1738
+ (_a = this.sortingPromise) === null || _a === void 0 ? void 0 : _a.call(this);
1739
+ this.sortingPromise = null;
1740
+ }
1741
+ constructor(revogrid, providers, config) {
1742
+ super(revogrid, providers);
1743
+ this.revogrid = revogrid;
1744
+ this.sortingPromise = null;
1745
+ this.postponeSort = debounce((order, comparison, ignoreViewportUpdate) => this.runSorting(order, comparison, ignoreViewportUpdate), 50);
1746
+ const setConfig = (cfg) => {
1747
+ var _a;
1748
+ if (cfg) {
1749
+ const sortingFunc = {};
1750
+ const order = {};
1751
+ (_a = cfg.columns) === null || _a === void 0 ? void 0 : _a.forEach(col => {
1752
+ sortingFunc[col.prop] = this.getComparer(col, col.order);
1753
+ order[col.prop] = col.order;
1754
+ });
1755
+ // // set sorting
1756
+ this.sorting = order;
1757
+ this.sortingFunc = sortingFunc;
1758
+ }
1759
+ };
1760
+ setConfig(config);
1761
+ this.addEventListener('sortingconfigchanged', ({ detail }) => {
1762
+ config = detail;
1763
+ setConfig(detail);
1764
+ this.startSorting(this.sorting, this.sortingFunc);
1765
+ });
1766
+ this.addEventListener('beforeanysource', ({ detail: { type }, }) => {
1767
+ // if sorting was provided - sort data
1768
+ if (!!this.sorting && this.sortingFunc) {
1769
+ const event = this.emit('beforesourcesortingapply', { type, sorting: this.sorting });
1770
+ if (event.defaultPrevented) {
1771
+ return;
1772
+ }
1773
+ this.startSorting(this.sorting, this.sortingFunc);
1774
+ }
1775
+ });
1776
+ this.addEventListener('aftercolumnsset', ({ detail: { order }, }) => {
1777
+ // if config provided - do nothing, read from config
1778
+ if (config) {
1779
+ return;
1780
+ }
1781
+ const columns = this.providers.column.getColumns();
1782
+ const sortingFunc = {};
1783
+ for (let prop in order) {
1784
+ const cmp = this.getComparer(getColumnByProp(columns, prop), order[prop]);
1785
+ sortingFunc[prop] = cmp;
1786
+ }
1787
+ // set sorting
1788
+ this.sorting = order;
1789
+ this.sortingFunc = order && sortingFunc;
1790
+ });
1791
+ this.addEventListener('beforeheaderclick', (e) => {
1792
+ var _a, _b, _c, _d;
1793
+ if (e.defaultPrevented) {
1794
+ return;
1795
+ }
1796
+ if (!((_b = (_a = e.detail) === null || _a === void 0 ? void 0 : _a.column) === null || _b === void 0 ? void 0 : _b.sortable)) {
1797
+ return;
1798
+ }
1799
+ this.headerclick(e.detail.column, e.detail.index, (_d = (_c = e.detail) === null || _c === void 0 ? void 0 : _c.originalEvent) === null || _d === void 0 ? void 0 : _d.shiftKey);
1800
+ });
1801
+ }
1802
+ startSorting(order, sortingFunc, ignoreViewportUpdate) {
1803
+ if (!this.sortingPromise) {
1804
+ // add job before render
1805
+ this.revogrid.jobsBeforeRender.push(new Promise(resolve => {
1806
+ this.sortingPromise = resolve;
1807
+ }));
1808
+ }
1809
+ this.postponeSort(order, sortingFunc, ignoreViewportUpdate);
1810
+ }
1811
+ getComparer(column, order) {
1812
+ var _a, _b;
1813
+ const cellCmp = ((_a = column === null || column === void 0 ? void 0 : column.cellCompare) === null || _a === void 0 ? void 0 : _a.bind({ order })) || ((_b = this.defaultCellCompare) === null || _b === void 0 ? void 0 : _b.bind({ column, order }));
1814
+ if (order == 'asc') {
1815
+ return cellCmp;
1816
+ }
1817
+ if (order == 'desc') {
1818
+ return this.descCellCompare(cellCmp);
1819
+ }
1820
+ return undefined;
1821
+ }
1822
+ /**
1823
+ * Apply sorting to data on header click
1824
+ * If additive - add to existing sorting, multiple columns can be sorted
1825
+ */
1826
+ headerclick(column, index, additive) {
1827
+ var _a, _b;
1828
+ let order = this.getNextOrder(column.order);
1829
+ const beforeEvent = this.emit('beforesorting', { column, order, additive });
1830
+ if (beforeEvent.defaultPrevented) {
1831
+ return;
1832
+ }
1833
+ order = beforeEvent.detail.order;
1834
+ const newCol = this.providers.column.updateColumnSorting(beforeEvent.detail.column, index, order, additive);
1835
+ // apply sort data
1836
+ const beforeApplyEvent = this.emit('beforesortingapply', {
1837
+ column: newCol,
1838
+ order,
1839
+ additive,
1840
+ });
1841
+ if (beforeApplyEvent.defaultPrevented) {
1842
+ return;
1843
+ }
1844
+ const cmp = this.getComparer(beforeApplyEvent.detail.column, beforeApplyEvent.detail.order);
1845
+ if (beforeApplyEvent.detail.additive && this.sorting) {
1846
+ const sorting = {};
1847
+ const sortingFunc = {};
1848
+ this.sorting = Object.assign(Object.assign({}, this.sorting), sorting);
1849
+ // extend sorting function with new sorting for multiple columns sorting
1850
+ this.sortingFunc = Object.assign(Object.assign({}, this.sortingFunc), sortingFunc);
1851
+ if (column.prop in sorting && size(sorting) > 1 && order === undefined) {
1852
+ delete sorting[column.prop];
1853
+ delete sortingFunc[column.prop];
1854
+ }
1855
+ else {
1856
+ sorting[column.prop] = order;
1857
+ sortingFunc[column.prop] = cmp;
1858
+ }
1859
+ }
1860
+ else {
1861
+ if (order) {
1862
+ // reset sorting
1863
+ this.sorting = { [column.prop]: order };
1864
+ this.sortingFunc = { [column.prop]: cmp };
1865
+ }
1866
+ else {
1867
+ (_a = this.sorting) === null || _a === void 0 ? true : delete _a[column.prop];
1868
+ (_b = this.sortingFunc) === null || _b === void 0 ? true : delete _b[column.prop];
1869
+ }
1870
+ }
1871
+ this.startSorting(this.sorting, this.sortingFunc);
1872
+ }
1873
+ /**
1874
+ * Sort items by sorting function
1875
+ * @requires proxyItems applied to row store
1876
+ * @requires source applied to row store
1877
+ *
1878
+ * @param sorting - per column sorting
1879
+ * @param data - this.stores['rgRow'].store.get('source')
1880
+ */
1881
+ sort(sorting, sortingFunc, types = rowTypes, ignoreViewportUpdate = false) {
1882
+ // if no sorting - reset
1883
+ if (!Object.keys(sorting || {}).length) {
1884
+ for (let type of types) {
1885
+ const storeService = this.providers.data.stores[type];
1886
+ // row data
1887
+ const source = storeService.store.get('source');
1888
+ // row indexes
1889
+ const proxyItems = storeService.store.get('proxyItems');
1890
+ // row indexes
1891
+ const newItemsOrder = Array.from({ length: source.length }, (_, i) => i); // recover indexes range(0, source.length)
1892
+ this.providers.dimension.updateSizesPositionByNewDataIndexes(type, newItemsOrder, proxyItems);
1893
+ storeService.setData({ proxyItems: newItemsOrder, source: [...source], });
1894
+ }
1895
+ }
1896
+ else {
1897
+ for (let type of types) {
1898
+ const storeService = this.providers.data.stores[type];
1899
+ // row data
1900
+ const source = storeService.store.get('source');
1901
+ // row indexes
1902
+ const proxyItems = storeService.store.get('proxyItems');
1903
+ const newItemsOrder = sortIndexByItems([...proxyItems], source, sortingFunc);
1904
+ // take row indexes before trim applied and proxy items
1905
+ const prevItems = storeService.store.get('items');
1906
+ storeService.setData({
1907
+ proxyItems: newItemsOrder,
1908
+ source: [...source],
1909
+ });
1910
+ // take currently visible row indexes
1911
+ const newItems = storeService.store.get('items');
1912
+ if (!ignoreViewportUpdate) {
1913
+ this.providers.dimension
1914
+ .updateSizesPositionByNewDataIndexes(type, newItems, prevItems);
1915
+ }
1916
+ }
1917
+ }
1918
+ this.emit('aftersortingapply');
1919
+ }
1920
+ defaultCellCompare(prop, a, b) {
1921
+ const aRaw = this.column ? getCellRaw(a, this.column) : a === null || a === void 0 ? void 0 : a[prop];
1922
+ const bRaw = this.column ? getCellRaw(b, this.column) : b === null || b === void 0 ? void 0 : b[prop];
1923
+ const av = aRaw === null || aRaw === void 0 ? void 0 : aRaw.toString().toLowerCase();
1924
+ const bv = bRaw === null || bRaw === void 0 ? void 0 : bRaw.toString().toLowerCase();
1925
+ return av == bv ? 0 : av > bv ? 1 : -1;
1926
+ }
1927
+ descCellCompare(cmp) {
1928
+ return (prop, a, b) => {
1929
+ return -1 * cmp(prop, a, b);
1930
+ };
1931
+ }
1932
+ getNextOrder(currentOrder) {
1933
+ switch (currentOrder) {
1934
+ case undefined:
1935
+ return 'asc';
1936
+ case 'asc':
1937
+ return 'desc';
1938
+ case 'desc':
1939
+ return undefined;
1940
+ }
1941
+ }
1942
+ }
1943
+
1944
+ // provide collapse data
1945
+ function doCollapse(pIndex, source) {
1946
+ const model = source[pIndex];
1947
+ const collapseValue = model[PSEUDO_GROUP_ITEM_VALUE];
1948
+ const trimmed = {};
1949
+ let i = pIndex + 1;
1950
+ const total = source.length;
1951
+ while (i < total) {
1952
+ const currentModel = source[i];
1953
+ if (isGrouping(currentModel)) {
1954
+ const currentValue = currentModel[PSEUDO_GROUP_ITEM_VALUE];
1955
+ if (!currentValue.length || !currentValue.startsWith(collapseValue + ',')) {
1956
+ break;
1957
+ }
1958
+ currentModel[GROUP_EXPANDED] = false;
1959
+ }
1960
+ trimmed[i++] = true;
1961
+ }
1962
+ model[GROUP_EXPANDED] = false;
1963
+ return { trimmed };
1964
+ }
1965
+ /**
1966
+ *
1967
+ * @param pIndex - physical index
1968
+ * @param vIndex - virtual index, need to update item collection
1969
+ * @param source - data source
1970
+ * @param rowItemsIndexes - rgRow indexes
1971
+ */
1972
+ function doExpand(vIndex, source, rowItemsIndexes) {
1973
+ const physicalIndex = rowItemsIndexes[vIndex];
1974
+ const model = source[physicalIndex];
1975
+ const currentGroup = getParsedGroup(model[PSEUDO_GROUP_ITEM_ID]);
1976
+ const trimmed = {};
1977
+ // no group found
1978
+ if (!currentGroup) {
1979
+ return { trimmed };
1980
+ }
1981
+ const groupItems = [];
1982
+ model[GROUP_EXPANDED] = true;
1983
+ let i = physicalIndex + 1;
1984
+ const total = source.length;
1985
+ let groupLevelOnly = 0;
1986
+ // go through all rows
1987
+ while (i < total) {
1988
+ const currentModel = source[i];
1989
+ const isGroup = isGrouping(currentModel);
1990
+ // group found
1991
+ if (isGroup) {
1992
+ if (!isSameGroup(currentGroup, model, currentModel)) {
1993
+ break;
1994
+ }
1995
+ else if (!groupLevelOnly) {
1996
+ // if get group first it's group only level
1997
+ groupLevelOnly = currentModel[GROUP_DEPTH];
1998
+ }
1999
+ }
2000
+ // level 0 or same depth
2001
+ if (!groupLevelOnly || (isGroup && groupLevelOnly === currentModel[GROUP_DEPTH])) {
2002
+ trimmed[i] = false;
2003
+ groupItems.push(i);
2004
+ }
2005
+ i++;
2006
+ }
2007
+ const result = {
2008
+ trimmed,
2009
+ };
2010
+ if (groupItems.length) {
2011
+ const items = [...rowItemsIndexes];
2012
+ items.splice(vIndex + 1, 0, ...groupItems);
2013
+ result.items = items;
2014
+ }
2015
+ return result;
2016
+ }
2017
+
2018
+ const TRIMMED_GROUPING = 'grouping';
2019
+ /**
2020
+ * Prepare trimming updated indexes for grouping
2021
+ * @param initiallyTrimed
2022
+ * @param firstLevelMap
2023
+ * @param secondLevelMap
2024
+ */
2025
+ function processDoubleConversionTrimmed(initiallyTrimed, firstLevelMap, secondLevelMap) {
2026
+ const trimemedOptionsToUpgrade = {};
2027
+ /**
2028
+ * go through all groups except grouping
2029
+ */
2030
+ for (let type in initiallyTrimed) {
2031
+ if (type === TRIMMED_GROUPING) {
2032
+ continue;
2033
+ }
2034
+ const items = initiallyTrimed[type];
2035
+ const newItems = {};
2036
+ for (let initialIndex in items) {
2037
+ /**
2038
+ * if item exists we find it in collection
2039
+ * we support 2 level of conversions
2040
+ */
2041
+ let newConversionIndex = firstLevelMap[initialIndex];
2042
+ if (secondLevelMap) {
2043
+ newConversionIndex = secondLevelMap[newConversionIndex];
2044
+ }
2045
+ /**
2046
+ * if item was trimmed previously
2047
+ * trimming makes sense to apply
2048
+ */
2049
+ if (items[initialIndex]) {
2050
+ newItems[newConversionIndex] = true;
2051
+ /**
2052
+ * If changes present apply changes to new source
2053
+ */
2054
+ if (newConversionIndex !== parseInt(initialIndex, 10)) {
2055
+ trimemedOptionsToUpgrade[type] = newItems;
2056
+ }
2057
+ }
2058
+ }
2059
+ }
2060
+ return trimemedOptionsToUpgrade;
2061
+ }
2062
+
2063
+ class GroupingRowPlugin extends BasePlugin {
2064
+ getStore(type = GROUPING_ROW_TYPE) {
2065
+ return this.providers.data.stores[type].store;
2066
+ }
2067
+ constructor(revogrid, providers) {
2068
+ super(revogrid, providers);
2069
+ this.revogrid = revogrid;
2070
+ this.providers = providers;
2071
+ }
2072
+ // befoce cell focus
2073
+ onFocus(e) {
2074
+ if (isGrouping(e.detail.model)) {
2075
+ e.preventDefault();
2076
+ }
2077
+ }
2078
+ // expand event triggered
2079
+ onExpand({ virtualIndex }) {
2080
+ const { source } = getSource(this.getStore().get('source'), this.getStore().get('proxyItems'));
2081
+ let newTrimmed = this.getStore().get('trimmed')[TRIMMED_GROUPING];
2082
+ let i = getPhysical(this.getStore(), virtualIndex);
2083
+ const isExpanded = getExpanded(source[i]);
2084
+ if (!isExpanded) {
2085
+ const { trimmed, items } = doExpand(virtualIndex, source, this.getStore().get('items'));
2086
+ newTrimmed = Object.assign(Object.assign({}, newTrimmed), trimmed);
2087
+ if (items) {
2088
+ setItems(this.getStore(), items);
2089
+ }
2090
+ }
2091
+ else {
2092
+ const { trimmed } = doCollapse(i, source);
2093
+ newTrimmed = Object.assign(Object.assign({}, newTrimmed), trimmed);
2094
+ this.revogrid.clearFocus();
2095
+ }
2096
+ this.getStore().set('source', source);
2097
+ this.revogrid.addTrimmed(newTrimmed, TRIMMED_GROUPING);
2098
+ }
2099
+ setColumnGrouping(cols) {
2100
+ // if 0 column as holder
2101
+ if (cols === null || cols === void 0 ? void 0 : cols.length) {
2102
+ cols[0][PSEUDO_GROUP_COLUMN] = true;
2103
+ return true;
2104
+ }
2105
+ return false;
2106
+ }
2107
+ setColumns({ columns }) {
2108
+ for (let type of columnTypes) {
2109
+ if (this.setColumnGrouping(columns[type])) {
2110
+ break;
2111
+ }
2112
+ }
2113
+ }
2114
+ // evaluate drag between groups
2115
+ onDrag(e) {
2116
+ const { from, to } = e.detail;
2117
+ const isDown = to - from >= 0;
2118
+ const { source } = getSource(this.getStore().get('source'), this.getStore().get('proxyItems'));
2119
+ const items = this.getStore().get('items');
2120
+ let i = isDown ? from : to;
2121
+ const end = isDown ? to : from;
2122
+ for (; i < end; i++) {
2123
+ const model = source[items[i]];
2124
+ const isGroup = isGrouping(model);
2125
+ if (isGroup) {
2126
+ e.preventDefault();
2127
+ return;
2128
+ }
2129
+ }
2130
+ }
2131
+ beforeTrimmedApply(trimmed, type) {
2132
+ /** Before filter apply remove grouping filtering */
2133
+ if (type === FILTER_TRIMMED_TYPE) {
2134
+ const source = this.getStore().get('source');
2135
+ for (let index in trimmed) {
2136
+ if (trimmed[index] && isGrouping(source[index])) {
2137
+ trimmed[index] = false;
2138
+ }
2139
+ }
2140
+ }
2141
+ }
2142
+ isSortingRunning() {
2143
+ const sortingPlugin = this.providers.plugins.getByClass(SortingPlugin);
2144
+ return !!(sortingPlugin === null || sortingPlugin === void 0 ? void 0 : sortingPlugin.sortingPromise);
2145
+ }
2146
+ /**
2147
+ * Starts global source update with group clearing and applying new one
2148
+ * Initiated when need to reapply grouping
2149
+ */
2150
+ doSourceUpdate(options) {
2151
+ var _a;
2152
+ /**
2153
+ * Get source without grouping
2154
+ * @param newOldIndexMap - provides us mapping with new indexes vs old indexes, we would use it for trimmed mapping
2155
+ */
2156
+ const { source, prevExpanded, oldNewIndexes } = getSource(this.getStore().get('source'), this.getStore().get('proxyItems'), true);
2157
+ const expanded = Object.assign({ prevExpanded }, options);
2158
+ /**
2159
+ * Group again
2160
+ * @param oldNewIndexMap - provides us mapping with new indexes vs old indexes
2161
+ */
2162
+ const { sourceWithGroups, depth, trimmed, oldNewIndexMap, } = gatherGrouping(source, ((_a = this.options) === null || _a === void 0 ? void 0 : _a.props) || [], expanded);
2163
+ const customRenderer = options === null || options === void 0 ? void 0 : options.groupLabelTemplate;
2164
+ // setup source
2165
+ this.providers.data.setData(sourceWithGroups, GROUPING_ROW_TYPE, this.revogrid.disableVirtualY, { depth, customRenderer }, true);
2166
+ this.updateTrimmed(trimmed, oldNewIndexes !== null && oldNewIndexes !== void 0 ? oldNewIndexes : {}, oldNewIndexMap);
2167
+ }
2168
+ /**
2169
+ * Apply grouping on data set
2170
+ * Clear grouping from source
2171
+ * If source came from other plugin
2172
+ */
2173
+ onDataSet(data) {
2174
+ var _a, _b;
2175
+ let preservedExpanded = {};
2176
+ if (((_a = this.options) === null || _a === void 0 ? void 0 : _a.preserveGroupingOnUpdate) !== false) {
2177
+ let { prevExpanded } = getSource(this.getStore().get('source'), this.getStore().get('proxyItems'), true);
2178
+ preservedExpanded = prevExpanded;
2179
+ }
2180
+ const source = data.source.filter(s => !isGrouping(s));
2181
+ const options = Object.assign(Object.assign({}, (this.revogrid.grouping || {})), { prevExpanded: preservedExpanded });
2182
+ const { sourceWithGroups, depth, trimmed, oldNewIndexMap, } = gatherGrouping(source, ((_b = this.options) === null || _b === void 0 ? void 0 : _b.props) || [], options);
2183
+ data.source = sourceWithGroups;
2184
+ this.providers.data.setGrouping({ depth });
2185
+ this.updateTrimmed(trimmed, oldNewIndexMap);
2186
+ }
2187
+ /**
2188
+ * External call to apply grouping. Called by revogrid when prop changed.
2189
+ */
2190
+ setGrouping(options) {
2191
+ var _a, _b;
2192
+ // unsubscribe from all events when group applied
2193
+ this.clearSubscriptions();
2194
+ this.options = options;
2195
+ // clear props, no grouping exists
2196
+ if (!((_b = (_a = this.options) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.length)) {
2197
+ this.clearGrouping();
2198
+ return;
2199
+ }
2200
+ // props exist and source initd
2201
+ const { source } = getSource(this.getStore().get('source'), this.getStore().get('proxyItems'));
2202
+ if (source.length) {
2203
+ this.doSourceUpdate(Object.assign({}, options));
2204
+ }
2205
+ // props exist and columns initd
2206
+ for (let t of columnTypes) {
2207
+ if (this.setColumnGrouping(this.providers.column.getColumns(t))) {
2208
+ this.providers.column.refreshByType(t);
2209
+ break;
2210
+ }
2211
+ }
2212
+ // if has any grouping subscribe to events again
2213
+ /** if grouping present and new data source arrived */
2214
+ this.addEventListener('beforesourceset', ({ detail }) => {
2215
+ var _a, _b, _c;
2216
+ if (!(((_b = (_a = this.options) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.length) && ((_c = detail === null || detail === void 0 ? void 0 : detail.source) === null || _c === void 0 ? void 0 : _c.length))) {
2217
+ return;
2218
+ }
2219
+ // if sorting is running don't apply grouping, wait for sorting, then it'll apply in @aftersortingapply
2220
+ if (this.isSortingRunning()) {
2221
+ return;
2222
+ }
2223
+ this.onDataSet(detail);
2224
+ });
2225
+ this.addEventListener('beforecolumnsset', ({ detail }) => {
2226
+ this.setColumns(detail);
2227
+ });
2228
+ /**
2229
+ * filter applied need to clear grouping and apply again
2230
+ * based on new results can be new grouping
2231
+ */
2232
+ this.addEventListener('beforetrimmed', ({ detail: { trimmed, trimmedType } }) => this.beforeTrimmedApply(trimmed, trimmedType));
2233
+ /**
2234
+ * sorting applied need to clear grouping and apply again
2235
+ * based on new results whole grouping order will changed
2236
+ */
2237
+ this.addEventListener('aftersortingapply', () => {
2238
+ var _a, _b;
2239
+ if (!((_b = (_a = this.options) === null || _a === void 0 ? void 0 : _a.props) === null || _b === void 0 ? void 0 : _b.length)) {
2240
+ return;
2241
+ }
2242
+ this.doSourceUpdate(Object.assign({}, this.options));
2243
+ });
2244
+ /**
2245
+ * Apply logic for focus inside of grouping
2246
+ * We can't focus on grouping rows, navigation only inside of groups for now
2247
+ */
2248
+ this.addEventListener('beforecellfocus', e => this.onFocus(e));
2249
+ /**
2250
+ * Prevent rgRow drag outside the group
2251
+ */
2252
+ this.addEventListener('roworderchanged', e => this.onDrag(e));
2253
+ /**
2254
+ * When grouping expand icon was clicked
2255
+ */
2256
+ this.addEventListener('groupexpandclick', e => this.onExpand(e.detail));
2257
+ }
2258
+ // clear grouping
2259
+ clearGrouping() {
2260
+ // clear columns
2261
+ columnTypes.forEach(t => {
2262
+ const cols = this.providers.column.getColumns(t);
2263
+ let deleted = false;
2264
+ cols.forEach(c => {
2265
+ if (isGroupingColumn(c)) {
2266
+ delete c[PSEUDO_GROUP_COLUMN];
2267
+ deleted = true;
2268
+ }
2269
+ });
2270
+ // if column store had grouping clear and refresh
2271
+ if (deleted) {
2272
+ this.providers.column.refreshByType(t);
2273
+ }
2274
+ });
2275
+ // clear rows
2276
+ const { source, oldNewIndexes } = getSource(this.getStore().get('source'), this.getStore().get('proxyItems'), true);
2277
+ this.providers.data.setData(source, GROUPING_ROW_TYPE, this.revogrid.disableVirtualY, undefined, true);
2278
+ this.updateTrimmed(undefined, undefined, oldNewIndexes);
2279
+ }
2280
+ updateTrimmed(trimmedGroup = {}, firstLevelMap = {}, secondLevelMap) {
2281
+ // map previously trimmed data
2282
+ const trimemedOptionsToUpgrade = processDoubleConversionTrimmed(this.getStore().get('trimmed'), firstLevelMap, secondLevelMap);
2283
+ for (let type in trimemedOptionsToUpgrade) {
2284
+ this.revogrid.addTrimmed(trimemedOptionsToUpgrade[type], type);
2285
+ }
2286
+ // const emptyGroups = this.filterOutEmptyGroups(trimemedOptionsToUpgrade, childrenByGroup);
2287
+ // setup trimmed data for grouping
2288
+ this.revogrid.addTrimmed(Object.assign({}, trimmedGroup), TRIMMED_GROUPING);
2289
+ }
2290
+ }
2291
+
2292
+ const COLUMN_DRAG_CLASS = 'column-drag-start';
2293
+ class ColumnOrderHandler {
2294
+ constructor() {
2295
+ this.offset = 0;
2296
+ }
2297
+ renderAutoscroll(_, parent) {
2298
+ if (!parent) {
2299
+ return;
2300
+ }
2301
+ this.autoscrollEl = document.createElement('div');
2302
+ this.autoscrollEl.classList.add('drag-auto-scroll-y');
2303
+ parent.appendChild(this.autoscrollEl);
2304
+ }
2305
+ autoscroll(pos, dataContainerSize, direction = 'translateX') {
2306
+ if (!this.autoscrollEl) {
2307
+ return;
2308
+ }
2309
+ const helperOffset = 10;
2310
+ // calculate current y position inside of the grid active holder
2311
+ // 3 - size of element + border
2312
+ const maxScroll = Math.min(pos + helperOffset, dataContainerSize - 3);
2313
+ this.autoscrollEl.style.transform = `${direction}(${maxScroll}px)`;
2314
+ this.autoscrollEl.scrollIntoView({
2315
+ block: 'nearest',
2316
+ inline: 'nearest',
2317
+ });
2318
+ }
2319
+ start(e, { dataEl, gridRect, scrollEl, gridEl }, dir = 'left') {
2320
+ gridEl.classList.add(COLUMN_DRAG_CLASS);
2321
+ const scrollContainerRect = scrollEl.getBoundingClientRect();
2322
+ if (scrollContainerRect) {
2323
+ this.offset = scrollContainerRect[dir] - gridRect[dir];
2324
+ }
2325
+ this.renderAutoscroll(e, dataEl);
2326
+ }
2327
+ stop(gridEl) {
2328
+ var _a;
2329
+ gridEl.classList.remove(COLUMN_DRAG_CLASS);
2330
+ if (this.element) {
2331
+ this.element.hidden = true;
2332
+ }
2333
+ this.offset = 0;
2334
+ (_a = this.autoscrollEl) === null || _a === void 0 ? void 0 : _a.remove();
2335
+ this.autoscrollEl = undefined;
2336
+ }
2337
+ showHandler(pos, size, direction = 'translateX') {
2338
+ if (!this.element) {
2339
+ return;
2340
+ }
2341
+ // do not allow overcross top of the scrollable area, header excluded
2342
+ if (this.offset) {
2343
+ pos = Math.max(pos, this.offset);
2344
+ }
2345
+ // can not be bigger then grid end
2346
+ pos = Math.min(pos, size);
2347
+ this.element.style.transform = `${direction}(${pos}px)`;
2348
+ this.element.hidden = false;
2349
+ }
2350
+ render() {
2351
+ const el = this.element = document.createElement('div');
2352
+ el.classList.add('drag-position-y');
2353
+ el.hidden = true;
2354
+ return el;
2355
+ }
2356
+ }
2357
+
2358
+ /**
2359
+ * Plugin for column manual move
2360
+ */
2361
+ const COLUMN_CLICK = ON_COLUMN_CLICK;
2362
+ const MOVE = 'columndragmousemove';
2363
+ const DRAG_END = 'columndragend';
2364
+ const BEFORE_DRAG_END = 'beforecolumndragend';
2365
+ // use this event subscription to drop D&D for particular columns
2366
+ const DRAG_START = 'columndragstart';
2367
+ class ColumnMovePlugin extends BasePlugin {
2368
+ constructor(revogrid, providers) {
2369
+ super(revogrid, providers);
2370
+ this.revogrid = revogrid;
2371
+ this.providers = providers;
2372
+ this.moveFunc = debounce((e) => this.doMove(e), 5);
2373
+ this.staticDragData = null;
2374
+ this.dragData = null;
2375
+ this.localSubscriptions = {};
2376
+ this.orderUi = new ColumnOrderHandler();
2377
+ revogrid.appendChild(this.orderUi.render());
2378
+ revogrid.classList.add('column-draggable');
2379
+ // Register events
2380
+ this.localSubscriptions['mouseleave'] = {
2381
+ target: document,
2382
+ callback: (e) => this.onMouseOut(e),
2383
+ };
2384
+ this.localSubscriptions['mouseup'] = {
2385
+ target: document,
2386
+ callback: (e) => this.onMouseUp(e),
2387
+ };
2388
+ this.localSubscriptions['mousemove'] = {
2389
+ target: document,
2390
+ callback: (e) => this.move(e),
2391
+ };
2392
+ this.addEventListener(COLUMN_CLICK, ({ detail }) => this.dragStart(detail));
2393
+ }
2394
+ dragStart({ event, data }) {
2395
+ if (event.defaultPrevented) {
2396
+ return;
2397
+ }
2398
+ const { defaultPrevented } = dispatch(this.revogrid, DRAG_START, data);
2399
+ // check if allowed to drag particulat column
2400
+ if (defaultPrevented) {
2401
+ return;
2402
+ }
2403
+ this.clearOrder();
2404
+ const { mouseleave, mouseup, mousemove } = this.localSubscriptions;
2405
+ mouseleave.target.addEventListener('mouseleave', mouseleave.callback);
2406
+ mouseup.target.addEventListener('mouseup', mouseup.callback);
2407
+ const dataEl = event.target.closest('revogr-header');
2408
+ const scrollEl = event.target.closest('revogr-viewport-scroll');
2409
+ if (!dataEl || !scrollEl) {
2410
+ return;
2411
+ }
2412
+ // no grouping drag and no row header column drag
2413
+ if (isColGrouping(data) || data.providers.type === 'rowHeaders') {
2414
+ return;
2415
+ }
2416
+ const cols = this.getDimension(data.pin || 'rgCol');
2417
+ const gridRect = this.revogrid.getBoundingClientRect();
2418
+ const elRect = dataEl.getBoundingClientRect();
2419
+ const startItem = getItemByPosition(cols, getLeftRelative(event.x, gridRect.left, elRect.left - gridRect.left));
2420
+ this.staticDragData = {
2421
+ startPos: event.x,
2422
+ startItem,
2423
+ data,
2424
+ dataEl,
2425
+ scrollEl,
2426
+ gridEl: this.revogrid,
2427
+ cols,
2428
+ };
2429
+ this.dragData = this.getData(this.staticDragData);
2430
+ mousemove.target.addEventListener('mousemove', mousemove.callback);
2431
+ this.orderUi.start(event, Object.assign(Object.assign({}, this.dragData), this.staticDragData));
2432
+ }
2433
+ doMove(e) {
2434
+ if (!this.staticDragData) {
2435
+ return;
2436
+ }
2437
+ const dragData = (this.dragData = this.getData(this.staticDragData));
2438
+ if (!dragData) {
2439
+ return;
2440
+ }
2441
+ const start = this.staticDragData.startPos;
2442
+ if (Math.abs(start - e.x) > 10) {
2443
+ const x = getLeftRelative(e.x, this.dragData.gridRect.left, this.dragData.scrollOffset);
2444
+ const rgCol = getItemByPosition(this.staticDragData.cols, x);
2445
+ this.orderUi.autoscroll(x, dragData.elRect.width);
2446
+ // prevent position change if out of bounds
2447
+ if (rgCol.itemIndex >= this.staticDragData.cols.count) {
2448
+ return;
2449
+ }
2450
+ this.orderUi.showHandler(rgCol.end + dragData.scrollOffset, dragData.gridRect.width);
2451
+ }
2452
+ }
2453
+ move(e) {
2454
+ dispatch(this.revogrid, MOVE, e);
2455
+ // then do move
2456
+ this.moveFunc(e);
2457
+ }
2458
+ onMouseOut(_) {
2459
+ this.clearOrder();
2460
+ }
2461
+ onMouseUp(e) {
2462
+ // apply new positions
2463
+ if (this.dragData && this.staticDragData) {
2464
+ let relativePos = getLeftRelative(e.x, this.dragData.gridRect.left, this.dragData.scrollOffset);
2465
+ if (relativePos < 0) {
2466
+ relativePos = 0;
2467
+ }
2468
+ const newPosition = getItemByPosition(this.staticDragData.cols, relativePos);
2469
+ const store = this.providers.column.stores[this.dragData.type].store;
2470
+ const newItems = [...store.get('items')];
2471
+ // prevent position change if needed
2472
+ const { defaultPrevented: stopDrag } = dispatch(this.revogrid, BEFORE_DRAG_END, Object.assign(Object.assign({}, this.staticDragData), { startPosition: this.staticDragData.startItem, newPosition, newItem: store.get('source')[newItems[this.staticDragData.startItem.itemIndex]] }));
2473
+ if (!stopDrag) {
2474
+ const prevItems = [...newItems];
2475
+ // todo: if move item out of group remove item from group
2476
+ const toMove = newItems.splice(this.staticDragData.startItem.itemIndex, 1);
2477
+ newItems.splice(newPosition.itemIndex, 0, ...toMove);
2478
+ store.set('items', newItems);
2479
+ this.providers.dimension.updateSizesPositionByNewDataIndexes(this.dragData.type, newItems, prevItems);
2480
+ }
2481
+ dispatch(this.revogrid, DRAG_END, this.dragData);
2482
+ }
2483
+ this.clearOrder();
2484
+ }
2485
+ clearLocalSubscriptions() {
2486
+ forEach(this.localSubscriptions, ({ target, callback }, key) => target.removeEventListener(key, callback));
2487
+ }
2488
+ clearOrder() {
2489
+ this.staticDragData = null;
2490
+ this.dragData = null;
2491
+ this.clearLocalSubscriptions();
2492
+ this.orderUi.stop(this.revogrid);
2493
+ }
2494
+ /**
2495
+ * Clearing subscription
2496
+ */
2497
+ clearSubscriptions() {
2498
+ super.clearSubscriptions();
2499
+ this.clearLocalSubscriptions();
2500
+ }
2501
+ getData({ gridEl, dataEl, data, }) {
2502
+ const gridRect = gridEl.getBoundingClientRect();
2503
+ const elRect = dataEl.getBoundingClientRect();
2504
+ const scrollOffset = elRect.left - gridRect.left;
2505
+ return {
2506
+ elRect,
2507
+ gridRect,
2508
+ type: data.pin || 'rgCol',
2509
+ scrollOffset,
2510
+ };
2511
+ }
2512
+ getDimension(type) {
2513
+ return this.providers.dimension.stores[type].getCurrentState();
2514
+ }
2515
+ }
2516
+ function getLeftRelative(absoluteX, gridPos, offset) {
2517
+ return absoluteX - gridPos - offset;
2518
+ }
2519
+
2520
+ export { AutoSizeColumnPlugin as A, BasePlugin as B, ColumnMovePlugin as C, DimensionStore as D, ExportFilePlugin as E, FILTER_TRIMMED_TYPE as F, GroupingRowPlugin as G, StretchColumn as S, isStretchPlugin as a, ExportCsv as b, columnTypes as c, FILTER_CONFIG_CHANGED_EVENT as d, FILTE_PANEL as e, FilterPlugin as f, filterCoreFunctionsIndexedByType as g, filterTypes as h, isRowType as i, filterNames as j, doCollapse as k, doExpand as l, getLeftRelative as m, SortingPlugin as n, forEach as o, rowTypes as r, sortIndexByItems as s };
2521
+
2522
+ //# sourceMappingURL=column.drag.plugin-d201beb7.js.map