@univerjs/sheets-filter 0.17.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,1504 +1 @@
1
- var $e = Object.defineProperty;
2
- var Le = (i, t, e) => t in i ? $e(i, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : i[t] = e;
3
- var C = (i, t, e) => Le(i, typeof t != "symbol" ? t + "" : t, e);
4
- import { createREGEXFromWildChar as _e, isNumeric as Ue, Disposable as P, Rectangle as te, mergeSets as K, Tools as se, extractPureTextFromCell as Pe, CellValueType as k, ColorKit as oe, UniverInstanceType as B, fromCallback as De, CommandType as O, IResourceManagerService as Be, IUniverInstanceService as T, ICommandService as N, IUndoRedoService as J, sequenceExecute as j, ErrorService as ze, LocaleService as He, Inject as A, Optional as Ve, DisposableCollection as Ce, moveMatrixArray as le, IConfigService as Re, Plugin as We, merge as je, touchDependencies as ke, Injector as qe } from "@univerjs/core";
5
- import { getSheetCommandTarget as V, SheetsSelectionsService as Ge, isSingleCellSelection as Qe, expandToContinuousRange as re, SheetInterceptorService as Je, RefRangeService as Ze, ZebraCrossingCacheController as Ke, SetWorksheetActiveOperation as Ye, CopySheetCommand as Xe, RemoveSheetCommand as et, INTERCEPTOR_POINT as tt, RemoveRowMutation as rt, InsertRowMutation as nt, SetRangeValuesMutation as it, MoveRowsCommand as st, MoveRangeCommand as ot, EffectRefRangId as ae, RemoveRowCommand as lt, RemoveColCommand as at, InsertColCommand as ct, InsertRowCommand as dt, InsertColMutation as pe, RemoveColMutation as Se, MoveColsMutation as Fe } from "@univerjs/sheets";
6
- import { BehaviorSubject as $, merge as ut, filter as ht, switchMap as ft, of as mt } from "rxjs";
7
- import { COLOR_BLACK_RGB as gt } from "@univerjs/engine-render";
8
- import { DataSyncPrimaryController as _t } from "@univerjs/rpc";
9
- import { IActiveDirtyManagerService as Ct, ISheetRowFilteredService as Rt } from "@univerjs/engine-formula";
10
- const we = "sheet.mutation.set-filter-range", ve = "sheet.mutation.set-filter-criteria", Me = "sheet.mutation.remove-filter", Ee = "sheet.mutation.re-calc-filter", Oe = /* @__PURE__ */ new Set([
11
- we,
12
- ve,
13
- Me,
14
- Ee
15
- ]);
16
- var b = /* @__PURE__ */ ((i) => (i[i.VALUES = 0] = "VALUES", i[i.COLORS = 1] = "COLORS", i[i.CONDITIONS = 2] = "CONDITIONS", i))(b || {}), I = /* @__PURE__ */ ((i) => (i.EQUAL = "equal", i.GREATER_THAN = "greaterThan", i.GREATER_THAN_OR_EQUAL = "greaterThanOrEqual", i.LESS_THAN = "lessThan", i.LESS_THAN_OR_EQUAL = "lessThanOrEqual", i.NOT_EQUALS = "notEqual", i))(I || {});
17
- const pt = {
18
- operator: I.GREATER_THAN,
19
- fn: (i, t) => D(i) ? i > t : !1
20
- }, St = {
21
- operator: I.GREATER_THAN_OR_EQUAL,
22
- fn: (i, t) => D(i) ? i >= t : !1
23
- }, Ft = {
24
- operator: I.LESS_THAN,
25
- fn: (i, t) => D(i) ? i < t : !1
26
- }, wt = {
27
- operator: I.LESS_THAN_OR_EQUAL,
28
- fn: (i, t) => D(i) ? i <= t : !1
29
- }, vt = {
30
- operator: I.EQUAL,
31
- fn: (i, t) => D(i) ? i === t : !1
32
- }, ye = {
33
- operator: I.NOT_EQUALS,
34
- fn: (i, t) => {
35
- if (typeof t == "string") {
36
- if (t === " ")
37
- return i != null;
38
- const e = Ne(i);
39
- return e && yt(t) ? !_e(t).test(e) : e !== t;
40
- }
41
- return D(i) ? i !== t : !0;
42
- }
43
- }, Ae = /* @__PURE__ */ new Map([]), Mt = [pt, St, Ft, wt, vt, ye];
44
- Mt.forEach((i) => {
45
- Ae.set(i.operator, i);
46
- });
47
- function Et(i) {
48
- return !!i;
49
- }
50
- const Ot = {
51
- fn: (i, t) => {
52
- const e = Ne(i);
53
- return e === null ? t === "" : _e(t).test(e);
54
- }
55
- };
56
- function ce(i) {
57
- return i ? Ae.get(i) : Ot;
58
- }
59
- function D(i) {
60
- return typeof i == "number";
61
- }
62
- function de(i) {
63
- return !!(typeof i == "number" || typeof i == "string" && Ue(i));
64
- }
65
- function Ne(i) {
66
- return typeof i == "boolean" || i == null ? null : typeof i == "string" ? i : i.toString();
67
- }
68
- function yt(i) {
69
- return typeof i == "number" ? !1 : i.indexOf("*") !== -1 || i.indexOf("?") !== -1;
70
- }
71
- const Y = () => /* @__PURE__ */ new Set();
72
- class q extends P {
73
- constructor(e, r, n) {
74
- super();
75
- C(this, "_filteredOutRows$", new $(Y()));
76
- /** An observable value. A set of filtered out rows. */
77
- C(this, "filteredOutRows$", this._filteredOutRows$.asObservable());
78
- // TODO: we may need to update which cols have criteria rather than simple boolean
79
- C(this, "_hasCriteria$", new $(!1));
80
- C(this, "hasCriteria$", this._hasCriteria$.asObservable());
81
- C(this, "_filterColumnByIndex", /* @__PURE__ */ new Map());
82
- C(this, "_alreadyFilteredOutRows", Y());
83
- C(this, "_range");
84
- this.unitId = e, this.subUnitId = r, this._worksheet = n;
85
- }
86
- get filteredOutRows() {
87
- return this._filteredOutRows$.getValue();
88
- }
89
- set filteredOutRows(e) {
90
- this._alreadyFilteredOutRows = e, this._filteredOutRows$.next(e);
91
- }
92
- dispose() {
93
- super.dispose(), this._filteredOutRows$.complete(), this._hasCriteria$.complete(), this._worksheet = null;
94
- }
95
- /**
96
- * Serialize this filter model to the JSON format representation.
97
- */
98
- serialize() {
99
- const e = {
100
- ref: te.clone(this._range),
101
- filterColumns: this._getAllFilterColumns(!0).sort(([r], [n]) => r - n).map(([r, n]) => n.serialize())
102
- };
103
- return this._alreadyFilteredOutRows && (e.cachedFilteredOut = Array.from(this._alreadyFilteredOutRows).sort()), e;
104
- }
105
- /**
106
- * Deserialize auto filter info to construct a `FilterModel` object.
107
- * @param unitId workbook id
108
- * @param subUnitId worksheet id
109
- * @param worksheet the Worksheet object
110
- * @param autoFilter auto filter data
111
- */
112
- static deserialize(e, r, n, s) {
113
- const o = new q(e, r, n);
114
- return o._dump(s), o;
115
- }
116
- _dump(e) {
117
- var r;
118
- this.setRange(e.ref), (r = e.filterColumns) == null || r.filter((n) => !(!n.filters && !n.colorFilters && !n.customFilters)).forEach((n) => this._setCriteriaWithoutReCalc(n.colId, n)), e.cachedFilteredOut ? (this._alreadyFilteredOutRows = new Set(e.cachedFilteredOut), this._emit()) : e.filterColumns && e.filterColumns.length > 0 && (this._reCalcAllColumns(), this._emit()), this._emitHasCriteria();
119
- }
120
- isRowFiltered(e) {
121
- return this._alreadyFilteredOutRows.has(e);
122
- }
123
- getRange() {
124
- if (!this._range)
125
- throw new Error("[FilterModel] could not get range before a range is set!");
126
- return this._range;
127
- }
128
- /**
129
- * Get filtered out rows except the specific column. This method is considered as "pure". In
130
- * another word it would not change `filteredOutRows` on `FilterModel` nor `FilterColumn`.
131
- * @param col
132
- */
133
- getFilteredOutRowsExceptCol(e) {
134
- return this._getAllFilterColumns(!0).filter(([r]) => r !== e).reduce((r, [, n]) => {
135
- const s = n.calc({ getAlreadyFilteredOutRows: () => r });
136
- return s ? K(r, s) : r;
137
- }, /* @__PURE__ */ new Set());
138
- }
139
- /**
140
- * Set range of the filter model, this would remove some `IFilterColumn`
141
- * if the new range not overlaps the old range.
142
- */
143
- setRange(e) {
144
- this._range = e, this._getAllFilterColumns(!0).forEach(([r, n]) => {
145
- n.setRangeAndColumn({
146
- startRow: e.startRow,
147
- endRow: e.endRow,
148
- startColumn: r,
149
- endColumn: r
150
- }, r);
151
- });
152
- }
153
- /**
154
- * Set or remove filter criteria on a specific row.
155
- */
156
- setCriteria(e, r, n = !1) {
157
- if (!this._range)
158
- throw new Error("[FilterModel] could not set criteria before a range is set!");
159
- if (!r) {
160
- this._removeCriteria(e), this._rebuildAlreadyFilteredOutRowsWithCache(), n && this._reCalcAllColumns(), this._emit(), this._emitHasCriteria();
161
- return;
162
- }
163
- this._setCriteriaWithoutReCalc(e, r), n && (this._rebuildAlreadyFilteredOutRowsWithCache(), this._getAllFilterColumns().forEach((s) => s.__clearCache()), this._reCalcWithNoCacheColumns(), this._emit(), this._emitHasCriteria());
164
- }
165
- getAllFilterColumns() {
166
- return this._getAllFilterColumns(!0);
167
- }
168
- getFilterColumn(e) {
169
- var r;
170
- return (r = this._filterColumnByIndex.get(e)) != null ? r : null;
171
- }
172
- reCalc() {
173
- this._reCalcAllColumns(), this._emit();
174
- }
175
- _getAllFilterColumns(e = !1) {
176
- const r = Array.from(this._filterColumnByIndex.entries());
177
- return e ? r : r.map(([n, s]) => s);
178
- }
179
- _reCalcAllColumns() {
180
- this._alreadyFilteredOutRows = Y(), this._getAllFilterColumns().forEach((e) => e.__clearCache()), this._reCalcWithNoCacheColumns();
181
- }
182
- _setCriteriaWithoutReCalc(e, r) {
183
- const n = this._range;
184
- if (!n)
185
- throw new Error("[FilterModel] could not set criteria before a range is set!");
186
- const { startColumn: s, endColumn: o } = n;
187
- if (e > o || e < s)
188
- throw new Error(`[FilterModel] could not set criteria on column ${e} which is out of range!`);
189
- let l;
190
- this._filterColumnByIndex.has(e) ? l = this._filterColumnByIndex.get(e) : (l = new At(
191
- this.unitId,
192
- this.subUnitId,
193
- this._worksheet,
194
- r,
195
- { getAlreadyFilteredOutRows: () => this._alreadyFilteredOutRows }
196
- ), l.setRangeAndColumn(n, e), this._filterColumnByIndex.set(e, l)), l.setCriteria(r);
197
- }
198
- _removeCriteria(e) {
199
- const r = this._filterColumnByIndex.get(e);
200
- r && (r.dispose(), this._filterColumnByIndex.delete(e));
201
- }
202
- _emit() {
203
- this._filteredOutRows$.next(this._alreadyFilteredOutRows);
204
- }
205
- _emitHasCriteria() {
206
- this._hasCriteria$.next(this._filterColumnByIndex.size > 0);
207
- }
208
- _rebuildAlreadyFilteredOutRowsWithCache() {
209
- const e = this._getAllFilterColumns().filter((r) => r.hasCache()).reduce((r, n) => K(r, n.filteredOutRows), /* @__PURE__ */ new Set());
210
- this._alreadyFilteredOutRows = e;
211
- }
212
- _reCalcWithNoCacheColumns() {
213
- const e = this._getAllFilterColumns().filter((r) => !r.hasCache());
214
- for (const r of e) {
215
- const n = r.reCalc();
216
- n && (this._alreadyFilteredOutRows = K(this._alreadyFilteredOutRows, n));
217
- }
218
- }
219
- }
220
- class At extends P {
221
- constructor(e, r, n, s, o) {
222
- super();
223
- C(this, "_filteredOutRows", null);
224
- /** Cache the filter function. */
225
- C(this, "_filterFn", null);
226
- C(this, "_range", null);
227
- C(this, "_column", 0);
228
- C(this, "_filterBy", b.VALUES);
229
- this.unitId = e, this.subUnitId = r, this._worksheet = n, this._criteria = s, this._filterColumnContext = o;
230
- }
231
- get filteredOutRows() {
232
- return this._filteredOutRows;
233
- }
234
- get filterBy() {
235
- return this._filterBy;
236
- }
237
- dispose() {
238
- super.dispose(), this._filteredOutRows = null;
239
- }
240
- /**
241
- * @internal
242
- */
243
- __clearCache() {
244
- this._filteredOutRows = null;
245
- }
246
- serialize() {
247
- if (!this._criteria)
248
- throw new Error("[FilterColumn]: could not serialize without a filter column!");
249
- return se.deepClone({
250
- ...this._criteria,
251
- colId: this._column
252
- });
253
- }
254
- hasCache() {
255
- return this._filteredOutRows !== null;
256
- }
257
- // The first row should be omitted!
258
- setRangeAndColumn(e, r) {
259
- this._range = e, this._column = r;
260
- }
261
- setCriteria(e) {
262
- this._criteria = e, this._generateFilterFn(), this._filteredOutRows = null;
263
- }
264
- getColumnData() {
265
- return se.deepClone(this._criteria);
266
- }
267
- /**
268
- * Trigger new calculation on this `FilterModel` instance.
269
- *
270
- * @external DO NOT EVER call this method from `FilterColumn` itself. The whole process heavily relies on
271
- * `filteredOutByOthers`, and it is more comprehensible if we let `FilterModel` take full control over the process.
272
- */
273
- reCalc() {
274
- return this._filteredOutRows = this.calc(this._filterColumnContext), this._filteredOutRows;
275
- }
276
- calc(e) {
277
- if (!this._filterFn)
278
- throw new Error("[FilterColumn] cannot calculate without a filter fn!");
279
- if (!this._range)
280
- throw new Error("[FilterColumn] cannot calculate without a range!");
281
- if (typeof this._column != "number")
282
- throw new TypeError("[FilterColumn] cannot calculate without a column offset!");
283
- const r = this._column, n = { startColumn: r, endColumn: r, startRow: this._range.startRow + 1, endRow: this._range.endRow }, s = /* @__PURE__ */ new Set(), o = e.getAlreadyFilteredOutRows();
284
- for (const l of this._worksheet.iterateByColumn(n, !1, !1)) {
285
- const { row: a, rowSpan: c, col: u } = l;
286
- if (o.has(a) && (!c || c === 1))
287
- continue;
288
- if (!(this._filterBy === b.VALUES ? this._filterFn(Pe(this._worksheet.getCell(a, u))) : this._filterBy === b.COLORS ? this._filterFn(this._worksheet.getComposedCellStyle(a, u)) : this._filterFn(Pt(this._worksheet, a, u))) && (s.add(a), c))
289
- for (let h = 1; h < c; h++)
290
- s.add(a + h);
291
- }
292
- return s;
293
- }
294
- _generateFilterFn() {
295
- this._criteria && (this._filterFn = Nt(this._criteria), this._filterBy = this._criteria.filters ? b.VALUES : this._criteria.colorFilters ? b.COLORS : b.CONDITIONS);
296
- }
297
- }
298
- function Nt(i) {
299
- if (i.filters)
300
- return Tt(i.filters);
301
- if (i.colorFilters)
302
- return It(i.colorFilters);
303
- if (i.customFilters)
304
- return xt(i.customFilters);
305
- throw new Error("[FilterModel]: other types of filters are not supported yet.");
306
- }
307
- function Tt(i) {
308
- const t = !!i.blank, e = new Set(i.filters);
309
- return (r) => r === void 0 || r === "" ? t : e.has(typeof r == "string" ? r : `${r}`);
310
- }
311
- function It(i) {
312
- if (i.cellFillColors) {
313
- const t = new Set(i.cellFillColors);
314
- return (e) => {
315
- var n;
316
- if (!e || !((n = e.bg) != null && n.rgb))
317
- return !!t.has(null);
318
- const r = new oe(e.bg.rgb).toRgbString();
319
- return t.has(r);
320
- };
321
- }
322
- if (i.cellTextColors) {
323
- const t = new Set(i.cellTextColors);
324
- return (e) => {
325
- var n;
326
- if (!e || !((n = e.cl) != null && n.rgb))
327
- return !!t.has(gt);
328
- const r = new oe(e.cl.rgb).toRgbString();
329
- return t.has(r);
330
- };
331
- }
332
- throw new Error("[FilterModel]: color filters are not supported yet.");
333
- }
334
- function xt(i) {
335
- const t = i.customFilters.map((e) => Ut(e));
336
- return Lt(t) ? i.and ? bt(t) : $t(t) : t[0];
337
- }
338
- function bt(i) {
339
- const [t, e] = i;
340
- return (r) => t(r) && e(r);
341
- }
342
- function $t(i) {
343
- const [t, e] = i;
344
- return (r) => t(r) || e(r);
345
- }
346
- function Lt(i) {
347
- return i.length === 2;
348
- }
349
- function Ut(i) {
350
- const t = i.val;
351
- if (i.operator === I.NOT_EQUALS && !de(t))
352
- return (n) => ye.fn(n, t);
353
- if (Et(i.operator)) {
354
- if (!de(t)) return () => !1;
355
- const n = ce(i.operator), s = Number(t);
356
- return (o) => n.fn(o, s);
357
- }
358
- const e = ce(i.operator);
359
- return (r) => e.fn(r, t);
360
- }
361
- function Pt(i, t, e) {
362
- const r = i.getCell(t, e);
363
- if (!r) return null;
364
- const n = i.getCellRaw(t, e);
365
- return r && !n ? ue(r) : n ? r.t === k.NUMBER && typeof r.v == "string" ? n.v : r.t === k.NUMBER ? Number(n.v) : ue(n) : null;
366
- }
367
- function ue(i) {
368
- var r, n;
369
- const t = (n = (r = i.p) == null ? void 0 : r.body) == null ? void 0 : n.dataStream;
370
- if (t) return t.trimEnd();
371
- const e = i.v;
372
- return typeof e == "string" ? i.t === k.BOOLEAN ? e.toUpperCase() : e : typeof e == "number" ? i.t === k.BOOLEAN ? e ? "TRUE" : "FALSE" : e : typeof e == "boolean" ? e ? "TRUE" : "FALSE" : "";
373
- }
374
- var Dt = Object.getOwnPropertyDescriptor, Bt = (i, t, e, r) => {
375
- for (var n = r > 1 ? void 0 : r ? Dt(t, e) : t, s = i.length - 1, o; s >= 0; s--)
376
- (o = i[s]) && (n = o(n) || n);
377
- return n;
378
- }, X = (i, t) => (e, r) => t(e, r, i);
379
- const Te = "SHEET_FILTER_PLUGIN";
380
- let M = class extends P {
381
- constructor(t, e, r) {
382
- super();
383
- C(this, "_filterModels", /* @__PURE__ */ new Map());
384
- C(this, "_loadedUnitId$", new $(null));
385
- C(this, "loadedUnitId$", this._loadedUnitId$.asObservable());
386
- C(this, "_errorMsg$", new $(null));
387
- C(this, "errorMsg$", this._errorMsg$.asObservable());
388
- C(this, "_activeFilterModel$", new $(null));
389
- /** An observable value emitting the current Workbook's active Worksheet's filter model (if there is one). */
390
- C(this, "activeFilterModel$", this._activeFilterModel$.asObservable());
391
- this._resourcesManagerService = t, this._univerInstanceService = e, this._commandService = r, this._initModel(), this._initActiveFilterModel();
392
- }
393
- /** The current Workbook's active Worksheet's filter model (if there is one). */
394
- get activeFilterModel() {
395
- return this._activeFilterModel$.getValue();
396
- }
397
- /**
398
- *
399
- * @param unitId
400
- * @param subUnitId
401
- */
402
- ensureFilterModel(t, e) {
403
- const r = this.getFilterModel(t, e);
404
- if (r)
405
- return r;
406
- const n = this._univerInstanceService.getUniverSheetInstance(t);
407
- if (!n)
408
- throw new Error(`[SheetsFilterService]: could not create "FilterModel" on a non-existing workbook ${t}!`);
409
- const s = n.getSheetBySheetId(e);
410
- if (!s)
411
- throw new Error(`[SheetsFilterService]: could not create "FilterModel" on a non-existing worksheet ${e}!`);
412
- const o = new q(t, e, s);
413
- return this._cacheFilterModel(t, e, o), o;
414
- }
415
- getFilterModel(t, e) {
416
- var r, n;
417
- return (n = (r = this._filterModels.get(t)) == null ? void 0 : r.get(e)) != null ? n : null;
418
- }
419
- removeFilterModel(t, e) {
420
- const r = this.getFilterModel(t, e);
421
- return r ? (r.dispose(), this._filterModels.get(t).delete(e), !0) : !1;
422
- }
423
- setFilterErrorMsg(t) {
424
- this._errorMsg$.next(t);
425
- }
426
- _updateActiveFilterModel() {
427
- let t;
428
- try {
429
- if (t = this._univerInstanceService.getCurrentUnitForType(B.UNIVER_SHEET), !t) {
430
- this._activeFilterModel$.next(null);
431
- return;
432
- }
433
- } catch (o) {
434
- console.error("[SheetsFilterService]: could not get active workbook!", o);
435
- return;
436
- }
437
- const e = t.getActiveSheet(!0);
438
- if (!e) {
439
- this._activeFilterModel$.next(null);
440
- return;
441
- }
442
- const r = e.getUnitId(), n = e.getSheetId(), s = this.getFilterModel(r, n);
443
- this._activeFilterModel$.next(s);
444
- }
445
- _initActiveFilterModel() {
446
- this.disposeWithMe(
447
- ut(
448
- // source1: executing filter related mutations
449
- De(this._commandService.onCommandExecuted.bind(this._commandService)).pipe(ht(([t]) => t.type === O.MUTATION && Oe.has(t.id))),
450
- // source2: activate sheet changes
451
- this._univerInstanceService.getCurrentTypeOfUnit$(B.UNIVER_SHEET).pipe(ft((t) => {
452
- var e;
453
- return (e = t == null ? void 0 : t.activeSheet$) != null ? e : mt(null);
454
- }))
455
- ).subscribe(() => this._updateActiveFilterModel())
456
- );
457
- }
458
- _serializeAutoFiltersForUnit(t) {
459
- const e = this._filterModels.get(t);
460
- if (!e)
461
- return "{}";
462
- const r = {};
463
- return e.forEach((n, s) => {
464
- r[s] = n.serialize();
465
- }), JSON.stringify(r);
466
- }
467
- _deserializeAutoFiltersForUnit(t, e) {
468
- const r = this._univerInstanceService.getUniverSheetInstance(t);
469
- Object.keys(e).forEach((n) => {
470
- const s = e[n], o = q.deserialize(t, n, r.getSheetBySheetId(n), s);
471
- this._cacheFilterModel(t, n, o);
472
- });
473
- }
474
- dispose() {
475
- super.dispose(), this._loadedUnitId$.complete(), this._errorMsg$.complete(), this._activeFilterModel$.complete(), this._filterModels.forEach((t) => {
476
- t.forEach((e) => e.dispose()), t.clear();
477
- }), this._filterModels.clear();
478
- }
479
- _initModel() {
480
- this._resourcesManagerService.registerPluginResource({
481
- pluginName: Te,
482
- businesses: [B.UNIVER_SHEET],
483
- toJson: (t) => this._serializeAutoFiltersForUnit(t),
484
- parseJson: (t) => JSON.parse(t),
485
- onLoad: (t, e) => {
486
- this._deserializeAutoFiltersForUnit(t, e), this._loadedUnitId$.next(t), this._updateActiveFilterModel();
487
- },
488
- onUnLoad: (t) => {
489
- const e = this._filterModels.get(t);
490
- e && (e.forEach((r) => r.dispose()), this._filterModels.delete(t));
491
- }
492
- });
493
- }
494
- _cacheFilterModel(t, e, r) {
495
- this._filterModels.has(t) || this._filterModels.set(t, /* @__PURE__ */ new Map()), this._filterModels.get(t).set(e, r);
496
- }
497
- };
498
- M = Bt([
499
- X(0, Be),
500
- X(1, T),
501
- X(2, N)
502
- ], M);
503
- const R = {
504
- id: we,
505
- type: O.MUTATION,
506
- handler: (i, t) => {
507
- const { subUnitId: e, unitId: r, range: n } = t;
508
- return i.get(M).ensureFilterModel(r, e).setRange(n), !0;
509
- }
510
- }, p = {
511
- id: ve,
512
- type: O.MUTATION,
513
- handler: (i, t) => {
514
- const { subUnitId: e, unitId: r, criteria: n, col: s, reCalc: o = !0 } = t, a = i.get(M).getFilterModel(r, e);
515
- return a ? (a.setCriteria(s, n, o), !0) : !1;
516
- }
517
- }, y = {
518
- id: Me,
519
- type: O.MUTATION,
520
- handler: (i, t) => {
521
- const { unitId: e, subUnitId: r } = t;
522
- return i.get(M).removeFilterModel(e, r);
523
- }
524
- }, z = {
525
- id: Ee,
526
- type: O.MUTATION,
527
- handler: (i, t) => {
528
- const { unitId: e, subUnitId: r } = t, s = i.get(M).getFilterModel(e, r);
529
- return s ? (s.reCalc(), !0) : !1;
530
- }
531
- }, zt = {
532
- id: "sheet.command.set-filter-range",
533
- type: O.COMMAND,
534
- handler: (i, t) => {
535
- const e = i.get(M), r = i.get(N), n = i.get(J), s = i.get(T), { unitId: o, subUnitId: l, range: a } = t;
536
- if (!V(s, t) || e.getFilterModel(o, l)) return !1;
537
- if (a.endRow === a.startRow) {
538
- const g = i.get(ze), _ = i.get(He);
539
- return g.emit(_.t("sheets-filter.command.not-valid-filter-range")), !1;
540
- }
541
- const d = { id: R.id, params: { unitId: o, subUnitId: l, range: a } }, h = r.syncExecuteCommand(d.id, d.params);
542
- return h && n.pushUndoRedo({
543
- unitID: o,
544
- undoMutations: [{ id: y.id, params: { unitId: o, subUnitId: l } }],
545
- redoMutations: [d]
546
- }), h;
547
- }
548
- }, Ht = {
549
- id: "sheet.command.remove-sheet-filter",
550
- type: O.COMMAND,
551
- handler: (i, t) => {
552
- const e = i.get(T), r = i.get(M), n = i.get(N), s = i.get(J), o = V(e, t);
553
- if (!o) return !1;
554
- const { unitId: l, subUnitId: a } = o, c = r.getFilterModel(l, a);
555
- if (!c) return !1;
556
- const u = c == null ? void 0 : c.serialize(), d = Vt(l, a, u), h = n.syncExecuteCommand(y.id, { unitId: l, subUnitId: a });
557
- return h && s.pushUndoRedo({
558
- unitID: l,
559
- undoMutations: d,
560
- redoMutations: [{ id: y.id, params: { unitId: l, subUnitId: a } }]
561
- }), h;
562
- }
563
- }, ur = {
564
- id: "sheet.command.smart-toggle-filter",
565
- type: O.COMMAND,
566
- handler: async (i) => {
567
- const t = i.get(T), e = i.get(M), r = i.get(N), n = t.getCurrentUnitForType(B.UNIVER_SHEET), s = n == null ? void 0 : n.getActiveSheet();
568
- if (!s || !n) return !1;
569
- const o = n.getUnitId(), l = s.getSheetId();
570
- if (e.getFilterModel(o, l))
571
- return r.executeCommand(Ht.id, { unitId: o, subUnitId: l });
572
- const u = i.get(Ge).getCurrentLastSelection();
573
- if (!u) return !1;
574
- const d = u.range, h = (
575
- // If the selection is a single cell, we should expand it to a continuous range in all directions.
576
- Qe(u) ? re(d, { left: !0, right: !0, up: !0, down: !0 }, s) : d.startRow === d.endRow ? re(d, { down: !0 }, s) : d
577
- );
578
- return r.executeCommand(zt.id, {
579
- unitId: o,
580
- subUnitId: l,
581
- range: h
582
- });
583
- }
584
- }, hr = {
585
- id: "sheet.command.set-filter-criteria",
586
- type: O.COMMAND,
587
- handler: (i, t) => {
588
- const e = i.get(M), r = i.get(N), n = i.get(J), { unitId: s, subUnitId: o, col: l, criteria: a } = t, c = e.getFilterModel(s, o);
589
- if (!c) return !1;
590
- const u = c.getRange();
591
- if (!u || l < u.startColumn || l > u.endColumn) return !1;
592
- const d = c.getFilterColumn(l), h = jt(s, o, l, d), g = {
593
- id: p.id,
594
- params: {
595
- unitId: s,
596
- subUnitId: o,
597
- col: l,
598
- criteria: a
599
- }
600
- }, _ = r.syncExecuteCommand(g.id, g.params);
601
- return _ && n.pushUndoRedo({
602
- unitID: s,
603
- undoMutations: [h],
604
- redoMutations: [g]
605
- }), _;
606
- }
607
- }, fr = {
608
- id: "sheet.command.clear-filter-criteria",
609
- type: O.COMMAND,
610
- handler: (i, t) => {
611
- const e = i.get(M), r = i.get(J), n = i.get(N), s = i.get(T), o = V(s, t);
612
- if (!o) return !1;
613
- const { unitId: l, subUnitId: a } = o, c = e.getFilterModel(o.unitId, o.subUnitId);
614
- if (!c) return !1;
615
- const u = c.serialize(), d = Ie(l, a, u), h = Wt(l, a, u);
616
- return j(h, n).result ? (r.pushUndoRedo({
617
- unitID: l,
618
- undoMutations: d,
619
- redoMutations: h
620
- }), !0) : !1;
621
- }
622
- }, mr = {
623
- id: "sheet.command.re-calc-filter",
624
- type: O.COMMAND,
625
- handler: (i, t) => {
626
- const e = i.get(M), r = i.get(N), n = i.get(T), s = V(n, t);
627
- if (!s) return !1;
628
- const { unitId: o, subUnitId: l } = s;
629
- return e.getFilterModel(s.unitId, s.subUnitId) ? r.executeCommand(z.id, { unitId: o, subUnitId: l }) : !1;
630
- }
631
- };
632
- function Vt(i, t, e) {
633
- const r = [], n = {
634
- id: R.id,
635
- params: {
636
- unitId: i,
637
- subUnitId: t,
638
- range: e.ref
639
- }
640
- };
641
- return r.push(n), Ie(i, t, e).forEach((o) => r.push(o)), r;
642
- }
643
- function Ie(i, t, e) {
644
- var n;
645
- const r = [];
646
- return (n = e.filterColumns) == null || n.forEach((s) => {
647
- const o = {
648
- id: p.id,
649
- params: {
650
- unitId: i,
651
- subUnitId: t,
652
- col: s.colId,
653
- criteria: s
654
- }
655
- };
656
- r.push(o);
657
- }), r;
658
- }
659
- function Wt(i, t, e) {
660
- var n;
661
- const r = [];
662
- return (n = e.filterColumns) == null || n.forEach((s) => {
663
- const o = {
664
- id: p.id,
665
- params: {
666
- unitId: i,
667
- subUnitId: t,
668
- col: s.colId,
669
- criteria: null
670
- }
671
- };
672
- r.push(o);
673
- }), r;
674
- }
675
- function jt(i, t, e, r) {
676
- if (!r)
677
- return {
678
- id: p.id,
679
- params: {
680
- unitId: i,
681
- subUnitId: t,
682
- col: e,
683
- criteria: null
684
- }
685
- };
686
- const n = r.serialize();
687
- return {
688
- id: p.id,
689
- params: {
690
- unitId: i,
691
- subUnitId: t,
692
- col: e,
693
- criteria: n
694
- }
695
- };
696
- }
697
- const xe = "sheets-filter.config", he = {};
698
- function kt(i, t) {
699
- for (let e = 0; e < i.length; e++) {
700
- let r = e;
701
- if (i[e])
702
- for (let n = e + 1; n < i.length; n++)
703
- i[r] && i[n] && t(i[r], i[n]) && (i[r] = null, r = n);
704
- }
705
- return i.filter((e) => e !== null);
706
- }
707
- function L(i) {
708
- return kt(i, (t, e) => t.id === p.id && e.id === p.id && t.params.unitId === e.params.unitId && t.params.subUnitId === e.params.subUnitId && t.params.col === e.params.col);
709
- }
710
- var qt = Object.getOwnPropertyDescriptor, Gt = (i, t, e, r) => {
711
- for (var n = r > 1 ? void 0 : r ? qt(t, e) : t, s = i.length - 1, o; s >= 0; s--)
712
- (o = i[s]) && (n = o(n) || n);
713
- return n;
714
- }, x = (i, t) => (e, r) => t(e, r, i);
715
- let H = class extends P {
716
- constructor(t, e, r, n, s, o, l) {
717
- super();
718
- C(this, "_disposableCollection", new Ce());
719
- this._commandService = t, this._sheetInterceptorService = e, this._sheetsFilterService = r, this._univerInstanceService = n, this._refRangeService = s, this._dataSyncPrimaryController = o, this._zebraCrossingCacheController = l, this._initCommands(), this._initRowFilteredInterceptor(), this._initInterceptors(), this._commandExecutedListener(), this._initErrorHandling(), this._initZebraCrossingCacheListener();
720
- }
721
- _initZebraCrossingCacheListener() {
722
- this.disposeWithMe(
723
- this._sheetsFilterService.activeFilterModel$.subscribe((t) => {
724
- t && this.disposeWithMe(
725
- t.filteredOutRows$.subscribe(() => {
726
- this._zebraCrossingCacheController.updateZebraCrossingCache(t.unitId, t.subUnitId);
727
- })
728
- );
729
- })
730
- );
731
- }
732
- _initCommands() {
733
- [
734
- p,
735
- R,
736
- z,
737
- y
738
- ].forEach((t) => {
739
- var e;
740
- this.disposeWithMe(this._commandService.registerCommand(t)), (e = this._dataSyncPrimaryController) == null || e.registerSyncingMutations(t);
741
- });
742
- }
743
- _initInterceptors() {
744
- this.disposeWithMe(this._sheetInterceptorService.interceptCommand({
745
- getMutations: (t) => this._getUpdateFilter(t)
746
- })), this.disposeWithMe(this._commandService.onCommandExecuted((t) => {
747
- if (t.id === Ye.id) {
748
- const e = t.params, r = e.subUnitId, n = e.unitId;
749
- if (!r || !n)
750
- return;
751
- this._registerRefRange(n, r);
752
- }
753
- if (t.id === R.id) {
754
- const e = t.params, r = e.subUnitId, n = e.unitId;
755
- if (!r || !n)
756
- return;
757
- this._registerRefRange(e.unitId, e.subUnitId);
758
- }
759
- })), this.disposeWithMe(this._sheetsFilterService.loadedUnitId$.subscribe((t) => {
760
- if (t) {
761
- const e = this._univerInstanceService.getUniverSheetInstance(t), r = e == null ? void 0 : e.getActiveSheet();
762
- r && this._registerRefRange(t, r.getSheetId());
763
- }
764
- }));
765
- }
766
- _registerRefRange(t, e) {
767
- var l;
768
- this._disposableCollection.dispose();
769
- const r = this._univerInstanceService.getUniverSheetInstance(t), n = r == null ? void 0 : r.getSheetBySheetId(e);
770
- if (!r || !n) return;
771
- const s = (l = this._sheetsFilterService.getFilterModel(t, e)) == null ? void 0 : l.getRange(), o = (a) => {
772
- switch (a.id) {
773
- case dt.id: {
774
- const c = a.params, u = c.unitId || t, d = c.subUnitId || e;
775
- return this._handleInsertRowCommand(c, u, d);
776
- }
777
- case ct.id: {
778
- const c = a.params, u = c.unitId || t, d = c.subUnitId || e;
779
- return this.handleInsertColCommand(c.range, u, d);
780
- }
781
- case at.id: {
782
- const c = a.params;
783
- return this.handleRemoveColCommand(c.range, t, e);
784
- }
785
- case lt.id: {
786
- const c = a.params;
787
- return this._handleRemoveRowCommand(c, t, e);
788
- }
789
- case ae.MoveColsCommandId: {
790
- const c = a.params;
791
- return this.handleMoveColsCommand({
792
- fromRange: c.fromRange,
793
- toRange: c.toRange
794
- }, t, e);
795
- }
796
- case ae.MoveRowsCommandId: {
797
- const c = a.params;
798
- return this._handleMoveRowsCommand(c, t, e);
799
- }
800
- case ot.id: {
801
- const c = a.params;
802
- return this._handleMoveRangeCommand(c, t, e);
803
- }
804
- }
805
- return { redos: [], undos: [] };
806
- };
807
- s && this._disposableCollection.add(this._refRangeService.registerRefRange(s, o, t, e));
808
- }
809
- _getUpdateFilter(t) {
810
- const { id: e } = t;
811
- switch (e) {
812
- case et.id: {
813
- const r = t.params;
814
- return this._handleRemoveSheetCommand(r, r.unitId, r.subUnitId);
815
- }
816
- case Xe.id: {
817
- const r = t.params, { targetSubUnitId: n, unitId: s, subUnitId: o } = r;
818
- return !s || !o || !n ? this._handleNull() : this._handleCopySheetCommand(s, o, n);
819
- }
820
- }
821
- return {
822
- redos: [],
823
- undos: []
824
- };
825
- }
826
- handleInsertColCommand(t, e, r) {
827
- var f;
828
- const n = this._sheetsFilterService.getFilterModel(e, r), s = (f = n == null ? void 0 : n.getRange()) != null ? f : null;
829
- if (!n || !s)
830
- return this._handleNull();
831
- const { startColumn: o, endColumn: l } = s, { startColumn: a, endColumn: c } = t, u = c - a + 1;
832
- if (c > l)
833
- return this._handleNull();
834
- const d = [], h = [], g = a, _ = {
835
- unitId: e,
836
- subUnitId: r,
837
- range: {
838
- ...s,
839
- startColumn: a <= o ? o + u : o,
840
- endColumn: l + u
841
- }
842
- }, S = {
843
- unitId: e,
844
- subUnitId: r,
845
- range: s
846
- };
847
- d.push({ id: R.id, params: _ }), h.push({ id: R.id, params: S });
848
- const F = n.getAllFilterColumns().filter((m) => m[0] >= g);
849
- if (F.length !== 0) {
850
- const { newRange: m, oldRange: v } = this._moveCriteria(e, r, F, u);
851
- d.push(...v.redos, ...m.redos), h.push(...m.undos, ...v.undos);
852
- }
853
- return { redos: L(d), undos: L(h) };
854
- }
855
- _handleInsertRowCommand(t, e, r) {
856
- var S;
857
- const n = this._sheetsFilterService.getFilterModel(e, r), s = (S = n == null ? void 0 : n.getRange()) != null ? S : null;
858
- if (!n || !s)
859
- return this._handleNull();
860
- const { startRow: o, endRow: l } = s, { startRow: a, endRow: c } = t.range, u = c - a + 1;
861
- if (c > l)
862
- return this._handleNull();
863
- const d = [], h = [], g = {
864
- unitId: e,
865
- subUnitId: r,
866
- range: {
867
- ...s,
868
- startRow: a <= o ? o + u : o,
869
- endRow: l + u
870
- }
871
- }, _ = {
872
- unitId: e,
873
- subUnitId: r,
874
- range: s
875
- };
876
- return d.push({ id: R.id, params: g }), h.push({ id: R.id, params: _ }), {
877
- redos: L(d),
878
- undos: L(h)
879
- };
880
- }
881
- handleRemoveColCommand(t, e, r) {
882
- var F;
883
- const n = this._sheetsFilterService.getFilterModel(e, r), s = (F = n == null ? void 0 : n.getRange()) != null ? F : null;
884
- if (!n || !s)
885
- return this._handleNull();
886
- const { startColumn: o, endColumn: l } = s, { startColumn: a, endColumn: c } = t;
887
- if (a > l)
888
- return this._handleNull();
889
- const u = [], d = [], h = c < o ? 0 : Math.min(c, l) - Math.max(a, o) + 1, g = c - a + 1, _ = n.getAllFilterColumns();
890
- _.forEach((f) => {
891
- const [m, v] = f;
892
- m <= c && m >= a && (u.push({ id: p.id, params: { unitId: e, subUnitId: r, col: m, criteria: null } }), d.push({ id: p.id, params: { unitId: e, subUnitId: r, col: m, criteria: { ...v.serialize(), colId: m } } }));
893
- });
894
- const S = _.filter((f) => {
895
- const [m, v] = f;
896
- return m > c;
897
- });
898
- let w = { undos: [], redos: [] };
899
- if (S.length > 0) {
900
- const { oldRange: f, newRange: m } = this._moveCriteria(e, r, S, -g);
901
- w = m, u.push(...f.redos), d.unshift(...f.undos);
902
- }
903
- if (h === l - o + 1) {
904
- const f = {
905
- unitId: e,
906
- subUnitId: r
907
- };
908
- u.push({ id: y.id, params: f }), d.unshift({ id: R.id, params: { range: s, unitId: e, subUnitId: r } });
909
- } else {
910
- const f = o <= a ? o : h === 0 ? o - g : a, m = o <= a ? l - h : l - g, v = {
911
- unitId: e,
912
- subUnitId: r,
913
- range: { ...s, startColumn: f, endColumn: m }
914
- };
915
- u.push({ id: R.id, params: v }), d.unshift({ id: R.id, params: { range: s, unitId: e, subUnitId: r } }), u.push(...w.redos), d.unshift(...w.undos);
916
- }
917
- return {
918
- undos: d,
919
- redos: u
920
- };
921
- }
922
- _handleRemoveRowCommand(t, e, r) {
923
- var S;
924
- const n = this._sheetsFilterService.getFilterModel(e, r);
925
- if (!n)
926
- return this._handleNull();
927
- const s = n.getRange(), { startRow: o, endRow: l } = s, { startRow: a, endRow: c } = t.range;
928
- if (a > l)
929
- return this._handleNull();
930
- if (c < o)
931
- return {
932
- undos: [{ id: R.id, params: { range: s, unitId: e, subUnitId: r } }],
933
- redos: [{
934
- id: R.id,
935
- params: {
936
- range: {
937
- ...s,
938
- startRow: o - (c - a + 1),
939
- endRow: l - (c - a + 1)
940
- },
941
- unitId: e,
942
- subUnitId: r
943
- }
944
- }]
945
- };
946
- const u = [], d = [], h = n.getAllFilterColumns(), g = o <= c && o >= a;
947
- d.push({ id: R.id, params: { range: s, unitId: e, subUnitId: r } });
948
- const _ = Math.min(c, l) - Math.max(a, o) + 1;
949
- if (_ === l - o + 1 || g) {
950
- const w = {
951
- unitId: e,
952
- subUnitId: r
953
- };
954
- u.push({ id: y.id, params: w }), h.forEach((F) => {
955
- const [f, m] = F, v = {
956
- unitId: e,
957
- subUnitId: r,
958
- col: f,
959
- criteria: { ...m.serialize(), colId: f }
960
- };
961
- d.push({ id: p.id, params: v });
962
- });
963
- } else {
964
- const w = (S = this._univerInstanceService.getUniverSheetInstance(e)) == null ? void 0 : S.getSheetBySheetId(r);
965
- if (!w)
966
- return this._handleNull();
967
- const F = [];
968
- for (let E = a; E <= c; E++)
969
- w.getRowFiltered(E) && F.push(E);
970
- const f = Math.min(o, a), m = f + (l - o) - _ + F.length, v = {
971
- unitId: e,
972
- subUnitId: r,
973
- range: {
974
- ...s,
975
- startRow: f,
976
- endRow: m
977
- }
978
- };
979
- u.push({ id: R.id, params: v });
980
- }
981
- return {
982
- undos: L(d),
983
- redos: L(u)
984
- };
985
- }
986
- // eslint-disable-next-line max-lines-per-function
987
- handleMoveColsCommand({ fromRange: t, toRange: e }, r, n) {
988
- var F;
989
- const s = this._sheetsFilterService.getFilterModel(r, n), o = (F = s == null ? void 0 : s.getRange()) != null ? F : null;
990
- if (!s || !o)
991
- return this._handleNull();
992
- const { startColumn: l, endColumn: a } = o;
993
- if (t.endColumn < l && e.startColumn <= l || t.startColumn > a && e.endColumn > a)
994
- return this._handleNull();
995
- const c = [], u = [], d = {};
996
- for (let f = l; f <= a; f++)
997
- d[f] = {
998
- colIndex: f,
999
- filter: s.getFilterColumn(f)
1000
- };
1001
- le(t.startColumn, t.endColumn - t.startColumn + 1, e.startColumn, d);
1002
- let h = o.startColumn, g = o.endColumn;
1003
- l >= t.startColumn && l <= t.endColumn && e.startColumn > t.startColumn && t.endColumn < a && (h = t.endColumn + 1), a >= t.startColumn && a <= t.endColumn && e.startColumn < t.startColumn && t.startColumn > l && (g = t.startColumn - 1);
1004
- const _ = Object.keys(d).map((f) => Number(f)), S = _.find((f) => d[f].colIndex === g), w = _.find((f) => d[f].colIndex === h);
1005
- if (_.forEach((f) => {
1006
- var ne, ie;
1007
- const { colIndex: m, filter: v } = d[f], E = f;
1008
- if (v) {
1009
- if (E >= w && E <= S) {
1010
- const Z = {
1011
- unitId: r,
1012
- subUnitId: n,
1013
- col: E,
1014
- criteria: { ...v.serialize(), colId: E }
1015
- }, be = {
1016
- unitId: r,
1017
- subUnitId: n,
1018
- col: E,
1019
- criteria: s.getFilterColumn(E) ? { ...(ne = s.getFilterColumn(E)) == null ? void 0 : ne.serialize(), colId: E } : null
1020
- };
1021
- c.push({ id: p.id, params: Z }), u.push({ id: p.id, params: be });
1022
- }
1023
- if (!((ie = d[m]) != null && ie.filter)) {
1024
- const Z = {
1025
- unitId: r,
1026
- subUnitId: n,
1027
- col: m,
1028
- criteria: null
1029
- };
1030
- c.push({ id: p.id, params: Z }), u.push({ id: p.id, params: { unitId: r, subUnitId: n, col: m, criteria: { ...v.serialize(), colId: m } } });
1031
- }
1032
- }
1033
- }), l !== w || a !== S) {
1034
- const f = {
1035
- unitId: r,
1036
- subUnitId: n,
1037
- range: {
1038
- ...o,
1039
- startColumn: w,
1040
- endColumn: S
1041
- }
1042
- };
1043
- c.unshift({ id: R.id, params: f }), u.unshift({ id: R.id, params: { range: o, unitId: r, subUnitId: n } });
1044
- }
1045
- return {
1046
- undos: u,
1047
- redos: c
1048
- };
1049
- }
1050
- _handleMoveRowsCommand(t, e, r) {
1051
- var f;
1052
- const n = this._sheetsFilterService.getFilterModel(e, r), s = (f = n == null ? void 0 : n.getRange()) != null ? f : null;
1053
- if (!n || !s)
1054
- return this._handleNull();
1055
- const { startRow: o, endRow: l } = s, { fromRange: a, toRange: c } = t;
1056
- if (a.endRow < o && c.startRow <= o || a.startRow > l && c.endRow > l)
1057
- return this._handleNull();
1058
- const u = [], d = [], h = {};
1059
- for (let m = o; m <= l; m++)
1060
- h[m] = {
1061
- oldIndex: m
1062
- };
1063
- const g = o;
1064
- let _ = l;
1065
- l >= a.startRow && l <= a.endRow && c.startRow < a.startRow && a.startRow > o && (_ = a.startRow - 1), le(a.startRow, a.endRow - a.startRow + 1, c.startRow, h);
1066
- const S = Object.keys(h).map((m) => Number(m)), w = S.find((m) => h[m].oldIndex === _), F = S.find((m) => h[m].oldIndex === g);
1067
- if (o !== F || l !== w) {
1068
- const m = {
1069
- unitId: e,
1070
- subUnitId: r,
1071
- range: {
1072
- ...s,
1073
- startRow: F,
1074
- endRow: w
1075
- }
1076
- };
1077
- u.push({ id: R.id, params: m }, { id: z.id, params: { unitId: e, subUnitId: r } }), d.push({ id: R.id, params: { range: s, unitId: e, subUnitId: r } }, { id: z.id, params: { unitId: e, subUnitId: r } });
1078
- }
1079
- return {
1080
- redos: u,
1081
- undos: d
1082
- };
1083
- }
1084
- _handleMoveRangeCommand(t, e, r) {
1085
- const { fromRange: n, toRange: s } = t, o = this._sheetsFilterService.getFilterModel(e, r);
1086
- if (!o)
1087
- return this._handleNull();
1088
- const l = o.getRange();
1089
- if (!l)
1090
- return this._handleNull();
1091
- const a = [], c = [];
1092
- if (te.contains(n, l)) {
1093
- const u = l.startRow - n.startRow, d = l.startColumn - n.startColumn, h = {
1094
- startRow: s.startRow + u,
1095
- startColumn: s.startColumn + d,
1096
- endRow: s.startRow + u + (l.endRow - l.startRow),
1097
- endColumn: s.startColumn + d + (l.endColumn - l.startColumn)
1098
- }, g = {
1099
- id: y.id,
1100
- params: {
1101
- unitId: e,
1102
- subUnitId: r
1103
- }
1104
- }, _ = { id: R.id, params: { unitId: e, subUnitId: r, range: h } }, S = { id: R.id, params: { unitId: e, subUnitId: r, range: l } };
1105
- a.push(g, _), c.push(g, S);
1106
- const w = o.getAllFilterColumns(), F = s.startColumn - n.startColumn;
1107
- w.forEach((f) => {
1108
- const [m, v] = f;
1109
- v && (a.push({ id: p.id, params: { unitId: e, subUnitId: r, col: m + F, criteria: { ...v.serialize(), colId: m + F } } }), c.push({ id: p.id, params: { unitId: e, subUnitId: r, col: m, criteria: { ...v.serialize(), colId: m } } }));
1110
- });
1111
- } else if (te.intersects(s, l)) {
1112
- const u = {
1113
- ...l,
1114
- endRow: Math.max(l.endRow, s.endRow)
1115
- };
1116
- a.push({ id: R.id, params: { unitId: e, subUnitId: r, range: u } }), c.push({ id: R.id, params: { unitId: e, subUnitId: r, range: l } });
1117
- }
1118
- return {
1119
- redos: a,
1120
- undos: c
1121
- };
1122
- }
1123
- _handleRemoveSheetCommand(t, e, r) {
1124
- const n = this._sheetsFilterService.getFilterModel(e, r);
1125
- if (!n)
1126
- return this._handleNull();
1127
- const s = n.getRange();
1128
- if (!s)
1129
- return this._handleNull();
1130
- const o = [], l = [];
1131
- return n.getAllFilterColumns().forEach(([c, u]) => {
1132
- l.push({ id: p.id, params: { unitId: e, subUnitId: r, col: c, criteria: { ...u.serialize(), colId: c } } });
1133
- }), o.push({ id: y.id, params: { unitId: e, subUnitId: r, range: s } }), l.unshift({ id: R.id, params: { range: s, unitId: e, subUnitId: r } }), {
1134
- undos: l,
1135
- redos: o
1136
- };
1137
- }
1138
- _handleCopySheetCommand(t, e, r) {
1139
- const n = this._sheetsFilterService.getFilterModel(t, e);
1140
- if (!n)
1141
- return this._handleNull();
1142
- const s = n.getRange();
1143
- if (!s)
1144
- return this._handleNull();
1145
- const o = [], l = [], a = [], c = [];
1146
- return n.getAllFilterColumns().forEach(([d, h]) => {
1147
- o.push({ id: p.id, params: { unitId: t, subUnitId: r, col: d, criteria: { ...h.serialize(), colId: d } } }), a.push({ id: p.id, params: { unitId: t, subUnitId: r, col: d, criteria: null } });
1148
- }), a.push({ id: y.id, params: { unitId: t, subUnitId: r, range: s } }), o.unshift({ id: R.id, params: { range: s, unitId: t, subUnitId: r } }), {
1149
- undos: l,
1150
- redos: o,
1151
- preUndos: a,
1152
- preRedos: c
1153
- };
1154
- }
1155
- _handleNull() {
1156
- return { redos: [], undos: [] };
1157
- }
1158
- _initRowFilteredInterceptor() {
1159
- this.disposeWithMe(this._sheetInterceptorService.intercept(tt.ROW_FILTERED, {
1160
- // sheet-interceptor.service.ts
1161
- handler: (t, e) => {
1162
- var r, n;
1163
- return t ? !0 : (n = (r = this._sheetsFilterService.getFilterModel(
1164
- e.unitId,
1165
- e.subUnitId
1166
- )) == null ? void 0 : r.isRowFiltered(e.row)) != null ? n : !1;
1167
- }
1168
- }));
1169
- }
1170
- _moveCriteria(t, e, r, n) {
1171
- const s = {
1172
- unitId: t,
1173
- subUnitId: e,
1174
- criteria: null,
1175
- col: -1
1176
- }, o = [], l = [], a = [], c = [];
1177
- return r.forEach((u) => {
1178
- const [d, h] = u;
1179
- l.push({
1180
- id: p.id,
1181
- params: {
1182
- ...s,
1183
- col: d
1184
- }
1185
- }), o.push({
1186
- id: p.id,
1187
- params: {
1188
- ...s,
1189
- col: d,
1190
- criteria: { ...h.serialize(), colId: d }
1191
- }
1192
- });
1193
- }), r.forEach((u) => {
1194
- const [d, h] = u;
1195
- c.push({
1196
- id: p.id,
1197
- params: {
1198
- ...s,
1199
- col: d + n,
1200
- criteria: { ...h.serialize(), colId: d + n }
1201
- }
1202
- }), a.push({
1203
- id: p.id,
1204
- params: {
1205
- ...s,
1206
- col: d + n,
1207
- criteria: null
1208
- }
1209
- });
1210
- }), {
1211
- newRange: {
1212
- redos: c,
1213
- undos: a
1214
- },
1215
- oldRange: {
1216
- redos: l,
1217
- undos: o
1218
- }
1219
- };
1220
- }
1221
- _commandExecutedListener() {
1222
- this.disposeWithMe(this._commandService.onCommandExecuted((t, e) => {
1223
- var c, u;
1224
- const { unitId: r, subUnitId: n } = t.params || {}, s = this._sheetsFilterService.getFilterModel(r, n);
1225
- if (!s) return;
1226
- const o = Array.from(s.filteredOutRows).sort((d, h) => d - h), l = [];
1227
- let a = !1;
1228
- if (t.id === rt.id) {
1229
- const { startRow: d, endRow: h } = t.params.range, g = o.filter((_) => _ >= d && _ <= h);
1230
- o.forEach((_) => {
1231
- if (_ < d)
1232
- l.push(_);
1233
- else if (a = !0, _ <= h) {
1234
- const S = Math.max(d, l.length ? l[l.length - 1] + 1 : d);
1235
- l.push(S);
1236
- } else
1237
- l.push(_ - (h - d + 1 - g.length));
1238
- });
1239
- }
1240
- if (t.id === nt.id) {
1241
- const { startRow: d, endRow: h } = t.params.range;
1242
- o.forEach((g) => {
1243
- g >= d ? (a = !0, l.push(g + (h - d + 1))) : l.push(g);
1244
- });
1245
- }
1246
- if (a && (s.filteredOutRows = new Set(l)), t.id === it.id && !(e != null && e.onlyLocal)) {
1247
- const d = this._getExtendRegion(r, n);
1248
- if (d) {
1249
- const h = t.params.cellValue;
1250
- if (h)
1251
- for (let g = d.startColumn; g <= d.endColumn; g++) {
1252
- const _ = (c = h == null ? void 0 : h[d.startRow]) == null ? void 0 : c[g];
1253
- if (_ && this._cellHasValue(_)) {
1254
- const S = (u = this._univerInstanceService.getUnit(r)) == null ? void 0 : u.getSheetBySheetId(n);
1255
- if (S) {
1256
- const w = re(d, { down: !0 }, S), F = this._sheetsFilterService.getFilterModel(r, n), f = F.getRange();
1257
- F.setRange({
1258
- ...f,
1259
- endRow: w.endRow
1260
- }), this._registerRefRange(r, n);
1261
- }
1262
- }
1263
- }
1264
- }
1265
- }
1266
- }));
1267
- }
1268
- _getExtendRegion(t, e) {
1269
- var a;
1270
- const r = this._sheetsFilterService.getFilterModel(t, e);
1271
- if (!r)
1272
- return null;
1273
- const n = (a = this._univerInstanceService.getUnit(t)) == null ? void 0 : a.getSheetBySheetId(e);
1274
- if (!n)
1275
- return null;
1276
- const s = r.getRange();
1277
- if (!s)
1278
- return null;
1279
- const o = n.getRowCount() - 1, l = n.getRowManager();
1280
- for (let c = s.endRow + 1; c <= o; c++)
1281
- if (l.getRowRawVisible(c))
1282
- return {
1283
- startRow: c,
1284
- endRow: c,
1285
- startColumn: s.startColumn,
1286
- endColumn: s.endColumn
1287
- };
1288
- return null;
1289
- }
1290
- _initErrorHandling() {
1291
- this.disposeWithMe(this._commandService.beforeCommandExecuted((t) => {
1292
- const e = t.params, r = V(this._univerInstanceService, e);
1293
- if (!r) return;
1294
- const { subUnitId: n, unitId: s } = r, o = this._sheetsFilterService.getFilterModel(s, n);
1295
- if (!o) return;
1296
- const l = o.getRange();
1297
- if (t.id === st.id && e.fromRange.startRow <= l.startRow && e.fromRange.endRow < l.endRow && e.fromRange.endRow >= l.startRow)
1298
- throw this._sheetsFilterService.setFilterErrorMsg("sheets-filter.msg.filter-header-forbidden"), new Error("[SheetsFilterController]: Cannot move header row of filter");
1299
- }));
1300
- }
1301
- _cellHasValue(t) {
1302
- const e = Object.values(t);
1303
- return !(e.length === 0 || e.every((r) => r == null));
1304
- }
1305
- };
1306
- H = Gt([
1307
- x(0, N),
1308
- x(1, A(Je)),
1309
- x(2, A(M)),
1310
- x(3, T),
1311
- x(4, A(Ze)),
1312
- x(5, Ve(_t)),
1313
- x(6, A(Ke))
1314
- ], H);
1315
- var Qt = Object.getOwnPropertyDescriptor, Jt = (i, t, e, r) => {
1316
- for (var n = r > 1 ? void 0 : r ? Qt(t, e) : t, s = i.length - 1, o; s >= 0; s--)
1317
- (o = i[s]) && (n = o(n) || n);
1318
- return n;
1319
- }, ee = (i, t) => (e, r) => t(e, r, i);
1320
- const Zt = [
1321
- p.id,
1322
- z.id
1323
- ], Kt = [
1324
- pe.id,
1325
- Se.id,
1326
- Fe.id
1327
- ];
1328
- let G = class extends P {
1329
- constructor(t, e, r) {
1330
- var s;
1331
- super();
1332
- C(this, "_d", new Ce());
1333
- C(this, "_visible$", new $(!1));
1334
- C(this, "visible$", this._visible$.asObservable());
1335
- C(this, "_enabled$", new $(!0));
1336
- C(this, "enabled$", this._enabled$.asObservable());
1337
- this._sheetsFilterController = t, this._commandService = e, this._configService = r;
1338
- const n = this._configService.getConfig(xe);
1339
- n != null && n.enableSyncSwitch && (this._visible$.next(!0), typeof n.enableSyncSwitch == "object" && this.setEnabled((s = n.enableSyncSwitch.defaultValue) != null ? s : !0));
1340
- }
1341
- get visible() {
1342
- return this._visible$.getValue();
1343
- }
1344
- get enabled() {
1345
- return this._enabled$.getValue();
1346
- }
1347
- setEnabled(t) {
1348
- this._enabled$.next(t), t ? this._d.dispose() : this._initOnlyLocalListener();
1349
- }
1350
- _initOnlyLocalListener() {
1351
- this._d.add(
1352
- this._commandService.beforeCommandExecuted((t, e) => {
1353
- Zt.includes(t.id) && (e || (e = {}), e.onlyLocal = !0);
1354
- })
1355
- ), this._d.add(
1356
- this._commandService.onCommandExecuted((t, e) => {
1357
- if (Kt.includes(t.id) && (e != null && e.fromCollab)) {
1358
- if (t.id === pe.id) {
1359
- const { range: r, unitId: n, subUnitId: s } = t.params, { redos: o } = this._sheetsFilterController.handleInsertColCommand(r, n, s);
1360
- j(o, this._commandService, e);
1361
- } else if (t.id === Se.id) {
1362
- const { range: r, unitId: n, subUnitId: s } = t.params, { redos: o } = this._sheetsFilterController.handleRemoveColCommand(r, n, s);
1363
- j(o, this._commandService, e);
1364
- } else if (t.id === Fe.id) {
1365
- const { sourceRange: r, targetRange: n, unitId: s, subUnitId: o } = t.params, { redos: l } = this._sheetsFilterController.handleMoveColsCommand({ fromRange: r, toRange: n }, s, o);
1366
- j(l, this._commandService, e);
1367
- }
1368
- }
1369
- })
1370
- );
1371
- }
1372
- };
1373
- G = Jt([
1374
- ee(0, A(H)),
1375
- ee(1, N),
1376
- ee(2, Re)
1377
- ], G);
1378
- const Yt = "@univerjs/sheets-filter", Xt = "0.17.0", fe = {
1379
- name: Yt,
1380
- version: Xt
1381
- };
1382
- var er = Object.getOwnPropertyDescriptor, tr = (i, t, e, r) => {
1383
- for (var n = r > 1 ? void 0 : r ? er(t, e) : t, s = i.length - 1, o; s >= 0; s--)
1384
- (o = i[s]) && (n = o(n) || n);
1385
- return n;
1386
- }, W = (i, t) => (e, r) => t(e, r, i);
1387
- let Q = class extends P {
1388
- constructor(i, t, e, r) {
1389
- super(), this._activeDirtyManagerService = i, this._sheetRowFilteredService = t, this._sheetsFilterService = e, this._univerInstanceService = r, this._initFormulaDirtyRange(), this._registerSheetRowFiltered();
1390
- }
1391
- _initFormulaDirtyRange() {
1392
- Oe.forEach((i) => {
1393
- this._activeDirtyManagerService.register(
1394
- i,
1395
- {
1396
- commandId: i,
1397
- getDirtyData: (t) => {
1398
- const e = t.params, { unitId: r, subUnitId: n } = e;
1399
- return {
1400
- dirtyRanges: this._getHideRowMutation(r, n),
1401
- clearDependencyTreeCache: {
1402
- [r]: {
1403
- [n]: "1"
1404
- }
1405
- }
1406
- };
1407
- }
1408
- }
1409
- );
1410
- });
1411
- }
1412
- _getHideRowMutation(i, t) {
1413
- var l, a;
1414
- const e = (l = this._sheetsFilterService.getFilterModel(i, t)) == null ? void 0 : l.getRange(), r = (a = this._univerInstanceService.getUnit(i)) == null ? void 0 : a.getSheetBySheetId(t);
1415
- if (e == null || r == null)
1416
- return [];
1417
- const { startRow: n, endRow: s } = e;
1418
- return [{
1419
- unitId: i,
1420
- sheetId: t,
1421
- range: {
1422
- startRow: n,
1423
- startColumn: 0,
1424
- endRow: s,
1425
- endColumn: r.getColumnCount() - 1
1426
- }
1427
- }];
1428
- }
1429
- _registerSheetRowFiltered() {
1430
- this._sheetRowFilteredService.register((i, t, e) => {
1431
- var r, n;
1432
- return (n = (r = this._sheetsFilterService.getFilterModel(i, t)) == null ? void 0 : r.isRowFiltered(e)) != null ? n : !1;
1433
- });
1434
- }
1435
- };
1436
- Q = tr([
1437
- W(0, A(Ct)),
1438
- W(1, A(Rt)),
1439
- W(2, A(M)),
1440
- W(3, T)
1441
- ], Q);
1442
- var rr = Object.getOwnPropertyDescriptor, nr = (i, t, e, r) => {
1443
- for (var n = r > 1 ? void 0 : r ? rr(t, e) : t, s = i.length - 1, o; s >= 0; s--)
1444
- (o = i[s]) && (n = o(n) || n);
1445
- return n;
1446
- }, me = (i, t) => (e, r) => t(e, r, i), U;
1447
- let ge = (U = class extends We {
1448
- constructor(i = he, t, e) {
1449
- super(), this._config = i, this._injector = t, this._configService = e;
1450
- const { ...r } = je(
1451
- {},
1452
- he,
1453
- this._config
1454
- );
1455
- this._configService.setConfig(xe, r);
1456
- }
1457
- onStarting() {
1458
- [
1459
- [Q],
1460
- [M],
1461
- [H],
1462
- [G]
1463
- ].forEach((i) => this._injector.add(i));
1464
- }
1465
- onReady() {
1466
- ke(this._injector, [
1467
- [Q],
1468
- [H],
1469
- [G]
1470
- ]);
1471
- }
1472
- }, C(U, "type", B.UNIVER_SHEET), C(U, "pluginName", Te), C(U, "packageName", fe.name), C(U, "version", fe.version), U);
1473
- ge = nr([
1474
- me(1, A(qe)),
1475
- me(2, Re)
1476
- ], ge);
1477
- export {
1478
- fr as ClearSheetsFilterCriteriaCommand,
1479
- I as CustomFilterOperator,
1480
- Oe as FILTER_MUTATIONS,
1481
- b as FilterBy,
1482
- At as FilterColumn,
1483
- q as FilterModel,
1484
- mr as ReCalcSheetsFilterCommand,
1485
- z as ReCalcSheetsFilterMutation,
1486
- Ht as RemoveSheetFilterCommand,
1487
- y as RemoveSheetsFilterMutation,
1488
- Te as SHEET_FILTER_SNAPSHOT_ID,
1489
- zt as SetSheetFilterRangeCommand,
1490
- hr as SetSheetsFilterCriteriaCommand,
1491
- p as SetSheetsFilterCriteriaMutation,
1492
- R as SetSheetsFilterRangeMutation,
1493
- M as SheetsFilterService,
1494
- G as SheetsFilterSyncController,
1495
- ur as SmartToggleSheetsFilterCommand,
1496
- ge as UniverSheetsFilterPlugin,
1497
- vt as equals,
1498
- ce as getCustomFilterFn,
1499
- pt as greaterThan,
1500
- St as greaterThanOrEqualTo,
1501
- Ft as lessThan,
1502
- wt as lessThanOrEqualTo,
1503
- ye as notEquals
1504
- };
1
+ import{CellValueType as e,ColorKit as t,CommandType as n,Disposable as r,DisposableCollection as i,ErrorService as a,ICommandService as o,IConfigService as s,IResourceManagerService as c,IUndoRedoService as l,IUniverInstanceService as u,Inject as d,Injector as f,LocaleService as p,Optional as m,Plugin as h,Rectangle as g,Tools as _,UniverInstanceType as v,createREGEXFromWildChar as ee,extractPureTextFromCell as te,fromCallback as ne,isNumeric as re,merge as ie,mergeSets as y,moveMatrixArray as ae,sequenceExecute as b,touchDependencies as oe}from"@univerjs/core";import{CopySheetCommand as se,EffectRefRangId as ce,INTERCEPTOR_POINT as le,InsertColCommand as ue,InsertColMutation as de,InsertRowCommand as fe,InsertRowMutation as pe,MoveColsMutation as me,MoveRangeCommand as he,MoveRowsCommand as ge,RefRangeService as _e,RemoveColCommand as ve,RemoveColMutation as ye,RemoveRowCommand as be,RemoveRowMutation as xe,RemoveSheetCommand as Se,SetRangeValuesMutation as Ce,SetWorksheetActiveOperation as we,SheetInterceptorService as Te,SheetsSelectionsService as Ee,ZebraCrossingCacheController as De,expandToContinuousRange as x,getSheetCommandTarget as S,isSingleCellSelection as Oe}from"@univerjs/sheets";import{BehaviorSubject as C,filter as ke,merge as Ae,of as je,switchMap as Me}from"rxjs";import{COLOR_BLACK_RGB as Ne}from"@univerjs/engine-render";import{DataSyncPrimaryController as Pe}from"@univerjs/rpc";import{IActiveDirtyManagerService as Fe,ISheetRowFilteredService as Ie}from"@univerjs/engine-formula";const w=`sheet.mutation.set-filter-range`,T=`sheet.mutation.set-filter-criteria`,E=`sheet.mutation.remove-filter`,D=`sheet.mutation.re-calc-filter`,O=new Set([w,T,E,D]);let k=function(e){return e[e.VALUES=0]=`VALUES`,e[e.COLORS=1]=`COLORS`,e[e.CONDITIONS=2]=`CONDITIONS`,e}({}),A=function(e){return e.EQUAL=`equal`,e.GREATER_THAN=`greaterThan`,e.GREATER_THAN_OR_EQUAL=`greaterThanOrEqual`,e.LESS_THAN=`lessThan`,e.LESS_THAN_OR_EQUAL=`lessThanOrEqual`,e.NOT_EQUALS=`notEqual`,e}({});const Le={operator:A.GREATER_THAN,fn:(e,t)=>P(e)?e>t:!1},Re={operator:A.GREATER_THAN_OR_EQUAL,fn:(e,t)=>P(e)?e>=t:!1},ze={operator:A.LESS_THAN,fn:(e,t)=>P(e)?e<t:!1},Be={operator:A.LESS_THAN_OR_EQUAL,fn:(e,t)=>P(e)?e<=t:!1},j={operator:A.EQUAL,fn:(e,t)=>P(e)?e===t:!1},M={operator:A.NOT_EQUALS,fn:(e,t)=>{if(typeof t==`string`){if(t===` `)return e!=null;let n=Ge(e);return n&&Ke(t)?!ee(t).test(n):n!==t}return P(e)?e!==t:!0}},Ve=new Map([]);[Le,Re,ze,Be,j,M].forEach(e=>{Ve.set(e.operator,e)});function He(e){return!!e}const Ue={fn:(e,t)=>{let n=Ge(e);return n===null?t===``:ee(t).test(n)}};function N(e){return e?Ve.get(e):Ue}function P(e){return typeof e==`number`}function We(e){return!!(typeof e==`number`||typeof e==`string`&&re(e))}function Ge(e){return typeof e==`boolean`||e==null?null:typeof e==`string`?e:e.toString()}function Ke(e){return typeof e==`number`?!1:e.indexOf(`*`)!==-1||e.indexOf(`?`)!==-1}function F(e){"@babel/helpers - typeof";return F=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},F(e)}function qe(e,t){if(F(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(F(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Je(e){var t=qe(e,`string`);return F(t)==`symbol`?t:t+``}function I(e,t,n){return(t=Je(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const L=()=>new Set;var R=class e extends r{get filteredOutRows(){return this._filteredOutRows$.getValue()}set filteredOutRows(e){this._alreadyFilteredOutRows=e,this._filteredOutRows$.next(e)}constructor(e,t,n){super(),this.unitId=e,this.subUnitId=t,this._worksheet=n,I(this,`_filteredOutRows$`,new C(L())),I(this,`filteredOutRows$`,this._filteredOutRows$.asObservable()),I(this,`_hasCriteria$`,new C(!1)),I(this,`hasCriteria$`,this._hasCriteria$.asObservable()),I(this,`_filterColumnByIndex`,new Map),I(this,`_alreadyFilteredOutRows`,L()),I(this,`_range`,void 0)}dispose(){super.dispose(),this._filteredOutRows$.complete(),this._hasCriteria$.complete(),this._worksheet=null}serialize(){let e={ref:g.clone(this._range),filterColumns:this._getAllFilterColumns(!0).sort(([e],[t])=>e-t).map(([e,t])=>t.serialize())};return this._alreadyFilteredOutRows&&(e.cachedFilteredOut=Array.from(this._alreadyFilteredOutRows).sort()),e}static deserialize(t,n,r,i){let a=new e(t,n,r);return a._dump(i),a}_dump(e){var t;this.setRange(e.ref),(t=e.filterColumns)==null||t.filter(e=>!(!e.filters&&!e.colorFilters&&!e.customFilters)).forEach(e=>this._setCriteriaWithoutReCalc(e.colId,e)),e.cachedFilteredOut?(this._alreadyFilteredOutRows=new Set(e.cachedFilteredOut),this._emit()):e.filterColumns&&e.filterColumns.length>0&&(this._reCalcAllColumns(),this._emit()),this._emitHasCriteria()}isRowFiltered(e){return this._alreadyFilteredOutRows.has(e)}getRange(){if(!this._range)throw Error(`[FilterModel] could not get range before a range is set!`);return this._range}getFilteredOutRowsExceptCol(e){return this._getAllFilterColumns(!0).filter(([t])=>t!==e).reduce((e,[,t])=>{let n=t.calc({getAlreadyFilteredOutRows:()=>e});return n?y(e,n):e},new Set)}setRange(e){this._range=e,this._getAllFilterColumns(!0).forEach(([t,n])=>{n.setRangeAndColumn({startRow:e.startRow,endRow:e.endRow,startColumn:t,endColumn:t},t)})}setCriteria(e,t,n=!1){if(!this._range)throw Error(`[FilterModel] could not set criteria before a range is set!`);if(!t){this._removeCriteria(e),this._rebuildAlreadyFilteredOutRowsWithCache(),n&&this._reCalcAllColumns(),this._emit(),this._emitHasCriteria();return}this._setCriteriaWithoutReCalc(e,t),n&&(this._rebuildAlreadyFilteredOutRowsWithCache(),this._getAllFilterColumns().forEach(e=>e.__clearCache()),this._reCalcWithNoCacheColumns(),this._emit(),this._emitHasCriteria())}getAllFilterColumns(){return this._getAllFilterColumns(!0)}getFilterColumn(e){var t;return(t=this._filterColumnByIndex.get(e))==null?null:t}reCalc(){this._reCalcAllColumns(),this._emit()}_getAllFilterColumns(e=!1){let t=Array.from(this._filterColumnByIndex.entries());return e?t:t.map(([e,t])=>t)}_reCalcAllColumns(){this._alreadyFilteredOutRows=L(),this._getAllFilterColumns().forEach(e=>e.__clearCache()),this._reCalcWithNoCacheColumns()}_setCriteriaWithoutReCalc(e,t){let n=this._range;if(!n)throw Error(`[FilterModel] could not set criteria before a range is set!`);let{startColumn:r,endColumn:i}=n;if(e>i||e<r)throw Error(`[FilterModel] could not set criteria on column ${e} which is out of range!`);let a;this._filterColumnByIndex.has(e)?a=this._filterColumnByIndex.get(e):(a=new Ye(this.unitId,this.subUnitId,this._worksheet,t,{getAlreadyFilteredOutRows:()=>this._alreadyFilteredOutRows}),a.setRangeAndColumn(n,e),this._filterColumnByIndex.set(e,a)),a.setCriteria(t)}_removeCriteria(e){let t=this._filterColumnByIndex.get(e);t&&(t.dispose(),this._filterColumnByIndex.delete(e))}_emit(){this._filteredOutRows$.next(this._alreadyFilteredOutRows)}_emitHasCriteria(){this._hasCriteria$.next(this._filterColumnByIndex.size>0)}_rebuildAlreadyFilteredOutRowsWithCache(){this._alreadyFilteredOutRows=this._getAllFilterColumns().filter(e=>e.hasCache()).reduce((e,t)=>y(e,t.filteredOutRows),new Set)}_reCalcWithNoCacheColumns(){let e=this._getAllFilterColumns().filter(e=>!e.hasCache());for(let t of e){let e=t.reCalc();e&&(this._alreadyFilteredOutRows=y(this._alreadyFilteredOutRows,e))}}},Ye=class extends r{get filteredOutRows(){return this._filteredOutRows}get filterBy(){return this._filterBy}constructor(e,t,n,r,i){super(),this.unitId=e,this.subUnitId=t,this._worksheet=n,this._criteria=r,this._filterColumnContext=i,I(this,`_filteredOutRows`,null),I(this,`_filterFn`,null),I(this,`_range`,null),I(this,`_column`,0),I(this,`_filterBy`,k.VALUES)}dispose(){super.dispose(),this._filteredOutRows=null}__clearCache(){this._filteredOutRows=null}serialize(){if(!this._criteria)throw Error(`[FilterColumn]: could not serialize without a filter column!`);return _.deepClone({...this._criteria,colId:this._column})}hasCache(){return this._filteredOutRows!==null}setRangeAndColumn(e,t){this._range=e,this._column=t}setCriteria(e){this._criteria=e,this._generateFilterFn(),this._filteredOutRows=null}getColumnData(){return _.deepClone(this._criteria)}reCalc(){return this._filteredOutRows=this.calc(this._filterColumnContext),this._filteredOutRows}calc(e){if(!this._filterFn)throw Error(`[FilterColumn] cannot calculate without a filter fn!`);if(!this._range)throw Error(`[FilterColumn] cannot calculate without a range!`);if(typeof this._column!=`number`)throw TypeError(`[FilterColumn] cannot calculate without a column offset!`);let t=this._column,n={startColumn:t,endColumn:t,startRow:this._range.startRow+1,endRow:this._range.endRow},r=new Set,i=e.getAlreadyFilteredOutRows();for(let e of this._worksheet.iterateByColumn(n,!1,!1)){let{row:t,rowSpan:n,col:a}=e;if(!(i.has(t)&&(!n||n===1))&&!(this._filterBy===k.VALUES?this._filterFn(te(this._worksheet.getCell(t,a))):this._filterBy===k.COLORS?this._filterFn(this._worksheet.getComposedCellStyle(t,a)):this._filterFn(it(this._worksheet,t,a)))&&(r.add(t),n))for(let e=1;e<n;e++)r.add(t+e)}return r}_generateFilterFn(){this._criteria&&(this._filterFn=Xe(this._criteria),this._filterBy=this._criteria.filters?k.VALUES:this._criteria.colorFilters?k.COLORS:k.CONDITIONS)}};function Xe(e){if(e.filters)return Ze(e.filters);if(e.colorFilters)return Qe(e.colorFilters);if(e.customFilters)return $e(e.customFilters);throw Error(`[FilterModel]: other types of filters are not supported yet.`)}function Ze(e){let t=!!e.blank,n=new Set(e.filters);return e=>e===void 0||e===``?t:n.has(typeof e==`string`?e:`${e}`)}function Qe(e){if(e.cellFillColors){let n=new Set(e.cellFillColors);return e=>{var r;if(!e||!((r=e.bg)!=null&&r.rgb))return!!n.has(null);let i=new t(e.bg.rgb).toRgbString();return n.has(i)}}if(e.cellTextColors){let n=new Set(e.cellTextColors);return e=>{var r;if(!e||!((r=e.cl)!=null&&r.rgb))return!!n.has(Ne);let i=new t(e.cl.rgb).toRgbString();return n.has(i)}}throw Error(`[FilterModel]: color filters are not supported yet.`)}function $e(e){let t=e.customFilters.map(e=>rt(e));return nt(t)?e.and?et(t):tt(t):t[0]}function et(e){let[t,n]=e;return e=>t(e)&&n(e)}function tt(e){let[t,n]=e;return e=>t(e)||n(e)}function nt(e){return e.length===2}function rt(e){let t=e.val;if(e.operator===A.NOT_EQUALS&&!We(t))return e=>M.fn(e,t);if(He(e.operator)){if(!We(t))return()=>!1;let n=N(e.operator),r=Number(t);return e=>n.fn(e,r)}let n=N(e.operator);return e=>n.fn(e,t)}function it(t,n,r){let i=t.getCell(n,r);if(!i)return null;let a=t.getCellRaw(n,r);return i&&!a?at(i):a?i.t===e.NUMBER&&typeof i.v==`string`?a.v:i.t===e.NUMBER?Number(a.v):at(a):null}function at(t){var n;let r=(n=t.p)==null||(n=n.body)==null?void 0:n.dataStream;if(r)return r.trimEnd();let i=t.v;return typeof i==`string`?t.t===e.BOOLEAN?i.toUpperCase():i:typeof i==`number`?t.t===e.BOOLEAN?i?`TRUE`:`FALSE`:i:typeof i==`boolean`?i?`TRUE`:`FALSE`:``}function z(e,t){return function(n,r){t(n,r,e)}}function B(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}const V=`SHEET_FILTER_PLUGIN`;let H=class extends r{get activeFilterModel(){return this._activeFilterModel$.getValue()}constructor(e,t,n){super(),this._resourcesManagerService=e,this._univerInstanceService=t,this._commandService=n,I(this,`_filterModels`,new Map),I(this,`_loadedUnitId$`,new C(null)),I(this,`loadedUnitId$`,this._loadedUnitId$.asObservable()),I(this,`_errorMsg$`,new C(null)),I(this,`errorMsg$`,this._errorMsg$.asObservable()),I(this,`_activeFilterModel$`,new C(null)),I(this,`activeFilterModel$`,this._activeFilterModel$.asObservable()),this._initModel(),this._initActiveFilterModel()}ensureFilterModel(e,t){let n=this.getFilterModel(e,t);if(n)return n;let r=this._univerInstanceService.getUniverSheetInstance(e);if(!r)throw Error(`[SheetsFilterService]: could not create "FilterModel" on a non-existing workbook ${e}!`);let i=r.getSheetBySheetId(t);if(!i)throw Error(`[SheetsFilterService]: could not create "FilterModel" on a non-existing worksheet ${t}!`);let a=new R(e,t,i);return this._cacheFilterModel(e,t,a),a}getFilterModel(e,t){var n,r;return(n=(r=this._filterModels.get(e))==null?void 0:r.get(t))==null?null:n}removeFilterModel(e,t){let n=this.getFilterModel(e,t);return n?(n.dispose(),this._filterModels.get(e).delete(t),!0):!1}setFilterErrorMsg(e){this._errorMsg$.next(e)}_updateActiveFilterModel(){let e;try{if(e=this._univerInstanceService.getCurrentUnitForType(v.UNIVER_SHEET),!e){this._activeFilterModel$.next(null);return}}catch(e){console.error(`[SheetsFilterService]: could not get active workbook!`,e);return}let t=e.getActiveSheet(!0);if(!t){this._activeFilterModel$.next(null);return}let n=t.getUnitId(),r=t.getSheetId(),i=this.getFilterModel(n,r);this._activeFilterModel$.next(i)}_initActiveFilterModel(){this.disposeWithMe(Ae(ne(this._commandService.onCommandExecuted.bind(this._commandService)).pipe(ke(([e])=>e.type===n.MUTATION&&O.has(e.id))),this._univerInstanceService.getCurrentTypeOfUnit$(v.UNIVER_SHEET).pipe(Me(e=>{var t;return(t=e==null?void 0:e.activeSheet$)==null?je(null):t}))).subscribe(()=>this._updateActiveFilterModel()))}_serializeAutoFiltersForUnit(e){let t=this._filterModels.get(e);if(!t)return`{}`;let n={};return t.forEach((e,t)=>{n[t]=e.serialize()}),JSON.stringify(n)}_deserializeAutoFiltersForUnit(e,t){let n=this._univerInstanceService.getUniverSheetInstance(e);Object.keys(t).forEach(r=>{let i=t[r],a=R.deserialize(e,r,n.getSheetBySheetId(r),i);this._cacheFilterModel(e,r,a)})}dispose(){super.dispose(),this._loadedUnitId$.complete(),this._errorMsg$.complete(),this._activeFilterModel$.complete(),this._filterModels.forEach(e=>{e.forEach(e=>e.dispose()),e.clear()}),this._filterModels.clear()}_initModel(){this._resourcesManagerService.registerPluginResource({pluginName:V,businesses:[v.UNIVER_SHEET],toJson:e=>this._serializeAutoFiltersForUnit(e),parseJson:e=>JSON.parse(e),onLoad:(e,t)=>{this._deserializeAutoFiltersForUnit(e,t),this._loadedUnitId$.next(e),this._updateActiveFilterModel()},onUnLoad:e=>{let t=this._filterModels.get(e);t&&(t.forEach(e=>e.dispose()),this._filterModels.delete(e))}})}_cacheFilterModel(e,t,n){this._filterModels.has(e)||this._filterModels.set(e,new Map),this._filterModels.get(e).set(t,n)}};H=B([z(0,c),z(1,u),z(2,o)],H);const U={id:w,type:n.MUTATION,handler:(e,t)=>{let{subUnitId:n,unitId:r,range:i}=t;return e.get(H).ensureFilterModel(r,n).setRange(i),!0}},W={id:T,type:n.MUTATION,handler:(e,t)=>{let{subUnitId:n,unitId:r,criteria:i,col:a,reCalc:o=!0}=t,s=e.get(H).getFilterModel(r,n);return s?(s.setCriteria(a,i,o),!0):!1}},G={id:E,type:n.MUTATION,handler:(e,t)=>{let{unitId:n,subUnitId:r}=t;return e.get(H).removeFilterModel(n,r)}},K={id:D,type:n.MUTATION,handler:(e,t)=>{let{unitId:n,subUnitId:r}=t,i=e.get(H).getFilterModel(n,r);return i?(i.reCalc(),!0):!1}},ot={id:`sheet.command.set-filter-range`,type:n.COMMAND,handler:(e,t)=>{let n=e.get(H),r=e.get(o),i=e.get(l),s=e.get(u),{unitId:c,subUnitId:d,range:f}=t;if(!S(s,t)||n.getFilterModel(c,d))return!1;if(f.endRow===f.startRow){let t=e.get(a),n=e.get(p);return t.emit(n.t(`sheets-filter.command.not-valid-filter-range`)),!1}let m={id:U.id,params:{unitId:c,subUnitId:d,range:f}},h=r.syncExecuteCommand(m.id,m.params);return h&&i.pushUndoRedo({unitID:c,undoMutations:[{id:G.id,params:{unitId:c,subUnitId:d}}],redoMutations:[m]}),h}},st={id:`sheet.command.remove-sheet-filter`,type:n.COMMAND,handler:(e,t)=>{let n=e.get(u),r=e.get(H),i=e.get(o),a=e.get(l),s=S(n,t);if(!s)return!1;let{unitId:c,subUnitId:d}=s,f=r.getFilterModel(c,d);if(!f)return!1;let p=ft(c,d,f==null?void 0:f.serialize()),m=i.syncExecuteCommand(G.id,{unitId:c,subUnitId:d});return m&&a.pushUndoRedo({unitID:c,undoMutations:p,redoMutations:[{id:G.id,params:{unitId:c,subUnitId:d}}]}),m}},ct={id:`sheet.command.smart-toggle-filter`,type:n.COMMAND,handler:async e=>{let t=e.get(u),n=e.get(H),r=e.get(o),i=t.getCurrentUnitForType(v.UNIVER_SHEET),a=i==null?void 0:i.getActiveSheet();if(!a||!i)return!1;let s=i.getUnitId(),c=a.getSheetId();if(n.getFilterModel(s,c))return r.executeCommand(st.id,{unitId:s,subUnitId:c});let l=e.get(Ee).getCurrentLastSelection();if(!l)return!1;let d=l.range,f=Oe(l)?x(d,{left:!0,right:!0,up:!0,down:!0},a):d.startRow===d.endRow?x(d,{down:!0},a):d;return r.executeCommand(ot.id,{unitId:s,subUnitId:c,range:f})}},lt={id:`sheet.command.set-filter-criteria`,type:n.COMMAND,handler:(e,t)=>{let n=e.get(H),r=e.get(o),i=e.get(l),{unitId:a,subUnitId:s,col:c,criteria:u}=t,d=n.getFilterModel(a,s);if(!d)return!1;let f=d.getRange();if(!f||c<f.startColumn||c>f.endColumn)return!1;let p=ht(a,s,c,d.getFilterColumn(c)),m={id:W.id,params:{unitId:a,subUnitId:s,col:c,criteria:u}},h=r.syncExecuteCommand(m.id,m.params);return h&&i.pushUndoRedo({unitID:a,undoMutations:[p],redoMutations:[m]}),h}},ut={id:`sheet.command.clear-filter-criteria`,type:n.COMMAND,handler:(e,t)=>{let n=e.get(H),r=e.get(l),i=e.get(o),a=S(e.get(u),t);if(!a)return!1;let{unitId:s,subUnitId:c}=a,d=n.getFilterModel(a.unitId,a.subUnitId);if(!d)return!1;let f=d.serialize(),p=pt(s,c,f),m=mt(s,c,f);return b(m,i).result?(r.pushUndoRedo({unitID:s,undoMutations:p,redoMutations:m}),!0):!1}},dt={id:`sheet.command.re-calc-filter`,type:n.COMMAND,handler:(e,t)=>{let n=e.get(H),r=e.get(o),i=S(e.get(u),t);if(!i)return!1;let{unitId:a,subUnitId:s}=i;return n.getFilterModel(i.unitId,i.subUnitId)?r.executeCommand(K.id,{unitId:a,subUnitId:s}):!1}};function ft(e,t,n){let r=[],i={id:U.id,params:{unitId:e,subUnitId:t,range:n.ref}};return r.push(i),pt(e,t,n).forEach(e=>r.push(e)),r}function pt(e,t,n){var r;let i=[];return(r=n.filterColumns)==null||r.forEach(n=>{let r={id:W.id,params:{unitId:e,subUnitId:t,col:n.colId,criteria:n}};i.push(r)}),i}function mt(e,t,n){var r;let i=[];return(r=n.filterColumns)==null||r.forEach(n=>{let r={id:W.id,params:{unitId:e,subUnitId:t,col:n.colId,criteria:null}};i.push(r)}),i}function ht(e,t,n,r){if(!r)return{id:W.id,params:{unitId:e,subUnitId:t,col:n,criteria:null}};let i=r.serialize();return{id:W.id,params:{unitId:e,subUnitId:t,col:n,criteria:i}}}const q=`sheets-filter.config`;Symbol(q);const J={};function gt(e,t){for(let n=0;n<e.length;n++){let r=n;if(e[n])for(let i=n+1;i<e.length;i++)e[r]&&e[i]&&t(e[r],e[i])&&(e[r]=null,r=i)}return e.filter(e=>e!==null)}function Y(e){return gt(e,(e,t)=>e.id===W.id&&t.id===W.id&&e.params.unitId===t.params.unitId&&e.params.subUnitId===t.params.subUnitId&&e.params.col===t.params.col)}let X=class extends r{constructor(e,t,n,r,a,o,s){super(),this._commandService=e,this._sheetInterceptorService=t,this._sheetsFilterService=n,this._univerInstanceService=r,this._refRangeService=a,this._dataSyncPrimaryController=o,this._zebraCrossingCacheController=s,I(this,`_disposableCollection`,new i),this._initCommands(),this._initRowFilteredInterceptor(),this._initInterceptors(),this._commandExecutedListener(),this._initErrorHandling(),this._initZebraCrossingCacheListener()}_initZebraCrossingCacheListener(){this.disposeWithMe(this._sheetsFilterService.activeFilterModel$.subscribe(e=>{e&&this.disposeWithMe(e.filteredOutRows$.subscribe(()=>{this._zebraCrossingCacheController.updateZebraCrossingCache(e.unitId,e.subUnitId)}))}))}_initCommands(){[W,U,K,G].forEach(e=>{var t;this.disposeWithMe(this._commandService.registerCommand(e)),(t=this._dataSyncPrimaryController)==null||t.registerSyncingMutations(e)})}_initInterceptors(){this.disposeWithMe(this._sheetInterceptorService.interceptCommand({getMutations:e=>this._getUpdateFilter(e)})),this.disposeWithMe(this._commandService.onCommandExecuted(e=>{if(e.id===we.id){let t=e.params,n=t.subUnitId,r=t.unitId;if(!n||!r)return;this._registerRefRange(r,n)}if(e.id===U.id){let t=e.params,n=t.subUnitId,r=t.unitId;if(!n||!r)return;this._registerRefRange(t.unitId,t.subUnitId)}})),this.disposeWithMe(this._sheetsFilterService.loadedUnitId$.subscribe(e=>{if(e){let t=this._univerInstanceService.getUniverSheetInstance(e),n=t==null?void 0:t.getActiveSheet();n&&this._registerRefRange(e,n.getSheetId())}}))}_registerRefRange(e,t){var n;this._disposableCollection.dispose();let r=this._univerInstanceService.getUniverSheetInstance(e),i=r==null?void 0:r.getSheetBySheetId(t);if(!r||!i)return;let a=(n=this._sheetsFilterService.getFilterModel(e,t))==null?void 0:n.getRange();a&&this._disposableCollection.add(this._refRangeService.registerRefRange(a,n=>{switch(n.id){case fe.id:{let r=n.params,i=r.unitId||e,a=r.subUnitId||t;return this._handleInsertRowCommand(r,i,a)}case ue.id:{let r=n.params,i=r.unitId||e,a=r.subUnitId||t;return this.handleInsertColCommand(r.range,i,a)}case ve.id:{let r=n.params;return this.handleRemoveColCommand(r.range,e,t)}case be.id:{let r=n.params;return this._handleRemoveRowCommand(r,e,t)}case ce.MoveColsCommandId:{let r=n.params;return this.handleMoveColsCommand({fromRange:r.fromRange,toRange:r.toRange},e,t)}case ce.MoveRowsCommandId:{let r=n.params;return this._handleMoveRowsCommand(r,e,t)}case he.id:{let r=n.params;return this._handleMoveRangeCommand(r,e,t)}}return{redos:[],undos:[]}},e,t))}_getUpdateFilter(e){let{id:t}=e;switch(t){case Se.id:{let t=e.params;return this._handleRemoveSheetCommand(t,t.unitId,t.subUnitId)}case se.id:{let{targetSubUnitId:t,unitId:n,subUnitId:r}=e.params;return!n||!r||!t?this._handleNull():this._handleCopySheetCommand(n,r,t)}}return{redos:[],undos:[]}}handleInsertColCommand(e,t,n){var r;let i=this._sheetsFilterService.getFilterModel(t,n),a=(r=i==null?void 0:i.getRange())==null?null:r;if(!i||!a)return this._handleNull();let{startColumn:o,endColumn:s}=a,{startColumn:c,endColumn:l}=e,u=l-c+1;if(l>s)return this._handleNull();let d=[],f=[],p=c,m={unitId:t,subUnitId:n,range:{...a,startColumn:c<=o?o+u:o,endColumn:s+u}},h={unitId:t,subUnitId:n,range:a};d.push({id:U.id,params:m}),f.push({id:U.id,params:h});let g=i.getAllFilterColumns().filter(e=>e[0]>=p);if(g.length!==0){let{newRange:e,oldRange:r}=this._moveCriteria(t,n,g,u);d.push(...r.redos,...e.redos),f.push(...e.undos,...r.undos)}return{redos:Y(d),undos:Y(f)}}_handleInsertRowCommand(e,t,n){var r;let i=this._sheetsFilterService.getFilterModel(t,n),a=(r=i==null?void 0:i.getRange())==null?null:r;if(!i||!a)return this._handleNull();let{startRow:o,endRow:s}=a,{startRow:c,endRow:l}=e.range,u=l-c+1;if(l>s)return this._handleNull();let d=[],f=[],p={unitId:t,subUnitId:n,range:{...a,startRow:c<=o?o+u:o,endRow:s+u}},m={unitId:t,subUnitId:n,range:a};return d.push({id:U.id,params:p}),f.push({id:U.id,params:m}),{redos:Y(d),undos:Y(f)}}handleRemoveColCommand(e,t,n){var r;let i=this._sheetsFilterService.getFilterModel(t,n),a=(r=i==null?void 0:i.getRange())==null?null:r;if(!i||!a)return this._handleNull();let{startColumn:o,endColumn:s}=a,{startColumn:c,endColumn:l}=e;if(c>s)return this._handleNull();let u=[],d=[],f=l<o?0:Math.min(l,s)-Math.max(c,o)+1,p=l-c+1,m=i.getAllFilterColumns();m.forEach(e=>{let[r,i]=e;r<=l&&r>=c&&(u.push({id:W.id,params:{unitId:t,subUnitId:n,col:r,criteria:null}}),d.push({id:W.id,params:{unitId:t,subUnitId:n,col:r,criteria:{...i.serialize(),colId:r}}}))});let h=m.filter(e=>{let[t,n]=e;return t>l}),g={undos:[],redos:[]};if(h.length>0){let{oldRange:e,newRange:r}=this._moveCriteria(t,n,h,-p);g=r,u.push(...e.redos),d.unshift(...e.undos)}if(f===s-o+1){let e={unitId:t,subUnitId:n};u.push({id:G.id,params:e}),d.unshift({id:U.id,params:{range:a,unitId:t,subUnitId:n}})}else{let e=o<=c?o:f===0?o-p:c,r=o<=c?s-f:s-p,i={unitId:t,subUnitId:n,range:{...a,startColumn:e,endColumn:r}};u.push({id:U.id,params:i}),d.unshift({id:U.id,params:{range:a,unitId:t,subUnitId:n}}),u.push(...g.redos),d.unshift(...g.undos)}return{undos:d,redos:u}}_handleRemoveRowCommand(e,t,n){let r=this._sheetsFilterService.getFilterModel(t,n);if(!r)return this._handleNull();let i=r.getRange(),{startRow:a,endRow:o}=i,{startRow:s,endRow:c}=e.range;if(s>o)return this._handleNull();if(c<a)return{undos:[{id:U.id,params:{range:i,unitId:t,subUnitId:n}}],redos:[{id:U.id,params:{range:{...i,startRow:a-(c-s+1),endRow:o-(c-s+1)},unitId:t,subUnitId:n}}]};let l=[],u=[],d=r.getAllFilterColumns(),f=a<=c&&a>=s;u.push({id:U.id,params:{range:i,unitId:t,subUnitId:n}});let p=Math.min(c,o)-Math.max(s,a)+1;if(p===o-a+1||f){let e={unitId:t,subUnitId:n};l.push({id:G.id,params:e}),d.forEach(e=>{let[r,i]=e,a={unitId:t,subUnitId:n,col:r,criteria:{...i.serialize(),colId:r}};u.push({id:W.id,params:a})})}else{var m;let e=(m=this._univerInstanceService.getUniverSheetInstance(t))==null?void 0:m.getSheetBySheetId(n);if(!e)return this._handleNull();let r=[];for(let t=s;t<=c;t++)e.getRowFiltered(t)&&r.push(t);let u=Math.min(a,s),d=u+(o-a)-p+r.length,f={unitId:t,subUnitId:n,range:{...i,startRow:u,endRow:d}};l.push({id:U.id,params:f})}return{undos:Y(u),redos:Y(l)}}handleMoveColsCommand({fromRange:e,toRange:t},n,r){var i;let a=this._sheetsFilterService.getFilterModel(n,r),o=(i=a==null?void 0:a.getRange())==null?null:i;if(!a||!o)return this._handleNull();let{startColumn:s,endColumn:c}=o;if(e.endColumn<s&&t.startColumn<=s||e.startColumn>c&&t.endColumn>c)return this._handleNull();let l=[],u=[],d={};for(let e=s;e<=c;e++)d[e]={colIndex:e,filter:a.getFilterColumn(e)};ae(e.startColumn,e.endColumn-e.startColumn+1,t.startColumn,d);let f=o.startColumn,p=o.endColumn;s>=e.startColumn&&s<=e.endColumn&&t.startColumn>e.startColumn&&e.endColumn<c&&(f=e.endColumn+1),c>=e.startColumn&&c<=e.endColumn&&t.startColumn<e.startColumn&&e.startColumn>s&&(p=e.startColumn-1);let m=Object.keys(d).map(e=>Number(e)),h=m.find(e=>d[e].colIndex===p),g=m.find(e=>d[e].colIndex===f);if(m.forEach(e=>{let{colIndex:t,filter:i}=d[e],o=e;if(i){var s;if(o>=g&&o<=h){var c;let e={unitId:n,subUnitId:r,col:o,criteria:{...i.serialize(),colId:o}},t={unitId:n,subUnitId:r,col:o,criteria:a.getFilterColumn(o)?{...(c=a.getFilterColumn(o))==null?void 0:c.serialize(),colId:o}:null};l.push({id:W.id,params:e}),u.push({id:W.id,params:t})}if(!((s=d[t])!=null&&s.filter)){let e={unitId:n,subUnitId:r,col:t,criteria:null};l.push({id:W.id,params:e}),u.push({id:W.id,params:{unitId:n,subUnitId:r,col:t,criteria:{...i.serialize(),colId:t}}})}}}),s!==g||c!==h){let e={unitId:n,subUnitId:r,range:{...o,startColumn:g,endColumn:h}};l.unshift({id:U.id,params:e}),u.unshift({id:U.id,params:{range:o,unitId:n,subUnitId:r}})}return{undos:u,redos:l}}_handleMoveRowsCommand(e,t,n){var r;let i=this._sheetsFilterService.getFilterModel(t,n),a=(r=i==null?void 0:i.getRange())==null?null:r;if(!i||!a)return this._handleNull();let{startRow:o,endRow:s}=a,{fromRange:c,toRange:l}=e;if(c.endRow<o&&l.startRow<=o||c.startRow>s&&l.endRow>s)return this._handleNull();let u=[],d=[],f={};for(let e=o;e<=s;e++)f[e]={oldIndex:e};let p=o,m=s;s>=c.startRow&&s<=c.endRow&&l.startRow<c.startRow&&c.startRow>o&&(m=c.startRow-1),ae(c.startRow,c.endRow-c.startRow+1,l.startRow,f);let h=Object.keys(f).map(e=>Number(e)),g=h.find(e=>f[e].oldIndex===m),_=h.find(e=>f[e].oldIndex===p);if(o!==_||s!==g){let e={unitId:t,subUnitId:n,range:{...a,startRow:_,endRow:g}};u.push({id:U.id,params:e},{id:K.id,params:{unitId:t,subUnitId:n}}),d.push({id:U.id,params:{range:a,unitId:t,subUnitId:n}},{id:K.id,params:{unitId:t,subUnitId:n}})}return{redos:u,undos:d}}_handleMoveRangeCommand(e,t,n){let{fromRange:r,toRange:i}=e,a=this._sheetsFilterService.getFilterModel(t,n);if(!a)return this._handleNull();let o=a.getRange();if(!o)return this._handleNull();let s=[],c=[];if(g.contains(r,o)){let e=o.startRow-r.startRow,l=o.startColumn-r.startColumn,u={startRow:i.startRow+e,startColumn:i.startColumn+l,endRow:i.startRow+e+(o.endRow-o.startRow),endColumn:i.startColumn+l+(o.endColumn-o.startColumn)},d={id:G.id,params:{unitId:t,subUnitId:n}},f={id:U.id,params:{unitId:t,subUnitId:n,range:u}},p={id:U.id,params:{unitId:t,subUnitId:n,range:o}};s.push(d,f),c.push(d,p);let m=a.getAllFilterColumns(),h=i.startColumn-r.startColumn;m.forEach(e=>{let[r,i]=e;i&&(s.push({id:W.id,params:{unitId:t,subUnitId:n,col:r+h,criteria:{...i.serialize(),colId:r+h}}}),c.push({id:W.id,params:{unitId:t,subUnitId:n,col:r,criteria:{...i.serialize(),colId:r}}}))})}else if(g.intersects(i,o)){let e={...o,endRow:Math.max(o.endRow,i.endRow)};s.push({id:U.id,params:{unitId:t,subUnitId:n,range:e}}),c.push({id:U.id,params:{unitId:t,subUnitId:n,range:o}})}return{redos:s,undos:c}}_handleRemoveSheetCommand(e,t,n){let r=this._sheetsFilterService.getFilterModel(t,n);if(!r)return this._handleNull();let i=r.getRange();if(!i)return this._handleNull();let a=[],o=[];return r.getAllFilterColumns().forEach(([e,r])=>{o.push({id:W.id,params:{unitId:t,subUnitId:n,col:e,criteria:{...r.serialize(),colId:e}}})}),a.push({id:G.id,params:{unitId:t,subUnitId:n,range:i}}),o.unshift({id:U.id,params:{range:i,unitId:t,subUnitId:n}}),{undos:o,redos:a}}_handleCopySheetCommand(e,t,n){let r=this._sheetsFilterService.getFilterModel(e,t);if(!r)return this._handleNull();let i=r.getRange();if(!i)return this._handleNull();let a=[],o=[],s=[];return r.getAllFilterColumns().forEach(([t,r])=>{a.push({id:W.id,params:{unitId:e,subUnitId:n,col:t,criteria:{...r.serialize(),colId:t}}}),s.push({id:W.id,params:{unitId:e,subUnitId:n,col:t,criteria:null}})}),s.push({id:G.id,params:{unitId:e,subUnitId:n,range:i}}),a.unshift({id:U.id,params:{range:i,unitId:e,subUnitId:n}}),{undos:o,redos:a,preUndos:s,preRedos:[]}}_handleNull(){return{redos:[],undos:[]}}_initRowFilteredInterceptor(){this.disposeWithMe(this._sheetInterceptorService.intercept(le.ROW_FILTERED,{handler:(e,t)=>{var n,r;return e?!0:(n=(r=this._sheetsFilterService.getFilterModel(t.unitId,t.subUnitId))==null?void 0:r.isRowFiltered(t.row))==null?!1:n}}))}_moveCriteria(e,t,n,r){let i={unitId:e,subUnitId:t,criteria:null,col:-1},a=[],o=[],s=[],c=[];return n.forEach(e=>{let[t,n]=e;o.push({id:W.id,params:{...i,col:t}}),a.push({id:W.id,params:{...i,col:t,criteria:{...n.serialize(),colId:t}}})}),n.forEach(e=>{let[t,n]=e;c.push({id:W.id,params:{...i,col:t+r,criteria:{...n.serialize(),colId:t+r}}}),s.push({id:W.id,params:{...i,col:t+r,criteria:null}})}),{newRange:{redos:c,undos:s},oldRange:{redos:o,undos:a}}}_commandExecutedListener(){this.disposeWithMe(this._commandService.onCommandExecuted((e,t)=>{let{unitId:n,subUnitId:r}=e.params||{},i=this._sheetsFilterService.getFilterModel(n,r);if(!i)return;let a=Array.from(i.filteredOutRows).sort((e,t)=>e-t),o=[],s=!1;if(e.id===xe.id){let{startRow:t,endRow:n}=e.params.range,r=a.filter(e=>e>=t&&e<=n);a.forEach(e=>{if(e<t)o.push(e);else if(s=!0,e<=n){let e=Math.max(t,o.length?o[o.length-1]+1:t);o.push(e)}else o.push(e-(n-t+1-r.length))})}if(e.id===pe.id){let{startRow:t,endRow:n}=e.params.range;a.forEach(e=>{e>=t?(s=!0,o.push(e+(n-t+1))):o.push(e)})}if(s&&(i.filteredOutRows=new Set(o)),e.id===Ce.id&&!(t!=null&&t.onlyLocal)){let t=this._getExtendRegion(n,r);if(t){let i=e.params.cellValue;if(i)for(let e=t.startColumn;e<=t.endColumn;e++){var c;let a=i==null||(c=i[t.startRow])==null?void 0:c[e];if(a&&this._cellHasValue(a)){var l;let e=(l=this._univerInstanceService.getUnit(n))==null?void 0:l.getSheetBySheetId(r);if(e){let i=x(t,{down:!0},e),a=this._sheetsFilterService.getFilterModel(n,r),o=a.getRange();a.setRange({...o,endRow:i.endRow}),this._registerRefRange(n,r)}}}}}}))}_getExtendRegion(e,t){var n;let r=this._sheetsFilterService.getFilterModel(e,t);if(!r)return null;let i=(n=this._univerInstanceService.getUnit(e))==null?void 0:n.getSheetBySheetId(t);if(!i)return null;let a=r.getRange();if(!a)return null;let o=i.getRowCount()-1,s=i.getRowManager();for(let e=a.endRow+1;e<=o;e++)if(s.getRowRawVisible(e))return{startRow:e,endRow:e,startColumn:a.startColumn,endColumn:a.endColumn};return null}_initErrorHandling(){this.disposeWithMe(this._commandService.beforeCommandExecuted(e=>{let t=e.params,n=S(this._univerInstanceService,t);if(!n)return;let{subUnitId:r,unitId:i}=n,a=this._sheetsFilterService.getFilterModel(i,r);if(!a)return;let o=a.getRange();if(e.id===ge.id&&t.fromRange.startRow<=o.startRow&&t.fromRange.endRow<o.endRow&&t.fromRange.endRow>=o.startRow)throw this._sheetsFilterService.setFilterErrorMsg(`sheets-filter.msg.filter-header-forbidden`),Error(`[SheetsFilterController]: Cannot move header row of filter`)}))}_cellHasValue(e){let t=Object.values(e);return!(t.length===0||t.every(e=>e==null))}};X=B([z(0,o),z(1,d(Te)),z(2,d(H)),z(3,u),z(4,d(_e)),z(5,m(Pe)),z(6,d(De))],X);const _t=[W.id,K.id],vt=[de.id,ye.id,me.id];let Z=class extends r{get visible(){return this._visible$.getValue()}get enabled(){return this._enabled$.getValue()}constructor(e,t,n){super(),this._sheetsFilterController=e,this._commandService=t,this._configService=n,I(this,`_d`,new i),I(this,`_visible$`,new C(!1)),I(this,`visible$`,this._visible$.asObservable()),I(this,`_enabled$`,new C(!0)),I(this,`enabled$`,this._enabled$.asObservable());let r=this._configService.getConfig(q);if(r!=null&&r.enableSyncSwitch&&(this._visible$.next(!0),typeof r.enableSyncSwitch==`object`)){var a;this.setEnabled((a=r.enableSyncSwitch.defaultValue)==null?!0:a)}}setEnabled(e){this._enabled$.next(e),e?this._d.dispose():this._initOnlyLocalListener()}_initOnlyLocalListener(){this._d.add(this._commandService.beforeCommandExecuted((e,t)=>{_t.includes(e.id)&&(t||(t={}),t.onlyLocal=!0)})),this._d.add(this._commandService.onCommandExecuted((e,t)=>{if(vt.includes(e.id)&&t!=null&&t.fromCollab){if(e.id===de.id){let{range:n,unitId:r,subUnitId:i}=e.params,{redos:a}=this._sheetsFilterController.handleInsertColCommand(n,r,i);b(a,this._commandService,t)}else if(e.id===ye.id){let{range:n,unitId:r,subUnitId:i}=e.params,{redos:a}=this._sheetsFilterController.handleRemoveColCommand(n,r,i);b(a,this._commandService,t)}else if(e.id===me.id){let{sourceRange:n,targetRange:r,unitId:i,subUnitId:a}=e.params,{redos:o}=this._sheetsFilterController.handleMoveColsCommand({fromRange:n,toRange:r},i,a);b(o,this._commandService,t)}}}))}};Z=B([z(0,d(X)),z(1,o),z(2,s)],Z);var yt=`@univerjs/sheets-filter`,bt=`0.18.0`;let Q=class extends r{constructor(e,t,n,r){super(),this._activeDirtyManagerService=e,this._sheetRowFilteredService=t,this._sheetsFilterService=n,this._univerInstanceService=r,this._initFormulaDirtyRange(),this._registerSheetRowFiltered()}_initFormulaDirtyRange(){O.forEach(e=>{this._activeDirtyManagerService.register(e,{commandId:e,getDirtyData:e=>{let{unitId:t,subUnitId:n}=e.params;return{dirtyRanges:this._getHideRowMutation(t,n),clearDependencyTreeCache:{[t]:{[n]:`1`}}}}})})}_getHideRowMutation(e,t){var n,r;let i=(n=this._sheetsFilterService.getFilterModel(e,t))==null?void 0:n.getRange(),a=(r=this._univerInstanceService.getUnit(e))==null?void 0:r.getSheetBySheetId(t);if(i==null||a==null)return[];let{startRow:o,endRow:s}=i;return[{unitId:e,sheetId:t,range:{startRow:o,startColumn:0,endRow:s,endColumn:a.getColumnCount()-1}}]}_registerSheetRowFiltered(){this._sheetRowFilteredService.register((e,t,n)=>{var r,i;return(r=(i=this._sheetsFilterService.getFilterModel(e,t))==null?void 0:i.isRowFiltered(n))==null?!1:r})}};Q=B([z(0,d(Fe)),z(1,d(Ie)),z(2,d(H)),z(3,u)],Q);let $=class extends h{constructor(e=J,t,n){super(),this._config=e,this._injector=t,this._configService=n;let{...r}=ie({},J,this._config);this._configService.setConfig(q,r)}onStarting(){[[Q],[H],[X],[Z]].forEach(e=>this._injector.add(e))}onReady(){oe(this._injector,[[Q],[X],[Z]])}};I($,`type`,v.UNIVER_SHEET),I($,`pluginName`,V),I($,`packageName`,yt),I($,`version`,bt),$=B([z(1,d(f)),z(2,s)],$);export{ut as ClearSheetsFilterCriteriaCommand,A as CustomFilterOperator,O as FILTER_MUTATIONS,k as FilterBy,Ye as FilterColumn,R as FilterModel,dt as ReCalcSheetsFilterCommand,K as ReCalcSheetsFilterMutation,st as RemoveSheetFilterCommand,G as RemoveSheetsFilterMutation,V as SHEET_FILTER_SNAPSHOT_ID,ot as SetSheetFilterRangeCommand,lt as SetSheetsFilterCriteriaCommand,W as SetSheetsFilterCriteriaMutation,U as SetSheetsFilterRangeMutation,H as SheetsFilterService,Z as SheetsFilterSyncController,ct as SmartToggleSheetsFilterCommand,$ as UniverSheetsFilterPlugin,j as equals,N as getCustomFilterFn,Le as greaterThan,Re as greaterThanOrEqualTo,ze as lessThan,Be as lessThanOrEqualTo,M as notEquals};