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