@univerjs/preset-sheets-node-core 0.12.1 → 0.12.2-experimental.20251129-0fa20cd
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/umd/index.js +6 -6
- package/lib/umd/locales/ja-JP.js +1 -1
- package/package.json +17 -17
package/lib/umd/index.js
CHANGED
|
@@ -7,17 +7,17 @@
|
|
|
7
7
|
|
|
8
8
|
|
|
9
9
|
// @univerjs/sheets/index
|
|
10
|
-
(function(g,i){typeof exports=="object"&&typeof module<"u"?i(exports,require("@univerjs/core"),require("rxjs"),require("@univerjs/engine-formula"),require("rxjs/operators"),require("@univerjs/rpc")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","rxjs","@univerjs/engine-formula","rxjs/operators","@univerjs/rpc"],i):(g=typeof globalThis<"u"?globalThis:g||self,i(g.UniverSheets={},g.UniverCore,g.rxjs,g.UniverEngineFormula,g.rxjs.operators,g.UniverRpc))})(this,(function(g,i,O,J,kt,Bi){"use strict";var $d=Object.defineProperty;var Ld=(g,i,O)=>i in g?$d(g,i,{enumerable:!0,configurable:!0,writable:!0,value:O}):g[i]=O;var f=(g,i,O)=>Ld(g,typeof i!="symbol"?i+"":i,O);function Hi(s,e,t){var r,a,u;if(e.t)return e.t;if(e.v===null)return null;const n=s.getStyleByCell(e),o=s.getStyleByCell(t);if(t.t===i.CellValueType.FORCE_STRING){if(!i.isTextFormat((r=o==null?void 0:o.n)==null?void 0:r.pattern)&&e.v!==void 0){if(i.isRealNum(e.v))return i.CellValueType.NUMBER;if(i.isBooleanString(`${e.v}`))return i.CellValueType.BOOLEAN}return i.CellValueType.FORCE_STRING}return Fi(n)?i.isTextFormat((a=n==null?void 0:n.n)==null?void 0:a.pattern)?i.CellValueType.STRING:no(e,t):i.isTextFormat((u=o==null?void 0:o.n)==null?void 0:u.pattern)?i.CellValueType.STRING:no(e,t)}function no(s,e){return s.v!==void 0?Vn(s.v,s.t):Vn(e.v,e.t)}function Fi(s){var e;return!!((e=s==null?void 0:s.n)!=null&&e.pattern)}function Vn(s,e){return s===null?null:typeof s=="string"?i.isRealNum(s)?(+s==0||+s==1)&&e===i.CellValueType.BOOLEAN?i.CellValueType.BOOLEAN:e!==i.CellValueType.STRING&&e!==i.CellValueType.FORCE_STRING&&i.willLoseNumericPrecision(s)?i.CellValueType.FORCE_STRING:i.CellValueType.NUMBER:i.isBooleanString(s)?i.CellValueType.BOOLEAN:i.CellValueType.STRING:typeof s=="number"?(s===0||s===1)&&e===i.CellValueType.BOOLEAN?i.CellValueType.BOOLEAN:i.CellValueType.NUMBER:typeof s=="boolean"?i.CellValueType.BOOLEAN:i.CellValueType.FORCE_STRING}const ge=(s,e)=>{if(s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId)==null)throw new Error("universheet is null error!");return{unitId:e.unitId,subUnitId:e.subUnitId,ranges:i.Tools.deepClone(e.ranges)}},j={id:"sheet.mutation.add-worksheet-merge",type:i.CommandType.MUTATION,handler:(s,e)=>{const n=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(n==null)throw new Error("universheet is null error!");const o=n.getSheetBySheetId(e.subUnitId);if(!o)return!1;const a=o.getConfig().mergeData,u=e.ranges;for(let l=0;l<u.length;l++)a.push(u[l]);return o.getSpanModel().rebuild(a),!0}},ji=i.createInterceptorKey("CELL_CONTENT"),Gi=i.createInterceptorKey("ROW_FILTERED"),Ae={CELL_CONTENT:ji,ROW_FILTERED:Gi};var so=(s=>(s[s.DATA_VALIDATION=9]="DATA_VALIDATION",s[s.NUMFMT=10]="NUMFMT",s[s.CELL_IMAGE=11]="CELL_IMAGE",s))(so||{});const oo="sheet.interceptor.range-theme-id",ro="sheet.interceptor.ignore-range-theme";var zi=Object.getOwnPropertyDescriptor,qi=(s,e,t,n)=>{for(var o=n>1?void 0:n?zi(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},Yi=(s,e)=>(t,n)=>e(t,n,s);const $n=i.createInterceptorKey("BEFORE_CELL_EDIT"),Zt=i.createInterceptorKey("AFTER_CELL_EDIT"),Qt=i.createInterceptorKey("VALIDATE_CELL");g.SheetInterceptorService=class extends i.Disposable{constructor(t){super();f(this,"_interceptorsByName",new Map);f(this,"_commandInterceptors",[]);f(this,"_rangeInterceptors",[]);f(this,"_autoHeightInterceptors",[]);f(this,"_beforeCommandInterceptor",[]);f(this,"_afterCommandInterceptors",[]);f(this,"_workbookDisposables",new Map);f(this,"_worksheetDisposables",new Map);f(this,"_interceptorsDirty",!1);f(this,"_composedInterceptorByKey",new Map);f(this,"writeCellInterceptor",new i.InterceptorManager({BEFORE_CELL_EDIT:$n,AFTER_CELL_EDIT:Zt,VALIDATE_CELL:Qt}));this._univerInstanceService=t,this.disposeWithMe(this._univerInstanceService.getTypeOfUnitAdded$(i.UniverInstanceType.UNIVER_SHEET).subscribe(n=>{this._interceptWorkbook(n)})),this.disposeWithMe(this._univerInstanceService.getTypeOfUnitDisposed$(i.UniverInstanceType.UNIVER_SHEET).subscribe(n=>this._disposeWorkbookInterceptor(n))),this.intercept(Ae.CELL_CONTENT,{priority:-1,effect:i.InterceptorEffectEnum.Style|i.InterceptorEffectEnum.Value,handler:n=>n}),this.disposeWithMe(this.writeCellInterceptor.intercept(Zt,{priority:-1,handler:n=>n})),this.disposeWithMe(this.writeCellInterceptor.intercept($n,{priority:-1,handler:n=>n})),this.disposeWithMe(this.writeCellInterceptor.intercept(Qt,{priority:-1,handler:n=>n}))}dispose(){super.dispose(),this._workbookDisposables.forEach(t=>t.dispose()),this._workbookDisposables.clear(),this._worksheetDisposables.forEach(t=>t.dispose()),this._worksheetDisposables.clear(),this._interceptorsByName.clear()}interceptCommand(t){if(this._commandInterceptors.includes(t))throw new Error("[SheetInterceptorService]: Interceptor already exists!");return this._commandInterceptors.push(t),this._commandInterceptors.sort((n,o)=>{var r,a;return((r=o.priority)!=null?r:0)-((a=n.priority)!=null?a:0)}),this.disposeWithMe(i.toDisposable(()=>i.remove(this._commandInterceptors,t)))}onCommandExecute(t){const n=this._commandInterceptors.map(o=>o.getMutations(t));return{preUndos:n.map(o=>{var r;return(r=o.preUndos)!=null?r:[]}).flat(),undos:n.map(o=>o.undos).flat(),preRedos:n.map(o=>{var r;return(r=o.preRedos)!=null?r:[]}).flat(),redos:n.map(o=>o.redos).flat()}}interceptAfterCommand(t){if(this._afterCommandInterceptors.includes(t))throw new Error("[SheetInterceptorService]: Interceptor already exists!");return this._afterCommandInterceptors.push(t),this._afterCommandInterceptors.sort((n,o)=>{var r,a;return((r=o.priority)!=null?r:0)-((a=n.priority)!=null?a:0)}),this.disposeWithMe(i.toDisposable(()=>i.remove(this._afterCommandInterceptors,t)))}afterCommandExecute(t){const n=this._afterCommandInterceptors.map(o=>o.getMutations(t));return{undos:n.map(o=>o.undos).flat(),redos:n.map(o=>o.redos).flat()}}interceptAutoHeight(t){if(this._autoHeightInterceptors.includes(t))throw new Error("[SheetInterceptorService]: Interceptor already exists!");return this._autoHeightInterceptors.push(t),this._autoHeightInterceptors.sort((n,o)=>{var r,a;return((r=o.priority)!=null?r:0)-((a=n.priority)!=null?a:0)}),this.disposeWithMe(i.toDisposable(()=>i.remove(this._autoHeightInterceptors,t)))}generateMutationsOfAutoHeight(t){const n=this._autoHeightInterceptors.map(o=>o.getMutations(t));return{preUndos:n.map(o=>{var r;return(r=o.preUndos)!=null?r:[]}).flat(),undos:n.map(o=>o.undos).flat(),preRedos:n.map(o=>{var r;return(r=o.preRedos)!=null?r:[]}).flat(),redos:n.map(o=>o.redos).flat()}}interceptBeforeCommand(t){if(this._beforeCommandInterceptor.includes(t))throw new Error("[SheetInterceptorService]: Interceptor already exists!");return this._beforeCommandInterceptor.push(t),this._beforeCommandInterceptor.sort((n,o)=>{var r,a;return((r=o.priority)!=null?r:0)-((a=n.priority)!=null?a:0)}),this.disposeWithMe(i.toDisposable(()=>i.remove(this._beforeCommandInterceptor,t)))}async beforeCommandExecute(t){return(await Promise.all(this._beforeCommandInterceptor.map(o=>o.performCheck(t)))).every(o=>o)}interceptRanges(t){if(this._rangeInterceptors.includes(t))throw new Error("[SheetInterceptorService]: Interceptor already exists!");return this._rangeInterceptors.push(t),this._rangeInterceptors.sort((n,o)=>{var r,a;return((r=o.priority)!=null?r:0)-((a=n.priority)!=null?a:0)}),this.disposeWithMe(i.toDisposable(()=>i.remove(this._rangeInterceptors,t)))}generateMutationsByRanges(t){const n=this._rangeInterceptors.map(o=>o.getMutations(t));return{preUndos:n.map(o=>{var r;return(r=o.preUndos)!=null?r:[]}).flat(),undos:n.map(o=>o.undos).flat(),preRedos:n.map(o=>{var r;return(r=o.preRedos)!=null?r:[]}).flat(),redos:n.map(o=>o.redos).flat()}}onWriteCell(t,n,o,r,a){const u={subUnitId:n.getSheetId(),unitId:t.getUnitId(),workbook:t,worksheet:n,row:o,col:r,origin:i.Tools.deepClone(a)};return this.writeCellInterceptor.fetchThroughInterceptors(Zt)(a,u)}onValidateCell(t,n,o,r){const a={subUnitId:n.getSheetId(),unitId:t.getUnitId(),workbook:t,worksheet:n,row:o,col:r};return this.writeCellInterceptor.fetchThroughInterceptors(Qt)(Promise.resolve(!0),a)}intercept(t,n){const o=t;this._interceptorsByName.has(o)||this._interceptorsByName.set(o,[]);const r=this._interceptorsByName.get(o);r.push(n);const a=r.sort((u,l)=>{var d,c;return((d=l.priority)!=null?d:0)-((c=u.priority)!=null?c:0)});if(this._interceptorsDirty=!0,o===Ae.CELL_CONTENT){const u=i.InterceptorEffectEnum.Style|i.InterceptorEffectEnum.Value;this._interceptorsByName.set(`${o}-${u}`,a);const l=i.InterceptorEffectEnum.Style|i.InterceptorEffectEnum.Value;return this._interceptorsByName.set(`${o}-${i.InterceptorEffectEnum.Style}`,a.filter(d=>((d.effect||l)&i.InterceptorEffectEnum.Style)>0)),this._interceptorsByName.set(`${o}-${i.InterceptorEffectEnum.Value}`,a.filter(d=>((d.effect||l)&i.InterceptorEffectEnum.Value)>0)),this.disposeWithMe(i.toDisposable(()=>{i.remove(this._interceptorsByName.get(o),n),i.remove(this._interceptorsByName.get(`${o}-${u}`),n),i.remove(this._interceptorsByName.get(`${o}-${i.InterceptorEffectEnum.Style}`),n),i.remove(this._interceptorsByName.get(`${o}-${i.InterceptorEffectEnum.Value}`),n)}))}else return this._interceptorsByName.set(o,a),this.disposeWithMe(i.toDisposable(()=>i.remove(this._interceptorsByName.get(o),n)))}fetchThroughInterceptors(t,n,o,r){const a=n===void 0?t:`${t}-${n}`,u=o!=null?o:a;let l=this._composedInterceptorByKey.get(u);if(!l||this._interceptorsDirty){let d=this._interceptorsByName.get(a);d&&r&&(d=d.filter(r)),l=i.composeInterceptors(d||[]),this._composedInterceptorByKey.set(u,l)}return l}_interceptWorkbook(t){const n=new i.DisposableCollection,o=t.getUnitId(),r=this,a=u=>{const l=u.getSheetId();u.__interceptViewModel(d=>{const c=new i.DisposableCollection;r._worksheetDisposables.set(io(o,u),c),c.add(d.registerCellContentInterceptor({getCell(m,h,R,C,S){const I=u.getCellRaw(m,h);return r.fetchThroughInterceptors(Ae.CELL_CONTENT,R,C,S)(I,{unitId:o,subUnitId:l,row:m,col:h,worksheet:u,workbook:t,rawData:I})}})),c.add(d.registerRowFilteredInterceptor({getRowFiltered(m){return!!r.fetchThroughInterceptors(Ae.ROW_FILTERED)(!1,{unitId:o,subUnitId:l,row:m,workbook:t,worksheet:u})}}))})};t.getSheets().forEach(u=>a(u)),n.add(t.sheetCreated$.subscribe(u=>a(u))),n.add(i.toDisposable(()=>t.getSheets().forEach(u=>this._disposeSheetInterceptor(o,u)))),n.add(t.sheetDisposed$.subscribe(u=>this._disposeSheetInterceptor(o,u))),this._workbookDisposables.set(o,n)}_disposeWorkbookInterceptor(t){const n=t.getUnitId(),o=this._workbookDisposables.get(n);o&&(o.dispose(),this._workbookDisposables.delete(n))}_disposeSheetInterceptor(t,n){const o=io(t,n),r=this._worksheetDisposables.get(o);r&&(r.dispose(),this._worksheetDisposables.delete(o))}},g.SheetInterceptorService=qi([Yi(0,i.IUniverInstanceService)],g.SheetInterceptorService);function io(s,e){return`${s}|${e.getSheetId()}`}const Z=s=>{const e={};return s.bg&&(e.bg={...s.bg}),s.ol&&(e.ol={...s.ol}),s.bd&&(e.bd={...s.bd}),s.cl&&(e.cl={...s.cl}),s.ht&&(e.ht=s.ht),s.vt&&(e.vt=s.vt),s.bl!==void 0&&(e.bl=s.bl),e};function Ki(s){const e={};if(s.length===1)return s[0];for(const t of s)t.bg&&(e.bg=t.bg),t.ol&&(e.ol=t.ol),t.bd&&(e.bd={...e.bd,...t.bd}),t.cl&&(e.cl=t.cl),t.ht&&(e.ht=t.ht),t.vt&&(e.vt=t.vt),t.bl!==void 0&&(e.bl=t.bl);return e}const x={wholeStyle:1,headerRowStyle:2,headerColumnStyle:4,firstRowStyle:8,secondRowStyle:16,lastRowStyle:32,firstColumnStyle:128,secondColumnStyle:256,lastColumnStyle:512};class We{constructor(e,t){f(this,"_name");f(this,"wholeStyle",null);f(this,"headerRowStyle",null);f(this,"headerColumnStyle",null);f(this,"firstRowStyle",null);f(this,"secondRowStyle",null);f(this,"lastRowStyle",null);f(this,"firstColumnStyle",null);f(this,"secondColumnStyle",null);f(this,"lastColumnStyle",null);f(this,"_mergeCacheMap",new Map);t&&this.fromJson({...t,name:e}),this._name=e}getName(){return this._name}getWholeStyle(){return this.wholeStyle}setWholeStyle(e){this.wholeStyle=e,this._resetStyleCache()}getFirstRowStyle(){return this.firstRowStyle}setFirstRowStyle(e){this.firstRowStyle=e,this._resetStyleCache()}getSecondRowStyle(){return this.secondRowStyle}setSecondRowStyle(e){this.secondRowStyle=e,this._resetStyleCache()}getLastRowStyle(){return this.lastRowStyle}setLastRowStyle(e){this.lastRowStyle=e,this._resetStyleCache()}getFirstColumnStyle(){return this.firstColumnStyle}setFirstColumnStyle(e){this.firstColumnStyle=e,this._resetStyleCache()}getSecondColumnStyle(){return this.secondColumnStyle}setSecondColumnStyle(e){this.secondColumnStyle=e,this._resetStyleCache()}getLastColumnStyle(){return this.lastColumnStyle}setLastColumnStyle(e){this.lastColumnStyle=e,this._resetStyleCache()}getHeaderRowStyle(){return this.headerRowStyle}setHeaderRowStyle(e){this.headerRowStyle=e,this._resetStyleCache()}getHeaderColumnStyle(){return this.headerColumnStyle}setHeaderColumnStyle(e){this.headerColumnStyle=e,this._resetStyleCache()}getStyle(e,t,n,o,r){let a=0;return n&&(a=a|x.lastRowStyle),o&&(a=a|x.lastColumnStyle),e>=0&&t>=0&&(a=a|x.wholeStyle),e%2===1&&(a=a|(r?x.secondRowStyle:x.firstRowStyle)),e%2===0&&(a=a|(r?x.firstRowStyle:x.secondRowStyle)),e===0&&(a=a|x.headerRowStyle),t===0&&(a=a|x.headerColumnStyle),t%2===1&&(a=a|x.firstColumnStyle),t%2===0&&(a=a|x.secondColumnStyle),a===0?null:this._getMergeStyle(a)}_getMergeStyle(e){let t=this._mergeCacheMap.get(e);return t||(t=this._mergeStyle(e),this._mergeCacheMap.set(e,t)),t}_mergeStyle(e){const t=[];return this.wholeStyle&&e&x.wholeStyle&&t.push(this.wholeStyle),this.firstColumnStyle&&e&x.firstColumnStyle&&t.push(this.firstColumnStyle),this.secondColumnStyle&&e&x.secondColumnStyle&&t.push(this.secondColumnStyle),this.firstRowStyle&&e&x.firstRowStyle&&t.push(this.firstRowStyle),this.secondRowStyle&&e&x.secondRowStyle&&t.push(this.secondRowStyle),this.headerColumnStyle&&e&x.headerColumnStyle&&t.push(this.headerColumnStyle),this.lastColumnStyle&&e&x.lastColumnStyle&&t.push(this.lastColumnStyle),this.headerRowStyle&&e&x.headerRowStyle&&t.push(this.headerRowStyle),this.lastRowStyle&&e&x.lastRowStyle&&t.push(this.lastRowStyle),Ki(t)}_resetStyleCache(){this._mergeCacheMap.clear()}toJson(){const e={name:this._name};return this.wholeStyle&&(e.wholeStyle=Z(this.wholeStyle)),this.headerRowStyle&&(e.headerRowStyle=Z(this.headerRowStyle)),this.headerColumnStyle&&(e.headerColumnStyle=Z(this.headerColumnStyle)),this.firstRowStyle&&(e.firstRowStyle=Z(this.firstRowStyle)),this.secondRowStyle&&(e.secondRowStyle=Z(this.secondRowStyle)),this.lastRowStyle&&(e.lastRowStyle=Z(this.lastRowStyle)),this.firstColumnStyle&&(e.firstColumnStyle=Z(this.firstColumnStyle)),this.secondColumnStyle&&(e.secondColumnStyle=Z(this.secondColumnStyle)),this.lastColumnStyle&&(e.lastColumnStyle=Z(this.lastColumnStyle)),e}fromJson(e){this._name=e.name,e.wholeStyle&&(this.wholeStyle=Z(e.wholeStyle)),e.headerRowStyle&&(this.headerRowStyle=Z(e.headerRowStyle)),e.headerColumnStyle&&(this.headerColumnStyle=Z(e.headerColumnStyle)),e.firstRowStyle&&(this.firstRowStyle=Z(e.firstRowStyle)),e.secondRowStyle&&(this.secondRowStyle=Z(e.secondRowStyle)),e.lastRowStyle&&(this.lastRowStyle=Z(e.lastRowStyle)),e.firstColumnStyle&&(this.firstColumnStyle=Z(e.firstColumnStyle)),e.secondColumnStyle&&(this.secondColumnStyle=Z(e.secondColumnStyle)),e.lastColumnStyle&&(this.lastColumnStyle=Z(e.lastColumnStyle))}dispose(){this._mergeCacheMap.clear()}}const Ji=(s,e,t)=>new We(`light-${s}`,{headerRowStyle:{bg:{rgb:e}},firstColumnStyle:{bg:{rgb:"rgb(255, 255, 255)"}},secondColumnStyle:{bg:{rgb:t}},lastRowStyle:{bg:{rgb:e}}}),xi=(s,e,t)=>new We(`middle-${s}`,{headerRowStyle:{bg:{rgb:e}},headerColumnStyle:{bg:{rgb:t}},secondRowStyle:{bg:{rgb:t}},lastRowStyle:{bg:{rgb:e}},lastColumnStyle:{bg:{rgb:t}}}),Xi=(s,e,t,n)=>new We(`dark-${s}`,{headerRowStyle:{bg:{rgb:e},cl:{rgb:"rgb(255, 255, 255)"},ht:i.HorizontalAlign.CENTER,bl:i.BooleanNumber.TRUE},firstRowStyle:{bg:{rgb:t}},secondRowStyle:{bg:{rgb:n}},lastRowStyle:{bg:{rgb:e}}}),Zi=[{baseName:"blue",header:"rgb(164, 202, 254)",color:"rgb(225, 239, 254)"},{baseName:"grey",header:"rgb(205, 208, 216)",color:"rgb(238, 239, 241)"},{baseName:"red",header:"rgb(248, 180, 180)",color:"rgb(253, 232, 232)"},{baseName:"orange",header:"rgb(253, 186, 140)",color:"rgb(254, 236, 220)"},{baseName:"yellow",header:"rgb(250, 200, 21)",color:"rgb(255, 244, 185)"},{baseName:"green",header:"rgb(132, 225, 188)",color:"rgb(222, 247, 236)"},{baseName:"azure",header:"rgb(126, 220, 226)",color:"rgb(213, 245, 246)"},{baseName:"indigo",header:"rgb(186, 198, 248)",color:"rgb(233, 237, 255)"},{baseName:"purple",header:"rgb(202, 191, 253)",color:"rgb(237, 235, 254)"},{baseName:"magenta",header:"rgb(248, 180, 217)",color:"rgb(252, 232, 243)"}],Qi=[{baseName:"blue",rowHeader:"rgb(63, 131, 248)",colHeader:"rgb(195, 221, 253)"},{baseName:"grey",rowHeader:"rgb(95, 101, 116)",colHeader:"rgb(227, 229, 234)"},{baseName:"red",rowHeader:"rgb(240, 82, 82)",colHeader:"rgb(251, 213, 213)"},{baseName:"orange",rowHeader:"rgb(255, 90, 31)",colHeader:"rgb(252, 217, 189)"},{baseName:"yellow",rowHeader:"rgb(212, 157, 15)",colHeader:"rgb(252, 220, 106)"},{baseName:"green",rowHeader:"rgb(13, 164, 113)",colHeader:"rgb(188, 240, 218)"},{baseName:"azure",rowHeader:"rgb(6, 148, 162)",colHeader:"rgb(175, 236, 239)"},{baseName:"indigo",rowHeader:"rgb(70, 106, 247)",colHeader:"rgb(210, 218, 250)"},{baseName:"purple",rowHeader:"rgb(144, 97, 249)",colHeader:"rgb(220, 215, 254)"},{baseName:"magenta",rowHeader:"rgb(231, 70, 148)",colHeader:"rgb(250, 209, 232)"}],ea=[{baseName:"blue",rowHeader:"rgb(30, 66, 159)",firstRow:"rgb(195, 221, 253)",secondRow:"rgb(118, 169, 250)"},{baseName:"grey",rowHeader:"rgb(44, 48, 64)",firstRow:"rgb(227, 229, 234)",secondRow:"rgb(151, 157, 172)"},{baseName:"red",rowHeader:"rgb(155, 28, 28)",firstRow:"rgb(251, 213, 213)",secondRow:"rgb(249, 128, 128)"},{baseName:"orange",rowHeader:"rgb(180, 52, 3)",firstRow:"rgb(252, 217, 189)",secondRow:"rgb(255, 138, 76)"},{baseName:"yellow",rowHeader:"rgb(154, 109, 21)",firstRow:"rgb(252, 220, 106)",secondRow:"rgb(212, 157, 15)"},{baseName:"green",rowHeader:"rgb(4, 108, 78)",firstRow:"rgb(188, 240, 218)",secondRow:"rgb(49, 196, 141)"},{baseName:"azure",rowHeader:"rgb(3, 102, 114)",firstRow:"rgb(175, 236, 239)",secondRow:"rgb(22, 189, 202)"},{baseName:"indigo",rowHeader:"rgb(16, 51, 191)",firstRow:"rgb(210, 218, 250)",secondRow:"rgb(98, 128, 249)"},{baseName:"purple",rowHeader:"rgb(74, 29, 150)",firstRow:"rgb(220, 215, 254)",secondRow:"rgb(172, 148, 250)"},{baseName:"magenta",rowHeader:"rgb(153, 21, 75)",firstRow:"rgb(250, 209, 232)",secondRow:"rgb(241, 126, 184)"}],ta=Zi.map(({baseName:s,header:e,color:t})=>Ji(s,e,t)),na=Qi.map(({baseName:s,rowHeader:e,colHeader:t})=>xi(s,e,t)),sa=ea.map(({baseName:s,rowHeader:e,firstRow:t,secondRow:n})=>Xi(s,e,t,n)),oa=[...ta,...na,...sa],ao={headerRowStyle:{bg:{rgb:"rgb(68,114,196)"},cl:{rgb:"rgb(255,255,255)"},ht:i.HorizontalAlign.CENTER,bl:i.BooleanNumber.TRUE},firstRowStyle:{bg:{rgb:"rgb(217,225,242)"}}},ra=new We("default",ao),ia=new We("default-last-row",{...ao,lastRowStyle:{bd:{t:{s:i.BorderStyleTypes.THIN,cl:{rgb:"rgb(68,114,196)"}}},ht:i.HorizontalAlign.CENTER,bl:i.BooleanNumber.TRUE}});class aa{constructor(){f(this,"_toggleRanges",[])}refresh(e,t){const{startRow:n,endRow:o}=e,r=[];let a=0,u=!1,l=-1;for(let d=n;d<=o;d++){if(!t(d)){a++,a%2===1?u=!0:(u=!1,l!==-1&&(r.push([l,d-1]),l=-1));continue}a%2===1?u?l===-1&&(l=d):(u=!0,l=d):u&&(r.push([l,d-2]),u=!1,l=-1),d===o&&u&&r.push([l,d])}this._toggleRanges=r}getToggleRanges(){return this._toggleRanges.concat()}getIsToggled(e){let t=0,n=this._toggleRanges.length-1;for(;t<=n;){const o=Math.floor((t+n)/2),[r,a]=this._toggleRanges[o];if(e<r)n=o-1;else if(e>a)t=o+1;else return!0}return!1}}var ua=Object.getOwnPropertyDescriptor,la=(s,e,t,n)=>{for(var o=n>1?void 0:n?ua(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},Ln=(s,e)=>(t,n)=>e(t,n,s);const da="SHEET_RANGE_THEME_MODEL_PLUGIN";g.SheetRangeThemeModel=class extends i.Disposable{constructor(t,n,o){super();f(this,"_rangeThemeStyleMap",new Map);f(this,"_rangeThemeStyleRuleMap",new Map);f(this,"_rTreeCollection",new Map);f(this,"_defaultRangeThemeMap",new Map);f(this,"_zebraCrossingCacheMap",new Map);f(this,"_rowVisibleFuncSet",new Map);f(this,"_rangeThemeMapChanged$",new O.Subject);f(this,"rangeThemeMapChange$",this._rangeThemeMapChanged$.asObservable());this._sheetInterceptorService=t,this._resourceManagerService=n,this._univerInstanceService=o,this._registerIntercept(),this._initSnapshot(),this._initDefaultTheme()}_initDefaultTheme(){this.registerDefaultRangeTheme(ra),this.registerDefaultRangeTheme(ia);for(const t of oa)this.registerDefaultRangeTheme(t)}_ensureRangeThemeStyleMap(t){return this._rangeThemeStyleMap.has(t)||this._rangeThemeStyleMap.set(t,new Map),this._rangeThemeStyleMap.get(t)}_ensureRangeThemeStyleRuleMap(t){return this._rangeThemeStyleRuleMap.has(t)||this._rangeThemeStyleRuleMap.set(t,new Map),this._rangeThemeStyleRuleMap.get(t)}_ensureRTreeCollection(t){return this._rTreeCollection.has(t)||this._rTreeCollection.set(t,new i.RTree),this._rTreeCollection.get(t)}getDefaultRangeThemeStyle(t){return this._defaultRangeThemeMap.get(t)}getCustomRangeThemeStyle(t,n){return this._ensureRangeThemeStyleMap(t).get(n)}_getSheetRowVisibleFuncSet(t,n){this._rowVisibleFuncSet.has(t)||this._rowVisibleFuncSet.set(t,new Map);const o=this._rowVisibleFuncSet.get(t);return o.has(n)||o.set(n,new Set),o.get(n)}_getSheetRowVisibleHasInit(t,n){var o;return!!(this._rowVisibleFuncSet.has(t)&&((o=this._rowVisibleFuncSet.get(t))!=null&&o.has(n)))}refreshSheetRowVisibleFuncSet(t,n){const o=this._getSheetRowVisibleFuncSet(t,n);o.clear();const r=this._univerInstanceService.getUnit(t);if(r){const a=r.getSheetBySheetId(n);if(a){const u=a.getRowCount(),l=a.getRowManager();for(let d=1;d<=u;d++)a.getRowVisible(d)?l.getRowHeight(d)===0&&o.add(d):o.add(d)}}}_ensureZebraCrossingCache(t,n,o){this._zebraCrossingCacheMap.has(t)||this._zebraCrossingCacheMap.set(t,new Map);const r=this._zebraCrossingCacheMap.get(t);r.has(n)||r.set(n,new Map);const a=r.get(n);return a.has(o)||a.set(o,new aa),a.get(o)}registerRangeThemeRule(t,n){const{unitId:o,subUnitId:r,range:a}=n,u=i.generateRandomId(),l=this._ensureRangeThemeStyleRuleMap(o),d=this._ensureRTreeCollection(o);l.set(u,{rangeInfo:n,themeName:t}),d.insert({unitId:o,sheetId:r,range:a,id:u}),this._getSheetRowVisibleHasInit(o,r)||this.refreshSheetRowVisibleFuncSet(o,r);const c=this._ensureZebraCrossingCache(o,r,u),m=this._getSheetRowVisibleFuncSet(o,r);c.refresh(a,h=>!m.has(h))}getRegisteredRangeThemeStyle(t){const{unitId:n,subUnitId:o,range:r}=t,a=this._ensureRTreeCollection(n),u=Array.from(a.bulkSearch([{unitId:n,sheetId:o,range:r}]));if(u[0]){const d=this._ensureRangeThemeStyleRuleMap(n).get(u[0]);if(d)return d.themeName}}refreshZebraCrossingCacheBySheet(t,n){this._zebraCrossingCacheMap.has(t)||this._zebraCrossingCacheMap.set(t,new Map);const o=this._zebraCrossingCacheMap.get(t);o.has(n)||o.set(n,new Map);const r=o.get(n);r&&r.forEach((a,u)=>{const d=this._ensureRangeThemeStyleRuleMap(t).get(u);d?a.refresh(d.rangeInfo.range,c=>!this._getSheetRowVisibleFuncSet(t,n).has(c)):r.delete(u)})}removeRangeThemeRule(t,n){const{unitId:o,subUnitId:r,range:a}=n,u=this._ensureRTreeCollection(o),l=Array.from(u.bulkSearch([{unitId:o,sheetId:r,range:a}])),d=this._ensureRangeThemeStyleRuleMap(o);for(let c=0;c<l.length;c++){const m=d.get(l[c]);if(m&&m.themeName===t){d.delete(l[c]),u.remove({unitId:o,sheetId:r,range:a,id:l[c]});const h=this._zebraCrossingCacheMap.get(o);if(h){const R=h.get(r);R&&R.delete(l[c])}break}}}registerDefaultRangeTheme(t){this._defaultRangeThemeMap.set(t.getName(),t),this._rangeThemeMapChanged$.next({type:"add",styleName:t.getName()})}unRegisterDefaultRangeTheme(t){this._defaultRangeThemeMap.delete(t),this._rangeThemeMapChanged$.next({type:"remove",styleName:t})}getRegisteredRangeThemes(){return Array.from(this._defaultRangeThemeMap.keys())}registerRangeThemeStyle(t,n){this._ensureRangeThemeStyleMap(t).set(n.getName(),n),this._rangeThemeMapChanged$.next({type:"add",styleName:n.getName()})}unregisterRangeThemeStyle(t,n){this._ensureRangeThemeStyleMap(t).delete(n),this._rangeThemeMapChanged$.next({type:"remove",styleName:n})}getALLRegisteredTheme(t){return Array.from(this._ensureRangeThemeStyleMap(t).keys())}getRangeThemeStyle(t,n){return this._defaultRangeThemeMap.has(n)?this._defaultRangeThemeMap.get(n):this._ensureRangeThemeStyleMap(t).get(n)}getCellStyle(t,n,o,r){const a={startRow:o,startColumn:r,endRow:o,endColumn:r},u=this._ensureRTreeCollection(t),l=Array.from(u.bulkSearch([{unitId:t,sheetId:n,range:a}]));if(l[0]){const c=this._ensureRangeThemeStyleRuleMap(t).get(l[0]);if(c){const{rangeInfo:m,themeName:h}=c,R=o-m.range.startRow,C=r-m.range.startColumn,S=this.getRangeThemeStyle(t,h),v=this._ensureZebraCrossingCache(t,n,l[0]).getIsToggled(o);if(S)return S.getStyle(R,C,o===m.range.endRow,r===m.range.endColumn,v)}}}_registerIntercept(){this.disposeWithMe(this._sheetInterceptorService.intercept(Ae.CELL_CONTENT,{id:oo,effect:i.InterceptorEffectEnum.Style,handler:(t,n,o)=>{const{row:r,col:a,unitId:u,subUnitId:l}=n,d=this.getCellStyle(u,l,r,a);if(d){const c=!t||t===n.rawData?{...n.rawData}:t;return c.themeStyle=d,o(c)}return o(t)}}))}toJson(t){const n=this._ensureRangeThemeStyleRuleMap(t),o=this._ensureRangeThemeStyleMap(t);if(o.size===0&&n.size===0)return"{}";const r={};n.forEach((u,l)=>{r[l]=u});const a={};return o.forEach((u,l)=>{a[l]=u.toJson()}),JSON.stringify({rangeThemeStyleRuleMap:r,rangeThemeStyleMapJson:a})}fromJSON(t,n){const{rangeThemeStyleRuleMap:o,rangeThemeStyleMapJson:r}=n;o&&Object.keys(o).forEach(a=>{const u=o[a],{themeName:l,rangeInfo:d}=u;l.startsWith("table")||(this.registerRangeThemeRule(l,d),this._ensureRTreeCollection(d.unitId).insert({unitId:a,sheetId:d.subUnitId,range:d.range,id:a}))}),r&&Object.keys(r).forEach(a=>{const u=r[a],l=new We(u.name);l.fromJson(u),this._ensureRangeThemeStyleMap(t).set(l.getName(),l)})}deleteUnitId(t){this._rangeThemeStyleMap.delete(t),this._rangeThemeStyleRuleMap.delete(t),this._rTreeCollection.delete(t)}_initSnapshot(){this.disposeWithMe(this._resourceManagerService.registerPluginResource({toJson:t=>this.toJson(t),parseJson:t=>{if(!t)return{};try{return JSON.parse(t)}catch{return{}}},businesses:[i.UniverInstanceType.UNIVER_SHEET],pluginName:da,onLoad:(t,n)=>{this.fromJSON(t,n)},onUnLoad:t=>{this.deleteUnitId(t)}}))}dispose(){super.dispose(),this._rangeThemeStyleMap.clear(),this._rangeThemeStyleRuleMap.clear(),this._defaultRangeThemeMap.clear(),this._rTreeCollection.clear(),this._zebraCrossingCacheMap.clear(),this._rowVisibleFuncSet.clear()}},g.SheetRangeThemeModel=la([Ln(0,i.Inject(g.SheetInterceptorService)),Ln(1,i.Inject(i.IResourceManagerService)),Ln(2,i.Inject(i.IUniverInstanceService))],g.SheetRangeThemeModel);function Bn(s,e){const{unitId:t}=e,n=t?s.getUnit(t,i.UniverInstanceType.UNIVER_SHEET):s.getCurrentUnitOfType(i.UniverInstanceType.UNIVER_SHEET);return n?{workbook:n,unitId:n.getUnitId()}:null}function P(s,e={}){const{unitId:t,subUnitId:n}=e,o=t?s.getUnit(t,i.UniverInstanceType.UNIVER_SHEET):s.getCurrentUnitOfType(i.UniverInstanceType.UNIVER_SHEET);if(!o)return null;const r=n?o.getSheetBySheetId(n):o.getActiveSheet(!0);return r?{worksheet:r,workbook:o,unitId:o.getUnitId(),subUnitId:r.getSheetId()}:null}function ve(s,e){const{unitId:t,subUnitId:n}=e,o=s.getUnit(t,i.UniverInstanceType.UNIVER_SHEET);if(!o)return null;const r=o.getSheetBySheetId(n);return r?{worksheet:r,workbook:o}:null}const rt={id:"sheet.mutation.set-worksheet-range-theme-style",type:i.CommandType.MUTATION,handler:(s,e)=>{const{unitId:t,subUnitId:n,range:o,themeName:r}=e,a=s.get(i.IUniverInstanceService),u=P(a),l=s.get(g.SheetRangeThemeModel);return u?(l.registerRangeThemeRule(r,{range:o,unitId:t,subUnitId:n}),!0):!1}},uo=(s,e)=>{const t=ve(s.get(i.IUniverInstanceService),e);if(!t)throw new Error("[SetWorksheetRangeThemeStyleMutation]: worksheet is null error!");const{worksheet:n}=t;return{unitId:e.unitId,subUnitId:n.getSheetId(),range:e.range,themeName:e.themeName}},it={id:"sheet.mutation.remove-worksheet-range-theme-style",type:i.CommandType.MUTATION,handler:(s,e)=>{const{unitId:t,subUnitId:n,range:o,themeName:r}=e,a=s.get(i.IUniverInstanceService),u=P(a),l=s.get(g.SheetRangeThemeModel);return u?(l.removeRangeThemeRule(r,{range:o,unitId:t,subUnitId:n}),!0):!1}},lo=(s,e)=>{const t=ve(s.get(i.IUniverInstanceService),e);if(!t)throw new Error("[DeleteWorksheetRangeThemeStyleMutationFactory]: worksheet is null error!");const{worksheet:n}=t;return{unitId:e.unitId,subUnitId:n.getSheetId(),range:e.range,themeName:e.themeName}},en=(s,e)=>{if(s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId)==null)throw new Error("universheet is null error!");return{unitId:e.unitId,subUnitId:e.subUnitId,range:e.range}},re={id:"sheet.mutation.insert-row",type:i.CommandType.MUTATION,handler:(s,e)=>{var C;const{unitId:t,subUnitId:n,range:o,rowInfo:r}=e,u=s.get(i.IUniverInstanceService).getUniverSheetInstance(t);if(u==null)throw new Error("universheet is null error!");const l=u.getSheetBySheetId(n);if(l==null)throw new Error("worksheet is null error!");const d=l.getRowManager().getRowData(),c={h:l.getConfig().defaultRowHeight,hd:0},m=o.startRow,h=o.endRow-o.startRow+1;for(let S=m;S<m+h;S++)r?i.insertMatrixArray(S,(C=r[S-o.startRow])!=null?C:c,d):i.insertMatrixArray(S,c,d);return l.setRowCount(l.getRowCount()+h),l.getCellMatrix().insertRows(o.startRow,h),!0}},Nt=(s,e)=>{if(s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId)==null)throw new Error("universheet is null error!");return{unitId:e.unitId,subUnitId:e.subUnitId,range:e.range}},ie={id:"sheet.mutation.insert-col",type:i.CommandType.MUTATION,handler:(s,e)=>{var C;const n=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(n==null)throw new Error("universheet is null error!");const o=n.getSheetBySheetId(e.subUnitId);if(!o)return!1;const r=o.getColumnManager(),{range:a,colInfo:u}=e,d=r.getColumnData(),c=a.startColumn,m=a.endColumn-a.startColumn+1,h=o.getConfig().defaultColumnWidth;for(let S=c;S<c+m;S++){const I={w:h,hd:0};u?i.insertMatrixArray(S,(C=u[S-a.startColumn])!=null?C:I,d):i.insertMatrixArray(S,I,d)}return o.setColumnCount(o.getColumnCount()+a.endColumn-a.startColumn+1),o.getCellMatrix().insertColumns(a.startColumn,m),!0}},Le={id:"sheet.mutation.move-range",type:i.CommandType.MUTATION,handler:(s,e)=>{const{from:t,to:n}=e;if(!t||!n)return!1;const r=s.get(i.IUniverInstanceService).getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET);if(!r)return!1;const a=r.getSheetBySheetId(e.from.subUnitId),u=r.getSheetBySheetId(e.to.subUnitId);if(!a||!u)return!1;const l=a.getCellMatrix(),d=u.getCellMatrix();return new i.ObjectMatrix(t.value).forValue((c,m,h)=>{h==null?l.realDeleteValue(c,m):l.setValue(c,m,h)}),new i.ObjectMatrix(n.value).forValue((c,m,h)=>{h==null?d.realDeleteValue(c,m):d.setValue(c,m,h)}),!0}};function co(s,e){const{unitId:t,subUnitId:n,sourceRange:o,targetRange:r}=e,a=o.startRow>r.startRow,u=o.endRow-o.startRow+1;return a?{unitId:t,subUnitId:n,sourceRange:i.Rectangle.clone(r),targetRange:{...o,endRow:o.endRow+u,startRow:o.startRow+u}}:{unitId:t,subUnitId:n,targetRange:i.Rectangle.clone(o),sourceRange:{...r,endRow:r.endRow-u,startRow:r.startRow-u}}}const pe={id:"sheet.mutation.move-rows",type:i.CommandType.MUTATION,handler:(s,e)=>{const{unitId:t,subUnitId:n,sourceRange:o,targetRange:r}=e,u=s.get(i.IUniverInstanceService).getUniverSheetInstance(t);if(!u)throw new Error("[MoveRowMutation] univerSheet is null!");const l=u.getSheetBySheetId(n);if(!l)throw new Error("[MoveRowMutation] worksheet is null!");const d=o.startRow,c=o.endRow-o.startRow+1,m=r.startRow,h=l.getRowManager().getRowData();return i.moveMatrixArray(d,c,m,h),l.getCellMatrix().moveRows(d,c,m),!0}};function mo(s,e){const{unitId:t,subUnitId:n,sourceRange:o,targetRange:r}=e,a=o.startColumn>r.startColumn,u=o.endColumn-o.startColumn+1;return a?{unitId:t,subUnitId:n,sourceRange:i.Rectangle.clone(r),targetRange:{...o,endColumn:o.endColumn+u,startColumn:o.startColumn+u}}:{unitId:t,subUnitId:n,targetRange:i.Rectangle.clone(o),sourceRange:{...r,startColumn:r.startColumn-u,endColumn:r.endColumn-u}}}const we={id:"sheet.mutation.move-columns",type:i.CommandType.MUTATION,handler:(s,e)=>{const{unitId:t,subUnitId:n,sourceRange:o,targetRange:r}=e,u=s.get(i.IUniverInstanceService).getUniverSheetInstance(t);if(!u)throw new Error("[MoveColumnMutation] univerSheet is null!");const l=u.getSheetBySheetId(n);if(!l)throw new Error("[MoveColumnMutation] worksheet is null!");const d=o.startColumn,c=o.endColumn-o.startColumn+1,m=r.startColumn,h=l.getColumnManager().getColumnData();return i.moveMatrixArray(d,c,m,h),l.getCellMatrix().moveColumns(d,c,m),!0}},ca=(s,e)=>{const o=e.getRowManager().getRowData(),r={},a=s.range,u=i.sliceMatrixArray(a.startRow,a.endRow,o),l=i.concatMatrixArray(r,u);return{unitId:s.unitId,subUnitId:s.subUnitId,range:s.range,rowInfo:l}},ae={id:"sheet.mutation.remove-rows",type:i.CommandType.MUTATION,handler:(s,e)=>{const n=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(n==null)throw new Error("universheet is null error!");const o=n.getSheetBySheetId(e.subUnitId);if(!o)return!1;const r=e.range,u=o.getRowManager().getRowData();for(let c=r.startRow;c<=r.endRow;c++)o.getRowFiltered(c);const l=r.endRow-r.startRow+1;return i.spliceArray(r.startRow,l,u),o.getCellMatrix().removeRows(r.startRow,l),o.setRowCount(o.getRowCount()-l),!0}},ma=(s,e)=>{const n=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(n==null)throw new Error("universheet is null error!");const o=n.getSheetBySheetId(e.subUnitId);if(o==null)throw new Error("worksheet is null error!");const u=o.getColumnManager().getColumnData(),l={},d=e.range,c=i.sliceMatrixArray(d.startColumn,d.endColumn,u),m=i.concatMatrixArray(l,c);return{unitId:e.unitId,subUnitId:e.subUnitId,range:e.range,colInfo:m}},ne={id:"sheet.mutation.remove-col",type:i.CommandType.MUTATION,handler:(s,e)=>{const n=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(n==null)throw new Error("universheet is null error!");const o=n.getSheetBySheetId(e.subUnitId);if(!o)return!1;const r=e.range,u=o.getColumnManager().getColumnData(),l=r.endColumn-r.startColumn+1;return i.spliceArray(r.startColumn,l,u),o.setColumnCount(o.getColumnCount()-l),o.getCellMatrix().removeColumns(r.startColumn,l),!0}},ue=(s,e)=>{const n=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(n==null)throw new Error("universheet is null error!");const o=n.getSheetBySheetId(e.subUnitId);if(o==null)throw new Error("worksheet is null error!");const a=o.getConfig().mergeData,u=e.ranges,l=[];for(let d=0;d<u.length;d++)for(let c=a.length-1;c>=0;c--){const m=a[c],h=u[d];i.Rectangle.intersects(m,h)&&l.push(a[c])}return{unitId:e.unitId,subUnitId:e.subUnitId,ranges:l}},G={id:"sheet.mutation.remove-worksheet-merge",type:i.CommandType.MUTATION,handler:(s,e)=>{const n=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(n==null)throw new Error("universheet is null error!");const o=n.getSheetBySheetId(e.subUnitId);if(!o)return!1;const a=o.getConfig().mergeData,u=e.ranges;for(let l=0;l<u.length;l++)for(let d=a.length-1;d>=0;d--){const c=a[d],m=u[l];i.Rectangle.intersects(c,m)&&a.splice(d,1)}return o.getSpanModel().rebuild(a),!0}},ho=s=>{const{order:e}=s,t={};return Object.keys(e).forEach(n=>{t[e[Number(n)]]=Number(n)}),{...s,order:t}},Ot={id:"sheet.mutation.reorder-range",type:i.CommandType.MUTATION,handler:(s,e)=>{const{subUnitId:t,unitId:n,range:o,order:r}=e,l=s.get(i.IUniverInstanceService).getUnit(n).getSheetBySheetId(t);if(!l)return!1;const d=new i.ObjectMatrix;i.Range.foreach(o,(m,h)=>{if(r.hasOwnProperty(m)){const R=r[m],C=i.Tools.deepClone(l.getCellRaw(R,h));d.setValue(m,h,C)}});const c=l.getCellMatrix();return d.forValue((m,h,R)=>{c.setValue(m,h,R)}),!0}};function ha(s,e){if(s==null)return s;const t=i.Tools.deepClone(s);if(e==null)return t;const n={};return"h"in e&&(n.h=t.h),"ia"in e&&(n.ia=t.ia),"ah"in e&&(n.ah=t.ah),"hd"in e&&(n.hd=t.hd),"s"in e&&(n.s=t.s),"custom"in e&&(n.custom=t.custom),n}function ga(s,e){if(s==null)return s;const t=i.Tools.deepClone(s);if(e==null)return t;const n={};return"w"in e&&(n.w=t.w),"hd"in e&&(n.hd=t.hd),"s"in e&&(n.s=t.s),"custom"in e&&(n.custom=t.custom),n}const go=(s,e)=>{const{unitId:t,subUnitId:n,columnData:o}=s,r={},a=e.getColumnManager();for(const u in o){const l=o[u],d=a.getColumn(Number(u));r[u]=ga(d,l)}return{unitId:t,subUnitId:n,columnData:r}},at={id:"sheet.mutation.set-col-data",type:i.CommandType.MUTATION,handler:(s,e)=>{const{columnData:t}=e,n=s.get(i.IUniverInstanceService),o=P(n,e);if(!o)return!1;const{worksheet:r}=o,a=r.getColumnManager();for(const u in t){const l=t[u];if(l==null){a.removeColumn(Number(u));continue}const d=a.getColumnOrCreate(Number(u));Object.assign(d,l)}return!0}},Ra=(s,e)=>{if(s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId)==null)throw new Error("universheet is null error!");return{unitId:e.unitId,subUnitId:e.subUnitId,ranges:e.ranges}},ut={id:"sheet.mutation.set-col-hidden",type:i.CommandType.MUTATION,handler:(s,e)=>{const n=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(!n)return!1;const o=n.getSheetBySheetId(e.subUnitId).getColumnManager();for(let r=0;r<e.ranges.length;r++){const a=e.ranges[r];for(let u=a.startColumn;u<a.endColumn+1;u++){const l=o.getColumnOrCreate(u);l!=null&&(l.hd=i.BooleanNumber.TRUE)}}return!0}},Ca=(s,e)=>{if(s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId)==null)throw new Error("universheet is null error!");return{unitId:e.unitId,subUnitId:e.subUnitId,ranges:e.ranges}},lt={id:"sheet.mutation.set-col-visible",type:i.CommandType.MUTATION,handler:(s,e)=>{const n=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(!n)return!1;const o=n.getSheetBySheetId(e.subUnitId).getColumnManager();for(let r=0;r<e.ranges.length;r++){const a=e.ranges[r];for(let u=a.startColumn;u<a.endColumn+1;u++){const l=o.getColumnOrCreate(u);l!=null&&(l.hd=i.BooleanNumber.FALSE)}}return!0}},dt={id:"sheet.mutation.set-gridlines-color",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=P(s.get(i.IUniverInstanceService),e);if(!t)return!1;const{worksheet:n}=t,o=n.getConfig();return o.gridlinesColor=e.color,!0}};function Sa(s,e,t){var a;const n=s.getStyleByCell(e);n==null&&delete e.s,typeof t.s=="string"&&(t.s=s.get(t.s));const o=tn(n,t.s?t.s:null);o&&(i.Tools.removeNull(o),Object.entries(o).forEach(([u,l])=>{typeof l=="object"&&l!==null&&Object.keys(l).length===0&&delete o[u]})),i.Tools.isEmptyObject(o)?delete e.s:e.s=s.setValue(o);const r=t.v?`${t.v}\r
|
|
11
|
-
`:"";!t.p&&e.p&&(r&&r!==((a=e.p.body)==null?void 0:a.dataStream)?delete e.p:
|
|
12
|
-
`)?s.body.dataStream.length-2:s.body.dataStream.length;if(t<r){const u={st:t,ed:r},l=tn({},e,!0);l&&i.Tools.removeNull(l),i.Tools.isEmptyObject(l)||(u.ts=l),n.push(u)}s.body.textRuns=i.normalizeTextRuns(n)}function Co(s,e){return e.v===void 0||e.v===null?e.v:s===i.CellValueType.NUMBER?Number(e.v):s===i.CellValueType.BOOLEAN?pa(e.v)?1:0:s===i.CellValueType.STRING||s===i.CellValueType.FORCE_STRING?`${e.v}`:e.v}function pa(s){if(typeof s=="string"){if(s.toUpperCase()==="TRUE")return!0;if(s.toUpperCase()==="FALSE")return!1;if(i.isSafeNumeric(s)){if(Number(s)===0)return!1;if(Number(s)===1)return!0}}if(typeof s=="number"){if(s===0)return!1;if(s===1)return!0}return typeof s=="boolean"?s:null}function wa(s){return s==null?null:(s.f===void 0&&(s.f=null),s.si===void 0&&(s.si=null),s.p===void 0&&(s.p=null),s.v===void 0&&(s.v=null),s.t===void 0&&(s.t=null),s.s===void 0&&(s.s=null),s.custom===void 0&&(s.custom=null),s)}const ce=(s,e)=>{const{unitId:t,subUnitId:n,cellValue:o}=e,a=s.get(i.IUniverInstanceService).getUniverSheetInstance(t);if(a==null)throw new Error("workbook is null error!");const u=a.getSheetBySheetId(n);if(u==null)throw new Error("worksheet is null error!");const l=u.getCellMatrix(),d=a.getStyles(),c=new i.ObjectMatrix;return new i.ObjectMatrix(o).forValue((h,R,C)=>{const S=i.Tools.deepClone(l==null?void 0:l.getValue(h,R))||{},I=d.getStyleByCell(S),v=d.getStyleByCell(C);S.s=fa(I,v),c.setValue(h,R,wa(S))}),{...e,options:{},cellValue:c.getMatrix()}},F={id:"sheet.mutation.set-range-values",type:i.CommandType.MUTATION,handler:(s,e)=>{const{cellValue:t,subUnitId:n,unitId:o}=e,a=s.get(i.IUniverInstanceService).getUnit(o);if(!a)return!1;const u=a.getSheetBySheetId(n);if(!u)return!1;const l=u.getCellMatrix(),d=a.getStyles();return new i.ObjectMatrix(t).forValue((m,h,R)=>{if(!R)l.realDeleteValue(m,h);else{let C=l.getValue(m,h)||{};C=ya(R,C,d),i.Tools.isEmptyObject(C)?l.realDeleteValue(m,h):l.setValue(m,h,C)}}),!0}},Ma=new Set(["f","p","si","custom","ref","xf"]);function ya(s,e,t){const n=Hi(t,s,e);return Object.keys(s).forEach(o=>{const r=o;if(Ma.has(r)){const a=s[r];_a(e,r,a)}else r==="v"?s.v!==void 0&&(e.v=Co(n,s)):r==="s"&&Sa(t,e,s)}),e.v!==void 0&&(e.t=n,e.v=Co(n,e)),e.v===null&&(delete e.t,delete e.v),e}function _a(s,e,t){t===void 0||(t===null?delete s[e]:s[e]=t)}const So=(s,e)=>{const{unitId:t,subUnitId:n,rowData:o}=s,r={},a=e.getRowManager();for(const u in o){const l=o[u],d=a.getRow(Number(u));r[u]=ha(d,l)}return{unitId:t,subUnitId:n,rowData:r}},ct={id:"sheet.mutation.set-row-data",type:i.CommandType.MUTATION,handler:(s,e)=>{const{rowData:t}=e,n=s.get(i.IUniverInstanceService),o=P(n,e);if(!o)return!1;const{worksheet:r}=o,a=r.getRowManager();for(const u in t){const l=t[u];if(l==null){a.removeRow(Number(u));continue}const d=a.getRowOrCreate(Number(u));Object.assign(d,l)}return!0}},ba=(s,e)=>{if(s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId)==null)throw new Error("universheet is null error!");return{unitId:e.unitId,subUnitId:e.subUnitId,ranges:e.ranges}},Ye={id:"sheet.mutation.set-row-visible",type:i.CommandType.MUTATION,handler:(s,e)=>{const n=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(n==null)throw new Error("universheet is null error!");const o=n.getSheetBySheetId(e.subUnitId).getRowManager();for(let r=0;r<e.ranges.length;r++){const a=e.ranges[r];for(let u=a.startRow;u<a.endRow+1;u++){const l=o.getRowOrCreate(u);l!=null&&(l.hd=0)}}return!0}},Ea=(s,e)=>{if(s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId)==null)throw new Error("universheet is null error!");return{unitId:e.unitId,subUnitId:e.subUnitId,ranges:e.ranges}},Ke={id:"sheet.mutation.set-row-hidden",type:i.CommandType.MUTATION,handler:(s,e)=>{const n=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(n==null)throw new Error("universheet is null error!");const o=n.getSheetBySheetId(e.subUnitId).getRowManager();for(let r=0;r<e.ranges.length;r++){const a=e.ranges[r];for(let u=a.startRow;u<a.endRow+1;u++){const l=o.getRowOrCreate(u);l!=null&&(l.hd=1)}}return!0}};function Hn(s){const e={},t={},n=Object.keys(s).map(Number).sort((o,r)=>o-r);if(n.length===0)return e;for(const o of n){const r=s[o];if(!i.Tools.isDefine(r))continue;const a=String(r);t[a]||(t[a]=[]),t[a].push(o)}for(const[o,r]of Object.entries(t)){const a=[];if(r.length===0)continue;let u=r[0],l=u;for(let d=1;d<r.length;d++){const c=r[d];c!==l+1&&(u===l?a.push(u):a.push([u,l]),u=c),l=c}u===l?a.push(u):a.push([u,l]),a.length===1&&typeof a[0]=="number"?e[o]=a[0]:e[o]=a}return e}function Fn(s){const e={};for(const[t,n]of Object.entries(s)){const o=Number(t);if(typeof n=="number"){e[n]=o;continue}for(const r of n)if(Array.isArray(r)){const[a,u]=r;for(let l=a;l<=u;l++)e[l]=o}else e[r]=o}return e}const jn=(s,e)=>{const{unitId:t,subUnitId:n,ranges:o}=s,r={},a=e.getColumnManager();for(let u=0;u<o.length;u++){const l=o[u];for(let d=l.startColumn;d<l.endColumn+1;d++)r[d]=a.getColumnWidth(d)}return{unitId:t,subUnitId:n,ranges:o,colWidth:{compress:!0,data:Hn(r)}}},Ve={id:"sheet.mutation.set-worksheet-col-width",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=s.get(i.IUniverInstanceService),n=P(t,e);if(!n)return!1;const{worksheet:o}=n,r=o.getColumnManager(),a=e.ranges;for(let u=0;u<a.length;u++){const l=a[u];for(let d=l.startColumn;d<l.endColumn+1;d++)if(o.getColVisible(d))if(typeof e.colWidth=="number")r.setColumnWidth(d,e.colWidth);else if(e.colWidth&&typeof e.colWidth=="object"&&"compress"in e.colWidth){const{data:m}=e.colWidth,h=Fn(m);i.Tools.isDefine(h[d])&&r.setColumnWidth(d,h[d])}else i.Tools.isDefine(e.colWidth[d])&&r.setColumnWidth(d,e.colWidth[d])}return!0}},fo=(s,e)=>{const t=ve(s.get(i.IUniverInstanceService),e);if(!t)throw new Error("[SetWorksheetColumnCountUndoMutationFactory]: worksheet is null error!");return{unitId:e.unitId,subUnitId:e.subUnitId,columnCount:t.worksheet.getColumnCount()}},mt={id:"sheet.mutation.set-worksheet-column-count",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=s.get(i.IUniverInstanceService),n=ve(t,e);return n?(n.worksheet.setColumnCount(e.columnCount),!0):!1}},ht={id:"sheet.mutation.set-worksheet-default-style",type:i.CommandType.MUTATION,handler:(s,e)=>{const{defaultStyle:t}=e,n=s.get(i.IUniverInstanceService),o=P(n);if(!o)return!1;const{worksheet:r}=o;return r?(r.setDefaultCellStyle(t),!0):!1}},Io=(s,e)=>{const t=ve(s.get(i.IUniverInstanceService),e);if(!t)throw new Error("[SetWorksheetDefaultStyleMutationFactory]: worksheet is null error!");const{worksheet:n}=t;return{unitId:e.unitId,subUnitId:n.getSheetId(),defaultStyle:n.getDefaultCellStyle()}},vo=(s,e)=>{const t=ve(s.get(i.IUniverInstanceService),e);if(!t)throw new Error("[SetWorksheetRowCountUndoMutationFactory]: worksheet is null error!");return{unitId:e.unitId,subUnitId:e.subUnitId,rowCount:t.worksheet.getRowCount()}},gt={id:"sheet.mutation.set-worksheet-row-count",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=s.get(i.IUniverInstanceService),n=ve(t,e);return n?(n.worksheet.setRowCount(e.rowCount),!0):!1}},po=(s,e)=>{var u,l;const{unitId:t,subUnitId:n,ranges:o}=s,r={},a=e.getRowManager();for(const{startRow:d,endRow:c}of o)for(let m=d;m<c+1;m++)r[m]=(l=(u=a.getRow(m))==null?void 0:u.h)!=null?l:e.getConfig().defaultRowHeight;return{unitId:t,subUnitId:n,ranges:o,rowHeight:{compress:!0,data:Hn(r)}}},Gn=(s,e)=>{var u;const{unitId:t,subUnitId:n,ranges:o}=s,r={},a=e.getRowManager();for(const{startRow:l,endRow:d}of o)for(let c=l;c<=d;c++)r[c]=(u=a.getRow(c))==null?void 0:u.ia;return{unitId:t,subUnitId:n,ranges:o,autoHeightInfo:r}},Ta=(s,e)=>{var u,l;const{unitId:t,subUnitId:n,rowsAutoHeightInfo:o}=s,r=[],a=e.getRowManager();for(const d of o){const{row:c}=d;r.push({row:c,autoHeight:(l=(u=a.getRow(c))==null?void 0:u.ah)!=null?l:e.getConfig().defaultRowHeight})}return{unitId:t,subUnitId:n,rowsAutoHeightInfo:r}},Ee={id:"sheet.mutation.set-worksheet-row-height",type:i.CommandType.MUTATION,handler:(s,e)=>{const{ranges:t,rowHeight:n}=e,o=s.get(i.IUniverInstanceService),r=P(o,e);if(!r)return!1;const{worksheet:a}=r,u=a.getRowManager();for(const{startRow:l,endRow:d}of t)for(let c=l;c<=d;c++)if(typeof n=="number")u.setRowHeight(c,n);else if(n&&typeof n=="object"&&"compress"in n){const{data:m}=n,h=Fn(m);i.Tools.isDefine(h[c])&&u.setRowHeight(c,h[c])}else i.Tools.isDefine(n[c])&&u.setRowHeight(c,n[c]);return!0}},Re={id:"sheet.mutation.set-worksheet-row-is-auto-height",type:i.CommandType.MUTATION,handler:(s,e)=>{var u;const{ranges:t,autoHeightInfo:n}=e,o=s.get(i.IUniverInstanceService),r=P(o,e);if(!r)return!1;const a=r.worksheet.getRowManager();for(const{startRow:l,endRow:d}of t)for(let c=l;c<=d;c++){const m=a.getRowOrCreate(c);typeof n=="number"?m.ia=n:m.ia=(u=n[c])!=null?u:void 0}return!0}},zn={id:"sheet.mutation.set-worksheet-row-auto-height",type:i.CommandType.MUTATION,handler:(s,e)=>{const{rowsAutoHeightInfo:t}=e,n=s.get(i.IUniverInstanceService),o=P(n,e);if(!o)return!1;const r=o.worksheet.getRowManager();for(const{row:a,autoHeight:u}of t){const l=r.getRowOrCreate(a);l.ah=u}return!0}},Rt={id:"sheet.mutation.toggle-gridlines",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=P(s.get(i.IUniverInstanceService),e);if(!t)return!1;const{worksheet:n}=t,o=n.getConfig();return o.showGridlines=e.showGridlines,!0}},Ct={id:"sheet.operation.set-worksheet-active",type:i.CommandType.OPERATION,handler:(s,e)=>{const t=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(!t)return!1;const n=t.getWorksheets();for(const[,o]of n)if(o.getSheetId()===e.subUnitId)return t.setActiveSheet(o),!0;return!1}};var wo=(s=>(s.SET_WORKSHEET_ROW_HEIGHT="sheet.mutation.set-worksheet-row-height",s.SET_WORKSHEET_ROW_IS_AUTO_HEIGHT="sheet.mutation.set-worksheet-row-is-auto-height",s.SET_WORKSHEET_ROW_AUTO_HEIGHT="sheet.mutation.set-worksheet-row-auto-height",s.SET_WORKSHEET_COL_WIDTH="sheet.mutation.set-worksheet-col-width",s.SET_WORKSHEET_ACTIVE="sheet.operation.set-worksheet-active",s.MOVE_ROWS="sheet.mutation.move-rows",s.MOVE_COLUMNS="sheet.mutation.move-columns",s.SET_COL_HIDDEN="sheet.mutation.set-col-hidden",s.SET_COL_VISIBLE="sheet.mutation.set-col-visible",s.SET_ROW_HIDDEN="sheet.mutation.set-row-hidden",s.SET_ROW_VISIBLE="sheet.mutation.set-row-visible",s.INSERT_COL="sheet.mutation.insert-col",s.INSERT_ROW="sheet.mutation.insert-row",s.REMOVE_COL="sheet.mutation.remove-col",s.REMOVE_ROW="sheet.mutation.remove-rows",s.TOGGLE_GRIDLINES="sheet.mutation.toggle-gridlines",s.SET_GRIDLINES_COLOR="sheet.mutation.set-gridlines-color",s))(wo||{}),Mo=(s=>(s.SET_RANGE_VALUES="sheet.mutation.set-range-values",s.MOVE_RANGE="sheet.mutation.move-range",s.REMOVE_WORKSHEET_MERGE="sheet.mutation.remove-worksheet-merge",s.ADD_WORKSHEET_MERGE="sheet.mutation.add-worksheet-merge",s.REORDER_RANGE="sheet.mutation.reorder-range",s.SET_WORKSHEET_DEFAULT_STYLE="sheet.mutation.set-worksheet-default-style",s.SET_ROW_DATA="sheet.mutation.set-row-data",s.SET_COL_DATA="sheet.mutation.set-col-data",s.SET_WORKSHEET_RANGE_THEME_STYLE="sheet.mutation.set-worksheet-range-theme-style",s.DELETE_WORKSHEET_RANGE_THEME_STYLE="sheet.mutation.delete-worksheet-range-theme-style",s))(Mo||{});const Ua=[Ee.id,Re.id,zn.id,Ve.id,Ct.id,pe.id,we.id,ut.id,lt.id,Ke.id,Ye.id,ie.id,re.id,ne.id,ae.id,Rt.id,dt.id,gt.id,mt.id],Pa=[F.id,Le.id,G.id,j.id,Ot.id,ht.id,ct.id,at.id,rt.id,it.id];function ka(s){switch(s.id){case"sheet.mutation.set-range-values":{const e=s.params,t=new i.ObjectMatrix(e.cellValue).getDataRange();return t.endRow===-1?[]:e.cellValue?[{unitId:e.unitId,subUnitId:e.subUnitId,range:t}]:[]}case"sheet.mutation.move-range":{const e=s.params;return[{unitId:e.unitId,subUnitId:e.from.subUnitId,range:new i.ObjectMatrix(e.from.value).getRange()},{unitId:e.unitId,subUnitId:e.to.subUnitId,range:new i.ObjectMatrix(e.to.value).getRange()}]}case"sheet.mutation.remove-worksheet-merge":{const e=s.params;return e.ranges.map(t=>({unitId:e.unitId,subUnitId:e.subUnitId,range:t}))}case"sheet.mutation.add-worksheet-merge":{const e=s.params;return e.ranges.map(t=>({unitId:e.unitId,subUnitId:e.subUnitId,range:t}))}case"sheet.mutation.reorder-range":{const e=s.params;return[{unitId:e.unitId,subUnitId:e.subUnitId,range:e.range}]}case"sheet.mutation.set-worksheet-default-style":{const e=s.params;return[{unitId:e.unitId,subUnitId:e.subUnitId,range:{startRow:0,endRow:Number.MAX_SAFE_INTEGER,startColumn:0,endColumn:Number.MAX_SAFE_INTEGER}}]}case"sheet.mutation.set-row-data":{const e=s.params,t=Object.keys(e.rowData).map(Number);return t.length===0?[]:[{unitId:e.unitId,subUnitId:e.subUnitId,range:{startRow:Math.min(...t),endRow:Math.max(...t),startColumn:0,endColumn:Number.MAX_SAFE_INTEGER}}]}case"sheet.mutation.set-col-data":{const e=s.params,t=Object.keys(e.columnData).map(Number);return t.length===0?[]:[{unitId:e.unitId,subUnitId:e.subUnitId,range:{startRow:0,endRow:Number.MAX_SAFE_INTEGER,startColumn:Math.min(...t),endColumn:Math.max(...t)}}]}case"sheet.mutation.set-worksheet-range-theme-style":case"sheet.mutation.delete-worksheet-range-theme-style":{const e=s.params;return[{unitId:e.unitId,subUnitId:e.subUnitId,range:e.range}]}default:return[]}}function Na(s,e){switch(s.id){case"sheet.mutation.set-worksheet-row-height":case"sheet.mutation.set-worksheet-row-is-auto-height":{const t=s.params;return t.ranges.map(n=>({unitId:t.unitId,subUnitId:t.subUnitId,range:{...n,rangeType:i.RANGE_TYPE.ROW}}))}case"sheet.mutation.set-worksheet-row-auto-height":{const t=s.params;return t.rowsAutoHeightInfo.map(n=>({unitId:t.unitId,subUnitId:t.subUnitId,range:{startRow:n.row,endRow:n.row,startColumn:0,endColumn:e-1,rangeType:i.RANGE_TYPE.ROW}}))}case"sheet.mutation.set-worksheet-col-width":{const t=s.params;return t.ranges.map(n=>({unitId:t.unitId,subUnitId:t.subUnitId,range:{...n,rangeType:i.RANGE_TYPE.COLUMN}}))}case"sheet.mutation.move-rows":case"sheet.mutation.move-columns":{const t=s.params;return[{unitId:t.unitId,subUnitId:t.subUnitId,range:t.targetRange},{unitId:t.unitId,subUnitId:t.subUnitId,range:t.sourceRange}]}case"sheet.mutation.set-col-hidden":case"sheet.mutation.set-col-visible":{const t=s.params;return t.ranges.map(n=>({unitId:t.unitId,subUnitId:t.subUnitId,range:{...n,rangeType:i.RANGE_TYPE.COLUMN}}))}case"sheet.mutation.set-row-hidden":case"sheet.mutation.set-row-visible":{const t=s.params;return t.ranges.map(n=>({unitId:t.unitId,subUnitId:t.subUnitId,range:{...n,rangeType:i.RANGE_TYPE.ROW}}))}case"sheet.mutation.insert-col":{const t=s.params;return[{unitId:t.unitId,subUnitId:t.subUnitId,range:{...t.range,rangeType:i.RANGE_TYPE.COLUMN}}]}case"sheet.mutation.insert-row":{const t=s.params;return[{unitId:t.unitId,subUnitId:t.subUnitId,range:{...t.range,rangeType:i.RANGE_TYPE.ROW}}]}case"sheet.mutation.remove-col":{const t=s.params;return[{unitId:t.unitId,subUnitId:t.subUnitId,range:{...t.range,rangeType:i.RANGE_TYPE.COLUMN}}]}case"sheet.mutation.remove-rows":{const t=s.params;return[{unitId:t.unitId,subUnitId:t.subUnitId,range:{...t.range,rangeType:i.RANGE_TYPE.ROW}}]}case"sheet.mutation.toggle-gridlines":case"sheet.mutation.set-gridlines-color":return[];default:return[]}}function yo(s){return s==null?!1:s.v!==void 0&&s.v!==null&&s.v!==""||s.p!==void 0}function nn(s,e){return s&&s.spanAnchor?yo(e.getValue(s.spanAnchor.startRow,s.spanAnchor.startColumn)):yo(s)}function Oa(s,e,t,n,o){const r=s.getCellMatrix(),a=s.getSpanModel().getMergedCellRange(e,t,n,o),u=new i.ObjectMatrix;return r.forValue((l,d)=>{const c=r.getValue(l,d);c&&u.setValue(l,d,c)}),a.forEach(l=>{const{startColumn:d,startRow:c,endColumn:m,endRow:h}=l;i.createRowColIter(c,h,d,m).forEach((R,C)=>{R===c&&C===d&&u.setValue(R,C,{...r.getValue(R,C),spanAnchor:{startRow:c,endRow:h,startColumn:d,endColumn:m}}),(R!==c||C!==d)&&(u.realDeleteValue(R,C),u.setValue(R,C,{spanAnchor:{startRow:c,endRow:h,startColumn:d,endColumn:m}}))})}),u}function Da(s,e,t,n){const{startRow:o,startColumn:r,endRow:a}=s;let u=null,l=!1;for(let d=o;d<=a;d++){const c=e.getValue(d,r-t);if(l=l||nn(c,e),!n&&l)break;c&&c.spanAnchor&&(u?u={startRow:Math.min(c.spanAnchor.startRow,u.startRow),startColumn:Math.min(c.spanAnchor.startColumn,u.startColumn),endRow:Math.max(c.spanAnchor.endRow,u.endRow),endColumn:Math.max(c.spanAnchor.endColumn,u.endColumn)}:u={startRow:c.spanAnchor.startRow,startColumn:c.spanAnchor.startColumn,endRow:c.spanAnchor.endRow,endColumn:c.spanAnchor.endColumn})}return l?(s.startColumn=s.startColumn-t,{spanAnchor:u,hasValue:!0,range:s}):{spanAnchor:null,hasValue:!1,range:s}}function Aa(s,e,t,n){const{startRow:o,endColumn:r,endRow:a}=s;let u=null,l=!1;for(let d=o;d<=a;d++){const c=e.getValue(d,r+t);if(l=l||nn(c,e),!n&&l)break;c&&c.spanAnchor&&(u?u={startRow:Math.min(c.spanAnchor.startRow,u.startRow),startColumn:Math.min(c.spanAnchor.startColumn,u.startColumn),endRow:Math.max(c.spanAnchor.endRow,u.endRow),endColumn:Math.max(c.spanAnchor.endColumn,u.endColumn)}:u={startRow:c.spanAnchor.startRow,startColumn:c.spanAnchor.startColumn,endRow:c.spanAnchor.endRow,endColumn:c.spanAnchor.endColumn})}return l?(s.endColumn=s.endColumn+t,{spanAnchor:u,hasValue:!0,range:s}):{spanAnchor:null,hasValue:!1,range:s}}function Wa(s,e,t,n){const{startRow:o,startColumn:r,endColumn:a}=s;let u=null,l=!1;for(let d=r;d<=a;d++){const c=e.getValue(o-t,d);if(l=l||nn(c,e),!n&&l)break;c&&c.spanAnchor&&(u?u={startRow:Math.min(c.spanAnchor.startRow,u.startRow),startColumn:Math.min(c.spanAnchor.startColumn,u.startColumn),endRow:Math.max(c.spanAnchor.endRow,u.endRow),endColumn:Math.max(c.spanAnchor.endColumn,u.endColumn)}:u={startRow:c.spanAnchor.startRow,startColumn:c.spanAnchor.startColumn,endRow:c.spanAnchor.endRow,endColumn:c.spanAnchor.endColumn})}return l?(s.startRow=s.startRow-t,{spanAnchor:u,hasValue:!0,range:s}):{spanAnchor:null,hasValue:!1,range:s}}function Va(s,e,t,n){const{startColumn:o,endColumn:r,endRow:a}=s;let u=null,l=!1;for(let d=o;d<=r;d++){const c=e.getValue(a+t,d);if(l=l||nn(c,e),!n&&l)break;c&&c.spanAnchor&&(u?u={startRow:Math.min(c.spanAnchor.startRow,u.startRow),startColumn:Math.min(c.spanAnchor.startColumn,u.startColumn),endRow:Math.max(c.spanAnchor.endRow,u.endRow),endColumn:Math.max(c.spanAnchor.endColumn,u.endColumn)}:u={startRow:c.spanAnchor.startRow,startColumn:c.spanAnchor.startColumn,endRow:c.spanAnchor.endRow,endColumn:c.spanAnchor.endColumn})}return l?(s.endRow=s.endRow+t,{spanAnchor:u,hasValue:!0,range:s}):{spanAnchor:null,hasValue:!1,range:s}}function $a(s,e,t){const n=t.getMaxRows(),o=t.getMaxColumns(),r=Oa(t,0,0,n-1,o-1),a=t.getSnapshot().mergeData.length>0,{left:u,right:l,up:d,down:c}=e;let m=!0,h={...s};const R=[];for(;m;){if(m=!1,d&&h.startRow!==0){const{hasValue:C,range:S,spanAnchor:I}=Wa(h,r,1,a);if(I&&R.push(I),C){h=S,m=!0;continue}}if(c&&h.endRow!==n-1){const{hasValue:C,range:S,spanAnchor:I}=Va(h,r,1,a);if(I&&R.push(I),C){h=S,m=!0;continue}}if(u&&h.startColumn!==0){const{hasValue:C,range:S,spanAnchor:I}=Da(h,r,1,a);if(I&&R.push(I),C){h=S,m=!0;continue}}if(l&&h.endColumn!==o-1){const{hasValue:C,range:S,spanAnchor:I}=Aa(h,r,1,a);if(I&&R.push(I),C){h=S,m=!0;continue}}}return R.length>0&&(h=i.Rectangle.union(h,...R)),h}const _o=s=>{const e=new i.ObjectMatrix;return s.forEach(t=>{i.Range.foreach(t,(n,o)=>{e.setValue(n,o,1)})}),e.forValue((t,n)=>{const o=e.getValue(t-1,n);o&&e.setValue(t,n,o+1)}),e},bo=s=>{const e=s;return e.forValue((t,n)=>{const o=s.getValue(t-1,n);o&&e.setValue(t,n,o+1)}),e},Eo=s=>{const e={area:0},t=(n,o)=>e.area<n?(e.area=n,e.range=o,!0):!1;return s.forValue((n,o,r)=>{let a=1,u=r;t(a*u,{startRow:n-u+1,endRow:n,startColumn:o,endColumn:o});const l={startRow:n-u+1,endRow:n,startColumn:0,endColumn:o};for(let d=o-1;d>=0&&s.getValue(n,d);d--){u=Math.min(s.getValue(n,d)||0,u),a++;const c=u*a;l.startColumn=d,l.startRow=n-u+1,t(c,l)}}),e},La=(s,e)=>{i.Range.foreach(e,(t,n)=>{s.realDeleteValue(t,n)});for(let t=e.startColumn;t<=e.endColumn;t++){const n=e.endRow+1;if(s.getValue(n,t)>0){s.setValue(n,t,1);let r=n+1;for(;s.getValue(r,t)>0;)s.setValue(r,t,s.getValue(r-1,t)+1),r++}}return s},qn=s=>{const e=[];let t=Eo(s);for(;t.area>0;)t.range&&(e.push(t.range),La(s,t.range)),t=Eo(s);return e},Yn=s=>{const e=_o(s);return qn(e)};class Ba{constructor(){f(this,"_matrix",new i.ObjectMatrix)}add(...e){return e.forEach(t=>{i.Range.foreach(t,(n,o)=>{this._matrix.setValue(n,o,1)})}),this}subtract(...e){return e.forEach(t=>{i.Range.foreach(t,(n,o)=>{this._matrix.realDeleteValue(n,o)})}),this}merge(){const e=bo(this._matrix);return qn(e)}}const Ha=1.5,Fa="rgba(255, 255, 255, 0.01)";function ja(s){const{rangeWithCoord:e,primaryWithCoord:t,style:n}=s,o={range:{startRow:e.startRow,startColumn:e.startColumn,endRow:e.endRow,endColumn:e.endColumn,rangeType:e.rangeType,unitId:e.unitId,sheetId:e.sheetId},primary:null,style:n};return t!=null&&(o.primary=To(t)),o}function To(s){const{actualRow:e,actualColumn:t,isMerged:n,isMergedMainCell:o}=s,{startRow:r,startColumn:a,endRow:u,endColumn:l}=s.mergeInfo;return{actualRow:e,actualColumn:t,isMerged:n,isMergedMainCell:o,startRow:r,startColumn:a,endRow:u,endColumn:l}}var Uo=(s=>(s[s.Tab=1]="Tab",s[s.Comma=2]="Comma",s[s.Semicolon=4]="Semicolon",s[s.Space=8]="Space",s[s.Custom=16]="Custom",s))(Uo||{});class Ga{constructor(){f(this,"_tabCount",0);f(this,"_commaCount",0);f(this,"_semicolonCount",0);f(this,"_spaceCount",0)}add(e){switch(e){case" ":this._tabCount++;break;case",":this._commaCount++;break;case";":this._semicolonCount++;break;case" ":this._spaceCount++;break}}update(e){e&&typeof e=="string"&&(e.includes(" ")&&this._tabCount++,e.includes(",")&&this._commaCount++,e.includes(";")&&this._semicolonCount++,e.trim().includes(" ")&&this._spaceCount++)}getDelimiter(){const e=Math.max(this._tabCount,this._commaCount,this._semicolonCount,this._spaceCount);return e===0||e===this._tabCount?1:e===this._commaCount?2:e===this._semicolonCount?4:e===this._spaceCount?8:1}}function za(s,e,t){const n=[];t!==void 0&&(s&16)>0&&n.push(t),(s&1)>0&&n.push(" "),(s&2)>0&&n.push(","),(s&4)>0&&n.push(";"),(s&8)>0&&n.push(" ");let o="";for(const a of n)o+=qa(a);let r="[".concat(o,"]");return e&&(r+="+"),new RegExp(r)}function qa(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Ya=s=>{var t;return((t=s.body)==null?void 0:t.dataStream.replace(/\r\n$/,""))||""};function Ka(s){if(s!=null){if(s.p)return Ya(s.p);if(s.v&&typeof s.v=="string")return s.v;if(s.t&&(s.t===i.CellValueType.FORCE_STRING||s.t===i.CellValueType.STRING))return String(s.v)}}function Po(s,e,t,n,o=!1){const r=i.Range.transformRange(e,s),{startColumn:a,startRow:u,endColumn:l,endRow:d}=r;if(a!==l)throw new Error("The range must be in the same column.");if(t&&(t&16)>0&&(n===void 0||n.length!==1))throw new Error("The custom delimiter must a character.");const c=t===void 0,m=c?new Ga:null,h=[];for(let p=u;p<=d;p++){const w=s.getCell(p,a),y=Ka(w);h.push(y),m&&m.update(y)}const R=c?m.getDelimiter():t,C=za(R,o,n);let S=-1,I=0,v=0;const M=[];for(const p of h){if(p!==void 0){const w=String(p).split(C);S<0?S=w.length:S=Math.max(S,w.length),M.push(w),I=v}else M.push(void 0);v++}return{rs:M,maxLength:S===-1?0:S,lastRow:I}}const Ja=(s,e,t="")=>s.reduce((n,o)=>{const r=o&&o[e];return typeof r!="string"?(console.warn(o,`${e} is not string`),n):(r?(n[r]||(n[r]=[]),n[r].push(o)):n[t].push(o),n)},{}),xa=(s=0)=>{let e=s;return function(){return e++}};function Xa(s){return s==null?!1:s.v!==void 0&&s.v!==null&&s.v!==""||s.p!==void 0}function Za(s,e){for(let t=s.startRow;t<=s.endRow;t++)for(let n=s.startColumn;n<=s.endColumn;n++){const o=e.getCell(t,n);if(Xa(o))return{startRow:t,startColumn:n,endRow:t,endColumn:n}}return null}function Kn(s){const e=new i.ObjectMatrix;return s.forEach(t=>{const{startRow:n,startColumn:o,endRow:r,endColumn:a}=t;for(let u=n;u<=r;u++)for(let l=o;l<=a;l++)e.setValue(u,l,null)}),e.clone()}function ko(s){const e=new i.ObjectMatrix;return s.forEach(t=>{const{startRow:n,startColumn:o,endRow:r,endColumn:a}=t;for(let u=n;u<=r;u++)for(let l=o;l<=a;l++)e.setValue(u,l,{v:null,p:null,f:null,si:null,custom:null})}),e.clone()}function Qa(s){const e=new i.ObjectMatrix;return s.forEach(t=>{const{startRow:n,startColumn:o,endRow:r,endColumn:a}=t;for(let u=n;u<=r;u++)for(let l=o;l<=a;l++)e.setValue(u,l,{s:null})}),e.clone()}function No(s,e,t,n){const o=e.get(i.IUniverInstanceService),r=t?o.getUnit(t,i.UniverInstanceType.UNIVER_SHEET):o.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET),a=n?r==null?void 0:r.getSheetBySheetId(n):r==null?void 0:r.getActiveSheet();if(!a)return null;const{startRow:u,endRow:l,startColumn:d,endColumn:c}=s,m=[],h=[];for(let R=u;R<=l;R++)a.getRowFiltered(R)||m.push(R);for(let R=d;R<=c;R++)h.push(R);return{rows:m,cols:h}}function Dt(s,e,t,n){const o=[],r=[];for(const h of s){const R=No(h,e,t,n);R&&(o.push(...R.rows),r.push(...R.cols))}const a=Array.from(new Set(o)).sort((h,R)=>h-R),u=Array.from(new Set(r)).sort((h,R)=>h-R),l=[];function d(h){const R=[];let C=h[0];for(let S=1;S<h.length;S++)h[S]!==h[S-1]+1&&(R.push([C,h[S-1]]),C=h[S]);return R.push([C,h[h.length-1]]),R}const c=d(a),m=d(u);for(const[h,R]of c)for(const[C,S]of m)l.push({startRow:h,endRow:R,startColumn:C,endColumn:S});return l}var Oo=(s=>(s.OthersCanView="othersCanView",s.NoOneElseCanView="noOneElseCanView",s))(Oo||{}),Do=(s=>(s.DesignedUserCanEdit="designedUserCanEdit",s.OnlyMe="onlyMe",s))(Do||{});class X{constructor(){f(this,"_model",new Map);f(this,"_ruleChange$",new O.Subject);f(this,"ruleChange$",this._ruleChange$.asObservable());f(this,"_ruleRefresh$",new O.Subject);f(this,"ruleRefresh$",this._ruleRefresh$.asObservable());f(this,"_rangeRuleInitStateChange",new O.BehaviorSubject(!1));f(this,"rangeRuleInitStateChange$",this._rangeRuleInitStateChange.asObservable())}dispose(){this._ruleChange$.complete(),this._ruleRefresh$.complete()}ruleRefresh(e){this._ruleRefresh$.next(e)}getRangeRuleInitState(){return this._rangeRuleInitStateChange.value}changeRuleInitState(e){this._rangeRuleInitStateChange.next(e)}addRule(e,t,n){this._ensureRuleMap(e,t).set(n.id,n),this._ruleChange$.next({unitId:e,subUnitId:t,rule:n,type:"add"})}deleteRule(e,t,n){var r,a,u,l;const o=(a=(r=this._model.get(e))==null?void 0:r.get(t))==null?void 0:a.get(n);o&&((l=(u=this._model.get(e))==null?void 0:u.get(t))==null||l.delete(n),this._ruleChange$.next({unitId:e,subUnitId:t,rule:o,type:"delete"}))}setRule(e,t,n,o){var a,u;const r=this.getRule(e,t,n);r&&((u=(a=this._model.get(e))==null?void 0:a.get(t))==null||u.set(n,o),this._ruleChange$.next({unitId:e,subUnitId:t,oldRule:r,rule:o,type:"set"}))}getRule(e,t,n){var o,r;return(r=(o=this._model.get(e))==null?void 0:o.get(t))==null?void 0:r.get(n)}getSubunitRuleList(e,t){var o;return[...(((o=this._model.get(e))==null?void 0:o.get(t))||new Map).values()]}getSubunitRuleListLength(e,t){var o;const n=(o=this._model.get(e))==null?void 0:o.get(t);return n?n.size:0}_ensureRuleMap(e,t){let n=this._model.get(e);n||(n=new Map,this._model.set(e,n));let o=n.get(t);return o||(o=new Map,n.set(t,o)),o}toObject(){const e={};return[...this._model.keys()].forEach(n=>{const o=this._model.get(n),r=[...o.keys()];e[n]={},r.forEach(a=>{const u=o.get(a);e[n][a]=[...u.values()]})}),e}fromObject(e){const t=new Map;Object.keys(e).forEach(n=>{const o=e[n],r=new Map;Object.keys(o).forEach(a=>{const u=o[a].reduce((l,d)=>(l.set(d.id,d),l),new Map);r.set(a,u)}),t.set(n,r)}),this._model=t}deleteUnitModel(e){this._model.delete(e)}createRuleId(e,t){let n=i.generateRandomId(4);const o=this._ensureRuleMap(e,t);for(;o.has(n);)n=i.generateRandomId(4);return n}getTargetByPermissionId(e,t){const n=this._model.get(e);if(!n)return null;for(const[o,r]of n)for(const a of r.values())if(a.permissionId===t)return[e,o];return null}}const eu=(s,e)=>{const t=s.get(X),n=e.ruleIds.map(r=>t.getRule(e.unitId,e.subUnitId,r)).filter(r=>!!r);return{id:Ce.id,params:{subUnitId:e.subUnitId,unitId:e.unitId,rules:n}}},Te={id:"sheet.mutation.delete-range-protection",type:i.CommandType.MUTATION,handler:(s,e)=>{const{unitId:t,subUnitId:n,ruleIds:o}=e,r=s.get(X);return o.forEach(a=>{r.deleteRule(t,n,a)}),!0}},tu=s=>{const e={...s,ruleIds:s.rules.map(t=>t.id)};return{id:Te.id,params:e}},Ce={id:"sheet.mutation.add-range-protection",type:i.CommandType.MUTATION,handler:(s,e)=>{const{unitId:t,subUnitId:n,rules:o}=e,r=s.get(X);return o.forEach(a=>{r.addRule(t,n,a)}),!0}},Ao={type:i.CommandType.COMMAND,id:"sheet.command.add-range-protection",async handler(s,e){if(!e)return!1;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(X),{rule:r,permissionId:a}=e,{unitId:u,subUnitId:l,ranges:d,description:c,viewState:m,editState:h}=r,R=[{ranges:d,permissionId:a,id:o.createRuleId(u,l),description:c,unitType:r.unitType,unitId:u,subUnitId:l,viewState:m,editState:h}];if(await t.executeCommand(Ce.id,{unitId:u,subUnitId:l,rules:R})){const S=[{id:Ce.id,params:{unitId:u,subUnitId:l,rules:R}}],I=[{id:Te.id,params:{unitId:u,subUnitId:l,ruleIds:R.map(v=>v.id)}}];n.pushUndoRedo({unitID:u,redoMutations:S,undoMutations:I})}return!0}};var te=(s=>(s[s.MOVE_START=0]="MOVE_START",s[s.MOVING=1]="MOVING",s[s.MOVE_END=2]="MOVE_END",s[s.ONLY_SET=3]="ONLY_SET",s))(te||{});class Wo extends i.Disposable{constructor(t){super();f(this,"_worksheetSelections",new Map);f(this,"_selectionMoveStart$",new O.Subject);f(this,"selectionMoveStart$",this._selectionMoveStart$.asObservable());f(this,"_selectionMoving$",new O.Subject);f(this,"selectionMoving$",this._selectionMoving$.asObservable());f(this,"_selectionMoveEnd$",new O.BehaviorSubject([]));f(this,"selectionMoveEnd$",this._selectionMoveEnd$.asObservable());f(this,"_selectionSet$",new O.BehaviorSubject([]));f(this,"selectionSet$",this._selectionSet$.asObservable());f(this,"selectionChanged$");f(this,"_beforeSelectionMoveEnd$",new O.BehaviorSubject([]));f(this,"beforeSelectionMoveEnd$",this._beforeSelectionMoveEnd$.asObservable());this._workbook=t,this.selectionChanged$=O.merge(this._selectionMoveEnd$,this._selectionSet$)}dispose(){super.dispose(),this._beforeSelectionMoveEnd$.complete(),this._selectionMoveEnd$.complete(),this._selectionMoving$.complete(),this._selectionMoveStart$.complete(),this._selectionSet$.complete(),this._workbook=null}addSelections(t,n){const o=this.getSelectionsOfWorksheet(t);o.push(...n),this._selectionSet$.next(o)}setSelections(t,n=[],o){switch(this.setSelectionsOfWorksheet(t,n),o){case te.MOVE_START:this._selectionMoveStart$.next(n);break;case te.MOVING:this._selectionMoving$.next(n);break;case te.MOVE_END:this._beforeSelectionMoveEnd$.next(n),this._selectionMoveEnd$.next(n);break;case te.ONLY_SET:{this._selectionSet$.next(n);break}default:this._selectionSet$.next(n);break}}getCurrentSelections(){return this._getCurrentSelections()}getSelectionOfWorksheet(t){return this.getSelectionsOfWorksheet(t)}getSelectionsOfWorksheet(t){return this._worksheetSelections.has(t)||this._worksheetSelections.set(t,[]),this._worksheetSelections.get(t)}setSelectionsOfWorksheet(t,n){this._worksheetSelections.set(t,[...n])}deleteSheetSelection(t){this._worksheetSelections.set(t,[])}clear(){this._worksheetSelections.clear(),this._selectionSet$.next([])}_getCurrentSelections(){return this.getSelectionsOfWorksheet(this._workbook.getActiveSheet().getSheetId())}getCurrentLastSelection(){const t=this._getCurrentSelections();return t[t.length-1]}}var nu=Object.getOwnPropertyDescriptor,su=(s,e,t,n)=>{for(var o=n>1?void 0:n?nu(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},ou=(s,e)=>(t,n)=>e(t,n,s);g.SheetsSelectionsService=class extends i.RxDisposable{constructor(t){super();f(this,"_cellStylesCache",new Map);f(this,"selectionMoveStart$");f(this,"selectionMoving$");f(this,"selectionMoveEnd$");f(this,"selectionSet$");f(this,"selectionChanged$");f(this,"_workbookSelections",new Map);this._instanceSrv=t,this._init()}get _currentSelectionPos(){const t=this._instanceSrv.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET);if(!t)return null;const n=t.getActiveSheet();return{unitId:t.getUnitId(),sheetId:n.getSheetId()}}get currentSelectionParam(){return this._currentSelectionPos}_init(){const t=this._instanceSrv.getCurrentTypeOfUnit$(i.UniverInstanceType.UNIVER_SHEET).pipe(O.shareReplay(1),O.takeUntil(this.dispose$));this.selectionMoveStart$=t.pipe().pipe(O.switchMap(n=>n?this._ensureWorkbookSelection(n.getUnitId()).selectionMoveStart$:O.of())).pipe(O.takeUntil(this.dispose$)),this.selectionMoving$=t.pipe(O.switchMap(n=>n?this._ensureWorkbookSelection(n.getUnitId()).selectionMoving$:O.of())).pipe(O.takeUntil(this.dispose$)),this.selectionMoveEnd$=t.pipe(O.switchMap(n=>n?this._ensureWorkbookSelection(n.getUnitId()).selectionMoveEnd$:O.of([]))).pipe(O.takeUntil(this.dispose$)),this.selectionSet$=t.pipe(O.switchMap(n=>n?this._ensureWorkbookSelection(n.getUnitId()).selectionSet$:O.of([]))).pipe(O.takeUntil(this.dispose$)),this.selectionChanged$=t.pipe(O.switchMap(n=>n?this._ensureWorkbookSelection(n.getUnitId()).selectionChanged$:O.of([]))).pipe(O.distinctUntilChanged((n,o)=>n.length!==o.length?!1:n.length===0&&o.length===0?!0:n.every((r,a)=>JSON.stringify(r)===JSON.stringify(o[a]))),O.skip(1)).pipe(O.takeUntil(this.dispose$)),this.disposeWithMe(this._instanceSrv.getTypeOfUnitDisposed$(i.UniverInstanceType.UNIVER_SHEET).pipe(O.takeUntil(this.dispose$)).subscribe(n=>{this._removeWorkbookSelection(n.getUnitId())})),this.disposeWithMe(this.selectionChanged$.pipe(O.takeUntil(this.dispose$)).subscribe(()=>{this._cellStylesCache.clear()}))}dispose(){super.dispose(),this._cellStylesCache.clear(),this._workbookSelections.forEach(t=>t.dispose()),this._workbookSelections.clear(),this.selectionMoveStart$=O.of(null),this.selectionMoving$=O.of(null),this.selectionMoveEnd$=O.of([]),this.selectionSet$=O.of(null),this.selectionChanged$=O.of(null)}clear(){this._workbookSelections.forEach(t=>t.clear())}getCurrentSelections(){return this._getCurrentSelections()}getCurrentLastSelection(){const t=this._getCurrentSelections();return t==null?void 0:t[t.length-1]}addSelections(t,n,o){if(typeof t=="string"){this._ensureWorkbookSelection(t).addSelections(n,o);return}const r=this._currentSelectionPos;if(!r)throw new Error("[SheetsSelectionsService]: cannot find current selection position!");const{unitId:a,sheetId:u}=r;this._ensureWorkbookSelection(a).addSelections(u,t)}setSelections(t,n,o,r){if(typeof t=="string"&&typeof n=="string"){const d=t;this._ensureWorkbookSelection(d).setSelections(n,o||[],r!=null?r:te.ONLY_SET);return}const a=this._currentSelectionPos;if(!a)throw new Error("[SheetsSelectionsService]: cannot find current selection position!");const{unitId:u,sheetId:l}=a;if(typeof t=="object"){const d=t!=null?t:o,c=n!=null?n:te.ONLY_SET;this._ensureWorkbookSelection(u).setSelections(l,d,c)}}clearCurrentSelections(){this._getCurrentSelections().splice(0)}isOverlapping(){const t=this.getCurrentSelections();return t==null?!1:t.some(({range:n},o)=>t.some(({range:r},a)=>o===a?!1:n.startRow<=r.endRow&&n.endRow>=r.startRow&&n.startColumn<=r.endColumn&&n.endColumn>=r.startColumn))}_getCurrentSelections(){const t=this._currentSelectionPos;if(!t)return[];const{unitId:n,sheetId:o}=t;return this._ensureWorkbookSelection(n).getSelectionsOfWorksheet(o)}getWorkbookSelections(t){return this._ensureWorkbookSelection(t)}_ensureWorkbookSelection(t){let n=this._workbookSelections.get(t);if(!n){const o=this._instanceSrv.getUnit(t);if(!o)throw new Error(`[SheetsSelectionsService]: cannot resolve unit with id "${t}"!`);n=new Wo(o),this._workbookSelections.set(t,n)}return n}_removeWorkbookSelection(t){this._workbookSelections.delete(t)}getCellStylesProperty(t){var a;const n=(a=this._instanceSrv.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET))==null?void 0:a.getActiveSheet(),o=this.getCurrentSelections();if(!n||o.length===0)return{isAllValuesSame:!1,value:null};let r=null;for(let u=0;u<o.length;u++){const l=o[u],{startRow:d,endRow:c,startColumn:m,endColumn:h}=l.range;for(let R=d;R<=c;R++)for(let C=m;C<=h;C++){const S=`${R}_${C}`;let I;this._cellStylesCache.has(S)?I=this._cellStylesCache.get(S):(I=n.getComposedCellStyle(R,C),this._cellStylesCache.set(S,I));const v=I[t];if(r!=null&&!i.Tools.diffValue(r,v))return{isAllValuesSame:!1,value:null};r=v}}return{isAllValuesSame:!0,value:r}}},g.SheetsSelectionsService=su([ou(0,i.IUniverInstanceService)],g.SheetsSelectionsService);const ru="DISABLE_NORMAL_SELECTIONS",iu="SELECTIONS_ENABLED",Vo="REF_SELECTIONS_ENABLED",sn={id:"sheet.command.clear-selection-all",type:i.CommandType.COMMAND,handler:(s,e)=>{var p;const t=s.get(i.IUniverInstanceService),n=s.get(i.ICommandService),o=s.get(g.SheetsSelectionsService),r=s.get(i.IUndoRedoService),a=s.get(g.SheetInterceptorService),u=t.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET);if(!u)return!1;const l=(e==null?void 0:e.unitId)||u.getUnitId(),d=u.getActiveSheet();if(!d)return!1;const c=(e==null?void 0:e.subUnitId)||d.getSheetId(),m=(e==null?void 0:e.ranges)||((p=o.getCurrentSelections())==null?void 0:p.map(w=>w.range));if(!(m!=null&&m.length))return!1;const h=Dt(m,s,l,c),R=[],C=[],S={subUnitId:c,unitId:l,cellValue:Kn(h)},I=ce(s,S);R.push({id:F.id,params:S}),C.push({id:F.id,params:I});const v=a.onCommandExecute({id:sn.id});return R.push(...v.redos),C.unshift(...v.undos),i.sequenceExecute(R,n)?(r.pushUndoRedo({unitID:l,undoMutations:C,redoMutations:R}),!0):!1}},on={id:"sheet.command.clear-selection-format",type:i.CommandType.COMMAND,handler:(s,e)=>{var p;const t=s.get(i.IUniverInstanceService),n=s.get(i.ICommandService),o=s.get(g.SheetsSelectionsService),r=s.get(i.IUndoRedoService),a=s.get(g.SheetInterceptorService),u=t.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET);if(!u)return!1;const l=(e==null?void 0:e.unitId)||u.getUnitId(),d=u.getActiveSheet();if(!d)return!1;const c=(e==null?void 0:e.subUnitId)||d.getSheetId(),m=(e==null?void 0:e.ranges)||((p=o.getCurrentSelections())==null?void 0:p.map(w=>w.range));if(!(m!=null&&m.length))return!1;const h=Dt(m,s,l,c),R=[],C=[],S={subUnitId:c,unitId:l,cellValue:Qa(h)},I=ce(s,S);R.push({id:F.id,params:S}),C.push({id:F.id,params:I});const v=a.onCommandExecute({id:on.id});return R.push(...v.redos),C.unshift(...v.undos),i.sequenceExecute(R,n)?(r.pushUndoRedo({unitID:l,undoMutations:C,redoMutations:R}),!0):!1}};function At(s,e,t=!0){const n=e.getMatrixWithMergedCells(...i.selectionToArray(s)),o=[];if(n.forValue((a,u,l)=>{if(l.colSpan!==void 0&&l.rowSpan!==void 0){const d={startRow:a,startColumn:u,endRow:a+l.rowSpan-1,endColumn:u+l.colSpan-1};i.Rectangle.contains(s,d)||o.push(d)}}),o.length===0)return s;const r=i.Rectangle.union(s,...o);return t?At(r,e,t):r}function au(s,e,t){let n=null;return t.getMatrixWithMergedCells(s,e,s,e).forValue((r,a,u)=>(n={actualRow:r,actualColumn:a,startRow:r,startColumn:a,isMerged:u.rowSpan!==void 0||u.colSpan!==void 0,isMergedMainCell:u.rowSpan!==void 0&&u.colSpan!==void 0,endRow:r+(u.rowSpan!==void 0?u.rowSpan-1:0),endColumn:a+(u.colSpan!==void 0?u.colSpan-1:0),rangeType:i.RANGE_TYPE.NORMAL},!1)),n||{actualColumn:e,actualRow:s,startRow:s,startColumn:e,endRow:s,endColumn:e,isMerged:!1,isMergedMainCell:!1,rangeType:i.RANGE_TYPE.NORMAL}}function uu(s,e,t){const{startRow:n,startColumn:o,endRow:r,endColumn:a}=s;return Number.isNaN(n)&&(s.startRow=0),Number.isNaN(r)&&(s.endRow=e-1),Number.isNaN(o)&&(s.startColumn=0),Number.isNaN(a)&&(s.endColumn=t-1),s}function se(s,e){const t=Number.isNaN(s.startRow)?0:s.startRow,n=Number.isNaN(s.startColumn)?0:s.startColumn,o=e.getMergedCell(t,n);return o?{...o,actualRow:t,actualColumn:n,rangeType:i.RANGE_TYPE.NORMAL,isMerged:!0,isMergedMainCell:!0}:{startRow:t,startColumn:n,endRow:s.startRow,endColumn:s.startColumn,actualRow:t,actualColumn:n,rangeType:i.RANGE_TYPE.NORMAL,isMerged:!1,isMergedMainCell:!1}}const Ue=(s,e,t)=>({id:q.id,params:{unitId:e.getUnitId(),subUnitId:t.getSheetId(),reveal:!0,selections:[{range:s,primary:se(s,t)}]}});function lu(s){if(!s)return!1;const{range:e,primary:t}=s;return i.Rectangle.equals(e,t)}function du(s){function e(t,n){function o(r){for(let a=r.startRow;a<=r.endRow;a++)if(!s.getRowFiltered(a))for(let u=r.startColumn;u<=r.endColumn;u++)n(a,u,r)}o(t)}return{forOperableEach:e}}const $o=s=>s.id!==oo;function $e(s,e,t,n,o,r,a){const u={};for(let l=e;l<=t;l++)for(let d=n;d<=o;d++){const c=r?s.getCellWithFilteredInterceptors(a,d,ro,$o):s.getCellWithFilteredInterceptors(l,a,ro,$o);!c||!c.s||(u[l]||(u[l]={}),u[l][d]={s:c.s})}return u}var cu=Object.getOwnPropertyDescriptor,mu=(s,e,t,n)=>{for(var o=n>1?void 0:n?cu(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},hu=(s,e)=>(t,n)=>e(t,n,s);const Lo=i.createIdentifier("sheets-formula.ref-selections.service");g.RefSelectionsService=class extends g.SheetsSelectionsService{constructor(e){super(e)}_init(){const e=this._getAliveWorkbooks$().pipe(O.takeUntil(this.dispose$));this.selectionMoveStart$=e.pipe(O.switchMap(t=>O.merge(...t.map(n=>n.selectionMoveStart$)))),this.selectionMoving$=e.pipe(O.switchMap(t=>O.merge(...t.map(n=>n.selectionMoving$)))),this.selectionMoveEnd$=e.pipe(O.switchMap(t=>O.merge(...t.map(n=>n.selectionMoveEnd$)))),this.selectionSet$=e.pipe(O.switchMap(t=>O.merge(...t.map(n=>n.selectionSet$))))}dispose(){super.dispose(),this.selectionMoveStart$=O.of(null),this.selectionMoving$=O.of(null),this.selectionMoveEnd$=O.of(null),this.selectionSet$=O.of(null),delete this._instanceSrv,this._workbookSelections.clear()}_getAliveWorkbooks$(){const e=this._instanceSrv.getAllUnitsForType(i.UniverInstanceType.UNIVER_SHEET);e.forEach(n=>this._ensureWorkbookSelection(n.getUnitId()));const t=new O.BehaviorSubject(e);return this.disposeWithMe(this._instanceSrv.getTypeOfUnitAdded$(i.UniverInstanceType.UNIVER_SHEET).subscribe(n=>{this._ensureWorkbookSelection(n.getUnitId()),t.next([...t.getValue(),n])})),this.disposeWithMe(this._instanceSrv.getTypeOfUnitDisposed$(i.UniverInstanceType.UNIVER_SHEET).subscribe(n=>{this._removeWorkbookSelection(n.getUnitId()),t.next(t.getValue().filter(o=>o!==n))})),t.pipe(O.map(n=>n.map(o=>this._ensureWorkbookSelection(o.getUnitId()))))}},g.RefSelectionsService=mu([hu(0,i.IUniverInstanceService)],g.RefSelectionsService);function Bo(s,e){const n=s.get(i.IContextService).getContextValue(Vo);return s.get(n&&!e?Lo:g.SheetsSelectionsService)}const q={id:"sheet.operation.set-selections",type:i.CommandType.OPERATION,handler:(s,e)=>{if(!e)return!1;const{selections:t,type:n,unitId:o,subUnitId:r}=e;return Bo(s).setSelections(o,r,[...t],n),!0}},Ho={id:"sheet.command.select-range",type:i.CommandType.COMMAND,handler:(s,e)=>{if(!e)return!1;const{unitId:t,subUnit:n,range:o}=e,r=s.get(i.ICommandService),a=P(s.get(i.IUniverInstanceService),e);if(!a)return!1;const u=[{range:o,primary:se(o,a.worksheet),style:null}];return r.syncExecuteCommand(q.id,{unitId:t,subUnitId:n,selections:u})}},Fo="sheet.command.move-range",Je={type:i.CommandType.COMMAND,id:Fo,handler:async(s,e)=>{var M,p;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=s.get(i.ErrorService),a=s.get(i.LocaleService),u=s.get(g.SheetInterceptorService),l=P(o);if(!l||!await u.beforeCommandExecute({id:Je.id,params:e}))return!1;const{worksheet:c,subUnitId:m,unitId:h}=l,R=rn(s,{unitId:h,subUnitId:m,range:e.fromRange},{subUnitId:m,range:e.toRange});if(R===null)return r.emit(a.t("sheets.info.acrossMergedCell")),!1;const C=u.onCommandExecute({id:Je.id,params:e}),S=[...(M=C.preRedos)!=null?M:[],...R.redos,...C.redos,{id:q.id,params:{unitId:h,subUnitId:m,selections:[{range:e.toRange,primary:gu(e.fromRange,e.toRange,c)}],type:te.MOVE_END}}],I=[...(p=C.preUndos)!=null?p:[],...R.undos,...C.undos,{id:q.id,params:{unitId:h,subUnitId:m,selections:[{range:e.fromRange,primary:se(e.fromRange,c)}],type:te.MOVE_END}}];if(i.sequenceExecute(S,t).result){const{undos:w,redos:y}=u.generateMutationsOfAutoHeight({unitId:h,subUnitId:m,ranges:[e.fromRange,e.toRange]}),b=u.afterCommandExecute({id:Je.id,params:e});return i.sequenceExecute([...b.redos,...y],t),n.pushUndoRedo({unitID:h,undoMutations:[...I,...b.undos,...w],redoMutations:[...S,...b.redos,...y]}),!0}return!1}};function rn(s,e,t,n=!1){const o=[],r=[],{range:a,subUnitId:u,unitId:l}=e,{range:d,subUnitId:c}=t,h=s.get(i.IUniverInstanceService).getUniverSheetInstance(l),R=h==null?void 0:h.getSheetBySheetId(c),C=h==null?void 0:h.getSheetBySheetId(u),S=R==null?void 0:R.getCellMatrix(),I=C==null?void 0:C.getCellMatrix();if(R&&C&&S&&I){const v=At(d,R,!1);if(!i.Rectangle.equals(d,v)&&!n)return null;const M=new i.ObjectMatrix,p=new i.ObjectMatrix,w=new i.ObjectMatrix;i.Range.foreach(a,(k,E)=>{const N=I.getValue(k,E);if(M.setValue(k,E,i.Tools.deepClone(N)),N){const W=h==null?void 0:h.getStyles().get(N.s);w.setValue(k,E,i.Tools.deepClone(W))}p.setValue(k,E,null)});const y=new i.ObjectMatrix,b=new i.ObjectMatrix;i.Range.foreach(d,(k,E)=>{y.setValue(k,E,i.Tools.deepClone(S.getValue(k,E)))}),i.Range.foreach(a,(k,E)=>{const N=i.cellToRange(k,E),W=i.Rectangle.getRelativeRange(N,a),V=i.Rectangle.getPositionRange(W,d),$=i.Tools.deepClone(w.getValue(k,E)),L=i.Tools.deepClone(M.getValue(k,E));L&&$&&(L.s=$),b.setValue(V.startRow,V.startColumn,L)});const T={fromRange:e.range,toRange:t.range,from:{value:p.getMatrix(),subUnitId:u},to:{value:b.getMatrix(),subUnitId:c},unitId:l},U={fromRange:t.range,toRange:e.range,from:{value:M.getMatrix(),subUnitId:u},to:{value:y.getMatrix(),subUnitId:c},unitId:l};o.push({id:Le.id,params:T}),r.push({id:Le.id,params:U})}return{redos:o,undos:r}}function gu(s,e,t){const n=s.startRow,o=s.startColumn,r=t.getMergedCell(n,o),a=se(e,t);if(r){const u=r.endRow-r.startRow+1,l=r.endColumn-r.startColumn+1;a.endRow=a.startRow+u-1,a.endColumn=a.startColumn+l-1,a.actualRow=a.startRow,a.actualColumn=a.startColumn,a.isMerged=!1,a.isMergedMainCell=!0}return a}var an=(s=>(s[s.UNIVER_UNKNOWN=0]="UNIVER_UNKNOWN",s[s.UNIVER_DOC=1]="UNIVER_DOC",s[s.UNIVER_SHEET=2]="UNIVER_SHEET",s[s.UNIVER_SLIDE=3]="UNIVER_SLIDE",s[s.UNIVER_PROJECT=4]="UNIVER_PROJECT",s[s.UNRECOGNIZED=-1]="UNRECOGNIZED",s))(an||{}),_=(s=>(s[s.View=0]="View",s[s.Edit=1]="Edit",s[s.ManageCollaborator=2]="ManageCollaborator",s[s.Print=3]="Print",s[s.Duplicate=4]="Duplicate",s[s.Comment=5]="Comment",s[s.Copy=6]="Copy",s[s.Share=7]="Share",s[s.Export=8]="Export",s[s.MoveWorksheet=9]="MoveWorksheet",s[s.DeleteWorksheet=10]="DeleteWorksheet",s[s.HideWorksheet=11]="HideWorksheet",s[s.RenameWorksheet=12]="RenameWorksheet",s[s.CreateWorksheet=13]="CreateWorksheet",s[s.SetWorksheetStyle=14]="SetWorksheetStyle",s[s.EditWorksheetCell=15]="EditWorksheetCell",s[s.InsertHyperlink=16]="InsertHyperlink",s[s.Sort=17]="Sort",s[s.Filter=18]="Filter",s[s.PivotTable=19]="PivotTable",s[s.FloatImg=20]="FloatImg",s[s.History=21]="History",s[s.RwHgtClWdt=22]="RwHgtClWdt",s[s.ViemRwHgtClWdt=23]="ViemRwHgtClWdt",s[s.ViewFilter=24]="ViewFilter",s[s.MoveSheet=25]="MoveSheet",s[s.DeleteSheet=26]="DeleteSheet",s[s.HideSheet=27]="HideSheet",s[s.CopySheet=28]="CopySheet",s[s.RenameSheet=29]="RenameSheet",s[s.CreateSheet=30]="CreateSheet",s[s.SelectProtectedCells=31]="SelectProtectedCells",s[s.SelectUnProtectedCells=32]="SelectUnProtectedCells",s[s.SetCellStyle=33]="SetCellStyle",s[s.SetCellValue=34]="SetCellValue",s[s.SetRowStyle=35]="SetRowStyle",s[s.SetColumnStyle=36]="SetColumnStyle",s[s.InsertRow=37]="InsertRow",s[s.InsertColumn=38]="InsertColumn",s[s.DeleteRow=39]="DeleteRow",s[s.DeleteColumn=40]="DeleteColumn",s[s.EditExtraObject=41]="EditExtraObject",s[s.Delete=42]="Delete",s[s.RecoverHistory=43]="RecoverHistory",s[s.ViewHistory=44]="ViewHistory",s[s.CreatePermissionObject=45]="CreatePermissionObject",s[s.UNRECOGNIZED=-1]="UNRECOGNIZED",s))(_||{}),D=(s=>(s[s.Unkonwn=0]="Unkonwn",s[s.Workbook=1]="Workbook",s[s.Worksheet=2]="Worksheet",s[s.SelectRange=3]="SelectRange",s[s.Document=4]="Document",s[s.Slide=5]="Slide",s[s.UNRECOGNIZED=-1]="UNRECOGNIZED",s))(D||{});class Se{constructor(e,t,n){f(this,"type",D.SelectRange);f(this,"subType",_.Edit);f(this,"status",i.PermissionStatus.INIT);f(this,"value",!0);f(this,"id");f(this,"unitId");f(this,"subUnitId");f(this,"permissionId");this.unitId=e,this.subUnitId=t,this.permissionId=n,this.id=`${D.SelectRange}.${_.Edit}.${n}`}}class un{constructor(e,t,n){f(this,"type",D.SelectRange);f(this,"subType",_.View);f(this,"status",i.PermissionStatus.INIT);f(this,"value",!0);f(this,"id");f(this,"unitId");f(this,"subUnitId");f(this,"permissionId");this.unitId=e,this.subUnitId=t,this.permissionId=n,this.id=`${D.SelectRange}.${_.View}.${n}`}}class Jn{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.Comment);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.Comment}_${e}`}}class xn{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.Copy);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.Copy}_${e}`}}class jo{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"subType",_.CopySheet);f(this,"status",i.PermissionStatus.INIT);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.CopySheet}_${e}`}}class Xn{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.CreatePermissionObject);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.CreatePermissionObject}_${e}`}}class Zn{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.CreateSheet);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.CreateSheet}_${e}`}}class Go{constructor(e){f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.DeleteColumn);this.unitId=e,this.id=`${this.type}.${_.DeleteColumn}_${e}`}}class zo{constructor(e){f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.DeleteRow);this.unitId=e,this.id=`${this.type}.${_.DeleteRow}_${e}`}}class Qn{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.DeleteSheet);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.DeleteSheet}_${e}`}}class es{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.Duplicate);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.Duplicate}_${e}`}}class me{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.Edit);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.Edit}_${e}`}}class ts{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.Export);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.Export}_${e}`}}class ln{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.HideSheet);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.HideSheet}_${e}`}}class qo{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.History);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.History}_${e}`}}class Yo{constructor(e){f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.InsertColumn);this.unitId=e,this.id=`${this.type}.${_.InsertColumn}_${e}`}}class Ko{constructor(e){f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.InsertRow);this.unitId=e,this.id=`${this.type}.${_.InsertRow}_${e}`}}class dn{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.ManageCollaborator);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.ManageCollaborator}_${e}`}}class cn{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.MoveSheet);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.MoveSheet}_${e}`}}class ns{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.Print);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.Print}_${e}`}}class ss{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.RecoverHistory);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.RecoverHistory}_${e}`}}class mn{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.RenameSheet);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.RenameSheet}_${e}`}}class os{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.Share);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.Share}_${e}`}}class rs{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.View);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.View}_${e}`}}class is{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.ViewHistory);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.ViewHistory}_${e}`}}class as{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.Copy);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.Copy}_${e}_${t}`}}class us{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.DeleteColumn);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.DeleteColumn}_${e}_${t}`}}class ls{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.Delete);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.Delete}_${e}_${t}`}}class ds{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.DeleteRow);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.DeleteRow}_${e}_${t}`}}class fe{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.Edit);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.Edit}_${e}_${t}`}}class cs{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.EditExtraObject);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.EditExtraObject}_${e}_${t}`}}class ms{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.Filter);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.Filter}_${e}_${t}`}}class hs{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.InsertColumn);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.InsertColumn}_${e}_${t}`}}class gs{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.InsertHyperlink);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.InsertHyperlink}_${e}_${t}`}}class Rs{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.InsertRow);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.InsertRow}_${e}_${t}`}}class Cs{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.ManageCollaborator);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.ManageCollaborator}_${e}_${t}`}}class Ss{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.PivotTable);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.PivotTable}_${e}_${t}`}}class Ru{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.SelectProtectedCells);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.SelectProtectedCells}_${e}_${t}`}}class Cu{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.SelectUnProtectedCells);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.SelectUnProtectedCells}_${e}_${t}`}}class fs{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.SetCellStyle);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.SetCellStyle}_${e}_${t}`}}class Wt{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.SetCellValue);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.SetCellValue}_${e}_${t}`}}class St{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.SetColumnStyle);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.SetColumnStyle}_${e}_${t}`}}class ft{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.SetRowStyle);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.SetRowStyle}_${e}_${t}`}}class Is{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.Sort);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.Sort}_${e}_${t}`}}class Vt{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.View);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.View}_${e}_${t}`}}const It={id:"sheet.command.set-range-values",type:i.CommandType.COMMAND,handler:(s,e)=>{var W;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=s.get(g.SheetsSelectionsService),a=s.get(g.SheetInterceptorService),u=s.get(i.IPermissionService),l=P(o,e);if(!l)return!1;const{subUnitId:d,unitId:c,workbook:m,worksheet:h}=l,{value:R,range:C,redoUndoId:S}=e,I=C?[C]:(W=r.getCurrentSelections())==null?void 0:W.map(V=>V.range);if(!I||!I.length||!u.getPermissionPoint(new fe(c,d).id))return!1;const v=new i.ObjectMatrix;let M;if(i.Tools.isArray(R))for(let V=0;V<I.length;V++){const{startRow:$,startColumn:L,endRow:Y,endColumn:z}=I[V];for(let K=0;K<=Y-$;K++)for(let oe=0;oe<=z-L;oe++)v.setValue(K+$,oe+L,R[K][oe])}else if(i.isICellData(R))for(let V=0;V<I.length;V++){const{startRow:$,startColumn:L,endRow:Y,endColumn:z}=I[V];for(let K=$;K<=Y;K++)for(let oe=L;oe<=z;oe++)v.setValue(K,oe,R)}else M=R;const p={subUnitId:d,unitId:c,cellValue:M!=null?M:v.getMatrix()},w=ce(s,p),y=i.mapObjectMatrix(p.cellValue,(V,$)=>h.getCellHeight(V,$)||void 0);if(!t.syncExecuteCommand(F.id,p))return!1;const{undos:T,redos:U}=a.onCommandExecute({id:It.id,params:p}),{undos:k,redos:E}=a.generateMutationsOfAutoHeight({unitId:c,subUnitId:d,ranges:I,cellHeights:new i.ObjectMatrix(y)});if(i.sequenceExecute([...U,...E],t).result){const V=Ue(C!=null?C:v.getRange(),m,h);return n.pushUndoRedo({unitID:c,undoMutations:[{id:F.id,params:w},...T,...k,V],redoMutations:[{id:F.id,params:p},...U,...E,i.Tools.deepClone(V)],id:S}),!0}return!1}};function vs(s,e){const t=[],n=[],{unitId:o,subUnitId:r,range:a,shiftDimension:u,cellValue:l={}}=e,d=s.get(i.IUniverInstanceService),c=s.get(g.SheetInterceptorService),m=d.getUniverSheetInstance(o),h=m==null?void 0:m.getSheetBySheetId(r);if(h){const R=h.getCellMatrix(),C=R.getDataRange();if(a.startColumn<=C.endColumn||a.startRow<=C.endRow){let p,w;if(u===i.Dimension.COLUMNS){const b=Math.min(a.endRow,C.endRow);let T=0;for(let k=a.startRow;k<=b;k++){const E=R.getRow(k),N=E?i.getArrayLength(E)-1:0;T=Math.max(T,N)}p={startRow:a.startRow,startColumn:a.startColumn,endRow:b,endColumn:T};const U=a.endColumn-a.startColumn+1;w={startRow:a.startRow,startColumn:p.startColumn+U,endRow:b,endColumn:p.endColumn+U}}else{const b=Math.min(a.endColumn,C.endColumn),T=C.endRow;p={startRow:a.startRow,startColumn:a.startColumn,endRow:T,endColumn:b};const U=a.endRow-a.startRow+1;w={startRow:p.startRow+U,startColumn:a.startColumn,endRow:p.endRow+U,endColumn:b}}const y=rn(s,{unitId:o,subUnitId:r,range:p},{subUnitId:r,range:w},!0);y&&(t.push(...y.redos),n.push(...y.undos))}if(Object.entries(l).length===0)for(let p=a.startRow;p<=a.endRow;p++){l[p]||(l[p]={});for(let w=a.startColumn;w<=a.endColumn;w++)l[p][w]=null}const S={subUnitId:r,unitId:o,cellValue:l},I=ce(s,S),{undos:v,redos:M}=c.onCommandExecute({id:It.id,params:{...S,range:a}});t.push({id:F.id,params:S},...M),n.push({id:F.id,params:I},...v)}return{redo:t,undo:n}}function ps(s,e){const t=[],n=[],{unitId:o,subUnitId:r,range:a,shiftDimension:u}=e,l=s.get(i.IUniverInstanceService),d=s.get(g.SheetInterceptorService),c=l.getUniverSheetInstance(o),m=c==null?void 0:c.getSheetBySheetId(r);if(m){const h=m.getCellMatrix(),R=h.getDataRange(),C={subUnitId:r,unitId:o,cellValue:Kn([a])},S=ce(s,C),I=d.onCommandExecute({id:It.id,params:C});if(t.push({id:F.id,params:C},...I.redos),n.push(...I.undos,{id:F.id,params:S}),a.startColumn<=R.endColumn||a.startRow<=R.endRow){let v=null,M=null;if(u===i.Dimension.COLUMNS&&a.endColumn<R.endColumn){const p=Math.min(a.endRow,R.endRow);let w=0;for(let b=a.startRow;b<=p;b++){const T=h.getRow(b),U=T?i.getArrayLength(T)-1:0;w=Math.max(w,U)}v={startRow:a.startRow,startColumn:a.endColumn+1,endRow:p,endColumn:w};const y=a.endColumn-a.startColumn+1;M={startRow:a.startRow,startColumn:v.startColumn-y,endRow:p,endColumn:v.endColumn-y}}if(u===i.Dimension.ROWS&&a.endRow<R.endRow){const p=Math.min(a.endColumn,R.endColumn),w=R.endRow;v={startRow:a.endRow+1,startColumn:a.startColumn,endRow:w,endColumn:p};const y=a.endRow-a.startRow+1;M={startRow:v.startRow-y,startColumn:a.startColumn,endRow:v.endRow-y,endColumn:p}}if(v&&M){const p=rn(s,{unitId:o,subUnitId:r,range:v},{subUnitId:r,range:M},!0);p&&(t.push(...p.redos),n.push(...p.undos))}}}return{redo:t,undo:n}}function Su(s,e,t,n,o,r){const{startRow:a,endRow:u,startColumn:l,endColumn:d}=e;if(o===i.Dimension.ROWS){const c=u-a+1;for(let m=t;m>=a;m--)for(let h=l;h<=d;h++){const R=s.getValue(m,h);R==null?s.realDeleteValue(m+c,h):s.setValue(m+c,h,R)}for(let m=u;m>=a;m--)for(let h=l;h<=d;h++)r&&r[m]&&r[m][h]?s.setValue(m,h,r[m][h]):s.realDeleteValue(m,h)}else if(o===i.Dimension.COLUMNS){const c=d-l+1;for(let m=a;m<=u;m++)for(let h=n;h>=l;h--){const R=s.getValue(m,h);R==null?s.realDeleteValue(m,h+c):s.setValue(m,h+c,R)}for(let m=a;m<=u;m++)for(let h=d;h>=l;h--)r&&r[m]&&r[m][h]?s.setValue(m,h,r[m][h]):s.realDeleteValue(m,h)}}function fu(s,e,t,n,o){const{startRow:r,endRow:a,startColumn:u,endColumn:l}=e,d=a-r+1,c=l-u+1;if(o===i.Dimension.ROWS)for(let m=r;m<=t;m++)for(let h=u;h<=l;h++){const R=s.getValue(m+d,h);R==null?s.realDeleteValue(m,h):s.setValue(m,h,R)}else if(o===i.Dimension.COLUMNS)for(let m=r;m<=a;m++)for(let h=u;h<=n;h++){const R=s.getValue(m,h+c);R==null?s.realDeleteValue(m,h):s.setValue(m,h,R)}}const Jo="sheet.command.delete-range-move-left",Be={type:i.CommandType.COMMAND,id:Jo,handler:async(s,e)=>{var w,y,b;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=s.get(g.SheetsSelectionsService),a=s.get(g.SheetInterceptorService),u=P(o);if(!u)return!1;const{worksheet:l,workbook:d,subUnitId:c,unitId:m}=u;let h=e==null?void 0:e.range;if(h||(h=(w=r.getCurrentLastSelection())==null?void 0:w.range),!h)return!1;const R={range:h,subUnitId:c,unitId:m,shiftDimension:i.Dimension.COLUMNS},C=a.onCommandExecute({id:Be.id,params:{range:h}}),{redo:S,undo:I}=ps(s,R),v=[...(y=C.preRedos)!=null?y:[],...S],M=[...C.undos,...I];if(v.push(...C.redos),v.push(Ue(h,d,l)),M.push(...(b=C.preUndos)!=null?b:[]),i.sequenceExecute(v,t).result){const T=a.afterCommandExecute({id:Be.id,params:{range:h}});return i.sequenceExecute(T.redos,t),M.push(...T.undos),v.push(...T.redos),n.pushUndoRedo({unitID:m,undoMutations:M.reverse(),redoMutations:v}),!0}return!1}},xo="sheet.command.delete-range-move-up",He={type:i.CommandType.COMMAND,id:xo,handler:async(s,e)=>{var w,y,b;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=s.get(g.SheetsSelectionsService),a=s.get(g.SheetInterceptorService),u=P(o);if(!u)return!1;const{unitId:l,subUnitId:d,workbook:c,worksheet:m}=u;let h=e==null?void 0:e.range;if(h||(h=(w=r.getCurrentLastSelection())==null?void 0:w.range),!h)return!1;const R={range:h,subUnitId:d,unitId:l,shiftDimension:i.Dimension.ROWS},C=a.onCommandExecute({id:He.id,params:{range:h}}),{redo:S,undo:I}=ps(s,R),v=[...(y=C.preRedos)!=null?y:[],...S],M=[...C.undos,...I];if(v.push(...C.redos),v.push(Ue(h,c,m)),M.push(...(b=C.preUndos)!=null?b:[]),i.sequenceExecute(v,t).result){const T=a.afterCommandExecute({id:He.id,params:{range:h}});return i.sequenceExecute(T.redos,t),M.push(...T.undos),v.push(...T.redos),n.pushUndoRedo({unitID:l,undoMutations:M.reverse(),redoMutations:v}),!0}return!1}},Iu="sheet.command.insert-range-move-down",xe={type:i.CommandType.COMMAND,id:"sheet.command.insert-range-move-down",handler:async(s,e)=>{var W,V,$;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=s.get(g.SheetsSelectionsService),a=s.get(g.SheetInterceptorService),u=s.get(i.ErrorService),l=s.get(i.LocaleService);if(r.isOverlapping())return u.emit(l.t("sheets.info.overlappingSelections")),!1;const d=P(o);if(!d)return!1;const{unitId:c,subUnitId:m,worksheet:h,workbook:R}=d;let C=e==null?void 0:e.range;if(C||(C=(W=r.getCurrentLastSelection())==null?void 0:W.range),!C)return!1;const S=[],I=[],v=h.getCellMatrix(),M=v.getDataRange(),w=v.getSlice(M.startRow,M.endRow,C.startColumn,C.endColumn).getDataRange().endRow,y=Math.max(w+(C.endRow-C.startRow+1)-M.endRow,0);if(y>0){const L=C.startRow-1,Y=h.getRowHeight(L),z={unitId:c,subUnitId:m,range:{startRow:M.endRow+1,endRow:M.endRow+y,startColumn:M.startColumn,endColumn:M.endColumn},rowInfo:new Array(y).fill(void 0).map(()=>({h:Y,hd:i.BooleanNumber.FALSE}))};S.push({id:re.id,params:z});const K=en(s,z);I.push({id:ae.id,params:K})}const b={};i.Range.foreach(C,(L,Y)=>{const z=h.getCell(L,Y);z&&(b[L]||(b[L]={}),b[L][Y]={s:z.s})});const T={range:C,subUnitId:m,unitId:c,shiftDimension:i.Dimension.ROWS,cellValue:b},{redo:U,undo:k}=vs(s,T);S.push(...U),I.push(...k);const E=a.onCommandExecute({id:xe.id,params:{range:C}});if(S.push(...E.redos),S.push(Ue(C,R,h)),I.push(...(V=E.preUndos)!=null?V:[]),S.unshift(...($=E.preRedos)!=null?$:[]),I.unshift(...E.undos),i.sequenceExecute(S,t)){const L=a.afterCommandExecute({id:xe.id,params:{range:C}});return i.sequenceExecute(L.redos,t),I.push(...L.undos),S.push(...L.redos),n.pushUndoRedo({unitID:c,undoMutations:I.reverse(),redoMutations:S}),!0}return!1}},ws="sheet.command.insert-range-move-right",vt={type:i.CommandType.COMMAND,id:ws,handler:async(s,e)=>{var W,V,$;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=s.get(g.SheetsSelectionsService),a=s.get(g.SheetInterceptorService),u=s.get(i.ErrorService),l=s.get(i.LocaleService);if(r.isOverlapping())return u.emit(l.t("sheets.info.overlappingSelections")),!1;const d=P(o);if(!d)return!1;const{workbook:c,worksheet:m,unitId:h,subUnitId:R}=d;let C=e==null?void 0:e.range;if(C||(C=(W=r.getCurrentLastSelection())==null?void 0:W.range),!C)return!1;const S=[],I=[],v=m.getCellMatrix(),M=v.getDataRange(),w=v.getSlice(C.startRow,C.endRow,M.startColumn,M.endColumn).getDataRange().endColumn,y=Math.max(w+(C.endColumn-C.startColumn+1)-M.endColumn,0);if(y>0){const L=C.startColumn-1,Y=m.getColumnWidth(L),z={unitId:h,subUnitId:R,range:{startRow:M.startRow+1,endRow:M.endRow,startColumn:M.endColumn+1,endColumn:M.endColumn+y},colInfo:new Array(y).fill(void 0).map(()=>({w:Y,hd:i.BooleanNumber.FALSE}))};S.push({id:ie.id,params:z});const K=Nt(s,z);I.push({id:ne.id,params:K})}const b={};i.Range.foreach(C,(L,Y)=>{const z=m.getCell(L,Y);!z||!z.s||(b[L]||(b[L]={}),b[L][Y]={s:z.s})});const T={range:C,subUnitId:R,unitId:h,shiftDimension:i.Dimension.COLUMNS,cellValue:b},{redo:U,undo:k}=vs(s,T);S.push(...U),I.push(...k);const E=a.onCommandExecute({id:vt.id,params:{range:C}});if(S.push(...E.redos),S.push(Ue(C,c,m)),I.push(...(V=E.preUndos)!=null?V:[]),S.unshift(...($=E.preRedos)!=null?$:[]),I.unshift(...E.undos),i.sequenceExecute(S,t).result){const L=a.afterCommandExecute({id:vt.id,params:{range:C}});return i.sequenceExecute(L.redos,t),I.push(...L.undos),S.push(...L.redos),n.pushUndoRedo({unitID:h,undoMutations:I.reverse(),redoMutations:S}),!0}return!1}},Xo="sheet.command.insert-row",Me={type:i.CommandType.COMMAND,id:Xo,handler:async(s,e)=>{const t=s.get(i.ICommandService),n=s.get(g.SheetInterceptorService),{range:o,direction:r,unitId:a,subUnitId:u,cellValue:l}=e;return await n.beforeCommandExecute({id:Me.id,params:e})?t.syncExecuteCommand(Ms.id,{range:o,direction:r,unitId:a,subUnitId:u,cellValue:l}):!1}},Ms={type:i.CommandType.COMMAND,id:"sheet.command.insert-row-by-range",handler:(s,e)=>{var U,k,E,N;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=s.get(g.SheetInterceptorService),a=P(o,e);if(!a)return!1;const{workbook:u,worksheet:l}=a,{range:d,direction:c,unitId:m,subUnitId:h,cellValue:R}=e,{startRow:C,endRow:S}=d;d.rangeType=i.RANGE_TYPE.ROW;const I=c===i.Direction.UP?C:C-1,v=l.getRowHeight(I),M={unitId:m,subUnitId:h,range:d,rowInfo:new Array(S-C+1).fill(void 0).map(()=>({h:v,hd:i.BooleanNumber.FALSE}))},p=en(s,M),w=[{id:re.id,params:M}],y=[{id:ae.id,params:p}];R&&Object.keys(R).length>0&&w.push({id:F.id,params:{unitId:m,subUnitId:h,cellValue:R}});const b=r.onCommandExecute({id:Me.id,params:e});if(w.unshift(...(U=b.preRedos)!=null?U:[]),w.push(...(k=b.redos)!=null?k:[]),w.push(Ue(d,u,l)),y.unshift(...(E=b.preUndos)!=null?E:[]),y.push(...(N=b.undos)!=null?N:[]),i.sequenceExecute(w,t).result){const W=r.afterCommandExecute({id:Me.id,params:e});return i.sequenceExecute(W.redos,t),w.push(...W.redos),y.push(...W.undos),n.pushUndoRedo({unitID:e.unitId,undoMutations:y,redoMutations:w}),!0}return!1}},Zo={type:i.CommandType.COMMAND,id:"sheet.command.insert-row-before",handler:async(s,e)=>{var I;const n=(I=s.get(g.SheetsSelectionsService).getCurrentSelections())==null?void 0:I.map(v=>v.range);let o;if((n==null?void 0:n.length)===1)o=n[0];else return!1;const r=s.get(i.IUniverInstanceService),a=P(r);if(!a)return!1;const{worksheet:u,subUnitId:l,unitId:d}=a,c=e.value||0,m=o.startRow,h=o.startRow+c-1,R=0,C=u.getColumnCount()-1,S={unitId:d,subUnitId:l,direction:i.Direction.UP,range:{startRow:m,endRow:h,startColumn:R,endColumn:C},cellValue:$e(u,m,h,R,C,!0,m-1)};return s.get(i.ICommandService).executeCommand(Me.id,S)}},Qo={type:i.CommandType.COMMAND,id:"sheet.command.insert-row-after",handler:async s=>{var S;const t=(S=s.get(g.SheetsSelectionsService).getCurrentSelections())==null?void 0:S.map(I=>I.range);let n;if((t==null?void 0:t.length)===1)n=t[0];else return!1;const o=s.get(i.IUniverInstanceService),r=P(o);if(!r)return!1;const{worksheet:a,unitId:u,subUnitId:l}=r,d=n.endRow-n.startRow+1,c=n.endRow+1,m=n.endRow+d,h=0,R=a.getColumnCount()-1,C={unitId:u,subUnitId:l,direction:i.Direction.DOWN,range:{startRow:c,endRow:m,startColumn:h,endColumn:R,rangeType:i.RANGE_TYPE.ROW},cellValue:$e(a,c,m,h,R,!0,n.endRow)};return s.get(i.ICommandService).executeCommand(Me.id,C)}},er={type:i.CommandType.COMMAND,id:"sheet.command.insert-multi-rows-above",handler:async(s,e)=>{var v;const n=(v=s.get(g.SheetsSelectionsService).getCurrentSelections())==null?void 0:v.map(M=>M.range);let o;if((n==null?void 0:n.length)===1)o=n[0];else return!1;const r=s.get(i.IUniverInstanceService),a=P(r);if(!a)return!1;const{worksheet:u,unitId:l,subUnitId:d}=a,c=e.value||0,m=o.startRow,h=o.startRow+c-1,R=0,C=u.getColumnCount()-1,S=$e(u,m,h,R,C,!0,m-1),I={unitId:l,subUnitId:d,direction:i.Direction.UP,range:{startRow:m,endRow:h,startColumn:R,endColumn:C,rangeType:i.RANGE_TYPE.ROW},cellValue:S};return s.get(i.ICommandService).executeCommand(Me.id,I)}},tr={type:i.CommandType.COMMAND,id:"sheet.command.insert-multi-rows-after",handler:async(s,e)=>{var I;const n=(I=s.get(g.SheetsSelectionsService).getCurrentSelections())==null?void 0:I.map(v=>v.range);let o;if((n==null?void 0:n.length)===1)o=n[0];else return!1;const r=s.get(i.IUniverInstanceService),a=P(r);if(!a)return!1;const{worksheet:u,unitId:l,subUnitId:d}=a,c=e.value||0,m=o.endRow+1,h=o.endRow+c,R=0,C=u.getColumnCount()-1,S={unitId:l,subUnitId:d,direction:i.Direction.DOWN,range:{startRow:m,endRow:h,startColumn:R,endColumn:C,rangeType:i.RANGE_TYPE.ROW},cellValue:$e(u,m,h,R,C,!0,o.endRow)};return s.get(i.ICommandService).executeCommand(Me.id,S)}},nr="sheet.command.insert-col",ye={type:i.CommandType.COMMAND,id:nr,handler:async(s,e)=>{const t=s.get(i.ICommandService),n=s.get(g.SheetInterceptorService),{range:o,direction:r,subUnitId:a,unitId:u,cellValue:l}=e;return await n.beforeCommandExecute({id:ye.id,params:e})?t.syncExecuteCommand(ys.id,{range:o,direction:r,unitId:u,subUnitId:a,cellValue:l}):!1}},ys={type:i.CommandType.COMMAND,id:"sheet.command.insert-col-by-range",handler:(s,e)=>{var T,U,k,E;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=s.get(g.SheetInterceptorService),{range:a,direction:u,subUnitId:l,unitId:d,cellValue:c}=e,{startColumn:m,endColumn:h}=e.range;a.rangeType=i.RANGE_TYPE.COLUMN;const R=o.getUniverSheetInstance(e.unitId),C=R.getSheetBySheetId(e.subUnitId),S=u===i.Direction.LEFT?m:m-1,I=C.getColumnWidth(S),v={unitId:d,subUnitId:l,range:a,colInfo:new Array(h-m+1).fill(void 0).map(()=>({w:I,hd:i.BooleanNumber.FALSE}))},M=Nt(s,v),p=[{id:ie.id,params:v}],w=[{id:ne.id,params:M}];c&&p.push({id:F.id,params:{unitId:d,subUnitId:l,cellValue:c}});const y=r.onCommandExecute({id:ye.id,params:e});if(p.unshift(...(T=y.preRedos)!=null?T:[]),p.push(...(U=y.redos)!=null?U:[]),p.push(Ue(a,R,C)),w.unshift(...(k=y.preUndos)!=null?k:[]),w.push(...(E=y.undos)!=null?E:[]),i.sequenceExecute(p,t).result){const N=r.afterCommandExecute({id:ye.id,params:e});return i.sequenceExecute(N.redos,t),p.push(...N.redos),w.push(...N.undos),n.pushUndoRedo({unitID:e.unitId,undoMutations:w.filter(Boolean),redoMutations:p.filter(Boolean)}),!0}return!1}},sr={type:i.CommandType.COMMAND,id:"sheet.command.insert-col-before",handler:async(s,e)=>{const n=s.get(g.SheetsSelectionsService).getCurrentSelections();let o;if((n==null?void 0:n.length)===1)o=n[0].range;else return!1;const r=s.get(i.IUniverInstanceService),a=P(r);if(!a)return!1;const{worksheet:u,unitId:l,subUnitId:d}=a,c=e.value||0,m=o.startColumn,h=o.startColumn+c-1,R=0,C=u.getRowCount()-1,S={unitId:l,subUnitId:d,direction:i.Direction.LEFT,range:{startColumn:m,endColumn:h,startRow:R,endRow:C,rangeType:i.RANGE_TYPE.COLUMN},cellValue:$e(u,R,C,m,h,!1,m-1)};return s.get(i.ICommandService).executeCommand(ye.id,S)}},or={type:i.CommandType.COMMAND,id:"sheet.command.insert-col-after",handler:async s=>{const t=s.get(g.SheetsSelectionsService).getCurrentSelections();let n;if((t==null?void 0:t.length)===1)n=t[0].range;else return!1;const o=s.get(i.IUniverInstanceService),r=P(o);if(!r)return!1;const{worksheet:a,unitId:u,subUnitId:l}=r,d=n.endColumn-n.startColumn+1,c=n.endColumn+1,m=n.endColumn+d,h=0,R=a.getRowCount()-1,C={unitId:u,subUnitId:l,direction:i.Direction.RIGHT,range:{startColumn:c,endColumn:m,startRow:h,endRow:R},cellValue:$e(a,h,R,c,m,!1,n.endColumn)};return s.get(i.ICommandService).executeCommand(ye.id,C)}},rr={type:i.CommandType.COMMAND,id:"sheet.command.insert-multi-cols-before",handler:async(s,e)=>{const n=s.get(g.SheetsSelectionsService).getCurrentSelections();let o;if((n==null?void 0:n.length)===1)o=n[0].range;else return!1;const r=s.get(i.IUniverInstanceService),a=P(r);if(!a)return!1;const{worksheet:u,unitId:l,subUnitId:d}=a,c=e.value||0,m=o.startColumn,h=o.startColumn+c-1,R=0,C=u.getRowCount()-1,S={unitId:l,subUnitId:d,direction:i.Direction.LEFT,range:{startColumn:m,endColumn:h,startRow:R,endRow:C,rangeType:i.RANGE_TYPE.COLUMN},cellValue:$e(u,R,C,m,h,!1,m-1)};return s.get(i.ICommandService).executeCommand(ye.id,S)}},ir={type:i.CommandType.COMMAND,id:"sheet.command.insert-multi-cols-right",handler:async(s,e)=>{const n=s.get(g.SheetsSelectionsService).getCurrentSelections();let o;if((n==null?void 0:n.length)===1)o=n[0].range;else return!1;const r=s.get(i.IUniverInstanceService),a=P(r);if(!a)return!1;const{worksheet:u,unitId:l,subUnitId:d}=a,c=e.value||0,m=o.endColumn+1,h=o.endColumn+c,R=0,C=u.getRowCount()-1,S={unitId:l,subUnitId:d,direction:i.Direction.RIGHT,range:{startColumn:m,endColumn:h,startRow:R,endRow:C},cellValue:$e(u,R,C,m,h,!1,o.endColumn)};return s.get(i.ICommandService).executeCommand(ye.id,S)}},hn="sheet.command.remove-row",_s={type:i.CommandType.COMMAND,id:"sheet.command.remove-row-by-range",handler:(s,e)=>{var I,v,M;if(!e)return!1;const t=s.get(i.IUniverInstanceService),n=P(t,e);if(!n)return!1;const{workbook:o,worksheet:r}=n,a=s.get(g.SheetInterceptorService),{range:u,unitId:l,subUnitId:d}=e,c=Dt([u],s,l,d).reverse(),m=[],h=[];c.forEach(p=>{const w=[],y=[],b={unitId:l,subUnitId:d,range:p},T=ca(b,r),U=r.getCellMatrix().getSlice(p.startRow,p.endRow,0,r.getColumnCount()-1),k={unitId:l,subUnitId:d,cellValue:U.getMatrix()};y.push({id:ae.id,params:b}),w.push({id:re.id,params:T}),w.push({id:F.id,params:k}),h.push(...y),m.unshift(...w)});const R=a.onCommandExecute({id:hn,params:{range:u}}),C=s.get(i.ICommandService);if(i.sequenceExecute([...(I=R.preRedos)!=null?I:[],...h,...R.redos,Ue(u,o,r)],C).result){const p=a.afterCommandExecute({id:hn,params:{range:u}});return i.sequenceExecute(p.redos,C),s.get(i.IUndoRedoService).pushUndoRedo({unitID:l,undoMutations:[...(v=R.preUndos)!=null?v:[],...m,...R.undos,...p.undos],redoMutations:[...(M=R.preRedos)!=null?M:[],...h,...R.redos,...p.redos]}),!0}return!1}},$t={type:i.CommandType.COMMAND,id:hn,handler:async(s,e)=>{var h;const t=s.get(g.SheetsSelectionsService),n=s.get(g.SheetInterceptorService),o=s.get(i.ICommandService);let r=e==null?void 0:e.range;if(r||(r=(h=t.getCurrentLastSelection())==null?void 0:h.range),!r)return!1;const a=s.get(i.IUniverInstanceService),u=P(a);if(!u)return!1;const{worksheet:l,subUnitId:d,unitId:c}=u;return r={...r,startColumn:0,endColumn:Math.max(l.getMaxColumns()-1,0)},await n.beforeCommandExecute({id:$t.id,params:{range:r}})?o.syncExecuteCommand(_s.id,{range:r,unitId:c,subUnitId:d}):!1}},gn="sheet.command.remove-col",bs={type:i.CommandType.COMMAND,id:"sheet.command.remove-col-by-range",handler:(s,e)=>{var v,M,p;if(!e)return!1;const t=s.get(i.IUniverInstanceService),n=P(t,e);if(!n)return!1;const{workbook:o,worksheet:r}=n,a=s.get(g.SheetInterceptorService),{range:u,unitId:l,subUnitId:d}=e,c={unitId:l,subUnitId:d,range:u},m=ma(s,c),h=r.getCellMatrix().getSlice(0,r.getRowCount()-1,u.startColumn,u.endColumn),R={unitId:l,subUnitId:d,cellValue:h.getMatrix()},C=a.onCommandExecute({id:gn,params:{range:u}}),S=s.get(i.ICommandService);if(i.sequenceExecute([...(v=C.preRedos)!=null?v:[],{id:ne.id,params:c},...C.redos,Ue(u,o,r)],S).result){const w=a.afterCommandExecute({id:gn,params:{range:u}});return i.sequenceExecute(w.redos,S),s.get(i.IUndoRedoService).pushUndoRedo({unitID:l,undoMutations:[...(M=C.preUndos)!=null?M:[],{id:ie.id,params:m},{id:F.id,params:R},...C.undos,...w.undos],redoMutations:[...(p=C.preRedos)!=null?p:[],{id:ne.id,params:c},...C.redos,...w.redos]}),!0}return!1}},Lt={type:i.CommandType.COMMAND,id:gn,handler:async(s,e)=>{var h;const t=s.get(g.SheetsSelectionsService),n=s.get(g.SheetInterceptorService),o=s.get(i.ICommandService);let r=e==null?void 0:e.range;if(r||(r=(h=t.getCurrentLastSelection())==null?void 0:h.range),!r)return!1;const a=s.get(i.IUniverInstanceService),u=P(a);if(!u)return!1;const{worksheet:l,subUnitId:d,unitId:c}=u;return r={...r,startRow:0,endRow:Math.max(l.getMaxRows()-1,0)},await n.beforeCommandExecute({id:Lt.id,params:{range:r}})?o.syncExecuteCommand(bs.id,{range:r,unitId:c,subUnitId:d}):!1}},ar=(s,e)=>{const t=s.get(i.IUniverInstanceService),{subUnitId:n,unitId:o}=e,r=ve(t,e);if(!r)throw new Error("[RemoveSheetUndoMutationFactory]: Worksheet is null error!");const{workbook:a,worksheet:u}=r,l=u.getConfig();return{index:a.getConfig().sheetOrder.findIndex(m=>m===n),sheet:l,unitId:o}},Xe={id:"sheet.mutation.remove-sheet",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=s.get(i.IUniverInstanceService),{subUnitId:n,unitId:o}=e,r=t.getUniverSheetInstance(o);return r?r.removeSheet(n):!1}};function vu(s,e){return e.getMergeData().some(t=>t.startRow<s&&s<=t.endRow)}function pu(s,e){return e.getMergeData().some(t=>t.startColumn<s&&s<=t.endColumn)}const ur="sheet.command.move-rows",pt={id:ur,type:i.CommandType.COMMAND,handler:(s,e)=>{var W,V;const t=s.get(g.SheetsSelectionsService),{fromRange:{startRow:n},toRange:{startRow:o},range:r}=e,a=r?[dr(r)]:t.getCurrentSelections(),u=a==null?void 0:a.filter($=>$.range.rangeType===i.RANGE_TYPE.ROW&&$.range.startRow<=n&&n<=$.range.endRow);if((u==null?void 0:u.length)!==1)return!1;const l=s.get(g.SheetInterceptorService),d=s.get(i.IUniverInstanceService),c=P(d,e);if(!c)return!1;const{workbook:m,worksheet:h}=c,R=m.getUnitId(),C=h.getSheetId(),S=s.get(i.ErrorService),I=s.get(i.LocaleService),v=u[0].range,M=u[0].primary,p=At(v,h,!1);if(!i.Rectangle.equals(v,p))return S.emit(I.t("sheets.info.partOfCell")),!1;if(vu(o,h))return S.emit(I.t("sheets.info.acrossMergedCell")),!1;const w={...v,startRow:o,endRow:o+v.endRow-v.startRow},y={unitId:R,subUnitId:C,sourceRange:v,targetRange:w},b=co(s,y),T=s.get(i.ICommandService),U=l.onCommandExecute({id:pt.id,params:e}),k=[...(W=U.preRedos)!=null?W:[],{id:pe.id,params:y}],E=[...(V=U.preUndos)!=null?V:[],{id:pe.id,params:b}];if(M){const L=o-n<0,Y=v.endRow-v.startRow+1,z=L?w:{...w,startRow:w.startRow-Y,endRow:w.endRow-Y},K={unitId:R,subUnitId:C,type:te.MOVE_END,selections:[{range:z,primary:se(z,h),style:null}]},oe={unitId:R,subUnitId:C,type:te.MOVE_END,selections:[{range:v,primary:M,style:null}]};k.push({id:q.id,params:K}),E.push({id:q.id,params:oe})}if(k.push(...U.redos),E.push(...U.undos),i.sequenceExecute(k,T).result){const $=l.afterCommandExecute({id:pt.id,params:e});return i.sequenceExecute($.redos,T),k.push(...$.redos),E.push(...$.undos),s.get(i.IUndoRedoService).pushUndoRedo({unitID:R,undoMutations:E,redoMutations:k}),!0}return!1}},lr="sheet.command.move-cols",wt={id:lr,type:i.CommandType.COMMAND,handler:(s,e)=>{var W,V;const t=s.get(g.SheetsSelectionsService),{fromRange:{startColumn:n},toRange:{startColumn:o},range:r}=e,a=r?[dr(r)]:t.getCurrentSelections(),u=a==null?void 0:a.filter($=>$.range.rangeType===i.RANGE_TYPE.COLUMN&&$.range.startColumn<=n&&n<=$.range.endColumn);if((u==null?void 0:u.length)!==1)return!1;const l=s.get(g.SheetInterceptorService),d=s.get(i.IUniverInstanceService),c=P(d,e);if(!c)return!1;const{workbook:m,worksheet:h}=c,R=m.getUnitId(),C=h.getSheetId(),S=s.get(i.ErrorService),I=s.get(i.LocaleService),v=u[0].range,M=u[0].primary,p=At(v,h,!1);if(!i.Rectangle.equals(v,p))return S.emit(I.t("sheets.info.partOfCell")),!1;if(pu(o,h))return S.emit(I.t("sheets.info.acrossMergedCell")),!1;const w={...v,startColumn:o,endColumn:o+v.endColumn-v.startColumn},y={unitId:R,subUnitId:C,sourceRange:v,targetRange:w},b=mo(s,y),T=s.get(i.ICommandService),U=l.onCommandExecute({id:wt.id,params:e}),k=[...(W=U.preRedos)!=null?W:[],{id:we.id,params:y}],E=[...(V=U.preUndos)!=null?V:[],{id:we.id,params:b}];if(M){const $=v.endColumn-v.startColumn+1,z=o-n<0?w:{...w,startColumn:w.startColumn-$,endColumn:w.endColumn-$},K={unitId:R,subUnitId:C,type:te.MOVE_END,selections:[{range:z,primary:se(z,h),style:null}]},oe={unitId:R,subUnitId:C,type:te.MOVE_END,selections:[{range:v,primary:M,style:null}]};k.push({id:q.id,params:K}),E.push({id:q.id,params:oe})}if(k.push(...U.redos),E.push(...U.undos),i.sequenceExecute(k,T).result){const $=l.afterCommandExecute({id:wt.id,params:e});return i.sequenceExecute($.redos,T),k.push(...$.redos),E.push(...$.undos),s.get(i.IUndoRedoService).pushUndoRedo({unitID:R,undoMutations:E,redoMutations:k}),!0}return!1}};function dr(s){return{range:s,primary:null,style:null}}var wu=Object.getOwnPropertyDescriptor,Mu=(s,e,t,n)=>{for(var o=n>1?void 0:n?wu(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},yu=(s,e)=>(t,n)=>e(t,n,s);g.SheetSkeletonService=class extends i.Disposable{constructor(t){super();f(this,"_sheetSkeletonStore",new Map);this._injector=t,this.disposeWithMe(()=>{this._sheetSkeletonStore=new Map})}getSkeleton(t,n){if(this._sheetSkeletonStore.has(t))return this._sheetSkeletonStore.get(t).get(n)}setSkeleton(t,n,o){this._sheetSkeletonStore.has(t)||this._sheetSkeletonStore.set(t,new Map),this._sheetSkeletonStore.get(t).set(n,o)}deleteSkeleton(t,n){this._sheetSkeletonStore.has(t)&&this._sheetSkeletonStore.get(t).delete(n)}},g.SheetSkeletonService=Mu([yu(0,i.Inject(i.Injector))],g.SheetSkeletonService);function Es(s,e){const t=new i.ObjectMatrix;return s.map(n=>i.Range.transformRange(n,e)).forEach(n=>{i.Range.foreach(n,(o,r)=>{const a=e.getCellHeight(o,r);a&&t.setValue(o,r,a)})}),t}const _u=1e4;function Bt(s,e){if(!e)return{suitableRanges:s,remainingRanges:[]};const t=e.worksheet.getColumnCount(),n=Math.ceil(_u/t),o=[],r=[],a=e.getOffsetRelativeToRowCol(0,e.scrollY).row,u=s.map(d=>{let c;return a>=d.startRow&&a<=d.endRow?c=0:a<d.startRow?c=d.startRow-a:c=a-d.endRow,{range:d,distance:c,rowCount:d.endRow-d.startRow+1}});u.sort((d,c)=>d.distance!==c.distance?d.distance-c.distance:d.rowCount-c.rowCount);let l=0;for(const d of u)if(l+d.rowCount<=n)o.push(d.range),l+=d.rowCount;else{const c=n-l;if(c>0){const m={...d.range,endRow:d.range.startRow+c-1},h={...d.range,startRow:d.range.startRow+c};o.push(m),r.push(h),l=n}else r.push(d.range)}return{suitableRanges:o,remainingRanges:r}}const cr="sheet.command.reorder-range",Rn={id:cr,type:i.CommandType.COMMAND,handler:(s,e)=>{var p,w;const{subUnitId:t,unitId:n,range:o,order:r}=e,a=s.get(i.ICommandService),u={id:Ot.id,params:{unitId:n,subUnitId:t,order:r,range:o}},l={id:Ot.id,params:ho(u.params)},d=s.get(g.SheetInterceptorService),c=d.onCommandExecute({id:Rn.id,params:e}),m=[...(p=c.preRedos)!=null?p:[],u,...c.redos],h=[...(w=c.preUndos)!=null?w:[],l,...c.undos],R=i.sequenceExecute(m,a),{suitableRanges:C,remainingRanges:S}=Bt([o],s.get(g.SheetSkeletonService).getSkeleton(n,t)),{undos:I,redos:v}=d.generateMutationsOfAutoHeight({unitId:n,subUnitId:t,ranges:[o],autoHeightRanges:C,lazyAutoHeightRanges:S}),M=d.afterCommandExecute({id:Rn.id,params:e});return R.result?(i.sequenceExecute([...M.redos,...v],a),s.get(i.IUndoRedoService).pushUndoRedo({unitID:n,undoMutations:[...h,...M.undos,...I],redoMutations:[...m,...M.redos,...v]}),!0):!1}},A={MoveRangeCommandId:Fo,InsertRowCommandId:Xo,InsertColCommandId:nr,RemoveColCommandId:gn,RemoveRowCommandId:hn,DeleteRangeMoveLeftCommandId:Jo,DeleteRangeMoveUpCommandId:xo,InsertRangeMoveDownCommandId:Iu,InsertRangeMoveRightCommandId:ws,MoveColsCommandId:lr,MoveRowsCommandId:ur,ReorderRangeCommandId:cr};var B=(s=>(s[s.Set=0]="Set",s[s.Delete=1]="Delete",s[s.HorizontalMove=2]="HorizontalMove",s[s.VerticalMove=3]="VerticalMove",s[s.Unknown=4]="Unknown",s))(B||{});const Cn=Number.MAX_SAFE_INTEGER,Pe=s=>{const e={...s},t=Number.isNaN(e.startRow)&&Number.isNaN(e.endRow)&&!Number.isNaN(e.startColumn)&&!Number.isNaN(e.endColumn),n=Number.isNaN(e.startColumn)&&Number.isNaN(e.endColumn)&&!Number.isNaN(e.startRow)&&!Number.isNaN(e.endRow);return(e.rangeType===i.RANGE_TYPE.COLUMN||t)&&(e.startRow=0,e.endRow=Cn),(e.rangeType===i.RANGE_TYPE.ROW||n)&&(e.startColumn=0,e.endColumn=Cn),e.rangeType===i.RANGE_TYPE.ALL&&(e.startColumn=0,e.endColumn=Cn,e.startRow=0,e.endRow=Cn),e},he=s=>{let e=s.rangeType;return s.rangeType===i.RANGE_TYPE.COLUMN?e=i.RANGE_TYPE.ROW:s.rangeType===i.RANGE_TYPE.ROW&&(e=i.RANGE_TYPE.COLUMN),{startRow:s.startColumn,endRow:s.endColumn,startColumn:s.startRow,endColumn:s.endRow,rangeType:e}},Ht=(s,e,t)=>{const n={...t},o={...e},r=(S,I)=>{const v=Math.max(S.start,I.start),M=Math.min(S.end,I.end);return M<v?null:{start:v,end:M}},a=S=>S.end-S.start+1,u=(S,I)=>({start:S.start-I.start,end:S.start-I.start+S.end-S.start}),l=(S,I)=>({start:I.start+S.start,end:I.start+S.start+S.end-S.start}),d=e.start>s.start;if(d){const S=Math.min(s.end,e.start)-s.start+1;o.start-=S,o.end-=S}const c=a(s),m=c,h=r(s,n),R=h&&a(h)>=a(n);if(s.end<n.start)n.start-=c,n.end-=c;else if(h){const S=a(h);if(R){const I=u(n,s),v=l(I,o);n.start=v.start,n.end=v.end}else h.start>s.start?d?(n.end-=S+c,n.start-=c):n.end-=S:d?n.end-=S:n.start>s.start&&n.end>s.end?(n.start-=c,n.end-=c+S):n.end-=S}const C=r(o,n);return R||(o.start<=n.start?(n.start+=m,n.end+=m):C&&(d?o.end<=n.start||o.start<=n.start&&o.end>=n.start?(n.start+=m,n.end+=m):o.start>=n.start&&o.start<=n.end&&(n.end+=m):n.start<o.start&&n.end>o.start?n.end+=m:(n.start>=o.end||n.start>=o.start&&n.start<=o.end)&&(n.end+=m,n.start+=m))),{step:n.start-t.start,length:a(n)-a(t)}},Ts=(s,e)=>{const{fromRange:t,toRange:n}=s.params||{};if(!n||!t)return[];const o=Pe(t),r=Pe(n),a=Pe(e),u=Ht({start:o.startRow,end:o.endRow},{start:r.startRow,end:r.endRow},{start:a.startRow,end:a.endRow});return u===null?[{type:B.Delete}]:[{type:B.VerticalMove,step:u.step||0,length:u.length||0}]},bu=(s,e)=>{const{fromRange:t,toRange:n}=s.params||{};if(!t||!n)return[e];const o=t.startRow,r=t.endRow-t.startRow+1,a=n.startRow,u=new i.ObjectMatrix;return i.Range.foreach(e,(d,c)=>{u.setValue(d,c,1)}),u.moveRows(o,r,a),i.queryObjectMatrix(u,d=>d===1)},Eu=(s,e)=>{const{range:t,order:n}=s.params||{};if(!t||!n)return[e];const o=new i.ObjectMatrix;i.Range.foreach(e,(u,l)=>{o.setValue(u,l,1)});const r=new i.ObjectMatrix;return i.Range.foreach(t,(u,l)=>{var d;if(Object.prototype.hasOwnProperty.call(n,u)){const c=n[u],m=(d=o.getValue(c,l))!=null?d:0;r.setValue(u,l,m)}}),r.forValue((u,l,d)=>{o.setValue(u,l,d)}),i.queryObjectMatrix(o,u=>u===1)},Us=(s,e)=>{const{fromRange:t,toRange:n}=s.params||{};if(!n||!t)return[];const o=Pe(t),r=Pe(n),a=Pe(e),u=Ht({start:o.startColumn,end:o.endColumn},{start:r.startColumn,end:r.endColumn},{start:a.startColumn,end:a.endColumn});return u===null?[{type:B.Delete}]:[{type:B.HorizontalMove,step:u.step||0,length:u.length||0}]},Tu=(s,e)=>{const{fromRange:t,toRange:n}=s.params||{};if(!t||!n)return[e];const o=t.startColumn,r=t.endColumn-t.startColumn+1,a=n.startColumn,u=new i.ObjectMatrix;return i.Range.foreach(e,(l,d)=>{u.setValue(l,d,1)}),u.moveColumns(o,r,a),i.queryObjectMatrix(u,l=>l===1)},mr=(s,e)=>{var r,a;const t=(r=s.params)==null?void 0:r.toRange,n=(a=s.params)==null?void 0:a.fromRange;if(!t||!n)return[];const o=[];if(i.Rectangle.contains(t,e)&&o.push({type:B.Delete}),i.Rectangle.contains(n,e)){o.push({type:B.Delete});const u=i.Rectangle.getRelativeRange(e,n),l=i.Rectangle.getPositionRange(u,t);return[{type:B.Set,range:l}]}return o},Uu=(s,e)=>{var m,h;const t=(m=s.params)==null?void 0:m.toRange,n=(h=s.params)==null?void 0:h.fromRange;if(!t||!n)return[e];if(!i.Rectangle.intersects(n,e)&&!i.Rectangle.intersects(t,e))return[e];if(i.Rectangle.contains(n,e)){const R=i.Rectangle.getRelativeRange(e,n);return[i.Rectangle.getPositionRange(R,t)]}const o=new i.ObjectMatrix;i.Range.foreach(e,(R,C)=>{o.setValue(R,C,1)});const r=new i.ObjectMatrix,a=i.Rectangle.getIntersects(n,e);a&&i.Range.foreach(a,(R,C)=>{o.getValue(R,C)&&(o.setValue(R,C,void 0),r.setValue(R,C,1))});const u=t.startColumn-n.startColumn,l=t.startRow-n.startRow,d={startColumn:t.startColumn-u,endColumn:t.endColumn-u,startRow:t.startRow-l,endRow:t.endRow-l};return d&&i.Range.foreach(d,(R,C)=>{var v;const S=R+l,I=C+u;o.setValue(S,I,(v=r.getValue(R,C))!=null?v:0)}),i.queryObjectMatrix(o,R=>R===1)},Ze=(s,e)=>{const t=Pe(s),n=Pe(e),o=a=>a.endColumn-a.startColumn+1,r=a=>a.endRow-a.startRow+1;if(t.startRow<=n.startRow&&t.endRow>=n.endRow){if(n.startColumn<t.startColumn&&n.endColumn>=t.startColumn&&n.endColumn<=t.endColumn||n.startColumn<t.startColumn&&n.endColumn>=t.endColumn){const a=i.Rectangle.getIntersects(n,t);if(a)return{step:0,length:-o(a)}}if(n.startColumn>=t.startColumn&&n.endColumn<=t.endColumn&&r(t)>=r(n))return null;if(n.startColumn>=t.startColumn&&n.startColumn<=t.endColumn&&n.endColumn>t.endColumn){const a=i.Rectangle.getIntersects(n,t);if(a){const u=-o(a);return{step:-(o(t)-o(a)),length:u}}}if(n.startColumn>t.endColumn)return{step:-o(t),length:0}}return{step:0,length:0}},Ps=(s,e)=>{var r;const t=(r=s.params)==null?void 0:r.range;if(!t)return[];const n=[],o=Ze(t,e);if(!o)n.push({type:B.Delete});else{const{step:a,length:u}=o;n.push({type:B.HorizontalMove,step:a,length:u})}return n},hr=(s,e,t)=>{var a;const n=(a=s.params)==null?void 0:a.range;if(!n)return[];const o=[];if(t&&t.length>0){let u=n.startRow;for(let l=n.startRow;l<=n.endRow;l++){if(t.includes(l)){if(l===u){u=l+1;continue}r({...n,startRow:u,endRow:l-1}),u=l+1;continue}l===n.endRow&&r({...n,startRow:u,endRow:n.endRow})}}else r(n);function r(u){const l=Ze(he(u),he(e));if(!l)o.push({type:B.Delete});else{const{step:d,length:c}=l;o.push({type:B.VerticalMove,step:d,length:c})}}return o},Pu=(s,e)=>{const{range:t,order:n}=s.params||{};if(!t||!n)return[];if(i.Rectangle.contains(t,e)&&e.endRow===e.startRow){const o=[],r=e.startRow;for(const a in n)if(n[a]===r){const u=Number(a);return o.push({type:B.VerticalMove,step:u-r,length:0}),o}return[]}return[]},Qe=(s,e)=>{const t=Pe(s),n=Pe(e),o=r=>r.endColumn-r.startColumn+1;return t.startRow<=n.startRow&&t.endRow>=n.endRow?n.startColumn<t.startColumn&&n.endColumn>=t.startColumn&&n.endColumn<=t.endColumn||n.startColumn<t.startColumn&&n.endColumn>=t.endColumn?{step:0,length:o(t)}:n.startColumn>=t.startColumn&&n.endColumn<=t.endColumn||n.startColumn>=t.startColumn&&n.startColumn<=t.endColumn&&n.endColumn>t.endColumn||n.startColumn>=t.endColumn?{step:o(t),length:0}:{step:0,length:0}:{step:0,length:0}};function ku(s,e,t){const n=[];if(i.Rectangle.contains(e,t)&&n.push({type:B.Delete}),i.Rectangle.contains(s,t)){n.push({type:B.Delete});const o=i.Rectangle.getRelativeRange(t,s),r=i.Rectangle.getPositionRange(o,e);return[{type:B.Set,range:r}]}return n}const gr=(s,e)=>{var u;const t=(u=s.params)==null?void 0:u.range;if(!t)return[];const n=[],o=Qe(he(t),he(e)),{step:r,length:a}=o;return n.push({type:B.VerticalMove,step:r,length:a}),n},Rr=(s,e)=>{var u;const t=(u=s.params)==null?void 0:u.range;if(!t)return[];const n=[],o=Qe(t,e),{step:r,length:a}=o;return n.push({type:B.HorizontalMove,step:r,length:a}),n},Cr=(s,e)=>{var u;const t=(u=s.params)==null?void 0:u.range;if(!t)return[];const n=[],o=Qe(he(t),he(e)),{step:r,length:a}=o;return n.push({type:B.VerticalMove,step:r,length:a}),n},Nu=(s,e)=>{var l;const t=(l=s.params)==null?void 0:l.range;if(!t)return[e];const n=t.endRow-t.startRow+1,o={...t,startRow:t.startRow,endRow:Number.POSITIVE_INFINITY},r=i.Rectangle.subtract(e,o),a=i.Rectangle.getIntersects(o,e);if(!a)return[e];const u=new i.ObjectMatrix;return r.forEach(d=>{i.Range.foreach(d,(c,m)=>{u.setValue(c,m,1)})}),a&&i.Range.foreach(a,(d,c)=>{u.setValue(d+n,c,1)}),i.queryObjectMatrix(u,d=>d===1)},Sr=(s,e)=>{var u;const t=(u=s.params)==null?void 0:u.range;if(!t)return[];const n=[],o=Qe(t,e),{step:r,length:a}=o;return n.push({type:B.HorizontalMove,step:r,length:a}),n},Ou=(s,e)=>{var l;const t=(l=s.params)==null?void 0:l.range;if(!t)return[e];const n=t.endColumn-t.startColumn+1,o={...t,startColumn:t.startColumn,endColumn:Number.POSITIVE_INFINITY},r=i.Rectangle.subtract(e,o),a=i.Rectangle.getIntersects(o,e);if(!a)return[e];const u=new i.ObjectMatrix;return r.forEach(d=>{i.Range.foreach(d,(c,m)=>{u.setValue(c,m,1)})}),a&&i.Range.foreach(a,(d,c)=>{u.setValue(d,c+n,1)}),i.queryObjectMatrix(u,d=>d===1)},fr=(s,e)=>{var r;const t=(r=s.params)==null?void 0:r.range;if(!t)return[];const n=[],o=Ze(t,e);if(!o)n.push({type:B.Delete});else{const{step:a,length:u}=o;n.push({type:B.HorizontalMove,step:a,length:u})}return n},Du=(s,e)=>{var d;const t=(d=s.params)==null?void 0:d.range;if(!t)return[e];const n={startRow:t.startRow,endRow:t.endRow,startColumn:t.startColumn,endColumn:Number.POSITIVE_INFINITY},o=t.endColumn-t.startColumn+1,r=i.Rectangle.getIntersects(t,e),a=i.Rectangle.subtract(e,n),u=i.Rectangle.getIntersects(n,e);if(!r&&!u)return[e];const l=new i.ObjectMatrix;return u&&i.Range.foreach(u,(c,m)=>{l.setValue(c,m-o,1)}),r&&i.Range.foreach(r,(c,m)=>{l.setValue(c,m-o,0)}),a.forEach(c=>{i.Range.foreach(c,(m,h)=>{l.setValue(m,h,1)})}),i.queryObjectMatrix(l,c=>c===1)},Ir=(s,e)=>{var r;const t=(r=s.params)==null?void 0:r.range;if(!t)return[];const n=[],o=Ze(he(t),he(e));if(!o)n.push({type:B.Delete});else{const{step:a,length:u}=o;n.push({type:B.VerticalMove,step:a,length:u})}return n},Au=(s,e)=>{var d;const t=(d=s.params)==null?void 0:d.range;if(!t)return[e];const n={...t,startRow:t.startRow,endRow:Number.POSITIVE_INFINITY},o=t.endRow-t.startRow+1,r=i.Rectangle.getIntersects(t,e),a=i.Rectangle.subtract(e,n),u=i.Rectangle.getIntersects(n,e);if(!r&&!u)return[e];const l=new i.ObjectMatrix;return u&&i.Range.foreach(u,(c,m)=>{l.setValue(c-o,m,1)}),r&&i.Range.foreach(r,(c,m)=>{l.setValue(c-o,m,0)}),a.forEach(c=>{i.Range.foreach(c,(m,h)=>{l.setValue(m,h,1)})}),i.queryObjectMatrix(l,c=>c===1)},Wu=(s,e)=>{var o;const t=(o=s.ranges)!=null?o:[s.range],n=new i.ObjectMatrix;return i.Range.foreach(e,(r,a)=>{n.setValue(r,a,1)}),t.forEach(r=>{const a=r.startRow,l=r.endRow-a+1;n.removeRows(a,l)}),i.queryObjectMatrix(n,r=>r===1)},Vu=(s,e)=>{const t=s.params,n=t.range.startRow,o=t.range.endRow-t.range.startRow+1;return e.startRow>=n?[{startRow:e.startRow+o,endRow:e.endRow+o,startColumn:e.startColumn,endColumn:e.endColumn}]:e.endRow<n?[e]:[{startRow:e.startRow,endRow:e.endRow+o,startColumn:e.startColumn,endColumn:e.endColumn}]},$u=(s,e)=>{const t=s.params,n=t.range.startColumn,o=t.range.endColumn-t.range.startColumn+1;return e.startColumn>=n?[{startRow:e.startRow,endRow:e.endRow,startColumn:e.startColumn+o,endColumn:e.endColumn+o}]:e.endColumn<n?[e]:[{startRow:e.startRow,endRow:e.endRow,startColumn:e.startColumn,endColumn:e.endColumn+o}]},et=(s,e)=>{let t={...e};return s.forEach(n=>{switch(n.type){case B.Delete:{t=null;break}case B.HorizontalMove:{if(!t)return;t.startColumn+=n.step,t.endColumn+=n.step+(n.length||0);break}case B.VerticalMove:{if(!t)return;t.startRow+=n.step,t.endRow+=n.step+(n.length||0);break}case B.Set:{t=n.range;break}}}),t&&(t.endColumn<t.startColumn||t.endRow<t.startRow)?null:t},ks=(s,e)=>{let t=[];switch(e.id){case A.DeleteRangeMoveLeftCommandId:{t=fr(e,s);break}case A.DeleteRangeMoveUpCommandId:{t=Ir(e,s);break}case A.InsertColCommandId:{t=Rr(e,s);break}case A.InsertRangeMoveDownCommandId:{t=Cr(e,s);break}case A.InsertRangeMoveRightCommandId:{t=Sr(e,s);break}case A.InsertRowCommandId:{t=gr(e,s);break}case A.MoveColsCommandId:{t=Us(e,s);break}case A.MoveRangeCommandId:{t=mr(e,s);break}case A.MoveRowsCommandId:{t=Ts(e,s);break}case A.RemoveColCommandId:{t=Ps(e,s);break}case A.RemoveRowCommandId:{t=hr(e,s);break}case A.ReorderRangeCommandId:{t=Pu(e,s);break}}return et(t,s)},Lu=(s,e,t)=>[Be.id,He.id].includes(e.id)||pr(e,t).some(r=>i.Rectangle.intersects(r,s))?ks(s,e):s,Ns=(s,e)=>{let t=[];switch(e.id){case A.DeleteRangeMoveLeftCommandId:return Du(e,s);case A.DeleteRangeMoveUpCommandId:return Au(e,s);case A.InsertRangeMoveDownCommandId:return Nu(e,s);case A.InsertRangeMoveRightCommandId:return Ou(e,s);case A.InsertColCommandId:return $u(e,s);case A.InsertRowCommandId:return Vu(e,s);case A.MoveColsCommandId:return Tu(e,s);case A.MoveRangeCommandId:return Uu(e,s);case A.MoveRowsCommandId:return bu(e,s);case A.ReorderRangeCommandId:return Eu(e,s);case A.RemoveColCommandId:{t=Ps(e,s);break}case A.RemoveRowCommandId:return Wu(e.params,s)}const n=et(t,s);return n?[n]:[]},Bu=(s,e,t)=>[Be.id,He.id,xe.id,ws].includes(e.id)||pr(e,t).some(r=>i.Rectangle.intersects(r,s))?Ns(s,e):s;function vr(s,e){const{id:t,params:n}=e;let o={length:0,step:0,type:B.Unknown};switch(t){case Xe.id:o.type=B.Delete;break;case pe.id:o=Ht({start:n.sourceRange.startRow,end:n.sourceRange.endRow},{start:n.targetRange.startRow,end:n.targetRange.endRow},{start:s.startRow,end:s.endRow}),o.type=B.VerticalMove;break;case we.id:o=Ht({start:n.sourceRange.startColumn,end:n.sourceRange.endColumn},{start:n.targetRange.startColumn,end:n.targetRange.endColumn},{start:s.startColumn,end:s.endColumn}),o.type=B.HorizontalMove;break;case ne.id:o=Ze(n.range,s),o?o.type=B.HorizontalMove:o={step:0,length:0,type:B.Delete};break;case ae.id:o=Ze(he(n.range),he(s)),o?o.type=B.VerticalMove:o={step:0,length:0,type:B.Delete};break;case re.id:o=Qe(he(n.range),he(s)),o.type=B.VerticalMove;break;case ie.id:o=Qe(n.range,s),o.type=B.HorizontalMove;break;case Le.id:{const r=n.fromRange||new i.ObjectMatrix(n.from).getRange(),a=n.toRange||new i.ObjectMatrix(n.to).getRange();o=ku(r,a,s)}break}return o?Array.isArray(o)?et(o,s):et([o],s):s}function pr(s,e){var n,o,r,a,u,l;const{selectionManagerService:t}=e;switch(s.id){case A.MoveColsCommandId:{const d=s.params;return[d.fromRange,{...d.toRange,startColumn:d.toRange.startColumn-.5,endColumn:d.toRange.endColumn-.5}]}case A.MoveRowsCommandId:{const d=s.params;return[d.fromRange,{...d.toRange,startRow:d.toRange.startRow-.5,endRow:d.toRange.startRow-.5}]}case A.MoveRangeCommandId:{const d=s;return[d.params.fromRange,d.params.toRange]}case A.InsertRowCommandId:{const c=s.params.range;return[{...c,startRow:c.startRow-.5,endRow:c.endRow-.5}]}case A.InsertColCommandId:{const c=s.params.range;return[{...c,startColumn:c.startColumn-.5,endColumn:c.endColumn-.5}]}case A.RemoveRowCommandId:return[s.params.range];case A.RemoveColCommandId:return[s.params.range];case A.DeleteRangeMoveUpCommandId:case A.InsertRangeMoveDownCommandId:{const c=((n=s.params)==null?void 0:n.range)||((r=(o=t.getCurrentSelections())==null?void 0:o.map(m=>m.range))==null?void 0:r[0]);return c?[c]:[]}case A.DeleteRangeMoveLeftCommandId:case A.InsertRangeMoveRightCommandId:{const c=((a=s.params)==null?void 0:a.range)||((l=(u=t.getCurrentSelections())==null?void 0:u.map(m=>m.range))==null?void 0:l[0]);return c?[c]:[]}case A.ReorderRangeCommandId:{const d=s,{range:c,order:m}=d.params,h=[];for(let R=c.startRow;R<=c.endRow;R++)R in m&&h.push({startRow:R,endRow:R,startColumn:c.startColumn,endColumn:c.endColumn});return h}}}function Hu(s){switch(s.id){case we.id:{const e=s.params;return[e.sourceRange,{...e.targetRange,startColumn:e.targetRange.startColumn-.5,endColumn:e.targetRange.startColumn-.5}]}case pe.id:{const e=s.params;return[e.sourceRange,{...e.targetRange,startRow:e.targetRange.startRow-.5,endRow:e.targetRange.startRow-.5}]}case Le.id:{const e=s.params;return[new i.ObjectMatrix(e.from.value).getRange(),new i.ObjectMatrix(e.to.value).getRange()]}case ie.id:{const t=s.params.range;return[{...t,startColumn:t.startColumn-.5,endColumn:t.startColumn-.5}]}case re.id:{const t=s.params.range;return[{...t,startRow:t.startRow-.5,endRow:t.startRow-.5}]}case ne.id:return[s.params.range];case ae.id:return[s.params.range]}}function Fu(s,e){var o,r,a,u,l,d;const t=s.get(i.IUniverInstanceService),n=s.get(g.SheetsSelectionsService);switch(e.id){case A.MoveColsCommandId:{const c=e.params,m=P(t,{unitId:c.unitId,subUnitId:c.subUnitId});return{unitId:m.unitId,subUnitId:m.subUnitId,ranges:[c.fromRange,{...c.toRange,startColumn:c.fromRange.startColumn<c.toRange.startColumn?c.fromRange.endColumn+1:c.toRange.startColumn,endColumn:c.fromRange.startColumn<c.toRange.startColumn?c.toRange.endColumn-1:c.fromRange.startColumn-1}]}}case A.MoveRowsCommandId:{const c=e.params,m=P(t,{unitId:c.unitId,subUnitId:c.subUnitId});return{unitId:m.unitId,subUnitId:m.subUnitId,ranges:[c.fromRange,{...c.toRange,startRow:c.fromRange.startRow<c.toRange.startRow?c.fromRange.endRow+1:c.toRange.startRow,endRow:c.fromRange.startRow<c.toRange.startRow?c.toRange.endRow-1:c.fromRange.startRow-1}]}}case A.MoveRangeCommandId:{const c=e.params,m=P(t);return{unitId:m.unitId,subUnitId:m.subUnitId,ranges:[c.fromRange,c.toRange]}}case A.InsertRowCommandId:{const c=e.params,m=c.range;return{unitId:c.unitId,subUnitId:c.subUnitId,ranges:[...m.startRow>0?[{...m,startRow:m.startRow-1,endRow:m.endRow-1}]:[],{...m,startRow:m.startRow,endRow:Number.MAX_SAFE_INTEGER}]}}case A.InsertColCommandId:{const c=e.params,m=c.range;return{unitId:c.unitId,subUnitId:c.subUnitId,ranges:[...m.startColumn>0?[{...m,startColumn:m.startColumn-1,endColumn:m.endColumn-1}]:[],{...m,startColumn:m.startColumn,endColumn:Number.MAX_SAFE_INTEGER}]}}case A.RemoveRowCommandId:{const m=e.params.range,h=P(t);return{unitId:h.unitId,subUnitId:h.subUnitId,ranges:[m,{...m,startRow:m.endRow+1,endRow:Number.MAX_SAFE_INTEGER}]}}case A.RemoveColCommandId:{const m=e.params.range,h=P(t);return{unitId:h.unitId,subUnitId:h.subUnitId,ranges:[m,{...m,startColumn:m.endColumn+1,endColumn:Number.MAX_SAFE_INTEGER}]}}case A.DeleteRangeMoveUpCommandId:case A.InsertRangeMoveDownCommandId:{const c=e,m=P(t),h=((o=c.params)==null?void 0:o.range)||((a=(r=n.getCurrentSelections())==null?void 0:r.map(R=>R.range))==null?void 0:a[0]);return h?{unitId:m.unitId,subUnitId:m.subUnitId,ranges:[h,{...h,startRow:h.endRow+1,endRow:Number.MAX_SAFE_INTEGER}]}:{unitId:m.unitId,subUnitId:m.subUnitId,ranges:[]}}case A.DeleteRangeMoveLeftCommandId:case A.InsertRangeMoveRightCommandId:{const m=((u=e.params)==null?void 0:u.range)||((d=(l=n.getCurrentSelections())==null?void 0:l.map(R=>R.range))==null?void 0:d[0]),h=P(t);return m?{unitId:h.unitId,subUnitId:h.subUnitId,ranges:[m,{...m,startColumn:m.endColumn+1,endColumn:Number.MAX_SAFE_INTEGER}]}:{unitId:h.unitId,subUnitId:h.subUnitId,ranges:[]}}case A.ReorderRangeCommandId:{const c=e,{range:m,order:h}=c.params,R=[];for(let S=m.startRow;S<=m.endRow;S++)S in h&&R.push({startRow:S,endRow:S,startColumn:m.startColumn,endColumn:m.endColumn});const C=P(t);return{unitId:C.unitId,subUnitId:C.subUnitId,ranges:R}}}}var ju=Object.getOwnPropertyDescriptor,Gu=(s,e,t,n)=>{for(var o=n>1?void 0:n?ju(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},Sn=(s,e)=>(t,n)=>e(t,n,s);const zu=i.createInterceptorKey("MERGE_REDO"),qu=i.createInterceptorKey("MERGE_UNDO"),wr=Math.floor(Number.MAX_SAFE_INTEGER/10);class Yu extends i.Disposable{constructor(e,t,n,o,r=!1){super(),this._unitId=e,this._subUnitId=t,this._range=n,this._callback=o,this._skipIntersects=r}onMutation(e){var o,r;if(((o=e.params)==null?void 0:o.unitId)!==this._unitId)return;if(e.id===Le.id){const a=e.params;if(a.from.subUnitId!==this._subUnitId||a.to.subUnitId!==this._subUnitId)return}else if(((r=e.params)==null?void 0:r.subUnitId)!==this._subUnitId)return;if(!this._range)return;if(this._skipIntersects){if(e.id===Xe.id)return;const a=Hu(e);if(a!=null&&a.some(u=>i.Rectangle.intersects(u,this._range)))return}const t=vr(this._range,e);if(t&&i.Rectangle.equals(t,this._range))return!1;const n=this._range;this._range=t,this._callback(n,t)}}g.RefRangeService=class extends i.Disposable{constructor(t,n,o,r){super();f(this,"interceptor",new i.InterceptorManager({MERGE_REDO:zu,MERGE_UNDO:qu}));f(this,"_watchRanges",new Set);f(this,"_refRangeManagerMap",new Map);f(this,"_serializer",Ku());f(this,"_onRefRangeChange",()=>{this._sheetInterceptorService.interceptCommand({getMutations:t=>{const n=this._univerInstanceService.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET).getActiveSheet(),o=Mr(this._univerInstanceService),r=yr(this._univerInstanceService);if(!n||!o||!r)return{redos:[],undos:[],preRedos:[],preUndos:[]};const l=((()=>{switch(t.id){case A.MoveColsCommandId:{const R=t.params,C=Math.min(R.fromRange.startColumn,R.toRange.startColumn);return this._checkRange([{...R.fromRange,startColumn:C,endColumn:n.getColumnCount()-1}],o,r)}case A.MoveRowsCommandId:{const R=t.params,C=Math.min(R.fromRange.startRow,R.toRange.startRow);return this._checkRange([{...R.fromRange,startRow:C,endRow:n.getRowCount()-1}],o,r)}case A.MoveRangeCommandId:{const R=t;return this._checkRange([R.params.fromRange,R.params.toRange],o,r)}case A.InsertRowCommandId:{const S={startRow:t.params.range.startRow,endRow:n.getRowCount()-1,startColumn:0,endColumn:n.getColumnCount()-1,rangeType:i.RANGE_TYPE.ROW};return this._checkRange([S],o,r)}case A.InsertColCommandId:{const C=t.params.range.startColumn,S={startRow:0,endRow:n.getRowCount()-1,startColumn:C,endColumn:n.getColumnCount()-1,rangeType:i.RANGE_TYPE.COLUMN};return this._checkRange([S],o,r)}case A.RemoveRowCommandId:{const S={startRow:t.params.range.startRow,endRow:n.getRowCount()-1,startColumn:0,endColumn:n.getColumnCount()-1,rangeType:i.RANGE_TYPE.ROW};return this._checkRange([S],o,r)}case A.RemoveColCommandId:{const C=t.params.range.startColumn,S={startRow:0,endRow:n.getRowCount()-1,startColumn:C,endColumn:n.getColumnCount()-1,rangeType:i.RANGE_TYPE.COLUMN};return this._checkRange([S],o,r)}case A.DeleteRangeMoveUpCommandId:case A.InsertRangeMoveDownCommandId:{const C=t.params.range||_r(this._selectionManagerService)[0],S={startRow:C.startRow,startColumn:C.startColumn,endColumn:C.endColumn,endRow:wr};return this._checkRange([S],o,r)}case A.DeleteRangeMoveLeftCommandId:case A.InsertRangeMoveRightCommandId:{const C=t.params.range||_r(this._selectionManagerService)[0],S={startRow:C.startRow,startColumn:C.startColumn,endColumn:wr,endRow:C.endRow};return this._checkRange([S],o,r)}case A.ReorderRangeCommandId:{const R=t,{range:C,order:S}=R.params,I=[];for(let v=C.startRow;v<=C.endRow;v++)v in S&&I.push({startRow:v,endRow:v,startColumn:C.startColumn,endColumn:C.endColumn});return this._checkRange(I,o,r)}}})()||[]).reduce((R,C)=>{const S=C(t);return R.push(S),R},[]).reduce((R,C)=>{var S,I;return R.redos.push(...C.redos),R.undos.push(...C.undos),R.preRedos.push(...(S=C.preRedos)!=null?S:[]),R.preUndos.push(...(I=C.preUndos)!=null?I:[]),R},{redos:[],undos:[],preUndos:[],preRedos:[]}),d=this.interceptor.fetchThroughInterceptors(this.interceptor.getInterceptPoints().MERGE_REDO)(l.preRedos,null)||[],c=this.interceptor.fetchThroughInterceptors(this.interceptor.getInterceptPoints().MERGE_REDO)(l.redos,null)||[],m=this.interceptor.fetchThroughInterceptors(this.interceptor.getInterceptPoints().MERGE_UNDO)(l.preUndos,null)||[],h=this.interceptor.fetchThroughInterceptors(this.interceptor.getInterceptPoints().MERGE_UNDO)(l.undos,null)||[];return{redos:c,undos:h,preRedos:d,preUndos:m}}})});f(this,"_checkRange",(t,n,o)=>{const r=br(n,o),a=this._refRangeManagerMap.get(r);if(a){const u=new Set;return[...a.keys()].forEach(d=>{const c=a.get(d),m=this._serializer.deserialize(d),h={...m,startRow:+m.startRow,endRow:+m.endRow,startColumn:+m.startColumn,endColumn:+m.endColumn,rangeType:m.rangeType&&+m.rangeType};t.some(R=>i.Rectangle.intersects(R,h))&&c&&c.forEach(R=>{u.add(R)})}),[...u]}return[]});f(this,"registerRefRange",(t,n,o,r)=>{const a=o||Mr(this._univerInstanceService),u=r||yr(this._univerInstanceService);if(!a||!u)return i.toDisposable(()=>{});const l=br(a,u),d=this._serializer.serialize(t);let c=this._refRangeManagerMap.get(l);c||(c=new Map,this._refRangeManagerMap.set(l,c));const m=c.get(d);return m?m.add(n):c.set(d,new Set([n])),i.toDisposable(()=>{const h=c.get(d);h&&(h.delete(n),h.size||(c.delete(d),c.size||this._refRangeManagerMap.delete(l)))})});this._commandService=t,this._sheetInterceptorService=n,this._univerInstanceService=o,this._selectionManagerService=r,this._onRefRangeChange(),this.interceptor.intercept(this.interceptor.getInterceptPoints().MERGE_REDO,{priority:-1,handler:a=>a}),this.interceptor.intercept(this.interceptor.getInterceptPoints().MERGE_UNDO,{priority:-1,handler:a=>a})}watchRange(t,n,o,r,a){let u;this._watchRanges.size===0&&(u=this._commandService.onCommandExecuted(m=>{if(m.type!==i.CommandType.MUTATION)return!1;for(const h of this._watchRanges)h.onMutation(m)}));const l=new Yu(t,n,o,r,a);this._watchRanges.add(l);const d=i.toDisposable(()=>{this._watchRanges.delete(l),this._watchRanges.size===0&&(u==null||u.dispose(),u=null)}),c=this.disposeWithMe(d);return i.toDisposable(()=>{c.dispose(),d.dispose()})}},g.RefRangeService=Gu([Sn(0,i.ICommandService),Sn(1,i.Inject(g.SheetInterceptorService)),Sn(2,i.Inject(i.IUniverInstanceService)),Sn(3,i.Inject(g.SheetsSelectionsService))],g.RefRangeService);function Mr(s){return s.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET).getUnitId()}function yr(s){var e;return(e=s.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET).getActiveSheet())==null?void 0:e.getSheetId()}function _r(s){var e;return((e=s.getCurrentSelections())==null?void 0:e.map(t=>t.range))||[]}function br(s,e){return`${s}_${e}`}function Ku(){const s=["startRow","startColumn","endRow","endColumn","rangeType"];return{deserialize:t=>{const n=s.reduce((r,a,u)=>(r[String(u)]=a,r),{});return t.split("_").reduce((r,a,u)=>{const l=String(u);return a&&n[l]&&(r[n[l]]=a),r},{})},serialize:t=>s.reduce((n,o,r)=>{const a=t[o];return a!==void 0?`${n}${r>0?"_":""}${a}`:`${n}`},"")}}var Ju=Object.getOwnPropertyDescriptor,xu=(s,e,t,n)=>{for(var o=n>1?void 0:n?Ju(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},Mt=(s,e)=>(t,n)=>e(t,n,s);const Xu=[ie.id,re.id,ne.id,ae.id],Zu=[pe.id,we.id];function Os(s,e){let t=s;if(e!==void 0){const n=[];for(let o=0;o<t.length;o++){const{startRow:r,endRow:a,startColumn:u,endColumn:l}=t[o];if(e===i.Dimension.ROWS)for(let d=r;d<=a;d++){const c={startRow:d,endRow:d,startColumn:u,endColumn:l};n.push(c)}else if(e===i.Dimension.COLUMNS)for(let d=u;d<=l;d++){const c={startRow:r,endRow:a,startColumn:d,endColumn:d};n.push(c)}}t=n}return t}const Er=i.createInterceptorKey("mergeCellPermissionCheck");g.MergeCellController=class extends i.Disposable{constructor(t,n,o,r,a,u){super();f(this,"disposableCollection",new i.DisposableCollection);f(this,"interceptor",new i.InterceptorManager({MERGE_CELL_INTERCEPTOR_CHECK:Er}));this._commandService=t,this._refRangeService=n,this._univerInstanceService=o,this._injector=r,this._sheetInterceptorService=a,this._selectionManagerService=u,this._onRefRangeChange(),this._initCommandInterceptor(),this._commandExecutedListener()}_initCommandInterceptor(){const t=this;this._sheetInterceptorService.interceptCommand({getMutations(n){var o;switch(n.id){case sn.id:case on.id:{const r=t._univerInstanceService.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET),a=r.getUnitId(),u=r==null?void 0:r.getActiveSheet();if(!u)return{redos:[],undos:[]};const l=u.getSheetId(),d=u.getConfig().mergeData,c=(o=t._selectionManagerService.getCurrentSelections())==null?void 0:o.map(m=>m.range);if(c&&c.length>0&&c.some(h=>d.some(R=>i.Rectangle.intersects(R,h)))){const h={unitId:a,subUnitId:l,ranges:c},R=ue(t._injector,h),C=[{id:G.id,params:h}],S=[{id:j.id,params:R}];return{redos:C,undos:S}}}}return{redos:[],undos:[]}}}),this._sheetInterceptorService.interceptRanges({getMutations:({unitId:n,subUnitId:o,ranges:r})=>{const a=[],u=[],l={redos:a,undos:u};if(!r||!r.length)return l;const d=P(this._univerInstanceService,{unitId:n,subUnitId:o});if(!d)return l;const{worksheet:c}=d,h=c.getMergeData().filter(R=>r.some(C=>i.Rectangle.intersects(R,C)));return h.length?(a.push({id:G.id,params:{unitId:n,subUnitId:o,ranges:h}}),u.push({id:j.id,params:{unitId:n,subUnitId:o,ranges:h}}),{undos:u,redos:a}):l}})}refRangeHandle(t,n,o){switch(t.id){case A.MoveColsCommandId:{const r=t.params;return this._handleMoveColsCommand(r,n,o)}case A.MoveRowsCommandId:{const r=t.params;return this._handleMoveRowsCommand(r,n,o)}case Me.id:{const r=t.params,a=r.unitId||n,u=r.subUnitId||o;return this._handleInsertRowCommand(r,a,u)}case ye.id:{const r=t.params,a=r.unitId||n,u=r.subUnitId||o;return this._handleInsertColCommand(r,a,u)}case Lt.id:{const r=t.params;return this._handleRemoveColCommand(r,n,o)}case $t.id:{const r=t.params;return this._handleRemoveRowCommand(r,n,o)}case Je.id:{const r=t.params;return this._handleMoveRangeCommand(r,n,o)}case vt.id:{const r=t.params;return this._handleInsertRangeMoveRightCommand(r,n,o)}case xe.id:{const r=t.params;return this._handleInsertRangeMoveDownCommand(r,n,o)}case He.id:{const r=t.params;return this._handleDeleteRangeMoveUpCommand(r,n,o)}case Be.id:{const r=t.params;return this._handleDeleteRangeMoveLeftCommand(r,n,o)}}return{redos:[],undos:[]}}_onRefRangeChange(){const t=(n,o)=>{const r=this._univerInstanceService.getUniverSheetInstance(n);if(!r)return;const a=r==null?void 0:r.getSheetBySheetId(o);if(!a)return;this.disposableCollection.dispose();const u=a.getMergeData(),l=d=>this.refRangeHandle(d,n,o);u.forEach(d=>{this.disposableCollection.add(this._refRangeService.registerRefRange(d,l,n,o))})};this.disposeWithMe(this._commandService.onCommandExecuted(n=>{if(n.id===Ct.id){const o=n.params,r=o.subUnitId,a=o.unitId;if(!r||!a)return;t(a,r)}if(n.id===j.id){const o=n.params,r=o.subUnitId,a=o.unitId;if(!r||!a)return;t(o.unitId,o.subUnitId)}})),this._univerInstanceService.getCurrentTypeOfUnit$(i.UniverInstanceType.UNIVER_SHEET).pipe(O.first(n=>!!n)).subscribe(n=>{const o=n.getActiveSheet();o&&t(n.getUnitId(),o.getSheetId())})}_handleMoveRowsCommand(t,n,o){const r=_e(this._univerInstanceService,n);if(!r)return this._handleNull();const a=be(r,o);if(!a)return this._handleNull();const u=[...a.getMergeData()],l={unitId:n,subUnitId:o,ranges:[]},d={unitId:n,subUnitId:o,ranges:[]},{fromRange:c}=t,{startRow:m,endRow:h}=c;if(u.forEach(S=>{if(m<=S.startRow&&h>=S.endRow){l.ranges.push(S);const I=Ts({id:A.MoveRowsCommandId,params:t},S),v=et(I,S);v&&d.ranges.push(v)}}),l.ranges.length===0)return this._handleNull();const R=ue(this._injector,l),C=ge(this._injector,d);return{preRedos:[{id:G.id,params:l}],redos:[{id:j.id,params:d}],preUndos:[{id:G.id,params:C}],undos:[{id:j.id,params:R}]}}_handleMoveColsCommand(t,n,o){const r=_e(this._univerInstanceService,n);if(!r)return this._handleNull();const a=be(r,o);if(!a)return this._handleNull();const u=[...a.getMergeData()],l={unitId:n,subUnitId:o,ranges:[]},d={unitId:n,subUnitId:o,ranges:[]},{fromRange:c}=t,{startColumn:m,endColumn:h}=c;if(u.forEach(S=>{if(m<=S.startColumn&&h>=S.endColumn){l.ranges.push(S);const I=Us({id:A.MoveColsCommandId,params:t},S),v=et(I,S);v&&d.ranges.push(v)}}),l.ranges.length===0)return this._handleNull();const R=ue(this._injector,l),C=ge(this._injector,d);return{preRedos:[{id:G.id,params:l}],redos:[{id:j.id,params:d}],preUndos:[{id:G.id,params:C}],undos:[{id:j.id,params:R}]}}_handleMoveRangeCommand(t,n,o){const r=_e(this._univerInstanceService,n);if(!r)return this._handleNull();const a=be(r,o);if(!a)return this._handleNull();const u=a.getMergeData(),l=u.filter(C=>i.Rectangle.intersects(C,t.fromRange)),d=u.filter(C=>i.Rectangle.intersects(C,t.toRange)),c=l.map(C=>i.Rectangle.getRelativeRange(C,t.fromRange)).map(C=>i.Rectangle.getPositionRange(C,t.toRange)),m=Os(c).filter(C=>!u.some(S=>i.Rectangle.equals(C,S))),h=[{id:G.id,params:{unitId:n,subUnitId:o,ranges:l}},{id:G.id,params:{unitId:n,subUnitId:o,ranges:d}},{id:j.id,params:{unitId:n,subUnitId:o,ranges:m}}],R=[{id:G.id,params:{unitId:n,subUnitId:o,ranges:m}},{id:j.id,params:{unitId:n,subUnitId:o,ranges:d}},{id:j.id,params:{unitId:n,subUnitId:o,ranges:l}}];return{redos:h,undos:R}}_handleInsertRowCommand(t,n,o){const r=_e(this._univerInstanceService,n);if(!r)return this._handleNull();const a=be(r,o);if(!a)return this._handleNull();const{range:u}=t,{startRow:l,endRow:d}=u,c=i.Tools.deepClone(a.getMergeData()).reduce((M,p)=>(l>p.startRow&&l<=p.endRow&&M.push(p),M),[]);if(c.length===0)return this._handleNull();const m=i.Tools.deepClone(a.getMergeData()).reduce((M,p)=>{if(l>p.startRow&&l<=p.endRow){const w=d-l+1;p.endRow+=w,this._checkIsMergeCell(p)&&M.push(p)}return M},[]),h={unitId:n,subUnitId:o,ranges:c},R=ue(this._injector,h),C={unitId:n,subUnitId:o,ranges:m},S=ge(this._injector,C),I=[{id:G.id,params:h},{id:j.id,params:C}],v=[{id:G.id,params:S},{id:j.id,params:R}];return{redos:I,undos:v}}_handleInsertColCommand(t,n,o){const{range:r}=t,a=_e(this._univerInstanceService,n);if(!a)return this._handleNull();const u=be(a,o);if(!u)return this._handleNull();const{startColumn:l,endColumn:d}=r,c=i.Tools.deepClone(u.getMergeData()).reduce((M,p)=>(l>p.startColumn&&l<=p.endColumn&&M.push(p),M),[]);if(c.length===0)return this._handleNull();const m=i.Tools.deepClone(u.getMergeData()).reduce((M,p)=>{if(l>p.startColumn&&l<=p.endColumn){const w=d-l+1;p.endColumn+=w,this._checkIsMergeCell(p)&&M.push(p)}return M},[]),h={unitId:n,subUnitId:o,ranges:c},R=ue(this._injector,h),C={unitId:n,subUnitId:o,ranges:m},S=ge(this._injector,C),I=[{id:G.id,params:h},{id:j.id,params:C}],v=[{id:G.id,params:S},{id:j.id,params:R}];return{redos:I,undos:v}}_handleRemoveColCommand(t,n,o){const r=_e(this._univerInstanceService,n);if(!r)return this._handleNull();const a=be(r,o);if(!a)return this._handleNull();const{range:u}=t,{startColumn:l,endColumn:d}=u,c=i.Tools.deepClone(a.getMergeData()).reduce((w,y)=>(i.Rectangle.intersects(u,y)&&w.push(y),w),[]);if(c.length===0)return this._handleNull();const m=i.Tools.deepClone(a.getMergeData()).reduce((w,y)=>{if(i.Rectangle.intersects(u,y)){if(l<=y.startColumn&&d>=y.endColumn)return w;l>=y.startColumn&&d<=y.endColumn?y.endColumn-=d-l+1:l<y.startColumn?(y.startColumn=l,y.endColumn-=d-l+1):d>y.endColumn&&(y.endColumn=l-1),this._checkIsMergeCell(y)&&w.push(y)}return w},[]),h={unitId:n,subUnitId:o,ranges:c},R=ue(this._injector,h),C={unitId:n,subUnitId:o,ranges:m},S=ge(this._injector,C),I=[{id:G.id,params:h}],v=[{id:j.id,params:C}],M=[{id:G.id,params:S}],p=[{id:j.id,params:R}];return{preUndos:M,undos:p,preRedos:I,redos:v}}_handleRemoveRowCommand(t,n,o){const{range:r}=t,a=_e(this._univerInstanceService,n);if(!a)return this._handleNull();const u=be(a,o);if(!u)return this._handleNull();const{startRow:l,endRow:d}=r,c=i.Tools.deepClone(u.getMergeData()).reduce((w,y)=>(i.Rectangle.intersects(r,y)&&w.push(y),w),[]);if(c.length===0)return this._handleNull();const m=i.Tools.deepClone(u.getMergeData()).reduce((w,y)=>{if(i.Rectangle.intersects(r,y)){if(l<=y.startRow&&d>=y.endRow)return w;l>=y.startRow&&d<=y.endRow?y.endRow-=d-l+1:l<y.startRow?(y.startRow=l,y.endRow-=d-l+1):d>y.endRow&&(y.endRow=l-1),this._checkIsMergeCell(y)&&w.push(y)}return w},[]),h={unitId:n,subUnitId:o,ranges:c},R=ue(this._injector,h),C={unitId:n,subUnitId:o,ranges:m},S=ge(this._injector,C),I=[{id:G.id,params:h}],v=[{id:j.id,params:C}],M=[{id:G.id,params:S}],p=[{id:j.id,params:R}];return{preUndos:M,undos:p,preRedos:I,redos:v}}_handleInsertRangeMoveRightCommand(t,n,o){const r=_e(this._univerInstanceService,n);if(!r)return this._handleNull();const a=be(r,o);if(!a)return this._handleNull();const u=t.range,l=a.getMaxColumns()-1,d=a.getMergeData(),c=[],m=[];d.forEach(I=>{const{startRow:v,endRow:M,startColumn:p,endColumn:w}=u;if(i.Rectangle.intersects({startRow:v,startColumn:p,endRow:M,endColumn:l},I)&&(c.push(I),i.Rectangle.contains({startRow:v,startColumn:p,endRow:M,endColumn:l},I))){const T=w-p+1;m.push({startRow:I.startRow,startColumn:I.startColumn+T,endRow:I.endRow,endColumn:I.endColumn+T})}});const h={unitId:n,subUnitId:o,ranges:c},R=ue(this._injector,h),C={unitId:n,subUnitId:o,ranges:m},S=ge(this._injector,C);return{preRedos:[{id:G.id,params:h}],redos:[{id:j.id,params:C}],preUndos:[{id:G.id,params:S}],undos:[{id:j.id,params:R}]}}_handleInsertRangeMoveDownCommand(t,n,o){const r=_e(this._univerInstanceService,n);if(!r)return this._handleNull();const a=be(r,o);if(!a)return this._handleNull();const u=t.range,l=a.getMaxRows()-1,d=a.getMergeData(),c=[],m=[];d.forEach(w=>{const{startRow:y,startColumn:b,endColumn:T,endRow:U}=u;if(i.Rectangle.intersects({startRow:y,startColumn:b,endRow:l,endColumn:T},w)&&(c.push(w),i.Rectangle.contains({startRow:y,startColumn:b,endRow:l,endColumn:T},w))){const N=U-y+1;m.push({startRow:w.startRow+N,startColumn:w.startColumn,endRow:w.endRow+N,endColumn:w.endColumn})}});const h={unitId:n,subUnitId:o,ranges:c},R=ue(this._injector,h),C={unitId:n,subUnitId:o,ranges:m},S=ge(this._injector,C),I=[{id:G.id,params:h}],v=[{id:j.id,params:C}],M=[{id:G.id,params:S}],p=[{id:j.id,params:R}];return{redos:v,undos:p,preRedos:I,preUndos:M}}_handleDeleteRangeMoveUpCommand(t,n,o){const r=_e(this._univerInstanceService,n);if(!r)return this._handleNull();const a=be(r,o);if(!a)return this._handleNull();const u=t.range,l=a.getMaxRows()-1,d=a.getMergeData(),c=[],m=[];d.forEach(w=>{const{startRow:y,startColumn:b,endColumn:T,endRow:U}=u;if(i.Rectangle.intersects({startRow:y,startColumn:b,endRow:l,endColumn:T},w)&&(c.push(w),i.Rectangle.contains({startRow:y,startColumn:b,endRow:l,endColumn:T},w))){const N=U-y+1,W=i.Rectangle.moveVertical(w,-N);m.push(W)}});const h={unitId:n,subUnitId:o,ranges:c},R=ue(this._injector,h),C={unitId:n,subUnitId:o,ranges:m},S=ge(this._injector,C),I=[{id:G.id,params:h}],v=[{id:j.id,params:C}],M=[{id:G.id,params:S}],p=[{id:j.id,params:R}];return{redos:v,undos:p,preRedos:I,preUndos:M}}_handleDeleteRangeMoveLeftCommand(t,n,o){const r=_e(this._univerInstanceService,n);if(!r)return this._handleNull();const a=be(r,o);if(!a)return this._handleNull();const u=t.range,l=a.getMaxColumns()-1,d=a.getMergeData(),c=[],m=[];d.forEach(I=>{const{startRow:v,endRow:M,startColumn:p,endColumn:w}=u;if(i.Rectangle.intersects({startRow:v,startColumn:p,endRow:M,endColumn:l},I)&&(c.push(I),i.Rectangle.contains({startRow:v,startColumn:p,endRow:M,endColumn:l},I))){const T=w-p+1;m.push({startRow:I.startRow,startColumn:I.startColumn-T,endRow:I.endRow,endColumn:I.endColumn-T})}});const h={unitId:n,subUnitId:o,ranges:c},R=ue(this._injector,h),C={unitId:n,subUnitId:o,ranges:m},S=ge(this._injector,C);return{preRedos:[{id:G.id,params:h}],redos:[{id:j.id,params:C}],undos:[{id:j.id,params:R}],preUndos:[{id:G.id,params:S}]}}_checkIsMergeCell(t){return!(t.startRow===t.endRow&&t.startColumn===t.endColumn)}_handleNull(){return{redos:[],undos:[]}}_commandExecutedListener(){this.disposeWithMe(this._commandService.onCommandExecuted(t=>{if(Zu.includes(t.id)){if(!t.params)return;const n=this._univerInstanceService.getUniverSheetInstance(t.params.unitId);if(!n)return;const o=n.getSheetBySheetId(t.params.subUnitId);if(!o)return;const{sourceRange:r,targetRange:a}=t.params,u=r.startColumn===a.startColumn&&r.endColumn===a.endColumn,l=u?r.endRow-r.startRow+1:r.endColumn-r.startColumn+1,d=u?r.startRow:r.startColumn,c=u?a.startRow:a.startColumn,m=o.getConfig().mergeData,h=[];m.forEach(I=>{let{startRow:v,endRow:M,startColumn:p,endColumn:w,rangeType:y}=I;i.Rectangle.intersects(I,r)||(u?d<v&&c>M?(v-=l,M-=l):d>M&&c<=v&&(v+=l,M+=l):d<p&&c>w?(p-=l,w-=l):d>w&&c<=p&&(p+=l,w+=l)),I.startRow===I.endRow&&I.startColumn===I.endColumn||h.push({startRow:v,endRow:M,startColumn:p,endColumn:w,rangeType:y})}),o.setMergeData(h),this.disposableCollection.dispose();const{unitId:R,subUnitId:C}=t.params,S=I=>this.refRangeHandle(I,R,C);h.forEach(I=>{this.disposableCollection.add(this._refRangeService.registerRefRange(I,S,R,C))})}if(Xu.includes(t.id)){const n=this._univerInstanceService.getUniverSheetInstance(t.params.unitId);if(!n)return;const o=n.getSheetBySheetId(t.params.subUnitId);if(!o)return;const r=o.getConfig().mergeData,a=t.params;if(!a)return;const{range:u}=a,l=t.id.includes("row"),d=t.id.includes("insert"),c=l?u.startRow:u.startColumn,m=l?u.endRow:u.endColumn,h=m-c+1,R=[];r.forEach(v=>{let{startRow:M,endRow:p,startColumn:w,endColumn:y,rangeType:b}=v;d?l?c<=M&&(M+=h,p+=h):c<=w&&(w+=h,y+=h):l?m<M&&(M-=h,p-=h):m<w&&(w-=h,y-=h),v.startRow===v.endRow&&v.startColumn===v.endColumn||R.push({startRow:M,endRow:p,startColumn:w,endColumn:y,rangeType:b})}),o.setMergeData(R),this.disposableCollection.dispose();const{unitId:C,subUnitId:S}=t.params,I=v=>this.refRangeHandle(v,C,S);R.forEach(v=>{this.disposableCollection.add(this._refRangeService.registerRefRange(v,I,C,S))})}}))}},g.MergeCellController=xu([Mt(0,i.Inject(i.ICommandService)),Mt(1,i.Inject(g.RefRangeService)),Mt(2,i.Inject(i.IUniverInstanceService)),Mt(3,i.Inject(i.Injector)),Mt(4,i.Inject(g.SheetInterceptorService)),Mt(5,i.Inject(g.SheetsSelectionsService))],g.MergeCellController);function _e(s,e){return e?s.getUniverSheetInstance(e):s.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET)}function be(s,e){return e?s.getSheetBySheetId(e):s.getActiveSheet()}function Qu(s,e){return e.some(t=>el(s,t))}function el(s,e){const{startRow:t,startColumn:n,endColumn:o,endRow:r}=e,a=s.getMatrixWithMergedCells(t,n,r,o);let u=!1;return a.forValue((l,d,c)=>{if(c&&(l!==t||d!==n)&&s.cellHasValue(c))return u=!0,!1}),u}function tl(s,e,t,n){const o=[],r=[],a=t.getSheetId();return n.forEach(u=>{const l=nl(t,u),d={unitId:e,subUnitId:a,cellValue:l.getData()},c=ce(s,d);o.push({id:F.id,params:c}),r.push({id:F.id,params:d})}),{undos:o,redos:r}}function nl(s,e){const{startRow:t,startColumn:n,endColumn:o,endRow:r}=e,a=s.getMatrixWithMergedCells(t,n,r,o,i.CellModeEnum.Raw),u=new i.ObjectMatrix;return a.forValue((l,d,c)=>{c&&(l!==t||d!==n)&&u.setValue(l,d,null)}),u}const Ft={type:i.CommandType.COMMAND,id:"sheet.command.add-worksheet-merge",handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=e.unitId,a=e.subUnitId,u=e.selections,l=Os(u,e.value),d=o.getUniverSheetInstance(r).getSheetBySheetId(a),c=[],m=[],h=Qu(d,l),R={unitId:r,subUnitId:a,ranges:l},C={unitId:r,subUnitId:a,ranges:l};c.push({id:G.id,params:R}),c.push({id:j.id,params:C});const S=ue(s,R),I=ge(s,C);if(m.push({id:G.id,params:I}),m.push({id:j.id,params:S}),h){const M=tl(s,r,d,l);c.unshift(...M.redos),m.push(...M.undos)}return i.sequenceExecute(c,t).result?(n.pushUndoRedo({unitID:r,undoMutations:m,redoMutations:c}),!0):!1}},sl={type:i.CommandType.COMMAND,id:"sheet.command.add-worksheet-merge-all",handler:async s=>{var d;const e=s.get(i.ICommandService),n=(d=s.get(g.SheetsSelectionsService).getCurrentSelections())==null?void 0:d.map(c=>c.range);if(!(n!=null&&n.length))return!1;const r=s.get(i.IUniverInstanceService).getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET);if(!r)return!1;const a=r.getActiveSheet();if(!a)return!1;const u=r.getUnitId(),l=a.getSheetId();return e.executeCommand(Ft.id,{selections:n,unitId:u,subUnitId:l})}},ol={type:i.CommandType.COMMAND,id:"sheet.command.add-worksheet-merge-vertical",handler:async s=>{var d;const e=s.get(i.ICommandService),n=(d=s.get(g.SheetsSelectionsService).getCurrentSelections())==null?void 0:d.map(c=>c.range);if(!(n!=null&&n.length))return!1;const r=s.get(i.IUniverInstanceService).getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET);if(!r)return!1;const a=r.getActiveSheet();if(!a)return!1;const u=r.getUnitId(),l=a.getSheetId();return e.executeCommand(Ft.id,{value:i.Dimension.COLUMNS,selections:n,unitId:u,subUnitId:l})}},rl={type:i.CommandType.COMMAND,id:"sheet.command.add-worksheet-merge-horizontal",handler:async s=>{var d;const e=s.get(i.ICommandService),n=(d=s.get(g.SheetsSelectionsService).getCurrentSelections())==null?void 0:d.map(c=>c.range);if(!(n!=null&&n.length))return!1;const r=s.get(i.IUniverInstanceService).getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET);if(!r)return!1;const a=r.getActiveSheet();if(!a)return!1;const u=r.getUnitId(),l=a.getSheetId();return e.executeCommand(Ft.id,{value:i.Dimension.ROWS,selections:n,unitId:u,subUnitId:l})}};function il(s,e,t,n,o){const r=s.get(i.IUniverInstanceService),a=P(r,{unitId:e,subUnitId:t});if(!a)return;const{worksheet:u}=a;if(u.getMergeData().some(m=>n.some(h=>i.Rectangle.intersects(h,m))))throw new Error("The ranges to be merged overlap with the existing merged cells");s.get(i.ICommandService).executeCommand(Ft.id,{unitId:e,subUnitId:t,selections:n,defaultMerge:o})}class ke{constructor(){f(this,"_model",new Map);f(this,"_ruleChange",new O.Subject);f(this,"_ruleRefresh",new O.Subject);f(this,"_resetOrder",new O.Subject);f(this,"ruleChange$",this._ruleChange.asObservable());f(this,"ruleRefresh$",this._ruleRefresh.asObservable());f(this,"resetOrder$",this._resetOrder.asObservable());f(this,"_worksheetRuleInitStateChange",new O.BehaviorSubject(!1));f(this,"worksheetRuleInitStateChange$",this._worksheetRuleInitStateChange.asObservable())}changeRuleInitState(e){this._worksheetRuleInitStateChange.next(e)}getSheetRuleInitState(){return this._worksheetRuleInitStateChange.value}addRule(e,t){this._ensureSubUnitMap(e).set(t.subUnitId,t),this._ruleChange.next({unitId:e,rule:t,type:"add",subUnitId:t.subUnitId})}deleteRule(e,t){var o,r,a;const n=(r=(o=this._model)==null?void 0:o.get(e))==null?void 0:r.get(t);n&&((a=this._model.get(e))==null||a.delete(t),this._ruleChange.next({unitId:e,rule:n,type:"delete",subUnitId:t}))}setRule(e,t,n){var r,a;const o=this.getRule(e,t);o&&((a=(r=this._model)==null?void 0:r.get(e))==null||a.set(t,n),this._ruleChange.next({unitId:e,oldRule:o,rule:n,type:"set",subUnitId:t}))}getRule(e,t){var n,o;return(o=(n=this._model)==null?void 0:n.get(e))==null?void 0:o.get(t)}toObject(){const e={};return[...this._model.keys()].forEach(n=>{const o=this._model.get(n);o!=null&&o.size&&(e[n]=[],[...o.keys()].forEach(a=>{const u=o.get(a);u&&e[n].push(u)}))}),e}fromObject(e){const t=new Map;Object.keys(e).forEach(n=>{const o=e[n];if(o!=null&&o.length){const r=new Map;o.forEach(a=>{r.set(a.subUnitId,a)}),t.set(n,r)}}),this._model=t}deleteUnitModel(e){this._model.delete(e)}_ensureSubUnitMap(e){let t=this._model.get(e);return t||(t=new Map,this._model.set(e,t)),t}ruleRefresh(e){this._ruleRefresh.next(e)}resetOrder(){this._resetOrder.next(Math.random())}getTargetByPermissionId(e,t){const n=this._model.get(e);if(!n)return null;for(const[o,r]of n)if(r.permissionId===t)return[e,o]}}const Fe={id:"sheet.mutation.add-worksheet-protection",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=s.get(ke),{unitId:n,rule:o}=e;return t.addRule(n,o),!0}},tt={id:"sheet.mutation.delete-worksheet-protection",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=s.get(ke),{unitId:n,subUnitId:o}=e;return t.deleteRule(n,o),!0}},Tr={type:i.CommandType.COMMAND,id:"sheet.command.add-worksheet-protection",async handler(s,e){if(!e)return!1;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),{rule:o,unitId:r}=e,a=o.subUnitId;if(await t.executeCommand(Fe.id,{unitId:r,rule:o,subUnitId:o.subUnitId})){const l=[{id:Fe.id,params:{unitId:r,rule:o,subUnitId:o.subUnitId}}],d=[{id:tt.id,params:{unitId:r,subUnitId:a}}];n.pushUndoRedo({unitID:r,redoMutations:l,undoMutations:d})}return!0}},Ur={type:i.CommandType.COMMAND,id:"sheet.command.set-worksheet-range-theme-style",handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),{unitId:o}=e,r=uo(s,e);return t.syncExecuteCommand(rt.id,e)?(n.pushUndoRedo({unitID:o,undoMutations:[{id:it.id,params:r}],redoMutations:[{id:rt.id,params:e}]}),!0):!1}},Pr={type:i.CommandType.COMMAND,id:"sheet.command.append-row",handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),{unitId:o,subUnitId:r,cellValue:a,insertRowNums:u,insertColumnNums:l,maxRows:d,maxColumns:c}=e,m={unitId:o,subUnitId:r,cellValue:a},h=ce(s,m),R=[{id:F.id,params:m}],C=[{id:F.id,params:h}];if(u){const I={unitId:o,subUnitId:r,range:{startRow:d,endRow:d,startColumn:0,endColumn:c-1}},v=en(s,I);R.unshift({id:re.id,params:I}),C.push({id:ae.id,params:v})}if(l){const I={unitId:o,subUnitId:r,range:{startRow:0,endRow:d-1,startColumn:c,endColumn:c-1+l}},v=Nt(s,I);R.unshift({id:ie.id,params:I}),C.push({id:ne.id,params:v})}return i.sequenceExecute(R,t).result?(n.pushUndoRedo({unitID:o,undoMutations:C,redoMutations:R}),!0):!1}},fn={id:"sheet.command.clear-selection-content",type:i.CommandType.COMMAND,handler:(s,e)=>{var p;const t=s.get(i.IUniverInstanceService),n=s.get(i.ICommandService),o=s.get(g.SheetsSelectionsService),r=s.get(i.IUndoRedoService),a=s.get(g.SheetInterceptorService),u=t.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET);if(!u)return!1;const l=(e==null?void 0:e.unitId)||u.getUnitId(),d=u.getActiveSheet();if(!d)return!1;const c=(e==null?void 0:e.subUnitId)||d.getSheetId(),m=(e==null?void 0:e.ranges)||((p=o.getCurrentSelections())==null?void 0:p.map(w=>w.range));if(!(m!=null&&m.length))return!1;const h=Dt(m,s,l,c),R={subUnitId:c,unitId:l,cellValue:ko(h)},C=ce(s,R),S=a.onCommandExecute({id:fn.id}),I=[{id:F.id,params:R},...S.redos],v=[...S.undos,{id:F.id,params:C}];return i.sequenceExecute(I,n).result?(r.pushUndoRedo({unitID:l,undoMutations:v,redoMutations:I}),!0):!1}},Ds=(s,e)=>({subUnitId:e.sheet.id,unitId:e.unitId,subUnitName:e.sheet.name}),yt={id:"sheet.mutation.insert-sheet",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=s.get(i.IUniverInstanceService),{sheet:n,index:o,unitId:r,styles:a}=e,u=t.getUniverSheetInstance(r);return u?(a&&u.addStyles(a),u.addWorksheet(n.id,o,n)):!1}},As={type:i.CommandType.COMMAND,id:"sheet.command.copy-sheet",handler:(s,e)=>{var w,y;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=s.get(g.SheetInterceptorService),a=s.get(i.LocaleService),u=P(o,e);if(!u)return!1;const{workbook:l,worksheet:d,unitId:c,subUnitId:m}=u,h=i.Tools.deepClone(d.getConfig());h.name=al(l,a,h.name),h.id=i.generateRandomId();const C={index:l.getSheetIndex(d)+1,sheet:h,unitId:c},S=Ds(s,C),I=r.onCommandExecute({id:As.id,params:{unitId:c,subUnitId:m,targetSubUnitId:h.id}}),v=[...(w=I.preRedos)!=null?w:[],{id:yt.id,params:C},...I.redos],M=[...(y=I.preUndos)!=null?y:[],{id:Xe.id,params:S},...I.undos];return i.sequenceExecute(v,t).result?(n.pushUndoRedo({unitID:c,undoMutations:M,redoMutations:v}),!0):!1}};function al(s,e,t){let n=`${t} ${e.t("sheets.tabs.sheetCopy","")}`,o=2;for(;s.checkSheetName(n);)n=`${t} ${e.t("sheets.tabs.sheetCopy",`${o}`)}`,o++;return n}const kr={type:i.CommandType.COMMAND,id:"sheet.command.delete-range-protection",async handler(s,e){if(!e)return!1;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),{unitId:o,subUnitId:r,rule:a}=e,u={unitId:o,subUnitId:r,ruleIds:[a.id]};return await t.executeCommand(Te.id,u)&&n.pushUndoRedo({unitID:o,redoMutations:[{id:Te.id,params:u}],undoMutations:[{id:Ce.id,params:{unitId:o,subUnitId:r,rules:[a]}}]}),!0}},Nr={type:i.CommandType.COMMAND,id:"sheet.command.delete-worksheet-protection",handler(s,e){if(!e)return!1;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),{rule:o,unitId:r,subUnitId:a}=e;t.executeCommand(tt.id,{unitId:r,subUnitId:a});const u=[{id:tt.id,params:{unitId:r,subUnitId:a}}],l=[{id:Fe.id,params:{unitId:r,rule:o,subUnitId:a}}];return n.pushUndoRedo({unitID:r,redoMutations:u,undoMutations:l}),!0}},Or={type:i.CommandType.COMMAND,id:"sheet.command.remove-worksheet-range-theme-style",handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),{unitId:o}=e,r=lo(s,e);return t.syncExecuteCommand(it.id,e)?(n.pushUndoRedo({unitID:o,undoMutations:[{id:rt.id,params:r}],redoMutations:[{id:it.id,params:e}]}),!0):!1}},Dr={id:"sheet.command.insert-defined-name",type:i.CommandType.COMMAND,handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService);if(!e)return!1;const o={...e};return t.syncExecuteCommand(J.SetDefinedNameMutation.id,o)?(n.pushUndoRedo({unitID:e.unitId,undoMutations:[{id:J.RemoveDefinedNameMutation.id,params:o}],redoMutations:[{id:J.SetDefinedNameMutation.id,params:o}]}),!0):!1}},Ar={id:"sheet.command.insert-sheet",type:i.CommandType.COMMAND,handler:(s,e)=>{var I;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=s.get(i.LocaleService),a=Bn(o,{unitId:e==null?void 0:e.unitId});if(!a)return!1;const{unitId:u,workbook:l}=a;let d=l.getSheets().length;const c=e==null?void 0:e.sheet,m=c==null?void 0:c.id,h=i.mergeWorksheetSnapshotWithDefault(c||{});e?(d=(I=e.index)!=null?I:d,h.id=m||i.generateRandomId(),h.name=(c==null?void 0:c.name)||l.generateNewSheetName(`${r.t("sheets.tabs.sheet")}`)):(h.id=i.generateRandomId(),h.name=l.generateNewSheetName(`${r.t("sheets.tabs.sheet")}`));const R={index:d,sheet:h,unitId:u},C=Ds(s,R);return t.syncExecuteCommand(yt.id,R)?(n.pushUndoRedo({unitID:u,undoMutations:[{id:Xe.id,params:C}],redoMutations:[{id:yt.id,params:R}]}),!0):!1}},_t={id:"sheet.mutation.register-worksheet-range-theme-style",type:i.CommandType.MUTATION,handler:(s,e)=>{const{unitId:t,rangeThemeStyleJson:n,themeName:o}=e,r=s.get(i.IUniverInstanceService),a=P(r),u=s.get(g.SheetRangeThemeModel);if(!a)return!1;const l=new We(o,n);return u.registerRangeThemeStyle(t,l),!0}},In={id:"sheet.mutation.unregister-worksheet-range-theme-style",type:i.CommandType.MUTATION,handler:(s,e)=>{const{unitId:t,themeName:n}=e,o=s.get(i.IUniverInstanceService),r=P(o),a=s.get(g.SheetRangeThemeModel);return r?(a.unregisterRangeThemeStyle(t,n),!0):!1}},Wr={id:"sheet.command.register-worksheet-range-theme-style",type:i.CommandType.COMMAND,handler:(s,e)=>{if(!e)return!1;const{unitId:t,rangeThemeStyle:n}=e,o=s.get(i.IUniverInstanceService),r=s.get(i.ICommandService),a=s.get(i.IUndoRedoService);if(!P(o))return!1;const l={unitId:t,themeName:n.getName(),rangeThemeStyleJson:n.toJson()},d={unitId:t,themeName:n.getName()};return r.syncExecuteCommand(_t.id,l)&&a.pushUndoRedo({unitID:t,undoMutations:[{id:In.id,params:d}],redoMutations:[{id:_t.id,params:l}]}),!0}},Ws={id:"sheet.command.remove-defined-name",type:i.CommandType.COMMAND,handler:(s,e)=>{var c,m;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(g.SheetInterceptorService);if(!e)return!1;const r={...e},a=o.onCommandExecute({id:Ws.id,params:e}),u=[...(c=a.preRedos)!=null?c:[],{id:J.RemoveDefinedNameMutation.id,params:r},...a.redos],l=[...(m=a.preUndos)!=null?m:[],{id:J.SetDefinedNameMutation.id,params:r},...a.undos];return i.sequenceExecute(u,t)?(n.pushUndoRedo({unitID:e.unitId,undoMutations:l.filter(Boolean),redoMutations:u.filter(Boolean)}),!0):!1}},vn={id:"sheet.command.remove-sheet",type:i.CommandType.COMMAND,handler:(s,e)=>{var v,M;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=s.get(g.SheetInterceptorService),a=P(o,e);if(!a)return!1;const{unitId:u,subUnitId:l,workbook:d,worksheet:c}=a;if(d.getSheets().length<=1)return!1;const m={subUnitId:l,unitId:u,subUnitName:c.getName()},h=ar(s,m),R=r.onCommandExecute({id:vn.id,params:{unitId:u,subUnitId:l}}),C=[...(v=R.preRedos)!=null?v:[],{id:Xe.id,params:m},...R.redos],S=[...(M=R.preUndos)!=null?M:[],{id:yt.id,params:h},...R.undos];return i.sequenceExecute(C,t).result?(n.pushUndoRedo({unitID:u,undoMutations:S,redoMutations:C}),!0):!1}},Vr={type:i.CommandType.COMMAND,id:"sheet.command.remove-worksheet-merge",handler:(s,e)=>{var N;const t=s.get(g.SheetsSelectionsService),n=s.get(i.ICommandService),o=s.get(i.IUndoRedoService),r=s.get(i.IUniverInstanceService),a=(e==null?void 0:e.ranges)||((N=t.getCurrentSelections())==null?void 0:N.map(W=>W.range));if(!(a!=null&&a.length))return!1;const u=P(r);if(!u)return!1;const{subUnitId:l,unitId:d,worksheet:c}=u,m={unitId:d,subUnitId:l,ranges:a},R=c.getConfig().mergeData.filter(W=>a.some(V=>i.Rectangle.intersects(V,W)));if(!R.length)return!1;const C=ue(s,m),S=t.getCurrentSelections();if(!(S!=null&&S.length))return!1;const I=i.Tools.deepClone(S),v=i.Tools.deepClone(S),M=v[v.length-1],{startRow:p,startColumn:w}=M.range;M.primary={startRow:p,startColumn:w,endRow:p,endColumn:w,actualRow:p,actualColumn:w,isMerged:!1,isMergedMainCell:!1};const y=ul(c,R),b={unitId:d,subUnitId:l,cellValue:y.redoParams.getMatrix()},T={unitId:d,subUnitId:l,cellValue:y.undoParams.getMatrix()},U=[{id:G.id,params:C},{id:F.id,params:b},{id:q.id,params:{selections:v}}],k=[{id:j.id,params:C},{id:F.id,params:T},{id:q.id,params:{selections:I}}];return i.sequenceExecute(U,n)?(o.pushUndoRedo({unitID:d,undoMutations:k,redoMutations:U}),!0):!1}};function ul(s,e){const t=new i.ObjectMatrix,n=new i.ObjectMatrix;return e.forEach(o=>{const{startRow:r,startColumn:a,endColumn:u,endRow:l}=o,d=s.getCellMatrix().getValue(r,a);if(d!=null&&d.s)for(let c=r;c<=l;c++)for(let m=a;m<=u;m++)(c!==r||m!==a)&&(t.setValue(c,m,{s:d.s}),n.setValue(c,m,null))}),{redoParams:t,undoParams:n}}class nt{constructor(){f(this,"_borderInfo",{type:i.BorderType.ALL,color:"#000000",style:i.BorderStyleTypes.THIN,activeBorderType:!1});f(this,"_borderInfo$",new O.BehaviorSubject(this._borderInfo));f(this,"borderInfo$",this._borderInfo$.asObservable())}dispose(){this._borderInfo$.complete()}setType(e){this._borderInfo.type=e,this.setActiveBorderType(!0),this._refresh()}setColor(e){this._borderInfo.color=e,this._refresh()}setStyle(e){this._borderInfo.style=e,this._refresh()}setActiveBorderType(e){this._borderInfo.activeBorderType=e}getBorderInfo(){return this._borderInfo}_refresh(){this._borderInfo$.next(this._borderInfo)}}function pn(s,e){const{startRow:t,startColumn:n,endRow:o,endColumn:r}=s;for(let a=t;a<=o;a++)for(let u=n;u<=r;u++)e(a,u)}const Vs=(s,e,t,n)=>{const{mr:o,worksheet:r}=s;e.startRow<0||e.startColumn<0||pn(e,(a,u)=>{var c,m;const l=r.getMergedCell(a,u);let d=t;if(l&&(t.bc_tr||t.ml_tr||t.bl_tr||t.tl_mr||t.tl_bc||t.tl_br)){if(n){const h=i.Tools.deepClone((c=o.getValue(l.startRow,l.startColumn))==null?void 0:c.s);d=h!=null&&h.bd?Object.assign(h.bd,t):t}o.setValue(l.startRow,l.startColumn,{s:{bd:d}})}else{if(n){const h=i.Tools.deepClone((m=o.getValue(a,u))==null?void 0:m.s);d=h!=null&&h.bd?Object.assign(h.bd,t):t}o.setValue(a,u,{s:{bd:d}})}})},ll=s=>{const e={startRow:s.startRow-1,startColumn:s.startColumn,endRow:s.startRow-1,endColumn:s.endColumn},t={startRow:s.startRow,startColumn:s.startColumn-1,endRow:s.endRow,endColumn:s.startColumn-1},n={startRow:s.endRow+1,startColumn:s.startColumn,endRow:s.endRow+1,endColumn:s.endColumn},o={startRow:s.startRow,startColumn:s.endColumn+1,endRow:s.endRow,endColumn:s.endColumn+1},r={startRow:s.startRow,startColumn:s.startColumn,endRow:s.startRow,endColumn:s.endColumn},a={startRow:s.startRow,startColumn:s.startColumn,endRow:s.endRow,endColumn:s.startColumn},u={startRow:s.endRow,startColumn:s.startColumn,endRow:s.endRow,endColumn:s.endColumn},l={startRow:s.startRow,startColumn:s.endColumn,endRow:s.endRow,endColumn:s.endColumn};return{topRangeOut:e,leftRangeOut:t,bottomRangeOut:n,rightRangeOut:o,topRange:r,leftRange:a,bottomRange:u,rightRange:l}};function dl(s,e,t){const{style:n,color:o,type:r}=s.getBorderInfo(),a=r===i.BorderType.TOP||r===i.BorderType.ALL||r===i.BorderType.OUTSIDE,u=r===i.BorderType.LEFT||r===i.BorderType.ALL||r===i.BorderType.OUTSIDE,l=r===i.BorderType.BOTTOM||r===i.BorderType.ALL||r===i.BorderType.OUTSIDE,d=r===i.BorderType.RIGHT||r===i.BorderType.ALL||r===i.BorderType.OUTSIDE,c=r===i.BorderType.VERTICAL||r===i.BorderType.ALL||r===i.BorderType.INSIDE,m=r===i.BorderType.HORIZONTAL||r===i.BorderType.ALL||r===i.BorderType.INSIDE,h=r.indexOf("tlbr")>-1,R=r.indexOf("tlbc")>-1,C=r.indexOf("tlmr")>-1,S=r.indexOf("bltr")>-1,I=r.indexOf("mltr")>-1,v=r.indexOf("bctr")>-1,M=t[0],{topRangeOut:p,leftRangeOut:w,bottomRangeOut:y,rightRangeOut:b,topRange:T,leftRange:U,bottomRange:k,rightRange:E}=ll(M),N=new i.ObjectMatrix,{worksheet:W,unitId:V,subUnitId:$}=e;return{worksheet:W,unitId:V,subUnitId:$,style:n,color:o,type:r,top:a,left:u,right:d,bottom:l,vertical:c,horizontal:m,tl_br:h,tl_bc:R,tl_mr:C,bl_tr:S,ml_tr:I,bc_tr:v,topRangeOut:p,leftRangeOut:w,bottomRangeOut:y,rightRangeOut:b,topRange:T,leftRange:U,bottomRange:k,rightRange:E,range:M,mr:N,borderStyle:{s:n,cl:{rgb:o}}}}const cl=s=>{const{range:e,mr:t,borderStyle:n,vertical:o,horizontal:r,worksheet:a}=s;o&&pn(e,(u,l)=>{var c,m,h;const d=a.getMergedCell(u,l);if(d){const R=(c=t.getValue(d.startRow,d.startColumn))==null?void 0:c.s;d.startColumn!==e.startColumn&&t.setValue(u,l,{s:{bd:R!=null&&R.bd?Object.assign(R.bd,{l:i.Tools.deepClone(n)}):{l:i.Tools.deepClone(n)}}})}else{if(l!==e.endColumn){const R=(m=t.getValue(u,l))==null?void 0:m.s;t.setValue(u,l,{s:{bd:R!=null&&R.bd?Object.assign(R.bd,{r:i.Tools.deepClone(n)}):{r:i.Tools.deepClone(n)}}})}if(l!==e.startColumn){const R=(h=t.getValue(u,l))==null?void 0:h.s;t.setValue(u,l,{s:{bd:R!=null&&R.bd?Object.assign(R.bd,{l:i.Tools.deepClone(n)}):{l:i.Tools.deepClone(n)}}})}}}),r&&pn(e,(u,l)=>{var c,m,h;const d=a.getMergedCell(u,l);if(d){const R=(c=t.getValue(d.startRow,d.startColumn))==null?void 0:c.s;d.startRow!==e.startRow&&t.setValue(u,l,{s:{bd:R!=null&&R.bd?Object.assign(R.bd,{t:i.Tools.deepClone(n)}):{t:i.Tools.deepClone(n)}}})}else{if(u!==e.endRow){const R=(m=t.getValue(u,l))==null?void 0:m.s;t.setValue(u,l,{s:{bd:R!=null&&R.bd?Object.assign(R.bd,{b:i.Tools.deepClone(n)}):{b:i.Tools.deepClone(n)}}})}if(u!==e.startRow){const R=(h=t.getValue(u,l))==null?void 0:h.s;t.setValue(u,l,{s:{bd:R!=null&&R.bd?Object.assign(R.bd,{t:i.Tools.deepClone(n)}):{t:i.Tools.deepClone(n)}}})}}})};function ml(s){const{borderStyle:e,tl_br:t,tl_bc:n,tl_mr:o,bl_tr:r,ml_tr:a,bc_tr:u}=s,l=(d,c,m)=>{Vs(s,d,c,m)};t&&l(s.range,{tl_br:i.Tools.deepClone(e)},!0),n&&l(s.range,{tl_bc:i.Tools.deepClone(e)},!0),o&&l(s.range,{tl_mr:i.Tools.deepClone(e)},!0),r&&l(s.range,{bl_tr:i.Tools.deepClone(e)},!0),a&&l(s.range,{ml_tr:i.Tools.deepClone(e)},!0),u&&l(s.range,{bc_tr:i.Tools.deepClone(e)},!0)}const hl=s=>{const{top:e,left:t,right:n,bottom:o,borderStyle:r,bottomRange:a,topRange:u,leftRange:l,rightRange:d,bottomRangeOut:c,topRangeOut:m,leftRangeOut:h,rightRangeOut:R}=s,C=(S,I,v)=>{Vs(s,S,I,v)};e&&(C(m,{b:null}),C(u,{t:i.Tools.deepClone(r)},!0)),o&&(C(c,{t:null}),C(a,{b:i.Tools.deepClone(r)},!0)),t&&(C(h,{r:null}),C(l,{l:i.Tools.deepClone(r)},!0)),n&&(C(R,{l:null}),C(d,{r:i.Tools.deepClone(r)},!0))},gl=s=>{const{range:e,worksheet:t,mr:n,top:o,bottom:r,left:a,right:u,vertical:l,horizontal:d,tl_br:c,tl_bc:m,tl_mr:h,bl_tr:R,ml_tr:C,bc_tr:S,topRange:I,bottomRange:v,leftRange:M,rightRange:p,topRangeOut:w,bottomRangeOut:y,leftRangeOut:b,rightRangeOut:T}=s,U=(k,E,N)=>{Vs(s,k,E,N)};!o&&!r&&!a&&!u&&!l&&!d&&!c&&!m&&!h&&!R&&!C&&!S&&(pn(e,(k,E)=>{var W,V,$,L,Y,z,K,oe;const N=t.getMergedCell(k,E);if(N){if(N.endColumn!==e.endColumn){const H=(W=n.getValue(N.startRow,N.startColumn))==null?void 0:W.s;n.setValue(k,E,{s:{bd:H!=null&&H.bd?Object.assign(H.bd,{r:null}):{r:null}}})}if(N.startColumn!==e.startColumn){const H=(V=n.getValue(N.startRow,N.startColumn))==null?void 0:V.s;n.setValue(k,E,{s:{bd:H!=null&&H.bd?Object.assign(H.bd,{l:null}):{l:null}}})}if(N.endRow!==e.endRow){const H=($=n.getValue(N.startRow,N.startColumn))==null?void 0:$.s;n.setValue(k,E,{s:{bd:H!=null&&H.bd?Object.assign(H.bd,{b:null}):{b:null}}})}if(N.startRow!==e.startRow){const H=(L=n.getValue(N.startRow,N.startColumn))==null?void 0:L.s;n.setValue(k,E,{s:{bd:H!=null&&H.bd?Object.assign(H.bd,{t:null}):{t:null}}})}}else{if(E!==e.endColumn){const H=(Y=n.getValue(k,E))==null?void 0:Y.s;n.setValue(k,E,{s:{bd:H!=null&&H.bd?Object.assign(H.bd,{r:null}):{r:null}}})}if(E!==e.startColumn){const H=(z=n.getValue(k,E))==null?void 0:z.s;n.setValue(k,E,{s:{bd:H!=null&&H.bd?Object.assign(H.bd,{l:null}):{l:null}}})}if(k!==e.endRow){const H=(K=n.getValue(k,E))==null?void 0:K.s;n.setValue(k,E,{s:{bd:H!=null&&H.bd?Object.assign(H.bd,{b:null}):{b:null}}})}if(k!==e.startRow){const H=(oe=n.getValue(k,E))==null?void 0:oe.s;n.setValue(k,E,{s:{bd:H!=null&&H.bd?Object.assign(H.bd,{t:null}):{t:null}}})}}}),U(w,{b:null}),U(I,{t:null},!0),U(y,{t:null}),U(v,{b:null},!0),U(b,{r:null}),U(M,{l:null},!0),U(T,{l:null}),U(p,{r:null},!0),U(e,{tl_br:null},!0),U(e,{tl_bc:null},!0),U(e,{tl_mr:null},!0),U(e,{bl_tr:null},!0),U(e,{ml_tr:null},!0),U(e,{bc_tr:null},!0))},bt={id:"sheet.command.set-border",type:i.CommandType.COMMAND,handler:(s,e)=>{var v;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=s.get(g.SheetsSelectionsService),a=s.get(nt),u=P(o,e);if(!u)return!1;const l=(e==null?void 0:e.ranges)||((v=r.getCurrentSelections())==null?void 0:v.map(M=>M.range));if(!(l!=null&&l.length))return!1;const{activeBorderType:d}=a.getBorderInfo();if(!d)return!1;const c=dl(a,u,l);cl(c),hl(c),ml(c),gl(c);const{unitId:m,subUnitId:h,mr:R}=c,C={unitId:m,subUnitId:h,cellValue:R.getData()},S=ce(s,C);return t.syncExecuteCommand(F.id,C)?(n.pushUndoRedo({unitID:m,undoMutations:[{id:F.id,params:S}],redoMutations:[{id:F.id,params:C}]}),!0):!1}},$r={id:"sheet.command.set-border-position",type:i.CommandType.COMMAND,handler:(s,e)=>{if(!e.value)return!1;const t=s.get(i.ICommandService);return s.get(nt).setType(e.value),t.syncExecuteCommand(bt.id)}},Lr={id:"sheet.command.set-border-style",type:i.CommandType.COMMAND,handler:(s,e)=>{const t=s.get(i.ICommandService);return s.get(nt).setStyle(e.value),t.syncExecuteCommand(bt.id)}},Br={id:"sheet.command.set-border-color",type:i.CommandType.COMMAND,handler:(s,e)=>{const t=s.get(i.ICommandService);return s.get(nt).setColor(e.value),t.syncExecuteCommand(bt.id)}},Hr={id:"sheet.command.set-border-basic",type:i.CommandType.COMMAND,handler:(s,e)=>{const{unitId:t,subUnitId:n,value:o,ranges:r}=e,{type:a,color:u,style:l}=o,d=s.get(i.ICommandService),c=s.get(nt);return c.setType(a),u&&c.setColor(u),c.setStyle(l),d.syncExecuteCommand(bt.id,{unitId:t,subUnitId:n,ranges:r})}},Fr={type:i.CommandType.COMMAND,id:"sheet.command.set-col-data",handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=P(o,e);if(!r)return!1;const{columnData:a}=e,{unitId:u,subUnitId:l,worksheet:d}=r,c={subUnitId:l,unitId:u,columnData:a},m=go(c,d);return t.syncExecuteCommand(at.id,c)?(n.pushUndoRedo({unitID:u,undoMutations:[{id:at.id,params:m}],redoMutations:[{id:at.id,params:c}]}),!0):!1}},Et={type:i.CommandType.COMMAND,id:"sheet.command.set-col-visible-on-cols",handler:(s,e)=>{var v,M;const{unitId:t,subUnitId:n,ranges:o}=e,r=s.get(g.SheetInterceptorService),a=s.get(i.ICommandService),u=s.get(i.IUniverInstanceService),l=P(u,{unitId:t,subUnitId:n});if(!l)return!1;const{worksheet:d}=l,c={unitId:t,subUnitId:n,ranges:o},m={unitId:t,subUnitId:n,reveal:!0,selections:o.map(p=>({range:p,primary:se(p,d),style:null}))},h=Ca(s,c),R={unitId:t,subUnitId:n,selections:jr(o).map(p=>({range:p,primary:se(p,d),style:null}))},C=i.sequenceExecute([{id:lt.id,params:c},{id:q.id,params:m}],a),S=r.onCommandExecute({id:Et.id,params:e}),I=i.sequenceExecute([...S.redos],a);if(C.result&&I.result){const p=r.afterCommandExecute({id:Et.id,params:e});return i.sequenceExecute(p.redos,a),s.get(i.IUndoRedoService).pushUndoRedo({unitID:t,undoMutations:[{id:ut.id,params:h},{id:q.id,params:R},...(v=S.undos)!=null?v:[],...p.undos],redoMutations:[...(M=S.preRedos)!=null?M:[],{id:lt.id,params:c},{id:q.id,params:m},...S.redos,...p.redos]}),!0}return!0}},$s={type:i.CommandType.COMMAND,id:"sheet.command.set-selected-cols-visible",handler:s=>{var d;const e=s.get(g.SheetsSelectionsService),t=s.get(i.ICommandService),n=(d=e.getCurrentSelections())==null?void 0:d.map(c=>c.range).filter(c=>c.rangeType===i.RANGE_TYPE.COLUMN);if(!(n!=null&&n.length))return!1;const o=P(s.get(i.IUniverInstanceService));if(!o)return!1;const{worksheet:r,unitId:a,subUnitId:u}=o,l=n.map(c=>r.getHiddenCols(c.startColumn,c.endColumn)).flat();return t.executeCommand(Et.id,{unitId:a,subUnitId:u,ranges:l})}},wn={type:i.CommandType.COMMAND,id:"sheet.command.set-col-hidden",handler:(s,e)=>{var M,p,w,y;const t=s.get(g.SheetsSelectionsService),n=s.get(g.SheetInterceptorService),o=s.get(i.IUniverInstanceService),r=s.get(i.ICommandService);let a=(M=e==null?void 0:e.ranges)!=null&&M.length?e.ranges:(p=t.getCurrentSelections())==null?void 0:p.map(b=>b.range).filter(b=>b.rangeType===i.RANGE_TYPE.COLUMN);if(!(a!=null&&a.length))return!1;const u=P(o,e);if(!u)return!1;const{worksheet:l,unitId:d,subUnitId:c}=u;a=Rl(u.worksheet,a);const m={unitId:d,subUnitId:c,ranges:a},h={unitId:d,subUnitId:c,selections:jr(a).map(b=>({range:b,primary:se(b,l),style:null}))},R=Ra(s,m),C={unitId:d,subUnitId:c,reveal:!0,selections:a.map(b=>({range:b,primary:se(b,l),style:null}))},S=i.sequenceExecute([{id:ut.id,params:m},{id:q.id,params:h}],r),I=n.onCommandExecute({id:wn.id,params:m}),v=i.sequenceExecute([...I.redos],r);if(S.result&&v.result){const b=n.afterCommandExecute({id:wn.id,params:m});return i.sequenceExecute(b.redos,r),s.get(i.IUndoRedoService).pushUndoRedo({unitID:d,undoMutations:[{id:lt.id,params:R},{id:q.id,params:C},...(w=I.undos)!=null?w:[],...b.undos],redoMutations:[...(y=I.preRedos)!=null?y:[],{id:ut.id,params:m},{id:q.id,params:h},...I.redos,...b.redos]}),!0}return!1}};function Rl(s,e){const t=s.getRowCount()-1,n=s.getHiddenCols(),o=[];return e.forEach(r=>{const a=n.filter(u=>u.startColumn>=r.startColumn&&u.endColumn<=r.endColumn);if(a.length){let u=r.startColumn;a.forEach(l=>{l.startColumn>u&&(o.push({startColumn:u,endColumn:l.startColumn-1,startRow:0,endRow:t}),u=l.endColumn+1)}),u<=r.endColumn&&o.push({startColumn:u,endColumn:r.endColumn,startRow:0,endRow:t})}else o.push(r)}),o}function jr(s){return Cl(s).map(t=>{const n=t.startColumn===0?t.endColumn+1:t.startColumn-1;return{...t,startColumn:n,endColumn:n}})}function Cl(s){const e=[];let t;return s.sort((n,o)=>n.startColumn-o.startColumn).forEach(n=>{if(!t){t=n;return}t.endColumn===n.startColumn-1?t.endColumn=n.endColumn:(e.push(t),t=n)}),e.push(t),e}const Ls={id:"sheet.command.set-defined-name",type:i.CommandType.COMMAND,handler:(s,e)=>{var m,h;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(g.SheetInterceptorService);if(!e)return!1;const r={...e},a=J.SetDefinedNameMutationFactory(s,e),u=o.onCommandExecute({id:Ls.id,params:e}),l=[...(m=u.preRedos)!=null?m:[],{id:J.RemoveDefinedNameMutation.id,params:a},{id:J.SetDefinedNameMutation.id,params:r},...u.redos],d=[...(h=u.preUndos)!=null?h:[],{id:J.RemoveDefinedNameMutation.id,params:r},{id:J.SetDefinedNameMutation.id,params:a},...u.undos];return i.sequenceExecute(l,t)?(n.pushUndoRedo({unitID:e.unitId,undoMutations:d.filter(Boolean),redoMutations:l.filter(Boolean)}),!0):!1}},Bs=(s,e)=>{const n=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(n==null)throw new Error("universheet is null error!");const o=n.getSheetBySheetId(e.subUnitId);if(o==null)throw new Error("worksheet is null error!");const a=o.getConfig().freeze;return{unitId:e.unitId,subUnitId:e.subUnitId,...a}},Ne={id:"sheet.mutation.set-frozen",type:i.CommandType.MUTATION,handler:(s,e)=>{const n=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(n==null)throw new Error("universheet is null error!");const o=n.getSheetBySheetId(e.subUnitId);if(!o)return!1;const r=o.getConfig(),{startRow:a,startColumn:u,ySplit:l,xSplit:d}=e;return r.freeze={startRow:a,startColumn:u,ySplit:l,xSplit:d},!0}},Gr={type:i.CommandType.COMMAND,id:"sheet.command.set-frozen",handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=P(o,{unitId:e.unitId,subUnitId:e.subUnitId});if(!r)return!1;const{unitId:a,subUnitId:u,worksheet:l}=r,{startColumn:d,startRow:c,xSplit:m,ySplit:h}=e;if(c>=l.getRowCount()||d>=l.getColumnCount()||m>=l.getColumnCount()||h>=l.getRowCount())return!1;const R={unitId:a,subUnitId:u,...e},C=Bs(s,R);return t.syncExecuteCommand(Ne.id,R)?(n.pushUndoRedo({unitID:a,undoMutations:[{id:Ne.id,params:C}],redoMutations:[{id:Ne.id,params:R}]}),!0):!1}},zr={type:i.CommandType.COMMAND,id:"sheet.command.cancel-frozen",handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUniverInstanceService),o=s.get(i.IUndoRedoService),r=P(n,{unitId:e==null?void 0:e.unitId,subUnitId:e==null?void 0:e.subUnitId});if(!r)return!1;const{unitId:a,subUnitId:u}=r,l={unitId:a,subUnitId:u,startRow:-1,startColumn:-1,xSplit:0,ySplit:0},d=Bs(s,l);return t.syncExecuteCommand(Ne.id,l)&&o.pushUndoRedo({unitID:a,undoMutations:[{id:Ne.id,params:d}],redoMutations:[{id:Ne.id,params:l}]}),!0}},qr={type:i.CommandType.COMMAND,id:"sheet.command.set-gridlines-color",handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=P(o);if(!r)return!1;const{worksheet:a}=r,u=a.getConfig().gridlinesColor;if(u===(e==null?void 0:e.color))return!1;const{unitId:l,subUnitId:d}=r,c={color:e==null?void 0:e.color,unitId:l,subUnitId:d},m={color:u,unitId:l,subUnitId:d};return t.syncExecuteCommand(dt.id,c)?(n.pushUndoRedo({unitID:l,undoMutations:[{id:dt.id,params:m}],redoMutations:[{id:dt.id,params:c}]}),!0):!1}},Q={id:"sheet.mutation.set-range-protection",type:i.CommandType.MUTATION,handler:(s,e)=>{const{unitId:t,subUnitId:n,rule:o,ruleId:r}=e;return s.get(X).setRule(t,n,r,o),!0}},Sl=(s,e)=>{const{unitId:t,subUnitId:n,ruleId:o}=e,a=s.get(X).getRule(t,n,o);return a?{id:Q.id,params:{...e,rule:a}}:null},st={id:"sheet.mutation.set-worksheet-protection",type:i.CommandType.MUTATION,handler:(s,e)=>{const{unitId:t,subUnitId:n,rule:o}=e;return s.get(ke).setRule(t,n,o),!0}},Yr={type:i.CommandType.COMMAND,id:"sheet.command.set-protection",async handler(s,e){if(!e)return!1;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(X),{rule:r,oldRule:a}=e,{unitId:u,subUnitId:l}=r,d=[],c=[];return(a==null?void 0:a.unitType)===r.unitType?r.unitType===D.Worksheet?(d.push({id:st.id,params:{unitId:u,subUnitId:l,rule:r}}),c.push({id:st.id,params:{unitId:u,subUnitId:l,rule:a}})):(d.push({id:Q.id,params:{unitId:u,subUnitId:l,rule:r,ruleId:r.id}}),c.push({id:Q.id,params:{unitId:u,subUnitId:l,ruleId:a.id,rule:a}})):(a&&(a.unitType===D.Worksheet?(d.push({id:tt.id,params:{unitId:u,subUnitId:l}}),c.push({id:Fe.id,params:{unitId:u,rule:a,subUnitId:a.subUnitId}})):a.unitType===D.SelectRange&&(d.push({id:Te.id,params:{unitId:u,subUnitId:l,ruleIds:[a.id]}}),c.push({id:Ce.id,params:{unitId:u,subUnitId:l,rules:[a]}}))),r.unitType===D.Worksheet?(d.push({id:Fe.id,params:{unitId:u,rule:r,subUnitId:r.subUnitId}}),c.unshift({id:tt.id,params:{unitId:u,subUnitId:l}})):r.unitType===D.SelectRange&&(r.id=o.createRuleId(u,l),d.push({id:Ce.id,params:{unitId:u,subUnitId:l,rules:[r]}}),c.unshift({id:Te.id,params:{unitId:u,subUnitId:l,ruleIds:[r.id]}}))),i.sequenceExecute(d,t)&&n.pushUndoRedo({unitID:u,undoMutations:c,redoMutations:d}),!0}},Kr={type:i.CommandType.COMMAND,id:"sheet.command.set-row-data",handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=P(o,e);if(!r)return!1;const{rowData:a}=e,{unitId:u,subUnitId:l,worksheet:d}=r,c={subUnitId:l,unitId:u,rowData:a},m=So(c,d);return t.syncExecuteCommand(ct.id,c)?(n.pushUndoRedo({unitID:u,undoMutations:[{id:ct.id,params:m}],redoMutations:[{id:ct.id,params:c}]}),!0):!1}},Tt={type:i.CommandType.COMMAND,id:"sheet.command.set-specific-rows-visible",handler:(s,e)=>{var v,M,p;const{unitId:t,subUnitId:n,ranges:o}=e,r=s.get(i.ICommandService),a=s.get(i.IUndoRedoService),u=s.get(g.SheetInterceptorService),l=P(s.get(i.IUniverInstanceService),{unitId:t,subUnitId:n});if(!l)return!1;const{worksheet:d}=l,c={unitId:t,subUnitId:n,ranges:o},m={unitId:t,subUnitId:n,reveal:!0,selections:o.map(w=>({range:w,primary:se(w,d),style:null}))},h=ba(s,c),R={unitId:t,subUnitId:n,selections:Jr(o).map(w=>({range:w,primary:se(w,d),style:null}))},C=i.sequenceExecute([{id:Ye.id,params:c},{id:q.id,params:m}],r),S=u.onCommandExecute({id:Tt.id,params:e}),I=i.sequenceExecute([...S.redos],r);if(C.result&&I.result){const w=u.afterCommandExecute({id:Tt.id,params:e});return i.sequenceExecute(w.redos,r),a.pushUndoRedo({unitID:t,undoMutations:[...(v=S.preUndos)!=null?v:[],{id:Ke.id,params:h},{id:q.id,params:R},...(M=S.undos)!=null?M:[],...w.undos],redoMutations:[...(p=S.preRedos)!=null?p:[],{id:Ye.id,params:c},{id:q.id,params:m},...S.redos,...w.redos]}),!0}return!0}},Hs={type:i.CommandType.COMMAND,id:"sheet.command.set-selected-rows-visible",handler:async s=>{var c;const e=s.get(g.SheetsSelectionsService),t=s.get(i.IUniverInstanceService),n=s.get(i.ICommandService),o=(c=e.getCurrentSelections())==null?void 0:c.map(m=>m.range).filter(m=>m.rangeType===i.RANGE_TYPE.ROW);if(!(o!=null&&o.length))return!1;const r=P(t);if(!r)return!1;const{worksheet:a,unitId:u,subUnitId:l}=r,d=o.map(m=>a.getHiddenRows(m.startRow,m.endRow)).flat();return n.executeCommand(Tt.id,{unitId:u,subUnitId:l,ranges:d})}},Mn={type:i.CommandType.COMMAND,id:"sheet.command.set-rows-hidden",handler:(s,e)=>{var M,p,w,y,b,T;const t=s.get(g.SheetsSelectionsService),n=s.get(i.ICommandService),o=s.get(i.IUndoRedoService),r=s.get(i.IUniverInstanceService),a=s.get(g.SheetInterceptorService);let u=(M=e==null?void 0:e.ranges)!=null&&M.length?e.ranges:(p=t.getCurrentSelections())==null?void 0:p.map(U=>U.range).filter(U=>U.rangeType===i.RANGE_TYPE.ROW);if(!(u!=null&&u.length))return!1;const l=P(r,e);if(!l)return!1;u=fl(l.worksheet,u);const{unitId:d,subUnitId:c,worksheet:m}=l,h={unitId:d,subUnitId:c,ranges:u},R={unitId:d,subUnitId:c,selections:Jr(u).map(U=>({range:U,primary:se(U,m),style:null}))},C=Ea(s,h),S={unitId:d,subUnitId:c,reveal:!0,selections:u.map(U=>({range:U,primary:se(U,m),style:null}))},I=a.onCommandExecute({id:Mn.id,params:h});if(i.sequenceExecute([...(w=I.preRedos)!=null?w:[],{id:Ke.id,params:h},{id:q.id,params:R},...I.redos],n).result){const U=a.afterCommandExecute({id:Mn.id,params:h});return i.sequenceExecute(U.redos,n),o.pushUndoRedo({unitID:d,undoMutations:[...(y=I.preUndos)!=null?y:[],{id:Ye.id,params:C},{id:q.id,params:S},...(b=I.undos)!=null?b:[],...U.undos],redoMutations:[...(T=I.preRedos)!=null?T:[],{id:Ke.id,params:h},{id:q.id,params:R},...I.redos,...U.redos]}),!0}return!0}};function fl(s,e){const t=s.getMaxColumns()-1,n=s.getHiddenRows(),o=[];return e.forEach(r=>{const a=n.filter(u=>u.startRow>=r.startRow&&u.endRow<=r.endRow);if(a.length){let u=r.startRow;a.forEach(l=>{l.startRow>u&&(o.push({startRow:u,endRow:l.startRow-1,startColumn:0,endColumn:t}),u=l.endRow+1)}),u<=r.endRow&&o.push({startRow:u,endRow:r.endRow,startColumn:0,endColumn:t})}else o.push(r)}),o}function Jr(s){return Il(s).map(t=>{const n=t.startRow===0?t.endRow+1:t.startRow-1;return{...t,startRow:n,endRow:n}})}function Il(s){const e=[];let t;return s.sort((n,o)=>n.startRow-o.startRow).forEach(n=>{if(!t){t=n;return}n.startRow===t.endRow+1?t.endRow=n.endRow:(e.push(t),t=n)}),e.push(t),e}const vl=["ff","fs","tr","tb"],ee={type:i.CommandType.COMMAND,id:"sheet.command.set-style",handler:(s,e)=>{var k;const t=s.get(i.IUniverInstanceService),n=P(t,e);if(!n)return!1;const{unitId:o,subUnitId:r,worksheet:a}=n,{range:u,style:l}=e,d=s.get(i.ICommandService),c=s.get(i.IUndoRedoService),m=s.get(g.SheetsSelectionsService),h=u?[u]:(k=m.getCurrentSelections())==null?void 0:k.map(E=>E.range);if(!(h!=null&&h.length))return!1;const R=new i.ObjectMatrix,C=du(a);if(i.Tools.isArray(l.value))for(let E=0;E<h.length;E++)C.forOperableEach(h[E],(N,W,V)=>{R.setValue(N,W,{s:{[l.type]:l.value[N-V.startRow][W-V.startColumn]}})});else for(let E=0;E<h.length;E++){const N={s:{[l.type]:l.value}};C.forOperableEach(h[E],(W,V)=>R.setValue(W,V,N))}const S={subUnitId:r,unitId:o,cellValue:R.getMatrix()},I=s.get(g.SheetSkeletonService).getSkeleton(o,r),v=ce(s,S),M=d.syncExecuteCommand(F.id,S),p=s.get(g.SheetInterceptorService);let w=[],y=[];if(vl.includes(e==null?void 0:e.style.type)){const{suitableRanges:E,remainingRanges:N}=Bt(h,I),W=Es(E,a),{undos:V,redos:$}=p.generateMutationsOfAutoHeight({unitId:o,subUnitId:r,ranges:E,autoHeightRanges:E,lazyAutoHeightRanges:N,cellHeights:W});w=V,y=$}const{undos:b,redos:T}=p.onCommandExecute({id:ee.id,params:e}),U=i.sequenceExecute([...T,...y],d);return M&&U.result?(c.pushUndoRedo({unitID:S.unitId,undoMutations:[{id:F.id,params:v},...b,...w],redoMutations:[{id:F.id,params:S},...T,...y]}),!0):!1}},pl={type:i.CommandType.COMMAND,id:"sheet.command.set-bold",handler:s=>{const e=s.get(g.SheetsSelectionsService).getCurrentLastSelection();if(!e)return!1;const t=P(s.get(i.IUniverInstanceService));if(!t)return!1;const{worksheet:n}=t,{actualRow:o,actualColumn:r}=e.primary,u={style:{type:"bl",value:n.getRange(o,r).getFontWeight()===i.FontWeight.BOLD?i.BooleanNumber.FALSE:i.BooleanNumber.TRUE}};return s.get(i.ICommandService).syncExecuteCommand(ee.id,u)}},wl={type:i.CommandType.COMMAND,id:"sheet.command.set-italic",handler:s=>{const e=s.get(g.SheetsSelectionsService).getCurrentLastSelection();if(!e)return!1;const t=P(s.get(i.IUniverInstanceService));if(!t)return!1;const{worksheet:n}=t;let o=!0;if(e.primary){const{startRow:a,startColumn:u}=e.primary;o=n.getRange(a,u).getFontStyle()===i.FontItalic.ITALIC}const r={style:{type:"it",value:o?i.BooleanNumber.FALSE:i.BooleanNumber.TRUE}};return s.get(i.ICommandService).syncExecuteCommand(ee.id,r)}},Ml={type:i.CommandType.COMMAND,id:"sheet.command.set-underline",handler:s=>{const e=s.get(g.SheetsSelectionsService).getCurrentLastSelection();if(!e)return!1;const t=P(s.get(i.IUniverInstanceService));if(!t)return!1;const{worksheet:n}=t;let o=!0;e.primary&&(o=!!n.getRange(e.primary.startRow,e.primary.startColumn).getUnderline().s);const r={style:{type:"ul",value:{s:o?i.BooleanNumber.FALSE:i.BooleanNumber.TRUE}}};return s.get(i.ICommandService).syncExecuteCommand(ee.id,r)}},yl={type:i.CommandType.COMMAND,id:"sheet.command.set-stroke",handler:s=>{const e=s.get(g.SheetsSelectionsService).getCurrentLastSelection();if(!e)return!1;const t=P(s.get(i.IUniverInstanceService));if(!t)return!1;const{worksheet:n}=t;let o=!0;e.primary&&(o=!!n.getRange(e.primary.actualRow,e.primary.actualColumn).getStrikeThrough().s);const r={style:{type:"st",value:{s:o?i.BooleanNumber.FALSE:i.BooleanNumber.TRUE}}};return s.get(i.ICommandService).syncExecuteCommand(ee.id,r)}},_l={type:i.CommandType.COMMAND,id:"sheet.command.set-overline",handler:s=>{const e=s.get(g.SheetsSelectionsService).getCurrentLastSelection();if(!e)return!1;const t=P(s.get(i.IUniverInstanceService));if(!t)return!1;const{worksheet:n}=t;let o=!0;e.primary&&(o=!!n.getRange(e.primary.startRow,e.primary.startColumn).getOverline().s);const r={style:{type:"ol",value:{s:o?i.BooleanNumber.FALSE:i.BooleanNumber.TRUE}}};return s.get(i.ICommandService).syncExecuteCommand(ee.id,r)}},bl={type:i.CommandType.COMMAND,id:"sheet.command.set-font-family",handler:(s,e)=>{if(!e)return!1;const t=s.get(i.ICommandService),n={style:{type:"ff",value:e.value}};return t.syncExecuteCommand(ee.id,n)}},El={type:i.CommandType.COMMAND,id:"sheet.command.set-font-size",handler:(s,e)=>{if(!e)return!1;const t=s.get(i.ICommandService),n={style:{type:"fs",value:e.value}};return t.syncExecuteCommand(ee.id,n)}},xr={type:i.CommandType.COMMAND,id:"sheet.command.set-text-color",handler:(s,e)=>{if(!e)return!1;const t=s.get(i.ICommandService),n={style:{type:"cl",value:{rgb:e.value}}};return t.syncExecuteCommand(ee.id,n)}},Xr={type:i.CommandType.COMMAND,id:"sheet.command.reset-text-color",handler:s=>{const e=s.get(i.ICommandService),t={style:{type:"cl",value:{rgb:null}}};return e.syncExecuteCommand(ee.id,t)}},Zr={type:i.CommandType.COMMAND,id:"sheet.command.set-background-color",handler:(s,e)=>{if(!e||!e.value)return!1;const t=s.get(i.ICommandService),n={style:{type:"bg",value:{rgb:e.value}}};return t.syncExecuteCommand(ee.id,n)}},Qr={type:i.CommandType.COMMAND,id:"sheet.command.reset-background-color",handler:s=>{const e=s.get(i.ICommandService),t={style:{type:"bg",value:{rgb:null}}};return e.syncExecuteCommand(ee.id,t)}},ei={type:i.CommandType.COMMAND,id:"sheet.command.set-vertical-text-align",handler:(s,e)=>{if(!e)return!1;const t=s.get(i.ICommandService),n={unitId:e.unitId,subUnitId:e.subUnitId,range:e.range,style:{type:"vt",value:e.value}};return t.syncExecuteCommand(ee.id,n)}},ti={type:i.CommandType.COMMAND,id:"sheet.command.set-horizontal-text-align",handler:(s,e)=>{if(!e)return!1;const t=s.get(i.ICommandService),n={unitId:e.unitId,subUnitId:e.subUnitId,range:e.range,style:{type:"ht",value:e.value}};return t.syncExecuteCommand(ee.id,n)}},ni={type:i.CommandType.COMMAND,id:"sheet.command.set-text-wrap",handler:(s,e)=>{if(!e)return!1;const t=s.get(i.ICommandService),n={unitId:e.unitId,subUnitId:e.subUnitId,range:e.range,style:{type:"tb",value:e.value}};return t.syncExecuteCommand(ee.id,n)}},si={type:i.CommandType.COMMAND,id:"sheet.command.set-text-rotation",handler:(s,e)=>{if(!e)return!1;const t=typeof e.value=="number"?{a:e.value}:{a:0,v:i.BooleanNumber.TRUE},n=s.get(i.ICommandService),o={unitId:e.unitId,subUnitId:e.subUnitId,range:e.range,style:{type:"tr",value:t}};return n.syncExecuteCommand(ee.id,o)}},Tl=(s,e)=>{const r=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId).getSheetBySheetId(e.subUnitId).getConfig().tabColor;return{...i.Tools.deepClone(e),color:r}},jt={id:"sheet.mutation.set-tab-color",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(!t)return!1;const n=t.getSheetBySheetId(e.subUnitId);return n?(n.getConfig().tabColor=e.color,!0):!1}},oi={type:i.CommandType.COMMAND,id:"sheet.command.set-tab-color",handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=P(s.get(i.IUniverInstanceService));if(!o)return!1;const{unitId:r,subUnitId:a}=o,u={color:e.value,unitId:r,subUnitId:a},l=Tl(s,u);return t.syncExecuteCommand(jt.id,u)?(n.pushUndoRedo({unitID:r,undoMutations:[{id:jt.id,params:l}],redoMutations:[{id:jt.id,params:u}]}),!0):!1}},Fs={id:"sheet.mutation.set-workbook-name",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=s.get(i.IUniverInstanceService).getUnit(e.unitId,i.UniverInstanceType.UNIVER_SHEET);return t?(t.setName(e.name),!0):!1}},js={type:i.CommandType.COMMAND,id:"sheet.command.set-workbook-name",handler:(s,e)=>{var l;const t=s.get(i.ICommandService),n=s.get(g.SheetInterceptorService);if(!Bn(s.get(i.IUniverInstanceService),e))return!1;const r=n.onCommandExecute({id:js.id,params:e}),a={name:e.name,unitId:e.unitId},u=[...(l=r.preRedos)!=null?l:[],{id:Fs.id,params:a},...r.redos];return i.sequenceExecute(u,t).result}},Ul=4,Gs={type:i.CommandType.COMMAND,id:"sheet.command.set-worksheet-activate",handler:(s,e,t)=>{const n=s.get(i.ICommandService),o=P(s.get(i.IUniverInstanceService),e);if(!o)return!1;const{unitId:r,subUnitId:a}=o;return new Promise(u=>{setTimeout(()=>{const l=n.syncExecuteCommand(Ct.id,{unitId:r,subUnitId:a},t);u(l)},Ul)})}},Gt={type:i.CommandType.COMMAND,id:"sheet.command.delta-column-width",handler:async(s,e)=>{const n=s.get(g.SheetsSelectionsService).getCurrentSelections();if(!(n!=null&&n.length))return!1;const o=s.get(i.ICommandService),r=s.get(i.IUndoRedoService),a=P(s.get(i.IUniverInstanceService));if(!a)return!1;const{worksheet:u,unitId:l,subUnitId:d}=a,{anchorCol:c,deltaX:m}=e,R=u.getColumnWidth(c)+m,C=n.length===1&&n[0].range.rangeType===i.RANGE_TYPE.ALL,S=n.filter(L=>L.range.rangeType===i.RANGE_TYPE.COLUMN),I=C?i.RANGE_TYPE.ALL:S.some(({range:L})=>{const{startColumn:Y,endColumn:z}=L;return Y<=c&&c<=z})?i.RANGE_TYPE.COLUMN:i.RANGE_TYPE.NORMAL;let v;if(I===i.RANGE_TYPE.ALL){const L=u.getRowCount(),Y=new Array(u.getColumnCount()).fill(void 0).map((z,K)=>({startRow:0,endRow:L-1,startColumn:K,endColumn:K}));v={subUnitId:d,unitId:l,colWidth:R,ranges:Y}}else I===i.RANGE_TYPE.COLUMN?v={subUnitId:d,unitId:l,ranges:S.map(L=>i.Rectangle.clone(L.range)),colWidth:R}:v={subUnitId:d,unitId:l,colWidth:R,ranges:[{startRow:0,endRow:u.getMaxRows()-1,startColumn:c,endColumn:c}]};const M=s.get(g.SheetSkeletonService).getSkeleton(l,d),{suitableRanges:p,remainingRanges:w}=Bt(v.ranges,M);Es(p,u);const y=s.get(g.SheetInterceptorService),{undos:b,redos:T}=y.onCommandExecute({id:Gt.id,params:v}),U=jn(v,u),k=o.syncExecuteCommand(Ve.id,v),{undos:E,redos:N}=y.generateMutationsOfAutoHeight({unitId:l,subUnitId:d,ranges:p,autoHeightRanges:p,lazyAutoHeightRanges:w}),{undos:W,redos:V}=s.get(g.SheetInterceptorService).afterCommandExecute({id:Gt.id,params:v}),$=i.sequenceExecute([...T,...V,...N],o);return k&&$.result&&r.pushUndoRedo({unitID:l,undoMutations:[{id:Ve.id,params:U},...b,...W,...E],redoMutations:[{id:Ve.id,params:v},...T,...V,...N]}),!0}},zt={type:i.CommandType.COMMAND,id:"sheet.command.set-worksheet-col-width",handler:(s,e)=>{var y,b,T,U;const t=s.get(g.SheetsSelectionsService),n=s.get(i.ICommandService),o=s.get(i.IUndoRedoService),r=s.get(g.SheetInterceptorService),a=(y=e==null?void 0:e.ranges)!=null&&y.length?e.ranges:(b=t.getCurrentSelections())==null?void 0:b.map(k=>k.range);if(!(a!=null&&a.length))return!1;const u=P(s.get(i.IUniverInstanceService),e);if(!u)return!1;const{subUnitId:l,unitId:d,worksheet:c}=u,m=s.get(g.SheetSkeletonService).getSkeleton(d,l),h={subUnitId:l,unitId:d,ranges:a,colWidth:e.value},{suitableRanges:R,remainingRanges:C}=Bt(h.ranges,m);Es(R,c);const S=jn(h,c),I=n.syncExecuteCommand(Ve.id,h),{undos:v,redos:M}=r.generateMutationsOfAutoHeight({unitId:d,subUnitId:l,ranges:R,autoHeightRanges:R,lazyAutoHeightRanges:C}),p=r.onCommandExecute({id:zt.id,params:h}),w=i.sequenceExecute([...p.redos,...M],n);if(I&&w.result){const k=r.afterCommandExecute({id:zt.id,params:h});return i.sequenceExecute(k.redos,n),o.pushUndoRedo({unitID:d,undoMutations:[...(T=p.preUndos)!=null?T:[],{id:Ve.id,params:S},...p.undos,...k.undos,...v],redoMutations:[...(U=p.preRedos)!=null?U:[],{id:Ve.id,params:h},...p.redos,...k.redos,...M]}),!0}return!1}};i.CommandType.COMMAND;const ri={type:i.CommandType.COMMAND,id:"sheet.command.set-worksheet-column-count",handler:(s,e)=>{const{unitId:t,subUnitId:n,columnCount:o}=e,r=s.get(i.ICommandService),a=s.get(i.IUndoRedoService),u=s.get(i.IUniverInstanceService);if(!P(u,e))return!1;const d={unitId:t,subUnitId:n,columnCount:o},c=fo(s,d);return r.syncExecuteCommand(mt.id,d)?(a.pushUndoRedo({unitID:t,undoMutations:[{id:mt.id,params:c}],redoMutations:[{id:mt.id,params:d}]}),!0):!1}},ii={type:i.CommandType.COMMAND,id:"sheet.command.set-worksheet-default-style",handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),{unitId:o}=e,r=Io(s,e);return t.syncExecuteCommand(ht.id,e)?(n.pushUndoRedo({unitID:o,undoMutations:[{id:ht.id,params:r}],redoMutations:[{id:ht.id,params:e}]}),!0):!1}},ai=(s,e)=>{const t=ve(s.get(i.IUniverInstanceService),e);if(!t)throw new Error("[SetWorksheetHideMutationFactory]: worksheet is null error!");const{worksheet:n}=t;return{hidden:n.isSheetHidden(),unitId:e.unitId,subUnitId:n.getSheetId()}},je={id:"sheet.mutation.set-worksheet-hidden",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(t==null)return!1;const n=t.getSheetBySheetId(e.subUnitId);return n?(n.getConfig().hidden=e.hidden,!0):!1}},ui={type:i.CommandType.COMMAND,id:"sheet.command.set-worksheet-hidden",handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.ErrorService),r=s.get(i.LocaleService),a=P(s.get(i.IUniverInstanceService),e);if(!a)return!1;const{workbook:u,worksheet:l,unitId:d,subUnitId:c}=a;if(l.getConfig().hidden===i.BooleanNumber.TRUE)return!1;const h={unitId:d,subUnitId:c,hidden:i.BooleanNumber.TRUE},R=ai(s,h);return u.getSheets().filter(v=>v.getConfig().hidden===i.BooleanNumber.FALSE).length===1?(o.emit(r.t("sheets.info.hideSheet")),!1):t.syncExecuteCommand(je.id,h)?(n.pushUndoRedo({unitID:d,undoMutations:[{id:je.id,params:R}],redoMutations:[{id:je.id,params:h}]}),!0):!1}},Pl=(s,e)=>{const t=ve(s.get(i.IUniverInstanceService),e);if(!t)throw new Error("[SetWorksheetNameMutationFactory]: worksheet is null error!");const{worksheet:n}=t;return{unitId:e.unitId,name:n.getName(),subUnitId:n.getSheetId()}},qt={id:"sheet.mutation.set-worksheet-name",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(t==null)return!1;const n=t.getSheetBySheetId(e.subUnitId);return n?(n.getConfig().name=e.name,!0):!1}},yn={type:i.CommandType.COMMAND,id:"sheet.command.set-worksheet-name",handler:(s,e)=>{var C,S;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(g.SheetInterceptorService),r=P(s.get(i.IUniverInstanceService),e);if(!r)return!1;const{unitId:a,subUnitId:u}=r,l={subUnitId:u,name:e.name,unitId:a},d=Pl(s,l),c=o.onCommandExecute({id:yn.id,params:e}),m=[...(C=c.preRedos)!=null?C:[],{id:qt.id,params:l},...c.redos],h=[...(S=c.preUndos)!=null?S:[],{id:qt.id,params:d},...c.undos];return i.sequenceExecute(m,t).result?(n.pushUndoRedo({unitID:a,undoMutations:h,redoMutations:m}),!0):!1}},kl=(s,e)=>({...i.Tools.deepClone(e),toOrder:e.fromOrder,fromOrder:e.toOrder}),Yt={id:"sheet.mutation.set-worksheet-order",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(!t)return!1;const n=t.getConfig();return n.sheetOrder.splice(e.fromOrder,1),n.sheetOrder.splice(e.toOrder,0,e.subUnitId),!0}},zs={type:i.CommandType.COMMAND,id:"sheet.command.set-worksheet-order",handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=P(s.get(i.IUniverInstanceService),e);if(!o)return!1;const{workbook:r,unitId:a,subUnitId:u}=o,d={fromOrder:r.getConfig().sheetOrder.indexOf(u),toOrder:e.order,unitId:a,subUnitId:u},c=kl(s,d);return t.syncExecuteCommand(Yt.id,d)?(n.pushUndoRedo({unitID:a,undoMutations:[{id:Yt.id,params:c}],redoMutations:[{id:Yt.id,params:d}]}),!0):!1}};class Ut{constructor(){f(this,"_model",new Map);f(this,"_pointChange",new O.Subject);f(this,"pointChange$",this._pointChange.asObservable())}addRule(e){this._ensureSubUnitMap(e.unitId).set(e.subUnitId,e),this._pointChange.next(e)}deleteRule(e,t){var o,r,a;const n=(o=this._model.get(e))==null?void 0:o.get(t);n&&((a=(r=this._model)==null?void 0:r.get(e))==null||a.delete(t),this._pointChange.next(n))}getRule(e,t){var n,o;return(o=(n=this._model)==null?void 0:n.get(e))==null?void 0:o.get(t)}toObject(){const e={};return[...this._model.keys()].forEach(n=>{const o=this._model.get(n);o!=null&&o.size&&(e[n]=[],[...o.keys()].forEach(a=>{const u=o.get(a);u&&e[n].push(u)}))}),e}fromObject(e){const t=new Map;Object.keys(e).forEach(n=>{const o=e[n];if(o!=null&&o.length){const r=new Map;o.forEach(a=>{r.set(a.subUnitId,a)}),t.set(n,r)}}),this._model=t}deleteUnitModel(e){this._model.delete(e)}_ensureSubUnitMap(e){let t=this._model.get(e);return t||(t=new Map,this._model.set(e,t)),t}getTargetByPermissionId(e,t){const n=this._model.get(e);if(!n)return null;for(const[o,r]of n)if(r.permissionId===t)return[e,o]}}class qs{constructor(e,t,n){f(this,"type",D.SelectRange);f(this,"subType",_.Delete);f(this,"status",i.PermissionStatus.INIT);f(this,"value",!0);f(this,"id");f(this,"unitId");f(this,"subUnitId");f(this,"permissionId");this.unitId=e,this.subUnitId=t,this.permissionId=n,this.id=`${D.SelectRange}.${_.Delete}.${n}`}}class Ys{constructor(e,t,n){f(this,"type",D.SelectRange);f(this,"subType",_.ManageCollaborator);f(this,"status",i.PermissionStatus.INIT);f(this,"value",!0);f(this,"id");f(this,"unitId");f(this,"subUnitId");f(this,"permissionId");this.unitId=e,this.subUnitId=t,this.permissionId=n,this.id=`${D.SelectRange}.${_.ManageCollaborator}.${n}`}}const le=()=>[un,Se,Ys,qs],Ge=[_.Edit,_.View,_.ManageCollaborator,_.Delete],Nl=(s="unitId",e="subUnitId",t="permissionId")=>le().reduce((n,o)=>{const r=new o(s,e,t);return n[r.subType]=r.value,n},{}),Pt=()=>[me,ns,Jn,rs,xn,ts,dn,Zn,Qn,mn,ln,es,os,cn,jo,is,ss,Xn,Ko,Yo,zo,Go],li=[_.Edit,_.Print,_.Comment,_.View,_.Copy,_.Export,_.ManageCollaborator,_.CreateSheet,_.DeleteSheet,_.RenameSheet,_.HideSheet,_.Duplicate,_.Share,_.MoveSheet,_.CopySheet,_.RecoverHistory,_.ViewHistory,_.CreatePermissionObject,_.InsertRow,_.InsertColumn,_.DeleteRow,_.DeleteColumn],de=()=>[fe,Vt,Cs,ls],Ie=()=>[as,us,ds,cs,ms,hs,Rs,gs,Ss,fs,Wt,St,ft,Is],_n=[_.Copy,_.DeleteColumn,_.DeleteRow,_.EditExtraObject,_.Filter,_.InsertColumn,_.InsertRow,_.InsertHyperlink,_.PivotTable,_.SetCellStyle,_.SetCellValue,_.SetColumnStyle,_.SetRowStyle,_.Sort];var Ol=Object.getOwnPropertyDescriptor,Dl=(s,e,t,n)=>{for(var o=n>1?void 0:n?Ol(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},ze=(s,e)=>(t,n)=>e(t,n,s);const Al="SHEET_WORKSHEET_PROTECTION_PLUGIN",Wl="SHEET_WORKSHEET_PROTECTION_POINT_PLUGIN";g.WorksheetPermissionService=class extends i.RxDisposable{constructor(e,t,n,o,r,a,u,l){super(),this._permissionService=e,this._univerInstanceService=t,this._injector=n,this._worksheetProtectionRuleModel=o,this._worksheetProtectionPointRuleModel=r,this._resourceManagerService=a,this._rangeProtectionRuleModel=u,this._logService=l,this._init(),this._initRuleChange(),this._initRuleSnapshot(),this._initPointSnapshot()}_init(){const e=t=>{const n=t.getUnitId(),o=r=>{const a=r.getSheetId();[...de(),...Ie()].forEach(u=>{const l=new u(n,a);this._permissionService.addPermissionPoint(l)}),this._logService.debug("[WorksheetPermissionService]","Initialization completed",n,a)};t.getSheets().forEach(r=>{o(r)}),t.sheetCreated$.subscribe(r=>{o(r)}),t.sheetDisposed$.subscribe(r=>{const a=r.getSheetId();this._rangeProtectionRuleModel.getSubunitRuleList(n,a).forEach(l=>{[...le()].forEach(d=>{const c=new d(n,a,l.permissionId);this._permissionService.deletePermissionPoint(c.id)})}),[...de(),...Ie()].forEach(l=>{const d=new l(n,a);this._permissionService.deletePermissionPoint(d.id)})})};this._univerInstanceService.getAllUnitsForType(i.UniverInstanceType.UNIVER_SHEET).forEach(t=>{e(t)}),this._univerInstanceService.getTypeOfUnitAdded$(i.UniverInstanceType.UNIVER_SHEET).pipe(kt.takeUntil(this.dispose$)).subscribe(e),this._univerInstanceService.getTypeOfUnitDisposed$(i.UniverInstanceType.UNIVER_SHEET).pipe(kt.takeUntil(this.dispose$)).subscribe(t=>{t.getSheets().forEach(n=>{const o=t.getUnitId(),r=n.getSheetId();de().forEach(a=>{const u=new a(o,r);this._permissionService.deletePermissionPoint(u.id)})})})}_initRuleChange(){this.disposeWithMe(this._worksheetProtectionRuleModel.ruleChange$.subscribe(e=>{switch(e.type){case"add":break;case"delete":{de().forEach(t=>{const n=new t(e.unitId,e.subUnitId);this._permissionService.updatePermissionPoint(n.id,!0)});break}case"set":{de().forEach(t=>{const n=new t(e.unitId,e.subUnitId);this._permissionService.updatePermissionPoint(n.id,e.rule)});break}}}))}_initRuleSnapshot(){const e=()=>{const n=this._worksheetProtectionRuleModel.toObject();return JSON.stringify(n)},t=n=>{if(!n)return{};try{return JSON.parse(n)}catch{return{}}};this.disposeWithMe(this._resourceManagerService.registerPluginResource({toJson:e,parseJson:t,pluginName:Al,businesses:[an.UNIVER_SHEET],onLoad:(n,o)=>{this._worksheetProtectionRuleModel.fromObject(o),Object.keys(o).forEach(r=>{de().forEach(a=>{const u=new a(n,r);u.value=!1,this._permissionService.addPermissionPoint(u)})}),this._worksheetProtectionRuleModel.changeRuleInitState(!0)},onUnLoad:n=>{const o=this._univerInstanceService.getUnit(n);o&&(o.getSheets().forEach(r=>{const a=r.getSheetId();[...de(),...Ie()].forEach(u=>{const l=new u(n,a);this._permissionService.deletePermissionPoint(l.id)})}),Pt().forEach(r=>{const a=new r(n);this._permissionService.deletePermissionPoint(a.id)})),this._worksheetProtectionRuleModel.deleteUnitModel(n)}}))}_initPointSnapshot(){const e=()=>{const n=this._worksheetProtectionPointRuleModel.toObject();return JSON.stringify(n)},t=n=>{if(!n)return{};try{return JSON.parse(n)}catch{return{}}};this.disposeWithMe(this._resourceManagerService.registerPluginResource({toJson:e,parseJson:t,pluginName:Wl,businesses:[an.UNIVER_SHEET],onLoad:(n,o)=>{this._worksheetProtectionPointRuleModel.fromObject(o),Object.keys(o).forEach(r=>{Ie().forEach(a=>{const u=new a(n,r);this._permissionService.addPermissionPoint(u)})})},onUnLoad:n=>{this._worksheetProtectionPointRuleModel.deleteUnitModel(n)}}))}},g.WorksheetPermissionService=Dl([ze(0,i.Inject(i.IPermissionService)),ze(1,i.Inject(i.IUniverInstanceService)),ze(2,i.Inject(i.Injector)),ze(3,i.Inject(ke)),ze(4,i.Inject(Ut)),ze(5,i.Inject(i.IResourceManagerService)),ze(6,i.Inject(X)),ze(7,i.Inject(i.ILogService))],g.WorksheetPermissionService);const bn={id:"sheet.mutation.set-worksheet-permission-points",type:i.CommandType.MUTATION,handler:(s,e)=>{const{rule:t}=e;return s.get(Ut).addRule(t),!0}},di={type:i.CommandType.COMMAND,id:"sheet.command.set-worksheet-permission-points",async handler(s,e){if(!e)return!1;const t=s.get(i.ICommandService),{rule:n}=e;return t.executeCommand(bn.id,{rule:n,unitId:n.unitId,subUnitId:n.subUnitId}),!0}},ci={type:i.CommandType.COMMAND,id:"sheet.command.set-worksheet-protection",async handler(s,e){if(!e)return!1;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),{rule:o,permissionId:r,oldRule:a}=e,{unitId:u,subUnitId:l}=o,d={...o,permissionId:r};if(await t.executeCommand(st.id,{unitId:u,subUnitId:l,newRule:d})){const m=[{id:st.id,params:{unitId:u,subUnitId:l,newRule:d}}],h=[{id:st.id,params:{unitId:u,subUnitId:l,rule:a}}];n.pushUndoRedo({unitID:u,redoMutations:m,undoMutations:h})}return!0}},Vl=(s,e)=>{const r=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId).getSheetBySheetId(e.subUnitId).getConfig().rightToLeft;return{...i.Tools.deepClone(e),rightToLeft:r}},En={id:"sheet.mutation.set-worksheet-right-to-left",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(!t)return!1;const n=t.getSheetBySheetId(e.subUnitId);if(!n)return!1;const o=n.getConfig();return o.rightToLeft=e.rightToLeft,!0}},$l={type:i.CommandType.COMMAND,id:"sheet.command.set-worksheet-right-to-left",handler:async(s,e)=>{var m;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=P(s.get(i.IUniverInstanceService),e);if(!o)return!1;const{unitId:r,subUnitId:a}=o;let u=i.BooleanNumber.FALSE;e&&(u=(m=e.rightToLeft)!=null?m:i.BooleanNumber.FALSE);const l={rightToLeft:u,unitId:r,subUnitId:a},d=Vl(s,l);return t.syncExecuteCommand(En.id,l)?(n.pushUndoRedo({unitID:r,undoMutations:[{id:En.id,params:d}],redoMutations:[{id:En.id,params:l}]}),!0):!1}},mi={type:i.CommandType.COMMAND,id:"sheet.command.set-worksheet-row-count",handler:(s,e)=>{const{unitId:t,subUnitId:n,rowCount:o}=e,r=s.get(i.ICommandService),a=s.get(i.IUndoRedoService),u=s.get(i.IUniverInstanceService);if(!P(u,e))return!1;const d={unitId:t,subUnitId:n,rowCount:o},c=vo(s,d);return r.syncExecuteCommand(gt.id,d)?(a.pushUndoRedo({unitID:t,undoMutations:[{id:gt.id,params:c}],redoMutations:[{id:gt.id,params:d}]}),!0):!1}},Kt={type:i.CommandType.COMMAND,id:"sheet.command.delta-row-height",handler:async(s,e)=>{var k,E;const n=s.get(g.SheetsSelectionsService).getCurrentSelections(),o=s.get(g.SheetInterceptorService);if(!(n!=null&&n.length))return!1;const r=P(s.get(i.IUniverInstanceService));if(!r)return!1;const{worksheet:a,subUnitId:u,unitId:l}=r,{anchorRow:d,deltaY:c}=e,h=a.getRowHeight(d)+c,R=n.length===1&&n[0].range.rangeType===i.RANGE_TYPE.ALL,C=n.filter(N=>N.range.rangeType===i.RANGE_TYPE.ROW),S=R?i.RANGE_TYPE.ALL:C.some(({range:N})=>{const{startRow:W,endRow:V}=N;return W<=d&&d<=V})?i.RANGE_TYPE.ROW:i.RANGE_TYPE.NORMAL;let I;if(S===i.RANGE_TYPE.ALL){const N=a.getColumnCount(),W=new Array(a.getRowCount()).fill(void 0).map((V,$)=>({startRow:$,endRow:$,startColumn:0,endColumn:N-1}));I={subUnitId:u,unitId:l,rowHeight:h,ranges:W}}else S===i.RANGE_TYPE.ROW?I={subUnitId:u,unitId:l,ranges:C.map(N=>i.Rectangle.clone(N.range)),rowHeight:h}:I={subUnitId:u,unitId:l,rowHeight:h,ranges:[{startRow:d,endRow:d,startColumn:0,endColumn:a.getMaxColumns()-1}]};const v=po(I,a),M={unitId:l,subUnitId:u,ranges:I.ranges,autoHeightInfo:i.BooleanNumber.FALSE},p=Gn(M,a),w=s.get(i.ICommandService),y=s.get(i.IUndoRedoService),b=o.onCommandExecute({id:Kt.id,params:I}),T=i.sequenceExecute([{id:Ee.id,params:I},{id:Re.id,params:M}],w),U=i.sequenceExecute([...b.redos],w);if(T.result&&U.result){const N=o.afterCommandExecute({id:Kt.id,params:I});return i.sequenceExecute(N.redos,w),y.pushUndoRedo({unitID:l,undoMutations:[...(k=b.preUndos)!=null?k:[],{id:Ee.id,params:v},{id:Re.id,params:p},...b.undos,...N.undos],redoMutations:[...(E=b.preRedos)!=null?E:[],{id:Ee.id,params:I},{id:Re.id,params:M},...b.redos,...N.redos]}),!0}return!1}},Jt={type:i.CommandType.COMMAND,id:"sheet.command.set-row-height",handler:(s,e)=>{var p,w,y,b;const t=s.get(g.SheetsSelectionsService),n=s.get(i.ICommandService),o=s.get(i.IUndoRedoService),r=s.get(i.IUniverInstanceService),a=s.get(g.SheetInterceptorService),u=(p=e==null?void 0:e.ranges)!=null&&p.length?e.ranges:(w=t.getCurrentSelections())==null?void 0:w.map(T=>T.range);if(!(u!=null&&u.length))return!1;const l=P(r,e);if(!l)return!1;const{unitId:d,subUnitId:c,worksheet:m}=l,h={subUnitId:c,unitId:d,ranges:u,rowHeight:e.value},R=po(h,m),C={unitId:d,subUnitId:c,ranges:h.ranges,autoHeightInfo:i.BooleanNumber.FALSE},S=Gn(C,m),I=i.sequenceExecute([{id:Ee.id,params:h},{id:Re.id,params:C}],n),v=a.onCommandExecute({id:Jt.id,params:h}),M=i.sequenceExecute([...v.redos],n);if(I.result&&M.result){const T=a.afterCommandExecute({id:Jt.id,params:h});return i.sequenceExecute(T.redos,n),o.pushUndoRedo({unitID:d,undoMutations:[...(y=v.preRedos)!=null?y:[],{id:Ee.id,params:R},{id:Re.id,params:S},...v.undos,...T.undos],redoMutations:[...(b=v.preRedos)!=null?b:[],{id:Ee.id,params:h},{id:Re.id,params:C},...v.redos,...T.redos]}),!0}return!1}},Tn={type:i.CommandType.COMMAND,id:"sheet.command.set-row-is-auto-height",handler:(s,e)=>{var T,U;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(g.SheetsSelectionsService),r=s.get(i.IUniverInstanceService),a=P(r,e);if(!a)return!1;const{unitId:u,subUnitId:l,worksheet:d}=a,c=(T=e==null?void 0:e.ranges)!=null&&T.length?e.ranges:(U=o.getCurrentSelections())==null?void 0:U.map(k=>k.range);if(!(c!=null&&c.length))return!1;const m={unitId:u,subUnitId:l,ranges:c,autoHeightInfo:i.BooleanNumber.TRUE},h=Gn(m,d),R=t.syncExecuteCommand(Re.id,m),C=s.get(g.SheetSkeletonService).getSkeleton(u,l),{suitableRanges:S,remainingRanges:I}=Bt(m.ranges,C),v=s.get(g.SheetInterceptorService),{undos:M,redos:p}=v.generateMutationsOfAutoHeight({unitId:u,subUnitId:l,ranges:S,autoHeightRanges:S,lazyAutoHeightRanges:I}),{undos:w,redos:y}=v.onCommandExecute({id:Tn.id,params:m}),b=i.sequenceExecute([...y,...p],t);return R&&b.result?(n.pushUndoRedo({unitID:u,undoMutations:[{id:Re.id,params:h},...w,...M],redoMutations:[{id:Re.id,params:m},...y,...p]}),!0):!1}},Ks={type:i.CommandType.COMMAND,id:"sheet.command.set-worksheet-show",handler:(s,e)=>{const{unitId:t,subUnitId:n}=e,o=s.get(i.ICommandService),r=s.get(i.IUndoRedoService),a=s.get(i.IUniverInstanceService);if(!P(s.get(i.IUniverInstanceService)))return!1;const l=a.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET);if(!l)return!1;const d=l.getSheetBySheetId(n);if(!d||d.getConfig().hidden===i.BooleanNumber.FALSE)return!1;const m={unitId:t,subUnitId:n,hidden:i.BooleanNumber.FALSE},h=ai(s,m),R=o.syncExecuteCommand(je.id,m),C={unitId:t,subUnitId:n},S=o.syncExecuteCommand(Ct.id,C);return R&&S?(r.pushUndoRedo({unitID:t,undoMutations:[{id:je.id,params:h}],redoMutations:[{id:je.id,params:m}]}),!0):!1}},hi={type:i.CommandType.COMMAND,id:"sheet.command.split-text-to-columns",handler:(s,e)=>{const{unitId:t,subUnitId:n,range:o,delimiter:r,customDelimiter:a,treatMultipleDelimitersAsOne:u}=e,l=s.get(i.ICommandService),d=s.get(i.IUniverInstanceService),c=s.get(i.IUndoRedoService);if(!P(s.get(i.IUniverInstanceService)))return!1;const h=d.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET);if(!h)return!1;const R=h.getSheetBySheetId(n);if(!R)return!1;const{lastRow:C,rs:S,maxLength:I}=Po(R,o,r,a,u),v=R.getColumnCount(),{startColumn:M}=i.Range.transformRange(o,R);if(o.startColumn!==o.endColumn)return!1;const p=[],w=[],y=M+I+1-v;if(y>0){const N={unitId:t,subUnitId:n,range:{startRow:0,endRow:R.getRowCount()-1,startColumn:v-1,endColumn:v-1+y}};p.push({id:ie.id,params:N});const W=Nt(s,N);w.push({id:ne.id,params:W})}const b={startRow:o.startRow,endRow:C,startColumn:M,endColumn:M+I},T=new i.ObjectMatrix;for(let N=b.startRow;N<=b.endRow;N++)for(let W=b.startColumn;W<=b.endColumn;W++){const V=S[N-b.startRow];W===0&&(V==null?void 0:V.length)===1?T.setValue(N,W,R.getCell(N,W)):T.setValue(N,W,{v:(V==null?void 0:V[W-b.startColumn])||null,p:null,f:null,si:null,custom:null})}const U={unitId:t,subUnitId:n,cellValue:T.clone()},k=ce(s,U);return p.push({id:F.id,params:U}),w.unshift({id:F.id,params:k}),i.sequenceExecute(p,l).result?(c.pushUndoRedo({unitID:t,undoMutations:w,redoMutations:p}),!0):!1}},gi={id:"sheet.command.toggle-cell-checkbox",type:i.CommandType.COMMAND,handler:(s,e)=>{if(!e)return!1;const{unitId:t,subUnitId:n,row:o,col:r,paragraphIndex:a}=e,l=s.get(i.IUniverInstanceService).getUnit(t,i.UniverInstanceType.UNIVER_SHEET),d=l==null?void 0:l.getSheetBySheetId(n),c=s.get(i.IUndoRedoService),m=s.get(i.ICommandService);if(!d)return!1;const h=d.getCell(o,r);if(!(h!=null&&h.p))return!1;const R=i.Tools.deepClone(h.p),C=new i.DocumentDataModel(R),S=i.BuildTextUtils.paragraph.bullet.toggleChecklist({document:C,paragraphIndex:a});if(!S)return!1;i.TextX.apply(C.getBody(),S.serialize());const I={unitId:t,subUnitId:n,cellValue:{[o]:{[r]:{p:R,t:i.CellValueType.STRING}}}},v={id:F.id,params:I},M=ce(s,I),p={id:F.id,params:M},w=[v],y=[p];return c.pushUndoRedo({redoMutations:w,undoMutations:y,unitID:t}),m.syncExecuteCommand(v.id,v.params)}},Ri={type:i.CommandType.COMMAND,id:"sheet.command.toggle-gridlines",handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=P(o);if(!r)return!1;const{worksheet:a}=r,u=a.getConfig().showGridlines;if(u===(e==null?void 0:e.showGridlines))return!1;const{unitId:l,subUnitId:d}=r,c={showGridlines:u===i.BooleanNumber.TRUE?i.BooleanNumber.FALSE:i.BooleanNumber.TRUE,unitId:l,subUnitId:d},m={showGridlines:u,unitId:l,subUnitId:d};return t.syncExecuteCommand(Rt.id,c)?(n.pushUndoRedo({unitID:l,undoMutations:[{id:Rt.id,params:m}],redoMutations:[{id:Rt.id,params:c}]}),!0):!1}},Ci={id:"sheet.command.unregister-worksheet-range-theme-style",type:i.CommandType.COMMAND,handler:(s,e)=>{var h;if(!e)return!1;const{unitId:t,themeName:n}=e,o=s.get(i.IUniverInstanceService),r=s.get(i.ICommandService),a=s.get(i.IUndoRedoService),u=s.get(g.SheetRangeThemeModel);if(!P(o))return!1;const d={unitId:t,themeName:n},c={unitId:t,themeName:n,rangeThemeStyleJson:(h=u.getRangeThemeStyle(t,n))==null?void 0:h.toJson()};return r.syncExecuteCommand(_t.id,e)&&a.pushUndoRedo({unitID:t,undoMutations:[{id:_t.id,params:c}],redoMutations:[{id:In.id,params:d}]}),!0}},Si={id:"sheet.mutation.add-range-theme",type:i.CommandType.MUTATION,handler:(s,e)=>{if(!e)return!1;const{styleJSON:t,unitId:n}=e,o=s.get(g.SheetRangeThemeModel),r=new We(t.name);return r.fromJson(t),o.registerRangeThemeStyle(n,r),!0}},fi={id:"sheet.mutation.empty",type:i.CommandType.MUTATION,handler:()=>!0},Ii={id:"sheet.operation.mark-dirty-row-auto-height",type:i.CommandType.OPERATION,handler:()=>!0},vi={id:"sheet.operation.cancel-mark-dirty-row-auto-height",type:i.CommandType.OPERATION,handler:()=>!0},ot=i.createIdentifier("INumfmtService"),Ll=(s,e)=>{const t=s.get(ot),{values:n,unitId:o,subUnitId:r}=e,a=[],u=[];Object.keys(n).forEach(d=>{n[d].ranges.forEach(m=>{i.Range.foreach(m,(h,R)=>{const C=t.getValue(o,r,h,R);C?a.push({pattern:C.pattern,row:h,col:R}):u.push({startColumn:R,endColumn:R,startRow:h,endRow:h})})})});const l=[];if(a.length){const d=Pn(o,r,a);Object.keys(d.values).forEach(c=>{const m=d.values[c];m.ranges=Yn(m.ranges)}),l.push({id:Un.id,params:Pn(o,r,a)})}return u.length&&l.push({id:Js.id,params:{unitId:o,subUnitId:r,ranges:u}}),l},Un={id:"sheet.mutation.set.numfmt",type:i.CommandType.MUTATION,handler:(s,e)=>{if(!e)return!1;const{values:t,refMap:n}=e,o=s.get(ot),r=e.unitId,a=e.subUnitId,u=Object.keys(t).reduce((l,d)=>{const c=n[d],m=t[d].ranges;return c&&l.push({...c,ranges:m}),l},[]);return o.setValues(r,a,u),!0}},Js={id:"sheet.mutation.remove.numfmt",type:i.CommandType.MUTATION,handler:(s,e)=>{if(!e)return!1;const{unitId:t,subUnitId:n,ranges:o}=e;return s.get(ot).deleteValues(t,n,o),!0}},Bl=(s,e)=>{const t=s.get(ot),{ranges:n,unitId:o,subUnitId:r}=e,a=[];if(n.forEach(l=>{i.Range.foreach(l,(d,c)=>{const m=t.getValue(o,r,d,c);m&&a.push({pattern:m.pattern,row:d,col:c})})}),!a.length)return[];const u=Pn(o,r,a);return Object.keys(u.values).forEach(l=>{const d=u.values[l];d.ranges=Yn(d.ranges)}),[{id:Un.id,params:u}]},Pn=(s,e,t)=>{const n=Ja(t,"pattern"),o={},r={},a=xa();return Object.keys(n).forEach(u=>{const l=n[u],d=a();o[d]={pattern:u},l.forEach(c=>{r[d]||(r[d]={ranges:[]}),r[d].ranges.push(i.cellToRange(c.row,c.col))})}),{unitId:s,subUnitId:e,refMap:o,values:r}},pi={id:"sheet.mutation.remove-range-theme",type:i.CommandType.MUTATION,handler:(s,e)=>{if(!e)return!1;const{styleName:t,unitId:n}=e;return s.get(g.SheetRangeThemeModel).unregisterRangeThemeStyle(n,t),!0}},wi={id:"sheet.mutation.set-range-theme",type:i.CommandType.MUTATION,handler:(s,e)=>{if(!e)return!1;const{unitId:t,styleName:n,style:o}=e,a=s.get(g.SheetRangeThemeModel).getRangeThemeStyle(t,n);return a&&(o.headerRowStyle&&a.setHeaderRowStyle(o.headerRowStyle),o.firstRowStyle&&a.setFirstRowStyle(o.firstRowStyle),o.secondRowStyle&&a.setSecondRowStyle(o.secondRowStyle),o.lastRowStyle&&a.setLastRowStyle(o.lastRowStyle)),!0}},Mi={id:"sheet.operation.scroll-to-cell",type:i.CommandType.OPERATION,handler:()=>!0},Hl=(s,e,t)=>{const o=s.get(g.SheetsSelectionsService).getCurrentSelections(),{value:r,selections:a,unitId:u,subUnitId:l}=e;if(o){const c=o[(o==null?void 0:o.length)-1].primary;if(c){const{actualColumn:m,actualRow:h}=c;let{startRow:R,startColumn:C,endRow:S,endColumn:I}=a[a.length-1];if(r===i.Dimension.COLUMNS){const w=t.find(y=>y.startColumn===m&&y.endColumn===m&&h===y.startRow);w&&(I=w.endColumn,R=w.startRow,S=w.endRow)}else if(r===i.Dimension.ROWS){const w=t.find(y=>y.startRow===h&&y.endRow===h&&m===y.startColumn);w&&(S=w.endRow,C=w.startColumn,I=w.endColumn)}const v={startRow:R,startColumn:C,endRow:S,endColumn:I,actualRow:h,actualColumn:m,isMerged:!0,isMergedMainCell:R===h&&C===m},M=o.map((w,y,b)=>({range:w.range,style:null,primary:y===b.length-1?v:null})),p={unitId:u,subUnitId:l,type:te.ONLY_SET,selections:M};return{id:q.id,params:p}}return null}return null},Fl=(s,e)=>{const n=s.get(g.SheetsSelectionsService).getCurrentSelections(),{unitId:o,subUnitId:r}=e;if(n&&n[(n==null?void 0:n.length)-1].primary){const l={unitId:o,subUnitId:r,type:te.ONLY_SET,selections:[...n]};return{id:q.id,params:l}}return null},yi="maxCellsPerSheet",jl=3e6;var Gl=Object.getOwnPropertyDescriptor,zl=(s,e,t,n)=>{for(var o=n>1?void 0:n?Gl(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},_i=(s,e)=>(t,n)=>e(t,n,s);const ql="SHEET_DEFINED_NAME_PLUGIN",Yl="AllDefaultWorkbook";g.DefinedNameDataController=class extends i.Disposable{constructor(e,t){super(),this._definedNamesService=e,this._resourceManagerService=t,this._initialize()}_initialize(){this._initSnapshot()}_initSnapshot(){const e=n=>{const o=this._definedNamesService.getDefinedNameMap(n);return o?JSON.stringify(o):""},t=n=>{if(!n)return{};try{return JSON.parse(n)}catch{return{}}};this.disposeWithMe(this._resourceManagerService.registerPluginResource({pluginName:ql,businesses:[i.UniverInstanceType.UNIVER_SHEET],toJson:n=>e(n),parseJson:n=>t(n),onUnLoad:n=>{this._definedNamesService.removeUnitDefinedName(n)},onLoad:(n,o)=>{this._definedNamesService.registerDefinedNames(n,o)}}))}},g.DefinedNameDataController=zl([_i(0,J.IDefinedNamesService),_i(1,i.IResourceManagerService)],g.DefinedNameDataController);const bi="sheets.config",Ei={};var Kl=Object.getOwnPropertyDescriptor,Jl=(s,e,t,n)=>{for(var o=n>1?void 0:n?Kl(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},xs=(s,e)=>(t,n)=>e(t,n,s);const xl=[Ne.id],Xl=[re.id,ie.id,ae.id,ne.id,pe.id,we.id];g.SheetsFreezeSyncController=class extends i.Disposable{constructor(t,n,o){var a,u;super();f(this,"_d",new i.DisposableCollection);f(this,"_enabled",!0);this._univerInstanceService=t,this._commandService=n,this._configService=o;const r=(u=(a=this._configService.getConfig(bi))==null?void 0:a.freezeSync)!=null?u:!0;this.setEnabled(r)}getEnabled(){return this._enabled}setEnabled(t){t?this._d.dispose():this._initOnlyLocalListener(),this._enabled=t}_initOnlyLocalListener(){this._d.add(this._commandService.beforeCommandExecuted((t,n)=>{xl.includes(t.id)&&(n||(n={}),n.onlyLocal=!0)})),this._d.add(this._commandService.onCommandExecuted((t,n)=>{if(Xl.includes(t.id)&&(n!=null&&n.fromCollab)){const{id:o,params:r}=t;o===re.id?this._handleInsertRowMutation(r,n):o===ie.id?this._handleInsertColMutation(r,n):o===ae.id?this._handleRemoveRowMutation(r,n):o===ne.id?this._handleRemoveColMutation(r,n):o===pe.id?this._handleMoveRowsMutation(r,n):o===we.id&&this._handleMoveColsMutation(r,n)}}))}_handleInsertRowMutation(t,n){const{range:o,unitId:r,subUnitId:a}=t,u=this._getFreeze(r,a);if(u&&o.startRow<u.startRow){const l=o.endRow-o.startRow+1,d={...u,startRow:Math.max(1,u.startRow+l),ySplit:Math.max(1,u.ySplit+l)};this._sequenceExecute(r,a,d,n)}}_handleInsertColMutation(t,n){const{range:o,unitId:r,subUnitId:a}=t,u=this._getFreeze(r,a);if(u&&o.startColumn<u.startColumn){const l=o.endColumn-o.startColumn+1,d={...u,startColumn:Math.max(1,u.startColumn+l),xSplit:Math.max(1,u.xSplit+l)};this._sequenceExecute(r,a,d,n)}}_handleRemoveRowMutation(t,n){const{range:o,unitId:r,subUnitId:a}=t,u=this._getFreeze(r,a);if(u&&o.startRow<u.startRow){const l=Math.min(u.startRow,o.endRow+1)-o.startRow,d={...u,startRow:Math.max(1,u.startRow-l),ySplit:Math.max(1,u.ySplit-l)};this._sequenceExecute(r,a,d,n)}}_handleRemoveColMutation(t,n){const{range:o,unitId:r,subUnitId:a}=t,u=this._getFreeze(r,a);if(u&&o.startColumn<u.startColumn){const l=Math.min(u.startColumn,o.endColumn+1)-o.startColumn,d={...u,startColumn:Math.max(1,u.startColumn-l),xSplit:Math.max(1,u.xSplit-l)};this._sequenceExecute(r,a,d,n)}}_handleMoveRowsMutation(t,n){const{sourceRange:o,targetRange:r,unitId:a,subUnitId:u}=t,l=this._getFreeze(a,u);if(!l||l.startRow<=0||o.startRow>=l.startRow&&r.startRow>=l.startRow||o.endRow<l.startRow&&r.endRow<l.startRow)return;const d=o.endRow-o.startRow+1,c=Math.max(Math.min(l.startRow,o.endRow+1)-o.startRow,0),m={...l};r.startRow>=l.startRow?(m.startRow=Math.max(1,l.startRow-c),m.ySplit=Math.max(1,l.ySplit-c)):(m.startRow=l.startRow+d-c,m.ySplit=l.ySplit+d-c),this._sequenceExecute(a,u,m,n)}_handleMoveColsMutation(t,n){const{sourceRange:o,targetRange:r,unitId:a,subUnitId:u}=t,l=this._getFreeze(a,u);if(!l||l.startColumn<=0||o.startColumn>=l.startColumn&&r.startColumn>=l.startColumn||o.endColumn<l.startColumn&&r.endColumn<l.startColumn)return;const d=o.endColumn-o.startColumn+1,c=Math.max(Math.min(l.startColumn,o.endColumn+1)-o.startColumn,0),m={...l};r.startColumn>=l.startColumn?(m.startColumn=Math.max(1,l.startColumn-c),m.xSplit=Math.max(1,l.xSplit-c)):(m.startColumn=l.startColumn+d-c,m.xSplit=l.xSplit+d-c),this._sequenceExecute(a,u,m,n)}_getFreeze(t,n){const o=this._univerInstanceService.getUnit(t,i.UniverInstanceType.UNIVER_SHEET);if(!o)return null;const r=o.getSheetBySheetId(n);return r?r.getFreeze():null}_sequenceExecute(t,n,o,r){i.sequenceExecute([{id:Ne.id,params:{...o,unitId:t,subUnitId:n,resetScroll:!1}}],this._commandService,r)}},g.SheetsFreezeSyncController=Jl([xs(0,i.Inject(i.IUniverInstanceService)),xs(1,i.ICommandService),xs(2,i.IConfigService)],g.SheetsFreezeSyncController);var Zl=Object.getOwnPropertyDescriptor,Ql=(s,e,t,n)=>{for(var o=n>1?void 0:n?Zl(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},Oe=(s,e)=>(t,n)=>e(t,n,s);g.SheetPermissionCheckController=class extends i.Disposable{constructor(t,n,o,r,a,u,l,d,c,m){super();f(this,"disposableCollection",new i.DisposableCollection);f(this,"_triggerPermissionUIEvent$",new O.Subject);f(this,"triggerPermissionUIEvent$",this._triggerPermissionUIEvent$.asObservable());this._commandService=t,this._univerInstanceService=n,this._permissionService=o,this._selectionManagerService=r,this._rangeProtectionRuleModel=a,this._worksheetProtectionRuleModel=u,this._localeService=l,this._lexerTreeBuilder=d,this._contextService=c,this._definedNamesService=m,this._initialize()}blockExecuteWithoutPermission(t){throw this._triggerPermissionUIEvent$.next(t),new i.CustomCommandExecutionError("have no permission")}_getPermissionCheck(t,n){let o=!0,r="";switch(t){case It.id:i.isICellData(n.value)&&n.value.f?(o=this._permissionCheckWithFormula(n),r=this._localeService.t("permission.dialog.formulaErr")):o=this._permissionCheckBySetRangeValue({workbookTypes:[me],rangeTypes:[Se],worksheetTypes:[Wt,fe]},n);break;case fn.id:o=this.permissionCheckWithRanges({workbookTypes:[me],rangeTypes:[Se],worksheetTypes:[Wt,fe]},n==null?void 0:n.ranges,n==null?void 0:n.unitId,n==null?void 0:n.subUnitId),r=this._localeService.t("permission.dialog.editErr");break;case Gt.id:case zt.id:o=this.permissionCheckWithoutRange({worksheetTypes:[St]}),r=this._localeService.t("permission.dialog.setRowColStyleErr");break;case Kt.id:case Jt.id:case Tn.id:o=this.permissionCheckWithoutRange({worksheetTypes:[ft]}),r=this._localeService.t("permission.dialog.setRowColStyleErr");break;case wt.id:case pt.id:o=this._permissionCheckByMoveCommand(n),r=this._localeService.t("permission.dialog.moveRowColErr");break;case Je.id:o=this._permissionCheckByMoveRangeCommand(n),r=this._localeService.t("permission.dialog.moveRangeErr");break;case zs.id:o=this._permissionCheckByWorksheetCommand([me,cn]),r=this._localeService.t("permission.dialog.operatorSheetErr"),o===!1&&this._worksheetProtectionRuleModel.resetOrder();break;case yn.id:o=this._permissionCheckByWorksheetCommand([me,mn]),r=this._localeService.t("permission.dialog.operatorSheetErr"),o===!1&&this._worksheetProtectionRuleModel.resetOrder();break;case Ks.id:{const{unitId:a,subUnitId:u}=n;o=this._permissionCheckByWorksheetCommand([me,ln],a,u),r=this._localeService.t("permission.dialog.operatorSheetErr"),o===!1&&this._worksheetProtectionRuleModel.resetOrder()}break;case Et.id:o=this.permissionCheckWithRanges({workbookTypes:[me],rangeTypes:[Se],worksheetTypes:[fe,St]},n.ranges,n.unitId,n.subUnitId),r=this._localeService.t("permission.dialog.setRowColStyleErr");break;case Tt.id:o=this.permissionCheckWithRanges({workbookTypes:[me],rangeTypes:[Se],worksheetTypes:[fe,ft]},n.ranges,n.unitId,n.subUnitId),r=this._localeService.t("permission.dialog.setRowColStyleErr");break;case $s.id:o=this.permissionCheckWithRanges({workbookTypes:[me],rangeTypes:[Se],worksheetTypes:[fe,St]}),r=this._localeService.t("permission.dialog.setRowColStyleErr");break;case Hs.id:o=this.permissionCheckWithRanges({workbookTypes:[me],rangeTypes:[Se],worksheetTypes:[fe,ft]}),r=this._localeService.t("permission.dialog.setRowColStyleErr");break;case vt.id:o=this._permissionCheckWithInsertRangeMove("right"),r=this._localeService.t("permission.dialog.insertOrDeleteMoveRangeErr");break;case xe.id:o=this._permissionCheckWithInsertRangeMove("bottom"),r=this._localeService.t("permission.dialog.insertOrDeleteMoveRangeErr");break;case Be.id:o=this._permissionCheckWithInsertRangeMove("left"),r=this._localeService.t("permission.dialog.insertOrDeleteMoveRangeErr");break;case He.id:o=this._permissionCheckWithInsertRangeMove("top"),r=this._localeService.t("permission.dialog.insertOrDeleteMoveRangeErr");break}o||this.blockExecuteWithoutPermission(r)}_initialize(){this._commandExecutedListener()}_commandExecutedListener(){this.disposeWithMe(this._commandService.beforeCommandExecuted(t=>{this._getPermissionCheck(t.id,t==null?void 0:t.params)})),this.disposeWithMe(this._commandService.onCommandExecuted(t=>{var n;if(t.id===qt.id){const o=t.params,{unitId:r=(n=this._univerInstanceService.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET))==null?void 0:n.getUnitId(),subUnitId:a}=o;if(!r||!a)return;const u=this._worksheetProtectionRuleModel.getRule(r,a),l=this._rangeProtectionRuleModel.getSubunitRuleList(r,a);u&&this._worksheetProtectionRuleModel.ruleRefresh(u.permissionId),l.length&&this._rangeProtectionRuleModel.ruleRefresh(a)}}))}_permissionCheckWithInsertRangeMove(t){var c;const n=P(this._univerInstanceService);if(!n)return!1;const{worksheet:o,unitId:r,subUnitId:a}=n,u=i.Tools.deepClone((c=this._selectionManagerService.getCurrentLastSelection())==null?void 0:c.range);return!(!u||(t==="top"||t==="bottom"?u.endRow=o.getRowCount()-1:(t==="left"||t==="right")&&(u.endColumn=o.getColumnCount()-1),this._rangeProtectionRuleModel.getSubunitRuleList(r,a).map(m=>m.ranges).flat().some(m=>i.Rectangle.getIntersects(u,m))))}_permissionCheckByWorksheetCommand(t,n,o){var c,m;const r=P(this._univerInstanceService,{unitId:n,subUnitId:o});if(!r)return!1;const{unitId:a,subUnitId:u}=r,l=this._worksheetProtectionRuleModel.getRule(a,u),d=this._rangeProtectionRuleModel.getSubunitRuleList(a,u).length>0;return l||d?(m=(c=this._permissionService.getPermissionPoint(new dn(a).id))==null?void 0:c.value)!=null?m:!1:this._permissionService.composePermission(t.map(h=>new h(a).id)).every(h=>h.value)}permissionCheckWithoutRange(t){var R,C,S,I;const n=P(this._univerInstanceService);if(!n)return!1;const{worksheet:o,unitId:r,subUnitId:a}=n,u=this._selectionManagerService.getCurrentLastSelection();if(!u)return!0;const l=(C=(R=u==null?void 0:u.primary)==null?void 0:R.actualRow)!=null?C:0,d=(I=(S=u==null?void 0:u.primary)==null?void 0:S.actualColumn)!=null?I:0,{workbookTypes:c,worksheetTypes:m,rangeTypes:h}=t;return!(c&&c.some(M=>{var y,b;const p=new M(r);return((b=(y=this._permissionService.getPermissionPoint(p.id))==null?void 0:y.value)!=null?b:!1)===!1})===!0||m&&m.some(M=>{var y,b;const p=new M(r,a);return((b=(y=this._permissionService.getPermissionPoint(p.id))==null?void 0:y.value)!=null?b:!1)===!1})===!0||h&&h.some(M=>{var T,U,k,E,N;const p=(U=(T=o.getCell(l,d))==null?void 0:T.selectionProtection)==null?void 0:U[0];if(!(p!=null&&p.ruleId))return!1;const w=(k=this._rangeProtectionRuleModel.getRule(r,a,p.ruleId))==null?void 0:k.permissionId;if(!w)return!1;const y=new M(r,a,w);return((N=(E=this._permissionService.getPermissionPoint(y.id))==null?void 0:E.value)!=null?N:!1)===!1})===!0)}permissionCheckWithRanges(t,n,o,r){var C;const a=P(this._univerInstanceService);if(!a)return!1;const{workbook:u,worksheet:l}=a;o||(o=u.getUnitId()),r||(r=l.getSheetId());const d=n!=null?n:(C=this._selectionManagerService.getCurrentSelections())==null?void 0:C.map(S=>S.range);if(!d)return!1;const{workbookTypes:c,worksheetTypes:m,rangeTypes:h}=t,R=[];return c&&R.push(...c.map(S=>new S(o).id)),m&&R.push(...m.map(S=>new S(o,r).id)),h&&this._rangeProtectionRuleModel.getSubunitRuleList(o,r).forEach(S=>{d.some(v=>S.ranges.some(M=>i.Rectangle.intersects(M,v)))&&R.push(...h.map(v=>new v(o,r,S.permissionId).id))}),R.length?this._permissionService.composePermission(R).every(S=>S.value):!0}_permissionCheckByMoveCommand(t){const n=P(this._univerInstanceService);if(!n)return!1;const{worksheet:o,unitId:r,subUnitId:a}=n,u=t.toRange;u.endRow===o.getRowCount()-1?u.endColumn=u.startColumn:u.endRow=u.startRow;const l=this._rangeProtectionRuleModel.getSubunitRuleList(r,a).reduce((d,c)=>[...d,...c.ranges],[]).filter(d=>i.Rectangle.intersects(d,u));return l.length>0?!1:(l.forEach(d=>{var c,m;for(let h=d.startRow;h<=d.endRow;h++)for(let R=d.startColumn;R<=d.endColumn;R++){const C=(m=(c=o.getCell(h,R))==null?void 0:c.selectionProtection)==null?void 0:m[0];if((C==null?void 0:C[_.Edit])===!1)return!1}}),!0)}_permissionCheckByMoveRangeCommand(t){const n=P(this._univerInstanceService);if(!n)return!1;const{worksheet:o,unitId:r,subUnitId:a}=n,u=t.toRange,l=this._rangeProtectionRuleModel.getSubunitRuleList(r,a).reduce((d,c)=>[...d,...c.ranges],[]).filter(d=>i.Rectangle.intersects(d,u));return l.length>0?!1:(l.forEach(d=>{var c,m;for(let h=d.startRow;h<=d.endRow;h++)for(let R=d.startColumn;R<=d.endColumn;R++){const C=(m=(c=o.getCell(h,R))==null?void 0:c.selectionProtection)==null?void 0:m[0];if((C==null?void 0:C[_.Edit])===!1)return!1}}),!0)}_permissionCheckBySetRangeValue(t,n){let o=[];n.range?o=[n.range]:o=[new i.ObjectMatrix(n.value).getDataRange()];const{unitId:r,subUnitId:a}=n;return this.permissionCheckWithRanges(t,o,r,a)}_permissionCheckWithFormula(t){var a,u,l,d,c;const n=t.value,o=t.range,r=n.f;if(r){const m=r.substring(1),h=this._univerInstanceService.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET),R=(a=t.unitId)!=null?a:h.getUnitId(),C=this._definedNamesService.getValueByName(R,m);if(C){let S=C.formulaOrRefString;S.startsWith(J.operatorToken.EQUALS)&&(S=S.slice(1));const I=S.split(",");for(let v=0;v<I.length;v++){const M=I[v],p=J.deserializeRangeWithSheet(M);if(p.sheetName){const w=h.getSheetBySheetName(p.sheetName);if(!w)return!0;const{startRow:y,endRow:b,startColumn:T,endColumn:U}=p.range;for(let k=y;k<=b;k++)for(let E=T;E<=U;E++){const N=(l=(u=w.getCell(k,E))==null?void 0:u.selectionProtection)==null?void 0:l[0];if((N==null?void 0:N[_.View])===!1)return!1}}}return!0}else{const S=this._lexerTreeBuilder.sequenceNodesBuilder(r);if(!S)return!0;for(let I=0;I<S.length;I++){const v=S[I];if(typeof v=="string"||v.nodeType!==J.sequenceNodeType.REFERENCE)continue;const{token:M}=v,p=J.deserializeRangeWithSheetWithCache(M),w=p.unitId?this._univerInstanceService.getUnit(p.unitId):this._univerInstanceService.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET);if(!w)return!0;let y=p.sheetName?w.getSheetBySheetName(p.sheetName):w.getActiveSheet();const b=w.getUnitId();if(p.sheetName){if(y=w.getSheetBySheetName(p.sheetName),!y)return!0;const N=y==null?void 0:y.getSheetId();if(!this._permissionService.getPermissionPoint(new Vt(b,N).id))return!1}if(!y)return!0;const{startRow:T,endRow:U,startColumn:k,endColumn:E}=p.range;for(let N=T;N<=U;N++)for(let W=k;W<=E;W++){const V=(c=(d=y.getCell(N,W))==null?void 0:d.selectionProtection)==null?void 0:c[0];if((V==null?void 0:V[_.View])===!1)return!1}}return!0}}if(o){const m=P(this._univerInstanceService);if(!m)return!1;const h=t.unitId||m.unitId,R=t.subUnitId||m.subUnitId,S=this._rangeProtectionRuleModel.getSubunitRuleList(h,R).filter(v=>v.ranges.some(M=>i.Rectangle.intersects(M,o))).map(v=>new Se(h,R,v.permissionId).id);if(!this._permissionService.composePermission(S).every(v=>v.value))return!1}return!0}},g.SheetPermissionCheckController=Ql([Oe(0,i.ICommandService),Oe(1,i.IUniverInstanceService),Oe(2,i.IPermissionService),Oe(3,i.Inject(g.SheetsSelectionsService)),Oe(4,i.Inject(X)),Oe(5,i.Inject(ke)),Oe(6,i.Inject(i.LocaleService)),Oe(7,i.Inject(J.LexerTreeBuilder)),Oe(8,i.IContextService),Oe(9,J.IDefinedNamesService)],g.SheetPermissionCheckController);var ed=Object.getOwnPropertyDescriptor,td=(s,e,t,n)=>{for(var o=n>1?void 0:n?ed(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},xt=(s,e)=>(t,n)=>e(t,n,s);g.WorkbookPermissionService=class extends i.Disposable{constructor(t,n,o,r,a){super();f(this,"_unitPermissionInitStateChange",new O.BehaviorSubject(!1));f(this,"unitPermissionInitStateChange$",this._unitPermissionInitStateChange.asObservable());this._permissionService=t,this._univerInstanceService=n,this._rangeProtectionRuleModel=o,this._worksheetProtectionRuleModel=r,this._worksheetProtectionPointModel=a,this._init()}_init(){const t=n=>{const o=n.getUnitId();Pt().forEach(r=>{const a=new r(o);this._permissionService.addPermissionPoint(a)})};this._univerInstanceService.getAllUnitsForType(i.UniverInstanceType.UNIVER_SHEET).forEach(n=>{t(n)}),this.disposeWithMe(this._univerInstanceService.getTypeOfUnitAdded$(i.UniverInstanceType.UNIVER_SHEET).subscribe(n=>{t(n)})),this.disposeWithMe(this._univerInstanceService.getTypeOfUnitDisposed$(i.UniverInstanceType.UNIVER_SHEET).subscribe(n=>{const o=n.getUnitId();n.getSheets().forEach(r=>{const a=r.getSheetId();this._rangeProtectionRuleModel.getSubunitRuleList(o,a).forEach(l=>{[...le()].forEach(d=>{const c=new d(o,a,l.permissionId);this._permissionService.deletePermissionPoint(c.id)})}),[...de(),...Ie()].forEach(l=>{const d=new l(o,a);this._permissionService.deletePermissionPoint(d.id)})}),Pt().forEach(r=>{const a=new r(o);this._permissionService.deletePermissionPoint(a.id)}),this._rangeProtectionRuleModel.deleteUnitModel(o),this._worksheetProtectionPointModel.deleteUnitModel(o),this._worksheetProtectionRuleModel.deleteUnitModel(o)}))}changeUnitInitState(t){this._unitPermissionInitStateChange.next(t)}},g.WorkbookPermissionService=td([xt(0,i.Inject(i.IPermissionService)),xt(1,i.Inject(i.IUniverInstanceService)),xt(2,i.Inject(X)),xt(3,i.Inject(ke)),xt(4,i.Inject(Ut))],g.WorkbookPermissionService);var nd=Object.getOwnPropertyDescriptor,sd=(s,e,t,n)=>{for(var o=n>1?void 0:n?nd(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},De=(s,e)=>(t,n)=>e(t,n,s);g.SheetPermissionInitController=class extends i.Disposable{constructor(e,t,n,o,r,a,u,l,d,c){super(),this._univerInstanceService=e,this._permissionService=t,this._authzIoService=n,this._rangeProtectionRuleModel=o,this._worksheetProtectionRuleModel=r,this._userManagerService=a,this._worksheetProtectionPointRuleModel=u,this._workbookPermissionService=l,this._undoRedoService=d,this._commandService=c}initPermission(){this._initRangePermissionFromSnapshot(),this._initRangePermissionChange(),this._initWorksheetPermissionFromSnapshot(),this._initWorksheetPermissionChange(),this._initWorksheetPermissionPointsChange(),this._initWorkbookPermissionFromSnapshot(),this._initUserChange(),this._refreshPermissionByCollaCreate()}refreshRangeProtectPermission(){this._initRangePermissionFromSnapshot()}async _initRangePermissionFromSnapshot(){const e=async t=>{const n=[],o=t.getUnitId(),r=t.getSheets(),a=new Map;if(r.forEach(u=>{const l=u.getSheetId();this._rangeProtectionRuleModel.getSubunitRuleList(o,l).forEach(d=>{a.set(d.permissionId,d),n.push({objectID:d.permissionId,unitID:o,objectType:D.SelectRange,actions:Ge})})}),!n.length){this._rangeProtectionRuleModel.changeRuleInitState(!0);return}this._authzIoService.batchAllowed(n).then(u=>{u.forEach(l=>{const d=a.get(l.objectID);if(d){if(!this._rangeProtectionRuleModel.getRule(o,d.subUnitId,d.id))return;le().forEach(m=>{const h=new m(o,d.subUnitId,l.objectID),R=h.subType,C=l.actions.find(S=>S.action===R);(C==null?void 0:C.allowed)!==void 0&&this._permissionService.updatePermissionPoint(h.id,C.allowed)})}}),this._rangeProtectionRuleModel.changeRuleInitState(!0)})};await Promise.all(this._univerInstanceService.getAllUnitsForType(i.UniverInstanceType.UNIVER_SHEET).map(t=>e(t))),this._rangeProtectionRuleModel.changeRuleInitState(!0)}_initRangePermissionChange(){this.disposeWithMe(this._rangeProtectionRuleModel.ruleChange$.subscribe(e=>{e.type!=="delete"?this._authzIoService.allowed({objectID:e.rule.permissionId,unitID:e.unitId,objectType:D.SelectRange,actions:Ge}).then(t=>{this._rangeProtectionRuleModel.getRule(e.unitId,e.subUnitId,e.rule.id)&&(le().forEach(o=>{if(e.type==="set"){const{rule:d,oldRule:c}=e;if(d.permissionId===(c==null?void 0:c.permissionId))return}const r=e.rule,a=new o(r.unitId,r.subUnitId,r.permissionId),u=a.subType,l=t.find(d=>d.action===u);l&&this._permissionService.updatePermissionPoint(a.id,l.allowed)}),this._rangeProtectionRuleModel.ruleRefresh(e.rule.permissionId))}):this._rangeProtectionRuleModel.getSubunitRuleList(e.unitId,e.subUnitId).length===0&&(this._worksheetProtectionPointRuleModel.deleteRule(e.unitId,e.subUnitId),[...Ie()].forEach(n=>{const o=new n(e.unitId,e.subUnitId);this._permissionService.updatePermissionPoint(o.id,o.value)}))}))}async initWorkbookPermissionChange(e){var n;const t=e||((n=this._univerInstanceService.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET))==null?void 0:n.getUnitId());if(t)return this._authzIoService.allowed({objectID:t,objectType:D.Workbook,unitID:t,actions:li}).then(o=>{Pt().forEach(r=>{const a=new r(t),u=a.subType,l=o.find(d=>d.action===u);l&&this._permissionService.updatePermissionPoint(a.id,l.allowed)})})}async _initWorkbookPermissionFromSnapshot(){await Promise.all(this._univerInstanceService.getAllUnitsForType(i.UniverInstanceType.UNIVER_SHEET).map(e=>this.initWorkbookPermissionChange(e.getUnitId()))),this._workbookPermissionService.changeUnitInitState(!0)}_initWorksheetPermissionChange(){this.disposeWithMe(this._worksheetProtectionRuleModel.ruleChange$.subscribe(e=>{e.type!=="delete"?this._authzIoService.allowed({objectID:e.rule.permissionId,unitID:e.unitId,objectType:D.Worksheet,actions:Ge}).then(t=>{const n=this._worksheetProtectionRuleModel.getRule(e.unitId,e.subUnitId);!n||n.permissionId!==e.rule.permissionId||(de().forEach(o=>{const r=new o(e.unitId,e.subUnitId),a=r.subType,u=t.find(l=>l.action===a);u&&this._permissionService.updatePermissionPoint(r.id,u.allowed)}),this._worksheetProtectionRuleModel.ruleRefresh(e.rule.permissionId))}):([...de(),...Ie()].forEach(t=>{const n=new t(e.unitId,e.subUnitId);this._permissionService.updatePermissionPoint(n.id,!0)}),this._worksheetProtectionPointRuleModel.deleteRule(e.unitId,e.subUnitId))}))}_initWorksheetPermissionPointsChange(){this.disposeWithMe(this._worksheetProtectionPointRuleModel.pointChange$.subscribe(e=>{this._authzIoService.allowed({objectID:e.permissionId,unitID:e.unitId,objectType:D.Worksheet,actions:_n}).then(t=>{const n=this._worksheetProtectionPointRuleModel.getRule(e.unitId,e.subUnitId);!n||n.permissionId!==e.permissionId||Ie().forEach(o=>{const r=new o(e.unitId,e.subUnitId),a=r.subType,u=t.find(l=>l.action===a);u&&this._permissionService.updatePermissionPoint(r.id,u.allowed)})})}))}async _initWorksheetPermissionFromSnapshot(){const e=async t=>{const n=[],o=t.getUnitId(),r=t.getSheets(),a=new Map;if(r.forEach(u=>{const l=u.getSheetId(),d=this._worksheetProtectionRuleModel.getRule(o,l);d&&(a.set(d.permissionId,d),n.push({objectID:d.permissionId,unitID:o,objectType:D.Worksheet,actions:Ge}));const c=this._worksheetProtectionPointRuleModel.getRule(o,l);c&&(a.set(c.permissionId,c),n.push({objectID:c.permissionId,unitID:o,objectType:D.Worksheet,actions:_n}))}),!n.length){this._worksheetProtectionRuleModel.changeRuleInitState(!0);return}this._authzIoService.batchAllowed(n).then(u=>{u.forEach(l=>{const d=a.get(l.objectID);if(d){const c=this._worksheetProtectionRuleModel.getRule(o,d.subUnitId)||this._worksheetProtectionPointRuleModel.getRule(o,d.subUnitId);if(!c||c.permissionId!==l.objectID)return;[...de(),...Ie()].forEach(m=>{const h=new m(o,d.subUnitId),R=h.subType,C=l.actions.find(S=>S.action===R);(C==null?void 0:C.allowed)!==void 0&&this._permissionService.updatePermissionPoint(h.id,C.allowed)})}}),this._worksheetProtectionRuleModel.changeRuleInitState(!0)})};await Promise.all(this._univerInstanceService.getAllUnitsForType(i.UniverInstanceType.UNIVER_SHEET).map(t=>e(t))),this._worksheetProtectionRuleModel.changeRuleInitState(!0)}_initUserChange(){this.disposeWithMe(this._userManagerService.currentUser$.pipe(O.skip(1)).subscribe(()=>{const e=this._permissionService.getAllPermissionPoint();this._permissionService.clearPermissionMap(),this._worksheetProtectionRuleModel.changeRuleInitState(!1),this._univerInstanceService.getAllUnitsForType(i.UniverInstanceType.UNIVER_SHEET).forEach(n=>{const o=n.getUnitId();Pt().forEach(r=>{let a=new r(o);e.has(a.id)&&(a=e.get(a.id)),this._permissionService.addPermissionPoint(a)}),n.getSheets().forEach(r=>{const a=r.getSheetId();[...de(),...Ie()].forEach(l=>{let d=new l(o,a);e.has(d.id)&&(d=e.get(d.id)),this._permissionService.addPermissionPoint(d)}),this._rangeProtectionRuleModel.getSubunitRuleList(o,a).forEach(l=>{le().forEach(d=>{let c=new d(o,a,l.permissionId);e.has(c.id)&&(c=e.get(c.id)),this._permissionService.addPermissionPoint(c)})})}),this._initWorkbookPermissionFromSnapshot(),this._initWorksheetPermissionFromSnapshot(),this._initRangePermissionFromSnapshot()})}))}refreshPermission(e,t){const n=this._worksheetProtectionRuleModel.getTargetByPermissionId(e,t);let o=!1;if(n){const[u,l]=n;this._authzIoService.allowed({objectID:t,unitID:e,objectType:D.Worksheet,actions:Ge}).then(d=>{if(!this._worksheetProtectionRuleModel.getTargetByPermissionId(e,t))return;let m="";de().forEach(h=>{var I;const R=new h(e,l),C=R.subType,S=d.find(v=>v.action===C);S&&(((I=this._permissionService.getPermissionPoint(R.id))==null?void 0:I.value)!==S.allowed&&(o=!0),this._permissionService.updatePermissionPoint(R.id,S.allowed),m+=`${S.action}_${S.allowed}`)}),this._worksheetProtectionRuleModel.ruleRefresh(`${t}_${m}`),o&&this._undoRedoService.clearUndoRedo(e)})}const r=this._worksheetProtectionPointRuleModel.getTargetByPermissionId(e,t);if(r){const[u,l]=r;this._authzIoService.allowed({objectID:t,unitID:e,objectType:D.Worksheet,actions:_n}).then(d=>{this._worksheetProtectionPointRuleModel.getTargetByPermissionId(e,t)&&(Ie().forEach(m=>{var S;const h=new m(e,l),R=h.subType,C=d.find(I=>I.action===R);C&&(((S=this._permissionService.getPermissionPoint(h.id))==null?void 0:S.value)!==C.allowed&&(o=!0),this._permissionService.updatePermissionPoint(h.id,C.allowed))}),o&&this._undoRedoService.clearUndoRedo(e))})}const a=this._rangeProtectionRuleModel.getTargetByPermissionId(e,t);if(a){const[u,l]=a;this._authzIoService.allowed({objectID:t,unitID:e,objectType:D.SelectRange,actions:Ge}).then(d=>{if(!this._rangeProtectionRuleModel.getTargetByPermissionId(e,t))return;let m="";le().forEach(h=>{var I;const R=new h(e,l,t),C=R.subType,S=d.find(v=>v.action===C);S&&(((I=this._permissionService.getPermissionPoint(R.id))==null?void 0:I.value)!==S.allowed&&(o=!0),this._permissionService.updatePermissionPoint(R.id,S.allowed),m+=`${S.action}_${S.allowed}`)}),this._rangeProtectionRuleModel.ruleRefresh(`${t}_${m}`),o&&this._undoRedoService.clearUndoRedo(e)})}}_refreshPermissionByCollaCreate(){this.disposeWithMe(this._commandService.onCommandExecuted((e,t)=>{if(t!=null&&t.fromCollab&&(e.id===Ce.id||e.id===Fe.id||e.id===bn.id)){const n=e.params;this._undoRedoService.clearUndoRedo(n.unitId)}}))}},g.SheetPermissionInitController=sd([De(0,i.IUniverInstanceService),De(1,i.IPermissionService),De(2,i.IAuthzIoService),De(3,i.Inject(X)),De(4,i.Inject(ke)),De(5,i.Inject(i.UserManagerService)),De(6,i.Inject(Ut)),De(7,i.Inject(g.WorkbookPermissionService)),De(8,i.Inject(i.IUndoRedoService)),De(9,i.Inject(i.ICommandService))],g.SheetPermissionInitController);var od=Object.getOwnPropertyDescriptor,rd=(s,e,t,n)=>{for(var o=n>1?void 0:n?od(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},Xs=(s,e)=>(t,n)=>e(t,n,s);g.ZebraCrossingCacheController=class extends i.Disposable{constructor(t,n,o){super();f(this,"_zebraCacheUpdateSubject",new O.Subject);this._commandService=t,this._sheetRangeThemeModel=n,this._univerInstanceService=o,this._init()}_init(){this._initializeCommandListener(),this._initTriggerCacheUpdateListener()}updateZebraCrossingCache(t,n){this._zebraCacheUpdateSubject.next({unitId:t,subUnitId:n})}_initializeCommandListener(){this.disposeWithMe(this._commandService.onCommandExecuted(t=>{const{id:n}=t;let o,r;switch(n){case re.id:{const a=t.params;o=a.unitId,r=a.subUnitId}break;case Ye.id:{const a=t.params;o=a.unitId,r=a.subUnitId}break;case Ke.id:{const a=t.params;o=a.unitId,r=a.subUnitId}break;case ae.id:{const a=t.params;o=a.unitId,r=a.subUnitId}break;case Ee.id:{const a=t.params;o=a.unitId,r=a.subUnitId}break}o&&r&&(this._sheetRangeThemeModel.refreshSheetRowVisibleFuncSet(o,r),this._sheetRangeThemeModel.refreshZebraCrossingCacheBySheet(o,r))}))}_initTriggerCacheUpdateListener(){this.disposeWithMe(this._zebraCacheUpdateSubject.subscribe(({unitId:t,subUnitId:n})=>{this._sheetRangeThemeModel.refreshSheetRowVisibleFuncSet(t,n),this._sheetRangeThemeModel.refreshZebraCrossingCacheBySheet(t,n)}))}},g.ZebraCrossingCacheController=rd([Xs(0,i.Inject(i.ICommandService)),Xs(1,i.Inject(g.SheetRangeThemeModel)),Xs(2,i.Inject(i.IUniverInstanceService))],g.ZebraCrossingCacheController);var id=Object.getOwnPropertyDescriptor,ad=(s,e,t,n)=>{for(var o=n>1?void 0:n?id(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},Ti=(s,e)=>(t,n)=>e(t,n,s);g.RangeProtectionRenderModel=class{constructor(e,t){f(this,"_cache",new i.LRUMap(1e4));this._selectionProtectionRuleModel=e,this._permissionService=t,this._init()}_init(){this._permissionService.permissionPointUpdate$.pipe(kt.filter(e=>e.type===D.SelectRange),kt.filter(e=>le().some(t=>e instanceof t)),kt.map(e=>e)).subscribe(e=>{const t=this._selectionProtectionRuleModel.getSubunitRuleList(e.unitId,e.subUnitId);for(const n of t)n.permissionId===e.permissionId&&n.ranges.forEach(o=>{i.Range.foreach(o,(r,a)=>{const u=this._createKey(e.unitId,e.subUnitId,r,a);this._cache.delete(u)})})}),this._selectionProtectionRuleModel.ruleChange$.subscribe(e=>{var t;e.rule.ranges.forEach(n=>{i.Range.foreach(n,(o,r)=>{const a=this._createKey(e.unitId,e.subUnitId,o,r);this._cache.delete(a)})}),e.type==="set"&&((t=e.oldRule)==null||t.ranges.forEach(n=>{i.Range.foreach(n,(o,r)=>{const a=this._createKey(e.unitId,e.subUnitId,o,r);this._cache.delete(a)})}))})}_createKey(e,t,n,o){return`${e}_${t}_${n}_${o}`}getCellInfo(e,t,n,o){const r=this._selectionProtectionRuleModel.getSubunitRuleList(e,t),a=[];if(!r||!r.length)return a;const u=this._createKey(e,t,n,o),l=this._cache.get(u);if(l)return l;const d=[];for(const c of r)if(c.ranges.some(m=>m.startRow<=n&&m.endRow>=n&&m.startColumn<=o&&m.endColumn>=o)){const m=le().reduce((h,R)=>{var I;const C=new R(e,t,c.permissionId),S=this._permissionService.getPermissionPoint(C.id);return h[C.subType]=(I=S==null?void 0:S.value)!=null?I:C.value,h},{});d.push({...m,ruleId:c.id,ranges:c.ranges})}return this._cache.set(u,d),d}clear(){this._cache.clear()}},g.RangeProtectionRenderModel=ad([Ti(0,i.Inject(X)),Ti(1,i.Inject(i.IPermissionService))],g.RangeProtectionRenderModel);var ud=Object.getOwnPropertyDescriptor,ld=(s,e,t,n)=>{for(var o=n>1?void 0:n?ud(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},Zs=(s,e)=>(t,n)=>e(t,n,s);g.RangeProtectionCache=class extends i.Disposable{constructor(t,n,o){super();f(this,"_cellRuleCache",new Map);f(this,"_permissionIdCache",new Map);f(this,"_cellInfoCache",new Map);f(this,"_rowInfoCache",new Map);f(this,"_colInfoCache",new Map);this._ruleModel=t,this._permissionService=n,this._univerInstanceService=o,this._initUpdateCellRuleCache(),this._initUpdateCellInfoCache(),this._initUpdateRowColInfoCache(),this._initCache()}_initCache(){this._univerInstanceService.getAllUnitsForType(i.UniverInstanceType.UNIVER_SHEET).forEach(t=>{t.getSheets().forEach(n=>{const o=t.getUnitId(),r=n.getSheetId();this.reBuildCache(o,r)})})}_initUpdateCellInfoCache(){this._permissionService.permissionPointUpdate$.pipe(O.filter(t=>t.type===D.SelectRange),O.map(t=>t)).subscribe(t=>{const{subUnitId:n,unitId:o,permissionId:r}=t,a=this._permissionIdCache.get(r);if(!a)return;const u=this._ruleModel.getRule(o,n,a);if(!u)return;const l=this._ensureCellInfoMap(o,n);u.ranges.forEach(d=>{const{startRow:c,endRow:m,startColumn:h,endColumn:R}=d;for(let C=c;C<=m;C++)for(let S=h;S<=R;S++)l.delete(`${C}-${S}`)})}),this._ruleModel.ruleChange$.subscribe(t=>{var a;const{unitId:n,subUnitId:o}=t,r=this._ensureCellInfoMap(n,o);t.rule.ranges.forEach(u=>{i.Range.foreach(u,(l,d)=>{r.delete(`${l}-${d}`)})}),t.type==="set"&&((a=t.oldRule)==null||a.ranges.forEach(u=>{i.Range.foreach(u,(l,d)=>{this._cellInfoCache.delete(`${l}-${d}`)})}))})}_initUpdateCellRuleCache(){this._ruleModel.ruleChange$.subscribe(t=>{const{type:n}=t;n==="add"?this._addCellRuleCache(t):n==="delete"?this._deleteCellRuleCache(t):(this._deleteCellRuleCache({...t,rule:t.oldRule}),this._addCellRuleCache(t))})}_ensureRuleMap(t,n){let o=this._cellRuleCache.get(t);o||(o=new Map,this._cellRuleCache.set(t,o));let r=o.get(n);return r||(r=new Map,o.set(n,r)),r}_ensureCellInfoMap(t,n){let o=this._cellInfoCache.get(t);o||(o=new Map,this._cellInfoCache.set(t,o));let r=o.get(n);return r||(r=new Map,o.set(n,r)),r}_ensureRowColInfoMap(t,n,o){let r=o==="row"?this._rowInfoCache.get(t):this._colInfoCache.get(t);r||(r=new Map,o==="row"?this._rowInfoCache.set(t,r):this._colInfoCache.set(t,r));let a=r.get(n);return a||(a=new Map,r.set(n,a)),a}_addCellRuleCache(t){const{subUnitId:n,unitId:o,rule:r}=t,a=this._ensureRuleMap(o,n);r.ranges.forEach(u=>{const{startRow:l,endRow:d,startColumn:c,endColumn:m}=u;for(let h=l;h<=d;h++)for(let R=c;R<=m;R++)a.set(`${h}-${R}`,r.id)}),this._permissionIdCache.set(r.permissionId,r.id)}_deleteCellRuleCache(t){const{subUnitId:n,unitId:o,rule:r}=t,a=this._ensureRuleMap(o,n),u=this._ensureCellInfoMap(o,n);r.ranges.forEach(l=>{const{startRow:d,endRow:c,startColumn:m,endColumn:h}=l;for(let R=d;R<=c;R++)for(let C=m;C<=h;C++)a.delete(`${R}-${C}`),u.delete(`${R}-${C}`)}),this._permissionIdCache.delete(r.permissionId)}_getSelectionActions(t,n,o){var c,m,h,R,C,S,I,v,M,p,w,y;const r=(h=(m=this._permissionService.getPermissionPoint((c=new Se(t,n,o.permissionId))==null?void 0:c.id))==null?void 0:m.value)!=null?h:!0,a=(S=(C=this._permissionService.getPermissionPoint((R=new un(t,n,o.permissionId))==null?void 0:R.id))==null?void 0:C.value)!=null?S:!0,u=(M=(v=this._permissionService.getPermissionPoint((I=new Ys(t,n,o.permissionId))==null?void 0:I.id))==null?void 0:v.value)!=null?M:!1,l=(y=(w=this._permissionService.getPermissionPoint((p=new qs(t,n,o.permissionId))==null?void 0:p.id))==null?void 0:w.value)!=null?y:!1;return{[_.Edit]:r,[_.View]:a,[_.ManageCollaborator]:u,[_.Delete]:l}}reBuildCache(t,n){const o=this._ensureRuleMap(t,n),r=this._ensureCellInfoMap(t,n);o.clear(),r.clear();const a=this._ensureRowColInfoMap(t,n,"row"),u=this._ensureRowColInfoMap(t,n,"col");a.clear(),u.clear(),this._ruleModel.getSubunitRuleList(t,n).forEach(l=>{const d=this._getSelectionActions(t,n,l),c={...d,ruleId:l.id,ranges:l.ranges};l.ranges.forEach(m=>{const{startRow:h,endRow:R,startColumn:C,endColumn:S}=m;for(let I=h;I<=R;I++){const v=a.get(`${I}`);v?v.set(l.id,d):a.set(`${I}`,new Map([[l.id,d]]));for(let M=C;M<=S;M++){o.set(`${I}-${M}`,l.id),r.set(`${I}-${M}`,c);const p=u.get(`${M}`);p?p.set(l.id,d):u.set(`${M}`,new Map([[l.id,d]]))}}}),this._permissionIdCache.set(l.permissionId,l.id)})}getRowPermissionInfo(t,n,o,r){var l;const a=(l=this._rowInfoCache.get(t))==null?void 0:l.get(n);if(!a)return!0;const u=a.get(`${o}`);return u?r.every(d=>{for(const c of u.values())if(c[d]===!1)return!1;return!0}):!0}getColPermissionInfo(t,n,o,r){var l;const a=(l=this._colInfoCache.get(t))==null?void 0:l.get(n);if(!a)return!0;const u=a.get(`${o}`);return u?r.every(d=>{for(const c of u.values())if(c[d]===!1)return!1;return!0}):!0}_initUpdateRowColInfoCache(){this._permissionService.permissionPointUpdate$.pipe(O.filter(t=>t.type===D.SelectRange),O.map(t=>t)).subscribe({next:t=>{const{subUnitId:n,unitId:o,permissionId:r}=t,a=this._permissionIdCache.get(r);if(!a)return;const u=this._ruleModel.getRule(o,n,a);if(!u)return;const l=this._ensureRowColInfoMap(o,n,"row"),d=this._ensureRowColInfoMap(o,n,"col"),c=this._getSelectionActions(o,n,u);u.ranges.forEach(m=>{const{startRow:h,endRow:R,startColumn:C,endColumn:S}=m;for(let I=h;I<=R;I++){const v=l.get(`${I}`);v?v.set(a,c):l.set(`${I}`,new Map([[a,c]]));for(let M=C;M<=S;M++){const p=d.get(`${M}`);p?p.set(a,c):d.set(`${M}`,new Map([[a,c]]))}}})}}),this._ruleModel.ruleChange$.subscribe(t=>{if(t.type==="delete"){const{unitId:n,subUnitId:o,rule:r}=t,a=this._ensureRowColInfoMap(n,o,"row"),u=this._ensureRowColInfoMap(n,o,"col");r.ranges.forEach(l=>{const{startRow:d,endRow:c,startColumn:m,endColumn:h}=l;for(let R=d;R<=c;R++){const C=a.get(`${R}`);C==null||C.delete(r.id);for(let S=m;S<=h;S++){const I=u.get(`${S}`);I==null||I.delete(r.id)}}})}})}getCellInfo(t,n,o,r){var c,m;const a=this._ensureCellInfoMap(t,n),u=a.get(`${o}-${r}`);if(u)return u;const l=(m=(c=this._cellRuleCache.get(t))==null?void 0:c.get(n))==null?void 0:m.get(`${o}-${r}`);if(!l)return;const d=this._ruleModel.getRule(t,n,l);if(d){const R={...this._getSelectionActions(t,n,d),ruleId:l,ranges:d.ranges};return a.set(`${o}-${r}`,R),R}}deleteUnit(t){this._cellRuleCache.delete(t),this._cellInfoCache.delete(t),this._rowInfoCache.delete(t),this._colInfoCache.delete(t);const n=this._univerInstanceService.getUnit(t);n==null||n.getSheets().forEach(o=>{const r=o.getSheetId();this._ruleModel.getSubunitRuleList(t,r).forEach(a=>{this._permissionIdCache.delete(a.permissionId)})})}},g.RangeProtectionCache=ld([Zs(0,i.Inject(X)),Zs(1,i.Inject(i.IPermissionService)),Zs(2,i.Inject(i.IUniverInstanceService))],g.RangeProtectionCache);const Ui="ONLY_REGISTER_FORMULA_RELATED_MUTATIONS_KEY";var dd=Object.getOwnPropertyDescriptor,cd=(s,e,t,n)=>{for(var o=n>1?void 0:n?dd(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},Qs=(s,e)=>(t,n)=>e(t,n,s);let kn=class extends i.Disposable{constructor(s,e,t){var o;super(),this._commandService=s,this._configService=e,this._dataSyncPrimaryController=t,[F,ie,re,yt,Le,pe,we,ne,ae,Xe,G,Js,j,Fs,qt,Un,Ot,fi,Ke,Ye,Ii,vi].forEach(r=>{var a;this._commandService.registerCommand(r),(a=this._dataSyncPrimaryController)==null||a.registerSyncingMutations(r)}),((o=this._configService.getConfig(Ui))!=null?o:!1)||[Pr,sn,fn,on,As,Be,He,Gt,Kt,or,sr,rr,ir,ys,ye,xe,vt,Qo,Zo,tr,er,Ms,Me,Ar,wt,Je,pt,_s,Lt,bs,$t,vn,Rn,Vr,Qr,Xr,Zr,Hr,Br,bt,$r,Lr,wn,ut,lt,zt,Fr,at,Gr,Ne,zr,ti,It,Jt,Mn,Kr,ct,$s,Hs,Et,Tt,ee,oi,jt,xr,si,ni,ei,js,Gs,Ct,ui,je,yn,zs,Yt,zn,Ee,Tn,Re,Ve,mi,gt,ri,mt,Ho,q,Mi,Dr,Ws,Ls,Ks,Ri,Rt,qr,dt,di,Fe,st,tt,bn,Ao,Yr,kr,Tr,Nr,ci,Ce,Te,Q,gi,ht,ii,hi,it,rt,In,_t,Ci,Wr,Ur,Or,Si,wi,pi].forEach(r=>this.disposeWithMe(this._commandService.registerCommand(r))),this._configService.setConfig(yi,jl)}};kn=cd([Qs(0,i.ICommandService),Qs(1,i.IConfigService),Qs(2,i.Optional(Bi.DataSyncPrimaryController))],kn);var md=Object.getOwnPropertyDescriptor,hd=(s,e,t,n)=>{for(var o=n>1?void 0:n?md(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},Pi=(s,e)=>(t,n)=>e(t,n,s);let Nn=class extends i.Disposable{constructor(s,e){super(),this._univerInstanceService=s,this._commandService=e,this._initialize()}_initialize(){this.disposeWithMe(this._commandService.onCommandExecuted(s=>{if(s.id!==J.SetFormulaCalculationResultMutation.id)return;const e=s.params,{unitData:t}=e,n=Object.keys(t),o=[];for(let a=0;a<n.length;a++){const u=n[a],l=t[u];if(l==null)continue;const d=Object.keys(l);for(let c=0;c<d.length;c++){const m=d[c],h=l[m];if(h==null)continue;const R=this._getMergedCellData(u,m,h),C={subUnitId:m,unitId:u,cellValue:R};o.push({id:F.id,params:C})}}return o.every(a=>this._commandService.executeCommand(a.id,a.params,{onlyLocal:!0,fromFormula:!0}))}))}_getMergedCellData(s,e,t){const n=this._univerInstanceService.getUniverSheetInstance(s),o=n==null?void 0:n.getStyles(),r=n==null?void 0:n.getSheetBySheetId(e),a=r==null?void 0:r.getCellMatrix(),u=new i.ObjectMatrix(t);return u.forValue((l,d,c)=>{const m=a==null?void 0:a.getValue(l,d),h=J.handleNumfmtInCell(m,c,o);u.setValue(l,d,h)}),u.getMatrix()}};Nn=hd([Pi(0,i.Inject(i.IUniverInstanceService)),Pi(1,i.ICommandService)],Nn);var gd=Object.getOwnPropertyDescriptor,Rd=(s,e,t,n)=>{for(var o=n>1?void 0:n?gd(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},Cd=(s,e)=>(t,n)=>e(t,n,s);let On=class extends i.Disposable{constructor(s){super(),this._sheetInterceptorService=s,this._initialize()}_initialize(){this._initInterceptorCellContent()}_initInterceptorCellContent(){this.disposeWithMe(this._sheetInterceptorService.intercept(Ae.CELL_CONTENT,{priority:11,effect:i.InterceptorEffectEnum.Value|i.InterceptorEffectEnum.Style,handler:(s,e,t)=>{var o;if(!s)return t(s);const n=e.workbook.getStyles().getStyleByCell(s);return i.isDefaultFormat((o=n==null?void 0:n.n)==null?void 0:o.pattern)&&(s==null?void 0:s.t)===i.CellValueType.NUMBER&&s.v!==void 0&&s.v!==null&&i.isRealNum(s.v)&&((!s||s===e.rawData)&&(s={...e.rawData}),s.v=J.stripErrorMargin(Number(s.v))),t(s)}}))}};On=Rd([Cd(0,i.Inject(g.SheetInterceptorService))],On);var Sd=Object.getOwnPropertyDescriptor,fd=(s,e,t,n)=>{for(var o=n>1?void 0:n?Sd(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},Dn=(s,e)=>(t,n)=>e(t,n,s);let An=class extends i.Disposable{constructor(s,e,t,n){super(),this._permissionService=s,this._worksheetProtectionRuleModel=e,this._sheetInterceptorService=t,this._rangeProtectionCache=n,this._initViewModelByRangeInterceptor(),this._initViewModelBySheetInterceptor()}_initViewModelByRangeInterceptor(){this.disposeWithMe(this._sheetInterceptorService.intercept(Ae.CELL_CONTENT,{priority:999,effect:i.InterceptorEffectEnum.Value|i.InterceptorEffectEnum.Style,handler:(s,e,t)=>{const{unitId:n,subUnitId:o,row:r,col:a}=e,u=this._rangeProtectionCache.getCellInfo(n,o,r,a);if(u){const l=u[_.View]===!1,d=!s||s===e.rawData?{...e.rawData}:s;return d.selectionProtection=[u],l?(delete d.s,delete d.v,delete d.p,d):t(d)}return t(s)}}))}_initViewModelBySheetInterceptor(){this.disposeWithMe(this._sheetInterceptorService.intercept(Ae.CELL_CONTENT,{priority:999,effect:i.InterceptorEffectEnum.Value|i.InterceptorEffectEnum.Style,handler:(s,e,t)=>{var a,u,l,d,c;const{unitId:n,subUnitId:o}=e,r=this._worksheetProtectionRuleModel.getRule(n,o);if(r!=null&&r.permissionId){const m=[{[_.View]:(u=(a=this._permissionService.getPermissionPoint(new Vt(n,o).id))==null?void 0:a.value)!=null?u:!1,[_.Edit]:(d=(l=this._permissionService.getPermissionPoint(new fe(n,o).id))==null?void 0:l.value)!=null?d:!1}],h=!((c=m[0])!=null&&c[_.View]),R=!s||s===e.rawData?{...s}:s;return R.hasWorksheetRule=!0,R.selectionProtection=m,h?(delete R.s,delete R.v,delete R.p,R):t(R)}return t(s)}}))}};An=fd([Dn(0,i.IPermissionService),Dn(1,i.Inject(ke)),Dn(2,i.Inject(g.SheetInterceptorService)),Dn(3,i.Inject(g.RangeProtectionCache))],An);const eo=i.createIdentifier("univer.exclusive-range-service");class ki extends i.Disposable{constructor(){super(...arguments);f(this,"_exclusiveRanges",new Map);f(this,"_exclusiveRangesChange$",new O.Subject);f(this,"exclusiveRangesChange$",this._exclusiveRangesChange$.asObservable())}_ensureUnitMap(t){return this._exclusiveRanges.has(t)||this._exclusiveRanges.set(t,new Map),this._exclusiveRanges.get(t)}_ensureSubunitMap(t,n){const o=this._ensureUnitMap(t);return o.has(n)||o.set(n,new Map),o.get(n)}_ensureFeature(t,n,o){const r=this._ensureSubunitMap(t,n);return r.has(o)||r.set(o,[]),r.get(o)}addExclusiveRange(t,n,o,r){const a=this._ensureFeature(t,n,o);a.push(...r),this._exclusiveRangesChange$.next({unitId:t,subUnitId:n,ranges:a.map(u=>u.range)})}getExclusiveRanges(t,n,o){var r,a;return(a=(r=this._exclusiveRanges.get(t))==null?void 0:r.get(n))==null?void 0:a.get(o)}clearExclusiveRanges(t,n,o){const r=this.getExclusiveRanges(t,n,o);this._exclusiveRangesChange$.next({unitId:t,subUnitId:n,ranges:(r==null?void 0:r.map(a=>a.range))||[]}),this._ensureFeature(t,n,o),this._exclusiveRanges.get(t).get(n).set(o,[])}clearExclusiveRangesByGroupId(t,n,o,r){const a=this.getExclusiveRanges(t,n,o);this._exclusiveRangesChange$.next({unitId:t,subUnitId:n,ranges:(a==null?void 0:a.map(l=>l.range))||[]});const u=this.getExclusiveRanges(t,n,o);if(u){const l=u.filter(d=>d.groupId!==r);this._exclusiveRanges.get(t).get(n).set(o,l)}}getInterestGroupId(t){const n=[];return t.forEach(o=>{var d;const r=o.range,{unitId:a,sheetId:u}=r;if(!a||!u)return;const l=(d=this._exclusiveRanges.get(a))==null?void 0:d.get(u);if(l)for(const c of l.keys()){const m=l.get(c);if(m){for(const h of m)if(i.Rectangle.intersects(r,h.range)){n.push(c);break}}}}),n}}var Id=Object.getOwnPropertyDescriptor,vd=(s,e,t,n)=>{for(var o=n>1?void 0:n?Id(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},to=(s,e)=>(t,n)=>e(t,n,s);g.NumfmtService=class extends i.Disposable{constructor(e,t,n){super(),this._resourceManagerService=e,this._univerInstanceService=t,this._logService=n}getValue(e,t,n,o){const r=this._univerInstanceService.getUniverSheetInstance(e);if(!r)return;const a=r==null?void 0:r.getSheetBySheetId(t);if(!a)return;const u=r.getStyles(),l=a.getCellRaw(n,o);if(l!=null&&l.s){const d=u.get(l.s);if(d!=null&&d.n)return d.n}return null}deleteValues(e,t,n){const o=this._univerInstanceService.getUniverSheetInstance(e);if(!o)return;const r=o==null?void 0:o.getSheetBySheetId(t);if(!r)return;const a=o.getStyles();n.forEach(u=>{i.Range.foreach(u,(l,d)=>{const c=r.getCellRaw(l,d);if(!c)return;const m=c==null?void 0:c.s,R={...m&&a.get(m)||{}};delete R.n;const C=a.setValue(R);c.s=C})})}setValues(e,t,n){const o=this._univerInstanceService.getUniverSheetInstance(e);if(!o)return;const r=o==null?void 0:o.getSheetBySheetId(t);if(!r)return;const a=o.getStyles(),u=r.getCellMatrix();n.forEach(l=>{l.ranges.forEach(d=>{i.Range.foreach(d,(c,m)=>{const h=r.getCellRaw(c,m);if(h){const C={...a.getStyleByCell(h)||{},n:{pattern:l.pattern}},S=a.setValue(C);h.s=S}else{const R={n:{pattern:l.pattern}},C=a.setValue(R);C&&u.setValue(c,m,{s:C})}})})})}},g.NumfmtService=vd([to(0,i.IResourceManagerService),to(1,i.IUniverInstanceService),to(2,i.ILogService)],g.NumfmtService);var pd=Object.getOwnPropertyDescriptor,wd=(s,e,t,n)=>{for(var o=n>1?void 0:n?pd(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},qe=(s,e)=>(t,n)=>e(t,n,s);const Ni=[ie.id,re.id,ne.id,ae.id],Oi=[pe.id,we.id];g.RangeProtectionRefRangeService=class extends i.Disposable{constructor(t,n,o,r,a,u,l,d){super();f(this,"disposableCollection",new i.DisposableCollection);this._selectionProtectionRuleModel=t,this._univerInstanceService=n,this._commandService=o,this._refRangeService=r,this._selectionProtectionRenderModel=a,this._rangeProtectionCache=u,this._sheetInterceptorService=l,this._rangeProtectionRuleModel=d,this._onRefRangeChange(),this._correctPermissionRange(),this._initReBuildCache(),this._initRemoveSheet()}_onRefRangeChange(){const t=(o,r)=>{const a=this._univerInstanceService.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET);if(!a||!(a==null?void 0:a.getSheetBySheetId(r)))return;this.disposableCollection.dispose();const l=c=>this.refRangeHandle(c,o,r);this._selectionProtectionRuleModel.getSubunitRuleList(o,r).reduce((c,m)=>[...c,...m.ranges],[]).forEach(c=>{this.disposableCollection.add(this._refRangeService.registerRefRange(c,l,o,r))})};this.disposeWithMe(this._commandService.onCommandExecuted(o=>{if(o.id===Gs.id){const r=o.params,a=r.subUnitId,u=r.unitId;if(!a||!u)return;t(u,a)}if(o.id===Q.id||o.id===Ce.id){const r=o.params,a=r.subUnitId,u=r.unitId;if(!a||!u)return;t(u,a)}}));const n=this._univerInstanceService.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET);if(n){const o=n.getActiveSheet();if(!o)return;t(n.getUnitId(),o.getSheetId())}}refRangeHandle(t,n,o){switch(t.id){case pt.id:return this._getRefRangeMutationsByMoveRows(t.params,n,o);case wt.id:return this._getRefRangeMutationsByMoveCols(t.params,n,o);case Me.id:return this._getRefRangeMutationsByInsertRows(t.params,n,o);case ye.id:return this._getRefRangeMutationsByInsertCols(t.params,n,o);case Lt.id:return this._getRefRangeMutationsByDeleteCols(t.params,n,o);case $t.id:return this._getRefRangeMutationsByDeleteRows(t.params,n,o)}return{redos:[],undos:[]}}_getRefRangeMutationsByDeleteCols(t,n,o){const r=this._selectionProtectionRuleModel.getSubunitRuleList(n,o).filter(u=>u.ranges.some(l=>i.Rectangle.intersects(l,t.range))),a=t.range;if(r.length){const u=[],l=[];return r.forEach(d=>{const c=i.Tools.deepClone(d),m=c.ranges.reduce((h,R)=>{if(i.Rectangle.intersects(R,a)){const C=i.Tools.deepClone(R),{startColumn:S,endColumn:I}=a;if(S<=C.startColumn&&I>=C.endColumn)return h;S>=C.startColumn&&I<=C.endColumn?C.endColumn-=I-S+1:S<C.startColumn?(C.startColumn=S,C.endColumn-=I-S+1):I>C.endColumn&&(C.endColumn=S-1),this._checkIsRightRange(C)&&h.push(C)}return h},[]);c.ranges=m,c.ranges.length?(u.push({id:Q.id,params:{unitId:n,subUnitId:o,rule:c,ruleId:d.id}}),l.push({id:Q.id,params:{unitId:n,subUnitId:o,rule:d,ruleId:d.id}})):(u.push({id:Te.id,params:{unitId:n,subUnitId:o,ruleIds:[d.id]}}),l.push({id:Ce.id,params:{unitId:n,subUnitId:o,name:"",rules:[d]}}))}),{redos:u,undos:l}}return{undos:[],redos:[]}}_getRefRangeMutationsByDeleteRows(t,n,o){const r=this._selectionProtectionRuleModel.getSubunitRuleList(n,o).filter(u=>u.ranges.some(l=>i.Rectangle.intersects(l,t.range))),a=t.range;if(r.length){const u=[],l=[];return r.forEach(d=>{const c=i.Tools.deepClone(d),m=c.ranges.reduce((h,R)=>{if(i.Rectangle.intersects(R,a)){const C=i.Tools.deepClone(R),{startRow:S,endRow:I}=a;if(S<=C.startRow&&I>=C.endRow)return h;S>=C.startRow&&I<=C.endRow?C.endRow-=I-S+1:S<C.startRow?(C.startRow=S,C.endRow-=I-S+1):I>C.endRow&&(C.endRow=S-1),this._checkIsRightRange(C)&&h.push(C)}return h},[]);c.ranges=m,u.push({id:Q.id,params:{unitId:n,subUnitId:o,rule:c,ruleId:d.id}}),l.push({id:Q.id,params:{unitId:n,subUnitId:o,rule:d,ruleId:d.id}})}),{redos:u,undos:l}}return{undos:[],redos:[]}}_getRefRangeMutationsByInsertCols(t,n,o){const r=t.range.startColumn,a=t.range.endColumn-t.range.startColumn+1,u=this._selectionProtectionRuleModel.getSubunitRuleList(n,o).filter(l=>l.ranges.some(d=>r>d.startColumn&&r<=d.endColumn));if(u.length){const l=[],d=[];return u.forEach(c=>{const m=i.Tools.deepClone(c);let h=!1;m.ranges.forEach(R=>{r>R.startColumn&&r<=R.endColumn&&(R.endColumn+=a,h=!0)}),h&&(l.push({id:Q.id,params:{unitId:n,subUnitId:o,rule:m,ruleId:c.id}}),d.push({id:Q.id,params:{unitId:n,subUnitId:o,rule:c,ruleId:c.id}}))}),{redos:l,undos:d}}return{undos:[],redos:[]}}_getRefRangeMutationsByInsertRows(t,n,o){const r=t.range.startRow,a=t.range.endRow-t.range.startRow+1,u=this._selectionProtectionRuleModel.getSubunitRuleList(n,o).filter(l=>l.ranges.some(d=>r>d.startRow&&r<=d.endRow));if(u.length){const l=[],d=[];return u.forEach(c=>{const m=i.Tools.deepClone(c);let h=!1;m.ranges.forEach(R=>{r>R.startRow&&r<=R.endRow&&(R.endRow+=a,h=!0)}),h&&(l.push({id:Q.id,params:{unitId:n,subUnitId:o,rule:m,ruleId:c.id}}),d.push({id:Q.id,params:{unitId:n,subUnitId:o,rule:c,ruleId:c.id}}))}),{redos:l,undos:d}}return{undos:[],redos:[]}}_getRefRangeMutationsByMoveRows(t,n,o){const r=t.toRange,a=r.startRow,u=r.endRow-r.startRow+1,l=this._selectionProtectionRuleModel.getSubunitRuleList(n,o).filter(d=>d.ranges.some(c=>a>c.startRow&&a<=c.endRow));if(l.length){const d=[],c=[];return l.forEach(m=>{const h=i.Tools.deepClone(m),C=t.fromRange.startRow;let S=!1;h.ranges.forEach(I=>{a>I.startRow&&a<=I.endRow&&(C<I.startRow&&(I.startRow=I.startRow-u,I.endRow=I.endRow-u),I.endRow+=u,S=!0)}),S&&(d.push({id:Q.id,params:{unitId:n,subUnitId:o,rule:h,ruleId:m.id}}),c.push({id:Q.id,params:{unitId:n,subUnitId:o,rule:m,ruleId:m.id}}))}),{redos:d,undos:c}}return{undos:[],redos:[]}}_getRefRangeMutationsByMoveCols(t,n,o){const r=t.toRange,a=r.startColumn,u=r.endColumn-r.startColumn+1,l=this._selectionProtectionRuleModel.getSubunitRuleList(n,o).filter(d=>d.ranges.some(c=>a>c.startColumn&&a<=c.endColumn));if(l.length){const d=[],c=[];return l.forEach(m=>{const h=i.Tools.deepClone(m),C=t.fromRange.startColumn;let S=!1;h.ranges.forEach(I=>{a>I.startColumn&&a<=I.endColumn&&(C<I.startColumn&&(I.startColumn=I.startColumn-u,I.endColumn=I.endColumn-u),I.endColumn+=u,S=!0)}),S&&(d.push({id:Q.id,params:{unitId:n,subUnitId:o,rule:h,ruleId:m.id}}),c.push({id:Q.id,params:{unitId:n,subUnitId:o,rule:m,ruleId:m.id}}))}),{redos:d,undos:c}}return{undos:[],redos:[]}}_correctPermissionRange(){this.disposeWithMe(this._commandService.onCommandExecuted(t=>{if(Oi.includes(t.id)){if(!t.params)return;const n=this._univerInstanceService.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET);if(!n)return;const o=n.getSheetBySheetId(t.params.subUnitId);if(!o)return;const{sourceRange:r,targetRange:a}=t.params,u=r.startColumn===a.startColumn&&r.endColumn===a.endColumn,l=u?r.endRow-r.startRow+1:r.endColumn-r.startColumn+1,d=u?r.startRow:r.startColumn,c=u?a.startRow:a.startColumn;this._selectionProtectionRuleModel.getSubunitRuleList(n.getUnitId(),o.getSheetId()).forEach(I=>{I.ranges.forEach(M=>{let{startRow:p,endRow:w,startColumn:y,endColumn:b}=M;i.Rectangle.intersects(M,r)||(u?d<p&&c>w?(p-=l,w-=l):d>w&&c<=p&&(p+=l,w+=l):d<y&&c>b?(y-=l,b-=l):d>b&&c<=y&&(y+=l,b+=l)),this._checkIsRightRange({startRow:p,endRow:w,startColumn:y,endColumn:b})&&(M.startColumn=y,M.endColumn=b,M.startRow=p,M.endRow=w)})}),this.disposableCollection.dispose();const{unitId:h,subUnitId:R}=t.params,C=I=>this.refRangeHandle(I,h,R);this._selectionProtectionRuleModel.getSubunitRuleList(h,R).reduce((I,v)=>[...I,...v.ranges],[]).forEach(I=>{this.disposableCollection.add(this._refRangeService.registerRefRange(I,C,h,R))}),this._selectionProtectionRenderModel.clear()}if(Ni.includes(t.id)){const n=this._univerInstanceService.getUniverSheetInstance(t.params.unitId);if(!n)return;const o=n.getSheetBySheetId(t.params.subUnitId);if(!o)return;const r=t.params;if(!r)return;const{range:a}=r,u=t.id.includes("row"),l=t.id.includes("insert"),d=u?a.startRow:a.startColumn,c=u?a.endRow:a.endColumn,m=c-d+1;this._selectionProtectionRuleModel.getSubunitRuleList(n.getUnitId(),o.getSheetId()).forEach(v=>{v.ranges.forEach(p=>{let{startRow:w,endRow:y,startColumn:b,endColumn:T}=p;l?u?d<=w&&(w+=m,y+=m):d<=b&&(b+=m,T+=m):u?c<w&&(w-=m,y-=m):c<b&&(b-=m,T-=m),this._checkIsRightRange({startRow:w,endRow:y,startColumn:b,endColumn:T})&&(p.startColumn=b,p.endColumn=T,p.startRow=w,p.endRow=y)})}),this.disposableCollection.dispose();const{unitId:R,subUnitId:C}=t.params,S=v=>this.refRangeHandle(v,R,C);this._selectionProtectionRuleModel.getSubunitRuleList(R,C).reduce((v,M)=>[...v,...M.ranges],[]).forEach(v=>{this.disposableCollection.add(this._refRangeService.registerRefRange(v,S,R,C))}),this._selectionProtectionRenderModel.clear()}}))}_checkIsRightRange(t){return t.startRow<=t.endRow&&t.startColumn<=t.endColumn}_initReBuildCache(){this.disposeWithMe(this._commandService.onCommandExecuted(t=>{if(Ni.includes(t.id)||Oi.includes(t.id)){const{unitId:n,subUnitId:o}=t.params;this._rangeProtectionCache.reBuildCache(n,o)}}))}_initRemoveSheet(){this._sheetInterceptorService.interceptCommand({getMutations:t=>{const n=[],o=[],r=[],a=[];if(t.id===vn.id){const u=t.params,l=[],d=[];this._rangeProtectionRuleModel.getSubunitRuleList(u.unitId,u.subUnitId).forEach(c=>{l.push(c.id),d.push(c)}),l.length&&d.length&&(r.push({id:Te.id,params:{unitId:u.unitId,subUnitId:u.subUnitId,ruleIds:l}}),n.push({id:Ce.id,params:{unitId:u.unitId,subUnitId:u.subUnitId,name:"",rules:d}}))}return{redos:o,undos:n,preRedos:r,preUndos:a}}})}},g.RangeProtectionRefRangeService=wd([qe(0,i.Inject(X)),qe(1,i.Inject(i.IUniverInstanceService)),qe(2,i.ICommandService),qe(3,i.Inject(g.RefRangeService)),qe(4,i.Inject(g.RangeProtectionRenderModel)),qe(5,i.Inject(g.RangeProtectionCache)),qe(6,i.Inject(g.SheetInterceptorService)),qe(7,i.Inject(X))],g.RangeProtectionRefRangeService);var Md=Object.getOwnPropertyDescriptor,yd=(s,e,t,n)=>{for(var o=n>1?void 0:n?Md(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},Xt=(s,e)=>(t,n)=>e(t,n,s);const _d="SHEET_RANGE_PROTECTION_PLUGIN";g.RangeProtectionService=class extends i.Disposable{constructor(e,t,n,o,r){super(),this._selectionProtectionRuleModel=e,this._permissionService=t,this._resourceManagerService=n,this._selectionProtectionCache=o,this._univerInstanceService=r,this._initSnapshot(),this._initRuleChange()}_initRuleChange(){this.disposeWithMe(this._selectionProtectionRuleModel.ruleChange$.subscribe(e=>{switch(e.type){case"add":{le().forEach(t=>{const n=new t(e.unitId,e.subUnitId,e.rule.permissionId);this._permissionService.addPermissionPoint(n)});break}case"delete":{le().forEach(t=>{const n=new t(e.unitId,e.subUnitId,e.rule.permissionId);this._permissionService.deletePermissionPoint(n.id)});break}case"set":{e.oldRule.permissionId!==e.rule.permissionId&&le().forEach(t=>{const n=new t(e.unitId,e.subUnitId,e.oldRule.permissionId);this._permissionService.deletePermissionPoint(n.id);const o=new t(e.unitId,e.subUnitId,e.rule.permissionId);this._permissionService.addPermissionPoint(o)});break}}}))}_initSnapshot(){const e=n=>{const r=this._selectionProtectionRuleModel.toObject()[n];return r?JSON.stringify(r):""},t=n=>{if(!n)return{};try{return JSON.parse(n)}catch{return{}}};this.disposeWithMe(this._resourceManagerService.registerPluginResource({toJson:e,parseJson:t,pluginName:_d,businesses:[an.UNIVER_SHEET],onLoad:(n,o)=>{const r=this._selectionProtectionRuleModel.toObject();r[n]=o,this._selectionProtectionRuleModel.fromObject(r);const a=[];Object.keys(o).forEach(u=>{const l=o[u];this._selectionProtectionRuleModel.getSubunitRuleList(n,u).forEach(d=>{a.push({objectID:d.permissionId,unitID:n,objectType:D.SelectRange,actions:Ge})}),l.forEach(d=>{le().forEach(c=>{const m=new c(n,u,d.permissionId);m.value=!1,this._permissionService.addPermissionPoint(m)})}),this._selectionProtectionCache.reBuildCache(n,u)})},onUnLoad:n=>{this._selectionProtectionCache.deleteUnit(n)}}))}},g.RangeProtectionService=yd([Xt(0,i.Inject(X)),Xt(1,i.Inject(i.IPermissionService)),Xt(2,i.Inject(i.IResourceManagerService)),Xt(3,i.Inject(g.RangeProtectionCache)),Xt(4,i.Inject(i.IUniverInstanceService))],g.RangeProtectionService);var bd=Object.getOwnPropertyDescriptor,Ed=(s,e,t,n)=>{for(var o=n>1?void 0:n?bd(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},Td=(s,e)=>(t,n)=>e(t,n,s);g.SheetRangeThemeService=class extends i.Disposable{constructor(e){super(),this._sheetRangeThemeModel=e}registerRangeTheme(e,t){this._sheetRangeThemeModel.registerRangeThemeStyle(e,t)}removeRangeThemeRule(e,t){this._sheetRangeThemeModel.removeRangeThemeRule(e,t)}getALLRegisterThemes(e){return this._sheetRangeThemeModel.getALLRegisteredTheme(e)}registerRangeThemeStyle(e,t){this._sheetRangeThemeModel.registerRangeThemeRule(e,t)}getAppliedRangeThemeStyle(e){return this._sheetRangeThemeModel.getRegisteredRangeThemeStyle(e)}getRegisteredRangeThemes(){return this._sheetRangeThemeModel.getRegisteredRangeThemes()}},g.SheetRangeThemeService=Ed([Td(0,i.Inject(g.SheetRangeThemeModel))],g.SheetRangeThemeService);var Ud=Object.defineProperty,Pd=Object.getOwnPropertyDescriptor,kd=(s,e,t)=>e in s?Ud(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Nd=(s,e,t,n)=>{for(var o=n>1?void 0:n?Pd(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},Di=(s,e)=>(t,n)=>e(t,n,s),Ai=(s,e,t)=>kd(s,typeof e!="symbol"?e+"":e,t);const Od="SHEET_PLUGIN";g.UniverSheetsPlugin=class extends i.Plugin{constructor(e=Ei,t,n){super(),this._config=e,this._injector=t,this._configService=n;const{...o}=i.merge({},Ei,this._config);this._configService.setConfig(bi,o),this._initConfig(),this._initDependencies()}_initConfig(){var e,t,n;(e=this._config)!=null&&e.onlyRegisterFormulaRelatedMutations&&this._configService.setConfig(Ui,!0),(t=this._config)!=null&&t.isRowStylePrecedeColumnStyle&&this._configService.setConfig(i.IS_ROW_STYLE_PRECEDE_COLUMN_STYLE,!0),(n=this._config)!=null&&n.autoHeightForMergedCells&&this._configService.setConfig(i.AUTO_HEIGHT_FOR_MERGED_CELLS,!0)}_initDependencies(){var t;const e=[[nt],[g.SheetsSelectionsService],[g.RefRangeService],[g.WorkbookPermissionService],[ot,{useClass:g.NumfmtService}],[g.SheetInterceptorService],[g.SheetRangeThemeService],[g.SheetSkeletonService],[kn],[g.MergeCellController],[On],[g.DefinedNameDataController],[g.ZebraCrossingCacheController],[g.SheetsFreezeSyncController],[g.WorksheetPermissionService],[ke],[Ut],[An],[g.SheetPermissionInitController],[g.SheetPermissionCheckController],[g.SheetRangeThemeModel],[g.RangeProtectionRenderModel],[X],[g.RangeProtectionCache],[g.RangeProtectionRefRangeService],[g.RangeProtectionService],[eo,{useClass:ki,deps:[g.SheetsSelectionsService]}]];(t=this._config)!=null&&t.notExecuteFormula||e.push([Nn]),i.registerDependencies(this._injector,i.mergeOverrideWithDependencies(e,this._config.override)),i.touchDependencies(this._injector,[[g.SheetInterceptorService],[g.RangeProtectionService],[eo],[g.SheetPermissionInitController],[g.SheetsFreezeSyncController]])}onStarting(){i.touchDependencies(this._injector,[[kn],[g.MergeCellController],[g.WorkbookPermissionService],[g.WorksheetPermissionService],[An],[g.SheetSkeletonService]])}onRendered(){i.touchDependencies(this._injector,[[ot]])}onReady(){i.touchDependencies(this._injector,[[Nn],[g.DefinedNameDataController],[g.ZebraCrossingCacheController],[g.SheetRangeThemeModel],[On],[g.RangeProtectionRenderModel],[g.RangeProtectionRefRangeService],[g.RefRangeService],[g.SheetPermissionCheckController]])}},Ai(g.UniverSheetsPlugin,"pluginName",Od),Ai(g.UniverSheetsPlugin,"type",i.UniverInstanceType.UNIVER_SHEET),g.UniverSheetsPlugin=Nd([i.DependentOn(J.UniverFormulaEnginePlugin),Di(1,i.Inject(i.Injector)),Di(2,i.IConfigService)],g.UniverSheetsPlugin);const Dd={WorkbookCommentPermission:Jn,WorkbookCopyPermission:xn,WorkbookCreateProtectPermission:Xn,WorkbookCreateSheetPermission:Zn,WorkbookDeleteSheetPermission:Qn,WorkbookDuplicatePermission:es,WorkbookEditablePermission:me,WorkbookExportPermission:ts,WorkbookHideSheetPermission:ln,WorkbookHistoryPermission:qo,WorkbookManageCollaboratorPermission:dn,WorkbookMoveSheetPermission:cn,WorkbookPrintPermission:ns,WorkbookRecoverHistoryPermission:ss,WorkbookRenameSheetPermission:mn,WorkbookSharePermission:os,WorkbookViewHistoryPermission:is,WorkbookViewPermission:rs,WorksheetCopyPermission:as,WorksheetDeleteColumnPermission:us,WorksheetDeleteProtectionPermission:ls,WorksheetDeleteRowPermission:ds,WorksheetEditExtraObjectPermission:cs,WorksheetEditPermission:fe,WorksheetFilterPermission:ms,WorksheetInsertColumnPermission:hs,WorksheetInsertHyperlinkPermission:gs,WorksheetInsertRowPermission:Rs,WorksheetManageCollaboratorPermission:Cs,WorksheetPivotTablePermission:Ss,WorksheetSetCellStylePermission:fs,WorksheetSetCellValuePermission:Wt,WorksheetSetColumnStylePermission:St,WorksheetSetRowStylePermission:ft,WorksheetSortPermission:Is,WorksheetViewPermission:Vt,RangeProtectionPermissionEditPoint:Se,RangeProtectionPermissionViewPoint:un},Ad=(s,e,t,n)=>{const o=s.get(i.IPermissionService),r=s.get(X),a=o.getPermissionPoint(new me(e).id);if(!(a!=null&&a.value))return!1;const u=o.getPermissionPoint(new fe(e,t).id);if(!(u!=null&&u.value))return!1;const d=r.getSubunitRuleList(e,t).filter(c=>c.ranges.some(m=>n.some(h=>i.Rectangle.intersects(m,h))));return d.length?d.every(c=>{const m=c.permissionId,h=o.getPermissionPoint(new Se(e,t,m).id);return!!(h!=null&&h.value)}):!0},Wi=(s,e,t,n=1,o=!0,r=!0)=>{const a=i.Range.transformRange(s,e),{startRow:u,endRow:l}=a;let d=t.startRow-n,c=e.getMergedCell(d,t.startColumn),m=!c||c.startRow===d&&c.startColumn===t.startColumn;for(;!e.getRowVisible(d)||!m;)d--,c=e.getMergedCell(d,t.startColumn),m=!c||c.startRow===d&&c.startColumn===t.startColumn;if(d>=u)return{...t,startRow:d,endRow:d};if(r){const h={...t,startRow:l,endRow:l};return $i(s,e,h,n,o,!1)}},Vi=(s,e,t,n=1,o=!0,r=!0)=>{const a=i.Range.transformRange(s,e),{startRow:u,endRow:l}=a;let d=t.endRow+n,c=e.getMergedCell(d,t.startColumn),m=!c||c.startRow===d&&c.startColumn===t.startColumn;for(;!e.getRowVisible(d)||!m;)d++,c=e.getMergedCell(d,t.startColumn),m=!c||c.startRow===d&&c.startColumn===t.startColumn;if(d<=l)return{...t,startRow:d,endRow:d};if(r){const h={...t,startRow:u,endRow:u};return Li(s,e,h,n,o,!1)}},$i=(s,e,t,n=1,o=!0,r=!0)=>{const a=i.Range.transformRange(s,e),{startColumn:u,endColumn:l}=a;let d=t.startColumn-n,c=e.getMergedCell(t.startRow,d),m=!c||c.startRow===t.startRow&&c.startColumn===d;for(;!e.getColVisible(d)||!m;)d--,c=e.getMergedCell(t.startRow,d),m=!c||c.startRow===t.startRow&&c.startColumn===d;if(d>=u)return{...t,startColumn:d,endColumn:d};if(r){const h={...t,startColumn:l,endColumn:l};return Wi(s,e,h,n,o,!1)}},Li=(s,e,t,n=1,o=!0,r=!0)=>{const a=i.Range.transformRange(s,e),{startColumn:u,endColumn:l}=a;let d=t.endColumn+n,c=e.getMergedCell(t.startRow,d),m=!c||c.startRow===t.startRow&&c.startColumn===d;for(;!e.getColVisible(d)||!m;)d++,c=e.getMergedCell(t.startRow,d),m=!c||c.startRow===t.startRow&&c.startColumn===d;if(d<=l)return{...t,endColumn:d,startColumn:d};if(r){const h={...t,startColumn:u,endColumn:u};return Vi(s,e,h,n,o,!1)}};function Wn(s,e,t){let n=null;return t.getMatrixWithMergedCells(s,e,s,e).forValue((r,a,u)=>(n={actualRow:r,actualColumn:a,startRow:r,startColumn:a,isMerged:u.rowSpan!==void 0||u.colSpan!==void 0,isMergedMainCell:u.rowSpan!==void 0&&u.colSpan!==void 0,endRow:r+(u.rowSpan!==void 0?u.rowSpan-1:0),endColumn:a+(u.colSpan!==void 0?u.colSpan-1:0),rangeType:i.RANGE_TYPE.NORMAL},!1)),n||{actualColumn:e,actualRow:s,startRow:s,startColumn:e,endRow:s,endColumn:e,isMerged:!1,isMergedMainCell:!1,rangeType:i.RANGE_TYPE.NORMAL}}const Wd=(s,e,t,n,o=1)=>{switch(n){case i.Direction.UP:return Wi(s,e,t,o);case i.Direction.DOWN:return Vi(s,e,t,o);case i.Direction.LEFT:return $i(s,e,t,o);case i.Direction.RIGHT:return Li(s,e,t,o)}},Vd=(s,e,t)=>{let n,o=-1,r;for(let v=0;v<s.length;v++)if(s[v].primary){n=s[v],o=v,r=n.primary;break}if(o===-1)return null;const a=e===i.Direction.LEFT||e===i.Direction.UP,u=a?o-1>=0?o-1:s.length-1:o+1<s.length?o+1:0,l=s[u];if(!n||!r)return null;const d={...r},{startRow:c,startColumn:m,endRow:h,endColumn:R}=n.range,C=a?d.startRow===c&&d.startColumn===m:d.endRow===h&&d.endColumn===R,S=C&&a;if(!i.Rectangle.equals(n.range,d)){const v=C?l.range:Wd(n.range,t,d,e);if(!v)return null;const M=S?Wn(v.endRow,v.endColumn,t):Wn(v.startRow,v.startColumn,t);return{startRow:M.startRow,startColumn:M.startColumn,endRow:M.endRow,endColumn:M.endColumn}}const I=S?Wn(l.range.endRow,l.range.endColumn,t):Wn(l.range.startRow,l.range.startColumn,t);return{startRow:I.startRow,startColumn:I.startColumn,endRow:I.endRow,endColumn:I.endColumn}};g.AFTER_CELL_EDIT=Zt,g.AddMergeRedoSelectionsOperationFactory=Hl,g.AddMergeUndoMutationFactory=ge,g.AddMergeUndoSelectionsOperationFactory=Fl,g.AddRangeProtectionCommand=Ao,g.AddRangeProtectionMutation=Ce,g.AddRangeThemeMutation=Si,g.AddWorksheetMergeAllCommand=sl,g.AddWorksheetMergeCommand=Ft,g.AddWorksheetMergeHorizontalCommand=rl,g.AddWorksheetMergeMutation=j,g.AddWorksheetMergeVerticalCommand=ol,g.AddWorksheetProtectionCommand=Tr,g.AddWorksheetProtectionMutation=Fe,g.AppendRowCommand=Pr,g.BEFORE_CELL_EDIT=$n,g.BorderStyleManagerService=nt,g.COMMAND_LISTENER_SKELETON_CHANGE=Ua,g.COMMAND_LISTENER_VALUE_CHANGE=Pa,g.CancelFrozenCommand=zr,g.CancelMarkDirtyRowAutoHeightMutation=vi,g.ClearSelectionAllCommand=sn,g.ClearSelectionContentCommand=fn,g.ClearSelectionFormatCommand=on,g.CopySheetCommand=As,g.DISABLE_NORMAL_SELECTIONS=ru,g.DeleteRangeMoveLeftCommand=Be,g.DeleteRangeMoveUpCommand=He,g.DeleteRangeProtectionCommand=kr,g.DeleteRangeProtectionMutation=Te,g.DeleteWorksheetProtectionCommand=Nr,g.DeleteWorksheetProtectionMutation=tt,g.DeleteWorksheetRangeThemeStyleCommand=Or,g.DeleteWorksheetRangeThemeStyleMutation=it,g.DeleteWorksheetRangeThemeStyleMutationFactory=lo,g.DeltaColumnWidthCommand=Gt,g.DeltaRowHeightCommand=Kt,g.EditStateEnum=Do,g.EffectRefRangId=A,g.EmptyMutation=fi,g.ExclusiveRangeService=ki,g.FactoryAddRangeProtectionMutation=tu,g.FactoryDeleteRangeProtectionMutation=eu,g.FactorySetRangeProtectionMutation=Sl,g.IExclusiveRangeService=eo,g.INTERCEPTOR_POINT=Ae,g.INumfmtService=ot,g.IRefSelectionsService=Lo,g.InsertColAfterCommand=or,g.InsertColBeforeCommand=sr,g.InsertColByRangeCommand=ys,g.InsertColCommand=ye,g.InsertColMutation=ie,g.InsertColMutationUndoFactory=Nt,g.InsertDefinedNameCommand=Dr,g.InsertMultiColsLeftCommand=rr,g.InsertMultiColsRightCommand=ir,g.InsertMultiRowsAboveCommand=er,g.InsertMultiRowsAfterCommand=tr,g.InsertRangeMoveDownCommand=xe,g.InsertRangeMoveRightCommand=vt,g.InsertRowAfterCommand=Qo,g.InsertRowBeforeCommand=Zo,g.InsertRowByRangeCommand=Ms,g.InsertRowCommand=Me,g.InsertRowMutation=re,g.InsertRowMutationUndoFactory=en,g.InsertSheetCommand=Ar,g.InsertSheetMutation=yt,g.InsertSheetUndoMutationFactory=Ds,g.InterceptCellContentPriority=so,g.MAX_CELL_PER_SHEET_KEY=yi,g.MERGE_CELL_INTERCEPTOR_CHECK=Er,g.MarkDirtyRowAutoHeightMutation=Ii,g.MoveColsCommand=wt,g.MoveColsMutation=we,g.MoveColsMutationUndoFactory=mo,g.MoveRangeCommand=Je,g.MoveRangeMutation=Le,g.MoveRowsCommand=pt,g.MoveRowsMutation=pe,g.MoveRowsMutationUndoFactory=co,g.OperatorType=B,g.PermissionPointsDefinitions=Dd,g.REF_SELECTIONS_ENABLED=Vo,g.RangeMergeUtil=Ba,g.RangeProtectionPermissionDeleteProtectionPoint=qs,g.RangeProtectionPermissionEditPoint=Se,g.RangeProtectionPermissionManageCollaPoint=Ys,g.RangeProtectionPermissionViewPoint=un,g.RangeProtectionRuleModel=X,g.RangeThemeStyle=We,g.RegisterWorksheetRangeThemeStyleCommand=Wr,g.RegisterWorksheetRangeThemeStyleMutation=_t,g.RemoveColByRangeCommand=bs,g.RemoveColCommand=Lt,g.RemoveColMutation=ne,g.RemoveDefinedNameCommand=Ws,g.RemoveMergeUndoMutationFactory=ue,g.RemoveNumfmtMutation=Js,g.RemoveRangeThemeMutation=pi,g.RemoveRowByRangeCommand=_s,g.RemoveRowCommand=$t,g.RemoveRowMutation=ae,g.RemoveSheetCommand=vn,g.RemoveSheetMutation=Xe,g.RemoveSheetUndoMutationFactory=ar,g.RemoveWorksheetMergeCommand=Vr,g.RemoveWorksheetMergeMutation=G,g.ReorderRangeCommand=Rn,g.ReorderRangeMutation=Ot,g.ReorderRangeUndoMutationFactory=ho,g.ResetBackgroundColorCommand=Qr,g.ResetTextColorCommand=Xr,g.SCOPE_WORKBOOK_VALUE_DEFINED_NAME=Yl,g.SELECTIONS_ENABLED=iu,g.SELECTION_CONTROL_BORDER_BUFFER_COLOR=Fa,g.SELECTION_CONTROL_BORDER_BUFFER_WIDTH=Ha,g.ScrollToCellOperation=Mi,g.SelectRangeCommand=Ho,g.SelectionMoveType=te,g.SetBackgroundColorCommand=Zr,g.SetBoldCommand=pl,g.SetBorderBasicCommand=Hr,g.SetBorderColorCommand=Br,g.SetBorderCommand=bt,g.SetBorderPositionCommand=$r,g.SetBorderStyleCommand=Lr,g.SetColDataCommand=Fr,g.SetColDataMutation=at,g.SetColDataMutationFactory=go,g.SetColHiddenCommand=wn,g.SetColHiddenMutation=ut,g.SetColVisibleMutation=lt,g.SetColWidthCommand=zt,g.SetDefinedNameCommand=Ls,g.SetFontFamilyCommand=bl,g.SetFontSizeCommand=El,g.SetFrozenCommand=Gr,g.SetFrozenMutation=Ne,g.SetFrozenMutationFactory=Bs,g.SetGridlinesColorCommand=qr,g.SetGridlinesColorMutation=dt,g.SetHorizontalTextAlignCommand=ti,g.SetItalicCommand=wl,g.SetNumfmtMutation=Un,g.SetOverlineCommand=_l,g.SetProtectionCommand=Yr,g.SetRangeProtectionMutation=Q,g.SetRangeThemeMutation=wi,g.SetRangeValuesCommand=It,g.SetRangeValuesMutation=F,g.SetRangeValuesUndoMutationFactory=ce,g.SetRowDataCommand=Kr,g.SetRowDataMutation=ct,g.SetRowDataMutationFactory=So,g.SetRowHeightCommand=Jt,g.SetRowHiddenCommand=Mn,g.SetRowHiddenMutation=Ke,g.SetRowVisibleMutation=Ye,g.SetSelectedColsVisibleCommand=$s,g.SetSelectedRowsVisibleCommand=Hs,g.SetSelectionsOperation=q,g.SetSpecificColsVisibleCommand=Et,g.SetSpecificRowsVisibleCommand=Tt,g.SetStrikeThroughCommand=yl,g.SetStyleCommand=ee,g.SetTabColorCommand=oi,g.SetTabColorMutation=jt,g.SetTextColorCommand=xr,g.SetTextRotationCommand=si,g.SetTextWrapCommand=ni,g.SetUnderlineCommand=Ml,g.SetVerticalTextAlignCommand=ei,g.SetWorkbookNameCommand=js,g.SetWorkbookNameMutation=Fs,g.SetWorksheetActivateCommand=Gs,g.SetWorksheetActiveOperation=Ct,g.SetWorksheetColWidthMutation=Ve,g.SetWorksheetColWidthMutationFactory=jn,g.SetWorksheetColumnCountCommand=ri,g.SetWorksheetColumnCountMutation=mt,g.SetWorksheetColumnCountUndoMutationFactory=fo,g.SetWorksheetDefaultStyleCommand=ii,g.SetWorksheetDefaultStyleMutation=ht,g.SetWorksheetDefaultStyleMutationFactory=Io,g.SetWorksheetHideCommand=ui,g.SetWorksheetHideMutation=je,g.SetWorksheetNameCommand=yn,g.SetWorksheetNameMutation=qt,g.SetWorksheetOrderCommand=zs,g.SetWorksheetOrderMutation=Yt,g.SetWorksheetPermissionPointsCommand=di,g.SetWorksheetPermissionPointsMutation=bn,g.SetWorksheetProtectionCommand=ci,g.SetWorksheetProtectionMutation=st,g.SetWorksheetRangeThemeStyleCommand=Ur,g.SetWorksheetRangeThemeStyleMutation=rt,g.SetWorksheetRangeThemeStyleMutationFactory=uo,g.SetWorksheetRightToLeftCommand=$l,g.SetWorksheetRightToLeftMutation=En,g.SetWorksheetRowAutoHeightMutation=zn,g.SetWorksheetRowAutoHeightMutationFactory=Ta,g.SetWorksheetRowCountCommand=mi,g.SetWorksheetRowCountMutation=gt,g.SetWorksheetRowCountUndoMutationFactory=vo,g.SetWorksheetRowHeightMutation=Ee,g.SetWorksheetRowIsAutoHeightCommand=Tn,g.SetWorksheetRowIsAutoHeightMutation=Re,g.SetWorksheetShowCommand=Ks,g.SheetSkeletonChangeType=wo,g.SheetValueChangeType=Mo,g.SplitDelimiterEnum=Uo,g.SplitTextToColumnsCommand=hi,g.ToggleCellCheckboxCommand=gi,g.ToggleGridlinesCommand=Ri,g.ToggleGridlinesMutation=Rt,g.UnitAction=_,g.UnitObject=D,g.UnregisterWorksheetRangeThemeStyleCommand=Ci,g.UnregisterWorksheetRangeThemeStyleMutation=In,g.VALIDATE_CELL=Qt,g.ViewStateEnum=Oo,g.WorkbookCommentPermission=Jn,g.WorkbookCopyPermission=xn,g.WorkbookCopySheetPermission=jo,g.WorkbookCreateProtectPermission=Xn,g.WorkbookCreateSheetPermission=Zn,g.WorkbookDeleteColumnPermission=Go,g.WorkbookDeleteRowPermission=zo,g.WorkbookDeleteSheetPermission=Qn,g.WorkbookDuplicatePermission=es,g.WorkbookEditablePermission=me,g.WorkbookExportPermission=ts,g.WorkbookHideSheetPermission=ln,g.WorkbookHistoryPermission=qo,g.WorkbookInsertColumnPermission=Yo,g.WorkbookInsertRowPermission=Ko,g.WorkbookManageCollaboratorPermission=dn,g.WorkbookMoveSheetPermission=cn,g.WorkbookPrintPermission=ns,g.WorkbookRecoverHistoryPermission=ss,g.WorkbookRenameSheetPermission=mn,g.WorkbookSelectionModel=Wo,g.WorkbookSharePermission=os,g.WorkbookViewHistoryPermission=is,g.WorkbookViewPermission=rs,g.WorksheetCopyPermission=as,g.WorksheetDeleteColumnPermission=us,g.WorksheetDeleteProtectionPermission=ls,g.WorksheetDeleteRowPermission=ds,g.WorksheetEditExtraObjectPermission=cs,g.WorksheetEditPermission=fe,g.WorksheetFilterPermission=ms,g.WorksheetInsertColumnPermission=hs,g.WorksheetInsertHyperlinkPermission=gs,g.WorksheetInsertRowPermission=Rs,g.WorksheetManageCollaboratorPermission=Cs,g.WorksheetPivotTablePermission=Ss,g.WorksheetProtectionPointModel=Ut,g.WorksheetProtectionRuleModel=ke,g.WorksheetSelectProtectedCellsPermission=Ru,g.WorksheetSelectUnProtectedCellsPermission=Cu,g.WorksheetSetCellStylePermission=fs,g.WorksheetSetCellValuePermission=Wt,g.WorksheetSetColumnStylePermission=St,g.WorksheetSetRowStylePermission=ft,g.WorksheetSortPermission=Is,g.WorksheetViewPermission=Vt,g.addMergeCellsUtil=il,g.adjustRangeOnMutation=vr,g.alignToMergedCellsBorders=At,g.baseProtectionActions=Ge,g.checkCellValueType=Vn,g.checkRangesEditablePermission=Ad,g.convertPrimaryWithCoordToPrimary=To,g.convertSelectionDataToRange=ja,g.copyRangeStyles=$e,g.createTopMatrixFromMatrix=bo,g.createTopMatrixFromRanges=_o,g.defaultWorkbookPermissionPoints=li,g.defaultWorksheetPermissionPoint=_n,g.expandToContinuousRange=$a,g.factoryRemoveNumfmtUndoMutation=Bl,g.factorySetNumfmtUndoMutation=Ll,g.findAllRectangle=qn,g.findFirstNonEmptyCell=Za,g.followSelectionOperation=Ue,g.generateNullCell=Kn,g.generateNullCellValue=ko,g.getAddMergeMutationRangeByType=Os,g.getAllRangePermissionPoint=le,g.getAllWorkbookPermissionPoint=Pt,g.getAllWorksheetPermissionPoint=de,g.getAllWorksheetPermissionPointByPointPanel=Ie,g.getCellAtRowCol=au,g.getDefaultRangePermission=Nl,g.getInsertRangeMutations=vs,g.getMoveRangeUndoRedoMutations=rn,g.getNextPrimaryCell=Vd,g.getPrimaryForRange=se,g.getRemoveRangeMutations=ps,g.getSelectionsService=Bo,g.getSeparateEffectedRangesOnCommand=Fu,g.getSheetCommandTarget=P,g.getSheetCommandTargetWorkbook=Bn,g.getSheetMutationTarget=ve,g.getSkeletonChangedEffectedRange=Na,g.getValueChangedEffectedRange=ka,g.getVisibleRanges=Dt,g.handleBaseInsertRange=Qe,g.handleBaseMoveRowsCols=Ht,g.handleBaseRemoveRange=Ze,g.handleCommonDefaultRangeChangeWithEffectRefCommands=Ns,g.handleCommonRangeChangeWithEffectRefCommandsSkipNoInterests=Bu,g.handleDefaultRangeChangeWithEffectRefCommands=ks,g.handleDefaultRangeChangeWithEffectRefCommandsSkipNoInterests=Lu,g.handleDeleteRangeMoveLeft=fr,g.handleDeleteRangeMoveUp=Ir,g.handleDeleteRangeMutation=fu,g.handleIRemoveCol=Ps,g.handleIRemoveRow=hr,g.handleInsertCol=Rr,g.handleInsertRangeMoveDown=Cr,g.handleInsertRangeMoveRight=Sr,g.handleInsertRangeMutation=Su,g.handleInsertRow=gr,g.handleMoveCols=Us,g.handleMoveRange=mr,g.handleMoveRows=Ts,g.isSingleCellSelection=lu,g.packNumberMap=Hn,g.rangeMerge=Yn,g.rangeToDiscreteRange=No,g.rotateRange=he,g.runRefRangeMutations=et,g.setEndForRange=uu,g.splitRangeText=Po,g.transformCellsToRange=Pn,g.unpackNumberMap=Fn,Object.defineProperty(g,Symbol.toStringTag,{value:"Module"})}));
|
|
10
|
+
(function(g,i){typeof exports=="object"&&typeof module<"u"?i(exports,require("@univerjs/core"),require("rxjs"),require("@univerjs/engine-formula"),require("rxjs/operators"),require("@univerjs/rpc")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","rxjs","@univerjs/engine-formula","rxjs/operators","@univerjs/rpc"],i):(g=typeof globalThis<"u"?globalThis:g||self,i(g.UniverSheets={},g.UniverCore,g.rxjs,g.UniverEngineFormula,g.rxjs.operators,g.UniverRpc))})(this,(function(g,i,O,J,kt,$i){"use strict";var Wd=Object.defineProperty;var Vd=(g,i,O)=>i in g?Wd(g,i,{enumerable:!0,configurable:!0,writable:!0,value:O}):g[i]=O;var f=(g,i,O)=>Vd(g,typeof i!="symbol"?i+"":i,O);function Li(s,e,t){var r,a,l;if(e.t)return e.t;if(e.v===null)return null;const n=s.getStyleByCell(e),o=s.getStyleByCell(t);if(t.t===i.CellValueType.FORCE_STRING){if(!i.isTextFormat((r=o==null?void 0:o.n)==null?void 0:r.pattern)&&e.v!==void 0){if(i.isRealNum(e.v))return i.CellValueType.NUMBER;if(i.isBooleanString(`${e.v}`))return i.CellValueType.BOOLEAN}return i.CellValueType.FORCE_STRING}return Bi(n)?i.isTextFormat((a=n==null?void 0:n.n)==null?void 0:a.pattern)?i.CellValueType.STRING:eo(e,t):i.isTextFormat((l=o==null?void 0:o.n)==null?void 0:l.pattern)?i.CellValueType.STRING:eo(e,t)}function eo(s,e){return s.v!==void 0?Vn(s.v,s.t):Vn(e.v,e.t)}function Bi(s){var e;return!!((e=s==null?void 0:s.n)!=null&&e.pattern)}function Vn(s,e){return s===null?null:typeof s=="string"?i.isRealNum(s)?(+s==0||+s==1)&&e===i.CellValueType.BOOLEAN?i.CellValueType.BOOLEAN:e!==i.CellValueType.STRING&&e!==i.CellValueType.FORCE_STRING&&i.willLoseNumericPrecision(s)?i.CellValueType.FORCE_STRING:i.CellValueType.NUMBER:i.isBooleanString(s)?i.CellValueType.BOOLEAN:i.CellValueType.STRING:typeof s=="number"?(s===0||s===1)&&e===i.CellValueType.BOOLEAN?i.CellValueType.BOOLEAN:i.CellValueType.NUMBER:typeof s=="boolean"?i.CellValueType.BOOLEAN:i.CellValueType.FORCE_STRING}const ge=(s,e)=>{if(s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId)==null)throw new Error("universheet is null error!");return{unitId:e.unitId,subUnitId:e.subUnitId,ranges:i.Tools.deepClone(e.ranges)}},j={id:"sheet.mutation.add-worksheet-merge",type:i.CommandType.MUTATION,handler:(s,e)=>{const n=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(n==null)throw new Error("universheet is null error!");const o=n.getSheetBySheetId(e.subUnitId);if(!o)return!1;const a=o.getConfig().mergeData,l=e.ranges;for(let u=0;u<l.length;u++)a.push(l[u]);return o.getSpanModel().rebuild(a),!0}},Hi=i.createInterceptorKey("CELL_CONTENT"),Fi=i.createInterceptorKey("ROW_FILTERED"),Ae={CELL_CONTENT:Hi,ROW_FILTERED:Fi};var to=(s=>(s[s.DATA_VALIDATION=9]="DATA_VALIDATION",s[s.NUMFMT=10]="NUMFMT",s[s.CELL_IMAGE=11]="CELL_IMAGE",s))(to||{});const no="sheet.interceptor.range-theme-id",so="sheet.interceptor.ignore-range-theme";var ji=Object.getOwnPropertyDescriptor,Gi=(s,e,t,n)=>{for(var o=n>1?void 0:n?ji(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},zi=(s,e)=>(t,n)=>e(t,n,s);const $n=i.createInterceptorKey("BEFORE_CELL_EDIT"),Zt=i.createInterceptorKey("AFTER_CELL_EDIT"),Qt=i.createInterceptorKey("VALIDATE_CELL");g.SheetInterceptorService=class extends i.Disposable{constructor(t){super();f(this,"_interceptorsByName",new Map);f(this,"_commandInterceptors",[]);f(this,"_rangeInterceptors",[]);f(this,"_autoHeightInterceptors",[]);f(this,"_beforeCommandInterceptor",[]);f(this,"_afterCommandInterceptors",[]);f(this,"_workbookDisposables",new Map);f(this,"_worksheetDisposables",new Map);f(this,"_interceptorsDirty",!1);f(this,"_composedInterceptorByKey",new Map);f(this,"writeCellInterceptor",new i.InterceptorManager({BEFORE_CELL_EDIT:$n,AFTER_CELL_EDIT:Zt,VALIDATE_CELL:Qt}));this._univerInstanceService=t,this.disposeWithMe(this._univerInstanceService.getTypeOfUnitAdded$(i.UniverInstanceType.UNIVER_SHEET).subscribe(n=>{this._interceptWorkbook(n)})),this.disposeWithMe(this._univerInstanceService.getTypeOfUnitDisposed$(i.UniverInstanceType.UNIVER_SHEET).subscribe(n=>this._disposeWorkbookInterceptor(n))),this.intercept(Ae.CELL_CONTENT,{priority:-1,effect:i.InterceptorEffectEnum.Style|i.InterceptorEffectEnum.Value,handler:n=>n}),this.disposeWithMe(this.writeCellInterceptor.intercept(Zt,{priority:-1,handler:n=>n})),this.disposeWithMe(this.writeCellInterceptor.intercept($n,{priority:-1,handler:n=>n})),this.disposeWithMe(this.writeCellInterceptor.intercept(Qt,{priority:-1,handler:n=>n}))}dispose(){super.dispose(),this._workbookDisposables.forEach(t=>t.dispose()),this._workbookDisposables.clear(),this._worksheetDisposables.forEach(t=>t.dispose()),this._worksheetDisposables.clear(),this._interceptorsByName.clear()}interceptCommand(t){if(this._commandInterceptors.includes(t))throw new Error("[SheetInterceptorService]: Interceptor already exists!");return this._commandInterceptors.push(t),this._commandInterceptors.sort((n,o)=>{var r,a;return((r=o.priority)!=null?r:0)-((a=n.priority)!=null?a:0)}),this.disposeWithMe(i.toDisposable(()=>i.remove(this._commandInterceptors,t)))}onCommandExecute(t){const n=this._commandInterceptors.map(o=>o.getMutations(t));return{preUndos:n.map(o=>{var r;return(r=o.preUndos)!=null?r:[]}).flat(),undos:n.map(o=>o.undos).flat(),preRedos:n.map(o=>{var r;return(r=o.preRedos)!=null?r:[]}).flat(),redos:n.map(o=>o.redos).flat()}}interceptAfterCommand(t){if(this._afterCommandInterceptors.includes(t))throw new Error("[SheetInterceptorService]: Interceptor already exists!");return this._afterCommandInterceptors.push(t),this._afterCommandInterceptors.sort((n,o)=>{var r,a;return((r=o.priority)!=null?r:0)-((a=n.priority)!=null?a:0)}),this.disposeWithMe(i.toDisposable(()=>i.remove(this._afterCommandInterceptors,t)))}afterCommandExecute(t){const n=this._afterCommandInterceptors.map(o=>o.getMutations(t));return{undos:n.map(o=>o.undos).flat(),redos:n.map(o=>o.redos).flat()}}interceptAutoHeight(t){if(this._autoHeightInterceptors.includes(t))throw new Error("[SheetInterceptorService]: Interceptor already exists!");return this._autoHeightInterceptors.push(t),this._autoHeightInterceptors.sort((n,o)=>{var r,a;return((r=o.priority)!=null?r:0)-((a=n.priority)!=null?a:0)}),this.disposeWithMe(i.toDisposable(()=>i.remove(this._autoHeightInterceptors,t)))}generateMutationsOfAutoHeight(t){const n=this._autoHeightInterceptors.map(o=>o.getMutations(t));return{preUndos:n.map(o=>{var r;return(r=o.preUndos)!=null?r:[]}).flat(),undos:n.map(o=>o.undos).flat(),preRedos:n.map(o=>{var r;return(r=o.preRedos)!=null?r:[]}).flat(),redos:n.map(o=>o.redos).flat()}}interceptBeforeCommand(t){if(this._beforeCommandInterceptor.includes(t))throw new Error("[SheetInterceptorService]: Interceptor already exists!");return this._beforeCommandInterceptor.push(t),this._beforeCommandInterceptor.sort((n,o)=>{var r,a;return((r=o.priority)!=null?r:0)-((a=n.priority)!=null?a:0)}),this.disposeWithMe(i.toDisposable(()=>i.remove(this._beforeCommandInterceptor,t)))}async beforeCommandExecute(t){return(await Promise.all(this._beforeCommandInterceptor.map(o=>o.performCheck(t)))).every(o=>o)}interceptRanges(t){if(this._rangeInterceptors.includes(t))throw new Error("[SheetInterceptorService]: Interceptor already exists!");return this._rangeInterceptors.push(t),this._rangeInterceptors.sort((n,o)=>{var r,a;return((r=o.priority)!=null?r:0)-((a=n.priority)!=null?a:0)}),this.disposeWithMe(i.toDisposable(()=>i.remove(this._rangeInterceptors,t)))}generateMutationsByRanges(t){const n=this._rangeInterceptors.map(o=>o.getMutations(t));return{preUndos:n.map(o=>{var r;return(r=o.preUndos)!=null?r:[]}).flat(),undos:n.map(o=>o.undos).flat(),preRedos:n.map(o=>{var r;return(r=o.preRedos)!=null?r:[]}).flat(),redos:n.map(o=>o.redos).flat()}}onWriteCell(t,n,o,r,a){const l={subUnitId:n.getSheetId(),unitId:t.getUnitId(),workbook:t,worksheet:n,row:o,col:r,origin:i.Tools.deepClone(a)};return this.writeCellInterceptor.fetchThroughInterceptors(Zt)(a,l)}onValidateCell(t,n,o,r){const a={subUnitId:n.getSheetId(),unitId:t.getUnitId(),workbook:t,worksheet:n,row:o,col:r};return this.writeCellInterceptor.fetchThroughInterceptors(Qt)(Promise.resolve(!0),a)}intercept(t,n){const o=t;this._interceptorsByName.has(o)||this._interceptorsByName.set(o,[]);const r=this._interceptorsByName.get(o);r.push(n);const a=r.sort((l,u)=>{var d,c;return((d=u.priority)!=null?d:0)-((c=l.priority)!=null?c:0)});if(this._interceptorsDirty=!0,o===Ae.CELL_CONTENT){const l=i.InterceptorEffectEnum.Style|i.InterceptorEffectEnum.Value;this._interceptorsByName.set(`${o}-${l}`,a);const u=i.InterceptorEffectEnum.Style|i.InterceptorEffectEnum.Value;return this._interceptorsByName.set(`${o}-${i.InterceptorEffectEnum.Style}`,a.filter(d=>((d.effect||u)&i.InterceptorEffectEnum.Style)>0)),this._interceptorsByName.set(`${o}-${i.InterceptorEffectEnum.Value}`,a.filter(d=>((d.effect||u)&i.InterceptorEffectEnum.Value)>0)),this.disposeWithMe(i.toDisposable(()=>{i.remove(this._interceptorsByName.get(o),n),i.remove(this._interceptorsByName.get(`${o}-${l}`),n),i.remove(this._interceptorsByName.get(`${o}-${i.InterceptorEffectEnum.Style}`),n),i.remove(this._interceptorsByName.get(`${o}-${i.InterceptorEffectEnum.Value}`),n)}))}else return this._interceptorsByName.set(o,a),this.disposeWithMe(i.toDisposable(()=>i.remove(this._interceptorsByName.get(o),n)))}fetchThroughInterceptors(t,n,o,r){const a=n===void 0?t:`${t}-${n}`,l=o!=null?o:a;let u=this._composedInterceptorByKey.get(l);if(!u||this._interceptorsDirty){let d=this._interceptorsByName.get(a);d&&r&&(d=d.filter(r)),u=i.composeInterceptors(d||[]),this._composedInterceptorByKey.set(l,u)}return u}_interceptWorkbook(t){const n=new i.DisposableCollection,o=t.getUnitId(),r=this,a=l=>{const u=l.getSheetId();l.__interceptViewModel(d=>{const c=new i.DisposableCollection;r._worksheetDisposables.set(oo(o,l),c),c.add(d.registerCellContentInterceptor({getCell(m,h,R,C,S){const I=l.getCellRaw(m,h);return r.fetchThroughInterceptors(Ae.CELL_CONTENT,R,C,S)(I,{unitId:o,subUnitId:u,row:m,col:h,worksheet:l,workbook:t,rawData:I})}})),c.add(d.registerRowFilteredInterceptor({getRowFiltered(m){return!!r.fetchThroughInterceptors(Ae.ROW_FILTERED)(!1,{unitId:o,subUnitId:u,row:m,workbook:t,worksheet:l})}}))})};t.getSheets().forEach(l=>a(l)),n.add(t.sheetCreated$.subscribe(l=>a(l))),n.add(i.toDisposable(()=>t.getSheets().forEach(l=>this._disposeSheetInterceptor(o,l)))),n.add(t.sheetDisposed$.subscribe(l=>this._disposeSheetInterceptor(o,l))),this._workbookDisposables.set(o,n)}_disposeWorkbookInterceptor(t){const n=t.getUnitId(),o=this._workbookDisposables.get(n);o&&(o.dispose(),this._workbookDisposables.delete(n))}_disposeSheetInterceptor(t,n){const o=oo(t,n),r=this._worksheetDisposables.get(o);r&&(r.dispose(),this._worksheetDisposables.delete(o))}},g.SheetInterceptorService=Gi([zi(0,i.IUniverInstanceService)],g.SheetInterceptorService);function oo(s,e){return`${s}|${e.getSheetId()}`}const Z=s=>{const e={};return s.bg&&(e.bg={...s.bg}),s.ol&&(e.ol={...s.ol}),s.bd&&(e.bd={...s.bd}),s.cl&&(e.cl={...s.cl}),s.ht&&(e.ht=s.ht),s.vt&&(e.vt=s.vt),s.bl!==void 0&&(e.bl=s.bl),e};function qi(s){const e={};if(s.length===1)return s[0];for(const t of s)t.bg&&(e.bg=t.bg),t.ol&&(e.ol=t.ol),t.bd&&(e.bd={...e.bd,...t.bd}),t.cl&&(e.cl=t.cl),t.ht&&(e.ht=t.ht),t.vt&&(e.vt=t.vt),t.bl!==void 0&&(e.bl=t.bl);return e}const x={wholeStyle:1,headerRowStyle:2,headerColumnStyle:4,firstRowStyle:8,secondRowStyle:16,lastRowStyle:32,firstColumnStyle:128,secondColumnStyle:256,lastColumnStyle:512};class We{constructor(e,t){f(this,"_name");f(this,"wholeStyle",null);f(this,"headerRowStyle",null);f(this,"headerColumnStyle",null);f(this,"firstRowStyle",null);f(this,"secondRowStyle",null);f(this,"lastRowStyle",null);f(this,"firstColumnStyle",null);f(this,"secondColumnStyle",null);f(this,"lastColumnStyle",null);f(this,"_mergeCacheMap",new Map);t&&this.fromJson({...t,name:e}),this._name=e}getName(){return this._name}getWholeStyle(){return this.wholeStyle}setWholeStyle(e){this.wholeStyle=e,this._resetStyleCache()}getFirstRowStyle(){return this.firstRowStyle}setFirstRowStyle(e){this.firstRowStyle=e,this._resetStyleCache()}getSecondRowStyle(){return this.secondRowStyle}setSecondRowStyle(e){this.secondRowStyle=e,this._resetStyleCache()}getLastRowStyle(){return this.lastRowStyle}setLastRowStyle(e){this.lastRowStyle=e,this._resetStyleCache()}getFirstColumnStyle(){return this.firstColumnStyle}setFirstColumnStyle(e){this.firstColumnStyle=e,this._resetStyleCache()}getSecondColumnStyle(){return this.secondColumnStyle}setSecondColumnStyle(e){this.secondColumnStyle=e,this._resetStyleCache()}getLastColumnStyle(){return this.lastColumnStyle}setLastColumnStyle(e){this.lastColumnStyle=e,this._resetStyleCache()}getHeaderRowStyle(){return this.headerRowStyle}setHeaderRowStyle(e){this.headerRowStyle=e,this._resetStyleCache()}getHeaderColumnStyle(){return this.headerColumnStyle}setHeaderColumnStyle(e){this.headerColumnStyle=e,this._resetStyleCache()}getStyle(e,t,n,o,r){let a=0;return n&&(a=a|x.lastRowStyle),o&&(a=a|x.lastColumnStyle),e>=0&&t>=0&&(a=a|x.wholeStyle),e%2===1&&(a=a|(r?x.secondRowStyle:x.firstRowStyle)),e%2===0&&(a=a|(r?x.firstRowStyle:x.secondRowStyle)),e===0&&(a=a|x.headerRowStyle),t===0&&(a=a|x.headerColumnStyle),t%2===1&&(a=a|x.firstColumnStyle),t%2===0&&(a=a|x.secondColumnStyle),a===0?null:this._getMergeStyle(a)}_getMergeStyle(e){let t=this._mergeCacheMap.get(e);return t||(t=this._mergeStyle(e),this._mergeCacheMap.set(e,t)),t}_mergeStyle(e){const t=[];return this.wholeStyle&&e&x.wholeStyle&&t.push(this.wholeStyle),this.firstColumnStyle&&e&x.firstColumnStyle&&t.push(this.firstColumnStyle),this.secondColumnStyle&&e&x.secondColumnStyle&&t.push(this.secondColumnStyle),this.firstRowStyle&&e&x.firstRowStyle&&t.push(this.firstRowStyle),this.secondRowStyle&&e&x.secondRowStyle&&t.push(this.secondRowStyle),this.headerColumnStyle&&e&x.headerColumnStyle&&t.push(this.headerColumnStyle),this.lastColumnStyle&&e&x.lastColumnStyle&&t.push(this.lastColumnStyle),this.headerRowStyle&&e&x.headerRowStyle&&t.push(this.headerRowStyle),this.lastRowStyle&&e&x.lastRowStyle&&t.push(this.lastRowStyle),qi(t)}_resetStyleCache(){this._mergeCacheMap.clear()}toJson(){const e={name:this._name};return this.wholeStyle&&(e.wholeStyle=Z(this.wholeStyle)),this.headerRowStyle&&(e.headerRowStyle=Z(this.headerRowStyle)),this.headerColumnStyle&&(e.headerColumnStyle=Z(this.headerColumnStyle)),this.firstRowStyle&&(e.firstRowStyle=Z(this.firstRowStyle)),this.secondRowStyle&&(e.secondRowStyle=Z(this.secondRowStyle)),this.lastRowStyle&&(e.lastRowStyle=Z(this.lastRowStyle)),this.firstColumnStyle&&(e.firstColumnStyle=Z(this.firstColumnStyle)),this.secondColumnStyle&&(e.secondColumnStyle=Z(this.secondColumnStyle)),this.lastColumnStyle&&(e.lastColumnStyle=Z(this.lastColumnStyle)),e}fromJson(e){this._name=e.name,e.wholeStyle&&(this.wholeStyle=Z(e.wholeStyle)),e.headerRowStyle&&(this.headerRowStyle=Z(e.headerRowStyle)),e.headerColumnStyle&&(this.headerColumnStyle=Z(e.headerColumnStyle)),e.firstRowStyle&&(this.firstRowStyle=Z(e.firstRowStyle)),e.secondRowStyle&&(this.secondRowStyle=Z(e.secondRowStyle)),e.lastRowStyle&&(this.lastRowStyle=Z(e.lastRowStyle)),e.firstColumnStyle&&(this.firstColumnStyle=Z(e.firstColumnStyle)),e.secondColumnStyle&&(this.secondColumnStyle=Z(e.secondColumnStyle)),e.lastColumnStyle&&(this.lastColumnStyle=Z(e.lastColumnStyle))}dispose(){this._mergeCacheMap.clear()}}const Yi=(s,e,t)=>new We(`light-${s}`,{headerRowStyle:{bg:{rgb:e}},firstColumnStyle:{bg:{rgb:"rgb(255, 255, 255)"}},secondColumnStyle:{bg:{rgb:t}},lastRowStyle:{bg:{rgb:e}}}),Ki=(s,e,t)=>new We(`middle-${s}`,{headerRowStyle:{bg:{rgb:e}},headerColumnStyle:{bg:{rgb:t}},secondRowStyle:{bg:{rgb:t}},lastRowStyle:{bg:{rgb:e}},lastColumnStyle:{bg:{rgb:t}}}),Ji=(s,e,t,n)=>new We(`dark-${s}`,{headerRowStyle:{bg:{rgb:e},cl:{rgb:"rgb(255, 255, 255)"},ht:i.HorizontalAlign.CENTER,bl:i.BooleanNumber.TRUE},firstRowStyle:{bg:{rgb:t}},secondRowStyle:{bg:{rgb:n}},lastRowStyle:{bg:{rgb:e}}}),xi=[{baseName:"blue",header:"rgb(164, 202, 254)",color:"rgb(225, 239, 254)"},{baseName:"grey",header:"rgb(205, 208, 216)",color:"rgb(238, 239, 241)"},{baseName:"red",header:"rgb(248, 180, 180)",color:"rgb(253, 232, 232)"},{baseName:"orange",header:"rgb(253, 186, 140)",color:"rgb(254, 236, 220)"},{baseName:"yellow",header:"rgb(250, 200, 21)",color:"rgb(255, 244, 185)"},{baseName:"green",header:"rgb(132, 225, 188)",color:"rgb(222, 247, 236)"},{baseName:"azure",header:"rgb(126, 220, 226)",color:"rgb(213, 245, 246)"},{baseName:"indigo",header:"rgb(186, 198, 248)",color:"rgb(233, 237, 255)"},{baseName:"purple",header:"rgb(202, 191, 253)",color:"rgb(237, 235, 254)"},{baseName:"magenta",header:"rgb(248, 180, 217)",color:"rgb(252, 232, 243)"}],Xi=[{baseName:"blue",rowHeader:"rgb(63, 131, 248)",colHeader:"rgb(195, 221, 253)"},{baseName:"grey",rowHeader:"rgb(95, 101, 116)",colHeader:"rgb(227, 229, 234)"},{baseName:"red",rowHeader:"rgb(240, 82, 82)",colHeader:"rgb(251, 213, 213)"},{baseName:"orange",rowHeader:"rgb(255, 90, 31)",colHeader:"rgb(252, 217, 189)"},{baseName:"yellow",rowHeader:"rgb(212, 157, 15)",colHeader:"rgb(252, 220, 106)"},{baseName:"green",rowHeader:"rgb(13, 164, 113)",colHeader:"rgb(188, 240, 218)"},{baseName:"azure",rowHeader:"rgb(6, 148, 162)",colHeader:"rgb(175, 236, 239)"},{baseName:"indigo",rowHeader:"rgb(70, 106, 247)",colHeader:"rgb(210, 218, 250)"},{baseName:"purple",rowHeader:"rgb(144, 97, 249)",colHeader:"rgb(220, 215, 254)"},{baseName:"magenta",rowHeader:"rgb(231, 70, 148)",colHeader:"rgb(250, 209, 232)"}],Zi=[{baseName:"blue",rowHeader:"rgb(30, 66, 159)",firstRow:"rgb(195, 221, 253)",secondRow:"rgb(118, 169, 250)"},{baseName:"grey",rowHeader:"rgb(44, 48, 64)",firstRow:"rgb(227, 229, 234)",secondRow:"rgb(151, 157, 172)"},{baseName:"red",rowHeader:"rgb(155, 28, 28)",firstRow:"rgb(251, 213, 213)",secondRow:"rgb(249, 128, 128)"},{baseName:"orange",rowHeader:"rgb(180, 52, 3)",firstRow:"rgb(252, 217, 189)",secondRow:"rgb(255, 138, 76)"},{baseName:"yellow",rowHeader:"rgb(154, 109, 21)",firstRow:"rgb(252, 220, 106)",secondRow:"rgb(212, 157, 15)"},{baseName:"green",rowHeader:"rgb(4, 108, 78)",firstRow:"rgb(188, 240, 218)",secondRow:"rgb(49, 196, 141)"},{baseName:"azure",rowHeader:"rgb(3, 102, 114)",firstRow:"rgb(175, 236, 239)",secondRow:"rgb(22, 189, 202)"},{baseName:"indigo",rowHeader:"rgb(16, 51, 191)",firstRow:"rgb(210, 218, 250)",secondRow:"rgb(98, 128, 249)"},{baseName:"purple",rowHeader:"rgb(74, 29, 150)",firstRow:"rgb(220, 215, 254)",secondRow:"rgb(172, 148, 250)"},{baseName:"magenta",rowHeader:"rgb(153, 21, 75)",firstRow:"rgb(250, 209, 232)",secondRow:"rgb(241, 126, 184)"}],Qi=xi.map(({baseName:s,header:e,color:t})=>Yi(s,e,t)),ea=Xi.map(({baseName:s,rowHeader:e,colHeader:t})=>Ki(s,e,t)),ta=Zi.map(({baseName:s,rowHeader:e,firstRow:t,secondRow:n})=>Ji(s,e,t,n)),na=[...Qi,...ea,...ta],ro={headerRowStyle:{bg:{rgb:"rgb(68,114,196)"},cl:{rgb:"rgb(255,255,255)"},ht:i.HorizontalAlign.CENTER,bl:i.BooleanNumber.TRUE},firstRowStyle:{bg:{rgb:"rgb(217,225,242)"}}},sa=new We("default",ro),oa=new We("default-last-row",{...ro,lastRowStyle:{bd:{t:{s:i.BorderStyleTypes.THIN,cl:{rgb:"rgb(68,114,196)"}}},ht:i.HorizontalAlign.CENTER,bl:i.BooleanNumber.TRUE}});class ra{constructor(){f(this,"_toggleRanges",[])}refresh(e,t){const{startRow:n,endRow:o}=e,r=[];let a=0,l=!1,u=-1;for(let d=n;d<=o;d++){if(!t(d)){a++,a%2===1?l=!0:(l=!1,u!==-1&&(r.push([u,d-1]),u=-1));continue}a%2===1?l?u===-1&&(u=d):(l=!0,u=d):l&&(r.push([u,d-2]),l=!1,u=-1),d===o&&l&&r.push([u,d])}this._toggleRanges=r}getToggleRanges(){return this._toggleRanges.concat()}getIsToggled(e){let t=0,n=this._toggleRanges.length-1;for(;t<=n;){const o=Math.floor((t+n)/2),[r,a]=this._toggleRanges[o];if(e<r)n=o-1;else if(e>a)t=o+1;else return!0}return!1}}var ia=Object.getOwnPropertyDescriptor,aa=(s,e,t,n)=>{for(var o=n>1?void 0:n?ia(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},Ln=(s,e)=>(t,n)=>e(t,n,s);const la="SHEET_RANGE_THEME_MODEL_PLUGIN";g.SheetRangeThemeModel=class extends i.Disposable{constructor(t,n,o){super();f(this,"_rangeThemeStyleMap",new Map);f(this,"_rangeThemeStyleRuleMap",new Map);f(this,"_rTreeCollection",new Map);f(this,"_defaultRangeThemeMap",new Map);f(this,"_zebraCrossingCacheMap",new Map);f(this,"_rowVisibleFuncSet",new Map);f(this,"_rangeThemeMapChanged$",new O.Subject);f(this,"rangeThemeMapChange$",this._rangeThemeMapChanged$.asObservable());this._sheetInterceptorService=t,this._resourceManagerService=n,this._univerInstanceService=o,this._registerIntercept(),this._initSnapshot(),this._initDefaultTheme()}_initDefaultTheme(){this.registerDefaultRangeTheme(sa),this.registerDefaultRangeTheme(oa);for(const t of na)this.registerDefaultRangeTheme(t)}_ensureRangeThemeStyleMap(t){return this._rangeThemeStyleMap.has(t)||this._rangeThemeStyleMap.set(t,new Map),this._rangeThemeStyleMap.get(t)}_ensureRangeThemeStyleRuleMap(t){return this._rangeThemeStyleRuleMap.has(t)||this._rangeThemeStyleRuleMap.set(t,new Map),this._rangeThemeStyleRuleMap.get(t)}_ensureRTreeCollection(t){return this._rTreeCollection.has(t)||this._rTreeCollection.set(t,new i.RTree),this._rTreeCollection.get(t)}getDefaultRangeThemeStyle(t){return this._defaultRangeThemeMap.get(t)}getCustomRangeThemeStyle(t,n){return this._ensureRangeThemeStyleMap(t).get(n)}_getSheetRowVisibleFuncSet(t,n){this._rowVisibleFuncSet.has(t)||this._rowVisibleFuncSet.set(t,new Map);const o=this._rowVisibleFuncSet.get(t);return o.has(n)||o.set(n,new Set),o.get(n)}_getSheetRowVisibleHasInit(t,n){var o;return!!(this._rowVisibleFuncSet.has(t)&&((o=this._rowVisibleFuncSet.get(t))!=null&&o.has(n)))}refreshSheetRowVisibleFuncSet(t,n){const o=this._getSheetRowVisibleFuncSet(t,n);o.clear();const r=this._univerInstanceService.getUnit(t);if(r){const a=r.getSheetBySheetId(n);if(a){const l=a.getRowCount(),u=a.getRowManager();for(let d=1;d<=l;d++)a.getRowVisible(d)?u.getRowHeight(d)===0&&o.add(d):o.add(d)}}}_ensureZebraCrossingCache(t,n,o){this._zebraCrossingCacheMap.has(t)||this._zebraCrossingCacheMap.set(t,new Map);const r=this._zebraCrossingCacheMap.get(t);r.has(n)||r.set(n,new Map);const a=r.get(n);return a.has(o)||a.set(o,new ra),a.get(o)}registerRangeThemeRule(t,n){const{unitId:o,subUnitId:r,range:a}=n,l=i.generateRandomId(),u=this._ensureRangeThemeStyleRuleMap(o),d=this._ensureRTreeCollection(o);u.set(l,{rangeInfo:n,themeName:t}),d.insert({unitId:o,sheetId:r,range:a,id:l}),this._getSheetRowVisibleHasInit(o,r)||this.refreshSheetRowVisibleFuncSet(o,r);const c=this._ensureZebraCrossingCache(o,r,l),m=this._getSheetRowVisibleFuncSet(o,r);c.refresh(a,h=>!m.has(h))}getRegisteredRangeThemeStyle(t){const{unitId:n,subUnitId:o,range:r}=t,a=this._ensureRTreeCollection(n),l=Array.from(a.bulkSearch([{unitId:n,sheetId:o,range:r}]));if(l[0]){const d=this._ensureRangeThemeStyleRuleMap(n).get(l[0]);if(d)return d.themeName}}refreshZebraCrossingCacheBySheet(t,n){this._zebraCrossingCacheMap.has(t)||this._zebraCrossingCacheMap.set(t,new Map);const o=this._zebraCrossingCacheMap.get(t);o.has(n)||o.set(n,new Map);const r=o.get(n);r&&r.forEach((a,l)=>{const d=this._ensureRangeThemeStyleRuleMap(t).get(l);d?a.refresh(d.rangeInfo.range,c=>!this._getSheetRowVisibleFuncSet(t,n).has(c)):r.delete(l)})}removeRangeThemeRule(t,n){const{unitId:o,subUnitId:r,range:a}=n,l=this._ensureRTreeCollection(o),u=Array.from(l.bulkSearch([{unitId:o,sheetId:r,range:a}])),d=this._ensureRangeThemeStyleRuleMap(o);for(let c=0;c<u.length;c++){const m=d.get(u[c]);if(m&&m.themeName===t){d.delete(u[c]),l.remove({unitId:o,sheetId:r,range:a,id:u[c]});const h=this._zebraCrossingCacheMap.get(o);if(h){const R=h.get(r);R&&R.delete(u[c])}break}}}registerDefaultRangeTheme(t){this._defaultRangeThemeMap.set(t.getName(),t),this._rangeThemeMapChanged$.next({type:"add",styleName:t.getName()})}unRegisterDefaultRangeTheme(t){this._defaultRangeThemeMap.delete(t),this._rangeThemeMapChanged$.next({type:"remove",styleName:t})}getRegisteredRangeThemes(){return Array.from(this._defaultRangeThemeMap.keys())}registerRangeThemeStyle(t,n){this._ensureRangeThemeStyleMap(t).set(n.getName(),n),this._rangeThemeMapChanged$.next({type:"add",styleName:n.getName()})}unregisterRangeThemeStyle(t,n){this._ensureRangeThemeStyleMap(t).delete(n),this._rangeThemeMapChanged$.next({type:"remove",styleName:n})}getALLRegisteredTheme(t){return Array.from(this._ensureRangeThemeStyleMap(t).keys())}getRangeThemeStyle(t,n){return this._defaultRangeThemeMap.has(n)?this._defaultRangeThemeMap.get(n):this._ensureRangeThemeStyleMap(t).get(n)}getCellStyle(t,n,o,r){const a={startRow:o,startColumn:r,endRow:o,endColumn:r},l=this._ensureRTreeCollection(t),u=Array.from(l.bulkSearch([{unitId:t,sheetId:n,range:a}]));if(u[0]){const c=this._ensureRangeThemeStyleRuleMap(t).get(u[0]);if(c){const{rangeInfo:m,themeName:h}=c,R=o-m.range.startRow,C=r-m.range.startColumn,S=this.getRangeThemeStyle(t,h),v=this._ensureZebraCrossingCache(t,n,u[0]).getIsToggled(o);if(S)return S.getStyle(R,C,o===m.range.endRow,r===m.range.endColumn,v)}}}_registerIntercept(){this.disposeWithMe(this._sheetInterceptorService.intercept(Ae.CELL_CONTENT,{id:no,effect:i.InterceptorEffectEnum.Style,handler:(t,n,o)=>{const{row:r,col:a,unitId:l,subUnitId:u}=n,d=this.getCellStyle(l,u,r,a);if(d){const c=!t||t===n.rawData?{...n.rawData}:t;return c.themeStyle=d,o(c)}return o(t)}}))}toJson(t){const n=this._ensureRangeThemeStyleRuleMap(t),o=this._ensureRangeThemeStyleMap(t);if(o.size===0&&n.size===0)return"{}";const r={};n.forEach((l,u)=>{r[u]=l});const a={};return o.forEach((l,u)=>{a[u]=l.toJson()}),JSON.stringify({rangeThemeStyleRuleMap:r,rangeThemeStyleMapJson:a})}fromJSON(t,n){const{rangeThemeStyleRuleMap:o,rangeThemeStyleMapJson:r}=n;o&&Object.keys(o).forEach(a=>{const l=o[a],{themeName:u,rangeInfo:d}=l;u.startsWith("table")||(this.registerRangeThemeRule(u,d),this._ensureRTreeCollection(d.unitId).insert({unitId:a,sheetId:d.subUnitId,range:d.range,id:a}))}),r&&Object.keys(r).forEach(a=>{const l=r[a],u=new We(l.name);u.fromJson(l),this._ensureRangeThemeStyleMap(t).set(u.getName(),u)})}deleteUnitId(t){this._rangeThemeStyleMap.delete(t),this._rangeThemeStyleRuleMap.delete(t),this._rTreeCollection.delete(t)}_initSnapshot(){this.disposeWithMe(this._resourceManagerService.registerPluginResource({toJson:t=>this.toJson(t),parseJson:t=>{if(!t)return{};try{return JSON.parse(t)}catch{return{}}},businesses:[i.UniverInstanceType.UNIVER_SHEET],pluginName:la,onLoad:(t,n)=>{this.fromJSON(t,n)},onUnLoad:t=>{this.deleteUnitId(t)}}))}dispose(){super.dispose(),this._rangeThemeStyleMap.clear(),this._rangeThemeStyleRuleMap.clear(),this._defaultRangeThemeMap.clear(),this._rTreeCollection.clear(),this._zebraCrossingCacheMap.clear(),this._rowVisibleFuncSet.clear()}},g.SheetRangeThemeModel=aa([Ln(0,i.Inject(g.SheetInterceptorService)),Ln(1,i.Inject(i.IResourceManagerService)),Ln(2,i.Inject(i.IUniverInstanceService))],g.SheetRangeThemeModel);function Bn(s,e){const{unitId:t}=e,n=t?s.getUnit(t,i.UniverInstanceType.UNIVER_SHEET):s.getCurrentUnitOfType(i.UniverInstanceType.UNIVER_SHEET);return n?{workbook:n,unitId:n.getUnitId()}:null}function P(s,e={}){const{unitId:t,subUnitId:n}=e,o=t?s.getUnit(t,i.UniverInstanceType.UNIVER_SHEET):s.getCurrentUnitOfType(i.UniverInstanceType.UNIVER_SHEET);if(!o)return null;const r=n?o.getSheetBySheetId(n):o.getActiveSheet(!0);return r?{worksheet:r,workbook:o,unitId:o.getUnitId(),subUnitId:r.getSheetId()}:null}function ve(s,e){const{unitId:t,subUnitId:n}=e,o=s.getUnit(t,i.UniverInstanceType.UNIVER_SHEET);if(!o)return null;const r=o.getSheetBySheetId(n);return r?{worksheet:r,workbook:o}:null}const rt={id:"sheet.mutation.set-worksheet-range-theme-style",type:i.CommandType.MUTATION,handler:(s,e)=>{const{unitId:t,subUnitId:n,range:o,themeName:r}=e,a=s.get(i.IUniverInstanceService),l=P(a),u=s.get(g.SheetRangeThemeModel);return l?(u.registerRangeThemeRule(r,{range:o,unitId:t,subUnitId:n}),!0):!1}},io=(s,e)=>{const t=ve(s.get(i.IUniverInstanceService),e);if(!t)throw new Error("[SetWorksheetRangeThemeStyleMutation]: worksheet is null error!");const{worksheet:n}=t;return{unitId:e.unitId,subUnitId:n.getSheetId(),range:e.range,themeName:e.themeName}},it={id:"sheet.mutation.remove-worksheet-range-theme-style",type:i.CommandType.MUTATION,handler:(s,e)=>{const{unitId:t,subUnitId:n,range:o,themeName:r}=e,a=s.get(i.IUniverInstanceService),l=P(a),u=s.get(g.SheetRangeThemeModel);return l?(u.removeRangeThemeRule(r,{range:o,unitId:t,subUnitId:n}),!0):!1}},ao=(s,e)=>{const t=ve(s.get(i.IUniverInstanceService),e);if(!t)throw new Error("[DeleteWorksheetRangeThemeStyleMutationFactory]: worksheet is null error!");const{worksheet:n}=t;return{unitId:e.unitId,subUnitId:n.getSheetId(),range:e.range,themeName:e.themeName}},en=(s,e)=>{if(s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId)==null)throw new Error("universheet is null error!");return{unitId:e.unitId,subUnitId:e.subUnitId,range:e.range}},re={id:"sheet.mutation.insert-row",type:i.CommandType.MUTATION,handler:(s,e)=>{var C;const{unitId:t,subUnitId:n,range:o,rowInfo:r}=e,l=s.get(i.IUniverInstanceService).getUniverSheetInstance(t);if(l==null)throw new Error("universheet is null error!");const u=l.getSheetBySheetId(n);if(u==null)throw new Error("worksheet is null error!");const d=u.getRowManager().getRowData(),c={h:u.getConfig().defaultRowHeight,hd:0},m=o.startRow,h=o.endRow-o.startRow+1;for(let S=m;S<m+h;S++)r?i.insertMatrixArray(S,(C=r[S-o.startRow])!=null?C:c,d):i.insertMatrixArray(S,c,d);return u.setRowCount(u.getRowCount()+h),u.getCellMatrix().insertRows(o.startRow,h),!0}},Nt=(s,e)=>{if(s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId)==null)throw new Error("universheet is null error!");return{unitId:e.unitId,subUnitId:e.subUnitId,range:e.range}},ie={id:"sheet.mutation.insert-col",type:i.CommandType.MUTATION,handler:(s,e)=>{var C;const n=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(n==null)throw new Error("universheet is null error!");const o=n.getSheetBySheetId(e.subUnitId);if(!o)return!1;const r=o.getColumnManager(),{range:a,colInfo:l}=e,d=r.getColumnData(),c=a.startColumn,m=a.endColumn-a.startColumn+1,h=o.getConfig().defaultColumnWidth;for(let S=c;S<c+m;S++){const I={w:h,hd:0};l?i.insertMatrixArray(S,(C=l[S-a.startColumn])!=null?C:I,d):i.insertMatrixArray(S,I,d)}return o.setColumnCount(o.getColumnCount()+a.endColumn-a.startColumn+1),o.getCellMatrix().insertColumns(a.startColumn,m),!0}},Le={id:"sheet.mutation.move-range",type:i.CommandType.MUTATION,handler:(s,e)=>{const{from:t,to:n}=e;if(!t||!n)return!1;const r=s.get(i.IUniverInstanceService).getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET);if(!r)return!1;const a=r.getSheetBySheetId(e.from.subUnitId),l=r.getSheetBySheetId(e.to.subUnitId);if(!a||!l)return!1;const u=a.getCellMatrix(),d=l.getCellMatrix();return new i.ObjectMatrix(t.value).forValue((c,m,h)=>{h==null?u.realDeleteValue(c,m):u.setValue(c,m,h)}),new i.ObjectMatrix(n.value).forValue((c,m,h)=>{h==null?d.realDeleteValue(c,m):d.setValue(c,m,h)}),!0}};function lo(s,e){const{unitId:t,subUnitId:n,sourceRange:o,targetRange:r}=e,a=o.startRow>r.startRow,l=o.endRow-o.startRow+1;return a?{unitId:t,subUnitId:n,sourceRange:i.Rectangle.clone(r),targetRange:{...o,endRow:o.endRow+l,startRow:o.startRow+l}}:{unitId:t,subUnitId:n,targetRange:i.Rectangle.clone(o),sourceRange:{...r,endRow:r.endRow-l,startRow:r.startRow-l}}}const pe={id:"sheet.mutation.move-rows",type:i.CommandType.MUTATION,handler:(s,e)=>{const{unitId:t,subUnitId:n,sourceRange:o,targetRange:r}=e,l=s.get(i.IUniverInstanceService).getUniverSheetInstance(t);if(!l)throw new Error("[MoveRowMutation] univerSheet is null!");const u=l.getSheetBySheetId(n);if(!u)throw new Error("[MoveRowMutation] worksheet is null!");const d=o.startRow,c=o.endRow-o.startRow+1,m=r.startRow,h=u.getRowManager().getRowData();return i.moveMatrixArray(d,c,m,h),u.getCellMatrix().moveRows(d,c,m),!0}};function uo(s,e){const{unitId:t,subUnitId:n,sourceRange:o,targetRange:r}=e,a=o.startColumn>r.startColumn,l=o.endColumn-o.startColumn+1;return a?{unitId:t,subUnitId:n,sourceRange:i.Rectangle.clone(r),targetRange:{...o,endColumn:o.endColumn+l,startColumn:o.startColumn+l}}:{unitId:t,subUnitId:n,targetRange:i.Rectangle.clone(o),sourceRange:{...r,startColumn:r.startColumn-l,endColumn:r.endColumn-l}}}const we={id:"sheet.mutation.move-columns",type:i.CommandType.MUTATION,handler:(s,e)=>{const{unitId:t,subUnitId:n,sourceRange:o,targetRange:r}=e,l=s.get(i.IUniverInstanceService).getUniverSheetInstance(t);if(!l)throw new Error("[MoveColumnMutation] univerSheet is null!");const u=l.getSheetBySheetId(n);if(!u)throw new Error("[MoveColumnMutation] worksheet is null!");const d=o.startColumn,c=o.endColumn-o.startColumn+1,m=r.startColumn,h=u.getColumnManager().getColumnData();return i.moveMatrixArray(d,c,m,h),u.getCellMatrix().moveColumns(d,c,m),!0}},ua=(s,e)=>{const o=e.getRowManager().getRowData(),r={},a=s.range,l=i.sliceMatrixArray(a.startRow,a.endRow,o),u=i.concatMatrixArray(r,l);return{unitId:s.unitId,subUnitId:s.subUnitId,range:s.range,rowInfo:u}},ae={id:"sheet.mutation.remove-rows",type:i.CommandType.MUTATION,handler:(s,e)=>{const n=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(n==null)throw new Error("universheet is null error!");const o=n.getSheetBySheetId(e.subUnitId);if(!o)return!1;const r=e.range,l=o.getRowManager().getRowData();for(let c=r.startRow;c<=r.endRow;c++)o.getRowFiltered(c);const u=r.endRow-r.startRow+1;return i.spliceArray(r.startRow,u,l),o.getCellMatrix().removeRows(r.startRow,u),o.setRowCount(o.getRowCount()-u),!0}},da=(s,e)=>{const n=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(n==null)throw new Error("universheet is null error!");const o=n.getSheetBySheetId(e.subUnitId);if(o==null)throw new Error("worksheet is null error!");const l=o.getColumnManager().getColumnData(),u={},d=e.range,c=i.sliceMatrixArray(d.startColumn,d.endColumn,l),m=i.concatMatrixArray(u,c);return{unitId:e.unitId,subUnitId:e.subUnitId,range:e.range,colInfo:m}},ne={id:"sheet.mutation.remove-col",type:i.CommandType.MUTATION,handler:(s,e)=>{const n=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(n==null)throw new Error("universheet is null error!");const o=n.getSheetBySheetId(e.subUnitId);if(!o)return!1;const r=e.range,l=o.getColumnManager().getColumnData(),u=r.endColumn-r.startColumn+1;return i.spliceArray(r.startColumn,u,l),o.setColumnCount(o.getColumnCount()-u),o.getCellMatrix().removeColumns(r.startColumn,u),!0}},le=(s,e)=>{const n=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(n==null)throw new Error("universheet is null error!");const o=n.getSheetBySheetId(e.subUnitId);if(o==null)throw new Error("worksheet is null error!");const a=o.getConfig().mergeData,l=e.ranges,u=[];for(let d=0;d<l.length;d++)for(let c=a.length-1;c>=0;c--){const m=a[c],h=l[d];i.Rectangle.intersects(m,h)&&u.push(a[c])}return{unitId:e.unitId,subUnitId:e.subUnitId,ranges:u}},G={id:"sheet.mutation.remove-worksheet-merge",type:i.CommandType.MUTATION,handler:(s,e)=>{const n=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(n==null)throw new Error("universheet is null error!");const o=n.getSheetBySheetId(e.subUnitId);if(!o)return!1;const a=o.getConfig().mergeData,l=e.ranges;for(let u=0;u<l.length;u++)for(let d=a.length-1;d>=0;d--){const c=a[d],m=l[u];i.Rectangle.intersects(c,m)&&a.splice(d,1)}return o.getSpanModel().rebuild(a),!0}},co=s=>{const{order:e}=s,t={};return Object.keys(e).forEach(n=>{t[e[Number(n)]]=Number(n)}),{...s,order:t}},Ot={id:"sheet.mutation.reorder-range",type:i.CommandType.MUTATION,handler:(s,e)=>{const{subUnitId:t,unitId:n,range:o,order:r}=e,u=s.get(i.IUniverInstanceService).getUnit(n).getSheetBySheetId(t);if(!u)return!1;const d=new i.ObjectMatrix;i.Range.foreach(o,(m,h)=>{if(r.hasOwnProperty(m)){const R=r[m],C=i.Tools.deepClone(u.getCellRaw(R,h));d.setValue(m,h,C)}});const c=u.getCellMatrix();return d.forValue((m,h,R)=>{c.setValue(m,h,R)}),!0}};function ca(s,e){if(s==null)return s;const t=i.Tools.deepClone(s);if(e==null)return t;const n={};return"h"in e&&(n.h=t.h),"ia"in e&&(n.ia=t.ia),"ah"in e&&(n.ah=t.ah),"hd"in e&&(n.hd=t.hd),"s"in e&&(n.s=t.s),"custom"in e&&(n.custom=t.custom),n}function ma(s,e){if(s==null)return s;const t=i.Tools.deepClone(s);if(e==null)return t;const n={};return"w"in e&&(n.w=t.w),"hd"in e&&(n.hd=t.hd),"s"in e&&(n.s=t.s),"custom"in e&&(n.custom=t.custom),n}const mo=(s,e)=>{const{unitId:t,subUnitId:n,columnData:o}=s,r={},a=e.getColumnManager();for(const l in o){const u=o[l],d=a.getColumn(Number(l));r[l]=ma(d,u)}return{unitId:t,subUnitId:n,columnData:r}},at={id:"sheet.mutation.set-col-data",type:i.CommandType.MUTATION,handler:(s,e)=>{const{columnData:t}=e,n=s.get(i.IUniverInstanceService),o=P(n,e);if(!o)return!1;const{worksheet:r}=o,a=r.getColumnManager();for(const l in t){const u=t[l];if(u==null){a.removeColumn(Number(l));continue}const d=a.getColumnOrCreate(Number(l));Object.assign(d,u)}return!0}},ha=(s,e)=>{if(s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId)==null)throw new Error("universheet is null error!");return{unitId:e.unitId,subUnitId:e.subUnitId,ranges:e.ranges}},lt={id:"sheet.mutation.set-col-hidden",type:i.CommandType.MUTATION,handler:(s,e)=>{const n=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(!n)return!1;const o=n.getSheetBySheetId(e.subUnitId).getColumnManager();for(let r=0;r<e.ranges.length;r++){const a=e.ranges[r];for(let l=a.startColumn;l<a.endColumn+1;l++){const u=o.getColumnOrCreate(l);u!=null&&(u.hd=i.BooleanNumber.TRUE)}}return!0}},ga=(s,e)=>{if(s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId)==null)throw new Error("universheet is null error!");return{unitId:e.unitId,subUnitId:e.subUnitId,ranges:e.ranges}},ut={id:"sheet.mutation.set-col-visible",type:i.CommandType.MUTATION,handler:(s,e)=>{const n=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(!n)return!1;const o=n.getSheetBySheetId(e.subUnitId).getColumnManager();for(let r=0;r<e.ranges.length;r++){const a=e.ranges[r];for(let l=a.startColumn;l<a.endColumn+1;l++){const u=o.getColumnOrCreate(l);u!=null&&(u.hd=i.BooleanNumber.FALSE)}}return!0}},dt={id:"sheet.mutation.set-gridlines-color",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=P(s.get(i.IUniverInstanceService),e);if(!t)return!1;const{worksheet:n}=t,o=n.getConfig();return o.gridlinesColor=e.color,!0}};function Ra(s,e,t){var a;const n=s.getStyleByCell(e);n==null&&delete e.s,typeof t.s=="string"&&(t.s=s.get(t.s));const o=tn(n,t.s?t.s:null);o&&(i.Tools.removeNull(o),Object.entries(o).forEach(([l,u])=>{typeof u=="object"&&u!==null&&Object.keys(u).length===0&&delete o[l]})),i.Tools.isEmptyObject(o)?delete e.s:e.s=s.setValue(o);const r=t.v?`${t.v}\r
|
|
11
|
+
`:"";!t.p&&e.p&&(r&&r!==((a=e.p.body)==null?void 0:a.dataStream)?delete e.p:fa(e.p,t.s?t.s:null))}function Ca(s,e){if(!e||!Object.keys(e).length)return s;const t=i.Tools.deepClone(s!=null?s:{});for(const n in e)n==="bd"?t[n]=Sa(t[n]||{},e[n]):n in t||(t[n]=null);return t}function Sa(s,e){if(!e||!Object.keys(e).length)return s;for(const t in e)t in s||(s[t]=null);return s}function tn(s,e,t=!1){if(e===null)return e;if(e===void 0)return s;const n=i.Tools.deepClone(s)||{};for(const o in e)t&&["bd","tr","td","ht","vt","tb","pd","bg"].includes(o)||(o in n&&o==="bd"?n[o]=Object.assign(n[o],e[o]):n[o]=e[o]);return"cl"in n&&("ul"in n&&n.ul&&(n.ul.cl=n.cl),"ol"in n&&n.ol&&(n.ol.cl=n.cl),"st"in n&&n.st&&(n.st.cl=n.cl)),n}function ho(s,e){return s.some(t=>t.startIndex===e)?ho(s,e+1):e}function fa(s,e){var a;if(s.body==null)return;Array.isArray(s.body.textRuns)||(s.body.textRuns=[]);let t=0;const n=[],o=((a=s.body)==null?void 0:a.paragraphs)||[];for(const l of s.body.textRuns){const{st:u,ed:d,ts:c={}}=l;if(t<u){const h={st:t,ed:u},R=tn({},e,!0);R&&i.Tools.removeNull(R),i.Tools.isEmptyObject(R)||(h.ts=R),n.push(h)}const m=tn(c,e,!0);m&&i.Tools.removeNull(m),i.Tools.isEmptyObject(m)?delete l.ts:l.ts=m,n.push(l),t=ho(o,d)}const r=s.body.dataStream.endsWith(`\r
|
|
12
|
+
`)?s.body.dataStream.length-2:s.body.dataStream.length;if(t<r){const l={st:t,ed:r},u=tn({},e,!0);u&&i.Tools.removeNull(u),i.Tools.isEmptyObject(u)||(l.ts=u),n.push(l)}s.body.textRuns=i.normalizeTextRuns(n)}function go(s,e){return e.v===void 0||e.v===null?e.v:s===i.CellValueType.NUMBER?Number(e.v):s===i.CellValueType.BOOLEAN?Ia(e.v)?1:0:s===i.CellValueType.STRING||s===i.CellValueType.FORCE_STRING?`${e.v}`:e.v}function Ia(s){if(typeof s=="string"){if(s.toUpperCase()==="TRUE")return!0;if(s.toUpperCase()==="FALSE")return!1;if(i.isSafeNumeric(s)){if(Number(s)===0)return!1;if(Number(s)===1)return!0}}if(typeof s=="number"){if(s===0)return!1;if(s===1)return!0}return typeof s=="boolean"?s:null}function va(s){return s==null?null:(s.f===void 0&&(s.f=null),s.si===void 0&&(s.si=null),s.p===void 0&&(s.p=null),s.v===void 0&&(s.v=null),s.t===void 0&&(s.t=null),s.s===void 0&&(s.s=null),s.custom===void 0&&(s.custom=null),s)}const ce=(s,e)=>{const{unitId:t,subUnitId:n,cellValue:o}=e,a=s.get(i.IUniverInstanceService).getUniverSheetInstance(t);if(a==null)throw new Error("workbook is null error!");const l=a.getSheetBySheetId(n);if(l==null)throw new Error("worksheet is null error!");const u=l.getCellMatrix(),d=a.getStyles(),c=new i.ObjectMatrix;return new i.ObjectMatrix(o).forValue((h,R,C)=>{const S=i.Tools.deepClone(u==null?void 0:u.getValue(h,R))||{},I=d.getStyleByCell(S),v=d.getStyleByCell(C);S.s=Ca(I,v),c.setValue(h,R,va(S))}),{...e,options:{},cellValue:c.getMatrix()}},F={id:"sheet.mutation.set-range-values",type:i.CommandType.MUTATION,handler:(s,e)=>{const{cellValue:t,subUnitId:n,unitId:o}=e,a=s.get(i.IUniverInstanceService).getUnit(o);if(!a)return!1;const l=a.getSheetBySheetId(n);if(!l)return!1;const u=l.getCellMatrix(),d=a.getStyles();return new i.ObjectMatrix(t).forValue((m,h,R)=>{if(!R)u.realDeleteValue(m,h);else{let C=u.getValue(m,h)||{};C=wa(R,C,d),i.Tools.isEmptyObject(C)?u.realDeleteValue(m,h):u.setValue(m,h,C)}}),!0}},pa=new Set(["f","p","si","custom","ref","xf"]);function wa(s,e,t){const n=Li(t,s,e);return Object.keys(s).forEach(o=>{const r=o;if(pa.has(r)){const a=s[r];Ma(e,r,a)}else r==="v"?s.v!==void 0&&(e.v=go(n,s)):r==="s"&&Ra(t,e,s)}),e.v!==void 0&&(e.t=n,e.v=go(n,e)),e.v===null&&(delete e.t,delete e.v),e}function Ma(s,e,t){t===void 0||(t===null?delete s[e]:s[e]=t)}const Ro=(s,e)=>{const{unitId:t,subUnitId:n,rowData:o}=s,r={},a=e.getRowManager();for(const l in o){const u=o[l],d=a.getRow(Number(l));r[l]=ca(d,u)}return{unitId:t,subUnitId:n,rowData:r}},ct={id:"sheet.mutation.set-row-data",type:i.CommandType.MUTATION,handler:(s,e)=>{const{rowData:t}=e,n=s.get(i.IUniverInstanceService),o=P(n,e);if(!o)return!1;const{worksheet:r}=o,a=r.getRowManager();for(const l in t){const u=t[l];if(u==null){a.removeRow(Number(l));continue}const d=a.getRowOrCreate(Number(l));Object.assign(d,u)}return!0}},ya=(s,e)=>{if(s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId)==null)throw new Error("universheet is null error!");return{unitId:e.unitId,subUnitId:e.subUnitId,ranges:e.ranges}},Ye={id:"sheet.mutation.set-row-visible",type:i.CommandType.MUTATION,handler:(s,e)=>{const n=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(n==null)throw new Error("universheet is null error!");const o=n.getSheetBySheetId(e.subUnitId).getRowManager();for(let r=0;r<e.ranges.length;r++){const a=e.ranges[r];for(let l=a.startRow;l<a.endRow+1;l++){const u=o.getRowOrCreate(l);u!=null&&(u.hd=0)}}return!0}},_a=(s,e)=>{if(s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId)==null)throw new Error("universheet is null error!");return{unitId:e.unitId,subUnitId:e.subUnitId,ranges:e.ranges}},Ke={id:"sheet.mutation.set-row-hidden",type:i.CommandType.MUTATION,handler:(s,e)=>{const n=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(n==null)throw new Error("universheet is null error!");const o=n.getSheetBySheetId(e.subUnitId).getRowManager();for(let r=0;r<e.ranges.length;r++){const a=e.ranges[r];for(let l=a.startRow;l<a.endRow+1;l++){const u=o.getRowOrCreate(l);u!=null&&(u.hd=1)}}return!0}},Hn=(s,e)=>{const{unitId:t,subUnitId:n,ranges:o}=s,r={},a=e.getColumnManager();for(let l=0;l<o.length;l++){const u=o[l];for(let d=u.startColumn;d<u.endColumn+1;d++)r[d]=a.getColumnWidth(d)}return{unitId:t,subUnitId:n,ranges:o,colWidth:r}},Ve={id:"sheet.mutation.set-worksheet-col-width",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=s.get(i.IUniverInstanceService),n=P(t,e);if(!n)return!1;const{worksheet:o}=n,r=o.getColumnManager(),a=e.ranges;for(let l=0;l<a.length;l++){const u=a[l];for(let d=u.startColumn;d<u.endColumn+1;d++)o.getColVisible(d)&&(typeof e.colWidth=="number"?r.setColumnWidth(d,e.colWidth):i.Tools.isDefine(e.colWidth[d])&&r.setColumnWidth(d,e.colWidth[d]))}return!0}},Co=(s,e)=>{const t=ve(s.get(i.IUniverInstanceService),e);if(!t)throw new Error("[SetWorksheetColumnCountUndoMutationFactory]: worksheet is null error!");return{unitId:e.unitId,subUnitId:e.subUnitId,columnCount:t.worksheet.getColumnCount()}},mt={id:"sheet.mutation.set-worksheet-column-count",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=s.get(i.IUniverInstanceService),n=ve(t,e);return n?(n.worksheet.setColumnCount(e.columnCount),!0):!1}},ht={id:"sheet.mutation.set-worksheet-default-style",type:i.CommandType.MUTATION,handler:(s,e)=>{const{defaultStyle:t}=e,n=s.get(i.IUniverInstanceService),o=P(n);if(!o)return!1;const{worksheet:r}=o;return r?(r.setDefaultCellStyle(t),!0):!1}},So=(s,e)=>{const t=ve(s.get(i.IUniverInstanceService),e);if(!t)throw new Error("[SetWorksheetDefaultStyleMutationFactory]: worksheet is null error!");const{worksheet:n}=t;return{unitId:e.unitId,subUnitId:n.getSheetId(),defaultStyle:n.getDefaultCellStyle()}},fo=(s,e)=>{const t=ve(s.get(i.IUniverInstanceService),e);if(!t)throw new Error("[SetWorksheetRowCountUndoMutationFactory]: worksheet is null error!");return{unitId:e.unitId,subUnitId:e.subUnitId,rowCount:t.worksheet.getRowCount()}},gt={id:"sheet.mutation.set-worksheet-row-count",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=s.get(i.IUniverInstanceService),n=ve(t,e);return n?(n.worksheet.setRowCount(e.rowCount),!0):!1}},Io=(s,e)=>{var l,u;const{unitId:t,subUnitId:n,ranges:o}=s,r={},a=e.getRowManager();for(const{startRow:d,endRow:c}of o)for(let m=d;m<c+1;m++)r[m]=(u=(l=a.getRow(m))==null?void 0:l.h)!=null?u:e.getConfig().defaultRowHeight;return{unitId:t,subUnitId:n,ranges:o,rowHeight:r}},Fn=(s,e)=>{var l;const{unitId:t,subUnitId:n,ranges:o}=s,r={},a=e.getRowManager();for(const{startRow:u,endRow:d}of o)for(let c=u;c<=d;c++)r[c]=(l=a.getRow(c))==null?void 0:l.ia;return{unitId:t,subUnitId:n,ranges:o,autoHeightInfo:r}},ba=(s,e)=>{var l,u;const{unitId:t,subUnitId:n,rowsAutoHeightInfo:o}=s,r=[],a=e.getRowManager();for(const d of o){const{row:c}=d;r.push({row:c,autoHeight:(u=(l=a.getRow(c))==null?void 0:l.ah)!=null?u:e.getConfig().defaultRowHeight})}return{unitId:t,subUnitId:n,rowsAutoHeightInfo:r}},Ee={id:"sheet.mutation.set-worksheet-row-height",type:i.CommandType.MUTATION,handler:(s,e)=>{const{ranges:t,rowHeight:n}=e,o=s.get(i.IUniverInstanceService),r=P(o,e);if(!r)return!1;const{worksheet:a}=r,l=a.getRowManager();for(const{startRow:u,endRow:d}of t)for(let c=u;c<=d;c++)typeof n=="number"?l.setRowHeight(c,n):i.Tools.isDefine(n[c])&&l.setRowHeight(c,n[c]);return!0}},Re={id:"sheet.mutation.set-worksheet-row-is-auto-height",type:i.CommandType.MUTATION,handler:(s,e)=>{var l;const{ranges:t,autoHeightInfo:n}=e,o=s.get(i.IUniverInstanceService),r=P(o,e);if(!r)return!1;const a=r.worksheet.getRowManager();for(const{startRow:u,endRow:d}of t)for(let c=u;c<=d;c++){const m=a.getRowOrCreate(c);typeof n=="number"?m.ia=n:m.ia=(l=n[c])!=null?l:void 0}return!0}},jn={id:"sheet.mutation.set-worksheet-row-auto-height",type:i.CommandType.MUTATION,handler:(s,e)=>{const{rowsAutoHeightInfo:t}=e,n=s.get(i.IUniverInstanceService),o=P(n,e);if(!o)return!1;const r=o.worksheet.getRowManager();for(const{row:a,autoHeight:l}of t){const u=r.getRowOrCreate(a);u.ah=l}return!0}},Rt={id:"sheet.mutation.toggle-gridlines",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=P(s.get(i.IUniverInstanceService),e);if(!t)return!1;const{worksheet:n}=t,o=n.getConfig();return o.showGridlines=e.showGridlines,!0}},Ct={id:"sheet.operation.set-worksheet-active",type:i.CommandType.OPERATION,handler:(s,e)=>{const t=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(!t)return!1;const n=t.getWorksheets();for(const[,o]of n)if(o.getSheetId()===e.subUnitId)return t.setActiveSheet(o),!0;return!1}};var vo=(s=>(s.SET_WORKSHEET_ROW_HEIGHT="sheet.mutation.set-worksheet-row-height",s.SET_WORKSHEET_ROW_IS_AUTO_HEIGHT="sheet.mutation.set-worksheet-row-is-auto-height",s.SET_WORKSHEET_ROW_AUTO_HEIGHT="sheet.mutation.set-worksheet-row-auto-height",s.SET_WORKSHEET_COL_WIDTH="sheet.mutation.set-worksheet-col-width",s.SET_WORKSHEET_ACTIVE="sheet.operation.set-worksheet-active",s.MOVE_ROWS="sheet.mutation.move-rows",s.MOVE_COLUMNS="sheet.mutation.move-columns",s.SET_COL_HIDDEN="sheet.mutation.set-col-hidden",s.SET_COL_VISIBLE="sheet.mutation.set-col-visible",s.SET_ROW_HIDDEN="sheet.mutation.set-row-hidden",s.SET_ROW_VISIBLE="sheet.mutation.set-row-visible",s.INSERT_COL="sheet.mutation.insert-col",s.INSERT_ROW="sheet.mutation.insert-row",s.REMOVE_COL="sheet.mutation.remove-col",s.REMOVE_ROW="sheet.mutation.remove-rows",s.TOGGLE_GRIDLINES="sheet.mutation.toggle-gridlines",s.SET_GRIDLINES_COLOR="sheet.mutation.set-gridlines-color",s))(vo||{}),po=(s=>(s.SET_RANGE_VALUES="sheet.mutation.set-range-values",s.MOVE_RANGE="sheet.mutation.move-range",s.REMOVE_WORKSHEET_MERGE="sheet.mutation.remove-worksheet-merge",s.ADD_WORKSHEET_MERGE="sheet.mutation.add-worksheet-merge",s.REORDER_RANGE="sheet.mutation.reorder-range",s.SET_WORKSHEET_DEFAULT_STYLE="sheet.mutation.set-worksheet-default-style",s.SET_ROW_DATA="sheet.mutation.set-row-data",s.SET_COL_DATA="sheet.mutation.set-col-data",s.SET_WORKSHEET_RANGE_THEME_STYLE="sheet.mutation.set-worksheet-range-theme-style",s.DELETE_WORKSHEET_RANGE_THEME_STYLE="sheet.mutation.delete-worksheet-range-theme-style",s))(po||{});const Ea=[Ee.id,Re.id,jn.id,Ve.id,Ct.id,pe.id,we.id,lt.id,ut.id,Ke.id,Ye.id,ie.id,re.id,ne.id,ae.id,Rt.id,dt.id,gt.id,mt.id],Ta=[F.id,Le.id,G.id,j.id,Ot.id,ht.id,ct.id,at.id,rt.id,it.id];function Ua(s){switch(s.id){case"sheet.mutation.set-range-values":{const e=s.params,t=new i.ObjectMatrix(e.cellValue).getDataRange();return t.endRow===-1?[]:e.cellValue?[{unitId:e.unitId,subUnitId:e.subUnitId,range:t}]:[]}case"sheet.mutation.move-range":{const e=s.params;return[{unitId:e.unitId,subUnitId:e.from.subUnitId,range:new i.ObjectMatrix(e.from.value).getRange()},{unitId:e.unitId,subUnitId:e.to.subUnitId,range:new i.ObjectMatrix(e.to.value).getRange()}]}case"sheet.mutation.remove-worksheet-merge":{const e=s.params;return e.ranges.map(t=>({unitId:e.unitId,subUnitId:e.subUnitId,range:t}))}case"sheet.mutation.add-worksheet-merge":{const e=s.params;return e.ranges.map(t=>({unitId:e.unitId,subUnitId:e.subUnitId,range:t}))}case"sheet.mutation.reorder-range":{const e=s.params;return[{unitId:e.unitId,subUnitId:e.subUnitId,range:e.range}]}case"sheet.mutation.set-worksheet-default-style":{const e=s.params;return[{unitId:e.unitId,subUnitId:e.subUnitId,range:{startRow:0,endRow:Number.MAX_SAFE_INTEGER,startColumn:0,endColumn:Number.MAX_SAFE_INTEGER}}]}case"sheet.mutation.set-row-data":{const e=s.params,t=Object.keys(e.rowData).map(Number);return t.length===0?[]:[{unitId:e.unitId,subUnitId:e.subUnitId,range:{startRow:Math.min(...t),endRow:Math.max(...t),startColumn:0,endColumn:Number.MAX_SAFE_INTEGER}}]}case"sheet.mutation.set-col-data":{const e=s.params,t=Object.keys(e.columnData).map(Number);return t.length===0?[]:[{unitId:e.unitId,subUnitId:e.subUnitId,range:{startRow:0,endRow:Number.MAX_SAFE_INTEGER,startColumn:Math.min(...t),endColumn:Math.max(...t)}}]}case"sheet.mutation.set-worksheet-range-theme-style":case"sheet.mutation.delete-worksheet-range-theme-style":{const e=s.params;return[{unitId:e.unitId,subUnitId:e.subUnitId,range:e.range}]}default:return[]}}function Pa(s,e){switch(s.id){case"sheet.mutation.set-worksheet-row-height":case"sheet.mutation.set-worksheet-row-is-auto-height":{const t=s.params;return t.ranges.map(n=>({unitId:t.unitId,subUnitId:t.subUnitId,range:{...n,rangeType:i.RANGE_TYPE.ROW}}))}case"sheet.mutation.set-worksheet-row-auto-height":{const t=s.params;return t.rowsAutoHeightInfo.map(n=>({unitId:t.unitId,subUnitId:t.subUnitId,range:{startRow:n.row,endRow:n.row,startColumn:0,endColumn:e-1,rangeType:i.RANGE_TYPE.ROW}}))}case"sheet.mutation.set-worksheet-col-width":{const t=s.params;return t.ranges.map(n=>({unitId:t.unitId,subUnitId:t.subUnitId,range:{...n,rangeType:i.RANGE_TYPE.COLUMN}}))}case"sheet.mutation.move-rows":case"sheet.mutation.move-columns":{const t=s.params;return[{unitId:t.unitId,subUnitId:t.subUnitId,range:t.targetRange},{unitId:t.unitId,subUnitId:t.subUnitId,range:t.sourceRange}]}case"sheet.mutation.set-col-hidden":case"sheet.mutation.set-col-visible":{const t=s.params;return t.ranges.map(n=>({unitId:t.unitId,subUnitId:t.subUnitId,range:{...n,rangeType:i.RANGE_TYPE.COLUMN}}))}case"sheet.mutation.set-row-hidden":case"sheet.mutation.set-row-visible":{const t=s.params;return t.ranges.map(n=>({unitId:t.unitId,subUnitId:t.subUnitId,range:{...n,rangeType:i.RANGE_TYPE.ROW}}))}case"sheet.mutation.insert-col":{const t=s.params;return[{unitId:t.unitId,subUnitId:t.subUnitId,range:{...t.range,rangeType:i.RANGE_TYPE.COLUMN}}]}case"sheet.mutation.insert-row":{const t=s.params;return[{unitId:t.unitId,subUnitId:t.subUnitId,range:{...t.range,rangeType:i.RANGE_TYPE.ROW}}]}case"sheet.mutation.remove-col":{const t=s.params;return[{unitId:t.unitId,subUnitId:t.subUnitId,range:{...t.range,rangeType:i.RANGE_TYPE.COLUMN}}]}case"sheet.mutation.remove-rows":{const t=s.params;return[{unitId:t.unitId,subUnitId:t.subUnitId,range:{...t.range,rangeType:i.RANGE_TYPE.ROW}}]}case"sheet.mutation.toggle-gridlines":case"sheet.mutation.set-gridlines-color":return[];default:return[]}}function wo(s){return s==null?!1:s.v!==void 0&&s.v!==null&&s.v!==""||s.p!==void 0}function nn(s,e){return s&&s.spanAnchor?wo(e.getValue(s.spanAnchor.startRow,s.spanAnchor.startColumn)):wo(s)}function ka(s,e,t,n,o){const r=s.getCellMatrix(),a=s.getSpanModel().getMergedCellRange(e,t,n,o),l=new i.ObjectMatrix;return r.forValue((u,d)=>{const c=r.getValue(u,d);c&&l.setValue(u,d,c)}),a.forEach(u=>{const{startColumn:d,startRow:c,endColumn:m,endRow:h}=u;i.createRowColIter(c,h,d,m).forEach((R,C)=>{R===c&&C===d&&l.setValue(R,C,{...r.getValue(R,C),spanAnchor:{startRow:c,endRow:h,startColumn:d,endColumn:m}}),(R!==c||C!==d)&&(l.realDeleteValue(R,C),l.setValue(R,C,{spanAnchor:{startRow:c,endRow:h,startColumn:d,endColumn:m}}))})}),l}function Na(s,e,t,n){const{startRow:o,startColumn:r,endRow:a}=s;let l=null,u=!1;for(let d=o;d<=a;d++){const c=e.getValue(d,r-t);if(u=u||nn(c,e),!n&&u)break;c&&c.spanAnchor&&(l?l={startRow:Math.min(c.spanAnchor.startRow,l.startRow),startColumn:Math.min(c.spanAnchor.startColumn,l.startColumn),endRow:Math.max(c.spanAnchor.endRow,l.endRow),endColumn:Math.max(c.spanAnchor.endColumn,l.endColumn)}:l={startRow:c.spanAnchor.startRow,startColumn:c.spanAnchor.startColumn,endRow:c.spanAnchor.endRow,endColumn:c.spanAnchor.endColumn})}return u?(s.startColumn=s.startColumn-t,{spanAnchor:l,hasValue:!0,range:s}):{spanAnchor:null,hasValue:!1,range:s}}function Oa(s,e,t,n){const{startRow:o,endColumn:r,endRow:a}=s;let l=null,u=!1;for(let d=o;d<=a;d++){const c=e.getValue(d,r+t);if(u=u||nn(c,e),!n&&u)break;c&&c.spanAnchor&&(l?l={startRow:Math.min(c.spanAnchor.startRow,l.startRow),startColumn:Math.min(c.spanAnchor.startColumn,l.startColumn),endRow:Math.max(c.spanAnchor.endRow,l.endRow),endColumn:Math.max(c.spanAnchor.endColumn,l.endColumn)}:l={startRow:c.spanAnchor.startRow,startColumn:c.spanAnchor.startColumn,endRow:c.spanAnchor.endRow,endColumn:c.spanAnchor.endColumn})}return u?(s.endColumn=s.endColumn+t,{spanAnchor:l,hasValue:!0,range:s}):{spanAnchor:null,hasValue:!1,range:s}}function Da(s,e,t,n){const{startRow:o,startColumn:r,endColumn:a}=s;let l=null,u=!1;for(let d=r;d<=a;d++){const c=e.getValue(o-t,d);if(u=u||nn(c,e),!n&&u)break;c&&c.spanAnchor&&(l?l={startRow:Math.min(c.spanAnchor.startRow,l.startRow),startColumn:Math.min(c.spanAnchor.startColumn,l.startColumn),endRow:Math.max(c.spanAnchor.endRow,l.endRow),endColumn:Math.max(c.spanAnchor.endColumn,l.endColumn)}:l={startRow:c.spanAnchor.startRow,startColumn:c.spanAnchor.startColumn,endRow:c.spanAnchor.endRow,endColumn:c.spanAnchor.endColumn})}return u?(s.startRow=s.startRow-t,{spanAnchor:l,hasValue:!0,range:s}):{spanAnchor:null,hasValue:!1,range:s}}function Aa(s,e,t,n){const{startColumn:o,endColumn:r,endRow:a}=s;let l=null,u=!1;for(let d=o;d<=r;d++){const c=e.getValue(a+t,d);if(u=u||nn(c,e),!n&&u)break;c&&c.spanAnchor&&(l?l={startRow:Math.min(c.spanAnchor.startRow,l.startRow),startColumn:Math.min(c.spanAnchor.startColumn,l.startColumn),endRow:Math.max(c.spanAnchor.endRow,l.endRow),endColumn:Math.max(c.spanAnchor.endColumn,l.endColumn)}:l={startRow:c.spanAnchor.startRow,startColumn:c.spanAnchor.startColumn,endRow:c.spanAnchor.endRow,endColumn:c.spanAnchor.endColumn})}return u?(s.endRow=s.endRow+t,{spanAnchor:l,hasValue:!0,range:s}):{spanAnchor:null,hasValue:!1,range:s}}function Wa(s,e,t){const n=t.getMaxRows(),o=t.getMaxColumns(),r=ka(t,0,0,n-1,o-1),a=t.getSnapshot().mergeData.length>0,{left:l,right:u,up:d,down:c}=e;let m=!0,h={...s};const R=[];for(;m;){if(m=!1,d&&h.startRow!==0){const{hasValue:C,range:S,spanAnchor:I}=Da(h,r,1,a);if(I&&R.push(I),C){h=S,m=!0;continue}}if(c&&h.endRow!==n-1){const{hasValue:C,range:S,spanAnchor:I}=Aa(h,r,1,a);if(I&&R.push(I),C){h=S,m=!0;continue}}if(l&&h.startColumn!==0){const{hasValue:C,range:S,spanAnchor:I}=Na(h,r,1,a);if(I&&R.push(I),C){h=S,m=!0;continue}}if(u&&h.endColumn!==o-1){const{hasValue:C,range:S,spanAnchor:I}=Oa(h,r,1,a);if(I&&R.push(I),C){h=S,m=!0;continue}}}return R.length>0&&(h=i.Rectangle.union(h,...R)),h}const Mo=s=>{const e=new i.ObjectMatrix;return s.forEach(t=>{i.Range.foreach(t,(n,o)=>{e.setValue(n,o,1)})}),e.forValue((t,n)=>{const o=e.getValue(t-1,n);o&&e.setValue(t,n,o+1)}),e},yo=s=>{const e=s;return e.forValue((t,n)=>{const o=s.getValue(t-1,n);o&&e.setValue(t,n,o+1)}),e},_o=s=>{const e={area:0},t=(n,o)=>e.area<n?(e.area=n,e.range=o,!0):!1;return s.forValue((n,o,r)=>{let a=1,l=r;t(a*l,{startRow:n-l+1,endRow:n,startColumn:o,endColumn:o});const u={startRow:n-l+1,endRow:n,startColumn:0,endColumn:o};for(let d=o-1;d>=0&&s.getValue(n,d);d--){l=Math.min(s.getValue(n,d)||0,l),a++;const c=l*a;u.startColumn=d,u.startRow=n-l+1,t(c,u)}}),e},Va=(s,e)=>{i.Range.foreach(e,(t,n)=>{s.realDeleteValue(t,n)});for(let t=e.startColumn;t<=e.endColumn;t++){const n=e.endRow+1;if(s.getValue(n,t)>0){s.setValue(n,t,1);let r=n+1;for(;s.getValue(r,t)>0;)s.setValue(r,t,s.getValue(r-1,t)+1),r++}}return s},Gn=s=>{const e=[];let t=_o(s);for(;t.area>0;)t.range&&(e.push(t.range),Va(s,t.range)),t=_o(s);return e},zn=s=>{const e=Mo(s);return Gn(e)};class $a{constructor(){f(this,"_matrix",new i.ObjectMatrix)}add(...e){return e.forEach(t=>{i.Range.foreach(t,(n,o)=>{this._matrix.setValue(n,o,1)})}),this}subtract(...e){return e.forEach(t=>{i.Range.foreach(t,(n,o)=>{this._matrix.realDeleteValue(n,o)})}),this}merge(){const e=yo(this._matrix);return Gn(e)}}const La=1.5,Ba="rgba(255, 255, 255, 0.01)";function Ha(s){const{rangeWithCoord:e,primaryWithCoord:t,style:n}=s,o={range:{startRow:e.startRow,startColumn:e.startColumn,endRow:e.endRow,endColumn:e.endColumn,rangeType:e.rangeType,unitId:e.unitId,sheetId:e.sheetId},primary:null,style:n};return t!=null&&(o.primary=bo(t)),o}function bo(s){const{actualRow:e,actualColumn:t,isMerged:n,isMergedMainCell:o}=s,{startRow:r,startColumn:a,endRow:l,endColumn:u}=s.mergeInfo;return{actualRow:e,actualColumn:t,isMerged:n,isMergedMainCell:o,startRow:r,startColumn:a,endRow:l,endColumn:u}}var Eo=(s=>(s[s.Tab=1]="Tab",s[s.Comma=2]="Comma",s[s.Semicolon=4]="Semicolon",s[s.Space=8]="Space",s[s.Custom=16]="Custom",s))(Eo||{});class Fa{constructor(){f(this,"_tabCount",0);f(this,"_commaCount",0);f(this,"_semicolonCount",0);f(this,"_spaceCount",0)}add(e){switch(e){case" ":this._tabCount++;break;case",":this._commaCount++;break;case";":this._semicolonCount++;break;case" ":this._spaceCount++;break}}update(e){e&&typeof e=="string"&&(e.includes(" ")&&this._tabCount++,e.includes(",")&&this._commaCount++,e.includes(";")&&this._semicolonCount++,e.trim().includes(" ")&&this._spaceCount++)}getDelimiter(){const e=Math.max(this._tabCount,this._commaCount,this._semicolonCount,this._spaceCount);return e===0||e===this._tabCount?1:e===this._commaCount?2:e===this._semicolonCount?4:e===this._spaceCount?8:1}}function ja(s,e,t){const n=[];t!==void 0&&(s&16)>0&&n.push(t),(s&1)>0&&n.push(" "),(s&2)>0&&n.push(","),(s&4)>0&&n.push(";"),(s&8)>0&&n.push(" ");let o="";for(const a of n)o+=Ga(a);let r="[".concat(o,"]");return e&&(r+="+"),new RegExp(r)}function Ga(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const za=s=>{var t;return((t=s.body)==null?void 0:t.dataStream.replace(/\r\n$/,""))||""};function qa(s){if(s!=null){if(s.p)return za(s.p);if(s.v&&typeof s.v=="string")return s.v;if(s.t&&(s.t===i.CellValueType.FORCE_STRING||s.t===i.CellValueType.STRING))return String(s.v)}}function To(s,e,t,n,o=!1){const r=i.Range.transformRange(e,s),{startColumn:a,startRow:l,endColumn:u,endRow:d}=r;if(a!==u)throw new Error("The range must be in the same column.");if(t&&(t&16)>0&&(n===void 0||n.length!==1))throw new Error("The custom delimiter must a character.");const c=t===void 0,m=c?new Fa:null,h=[];for(let p=l;p<=d;p++){const w=s.getCell(p,a),y=qa(w);h.push(y),m&&m.update(y)}const R=c?m.getDelimiter():t,C=ja(R,o,n);let S=-1,I=0,v=0;const M=[];for(const p of h){if(p!==void 0){const w=String(p).split(C);S<0?S=w.length:S=Math.max(S,w.length),M.push(w),I=v}else M.push(void 0);v++}return{rs:M,maxLength:S===-1?0:S,lastRow:I}}const Ya=(s,e,t="")=>s.reduce((n,o)=>{const r=o&&o[e];return typeof r!="string"?(console.warn(o,`${e} is not string`),n):(r?(n[r]||(n[r]=[]),n[r].push(o)):n[t].push(o),n)},{}),Ka=(s=0)=>{let e=s;return function(){return e++}};function Ja(s){return s==null?!1:s.v!==void 0&&s.v!==null&&s.v!==""||s.p!==void 0}function xa(s,e){for(let t=s.startRow;t<=s.endRow;t++)for(let n=s.startColumn;n<=s.endColumn;n++){const o=e.getCell(t,n);if(Ja(o))return{startRow:t,startColumn:n,endRow:t,endColumn:n}}return null}function qn(s){const e=new i.ObjectMatrix;return s.forEach(t=>{const{startRow:n,startColumn:o,endRow:r,endColumn:a}=t;for(let l=n;l<=r;l++)for(let u=o;u<=a;u++)e.setValue(l,u,null)}),e.clone()}function Uo(s){const e=new i.ObjectMatrix;return s.forEach(t=>{const{startRow:n,startColumn:o,endRow:r,endColumn:a}=t;for(let l=n;l<=r;l++)for(let u=o;u<=a;u++)e.setValue(l,u,{v:null,p:null,f:null,si:null,custom:null})}),e.clone()}function Xa(s){const e=new i.ObjectMatrix;return s.forEach(t=>{const{startRow:n,startColumn:o,endRow:r,endColumn:a}=t;for(let l=n;l<=r;l++)for(let u=o;u<=a;u++)e.setValue(l,u,{s:null})}),e.clone()}function Po(s,e,t,n){const o=e.get(i.IUniverInstanceService),r=t?o.getUnit(t,i.UniverInstanceType.UNIVER_SHEET):o.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET),a=n?r==null?void 0:r.getSheetBySheetId(n):r==null?void 0:r.getActiveSheet();if(!a)return null;const{startRow:l,endRow:u,startColumn:d,endColumn:c}=s,m=[],h=[];for(let R=l;R<=u;R++)a.getRowFiltered(R)||m.push(R);for(let R=d;R<=c;R++)h.push(R);return{rows:m,cols:h}}function Dt(s,e,t,n){const o=[],r=[];for(const h of s){const R=Po(h,e,t,n);R&&(o.push(...R.rows),r.push(...R.cols))}const a=Array.from(new Set(o)).sort((h,R)=>h-R),l=Array.from(new Set(r)).sort((h,R)=>h-R),u=[];function d(h){const R=[];let C=h[0];for(let S=1;S<h.length;S++)h[S]!==h[S-1]+1&&(R.push([C,h[S-1]]),C=h[S]);return R.push([C,h[h.length-1]]),R}const c=d(a),m=d(l);for(const[h,R]of c)for(const[C,S]of m)u.push({startRow:h,endRow:R,startColumn:C,endColumn:S});return u}var ko=(s=>(s.OthersCanView="othersCanView",s.NoOneElseCanView="noOneElseCanView",s))(ko||{}),No=(s=>(s.DesignedUserCanEdit="designedUserCanEdit",s.OnlyMe="onlyMe",s))(No||{});class X{constructor(){f(this,"_model",new Map);f(this,"_ruleChange$",new O.Subject);f(this,"ruleChange$",this._ruleChange$.asObservable());f(this,"_ruleRefresh$",new O.Subject);f(this,"ruleRefresh$",this._ruleRefresh$.asObservable());f(this,"_rangeRuleInitStateChange",new O.BehaviorSubject(!1));f(this,"rangeRuleInitStateChange$",this._rangeRuleInitStateChange.asObservable())}dispose(){this._ruleChange$.complete(),this._ruleRefresh$.complete()}ruleRefresh(e){this._ruleRefresh$.next(e)}getRangeRuleInitState(){return this._rangeRuleInitStateChange.value}changeRuleInitState(e){this._rangeRuleInitStateChange.next(e)}addRule(e,t,n){this._ensureRuleMap(e,t).set(n.id,n),this._ruleChange$.next({unitId:e,subUnitId:t,rule:n,type:"add"})}deleteRule(e,t,n){var r,a,l,u;const o=(a=(r=this._model.get(e))==null?void 0:r.get(t))==null?void 0:a.get(n);o&&((u=(l=this._model.get(e))==null?void 0:l.get(t))==null||u.delete(n),this._ruleChange$.next({unitId:e,subUnitId:t,rule:o,type:"delete"}))}setRule(e,t,n,o){var a,l;const r=this.getRule(e,t,n);r&&((l=(a=this._model.get(e))==null?void 0:a.get(t))==null||l.set(n,o),this._ruleChange$.next({unitId:e,subUnitId:t,oldRule:r,rule:o,type:"set"}))}getRule(e,t,n){var o,r;return(r=(o=this._model.get(e))==null?void 0:o.get(t))==null?void 0:r.get(n)}getSubunitRuleList(e,t){var o;return[...(((o=this._model.get(e))==null?void 0:o.get(t))||new Map).values()]}getSubunitRuleListLength(e,t){var o;const n=(o=this._model.get(e))==null?void 0:o.get(t);return n?n.size:0}_ensureRuleMap(e,t){let n=this._model.get(e);n||(n=new Map,this._model.set(e,n));let o=n.get(t);return o||(o=new Map,n.set(t,o)),o}toObject(){const e={};return[...this._model.keys()].forEach(n=>{const o=this._model.get(n),r=[...o.keys()];e[n]={},r.forEach(a=>{const l=o.get(a);e[n][a]=[...l.values()]})}),e}fromObject(e){const t=new Map;Object.keys(e).forEach(n=>{const o=e[n],r=new Map;Object.keys(o).forEach(a=>{const l=o[a].reduce((u,d)=>(u.set(d.id,d),u),new Map);r.set(a,l)}),t.set(n,r)}),this._model=t}deleteUnitModel(e){this._model.delete(e)}createRuleId(e,t){let n=i.generateRandomId(4);const o=this._ensureRuleMap(e,t);for(;o.has(n);)n=i.generateRandomId(4);return n}getTargetByPermissionId(e,t){const n=this._model.get(e);if(!n)return null;for(const[o,r]of n)for(const a of r.values())if(a.permissionId===t)return[e,o];return null}}const Za=(s,e)=>{const t=s.get(X),n=e.ruleIds.map(r=>t.getRule(e.unitId,e.subUnitId,r)).filter(r=>!!r);return{id:Ce.id,params:{subUnitId:e.subUnitId,unitId:e.unitId,rules:n}}},Te={id:"sheet.mutation.delete-range-protection",type:i.CommandType.MUTATION,handler:(s,e)=>{const{unitId:t,subUnitId:n,ruleIds:o}=e,r=s.get(X);return o.forEach(a=>{r.deleteRule(t,n,a)}),!0}},Qa=s=>{const e={...s,ruleIds:s.rules.map(t=>t.id)};return{id:Te.id,params:e}},Ce={id:"sheet.mutation.add-range-protection",type:i.CommandType.MUTATION,handler:(s,e)=>{const{unitId:t,subUnitId:n,rules:o}=e,r=s.get(X);return o.forEach(a=>{r.addRule(t,n,a)}),!0}},Oo={type:i.CommandType.COMMAND,id:"sheet.command.add-range-protection",async handler(s,e){if(!e)return!1;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(X),{rule:r,permissionId:a}=e,{unitId:l,subUnitId:u,ranges:d,description:c,viewState:m,editState:h}=r,R=[{ranges:d,permissionId:a,id:o.createRuleId(l,u),description:c,unitType:r.unitType,unitId:l,subUnitId:u,viewState:m,editState:h}];if(await t.executeCommand(Ce.id,{unitId:l,subUnitId:u,rules:R})){const S=[{id:Ce.id,params:{unitId:l,subUnitId:u,rules:R}}],I=[{id:Te.id,params:{unitId:l,subUnitId:u,ruleIds:R.map(v=>v.id)}}];n.pushUndoRedo({unitID:l,redoMutations:S,undoMutations:I})}return!0}};var te=(s=>(s[s.MOVE_START=0]="MOVE_START",s[s.MOVING=1]="MOVING",s[s.MOVE_END=2]="MOVE_END",s[s.ONLY_SET=3]="ONLY_SET",s))(te||{});class Do extends i.Disposable{constructor(t){super();f(this,"_worksheetSelections",new Map);f(this,"_selectionMoveStart$",new O.Subject);f(this,"selectionMoveStart$",this._selectionMoveStart$.asObservable());f(this,"_selectionMoving$",new O.Subject);f(this,"selectionMoving$",this._selectionMoving$.asObservable());f(this,"_selectionMoveEnd$",new O.BehaviorSubject([]));f(this,"selectionMoveEnd$",this._selectionMoveEnd$.asObservable());f(this,"_selectionSet$",new O.BehaviorSubject([]));f(this,"selectionSet$",this._selectionSet$.asObservable());f(this,"selectionChanged$");f(this,"_beforeSelectionMoveEnd$",new O.BehaviorSubject([]));f(this,"beforeSelectionMoveEnd$",this._beforeSelectionMoveEnd$.asObservable());this._workbook=t,this.selectionChanged$=O.merge(this._selectionMoveEnd$,this._selectionSet$)}dispose(){super.dispose(),this._beforeSelectionMoveEnd$.complete(),this._selectionMoveEnd$.complete(),this._selectionMoving$.complete(),this._selectionMoveStart$.complete(),this._selectionSet$.complete(),this._workbook=null}addSelections(t,n){const o=this.getSelectionsOfWorksheet(t);o.push(...n),this._selectionSet$.next(o)}setSelections(t,n=[],o){switch(this.setSelectionsOfWorksheet(t,n),o){case te.MOVE_START:this._selectionMoveStart$.next(n);break;case te.MOVING:this._selectionMoving$.next(n);break;case te.MOVE_END:this._beforeSelectionMoveEnd$.next(n),this._selectionMoveEnd$.next(n);break;case te.ONLY_SET:{this._selectionSet$.next(n);break}default:this._selectionSet$.next(n);break}}getCurrentSelections(){return this._getCurrentSelections()}getSelectionOfWorksheet(t){return this.getSelectionsOfWorksheet(t)}getSelectionsOfWorksheet(t){return this._worksheetSelections.has(t)||this._worksheetSelections.set(t,[]),this._worksheetSelections.get(t)}setSelectionsOfWorksheet(t,n){this._worksheetSelections.set(t,[...n])}deleteSheetSelection(t){this._worksheetSelections.set(t,[])}clear(){this._worksheetSelections.clear(),this._selectionSet$.next([])}_getCurrentSelections(){return this.getSelectionsOfWorksheet(this._workbook.getActiveSheet().getSheetId())}getCurrentLastSelection(){const t=this._getCurrentSelections();return t[t.length-1]}}var el=Object.getOwnPropertyDescriptor,tl=(s,e,t,n)=>{for(var o=n>1?void 0:n?el(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},nl=(s,e)=>(t,n)=>e(t,n,s);g.SheetsSelectionsService=class extends i.RxDisposable{constructor(t){super();f(this,"_cellStylesCache",new Map);f(this,"selectionMoveStart$");f(this,"selectionMoving$");f(this,"selectionMoveEnd$");f(this,"selectionSet$");f(this,"selectionChanged$");f(this,"_workbookSelections",new Map);this._instanceSrv=t,this._init()}get _currentSelectionPos(){const t=this._instanceSrv.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET);if(!t)return null;const n=t.getActiveSheet();return{unitId:t.getUnitId(),sheetId:n.getSheetId()}}get currentSelectionParam(){return this._currentSelectionPos}_init(){const t=this._instanceSrv.getCurrentTypeOfUnit$(i.UniverInstanceType.UNIVER_SHEET).pipe(O.shareReplay(1),O.takeUntil(this.dispose$));this.selectionMoveStart$=t.pipe().pipe(O.switchMap(n=>n?this._ensureWorkbookSelection(n.getUnitId()).selectionMoveStart$:O.of())).pipe(O.takeUntil(this.dispose$)),this.selectionMoving$=t.pipe(O.switchMap(n=>n?this._ensureWorkbookSelection(n.getUnitId()).selectionMoving$:O.of())).pipe(O.takeUntil(this.dispose$)),this.selectionMoveEnd$=t.pipe(O.switchMap(n=>n?this._ensureWorkbookSelection(n.getUnitId()).selectionMoveEnd$:O.of([]))).pipe(O.takeUntil(this.dispose$)),this.selectionSet$=t.pipe(O.switchMap(n=>n?this._ensureWorkbookSelection(n.getUnitId()).selectionSet$:O.of([]))).pipe(O.takeUntil(this.dispose$)),this.selectionChanged$=t.pipe(O.switchMap(n=>n?this._ensureWorkbookSelection(n.getUnitId()).selectionChanged$:O.of([]))).pipe(O.distinctUntilChanged((n,o)=>n.length!==o.length?!1:n.length===0&&o.length===0?!0:n.every((r,a)=>JSON.stringify(r)===JSON.stringify(o[a]))),O.skip(1)).pipe(O.takeUntil(this.dispose$)),this.disposeWithMe(this._instanceSrv.getTypeOfUnitDisposed$(i.UniverInstanceType.UNIVER_SHEET).pipe(O.takeUntil(this.dispose$)).subscribe(n=>{this._removeWorkbookSelection(n.getUnitId())})),this.disposeWithMe(this.selectionChanged$.pipe(O.takeUntil(this.dispose$)).subscribe(()=>{this._cellStylesCache.clear()}))}dispose(){super.dispose(),this._cellStylesCache.clear(),this._workbookSelections.forEach(t=>t.dispose()),this._workbookSelections.clear(),this.selectionMoveStart$=O.of(null),this.selectionMoving$=O.of(null),this.selectionMoveEnd$=O.of([]),this.selectionSet$=O.of(null),this.selectionChanged$=O.of(null)}clear(){this._workbookSelections.forEach(t=>t.clear())}getCurrentSelections(){return this._getCurrentSelections()}getCurrentLastSelection(){const t=this._getCurrentSelections();return t==null?void 0:t[t.length-1]}addSelections(t,n,o){if(typeof t=="string"){this._ensureWorkbookSelection(t).addSelections(n,o);return}const r=this._currentSelectionPos;if(!r)throw new Error("[SheetsSelectionsService]: cannot find current selection position!");const{unitId:a,sheetId:l}=r;this._ensureWorkbookSelection(a).addSelections(l,t)}setSelections(t,n,o,r){if(typeof t=="string"&&typeof n=="string"){const d=t;this._ensureWorkbookSelection(d).setSelections(n,o||[],r!=null?r:te.ONLY_SET);return}const a=this._currentSelectionPos;if(!a)throw new Error("[SheetsSelectionsService]: cannot find current selection position!");const{unitId:l,sheetId:u}=a;if(typeof t=="object"){const d=t!=null?t:o,c=n!=null?n:te.ONLY_SET;this._ensureWorkbookSelection(l).setSelections(u,d,c)}}clearCurrentSelections(){this._getCurrentSelections().splice(0)}isOverlapping(){const t=this.getCurrentSelections();return t==null?!1:t.some(({range:n},o)=>t.some(({range:r},a)=>o===a?!1:n.startRow<=r.endRow&&n.endRow>=r.startRow&&n.startColumn<=r.endColumn&&n.endColumn>=r.startColumn))}_getCurrentSelections(){const t=this._currentSelectionPos;if(!t)return[];const{unitId:n,sheetId:o}=t;return this._ensureWorkbookSelection(n).getSelectionsOfWorksheet(o)}getWorkbookSelections(t){return this._ensureWorkbookSelection(t)}_ensureWorkbookSelection(t){let n=this._workbookSelections.get(t);if(!n){const o=this._instanceSrv.getUnit(t);if(!o)throw new Error(`[SheetsSelectionsService]: cannot resolve unit with id "${t}"!`);n=new Do(o),this._workbookSelections.set(t,n)}return n}_removeWorkbookSelection(t){this._workbookSelections.delete(t)}getCellStylesProperty(t){var a;const n=(a=this._instanceSrv.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET))==null?void 0:a.getActiveSheet(),o=this.getCurrentSelections();if(!n||o.length===0)return{isAllValuesSame:!1,value:null};let r=null;for(let l=0;l<o.length;l++){const u=o[l],{startRow:d,endRow:c,startColumn:m,endColumn:h}=u.range;for(let R=d;R<=c;R++)for(let C=m;C<=h;C++){const S=`${R}_${C}`;let I;this._cellStylesCache.has(S)?I=this._cellStylesCache.get(S):(I=n.getComposedCellStyle(R,C),this._cellStylesCache.set(S,I));const v=I[t];if(r!=null&&!i.Tools.diffValue(r,v))return{isAllValuesSame:!1,value:null};r=v}}return{isAllValuesSame:!0,value:r}}},g.SheetsSelectionsService=tl([nl(0,i.IUniverInstanceService)],g.SheetsSelectionsService);const sl="DISABLE_NORMAL_SELECTIONS",ol="SELECTIONS_ENABLED",Ao="REF_SELECTIONS_ENABLED",sn={id:"sheet.command.clear-selection-all",type:i.CommandType.COMMAND,handler:(s,e)=>{var p;const t=s.get(i.IUniverInstanceService),n=s.get(i.ICommandService),o=s.get(g.SheetsSelectionsService),r=s.get(i.IUndoRedoService),a=s.get(g.SheetInterceptorService),l=t.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET);if(!l)return!1;const u=(e==null?void 0:e.unitId)||l.getUnitId(),d=l.getActiveSheet();if(!d)return!1;const c=(e==null?void 0:e.subUnitId)||d.getSheetId(),m=(e==null?void 0:e.ranges)||((p=o.getCurrentSelections())==null?void 0:p.map(w=>w.range));if(!(m!=null&&m.length))return!1;const h=Dt(m,s,u,c),R=[],C=[],S={subUnitId:c,unitId:u,cellValue:qn(h)},I=ce(s,S);R.push({id:F.id,params:S}),C.push({id:F.id,params:I});const v=a.onCommandExecute({id:sn.id});return R.push(...v.redos),C.unshift(...v.undos),i.sequenceExecute(R,n)?(r.pushUndoRedo({unitID:u,undoMutations:C,redoMutations:R}),!0):!1}},on={id:"sheet.command.clear-selection-format",type:i.CommandType.COMMAND,handler:(s,e)=>{var p;const t=s.get(i.IUniverInstanceService),n=s.get(i.ICommandService),o=s.get(g.SheetsSelectionsService),r=s.get(i.IUndoRedoService),a=s.get(g.SheetInterceptorService),l=t.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET);if(!l)return!1;const u=(e==null?void 0:e.unitId)||l.getUnitId(),d=l.getActiveSheet();if(!d)return!1;const c=(e==null?void 0:e.subUnitId)||d.getSheetId(),m=(e==null?void 0:e.ranges)||((p=o.getCurrentSelections())==null?void 0:p.map(w=>w.range));if(!(m!=null&&m.length))return!1;const h=Dt(m,s,u,c),R=[],C=[],S={subUnitId:c,unitId:u,cellValue:Xa(h)},I=ce(s,S);R.push({id:F.id,params:S}),C.push({id:F.id,params:I});const v=a.onCommandExecute({id:on.id});return R.push(...v.redos),C.unshift(...v.undos),i.sequenceExecute(R,n)?(r.pushUndoRedo({unitID:u,undoMutations:C,redoMutations:R}),!0):!1}};function At(s,e,t=!0){const n=e.getMatrixWithMergedCells(...i.selectionToArray(s)),o=[];if(n.forValue((a,l,u)=>{if(u.colSpan!==void 0&&u.rowSpan!==void 0){const d={startRow:a,startColumn:l,endRow:a+u.rowSpan-1,endColumn:l+u.colSpan-1};i.Rectangle.contains(s,d)||o.push(d)}}),o.length===0)return s;const r=i.Rectangle.union(s,...o);return t?At(r,e,t):r}function rl(s,e,t){let n=null;return t.getMatrixWithMergedCells(s,e,s,e).forValue((r,a,l)=>(n={actualRow:r,actualColumn:a,startRow:r,startColumn:a,isMerged:l.rowSpan!==void 0||l.colSpan!==void 0,isMergedMainCell:l.rowSpan!==void 0&&l.colSpan!==void 0,endRow:r+(l.rowSpan!==void 0?l.rowSpan-1:0),endColumn:a+(l.colSpan!==void 0?l.colSpan-1:0),rangeType:i.RANGE_TYPE.NORMAL},!1)),n||{actualColumn:e,actualRow:s,startRow:s,startColumn:e,endRow:s,endColumn:e,isMerged:!1,isMergedMainCell:!1,rangeType:i.RANGE_TYPE.NORMAL}}function il(s,e,t){const{startRow:n,startColumn:o,endRow:r,endColumn:a}=s;return Number.isNaN(n)&&(s.startRow=0),Number.isNaN(r)&&(s.endRow=e-1),Number.isNaN(o)&&(s.startColumn=0),Number.isNaN(a)&&(s.endColumn=t-1),s}function se(s,e){const t=Number.isNaN(s.startRow)?0:s.startRow,n=Number.isNaN(s.startColumn)?0:s.startColumn,o=e.getMergedCell(t,n);return o?{...o,actualRow:t,actualColumn:n,rangeType:i.RANGE_TYPE.NORMAL,isMerged:!0,isMergedMainCell:!0}:{startRow:t,startColumn:n,endRow:s.startRow,endColumn:s.startColumn,actualRow:t,actualColumn:n,rangeType:i.RANGE_TYPE.NORMAL,isMerged:!1,isMergedMainCell:!1}}const Ue=(s,e,t)=>({id:q.id,params:{unitId:e.getUnitId(),subUnitId:t.getSheetId(),reveal:!0,selections:[{range:s,primary:se(s,t)}]}});function al(s){if(!s)return!1;const{range:e,primary:t}=s;return i.Rectangle.equals(e,t)}function ll(s){function e(t,n){function o(r){for(let a=r.startRow;a<=r.endRow;a++)if(!s.getRowFiltered(a))for(let l=r.startColumn;l<=r.endColumn;l++)n(a,l,r)}o(t)}return{forOperableEach:e}}const Wo=s=>s.id!==no;function $e(s,e,t,n,o,r,a){const l={};for(let u=e;u<=t;u++)for(let d=n;d<=o;d++){const c=r?s.getCellWithFilteredInterceptors(a,d,so,Wo):s.getCellWithFilteredInterceptors(u,a,so,Wo);!c||!c.s||(l[u]||(l[u]={}),l[u][d]={s:c.s})}for(const u in l){for(const d in l[u]){const c=l[u][d];c.s&&typeof c.s=="object"&&i.Tools.isEmptyObject(c.s)&&delete c.s,i.Tools.isEmptyObject(c)&&delete l[u][d]}i.Tools.isEmptyObject(l[u])&&delete l[u]}return l}var ul=Object.getOwnPropertyDescriptor,dl=(s,e,t,n)=>{for(var o=n>1?void 0:n?ul(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},cl=(s,e)=>(t,n)=>e(t,n,s);const Vo=i.createIdentifier("sheets-formula.ref-selections.service");g.RefSelectionsService=class extends g.SheetsSelectionsService{constructor(e){super(e)}_init(){const e=this._getAliveWorkbooks$().pipe(O.takeUntil(this.dispose$));this.selectionMoveStart$=e.pipe(O.switchMap(t=>O.merge(...t.map(n=>n.selectionMoveStart$)))),this.selectionMoving$=e.pipe(O.switchMap(t=>O.merge(...t.map(n=>n.selectionMoving$)))),this.selectionMoveEnd$=e.pipe(O.switchMap(t=>O.merge(...t.map(n=>n.selectionMoveEnd$)))),this.selectionSet$=e.pipe(O.switchMap(t=>O.merge(...t.map(n=>n.selectionSet$))))}dispose(){super.dispose(),this.selectionMoveStart$=O.of(null),this.selectionMoving$=O.of(null),this.selectionMoveEnd$=O.of(null),this.selectionSet$=O.of(null),delete this._instanceSrv,this._workbookSelections.clear()}_getAliveWorkbooks$(){const e=this._instanceSrv.getAllUnitsForType(i.UniverInstanceType.UNIVER_SHEET);e.forEach(n=>this._ensureWorkbookSelection(n.getUnitId()));const t=new O.BehaviorSubject(e);return this.disposeWithMe(this._instanceSrv.getTypeOfUnitAdded$(i.UniverInstanceType.UNIVER_SHEET).subscribe(n=>{this._ensureWorkbookSelection(n.getUnitId()),t.next([...t.getValue(),n])})),this.disposeWithMe(this._instanceSrv.getTypeOfUnitDisposed$(i.UniverInstanceType.UNIVER_SHEET).subscribe(n=>{this._removeWorkbookSelection(n.getUnitId()),t.next(t.getValue().filter(o=>o!==n))})),t.pipe(O.map(n=>n.map(o=>this._ensureWorkbookSelection(o.getUnitId()))))}},g.RefSelectionsService=dl([cl(0,i.IUniverInstanceService)],g.RefSelectionsService);function $o(s,e){const n=s.get(i.IContextService).getContextValue(Ao);return s.get(n&&!e?Vo:g.SheetsSelectionsService)}const q={id:"sheet.operation.set-selections",type:i.CommandType.OPERATION,handler:(s,e)=>{if(!e)return!1;const{selections:t,type:n,unitId:o,subUnitId:r}=e;return $o(s).setSelections(o,r,[...t],n),!0}},Lo={id:"sheet.command.select-range",type:i.CommandType.COMMAND,handler:(s,e)=>{if(!e)return!1;const{unitId:t,subUnit:n,range:o}=e,r=s.get(i.ICommandService),a=P(s.get(i.IUniverInstanceService),e);if(!a)return!1;const l=[{range:o,primary:se(o,a.worksheet),style:null}];return r.syncExecuteCommand(q.id,{unitId:t,subUnitId:n,selections:l})}},Bo="sheet.command.move-range",Je={type:i.CommandType.COMMAND,id:Bo,handler:async(s,e)=>{var M,p;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=s.get(i.ErrorService),a=s.get(i.LocaleService),l=s.get(g.SheetInterceptorService),u=P(o);if(!u||!await l.beforeCommandExecute({id:Je.id,params:e}))return!1;const{worksheet:c,subUnitId:m,unitId:h}=u,R=rn(s,{unitId:h,subUnitId:m,range:e.fromRange},{subUnitId:m,range:e.toRange});if(R===null)return r.emit(a.t("sheets.info.acrossMergedCell")),!1;const C=l.onCommandExecute({id:Je.id,params:e}),S=[...(M=C.preRedos)!=null?M:[],...R.redos,...C.redos,{id:q.id,params:{unitId:h,subUnitId:m,selections:[{range:e.toRange,primary:ml(e.fromRange,e.toRange,c)}],type:te.MOVE_END}}],I=[...(p=C.preUndos)!=null?p:[],...R.undos,...C.undos,{id:q.id,params:{unitId:h,subUnitId:m,selections:[{range:e.fromRange,primary:se(e.fromRange,c)}],type:te.MOVE_END}}];if(i.sequenceExecute(S,t).result){const{undos:w,redos:y}=l.generateMutationsOfAutoHeight({unitId:h,subUnitId:m,ranges:[e.fromRange,e.toRange]}),b=l.afterCommandExecute({id:Je.id,params:e});return i.sequenceExecute([...b.redos,...y],t),n.pushUndoRedo({unitID:h,undoMutations:[...I,...b.undos,...w],redoMutations:[...S,...b.redos,...y]}),!0}return!1}};function rn(s,e,t,n=!1){const o=[],r=[],{range:a,subUnitId:l,unitId:u}=e,{range:d,subUnitId:c}=t,h=s.get(i.IUniverInstanceService).getUniverSheetInstance(u),R=h==null?void 0:h.getSheetBySheetId(c),C=h==null?void 0:h.getSheetBySheetId(l),S=R==null?void 0:R.getCellMatrix(),I=C==null?void 0:C.getCellMatrix();if(R&&C&&S&&I){const v=At(d,R,!1);if(!i.Rectangle.equals(d,v)&&!n)return null;const M=new i.ObjectMatrix,p=new i.ObjectMatrix,w=new i.ObjectMatrix;i.Range.foreach(a,(k,E)=>{const N=I.getValue(k,E);if(M.setValue(k,E,i.Tools.deepClone(N)),N){const W=h==null?void 0:h.getStyles().get(N.s);w.setValue(k,E,i.Tools.deepClone(W))}p.setValue(k,E,null)});const y=new i.ObjectMatrix,b=new i.ObjectMatrix;i.Range.foreach(d,(k,E)=>{y.setValue(k,E,i.Tools.deepClone(S.getValue(k,E)))}),i.Range.foreach(a,(k,E)=>{const N=i.cellToRange(k,E),W=i.Rectangle.getRelativeRange(N,a),V=i.Rectangle.getPositionRange(W,d),$=i.Tools.deepClone(w.getValue(k,E)),L=i.Tools.deepClone(M.getValue(k,E));L&&$&&(L.s=$),b.setValue(V.startRow,V.startColumn,L)});const T={fromRange:e.range,toRange:t.range,from:{value:p.getMatrix(),subUnitId:l},to:{value:b.getMatrix(),subUnitId:c},unitId:u},U={fromRange:t.range,toRange:e.range,from:{value:M.getMatrix(),subUnitId:l},to:{value:y.getMatrix(),subUnitId:c},unitId:u};o.push({id:Le.id,params:T}),r.push({id:Le.id,params:U})}return{redos:o,undos:r}}function ml(s,e,t){const n=s.startRow,o=s.startColumn,r=t.getMergedCell(n,o),a=se(e,t);if(r){const l=r.endRow-r.startRow+1,u=r.endColumn-r.startColumn+1;a.endRow=a.startRow+l-1,a.endColumn=a.startColumn+u-1,a.actualRow=a.startRow,a.actualColumn=a.startColumn,a.isMerged=!1,a.isMergedMainCell=!0}return a}var an=(s=>(s[s.UNIVER_UNKNOWN=0]="UNIVER_UNKNOWN",s[s.UNIVER_DOC=1]="UNIVER_DOC",s[s.UNIVER_SHEET=2]="UNIVER_SHEET",s[s.UNIVER_SLIDE=3]="UNIVER_SLIDE",s[s.UNIVER_PROJECT=4]="UNIVER_PROJECT",s[s.UNRECOGNIZED=-1]="UNRECOGNIZED",s))(an||{}),_=(s=>(s[s.View=0]="View",s[s.Edit=1]="Edit",s[s.ManageCollaborator=2]="ManageCollaborator",s[s.Print=3]="Print",s[s.Duplicate=4]="Duplicate",s[s.Comment=5]="Comment",s[s.Copy=6]="Copy",s[s.Share=7]="Share",s[s.Export=8]="Export",s[s.MoveWorksheet=9]="MoveWorksheet",s[s.DeleteWorksheet=10]="DeleteWorksheet",s[s.HideWorksheet=11]="HideWorksheet",s[s.RenameWorksheet=12]="RenameWorksheet",s[s.CreateWorksheet=13]="CreateWorksheet",s[s.SetWorksheetStyle=14]="SetWorksheetStyle",s[s.EditWorksheetCell=15]="EditWorksheetCell",s[s.InsertHyperlink=16]="InsertHyperlink",s[s.Sort=17]="Sort",s[s.Filter=18]="Filter",s[s.PivotTable=19]="PivotTable",s[s.FloatImg=20]="FloatImg",s[s.History=21]="History",s[s.RwHgtClWdt=22]="RwHgtClWdt",s[s.ViemRwHgtClWdt=23]="ViemRwHgtClWdt",s[s.ViewFilter=24]="ViewFilter",s[s.MoveSheet=25]="MoveSheet",s[s.DeleteSheet=26]="DeleteSheet",s[s.HideSheet=27]="HideSheet",s[s.CopySheet=28]="CopySheet",s[s.RenameSheet=29]="RenameSheet",s[s.CreateSheet=30]="CreateSheet",s[s.SelectProtectedCells=31]="SelectProtectedCells",s[s.SelectUnProtectedCells=32]="SelectUnProtectedCells",s[s.SetCellStyle=33]="SetCellStyle",s[s.SetCellValue=34]="SetCellValue",s[s.SetRowStyle=35]="SetRowStyle",s[s.SetColumnStyle=36]="SetColumnStyle",s[s.InsertRow=37]="InsertRow",s[s.InsertColumn=38]="InsertColumn",s[s.DeleteRow=39]="DeleteRow",s[s.DeleteColumn=40]="DeleteColumn",s[s.EditExtraObject=41]="EditExtraObject",s[s.Delete=42]="Delete",s[s.RecoverHistory=43]="RecoverHistory",s[s.ViewHistory=44]="ViewHistory",s[s.CreatePermissionObject=45]="CreatePermissionObject",s[s.UNRECOGNIZED=-1]="UNRECOGNIZED",s))(_||{}),D=(s=>(s[s.Unkonwn=0]="Unkonwn",s[s.Workbook=1]="Workbook",s[s.Worksheet=2]="Worksheet",s[s.SelectRange=3]="SelectRange",s[s.Document=4]="Document",s[s.Slide=5]="Slide",s[s.UNRECOGNIZED=-1]="UNRECOGNIZED",s))(D||{});class Se{constructor(e,t,n){f(this,"type",D.SelectRange);f(this,"subType",_.Edit);f(this,"status",i.PermissionStatus.INIT);f(this,"value",!0);f(this,"id");f(this,"unitId");f(this,"subUnitId");f(this,"permissionId");this.unitId=e,this.subUnitId=t,this.permissionId=n,this.id=`${D.SelectRange}.${_.Edit}.${n}`}}class ln{constructor(e,t,n){f(this,"type",D.SelectRange);f(this,"subType",_.View);f(this,"status",i.PermissionStatus.INIT);f(this,"value",!1);f(this,"id");f(this,"unitId");f(this,"subUnitId");f(this,"permissionId");this.unitId=e,this.subUnitId=t,this.permissionId=n,this.id=`${D.SelectRange}.${_.View}.${n}`}}class Yn{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.Comment);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.Comment}_${e}`}}class Kn{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.Copy);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.Copy}_${e}`}}class Ho{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"subType",_.CopySheet);f(this,"status",i.PermissionStatus.INIT);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.CopySheet}_${e}`}}class Jn{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.CreatePermissionObject);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.CreatePermissionObject}_${e}`}}class xn{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.CreateSheet);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.CreateSheet}_${e}`}}class Fo{constructor(e){f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.DeleteColumn);this.unitId=e,this.id=`${this.type}.${_.DeleteColumn}_${e}`}}class jo{constructor(e){f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.DeleteRow);this.unitId=e,this.id=`${this.type}.${_.DeleteRow}_${e}`}}class Xn{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.DeleteSheet);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.DeleteSheet}_${e}`}}class Zn{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.Duplicate);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.Duplicate}_${e}`}}class me{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.Edit);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.Edit}_${e}`}}class Qn{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.Export);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.Export}_${e}`}}class un{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.HideSheet);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.HideSheet}_${e}`}}class Go{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.History);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.History}_${e}`}}class zo{constructor(e){f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.InsertColumn);this.unitId=e,this.id=`${this.type}.${_.InsertColumn}_${e}`}}class qo{constructor(e){f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.InsertRow);this.unitId=e,this.id=`${this.type}.${_.InsertRow}_${e}`}}class dn{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.ManageCollaborator);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.ManageCollaborator}_${e}`}}class cn{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.MoveSheet);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.MoveSheet}_${e}`}}class es{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.Print);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.Print}_${e}`}}class ts{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.RecoverHistory);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.RecoverHistory}_${e}`}}class mn{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.RenameSheet);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.RenameSheet}_${e}`}}class ns{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.Share);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.Share}_${e}`}}class ss{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.View);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.View}_${e}`}}class os{constructor(e){f(this,"id");f(this,"value",!0);f(this,"type",D.Workbook);f(this,"status",i.PermissionStatus.INIT);f(this,"subType",_.ViewHistory);this.unitId=e,this.unitId=e,this.id=`${this.type}.${_.ViewHistory}_${e}`}}class rs{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.Copy);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.Copy}_${e}_${t}`}}class is{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.DeleteColumn);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.DeleteColumn}_${e}_${t}`}}class as{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.Delete);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.Delete}_${e}_${t}`}}class ls{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.DeleteRow);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.DeleteRow}_${e}_${t}`}}class fe{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.Edit);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.Edit}_${e}_${t}`}}class us{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.EditExtraObject);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.EditExtraObject}_${e}_${t}`}}class ds{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.Filter);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.Filter}_${e}_${t}`}}class cs{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.InsertColumn);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.InsertColumn}_${e}_${t}`}}class ms{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.InsertHyperlink);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.InsertHyperlink}_${e}_${t}`}}class hs{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.InsertRow);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.InsertRow}_${e}_${t}`}}class gs{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.ManageCollaborator);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.ManageCollaborator}_${e}_${t}`}}class Rs{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.PivotTable);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.PivotTable}_${e}_${t}`}}class hl{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.SelectProtectedCells);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.SelectProtectedCells}_${e}_${t}`}}class gl{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.SelectUnProtectedCells);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.SelectUnProtectedCells}_${e}_${t}`}}class Cs{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.SetCellStyle);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.SetCellStyle}_${e}_${t}`}}class Wt{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.SetCellValue);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.SetCellValue}_${e}_${t}`}}class St{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.SetColumnStyle);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.SetColumnStyle}_${e}_${t}`}}class ft{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.SetRowStyle);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.SetRowStyle}_${e}_${t}`}}class Ss{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.Sort);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.Sort}_${e}_${t}`}}class Vt{constructor(e,t){f(this,"value",!0);f(this,"type",D.Worksheet);f(this,"status",i.PermissionStatus.INIT);f(this,"id");f(this,"subType",_.View);this.unitId=e,this.subUnitId=t,this.id=`${this.type}.${_.View}_${e}_${t}`}}const It={id:"sheet.command.set-range-values",type:i.CommandType.COMMAND,handler:(s,e)=>{var W;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=s.get(g.SheetsSelectionsService),a=s.get(g.SheetInterceptorService),l=s.get(i.IPermissionService),u=P(o,e);if(!u)return!1;const{subUnitId:d,unitId:c,workbook:m,worksheet:h}=u,{value:R,range:C,redoUndoId:S}=e,I=C?[C]:(W=r.getCurrentSelections())==null?void 0:W.map(V=>V.range);if(!I||!I.length||!l.getPermissionPoint(new fe(c,d).id))return!1;const v=new i.ObjectMatrix;let M;if(i.Tools.isArray(R))for(let V=0;V<I.length;V++){const{startRow:$,startColumn:L,endRow:Y,endColumn:z}=I[V];for(let K=0;K<=Y-$;K++)for(let oe=0;oe<=z-L;oe++)v.setValue(K+$,oe+L,R[K][oe])}else if(i.isICellData(R))for(let V=0;V<I.length;V++){const{startRow:$,startColumn:L,endRow:Y,endColumn:z}=I[V];for(let K=$;K<=Y;K++)for(let oe=L;oe<=z;oe++)v.setValue(K,oe,R)}else M=R;const p={subUnitId:d,unitId:c,cellValue:M!=null?M:v.getMatrix()},w=ce(s,p),y=i.mapObjectMatrix(p.cellValue,(V,$)=>h.getCellHeight(V,$)||void 0);if(!t.syncExecuteCommand(F.id,p))return!1;const{undos:T,redos:U}=a.onCommandExecute({id:It.id,params:p}),{undos:k,redos:E}=a.generateMutationsOfAutoHeight({unitId:c,subUnitId:d,ranges:I,cellHeights:new i.ObjectMatrix(y)});if(i.sequenceExecute([...U,...E],t).result){const V=Ue(C!=null?C:v.getRange(),m,h);return n.pushUndoRedo({unitID:c,undoMutations:[{id:F.id,params:w},...T,...k,V],redoMutations:[{id:F.id,params:p},...U,...E,i.Tools.deepClone(V)],id:S}),!0}return!1}};function fs(s,e){const t=[],n=[],{unitId:o,subUnitId:r,range:a,shiftDimension:l,cellValue:u={}}=e,d=s.get(i.IUniverInstanceService),c=s.get(g.SheetInterceptorService),m=d.getUniverSheetInstance(o),h=m==null?void 0:m.getSheetBySheetId(r);if(h){const R=h.getCellMatrix(),C=R.getDataRange();if(a.startColumn<=C.endColumn||a.startRow<=C.endRow){let p,w;if(l===i.Dimension.COLUMNS){const b=Math.min(a.endRow,C.endRow);let T=0;for(let k=a.startRow;k<=b;k++){const E=R.getRow(k),N=E?i.getArrayLength(E)-1:0;T=Math.max(T,N)}p={startRow:a.startRow,startColumn:a.startColumn,endRow:b,endColumn:T};const U=a.endColumn-a.startColumn+1;w={startRow:a.startRow,startColumn:p.startColumn+U,endRow:b,endColumn:p.endColumn+U}}else{const b=Math.min(a.endColumn,C.endColumn),T=C.endRow;p={startRow:a.startRow,startColumn:a.startColumn,endRow:T,endColumn:b};const U=a.endRow-a.startRow+1;w={startRow:p.startRow+U,startColumn:a.startColumn,endRow:p.endRow+U,endColumn:b}}const y=rn(s,{unitId:o,subUnitId:r,range:p},{subUnitId:r,range:w},!0);y&&(t.push(...y.redos),n.push(...y.undos))}if(Object.entries(u).length===0)for(let p=a.startRow;p<=a.endRow;p++){u[p]||(u[p]={});for(let w=a.startColumn;w<=a.endColumn;w++)u[p][w]=null}const S={subUnitId:r,unitId:o,cellValue:u},I=ce(s,S),{undos:v,redos:M}=c.onCommandExecute({id:It.id,params:{...S,range:a}});t.push({id:F.id,params:S},...M),n.push({id:F.id,params:I},...v)}return{redo:t,undo:n}}function Is(s,e){const t=[],n=[],{unitId:o,subUnitId:r,range:a,shiftDimension:l}=e,u=s.get(i.IUniverInstanceService),d=s.get(g.SheetInterceptorService),c=u.getUniverSheetInstance(o),m=c==null?void 0:c.getSheetBySheetId(r);if(m){const h=m.getCellMatrix(),R=h.getDataRange(),C={subUnitId:r,unitId:o,cellValue:qn([a])},S=ce(s,C),I=d.onCommandExecute({id:It.id,params:C});if(t.push({id:F.id,params:C},...I.redos),n.push(...I.undos,{id:F.id,params:S}),a.startColumn<=R.endColumn||a.startRow<=R.endRow){let v=null,M=null;if(l===i.Dimension.COLUMNS&&a.endColumn<R.endColumn){const p=Math.min(a.endRow,R.endRow);let w=0;for(let b=a.startRow;b<=p;b++){const T=h.getRow(b),U=T?i.getArrayLength(T)-1:0;w=Math.max(w,U)}v={startRow:a.startRow,startColumn:a.endColumn+1,endRow:p,endColumn:w};const y=a.endColumn-a.startColumn+1;M={startRow:a.startRow,startColumn:v.startColumn-y,endRow:p,endColumn:v.endColumn-y}}if(l===i.Dimension.ROWS&&a.endRow<R.endRow){const p=Math.min(a.endColumn,R.endColumn),w=R.endRow;v={startRow:a.endRow+1,startColumn:a.startColumn,endRow:w,endColumn:p};const y=a.endRow-a.startRow+1;M={startRow:v.startRow-y,startColumn:a.startColumn,endRow:v.endRow-y,endColumn:p}}if(v&&M){const p=rn(s,{unitId:o,subUnitId:r,range:v},{subUnitId:r,range:M},!0);p&&(t.push(...p.redos),n.push(...p.undos))}}}return{redo:t,undo:n}}function Rl(s,e,t,n,o,r){const{startRow:a,endRow:l,startColumn:u,endColumn:d}=e;if(o===i.Dimension.ROWS){const c=l-a+1;for(let m=t;m>=a;m--)for(let h=u;h<=d;h++){const R=s.getValue(m,h);R==null?s.realDeleteValue(m+c,h):s.setValue(m+c,h,R)}for(let m=l;m>=a;m--)for(let h=u;h<=d;h++)r&&r[m]&&r[m][h]?s.setValue(m,h,r[m][h]):s.realDeleteValue(m,h)}else if(o===i.Dimension.COLUMNS){const c=d-u+1;for(let m=a;m<=l;m++)for(let h=n;h>=u;h--){const R=s.getValue(m,h);R==null?s.realDeleteValue(m,h+c):s.setValue(m,h+c,R)}for(let m=a;m<=l;m++)for(let h=d;h>=u;h--)r&&r[m]&&r[m][h]?s.setValue(m,h,r[m][h]):s.realDeleteValue(m,h)}}function Cl(s,e,t,n,o){const{startRow:r,endRow:a,startColumn:l,endColumn:u}=e,d=a-r+1,c=u-l+1;if(o===i.Dimension.ROWS)for(let m=r;m<=t;m++)for(let h=l;h<=u;h++){const R=s.getValue(m+d,h);R==null?s.realDeleteValue(m,h):s.setValue(m,h,R)}else if(o===i.Dimension.COLUMNS)for(let m=r;m<=a;m++)for(let h=l;h<=n;h++){const R=s.getValue(m,h+c);R==null?s.realDeleteValue(m,h):s.setValue(m,h,R)}}const Yo="sheet.command.delete-range-move-left",Be={type:i.CommandType.COMMAND,id:Yo,handler:async(s,e)=>{var w,y,b;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=s.get(g.SheetsSelectionsService),a=s.get(g.SheetInterceptorService),l=P(o);if(!l)return!1;const{worksheet:u,workbook:d,subUnitId:c,unitId:m}=l;let h=e==null?void 0:e.range;if(h||(h=(w=r.getCurrentLastSelection())==null?void 0:w.range),!h)return!1;const R={range:h,subUnitId:c,unitId:m,shiftDimension:i.Dimension.COLUMNS},C=a.onCommandExecute({id:Be.id,params:{range:h}}),{redo:S,undo:I}=Is(s,R),v=[...(y=C.preRedos)!=null?y:[],...S],M=[...C.undos,...I];if(v.push(...C.redos),v.push(Ue(h,d,u)),M.push(...(b=C.preUndos)!=null?b:[]),i.sequenceExecute(v,t).result){const T=a.afterCommandExecute({id:Be.id,params:{range:h}});return i.sequenceExecute(T.redos,t),M.push(...T.undos),v.push(...T.redos),n.pushUndoRedo({unitID:m,undoMutations:M.reverse(),redoMutations:v}),!0}return!1}},Ko="sheet.command.delete-range-move-up",He={type:i.CommandType.COMMAND,id:Ko,handler:async(s,e)=>{var w,y,b;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=s.get(g.SheetsSelectionsService),a=s.get(g.SheetInterceptorService),l=P(o);if(!l)return!1;const{unitId:u,subUnitId:d,workbook:c,worksheet:m}=l;let h=e==null?void 0:e.range;if(h||(h=(w=r.getCurrentLastSelection())==null?void 0:w.range),!h)return!1;const R={range:h,subUnitId:d,unitId:u,shiftDimension:i.Dimension.ROWS},C=a.onCommandExecute({id:He.id,params:{range:h}}),{redo:S,undo:I}=Is(s,R),v=[...(y=C.preRedos)!=null?y:[],...S],M=[...C.undos,...I];if(v.push(...C.redos),v.push(Ue(h,c,m)),M.push(...(b=C.preUndos)!=null?b:[]),i.sequenceExecute(v,t).result){const T=a.afterCommandExecute({id:He.id,params:{range:h}});return i.sequenceExecute(T.redos,t),M.push(...T.undos),v.push(...T.redos),n.pushUndoRedo({unitID:u,undoMutations:M.reverse(),redoMutations:v}),!0}return!1}},Sl="sheet.command.insert-range-move-down",xe={type:i.CommandType.COMMAND,id:"sheet.command.insert-range-move-down",handler:async(s,e)=>{var W,V,$;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=s.get(g.SheetsSelectionsService),a=s.get(g.SheetInterceptorService),l=s.get(i.ErrorService),u=s.get(i.LocaleService);if(r.isOverlapping())return l.emit(u.t("sheets.info.overlappingSelections")),!1;const d=P(o);if(!d)return!1;const{unitId:c,subUnitId:m,worksheet:h,workbook:R}=d;let C=e==null?void 0:e.range;if(C||(C=(W=r.getCurrentLastSelection())==null?void 0:W.range),!C)return!1;const S=[],I=[],v=h.getCellMatrix(),M=v.getDataRange(),w=v.getSlice(M.startRow,M.endRow,C.startColumn,C.endColumn).getDataRange().endRow,y=Math.max(w+(C.endRow-C.startRow+1)-M.endRow,0);if(y>0){const L=C.startRow-1,Y=h.getRowHeight(L),z={unitId:c,subUnitId:m,range:{startRow:M.endRow+1,endRow:M.endRow+y,startColumn:M.startColumn,endColumn:M.endColumn},rowInfo:new Array(y).fill(void 0).map(()=>({h:Y,hd:i.BooleanNumber.FALSE}))};S.push({id:re.id,params:z});const K=en(s,z);I.push({id:ae.id,params:K})}const b={};i.Range.foreach(C,(L,Y)=>{const z=h.getCell(L,Y);z&&(b[L]||(b[L]={}),b[L][Y]={s:z.s})});const T={range:C,subUnitId:m,unitId:c,shiftDimension:i.Dimension.ROWS,cellValue:b},{redo:U,undo:k}=fs(s,T);S.push(...U),I.push(...k);const E=a.onCommandExecute({id:xe.id,params:{range:C}});if(S.push(...E.redos),S.push(Ue(C,R,h)),I.push(...(V=E.preUndos)!=null?V:[]),S.unshift(...($=E.preRedos)!=null?$:[]),I.unshift(...E.undos),i.sequenceExecute(S,t)){const L=a.afterCommandExecute({id:xe.id,params:{range:C}});return i.sequenceExecute(L.redos,t),I.push(...L.undos),S.push(...L.redos),n.pushUndoRedo({unitID:c,undoMutations:I.reverse(),redoMutations:S}),!0}return!1}},vs="sheet.command.insert-range-move-right",vt={type:i.CommandType.COMMAND,id:vs,handler:async(s,e)=>{var W,V,$;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=s.get(g.SheetsSelectionsService),a=s.get(g.SheetInterceptorService),l=s.get(i.ErrorService),u=s.get(i.LocaleService);if(r.isOverlapping())return l.emit(u.t("sheets.info.overlappingSelections")),!1;const d=P(o);if(!d)return!1;const{workbook:c,worksheet:m,unitId:h,subUnitId:R}=d;let C=e==null?void 0:e.range;if(C||(C=(W=r.getCurrentLastSelection())==null?void 0:W.range),!C)return!1;const S=[],I=[],v=m.getCellMatrix(),M=v.getDataRange(),w=v.getSlice(C.startRow,C.endRow,M.startColumn,M.endColumn).getDataRange().endColumn,y=Math.max(w+(C.endColumn-C.startColumn+1)-M.endColumn,0);if(y>0){const L=C.startColumn-1,Y=m.getColumnWidth(L),z={unitId:h,subUnitId:R,range:{startRow:M.startRow+1,endRow:M.endRow,startColumn:M.endColumn+1,endColumn:M.endColumn+y},colInfo:new Array(y).fill(void 0).map(()=>({w:Y,hd:i.BooleanNumber.FALSE}))};S.push({id:ie.id,params:z});const K=Nt(s,z);I.push({id:ne.id,params:K})}const b={};i.Range.foreach(C,(L,Y)=>{const z=m.getCell(L,Y);!z||!z.s||(b[L]||(b[L]={}),b[L][Y]={s:z.s})});const T={range:C,subUnitId:R,unitId:h,shiftDimension:i.Dimension.COLUMNS,cellValue:b},{redo:U,undo:k}=fs(s,T);S.push(...U),I.push(...k);const E=a.onCommandExecute({id:vt.id,params:{range:C}});if(S.push(...E.redos),S.push(Ue(C,c,m)),I.push(...(V=E.preUndos)!=null?V:[]),S.unshift(...($=E.preRedos)!=null?$:[]),I.unshift(...E.undos),i.sequenceExecute(S,t).result){const L=a.afterCommandExecute({id:vt.id,params:{range:C}});return i.sequenceExecute(L.redos,t),I.push(...L.undos),S.push(...L.redos),n.pushUndoRedo({unitID:h,undoMutations:I.reverse(),redoMutations:S}),!0}return!1}},Jo="sheet.command.insert-row",Me={type:i.CommandType.COMMAND,id:Jo,handler:async(s,e)=>{const t=s.get(i.ICommandService),n=s.get(g.SheetInterceptorService),{range:o,direction:r,unitId:a,subUnitId:l,cellValue:u}=e;return await n.beforeCommandExecute({id:Me.id,params:e})?t.syncExecuteCommand(ps.id,{range:o,direction:r,unitId:a,subUnitId:l,cellValue:u}):!1}},ps={type:i.CommandType.COMMAND,id:"sheet.command.insert-row-by-range",handler:(s,e)=>{var U,k,E,N;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=s.get(g.SheetInterceptorService),a=P(o,e);if(!a)return!1;const{workbook:l,worksheet:u}=a,{range:d,direction:c,unitId:m,subUnitId:h,cellValue:R}=e,{startRow:C,endRow:S}=d;d.rangeType=i.RANGE_TYPE.ROW;const I=c===i.Direction.UP?C:C-1,v=u.getRowHeight(I),M={unitId:m,subUnitId:h,range:d,rowInfo:new Array(S-C+1).fill(void 0).map(()=>({h:v,hd:i.BooleanNumber.FALSE}))},p=en(s,M),w=[{id:re.id,params:M}],y=[{id:ae.id,params:p}];R&&Object.keys(R).length>0&&w.push({id:F.id,params:{unitId:m,subUnitId:h,cellValue:R}});const b=r.onCommandExecute({id:Me.id,params:e});if(w.unshift(...(U=b.preRedos)!=null?U:[]),w.push(...(k=b.redos)!=null?k:[]),w.push(Ue(d,l,u)),y.unshift(...(E=b.preUndos)!=null?E:[]),y.push(...(N=b.undos)!=null?N:[]),i.sequenceExecute(w,t).result){const W=r.afterCommandExecute({id:Me.id,params:e});return i.sequenceExecute(W.redos,t),w.push(...W.redos),y.push(...W.undos),n.pushUndoRedo({unitID:e.unitId,undoMutations:y,redoMutations:w}),!0}return!1}},xo={type:i.CommandType.COMMAND,id:"sheet.command.insert-row-before",handler:async(s,e)=>{var I;const n=(I=s.get(g.SheetsSelectionsService).getCurrentSelections())==null?void 0:I.map(v=>v.range);let o;if((n==null?void 0:n.length)===1)o=n[0];else return!1;const r=s.get(i.IUniverInstanceService),a=P(r);if(!a)return!1;const{worksheet:l,subUnitId:u,unitId:d}=a,c=e.value||0,m=o.startRow,h=o.startRow+c-1,R=0,C=l.getColumnCount()-1,S={unitId:d,subUnitId:u,direction:i.Direction.UP,range:{startRow:m,endRow:h,startColumn:R,endColumn:C},cellValue:$e(l,m,h,R,C,!0,m-1)};return s.get(i.ICommandService).executeCommand(Me.id,S)}},Xo={type:i.CommandType.COMMAND,id:"sheet.command.insert-row-after",handler:async s=>{var S;const t=(S=s.get(g.SheetsSelectionsService).getCurrentSelections())==null?void 0:S.map(I=>I.range);let n;if((t==null?void 0:t.length)===1)n=t[0];else return!1;const o=s.get(i.IUniverInstanceService),r=P(o);if(!r)return!1;const{worksheet:a,unitId:l,subUnitId:u}=r,d=n.endRow-n.startRow+1,c=n.endRow+1,m=n.endRow+d,h=0,R=a.getColumnCount()-1,C={unitId:l,subUnitId:u,direction:i.Direction.DOWN,range:{startRow:c,endRow:m,startColumn:h,endColumn:R,rangeType:i.RANGE_TYPE.ROW},cellValue:$e(a,c,m,h,R,!0,n.endRow)};return s.get(i.ICommandService).executeCommand(Me.id,C)}},Zo={type:i.CommandType.COMMAND,id:"sheet.command.insert-multi-rows-above",handler:async(s,e)=>{var v;const n=(v=s.get(g.SheetsSelectionsService).getCurrentSelections())==null?void 0:v.map(M=>M.range);let o;if((n==null?void 0:n.length)===1)o=n[0];else return!1;const r=s.get(i.IUniverInstanceService),a=P(r);if(!a)return!1;const{worksheet:l,unitId:u,subUnitId:d}=a,c=e.value||0,m=o.startRow,h=o.startRow+c-1,R=0,C=l.getColumnCount()-1,S=$e(l,m,h,R,C,!0,m-1),I={unitId:u,subUnitId:d,direction:i.Direction.UP,range:{startRow:m,endRow:h,startColumn:R,endColumn:C,rangeType:i.RANGE_TYPE.ROW},cellValue:S};return s.get(i.ICommandService).executeCommand(Me.id,I)}},Qo={type:i.CommandType.COMMAND,id:"sheet.command.insert-multi-rows-after",handler:async(s,e)=>{var I;const n=(I=s.get(g.SheetsSelectionsService).getCurrentSelections())==null?void 0:I.map(v=>v.range);let o;if((n==null?void 0:n.length)===1)o=n[0];else return!1;const r=s.get(i.IUniverInstanceService),a=P(r);if(!a)return!1;const{worksheet:l,unitId:u,subUnitId:d}=a,c=e.value||0,m=o.endRow+1,h=o.endRow+c,R=0,C=l.getColumnCount()-1,S={unitId:u,subUnitId:d,direction:i.Direction.DOWN,range:{startRow:m,endRow:h,startColumn:R,endColumn:C,rangeType:i.RANGE_TYPE.ROW},cellValue:$e(l,m,h,R,C,!0,o.endRow)};return s.get(i.ICommandService).executeCommand(Me.id,S)}},er="sheet.command.insert-col",ye={type:i.CommandType.COMMAND,id:er,handler:async(s,e)=>{const t=s.get(i.ICommandService),n=s.get(g.SheetInterceptorService),{range:o,direction:r,subUnitId:a,unitId:l,cellValue:u}=e;return await n.beforeCommandExecute({id:ye.id,params:e})?t.syncExecuteCommand(ws.id,{range:o,direction:r,unitId:l,subUnitId:a,cellValue:u}):!1}},ws={type:i.CommandType.COMMAND,id:"sheet.command.insert-col-by-range",handler:(s,e)=>{var T,U,k,E;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=s.get(g.SheetInterceptorService),{range:a,direction:l,subUnitId:u,unitId:d,cellValue:c}=e,{startColumn:m,endColumn:h}=e.range;a.rangeType=i.RANGE_TYPE.COLUMN;const R=o.getUniverSheetInstance(e.unitId),C=R.getSheetBySheetId(e.subUnitId),S=l===i.Direction.LEFT?m:m-1,I=C.getColumnWidth(S),v={unitId:d,subUnitId:u,range:a,colInfo:new Array(h-m+1).fill(void 0).map(()=>({w:I,hd:i.BooleanNumber.FALSE}))},M=Nt(s,v),p=[{id:ie.id,params:v}],w=[{id:ne.id,params:M}];c&&p.push({id:F.id,params:{unitId:d,subUnitId:u,cellValue:c}});const y=r.onCommandExecute({id:ye.id,params:e});if(p.unshift(...(T=y.preRedos)!=null?T:[]),p.push(...(U=y.redos)!=null?U:[]),p.push(Ue(a,R,C)),w.unshift(...(k=y.preUndos)!=null?k:[]),w.push(...(E=y.undos)!=null?E:[]),i.sequenceExecute(p,t).result){const N=r.afterCommandExecute({id:ye.id,params:e});return i.sequenceExecute(N.redos,t),p.push(...N.redos),w.push(...N.undos),n.pushUndoRedo({unitID:e.unitId,undoMutations:w.filter(Boolean),redoMutations:p.filter(Boolean)}),!0}return!1}},tr={type:i.CommandType.COMMAND,id:"sheet.command.insert-col-before",handler:async(s,e)=>{const n=s.get(g.SheetsSelectionsService).getCurrentSelections();let o;if((n==null?void 0:n.length)===1)o=n[0].range;else return!1;const r=s.get(i.IUniverInstanceService),a=P(r);if(!a)return!1;const{worksheet:l,unitId:u,subUnitId:d}=a,c=e.value||0,m=o.startColumn,h=o.startColumn+c-1,R=0,C=l.getRowCount()-1,S={unitId:u,subUnitId:d,direction:i.Direction.LEFT,range:{startColumn:m,endColumn:h,startRow:R,endRow:C,rangeType:i.RANGE_TYPE.COLUMN},cellValue:$e(l,R,C,m,h,!1,m-1)};return s.get(i.ICommandService).executeCommand(ye.id,S)}},nr={type:i.CommandType.COMMAND,id:"sheet.command.insert-col-after",handler:async s=>{const t=s.get(g.SheetsSelectionsService).getCurrentSelections();let n;if((t==null?void 0:t.length)===1)n=t[0].range;else return!1;const o=s.get(i.IUniverInstanceService),r=P(o);if(!r)return!1;const{worksheet:a,unitId:l,subUnitId:u}=r,d=n.endColumn-n.startColumn+1,c=n.endColumn+1,m=n.endColumn+d,h=0,R=a.getRowCount()-1,C={unitId:l,subUnitId:u,direction:i.Direction.RIGHT,range:{startColumn:c,endColumn:m,startRow:h,endRow:R},cellValue:$e(a,h,R,c,m,!1,n.endColumn)};return s.get(i.ICommandService).executeCommand(ye.id,C)}},sr={type:i.CommandType.COMMAND,id:"sheet.command.insert-multi-cols-before",handler:async(s,e)=>{const n=s.get(g.SheetsSelectionsService).getCurrentSelections();let o;if((n==null?void 0:n.length)===1)o=n[0].range;else return!1;const r=s.get(i.IUniverInstanceService),a=P(r);if(!a)return!1;const{worksheet:l,unitId:u,subUnitId:d}=a,c=e.value||0,m=o.startColumn,h=o.startColumn+c-1,R=0,C=l.getRowCount()-1,S={unitId:u,subUnitId:d,direction:i.Direction.LEFT,range:{startColumn:m,endColumn:h,startRow:R,endRow:C,rangeType:i.RANGE_TYPE.COLUMN},cellValue:$e(l,R,C,m,h,!1,m-1)};return s.get(i.ICommandService).executeCommand(ye.id,S)}},or={type:i.CommandType.COMMAND,id:"sheet.command.insert-multi-cols-right",handler:async(s,e)=>{const n=s.get(g.SheetsSelectionsService).getCurrentSelections();let o;if((n==null?void 0:n.length)===1)o=n[0].range;else return!1;const r=s.get(i.IUniverInstanceService),a=P(r);if(!a)return!1;const{worksheet:l,unitId:u,subUnitId:d}=a,c=e.value||0,m=o.endColumn+1,h=o.endColumn+c,R=0,C=l.getRowCount()-1,S={unitId:u,subUnitId:d,direction:i.Direction.RIGHT,range:{startColumn:m,endColumn:h,startRow:R,endRow:C},cellValue:$e(l,R,C,m,h,!1,o.endColumn)};return s.get(i.ICommandService).executeCommand(ye.id,S)}},hn="sheet.command.remove-row",Ms={type:i.CommandType.COMMAND,id:"sheet.command.remove-row-by-range",handler:(s,e)=>{var I,v,M;if(!e)return!1;const t=s.get(i.IUniverInstanceService),n=P(t,e);if(!n)return!1;const{workbook:o,worksheet:r}=n,a=s.get(g.SheetInterceptorService),{range:l,unitId:u,subUnitId:d}=e,c=Dt([l],s,u,d).reverse(),m=[],h=[];c.forEach(p=>{const w=[],y=[],b={unitId:u,subUnitId:d,range:p},T=ua(b,r),U=r.getCellMatrix().getSlice(p.startRow,p.endRow,0,r.getColumnCount()-1),k={unitId:u,subUnitId:d,cellValue:U.getMatrix()};y.push({id:ae.id,params:b}),w.push({id:re.id,params:T}),w.push({id:F.id,params:k}),h.push(...y),m.unshift(...w)});const R=a.onCommandExecute({id:hn,params:{range:l}}),C=s.get(i.ICommandService);if(i.sequenceExecute([...(I=R.preRedos)!=null?I:[],...h,...R.redos,Ue(l,o,r)],C).result){const p=a.afterCommandExecute({id:hn,params:{range:l}});return i.sequenceExecute(p.redos,C),s.get(i.IUndoRedoService).pushUndoRedo({unitID:u,undoMutations:[...(v=R.preUndos)!=null?v:[],...m,...R.undos,...p.undos],redoMutations:[...(M=R.preRedos)!=null?M:[],...h,...R.redos,...p.redos]}),!0}return!1}},$t={type:i.CommandType.COMMAND,id:hn,handler:async(s,e)=>{var h;const t=s.get(g.SheetsSelectionsService),n=s.get(g.SheetInterceptorService),o=s.get(i.ICommandService);let r=e==null?void 0:e.range;if(r||(r=(h=t.getCurrentLastSelection())==null?void 0:h.range),!r)return!1;const a=s.get(i.IUniverInstanceService),l=P(a);if(!l)return!1;const{worksheet:u,subUnitId:d,unitId:c}=l;return r={...r,startColumn:0,endColumn:Math.max(u.getMaxColumns()-1,0)},await n.beforeCommandExecute({id:$t.id,params:{range:r}})?o.syncExecuteCommand(Ms.id,{range:r,unitId:c,subUnitId:d}):!1}},gn="sheet.command.remove-col",ys={type:i.CommandType.COMMAND,id:"sheet.command.remove-col-by-range",handler:(s,e)=>{var v,M,p;if(!e)return!1;const t=s.get(i.IUniverInstanceService),n=P(t,e);if(!n)return!1;const{workbook:o,worksheet:r}=n,a=s.get(g.SheetInterceptorService),{range:l,unitId:u,subUnitId:d}=e,c={unitId:u,subUnitId:d,range:l},m=da(s,c),h=r.getCellMatrix().getSlice(0,r.getRowCount()-1,l.startColumn,l.endColumn),R={unitId:u,subUnitId:d,cellValue:h.getMatrix()},C=a.onCommandExecute({id:gn,params:{range:l}}),S=s.get(i.ICommandService);if(i.sequenceExecute([...(v=C.preRedos)!=null?v:[],{id:ne.id,params:c},...C.redos,Ue(l,o,r)],S).result){const w=a.afterCommandExecute({id:gn,params:{range:l}});return i.sequenceExecute(w.redos,S),s.get(i.IUndoRedoService).pushUndoRedo({unitID:u,undoMutations:[...(M=C.preUndos)!=null?M:[],{id:ie.id,params:m},{id:F.id,params:R},...C.undos,...w.undos],redoMutations:[...(p=C.preRedos)!=null?p:[],{id:ne.id,params:c},...C.redos,...w.redos]}),!0}return!1}},Lt={type:i.CommandType.COMMAND,id:gn,handler:async(s,e)=>{var h;const t=s.get(g.SheetsSelectionsService),n=s.get(g.SheetInterceptorService),o=s.get(i.ICommandService);let r=e==null?void 0:e.range;if(r||(r=(h=t.getCurrentLastSelection())==null?void 0:h.range),!r)return!1;const a=s.get(i.IUniverInstanceService),l=P(a);if(!l)return!1;const{worksheet:u,subUnitId:d,unitId:c}=l;return r={...r,startRow:0,endRow:Math.max(u.getMaxRows()-1,0)},await n.beforeCommandExecute({id:Lt.id,params:{range:r}})?o.syncExecuteCommand(ys.id,{range:r,unitId:c,subUnitId:d}):!1}},rr=(s,e)=>{const t=s.get(i.IUniverInstanceService),{subUnitId:n,unitId:o}=e,r=ve(t,e);if(!r)throw new Error("[RemoveSheetUndoMutationFactory]: Worksheet is null error!");const{workbook:a,worksheet:l}=r,u=l.getConfig();return{index:a.getConfig().sheetOrder.findIndex(m=>m===n),sheet:u,unitId:o}},Xe={id:"sheet.mutation.remove-sheet",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=s.get(i.IUniverInstanceService),{subUnitId:n,unitId:o}=e,r=t.getUniverSheetInstance(o);return r?r.removeSheet(n):!1}};function fl(s,e){return e.getMergeData().some(t=>t.startRow<s&&s<=t.endRow)}function Il(s,e){return e.getMergeData().some(t=>t.startColumn<s&&s<=t.endColumn)}const ir="sheet.command.move-rows",pt={id:ir,type:i.CommandType.COMMAND,handler:(s,e)=>{var W,V;const t=s.get(g.SheetsSelectionsService),{fromRange:{startRow:n},toRange:{startRow:o},range:r}=e,a=r?[lr(r)]:t.getCurrentSelections(),l=a==null?void 0:a.filter($=>$.range.rangeType===i.RANGE_TYPE.ROW&&$.range.startRow<=n&&n<=$.range.endRow);if((l==null?void 0:l.length)!==1)return!1;const u=s.get(g.SheetInterceptorService),d=s.get(i.IUniverInstanceService),c=P(d,e);if(!c)return!1;const{workbook:m,worksheet:h}=c,R=m.getUnitId(),C=h.getSheetId(),S=s.get(i.ErrorService),I=s.get(i.LocaleService),v=l[0].range,M=l[0].primary,p=At(v,h,!1);if(!i.Rectangle.equals(v,p))return S.emit(I.t("sheets.info.partOfCell")),!1;if(fl(o,h))return S.emit(I.t("sheets.info.acrossMergedCell")),!1;const w={...v,startRow:o,endRow:o+v.endRow-v.startRow},y={unitId:R,subUnitId:C,sourceRange:v,targetRange:w},b=lo(s,y),T=s.get(i.ICommandService),U=u.onCommandExecute({id:pt.id,params:e}),k=[...(W=U.preRedos)!=null?W:[],{id:pe.id,params:y}],E=[...(V=U.preUndos)!=null?V:[],{id:pe.id,params:b}];if(M){const L=o-n<0,Y=v.endRow-v.startRow+1,z=L?w:{...w,startRow:w.startRow-Y,endRow:w.endRow-Y},K={unitId:R,subUnitId:C,type:te.MOVE_END,selections:[{range:z,primary:se(z,h),style:null}]},oe={unitId:R,subUnitId:C,type:te.MOVE_END,selections:[{range:v,primary:M,style:null}]};k.push({id:q.id,params:K}),E.push({id:q.id,params:oe})}if(k.push(...U.redos),E.push(...U.undos),i.sequenceExecute(k,T).result){const $=u.afterCommandExecute({id:pt.id,params:e});return i.sequenceExecute($.redos,T),k.push(...$.redos),E.push(...$.undos),s.get(i.IUndoRedoService).pushUndoRedo({unitID:R,undoMutations:E,redoMutations:k}),!0}return!1}},ar="sheet.command.move-cols",wt={id:ar,type:i.CommandType.COMMAND,handler:(s,e)=>{var W,V;const t=s.get(g.SheetsSelectionsService),{fromRange:{startColumn:n},toRange:{startColumn:o},range:r}=e,a=r?[lr(r)]:t.getCurrentSelections(),l=a==null?void 0:a.filter($=>$.range.rangeType===i.RANGE_TYPE.COLUMN&&$.range.startColumn<=n&&n<=$.range.endColumn);if((l==null?void 0:l.length)!==1)return!1;const u=s.get(g.SheetInterceptorService),d=s.get(i.IUniverInstanceService),c=P(d,e);if(!c)return!1;const{workbook:m,worksheet:h}=c,R=m.getUnitId(),C=h.getSheetId(),S=s.get(i.ErrorService),I=s.get(i.LocaleService),v=l[0].range,M=l[0].primary,p=At(v,h,!1);if(!i.Rectangle.equals(v,p))return S.emit(I.t("sheets.info.partOfCell")),!1;if(Il(o,h))return S.emit(I.t("sheets.info.acrossMergedCell")),!1;const w={...v,startColumn:o,endColumn:o+v.endColumn-v.startColumn},y={unitId:R,subUnitId:C,sourceRange:v,targetRange:w},b=uo(s,y),T=s.get(i.ICommandService),U=u.onCommandExecute({id:wt.id,params:e}),k=[...(W=U.preRedos)!=null?W:[],{id:we.id,params:y}],E=[...(V=U.preUndos)!=null?V:[],{id:we.id,params:b}];if(M){const $=v.endColumn-v.startColumn+1,z=o-n<0?w:{...w,startColumn:w.startColumn-$,endColumn:w.endColumn-$},K={unitId:R,subUnitId:C,type:te.MOVE_END,selections:[{range:z,primary:se(z,h),style:null}]},oe={unitId:R,subUnitId:C,type:te.MOVE_END,selections:[{range:v,primary:M,style:null}]};k.push({id:q.id,params:K}),E.push({id:q.id,params:oe})}if(k.push(...U.redos),E.push(...U.undos),i.sequenceExecute(k,T).result){const $=u.afterCommandExecute({id:wt.id,params:e});return i.sequenceExecute($.redos,T),k.push(...$.redos),E.push(...$.undos),s.get(i.IUndoRedoService).pushUndoRedo({unitID:R,undoMutations:E,redoMutations:k}),!0}return!1}};function lr(s){return{range:s,primary:null,style:null}}var vl=Object.getOwnPropertyDescriptor,pl=(s,e,t,n)=>{for(var o=n>1?void 0:n?vl(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},wl=(s,e)=>(t,n)=>e(t,n,s);g.SheetSkeletonService=class extends i.Disposable{constructor(t){super();f(this,"_sheetSkeletonStore",new Map);this._injector=t,this.disposeWithMe(()=>{this._sheetSkeletonStore=new Map})}getSkeleton(t,n){if(this._sheetSkeletonStore.has(t))return this._sheetSkeletonStore.get(t).get(n)}setSkeleton(t,n,o){this._sheetSkeletonStore.has(t)||this._sheetSkeletonStore.set(t,new Map),this._sheetSkeletonStore.get(t).set(n,o)}deleteSkeleton(t,n){this._sheetSkeletonStore.has(t)&&this._sheetSkeletonStore.get(t).delete(n)}},g.SheetSkeletonService=pl([wl(0,i.Inject(i.Injector))],g.SheetSkeletonService);function _s(s,e){const t=new i.ObjectMatrix;return s.map(n=>i.Range.transformRange(n,e)).forEach(n=>{i.Range.foreach(n,(o,r)=>{const a=e.getCellHeight(o,r);a&&t.setValue(o,r,a)})}),t}const Ml=1e4;function Bt(s,e){if(!e)return{suitableRanges:s,remainingRanges:[]};const t=e.worksheet.getColumnCount(),n=Math.ceil(Ml/t),o=[],r=[],a=e.getOffsetRelativeToRowCol(0,e.scrollY).row,l=s.map(d=>{let c;return a>=d.startRow&&a<=d.endRow?c=0:a<d.startRow?c=d.startRow-a:c=a-d.endRow,{range:d,distance:c,rowCount:d.endRow-d.startRow+1}});l.sort((d,c)=>d.distance!==c.distance?d.distance-c.distance:d.rowCount-c.rowCount);let u=0;for(const d of l)if(u+d.rowCount<=n)o.push(d.range),u+=d.rowCount;else{const c=n-u;if(c>0){const m={...d.range,endRow:d.range.startRow+c-1},h={...d.range,startRow:d.range.startRow+c};o.push(m),r.push(h),u=n}else r.push(d.range)}return{suitableRanges:o,remainingRanges:r}}const ur="sheet.command.reorder-range",Rn={id:ur,type:i.CommandType.COMMAND,handler:(s,e)=>{var p,w;const{subUnitId:t,unitId:n,range:o,order:r}=e,a=s.get(i.ICommandService),l={id:Ot.id,params:{unitId:n,subUnitId:t,order:r,range:o}},u={id:Ot.id,params:co(l.params)},d=s.get(g.SheetInterceptorService),c=d.onCommandExecute({id:Rn.id,params:e}),m=[...(p=c.preRedos)!=null?p:[],l,...c.redos],h=[...(w=c.preUndos)!=null?w:[],u,...c.undos],R=i.sequenceExecute(m,a),{suitableRanges:C,remainingRanges:S}=Bt([o],s.get(g.SheetSkeletonService).getSkeleton(n,t)),{undos:I,redos:v}=d.generateMutationsOfAutoHeight({unitId:n,subUnitId:t,ranges:[o],autoHeightRanges:C,lazyAutoHeightRanges:S}),M=d.afterCommandExecute({id:Rn.id,params:e});return R.result?(i.sequenceExecute([...M.redos,...v],a),s.get(i.IUndoRedoService).pushUndoRedo({unitID:n,undoMutations:[...h,...M.undos,...I],redoMutations:[...m,...M.redos,...v]}),!0):!1}},A={MoveRangeCommandId:Bo,InsertRowCommandId:Jo,InsertColCommandId:er,RemoveColCommandId:gn,RemoveRowCommandId:hn,DeleteRangeMoveLeftCommandId:Yo,DeleteRangeMoveUpCommandId:Ko,InsertRangeMoveDownCommandId:Sl,InsertRangeMoveRightCommandId:vs,MoveColsCommandId:ar,MoveRowsCommandId:ir,ReorderRangeCommandId:ur};var B=(s=>(s[s.Set=0]="Set",s[s.Delete=1]="Delete",s[s.HorizontalMove=2]="HorizontalMove",s[s.VerticalMove=3]="VerticalMove",s[s.Unknown=4]="Unknown",s))(B||{});const Cn=Number.MAX_SAFE_INTEGER,Pe=s=>{const e={...s},t=Number.isNaN(e.startRow)&&Number.isNaN(e.endRow)&&!Number.isNaN(e.startColumn)&&!Number.isNaN(e.endColumn),n=Number.isNaN(e.startColumn)&&Number.isNaN(e.endColumn)&&!Number.isNaN(e.startRow)&&!Number.isNaN(e.endRow);return(e.rangeType===i.RANGE_TYPE.COLUMN||t)&&(e.startRow=0,e.endRow=Cn),(e.rangeType===i.RANGE_TYPE.ROW||n)&&(e.startColumn=0,e.endColumn=Cn),e.rangeType===i.RANGE_TYPE.ALL&&(e.startColumn=0,e.endColumn=Cn,e.startRow=0,e.endRow=Cn),e},he=s=>{let e=s.rangeType;return s.rangeType===i.RANGE_TYPE.COLUMN?e=i.RANGE_TYPE.ROW:s.rangeType===i.RANGE_TYPE.ROW&&(e=i.RANGE_TYPE.COLUMN),{startRow:s.startColumn,endRow:s.endColumn,startColumn:s.startRow,endColumn:s.endRow,rangeType:e}},Ht=(s,e,t)=>{const n={...t},o={...e},r=(S,I)=>{const v=Math.max(S.start,I.start),M=Math.min(S.end,I.end);return M<v?null:{start:v,end:M}},a=S=>S.end-S.start+1,l=(S,I)=>({start:S.start-I.start,end:S.start-I.start+S.end-S.start}),u=(S,I)=>({start:I.start+S.start,end:I.start+S.start+S.end-S.start}),d=e.start>s.start;if(d){const S=Math.min(s.end,e.start)-s.start+1;o.start-=S,o.end-=S}const c=a(s),m=c,h=r(s,n),R=h&&a(h)>=a(n);if(s.end<n.start)n.start-=c,n.end-=c;else if(h){const S=a(h);if(R){const I=l(n,s),v=u(I,o);n.start=v.start,n.end=v.end}else h.start>s.start?d?(n.end-=S+c,n.start-=c):n.end-=S:d?n.end-=S:n.start>s.start&&n.end>s.end?(n.start-=c,n.end-=c+S):n.end-=S}const C=r(o,n);return R||(o.start<=n.start?(n.start+=m,n.end+=m):C&&(d?o.end<=n.start||o.start<=n.start&&o.end>=n.start?(n.start+=m,n.end+=m):o.start>=n.start&&o.start<=n.end&&(n.end+=m):n.start<o.start&&n.end>o.start?n.end+=m:(n.start>=o.end||n.start>=o.start&&n.start<=o.end)&&(n.end+=m,n.start+=m))),{step:n.start-t.start,length:a(n)-a(t)}},bs=(s,e)=>{const{fromRange:t,toRange:n}=s.params||{};if(!n||!t)return[];const o=Pe(t),r=Pe(n),a=Pe(e),l=Ht({start:o.startRow,end:o.endRow},{start:r.startRow,end:r.endRow},{start:a.startRow,end:a.endRow});return l===null?[{type:B.Delete}]:[{type:B.VerticalMove,step:l.step||0,length:l.length||0}]},yl=(s,e)=>{const{fromRange:t,toRange:n}=s.params||{};if(!t||!n)return[e];const o=t.startRow,r=t.endRow-t.startRow+1,a=n.startRow,l=new i.ObjectMatrix;return i.Range.foreach(e,(d,c)=>{l.setValue(d,c,1)}),l.moveRows(o,r,a),i.queryObjectMatrix(l,d=>d===1)},_l=(s,e)=>{const{range:t,order:n}=s.params||{};if(!t||!n)return[e];const o=new i.ObjectMatrix;i.Range.foreach(e,(l,u)=>{o.setValue(l,u,1)});const r=new i.ObjectMatrix;return i.Range.foreach(t,(l,u)=>{var d;if(Object.prototype.hasOwnProperty.call(n,l)){const c=n[l],m=(d=o.getValue(c,u))!=null?d:0;r.setValue(l,u,m)}}),r.forValue((l,u,d)=>{o.setValue(l,u,d)}),i.queryObjectMatrix(o,l=>l===1)},Es=(s,e)=>{const{fromRange:t,toRange:n}=s.params||{};if(!n||!t)return[];const o=Pe(t),r=Pe(n),a=Pe(e),l=Ht({start:o.startColumn,end:o.endColumn},{start:r.startColumn,end:r.endColumn},{start:a.startColumn,end:a.endColumn});return l===null?[{type:B.Delete}]:[{type:B.HorizontalMove,step:l.step||0,length:l.length||0}]},bl=(s,e)=>{const{fromRange:t,toRange:n}=s.params||{};if(!t||!n)return[e];const o=t.startColumn,r=t.endColumn-t.startColumn+1,a=n.startColumn,l=new i.ObjectMatrix;return i.Range.foreach(e,(u,d)=>{l.setValue(u,d,1)}),l.moveColumns(o,r,a),i.queryObjectMatrix(l,u=>u===1)},dr=(s,e)=>{var r,a;const t=(r=s.params)==null?void 0:r.toRange,n=(a=s.params)==null?void 0:a.fromRange;if(!t||!n)return[];const o=[];if(i.Rectangle.contains(t,e)&&o.push({type:B.Delete}),i.Rectangle.contains(n,e)){o.push({type:B.Delete});const l=i.Rectangle.getRelativeRange(e,n),u=i.Rectangle.getPositionRange(l,t);return[{type:B.Set,range:u}]}return o},El=(s,e)=>{var m,h;const t=(m=s.params)==null?void 0:m.toRange,n=(h=s.params)==null?void 0:h.fromRange;if(!t||!n)return[e];if(!i.Rectangle.intersects(n,e)&&!i.Rectangle.intersects(t,e))return[e];if(i.Rectangle.contains(n,e)){const R=i.Rectangle.getRelativeRange(e,n);return[i.Rectangle.getPositionRange(R,t)]}const o=new i.ObjectMatrix;i.Range.foreach(e,(R,C)=>{o.setValue(R,C,1)});const r=new i.ObjectMatrix,a=i.Rectangle.getIntersects(n,e);a&&i.Range.foreach(a,(R,C)=>{o.getValue(R,C)&&(o.setValue(R,C,void 0),r.setValue(R,C,1))});const l=t.startColumn-n.startColumn,u=t.startRow-n.startRow,d={startColumn:t.startColumn-l,endColumn:t.endColumn-l,startRow:t.startRow-u,endRow:t.endRow-u};return d&&i.Range.foreach(d,(R,C)=>{var v;const S=R+u,I=C+l;o.setValue(S,I,(v=r.getValue(R,C))!=null?v:0)}),i.queryObjectMatrix(o,R=>R===1)},Ze=(s,e)=>{const t=Pe(s),n=Pe(e),o=a=>a.endColumn-a.startColumn+1,r=a=>a.endRow-a.startRow+1;if(t.startRow<=n.startRow&&t.endRow>=n.endRow){if(n.startColumn<t.startColumn&&n.endColumn>=t.startColumn&&n.endColumn<=t.endColumn||n.startColumn<t.startColumn&&n.endColumn>=t.endColumn){const a=i.Rectangle.getIntersects(n,t);if(a)return{step:0,length:-o(a)}}if(n.startColumn>=t.startColumn&&n.endColumn<=t.endColumn&&r(t)>=r(n))return null;if(n.startColumn>=t.startColumn&&n.startColumn<=t.endColumn&&n.endColumn>t.endColumn){const a=i.Rectangle.getIntersects(n,t);if(a){const l=-o(a);return{step:-(o(t)-o(a)),length:l}}}if(n.startColumn>t.endColumn)return{step:-o(t),length:0}}return{step:0,length:0}},Ts=(s,e)=>{var r;const t=(r=s.params)==null?void 0:r.range;if(!t)return[];const n=[],o=Ze(t,e);if(!o)n.push({type:B.Delete});else{const{step:a,length:l}=o;n.push({type:B.HorizontalMove,step:a,length:l})}return n},cr=(s,e,t)=>{var a;const n=(a=s.params)==null?void 0:a.range;if(!n)return[];const o=[];if(t&&t.length>0){let l=n.startRow;for(let u=n.startRow;u<=n.endRow;u++){if(t.includes(u)){if(u===l){l=u+1;continue}r({...n,startRow:l,endRow:u-1}),l=u+1;continue}u===n.endRow&&r({...n,startRow:l,endRow:n.endRow})}}else r(n);function r(l){const u=Ze(he(l),he(e));if(!u)o.push({type:B.Delete});else{const{step:d,length:c}=u;o.push({type:B.VerticalMove,step:d,length:c})}}return o},Tl=(s,e)=>{const{range:t,order:n}=s.params||{};if(!t||!n)return[];if(i.Rectangle.contains(t,e)&&e.endRow===e.startRow){const o=[],r=e.startRow;for(const a in n)if(n[a]===r){const l=Number(a);return o.push({type:B.VerticalMove,step:l-r,length:0}),o}return[]}return[]},Qe=(s,e)=>{const t=Pe(s),n=Pe(e),o=r=>r.endColumn-r.startColumn+1;return t.startRow<=n.startRow&&t.endRow>=n.endRow?n.startColumn<t.startColumn&&n.endColumn>=t.startColumn&&n.endColumn<=t.endColumn||n.startColumn<t.startColumn&&n.endColumn>=t.endColumn?{step:0,length:o(t)}:n.startColumn>=t.startColumn&&n.endColumn<=t.endColumn||n.startColumn>=t.startColumn&&n.startColumn<=t.endColumn&&n.endColumn>t.endColumn||n.startColumn>=t.endColumn?{step:o(t),length:0}:{step:0,length:0}:{step:0,length:0}};function Ul(s,e,t){const n=[];if(i.Rectangle.contains(e,t)&&n.push({type:B.Delete}),i.Rectangle.contains(s,t)){n.push({type:B.Delete});const o=i.Rectangle.getRelativeRange(t,s),r=i.Rectangle.getPositionRange(o,e);return[{type:B.Set,range:r}]}return n}const mr=(s,e)=>{var l;const t=(l=s.params)==null?void 0:l.range;if(!t)return[];const n=[],o=Qe(he(t),he(e)),{step:r,length:a}=o;return n.push({type:B.VerticalMove,step:r,length:a}),n},hr=(s,e)=>{var l;const t=(l=s.params)==null?void 0:l.range;if(!t)return[];const n=[],o=Qe(t,e),{step:r,length:a}=o;return n.push({type:B.HorizontalMove,step:r,length:a}),n},gr=(s,e)=>{var l;const t=(l=s.params)==null?void 0:l.range;if(!t)return[];const n=[],o=Qe(he(t),he(e)),{step:r,length:a}=o;return n.push({type:B.VerticalMove,step:r,length:a}),n},Pl=(s,e)=>{var u;const t=(u=s.params)==null?void 0:u.range;if(!t)return[e];const n=t.endRow-t.startRow+1,o={...t,startRow:t.startRow,endRow:Number.POSITIVE_INFINITY},r=i.Rectangle.subtract(e,o),a=i.Rectangle.getIntersects(o,e);if(!a)return[e];const l=new i.ObjectMatrix;return r.forEach(d=>{i.Range.foreach(d,(c,m)=>{l.setValue(c,m,1)})}),a&&i.Range.foreach(a,(d,c)=>{l.setValue(d+n,c,1)}),i.queryObjectMatrix(l,d=>d===1)},Rr=(s,e)=>{var l;const t=(l=s.params)==null?void 0:l.range;if(!t)return[];const n=[],o=Qe(t,e),{step:r,length:a}=o;return n.push({type:B.HorizontalMove,step:r,length:a}),n},kl=(s,e)=>{var u;const t=(u=s.params)==null?void 0:u.range;if(!t)return[e];const n=t.endColumn-t.startColumn+1,o={...t,startColumn:t.startColumn,endColumn:Number.POSITIVE_INFINITY},r=i.Rectangle.subtract(e,o),a=i.Rectangle.getIntersects(o,e);if(!a)return[e];const l=new i.ObjectMatrix;return r.forEach(d=>{i.Range.foreach(d,(c,m)=>{l.setValue(c,m,1)})}),a&&i.Range.foreach(a,(d,c)=>{l.setValue(d,c+n,1)}),i.queryObjectMatrix(l,d=>d===1)},Cr=(s,e)=>{var r;const t=(r=s.params)==null?void 0:r.range;if(!t)return[];const n=[],o=Ze(t,e);if(!o)n.push({type:B.Delete});else{const{step:a,length:l}=o;n.push({type:B.HorizontalMove,step:a,length:l})}return n},Nl=(s,e)=>{var d;const t=(d=s.params)==null?void 0:d.range;if(!t)return[e];const n={startRow:t.startRow,endRow:t.endRow,startColumn:t.startColumn,endColumn:Number.POSITIVE_INFINITY},o=t.endColumn-t.startColumn+1,r=i.Rectangle.getIntersects(t,e),a=i.Rectangle.subtract(e,n),l=i.Rectangle.getIntersects(n,e);if(!r&&!l)return[e];const u=new i.ObjectMatrix;return l&&i.Range.foreach(l,(c,m)=>{u.setValue(c,m-o,1)}),r&&i.Range.foreach(r,(c,m)=>{u.setValue(c,m-o,0)}),a.forEach(c=>{i.Range.foreach(c,(m,h)=>{u.setValue(m,h,1)})}),i.queryObjectMatrix(u,c=>c===1)},Sr=(s,e)=>{var r;const t=(r=s.params)==null?void 0:r.range;if(!t)return[];const n=[],o=Ze(he(t),he(e));if(!o)n.push({type:B.Delete});else{const{step:a,length:l}=o;n.push({type:B.VerticalMove,step:a,length:l})}return n},Ol=(s,e)=>{var d;const t=(d=s.params)==null?void 0:d.range;if(!t)return[e];const n={...t,startRow:t.startRow,endRow:Number.POSITIVE_INFINITY},o=t.endRow-t.startRow+1,r=i.Rectangle.getIntersects(t,e),a=i.Rectangle.subtract(e,n),l=i.Rectangle.getIntersects(n,e);if(!r&&!l)return[e];const u=new i.ObjectMatrix;return l&&i.Range.foreach(l,(c,m)=>{u.setValue(c-o,m,1)}),r&&i.Range.foreach(r,(c,m)=>{u.setValue(c-o,m,0)}),a.forEach(c=>{i.Range.foreach(c,(m,h)=>{u.setValue(m,h,1)})}),i.queryObjectMatrix(u,c=>c===1)},Dl=(s,e)=>{var o;const t=(o=s.ranges)!=null?o:[s.range],n=new i.ObjectMatrix;return i.Range.foreach(e,(r,a)=>{n.setValue(r,a,1)}),t.forEach(r=>{const a=r.startRow,u=r.endRow-a+1;n.removeRows(a,u)}),i.queryObjectMatrix(n,r=>r===1)},Al=(s,e)=>{const t=s.params,n=t.range.startRow,o=t.range.endRow-t.range.startRow+1;return e.startRow>=n?[{startRow:e.startRow+o,endRow:e.endRow+o,startColumn:e.startColumn,endColumn:e.endColumn}]:e.endRow<n?[e]:[{startRow:e.startRow,endRow:e.endRow+o,startColumn:e.startColumn,endColumn:e.endColumn}]},Wl=(s,e)=>{const t=s.params,n=t.range.startColumn,o=t.range.endColumn-t.range.startColumn+1;return e.startColumn>=n?[{startRow:e.startRow,endRow:e.endRow,startColumn:e.startColumn+o,endColumn:e.endColumn+o}]:e.endColumn<n?[e]:[{startRow:e.startRow,endRow:e.endRow,startColumn:e.startColumn,endColumn:e.endColumn+o}]},et=(s,e)=>{let t={...e};return s.forEach(n=>{switch(n.type){case B.Delete:{t=null;break}case B.HorizontalMove:{if(!t)return;t.startColumn+=n.step,t.endColumn+=n.step+(n.length||0);break}case B.VerticalMove:{if(!t)return;t.startRow+=n.step,t.endRow+=n.step+(n.length||0);break}case B.Set:{t=n.range;break}}}),t&&(t.endColumn<t.startColumn||t.endRow<t.startRow)?null:t},Us=(s,e)=>{let t=[];switch(e.id){case A.DeleteRangeMoveLeftCommandId:{t=Cr(e,s);break}case A.DeleteRangeMoveUpCommandId:{t=Sr(e,s);break}case A.InsertColCommandId:{t=hr(e,s);break}case A.InsertRangeMoveDownCommandId:{t=gr(e,s);break}case A.InsertRangeMoveRightCommandId:{t=Rr(e,s);break}case A.InsertRowCommandId:{t=mr(e,s);break}case A.MoveColsCommandId:{t=Es(e,s);break}case A.MoveRangeCommandId:{t=dr(e,s);break}case A.MoveRowsCommandId:{t=bs(e,s);break}case A.RemoveColCommandId:{t=Ts(e,s);break}case A.RemoveRowCommandId:{t=cr(e,s);break}case A.ReorderRangeCommandId:{t=Tl(e,s);break}}return et(t,s)},Vl=(s,e,t)=>[Be.id,He.id].includes(e.id)||Ir(e,t).some(r=>i.Rectangle.intersects(r,s))?Us(s,e):s,Ps=(s,e)=>{let t=[];switch(e.id){case A.DeleteRangeMoveLeftCommandId:return Nl(e,s);case A.DeleteRangeMoveUpCommandId:return Ol(e,s);case A.InsertRangeMoveDownCommandId:return Pl(e,s);case A.InsertRangeMoveRightCommandId:return kl(e,s);case A.InsertColCommandId:return Wl(e,s);case A.InsertRowCommandId:return Al(e,s);case A.MoveColsCommandId:return bl(e,s);case A.MoveRangeCommandId:return El(e,s);case A.MoveRowsCommandId:return yl(e,s);case A.ReorderRangeCommandId:return _l(e,s);case A.RemoveColCommandId:{t=Ts(e,s);break}case A.RemoveRowCommandId:return Dl(e.params,s)}const n=et(t,s);return n?[n]:[]},$l=(s,e,t)=>[Be.id,He.id,xe.id,vs].includes(e.id)||Ir(e,t).some(r=>i.Rectangle.intersects(r,s))?Ps(s,e):s;function fr(s,e){const{id:t,params:n}=e;let o={length:0,step:0,type:B.Unknown};switch(t){case Xe.id:o.type=B.Delete;break;case pe.id:o=Ht({start:n.sourceRange.startRow,end:n.sourceRange.endRow},{start:n.targetRange.startRow,end:n.targetRange.endRow},{start:s.startRow,end:s.endRow}),o.type=B.VerticalMove;break;case we.id:o=Ht({start:n.sourceRange.startColumn,end:n.sourceRange.endColumn},{start:n.targetRange.startColumn,end:n.targetRange.endColumn},{start:s.startColumn,end:s.endColumn}),o.type=B.HorizontalMove;break;case ne.id:o=Ze(n.range,s),o?o.type=B.HorizontalMove:o={step:0,length:0,type:B.Delete};break;case ae.id:o=Ze(he(n.range),he(s)),o?o.type=B.VerticalMove:o={step:0,length:0,type:B.Delete};break;case re.id:o=Qe(he(n.range),he(s)),o.type=B.VerticalMove;break;case ie.id:o=Qe(n.range,s),o.type=B.HorizontalMove;break;case Le.id:{const r=n.fromRange||new i.ObjectMatrix(n.from).getRange(),a=n.toRange||new i.ObjectMatrix(n.to).getRange();o=Ul(r,a,s)}break}return o?Array.isArray(o)?et(o,s):et([o],s):s}function Ir(s,e){var n,o,r,a,l,u;const{selectionManagerService:t}=e;switch(s.id){case A.MoveColsCommandId:{const d=s.params;return[d.fromRange,{...d.toRange,startColumn:d.toRange.startColumn-.5,endColumn:d.toRange.endColumn-.5}]}case A.MoveRowsCommandId:{const d=s.params;return[d.fromRange,{...d.toRange,startRow:d.toRange.startRow-.5,endRow:d.toRange.startRow-.5}]}case A.MoveRangeCommandId:{const d=s;return[d.params.fromRange,d.params.toRange]}case A.InsertRowCommandId:{const c=s.params.range;return[{...c,startRow:c.startRow-.5,endRow:c.endRow-.5}]}case A.InsertColCommandId:{const c=s.params.range;return[{...c,startColumn:c.startColumn-.5,endColumn:c.endColumn-.5}]}case A.RemoveRowCommandId:return[s.params.range];case A.RemoveColCommandId:return[s.params.range];case A.DeleteRangeMoveUpCommandId:case A.InsertRangeMoveDownCommandId:{const c=((n=s.params)==null?void 0:n.range)||((r=(o=t.getCurrentSelections())==null?void 0:o.map(m=>m.range))==null?void 0:r[0]);return c?[c]:[]}case A.DeleteRangeMoveLeftCommandId:case A.InsertRangeMoveRightCommandId:{const c=((a=s.params)==null?void 0:a.range)||((u=(l=t.getCurrentSelections())==null?void 0:l.map(m=>m.range))==null?void 0:u[0]);return c?[c]:[]}case A.ReorderRangeCommandId:{const d=s,{range:c,order:m}=d.params,h=[];for(let R=c.startRow;R<=c.endRow;R++)R in m&&h.push({startRow:R,endRow:R,startColumn:c.startColumn,endColumn:c.endColumn});return h}}}function Ll(s){switch(s.id){case we.id:{const e=s.params;return[e.sourceRange,{...e.targetRange,startColumn:e.targetRange.startColumn-.5,endColumn:e.targetRange.startColumn-.5}]}case pe.id:{const e=s.params;return[e.sourceRange,{...e.targetRange,startRow:e.targetRange.startRow-.5,endRow:e.targetRange.startRow-.5}]}case Le.id:{const e=s.params;return[new i.ObjectMatrix(e.from.value).getRange(),new i.ObjectMatrix(e.to.value).getRange()]}case ie.id:{const t=s.params.range;return[{...t,startColumn:t.startColumn-.5,endColumn:t.startColumn-.5}]}case re.id:{const t=s.params.range;return[{...t,startRow:t.startRow-.5,endRow:t.startRow-.5}]}case ne.id:return[s.params.range];case ae.id:return[s.params.range]}}function Bl(s,e){var o,r,a,l,u,d;const t=s.get(i.IUniverInstanceService),n=s.get(g.SheetsSelectionsService);switch(e.id){case A.MoveColsCommandId:{const c=e.params,m=P(t,{unitId:c.unitId,subUnitId:c.subUnitId});return{unitId:m.unitId,subUnitId:m.subUnitId,ranges:[c.fromRange,{...c.toRange,startColumn:c.fromRange.startColumn<c.toRange.startColumn?c.fromRange.endColumn+1:c.toRange.startColumn,endColumn:c.fromRange.startColumn<c.toRange.startColumn?c.toRange.endColumn-1:c.fromRange.startColumn-1}]}}case A.MoveRowsCommandId:{const c=e.params,m=P(t,{unitId:c.unitId,subUnitId:c.subUnitId});return{unitId:m.unitId,subUnitId:m.subUnitId,ranges:[c.fromRange,{...c.toRange,startRow:c.fromRange.startRow<c.toRange.startRow?c.fromRange.endRow+1:c.toRange.startRow,endRow:c.fromRange.startRow<c.toRange.startRow?c.toRange.endRow-1:c.fromRange.startRow-1}]}}case A.MoveRangeCommandId:{const c=e.params,m=P(t);return{unitId:m.unitId,subUnitId:m.subUnitId,ranges:[c.fromRange,c.toRange]}}case A.InsertRowCommandId:{const c=e.params,m=c.range;return{unitId:c.unitId,subUnitId:c.subUnitId,ranges:[...m.startRow>0?[{...m,startRow:m.startRow-1,endRow:m.endRow-1}]:[],{...m,startRow:m.startRow,endRow:Number.MAX_SAFE_INTEGER}]}}case A.InsertColCommandId:{const c=e.params,m=c.range;return{unitId:c.unitId,subUnitId:c.subUnitId,ranges:[...m.startColumn>0?[{...m,startColumn:m.startColumn-1,endColumn:m.endColumn-1}]:[],{...m,startColumn:m.startColumn,endColumn:Number.MAX_SAFE_INTEGER}]}}case A.RemoveRowCommandId:{const m=e.params.range,h=P(t);return{unitId:h.unitId,subUnitId:h.subUnitId,ranges:[m,{...m,startRow:m.endRow+1,endRow:Number.MAX_SAFE_INTEGER}]}}case A.RemoveColCommandId:{const m=e.params.range,h=P(t);return{unitId:h.unitId,subUnitId:h.subUnitId,ranges:[m,{...m,startColumn:m.endColumn+1,endColumn:Number.MAX_SAFE_INTEGER}]}}case A.DeleteRangeMoveUpCommandId:case A.InsertRangeMoveDownCommandId:{const c=e,m=P(t),h=((o=c.params)==null?void 0:o.range)||((a=(r=n.getCurrentSelections())==null?void 0:r.map(R=>R.range))==null?void 0:a[0]);return h?{unitId:m.unitId,subUnitId:m.subUnitId,ranges:[h,{...h,startRow:h.endRow+1,endRow:Number.MAX_SAFE_INTEGER}]}:{unitId:m.unitId,subUnitId:m.subUnitId,ranges:[]}}case A.DeleteRangeMoveLeftCommandId:case A.InsertRangeMoveRightCommandId:{const m=((l=e.params)==null?void 0:l.range)||((d=(u=n.getCurrentSelections())==null?void 0:u.map(R=>R.range))==null?void 0:d[0]),h=P(t);return m?{unitId:h.unitId,subUnitId:h.subUnitId,ranges:[m,{...m,startColumn:m.endColumn+1,endColumn:Number.MAX_SAFE_INTEGER}]}:{unitId:h.unitId,subUnitId:h.subUnitId,ranges:[]}}case A.ReorderRangeCommandId:{const c=e,{range:m,order:h}=c.params,R=[];for(let S=m.startRow;S<=m.endRow;S++)S in h&&R.push({startRow:S,endRow:S,startColumn:m.startColumn,endColumn:m.endColumn});const C=P(t);return{unitId:C.unitId,subUnitId:C.subUnitId,ranges:R}}}}var Hl=Object.getOwnPropertyDescriptor,Fl=(s,e,t,n)=>{for(var o=n>1?void 0:n?Hl(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},Sn=(s,e)=>(t,n)=>e(t,n,s);const jl=i.createInterceptorKey("MERGE_REDO"),Gl=i.createInterceptorKey("MERGE_UNDO"),vr=Math.floor(Number.MAX_SAFE_INTEGER/10);class zl extends i.Disposable{constructor(e,t,n,o,r=!1){super(),this._unitId=e,this._subUnitId=t,this._range=n,this._callback=o,this._skipIntersects=r}onMutation(e){var o,r;if(((o=e.params)==null?void 0:o.unitId)!==this._unitId)return;if(e.id===Le.id){const a=e.params;if(a.from.subUnitId!==this._subUnitId||a.to.subUnitId!==this._subUnitId)return}else if(((r=e.params)==null?void 0:r.subUnitId)!==this._subUnitId)return;if(!this._range)return;if(this._skipIntersects){if(e.id===Xe.id)return;const a=Ll(e);if(a!=null&&a.some(l=>i.Rectangle.intersects(l,this._range)))return}const t=fr(this._range,e);if(t&&i.Rectangle.equals(t,this._range))return!1;const n=this._range;this._range=t,this._callback(n,t)}}g.RefRangeService=class extends i.Disposable{constructor(t,n,o,r){super();f(this,"interceptor",new i.InterceptorManager({MERGE_REDO:jl,MERGE_UNDO:Gl}));f(this,"_watchRanges",new Set);f(this,"_refRangeManagerMap",new Map);f(this,"_serializer",ql());f(this,"_onRefRangeChange",()=>{this._sheetInterceptorService.interceptCommand({getMutations:t=>{const n=this._univerInstanceService.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET).getActiveSheet(),o=pr(this._univerInstanceService),r=wr(this._univerInstanceService);if(!n||!o||!r)return{redos:[],undos:[],preRedos:[],preUndos:[]};const u=((()=>{switch(t.id){case A.MoveColsCommandId:{const R=t.params,C=Math.min(R.fromRange.startColumn,R.toRange.startColumn);return this._checkRange([{...R.fromRange,startColumn:C,endColumn:n.getColumnCount()-1}],o,r)}case A.MoveRowsCommandId:{const R=t.params,C=Math.min(R.fromRange.startRow,R.toRange.startRow);return this._checkRange([{...R.fromRange,startRow:C,endRow:n.getRowCount()-1}],o,r)}case A.MoveRangeCommandId:{const R=t;return this._checkRange([R.params.fromRange,R.params.toRange],o,r)}case A.InsertRowCommandId:{const S={startRow:t.params.range.startRow,endRow:n.getRowCount()-1,startColumn:0,endColumn:n.getColumnCount()-1,rangeType:i.RANGE_TYPE.ROW};return this._checkRange([S],o,r)}case A.InsertColCommandId:{const C=t.params.range.startColumn,S={startRow:0,endRow:n.getRowCount()-1,startColumn:C,endColumn:n.getColumnCount()-1,rangeType:i.RANGE_TYPE.COLUMN};return this._checkRange([S],o,r)}case A.RemoveRowCommandId:{const S={startRow:t.params.range.startRow,endRow:n.getRowCount()-1,startColumn:0,endColumn:n.getColumnCount()-1,rangeType:i.RANGE_TYPE.ROW};return this._checkRange([S],o,r)}case A.RemoveColCommandId:{const C=t.params.range.startColumn,S={startRow:0,endRow:n.getRowCount()-1,startColumn:C,endColumn:n.getColumnCount()-1,rangeType:i.RANGE_TYPE.COLUMN};return this._checkRange([S],o,r)}case A.DeleteRangeMoveUpCommandId:case A.InsertRangeMoveDownCommandId:{const C=t.params.range||Mr(this._selectionManagerService)[0],S={startRow:C.startRow,startColumn:C.startColumn,endColumn:C.endColumn,endRow:vr};return this._checkRange([S],o,r)}case A.DeleteRangeMoveLeftCommandId:case A.InsertRangeMoveRightCommandId:{const C=t.params.range||Mr(this._selectionManagerService)[0],S={startRow:C.startRow,startColumn:C.startColumn,endColumn:vr,endRow:C.endRow};return this._checkRange([S],o,r)}case A.ReorderRangeCommandId:{const R=t,{range:C,order:S}=R.params,I=[];for(let v=C.startRow;v<=C.endRow;v++)v in S&&I.push({startRow:v,endRow:v,startColumn:C.startColumn,endColumn:C.endColumn});return this._checkRange(I,o,r)}}})()||[]).reduce((R,C)=>{const S=C(t);return R.push(S),R},[]).reduce((R,C)=>{var S,I;return R.redos.push(...C.redos),R.undos.push(...C.undos),R.preRedos.push(...(S=C.preRedos)!=null?S:[]),R.preUndos.push(...(I=C.preUndos)!=null?I:[]),R},{redos:[],undos:[],preUndos:[],preRedos:[]}),d=this.interceptor.fetchThroughInterceptors(this.interceptor.getInterceptPoints().MERGE_REDO)(u.preRedos,null)||[],c=this.interceptor.fetchThroughInterceptors(this.interceptor.getInterceptPoints().MERGE_REDO)(u.redos,null)||[],m=this.interceptor.fetchThroughInterceptors(this.interceptor.getInterceptPoints().MERGE_UNDO)(u.preUndos,null)||[],h=this.interceptor.fetchThroughInterceptors(this.interceptor.getInterceptPoints().MERGE_UNDO)(u.undos,null)||[];return{redos:c,undos:h,preRedos:d,preUndos:m}}})});f(this,"_checkRange",(t,n,o)=>{const r=yr(n,o),a=this._refRangeManagerMap.get(r);if(a){const l=new Set;return[...a.keys()].forEach(d=>{const c=a.get(d),m=this._serializer.deserialize(d),h={...m,startRow:+m.startRow,endRow:+m.endRow,startColumn:+m.startColumn,endColumn:+m.endColumn,rangeType:m.rangeType&&+m.rangeType};t.some(R=>i.Rectangle.intersects(R,h))&&c&&c.forEach(R=>{l.add(R)})}),[...l]}return[]});f(this,"registerRefRange",(t,n,o,r)=>{const a=o||pr(this._univerInstanceService),l=r||wr(this._univerInstanceService);if(!a||!l)return i.toDisposable(()=>{});const u=yr(a,l),d=this._serializer.serialize(t);let c=this._refRangeManagerMap.get(u);c||(c=new Map,this._refRangeManagerMap.set(u,c));const m=c.get(d);return m?m.add(n):c.set(d,new Set([n])),i.toDisposable(()=>{const h=c.get(d);h&&(h.delete(n),h.size||(c.delete(d),c.size||this._refRangeManagerMap.delete(u)))})});this._commandService=t,this._sheetInterceptorService=n,this._univerInstanceService=o,this._selectionManagerService=r,this._onRefRangeChange(),this.interceptor.intercept(this.interceptor.getInterceptPoints().MERGE_REDO,{priority:-1,handler:a=>a}),this.interceptor.intercept(this.interceptor.getInterceptPoints().MERGE_UNDO,{priority:-1,handler:a=>a})}watchRange(t,n,o,r,a){let l;this._watchRanges.size===0&&(l=this._commandService.onCommandExecuted(m=>{if(m.type!==i.CommandType.MUTATION)return!1;for(const h of this._watchRanges)h.onMutation(m)}));const u=new zl(t,n,o,r,a);this._watchRanges.add(u);const d=i.toDisposable(()=>{this._watchRanges.delete(u),this._watchRanges.size===0&&(l==null||l.dispose(),l=null)}),c=this.disposeWithMe(d);return i.toDisposable(()=>{c.dispose(),d.dispose()})}},g.RefRangeService=Fl([Sn(0,i.ICommandService),Sn(1,i.Inject(g.SheetInterceptorService)),Sn(2,i.Inject(i.IUniverInstanceService)),Sn(3,i.Inject(g.SheetsSelectionsService))],g.RefRangeService);function pr(s){return s.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET).getUnitId()}function wr(s){var e;return(e=s.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET).getActiveSheet())==null?void 0:e.getSheetId()}function Mr(s){var e;return((e=s.getCurrentSelections())==null?void 0:e.map(t=>t.range))||[]}function yr(s,e){return`${s}_${e}`}function ql(){const s=["startRow","startColumn","endRow","endColumn","rangeType"];return{deserialize:t=>{const n=s.reduce((r,a,l)=>(r[String(l)]=a,r),{});return t.split("_").reduce((r,a,l)=>{const u=String(l);return a&&n[u]&&(r[n[u]]=a),r},{})},serialize:t=>s.reduce((n,o,r)=>{const a=t[o];return a!==void 0?`${n}${r>0?"_":""}${a}`:`${n}`},"")}}var Yl=Object.getOwnPropertyDescriptor,Kl=(s,e,t,n)=>{for(var o=n>1?void 0:n?Yl(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},Mt=(s,e)=>(t,n)=>e(t,n,s);const Jl=[ie.id,re.id,ne.id,ae.id],xl=[pe.id,we.id];function ks(s,e){let t=s;if(e!==void 0){const n=[];for(let o=0;o<t.length;o++){const{startRow:r,endRow:a,startColumn:l,endColumn:u}=t[o];if(e===i.Dimension.ROWS)for(let d=r;d<=a;d++){const c={startRow:d,endRow:d,startColumn:l,endColumn:u};n.push(c)}else if(e===i.Dimension.COLUMNS)for(let d=l;d<=u;d++){const c={startRow:r,endRow:a,startColumn:d,endColumn:d};n.push(c)}}t=n}return t}const _r=i.createInterceptorKey("mergeCellPermissionCheck");g.MergeCellController=class extends i.Disposable{constructor(t,n,o,r,a,l){super();f(this,"disposableCollection",new i.DisposableCollection);f(this,"interceptor",new i.InterceptorManager({MERGE_CELL_INTERCEPTOR_CHECK:_r}));this._commandService=t,this._refRangeService=n,this._univerInstanceService=o,this._injector=r,this._sheetInterceptorService=a,this._selectionManagerService=l,this._onRefRangeChange(),this._initCommandInterceptor(),this._commandExecutedListener()}_initCommandInterceptor(){const t=this;this._sheetInterceptorService.interceptCommand({getMutations(n){var o;switch(n.id){case sn.id:case on.id:{const r=t._univerInstanceService.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET),a=r.getUnitId(),l=r==null?void 0:r.getActiveSheet();if(!l)return{redos:[],undos:[]};const u=l.getSheetId(),d=l.getConfig().mergeData,c=(o=t._selectionManagerService.getCurrentSelections())==null?void 0:o.map(m=>m.range);if(c&&c.length>0&&c.some(h=>d.some(R=>i.Rectangle.intersects(R,h)))){const h={unitId:a,subUnitId:u,ranges:c},R=le(t._injector,h),C=[{id:G.id,params:h}],S=[{id:j.id,params:R}];return{redos:C,undos:S}}}}return{redos:[],undos:[]}}}),this._sheetInterceptorService.interceptRanges({getMutations:({unitId:n,subUnitId:o,ranges:r})=>{const a=[],l=[],u={redos:a,undos:l};if(!r||!r.length)return u;const d=P(this._univerInstanceService,{unitId:n,subUnitId:o});if(!d)return u;const{worksheet:c}=d,h=c.getMergeData().filter(R=>r.some(C=>i.Rectangle.intersects(R,C)));return h.length?(a.push({id:G.id,params:{unitId:n,subUnitId:o,ranges:h}}),l.push({id:j.id,params:{unitId:n,subUnitId:o,ranges:h}}),{undos:l,redos:a}):u}})}refRangeHandle(t,n,o){switch(t.id){case A.MoveColsCommandId:{const r=t.params;return this._handleMoveColsCommand(r,n,o)}case A.MoveRowsCommandId:{const r=t.params;return this._handleMoveRowsCommand(r,n,o)}case Me.id:{const r=t.params,a=r.unitId||n,l=r.subUnitId||o;return this._handleInsertRowCommand(r,a,l)}case ye.id:{const r=t.params,a=r.unitId||n,l=r.subUnitId||o;return this._handleInsertColCommand(r,a,l)}case Lt.id:{const r=t.params;return this._handleRemoveColCommand(r,n,o)}case $t.id:{const r=t.params;return this._handleRemoveRowCommand(r,n,o)}case Je.id:{const r=t.params;return this._handleMoveRangeCommand(r,n,o)}case vt.id:{const r=t.params;return this._handleInsertRangeMoveRightCommand(r,n,o)}case xe.id:{const r=t.params;return this._handleInsertRangeMoveDownCommand(r,n,o)}case He.id:{const r=t.params;return this._handleDeleteRangeMoveUpCommand(r,n,o)}case Be.id:{const r=t.params;return this._handleDeleteRangeMoveLeftCommand(r,n,o)}}return{redos:[],undos:[]}}_onRefRangeChange(){const t=(n,o)=>{const r=this._univerInstanceService.getUniverSheetInstance(n);if(!r)return;const a=r==null?void 0:r.getSheetBySheetId(o);if(!a)return;this.disposableCollection.dispose();const l=a.getMergeData(),u=d=>this.refRangeHandle(d,n,o);l.forEach(d=>{this.disposableCollection.add(this._refRangeService.registerRefRange(d,u,n,o))})};this.disposeWithMe(this._commandService.onCommandExecuted(n=>{if(n.id===Ct.id){const o=n.params,r=o.subUnitId,a=o.unitId;if(!r||!a)return;t(a,r)}if(n.id===j.id){const o=n.params,r=o.subUnitId,a=o.unitId;if(!r||!a)return;t(o.unitId,o.subUnitId)}})),this._univerInstanceService.getCurrentTypeOfUnit$(i.UniverInstanceType.UNIVER_SHEET).pipe(O.first(n=>!!n)).subscribe(n=>{const o=n.getActiveSheet();o&&t(n.getUnitId(),o.getSheetId())})}_handleMoveRowsCommand(t,n,o){const r=_e(this._univerInstanceService,n);if(!r)return this._handleNull();const a=be(r,o);if(!a)return this._handleNull();const l=[...a.getMergeData()],u={unitId:n,subUnitId:o,ranges:[]},d={unitId:n,subUnitId:o,ranges:[]},{fromRange:c}=t,{startRow:m,endRow:h}=c;if(l.forEach(S=>{if(m<=S.startRow&&h>=S.endRow){u.ranges.push(S);const I=bs({id:A.MoveRowsCommandId,params:t},S),v=et(I,S);v&&d.ranges.push(v)}}),u.ranges.length===0)return this._handleNull();const R=le(this._injector,u),C=ge(this._injector,d);return{preRedos:[{id:G.id,params:u}],redos:[{id:j.id,params:d}],preUndos:[{id:G.id,params:C}],undos:[{id:j.id,params:R}]}}_handleMoveColsCommand(t,n,o){const r=_e(this._univerInstanceService,n);if(!r)return this._handleNull();const a=be(r,o);if(!a)return this._handleNull();const l=[...a.getMergeData()],u={unitId:n,subUnitId:o,ranges:[]},d={unitId:n,subUnitId:o,ranges:[]},{fromRange:c}=t,{startColumn:m,endColumn:h}=c;if(l.forEach(S=>{if(m<=S.startColumn&&h>=S.endColumn){u.ranges.push(S);const I=Es({id:A.MoveColsCommandId,params:t},S),v=et(I,S);v&&d.ranges.push(v)}}),u.ranges.length===0)return this._handleNull();const R=le(this._injector,u),C=ge(this._injector,d);return{preRedos:[{id:G.id,params:u}],redos:[{id:j.id,params:d}],preUndos:[{id:G.id,params:C}],undos:[{id:j.id,params:R}]}}_handleMoveRangeCommand(t,n,o){const r=_e(this._univerInstanceService,n);if(!r)return this._handleNull();const a=be(r,o);if(!a)return this._handleNull();const l=a.getMergeData(),u=l.filter(C=>i.Rectangle.intersects(C,t.fromRange)),d=l.filter(C=>i.Rectangle.intersects(C,t.toRange)),c=u.map(C=>i.Rectangle.getRelativeRange(C,t.fromRange)).map(C=>i.Rectangle.getPositionRange(C,t.toRange)),m=ks(c).filter(C=>!l.some(S=>i.Rectangle.equals(C,S))),h=[{id:G.id,params:{unitId:n,subUnitId:o,ranges:u}},{id:G.id,params:{unitId:n,subUnitId:o,ranges:d}},{id:j.id,params:{unitId:n,subUnitId:o,ranges:m}}],R=[{id:G.id,params:{unitId:n,subUnitId:o,ranges:m}},{id:j.id,params:{unitId:n,subUnitId:o,ranges:d}},{id:j.id,params:{unitId:n,subUnitId:o,ranges:u}}];return{redos:h,undos:R}}_handleInsertRowCommand(t,n,o){const r=_e(this._univerInstanceService,n);if(!r)return this._handleNull();const a=be(r,o);if(!a)return this._handleNull();const{range:l}=t,{startRow:u,endRow:d}=l,c=i.Tools.deepClone(a.getMergeData()).reduce((M,p)=>(u>p.startRow&&u<=p.endRow&&M.push(p),M),[]);if(c.length===0)return this._handleNull();const m=i.Tools.deepClone(a.getMergeData()).reduce((M,p)=>{if(u>p.startRow&&u<=p.endRow){const w=d-u+1;p.endRow+=w,this._checkIsMergeCell(p)&&M.push(p)}return M},[]),h={unitId:n,subUnitId:o,ranges:c},R=le(this._injector,h),C={unitId:n,subUnitId:o,ranges:m},S=ge(this._injector,C),I=[{id:G.id,params:h},{id:j.id,params:C}],v=[{id:G.id,params:S},{id:j.id,params:R}];return{redos:I,undos:v}}_handleInsertColCommand(t,n,o){const{range:r}=t,a=_e(this._univerInstanceService,n);if(!a)return this._handleNull();const l=be(a,o);if(!l)return this._handleNull();const{startColumn:u,endColumn:d}=r,c=i.Tools.deepClone(l.getMergeData()).reduce((M,p)=>(u>p.startColumn&&u<=p.endColumn&&M.push(p),M),[]);if(c.length===0)return this._handleNull();const m=i.Tools.deepClone(l.getMergeData()).reduce((M,p)=>{if(u>p.startColumn&&u<=p.endColumn){const w=d-u+1;p.endColumn+=w,this._checkIsMergeCell(p)&&M.push(p)}return M},[]),h={unitId:n,subUnitId:o,ranges:c},R=le(this._injector,h),C={unitId:n,subUnitId:o,ranges:m},S=ge(this._injector,C),I=[{id:G.id,params:h},{id:j.id,params:C}],v=[{id:G.id,params:S},{id:j.id,params:R}];return{redos:I,undos:v}}_handleRemoveColCommand(t,n,o){const r=_e(this._univerInstanceService,n);if(!r)return this._handleNull();const a=be(r,o);if(!a)return this._handleNull();const{range:l}=t,{startColumn:u,endColumn:d}=l,c=i.Tools.deepClone(a.getMergeData()).reduce((w,y)=>(i.Rectangle.intersects(l,y)&&w.push(y),w),[]);if(c.length===0)return this._handleNull();const m=i.Tools.deepClone(a.getMergeData()).reduce((w,y)=>{if(i.Rectangle.intersects(l,y)){if(u<=y.startColumn&&d>=y.endColumn)return w;u>=y.startColumn&&d<=y.endColumn?y.endColumn-=d-u+1:u<y.startColumn?(y.startColumn=u,y.endColumn-=d-u+1):d>y.endColumn&&(y.endColumn=u-1),this._checkIsMergeCell(y)&&w.push(y)}return w},[]),h={unitId:n,subUnitId:o,ranges:c},R=le(this._injector,h),C={unitId:n,subUnitId:o,ranges:m},S=ge(this._injector,C),I=[{id:G.id,params:h}],v=[{id:j.id,params:C}],M=[{id:G.id,params:S}],p=[{id:j.id,params:R}];return{preUndos:M,undos:p,preRedos:I,redos:v}}_handleRemoveRowCommand(t,n,o){const{range:r}=t,a=_e(this._univerInstanceService,n);if(!a)return this._handleNull();const l=be(a,o);if(!l)return this._handleNull();const{startRow:u,endRow:d}=r,c=i.Tools.deepClone(l.getMergeData()).reduce((w,y)=>(i.Rectangle.intersects(r,y)&&w.push(y),w),[]);if(c.length===0)return this._handleNull();const m=i.Tools.deepClone(l.getMergeData()).reduce((w,y)=>{if(i.Rectangle.intersects(r,y)){if(u<=y.startRow&&d>=y.endRow)return w;u>=y.startRow&&d<=y.endRow?y.endRow-=d-u+1:u<y.startRow?(y.startRow=u,y.endRow-=d-u+1):d>y.endRow&&(y.endRow=u-1),this._checkIsMergeCell(y)&&w.push(y)}return w},[]),h={unitId:n,subUnitId:o,ranges:c},R=le(this._injector,h),C={unitId:n,subUnitId:o,ranges:m},S=ge(this._injector,C),I=[{id:G.id,params:h}],v=[{id:j.id,params:C}],M=[{id:G.id,params:S}],p=[{id:j.id,params:R}];return{preUndos:M,undos:p,preRedos:I,redos:v}}_handleInsertRangeMoveRightCommand(t,n,o){const r=_e(this._univerInstanceService,n);if(!r)return this._handleNull();const a=be(r,o);if(!a)return this._handleNull();const l=t.range,u=a.getMaxColumns()-1,d=a.getMergeData(),c=[],m=[];d.forEach(I=>{const{startRow:v,endRow:M,startColumn:p,endColumn:w}=l;if(i.Rectangle.intersects({startRow:v,startColumn:p,endRow:M,endColumn:u},I)&&(c.push(I),i.Rectangle.contains({startRow:v,startColumn:p,endRow:M,endColumn:u},I))){const T=w-p+1;m.push({startRow:I.startRow,startColumn:I.startColumn+T,endRow:I.endRow,endColumn:I.endColumn+T})}});const h={unitId:n,subUnitId:o,ranges:c},R=le(this._injector,h),C={unitId:n,subUnitId:o,ranges:m},S=ge(this._injector,C);return{preRedos:[{id:G.id,params:h}],redos:[{id:j.id,params:C}],preUndos:[{id:G.id,params:S}],undos:[{id:j.id,params:R}]}}_handleInsertRangeMoveDownCommand(t,n,o){const r=_e(this._univerInstanceService,n);if(!r)return this._handleNull();const a=be(r,o);if(!a)return this._handleNull();const l=t.range,u=a.getMaxRows()-1,d=a.getMergeData(),c=[],m=[];d.forEach(w=>{const{startRow:y,startColumn:b,endColumn:T,endRow:U}=l;if(i.Rectangle.intersects({startRow:y,startColumn:b,endRow:u,endColumn:T},w)&&(c.push(w),i.Rectangle.contains({startRow:y,startColumn:b,endRow:u,endColumn:T},w))){const N=U-y+1;m.push({startRow:w.startRow+N,startColumn:w.startColumn,endRow:w.endRow+N,endColumn:w.endColumn})}});const h={unitId:n,subUnitId:o,ranges:c},R=le(this._injector,h),C={unitId:n,subUnitId:o,ranges:m},S=ge(this._injector,C),I=[{id:G.id,params:h}],v=[{id:j.id,params:C}],M=[{id:G.id,params:S}],p=[{id:j.id,params:R}];return{redos:v,undos:p,preRedos:I,preUndos:M}}_handleDeleteRangeMoveUpCommand(t,n,o){const r=_e(this._univerInstanceService,n);if(!r)return this._handleNull();const a=be(r,o);if(!a)return this._handleNull();const l=t.range,u=a.getMaxRows()-1,d=a.getMergeData(),c=[],m=[];d.forEach(w=>{const{startRow:y,startColumn:b,endColumn:T,endRow:U}=l;if(i.Rectangle.intersects({startRow:y,startColumn:b,endRow:u,endColumn:T},w)&&(c.push(w),i.Rectangle.contains({startRow:y,startColumn:b,endRow:u,endColumn:T},w))){const N=U-y+1,W=i.Rectangle.moveVertical(w,-N);m.push(W)}});const h={unitId:n,subUnitId:o,ranges:c},R=le(this._injector,h),C={unitId:n,subUnitId:o,ranges:m},S=ge(this._injector,C),I=[{id:G.id,params:h}],v=[{id:j.id,params:C}],M=[{id:G.id,params:S}],p=[{id:j.id,params:R}];return{redos:v,undos:p,preRedos:I,preUndos:M}}_handleDeleteRangeMoveLeftCommand(t,n,o){const r=_e(this._univerInstanceService,n);if(!r)return this._handleNull();const a=be(r,o);if(!a)return this._handleNull();const l=t.range,u=a.getMaxColumns()-1,d=a.getMergeData(),c=[],m=[];d.forEach(I=>{const{startRow:v,endRow:M,startColumn:p,endColumn:w}=l;if(i.Rectangle.intersects({startRow:v,startColumn:p,endRow:M,endColumn:u},I)&&(c.push(I),i.Rectangle.contains({startRow:v,startColumn:p,endRow:M,endColumn:u},I))){const T=w-p+1;m.push({startRow:I.startRow,startColumn:I.startColumn-T,endRow:I.endRow,endColumn:I.endColumn-T})}});const h={unitId:n,subUnitId:o,ranges:c},R=le(this._injector,h),C={unitId:n,subUnitId:o,ranges:m},S=ge(this._injector,C);return{preRedos:[{id:G.id,params:h}],redos:[{id:j.id,params:C}],undos:[{id:j.id,params:R}],preUndos:[{id:G.id,params:S}]}}_checkIsMergeCell(t){return!(t.startRow===t.endRow&&t.startColumn===t.endColumn)}_handleNull(){return{redos:[],undos:[]}}_commandExecutedListener(){this.disposeWithMe(this._commandService.onCommandExecuted(t=>{if(xl.includes(t.id)){if(!t.params)return;const n=this._univerInstanceService.getUniverSheetInstance(t.params.unitId);if(!n)return;const o=n.getSheetBySheetId(t.params.subUnitId);if(!o)return;const{sourceRange:r,targetRange:a}=t.params,l=r.startColumn===a.startColumn&&r.endColumn===a.endColumn,u=l?r.endRow-r.startRow+1:r.endColumn-r.startColumn+1,d=l?r.startRow:r.startColumn,c=l?a.startRow:a.startColumn,m=o.getConfig().mergeData,h=[];m.forEach(I=>{let{startRow:v,endRow:M,startColumn:p,endColumn:w,rangeType:y}=I;i.Rectangle.intersects(I,r)||(l?d<v&&c>M?(v-=u,M-=u):d>M&&c<=v&&(v+=u,M+=u):d<p&&c>w?(p-=u,w-=u):d>w&&c<=p&&(p+=u,w+=u)),I.startRow===I.endRow&&I.startColumn===I.endColumn||h.push({startRow:v,endRow:M,startColumn:p,endColumn:w,rangeType:y})}),o.setMergeData(h),this.disposableCollection.dispose();const{unitId:R,subUnitId:C}=t.params,S=I=>this.refRangeHandle(I,R,C);h.forEach(I=>{this.disposableCollection.add(this._refRangeService.registerRefRange(I,S,R,C))})}if(Jl.includes(t.id)){const n=this._univerInstanceService.getUniverSheetInstance(t.params.unitId);if(!n)return;const o=n.getSheetBySheetId(t.params.subUnitId);if(!o)return;const r=o.getConfig().mergeData,a=t.params;if(!a)return;const{range:l}=a,u=t.id.includes("row"),d=t.id.includes("insert"),c=u?l.startRow:l.startColumn,m=u?l.endRow:l.endColumn,h=m-c+1,R=[];r.forEach(v=>{let{startRow:M,endRow:p,startColumn:w,endColumn:y,rangeType:b}=v;d?u?c<=M&&(M+=h,p+=h):c<=w&&(w+=h,y+=h):u?m<M&&(M-=h,p-=h):m<w&&(w-=h,y-=h),v.startRow===v.endRow&&v.startColumn===v.endColumn||R.push({startRow:M,endRow:p,startColumn:w,endColumn:y,rangeType:b})}),o.setMergeData(R),this.disposableCollection.dispose();const{unitId:C,subUnitId:S}=t.params,I=v=>this.refRangeHandle(v,C,S);R.forEach(v=>{this.disposableCollection.add(this._refRangeService.registerRefRange(v,I,C,S))})}}))}},g.MergeCellController=Kl([Mt(0,i.Inject(i.ICommandService)),Mt(1,i.Inject(g.RefRangeService)),Mt(2,i.Inject(i.IUniverInstanceService)),Mt(3,i.Inject(i.Injector)),Mt(4,i.Inject(g.SheetInterceptorService)),Mt(5,i.Inject(g.SheetsSelectionsService))],g.MergeCellController);function _e(s,e){return e?s.getUniverSheetInstance(e):s.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET)}function be(s,e){return e?s.getSheetBySheetId(e):s.getActiveSheet()}function Xl(s,e){return e.some(t=>Zl(s,t))}function Zl(s,e){const{startRow:t,startColumn:n,endColumn:o,endRow:r}=e,a=s.getMatrixWithMergedCells(t,n,r,o);let l=!1;return a.forValue((u,d,c)=>{if(c&&(u!==t||d!==n)&&s.cellHasValue(c))return l=!0,!1}),l}function Ql(s,e,t,n){const o=[],r=[],a=t.getSheetId();return n.forEach(l=>{const u=eu(t,l),d={unitId:e,subUnitId:a,cellValue:u.getData()},c=ce(s,d);o.push({id:F.id,params:c}),r.push({id:F.id,params:d})}),{undos:o,redos:r}}function eu(s,e){const{startRow:t,startColumn:n,endColumn:o,endRow:r}=e,a=s.getMatrixWithMergedCells(t,n,r,o,i.CellModeEnum.Raw),l=new i.ObjectMatrix;return a.forValue((u,d,c)=>{c&&(u!==t||d!==n)&&l.setValue(u,d,null)}),l}const Ft={type:i.CommandType.COMMAND,id:"sheet.command.add-worksheet-merge",handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=e.unitId,a=e.subUnitId,l=e.selections,u=ks(l,e.value),d=o.getUniverSheetInstance(r).getSheetBySheetId(a),c=[],m=[],h=Xl(d,u),R={unitId:r,subUnitId:a,ranges:u},C={unitId:r,subUnitId:a,ranges:u};c.push({id:G.id,params:R}),c.push({id:j.id,params:C});const S=le(s,R),I=ge(s,C);if(m.push({id:G.id,params:I}),m.push({id:j.id,params:S}),h){const M=Ql(s,r,d,u);c.unshift(...M.redos),m.push(...M.undos)}return i.sequenceExecute(c,t).result?(n.pushUndoRedo({unitID:r,undoMutations:m,redoMutations:c}),!0):!1}},tu={type:i.CommandType.COMMAND,id:"sheet.command.add-worksheet-merge-all",handler:async s=>{var d;const e=s.get(i.ICommandService),n=(d=s.get(g.SheetsSelectionsService).getCurrentSelections())==null?void 0:d.map(c=>c.range);if(!(n!=null&&n.length))return!1;const r=s.get(i.IUniverInstanceService).getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET);if(!r)return!1;const a=r.getActiveSheet();if(!a)return!1;const l=r.getUnitId(),u=a.getSheetId();return e.executeCommand(Ft.id,{selections:n,unitId:l,subUnitId:u})}},nu={type:i.CommandType.COMMAND,id:"sheet.command.add-worksheet-merge-vertical",handler:async s=>{var d;const e=s.get(i.ICommandService),n=(d=s.get(g.SheetsSelectionsService).getCurrentSelections())==null?void 0:d.map(c=>c.range);if(!(n!=null&&n.length))return!1;const r=s.get(i.IUniverInstanceService).getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET);if(!r)return!1;const a=r.getActiveSheet();if(!a)return!1;const l=r.getUnitId(),u=a.getSheetId();return e.executeCommand(Ft.id,{value:i.Dimension.COLUMNS,selections:n,unitId:l,subUnitId:u})}},su={type:i.CommandType.COMMAND,id:"sheet.command.add-worksheet-merge-horizontal",handler:async s=>{var d;const e=s.get(i.ICommandService),n=(d=s.get(g.SheetsSelectionsService).getCurrentSelections())==null?void 0:d.map(c=>c.range);if(!(n!=null&&n.length))return!1;const r=s.get(i.IUniverInstanceService).getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET);if(!r)return!1;const a=r.getActiveSheet();if(!a)return!1;const l=r.getUnitId(),u=a.getSheetId();return e.executeCommand(Ft.id,{value:i.Dimension.ROWS,selections:n,unitId:l,subUnitId:u})}};function ou(s,e,t,n,o){const r=s.get(i.IUniverInstanceService),a=P(r,{unitId:e,subUnitId:t});if(!a)return;const{worksheet:l}=a;if(l.getMergeData().some(m=>n.some(h=>i.Rectangle.intersects(h,m))))throw new Error("The ranges to be merged overlap with the existing merged cells");s.get(i.ICommandService).executeCommand(Ft.id,{unitId:e,subUnitId:t,selections:n,defaultMerge:o})}class ke{constructor(){f(this,"_model",new Map);f(this,"_ruleChange",new O.Subject);f(this,"_ruleRefresh",new O.Subject);f(this,"_resetOrder",new O.Subject);f(this,"ruleChange$",this._ruleChange.asObservable());f(this,"ruleRefresh$",this._ruleRefresh.asObservable());f(this,"resetOrder$",this._resetOrder.asObservable());f(this,"_worksheetRuleInitStateChange",new O.BehaviorSubject(!1));f(this,"worksheetRuleInitStateChange$",this._worksheetRuleInitStateChange.asObservable())}changeRuleInitState(e){this._worksheetRuleInitStateChange.next(e)}getSheetRuleInitState(){return this._worksheetRuleInitStateChange.value}addRule(e,t){this._ensureSubUnitMap(e).set(t.subUnitId,t),this._ruleChange.next({unitId:e,rule:t,type:"add",subUnitId:t.subUnitId})}deleteRule(e,t){var o,r,a;const n=(r=(o=this._model)==null?void 0:o.get(e))==null?void 0:r.get(t);n&&((a=this._model.get(e))==null||a.delete(t),this._ruleChange.next({unitId:e,rule:n,type:"delete",subUnitId:t}))}setRule(e,t,n){var r,a;const o=this.getRule(e,t);o&&((a=(r=this._model)==null?void 0:r.get(e))==null||a.set(t,n),this._ruleChange.next({unitId:e,oldRule:o,rule:n,type:"set",subUnitId:t}))}getRule(e,t){var n,o;return(o=(n=this._model)==null?void 0:n.get(e))==null?void 0:o.get(t)}toObject(){const e={};return[...this._model.keys()].forEach(n=>{const o=this._model.get(n);o!=null&&o.size&&(e[n]=[],[...o.keys()].forEach(a=>{const l=o.get(a);l&&e[n].push(l)}))}),e}fromObject(e){const t=new Map;Object.keys(e).forEach(n=>{const o=e[n];if(o!=null&&o.length){const r=new Map;o.forEach(a=>{r.set(a.subUnitId,a)}),t.set(n,r)}}),this._model=t}deleteUnitModel(e){this._model.delete(e)}_ensureSubUnitMap(e){let t=this._model.get(e);return t||(t=new Map,this._model.set(e,t)),t}ruleRefresh(e){this._ruleRefresh.next(e)}resetOrder(){this._resetOrder.next(Math.random())}getTargetByPermissionId(e,t){const n=this._model.get(e);if(!n)return null;for(const[o,r]of n)if(r.permissionId===t)return[e,o]}}const Fe={id:"sheet.mutation.add-worksheet-protection",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=s.get(ke),{unitId:n,rule:o}=e;return t.addRule(n,o),!0}},tt={id:"sheet.mutation.delete-worksheet-protection",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=s.get(ke),{unitId:n,subUnitId:o}=e;return t.deleteRule(n,o),!0}},br={type:i.CommandType.COMMAND,id:"sheet.command.add-worksheet-protection",async handler(s,e){if(!e)return!1;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),{rule:o,unitId:r}=e,a=o.subUnitId;if(await t.executeCommand(Fe.id,{unitId:r,rule:o,subUnitId:o.subUnitId})){const u=[{id:Fe.id,params:{unitId:r,rule:o,subUnitId:o.subUnitId}}],d=[{id:tt.id,params:{unitId:r,subUnitId:a}}];n.pushUndoRedo({unitID:r,redoMutations:u,undoMutations:d})}return!0}},Er={type:i.CommandType.COMMAND,id:"sheet.command.set-worksheet-range-theme-style",handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),{unitId:o}=e,r=io(s,e);return t.syncExecuteCommand(rt.id,e)?(n.pushUndoRedo({unitID:o,undoMutations:[{id:it.id,params:r}],redoMutations:[{id:rt.id,params:e}]}),!0):!1}},Tr={type:i.CommandType.COMMAND,id:"sheet.command.append-row",handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),{unitId:o,subUnitId:r,cellValue:a,insertRowNums:l,insertColumnNums:u,maxRows:d,maxColumns:c}=e,m={unitId:o,subUnitId:r,cellValue:a},h=ce(s,m),R=[{id:F.id,params:m}],C=[{id:F.id,params:h}];if(l){const I={unitId:o,subUnitId:r,range:{startRow:d,endRow:d,startColumn:0,endColumn:c-1}},v=en(s,I);R.unshift({id:re.id,params:I}),C.push({id:ae.id,params:v})}if(u){const I={unitId:o,subUnitId:r,range:{startRow:0,endRow:d-1,startColumn:c,endColumn:c-1+u}},v=Nt(s,I);R.unshift({id:ie.id,params:I}),C.push({id:ne.id,params:v})}return i.sequenceExecute(R,t).result?(n.pushUndoRedo({unitID:o,undoMutations:C,redoMutations:R}),!0):!1}},fn={id:"sheet.command.clear-selection-content",type:i.CommandType.COMMAND,handler:(s,e)=>{var p;const t=s.get(i.IUniverInstanceService),n=s.get(i.ICommandService),o=s.get(g.SheetsSelectionsService),r=s.get(i.IUndoRedoService),a=s.get(g.SheetInterceptorService),l=t.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET);if(!l)return!1;const u=(e==null?void 0:e.unitId)||l.getUnitId(),d=l.getActiveSheet();if(!d)return!1;const c=(e==null?void 0:e.subUnitId)||d.getSheetId(),m=(e==null?void 0:e.ranges)||((p=o.getCurrentSelections())==null?void 0:p.map(w=>w.range));if(!(m!=null&&m.length))return!1;const h=Dt(m,s,u,c),R={subUnitId:c,unitId:u,cellValue:Uo(h)},C=ce(s,R),S=a.onCommandExecute({id:fn.id}),I=[{id:F.id,params:R},...S.redos],v=[...S.undos,{id:F.id,params:C}];return i.sequenceExecute(I,n).result?(r.pushUndoRedo({unitID:u,undoMutations:v,redoMutations:I}),!0):!1}},Ns=(s,e)=>({subUnitId:e.sheet.id,unitId:e.unitId,subUnitName:e.sheet.name}),yt={id:"sheet.mutation.insert-sheet",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=s.get(i.IUniverInstanceService),{sheet:n,index:o,unitId:r,styles:a}=e,l=t.getUniverSheetInstance(r);return l?(a&&l.addStyles(a),l.addWorksheet(n.id,o,n)):!1}},Os={type:i.CommandType.COMMAND,id:"sheet.command.copy-sheet",handler:(s,e)=>{var w,y;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=s.get(g.SheetInterceptorService),a=s.get(i.LocaleService),l=P(o,e);if(!l)return!1;const{workbook:u,worksheet:d,unitId:c,subUnitId:m}=l,h=i.Tools.deepClone(d.getConfig());h.name=ru(u,a,h.name),h.id=i.generateRandomId();const C={index:u.getSheetIndex(d)+1,sheet:h,unitId:c},S=Ns(s,C),I=r.onCommandExecute({id:Os.id,params:{unitId:c,subUnitId:m,targetSubUnitId:h.id}}),v=[...(w=I.preRedos)!=null?w:[],{id:yt.id,params:C},...I.redos],M=[...(y=I.preUndos)!=null?y:[],{id:Xe.id,params:S},...I.undos];return i.sequenceExecute(v,t).result?(n.pushUndoRedo({unitID:c,undoMutations:M,redoMutations:v}),!0):!1}};function ru(s,e,t){let n=`${t} ${e.t("sheets.tabs.sheetCopy","")}`,o=2;for(;s.checkSheetName(n);)n=`${t} ${e.t("sheets.tabs.sheetCopy",`${o}`)}`,o++;return n}const Ur={type:i.CommandType.COMMAND,id:"sheet.command.delete-range-protection",async handler(s,e){if(!e)return!1;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),{unitId:o,subUnitId:r,rule:a}=e,l={unitId:o,subUnitId:r,ruleIds:[a.id]};return await t.executeCommand(Te.id,l)&&n.pushUndoRedo({unitID:o,redoMutations:[{id:Te.id,params:l}],undoMutations:[{id:Ce.id,params:{unitId:o,subUnitId:r,rules:[a]}}]}),!0}},Pr={type:i.CommandType.COMMAND,id:"sheet.command.delete-worksheet-protection",handler(s,e){if(!e)return!1;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),{rule:o,unitId:r,subUnitId:a}=e;t.executeCommand(tt.id,{unitId:r,subUnitId:a});const l=[{id:tt.id,params:{unitId:r,subUnitId:a}}],u=[{id:Fe.id,params:{unitId:r,rule:o,subUnitId:a}}];return n.pushUndoRedo({unitID:r,redoMutations:l,undoMutations:u}),!0}},kr={type:i.CommandType.COMMAND,id:"sheet.command.remove-worksheet-range-theme-style",handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),{unitId:o}=e,r=ao(s,e);return t.syncExecuteCommand(it.id,e)?(n.pushUndoRedo({unitID:o,undoMutations:[{id:rt.id,params:r}],redoMutations:[{id:it.id,params:e}]}),!0):!1}},Nr={id:"sheet.command.insert-defined-name",type:i.CommandType.COMMAND,handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService);if(!e)return!1;const o={...e};return t.syncExecuteCommand(J.SetDefinedNameMutation.id,o)?(n.pushUndoRedo({unitID:e.unitId,undoMutations:[{id:J.RemoveDefinedNameMutation.id,params:o}],redoMutations:[{id:J.SetDefinedNameMutation.id,params:o}]}),!0):!1}},Or={id:"sheet.command.insert-sheet",type:i.CommandType.COMMAND,handler:(s,e)=>{var I;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=s.get(i.LocaleService),a=Bn(o,{unitId:e==null?void 0:e.unitId});if(!a)return!1;const{unitId:l,workbook:u}=a;let d=u.getSheets().length;const c=e==null?void 0:e.sheet,m=c==null?void 0:c.id,h=i.mergeWorksheetSnapshotWithDefault(c||{});e?(d=(I=e.index)!=null?I:d,h.id=m||i.generateRandomId(),h.name=(c==null?void 0:c.name)||u.generateNewSheetName(`${r.t("sheets.tabs.sheet")}`)):(h.id=i.generateRandomId(),h.name=u.generateNewSheetName(`${r.t("sheets.tabs.sheet")}`));const R={index:d,sheet:h,unitId:l},C=Ns(s,R);return t.syncExecuteCommand(yt.id,R)?(n.pushUndoRedo({unitID:l,undoMutations:[{id:Xe.id,params:C}],redoMutations:[{id:yt.id,params:R}]}),!0):!1}},_t={id:"sheet.mutation.register-worksheet-range-theme-style",type:i.CommandType.MUTATION,handler:(s,e)=>{const{unitId:t,rangeThemeStyleJson:n,themeName:o}=e,r=s.get(i.IUniverInstanceService),a=P(r),l=s.get(g.SheetRangeThemeModel);if(!a)return!1;const u=new We(o,n);return l.registerRangeThemeStyle(t,u),!0}},In={id:"sheet.mutation.unregister-worksheet-range-theme-style",type:i.CommandType.MUTATION,handler:(s,e)=>{const{unitId:t,themeName:n}=e,o=s.get(i.IUniverInstanceService),r=P(o),a=s.get(g.SheetRangeThemeModel);return r?(a.unregisterRangeThemeStyle(t,n),!0):!1}},Dr={id:"sheet.command.register-worksheet-range-theme-style",type:i.CommandType.COMMAND,handler:(s,e)=>{if(!e)return!1;const{unitId:t,rangeThemeStyle:n}=e,o=s.get(i.IUniverInstanceService),r=s.get(i.ICommandService),a=s.get(i.IUndoRedoService);if(!P(o))return!1;const u={unitId:t,themeName:n.getName(),rangeThemeStyleJson:n.toJson()},d={unitId:t,themeName:n.getName()};return r.syncExecuteCommand(_t.id,u)&&a.pushUndoRedo({unitID:t,undoMutations:[{id:In.id,params:d}],redoMutations:[{id:_t.id,params:u}]}),!0}},Ds={id:"sheet.command.remove-defined-name",type:i.CommandType.COMMAND,handler:(s,e)=>{var c,m;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(g.SheetInterceptorService);if(!e)return!1;const r={...e},a=o.onCommandExecute({id:Ds.id,params:e}),l=[...(c=a.preRedos)!=null?c:[],{id:J.RemoveDefinedNameMutation.id,params:r},...a.redos],u=[...(m=a.preUndos)!=null?m:[],{id:J.SetDefinedNameMutation.id,params:r},...a.undos];return i.sequenceExecute(l,t)?(n.pushUndoRedo({unitID:e.unitId,undoMutations:u.filter(Boolean),redoMutations:l.filter(Boolean)}),!0):!1}},vn={id:"sheet.command.remove-sheet",type:i.CommandType.COMMAND,handler:(s,e)=>{var v,M;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=s.get(g.SheetInterceptorService),a=P(o,e);if(!a)return!1;const{unitId:l,subUnitId:u,workbook:d,worksheet:c}=a;if(d.getSheets().length<=1)return!1;const m={subUnitId:u,unitId:l,subUnitName:c.getName()},h=rr(s,m),R=r.onCommandExecute({id:vn.id,params:{unitId:l,subUnitId:u}}),C=[...(v=R.preRedos)!=null?v:[],{id:Xe.id,params:m},...R.redos],S=[...(M=R.preUndos)!=null?M:[],{id:yt.id,params:h},...R.undos];return i.sequenceExecute(C,t).result?(n.pushUndoRedo({unitID:l,undoMutations:S,redoMutations:C}),!0):!1}},Ar={type:i.CommandType.COMMAND,id:"sheet.command.remove-worksheet-merge",handler:(s,e)=>{var N;const t=s.get(g.SheetsSelectionsService),n=s.get(i.ICommandService),o=s.get(i.IUndoRedoService),r=s.get(i.IUniverInstanceService),a=(e==null?void 0:e.ranges)||((N=t.getCurrentSelections())==null?void 0:N.map(W=>W.range));if(!(a!=null&&a.length))return!1;const l=P(r);if(!l)return!1;const{subUnitId:u,unitId:d,worksheet:c}=l,m={unitId:d,subUnitId:u,ranges:a},R=c.getConfig().mergeData.filter(W=>a.some(V=>i.Rectangle.intersects(V,W)));if(!R.length)return!1;const C=le(s,m),S=t.getCurrentSelections();if(!(S!=null&&S.length))return!1;const I=i.Tools.deepClone(S),v=i.Tools.deepClone(S),M=v[v.length-1],{startRow:p,startColumn:w}=M.range;M.primary={startRow:p,startColumn:w,endRow:p,endColumn:w,actualRow:p,actualColumn:w,isMerged:!1,isMergedMainCell:!1};const y=iu(c,R),b={unitId:d,subUnitId:u,cellValue:y.redoParams.getMatrix()},T={unitId:d,subUnitId:u,cellValue:y.undoParams.getMatrix()},U=[{id:G.id,params:C},{id:F.id,params:b},{id:q.id,params:{selections:v}}],k=[{id:j.id,params:C},{id:F.id,params:T},{id:q.id,params:{selections:I}}];return i.sequenceExecute(U,n)?(o.pushUndoRedo({unitID:d,undoMutations:k,redoMutations:U}),!0):!1}};function iu(s,e){const t=new i.ObjectMatrix,n=new i.ObjectMatrix;return e.forEach(o=>{const{startRow:r,startColumn:a,endColumn:l,endRow:u}=o,d=s.getCellMatrix().getValue(r,a);if(d!=null&&d.s)for(let c=r;c<=u;c++)for(let m=a;m<=l;m++)(c!==r||m!==a)&&(t.setValue(c,m,{s:d.s}),n.setValue(c,m,null))}),{redoParams:t,undoParams:n}}class nt{constructor(){f(this,"_borderInfo",{type:i.BorderType.ALL,color:"#000000",style:i.BorderStyleTypes.THIN,activeBorderType:!1});f(this,"_borderInfo$",new O.BehaviorSubject(this._borderInfo));f(this,"borderInfo$",this._borderInfo$.asObservable())}dispose(){this._borderInfo$.complete()}setType(e){this._borderInfo.type=e,this.setActiveBorderType(!0),this._refresh()}setColor(e){this._borderInfo.color=e,this._refresh()}setStyle(e){this._borderInfo.style=e,this._refresh()}setActiveBorderType(e){this._borderInfo.activeBorderType=e}getBorderInfo(){return this._borderInfo}_refresh(){this._borderInfo$.next(this._borderInfo)}}function pn(s,e){const{startRow:t,startColumn:n,endRow:o,endColumn:r}=s;for(let a=t;a<=o;a++)for(let l=n;l<=r;l++)e(a,l)}const As=(s,e,t,n)=>{const{mr:o,worksheet:r}=s;e.startRow<0||e.startColumn<0||pn(e,(a,l)=>{var c,m;const u=r.getMergedCell(a,l);let d=t;if(u&&(t.bc_tr||t.ml_tr||t.bl_tr||t.tl_mr||t.tl_bc||t.tl_br)){if(n){const h=i.Tools.deepClone((c=o.getValue(u.startRow,u.startColumn))==null?void 0:c.s);d=h!=null&&h.bd?Object.assign(h.bd,t):t}o.setValue(u.startRow,u.startColumn,{s:{bd:d}})}else{if(n){const h=i.Tools.deepClone((m=o.getValue(a,l))==null?void 0:m.s);d=h!=null&&h.bd?Object.assign(h.bd,t):t}o.setValue(a,l,{s:{bd:d}})}})},au=s=>{const e={startRow:s.startRow-1,startColumn:s.startColumn,endRow:s.startRow-1,endColumn:s.endColumn},t={startRow:s.startRow,startColumn:s.startColumn-1,endRow:s.endRow,endColumn:s.startColumn-1},n={startRow:s.endRow+1,startColumn:s.startColumn,endRow:s.endRow+1,endColumn:s.endColumn},o={startRow:s.startRow,startColumn:s.endColumn+1,endRow:s.endRow,endColumn:s.endColumn+1},r={startRow:s.startRow,startColumn:s.startColumn,endRow:s.startRow,endColumn:s.endColumn},a={startRow:s.startRow,startColumn:s.startColumn,endRow:s.endRow,endColumn:s.startColumn},l={startRow:s.endRow,startColumn:s.startColumn,endRow:s.endRow,endColumn:s.endColumn},u={startRow:s.startRow,startColumn:s.endColumn,endRow:s.endRow,endColumn:s.endColumn};return{topRangeOut:e,leftRangeOut:t,bottomRangeOut:n,rightRangeOut:o,topRange:r,leftRange:a,bottomRange:l,rightRange:u}};function lu(s,e,t){const{style:n,color:o,type:r}=s.getBorderInfo(),a=r===i.BorderType.TOP||r===i.BorderType.ALL||r===i.BorderType.OUTSIDE,l=r===i.BorderType.LEFT||r===i.BorderType.ALL||r===i.BorderType.OUTSIDE,u=r===i.BorderType.BOTTOM||r===i.BorderType.ALL||r===i.BorderType.OUTSIDE,d=r===i.BorderType.RIGHT||r===i.BorderType.ALL||r===i.BorderType.OUTSIDE,c=r===i.BorderType.VERTICAL||r===i.BorderType.ALL||r===i.BorderType.INSIDE,m=r===i.BorderType.HORIZONTAL||r===i.BorderType.ALL||r===i.BorderType.INSIDE,h=r.indexOf("tlbr")>-1,R=r.indexOf("tlbc")>-1,C=r.indexOf("tlmr")>-1,S=r.indexOf("bltr")>-1,I=r.indexOf("mltr")>-1,v=r.indexOf("bctr")>-1,M=t[0],{topRangeOut:p,leftRangeOut:w,bottomRangeOut:y,rightRangeOut:b,topRange:T,leftRange:U,bottomRange:k,rightRange:E}=au(M),N=new i.ObjectMatrix,{worksheet:W,unitId:V,subUnitId:$}=e;return{worksheet:W,unitId:V,subUnitId:$,style:n,color:o,type:r,top:a,left:l,right:d,bottom:u,vertical:c,horizontal:m,tl_br:h,tl_bc:R,tl_mr:C,bl_tr:S,ml_tr:I,bc_tr:v,topRangeOut:p,leftRangeOut:w,bottomRangeOut:y,rightRangeOut:b,topRange:T,leftRange:U,bottomRange:k,rightRange:E,range:M,mr:N,borderStyle:{s:n,cl:{rgb:o}}}}const uu=s=>{const{range:e,mr:t,borderStyle:n,vertical:o,horizontal:r,worksheet:a}=s;o&&pn(e,(l,u)=>{var c,m,h;const d=a.getMergedCell(l,u);if(d){const R=(c=t.getValue(d.startRow,d.startColumn))==null?void 0:c.s;d.startColumn!==e.startColumn&&t.setValue(l,u,{s:{bd:R!=null&&R.bd?Object.assign(R.bd,{l:i.Tools.deepClone(n)}):{l:i.Tools.deepClone(n)}}})}else{if(u!==e.endColumn){const R=(m=t.getValue(l,u))==null?void 0:m.s;t.setValue(l,u,{s:{bd:R!=null&&R.bd?Object.assign(R.bd,{r:i.Tools.deepClone(n)}):{r:i.Tools.deepClone(n)}}})}if(u!==e.startColumn){const R=(h=t.getValue(l,u))==null?void 0:h.s;t.setValue(l,u,{s:{bd:R!=null&&R.bd?Object.assign(R.bd,{l:i.Tools.deepClone(n)}):{l:i.Tools.deepClone(n)}}})}}}),r&&pn(e,(l,u)=>{var c,m,h;const d=a.getMergedCell(l,u);if(d){const R=(c=t.getValue(d.startRow,d.startColumn))==null?void 0:c.s;d.startRow!==e.startRow&&t.setValue(l,u,{s:{bd:R!=null&&R.bd?Object.assign(R.bd,{t:i.Tools.deepClone(n)}):{t:i.Tools.deepClone(n)}}})}else{if(l!==e.endRow){const R=(m=t.getValue(l,u))==null?void 0:m.s;t.setValue(l,u,{s:{bd:R!=null&&R.bd?Object.assign(R.bd,{b:i.Tools.deepClone(n)}):{b:i.Tools.deepClone(n)}}})}if(l!==e.startRow){const R=(h=t.getValue(l,u))==null?void 0:h.s;t.setValue(l,u,{s:{bd:R!=null&&R.bd?Object.assign(R.bd,{t:i.Tools.deepClone(n)}):{t:i.Tools.deepClone(n)}}})}}})};function du(s){const{borderStyle:e,tl_br:t,tl_bc:n,tl_mr:o,bl_tr:r,ml_tr:a,bc_tr:l}=s,u=(d,c,m)=>{As(s,d,c,m)};t&&u(s.range,{tl_br:i.Tools.deepClone(e)},!0),n&&u(s.range,{tl_bc:i.Tools.deepClone(e)},!0),o&&u(s.range,{tl_mr:i.Tools.deepClone(e)},!0),r&&u(s.range,{bl_tr:i.Tools.deepClone(e)},!0),a&&u(s.range,{ml_tr:i.Tools.deepClone(e)},!0),l&&u(s.range,{bc_tr:i.Tools.deepClone(e)},!0)}const cu=s=>{const{top:e,left:t,right:n,bottom:o,borderStyle:r,bottomRange:a,topRange:l,leftRange:u,rightRange:d,bottomRangeOut:c,topRangeOut:m,leftRangeOut:h,rightRangeOut:R}=s,C=(S,I,v)=>{As(s,S,I,v)};e&&(C(m,{b:null}),C(l,{t:i.Tools.deepClone(r)},!0)),o&&(C(c,{t:null}),C(a,{b:i.Tools.deepClone(r)},!0)),t&&(C(h,{r:null}),C(u,{l:i.Tools.deepClone(r)},!0)),n&&(C(R,{l:null}),C(d,{r:i.Tools.deepClone(r)},!0))},mu=s=>{const{range:e,worksheet:t,mr:n,top:o,bottom:r,left:a,right:l,vertical:u,horizontal:d,tl_br:c,tl_bc:m,tl_mr:h,bl_tr:R,ml_tr:C,bc_tr:S,topRange:I,bottomRange:v,leftRange:M,rightRange:p,topRangeOut:w,bottomRangeOut:y,leftRangeOut:b,rightRangeOut:T}=s,U=(k,E,N)=>{As(s,k,E,N)};!o&&!r&&!a&&!l&&!u&&!d&&!c&&!m&&!h&&!R&&!C&&!S&&(pn(e,(k,E)=>{var W,V,$,L,Y,z,K,oe;const N=t.getMergedCell(k,E);if(N){if(N.endColumn!==e.endColumn){const H=(W=n.getValue(N.startRow,N.startColumn))==null?void 0:W.s;n.setValue(k,E,{s:{bd:H!=null&&H.bd?Object.assign(H.bd,{r:null}):{r:null}}})}if(N.startColumn!==e.startColumn){const H=(V=n.getValue(N.startRow,N.startColumn))==null?void 0:V.s;n.setValue(k,E,{s:{bd:H!=null&&H.bd?Object.assign(H.bd,{l:null}):{l:null}}})}if(N.endRow!==e.endRow){const H=($=n.getValue(N.startRow,N.startColumn))==null?void 0:$.s;n.setValue(k,E,{s:{bd:H!=null&&H.bd?Object.assign(H.bd,{b:null}):{b:null}}})}if(N.startRow!==e.startRow){const H=(L=n.getValue(N.startRow,N.startColumn))==null?void 0:L.s;n.setValue(k,E,{s:{bd:H!=null&&H.bd?Object.assign(H.bd,{t:null}):{t:null}}})}}else{if(E!==e.endColumn){const H=(Y=n.getValue(k,E))==null?void 0:Y.s;n.setValue(k,E,{s:{bd:H!=null&&H.bd?Object.assign(H.bd,{r:null}):{r:null}}})}if(E!==e.startColumn){const H=(z=n.getValue(k,E))==null?void 0:z.s;n.setValue(k,E,{s:{bd:H!=null&&H.bd?Object.assign(H.bd,{l:null}):{l:null}}})}if(k!==e.endRow){const H=(K=n.getValue(k,E))==null?void 0:K.s;n.setValue(k,E,{s:{bd:H!=null&&H.bd?Object.assign(H.bd,{b:null}):{b:null}}})}if(k!==e.startRow){const H=(oe=n.getValue(k,E))==null?void 0:oe.s;n.setValue(k,E,{s:{bd:H!=null&&H.bd?Object.assign(H.bd,{t:null}):{t:null}}})}}}),U(w,{b:null}),U(I,{t:null},!0),U(y,{t:null}),U(v,{b:null},!0),U(b,{r:null}),U(M,{l:null},!0),U(T,{l:null}),U(p,{r:null},!0),U(e,{tl_br:null},!0),U(e,{tl_bc:null},!0),U(e,{tl_mr:null},!0),U(e,{bl_tr:null},!0),U(e,{ml_tr:null},!0),U(e,{bc_tr:null},!0))},bt={id:"sheet.command.set-border",type:i.CommandType.COMMAND,handler:(s,e)=>{var v;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=s.get(g.SheetsSelectionsService),a=s.get(nt),l=P(o,e);if(!l)return!1;const u=(e==null?void 0:e.ranges)||((v=r.getCurrentSelections())==null?void 0:v.map(M=>M.range));if(!(u!=null&&u.length))return!1;const{activeBorderType:d}=a.getBorderInfo();if(!d)return!1;const c=lu(a,l,u);uu(c),cu(c),du(c),mu(c);const{unitId:m,subUnitId:h,mr:R}=c,C={unitId:m,subUnitId:h,cellValue:R.getData()},S=ce(s,C);return t.syncExecuteCommand(F.id,C)?(n.pushUndoRedo({unitID:m,undoMutations:[{id:F.id,params:S}],redoMutations:[{id:F.id,params:C}]}),!0):!1}},Wr={id:"sheet.command.set-border-position",type:i.CommandType.COMMAND,handler:(s,e)=>{if(!e.value)return!1;const t=s.get(i.ICommandService);return s.get(nt).setType(e.value),t.syncExecuteCommand(bt.id)}},Vr={id:"sheet.command.set-border-style",type:i.CommandType.COMMAND,handler:(s,e)=>{const t=s.get(i.ICommandService);return s.get(nt).setStyle(e.value),t.syncExecuteCommand(bt.id)}},$r={id:"sheet.command.set-border-color",type:i.CommandType.COMMAND,handler:(s,e)=>{const t=s.get(i.ICommandService);return s.get(nt).setColor(e.value),t.syncExecuteCommand(bt.id)}},Lr={id:"sheet.command.set-border-basic",type:i.CommandType.COMMAND,handler:(s,e)=>{const{unitId:t,subUnitId:n,value:o,ranges:r}=e,{type:a,color:l,style:u}=o,d=s.get(i.ICommandService),c=s.get(nt);return c.setType(a),l&&c.setColor(l),c.setStyle(u),d.syncExecuteCommand(bt.id,{unitId:t,subUnitId:n,ranges:r})}},Br={type:i.CommandType.COMMAND,id:"sheet.command.set-col-data",handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=P(o,e);if(!r)return!1;const{columnData:a}=e,{unitId:l,subUnitId:u,worksheet:d}=r,c={subUnitId:u,unitId:l,columnData:a},m=mo(c,d);return t.syncExecuteCommand(at.id,c)?(n.pushUndoRedo({unitID:l,undoMutations:[{id:at.id,params:m}],redoMutations:[{id:at.id,params:c}]}),!0):!1}},Et={type:i.CommandType.COMMAND,id:"sheet.command.set-col-visible-on-cols",handler:(s,e)=>{var v,M;const{unitId:t,subUnitId:n,ranges:o}=e,r=s.get(g.SheetInterceptorService),a=s.get(i.ICommandService),l=s.get(i.IUniverInstanceService),u=P(l,{unitId:t,subUnitId:n});if(!u)return!1;const{worksheet:d}=u,c={unitId:t,subUnitId:n,ranges:o},m={unitId:t,subUnitId:n,reveal:!0,selections:o.map(p=>({range:p,primary:se(p,d),style:null}))},h=ga(s,c),R={unitId:t,subUnitId:n,selections:Hr(o).map(p=>({range:p,primary:se(p,d),style:null}))},C=i.sequenceExecute([{id:ut.id,params:c},{id:q.id,params:m}],a),S=r.onCommandExecute({id:Et.id,params:e}),I=i.sequenceExecute([...S.redos],a);if(C.result&&I.result){const p=r.afterCommandExecute({id:Et.id,params:e});return i.sequenceExecute(p.redos,a),s.get(i.IUndoRedoService).pushUndoRedo({unitID:t,undoMutations:[{id:lt.id,params:h},{id:q.id,params:R},...(v=S.undos)!=null?v:[],...p.undos],redoMutations:[...(M=S.preRedos)!=null?M:[],{id:ut.id,params:c},{id:q.id,params:m},...S.redos,...p.redos]}),!0}return!0}},Ws={type:i.CommandType.COMMAND,id:"sheet.command.set-selected-cols-visible",handler:s=>{var d;const e=s.get(g.SheetsSelectionsService),t=s.get(i.ICommandService),n=(d=e.getCurrentSelections())==null?void 0:d.map(c=>c.range).filter(c=>c.rangeType===i.RANGE_TYPE.COLUMN);if(!(n!=null&&n.length))return!1;const o=P(s.get(i.IUniverInstanceService));if(!o)return!1;const{worksheet:r,unitId:a,subUnitId:l}=o,u=n.map(c=>r.getHiddenCols(c.startColumn,c.endColumn)).flat();return t.executeCommand(Et.id,{unitId:a,subUnitId:l,ranges:u})}},wn={type:i.CommandType.COMMAND,id:"sheet.command.set-col-hidden",handler:(s,e)=>{var M,p,w,y;const t=s.get(g.SheetsSelectionsService),n=s.get(g.SheetInterceptorService),o=s.get(i.IUniverInstanceService),r=s.get(i.ICommandService);let a=(M=e==null?void 0:e.ranges)!=null&&M.length?e.ranges:(p=t.getCurrentSelections())==null?void 0:p.map(b=>b.range).filter(b=>b.rangeType===i.RANGE_TYPE.COLUMN);if(!(a!=null&&a.length))return!1;const l=P(o,e);if(!l)return!1;const{worksheet:u,unitId:d,subUnitId:c}=l;a=hu(l.worksheet,a);const m={unitId:d,subUnitId:c,ranges:a},h={unitId:d,subUnitId:c,selections:Hr(a).map(b=>({range:b,primary:se(b,u),style:null}))},R=ha(s,m),C={unitId:d,subUnitId:c,reveal:!0,selections:a.map(b=>({range:b,primary:se(b,u),style:null}))},S=i.sequenceExecute([{id:lt.id,params:m},{id:q.id,params:h}],r),I=n.onCommandExecute({id:wn.id,params:m}),v=i.sequenceExecute([...I.redos],r);if(S.result&&v.result){const b=n.afterCommandExecute({id:wn.id,params:m});return i.sequenceExecute(b.redos,r),s.get(i.IUndoRedoService).pushUndoRedo({unitID:d,undoMutations:[{id:ut.id,params:R},{id:q.id,params:C},...(w=I.undos)!=null?w:[],...b.undos],redoMutations:[...(y=I.preRedos)!=null?y:[],{id:lt.id,params:m},{id:q.id,params:h},...I.redos,...b.redos]}),!0}return!1}};function hu(s,e){const t=s.getRowCount()-1,n=s.getHiddenCols(),o=[];return e.forEach(r=>{const a=n.filter(l=>l.startColumn>=r.startColumn&&l.endColumn<=r.endColumn);if(a.length){let l=r.startColumn;a.forEach(u=>{u.startColumn>l&&(o.push({startColumn:l,endColumn:u.startColumn-1,startRow:0,endRow:t}),l=u.endColumn+1)}),l<=r.endColumn&&o.push({startColumn:l,endColumn:r.endColumn,startRow:0,endRow:t})}else o.push(r)}),o}function Hr(s){return gu(s).map(t=>{const n=t.startColumn===0?t.endColumn+1:t.startColumn-1;return{...t,startColumn:n,endColumn:n}})}function gu(s){const e=[];let t;return s.sort((n,o)=>n.startColumn-o.startColumn).forEach(n=>{if(!t){t=n;return}t.endColumn===n.startColumn-1?t.endColumn=n.endColumn:(e.push(t),t=n)}),e.push(t),e}const Vs={id:"sheet.command.set-defined-name",type:i.CommandType.COMMAND,handler:(s,e)=>{var m,h;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(g.SheetInterceptorService);if(!e)return!1;const r={...e},a=J.SetDefinedNameMutationFactory(s,e),l=o.onCommandExecute({id:Vs.id,params:e}),u=[...(m=l.preRedos)!=null?m:[],{id:J.RemoveDefinedNameMutation.id,params:a},{id:J.SetDefinedNameMutation.id,params:r},...l.redos],d=[...(h=l.preUndos)!=null?h:[],{id:J.RemoveDefinedNameMutation.id,params:r},{id:J.SetDefinedNameMutation.id,params:a},...l.undos];return i.sequenceExecute(u,t)?(n.pushUndoRedo({unitID:e.unitId,undoMutations:d.filter(Boolean),redoMutations:u.filter(Boolean)}),!0):!1}},$s=(s,e)=>{const n=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(n==null)throw new Error("universheet is null error!");const o=n.getSheetBySheetId(e.subUnitId);if(o==null)throw new Error("worksheet is null error!");const a=o.getConfig().freeze;return{unitId:e.unitId,subUnitId:e.subUnitId,...a}},Ne={id:"sheet.mutation.set-frozen",type:i.CommandType.MUTATION,handler:(s,e)=>{const n=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(n==null)throw new Error("universheet is null error!");const o=n.getSheetBySheetId(e.subUnitId);if(!o)return!1;const r=o.getConfig(),{startRow:a,startColumn:l,ySplit:u,xSplit:d}=e;return r.freeze={startRow:a,startColumn:l,ySplit:u,xSplit:d},!0}},Fr={type:i.CommandType.COMMAND,id:"sheet.command.set-frozen",handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=P(o,{unitId:e.unitId,subUnitId:e.subUnitId});if(!r)return!1;const{unitId:a,subUnitId:l,worksheet:u}=r,{startColumn:d,startRow:c,xSplit:m,ySplit:h}=e;if(c>=u.getRowCount()||d>=u.getColumnCount()||m>=u.getColumnCount()||h>=u.getRowCount())return!1;const R={unitId:a,subUnitId:l,...e},C=$s(s,R);return t.syncExecuteCommand(Ne.id,R)?(n.pushUndoRedo({unitID:a,undoMutations:[{id:Ne.id,params:C}],redoMutations:[{id:Ne.id,params:R}]}),!0):!1}},jr={type:i.CommandType.COMMAND,id:"sheet.command.cancel-frozen",handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUniverInstanceService),o=s.get(i.IUndoRedoService),r=P(n,{unitId:e==null?void 0:e.unitId,subUnitId:e==null?void 0:e.subUnitId});if(!r)return!1;const{unitId:a,subUnitId:l}=r,u={unitId:a,subUnitId:l,startRow:-1,startColumn:-1,xSplit:0,ySplit:0},d=$s(s,u);return t.syncExecuteCommand(Ne.id,u)&&o.pushUndoRedo({unitID:a,undoMutations:[{id:Ne.id,params:d}],redoMutations:[{id:Ne.id,params:u}]}),!0}},Gr={type:i.CommandType.COMMAND,id:"sheet.command.set-gridlines-color",handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=P(o);if(!r)return!1;const{worksheet:a}=r,l=a.getConfig().gridlinesColor;if(l===(e==null?void 0:e.color))return!1;const{unitId:u,subUnitId:d}=r,c={color:e==null?void 0:e.color,unitId:u,subUnitId:d},m={color:l,unitId:u,subUnitId:d};return t.syncExecuteCommand(dt.id,c)?(n.pushUndoRedo({unitID:u,undoMutations:[{id:dt.id,params:m}],redoMutations:[{id:dt.id,params:c}]}),!0):!1}},Q={id:"sheet.mutation.set-range-protection",type:i.CommandType.MUTATION,handler:(s,e)=>{const{unitId:t,subUnitId:n,rule:o,ruleId:r}=e;return s.get(X).setRule(t,n,r,o),!0}},Ru=(s,e)=>{const{unitId:t,subUnitId:n,ruleId:o}=e,a=s.get(X).getRule(t,n,o);return a?{id:Q.id,params:{...e,rule:a}}:null},st={id:"sheet.mutation.set-worksheet-protection",type:i.CommandType.MUTATION,handler:(s,e)=>{const{unitId:t,subUnitId:n,rule:o}=e;return s.get(ke).setRule(t,n,o),!0}},zr={type:i.CommandType.COMMAND,id:"sheet.command.set-protection",async handler(s,e){if(!e)return!1;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(X),{rule:r,oldRule:a}=e,{unitId:l,subUnitId:u}=r,d=[],c=[];return(a==null?void 0:a.unitType)===r.unitType?r.unitType===D.Worksheet?(d.push({id:st.id,params:{unitId:l,subUnitId:u,rule:r}}),c.push({id:st.id,params:{unitId:l,subUnitId:u,rule:a}})):(d.push({id:Q.id,params:{unitId:l,subUnitId:u,rule:r,ruleId:r.id}}),c.push({id:Q.id,params:{unitId:l,subUnitId:u,ruleId:a.id,rule:a}})):(a&&(a.unitType===D.Worksheet?(d.push({id:tt.id,params:{unitId:l,subUnitId:u}}),c.push({id:Fe.id,params:{unitId:l,rule:a,subUnitId:a.subUnitId}})):a.unitType===D.SelectRange&&(d.push({id:Te.id,params:{unitId:l,subUnitId:u,ruleIds:[a.id]}}),c.push({id:Ce.id,params:{unitId:l,subUnitId:u,rules:[a]}}))),r.unitType===D.Worksheet?(d.push({id:Fe.id,params:{unitId:l,rule:r,subUnitId:r.subUnitId}}),c.unshift({id:tt.id,params:{unitId:l,subUnitId:u}})):r.unitType===D.SelectRange&&(r.id=o.createRuleId(l,u),d.push({id:Ce.id,params:{unitId:l,subUnitId:u,rules:[r]}}),c.unshift({id:Te.id,params:{unitId:l,subUnitId:u,ruleIds:[r.id]}}))),i.sequenceExecute(d,t)&&n.pushUndoRedo({unitID:l,undoMutations:c,redoMutations:d}),!0}},qr={type:i.CommandType.COMMAND,id:"sheet.command.set-row-data",handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=P(o,e);if(!r)return!1;const{rowData:a}=e,{unitId:l,subUnitId:u,worksheet:d}=r,c={subUnitId:u,unitId:l,rowData:a},m=Ro(c,d);return t.syncExecuteCommand(ct.id,c)?(n.pushUndoRedo({unitID:l,undoMutations:[{id:ct.id,params:m}],redoMutations:[{id:ct.id,params:c}]}),!0):!1}},Tt={type:i.CommandType.COMMAND,id:"sheet.command.set-specific-rows-visible",handler:(s,e)=>{var v,M,p;const{unitId:t,subUnitId:n,ranges:o}=e,r=s.get(i.ICommandService),a=s.get(i.IUndoRedoService),l=s.get(g.SheetInterceptorService),u=P(s.get(i.IUniverInstanceService),{unitId:t,subUnitId:n});if(!u)return!1;const{worksheet:d}=u,c={unitId:t,subUnitId:n,ranges:o},m={unitId:t,subUnitId:n,reveal:!0,selections:o.map(w=>({range:w,primary:se(w,d),style:null}))},h=ya(s,c),R={unitId:t,subUnitId:n,selections:Yr(o).map(w=>({range:w,primary:se(w,d),style:null}))},C=i.sequenceExecute([{id:Ye.id,params:c},{id:q.id,params:m}],r),S=l.onCommandExecute({id:Tt.id,params:e}),I=i.sequenceExecute([...S.redos],r);if(C.result&&I.result){const w=l.afterCommandExecute({id:Tt.id,params:e});return i.sequenceExecute(w.redos,r),a.pushUndoRedo({unitID:t,undoMutations:[...(v=S.preUndos)!=null?v:[],{id:Ke.id,params:h},{id:q.id,params:R},...(M=S.undos)!=null?M:[],...w.undos],redoMutations:[...(p=S.preRedos)!=null?p:[],{id:Ye.id,params:c},{id:q.id,params:m},...S.redos,...w.redos]}),!0}return!0}},Ls={type:i.CommandType.COMMAND,id:"sheet.command.set-selected-rows-visible",handler:async s=>{var c;const e=s.get(g.SheetsSelectionsService),t=s.get(i.IUniverInstanceService),n=s.get(i.ICommandService),o=(c=e.getCurrentSelections())==null?void 0:c.map(m=>m.range).filter(m=>m.rangeType===i.RANGE_TYPE.ROW);if(!(o!=null&&o.length))return!1;const r=P(t);if(!r)return!1;const{worksheet:a,unitId:l,subUnitId:u}=r,d=o.map(m=>a.getHiddenRows(m.startRow,m.endRow)).flat();return n.executeCommand(Tt.id,{unitId:l,subUnitId:u,ranges:d})}},Mn={type:i.CommandType.COMMAND,id:"sheet.command.set-rows-hidden",handler:(s,e)=>{var M,p,w,y,b,T;const t=s.get(g.SheetsSelectionsService),n=s.get(i.ICommandService),o=s.get(i.IUndoRedoService),r=s.get(i.IUniverInstanceService),a=s.get(g.SheetInterceptorService);let l=(M=e==null?void 0:e.ranges)!=null&&M.length?e.ranges:(p=t.getCurrentSelections())==null?void 0:p.map(U=>U.range).filter(U=>U.rangeType===i.RANGE_TYPE.ROW);if(!(l!=null&&l.length))return!1;const u=P(r,e);if(!u)return!1;l=Cu(u.worksheet,l);const{unitId:d,subUnitId:c,worksheet:m}=u,h={unitId:d,subUnitId:c,ranges:l},R={unitId:d,subUnitId:c,selections:Yr(l).map(U=>({range:U,primary:se(U,m),style:null}))},C=_a(s,h),S={unitId:d,subUnitId:c,reveal:!0,selections:l.map(U=>({range:U,primary:se(U,m),style:null}))},I=a.onCommandExecute({id:Mn.id,params:h});if(i.sequenceExecute([...(w=I.preRedos)!=null?w:[],{id:Ke.id,params:h},{id:q.id,params:R},...I.redos],n).result){const U=a.afterCommandExecute({id:Mn.id,params:h});return i.sequenceExecute(U.redos,n),o.pushUndoRedo({unitID:d,undoMutations:[...(y=I.preUndos)!=null?y:[],{id:Ye.id,params:C},{id:q.id,params:S},...(b=I.undos)!=null?b:[],...U.undos],redoMutations:[...(T=I.preRedos)!=null?T:[],{id:Ke.id,params:h},{id:q.id,params:R},...I.redos,...U.redos]}),!0}return!0}};function Cu(s,e){const t=s.getMaxColumns()-1,n=s.getHiddenRows(),o=[];return e.forEach(r=>{const a=n.filter(l=>l.startRow>=r.startRow&&l.endRow<=r.endRow);if(a.length){let l=r.startRow;a.forEach(u=>{u.startRow>l&&(o.push({startRow:l,endRow:u.startRow-1,startColumn:0,endColumn:t}),l=u.endRow+1)}),l<=r.endRow&&o.push({startRow:l,endRow:r.endRow,startColumn:0,endColumn:t})}else o.push(r)}),o}function Yr(s){return Su(s).map(t=>{const n=t.startRow===0?t.endRow+1:t.startRow-1;return{...t,startRow:n,endRow:n}})}function Su(s){const e=[];let t;return s.sort((n,o)=>n.startRow-o.startRow).forEach(n=>{if(!t){t=n;return}n.startRow===t.endRow+1?t.endRow=n.endRow:(e.push(t),t=n)}),e.push(t),e}const fu=["ff","fs","tr","tb"],ee={type:i.CommandType.COMMAND,id:"sheet.command.set-style",handler:(s,e)=>{var k;const t=s.get(i.IUniverInstanceService),n=P(t,e);if(!n)return!1;const{unitId:o,subUnitId:r,worksheet:a}=n,{range:l,style:u}=e,d=s.get(i.ICommandService),c=s.get(i.IUndoRedoService),m=s.get(g.SheetsSelectionsService),h=l?[l]:(k=m.getCurrentSelections())==null?void 0:k.map(E=>E.range);if(!(h!=null&&h.length))return!1;const R=new i.ObjectMatrix,C=ll(a);if(i.Tools.isArray(u.value))for(let E=0;E<h.length;E++)C.forOperableEach(h[E],(N,W,V)=>{R.setValue(N,W,{s:{[u.type]:u.value[N-V.startRow][W-V.startColumn]}})});else for(let E=0;E<h.length;E++){const N={s:{[u.type]:u.value}};C.forOperableEach(h[E],(W,V)=>R.setValue(W,V,N))}const S={subUnitId:r,unitId:o,cellValue:R.getMatrix()},I=s.get(g.SheetSkeletonService).getSkeleton(o,r),v=ce(s,S),M=d.syncExecuteCommand(F.id,S),p=s.get(g.SheetInterceptorService);let w=[],y=[];if(fu.includes(e==null?void 0:e.style.type)){const{suitableRanges:E,remainingRanges:N}=Bt(h,I),W=_s(E,a),{undos:V,redos:$}=p.generateMutationsOfAutoHeight({unitId:o,subUnitId:r,ranges:E,autoHeightRanges:E,lazyAutoHeightRanges:N,cellHeights:W});w=V,y=$}const{undos:b,redos:T}=p.onCommandExecute({id:ee.id,params:e}),U=i.sequenceExecute([...T,...y],d);return M&&U.result?(c.pushUndoRedo({unitID:S.unitId,undoMutations:[{id:F.id,params:v},...b,...w],redoMutations:[{id:F.id,params:S},...T,...y]}),!0):!1}},Iu={type:i.CommandType.COMMAND,id:"sheet.command.set-bold",handler:s=>{const e=s.get(g.SheetsSelectionsService).getCurrentLastSelection();if(!e)return!1;const t=P(s.get(i.IUniverInstanceService));if(!t)return!1;const{worksheet:n}=t,{actualRow:o,actualColumn:r}=e.primary,l={style:{type:"bl",value:n.getRange(o,r).getFontWeight()===i.FontWeight.BOLD?i.BooleanNumber.FALSE:i.BooleanNumber.TRUE}};return s.get(i.ICommandService).syncExecuteCommand(ee.id,l)}},vu={type:i.CommandType.COMMAND,id:"sheet.command.set-italic",handler:s=>{const e=s.get(g.SheetsSelectionsService).getCurrentLastSelection();if(!e)return!1;const t=P(s.get(i.IUniverInstanceService));if(!t)return!1;const{worksheet:n}=t;let o=!0;if(e.primary){const{startRow:a,startColumn:l}=e.primary;o=n.getRange(a,l).getFontStyle()===i.FontItalic.ITALIC}const r={style:{type:"it",value:o?i.BooleanNumber.FALSE:i.BooleanNumber.TRUE}};return s.get(i.ICommandService).syncExecuteCommand(ee.id,r)}},pu={type:i.CommandType.COMMAND,id:"sheet.command.set-underline",handler:s=>{const e=s.get(g.SheetsSelectionsService).getCurrentLastSelection();if(!e)return!1;const t=P(s.get(i.IUniverInstanceService));if(!t)return!1;const{worksheet:n}=t;let o=!0;e.primary&&(o=!!n.getRange(e.primary.startRow,e.primary.startColumn).getUnderline().s);const r={style:{type:"ul",value:{s:o?i.BooleanNumber.FALSE:i.BooleanNumber.TRUE}}};return s.get(i.ICommandService).syncExecuteCommand(ee.id,r)}},wu={type:i.CommandType.COMMAND,id:"sheet.command.set-stroke",handler:s=>{const e=s.get(g.SheetsSelectionsService).getCurrentLastSelection();if(!e)return!1;const t=P(s.get(i.IUniverInstanceService));if(!t)return!1;const{worksheet:n}=t;let o=!0;e.primary&&(o=!!n.getRange(e.primary.actualRow,e.primary.actualColumn).getStrikeThrough().s);const r={style:{type:"st",value:{s:o?i.BooleanNumber.FALSE:i.BooleanNumber.TRUE}}};return s.get(i.ICommandService).syncExecuteCommand(ee.id,r)}},Mu={type:i.CommandType.COMMAND,id:"sheet.command.set-overline",handler:s=>{const e=s.get(g.SheetsSelectionsService).getCurrentLastSelection();if(!e)return!1;const t=P(s.get(i.IUniverInstanceService));if(!t)return!1;const{worksheet:n}=t;let o=!0;e.primary&&(o=!!n.getRange(e.primary.startRow,e.primary.startColumn).getOverline().s);const r={style:{type:"ol",value:{s:o?i.BooleanNumber.FALSE:i.BooleanNumber.TRUE}}};return s.get(i.ICommandService).syncExecuteCommand(ee.id,r)}},yu={type:i.CommandType.COMMAND,id:"sheet.command.set-font-family",handler:(s,e)=>{if(!e)return!1;const t=s.get(i.ICommandService),n={style:{type:"ff",value:e.value}};return t.syncExecuteCommand(ee.id,n)}},_u={type:i.CommandType.COMMAND,id:"sheet.command.set-font-size",handler:(s,e)=>{if(!e)return!1;const t=s.get(i.ICommandService),n={style:{type:"fs",value:e.value}};return t.syncExecuteCommand(ee.id,n)}},Kr={type:i.CommandType.COMMAND,id:"sheet.command.set-text-color",handler:(s,e)=>{if(!e)return!1;const t=s.get(i.ICommandService),n={style:{type:"cl",value:{rgb:e.value}}};return t.syncExecuteCommand(ee.id,n)}},Jr={type:i.CommandType.COMMAND,id:"sheet.command.reset-text-color",handler:s=>{const e=s.get(i.ICommandService),t={style:{type:"cl",value:{rgb:null}}};return e.syncExecuteCommand(ee.id,t)}},xr={type:i.CommandType.COMMAND,id:"sheet.command.set-background-color",handler:(s,e)=>{if(!e||!e.value)return!1;const t=s.get(i.ICommandService),n={style:{type:"bg",value:{rgb:e.value}}};return t.syncExecuteCommand(ee.id,n)}},Xr={type:i.CommandType.COMMAND,id:"sheet.command.reset-background-color",handler:s=>{const e=s.get(i.ICommandService),t={style:{type:"bg",value:{rgb:null}}};return e.syncExecuteCommand(ee.id,t)}},Zr={type:i.CommandType.COMMAND,id:"sheet.command.set-vertical-text-align",handler:(s,e)=>{if(!e)return!1;const t=s.get(i.ICommandService),n={unitId:e.unitId,subUnitId:e.subUnitId,range:e.range,style:{type:"vt",value:e.value}};return t.syncExecuteCommand(ee.id,n)}},Qr={type:i.CommandType.COMMAND,id:"sheet.command.set-horizontal-text-align",handler:(s,e)=>{if(!e)return!1;const t=s.get(i.ICommandService),n={unitId:e.unitId,subUnitId:e.subUnitId,range:e.range,style:{type:"ht",value:e.value}};return t.syncExecuteCommand(ee.id,n)}},ei={type:i.CommandType.COMMAND,id:"sheet.command.set-text-wrap",handler:(s,e)=>{if(!e)return!1;const t=s.get(i.ICommandService),n={unitId:e.unitId,subUnitId:e.subUnitId,range:e.range,style:{type:"tb",value:e.value}};return t.syncExecuteCommand(ee.id,n)}},ti={type:i.CommandType.COMMAND,id:"sheet.command.set-text-rotation",handler:(s,e)=>{if(!e)return!1;const t=typeof e.value=="number"?{a:e.value}:{a:0,v:i.BooleanNumber.TRUE},n=s.get(i.ICommandService),o={unitId:e.unitId,subUnitId:e.subUnitId,range:e.range,style:{type:"tr",value:t}};return n.syncExecuteCommand(ee.id,o)}},bu=(s,e)=>{const r=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId).getSheetBySheetId(e.subUnitId).getConfig().tabColor;return{...i.Tools.deepClone(e),color:r}},jt={id:"sheet.mutation.set-tab-color",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(!t)return!1;const n=t.getSheetBySheetId(e.subUnitId);return n?(n.getConfig().tabColor=e.color,!0):!1}},ni={type:i.CommandType.COMMAND,id:"sheet.command.set-tab-color",handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=P(s.get(i.IUniverInstanceService));if(!o)return!1;const{unitId:r,subUnitId:a}=o,l={color:e.value,unitId:r,subUnitId:a},u=bu(s,l);return t.syncExecuteCommand(jt.id,l)?(n.pushUndoRedo({unitID:r,undoMutations:[{id:jt.id,params:u}],redoMutations:[{id:jt.id,params:l}]}),!0):!1}},Bs={id:"sheet.mutation.set-workbook-name",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=s.get(i.IUniverInstanceService).getUnit(e.unitId,i.UniverInstanceType.UNIVER_SHEET);return t?(t.setName(e.name),!0):!1}},Hs={type:i.CommandType.COMMAND,id:"sheet.command.set-workbook-name",handler:(s,e)=>{var u;const t=s.get(i.ICommandService),n=s.get(g.SheetInterceptorService);if(!Bn(s.get(i.IUniverInstanceService),e))return!1;const r=n.onCommandExecute({id:Hs.id,params:e}),a={name:e.name,unitId:e.unitId},l=[...(u=r.preRedos)!=null?u:[],{id:Bs.id,params:a},...r.redos];return i.sequenceExecute(l,t).result}},Eu=4,Fs={type:i.CommandType.COMMAND,id:"sheet.command.set-worksheet-activate",handler:(s,e,t)=>{const n=s.get(i.ICommandService),o=P(s.get(i.IUniverInstanceService),e);if(!o)return!1;const{unitId:r,subUnitId:a}=o;return new Promise(l=>{setTimeout(()=>{const u=n.syncExecuteCommand(Ct.id,{unitId:r,subUnitId:a},t);l(u)},Eu)})}},Gt={type:i.CommandType.COMMAND,id:"sheet.command.delta-column-width",handler:async(s,e)=>{const n=s.get(g.SheetsSelectionsService).getCurrentSelections();if(!(n!=null&&n.length))return!1;const o=s.get(i.ICommandService),r=s.get(i.IUndoRedoService),a=P(s.get(i.IUniverInstanceService));if(!a)return!1;const{worksheet:l,unitId:u,subUnitId:d}=a,{anchorCol:c,deltaX:m}=e,R=l.getColumnWidth(c)+m,C=n.length===1&&n[0].range.rangeType===i.RANGE_TYPE.ALL,S=n.filter(L=>L.range.rangeType===i.RANGE_TYPE.COLUMN),I=C?i.RANGE_TYPE.ALL:S.some(({range:L})=>{const{startColumn:Y,endColumn:z}=L;return Y<=c&&c<=z})?i.RANGE_TYPE.COLUMN:i.RANGE_TYPE.NORMAL;let v;if(I===i.RANGE_TYPE.ALL){const L=l.getRowCount(),Y=new Array(l.getColumnCount()).fill(void 0).map((z,K)=>({startRow:0,endRow:L-1,startColumn:K,endColumn:K}));v={subUnitId:d,unitId:u,colWidth:R,ranges:Y}}else I===i.RANGE_TYPE.COLUMN?v={subUnitId:d,unitId:u,ranges:S.map(L=>i.Rectangle.clone(L.range)),colWidth:R}:v={subUnitId:d,unitId:u,colWidth:R,ranges:[{startRow:0,endRow:l.getMaxRows()-1,startColumn:c,endColumn:c}]};const M=s.get(g.SheetSkeletonService).getSkeleton(u,d),{suitableRanges:p,remainingRanges:w}=Bt(v.ranges,M);_s(p,l);const y=s.get(g.SheetInterceptorService),{undos:b,redos:T}=y.onCommandExecute({id:Gt.id,params:v}),U=Hn(v,l),k=o.syncExecuteCommand(Ve.id,v),{undos:E,redos:N}=y.generateMutationsOfAutoHeight({unitId:u,subUnitId:d,ranges:p,autoHeightRanges:p,lazyAutoHeightRanges:w}),{undos:W,redos:V}=s.get(g.SheetInterceptorService).afterCommandExecute({id:Gt.id,params:v}),$=i.sequenceExecute([...T,...V,...N],o);return k&&$.result&&r.pushUndoRedo({unitID:u,undoMutations:[{id:Ve.id,params:U},...b,...W,...E],redoMutations:[{id:Ve.id,params:v},...T,...V,...N]}),!0}},zt={type:i.CommandType.COMMAND,id:"sheet.command.set-worksheet-col-width",handler:(s,e)=>{var y,b,T,U;const t=s.get(g.SheetsSelectionsService),n=s.get(i.ICommandService),o=s.get(i.IUndoRedoService),r=s.get(g.SheetInterceptorService),a=(y=e==null?void 0:e.ranges)!=null&&y.length?e.ranges:(b=t.getCurrentSelections())==null?void 0:b.map(k=>k.range);if(!(a!=null&&a.length))return!1;const l=P(s.get(i.IUniverInstanceService),e);if(!l)return!1;const{subUnitId:u,unitId:d,worksheet:c}=l,m=s.get(g.SheetSkeletonService).getSkeleton(d,u),h={subUnitId:u,unitId:d,ranges:a,colWidth:e.value},{suitableRanges:R,remainingRanges:C}=Bt(h.ranges,m);_s(R,c);const S=Hn(h,c),I=n.syncExecuteCommand(Ve.id,h),{undos:v,redos:M}=r.generateMutationsOfAutoHeight({unitId:d,subUnitId:u,ranges:R,autoHeightRanges:R,lazyAutoHeightRanges:C}),p=r.onCommandExecute({id:zt.id,params:h}),w=i.sequenceExecute([...p.redos,...M],n);if(I&&w.result){const k=r.afterCommandExecute({id:zt.id,params:h});return i.sequenceExecute(k.redos,n),o.pushUndoRedo({unitID:d,undoMutations:[...(T=p.preUndos)!=null?T:[],{id:Ve.id,params:S},...p.undos,...k.undos,...v],redoMutations:[...(U=p.preRedos)!=null?U:[],{id:Ve.id,params:h},...p.redos,...k.redos,...M]}),!0}return!1}};i.CommandType.COMMAND;const si={type:i.CommandType.COMMAND,id:"sheet.command.set-worksheet-column-count",handler:(s,e)=>{const{unitId:t,subUnitId:n,columnCount:o}=e,r=s.get(i.ICommandService),a=s.get(i.IUndoRedoService),l=s.get(i.IUniverInstanceService);if(!P(l,e))return!1;const d={unitId:t,subUnitId:n,columnCount:o},c=Co(s,d);return r.syncExecuteCommand(mt.id,d)?(a.pushUndoRedo({unitID:t,undoMutations:[{id:mt.id,params:c}],redoMutations:[{id:mt.id,params:d}]}),!0):!1}},oi={type:i.CommandType.COMMAND,id:"sheet.command.set-worksheet-default-style",handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),{unitId:o}=e,r=So(s,e);return t.syncExecuteCommand(ht.id,e)?(n.pushUndoRedo({unitID:o,undoMutations:[{id:ht.id,params:r}],redoMutations:[{id:ht.id,params:e}]}),!0):!1}},ri=(s,e)=>{const t=ve(s.get(i.IUniverInstanceService),e);if(!t)throw new Error("[SetWorksheetHideMutationFactory]: worksheet is null error!");const{worksheet:n}=t;return{hidden:n.isSheetHidden(),unitId:e.unitId,subUnitId:n.getSheetId()}},je={id:"sheet.mutation.set-worksheet-hidden",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(t==null)return!1;const n=t.getSheetBySheetId(e.subUnitId);return n?(n.getConfig().hidden=e.hidden,!0):!1}},ii={type:i.CommandType.COMMAND,id:"sheet.command.set-worksheet-hidden",handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.ErrorService),r=s.get(i.LocaleService),a=P(s.get(i.IUniverInstanceService),e);if(!a)return!1;const{workbook:l,worksheet:u,unitId:d,subUnitId:c}=a;if(u.getConfig().hidden===i.BooleanNumber.TRUE)return!1;const h={unitId:d,subUnitId:c,hidden:i.BooleanNumber.TRUE},R=ri(s,h);return l.getSheets().filter(v=>v.getConfig().hidden===i.BooleanNumber.FALSE).length===1?(o.emit(r.t("sheets.info.hideSheet")),!1):t.syncExecuteCommand(je.id,h)?(n.pushUndoRedo({unitID:d,undoMutations:[{id:je.id,params:R}],redoMutations:[{id:je.id,params:h}]}),!0):!1}},Tu=(s,e)=>{const t=ve(s.get(i.IUniverInstanceService),e);if(!t)throw new Error("[SetWorksheetNameMutationFactory]: worksheet is null error!");const{worksheet:n}=t;return{unitId:e.unitId,name:n.getName(),subUnitId:n.getSheetId()}},qt={id:"sheet.mutation.set-worksheet-name",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(t==null)return!1;const n=t.getSheetBySheetId(e.subUnitId);return n?(n.getConfig().name=e.name,!0):!1}},yn={type:i.CommandType.COMMAND,id:"sheet.command.set-worksheet-name",handler:(s,e)=>{var C,S;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(g.SheetInterceptorService),r=P(s.get(i.IUniverInstanceService),e);if(!r)return!1;const{unitId:a,subUnitId:l}=r,u={subUnitId:l,name:e.name,unitId:a},d=Tu(s,u),c=o.onCommandExecute({id:yn.id,params:e}),m=[...(C=c.preRedos)!=null?C:[],{id:qt.id,params:u},...c.redos],h=[...(S=c.preUndos)!=null?S:[],{id:qt.id,params:d},...c.undos];return i.sequenceExecute(m,t).result?(n.pushUndoRedo({unitID:a,undoMutations:h,redoMutations:m}),!0):!1}},Uu=(s,e)=>({...i.Tools.deepClone(e),toOrder:e.fromOrder,fromOrder:e.toOrder}),Yt={id:"sheet.mutation.set-worksheet-order",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(!t)return!1;const n=t.getConfig();return n.sheetOrder.splice(e.fromOrder,1),n.sheetOrder.splice(e.toOrder,0,e.subUnitId),!0}},js={type:i.CommandType.COMMAND,id:"sheet.command.set-worksheet-order",handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=P(s.get(i.IUniverInstanceService),e);if(!o)return!1;const{workbook:r,unitId:a,subUnitId:l}=o,d={fromOrder:r.getConfig().sheetOrder.indexOf(l),toOrder:e.order,unitId:a,subUnitId:l},c=Uu(s,d);return t.syncExecuteCommand(Yt.id,d)?(n.pushUndoRedo({unitID:a,undoMutations:[{id:Yt.id,params:c}],redoMutations:[{id:Yt.id,params:d}]}),!0):!1}};class Ut{constructor(){f(this,"_model",new Map);f(this,"_pointChange",new O.Subject);f(this,"pointChange$",this._pointChange.asObservable())}addRule(e){this._ensureSubUnitMap(e.unitId).set(e.subUnitId,e),this._pointChange.next(e)}deleteRule(e,t){var o,r,a;const n=(o=this._model.get(e))==null?void 0:o.get(t);n&&((a=(r=this._model)==null?void 0:r.get(e))==null||a.delete(t),this._pointChange.next(n))}getRule(e,t){var n,o;return(o=(n=this._model)==null?void 0:n.get(e))==null?void 0:o.get(t)}toObject(){const e={};return[...this._model.keys()].forEach(n=>{const o=this._model.get(n);o!=null&&o.size&&(e[n]=[],[...o.keys()].forEach(a=>{const l=o.get(a);l&&e[n].push(l)}))}),e}fromObject(e){const t=new Map;Object.keys(e).forEach(n=>{const o=e[n];if(o!=null&&o.length){const r=new Map;o.forEach(a=>{r.set(a.subUnitId,a)}),t.set(n,r)}}),this._model=t}deleteUnitModel(e){this._model.delete(e)}_ensureSubUnitMap(e){let t=this._model.get(e);return t||(t=new Map,this._model.set(e,t)),t}getTargetByPermissionId(e,t){const n=this._model.get(e);if(!n)return null;for(const[o,r]of n)if(r.permissionId===t)return[e,o]}}class Gs{constructor(e,t,n){f(this,"type",D.SelectRange);f(this,"subType",_.Delete);f(this,"status",i.PermissionStatus.INIT);f(this,"value",!0);f(this,"id");f(this,"unitId");f(this,"subUnitId");f(this,"permissionId");this.unitId=e,this.subUnitId=t,this.permissionId=n,this.id=`${D.SelectRange}.${_.Delete}.${n}`}}class zs{constructor(e,t,n){f(this,"type",D.SelectRange);f(this,"subType",_.ManageCollaborator);f(this,"status",i.PermissionStatus.INIT);f(this,"value",!0);f(this,"id");f(this,"unitId");f(this,"subUnitId");f(this,"permissionId");this.unitId=e,this.subUnitId=t,this.permissionId=n,this.id=`${D.SelectRange}.${_.ManageCollaborator}.${n}`}}const ue=()=>[ln,Se,zs,Gs],Ge=[_.Edit,_.View,_.ManageCollaborator,_.Delete],Pu=(s="unitId",e="subUnitId",t="permissionId")=>ue().reduce((n,o)=>{const r=new o(s,e,t);return n[r.subType]=r.value,n},{}),Pt=()=>[me,es,Yn,ss,Kn,Qn,dn,xn,Xn,mn,un,Zn,ns,cn,Ho,os,ts,Jn,qo,zo,jo,Fo],ai=[_.Edit,_.Print,_.Comment,_.View,_.Copy,_.Export,_.ManageCollaborator,_.CreateSheet,_.DeleteSheet,_.RenameSheet,_.HideSheet,_.Duplicate,_.Share,_.MoveSheet,_.CopySheet,_.RecoverHistory,_.ViewHistory,_.CreatePermissionObject,_.InsertRow,_.InsertColumn,_.DeleteRow,_.DeleteColumn],de=()=>[fe,Vt,gs,as],Ie=()=>[rs,is,ls,us,ds,cs,hs,ms,Rs,Cs,Wt,St,ft,Ss],_n=[_.Copy,_.DeleteColumn,_.DeleteRow,_.EditExtraObject,_.Filter,_.InsertColumn,_.InsertRow,_.InsertHyperlink,_.PivotTable,_.SetCellStyle,_.SetCellValue,_.SetColumnStyle,_.SetRowStyle,_.Sort];var ku=Object.getOwnPropertyDescriptor,Nu=(s,e,t,n)=>{for(var o=n>1?void 0:n?ku(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},ze=(s,e)=>(t,n)=>e(t,n,s);const Ou="SHEET_WORKSHEET_PROTECTION_PLUGIN",Du="SHEET_WORKSHEET_PROTECTION_POINT_PLUGIN";g.WorksheetPermissionService=class extends i.RxDisposable{constructor(e,t,n,o,r,a,l,u){super(),this._permissionService=e,this._univerInstanceService=t,this._injector=n,this._worksheetProtectionRuleModel=o,this._worksheetProtectionPointRuleModel=r,this._resourceManagerService=a,this._rangeProtectionRuleModel=l,this._logService=u,this._init(),this._initRuleChange(),this._initRuleSnapshot(),this._initPointSnapshot()}_init(){const e=t=>{const n=t.getUnitId(),o=r=>{const a=r.getSheetId();[...de(),...Ie()].forEach(l=>{const u=new l(n,a);this._permissionService.addPermissionPoint(u)}),this._logService.debug("[WorksheetPermissionService]","Initialization completed",n,a)};t.getSheets().forEach(r=>{o(r)}),t.sheetCreated$.subscribe(r=>{o(r)}),t.sheetDisposed$.subscribe(r=>{const a=r.getSheetId();this._rangeProtectionRuleModel.getSubunitRuleList(n,a).forEach(u=>{[...ue()].forEach(d=>{const c=new d(n,a,u.permissionId);this._permissionService.deletePermissionPoint(c.id)})}),[...de(),...Ie()].forEach(u=>{const d=new u(n,a);this._permissionService.deletePermissionPoint(d.id)})})};this._univerInstanceService.getAllUnitsForType(i.UniverInstanceType.UNIVER_SHEET).forEach(t=>{e(t)}),this._univerInstanceService.getTypeOfUnitAdded$(i.UniverInstanceType.UNIVER_SHEET).pipe(kt.takeUntil(this.dispose$)).subscribe(e),this._univerInstanceService.getTypeOfUnitDisposed$(i.UniverInstanceType.UNIVER_SHEET).pipe(kt.takeUntil(this.dispose$)).subscribe(t=>{t.getSheets().forEach(n=>{const o=t.getUnitId(),r=n.getSheetId();de().forEach(a=>{const l=new a(o,r);this._permissionService.deletePermissionPoint(l.id)})})})}_initRuleChange(){this.disposeWithMe(this._worksheetProtectionRuleModel.ruleChange$.subscribe(e=>{switch(e.type){case"add":break;case"delete":{de().forEach(t=>{const n=new t(e.unitId,e.subUnitId);this._permissionService.updatePermissionPoint(n.id,!0)});break}case"set":{de().forEach(t=>{const n=new t(e.unitId,e.subUnitId);this._permissionService.updatePermissionPoint(n.id,e.rule)});break}}}))}_initRuleSnapshot(){const e=()=>{const n=this._worksheetProtectionRuleModel.toObject();return JSON.stringify(n)},t=n=>{if(!n)return{};try{return JSON.parse(n)}catch{return{}}};this.disposeWithMe(this._resourceManagerService.registerPluginResource({toJson:e,parseJson:t,pluginName:Ou,businesses:[an.UNIVER_SHEET],onLoad:(n,o)=>{this._worksheetProtectionRuleModel.fromObject(o),Object.keys(o).forEach(r=>{de().forEach(a=>{const l=new a(n,r);l.value=!1,this._permissionService.addPermissionPoint(l)})}),this._worksheetProtectionRuleModel.changeRuleInitState(!0)},onUnLoad:n=>{const o=this._univerInstanceService.getUnit(n);o&&(o.getSheets().forEach(r=>{const a=r.getSheetId();[...de(),...Ie()].forEach(l=>{const u=new l(n,a);this._permissionService.deletePermissionPoint(u.id)})}),Pt().forEach(r=>{const a=new r(n);this._permissionService.deletePermissionPoint(a.id)})),this._worksheetProtectionRuleModel.deleteUnitModel(n)}}))}_initPointSnapshot(){const e=()=>{const n=this._worksheetProtectionPointRuleModel.toObject();return JSON.stringify(n)},t=n=>{if(!n)return{};try{return JSON.parse(n)}catch{return{}}};this.disposeWithMe(this._resourceManagerService.registerPluginResource({toJson:e,parseJson:t,pluginName:Du,businesses:[an.UNIVER_SHEET],onLoad:(n,o)=>{this._worksheetProtectionPointRuleModel.fromObject(o),Object.keys(o).forEach(r=>{Ie().forEach(a=>{const l=new a(n,r);this._permissionService.addPermissionPoint(l)})})},onUnLoad:n=>{this._worksheetProtectionPointRuleModel.deleteUnitModel(n)}}))}},g.WorksheetPermissionService=Nu([ze(0,i.Inject(i.IPermissionService)),ze(1,i.Inject(i.IUniverInstanceService)),ze(2,i.Inject(i.Injector)),ze(3,i.Inject(ke)),ze(4,i.Inject(Ut)),ze(5,i.Inject(i.IResourceManagerService)),ze(6,i.Inject(X)),ze(7,i.Inject(i.ILogService))],g.WorksheetPermissionService);const bn={id:"sheet.mutation.set-worksheet-permission-points",type:i.CommandType.MUTATION,handler:(s,e)=>{const{rule:t}=e;return s.get(Ut).addRule(t),!0}},li={type:i.CommandType.COMMAND,id:"sheet.command.set-worksheet-permission-points",async handler(s,e){if(!e)return!1;const t=s.get(i.ICommandService),{rule:n}=e;return t.executeCommand(bn.id,{rule:n,unitId:n.unitId,subUnitId:n.subUnitId}),!0}},ui={type:i.CommandType.COMMAND,id:"sheet.command.set-worksheet-protection",async handler(s,e){if(!e)return!1;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),{rule:o,permissionId:r,oldRule:a}=e,{unitId:l,subUnitId:u}=o,d={...o,permissionId:r};if(await t.executeCommand(st.id,{unitId:l,subUnitId:u,newRule:d})){const m=[{id:st.id,params:{unitId:l,subUnitId:u,newRule:d}}],h=[{id:st.id,params:{unitId:l,subUnitId:u,rule:a}}];n.pushUndoRedo({unitID:l,redoMutations:m,undoMutations:h})}return!0}},Au=(s,e)=>{const r=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId).getSheetBySheetId(e.subUnitId).getConfig().rightToLeft;return{...i.Tools.deepClone(e),rightToLeft:r}},En={id:"sheet.mutation.set-worksheet-right-to-left",type:i.CommandType.MUTATION,handler:(s,e)=>{const t=s.get(i.IUniverInstanceService).getUniverSheetInstance(e.unitId);if(!t)return!1;const n=t.getSheetBySheetId(e.subUnitId);if(!n)return!1;const o=n.getConfig();return o.rightToLeft=e.rightToLeft,!0}},Wu={type:i.CommandType.COMMAND,id:"sheet.command.set-worksheet-right-to-left",handler:async(s,e)=>{var m;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=P(s.get(i.IUniverInstanceService),e);if(!o)return!1;const{unitId:r,subUnitId:a}=o;let l=i.BooleanNumber.FALSE;e&&(l=(m=e.rightToLeft)!=null?m:i.BooleanNumber.FALSE);const u={rightToLeft:l,unitId:r,subUnitId:a},d=Au(s,u);return t.syncExecuteCommand(En.id,u)?(n.pushUndoRedo({unitID:r,undoMutations:[{id:En.id,params:d}],redoMutations:[{id:En.id,params:u}]}),!0):!1}},di={type:i.CommandType.COMMAND,id:"sheet.command.set-worksheet-row-count",handler:(s,e)=>{const{unitId:t,subUnitId:n,rowCount:o}=e,r=s.get(i.ICommandService),a=s.get(i.IUndoRedoService),l=s.get(i.IUniverInstanceService);if(!P(l,e))return!1;const d={unitId:t,subUnitId:n,rowCount:o},c=fo(s,d);return r.syncExecuteCommand(gt.id,d)?(a.pushUndoRedo({unitID:t,undoMutations:[{id:gt.id,params:c}],redoMutations:[{id:gt.id,params:d}]}),!0):!1}},Kt={type:i.CommandType.COMMAND,id:"sheet.command.delta-row-height",handler:async(s,e)=>{var k,E;const n=s.get(g.SheetsSelectionsService).getCurrentSelections(),o=s.get(g.SheetInterceptorService);if(!(n!=null&&n.length))return!1;const r=P(s.get(i.IUniverInstanceService));if(!r)return!1;const{worksheet:a,subUnitId:l,unitId:u}=r,{anchorRow:d,deltaY:c}=e,h=a.getRowHeight(d)+c,R=n.length===1&&n[0].range.rangeType===i.RANGE_TYPE.ALL,C=n.filter(N=>N.range.rangeType===i.RANGE_TYPE.ROW),S=R?i.RANGE_TYPE.ALL:C.some(({range:N})=>{const{startRow:W,endRow:V}=N;return W<=d&&d<=V})?i.RANGE_TYPE.ROW:i.RANGE_TYPE.NORMAL;let I;if(S===i.RANGE_TYPE.ALL){const N=a.getColumnCount(),W=new Array(a.getRowCount()).fill(void 0).map((V,$)=>({startRow:$,endRow:$,startColumn:0,endColumn:N-1}));I={subUnitId:l,unitId:u,rowHeight:h,ranges:W}}else S===i.RANGE_TYPE.ROW?I={subUnitId:l,unitId:u,ranges:C.map(N=>i.Rectangle.clone(N.range)),rowHeight:h}:I={subUnitId:l,unitId:u,rowHeight:h,ranges:[{startRow:d,endRow:d,startColumn:0,endColumn:a.getMaxColumns()-1}]};const v=Io(I,a),M={unitId:u,subUnitId:l,ranges:I.ranges,autoHeightInfo:i.BooleanNumber.FALSE},p=Fn(M,a),w=s.get(i.ICommandService),y=s.get(i.IUndoRedoService),b=o.onCommandExecute({id:Kt.id,params:I}),T=i.sequenceExecute([{id:Ee.id,params:I},{id:Re.id,params:M}],w),U=i.sequenceExecute([...b.redos],w);if(T.result&&U.result){const N=o.afterCommandExecute({id:Kt.id,params:I});return i.sequenceExecute(N.redos,w),y.pushUndoRedo({unitID:u,undoMutations:[...(k=b.preUndos)!=null?k:[],{id:Ee.id,params:v},{id:Re.id,params:p},...b.undos,...N.undos],redoMutations:[...(E=b.preRedos)!=null?E:[],{id:Ee.id,params:I},{id:Re.id,params:M},...b.redos,...N.redos]}),!0}return!1}},Jt={type:i.CommandType.COMMAND,id:"sheet.command.set-row-height",handler:(s,e)=>{var p,w,y,b;const t=s.get(g.SheetsSelectionsService),n=s.get(i.ICommandService),o=s.get(i.IUndoRedoService),r=s.get(i.IUniverInstanceService),a=s.get(g.SheetInterceptorService),l=(p=e==null?void 0:e.ranges)!=null&&p.length?e.ranges:(w=t.getCurrentSelections())==null?void 0:w.map(T=>T.range);if(!(l!=null&&l.length))return!1;const u=P(r,e);if(!u)return!1;const{unitId:d,subUnitId:c,worksheet:m}=u,h={subUnitId:c,unitId:d,ranges:l,rowHeight:e.value},R=Io(h,m),C={unitId:d,subUnitId:c,ranges:h.ranges,autoHeightInfo:i.BooleanNumber.FALSE},S=Fn(C,m),I=i.sequenceExecute([{id:Ee.id,params:h},{id:Re.id,params:C}],n),v=a.onCommandExecute({id:Jt.id,params:h}),M=i.sequenceExecute([...v.redos],n);if(I.result&&M.result){const T=a.afterCommandExecute({id:Jt.id,params:h});return i.sequenceExecute(T.redos,n),o.pushUndoRedo({unitID:d,undoMutations:[...(y=v.preRedos)!=null?y:[],{id:Ee.id,params:R},{id:Re.id,params:S},...v.undos,...T.undos],redoMutations:[...(b=v.preRedos)!=null?b:[],{id:Ee.id,params:h},{id:Re.id,params:C},...v.redos,...T.redos]}),!0}return!1}},Tn={type:i.CommandType.COMMAND,id:"sheet.command.set-row-is-auto-height",handler:(s,e)=>{var T,U;const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(g.SheetsSelectionsService),r=s.get(i.IUniverInstanceService),a=P(r,e);if(!a)return!1;const{unitId:l,subUnitId:u,worksheet:d}=a,c=(T=e==null?void 0:e.ranges)!=null&&T.length?e.ranges:(U=o.getCurrentSelections())==null?void 0:U.map(k=>k.range);if(!(c!=null&&c.length))return!1;const m={unitId:l,subUnitId:u,ranges:c,autoHeightInfo:i.BooleanNumber.TRUE},h=Fn(m,d),R=t.syncExecuteCommand(Re.id,m),C=s.get(g.SheetSkeletonService).getSkeleton(l,u),{suitableRanges:S,remainingRanges:I}=Bt(m.ranges,C),v=s.get(g.SheetInterceptorService),{undos:M,redos:p}=v.generateMutationsOfAutoHeight({unitId:l,subUnitId:u,ranges:S,autoHeightRanges:S,lazyAutoHeightRanges:I}),{undos:w,redos:y}=v.onCommandExecute({id:Tn.id,params:m}),b=i.sequenceExecute([...y,...p],t);return R&&b.result?(n.pushUndoRedo({unitID:l,undoMutations:[{id:Re.id,params:h},...w,...M],redoMutations:[{id:Re.id,params:m},...y,...p]}),!0):!1}},qs={type:i.CommandType.COMMAND,id:"sheet.command.set-worksheet-show",handler:(s,e)=>{const{unitId:t,subUnitId:n}=e,o=s.get(i.ICommandService),r=s.get(i.IUndoRedoService),a=s.get(i.IUniverInstanceService);if(!P(s.get(i.IUniverInstanceService)))return!1;const u=a.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET);if(!u)return!1;const d=u.getSheetBySheetId(n);if(!d||d.getConfig().hidden===i.BooleanNumber.FALSE)return!1;const m={unitId:t,subUnitId:n,hidden:i.BooleanNumber.FALSE},h=ri(s,m),R=o.syncExecuteCommand(je.id,m),C={unitId:t,subUnitId:n},S=o.syncExecuteCommand(Ct.id,C);return R&&S?(r.pushUndoRedo({unitID:t,undoMutations:[{id:je.id,params:h}],redoMutations:[{id:je.id,params:m}]}),!0):!1}},ci={type:i.CommandType.COMMAND,id:"sheet.command.split-text-to-columns",handler:(s,e)=>{const{unitId:t,subUnitId:n,range:o,delimiter:r,customDelimiter:a,treatMultipleDelimitersAsOne:l}=e,u=s.get(i.ICommandService),d=s.get(i.IUniverInstanceService),c=s.get(i.IUndoRedoService);if(!P(s.get(i.IUniverInstanceService)))return!1;const h=d.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET);if(!h)return!1;const R=h.getSheetBySheetId(n);if(!R)return!1;const{lastRow:C,rs:S,maxLength:I}=To(R,o,r,a,l),v=R.getColumnCount(),{startColumn:M}=i.Range.transformRange(o,R);if(o.startColumn!==o.endColumn)return!1;const p=[],w=[],y=M+I+1-v;if(y>0){const N={unitId:t,subUnitId:n,range:{startRow:0,endRow:R.getRowCount()-1,startColumn:v-1,endColumn:v-1+y}};p.push({id:ie.id,params:N});const W=Nt(s,N);w.push({id:ne.id,params:W})}const b={startRow:o.startRow,endRow:C,startColumn:M,endColumn:M+I},T=new i.ObjectMatrix;for(let N=b.startRow;N<=b.endRow;N++)for(let W=b.startColumn;W<=b.endColumn;W++){const V=S[N-b.startRow];W===0&&(V==null?void 0:V.length)===1?T.setValue(N,W,R.getCell(N,W)):T.setValue(N,W,{v:(V==null?void 0:V[W-b.startColumn])||null,p:null,f:null,si:null,custom:null})}const U={unitId:t,subUnitId:n,cellValue:T.clone()},k=ce(s,U);return p.push({id:F.id,params:U}),w.unshift({id:F.id,params:k}),i.sequenceExecute(p,u).result?(c.pushUndoRedo({unitID:t,undoMutations:w,redoMutations:p}),!0):!1}},mi={id:"sheet.command.toggle-cell-checkbox",type:i.CommandType.COMMAND,handler:(s,e)=>{if(!e)return!1;const{unitId:t,subUnitId:n,row:o,col:r,paragraphIndex:a}=e,u=s.get(i.IUniverInstanceService).getUnit(t,i.UniverInstanceType.UNIVER_SHEET),d=u==null?void 0:u.getSheetBySheetId(n),c=s.get(i.IUndoRedoService),m=s.get(i.ICommandService);if(!d)return!1;const h=d.getCell(o,r);if(!(h!=null&&h.p))return!1;const R=i.Tools.deepClone(h.p),C=new i.DocumentDataModel(R),S=i.BuildTextUtils.paragraph.bullet.toggleChecklist({document:C,paragraphIndex:a});if(!S)return!1;i.TextX.apply(C.getBody(),S.serialize());const I={unitId:t,subUnitId:n,cellValue:{[o]:{[r]:{p:R,t:i.CellValueType.STRING}}}},v={id:F.id,params:I},M=ce(s,I),p={id:F.id,params:M},w=[v],y=[p];return c.pushUndoRedo({redoMutations:w,undoMutations:y,unitID:t}),m.syncExecuteCommand(v.id,v.params)}},hi={type:i.CommandType.COMMAND,id:"sheet.command.toggle-gridlines",handler:(s,e)=>{const t=s.get(i.ICommandService),n=s.get(i.IUndoRedoService),o=s.get(i.IUniverInstanceService),r=P(o);if(!r)return!1;const{worksheet:a}=r,l=a.getConfig().showGridlines;if(l===(e==null?void 0:e.showGridlines))return!1;const{unitId:u,subUnitId:d}=r,c={showGridlines:l===i.BooleanNumber.TRUE?i.BooleanNumber.FALSE:i.BooleanNumber.TRUE,unitId:u,subUnitId:d},m={showGridlines:l,unitId:u,subUnitId:d};return t.syncExecuteCommand(Rt.id,c)?(n.pushUndoRedo({unitID:u,undoMutations:[{id:Rt.id,params:m}],redoMutations:[{id:Rt.id,params:c}]}),!0):!1}},gi={id:"sheet.command.unregister-worksheet-range-theme-style",type:i.CommandType.COMMAND,handler:(s,e)=>{var h;if(!e)return!1;const{unitId:t,themeName:n}=e,o=s.get(i.IUniverInstanceService),r=s.get(i.ICommandService),a=s.get(i.IUndoRedoService),l=s.get(g.SheetRangeThemeModel);if(!P(o))return!1;const d={unitId:t,themeName:n},c={unitId:t,themeName:n,rangeThemeStyleJson:(h=l.getRangeThemeStyle(t,n))==null?void 0:h.toJson()};return r.syncExecuteCommand(_t.id,e)&&a.pushUndoRedo({unitID:t,undoMutations:[{id:_t.id,params:c}],redoMutations:[{id:In.id,params:d}]}),!0}},Ri={id:"sheet.mutation.add-range-theme",type:i.CommandType.MUTATION,handler:(s,e)=>{if(!e)return!1;const{styleJSON:t,unitId:n}=e,o=s.get(g.SheetRangeThemeModel),r=new We(t.name);return r.fromJson(t),o.registerRangeThemeStyle(n,r),!0}},Ci={id:"sheet.mutation.empty",type:i.CommandType.MUTATION,handler:()=>!0},Si={id:"sheet.operation.mark-dirty-row-auto-height",type:i.CommandType.OPERATION,handler:()=>!0},fi={id:"sheet.operation.cancel-mark-dirty-row-auto-height",type:i.CommandType.OPERATION,handler:()=>!0},ot=i.createIdentifier("INumfmtService"),Vu=(s,e)=>{const t=s.get(ot),{values:n,unitId:o,subUnitId:r}=e,a=[],l=[];Object.keys(n).forEach(d=>{n[d].ranges.forEach(m=>{i.Range.foreach(m,(h,R)=>{const C=t.getValue(o,r,h,R);C?a.push({pattern:C.pattern,row:h,col:R}):l.push({startColumn:R,endColumn:R,startRow:h,endRow:h})})})});const u=[];if(a.length){const d=Pn(o,r,a);Object.keys(d.values).forEach(c=>{const m=d.values[c];m.ranges=zn(m.ranges)}),u.push({id:Un.id,params:Pn(o,r,a)})}return l.length&&u.push({id:Ys.id,params:{unitId:o,subUnitId:r,ranges:l}}),u},Un={id:"sheet.mutation.set.numfmt",type:i.CommandType.MUTATION,handler:(s,e)=>{if(!e)return!1;const{values:t,refMap:n}=e,o=s.get(ot),r=e.unitId,a=e.subUnitId,l=Object.keys(t).reduce((u,d)=>{const c=n[d],m=t[d].ranges;return c&&u.push({...c,ranges:m}),u},[]);return o.setValues(r,a,l),!0}},Ys={id:"sheet.mutation.remove.numfmt",type:i.CommandType.MUTATION,handler:(s,e)=>{if(!e)return!1;const{unitId:t,subUnitId:n,ranges:o}=e;return s.get(ot).deleteValues(t,n,o),!0}},$u=(s,e)=>{const t=s.get(ot),{ranges:n,unitId:o,subUnitId:r}=e,a=[];if(n.forEach(u=>{i.Range.foreach(u,(d,c)=>{const m=t.getValue(o,r,d,c);m&&a.push({pattern:m.pattern,row:d,col:c})})}),!a.length)return[];const l=Pn(o,r,a);return Object.keys(l.values).forEach(u=>{const d=l.values[u];d.ranges=zn(d.ranges)}),[{id:Un.id,params:l}]},Pn=(s,e,t)=>{const n=Ya(t,"pattern"),o={},r={},a=Ka();return Object.keys(n).forEach(l=>{const u=n[l],d=a();o[d]={pattern:l},u.forEach(c=>{r[d]||(r[d]={ranges:[]}),r[d].ranges.push(i.cellToRange(c.row,c.col))})}),{unitId:s,subUnitId:e,refMap:o,values:r}},Ii={id:"sheet.mutation.remove-range-theme",type:i.CommandType.MUTATION,handler:(s,e)=>{if(!e)return!1;const{styleName:t,unitId:n}=e;return s.get(g.SheetRangeThemeModel).unregisterRangeThemeStyle(n,t),!0}},vi={id:"sheet.mutation.set-range-theme",type:i.CommandType.MUTATION,handler:(s,e)=>{if(!e)return!1;const{unitId:t,styleName:n,style:o}=e,a=s.get(g.SheetRangeThemeModel).getRangeThemeStyle(t,n);return a&&(o.headerRowStyle&&a.setHeaderRowStyle(o.headerRowStyle),o.firstRowStyle&&a.setFirstRowStyle(o.firstRowStyle),o.secondRowStyle&&a.setSecondRowStyle(o.secondRowStyle),o.lastRowStyle&&a.setLastRowStyle(o.lastRowStyle)),!0}},pi={id:"sheet.operation.scroll-to-cell",type:i.CommandType.OPERATION,handler:()=>!0},Lu=(s,e,t)=>{const o=s.get(g.SheetsSelectionsService).getCurrentSelections(),{value:r,selections:a,unitId:l,subUnitId:u}=e;if(o){const c=o[(o==null?void 0:o.length)-1].primary;if(c){const{actualColumn:m,actualRow:h}=c;let{startRow:R,startColumn:C,endRow:S,endColumn:I}=a[a.length-1];if(r===i.Dimension.COLUMNS){const w=t.find(y=>y.startColumn===m&&y.endColumn===m&&h===y.startRow);w&&(I=w.endColumn,R=w.startRow,S=w.endRow)}else if(r===i.Dimension.ROWS){const w=t.find(y=>y.startRow===h&&y.endRow===h&&m===y.startColumn);w&&(S=w.endRow,C=w.startColumn,I=w.endColumn)}const v={startRow:R,startColumn:C,endRow:S,endColumn:I,actualRow:h,actualColumn:m,isMerged:!0,isMergedMainCell:R===h&&C===m},M=o.map((w,y,b)=>({range:w.range,style:null,primary:y===b.length-1?v:null})),p={unitId:l,subUnitId:u,type:te.ONLY_SET,selections:M};return{id:q.id,params:p}}return null}return null},Bu=(s,e)=>{const n=s.get(g.SheetsSelectionsService).getCurrentSelections(),{unitId:o,subUnitId:r}=e;if(n&&n[(n==null?void 0:n.length)-1].primary){const u={unitId:o,subUnitId:r,type:te.ONLY_SET,selections:[...n]};return{id:q.id,params:u}}return null},wi="maxCellsPerSheet",Hu=3e6;var Fu=Object.getOwnPropertyDescriptor,ju=(s,e,t,n)=>{for(var o=n>1?void 0:n?Fu(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},Mi=(s,e)=>(t,n)=>e(t,n,s);const Gu="SHEET_DEFINED_NAME_PLUGIN",zu="AllDefaultWorkbook";g.DefinedNameDataController=class extends i.Disposable{constructor(e,t){super(),this._definedNamesService=e,this._resourceManagerService=t,this._initialize()}_initialize(){this._initSnapshot()}_initSnapshot(){const e=n=>{const o=this._definedNamesService.getDefinedNameMap(n);return o?JSON.stringify(o):""},t=n=>{if(!n)return{};try{return JSON.parse(n)}catch{return{}}};this.disposeWithMe(this._resourceManagerService.registerPluginResource({pluginName:Gu,businesses:[i.UniverInstanceType.UNIVER_SHEET],toJson:n=>e(n),parseJson:n=>t(n),onUnLoad:n=>{this._definedNamesService.removeUnitDefinedName(n)},onLoad:(n,o)=>{this._definedNamesService.registerDefinedNames(n,o)}}))}},g.DefinedNameDataController=ju([Mi(0,J.IDefinedNamesService),Mi(1,i.IResourceManagerService)],g.DefinedNameDataController);const yi="sheets.config",_i={};var qu=Object.getOwnPropertyDescriptor,Yu=(s,e,t,n)=>{for(var o=n>1?void 0:n?qu(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},Ks=(s,e)=>(t,n)=>e(t,n,s);const Ku=[Ne.id],Ju=[re.id,ie.id,ae.id,ne.id,pe.id,we.id];g.SheetsFreezeSyncController=class extends i.Disposable{constructor(t,n,o){var a,l;super();f(this,"_d",new i.DisposableCollection);f(this,"_enabled",!0);this._univerInstanceService=t,this._commandService=n,this._configService=o;const r=(l=(a=this._configService.getConfig(yi))==null?void 0:a.freezeSync)!=null?l:!0;this.setEnabled(r)}getEnabled(){return this._enabled}setEnabled(t){t?this._d.dispose():this._initOnlyLocalListener(),this._enabled=t}_initOnlyLocalListener(){this._d.add(this._commandService.beforeCommandExecuted((t,n)=>{Ku.includes(t.id)&&(n||(n={}),n.onlyLocal=!0)})),this._d.add(this._commandService.onCommandExecuted((t,n)=>{if(Ju.includes(t.id)&&(n!=null&&n.fromCollab)){const{id:o,params:r}=t;o===re.id?this._handleInsertRowMutation(r,n):o===ie.id?this._handleInsertColMutation(r,n):o===ae.id?this._handleRemoveRowMutation(r,n):o===ne.id?this._handleRemoveColMutation(r,n):o===pe.id?this._handleMoveRowsMutation(r,n):o===we.id&&this._handleMoveColsMutation(r,n)}}))}_handleInsertRowMutation(t,n){const{range:o,unitId:r,subUnitId:a}=t,l=this._getFreeze(r,a);if(l&&o.startRow<l.startRow){const u=o.endRow-o.startRow+1,d={...l,startRow:Math.max(1,l.startRow+u),ySplit:Math.max(1,l.ySplit+u)};this._sequenceExecute(r,a,d,n)}}_handleInsertColMutation(t,n){const{range:o,unitId:r,subUnitId:a}=t,l=this._getFreeze(r,a);if(l&&o.startColumn<l.startColumn){const u=o.endColumn-o.startColumn+1,d={...l,startColumn:Math.max(1,l.startColumn+u),xSplit:Math.max(1,l.xSplit+u)};this._sequenceExecute(r,a,d,n)}}_handleRemoveRowMutation(t,n){const{range:o,unitId:r,subUnitId:a}=t,l=this._getFreeze(r,a);if(l&&o.startRow<l.startRow){const u=Math.min(l.startRow,o.endRow+1)-o.startRow,d={...l,startRow:Math.max(1,l.startRow-u),ySplit:Math.max(1,l.ySplit-u)};this._sequenceExecute(r,a,d,n)}}_handleRemoveColMutation(t,n){const{range:o,unitId:r,subUnitId:a}=t,l=this._getFreeze(r,a);if(l&&o.startColumn<l.startColumn){const u=Math.min(l.startColumn,o.endColumn+1)-o.startColumn,d={...l,startColumn:Math.max(1,l.startColumn-u),xSplit:Math.max(1,l.xSplit-u)};this._sequenceExecute(r,a,d,n)}}_handleMoveRowsMutation(t,n){const{sourceRange:o,targetRange:r,unitId:a,subUnitId:l}=t,u=this._getFreeze(a,l);if(!u||u.startRow<=0||o.startRow>=u.startRow&&r.startRow>=u.startRow||o.endRow<u.startRow&&r.endRow<u.startRow)return;const d=o.endRow-o.startRow+1,c=Math.max(Math.min(u.startRow,o.endRow+1)-o.startRow,0),m={...u};r.startRow>=u.startRow?(m.startRow=Math.max(1,u.startRow-c),m.ySplit=Math.max(1,u.ySplit-c)):(m.startRow=u.startRow+d-c,m.ySplit=u.ySplit+d-c),this._sequenceExecute(a,l,m,n)}_handleMoveColsMutation(t,n){const{sourceRange:o,targetRange:r,unitId:a,subUnitId:l}=t,u=this._getFreeze(a,l);if(!u||u.startColumn<=0||o.startColumn>=u.startColumn&&r.startColumn>=u.startColumn||o.endColumn<u.startColumn&&r.endColumn<u.startColumn)return;const d=o.endColumn-o.startColumn+1,c=Math.max(Math.min(u.startColumn,o.endColumn+1)-o.startColumn,0),m={...u};r.startColumn>=u.startColumn?(m.startColumn=Math.max(1,u.startColumn-c),m.xSplit=Math.max(1,u.xSplit-c)):(m.startColumn=u.startColumn+d-c,m.xSplit=u.xSplit+d-c),this._sequenceExecute(a,l,m,n)}_getFreeze(t,n){const o=this._univerInstanceService.getUnit(t,i.UniverInstanceType.UNIVER_SHEET);if(!o)return null;const r=o.getSheetBySheetId(n);return r?r.getFreeze():null}_sequenceExecute(t,n,o,r){i.sequenceExecute([{id:Ne.id,params:{...o,unitId:t,subUnitId:n,resetScroll:!1}}],this._commandService,r)}},g.SheetsFreezeSyncController=Yu([Ks(0,i.Inject(i.IUniverInstanceService)),Ks(1,i.ICommandService),Ks(2,i.IConfigService)],g.SheetsFreezeSyncController);var xu=Object.getOwnPropertyDescriptor,Xu=(s,e,t,n)=>{for(var o=n>1?void 0:n?xu(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},Oe=(s,e)=>(t,n)=>e(t,n,s);g.SheetPermissionCheckController=class extends i.Disposable{constructor(t,n,o,r,a,l,u,d,c,m){super();f(this,"disposableCollection",new i.DisposableCollection);f(this,"_triggerPermissionUIEvent$",new O.Subject);f(this,"triggerPermissionUIEvent$",this._triggerPermissionUIEvent$.asObservable());this._commandService=t,this._univerInstanceService=n,this._permissionService=o,this._selectionManagerService=r,this._rangeProtectionRuleModel=a,this._worksheetProtectionRuleModel=l,this._localeService=u,this._lexerTreeBuilder=d,this._contextService=c,this._definedNamesService=m,this._initialize()}blockExecuteWithoutPermission(t){throw this._triggerPermissionUIEvent$.next(t),new i.CustomCommandExecutionError("have no permission")}_getPermissionCheck(t,n){let o=!0,r="";switch(t){case It.id:i.isICellData(n.value)&&n.value.f?(o=this._permissionCheckWithFormula(n),r=this._localeService.t("permission.dialog.formulaErr")):o=this._permissionCheckBySetRangeValue({workbookTypes:[me],rangeTypes:[Se],worksheetTypes:[Wt,fe]},n);break;case fn.id:o=this.permissionCheckWithRanges({workbookTypes:[me],rangeTypes:[Se],worksheetTypes:[Wt,fe]},n==null?void 0:n.ranges,n==null?void 0:n.unitId,n==null?void 0:n.subUnitId),r=this._localeService.t("permission.dialog.editErr");break;case Gt.id:case zt.id:o=this.permissionCheckWithoutRange({worksheetTypes:[St]}),r=this._localeService.t("permission.dialog.setRowColStyleErr");break;case Kt.id:case Jt.id:case Tn.id:o=this.permissionCheckWithoutRange({worksheetTypes:[ft]}),r=this._localeService.t("permission.dialog.setRowColStyleErr");break;case wt.id:case pt.id:o=this._permissionCheckByMoveCommand(n),r=this._localeService.t("permission.dialog.moveRowColErr");break;case Je.id:o=this._permissionCheckByMoveRangeCommand(n),r=this._localeService.t("permission.dialog.moveRangeErr");break;case js.id:o=this._permissionCheckByWorksheetCommand([me,cn]),r=this._localeService.t("permission.dialog.operatorSheetErr"),o===!1&&this._worksheetProtectionRuleModel.resetOrder();break;case yn.id:o=this._permissionCheckByWorksheetCommand([me,mn]),r=this._localeService.t("permission.dialog.operatorSheetErr"),o===!1&&this._worksheetProtectionRuleModel.resetOrder();break;case qs.id:{const{unitId:a,subUnitId:l}=n;o=this._permissionCheckByWorksheetCommand([me,un],a,l),r=this._localeService.t("permission.dialog.operatorSheetErr"),o===!1&&this._worksheetProtectionRuleModel.resetOrder()}break;case Et.id:o=this.permissionCheckWithRanges({workbookTypes:[me],rangeTypes:[Se],worksheetTypes:[fe,St]},n.ranges,n.unitId,n.subUnitId),r=this._localeService.t("permission.dialog.setRowColStyleErr");break;case Tt.id:o=this.permissionCheckWithRanges({workbookTypes:[me],rangeTypes:[Se],worksheetTypes:[fe,ft]},n.ranges,n.unitId,n.subUnitId),r=this._localeService.t("permission.dialog.setRowColStyleErr");break;case Ws.id:o=this.permissionCheckWithRanges({workbookTypes:[me],rangeTypes:[Se],worksheetTypes:[fe,St]}),r=this._localeService.t("permission.dialog.setRowColStyleErr");break;case Ls.id:o=this.permissionCheckWithRanges({workbookTypes:[me],rangeTypes:[Se],worksheetTypes:[fe,ft]}),r=this._localeService.t("permission.dialog.setRowColStyleErr");break;case vt.id:o=this._permissionCheckWithInsertRangeMove("right"),r=this._localeService.t("permission.dialog.insertOrDeleteMoveRangeErr");break;case xe.id:o=this._permissionCheckWithInsertRangeMove("bottom"),r=this._localeService.t("permission.dialog.insertOrDeleteMoveRangeErr");break;case Be.id:o=this._permissionCheckWithInsertRangeMove("left"),r=this._localeService.t("permission.dialog.insertOrDeleteMoveRangeErr");break;case He.id:o=this._permissionCheckWithInsertRangeMove("top"),r=this._localeService.t("permission.dialog.insertOrDeleteMoveRangeErr");break}o||this.blockExecuteWithoutPermission(r)}_initialize(){this._commandExecutedListener()}_commandExecutedListener(){this.disposeWithMe(this._commandService.beforeCommandExecuted(t=>{this._getPermissionCheck(t.id,t==null?void 0:t.params)})),this.disposeWithMe(this._commandService.onCommandExecuted(t=>{var n;if(t.id===qt.id){const o=t.params,{unitId:r=(n=this._univerInstanceService.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET))==null?void 0:n.getUnitId(),subUnitId:a}=o;if(!r||!a)return;const l=this._worksheetProtectionRuleModel.getRule(r,a),u=this._rangeProtectionRuleModel.getSubunitRuleList(r,a);l&&this._worksheetProtectionRuleModel.ruleRefresh(l.permissionId),u.length&&this._rangeProtectionRuleModel.ruleRefresh(a)}}))}_permissionCheckWithInsertRangeMove(t){var c;const n=P(this._univerInstanceService);if(!n)return!1;const{worksheet:o,unitId:r,subUnitId:a}=n,l=i.Tools.deepClone((c=this._selectionManagerService.getCurrentLastSelection())==null?void 0:c.range);return!(!l||(t==="top"||t==="bottom"?l.endRow=o.getRowCount()-1:(t==="left"||t==="right")&&(l.endColumn=o.getColumnCount()-1),this._rangeProtectionRuleModel.getSubunitRuleList(r,a).map(m=>m.ranges).flat().some(m=>i.Rectangle.getIntersects(l,m))))}_permissionCheckByWorksheetCommand(t,n,o){var c,m;const r=P(this._univerInstanceService,{unitId:n,subUnitId:o});if(!r)return!1;const{unitId:a,subUnitId:l}=r,u=this._worksheetProtectionRuleModel.getRule(a,l),d=this._rangeProtectionRuleModel.getSubunitRuleList(a,l).length>0;return u||d?(m=(c=this._permissionService.getPermissionPoint(new dn(a).id))==null?void 0:c.value)!=null?m:!1:this._permissionService.composePermission(t.map(h=>new h(a).id)).every(h=>h.value)}permissionCheckWithoutRange(t){var R,C,S,I;const n=P(this._univerInstanceService);if(!n)return!1;const{worksheet:o,unitId:r,subUnitId:a}=n,l=this._selectionManagerService.getCurrentLastSelection();if(!l)return!0;const u=(C=(R=l==null?void 0:l.primary)==null?void 0:R.actualRow)!=null?C:0,d=(I=(S=l==null?void 0:l.primary)==null?void 0:S.actualColumn)!=null?I:0,{workbookTypes:c,worksheetTypes:m,rangeTypes:h}=t;return!(c&&c.some(M=>{var y,b;const p=new M(r);return((b=(y=this._permissionService.getPermissionPoint(p.id))==null?void 0:y.value)!=null?b:!1)===!1})===!0||m&&m.some(M=>{var y,b;const p=new M(r,a);return((b=(y=this._permissionService.getPermissionPoint(p.id))==null?void 0:y.value)!=null?b:!1)===!1})===!0||h&&h.some(M=>{var T,U,k,E,N;const p=(U=(T=o.getCell(u,d))==null?void 0:T.selectionProtection)==null?void 0:U[0];if(!(p!=null&&p.ruleId))return!1;const w=(k=this._rangeProtectionRuleModel.getRule(r,a,p.ruleId))==null?void 0:k.permissionId;if(!w)return!1;const y=new M(r,a,w);return((N=(E=this._permissionService.getPermissionPoint(y.id))==null?void 0:E.value)!=null?N:!1)===!1})===!0)}permissionCheckWithRanges(t,n,o,r){var C;const a=P(this._univerInstanceService);if(!a)return!1;const{workbook:l,worksheet:u}=a;o||(o=l.getUnitId()),r||(r=u.getSheetId());const d=n!=null?n:(C=this._selectionManagerService.getCurrentSelections())==null?void 0:C.map(S=>S.range);if(!d)return!1;const{workbookTypes:c,worksheetTypes:m,rangeTypes:h}=t,R=[];return c&&R.push(...c.map(S=>new S(o).id)),m&&R.push(...m.map(S=>new S(o,r).id)),h&&this._rangeProtectionRuleModel.getSubunitRuleList(o,r).forEach(S=>{d.some(v=>S.ranges.some(M=>i.Rectangle.intersects(M,v)))&&R.push(...h.map(v=>new v(o,r,S.permissionId).id))}),R.length?this._permissionService.composePermission(R).every(S=>S.value):!0}_permissionCheckByMoveCommand(t){const n=P(this._univerInstanceService);if(!n)return!1;const{worksheet:o,unitId:r,subUnitId:a}=n,l=t.toRange;l.endRow===o.getRowCount()-1?l.endColumn=l.startColumn:l.endRow=l.startRow;const u=this._rangeProtectionRuleModel.getSubunitRuleList(r,a).reduce((d,c)=>[...d,...c.ranges],[]).filter(d=>i.Rectangle.intersects(d,l));return u.length>0?!1:(u.forEach(d=>{var c,m;for(let h=d.startRow;h<=d.endRow;h++)for(let R=d.startColumn;R<=d.endColumn;R++){const C=(m=(c=o.getCell(h,R))==null?void 0:c.selectionProtection)==null?void 0:m[0];if((C==null?void 0:C[_.Edit])===!1)return!1}}),!0)}_permissionCheckByMoveRangeCommand(t){const n=P(this._univerInstanceService);if(!n)return!1;const{worksheet:o,unitId:r,subUnitId:a}=n,l=t.toRange,u=this._rangeProtectionRuleModel.getSubunitRuleList(r,a).reduce((d,c)=>[...d,...c.ranges],[]).filter(d=>i.Rectangle.intersects(d,l));return u.length>0?!1:(u.forEach(d=>{var c,m;for(let h=d.startRow;h<=d.endRow;h++)for(let R=d.startColumn;R<=d.endColumn;R++){const C=(m=(c=o.getCell(h,R))==null?void 0:c.selectionProtection)==null?void 0:m[0];if((C==null?void 0:C[_.Edit])===!1)return!1}}),!0)}_permissionCheckBySetRangeValue(t,n){let o=[];n.range?o=[n.range]:o=[new i.ObjectMatrix(n.value).getDataRange()];const{unitId:r,subUnitId:a}=n;return this.permissionCheckWithRanges(t,o,r,a)}_permissionCheckWithFormula(t){var a,l,u,d,c;const n=t.value,o=t.range,r=n.f;if(r){const m=r.substring(1),h=this._univerInstanceService.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET),R=(a=t.unitId)!=null?a:h.getUnitId(),C=this._definedNamesService.getValueByName(R,m);if(C){let S=C.formulaOrRefString;S.startsWith(J.operatorToken.EQUALS)&&(S=S.slice(1));const I=S.split(",");for(let v=0;v<I.length;v++){const M=I[v],p=J.deserializeRangeWithSheet(M);if(p.sheetName){const w=h.getSheetBySheetName(p.sheetName);if(!w)return!0;const{startRow:y,endRow:b,startColumn:T,endColumn:U}=p.range;for(let k=y;k<=b;k++)for(let E=T;E<=U;E++){const N=(u=(l=w.getCell(k,E))==null?void 0:l.selectionProtection)==null?void 0:u[0];if((N==null?void 0:N[_.View])===!1)return!1}}}return!0}else{const S=this._lexerTreeBuilder.sequenceNodesBuilder(r);if(!S)return!0;for(let I=0;I<S.length;I++){const v=S[I];if(typeof v=="string"||v.nodeType!==J.sequenceNodeType.REFERENCE)continue;const{token:M}=v,p=J.deserializeRangeWithSheetWithCache(M),w=p.unitId?this._univerInstanceService.getUnit(p.unitId):this._univerInstanceService.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET);if(!w)return!0;let y=p.sheetName?w.getSheetBySheetName(p.sheetName):w.getActiveSheet();const b=w.getUnitId();if(p.sheetName){if(y=w.getSheetBySheetName(p.sheetName),!y)return!0;const N=y==null?void 0:y.getSheetId();if(!this._permissionService.getPermissionPoint(new Vt(b,N).id))return!1}if(!y)return!0;const{startRow:T,endRow:U,startColumn:k,endColumn:E}=p.range;for(let N=T;N<=U;N++)for(let W=k;W<=E;W++){const V=(c=(d=y.getCell(N,W))==null?void 0:d.selectionProtection)==null?void 0:c[0];if((V==null?void 0:V[_.View])===!1)return!1}}return!0}}if(o){const m=P(this._univerInstanceService);if(!m)return!1;const h=t.unitId||m.unitId,R=t.subUnitId||m.subUnitId,S=this._rangeProtectionRuleModel.getSubunitRuleList(h,R).filter(v=>v.ranges.some(M=>i.Rectangle.intersects(M,o))).map(v=>new Se(h,R,v.permissionId).id);if(!this._permissionService.composePermission(S).every(v=>v.value))return!1}return!0}},g.SheetPermissionCheckController=Xu([Oe(0,i.ICommandService),Oe(1,i.IUniverInstanceService),Oe(2,i.IPermissionService),Oe(3,i.Inject(g.SheetsSelectionsService)),Oe(4,i.Inject(X)),Oe(5,i.Inject(ke)),Oe(6,i.Inject(i.LocaleService)),Oe(7,i.Inject(J.LexerTreeBuilder)),Oe(8,i.IContextService),Oe(9,J.IDefinedNamesService)],g.SheetPermissionCheckController);var Zu=Object.getOwnPropertyDescriptor,Qu=(s,e,t,n)=>{for(var o=n>1?void 0:n?Zu(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},xt=(s,e)=>(t,n)=>e(t,n,s);g.WorkbookPermissionService=class extends i.Disposable{constructor(t,n,o,r,a){super();f(this,"_unitPermissionInitStateChange",new O.BehaviorSubject(!1));f(this,"unitPermissionInitStateChange$",this._unitPermissionInitStateChange.asObservable());this._permissionService=t,this._univerInstanceService=n,this._rangeProtectionRuleModel=o,this._worksheetProtectionRuleModel=r,this._worksheetProtectionPointModel=a,this._init()}_init(){const t=n=>{const o=n.getUnitId();Pt().forEach(r=>{const a=new r(o);this._permissionService.addPermissionPoint(a)})};this._univerInstanceService.getAllUnitsForType(i.UniverInstanceType.UNIVER_SHEET).forEach(n=>{t(n)}),this.disposeWithMe(this._univerInstanceService.getTypeOfUnitAdded$(i.UniverInstanceType.UNIVER_SHEET).subscribe(n=>{t(n)})),this.disposeWithMe(this._univerInstanceService.getTypeOfUnitDisposed$(i.UniverInstanceType.UNIVER_SHEET).subscribe(n=>{const o=n.getUnitId();n.getSheets().forEach(r=>{const a=r.getSheetId();this._rangeProtectionRuleModel.getSubunitRuleList(o,a).forEach(u=>{[...ue()].forEach(d=>{const c=new d(o,a,u.permissionId);this._permissionService.deletePermissionPoint(c.id)})}),[...de(),...Ie()].forEach(u=>{const d=new u(o,a);this._permissionService.deletePermissionPoint(d.id)})}),Pt().forEach(r=>{const a=new r(o);this._permissionService.deletePermissionPoint(a.id)}),this._rangeProtectionRuleModel.deleteUnitModel(o),this._worksheetProtectionPointModel.deleteUnitModel(o),this._worksheetProtectionRuleModel.deleteUnitModel(o)}))}changeUnitInitState(t){this._unitPermissionInitStateChange.next(t)}},g.WorkbookPermissionService=Qu([xt(0,i.Inject(i.IPermissionService)),xt(1,i.Inject(i.IUniverInstanceService)),xt(2,i.Inject(X)),xt(3,i.Inject(ke)),xt(4,i.Inject(Ut))],g.WorkbookPermissionService);var ed=Object.getOwnPropertyDescriptor,td=(s,e,t,n)=>{for(var o=n>1?void 0:n?ed(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},De=(s,e)=>(t,n)=>e(t,n,s);g.SheetPermissionInitController=class extends i.Disposable{constructor(e,t,n,o,r,a,l,u,d,c){super(),this._univerInstanceService=e,this._permissionService=t,this._authzIoService=n,this._rangeProtectionRuleModel=o,this._worksheetProtectionRuleModel=r,this._userManagerService=a,this._worksheetProtectionPointRuleModel=l,this._workbookPermissionService=u,this._undoRedoService=d,this._commandService=c}initPermission(){this._initRangePermissionFromSnapshot(),this._initRangePermissionChange(),this._initWorksheetPermissionFromSnapshot(),this._initWorksheetPermissionChange(),this._initWorksheetPermissionPointsChange(),this._initWorkbookPermissionFromSnapshot(),this._initUserChange(),this._refreshPermissionByCollaCreate()}refreshRangeProtectPermission(){this._initRangePermissionFromSnapshot()}async _initRangePermissionFromSnapshot(){const e=async t=>{const n=[],o=t.getUnitId(),r=t.getSheets(),a=new Map;if(r.forEach(l=>{const u=l.getSheetId();this._rangeProtectionRuleModel.getSubunitRuleList(o,u).forEach(d=>{a.set(d.permissionId,d),n.push({objectID:d.permissionId,unitID:o,objectType:D.SelectRange,actions:Ge})})}),!n.length){this._rangeProtectionRuleModel.changeRuleInitState(!0);return}this._authzIoService.batchAllowed(n).then(l=>{l.forEach(u=>{const d=a.get(u.objectID);if(d){if(!this._rangeProtectionRuleModel.getRule(o,d.subUnitId,d.id))return;ue().forEach(m=>{const h=new m(o,d.subUnitId,u.objectID),R=h.subType,C=u.actions.find(S=>S.action===R);(C==null?void 0:C.allowed)!==void 0&&this._permissionService.updatePermissionPoint(h.id,C.allowed)})}}),this._rangeProtectionRuleModel.changeRuleInitState(!0)})};await Promise.all(this._univerInstanceService.getAllUnitsForType(i.UniverInstanceType.UNIVER_SHEET).map(t=>e(t))),this._rangeProtectionRuleModel.changeRuleInitState(!0)}_initRangePermissionChange(){this.disposeWithMe(this._rangeProtectionRuleModel.ruleChange$.subscribe(e=>{e.type!=="delete"?this._authzIoService.allowed({objectID:e.rule.permissionId,unitID:e.unitId,objectType:D.SelectRange,actions:Ge}).then(t=>{this._rangeProtectionRuleModel.getRule(e.unitId,e.subUnitId,e.rule.id)&&(ue().forEach(o=>{if(e.type==="set"){const{rule:d,oldRule:c}=e;if(d.permissionId===(c==null?void 0:c.permissionId))return}const r=e.rule,a=new o(r.unitId,r.subUnitId,r.permissionId),l=a.subType,u=t.find(d=>d.action===l);u&&this._permissionService.updatePermissionPoint(a.id,u.allowed)}),this._rangeProtectionRuleModel.ruleRefresh(e.rule.permissionId))}):this._rangeProtectionRuleModel.getSubunitRuleList(e.unitId,e.subUnitId).length===0&&(this._worksheetProtectionPointRuleModel.deleteRule(e.unitId,e.subUnitId),[...Ie()].forEach(n=>{const o=new n(e.unitId,e.subUnitId);this._permissionService.updatePermissionPoint(o.id,o.value)}))}))}async initWorkbookPermissionChange(e){var n;const t=e||((n=this._univerInstanceService.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET))==null?void 0:n.getUnitId());if(t)return this._authzIoService.allowed({objectID:t,objectType:D.Workbook,unitID:t,actions:ai}).then(o=>{Pt().forEach(r=>{const a=new r(t),l=a.subType,u=o.find(d=>d.action===l);u&&this._permissionService.updatePermissionPoint(a.id,u.allowed)})})}async _initWorkbookPermissionFromSnapshot(){await Promise.all(this._univerInstanceService.getAllUnitsForType(i.UniverInstanceType.UNIVER_SHEET).map(e=>this.initWorkbookPermissionChange(e.getUnitId()))),this._workbookPermissionService.changeUnitInitState(!0)}_initWorksheetPermissionChange(){this.disposeWithMe(this._worksheetProtectionRuleModel.ruleChange$.subscribe(e=>{e.type!=="delete"?this._authzIoService.allowed({objectID:e.rule.permissionId,unitID:e.unitId,objectType:D.Worksheet,actions:Ge}).then(t=>{const n=this._worksheetProtectionRuleModel.getRule(e.unitId,e.subUnitId);!n||n.permissionId!==e.rule.permissionId||(de().forEach(o=>{const r=new o(e.unitId,e.subUnitId),a=r.subType,l=t.find(u=>u.action===a);l&&this._permissionService.updatePermissionPoint(r.id,l.allowed)}),this._worksheetProtectionRuleModel.ruleRefresh(e.rule.permissionId))}):([...de(),...Ie()].forEach(t=>{const n=new t(e.unitId,e.subUnitId);this._permissionService.updatePermissionPoint(n.id,!0)}),this._worksheetProtectionPointRuleModel.deleteRule(e.unitId,e.subUnitId))}))}_initWorksheetPermissionPointsChange(){this.disposeWithMe(this._worksheetProtectionPointRuleModel.pointChange$.subscribe(e=>{this._authzIoService.allowed({objectID:e.permissionId,unitID:e.unitId,objectType:D.Worksheet,actions:_n}).then(t=>{const n=this._worksheetProtectionPointRuleModel.getRule(e.unitId,e.subUnitId);!n||n.permissionId!==e.permissionId||Ie().forEach(o=>{const r=new o(e.unitId,e.subUnitId),a=r.subType,l=t.find(u=>u.action===a);l&&this._permissionService.updatePermissionPoint(r.id,l.allowed)})})}))}async _initWorksheetPermissionFromSnapshot(){const e=async t=>{const n=[],o=t.getUnitId(),r=t.getSheets(),a=new Map;if(r.forEach(l=>{const u=l.getSheetId(),d=this._worksheetProtectionRuleModel.getRule(o,u);d&&(a.set(d.permissionId,d),n.push({objectID:d.permissionId,unitID:o,objectType:D.Worksheet,actions:Ge}));const c=this._worksheetProtectionPointRuleModel.getRule(o,u);c&&(a.set(c.permissionId,c),n.push({objectID:c.permissionId,unitID:o,objectType:D.Worksheet,actions:_n}))}),!n.length){this._worksheetProtectionRuleModel.changeRuleInitState(!0);return}this._authzIoService.batchAllowed(n).then(l=>{l.forEach(u=>{const d=a.get(u.objectID);if(d){const c=this._worksheetProtectionRuleModel.getRule(o,d.subUnitId)||this._worksheetProtectionPointRuleModel.getRule(o,d.subUnitId);if(!c||c.permissionId!==u.objectID)return;[...de(),...Ie()].forEach(m=>{const h=new m(o,d.subUnitId),R=h.subType,C=u.actions.find(S=>S.action===R);(C==null?void 0:C.allowed)!==void 0&&this._permissionService.updatePermissionPoint(h.id,C.allowed)})}}),this._worksheetProtectionRuleModel.changeRuleInitState(!0)})};await Promise.all(this._univerInstanceService.getAllUnitsForType(i.UniverInstanceType.UNIVER_SHEET).map(t=>e(t))),this._worksheetProtectionRuleModel.changeRuleInitState(!0)}_initUserChange(){this.disposeWithMe(this._userManagerService.currentUser$.pipe(O.skip(1)).subscribe(()=>{const e=this._permissionService.getAllPermissionPoint();this._permissionService.clearPermissionMap(),this._worksheetProtectionRuleModel.changeRuleInitState(!1),this._univerInstanceService.getAllUnitsForType(i.UniverInstanceType.UNIVER_SHEET).forEach(n=>{const o=n.getUnitId();Pt().forEach(r=>{let a=new r(o);e.has(a.id)&&(a=e.get(a.id)),this._permissionService.addPermissionPoint(a)}),n.getSheets().forEach(r=>{const a=r.getSheetId();[...de(),...Ie()].forEach(u=>{let d=new u(o,a);e.has(d.id)&&(d=e.get(d.id)),this._permissionService.addPermissionPoint(d)}),this._rangeProtectionRuleModel.getSubunitRuleList(o,a).forEach(u=>{ue().forEach(d=>{let c=new d(o,a,u.permissionId);e.has(c.id)&&(c=e.get(c.id)),this._permissionService.addPermissionPoint(c)})})}),this._initWorkbookPermissionFromSnapshot(),this._initWorksheetPermissionFromSnapshot(),this._initRangePermissionFromSnapshot()})}))}refreshPermission(e,t){const n=this._worksheetProtectionRuleModel.getTargetByPermissionId(e,t);let o=!1;if(n){const[l,u]=n;this._authzIoService.allowed({objectID:t,unitID:e,objectType:D.Worksheet,actions:Ge}).then(d=>{if(!this._worksheetProtectionRuleModel.getTargetByPermissionId(e,t))return;let m="";de().forEach(h=>{var I;const R=new h(e,u),C=R.subType,S=d.find(v=>v.action===C);S&&(((I=this._permissionService.getPermissionPoint(R.id))==null?void 0:I.value)!==S.allowed&&(o=!0),this._permissionService.updatePermissionPoint(R.id,S.allowed),m+=`${S.action}_${S.allowed}`)}),this._worksheetProtectionRuleModel.ruleRefresh(`${t}_${m}`),o&&this._undoRedoService.clearUndoRedo(e)})}const r=this._worksheetProtectionPointRuleModel.getTargetByPermissionId(e,t);if(r){const[l,u]=r;this._authzIoService.allowed({objectID:t,unitID:e,objectType:D.Worksheet,actions:_n}).then(d=>{this._worksheetProtectionPointRuleModel.getTargetByPermissionId(e,t)&&(Ie().forEach(m=>{var S;const h=new m(e,u),R=h.subType,C=d.find(I=>I.action===R);C&&(((S=this._permissionService.getPermissionPoint(h.id))==null?void 0:S.value)!==C.allowed&&(o=!0),this._permissionService.updatePermissionPoint(h.id,C.allowed))}),o&&this._undoRedoService.clearUndoRedo(e))})}const a=this._rangeProtectionRuleModel.getTargetByPermissionId(e,t);if(a){const[l,u]=a;this._authzIoService.allowed({objectID:t,unitID:e,objectType:D.SelectRange,actions:Ge}).then(d=>{if(!this._rangeProtectionRuleModel.getTargetByPermissionId(e,t))return;let m="";ue().forEach(h=>{var I;const R=new h(e,u,t),C=R.subType,S=d.find(v=>v.action===C);S&&(((I=this._permissionService.getPermissionPoint(R.id))==null?void 0:I.value)!==S.allowed&&(o=!0),this._permissionService.updatePermissionPoint(R.id,S.allowed),m+=`${S.action}_${S.allowed}`)}),this._rangeProtectionRuleModel.ruleRefresh(`${t}_${m}`),o&&this._undoRedoService.clearUndoRedo(e)})}}_refreshPermissionByCollaCreate(){this.disposeWithMe(this._commandService.onCommandExecuted((e,t)=>{if(t!=null&&t.fromCollab&&(e.id===Ce.id||e.id===Fe.id||e.id===bn.id)){const n=e.params;this._undoRedoService.clearUndoRedo(n.unitId)}}))}},g.SheetPermissionInitController=td([De(0,i.IUniverInstanceService),De(1,i.IPermissionService),De(2,i.IAuthzIoService),De(3,i.Inject(X)),De(4,i.Inject(ke)),De(5,i.Inject(i.UserManagerService)),De(6,i.Inject(Ut)),De(7,i.Inject(g.WorkbookPermissionService)),De(8,i.Inject(i.IUndoRedoService)),De(9,i.Inject(i.ICommandService))],g.SheetPermissionInitController);var nd=Object.getOwnPropertyDescriptor,sd=(s,e,t,n)=>{for(var o=n>1?void 0:n?nd(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},Js=(s,e)=>(t,n)=>e(t,n,s);g.ZebraCrossingCacheController=class extends i.Disposable{constructor(t,n,o){super();f(this,"_zebraCacheUpdateSubject",new O.Subject);this._commandService=t,this._sheetRangeThemeModel=n,this._univerInstanceService=o,this._init()}_init(){this._initializeCommandListener(),this._initTriggerCacheUpdateListener()}updateZebraCrossingCache(t,n){this._zebraCacheUpdateSubject.next({unitId:t,subUnitId:n})}_initializeCommandListener(){this.disposeWithMe(this._commandService.onCommandExecuted(t=>{const{id:n}=t;let o,r;switch(n){case re.id:{const a=t.params;o=a.unitId,r=a.subUnitId}break;case Ye.id:{const a=t.params;o=a.unitId,r=a.subUnitId}break;case Ke.id:{const a=t.params;o=a.unitId,r=a.subUnitId}break;case ae.id:{const a=t.params;o=a.unitId,r=a.subUnitId}break;case Ee.id:{const a=t.params;o=a.unitId,r=a.subUnitId}break}o&&r&&(this._sheetRangeThemeModel.refreshSheetRowVisibleFuncSet(o,r),this._sheetRangeThemeModel.refreshZebraCrossingCacheBySheet(o,r))}))}_initTriggerCacheUpdateListener(){this.disposeWithMe(this._zebraCacheUpdateSubject.subscribe(({unitId:t,subUnitId:n})=>{this._sheetRangeThemeModel.refreshSheetRowVisibleFuncSet(t,n),this._sheetRangeThemeModel.refreshZebraCrossingCacheBySheet(t,n)}))}},g.ZebraCrossingCacheController=sd([Js(0,i.Inject(i.ICommandService)),Js(1,i.Inject(g.SheetRangeThemeModel)),Js(2,i.Inject(i.IUniverInstanceService))],g.ZebraCrossingCacheController);var od=Object.getOwnPropertyDescriptor,rd=(s,e,t,n)=>{for(var o=n>1?void 0:n?od(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},bi=(s,e)=>(t,n)=>e(t,n,s);g.RangeProtectionRenderModel=class{constructor(e,t){f(this,"_cache",new i.LRUMap(1e4));this._selectionProtectionRuleModel=e,this._permissionService=t,this._init()}_init(){this._permissionService.permissionPointUpdate$.pipe(kt.filter(e=>e.type===D.SelectRange),kt.filter(e=>ue().some(t=>e instanceof t)),kt.map(e=>e)).subscribe(e=>{const t=this._selectionProtectionRuleModel.getSubunitRuleList(e.unitId,e.subUnitId);for(const n of t)n.permissionId===e.permissionId&&n.ranges.forEach(o=>{i.Range.foreach(o,(r,a)=>{const l=this._createKey(e.unitId,e.subUnitId,r,a);this._cache.delete(l)})})}),this._selectionProtectionRuleModel.ruleChange$.subscribe(e=>{var t;e.rule.ranges.forEach(n=>{i.Range.foreach(n,(o,r)=>{const a=this._createKey(e.unitId,e.subUnitId,o,r);this._cache.delete(a)})}),e.type==="set"&&((t=e.oldRule)==null||t.ranges.forEach(n=>{i.Range.foreach(n,(o,r)=>{const a=this._createKey(e.unitId,e.subUnitId,o,r);this._cache.delete(a)})}))})}_createKey(e,t,n,o){return`${e}_${t}_${n}_${o}`}getCellInfo(e,t,n,o){const r=this._selectionProtectionRuleModel.getSubunitRuleList(e,t),a=[];if(!r||!r.length)return a;const l=this._createKey(e,t,n,o),u=this._cache.get(l);if(u)return u;const d=[];for(const c of r)if(c.ranges.some(m=>m.startRow<=n&&m.endRow>=n&&m.startColumn<=o&&m.endColumn>=o)){const m=ue().reduce((h,R)=>{var I;const C=new R(e,t,c.permissionId),S=this._permissionService.getPermissionPoint(C.id);return h[C.subType]=(I=S==null?void 0:S.value)!=null?I:C.value,h},{});d.push({...m,ruleId:c.id,ranges:c.ranges})}return this._cache.set(l,d),d}clear(){this._cache.clear()}},g.RangeProtectionRenderModel=rd([bi(0,i.Inject(X)),bi(1,i.Inject(i.IPermissionService))],g.RangeProtectionRenderModel);var id=Object.getOwnPropertyDescriptor,ad=(s,e,t,n)=>{for(var o=n>1?void 0:n?id(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},xs=(s,e)=>(t,n)=>e(t,n,s);g.RangeProtectionCache=class extends i.Disposable{constructor(t,n,o){super();f(this,"_cellRuleCache",new Map);f(this,"_permissionIdCache",new Map);f(this,"_cellInfoCache",new Map);f(this,"_rowInfoCache",new Map);f(this,"_colInfoCache",new Map);this._ruleModel=t,this._permissionService=n,this._univerInstanceService=o,this._initUpdateCellRuleCache(),this._initUpdateCellInfoCache(),this._initUpdateRowColInfoCache(),this._initCache()}_initCache(){this._univerInstanceService.getAllUnitsForType(i.UniverInstanceType.UNIVER_SHEET).forEach(t=>{t.getSheets().forEach(n=>{const o=t.getUnitId(),r=n.getSheetId();this.reBuildCache(o,r)})})}_initUpdateCellInfoCache(){this._permissionService.permissionPointUpdate$.pipe(O.filter(t=>t.type===D.SelectRange),O.map(t=>t)).subscribe(t=>{const{subUnitId:n,unitId:o,permissionId:r}=t,a=this._permissionIdCache.get(r);if(!a)return;const l=this._ruleModel.getRule(o,n,a);if(!l)return;const u=this._ensureCellInfoMap(o,n);l.ranges.forEach(d=>{const{startRow:c,endRow:m,startColumn:h,endColumn:R}=d;for(let C=c;C<=m;C++)for(let S=h;S<=R;S++)u.delete(`${C}-${S}`)})}),this._ruleModel.ruleChange$.subscribe(t=>{var a;const{unitId:n,subUnitId:o}=t,r=this._ensureCellInfoMap(n,o);t.rule.ranges.forEach(l=>{i.Range.foreach(l,(u,d)=>{r.delete(`${u}-${d}`)})}),t.type==="set"&&((a=t.oldRule)==null||a.ranges.forEach(l=>{i.Range.foreach(l,(u,d)=>{this._cellInfoCache.delete(`${u}-${d}`)})}))})}_initUpdateCellRuleCache(){this._ruleModel.ruleChange$.subscribe(t=>{const{type:n}=t;n==="add"?this._addCellRuleCache(t):n==="delete"?this._deleteCellRuleCache(t):(this._deleteCellRuleCache({...t,rule:t.oldRule}),this._addCellRuleCache(t))})}_ensureRuleMap(t,n){let o=this._cellRuleCache.get(t);o||(o=new Map,this._cellRuleCache.set(t,o));let r=o.get(n);return r||(r=new Map,o.set(n,r)),r}_ensureCellInfoMap(t,n){let o=this._cellInfoCache.get(t);o||(o=new Map,this._cellInfoCache.set(t,o));let r=o.get(n);return r||(r=new Map,o.set(n,r)),r}_ensureRowColInfoMap(t,n,o){let r=o==="row"?this._rowInfoCache.get(t):this._colInfoCache.get(t);r||(r=new Map,o==="row"?this._rowInfoCache.set(t,r):this._colInfoCache.set(t,r));let a=r.get(n);return a||(a=new Map,r.set(n,a)),a}_addCellRuleCache(t){const{subUnitId:n,unitId:o,rule:r}=t,a=this._ensureRuleMap(o,n);r.ranges.forEach(l=>{const{startRow:u,endRow:d,startColumn:c,endColumn:m}=l;for(let h=u;h<=d;h++)for(let R=c;R<=m;R++)a.set(`${h}-${R}`,r.id)}),this._permissionIdCache.set(r.permissionId,r.id)}_deleteCellRuleCache(t){const{subUnitId:n,unitId:o,rule:r}=t,a=this._ensureRuleMap(o,n),l=this._ensureCellInfoMap(o,n);r.ranges.forEach(u=>{const{startRow:d,endRow:c,startColumn:m,endColumn:h}=u;for(let R=d;R<=c;R++)for(let C=m;C<=h;C++)a.delete(`${R}-${C}`),l.delete(`${R}-${C}`)}),this._permissionIdCache.delete(r.permissionId)}_getSelectionActions(t,n,o){var c,m,h,R,C,S,I,v,M,p,w,y;const r=(h=(m=this._permissionService.getPermissionPoint((c=new Se(t,n,o.permissionId))==null?void 0:c.id))==null?void 0:m.value)!=null?h:!1,a=(S=(C=this._permissionService.getPermissionPoint((R=new ln(t,n,o.permissionId))==null?void 0:R.id))==null?void 0:C.value)!=null?S:!1,l=(M=(v=this._permissionService.getPermissionPoint((I=new zs(t,n,o.permissionId))==null?void 0:I.id))==null?void 0:v.value)!=null?M:!1,u=(y=(w=this._permissionService.getPermissionPoint((p=new Gs(t,n,o.permissionId))==null?void 0:p.id))==null?void 0:w.value)!=null?y:!1;return{[_.Edit]:r,[_.View]:a,[_.ManageCollaborator]:l,[_.Delete]:u}}reBuildCache(t,n){const o=this._ensureRuleMap(t,n),r=this._ensureCellInfoMap(t,n);o.clear(),r.clear();const a=this._ensureRowColInfoMap(t,n,"row"),l=this._ensureRowColInfoMap(t,n,"col");a.clear(),l.clear(),this._ruleModel.getSubunitRuleList(t,n).forEach(u=>{const d=this._getSelectionActions(t,n,u),c={...d,ruleId:u.id,ranges:u.ranges};u.ranges.forEach(m=>{const{startRow:h,endRow:R,startColumn:C,endColumn:S}=m;for(let I=h;I<=R;I++){const v=a.get(`${I}`);v?v.set(u.id,d):a.set(`${I}`,new Map([[u.id,d]]));for(let M=C;M<=S;M++){o.set(`${I}-${M}`,u.id),r.set(`${I}-${M}`,c);const p=l.get(`${M}`);p?p.set(u.id,d):l.set(`${M}`,new Map([[u.id,d]]))}}}),this._permissionIdCache.set(u.permissionId,u.id)})}getRowPermissionInfo(t,n,o,r){var u;const a=(u=this._rowInfoCache.get(t))==null?void 0:u.get(n);if(!a)return!0;const l=a.get(`${o}`);return l?r.every(d=>{for(const c of l.values())if(c[d]===!1)return!1;return!0}):!0}getColPermissionInfo(t,n,o,r){var u;const a=(u=this._colInfoCache.get(t))==null?void 0:u.get(n);if(!a)return!0;const l=a.get(`${o}`);return l?r.every(d=>{for(const c of l.values())if(c[d]===!1)return!1;return!0}):!0}_initUpdateRowColInfoCache(){this._permissionService.permissionPointUpdate$.pipe(O.filter(t=>t.type===D.SelectRange),O.map(t=>t)).subscribe({next:t=>{const{subUnitId:n,unitId:o,permissionId:r}=t,a=this._permissionIdCache.get(r);if(!a)return;const l=this._ruleModel.getRule(o,n,a);if(!l)return;const u=this._ensureRowColInfoMap(o,n,"row"),d=this._ensureRowColInfoMap(o,n,"col"),c=this._getSelectionActions(o,n,l);l.ranges.forEach(m=>{const{startRow:h,endRow:R,startColumn:C,endColumn:S}=m;for(let I=h;I<=R;I++){const v=u.get(`${I}`);v?v.set(a,c):u.set(`${I}`,new Map([[a,c]]));for(let M=C;M<=S;M++){const p=d.get(`${M}`);p?p.set(a,c):d.set(`${M}`,new Map([[a,c]]))}}})}}),this._ruleModel.ruleChange$.subscribe(t=>{if(t.type==="delete"){const{unitId:n,subUnitId:o,rule:r}=t,a=this._ensureRowColInfoMap(n,o,"row"),l=this._ensureRowColInfoMap(n,o,"col");r.ranges.forEach(u=>{const{startRow:d,endRow:c,startColumn:m,endColumn:h}=u;for(let R=d;R<=c;R++){const C=a.get(`${R}`);C==null||C.delete(r.id);for(let S=m;S<=h;S++){const I=l.get(`${S}`);I==null||I.delete(r.id)}}})}})}getCellInfo(t,n,o,r){var c,m;const a=this._ensureCellInfoMap(t,n),l=a.get(`${o}-${r}`);if(l)return l;const u=(m=(c=this._cellRuleCache.get(t))==null?void 0:c.get(n))==null?void 0:m.get(`${o}-${r}`);if(!u)return;const d=this._ruleModel.getRule(t,n,u);if(d){const R={...this._getSelectionActions(t,n,d),ruleId:u,ranges:d.ranges};return a.set(`${o}-${r}`,R),R}}deleteUnit(t){this._cellRuleCache.delete(t),this._cellInfoCache.delete(t),this._rowInfoCache.delete(t),this._colInfoCache.delete(t);const n=this._univerInstanceService.getUnit(t);n==null||n.getSheets().forEach(o=>{const r=o.getSheetId();this._ruleModel.getSubunitRuleList(t,r).forEach(a=>{this._permissionIdCache.delete(a.permissionId)})})}},g.RangeProtectionCache=ad([xs(0,i.Inject(X)),xs(1,i.Inject(i.IPermissionService)),xs(2,i.Inject(i.IUniverInstanceService))],g.RangeProtectionCache);const Ei="ONLY_REGISTER_FORMULA_RELATED_MUTATIONS_KEY";var ld=Object.getOwnPropertyDescriptor,ud=(s,e,t,n)=>{for(var o=n>1?void 0:n?ld(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},Xs=(s,e)=>(t,n)=>e(t,n,s);let kn=class extends i.Disposable{constructor(s,e,t){var o;super(),this._commandService=s,this._configService=e,this._dataSyncPrimaryController=t,[F,ie,re,yt,Le,pe,we,ne,ae,Xe,G,Ys,j,Bs,qt,Un,Ot,Ci,Ke,Ye,Si,fi].forEach(r=>{var a;this._commandService.registerCommand(r),(a=this._dataSyncPrimaryController)==null||a.registerSyncingMutations(r)}),((o=this._configService.getConfig(Ei))!=null?o:!1)||[Tr,sn,fn,on,Os,Be,He,Gt,Kt,nr,tr,sr,or,ws,ye,xe,vt,Xo,xo,Qo,Zo,ps,Me,Or,wt,Je,pt,Ms,Lt,ys,$t,vn,Rn,Ar,Xr,Jr,xr,Lr,$r,bt,Wr,Vr,wn,lt,ut,zt,Br,at,Fr,Ne,jr,Qr,It,Jt,Mn,qr,ct,Ws,Ls,Et,Tt,ee,ni,jt,Kr,ti,ei,Zr,Hs,Fs,Ct,ii,je,yn,js,Yt,jn,Ee,Tn,Re,Ve,di,gt,si,mt,Lo,q,pi,Nr,Ds,Vs,qs,hi,Rt,Gr,dt,li,Fe,st,tt,bn,Oo,zr,Ur,br,Pr,ui,Ce,Te,Q,mi,ht,oi,ci,it,rt,In,_t,gi,Dr,Er,kr,Ri,vi,Ii].forEach(r=>this.disposeWithMe(this._commandService.registerCommand(r))),this._configService.setConfig(wi,Hu)}};kn=ud([Xs(0,i.ICommandService),Xs(1,i.IConfigService),Xs(2,i.Optional($i.DataSyncPrimaryController))],kn);var dd=Object.getOwnPropertyDescriptor,cd=(s,e,t,n)=>{for(var o=n>1?void 0:n?dd(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},Ti=(s,e)=>(t,n)=>e(t,n,s);let Nn=class extends i.Disposable{constructor(s,e){super(),this._univerInstanceService=s,this._commandService=e,this._initialize()}_initialize(){this.disposeWithMe(this._commandService.onCommandExecuted(s=>{if(s.id!==J.SetFormulaCalculationResultMutation.id)return;const e=s.params,{unitData:t}=e,n=Object.keys(t),o=[];for(let a=0;a<n.length;a++){const l=n[a],u=t[l];if(u==null)continue;const d=Object.keys(u);for(let c=0;c<d.length;c++){const m=d[c],h=u[m];if(h==null)continue;const R=this._getMergedCellData(l,m,h),C={subUnitId:m,unitId:l,cellValue:R};o.push({id:F.id,params:C})}}return o.every(a=>this._commandService.executeCommand(a.id,a.params,{onlyLocal:!0,fromFormula:!0}))}))}_getMergedCellData(s,e,t){const n=this._univerInstanceService.getUniverSheetInstance(s),o=n==null?void 0:n.getStyles(),r=n==null?void 0:n.getSheetBySheetId(e),a=r==null?void 0:r.getCellMatrix(),l=new i.ObjectMatrix(t);return l.forValue((u,d,c)=>{const m=a==null?void 0:a.getValue(u,d),h=J.handleNumfmtInCell(m,c,o);l.setValue(u,d,h)}),l.getMatrix()}};Nn=cd([Ti(0,i.Inject(i.IUniverInstanceService)),Ti(1,i.ICommandService)],Nn);var md=Object.getOwnPropertyDescriptor,hd=(s,e,t,n)=>{for(var o=n>1?void 0:n?md(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},gd=(s,e)=>(t,n)=>e(t,n,s);let On=class extends i.Disposable{constructor(s){super(),this._sheetInterceptorService=s,this._initialize()}_initialize(){this._initInterceptorCellContent()}_initInterceptorCellContent(){this.disposeWithMe(this._sheetInterceptorService.intercept(Ae.CELL_CONTENT,{priority:11,effect:i.InterceptorEffectEnum.Value|i.InterceptorEffectEnum.Style,handler:(s,e,t)=>{var o;if(!s)return t(s);const n=e.workbook.getStyles().getStyleByCell(s);return i.isDefaultFormat((o=n==null?void 0:n.n)==null?void 0:o.pattern)&&(s==null?void 0:s.t)===i.CellValueType.NUMBER&&s.v!==void 0&&s.v!==null&&i.isRealNum(s.v)&&((!s||s===e.rawData)&&(s={...e.rawData}),s.v=J.stripErrorMargin(Number(s.v))),t(s)}}))}};On=hd([gd(0,i.Inject(g.SheetInterceptorService))],On);var Rd=Object.getOwnPropertyDescriptor,Cd=(s,e,t,n)=>{for(var o=n>1?void 0:n?Rd(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},Dn=(s,e)=>(t,n)=>e(t,n,s);let An=class extends i.Disposable{constructor(s,e,t,n){super(),this._permissionService=s,this._worksheetProtectionRuleModel=e,this._sheetInterceptorService=t,this._rangeProtectionCache=n,this._initViewModelByRangeInterceptor(),this._initViewModelBySheetInterceptor()}_initViewModelByRangeInterceptor(){this.disposeWithMe(this._sheetInterceptorService.intercept(Ae.CELL_CONTENT,{priority:999,effect:i.InterceptorEffectEnum.Value|i.InterceptorEffectEnum.Style,handler:(s,e,t)=>{const{unitId:n,subUnitId:o,row:r,col:a}=e,l=this._rangeProtectionCache.getCellInfo(n,o,r,a);if(l){const u=l[_.View]===!1,d=!s||s===e.rawData?{...e.rawData}:s;return d.selectionProtection=[l],u?(delete d.s,delete d.v,delete d.p,d):t(d)}return t(s)}}))}_initViewModelBySheetInterceptor(){this.disposeWithMe(this._sheetInterceptorService.intercept(Ae.CELL_CONTENT,{priority:999,effect:i.InterceptorEffectEnum.Value|i.InterceptorEffectEnum.Style,handler:(s,e,t)=>{var a,l,u,d,c;const{unitId:n,subUnitId:o}=e,r=this._worksheetProtectionRuleModel.getRule(n,o);if(r!=null&&r.permissionId){const m=[{[_.View]:(l=(a=this._permissionService.getPermissionPoint(new Vt(n,o).id))==null?void 0:a.value)!=null?l:!1,[_.Edit]:(d=(u=this._permissionService.getPermissionPoint(new fe(n,o).id))==null?void 0:u.value)!=null?d:!1}],h=!((c=m[0])!=null&&c[_.View]),R=!s||s===e.rawData?{...s}:s;return R.hasWorksheetRule=!0,R.selectionProtection=m,h?(delete R.s,delete R.v,delete R.p,R):t(R)}return t(s)}}))}};An=Cd([Dn(0,i.IPermissionService),Dn(1,i.Inject(ke)),Dn(2,i.Inject(g.SheetInterceptorService)),Dn(3,i.Inject(g.RangeProtectionCache))],An);const Zs=i.createIdentifier("univer.exclusive-range-service");class Ui extends i.Disposable{constructor(){super(...arguments);f(this,"_exclusiveRanges",new Map);f(this,"_exclusiveRangesChange$",new O.Subject);f(this,"exclusiveRangesChange$",this._exclusiveRangesChange$.asObservable())}_ensureUnitMap(t){return this._exclusiveRanges.has(t)||this._exclusiveRanges.set(t,new Map),this._exclusiveRanges.get(t)}_ensureSubunitMap(t,n){const o=this._ensureUnitMap(t);return o.has(n)||o.set(n,new Map),o.get(n)}_ensureFeature(t,n,o){const r=this._ensureSubunitMap(t,n);return r.has(o)||r.set(o,[]),r.get(o)}addExclusiveRange(t,n,o,r){const a=this._ensureFeature(t,n,o);a.push(...r),this._exclusiveRangesChange$.next({unitId:t,subUnitId:n,ranges:a.map(l=>l.range)})}getExclusiveRanges(t,n,o){var r,a;return(a=(r=this._exclusiveRanges.get(t))==null?void 0:r.get(n))==null?void 0:a.get(o)}clearExclusiveRanges(t,n,o){const r=this.getExclusiveRanges(t,n,o);this._exclusiveRangesChange$.next({unitId:t,subUnitId:n,ranges:(r==null?void 0:r.map(a=>a.range))||[]}),this._ensureFeature(t,n,o),this._exclusiveRanges.get(t).get(n).set(o,[])}clearExclusiveRangesByGroupId(t,n,o,r){const a=this.getExclusiveRanges(t,n,o);this._exclusiveRangesChange$.next({unitId:t,subUnitId:n,ranges:(a==null?void 0:a.map(u=>u.range))||[]});const l=this.getExclusiveRanges(t,n,o);if(l){const u=l.filter(d=>d.groupId!==r);this._exclusiveRanges.get(t).get(n).set(o,u)}}getInterestGroupId(t){const n=[];return t.forEach(o=>{var d;const r=o.range,{unitId:a,sheetId:l}=r;if(!a||!l)return;const u=(d=this._exclusiveRanges.get(a))==null?void 0:d.get(l);if(u)for(const c of u.keys()){const m=u.get(c);if(m){for(const h of m)if(i.Rectangle.intersects(r,h.range)){n.push(c);break}}}}),n}}var Sd=Object.getOwnPropertyDescriptor,fd=(s,e,t,n)=>{for(var o=n>1?void 0:n?Sd(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},Qs=(s,e)=>(t,n)=>e(t,n,s);g.NumfmtService=class extends i.Disposable{constructor(e,t,n){super(),this._resourceManagerService=e,this._univerInstanceService=t,this._logService=n}getValue(e,t,n,o){const r=this._univerInstanceService.getUniverSheetInstance(e);if(!r)return;const a=r==null?void 0:r.getSheetBySheetId(t);if(!a)return;const l=r.getStyles(),u=a.getCellRaw(n,o);if(u!=null&&u.s){const d=l.get(u.s);if(d!=null&&d.n)return d.n}return null}deleteValues(e,t,n){const o=this._univerInstanceService.getUniverSheetInstance(e);if(!o)return;const r=o==null?void 0:o.getSheetBySheetId(t);if(!r)return;const a=o.getStyles();n.forEach(l=>{i.Range.foreach(l,(u,d)=>{const c=r.getCellRaw(u,d);if(!c)return;const m=c==null?void 0:c.s,R={...m&&a.get(m)||{}};delete R.n;const C=a.setValue(R);c.s=C})})}setValues(e,t,n){const o=this._univerInstanceService.getUniverSheetInstance(e);if(!o)return;const r=o==null?void 0:o.getSheetBySheetId(t);if(!r)return;const a=o.getStyles(),l=r.getCellMatrix();n.forEach(u=>{u.ranges.forEach(d=>{i.Range.foreach(d,(c,m)=>{const h=r.getCellRaw(c,m);if(h){const C={...a.getStyleByCell(h)||{},n:{pattern:u.pattern}},S=a.setValue(C);h.s=S}else{const R={n:{pattern:u.pattern}},C=a.setValue(R);C&&l.setValue(c,m,{s:C})}})})})}},g.NumfmtService=fd([Qs(0,i.IResourceManagerService),Qs(1,i.IUniverInstanceService),Qs(2,i.ILogService)],g.NumfmtService);var Id=Object.getOwnPropertyDescriptor,vd=(s,e,t,n)=>{for(var o=n>1?void 0:n?Id(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},qe=(s,e)=>(t,n)=>e(t,n,s);const Pi=[ie.id,re.id,ne.id,ae.id],ki=[pe.id,we.id];g.RangeProtectionRefRangeService=class extends i.Disposable{constructor(t,n,o,r,a,l,u,d){super();f(this,"disposableCollection",new i.DisposableCollection);this._selectionProtectionRuleModel=t,this._univerInstanceService=n,this._commandService=o,this._refRangeService=r,this._selectionProtectionRenderModel=a,this._rangeProtectionCache=l,this._sheetInterceptorService=u,this._rangeProtectionRuleModel=d,this._onRefRangeChange(),this._correctPermissionRange(),this._initReBuildCache(),this._initRemoveSheet()}_onRefRangeChange(){const t=(o,r)=>{const a=this._univerInstanceService.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET);if(!a||!(a==null?void 0:a.getSheetBySheetId(r)))return;this.disposableCollection.dispose();const u=c=>this.refRangeHandle(c,o,r);this._selectionProtectionRuleModel.getSubunitRuleList(o,r).reduce((c,m)=>[...c,...m.ranges],[]).forEach(c=>{this.disposableCollection.add(this._refRangeService.registerRefRange(c,u,o,r))})};this.disposeWithMe(this._commandService.onCommandExecuted(o=>{if(o.id===Fs.id){const r=o.params,a=r.subUnitId,l=r.unitId;if(!a||!l)return;t(l,a)}if(o.id===Q.id||o.id===Ce.id){const r=o.params,a=r.subUnitId,l=r.unitId;if(!a||!l)return;t(l,a)}}));const n=this._univerInstanceService.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET);if(n){const o=n.getActiveSheet();if(!o)return;t(n.getUnitId(),o.getSheetId())}}refRangeHandle(t,n,o){switch(t.id){case pt.id:return this._getRefRangeMutationsByMoveRows(t.params,n,o);case wt.id:return this._getRefRangeMutationsByMoveCols(t.params,n,o);case Me.id:return this._getRefRangeMutationsByInsertRows(t.params,n,o);case ye.id:return this._getRefRangeMutationsByInsertCols(t.params,n,o);case Lt.id:return this._getRefRangeMutationsByDeleteCols(t.params,n,o);case $t.id:return this._getRefRangeMutationsByDeleteRows(t.params,n,o)}return{redos:[],undos:[]}}_getRefRangeMutationsByDeleteCols(t,n,o){const r=this._selectionProtectionRuleModel.getSubunitRuleList(n,o).filter(l=>l.ranges.some(u=>i.Rectangle.intersects(u,t.range))),a=t.range;if(r.length){const l=[],u=[];return r.forEach(d=>{const c=i.Tools.deepClone(d),m=c.ranges.reduce((h,R)=>{if(i.Rectangle.intersects(R,a)){const C=i.Tools.deepClone(R),{startColumn:S,endColumn:I}=a;if(S<=C.startColumn&&I>=C.endColumn)return h;S>=C.startColumn&&I<=C.endColumn?C.endColumn-=I-S+1:S<C.startColumn?(C.startColumn=S,C.endColumn-=I-S+1):I>C.endColumn&&(C.endColumn=S-1),this._checkIsRightRange(C)&&h.push(C)}return h},[]);c.ranges=m,c.ranges.length?(l.push({id:Q.id,params:{unitId:n,subUnitId:o,rule:c,ruleId:d.id}}),u.push({id:Q.id,params:{unitId:n,subUnitId:o,rule:d,ruleId:d.id}})):(l.push({id:Te.id,params:{unitId:n,subUnitId:o,ruleIds:[d.id]}}),u.push({id:Ce.id,params:{unitId:n,subUnitId:o,name:"",rules:[d]}}))}),{redos:l,undos:u}}return{undos:[],redos:[]}}_getRefRangeMutationsByDeleteRows(t,n,o){const r=this._selectionProtectionRuleModel.getSubunitRuleList(n,o).filter(l=>l.ranges.some(u=>i.Rectangle.intersects(u,t.range))),a=t.range;if(r.length){const l=[],u=[];return r.forEach(d=>{const c=i.Tools.deepClone(d),m=c.ranges.reduce((h,R)=>{if(i.Rectangle.intersects(R,a)){const C=i.Tools.deepClone(R),{startRow:S,endRow:I}=a;if(S<=C.startRow&&I>=C.endRow)return h;S>=C.startRow&&I<=C.endRow?C.endRow-=I-S+1:S<C.startRow?(C.startRow=S,C.endRow-=I-S+1):I>C.endRow&&(C.endRow=S-1),this._checkIsRightRange(C)&&h.push(C)}return h},[]);c.ranges=m,l.push({id:Q.id,params:{unitId:n,subUnitId:o,rule:c,ruleId:d.id}}),u.push({id:Q.id,params:{unitId:n,subUnitId:o,rule:d,ruleId:d.id}})}),{redos:l,undos:u}}return{undos:[],redos:[]}}_getRefRangeMutationsByInsertCols(t,n,o){const r=t.range.startColumn,a=t.range.endColumn-t.range.startColumn+1,l=this._selectionProtectionRuleModel.getSubunitRuleList(n,o).filter(u=>u.ranges.some(d=>r>d.startColumn&&r<=d.endColumn));if(l.length){const u=[],d=[];return l.forEach(c=>{const m=i.Tools.deepClone(c);let h=!1;m.ranges.forEach(R=>{r>R.startColumn&&r<=R.endColumn&&(R.endColumn+=a,h=!0)}),h&&(u.push({id:Q.id,params:{unitId:n,subUnitId:o,rule:m,ruleId:c.id}}),d.push({id:Q.id,params:{unitId:n,subUnitId:o,rule:c,ruleId:c.id}}))}),{redos:u,undos:d}}return{undos:[],redos:[]}}_getRefRangeMutationsByInsertRows(t,n,o){const r=t.range.startRow,a=t.range.endRow-t.range.startRow+1,l=this._selectionProtectionRuleModel.getSubunitRuleList(n,o).filter(u=>u.ranges.some(d=>r>d.startRow&&r<=d.endRow));if(l.length){const u=[],d=[];return l.forEach(c=>{const m=i.Tools.deepClone(c);let h=!1;m.ranges.forEach(R=>{r>R.startRow&&r<=R.endRow&&(R.endRow+=a,h=!0)}),h&&(u.push({id:Q.id,params:{unitId:n,subUnitId:o,rule:m,ruleId:c.id}}),d.push({id:Q.id,params:{unitId:n,subUnitId:o,rule:c,ruleId:c.id}}))}),{redos:u,undos:d}}return{undos:[],redos:[]}}_getRefRangeMutationsByMoveRows(t,n,o){const r=t.toRange,a=r.startRow,l=r.endRow-r.startRow+1,u=this._selectionProtectionRuleModel.getSubunitRuleList(n,o).filter(d=>d.ranges.some(c=>a>c.startRow&&a<=c.endRow));if(u.length){const d=[],c=[];return u.forEach(m=>{const h=i.Tools.deepClone(m),C=t.fromRange.startRow;let S=!1;h.ranges.forEach(I=>{a>I.startRow&&a<=I.endRow&&(C<I.startRow&&(I.startRow=I.startRow-l,I.endRow=I.endRow-l),I.endRow+=l,S=!0)}),S&&(d.push({id:Q.id,params:{unitId:n,subUnitId:o,rule:h,ruleId:m.id}}),c.push({id:Q.id,params:{unitId:n,subUnitId:o,rule:m,ruleId:m.id}}))}),{redos:d,undos:c}}return{undos:[],redos:[]}}_getRefRangeMutationsByMoveCols(t,n,o){const r=t.toRange,a=r.startColumn,l=r.endColumn-r.startColumn+1,u=this._selectionProtectionRuleModel.getSubunitRuleList(n,o).filter(d=>d.ranges.some(c=>a>c.startColumn&&a<=c.endColumn));if(u.length){const d=[],c=[];return u.forEach(m=>{const h=i.Tools.deepClone(m),C=t.fromRange.startColumn;let S=!1;h.ranges.forEach(I=>{a>I.startColumn&&a<=I.endColumn&&(C<I.startColumn&&(I.startColumn=I.startColumn-l,I.endColumn=I.endColumn-l),I.endColumn+=l,S=!0)}),S&&(d.push({id:Q.id,params:{unitId:n,subUnitId:o,rule:h,ruleId:m.id}}),c.push({id:Q.id,params:{unitId:n,subUnitId:o,rule:m,ruleId:m.id}}))}),{redos:d,undos:c}}return{undos:[],redos:[]}}_correctPermissionRange(){this.disposeWithMe(this._commandService.onCommandExecuted(t=>{if(ki.includes(t.id)){if(!t.params)return;const n=this._univerInstanceService.getCurrentUnitForType(i.UniverInstanceType.UNIVER_SHEET);if(!n)return;const o=n.getSheetBySheetId(t.params.subUnitId);if(!o)return;const{sourceRange:r,targetRange:a}=t.params,l=r.startColumn===a.startColumn&&r.endColumn===a.endColumn,u=l?r.endRow-r.startRow+1:r.endColumn-r.startColumn+1,d=l?r.startRow:r.startColumn,c=l?a.startRow:a.startColumn;this._selectionProtectionRuleModel.getSubunitRuleList(n.getUnitId(),o.getSheetId()).forEach(I=>{I.ranges.forEach(M=>{let{startRow:p,endRow:w,startColumn:y,endColumn:b}=M;i.Rectangle.intersects(M,r)||(l?d<p&&c>w?(p-=u,w-=u):d>w&&c<=p&&(p+=u,w+=u):d<y&&c>b?(y-=u,b-=u):d>b&&c<=y&&(y+=u,b+=u)),this._checkIsRightRange({startRow:p,endRow:w,startColumn:y,endColumn:b})&&(M.startColumn=y,M.endColumn=b,M.startRow=p,M.endRow=w)})}),this.disposableCollection.dispose();const{unitId:h,subUnitId:R}=t.params,C=I=>this.refRangeHandle(I,h,R);this._selectionProtectionRuleModel.getSubunitRuleList(h,R).reduce((I,v)=>[...I,...v.ranges],[]).forEach(I=>{this.disposableCollection.add(this._refRangeService.registerRefRange(I,C,h,R))}),this._selectionProtectionRenderModel.clear()}if(Pi.includes(t.id)){const n=this._univerInstanceService.getUniverSheetInstance(t.params.unitId);if(!n)return;const o=n.getSheetBySheetId(t.params.subUnitId);if(!o)return;const r=t.params;if(!r)return;const{range:a}=r,l=t.id.includes("row"),u=t.id.includes("insert"),d=l?a.startRow:a.startColumn,c=l?a.endRow:a.endColumn,m=c-d+1;this._selectionProtectionRuleModel.getSubunitRuleList(n.getUnitId(),o.getSheetId()).forEach(v=>{v.ranges.forEach(p=>{let{startRow:w,endRow:y,startColumn:b,endColumn:T}=p;u?l?d<=w&&(w+=m,y+=m):d<=b&&(b+=m,T+=m):l?c<w&&(w-=m,y-=m):c<b&&(b-=m,T-=m),this._checkIsRightRange({startRow:w,endRow:y,startColumn:b,endColumn:T})&&(p.startColumn=b,p.endColumn=T,p.startRow=w,p.endRow=y)})}),this.disposableCollection.dispose();const{unitId:R,subUnitId:C}=t.params,S=v=>this.refRangeHandle(v,R,C);this._selectionProtectionRuleModel.getSubunitRuleList(R,C).reduce((v,M)=>[...v,...M.ranges],[]).forEach(v=>{this.disposableCollection.add(this._refRangeService.registerRefRange(v,S,R,C))}),this._selectionProtectionRenderModel.clear()}}))}_checkIsRightRange(t){return t.startRow<=t.endRow&&t.startColumn<=t.endColumn}_initReBuildCache(){this.disposeWithMe(this._commandService.onCommandExecuted(t=>{if(Pi.includes(t.id)||ki.includes(t.id)){const{unitId:n,subUnitId:o}=t.params;this._rangeProtectionCache.reBuildCache(n,o)}}))}_initRemoveSheet(){this._sheetInterceptorService.interceptCommand({getMutations:t=>{const n=[],o=[],r=[],a=[];if(t.id===vn.id){const l=t.params,u=[],d=[];this._rangeProtectionRuleModel.getSubunitRuleList(l.unitId,l.subUnitId).forEach(c=>{u.push(c.id),d.push(c)}),u.length&&d.length&&(r.push({id:Te.id,params:{unitId:l.unitId,subUnitId:l.subUnitId,ruleIds:u}}),n.push({id:Ce.id,params:{unitId:l.unitId,subUnitId:l.subUnitId,name:"",rules:d}}))}return{redos:o,undos:n,preRedos:r,preUndos:a}}})}},g.RangeProtectionRefRangeService=vd([qe(0,i.Inject(X)),qe(1,i.Inject(i.IUniverInstanceService)),qe(2,i.ICommandService),qe(3,i.Inject(g.RefRangeService)),qe(4,i.Inject(g.RangeProtectionRenderModel)),qe(5,i.Inject(g.RangeProtectionCache)),qe(6,i.Inject(g.SheetInterceptorService)),qe(7,i.Inject(X))],g.RangeProtectionRefRangeService);var pd=Object.getOwnPropertyDescriptor,wd=(s,e,t,n)=>{for(var o=n>1?void 0:n?pd(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},Xt=(s,e)=>(t,n)=>e(t,n,s);const Md="SHEET_RANGE_PROTECTION_PLUGIN";g.RangeProtectionService=class extends i.Disposable{constructor(e,t,n,o,r){super(),this._selectionProtectionRuleModel=e,this._permissionService=t,this._resourceManagerService=n,this._selectionProtectionCache=o,this._univerInstanceService=r,this._initSnapshot(),this._initRuleChange()}_initRuleChange(){this.disposeWithMe(this._selectionProtectionRuleModel.ruleChange$.subscribe(e=>{switch(e.type){case"add":{ue().forEach(t=>{const n=new t(e.unitId,e.subUnitId,e.rule.permissionId);this._permissionService.addPermissionPoint(n)});break}case"delete":{ue().forEach(t=>{const n=new t(e.unitId,e.subUnitId,e.rule.permissionId);this._permissionService.deletePermissionPoint(n.id)});break}case"set":{e.oldRule.permissionId!==e.rule.permissionId&&ue().forEach(t=>{const n=new t(e.unitId,e.subUnitId,e.oldRule.permissionId);this._permissionService.deletePermissionPoint(n.id);const o=new t(e.unitId,e.subUnitId,e.rule.permissionId);this._permissionService.addPermissionPoint(o)});break}}}))}_initSnapshot(){const e=n=>{const r=this._selectionProtectionRuleModel.toObject()[n];return r?JSON.stringify(r):""},t=n=>{if(!n)return{};try{return JSON.parse(n)}catch{return{}}};this.disposeWithMe(this._resourceManagerService.registerPluginResource({toJson:e,parseJson:t,pluginName:Md,businesses:[an.UNIVER_SHEET],onLoad:(n,o)=>{const r=this._selectionProtectionRuleModel.toObject();r[n]=o,this._selectionProtectionRuleModel.fromObject(r);const a=[];Object.keys(o).forEach(l=>{const u=o[l];this._selectionProtectionRuleModel.getSubunitRuleList(n,l).forEach(d=>{a.push({objectID:d.permissionId,unitID:n,objectType:D.SelectRange,actions:Ge})}),u.forEach(d=>{ue().forEach(c=>{const m=new c(n,l,d.permissionId);m.value=!1,this._permissionService.addPermissionPoint(m)})}),this._selectionProtectionCache.reBuildCache(n,l)})},onUnLoad:n=>{this._selectionProtectionCache.deleteUnit(n)}}))}},g.RangeProtectionService=wd([Xt(0,i.Inject(X)),Xt(1,i.Inject(i.IPermissionService)),Xt(2,i.Inject(i.IResourceManagerService)),Xt(3,i.Inject(g.RangeProtectionCache)),Xt(4,i.Inject(i.IUniverInstanceService))],g.RangeProtectionService);var yd=Object.getOwnPropertyDescriptor,_d=(s,e,t,n)=>{for(var o=n>1?void 0:n?yd(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},bd=(s,e)=>(t,n)=>e(t,n,s);g.SheetRangeThemeService=class extends i.Disposable{constructor(e){super(),this._sheetRangeThemeModel=e}registerRangeTheme(e,t){this._sheetRangeThemeModel.registerRangeThemeStyle(e,t)}removeRangeThemeRule(e,t){this._sheetRangeThemeModel.removeRangeThemeRule(e,t)}getALLRegisterThemes(e){return this._sheetRangeThemeModel.getALLRegisteredTheme(e)}registerRangeThemeStyle(e,t){this._sheetRangeThemeModel.registerRangeThemeRule(e,t)}getAppliedRangeThemeStyle(e){return this._sheetRangeThemeModel.getRegisteredRangeThemeStyle(e)}getRegisteredRangeThemes(){return this._sheetRangeThemeModel.getRegisteredRangeThemes()}},g.SheetRangeThemeService=_d([bd(0,i.Inject(g.SheetRangeThemeModel))],g.SheetRangeThemeService);var Ed=Object.defineProperty,Td=Object.getOwnPropertyDescriptor,Ud=(s,e,t)=>e in s?Ed(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Pd=(s,e,t,n)=>{for(var o=n>1?void 0:n?Td(e,t):e,r=s.length-1,a;r>=0;r--)(a=s[r])&&(o=a(o)||o);return o},Ni=(s,e)=>(t,n)=>e(t,n,s),Oi=(s,e,t)=>Ud(s,typeof e!="symbol"?e+"":e,t);const kd="SHEET_PLUGIN";g.UniverSheetsPlugin=class extends i.Plugin{constructor(e=_i,t,n){super(),this._config=e,this._injector=t,this._configService=n;const{...o}=i.merge({},_i,this._config);this._configService.setConfig(yi,o),this._initConfig(),this._initDependencies()}_initConfig(){var e,t,n;(e=this._config)!=null&&e.onlyRegisterFormulaRelatedMutations&&this._configService.setConfig(Ei,!0),(t=this._config)!=null&&t.isRowStylePrecedeColumnStyle&&this._configService.setConfig(i.IS_ROW_STYLE_PRECEDE_COLUMN_STYLE,!0),(n=this._config)!=null&&n.autoHeightForMergedCells&&this._configService.setConfig(i.AUTO_HEIGHT_FOR_MERGED_CELLS,!0)}_initDependencies(){var t;const e=[[nt],[g.SheetsSelectionsService],[g.RefRangeService],[g.WorkbookPermissionService],[ot,{useClass:g.NumfmtService}],[g.SheetInterceptorService],[g.SheetRangeThemeService],[g.SheetSkeletonService],[kn],[g.MergeCellController],[On],[g.DefinedNameDataController],[g.ZebraCrossingCacheController],[g.SheetsFreezeSyncController],[g.WorksheetPermissionService],[ke],[Ut],[An],[g.SheetPermissionInitController],[g.SheetPermissionCheckController],[g.SheetRangeThemeModel],[g.RangeProtectionRenderModel],[X],[g.RangeProtectionCache],[g.RangeProtectionRefRangeService],[g.RangeProtectionService],[Zs,{useClass:Ui,deps:[g.SheetsSelectionsService]}]];(t=this._config)!=null&&t.notExecuteFormula||e.push([Nn]),i.registerDependencies(this._injector,i.mergeOverrideWithDependencies(e,this._config.override)),i.touchDependencies(this._injector,[[g.SheetInterceptorService],[g.RangeProtectionService],[Zs],[g.SheetPermissionInitController],[g.SheetsFreezeSyncController]])}onStarting(){i.touchDependencies(this._injector,[[kn],[g.MergeCellController],[g.WorkbookPermissionService],[g.WorksheetPermissionService],[An],[g.SheetSkeletonService]])}onRendered(){i.touchDependencies(this._injector,[[ot]])}onReady(){i.touchDependencies(this._injector,[[Nn],[g.DefinedNameDataController],[g.ZebraCrossingCacheController],[g.SheetRangeThemeModel],[On],[g.RangeProtectionRenderModel],[g.RangeProtectionRefRangeService],[g.RefRangeService],[g.SheetPermissionCheckController]])}},Oi(g.UniverSheetsPlugin,"pluginName",kd),Oi(g.UniverSheetsPlugin,"type",i.UniverInstanceType.UNIVER_SHEET),g.UniverSheetsPlugin=Pd([i.DependentOn(J.UniverFormulaEnginePlugin),Ni(1,i.Inject(i.Injector)),Ni(2,i.IConfigService)],g.UniverSheetsPlugin);const Nd={WorkbookCommentPermission:Yn,WorkbookCopyPermission:Kn,WorkbookCreateProtectPermission:Jn,WorkbookCreateSheetPermission:xn,WorkbookDeleteSheetPermission:Xn,WorkbookDuplicatePermission:Zn,WorkbookEditablePermission:me,WorkbookExportPermission:Qn,WorkbookHideSheetPermission:un,WorkbookHistoryPermission:Go,WorkbookManageCollaboratorPermission:dn,WorkbookMoveSheetPermission:cn,WorkbookPrintPermission:es,WorkbookRecoverHistoryPermission:ts,WorkbookRenameSheetPermission:mn,WorkbookSharePermission:ns,WorkbookViewHistoryPermission:os,WorkbookViewPermission:ss,WorksheetCopyPermission:rs,WorksheetDeleteColumnPermission:is,WorksheetDeleteProtectionPermission:as,WorksheetDeleteRowPermission:ls,WorksheetEditExtraObjectPermission:us,WorksheetEditPermission:fe,WorksheetFilterPermission:ds,WorksheetInsertColumnPermission:cs,WorksheetInsertHyperlinkPermission:ms,WorksheetInsertRowPermission:hs,WorksheetManageCollaboratorPermission:gs,WorksheetPivotTablePermission:Rs,WorksheetSetCellStylePermission:Cs,WorksheetSetCellValuePermission:Wt,WorksheetSetColumnStylePermission:St,WorksheetSetRowStylePermission:ft,WorksheetSortPermission:Ss,WorksheetViewPermission:Vt,RangeProtectionPermissionEditPoint:Se,RangeProtectionPermissionViewPoint:ln},Od=(s,e,t,n)=>{const o=s.get(i.IPermissionService),r=s.get(X),a=o.getPermissionPoint(new me(e).id);if(!(a!=null&&a.value))return!1;const l=o.getPermissionPoint(new fe(e,t).id);if(!(l!=null&&l.value))return!1;const d=r.getSubunitRuleList(e,t).filter(c=>c.ranges.some(m=>n.some(h=>i.Rectangle.intersects(m,h))));return d.length?d.every(c=>{const m=c.permissionId,h=o.getPermissionPoint(new Se(e,t,m).id);return!!(h!=null&&h.value)}):!0},Di=(s,e,t,n=1,o=!0,r=!0)=>{const a=i.Range.transformRange(s,e),{startRow:l,endRow:u}=a;let d=t.startRow-n,c=e.getMergedCell(d,t.startColumn),m=!c||c.startRow===d&&c.startColumn===t.startColumn;for(;!e.getRowVisible(d)||!m;)d--,c=e.getMergedCell(d,t.startColumn),m=!c||c.startRow===d&&c.startColumn===t.startColumn;if(d>=l)return{...t,startRow:d,endRow:d};if(r){const h={...t,startRow:u,endRow:u};return Wi(s,e,h,n,o,!1)}},Ai=(s,e,t,n=1,o=!0,r=!0)=>{const a=i.Range.transformRange(s,e),{startRow:l,endRow:u}=a;let d=t.endRow+n,c=e.getMergedCell(d,t.startColumn),m=!c||c.startRow===d&&c.startColumn===t.startColumn;for(;!e.getRowVisible(d)||!m;)d++,c=e.getMergedCell(d,t.startColumn),m=!c||c.startRow===d&&c.startColumn===t.startColumn;if(d<=u)return{...t,startRow:d,endRow:d};if(r){const h={...t,startRow:l,endRow:l};return Vi(s,e,h,n,o,!1)}},Wi=(s,e,t,n=1,o=!0,r=!0)=>{const a=i.Range.transformRange(s,e),{startColumn:l,endColumn:u}=a;let d=t.startColumn-n,c=e.getMergedCell(t.startRow,d),m=!c||c.startRow===t.startRow&&c.startColumn===d;for(;!e.getColVisible(d)||!m;)d--,c=e.getMergedCell(t.startRow,d),m=!c||c.startRow===t.startRow&&c.startColumn===d;if(d>=l)return{...t,startColumn:d,endColumn:d};if(r){const h={...t,startColumn:u,endColumn:u};return Di(s,e,h,n,o,!1)}},Vi=(s,e,t,n=1,o=!0,r=!0)=>{const a=i.Range.transformRange(s,e),{startColumn:l,endColumn:u}=a;let d=t.endColumn+n,c=e.getMergedCell(t.startRow,d),m=!c||c.startRow===t.startRow&&c.startColumn===d;for(;!e.getColVisible(d)||!m;)d++,c=e.getMergedCell(t.startRow,d),m=!c||c.startRow===t.startRow&&c.startColumn===d;if(d<=u)return{...t,endColumn:d,startColumn:d};if(r){const h={...t,startColumn:l,endColumn:l};return Ai(s,e,h,n,o,!1)}};function Wn(s,e,t){let n=null;return t.getMatrixWithMergedCells(s,e,s,e).forValue((r,a,l)=>(n={actualRow:r,actualColumn:a,startRow:r,startColumn:a,isMerged:l.rowSpan!==void 0||l.colSpan!==void 0,isMergedMainCell:l.rowSpan!==void 0&&l.colSpan!==void 0,endRow:r+(l.rowSpan!==void 0?l.rowSpan-1:0),endColumn:a+(l.colSpan!==void 0?l.colSpan-1:0),rangeType:i.RANGE_TYPE.NORMAL},!1)),n||{actualColumn:e,actualRow:s,startRow:s,startColumn:e,endRow:s,endColumn:e,isMerged:!1,isMergedMainCell:!1,rangeType:i.RANGE_TYPE.NORMAL}}const Dd=(s,e,t,n,o=1)=>{switch(n){case i.Direction.UP:return Di(s,e,t,o);case i.Direction.DOWN:return Ai(s,e,t,o);case i.Direction.LEFT:return Wi(s,e,t,o);case i.Direction.RIGHT:return Vi(s,e,t,o)}},Ad=(s,e,t)=>{let n,o=-1,r;for(let v=0;v<s.length;v++)if(s[v].primary){n=s[v],o=v,r=n.primary;break}if(o===-1)return null;const a=e===i.Direction.LEFT||e===i.Direction.UP,l=a?o-1>=0?o-1:s.length-1:o+1<s.length?o+1:0,u=s[l];if(!n||!r)return null;const d={...r},{startRow:c,startColumn:m,endRow:h,endColumn:R}=n.range,C=a?d.startRow===c&&d.startColumn===m:d.endRow===h&&d.endColumn===R,S=C&&a;if(!i.Rectangle.equals(n.range,d)){const v=C?u.range:Dd(n.range,t,d,e);if(!v)return null;const M=S?Wn(v.endRow,v.endColumn,t):Wn(v.startRow,v.startColumn,t);return{startRow:M.startRow,startColumn:M.startColumn,endRow:M.endRow,endColumn:M.endColumn}}const I=S?Wn(u.range.endRow,u.range.endColumn,t):Wn(u.range.startRow,u.range.startColumn,t);return{startRow:I.startRow,startColumn:I.startColumn,endRow:I.endRow,endColumn:I.endColumn}};g.AFTER_CELL_EDIT=Zt,g.AddMergeRedoSelectionsOperationFactory=Lu,g.AddMergeUndoMutationFactory=ge,g.AddMergeUndoSelectionsOperationFactory=Bu,g.AddRangeProtectionCommand=Oo,g.AddRangeProtectionMutation=Ce,g.AddRangeThemeMutation=Ri,g.AddWorksheetMergeAllCommand=tu,g.AddWorksheetMergeCommand=Ft,g.AddWorksheetMergeHorizontalCommand=su,g.AddWorksheetMergeMutation=j,g.AddWorksheetMergeVerticalCommand=nu,g.AddWorksheetProtectionCommand=br,g.AddWorksheetProtectionMutation=Fe,g.AppendRowCommand=Tr,g.BEFORE_CELL_EDIT=$n,g.BorderStyleManagerService=nt,g.COMMAND_LISTENER_SKELETON_CHANGE=Ea,g.COMMAND_LISTENER_VALUE_CHANGE=Ta,g.CancelFrozenCommand=jr,g.CancelMarkDirtyRowAutoHeightMutation=fi,g.ClearSelectionAllCommand=sn,g.ClearSelectionContentCommand=fn,g.ClearSelectionFormatCommand=on,g.CopySheetCommand=Os,g.DISABLE_NORMAL_SELECTIONS=sl,g.DeleteRangeMoveLeftCommand=Be,g.DeleteRangeMoveUpCommand=He,g.DeleteRangeProtectionCommand=Ur,g.DeleteRangeProtectionMutation=Te,g.DeleteWorksheetProtectionCommand=Pr,g.DeleteWorksheetProtectionMutation=tt,g.DeleteWorksheetRangeThemeStyleCommand=kr,g.DeleteWorksheetRangeThemeStyleMutation=it,g.DeleteWorksheetRangeThemeStyleMutationFactory=ao,g.DeltaColumnWidthCommand=Gt,g.DeltaRowHeightCommand=Kt,g.EditStateEnum=No,g.EffectRefRangId=A,g.EmptyMutation=Ci,g.ExclusiveRangeService=Ui,g.FactoryAddRangeProtectionMutation=Qa,g.FactoryDeleteRangeProtectionMutation=Za,g.FactorySetRangeProtectionMutation=Ru,g.IExclusiveRangeService=Zs,g.INTERCEPTOR_POINT=Ae,g.INumfmtService=ot,g.IRefSelectionsService=Vo,g.InsertColAfterCommand=nr,g.InsertColBeforeCommand=tr,g.InsertColByRangeCommand=ws,g.InsertColCommand=ye,g.InsertColMutation=ie,g.InsertColMutationUndoFactory=Nt,g.InsertDefinedNameCommand=Nr,g.InsertMultiColsLeftCommand=sr,g.InsertMultiColsRightCommand=or,g.InsertMultiRowsAboveCommand=Zo,g.InsertMultiRowsAfterCommand=Qo,g.InsertRangeMoveDownCommand=xe,g.InsertRangeMoveRightCommand=vt,g.InsertRowAfterCommand=Xo,g.InsertRowBeforeCommand=xo,g.InsertRowByRangeCommand=ps,g.InsertRowCommand=Me,g.InsertRowMutation=re,g.InsertRowMutationUndoFactory=en,g.InsertSheetCommand=Or,g.InsertSheetMutation=yt,g.InsertSheetUndoMutationFactory=Ns,g.InterceptCellContentPriority=to,g.MAX_CELL_PER_SHEET_KEY=wi,g.MERGE_CELL_INTERCEPTOR_CHECK=_r,g.MarkDirtyRowAutoHeightMutation=Si,g.MoveColsCommand=wt,g.MoveColsMutation=we,g.MoveColsMutationUndoFactory=uo,g.MoveRangeCommand=Je,g.MoveRangeMutation=Le,g.MoveRowsCommand=pt,g.MoveRowsMutation=pe,g.MoveRowsMutationUndoFactory=lo,g.OperatorType=B,g.PermissionPointsDefinitions=Nd,g.REF_SELECTIONS_ENABLED=Ao,g.RangeMergeUtil=$a,g.RangeProtectionPermissionDeleteProtectionPoint=Gs,g.RangeProtectionPermissionEditPoint=Se,g.RangeProtectionPermissionManageCollaPoint=zs,g.RangeProtectionPermissionViewPoint=ln,g.RangeProtectionRuleModel=X,g.RangeThemeStyle=We,g.RegisterWorksheetRangeThemeStyleCommand=Dr,g.RegisterWorksheetRangeThemeStyleMutation=_t,g.RemoveColByRangeCommand=ys,g.RemoveColCommand=Lt,g.RemoveColMutation=ne,g.RemoveDefinedNameCommand=Ds,g.RemoveMergeUndoMutationFactory=le,g.RemoveNumfmtMutation=Ys,g.RemoveRangeThemeMutation=Ii,g.RemoveRowByRangeCommand=Ms,g.RemoveRowCommand=$t,g.RemoveRowMutation=ae,g.RemoveSheetCommand=vn,g.RemoveSheetMutation=Xe,g.RemoveSheetUndoMutationFactory=rr,g.RemoveWorksheetMergeCommand=Ar,g.RemoveWorksheetMergeMutation=G,g.ReorderRangeCommand=Rn,g.ReorderRangeMutation=Ot,g.ReorderRangeUndoMutationFactory=co,g.ResetBackgroundColorCommand=Xr,g.ResetTextColorCommand=Jr,g.SCOPE_WORKBOOK_VALUE_DEFINED_NAME=zu,g.SELECTIONS_ENABLED=ol,g.SELECTION_CONTROL_BORDER_BUFFER_COLOR=Ba,g.SELECTION_CONTROL_BORDER_BUFFER_WIDTH=La,g.ScrollToCellOperation=pi,g.SelectRangeCommand=Lo,g.SelectionMoveType=te,g.SetBackgroundColorCommand=xr,g.SetBoldCommand=Iu,g.SetBorderBasicCommand=Lr,g.SetBorderColorCommand=$r,g.SetBorderCommand=bt,g.SetBorderPositionCommand=Wr,g.SetBorderStyleCommand=Vr,g.SetColDataCommand=Br,g.SetColDataMutation=at,g.SetColDataMutationFactory=mo,g.SetColHiddenCommand=wn,g.SetColHiddenMutation=lt,g.SetColVisibleMutation=ut,g.SetColWidthCommand=zt,g.SetDefinedNameCommand=Vs,g.SetFontFamilyCommand=yu,g.SetFontSizeCommand=_u,g.SetFrozenCommand=Fr,g.SetFrozenMutation=Ne,g.SetFrozenMutationFactory=$s,g.SetGridlinesColorCommand=Gr,g.SetGridlinesColorMutation=dt,g.SetHorizontalTextAlignCommand=Qr,g.SetItalicCommand=vu,g.SetNumfmtMutation=Un,g.SetOverlineCommand=Mu,g.SetProtectionCommand=zr,g.SetRangeProtectionMutation=Q,g.SetRangeThemeMutation=vi,g.SetRangeValuesCommand=It,g.SetRangeValuesMutation=F,g.SetRangeValuesUndoMutationFactory=ce,g.SetRowDataCommand=qr,g.SetRowDataMutation=ct,g.SetRowDataMutationFactory=Ro,g.SetRowHeightCommand=Jt,g.SetRowHiddenCommand=Mn,g.SetRowHiddenMutation=Ke,g.SetRowVisibleMutation=Ye,g.SetSelectedColsVisibleCommand=Ws,g.SetSelectedRowsVisibleCommand=Ls,g.SetSelectionsOperation=q,g.SetSpecificColsVisibleCommand=Et,g.SetSpecificRowsVisibleCommand=Tt,g.SetStrikeThroughCommand=wu,g.SetStyleCommand=ee,g.SetTabColorCommand=ni,g.SetTabColorMutation=jt,g.SetTextColorCommand=Kr,g.SetTextRotationCommand=ti,g.SetTextWrapCommand=ei,g.SetUnderlineCommand=pu,g.SetVerticalTextAlignCommand=Zr,g.SetWorkbookNameCommand=Hs,g.SetWorkbookNameMutation=Bs,g.SetWorksheetActivateCommand=Fs,g.SetWorksheetActiveOperation=Ct,g.SetWorksheetColWidthMutation=Ve,g.SetWorksheetColWidthMutationFactory=Hn,g.SetWorksheetColumnCountCommand=si,g.SetWorksheetColumnCountMutation=mt,g.SetWorksheetColumnCountUndoMutationFactory=Co,g.SetWorksheetDefaultStyleCommand=oi,g.SetWorksheetDefaultStyleMutation=ht,g.SetWorksheetDefaultStyleMutationFactory=So,g.SetWorksheetHideCommand=ii,g.SetWorksheetHideMutation=je,g.SetWorksheetNameCommand=yn,g.SetWorksheetNameMutation=qt,g.SetWorksheetOrderCommand=js,g.SetWorksheetOrderMutation=Yt,g.SetWorksheetPermissionPointsCommand=li,g.SetWorksheetPermissionPointsMutation=bn,g.SetWorksheetProtectionCommand=ui,g.SetWorksheetProtectionMutation=st,g.SetWorksheetRangeThemeStyleCommand=Er,g.SetWorksheetRangeThemeStyleMutation=rt,g.SetWorksheetRangeThemeStyleMutationFactory=io,g.SetWorksheetRightToLeftCommand=Wu,g.SetWorksheetRightToLeftMutation=En,g.SetWorksheetRowAutoHeightMutation=jn,g.SetWorksheetRowAutoHeightMutationFactory=ba,g.SetWorksheetRowCountCommand=di,g.SetWorksheetRowCountMutation=gt,g.SetWorksheetRowCountUndoMutationFactory=fo,g.SetWorksheetRowHeightMutation=Ee,g.SetWorksheetRowIsAutoHeightCommand=Tn,g.SetWorksheetRowIsAutoHeightMutation=Re,g.SetWorksheetShowCommand=qs,g.SheetSkeletonChangeType=vo,g.SheetValueChangeType=po,g.SplitDelimiterEnum=Eo,g.SplitTextToColumnsCommand=ci,g.ToggleCellCheckboxCommand=mi,g.ToggleGridlinesCommand=hi,g.ToggleGridlinesMutation=Rt,g.UnitAction=_,g.UnitObject=D,g.UnregisterWorksheetRangeThemeStyleCommand=gi,g.UnregisterWorksheetRangeThemeStyleMutation=In,g.VALIDATE_CELL=Qt,g.ViewStateEnum=ko,g.WorkbookCommentPermission=Yn,g.WorkbookCopyPermission=Kn,g.WorkbookCopySheetPermission=Ho,g.WorkbookCreateProtectPermission=Jn,g.WorkbookCreateSheetPermission=xn,g.WorkbookDeleteColumnPermission=Fo,g.WorkbookDeleteRowPermission=jo,g.WorkbookDeleteSheetPermission=Xn,g.WorkbookDuplicatePermission=Zn,g.WorkbookEditablePermission=me,g.WorkbookExportPermission=Qn,g.WorkbookHideSheetPermission=un,g.WorkbookHistoryPermission=Go,g.WorkbookInsertColumnPermission=zo,g.WorkbookInsertRowPermission=qo,g.WorkbookManageCollaboratorPermission=dn,g.WorkbookMoveSheetPermission=cn,g.WorkbookPrintPermission=es,g.WorkbookRecoverHistoryPermission=ts,g.WorkbookRenameSheetPermission=mn,g.WorkbookSelectionModel=Do,g.WorkbookSharePermission=ns,g.WorkbookViewHistoryPermission=os,g.WorkbookViewPermission=ss,g.WorksheetCopyPermission=rs,g.WorksheetDeleteColumnPermission=is,g.WorksheetDeleteProtectionPermission=as,g.WorksheetDeleteRowPermission=ls,g.WorksheetEditExtraObjectPermission=us,g.WorksheetEditPermission=fe,g.WorksheetFilterPermission=ds,g.WorksheetInsertColumnPermission=cs,g.WorksheetInsertHyperlinkPermission=ms,g.WorksheetInsertRowPermission=hs,g.WorksheetManageCollaboratorPermission=gs,g.WorksheetPivotTablePermission=Rs,g.WorksheetProtectionPointModel=Ut,g.WorksheetProtectionRuleModel=ke,g.WorksheetSelectProtectedCellsPermission=hl,g.WorksheetSelectUnProtectedCellsPermission=gl,g.WorksheetSetCellStylePermission=Cs,g.WorksheetSetCellValuePermission=Wt,g.WorksheetSetColumnStylePermission=St,g.WorksheetSetRowStylePermission=ft,g.WorksheetSortPermission=Ss,g.WorksheetViewPermission=Vt,g.addMergeCellsUtil=ou,g.adjustRangeOnMutation=fr,g.alignToMergedCellsBorders=At,g.baseProtectionActions=Ge,g.checkCellValueType=Vn,g.checkRangesEditablePermission=Od,g.convertPrimaryWithCoordToPrimary=bo,g.convertSelectionDataToRange=Ha,g.copyRangeStyles=$e,g.createTopMatrixFromMatrix=yo,g.createTopMatrixFromRanges=Mo,g.defaultWorkbookPermissionPoints=ai,g.defaultWorksheetPermissionPoint=_n,g.expandToContinuousRange=Wa,g.factoryRemoveNumfmtUndoMutation=$u,g.factorySetNumfmtUndoMutation=Vu,g.findAllRectangle=Gn,g.findFirstNonEmptyCell=xa,g.followSelectionOperation=Ue,g.generateNullCell=qn,g.generateNullCellValue=Uo,g.getAddMergeMutationRangeByType=ks,g.getAllRangePermissionPoint=ue,g.getAllWorkbookPermissionPoint=Pt,g.getAllWorksheetPermissionPoint=de,g.getAllWorksheetPermissionPointByPointPanel=Ie,g.getCellAtRowCol=rl,g.getDefaultRangePermission=Pu,g.getInsertRangeMutations=fs,g.getMoveRangeUndoRedoMutations=rn,g.getNextPrimaryCell=Ad,g.getPrimaryForRange=se,g.getRemoveRangeMutations=Is,g.getSelectionsService=$o,g.getSeparateEffectedRangesOnCommand=Bl,g.getSheetCommandTarget=P,g.getSheetCommandTargetWorkbook=Bn,g.getSheetMutationTarget=ve,g.getSkeletonChangedEffectedRange=Pa,g.getValueChangedEffectedRange=Ua,g.getVisibleRanges=Dt,g.handleBaseInsertRange=Qe,g.handleBaseMoveRowsCols=Ht,g.handleBaseRemoveRange=Ze,g.handleCommonDefaultRangeChangeWithEffectRefCommands=Ps,g.handleCommonRangeChangeWithEffectRefCommandsSkipNoInterests=$l,g.handleDefaultRangeChangeWithEffectRefCommands=Us,g.handleDefaultRangeChangeWithEffectRefCommandsSkipNoInterests=Vl,g.handleDeleteRangeMoveLeft=Cr,g.handleDeleteRangeMoveUp=Sr,g.handleDeleteRangeMutation=Cl,g.handleIRemoveCol=Ts,g.handleIRemoveRow=cr,g.handleInsertCol=hr,g.handleInsertRangeMoveDown=gr,g.handleInsertRangeMoveRight=Rr,g.handleInsertRangeMutation=Rl,g.handleInsertRow=mr,g.handleMoveCols=Es,g.handleMoveRange=dr,g.handleMoveRows=bs,g.isSingleCellSelection=al,g.rangeMerge=zn,g.rangeToDiscreteRange=Po,g.rotateRange=he,g.runRefRangeMutations=et,g.setEndForRange=il,g.splitRangeText=To,g.transformCellsToRange=Pn,Object.defineProperty(g,Symbol.toStringTag,{value:"Module"})}));
|
|
13
13
|
|
|
14
14
|
|
|
15
15
|
// @univerjs/sheets/facade
|
|
16
|
-
(function(c,h){typeof exports=="object"&&typeof module<"u"?h(exports,require("@univerjs/core"),require("@univerjs/core/facade"),require("@univerjs/sheets"),require("@univerjs/engine-formula"),require("rxjs"),require("rxjs/operators")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","@univerjs/core/facade","@univerjs/sheets","@univerjs/engine-formula","rxjs","rxjs/operators"],h):(c=typeof globalThis<"u"?globalThis:c||self,h(c.UniverSheetsFacade={},c.UniverCore,c.UniverCoreFacade,c.UniverSheets,c.UniverEngineFormula,c.rxjs,c.rxjs.operators))})(this,(function(c,h,I,a,P,M,w){"use strict";var ye=Object.defineProperty;var Ue=(c,h,I)=>h in c?ye(c,h,{enumerable:!0,configurable:!0,writable:!0,value:I}):c[h]=I;var k=(c,h,I)=>Ue(c,typeof h!="symbol"?h+"":h,I);var D;var ee=Object.getOwnPropertyDescriptor,te=(r,n,e,t)=>{for(var i=t>1?void 0:t?ee(n,e):n,o=r.length-1,s;o>=0;o--)(s=r[o])&&(i=s(i)||i);return i},R=(r,n)=>(e,t)=>n(e,t,r);function ne(r,n,e){const t=e.getDefinedNameMap(r);if(t==null)return n.t("definedName.defaultName")+1;const o=Array.from(Object.values(t)).length+1,s=n.t("definedName.defaultName")+o;if(e.getValueByName(r,s)==null)return s;let d=o+1;for(;;){const u=n.t("definedName.defaultName")+d;if(e.getValueByName(r,u)==null)return u;d++}}class T{constructor(){k(this,"_definedNameParam");this._definedNameParam={id:h.generateRandomId(10),unitId:"",name:"",formulaOrRefString:"",localSheetId:a.SCOPE_WORKBOOK_VALUE_DEFINED_NAME}}setName(n){return this._definedNameParam.name=n,this}setFormula(n){return this._definedNameParam.formulaOrRefString=`=${n}`,this}setRef(n){return this._definedNameParam.formulaOrRefString=n,this}setRefByRange(n,e,t,i){return this._definedNameParam.formulaOrRefString=P.serializeRange({startRow:n,endRow:n+(t!=null?t:1)-1,startColumn:e,endColumn:e+(i!=null?i:1)-1}),this}setComment(n){return this._definedNameParam.comment=n,this}setScopeToWorksheet(n){return this._definedNameParam.localSheetId=n.getSheetId(),this}setScopeToWorkbook(){return this._definedNameParam.localSheetId=a.SCOPE_WORKBOOK_VALUE_DEFINED_NAME,this}setHidden(n){return this._definedNameParam.hidden=n,this}build(){return this._definedNameParam}load(n){return this._definedNameParam=n,this}}let O=class extends I.FBase{constructor(r,n,e,t,i,o,s,d,u,l){super(),this._definedNameParam=r,this._injector=n,this._commandService=e,this._permissionService=t,this._worksheetProtectionRuleModel=i,this._rangeProtectionRuleModel=o,this._worksheetProtectionPointRuleModel=s,this._authzIoService=d,this._localeService=u,this._definedNamesService=l}_apply(){this._definedNameParam.name===""&&(this._definedNameParam.name=ne(this._definedNameParam.unitId,this._localeService,this._definedNamesService)),this._commandService.syncExecuteCommand(a.SetDefinedNameCommand.id,this._definedNameParam)}getName(){return this._definedNameParam.name}setName(r){this._definedNameParam.name=r,this._apply()}setFormula(r){this._definedNameParam.formulaOrRefString=`=${r}`,this._apply()}setRef(r){this._definedNameParam.formulaOrRefString=r,this._apply()}getFormulaOrRefString(){return this._definedNameParam.formulaOrRefString}setRefByRange(r,n,e,t){this._definedNameParam.formulaOrRefString=P.serializeRange({startRow:r,endRow:r+(e!=null?e:1)-1,startColumn:n,endColumn:n+(t!=null?t:1)-1}),this._apply()}getComment(){return this._definedNameParam.comment}setComment(r){this._definedNameParam.comment=r,this._apply()}setScopeToWorksheet(r){this._definedNameParam.localSheetId=r.getSheetId(),this._apply()}setScopeToWorkbook(){this._definedNameParam.localSheetId=a.SCOPE_WORKBOOK_VALUE_DEFINED_NAME,this._apply()}setHidden(r){this._definedNameParam.hidden=r,this._apply()}delete(){this._commandService.syncExecuteCommand(a.RemoveDefinedNameCommand.id,this._definedNameParam)}getLocalSheetId(){return this._definedNameParam.localSheetId}isWorkbookScope(){return this._definedNameParam.localSheetId===a.SCOPE_WORKBOOK_VALUE_DEFINED_NAME}toBuilder(){const r=this._injector.createInstance(T);return r.load(this._definedNameParam),r}};O=te([R(1,h.Inject(h.Injector)),R(2,h.ICommandService),R(3,h.IPermissionService),R(4,h.Inject(a.WorksheetProtectionRuleModel)),R(5,h.Inject(a.RangeProtectionRuleModel)),R(6,h.Inject(a.WorksheetProtectionPointModel)),R(7,h.Inject(h.IAuthzIoService)),R(8,h.Inject(h.LocaleService)),R(9,P.IDefinedNamesService)],O);var ie=Object.getOwnPropertyDescriptor,re=(r,n,e,t)=>{for(var i=t>1?void 0:t?ie(n,e):n,o=r.length-1,s;o>=0;o--)(s=r[o])&&(i=s(i)||i);return i},E=(r,n)=>(e,t)=>n(e,t,r);c.FPermission=class extends I.FBase{constructor(e,t,i,o,s,d,u,l){super();k(this,"permissionPointsDefinition",a.PermissionPointsDefinitions);k(this,"rangeRuleChangedAfterAuth$");k(this,"sheetRuleChangedAfterAuth$");k(this,"unitPermissionInitStateChange$");this._injector=e,this._commandService=t,this._permissionService=i,this._worksheetProtectionRuleModel=o,this._rangeProtectionRuleModel=s,this._worksheetProtectionPointRuleModel=d,this._workbookPermissionService=u,this._authzIoService=l,this.rangeRuleChangedAfterAuth$=this._rangeProtectionRuleModel.ruleRefresh$,this.sheetRuleChangedAfterAuth$=this._worksheetProtectionRuleModel.ruleRefresh$,this.unitPermissionInitStateChange$=this._workbookPermissionService.unitPermissionInitStateChange$}setWorkbookPermissionPoint(e,t,i){const o=new t(e);this._permissionService.getPermissionPoint(o.id)||this._permissionService.addPermissionPoint(o),this._permissionService.updatePermissionPoint(o.id,i)}checkWorkbookPermissionPoint(e,t){const i=new t(e),o=this._permissionService.getPermissionPoint(i.id);if(o)return o.value}setWorkbookEditPermission(e,t){this.setWorkbookPermissionPoint(e,a.WorkbookEditablePermission,t)}async addWorksheetBasePermission(e,t){if(this._rangeProtectionRuleModel.getSubunitRuleList(e,t).length>0)throw new Error("sheet protection cannot intersect with range protection");const o=await this._authzIoService.create({objectType:a.UnitObject.Worksheet,worksheetObject:{collaborators:[],unitID:e,strategies:[],name:"",scope:void 0}});if(this._commandService.syncExecuteCommand(a.AddWorksheetProtectionMutation.id,{unitId:e,subUnitId:t,rule:{permissionId:o,unitType:a.UnitObject.Worksheet,unitId:e,subUnitId:t}}))return o}removeWorksheetPermission(e,t){this._commandService.syncExecuteCommand(a.DeleteWorksheetProtectionMutation.id,{unitId:e,subUnitId:t}),[...a.getAllWorksheetPermissionPoint(),...a.getAllWorksheetPermissionPointByPointPanel()].forEach(i=>{const o=new i(e,t);this._permissionService.updatePermissionPoint(o.id,!0)}),this._worksheetProtectionPointRuleModel.deleteRule(e,t)}async setWorksheetPermissionPoint(e,t,i,o){const s=this._worksheetProtectionRuleModel.getRule(e,t);let d;if(i===a.WorksheetEditPermission||i===a.WorksheetViewPermission)if(s)d=s.permissionId;else{if(this._rangeProtectionRuleModel.getSubunitRuleList(e,t).length>0)throw new Error("sheet protection cannot intersect with range protection");d=await this.addWorksheetBasePermission(e,t)}else{const _=this._worksheetProtectionPointRuleModel.getRule(e,t);_?d=_.permissionId:(d=await this._authzIoService.create({objectType:a.UnitObject.Worksheet,worksheetObject:{collaborators:[],unitID:e,strategies:[],name:"",scope:void 0}}),this._commandService.syncExecuteCommand(a.SetWorksheetPermissionPointsMutation.id,{unitId:e,subUnitId:t,rule:{unitId:e,subUnitId:t,permissionId:d}}))}const l=new i(e,t);return this._permissionService.getPermissionPoint(l.id)||this._permissionService.addPermissionPoint(l),this._permissionService.updatePermissionPoint(l.id,o),d}checkWorksheetPermissionPoint(e,t,i){const o=new i(e,t),s=this._permissionService.getPermissionPoint(o.id);if(s)return s.value}async addRangeBaseProtection(e,t,i){const o=await this._authzIoService.create({objectType:a.UnitObject.SelectRange,selectRangeObject:{collaborators:[],unitID:e,name:"",scope:void 0}}),s=`ruleId_${h.generateRandomId(6)}`;if(this._worksheetProtectionRuleModel.getRule(e,t))throw new Error("sheet protection cannot intersect with range protection");if(this._rangeProtectionRuleModel.getSubunitRuleList(e,t).some(_=>_.ranges.some(C=>i.some(v=>h.Rectangle.intersects(v.getRange(),C)))))throw new Error("range protection cannot intersect");if(this._commandService.syncExecuteCommand(a.AddRangeProtectionMutation.id,{unitId:e,subUnitId:t,rules:[{permissionId:o,unitType:a.UnitObject.SelectRange,unitId:e,subUnitId:t,ranges:i.map(_=>_.getRange()),id:s}]}))return{permissionId:o,ruleId:s}}removeRangeProtection(e,t,i){this._commandService.syncExecuteCommand(a.DeleteRangeProtectionMutation.id,{unitId:e,subUnitId:t,ruleIds:i})&&this._rangeProtectionRuleModel.getSubunitRuleList(e,t).length===0&&(this._worksheetProtectionPointRuleModel.deleteRule(e,t),[...a.getAllWorksheetPermissionPointByPointPanel()].forEach(d=>{const u=new d(e,t);this._permissionService.updatePermissionPoint(u.id,u.value)}))}setRangeProtectionPermissionPoint(e,t,i,o,s){const d=new o(e,t,i);this._permissionService.getPermissionPoint(d.id)||this._permissionService.addPermissionPoint(d),this._permissionService.updatePermissionPoint(d.id,s)}setRangeProtectionRanges(e,t,i,o){const s=this._rangeProtectionRuleModel.getRule(e,t,i);if(s){if(this._rangeProtectionRuleModel.getSubunitRuleList(e,t).filter(l=>l.id!==i).some(l=>l.ranges.some(m=>o.some(_=>h.Rectangle.intersects(_.getRange(),m)))))throw new Error("range protection cannot intersect");this._commandService.syncExecuteCommand(a.SetRangeProtectionMutation.id,{unitId:e,subUnitId:t,ruleId:i,rule:{...s,ranges:o.map(l=>l.getRange())}})}}getPermissionInfoWithCell(e,t,i,o){const s=h.cellToRange(i,o),d=this._rangeProtectionRuleModel.getSubunitRuleList(e,t).find(u=>u.ranges.some(m=>h.Rectangle.intersects(s,m)));if(d)return{permissionId:d.permissionId,ruleId:d.id}}},c.FPermission=re([E(0,h.Inject(h.Injector)),E(1,h.ICommandService),E(2,h.IPermissionService),E(3,h.Inject(a.WorksheetProtectionRuleModel)),E(4,h.Inject(a.RangeProtectionRuleModel)),E(5,h.Inject(a.WorksheetProtectionPointModel)),E(6,h.Inject(a.WorkbookPermissionService)),E(7,h.Inject(h.IAuthzIoService))],c.FPermission);var oe=Object.getOwnPropertyDescriptor,se=(r,n,e,t)=>{for(var i=t>1?void 0:t?oe(n,e):n,o=r.length-1,s;o>=0;o--)(s=r[o])&&(i=s(i)||i);return i},ae=(r,n)=>(e,t)=>n(e,t,r);c.FSelection=class{constructor(n,e,t,i){this._workbook=n,this._worksheet=e,this._selections=t,this._injector=i}getActiveRange(){const n=this._selections.find(e=>!!e.primary);return n?this._injector.createInstance(c.FRange,this._workbook,this._worksheet,n.range):null}getActiveRangeList(){return this._selections.map(n=>this._injector.createInstance(c.FRange,this._workbook,this._worksheet,n.range))}getCurrentCell(){const n=this._selections.find(e=>!!e.primary);return n?n.primary:null}getActiveSheet(){const n=this._injector.createInstance(c.FWorkbook,this._workbook);return this._injector.createInstance(c.FWorksheet,n,this._workbook,this._worksheet)}updatePrimaryCell(n){const e=this._injector.get(h.ICommandService);let t=[],i=!1;for(const{range:s,style:d}of this._selections)h.Rectangle.contains(s,n.getRange())?(t.push({range:s,primary:a.getPrimaryForRange(n.getRange(),this._worksheet),style:d}),i=!0):t.push({range:s,primary:null,style:d});i||(t=[{range:n.getRange(),primary:a.getPrimaryForRange(n.getRange(),this._worksheet)}]);const o={unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),selections:t};return e.syncExecuteCommand(a.SetSelectionsOperation.id,o),new c.FSelection(this._workbook,this._worksheet,t,this._injector)}getNextDataRange(n){if(!this._selections.find(i=>!!i.primary))return null;const t=a.getNextPrimaryCell(this._selections.concat(),n,this._worksheet);return t?this._injector.createInstance(c.FRange,this._workbook,this._worksheet,t):null}},c.FSelection=se([ae(3,h.Inject(h.Injector))],c.FSelection);var x=(r=>(r[r.Reader=0]="Reader",r[r.Editor=1]="Editor",r[r.Owner=2]="Owner",r[r.UNRECOGNIZED=-1]="UNRECOGNIZED",r))(x||{}),he=Object.getOwnPropertyDescriptor,de=(r,n,e,t)=>{for(var i=t>1?void 0:t?he(n,e):n,o=r.length-1,s;o>=0;o--)(s=r[o])&&(i=s(i)||i);return i},B=(r,n)=>(e,t)=>n(e,t,r);let y=class{constructor(r,n,e,t,i,o,s,d,u){this._unitId=r,this._subUnitId=n,this._ruleId=e,this._permissionId=t,this._ranges=i,this._options=o,this._injector=s,this._commandService=d,this._rangeProtectionRuleModel=u}get id(){return this._ruleId}get ranges(){return this._ranges}get options(){return{...this._options}}async updateRanges(r){if(!r||r.length===0)throw new Error("Ranges cannot be empty");const n=this._rangeProtectionRuleModel.getRule(this._unitId,this._subUnitId,this._ruleId);if(!n)throw new Error(`Rule ${this._ruleId} not found`);if(this._rangeProtectionRuleModel.getSubunitRuleList(this._unitId,this._subUnitId).filter(i=>i.id!==this._ruleId).some(i=>i.ranges.some(o=>r.some(s=>{const d=s.getRange();return this._rangesIntersect(d,o)}))))throw new Error("Range protection cannot intersect with other protection rules");await this._commandService.executeCommand(a.SetRangeProtectionMutation.id,{unitId:this._unitId,subUnitId:this._subUnitId,ruleId:this._ruleId,rule:{...n,ranges:r.map(i=>i.getRange())}}),this._ranges.length=0,this._ranges.push(...r)}async updateOptions(r){const n=this._rangeProtectionRuleModel.getRule(this._unitId,this._subUnitId,this._ruleId);if(!n)throw new Error(`Rule ${this._ruleId} not found`);const e={...this._options,...r};await this._commandService.executeCommand(a.SetRangeProtectionMutation.id,{unitId:this._unitId,subUnitId:this._subUnitId,ruleId:this._ruleId,rule:{...n}}),Object.assign(this._options,e)}async remove(){await this._commandService.executeCommand(a.DeleteRangeProtectionMutation.id,{unitId:this._unitId,subUnitId:this._subUnitId,ruleIds:[this._ruleId]})}_rangesIntersect(r,n){return!(r.endRow<n.startRow||r.startRow>n.endRow||r.endColumn<n.startColumn||r.startColumn>n.endColumn)}};y=de([B(6,h.Inject(h.Injector)),B(7,h.Inject(h.ICommandService)),B(8,h.Inject(a.RangeProtectionRuleModel))],y);var q=(r=>(r[r.Reader=0]="Reader",r[r.Editor=1]="Editor",r[r.Owner=2]="Owner",r))(q||{}),g=(r=>(r.Edit="WorkbookEdit",r.View="WorkbookView",r.Print="WorkbookPrint",r.Export="WorkbookExport",r.Share="WorkbookShare",r.CopyContent="WorkbookCopy",r.DuplicateFile="WorkbookDuplicate",r.Comment="WorkbookComment",r.ManageCollaborator="WorkbookManageCollaborator",r.CreateSheet="WorkbookCreateSheet",r.DeleteSheet="WorkbookDeleteSheet",r.RenameSheet="WorkbookRenameSheet",r.MoveSheet="WorkbookMoveSheet",r.HideSheet="WorkbookHideSheet",r.ViewHistory="WorkbookViewHistory",r.ManageHistory="WorkbookHistory",r.RecoverHistory="WorkbookRecoverHistory",r.CreateProtection="WorkbookCreateProtect",r.InsertRow="WorkbookInsertRow",r.InsertColumn="WorkbookInsertColumn",r.DeleteRow="WorkbookDeleteRow",r.DeleteColumn="WorkbookDeleteColumn",r.CopySheet="WorkbookCopySheet",r))(g||{}),S=(r=>(r.Edit="WorksheetEdit",r.View="WorksheetView",r.Copy="WorksheetCopy",r.SetCellValue="WorksheetSetCellValue",r.SetCellStyle="WorksheetSetCellStyle",r.SetRowStyle="WorksheetSetRowStyle",r.SetColumnStyle="WorksheetSetColumnStyle",r.InsertRow="WorksheetInsertRow",r.InsertColumn="WorksheetInsertColumn",r.DeleteRow="WorksheetDeleteRow",r.DeleteColumn="WorksheetDeleteColumn",r.Sort="WorksheetSort",r.Filter="WorksheetFilter",r.PivotTable="WorksheetPivotTable",r.InsertHyperlink="WorksheetInsertHyperlink",r.EditExtraObject="WorksheetEditExtraObject",r.ManageCollaborator="WorksheetManageCollaborator",r.DeleteProtection="WorksheetDeleteProtection",r.SelectProtectedCells="WorksheetSelectProtectedCells",r.SelectUnProtectedCells="WorksheetSelectUnProtectedCells",r))(S||{}),b=(r=>(r.Edit="RangeEdit",r.View="RangeView",r.ManageCollaborator="RangeManageCollaborator",r.Delete="RangeDeleteProtection",r))(b||{});const V={[g.Edit]:a.WorkbookEditablePermission,[g.View]:a.WorkbookViewPermission,[g.Print]:a.WorkbookPrintPermission,[g.Export]:a.WorkbookExportPermission,[g.Share]:a.WorkbookSharePermission,[g.CopyContent]:a.WorkbookCopyPermission,[g.DuplicateFile]:a.WorkbookDuplicatePermission,[g.Comment]:a.WorkbookCommentPermission,[g.ManageCollaborator]:a.WorkbookManageCollaboratorPermission,[g.CreateSheet]:a.WorkbookCreateSheetPermission,[g.DeleteSheet]:a.WorkbookDeleteSheetPermission,[g.RenameSheet]:a.WorkbookRenameSheetPermission,[g.MoveSheet]:a.WorkbookMoveSheetPermission,[g.HideSheet]:a.WorkbookHideSheetPermission,[g.ViewHistory]:a.WorkbookViewHistoryPermission,[g.ManageHistory]:a.WorkbookHistoryPermission,[g.RecoverHistory]:a.WorkbookRecoverHistoryPermission,[g.CreateProtection]:a.WorkbookCreateProtectPermission,[g.InsertRow]:a.WorkbookInsertRowPermission,[g.InsertColumn]:a.WorkbookInsertColumnPermission,[g.DeleteRow]:a.WorkbookDeleteRowPermission,[g.DeleteColumn]:a.WorkbookDeleteColumnPermission,[g.CopySheet]:a.WorkbookCopySheetPermission},A={[S.Edit]:a.WorksheetEditPermission,[S.View]:a.WorksheetViewPermission,[S.Copy]:a.WorksheetCopyPermission,[S.SetCellValue]:a.WorksheetSetCellValuePermission,[S.SetCellStyle]:a.WorksheetSetCellStylePermission,[S.SetRowStyle]:a.WorksheetSetRowStylePermission,[S.SetColumnStyle]:a.WorksheetSetColumnStylePermission,[S.InsertRow]:a.WorksheetInsertRowPermission,[S.InsertColumn]:a.WorksheetInsertColumnPermission,[S.DeleteRow]:a.WorksheetDeleteRowPermission,[S.DeleteColumn]:a.WorksheetDeleteColumnPermission,[S.Sort]:a.WorksheetSortPermission,[S.Filter]:a.WorksheetFilterPermission,[S.PivotTable]:a.WorksheetPivotTablePermission,[S.InsertHyperlink]:a.WorksheetInsertHyperlinkPermission,[S.EditExtraObject]:a.WorksheetEditExtraObjectPermission,[S.ManageCollaborator]:a.WorksheetManageCollaboratorPermission,[S.DeleteProtection]:a.WorksheetDeleteProtectionPermission,[S.SelectProtectedCells]:a.WorksheetSelectProtectedCellsPermission,[S.SelectUnProtectedCells]:a.WorksheetSelectUnProtectedCellsPermission},j={[b.Edit]:a.RangeProtectionPermissionEditPoint,[b.View]:a.RangeProtectionPermissionViewPoint,[b.ManageCollaborator]:a.RangeProtectionPermissionManageCollaPoint,[b.Delete]:a.RangeProtectionPermissionDeleteProtectionPoint};var ue=Object.getOwnPropertyDescriptor,le=(r,n,e,t)=>{for(var i=t>1?void 0:t?ue(n,e):n,o=r.length-1,s;o>=0;o--)(s=r[o])&&(i=s(i)||i);return i},W=(r,n)=>(e,t)=>n(e,t,r);let H=class{constructor(r,n,e,t,i,o,s){k(this,"_permissionSubject");k(this,"_rangeRulesSubject");k(this,"permission$");k(this,"pointChange$");k(this,"rangeProtectionChange$");k(this,"rangeProtectionRules$");k(this,"_unitId");k(this,"_subUnitId");k(this,"_subscriptions",[]);this._worksheet=r,this._injector=n,this._permissionService=e,this._authzIoService=t,this._commandService=i,this._rangeProtectionRuleModel=o,this._worksheetProtectionPointModel=s,this._unitId=this._worksheet.getWorkbook().getUnitId(),this._subUnitId=this._worksheet.getSheetId(),this._permissionSubject=new M.BehaviorSubject(this._buildSnapshot()),this._rangeRulesSubject=new M.BehaviorSubject(this._buildRangeProtectionRules()),this.permission$=this._createPermissionStream(),this.pointChange$=this._createPointChangeStream(),this.rangeProtectionChange$=this._createRangeProtectionChangeStream(),this.rangeProtectionRules$=this._createRangeProtectionRulesStream()}_createPermissionStream(){const r=this._permissionService.permissionPointUpdate$.pipe(w.filter(n=>n.id.includes(this._unitId)&&n.id.includes(this._subUnitId))).subscribe(()=>{this._permissionSubject.next(this._buildSnapshot())});return this._subscriptions.push(r),this._permissionSubject.asObservable().pipe(w.distinctUntilChanged((n,e)=>JSON.stringify(n)===JSON.stringify(e)),w.shareReplay({bufferSize:1,refCount:!0}))}_createPointChangeStream(){return this._permissionService.permissionPointUpdate$.pipe(w.filter(r=>r.id.includes(this._unitId)&&r.id.includes(this._subUnitId)),w.map(r=>{var e,t;const n=this._extractWorksheetPointType(r.id);return n?{point:n,value:(e=r.value)!=null?e:!1,oldValue:!((t=r.value)!=null&&t)}:null}),w.filter(r=>r!==null),w.shareReplay({bufferSize:1,refCount:!0}))}_createRangeProtectionChangeStream(){return this._rangeProtectionRuleModel.ruleChange$.pipe(w.filter(r=>r.unitId===this._unitId&&r.subUnitId===this._subUnitId),w.map(r=>{const n=this._buildRangeProtectionRules();return{type:r.type==="delete"?"delete":r.type==="set"?"update":"add",rules:n}}),w.shareReplay({bufferSize:1,refCount:!0}))}_createRangeProtectionRulesStream(){const r=this._rangeProtectionRuleModel.ruleChange$.pipe(w.filter(n=>n.unitId===this._unitId&&n.subUnitId===this._subUnitId)).subscribe(()=>{this._rangeRulesSubject.next(this._buildRangeProtectionRules())});return this._subscriptions.push(r),this._rangeRulesSubject.asObservable().pipe(w.distinctUntilChanged((n,e)=>n.length!==e.length?!1:n.every((t,i)=>t.id===e[i].id)),w.shareReplay({bufferSize:1,refCount:!0}))}_extractWorksheetPointType(r){for(const[n,e]of Object.entries(A))if(new e(this._unitId,this._subUnitId).id===r)return n;return null}_getRuleEditPermission(r){var i;const n=j[b.Edit];if(!n)return!1;const e=new n(this._unitId,this._subUnitId,r.permissionId),t=this._permissionService.getPermissionPoint(e.id);return(i=t==null?void 0:t.value)!=null?i:!1}_buildSnapshot(){const r={};for(const n in S){const e=S[n];r[e]=this.getPoint(e)}return r}_buildRangeProtectionRules(){return this._rangeProtectionRuleModel.getSubunitRuleList(this._unitId,this._subUnitId).map(n=>{const e=n.ranges.map(t=>this._worksheet.getRange(t.startRow,t.startColumn,t.endRow-t.startRow+1,t.endColumn-t.startColumn+1));return this._injector.createInstance(y,this._unitId,this._subUnitId,n.id,n.permissionId,e,{name:n.description||"",allowEdit:this._getRuleEditPermission(n)})})}async setMode(r){const n=this._getModePermissions(r);await this._batchSetPermissionPoints(n)}_getModePermissions(r){const n={};switch(Object.values(S).forEach(e=>{n[e]=!1}),r){case"editable":Object.values(S).forEach(e=>{n[e]=!0});break;case"readOnly":n[S.View]=!0;break;case"filterOnly":n[S.View]=!0,n[S.Sort]=!0,n[S.Filter]=!0;break}return n}async _batchSetPermissionPoints(r){const n=[];for(const[e,t]of Object.entries(r)){const i=e,o=A[i];if(!o)throw new Error(`Unknown worksheet permission point: ${i}`);const s=this.getPoint(i);if(s===t)continue;const d=new o(this._unitId,this._subUnitId);this._permissionService.getPermissionPoint(d.id)||this._permissionService.addPermissionPoint(d),this._permissionService.updatePermissionPoint(d.id,t),n.push({point:i,value:t,oldValue:s})}if(n.length>0){const e=this._buildSnapshot();this._permissionSubject.next(e)}}async setReadOnly(){await this.setMode("readOnly")}async setEditable(){await this.setMode("editable")}canEdit(){return this.getPoint(S.Edit)}canEditCell(r,n){if(!this.canEdit())return!1;const e=this._rangeProtectionRuleModel.getSubunitRuleList(this._unitId,this._subUnitId);for(const t of e)for(const i of t.ranges)if(r>=i.startRow&&r<=i.endRow&&n>=i.startColumn&&n<=i.endColumn)return this._getRuleEditPermission(t);return!0}canViewCell(r,n){return this.getPoint(S.View)}debugCellPermission(r,n){const e=[],t=this._rangeProtectionRuleModel.getSubunitRuleList(this._unitId,this._subUnitId);for(const i of t)for(const o of i.ranges)if(r>=o.startRow&&r<=o.endRow&&n>=o.startColumn&&n<=o.endColumn){e.push({ruleId:i.id,rangeRefs:i.ranges.map(s=>`R${s.startRow}C${s.startColumn}:R${s.endRow}C${s.endColumn}`),options:{name:i.description||"",allowEdit:this._getRuleEditPermission(i)}});break}return e.length===0?null:{row:r,col:n,hitRules:e}}async setPoint(r,n){const e=A[r];if(!e)throw new Error(`Unknown worksheet permission point: ${r}`);if(this.getPoint(r)===n)return;const i=new e(this._unitId,this._subUnitId);this._permissionService.getPermissionPoint(i.id)||this._permissionService.addPermissionPoint(i),this._permissionService.updatePermissionPoint(i.id,n);const s=this._buildSnapshot();this._permissionSubject.next(s)}getPoint(r){var i;const n=A[r];if(!n)throw new Error(`Unknown worksheet permission point: ${r}`);const e=new n(this._unitId,this._subUnitId),t=this._permissionService.getPermissionPoint(e.id);return(i=t==null?void 0:t.value)!=null?i:!0}getSnapshot(){return this._buildSnapshot()}async applyConfig(r){if(r.mode&&await this.setMode(r.mode),r.points)for(const[n,e]of Object.entries(r.points))typeof e=="boolean"&&await this.setPoint(n,e);if(r.rangeProtections&&r.rangeProtections.length>0){const n=r.rangeProtections.map(e=>({ranges:e.rangeRefs.map(t=>this._worksheet.getRange(t)),options:e.options}));await this.protectRanges(n)}}async protectRanges(r){if(!r||r.length===0)throw new Error("Configs cannot be empty");const n=await Promise.all(r.map(o=>{var s,d,u,l;return this._authzIoService.create({objectType:a.UnitObject.SelectRange,selectRangeObject:{collaborators:(u=(d=(s=o.options)==null?void 0:s.allowedUsers)==null?void 0:d.map(m=>({id:m,role:x.Editor,subject:void 0})))!=null?u:[],unitID:this._unitId,name:((l=o.options)==null?void 0:l.name)||"",scope:void 0}})})),e=r.map((o,s)=>{var l;const d=this._determineViewState(o.options),u=this._determineEditState(o.options);return{permissionId:n[s],unitType:a.UnitObject.SelectRange,unitId:this._unitId,subUnitId:this._subUnitId,ranges:o.ranges.map(m=>m.getRange()),id:this._rangeProtectionRuleModel.createRuleId(this._unitId,this._subUnitId),description:((l=o.options)==null?void 0:l.name)||"",viewState:d,editState:u}});if(!await this._commandService.executeCommand(a.AddRangeProtectionMutation.id,{unitId:this._unitId,subUnitId:this._subUnitId,rules:e}))throw new Error("Failed to create range protection rules");return await Promise.all(r.map((o,s)=>this._setPermissionPoints(n[s],o.options))),e.map((o,s)=>this._injector.createInstance(y,this._unitId,this._subUnitId,o.id,o.permissionId,r[s].ranges,r[s].options||{}))}_determineViewState(r){return(r==null?void 0:r.allowViewByOthers)===!1?a.ViewStateEnum.NoOneElseCanView:a.ViewStateEnum.OthersCanView}_determineEditState(r){var n;return(r==null?void 0:r.allowEdit)===!0&&((n=r==null?void 0:r.allowedUsers)!=null&&n.length)?a.EditStateEnum.DesignedUserCanEdit:a.EditStateEnum.OnlyMe}async _setPermissionPoints(r,n){if(!n)return;const e=(t,i)=>t===void 0?i:typeof t=="boolean"?t:!0;await this._setPermissionPoint(r,b.Edit,e(n.allowEdit,!1)),await this._setPermissionPoint(r,b.View,e(n.allowViewByOthers,!0))}async _setPermissionPoint(r,n,e){const t=j[n];if(!t)return;const i=new t(this._unitId,this._subUnitId,r);this._permissionService.getPermissionPoint(i.id)||this._permissionService.addPermissionPoint(i),this._permissionService.updatePermissionPoint(i.id,e)}async unprotectRules(r){!r||r.length===0||await this._commandService.executeCommand(a.DeleteRangeProtectionMutation.id,{unitId:this._unitId,subUnitId:this._subUnitId,ruleIds:r})}async listRangeProtectionRules(){return this._buildRangeProtectionRules()}subscribe(r){const n=this.permission$.subscribe(r);return()=>n.unsubscribe()}dispose(){this._subscriptions.forEach(r=>r.unsubscribe()),this._permissionSubject.complete(),this._rangeRulesSubject.complete()}};H=le([W(1,h.Inject(h.Injector)),W(2,h.IPermissionService),W(3,h.IAuthzIoService),W(4,h.ICommandService),W(5,h.Inject(a.RangeProtectionRuleModel)),W(6,h.Inject(a.WorksheetProtectionPointModel))],H);function ce(r){switch(r){case"left":return h.HorizontalAlign.LEFT;case"center":return h.HorizontalAlign.CENTER;case"normal":return h.HorizontalAlign.RIGHT;default:throw new Error(`Invalid horizontal alignment: ${r}`)}}function J(r){switch(r){case h.HorizontalAlign.LEFT:return"left";case h.HorizontalAlign.CENTER:return"center";case h.HorizontalAlign.RIGHT:return"normal";default:return"general"}}function me(r){switch(r){case"top":return h.VerticalAlign.TOP;case"middle":return h.VerticalAlign.MIDDLE;case"bottom":return h.VerticalAlign.BOTTOM;default:throw new Error(`Invalid vertical alignment: ${r}`)}}function Z(r){switch(r){case h.VerticalAlign.TOP:return"top";case h.VerticalAlign.MIDDLE:return"middle";case h.VerticalAlign.BOTTOM:return"bottom";default:return"general"}}function $(r,n){return{startRow:r.startRow,endRow:r.endRow,startColumn:0,endColumn:n.getColumnCount()-1,rangeType:h.RANGE_TYPE.ROW}}function z(r,n){return{startRow:0,endRow:n.getRowCount()-1,startColumn:r.startColumn,endColumn:r.endColumn,rangeType:h.RANGE_TYPE.COLUMN}}var ge=Object.getOwnPropertyDescriptor,_e=(r,n,e,t)=>{for(var i=t>1?void 0:t?ge(n,e):n,o=r.length-1,s;o>=0;o--)(s=r[o])&&(i=s(i)||i);return i},F=(r,n)=>(e,t)=>n(e,t,r);c.FWorksheet=class extends I.FBaseInitialable{constructor(e,t,i,o,s,d,u){super(o);k(this,"setActiveSelection",this.setActiveRange);this._fWorkbook=e,this._workbook=t,this._worksheet=i,this._injector=o,this._selectionManagerService=s,this._logService=d,this._commandService=u}dispose(){super.dispose(),delete this._fWorkbook,delete this._workbook,delete this._worksheet}getSheet(){return this._worksheet}getInject(){return this._injector}getWorkbook(){return this._workbook}getSheetId(){return this._worksheet.getSheetId()}getSheetName(){return this._worksheet.getName()}getSelection(){const e=this._selectionManagerService.getCurrentSelections();return e?this._injector.createInstance(c.FSelection,this._workbook,this._worksheet,e):null}getDefaultStyle(){return this._worksheet.getDefaultCellStyle()}getRowDefaultStyle(e,t=!1){return t?this._worksheet.getRowStyle(e,t):this._worksheet.getRowStyle(e)}getColumnDefaultStyle(e,t=!1){return t?this._worksheet.getColumnStyle(e,t):this._worksheet.getColumnStyle(e)}setDefaultStyle(e){const t=this._workbook.getUnitId(),i=this._worksheet.getSheetId();return this._commandService.syncExecuteCommand(a.SetWorksheetDefaultStyleMutation.id,{unitId:t,subUnitId:i,defaultStyle:e}),this._worksheet.setDefaultCellStyle(e),this}setColumnDefaultStyle(e,t){const i=this._workbook.getUnitId(),o=this._worksheet.getSheetId(),s={unitId:i,subUnitId:o,columnData:{[e]:{s:t}}};return this._commandService.syncExecuteCommand(a.SetColDataCommand.id,s),this}setRowDefaultStyle(e,t){const i=this._workbook.getUnitId(),o=this._worksheet.getSheetId(),s={unitId:i,subUnitId:o,rowData:{[e]:{s:t}}};return this._commandService.syncExecuteCommand(a.SetRowDataCommand.id,s),this}getRange(e,t,i,o){let s,d;if(typeof e=="object")s=e,d=this._worksheet;else if(typeof e=="string"){const{range:u,sheetName:l}=P.deserializeRangeWithSheet(e),m=l?this._workbook.getSheetBySheetName(l):this._worksheet;if(!m)throw new Error("Range not found");d=m,s={...u,unitId:this._workbook.getUnitId(),sheetId:d.getSheetId(),rangeType:h.RANGE_TYPE.NORMAL,startRow:u.rangeType===h.RANGE_TYPE.COLUMN?0:u.startRow,endRow:u.rangeType===h.RANGE_TYPE.COLUMN?d.getMaxRows()-1:u.endRow,startColumn:u.rangeType===h.RANGE_TYPE.ROW?0:u.startColumn,endColumn:u.rangeType===h.RANGE_TYPE.ROW?d.getMaxColumns()-1:u.endColumn}}else if(typeof e=="number"&&t!==void 0)d=this._worksheet,s={startRow:e,endRow:e+(i!=null?i:1)-1,startColumn:t,endColumn:t+(o!=null?o:1)-1,unitId:this._workbook.getUnitId(),sheetId:this._worksheet.getSheetId()};else throw new Error("Invalid range specification");return this._injector.createInstance(c.FRange,this._workbook,d,s)}getMaxColumns(){return this._worksheet.getMaxColumns()}getMaxRows(){return this._worksheet.getMaxRows()}insertRowAfter(e){return this.insertRowsAfter(e,1)}insertRowBefore(e){return this.insertRowsBefore(e,1)}insertRows(e,t=1){return this.insertRowsBefore(e,t)}insertRowsAfter(e,t){const i=this._workbook.getUnitId(),o=this._worksheet.getSheetId(),s=h.Direction.DOWN,d=e+1,u=e+t,l=0,m=this._worksheet.getColumnCount()-1,_=a.copyRangeStyles(this._worksheet,d,u,l,m,!0,e);return this._commandService.syncExecuteCommand(a.InsertRowByRangeCommand.id,{unitId:i,subUnitId:o,direction:s,range:{startRow:d,endRow:u,startColumn:l,endColumn:m},cellValue:_}),this}insertRowsBefore(e,t){const i=this._workbook.getUnitId(),o=this._worksheet.getSheetId(),s=h.Direction.UP,d=e,u=e+t-1,l=0,m=this._worksheet.getColumnCount()-1,_=a.copyRangeStyles(this._worksheet,d,u,l,m,!0,e-1);return this._commandService.syncExecuteCommand(a.InsertRowByRangeCommand.id,{unitId:i,subUnitId:o,direction:s,range:{startRow:d,endRow:u,startColumn:l,endColumn:m},cellValue:_}),this}deleteRow(e){return this.deleteRows(e,1)}deleteRows(e,t){const i={startRow:e,endRow:e+t-1,startColumn:0,endColumn:this._worksheet.getColumnCount()-1};return this._commandService.syncExecuteCommand(a.RemoveRowByRangeCommand.id,{range:i,unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId()}),this}moveRows(e,t){const i=this._workbook.getUnitId(),o=this._worksheet.getSheetId(),s=$(e.getRange(),this._worksheet),d=s,u={startRow:t,endRow:t,startColumn:s.startColumn,endColumn:s.endColumn};return this._commandService.syncExecuteCommand(a.MoveRowsCommand.id,{unitId:i,subUnitId:o,range:s,fromRange:d,toRange:u}),this}hideRow(e){const t=this._workbook.getUnitId(),i=this._worksheet.getSheetId(),o=$(e.getRange(),this._worksheet);return this._commandService.syncExecuteCommand(a.SetRowHiddenCommand.id,{unitId:t,subUnitId:i,ranges:[o]}),this}hideRows(e,t=1){const i=this._workbook.getUnitId(),o=this._worksheet.getSheetId(),s={startRow:e,endRow:e+t-1,startColumn:0,endColumn:this._worksheet.getColumnCount()-1,rangeType:h.RANGE_TYPE.ROW};return this._commandService.syncExecuteCommand(a.SetRowHiddenCommand.id,{unitId:i,subUnitId:o,ranges:[s]}),this}unhideRow(e){const t=this._workbook.getUnitId(),i=this._worksheet.getSheetId(),o=$(e.getRange(),this._worksheet);return this._commandService.syncExecuteCommand(a.SetSpecificRowsVisibleCommand.id,{unitId:t,subUnitId:i,ranges:[o]}),this}showRows(e,t=1){const i=this._workbook.getUnitId(),o=this._worksheet.getSheetId(),s={startRow:e,endRow:e+t-1,startColumn:0,endColumn:this._worksheet.getColumnCount()-1,rangeType:h.RANGE_TYPE.ROW};return this._commandService.syncExecuteCommand(a.SetSpecificRowsVisibleCommand.id,{unitId:i,subUnitId:o,ranges:[s]}),this}setRowHeight(e,t){return this.setRowHeights(e,1,t)}autoFitRow(e,t=h.BooleanNumber.TRUE){const i=this._workbook.getUnitId(),o=this._worksheet.getSheetId(),s=[{startRow:e,endRow:e,startColumn:0,endColumn:this._worksheet.getColumnCount()-1}];return this._commandService.syncExecuteCommand(a.SetTextWrapCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:s[0],value:h.WrapStrategy.WRAP}),this._commandService.syncExecuteCommand(a.SetWorksheetRowIsAutoHeightMutation.id,{unitId:i,subUnitId:o,ranges:s,autoHeightInfo:t}),this}setRowHeights(e,t,i){var m;const o=this._workbook.getUnitId(),s=this._worksheet.getSheetId(),d=this._worksheet.getRowManager(),u=[],l=[];for(let _=e;_<e+t;_++){const C=((m=d.getRow(_))==null?void 0:m.ah)||this._worksheet.getConfig().defaultRowHeight,v={startRow:_,endRow:_,startColumn:0,endColumn:this._worksheet.getColumnCount()-1};i<=C?u.push(v):l.push(v)}return l.length>0&&this._commandService.syncExecuteCommand(a.SetRowHeightCommand.id,{unitId:o,subUnitId:s,ranges:l,value:i}),u.length>0&&this._commandService.syncExecuteCommand(a.SetWorksheetRowIsAutoHeightCommand.id,{unitId:o,subUnitId:s,ranges:u}),this}getRowHeight(e){return this._worksheet.getRowHeight(e)}setRowAutoHeight(e,t){const i=this._workbook.getUnitId(),o=this._worksheet.getSheetId(),s=[{startRow:e,endRow:e+t-1,startColumn:0,endColumn:this._worksheet.getColumnCount()-1}];return this._commandService.syncExecuteCommand(a.SetWorksheetRowIsAutoHeightCommand.id,{unitId:i,subUnitId:o,ranges:s}),this}setRangesAutoHeight(e){const t=this._workbook.getUnitId(),i=this._worksheet.getSheetId();return this._commandService.syncExecuteCommand(a.SetWorksheetRowIsAutoHeightCommand.id,{unitId:t,subUnitId:i,ranges:e}),this}setRowHeightsForced(e,t,i){const o=this._workbook.getUnitId(),s=this._worksheet.getSheetId(),d=[{startRow:e,endRow:e+t-1,startColumn:0,endColumn:this._worksheet.getColumnCount()-1}];return this._commandService.syncExecuteCommand(a.SetRowHeightCommand.id,{unitId:o,subUnitId:s,ranges:d,value:i}),this}setRowCustom(e){const t=this._workbook.getUnitId(),i=this._worksheet.getSheetId(),o={};for(const[d,u]of Object.entries(e))o[Number(d)]={custom:u};const s={unitId:t,subUnitId:i,rowData:o};return this._commandService.syncExecuteCommand(a.SetRowDataCommand.id,s),this}insertColumnAfter(e){return this.insertColumnsAfter(e,1)}insertColumnBefore(e){return this.insertColumnsBefore(e,1)}insertColumns(e,t=1){return this.insertColumnsBefore(e,t)}insertColumnsAfter(e,t){const i=this._workbook.getUnitId(),o=this._worksheet.getSheetId(),s=h.Direction.RIGHT,d=0,u=this._worksheet.getRowCount()-1,l=e+1,m=e+t,_=a.copyRangeStyles(this._worksheet,d,u,l,m,!1,e);return this._commandService.syncExecuteCommand(a.InsertColByRangeCommand.id,{unitId:i,subUnitId:o,direction:s,range:{startRow:d,endRow:u,startColumn:l,endColumn:m},cellValue:_}),this}insertColumnsBefore(e,t){const i=this._workbook.getUnitId(),o=this._worksheet.getSheetId(),s=h.Direction.LEFT,d=0,u=this._worksheet.getRowCount()-1,l=e,m=e+t-1,_=a.copyRangeStyles(this._worksheet,d,u,l,m,!1,e-1);return this._commandService.syncExecuteCommand(a.InsertColByRangeCommand.id,{unitId:i,subUnitId:o,direction:s,range:{startRow:d,endRow:u,startColumn:l,endColumn:m},cellValue:_}),this}deleteColumn(e){return this.deleteColumns(e,1)}deleteColumns(e,t){const i={startRow:0,endRow:this._worksheet.getRowCount()-1,startColumn:e,endColumn:e+t-1};return this._commandService.syncExecuteCommand(a.RemoveColByRangeCommand.id,{range:i,unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId()}),this}moveColumns(e,t){const i=this._workbook.getUnitId(),o=this._worksheet.getSheetId(),s=z(e.getRange(),this._worksheet),d=s,u={startRow:0,endRow:this._worksheet.getRowCount()-1,startColumn:t,endColumn:t};return this._commandService.syncExecuteCommand(a.MoveColsCommand.id,{unitId:i,subUnitId:o,range:s,fromRange:d,toRange:u}),this}hideColumn(e){const t=this._workbook.getUnitId(),i=this._worksheet.getSheetId(),o=z(e.getRange(),this._worksheet);return this._commandService.syncExecuteCommand(a.SetColHiddenCommand.id,{unitId:t,subUnitId:i,ranges:[o]}),this}hideColumns(e,t=1){const i=this._workbook.getUnitId(),o=this._worksheet.getSheetId(),s={startRow:0,endRow:this._worksheet.getRowCount()-1,startColumn:e,endColumn:e+t-1,rangeType:h.RANGE_TYPE.COLUMN};return this._commandService.syncExecuteCommand(a.SetColHiddenCommand.id,{unitId:i,subUnitId:o,ranges:[s]}),this}unhideColumn(e){const t=this._workbook.getUnitId(),i=this._worksheet.getSheetId(),o=z(e.getRange(),this._worksheet);return this._commandService.syncExecuteCommand(a.SetSpecificColsVisibleCommand.id,{unitId:t,subUnitId:i,ranges:[o]}),this}showColumns(e,t=1){const i=this._workbook.getUnitId(),o=this._worksheet.getSheetId(),s={startRow:0,endRow:this._worksheet.getRowCount()-1,startColumn:e,endColumn:e+t-1,rangeType:h.RANGE_TYPE.COLUMN};return this._commandService.syncExecuteCommand(a.SetSpecificColsVisibleCommand.id,{unitId:i,subUnitId:o,ranges:[s]}),this}setColumnWidth(e,t){return this.setColumnWidths(e,1,t)}setColumnWidths(e,t,i){const o=this._workbook.getUnitId(),s=this._worksheet.getSheetId(),d=[{startColumn:e,endColumn:e+t-1,startRow:0,endRow:this._worksheet.getRowCount()-1}];return this._commandService.syncExecuteCommand(a.SetColWidthCommand.id,{unitId:o,subUnitId:s,ranges:d,value:i}),this}getColumnWidth(e){return this._worksheet.getColumnWidth(e)}setColumnCustom(e){const t=this._workbook.getUnitId(),i=this._worksheet.getSheetId(),o={};for(const[d,u]of Object.entries(e))o[Number(d)]={custom:u};const s={unitId:t,subUnitId:i,columnData:o};return this._commandService.syncExecuteCommand(a.SetColDataCommand.id,s),this}getMergeData(){return this._worksheet.getMergeData().map(e=>this._injector.createInstance(c.FRange,this._workbook,this._worksheet,e))}getMergedRanges(){return this._worksheet.getSnapshot().mergeData.map(t=>this._injector.createInstance(c.FRange,this._workbook,this._worksheet,t))}getCellMergeData(e,t){const o=this._worksheet.getMergedCell(e,t);if(o)return this._injector.createInstance(c.FRange,this._workbook,this._worksheet,o)}getActiveRange(){return this._fWorkbook.getActiveRange()}setActiveRange(e){const{unitId:t,sheetId:i}=e.getRange();if(t!==this._workbook.getUnitId()||i!==this._worksheet.getSheetId())throw new Error("Specified range must be part of the sheet.");return this._fWorkbook.setActiveRange(e),this}getActiveCell(){return this._fWorkbook.getActiveCell()}setFreeze(e){return this._logService.warn("setFreeze is deprecated, use setFrozenRows and setFrozenColumns instead"),this._commandService.syncExecuteCommand(a.SetFrozenCommand.id,{...e,unitId:this._workbook.getUnitId(),subUnitId:this.getSheetId()}),this}cancelFreeze(){return this._commandService.syncExecuteCommand(a.CancelFrozenCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this.getSheetId()}),this}getFreeze(){return this._worksheet.getFreeze()}setFrozenColumns(...e){const t=this.getFreeze();if(arguments.length===1){const i=e[0];this.setFreeze({...t,startColumn:i>0?i:-1,xSplit:i})}else if(arguments.length===2){let[i=0,o=0]=e;i>o&&([i,o]=[o,i]),this._commandService.syncExecuteCommand(a.SetFrozenCommand.id,{startColumn:o+1,xSplit:o-i+1,startRow:t.startRow,ySplit:t.ySplit,unitId:this._workbook.getUnitId(),subUnitId:this.getSheetId()})}return this}setFrozenRows(...e){const t=this.getFreeze();if(arguments.length===1){const i=e[0];this.setFreeze({...t,startRow:i>0?i:-1,ySplit:i})}else if(arguments.length===2){let[i=0,o=0]=e;i>o&&([i,o]=[o,i]),this._commandService.syncExecuteCommand(a.SetFrozenCommand.id,{startRow:o+1,ySplit:o-i+1,startColumn:t.startColumn,xSplit:t.xSplit,unitId:this._workbook.getUnitId(),subUnitId:this.getSheetId()})}return this}getFrozenColumns(){const e=this.getFreeze();return e.startColumn===-1?0:e.startColumn}getFrozenRows(){const e=this.getFreeze();return e.startRow===-1?0:e.startRow}getFrozenRowRange(){const e=this._worksheet.getFreeze();return{startRow:e.startRow-e.ySplit,endRow:e.startRow-1}}getFrozenColumnRange(){const e=this._worksheet.getFreeze();return{startColumn:e.startColumn-e.xSplit,endColumn:e.startColumn-1}}hasHiddenGridLines(){return this._worksheet.getConfig().showGridlines===h.BooleanNumber.FALSE}setHiddenGridlines(e){return this._commandService.syncExecuteCommand(a.ToggleGridlinesCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),showGridlines:e?h.BooleanNumber.FALSE:h.BooleanNumber.TRUE}),this}setGridLinesColor(e){return this._commandService.syncExecuteCommand(a.SetGridlinesColorCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),color:e}),this}getGridLinesColor(){return this._worksheet.getGridlinesColor()}setTabColor(e){return this._commandService.syncExecuteCommand(a.SetTabColorCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),value:e}),this}getTabColor(){return this._worksheet.getTabColor()}onCellDataChange(e){return this._injector.get(h.ICommandService).onCommandExecuted(i=>{if(i.id===a.SetRangeValuesMutation.id){const o=i.params;o.unitId===this._workbook.getUnitId()&&o.subUnitId===this._worksheet.getSheetId()&&o.cellValue&&e(new h.ObjectMatrix(o.cellValue))}})}onBeforeCellDataChange(e){return this._injector.get(h.ICommandService).beforeCommandExecuted(i=>{if(i.id===a.SetRangeValuesMutation.id){const o=i.params;o.unitId===this._workbook.getUnitId()&&o.subUnitId===this._worksheet.getSheetId()&&o.cellValue&&e(new h.ObjectMatrix(o.cellValue))}})}hideSheet(){const e=this._injector.get(h.ICommandService);if(this._workbook.getSheets().filter(s=>s.isSheetHidden()!==h.BooleanNumber.TRUE).length<=1)throw new Error("Cannot hide the only visible sheet");return e.syncExecuteCommand(a.SetWorksheetHideCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId()}),this}showSheet(){return this._injector.get(h.ICommandService).syncExecuteCommand(a.SetWorksheetShowCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId()}),this}isSheetHidden(){return this._worksheet.isSheetHidden()===h.BooleanNumber.TRUE}setName(e){return this._commandService.syncExecuteCommand(a.SetWorksheetNameCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),name:e}),this}activate(){return this._fWorkbook.setActiveSheet(this),this}getIndex(){return this._workbook.getSheetIndex(this._worksheet)}clear(e){if(e&&e.contentsOnly&&!e.formatOnly)return this.clearContents();if(e&&e.formatOnly&&!e.contentsOnly)return this.clearFormats();const t=this._workbook.getUnitId(),i=this._worksheet.getSheetId(),o=this._injector.get(h.ICommandService),s={startRow:0,endRow:this._worksheet.getRowCount()-1,startColumn:0,endColumn:this._worksheet.getColumnCount()-1};return o.syncExecuteCommand(a.ClearSelectionAllCommand.id,{unitId:t,subUnitId:i,ranges:[s],options:e}),this}clearContents(){const e=this._workbook.getUnitId(),t=this._worksheet.getSheetId(),i=this._injector.get(h.ICommandService),o={startRow:0,endRow:this._worksheet.getRowCount()-1,startColumn:0,endColumn:this._worksheet.getColumnCount()-1};return i.syncExecuteCommand(a.ClearSelectionContentCommand.id,{unitId:e,subUnitId:t,ranges:[o]}),this}clearFormats(){const e=this._workbook.getUnitId(),t=this._worksheet.getSheetId(),i=this._injector.get(h.ICommandService),o={startRow:0,endRow:this._worksheet.getRowCount()-1,startColumn:0,endColumn:this._worksheet.getColumnCount()-1};return i.syncExecuteCommand(a.ClearSelectionFormatCommand.id,{unitId:e,subUnitId:t,ranges:[o]}),this}getDataRange(){const{startRow:e,endRow:t,startColumn:i,endColumn:o}=this._worksheet.getDataRealRange();return this.getRange(e,i,t-e+1,o-i+1)}getLastColumns(){return this._worksheet.getLastColumnWithContent()}getLastColumn(){return this._worksheet.getLastColumnWithContent()}getLastRows(){return this._worksheet.getLastRowWithContent()}getLastRow(){return this._worksheet.getLastRowWithContent()}equalTo(e){return e instanceof c.FWorksheet?this._worksheet.getSheetId()===e.getSheetId()&&this._workbook.getUnitId()===e.getWorkbook().getUnitId():!1}insertDefinedName(e,t){const o=this._injector.createInstance(T).setName(e).setRef(t).build();o.localSheetId=this.getSheetId(),this._fWorkbook.insertDefinedNameBuilder(o)}getDefinedNames(){return this._fWorkbook.getDefinedNames().filter(t=>t.getLocalSheetId()===this.getSheetId())}setCustomMetadata(e){return this._worksheet.setCustomMetadata(e),this}getCustomMetadata(){return this._worksheet.getCustomMetadata()}setRowCustomMetadata(e,t){return this._worksheet.getRowManager().setCustomMetadata(e,t),this}setColumnCustomMetadata(e,t){return this._worksheet.getColumnManager().setCustomMetadata(e,t),this}getRowCustomMetadata(e){return this._worksheet.getRowManager().getCustomMetadata(e)}getColumnCustomMetadata(e){return this._worksheet.getColumnManager().getCustomMetadata(e)}appendRow(e){const t=this._worksheet.getCellMatrix().hasValue(),i=this._worksheet.getLastRowWithContent(),o=this._worksheet.getRowCount(),s=this._worksheet.getColumnCount(),d=t?i+1:i,u=new h.ObjectMatrix;for(let l=0;l<e.length;l++)u.setValue(d,l,h.covertCellValue(e[l]));return this._commandService.syncExecuteCommand(a.AppendRowCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),cellValue:u.getMatrix(),insertRowNums:d>o-1?1:0,insertColumnNums:e.length>s?e.length-s:0,maxRows:o,maxColumns:s}),this}setRowCount(e){return this._commandService.syncExecuteCommand(a.SetWorksheetRowCountCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),rowCount:e}),this}setColumnCount(e){return this._commandService.syncExecuteCommand(a.SetWorksheetColumnCountCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),columnCount:e}),this}getWorksheetPermission(){return this._injector.createInstance(H,this)}},c.FWorksheet=_e([F(3,h.Inject(h.Injector)),F(4,h.Inject(a.SheetsSelectionsService)),F(5,h.Inject(h.ILogService)),F(6,h.ICommandService)],c.FWorksheet);var Se=Object.getOwnPropertyDescriptor,we=(r,n,e,t)=>{for(var i=t>1?void 0:t?Se(n,e):n,o=r.length-1,s;o>=0;o--)(s=r[o])&&(i=s(i)||i);return i},N=(r,n)=>(e,t)=>n(e,t,r);let L=class{constructor(r,n,e,t,i,o,s,d,u){k(this,"_permissionSubject");k(this,"_subscriptions",[]);k(this,"permission$");k(this,"protectionChange$");this._unitId=r,this._subUnitId=n,this._range=e,this._worksheet=t,this._injector=i,this._permissionService=o,this._authzIoService=s,this._commandService=d,this._rangeProtectionRuleModel=u,this._permissionSubject=new M.BehaviorSubject(this._buildSnapshot()),this.permission$=this._createPermissionStream(),this.protectionChange$=this._createProtectionChangeStream()}_createPermissionStream(){const r=this._permissionService.permissionPointUpdate$.pipe(w.filter(n=>{const e=n.id;return e.includes(this._unitId)&&e.includes(this._subUnitId)})).subscribe(()=>{this._permissionSubject.next(this._buildSnapshot())});return this._subscriptions.push(r),this._permissionSubject.asObservable().pipe(w.distinctUntilChanged((n,e)=>JSON.stringify(n)===JSON.stringify(e)),w.shareReplay({bufferSize:1,refCount:!0}))}_createProtectionChangeStream(){return this._rangeProtectionRuleModel.ruleChange$.pipe(w.filter(r=>r.unitId!==this._unitId||r.subUnitId!==this._subUnitId?!1:r.type==="delete"?this._rangeMatches(r.rule):r.type==="add"?this._rangeMatches(r.rule):!1),w.map(r=>(this._permissionSubject.next(this._buildSnapshot()),r.type==="delete"?{type:"unprotected",ruleId:r.rule.id}:{type:"protected",rule:this._createFacadeRule(r.rule)})),w.shareReplay({bufferSize:1,refCount:!0}))}_rangeMatches(r){const n=this._range.getRange();return r.ranges.some(e=>n.startRow===e.startRow&&n.startColumn===e.startColumn&&n.endRow===e.endRow&&n.endColumn===e.endColumn)}_createFacadeRule(r){const n=r.ranges.map(t=>this._worksheet.getRange(t.startRow,t.startColumn,t.endRow-t.startRow+1,t.endColumn-t.startColumn+1)),e={name:r.description||"",allowViewByOthers:r.viewState!==a.ViewStateEnum.NoOneElseCanView,allowEdit:r.editState===a.EditStateEnum.DesignedUserCanEdit};return this._injector.createInstance(y,this._unitId,this._subUnitId,r.id,r.permissionId,n,e)}getPoint(r){const n=j[r];if(!n)return console.warn(`Unknown permission point: ${r}`),!1;const e=this._getProtectionRule();if(e){const s=new n(this._unitId,this._subUnitId,e.permissionId),d=this._permissionService.getPermissionPoint(s.id);if(d)return d.value}const t=this._getLocalPermissionId(),i=new n(this._unitId,this._subUnitId,t),o=this._permissionService.getPermissionPoint(i.id);return o?o.value:!0}getSnapshot(){return this._buildSnapshot()}isProtected(){return this._getProtectionRule()!==null}canEdit(){return this.getPoint(b.Edit)}canView(){return this.getPoint(b.View)}canManageCollaborator(){return this.getPoint(b.ManageCollaborator)}canDelete(){return this.getPoint(b.Delete)}async setPoint(r,n){const e=j[r];if(!e)throw new Error(`Unknown permission point: ${r}`);if(this.getPoint(r)===n)return;const i=this._getProtectionRule(),o=(i==null?void 0:i.permissionId)||this._getLocalPermissionId(),s=new e(this._unitId,this._subUnitId,o);this._permissionService.getPermissionPoint(s.id)||this._permissionService.addPermissionPoint(s),this._permissionService.updatePermissionPoint(s.id,n),this._permissionSubject.next(this._buildSnapshot())}_getLocalPermissionId(){const r=this._range.getRange();return`local-${this._unitId}-${this._subUnitId}-${r.startRow}-${r.startColumn}-${r.endRow}-${r.endColumn}`}async protect(r){var d,u;if(this.isProtected())throw new Error("Range is already protected");const n=await this._authzIoService.create({objectType:a.UnitObject.SelectRange,selectRangeObject:{collaborators:(u=(d=r==null?void 0:r.allowedUsers)==null?void 0:d.map(l=>({id:l,role:x.Editor,subject:void 0})))!=null?u:[],unitID:this._unitId,name:(r==null?void 0:r.name)||"",scope:void 0}}),e=this._rangeProtectionRuleModel.createRuleId(this._unitId,this._subUnitId),t=this._range.getRange(),i=this._determineViewState(r),o=this._determineEditState(r);return await this._commandService.executeCommand(a.AddRangeProtectionMutation.id,{unitId:this._unitId,subUnitId:this._subUnitId,rules:[{id:e,permissionId:n,unitType:3,unitId:this._unitId,subUnitId:this._subUnitId,ranges:[t],description:r==null?void 0:r.name,viewState:i,editState:o}]}),await this._setPermissionPoints(n,r),this._injector.createInstance(y,this._unitId,this._subUnitId,e,n,[this._range],r||{})}_determineViewState(r){return(r==null?void 0:r.allowViewByOthers)===!1?a.ViewStateEnum.NoOneElseCanView:a.ViewStateEnum.OthersCanView}_determineEditState(r){var n;return(r==null?void 0:r.allowEdit)===!0&&((n=r==null?void 0:r.allowedUsers)!=null&&n.length)?a.EditStateEnum.DesignedUserCanEdit:a.EditStateEnum.OnlyMe}async _setPermissionPoints(r,n){if(!n)return;const e=(t,i)=>t===void 0?i:typeof t=="boolean"?t:!0;await this._setPermissionPoint(r,b.Edit,e(n.allowEdit,!1)),await this._setPermissionPoint(r,b.View,e(n.allowViewByOthers,!0))}async _setPermissionPoint(r,n,e){const t=j[n];if(!t)return;const i=new t(this._unitId,this._subUnitId,r);this._permissionService.getPermissionPoint(i.id)||this._permissionService.addPermissionPoint(i),this._permissionService.updatePermissionPoint(i.id,e)}async unprotect(){const r=this._getProtectionRule();if(!r)return;const n=r.id;await this._commandService.executeCommand(a.DeleteRangeProtectionMutation.id,{unitId:this._unitId,subUnitId:this._subUnitId,ruleIds:[n]})}async listRules(){return await this._buildProtectionRulesAsync()}subscribe(r){const n=this.permission$.subscribe(r);return()=>n.unsubscribe()}_getProtectionRule(){const r=this._rangeProtectionRuleModel.getSubunitRuleList(this._unitId,this._subUnitId),n=this._range.getRange();for(const e of r)for(const t of e.ranges)if(n.startRow===t.startRow&&n.startColumn===t.startColumn&&n.endRow===t.endRow&&n.endColumn===t.endColumn)return e;return null}_buildProtectionRules(){return this._rangeProtectionRuleModel.getSubunitRuleList(this._unitId,this._subUnitId).map(n=>{const e=n.ranges.map(i=>this._worksheet.getRange(i.startRow,i.startColumn,i.endRow-i.startRow+1,i.endColumn-i.startColumn+1)),t={name:n.description||"",allowViewByOthers:n.viewState!==a.ViewStateEnum.NoOneElseCanView};return n.editState===a.EditStateEnum.DesignedUserCanEdit?t.allowEdit=!0:t.allowEdit=!1,this._injector.createInstance(y,this._unitId,this._subUnitId,n.id,n.permissionId,e,t)})}async _buildProtectionRulesAsync(){const r=this._rangeProtectionRuleModel.getSubunitRuleList(this._unitId,this._subUnitId);return(await Promise.all(r.map(async e=>{const t=e.ranges.map(o=>this._worksheet.getRange(o.startRow,o.startColumn,o.endRow-o.startRow+1,o.endColumn-o.startColumn+1)),i={name:e.description||"",allowViewByOthers:e.viewState!==a.ViewStateEnum.NoOneElseCanView};if(e.editState===a.EditStateEnum.DesignedUserCanEdit)try{const s=(await this._authzIoService.listCollaborators({objectID:e.permissionId,unitID:this._unitId})).filter(d=>d.role===x.Editor).map(d=>{var u;return((u=d.subject)==null?void 0:u.userID)||d.id});i.allowEdit=s.length>0}catch(o){console.warn(`Failed to fetch collaborators for rule ${e.id}:`,o),i.allowEdit=!1}else i.allowEdit=!1;return{rule:e,ranges:t,options:i}}))).map(({rule:e,ranges:t,options:i})=>this._injector.createInstance(y,this._unitId,this._subUnitId,e.id,e.permissionId,t,i))}_buildSnapshot(){const r={};return Object.values(b).forEach(n=>{r[n]=this.getPoint(n)}),r}dispose(){this._subscriptions.forEach(r=>r.unsubscribe()),this._permissionSubject.complete()}};L=we([N(4,h.Inject(h.Injector)),N(5,h.Inject(h.IPermissionService)),N(6,h.Inject(h.IAuthzIoService)),N(7,h.Inject(h.ICommandService)),N(8,h.Inject(a.RangeProtectionRuleModel))],L);var Ce=Object.getOwnPropertyDescriptor,ke=(r,n,e,t)=>{for(var i=t>1?void 0:t?Ce(n,e):n,o=r.length-1,s;o>=0;o--)(s=r[o])&&(i=s(i)||i);return i},G=(r,n)=>(e,t)=>n(e,t,r);c.FRange=(D=class extends I.FBaseInitialable{constructor(n,e,t,i,o,s){super(i),this._workbook=n,this._worksheet=e,this._range=t,this._injector=i,this._commandService=o,this._formulaDataModel=s,this._runInitializers(this._injector,this._workbook,this._worksheet,this._range,this._commandService,this._formulaDataModel)}getUnitId(){return this._workbook.getUnitId()}getSheetName(){return this._worksheet.getName()}getSheetId(){return this._worksheet.getSheetId()}getRange(){return this._range}getRow(){return this._range.startRow}getLastRow(){return this._range.endRow}getColumn(){return this._range.startColumn}getLastColumn(){return this._range.endColumn}getWidth(){return this._range.endColumn-this._range.startColumn+1}getHeight(){return this._range.endRow-this._range.startRow+1}isMerged(){const{startColumn:n,startRow:e,endColumn:t,endRow:i}=this._range;return this._worksheet.getMergedCellRange(e,n,i,t).some(s=>h.Rectangle.equals(s,this._range))}getCellStyleData(n="row"){return n!=="cell"?this._worksheet.getComposedCellStyle(this._range.startRow,this._range.startColumn,n==="row"):this._worksheet.getCellStyle(this._range.startRow,this._range.startColumn)}getFontFamily(n="row"){var e,t;return(t=(e=this.getCellStyleData(n))==null?void 0:e.ff)!=null?t:null}getFontSize(n="row"){var e,t;return(t=(e=this.getCellStyleData(n))==null?void 0:e.fs)!=null?t:null}getCellStyle(n="row"){const e=this.getCellStyleData(n);return e?h.TextStyleValue.create(e):null}getCellStyles(n="row"){return this.getCellDatas().map((t,i)=>t.map((o,s)=>{if(!o)return null;const d=n!=="cell"?this._worksheet.getComposedCellStyle(i+this._range.startRow,s+this._range.startColumn,n==="row"):this._worksheet.getCellStyle(i+this._range.startRow,s+this._range.startColumn);return d?h.TextStyleValue.create(d):null}))}getValue(n){var e,t;return n?this.getValueAndRichTextValue():(t=(e=this._worksheet.getCell(this._range.startRow,this._range.startColumn))==null?void 0:e.v)!=null?t:null}getRawValue(){var e,t;const n=this._worksheet.getCellMatrix().getValue(this._range.startRow,this._range.startColumn);return n!=null&&n.p&&((e=n.p.body)!=null&&e.dataStream)?n.p.body.dataStream:(t=n==null?void 0:n.v)!=null?t:null}getDisplayValue(){var e,t,i;const n=this._worksheet.getCell(this._range.startRow,this._range.startColumn);return n!=null&&n.p&&((e=n.p.body)!=null&&e.dataStream)?n.p.body.dataStream:(i=(t=n==null?void 0:n.v)==null?void 0:t.toString())!=null?i:""}getValues(n){var d,u;if(n)return this.getValueAndRichTextValues();const{startRow:e,endRow:t,startColumn:i,endColumn:o}=this._range,s=[];for(let l=e;l<=t;l++){const m=[];for(let _=i;_<=o;_++)m.push((u=(d=this._worksheet.getCell(l,_))==null?void 0:d.v)!=null?u:null);s.push(m)}return s}getRawValues(){var d,u;const n=this._worksheet.getCellMatrix(),{startRow:e,endRow:t,startColumn:i,endColumn:o}=this._range,s=[];for(let l=e;l<=t;l++){const m=[];for(let _=i;_<=o;_++){const C=n.getValue(l,_);C!=null&&C.p&&((d=C.p.body)!=null&&d.dataStream)?m.push(C.p.body.dataStream):m.push((u=C==null?void 0:C.v)!=null?u:null)}s.push(m)}return s}getDisplayValues(){var s,d,u;const{startRow:n,endRow:e,startColumn:t,endColumn:i}=this._range,o=[];for(let l=n;l<=e;l++){const m=[];for(let _=t;_<=i;_++){const C=this._worksheet.getCell(l,_);C!=null&&C.p&&((s=C.p.body)!=null&&s.dataStream)?m.push(C.p.body.dataStream):m.push((u=(d=C==null?void 0:C.v)==null?void 0:d.toString())!=null?u:"")}o.push(m)}return o}getCellData(){var n;return(n=this._worksheet.getCell(this._range.startRow,this._range.startColumn))!=null?n:null}getCellDatas(){return this.getCellDataGrid()}getCellDataGrid(){const{startRow:n,endRow:e,startColumn:t,endColumn:i}=this._range,o=[];for(let s=n;s<=e;s++){const d=[];for(let u=t;u<=i;u++)d.push(this._worksheet.getCellRaw(s,u));o.push(d)}return o}getRichTextValue(){const n=this.getCellData();return n!=null&&n.p?new h.RichTextValue(n.p):null}getRichTextValues(){return this.getCellDataGrid().map(e=>e.map(t=>t!=null&&t.p?new h.RichTextValue(t.p):null))}getValueAndRichTextValue(){const n=this.getCellData();return n!=null&&n.p?new h.RichTextValue(n.p):n==null?void 0:n.v}getValueAndRichTextValues(){return this.getCellDatas().map(e=>e.map(t=>t!=null&&t.p?new h.RichTextValue(t.p):t==null?void 0:t.v))}getFormula(){var n;return(n=this._formulaDataModel.getFormulaStringByCell(this._range.startRow,this._range.startColumn,this._worksheet.getSheetId(),this._workbook.getUnitId()))!=null?n:""}getFormulas(){const n=[],{startRow:e,endRow:t,startColumn:i,endColumn:o}=this._range,s=this._worksheet.getSheetId(),d=this._workbook.getUnitId();for(let u=e;u<=t;u++){const l=[];for(let m=i;m<=o;m++){const _=this._formulaDataModel.getFormulaStringByCell(u,m,s,d);l.push(_||"")}n.push(l)}return n}getWrap(){return this._worksheet.getRange(this._range).getWrap()===h.BooleanNumber.TRUE}getWraps(){const n=this.getCellDatas(),e=this._workbook.getStyles();return n.map(t=>t.map(i=>{var o;return((o=e.getStyleByCell(i))==null?void 0:o.tb)===h.WrapStrategy.WRAP}))}getWrapStrategy(){return this._worksheet.getRange(this._range).getWrapStrategy()}getHorizontalAlignment(){const n=this._worksheet.getRange(this._range).getHorizontalAlignment();return J(n)}getHorizontalAlignments(){return this._worksheet.getRange(this._range).getHorizontalAlignments().map(e=>e.map(t=>J(t)))}getVerticalAlignment(){return Z(this._worksheet.getRange(this._range).getVerticalAlignment())}getVerticalAlignments(){return this._worksheet.getRange(this._range).getVerticalAlignments().map(e=>e.map(t=>Z(t)))}setCustomMetaData(n){return this.setValue({custom:n})}setCustomMetaDatas(n){return this.setValues(n.map(e=>e.map(t=>({custom:t}))))}getCustomMetaData(){var e;const n=this.getCellData();return(e=n==null?void 0:n.custom)!=null?e:null}getCustomMetaDatas(){return this.getCellDataGrid().map(e=>e.map(t=>{var i;return(i=t==null?void 0:t.custom)!=null?i:null}))}setBorder(n,e,t){return this._commandService.syncExecuteCommand(a.SetBorderBasicCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),ranges:[this._range],value:{type:n,style:e,color:t}}),this}getBackground(){var e,t;const n=this.getCellStyle();return(t=(e=n==null?void 0:n.background)==null?void 0:e.rgb)!=null?t:h.DEFAULT_STYLES.bg.rgb}getBackgrounds(){return this.getCellStyles().map(e=>e.map(t=>{var i,o;return(o=(i=t==null?void 0:t.background)==null?void 0:i.rgb)!=null?o:h.DEFAULT_STYLES.bg.rgb}))}setBackgroundColor(n){return this._commandService.syncExecuteCommand(a.SetStyleCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,style:{type:"bg",value:{rgb:n}}}),this}setBackground(n){return this.setBackgroundColor(n),this}setTextRotation(n){return this._commandService.syncExecuteCommand(a.SetTextRotationCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,value:n}),this}setValue(n){const e=h.covertCellValue(n);if(!e)throw new Error("Invalid value");return this._commandService.syncExecuteCommand(a.SetRangeValuesCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,value:e}),this}setValueForCell(n){const e=h.covertCellValue(n);if(!e)throw new Error("Invalid value");return this._commandService.syncExecuteCommand(a.SetRangeValuesCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:{startColumn:this._range.startColumn,startRow:this._range.startRow,endColumn:this._range.startColumn,endRow:this._range.startRow},value:e}),this}setRichTextValueForCell(n){const e=n instanceof h.RichTextValue?n.getData():n,t={unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:{startColumn:this._range.startColumn,startRow:this._range.startRow,endColumn:this._range.startColumn,endRow:this._range.startRow},value:{p:e}};return this._commandService.syncExecuteCommand(a.SetRangeValuesCommand.id,t),this}setRichTextValues(n){const e=n.map(o=>o.map(s=>s&&{p:s instanceof h.RichTextValue?s.getData():s})),t=h.covertCellValues(e,this._range),i={unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,value:t};return this._commandService.syncExecuteCommand(a.SetRangeValuesCommand.id,i),this}setWrap(n){return this._commandService.syncExecuteCommand(a.SetTextWrapCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,value:n?h.WrapStrategy.WRAP:h.WrapStrategy.UNSPECIFIED}),this}setWrapStrategy(n){return this._commandService.syncExecuteCommand(a.SetTextWrapCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,value:n}),this}setVerticalAlignment(n){return this._commandService.syncExecuteCommand(a.SetVerticalTextAlignCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,value:me(n)}),this}setHorizontalAlignment(n){return this._commandService.syncExecuteCommand(a.SetHorizontalTextAlignCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,value:ce(n)}),this}setValues(n){const e=h.covertCellValues(n,this._range);return this._commandService.syncExecuteCommand(a.SetRangeValuesCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,value:e}),this}setFontWeight(n){let e;if(n==="bold")e=h.BooleanNumber.TRUE;else if(n==="normal")e=h.BooleanNumber.FALSE;else if(n===null)e=null;else throw new Error("Invalid fontWeight");const t={type:"bl",value:e},i={unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,style:t};return this._commandService.syncExecuteCommand(a.SetStyleCommand.id,i),this}setFontStyle(n){let e;if(n==="italic")e=h.BooleanNumber.TRUE;else if(n==="normal")e=h.BooleanNumber.FALSE;else if(n===null)e=null;else throw new Error("Invalid fontStyle");const t={type:"it",value:e},i={unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,style:t};return this._commandService.syncExecuteCommand(a.SetStyleCommand.id,i),this}setFontLine(n){if(n==="underline")this._setFontUnderline({s:h.BooleanNumber.TRUE});else if(n==="line-through")this._setFontStrikethrough({s:h.BooleanNumber.TRUE});else if(n==="none")this._setFontUnderline({s:h.BooleanNumber.FALSE}),this._setFontStrikethrough({s:h.BooleanNumber.FALSE});else if(n===null)this._setFontUnderline(null),this._setFontStrikethrough(null);else throw new Error("Invalid fontLine");return this}_setFontUnderline(n){const e={type:"ul",value:n},t={unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,style:e};this._commandService.syncExecuteCommand(a.SetStyleCommand.id,t)}_setFontStrikethrough(n){const e={type:"st",value:n},t={unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,style:e};this._commandService.syncExecuteCommand(a.SetStyleCommand.id,t)}setFontFamily(n){const e={type:"ff",value:n},t={unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,style:e};return this._commandService.syncExecuteCommand(a.SetStyleCommand.id,t),this}setFontSize(n){const e={type:"fs",value:n},t={unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,style:e};return this._commandService.syncExecuteCommand(a.SetStyleCommand.id,t),this}setFontColor(n){const t={type:"cl",value:n===null?null:{rgb:n}},i={unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,style:t};return this._commandService.syncExecuteCommand(a.SetStyleCommand.id,i),this}merge(n=!0){const e=this._workbook.getUnitId(),t=this._worksheet.getSheetId();return a.addMergeCellsUtil(this._injector,e,t,[this._range],n),this}mergeAcross(n=!0){const e=a.getAddMergeMutationRangeByType([this._range],h.Dimension.ROWS),t=this._workbook.getUnitId(),i=this._worksheet.getSheetId();return a.addMergeCellsUtil(this._injector,t,i,e,n),this}mergeVertically(n=!0){const e=a.getAddMergeMutationRangeByType([this._range],h.Dimension.COLUMNS),t=this._workbook.getUnitId(),i=this._worksheet.getSheetId();return a.addMergeCellsUtil(this._injector,t,i,e,n),this}isPartOfMerge(){const{startRow:n,startColumn:e,endRow:t,endColumn:i}=this._range;return this._worksheet.getMergedCellRange(n,e,t,i).length>0}breakApart(){return this._commandService.syncExecuteCommand(a.RemoveWorksheetMergeCommand.id,{ranges:[this._range]}),this}forEach(n){const{startColumn:e,startRow:t,endColumn:i,endRow:o}=this._range;this._worksheet.getMatrixWithMergedCells(t,e,o,i).forValue((s,d,u)=>{n(s,d,u)})}getA1Notation(n,e,t){const i={...this._range,startAbsoluteRefType:e,endAbsoluteRefType:t};return n?P.serializeRangeWithSheet(this._worksheet.getName(),i):P.serializeRange(i)}activate(){return this._injector.createInstance(c.FWorkbook,this._workbook).setActiveRange(this),this}activateAsCurrentCell(){const n=this._worksheet.getMergedCell(this._range.startRow,this._range.startColumn);if(n&&h.Rectangle.equals(n,this._range)||!n&&this._range.startRow===this._range.endRow&&this._range.startColumn===this._range.endColumn){const i=this._injector.createInstance(c.FWorkbook,this._workbook).getActiveRange();if(!i||i.getUnitId()!==this.getUnitId()||i.getSheetId()!==this.getSheetId())return this.activate();if(h.Rectangle.contains(i.getRange(),this._range)){const o={unitId:this.getUnitId(),subUnitId:this.getSheetId(),selections:[{range:i.getRange(),primary:a.getPrimaryForRange(this.getRange(),this._worksheet),style:null}]};return this._commandService.syncExecuteCommand(a.SetSelectionsOperation.id,o),this}return this.activate()}else throw new Error("The range is not a single cell")}splitTextToColumns(n,e,t){this._commandService.syncExecuteCommand(a.SplitTextToColumnsCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,delimiter:e,customDelimiter:t,treatMultipleDelimitersAsOne:n})}useThemeStyle(n){if(n==null){const e=this.getUsedThemeStyle();e&&this.removeThemeStyle(e)}else this._commandService.syncExecuteCommand(a.SetWorksheetRangeThemeStyleCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,themeName:n})}removeThemeStyle(n){this._commandService.syncExecuteCommand(a.DeleteWorksheetRangeThemeStyleCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,themeName:n})}getUsedThemeStyle(){return this._injector.get(a.SheetRangeThemeService).getAppliedRangeThemeStyle({unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range})}clear(n){return n&&n.contentsOnly&&!n.formatOnly?this.clearContent():n&&n.formatOnly&&!n.contentsOnly?this.clearFormat():(this._commandService.syncExecuteCommand(a.ClearSelectionAllCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),ranges:[this._range],options:n}),this)}clearContent(){return this._commandService.syncExecuteCommand(a.ClearSelectionContentCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),ranges:[this._range]}),this}clearFormat(){return this._commandService.syncExecuteCommand(a.ClearSelectionFormatCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),ranges:[this._range]}),this}insertCells(n){n===h.Dimension.ROWS?this._commandService.executeCommand(a.InsertRangeMoveDownCommand.id,{range:this._range}):this._commandService.executeCommand(a.InsertRangeMoveRightCommand.id,{range:this._range})}deleteCells(n){n===h.Dimension.ROWS?this._commandService.executeCommand(a.DeleteRangeMoveUpCommand.id,{range:this._range}):this._commandService.executeCommand(a.DeleteRangeMoveLeftCommand.id,{range:this._range})}getDataRegion(n){const{startRow:e,startColumn:t,endRow:i,endColumn:o}=this._range,s=this._worksheet.getMaxRows(),d=this._worksheet.getMaxColumns(),u=this._worksheet.getCellMatrix();let l=e,m=t,_=i,C=o;if(n!==h.Dimension.COLUMNS){let v=!1,U=!1;for(let p=t;p<=o&&(e>0&&!h.isNullCell(u.getValue(e-1,p))&&(v=!0),i<s-1&&!h.isNullCell(u.getValue(i+1,p))&&(U=!0),!(v&&U));p++);v&&(l=e-1),U&&(_=i+1)}if(n!==h.Dimension.ROWS){let v=!1,U=!1;for(let p=e;p<=i&&(t>0&&!h.isNullCell(u.getValue(p,t-1))&&(v=!0),o<d-1&&!h.isNullCell(u.getValue(p,o+1))&&(U=!0),!(v&&U));p++);v&&(m=t-1),U&&(C=o+1)}return this._injector.createInstance(c.FRange,this._workbook,this._worksheet,{startRow:l,startColumn:m,endRow:_,endColumn:C})}isBlank(){const n=this._worksheet.getCellMatrix(),{startRow:e,startColumn:t,endRow:i,endColumn:o}=this._range;let s=!0;for(let d=e;d<=i;d++){for(let u=t;u<=o;u++)if(!h.isNullCell(n.getValue(d,u))){s=!1;break}if(!s)break}return s}offset(n,e,t,i){const{startRow:o,startColumn:s,endRow:d,endColumn:u}=this._range,l=o+n,m=s+e,_=t?l+t-1:d+n,C=i?m+i-1:u+e;if(l<0||m<0||_<0||C<0)throw new Error("The row or column index is out of range");return this._injector.createInstance(c.FRange,this._workbook,this._worksheet,{startRow:l,startColumn:m,endRow:_,endColumn:C})}setFormula(n){return this.setValue({f:n})}setFormulas(n){return this.setValues(n.map(e=>e.map(t=>({f:t}))))}getRangePermission(){const n=this._injector.createInstance(c.FWorksheet,this._injector.createInstance(c.FWorkbook,this._workbook),this._workbook,this._worksheet);return this._injector.createInstance(L,this._workbook.getUnitId(),this._worksheet.getSheetId(),this,n)}},D._enableManualInit(),D),c.FRange=ke([G(3,h.Inject(h.Injector)),G(4,h.ICommandService),G(5,h.Inject(P.FormulaDataModel))],c.FRange);var Ie=Object.getOwnPropertyDescriptor,be=(r,n,e,t)=>{for(var i=t>1?void 0:t?Ie(n,e):n,o=r.length-1,s;o>=0;o--)(s=r[o])&&(i=s(i)||i);return i},K=(r,n)=>(e,t)=>n(e,t,r);let Y=class{constructor(r,n,e,t){k(this,"_permissionSubject");k(this,"_collaboratorChangeSubject",new M.Subject);k(this,"permission$");k(this,"pointChange$");k(this,"collaboratorChange$");k(this,"_subscriptions",[]);this._unitId=r,this._injector=n,this._permissionService=e,this._authzIoService=t,this._permissionSubject=new M.BehaviorSubject(this._buildSnapshot()),this.permission$=this._createPermissionStream(),this.pointChange$=this._createPointChangeStream(),this.collaboratorChange$=this._collaboratorChangeSubject.asObservable().pipe(w.shareReplay({bufferSize:1,refCount:!0}))}_createPermissionStream(){const r=this._permissionService.permissionPointUpdate$.pipe(w.filter(n=>n.id.includes(this._unitId))).subscribe(()=>{this._permissionSubject.next(this._buildSnapshot())});return this._subscriptions.push(r),this._permissionSubject.asObservable().pipe(w.distinctUntilChanged((n,e)=>JSON.stringify(n)===JSON.stringify(e)),w.shareReplay({bufferSize:1,refCount:!0}))}_createPointChangeStream(){const r=new Map;for(const n in g){const e=g[n];r.set(e,this.getPoint(e))}return this._permissionService.permissionPointUpdate$.pipe(w.filter(n=>n.id.includes(this._unitId)),w.map(n=>{const e=this._extractWorkbookPointType(n.id);if(!e)return null;const t=!!n.value,i=r.get(e);return r.set(e,t),i===t?null:{point:e,value:t,oldValue:i}}),w.filter(n=>n!==null),w.shareReplay({bufferSize:1,refCount:!0}))}_extractWorkbookPointType(r){for(const n in g){const e=g[n],t=V[e];if(!t)continue;if(new t(this._unitId).id===r)return e}return null}_buildSnapshot(){const r={};for(const n in g){const e=g[n];r[e]=this.getPoint(e)}return r}async setMode(r){const n=this._getModePermissions(r);await this._batchSetPermissionPoints(n)}_getModePermissions(r){const n={};switch(Object.values(g).forEach(e=>{n[e]=!1}),r){case"owner":Object.values(g).forEach(e=>{n[e]=!0});break;case"editor":n[g.Edit]=!0,n[g.View]=!0,n[g.Print]=!0,n[g.Export]=!0,n[g.CopyContent]=!0,n[g.Comment]=!0,n[g.CreateSheet]=!0,n[g.DeleteSheet]=!0,n[g.RenameSheet]=!0,n[g.MoveSheet]=!0,n[g.HideSheet]=!0,n[g.InsertRow]=!0,n[g.InsertColumn]=!0,n[g.DeleteRow]=!0,n[g.DeleteColumn]=!0,n[g.CopySheet]=!0,n[g.CreateProtection]=!0;break;case"viewer":n[g.View]=!0,n[g.Print]=!0;break;case"commenter":n[g.View]=!0,n[g.Comment]=!0,n[g.Print]=!0;break}return n}async _batchSetPermissionPoints(r){const n=[];for(const[e,t]of Object.entries(r)){const i=e,o=V[i];if(!o)throw new Error(`Unknown workbook permission point: ${i}`);const s=this.getPoint(i);if(s===t)continue;const d=new o(this._unitId);this._permissionService.getPermissionPoint(d.id)||this._permissionService.addPermissionPoint(d),this._permissionService.updatePermissionPoint(d.id,t),n.push({point:i,value:t,oldValue:s})}if(n.length>0){const e=this._buildSnapshot();this._permissionSubject.next(e)}}async setReadOnly(){await this.setMode("viewer")}async setEditable(){await this.setMode("editor")}canEdit(){return this.getPoint(g.Edit)}async setPoint(r,n){const e=V[r];if(!e)throw new Error(`Unknown workbook permission point: ${r}`);if(this.getPoint(r)===n)return;const i=new e(this._unitId);this._permissionService.getPermissionPoint(i.id)||this._permissionService.addPermissionPoint(i),this._permissionService.updatePermissionPoint(i.id,n);const s=this._buildSnapshot();this._permissionSubject.next(s)}getPoint(r){var i;const n=V[r];if(!n)throw new Error(`Unknown workbook permission point: ${r}`);const e=new n(this._unitId),t=this._permissionService.getPermissionPoint(e.id);return(i=t==null?void 0:t.value)!=null?i:!0}getSnapshot(){return this._buildSnapshot()}async setCollaborators(r){const n=r.map(e=>({id:e.user.userID,subject:e.user,role:e.role}));await this._authzIoService.putCollaborators({objectID:this._unitId,unitID:this._unitId,collaborators:n}),r.forEach(e=>{this._collaboratorChangeSubject.next({type:"add",collaborator:{user:{id:e.user.userID},role:e.role}})})}async addCollaborator(r,n){await this._authzIoService.createCollaborator({objectID:this._unitId,unitID:this._unitId,collaborators:[{id:r.userID,subject:r,role:n}]}),this._collaboratorChangeSubject.next({type:"add",collaborator:{user:{id:r.userID},role:n}})}async updateCollaborator(r,n){await this._authzIoService.updateCollaborator({objectID:this._unitId,unitID:this._unitId,collaborator:{id:r.userID,subject:r,role:n}}),this._collaboratorChangeSubject.next({type:"update",collaborator:{user:{id:r.userID},role:n}})}async removeCollaborator(r){await this._authzIoService.deleteCollaborator({objectID:this._unitId,unitID:this._unitId,collaboratorID:r}),this._collaboratorChangeSubject.next({type:"delete",collaborator:{user:{id:r},role:q.Reader}})}async removeCollaborators(r){for(const n of r)await this.removeCollaborator(n)}async listCollaborators(){return(await this._authzIoService.listCollaborators({objectID:this._unitId,unitID:this._unitId})).map(n=>{var e,t;return{user:{id:((e=n.subject)==null?void 0:e.userID)||n.id,displayName:((t=n.subject)==null?void 0:t.name)||""},role:n.role}})}subscribe(r){const n=this.permission$.subscribe(r);return()=>n.unsubscribe()}dispose(){this._subscriptions.forEach(r=>r.unsubscribe()),this._permissionSubject.complete(),this._collaboratorChangeSubject.complete()}};Y=be([K(1,h.Inject(h.Injector)),K(2,h.IPermissionService),K(3,h.IAuthzIoService)],Y);var ve=Object.getOwnPropertyDescriptor,Re=(r,n,e,t)=>{for(var i=t>1?void 0:t?ve(n,e):n,o=r.length-1,s;o>=0;o--)(s=r[o])&&(i=s(i)||i);return i},f=(r,n)=>(e,t)=>n(e,t,r);c.FWorkbook=class extends I.FBaseInitialable{constructor(e,t,i,o,s,d,u,l,m,_){super(t);k(this,"id");this._workbook=e,this._injector=t,this._resourceLoaderService=i,this._selectionManagerService=o,this._univerInstanceService=s,this._commandService=d,this._permissionService=u,this._logService=l,this._localeService=m,this._definedNamesService=_,this.id=this._workbook.getUnitId()}getWorkbook(){return this._workbook}dispose(){super.dispose(),this._workbook=null}getId(){return this.id}getName(){return this._workbook.name}setName(e){return this._commandService.syncExecuteCommand(a.SetWorkbookNameCommand.id,{unitId:this._workbook.getUnitId(),name:e}),this}save(){return this._resourceLoaderService.saveUnit(this._workbook.getUnitId())}getSnapshot(){return this._logService.warn("use 'save' instead of 'getSnapshot'"),this.save()}getActiveSheet(){const e=this._workbook.getActiveSheet();return this._injector.createInstance(c.FWorksheet,this,this._workbook,e)}getSheets(){return this._workbook.getSheets().map(e=>this._injector.createInstance(c.FWorksheet,this,this._workbook,e))}create(e,t,i,o){var l,m,_;const s=h.mergeWorksheetSnapshotWithDefault(h.Tools.deepClone((l=o==null?void 0:o.sheet)!=null?l:{}));s.name=e,s.rowCount=t,s.columnCount=i,s.id=(m=o==null?void 0:o.sheet)==null?void 0:m.id;const d=(_=o==null?void 0:o.index)!=null?_:this._workbook.getSheets().length;this._commandService.syncExecuteCommand(a.InsertSheetCommand.id,{unitId:this.id,index:d,sheet:s}),this._commandService.syncExecuteCommand(a.SetWorksheetActiveOperation.id,{unitId:this.id,subUnitId:this._workbook.getSheets()[d].getSheetId()});const u=this._workbook.getActiveSheet();if(!u)throw new Error("No active sheet found");return this._injector.createInstance(c.FWorksheet,this,this._workbook,u)}getSheetBySheetId(e){const t=this._workbook.getSheetBySheetId(e);return t?this._injector.createInstance(c.FWorksheet,this,this._workbook,t):null}getSheetByName(e){const t=this._workbook.getSheetBySheetName(e);return t?this._injector.createInstance(c.FWorksheet,this,this._workbook,t):null}setActiveSheet(e){return this._commandService.syncExecuteCommand(a.SetWorksheetActiveOperation.id,{unitId:this.id,subUnitId:typeof e=="string"?e:e.getSheetId()}),typeof e=="string"?this.getSheetBySheetId(e):e}insertSheet(e,t){var d,u,l;const i=h.mergeWorksheetSnapshotWithDefault(h.Tools.deepClone((d=t==null?void 0:t.sheet)!=null?d:{}));i.name=e,i.id=(u=t==null?void 0:t.sheet)==null?void 0:u.id;const o=(l=t==null?void 0:t.index)!=null?l:this._workbook.getSheets().length;this._commandService.syncExecuteCommand(a.InsertSheetCommand.id,{unitId:this.id,index:o,sheet:i}),this._commandService.syncExecuteCommand(a.SetWorksheetActiveOperation.id,{unitId:this.id,subUnitId:this._workbook.getSheets()[o].getSheetId()});const s=this._workbook.getActiveSheet();if(!s)throw new Error("No active sheet found");return this._injector.createInstance(c.FWorksheet,this,this._workbook,s)}deleteSheet(e){const t=this.id,i=typeof e=="string"?e:e.getSheetId();return this._commandService.syncExecuteCommand(a.RemoveSheetCommand.id,{unitId:t,subUnitId:i})}undo(){return this._univerInstanceService.focusUnit(this.id),this._commandService.syncExecuteCommand(h.UndoCommand.id),this}redo(){return this._univerInstanceService.focusUnit(this.id),this._commandService.syncExecuteCommand(h.RedoCommand.id),this}onBeforeCommandExecute(e){return this._commandService.beforeCommandExecuted(t=>{var i;((i=t.params)==null?void 0:i.unitId)===this.id&&e(t)})}onCommandExecuted(e){return this._commandService.onCommandExecuted(t=>{var i;((i=t.params)==null?void 0:i.unitId)===this.id&&e(t)})}onSelectionChange(e){return h.toDisposable(this._selectionManagerService.selectionMoveEnd$.subscribe(t=>{this._univerInstanceService.getCurrentUnitForType(h.UniverInstanceType.UNIVER_SHEET).getUnitId()===this.id&&(t!=null&&t.length?e(t.map(i=>i.range)):e([]))}))}setEditable(e){const t=new a.WorkbookEditablePermission(this._workbook.getUnitId());return this._permissionService.getPermissionPoint(t.id)||this._permissionService.addPermissionPoint(t),this._permissionService.updatePermissionPoint(t.id,e),this}setActiveRange(e){const t=this.getActiveSheet(),i=e.getRange().sheetId||t.getSheetId(),o=i?this._workbook.getSheetBySheetId(i):this._workbook.getActiveSheet(!0);if(!o)throw new Error("No active sheet found");o.getSheetId()!==t.getSheetId()&&this.setActiveSheet(this._injector.createInstance(c.FWorksheet,this,this._workbook,o));const s={unitId:this.getId(),subUnitId:i,selections:[e].map(d=>({range:d.getRange(),primary:a.getPrimaryForRange(d.getRange(),o),style:null}))};return this._commandService.syncExecuteCommand(a.SetSelectionsOperation.id,s),this}getActiveRange(){const e=this._workbook.getActiveSheet(),i=this._selectionManagerService.getCurrentSelections().find(o=>!!o.primary);return i?this._injector.createInstance(c.FRange,this._workbook,e,i.range):null}getActiveCell(){const e=this._workbook.getActiveSheet(),i=this._selectionManagerService.getCurrentSelections().find(s=>!!s.primary);if(!i)return null;const o={...i.primary,rangeType:h.RANGE_TYPE.NORMAL};return this._injector.createInstance(c.FRange,this._workbook,e,o)}deleteActiveSheet(){const e=this.getActiveSheet();return this.deleteSheet(e)}duplicateSheet(e){return this._commandService.syncExecuteCommand(a.CopySheetCommand.id,{unitId:e.getWorkbook().getUnitId(),subUnitId:e.getSheetId()}),this._injector.createInstance(c.FWorksheet,this,this._workbook,this._workbook.getActiveSheet())}duplicateActiveSheet(){const e=this.getActiveSheet();return this.duplicateSheet(e)}getNumSheets(){return this._workbook.getSheets().length}getLocale(){return this._localeService.getCurrentLocale()}setLocale(e){this._localeService.setLocale(e)}setSpreadsheetLocale(e){return this._localeService.setLocale(e),this}getUrl(){return location.href}moveSheet(e,t){let i=t;return i<0?i=0:i>this._workbook.getSheets().length-1&&(i=this._workbook.getSheets().length-1),this._commandService.syncExecuteCommand(a.SetWorksheetOrderCommand.id,{unitId:e.getWorkbook().getUnitId(),order:i,subUnitId:e.getSheetId()}),this}moveActiveSheet(e){const t=this.getActiveSheet();return this.moveSheet(t,e)}getPermission(){return this._injector.createInstance(c.FPermission)}getWorkbookPermission(){return this._injector.createInstance(Y,this._workbook.getUnitId())}getDefinedName(e){const t=this._definedNamesService.getValueByName(this.id,e);return t?this._injector.createInstance(O,{...t,unitId:this.id}):null}getDefinedNames(){const e=this._definedNamesService.getDefinedNameMap(this.id);return e?Object.values(e).map(t=>this._injector.createInstance(O,{...t,unitId:this.id})):[]}insertDefinedName(e,t){const o=this._injector.createInstance(T).setName(e).setRef(t).build();return o.localSheetId=a.SCOPE_WORKBOOK_VALUE_DEFINED_NAME,this.insertDefinedNameBuilder(o),this}deleteDefinedName(e){const t=this.getDefinedName(e);return t?(t.delete(),!0):!1}insertDefinedNameBuilder(e){e.unitId=this.getId(),this._commandService.syncExecuteCommand(a.SetDefinedNameCommand.id,e)}updateDefinedNameBuilder(e){this._commandService.syncExecuteCommand(a.SetDefinedNameCommand.id,e)}getRegisteredRangeThemes(){return this._injector.get(a.SheetRangeThemeService).getRegisteredRangeThemes()}registerRangeTheme(e){this._commandService.syncExecuteCommand(a.RegisterWorksheetRangeThemeStyleCommand.id,{unitId:this.getId(),rangeThemeStyle:e})}unregisterRangeTheme(e){this._commandService.syncExecuteCommand(a.UnregisterWorksheetRangeThemeStyleCommand.id,{unitId:this.getId(),themeName:e})}createRangeThemeStyle(e,t){return new a.RangeThemeStyle(e,t)}setCustomMetadata(e){return this._workbook.setCustomMetadata(e),this}getCustomMetadata(){return this._workbook.getCustomMetadata()}addStyles(e){this._workbook.addStyles(e)}removeStyles(e){this._workbook.removeStyles(e)}},c.FWorkbook=Re([f(1,h.Inject(h.Injector)),f(2,h.Inject(h.IResourceLoaderService)),f(3,h.Inject(a.SheetsSelectionsService)),f(4,h.IUniverInstanceService),f(5,h.ICommandService),f(6,h.IPermissionService),f(7,h.ILogService),f(8,h.Inject(h.LocaleService)),f(9,P.IDefinedNamesService)],c.FWorkbook);class fe extends I.FUniver{getCommandSheetTarget(n){var o;const e=n.params;if(!e)return this.getActiveSheet();const t=e.unitId?this.getUniverSheet(e.unitId):(o=this.getActiveWorkbook)==null?void 0:o.call(this);if(!t)return;const i=t.getSheetBySheetId(e.subUnitId||e.sheetId)||t.getActiveSheet();if(i)return{workbook:t,worksheet:i}}getSheetTarget(n,e){const t=this.getUniverSheet(n);if(!t)return;const i=t.getSheetBySheetId(e);if(i)return{workbook:t,worksheet:i}}_initWorkbookEvent(n){const e=n.get(h.IUniverInstanceService);this.registerEventHandler(this.Event.WorkbookDisposed,()=>e.unitDisposed$.subscribe(t=>{t.type===h.UniverInstanceType.UNIVER_SHEET&&this.fireEvent(this.Event.WorkbookDisposed,{unitId:t.getUnitId(),unitType:t.type,snapshot:t.getSnapshot()})})),this.registerEventHandler(this.Event.WorkbookCreated,()=>e.unitAdded$.subscribe(t=>{if(t.type===h.UniverInstanceType.UNIVER_SHEET){const i=t,o=n.createInstance(c.FWorkbook,i);this.fireEvent(this.Event.WorkbookCreated,{unitId:t.getUnitId(),type:t.type,workbook:o,unit:o})}}))}_initialize(n){const e=n.get(h.ICommandService);this.registerEventHandler(this.Event.BeforeSheetCreate,()=>e.beforeCommandExecuted(t=>{var i;if(t.id===a.InsertSheetCommand.id){const o=t.params,{unitId:s,index:d,sheet:u}=o||{},l=s?this.getUniverSheet(s):(i=this.getActiveWorkbook)==null?void 0:i.call(this);if(!l)return;const m={workbook:l,index:d,sheet:u};if(this.fireEvent(this.Event.BeforeSheetCreate,m),m.cancel)throw new h.CanceledError}})),this.registerEventHandler(this.Event.BeforeActiveSheetChange,()=>e.beforeCommandExecuted(t=>{var i;if(t.id===a.SetWorksheetActiveOperation.id){const{subUnitId:o,unitId:s}=t.params,d=s?this.getUniverSheet(s):(i=this.getActiveWorkbook)==null?void 0:i.call(this);if(!d||!o)return;const u=d.getSheetBySheetId(o),l=d.getActiveSheet();if(!u||!l)return;const m={workbook:d,activeSheet:u,oldActiveSheet:l};if(this.fireEvent(this.Event.BeforeActiveSheetChange,m),m.cancel)throw new h.CanceledError}})),this.registerEventHandler(this.Event.BeforeSheetDelete,()=>e.beforeCommandExecuted(t=>{if(t.id===a.RemoveSheetCommand.id){const i=this.getCommandSheetTarget(t);if(!i)return;const{workbook:o,worksheet:s}=i,d={workbook:o,worksheet:s};if(this.fireEvent(this.Event.BeforeSheetDelete,d),d.cancel)throw new h.CanceledError}})),this.registerEventHandler(this.Event.BeforeSheetMove,()=>e.beforeCommandExecuted(t=>{if(t.id===a.SetWorksheetOrderMutation.id){const{fromOrder:i,toOrder:o}=t.params,s=this.getCommandSheetTarget(t);if(!s)return;const d={workbook:s.workbook,worksheet:s.worksheet,newIndex:o,oldIndex:i};if(this.fireEvent(this.Event.BeforeSheetMove,d),d.cancel)throw new h.CanceledError}})),this.registerEventHandler(this.Event.BeforeSheetNameChange,()=>e.beforeCommandExecuted(t=>{if(t.id===a.SetWorksheetNameCommand.id){const{name:i}=t.params,o=this.getCommandSheetTarget(t);if(!o)return;const s={workbook:o.workbook,worksheet:o.worksheet,newName:i,oldName:o.worksheet.getSheetName()};if(this.fireEvent(this.Event.BeforeSheetNameChange,s),s.cancel)throw new h.CanceledError}})),this.registerEventHandler(this.Event.BeforeSheetTabColorChange,()=>e.beforeCommandExecuted(t=>{if(t.id===a.SetTabColorMutation.id){const{color:i}=t.params,o=this.getCommandSheetTarget(t);if(!o)return;const s={workbook:o.workbook,worksheet:o.worksheet,newColor:i,oldColor:o.worksheet.getTabColor()};if(this.fireEvent(this.Event.BeforeSheetTabColorChange,s),s.cancel)throw new h.CanceledError}})),this.registerEventHandler(this.Event.BeforeSheetHideChange,()=>e.beforeCommandExecuted(t=>{if(t.id===a.SetWorksheetHideMutation.id){const{hidden:i}=t.params,o=this.getCommandSheetTarget(t);if(!o)return;const s={workbook:o.workbook,worksheet:o.worksheet,hidden:!!i};if(this.fireEvent(this.Event.BeforeSheetHideChange,s),s.cancel)throw new h.CanceledError}})),this.registerEventHandler(this.Event.BeforeGridlineColorChange,()=>e.beforeCommandExecuted(t=>{var i;if(t.id===a.SetGridlinesColorCommand.id){const o=this.getCommandSheetTarget(t);if(!o)return;const s={...o,color:(i=t.params)==null?void 0:i.color};if(this.fireEvent(this.Event.BeforeGridlineColorChange,s),s.cancel)throw new h.CanceledError}})),this.registerEventHandler(this.Event.BeforeGridlineEnableChange,()=>e.beforeCommandExecuted(t=>{var i;if(t.id===a.ToggleGridlinesCommand.id){const o=this.getCommandSheetTarget(t);if(!o)return;const s={...o,enabled:!!((i=t.params)!=null&&i.showGridlines)};if(this.fireEvent(this.Event.BeforeGridlineEnableChange,s),s.cancel)throw new h.CanceledError}})),this.registerEventHandler(this.Event.SheetValueChanged,()=>e.onCommandExecuted(t=>{if(a.COMMAND_LISTENER_VALUE_CHANGE.indexOf(t.id)>-1){if(!this.getActiveSheet())return;const o=a.getValueChangedEffectedRange(t).map(s=>{var d,u;return(u=(d=this.getWorkbook(s.unitId))==null?void 0:d.getSheetBySheetId(s.subUnitId))==null?void 0:u.getRange(s.range)}).filter(Boolean);if(!o.length)return;this.fireEvent(this.Event.SheetValueChanged,{payload:t,effectedRanges:o})}})),this.registerEventHandler(this.Event.SheetCreated,()=>e.onCommandExecuted(t=>{var i;if(t.id===a.InsertSheetCommand.id){const o=t.params,{unitId:s}=o||{},d=s?this.getUniverSheet(s):(i=this.getActiveWorkbook)==null?void 0:i.call(this);if(!d)return;const u=d.getActiveSheet();if(!u)return;const l={workbook:d,worksheet:u};this.fireEvent(this.Event.SheetCreated,l)}})),this.registerEventHandler(this.Event.ActiveSheetChanged,()=>e.onCommandExecuted(t=>{if(t.id===a.SetWorksheetActiveOperation.id){const i=this.getActiveSheet();if(!i)return;const{workbook:o,worksheet:s}=i;this._fireActiveSheetChanged(o,s)}})),this.registerEventHandler(this.Event.SheetDeleted,()=>e.onCommandExecuted(t=>{var i;if(t.id===a.RemoveSheetCommand.id){const{subUnitId:o,unitId:s}=t.params,d=s?this.getUniverSheet(s):(i=this.getActiveWorkbook)==null?void 0:i.call(this);if(!d||!o)return;this._fireSheetDeleted(d,o)}})),this.registerEventHandler(this.Event.SheetMoved,()=>e.onCommandExecuted(t=>{if(t.id===a.SetWorksheetOrderMutation.id){const{toOrder:i}=t.params,o=this.getCommandSheetTarget(t);if(!o)return;this._fireSheetMoved(o.workbook,o.worksheet,i)}})),this.registerEventHandler(this.Event.SheetNameChanged,()=>e.onCommandExecuted(t=>{if(t.id===a.SetWorksheetNameCommand.id){const{name:i}=t.params,o=this.getCommandSheetTarget(t);if(!o)return;this._fireSheetNameChanged(o.workbook,o.worksheet,i)}})),this.registerEventHandler(this.Event.SheetTabColorChanged,()=>e.onCommandExecuted(t=>{if(t.id===a.SetTabColorMutation.id){const{color:i}=t.params,o=this.getCommandSheetTarget(t);if(!o)return;this._fireSheetTabColorChanged(o.workbook,o.worksheet,i)}})),this.registerEventHandler(this.Event.SheetHideChanged,()=>e.onCommandExecuted(t=>{if(t.id===a.SetWorksheetHideMutation.id){const{hidden:i}=t.params,o=this.getCommandSheetTarget(t);if(!o)return;this._fireSheetHideChanged(o.workbook,o.worksheet,!!i)}})),this.registerEventHandler(this.Event.GridlineChanged,()=>e.onCommandExecuted(t=>{if(t.id===a.SetGridlinesColorCommand.id||t.id===a.ToggleGridlinesCommand.id){const i=this.getCommandSheetTarget(t);if(!i)return;this.fireEvent(this.Event.GridlineChanged,{...i,enabled:!i.worksheet.hasHiddenGridLines(),color:i.worksheet.getGridLinesColor()})}})),this._initWorkbookEvent(n)}createUniverSheet(n,e){const i=this._injector.get(h.IUniverInstanceService).createUnit(h.UniverInstanceType.UNIVER_SHEET,n,e);return this._injector.createInstance(c.FWorkbook,i)}createWorkbook(n,e){return this.createUniverSheet(n,e)}getActiveWorkbook(){const n=this._univerInstanceService.getCurrentUnitForType(h.UniverInstanceType.UNIVER_SHEET);return n?this._injector.createInstance(c.FWorkbook,n):null}getActiveUniverSheet(){return this.getActiveWorkbook()}getUniverSheet(n){const e=this._univerInstanceService.getUnit(n,h.UniverInstanceType.UNIVER_SHEET);return e?this._injector.createInstance(c.FWorkbook,e):null}getWorkbook(n){return this.getUniverSheet(n)}getPermission(){return this._injector.createInstance(c.FPermission)}onUniverSheetCreated(n){const e=this._univerInstanceService.getTypeOfUnitAdded$(h.UniverInstanceType.UNIVER_SHEET).subscribe(t=>{const i=this._injector.createInstance(c.FWorkbook,t);n(i)});return h.toDisposable(e)}newDefinedName(){return this._injector.createInstance(T)}getActiveSheet(){const n=this.getActiveWorkbook();if(!n)return null;const e=n.getActiveSheet();return e?{workbook:n,worksheet:e}:null}setFreezeSync(n){this._injector.get(a.SheetsFreezeSyncController).setEnabled(n)}_fireActiveSheetChanged(n,e){this.fireEvent(this.Event.ActiveSheetChanged,{workbook:n,activeSheet:e})}_fireSheetDeleted(n,e){this.fireEvent(this.Event.SheetDeleted,{workbook:n,sheetId:e})}_fireSheetMoved(n,e,t){this.fireEvent(this.Event.SheetMoved,{workbook:n,worksheet:e,newIndex:t})}_fireSheetNameChanged(n,e,t){this.fireEvent(this.Event.SheetNameChanged,{workbook:n,worksheet:e,newName:t})}_fireSheetTabColorChanged(n,e,t){this.fireEvent(this.Event.SheetTabColorChanged,{workbook:n,worksheet:e,newColor:t})}_fireSheetHideChanged(n,e,t){this.fireEvent(this.Event.SheetHideChanged,{workbook:n,worksheet:e,hidden:t})}}I.FUniver.extend(fe);class Q{get SheetValueChangeType(){return a.SheetValueChangeType}get SheetSkeletonChangeType(){return a.SheetSkeletonChangeType}get SplitDelimiterType(){return a.SplitDelimiterEnum}}I.FEnum.extend(Q);class X{get SheetCreated(){return"SheetCreated"}get BeforeSheetCreate(){return"BeforeSheetCreate"}get WorkbookCreated(){return"WorkbookCreated"}get WorkbookDisposed(){return"WorkbookDisposed"}get GridlineChanged(){return"GridlineChanged"}get BeforeGridlineEnableChange(){return"BeforeGridlineEnableChange"}get BeforeGridlineColorChange(){return"BeforeGridlineColorChange"}get BeforeActiveSheetChange(){return"BeforeActiveSheetChange"}get ActiveSheetChanged(){return"ActiveSheetChanged"}get SheetDeleted(){return"SheetDeleted"}get BeforeSheetDelete(){return"BeforeSheetDelete"}get SheetMoved(){return"SheetMoved"}get BeforeSheetMove(){return"BeforeSheetMove"}get SheetNameChanged(){return"SheetNameChanged"}get BeforeSheetNameChange(){return"BeforeSheetNameChange"}get SheetTabColorChanged(){return"SheetTabColorChanged"}get BeforeSheetTabColorChange(){return"BeforeSheetTabColorChange"}get SheetHideChanged(){return"SheetHideChanged"}get BeforeSheetHideChange(){return"BeforeSheetHideChange"}get SheetValueChanged(){return"SheetValueChanged"}}I.FEventName.extend(X);var pe=Object.getOwnPropertyDescriptor,Pe=(r,n,e,t)=>{for(var i=t>1?void 0:t?pe(n,e):n,o=r.length-1,s;o>=0;o--)(s=r[o])&&(i=s(i)||i);return i},Ee=(r,n)=>(e,t)=>n(e,t,r);c.FSheetHooks=class extends I.FBase{constructor(n){super(),this._injector=n}},c.FSheetHooks=Pe([Ee(0,h.Inject(h.Injector))],c.FSheetHooks),c.FSheetEventName=X,c.FSheetsEnum=Q,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})}));
|
|
16
|
+
(function(c,h){typeof exports=="object"&&typeof module<"u"?h(exports,require("@univerjs/core"),require("@univerjs/core/facade"),require("@univerjs/sheets"),require("@univerjs/engine-formula"),require("rxjs"),require("rxjs/operators")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","@univerjs/core/facade","@univerjs/sheets","@univerjs/engine-formula","rxjs","rxjs/operators"],h):(c=typeof globalThis<"u"?globalThis:c||self,h(c.UniverSheetsFacade={},c.UniverCore,c.UniverCoreFacade,c.UniverSheets,c.UniverEngineFormula,c.rxjs,c.rxjs.operators))})(this,(function(c,h,b,s,P,j,C){"use strict";var De=Object.defineProperty;var je=(c,h,b)=>h in c?De(c,h,{enumerable:!0,configurable:!0,writable:!0,value:b}):c[h]=b;var w=(c,h,b)=>je(c,typeof h!="symbol"?h+"":h,b);var D;var te=Object.getOwnPropertyDescriptor,ne=(r,n,e,t)=>{for(var i=t>1?void 0:t?te(n,e):n,o=r.length-1,a;o>=0;o--)(a=r[o])&&(i=a(i)||i);return i},p=(r,n)=>(e,t)=>n(e,t,r);function ie(r,n,e){const t=e.getDefinedNameMap(r);if(t==null)return n.t("definedName.defaultName")+1;const o=Array.from(Object.values(t)).length+1,a=n.t("definedName.defaultName")+o;if(e.getValueByName(r,a)==null)return a;let d=o+1;for(;;){const u=n.t("definedName.defaultName")+d;if(e.getValueByName(r,u)==null)return u;d++}}class V{constructor(){w(this,"_definedNameParam");this._definedNameParam={id:h.generateRandomId(10),unitId:"",name:"",formulaOrRefString:"",localSheetId:s.SCOPE_WORKBOOK_VALUE_DEFINED_NAME}}setName(n){return this._definedNameParam.name=n,this}setFormula(n){return this._definedNameParam.formulaOrRefString=`=${n}`,this}setRef(n){return this._definedNameParam.formulaOrRefString=n,this}setRefByRange(n,e,t,i){return this._definedNameParam.formulaOrRefString=P.serializeRange({startRow:n,endRow:n+(t!=null?t:1)-1,startColumn:e,endColumn:e+(i!=null?i:1)-1}),this}setComment(n){return this._definedNameParam.comment=n,this}setScopeToWorksheet(n){return this._definedNameParam.localSheetId=n.getSheetId(),this}setScopeToWorkbook(){return this._definedNameParam.localSheetId=s.SCOPE_WORKBOOK_VALUE_DEFINED_NAME,this}setHidden(n){return this._definedNameParam.hidden=n,this}build(){return this._definedNameParam}load(n){return this._definedNameParam=n,this}}let A=class extends b.FBase{constructor(r,n,e,t,i,o,a,d,u,l){super(),this._definedNameParam=r,this._injector=n,this._commandService=e,this._permissionService=t,this._worksheetProtectionRuleModel=i,this._rangeProtectionRuleModel=o,this._worksheetProtectionPointRuleModel=a,this._authzIoService=d,this._localeService=u,this._definedNamesService=l}_apply(){this._definedNameParam.name===""&&(this._definedNameParam.name=ie(this._definedNameParam.unitId,this._localeService,this._definedNamesService)),this._commandService.syncExecuteCommand(s.SetDefinedNameCommand.id,this._definedNameParam)}getName(){return this._definedNameParam.name}setName(r){this._definedNameParam.name=r,this._apply()}setFormula(r){this._definedNameParam.formulaOrRefString=`=${r}`,this._apply()}setRef(r){this._definedNameParam.formulaOrRefString=r,this._apply()}getFormulaOrRefString(){return this._definedNameParam.formulaOrRefString}setRefByRange(r,n,e,t){this._definedNameParam.formulaOrRefString=P.serializeRange({startRow:r,endRow:r+(e!=null?e:1)-1,startColumn:n,endColumn:n+(t!=null?t:1)-1}),this._apply()}getComment(){return this._definedNameParam.comment}setComment(r){this._definedNameParam.comment=r,this._apply()}setScopeToWorksheet(r){this._definedNameParam.localSheetId=r.getSheetId(),this._apply()}setScopeToWorkbook(){this._definedNameParam.localSheetId=s.SCOPE_WORKBOOK_VALUE_DEFINED_NAME,this._apply()}setHidden(r){this._definedNameParam.hidden=r,this._apply()}delete(){this._commandService.syncExecuteCommand(s.RemoveDefinedNameCommand.id,this._definedNameParam)}getLocalSheetId(){return this._definedNameParam.localSheetId}isWorkbookScope(){return this._definedNameParam.localSheetId===s.SCOPE_WORKBOOK_VALUE_DEFINED_NAME}toBuilder(){const r=this._injector.createInstance(V);return r.load(this._definedNameParam),r}};A=ne([p(1,h.Inject(h.Injector)),p(2,h.ICommandService),p(3,h.IPermissionService),p(4,h.Inject(s.WorksheetProtectionRuleModel)),p(5,h.Inject(s.RangeProtectionRuleModel)),p(6,h.Inject(s.WorksheetProtectionPointModel)),p(7,h.Inject(h.IAuthzIoService)),p(8,h.Inject(h.LocaleService)),p(9,P.IDefinedNamesService)],A);var M=(r=>(r[r.Reader=0]="Reader",r[r.Editor=1]="Editor",r[r.Owner=2]="Owner",r))(M||{}),g=(r=>(r.Edit="WorkbookEdit",r.View="WorkbookView",r.Print="WorkbookPrint",r.Export="WorkbookExport",r.Share="WorkbookShare",r.CopyContent="WorkbookCopy",r.DuplicateFile="WorkbookDuplicate",r.Comment="WorkbookComment",r.ManageCollaborator="WorkbookManageCollaborator",r.CreateSheet="WorkbookCreateSheet",r.DeleteSheet="WorkbookDeleteSheet",r.RenameSheet="WorkbookRenameSheet",r.MoveSheet="WorkbookMoveSheet",r.HideSheet="WorkbookHideSheet",r.ViewHistory="WorkbookViewHistory",r.ManageHistory="WorkbookHistory",r.RecoverHistory="WorkbookRecoverHistory",r.CreateProtection="WorkbookCreateProtect",r.InsertRow="WorkbookInsertRow",r.InsertColumn="WorkbookInsertColumn",r.DeleteRow="WorkbookDeleteRow",r.DeleteColumn="WorkbookDeleteColumn",r.CopySheet="WorkbookCopySheet",r))(g||{}),S=(r=>(r.Edit="WorksheetEdit",r.View="WorksheetView",r.Copy="WorksheetCopy",r.SetCellValue="WorksheetSetCellValue",r.SetCellStyle="WorksheetSetCellStyle",r.SetRowStyle="WorksheetSetRowStyle",r.SetColumnStyle="WorksheetSetColumnStyle",r.InsertRow="WorksheetInsertRow",r.InsertColumn="WorksheetInsertColumn",r.DeleteRow="WorksheetDeleteRow",r.DeleteColumn="WorksheetDeleteColumn",r.Sort="WorksheetSort",r.Filter="WorksheetFilter",r.PivotTable="WorksheetPivotTable",r.InsertHyperlink="WorksheetInsertHyperlink",r.EditExtraObject="WorksheetEditExtraObject",r.ManageCollaborator="WorksheetManageCollaborator",r.DeleteProtection="WorksheetDeleteProtection",r.SelectProtectedCells="WorksheetSelectProtectedCells",r.SelectUnProtectedCells="WorksheetSelectUnProtectedCells",r))(S||{}),I=(r=>(r.Edit="RangeEdit",r.View="RangeView",r.ManageCollaborator="RangeManageCollaborator",r.Delete="RangeDeleteProtection",r))(I||{}),re=Object.getOwnPropertyDescriptor,oe=(r,n,e,t)=>{for(var i=t>1?void 0:t?re(n,e):n,o=r.length-1,a;o>=0;o--)(a=r[o])&&(i=a(i)||i);return i},U=(r,n)=>(e,t)=>n(e,t,r);c.FPermission=class extends b.FBase{constructor(e,t,i,o,a,d,u,l){super();w(this,"permissionPointsDefinition",s.PermissionPointsDefinitions);w(this,"rangeRuleChangedAfterAuth$");w(this,"sheetRuleChangedAfterAuth$");w(this,"unitPermissionInitStateChange$");this._injector=e,this._commandService=t,this._permissionService=i,this._worksheetProtectionRuleModel=o,this._rangeProtectionRuleModel=a,this._worksheetProtectionPointRuleModel=d,this._workbookPermissionService=u,this._authzIoService=l,this.rangeRuleChangedAfterAuth$=this._rangeProtectionRuleModel.ruleRefresh$,this.sheetRuleChangedAfterAuth$=this._worksheetProtectionRuleModel.ruleRefresh$,this.unitPermissionInitStateChange$=this._workbookPermissionService.unitPermissionInitStateChange$}setWorkbookPermissionPoint(e,t,i){const o=new t(e);this._permissionService.getPermissionPoint(o.id)||this._permissionService.addPermissionPoint(o),this._permissionService.updatePermissionPoint(o.id,i)}checkWorkbookPermissionPoint(e,t){const i=new t(e),o=this._permissionService.getPermissionPoint(i.id);if(o)return o.value}setWorkbookEditPermission(e,t){this.setWorkbookPermissionPoint(e,s.WorkbookEditablePermission,t)}async addWorksheetBasePermission(e,t,i){let o=[];i!=null&&i.allowedUsers&&(o=i.allowedUsers.map(u=>({id:u,role:M.Editor,subject:void 0})));const a=await this._authzIoService.create({objectType:s.UnitObject.Worksheet,worksheetObject:{collaborators:o,unitID:e,strategies:[],name:(i==null?void 0:i.name)||"",scope:void 0}});if(this._commandService.syncExecuteCommand(s.AddWorksheetProtectionMutation.id,{unitId:e,subUnitId:t,rule:{permissionId:a,unitType:s.UnitObject.Worksheet,unitId:e,subUnitId:t}}))return a}removeWorksheetPermission(e,t){this._commandService.syncExecuteCommand(s.DeleteWorksheetProtectionMutation.id,{unitId:e,subUnitId:t}),[...s.getAllWorksheetPermissionPoint(),...s.getAllWorksheetPermissionPointByPointPanel()].forEach(i=>{const o=new i(e,t);this._permissionService.updatePermissionPoint(o.id,!0)}),this._worksheetProtectionPointRuleModel.deleteRule(e,t)}async setWorksheetPermissionPoint(e,t,i,o){const a=this._worksheetProtectionRuleModel.getRule(e,t);let d;if(i===s.WorksheetEditPermission||i===s.WorksheetViewPermission)a?d=a.permissionId:d=await this.addWorksheetBasePermission(e,t);else{const _=this._worksheetProtectionPointRuleModel.getRule(e,t);_?d=_.permissionId:(d=await this._authzIoService.create({objectType:s.UnitObject.Worksheet,worksheetObject:{collaborators:[],unitID:e,strategies:[],name:"",scope:void 0}}),this._commandService.syncExecuteCommand(s.SetWorksheetPermissionPointsMutation.id,{unitId:e,subUnitId:t,rule:{unitId:e,subUnitId:t,permissionId:d}}))}const l=new i(e,t);return this._permissionService.getPermissionPoint(l.id)||this._permissionService.addPermissionPoint(l),this._permissionService.updatePermissionPoint(l.id,o),d}checkWorksheetPermissionPoint(e,t,i){const o=new i(e,t),a=this._permissionService.getPermissionPoint(o.id);if(a)return a.value}async addRangeBaseProtection(e,t,i,o){var R,f;const a=await this._authzIoService.create({objectType:s.UnitObject.SelectRange,selectRangeObject:{collaborators:(f=(R=o==null?void 0:o.allowedUsers)==null?void 0:R.map(T=>({id:T,role:M.Editor,subject:void 0})))!=null?f:[],unitID:e,name:(o==null?void 0:o.name)||"",scope:void 0}}),d=`ruleId_${h.generateRandomId(6)}`;if(this._rangeProtectionRuleModel.getSubunitRuleList(e,t).some(T=>T.ranges.some(Ue=>i.some(We=>h.Rectangle.intersects(We.getRange(),Ue)))))throw new Error("range protection cannot intersect");const m=this._determineRangeViewState(o),_=this._determineRangeEditState(o),k={unitId:e,subUnitId:t,rules:[{permissionId:a,unitType:s.UnitObject.SelectRange,unitId:e,subUnitId:t,ranges:i.map(T=>T.getRange()),id:d,description:o==null?void 0:o.name,viewState:m,editState:_}]};if(this._commandService.syncExecuteCommand(s.AddRangeProtectionMutation.id,k))return{permissionId:a,ruleId:d}}_determineRangeViewState(e){return(e==null?void 0:e.allowViewByOthers)===!1?s.ViewStateEnum.NoOneElseCanView:s.ViewStateEnum.OthersCanView}_determineRangeEditState(e){var t;return(e==null?void 0:e.allowEdit)===!0&&((t=e==null?void 0:e.allowedUsers)!=null&&t.length)?s.EditStateEnum.DesignedUserCanEdit:s.EditStateEnum.OnlyMe}removeRangeProtection(e,t,i){this._commandService.syncExecuteCommand(s.DeleteRangeProtectionMutation.id,{unitId:e,subUnitId:t,ruleIds:i})&&this._rangeProtectionRuleModel.getSubunitRuleList(e,t).length===0&&(this._worksheetProtectionPointRuleModel.deleteRule(e,t),[...s.getAllWorksheetPermissionPointByPointPanel()].forEach(d=>{const u=new d(e,t);this._permissionService.updatePermissionPoint(u.id,u.value)}))}setRangeProtectionPermissionPoint(e,t,i,o,a){const d=new o(e,t,i);this._permissionService.getPermissionPoint(d.id)||this._permissionService.addPermissionPoint(d),this._permissionService.updatePermissionPoint(d.id,a)}setRangeProtectionRanges(e,t,i,o){const a=this._rangeProtectionRuleModel.getRule(e,t,i);if(a){if(this._rangeProtectionRuleModel.getSubunitRuleList(e,t).filter(l=>l.id!==i).some(l=>l.ranges.some(m=>o.some(_=>h.Rectangle.intersects(_.getRange(),m)))))throw new Error("range protection cannot intersect");this._commandService.syncExecuteCommand(s.SetRangeProtectionMutation.id,{unitId:e,subUnitId:t,ruleId:i,rule:{...a,ranges:o.map(l=>l.getRange())}})}}getPermissionInfoWithCell(e,t,i,o){const a=h.cellToRange(i,o),d=this._rangeProtectionRuleModel.getSubunitRuleList(e,t).find(u=>u.ranges.some(m=>h.Rectangle.intersects(a,m)));if(d)return{permissionId:d.permissionId,ruleId:d.id}}},c.FPermission=oe([U(0,h.Inject(h.Injector)),U(1,h.ICommandService),U(2,h.IPermissionService),U(3,h.Inject(s.WorksheetProtectionRuleModel)),U(4,h.Inject(s.RangeProtectionRuleModel)),U(5,h.Inject(s.WorksheetProtectionPointModel)),U(6,h.Inject(s.WorkbookPermissionService)),U(7,h.Inject(h.IAuthzIoService))],c.FPermission);var se=Object.getOwnPropertyDescriptor,ae=(r,n,e,t)=>{for(var i=t>1?void 0:t?se(n,e):n,o=r.length-1,a;o>=0;o--)(a=r[o])&&(i=a(i)||i);return i},he=(r,n)=>(e,t)=>n(e,t,r);c.FSelection=class{constructor(n,e,t,i){this._workbook=n,this._worksheet=e,this._selections=t,this._injector=i}getActiveRange(){const n=this._selections.find(e=>!!e.primary);return n?this._injector.createInstance(c.FRange,this._workbook,this._worksheet,n.range):null}getActiveRangeList(){return this._selections.map(n=>this._injector.createInstance(c.FRange,this._workbook,this._worksheet,n.range))}getCurrentCell(){const n=this._selections.find(e=>!!e.primary);return n?n.primary:null}getActiveSheet(){const n=this._injector.createInstance(c.FWorkbook,this._workbook);return this._injector.createInstance(c.FWorksheet,n,this._workbook,this._worksheet)}updatePrimaryCell(n){const e=this._injector.get(h.ICommandService);let t=[],i=!1;for(const{range:a,style:d}of this._selections)h.Rectangle.contains(a,n.getRange())?(t.push({range:a,primary:s.getPrimaryForRange(n.getRange(),this._worksheet),style:d}),i=!0):t.push({range:a,primary:null,style:d});i||(t=[{range:n.getRange(),primary:s.getPrimaryForRange(n.getRange(),this._worksheet)}]);const o={unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),selections:t};return e.syncExecuteCommand(s.SetSelectionsOperation.id,o),new c.FSelection(this._workbook,this._worksheet,t,this._injector)}getNextDataRange(n){if(!this._selections.find(i=>!!i.primary))return null;const t=s.getNextPrimaryCell(this._selections.concat(),n,this._worksheet);return t?this._injector.createInstance(c.FRange,this._workbook,this._worksheet,t):null}},c.FSelection=ae([he(3,h.Inject(h.Injector))],c.FSelection);var H=(r=>(r[r.Reader=0]="Reader",r[r.Editor=1]="Editor",r[r.Owner=2]="Owner",r[r.UNRECOGNIZED=-1]="UNRECOGNIZED",r))(H||{}),de=Object.getOwnPropertyDescriptor,ue=(r,n,e,t)=>{for(var i=t>1?void 0:t?de(n,e):n,o=r.length-1,a;o>=0;o--)(a=r[o])&&(i=a(i)||i);return i},$=(r,n)=>(e,t)=>n(e,t,r);let E=class{constructor(r,n,e,t,i,o,a,d,u){this._unitId=r,this._subUnitId=n,this._ruleId=e,this._permissionId=t,this._ranges=i,this._options=o,this._injector=a,this._commandService=d,this._rangeProtectionRuleModel=u}get id(){return this._ruleId}get ranges(){return this._ranges}get options(){return{...this._options}}async updateRanges(r){if(!r||r.length===0)throw new Error("Ranges cannot be empty");const n=this._rangeProtectionRuleModel.getRule(this._unitId,this._subUnitId,this._ruleId);if(!n)throw new Error(`Rule ${this._ruleId} not found`);if(this._rangeProtectionRuleModel.getSubunitRuleList(this._unitId,this._subUnitId).filter(i=>i.id!==this._ruleId).some(i=>i.ranges.some(o=>r.some(a=>{const d=a.getRange();return this._rangesIntersect(d,o)}))))throw new Error("Range protection cannot intersect with other protection rules");await this._commandService.executeCommand(s.SetRangeProtectionMutation.id,{unitId:this._unitId,subUnitId:this._subUnitId,ruleId:this._ruleId,rule:{...n,ranges:r.map(i=>i.getRange())}}),this._ranges.length=0,this._ranges.push(...r)}async remove(){await this._commandService.executeCommand(s.DeleteRangeProtectionMutation.id,{unitId:this._unitId,subUnitId:this._subUnitId,ruleIds:[this._ruleId]})}_rangesIntersect(r,n){return!(r.endRow<n.startRow||r.startRow>n.endRow||r.endColumn<n.startColumn||r.startColumn>n.endColumn)}};E=ue([$(6,h.Inject(h.Injector)),$(7,h.Inject(h.ICommandService)),$(8,h.Inject(s.RangeProtectionRuleModel))],E);const x={[g.Edit]:s.WorkbookEditablePermission,[g.View]:s.WorkbookViewPermission,[g.Print]:s.WorkbookPrintPermission,[g.Export]:s.WorkbookExportPermission,[g.Share]:s.WorkbookSharePermission,[g.CopyContent]:s.WorkbookCopyPermission,[g.DuplicateFile]:s.WorkbookDuplicatePermission,[g.Comment]:s.WorkbookCommentPermission,[g.ManageCollaborator]:s.WorkbookManageCollaboratorPermission,[g.CreateSheet]:s.WorkbookCreateSheetPermission,[g.DeleteSheet]:s.WorkbookDeleteSheetPermission,[g.RenameSheet]:s.WorkbookRenameSheetPermission,[g.MoveSheet]:s.WorkbookMoveSheetPermission,[g.HideSheet]:s.WorkbookHideSheetPermission,[g.ViewHistory]:s.WorkbookViewHistoryPermission,[g.ManageHistory]:s.WorkbookHistoryPermission,[g.RecoverHistory]:s.WorkbookRecoverHistoryPermission,[g.CreateProtection]:s.WorkbookCreateProtectPermission,[g.InsertRow]:s.WorkbookInsertRowPermission,[g.InsertColumn]:s.WorkbookInsertColumnPermission,[g.DeleteRow]:s.WorkbookDeleteRowPermission,[g.DeleteColumn]:s.WorkbookDeleteColumnPermission,[g.CopySheet]:s.WorkbookCopySheetPermission},F={[S.Edit]:s.WorksheetEditPermission,[S.View]:s.WorksheetViewPermission,[S.Copy]:s.WorksheetCopyPermission,[S.SetCellValue]:s.WorksheetSetCellValuePermission,[S.SetCellStyle]:s.WorksheetSetCellStylePermission,[S.SetRowStyle]:s.WorksheetSetRowStylePermission,[S.SetColumnStyle]:s.WorksheetSetColumnStylePermission,[S.InsertRow]:s.WorksheetInsertRowPermission,[S.InsertColumn]:s.WorksheetInsertColumnPermission,[S.DeleteRow]:s.WorksheetDeleteRowPermission,[S.DeleteColumn]:s.WorksheetDeleteColumnPermission,[S.Sort]:s.WorksheetSortPermission,[S.Filter]:s.WorksheetFilterPermission,[S.PivotTable]:s.WorksheetPivotTablePermission,[S.InsertHyperlink]:s.WorksheetInsertHyperlinkPermission,[S.EditExtraObject]:s.WorksheetEditExtraObjectPermission,[S.ManageCollaborator]:s.WorksheetManageCollaboratorPermission,[S.DeleteProtection]:s.WorksheetDeleteProtectionPermission,[S.SelectProtectedCells]:s.WorksheetSelectProtectedCellsPermission,[S.SelectUnProtectedCells]:s.WorksheetSelectUnProtectedCellsPermission},N={[I.Edit]:s.RangeProtectionPermissionEditPoint,[I.View]:s.RangeProtectionPermissionViewPoint,[I.ManageCollaborator]:s.RangeProtectionPermissionManageCollaPoint,[I.Delete]:s.RangeProtectionPermissionDeleteProtectionPoint};var le=Object.getOwnPropertyDescriptor,ce=(r,n,e,t)=>{for(var i=t>1?void 0:t?le(n,e):n,o=r.length-1,a;o>=0;o--)(a=r[o])&&(i=a(i)||i);return i},W=(r,n)=>(e,t)=>n(e,t,r);let z=class{constructor(r,n,e,t,i,o,a,d){w(this,"_permissionSubject");w(this,"_rangeRulesSubject");w(this,"permission$");w(this,"pointChange$");w(this,"rangeProtectionChange$");w(this,"rangeProtectionRules$");w(this,"_unitId");w(this,"_subUnitId");w(this,"_subscriptions",[]);w(this,"_fPermission");this._worksheet=r,this._injector=n,this._permissionService=e,this._authzIoService=t,this._commandService=i,this._rangeProtectionRuleModel=o,this._worksheetProtectionPointModel=a,this._worksheetProtectionRuleModel=d,this._unitId=this._worksheet.getWorkbook().getUnitId(),this._subUnitId=this._worksheet.getSheetId(),this._fPermission=this._injector.createInstance(c.FPermission),this._permissionSubject=new j.BehaviorSubject(this._buildSnapshot()),this._rangeRulesSubject=new j.BehaviorSubject(this._buildRangeProtectionRules()),this.permission$=this._createPermissionStream(),this.pointChange$=this._createPointChangeStream(),this.rangeProtectionChange$=this._createRangeProtectionChangeStream(),this.rangeProtectionRules$=this._createRangeProtectionRulesStream()}_createPermissionStream(){const r=this._permissionService.permissionPointUpdate$.pipe(C.filter(n=>n.id.includes(this._unitId)&&n.id.includes(this._subUnitId))).subscribe(()=>{this._permissionSubject.next(this._buildSnapshot())});return this._subscriptions.push(r),this._permissionSubject.asObservable().pipe(C.distinctUntilChanged((n,e)=>JSON.stringify(n)===JSON.stringify(e)),C.shareReplay({bufferSize:1,refCount:!0}))}_createPointChangeStream(){return this._permissionService.permissionPointUpdate$.pipe(C.filter(r=>r.id.includes(this._unitId)&&r.id.includes(this._subUnitId)),C.map(r=>{var e,t;const n=this._extractWorksheetPointType(r.id);return n?{point:n,value:(e=r.value)!=null?e:!1,oldValue:!((t=r.value)!=null&&t)}:null}),C.filter(r=>r!==null),C.shareReplay({bufferSize:1,refCount:!0}))}_createRangeProtectionChangeStream(){return this._rangeProtectionRuleModel.ruleChange$.pipe(C.filter(r=>r.unitId===this._unitId&&r.subUnitId===this._subUnitId),C.map(r=>{const n=this._buildRangeProtectionRules();return{type:r.type==="delete"?"delete":r.type==="set"?"update":"add",rules:n}}),C.shareReplay({bufferSize:1,refCount:!0}))}_createRangeProtectionRulesStream(){const r=this._rangeProtectionRuleModel.ruleChange$.pipe(C.filter(n=>n.unitId===this._unitId&&n.subUnitId===this._subUnitId)).subscribe(()=>{this._rangeRulesSubject.next(this._buildRangeProtectionRules())});return this._subscriptions.push(r),this._rangeRulesSubject.asObservable().pipe(C.distinctUntilChanged((n,e)=>n.length!==e.length?!1:n.every((t,i)=>t.id===e[i].id)),C.shareReplay({bufferSize:1,refCount:!0}))}_extractWorksheetPointType(r){for(const[n,e]of Object.entries(F))if(new e(this._unitId,this._subUnitId).id===r)return n;return null}_getRuleEditPermission(r){var i;const n=N[I.Edit];if(!n)return!1;const e=new n(this._unitId,this._subUnitId,r.permissionId),t=this._permissionService.getPermissionPoint(e.id);return(i=t==null?void 0:t.value)!=null?i:!1}_buildSnapshot(){const r={};for(const n in S){const e=S[n];r[e]=this.getPoint(e)}return r}_buildRangeProtectionRules(){return this._rangeProtectionRuleModel.getSubunitRuleList(this._unitId,this._subUnitId).map(n=>{const e=n.ranges.map(t=>this._worksheet.getRange(t.startRow,t.startColumn,t.endRow-t.startRow+1,t.endColumn-t.startColumn+1));return this._injector.createInstance(E,this._unitId,this._subUnitId,n.id,n.permissionId,e,{name:n.description||"",allowEdit:this._getRuleEditPermission(n)})})}_buildProtectionRule(r){const n=r.ranges.map(t=>this._worksheet.getRange(t)),e={name:r.description||"",allowViewByOthers:r.viewState!==s.ViewStateEnum.NoOneElseCanView};return r.editState===s.EditStateEnum.DesignedUserCanEdit?e.allowEdit=!0:e.allowEdit=!1,this._injector.createInstance(E,this._unitId,this._subUnitId,r.id,r.permissionId,n,e)}debugCellPermission(r,n){const e=this._fPermission.getPermissionInfoWithCell(this._unitId,this._subUnitId,r,n);if(!e)return;const{ruleId:t}=e,i=this._rangeProtectionRuleModel.getRule(this._unitId,this._subUnitId,t);if(i)return this._buildProtectionRule(i)}async protect(r){if(this.isProtected())throw new Error("Worksheet is already protected. Call unprotect() first.");const n=await this._fPermission.addWorksheetBasePermission(this._unitId,this._subUnitId,r);if(!n)throw new Error("Failed to create worksheet protection");return n}async unprotect(){if(!this.isProtected())return;this._fPermission.removeWorksheetPermission(this._unitId,this._subUnitId);const r=this._buildSnapshot();this._permissionSubject.next(r)}isProtected(){return!!this._worksheetProtectionRuleModel.getRule(this._unitId,this._subUnitId)}async setMode(r){const n=this._getModePermissions(r);await this._batchSetPermissionPoints(n)}_getModePermissions(r){const n={};switch(Object.values(S).forEach(e=>{n[e]=!1}),r){case"editable":Object.values(S).forEach(e=>{n[e]=!0});break;case"readOnly":n[S.View]=!0;break;case"filterOnly":n[S.View]=!0,n[S.Sort]=!0,n[S.Filter]=!0;break}return n}async _batchSetPermissionPoints(r){const n=[];for(const[e,t]of Object.entries(r)){const i=e,o=F[i];if(!o)throw new Error(`Unknown worksheet permission point: ${i}`);const a=this.getPoint(i);a!==t&&(await this._fPermission.setWorksheetPermissionPoint(this._unitId,this._subUnitId,o,t),n.push({point:i,value:t,oldValue:a}))}if(n.length>0){const e=this._buildSnapshot();this._permissionSubject.next(e)}}async setReadOnly(){await this.setMode("readOnly")}async setEditable(){await this.setMode("editable")}canEdit(){return this.getPoint(S.Edit)}canEditCell(r,n){if(!this.canEdit())return!1;const e=this._rangeProtectionRuleModel.getSubunitRuleList(this._unitId,this._subUnitId);for(const t of e)for(const i of t.ranges)if(r>=i.startRow&&r<=i.endRow&&n>=i.startColumn&&n<=i.endColumn)return this._getRuleEditPermission(t);return!0}canViewCell(r,n){return this.getPoint(S.View)}async setPoint(r,n){const e=F[r];if(!e)throw new Error(`Unknown worksheet permission point: ${r}`);if(this.getPoint(r)===n)return;await this._fPermission.setWorksheetPermissionPoint(this._unitId,this._subUnitId,e,n);const i=this._buildSnapshot();this._permissionSubject.next(i)}getPoint(r){var i;const n=F[r];if(!n)throw new Error(`Unknown worksheet permission point: ${r}`);const e=new n(this._unitId,this._subUnitId),t=this._permissionService.getPermissionPoint(e.id);return(i=t==null?void 0:t.value)!=null?i:!0}getSnapshot(){return this._buildSnapshot()}async applyConfig(r){if(r.mode&&await this.setMode(r.mode),r.points)for(const[n,e]of Object.entries(r.points))typeof e=="boolean"&&await this.setPoint(n,e);if(r.rangeProtections&&r.rangeProtections.length>0){const n=r.rangeProtections.map(e=>({ranges:e.rangeRefs.map(t=>this._worksheet.getRange(t)),options:e.options}));await this.protectRanges(n)}}async protectRanges(r){if(!r||r.length===0)throw new Error("Configs cannot be empty");const n=await Promise.all(r.map(o=>{var a,d,u,l;return this._authzIoService.create({objectType:s.UnitObject.SelectRange,selectRangeObject:{collaborators:(u=(d=(a=o.options)==null?void 0:a.allowedUsers)==null?void 0:d.map(m=>({id:m,role:H.Editor,subject:void 0})))!=null?u:[],unitID:this._unitId,name:((l=o.options)==null?void 0:l.name)||"",scope:void 0}})})),e=r.map((o,a)=>{var l;const d=this._determineViewState(o.options),u=this._determineEditState(o.options);return{permissionId:n[a],unitType:s.UnitObject.SelectRange,unitId:this._unitId,subUnitId:this._subUnitId,ranges:o.ranges.map(m=>m.getRange()),id:this._rangeProtectionRuleModel.createRuleId(this._unitId,this._subUnitId),description:((l=o.options)==null?void 0:l.name)||"",viewState:d,editState:u}});if(!await this._commandService.executeCommand(s.AddRangeProtectionMutation.id,{unitId:this._unitId,subUnitId:this._subUnitId,rules:e}))throw new Error("Failed to create range protection rules");return await Promise.all(r.map((o,a)=>this._setPermissionPoints(n[a],o.options))),e.map((o,a)=>this._injector.createInstance(E,this._unitId,this._subUnitId,o.id,o.permissionId,r[a].ranges,r[a].options||{}))}_determineViewState(r){return(r==null?void 0:r.allowViewByOthers)===!1?s.ViewStateEnum.NoOneElseCanView:s.ViewStateEnum.OthersCanView}_determineEditState(r){var n;return(r==null?void 0:r.allowEdit)===!0&&((n=r==null?void 0:r.allowedUsers)!=null&&n.length)?s.EditStateEnum.DesignedUserCanEdit:s.EditStateEnum.OnlyMe}async _setPermissionPoints(r,n){if(!n)return;const e=(t,i)=>t===void 0?i:typeof t=="boolean"?t:!0;await this._setPermissionPoint(r,I.Edit,e(n.allowEdit,!1)),await this._setPermissionPoint(r,I.View,e(n.allowViewByOthers,!0))}async _setPermissionPoint(r,n,e){const t=N[n];t&&this._fPermission.setRangeProtectionPermissionPoint(this._unitId,this._subUnitId,r,t,e)}async unprotectRules(r){!r||r.length===0||this._fPermission.removeRangeProtection(this._unitId,this._subUnitId,r)}async listRangeProtectionRules(){return this._buildRangeProtectionRules()}subscribe(r){const n=this.permission$.subscribe(r);return()=>n.unsubscribe()}dispose(){this._subscriptions.forEach(r=>r.unsubscribe()),this._permissionSubject.complete(),this._rangeRulesSubject.complete()}};z=ce([W(1,h.Inject(h.Injector)),W(2,h.IPermissionService),W(3,h.IAuthzIoService),W(4,h.ICommandService),W(5,h.Inject(s.RangeProtectionRuleModel)),W(6,h.Inject(s.WorksheetProtectionPointModel)),W(7,h.Inject(s.WorksheetProtectionRuleModel))],z);function me(r){switch(r){case"left":return h.HorizontalAlign.LEFT;case"center":return h.HorizontalAlign.CENTER;case"normal":return h.HorizontalAlign.RIGHT;default:throw new Error(`Invalid horizontal alignment: ${r}`)}}function Z(r){switch(r){case h.HorizontalAlign.LEFT:return"left";case h.HorizontalAlign.CENTER:return"center";case h.HorizontalAlign.RIGHT:return"normal";default:return"general"}}function ge(r){switch(r){case"top":return h.VerticalAlign.TOP;case"middle":return h.VerticalAlign.MIDDLE;case"bottom":return h.VerticalAlign.BOTTOM;default:throw new Error(`Invalid vertical alignment: ${r}`)}}function Q(r){switch(r){case h.VerticalAlign.TOP:return"top";case h.VerticalAlign.MIDDLE:return"middle";case h.VerticalAlign.BOTTOM:return"bottom";default:return"general"}}function L(r,n){return{startRow:r.startRow,endRow:r.endRow,startColumn:0,endColumn:n.getColumnCount()-1,rangeType:h.RANGE_TYPE.ROW}}function G(r,n){return{startRow:0,endRow:n.getRowCount()-1,startColumn:r.startColumn,endColumn:r.endColumn,rangeType:h.RANGE_TYPE.COLUMN}}var _e=Object.getOwnPropertyDescriptor,Se=(r,n,e,t)=>{for(var i=t>1?void 0:t?_e(n,e):n,o=r.length-1,a;o>=0;o--)(a=r[o])&&(i=a(i)||i);return i},B=(r,n)=>(e,t)=>n(e,t,r);c.FWorksheet=class extends b.FBaseInitialable{constructor(e,t,i,o,a,d,u){super(o);w(this,"setActiveSelection",this.setActiveRange);this._fWorkbook=e,this._workbook=t,this._worksheet=i,this._injector=o,this._selectionManagerService=a,this._logService=d,this._commandService=u}dispose(){super.dispose(),delete this._fWorkbook,delete this._workbook,delete this._worksheet}getSheet(){return this._worksheet}getInject(){return this._injector}getWorkbook(){return this._workbook}getSheetId(){return this._worksheet.getSheetId()}getSheetName(){return this._worksheet.getName()}getSelection(){const e=this._selectionManagerService.getCurrentSelections();return e?this._injector.createInstance(c.FSelection,this._workbook,this._worksheet,e):null}getDefaultStyle(){return this._worksheet.getDefaultCellStyle()}getRowDefaultStyle(e,t=!1){return t?this._worksheet.getRowStyle(e,t):this._worksheet.getRowStyle(e)}getColumnDefaultStyle(e,t=!1){return t?this._worksheet.getColumnStyle(e,t):this._worksheet.getColumnStyle(e)}setDefaultStyle(e){const t=this._workbook.getUnitId(),i=this._worksheet.getSheetId();return this._commandService.syncExecuteCommand(s.SetWorksheetDefaultStyleMutation.id,{unitId:t,subUnitId:i,defaultStyle:e}),this._worksheet.setDefaultCellStyle(e),this}setColumnDefaultStyle(e,t){const i=this._workbook.getUnitId(),o=this._worksheet.getSheetId(),a={unitId:i,subUnitId:o,columnData:{[e]:{s:t}}};return this._commandService.syncExecuteCommand(s.SetColDataCommand.id,a),this}setRowDefaultStyle(e,t){const i=this._workbook.getUnitId(),o=this._worksheet.getSheetId(),a={unitId:i,subUnitId:o,rowData:{[e]:{s:t}}};return this._commandService.syncExecuteCommand(s.SetRowDataCommand.id,a),this}getRange(e,t,i,o){let a,d;if(typeof e=="object")a=e,d=this._worksheet;else if(typeof e=="string"){const{range:u,sheetName:l}=P.deserializeRangeWithSheet(e),m=l?this._workbook.getSheetBySheetName(l):this._worksheet;if(!m)throw new Error("Range not found");d=m,a={...u,unitId:this._workbook.getUnitId(),sheetId:d.getSheetId(),rangeType:h.RANGE_TYPE.NORMAL,startRow:u.rangeType===h.RANGE_TYPE.COLUMN?0:u.startRow,endRow:u.rangeType===h.RANGE_TYPE.COLUMN?d.getMaxRows()-1:u.endRow,startColumn:u.rangeType===h.RANGE_TYPE.ROW?0:u.startColumn,endColumn:u.rangeType===h.RANGE_TYPE.ROW?d.getMaxColumns()-1:u.endColumn}}else if(typeof e=="number"&&t!==void 0)d=this._worksheet,a={startRow:e,endRow:e+(i!=null?i:1)-1,startColumn:t,endColumn:t+(o!=null?o:1)-1,unitId:this._workbook.getUnitId(),sheetId:this._worksheet.getSheetId()};else throw new Error("Invalid range specification");return this._injector.createInstance(c.FRange,this._workbook,d,a)}getMaxColumns(){return this._worksheet.getMaxColumns()}getMaxRows(){return this._worksheet.getMaxRows()}insertRowAfter(e){return this.insertRowsAfter(e,1)}insertRowBefore(e){return this.insertRowsBefore(e,1)}insertRows(e,t=1){return this.insertRowsBefore(e,t)}insertRowsAfter(e,t){const i=this._workbook.getUnitId(),o=this._worksheet.getSheetId(),a=h.Direction.DOWN,d=e+1,u=e+t,l=0,m=this._worksheet.getColumnCount()-1,_=s.copyRangeStyles(this._worksheet,d,u,l,m,!0,e);return this._commandService.syncExecuteCommand(s.InsertRowByRangeCommand.id,{unitId:i,subUnitId:o,direction:a,range:{startRow:d,endRow:u,startColumn:l,endColumn:m},cellValue:_}),this}insertRowsBefore(e,t){const i=this._workbook.getUnitId(),o=this._worksheet.getSheetId(),a=h.Direction.UP,d=e,u=e+t-1,l=0,m=this._worksheet.getColumnCount()-1,_=s.copyRangeStyles(this._worksheet,d,u,l,m,!0,e-1);return this._commandService.syncExecuteCommand(s.InsertRowByRangeCommand.id,{unitId:i,subUnitId:o,direction:a,range:{startRow:d,endRow:u,startColumn:l,endColumn:m},cellValue:_}),this}deleteRow(e){return this.deleteRows(e,1)}deleteRows(e,t){const i={startRow:e,endRow:e+t-1,startColumn:0,endColumn:this._worksheet.getColumnCount()-1};return this._commandService.syncExecuteCommand(s.RemoveRowByRangeCommand.id,{range:i,unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId()}),this}moveRows(e,t){const i=this._workbook.getUnitId(),o=this._worksheet.getSheetId(),a=L(e.getRange(),this._worksheet),d=a,u={startRow:t,endRow:t,startColumn:a.startColumn,endColumn:a.endColumn};return this._commandService.syncExecuteCommand(s.MoveRowsCommand.id,{unitId:i,subUnitId:o,range:a,fromRange:d,toRange:u}),this}hideRow(e){const t=this._workbook.getUnitId(),i=this._worksheet.getSheetId(),o=L(e.getRange(),this._worksheet);return this._commandService.syncExecuteCommand(s.SetRowHiddenCommand.id,{unitId:t,subUnitId:i,ranges:[o]}),this}hideRows(e,t=1){const i=this._workbook.getUnitId(),o=this._worksheet.getSheetId(),a={startRow:e,endRow:e+t-1,startColumn:0,endColumn:this._worksheet.getColumnCount()-1,rangeType:h.RANGE_TYPE.ROW};return this._commandService.syncExecuteCommand(s.SetRowHiddenCommand.id,{unitId:i,subUnitId:o,ranges:[a]}),this}unhideRow(e){const t=this._workbook.getUnitId(),i=this._worksheet.getSheetId(),o=L(e.getRange(),this._worksheet);return this._commandService.syncExecuteCommand(s.SetSpecificRowsVisibleCommand.id,{unitId:t,subUnitId:i,ranges:[o]}),this}showRows(e,t=1){const i=this._workbook.getUnitId(),o=this._worksheet.getSheetId(),a={startRow:e,endRow:e+t-1,startColumn:0,endColumn:this._worksheet.getColumnCount()-1,rangeType:h.RANGE_TYPE.ROW};return this._commandService.syncExecuteCommand(s.SetSpecificRowsVisibleCommand.id,{unitId:i,subUnitId:o,ranges:[a]}),this}setRowHeight(e,t){return this.setRowHeights(e,1,t)}autoFitRow(e,t=h.BooleanNumber.TRUE){const i=this._workbook.getUnitId(),o=this._worksheet.getSheetId(),a=[{startRow:e,endRow:e,startColumn:0,endColumn:this._worksheet.getColumnCount()-1}];return this._commandService.syncExecuteCommand(s.SetTextWrapCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:a[0],value:h.WrapStrategy.WRAP}),this._commandService.syncExecuteCommand(s.SetWorksheetRowIsAutoHeightMutation.id,{unitId:i,subUnitId:o,ranges:a,autoHeightInfo:t}),this}setRowHeights(e,t,i){var m;const o=this._workbook.getUnitId(),a=this._worksheet.getSheetId(),d=this._worksheet.getRowManager(),u=[],l=[];for(let _=e;_<e+t;_++){const k=((m=d.getRow(_))==null?void 0:m.ah)||this._worksheet.getConfig().defaultRowHeight,v={startRow:_,endRow:_,startColumn:0,endColumn:this._worksheet.getColumnCount()-1};i<=k?u.push(v):l.push(v)}return l.length>0&&this._commandService.syncExecuteCommand(s.SetRowHeightCommand.id,{unitId:o,subUnitId:a,ranges:l,value:i}),u.length>0&&this._commandService.syncExecuteCommand(s.SetWorksheetRowIsAutoHeightCommand.id,{unitId:o,subUnitId:a,ranges:u}),this}getRowHeight(e){return this._worksheet.getRowHeight(e)}setRowAutoHeight(e,t){const i=this._workbook.getUnitId(),o=this._worksheet.getSheetId(),a=[{startRow:e,endRow:e+t-1,startColumn:0,endColumn:this._worksheet.getColumnCount()-1}];return this._commandService.syncExecuteCommand(s.SetWorksheetRowIsAutoHeightCommand.id,{unitId:i,subUnitId:o,ranges:a}),this}setRangesAutoHeight(e){const t=this._workbook.getUnitId(),i=this._worksheet.getSheetId();return this._commandService.syncExecuteCommand(s.SetWorksheetRowIsAutoHeightCommand.id,{unitId:t,subUnitId:i,ranges:e}),this}setRowHeightsForced(e,t,i){const o=this._workbook.getUnitId(),a=this._worksheet.getSheetId(),d=[{startRow:e,endRow:e+t-1,startColumn:0,endColumn:this._worksheet.getColumnCount()-1}];return this._commandService.syncExecuteCommand(s.SetRowHeightCommand.id,{unitId:o,subUnitId:a,ranges:d,value:i}),this}setRowCustom(e){const t=this._workbook.getUnitId(),i=this._worksheet.getSheetId(),o={};for(const[d,u]of Object.entries(e))o[Number(d)]={custom:u};const a={unitId:t,subUnitId:i,rowData:o};return this._commandService.syncExecuteCommand(s.SetRowDataCommand.id,a),this}insertColumnAfter(e){return this.insertColumnsAfter(e,1)}insertColumnBefore(e){return this.insertColumnsBefore(e,1)}insertColumns(e,t=1){return this.insertColumnsBefore(e,t)}insertColumnsAfter(e,t){const i=this._workbook.getUnitId(),o=this._worksheet.getSheetId(),a=h.Direction.RIGHT,d=0,u=this._worksheet.getRowCount()-1,l=e+1,m=e+t,_=s.copyRangeStyles(this._worksheet,d,u,l,m,!1,e);return this._commandService.syncExecuteCommand(s.InsertColByRangeCommand.id,{unitId:i,subUnitId:o,direction:a,range:{startRow:d,endRow:u,startColumn:l,endColumn:m},cellValue:_}),this}insertColumnsBefore(e,t){const i=this._workbook.getUnitId(),o=this._worksheet.getSheetId(),a=h.Direction.LEFT,d=0,u=this._worksheet.getRowCount()-1,l=e,m=e+t-1,_=s.copyRangeStyles(this._worksheet,d,u,l,m,!1,e-1);return this._commandService.syncExecuteCommand(s.InsertColByRangeCommand.id,{unitId:i,subUnitId:o,direction:a,range:{startRow:d,endRow:u,startColumn:l,endColumn:m},cellValue:_}),this}deleteColumn(e){return this.deleteColumns(e,1)}deleteColumns(e,t){const i={startRow:0,endRow:this._worksheet.getRowCount()-1,startColumn:e,endColumn:e+t-1};return this._commandService.syncExecuteCommand(s.RemoveColByRangeCommand.id,{range:i,unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId()}),this}moveColumns(e,t){const i=this._workbook.getUnitId(),o=this._worksheet.getSheetId(),a=G(e.getRange(),this._worksheet),d=a,u={startRow:0,endRow:this._worksheet.getRowCount()-1,startColumn:t,endColumn:t};return this._commandService.syncExecuteCommand(s.MoveColsCommand.id,{unitId:i,subUnitId:o,range:a,fromRange:d,toRange:u}),this}hideColumn(e){const t=this._workbook.getUnitId(),i=this._worksheet.getSheetId(),o=G(e.getRange(),this._worksheet);return this._commandService.syncExecuteCommand(s.SetColHiddenCommand.id,{unitId:t,subUnitId:i,ranges:[o]}),this}hideColumns(e,t=1){const i=this._workbook.getUnitId(),o=this._worksheet.getSheetId(),a={startRow:0,endRow:this._worksheet.getRowCount()-1,startColumn:e,endColumn:e+t-1,rangeType:h.RANGE_TYPE.COLUMN};return this._commandService.syncExecuteCommand(s.SetColHiddenCommand.id,{unitId:i,subUnitId:o,ranges:[a]}),this}unhideColumn(e){const t=this._workbook.getUnitId(),i=this._worksheet.getSheetId(),o=G(e.getRange(),this._worksheet);return this._commandService.syncExecuteCommand(s.SetSpecificColsVisibleCommand.id,{unitId:t,subUnitId:i,ranges:[o]}),this}showColumns(e,t=1){const i=this._workbook.getUnitId(),o=this._worksheet.getSheetId(),a={startRow:0,endRow:this._worksheet.getRowCount()-1,startColumn:e,endColumn:e+t-1,rangeType:h.RANGE_TYPE.COLUMN};return this._commandService.syncExecuteCommand(s.SetSpecificColsVisibleCommand.id,{unitId:i,subUnitId:o,ranges:[a]}),this}setColumnWidth(e,t){return this.setColumnWidths(e,1,t)}setColumnWidths(e,t,i){const o=this._workbook.getUnitId(),a=this._worksheet.getSheetId(),d=[{startColumn:e,endColumn:e+t-1,startRow:0,endRow:this._worksheet.getRowCount()-1}];return this._commandService.syncExecuteCommand(s.SetColWidthCommand.id,{unitId:o,subUnitId:a,ranges:d,value:i}),this}getColumnWidth(e){return this._worksheet.getColumnWidth(e)}setColumnCustom(e){const t=this._workbook.getUnitId(),i=this._worksheet.getSheetId(),o={};for(const[d,u]of Object.entries(e))o[Number(d)]={custom:u};const a={unitId:t,subUnitId:i,columnData:o};return this._commandService.syncExecuteCommand(s.SetColDataCommand.id,a),this}getMergeData(){return this._worksheet.getMergeData().map(e=>this._injector.createInstance(c.FRange,this._workbook,this._worksheet,e))}getMergedRanges(){return this._worksheet.getSnapshot().mergeData.map(t=>this._injector.createInstance(c.FRange,this._workbook,this._worksheet,t))}getCellMergeData(e,t){const o=this._worksheet.getMergedCell(e,t);if(o)return this._injector.createInstance(c.FRange,this._workbook,this._worksheet,o)}getActiveRange(){return this._fWorkbook.getActiveRange()}setActiveRange(e){const{unitId:t,sheetId:i}=e.getRange();if(t!==this._workbook.getUnitId()||i!==this._worksheet.getSheetId())throw new Error("Specified range must be part of the sheet.");return this._fWorkbook.setActiveRange(e),this}getActiveCell(){return this._fWorkbook.getActiveCell()}setFreeze(e){return this._logService.warn("setFreeze is deprecated, use setFrozenRows and setFrozenColumns instead"),this._commandService.syncExecuteCommand(s.SetFrozenCommand.id,{...e,unitId:this._workbook.getUnitId(),subUnitId:this.getSheetId()}),this}cancelFreeze(){return this._commandService.syncExecuteCommand(s.CancelFrozenCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this.getSheetId()}),this}getFreeze(){return this._worksheet.getFreeze()}setFrozenColumns(...e){const t=this.getFreeze();if(arguments.length===1){const i=e[0];this.setFreeze({...t,startColumn:i>0?i:-1,xSplit:i})}else if(arguments.length===2){let[i=0,o=0]=e;i>o&&([i,o]=[o,i]),this._commandService.syncExecuteCommand(s.SetFrozenCommand.id,{startColumn:o+1,xSplit:o-i+1,startRow:t.startRow,ySplit:t.ySplit,unitId:this._workbook.getUnitId(),subUnitId:this.getSheetId()})}return this}setFrozenRows(...e){const t=this.getFreeze();if(arguments.length===1){const i=e[0];this.setFreeze({...t,startRow:i>0?i:-1,ySplit:i})}else if(arguments.length===2){let[i=0,o=0]=e;i>o&&([i,o]=[o,i]),this._commandService.syncExecuteCommand(s.SetFrozenCommand.id,{startRow:o+1,ySplit:o-i+1,startColumn:t.startColumn,xSplit:t.xSplit,unitId:this._workbook.getUnitId(),subUnitId:this.getSheetId()})}return this}getFrozenColumns(){const e=this.getFreeze();return e.startColumn===-1?0:e.startColumn}getFrozenRows(){const e=this.getFreeze();return e.startRow===-1?0:e.startRow}getFrozenRowRange(){const e=this._worksheet.getFreeze();return{startRow:e.startRow-e.ySplit,endRow:e.startRow-1}}getFrozenColumnRange(){const e=this._worksheet.getFreeze();return{startColumn:e.startColumn-e.xSplit,endColumn:e.startColumn-1}}hasHiddenGridLines(){return this._worksheet.getConfig().showGridlines===h.BooleanNumber.FALSE}setHiddenGridlines(e){return this._commandService.syncExecuteCommand(s.ToggleGridlinesCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),showGridlines:e?h.BooleanNumber.FALSE:h.BooleanNumber.TRUE}),this}setGridLinesColor(e){return this._commandService.syncExecuteCommand(s.SetGridlinesColorCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),color:e}),this}getGridLinesColor(){return this._worksheet.getGridlinesColor()}setTabColor(e){return this._commandService.syncExecuteCommand(s.SetTabColorCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),value:e}),this}getTabColor(){return this._worksheet.getTabColor()}onCellDataChange(e){return this._injector.get(h.ICommandService).onCommandExecuted(i=>{if(i.id===s.SetRangeValuesMutation.id){const o=i.params;o.unitId===this._workbook.getUnitId()&&o.subUnitId===this._worksheet.getSheetId()&&o.cellValue&&e(new h.ObjectMatrix(o.cellValue))}})}onBeforeCellDataChange(e){return this._injector.get(h.ICommandService).beforeCommandExecuted(i=>{if(i.id===s.SetRangeValuesMutation.id){const o=i.params;o.unitId===this._workbook.getUnitId()&&o.subUnitId===this._worksheet.getSheetId()&&o.cellValue&&e(new h.ObjectMatrix(o.cellValue))}})}hideSheet(){const e=this._injector.get(h.ICommandService);if(this._workbook.getSheets().filter(a=>a.isSheetHidden()!==h.BooleanNumber.TRUE).length<=1)throw new Error("Cannot hide the only visible sheet");return e.syncExecuteCommand(s.SetWorksheetHideCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId()}),this}showSheet(){return this._injector.get(h.ICommandService).syncExecuteCommand(s.SetWorksheetShowCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId()}),this}isSheetHidden(){return this._worksheet.isSheetHidden()===h.BooleanNumber.TRUE}setName(e){return this._commandService.syncExecuteCommand(s.SetWorksheetNameCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),name:e}),this}activate(){return this._fWorkbook.setActiveSheet(this),this}getIndex(){return this._workbook.getSheetIndex(this._worksheet)}clear(e){if(e&&e.contentsOnly&&!e.formatOnly)return this.clearContents();if(e&&e.formatOnly&&!e.contentsOnly)return this.clearFormats();const t=this._workbook.getUnitId(),i=this._worksheet.getSheetId(),o=this._injector.get(h.ICommandService),a={startRow:0,endRow:this._worksheet.getRowCount()-1,startColumn:0,endColumn:this._worksheet.getColumnCount()-1};return o.syncExecuteCommand(s.ClearSelectionAllCommand.id,{unitId:t,subUnitId:i,ranges:[a],options:e}),this}clearContents(){const e=this._workbook.getUnitId(),t=this._worksheet.getSheetId(),i=this._injector.get(h.ICommandService),o={startRow:0,endRow:this._worksheet.getRowCount()-1,startColumn:0,endColumn:this._worksheet.getColumnCount()-1};return i.syncExecuteCommand(s.ClearSelectionContentCommand.id,{unitId:e,subUnitId:t,ranges:[o]}),this}clearFormats(){const e=this._workbook.getUnitId(),t=this._worksheet.getSheetId(),i=this._injector.get(h.ICommandService),o={startRow:0,endRow:this._worksheet.getRowCount()-1,startColumn:0,endColumn:this._worksheet.getColumnCount()-1};return i.syncExecuteCommand(s.ClearSelectionFormatCommand.id,{unitId:e,subUnitId:t,ranges:[o]}),this}getDataRange(){const{startRow:e,endRow:t,startColumn:i,endColumn:o}=this._worksheet.getDataRealRange();return this.getRange(e,i,t-e+1,o-i+1)}getLastColumns(){return this._worksheet.getLastColumnWithContent()}getLastColumn(){return this._worksheet.getLastColumnWithContent()}getLastRows(){return this._worksheet.getLastRowWithContent()}getLastRow(){return this._worksheet.getLastRowWithContent()}equalTo(e){return e instanceof c.FWorksheet?this._worksheet.getSheetId()===e.getSheetId()&&this._workbook.getUnitId()===e.getWorkbook().getUnitId():!1}insertDefinedName(e,t){const o=this._injector.createInstance(V).setName(e).setRef(t).build();o.localSheetId=this.getSheetId(),this._fWorkbook.insertDefinedNameBuilder(o)}getDefinedNames(){return this._fWorkbook.getDefinedNames().filter(t=>t.getLocalSheetId()===this.getSheetId())}setCustomMetadata(e){return this._worksheet.setCustomMetadata(e),this}getCustomMetadata(){return this._worksheet.getCustomMetadata()}setRowCustomMetadata(e,t){return this._worksheet.getRowManager().setCustomMetadata(e,t),this}setColumnCustomMetadata(e,t){return this._worksheet.getColumnManager().setCustomMetadata(e,t),this}getRowCustomMetadata(e){return this._worksheet.getRowManager().getCustomMetadata(e)}getColumnCustomMetadata(e){return this._worksheet.getColumnManager().getCustomMetadata(e)}appendRow(e){const t=this._worksheet.getCellMatrix().hasValue(),i=this._worksheet.getLastRowWithContent(),o=this._worksheet.getRowCount(),a=this._worksheet.getColumnCount(),d=t?i+1:i,u=new h.ObjectMatrix;for(let l=0;l<e.length;l++)u.setValue(d,l,h.covertCellValue(e[l]));return this._commandService.syncExecuteCommand(s.AppendRowCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),cellValue:u.getMatrix(),insertRowNums:d>o-1?1:0,insertColumnNums:e.length>a?e.length-a:0,maxRows:o,maxColumns:a}),this}setRowCount(e){return this._commandService.syncExecuteCommand(s.SetWorksheetRowCountCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),rowCount:e}),this}setColumnCount(e){return this._commandService.syncExecuteCommand(s.SetWorksheetColumnCountCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),columnCount:e}),this}getWorksheetPermission(){return this._injector.createInstance(z,this)}},c.FWorksheet=Se([B(3,h.Inject(h.Injector)),B(4,h.Inject(s.SheetsSelectionsService)),B(5,h.Inject(h.ILogService)),B(6,h.ICommandService)],c.FWorksheet);var we=Object.getOwnPropertyDescriptor,Ce=(r,n,e,t)=>{for(var i=t>1?void 0:t?we(n,e):n,o=r.length-1,a;o>=0;o--)(a=r[o])&&(i=a(i)||i);return i},O=(r,n)=>(e,t)=>n(e,t,r);let K=class{constructor(r,n,e,t,i,o,a,d,u){w(this,"_permissionSubject");w(this,"_subscriptions",[]);w(this,"_fPermission");w(this,"permission$");w(this,"protectionChange$");this._unitId=r,this._subUnitId=n,this._range=e,this._worksheet=t,this._injector=i,this._permissionService=o,this._authzIoService=a,this._commandService=d,this._rangeProtectionRuleModel=u,this._fPermission=this._injector.createInstance(c.FPermission),this._permissionSubject=new j.BehaviorSubject(this._buildSnapshot()),this.permission$=this._createPermissionStream(),this.protectionChange$=this._createProtectionChangeStream()}_createPermissionStream(){const r=this._permissionService.permissionPointUpdate$.pipe(C.filter(n=>{const e=n.id;return e.includes(this._unitId)&&e.includes(this._subUnitId)})).subscribe(()=>{this._permissionSubject.next(this._buildSnapshot())});return this._subscriptions.push(r),this._permissionSubject.asObservable().pipe(C.distinctUntilChanged((n,e)=>JSON.stringify(n)===JSON.stringify(e)),C.shareReplay({bufferSize:1,refCount:!0}))}_createProtectionChangeStream(){return this._rangeProtectionRuleModel.ruleChange$.pipe(C.filter(r=>r.unitId!==this._unitId||r.subUnitId!==this._subUnitId?!1:r.type==="delete"?this._rangeMatches(r.rule):r.type==="add"?this._rangeMatches(r.rule):!1),C.map(r=>(this._permissionSubject.next(this._buildSnapshot()),r.type==="delete"?{type:"unprotected",ruleId:r.rule.id}:{type:"protected",rule:this._createFacadeRule(r.rule)})),C.shareReplay({bufferSize:1,refCount:!0}))}_rangeMatches(r){const n=this._range.getRange();return r.ranges.some(e=>n.startRow===e.startRow&&n.startColumn===e.startColumn&&n.endRow===e.endRow&&n.endColumn===e.endColumn)}_createFacadeRule(r){const n=r.ranges.map(t=>this._worksheet.getRange(t.startRow,t.startColumn,t.endRow-t.startRow+1,t.endColumn-t.startColumn+1)),e={name:r.description||"",allowViewByOthers:r.viewState!==s.ViewStateEnum.NoOneElseCanView,allowEdit:r.editState===s.EditStateEnum.DesignedUserCanEdit};return this._injector.createInstance(E,this._unitId,this._subUnitId,r.id,r.permissionId,n,e)}getPoint(r){const n=N[r];if(!n)return console.warn(`Unknown permission point: ${r}`),!1;const e=this._getProtectionRule();if(e){const t=new n(this._unitId,this._subUnitId,e.permissionId),i=this._permissionService.getPermissionPoint(t.id);if(i)return i.value}return!0}getSnapshot(){return this._buildSnapshot()}isProtected(){return this._getProtectionRule()!==null}canEdit(){return this.getPoint(I.Edit)}canView(){return this.getPoint(I.View)}canManageCollaborator(){return this.getPoint(I.ManageCollaborator)}canDelete(){return this.getPoint(I.Delete)}async setPoint(r,n){const e=N[r];if(!e)throw new Error(`Unknown permission point: ${r}`);const t=this._getProtectionRule();if(!t)throw new Error("Cannot set permission point: No protection rule exists for this range. Call protect() first.");if(this.getPoint(r)===n)return;const o=t.permissionId;this._fPermission.setRangeProtectionPermissionPoint(this._unitId,this._subUnitId,o,e,n),this._permissionSubject.next(this._buildSnapshot())}async protect(r){if(this.isProtected())throw new Error("Range is already protected");const n=await this._fPermission.addRangeBaseProtection(this._unitId,this._subUnitId,[this._range],r);if(!n)throw new Error("Failed to create range protection");const{permissionId:e,ruleId:t}=n;return await this._setPermissionPoints(e,r),this._injector.createInstance(E,this._unitId,this._subUnitId,t,e,[this._range],r||{})}_determineViewState(r){return(r==null?void 0:r.allowViewByOthers)===!1?s.ViewStateEnum.NoOneElseCanView:s.ViewStateEnum.OthersCanView}_determineEditState(r){var n;return(r==null?void 0:r.allowEdit)===!0&&((n=r==null?void 0:r.allowedUsers)!=null&&n.length)?s.EditStateEnum.DesignedUserCanEdit:s.EditStateEnum.OnlyMe}async _setPermissionPoints(r,n){if(!n)return;const e=(t,i)=>t===void 0?i:typeof t=="boolean"?t:!0;await this._setPermissionPoint(r,I.Edit,e(n.allowEdit,!1)),await this._setPermissionPoint(r,I.View,e(n.allowViewByOthers,!0))}async _setPermissionPoint(r,n,e){const t=N[n];t&&this._fPermission.setRangeProtectionPermissionPoint(this._unitId,this._subUnitId,r,t,e)}async unprotect(){const r=this._getProtectionRule();if(!r)return;const n=r.id;this._fPermission.removeRangeProtection(this._unitId,this._subUnitId,[n])}async listRules(){return await this._buildProtectionRulesAsync()}subscribe(r){const n=this.permission$.subscribe(r);return()=>n.unsubscribe()}_getProtectionRule(){const r=this._rangeProtectionRuleModel.getSubunitRuleList(this._unitId,this._subUnitId),n=this._range.getRange();for(const e of r)for(const t of e.ranges)if(n.startRow===t.startRow&&n.startColumn===t.startColumn&&n.endRow===t.endRow&&n.endColumn===t.endColumn)return e;return null}_buildProtectionRules(){return this._rangeProtectionRuleModel.getSubunitRuleList(this._unitId,this._subUnitId).map(n=>{const e=n.ranges.map(i=>this._worksheet.getRange(i.startRow,i.startColumn,i.endRow-i.startRow+1,i.endColumn-i.startColumn+1)),t={name:n.description||"",allowViewByOthers:n.viewState!==s.ViewStateEnum.NoOneElseCanView};return n.editState===s.EditStateEnum.DesignedUserCanEdit?t.allowEdit=!0:t.allowEdit=!1,this._injector.createInstance(E,this._unitId,this._subUnitId,n.id,n.permissionId,e,t)})}async _buildProtectionRulesAsync(){const r=this._rangeProtectionRuleModel.getSubunitRuleList(this._unitId,this._subUnitId);return(await Promise.all(r.map(async e=>{const t=e.ranges.map(o=>this._worksheet.getRange(o.startRow,o.startColumn,o.endRow-o.startRow+1,o.endColumn-o.startColumn+1)),i={name:e.description||"",allowViewByOthers:e.viewState!==s.ViewStateEnum.NoOneElseCanView};if(e.editState===s.EditStateEnum.DesignedUserCanEdit)try{const a=(await this._authzIoService.listCollaborators({objectID:e.permissionId,unitID:this._unitId})).filter(d=>d.role===H.Editor).map(d=>{var u;return((u=d.subject)==null?void 0:u.userID)||d.id});i.allowEdit=a.length>0}catch(o){console.warn(`Failed to fetch collaborators for rule ${e.id}:`,o),i.allowEdit=!1}else i.allowEdit=!1;return{rule:e,ranges:t,options:i}}))).map(({rule:e,ranges:t,options:i})=>this._injector.createInstance(E,this._unitId,this._subUnitId,e.id,e.permissionId,t,i))}_buildSnapshot(){const r={};return Object.values(I).forEach(n=>{r[n]=this.getPoint(n)}),r}dispose(){this._subscriptions.forEach(r=>r.unsubscribe()),this._permissionSubject.complete()}};K=Ce([O(4,h.Inject(h.Injector)),O(5,h.Inject(h.IPermissionService)),O(6,h.Inject(h.IAuthzIoService)),O(7,h.Inject(h.ICommandService)),O(8,h.Inject(s.RangeProtectionRuleModel))],K);var ke=Object.getOwnPropertyDescriptor,Ie=(r,n,e,t)=>{for(var i=t>1?void 0:t?ke(n,e):n,o=r.length-1,a;o>=0;o--)(a=r[o])&&(i=a(i)||i);return i},Y=(r,n)=>(e,t)=>n(e,t,r);c.FRange=(D=class extends b.FBaseInitialable{constructor(n,e,t,i,o,a){super(i),this._workbook=n,this._worksheet=e,this._range=t,this._injector=i,this._commandService=o,this._formulaDataModel=a,this._runInitializers(this._injector,this._workbook,this._worksheet,this._range,this._commandService,this._formulaDataModel)}getUnitId(){return this._workbook.getUnitId()}getSheetName(){return this._worksheet.getName()}getSheetId(){return this._worksheet.getSheetId()}getRange(){return this._range}getRow(){return this._range.startRow}getLastRow(){return this._range.endRow}getColumn(){return this._range.startColumn}getLastColumn(){return this._range.endColumn}getWidth(){return this._range.endColumn-this._range.startColumn+1}getHeight(){return this._range.endRow-this._range.startRow+1}isMerged(){const{startColumn:n,startRow:e,endColumn:t,endRow:i}=this._range;return this._worksheet.getMergedCellRange(e,n,i,t).some(a=>h.Rectangle.equals(a,this._range))}getCellStyleData(n="row"){return n!=="cell"?this._worksheet.getComposedCellStyle(this._range.startRow,this._range.startColumn,n==="row"):this._worksheet.getCellStyle(this._range.startRow,this._range.startColumn)}getFontFamily(n="row"){var e,t;return(t=(e=this.getCellStyleData(n))==null?void 0:e.ff)!=null?t:null}getFontSize(n="row"){var e,t;return(t=(e=this.getCellStyleData(n))==null?void 0:e.fs)!=null?t:null}getCellStyle(n="row"){const e=this.getCellStyleData(n);return e?h.TextStyleValue.create(e):null}getCellStyles(n="row"){return this.getCellDatas().map((t,i)=>t.map((o,a)=>{if(!o)return null;const d=n!=="cell"?this._worksheet.getComposedCellStyle(i+this._range.startRow,a+this._range.startColumn,n==="row"):this._worksheet.getCellStyle(i+this._range.startRow,a+this._range.startColumn);return d?h.TextStyleValue.create(d):null}))}getValue(n){var e,t;return n?this.getValueAndRichTextValue():(t=(e=this._worksheet.getCell(this._range.startRow,this._range.startColumn))==null?void 0:e.v)!=null?t:null}getRawValue(){var e,t;const n=this._worksheet.getCellMatrix().getValue(this._range.startRow,this._range.startColumn);return n!=null&&n.p&&((e=n.p.body)!=null&&e.dataStream)?n.p.body.dataStream:(t=n==null?void 0:n.v)!=null?t:null}getDisplayValue(){var e,t,i;const n=this._worksheet.getCell(this._range.startRow,this._range.startColumn);return n!=null&&n.p&&((e=n.p.body)!=null&&e.dataStream)?n.p.body.dataStream:(i=(t=n==null?void 0:n.v)==null?void 0:t.toString())!=null?i:""}getValues(n){var d,u;if(n)return this.getValueAndRichTextValues();const{startRow:e,endRow:t,startColumn:i,endColumn:o}=this._range,a=[];for(let l=e;l<=t;l++){const m=[];for(let _=i;_<=o;_++)m.push((u=(d=this._worksheet.getCell(l,_))==null?void 0:d.v)!=null?u:null);a.push(m)}return a}getRawValues(){var d,u;const n=this._worksheet.getCellMatrix(),{startRow:e,endRow:t,startColumn:i,endColumn:o}=this._range,a=[];for(let l=e;l<=t;l++){const m=[];for(let _=i;_<=o;_++){const k=n.getValue(l,_);k!=null&&k.p&&((d=k.p.body)!=null&&d.dataStream)?m.push(k.p.body.dataStream):m.push((u=k==null?void 0:k.v)!=null?u:null)}a.push(m)}return a}getDisplayValues(){var a,d,u;const{startRow:n,endRow:e,startColumn:t,endColumn:i}=this._range,o=[];for(let l=n;l<=e;l++){const m=[];for(let _=t;_<=i;_++){const k=this._worksheet.getCell(l,_);k!=null&&k.p&&((a=k.p.body)!=null&&a.dataStream)?m.push(k.p.body.dataStream):m.push((u=(d=k==null?void 0:k.v)==null?void 0:d.toString())!=null?u:"")}o.push(m)}return o}getCellData(){var n;return(n=this._worksheet.getCell(this._range.startRow,this._range.startColumn))!=null?n:null}getCellDatas(){return this.getCellDataGrid()}getCellDataGrid(){const{startRow:n,endRow:e,startColumn:t,endColumn:i}=this._range,o=[];for(let a=n;a<=e;a++){const d=[];for(let u=t;u<=i;u++)d.push(this._worksheet.getCellRaw(a,u));o.push(d)}return o}getRichTextValue(){const n=this.getCellData();return n!=null&&n.p?new h.RichTextValue(n.p):null}getRichTextValues(){return this.getCellDataGrid().map(e=>e.map(t=>t!=null&&t.p?new h.RichTextValue(t.p):null))}getValueAndRichTextValue(){const n=this.getCellData();return n!=null&&n.p?new h.RichTextValue(n.p):n==null?void 0:n.v}getValueAndRichTextValues(){return this.getCellDatas().map(e=>e.map(t=>t!=null&&t.p?new h.RichTextValue(t.p):t==null?void 0:t.v))}getFormula(){var n;return(n=this._formulaDataModel.getFormulaStringByCell(this._range.startRow,this._range.startColumn,this._worksheet.getSheetId(),this._workbook.getUnitId()))!=null?n:""}getFormulas(){const n=[],{startRow:e,endRow:t,startColumn:i,endColumn:o}=this._range,a=this._worksheet.getSheetId(),d=this._workbook.getUnitId();for(let u=e;u<=t;u++){const l=[];for(let m=i;m<=o;m++){const _=this._formulaDataModel.getFormulaStringByCell(u,m,a,d);l.push(_||"")}n.push(l)}return n}getWrap(){return this._worksheet.getRange(this._range).getWrap()===h.BooleanNumber.TRUE}getWraps(){const n=this.getCellDatas(),e=this._workbook.getStyles();return n.map(t=>t.map(i=>{var o;return((o=e.getStyleByCell(i))==null?void 0:o.tb)===h.WrapStrategy.WRAP}))}getWrapStrategy(){return this._worksheet.getRange(this._range).getWrapStrategy()}getHorizontalAlignment(){const n=this._worksheet.getRange(this._range).getHorizontalAlignment();return Z(n)}getHorizontalAlignments(){return this._worksheet.getRange(this._range).getHorizontalAlignments().map(e=>e.map(t=>Z(t)))}getVerticalAlignment(){return Q(this._worksheet.getRange(this._range).getVerticalAlignment())}getVerticalAlignments(){return this._worksheet.getRange(this._range).getVerticalAlignments().map(e=>e.map(t=>Q(t)))}setCustomMetaData(n){return this.setValue({custom:n})}setCustomMetaDatas(n){return this.setValues(n.map(e=>e.map(t=>({custom:t}))))}getCustomMetaData(){var e;const n=this.getCellData();return(e=n==null?void 0:n.custom)!=null?e:null}getCustomMetaDatas(){return this.getCellDataGrid().map(e=>e.map(t=>{var i;return(i=t==null?void 0:t.custom)!=null?i:null}))}setBorder(n,e,t){return this._commandService.syncExecuteCommand(s.SetBorderBasicCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),ranges:[this._range],value:{type:n,style:e,color:t}}),this}getBackground(){var e,t;const n=this.getCellStyle();return(t=(e=n==null?void 0:n.background)==null?void 0:e.rgb)!=null?t:h.DEFAULT_STYLES.bg.rgb}getBackgrounds(){return this.getCellStyles().map(e=>e.map(t=>{var i,o;return(o=(i=t==null?void 0:t.background)==null?void 0:i.rgb)!=null?o:h.DEFAULT_STYLES.bg.rgb}))}setBackgroundColor(n){return this._commandService.syncExecuteCommand(s.SetStyleCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,style:{type:"bg",value:{rgb:n}}}),this}setBackground(n){return this.setBackgroundColor(n),this}setTextRotation(n){return this._commandService.syncExecuteCommand(s.SetTextRotationCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,value:n}),this}setValue(n){const e=h.covertCellValue(n);if(!e)throw new Error("Invalid value");return this._commandService.syncExecuteCommand(s.SetRangeValuesCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,value:e}),this}setValueForCell(n){const e=h.covertCellValue(n);if(!e)throw new Error("Invalid value");return this._commandService.syncExecuteCommand(s.SetRangeValuesCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:{startColumn:this._range.startColumn,startRow:this._range.startRow,endColumn:this._range.startColumn,endRow:this._range.startRow},value:e}),this}setRichTextValueForCell(n){const e=n instanceof h.RichTextValue?n.getData():n,t={unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:{startColumn:this._range.startColumn,startRow:this._range.startRow,endColumn:this._range.startColumn,endRow:this._range.startRow},value:{p:e}};return this._commandService.syncExecuteCommand(s.SetRangeValuesCommand.id,t),this}setRichTextValues(n){const e=n.map(o=>o.map(a=>a&&{p:a instanceof h.RichTextValue?a.getData():a})),t=h.covertCellValues(e,this._range),i={unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,value:t};return this._commandService.syncExecuteCommand(s.SetRangeValuesCommand.id,i),this}setWrap(n){return this._commandService.syncExecuteCommand(s.SetTextWrapCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,value:n?h.WrapStrategy.WRAP:h.WrapStrategy.UNSPECIFIED}),this}setWrapStrategy(n){return this._commandService.syncExecuteCommand(s.SetTextWrapCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,value:n}),this}setVerticalAlignment(n){return this._commandService.syncExecuteCommand(s.SetVerticalTextAlignCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,value:ge(n)}),this}setHorizontalAlignment(n){return this._commandService.syncExecuteCommand(s.SetHorizontalTextAlignCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,value:me(n)}),this}setValues(n){const e=h.covertCellValues(n,this._range);return this._commandService.syncExecuteCommand(s.SetRangeValuesCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,value:e}),this}setFontWeight(n){let e;if(n==="bold")e=h.BooleanNumber.TRUE;else if(n==="normal")e=h.BooleanNumber.FALSE;else if(n===null)e=null;else throw new Error("Invalid fontWeight");const t={type:"bl",value:e},i={unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,style:t};return this._commandService.syncExecuteCommand(s.SetStyleCommand.id,i),this}setFontStyle(n){let e;if(n==="italic")e=h.BooleanNumber.TRUE;else if(n==="normal")e=h.BooleanNumber.FALSE;else if(n===null)e=null;else throw new Error("Invalid fontStyle");const t={type:"it",value:e},i={unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,style:t};return this._commandService.syncExecuteCommand(s.SetStyleCommand.id,i),this}setFontLine(n){if(n==="underline")this._setFontUnderline({s:h.BooleanNumber.TRUE});else if(n==="line-through")this._setFontStrikethrough({s:h.BooleanNumber.TRUE});else if(n==="none")this._setFontUnderline({s:h.BooleanNumber.FALSE}),this._setFontStrikethrough({s:h.BooleanNumber.FALSE});else if(n===null)this._setFontUnderline(null),this._setFontStrikethrough(null);else throw new Error("Invalid fontLine");return this}_setFontUnderline(n){const e={type:"ul",value:n},t={unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,style:e};this._commandService.syncExecuteCommand(s.SetStyleCommand.id,t)}_setFontStrikethrough(n){const e={type:"st",value:n},t={unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,style:e};this._commandService.syncExecuteCommand(s.SetStyleCommand.id,t)}setFontFamily(n){const e={type:"ff",value:n},t={unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,style:e};return this._commandService.syncExecuteCommand(s.SetStyleCommand.id,t),this}setFontSize(n){const e={type:"fs",value:n},t={unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,style:e};return this._commandService.syncExecuteCommand(s.SetStyleCommand.id,t),this}setFontColor(n){const t={type:"cl",value:n===null?null:{rgb:n}},i={unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,style:t};return this._commandService.syncExecuteCommand(s.SetStyleCommand.id,i),this}merge(n=!0){const e=this._workbook.getUnitId(),t=this._worksheet.getSheetId();return s.addMergeCellsUtil(this._injector,e,t,[this._range],n),this}mergeAcross(n=!0){const e=s.getAddMergeMutationRangeByType([this._range],h.Dimension.ROWS),t=this._workbook.getUnitId(),i=this._worksheet.getSheetId();return s.addMergeCellsUtil(this._injector,t,i,e,n),this}mergeVertically(n=!0){const e=s.getAddMergeMutationRangeByType([this._range],h.Dimension.COLUMNS),t=this._workbook.getUnitId(),i=this._worksheet.getSheetId();return s.addMergeCellsUtil(this._injector,t,i,e,n),this}isPartOfMerge(){const{startRow:n,startColumn:e,endRow:t,endColumn:i}=this._range;return this._worksheet.getMergedCellRange(n,e,t,i).length>0}breakApart(){return this._commandService.syncExecuteCommand(s.RemoveWorksheetMergeCommand.id,{ranges:[this._range]}),this}forEach(n){const{startColumn:e,startRow:t,endColumn:i,endRow:o}=this._range;this._worksheet.getMatrixWithMergedCells(t,e,o,i).forValue((a,d,u)=>{n(a,d,u)})}getA1Notation(n,e,t){const i={...this._range,startAbsoluteRefType:e,endAbsoluteRefType:t};return n?P.serializeRangeWithSheet(this._worksheet.getName(),i):P.serializeRange(i)}activate(){return this._injector.createInstance(c.FWorkbook,this._workbook).setActiveRange(this),this}activateAsCurrentCell(){const n=this._worksheet.getMergedCell(this._range.startRow,this._range.startColumn);if(n&&h.Rectangle.equals(n,this._range)||!n&&this._range.startRow===this._range.endRow&&this._range.startColumn===this._range.endColumn){const i=this._injector.createInstance(c.FWorkbook,this._workbook).getActiveRange();if(!i||i.getUnitId()!==this.getUnitId()||i.getSheetId()!==this.getSheetId())return this.activate();if(h.Rectangle.contains(i.getRange(),this._range)){const o={unitId:this.getUnitId(),subUnitId:this.getSheetId(),selections:[{range:i.getRange(),primary:s.getPrimaryForRange(this.getRange(),this._worksheet),style:null}]};return this._commandService.syncExecuteCommand(s.SetSelectionsOperation.id,o),this}return this.activate()}else throw new Error("The range is not a single cell")}splitTextToColumns(n,e,t){this._commandService.syncExecuteCommand(s.SplitTextToColumnsCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,delimiter:e,customDelimiter:t,treatMultipleDelimitersAsOne:n})}useThemeStyle(n){if(n==null){const e=this.getUsedThemeStyle();e&&this.removeThemeStyle(e)}else this._commandService.syncExecuteCommand(s.SetWorksheetRangeThemeStyleCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,themeName:n})}removeThemeStyle(n){this._commandService.syncExecuteCommand(s.DeleteWorksheetRangeThemeStyleCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range,themeName:n})}getUsedThemeStyle(){return this._injector.get(s.SheetRangeThemeService).getAppliedRangeThemeStyle({unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),range:this._range})}clear(n){return n&&n.contentsOnly&&!n.formatOnly?this.clearContent():n&&n.formatOnly&&!n.contentsOnly?this.clearFormat():(this._commandService.syncExecuteCommand(s.ClearSelectionAllCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),ranges:[this._range],options:n}),this)}clearContent(){return this._commandService.syncExecuteCommand(s.ClearSelectionContentCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),ranges:[this._range]}),this}clearFormat(){return this._commandService.syncExecuteCommand(s.ClearSelectionFormatCommand.id,{unitId:this._workbook.getUnitId(),subUnitId:this._worksheet.getSheetId(),ranges:[this._range]}),this}insertCells(n){n===h.Dimension.ROWS?this._commandService.executeCommand(s.InsertRangeMoveDownCommand.id,{range:this._range}):this._commandService.executeCommand(s.InsertRangeMoveRightCommand.id,{range:this._range})}deleteCells(n){n===h.Dimension.ROWS?this._commandService.executeCommand(s.DeleteRangeMoveUpCommand.id,{range:this._range}):this._commandService.executeCommand(s.DeleteRangeMoveLeftCommand.id,{range:this._range})}getDataRegion(n){const{startRow:e,startColumn:t,endRow:i,endColumn:o}=this._range,a=this._worksheet.getMaxRows(),d=this._worksheet.getMaxColumns(),u=this._worksheet.getCellMatrix();let l=e,m=t,_=i,k=o;if(n!==h.Dimension.COLUMNS){let v=!1,R=!1;for(let f=t;f<=o&&(e>0&&!h.isNullCell(u.getValue(e-1,f))&&(v=!0),i<a-1&&!h.isNullCell(u.getValue(i+1,f))&&(R=!0),!(v&&R));f++);v&&(l=e-1),R&&(_=i+1)}if(n!==h.Dimension.ROWS){let v=!1,R=!1;for(let f=e;f<=i&&(t>0&&!h.isNullCell(u.getValue(f,t-1))&&(v=!0),o<d-1&&!h.isNullCell(u.getValue(f,o+1))&&(R=!0),!(v&&R));f++);v&&(m=t-1),R&&(k=o+1)}return this._injector.createInstance(c.FRange,this._workbook,this._worksheet,{startRow:l,startColumn:m,endRow:_,endColumn:k})}isBlank(){const n=this._worksheet.getCellMatrix(),{startRow:e,startColumn:t,endRow:i,endColumn:o}=this._range;let a=!0;for(let d=e;d<=i;d++){for(let u=t;u<=o;u++)if(!h.isNullCell(n.getValue(d,u))){a=!1;break}if(!a)break}return a}offset(n,e,t,i){const{startRow:o,startColumn:a,endRow:d,endColumn:u}=this._range,l=o+n,m=a+e,_=t?l+t-1:d+n,k=i?m+i-1:u+e;if(l<0||m<0||_<0||k<0)throw new Error("The row or column index is out of range");return this._injector.createInstance(c.FRange,this._workbook,this._worksheet,{startRow:l,startColumn:m,endRow:_,endColumn:k})}setFormula(n){return this.setValue({f:n})}setFormulas(n){return this.setValues(n.map(e=>e.map(t=>({f:t}))))}getRangePermission(){const n=this._injector.createInstance(c.FWorksheet,this._injector.createInstance(c.FWorkbook,this._workbook),this._workbook,this._worksheet);return this._injector.createInstance(K,this._workbook.getUnitId(),this._worksheet.getSheetId(),this,n)}},D._enableManualInit(),D),c.FRange=Ie([Y(3,h.Inject(h.Injector)),Y(4,h.ICommandService),Y(5,h.Inject(P.FormulaDataModel))],c.FRange);var be=Object.getOwnPropertyDescriptor,fe=(r,n,e,t)=>{for(var i=t>1?void 0:t?be(n,e):n,o=r.length-1,a;o>=0;o--)(a=r[o])&&(i=a(i)||i);return i},q=(r,n)=>(e,t)=>n(e,t,r);let J=class{constructor(r,n,e,t){w(this,"_permissionSubject");w(this,"_collaboratorChangeSubject",new j.Subject);w(this,"permission$");w(this,"pointChange$");w(this,"collaboratorChange$");w(this,"_subscriptions",[]);w(this,"_fPermission");this._unitId=r,this._injector=n,this._permissionService=e,this._authzIoService=t,this._fPermission=this._injector.createInstance(c.FPermission),this._permissionSubject=new j.BehaviorSubject(this._buildSnapshot()),this.permission$=this._createPermissionStream(),this.pointChange$=this._createPointChangeStream(),this.collaboratorChange$=this._collaboratorChangeSubject.asObservable().pipe(C.shareReplay({bufferSize:1,refCount:!0}))}_createPermissionStream(){const r=this._permissionService.permissionPointUpdate$.pipe(C.filter(n=>n.id.includes(this._unitId))).subscribe(()=>{this._permissionSubject.next(this._buildSnapshot())});return this._subscriptions.push(r),this._permissionSubject.asObservable().pipe(C.distinctUntilChanged((n,e)=>JSON.stringify(n)===JSON.stringify(e)),C.shareReplay({bufferSize:1,refCount:!0}))}_createPointChangeStream(){const r=new Map;for(const n in g){const e=g[n];r.set(e,this.getPoint(e))}return this._permissionService.permissionPointUpdate$.pipe(C.filter(n=>n.id.includes(this._unitId)),C.map(n=>{const e=this._extractWorkbookPointType(n.id);if(!e)return null;const t=!!n.value,i=r.get(e);return r.set(e,t),i===t?null:{point:e,value:t,oldValue:i}}),C.filter(n=>n!==null),C.shareReplay({bufferSize:1,refCount:!0}))}_extractWorkbookPointType(r){for(const n in g){const e=g[n],t=x[e];if(!t)continue;if(new t(this._unitId).id===r)return e}return null}_buildSnapshot(){const r={};for(const n in g){const e=g[n];r[e]=this.getPoint(e)}return r}async setMode(r){const n=this._getModePermissions(r);await this._batchSetPermissionPoints(n)}_getModePermissions(r){const n={};switch(Object.values(g).forEach(e=>{n[e]=!1}),r){case"owner":Object.values(g).forEach(e=>{n[e]=!0});break;case"editor":n[g.Edit]=!0,n[g.View]=!0,n[g.Print]=!0,n[g.Export]=!0,n[g.CopyContent]=!0,n[g.Comment]=!0,n[g.CreateSheet]=!0,n[g.DeleteSheet]=!0,n[g.RenameSheet]=!0,n[g.MoveSheet]=!0,n[g.HideSheet]=!0,n[g.InsertRow]=!0,n[g.InsertColumn]=!0,n[g.DeleteRow]=!0,n[g.DeleteColumn]=!0,n[g.CopySheet]=!0,n[g.CreateProtection]=!0;break;case"viewer":n[g.View]=!0,n[g.Print]=!0;break;case"commenter":n[g.View]=!0,n[g.Comment]=!0,n[g.Print]=!0;break}return n}async _batchSetPermissionPoints(r){const n=[];for(const[e,t]of Object.entries(r)){const i=e,o=x[i];if(!o)throw new Error(`Unknown workbook permission point: ${i}`);const a=this.getPoint(i);a!==t&&(this._fPermission.setWorkbookPermissionPoint(this._unitId,o,t),n.push({point:i,value:t,oldValue:a}))}if(n.length>0){const e=this._buildSnapshot();this._permissionSubject.next(e)}}async setReadOnly(){await this.setMode("viewer")}async setEditable(){await this.setMode("editor")}canEdit(){return this.getPoint(g.Edit)}async setPoint(r,n){const e=x[r];if(!e)throw new Error(`Unknown workbook permission point: ${r}`);if(this.getPoint(r)===n)return;this._fPermission.setWorkbookPermissionPoint(this._unitId,e,n);const i=this._buildSnapshot();this._permissionSubject.next(i)}getPoint(r){var i;const n=x[r];if(!n)throw new Error(`Unknown workbook permission point: ${r}`);const e=new n(this._unitId),t=this._permissionService.getPermissionPoint(e.id);return(i=t==null?void 0:t.value)!=null?i:!0}getSnapshot(){return this._buildSnapshot()}async setCollaborators(r){const n=r.map(e=>({id:e.user.userID,subject:e.user,role:e.role}));await this._authzIoService.putCollaborators({objectID:this._unitId,unitID:this._unitId,collaborators:n}),r.forEach(e=>{this._collaboratorChangeSubject.next({type:"add",collaborator:{user:{id:e.user.userID},role:e.role}})})}async addCollaborator(r,n){await this._authzIoService.createCollaborator({objectID:this._unitId,unitID:this._unitId,collaborators:[{id:r.userID,subject:r,role:n}]}),this._collaboratorChangeSubject.next({type:"add",collaborator:{user:{id:r.userID},role:n}})}async updateCollaborator(r,n){await this._authzIoService.updateCollaborator({objectID:this._unitId,unitID:this._unitId,collaborator:{id:r.userID,subject:r,role:n}}),this._collaboratorChangeSubject.next({type:"update",collaborator:{user:{id:r.userID},role:n}})}async removeCollaborator(r){await this._authzIoService.deleteCollaborator({objectID:this._unitId,unitID:this._unitId,collaboratorID:r}),this._collaboratorChangeSubject.next({type:"delete",collaborator:{user:{id:r},role:M.Reader}})}async removeCollaborators(r){for(const n of r)await this.removeCollaborator(n)}async listCollaborators(){return(await this._authzIoService.listCollaborators({objectID:this._unitId,unitID:this._unitId})).map(n=>{var e,t;return{user:{id:((e=n.subject)==null?void 0:e.userID)||n.id,displayName:((t=n.subject)==null?void 0:t.name)||""},role:n.role}})}subscribe(r){const n=this.permission$.subscribe(r);return()=>n.unsubscribe()}dispose(){this._subscriptions.forEach(r=>r.unsubscribe()),this._permissionSubject.complete(),this._collaboratorChangeSubject.complete()}};J=fe([q(1,h.Inject(h.Injector)),q(2,h.IPermissionService),q(3,h.IAuthzIoService)],J);var ve=Object.getOwnPropertyDescriptor,Re=(r,n,e,t)=>{for(var i=t>1?void 0:t?ve(n,e):n,o=r.length-1,a;o>=0;o--)(a=r[o])&&(i=a(i)||i);return i},y=(r,n)=>(e,t)=>n(e,t,r);c.FWorkbook=class extends b.FBaseInitialable{constructor(e,t,i,o,a,d,u,l,m,_){super(t);w(this,"id");this._workbook=e,this._injector=t,this._resourceLoaderService=i,this._selectionManagerService=o,this._univerInstanceService=a,this._commandService=d,this._permissionService=u,this._logService=l,this._localeService=m,this._definedNamesService=_,this.id=this._workbook.getUnitId()}getWorkbook(){return this._workbook}dispose(){super.dispose(),this._workbook=null}getId(){return this.id}getName(){return this._workbook.name}setName(e){return this._commandService.syncExecuteCommand(s.SetWorkbookNameCommand.id,{unitId:this._workbook.getUnitId(),name:e}),this}save(){return this._resourceLoaderService.saveUnit(this._workbook.getUnitId())}getSnapshot(){return this._logService.warn("use 'save' instead of 'getSnapshot'"),this.save()}getActiveSheet(){const e=this._workbook.getActiveSheet();return this._injector.createInstance(c.FWorksheet,this,this._workbook,e)}getSheets(){return this._workbook.getSheets().map(e=>this._injector.createInstance(c.FWorksheet,this,this._workbook,e))}create(e,t,i,o){var l,m,_;const a=h.mergeWorksheetSnapshotWithDefault(h.Tools.deepClone((l=o==null?void 0:o.sheet)!=null?l:{}));a.name=e,a.rowCount=t,a.columnCount=i,a.id=(m=o==null?void 0:o.sheet)==null?void 0:m.id;const d=(_=o==null?void 0:o.index)!=null?_:this._workbook.getSheets().length;this._commandService.syncExecuteCommand(s.InsertSheetCommand.id,{unitId:this.id,index:d,sheet:a}),this._commandService.syncExecuteCommand(s.SetWorksheetActiveOperation.id,{unitId:this.id,subUnitId:this._workbook.getSheets()[d].getSheetId()});const u=this._workbook.getActiveSheet();if(!u)throw new Error("No active sheet found");return this._injector.createInstance(c.FWorksheet,this,this._workbook,u)}getSheetBySheetId(e){const t=this._workbook.getSheetBySheetId(e);return t?this._injector.createInstance(c.FWorksheet,this,this._workbook,t):null}getSheetByName(e){const t=this._workbook.getSheetBySheetName(e);return t?this._injector.createInstance(c.FWorksheet,this,this._workbook,t):null}setActiveSheet(e){return this._commandService.syncExecuteCommand(s.SetWorksheetActiveOperation.id,{unitId:this.id,subUnitId:typeof e=="string"?e:e.getSheetId()}),typeof e=="string"?this.getSheetBySheetId(e):e}insertSheet(e,t){var d,u,l;const i=h.mergeWorksheetSnapshotWithDefault(h.Tools.deepClone((d=t==null?void 0:t.sheet)!=null?d:{}));i.name=e,i.id=(u=t==null?void 0:t.sheet)==null?void 0:u.id;const o=(l=t==null?void 0:t.index)!=null?l:this._workbook.getSheets().length;this._commandService.syncExecuteCommand(s.InsertSheetCommand.id,{unitId:this.id,index:o,sheet:i}),this._commandService.syncExecuteCommand(s.SetWorksheetActiveOperation.id,{unitId:this.id,subUnitId:this._workbook.getSheets()[o].getSheetId()});const a=this._workbook.getActiveSheet();if(!a)throw new Error("No active sheet found");return this._injector.createInstance(c.FWorksheet,this,this._workbook,a)}deleteSheet(e){const t=this.id,i=typeof e=="string"?e:e.getSheetId();return this._commandService.syncExecuteCommand(s.RemoveSheetCommand.id,{unitId:t,subUnitId:i})}undo(){return this._univerInstanceService.focusUnit(this.id),this._commandService.syncExecuteCommand(h.UndoCommand.id),this}redo(){return this._univerInstanceService.focusUnit(this.id),this._commandService.syncExecuteCommand(h.RedoCommand.id),this}onBeforeCommandExecute(e){return this._commandService.beforeCommandExecuted(t=>{var i;((i=t.params)==null?void 0:i.unitId)===this.id&&e(t)})}onCommandExecuted(e){return this._commandService.onCommandExecuted(t=>{var i;((i=t.params)==null?void 0:i.unitId)===this.id&&e(t)})}onSelectionChange(e){return h.toDisposable(this._selectionManagerService.selectionMoveEnd$.subscribe(t=>{this._univerInstanceService.getCurrentUnitForType(h.UniverInstanceType.UNIVER_SHEET).getUnitId()===this.id&&(t!=null&&t.length?e(t.map(i=>i.range)):e([]))}))}setEditable(e){const t=new s.WorkbookEditablePermission(this._workbook.getUnitId());return this._permissionService.getPermissionPoint(t.id)||this._permissionService.addPermissionPoint(t),this._permissionService.updatePermissionPoint(t.id,e),this}setActiveRange(e){const t=this.getActiveSheet(),i=e.getRange().sheetId||t.getSheetId(),o=i?this._workbook.getSheetBySheetId(i):this._workbook.getActiveSheet(!0);if(!o)throw new Error("No active sheet found");o.getSheetId()!==t.getSheetId()&&this.setActiveSheet(this._injector.createInstance(c.FWorksheet,this,this._workbook,o));const a={unitId:this.getId(),subUnitId:i,selections:[e].map(d=>({range:d.getRange(),primary:s.getPrimaryForRange(d.getRange(),o),style:null}))};return this._commandService.syncExecuteCommand(s.SetSelectionsOperation.id,a),this}getActiveRange(){const e=this._workbook.getActiveSheet(),i=this._selectionManagerService.getCurrentSelections().find(o=>!!o.primary);return i?this._injector.createInstance(c.FRange,this._workbook,e,i.range):null}getActiveCell(){const e=this._workbook.getActiveSheet(),i=this._selectionManagerService.getCurrentSelections().find(a=>!!a.primary);if(!i)return null;const o={...i.primary,rangeType:h.RANGE_TYPE.NORMAL};return this._injector.createInstance(c.FRange,this._workbook,e,o)}deleteActiveSheet(){const e=this.getActiveSheet();return this.deleteSheet(e)}duplicateSheet(e){return this._commandService.syncExecuteCommand(s.CopySheetCommand.id,{unitId:e.getWorkbook().getUnitId(),subUnitId:e.getSheetId()}),this._injector.createInstance(c.FWorksheet,this,this._workbook,this._workbook.getActiveSheet())}duplicateActiveSheet(){const e=this.getActiveSheet();return this.duplicateSheet(e)}getNumSheets(){return this._workbook.getSheets().length}getLocale(){return this._localeService.getCurrentLocale()}setLocale(e){this._localeService.setLocale(e)}setSpreadsheetLocale(e){return this._localeService.setLocale(e),this}getUrl(){return location.href}moveSheet(e,t){let i=t;return i<0?i=0:i>this._workbook.getSheets().length-1&&(i=this._workbook.getSheets().length-1),this._commandService.syncExecuteCommand(s.SetWorksheetOrderCommand.id,{unitId:e.getWorkbook().getUnitId(),order:i,subUnitId:e.getSheetId()}),this}moveActiveSheet(e){const t=this.getActiveSheet();return this.moveSheet(t,e)}getPermission(){return this._injector.createInstance(c.FPermission)}getWorkbookPermission(){return this._injector.createInstance(J,this._workbook.getUnitId())}getDefinedName(e){const t=this._definedNamesService.getValueByName(this.id,e);return t?this._injector.createInstance(A,{...t,unitId:this.id}):null}getDefinedNames(){const e=this._definedNamesService.getDefinedNameMap(this.id);return e?Object.values(e).map(t=>this._injector.createInstance(A,{...t,unitId:this.id})):[]}insertDefinedName(e,t){const o=this._injector.createInstance(V).setName(e).setRef(t).build();return o.localSheetId=s.SCOPE_WORKBOOK_VALUE_DEFINED_NAME,this.insertDefinedNameBuilder(o),this}deleteDefinedName(e){const t=this.getDefinedName(e);return t?(t.delete(),!0):!1}insertDefinedNameBuilder(e){e.unitId=this.getId(),this._commandService.syncExecuteCommand(s.SetDefinedNameCommand.id,e)}updateDefinedNameBuilder(e){this._commandService.syncExecuteCommand(s.SetDefinedNameCommand.id,e)}getRegisteredRangeThemes(){return this._injector.get(s.SheetRangeThemeService).getRegisteredRangeThemes()}registerRangeTheme(e){this._commandService.syncExecuteCommand(s.RegisterWorksheetRangeThemeStyleCommand.id,{unitId:this.getId(),rangeThemeStyle:e})}unregisterRangeTheme(e){this._commandService.syncExecuteCommand(s.UnregisterWorksheetRangeThemeStyleCommand.id,{unitId:this.getId(),themeName:e})}createRangeThemeStyle(e,t){return new s.RangeThemeStyle(e,t)}setCustomMetadata(e){return this._workbook.setCustomMetadata(e),this}getCustomMetadata(){return this._workbook.getCustomMetadata()}addStyles(e){this._workbook.addStyles(e)}removeStyles(e){this._workbook.removeStyles(e)}},c.FWorkbook=Re([y(1,h.Inject(h.Injector)),y(2,h.Inject(h.IResourceLoaderService)),y(3,h.Inject(s.SheetsSelectionsService)),y(4,h.IUniverInstanceService),y(5,h.ICommandService),y(6,h.IPermissionService),y(7,h.ILogService),y(8,h.Inject(h.LocaleService)),y(9,P.IDefinedNamesService)],c.FWorkbook);class pe extends b.FUniver{getCommandSheetTarget(n){var o;const e=n.params;if(!e)return this.getActiveSheet();const t=e.unitId?this.getUniverSheet(e.unitId):(o=this.getActiveWorkbook)==null?void 0:o.call(this);if(!t)return;const i=t.getSheetBySheetId(e.subUnitId||e.sheetId)||t.getActiveSheet();if(i)return{workbook:t,worksheet:i}}getSheetTarget(n,e){const t=this.getUniverSheet(n);if(!t)return;const i=t.getSheetBySheetId(e);if(i)return{workbook:t,worksheet:i}}_initWorkbookEvent(n){const e=n.get(h.IUniverInstanceService);this.registerEventHandler(this.Event.WorkbookDisposed,()=>e.unitDisposed$.subscribe(t=>{t.type===h.UniverInstanceType.UNIVER_SHEET&&this.fireEvent(this.Event.WorkbookDisposed,{unitId:t.getUnitId(),unitType:t.type,snapshot:t.getSnapshot()})})),this.registerEventHandler(this.Event.WorkbookCreated,()=>e.unitAdded$.subscribe(t=>{if(t.type===h.UniverInstanceType.UNIVER_SHEET){const i=t,o=n.createInstance(c.FWorkbook,i);this.fireEvent(this.Event.WorkbookCreated,{unitId:t.getUnitId(),type:t.type,workbook:o,unit:o})}}))}_initialize(n){const e=n.get(h.ICommandService);this.registerEventHandler(this.Event.BeforeSheetCreate,()=>e.beforeCommandExecuted(t=>{var i;if(t.id===s.InsertSheetCommand.id){const o=t.params,{unitId:a,index:d,sheet:u}=o||{},l=a?this.getUniverSheet(a):(i=this.getActiveWorkbook)==null?void 0:i.call(this);if(!l)return;const m={workbook:l,index:d,sheet:u};if(this.fireEvent(this.Event.BeforeSheetCreate,m),m.cancel)throw new h.CanceledError}})),this.registerEventHandler(this.Event.BeforeActiveSheetChange,()=>e.beforeCommandExecuted(t=>{var i;if(t.id===s.SetWorksheetActiveOperation.id){const{subUnitId:o,unitId:a}=t.params,d=a?this.getUniverSheet(a):(i=this.getActiveWorkbook)==null?void 0:i.call(this);if(!d||!o)return;const u=d.getSheetBySheetId(o),l=d.getActiveSheet();if(!u||!l)return;const m={workbook:d,activeSheet:u,oldActiveSheet:l};if(this.fireEvent(this.Event.BeforeActiveSheetChange,m),m.cancel)throw new h.CanceledError}})),this.registerEventHandler(this.Event.BeforeSheetDelete,()=>e.beforeCommandExecuted(t=>{if(t.id===s.RemoveSheetCommand.id){const i=this.getCommandSheetTarget(t);if(!i)return;const{workbook:o,worksheet:a}=i,d={workbook:o,worksheet:a};if(this.fireEvent(this.Event.BeforeSheetDelete,d),d.cancel)throw new h.CanceledError}})),this.registerEventHandler(this.Event.BeforeSheetMove,()=>e.beforeCommandExecuted(t=>{if(t.id===s.SetWorksheetOrderMutation.id){const{fromOrder:i,toOrder:o}=t.params,a=this.getCommandSheetTarget(t);if(!a)return;const d={workbook:a.workbook,worksheet:a.worksheet,newIndex:o,oldIndex:i};if(this.fireEvent(this.Event.BeforeSheetMove,d),d.cancel)throw new h.CanceledError}})),this.registerEventHandler(this.Event.BeforeSheetNameChange,()=>e.beforeCommandExecuted(t=>{if(t.id===s.SetWorksheetNameCommand.id){const{name:i}=t.params,o=this.getCommandSheetTarget(t);if(!o)return;const a={workbook:o.workbook,worksheet:o.worksheet,newName:i,oldName:o.worksheet.getSheetName()};if(this.fireEvent(this.Event.BeforeSheetNameChange,a),a.cancel)throw new h.CanceledError}})),this.registerEventHandler(this.Event.BeforeSheetTabColorChange,()=>e.beforeCommandExecuted(t=>{if(t.id===s.SetTabColorMutation.id){const{color:i}=t.params,o=this.getCommandSheetTarget(t);if(!o)return;const a={workbook:o.workbook,worksheet:o.worksheet,newColor:i,oldColor:o.worksheet.getTabColor()};if(this.fireEvent(this.Event.BeforeSheetTabColorChange,a),a.cancel)throw new h.CanceledError}})),this.registerEventHandler(this.Event.BeforeSheetHideChange,()=>e.beforeCommandExecuted(t=>{if(t.id===s.SetWorksheetHideMutation.id){const{hidden:i}=t.params,o=this.getCommandSheetTarget(t);if(!o)return;const a={workbook:o.workbook,worksheet:o.worksheet,hidden:!!i};if(this.fireEvent(this.Event.BeforeSheetHideChange,a),a.cancel)throw new h.CanceledError}})),this.registerEventHandler(this.Event.BeforeGridlineColorChange,()=>e.beforeCommandExecuted(t=>{var i;if(t.id===s.SetGridlinesColorCommand.id){const o=this.getCommandSheetTarget(t);if(!o)return;const a={...o,color:(i=t.params)==null?void 0:i.color};if(this.fireEvent(this.Event.BeforeGridlineColorChange,a),a.cancel)throw new h.CanceledError}})),this.registerEventHandler(this.Event.BeforeGridlineEnableChange,()=>e.beforeCommandExecuted(t=>{var i;if(t.id===s.ToggleGridlinesCommand.id){const o=this.getCommandSheetTarget(t);if(!o)return;const a={...o,enabled:!!((i=t.params)!=null&&i.showGridlines)};if(this.fireEvent(this.Event.BeforeGridlineEnableChange,a),a.cancel)throw new h.CanceledError}})),this.registerEventHandler(this.Event.SheetValueChanged,()=>e.onCommandExecuted(t=>{if(s.COMMAND_LISTENER_VALUE_CHANGE.indexOf(t.id)>-1){if(!this.getActiveSheet())return;const o=s.getValueChangedEffectedRange(t).map(a=>{var d,u;return(u=(d=this.getWorkbook(a.unitId))==null?void 0:d.getSheetBySheetId(a.subUnitId))==null?void 0:u.getRange(a.range)}).filter(Boolean);if(!o.length)return;this.fireEvent(this.Event.SheetValueChanged,{payload:t,effectedRanges:o})}})),this.registerEventHandler(this.Event.SheetCreated,()=>e.onCommandExecuted(t=>{var i;if(t.id===s.InsertSheetCommand.id){const o=t.params,{unitId:a}=o||{},d=a?this.getUniverSheet(a):(i=this.getActiveWorkbook)==null?void 0:i.call(this);if(!d)return;const u=d.getActiveSheet();if(!u)return;const l={workbook:d,worksheet:u};this.fireEvent(this.Event.SheetCreated,l)}})),this.registerEventHandler(this.Event.ActiveSheetChanged,()=>e.onCommandExecuted(t=>{if(t.id===s.SetWorksheetActiveOperation.id){const i=this.getActiveSheet();if(!i)return;const{workbook:o,worksheet:a}=i;this._fireActiveSheetChanged(o,a)}})),this.registerEventHandler(this.Event.SheetDeleted,()=>e.onCommandExecuted(t=>{var i;if(t.id===s.RemoveSheetCommand.id){const{subUnitId:o,unitId:a}=t.params,d=a?this.getUniverSheet(a):(i=this.getActiveWorkbook)==null?void 0:i.call(this);if(!d||!o)return;this._fireSheetDeleted(d,o)}})),this.registerEventHandler(this.Event.SheetMoved,()=>e.onCommandExecuted(t=>{if(t.id===s.SetWorksheetOrderMutation.id){const{toOrder:i}=t.params,o=this.getCommandSheetTarget(t);if(!o)return;this._fireSheetMoved(o.workbook,o.worksheet,i)}})),this.registerEventHandler(this.Event.SheetNameChanged,()=>e.onCommandExecuted(t=>{if(t.id===s.SetWorksheetNameCommand.id){const{name:i}=t.params,o=this.getCommandSheetTarget(t);if(!o)return;this._fireSheetNameChanged(o.workbook,o.worksheet,i)}})),this.registerEventHandler(this.Event.SheetTabColorChanged,()=>e.onCommandExecuted(t=>{if(t.id===s.SetTabColorMutation.id){const{color:i}=t.params,o=this.getCommandSheetTarget(t);if(!o)return;this._fireSheetTabColorChanged(o.workbook,o.worksheet,i)}})),this.registerEventHandler(this.Event.SheetHideChanged,()=>e.onCommandExecuted(t=>{if(t.id===s.SetWorksheetHideMutation.id){const{hidden:i}=t.params,o=this.getCommandSheetTarget(t);if(!o)return;this._fireSheetHideChanged(o.workbook,o.worksheet,!!i)}})),this.registerEventHandler(this.Event.GridlineChanged,()=>e.onCommandExecuted(t=>{if(t.id===s.SetGridlinesColorCommand.id||t.id===s.ToggleGridlinesCommand.id){const i=this.getCommandSheetTarget(t);if(!i)return;this.fireEvent(this.Event.GridlineChanged,{...i,enabled:!i.worksheet.hasHiddenGridLines(),color:i.worksheet.getGridLinesColor()})}})),this._initWorkbookEvent(n)}createUniverSheet(n,e){const i=this._injector.get(h.IUniverInstanceService).createUnit(h.UniverInstanceType.UNIVER_SHEET,n,e);return this._injector.createInstance(c.FWorkbook,i)}createWorkbook(n,e){return this.createUniverSheet(n,e)}getActiveWorkbook(){const n=this._univerInstanceService.getCurrentUnitForType(h.UniverInstanceType.UNIVER_SHEET);return n?this._injector.createInstance(c.FWorkbook,n):null}getActiveUniverSheet(){return this.getActiveWorkbook()}getUniverSheet(n){const e=this._univerInstanceService.getUnit(n,h.UniverInstanceType.UNIVER_SHEET);return e?this._injector.createInstance(c.FWorkbook,e):null}getWorkbook(n){return this.getUniverSheet(n)}getPermission(){return this._injector.createInstance(c.FPermission)}onUniverSheetCreated(n){const e=this._univerInstanceService.getTypeOfUnitAdded$(h.UniverInstanceType.UNIVER_SHEET).subscribe(t=>{const i=this._injector.createInstance(c.FWorkbook,t);n(i)});return h.toDisposable(e)}newDefinedName(){return this._injector.createInstance(V)}getActiveSheet(){const n=this.getActiveWorkbook();if(!n)return null;const e=n.getActiveSheet();return e?{workbook:n,worksheet:e}:null}setFreezeSync(n){this._injector.get(s.SheetsFreezeSyncController).setEnabled(n)}_fireActiveSheetChanged(n,e){this.fireEvent(this.Event.ActiveSheetChanged,{workbook:n,activeSheet:e})}_fireSheetDeleted(n,e){this.fireEvent(this.Event.SheetDeleted,{workbook:n,sheetId:e})}_fireSheetMoved(n,e,t){this.fireEvent(this.Event.SheetMoved,{workbook:n,worksheet:e,newIndex:t})}_fireSheetNameChanged(n,e,t){this.fireEvent(this.Event.SheetNameChanged,{workbook:n,worksheet:e,newName:t})}_fireSheetTabColorChanged(n,e,t){this.fireEvent(this.Event.SheetTabColorChanged,{workbook:n,worksheet:e,newColor:t})}_fireSheetHideChanged(n,e,t){this.fireEvent(this.Event.SheetHideChanged,{workbook:n,worksheet:e,hidden:t})}}b.FUniver.extend(pe);class X{get SheetValueChangeType(){return s.SheetValueChangeType}get SheetSkeletonChangeType(){return s.SheetSkeletonChangeType}get SplitDelimiterType(){return s.SplitDelimiterEnum}get UnitRole(){return M}get WorkbookPermissionPoint(){return g}get WorksheetPermissionPoint(){return S}get RangePermissionPoint(){return I}}b.FEnum.extend(X);class ee{get SheetCreated(){return"SheetCreated"}get BeforeSheetCreate(){return"BeforeSheetCreate"}get WorkbookCreated(){return"WorkbookCreated"}get WorkbookDisposed(){return"WorkbookDisposed"}get GridlineChanged(){return"GridlineChanged"}get BeforeGridlineEnableChange(){return"BeforeGridlineEnableChange"}get BeforeGridlineColorChange(){return"BeforeGridlineColorChange"}get BeforeActiveSheetChange(){return"BeforeActiveSheetChange"}get ActiveSheetChanged(){return"ActiveSheetChanged"}get SheetDeleted(){return"SheetDeleted"}get BeforeSheetDelete(){return"BeforeSheetDelete"}get SheetMoved(){return"SheetMoved"}get BeforeSheetMove(){return"BeforeSheetMove"}get SheetNameChanged(){return"SheetNameChanged"}get BeforeSheetNameChange(){return"BeforeSheetNameChange"}get SheetTabColorChanged(){return"SheetTabColorChanged"}get BeforeSheetTabColorChange(){return"BeforeSheetTabColorChange"}get SheetHideChanged(){return"SheetHideChanged"}get BeforeSheetHideChange(){return"BeforeSheetHideChange"}get SheetValueChanged(){return"SheetValueChanged"}}b.FEventName.extend(ee);var Ee=Object.getOwnPropertyDescriptor,ye=(r,n,e,t)=>{for(var i=t>1?void 0:t?Ee(n,e):n,o=r.length-1,a;o>=0;o--)(a=r[o])&&(i=a(i)||i);return i},Pe=(r,n)=>(e,t)=>n(e,t,r);c.FSheetHooks=class extends b.FBase{constructor(n){super(),this._injector=n}},c.FSheetHooks=ye([Pe(0,h.Inject(h.Injector))],c.FSheetHooks),c.FSheetEventName=ee,c.FSheetsEnum=X,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})}));
|
|
17
17
|
|
|
18
18
|
|
|
19
19
|
// @univerjs/sheets-numfmt/index
|
|
20
|
-
(function(r,t){typeof exports=="object"&&typeof module<"u"?t(exports,require("@univerjs/core"),require("@univerjs/sheets"),require("rxjs"),require("@univerjs/engine-formula")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","@univerjs/sheets","rxjs","@univerjs/engine-formula"],t):(r=typeof globalThis<"u"?globalThis:r||self,t(r.UniverSheetsNumfmt={},r.UniverCore,r.UniverSheets,r.rxjs,r.UniverEngineFormula))})(this,(function(r,t,u,N,X){"use strict";var de=Object.defineProperty;var ge=(r,t,u)=>t in r?de(r,t,{enumerable:!0,configurable:!0,writable:!0,value:u}):r[t]=u;var V=(r,t,u)=>ge(r,typeof t!="symbol"?t+"":t,u);const P=["$","£","¥","¤","֏","؋","৳","฿","៛","₡","₦","₩","₪","₫","€","₭","₮","₱","₲","₴","₸","₹","₺","₼","₽","₾","₿","﷼"],E=new Map([[t.LocaleType.EN_US,"$"],[t.LocaleType.RU_RU,"₽"],[t.LocaleType.VI_VN,"₫"],[t.LocaleType.ZH_CN,"¥"],[t.LocaleType.ZH_TW,"NT$"],[t.LocaleType.FR_FR,"€"],[t.LocaleType.FA_IR,"﷼"],[t.LocaleType.KO_KR,"₩"],[t.LocaleType.ES_ES,"€"],[t.LocaleType.CA_ES,"€"]]);function j(e){switch(e){case t.LocaleType.CA_ES:case t.LocaleType.ES_ES:case t.LocaleType.FR_FR:return{icon:"EuroIcon",symbol:E.get(e)||"€",locale:e};case t.LocaleType.RU_RU:return{icon:"RoubleIcon",symbol:E.get(e)||"₽",locale:e};case t.LocaleType.ZH_CN:return{icon:"RmbIcon",symbol:E.get(e)||"¥",locale:e};case t.LocaleType.EN_US:default:return{icon:"DollarIcon",symbol:"$",locale:t.LocaleType.EN_US}}}function F(e){return E.get(e)||"$"}function A(e,a=2){let i=a;a>127&&(i=127);let n="";return i>0&&(n=`.${"0".repeat(i)}`),`"${F(e)}"#,##0${n}_);[Red]("${F(e)}"#,##0${n})`}const B=[{label:"1930-08-05",suffix:"yyyy-MM-dd"},{label:"1930/08/05",suffix:"yyyy/MM/dd"},{label:"1930年08月05日",suffix:'yyyy"年"MM"月"dd"日"'},{label:"08-05",suffix:"MM-dd"},{label:"8月5日",suffix:'M"月"d"日"'},{label:"13:30:30",suffix:"h:mm:ss"},{label:"13:30",suffix:"h:mm"},{label:"下午01:30",suffix:"A/P hh:mm"},{label:"下午1:30",suffix:"A/P h:mm"},{label:"下午1:30:30",suffix:"A/P h:mm:ss"},{label:"08-05 下午 01:30",suffix:"MM-dd A/P hh:mm"}],G=[{label:"(1,235)",suffix:"#,##0_);(#,##0)"},{label:"(1,235) ",suffix:"#,##0_);[Red](#,##0)",color:"red"},{label:"1,234.56",suffix:"#,##0.00_);#,##0.00"},{label:"1,234.56",suffix:"#,##0.00_);[Red]#,##0.00",color:"red"},{label:"-1,234.56",suffix:"#,##0.00_);-#,##0.00"},{label:"-1,234.56",suffix:"#,##0.00_);[Red]-#,##0.00",color:"red"}],H=[{label:e=>`${e}1,235`,suffix:e=>`"${e}"#,##0.00_);"${e}"#,##0.00`},{label:e=>`${e}1,235`,suffix:e=>`"${e}"#,##0.00_);[Red]"${e}"#,##0.00`,color:"red"},{label:e=>`(${e}1,235)`,suffix:e=>`"${e}"#,##0.00_);("${e}"#,##0.00)`},{label:e=>`(${e}1,235)`,suffix:e=>`"${e}"#,##0.00_);[Red]("${e}"#,##0.00)`,color:"red"},{label:e=>`-${e}1,235`,suffix:e=>`"${e}"#,##0.00_);-"${e}"#,##0.00`},{label:e=>`-${e}1,235`,suffix:e=>`"${e}"#,##0.00_);[Red]-"${e}"#,##0.00`,color:"red"}],U=(e,a=0)=>{var n;return e&&(n=t.numfmt.getFormatInfo(e).maxDecimals)!=null?n:a},L=e=>new Array(Math.min(Math.max(0,Number(e)),30)).fill(0).join(""),$=(e,a)=>e.split(";").map(n=>/\.0?/.test(n)?n.replace(/\.0*/g,`${a>0?".":""}${L(Number(a||0))}`):/0([^0]?)|0$/.test(n)?n.replace(/0([^0]+)|0$/,`0${a>0?".":""}${L(Number(a||0))}$1`):n).join(";"),J=e=>/\.0?/.test(e)||/0([^0]?)|0$/.test(e),I={id:"sheet.command.numfmt.set.numfmt",type:t.CommandType.COMMAND,handler:(e,a)=>{if(!a)return!1;const i=e.get(t.ICommandService),n=e.get(t.IUniverInstanceService),s=e.get(t.IUndoRedoService),l=u.getSheetCommandTarget(n,a);if(!l)return!1;const{unitId:m,subUnitId:S,worksheet:o}=l,f=a.values.filter(c=>!!c.pattern),T=a.values.filter(c=>!c.pattern),M=u.transformCellsToRange(m,S,f),y={unitId:m,subUnitId:S,ranges:T.map(c=>({startColumn:c.col,startRow:c.row,endColumn:c.col,endRow:c.row}))},b=[],p=[];if(f.length){const c=f.reduce((g,d)=>{t.isTextFormat(d.pattern)&&g.setValue(d.row,d.col,{t:t.CellValueType.STRING});const _=o.getCellRaw(d.row,d.col);if(_){const O=u.checkCellValueType(_.v);O!==_.t&&g.setValue(d.row,d.col,{t:O})}return g},new t.ObjectMatrix).getMatrix(),v=new t.ObjectMatrix;new t.ObjectMatrix(c).forValue((g,d)=>{const _=o.getCellRaw(g,d);_?v.setValue(g,d,{t:_.t}):v.setValue(g,d,{t:void 0})}),Object.keys(M.values).forEach(g=>{const d=M.values[g];d.ranges=u.rangeMerge(d.ranges)}),b.push({id:u.SetNumfmtMutation.id,params:M});const h=u.factorySetNumfmtUndoMutation(e,M);p.push(...h)}if(T.length){y.ranges=u.rangeMerge(y.ranges);const c=T.reduce((g,d)=>{const _=o.getCellRaw(d.row,d.col);if(_){const O=u.checkCellValueType(_.v);O!==_.t&&g.setValue(d.row,d.col,{t:O})}return g},new t.ObjectMatrix).getMatrix(),v=new t.ObjectMatrix;new t.ObjectMatrix(c).forValue((g,d)=>{const _=o.getCellRaw(g,d);_?v.setValue(g,d,{t:_.t}):v.setValue(g,d,{t:void 0})}),b.push({id:u.RemoveNumfmtMutation.id,params:y},{id:u.SetRangeValuesMutation.id,params:{unitId:m,subUnitId:S,cellValue:c}});const h=u.factoryRemoveNumfmtUndoMutation(e,y);p.push({id:u.SetRangeValuesMutation.id,params:{unitId:m,subUnitId:S,cellValue:v.getMatrix()}},...h)}const C=t.sequenceExecute(b,i).result;return C&&s.pushUndoRedo({unitID:m,undoMutations:p,redoMutations:b}),C}},x={id:"sheet.command.numfmt.add.decimal.command",type:t.CommandType.COMMAND,handler:async e=>{const a=e.get(t.ICommandService),i=e.get(u.SheetsSelectionsService),n=e.get(u.INumfmtService),s=e.get(t.IUniverInstanceService),l=i.getCurrentSelections();if(!l||!l.length)return!1;const m=u.getSheetCommandTarget(s);if(!m)return!1;const{unitId:S,subUnitId:o}=m;let f=0;l.forEach(b=>{t.Range.foreach(b.range,(p,C)=>{const c=n.getValue(S,o,p,C);if(!c){const h=m.worksheet.getCellRaw(p,C);if(!f&&h&&h.t===t.CellValueType.NUMBER&&h.v){const g=/\.(\d*)$/.exec(String(h.v));if(g){const d=g[1].length;if(!d)return;f=Math.max(f,d)}}return}const v=U(c.pattern);f=v>f?v:f})});const T=f+1,M=$(`0${T>0?".0":""}`,T),y=[];return l.forEach(b=>{t.Range.foreach(b.range,(p,C)=>{const c=n.getValue(S,o,p,C);if(t.isDefaultFormat(c==null?void 0:c.pattern))y.push({row:p,col:C,pattern:M});else{const v=U(c.pattern),h=$(c.pattern,v+1);h!==c.pattern&&y.push({row:p,col:C,pattern:h})}})}),y.length?await a.executeCommand(I.id,{values:y}):!1}},W={id:"sheet.command.numfmt.set.currency",type:t.CommandType.COMMAND,handler:async e=>{const a=e.get(t.ICommandService),i=e.get(u.SheetsSelectionsService),n=e.get(t.LocaleService),s=i.getCurrentSelections();if(!s||!s.length)return!1;const l=[],m=j(n.getCurrentLocale()),S=A(m.locale);return s.forEach(f=>{t.Range.foreach(f.range,(T,M)=>{l.push({row:T,col:M,pattern:S,type:"currency"})})}),await a.executeCommand(I.id,{values:l})}},K={id:"sheet.command.numfmt.set.percent",type:t.CommandType.COMMAND,handler:async e=>{const a=e.get(t.ICommandService),n=e.get(u.SheetsSelectionsService).getCurrentSelections();if(!n||!n.length)return!1;const s=[],l="0%";return n.forEach(S=>{t.Range.foreach(S.range,(o,f)=>{s.push({row:o,col:f,pattern:l,type:"percent"})})}),await a.executeCommand(I.id,{values:s})}},q={id:"sheet.command.numfmt.subtract.decimal.command",type:t.CommandType.COMMAND,handler:async e=>{const a=e.get(t.ICommandService),i=e.get(u.SheetsSelectionsService),n=e.get(u.INumfmtService),s=e.get(t.IUniverInstanceService),l=i.getCurrentSelections();if(!l||!l.length)return!1;const m=u.getSheetCommandTarget(s);if(!m)return!1;const{unitId:S,subUnitId:o}=m;let f=0;l.forEach(p=>{t.Range.foreach(p.range,(C,c)=>{const v=n.getValue(S,o,C,c);if(!v){const g=m.worksheet.getCellRaw(C,c);if(!f&&g&&g.t===t.CellValueType.NUMBER&&g.v){const d=/\.(\d*)$/.exec(String(g.v));if(d){const _=d[1].length;if(!_)return;f=Math.max(f,_)}}return}const h=U(v.pattern);f=h>f?h:f})});const T=f-1,M=$(`0${T>0?".0":"."}`,T),y=[];return l.forEach(p=>{t.Range.foreach(p.range,(C,c)=>{const v=n.getValue(S,o,C,c);if(t.isDefaultFormat(v==null?void 0:v.pattern))y.push({row:C,col:c,pattern:M});else{const h=U(v.pattern);y.push({row:C,col:c,pattern:$(v.pattern,h-1)})}})}),await a.executeCommand(I.id,{values:y})}},D="sheets-numfmt.config",Z={},Q=e=>t.numfmt.getFormatInfo(e).type||"unknown",k=(e,a,i="en")=>{const n=t.numfmt.formatColor(e,a),s=n?String(n):void 0,l=t.numfmt.format(e,a,{locale:i,throws:!1});return a<0?{result:l,color:s}:{result:l}},Y=(e,a,i)=>e===t.DEFAULT_NUMBER_FORMAT?{result:String(X.stripErrorMargin(a))}:k(e,a,i);var ee=Object.getOwnPropertyDescriptor,te=(e,a,i,n)=>{for(var s=n>1?void 0:n?ee(a,i):a,l=e.length-1,m;l>=0;l--)(m=e[l])&&(s=m(s)||s);return s},R=(e,a)=>(i,n)=>a(i,n,e);const ne={tl:{size:6,color:"#409f11"}};r.SheetsNumfmtCellContentController=class extends t.Disposable{constructor(i,n,s,l,m,S,o){super();V(this,"_locale$",new N.BehaviorSubject("en"));V(this,"locale$",this._locale$.asObservable());this._instanceService=i,this._sheetInterceptorService=n,this._themeService=s,this._commandService=l,this._numfmtService=m,this._localeService=S,this._configService=o,this._initInterceptorCellContent()}get locale(){const i=this._locale$.getValue();if(i)return i;switch(this._localeService.getCurrentLocale()){case t.LocaleType.FR_FR:return"fr";case t.LocaleType.RU_RU:return"ru";case t.LocaleType.VI_VN:return"vi";case t.LocaleType.ZH_CN:return"zh-CN";case t.LocaleType.KO_KR:return"ko";case t.LocaleType.ZH_TW:return"zh-TW";case t.LocaleType.ES_ES:case t.LocaleType.CA_ES:return"es";case t.LocaleType.EN_US:case t.LocaleType.FA_IR:default:return"en"}}_initInterceptorCellContent(){const i=new t.ObjectMatrix;this.disposeWithMe(N.merge(this._locale$,this._localeService.currentLocale$).subscribe(()=>{i.reset()})),this.disposeWithMe(this._sheetInterceptorService.intercept(u.INTERCEPTOR_POINT.CELL_CONTENT,{effect:t.InterceptorEffectEnum.Value|t.InterceptorEffectEnum.Style,handler:(n,s,l)=>{var p,C;if(!n||n.v===void 0||n.v===null||n.t===t.CellValueType.BOOLEAN||n.t===t.CellValueType.FORCE_STRING)return l(n);const m=s.unitId,S=s.subUnitId;let o;if(n!=null&&n.s){const c=s.workbook.getStyles().get(n.s);c!=null&&c.n&&(o=c.n)}if(o||(o=this._numfmtService.getValue(m,S,s.row,s.col)),t.isDefaultFormat(o==null?void 0:o.pattern)||n.t!==t.CellValueType.NUMBER&&u.checkCellValueType(n.v,n.t)!==t.CellValueType.NUMBER)return l(n);const f=n;if((!n||n===s.rawData)&&(n={...s.rawData}),t.isTextFormat(o==null?void 0:o.pattern))return(p=this._configService.getConfig(D))!=null&&p.disableTextFormatMark?(n.t=t.CellValueType.STRING,l(n)):(n.t=t.CellValueType.STRING,n.markers={...n==null?void 0:n.markers,...ne},l(n));let T="";const M=i.getValue(s.row,s.col);if(M&&M.parameters===`${f.v}_${o==null?void 0:o.pattern}`)return l({...n,...M.result});const y=Y(o==null?void 0:o.pattern,Number(f.v),this.locale);if(T=y.result,!T)return l(n);const b={v:T,t:t.CellValueType.NUMBER};if(y.color){const c=(C=this._themeService.getColorFromTheme(`${y.color}.500`))!=null?C:y.color;c&&(b.interceptorStyle={cl:{rgb:c}})}return i.setValue(s.row,s.col,{result:b,parameters:`${f.v}_${o==null?void 0:o.pattern}`}),Object.assign(n,b),l(n)},priority:u.InterceptCellContentPriority.NUMFMT})),this.disposeWithMe(this._commandService.onCommandExecuted(n=>{if(n.id===u.SetNumfmtMutation.id){const s=n.params;Object.keys(s.values).forEach(l=>{s.values[l].ranges.forEach(S=>{t.Range.foreach(S,(o,f)=>{i.realDeleteValue(o,f)})})})}else if(n.id===u.SetRangeValuesMutation.id){const s=n.params;new t.ObjectMatrix(s.cellValue).forValue((l,m)=>{i.realDeleteValue(l,m)})}})),this.disposeWithMe(this._instanceService.getCurrentTypeOfUnit$(t.UniverInstanceType.UNIVER_SHEET).pipe(N.switchMap(n=>{var s;return(s=n==null?void 0:n.activeSheet$)!=null?s:N.of(null)}),N.skip(1)).subscribe(()=>i.reset()))}setNumfmtLocal(i){this._locale$.next(i)}},r.SheetsNumfmtCellContentController=te([R(0,t.IUniverInstanceService),R(1,t.Inject(u.SheetInterceptorService)),R(2,t.Inject(t.ThemeService)),R(3,t.Inject(t.ICommandService)),R(4,t.Inject(u.INumfmtService)),R(5,t.Inject(t.LocaleService)),R(6,t.IConfigService)],r.SheetsNumfmtCellContentController);const ae="SHEET_NUMFMT_PLUGIN";var re=Object.defineProperty,ie=Object.getOwnPropertyDescriptor,se=(e,a,i)=>a in e?re(e,a,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[a]=i,le=(e,a,i,n)=>{for(var s=n>1?void 0:n?ie(a,i):a,l=e.length-1,m;l>=0;l--)(m=e[l])&&(s=m(s)||s);return s},w=(e,a)=>(i,n)=>a(i,n,e),z=(e,a,i)=>se(e,typeof a!="symbol"?a+"":a,i);r.UniverSheetsNumfmtPlugin=class extends t.Plugin{constructor(a=Z,i,n,s){super(),this._config=a,this._injector=i,this._configService=n,this._commandService=s;const{...l}=t.merge({},Z,this._config);this._configService.setConfig(D,l)}onStarting(){t.registerDependencies(this._injector,[[r.SheetsNumfmtCellContentController]]),t.touchDependencies(this._injector,[[r.SheetsNumfmtCellContentController]])}onRendered(){[x,q,W,K,I].forEach(a=>{this.disposeWithMe(this._commandService.registerCommand(a))})}},z(r.UniverSheetsNumfmtPlugin,"pluginName",ae),z(r.UniverSheetsNumfmtPlugin,"type",t.UniverInstanceType.UNIVER_SHEET),r.UniverSheetsNumfmtPlugin=le([t.DependentOn(u.UniverSheetsPlugin),w(1,t.Inject(t.Injector)),w(2,t.IConfigService),w(3,t.ICommandService)],r.UniverSheetsNumfmtPlugin);const ce=e=>P.find(i=>e.includes(i)),oe=()=>P.map(e=>({label:e,value:e})),ue=e=>H.map(a=>({label:a.label(e),value:a.suffix(e),color:a.color})),me=()=>B.map(e=>({label:e.label,value:e.suffix})),fe=()=>G.map(e=>({label:e.label,value:e.suffix,color:e.color}));r.AddDecimalCommand=x,r.CURRENCYFORMAT=H,r.DATEFMTLISG=B,r.NUMBERFORMAT=G,r.SHEETS_NUMFMT_PLUGIN_CONFIG_KEY=D,r.SetCurrencyCommand=W,r.SetNumfmtCommand=I,r.SetPercentCommand=K,r.SubtractDecimalCommand=q,r.currencySymbols=P,r.getCurrencyFormat=A,r.getCurrencyFormatOptions=ue,r.getCurrencyOptions=oe,r.getCurrencySymbolByLocale=F,r.getCurrencySymbolIconByLocale=j,r.getCurrencyType=ce,r.getDateFormatOptions=me,r.getDecimalFromPattern=U,r.getDecimalString=L,r.getNumberFormatOptions=fe,r.getPatternPreview=k,r.getPatternPreviewIgnoreGeneral=Y,r.getPatternType=Q,r.isPatternHasDecimal=J,r.localeCurrencySymbolMap=E,r.setPatternDecimal=$,Object.defineProperty(r,Symbol.toStringTag,{value:"Module"})}));
|
|
20
|
+
(function(r,t){typeof exports=="object"&&typeof module<"u"?t(exports,require("@univerjs/core"),require("@univerjs/sheets"),require("rxjs"),require("@univerjs/engine-formula")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","@univerjs/sheets","rxjs","@univerjs/engine-formula"],t):(r=typeof globalThis<"u"?globalThis:r||self,t(r.UniverSheetsNumfmt={},r.UniverCore,r.UniverSheets,r.rxjs,r.UniverEngineFormula))})(this,(function(r,t,u,N,X){"use strict";var de=Object.defineProperty;var ge=(r,t,u)=>t in r?de(r,t,{enumerable:!0,configurable:!0,writable:!0,value:u}):r[t]=u;var V=(r,t,u)=>ge(r,typeof t!="symbol"?t+"":t,u);const P=["$","£","¥","¤","֏","؋","৳","฿","៛","₡","₦","₩","₪","₫","€","₭","₮","₱","₲","₴","₸","₹","₺","₼","₽","₾","₿","﷼"],E=new Map([[t.LocaleType.EN_US,"$"],[t.LocaleType.RU_RU,"₽"],[t.LocaleType.VI_VN,"₫"],[t.LocaleType.ZH_CN,"¥"],[t.LocaleType.ZH_TW,"NT$"],[t.LocaleType.FR_FR,"€"],[t.LocaleType.FA_IR,"﷼"],[t.LocaleType.KO_KR,"₩"],[t.LocaleType.ES_ES,"€"],[t.LocaleType.CA_ES,"€"]]);function j(e){switch(e){case t.LocaleType.CA_ES:case t.LocaleType.ES_ES:case t.LocaleType.FR_FR:return{icon:"EuroIcon",symbol:E.get(e)||"€",locale:e};case t.LocaleType.RU_RU:return{icon:"RoubleIcon",symbol:E.get(e)||"₽",locale:e};case t.LocaleType.ZH_CN:return{icon:"RmbIcon",symbol:E.get(e)||"¥",locale:e};case t.LocaleType.EN_US:default:return{icon:"DollarIcon",symbol:"$",locale:t.LocaleType.EN_US}}}function F(e){return E.get(e)||"$"}function A(e,a=2){let i=a;a>127&&(i=127);let n="";return i>0&&(n=`.${"0".repeat(i)}`),`"${F(e)}"#,##0${n}_);[Red]("${F(e)}"#,##0${n})`}const B=[{label:"1930-08-05",suffix:"yyyy-MM-dd"},{label:"1930/08/05",suffix:"yyyy/MM/dd"},{label:"1930年08月05日",suffix:'yyyy"年"MM"月"dd"日"'},{label:"08-05",suffix:"MM-dd"},{label:"8月5日",suffix:'M"月"d"日"'},{label:"13:30:30",suffix:"h:mm:ss"},{label:"13:30",suffix:"h:mm"},{label:"下午01:30",suffix:"A/P hh:mm"},{label:"下午1:30",suffix:"A/P h:mm"},{label:"下午1:30:30",suffix:"A/P h:mm:ss"},{label:"08-05 下午 01:30",suffix:"MM-dd A/P hh:mm"}],G=[{label:"(1,235)",suffix:"#,##0_);(#,##0)"},{label:"(1,235) ",suffix:"#,##0_);[Red](#,##0)",color:"red"},{label:"1,234.56",suffix:"#,##0.00_);#,##0.00"},{label:"1,234.56",suffix:"#,##0.00_);[Red]#,##0.00",color:"red"},{label:"-1,234.56",suffix:"#,##0.00_);-#,##0.00"},{label:"-1,234.56",suffix:"#,##0.00_);[Red]-#,##0.00",color:"red"}],H=[{label:e=>`${e}1,235`,suffix:e=>`"${e}"#,##0.00_);"${e}"#,##0.00`},{label:e=>`${e}1,235`,suffix:e=>`"${e}"#,##0.00_);[Red]"${e}"#,##0.00`,color:"red"},{label:e=>`(${e}1,235)`,suffix:e=>`"${e}"#,##0.00_);("${e}"#,##0.00)`},{label:e=>`(${e}1,235)`,suffix:e=>`"${e}"#,##0.00_);[Red]("${e}"#,##0.00)`,color:"red"},{label:e=>`-${e}1,235`,suffix:e=>`"${e}"#,##0.00_);-"${e}"#,##0.00`},{label:e=>`-${e}1,235`,suffix:e=>`"${e}"#,##0.00_);[Red]-"${e}"#,##0.00`,color:"red"}],U=(e,a=0)=>{var n;return e&&(n=t.numfmt.getFormatInfo(e).maxDecimals)!=null?n:a},L=e=>new Array(Math.min(Math.max(0,Number(e)),30)).fill(0).join(""),$=(e,a)=>e.split(";").map(n=>/\.0?/.test(n)?n.replace(/\.0*/g,`${a>0?".":""}${L(Number(a||0))}`):/0([^0]?)|0$/.test(n)?n.replace(/0([^0]+)|0$/,`0${a>0?".":""}${L(Number(a||0))}$1`):n).join(";"),J=e=>/\.0?/.test(e)||/0([^0]?)|0$/.test(e),I={id:"sheet.command.numfmt.set.numfmt",type:t.CommandType.COMMAND,handler:(e,a)=>{if(!a)return!1;const i=e.get(t.ICommandService),n=e.get(t.IUniverInstanceService),s=e.get(t.IUndoRedoService),l=u.getSheetCommandTarget(n,a);if(!l)return!1;const{unitId:m,subUnitId:S,worksheet:o}=l,f=a.values.filter(c=>!!c.pattern),T=a.values.filter(c=>!c.pattern),M=u.transformCellsToRange(m,S,f),y={unitId:m,subUnitId:S,ranges:T.map(c=>({startColumn:c.col,startRow:c.row,endColumn:c.col,endRow:c.row}))},b=[],p=[];if(f.length){const c=f.reduce((g,d)=>{t.isTextFormat(d.pattern)&&g.setValue(d.row,d.col,{t:t.CellValueType.STRING});const _=o.getCellRaw(d.row,d.col);if(_){const O=u.checkCellValueType(_.v);O!==_.t&&g.setValue(d.row,d.col,{t:O})}return g},new t.ObjectMatrix).getMatrix(),v=new t.ObjectMatrix;new t.ObjectMatrix(c).forValue((g,d)=>{const _=o.getCellRaw(g,d);_?v.setValue(g,d,{t:_.t}):v.setValue(g,d,{t:void 0})}),Object.keys(M.values).forEach(g=>{const d=M.values[g];d.ranges=u.rangeMerge(d.ranges)}),b.push({id:u.SetNumfmtMutation.id,params:M});const h=u.factorySetNumfmtUndoMutation(e,M);p.push(...h)}if(T.length){y.ranges=u.rangeMerge(y.ranges);const c=T.reduce((g,d)=>{const _=o.getCellRaw(d.row,d.col);if(_){const O=u.checkCellValueType(_.v);O!==_.t&&g.setValue(d.row,d.col,{t:O})}return g},new t.ObjectMatrix).getMatrix(),v=new t.ObjectMatrix;new t.ObjectMatrix(c).forValue((g,d)=>{const _=o.getCellRaw(g,d);_?v.setValue(g,d,{t:_.t}):v.setValue(g,d,{t:void 0})}),b.push({id:u.RemoveNumfmtMutation.id,params:y},{id:u.SetRangeValuesMutation.id,params:{unitId:m,subUnitId:S,cellValue:c}});const h=u.factoryRemoveNumfmtUndoMutation(e,y);p.push({id:u.SetRangeValuesMutation.id,params:{unitId:m,subUnitId:S,cellValue:v.getMatrix()}},...h)}const C=t.sequenceExecute(b,i).result;return C&&s.pushUndoRedo({unitID:m,undoMutations:p,redoMutations:b}),C}},x={id:"sheet.command.numfmt.add.decimal.command",type:t.CommandType.COMMAND,handler:async e=>{const a=e.get(t.ICommandService),i=e.get(u.SheetsSelectionsService),n=e.get(u.INumfmtService),s=e.get(t.IUniverInstanceService),l=i.getCurrentSelections();if(!l||!l.length)return!1;const m=u.getSheetCommandTarget(s);if(!m)return!1;const{unitId:S,subUnitId:o}=m;let f=0;l.forEach(b=>{t.Range.foreach(b.range,(p,C)=>{const c=n.getValue(S,o,p,C);if(!c){const h=m.worksheet.getCellRaw(p,C);if(!f&&h&&h.t===t.CellValueType.NUMBER&&h.v){const g=/\.(\d*)$/.exec(String(h.v));if(g){const d=g[1].length;if(!d)return;f=Math.max(f,d)}}return}const v=U(c.pattern);f=v>f?v:f})});const T=f+1,M=$(`0${T>0?".0":""}`,T),y=[];return l.forEach(b=>{t.Range.foreach(b.range,(p,C)=>{const c=n.getValue(S,o,p,C);if(t.isDefaultFormat(c==null?void 0:c.pattern))y.push({row:p,col:C,pattern:M});else{const v=U(c.pattern),h=$(c.pattern,v+1);h!==c.pattern&&y.push({row:p,col:C,pattern:h})}})}),y.length?await a.executeCommand(I.id,{values:y}):!1}},W={id:"sheet.command.numfmt.set.currency",type:t.CommandType.COMMAND,handler:async e=>{const a=e.get(t.ICommandService),i=e.get(u.SheetsSelectionsService),n=e.get(t.LocaleService),s=i.getCurrentSelections();if(!s||!s.length)return!1;const l=[],m=j(n.getCurrentLocale()),S=A(m.locale);return s.forEach(f=>{t.Range.foreach(f.range,(T,M)=>{l.push({row:T,col:M,pattern:S,type:"currency"})})}),await a.executeCommand(I.id,{values:l})}},K={id:"sheet.command.numfmt.set.percent",type:t.CommandType.COMMAND,handler:async e=>{const a=e.get(t.ICommandService),n=e.get(u.SheetsSelectionsService).getCurrentSelections();if(!n||!n.length)return!1;const s=[],l="0%";return n.forEach(S=>{t.Range.foreach(S.range,(o,f)=>{s.push({row:o,col:f,pattern:l,type:"percent"})})}),await a.executeCommand(I.id,{values:s})}},q={id:"sheet.command.numfmt.subtract.decimal.command",type:t.CommandType.COMMAND,handler:async e=>{const a=e.get(t.ICommandService),i=e.get(u.SheetsSelectionsService),n=e.get(u.INumfmtService),s=e.get(t.IUniverInstanceService),l=i.getCurrentSelections();if(!l||!l.length)return!1;const m=u.getSheetCommandTarget(s);if(!m)return!1;const{unitId:S,subUnitId:o}=m;let f=0;l.forEach(p=>{t.Range.foreach(p.range,(C,c)=>{const v=n.getValue(S,o,C,c);if(!v){const g=m.worksheet.getCellRaw(C,c);if(!f&&g&&g.t===t.CellValueType.NUMBER&&g.v){const d=/\.(\d*)$/.exec(String(g.v));if(d){const _=d[1].length;if(!_)return;f=Math.max(f,_)}}return}const h=U(v.pattern);f=h>f?h:f})});const T=f-1,M=$(`0${T>0?".0":"."}`,T),y=[];return l.forEach(p=>{t.Range.foreach(p.range,(C,c)=>{const v=n.getValue(S,o,C,c);if(t.isDefaultFormat(v==null?void 0:v.pattern))y.push({row:C,col:c,pattern:M});else{const h=U(v.pattern);y.push({row:C,col:c,pattern:$(v.pattern,h-1)})}})}),await a.executeCommand(I.id,{values:y})}},D="sheets-numfmt.config",Z={},Q=e=>t.numfmt.getFormatInfo(e).type||"unknown",k=(e,a,i="en")=>{try{const n=t.numfmt.formatColor(e,a),s=n?String(n):void 0,l=t.numfmt.format(e,a,{locale:i,throws:!1});return a<0?{result:l,color:s}:{result:l}}catch(n){console.warn("getPatternPreview error:",e,n)}return{result:String(a)}},Y=(e,a,i)=>e===t.DEFAULT_NUMBER_FORMAT?{result:String(X.stripErrorMargin(a))}:k(e,a,i);var ee=Object.getOwnPropertyDescriptor,te=(e,a,i,n)=>{for(var s=n>1?void 0:n?ee(a,i):a,l=e.length-1,m;l>=0;l--)(m=e[l])&&(s=m(s)||s);return s},R=(e,a)=>(i,n)=>a(i,n,e);const ne={tl:{size:6,color:"#409f11"}};r.SheetsNumfmtCellContentController=class extends t.Disposable{constructor(i,n,s,l,m,S,o){super();V(this,"_locale$",new N.BehaviorSubject("en"));V(this,"locale$",this._locale$.asObservable());this._instanceService=i,this._sheetInterceptorService=n,this._themeService=s,this._commandService=l,this._numfmtService=m,this._localeService=S,this._configService=o,this._initInterceptorCellContent()}get locale(){const i=this._locale$.getValue();if(i)return i;switch(this._localeService.getCurrentLocale()){case t.LocaleType.FR_FR:return"fr";case t.LocaleType.RU_RU:return"ru";case t.LocaleType.VI_VN:return"vi";case t.LocaleType.ZH_CN:return"zh-CN";case t.LocaleType.KO_KR:return"ko";case t.LocaleType.ZH_TW:return"zh-TW";case t.LocaleType.ES_ES:case t.LocaleType.CA_ES:return"es";case t.LocaleType.EN_US:case t.LocaleType.FA_IR:default:return"en"}}_initInterceptorCellContent(){const i=new t.ObjectMatrix;this.disposeWithMe(N.merge(this._locale$,this._localeService.currentLocale$).subscribe(()=>{i.reset()})),this.disposeWithMe(this._sheetInterceptorService.intercept(u.INTERCEPTOR_POINT.CELL_CONTENT,{effect:t.InterceptorEffectEnum.Value|t.InterceptorEffectEnum.Style,handler:(n,s,l)=>{var p,C;if(!n||n.v===void 0||n.v===null||n.t===t.CellValueType.BOOLEAN||n.t===t.CellValueType.FORCE_STRING)return l(n);const m=s.unitId,S=s.subUnitId;let o;if(n!=null&&n.s){const c=s.workbook.getStyles().get(n.s);c!=null&&c.n&&(o=c.n)}if(o||(o=this._numfmtService.getValue(m,S,s.row,s.col)),t.isDefaultFormat(o==null?void 0:o.pattern)||n.t!==t.CellValueType.NUMBER&&u.checkCellValueType(n.v,n.t)!==t.CellValueType.NUMBER)return l(n);const f=n;if((!n||n===s.rawData)&&(n={...s.rawData}),t.isTextFormat(o==null?void 0:o.pattern))return(p=this._configService.getConfig(D))!=null&&p.disableTextFormatMark?(n.t=t.CellValueType.STRING,l(n)):(n.t=t.CellValueType.STRING,n.markers={...n==null?void 0:n.markers,...ne},l(n));let T="";const M=i.getValue(s.row,s.col);if(M&&M.parameters===`${f.v}_${o==null?void 0:o.pattern}`)return l({...n,...M.result});const y=Y(o==null?void 0:o.pattern,Number(f.v),this.locale);if(T=y.result,!T)return l(n);const b={v:T,t:t.CellValueType.NUMBER};if(y.color){const c=(C=this._themeService.getColorFromTheme(`${y.color}.500`))!=null?C:y.color;c&&(b.interceptorStyle={cl:{rgb:c}})}return i.setValue(s.row,s.col,{result:b,parameters:`${f.v}_${o==null?void 0:o.pattern}`}),Object.assign(n,b),l(n)},priority:u.InterceptCellContentPriority.NUMFMT})),this.disposeWithMe(this._commandService.onCommandExecuted(n=>{if(n.id===u.SetNumfmtMutation.id){const s=n.params;Object.keys(s.values).forEach(l=>{s.values[l].ranges.forEach(S=>{t.Range.foreach(S,(o,f)=>{i.realDeleteValue(o,f)})})})}else if(n.id===u.SetRangeValuesMutation.id){const s=n.params;new t.ObjectMatrix(s.cellValue).forValue((l,m)=>{i.realDeleteValue(l,m)})}})),this.disposeWithMe(this._instanceService.getCurrentTypeOfUnit$(t.UniverInstanceType.UNIVER_SHEET).pipe(N.switchMap(n=>{var s;return(s=n==null?void 0:n.activeSheet$)!=null?s:N.of(null)}),N.skip(1)).subscribe(()=>i.reset()))}setNumfmtLocal(i){this._locale$.next(i)}},r.SheetsNumfmtCellContentController=te([R(0,t.IUniverInstanceService),R(1,t.Inject(u.SheetInterceptorService)),R(2,t.Inject(t.ThemeService)),R(3,t.Inject(t.ICommandService)),R(4,t.Inject(u.INumfmtService)),R(5,t.Inject(t.LocaleService)),R(6,t.IConfigService)],r.SheetsNumfmtCellContentController);const ae="SHEET_NUMFMT_PLUGIN";var re=Object.defineProperty,ie=Object.getOwnPropertyDescriptor,se=(e,a,i)=>a in e?re(e,a,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[a]=i,le=(e,a,i,n)=>{for(var s=n>1?void 0:n?ie(a,i):a,l=e.length-1,m;l>=0;l--)(m=e[l])&&(s=m(s)||s);return s},w=(e,a)=>(i,n)=>a(i,n,e),z=(e,a,i)=>se(e,typeof a!="symbol"?a+"":a,i);r.UniverSheetsNumfmtPlugin=class extends t.Plugin{constructor(a=Z,i,n,s){super(),this._config=a,this._injector=i,this._configService=n,this._commandService=s;const{...l}=t.merge({},Z,this._config);this._configService.setConfig(D,l)}onStarting(){t.registerDependencies(this._injector,[[r.SheetsNumfmtCellContentController]]),t.touchDependencies(this._injector,[[r.SheetsNumfmtCellContentController]])}onRendered(){[x,q,W,K,I].forEach(a=>{this.disposeWithMe(this._commandService.registerCommand(a))})}},z(r.UniverSheetsNumfmtPlugin,"pluginName",ae),z(r.UniverSheetsNumfmtPlugin,"type",t.UniverInstanceType.UNIVER_SHEET),r.UniverSheetsNumfmtPlugin=le([t.DependentOn(u.UniverSheetsPlugin),w(1,t.Inject(t.Injector)),w(2,t.IConfigService),w(3,t.ICommandService)],r.UniverSheetsNumfmtPlugin);const ce=e=>P.find(i=>e.includes(i)),oe=()=>P.map(e=>({label:e,value:e})),ue=e=>H.map(a=>({label:a.label(e),value:a.suffix(e),color:a.color})),me=()=>B.map(e=>({label:e.label,value:e.suffix})),fe=()=>G.map(e=>({label:e.label,value:e.suffix,color:e.color}));r.AddDecimalCommand=x,r.CURRENCYFORMAT=H,r.DATEFMTLISG=B,r.NUMBERFORMAT=G,r.SHEETS_NUMFMT_PLUGIN_CONFIG_KEY=D,r.SetCurrencyCommand=W,r.SetNumfmtCommand=I,r.SetPercentCommand=K,r.SubtractDecimalCommand=q,r.currencySymbols=P,r.getCurrencyFormat=A,r.getCurrencyFormatOptions=ue,r.getCurrencyOptions=oe,r.getCurrencySymbolByLocale=F,r.getCurrencySymbolIconByLocale=j,r.getCurrencyType=ce,r.getDateFormatOptions=me,r.getDecimalFromPattern=U,r.getDecimalString=L,r.getNumberFormatOptions=fe,r.getPatternPreview=k,r.getPatternPreviewIgnoreGeneral=Y,r.getPatternType=Q,r.isPatternHasDecimal=J,r.localeCurrencySymbolMap=E,r.setPatternDecimal=$,Object.defineProperty(r,Symbol.toStringTag,{value:"Module"})}));
|
|
21
21
|
|
|
22
22
|
|
|
23
23
|
// @univerjs/sheets-numfmt/facade
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
|
|
26
26
|
|
|
27
27
|
// @univerjs/sheets-data-validation/index
|
|
28
|
-
(function(m,r){typeof exports=="object"&&typeof module<"u"?r(exports,require("@univerjs/core"),require("@univerjs/data-validation"),require("@univerjs/engine-formula"),require("@univerjs/sheets"),require("rxjs"),require("@univerjs/sheets-formula")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","@univerjs/data-validation","@univerjs/engine-formula","@univerjs/sheets","rxjs","@univerjs/sheets-formula"],r):(m=typeof globalThis<"u"?globalThis:m||self,r(m.UniverSheetsDataValidation={},m.UniverCore,m.UniverDataValidation,m.UniverEngineFormula,m.UniverSheets,m.rxjs,m.UniverSheetsFormula))})(this,(function(m,r,p,y,D,A,Z){"use strict";var It=Object.defineProperty;var Ct=(m,r,p)=>r in m?It(m,r,{enumerable:!0,configurable:!0,writable:!0,value:p}):m[r]=p;var S=(m,r,p)=>Ct(m,typeof r!="symbol"?r+"":r,p);var He=Object.getOwnPropertyDescriptor,We=(o,s,e,t)=>{for(var a=t>1?void 0:t?He(s,e):s,i=o.length-1,n;i>=0;i--)(n=o[i])&&(a=n(a)||a);return a},de=(o,s)=>(e,t)=>s(e,t,o);m.DataValidationCacheService=class extends r.Disposable{constructor(e,t,a){super();S(this,"_cacheMatrix",new Map);S(this,"_dirtyRanges$",new A.Subject);S(this,"dirtyRanges$",this._dirtyRanges$.asObservable());this._commandService=e,this._univerInstanceService=t,this._sheetDataValidationModel=a,this._initDirtyRanges(),this._initSheetRemove()}_initDirtyRanges(){this.disposeWithMe(this._commandService.onCommandExecuted(e=>{if(e.id===D.SetRangeValuesMutation.id){const{cellValue:t,unitId:a,subUnitId:i}=e.params;if(t){const n=new r.ObjectMatrix(t).getDataRange();if(n.endRow===-1)return;const d=this._sheetDataValidationModel.getRules(a,i).map(c=>c.ranges).flat().map(c=>r.getIntersectRange(c,n)).filter(Boolean);d.length&&this.markRangeDirty(a,i,d,!0)}}}))}_initSheetRemove(){this.disposeWithMe(this._commandService.onCommandExecuted(e=>{var t;if(e.id===D.RemoveSheetMutation.id){const{unitId:a,subUnitId:i}=e.params;(t=this._cacheMatrix.get(a))==null||t.delete(i)}})),this.disposeWithMe(this._univerInstanceService.unitDisposed$.subscribe(e=>{e.type===r.UniverInstanceType.UNIVER_SHEET&&this._cacheMatrix.delete(e.getUnitId())}))}_ensureCache(e,t){let a=this._cacheMatrix.get(e);a||(a=new Map,this._cacheMatrix.set(e,a));let i=a.get(t);return i||(i=new r.ObjectMatrix,a.set(t,i)),i}ensureCache(e,t){return this._ensureCache(e,t)}addRule(e,t,a){this.markRangeDirty(e,t,a.ranges)}removeRule(e,t,a){this._deleteRange(e,t,a.ranges)}markRangeDirty(e,t,a,i){const n=this._ensureCache(e,t);a.forEach(l=>{r.Range.foreach(l,(u,d)=>{n.getValue(u,d)!==void 0&&n.setValue(u,d,void 0)})}),this._dirtyRanges$.next({unitId:e,subUnitId:t,ranges:a,isSetRange:i})}_deleteRange(e,t,a){const i=this._ensureCache(e,t);a.forEach(n=>{r.Range.foreach(n,(l,u)=>{i.realDeleteValue(l,u)})}),this._dirtyRanges$.next({unitId:e,subUnitId:t,ranges:a})}getValue(e,t,a,i){return this._ensureCache(e,t).getValue(a,i)}},m.DataValidationCacheService=We([de(0,r.Inject(r.ICommandService)),de(1,r.Inject(r.IUniverInstanceService)),de(2,r.Inject(p.DataValidationModel))],m.DataValidationCacheService);function U(o){var s,e;return(e=(s=o==null?void 0:o[0])==null?void 0:s[0])==null?void 0:e.v}function j(o){var s;return(s=o==null?void 0:o[0])==null?void 0:s[0]}function E(o){return!y.ERROR_TYPE_SET.has(o)}function P(o,s){var t;const e=s.getValidatorItem(o);return(t=e==null?void 0:e.offsetFormulaByRange)!=null?t:!1}var $e=Object.getOwnPropertyDescriptor,ke=(o,s,e,t)=>{for(var a=t>1?void 0:t?$e(s,e):s,i=o.length-1,n;i>=0;i--)(n=o[i])&&(a=n(a)||a);return a},H=(o,s)=>(e,t)=>s(e,t,o);m.DataValidationCustomFormulaService=class extends r.Disposable{constructor(e,t,a,i,n){super();S(this,"_ruleFormulaMap",new Map);S(this,"_ruleFormulaMap2",new Map);this._instanceSrv=e,this._registerOtherFormulaService=t,this._dataValidationModel=a,this._dataValidationCacheService=i,this._validatorRegistryService=n,this._initFormulaResultHandler(),this._initDirtyRanges()}dispose(){super.dispose(),this._ruleFormulaMap.clear(),this._ruleFormulaMap2.clear()}_initFormulaResultHandler(){this.disposeWithMe(this._registerOtherFormulaService.formulaResult$.subscribe(e=>{for(const t in e){const a=e[t];if(this._instanceSrv.getUnitType(t)===r.UniverInstanceType.UNIVER_SHEET)for(const n in a){const l=a[n],{ruleFormulaMap:u}=this._ensureMaps(t,n);l.forEach(d=>{var g,f;const c=u.get((g=d.extra)==null?void 0:g.ruleId),h=this._dataValidationModel.getRuleById(t,n,(f=d.extra)==null?void 0:f.ruleId);h&&c&&this._dataValidationCacheService.markRangeDirty(t,n,h.ranges)})}}}))}_ensureMaps(e,t){let a=this._ruleFormulaMap.get(e),i=this._ruleFormulaMap2.get(e);a||(a=new Map,this._ruleFormulaMap.set(e,a)),i||(i=new Map,this._ruleFormulaMap2.set(e,i));let n=a.get(t);n||(n=new Map,a.set(t,n));let l=i.get(t);return l||(l=new Map,i.set(t,l)),{ruleFormulaMap:n,ruleFormulaMap2:l}}_registerFormula(e,t,a,i,n){return this._registerOtherFormulaService.registerFormulaWithRange(e,t,i,n,{ruleId:a})}_handleDirtyRanges(e,t,a){this._dataValidationModel.getRules(e,t).forEach(n=>{const l=n.ranges;r.Rectangle.doAnyRangesIntersect(l,a)&&this.makeRuleDirty(e,t,n.uid)})}_initDirtyRanges(){this.disposeWithMe(this._dataValidationCacheService.dirtyRanges$.subscribe(e=>{e.isSetRange&&this._handleDirtyRanges(e.unitId,e.subUnitId,e.ranges)}))}deleteByRuleId(e,t,a){const{ruleFormulaMap:i,ruleFormulaMap2:n}=this._ensureMaps(e,t),l=this._dataValidationModel.getRuleById(e,t,a),u=i.get(a);if(!l||!u)return;const d=i.get(a);d&&(i.delete(a),this._registerOtherFormulaService.deleteFormula(e,t,[d.formulaId]));const c=n.get(a);c&&(n.delete(a),this._registerOtherFormulaService.deleteFormula(e,t,[c.formulaId]))}_addFormulaByRange(e,t,a,i,n,l){const{ruleFormulaMap:u,ruleFormulaMap2:d}=this._ensureMaps(e,t),c=l[0].startRow,h=l[0].startColumn;if(i&&r.isFormulaString(i)){const g=this._registerFormula(e,t,a,i,l);u.set(a,{formula:i,originCol:h,originRow:c,formulaId:g})}if(n&&r.isFormulaString(n)){const g=this._registerFormula(e,t,a,n,l);d.set(a,{formula:n,originCol:h,originRow:c,formulaId:g})}}addRule(e,t,a){if(P(a.type,this._validatorRegistryService)){const{ranges:i,formula1:n,formula2:l,uid:u}=a;this._addFormulaByRange(e,t,u,n,l,i)}}async getCellFormulaValue(e,t,a,i,n){var R,_;const{ruleFormulaMap:l}=this._ensureMaps(e,t),u=l.get(a);if(!u)return Promise.resolve(void 0);const d=await this._registerOtherFormulaService.getFormulaValue(e,t,u.formulaId),{originRow:c,originCol:h}=u,g=i-c,f=n-h;return j((_=(R=d==null?void 0:d.result)==null?void 0:R[g])==null?void 0:_[f])}async getCellFormula2Value(e,t,a,i,n){var R,_;const{ruleFormulaMap2:l}=this._ensureMaps(e,t),u=l.get(a);if(!u)return Promise.resolve(void 0);const d=await this._registerOtherFormulaService.getFormulaValue(e,t,u.formulaId),{originRow:c,originCol:h}=u,g=i-c,f=n-h;return j((_=(R=d==null?void 0:d.result)==null?void 0:R[g])==null?void 0:_[f])}getCellFormulaValueSync(e,t,a,i,n){var R,_;const{ruleFormulaMap:l}=this._ensureMaps(e,t),u=l.get(a);if(!u)return;const d=this._registerOtherFormulaService.getFormulaValueSync(e,t,u.formulaId),{originRow:c,originCol:h}=u,g=i-c,f=n-h;return j((_=(R=d==null?void 0:d.result)==null?void 0:R[g])==null?void 0:_[f])}getCellFormula2ValueSync(e,t,a,i,n){var R,_;const{ruleFormulaMap2:l}=this._ensureMaps(e,t),u=l.get(a);if(!u)return;const d=this._registerOtherFormulaService.getFormulaValueSync(e,t,u.formulaId),{originRow:c,originCol:h}=u,g=i-c,f=n-h;return j((_=(R=d==null?void 0:d.result)==null?void 0:R[g])==null?void 0:_[f])}getRuleFormulaInfo(e,t,a){const{ruleFormulaMap:i}=this._ensureMaps(e,t);return i.get(a)}makeRuleDirty(e,t,a){var l,u,d,c;const i=(u=(l=this._ruleFormulaMap.get(e))==null?void 0:l.get(t))==null?void 0:u.get(a),n=(c=(d=this._ruleFormulaMap2.get(e))==null?void 0:d.get(t))==null?void 0:c.get(a);i&&this._registerOtherFormulaService.markFormulaDirty(e,t,i.formulaId),n&&this._registerOtherFormulaService.markFormulaDirty(e,t,n.formulaId)}},m.DataValidationCustomFormulaService=ke([H(0,r.IUniverInstanceService),H(1,r.Inject(Z.RegisterOtherFormulaService)),H(2,r.Inject(p.DataValidationModel)),H(3,r.Inject(m.DataValidationCacheService)),H(4,r.Inject(p.DataValidatorRegistryService))],m.DataValidationCustomFormulaService);var xe=Object.getOwnPropertyDescriptor,qe=(o,s,e,t)=>{for(var a=t>1?void 0:t?xe(s,e):s,i=o.length-1,n;i>=0;i--)(n=o[i])&&(a=n(a)||a);return a},W=(o,s)=>(e,t)=>s(e,t,o);m.DataValidationFormulaService=class extends r.Disposable{constructor(e,t,a,i,n){super();S(this,"_formulaRuleMap",new Map);this._instanceService=e,this._registerOtherFormulaService=t,this._dataValidationCacheService=a,this._dataValidationModel=i,this._validatorRegistryService=n,this._initFormulaResultHandler()}_initFormulaResultHandler(){this.disposeWithMe(this._registerOtherFormulaService.formulaResult$.subscribe(e=>{for(const t in e){const a=e[t];if(this._instanceService.getUnitType(t)===r.UniverInstanceType.UNIVER_SHEET)for(const n in a){const l=a[n],u=this._ensureRuleFormulaMap(t,n);l.forEach(d=>{var c,h;if(u.get((c=d.extra)==null?void 0:c.ruleId)){const g=this._dataValidationModel.getRuleById(t,n,(h=d.extra)==null?void 0:h.ruleId);g&&this._dataValidationCacheService.markRangeDirty(t,n,g.ranges)}})}}}))}_ensureRuleFormulaMap(e,t){let a=this._formulaRuleMap.get(e);a||(a=new Map,this._formulaRuleMap.set(e,a));let i=a.get(t);return i||(i=new Map,a.set(t,i)),i}_registerSingleFormula(e,t,a,i){const n=[{startColumn:0,endColumn:0,startRow:0,endRow:0}];return this._registerOtherFormulaService.registerFormulaWithRange(e,t,a,n,{ruleId:i})}addRule(e,t,a){if(!P(a.type,this._validatorRegistryService)&&a.type!==r.DataValidationType.CHECKBOX){const{formula1:i,formula2:n,uid:l}=a,u=r.isFormulaString(i),d=r.isFormulaString(n);if(!u&&!d)return;const c=this._ensureRuleFormulaMap(e,t),h=[void 0,void 0];if(u){const g=this._registerSingleFormula(e,t,i,l);h[0]={id:g,text:i}}if(d){const g=this._registerSingleFormula(e,t,n,l);h[1]={id:g,text:n}}c.set(l,h)}}removeRule(e,t,a){const n=this._ensureRuleFormulaMap(e,t).get(a);if(!n)return;const[l,u]=n,d=[l==null?void 0:l.id,u==null?void 0:u.id].filter(Boolean);d.length&&this._registerOtherFormulaService.deleteFormula(e,t,d)}getRuleFormulaResult(e,t,a){const n=this._ensureRuleFormulaMap(e,t).get(a);if(!n)return Promise.resolve(null);const l=async u=>u&&this._registerOtherFormulaService.getFormulaValue(e,t,u.id);return Promise.all([l(n[0]),l(n[1])])}getRuleFormulaResultSync(e,t,a){const n=this._ensureRuleFormulaMap(e,t).get(a);if(n)return n.map(l=>{if(l)return this._registerOtherFormulaService.getFormulaValueSync(e,t,l.id)})}getRuleFormulaInfo(e,t,a){return this._ensureRuleFormulaMap(e,t).get(a)}},m.DataValidationFormulaService=qe([W(0,r.IUniverInstanceService),W(1,r.Inject(Z.RegisterOtherFormulaService)),W(2,r.Inject(m.DataValidationCacheService)),W(3,r.Inject(p.DataValidationModel)),W(4,r.Inject(p.DataValidatorRegistryService))],m.DataValidationFormulaService);function w(o){return r.getOriginCellValue(o)}function Ve(o){var s;return String((s=w(o))!=null?s:"")}class ce{constructor(s,e,t,a,i=!1){S(this,"_map");S(this,"_tree",new r.RBush);S(this,"_dirty",!0);S(this,"_buildTree",()=>{if(!this._dirty||this._disableTree)return;this._tree.clear();const s=[];this._map.forEach((e,t)=>{e.forEach(a=>{s.push({minX:a.startRow,maxX:a.endRow,minY:a.startColumn,maxY:a.endColumn,ruleId:t})})}),this._tree.load(s),this._dirty=!1});S(this,"_debonceBuildTree",r.debounce(this._buildTree,0));this._unitId=e,this._subUnitId=t,this._univerInstanceService=a,this._disableTree=i,this._map=s,this._buildTree()}get _worksheet(){var s;return(s=this._univerInstanceService.getUnit(this._unitId,r.UniverInstanceType.UNIVER_SHEET))==null?void 0:s.getSheetBySheetId(this._subUnitId)}_addRule(s,e){if(!this._worksheet)return;const t=r.Rectangle.mergeRanges(e.map(a=>r.Range.transformRange(a,this._worksheet)));this._map.forEach((a,i)=>{const n=r.Rectangle.subtractMulti(a,t);n.length===0?this._map.delete(i):this._map.set(i,n)}),this._dirty=!0,this._map.set(s,t),this._debonceBuildTree()}addRule(s){this._addRule(s.uid,s.ranges)}removeRange(s){if(!this._worksheet)return;const e=s.map(t=>r.Range.transformRange(t,this._worksheet));this._map.forEach((t,a)=>{const i=r.Rectangle.subtractMulti(t,e);i.length===0?this._map.delete(a):this._map.set(a,i)}),this._dirty=!0,this._debonceBuildTree()}_removeRule(s){this._map.delete(s),this._dirty=!0,this._debonceBuildTree()}removeRule(s){this._removeRule(s.uid)}updateRange(s,e){this._removeRule(s),this._addRule(s,e)}addRangeRules(s){s.forEach(({id:e,ranges:t})=>{if(!t.length)return;let a=this._map.get(e);a?(this._map.set(e,r.Rectangle.mergeRanges([...a,...t])),a=this._map.get(e)):(a=t,this._map.set(e,a)),this._map.forEach((i,n)=>{if(n===e)return;const l=r.Rectangle.subtractMulti(i,t);l.length===0?this._map.delete(n):this._map.set(n,l)})}),this._dirty=!0,this._debonceBuildTree()}diff(s){const e=[];let t=0;return s.forEach((a,i)=>{var u;const n=(u=this._map.get(a.uid))!=null?u:[],l=a.ranges;n.length!==0&&(n.length!==l.length||n.some((d,c)=>!r.Rectangle.equals(d,l[c])))&&e.push({type:"update",ruleId:a.uid,oldRanges:l,newRanges:r.Rectangle.sort(n),rule:a}),n.length===0&&(e.push({type:"delete",rule:a,index:i-t}),t++)}),e}diffWithAddition(s,e){const t=[];let a=0;return s.forEach((i,n)=>{var d;const l=(d=this._map.get(i.uid))!=null?d:[],u=i.ranges;l.length!==0&&(l.length!==u.length||l.some((c,h)=>!r.Rectangle.equals(c,u[h])))&&t.push({type:"update",ruleId:i.uid,oldRanges:u,newRanges:r.Rectangle.sort(l),rule:i}),l.length===0&&(t.push({type:"delete",rule:i,index:n-a}),a++)}),Array.from(e).forEach(i=>{var l;const n=(l=this._map.get(i.uid))!=null?l:[];t.push({type:"add",rule:{...i,ranges:r.Rectangle.sort(n)}})}),t}clone(){return new ce(new Map(r.Tools.deepClone(Array.from(this._map.entries()))),this._unitId,this._subUnitId,this._univerInstanceService,!0)}getValue(s,e){this._dirty&&this._buildTree();const t=this._tree.search({minX:s,maxX:s,minY:e,maxY:e});return t.length>0?t[0].ruleId:void 0}}var Qe=Object.getOwnPropertyDescriptor,Ge=(o,s,e,t)=>{for(var a=t>1?void 0:t?Qe(s,e):s,i=o.length-1,n;i>=0;i--)(n=o[i])&&(a=n(a)||a);return a},N=(o,s)=>(e,t)=>s(e,t,o);m.SheetDataValidationModel=class extends r.Disposable{constructor(e,t,a,i,n,l,u){super();S(this,"_ruleMatrixMap",new Map);S(this,"_validStatusChange$",new A.Subject);S(this,"_ruleChange$",new A.Subject);S(this,"ruleChange$",this._ruleChange$.asObservable());S(this,"validStatusChange$",this._validStatusChange$.asObservable());this._dataValidationModel=e,this._univerInstanceService=t,this._dataValidatorRegistryService=a,this._dataValidationCacheService=i,this._dataValidationFormulaService=n,this._dataValidationCustomFormulaService=l,this._commandService=u,this._initRuleUpdateListener(),this.disposeWithMe(()=>{this._ruleChange$.complete(),this._validStatusChange$.complete()}),this._initUniverInstanceListener()}_initUniverInstanceListener(){this.disposeWithMe(this._univerInstanceService.unitDisposed$.subscribe(e=>{this._ruleMatrixMap.delete(e.getUnitId())})),this.disposeWithMe(this._commandService.onCommandExecuted(e=>{if(e.id===D.RemoveSheetMutation.id){const{unitId:t,subUnitId:a}=e.params,i=this._ruleMatrixMap.get(t);i&&i.delete(a)}}))}_initRuleUpdateListener(){const e=this._dataValidationModel.getAll();for(const[t,a]of e)for(const[i,n]of a)for(const l of n)this._addRule(t,i,l),this._ruleChange$.next({type:"add",unitId:t,subUnitId:i,rule:l,source:"patched"});this.disposeWithMe(this._dataValidationModel.ruleChange$.subscribe(t=>{switch(t.type){case"add":this._addRule(t.unitId,t.subUnitId,t.rule);break;case"update":this._updateRule(t.unitId,t.subUnitId,t.rule.uid,t.oldRule,t.updatePayload);break;case"remove":this._removeRule(t.unitId,t.subUnitId,t.rule);break}this._ruleChange$.next(t)}))}_ensureRuleMatrix(e,t){let a=this._ruleMatrixMap.get(e);a||(a=new Map,this._ruleMatrixMap.set(e,a));let i=a.get(t);return i||(i=new ce(new Map,e,t,this._univerInstanceService),a.set(t,i)),i}_addRuleSideEffect(e,t,a){this._ensureRuleMatrix(e,t).addRule(a),this._dataValidationCacheService.addRule(e,t,a),this._dataValidationFormulaService.addRule(e,t,a),this._dataValidationCustomFormulaService.addRule(e,t,a)}_addRule(e,t,a){(Array.isArray(a)?a:[a]).forEach(n=>{this._addRuleSideEffect(e,t,n)})}_updateRule(e,t,a,i,n){const l=this._ensureRuleMatrix(e,t),u={...i,...n.payload};n.type===p.UpdateRuleType.RANGE?l.updateRange(a,n.payload):n.type===p.UpdateRuleType.ALL&&l.updateRange(a,n.payload.ranges),this._dataValidationCacheService.removeRule(e,t,i),this._dataValidationCacheService.addRule(e,t,u),this._dataValidationFormulaService.removeRule(e,t,i.uid),this._dataValidationFormulaService.addRule(e,t,u),this._dataValidationCustomFormulaService.deleteByRuleId(e,t,a),this._dataValidationCustomFormulaService.addRule(e,t,u)}_removeRule(e,t,a){this._ensureRuleMatrix(e,t).removeRule(a),this._dataValidationCacheService.removeRule(e,t,a),this._dataValidationCustomFormulaService.deleteByRuleId(e,t,a.uid)}getValidator(e){return this._dataValidatorRegistryService.getValidatorItem(e)}getRuleIdByLocation(e,t,a,i){return this._ensureRuleMatrix(e,t).getValue(a,i)}getRuleByLocation(e,t,a,i){const n=this.getRuleIdByLocation(e,t,a,i);if(n)return this._dataValidationModel.getRuleById(e,t,n)}validator(e,t,a){const{col:i,row:n,unitId:l,subUnitId:u,worksheet:d}=t,c=(_,V)=>{a&&a(_,V),V&&this._validStatusChange$.next({unitId:l,subUnitId:u,ruleId:e.uid,status:_,row:n,col:i})},h=d.getCellValueOnly(n,i),g=this.getValidator(e.type),f=d.getCellRaw(n,i),R=w(f);if(g){const _=this._dataValidationCacheService.ensureCache(l,u),V=_.getValue(n,i);return V==null?(_.setValue(n,i,r.DataValidationStatus.VALIDATING),g.validator({value:R,unitId:l,subUnitId:u,row:n,column:i,worksheet:t.worksheet,workbook:t.workbook,interceptValue:w(h),t:f==null?void 0:f.t},e).then(v=>{const M=v?r.DataValidationStatus.VALID:r.DataValidationStatus.INVALID,T=_.getValue(n,i);M===r.DataValidationStatus.VALID?_.realDeleteValue(n,i):_.setValue(n,i,M),c(M,V!==T)}),r.DataValidationStatus.VALIDATING):(c(V!=null?V:r.DataValidationStatus.VALID,!1),V!=null?V:r.DataValidationStatus.VALID)}else return c(r.DataValidationStatus.VALID,!1),r.DataValidationStatus.VALID}getRuleObjectMatrix(e,t){return this._ensureRuleMatrix(e,t)}getRuleById(e,t,a){return this._dataValidationModel.getRuleById(e,t,a)}getRuleIndex(e,t,a){return this._dataValidationModel.getRuleIndex(e,t,a)}getRules(e,t){return[...this._dataValidationModel.getRules(e,t)]}getUnitRules(e){return this._dataValidationModel.getUnitRules(e)}deleteUnitRules(e){return this._dataValidationModel.deleteUnitRules(e)}getSubUnitIds(e){return this._dataValidationModel.getSubUnitIds(e)}getAll(){return this._dataValidationModel.getAll()}},m.SheetDataValidationModel=Ge([N(0,r.Inject(p.DataValidationModel)),N(1,r.IUniverInstanceService),N(2,r.Inject(p.DataValidatorRegistryService)),N(3,r.Inject(m.DataValidationCacheService)),N(4,r.Inject(m.DataValidationFormulaService)),N(5,r.Inject(m.DataValidationCustomFormulaService)),N(6,r.ICommandService)],m.SheetDataValidationModel);const $=1,k=0;function De(o,s){return r.Tools.isBlank(o)?s.t("dataValidation.validFail.value"):r.isFormulaString(o)?s.t("dataValidation.validFail.primitive"):""}const x=o=>r.Tools.isDefine(o)&&String(o).toLowerCase()==="true"?"1":String(o).toLowerCase()==="false"?"0":o;class Me extends p.BaseDataValidator{constructor(){super(...arguments);S(this,"id",r.DataValidationType.CHECKBOX);S(this,"title","dataValidation.checkbox.title");S(this,"operators",[]);S(this,"scopes",["sheet"]);S(this,"order",41);S(this,"offsetFormulaByRange",!1);S(this,"_formulaService",this.injector.get(m.DataValidationFormulaService));S(this,"skipDefaultFontRender",(e,t,a)=>{const{unitId:i,subUnitId:n}=a,{formula1:l,formula2:u}=this.parseFormulaSync(e,i,n),d=`${t!=null?t:""}`;return!d||d===`${l}`||d===`${u}`})}validatorFormula(e,t,a){const{formula1:i,formula2:n}=e,l=i===n;if(r.Tools.isBlank(i)&&r.Tools.isBlank(n))return{success:!0};if(l)return{success:!1,formula1:this.localeService.t("dataValidation.validFail.checkboxEqual"),formula2:this.localeService.t("dataValidation.validFail.checkboxEqual")};const u=De(i,this.localeService),d=De(n,this.localeService);return{success:!u&&!d,formula1:u,formula2:d}}async parseFormula(e,t,a){var h,g,f,R;const{formula1:i=$,formula2:n=k}=e,l=await this._formulaService.getRuleFormulaResult(t,a,e.uid),u=r.isFormulaString(i)?U((g=(h=l==null?void 0:l[0])==null?void 0:h.result)==null?void 0:g[0][0]):i,d=r.isFormulaString(n)?U((R=(f=l==null?void 0:l[1])==null?void 0:f.result)==null?void 0:R[0][0]):n,c=E(String(u))&&E(String(d));return{formula1:x(u),formula2:x(d),originFormula1:u,originFormula2:d,isFormulaValid:c}}getExtraStyle(e,t){return{tb:r.WrapStrategy.CLIP}}parseFormulaSync(e,t,a){var h,g,f,R;const{formula1:i=$,formula2:n=k}=e,l=this._formulaService.getRuleFormulaResultSync(t,a,e.uid),u=r.isFormulaString(i)?U((g=(h=l==null?void 0:l[0])==null?void 0:h.result)==null?void 0:g[0][0]):i,d=r.isFormulaString(n)?U((R=(f=l==null?void 0:l[1])==null?void 0:f.result)==null?void 0:R[0][0]):n,c=E(String(u))&&E(String(d));return{formula1:x(u),formula2:x(d),originFormula1:u,originFormula2:d,isFormulaValid:c}}async isValidType(e,t,a){const{value:i,unitId:n,subUnitId:l}=e,{formula1:u,formula2:d,originFormula1:c,originFormula2:h}=await this.parseFormula(a,n,l);return!r.Tools.isDefine(u)||!r.Tools.isDefine(d)?!0:r.Tools.isDefine(i)&&(String(i)===String(u)||String(i)===String(d)||String(i)===String(c!=null?c:"")||String(i)===String(h!=null?h:""))}generateRuleErrorMessage(e){return this.localeService.t("dataValidation.checkbox.error")}generateRuleName(e){return this.titleStr}}const Ye={[r.DataValidationOperator.BETWEEN]:"dataValidation.date.operators.between",[r.DataValidationOperator.EQUAL]:"dataValidation.date.operators.equal",[r.DataValidationOperator.GREATER_THAN]:"dataValidation.date.operators.greaterThan",[r.DataValidationOperator.GREATER_THAN_OR_EQUAL]:"dataValidation.date.operators.greaterThanOrEqual",[r.DataValidationOperator.LESS_THAN]:"dataValidation.date.operators.lessThan",[r.DataValidationOperator.LESS_THAN_OR_EQUAL]:"dataValidation.date.operators.lessThanOrEqual",[r.DataValidationOperator.NOT_BETWEEN]:"dataValidation.date.operators.notBetween",[r.DataValidationOperator.NOT_EQUAL]:"dataValidation.date.operators.notEqual"};r.DataValidationOperator.BETWEEN+"",r.DataValidationOperator.EQUAL+"",r.DataValidationOperator.GREATER_THAN+"",r.DataValidationOperator.GREATER_THAN_OR_EQUAL+"",r.DataValidationOperator.LESS_THAN+"",r.DataValidationOperator.LESS_THAN_OR_EQUAL+"",r.DataValidationOperator.NOT_BETWEEN+"",r.DataValidationOperator.NOT_EQUAL+"";const Ee={[r.DataValidationOperator.BETWEEN]:"dataValidation.date.ruleName.between",[r.DataValidationOperator.EQUAL]:"dataValidation.date.ruleName.equal",[r.DataValidationOperator.GREATER_THAN]:"dataValidation.date.ruleName.greaterThan",[r.DataValidationOperator.GREATER_THAN_OR_EQUAL]:"dataValidation.date.ruleName.greaterThanOrEqual",[r.DataValidationOperator.LESS_THAN]:"dataValidation.date.ruleName.lessThan",[r.DataValidationOperator.LESS_THAN_OR_EQUAL]:"dataValidation.date.ruleName.lessThanOrEqual",[r.DataValidationOperator.NOT_BETWEEN]:"dataValidation.date.ruleName.notBetween",[r.DataValidationOperator.NOT_EQUAL]:"dataValidation.date.ruleName.notEqual",NONE:"dataValidation.date.ruleName.legal"},Xe={[r.DataValidationOperator.BETWEEN]:"dataValidation.date.errorMsg.between",[r.DataValidationOperator.EQUAL]:"dataValidation.date.errorMsg.equal",[r.DataValidationOperator.GREATER_THAN]:"dataValidation.date.errorMsg.greaterThan",[r.DataValidationOperator.GREATER_THAN_OR_EQUAL]:"dataValidation.date.errorMsg.greaterThanOrEqual",[r.DataValidationOperator.LESS_THAN]:"dataValidation.date.errorMsg.lessThan",[r.DataValidationOperator.LESS_THAN_OR_EQUAL]:"dataValidation.date.errorMsg.lessThanOrEqual",[r.DataValidationOperator.NOT_BETWEEN]:"dataValidation.date.errorMsg.notBetween",[r.DataValidationOperator.NOT_EQUAL]:"dataValidation.date.errorMsg.notEqual",NONE:"dataValidation.date.errorMsg.legal"},J=[r.DataValidationOperator.BETWEEN,r.DataValidationOperator.NOT_BETWEEN],q="{FORMULA1}",Q="{FORMULA2}";function Ke(o){return o.filter(Boolean).join(",")}function G(o){return o.split(",").filter(Boolean)}function ze(o){const s=w(o);return s==null?"":s.toString()}function Y(o,s,e){const{formula1:t,formula2:a}=s,i=s.ranges[0].startRow,n=s.ranges[0].startColumn,l=e.row-i,u=e.col-n,d=r.isFormulaString(t)?o.moveFormulaRefOffset(t,u,l,!0):t,c=r.isFormulaString(a)?o.moveFormulaRefOffset(a,u,l,!0):a;return{transformedFormula1:d,transformedFormula2:c}}const me=o=>{var e,t;if(o==null||typeof o=="boolean")return;if(typeof o=="number"||!Number.isNaN(+o))return+o;const s=(e=r.numfmt.parseDate(o))==null?void 0:e.v;return r.Tools.isDefine(s)?s:(t=r.numfmt.parseDate(r.dayjs(o).format("YYYY-MM-DD HH:mm:ss")))==null?void 0:t.v};class ye extends p.BaseDataValidator{constructor(){super(...arguments);S(this,"id",r.DataValidationType.DATE);S(this,"title","dataValidation.date.title");S(this,"order",40);S(this,"operators",[r.DataValidationOperator.BETWEEN,r.DataValidationOperator.EQUAL,r.DataValidationOperator.GREATER_THAN,r.DataValidationOperator.GREATER_THAN_OR_EQUAL,r.DataValidationOperator.LESS_THAN,r.DataValidationOperator.LESS_THAN_OR_EQUAL,r.DataValidationOperator.NOT_BETWEEN,r.DataValidationOperator.NOT_EQUAL]);S(this,"scopes",["sheet"]);S(this,"_customFormulaService",this.injector.get(m.DataValidationCustomFormulaService));S(this,"_lexerTreeBuilder",this.injector.get(y.LexerTreeBuilder))}async parseFormula(e,t,a,i,n){const l=await this._customFormulaService.getCellFormulaValue(t,a,e.uid,i,n),u=await this._customFormulaService.getCellFormula2Value(t,a,e.uid,i,n),{formula1:d,formula2:c}=e,h=E(String(l==null?void 0:l.v))&&E(String(u==null?void 0:u.v));return{formula1:me(r.isFormulaString(d)?l==null?void 0:l.v:d),formula2:me(r.isFormulaString(c)?u==null?void 0:u.v:c),isFormulaValid:h}}async isValidType(e){const{interceptValue:t,value:a}=e;return typeof a=="number"&&typeof t=="string"||typeof t=="string"?!!r.numfmt.parseDate(t):!1}_validatorSingleFormula(e){return!r.Tools.isBlank(e)&&(r.isFormulaString(e)||!Number.isNaN(+e)||!!(e&&r.numfmt.parseDate(e)))}validatorFormula(e,t,a){const i=e.operator;if(!i)return{success:!0};const n=this._validatorSingleFormula(e.formula1),l=this.localeService.t("dataValidation.validFail.date");if(J.includes(i)){const d=this._validatorSingleFormula(e.formula2);return{success:n&&d,formula1:n?void 0:l,formula2:d?void 0:l}}return{success:n,formula1:n?void 0:l}}normalizeFormula(e,t,a){const{formula1:i,formula2:n,bizInfo:l}=e,u=d=>{var h;if(!d)return d;let c;if(!Number.isNaN(+d))c=r.numfmt.dateFromSerial(+d);else{const g=(h=r.numfmt.parseDate(d))==null?void 0:h.v;if(g==null)return"";c=r.numfmt.dateFromSerial(g)}return r.dayjs(`${c[0]}/${c[1]}/${c[2]} ${c[3]}:${c[4]}:${c[5]}`).format(l!=null&&l.showTime?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD")};return{formula1:r.isFormulaString(i)?i:u(`${i}`),formula2:r.isFormulaString(n)?n:u(`${n}`)}}transform(e,t,a){const{value:i}=e;return{...e,value:me(i)}}get operatorNames(){return this.operators.map(e=>this.localeService.t(Ye[e]))}generateRuleName(e){var a,i;if(!e.operator)return this.localeService.t(Ee.NONE);const t=this.localeService.t(Ee[e.operator]).replace(q,(a=e.formula1)!=null?a:"").replace(Q,(i=e.formula2)!=null?i:"");return`${this.titleStr} ${t}`}generateRuleErrorMessage(e,t){if(!e.operator)return this.titleStr;const{transformedFormula1:a,transformedFormula2:i}=Y(this._lexerTreeBuilder,e,t);return`${this.localeService.t(Xe[e.operator]).replace(q,a!=null?a:"").replace(Q,i!=null?i:"")}`}}r.DataValidationOperator.BETWEEN+"",r.DataValidationOperator.EQUAL+"",r.DataValidationOperator.GREATER_THAN+"",r.DataValidationOperator.GREATER_THAN_OR_EQUAL+"",r.DataValidationOperator.LESS_THAN+"",r.DataValidationOperator.LESS_THAN_OR_EQUAL+"",r.DataValidationOperator.NOT_BETWEEN+"",r.DataValidationOperator.NOT_EQUAL+"",r.DataValidationOperator.BETWEEN+"",r.DataValidationOperator.EQUAL+"",r.DataValidationOperator.GREATER_THAN+"",r.DataValidationOperator.GREATER_THAN_OR_EQUAL+"",r.DataValidationOperator.LESS_THAN+"",r.DataValidationOperator.LESS_THAN_OR_EQUAL+"",r.DataValidationOperator.NOT_BETWEEN+"",r.DataValidationOperator.NOT_EQUAL+"";const ee={[r.DataValidationOperator.BETWEEN]:"dataValidation.errorMsg.between",[r.DataValidationOperator.EQUAL]:"dataValidation.errorMsg.equal",[r.DataValidationOperator.GREATER_THAN]:"dataValidation.errorMsg.greaterThan",[r.DataValidationOperator.GREATER_THAN_OR_EQUAL]:"dataValidation.errorMsg.greaterThanOrEqual",[r.DataValidationOperator.LESS_THAN]:"dataValidation.errorMsg.lessThan",[r.DataValidationOperator.LESS_THAN_OR_EQUAL]:"dataValidation.errorMsg.lessThanOrEqual",[r.DataValidationOperator.NOT_BETWEEN]:"dataValidation.errorMsg.notBetween",[r.DataValidationOperator.NOT_EQUAL]:"dataValidation.errorMsg.notEqual",NONE:"dataValidation.errorMsg.legal"};function X(o){return+o}class Ze extends p.BaseDataValidator{constructor(){super(...arguments);S(this,"_customFormulaService",this.injector.get(m.DataValidationCustomFormulaService));S(this,"id",r.DataValidationType.DECIMAL);S(this,"_lexerTreeBuilder",this.injector.get(y.LexerTreeBuilder));S(this,"title","dataValidation.decimal.title");S(this,"order",20);S(this,"operators",[r.DataValidationOperator.BETWEEN,r.DataValidationOperator.EQUAL,r.DataValidationOperator.GREATER_THAN,r.DataValidationOperator.GREATER_THAN_OR_EQUAL,r.DataValidationOperator.LESS_THAN,r.DataValidationOperator.LESS_THAN_OR_EQUAL,r.DataValidationOperator.NOT_BETWEEN,r.DataValidationOperator.NOT_EQUAL]);S(this,"scopes",["sheet"])}_isFormulaOrNumber(e){return!r.Tools.isBlank(e)&&(r.isFormulaString(e)||!Number.isNaN(+e))}async isValidType(e,t,a){const{value:i}=e;return!Number.isNaN(X(i))}transform(e,t,a){const{value:i}=e;return{...e,value:X(i)}}_parseNumber(e){return e==null?Number.NaN:+e}async parseFormula(e,t,a,i,n){const l=await this._customFormulaService.getCellFormulaValue(t,a,e.uid,i,n),u=await this._customFormulaService.getCellFormula2Value(t,a,e.uid,i,n),{formula1:d,formula2:c}=e,h=E(String(l==null?void 0:l.v))&&E(String(u==null?void 0:u.v));return{formula1:this._parseNumber(r.isFormulaString(d)?l==null?void 0:l.v:d),formula2:this._parseNumber(r.isFormulaString(c)?u==null?void 0:u.v:c),isFormulaValid:h}}validatorFormula(e,t,a){const i=e.operator;if(!i)return{success:!0};const n=r.Tools.isDefine(e.formula1)&&this._isFormulaOrNumber(e.formula1),l=r.Tools.isDefine(e.formula2)&&this._isFormulaOrNumber(e.formula2),u=J.includes(i),d=this.localeService.t("dataValidation.validFail.number");return u?{success:n&&l,formula1:n?void 0:d,formula2:l?void 0:d}:{success:n,formula1:n?"":d}}generateRuleErrorMessage(e,t){if(!e.operator)return this.localeService.t(ee.NONE).replace("{TYPE}",this.titleStr);const{transformedFormula1:a,transformedFormula2:i}=Y(this._lexerTreeBuilder,e,t);return`${this.localeService.t(ee[e.operator]).replace(q,a!=null?a:"").replace(Q,i!=null?i:"")}`}}function he(o){if(!o)return[];const s=new Set;return o.forEach(e=>{e.forEach(t=>{var i,n;const a=w(t);if(a!=null){if(typeof a!="string"&&typeof(t==null?void 0:t.s)=="object"&&((n=(i=t.s)==null?void 0:i.n)!=null&&n.pattern)){s.add(r.numfmt.format(t.s.n.pattern,a,{throws:!1}));return}E(a.toString())&&s.add(a.toString())}})}),[...s]}const Je=["if","indirect","choose","offset"];function et(o,s){if(!r.isFormulaString(o)||y.isReferenceString(o.slice(1)))return!0;const t=s.sequenceNodesBuilder(o);return t&&t.some(a=>typeof a=="object"&&a.nodeType===y.sequenceNodeType.FUNCTION&&Je.indexOf(a.token.toLowerCase())>-1)}function tt(o,s){const{formula1:e="",ranges:t}=o;if(y.isReferenceString(e.slice(1))){const i=y.deserializeRangeWithSheet(e.slice(1));if((!i.sheetName||i.sheetName===s)&&t.some(n=>r.Rectangle.intersects(n,i.range)))return!0}return!1}class ge extends p.BaseDataValidator{constructor(){super(...arguments);S(this,"formulaService",this.injector.get(m.DataValidationFormulaService));S(this,"_lexer",this.injector.get(y.LexerTreeBuilder));S(this,"_univerInstanceService",this.injector.get(r.IUniverInstanceService));S(this,"order",50);S(this,"offsetFormulaByRange",!1);S(this,"id",r.DataValidationType.LIST);S(this,"title","dataValidation.list.title");S(this,"operators",[]);S(this,"scopes",["sheet"]);S(this,"skipDefaultFontRender",e=>e.renderMode!==r.DataValidationRenderMode.TEXT)}validatorFormula(e,t,a){var d,c,h;const i=!r.Tools.isBlank(e.formula1),n=et((d=e.formula1)!=null?d:"",this._lexer),l=(h=(c=this._univerInstanceService.getUnit(t,r.UniverInstanceType.UNIVER_SHEET))==null?void 0:c.getSheetBySheetId(a))==null?void 0:h.getName(),u=tt(e,l!=null?l:"");return{success:!!(i&&n&&!u),formula1:i?n?u?this.localeService.t("dataValidation.validFail.listIntersects"):void 0:this.localeService.t("dataValidation.validFail.listInvalid"):this.localeService.t("dataValidation.validFail.list")}}getExtraStyle(e,t,{style:a}){var n;const i=(n=a.tb!==r.WrapStrategy.OVERFLOW?a.tb:r.WrapStrategy.CLIP)!=null?n:r.WrapStrategy.WRAP;if(e.type===r.DataValidationType.LIST&&(e.renderMode===r.DataValidationRenderMode.ARROW||e.renderMode===r.DataValidationRenderMode.TEXT)){const l=this.getListWithColorMap(e),u=`${t!=null?t:""}`,d=l[u];if(d)return{bg:{rgb:d},tb:i}}return{tb:i}}parseCellValue(e){const t=e.toString();return G(t)}async parseFormula(e,t,a){var u,d;const i=await this.formulaService.getRuleFormulaResult(t,a,e.uid),n=U((d=(u=i==null?void 0:i[0])==null?void 0:u.result)==null?void 0:d[0][0]);return{formula1:void 0,formula2:void 0,isFormulaValid:E(String(n))}}async isValidType(e,t,a){var g,f;const{value:i,unitId:n,subUnitId:l}=e,{formula1:u=""}=a,d=await this.formulaService.getRuleFormulaResult(n,l,a.uid),c=r.isFormulaString(u)?he((f=(g=d==null?void 0:d[0])==null?void 0:g.result)==null?void 0:f[0][0]):G(u);return this.parseCellValue(i).every(R=>c.includes(R))}generateRuleName(){return this.localeService.t("dataValidation.list.name")}generateRuleErrorMessage(){return this.localeService.t("dataValidation.list.error")}getList(e,t,a){var g,f,R,_;const{formula1:i=""}=e,n=this.injector.get(r.IUniverInstanceService),l=(g=t?n.getUniverSheetInstance(t):void 0)!=null?g:n.getCurrentUnitForType(r.UniverInstanceType.UNIVER_SHEET);if(!l)return[];const u=(f=a?l.getSheetBySheetId(a):void 0)!=null?f:l.getActiveSheet();if(!u)return[];const d=l.getUnitId(),c=u.getSheetId(),h=this.formulaService.getRuleFormulaResultSync(d,c,e.uid);return r.isFormulaString(i)?he((_=(R=h==null?void 0:h[0])==null?void 0:R.result)==null?void 0:_[0][0]):G(i)}async getListAsync(e,t,a){var g,f,R,_;const{formula1:i=""}=e,n=this.injector.get(r.IUniverInstanceService),l=(g=t?n.getUniverSheetInstance(t):void 0)!=null?g:n.getCurrentUnitForType(r.UniverInstanceType.UNIVER_SHEET);if(!l)return[];const u=(f=a?l.getSheetBySheetId(a):void 0)!=null?f:l.getActiveSheet();if(!u)return[];const d=l.getUnitId(),c=u.getSheetId(),h=await this.formulaService.getRuleFormulaResult(d,c,e.uid);return r.isFormulaString(i)?he((_=(R=h==null?void 0:h[0])==null?void 0:R.result)==null?void 0:_[0][0]):G(i)}getListWithColor(e,t,a){const i=this.getList(e,t,a),n=(e.formula2||"").split(",");return i.map((l,u)=>({label:l,color:n[u]}))}getListWithColorMap(e,t,a){const i=this.getListWithColor(e,t,a),n={};return i.forEach(l=>{l.color&&(n[l.label]=l.color)}),n}}class at extends p.BaseDataValidator{constructor(){super(...arguments);S(this,"id",r.DataValidationType.TEXT_LENGTH);S(this,"title","dataValidation.textLength.title");S(this,"_lexerTreeBuilder",this.injector.get(y.LexerTreeBuilder));S(this,"order",30);S(this,"operators",[r.DataValidationOperator.BETWEEN,r.DataValidationOperator.EQUAL,r.DataValidationOperator.GREATER_THAN,r.DataValidationOperator.GREATER_THAN_OR_EQUAL,r.DataValidationOperator.LESS_THAN,r.DataValidationOperator.LESS_THAN_OR_EQUAL,r.DataValidationOperator.NOT_BETWEEN,r.DataValidationOperator.NOT_EQUAL]);S(this,"scopes",["sheet"]);S(this,"_customFormulaService",this.injector.get(m.DataValidationCustomFormulaService))}_isFormulaOrInt(e){return!r.Tools.isBlank(e)&&(r.isFormulaString(e)||!Number.isNaN(+e)&&Number.isInteger(+e))}validatorFormula(e,t,a){const i=e.operator;if(!i)return{success:!1};const n=r.Tools.isDefine(e.formula1)&&this._isFormulaOrInt(e.formula1),l=r.Tools.isDefine(e.formula2)&&this._isFormulaOrInt(e.formula2),u=J.includes(i),d=this.localeService.t("dataValidation.validFail.number");return u?{success:n&&l,formula1:n?void 0:d,formula2:l?void 0:d}:{success:n,formula1:d}}_parseNumber(e){return e==null?Number.NaN:+e}async parseFormula(e,t,a,i,n){const l=await this._customFormulaService.getCellFormulaValue(t,a,e.uid,i,n),u=await this._customFormulaService.getCellFormula2Value(t,a,e.uid,i,n),{formula1:d,formula2:c}=e,h=E(String(l==null?void 0:l.v))&&E(String(u==null?void 0:u.v));return{formula1:this._parseNumber(r.isFormulaString(d)?l==null?void 0:l.v:d),formula2:this._parseNumber(r.isFormulaString(c)?u==null?void 0:u.v:c),isFormulaValid:h}}transform(e,t,a){return{...e,value:e.value.toString().length}}async isValidType(e,t,a){const{value:i}=e;return typeof i=="string"||typeof i=="number"}generateRuleErrorMessage(e,t){if(!e.operator)return this.titleStr;const{transformedFormula1:a,transformedFormula2:i}=Y(this._lexerTreeBuilder,e,t);return`${this.localeService.t(p.TextLengthErrorTitleMap[e.operator]).replace(q,a!=null?a:"").replace(Q,i!=null?i:"")}`}}function Te(o){var e,t;return o?o.p?!((t=(e=o.p.body)==null?void 0:e.dataStream)!=null?t:"").slice(0,-2).trim():r.Tools.isBlank(o.v):!0}function K(o,s,e,t,a="command",i=!0){const n=t.get(y.LexerTreeBuilder),l=t.get(p.DataValidatorRegistryService),u=[],d=[],c=t.get(m.SheetDataValidationModel),h=t.get(r.IUniverInstanceService),g=D.getSheetCommandTarget(h,{unitId:o,subUnitId:s});if(!g)return{redoMutations:u,undoMutations:d};const{worksheet:f}=g,R=new r.ObjectMatrix;let _=!1;function V(v,M){i&&v.forEach(T=>{r.Range.foreach(T,(O,I)=>{const F=f.getCellRaw(O,I),B=Ve(F);(Te(F)||B===M)&&!(F!=null&&F.p)&&(_=!0,R.setValue(O,I,{v:M,p:null}))})})}if(e.forEach(v=>{switch(v.type){case"delete":u.push({id:p.RemoveDataValidationMutation.id,params:{unitId:o,subUnitId:s,ruleId:v.rule.uid,source:a}}),d.unshift({id:p.AddDataValidationMutation.id,params:{unitId:o,subUnitId:s,rule:v.rule,index:v.index,source:a}});break;case"update":{if(P(v.rule.type,l)){const T=v.oldRanges[0].startRow,O=v.oldRanges[0].startColumn,I=v.newRanges[0].startRow,F=v.newRanges[0].startColumn,B=I-T,oe=F-O,se=r.isFormulaString(v.rule.formula1)?n.moveFormulaRefOffset(v.rule.formula1,oe,B):v.rule.formula1,le=r.isFormulaString(v.rule.formula2)?n.moveFormulaRefOffset(v.rule.formula2,oe,B):v.rule.formula2;se!==v.rule.formula1||le!==v.rule.formula2||!r.isRangesEqual(v.newRanges,v.oldRanges)?(u.push({id:p.UpdateDataValidationMutation.id,params:{unitId:o,subUnitId:s,ruleId:v.ruleId,payload:{type:p.UpdateRuleType.ALL,payload:{formula1:se,formula2:le,ranges:v.newRanges}}}}),d.unshift({id:p.UpdateDataValidationMutation.id,params:{unitId:o,subUnitId:s,ruleId:v.ruleId,payload:{type:p.UpdateRuleType.ALL,payload:{formula1:v.rule.formula1,formula2:v.rule.formula2,ranges:v.oldRanges}}}})):(u.push({id:p.UpdateDataValidationMutation.id,params:{unitId:o,subUnitId:s,ruleId:v.ruleId,payload:{type:p.UpdateRuleType.RANGE,payload:v.newRanges},source:a}}),d.unshift({id:p.UpdateDataValidationMutation.id,params:{unitId:o,subUnitId:s,ruleId:v.ruleId,payload:{type:p.UpdateRuleType.RANGE,payload:v.oldRanges},source:a}}))}else u.push({id:p.UpdateDataValidationMutation.id,params:{unitId:o,subUnitId:s,ruleId:v.ruleId,payload:{type:p.UpdateRuleType.RANGE,payload:v.newRanges},source:a}}),d.unshift({id:p.UpdateDataValidationMutation.id,params:{unitId:o,subUnitId:s,ruleId:v.ruleId,payload:{type:p.UpdateRuleType.RANGE,payload:v.oldRanges},source:a}});const M=c.getRuleById(o,s,v.ruleId);if(M&&M.type===r.DataValidationType.CHECKBOX){const O=c.getValidator(r.DataValidationType.CHECKBOX).parseFormulaSync(M,o,s);V(v.newRanges,O.formula2)}break}case"add":{if(u.push({id:p.AddDataValidationMutation.id,params:{unitId:o,subUnitId:s,rule:v.rule,source:a}}),d.unshift({id:p.RemoveDataValidationMutation.id,params:{unitId:o,subUnitId:s,ruleId:v.rule.uid,source:a}}),v.rule.type===r.DataValidationType.CHECKBOX){const T=c.getValidator(r.DataValidationType.CHECKBOX).parseFormulaSync(v.rule,o,s);V(v.rule.ranges,T.originFormula2)}break}}}),_){const v={id:D.SetRangeValuesMutation.id,params:{unitId:o,subUnitId:s,cellValue:R.getData()}},M={id:D.SetRangeValuesMutation.id,params:D.SetRangeValuesUndoMutationFactory(t,v.params)};u.push(v),d.push(M)}return{redoMutations:u,undoMutations:d}}const Oe={type:r.CommandType.COMMAND,id:"sheet.command.updateDataValidationRuleRange",handler(o,s){if(!s)return!1;const{unitId:e,subUnitId:t,ranges:a,ruleId:i}=s,n=o.get(m.SheetDataValidationModel),l=o.get(r.ICommandService),u=o.get(r.IUndoRedoService);if(!n.getRuleById(e,t,i))return!1;const c=n.getRuleObjectMatrix(e,t).clone();c.updateRange(i,a);const h=c.diff(n.getRules(e,t)),{redoMutations:g,undoMutations:f}=K(e,t,h,o);return u.pushUndoRedo({undoMutations:f,redoMutations:g,unitID:e}),r.sequenceExecute(g,l),!0}},Fe={type:r.CommandType.COMMAND,id:"sheet.command.addDataValidation",handler(o,s){if(!s)return!1;const{unitId:e,subUnitId:t,rule:a}=s,i=o.get(m.SheetDataValidationModel),n=o.get(r.ICommandService),l=o.get(r.IUndoRedoService),u=i.getRuleObjectMatrix(e,t).clone();u.addRule(a);const d=u.diff(i.getRules(e,t)),c=i.getValidator(a.type),h={unitId:e,subUnitId:t,rule:{...a,...c==null?void 0:c.normalizeFormula(a,e,t)}},{redoMutations:g,undoMutations:f}=K(e,t,d,o);return g.push({id:p.AddDataValidationMutation.id,params:h}),f.unshift({id:p.RemoveDataValidationMutation.id,params:{unitId:e,subUnitId:t,ruleId:a.uid}}),l.pushUndoRedo({unitID:e,redoMutations:g,undoMutations:f}),r.sequenceExecute(g,n),!0}},Ie={type:r.CommandType.COMMAND,id:"sheets.command.update-data-validation-setting",handler(o,s){if(!s)return!1;const e=o.get(r.ICommandService),t=o.get(r.IUndoRedoService),a=o.get(m.SheetDataValidationModel),i=o.get(p.DataValidatorRegistryService),{unitId:n,subUnitId:l,ruleId:u,setting:d}=s,c=i.getValidatorItem(d.type);if(!c)return!1;const h=a.getRuleById(n,l,u);if(!h)return!1;const g={...h,...d};if(!c.validatorFormula(g,n,l).success)return!1;const f={unitId:n,subUnitId:l,ruleId:u,payload:{type:p.UpdateRuleType.SETTING,payload:{...d,...c.normalizeFormula(g,n,l)}}},R=[{id:p.UpdateDataValidationMutation.id,params:f}],_={unitId:n,subUnitId:l,ruleId:u,payload:{type:p.UpdateRuleType.SETTING,payload:p.getRuleSetting(h)}},V=[{id:p.UpdateDataValidationMutation.id,params:_}];if(d.type===r.DataValidationType.CHECKBOX){const M=h.ranges,T=o.get(r.IUniverInstanceService),O=D.getSheetCommandTarget(T,{unitId:n,subUnitId:l});if(O){const I=new r.ObjectMatrix,{worksheet:F}=O,{formula2:B=k,formula1:oe=$}=h,{formula2:se=k,formula1:le=$}=d;let Re=!1;if(M.forEach(ue=>{r.Range.foreach(ue,(z,_e)=>{const C=F.getCellRaw(z,_e),Pe=Ve(C);(Te(C)||Pe===String(B))&&!(C!=null&&C.p)?(I.setValue(z,_e,{v:se,p:null}),Re=!0):Pe===String(oe)&&!(C!=null&&C.p)&&(I.setValue(z,_e,{v:le,p:null}),Re=!0)})}),Re){const ue={id:D.SetRangeValuesMutation.id,params:{unitId:n,subUnitId:l,cellValue:I.getData()}},z={id:D.SetRangeValuesMutation.id,params:D.SetRangeValuesUndoMutationFactory(o,ue.params)};R.push(ue),V.push(z)}}}return r.sequenceExecute(R,e).result?(t.pushUndoRedo({unitID:n,redoMutations:R,undoMutations:V}),!0):!1}},Ce={type:r.CommandType.COMMAND,id:"sheets.command.update-data-validation-options",handler(o,s){if(!s)return!1;const e=o.get(r.ICommandService),t=o.get(r.IUndoRedoService),a=o.get(m.SheetDataValidationModel),{unitId:i,subUnitId:n,ruleId:l,options:u}=s,d=a.getRuleById(i,n,l);if(!d)return!1;const c={unitId:i,subUnitId:n,ruleId:l,payload:{type:p.UpdateRuleType.OPTIONS,payload:u}},h=[{id:p.UpdateDataValidationMutation.id,params:c}],g={unitId:i,subUnitId:n,ruleId:l,payload:{type:p.UpdateRuleType.OPTIONS,payload:p.getRuleOptions(d)}},f=[{id:p.UpdateDataValidationMutation.id,params:g}];return t.pushUndoRedo({unitID:i,redoMutations:h,undoMutations:f}),e.executeCommand(p.UpdateDataValidationMutation.id,c),!0}},Ne={type:r.CommandType.COMMAND,id:"sheets.command.clear-range-data-validation",handler(o,s){if(!s)return!1;const{unitId:e,subUnitId:t,ranges:a}=s,i=o.get(r.ICommandService),n=o.get(r.IUniverInstanceService),l=D.getSheetCommandTarget(n,{unitId:e,subUnitId:t}),u=o.get(m.SheetDataValidationModel);if(!l)return!1;const d=o.get(r.IUndoRedoService),c=u.getRuleObjectMatrix(e,t).clone();c.removeRange(a);const h=c.diff(u.getRules(e,t)),{redoMutations:g,undoMutations:f}=K(e,t,h,o);return d.pushUndoRedo({unitID:e,redoMutations:g,undoMutations:f}),r.sequenceExecute(g,i).result}},Ae={type:r.CommandType.COMMAND,id:"sheet.command.remove-all-data-validation",handler(o,s){if(!s)return!1;const{unitId:e,subUnitId:t}=s,a=o.get(r.ICommandService),i=o.get(m.SheetDataValidationModel),n=o.get(r.IUndoRedoService),l=[...i.getRules(e,t)],u={unitId:e,subUnitId:t,ruleId:l.map(h=>h.uid)},d=[{id:p.RemoveDataValidationMutation.id,params:u}],c=[{id:p.AddDataValidationMutation.id,params:{unitId:e,subUnitId:t,rule:l}}];return n.pushUndoRedo({redoMutations:d,undoMutations:c,unitID:e}),a.executeCommand(p.RemoveDataValidationMutation.id,u),!0}},it=(o,s)=>{const e=o.get(m.SheetDataValidationModel),{unitId:t,subUnitId:a,ruleId:i,source:n}=s;if(Array.isArray(i)){const u=i.map(d=>e.getRuleById(t,a,d)).filter(Boolean);return[{id:p.AddDataValidationMutation.id,params:{unitId:t,subUnitId:a,rule:u,source:n}}]}return[{id:p.AddDataValidationMutation.id,params:{unitId:t,subUnitId:a,rule:{...e.getRuleById(t,a,i)},index:e.getRuleIndex(t,a,i)}}]},Ue={type:r.CommandType.COMMAND,id:"sheet.command.remove-data-validation-rule",handler(o,s){if(!s)return!1;const{unitId:e,subUnitId:t,ruleId:a}=s,i=o.get(r.ICommandService),n=o.get(r.IUndoRedoService),l=o.get(m.SheetDataValidationModel),u=[{id:p.RemoveDataValidationMutation.id,params:s}],d=[{id:p.AddDataValidationMutation.id,params:{unitId:e,subUnitId:t,rule:{...l.getRuleById(e,t,a)},index:l.getRuleIndex(e,t,a)}}];return n.pushUndoRedo({undoMutations:d,redoMutations:u,unitID:s.unitId}),i.executeCommand(p.RemoveDataValidationMutation.id,s),!0}},we="SHEET_DATA_VALIDATION_PLUGIN";var Le=(o=>(o[o.View=0]="View",o[o.Edit=1]="Edit",o[o.ManageCollaborator=2]="ManageCollaborator",o[o.Print=3]="Print",o[o.Duplicate=4]="Duplicate",o[o.Comment=5]="Comment",o[o.Copy=6]="Copy",o[o.Share=7]="Share",o[o.Export=8]="Export",o[o.MoveWorksheet=9]="MoveWorksheet",o[o.DeleteWorksheet=10]="DeleteWorksheet",o[o.HideWorksheet=11]="HideWorksheet",o[o.RenameWorksheet=12]="RenameWorksheet",o[o.CreateWorksheet=13]="CreateWorksheet",o[o.SetWorksheetStyle=14]="SetWorksheetStyle",o[o.EditWorksheetCell=15]="EditWorksheetCell",o[o.InsertHyperlink=16]="InsertHyperlink",o[o.Sort=17]="Sort",o[o.Filter=18]="Filter",o[o.PivotTable=19]="PivotTable",o[o.FloatImg=20]="FloatImg",o[o.History=21]="History",o[o.RwHgtClWdt=22]="RwHgtClWdt",o[o.ViemRwHgtClWdt=23]="ViemRwHgtClWdt",o[o.ViewFilter=24]="ViewFilter",o[o.MoveSheet=25]="MoveSheet",o[o.DeleteSheet=26]="DeleteSheet",o[o.HideSheet=27]="HideSheet",o[o.CopySheet=28]="CopySheet",o[o.RenameSheet=29]="RenameSheet",o[o.CreateSheet=30]="CreateSheet",o[o.SelectProtectedCells=31]="SelectProtectedCells",o[o.SelectUnProtectedCells=32]="SelectUnProtectedCells",o[o.SetCellStyle=33]="SetCellStyle",o[o.SetCellValue=34]="SetCellValue",o[o.SetRowStyle=35]="SetRowStyle",o[o.SetColumnStyle=36]="SetColumnStyle",o[o.InsertRow=37]="InsertRow",o[o.InsertColumn=38]="InsertColumn",o[o.DeleteRow=39]="DeleteRow",o[o.DeleteColumn=40]="DeleteColumn",o[o.EditExtraObject=41]="EditExtraObject",o[o.Delete=42]="Delete",o[o.RecoverHistory=43]="RecoverHistory",o[o.ViewHistory=44]="ViewHistory",o[o.CreatePermissionObject=45]="CreatePermissionObject",o[o.UNRECOGNIZED=-1]="UNRECOGNIZED",o))(Le||{}),rt=Object.getOwnPropertyDescriptor,nt=(o,s,e,t)=>{for(var a=t>1?void 0:t?rt(s,e):s,i=o.length-1,n;i>=0;i--)(n=o[i])&&(a=n(a)||a);return a},pe=(o,s)=>(e,t)=>s(e,t,o);m.DataValidationFormulaController=class extends r.Disposable{constructor(s,e,t){super(),this._univerInstanceService=s,this._permissionService=e,this._lexerTreeBuilder=t}getFormulaRefCheck(s){var t,a;const e=this._lexerTreeBuilder.sequenceNodesBuilder(s);if(!e)return!0;for(let i=0;i<e.length;i++){const n=e[i];if(typeof n=="string")continue;const{token:l}=n,u=y.deserializeRangeWithSheetWithCache(l),d=this._univerInstanceService.getCurrentUnitForType(r.UniverInstanceType.UNIVER_SHEET);let c=d.getActiveSheet();const h=d.getUnitId();if(u.sheetName){if(c=d.getSheetBySheetName(u.sheetName),!c)return!1;const V=c==null?void 0:c.getSheetId();if(!this._permissionService.getPermissionPoint(new D.WorksheetViewPermission(h,V).id))return!1}if(!c)return!1;const{startRow:g,endRow:f,startColumn:R,endColumn:_}=u.range;for(let V=g;V<=f;V++)for(let v=R;v<=_;v++){const M=(a=(t=c.getCell(V,v))==null?void 0:t.selectionProtection)==null?void 0:a[0];if((M==null?void 0:M[Le.View])===!1)return!1}}return!0}},m.DataValidationFormulaController=nt([pe(0,r.IUniverInstanceService),pe(1,r.IPermissionService),pe(2,r.Inject(y.LexerTreeBuilder))],m.DataValidationFormulaController);const ot="sheets-data-validation.config",be={};var st=Object.getOwnPropertyDescriptor,lt=(o,s,e,t)=>{for(var a=t>1?void 0:t?st(s,e):s,i=o.length-1,n;i>=0;i--)(n=o[i])&&(a=n(a)||a);return a},Se=(o,s)=>(e,t)=>s(e,t,o);let te=class extends r.Disposable{constructor(s,e,t){super();S(this,"_disposableMap",new Map);S(this,"registerRule",(s,e,t)=>{P(t.type,this._validatorRegistryService)&&this.register(s,e,t)});this._dataValidationModel=s,this._formulaRefRangeService=e,this._validatorRegistryService=t,this._initRefRange()}_getIdWithUnitId(s,e,t){return`${s}_${e}_${t}`}register(s,e,t){const a=t.ranges,i=t.formula1,n=t.formula2,l=this._formulaRefRangeService.registerRangeFormula(s,e,a,[i!=null?i:"",n!=null?n:""],d=>{if(d.length===0)return{undos:[{id:p.AddDataValidationMutation.id,params:{unitId:s,subUnitId:e,rule:t,source:"patched"}}],redos:[{id:p.RemoveDataValidationMutation.id,params:{unitId:s,subUnitId:e,ruleId:t.uid,source:"patched"}}]};const c=[],h=[],g=d[0];c.push({id:p.UpdateDataValidationMutation.id,params:{unitId:s,subUnitId:e,ruleId:t.uid,payload:{type:p.UpdateRuleType.ALL,payload:{ranges:g.ranges,formula1:g.formulas[0],formula2:g.formulas[1]}},source:"patched"}}),h.push({id:p.UpdateDataValidationMutation.id,params:{unitId:s,subUnitId:e,ruleId:t.uid,payload:{type:p.UpdateRuleType.ALL,payload:{ranges:a,formula1:i,formula2:n}},source:"patched"}});for(let f=1;f<d.length;f++){const R=d[f],_=r.generateRandomId();c.push({id:p.AddDataValidationMutation.id,params:{unitId:s,subUnitId:e,rule:{...t,uid:_,formula1:R.formulas[0],formula2:R.formulas[1],ranges:R.ranges},source:"patched"}}),h.push({id:p.RemoveDataValidationMutation.id,params:{unitId:s,subUnitId:e,ruleId:_,source:"patched"}})}return{undos:h,redos:c}}),u=this._getIdWithUnitId(s,e,t.uid);this._disposableMap.set(u,l)}_initRefRange(){const s=this._dataValidationModel.getAll();for(const[e,t]of s)for(const[a,i]of t)for(const n of i)this.registerRule(e,a,n);this.disposeWithMe(this._dataValidationModel.ruleChange$.subscribe(e=>{const{unitId:t,subUnitId:a,rule:i}=e;switch(e.type){case"add":{const n=e.rule;this.registerRule(e.unitId,e.subUnitId,n);break}case"remove":{const n=this._disposableMap.get(this._getIdWithUnitId(t,a,i.uid));n&&n.dispose();break}case"update":{const n=e.rule,l=this._disposableMap.get(this._getIdWithUnitId(t,a,n.uid));l&&l.dispose(),this.registerRule(e.unitId,e.subUnitId,n);break}}})),this.disposeWithMe(r.toDisposable(()=>{this._disposableMap.forEach(e=>{e.dispose()}),this._disposableMap.clear()}))}};te=lt([Se(0,r.Inject(m.SheetDataValidationModel)),Se(1,r.Inject(Z.FormulaRefRangeService)),Se(2,r.Inject(p.DataValidatorRegistryService))],te);var ut=Object.getOwnPropertyDescriptor,dt=(o,s,e,t)=>{for(var a=t>1?void 0:t?ut(s,e):s,i=o.length-1,n;i>=0;i--)(n=o[i])&&(a=n(a)||a);return a},L=(o,s)=>(e,t)=>s(e,t,o);let ae=class extends r.Disposable{constructor(s,e,t,a,i,n){super();S(this,"_disposableMap",new Map);S(this,"registerRule",(s,e,t)=>{P(t.type,this._validatorRegistryService)||(this.register(s,e,t),this.registerFormula(s,e,t))});this._dataValidationModel=s,this._injector=e,this._refRangeService=t,this._dataValidationFormulaService=a,this._formulaRefRangeService=i,this._validatorRegistryService=n,this._initRefRange()}_getIdWithUnitId(s,e,t){return`${s}_${e}_${t}`}registerFormula(s,e,t){var d;const a=t.uid,i=this._getIdWithUnitId(s,e,a),n=(d=this._disposableMap.get(i))!=null?d:new Set,l=(c,h)=>{const g=this._dataValidationModel.getRuleById(s,e,a);if(!g)return{redos:[],undos:[]};const f=g[c];if(!f||f===h)return{redos:[],undos:[]};const R={unitId:s,subUnitId:e,ruleId:t.uid,payload:{type:p.UpdateRuleType.SETTING,payload:{type:g.type,formula1:g.formula1,formula2:g.formula2,[c]:h}},source:"patched"},_={unitId:s,subUnitId:e,ruleId:t.uid,payload:{type:p.UpdateRuleType.SETTING,payload:{type:g.type,formula1:g.formula1,formula2:g.formula2}},source:"patched"},V=[{id:p.UpdateDataValidationMutation.id,params:R}],v=[{id:p.UpdateDataValidationMutation.id,params:_}];return{redos:V,undos:v}},u=this._dataValidationFormulaService.getRuleFormulaInfo(s,e,a);if(u){const[c,h]=u;if(c){const g=this._formulaRefRangeService.registerFormula(s,e,c.text,f=>l("formula1",f));n.add(()=>g.dispose())}if(h){const g=this._formulaRefRangeService.registerFormula(s,e,h.text,f=>l("formula2",f));n.add(()=>g.dispose())}}}register(s,e,t){var u;const a=d=>{const c=[...t.ranges],g=c.map(R=>D.handleCommonDefaultRangeChangeWithEffectRefCommands(R,d)).filter(R=>!!R).flat();if(r.isRangesEqual(g,c))return{redos:[],undos:[]};if(g.length){const R={unitId:s,subUnitId:e,ruleId:t.uid,payload:{type:p.UpdateRuleType.RANGE,payload:g},source:"patched"},_=[{id:p.UpdateDataValidationMutation.id,params:R}],V=[{id:p.UpdateDataValidationMutation.id,params:{unitId:s,subUnitId:e,ruleId:t.uid,payload:{type:p.UpdateRuleType.RANGE,payload:c},source:"patched"}}];return{redos:_,undos:V}}else{const R={unitId:s,subUnitId:e,ruleId:t.uid},_=[{id:p.RemoveDataValidationMutation.id,params:R}],V=it(this._injector,R);return{redos:_,undos:V}}},i=[];t.ranges.forEach(d=>{const c=this._refRangeService.registerRefRange(d,a,s,e);i.push(()=>c.dispose())});const n=this._getIdWithUnitId(s,e,t.uid),l=(u=this._disposableMap.get(n))!=null?u:new Set;l.add(()=>i.forEach(d=>d())),this._disposableMap.set(n,l)}_initRefRange(){const s=this._dataValidationModel.getAll();for(const[e,t]of s)for(const[a,i]of t)for(const n of i)this.registerRule(e,a,n);this.disposeWithMe(this._dataValidationModel.ruleChange$.subscribe(e=>{const{unitId:t,subUnitId:a,rule:i}=e;switch(e.type){case"add":{const n=e.rule;this.registerRule(e.unitId,e.subUnitId,n);break}case"remove":{const n=this._disposableMap.get(this._getIdWithUnitId(t,a,i.uid));n&&n.forEach(l=>l());break}case"update":{const n=e.rule,l=this._disposableMap.get(this._getIdWithUnitId(t,a,n.uid));l&&l.forEach(u=>u()),this.registerRule(e.unitId,e.subUnitId,n);break}}})),this.disposeWithMe(r.toDisposable(()=>{this._disposableMap.forEach(e=>{e.forEach(t=>t())}),this._disposableMap.clear()}))}};ae=dt([L(0,r.Inject(m.SheetDataValidationModel)),L(1,r.Inject(r.Injector)),L(2,r.Inject(D.RefRangeService)),L(3,r.Inject(m.DataValidationFormulaService)),L(4,r.Inject(Z.FormulaRefRangeService)),L(5,r.Inject(p.DataValidatorRegistryService))],ae);var ct=Object.getOwnPropertyDescriptor,mt=(o,s,e,t)=>{for(var a=t>1?void 0:t?ct(s,e):s,i=o.length-1,n;i>=0;i--)(n=o[i])&&(a=n(a)||a);return a},fe=(o,s)=>(e,t)=>s(e,t,o);let ie=class extends r.Disposable{constructor(o,s,e){super(),this._sheetInterceptorService=o,this._univerInstanceService=s,this._sheetDataValidationModel=e,this._initSheetChange()}_initSheetChange(){this.disposeWithMe(this._sheetInterceptorService.interceptCommand({getMutations:o=>{var s;if(o.id===D.RemoveSheetCommand.id){const e=o.params,t=e.unitId||this._univerInstanceService.getCurrentUnitForType(r.UniverInstanceType.UNIVER_SHEET).getUnitId(),a=this._univerInstanceService.getUniverSheetInstance(t);if(!a)return{redos:[],undos:[]};const i=e.subUnitId||((s=a.getActiveSheet())==null?void 0:s.getSheetId());if(!i)return{redos:[],undos:[]};const n=this._sheetDataValidationModel.getRules(t,i);if(n.length===0)return{redos:[],undos:[]};const l=n.map(c=>c.uid),u={unitId:t,subUnitId:i,ruleId:l,source:"patched"},d={unitId:t,subUnitId:i,rule:[...n],source:"patched"};return{redos:[{id:p.RemoveDataValidationMutation.id,params:u}],undos:[{id:p.AddDataValidationMutation.id,params:d}]}}else if(o.id===D.CopySheetCommand.id){const e=o.params,{unitId:t,subUnitId:a,targetSubUnitId:i}=e;if(!t||!a||!i)return{redos:[],undos:[]};const n=this._sheetDataValidationModel.getRules(t,a);if(n.length===0)return{redos:[],undos:[]};const l=n.map(u=>({...u,uid:r.generateRandomId(6)}));return{redos:[{id:p.AddDataValidationMutation.id,params:{unitId:t,subUnitId:i,rule:l,source:"patched"}}],undos:[{id:p.RemoveDataValidationMutation.id,params:{unitId:t,subUnitId:i,ruleId:l.map(u=>u.uid),source:"patched"}}]}}return{redos:[],undos:[]}}}))}};ie=mt([fe(0,r.Inject(D.SheetInterceptorService)),fe(1,r.Inject(r.IUniverInstanceService)),fe(2,r.Inject(m.SheetDataValidationModel))],ie);class ht extends p.BaseDataValidator{constructor(){super(...arguments);S(this,"id",r.DataValidationType.ANY);S(this,"title","dataValidation.any.title");S(this,"operators",[]);S(this,"scopes",["sheet"]);S(this,"order",0);S(this,"offsetFormulaByRange",!1)}async parseFormula(e,t,a){return{formula1:e.formula1,formula2:e.formula2,isFormulaValid:!0}}validatorFormula(e,t,a){return{success:!0}}async isValidType(e,t,a){return!0}generateRuleErrorMessage(e){return this.localeService.t("dataValidation.any.error")}}class gt extends p.BaseDataValidator{constructor(){super(...arguments);S(this,"id",r.DataValidationType.CUSTOM);S(this,"title","dataValidation.custom.title");S(this,"operators",[]);S(this,"scopes",["sheet"]);S(this,"order",60);S(this,"_customFormulaService",this.injector.get(m.DataValidationCustomFormulaService));S(this,"_lexerTreeBuilder",this.injector.get(y.LexerTreeBuilder))}validatorFormula(e,t,a){var d;const i=r.isFormulaString(e.formula1),n=(d=e.formula1)!=null?d:"",u=this._lexerTreeBuilder.checkIfAddBracket(n)===0&&n.startsWith(y.operatorToken.EQUALS);return{success:i&&u,formula1:i&&u?"":this.localeService.t("dataValidation.validFail.formula")}}async parseFormula(e,t,a){return{formula1:void 0,formula2:void 0,isFormulaValid:!0}}async isValidType(e,t,a){const{column:i,row:n,unitId:l,subUnitId:u}=e,d=await this._customFormulaService.getCellFormulaValue(l,u,a.uid,n,i),c=d==null?void 0:d.v;return E(String(c))&&r.Tools.isDefine(c)&&c!==""?d.t===r.CellValueType.BOOLEAN?!!c:typeof c=="boolean"?c:typeof c=="number"?!!c:typeof c=="string"?E(c):!!c:!1}generateRuleErrorMessage(e){return this.localeService.t("dataValidation.custom.error")}generateRuleName(e){var t;return this.localeService.t("dataValidation.custom.ruleName").replace("{FORMULA1}",(t=e.formula1)!=null?t:"")}}class Be extends ge{constructor(){super(...arguments);S(this,"id",r.DataValidationType.LIST_MULTIPLE);S(this,"title","dataValidation.listMultiple.title");S(this,"offsetFormulaByRange",!1);S(this,"skipDefaultFontRender",()=>!0)}}class pt extends p.BaseDataValidator{constructor(){super(...arguments);S(this,"_customFormulaService",this.injector.get(m.DataValidationCustomFormulaService));S(this,"_lexerTreeBuilder",this.injector.get(y.LexerTreeBuilder));S(this,"id",r.DataValidationType.WHOLE);S(this,"title","dataValidation.whole.title");S(this,"order",10);S(this,"operators",[r.DataValidationOperator.BETWEEN,r.DataValidationOperator.EQUAL,r.DataValidationOperator.GREATER_THAN,r.DataValidationOperator.GREATER_THAN_OR_EQUAL,r.DataValidationOperator.LESS_THAN,r.DataValidationOperator.LESS_THAN_OR_EQUAL,r.DataValidationOperator.NOT_BETWEEN,r.DataValidationOperator.NOT_EQUAL]);S(this,"scopes",["sheet"])}_isFormulaOrInt(e){return!r.Tools.isBlank(e)&&(r.isFormulaString(e)||!Number.isNaN(+e)&&Number.isInteger(+e))}async isValidType(e,t,a){const{value:i}=e,n=X(i);return!Number.isNaN(n)&&Number.isInteger(n)}transform(e,t,a){const{value:i}=e;return{...e,value:X(i)}}_parseNumber(e){return e==null?Number.NaN:+e}async parseFormula(e,t,a,i,n){const l=await this._customFormulaService.getCellFormulaValue(t,a,e.uid,i,n),u=await this._customFormulaService.getCellFormula2Value(t,a,e.uid,i,n),{formula1:d,formula2:c}=e,h=r.isFormulaString(d)?l==null?void 0:l.v:d,g=r.isFormulaString(c)?u==null?void 0:u.v:c,f=E(`${h}`)&&E(`${g}`);return{formula1:this._parseNumber(h),formula2:this._parseNumber(g),isFormulaValid:f}}validatorFormula(e,t,a){const i=e.operator;if(!i)return{success:!0};const n=r.Tools.isDefine(e.formula1)&&this._isFormulaOrInt(e.formula1),l=r.Tools.isDefine(e.formula2)&&this._isFormulaOrInt(e.formula2),u=J.includes(i),d=this.localeService.t("dataValidation.validFail.number");return u?{success:n&&l,formula1:n?void 0:d,formula2:l?void 0:d}:{success:n,formula1:d}}generateRuleErrorMessage(e,t){if(!e.operator)return this.localeService.t(ee.NONE).replace("{TYPE}",this.titleStr);const{transformedFormula1:a,transformedFormula2:i}=Y(this._lexerTreeBuilder,e,t);return`${this.localeService.t(ee[e.operator]).replace(q,a!=null?a:"").replace(Q,i!=null?i:"")}`}}var St=Object.getOwnPropertyDescriptor,ft=(o,s,e,t)=>{for(var a=t>1?void 0:t?St(s,e):s,i=o.length-1,n;i>=0;i--)(n=o[i])&&(a=n(a)||a);return a},b=(o,s)=>(e,t)=>s(e,t,o);let re=class extends r.RxDisposable{constructor(o,s,e,t,a,i){super(),this._univerInstanceService=o,this._dataValidatorRegistryService=s,this._injector=e,this._selectionManagerService=t,this._sheetInterceptorService=a,this._sheetDataValidationModel=i,this._init()}_init(){this._registerValidators(),this._initCommandInterceptor()}_registerValidators(){[ht,Ze,pt,at,ye,Me,ge,Be,gt].forEach(o=>{const s=this._injector.createInstance(o);this.disposeWithMe(this._dataValidatorRegistryService.register(s)),this.disposeWithMe(r.toDisposable(()=>this._injector.delete(o)))})}_initCommandInterceptor(){this._sheetInterceptorService.interceptCommand({getMutations:o=>{var s;if(o.id===D.ClearSelectionAllCommand.id){const e=this._univerInstanceService.getCurrentUnitForType(r.UniverInstanceType.UNIVER_SHEET),t=e.getUnitId(),a=e.getActiveSheet();if(!a)throw new Error("No active sheet found");const i=a.getSheetId(),n=(s=this._selectionManagerService.getCurrentSelections())==null?void 0:s.map(h=>h.range),l=this._sheetDataValidationModel.getRuleObjectMatrix(t,i).clone();n&&l.removeRange(n);const u=l.diff(this._sheetDataValidationModel.getRules(t,i)),{redoMutations:d,undoMutations:c}=K(t,i,u,this._injector,"patched");return{undos:c,redos:d}}return{undos:[],redos:[]}}})}};re=ft([b(0,r.IUniverInstanceService),b(1,r.Inject(p.DataValidatorRegistryService)),b(2,r.Inject(r.Injector)),b(3,r.Inject(D.SheetsSelectionsService)),b(4,r.Inject(D.SheetInterceptorService)),b(5,r.Inject(m.SheetDataValidationModel))],re);var vt=Object.getOwnPropertyDescriptor,Rt=(o,s,e,t)=>{for(var a=t>1?void 0:t?vt(s,e):s,i=o.length-1,n;i>=0;i--)(n=o[i])&&(a=n(a)||a);return a},ne=(o,s)=>(e,t)=>s(e,t,o);m.SheetsDataValidationValidatorService=class extends r.Disposable{constructor(s,e,t,a){super(),this._univerInstanceService=s,this._sheetDataValidationModel=e,this._dataValidationCacheService=t,this._lifecycleService=a,this._initRecalculate()}_initRecalculate(){const s=e=>{if(e.length===0)return;const t=this._univerInstanceService.getCurrentUnitForType(r.UniverInstanceType.UNIVER_SHEET),a=t==null?void 0:t.getActiveSheet(),i={};e.flat().forEach(n=>{i[n.unitId]||(i[n.unitId]={}),i[n.unitId][n.subUnitId]||(i[n.unitId][n.subUnitId]=[]);const l=this._univerInstanceService.getUnit(n.unitId,r.UniverInstanceType.UNIVER_SHEET),u=l==null?void 0:l.getSheetBySheetId(n.subUnitId);u&&i[n.unitId][n.subUnitId].push(...n.ranges.map(d=>r.Range.transformRange(d,u)))}),Object.entries(i).forEach(([n,l])=>{Object.entries(l).forEach(([u,d])=>{(t==null?void 0:t.getUnitId())===n&&(a==null?void 0:a.getSheetId())===u?this.validatorRanges(n,u,d):requestIdleCallback(()=>{this.validatorRanges(n,u,d)})})})};this.disposeWithMe(this._dataValidationCacheService.dirtyRanges$.pipe(A.bufferWhen(()=>this._lifecycleService.lifecycle$.pipe(A.filter(e=>e===r.LifecycleStages.Rendered)))).subscribe(s)),this.disposeWithMe(this._dataValidationCacheService.dirtyRanges$.pipe(A.filter(()=>this._lifecycleService.stage>=r.LifecycleStages.Rendered),r.bufferDebounceTime(20)).subscribe(s))}async _validatorByCell(s,e,t,a){const i=s.getUnitId(),n=e.getSheetId();if(!r.Tools.isDefine(t)||!r.Tools.isDefine(a))throw new Error(`row or col is not defined, row: ${t}, col: ${a}`);const l=this._sheetDataValidationModel.getRuleByLocation(i,n,t,a);return l?new Promise(u=>{this._sheetDataValidationModel.validator(l,{unitId:i,subUnitId:n,row:t,col:a,worksheet:e,workbook:s},d=>{u(d)})}):r.DataValidationStatus.VALID}async validatorCell(s,e,t,a){const i=this._univerInstanceService.getUnit(s,r.UniverInstanceType.UNIVER_SHEET);if(!i)throw new Error(`cannot find current workbook, unitId: ${s}`);const n=i.getSheetBySheetId(e);if(!n)throw new Error(`cannot find current worksheet, sheetId: ${e}`);return this._validatorByCell(i,n,t,a)}validatorRanges(s,e,t){if(!t.length)return Promise.resolve([]);const a=this._univerInstanceService.getUnit(s,r.UniverInstanceType.UNIVER_SHEET);if(!a)throw new Error(`cannot find current workbook, unitId: ${s}`);const i=a.getSheetBySheetId(e);if(!i)throw new Error(`cannot find current worksheet, sheetId: ${e}`);const l=this._sheetDataValidationModel.getRules(s,e).map(d=>d.ranges).flat(),u=t.map(d=>l.map(c=>r.getIntersectRange(d,c))).flat().filter(Boolean);return Promise.all(u.map(d=>{const c=[];return r.Range.foreach(d,(h,g)=>{c.push(this._validatorByCell(a,i,h,g))}),Promise.all(c)}))}async validatorWorksheet(s,e){const t=this._univerInstanceService.getUnit(s,r.UniverInstanceType.UNIVER_SHEET);if(!t)throw new Error(`cannot find current workbook, unitId: ${s}`);const a=t.getSheetBySheetId(e);if(!a)throw new Error(`cannot find current worksheet, sheetId: ${e}`);const i=this._sheetDataValidationModel.getRules(s,e);return await Promise.all(i.map(n=>Promise.all(n.ranges.map(l=>{const u=[];return r.Range.foreach(l,(d,c)=>{u.push(this._validatorByCell(t,a,d,c))}),Promise.all(u)})))),this._dataValidationCacheService.ensureCache(s,e)}async validatorWorkbook(s){const e=this._sheetDataValidationModel.getSubUnitIds(s),t=await Promise.all(e.map(i=>this.validatorWorksheet(s,i))),a={};return t.forEach((i,n)=>{a[e[n]]=i}),a}getDataValidations(s,e,t){const a=this._sheetDataValidationModel.getRuleObjectMatrix(s,e),i=new Set;return t.forEach(l=>{r.Range.foreach(l,(u,d)=>{const c=a.getValue(u,d);c&&i.add(c)})}),Array.from(i).map(l=>this._sheetDataValidationModel.getRuleById(s,e,l)).filter(Boolean)}getDataValidation(s,e,t){return this.getDataValidations(s,e,t)[0]}},m.SheetsDataValidationValidatorService=Rt([ne(0,r.IUniverInstanceService),ne(1,r.Inject(m.SheetDataValidationModel)),ne(2,r.Inject(m.DataValidationCacheService)),ne(3,r.Inject(r.LifecycleService))],m.SheetsDataValidationValidatorService);var _t=Object.defineProperty,Vt=Object.getOwnPropertyDescriptor,Dt=(o,s,e)=>s in o?_t(o,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[s]=e,Mt=(o,s,e,t)=>{for(var a=t>1?void 0:t?Vt(s,e):s,i=o.length-1,n;i>=0;i--)(n=o[i])&&(a=n(a)||a);return a},ve=(o,s)=>(e,t)=>s(e,t,o),je=(o,s,e)=>Dt(o,typeof s!="symbol"?s+"":s,e);m.UniverSheetsDataValidationPlugin=class extends r.Plugin{constructor(s=be,e,t,a){super(),this._config=s,this._injector=e,this._commandService=t,this._configService=a;const{...i}=r.merge({},be,this._config);this._configService.setConfig(ot,i)}onStarting(){[[m.DataValidationCacheService],[m.DataValidationFormulaService],[m.DataValidationCustomFormulaService],[m.SheetsDataValidationValidatorService],[m.SheetDataValidationModel],[re],[m.DataValidationFormulaController],[ie],[ae],[te]].forEach(s=>{this._injector.add(s)}),[Fe,Oe,Ie,Ce,Ue,Ae,Ne].forEach(s=>{this._commandService.registerCommand(s)}),this._injector.get(m.DataValidationCacheService),this._injector.get(m.SheetsDataValidationValidatorService),this._injector.get(re),this._injector.get(te),this._injector.get(ae)}onReady(){this._injector.get(ie)}onRendered(){this._injector.get(m.DataValidationFormulaController)}},je(m.UniverSheetsDataValidationPlugin,"pluginName",we),je(m.UniverSheetsDataValidationPlugin,"type",r.UniverInstanceType.UNIVER_SHEET),m.UniverSheetsDataValidationPlugin=Mt([r.DependentOn(p.UniverDataValidationPlugin),ve(1,r.Inject(r.Injector)),ve(2,r.ICommandService),ve(3,r.IConfigService)],m.UniverSheetsDataValidationPlugin);function Et(o){const e=o.get(D.SheetsSelectionsService).getCurrentSelections().map(i=>i.range);return{uid:r.generateRandomId(6),type:r.DataValidationType.DECIMAL,operator:r.DataValidationOperator.EQUAL,formula1:"100",ranges:e!=null?e:[{startColumn:0,endColumn:0,startRow:0,endRow:0}]}}const yt="data-validation.custom-formula-input",Tt="data-validation.formula-input",Ot="data-validation.list-formula-input",Ft="data-validation.checkbox-formula-input";m.AddSheetDataValidationCommand=Fe,m.BASE_FORMULA_INPUT_NAME=Tt,m.CHECKBOX_FORMULA_1=$,m.CHECKBOX_FORMULA_2=k,m.CHECKBOX_FORMULA_INPUT_NAME=Ft,m.CUSTOM_FORMULA_INPUT_NAME=yt,m.CheckboxValidator=Me,m.ClearRangeDataValidationCommand=Ne,m.DATA_VALIDATION_PLUGIN_NAME=we,m.DateValidator=ye,m.LIST_FORMULA_INPUT_NAME=Ot,m.ListMultipleValidator=Be,m.ListValidator=ge,m.RemoveSheetAllDataValidationCommand=Ae,m.RemoveSheetDataValidationCommand=Ue,m.UpdateSheetDataValidationOptionsCommand=Ce,m.UpdateSheetDataValidationRangeCommand=Oe,m.UpdateSheetDataValidationSettingCommand=Ie,m.createDefaultNewRule=Et,m.deserializeListOptions=G,m.getCellValueNumber=X,m.getCellValueOrigin=w,m.getDataValidationCellValue=ze,m.getDataValidationDiffMutations=K,m.getFormulaCellData=j,m.getFormulaResult=U,m.getTransformedFormula=Y,m.isLegalFormulaResult=E,m.serializeListOptions=Ke,m.transformCheckboxValue=x,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
|
|
28
|
+
(function(m,r){typeof exports=="object"&&typeof module<"u"?r(exports,require("@univerjs/core"),require("@univerjs/data-validation"),require("@univerjs/engine-formula"),require("@univerjs/sheets"),require("rxjs"),require("@univerjs/sheets-formula")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","@univerjs/data-validation","@univerjs/engine-formula","@univerjs/sheets","rxjs","@univerjs/sheets-formula"],r):(m=typeof globalThis<"u"?globalThis:m||self,r(m.UniverSheetsDataValidation={},m.UniverCore,m.UniverDataValidation,m.UniverEngineFormula,m.UniverSheets,m.rxjs,m.UniverSheetsFormula))})(this,(function(m,r,p,y,D,A,Z){"use strict";var It=Object.defineProperty;var Ct=(m,r,p)=>r in m?It(m,r,{enumerable:!0,configurable:!0,writable:!0,value:p}):m[r]=p;var S=(m,r,p)=>Ct(m,typeof r!="symbol"?r+"":r,p);var He=Object.getOwnPropertyDescriptor,We=(o,s,e,t)=>{for(var a=t>1?void 0:t?He(s,e):s,i=o.length-1,n;i>=0;i--)(n=o[i])&&(a=n(a)||a);return a},de=(o,s)=>(e,t)=>s(e,t,o);m.DataValidationCacheService=class extends r.Disposable{constructor(e,t,a){super();S(this,"_cacheMatrix",new Map);S(this,"_dirtyRanges$",new A.Subject);S(this,"dirtyRanges$",this._dirtyRanges$.asObservable());this._commandService=e,this._univerInstanceService=t,this._sheetDataValidationModel=a,this._initDirtyRanges(),this._initSheetRemove()}_initDirtyRanges(){this.disposeWithMe(this._commandService.onCommandExecuted((e,t)=>{if(e.id===D.SetRangeValuesMutation.id&&!(t!=null&&t.onlyLocal)){const{cellValue:a,unitId:i,subUnitId:n}=e.params;if(a){const l=new r.ObjectMatrix(a).getDataRange();if(l.endRow===-1)return;const c=this._sheetDataValidationModel.getRules(i,n).map(h=>h.ranges).flat().map(h=>r.getIntersectRange(h,l)).filter(Boolean);c.length&&this.markRangeDirty(i,n,c,!0)}}}))}_initSheetRemove(){this.disposeWithMe(this._commandService.onCommandExecuted(e=>{var t;if(e.id===D.RemoveSheetMutation.id){const{unitId:a,subUnitId:i}=e.params;(t=this._cacheMatrix.get(a))==null||t.delete(i)}})),this.disposeWithMe(this._univerInstanceService.unitDisposed$.subscribe(e=>{e.type===r.UniverInstanceType.UNIVER_SHEET&&this._cacheMatrix.delete(e.getUnitId())}))}_ensureCache(e,t){let a=this._cacheMatrix.get(e);a||(a=new Map,this._cacheMatrix.set(e,a));let i=a.get(t);return i||(i=new r.ObjectMatrix,a.set(t,i)),i}ensureCache(e,t){return this._ensureCache(e,t)}addRule(e,t,a){this.markRangeDirty(e,t,a.ranges)}removeRule(e,t,a){this._deleteRange(e,t,a.ranges)}markRangeDirty(e,t,a,i){const n=this._ensureCache(e,t);a.forEach(l=>{r.Range.foreach(l,(u,d)=>{n.getValue(u,d)!==void 0&&n.setValue(u,d,void 0)})}),this._dirtyRanges$.next({unitId:e,subUnitId:t,ranges:a,isSetRange:i})}_deleteRange(e,t,a){const i=this._ensureCache(e,t);a.forEach(n=>{r.Range.foreach(n,(l,u)=>{i.realDeleteValue(l,u)})}),this._dirtyRanges$.next({unitId:e,subUnitId:t,ranges:a})}getValue(e,t,a,i){return this._ensureCache(e,t).getValue(a,i)}},m.DataValidationCacheService=We([de(0,r.Inject(r.ICommandService)),de(1,r.Inject(r.IUniverInstanceService)),de(2,r.Inject(p.DataValidationModel))],m.DataValidationCacheService);function U(o){var s,e;return(e=(s=o==null?void 0:o[0])==null?void 0:s[0])==null?void 0:e.v}function j(o){var s;return(s=o==null?void 0:o[0])==null?void 0:s[0]}function E(o){return!y.ERROR_TYPE_SET.has(o)}function P(o,s){var t;const e=s.getValidatorItem(o);return(t=e==null?void 0:e.offsetFormulaByRange)!=null?t:!1}var $e=Object.getOwnPropertyDescriptor,ke=(o,s,e,t)=>{for(var a=t>1?void 0:t?$e(s,e):s,i=o.length-1,n;i>=0;i--)(n=o[i])&&(a=n(a)||a);return a},H=(o,s)=>(e,t)=>s(e,t,o);m.DataValidationCustomFormulaService=class extends r.Disposable{constructor(e,t,a,i,n){super();S(this,"_ruleFormulaMap",new Map);S(this,"_ruleFormulaMap2",new Map);this._instanceSrv=e,this._registerOtherFormulaService=t,this._dataValidationModel=a,this._dataValidationCacheService=i,this._validatorRegistryService=n,this._initFormulaResultHandler(),this._initDirtyRanges()}dispose(){super.dispose(),this._ruleFormulaMap.clear(),this._ruleFormulaMap2.clear()}_initFormulaResultHandler(){this.disposeWithMe(this._registerOtherFormulaService.formulaResult$.subscribe(e=>{for(const t in e){const a=e[t];if(this._instanceSrv.getUnitType(t)===r.UniverInstanceType.UNIVER_SHEET)for(const n in a){const l=a[n],{ruleFormulaMap:u}=this._ensureMaps(t,n);l.forEach(d=>{var g,f;const c=u.get((g=d.extra)==null?void 0:g.ruleId),h=this._dataValidationModel.getRuleById(t,n,(f=d.extra)==null?void 0:f.ruleId);h&&c&&this._dataValidationCacheService.markRangeDirty(t,n,h.ranges)})}}}))}_ensureMaps(e,t){let a=this._ruleFormulaMap.get(e),i=this._ruleFormulaMap2.get(e);a||(a=new Map,this._ruleFormulaMap.set(e,a)),i||(i=new Map,this._ruleFormulaMap2.set(e,i));let n=a.get(t);n||(n=new Map,a.set(t,n));let l=i.get(t);return l||(l=new Map,i.set(t,l)),{ruleFormulaMap:n,ruleFormulaMap2:l}}_registerFormula(e,t,a,i,n){return this._registerOtherFormulaService.registerFormulaWithRange(e,t,i,n,{ruleId:a})}_handleDirtyRanges(e,t,a){this._dataValidationModel.getRules(e,t).forEach(n=>{const l=n.ranges;r.Rectangle.doAnyRangesIntersect(l,a)&&this.makeRuleDirty(e,t,n.uid)})}_initDirtyRanges(){this.disposeWithMe(this._dataValidationCacheService.dirtyRanges$.subscribe(e=>{e.isSetRange&&this._handleDirtyRanges(e.unitId,e.subUnitId,e.ranges)}))}deleteByRuleId(e,t,a){const{ruleFormulaMap:i,ruleFormulaMap2:n}=this._ensureMaps(e,t),l=this._dataValidationModel.getRuleById(e,t,a),u=i.get(a);if(!l||!u)return;const d=i.get(a);d&&(i.delete(a),this._registerOtherFormulaService.deleteFormula(e,t,[d.formulaId]));const c=n.get(a);c&&(n.delete(a),this._registerOtherFormulaService.deleteFormula(e,t,[c.formulaId]))}_addFormulaByRange(e,t,a,i,n,l){const{ruleFormulaMap:u,ruleFormulaMap2:d}=this._ensureMaps(e,t),c=l[0].startRow,h=l[0].startColumn;if(i&&r.isFormulaString(i)){const g=this._registerFormula(e,t,a,i,l);u.set(a,{formula:i,originCol:h,originRow:c,formulaId:g})}if(n&&r.isFormulaString(n)){const g=this._registerFormula(e,t,a,n,l);d.set(a,{formula:n,originCol:h,originRow:c,formulaId:g})}}addRule(e,t,a){if(P(a.type,this._validatorRegistryService)){const{ranges:i,formula1:n,formula2:l,uid:u}=a;this._addFormulaByRange(e,t,u,n,l,i)}}async getCellFormulaValue(e,t,a,i,n){var R,_;const{ruleFormulaMap:l}=this._ensureMaps(e,t),u=l.get(a);if(!u)return Promise.resolve(void 0);const d=await this._registerOtherFormulaService.getFormulaValue(e,t,u.formulaId),{originRow:c,originCol:h}=u,g=i-c,f=n-h;return j((_=(R=d==null?void 0:d.result)==null?void 0:R[g])==null?void 0:_[f])}async getCellFormula2Value(e,t,a,i,n){var R,_;const{ruleFormulaMap2:l}=this._ensureMaps(e,t),u=l.get(a);if(!u)return Promise.resolve(void 0);const d=await this._registerOtherFormulaService.getFormulaValue(e,t,u.formulaId),{originRow:c,originCol:h}=u,g=i-c,f=n-h;return j((_=(R=d==null?void 0:d.result)==null?void 0:R[g])==null?void 0:_[f])}getCellFormulaValueSync(e,t,a,i,n){var R,_;const{ruleFormulaMap:l}=this._ensureMaps(e,t),u=l.get(a);if(!u)return;const d=this._registerOtherFormulaService.getFormulaValueSync(e,t,u.formulaId),{originRow:c,originCol:h}=u,g=i-c,f=n-h;return j((_=(R=d==null?void 0:d.result)==null?void 0:R[g])==null?void 0:_[f])}getCellFormula2ValueSync(e,t,a,i,n){var R,_;const{ruleFormulaMap2:l}=this._ensureMaps(e,t),u=l.get(a);if(!u)return;const d=this._registerOtherFormulaService.getFormulaValueSync(e,t,u.formulaId),{originRow:c,originCol:h}=u,g=i-c,f=n-h;return j((_=(R=d==null?void 0:d.result)==null?void 0:R[g])==null?void 0:_[f])}getRuleFormulaInfo(e,t,a){const{ruleFormulaMap:i}=this._ensureMaps(e,t);return i.get(a)}makeRuleDirty(e,t,a){var l,u,d,c;const i=(u=(l=this._ruleFormulaMap.get(e))==null?void 0:l.get(t))==null?void 0:u.get(a),n=(c=(d=this._ruleFormulaMap2.get(e))==null?void 0:d.get(t))==null?void 0:c.get(a);i&&this._registerOtherFormulaService.markFormulaDirty(e,t,i.formulaId),n&&this._registerOtherFormulaService.markFormulaDirty(e,t,n.formulaId)}},m.DataValidationCustomFormulaService=ke([H(0,r.IUniverInstanceService),H(1,r.Inject(Z.RegisterOtherFormulaService)),H(2,r.Inject(p.DataValidationModel)),H(3,r.Inject(m.DataValidationCacheService)),H(4,r.Inject(p.DataValidatorRegistryService))],m.DataValidationCustomFormulaService);var xe=Object.getOwnPropertyDescriptor,qe=(o,s,e,t)=>{for(var a=t>1?void 0:t?xe(s,e):s,i=o.length-1,n;i>=0;i--)(n=o[i])&&(a=n(a)||a);return a},W=(o,s)=>(e,t)=>s(e,t,o);m.DataValidationFormulaService=class extends r.Disposable{constructor(e,t,a,i,n){super();S(this,"_formulaRuleMap",new Map);this._instanceService=e,this._registerOtherFormulaService=t,this._dataValidationCacheService=a,this._dataValidationModel=i,this._validatorRegistryService=n,this._initFormulaResultHandler()}_initFormulaResultHandler(){this.disposeWithMe(this._registerOtherFormulaService.formulaResult$.subscribe(e=>{for(const t in e){const a=e[t];if(this._instanceService.getUnitType(t)===r.UniverInstanceType.UNIVER_SHEET)for(const n in a){const l=a[n],u=this._ensureRuleFormulaMap(t,n);l.forEach(d=>{var c,h;if(u.get((c=d.extra)==null?void 0:c.ruleId)){const g=this._dataValidationModel.getRuleById(t,n,(h=d.extra)==null?void 0:h.ruleId);g&&this._dataValidationCacheService.markRangeDirty(t,n,g.ranges)}})}}}))}_ensureRuleFormulaMap(e,t){let a=this._formulaRuleMap.get(e);a||(a=new Map,this._formulaRuleMap.set(e,a));let i=a.get(t);return i||(i=new Map,a.set(t,i)),i}_registerSingleFormula(e,t,a,i){const n=[{startColumn:0,endColumn:0,startRow:0,endRow:0}];return this._registerOtherFormulaService.registerFormulaWithRange(e,t,a,n,{ruleId:i})}addRule(e,t,a){if(!P(a.type,this._validatorRegistryService)&&a.type!==r.DataValidationType.CHECKBOX){const{formula1:i,formula2:n,uid:l}=a,u=r.isFormulaString(i),d=r.isFormulaString(n);if(!u&&!d)return;const c=this._ensureRuleFormulaMap(e,t),h=[void 0,void 0];if(u){const g=this._registerSingleFormula(e,t,i,l);h[0]={id:g,text:i}}if(d){const g=this._registerSingleFormula(e,t,n,l);h[1]={id:g,text:n}}c.set(l,h)}}removeRule(e,t,a){const n=this._ensureRuleFormulaMap(e,t).get(a);if(!n)return;const[l,u]=n,d=[l==null?void 0:l.id,u==null?void 0:u.id].filter(Boolean);d.length&&this._registerOtherFormulaService.deleteFormula(e,t,d)}getRuleFormulaResult(e,t,a){const n=this._ensureRuleFormulaMap(e,t).get(a);if(!n)return Promise.resolve(null);const l=async u=>u&&this._registerOtherFormulaService.getFormulaValue(e,t,u.id);return Promise.all([l(n[0]),l(n[1])])}getRuleFormulaResultSync(e,t,a){const n=this._ensureRuleFormulaMap(e,t).get(a);if(n)return n.map(l=>{if(l)return this._registerOtherFormulaService.getFormulaValueSync(e,t,l.id)})}getRuleFormulaInfo(e,t,a){return this._ensureRuleFormulaMap(e,t).get(a)}},m.DataValidationFormulaService=qe([W(0,r.IUniverInstanceService),W(1,r.Inject(Z.RegisterOtherFormulaService)),W(2,r.Inject(m.DataValidationCacheService)),W(3,r.Inject(p.DataValidationModel)),W(4,r.Inject(p.DataValidatorRegistryService))],m.DataValidationFormulaService);function w(o){return r.getOriginCellValue(o)}function Ve(o){var s;return String((s=w(o))!=null?s:"")}class ce{constructor(s,e,t,a,i=!1){S(this,"_map");S(this,"_tree",new r.RBush);S(this,"_dirty",!0);S(this,"_buildTree",()=>{if(!this._dirty||this._disableTree)return;this._tree.clear();const s=[];this._map.forEach((e,t)=>{e.forEach(a=>{s.push({minX:a.startRow,maxX:a.endRow,minY:a.startColumn,maxY:a.endColumn,ruleId:t})})}),this._tree.load(s),this._dirty=!1});S(this,"_debonceBuildTree",r.debounce(this._buildTree,0));this._unitId=e,this._subUnitId=t,this._univerInstanceService=a,this._disableTree=i,this._map=s,this._buildTree()}get _worksheet(){var s;return(s=this._univerInstanceService.getUnit(this._unitId,r.UniverInstanceType.UNIVER_SHEET))==null?void 0:s.getSheetBySheetId(this._subUnitId)}_addRule(s,e){if(!this._worksheet)return;const t=r.Rectangle.mergeRanges(e.map(a=>r.Range.transformRange(a,this._worksheet)));this._map.forEach((a,i)=>{const n=r.Rectangle.subtractMulti(a,t);n.length===0?this._map.delete(i):this._map.set(i,n)}),this._dirty=!0,this._map.set(s,t),this._debonceBuildTree()}addRule(s){this._addRule(s.uid,s.ranges)}removeRange(s){if(!this._worksheet)return;const e=s.map(t=>r.Range.transformRange(t,this._worksheet));this._map.forEach((t,a)=>{const i=r.Rectangle.subtractMulti(t,e);i.length===0?this._map.delete(a):this._map.set(a,i)}),this._dirty=!0,this._debonceBuildTree()}_removeRule(s){this._map.delete(s),this._dirty=!0,this._debonceBuildTree()}removeRule(s){this._removeRule(s.uid)}updateRange(s,e){this._removeRule(s),this._addRule(s,e)}addRangeRules(s){s.forEach(({id:e,ranges:t})=>{if(!t.length)return;let a=this._map.get(e);a?(this._map.set(e,r.Rectangle.mergeRanges([...a,...t])),a=this._map.get(e)):(a=t,this._map.set(e,a)),this._map.forEach((i,n)=>{if(n===e)return;const l=r.Rectangle.subtractMulti(i,t);l.length===0?this._map.delete(n):this._map.set(n,l)})}),this._dirty=!0,this._debonceBuildTree()}diff(s){const e=[];let t=0;return s.forEach((a,i)=>{var u;const n=(u=this._map.get(a.uid))!=null?u:[],l=a.ranges;n.length!==0&&(n.length!==l.length||n.some((d,c)=>!r.Rectangle.equals(d,l[c])))&&e.push({type:"update",ruleId:a.uid,oldRanges:l,newRanges:r.Rectangle.sort(n),rule:a}),n.length===0&&(e.push({type:"delete",rule:a,index:i-t}),t++)}),e}diffWithAddition(s,e){const t=[];let a=0;return s.forEach((i,n)=>{var d;const l=(d=this._map.get(i.uid))!=null?d:[],u=i.ranges;l.length!==0&&(l.length!==u.length||l.some((c,h)=>!r.Rectangle.equals(c,u[h])))&&t.push({type:"update",ruleId:i.uid,oldRanges:u,newRanges:r.Rectangle.sort(l),rule:i}),l.length===0&&(t.push({type:"delete",rule:i,index:n-a}),a++)}),Array.from(e).forEach(i=>{var l;const n=(l=this._map.get(i.uid))!=null?l:[];t.push({type:"add",rule:{...i,ranges:r.Rectangle.sort(n)}})}),t}clone(){return new ce(new Map(r.Tools.deepClone(Array.from(this._map.entries()))),this._unitId,this._subUnitId,this._univerInstanceService,!0)}getValue(s,e){this._dirty&&this._buildTree();const t=this._tree.search({minX:s,maxX:s,minY:e,maxY:e});return t.length>0?t[0].ruleId:void 0}}var Qe=Object.getOwnPropertyDescriptor,Ge=(o,s,e,t)=>{for(var a=t>1?void 0:t?Qe(s,e):s,i=o.length-1,n;i>=0;i--)(n=o[i])&&(a=n(a)||a);return a},N=(o,s)=>(e,t)=>s(e,t,o);m.SheetDataValidationModel=class extends r.Disposable{constructor(e,t,a,i,n,l,u){super();S(this,"_ruleMatrixMap",new Map);S(this,"_validStatusChange$",new A.Subject);S(this,"_ruleChange$",new A.Subject);S(this,"ruleChange$",this._ruleChange$.asObservable());S(this,"validStatusChange$",this._validStatusChange$.asObservable());this._dataValidationModel=e,this._univerInstanceService=t,this._dataValidatorRegistryService=a,this._dataValidationCacheService=i,this._dataValidationFormulaService=n,this._dataValidationCustomFormulaService=l,this._commandService=u,this._initRuleUpdateListener(),this.disposeWithMe(()=>{this._ruleChange$.complete(),this._validStatusChange$.complete()}),this._initUniverInstanceListener()}_initUniverInstanceListener(){this.disposeWithMe(this._univerInstanceService.unitDisposed$.subscribe(e=>{this._ruleMatrixMap.delete(e.getUnitId())})),this.disposeWithMe(this._commandService.onCommandExecuted(e=>{if(e.id===D.RemoveSheetMutation.id){const{unitId:t,subUnitId:a}=e.params,i=this._ruleMatrixMap.get(t);i&&i.delete(a)}}))}_initRuleUpdateListener(){const e=this._dataValidationModel.getAll();for(const[t,a]of e)for(const[i,n]of a)for(const l of n)this._addRule(t,i,l),this._ruleChange$.next({type:"add",unitId:t,subUnitId:i,rule:l,source:"patched"});this.disposeWithMe(this._dataValidationModel.ruleChange$.subscribe(t=>{switch(t.type){case"add":this._addRule(t.unitId,t.subUnitId,t.rule);break;case"update":this._updateRule(t.unitId,t.subUnitId,t.rule.uid,t.oldRule,t.updatePayload);break;case"remove":this._removeRule(t.unitId,t.subUnitId,t.rule);break}this._ruleChange$.next(t)}))}_ensureRuleMatrix(e,t){let a=this._ruleMatrixMap.get(e);a||(a=new Map,this._ruleMatrixMap.set(e,a));let i=a.get(t);return i||(i=new ce(new Map,e,t,this._univerInstanceService),a.set(t,i)),i}_addRuleSideEffect(e,t,a){this._ensureRuleMatrix(e,t).addRule(a),this._dataValidationCacheService.addRule(e,t,a),this._dataValidationFormulaService.addRule(e,t,a),this._dataValidationCustomFormulaService.addRule(e,t,a)}_addRule(e,t,a){(Array.isArray(a)?a:[a]).forEach(n=>{this._addRuleSideEffect(e,t,n)})}_updateRule(e,t,a,i,n){const l=this._ensureRuleMatrix(e,t),u={...i,...n.payload};n.type===p.UpdateRuleType.RANGE?l.updateRange(a,n.payload):n.type===p.UpdateRuleType.ALL&&l.updateRange(a,n.payload.ranges),this._dataValidationCacheService.removeRule(e,t,i),this._dataValidationCacheService.addRule(e,t,u),this._dataValidationFormulaService.removeRule(e,t,i.uid),this._dataValidationFormulaService.addRule(e,t,u),this._dataValidationCustomFormulaService.deleteByRuleId(e,t,a),this._dataValidationCustomFormulaService.addRule(e,t,u)}_removeRule(e,t,a){this._ensureRuleMatrix(e,t).removeRule(a),this._dataValidationCacheService.removeRule(e,t,a),this._dataValidationCustomFormulaService.deleteByRuleId(e,t,a.uid)}getValidator(e){return this._dataValidatorRegistryService.getValidatorItem(e)}getRuleIdByLocation(e,t,a,i){return this._ensureRuleMatrix(e,t).getValue(a,i)}getRuleByLocation(e,t,a,i){const n=this.getRuleIdByLocation(e,t,a,i);if(n)return this._dataValidationModel.getRuleById(e,t,n)}validator(e,t,a){const{col:i,row:n,unitId:l,subUnitId:u,worksheet:d}=t,c=(_,V)=>{a&&a(_,V),V&&this._validStatusChange$.next({unitId:l,subUnitId:u,ruleId:e.uid,status:_,row:n,col:i})},h=d.getCellValueOnly(n,i),g=this.getValidator(e.type),f=d.getCellRaw(n,i),R=w(f);if(g){const _=this._dataValidationCacheService.ensureCache(l,u),V=_.getValue(n,i);return V==null?(_.setValue(n,i,r.DataValidationStatus.VALIDATING),g.validator({value:R,unitId:l,subUnitId:u,row:n,column:i,worksheet:t.worksheet,workbook:t.workbook,interceptValue:w(h),t:f==null?void 0:f.t},e).then(v=>{const M=v?r.DataValidationStatus.VALID:r.DataValidationStatus.INVALID,T=_.getValue(n,i);M===r.DataValidationStatus.VALID?_.realDeleteValue(n,i):_.setValue(n,i,M),c(M,V!==T)}),r.DataValidationStatus.VALIDATING):(c(V!=null?V:r.DataValidationStatus.VALID,!1),V!=null?V:r.DataValidationStatus.VALID)}else return c(r.DataValidationStatus.VALID,!1),r.DataValidationStatus.VALID}getRuleObjectMatrix(e,t){return this._ensureRuleMatrix(e,t)}getRuleById(e,t,a){return this._dataValidationModel.getRuleById(e,t,a)}getRuleIndex(e,t,a){return this._dataValidationModel.getRuleIndex(e,t,a)}getRules(e,t){return[...this._dataValidationModel.getRules(e,t)]}getUnitRules(e){return this._dataValidationModel.getUnitRules(e)}deleteUnitRules(e){return this._dataValidationModel.deleteUnitRules(e)}getSubUnitIds(e){return this._dataValidationModel.getSubUnitIds(e)}getAll(){return this._dataValidationModel.getAll()}},m.SheetDataValidationModel=Ge([N(0,r.Inject(p.DataValidationModel)),N(1,r.IUniverInstanceService),N(2,r.Inject(p.DataValidatorRegistryService)),N(3,r.Inject(m.DataValidationCacheService)),N(4,r.Inject(m.DataValidationFormulaService)),N(5,r.Inject(m.DataValidationCustomFormulaService)),N(6,r.ICommandService)],m.SheetDataValidationModel);const $=1,k=0;function De(o,s){return r.Tools.isBlank(o)?s.t("dataValidation.validFail.value"):r.isFormulaString(o)?s.t("dataValidation.validFail.primitive"):""}const x=o=>r.Tools.isDefine(o)&&String(o).toLowerCase()==="true"?"1":String(o).toLowerCase()==="false"?"0":o;class Me extends p.BaseDataValidator{constructor(){super(...arguments);S(this,"id",r.DataValidationType.CHECKBOX);S(this,"title","dataValidation.checkbox.title");S(this,"operators",[]);S(this,"scopes",["sheet"]);S(this,"order",41);S(this,"offsetFormulaByRange",!1);S(this,"_formulaService",this.injector.get(m.DataValidationFormulaService));S(this,"skipDefaultFontRender",(e,t,a)=>{const{unitId:i,subUnitId:n}=a,{formula1:l,formula2:u}=this.parseFormulaSync(e,i,n),d=`${t!=null?t:""}`;return!d||d===`${l}`||d===`${u}`})}validatorFormula(e,t,a){const{formula1:i,formula2:n}=e,l=i===n;if(r.Tools.isBlank(i)&&r.Tools.isBlank(n))return{success:!0};if(l)return{success:!1,formula1:this.localeService.t("dataValidation.validFail.checkboxEqual"),formula2:this.localeService.t("dataValidation.validFail.checkboxEqual")};const u=De(i,this.localeService),d=De(n,this.localeService);return{success:!u&&!d,formula1:u,formula2:d}}async parseFormula(e,t,a){var h,g,f,R;const{formula1:i=$,formula2:n=k}=e,l=await this._formulaService.getRuleFormulaResult(t,a,e.uid),u=r.isFormulaString(i)?U((g=(h=l==null?void 0:l[0])==null?void 0:h.result)==null?void 0:g[0][0]):i,d=r.isFormulaString(n)?U((R=(f=l==null?void 0:l[1])==null?void 0:f.result)==null?void 0:R[0][0]):n,c=E(String(u))&&E(String(d));return{formula1:x(u),formula2:x(d),originFormula1:u,originFormula2:d,isFormulaValid:c}}getExtraStyle(e,t){return{tb:r.WrapStrategy.CLIP}}parseFormulaSync(e,t,a){var h,g,f,R;const{formula1:i=$,formula2:n=k}=e,l=this._formulaService.getRuleFormulaResultSync(t,a,e.uid),u=r.isFormulaString(i)?U((g=(h=l==null?void 0:l[0])==null?void 0:h.result)==null?void 0:g[0][0]):i,d=r.isFormulaString(n)?U((R=(f=l==null?void 0:l[1])==null?void 0:f.result)==null?void 0:R[0][0]):n,c=E(String(u))&&E(String(d));return{formula1:x(u),formula2:x(d),originFormula1:u,originFormula2:d,isFormulaValid:c}}async isValidType(e,t,a){const{value:i,unitId:n,subUnitId:l}=e,{formula1:u,formula2:d,originFormula1:c,originFormula2:h}=await this.parseFormula(a,n,l);return!r.Tools.isDefine(u)||!r.Tools.isDefine(d)?!0:r.Tools.isDefine(i)&&(String(i)===String(u)||String(i)===String(d)||String(i)===String(c!=null?c:"")||String(i)===String(h!=null?h:""))}generateRuleErrorMessage(e){return this.localeService.t("dataValidation.checkbox.error")}generateRuleName(e){return this.titleStr}}const Ye={[r.DataValidationOperator.BETWEEN]:"dataValidation.date.operators.between",[r.DataValidationOperator.EQUAL]:"dataValidation.date.operators.equal",[r.DataValidationOperator.GREATER_THAN]:"dataValidation.date.operators.greaterThan",[r.DataValidationOperator.GREATER_THAN_OR_EQUAL]:"dataValidation.date.operators.greaterThanOrEqual",[r.DataValidationOperator.LESS_THAN]:"dataValidation.date.operators.lessThan",[r.DataValidationOperator.LESS_THAN_OR_EQUAL]:"dataValidation.date.operators.lessThanOrEqual",[r.DataValidationOperator.NOT_BETWEEN]:"dataValidation.date.operators.notBetween",[r.DataValidationOperator.NOT_EQUAL]:"dataValidation.date.operators.notEqual"};r.DataValidationOperator.BETWEEN+"",r.DataValidationOperator.EQUAL+"",r.DataValidationOperator.GREATER_THAN+"",r.DataValidationOperator.GREATER_THAN_OR_EQUAL+"",r.DataValidationOperator.LESS_THAN+"",r.DataValidationOperator.LESS_THAN_OR_EQUAL+"",r.DataValidationOperator.NOT_BETWEEN+"",r.DataValidationOperator.NOT_EQUAL+"";const Ee={[r.DataValidationOperator.BETWEEN]:"dataValidation.date.ruleName.between",[r.DataValidationOperator.EQUAL]:"dataValidation.date.ruleName.equal",[r.DataValidationOperator.GREATER_THAN]:"dataValidation.date.ruleName.greaterThan",[r.DataValidationOperator.GREATER_THAN_OR_EQUAL]:"dataValidation.date.ruleName.greaterThanOrEqual",[r.DataValidationOperator.LESS_THAN]:"dataValidation.date.ruleName.lessThan",[r.DataValidationOperator.LESS_THAN_OR_EQUAL]:"dataValidation.date.ruleName.lessThanOrEqual",[r.DataValidationOperator.NOT_BETWEEN]:"dataValidation.date.ruleName.notBetween",[r.DataValidationOperator.NOT_EQUAL]:"dataValidation.date.ruleName.notEqual",NONE:"dataValidation.date.ruleName.legal"},Xe={[r.DataValidationOperator.BETWEEN]:"dataValidation.date.errorMsg.between",[r.DataValidationOperator.EQUAL]:"dataValidation.date.errorMsg.equal",[r.DataValidationOperator.GREATER_THAN]:"dataValidation.date.errorMsg.greaterThan",[r.DataValidationOperator.GREATER_THAN_OR_EQUAL]:"dataValidation.date.errorMsg.greaterThanOrEqual",[r.DataValidationOperator.LESS_THAN]:"dataValidation.date.errorMsg.lessThan",[r.DataValidationOperator.LESS_THAN_OR_EQUAL]:"dataValidation.date.errorMsg.lessThanOrEqual",[r.DataValidationOperator.NOT_BETWEEN]:"dataValidation.date.errorMsg.notBetween",[r.DataValidationOperator.NOT_EQUAL]:"dataValidation.date.errorMsg.notEqual",NONE:"dataValidation.date.errorMsg.legal"},J=[r.DataValidationOperator.BETWEEN,r.DataValidationOperator.NOT_BETWEEN],q="{FORMULA1}",Q="{FORMULA2}";function Ke(o){return o.filter(Boolean).join(",")}function G(o){return o.split(",").filter(Boolean)}function ze(o){const s=w(o);return s==null?"":s.toString()}function Y(o,s,e){const{formula1:t,formula2:a}=s,i=s.ranges[0].startRow,n=s.ranges[0].startColumn,l=e.row-i,u=e.col-n,d=r.isFormulaString(t)?o.moveFormulaRefOffset(t,u,l,!0):t,c=r.isFormulaString(a)?o.moveFormulaRefOffset(a,u,l,!0):a;return{transformedFormula1:d,transformedFormula2:c}}const me=o=>{var e,t;if(o==null||typeof o=="boolean")return;if(typeof o=="number"||!Number.isNaN(+o))return+o;const s=(e=r.numfmt.parseDate(o))==null?void 0:e.v;return r.Tools.isDefine(s)?s:(t=r.numfmt.parseDate(r.dayjs(o).format("YYYY-MM-DD HH:mm:ss")))==null?void 0:t.v};class ye extends p.BaseDataValidator{constructor(){super(...arguments);S(this,"id",r.DataValidationType.DATE);S(this,"title","dataValidation.date.title");S(this,"order",40);S(this,"operators",[r.DataValidationOperator.BETWEEN,r.DataValidationOperator.EQUAL,r.DataValidationOperator.GREATER_THAN,r.DataValidationOperator.GREATER_THAN_OR_EQUAL,r.DataValidationOperator.LESS_THAN,r.DataValidationOperator.LESS_THAN_OR_EQUAL,r.DataValidationOperator.NOT_BETWEEN,r.DataValidationOperator.NOT_EQUAL]);S(this,"scopes",["sheet"]);S(this,"_customFormulaService",this.injector.get(m.DataValidationCustomFormulaService));S(this,"_lexerTreeBuilder",this.injector.get(y.LexerTreeBuilder))}async parseFormula(e,t,a,i,n){const l=await this._customFormulaService.getCellFormulaValue(t,a,e.uid,i,n),u=await this._customFormulaService.getCellFormula2Value(t,a,e.uid,i,n),{formula1:d,formula2:c}=e,h=E(String(l==null?void 0:l.v))&&E(String(u==null?void 0:u.v));return{formula1:me(r.isFormulaString(d)?l==null?void 0:l.v:d),formula2:me(r.isFormulaString(c)?u==null?void 0:u.v:c),isFormulaValid:h}}async isValidType(e){const{interceptValue:t,value:a}=e;return typeof a=="number"&&typeof t=="string"||typeof t=="string"?!!r.numfmt.parseDate(t):!1}_validatorSingleFormula(e){return!r.Tools.isBlank(e)&&(r.isFormulaString(e)||!Number.isNaN(+e)||!!(e&&r.numfmt.parseDate(e)))}validatorFormula(e,t,a){const i=e.operator;if(!i)return{success:!0};const n=this._validatorSingleFormula(e.formula1),l=this.localeService.t("dataValidation.validFail.date");if(J.includes(i)){const d=this._validatorSingleFormula(e.formula2);return{success:n&&d,formula1:n?void 0:l,formula2:d?void 0:l}}return{success:n,formula1:n?void 0:l}}normalizeFormula(e,t,a){const{formula1:i,formula2:n,bizInfo:l}=e,u=d=>{var h;if(!d)return d;let c;if(!Number.isNaN(+d))c=r.numfmt.dateFromSerial(+d);else{const g=(h=r.numfmt.parseDate(d))==null?void 0:h.v;if(g==null)return"";c=r.numfmt.dateFromSerial(g)}return r.dayjs(`${c[0]}/${c[1]}/${c[2]} ${c[3]}:${c[4]}:${c[5]}`).format(l!=null&&l.showTime?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD")};return{formula1:r.isFormulaString(i)?i:u(`${i}`),formula2:r.isFormulaString(n)?n:u(`${n}`)}}transform(e,t,a){const{value:i}=e;return{...e,value:me(i)}}get operatorNames(){return this.operators.map(e=>this.localeService.t(Ye[e]))}generateRuleName(e){var a,i;if(!e.operator)return this.localeService.t(Ee.NONE);const t=this.localeService.t(Ee[e.operator]).replace(q,(a=e.formula1)!=null?a:"").replace(Q,(i=e.formula2)!=null?i:"");return`${this.titleStr} ${t}`}generateRuleErrorMessage(e,t){if(!e.operator)return this.titleStr;const{transformedFormula1:a,transformedFormula2:i}=Y(this._lexerTreeBuilder,e,t);return`${this.localeService.t(Xe[e.operator]).replace(q,a!=null?a:"").replace(Q,i!=null?i:"")}`}}r.DataValidationOperator.BETWEEN+"",r.DataValidationOperator.EQUAL+"",r.DataValidationOperator.GREATER_THAN+"",r.DataValidationOperator.GREATER_THAN_OR_EQUAL+"",r.DataValidationOperator.LESS_THAN+"",r.DataValidationOperator.LESS_THAN_OR_EQUAL+"",r.DataValidationOperator.NOT_BETWEEN+"",r.DataValidationOperator.NOT_EQUAL+"",r.DataValidationOperator.BETWEEN+"",r.DataValidationOperator.EQUAL+"",r.DataValidationOperator.GREATER_THAN+"",r.DataValidationOperator.GREATER_THAN_OR_EQUAL+"",r.DataValidationOperator.LESS_THAN+"",r.DataValidationOperator.LESS_THAN_OR_EQUAL+"",r.DataValidationOperator.NOT_BETWEEN+"",r.DataValidationOperator.NOT_EQUAL+"";const ee={[r.DataValidationOperator.BETWEEN]:"dataValidation.errorMsg.between",[r.DataValidationOperator.EQUAL]:"dataValidation.errorMsg.equal",[r.DataValidationOperator.GREATER_THAN]:"dataValidation.errorMsg.greaterThan",[r.DataValidationOperator.GREATER_THAN_OR_EQUAL]:"dataValidation.errorMsg.greaterThanOrEqual",[r.DataValidationOperator.LESS_THAN]:"dataValidation.errorMsg.lessThan",[r.DataValidationOperator.LESS_THAN_OR_EQUAL]:"dataValidation.errorMsg.lessThanOrEqual",[r.DataValidationOperator.NOT_BETWEEN]:"dataValidation.errorMsg.notBetween",[r.DataValidationOperator.NOT_EQUAL]:"dataValidation.errorMsg.notEqual",NONE:"dataValidation.errorMsg.legal"};function X(o){return+o}class Ze extends p.BaseDataValidator{constructor(){super(...arguments);S(this,"_customFormulaService",this.injector.get(m.DataValidationCustomFormulaService));S(this,"id",r.DataValidationType.DECIMAL);S(this,"_lexerTreeBuilder",this.injector.get(y.LexerTreeBuilder));S(this,"title","dataValidation.decimal.title");S(this,"order",20);S(this,"operators",[r.DataValidationOperator.BETWEEN,r.DataValidationOperator.EQUAL,r.DataValidationOperator.GREATER_THAN,r.DataValidationOperator.GREATER_THAN_OR_EQUAL,r.DataValidationOperator.LESS_THAN,r.DataValidationOperator.LESS_THAN_OR_EQUAL,r.DataValidationOperator.NOT_BETWEEN,r.DataValidationOperator.NOT_EQUAL]);S(this,"scopes",["sheet"])}_isFormulaOrNumber(e){return!r.Tools.isBlank(e)&&(r.isFormulaString(e)||!Number.isNaN(+e))}async isValidType(e,t,a){const{value:i}=e;return!Number.isNaN(X(i))}transform(e,t,a){const{value:i}=e;return{...e,value:X(i)}}_parseNumber(e){return e==null?Number.NaN:+e}async parseFormula(e,t,a,i,n){const l=await this._customFormulaService.getCellFormulaValue(t,a,e.uid,i,n),u=await this._customFormulaService.getCellFormula2Value(t,a,e.uid,i,n),{formula1:d,formula2:c}=e,h=E(String(l==null?void 0:l.v))&&E(String(u==null?void 0:u.v));return{formula1:this._parseNumber(r.isFormulaString(d)?l==null?void 0:l.v:d),formula2:this._parseNumber(r.isFormulaString(c)?u==null?void 0:u.v:c),isFormulaValid:h}}validatorFormula(e,t,a){const i=e.operator;if(!i)return{success:!0};const n=r.Tools.isDefine(e.formula1)&&this._isFormulaOrNumber(e.formula1),l=r.Tools.isDefine(e.formula2)&&this._isFormulaOrNumber(e.formula2),u=J.includes(i),d=this.localeService.t("dataValidation.validFail.number");return u?{success:n&&l,formula1:n?void 0:d,formula2:l?void 0:d}:{success:n,formula1:n?"":d}}generateRuleErrorMessage(e,t){if(!e.operator)return this.localeService.t(ee.NONE).replace("{TYPE}",this.titleStr);const{transformedFormula1:a,transformedFormula2:i}=Y(this._lexerTreeBuilder,e,t);return`${this.localeService.t(ee[e.operator]).replace(q,a!=null?a:"").replace(Q,i!=null?i:"")}`}}function he(o){if(!o)return[];const s=new Set;return o.forEach(e=>{e.forEach(t=>{var i,n;const a=w(t);if(a!=null){if(typeof a!="string"&&typeof(t==null?void 0:t.s)=="object"&&((n=(i=t.s)==null?void 0:i.n)!=null&&n.pattern)){s.add(r.numfmt.format(t.s.n.pattern,a,{throws:!1}));return}E(a.toString())&&s.add(a.toString())}})}),[...s]}const Je=["if","indirect","choose","offset"];function et(o,s){if(!r.isFormulaString(o)||y.isReferenceString(o.slice(1)))return!0;const t=s.sequenceNodesBuilder(o);return t&&t.some(a=>typeof a=="object"&&a.nodeType===y.sequenceNodeType.FUNCTION&&Je.indexOf(a.token.toLowerCase())>-1)}function tt(o,s){const{formula1:e="",ranges:t}=o;if(y.isReferenceString(e.slice(1))){const i=y.deserializeRangeWithSheet(e.slice(1));if((!i.sheetName||i.sheetName===s)&&t.some(n=>r.Rectangle.intersects(n,i.range)))return!0}return!1}class ge extends p.BaseDataValidator{constructor(){super(...arguments);S(this,"formulaService",this.injector.get(m.DataValidationFormulaService));S(this,"_lexer",this.injector.get(y.LexerTreeBuilder));S(this,"_univerInstanceService",this.injector.get(r.IUniverInstanceService));S(this,"order",50);S(this,"offsetFormulaByRange",!1);S(this,"id",r.DataValidationType.LIST);S(this,"title","dataValidation.list.title");S(this,"operators",[]);S(this,"scopes",["sheet"]);S(this,"skipDefaultFontRender",e=>e.renderMode!==r.DataValidationRenderMode.TEXT)}validatorFormula(e,t,a){var d,c,h;const i=!r.Tools.isBlank(e.formula1),n=et((d=e.formula1)!=null?d:"",this._lexer),l=(h=(c=this._univerInstanceService.getUnit(t,r.UniverInstanceType.UNIVER_SHEET))==null?void 0:c.getSheetBySheetId(a))==null?void 0:h.getName(),u=tt(e,l!=null?l:"");return{success:!!(i&&n&&!u),formula1:i?n?u?this.localeService.t("dataValidation.validFail.listIntersects"):void 0:this.localeService.t("dataValidation.validFail.listInvalid"):this.localeService.t("dataValidation.validFail.list")}}getExtraStyle(e,t,{style:a}){var n;const i=(n=a.tb!==r.WrapStrategy.OVERFLOW?a.tb:r.WrapStrategy.CLIP)!=null?n:r.WrapStrategy.WRAP;if(e.type===r.DataValidationType.LIST&&(e.renderMode===r.DataValidationRenderMode.ARROW||e.renderMode===r.DataValidationRenderMode.TEXT)){const l=this.getListWithColorMap(e),u=`${t!=null?t:""}`,d=l[u];if(d)return{bg:{rgb:d},tb:i}}return{tb:i}}parseCellValue(e){const t=e.toString();return G(t)}async parseFormula(e,t,a){var u,d;const i=await this.formulaService.getRuleFormulaResult(t,a,e.uid),n=U((d=(u=i==null?void 0:i[0])==null?void 0:u.result)==null?void 0:d[0][0]);return{formula1:void 0,formula2:void 0,isFormulaValid:E(String(n))}}async isValidType(e,t,a){var g,f;const{value:i,unitId:n,subUnitId:l}=e,{formula1:u=""}=a,d=await this.formulaService.getRuleFormulaResult(n,l,a.uid),c=r.isFormulaString(u)?he((f=(g=d==null?void 0:d[0])==null?void 0:g.result)==null?void 0:f[0][0]):G(u);return this.parseCellValue(i).every(R=>c.includes(R))}generateRuleName(){return this.localeService.t("dataValidation.list.name")}generateRuleErrorMessage(){return this.localeService.t("dataValidation.list.error")}getList(e,t,a){var g,f,R,_;const{formula1:i=""}=e,n=this.injector.get(r.IUniverInstanceService),l=(g=t?n.getUniverSheetInstance(t):void 0)!=null?g:n.getCurrentUnitForType(r.UniverInstanceType.UNIVER_SHEET);if(!l)return[];const u=(f=a?l.getSheetBySheetId(a):void 0)!=null?f:l.getActiveSheet();if(!u)return[];const d=l.getUnitId(),c=u.getSheetId(),h=this.formulaService.getRuleFormulaResultSync(d,c,e.uid);return r.isFormulaString(i)?he((_=(R=h==null?void 0:h[0])==null?void 0:R.result)==null?void 0:_[0][0]):G(i)}async getListAsync(e,t,a){var g,f,R,_;const{formula1:i=""}=e,n=this.injector.get(r.IUniverInstanceService),l=(g=t?n.getUniverSheetInstance(t):void 0)!=null?g:n.getCurrentUnitForType(r.UniverInstanceType.UNIVER_SHEET);if(!l)return[];const u=(f=a?l.getSheetBySheetId(a):void 0)!=null?f:l.getActiveSheet();if(!u)return[];const d=l.getUnitId(),c=u.getSheetId(),h=await this.formulaService.getRuleFormulaResult(d,c,e.uid);return r.isFormulaString(i)?he((_=(R=h==null?void 0:h[0])==null?void 0:R.result)==null?void 0:_[0][0]):G(i)}getListWithColor(e,t,a){const i=this.getList(e,t,a),n=(e.formula2||"").split(",");return i.map((l,u)=>({label:l,color:n[u]}))}getListWithColorMap(e,t,a){const i=this.getListWithColor(e,t,a),n={};return i.forEach(l=>{l.color&&(n[l.label]=l.color)}),n}}class at extends p.BaseDataValidator{constructor(){super(...arguments);S(this,"id",r.DataValidationType.TEXT_LENGTH);S(this,"title","dataValidation.textLength.title");S(this,"_lexerTreeBuilder",this.injector.get(y.LexerTreeBuilder));S(this,"order",30);S(this,"operators",[r.DataValidationOperator.BETWEEN,r.DataValidationOperator.EQUAL,r.DataValidationOperator.GREATER_THAN,r.DataValidationOperator.GREATER_THAN_OR_EQUAL,r.DataValidationOperator.LESS_THAN,r.DataValidationOperator.LESS_THAN_OR_EQUAL,r.DataValidationOperator.NOT_BETWEEN,r.DataValidationOperator.NOT_EQUAL]);S(this,"scopes",["sheet"]);S(this,"_customFormulaService",this.injector.get(m.DataValidationCustomFormulaService))}_isFormulaOrInt(e){return!r.Tools.isBlank(e)&&(r.isFormulaString(e)||!Number.isNaN(+e)&&Number.isInteger(+e))}validatorFormula(e,t,a){const i=e.operator;if(!i)return{success:!1};const n=r.Tools.isDefine(e.formula1)&&this._isFormulaOrInt(e.formula1),l=r.Tools.isDefine(e.formula2)&&this._isFormulaOrInt(e.formula2),u=J.includes(i),d=this.localeService.t("dataValidation.validFail.number");return u?{success:n&&l,formula1:n?void 0:d,formula2:l?void 0:d}:{success:n,formula1:d}}_parseNumber(e){return e==null?Number.NaN:+e}async parseFormula(e,t,a,i,n){const l=await this._customFormulaService.getCellFormulaValue(t,a,e.uid,i,n),u=await this._customFormulaService.getCellFormula2Value(t,a,e.uid,i,n),{formula1:d,formula2:c}=e,h=E(String(l==null?void 0:l.v))&&E(String(u==null?void 0:u.v));return{formula1:this._parseNumber(r.isFormulaString(d)?l==null?void 0:l.v:d),formula2:this._parseNumber(r.isFormulaString(c)?u==null?void 0:u.v:c),isFormulaValid:h}}transform(e,t,a){return{...e,value:e.value.toString().length}}async isValidType(e,t,a){const{value:i}=e;return typeof i=="string"||typeof i=="number"}generateRuleErrorMessage(e,t){if(!e.operator)return this.titleStr;const{transformedFormula1:a,transformedFormula2:i}=Y(this._lexerTreeBuilder,e,t);return`${this.localeService.t(p.TextLengthErrorTitleMap[e.operator]).replace(q,a!=null?a:"").replace(Q,i!=null?i:"")}`}}function Te(o){var e,t;return o?o.p?!((t=(e=o.p.body)==null?void 0:e.dataStream)!=null?t:"").slice(0,-2).trim():r.Tools.isBlank(o.v):!0}function K(o,s,e,t,a="command",i=!0){const n=t.get(y.LexerTreeBuilder),l=t.get(p.DataValidatorRegistryService),u=[],d=[],c=t.get(m.SheetDataValidationModel),h=t.get(r.IUniverInstanceService),g=D.getSheetCommandTarget(h,{unitId:o,subUnitId:s});if(!g)return{redoMutations:u,undoMutations:d};const{worksheet:f}=g,R=new r.ObjectMatrix;let _=!1;function V(v,M){i&&v.forEach(T=>{r.Range.foreach(T,(O,I)=>{const F=f.getCellRaw(O,I),B=Ve(F);(Te(F)||B===M)&&!(F!=null&&F.p)&&(_=!0,R.setValue(O,I,{v:M,p:null}))})})}if(e.forEach(v=>{switch(v.type){case"delete":u.push({id:p.RemoveDataValidationMutation.id,params:{unitId:o,subUnitId:s,ruleId:v.rule.uid,source:a}}),d.unshift({id:p.AddDataValidationMutation.id,params:{unitId:o,subUnitId:s,rule:v.rule,index:v.index,source:a}});break;case"update":{if(P(v.rule.type,l)){const T=v.oldRanges[0].startRow,O=v.oldRanges[0].startColumn,I=v.newRanges[0].startRow,F=v.newRanges[0].startColumn,B=I-T,oe=F-O,se=r.isFormulaString(v.rule.formula1)?n.moveFormulaRefOffset(v.rule.formula1,oe,B):v.rule.formula1,le=r.isFormulaString(v.rule.formula2)?n.moveFormulaRefOffset(v.rule.formula2,oe,B):v.rule.formula2;se!==v.rule.formula1||le!==v.rule.formula2||!r.isRangesEqual(v.newRanges,v.oldRanges)?(u.push({id:p.UpdateDataValidationMutation.id,params:{unitId:o,subUnitId:s,ruleId:v.ruleId,payload:{type:p.UpdateRuleType.ALL,payload:{formula1:se,formula2:le,ranges:v.newRanges}}}}),d.unshift({id:p.UpdateDataValidationMutation.id,params:{unitId:o,subUnitId:s,ruleId:v.ruleId,payload:{type:p.UpdateRuleType.ALL,payload:{formula1:v.rule.formula1,formula2:v.rule.formula2,ranges:v.oldRanges}}}})):(u.push({id:p.UpdateDataValidationMutation.id,params:{unitId:o,subUnitId:s,ruleId:v.ruleId,payload:{type:p.UpdateRuleType.RANGE,payload:v.newRanges},source:a}}),d.unshift({id:p.UpdateDataValidationMutation.id,params:{unitId:o,subUnitId:s,ruleId:v.ruleId,payload:{type:p.UpdateRuleType.RANGE,payload:v.oldRanges},source:a}}))}else u.push({id:p.UpdateDataValidationMutation.id,params:{unitId:o,subUnitId:s,ruleId:v.ruleId,payload:{type:p.UpdateRuleType.RANGE,payload:v.newRanges},source:a}}),d.unshift({id:p.UpdateDataValidationMutation.id,params:{unitId:o,subUnitId:s,ruleId:v.ruleId,payload:{type:p.UpdateRuleType.RANGE,payload:v.oldRanges},source:a}});const M=c.getRuleById(o,s,v.ruleId);if(M&&M.type===r.DataValidationType.CHECKBOX){const O=c.getValidator(r.DataValidationType.CHECKBOX).parseFormulaSync(M,o,s);V(v.newRanges,O.formula2)}break}case"add":{if(u.push({id:p.AddDataValidationMutation.id,params:{unitId:o,subUnitId:s,rule:v.rule,source:a}}),d.unshift({id:p.RemoveDataValidationMutation.id,params:{unitId:o,subUnitId:s,ruleId:v.rule.uid,source:a}}),v.rule.type===r.DataValidationType.CHECKBOX){const T=c.getValidator(r.DataValidationType.CHECKBOX).parseFormulaSync(v.rule,o,s);V(v.rule.ranges,T.originFormula2)}break}}}),_){const v={id:D.SetRangeValuesMutation.id,params:{unitId:o,subUnitId:s,cellValue:R.getData()}},M={id:D.SetRangeValuesMutation.id,params:D.SetRangeValuesUndoMutationFactory(t,v.params)};u.push(v),d.push(M)}return{redoMutations:u,undoMutations:d}}const Oe={type:r.CommandType.COMMAND,id:"sheet.command.updateDataValidationRuleRange",handler(o,s){if(!s)return!1;const{unitId:e,subUnitId:t,ranges:a,ruleId:i}=s,n=o.get(m.SheetDataValidationModel),l=o.get(r.ICommandService),u=o.get(r.IUndoRedoService);if(!n.getRuleById(e,t,i))return!1;const c=n.getRuleObjectMatrix(e,t).clone();c.updateRange(i,a);const h=c.diff(n.getRules(e,t)),{redoMutations:g,undoMutations:f}=K(e,t,h,o);return u.pushUndoRedo({undoMutations:f,redoMutations:g,unitID:e}),r.sequenceExecute(g,l),!0}},Fe={type:r.CommandType.COMMAND,id:"sheet.command.addDataValidation",handler(o,s){if(!s)return!1;const{unitId:e,subUnitId:t,rule:a}=s,i=o.get(m.SheetDataValidationModel),n=o.get(r.ICommandService),l=o.get(r.IUndoRedoService),u=i.getRuleObjectMatrix(e,t).clone();u.addRule(a);const d=u.diff(i.getRules(e,t)),c=i.getValidator(a.type),h={unitId:e,subUnitId:t,rule:{...a,...c==null?void 0:c.normalizeFormula(a,e,t)}},{redoMutations:g,undoMutations:f}=K(e,t,d,o);return g.push({id:p.AddDataValidationMutation.id,params:h}),f.unshift({id:p.RemoveDataValidationMutation.id,params:{unitId:e,subUnitId:t,ruleId:a.uid}}),l.pushUndoRedo({unitID:e,redoMutations:g,undoMutations:f}),r.sequenceExecute(g,n),!0}},Ie={type:r.CommandType.COMMAND,id:"sheets.command.update-data-validation-setting",handler(o,s){if(!s)return!1;const e=o.get(r.ICommandService),t=o.get(r.IUndoRedoService),a=o.get(m.SheetDataValidationModel),i=o.get(p.DataValidatorRegistryService),{unitId:n,subUnitId:l,ruleId:u,setting:d}=s,c=i.getValidatorItem(d.type);if(!c)return!1;const h=a.getRuleById(n,l,u);if(!h)return!1;const g={...h,...d};if(!c.validatorFormula(g,n,l).success)return!1;const f={unitId:n,subUnitId:l,ruleId:u,payload:{type:p.UpdateRuleType.SETTING,payload:{...d,...c.normalizeFormula(g,n,l)}}},R=[{id:p.UpdateDataValidationMutation.id,params:f}],_={unitId:n,subUnitId:l,ruleId:u,payload:{type:p.UpdateRuleType.SETTING,payload:p.getRuleSetting(h)}},V=[{id:p.UpdateDataValidationMutation.id,params:_}];if(d.type===r.DataValidationType.CHECKBOX){const M=h.ranges,T=o.get(r.IUniverInstanceService),O=D.getSheetCommandTarget(T,{unitId:n,subUnitId:l});if(O){const I=new r.ObjectMatrix,{worksheet:F}=O,{formula2:B=k,formula1:oe=$}=h,{formula2:se=k,formula1:le=$}=d;let Re=!1;if(M.forEach(ue=>{r.Range.foreach(ue,(z,_e)=>{const C=F.getCellRaw(z,_e),Pe=Ve(C);(Te(C)||Pe===String(B))&&!(C!=null&&C.p)?(I.setValue(z,_e,{v:se,p:null}),Re=!0):Pe===String(oe)&&!(C!=null&&C.p)&&(I.setValue(z,_e,{v:le,p:null}),Re=!0)})}),Re){const ue={id:D.SetRangeValuesMutation.id,params:{unitId:n,subUnitId:l,cellValue:I.getData()}},z={id:D.SetRangeValuesMutation.id,params:D.SetRangeValuesUndoMutationFactory(o,ue.params)};R.push(ue),V.push(z)}}}return r.sequenceExecute(R,e).result?(t.pushUndoRedo({unitID:n,redoMutations:R,undoMutations:V}),!0):!1}},Ce={type:r.CommandType.COMMAND,id:"sheets.command.update-data-validation-options",handler(o,s){if(!s)return!1;const e=o.get(r.ICommandService),t=o.get(r.IUndoRedoService),a=o.get(m.SheetDataValidationModel),{unitId:i,subUnitId:n,ruleId:l,options:u}=s,d=a.getRuleById(i,n,l);if(!d)return!1;const c={unitId:i,subUnitId:n,ruleId:l,payload:{type:p.UpdateRuleType.OPTIONS,payload:u}},h=[{id:p.UpdateDataValidationMutation.id,params:c}],g={unitId:i,subUnitId:n,ruleId:l,payload:{type:p.UpdateRuleType.OPTIONS,payload:p.getRuleOptions(d)}},f=[{id:p.UpdateDataValidationMutation.id,params:g}];return t.pushUndoRedo({unitID:i,redoMutations:h,undoMutations:f}),e.executeCommand(p.UpdateDataValidationMutation.id,c),!0}},Ne={type:r.CommandType.COMMAND,id:"sheets.command.clear-range-data-validation",handler(o,s){if(!s)return!1;const{unitId:e,subUnitId:t,ranges:a}=s,i=o.get(r.ICommandService),n=o.get(r.IUniverInstanceService),l=D.getSheetCommandTarget(n,{unitId:e,subUnitId:t}),u=o.get(m.SheetDataValidationModel);if(!l)return!1;const d=o.get(r.IUndoRedoService),c=u.getRuleObjectMatrix(e,t).clone();c.removeRange(a);const h=c.diff(u.getRules(e,t)),{redoMutations:g,undoMutations:f}=K(e,t,h,o);return d.pushUndoRedo({unitID:e,redoMutations:g,undoMutations:f}),r.sequenceExecute(g,i).result}},Ae={type:r.CommandType.COMMAND,id:"sheet.command.remove-all-data-validation",handler(o,s){if(!s)return!1;const{unitId:e,subUnitId:t}=s,a=o.get(r.ICommandService),i=o.get(m.SheetDataValidationModel),n=o.get(r.IUndoRedoService),l=[...i.getRules(e,t)],u={unitId:e,subUnitId:t,ruleId:l.map(h=>h.uid)},d=[{id:p.RemoveDataValidationMutation.id,params:u}],c=[{id:p.AddDataValidationMutation.id,params:{unitId:e,subUnitId:t,rule:l}}];return n.pushUndoRedo({redoMutations:d,undoMutations:c,unitID:e}),a.executeCommand(p.RemoveDataValidationMutation.id,u),!0}},it=(o,s)=>{const e=o.get(m.SheetDataValidationModel),{unitId:t,subUnitId:a,ruleId:i,source:n}=s;if(Array.isArray(i)){const u=i.map(d=>e.getRuleById(t,a,d)).filter(Boolean);return[{id:p.AddDataValidationMutation.id,params:{unitId:t,subUnitId:a,rule:u,source:n}}]}return[{id:p.AddDataValidationMutation.id,params:{unitId:t,subUnitId:a,rule:{...e.getRuleById(t,a,i)},index:e.getRuleIndex(t,a,i)}}]},Ue={type:r.CommandType.COMMAND,id:"sheet.command.remove-data-validation-rule",handler(o,s){if(!s)return!1;const{unitId:e,subUnitId:t,ruleId:a}=s,i=o.get(r.ICommandService),n=o.get(r.IUndoRedoService),l=o.get(m.SheetDataValidationModel),u=[{id:p.RemoveDataValidationMutation.id,params:s}],d=[{id:p.AddDataValidationMutation.id,params:{unitId:e,subUnitId:t,rule:{...l.getRuleById(e,t,a)},index:l.getRuleIndex(e,t,a)}}];return n.pushUndoRedo({undoMutations:d,redoMutations:u,unitID:s.unitId}),i.executeCommand(p.RemoveDataValidationMutation.id,s),!0}},we="SHEET_DATA_VALIDATION_PLUGIN";var Le=(o=>(o[o.View=0]="View",o[o.Edit=1]="Edit",o[o.ManageCollaborator=2]="ManageCollaborator",o[o.Print=3]="Print",o[o.Duplicate=4]="Duplicate",o[o.Comment=5]="Comment",o[o.Copy=6]="Copy",o[o.Share=7]="Share",o[o.Export=8]="Export",o[o.MoveWorksheet=9]="MoveWorksheet",o[o.DeleteWorksheet=10]="DeleteWorksheet",o[o.HideWorksheet=11]="HideWorksheet",o[o.RenameWorksheet=12]="RenameWorksheet",o[o.CreateWorksheet=13]="CreateWorksheet",o[o.SetWorksheetStyle=14]="SetWorksheetStyle",o[o.EditWorksheetCell=15]="EditWorksheetCell",o[o.InsertHyperlink=16]="InsertHyperlink",o[o.Sort=17]="Sort",o[o.Filter=18]="Filter",o[o.PivotTable=19]="PivotTable",o[o.FloatImg=20]="FloatImg",o[o.History=21]="History",o[o.RwHgtClWdt=22]="RwHgtClWdt",o[o.ViemRwHgtClWdt=23]="ViemRwHgtClWdt",o[o.ViewFilter=24]="ViewFilter",o[o.MoveSheet=25]="MoveSheet",o[o.DeleteSheet=26]="DeleteSheet",o[o.HideSheet=27]="HideSheet",o[o.CopySheet=28]="CopySheet",o[o.RenameSheet=29]="RenameSheet",o[o.CreateSheet=30]="CreateSheet",o[o.SelectProtectedCells=31]="SelectProtectedCells",o[o.SelectUnProtectedCells=32]="SelectUnProtectedCells",o[o.SetCellStyle=33]="SetCellStyle",o[o.SetCellValue=34]="SetCellValue",o[o.SetRowStyle=35]="SetRowStyle",o[o.SetColumnStyle=36]="SetColumnStyle",o[o.InsertRow=37]="InsertRow",o[o.InsertColumn=38]="InsertColumn",o[o.DeleteRow=39]="DeleteRow",o[o.DeleteColumn=40]="DeleteColumn",o[o.EditExtraObject=41]="EditExtraObject",o[o.Delete=42]="Delete",o[o.RecoverHistory=43]="RecoverHistory",o[o.ViewHistory=44]="ViewHistory",o[o.CreatePermissionObject=45]="CreatePermissionObject",o[o.UNRECOGNIZED=-1]="UNRECOGNIZED",o))(Le||{}),rt=Object.getOwnPropertyDescriptor,nt=(o,s,e,t)=>{for(var a=t>1?void 0:t?rt(s,e):s,i=o.length-1,n;i>=0;i--)(n=o[i])&&(a=n(a)||a);return a},pe=(o,s)=>(e,t)=>s(e,t,o);m.DataValidationFormulaController=class extends r.Disposable{constructor(s,e,t){super(),this._univerInstanceService=s,this._permissionService=e,this._lexerTreeBuilder=t}getFormulaRefCheck(s){var t,a;const e=this._lexerTreeBuilder.sequenceNodesBuilder(s);if(!e)return!0;for(let i=0;i<e.length;i++){const n=e[i];if(typeof n=="string")continue;const{token:l}=n,u=y.deserializeRangeWithSheetWithCache(l),d=this._univerInstanceService.getCurrentUnitForType(r.UniverInstanceType.UNIVER_SHEET);let c=d.getActiveSheet();const h=d.getUnitId();if(u.sheetName){if(c=d.getSheetBySheetName(u.sheetName),!c)return!1;const V=c==null?void 0:c.getSheetId();if(!this._permissionService.getPermissionPoint(new D.WorksheetViewPermission(h,V).id))return!1}if(!c)return!1;const{startRow:g,endRow:f,startColumn:R,endColumn:_}=u.range;for(let V=g;V<=f;V++)for(let v=R;v<=_;v++){const M=(a=(t=c.getCell(V,v))==null?void 0:t.selectionProtection)==null?void 0:a[0];if((M==null?void 0:M[Le.View])===!1)return!1}}return!0}},m.DataValidationFormulaController=nt([pe(0,r.IUniverInstanceService),pe(1,r.IPermissionService),pe(2,r.Inject(y.LexerTreeBuilder))],m.DataValidationFormulaController);const ot="sheets-data-validation.config",be={};var st=Object.getOwnPropertyDescriptor,lt=(o,s,e,t)=>{for(var a=t>1?void 0:t?st(s,e):s,i=o.length-1,n;i>=0;i--)(n=o[i])&&(a=n(a)||a);return a},Se=(o,s)=>(e,t)=>s(e,t,o);let te=class extends r.Disposable{constructor(s,e,t){super();S(this,"_disposableMap",new Map);S(this,"registerRule",(s,e,t)=>{P(t.type,this._validatorRegistryService)&&this.register(s,e,t)});this._dataValidationModel=s,this._formulaRefRangeService=e,this._validatorRegistryService=t,this._initRefRange()}_getIdWithUnitId(s,e,t){return`${s}_${e}_${t}`}register(s,e,t){const a=t.ranges,i=t.formula1,n=t.formula2,l=this._formulaRefRangeService.registerRangeFormula(s,e,a,[i!=null?i:"",n!=null?n:""],d=>{if(d.length===0)return{undos:[{id:p.AddDataValidationMutation.id,params:{unitId:s,subUnitId:e,rule:t,source:"patched"}}],redos:[{id:p.RemoveDataValidationMutation.id,params:{unitId:s,subUnitId:e,ruleId:t.uid,source:"patched"}}]};const c=[],h=[],g=d[0];c.push({id:p.UpdateDataValidationMutation.id,params:{unitId:s,subUnitId:e,ruleId:t.uid,payload:{type:p.UpdateRuleType.ALL,payload:{ranges:g.ranges,formula1:g.formulas[0],formula2:g.formulas[1]}},source:"patched"}}),h.push({id:p.UpdateDataValidationMutation.id,params:{unitId:s,subUnitId:e,ruleId:t.uid,payload:{type:p.UpdateRuleType.ALL,payload:{ranges:a,formula1:i,formula2:n}},source:"patched"}});for(let f=1;f<d.length;f++){const R=d[f],_=r.generateRandomId();c.push({id:p.AddDataValidationMutation.id,params:{unitId:s,subUnitId:e,rule:{...t,uid:_,formula1:R.formulas[0],formula2:R.formulas[1],ranges:R.ranges},source:"patched"}}),h.push({id:p.RemoveDataValidationMutation.id,params:{unitId:s,subUnitId:e,ruleId:_,source:"patched"}})}return{undos:h,redos:c}}),u=this._getIdWithUnitId(s,e,t.uid);this._disposableMap.set(u,l)}_initRefRange(){const s=this._dataValidationModel.getAll();for(const[e,t]of s)for(const[a,i]of t)for(const n of i)this.registerRule(e,a,n);this.disposeWithMe(this._dataValidationModel.ruleChange$.subscribe(e=>{const{unitId:t,subUnitId:a,rule:i}=e;switch(e.type){case"add":{const n=e.rule;this.registerRule(e.unitId,e.subUnitId,n);break}case"remove":{const n=this._disposableMap.get(this._getIdWithUnitId(t,a,i.uid));n&&n.dispose();break}case"update":{const n=e.rule,l=this._disposableMap.get(this._getIdWithUnitId(t,a,n.uid));l&&l.dispose(),this.registerRule(e.unitId,e.subUnitId,n);break}}})),this.disposeWithMe(r.toDisposable(()=>{this._disposableMap.forEach(e=>{e.dispose()}),this._disposableMap.clear()}))}};te=lt([Se(0,r.Inject(m.SheetDataValidationModel)),Se(1,r.Inject(Z.FormulaRefRangeService)),Se(2,r.Inject(p.DataValidatorRegistryService))],te);var ut=Object.getOwnPropertyDescriptor,dt=(o,s,e,t)=>{for(var a=t>1?void 0:t?ut(s,e):s,i=o.length-1,n;i>=0;i--)(n=o[i])&&(a=n(a)||a);return a},L=(o,s)=>(e,t)=>s(e,t,o);let ae=class extends r.Disposable{constructor(s,e,t,a,i,n){super();S(this,"_disposableMap",new Map);S(this,"registerRule",(s,e,t)=>{P(t.type,this._validatorRegistryService)||(this.register(s,e,t),this.registerFormula(s,e,t))});this._dataValidationModel=s,this._injector=e,this._refRangeService=t,this._dataValidationFormulaService=a,this._formulaRefRangeService=i,this._validatorRegistryService=n,this._initRefRange()}_getIdWithUnitId(s,e,t){return`${s}_${e}_${t}`}registerFormula(s,e,t){var d;const a=t.uid,i=this._getIdWithUnitId(s,e,a),n=(d=this._disposableMap.get(i))!=null?d:new Set,l=(c,h)=>{const g=this._dataValidationModel.getRuleById(s,e,a);if(!g)return{redos:[],undos:[]};const f=g[c];if(!f||f===h)return{redos:[],undos:[]};const R={unitId:s,subUnitId:e,ruleId:t.uid,payload:{type:p.UpdateRuleType.SETTING,payload:{type:g.type,formula1:g.formula1,formula2:g.formula2,[c]:h}},source:"patched"},_={unitId:s,subUnitId:e,ruleId:t.uid,payload:{type:p.UpdateRuleType.SETTING,payload:{type:g.type,formula1:g.formula1,formula2:g.formula2}},source:"patched"},V=[{id:p.UpdateDataValidationMutation.id,params:R}],v=[{id:p.UpdateDataValidationMutation.id,params:_}];return{redos:V,undos:v}},u=this._dataValidationFormulaService.getRuleFormulaInfo(s,e,a);if(u){const[c,h]=u;if(c){const g=this._formulaRefRangeService.registerFormula(s,e,c.text,f=>l("formula1",f));n.add(()=>g.dispose())}if(h){const g=this._formulaRefRangeService.registerFormula(s,e,h.text,f=>l("formula2",f));n.add(()=>g.dispose())}}}register(s,e,t){var u;const a=d=>{const c=[...t.ranges],g=c.map(R=>D.handleCommonDefaultRangeChangeWithEffectRefCommands(R,d)).filter(R=>!!R).flat();if(r.isRangesEqual(g,c))return{redos:[],undos:[]};if(g.length){const R={unitId:s,subUnitId:e,ruleId:t.uid,payload:{type:p.UpdateRuleType.RANGE,payload:g},source:"patched"},_=[{id:p.UpdateDataValidationMutation.id,params:R}],V=[{id:p.UpdateDataValidationMutation.id,params:{unitId:s,subUnitId:e,ruleId:t.uid,payload:{type:p.UpdateRuleType.RANGE,payload:c},source:"patched"}}];return{redos:_,undos:V}}else{const R={unitId:s,subUnitId:e,ruleId:t.uid},_=[{id:p.RemoveDataValidationMutation.id,params:R}],V=it(this._injector,R);return{redos:_,undos:V}}},i=[];t.ranges.forEach(d=>{const c=this._refRangeService.registerRefRange(d,a,s,e);i.push(()=>c.dispose())});const n=this._getIdWithUnitId(s,e,t.uid),l=(u=this._disposableMap.get(n))!=null?u:new Set;l.add(()=>i.forEach(d=>d())),this._disposableMap.set(n,l)}_initRefRange(){const s=this._dataValidationModel.getAll();for(const[e,t]of s)for(const[a,i]of t)for(const n of i)this.registerRule(e,a,n);this.disposeWithMe(this._dataValidationModel.ruleChange$.subscribe(e=>{const{unitId:t,subUnitId:a,rule:i}=e;switch(e.type){case"add":{const n=e.rule;this.registerRule(e.unitId,e.subUnitId,n);break}case"remove":{const n=this._disposableMap.get(this._getIdWithUnitId(t,a,i.uid));n&&n.forEach(l=>l());break}case"update":{const n=e.rule,l=this._disposableMap.get(this._getIdWithUnitId(t,a,n.uid));l&&l.forEach(u=>u()),this.registerRule(e.unitId,e.subUnitId,n);break}}})),this.disposeWithMe(r.toDisposable(()=>{this._disposableMap.forEach(e=>{e.forEach(t=>t())}),this._disposableMap.clear()}))}};ae=dt([L(0,r.Inject(m.SheetDataValidationModel)),L(1,r.Inject(r.Injector)),L(2,r.Inject(D.RefRangeService)),L(3,r.Inject(m.DataValidationFormulaService)),L(4,r.Inject(Z.FormulaRefRangeService)),L(5,r.Inject(p.DataValidatorRegistryService))],ae);var ct=Object.getOwnPropertyDescriptor,mt=(o,s,e,t)=>{for(var a=t>1?void 0:t?ct(s,e):s,i=o.length-1,n;i>=0;i--)(n=o[i])&&(a=n(a)||a);return a},fe=(o,s)=>(e,t)=>s(e,t,o);let ie=class extends r.Disposable{constructor(o,s,e){super(),this._sheetInterceptorService=o,this._univerInstanceService=s,this._sheetDataValidationModel=e,this._initSheetChange()}_initSheetChange(){this.disposeWithMe(this._sheetInterceptorService.interceptCommand({getMutations:o=>{var s;if(o.id===D.RemoveSheetCommand.id){const e=o.params,t=e.unitId||this._univerInstanceService.getCurrentUnitForType(r.UniverInstanceType.UNIVER_SHEET).getUnitId(),a=this._univerInstanceService.getUniverSheetInstance(t);if(!a)return{redos:[],undos:[]};const i=e.subUnitId||((s=a.getActiveSheet())==null?void 0:s.getSheetId());if(!i)return{redos:[],undos:[]};const n=this._sheetDataValidationModel.getRules(t,i);if(n.length===0)return{redos:[],undos:[]};const l=n.map(c=>c.uid),u={unitId:t,subUnitId:i,ruleId:l,source:"patched"},d={unitId:t,subUnitId:i,rule:[...n],source:"patched"};return{redos:[{id:p.RemoveDataValidationMutation.id,params:u}],undos:[{id:p.AddDataValidationMutation.id,params:d}]}}else if(o.id===D.CopySheetCommand.id){const e=o.params,{unitId:t,subUnitId:a,targetSubUnitId:i}=e;if(!t||!a||!i)return{redos:[],undos:[]};const n=this._sheetDataValidationModel.getRules(t,a);if(n.length===0)return{redos:[],undos:[]};const l=n.map(u=>({...u,uid:r.generateRandomId(6)}));return{redos:[{id:p.AddDataValidationMutation.id,params:{unitId:t,subUnitId:i,rule:l,source:"patched"}}],undos:[{id:p.RemoveDataValidationMutation.id,params:{unitId:t,subUnitId:i,ruleId:l.map(u=>u.uid),source:"patched"}}]}}return{redos:[],undos:[]}}}))}};ie=mt([fe(0,r.Inject(D.SheetInterceptorService)),fe(1,r.Inject(r.IUniverInstanceService)),fe(2,r.Inject(m.SheetDataValidationModel))],ie);class ht extends p.BaseDataValidator{constructor(){super(...arguments);S(this,"id",r.DataValidationType.ANY);S(this,"title","dataValidation.any.title");S(this,"operators",[]);S(this,"scopes",["sheet"]);S(this,"order",0);S(this,"offsetFormulaByRange",!1)}async parseFormula(e,t,a){return{formula1:e.formula1,formula2:e.formula2,isFormulaValid:!0}}validatorFormula(e,t,a){return{success:!0}}async isValidType(e,t,a){return!0}generateRuleErrorMessage(e){return this.localeService.t("dataValidation.any.error")}}class gt extends p.BaseDataValidator{constructor(){super(...arguments);S(this,"id",r.DataValidationType.CUSTOM);S(this,"title","dataValidation.custom.title");S(this,"operators",[]);S(this,"scopes",["sheet"]);S(this,"order",60);S(this,"_customFormulaService",this.injector.get(m.DataValidationCustomFormulaService));S(this,"_lexerTreeBuilder",this.injector.get(y.LexerTreeBuilder))}validatorFormula(e,t,a){var d;const i=r.isFormulaString(e.formula1),n=(d=e.formula1)!=null?d:"",u=this._lexerTreeBuilder.checkIfAddBracket(n)===0&&n.startsWith(y.operatorToken.EQUALS);return{success:i&&u,formula1:i&&u?"":this.localeService.t("dataValidation.validFail.formula")}}async parseFormula(e,t,a){return{formula1:void 0,formula2:void 0,isFormulaValid:!0}}async isValidType(e,t,a){const{column:i,row:n,unitId:l,subUnitId:u}=e,d=await this._customFormulaService.getCellFormulaValue(l,u,a.uid,n,i),c=d==null?void 0:d.v;return E(String(c))&&r.Tools.isDefine(c)&&c!==""?d.t===r.CellValueType.BOOLEAN?!!c:typeof c=="boolean"?c:typeof c=="number"?!!c:typeof c=="string"?E(c):!!c:!1}generateRuleErrorMessage(e){return this.localeService.t("dataValidation.custom.error")}generateRuleName(e){var t;return this.localeService.t("dataValidation.custom.ruleName").replace("{FORMULA1}",(t=e.formula1)!=null?t:"")}}class Be extends ge{constructor(){super(...arguments);S(this,"id",r.DataValidationType.LIST_MULTIPLE);S(this,"title","dataValidation.listMultiple.title");S(this,"offsetFormulaByRange",!1);S(this,"skipDefaultFontRender",()=>!0)}}class pt extends p.BaseDataValidator{constructor(){super(...arguments);S(this,"_customFormulaService",this.injector.get(m.DataValidationCustomFormulaService));S(this,"_lexerTreeBuilder",this.injector.get(y.LexerTreeBuilder));S(this,"id",r.DataValidationType.WHOLE);S(this,"title","dataValidation.whole.title");S(this,"order",10);S(this,"operators",[r.DataValidationOperator.BETWEEN,r.DataValidationOperator.EQUAL,r.DataValidationOperator.GREATER_THAN,r.DataValidationOperator.GREATER_THAN_OR_EQUAL,r.DataValidationOperator.LESS_THAN,r.DataValidationOperator.LESS_THAN_OR_EQUAL,r.DataValidationOperator.NOT_BETWEEN,r.DataValidationOperator.NOT_EQUAL]);S(this,"scopes",["sheet"])}_isFormulaOrInt(e){return!r.Tools.isBlank(e)&&(r.isFormulaString(e)||!Number.isNaN(+e)&&Number.isInteger(+e))}async isValidType(e,t,a){const{value:i}=e,n=X(i);return!Number.isNaN(n)&&Number.isInteger(n)}transform(e,t,a){const{value:i}=e;return{...e,value:X(i)}}_parseNumber(e){return e==null?Number.NaN:+e}async parseFormula(e,t,a,i,n){const l=await this._customFormulaService.getCellFormulaValue(t,a,e.uid,i,n),u=await this._customFormulaService.getCellFormula2Value(t,a,e.uid,i,n),{formula1:d,formula2:c}=e,h=r.isFormulaString(d)?l==null?void 0:l.v:d,g=r.isFormulaString(c)?u==null?void 0:u.v:c,f=E(`${h}`)&&E(`${g}`);return{formula1:this._parseNumber(h),formula2:this._parseNumber(g),isFormulaValid:f}}validatorFormula(e,t,a){const i=e.operator;if(!i)return{success:!0};const n=r.Tools.isDefine(e.formula1)&&this._isFormulaOrInt(e.formula1),l=r.Tools.isDefine(e.formula2)&&this._isFormulaOrInt(e.formula2),u=J.includes(i),d=this.localeService.t("dataValidation.validFail.number");return u?{success:n&&l,formula1:n?void 0:d,formula2:l?void 0:d}:{success:n,formula1:d}}generateRuleErrorMessage(e,t){if(!e.operator)return this.localeService.t(ee.NONE).replace("{TYPE}",this.titleStr);const{transformedFormula1:a,transformedFormula2:i}=Y(this._lexerTreeBuilder,e,t);return`${this.localeService.t(ee[e.operator]).replace(q,a!=null?a:"").replace(Q,i!=null?i:"")}`}}var St=Object.getOwnPropertyDescriptor,ft=(o,s,e,t)=>{for(var a=t>1?void 0:t?St(s,e):s,i=o.length-1,n;i>=0;i--)(n=o[i])&&(a=n(a)||a);return a},b=(o,s)=>(e,t)=>s(e,t,o);let re=class extends r.RxDisposable{constructor(o,s,e,t,a,i){super(),this._univerInstanceService=o,this._dataValidatorRegistryService=s,this._injector=e,this._selectionManagerService=t,this._sheetInterceptorService=a,this._sheetDataValidationModel=i,this._init()}_init(){this._registerValidators(),this._initCommandInterceptor()}_registerValidators(){[ht,Ze,pt,at,ye,Me,ge,Be,gt].forEach(o=>{const s=this._injector.createInstance(o);this.disposeWithMe(this._dataValidatorRegistryService.register(s)),this.disposeWithMe(r.toDisposable(()=>this._injector.delete(o)))})}_initCommandInterceptor(){this._sheetInterceptorService.interceptCommand({getMutations:o=>{var s;if(o.id===D.ClearSelectionAllCommand.id){const e=this._univerInstanceService.getCurrentUnitForType(r.UniverInstanceType.UNIVER_SHEET),t=e.getUnitId(),a=e.getActiveSheet();if(!a)throw new Error("No active sheet found");const i=a.getSheetId(),n=(s=this._selectionManagerService.getCurrentSelections())==null?void 0:s.map(h=>h.range),l=this._sheetDataValidationModel.getRuleObjectMatrix(t,i).clone();n&&l.removeRange(n);const u=l.diff(this._sheetDataValidationModel.getRules(t,i)),{redoMutations:d,undoMutations:c}=K(t,i,u,this._injector,"patched");return{undos:c,redos:d}}return{undos:[],redos:[]}}})}};re=ft([b(0,r.IUniverInstanceService),b(1,r.Inject(p.DataValidatorRegistryService)),b(2,r.Inject(r.Injector)),b(3,r.Inject(D.SheetsSelectionsService)),b(4,r.Inject(D.SheetInterceptorService)),b(5,r.Inject(m.SheetDataValidationModel))],re);var vt=Object.getOwnPropertyDescriptor,Rt=(o,s,e,t)=>{for(var a=t>1?void 0:t?vt(s,e):s,i=o.length-1,n;i>=0;i--)(n=o[i])&&(a=n(a)||a);return a},ne=(o,s)=>(e,t)=>s(e,t,o);m.SheetsDataValidationValidatorService=class extends r.Disposable{constructor(s,e,t,a){super(),this._univerInstanceService=s,this._sheetDataValidationModel=e,this._dataValidationCacheService=t,this._lifecycleService=a,this._initRecalculate()}_initRecalculate(){const s=e=>{if(e.length===0)return;const t=this._univerInstanceService.getCurrentUnitForType(r.UniverInstanceType.UNIVER_SHEET),a=t==null?void 0:t.getActiveSheet(),i={};e.flat().forEach(n=>{i[n.unitId]||(i[n.unitId]={}),i[n.unitId][n.subUnitId]||(i[n.unitId][n.subUnitId]=[]);const l=this._univerInstanceService.getUnit(n.unitId,r.UniverInstanceType.UNIVER_SHEET),u=l==null?void 0:l.getSheetBySheetId(n.subUnitId);u&&i[n.unitId][n.subUnitId].push(...n.ranges.map(d=>r.Range.transformRange(d,u)))}),Object.entries(i).forEach(([n,l])=>{Object.entries(l).forEach(([u,d])=>{(t==null?void 0:t.getUnitId())===n&&(a==null?void 0:a.getSheetId())===u?this.validatorRanges(n,u,d):requestIdleCallback(()=>{this.validatorRanges(n,u,d)})})})};this.disposeWithMe(this._dataValidationCacheService.dirtyRanges$.pipe(A.bufferWhen(()=>this._lifecycleService.lifecycle$.pipe(A.filter(e=>e===r.LifecycleStages.Rendered)))).subscribe(s)),this.disposeWithMe(this._dataValidationCacheService.dirtyRanges$.pipe(A.filter(()=>this._lifecycleService.stage>=r.LifecycleStages.Rendered),r.bufferDebounceTime(20)).subscribe(s))}async _validatorByCell(s,e,t,a){const i=s.getUnitId(),n=e.getSheetId();if(!r.Tools.isDefine(t)||!r.Tools.isDefine(a))throw new Error(`row or col is not defined, row: ${t}, col: ${a}`);const l=this._sheetDataValidationModel.getRuleByLocation(i,n,t,a);return l?new Promise(u=>{this._sheetDataValidationModel.validator(l,{unitId:i,subUnitId:n,row:t,col:a,worksheet:e,workbook:s},d=>{u(d)})}):r.DataValidationStatus.VALID}async validatorCell(s,e,t,a){const i=this._univerInstanceService.getUnit(s,r.UniverInstanceType.UNIVER_SHEET);if(!i)throw new Error(`cannot find current workbook, unitId: ${s}`);const n=i.getSheetBySheetId(e);if(!n)throw new Error(`cannot find current worksheet, sheetId: ${e}`);return this._validatorByCell(i,n,t,a)}validatorRanges(s,e,t){if(!t.length)return Promise.resolve([]);const a=this._univerInstanceService.getUnit(s,r.UniverInstanceType.UNIVER_SHEET);if(!a)throw new Error(`cannot find current workbook, unitId: ${s}`);const i=a.getSheetBySheetId(e);if(!i)throw new Error(`cannot find current worksheet, sheetId: ${e}`);const l=this._sheetDataValidationModel.getRules(s,e).map(d=>d.ranges).flat(),u=t.map(d=>l.map(c=>r.getIntersectRange(d,c))).flat().filter(Boolean);return Promise.all(u.map(d=>{const c=[];return r.Range.foreach(d,(h,g)=>{c.push(this._validatorByCell(a,i,h,g))}),Promise.all(c)}))}async validatorWorksheet(s,e){const t=this._univerInstanceService.getUnit(s,r.UniverInstanceType.UNIVER_SHEET);if(!t)throw new Error(`cannot find current workbook, unitId: ${s}`);const a=t.getSheetBySheetId(e);if(!a)throw new Error(`cannot find current worksheet, sheetId: ${e}`);const i=this._sheetDataValidationModel.getRules(s,e);return await Promise.all(i.map(n=>Promise.all(n.ranges.map(l=>{const u=[];return r.Range.foreach(l,(d,c)=>{u.push(this._validatorByCell(t,a,d,c))}),Promise.all(u)})))),this._dataValidationCacheService.ensureCache(s,e)}async validatorWorkbook(s){const e=this._sheetDataValidationModel.getSubUnitIds(s),t=await Promise.all(e.map(i=>this.validatorWorksheet(s,i))),a={};return t.forEach((i,n)=>{a[e[n]]=i}),a}getDataValidations(s,e,t){const a=this._sheetDataValidationModel.getRuleObjectMatrix(s,e),i=new Set;return t.forEach(l=>{r.Range.foreach(l,(u,d)=>{const c=a.getValue(u,d);c&&i.add(c)})}),Array.from(i).map(l=>this._sheetDataValidationModel.getRuleById(s,e,l)).filter(Boolean)}getDataValidation(s,e,t){return this.getDataValidations(s,e,t)[0]}},m.SheetsDataValidationValidatorService=Rt([ne(0,r.IUniverInstanceService),ne(1,r.Inject(m.SheetDataValidationModel)),ne(2,r.Inject(m.DataValidationCacheService)),ne(3,r.Inject(r.LifecycleService))],m.SheetsDataValidationValidatorService);var _t=Object.defineProperty,Vt=Object.getOwnPropertyDescriptor,Dt=(o,s,e)=>s in o?_t(o,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[s]=e,Mt=(o,s,e,t)=>{for(var a=t>1?void 0:t?Vt(s,e):s,i=o.length-1,n;i>=0;i--)(n=o[i])&&(a=n(a)||a);return a},ve=(o,s)=>(e,t)=>s(e,t,o),je=(o,s,e)=>Dt(o,typeof s!="symbol"?s+"":s,e);m.UniverSheetsDataValidationPlugin=class extends r.Plugin{constructor(s=be,e,t,a){super(),this._config=s,this._injector=e,this._commandService=t,this._configService=a;const{...i}=r.merge({},be,this._config);this._configService.setConfig(ot,i)}onStarting(){[[m.DataValidationCacheService],[m.DataValidationFormulaService],[m.DataValidationCustomFormulaService],[m.SheetsDataValidationValidatorService],[m.SheetDataValidationModel],[re],[m.DataValidationFormulaController],[ie],[ae],[te]].forEach(s=>{this._injector.add(s)}),[Fe,Oe,Ie,Ce,Ue,Ae,Ne].forEach(s=>{this._commandService.registerCommand(s)}),this._injector.get(m.DataValidationCacheService),this._injector.get(m.SheetsDataValidationValidatorService),this._injector.get(re),this._injector.get(te),this._injector.get(ae)}onReady(){this._injector.get(ie)}onRendered(){this._injector.get(m.DataValidationFormulaController)}},je(m.UniverSheetsDataValidationPlugin,"pluginName",we),je(m.UniverSheetsDataValidationPlugin,"type",r.UniverInstanceType.UNIVER_SHEET),m.UniverSheetsDataValidationPlugin=Mt([r.DependentOn(p.UniverDataValidationPlugin),ve(1,r.Inject(r.Injector)),ve(2,r.ICommandService),ve(3,r.IConfigService)],m.UniverSheetsDataValidationPlugin);function Et(o){const e=o.get(D.SheetsSelectionsService).getCurrentSelections().map(i=>i.range);return{uid:r.generateRandomId(6),type:r.DataValidationType.DECIMAL,operator:r.DataValidationOperator.EQUAL,formula1:"100",ranges:e!=null?e:[{startColumn:0,endColumn:0,startRow:0,endRow:0}]}}const yt="data-validation.custom-formula-input",Tt="data-validation.formula-input",Ot="data-validation.list-formula-input",Ft="data-validation.checkbox-formula-input";m.AddSheetDataValidationCommand=Fe,m.BASE_FORMULA_INPUT_NAME=Tt,m.CHECKBOX_FORMULA_1=$,m.CHECKBOX_FORMULA_2=k,m.CHECKBOX_FORMULA_INPUT_NAME=Ft,m.CUSTOM_FORMULA_INPUT_NAME=yt,m.CheckboxValidator=Me,m.ClearRangeDataValidationCommand=Ne,m.DATA_VALIDATION_PLUGIN_NAME=we,m.DateValidator=ye,m.LIST_FORMULA_INPUT_NAME=Ot,m.ListMultipleValidator=Be,m.ListValidator=ge,m.RemoveSheetAllDataValidationCommand=Ae,m.RemoveSheetDataValidationCommand=Ue,m.UpdateSheetDataValidationOptionsCommand=Ce,m.UpdateSheetDataValidationRangeCommand=Oe,m.UpdateSheetDataValidationSettingCommand=Ie,m.createDefaultNewRule=Et,m.deserializeListOptions=G,m.getCellValueNumber=X,m.getCellValueOrigin=w,m.getDataValidationCellValue=ze,m.getDataValidationDiffMutations=K,m.getFormulaCellData=j,m.getFormulaResult=U,m.getTransformedFormula=Y,m.isLegalFormulaResult=E,m.serializeListOptions=Ke,m.transformCheckboxValue=x,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
|
|
29
29
|
|
|
30
30
|
|
|
31
31
|
// @univerjs/sheets-data-validation/facade
|