@univerjs/sheets-filter 0.20.1 → 0.21.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/cjs/index.js CHANGED
@@ -1 +1,2351 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require(`@univerjs/core`),t=require(`@univerjs/sheets`),n=require(`rxjs`),r=require(`@univerjs/engine-render`),i=require(`@univerjs/rpc`),a=require(`@univerjs/engine-formula`);const o=`sheet.mutation.set-filter-range`,s=`sheet.mutation.set-filter-criteria`,c=`sheet.mutation.remove-filter`,l=`sheet.mutation.re-calc-filter`,u=new Set([o,s,c,l]);let d=function(e){return e[e.VALUES=0]=`VALUES`,e[e.COLORS=1]=`COLORS`,e[e.CONDITIONS=2]=`CONDITIONS`,e}({}),f=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 p={operator:f.GREATER_THAN,fn:(e,t)=>x(e)?e>t:!1},m={operator:f.GREATER_THAN_OR_EQUAL,fn:(e,t)=>x(e)?e>=t:!1},h={operator:f.LESS_THAN,fn:(e,t)=>x(e)?e<t:!1},g={operator:f.LESS_THAN_OR_EQUAL,fn:(e,t)=>x(e)?e<=t:!1},_={operator:f.EQUAL,fn:(e,t)=>x(e)?e===t:!1},v={operator:f.NOT_EQUALS,fn:(t,n)=>{if(typeof n==`string`){if(n===` `)return t!=null;let r=C(t);return r&&ne(n)?!(0,e.createREGEXFromWildChar)(n).test(r):r!==n}return x(t)?t!==n:!0}},y=new Map([]);[p,m,h,g,_,v].forEach(e=>{y.set(e.operator,e)});function ee(e){return!!e}const te={fn:(t,n)=>{let r=C(t);return r===null?n===``:(0,e.createREGEXFromWildChar)(n).test(r)}};function b(e){return e?y.get(e):te}function x(e){return typeof e==`number`}function S(t){return!!(typeof t==`number`||typeof t==`string`&&(0,e.isNumeric)(t))}function C(e){return typeof e==`boolean`||e==null?null:typeof e==`string`?e:e.toString()}function ne(e){return typeof e==`number`?!1:e.indexOf(`*`)!==-1||e.indexOf(`?`)!==-1}function w(e){"@babel/helpers - typeof";return w=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},w(e)}function re(e,t){if(w(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(w(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function ie(e){var t=re(e,`string`);return w(t)==`symbol`?t:t+``}function T(e,t,n){return(t=ie(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const E=()=>new Set;var D=class t extends e.Disposable{get filteredOutRows(){return this._filteredOutRows$.getValue()}set filteredOutRows(e){this._alreadyFilteredOutRows=e,this._filteredOutRows$.next(e)}constructor(e,t,r){super(),this.unitId=e,this.subUnitId=t,this._worksheet=r,T(this,`_filteredOutRows$`,new n.BehaviorSubject(E())),T(this,`filteredOutRows$`,this._filteredOutRows$.asObservable()),T(this,`_hasCriteria$`,new n.BehaviorSubject(!1)),T(this,`hasCriteria$`,this._hasCriteria$.asObservable()),T(this,`_filterColumnByIndex`,new Map),T(this,`_alreadyFilteredOutRows`,E()),T(this,`_range`,void 0)}dispose(){super.dispose(),this._filteredOutRows$.complete(),this._hasCriteria$.complete(),this._worksheet=null}serialize(){let t={ref:e.Rectangle.clone(this._range),filterColumns:this._getAllFilterColumns(!0).sort(([e],[t])=>e-t).map(([e,t])=>t.serialize())};return this._alreadyFilteredOutRows&&(t.cachedFilteredOut=Array.from(this._alreadyFilteredOutRows).sort()),t}static deserialize(e,n,r,i){let a=new t(e,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(t){return this._getAllFilterColumns(!0).filter(([e])=>e!==t).reduce((t,[,n])=>{let r=n.calc({getAlreadyFilteredOutRows:()=>t});return r?(0,e.mergeSets)(t,r):t},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=E(),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 O(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((t,n)=>(0,e.mergeSets)(t,n.filteredOutRows),new Set)}_reCalcWithNoCacheColumns(){let t=this._getAllFilterColumns().filter(e=>!e.hasCache());for(let n of t){let t=n.reCalc();t&&(this._alreadyFilteredOutRows=(0,e.mergeSets)(this._alreadyFilteredOutRows,t))}}},O=class extends e.Disposable{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,T(this,`_filteredOutRows`,null),T(this,`_filterFn`,null),T(this,`_range`,null),T(this,`_column`,0),T(this,`_filterBy`,d.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 e.Tools.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 e.Tools.deepClone(this._criteria)}reCalc(){return this._filteredOutRows=this.calc(this._filterColumnContext),this._filteredOutRows}calc(t){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 n=this._column,r={startColumn:n,endColumn:n,startRow:this._range.startRow+1,endRow:this._range.endRow},i=new Set,a=t.getAlreadyFilteredOutRows();for(let t of this._worksheet.iterateByColumn(r,!1,!1)){let{row:n,rowSpan:r,col:o}=t;if(!(a.has(n)&&(!r||r===1))&&!(this._filterBy===d.VALUES?this._filterFn((0,e.extractPureTextFromCell)(this._worksheet.getCell(n,o))):this._filterBy===d.COLORS?this._filterFn(this._worksheet.getComposedCellStyle(n,o)):this._filterFn(ce(this._worksheet,n,o)))&&(i.add(n),r))for(let e=1;e<r;e++)i.add(n+e)}return i}_generateFilterFn(){this._criteria&&(this._filterFn=ae(this._criteria),this._filterBy=this._criteria.filters?d.VALUES:this._criteria.colorFilters?d.COLORS:d.CONDITIONS)}};function ae(e){if(e.filters)return k(e.filters);if(e.colorFilters)return A(e.colorFilters);if(e.customFilters)return j(e.customFilters);throw Error(`[FilterModel]: other types of filters are not supported yet.`)}function k(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 A(t){if(t.cellFillColors){let n=new Set(t.cellFillColors);return t=>{var r;if(!t||!((r=t.bg)!=null&&r.rgb))return!!n.has(null);let i=new e.ColorKit(t.bg.rgb).toRgbString();return n.has(i)}}if(t.cellTextColors){let n=new Set(t.cellTextColors);return t=>{var i;if(!t||!((i=t.cl)!=null&&i.rgb))return!!n.has(r.COLOR_BLACK_RGB);let a=new e.ColorKit(t.cl.rgb).toRgbString();return n.has(a)}}throw Error(`[FilterModel]: color filters are not supported yet.`)}function j(e){let t=e.customFilters.map(e=>se(e));return oe(t)?e.and?M(t):N(t):t[0]}function M(e){let[t,n]=e;return e=>t(e)&&n(e)}function N(e){let[t,n]=e;return e=>t(e)||n(e)}function oe(e){return e.length===2}function se(e){let t=e.val;if(e.operator===f.NOT_EQUALS&&!S(t))return e=>v.fn(e,t);if(ee(e.operator)){if(!S(t))return()=>!1;let n=b(e.operator),r=Number(t);return e=>n.fn(e,r)}let n=b(e.operator);return e=>n.fn(e,t)}function ce(t,n,r){let i=t.getCell(n,r);if(!i)return null;let a=t.getCellRaw(n,r);return i&&!a?P(i):a?i.t===e.CellValueType.NUMBER&&typeof i.v==`string`?a.v:i.t===e.CellValueType.NUMBER?Number(a.v):P(a):null}function P(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.CellValueType.BOOLEAN?i.toUpperCase():i:typeof i==`number`?t.t===e.CellValueType.BOOLEAN?i?`TRUE`:`FALSE`:i:typeof i==`boolean`?i?`TRUE`:`FALSE`:``}function F(e,t){return function(n,r){t(n,r,e)}}function I(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 L=`SHEET_FILTER_PLUGIN`;let R=class extends e.Disposable{get activeFilterModel(){return this._activeFilterModel$.getValue()}constructor(e,t,r){super(),this._resourcesManagerService=e,this._univerInstanceService=t,this._commandService=r,T(this,`_filterModels`,new Map),T(this,`_loadedUnitId$`,new n.BehaviorSubject(null)),T(this,`loadedUnitId$`,this._loadedUnitId$.asObservable()),T(this,`_errorMsg$`,new n.BehaviorSubject(null)),T(this,`errorMsg$`,this._errorMsg$.asObservable()),T(this,`_activeFilterModel$`,new n.BehaviorSubject(null)),T(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 D(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 t;try{if(t=this._univerInstanceService.getCurrentUnitForType(e.UniverInstanceType.UNIVER_SHEET),!t){this._activeFilterModel$.next(null);return}}catch(e){console.error(`[SheetsFilterService]: could not get active workbook!`,e);return}let n=t.getActiveSheet(!0);if(!n){this._activeFilterModel$.next(null);return}let r=n.getUnitId(),i=n.getSheetId(),a=this.getFilterModel(r,i);this._activeFilterModel$.next(a)}_initActiveFilterModel(){this.disposeWithMe((0,n.merge)((0,e.fromCallback)(this._commandService.onCommandExecuted.bind(this._commandService)).pipe((0,n.filter)(([t])=>t.type===e.CommandType.MUTATION&&u.has(t.id))),this._univerInstanceService.getCurrentTypeOfUnit$(e.UniverInstanceType.UNIVER_SHEET).pipe((0,n.switchMap)(e=>{var t;return(t=e==null?void 0:e.activeSheet$)==null?(0,n.of)(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=D.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:L,businesses:[e.UniverInstanceType.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)}};R=I([F(0,e.IResourceManagerService),F(1,e.IUniverInstanceService),F(2,e.ICommandService)],R);const z={id:o,type:e.CommandType.MUTATION,handler:(e,t)=>{let{subUnitId:n,unitId:r,range:i}=t;return e.get(R).ensureFilterModel(r,n).setRange(i),!0}},B={id:s,type:e.CommandType.MUTATION,handler:(e,t)=>{let{subUnitId:n,unitId:r,criteria:i,col:a,reCalc:o=!0}=t,s=e.get(R).getFilterModel(r,n);return s?(s.setCriteria(a,i,o),!0):!1}},V={id:c,type:e.CommandType.MUTATION,handler:(e,t)=>{let{unitId:n,subUnitId:r}=t;return e.get(R).removeFilterModel(n,r)}},H={id:l,type:e.CommandType.MUTATION,handler:(e,t)=>{let{unitId:n,subUnitId:r}=t,i=e.get(R).getFilterModel(n,r);return i?(i.reCalc(),!0):!1}},U={id:`sheet.command.set-filter-range`,type:e.CommandType.COMMAND,handler:(n,r)=>{let i=n.get(R),a=n.get(e.ICommandService),o=n.get(e.IUndoRedoService),s=n.get(e.IUniverInstanceService),{unitId:c,subUnitId:l,range:u}=r;if(!(0,t.getSheetCommandTarget)(s,r)||i.getFilterModel(c,l))return!1;if(u.endRow===u.startRow){let t=n.get(e.ErrorService),r=n.get(e.LocaleService);return t.emit(r.t(`sheets-filter.command.not-valid-filter-range`)),!1}let d={id:z.id,params:{unitId:c,subUnitId:l,range:u}},f=a.syncExecuteCommand(d.id,d.params);return f&&o.pushUndoRedo({unitID:c,undoMutations:[{id:V.id,params:{unitId:c,subUnitId:l}}],redoMutations:[d]}),f}},W={id:`sheet.command.remove-sheet-filter`,type:e.CommandType.COMMAND,handler:(n,r)=>{let i=(0,t.getSheetCommandTarget)(n.get(e.IUniverInstanceService),r);if(!i)return!1;let a=n.get(R),{unitId:o,subUnitId:s}=i,c=a.getFilterModel(o,s);if(!c)return!1;let l=c.getRange();if(!l)return!1;let u=n.get(e.ICommandService),d=n.get(e.IUndoRedoService),f=pe(o,s,c.serialize()),p=u.syncExecuteCommand(V.id,{unitId:o,subUnitId:s});return p&&(d.pushUndoRedo({unitID:o,undoMutations:f,redoMutations:[{id:V.id,params:{unitId:o,subUnitId:s}}]}),u.executeCommand(t.MarkDirtyFilterChangeMutation.id,{unitId:o,subUnitId:s,filterRange:l})),p}},le={id:`sheet.command.smart-toggle-filter`,type:e.CommandType.COMMAND,handler:async n=>{let r=n.get(e.IUniverInstanceService),i=n.get(R),a=n.get(e.ICommandService),o=r.getCurrentUnitForType(e.UniverInstanceType.UNIVER_SHEET),s=o==null?void 0:o.getActiveSheet();if(!s||!o)return!1;let c=o.getUnitId(),l=s.getSheetId();if(i.getFilterModel(c,l))return a.executeCommand(W.id,{unitId:c,subUnitId:l});let u=n.get(t.SheetsSelectionsService).getCurrentLastSelection();if(!u)return!1;let d=u.range,f=(0,t.isSingleCellSelection)(u)?(0,t.expandToContinuousRange)(d,{left:!0,right:!0,up:!0,down:!0},s):d.startRow===d.endRow?(0,t.expandToContinuousRange)(d,{down:!0},s):d;return a.executeCommand(U.id,{unitId:c,subUnitId:l,range:f})}},ue={id:`sheet.command.set-filter-criteria`,type:e.CommandType.COMMAND,handler:(n,r)=>{let i=(0,t.getSheetCommandTarget)(n.get(e.IUniverInstanceService),r);if(!i)return!1;let a=n.get(R),{unitId:o,subUnitId:s}=i,c=a.getFilterModel(o,s);if(!c)return!1;let{col:l,criteria:u}=r,d=c.getRange();if(!d||l<d.startColumn||l>d.endColumn)return!1;let f=n.get(e.ICommandService),p=n.get(e.IUndoRedoService),m=he(o,s,l,c.getFilterColumn(l)),h={id:B.id,params:{unitId:o,subUnitId:s,col:l,criteria:u}},g=f.syncExecuteCommand(h.id,h.params);return g&&(p.pushUndoRedo({unitID:o,undoMutations:[m],redoMutations:[h]}),f.executeCommand(t.MarkDirtyFilterChangeMutation.id,{unitId:o,subUnitId:s,filterRange:d})),g}},de={id:`sheet.command.clear-filter-criteria`,type:e.CommandType.COMMAND,handler:(n,r)=>{let i=(0,t.getSheetCommandTarget)(n.get(e.IUniverInstanceService),r);if(!i)return!1;let a=n.get(R),{unitId:o,subUnitId:s}=i,c=a.getFilterModel(o,s);if(!c)return!1;let l=c.getRange();if(!l)return!1;let u=n.get(e.IUndoRedoService),d=n.get(e.ICommandService),f=c.serialize(),p=G(o,s,f),m=me(o,s,f);return(0,e.sequenceExecute)(m,d).result?(u.pushUndoRedo({unitID:o,undoMutations:p,redoMutations:m}),d.executeCommand(t.MarkDirtyFilterChangeMutation.id,{unitId:o,subUnitId:s,filterRange:l}),!0):!1}},fe={id:`sheet.command.re-calc-filter`,type:e.CommandType.COMMAND,handler:(n,r)=>{let i=n.get(R),a=n.get(e.ICommandService),o=(0,t.getSheetCommandTarget)(n.get(e.IUniverInstanceService),r);if(!o)return!1;let{unitId:s,subUnitId:c}=o;return i.getFilterModel(o.unitId,o.subUnitId)?a.executeCommand(H.id,{unitId:s,subUnitId:c}):!1}};function pe(e,t,n){let r=[],i={id:z.id,params:{unitId:e,subUnitId:t,range:n.ref}};return r.push(i),G(e,t,n).forEach(e=>r.push(e)),r}function G(e,t,n){var r;let i=[];return(r=n.filterColumns)==null||r.forEach(n=>{let r={id:B.id,params:{unitId:e,subUnitId:t,col:n.colId,criteria:n}};i.push(r)}),i}function me(e,t,n){var r;let i=[];return(r=n.filterColumns)==null||r.forEach(n=>{let r={id:B.id,params:{unitId:e,subUnitId:t,col:n.colId,criteria:null}};i.push(r)}),i}function he(e,t,n,r){if(!r)return{id:B.id,params:{unitId:e,subUnitId:t,col:n,criteria:null}};let i=r.serialize();return{id:B.id,params:{unitId:e,subUnitId:t,col:n,criteria:i}}}const K=`sheets-filter.config`;Symbol(K);const q={};function ge(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 J(e){return ge(e,(e,t)=>e.id===B.id&&t.id===B.id&&e.params.unitId===t.params.unitId&&e.params.subUnitId===t.params.subUnitId&&e.params.col===t.params.col)}let Y=class extends e.Disposable{constructor(t,n,r,i,a,o,s){super(),this._commandService=t,this._sheetInterceptorService=n,this._sheetsFilterService=r,this._univerInstanceService=i,this._refRangeService=a,this._dataSyncPrimaryController=o,this._zebraCrossingCacheController=s,T(this,`_disposableCollection`,new e.DisposableCollection),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(){[B,z,H,V].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===t.SetWorksheetActiveOperation.id){let t=e.params,n=t.subUnitId,r=t.unitId;if(!n||!r)return;this._registerRefRange(r,n)}if(e.id===z.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,n){var r;this._disposableCollection.dispose();let i=this._univerInstanceService.getUniverSheetInstance(e),a=i==null?void 0:i.getSheetBySheetId(n);if(!i||!a)return;let o=(r=this._sheetsFilterService.getFilterModel(e,n))==null?void 0:r.getRange();o&&this._disposableCollection.add(this._refRangeService.registerRefRange(o,r=>{switch(r.id){case t.InsertRowCommand.id:{let t=r.params,i=t.unitId||e,a=t.subUnitId||n;return this._handleInsertRowCommand(t,i,a)}case t.InsertColCommand.id:{let t=r.params,i=t.unitId||e,a=t.subUnitId||n;return this.handleInsertColCommand(t.range,i,a)}case t.RemoveColCommand.id:{let t=r.params;return this.handleRemoveColCommand(t.range,e,n)}case t.RemoveRowCommand.id:{let t=r.params;return this._handleRemoveRowCommand(t,e,n)}case t.EffectRefRangId.MoveColsCommandId:{let t=r.params;return this.handleMoveColsCommand({fromRange:t.fromRange,toRange:t.toRange},e,n)}case t.EffectRefRangId.MoveRowsCommandId:{let t=r.params;return this._handleMoveRowsCommand(t,e,n)}case t.MoveRangeCommand.id:{let t=r.params;return this._handleMoveRangeCommand(t,e,n)}}return{redos:[],undos:[]}},e,n))}_getUpdateFilter(e){let{id:n}=e;switch(n){case t.RemoveSheetCommand.id:{let t=e.params;return this._handleRemoveSheetCommand(t,t.unitId,t.subUnitId)}case t.CopySheetCommand.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:z.id,params:m}),f.push({id:z.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:J(d),undos:J(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:z.id,params:p}),f.push({id:z.id,params:m}),{redos:J(d),undos:J(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:B.id,params:{unitId:t,subUnitId:n,col:r,criteria:null}}),d.push({id:B.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:V.id,params:e}),d.unshift({id:z.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:z.id,params:i}),d.unshift({id:z.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:z.id,params:{range:i,unitId:t,subUnitId:n}}],redos:[{id:z.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:z.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:V.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:B.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:z.id,params:f})}return{undos:J(u),redos:J(l)}}handleMoveColsCommand({fromRange:t,toRange:n},r,i){var a;let o=this._sheetsFilterService.getFilterModel(r,i),s=(a=o==null?void 0:o.getRange())==null?null:a;if(!o||!s)return this._handleNull();let{startColumn:c,endColumn:l}=s;if(t.endColumn<c&&n.startColumn<=c||t.startColumn>l&&n.endColumn>l)return this._handleNull();let u=[],d=[],f={};for(let e=c;e<=l;e++)f[e]={colIndex:e,filter:o.getFilterColumn(e)};(0,e.moveMatrixArray)(t.startColumn,t.endColumn-t.startColumn+1,n.startColumn,f);let p=s.startColumn,m=s.endColumn;c>=t.startColumn&&c<=t.endColumn&&n.startColumn>t.startColumn&&t.endColumn<l&&(p=t.endColumn+1),l>=t.startColumn&&l<=t.endColumn&&n.startColumn<t.startColumn&&t.startColumn>c&&(m=t.startColumn-1);let h=Object.keys(f).map(e=>Number(e)),g=h.find(e=>f[e].colIndex===m),_=h.find(e=>f[e].colIndex===p);if(h.forEach(e=>{let{colIndex:t,filter:n}=f[e],a=e;if(n){var s;if(a>=_&&a<=g){var c;let e={unitId:r,subUnitId:i,col:a,criteria:{...n.serialize(),colId:a}},t={unitId:r,subUnitId:i,col:a,criteria:o.getFilterColumn(a)?{...(c=o.getFilterColumn(a))==null?void 0:c.serialize(),colId:a}:null};u.push({id:B.id,params:e}),d.push({id:B.id,params:t})}if(!((s=f[t])!=null&&s.filter)){let e={unitId:r,subUnitId:i,col:t,criteria:null};u.push({id:B.id,params:e}),d.push({id:B.id,params:{unitId:r,subUnitId:i,col:t,criteria:{...n.serialize(),colId:t}}})}}}),c!==_||l!==g){let e={unitId:r,subUnitId:i,range:{...s,startColumn:_,endColumn:g}};u.unshift({id:z.id,params:e}),d.unshift({id:z.id,params:{range:s,unitId:r,subUnitId:i}})}return{undos:d,redos:u}}_handleMoveRowsCommand(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{startRow:s,endRow:c}=o,{fromRange:l,toRange:u}=t;if(l.endRow<s&&u.startRow<=s||l.startRow>c&&u.endRow>c)return this._handleNull();let d=[],f=[],p={};for(let e=s;e<=c;e++)p[e]={oldIndex:e};let m=s,h=c;c>=l.startRow&&c<=l.endRow&&u.startRow<l.startRow&&l.startRow>s&&(h=l.startRow-1),(0,e.moveMatrixArray)(l.startRow,l.endRow-l.startRow+1,u.startRow,p);let g=Object.keys(p).map(e=>Number(e)),_=g.find(e=>p[e].oldIndex===h),v=g.find(e=>p[e].oldIndex===m);if(s!==v||c!==_){let e={unitId:n,subUnitId:r,range:{...o,startRow:v,endRow:_}};d.push({id:z.id,params:e},{id:H.id,params:{unitId:n,subUnitId:r}}),f.push({id:z.id,params:{range:o,unitId:n,subUnitId:r}},{id:H.id,params:{unitId:n,subUnitId:r}})}return{redos:d,undos:f}}_handleMoveRangeCommand(t,n,r){let{fromRange:i,toRange:a}=t,o=this._sheetsFilterService.getFilterModel(n,r);if(!o)return this._handleNull();let s=o.getRange();if(!s)return this._handleNull();let c=[],l=[];if(e.Rectangle.contains(i,s)){let e=s.startRow-i.startRow,t=s.startColumn-i.startColumn,u={startRow:a.startRow+e,startColumn:a.startColumn+t,endRow:a.startRow+e+(s.endRow-s.startRow),endColumn:a.startColumn+t+(s.endColumn-s.startColumn)},d={id:V.id,params:{unitId:n,subUnitId:r}},f={id:z.id,params:{unitId:n,subUnitId:r,range:u}},p={id:z.id,params:{unitId:n,subUnitId:r,range:s}};c.push(d,f),l.push(d,p);let m=o.getAllFilterColumns(),h=a.startColumn-i.startColumn;m.forEach(e=>{let[t,i]=e;i&&(c.push({id:B.id,params:{unitId:n,subUnitId:r,col:t+h,criteria:{...i.serialize(),colId:t+h}}}),l.push({id:B.id,params:{unitId:n,subUnitId:r,col:t,criteria:{...i.serialize(),colId:t}}}))})}else if(e.Rectangle.intersects(a,s)){let e={...s,endRow:Math.max(s.endRow,a.endRow)};c.push({id:z.id,params:{unitId:n,subUnitId:r,range:e}}),l.push({id:z.id,params:{unitId:n,subUnitId:r,range:s}})}return{redos:c,undos:l}}_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:B.id,params:{unitId:t,subUnitId:n,col:e,criteria:{...r.serialize(),colId:e}}})}),a.push({id:V.id,params:{unitId:t,subUnitId:n,range:i}}),o.unshift({id:z.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:B.id,params:{unitId:e,subUnitId:n,col:t,criteria:{...r.serialize(),colId:t}}}),s.push({id:B.id,params:{unitId:e,subUnitId:n,col:t,criteria:null}})}),s.push({id:V.id,params:{unitId:e,subUnitId:n,range:i}}),a.unshift({id:z.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(t.INTERCEPTOR_POINT.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:B.id,params:{...i,col:t}}),a.push({id:B.id,params:{...i,col:t,criteria:{...n.serialize(),colId:t}}})}),n.forEach(e=>{let[t,n]=e;c.push({id:B.id,params:{...i,col:t+r,criteria:{...n.serialize(),colId:t+r}}}),s.push({id:B.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,n)=>{let{unitId:r,subUnitId:i}=e.params||{},a=this._sheetsFilterService.getFilterModel(r,i);if(!a)return;let o=Array.from(a.filteredOutRows).sort((e,t)=>e-t),s=[],c=!1;if(e.id===t.RemoveRowMutation.id){let{startRow:t,endRow:n}=e.params.range,r=o.filter(e=>e>=t&&e<=n);o.forEach(e=>{if(e<t)s.push(e);else if(c=!0,e<=n){let e=Math.max(t,s.length?s[s.length-1]+1:t);s.push(e)}else s.push(e-(n-t+1-r.length))})}if(e.id===t.InsertRowMutation.id){let{startRow:t,endRow:n}=e.params.range;o.forEach(e=>{e>=t?(c=!0,s.push(e+(n-t+1))):s.push(e)})}if(c&&(a.filteredOutRows=new Set(s)),e.id===t.SetRangeValuesMutation.id&&!(n!=null&&n.onlyLocal)){let n=this._getExtendRegion(r,i);if(n){let a=e.params.cellValue;if(a)for(let e=n.startColumn;e<=n.endColumn;e++){var l;let o=a==null||(l=a[n.startRow])==null?void 0:l[e];if(o&&this._cellHasValue(o)){var u;let e=(u=this._univerInstanceService.getUnit(r))==null?void 0:u.getSheetBySheetId(i);if(e){let a=(0,t.expandToContinuousRange)(n,{down:!0},e),o=this._sheetsFilterService.getFilterModel(r,i),s=o.getRange();o.setRange({...s,endRow:a.endRow}),this._registerRefRange(r,i)}}}}}}))}_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 n=e.params,r=(0,t.getSheetCommandTarget)(this._univerInstanceService,n);if(!r)return;let{subUnitId:i,unitId:a}=r,o=this._sheetsFilterService.getFilterModel(a,i);if(!o)return;let s=o.getRange();if(e.id===t.MoveRowsCommand.id&&n.fromRange.startRow<=s.startRow&&n.fromRange.endRow<s.endRow&&n.fromRange.endRow>=s.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))}};Y=I([F(0,e.ICommandService),F(1,(0,e.Inject)(t.SheetInterceptorService)),F(2,(0,e.Inject)(R)),F(3,e.IUniverInstanceService),F(4,(0,e.Inject)(t.RefRangeService)),F(5,(0,e.Optional)(i.DataSyncPrimaryController)),F(6,(0,e.Inject)(t.ZebraCrossingCacheController))],Y);const _e=[B.id,H.id],ve=[t.InsertColMutation.id,t.RemoveColMutation.id,t.MoveColsMutation.id];let X=class extends e.Disposable{get visible(){return this._visible$.getValue()}get enabled(){return this._enabled$.getValue()}constructor(t,r,i){super(),this._sheetsFilterController=t,this._commandService=r,this._configService=i,T(this,`_d`,new e.DisposableCollection),T(this,`_visible$`,new n.BehaviorSubject(!1)),T(this,`visible$`,this._visible$.asObservable()),T(this,`_enabled$`,new n.BehaviorSubject(!0)),T(this,`enabled$`,this._enabled$.asObservable());let a=this._configService.getConfig(K);if(a!=null&&a.enableSyncSwitch&&(this._visible$.next(!0),typeof a.enableSyncSwitch==`object`)){var o;this.setEnabled((o=a.enableSyncSwitch.defaultValue)==null?!0:o)}}setEnabled(e){this._enabled$.next(e),e?this._d.dispose():this._initOnlyLocalListener()}_initOnlyLocalListener(){this._d.add(this._commandService.beforeCommandExecuted((e,t)=>{_e.includes(e.id)&&(t||(t={}),t.onlyLocal=!0)})),this._d.add(this._commandService.onCommandExecuted((n,r)=>{if(ve.includes(n.id)&&r!=null&&r.fromCollab){if(n.id===t.InsertColMutation.id){let{range:t,unitId:i,subUnitId:a}=n.params,{redos:o}=this._sheetsFilterController.handleInsertColCommand(t,i,a);(0,e.sequenceExecute)(o,this._commandService,r)}else if(n.id===t.RemoveColMutation.id){let{range:t,unitId:i,subUnitId:a}=n.params,{redos:o}=this._sheetsFilterController.handleRemoveColCommand(t,i,a);(0,e.sequenceExecute)(o,this._commandService,r)}else if(n.id===t.MoveColsMutation.id){let{sourceRange:t,targetRange:i,unitId:a,subUnitId:o}=n.params,{redos:s}=this._sheetsFilterController.handleMoveColsCommand({fromRange:t,toRange:i},a,o);(0,e.sequenceExecute)(s,this._commandService,r)}}}))}};X=I([F(0,(0,e.Inject)(Y)),F(1,e.ICommandService),F(2,e.IConfigService)],X);var Z=`@univerjs/sheets-filter`,ye=`0.20.1`;let Q=class extends e.Disposable{constructor(e,t,n,r){super(),this._activeDirtyManagerService=e,this._sheetRowFilteredService=t,this._sheetsFilterService=n,this._univerInstanceService=r,this._initFormulaDirtyRange(),this._registerSheetRowFiltered()}_initFormulaDirtyRange(){u.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=I([F(0,(0,e.Inject)(a.IActiveDirtyManagerService)),F(1,(0,e.Inject)(a.ISheetRowFilteredService)),F(2,(0,e.Inject)(R)),F(3,e.IUniverInstanceService)],Q);let $=class extends e.Plugin{constructor(t=q,n,r){super(),this._config=t,this._injector=n,this._configService=r;let{...i}=(0,e.merge)({},q,this._config);this._configService.setConfig(K,i)}onStarting(){[[Q],[R],[Y],[X]].forEach(e=>this._injector.add(e))}onReady(){(0,e.touchDependencies)(this._injector,[[Q],[Y],[X]])}};T($,`type`,e.UniverInstanceType.UNIVER_SHEET),T($,`pluginName`,L),T($,`packageName`,Z),T($,`version`,ye),$=I([F(1,(0,e.Inject)(e.Injector)),F(2,e.IConfigService)],$),exports.ClearSheetsFilterCriteriaCommand=de,exports.CustomFilterOperator=f,exports.FILTER_MUTATIONS=u,exports.FilterBy=d,exports.FilterColumn=O,exports.FilterModel=D,exports.ReCalcSheetsFilterCommand=fe,exports.ReCalcSheetsFilterMutation=H,exports.RemoveSheetFilterCommand=W,exports.RemoveSheetsFilterMutation=V,exports.SHEET_FILTER_SNAPSHOT_ID=L,exports.SetSheetFilterRangeCommand=U,exports.SetSheetsFilterCriteriaCommand=ue,exports.SetSheetsFilterCriteriaMutation=B,exports.SetSheetsFilterRangeMutation=z,Object.defineProperty(exports,`SheetsFilterService`,{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,`SheetsFilterSyncController`,{enumerable:!0,get:function(){return X}}),exports.SmartToggleSheetsFilterCommand=le,Object.defineProperty(exports,`UniverSheetsFilterPlugin`,{enumerable:!0,get:function(){return $}}),exports.equals=_,exports.getCustomFilterFn=b,exports.greaterThan=p,exports.greaterThanOrEqualTo=m,exports.lessThan=h,exports.lessThanOrEqualTo=g,exports.notEquals=v;
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ let _univerjs_core = require("@univerjs/core");
3
+ let _univerjs_sheets = require("@univerjs/sheets");
4
+ let rxjs = require("rxjs");
5
+ let _univerjs_engine_render = require("@univerjs/engine-render");
6
+ let _univerjs_rpc = require("@univerjs/rpc");
7
+ let _univerjs_engine_formula = require("@univerjs/engine-formula");
8
+
9
+ //#region src/common/const.ts
10
+ /**
11
+ * Copyright 2023-present DreamNum Co., Ltd.
12
+ *
13
+ * Licensed under the Apache License, Version 2.0 (the "License");
14
+ * you may not use this file except in compliance with the License.
15
+ * You may obtain a copy of the License at
16
+ *
17
+ * http://www.apache.org/licenses/LICENSE-2.0
18
+ *
19
+ * Unless required by applicable law or agreed to in writing, software
20
+ * distributed under the License is distributed on an "AS IS" BASIS,
21
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22
+ * See the License for the specific language governing permissions and
23
+ * limitations under the License.
24
+ */
25
+ const SetSheetsFilterRangeMutationId = "sheet.mutation.set-filter-range";
26
+ const SetSheetsFilterCriteriaMutationId = "sheet.mutation.set-filter-criteria";
27
+ const RemoveSheetsFilterMutationId = "sheet.mutation.remove-filter";
28
+ const ReCalcSheetsFilterMutationId = "sheet.mutation.re-calc-filter";
29
+ const FILTER_MUTATIONS = new Set([
30
+ SetSheetsFilterRangeMutationId,
31
+ SetSheetsFilterCriteriaMutationId,
32
+ RemoveSheetsFilterMutationId,
33
+ ReCalcSheetsFilterMutationId
34
+ ]);
35
+
36
+ //#endregion
37
+ //#region src/models/types.ts
38
+ /**
39
+ * The filter types.
40
+ */
41
+ let FilterBy = /* @__PURE__ */ function(FilterBy) {
42
+ FilterBy[FilterBy["VALUES"] = 0] = "VALUES";
43
+ FilterBy[FilterBy["COLORS"] = 1] = "COLORS";
44
+ FilterBy[FilterBy["CONDITIONS"] = 2] = "CONDITIONS";
45
+ return FilterBy;
46
+ }({});
47
+ /**
48
+ * Basic custom filter operators.
49
+ *
50
+ * @internal
51
+ * doesNotContain, isBlank, isNotBlank are not defined in OOXML. They are represented by regex-like values.
52
+ */
53
+ let CustomFilterOperator = /* @__PURE__ */ function(CustomFilterOperator) {
54
+ /** "EQUAL" operator. */
55
+ CustomFilterOperator["EQUAL"] = "equal";
56
+ /** "GREATER_THAN" operator. */
57
+ CustomFilterOperator["GREATER_THAN"] = "greaterThan";
58
+ /** "GREATER_THAN_OR_EQUAL" operator. */
59
+ CustomFilterOperator["GREATER_THAN_OR_EQUAL"] = "greaterThanOrEqual";
60
+ /** "LESS_THAN" operator. */
61
+ CustomFilterOperator["LESS_THAN"] = "lessThan";
62
+ /** "LESS_THAN_OR_EQUAL" operator. */
63
+ CustomFilterOperator["LESS_THAN_OR_EQUAL"] = "lessThanOrEqual";
64
+ /** "NOT_EQUALS" operator. */
65
+ CustomFilterOperator["NOT_EQUALS"] = "notEqual";
66
+ return CustomFilterOperator;
67
+ }({});
68
+
69
+ //#endregion
70
+ //#region src/models/custom-filters.ts
71
+ const greaterThan = {
72
+ operator: CustomFilterOperator.GREATER_THAN,
73
+ fn: (value, compare) => {
74
+ if (!ensureNumber(value)) return false;
75
+ return value > compare;
76
+ }
77
+ };
78
+ const greaterThanOrEqualTo = {
79
+ operator: CustomFilterOperator.GREATER_THAN_OR_EQUAL,
80
+ fn: (value, compare) => {
81
+ if (!ensureNumber(value)) return false;
82
+ return value >= compare;
83
+ }
84
+ };
85
+ const lessThan = {
86
+ operator: CustomFilterOperator.LESS_THAN,
87
+ fn: (value, compare) => {
88
+ if (!ensureNumber(value)) return false;
89
+ return value < compare;
90
+ }
91
+ };
92
+ const lessThanOrEqualTo = {
93
+ operator: CustomFilterOperator.LESS_THAN_OR_EQUAL,
94
+ fn: (value, compare) => {
95
+ if (!ensureNumber(value)) return false;
96
+ return value <= compare;
97
+ }
98
+ };
99
+ const equals = {
100
+ operator: CustomFilterOperator.EQUAL,
101
+ fn: (value, compare) => {
102
+ if (!ensureNumber(value)) return false;
103
+ return value === compare;
104
+ }
105
+ };
106
+ const notEquals = {
107
+ operator: CustomFilterOperator.NOT_EQUALS,
108
+ fn: (value, compare) => {
109
+ if (typeof compare === "string") {
110
+ if (compare === " ") {
111
+ if (value !== void 0 && value !== null) return true;
112
+ return false;
113
+ }
114
+ const ensuredString = ensureString(value);
115
+ if (ensuredString && isWildCardString(compare)) return !(0, _univerjs_core.createREGEXFromWildChar)(compare).test(ensuredString);
116
+ return ensuredString !== compare;
117
+ }
118
+ if (!ensureNumber(value)) return true;
119
+ return value !== compare;
120
+ }
121
+ };
122
+ const CustomFilterFnRegistry = /* @__PURE__ */ new Map([]);
123
+ [
124
+ greaterThan,
125
+ greaterThanOrEqualTo,
126
+ lessThan,
127
+ lessThanOrEqualTo,
128
+ equals,
129
+ notEquals
130
+ ].forEach((fn) => {
131
+ CustomFilterFnRegistry.set(fn.operator, fn);
132
+ });
133
+ function isNumericFilterFn(operator) {
134
+ return !!operator;
135
+ }
136
+ /** This operators matches texts. */
137
+ const textMatch = { fn: (value, compare) => {
138
+ const ensured = ensureString(value);
139
+ if (ensured === null) {
140
+ if (compare === "") return true;
141
+ return false;
142
+ }
143
+ return (0, _univerjs_core.createREGEXFromWildChar)(compare).test(ensured);
144
+ } };
145
+ function getCustomFilterFn(operator) {
146
+ if (!operator) return textMatch;
147
+ return CustomFilterFnRegistry.get(operator);
148
+ }
149
+ function ensureNumber(value) {
150
+ return typeof value === "number";
151
+ }
152
+ function ensureNumeric(value) {
153
+ if (typeof value === "number") return true;
154
+ if (typeof value === "string" && (0, _univerjs_core.isNumeric)(value)) return true;
155
+ return false;
156
+ }
157
+ function ensureString(value) {
158
+ if (typeof value === "boolean" || value == null) return null;
159
+ return typeof value === "string" ? value : value.toString();
160
+ }
161
+ function isWildCardString(str) {
162
+ if (typeof str === "number") return false;
163
+ return str.indexOf("*") !== -1 || str.indexOf("?") !== -1;
164
+ }
165
+
166
+ //#endregion
167
+ //#region \0@oxc-project+runtime@0.124.0/helpers/typeof.js
168
+ function _typeof(o) {
169
+ "@babel/helpers - typeof";
170
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
171
+ return typeof o;
172
+ } : function(o) {
173
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
174
+ }, _typeof(o);
175
+ }
176
+
177
+ //#endregion
178
+ //#region \0@oxc-project+runtime@0.124.0/helpers/toPrimitive.js
179
+ function toPrimitive(t, r) {
180
+ if ("object" != _typeof(t) || !t) return t;
181
+ var e = t[Symbol.toPrimitive];
182
+ if (void 0 !== e) {
183
+ var i = e.call(t, r || "default");
184
+ if ("object" != _typeof(i)) return i;
185
+ throw new TypeError("@@toPrimitive must return a primitive value.");
186
+ }
187
+ return ("string" === r ? String : Number)(t);
188
+ }
189
+
190
+ //#endregion
191
+ //#region \0@oxc-project+runtime@0.124.0/helpers/toPropertyKey.js
192
+ function toPropertyKey(t) {
193
+ var i = toPrimitive(t, "string");
194
+ return "symbol" == _typeof(i) ? i : i + "";
195
+ }
196
+
197
+ //#endregion
198
+ //#region \0@oxc-project+runtime@0.124.0/helpers/defineProperty.js
199
+ function _defineProperty(e, r, t) {
200
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
201
+ value: t,
202
+ enumerable: !0,
203
+ configurable: !0,
204
+ writable: !0
205
+ }) : e[r] = t, e;
206
+ }
207
+
208
+ //#endregion
209
+ //#region src/models/filter-model.ts
210
+ const EMPTY = () => /* @__PURE__ */ new Set();
211
+ /**
212
+ * This is the in-memory model of filter.
213
+ */
214
+ var FilterModel = class FilterModel extends _univerjs_core.Disposable {
215
+ get filteredOutRows() {
216
+ return this._filteredOutRows$.getValue();
217
+ }
218
+ set filteredOutRows(rows) {
219
+ this._alreadyFilteredOutRows = rows;
220
+ this._filteredOutRows$.next(rows);
221
+ }
222
+ constructor(unitId, subUnitId, _worksheet) {
223
+ super();
224
+ this.unitId = unitId;
225
+ this.subUnitId = subUnitId;
226
+ this._worksheet = _worksheet;
227
+ _defineProperty(this, "_filteredOutRows$", new rxjs.BehaviorSubject(EMPTY()));
228
+ _defineProperty(this, "filteredOutRows$", this._filteredOutRows$.asObservable());
229
+ _defineProperty(this, "_hasCriteria$", new rxjs.BehaviorSubject(false));
230
+ _defineProperty(this, "hasCriteria$", this._hasCriteria$.asObservable());
231
+ _defineProperty(this, "_filterColumnByIndex", /* @__PURE__ */ new Map());
232
+ _defineProperty(this, "_alreadyFilteredOutRows", EMPTY());
233
+ _defineProperty(this, "_range", void 0);
234
+ }
235
+ dispose() {
236
+ super.dispose();
237
+ this._filteredOutRows$.complete();
238
+ this._hasCriteria$.complete();
239
+ this._worksheet = null;
240
+ }
241
+ /**
242
+ * Serialize this filter model to the JSON format representation.
243
+ */
244
+ serialize() {
245
+ const result = {
246
+ ref: _univerjs_core.Rectangle.clone(this._range),
247
+ filterColumns: this._getAllFilterColumns(true).sort(([offset1], [offset2]) => offset1 - offset2).map(([_, filterColumn]) => filterColumn.serialize())
248
+ };
249
+ if (this._alreadyFilteredOutRows) result.cachedFilteredOut = Array.from(this._alreadyFilteredOutRows).sort();
250
+ return result;
251
+ }
252
+ /**
253
+ * Deserialize auto filter info to construct a `FilterModel` object.
254
+ * @param unitId workbook id
255
+ * @param subUnitId worksheet id
256
+ * @param worksheet the Worksheet object
257
+ * @param autoFilter auto filter data
258
+ */
259
+ static deserialize(unitId, subUnitId, worksheet, autoFilter) {
260
+ const filterModel = new FilterModel(unitId, subUnitId, worksheet);
261
+ filterModel._dump(autoFilter);
262
+ return filterModel;
263
+ }
264
+ _dump(autoFilter) {
265
+ var _autoFilter$filterCol;
266
+ this.setRange(autoFilter.ref);
267
+ (_autoFilter$filterCol = autoFilter.filterColumns) === null || _autoFilter$filterCol === void 0 || _autoFilter$filterCol.filter((filterColumn) => {
268
+ if (!filterColumn.filters && !filterColumn.colorFilters && !filterColumn.customFilters) return false;
269
+ return true;
270
+ }).forEach((filterColumn) => this._setCriteriaWithoutReCalc(filterColumn.colId, filterColumn));
271
+ if (autoFilter.cachedFilteredOut) {
272
+ this._alreadyFilteredOutRows = new Set(autoFilter.cachedFilteredOut);
273
+ this._emit();
274
+ } else if (autoFilter.filterColumns && autoFilter.filterColumns.length > 0) {
275
+ this._reCalcAllColumns();
276
+ this._emit();
277
+ }
278
+ this._emitHasCriteria();
279
+ }
280
+ isRowFiltered(row) {
281
+ return this._alreadyFilteredOutRows.has(row);
282
+ }
283
+ getRange() {
284
+ if (!this._range) throw new Error("[FilterModel] could not get range before a range is set!");
285
+ return this._range;
286
+ }
287
+ /**
288
+ * Get filtered out rows except the specific column. This method is considered as "pure". In
289
+ * another word it would not change `filteredOutRows` on `FilterModel` nor `FilterColumn`.
290
+ * @param col
291
+ */
292
+ getFilteredOutRowsExceptCol(col) {
293
+ return this._getAllFilterColumns(true).filter(([colOffset]) => colOffset !== col).reduce((acc, [, filterColumn]) => {
294
+ const newResult = filterColumn.calc({ getAlreadyFilteredOutRows: () => acc });
295
+ if (newResult) return (0, _univerjs_core.mergeSets)(acc, newResult);
296
+ return acc;
297
+ }, /* @__PURE__ */ new Set());
298
+ }
299
+ /**
300
+ * Set range of the filter model, this would remove some `IFilterColumn`
301
+ * if the new range not overlaps the old range.
302
+ */
303
+ setRange(range) {
304
+ this._range = range;
305
+ this._getAllFilterColumns(true).forEach(([col, filterColumn]) => {
306
+ filterColumn.setRangeAndColumn({
307
+ startRow: range.startRow,
308
+ endRow: range.endRow,
309
+ startColumn: col,
310
+ endColumn: col
311
+ }, col);
312
+ });
313
+ }
314
+ /**
315
+ * Set or remove filter criteria on a specific row.
316
+ */
317
+ setCriteria(col, criteria, reCalc = false) {
318
+ if (!this._range) throw new Error("[FilterModel] could not set criteria before a range is set!");
319
+ if (!criteria) {
320
+ this._removeCriteria(col);
321
+ this._rebuildAlreadyFilteredOutRowsWithCache();
322
+ if (reCalc) this._reCalcAllColumns();
323
+ this._emit();
324
+ this._emitHasCriteria();
325
+ return;
326
+ }
327
+ this._setCriteriaWithoutReCalc(col, criteria);
328
+ if (reCalc) {
329
+ this._rebuildAlreadyFilteredOutRowsWithCache();
330
+ this._getAllFilterColumns().forEach((filterColumn) => filterColumn.__clearCache());
331
+ this._reCalcWithNoCacheColumns();
332
+ this._emit();
333
+ this._emitHasCriteria();
334
+ }
335
+ }
336
+ getAllFilterColumns() {
337
+ return this._getAllFilterColumns(true);
338
+ }
339
+ getFilterColumn(index) {
340
+ var _this$_filterColumnBy;
341
+ return (_this$_filterColumnBy = this._filterColumnByIndex.get(index)) !== null && _this$_filterColumnBy !== void 0 ? _this$_filterColumnBy : null;
342
+ }
343
+ reCalc() {
344
+ this._reCalcAllColumns();
345
+ this._emit();
346
+ }
347
+ _getAllFilterColumns(withCol = false) {
348
+ const columns = Array.from(this._filterColumnByIndex.entries());
349
+ if (withCol) return columns;
350
+ return columns.map(([_, filterColumn]) => filterColumn);
351
+ }
352
+ _reCalcAllColumns() {
353
+ this._alreadyFilteredOutRows = EMPTY();
354
+ this._getAllFilterColumns().forEach((filterColumn) => filterColumn.__clearCache());
355
+ this._reCalcWithNoCacheColumns();
356
+ }
357
+ _setCriteriaWithoutReCalc(col, criteria) {
358
+ const range = this._range;
359
+ if (!range) throw new Error("[FilterModel] could not set criteria before a range is set!");
360
+ const { startColumn, endColumn } = range;
361
+ if (col > endColumn || col < startColumn) throw new Error(`[FilterModel] could not set criteria on column ${col} which is out of range!`);
362
+ let filterColumn;
363
+ if (this._filterColumnByIndex.has(col)) filterColumn = this._filterColumnByIndex.get(col);
364
+ else {
365
+ filterColumn = new FilterColumn(this.unitId, this.subUnitId, this._worksheet, criteria, { getAlreadyFilteredOutRows: () => this._alreadyFilteredOutRows });
366
+ filterColumn.setRangeAndColumn(range, col);
367
+ this._filterColumnByIndex.set(col, filterColumn);
368
+ }
369
+ filterColumn.setCriteria(criteria);
370
+ }
371
+ _removeCriteria(col) {
372
+ const filterColumn = this._filterColumnByIndex.get(col);
373
+ if (filterColumn) {
374
+ filterColumn.dispose();
375
+ this._filterColumnByIndex.delete(col);
376
+ }
377
+ }
378
+ _emit() {
379
+ this._filteredOutRows$.next(this._alreadyFilteredOutRows);
380
+ }
381
+ _emitHasCriteria() {
382
+ this._hasCriteria$.next(this._filterColumnByIndex.size > 0);
383
+ }
384
+ _rebuildAlreadyFilteredOutRowsWithCache() {
385
+ this._alreadyFilteredOutRows = this._getAllFilterColumns().filter((filterColumn) => filterColumn.hasCache()).reduce((acc, filterColumn) => {
386
+ return (0, _univerjs_core.mergeSets)(acc, filterColumn.filteredOutRows);
387
+ }, /* @__PURE__ */ new Set());
388
+ }
389
+ _reCalcWithNoCacheColumns() {
390
+ const noCacheFilteredOutRows = this._getAllFilterColumns().filter((filterColumn) => !filterColumn.hasCache());
391
+ for (const filterColumn of noCacheFilteredOutRows) {
392
+ const filteredRows = filterColumn.reCalc();
393
+ if (filteredRows) this._alreadyFilteredOutRows = (0, _univerjs_core.mergeSets)(this._alreadyFilteredOutRows, filteredRows);
394
+ }
395
+ }
396
+ };
397
+ /**
398
+ * This is the filter criteria on a specific column.
399
+ */
400
+ var FilterColumn = class extends _univerjs_core.Disposable {
401
+ get filteredOutRows() {
402
+ return this._filteredOutRows;
403
+ }
404
+ get filterBy() {
405
+ return this._filterBy;
406
+ }
407
+ constructor(unitId, subUnitId, _worksheet, _criteria, _filterColumnContext) {
408
+ super();
409
+ this.unitId = unitId;
410
+ this.subUnitId = subUnitId;
411
+ this._worksheet = _worksheet;
412
+ this._criteria = _criteria;
413
+ this._filterColumnContext = _filterColumnContext;
414
+ _defineProperty(this, "_filteredOutRows", null);
415
+ _defineProperty(this, "_filterFn", null);
416
+ _defineProperty(this, "_range", null);
417
+ _defineProperty(this, "_column", 0);
418
+ _defineProperty(this, "_filterBy", FilterBy.VALUES);
419
+ }
420
+ dispose() {
421
+ super.dispose();
422
+ this._filteredOutRows = null;
423
+ }
424
+ /**
425
+ * @internal
426
+ */
427
+ __clearCache() {
428
+ this._filteredOutRows = null;
429
+ }
430
+ serialize() {
431
+ if (!this._criteria) throw new Error("[FilterColumn]: could not serialize without a filter column!");
432
+ return _univerjs_core.Tools.deepClone({
433
+ ...this._criteria,
434
+ colId: this._column
435
+ });
436
+ }
437
+ hasCache() {
438
+ return this._filteredOutRows !== null;
439
+ }
440
+ setRangeAndColumn(range, column) {
441
+ this._range = range;
442
+ this._column = column;
443
+ }
444
+ setCriteria(criteria) {
445
+ this._criteria = criteria;
446
+ this._generateFilterFn();
447
+ this._filteredOutRows = null;
448
+ }
449
+ getColumnData() {
450
+ return _univerjs_core.Tools.deepClone(this._criteria);
451
+ }
452
+ /**
453
+ * Trigger new calculation on this `FilterModel` instance.
454
+ *
455
+ * @external DO NOT EVER call this method from `FilterColumn` itself. The whole process heavily relies on
456
+ * `filteredOutByOthers`, and it is more comprehensible if we let `FilterModel` take full control over the process.
457
+ */
458
+ reCalc() {
459
+ this._filteredOutRows = this.calc(this._filterColumnContext);
460
+ return this._filteredOutRows;
461
+ }
462
+ calc(context) {
463
+ if (!this._filterFn) throw new Error("[FilterColumn] cannot calculate without a filter fn!");
464
+ if (!this._range) throw new Error("[FilterColumn] cannot calculate without a range!");
465
+ if (typeof this._column !== "number") throw new TypeError("[FilterColumn] cannot calculate without a column offset!");
466
+ const column = this._column;
467
+ const iterateRange = {
468
+ startColumn: column,
469
+ endColumn: column,
470
+ startRow: this._range.startRow + 1,
471
+ endRow: this._range.endRow
472
+ };
473
+ const filteredOutRows = /* @__PURE__ */ new Set();
474
+ const filteredOutByOthers = context.getAlreadyFilteredOutRows();
475
+ for (const range of this._worksheet.iterateByColumn(iterateRange, false, false)) {
476
+ const { row, rowSpan, col } = range;
477
+ if (filteredOutByOthers.has(row) && (!rowSpan || rowSpan === 1)) continue;
478
+ if (!(this._filterBy === FilterBy.VALUES ? this._filterFn((0, _univerjs_core.extractPureTextFromCell)(this._worksheet.getCell(row, col))) : this._filterBy === FilterBy.COLORS ? this._filterFn(this._worksheet.getComposedCellStyle(row, col)) : this._filterFn(getFilterValueForConditionalFiltering(this._worksheet, row, col)))) {
479
+ filteredOutRows.add(row);
480
+ if (rowSpan) for (let i = 1; i < rowSpan; i++) filteredOutRows.add(row + i);
481
+ }
482
+ }
483
+ return filteredOutRows;
484
+ }
485
+ _generateFilterFn() {
486
+ if (!this._criteria) return;
487
+ this._filterFn = generateFilterFn(this._criteria);
488
+ this._filterBy = this._criteria.filters ? FilterBy.VALUES : this._criteria.colorFilters ? FilterBy.COLORS : FilterBy.CONDITIONS;
489
+ }
490
+ };
491
+ /**
492
+ * This functions take a `IFilterColumn` as input and return a function that can be used to filter rows.
493
+ * @param column
494
+ * @returns the filter function that takes the cell's value and return a boolean.
495
+ */
496
+ function generateFilterFn(column) {
497
+ if (column.filters) return filterByValuesFnFactory(column.filters);
498
+ if (column.colorFilters) return filterByColorsFnFactory(column.colorFilters);
499
+ if (column.customFilters) return customFilterFnFactory(column.customFilters);
500
+ throw new Error("[FilterModel]: other types of filters are not supported yet.");
501
+ }
502
+ function filterByValuesFnFactory(values) {
503
+ const includeBlank = !!values.blank;
504
+ const valuesSet = new Set(values.filters);
505
+ return (value) => {
506
+ if (value === void 0 || value === "") return includeBlank;
507
+ return valuesSet.has(typeof value === "string" ? value : `${value}`);
508
+ };
509
+ }
510
+ function filterByColorsFnFactory(colorFilters) {
511
+ if (colorFilters.cellFillColors) {
512
+ const fillColorsSet = new Set(colorFilters.cellFillColors);
513
+ return (cellStyle) => {
514
+ var _cellStyle$bg;
515
+ if (!cellStyle || !((_cellStyle$bg = cellStyle.bg) === null || _cellStyle$bg === void 0 ? void 0 : _cellStyle$bg.rgb)) {
516
+ if (fillColorsSet.has(null)) return true;
517
+ return false;
518
+ }
519
+ const bg = new _univerjs_core.ColorKit(cellStyle.bg.rgb).toRgbString();
520
+ return fillColorsSet.has(bg);
521
+ };
522
+ }
523
+ if (colorFilters.cellTextColors) {
524
+ const textColorsSet = new Set(colorFilters.cellTextColors);
525
+ return (cellStyle) => {
526
+ var _cellStyle$cl;
527
+ if (!cellStyle || !((_cellStyle$cl = cellStyle.cl) === null || _cellStyle$cl === void 0 ? void 0 : _cellStyle$cl.rgb)) {
528
+ if (textColorsSet.has(_univerjs_engine_render.COLOR_BLACK_RGB)) return true;
529
+ return false;
530
+ }
531
+ const cl = new _univerjs_core.ColorKit(cellStyle.cl.rgb).toRgbString();
532
+ return textColorsSet.has(cl);
533
+ };
534
+ }
535
+ throw new Error("[FilterModel]: color filters are not supported yet.");
536
+ }
537
+ function customFilterFnFactory(customFilters) {
538
+ const customFilterFns = customFilters.customFilters.map((filter) => generateCustomFilterFn(filter));
539
+ if (isCompoundCustomFilter(customFilterFns)) {
540
+ if (customFilters.and) return AND(customFilterFns);
541
+ return OR(customFilterFns);
542
+ }
543
+ return customFilterFns[0];
544
+ }
545
+ function AND(filterFns) {
546
+ const [fn1, fn2] = filterFns;
547
+ return (value) => fn1(value) && fn2(value);
548
+ }
549
+ function OR(filterFns) {
550
+ const [fn1, fn2] = filterFns;
551
+ return (value) => fn1(value) || fn2(value);
552
+ }
553
+ function isCompoundCustomFilter(filter) {
554
+ return filter.length === 2;
555
+ }
556
+ function generateCustomFilterFn(filter) {
557
+ const compare = filter.val;
558
+ if (filter.operator === CustomFilterOperator.NOT_EQUALS) {
559
+ if (!ensureNumeric(compare)) return (value) => notEquals.fn(value, compare);
560
+ }
561
+ if (isNumericFilterFn(filter.operator)) {
562
+ if (!ensureNumeric(compare)) return () => false;
563
+ const customFilterFn = getCustomFilterFn(filter.operator);
564
+ const ensuredNumber = Number(compare);
565
+ return (value) => customFilterFn.fn(value, ensuredNumber);
566
+ }
567
+ const customFilterFn = getCustomFilterFn(filter.operator);
568
+ return (value) => customFilterFn.fn(value, compare);
569
+ }
570
+ function getFilterValueForConditionalFiltering(worksheet, row, col) {
571
+ const interceptedCell = worksheet.getCell(row, col);
572
+ if (!interceptedCell) return null;
573
+ const rawCell = worksheet.getCellRaw(row, col);
574
+ if (interceptedCell && !rawCell) return extractFilterValueFromCell(interceptedCell);
575
+ if (!rawCell) return null;
576
+ if (interceptedCell.t === _univerjs_core.CellValueType.NUMBER && typeof interceptedCell.v === "string") return rawCell.v;
577
+ if (interceptedCell.t === _univerjs_core.CellValueType.NUMBER) return Number(rawCell.v);
578
+ return extractFilterValueFromCell(rawCell);
579
+ }
580
+ function extractFilterValueFromCell(cell) {
581
+ var _cell$p;
582
+ const richTextValue = (_cell$p = cell.p) === null || _cell$p === void 0 || (_cell$p = _cell$p.body) === null || _cell$p === void 0 ? void 0 : _cell$p.dataStream;
583
+ if (richTextValue) return richTextValue.trimEnd();
584
+ const rawValue = cell.v;
585
+ if (typeof rawValue === "string") {
586
+ if (cell.t === _univerjs_core.CellValueType.BOOLEAN) return rawValue.toUpperCase();
587
+ return rawValue;
588
+ }
589
+ if (typeof rawValue === "number") {
590
+ if (cell.t === _univerjs_core.CellValueType.BOOLEAN) return rawValue ? "TRUE" : "FALSE";
591
+ return rawValue;
592
+ }
593
+ if (typeof rawValue === "boolean") return rawValue ? "TRUE" : "FALSE";
594
+ return "";
595
+ }
596
+
597
+ //#endregion
598
+ //#region \0@oxc-project+runtime@0.124.0/helpers/decorateParam.js
599
+ function __decorateParam(paramIndex, decorator) {
600
+ return function(target, key) {
601
+ decorator(target, key, paramIndex);
602
+ };
603
+ }
604
+
605
+ //#endregion
606
+ //#region \0@oxc-project+runtime@0.124.0/helpers/decorate.js
607
+ function __decorate(decorators, target, key, desc) {
608
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
609
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
610
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
611
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
612
+ }
613
+
614
+ //#endregion
615
+ //#region src/services/sheet-filter.service.ts
616
+ const SHEET_FILTER_SNAPSHOT_ID = "SHEET_FILTER_PLUGIN";
617
+ let SheetsFilterService = class SheetsFilterService extends _univerjs_core.Disposable {
618
+ /** The current Workbook's active Worksheet's filter model (if there is one). */
619
+ get activeFilterModel() {
620
+ return this._activeFilterModel$.getValue();
621
+ }
622
+ constructor(_resourcesManagerService, _univerInstanceService, _commandService) {
623
+ super();
624
+ this._resourcesManagerService = _resourcesManagerService;
625
+ this._univerInstanceService = _univerInstanceService;
626
+ this._commandService = _commandService;
627
+ _defineProperty(this, "_filterModels", /* @__PURE__ */ new Map());
628
+ _defineProperty(this, "_loadedUnitId$", new rxjs.BehaviorSubject(null));
629
+ _defineProperty(this, "loadedUnitId$", this._loadedUnitId$.asObservable());
630
+ _defineProperty(this, "_errorMsg$", new rxjs.BehaviorSubject(null));
631
+ _defineProperty(this, "errorMsg$", this._errorMsg$.asObservable());
632
+ _defineProperty(this, "_activeFilterModel$", new rxjs.BehaviorSubject(null));
633
+ _defineProperty(this, "activeFilterModel$", this._activeFilterModel$.asObservable());
634
+ this._initModel();
635
+ this._initActiveFilterModel();
636
+ }
637
+ /**
638
+ *
639
+ * @param unitId
640
+ * @param subUnitId
641
+ */
642
+ ensureFilterModel(unitId, subUnitId) {
643
+ const already = this.getFilterModel(unitId, subUnitId);
644
+ if (already) return already;
645
+ const workbook = this._univerInstanceService.getUniverSheetInstance(unitId);
646
+ if (!workbook) throw new Error(`[SheetsFilterService]: could not create "FilterModel" on a non-existing workbook ${unitId}!`);
647
+ const worksheet = workbook.getSheetBySheetId(subUnitId);
648
+ if (!worksheet) throw new Error(`[SheetsFilterService]: could not create "FilterModel" on a non-existing worksheet ${subUnitId}!`);
649
+ const filterModel = new FilterModel(unitId, subUnitId, worksheet);
650
+ this._cacheFilterModel(unitId, subUnitId, filterModel);
651
+ return filterModel;
652
+ }
653
+ getFilterModel(unitId, subUnitId) {
654
+ var _this$_filterModels$g, _this$_filterModels$g2;
655
+ return (_this$_filterModels$g = (_this$_filterModels$g2 = this._filterModels.get(unitId)) === null || _this$_filterModels$g2 === void 0 ? void 0 : _this$_filterModels$g2.get(subUnitId)) !== null && _this$_filterModels$g !== void 0 ? _this$_filterModels$g : null;
656
+ }
657
+ removeFilterModel(unitId, subUnitId) {
658
+ const already = this.getFilterModel(unitId, subUnitId);
659
+ if (already) {
660
+ already.dispose();
661
+ this._filterModels.get(unitId).delete(subUnitId);
662
+ return true;
663
+ }
664
+ return false;
665
+ }
666
+ setFilterErrorMsg(content) {
667
+ this._errorMsg$.next(content);
668
+ }
669
+ _updateActiveFilterModel() {
670
+ let workbook;
671
+ try {
672
+ workbook = this._univerInstanceService.getCurrentUnitForType(_univerjs_core.UniverInstanceType.UNIVER_SHEET);
673
+ if (!workbook) {
674
+ this._activeFilterModel$.next(null);
675
+ return;
676
+ }
677
+ } catch (err) {
678
+ console.error("[SheetsFilterService]: could not get active workbook!", err);
679
+ return;
680
+ }
681
+ const activeSheet = workbook.getActiveSheet(true);
682
+ if (!activeSheet) {
683
+ this._activeFilterModel$.next(null);
684
+ return;
685
+ }
686
+ const unitId = activeSheet.getUnitId();
687
+ const subUnitId = activeSheet.getSheetId();
688
+ const filterModel = this.getFilterModel(unitId, subUnitId);
689
+ this._activeFilterModel$.next(filterModel);
690
+ }
691
+ _initActiveFilterModel() {
692
+ this.disposeWithMe((0, rxjs.merge)((0, _univerjs_core.fromCallback)(this._commandService.onCommandExecuted.bind(this._commandService)).pipe((0, rxjs.filter)(([command]) => command.type === _univerjs_core.CommandType.MUTATION && FILTER_MUTATIONS.has(command.id))), this._univerInstanceService.getCurrentTypeOfUnit$(_univerjs_core.UniverInstanceType.UNIVER_SHEET).pipe((0, rxjs.switchMap)((workbook) => {
693
+ var _workbook$activeSheet;
694
+ return (_workbook$activeSheet = workbook === null || workbook === void 0 ? void 0 : workbook.activeSheet$) !== null && _workbook$activeSheet !== void 0 ? _workbook$activeSheet : (0, rxjs.of)(null);
695
+ }))).subscribe(() => this._updateActiveFilterModel()));
696
+ }
697
+ _serializeAutoFiltersForUnit(unitId) {
698
+ const allFilterModels = this._filterModels.get(unitId);
699
+ if (!allFilterModels) return "{}";
700
+ const json = {};
701
+ allFilterModels.forEach((model, worksheetId) => {
702
+ json[worksheetId] = model.serialize();
703
+ });
704
+ return JSON.stringify(json);
705
+ }
706
+ _deserializeAutoFiltersForUnit(unitId, json) {
707
+ const workbook = this._univerInstanceService.getUniverSheetInstance(unitId);
708
+ Object.keys(json).forEach((worksheetId) => {
709
+ const autoFilter = json[worksheetId];
710
+ const filterModel = FilterModel.deserialize(unitId, worksheetId, workbook.getSheetBySheetId(worksheetId), autoFilter);
711
+ this._cacheFilterModel(unitId, worksheetId, filterModel);
712
+ });
713
+ }
714
+ dispose() {
715
+ super.dispose();
716
+ this._loadedUnitId$.complete();
717
+ this._errorMsg$.complete();
718
+ this._activeFilterModel$.complete();
719
+ this._filterModels.forEach((allFilterModels) => {
720
+ allFilterModels.forEach((model) => model.dispose());
721
+ allFilterModels.clear();
722
+ });
723
+ this._filterModels.clear();
724
+ }
725
+ _initModel() {
726
+ this._resourcesManagerService.registerPluginResource({
727
+ pluginName: SHEET_FILTER_SNAPSHOT_ID,
728
+ businesses: [_univerjs_core.UniverInstanceType.UNIVER_SHEET],
729
+ toJson: (id) => this._serializeAutoFiltersForUnit(id),
730
+ parseJson: (json) => JSON.parse(json),
731
+ onLoad: (unitId, value) => {
732
+ this._deserializeAutoFiltersForUnit(unitId, value);
733
+ this._loadedUnitId$.next(unitId);
734
+ this._updateActiveFilterModel();
735
+ },
736
+ onUnLoad: (unitId) => {
737
+ const allFilterModels = this._filterModels.get(unitId);
738
+ if (allFilterModels) {
739
+ allFilterModels.forEach((model) => model.dispose());
740
+ this._filterModels.delete(unitId);
741
+ }
742
+ }
743
+ });
744
+ }
745
+ _cacheFilterModel(unitId, subUnitId, filterModel) {
746
+ if (!this._filterModels.has(unitId)) this._filterModels.set(unitId, /* @__PURE__ */ new Map());
747
+ this._filterModels.get(unitId).set(subUnitId, filterModel);
748
+ }
749
+ };
750
+ SheetsFilterService = __decorate([
751
+ __decorateParam(0, _univerjs_core.IResourceManagerService),
752
+ __decorateParam(1, _univerjs_core.IUniverInstanceService),
753
+ __decorateParam(2, _univerjs_core.ICommandService)
754
+ ], SheetsFilterService);
755
+
756
+ //#endregion
757
+ //#region src/commands/mutations/sheets-filter.mutation.ts
758
+ /**
759
+ * A {@link CommandType.MUTATION} to set filter range in a {@link Worksheet}. If no {@link FilterModel} exists,
760
+ * a new `FilterModel` will be created.
761
+ *
762
+ * Since there could only be a filter on a worksheet, when you want to update the range, you
763
+ * don't necessarily need to remove the filter first, you can just execute this mutation.
764
+ */
765
+ const SetSheetsFilterRangeMutation = {
766
+ id: SetSheetsFilterRangeMutationId,
767
+ type: _univerjs_core.CommandType.MUTATION,
768
+ handler: (accessor, params) => {
769
+ const { subUnitId, unitId, range } = params;
770
+ accessor.get(SheetsFilterService).ensureFilterModel(unitId, subUnitId).setRange(range);
771
+ return true;
772
+ }
773
+ };
774
+ /**
775
+ * A {@link CommandType.MUTATION} to set filter criteria of a given column of a {@link FilterModel}.
776
+ */
777
+ const SetSheetsFilterCriteriaMutation = {
778
+ id: SetSheetsFilterCriteriaMutationId,
779
+ type: _univerjs_core.CommandType.MUTATION,
780
+ handler: (accessor, params) => {
781
+ const { subUnitId, unitId, criteria, col, reCalc = true } = params;
782
+ const filterModel = accessor.get(SheetsFilterService).getFilterModel(unitId, subUnitId);
783
+ if (!filterModel) return false;
784
+ filterModel.setCriteria(col, criteria, reCalc);
785
+ return true;
786
+ }
787
+ };
788
+ /**
789
+ * A {@link CommandType.MUTATION} to remove a {@link FilterModel} in a {@link Worksheet}.
790
+ */
791
+ const RemoveSheetsFilterMutation = {
792
+ id: RemoveSheetsFilterMutationId,
793
+ type: _univerjs_core.CommandType.MUTATION,
794
+ handler: (accessor, params) => {
795
+ const { unitId, subUnitId } = params;
796
+ return accessor.get(SheetsFilterService).removeFilterModel(unitId, subUnitId);
797
+ }
798
+ };
799
+ /**
800
+ * A {@link CommandType.MUTATION} to re-calculate a {@link FilterModel}.
801
+ */
802
+ const ReCalcSheetsFilterMutation = {
803
+ id: ReCalcSheetsFilterMutationId,
804
+ type: _univerjs_core.CommandType.MUTATION,
805
+ handler: (accessor, params) => {
806
+ const { unitId, subUnitId } = params;
807
+ const filterModel = accessor.get(SheetsFilterService).getFilterModel(unitId, subUnitId);
808
+ if (!filterModel) return false;
809
+ filterModel.reCalc();
810
+ return true;
811
+ }
812
+ };
813
+
814
+ //#endregion
815
+ //#region src/commands/commands/sheets-filter.command.ts
816
+ /**
817
+ * A {@link CommandType.COMMAND} to set filter range in a Worksheet. Its params {@link ISetSheetFilterRangeCommandParams}
818
+ * is required. If the {@link FilterModel} does not exist, it will be created.
819
+ */
820
+ const SetSheetFilterRangeCommand = {
821
+ id: "sheet.command.set-filter-range",
822
+ type: _univerjs_core.CommandType.COMMAND,
823
+ handler: (accessor, params) => {
824
+ const sheetsFilterService = accessor.get(SheetsFilterService);
825
+ const commandService = accessor.get(_univerjs_core.ICommandService);
826
+ const undoRedoService = accessor.get(_univerjs_core.IUndoRedoService);
827
+ const instanceSrv = accessor.get(_univerjs_core.IUniverInstanceService);
828
+ const { unitId, subUnitId, range } = params;
829
+ if (!(0, _univerjs_sheets.getSheetCommandTarget)(instanceSrv, params)) return false;
830
+ if (sheetsFilterService.getFilterModel(unitId, subUnitId)) return false;
831
+ if (range.endRow === range.startRow) {
832
+ const errorService = accessor.get(_univerjs_core.ErrorService);
833
+ const localeService = accessor.get(_univerjs_core.LocaleService);
834
+ errorService.emit(localeService.t("sheets-filter.command.not-valid-filter-range"));
835
+ return false;
836
+ }
837
+ const redoMutation = {
838
+ id: SetSheetsFilterRangeMutation.id,
839
+ params: {
840
+ unitId,
841
+ subUnitId,
842
+ range
843
+ }
844
+ };
845
+ const result = commandService.syncExecuteCommand(redoMutation.id, redoMutation.params);
846
+ if (result) undoRedoService.pushUndoRedo({
847
+ unitID: unitId,
848
+ undoMutations: [{
849
+ id: RemoveSheetsFilterMutation.id,
850
+ params: {
851
+ unitId,
852
+ subUnitId
853
+ }
854
+ }],
855
+ redoMutations: [redoMutation]
856
+ });
857
+ return result;
858
+ }
859
+ };
860
+ /**
861
+ * A {@link CommandType.COMMAND} to remove filter in a Worksheet. Its params {@link ISheetCommandSharedParams} is
862
+ * required. If the {@link FilterModel} does not exist, it will fail to execute.
863
+ */
864
+ const RemoveSheetFilterCommand = {
865
+ id: "sheet.command.remove-sheet-filter",
866
+ type: _univerjs_core.CommandType.COMMAND,
867
+ handler: (accessor, params) => {
868
+ const target = (0, _univerjs_sheets.getSheetCommandTarget)(accessor.get(_univerjs_core.IUniverInstanceService), params);
869
+ if (!target) return false;
870
+ const sheetsFilterService = accessor.get(SheetsFilterService);
871
+ const { unitId, subUnitId } = target;
872
+ const filterModel = sheetsFilterService.getFilterModel(unitId, subUnitId);
873
+ if (!filterModel) return false;
874
+ const filterRange = filterModel.getRange();
875
+ if (!filterRange) return false;
876
+ const commandService = accessor.get(_univerjs_core.ICommandService);
877
+ const undoRedoService = accessor.get(_univerjs_core.IUndoRedoService);
878
+ const undoMutations = destructFilterModel(unitId, subUnitId, filterModel.serialize());
879
+ const result = commandService.syncExecuteCommand(RemoveSheetsFilterMutation.id, {
880
+ unitId,
881
+ subUnitId
882
+ });
883
+ if (result) {
884
+ undoRedoService.pushUndoRedo({
885
+ unitID: unitId,
886
+ undoMutations,
887
+ redoMutations: [{
888
+ id: RemoveSheetsFilterMutation.id,
889
+ params: {
890
+ unitId,
891
+ subUnitId
892
+ }
893
+ }]
894
+ });
895
+ commandService.executeCommand(_univerjs_sheets.MarkDirtyFilterChangeMutation.id, {
896
+ unitId,
897
+ subUnitId,
898
+ filterRange
899
+ });
900
+ }
901
+ return result;
902
+ }
903
+ };
904
+ /**
905
+ * A {@link CommandType.COMMAND} to toggle filter in the current {@link Worksheet}.
906
+ */
907
+ const SmartToggleSheetsFilterCommand = {
908
+ id: "sheet.command.smart-toggle-filter",
909
+ type: _univerjs_core.CommandType.COMMAND,
910
+ handler: async (accessor) => {
911
+ const univerInstanceService = accessor.get(_univerjs_core.IUniverInstanceService);
912
+ const sheetsFilterService = accessor.get(SheetsFilterService);
913
+ const commandService = accessor.get(_univerjs_core.ICommandService);
914
+ const currentWorkbook = univerInstanceService.getCurrentUnitForType(_univerjs_core.UniverInstanceType.UNIVER_SHEET);
915
+ const currentWorksheet = currentWorkbook === null || currentWorkbook === void 0 ? void 0 : currentWorkbook.getActiveSheet();
916
+ if (!currentWorksheet || !currentWorkbook) return false;
917
+ const unitId = currentWorkbook.getUnitId();
918
+ const subUnitId = currentWorksheet.getSheetId();
919
+ if (sheetsFilterService.getFilterModel(unitId, subUnitId)) return commandService.executeCommand(RemoveSheetFilterCommand.id, {
920
+ unitId,
921
+ subUnitId
922
+ });
923
+ const lastSelection = accessor.get(_univerjs_sheets.SheetsSelectionsService).getCurrentLastSelection();
924
+ if (!lastSelection) return false;
925
+ const startRange = lastSelection.range;
926
+ const targetFilterRange = (0, _univerjs_sheets.isSingleCellSelection)(lastSelection) ? (0, _univerjs_sheets.expandToContinuousRange)(startRange, {
927
+ left: true,
928
+ right: true,
929
+ up: true,
930
+ down: true
931
+ }, currentWorksheet) : startRange.startRow === startRange.endRow ? (0, _univerjs_sheets.expandToContinuousRange)(startRange, { down: true }, currentWorksheet) : startRange;
932
+ return commandService.executeCommand(SetSheetFilterRangeCommand.id, {
933
+ unitId,
934
+ subUnitId,
935
+ range: targetFilterRange
936
+ });
937
+ }
938
+ };
939
+ /**
940
+ * A {@link CommandType.COMMAND} to set filter criteria to a column in the targeting {@link FilterModel}. Its params
941
+ * {@link ISetSheetsFilterCriteriaCommandParams} is required.
942
+ */
943
+ const SetSheetsFilterCriteriaCommand = {
944
+ id: "sheet.command.set-filter-criteria",
945
+ type: _univerjs_core.CommandType.COMMAND,
946
+ handler: (accessor, params) => {
947
+ const target = (0, _univerjs_sheets.getSheetCommandTarget)(accessor.get(_univerjs_core.IUniverInstanceService), params);
948
+ if (!target) return false;
949
+ const sheetsFilterService = accessor.get(SheetsFilterService);
950
+ const { unitId, subUnitId } = target;
951
+ const filterModel = sheetsFilterService.getFilterModel(unitId, subUnitId);
952
+ if (!filterModel) return false;
953
+ const { col, criteria } = params;
954
+ const filterRange = filterModel.getRange();
955
+ if (!filterRange || col < filterRange.startColumn || col > filterRange.endColumn) return false;
956
+ const commandService = accessor.get(_univerjs_core.ICommandService);
957
+ const undoRedoService = accessor.get(_univerjs_core.IUndoRedoService);
958
+ const undoMutation = destructFilterColumn(unitId, subUnitId, col, filterModel.getFilterColumn(col));
959
+ const redoMutation = {
960
+ id: SetSheetsFilterCriteriaMutation.id,
961
+ params: {
962
+ unitId,
963
+ subUnitId,
964
+ col,
965
+ criteria
966
+ }
967
+ };
968
+ const result = commandService.syncExecuteCommand(redoMutation.id, redoMutation.params);
969
+ if (result) {
970
+ undoRedoService.pushUndoRedo({
971
+ unitID: unitId,
972
+ undoMutations: [undoMutation],
973
+ redoMutations: [redoMutation]
974
+ });
975
+ commandService.executeCommand(_univerjs_sheets.MarkDirtyFilterChangeMutation.id, {
976
+ unitId,
977
+ subUnitId,
978
+ filterRange
979
+ });
980
+ }
981
+ return result;
982
+ }
983
+ };
984
+ /**
985
+ * A {@link CommandType.COMMAND} to clear all filter criteria in the targeting {@link FilterModel}. Its params
986
+ * {@link ISheetCommandSharedParams} is required.
987
+ */
988
+ const ClearSheetsFilterCriteriaCommand = {
989
+ id: "sheet.command.clear-filter-criteria",
990
+ type: _univerjs_core.CommandType.COMMAND,
991
+ handler: (accessor, params) => {
992
+ const target = (0, _univerjs_sheets.getSheetCommandTarget)(accessor.get(_univerjs_core.IUniverInstanceService), params);
993
+ if (!target) return false;
994
+ const sheetsFilterService = accessor.get(SheetsFilterService);
995
+ const { unitId, subUnitId } = target;
996
+ const filterModel = sheetsFilterService.getFilterModel(unitId, subUnitId);
997
+ if (!filterModel) return false;
998
+ const filterRange = filterModel.getRange();
999
+ if (!filterRange) return false;
1000
+ const undoRedoService = accessor.get(_univerjs_core.IUndoRedoService);
1001
+ const commandService = accessor.get(_univerjs_core.ICommandService);
1002
+ const autoFilter = filterModel.serialize();
1003
+ const undoMutations = destructFilterCriteria(unitId, subUnitId, autoFilter);
1004
+ const redoMutations = generateRemoveCriteriaMutations(unitId, subUnitId, autoFilter);
1005
+ if ((0, _univerjs_core.sequenceExecute)(redoMutations, commandService).result) {
1006
+ undoRedoService.pushUndoRedo({
1007
+ unitID: unitId,
1008
+ undoMutations,
1009
+ redoMutations
1010
+ });
1011
+ commandService.executeCommand(_univerjs_sheets.MarkDirtyFilterChangeMutation.id, {
1012
+ unitId,
1013
+ subUnitId,
1014
+ filterRange
1015
+ });
1016
+ return true;
1017
+ }
1018
+ return false;
1019
+ }
1020
+ };
1021
+ /**
1022
+ * A {@link CommandType.COMMAND} forcing the currently active {@link FilterModel} to re-calculate all filter criteria.
1023
+ * Its params {@link ISheetCommandSharedParams} is required.
1024
+ */
1025
+ const ReCalcSheetsFilterCommand = {
1026
+ id: "sheet.command.re-calc-filter",
1027
+ type: _univerjs_core.CommandType.COMMAND,
1028
+ handler: (accessor, params) => {
1029
+ const sheetsFilterService = accessor.get(SheetsFilterService);
1030
+ const commandService = accessor.get(_univerjs_core.ICommandService);
1031
+ const commandTarget = (0, _univerjs_sheets.getSheetCommandTarget)(accessor.get(_univerjs_core.IUniverInstanceService), params);
1032
+ if (!commandTarget) return false;
1033
+ const { unitId, subUnitId } = commandTarget;
1034
+ if (!sheetsFilterService.getFilterModel(commandTarget.unitId, commandTarget.subUnitId)) return false;
1035
+ return commandService.executeCommand(ReCalcSheetsFilterMutation.id, {
1036
+ unitId,
1037
+ subUnitId
1038
+ });
1039
+ }
1040
+ };
1041
+ /**
1042
+ * Destruct a `FilterModel` to a list of mutations.
1043
+ * @param {string} unitId - the unit id of the Workbook
1044
+ * @param {string} subUnitId - the sub unit id of the Worksheet
1045
+ * @param {IAutoFilter} autoFilter - the to be destructed FilterModel
1046
+ * @returns a list of mutations those can be used to reconstruct the FilterModel
1047
+ */
1048
+ function destructFilterModel(unitId, subUnitId, autoFilter) {
1049
+ const mutations = [];
1050
+ const setFilterMutation = {
1051
+ id: SetSheetsFilterRangeMutation.id,
1052
+ params: {
1053
+ unitId,
1054
+ subUnitId,
1055
+ range: autoFilter.ref
1056
+ }
1057
+ };
1058
+ mutations.push(setFilterMutation);
1059
+ destructFilterCriteria(unitId, subUnitId, autoFilter).forEach((m) => mutations.push(m));
1060
+ return mutations;
1061
+ }
1062
+ /**
1063
+ * Transform a {@link FilterModel} to a list of mutations to set the filter criteria.
1064
+ * @param unitId - the unit id of the {@link Workbook}
1065
+ * @param subUnitId - the sub unit id of the {@link Worksheet}
1066
+ * @param autoFilter - the to be destructed {@link FilterModel}
1067
+ * @returns {IMutationInfo<ISetSheetsFilterCriteriaMutationParams>} a list of mutations those can be used to
1068
+ * reconstruct the {@link FilterModel}
1069
+ */
1070
+ function destructFilterCriteria(unitId, subUnitId, autoFilter) {
1071
+ var _autoFilter$filterCol;
1072
+ const mutations = [];
1073
+ (_autoFilter$filterCol = autoFilter.filterColumns) === null || _autoFilter$filterCol === void 0 || _autoFilter$filterCol.forEach((filterColumn) => {
1074
+ const setFilterCriteriaMutation = {
1075
+ id: SetSheetsFilterCriteriaMutation.id,
1076
+ params: {
1077
+ unitId,
1078
+ subUnitId,
1079
+ col: filterColumn.colId,
1080
+ criteria: filterColumn
1081
+ }
1082
+ };
1083
+ mutations.push(setFilterCriteriaMutation);
1084
+ });
1085
+ return mutations;
1086
+ }
1087
+ /** Generate mutations to remove all criteria on a `FilterModel` */
1088
+ function generateRemoveCriteriaMutations(unitId, subUnitId, autoFilter) {
1089
+ var _autoFilter$filterCol2;
1090
+ const mutations = [];
1091
+ (_autoFilter$filterCol2 = autoFilter.filterColumns) === null || _autoFilter$filterCol2 === void 0 || _autoFilter$filterCol2.forEach((filterColumn) => {
1092
+ const removeFilterCriteriaMutation = {
1093
+ id: SetSheetsFilterCriteriaMutation.id,
1094
+ params: {
1095
+ unitId,
1096
+ subUnitId,
1097
+ col: filterColumn.colId,
1098
+ criteria: null
1099
+ }
1100
+ };
1101
+ mutations.push(removeFilterCriteriaMutation);
1102
+ });
1103
+ return mutations;
1104
+ }
1105
+ /**
1106
+ * Prepare the undo mutation, it should rollback to the old criteria if there's already a `FilterColumn`,
1107
+ * or remove the filter criteria when there is no `FilterColumn`.
1108
+ * @param {string} unitId
1109
+ * @param {string} subUnitId
1110
+ * @param {number} colId
1111
+ * @param {Nullable<FilterColumn>} filterColumn
1112
+ * @returns {IMutationInfo<ISetSheetsFilterCriteriaMutationParams>} the undo mutation
1113
+ */
1114
+ function destructFilterColumn(unitId, subUnitId, colId, filterColumn) {
1115
+ if (!filterColumn) return {
1116
+ id: SetSheetsFilterCriteriaMutation.id,
1117
+ params: {
1118
+ unitId,
1119
+ subUnitId,
1120
+ col: colId,
1121
+ criteria: null
1122
+ }
1123
+ };
1124
+ const serialize = filterColumn.serialize();
1125
+ return {
1126
+ id: SetSheetsFilterCriteriaMutation.id,
1127
+ params: {
1128
+ unitId,
1129
+ subUnitId,
1130
+ col: colId,
1131
+ criteria: serialize
1132
+ }
1133
+ };
1134
+ }
1135
+
1136
+ //#endregion
1137
+ //#region src/config/config.ts
1138
+ /**
1139
+ * Copyright 2023-present DreamNum Co., Ltd.
1140
+ *
1141
+ * Licensed under the Apache License, Version 2.0 (the "License");
1142
+ * you may not use this file except in compliance with the License.
1143
+ * You may obtain a copy of the License at
1144
+ *
1145
+ * http://www.apache.org/licenses/LICENSE-2.0
1146
+ *
1147
+ * Unless required by applicable law or agreed to in writing, software
1148
+ * distributed under the License is distributed on an "AS IS" BASIS,
1149
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1150
+ * See the License for the specific language governing permissions and
1151
+ * limitations under the License.
1152
+ */
1153
+ const SHEETS_FILTER_PLUGIN_CONFIG_KEY = "sheets-filter.config";
1154
+ const configSymbol = Symbol(SHEETS_FILTER_PLUGIN_CONFIG_KEY);
1155
+ const defaultPluginConfig = {};
1156
+
1157
+ //#endregion
1158
+ //#region src/utils.ts
1159
+ function objectsShaker(target, isEqual) {
1160
+ for (let i = 0; i < target.length; i++) {
1161
+ let cur = i;
1162
+ if (target[i]) {
1163
+ for (let j = i + 1; j < target.length; j++) if (target[cur] && target[j] && isEqual(target[cur], target[j])) {
1164
+ target[cur] = null;
1165
+ cur = j;
1166
+ }
1167
+ }
1168
+ }
1169
+ return target.filter((o) => o !== null);
1170
+ }
1171
+ function mergeSetFilterCriteria(mutations) {
1172
+ return objectsShaker(mutations, (o1, o2) => o1.id === SetSheetsFilterCriteriaMutation.id && o2.id === SetSheetsFilterCriteriaMutation.id && o1.params.unitId === o2.params.unitId && o1.params.subUnitId === o2.params.subUnitId && o1.params.col === o2.params.col);
1173
+ }
1174
+
1175
+ //#endregion
1176
+ //#region src/controllers/sheets-filter.controller.ts
1177
+ let SheetsFilterController = class SheetsFilterController extends _univerjs_core.Disposable {
1178
+ constructor(_commandService, _sheetInterceptorService, _sheetsFilterService, _univerInstanceService, _refRangeService, _dataSyncPrimaryController, _zebraCrossingCacheController) {
1179
+ super();
1180
+ this._commandService = _commandService;
1181
+ this._sheetInterceptorService = _sheetInterceptorService;
1182
+ this._sheetsFilterService = _sheetsFilterService;
1183
+ this._univerInstanceService = _univerInstanceService;
1184
+ this._refRangeService = _refRangeService;
1185
+ this._dataSyncPrimaryController = _dataSyncPrimaryController;
1186
+ this._zebraCrossingCacheController = _zebraCrossingCacheController;
1187
+ _defineProperty(this, "_disposableCollection", new _univerjs_core.DisposableCollection());
1188
+ this._initCommands();
1189
+ this._initRowFilteredInterceptor();
1190
+ this._initInterceptors();
1191
+ this._commandExecutedListener();
1192
+ this._initErrorHandling();
1193
+ this._initZebraCrossingCacheListener();
1194
+ }
1195
+ _initZebraCrossingCacheListener() {
1196
+ this.disposeWithMe(this._sheetsFilterService.activeFilterModel$.subscribe((filterModel) => {
1197
+ if (!filterModel) return;
1198
+ this.disposeWithMe(filterModel.filteredOutRows$.subscribe(() => {
1199
+ this._zebraCrossingCacheController.updateZebraCrossingCache(filterModel.unitId, filterModel.subUnitId);
1200
+ }));
1201
+ }));
1202
+ }
1203
+ _initCommands() {
1204
+ [
1205
+ SetSheetsFilterCriteriaMutation,
1206
+ SetSheetsFilterRangeMutation,
1207
+ ReCalcSheetsFilterMutation,
1208
+ RemoveSheetsFilterMutation
1209
+ ].forEach((command) => {
1210
+ var _this$_dataSyncPrimar;
1211
+ this.disposeWithMe(this._commandService.registerCommand(command));
1212
+ (_this$_dataSyncPrimar = this._dataSyncPrimaryController) === null || _this$_dataSyncPrimar === void 0 || _this$_dataSyncPrimar.registerSyncingMutations(command);
1213
+ });
1214
+ }
1215
+ _initInterceptors() {
1216
+ this.disposeWithMe(this._sheetInterceptorService.interceptCommand({ getMutations: (command) => this._getUpdateFilter(command) }));
1217
+ this.disposeWithMe(this._commandService.onCommandExecuted((commandInfo) => {
1218
+ if (commandInfo.id === _univerjs_sheets.SetWorksheetActiveOperation.id) {
1219
+ const params = commandInfo.params;
1220
+ const sheetId = params.subUnitId;
1221
+ const unitId = params.unitId;
1222
+ if (!sheetId || !unitId) return;
1223
+ this._registerRefRange(unitId, sheetId);
1224
+ }
1225
+ if (commandInfo.id === SetSheetsFilterRangeMutation.id) {
1226
+ const params = commandInfo.params;
1227
+ const sheetId = params.subUnitId;
1228
+ const unitId = params.unitId;
1229
+ if (!sheetId || !unitId) return;
1230
+ this._registerRefRange(params.unitId, params.subUnitId);
1231
+ }
1232
+ }));
1233
+ this.disposeWithMe(this._sheetsFilterService.loadedUnitId$.subscribe((unitId) => {
1234
+ if (unitId) {
1235
+ const workbook = this._univerInstanceService.getUniverSheetInstance(unitId);
1236
+ const sheet = workbook === null || workbook === void 0 ? void 0 : workbook.getActiveSheet();
1237
+ if (sheet) this._registerRefRange(unitId, sheet.getSheetId());
1238
+ }
1239
+ }));
1240
+ }
1241
+ _registerRefRange(unitId, subUnitId) {
1242
+ var _this$_sheetsFilterSe;
1243
+ this._disposableCollection.dispose();
1244
+ const workbook = this._univerInstanceService.getUniverSheetInstance(unitId);
1245
+ const workSheet = workbook === null || workbook === void 0 ? void 0 : workbook.getSheetBySheetId(subUnitId);
1246
+ if (!workbook || !workSheet) return;
1247
+ const range = (_this$_sheetsFilterSe = this._sheetsFilterService.getFilterModel(unitId, subUnitId)) === null || _this$_sheetsFilterSe === void 0 ? void 0 : _this$_sheetsFilterSe.getRange();
1248
+ const handler = (config) => {
1249
+ switch (config.id) {
1250
+ case _univerjs_sheets.InsertRowCommand.id: {
1251
+ const params = config.params;
1252
+ const _unitId = params.unitId || unitId;
1253
+ const _subUnitId = params.subUnitId || subUnitId;
1254
+ return this._handleInsertRowCommand(params, _unitId, _subUnitId);
1255
+ }
1256
+ case _univerjs_sheets.InsertColCommand.id: {
1257
+ const params = config.params;
1258
+ const _unitId = params.unitId || unitId;
1259
+ const _subUnitId = params.subUnitId || subUnitId;
1260
+ return this.handleInsertColCommand(params.range, _unitId, _subUnitId);
1261
+ }
1262
+ case _univerjs_sheets.RemoveColCommand.id: {
1263
+ const params = config.params;
1264
+ return this.handleRemoveColCommand(params.range, unitId, subUnitId);
1265
+ }
1266
+ case _univerjs_sheets.RemoveRowCommand.id: {
1267
+ const params = config.params;
1268
+ return this._handleRemoveRowCommand(params, unitId, subUnitId);
1269
+ }
1270
+ case _univerjs_sheets.EffectRefRangId.MoveColsCommandId: {
1271
+ const params = config.params;
1272
+ return this.handleMoveColsCommand({
1273
+ fromRange: params.fromRange,
1274
+ toRange: params.toRange
1275
+ }, unitId, subUnitId);
1276
+ }
1277
+ case _univerjs_sheets.EffectRefRangId.MoveRowsCommandId: {
1278
+ const params = config.params;
1279
+ return this._handleMoveRowsCommand(params, unitId, subUnitId);
1280
+ }
1281
+ case _univerjs_sheets.MoveRangeCommand.id: {
1282
+ const params = config.params;
1283
+ return this._handleMoveRangeCommand(params, unitId, subUnitId);
1284
+ }
1285
+ }
1286
+ return {
1287
+ redos: [],
1288
+ undos: []
1289
+ };
1290
+ };
1291
+ if (range) this._disposableCollection.add(this._refRangeService.registerRefRange(range, handler, unitId, subUnitId));
1292
+ }
1293
+ _getUpdateFilter(command) {
1294
+ const { id } = command;
1295
+ switch (id) {
1296
+ case _univerjs_sheets.RemoveSheetCommand.id: {
1297
+ const params = command.params;
1298
+ return this._handleRemoveSheetCommand(params, params.unitId, params.subUnitId);
1299
+ }
1300
+ case _univerjs_sheets.CopySheetCommand.id: {
1301
+ const { targetSubUnitId, unitId, subUnitId } = command.params;
1302
+ if (!unitId || !subUnitId || !targetSubUnitId) return this._handleNull();
1303
+ return this._handleCopySheetCommand(unitId, subUnitId, targetSubUnitId);
1304
+ }
1305
+ }
1306
+ return {
1307
+ redos: [],
1308
+ undos: []
1309
+ };
1310
+ }
1311
+ handleInsertColCommand(range, unitId, subUnitId) {
1312
+ var _filterModel$getRange;
1313
+ const filterModel = this._sheetsFilterService.getFilterModel(unitId, subUnitId);
1314
+ const filterRange = (_filterModel$getRange = filterModel === null || filterModel === void 0 ? void 0 : filterModel.getRange()) !== null && _filterModel$getRange !== void 0 ? _filterModel$getRange : null;
1315
+ if (!filterModel || !filterRange) return this._handleNull();
1316
+ const { startColumn, endColumn } = filterRange;
1317
+ const { startColumn: insertStartColumn, endColumn: insertEndColumn } = range;
1318
+ const count = insertEndColumn - insertStartColumn + 1;
1319
+ if (insertEndColumn > endColumn) return this._handleNull();
1320
+ const redos = [];
1321
+ const undos = [];
1322
+ const anchor = insertStartColumn;
1323
+ const setFilterRangeMutationParams = {
1324
+ unitId,
1325
+ subUnitId,
1326
+ range: {
1327
+ ...filterRange,
1328
+ startColumn: insertStartColumn <= startColumn ? startColumn + count : startColumn,
1329
+ endColumn: endColumn + count
1330
+ }
1331
+ };
1332
+ const undoSetFilterRangeMutationParams = {
1333
+ unitId,
1334
+ subUnitId,
1335
+ range: filterRange
1336
+ };
1337
+ redos.push({
1338
+ id: SetSheetsFilterRangeMutation.id,
1339
+ params: setFilterRangeMutationParams
1340
+ });
1341
+ undos.push({
1342
+ id: SetSheetsFilterRangeMutation.id,
1343
+ params: undoSetFilterRangeMutationParams
1344
+ });
1345
+ const effected = filterModel.getAllFilterColumns().filter((column) => column[0] >= anchor);
1346
+ if (effected.length !== 0) {
1347
+ const { newRange, oldRange } = this._moveCriteria(unitId, subUnitId, effected, count);
1348
+ redos.push(...oldRange.redos, ...newRange.redos);
1349
+ undos.push(...newRange.undos, ...oldRange.undos);
1350
+ }
1351
+ return {
1352
+ redos: mergeSetFilterCriteria(redos),
1353
+ undos: mergeSetFilterCriteria(undos)
1354
+ };
1355
+ }
1356
+ _handleInsertRowCommand(config, unitId, subUnitId) {
1357
+ var _filterModel$getRange2;
1358
+ const filterModel = this._sheetsFilterService.getFilterModel(unitId, subUnitId);
1359
+ const filterRange = (_filterModel$getRange2 = filterModel === null || filterModel === void 0 ? void 0 : filterModel.getRange()) !== null && _filterModel$getRange2 !== void 0 ? _filterModel$getRange2 : null;
1360
+ if (!filterModel || !filterRange) return this._handleNull();
1361
+ const { startRow, endRow } = filterRange;
1362
+ const { startRow: insertStartRow, endRow: insertEndRow } = config.range;
1363
+ const rowCount = insertEndRow - insertStartRow + 1;
1364
+ if (insertEndRow > endRow) return this._handleNull();
1365
+ const redos = [];
1366
+ const undos = [];
1367
+ const setFilterRangeParams = {
1368
+ unitId,
1369
+ subUnitId,
1370
+ range: {
1371
+ ...filterRange,
1372
+ startRow: insertStartRow <= startRow ? startRow + rowCount : startRow,
1373
+ endRow: endRow + rowCount
1374
+ }
1375
+ };
1376
+ const undoSetFilterRangeMutationParams = {
1377
+ unitId,
1378
+ subUnitId,
1379
+ range: filterRange
1380
+ };
1381
+ redos.push({
1382
+ id: SetSheetsFilterRangeMutation.id,
1383
+ params: setFilterRangeParams
1384
+ });
1385
+ undos.push({
1386
+ id: SetSheetsFilterRangeMutation.id,
1387
+ params: undoSetFilterRangeMutationParams
1388
+ });
1389
+ return {
1390
+ redos: mergeSetFilterCriteria(redos),
1391
+ undos: mergeSetFilterCriteria(undos)
1392
+ };
1393
+ }
1394
+ handleRemoveColCommand(range, unitId, subUnitId) {
1395
+ var _filterModel$getRange3;
1396
+ const filterModel = this._sheetsFilterService.getFilterModel(unitId, subUnitId);
1397
+ const filterRange = (_filterModel$getRange3 = filterModel === null || filterModel === void 0 ? void 0 : filterModel.getRange()) !== null && _filterModel$getRange3 !== void 0 ? _filterModel$getRange3 : null;
1398
+ if (!filterModel || !filterRange) return this._handleNull();
1399
+ const { startColumn, endColumn } = filterRange;
1400
+ const { startColumn: removeStartColumn, endColumn: removeEndColumn } = range;
1401
+ if (removeStartColumn > endColumn) return this._handleNull();
1402
+ const redos = [];
1403
+ const undos = [];
1404
+ const rangeRemoveCount = removeEndColumn < startColumn ? 0 : Math.min(removeEndColumn, endColumn) - Math.max(removeStartColumn, startColumn) + 1;
1405
+ const removeCount = removeEndColumn - removeStartColumn + 1;
1406
+ const filterColumn = filterModel.getAllFilterColumns();
1407
+ filterColumn.forEach((column) => {
1408
+ const [col, filter] = column;
1409
+ if (col <= removeEndColumn && col >= removeStartColumn) {
1410
+ redos.push({
1411
+ id: SetSheetsFilterCriteriaMutation.id,
1412
+ params: {
1413
+ unitId,
1414
+ subUnitId,
1415
+ col,
1416
+ criteria: null
1417
+ }
1418
+ });
1419
+ undos.push({
1420
+ id: SetSheetsFilterCriteriaMutation.id,
1421
+ params: {
1422
+ unitId,
1423
+ subUnitId,
1424
+ col,
1425
+ criteria: {
1426
+ ...filter.serialize(),
1427
+ colId: col
1428
+ }
1429
+ }
1430
+ });
1431
+ }
1432
+ });
1433
+ const shifted = filterColumn.filter((column) => {
1434
+ const [col, _] = column;
1435
+ return col > removeEndColumn;
1436
+ });
1437
+ let newRangeCriteria = {
1438
+ undos: [],
1439
+ redos: []
1440
+ };
1441
+ if (shifted.length > 0) {
1442
+ const { oldRange, newRange } = this._moveCriteria(unitId, subUnitId, shifted, -removeCount);
1443
+ newRangeCriteria = newRange;
1444
+ redos.push(...oldRange.redos);
1445
+ undos.unshift(...oldRange.undos);
1446
+ }
1447
+ if (rangeRemoveCount === endColumn - startColumn + 1) {
1448
+ const removeFilterRangeMutationParams = {
1449
+ unitId,
1450
+ subUnitId
1451
+ };
1452
+ redos.push({
1453
+ id: RemoveSheetsFilterMutation.id,
1454
+ params: removeFilterRangeMutationParams
1455
+ });
1456
+ undos.unshift({
1457
+ id: SetSheetsFilterRangeMutation.id,
1458
+ params: {
1459
+ range: filterRange,
1460
+ unitId,
1461
+ subUnitId
1462
+ }
1463
+ });
1464
+ } else {
1465
+ const newStartColumn = startColumn <= removeStartColumn ? startColumn : rangeRemoveCount === 0 ? startColumn - removeCount : removeStartColumn;
1466
+ const newEndColumn = startColumn <= removeStartColumn ? endColumn - rangeRemoveCount : endColumn - removeCount;
1467
+ const setFilterRangeMutationParams = {
1468
+ unitId,
1469
+ subUnitId,
1470
+ range: {
1471
+ ...filterRange,
1472
+ startColumn: newStartColumn,
1473
+ endColumn: newEndColumn
1474
+ }
1475
+ };
1476
+ redos.push({
1477
+ id: SetSheetsFilterRangeMutation.id,
1478
+ params: setFilterRangeMutationParams
1479
+ });
1480
+ undos.unshift({
1481
+ id: SetSheetsFilterRangeMutation.id,
1482
+ params: {
1483
+ range: filterRange,
1484
+ unitId,
1485
+ subUnitId
1486
+ }
1487
+ });
1488
+ redos.push(...newRangeCriteria.redos);
1489
+ undos.unshift(...newRangeCriteria.undos);
1490
+ }
1491
+ return {
1492
+ undos,
1493
+ redos
1494
+ };
1495
+ }
1496
+ _handleRemoveRowCommand(config, unitId, subUnitId) {
1497
+ const filterModel = this._sheetsFilterService.getFilterModel(unitId, subUnitId);
1498
+ if (!filterModel) return this._handleNull();
1499
+ const filterRange = filterModel.getRange();
1500
+ const { startRow, endRow } = filterRange;
1501
+ const { startRow: removeStartRow, endRow: removeEndRow } = config.range;
1502
+ if (removeStartRow > endRow) return this._handleNull();
1503
+ if (removeEndRow < startRow) return {
1504
+ undos: [{
1505
+ id: SetSheetsFilterRangeMutation.id,
1506
+ params: {
1507
+ range: filterRange,
1508
+ unitId,
1509
+ subUnitId
1510
+ }
1511
+ }],
1512
+ redos: [{
1513
+ id: SetSheetsFilterRangeMutation.id,
1514
+ params: {
1515
+ range: {
1516
+ ...filterRange,
1517
+ startRow: startRow - (removeEndRow - removeStartRow + 1),
1518
+ endRow: endRow - (removeEndRow - removeStartRow + 1)
1519
+ },
1520
+ unitId,
1521
+ subUnitId
1522
+ }
1523
+ }]
1524
+ };
1525
+ const redos = [];
1526
+ const undos = [];
1527
+ const filterColumn = filterModel.getAllFilterColumns();
1528
+ const filterHeaderIsRemoved = startRow <= removeEndRow && startRow >= removeStartRow;
1529
+ undos.push({
1530
+ id: SetSheetsFilterRangeMutation.id,
1531
+ params: {
1532
+ range: filterRange,
1533
+ unitId,
1534
+ subUnitId
1535
+ }
1536
+ });
1537
+ const count = Math.min(removeEndRow, endRow) - Math.max(removeStartRow, startRow) + 1;
1538
+ if (count === endRow - startRow + 1 || filterHeaderIsRemoved) {
1539
+ const removeFilterRangeMutationParams = {
1540
+ unitId,
1541
+ subUnitId
1542
+ };
1543
+ redos.push({
1544
+ id: RemoveSheetsFilterMutation.id,
1545
+ params: removeFilterRangeMutationParams
1546
+ });
1547
+ filterColumn.forEach((column) => {
1548
+ const [offset, filter] = column;
1549
+ const setCriteriaMutationParams = {
1550
+ unitId,
1551
+ subUnitId,
1552
+ col: offset,
1553
+ criteria: {
1554
+ ...filter.serialize(),
1555
+ colId: offset
1556
+ }
1557
+ };
1558
+ undos.push({
1559
+ id: SetSheetsFilterCriteriaMutation.id,
1560
+ params: setCriteriaMutationParams
1561
+ });
1562
+ });
1563
+ } else {
1564
+ var _this$_univerInstance;
1565
+ const worksheet = (_this$_univerInstance = this._univerInstanceService.getUniverSheetInstance(unitId)) === null || _this$_univerInstance === void 0 ? void 0 : _this$_univerInstance.getSheetBySheetId(subUnitId);
1566
+ if (!worksheet) return this._handleNull();
1567
+ const hiddenRows = [];
1568
+ for (let r = removeStartRow; r <= removeEndRow; r++) if (worksheet.getRowFiltered(r)) hiddenRows.push(r);
1569
+ const afterStartRow = Math.min(startRow, removeStartRow);
1570
+ const afterEndRow = afterStartRow + (endRow - startRow) - count + hiddenRows.length;
1571
+ const setFilterRangeMutationParams = {
1572
+ unitId,
1573
+ subUnitId,
1574
+ range: {
1575
+ ...filterRange,
1576
+ startRow: afterStartRow,
1577
+ endRow: afterEndRow
1578
+ }
1579
+ };
1580
+ redos.push({
1581
+ id: SetSheetsFilterRangeMutation.id,
1582
+ params: setFilterRangeMutationParams
1583
+ });
1584
+ }
1585
+ return {
1586
+ undos: mergeSetFilterCriteria(undos),
1587
+ redos: mergeSetFilterCriteria(redos)
1588
+ };
1589
+ }
1590
+ handleMoveColsCommand({ fromRange, toRange }, unitId, subUnitId) {
1591
+ var _filterModel$getRange4;
1592
+ const filterModel = this._sheetsFilterService.getFilterModel(unitId, subUnitId);
1593
+ const filterRange = (_filterModel$getRange4 = filterModel === null || filterModel === void 0 ? void 0 : filterModel.getRange()) !== null && _filterModel$getRange4 !== void 0 ? _filterModel$getRange4 : null;
1594
+ if (!filterModel || !filterRange) return this._handleNull();
1595
+ const { startColumn, endColumn } = filterRange;
1596
+ if (fromRange.endColumn < startColumn && toRange.startColumn <= startColumn || fromRange.startColumn > endColumn && toRange.endColumn > endColumn) return this._handleNull();
1597
+ const redos = [];
1598
+ const undos = [];
1599
+ const filterCol = {};
1600
+ for (let col = startColumn; col <= endColumn; col++) filterCol[col] = {
1601
+ colIndex: col,
1602
+ filter: filterModel.getFilterColumn(col)
1603
+ };
1604
+ (0, _univerjs_core.moveMatrixArray)(fromRange.startColumn, fromRange.endColumn - fromRange.startColumn + 1, toRange.startColumn, filterCol);
1605
+ let startBorder = filterRange.startColumn;
1606
+ let endBorder = filterRange.endColumn;
1607
+ if (startColumn >= fromRange.startColumn && startColumn <= fromRange.endColumn && toRange.startColumn > fromRange.startColumn && fromRange.endColumn < endColumn) startBorder = fromRange.endColumn + 1;
1608
+ if (endColumn >= fromRange.startColumn && endColumn <= fromRange.endColumn && toRange.startColumn < fromRange.startColumn && fromRange.startColumn > startColumn) endBorder = fromRange.startColumn - 1;
1609
+ const numberCols = Object.keys(filterCol).map((col) => Number(col));
1610
+ const newEnd = numberCols.find((col) => filterCol[col].colIndex === endBorder);
1611
+ const newStart = numberCols.find((col) => filterCol[col].colIndex === startBorder);
1612
+ numberCols.forEach((col) => {
1613
+ const { colIndex: oldColIndex, filter } = filterCol[col];
1614
+ const newColIndex = col;
1615
+ if (filter) {
1616
+ var _filterCol$oldColInde;
1617
+ if (newColIndex >= newStart && newColIndex <= newEnd) {
1618
+ var _filterModel$getFilte;
1619
+ const setCriteriaMutationParams = {
1620
+ unitId,
1621
+ subUnitId,
1622
+ col: newColIndex,
1623
+ criteria: {
1624
+ ...filter.serialize(),
1625
+ colId: newColIndex
1626
+ }
1627
+ };
1628
+ const undoSetCriteriaMutationParams = {
1629
+ unitId,
1630
+ subUnitId,
1631
+ col: newColIndex,
1632
+ criteria: filterModel.getFilterColumn(newColIndex) ? {
1633
+ ...(_filterModel$getFilte = filterModel.getFilterColumn(newColIndex)) === null || _filterModel$getFilte === void 0 ? void 0 : _filterModel$getFilte.serialize(),
1634
+ colId: newColIndex
1635
+ } : null
1636
+ };
1637
+ redos.push({
1638
+ id: SetSheetsFilterCriteriaMutation.id,
1639
+ params: setCriteriaMutationParams
1640
+ });
1641
+ undos.push({
1642
+ id: SetSheetsFilterCriteriaMutation.id,
1643
+ params: undoSetCriteriaMutationParams
1644
+ });
1645
+ }
1646
+ if (!((_filterCol$oldColInde = filterCol[oldColIndex]) === null || _filterCol$oldColInde === void 0 ? void 0 : _filterCol$oldColInde.filter)) {
1647
+ const setCriteriaMutationParams = {
1648
+ unitId,
1649
+ subUnitId,
1650
+ col: oldColIndex,
1651
+ criteria: null
1652
+ };
1653
+ redos.push({
1654
+ id: SetSheetsFilterCriteriaMutation.id,
1655
+ params: setCriteriaMutationParams
1656
+ });
1657
+ undos.push({
1658
+ id: SetSheetsFilterCriteriaMutation.id,
1659
+ params: {
1660
+ unitId,
1661
+ subUnitId,
1662
+ col: oldColIndex,
1663
+ criteria: {
1664
+ ...filter.serialize(),
1665
+ colId: oldColIndex
1666
+ }
1667
+ }
1668
+ });
1669
+ }
1670
+ }
1671
+ });
1672
+ if (startColumn !== newStart || endColumn !== newEnd) {
1673
+ const setFilterRangeMutationParams = {
1674
+ unitId,
1675
+ subUnitId,
1676
+ range: {
1677
+ ...filterRange,
1678
+ startColumn: newStart,
1679
+ endColumn: newEnd
1680
+ }
1681
+ };
1682
+ redos.unshift({
1683
+ id: SetSheetsFilterRangeMutation.id,
1684
+ params: setFilterRangeMutationParams
1685
+ });
1686
+ undos.unshift({
1687
+ id: SetSheetsFilterRangeMutation.id,
1688
+ params: {
1689
+ range: filterRange,
1690
+ unitId,
1691
+ subUnitId
1692
+ }
1693
+ });
1694
+ }
1695
+ return {
1696
+ undos,
1697
+ redos
1698
+ };
1699
+ }
1700
+ _handleMoveRowsCommand(config, unitId, subUnitId) {
1701
+ var _filterModel$getRange5;
1702
+ const filterModel = this._sheetsFilterService.getFilterModel(unitId, subUnitId);
1703
+ const filterRange = (_filterModel$getRange5 = filterModel === null || filterModel === void 0 ? void 0 : filterModel.getRange()) !== null && _filterModel$getRange5 !== void 0 ? _filterModel$getRange5 : null;
1704
+ if (!filterModel || !filterRange) return this._handleNull();
1705
+ const { startRow, endRow } = filterRange;
1706
+ const { fromRange, toRange } = config;
1707
+ if (fromRange.endRow < startRow && toRange.startRow <= startRow || fromRange.startRow > endRow && toRange.endRow > endRow) return this._handleNull();
1708
+ const redos = [];
1709
+ const undos = [];
1710
+ const filterRow = {};
1711
+ for (let row = startRow; row <= endRow; row++) filterRow[row] = { oldIndex: row };
1712
+ const startBorder = startRow;
1713
+ let endBorder = endRow;
1714
+ if (endRow >= fromRange.startRow && endRow <= fromRange.endRow && toRange.startRow < fromRange.startRow && fromRange.startRow > startRow) endBorder = fromRange.startRow - 1;
1715
+ (0, _univerjs_core.moveMatrixArray)(fromRange.startRow, fromRange.endRow - fromRange.startRow + 1, toRange.startRow, filterRow);
1716
+ const numberRows = Object.keys(filterRow).map((row) => Number(row));
1717
+ const newEnd = numberRows.find((row) => filterRow[row].oldIndex === endBorder);
1718
+ const newStart = numberRows.find((row) => filterRow[row].oldIndex === startBorder);
1719
+ if (startRow !== newStart || endRow !== newEnd) {
1720
+ const setFilterRangeMutationParams = {
1721
+ unitId,
1722
+ subUnitId,
1723
+ range: {
1724
+ ...filterRange,
1725
+ startRow: newStart,
1726
+ endRow: newEnd
1727
+ }
1728
+ };
1729
+ redos.push({
1730
+ id: SetSheetsFilterRangeMutation.id,
1731
+ params: setFilterRangeMutationParams
1732
+ }, {
1733
+ id: ReCalcSheetsFilterMutation.id,
1734
+ params: {
1735
+ unitId,
1736
+ subUnitId
1737
+ }
1738
+ });
1739
+ undos.push({
1740
+ id: SetSheetsFilterRangeMutation.id,
1741
+ params: {
1742
+ range: filterRange,
1743
+ unitId,
1744
+ subUnitId
1745
+ }
1746
+ }, {
1747
+ id: ReCalcSheetsFilterMutation.id,
1748
+ params: {
1749
+ unitId,
1750
+ subUnitId
1751
+ }
1752
+ });
1753
+ }
1754
+ return {
1755
+ redos,
1756
+ undos
1757
+ };
1758
+ }
1759
+ _handleMoveRangeCommand(config, unitId, subUnitId) {
1760
+ const { fromRange, toRange } = config;
1761
+ const filterModel = this._sheetsFilterService.getFilterModel(unitId, subUnitId);
1762
+ if (!filterModel) return this._handleNull();
1763
+ const filterRange = filterModel.getRange();
1764
+ if (!filterRange) return this._handleNull();
1765
+ const redos = [];
1766
+ const undos = [];
1767
+ if (_univerjs_core.Rectangle.contains(fromRange, filterRange)) {
1768
+ const rowOffset = filterRange.startRow - fromRange.startRow;
1769
+ const colOffset = filterRange.startColumn - fromRange.startColumn;
1770
+ const newFilterRange = {
1771
+ startRow: toRange.startRow + rowOffset,
1772
+ startColumn: toRange.startColumn + colOffset,
1773
+ endRow: toRange.startRow + rowOffset + (filterRange.endRow - filterRange.startRow),
1774
+ endColumn: toRange.startColumn + colOffset + (filterRange.endColumn - filterRange.startColumn)
1775
+ };
1776
+ const removeFilter = {
1777
+ id: RemoveSheetsFilterMutation.id,
1778
+ params: {
1779
+ unitId,
1780
+ subUnitId
1781
+ }
1782
+ };
1783
+ const setNewFilterRange = {
1784
+ id: SetSheetsFilterRangeMutation.id,
1785
+ params: {
1786
+ unitId,
1787
+ subUnitId,
1788
+ range: newFilterRange
1789
+ }
1790
+ };
1791
+ const setOldFilterRange = {
1792
+ id: SetSheetsFilterRangeMutation.id,
1793
+ params: {
1794
+ unitId,
1795
+ subUnitId,
1796
+ range: filterRange
1797
+ }
1798
+ };
1799
+ redos.push(removeFilter, setNewFilterRange);
1800
+ undos.push(removeFilter, setOldFilterRange);
1801
+ const filterColumn = filterModel.getAllFilterColumns();
1802
+ const moveColDelta = toRange.startColumn - fromRange.startColumn;
1803
+ filterColumn.forEach((column) => {
1804
+ const [col, criteria] = column;
1805
+ if (criteria) {
1806
+ redos.push({
1807
+ id: SetSheetsFilterCriteriaMutation.id,
1808
+ params: {
1809
+ unitId,
1810
+ subUnitId,
1811
+ col: col + moveColDelta,
1812
+ criteria: {
1813
+ ...criteria.serialize(),
1814
+ colId: col + moveColDelta
1815
+ }
1816
+ }
1817
+ });
1818
+ undos.push({
1819
+ id: SetSheetsFilterCriteriaMutation.id,
1820
+ params: {
1821
+ unitId,
1822
+ subUnitId,
1823
+ col,
1824
+ criteria: {
1825
+ ...criteria.serialize(),
1826
+ colId: col
1827
+ }
1828
+ }
1829
+ });
1830
+ }
1831
+ });
1832
+ } else if (_univerjs_core.Rectangle.intersects(toRange, filterRange)) {
1833
+ const newFilterRange = {
1834
+ ...filterRange,
1835
+ endRow: Math.max(filterRange.endRow, toRange.endRow)
1836
+ };
1837
+ redos.push({
1838
+ id: SetSheetsFilterRangeMutation.id,
1839
+ params: {
1840
+ unitId,
1841
+ subUnitId,
1842
+ range: newFilterRange
1843
+ }
1844
+ });
1845
+ undos.push({
1846
+ id: SetSheetsFilterRangeMutation.id,
1847
+ params: {
1848
+ unitId,
1849
+ subUnitId,
1850
+ range: filterRange
1851
+ }
1852
+ });
1853
+ }
1854
+ return {
1855
+ redos,
1856
+ undos
1857
+ };
1858
+ }
1859
+ _handleRemoveSheetCommand(config, unitId, subUnitId) {
1860
+ const filterModel = this._sheetsFilterService.getFilterModel(unitId, subUnitId);
1861
+ if (!filterModel) return this._handleNull();
1862
+ const filterRange = filterModel.getRange();
1863
+ if (!filterRange) return this._handleNull();
1864
+ const redos = [];
1865
+ const undos = [];
1866
+ filterModel.getAllFilterColumns().forEach(([col, filter]) => {
1867
+ undos.push({
1868
+ id: SetSheetsFilterCriteriaMutation.id,
1869
+ params: {
1870
+ unitId,
1871
+ subUnitId,
1872
+ col,
1873
+ criteria: {
1874
+ ...filter.serialize(),
1875
+ colId: col
1876
+ }
1877
+ }
1878
+ });
1879
+ });
1880
+ redos.push({
1881
+ id: RemoveSheetsFilterMutation.id,
1882
+ params: {
1883
+ unitId,
1884
+ subUnitId,
1885
+ range: filterRange
1886
+ }
1887
+ });
1888
+ undos.unshift({
1889
+ id: SetSheetsFilterRangeMutation.id,
1890
+ params: {
1891
+ range: filterRange,
1892
+ unitId,
1893
+ subUnitId
1894
+ }
1895
+ });
1896
+ return {
1897
+ undos,
1898
+ redos
1899
+ };
1900
+ }
1901
+ _handleCopySheetCommand(unitId, subUnitId, targetSubUnitId) {
1902
+ const filterModel = this._sheetsFilterService.getFilterModel(unitId, subUnitId);
1903
+ if (!filterModel) return this._handleNull();
1904
+ const filterRange = filterModel.getRange();
1905
+ if (!filterRange) return this._handleNull();
1906
+ const redos = [];
1907
+ const undos = [];
1908
+ const preUndos = [];
1909
+ const preRedos = [];
1910
+ filterModel.getAllFilterColumns().forEach(([col, filter]) => {
1911
+ redos.push({
1912
+ id: SetSheetsFilterCriteriaMutation.id,
1913
+ params: {
1914
+ unitId,
1915
+ subUnitId: targetSubUnitId,
1916
+ col,
1917
+ criteria: {
1918
+ ...filter.serialize(),
1919
+ colId: col
1920
+ }
1921
+ }
1922
+ });
1923
+ preUndos.push({
1924
+ id: SetSheetsFilterCriteriaMutation.id,
1925
+ params: {
1926
+ unitId,
1927
+ subUnitId: targetSubUnitId,
1928
+ col,
1929
+ criteria: null
1930
+ }
1931
+ });
1932
+ });
1933
+ preUndos.push({
1934
+ id: RemoveSheetsFilterMutation.id,
1935
+ params: {
1936
+ unitId,
1937
+ subUnitId: targetSubUnitId,
1938
+ range: filterRange
1939
+ }
1940
+ });
1941
+ redos.unshift({
1942
+ id: SetSheetsFilterRangeMutation.id,
1943
+ params: {
1944
+ range: filterRange,
1945
+ unitId,
1946
+ subUnitId: targetSubUnitId
1947
+ }
1948
+ });
1949
+ return {
1950
+ undos,
1951
+ redos,
1952
+ preUndos,
1953
+ preRedos
1954
+ };
1955
+ }
1956
+ _handleNull() {
1957
+ return {
1958
+ redos: [],
1959
+ undos: []
1960
+ };
1961
+ }
1962
+ _initRowFilteredInterceptor() {
1963
+ this.disposeWithMe(this._sheetInterceptorService.intercept(_univerjs_sheets.INTERCEPTOR_POINT.ROW_FILTERED, { handler: (filtered, rowLocation) => {
1964
+ var _this$_sheetsFilterSe2, _this$_sheetsFilterSe3;
1965
+ if (filtered) return true;
1966
+ return (_this$_sheetsFilterSe2 = (_this$_sheetsFilterSe3 = this._sheetsFilterService.getFilterModel(rowLocation.unitId, rowLocation.subUnitId)) === null || _this$_sheetsFilterSe3 === void 0 ? void 0 : _this$_sheetsFilterSe3.isRowFiltered(rowLocation.row)) !== null && _this$_sheetsFilterSe2 !== void 0 ? _this$_sheetsFilterSe2 : false;
1967
+ } }));
1968
+ }
1969
+ _moveCriteria(unitId, subUnitId, target, step) {
1970
+ const defaultSetCriteriaMutationParams = {
1971
+ unitId,
1972
+ subUnitId,
1973
+ criteria: null,
1974
+ col: -1
1975
+ };
1976
+ const oldUndos = [];
1977
+ const oldRedos = [];
1978
+ const newUndos = [];
1979
+ const newRedos = [];
1980
+ target.forEach((column) => {
1981
+ const [offset, filter] = column;
1982
+ oldRedos.push({
1983
+ id: SetSheetsFilterCriteriaMutation.id,
1984
+ params: {
1985
+ ...defaultSetCriteriaMutationParams,
1986
+ col: offset
1987
+ }
1988
+ });
1989
+ oldUndos.push({
1990
+ id: SetSheetsFilterCriteriaMutation.id,
1991
+ params: {
1992
+ ...defaultSetCriteriaMutationParams,
1993
+ col: offset,
1994
+ criteria: {
1995
+ ...filter.serialize(),
1996
+ colId: offset
1997
+ }
1998
+ }
1999
+ });
2000
+ });
2001
+ target.forEach((column) => {
2002
+ const [offset, filter] = column;
2003
+ newRedos.push({
2004
+ id: SetSheetsFilterCriteriaMutation.id,
2005
+ params: {
2006
+ ...defaultSetCriteriaMutationParams,
2007
+ col: offset + step,
2008
+ criteria: {
2009
+ ...filter.serialize(),
2010
+ colId: offset + step
2011
+ }
2012
+ }
2013
+ });
2014
+ newUndos.push({
2015
+ id: SetSheetsFilterCriteriaMutation.id,
2016
+ params: {
2017
+ ...defaultSetCriteriaMutationParams,
2018
+ col: offset + step,
2019
+ criteria: null
2020
+ }
2021
+ });
2022
+ });
2023
+ return {
2024
+ newRange: {
2025
+ redos: newRedos,
2026
+ undos: newUndos
2027
+ },
2028
+ oldRange: {
2029
+ redos: oldRedos,
2030
+ undos: oldUndos
2031
+ }
2032
+ };
2033
+ }
2034
+ _commandExecutedListener() {
2035
+ this.disposeWithMe(this._commandService.onCommandExecuted((command, options) => {
2036
+ const { unitId, subUnitId } = command.params || {};
2037
+ const filterModel = this._sheetsFilterService.getFilterModel(unitId, subUnitId);
2038
+ if (!filterModel) return;
2039
+ const filteredOutRows = Array.from(filterModel.filteredOutRows).sort((a, b) => a - b);
2040
+ const newFilteredOutRows = [];
2041
+ let changed = false;
2042
+ if (command.id === _univerjs_sheets.RemoveRowMutation.id) {
2043
+ const { startRow, endRow } = command.params.range;
2044
+ const filterOutInRemove = filteredOutRows.filter((row) => row >= startRow && row <= endRow);
2045
+ filteredOutRows.forEach((row) => {
2046
+ if (row < startRow) newFilteredOutRows.push(row);
2047
+ else {
2048
+ changed = true;
2049
+ if (row <= endRow) {
2050
+ const newIndex = Math.max(startRow, newFilteredOutRows.length ? newFilteredOutRows[newFilteredOutRows.length - 1] + 1 : startRow);
2051
+ newFilteredOutRows.push(newIndex);
2052
+ } else newFilteredOutRows.push(row - (endRow - startRow + 1 - filterOutInRemove.length));
2053
+ }
2054
+ });
2055
+ }
2056
+ if (command.id === _univerjs_sheets.InsertRowMutation.id) {
2057
+ const { startRow, endRow } = command.params.range;
2058
+ filteredOutRows.forEach((row) => {
2059
+ if (row >= startRow) {
2060
+ changed = true;
2061
+ newFilteredOutRows.push(row + (endRow - startRow + 1));
2062
+ } else newFilteredOutRows.push(row);
2063
+ });
2064
+ }
2065
+ if (changed) filterModel.filteredOutRows = new Set(newFilteredOutRows);
2066
+ if (command.id === _univerjs_sheets.SetRangeValuesMutation.id && !(options === null || options === void 0 ? void 0 : options.onlyLocal)) {
2067
+ const extendRegion = this._getExtendRegion(unitId, subUnitId);
2068
+ if (extendRegion) {
2069
+ const cellValue = command.params.cellValue;
2070
+ if (cellValue) for (let col = extendRegion.startColumn; col <= extendRegion.endColumn; col++) {
2071
+ var _cellValue$extendRegi;
2072
+ const cell = cellValue === null || cellValue === void 0 || (_cellValue$extendRegi = cellValue[extendRegion.startRow]) === null || _cellValue$extendRegi === void 0 ? void 0 : _cellValue$extendRegi[col];
2073
+ if (cell && this._cellHasValue(cell)) {
2074
+ var _this$_univerInstance2;
2075
+ const worksheet = (_this$_univerInstance2 = this._univerInstanceService.getUnit(unitId)) === null || _this$_univerInstance2 === void 0 ? void 0 : _this$_univerInstance2.getSheetBySheetId(subUnitId);
2076
+ if (worksheet) {
2077
+ const extendedRange = (0, _univerjs_sheets.expandToContinuousRange)(extendRegion, { down: true }, worksheet);
2078
+ const filterModel = this._sheetsFilterService.getFilterModel(unitId, subUnitId);
2079
+ const filterRange = filterModel.getRange();
2080
+ filterModel.setRange({
2081
+ ...filterRange,
2082
+ endRow: extendedRange.endRow
2083
+ });
2084
+ this._registerRefRange(unitId, subUnitId);
2085
+ }
2086
+ }
2087
+ }
2088
+ }
2089
+ }
2090
+ }));
2091
+ }
2092
+ _getExtendRegion(unitId, subUnitId) {
2093
+ var _this$_univerInstance3;
2094
+ const filterModel = this._sheetsFilterService.getFilterModel(unitId, subUnitId);
2095
+ if (!filterModel) return null;
2096
+ const worksheet = (_this$_univerInstance3 = this._univerInstanceService.getUnit(unitId)) === null || _this$_univerInstance3 === void 0 ? void 0 : _this$_univerInstance3.getSheetBySheetId(subUnitId);
2097
+ if (!worksheet) return null;
2098
+ const filterRange = filterModel.getRange();
2099
+ if (!filterRange) return null;
2100
+ const maxRowIndex = worksheet.getRowCount() - 1;
2101
+ const rowManager = worksheet.getRowManager();
2102
+ for (let row = filterRange.endRow + 1; row <= maxRowIndex; row++) if (rowManager.getRowRawVisible(row)) return {
2103
+ startRow: row,
2104
+ endRow: row,
2105
+ startColumn: filterRange.startColumn,
2106
+ endColumn: filterRange.endColumn
2107
+ };
2108
+ return null;
2109
+ }
2110
+ _initErrorHandling() {
2111
+ this.disposeWithMe(this._commandService.beforeCommandExecuted((command) => {
2112
+ const params = command.params;
2113
+ const target = (0, _univerjs_sheets.getSheetCommandTarget)(this._univerInstanceService, params);
2114
+ if (!target) return;
2115
+ const { subUnitId, unitId } = target;
2116
+ const filterModel = this._sheetsFilterService.getFilterModel(unitId, subUnitId);
2117
+ if (!filterModel) return;
2118
+ const filterRange = filterModel.getRange();
2119
+ if (command.id === _univerjs_sheets.MoveRowsCommand.id && params.fromRange.startRow <= filterRange.startRow && params.fromRange.endRow < filterRange.endRow && params.fromRange.endRow >= filterRange.startRow) {
2120
+ this._sheetsFilterService.setFilterErrorMsg("sheets-filter.msg.filter-header-forbidden");
2121
+ throw new Error("[SheetsFilterController]: Cannot move header row of filter");
2122
+ }
2123
+ }));
2124
+ }
2125
+ _cellHasValue(cell) {
2126
+ const values = Object.values(cell);
2127
+ if (values.length === 0 || values.every((v) => v == null)) return false;
2128
+ return true;
2129
+ }
2130
+ };
2131
+ SheetsFilterController = __decorate([
2132
+ __decorateParam(0, _univerjs_core.ICommandService),
2133
+ __decorateParam(1, (0, _univerjs_core.Inject)(_univerjs_sheets.SheetInterceptorService)),
2134
+ __decorateParam(2, (0, _univerjs_core.Inject)(SheetsFilterService)),
2135
+ __decorateParam(3, _univerjs_core.IUniverInstanceService),
2136
+ __decorateParam(4, (0, _univerjs_core.Inject)(_univerjs_sheets.RefRangeService)),
2137
+ __decorateParam(5, (0, _univerjs_core.Optional)(_univerjs_rpc.DataSyncPrimaryController)),
2138
+ __decorateParam(6, (0, _univerjs_core.Inject)(_univerjs_sheets.ZebraCrossingCacheController))
2139
+ ], SheetsFilterController);
2140
+
2141
+ //#endregion
2142
+ //#region src/controllers/sheets-filter-sync.controller.ts
2143
+ const sheetsFilterOnlyLocalMutationIds = [SetSheetsFilterCriteriaMutation.id, ReCalcSheetsFilterMutation.id];
2144
+ const effectedByOnlyLocalMutationIds = [
2145
+ _univerjs_sheets.InsertColMutation.id,
2146
+ _univerjs_sheets.RemoveColMutation.id,
2147
+ _univerjs_sheets.MoveColsMutation.id
2148
+ ];
2149
+ let SheetsFilterSyncController = class SheetsFilterSyncController extends _univerjs_core.Disposable {
2150
+ get visible() {
2151
+ return this._visible$.getValue();
2152
+ }
2153
+ get enabled() {
2154
+ return this._enabled$.getValue();
2155
+ }
2156
+ constructor(_sheetsFilterController, _commandService, _configService) {
2157
+ super();
2158
+ this._sheetsFilterController = _sheetsFilterController;
2159
+ this._commandService = _commandService;
2160
+ this._configService = _configService;
2161
+ _defineProperty(this, "_d", new _univerjs_core.DisposableCollection());
2162
+ _defineProperty(this, "_visible$", new rxjs.BehaviorSubject(false));
2163
+ _defineProperty(this, "visible$", this._visible$.asObservable());
2164
+ _defineProperty(this, "_enabled$", new rxjs.BehaviorSubject(true));
2165
+ _defineProperty(this, "enabled$", this._enabled$.asObservable());
2166
+ const config = this._configService.getConfig(SHEETS_FILTER_PLUGIN_CONFIG_KEY);
2167
+ if (config === null || config === void 0 ? void 0 : config.enableSyncSwitch) {
2168
+ this._visible$.next(true);
2169
+ if (typeof config.enableSyncSwitch === "object") {
2170
+ var _config$enableSyncSwi;
2171
+ this.setEnabled((_config$enableSyncSwi = config.enableSyncSwitch.defaultValue) !== null && _config$enableSyncSwi !== void 0 ? _config$enableSyncSwi : true);
2172
+ }
2173
+ }
2174
+ }
2175
+ setEnabled(enabled) {
2176
+ this._enabled$.next(enabled);
2177
+ if (enabled) this._d.dispose();
2178
+ else this._initOnlyLocalListener();
2179
+ }
2180
+ _initOnlyLocalListener() {
2181
+ this._d.add(this._commandService.beforeCommandExecuted((commandInfo, options) => {
2182
+ if (sheetsFilterOnlyLocalMutationIds.includes(commandInfo.id)) {
2183
+ if (!options) options = {};
2184
+ options.onlyLocal = true;
2185
+ }
2186
+ }));
2187
+ this._d.add(this._commandService.onCommandExecuted((commandInfo, options) => {
2188
+ if (effectedByOnlyLocalMutationIds.includes(commandInfo.id) && (options === null || options === void 0 ? void 0 : options.fromCollab)) {
2189
+ if (commandInfo.id === _univerjs_sheets.InsertColMutation.id) {
2190
+ const { range, unitId, subUnitId } = commandInfo.params;
2191
+ const { redos } = this._sheetsFilterController.handleInsertColCommand(range, unitId, subUnitId);
2192
+ (0, _univerjs_core.sequenceExecute)(redos, this._commandService, options);
2193
+ } else if (commandInfo.id === _univerjs_sheets.RemoveColMutation.id) {
2194
+ const { range, unitId, subUnitId } = commandInfo.params;
2195
+ const { redos } = this._sheetsFilterController.handleRemoveColCommand(range, unitId, subUnitId);
2196
+ (0, _univerjs_core.sequenceExecute)(redos, this._commandService, options);
2197
+ } else if (commandInfo.id === _univerjs_sheets.MoveColsMutation.id) {
2198
+ const { sourceRange: fromRange, targetRange: toRange, unitId, subUnitId } = commandInfo.params;
2199
+ const { redos } = this._sheetsFilterController.handleMoveColsCommand({
2200
+ fromRange,
2201
+ toRange
2202
+ }, unitId, subUnitId);
2203
+ (0, _univerjs_core.sequenceExecute)(redos, this._commandService, options);
2204
+ }
2205
+ }
2206
+ }));
2207
+ }
2208
+ };
2209
+ SheetsFilterSyncController = __decorate([
2210
+ __decorateParam(0, (0, _univerjs_core.Inject)(SheetsFilterController)),
2211
+ __decorateParam(1, _univerjs_core.ICommandService),
2212
+ __decorateParam(2, _univerjs_core.IConfigService)
2213
+ ], SheetsFilterSyncController);
2214
+
2215
+ //#endregion
2216
+ //#region package.json
2217
+ var name = "@univerjs/sheets-filter";
2218
+ var version = "0.21.0";
2219
+
2220
+ //#endregion
2221
+ //#region src/services/sheet-filter-formula.service.ts
2222
+ let SheetsFilterFormulaService = class SheetsFilterFormulaService extends _univerjs_core.Disposable {
2223
+ constructor(_activeDirtyManagerService, _sheetRowFilteredService, _sheetsFilterService, _univerInstanceService) {
2224
+ super();
2225
+ this._activeDirtyManagerService = _activeDirtyManagerService;
2226
+ this._sheetRowFilteredService = _sheetRowFilteredService;
2227
+ this._sheetsFilterService = _sheetsFilterService;
2228
+ this._univerInstanceService = _univerInstanceService;
2229
+ this._initFormulaDirtyRange();
2230
+ this._registerSheetRowFiltered();
2231
+ }
2232
+ _initFormulaDirtyRange() {
2233
+ FILTER_MUTATIONS.forEach((commandId) => {
2234
+ this._activeDirtyManagerService.register(commandId, {
2235
+ commandId,
2236
+ getDirtyData: (commandInfo) => {
2237
+ const { unitId, subUnitId } = commandInfo.params;
2238
+ return {
2239
+ dirtyRanges: this._getHideRowMutation(unitId, subUnitId),
2240
+ clearDependencyTreeCache: { [unitId]: { [subUnitId]: "1" } }
2241
+ };
2242
+ }
2243
+ });
2244
+ });
2245
+ }
2246
+ _getHideRowMutation(unitId, subUnitId) {
2247
+ var _this$_sheetsFilterSe, _this$_univerInstance;
2248
+ const range = (_this$_sheetsFilterSe = this._sheetsFilterService.getFilterModel(unitId, subUnitId)) === null || _this$_sheetsFilterSe === void 0 ? void 0 : _this$_sheetsFilterSe.getRange();
2249
+ const sheet = (_this$_univerInstance = this._univerInstanceService.getUnit(unitId)) === null || _this$_univerInstance === void 0 ? void 0 : _this$_univerInstance.getSheetBySheetId(subUnitId);
2250
+ if (range == null || sheet == null) return [];
2251
+ const { startRow, endRow } = range;
2252
+ return [{
2253
+ unitId,
2254
+ sheetId: subUnitId,
2255
+ range: {
2256
+ startRow,
2257
+ startColumn: 0,
2258
+ endRow,
2259
+ endColumn: sheet.getColumnCount() - 1
2260
+ }
2261
+ }];
2262
+ }
2263
+ _registerSheetRowFiltered() {
2264
+ this._sheetRowFilteredService.register((unitId, subUnitId, row) => {
2265
+ var _this$_sheetsFilterSe2, _this$_sheetsFilterSe3;
2266
+ return (_this$_sheetsFilterSe2 = (_this$_sheetsFilterSe3 = this._sheetsFilterService.getFilterModel(unitId, subUnitId)) === null || _this$_sheetsFilterSe3 === void 0 ? void 0 : _this$_sheetsFilterSe3.isRowFiltered(row)) !== null && _this$_sheetsFilterSe2 !== void 0 ? _this$_sheetsFilterSe2 : false;
2267
+ });
2268
+ }
2269
+ };
2270
+ SheetsFilterFormulaService = __decorate([
2271
+ __decorateParam(0, (0, _univerjs_core.Inject)(_univerjs_engine_formula.IActiveDirtyManagerService)),
2272
+ __decorateParam(1, (0, _univerjs_core.Inject)(_univerjs_engine_formula.ISheetRowFilteredService)),
2273
+ __decorateParam(2, (0, _univerjs_core.Inject)(SheetsFilterService)),
2274
+ __decorateParam(3, _univerjs_core.IUniverInstanceService)
2275
+ ], SheetsFilterFormulaService);
2276
+
2277
+ //#endregion
2278
+ //#region src/plugin.ts
2279
+ let UniverSheetsFilterPlugin = class UniverSheetsFilterPlugin extends _univerjs_core.Plugin {
2280
+ constructor(_config = defaultPluginConfig, _injector, _configService) {
2281
+ super();
2282
+ this._config = _config;
2283
+ this._injector = _injector;
2284
+ this._configService = _configService;
2285
+ const { ...rest } = (0, _univerjs_core.merge)({}, defaultPluginConfig, this._config);
2286
+ this._configService.setConfig(SHEETS_FILTER_PLUGIN_CONFIG_KEY, rest);
2287
+ }
2288
+ onStarting() {
2289
+ [
2290
+ [SheetsFilterFormulaService],
2291
+ [SheetsFilterService],
2292
+ [SheetsFilterController],
2293
+ [SheetsFilterSyncController]
2294
+ ].forEach((d) => this._injector.add(d));
2295
+ }
2296
+ onReady() {
2297
+ (0, _univerjs_core.touchDependencies)(this._injector, [
2298
+ [SheetsFilterFormulaService],
2299
+ [SheetsFilterController],
2300
+ [SheetsFilterSyncController]
2301
+ ]);
2302
+ }
2303
+ };
2304
+ _defineProperty(UniverSheetsFilterPlugin, "type", _univerjs_core.UniverInstanceType.UNIVER_SHEET);
2305
+ _defineProperty(UniverSheetsFilterPlugin, "pluginName", SHEET_FILTER_SNAPSHOT_ID);
2306
+ _defineProperty(UniverSheetsFilterPlugin, "packageName", name);
2307
+ _defineProperty(UniverSheetsFilterPlugin, "version", version);
2308
+ UniverSheetsFilterPlugin = __decorate([__decorateParam(1, (0, _univerjs_core.Inject)(_univerjs_core.Injector)), __decorateParam(2, _univerjs_core.IConfigService)], UniverSheetsFilterPlugin);
2309
+
2310
+ //#endregion
2311
+ exports.ClearSheetsFilterCriteriaCommand = ClearSheetsFilterCriteriaCommand;
2312
+ exports.CustomFilterOperator = CustomFilterOperator;
2313
+ exports.FILTER_MUTATIONS = FILTER_MUTATIONS;
2314
+ exports.FilterBy = FilterBy;
2315
+ exports.FilterColumn = FilterColumn;
2316
+ exports.FilterModel = FilterModel;
2317
+ exports.ReCalcSheetsFilterCommand = ReCalcSheetsFilterCommand;
2318
+ exports.ReCalcSheetsFilterMutation = ReCalcSheetsFilterMutation;
2319
+ exports.RemoveSheetFilterCommand = RemoveSheetFilterCommand;
2320
+ exports.RemoveSheetsFilterMutation = RemoveSheetsFilterMutation;
2321
+ exports.SHEET_FILTER_SNAPSHOT_ID = SHEET_FILTER_SNAPSHOT_ID;
2322
+ exports.SetSheetFilterRangeCommand = SetSheetFilterRangeCommand;
2323
+ exports.SetSheetsFilterCriteriaCommand = SetSheetsFilterCriteriaCommand;
2324
+ exports.SetSheetsFilterCriteriaMutation = SetSheetsFilterCriteriaMutation;
2325
+ exports.SetSheetsFilterRangeMutation = SetSheetsFilterRangeMutation;
2326
+ Object.defineProperty(exports, 'SheetsFilterService', {
2327
+ enumerable: true,
2328
+ get: function () {
2329
+ return SheetsFilterService;
2330
+ }
2331
+ });
2332
+ Object.defineProperty(exports, 'SheetsFilterSyncController', {
2333
+ enumerable: true,
2334
+ get: function () {
2335
+ return SheetsFilterSyncController;
2336
+ }
2337
+ });
2338
+ exports.SmartToggleSheetsFilterCommand = SmartToggleSheetsFilterCommand;
2339
+ Object.defineProperty(exports, 'UniverSheetsFilterPlugin', {
2340
+ enumerable: true,
2341
+ get: function () {
2342
+ return UniverSheetsFilterPlugin;
2343
+ }
2344
+ });
2345
+ exports.equals = equals;
2346
+ exports.getCustomFilterFn = getCustomFilterFn;
2347
+ exports.greaterThan = greaterThan;
2348
+ exports.greaterThanOrEqualTo = greaterThanOrEqualTo;
2349
+ exports.lessThan = lessThan;
2350
+ exports.lessThanOrEqualTo = lessThanOrEqualTo;
2351
+ exports.notEquals = notEquals;