UNPKG

@univerjs/sheets-formula

Version:

| Package Name | UMD Namespace | Version | License | Downloads | Contains CSS | Contains i18n locales | | --- | --- | --- | --- | --- | :---: | :---: | | `@univerjs/sheets-formula` | `UniverSheetsFormula` | [![][npm-version-shield]][npm-version-link] | ![

1 lines • 410 kB
"use strict";var Ye=Object.defineProperty;var we=(r,t,n)=>t in r?Ye(r,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):r[t]=n;var g=(r,t,n)=>we(r,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("@univerjs/core"),l=require("@univerjs/sheets"),e=require("@univerjs/engine-formula"),Y=require("rxjs"),le=require("@univerjs/rpc"),Ue={id:"formula.command.insert-function",type:c.CommandType.COMMAND,handler:async(r,t)=>{const{list:n,listOfRangeHasNumber:a}=t,i=r.get(c.ICommandService),o=new c.ObjectMatrix;n.forEach(m=>{const{range:f,primary:s,formula:d}=m,{row:T,column:N}=s,L=c.generateRandomId(6);o.setValue(T,N,{f:d,si:L});const{startRow:A,startColumn:S,endRow:C,endColumn:p}=f;for(let I=A;I<=C;I++)for(let E=S;E<=p;E++)(I!==T||E!==N)&&o.setValue(I,E,{si:L})}),a&&a.length>0&&a.forEach(m=>{const{primary:f,formula:s}=m;o.setValue(f.row,f.column,{f:s})});const u={value:o.getData()};return i.executeCommand(l.SetRangeValuesCommand.id,u)}},ge={id:"sheets-formula.command.quick-sum",type:c.CommandType.COMMAND,handler:async r=>{const n=r.get(l.SheetsSelectionsService).getCurrentLastSelection();if(!n)return!1;const a=r.get(c.IUniverInstanceService),i=l.getSheetCommandTarget(a);if(!i)return!1;const o=n.range,{worksheet:u}=i;let m=l.findFirstNonEmptyCell(o,u);if(!m)return!1;m=l.alignToMergedCellsBorders(m,u);const f=l.expandToContinuousRange({startRow:m.startRow,startColumn:m.startColumn,endRow:o.endRow,endColumn:o.endColumn},{left:!0,right:!0,up:!0,down:!0},u),s=new c.ObjectMatrix,d=l.alignToMergedCellsBorders({startRow:f.endRow,endRow:f.endRow,startColumn:f.startColumn,endColumn:f.endColumn},u);if(!c.Rectangle.equals(d,f))for(const L of u.iterateByColumn(d))(!L.value||!u.cellHasValue(L.value))&&s.setValue(L.row,L.col,{f:`=SUM(${e.serializeRange({startColumn:L.col,endColumn:L.col,startRow:f.startRow,endRow:L.row-1})})`});const T=l.alignToMergedCellsBorders({startRow:f.startRow,startColumn:f.endColumn,endRow:f.endRow,endColumn:f.endColumn},u);if(!c.Rectangle.equals(T,f))for(const L of u.iterateByRow(T))(!L.value||!u.cellHasValue(L.value))&&s.setValue(L.row,L.col,{f:`=SUM(${e.serializeRange({startColumn:f.startColumn,endColumn:L.col-1,startRow:L.row,endRow:L.row})})`});const N=r.get(c.ICommandService);return(await c.sequenceExecuteAsync([{id:l.SetRangeValuesCommand.id,params:{range:f,value:s.getMatrix()}},{id:l.SetSelectionsOperation.id,params:{unitId:i.unitId,subUnitId:i.subUnitId,selections:[{range:f,primary:c.Rectangle.contains(f,n.primary)?n.primary:{...m,actualRow:m.startRow,actualColumn:m.startColumn},style:null}]}}],N)).result}},z={type:c.CommandType.MUTATION,id:"sheet.mutation.data-validation-formula-mark-dirty",handler(){return!0}},ee="sheets-formula.base.config";var w=(r=>(r[r.FORCED=0]="FORCED",r[r.WHEN_EMPTY=1]="WHEN_EMPTY",r[r.NO_CALCULATION=2]="NO_CALCULATION",r))(w||{});const Fe={},Xe="sheets-formula.remote.config",be={};var $=(r=>(r[r.NOT_REGISTER=1]="NOT_REGISTER",r[r.SUCCESS=2]="SUCCESS",r[r.WAIT=3]="WAIT",r[r.ERROR=4]="ERROR",r))($||{}),We=Object.getOwnPropertyDescriptor,Ke=(r,t,n,a)=>{for(var i=a>1?void 0:a?We(t,n):t,o=r.length-1,u;o>=0;o--)(u=r[o])&&(i=u(i)||i);return i},Ie=(r,t)=>(n,a)=>t(n,a,r);exports.RegisterOtherFormulaService=class extends c.Disposable{constructor(n,a,i){super();g(this,"_formulaCacheMap",new Map);g(this,"_formulaChangeWithRange$",new Y.Subject);g(this,"formulaChangeWithRange$",this._formulaChangeWithRange$.asObservable());g(this,"_formulaResult$",new Y.Subject);g(this,"formulaResult$",this._formulaResult$.asObservable());g(this,"calculateStarted$",new Y.BehaviorSubject(!1));this._commandService=n,this._activeDirtyManagerService=a,this._lifecycleService=i,this._initFormulaRegister(),this._initFormulaCalculationResultChange()}dispose(){super.dispose(),this._formulaChangeWithRange$.complete(),this._formulaResult$.complete(),this.calculateStarted$.complete()}_ensureCacheMap(n,a){let i=this._formulaCacheMap.get(n);i||(i=new Map,this._formulaCacheMap.set(n,i));let o=i.get(a);return o||(o=new Map,i.set(a,o)),o}_createFormulaId(n,a){return`formula.${n}_${a}_${c.generateRandomId(8)}`}_initFormulaRegister(){this._activeDirtyManagerService.register(z.id,{commandId:z.id,getDirtyData(a){return{dirtyUnitOtherFormulaMap:a.params}}});const n=a=>{const{unitId:i,subUnitId:o,formulaText:u,formulaId:m,ranges:f}=a;if(!this._ensureCacheMap(i,o).has(m))return;const d={unitId:i,subUnitId:o,formulaMap:{[m]:{f:u,ranges:f}}};this._commandService.executeCommand(e.SetOtherFormulaMutation.id,d).then(()=>{this._commandService.executeCommand(z.id,{[i]:{[o]:{[m]:!0}}})})};this.disposeWithMe(this._formulaChangeWithRange$.pipe(Y.bufferWhen(()=>this.calculateStarted$.pipe(Y.filter(a=>a)))).subscribe(a=>a.forEach(n))),this.disposeWithMe(this._formulaChangeWithRange$.pipe(Y.filter(()=>this.calculateStarted$.getValue())).subscribe(n))}_initFormulaCalculationResultChange(){this.disposeWithMe(this._commandService.onCommandExecuted(n=>{if(n.id===e.SetFormulaCalculationResultMutation.id){const a=n.params,{unitOtherData:i}=a,o={};for(const u in i){const m=i[u],f={};o[u]=f;for(const s in m){const d=this._ensureCacheMap(u,s),T=m[s],N=[];f[s]=N;for(const L in T){const A=T[L];if(d.has(L)){const S=d.get(L);if(!S)continue;S.result||(S.result={});const C=new c.ObjectMatrix(A),p=new c.ObjectMatrix(S.result);C.forValue((I,E,P)=>{p.setValue(I,E,P)}),S.status=$.SUCCESS,S.callbacks.forEach(I=>{I(A)}),S.callbacks.clear(),N.push(S)}}}}this._formulaResult$.next(o)}}))}registerFormulaWithRange(n,a,i,o=[{startRow:0,endRow:0,startColumn:0,endColumn:0}],u){const m=this._createFormulaId(n,a);return this._ensureCacheMap(n,a).set(m,{result:void 0,status:$.WAIT,formulaId:m,callbacks:new Set,extra:u}),this._formulaChangeWithRange$.next({unitId:n,subUnitId:a,formulaText:i,formulaId:m,ranges:o}),m}deleteFormula(n,a,i){const o={unitId:n,subUnitId:a,formulaIdList:i};this._commandService.executeCommand(e.RemoveOtherFormulaMutation.id,o);const u=this._ensureCacheMap(n,a);i.forEach(m=>u.delete(m))}getFormulaValue(n,a,i){const o=this._ensureCacheMap(n,a),u=o.get(i);return u?u.status===$.SUCCESS||u.status===$.ERROR?Promise.resolve(u):new Promise(m=>{u.callbacks.add(()=>{m(o.get(i))})}):Promise.resolve(null)}getFormulaValueSync(n,a,i){return this._ensureCacheMap(n,a).get(i)}markFormulaDirty(n,a,i){const o=this.getFormulaValueSync(n,a,i);o&&(o.status=$.WAIT,this._commandService.executeCommand(z.id,{[n]:{[a]:{[i]:!0}}}))}};exports.RegisterOtherFormulaService=Ke([Ie(0,c.ICommandService),Ie(1,e.IActiveDirtyManagerService),Ie(2,c.Inject(c.LifecycleService))],exports.RegisterOtherFormulaService);var ke=Object.getOwnPropertyDescriptor,Qe=(r,t,n,a)=>{for(var i=a>1?void 0:a?ke(t,n):t,o=r.length-1,u;o>=0;o--)(u=r[o])&&(i=u(i)||i);return i},Q=(r,t)=>(n,a)=>t(n,a,r);const ye={done:0,count:0},Ae={onlyLocal:!0};exports.TriggerCalculationController=class extends c.Disposable{constructor(n,a,i,o,u,m,f){super();g(this,"_waitingCommandQueue",[]);g(this,"_executingDirtyData",{forceCalculation:!1,dirtyRanges:[],dirtyNameMap:{},dirtyDefinedNameMap:{},dirtyUnitFeatureMap:{},dirtyUnitOtherFormulaMap:{},clearDependencyTreeCache:{}});g(this,"_setTimeoutKey",-1);g(this,"_startExecutionTime",0);g(this,"_totalCalculationTaskCount",0);g(this,"_doneCalculationTaskCount",0);g(this,"_executionInProgressParams",null);g(this,"_restartCalculation",!1);g(this,"_forceCalculating",!1);g(this,"_progress$",new Y.BehaviorSubject(ye));g(this,"progress$",this._progress$.asObservable());this._commandService=n,this._activeDirtyManagerService=a,this._logService=i,this._configService=o,this._formulaDataModel=u,this._localeService=m,this._registerOtherFormulaService=f,this._commandExecutedListener(),this._initialExecuteFormulaProcessListener(),this._initialExecuteFormula()}_emitProgress(n){this._progress$.next({done:this._doneCalculationTaskCount,count:this._totalCalculationTaskCount,label:n})}_startProgress(){this._doneCalculationTaskCount=0,this._totalCalculationTaskCount=1;const n=this._localeService.t("formula.progress.analyzing");this._emitProgress(n)}_calculateProgress(n){if(this._executionInProgressParams){const{totalFormulasToCalculate:a,completedFormulasCount:i,totalArrayFormulasToCalculate:o,completedArrayFormulasCount:u}=this._executionInProgressParams;if(this._doneCalculationTaskCount=i+u,this._totalCalculationTaskCount=a+o,this._totalCalculationTaskCount===0)return;this._emitProgress(n)}}_completeProgress(){this._doneCalculationTaskCount=this._totalCalculationTaskCount=1;const n=this._localeService.t("formula.progress.done");this._emitProgress(n)}clearProgress(){this._doneCalculationTaskCount=0,this._totalCalculationTaskCount=0,this._emitProgress()}dispose(){super.dispose(),this._progress$.next(ye),this._progress$.complete(),clearTimeout(this._setTimeoutKey)}_getCalculationMode(){var a;const n=this._configService.getConfig(ee);return(a=n==null?void 0:n.initialFormulaComputing)!=null?a:w.WHEN_EMPTY}_commandExecutedListener(){this.disposeWithMe(this._commandService.beforeCommandExecuted(n=>{if(n.id===e.SetFormulaCalculationStartMutation.id){const a=n.params;a.rowData=this._formulaDataModel.getHiddenRowsFiltered()}})),this.disposeWithMe(this._commandService.onCommandExecuted((n,a)=>{if(this._activeDirtyManagerService.get(n.id)){if(n.id===l.SetRangeValuesMutation.id){const i=n.params;if(a&&a.onlyLocal===!0||i.trigger===l.SetStyleCommand.id||i.trigger===l.SetBorderCommand.id||i.trigger===l.ClearSelectionFormatCommand.id)return}this._waitingCommandQueue.push(n),clearTimeout(this._setTimeoutKey),this._setTimeoutKey=setTimeout(()=>{const i=this._generateDirty(this._waitingCommandQueue);this._executingDirtyData=this._mergeDirty(this._executingDirtyData,i),this._executionInProgressParams==null?this._commandService.executeCommand(e.SetFormulaCalculationStartMutation.id,{...this._executingDirtyData},Ae):(this._restartCalculation=!0,this._commandService.executeCommand(e.SetFormulaCalculationStopMutation.id,{})),this._waitingCommandQueue=[]},100)}}))}_generateDirty(n){const a=[],i={},o={},u={},m={},f={};for(const s of n){const d=this._activeDirtyManagerService.get(s.id);if(d==null)continue;const T=d.getDirtyData(s),{dirtyRanges:N,dirtyNameMap:L,dirtyDefinedNameMap:A,dirtyUnitFeatureMap:S,dirtyUnitOtherFormulaMap:C,clearDependencyTreeCache:p}=T;N!=null&&this._mergeDirtyRanges(a,N),L!=null&&this._mergeDirtyNameMap(i,L),A!=null&&this._mergeDirtyNameMap(o,A),S!=null&&this._mergeDirtyUnitFeatureOrOtherFormulaMap(u,S),C!=null&&this._mergeDirtyUnitFeatureOrOtherFormulaMap(m,C),p!=null&&this._mergeDirtyNameMap(f,p)}return{dirtyRanges:a,dirtyNameMap:i,dirtyDefinedNameMap:o,dirtyUnitFeatureMap:u,dirtyUnitOtherFormulaMap:m,forceCalculation:!1,clearDependencyTreeCache:f,maxIteration:this._configService.getConfig(e.ENGINE_FORMULA_CYCLE_REFERENCE_COUNT)}}_mergeDirty(n,a){const i=[...n.dirtyRanges,...a.dirtyRanges],o={...n.dirtyNameMap},u={...n.dirtyDefinedNameMap},m={...n.dirtyUnitFeatureMap},f={...n.dirtyUnitOtherFormulaMap},s={...n.clearDependencyTreeCache};this._mergeDirtyNameMap(o,a.dirtyNameMap),this._mergeDirtyNameMap(u,a.dirtyDefinedNameMap),this._mergeDirtyUnitFeatureOrOtherFormulaMap(m,a.dirtyUnitFeatureMap),this._mergeDirtyUnitFeatureOrOtherFormulaMap(f,a.dirtyUnitOtherFormulaMap),this._mergeDirtyNameMap(s,a.clearDependencyTreeCache);const d=n.maxIteration||a.maxIteration;return{dirtyRanges:i,dirtyNameMap:o,dirtyDefinedNameMap:u,dirtyUnitFeatureMap:m,dirtyUnitOtherFormulaMap:f,forceCalculation:!!this._forceCalculating,clearDependencyTreeCache:s,maxIteration:d}}_mergeDirtyRanges(n,a){for(const i of a){let o=!1;for(const u of n)if(i.unitId===u.unitId&&i.sheetId===u.sheetId){const{startRow:m,startColumn:f,endRow:s,endColumn:d}=i.range,{startRow:T,startColumn:N,endRow:L,endColumn:A}=u.range;if(m===T&&f===N&&s===L&&d===A){o=!0;break}}o||n.push(i)}}_mergeDirtyNameMap(n,a){Object.keys(a).forEach(i=>{n[i]==null&&(n[i]={}),Object.keys(a[i]).forEach(o=>{var u;(u=a[i])!=null&&u[o]&&(n[i][o]=a[i][o])})})}_mergeDirtyUnitFeatureOrOtherFormulaMap(n,a){Object.keys(a).forEach(i=>{n[i]==null&&(n[i]={}),Object.keys(a[i]).forEach(o=>{n[i][o]==null&&(n[i][o]={}),Object.keys(a[i][o]).forEach(u=>{n[i][o][u]=a[i][o][u]||!1})})})}_initialExecuteFormulaProcessListener(){let n=null,a=0;this.disposeWithMe(this._commandService.onCommandExecuted(i=>{if(i.id===e.SetFormulaCalculationStartMutation.id){const{forceCalculation:u=!1}=i.params;u&&(this._forceCalculating=!0)}else i.id===e.SetFormulaCalculationStopMutation.id&&this.clearProgress();if(i.id!==e.SetFormulaCalculationNotificationMutation.id)return;const o=i.params;if(o.stageInfo!=null){const{stage:u}=o.stageInfo;if(u===e.FormulaExecuteStageType.START)a===0&&(this._startExecutionTime=performance.now()),a++,n!==null&&(clearTimeout(n),n=null),n=setTimeout(()=>{n=null,this._startProgress()},1e3);else if(u===e.FormulaExecuteStageType.CURRENTLY_CALCULATING){if(this._executionInProgressParams=o.stageInfo,n===null){const m=this._localeService.t("formula.progress.calculating");this._calculateProgress(m)}}else if(u===e.FormulaExecuteStageType.START_DEPENDENCY_ARRAY_FORMULA){if(this._executionInProgressParams=o.stageInfo,n===null){const m=this._localeService.t("formula.progress.array-analysis");this._calculateProgress(m)}}else if(u===e.FormulaExecuteStageType.CURRENTLY_CALCULATING_ARRAY_FORMULA&&(this._executionInProgressParams=o.stageInfo,n===null)){const m=this._localeService.t("formula.progress.array-calculation");this._calculateProgress(m)}}else{const u=o.functionsExecutedState;let m="";switch(a--,u){case e.FormulaExecutedStateType.NOT_EXECUTED:m="No tasks are being executed anymore",this._resetExecutingDirtyData();break;case e.FormulaExecutedStateType.STOP_EXECUTION:m="The execution of the formula has been stopped",a=0;break;case e.FormulaExecutedStateType.SUCCESS:m="Formula calculation succeeded",(a===0||a===-1)&&(m+=`. Total time consumed: ${performance.now()-this._startExecutionTime} ms`),this._resetExecutingDirtyData();break;case e.FormulaExecutedStateType.INITIAL:m="Waiting for calculation",this._resetExecutingDirtyData();break}(a===0||a===-1)&&(n?(clearTimeout(n),n=null,this.clearProgress()):this._completeProgress(),a=0,this._doneCalculationTaskCount=0,this._totalCalculationTaskCount=0,this._forceCalculating=!1),u===e.FormulaExecutedStateType.STOP_EXECUTION&&this._restartCalculation?(this._restartCalculation=!1,this._commandService.executeCommand(e.SetFormulaCalculationStartMutation.id,{...this._executingDirtyData},Ae)):this._executionInProgressParams=null,this._logService.debug("[TriggerCalculationController]",m)}}))}_resetExecutingDirtyData(){this._executingDirtyData={dirtyRanges:[],dirtyNameMap:{},dirtyDefinedNameMap:{},dirtyUnitFeatureMap:{},dirtyUnitOtherFormulaMap:{},forceCalculation:!1,clearDependencyTreeCache:{}}}_initialExecuteFormula(){const n=this._getCalculationMode(),a=this._getDirtyDataByCalculationMode(n);this._commandService.executeCommand(e.SetFormulaCalculationStartMutation.id,a,Ae),this._registerOtherFormulaService.calculateStarted$.next(!0)}_getDirtyDataByCalculationMode(n){const a=n===w.FORCED,i=n===w.WHEN_EMPTY?this._formulaDataModel.getFormulaDirtyRanges():[];return{forceCalculation:a,dirtyRanges:i,dirtyNameMap:{},dirtyDefinedNameMap:{},dirtyUnitFeatureMap:{},dirtyUnitOtherFormulaMap:{},clearDependencyTreeCache:{},maxIteration:this._configService.getConfig(e.ENGINE_FORMULA_CYCLE_REFERENCE_COUNT)}}};exports.TriggerCalculationController=Qe([Q(0,c.ICommandService),Q(1,e.IActiveDirtyManagerService),Q(2,c.ILogService),Q(3,c.IConfigService),Q(4,c.Inject(e.FormulaDataModel)),Q(5,c.Inject(c.LocaleService)),Q(6,c.Inject(exports.RegisterOtherFormulaService))],exports.TriggerCalculationController);function je(r,t,n){var a;return r==null||r[t]==null||((a=r[t])==null?void 0:a[n])==null}function Se(r,t,n){var a;if(n){if(r&&r[t]&&((a=r[t])!=null&&a[n]))return delete r[t][n],{[t]:{[n]:null}}}else if(r&&r[t])return delete r[t],{[t]:null}}var D=(r=>(r[r.MoveRange=0]="MoveRange",r[r.MoveRows=1]="MoveRows",r[r.MoveCols=2]="MoveCols",r[r.InsertRow=3]="InsertRow",r[r.InsertColumn=4]="InsertColumn",r[r.RemoveRow=5]="RemoveRow",r[r.RemoveColumn=6]="RemoveColumn",r[r.DeleteMoveLeft=7]="DeleteMoveLeft",r[r.DeleteMoveUp=8]="DeleteMoveUp",r[r.InsertMoveDown=9]="InsertMoveDown",r[r.InsertMoveRight=10]="InsertMoveRight",r[r.SetName=11]="SetName",r[r.RemoveSheet=12]="RemoveSheet",r[r.SetDefinedName=13]="SetDefinedName",r[r.RemoveDefinedName=14]="RemoveDefinedName",r))(D||{});const $e=[11,12,13,14];function ze(r,t,n){const{type:a}=n;return $e.includes(a)?Ze(r,t):Je(r,t,n)}function Ze(r,t){const n=[],a=[];return Object.keys(t).forEach(i=>{const o=t[i],u=r[i];if(o==null||u==null)return!0;Object.keys(o).forEach(m=>{const f=new c.ObjectMatrix(o[m]||{}),s=new c.ObjectMatrix(u[m]||{}),d=new c.ObjectMatrix,T=new c.ObjectMatrix;if(f.forValue((C,p,I)=>{if(I==null)return!0;const E=ae(I);E!==null&&(d.setValue(C,p,E),T.setValue(C,p,s.getValue(C,p)))}),d.getSizeOf()===0)return;const N={subUnitId:m,unitId:i,cellValue:d.getMatrix()},L={id:l.SetRangeValuesMutation.id,params:N};a.push(L);const A={subUnitId:m,unitId:i,cellValue:T.getMatrix()},S={id:l.SetRangeValuesMutation.id,params:A};n.push(S)})}),{undos:n,redos:a}}function Je(r,t,n){const{redoFormulaData:a,undoFormulaData:i}=et(r,t,n),o=[],u=[];return Object.keys(a).forEach(m=>{Object.keys(a[m]).forEach(f=>{if(Object.keys(a[m][f]).length!==0){const s={subUnitId:f,unitId:m,cellValue:a[m][f]},d={id:l.SetRangeValuesMutation.id,params:s};o.push(d)}})}),Object.keys(i).forEach(m=>{Object.keys(i[m]).forEach(f=>{if(Object.keys(i[m][f]).length!==0){const s={subUnitId:f,unitId:m,cellValue:i[m][f]},d={id:l.SetRangeValuesMutation.id,params:s};u.push(d)}})}),{undos:u,redos:o}}function et(r,t,n){const a={},i={},{unitId:o,sheetId:u}=n;return new Set([...Object.keys(r),...Object.keys(t)]).forEach(f=>{if(je(r,f,u))return;new Set([...Object.keys(r[f]||{}),...Object.keys(t[f]||{})]).forEach(d=>{var I,E;const T=(I=r[f])==null?void 0:I[d],N=(E=t[f])==null?void 0:E[d],L=new c.ObjectMatrix(T||{}),A=new c.ObjectMatrix(N||{});let S=[];f!==o||d!==u?S=nt(A):S=tt(L,A,n);const C=Tt(S,L,A),p=Nt(S,L);a[f]||(a[f]={}),i[f]||(i[f]={}),a[f][d]={...a[f][d],...C},i[f][d]={...i[f][d],...p}})}),{redoFormulaData:a,undoFormulaData:i}}function tt(r,t,n){const{type:a,from:i,to:o,range:u}=n,m=[];return r.forValue((f,s,d)=>{if(d==null||!qe(d))return!0;const T=c.cellToRange(f,s);let N=null,L=!1;if([0,1,2].includes(a))N=at(a,i,o,T);else if(u!=null){const A=it(T,n);N=A.newCell,L=A.isReverse}if(c.Tools.diffValue(T,N)&&!t.getValue(f,s))return!0;L?m.unshift({oldCell:T,newCell:N}):m.push({oldCell:T,newCell:N})}),m}function nt(r){const t=[];return r.forValue((n,a,i)=>{if(i==null||!qe(i))return!0;const o=c.cellToRange(n,a);t.push({oldCell:o,newCell:o})}),t}function at(r,t,n,a){if(t==null||n==null)return null;switch(r){case 0:return rt(t,n,a);case 1:return ot(t,n,a);case 2:return ut(t,n,a);default:return null}}function it(r,t){const{type:n,rangeFilteredRows:a}=t,i=t.range;let o=null,u=!1;switch(n){case 3:o=mt(i,r),u=!0;break;case 4:o=ct(i,r),u=!0;break;case 5:o=ft(i,r,a);break;case 6:o=lt(i,r);break;case 7:o=st(i,r);break;case 8:o=pt(i,r);break;case 9:o=dt(i,r),u=!0;break;case 10:o=Lt(i,r),u=!0;break}return{newCell:o,isReverse:u}}function rt(r,t,n){const a=l.handleMoveRange({id:l.EffectRefRangId.MoveRangeCommandId,params:{toRange:t,fromRange:r}},n);return l.runRefRangeMutations(a,n)}function ot(r,t,n){const a=l.handleMoveRows({id:l.EffectRefRangId.MoveRowsCommandId,params:{toRange:t,fromRange:r}},n);return l.runRefRangeMutations(a,n)}function ut(r,t,n){const a=l.handleMoveCols({id:l.EffectRefRangId.MoveColsCommandId,params:{toRange:t,fromRange:r}},n);return l.runRefRangeMutations(a,n)}function mt(r,t){const n=l.handleInsertRow({id:l.EffectRefRangId.InsertRowCommandId,params:{range:r,unitId:"",subUnitId:"",direction:c.Direction.DOWN}},t);return l.runRefRangeMutations(n,t)}function ct(r,t){const n=l.handleInsertCol({id:l.EffectRefRangId.InsertColCommandId,params:{range:r,unitId:"",subUnitId:"",direction:c.Direction.RIGHT}},t);return l.runRefRangeMutations(n,t)}function ft(r,t,n){const a=l.handleIRemoveRow({id:l.EffectRefRangId.RemoveRowCommandId,params:{range:r}},t,n);return l.runRefRangeMutations(a,t)}function lt(r,t){const n=l.handleIRemoveCol({id:l.EffectRefRangId.RemoveColCommandId,params:{range:r}},t);return l.runRefRangeMutations(n,t)}function st(r,t){const n=l.handleDeleteRangeMoveLeft({id:l.EffectRefRangId.DeleteRangeMoveLeftCommandId,params:{range:r}},t);return l.runRefRangeMutations(n,t)}function pt(r,t){const n=l.handleDeleteRangeMoveUp({id:l.EffectRefRangId.DeleteRangeMoveUpCommandId,params:{range:r}},t);return l.runRefRangeMutations(n,t)}function dt(r,t){const n=l.handleInsertRangeMoveDown({id:l.EffectRefRangId.InsertRangeMoveDownCommandId,params:{range:r}},t);return l.runRefRangeMutations(n,t)}function Lt(r,t){const n=l.handleInsertRangeMoveRight({id:l.EffectRefRangId.InsertRangeMoveRightCommandId,params:{range:r}},t);return l.runRefRangeMutations(n,t)}function Tt(r,t,n){var i,o,u;const a=new c.ObjectMatrix({});for(let m=0;m<r.length;m++){const{oldCell:f,newCell:s}=r[m];if((i=a.getValue(f.startRow,f.startColumn))!=null&&i.f||(o=a.getValue(f.startRow,f.startColumn))!=null&&o.si||a.setValue(f.startRow,f.startColumn,{f:null,si:null}),s){const d=(u=n.getValue(f.startRow,f.startColumn))!=null?u:t.getValue(f.startRow,f.startColumn),T=ae(d);a.setValue(s.startRow,s.startColumn,T)}}return a.getMatrix()}function Nt(r,t){const n=new c.ObjectMatrix({});for(let a=r.length-1;a>=0;a--){const{oldCell:i,newCell:o}=r[a],u=t.getValue(i.startRow,i.startColumn),m=ae(u);if(n.setValue(i.startRow,i.startColumn,m),o){const f=t.getValue(o.startRow,o.startColumn),s=ae(f);n.setValue(o.startRow,o.startColumn,s!=null?s:{f:null,si:null})}}return n.getMatrix()}function ae(r){if(r==null)return;const{f:t,si:n,x:a=0,y:i=0}=r,o=c.isFormulaString(t),u=c.isFormulaId(n);if(!o&&!u)return{f:null,si:null};const m={};return u&&(m.si=n),o&&a===0&&i===0&&(m.f=t),m.f===void 0&&(m.f=null),m.si===void 0&&(m.si=null),m}function Pt(r){const t=new c.ObjectMatrix({});return new c.ObjectMatrix(r).forValue((a,i,o)=>{const u=ae(o);u&&t.setValue(a,i,u)}),t.getMatrix()}function qe(r){const t=(r==null?void 0:r.f)||"",n=(r==null?void 0:r.si)||"",a=c.isFormulaString(t),i=c.isFormulaId(n);return!!(a||i)}function he(r,t,n,a,i,o){if((i==null||i.length===0)&&(o==null||o.length===0)){if(r===n&&t===a)return!0}else if((r===i||i==null||i.length===0)&&t===o)return!0;return!1}function Be(r,t,n=0,a=0){const i=[];for(let o=0,u=r.length;o<u;o++){const m=r[o];if(typeof m=="string"||m.nodeType!==e.sequenceNodeType.REFERENCE||t.includes(o)){i.push(m);continue}const{token:f}=m,s=e.deserializeRangeWithSheetWithCache(f),{range:d,sheetName:T,unitId:N}=s,L=c.Rectangle.moveOffset(d,n,a);i.push({...m,token:e.serializeRangeToRefString({range:L,unitId:N,sheetName:T})})}return i}function ve(r,t,n,a){const{type:i,unitId:o,sheetId:u,range:m,from:f,to:s,rangeFilteredRows:d}=t,{range:T,sheetId:N,unitId:L,sheetName:A,refOffsetX:S,refOffsetY:C}=r;if(!he(o,u,n,a,L,N))return;const p=c.Rectangle.moveOffset(T,S,C);let I=null;if(i===D.MoveRange){if(f==null||s==null)return;const E=Re(p,f),P=c.getIntersectRange(p,f);if(P==null||E!==4)return;const R=l.handleMoveRange({id:l.EffectRefRangId.MoveRangeCommandId,params:{toRange:s,fromRange:f}},P),F=l.runRefRangeMutations(R,P);if(F==null)return e.ErrorType.REF;I=Ce(E,F,f,s,p,P)}else if(i===D.MoveRows){if(f==null||s==null)return;const E=Re(p,f);let P=c.getIntersectRange(p,f);if(P==null&&(f.endRow<p.startRow&&s.endRow<=p.startRow||f.startRow>p.endRow&&s.startRow>p.endRow))return;P==null&&(P={startRow:p.startRow,endRow:p.endRow,startColumn:p.startColumn,endColumn:p.endColumn,rangeType:c.RANGE_TYPE.NORMAL});const R=l.handleMoveRows({id:l.EffectRefRangId.MoveRowsCommandId,params:{toRange:s,fromRange:f}},P),F=l.runRefRangeMutations(R,P);if(F==null)return e.ErrorType.REF;I=Ce(E,F,f,s,p,P)}else if(i===D.MoveCols){if(f==null||s==null)return;const E=Re(p,f);let P=c.getIntersectRange(p,f);if(P==null&&(f.endColumn<p.startColumn&&s.endColumn<=p.startColumn||f.startColumn>p.endColumn&&s.startColumn>p.endColumn))return;P==null&&(P={startRow:p.startRow,endRow:p.endRow,startColumn:p.startColumn,endColumn:p.endColumn,rangeType:c.RANGE_TYPE.NORMAL});const R=l.handleMoveCols({id:l.EffectRefRangId.MoveColsCommandId,params:{toRange:s,fromRange:f}},P),F=l.runRefRangeMutations(R,P);if(F==null)return e.ErrorType.REF;I=Ce(E,F,f,s,p,P)}if(m!=null){if(i===D.InsertRow){const E=l.handleInsertRow({id:l.EffectRefRangId.InsertRowCommandId,params:{range:m,unitId:"",subUnitId:"",direction:c.Direction.DOWN}},p),P=l.runRefRangeMutations(E,p);if(P==null)return;I={...p,...P}}else if(i===D.InsertColumn){const E=l.handleInsertCol({id:l.EffectRefRangId.InsertColCommandId,params:{range:m,unitId:"",subUnitId:"",direction:c.Direction.RIGHT}},p),P=l.runRefRangeMutations(E,p);if(P==null)return;I={...p,...P}}else if(i===D.RemoveRow){const E=l.handleIRemoveRow({id:l.EffectRefRangId.RemoveRowCommandId,params:{range:m}},p,d),P=l.runRefRangeMutations(E,p);if(P==null)return e.ErrorType.REF;I={...p,...P}}else if(i===D.RemoveColumn){const E=l.handleIRemoveCol({id:l.EffectRefRangId.RemoveColCommandId,params:{range:m}},p),P=l.runRefRangeMutations(E,p);if(P==null)return e.ErrorType.REF;I={...p,...P}}else if(i===D.DeleteMoveLeft){const E=l.handleDeleteRangeMoveLeft({id:l.EffectRefRangId.DeleteRangeMoveLeftCommandId,params:{range:m}},p),P=l.runRefRangeMutations(E,p);if(P==null)return e.ErrorType.REF;I={...p,...P}}else if(i===D.DeleteMoveUp){const E=l.handleDeleteRangeMoveUp({id:l.EffectRefRangId.DeleteRangeMoveUpCommandId,params:{range:m}},p),P=l.runRefRangeMutations(E,p);if(P==null)return e.ErrorType.REF;I={...p,...P}}else if(i===D.InsertMoveDown){const E=l.handleInsertRangeMoveDown({id:l.EffectRefRangId.InsertRangeMoveDownCommandId,params:{range:m}},p),P=l.runRefRangeMutations(E,p);if(P==null)return;I={...p,...P}}else if(i===D.InsertMoveRight){const E=l.handleInsertRangeMoveRight({id:l.EffectRefRangId.InsertRangeMoveRightCommandId,params:{range:m}},p),P=l.runRefRangeMutations(E,p);if(P==null)return;I={...p,...P}}}if(I!=null)return e.serializeRangeToRefString({range:I,sheetName:A,unitId:L})}function Ce(r,t,n,a,i,o){const{startRow:u,endRow:m,startColumn:f,endColumn:s,rangeType:d}=ne(t),{startRow:T,startColumn:N,endRow:L,endColumn:A,rangeType:S=c.RANGE_TYPE.NORMAL}=ne(n),{startRow:C,startColumn:p,endRow:I,endColumn:E}=ne(a),{startRow:P,endRow:R,startColumn:F,endColumn:x}=ne(o),{startRow:M,endRow:b,startColumn:_,endColumn:y,rangeType:U=c.RANGE_TYPE.NORMAL}=ne(i),O={...i};function q(){return d===c.RANGE_TYPE.COLUMN&&U===c.RANGE_TYPE.COLUMN?!0:f>=_&&s<=y}function X(){return d===c.RANGE_TYPE.ROW&&U===c.RANGE_TYPE.ROW?!0:u>=M&&m<=b}if(r===0)if(q())if(u<M)O.startRow=u;else if(u>=b)O.endRow-=L+1-M;else return;else return;else if(r===1)if(q())if(m>b)O.endRow=m;else if(m<=M)O.startRow+=b-T+1;else return;else return;else if(r===2)if(X())if(f<_)O.startColumn=f;else if(f>=y)O.endColumn-=A+1-_;else return;else return;else if(r===3)if(X())if(s>y)O.endColumn=s;else if(s<=_)O.startColumn+=y-N+1;else return;else return;else r===4?(O.startRow=u,O.startColumn=f,O.endRow=m,O.endColumn=s):N<=_&&A>=y||S===c.RANGE_TYPE.ROW&&U===c.RANGE_TYPE.ROW?n.endRow<M?(C>=M&&(O.startRow-=L-T+1),C>=b&&(O.endRow-=L-T+1)):n.startRow>b?(I<=b&&(O.endRow+=L-T+1),I<=M&&(O.startRow+=L-T+1)):n.startRow>=M&&n.endRow<=b&&(C<=M?O.startRow+=L-T+1:C>=b&&(O.endRow-=L-T+1)):T<=M&&L>=b||S===c.RANGE_TYPE.COLUMN&&U===c.RANGE_TYPE.COLUMN?n.endColumn<_?(p>=_&&(O.startColumn-=A-N+1),p>=y&&(O.endColumn-=A-N+1)):n.startColumn>y?(E<=y&&(O.endColumn+=A-N+1),E<=_&&(O.startColumn+=A-N+1)):n.startColumn>=_&&n.endColumn<=y&&(p<=_?O.startColumn+=A-N+1:p>=y&&(O.endColumn-=A-N+1)):((p<=x+1&&E>=y||p<=_&&E>=F-1)&&C<=M&&I>=b||(C<=R+1&&I>=b||C<=M&&I>=P-1)&&p<=_&&E>=y,O.startRow=u,O.startColumn=f,O.endRow=m,O.endColumn=s);return O}function Re(r,t){const n=Z(r.startRow),a=J(r.endRow),i=Z(r.startColumn),o=J(r.endColumn),u=Z(t.startRow),m=J(t.endRow),f=Z(t.startColumn),s=J(t.endColumn);function d(){return r.rangeType===c.RANGE_TYPE.COLUMN&&t.rangeType===c.RANGE_TYPE.COLUMN?!0:n>=u&&a<=m}function T(){return r.rangeType===c.RANGE_TYPE.ROW&&t.rangeType===c.RANGE_TYPE.ROW?!0:i>=f&&o<=s}function N(){return r.rangeType===c.RANGE_TYPE.ALL&&t.rangeType===c.RANGE_TYPE.ALL}return d()&&T()||N()?4:T()&&n>=u&&n<=m&&a>m?0:T()&&a>=u&&a<=m&&n<u?1:d()&&i>=f&&i<=s&&o>s?2:d()&&o>=f&&o<=s&&i<f?3:null}function Z(r){return isNaN(r)?-1/0:r}function J(r){return isNaN(r)?1/0:r}function ne(r){const{startRow:t,endRow:n,startColumn:a,endColumn:i}=r;return{...r,startRow:Z(t),endRow:J(n),startColumn:Z(a),endColumn:J(i)}}function Ve(r,t){const{id:n}=t;let a=null;switch(n){case l.MoveRangeCommand.id:a=Et(t,r);break;case l.MoveRowsCommand.id:a=It(t,r);break;case l.MoveColsCommand.id:a=At(t,r);break;case l.InsertRowCommand.id:a=St(t);break;case l.InsertColCommand.id:a=Ct(t);break;case l.InsertRangeMoveRightCommand.id:a=Rt(t,r);break;case l.InsertRangeMoveDownCommand.id:a=Ot(t,r);break;case l.RemoveRowCommand.id:a=Mt(t,r);break;case l.RemoveColCommand.id:a=_t(t,r);break;case l.DeleteRangeMoveUpCommand.id:a=Dt(t,r);break;case l.DeleteRangeMoveLeftCommand.id:a=Ft(t,r);break;case l.SetWorksheetNameCommand.id:a=bt(t,r);break;case l.RemoveSheetCommand.id:a=yt(t,r);break;case l.SetDefinedNameCommand.id:a=xt(t,r);break;case l.RemoveDefinedNameCommand.id:a=Ut(t,r);break}return a}function v(r){var a;const t=r.getUnitId(),n=((a=r.getActiveSheet())==null?void 0:a.getSheetId())||"";return{unitId:t,sheetId:n}}function Et(r,t){const{params:n}=r;if(!n)return null;const{fromRange:a,toRange:i}=n;if(!a||!i)return null;const{unitId:o,sheetId:u}=v(t);return{type:D.MoveRange,from:a,to:i,unitId:o,sheetId:u}}function It(r,t){const{params:n}=r;if(!n)return null;const{fromRange:{startRow:a,endRow:i},toRange:{startRow:o,endRow:u}}=n,m=t.getUnitId(),f=t.getActiveSheet();if(!f)return null;const s=f.getSheetId(),d={startRow:a,startColumn:0,endRow:i,endColumn:f.getColumnCount()-1,rangeType:c.RANGE_TYPE.ROW},T={startRow:o,startColumn:0,endRow:u,endColumn:f.getColumnCount()-1,rangeType:c.RANGE_TYPE.ROW};return{type:D.MoveRows,from:d,to:T,unitId:m,sheetId:s}}function At(r,t){const{params:n}=r;if(!n)return null;const{fromRange:{startColumn:a,endColumn:i},toRange:{startColumn:o,endColumn:u}}=n,m=t.getUnitId(),f=t.getActiveSheet();if(!f)return null;const s=f.getSheetId(),d={startRow:0,startColumn:a,endRow:f.getRowCount()-1,endColumn:i,rangeType:c.RANGE_TYPE.COLUMN},T={startRow:0,startColumn:o,endRow:f.getRowCount()-1,endColumn:u,rangeType:c.RANGE_TYPE.COLUMN};return{type:D.MoveCols,from:d,to:T,unitId:m,sheetId:s}}function St(r){const{params:t}=r;if(!t)return null;const{range:n,unitId:a,subUnitId:i}=t;return{type:D.InsertRow,range:n,unitId:a,sheetId:i}}function Ct(r){const{params:t}=r;if(!t)return null;const{range:n,unitId:a,subUnitId:i}=t;return{type:D.InsertColumn,range:n,unitId:a,sheetId:i}}function Rt(r,t){const{params:n}=r;if(!n)return null;const{range:a}=n,{unitId:i,sheetId:o}=v(t);return{type:D.InsertMoveRight,range:a,unitId:i,sheetId:o}}function Ot(r,t){const{params:n}=r;if(!n)return null;const{range:a}=n,{unitId:i,sheetId:o}=v(t);return{type:D.InsertMoveDown,range:a,unitId:i,sheetId:o}}function Mt(r,t){var u,m;const{params:n}=r;if(!n)return null;const{range:a}=n,{unitId:i,sheetId:o}=v(t);return{type:D.RemoveRow,range:a,unitId:i,sheetId:o,rangeFilteredRows:(m=(u=t.getSheetBySheetId(o))==null?void 0:u.getRangeFilterRows(a))!=null?m:[]}}function _t(r,t){const{params:n}=r;if(!n)return null;const{range:a}=n,{unitId:i,sheetId:o}=v(t);return{type:D.RemoveColumn,range:a,unitId:i,sheetId:o}}function Dt(r,t){const{params:n}=r;if(!n)return null;const{range:a}=n,{unitId:i,sheetId:o}=v(t);return{type:D.DeleteMoveUp,range:a,unitId:i,sheetId:o}}function Ft(r,t){const{params:n}=r;if(!n)return null;const{range:a}=n,{unitId:i,sheetId:o}=v(t);return{type:D.DeleteMoveLeft,range:a,unitId:i,sheetId:o}}function bt(r,t){const{params:n}=r;if(!n)return null;const{unitId:a,subUnitId:i,name:o}=n,{unitId:u,sheetId:m}=v(t);return{type:D.SetName,unitId:a||u,sheetId:i||m,sheetName:o}}function yt(r,t){const{params:n}=r;if(!n)return null;const{unitId:a,subUnitId:i}=n,{unitId:o,sheetId:u}=v(t);return{type:D.RemoveSheet,unitId:a||o,sheetId:i||u}}function xt(r,t){const{params:n}=r;if(!n)return null;const{unitId:a,name:i,id:o}=n,{sheetId:u}=v(t);return{type:D.SetDefinedName,unitId:a,sheetId:u,definedName:i,definedNameId:o}}function Ut(r,t){const{params:n}=r;if(!n)return null;const{unitId:a,name:i,id:o}=n,{sheetId:u}=v(t);return{type:D.RemoveDefinedName,unitId:a,sheetId:u,definedName:i,definedNameId:o}}var gt=Object.getOwnPropertyDescriptor,qt=(r,t,n,a)=>{for(var i=a>1?void 0:a?gt(t,n):t,o=r.length-1,u;o>=0;o--)(u=r[o])&&(i=u(i)||i);return i},oe=(r,t)=>(n,a)=>t(n,a,r);exports.UpdateDefinedNameController=class extends c.Disposable{constructor(t,n,a,i){super(),this._definedNamesService=t,this._univerInstanceService=n,this._sheetInterceptorService=a,this._lexerTreeBuilder=i,this._initialize()}_initialize(){this._commandExecutedListener()}_commandExecutedListener(){this.disposeWithMe(this._sheetInterceptorService.interceptCommand({getMutations:t=>{if(t.id===l.SetDefinedNameCommand.id||t.id===l.RemoveDefinedNameCommand.id)return{redos:[],undos:[]};const n=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET);if(n==null)return{redos:[],undos:[]};const a=Ve(n,t);return a?this._getUpdateDefinedNameMutations(n,a):{redos:[],undos:[]}}}))}_getUpdateDefinedNameMutations(t,n){const{type:a,unitId:i,sheetId:o}=n,u=this._definedNamesService.getDefinedNameMap(i);if(!u)return{redos:[],undos:[]};const m=[],f=[];return Object.values(u).forEach(s=>{var p;const{formulaOrRefString:d}=s,T=this._lexerTreeBuilder.sequenceNodesBuilder(d);if(T==null)return!0;let N=!1;const L=[];for(let I=0,E=T.length;I<E;I++){const P=T[I];if(typeof P=="string"||P.nodeType!==e.sequenceNodeType.REFERENCE)continue;const{token:R}=P,F=e.deserializeRangeWithSheetWithCache(R),{range:x,sheetName:M,unitId:b}=F,_=((p=t.getSheetBySheetName(M))==null?void 0:p.getSheetId())||"",y={range:x,sheetId:_,unitId:b,sheetName:M,refOffsetX:0,refOffsetY:0};let U=null;if(a===D.RemoveSheet)U=this._removeSheet(s,i,o);else if(a===D.SetName){const{sheetId:O,sheetName:q}=n;if(q==null||_==null||_.length===0||O!==_)continue;U=e.serializeRangeToRefString({range:x,sheetName:q,unitId:b})}else U=ve(y,n,i,o);U!=null&&(T[I]={...P,token:U},N=!0,L.push(I))}if(!N)return!0;const A=e.generateStringWithSequence(Be(T,L)),S={id:e.SetDefinedNameMutation.id,params:{unitId:i,...s,formulaOrRefString:A}};m.push(S);const C={id:e.SetDefinedNameMutation.id,params:{unitId:i,...s}};f.push(C)}),{redos:m,undos:f}}_removeSheet(t,n,a){var u;const{formulaOrRefString:i}=t;return((u=this._definedNamesService.getWorksheetByRef(n,i))==null?void 0:u.getSheetId())===a?e.ErrorType.REF:null}};exports.UpdateDefinedNameController=qt([oe(0,e.IDefinedNamesService),oe(1,c.IUniverInstanceService),oe(2,c.Inject(l.SheetInterceptorService)),oe(3,c.Inject(e.LexerTreeBuilder))],exports.UpdateDefinedNameController);var ht=Object.getOwnPropertyDescriptor,Bt=(r,t,n,a)=>{for(var i=a>1?void 0:a?ht(t,n):t,o=r.length-1,u;o>=0;o--)(u=r[o])&&(i=u(i)||i);return i},H=(r,t)=>(n,a)=>t(n,a,r);exports.UpdateFormulaController=class extends c.Disposable{constructor(t,n,a,i,o,u,m,f){super(),this._univerInstanceService=t,this._commandService=n,this._lexerTreeBuilder=a,this._formulaDataModel=i,this._sheetInterceptorService=o,this._definedNamesService=u,this._configService=m,this._injector=f,this._commandExecutedListener()}_commandExecutedListener(){this.disposeWithMe(this._sheetInterceptorService.interceptCommand({getMutations:t=>this._getUpdateFormula(t)})),this.disposeWithMe(this._commandService.onCommandExecuted(t=>{if(t.params)if(t.id===l.RemoveSheetMutation.id){const{subUnitId:n,unitId:a}=t.params;this._handleWorkbookDisposed(a,n)}else t.id===l.InsertSheetMutation.id&&this._handleInsertSheetMutation(t.params)})),this.disposeWithMe(this._commandService.beforeCommandExecuted((t,n)=>{if(t.id===l.SetRangeValuesMutation.id){const a=t.params;if(n&&n.onlyLocal===!0||a.trigger===l.SetStyleCommand.id||a.trigger===l.SetBorderCommand.id||a.trigger===l.ClearSelectionFormatCommand.id)return;this._handleSetRangeValuesMutation(a)}})),this.disposeWithMe(this._univerInstanceService.getTypeOfUnitAdded$(c.UniverInstanceType.UNIVER_SHEET).subscribe(t=>this._handleWorkbookAdded(t))),this.disposeWithMe(this._univerInstanceService.getTypeOfUnitDisposed$(c.UniverInstanceType.UNIVER_SHEET).pipe(Y.map(t=>t.getUnitId())).subscribe(t=>this._handleWorkbookDisposed(t)))}_handleSetRangeValuesMutation(t){const{subUnitId:n,unitId:a,cellValue:i}=t;if(i==null)return;const o=this._formulaDataModel.updateFormulaData(a,n,i),u={[a]:{[n]:o}};this._commandService.executeCommand(l.SetRangeValuesMutation.id,{unitId:a,subUnitId:n,cellValue:Pt(o)},{onlyLocal:!0,fromFormula:!0}),this._formulaDataModel.updateArrayFormulaCellData(a,n,i),this._formulaDataModel.updateArrayFormulaRange(a,n,i),this._commandService.executeCommand(e.SetFormulaDataMutation.id,{formulaData:u},{onlyLocal:!0}),this._commandService.executeCommand(e.SetArrayFormulaDataMutation.id,{arrayFormulaRange:this._formulaDataModel.getArrayFormulaRange(),arrayFormulaCellData:this._formulaDataModel.getArrayFormulaCellData()},{onlyLocal:!0,remove:!0})}_handleWorkbookDisposed(t,n){const a=this._formulaDataModel.getFormulaData(),i=Se(a,t,n),o=this._formulaDataModel.getArrayFormulaRange(),u=Se(o,t,n),m=this._formulaDataModel.getArrayFormulaCellData(),f=Se(m,t,n);i&&this._commandService.executeCommand(e.SetFormulaDataMutation.id,{formulaData:i},{onlyLocal:!0}),u&&f&&this._commandService.executeCommand(e.SetArrayFormulaDataMutation.id,{arrayFormulaRange:o,arrayFormulaCellData:m},{onlyLocal:!0})}_handleInsertSheetMutation(t){const{sheet:n,unitId:a}=t,i=this._formulaDataModel.getFormulaData(),{id:o,cellData:u}=n,m=new c.ObjectMatrix(u),f=e.initSheetFormulaData(i,a,o,m);this._commandService.executeCommand(e.SetFormulaDataMutation.id,{formulaData:f},{onlyLocal:!0})}_handleWorkbookAdded(t){var s;const n={},a=t.getUnitId(),i={[a]:{}};t.getSheets().forEach(d=>{var A;const T=d.getCellMatrix(),N=d.getSheetId(),L=e.initSheetFormulaData(n,a,N,T);i[a][N]=(A=L[a])==null?void 0:A[N]}),this._commandService.executeCommand(e.SetFormulaDataMutation.id,{formulaData:i},{onlyLocal:!0});const u=this._configService.getConfig(ee),m=(s=u==null?void 0:u.initialFormulaComputing)!=null?s:w.WHEN_EMPTY,f=this._getDirtyDataByCalculationMode(m);this._commandService.executeCommand(e.SetFormulaCalculationStartMutation.id,f,{onlyLocal:!0})}_getDirtyDataByCalculationMode(t){const n=t===w.FORCED,a=t===w.WHEN_EMPTY?this._formulaDataModel.getFormulaDirtyRanges():[];return{forceCalculation:n,dirtyRanges:a,dirtyNameMap:{},dirtyDefinedNameMap:{},dirtyUnitFeatureMap:{},dirtyUnitOtherFormulaMap:{},clearDependencyTreeCache:{}}}_getUpdateFormula(t){const n=this._univerInstanceService.getCurrentUnitForType(c.UniverInstanceType.UNIVER_SHEET);if(!n)return{undos:[],redos:[]};const a=Ve(n,t);if(a){const{unitSheetNameMap:i}=this._formulaDataModel.getCalculateData(),o=this._formulaDataModel.getFormulaData(),{newFormulaData:u}=this._getFormulaReferenceMoveInfo(o,i,a),{undos:m,redos:f}=ze(o,u,a);return{undos:m,redos:f}}return{undos:[],redos:[]}}_getFormulaReferenceMoveInfo(t,n,a){if(!c.Tools.isDefine(t))return{newFormulaData:{},oldFormulaData:{}};const i=Object.keys(t);if(i.length===0)return{newFormulaData:{},oldFormulaData:{}};const o={},u={};for(const m of i){const f=t[m];if(f==null)continue;const s=Object.keys(f);c.Tools.isDefine(o[m])||(o[m]={}),c.Tools.isDefine(u[m])||(u[m]={});for(const d of s){const T=new c.ObjectMatrix(f[d]||{}),N=new c.ObjectMatrix,L=[];T.forValue((A,S,C)=>{var y;if(!C)return!0;const{f:p,x:I,y:E,si:P}=C,R=this._lexerTreeBuilder.sequenceNodesBuilder(p);if(R==null)return!0;let F=!1;const x=[],{type:M,from:b}=a;for(let U=0,O=R.length;U<O;U++){const q=R[U];if(typeof q=="string")continue;const{token:X,nodeType:W}=q;if((M===D.SetDefinedName||M===D.RemoveDefinedName)&&(W===e.sequenceNodeType.DEFINED_NAME||W===e.sequenceNodeType.FUNCTION)){const{definedNameId:re,definedName:j}=a;if(re===void 0||j===void 0)continue;const k=this._definedNamesService.getValueById(m,re);if(k==null||k.name!==X)continue;R[U]={...q,token:M===D.SetDefinedName?j:e.ErrorType.REF},F=!0,x.push(U);continue}else if(W!==e.sequenceNodeType.REFERENCE)continue;const K=e.deserializeRangeWithSheetWithCache(X),{range:h,sheetName:V,unitId:G}=K,ie=G==null||G.length===0?m:G,B=((y=n==null?void 0:n[ie])==null?void 0:y[V])||"";if(!he(a.unitId,a.sheetId,m,d,G,B))continue;const Ee={range:h,sheetId:B,unitId:G,sheetName:V,refOffsetX:I||0,refOffsetY:E||0};let te=null;if(M===D.SetName){const{unitId:re,sheetId:j,sheetName:k}=a;if(k==null||B==null||B.length===0||j!==B)continue;te=e.serializeRangeToRefString({range:h,sheetName:k,unitId:G})}else if(M===D.RemoveSheet){const{unitId:re,sheetId:j,sheetName:k}=a;if(B==null||B.length===0||j!==B)continue;te=e.ErrorType.REF}else M!==D.SetDefinedName&&(te=ve(Ee,a,m,d));te!=null&&(R[U]={...q,token:te},F=!0,x.push(U),P&&(I!=null?I:0)===0&&(E!=null?E:0)===0&&L.push(P))}if(!F)if(P&&[D.MoveRows,D.MoveCols,D.MoveRange].includes(M)){if(b&&b.startRow<=A&&A<=b.endRow&&b.startColumn<=S&&S<=b.endColumn)(I!=null?I:0)===0&&(E!=null?E:0)===0&&L.push(P);else if(!L.includes(P))return!0}else return!0;const _=Be(R,x,I,E);N.setValue(A,S,{f:`=${e.generateStringWithSequence(_)}`})}),u[m]&&(u[m][d]=N.getData())}}return{newFormulaData:u}}};exports.UpdateFormulaController=Bt([H(0,c.IUniverInstanceService),H(1,c.ICommandService),H(2,c.Inject(e.LexerTreeBuilder)),H(3,c.Inject(e.FormulaDataModel)),H(4,c.Inject(l.SheetInterceptorService)),H(5,e.IDefinedNamesService),H(6,c.IConfigService),H(7,c.Inject(c.Injector))],exports.UpdateFormulaController);const vt="SHEETS_FORMULA_PLUGIN";var Vt=Object.getOwnPropertyDescriptor,Gt=(r,t,n,a)=>{for(var i=a>1?void 0:a?Vt(t,n):t,o=r.length-1,u;o>=0;o--)(u=r[o])&&(i=u(i)||i);return i},Oe=(r,t)=>(n,a)=>t(n,a,r);let se=class extends c.Disposable{constructor(r,t,n){super(),this._activeDirtyManagerService=r,this._univerInstanceService=t,this._formulaDataModel=n,this._initialize()}_initialize(){this._initialConversion()}_initialConversion(){this._activeDirtyManagerService.register(l.SetRangeValuesMutation.id,{commandId:l.SetRangeValuesMutation.id,getDirtyData:r=>{const t=r.params;return t.trigger===l.SetStyleCommand.id?{}:{dirtyRanges:this._getSetRangeValuesMutationDirtyRange(t)}}}),this._initialMove(),this._initialRowAndColumn(),this._initialHideRow(),this._initialSheet(),this._initialDefinedName()}_initialMove(){this._activeDirtyManagerService.register(l.MoveRangeMutation.id,{commandId:l.MoveRangeMutation.id,getDirtyData:r=>{const t=r.params;return{dirtyRanges:this._getMoveRangeMutationDirtyRange(t),clearDependencyTreeCache:{[t.unitId]:{[t.to.subUnitId]:"1",[t.from.subUnitId]:"1"}}}}}),this._activeDirtyManagerService.register(l.MoveRowsMutation.id,{commandId:l.MoveRowsMutation.id,getDirtyData:r=>{const t=r.params;return{dirtyRanges:this._getMoveRowsMutationDirtyRange(t),clearDependencyTreeCache:{[t.unitId]:{[t.subUnitId]:"1"}}}}}),this._activeDirtyManagerService.register(l.MoveColsMutation.id,{commandId:l.MoveColsMutation.id,getDirtyData:r=>{const t=r.params;return{dirtyRanges:this._getMoveRowsMutationDirtyRange(t),clearDependencyTreeCache:{[t.unitId]:{[t.subUnitId]:"1"}}}}}),this._activeDirtyManagerService.register(l.ReorderRangeMutation.id,{commandId:l.ReorderRangeMutation.id,getDirtyData:r=>{const t=r.params;return{dirtyRanges:this._getReorderRangeMutationDirtyRange(t),clearDependencyTreeCache:{[t.unitId]:{[t.subUnitId]:"1"}}}}})}_initialRowAndColumn(){this._activeDirtyManagerService.register(l.RemoveRowMutation.id,{commandId:l.RemoveRowMutation.id,getDirtyData:r=>{const t=r.params;return{dirtyRanges:this._getRemoveRowOrColumnMutation(t,!0),clearDependencyTreeCache:{[t.unitId]:{[t.subUnitId]:"1"}}}}}),this._activeDirtyManagerService.register(l.RemoveColMutation.id,{commandId:l.RemoveColMutation.id,getDirtyData:r=>{const t=r.params;return{dirtyRanges:this._getRemoveRowOrColumnMutation(t,!1),clearDependencyTreeCache:{[t.unitId]:{[t.subUnitId]:"1"}}}}}),this._activeDirtyManagerService.register(l.InsertColMutation.id,{commandId:l.InsertColMutation.id,getDirtyData:r=>{const t=r.params;return{clearDependencyTreeCache:{[t.unitId]:{[t.subUnitId]:"1"}}}}}),this._activeDirtyManagerService.register(l.InsertRowMutation.id,{commandId:l.InsertRowMutation.id,getDirtyData:r=>{const t=r.params;return{clearDependencyTreeCache:{[t.unitId]:{[t.subUnitId]:"1"}}}}})}_initialHideRow(){this._activeDirtyManagerService.register(l.SetRowHiddenMutation.id,{commandId:l.SetRowHiddenMutation.id,getDirtyData:r=>{const t=r.params;return{dirtyRanges:this._getHideRowMutation(t),clearDependencyTreeCache:{[t.unitId]:{[t.subUnitId]:"1"}}}}}),this._activeDirtyManagerService.register(l.SetRowVisibleMutation.id,{commandId:l.SetRowVisibleMutation.id,getDirtyData:r=>{const t=r.params;return{dirtyRanges:this._getHideRowMutation(t),clearDependencyTreeCache:{[t.unitId]:{[t.subUnitId]:"1"}}}}})}_initialSheet(){this._activeDirtyManagerService.register(l.RemoveSheetMutation.id,{commandId:l.RemoveSheetMutation.id,getDirtyData:r=>{const t=r.params;return{dirtyNameMap:this._getRemoveSheetMutation(t),clearDependencyTreeCache:{[t.unitId]:{[t.subUnitId]:"1"}}}}}),this._activeDirtyManagerService.register(l.InsertSheetMutation.id,{commandId:l.InsertSheetMutation.id,getDirtyData:r=>{const t=r.params;return{dirtyNameMap:this._getInsertSheetMutation(t)}}})}_initialDefinedName(){this._activeDirtyManagerService.register(e.SetDefinedNameMutation.id,{commandId:e.SetDefinedNameMutation.id,getDirtyData:r=>{const t=r.params;return{dirtyDefinedNameMap:this._getDefinedNameMutation(t)}}}),this._activeDirtyManagerService.register(e.RemoveDefinedNameMutation.id,{commandId:e.RemoveDefinedNameMutation.id,getDirtyData:r=>{const t=r.params;return{dirtyDefinedNameMap:this._getDefinedNameMutation(t)}}})}_getDefinedNameMutation(r){const{unitId:t,name:n,formulaOrRefString:a}=r,i={};return r==null?{}:(i[t]={},i[t][n]=a,i)}_getSetRangeValuesMutationDirtyRange(r){const{subUnitId:t,unitId:n,cellValue:a}=r,i=[];return a==null||(i.push(...this._getDirtyRangesByCellValue(n,t,a)),i.push(...this._getDirtyRangesForArrayFormula(n,t,a))),i}_getMoveRangeMutationDirtyRange(r){const{unitId:t,from:n,to:a}=r,i=[];return i.push(...this._getDirtyRangesByCellValue(t,n.subUnitId,n.value)),i.push(...this._getDirtyRangesByCellValue(t,a.subUnitId,a.value)),i.push(...this._getDirtyRangesForArrayFormula(t,a.subUnitId,a.value)),i}_getMoveRowsMutationDirtyRange(r){const{subUnitId:t,unitId:n,sourceRange:a,targetRange:i}=r,o=[],u=this._rangeToMatrix(a).getData(),m=this._rangeToMatrix(i).getData();return o.push(...this._getDirtyRangesByCellValue(n,t,u)),o.push(...this._getDirtyRangesByCellValue(n,t,m)),o.push(...this._getDirtyRangesForArrayFormula(n,t,m)),o}_getReorderRangeMutationDirtyRange(r){const{unitId:t,subUnitId:n,range:a}=r,i=this._rangeToMatrix(a).getData(),o=[];return o.push(...this._getDirtyRangesByCellValue(t,n,i)),o.push(...this._getDirtyRangesForArrayFormula(t,n,i)),o}_getRemoveRowOrColumnMutation(r,t=!0){const{subUnitId:n,unitId:a,range:i}=r,o=[],u=this._univerInstanceService.getUniverSheetInstance(a),m=u==null?void 0:u.getSheetBySheetId(n),f=(m==null?void 0:m.getRowCount())||0,s=(m==null?void 0:m.getColumnCount())||0;let d=null;const{startRow:T,endRow:N,startColumn:L,endColumn:A}=i;t===!0?d=this._rangeToMatrix({startRow:T,startColumn:0,endRow:N,endColumn:s-1}):d=this._rangeToMatrix({startRow:0,startColumn:L,endRow:f,endColumn:A});const S=d.getData();return o.push(...this._getDirtyRangesByCellValue(a,n,S)),o.push(...this._getDirtyRangesForArrayFormula(a,n,S)),o}_getHideRowMutation(r){const{subUnitId:t,unitId:n,ranges:a}=r,i=[];return a.forEach(o=>{const u=this._rangeToMatrix(o).getMatrix();i.push(...this._getDirtyRangesByCellValue(n,t,u))}),i}_getRemoveSheetMutation(r){const t={},{subUnitId:n,unitId:a,subUnitName:i}=r;return t[a]==null&&(t[a]={}),t[a][n]=i,t}_getInsertSheetMutation(r){const t={},{sheet:n,unitId:a}=r;return t[a]==null&&(t[a]={}),t[a][n.id]=n.name,t}_rangeToMatrix(r){const t=new c.ObjectMatrix,{startRow:n,startColumn:a,endRow:i,endColumn:o}=r;for(let u=n;u<=i;u++)for(let m=a;m<=o;m++)t.setValue(u,m,{});return t}_getDirtyRangesByCellValue(r,t,n){const a=[];return n==null||new c.ObjectMatrix(n).getDiscreteRanges().forEach(u=>{a.push({unitId:r,sheetId:t,range:u})}),a}_getDirtyRangesForArrayFormula(r,t,n){var u,m;const a=[];if(n==null)return a;const i=new c.ObjectMatrix(n),o=this._formulaDataModel.getArrayFormulaRange();if((u=o==null?void 0:o[r])!=null&&u[t]){const f=new c.ObjectMatrix((m=o==null?void 0:o[r])==null?void 0:m[t]);i.forValue((s,d)=>{f.forValue((T,N,L)=>{if(L==null)return!0;const{startRow:A,startColumn:S,endRow:C,endColumn:p}=L;s>=A&&s<=C&&d>=S&&d<=p&&a.push({unitId:r,sheetId:t,range:{startRow:A,startColumn:S,endRow:A,endColumn:S}})})})}return a}};se=Gt([Oe(0,e.IActiveDirtyManagerService),Oe(1,c.IUniverInstanceService),Oe(2,c.Inject(e.FormulaDataModel))],se);var Ht=Object.getOwnPropertyDescriptor,Yt=(r,t,n,a)=>{for(var i=a>1?void 0:a?Ht(t,n):t,o=r.length-1,u;o>=0;o--)(u=r[o])&&(i=u(i)||i);return i},ue=(r,t)=>(n,a)=>t(n,a,r);let pe=class extends c.Disposable{constructor(r,t,n,a){super(),this._commandService=r,this._configService=t,this._sheetInterceptorService=n,this._formulaDataModel=a,this._initialize()}_initialize(){this._commandExecutedListener(),this._initInterceptorCellContent()}_commandExecutedListener(){this.disposeWithMe(this._commandService.onCommandExecuted(r=>{var i;if(r.id!==e.SetArrayFormulaDataMutation.id)return;const t=r.params;if(t==null)return;const{arrayFormulaRange:n,arrayFormulaCellData:a}=t;this._formulaDataModel.setArrayFormulaRange(n