@univerjs/sheets-ui 0.6.1-nightly.202502211606 → 0.6.1-nightly.202502221605

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cjs/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var vd=Object.defineProperty;var Cd=(n,r,e)=>r in n?vd(n,r,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[r]=e;var E=(n,r,e)=>Cd(n,typeof r!="symbol"?r+"":r,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const $=require("@univerjs/docs-ui"),a=require("@univerjs/core"),w=require("@univerjs/engine-render"),I=require("@univerjs/ui"),V=require("react"),O=require("rxjs"),m=require("@univerjs/sheets"),Re=require("@univerjs/docs"),K=require("@univerjs/engine-formula"),Id=require("@univerjs/engine-numfmt"),Z=require("@univerjs/design"),_=require("react/jsx-runtime"),_d=require("@univerjs/telemetry"),Ka=require("rxjs/operators");function Pr(n,r){if(n==null)return;const e=r.getRenderById(n);if(e==null)return;const{mainComponent:t,scene:o,engine:i,components:s}=e,l=t,c=s.get($.DOCS_VIEW_KEY.BACKGROUND);return{document:l,docBackground:c,scene:o,engine:i}}const Di=[10,400],us="RANGE_SELECTOR_COMPONENT_KEY",Or="EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY";var me=(n=>(n.MAIN="__SpreadsheetRender__",n.ROW="__SpreadsheetRowHeader__",n.COLUMN="__SpreadsheetColumnHeader__",n.LEFT_TOP="__SpreadsheetLeftTopPlaceholder__",n))(me||{});const zs=0,tr=1,_t=10,bd=11,Xs=12,xr={id:"sheet.command.set-row-header-width",type:a.CommandType.COMMAND,handler:async(n,r)=>{if(!r)return!1;const e=n.get(w.IRenderManagerService);if(!e)return!1;const{unitId:t,subUnitId:o,size:i}=r,s=e.getRenderById(t);if(s){e.getRenderById(t).with(exports.SheetSkeletonManagerService).setRowHeaderSize(s,o,i);const{components:c}=s,d=c.get(me.ROW);d&&d.setCustomHeader({headerStyle:{size:i}})}return!0}},Ar={id:"sheet.command.set-col-header-height",type:a.CommandType.COMMAND,handler:async(n,r)=>{if(!r)return!1;const e=n.get(w.IRenderManagerService);if(!e)return!1;const{unitId:t,subUnitId:o,size:i}=r,s=e.getRenderById(t);if(s){e.getRenderById(t).with(exports.SheetSkeletonManagerService).setColumnHeaderSize(s,o,i);const{components:c}=s,d=c.get(me.COLUMN);d&&d.setCustomHeader({headerStyle:{size:i}})}return!0}},Hi=a.createInterceptorKey("rangeMovePermissionCheck"),Vi=a.createInterceptorKey("rangeFillPermissionCheck");var hs=(n=>(n[n.FORMULA_EDITOR_SHOW=100]="FORMULA_EDITOR_SHOW",n[n.MARK_SELECTION=1e4]="MARK_SELECTION",n))(hs||{});function bt(n){const r=n.getCurrentTheme(),e=new a.ColorKit(r.primaryColor).setAlpha(.07).toRgbString();return{strokeWidth:1,stroke:r.primaryColor,fill:e,widgets:{},widgetSize:6,widgetStrokeWidth:1,widgetStroke:r.colorWhite,autofillSize:6,autofillStrokeWidth:1,autofillStroke:r.colorWhite,rowHeaderFill:e,rowHeaderStroke:r.primaryColor,rowHeaderStrokeWidth:1,columnHeaderFill:e,columnHeaderStroke:r.primaryColor,columnHeaderStrokeWidth:1,expandCornerSize:40}}class Rd{constructor(){E(this,"_startColumn",-1);E(this,"_startRow",-1);E(this,"_endColumn",-1);E(this,"_endRow",-1);E(this,"_startX",0);E(this,"_startY",0);E(this,"_endX",0);E(this,"_endY",0);E(this,"_primary");E(this,"_rangeType",a.RANGE_TYPE.NORMAL)}get startColumn(){return this._startColumn}get startRow(){return this._startRow}get endColumn(){return this._endColumn}get endRow(){return this._endRow}get startX(){return this._startX}get startY(){return this._startY}get endX(){return this._endX}get endY(){return this._endY}get currentCell(){return this._primary}get rangeType(){return this._rangeType}isEqual(r){const{startColumn:e,startRow:t,endColumn:o,endRow:i}=this,{startColumn:s,startRow:l,endColumn:c,endRow:d}=r;return e===s&&t===l&&o===c&&i===d}isInclude(r){const{startColumn:e,startRow:t,endColumn:o,endRow:i}=this,{startColumn:s,startRow:l,endColumn:c,endRow:d}=r;return!(c<e||s>o||l>i||d<t)}highlightToSelection(){if(this._primary)return a.convertCellToRange(this._primary)}getRange(){return{startColumn:this._startColumn,startRow:this._startRow,endColumn:this._endColumn,endRow:this._endRow,startX:this._startX,startY:this._startY,endX:this._endX,endY:this._endY,rangeType:this.rangeType}}getCell(){return this._primary}getRangeType(){return this._rangeType}setRangeType(r){this._rangeType=r}getValue(){return{rangeWithCoord:this.getRange(),primaryWithCoord:this._primary}}setValue(r,e){const{startColumn:t,startRow:o,endColumn:i,endRow:s,startX:l,startY:c,endX:d,endY:u,rangeType:h}=r;this._startColumn=t,this._startRow=o,this._endColumn=i,this._endRow=s,this._startX=l,this._startY=c,this._endX=d,this._endY=u,h!==void 0&&(this._rangeType=h),e!==void 0&&this.setCurrentCell(e)}setCurrentCell(r){this._primary=r}clearCurrentCell(){this._primary=null}}function bn(n,r){const{startRow:e,startColumn:t,endRow:o,endColumn:i,rangeType:s}=r,l=o<e?o:e,c=o<e?e:o,d=i<t?i:t,u=i<t?t:i,h=n.getNoMergeCellWithCoordByIndex(l,d),g=n.getNoMergeCellWithCoordByIndex(c,u);return{startRow:e,startColumn:t,endRow:o,endColumn:i,rangeType:s,startY:(h==null?void 0:h.startY)||0,endY:(g==null?void 0:g.endY)||0,startX:(h==null?void 0:h.startX)||0,endX:(g==null?void 0:g.endX)||0}}function Me(n,r){const{range:e,primary:t,style:o}=n,i=bn(r,e),s=t&&$n(r,t);return{rangeWithCoord:i,primaryWithCoord:s,style:o}}function $n(n,r){const{actualRow:e,actualColumn:t,isMerged:o,isMergedMainCell:i,startRow:s,startColumn:l,endRow:c,endColumn:d}=r,u=n.getNoMergeCellWithCoordByIndex(e,t),h=n.getNoMergeCellWithCoordByIndex(s,l),g=n.getNoMergeCellWithCoordByIndex(c,d);return{actualRow:e,actualColumn:t,isMerged:o,isMergedMainCell:i,startX:u.startX,startY:u.startY,endX:u.endX,endY:u.endY,mergeInfo:{startRow:s,startColumn:l,endRow:c,endColumn:d,startY:(h==null?void 0:h.startY)||0,endY:(g==null?void 0:g.endY)||0,startX:(h==null?void 0:h.startX)||0,endX:(g==null?void 0:g.endX)||0}}}const Ys="__SpreadsheetHelperSelectionTempRect",Ed=35;class qa{constructor(r,e){E(this,"_startOffsetX",0);E(this,"_startOffsetY",0);E(this,"_relativeSelectionPositionRow",0);E(this,"_relativeSelectionPositionColumn",0);E(this,"_relativeSelectionRowLength",0);E(this,"_relativeSelectionColumnLength",0);E(this,"_scenePointerMoveSub");E(this,"_scenePointerUpSub");E(this,"_helperSelection");E(this,"_scrollTimer");E(this,"_activeViewport");E(this,"_targetSelection",{startY:0,endY:0,startX:0,endX:0,startRow:-1,endRow:-1,startColumn:-1,endColumn:-1});E(this,"_isInMergeState",!1);E(this,"_fillControlColors",[]);E(this,"_skeleton");E(this,"_scene");E(this,"_themeService");E(this,"_injector");E(this,"_selectionHooks");this._control=r,this._skeleton=e.skeleton,this._scene=e.scene,this._themeService=e.themeService,this._injector=e.injector,this._selectionHooks=e.selectionHooks,this._initialControl(),this._initialWidget(),this._initialAutoFill(),this._control.dispose$.subscribe(()=>{this.dispose()})}get isHelperSelection(){return this._control.isHelperSelection}dispose(){var r,e;(r=this._scrollTimer)==null||r.dispose(),this._fillControlColors=[],this._clearObserverEvent(),(e=this._helperSelection)==null||e.dispose()}_getFreeze(){var t,o;return(o=(t=this._injector.get(w.IRenderManagerService).withCurrentTypeOfUnit(a.UniverInstanceType.UNIVER_SHEET,exports.SheetSkeletonManagerService))==null?void 0:t.getCurrentParam())==null?void 0:o.skeleton.getWorksheetConfig().freeze}_isSelectionInViewport(r,e){const t=this._getFreeze()||{startRow:-1,startColumn:-1};switch(e.viewportKey){case w.SHEET_VIEWPORT_KEY.VIEW_MAIN:return r.endRow>=t.startRow&&r.endColumn>=t.startColumn;case w.SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP:case w.SHEET_VIEWPORT_KEY.VIEW_COLUMN_RIGHT:return r.endColumn>=t.startColumn&&r.startRow<t.startRow;case w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT:case w.SHEET_VIEWPORT_KEY.VIEW_ROW_BOTTOM:return r.endRow>=t.startRow&&r.startColumn<t.startColumn;case w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP:case w.SHEET_VIEWPORT_KEY.VIEW_COLUMN_LEFT:case w.SHEET_VIEWPORT_KEY.VIEW_ROW_TOP:case w.SHEET_VIEWPORT_KEY.VIEW_LEFT_TOP:return r.startRow<t.startRow&&r.startColumn<t.startColumn}}_clearObserverEvent(){var r,e;(r=this._scenePointerMoveSub)==null||r.unsubscribe(),(e=this._scenePointerUpSub)==null||e.unsubscribe(),this._scenePointerMoveSub=null,this._scenePointerUpSub=null}_initialControl(){const{leftControl:r,rightControl:e,topControl:t,bottomControl:o}=this._control;[r,e,t,o].forEach(i=>{i.onPointerEnter$.subscribeEvent(()=>{var l;((l=this._injector.get(ve,a.Quantity.OPTIONAL))==null?void 0:l.interceptor.fetchThroughInterceptors(Hi)(!1,null))!==!1&&i.setCursor(w.CURSOR_TYPE.MOVE)}),i.onPointerLeave$.subscribeEvent(()=>{i.resetCursor()}),i.onPointerDown$.subscribeEvent(this._controlPointerDownHandler.bind(this))})}_controlMoving(r,e){var A;const t=this._scene,o=t.getScrollXYInfoByViewport(w.Vector2.FromArray([r,e])),{scaleX:i,scaleY:s}=t.getAncestorScale(),l=this._skeleton.getCellIndexByOffset(r,e,i,s,o),{row:c,column:d}=l,u=this._skeleton.getRowCount()-1,h=this._skeleton.getColumnCount()-1;let g=Math.max(0,c+this._relativeSelectionPositionRow),S=g+this._relativeSelectionRowLength;S>u&&(S=u,S-g<this._relativeSelectionRowLength&&(g=S-this._relativeSelectionRowLength));let f=Math.max(0,d+this._relativeSelectionPositionColumn),p=f+this._relativeSelectionColumnLength;p>h&&(p=h,p-f<this._relativeSelectionColumnLength&&(f=p-this._relativeSelectionColumnLength));const v=this._skeleton.worksheet.getCellInfoInMergeData(g,f),b=Me({range:{startRow:g,endRow:S,startColumn:f,endColumn:p},primary:v,style:null},this._skeleton),R=this._skeleton.getNoMergeCellWithCoordByIndex(g,f),T=this._skeleton.getNoMergeCellWithCoordByIndex(S,p),M=(R==null?void 0:R.startY)||0,y=(T==null?void 0:T.endY)||0,P=(R==null?void 0:R.startX)||0,x=(T==null?void 0:T.endX)||0;(A=this._helperSelection)==null||A.transformByState({left:P,top:M,width:x-P,height:y-M}),this._targetSelection={...b.rangeWithCoord},this._control.selectionMoving$.next(b.rangeWithCoord)}_controlPointerDownHandler(r){const{offsetX:e,offsetY:t}=r,o=this._scene,i=o.getCoordRelativeToViewport(w.Vector2.FromArray([e,t])),{x:s,y:l}=i,c=o.getScrollXYInfoByViewport(i),{scaleX:d,scaleY:u}=o.getAncestorScale(),h=this._skeleton.getCellIndexByOffset(s,l,d,u,c);this._startOffsetX=s,this._startOffsetY=l;const{row:g,column:S}=h,{startRow:f,startColumn:p,endRow:v,endColumn:C}=this._control.model;let b=0,R=0;g<f?b-=1:g>v&&(b+=1),S<p?R-=1:S>C&&(R+=1),this._relativeSelectionPositionRow=f-g+b,this._relativeSelectionPositionColumn=p-S+R,this._relativeSelectionRowLength=v-f,this._relativeSelectionColumnLength=C-p;const T=this._control.currentStyle,M=this._getScale();this.isHelperSelection&&(this._helperSelection=new w.Rect(Ys,{stroke:T.stroke,strokeWidth:T.strokeWidth/M}),o.addObject(this._helperSelection));const y=o.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN),P=w.ScrollTimer.create(o);this._scrollTimer=P,P.startScroll(s,l,y),o.disableObjectsEvent(),this._scenePointerMoveSub=o.onPointerMove$.subscribeEvent(x=>{var H;const{offsetX:A,offsetY:k}=x;if(((H=this._injector.get(ve,a.Quantity.OPTIONAL))==null?void 0:H.interceptor.fetchThroughInterceptors(Hi)(!1,null))===!1)return;const{x:D,y:W}=o.getCoordRelativeToViewport(w.Vector2.FromArray([A,k]));this._controlMoving(D,W),o.setCursor(w.CURSOR_TYPE.MOVE),P.scrolling(D,W,()=>{this._controlMoving(D,W)})}),this._scenePointerUpSub=o.onPointerUp$.subscribeEvent(()=>{var A,k,N,D;(A=this._helperSelection)==null||A.dispose();const x=this._scene;x.resetCursor(),this._clearObserverEvent(),x.enableObjectsEvent(),(k=this._scrollTimer)==null||k.dispose(),this._control.selectionMoveEnd$.next(this._targetSelection),(D=(N=this._selectionHooks).selectionMoveEnd)==null||D.call(N)})}_initialWidget(){const{topLeftWidget:r,topCenterWidget:e,topRightWidget:t,middleLeftWidget:o,middleRightWidget:i,bottomLeftWidget:s,bottomCenterWidget:l,bottomRightWidget:c}=this._control,d=[w.CURSOR_TYPE.NORTH_WEST_RESIZE,w.CURSOR_TYPE.NORTH_RESIZE,w.CURSOR_TYPE.NORTH_EAST_RESIZE,w.CURSOR_TYPE.WEST_RESIZE,w.CURSOR_TYPE.EAST_RESIZE,w.CURSOR_TYPE.SOUTH_WEST_RESIZE,w.CURSOR_TYPE.SOUTH_RESIZE,w.CURSOR_TYPE.SOUTH_EAST_RESIZE];[r,e,t,o,i,s,l,c].forEach((u,h)=>{u.onPointerEnter$.subscribeEvent(()=>{u.setCursor(d[h])}),u.onPointerLeave$.subscribeEvent(()=>{u.resetCursor()}),u.onPointerDown$.subscribeEvent(g=>{this._widgetPointerDownEvent(g,d[h])})})}_widgetPointerDownEvent(r,e){const t=this._scene,{offsetX:o,offsetY:i}=r,s=t.getCoordRelativeToViewport(w.Vector2.FromArray([o,i])),{x:l,y:c}=s;this._startOffsetX=o,this._startOffsetY=i;const{startRow:d,startColumn:u,endRow:h,endColumn:g}=this._control.model,S=Math.min(d,h),f=Math.min(u,g),p=Math.max(d,h),v=Math.max(u,g);this._relativeSelectionPositionRow=S,this._relativeSelectionPositionColumn=f,this._relativeSelectionRowLength=p-S,this._relativeSelectionColumnLength=v-f,e===w.CURSOR_TYPE.NORTH_WEST_RESIZE?(this._relativeSelectionPositionRow=p,this._relativeSelectionPositionColumn=v):e===w.CURSOR_TYPE.NORTH_RESIZE?this._relativeSelectionPositionRow=p:e===w.CURSOR_TYPE.NORTH_EAST_RESIZE?this._relativeSelectionPositionRow=p:e===w.CURSOR_TYPE.WEST_RESIZE?this._relativeSelectionPositionColumn=v:e===w.CURSOR_TYPE.SOUTH_WEST_RESIZE?this._relativeSelectionPositionColumn=v:e===w.CURSOR_TYPE.SOUTH_RESIZE&&(this._relativeSelectionPositionRow=S);const C=w.ScrollTimer.create(t),b=t.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN);C.startScroll(l,c,b),this._scrollTimer=C,t.disableObjectsEvent(),this._scenePointerMoveSub=t.onPointerMove$.subscribeEvent(R=>{const{offsetX:T,offsetY:M}=R,{x:y,y:P}=t.getCoordRelativeToViewport(w.Vector2.FromArray([T,M]));this._widgetMoving(y,P,e),t.setCursor(e),C.scrolling(y,P,()=>{this._widgetMoving(y,P,e)})}),this._scenePointerUpSub=t.onPointerUp$.subscribeEvent(()=>{var T,M,y;const R=this._scene;R.resetCursor(),this._clearObserverEvent(),R.enableObjectsEvent(),(T=this._scrollTimer)==null||T.dispose(),this._control.selectionScaled$.next(this._targetSelection),(y=(M=this._selectionHooks).selectionMoveEnd)==null||y.call(M)})}_widgetMoving(r,e,t){const o=this._scene,i=o.getScrollXYInfoByViewport(w.Vector2.FromArray([this._startOffsetX,this._startOffsetY])),{scaleX:s,scaleY:l}=o.getAncestorScale(),c=this._skeleton.getCellIndexByOffset(r,e,s,l,i),{row:d,column:u}=c;let h=this._relativeSelectionPositionRow,g=this._relativeSelectionPositionColumn,S=d,f=u;t===w.CURSOR_TYPE.NORTH_WEST_RESIZE?(h=d,g=u,S=this._relativeSelectionPositionRow,f=this._relativeSelectionPositionColumn):t===w.CURSOR_TYPE.NORTH_RESIZE?(h=d,g=this._relativeSelectionPositionColumn,S=this._relativeSelectionPositionRow,f=this._relativeSelectionPositionColumn+this._relativeSelectionColumnLength):t===w.CURSOR_TYPE.NORTH_EAST_RESIZE?(h=d,g=this._relativeSelectionPositionColumn,S=this._relativeSelectionPositionRow,f=u):t===w.CURSOR_TYPE.WEST_RESIZE?(h=this._relativeSelectionPositionRow,g=u,S=this._relativeSelectionPositionRow+this._relativeSelectionRowLength,f=this._relativeSelectionPositionColumn):t===w.CURSOR_TYPE.EAST_RESIZE?S=this._relativeSelectionPositionRow+this._relativeSelectionRowLength:t===w.CURSOR_TYPE.SOUTH_WEST_RESIZE?(h=this._relativeSelectionPositionRow,g=u,S=d,f=this._relativeSelectionPositionColumn):t===w.CURSOR_TYPE.SOUTH_RESIZE&&(h=this._relativeSelectionPositionRow,g=this._relativeSelectionPositionColumn,S=d,f=this._relativeSelectionPositionColumn+this._relativeSelectionColumnLength);const p=this._swapPositions(h,g,S,f),v=this._skeleton.getCellWithMergeInfoByIndex(h,g),b=Me({range:p,primary:v,style:null},this._skeleton);this._targetSelection={...b.rangeWithCoord},this._control.updateRangeBySelectionWithCoord(b),this._control.selectionScaling$.next(this._targetSelection)}_initialAutoFill(){const{fillControl:r}=this._control;r.onPointerEnter$.subscribeEvent(e=>{this._injector.get(ve).interceptor.fetchThroughInterceptors(Vi)(!1,{x:e.offsetX,y:e.offsetY,skeleton:this._skeleton,scene:this._scene})&&r.setCursor(w.CURSOR_TYPE.CROSSHAIR)}),r.onPointerLeave$.subscribeEvent(()=>{r.resetCursor()}),r.onPointerDown$.subscribeEvent(this._autoFillForPointerdown.bind(this))}_autoFillMoving(r,e){var k,N,D;const t=this._scene,o=t.getViewportScrollXY(this._activeViewport),{scaleX:i,scaleY:s}=t.getAncestorScale(),l=this._skeleton.getCellIndexByOffset(r,e,i,s,o),{row:c,column:d}=l,u=t.getCoordRelativeToViewport(w.Vector2.FromArray([r,e])),h=this._skeleton.getRowCount()-1,g=this._skeleton.getColumnCount()-1;let S=this._relativeSelectionPositionRow,f=this._relativeSelectionPositionColumn,p=this._relativeSelectionPositionRow+this._relativeSelectionRowLength,v=this._relativeSelectionPositionColumn+this._relativeSelectionColumnLength,C=!1,b=!0;if((d<f||d>v)&&c>=S&&c<=p){const W=this._fillRuler(d,f,v,this._relativeSelectionColumnLength,g);f=W.startRowOrColumn,v=W.endRowOrColumn,C=W.isLighten,b=!1}else if((c<S||c>p)&&d>=f&&d<=v){const W=this._fillRuler(c,S,p,this._relativeSelectionRowLength,h);S=W.startRowOrColumn,p=W.endRowOrColumn,C=W.isLighten}else if(Math.abs(this._startOffsetX-u.x-o.x)/2>Math.abs(this._startOffsetY-u.y-o.y)){const W=this._fillRuler(d,f,v,this._relativeSelectionColumnLength,g);f=W.startRowOrColumn,v=W.endRowOrColumn,C=W.isLighten,b=!1}else{const W=this._fillRuler(c,S,p,this._relativeSelectionRowLength,h);S=W.startRowOrColumn,p=W.endRowOrColumn,C=W.isLighten}const R=this._skeleton.getNoMergeCellWithCoordByIndex(S,f),T=this._skeleton.getNoMergeCellWithCoordByIndex(p,v),M=(R==null?void 0:R.startY)||0,y=(T==null?void 0:T.endY)||0,P=(R==null?void 0:R.startX)||0,x=(T==null?void 0:T.endX)||0;C?this._controlHandler((W,H)=>{const U=new a.ColorKit(this._fillControlColors[H]).lighten(Ed).toRgbString();W.setProps({fill:U})}):this._controlHandler((W,H)=>{W.setProps({fill:this._fillControlColors[H]})});const A=m.SELECTION_CONTROL_BORDER_BUFFER_WIDTH/this._getScale();S===p&&b===!0||f===v&&b===!1?(k=this._helperSelection)==null||k.hide():((N=this._helperSelection)==null||N.transformByState({left:P-A/2,top:M-A/2,width:x-P,height:y-M}),(D=this._helperSelection)==null||D.show()),this._targetSelection={startY:M,endY:y,startX:P,endX:x,startRow:S,endRow:p,startColumn:f,endColumn:v},this._control.selectionFilling$.next(this._targetSelection)}_autoFillForPointerdown(r){const{offsetX:e,offsetY:t}=r,o=this._scene,i=o.getCoordRelativeToViewport(w.Vector2.FromArray([e,t])),{x:s,y:l}=i;this._startOffsetX=s,this._startOffsetY=l;const{startRow:c,startColumn:d,endRow:u,endColumn:h}=this._control.model;this._isInMergeState=this._hasMergeInRange(c,d,u,h),this._relativeSelectionPositionRow=c,this._relativeSelectionPositionColumn=d,this._relativeSelectionRowLength=u-c,this._relativeSelectionColumnLength=h-d;const g=this._control.currentStyle;let S=g==null?void 0:g.stroke,f=g==null?void 0:g.strokeWidth;const p=bt(this._themeService);S==null&&(S=p.stroke),f==null&&(f=p.strokeWidth);const v=this._getScale();f/=v;const C=m.SELECTION_CONTROL_BORDER_BUFFER_WIDTH/v,b=new a.ColorKit(S).darken(2).toRgbString();this.isHelperSelection&&(this._helperSelection=new w.Rect(Ys,{stroke:b,strokeWidth:f+C/2}),o.addObject(this._helperSelection)),this._activeViewport=o.getActiveViewportByCoord(w.Vector2.FromArray([e,t]));const R=o.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN),T=w.ScrollTimer.create(o,this._activeViewport.viewportKey===w.SHEET_VIEWPORT_KEY.VIEW_MAIN?w.ScrollTimerType.ALL:w.ScrollTimerType.NONE);T.startScroll(s,l,R),this._scrollTimer=T,o.disableObjectsEvent(),this._controlHandler(M=>{this._fillControlColors.push(M.fill)}),this._scenePointerMoveSub=o.onPointerMove$.subscribeEvent(M=>{var W;const{offsetX:y,offsetY:P}=M,x=o.getActiveViewportByCoord(w.Vector2.FromArray([y,P]));if(!this._injector.get(ve).interceptor.fetchThroughInterceptors(Vi)(!1,{x:r.offsetX,y:r.offsetY,skeleton:this._skeleton,scene:this._scene}))return;const{x:k,y:N}=o.getCoordRelativeToViewport(w.Vector2.FromArray([y,P]));this._autoFillMoving(k,N),o.setCursor(w.CURSOR_TYPE.CROSSHAIR);const D=this._targetSelection;if(R&&x&&((W=this._activeViewport)==null?void 0:W.viewportKey)!==(x==null?void 0:x.viewportKey)){let H;D.startRow!==c?(T.scrollTimerType=w.ScrollTimerType.Y,H={...D,endRow:D.startRow}):D.endRow!==u?(T.scrollTimerType=w.ScrollTimerType.Y,H={...D,startRow:D.endRow}):D.startColumn!==d?(T.scrollTimerType=w.ScrollTimerType.X,H={...D,endColumn:D.startColumn}):(T.scrollTimerType=w.ScrollTimerType.X,H={...D,startColumn:D.endColumn}),this._isSelectionInViewport(H,x)&&(R.scrollToBarPos({x:T.scrollTimerType===w.ScrollTimerType.X?0:void 0,y:T.scrollTimerType===w.ScrollTimerType.Y?0:void 0}),this._activeViewport=x)}T.scrolling(k,N,()=>{this._autoFillMoving(k,N)})}),this._scenePointerUpSub=o.onPointerUp$.subscribeEvent(()=>{var y,P;(y=this._helperSelection)==null||y.dispose();const M=this._scene;M.resetCursor(),this._clearObserverEvent(),M.enableObjectsEvent(),(P=this._scrollTimer)==null||P.dispose(),this._control.refreshSelectionFilled(this._targetSelection),this._isInMergeState=!1,this._controlHandler((x,A)=>{x.setProps({fill:this._fillControlColors[A]})}),this._fillControlColors=[]})}_hasMergeInRange(r,e,t,o){return this._skeleton.worksheet.getMergedCellRange(r,e,t,o).length>0}_swapPositions(r,e,t,o){const i=Math.min(r,t),s=Math.min(e,o),l=Math.max(r,t),c=Math.max(e,o);return{startRow:i,startColumn:s,endRow:l,endColumn:c}}_controlHandler(r){const{leftControl:e,rightControl:t,topControl:o,bottomControl:i,backgroundControlTop:s,backgroundControlMiddleLeft:l,backgroundControlMiddleRight:c,backgroundControlBottom:d,fillControl:u}=this._control,h=[e,t,o,i,s,l,c,d,u];for(let g=0,S=h.length;g<S;g++){const f=h[g];r(f,g)}}_fillRuler(r,e,t,o,i){let s=!1;if(r<e)if(this._isInMergeState&&r<e){const l=e-r,c=o+1,d=Math.ceil(l/c);let u=e-d*c;u<0&&(u=e-(d-1)*c),e=u}else e=r;else if(r>=e&&r<=t)s=!0,this._isInMergeState||(t=r);else if(this._isInMergeState&&r>t){const l=r-t,c=o+1,d=Math.ceil(l/c);let u=t+d*c;u>i&&(u=t+(d-1)*c),t=u}else t=r;return{rowOrColumn:r,startRowOrColumn:e,endRowOrColumn:t,isLighten:s}}_getScale(){const{scaleX:r,scaleY:e}=this._scene.getAncestorScale();return Math.max(r,e)}}var Wi=(n=>(n.Selection="__SpreadsheetSelectionShape__",n.top="__SpreadsheetSelectionTopControl__",n.bottom="__SpreadsheetSelectionBottomControl__",n.left="__SpreadsheetSelectionShapeLeftControl__",n.right="__SpreadsheetSelectionShapeRightControl__",n.backgroundTop="__SpreadsheetSelectionBackgroundControlTop__",n.backgroundMiddleLeft="__SpreadsheetSelectionBackgroundControlMiddleLeft__",n.backgroundMiddleRight="__SpreadsheetSelectionBackgroundControlMiddleRight__",n.backgroundBottom="__SpreadsheetSelectionBackgroundControlBottom__",n.fill="__SpreadsheetSelectionFillControl__",n.fillTopLeft="__SpreadsheetSelectionFillControlTopLeft__",n.fillBottomRight="__SpreadsheetSelectionFillControlBottomRight__",n.fillTopLeftInner="__SpreadsheetSelectionFillControlTopLeftInner__",n.fillBottomRightInner="__SpreadsheetSelectionFillControlBottomRightInner__",n.lineMain="__SpreadsheetDragLineMainControl__",n.lineContent="__SpreadsheetDragLineContentControl__",n.line="__SpreadsheetDragLineControl__",n.dash="__SpreadsheetDragDashControl__",n.rowHeaderBackground="__SpreadSheetSelectionRowHeaderBackground__",n.rowHeaderBorder="__SpreadSheetSelectionRowHeaderBorder__",n.rowHeaderGroup="__SpreadSheetSelectionRowHeaderGroup__",n.columnHeaderBackground="__SpreadSheetSelectionColumnHeaderBackground__",n.columnHeaderBorder="__SpreadSheetSelectionColumnHeaderBorder__",n.columnHeaderGroup="__SpreadSheetSelectionColumnHeaderGroup__",n.topLeftWidget="__SpreadSheetSelectionTopLeftWidget__",n.topCenterWidget="__SpreadSheetSelectionTopCenterWidget__",n.topRightWidget="__SpreadSheetSelectionTopRightWidget__",n.middleLeftWidget="__SpreadSheetSelectionMiddleLeftWidget__",n.middleRightWidget="__SpreadSheetSelectionMiddleRightWidget__",n.bottomLeftWidget="__SpreadSheetSelectionBottomLeftWidget__",n.bottomCenterWidget="__SpreadSheetSelectionBottomCenterWidget__",n.bottomRightWidget="__SpreadSheetSelectionBottomRightWidget__",n))(Wi||{});const Gs=.3;class co extends a.Disposable{constructor(e,t,o,i){var s,l,c,d;super();E(this,"_isHelperSelection",!0);E(this,"_enableAutoFill",!0);E(this,"_showAutoFill",!1);E(this,"_highlightHeader",!0);E(this,"_selectionRenderModel");E(this,"_leftBorder");E(this,"_rightBorder");E(this,"_topBorder");E(this,"_bottomBorder");E(this,"_backgroundControlTop");E(this,"_backgroundControlBottom");E(this,"_backgroundControlMiddleLeft");E(this,"_backgroundControlMiddleRight");E(this,"_autoFillControl");E(this,"_selectionShapeGroup");E(this,"_rowHeaderBackground");E(this,"_rowHeaderBorder");E(this,"_rowHeaderGroup");E(this,"_columnHeaderBackground");E(this,"_columnHeaderBorder");E(this,"_columnHeaderGroup");E(this,"_dashedRect");E(this,"_topLeftWidget");E(this,"_topCenterWidget");E(this,"_topRightWidget");E(this,"_middleLeftWidget");E(this,"_middleRightWidget");E(this,"_bottomLeftWidget");E(this,"_bottomCenterWidget");E(this,"_bottomRightWidget");E(this,"_defaultStyle");E(this,"_currentStyle");E(this,"_rowHeaderWidth",0);E(this,"_columnHeaderHeight",0);E(this,"_widgetRects",[]);E(this,"_controlExtension");E(this,"_dispose$",new O.BehaviorSubject(this));E(this,"dispose$",this._dispose$.asObservable());E(this,"selectionMoving$",new O.Subject);E(this,"selectionMoveEnd$",new O.Subject);E(this,"selectionScaling$",new O.Subject);E(this,"selectionScaled$",new O.Subject);E(this,"selectionFilling$",new O.Subject);E(this,"_selectionFilled$",new O.Subject);E(this,"selectionFilled$",this._selectionFilled$.asObservable());E(this,"_antLineOffset",0);E(this,"_antRequestNewFrame",-1);this._scene=e,this._zIndex=t,this._themeService=o,this._enableAutoFill=(s=i==null?void 0:i.enableAutoFill)!=null?s:!0,this._highlightHeader=(l=i==null?void 0:i.highlightHeader)!=null?l:!0,this._rowHeaderWidth=(c=i==null?void 0:i.rowHeaderWidth)!=null?c:0,this._columnHeaderHeight=(d=i==null?void 0:i.columnHeaderHeight)!=null?d:0,this._initializeSheetBody(),this._initialHeader()}_initializeSheetBody(){this._defaultStyle=bt(this._themeService),this._currentStyle=bt(this._themeService),this._selectionRenderModel=new Rd;const e=this._zIndex;this._leftBorder=new w.Rect("__SpreadsheetSelectionShapeLeftControl__"+e,{zIndex:e}),this._rightBorder=new w.Rect("__SpreadsheetSelectionShapeRightControl__"+e,{zIndex:e}),this._topBorder=new w.Rect("__SpreadsheetSelectionTopControl__"+e,{zIndex:e}),this._bottomBorder=new w.Rect("__SpreadsheetSelectionBottomControl__"+e,{zIndex:e}),this._backgroundControlTop=new w.Rect("__SpreadsheetSelectionBackgroundControlTop__"+e,{zIndex:e-1,evented:!1}),this._backgroundControlBottom=new w.Rect("__SpreadsheetSelectionBackgroundControlBottom__"+e,{zIndex:e-1,evented:!1}),this._backgroundControlMiddleLeft=new w.Rect("__SpreadsheetSelectionBackgroundControlMiddleLeft__"+e,{zIndex:e-1,evented:!1}),this._backgroundControlMiddleRight=new w.Rect("__SpreadsheetSelectionBackgroundControlMiddleRight__"+e,{zIndex:e-1,evented:!1}),this._autoFillControl=new w.Rect("__SpreadsheetSelectionFillControl__"+e,{zIndex:e+1}),this._autoFillControl.hide(),this._dashedRect=new w.DashedRect("__SpreadsheetDragDashControl__"+e,{zIndex:e+2,evented:!1,stroke:"#fff"});const t=[this._autoFillControl,this._leftBorder,this._rightBorder,this._topBorder,this._bottomBorder,this._backgroundControlTop,this._backgroundControlMiddleLeft,this._backgroundControlMiddleRight,this._backgroundControlBottom,this._dashedRect];this._widgetRects=this._initialWidget(),this._selectionShapeGroup=new w.Group("__SpreadsheetSelectionShape__"+e,...t,...this._widgetRects),this._selectionShapeGroup.hide(),this._selectionShapeGroup.evented=!1,this._selectionShapeGroup.zIndex=e;const o=this.getScene();o.addObject(this._selectionShapeGroup,tr),this.disposeWithMe(a.toDisposable(o.onTransformChange$.subscribeEvent(i=>{i.type===w.TRANSFORM_CHANGE_OBSERVABLE_TYPE.scale&&(this._updateLayoutOfSelectionControl(this._currentStyle),this._updateControlCoord())})))}_initialHeader(){const e=this._zIndex;this._rowHeaderBackground=new w.Rect("__SpreadSheetSelectionRowHeaderBackground__"+e,{zIndex:e-1,evented:!1}),this._rowHeaderBorder=new w.Rect("__SpreadSheetSelectionRowHeaderBorder__"+e,{zIndex:e-1,evented:!1}),this._rowHeaderGroup=new w.Group("__SpreadSheetSelectionRowHeaderGroup__"+e,this._rowHeaderBackground,this._rowHeaderBorder),this._rowHeaderGroup.hide(),this._rowHeaderGroup.evented=!1,this._rowHeaderGroup.zIndex=e,this._columnHeaderBackground=new w.Rect("__SpreadSheetSelectionColumnHeaderBackground__"+e,{zIndex:e-1,evented:!1}),this._columnHeaderBorder=new w.Rect("__SpreadSheetSelectionColumnHeaderBorder__"+e,{zIndex:e-1,evented:!1}),this._columnHeaderGroup=new w.Group("__SpreadSheetSelectionColumnHeaderGroup__"+e,this._columnHeaderBackground,this._columnHeaderBorder),this._columnHeaderGroup.hide(),this._columnHeaderGroup.evented=!1,this._columnHeaderGroup.zIndex=e,this.getScene().addObjects([this._rowHeaderGroup,this._columnHeaderGroup],bd)}_initialWidget(){const e=this._zIndex;return this._topLeftWidget=new w.Rect("__SpreadSheetSelectionTopLeftWidget__"+e,{zIndex:e+1}),this._topCenterWidget=new w.Rect("__SpreadSheetSelectionTopCenterWidget__"+e,{zIndex:e+1}),this._topRightWidget=new w.Rect("__SpreadSheetSelectionTopRightWidget__"+e,{zIndex:e+1}),this._middleLeftWidget=new w.Rect("__SpreadSheetSelectionMiddleLeftWidget__"+e,{zIndex:e+1}),this._middleRightWidget=new w.Rect("__SpreadSheetSelectionMiddleRightWidget__"+e,{zIndex:e+1}),this._bottomLeftWidget=new w.Rect("__SpreadSheetSelectionBottomLeftWidget__"+e,{zIndex:e+1}),this._bottomCenterWidget=new w.Rect("__SpreadSheetSelectionBottomCenterWidget__"+e,{zIndex:e+1}),this._bottomRightWidget=new w.Rect("__SpreadSheetSelectionBottomRightWidget__"+e,{zIndex:e+1}),[this._topLeftWidget,this._topCenterWidget,this._topRightWidget,this._middleLeftWidget,this._middleRightWidget,this._bottomLeftWidget,this._bottomCenterWidget,this._bottomRightWidget]}get zIndex(){return this._zIndex}get leftControl(){return this._leftBorder}get rightControl(){return this._rightBorder}get topControl(){return this._topBorder}get bottomControl(){return this._bottomBorder}get fillControl(){return this._autoFillControl}get backgroundControlTop(){return this._backgroundControlTop}get backgroundControlBottom(){return this._backgroundControlBottom}get backgroundControlMiddleLeft(){return this._backgroundControlMiddleLeft}get backgroundControlMiddleRight(){return this._backgroundControlMiddleRight}get selectionShape(){return this._selectionShapeGroup}get columnHeaderGroup(){return this._columnHeaderGroup}get rowHeaderGroup(){return this._rowHeaderGroup}get selectionShapeGroup(){return this._selectionShapeGroup}get model(){return this._selectionRenderModel}get topLeftWidget(){return this._topLeftWidget}get topCenterWidget(){return this._topCenterWidget}get topRightWidget(){return this._topRightWidget}get middleLeftWidget(){return this._middleLeftWidget}get middleRightWidget(){return this._middleRightWidget}get bottomLeftWidget(){return this._bottomLeftWidget}get bottomCenterWidget(){return this._bottomCenterWidget}get bottomRightWidget(){return this._bottomRightWidget}get themeService(){return this._themeService}get selectionModel(){return this._selectionRenderModel}set selectionModel(e){this._selectionRenderModel=e}get currentStyle(){return this._currentStyle}set currentStyle(e){this._currentStyle=e}get dashedRect(){return this._dashedRect}get isHelperSelection(){return this._isHelperSelection}get rowHeaderWidth(){return this._rowHeaderWidth}set rowHeaderWidth(e){this._rowHeaderWidth=e}get columnHeaderHeight(){return this._columnHeaderHeight}set columnHeaderHeight(e){this._columnHeaderHeight=e}setControlExtension(e){this._controlExtension=new qa(this,e)}setEvent(e){this.leftControl.evented=e,this.rightControl.evented=e,this.topControl.evented=e,this.bottomControl.evented=e}refreshSelectionFilled(e){this._selectionFilled$.next(e)}_updateLayoutOfSelectionControl(e){e&&(this.currentStyle=Object.assign({},this._defaultStyle,e));const t=this.currentStyle,{stroke:o,widgets:i,autofillStroke:s,strokeDash:l,isAnimationDash:c}=t;let d=t.autofillSize,u=t.strokeWidth,h=t.autofillStrokeWidth;const g=this._getScale(),S=(u+m.SELECTION_CONTROL_BORDER_BUFFER_WIDTH)/2/g;u/=g,d/=g,h/=g<1?1:g;const f=m.SELECTION_CONTROL_BORDER_BUFFER_WIDTH/g,p=w.FIX_ONE_PIXEL_BLUR_OFFSET/g,{startX:v,startY:C,endX:b,endY:R}=this._selectionRenderModel;if(this.leftControl.transformByState({height:R-C,left:-S+p,width:u,strokeWidth:f,top:-f/2+p}),this.leftControl.setProps({fill:o,stroke:m.SELECTION_CONTROL_BORDER_BUFFER_COLOR}),this.rightControl.transformByState({height:R-C,left:b-v-S+p,width:u,strokeWidth:f,top:-f/2+p}),this.rightControl.setProps({fill:o,stroke:m.SELECTION_CONTROL_BORDER_BUFFER_COLOR}),this.topControl.transformByState({width:b-v+u,top:-S+p,left:-S+p,height:u,strokeWidth:f}),this.topControl.setProps({fill:o,stroke:m.SELECTION_CONTROL_BORDER_BUFFER_COLOR}),this.bottomControl.transformByState({width:b-v+u,top:R-C-S+p,height:u,left:-S+p,strokeWidth:f}),this.bottomControl.setProps({fill:o,stroke:m.SELECTION_CONTROL_BORDER_BUFFER_COLOR}),l==null)this.dashedRect.hide(),this._stopAntLineAnimation();else{const T=t.strokeWidth*2/g;this.dashedRect.transformByState({height:R-C,width:b-v,strokeWidth:T,left:-T/2+p,top:-T/2+p}),this.dashedRect.setProps({strokeDashArray:[0,l/g]}),this._stopAntLineAnimation(),c!==!1&&this._startAntLineAnimation(),this.dashedRect.show()}if(this._showAutoFill=this._showAutoFill&&this._enableAutoFill,this._showAutoFill&&!this._hasWidgets(i)){const T={fill:o,stroke:s,strokeScaleEnabled:!1},M={width:d-h,height:d-h,left:b-v-d/2+h/2-p,top:R-C-d/2+h/2-p,strokeWidth:h};this._autoFillControl.setProps(T),this._autoFillControl.transformByState(M),this._autoFillControl.show()}else this._autoFillControl.hide();this._updateBackgroundControl(t),this._updateHeaderBackground(t),this._updateWidgets(t)}_updateControlCoord(){const{startX:e,startY:t}=this._selectionRenderModel;this.selectionShapeGroup.show(),this.selectionShapeGroup.translate(e,t),this.selectionShapeGroup.makeDirtyNoDebounce(!0)}updateStyle(e){this._updateLayoutOfSelectionControl(e),this._updateControlCoord()}updateRange(e,t){this._selectionRenderModel.setValue(e,t),this._showAutoFill=t!==null,this._updateLayoutOfSelectionControl(),this._updateControlCoord()}updateRangeBySelectionWithCoord(e,t){t&&(this._rowHeaderWidth=t.getWorksheetConfig().rowHeader.width,this._columnHeaderHeight=t.getWorksheetConfig().columnHeader.height),this._selectionRenderModel.setValue(e.rangeWithCoord,e.primaryWithCoord),this._showAutoFill=e.primaryWithCoord!==null,this._updateLayoutOfSelectionControl(e.style),this._updateControlCoord()}update(e,t=0,o=0,i,s){this._rowHeaderWidth=t,this._columnHeaderHeight=o,this.updateRangeBySelectionWithCoord({rangeWithCoord:e,primaryWithCoord:s,style:i}),i&&this.updateStyle(i)}updateCurrCell(e){this._showAutoFill=e!==null,this._selectionRenderModel.setCurrentCell(e)}clearHighlight(){this._showAutoFill=!1,this._selectionRenderModel.clearCurrentCell(),this._updateLayoutOfSelectionControl(this._currentStyle)}getScene(){return this._scene}dispose(){var e,t,o,i,s,l,c,d,u,h,g,S,f,p,v,C,b,R,T,M,y,P,x,A,k;(e=this._leftBorder)==null||e.dispose(),(t=this._rightBorder)==null||t.dispose(),(o=this._topBorder)==null||o.dispose(),(i=this._bottomBorder)==null||i.dispose(),(s=this._backgroundControlTop)==null||s.dispose(),(l=this._backgroundControlMiddleLeft)==null||l.dispose(),(c=this._backgroundControlMiddleRight)==null||c.dispose(),(d=this._backgroundControlBottom)==null||d.dispose(),this._autoFillControl.dispose(),(u=this._selectionShapeGroup)==null||u.dispose(),(h=this._rowHeaderBackground)==null||h.dispose(),(g=this._rowHeaderBorder)==null||g.dispose(),(S=this._rowHeaderGroup)==null||S.dispose(),(f=this._rowHeaderBackground)==null||f.dispose(),(p=this._columnHeaderBackground)==null||p.dispose(),(v=this._columnHeaderBorder)==null||v.dispose(),(C=this._columnHeaderGroup)==null||C.dispose(),(b=this._topLeftWidget)==null||b.dispose(),(R=this._topCenterWidget)==null||R.dispose(),(T=this._topRightWidget)==null||T.dispose(),(M=this._middleLeftWidget)==null||M.dispose(),(y=this._middleRightWidget)==null||y.dispose(),(P=this._bottomLeftWidget)==null||P.dispose(),(x=this._bottomCenterWidget)==null||x.dispose(),(A=this._bottomRightWidget)==null||A.dispose(),(k=this._controlExtension)==null||k.dispose(),super.dispose(),this._dispose$.next(this),this._dispose$.complete()}getCurrentCellInfo(){const e=this.model.currentCell;if(e){let t;if(e.isMerged){const o=e.mergeInfo;t={startRow:o.startRow,endRow:o.endRow,startColumn:o.startColumn,endColumn:o.endColumn,startX:o.startX,endX:o.endX,startY:o.startY,endY:o.endY}}else{const{actualRow:o,actualColumn:i,startX:s,endX:l,startY:c,endY:d}=e;t={startRow:o,endRow:o,startColumn:i,endColumn:i,startX:s,endX:l,startY:c,endY:d}}return t}}getValue(){return{...this._selectionRenderModel.getValue(),style:this._currentStyle}}getRange(){return this._selectionRenderModel.getValue().rangeWithCoord}enableHelperSelection(){this._isHelperSelection=!0}disableHelperSelection(){this._isHelperSelection=!1}_updateHeaderBackground(e){const{startX:t,startY:o,endX:i,endY:s,rangeType:l}=this._selectionRenderModel,c=this._currentStyle,d=this._getScale(),{stroke:u,rowHeaderFill:h=c.rowHeaderFill,rowHeaderStroke:g=c.rowHeaderStroke,columnHeaderFill:S=c.columnHeaderFill,columnHeaderStroke:f=c.columnHeaderStroke}=e;let{rowHeaderStrokeWidth:p=c.rowHeaderStrokeWidth,columnHeaderStrokeWidth:v=c.columnHeaderStrokeWidth}=e;p/=d,v/=d;const C=this._rowHeaderWidth,b=this._columnHeaderHeight;if(this._highlightHeader&&b>0){let R=S;l===a.RANGE_TYPE.COLUMN&&(R=new a.ColorKit(u).setAlpha(Gs).toString()),this._columnHeaderBackground.setProps({fill:R}),this._columnHeaderBackground.resize(i-t,b),this._columnHeaderBorder.setProps({fill:f}),this._columnHeaderBorder.transformByState({width:i-t,height:v,top:b-v+1/d}),this._columnHeaderGroup.show(),this._columnHeaderGroup.translate(t,0)}else this._columnHeaderGroup.hide();if(this._columnHeaderGroup.makeDirty(!0),this._highlightHeader&&C>0){let R=h;l===a.RANGE_TYPE.ROW&&(R=new a.ColorKit(u).setAlpha(Gs).toString()),this._rowHeaderBackground.setProps({fill:R}),this._rowHeaderBackground.resize(C,s-o),this._rowHeaderBorder.setProps({fill:g}),this._rowHeaderBorder.transformByState({width:p,height:s-o,left:C-p+1/d}),this._rowHeaderGroup.show(),this._rowHeaderGroup.translate(0,o)}else this._rowHeaderGroup.hide();this._rowHeaderGroup.makeDirty(!0)}_updateBackgroundControl(e){const{startX:t,startY:o,endX:i,endY:s}=this._selectionRenderModel,l=this._getScale(),{fill:c=e.fill}=e;let{strokeWidth:d}=e;d/=l;const u=this._selectionRenderModel.highlightToSelection();if(!u){this._backgroundControlTop.resize(i-t,s-o),this._backgroundControlTop.setProps({fill:c}),this._backgroundControlBottom.resize(0,0),this._backgroundControlMiddleLeft.resize(0,0),this._backgroundControlMiddleRight.resize(0,0);return}const{startX:h,startY:g,endX:S,endY:f}=u,p=d/2,v={left:-p,top:-p,width:i-t+p*2,height:g-o+p};v.height<0&&(v.width=0,v.height=0),this._backgroundControlTop.transformByState(v);const C={left:-p,top:g-o,width:h-t+p,height:f-g};C.width<0&&(C.width=0,C.height=0),this._backgroundControlMiddleLeft.transformByState(C);const b={left:S-t-p,top:g-o,width:i-S+p*2,height:f-g};b.width<0&&(b.width=0,b.height=0),this._backgroundControlMiddleRight.transformByState(b);const R={left:-p,top:f-o,width:i-t+p*2,height:s-f+p};R.height<0&&(R.width=0,R.height=0),this._backgroundControlBottom.transformByState(R),this._backgroundControlTop.setProps({fill:c}),this._backgroundControlMiddleLeft.setProps({fill:c}),this._backgroundControlMiddleRight.setProps({fill:c}),this._backgroundControlBottom.setProps({fill:c})}_updateWidgets(e){const{startX:t,startY:o,endX:i,endY:s}=this._selectionRenderModel,{stroke:l=e.stroke,widgets:c=e.widgets,widgetStroke:d=e.widgetStroke}=e,u=this._getScale();let{widgetSize:h,widgetStrokeWidth:g}=e;h/=u,g/=u;const S={left:-h/2+g/2,center:(i-t)/2-h/2+g/2,right:i-t-h/2+g/2,top:-h/2,middle:(s-o)/2-h/2,bottom:s-o-h/2+g/2},f=h-g;this._widgetRects.forEach(p=>{p.setProps({fill:l,stroke:d})}),c.tl===!0?(this._topLeftWidget.transformByState({height:f,width:f,left:S.left,top:S.top,strokeWidth:g}),this._topLeftWidget.show()):this._topLeftWidget.hide(),c.tc===!0?(this._topCenterWidget.transformByState({height:f,width:f,left:S.center,top:S.top,strokeWidth:g}),this._topCenterWidget.show()):this._topCenterWidget.hide(),c.tr===!0?(this._topRightWidget.transformByState({height:f,width:f,left:S.right,top:S.top,strokeWidth:g}),this._topRightWidget.show()):this._topRightWidget.hide(),c.ml===!0?(this._middleLeftWidget.transformByState({height:f,width:f,left:S.left,top:S.middle,strokeWidth:g}),this._middleLeftWidget.show()):this._middleLeftWidget.hide(),c.mr===!0?(this._middleRightWidget.transformByState({height:f,width:f,left:S.right,top:S.middle,strokeWidth:g}),this._middleRightWidget.show()):this._middleRightWidget.hide(),c.bl===!0?(this._bottomLeftWidget.transformByState({height:f,width:f,left:S.left,top:S.bottom,strokeWidth:g}),this._bottomLeftWidget.show()):this._bottomLeftWidget.hide(),c.bc===!0?(this._bottomCenterWidget.transformByState({height:f,width:f,left:S.center,top:S.bottom,strokeWidth:g}),this._bottomCenterWidget.show()):this._bottomCenterWidget.hide(),c.br===!0?(this._bottomRightWidget.transformByState({height:f,width:f,left:S.right,top:S.bottom,strokeWidth:g}),this._bottomRightWidget.show()):this._bottomRightWidget.hide()}_hasWidgets(e){if(e==null)return!1;const t=Object.keys(e);if(t.length===0)return!1;for(const o of t)if(e[o]===!0)return!0;return!1}_getScale(){const{scaleX:e,scaleY:t}=this._scene.getAncestorScale();return Math.max(e,t)}_stopAntLineAnimation(){this._antLineOffset=0,w.cancelRequestFrame(this._antRequestNewFrame)}_startAntLineAnimation(){const e=this._getScale();this._antLineOffset+=.6/e,this._antLineOffset>160/e&&(this._antLineOffset=0),this.dashedRect.setProps({strokeDashOffset:-this._antLineOffset}),this._antRequestNewFrame=w.requestNewFrame(()=>{this._startAntLineAnimation()})}}class Td extends w.Layer{render(r,e=!1){const t=a.Tools.now();return super.render(r,e),this._afterRender(t),this}_afterRender(r){this.scene.getEngine().renderFrameTimeMetric$.next(["selectionLayer",a.Tools.now()-r])}}const ve=a.createIdentifier("univer.sheet.selection-render-service");class ms extends a.Disposable{constructor(e,t,o,i,s){super();E(this,"_downObserver");E(this,"_scenePointerMoveSub");E(this,"_scenePointerUpSub");E(this,"_controlFillConfig$",new O.BehaviorSubject(null));E(this,"controlFillConfig$",this._controlFillConfig$.asObservable());E(this,"_selectionControls",[]);E(this,"_startRangeWhenPointerDown",{startY:0,endY:0,startX:0,endX:0,startRow:-1,endRow:-1,startColumn:-1,endColumn:-1});E(this,"_activeControlIndex",-1);E(this,"_startViewportPosX",0);E(this,"_startViewportPosY",0);E(this,"_scrollTimer");E(this,"_cancelDownSubscription");E(this,"_cancelUpSubscription");E(this,"_skeleton");E(this,"_scene");E(this,"_highlightHeader",!0);E(this,"_rangeType",a.RANGE_TYPE.NORMAL);E(this,"_selectionStyle");E(this,"_remainLastEnabled",!1);E(this,"_skipLastEnabled",!1);E(this,"_singleSelectionEnabled",!1);E(this,"_selectionMoveEnd$",new O.BehaviorSubject([]));E(this,"selectionMoveEnd$",this._selectionMoveEnd$.asObservable());E(this,"_selectionMoving$",new O.Subject);E(this,"selectionMoving$",this._selectionMoving$.asObservable());E(this,"_selectionMoveStart$",new O.Subject);E(this,"selectionMoveStart$",this._selectionMoveStart$.asObservable());E(this,"_selectionMoving",!1);E(this,"_selectionTheme");E(this,"_activeViewport");E(this,"interceptor",new a.InterceptorManager({RANGE_MOVE_PERMISSION_CHECK:Hi,RANGE_FILL_PERMISSION_CHECK:Vi}));E(this,"_escapeShortcutDisposable",null);this._injector=e,this._themeService=t,this._shortcutService=o,this._sheetSkeletonManagerService=i,this.contextService=s,this._initSelectionThemeFromThemeService(),this._initMoving()}get selectionMoving(){return this._selectionMoving}get _shouldDetectMergedCells(){return this._rangeType===a.RANGE_TYPE.NORMAL}_initMoving(){this.disposeWithMe(this._selectionMoving$.subscribe(()=>{this._selectionMoving=!0})),this.disposeWithMe(this._selectionMoveEnd$.subscribe(()=>{this._selectionMoving=!1}))}_setSelectionStyle(e){this._selectionStyle=e}getViewPort(){return this._activeViewport}setSingleSelectionEnabled(e=!1){this._singleSelectionEnabled=e}newSelectionControl(e,t,o){const i=this.getSelectionControls().length,{rowHeaderWidth:s,columnHeaderHeight:l}=t,c=new co(e,i,this._selectionTheme,{highlightHeader:this._highlightHeader,rowHeaderWidth:s,columnHeaderHeight:l});this._selectionControls.push(c);const d=Me(o,t);return c.updateRangeBySelectionWithCoord(d,t),c.setControlExtension({skeleton:t,scene:e,themeService:this._selectionTheme,injector:this._injector,selectionHooks:{selectionMoveEnd:()=>{this._selectionMoveEnd$.next(this.getSelectionDataWithStyle())}}}),c}resetSelectionsByModelData(e){const t=this.getSelectionControls(),o=this._skeleton;if(!(!t||!o)){for(let i=0,s=e.length;i<s;i++){const l=e[i],c=Me(l,this._skeleton),d=t[i];d?d.updateRangeBySelectionWithCoord(c,o):this.isSelectionEnabled()&&this.newSelectionControl(this._scene,o,l)}e.length<t.length&&t.splice(e.length).forEach(s=>s.dispose())}}refreshSelectionMoveStart(){this._selectionMoveStart$.next(this.getSelectionDataWithStyle())}refreshSelectionMoveEnd(){this._selectionMoveEnd$.next(this.getSelectionDataWithStyle())}_initSelectionThemeFromThemeService(){const e=this._themeService.getCurrentTheme();this._selectionTheme=new a.ThemeService,this._selectionTheme.setTheme(e)}setSelectionTheme(e){this._selectionTheme.setTheme(e)}_changeRuntime(e,t,o){this._skeleton=e,this._scene=t,this._activeViewport=o||(t==null?void 0:t.getViewports()[0]),t.findLayerByZIndex(tr)||t.addLayer(new Td(t,[],tr))}getSkeleton(){return this._skeleton}getSelectionDataWithStyle(){const e=this._selectionControls,[t,o]=this._skeleton.getLocation();return e.map(i=>{const s=i.getValue();return s.rangeWithCoord.sheetId=o,s.rangeWithCoord.unitId=t,s})}getSelectionControls(){return this._selectionControls}_addSelectionControlByModelData(e){var l;const t=this._skeleton,o=(l=e.style)!=null?l:bt(this._selectionTheme),i=this._scene;return e.style=o,this.newSelectionControl(i,t,e)}_clearAllSelectionControls(){const e=this._selectionControls;for(const t of e)t.dispose();this._selectionControls.length=0}_getFreeze(){var t;return(t=this._sheetSkeletonManagerService.getCurrentParam())==null?void 0:t.skeleton.getWorksheetConfig().freeze}_getViewportByCell(e,t){if(e===void 0||t===void 0)return null;const o=this._getFreeze();if(!o||o.startRow<=0&&o.startColumn<=0)return this._scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN);if(e>o.startRow&&t>o.startColumn)return this._scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN);if(e<=o.startRow&&t<=o.startColumn)return this._scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP);if(e<=o.startRow&&t>o.startColumn)return this._scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP);if(e>o.startRow&&t<=o.startColumn)return this._scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT)}getActiveRange(){const e=this.getSelectionControls(),t=e&&e[e.length-1].model;return t&&{startRow:t.startRow,startColumn:t.startColumn,endRow:t.endRow,endColumn:t.endColumn}}setActiveSelectionIndex(e){this._activeControlIndex=e}resetActiveSelectionIndex(){this._activeControlIndex=-1}getActiveSelectionControl(){const e=this.getSelectionControls();if(e)return this._activeControlIndex<0?e[e.length-1]:e[this._activeControlIndex]}endSelection(){var e;this._clearUpdatingListeners(),this._selectionMoveEnd$.next(this.getSelectionDataWithStyle()),(e=this._escapeShortcutDisposable)==null||e.dispose(),this._escapeShortcutDisposable=null}_reset(){var e;this._clearAllSelectionControls(),(e=this._downObserver)==null||e.unsubscribe(),this._downObserver=null}_setupPointerMoveListener(e,t,o,i=w.ScrollTimerType.ALL,s,l){var f,p;let c=0,d=0,u=s,h=l;this._scrollTimer=w.ScrollTimer.create(this._scene,i),this._scrollTimer.startScroll((f=e==null?void 0:e.left)!=null?f:0,(p=e==null?void 0:e.top)!=null?p:0,e);const g=this._scene,S=g.getActiveViewportByCoord(w.Vector2.FromArray([s,l]));this._scenePointerMoveSub=g.onPointerMove$.subscribeEvent(v=>{var D,W,H,U,B,F,L,j,z;const{offsetX:C,offsetY:b}=v,{x:R,y:T}=g.getCoordRelativeToViewport(w.Vector2.FromArray([C,b]));this._movingHandler(R,T,t,o);let M=R,y=T;const P=this.getActiveSelectionControl(),x=this._getFreeze(),A=P==null?void 0:P.model,k=(D=g.getActiveViewportByCoord(w.Vector2.FromArray([C,b])))!=null?D:this._getViewportByCell(A==null?void 0:A.endRow,A==null?void 0:A.endColumn);if((()=>{if(!S||!k||!e)return!1;const q=[w.SHEET_VIEWPORT_KEY.VIEW_MAIN,w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP,w.SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP,w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT];return q.includes(S.viewportKey)&&q.includes(k.viewportKey)})()){if(!S||!k||!e)return!1;const q=u<e.left&&R>e.left||u>e.left&&R<e.left,te=h<e.top&&T>e.top||h>e.top&&T<e.top;q&&(c+=1),te&&(d+=1);const Q=S.viewportKey,re=k.viewportKey;if(Q===w.SHEET_VIEWPORT_KEY.VIEW_ROW_TOP)b<e.top&&((W=A==null?void 0:A.endRow)!=null?W:0)<((H=x==null?void 0:x.startRow)!=null?H:0)?y=e.top:te&&d%2===1&&e.scrollToViewportPos({viewportScrollY:0});else if(Q===w.SHEET_VIEWPORT_KEY.VIEW_COLUMN_LEFT)C<e.left&&((U=A==null?void 0:A.endColumn)!=null?U:0)<((B=x==null?void 0:x.startColumn)!=null?B:0)?M=e.left:q&&c%2===1&&e.scrollToViewportPos({viewportScrollX:0});else if(Q===re){let se=!1,X=!1;Q===w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP?(se=!0,X=!0):Q===w.SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP?X=!0:Q===w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT&&(se=!0),((F=A==null?void 0:A.endRow)!=null?F:0)>((L=x==null?void 0:x.startRow)!=null?L:0)&&(X=!1),((j=A==null?void 0:A.endColumn)!=null?j:0)>((z=x==null?void 0:x.startColumn)!=null?z:0)&&(se=!1),se&&(M=e.left),X&&(y=e.top)}else{const se={x:S.scrollX,y:S.scrollY},X={x:k.scrollX,y:k.scrollY},Y=se.x!==X.x&&q&&c%2===1,G=se.y!==X.y&&te&&d%2===1;(Y||G)&&(e.scrollToBarPos({x:Y?se.x:void 0,y:G?se.y:void 0}),Y||(M=e.left),G||(y=e.top)),(Q===w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP&&re===w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT||re===w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP&&Q===w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT)&&(M=e.left),(Q===w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP&&re===w.SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP||re===w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP&&Q===w.SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP)&&(y=e.top)}u=R,h=T}this._scrollTimer.scrolling(M,y,()=>{this._movingHandler(R,T,t,o)})})}attachSelectionWithCoord(e){return Me(e,this._skeleton)}attachPrimaryWithCoord(e){return $n(this._skeleton,e)}getSelectionCellByPosition(e,t){return this.getCellWithCoordByOffset(e,t)}getCellWithCoordByOffset(e,t,o){const i=this._scene,s=o!=null?o:this._skeleton,l=i.getViewportScrollXY(i.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN)),{scaleX:c,scaleY:d}=i.getAncestorScale();return s.getCellWithCoordByOffset(e,t,c,d,l)}_movingHandler(e,t,o,i){var M,y,P,x,A;const s=this._skeleton,l=this._scene,[c,d]=s.getLocation(),u={startRow:(M=o==null?void 0:o.model.startRow)!=null?M:-1,endRow:(y=o==null?void 0:o.model.endRow)!=null?y:-1,startColumn:(P=o==null?void 0:o.model.startColumn)!=null?P:-1,endColumn:(x=o==null?void 0:o.model.endColumn)!=null?x:-1},h=l.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN),g=(A=this._getViewportByCell(u.endRow,u.endColumn))!=null?A:h,S=l.getScrollXYInfoByViewport(w.Vector2.FromArray([this._startViewportPosX,this._startViewportPosY]),g),{scaleX:f,scaleY:p}=l.getAncestorScale();i===a.RANGE_TYPE.ROW?e=Number.POSITIVE_INFINITY:i===a.RANGE_TYPE.COLUMN&&(t=Number.POSITIVE_INFINITY);const v=this._skeleton.getCellByOffset(e,t,f,p,S);if(!v)return;let C={startRow:Math.min(v.startRow,this._startRangeWhenPointerDown.startRow),startColumn:Math.min(v.startColumn,this._startRangeWhenPointerDown.startColumn),endRow:Math.max(v.endRow,this._startRangeWhenPointerDown.endRow),endColumn:Math.max(v.endColumn,this._startRangeWhenPointerDown.endColumn)};this._shouldDetectMergedCells&&(C=s.expandRangeByMerge(C));const R=Me({range:C,primary:void 0,style:null},s);R.rangeWithCoord.unitId=c,R.rangeWithCoord.sheetId=d,R.rangeWithCoord.rangeType=i;const T=u.startRow!==C.startRow||u.startColumn!==C.startColumn||u.endRow!==C.endRow||u.endColumn!==C.endColumn;o!=null&&T&&(o.updateRangeBySelectionWithCoord(R),this._selectionMoving$.next(this.getSelectionDataWithStyle()))}_clearUpdatingListeners(){var t,o,i,s,l;this._scene.enableObjectsEvent(),(t=this._scenePointerMoveSub)==null||t.unsubscribe(),this._scenePointerMoveSub=null,(o=this._scenePointerUpSub)==null||o.unsubscribe(),this._scenePointerUpSub=null,(i=this._cancelDownSubscription)==null||i.unsubscribe(),this._cancelDownSubscription=null,(s=this._cancelUpSubscription)==null||s.unsubscribe(),this._cancelUpSubscription=null,(l=this._scrollTimer)==null||l.dispose()}_addEndingListeners(){var o,i,s;const e=this._scene,t=(o=e.getEngine())==null?void 0:o.activeScene;!t||t===e||((i=this._cancelDownSubscription)==null||i.unsubscribe(),this._cancelDownSubscription=null,(s=this._cancelUpSubscription)==null||s.unsubscribe(),this._cancelUpSubscription=null,this._cancelDownSubscription=t.onPointerDown$.subscribeEvent(()=>this._clearUpdatingListeners()),this._cancelUpSubscription=t.onPointerUp$.subscribeEvent(()=>this._clearUpdatingListeners()))}_getSelectionWithCoordByOffset(e,t,o,i,s){const l=this._skeleton;if(l==null)return null;if(this._shouldDetectMergedCells){const C=l==null?void 0:l.getCellWithCoordByOffset(e,t,o,i,s,{firstMatch:!0});if(!C)return;const b=a.convertCellToRange(C);return{primaryWithCoord:C,rangeWithCoord:b}}const{row:c,column:d}=l.getCellIndexByOffset(e,t,o,i,s),u=l.getNoMergeCellWithCoordByIndex(c,d),{startX:h,startY:g,endX:S,endY:f}=u,p={startY:g,endY:f,startX:h,endX:S,startRow:c,endRow:c,startColumn:d,endColumn:d};return{primaryWithCoord:{mergeInfo:p,actualRow:c,actualColumn:d,isMerged:!1,isMergedMainCell:!1,startY:g,endY:f,startX:h,endX:S},rangeWithCoord:p}}_checkClearPreviousControls(e){this.getSelectionControls().length!==0&&(!e.ctrlKey&&!e.shiftKey&&!this._remainLastEnabled||this._singleSelectionEnabled&&!e.shiftKey)&&this._clearAllSelectionControls()}_makeSelectionByTwoCells(e,t,o,i,s){const{actualRow:l,actualColumn:c,mergeInfo:d}=e;this._startRangeWhenPointerDown={...e.mergeInfo};const u=Math.min(l,t.startRow,d.startRow),h=Math.max(l,t.endRow,d.endRow),g=Math.min(c,t.startColumn,d.startColumn),S=Math.max(c,t.endColumn,d.endColumn),p={range:o.expandRangeByMerge({startRow:u,startColumn:g,endRow:h,endColumn:S}),primary:null,style:null},v=Me(p,o);s.updateRangeBySelectionWithCoord(v)}isSelectionEnabled(){return this.contextService.getContextValue(m.SELECTIONS_ENABLED)}isSelectionDisabled(){return this.contextService.getContextValue(m.SELECTIONS_ENABLED)===!1}inRefSelectionMode(){return this.contextService.getContextValue(m.REF_SELECTIONS_ENABLED)}}function gs(n){return{range:{startRow:0,startColumn:0,endRow:n.getRowCount()-1,endColumn:n.getColumnCount()-1,rangeType:a.RANGE_TYPE.ALL},primary:kr(n).primary,style:null}}function kr(n){return Qa(n,{startRow:0,startColumn:0,endRow:0,endColumn:0})}function Qa(n,r){const e=n.worksheet.getCellInfoInMergeData(r.startRow,r.startColumn),t=n.worksheet.getCellInfoInMergeData(r.endRow,r.endColumn);return{range:{startRow:e.startRow,startColumn:e.startColumn,endRow:t.endRow,endColumn:t.endColumn,rangeType:a.RANGE_TYPE.NORMAL},primary:{actualRow:e.startRow,actualColumn:e.startColumn,startRow:e.startRow,startColumn:e.startColumn,endRow:e.endRow,endColumn:e.endColumn,isMerged:e.isMerged,isMergedMainCell:e.isMergedMainCell},style:null}}var wd=Object.getOwnPropertyDescriptor,yd=(n,r,e,t)=>{for(var o=t>1?void 0:t?wd(r,e):r,i=n.length-1,s;i>=0;i--)(s=n[i])&&(o=s(o)||o);return o},Zs=(n,r)=>(e,t)=>r(e,t,n);exports.SheetSkeletonManagerService=class extends a.Disposable{constructor(e,t,o){super();E(this,"_sheetId","");E(this,"_sheetSkeletonParamStore",new Map);E(this,"_currentSkeleton$",new O.BehaviorSubject(null));E(this,"currentSkeleton$",this._currentSkeleton$.asObservable());E(this,"_currentSkeletonBefore$",new O.BehaviorSubject(null));E(this,"currentSkeletonBefore$",this._currentSkeletonBefore$.asObservable());this._context=e,this._injector=t,this._sheetSkService=o,this.disposeWithMe(()=>{this._currentSkeletonBefore$.complete(),this._currentSkeleton$.complete(),this._sheetSkeletonParamStore.forEach(i=>this.disposeSkeleton(i.sheetId)),this._sheetSkeletonParamStore.clear()}),this._initRemoveSheet()}_initRemoveSheet(){this.disposeWithMe(this._context.unit.sheetDisposed$.subscribe(e=>{this.disposeSkeleton(e.getSheetId())}))}getCurrentSkeleton(){var e;return(e=this.getCurrentParam())==null?void 0:e.skeleton}getCurrent(){return this.getCurrentParam()}getCurrentParam(){return this._getSkeletonParam(this._sheetId)}getSkeleton(e){return this._getSkeleton(e)}getSkeletonParam(e){return this._getSkeletonParam(e)}getWorksheetSkeleton(e){return this.getSkeletonParam(e)}getUnitSkeleton(e,t){const o=this._getSkeletonParam(t);return o!=null&&(o.unitId=e),o}setCurrent(e){this._setCurrent(e.sheetId)}setSkeletonParam(e,t){this._sheetSkService.setSkeleton(t.unitId,e,t.skeleton),this._sheetSkeletonParamStore.set(e,t)}_setCurrent(e){this._sheetId=e;const t=this._getSkeletonParam(e),o=this._context.unitId;if(t!=null)this.reCalculate(t);else{const l=this._context.unit.getSheetBySheetId(e);if(l==null)return;const c=this._context.scene,d=this._buildSkeleton(l,c);this.setSkeletonParam(e,{unitId:o,sheetId:e,skeleton:d,dirty:!1})}const i=this._getSkeletonParam(e);this._currentSkeletonBefore$.next(i),this._currentSkeleton$.next(i)}reCalculate(e){e||(e=this.getCurrentParam()),e!=null&&(e.dirty&&(e.skeleton.makeDirty(!0),e.dirty=!1),e.skeleton.calculate())}makeDirty(e,t=!0){const o=this._getSkeletonParam(e.sheetId);o!=null&&(o.dirty=t)}getOrCreateSkeleton(e){return this.ensureSkeleton(e.sheetId)}ensureSkeleton(e){const t=this._getSkeletonParam(e);if(t)return t.skeleton;const i=this._context.unit.getSheetBySheetId(e);if(!i)return;const s=this._buildSkeleton(i);return this.setSkeletonParam(e,{unitId:this._context.unitId,sheetId:e,skeleton:s,dirty:!1}),s}disposeSkeleton(e){const t=this.getSkeletonParam(e);t&&(t.skeleton.dispose(),this._sheetSkeletonParamStore.delete(e),this._sheetSkService.deleteSkeleton(t.unitId,e))}attachRangeWithCoord(e){const t=this.getCurrentSkeleton();return t?bn(t,e):null}_getSkeletonParam(e){return this._sheetSkeletonParamStore.get(e)}_getSkeleton(e){const t=this._getSkeletonParam(e);return t?t.skeleton:null}_buildSkeleton(e,t){return this._injector.createInstance(w.SpreadsheetSkeleton,e,this._context.unit.getStyles())}setColumnHeaderSize(e,t,o){var u;if(!e)return;const i=(u=this.getWorksheetSkeleton(t))==null?void 0:u.skeleton;if(!i)return;i.columnHeaderHeight=o,e.scene.getViewports()[0].top=o,e.scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_COLUMN_RIGHT).setViewportSize({height:o}),e.scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_COLUMN_LEFT).setViewportSize({height:o}),e.scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_ROW_BOTTOM).setViewportSize({top:o}),e.scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_ROW_TOP).setViewportSize({top:o}),e.scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_LEFT_TOP).setViewportSize({height:o});const s=e==null?void 0:e.with(m.SheetsSelectionsService),l=e==null?void 0:e.with(ve),c=s.getCurrentSelections();l.resetSelectionsByModelData(c);const d=this.getUnitSkeleton(e.unitId,t);d&&(d.commandId=Ar.id,this._currentSkeleton$.next(d))}setRowHeaderSize(e,t,o){var f;const i=(f=this.getWorksheetSkeleton(t))==null?void 0:f.skeleton;if(!e||!i)return;i.rowHeaderWidth=o;const s=e.scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_LEFT_TOP).width||46,l=o-s,c=e.scene.getViewports()[0].left;e.scene.getViewports()[0].left=c+l,e.scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_ROW_BOTTOM).setViewportSize({width:o}),e.scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_ROW_TOP).setViewportSize({width:o}),e.scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_COLUMN_LEFT).setViewportSize({left:o});const d=e.scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_COLUMN_RIGHT).left||0;e.scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_COLUMN_RIGHT).setViewportSize({left:d+l}),e.scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_LEFT_TOP).setViewportSize({width:o});const u=e==null?void 0:e.with(m.SheetsSelectionsService),h=e==null?void 0:e.with(ve),g=u.getCurrentSelections();h.resetSelectionsByModelData(g);const S=this.getCurrent();S&&(S.commandId=xr.id,this._currentSkeleton$.next(S))}};exports.SheetSkeletonManagerService=yd([Zs(1,a.Inject(a.Injector)),Zs(2,a.Inject(m.SheetSkeletonService))],exports.SheetSkeletonManagerService);function ht(){const n=I.useDependency(a.IUniverInstanceService),r=I.useObservable(()=>n.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET),void 0,void 0,[]);return r!=null?r:null}function Md(n){return I.useObservable(()=>{var e;return(e=n==null?void 0:n.activeSheet$)!=null?e:O.of(null)},void 0,void 0,[n])}function Pd(){const n=I.useDependency(a.IUniverInstanceService);return I.useObservable(()=>O.merge([n.getTypeOfUnitAdded$(a.UniverInstanceType.UNIVER_SHEET),n.getTypeOfUnitDisposed$(a.UniverInstanceType.UNIVER_SHEET)]).pipe(O.map(()=>n.getAllUnitsForType(a.UniverInstanceType.UNIVER_SHEET)),O.startWith(n.getAllUnitsForType(a.UniverInstanceType.UNIVER_SHEET))),[],void 0,[n])}const Od="SheetUI";var Ss=(n=>(n.FILTER_PANEL_EMBED_POINT="filter-panel-embed-point",n.SHEETS_FOOTER="sheets-footer",n.FORMULA_AUX="formula-aux",n))(Ss||{});const Rt="sheets-ui.config",Ja=Symbol("HIDE_STATUS_BAR_STATISTIC"),Ui={formulaBar:!0,maxAutoHeightCount:1e3};var xd=Object.getOwnPropertyDescriptor,Ad=(n,r,e,t)=>{for(var o=t>1?void 0:t?xd(r,e):r,i=n.length-1,s;i>=0;i--)(s=n[i])&&(o=s(o)||o);return o},Ln=(n,r)=>(e,t)=>r(e,t,n);const fs=["ff","fs","tr","tb"];exports.AutoHeightController=class extends a.Disposable{constructor(r,e,t,o,i){super(),this._renderManagerService=r,this._sheetInterceptorService=e,this._selectionManagerService=t,this._univerInstanceService=o,this._configService=i,this._initialize()}_getRangesScope(r){let e,t;for(const{startRow:o,endRow:i}of r)e=e===void 0?o:Math.min(e,o),t=t===void 0?i:Math.max(t,i);return t-e+1}getUndoRedoParamsOfAutoHeight(r){const{_univerInstanceService:e,_configService:t}=this,o=e.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET),i=o.getActiveSheet(),s=o.getUnitId(),l=i.getSheetId(),c=this._renderManagerService.getRenderById(s).with(exports.SheetSkeletonManagerService);if(!l||!c.getCurrentParam())return{redos:[],undos:[]};const d=t.getConfig(Rt),u=this._getRangesScope(r);if((d==null?void 0:d.maxAutoHeightCount)<u)return{redos:[],undos:[]};const{skeleton:h}=c.getCurrentParam(),g=h.calculateAutoHeightInRange(r),S={subUnitId:l,unitId:s,rowsAutoHeightInfo:g},f=m.SetWorksheetRowAutoHeightMutationFactory(S,i);return{undos:[{id:m.SetWorksheetRowAutoHeightMutation.id,params:f}],redos:[{id:m.SetWorksheetRowAutoHeightMutation.id,params:S}]}}_initialize(){const{_sheetInterceptorService:r,_selectionManagerService:e}=this;this.disposeWithMe(r.interceptCommand({getMutations:t=>{if(t.id===m.SetRangeValuesCommand.id){const o=t.params;return this.getUndoRedoParamsOfAutoHeight(o.range)}return{redos:[],undos:[]}}})),this.disposeWithMe(r.interceptCommand({getMutations:t=>t.id!==m.SetWorksheetRowIsAutoHeightCommand.id?{redos:[],undos:[]}:this.getUndoRedoParamsOfAutoHeight(t.params.ranges)})),this.disposeWithMe(r.interceptCommand({getMutations:t=>{var i,s;if(t.id!==m.SetStyleCommand.id)return{redos:[],undos:[]};if(!fs.includes((i=t.params)==null?void 0:i.style.type))return{redos:[],undos:[]};const o=(s=e.getCurrentSelections())==null?void 0:s.map(l=>l.range);return o!=null&&o.length?this.getUndoRedoParamsOfAutoHeight(o):{redos:[],undos:[]}}})),this.disposeWithMe(r.interceptAfterCommand({getMutations:t=>{if(t.id===m.MoveRangeCommand.id){const o=t.params;return this.getUndoRedoParamsOfAutoHeight([o.fromRange,o.toRange])}if(t.id===m.ReorderRangeCommand.id){const o=t.params;return this.getUndoRedoParamsOfAutoHeight([o.range])}return{redos:[],undos:[]}}}))}};exports.AutoHeightController=Ad([Ln(0,w.IRenderManagerService),Ln(1,a.Inject(m.SheetInterceptorService)),Ln(2,a.Inject(m.SheetsSelectionsService)),Ln(3,a.Inject(a.IUniverInstanceService)),Ln(4,a.IConfigService)],exports.AutoHeightController);function Sn(n,r,e,t){const o=r.get(a.IUniverInstanceService),i=e?o.getUnit(e,a.UniverInstanceType.UNIVER_SHEET):o.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET),s=t?i==null?void 0:i.getSheetBySheetId(t):i==null?void 0:i.getActiveSheet();if(!s)return null;const{startRow:l,endRow:c,startColumn:d,endColumn:u}=n,h=[],g=[];for(let S=l;S<=c;S++)s.getRowFiltered(S)||h.push(S);for(let S=d;S<=u;S++)g.push(S);return{rows:h,cols:g}}function Et(n){const{rows:r,cols:e}=n;return{startRow:r[0],endRow:r[r.length-1],startColumn:e[0],endColumn:e[e.length-1]}}function Kt(n){let r=[],e=[];const t=[];return n.forEach(o=>{r=r.concat(o.rows),e=e.concat(o.cols)}),r=Array.from(new Set(r)).sort((o,i)=>o-i),e=Array.from(new Set(e)).sort((o,i)=>o-i),n.forEach(o=>{t.push({startRow:r.findIndex(i=>i===o.rows[0]),endRow:r.findIndex(i=>i===o.rows[o.rows.length-1]),startColumn:e.findIndex(i=>i===o.cols[0]),endColumn:e.findIndex(i=>i===o.cols[o.cols.length-1])})}),{ranges:t,mapFunc:(o,i)=>({row:r[o],col:e[i]})}}function kd(n){const r=new a.ObjectMatrix;return n.forEach(e=>{const{rows:t,cols:o}=e;t.forEach(i=>{o.forEach(s=>{r.setValue(i,s,{v:null,p:null,f:null,si:null,custom:null})})})}),r.getData()}const Li={零:0,一:1,二:2,三:3,四:4,五:5,六:6,七:7,八:8,九:9},nr=["零","一","二","三","四","五","六","七","八","九"],Ks=["","万","亿","万亿","亿亿"],Nd=["","十","百","千"],$a={十:{value:10,secUnit:!1},百:{value:100,secUnit:!1},千:{value:1e3,secUnit:!1},万:{value:1e4,secUnit:!0},亿:{value:1e8,secUnit:!0}};function ct(n){if(!n)return 0;let r=0,e=0,t=0,o=!1;const i=n.split("");for(let s=0;s<i.length;s++){const l=Li[i[s]];if(typeof l<"u")t=l,s===i.length-1&&(e+=t);else{const c=$a[i[s]],d=c.value;o=c.secUnit,o?(e=(e+t)*d,r+=e,e=0):e+=t*d,t=0}}return r+e}function Dd(n){let r="",e="",t=0,o=!0;for(;n>0;){const i=n%10;i===0?o||(o=!0,e=nr[i]+e):(o=!1,r=nr[i],r+=Nd[t],e=r+e),t++,n=Math.floor(n/10)}return e}function Hd(n){let r=0,e="",t="",o=!1;if(n===0)return nr[0];for(;n>0;){const i=n%1e4;o&&(t=nr[0]+t),e=Dd(i),e+=i!==0?Ks[r]:Ks[0],t=e+t,o=i<1e3&&i>0,n=Math.floor(n/1e4),r++}return t}function Vd(n){if(!n)return!1;let r=!0;if(n)if(n.length===1)n==="日"||n in Li?r=!0:r=!1;else{const e=n.split("");for(let t=0;t<e.length;t++)if(!(e[t]in Li||e[t]in $a)){r=!1;break}}return r}function Uo(n){if(!n)return{isExtendNumber:!1};const r=/0|([1-9]+[0-9]*)/g,e=r.test(n);if(e){const t=n.match(r);if(t&&t.length>0){const o=t[t.length-1],i=n.lastIndexOf(o),s=n.substr(0,i),l=n.substr(i+o.length);return{isExtendNumber:!0,matchTxt:Number(o),beforeTxt:s,afterTxt:l}}return{isExtendNumber:!1}}return{isExtendNumber:e}}function Wd(n){let r;return n.length===2&&(n==="周一"||n==="周二"||n==="周三"||n==="周四"||n==="周五"||n==="周六"||n==="周日")?r=!0:r=!1,r}function Ud(n){let r;return n.length===3&&(n==="星期一"||n==="星期二"||n==="星期三"||n==="星期四"||n==="星期五"||n==="星期六"||n==="星期日")?r=!0:r=!1,r}function Ld(n,r){let e=0;for(let t=0;t<n.length&&n[t]<r;t++)e++;return e}function uo(n){let r=!0;const e=n[1]-n[0];for(let t=1;t<n.length;t++)if(n[t]-n[t-1]!==e){r=!1;break}return r}function Bd(n,r,e){const t=[],o=Math.floor(r/n),i=r%n;let s=0;if(o>0){for(let l=0;l<o;l++)for(let c=0;c<e.length;c++)t[e[c]+l*n]=s,s++;for(let l=0;l<e.length&&e[l]<i;l++)t[e[l]+n*o]=s,s++}else for(let l=0;l<e.length&&e[l]<i;l++)t[e[l]]=s,s++;return t}function jt(n,r){const e=[];for(let t=1;t<=r;t++){const o=(t-1)%n.length,i=a.Tools.deepClone(n[o]);zt(i),e.push({v:null,s:null,p:null,f:null,si:null,t:null,...i})}return e}function Fd(n,r){var t;const e=[];for(let o=1;o<=r;o++){const i=(o-1)%n.length,s={s:(t=n[i])==null?void 0:t.s};e.push(s)}return e}function jd(n){let r=!0;const e=n[1]/n[0];for(let t=1;t<n.length;t++)if(n[t]/n[t-1]!==e){r=!1;break}return r}function zd(n){const r=[];for(let e=1;e<=n;e++)r.push(e);return r}function or(n,r,e){var i,s,l,c;const t=[],o=[];for(let d=0;d<n.length;d++)o.push(Number((i=n[d])==null?void 0:i.v));if(n.length>2&&jd(o))for(let d=1;d<=r;d++){const u=(d-1)%n.length,h=a.Tools.deepClone(n[u]);zt(h);const g=Number((s=n[n.length-1])==null?void 0:s.v)*(Number((l=n[1])==null?void 0:l.v)/Number((c=n[0])==null?void 0:c.v))**d;h&&($s(h)&&(h.v=g),t.push(h))}else{const d=zd(n.length);for(let u=1;u<=r;u++){const h=(u-1)%n.length,g=a.Tools.deepClone(n[h]);zt(g);const S=e===a.Direction.DOWN||e===a.Direction.RIGHT,f=Xd(n.length+u,o,d,S);g&&($s(g)&&(g.v=f),t.push(g))}}return t}function Xd(n,r,e,t=!0){function o(h){let g=0;for(let S=0;S<h.length;S++)g+=h[S];return g/h.length}const i=o(e),s=o(r);let l=0,c=0;for(let h=0;h<e.length;h++)l+=(e[h]-i)*(r[h]-s),c+=(e[h]-i)*(e[h]-i);let d;c===0?d=t?1:-1:d=l/c;const u=s-d*i;return Math.round((u+d*n)*1e5)/1e5}function qs(n,r,e){var i;const t=[],o=/0|([1-9]+[0-9]*)/g;for(let s=1;s<=r;s++){const l=(s-1)%n.length,c=a.Tools.deepClone(n[l]);zt(c);const d=`${(i=n[n.length-1])==null?void 0:i.v}`,u=d==null?void 0:d.match(o),h=u==null?void 0:u[u.length-1],g=Math.abs(Number(h)+e*s);if(!d||!h)continue;const S=d.lastIndexOf(h),f=d.substr(0,S)+g.toString()+d.substr(S+h.length);c&&(c.v=f,t.push(c))}return t}function Rn(n,r,e,t=0){var l,c;const o=[["日","一","二","三","四","五","六"],["周日","周一","周二","周三","周四","周五","周六"],["星期日","星期一","星期二","星期三","星期四","星期五","星期六"]];if(t>=o.length)return[];const i=o[t],s=[];for(let d=1;d<=r;d++){const u=(d-1)%n.length,h=a.Tools.deepClone(n[u]);zt(h);let g=0;if(((l=n[n.length-1])==null?void 0:l.v)===i[0])g=7+e*d;else{const f=`${(c=n[n.length-1])==null?void 0:c.v}`;if(f){const p=f.substr(f.length-1,1);g=ct(p)+e*d}}g<0&&(g=Math.ceil(Math.abs(g)/7)*7+g);const S=g%7;h&&(h.v=i[S],s.push(h))}return s}function Qs(n,r,e){var o;const t=[];for(let i=1;i<=r;i++){const s=(i-1)%n.length,l=a.Tools.deepClone(n[s]);zt(l);const c=`${(o=n[n.length-1])==null?void 0:o.v}`,d=ct(c)+e*i;let u;d<=0?u="零":u=Hd(d),l&&(l.v=u,t.push(l))}return t}const qn={enWeek1:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],enWeek2:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],enMonth1:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],enMonth2:["January","February","March","April","May","June","July","August","September","October","November","December"],chnMonth1:["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],chnMonth2:["正月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","腊月"],chHour1:["子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"],chHour2:["子时","丑时","寅时","卯时","辰时","巳时","午时","未时","申时","酉时","戌时","亥时"],chYear1:["甲","乙","丙","丁","戊","己","庚","辛","壬","癸"],chSeason1:["春","夏","秋","冬"],chSeason2:["春季","夏季","秋季","冬季"]};function Yd(n){let r=!1;return Object.keys(qn).forEach(e=>{qn[e].includes(n)&&(r=!0)}),r}function Yr(n){let r="";const e=[];return Object.keys(qn).forEach(t=>{qn[t].includes(n)&&(r=t,e.push(...qn[t]))}),{name:r,series:e}}function Js(n,r,e,t){var s;const o=t.length,i=[];for(let l=1;l<=r;l++){const c=(l-1)%n.length,d=a.Tools.deepClone(n[c]);zt(d);const u=`${(s=n[n.length-1])==null?void 0:s.v}`;let h=t.indexOf(u)+e*l;h<0&&(h+=Math.abs(e)*o);const g=h%o;d&&(d.v=t[g],i.push(d))}return i}function Gd(n,r){const e=[];let t;if(r.startRow<n.startRow)t=a.Direction.UP;else if(r.endRow>n.endRow)t=a.Direction.DOWN;else if(r.startColumn<n.startColumn)t=a.Direction.LEFT;else if(r.endColumn>n.endColumn)t=a.Direction.RIGHT;else return[];if(t===a.Direction.DOWN||t===a.Direction.UP){const o=n.endRow-n.startRow+1,i=r.endRow-r.startRow+1,s=Math.floor(i/o),l=i%o,c={startRow:0,startColumn:0,endRow:n.endRow-n.startRow,endColumn:n.endColumn-n.startColumn};if(t===a.Direction.DOWN){for(let d=0;d<s;d++)e.push({repeatStartCell:{row:n.startRow+(d+1)*o,col:n.startColumn},relativeRange:c});l>0&&e.push({repeatStartCell:{row:n.startRow+(s+1)*o,col:n.startColumn},relativeRange:{startRow:0,startColumn:0,endRow:l-1,endColumn:n.endColumn-n.startColumn}})}else{for(let d=0;d<s;d++)e.push({repeatStartCell:{row:n.startRow-(d+1)*o,col:n.startColumn},relativeRange:c});l>0&&e.push({repeatStartCell:{row:n.startRow-(s+1)*o,col:n.startColumn},relativeRange:{startRow:o-l,endRow:o-1,startColumn:0,endColumn:n.endColumn-n.startColumn}})}}if(t===a.Direction.RIGHT||t===a.Direction.LEFT){const o=n.endColumn-n.startColumn+1,i=r.endColumn-r.startColumn+1,s=Math.floor(i/o),l=i%o,c={startRow:0,startColumn:0,endRow:n.endRow-n.startRow,endColumn:n.endColumn-n.startColumn};if(t===a.Direction.RIGHT){for(let d=0;d<s;d++)e.push({repeatStartCell:{row:n.startRow,col:n.startColumn+(d+1)*o},relativeRange:c});l>0&&e.push({repeatStartCell:{row:n.startRow,col:n.startColumn+(s+1)*o},relativeRange:{startRow:0,startColumn:0,endRow:n.endRow-n.startRow,endColumn:l-1}})}else{for(let d=0;d<s;d++)e.push({repeatStartCell:{row:n.startRow,col:n.startColumn-(d+1)*o},relativeRange:c});l>0&&e.push({repeatStartCell:{row:n.startRow,col:n.startColumn-(s+1)*o},relativeRange:{startRow:0,startColumn:o-l,endRow:n.endRow-n.startRow,endColumn:o-1}})}}return e}function $s(n){return!(a.isFormulaString(n.f)||a.isFormulaId(n.si)||n.t===a.CellValueType.BOOLEAN)}function zt(n){n&&"custom"in n&&delete n.custom}var mn=(n=>(n.Append="APPEND",n.Default="DEFAULT",n.Only="ONLY",n))(mn||{}),_e=(n=>(n.NUMBER="number",n.DATE="date",n.EXTEND_NUMBER="extendNumber",n.CHN_NUMBER="chnNumber",n.CHN_WEEK2="chnWeek2",n.CHN_WEEK3="chnWeek3",n.LOOP_SERIES="loopSeries",n.FORMULA="formula",n.OTHER="other",n))(_e||{}),le=(n=>(n.COPY="COPY",n.SERIES="SERIES",n.ONLY_FORMAT="ONLY_FORMAT",n.NO_FORMAT="NO_FORMAT",n))(le||{});const Zd={type:_e.DATE,priority:1100,match:(n,r)=>{var e;if(n!=null&&n.f||n!=null&&n.si)return!1;if((typeof(n==null?void 0:n.v)=="number"||(n==null?void 0:n.t)===a.CellValueType.NUMBER)&&n.s){if(typeof n.s=="string"){const o=r.get(a.IUniverInstanceService).getFocusedUnit().getStyles().get(n.s),i=(e=o==null?void 0:o.n)==null?void 0:e.pattern;if(i)return a.numfmt.getInfo(i).isDate}else if(n.s.n&&a.numfmt.getInfo(n.s.n.pattern).isDate)return!0}return!1},isContinue:(n,r)=>n.type===_e.DATE,applyFunctions:{[le.SERIES]:(n,r,e)=>{const{data:t}=n;return e===a.Direction.LEFT||e===a.Direction.UP?(t.reverse(),or(t,r,e).reverse()):or(t,r,e)}}},Kd={type:_e.NUMBER,priority:1e3,match:n=>typeof(n==null?void 0:n.v)=="number"||(n==null?void 0:n.t)===a.CellValueType.NUMBER,isContinue:(n,r)=>n.type===_e.NUMBER,applyFunctions:{[le.SERIES]:(n,r,e)=>{const{data:t}=n;return e===a.Direction.LEFT||e===a.Direction.UP?(t.reverse(),or(t,r,e).reverse()):or(t,r,e)}}},el={type:_e.OTHER,priority:0,match:()=>!0,isContinue:(n,r)=>n.type===_e.OTHER},qd={type:_e.EXTEND_NUMBER,priority:900,match:n=>Uo(`${n==null?void 0:n.v}`||"").isExtendNumber,isContinue:(n,r)=>{var e;if(n.type===_e.EXTEND_NUMBER){const{beforeTxt:t,afterTxt:o}=Uo(`${(e=n.cellData)==null?void 0:e.v}`||""),{beforeTxt:i,afterTxt:s}=Uo(`${r==null?void 0:r.v}`||"");if(t===i&&o===s)return!0}return!1},applyFunctions:{[le.SERIES]:(n,r,e)=>{var l;const{data:t}=n,o=e===a.Direction.UP||e===a.Direction.LEFT;let i;if(t.length===1)return i=o?-1:1,Ue(qs(t,r,i),o);const s=[];for(let c=0;c<t.length;c++){const d=`${(l=t[c])==null?void 0:l.v}`;d&&s.push(Number(Uo(d).matchTxt))}return o&&(t.reverse(),s.reverse()),uo(s)?(i=s[1]-s[0],Ue(qs(t,r,i),o)):jt(t,r)}}},Qd={type:_e.CHN_NUMBER,priority:830,match:n=>!!Vd(`${n==null?void 0:n.v}`||""),isContinue:(n,r)=>n.type===_e.CHN_NUMBER,applyFunctions:{[le.SERIES]:(n,r,e)=>{var c,d,u;const{data:t}=n,o=e===a.Direction.LEFT||e===a.Direction.UP;if(t.length===1){const h=`${(c=t[0])==null?void 0:c.v}`;let g;return o?g=-1:g=1,h&&(h==="日"||ct(h)<7)?Ue(Rn(t,r,g),o):Ue(Qs(t,r,g),o)}let i=!1;for(let h=0;h<t.length;h++)if(((d=t[h])==null?void 0:d.v)==="日"){i=!0;break}const s=[];let l=0;for(let h=0;h<t.length;h++){const g=`${(u=t[h])==null?void 0:u.v}`;g==="日"?h===0?s.push(0):(l++,s.push(l*7)):i&&ct(g)>0&&ct(g)<7?s.push(ct(g)+l*7):s.push(ct(g))}if(o&&(t.reverse(),s.reverse()),uo(s)){if(i||s[s.length-1]<6&&s[0]>0||s[0]<6&&s[s.length-1]>0){const g=s[1]-s[0];return Ue(Rn(t,r,g),o)}const h=s[1]-s[0];return Ue(Qs(t,r,h),o)}return jt(t,r)}}},Jd={type:_e.CHN_WEEK2,priority:820,match:n=>!!Wd(`${n==null?void 0:n.v}`||""),isContinue:(n,r)=>n.type===_e.CHN_WEEK2,applyFunctions:{[le.SERIES]:(n,r,e)=>{var l;const{data:t}=n,o=e===a.Direction.LEFT||e===a.Direction.UP;if(t.length===1){let c;return o?c=-1:c=1,Ue(Rn(t,r,c,1),o)}const i=[];let s=0;for(let c=0;c<t.length;c++){const d=`${(l=t[c])==null?void 0:l.v}`,u=d==null?void 0:d.substr(d.length-1,1);d==="周日"?c===0?i.push(0):(s++,i.push(s*7)):i.push(ct(u)+s*7)}if(o&&(t.reverse(),i.reverse()),uo(i)){const c=i[1]-i[0];return Ue(Rn(t,r,c,1),o)}return jt(t,r)}}},$d={type:_e.CHN_WEEK3,priority:810,match:n=>Ud(`${n==null?void 0:n.v}`||""),isContinue:(n,r)=>n.type===_e.CHN_WEEK3,applyFunctions:{[le.SERIES]:(n,r,e)=>{var l;const{data:t}=n,o=e===a.Direction.LEFT||e===a.Direction.UP;if(t.length===1){let c;return o?c=-1:c=1,Ue(Rn(t,r,c,2),o)}const i=[];let s=0;for(let c=0;c<t.length;c++){const d=`${(l=t[c])==null?void 0:l.v}`;if(d){const u=d.substr(d.length-1,1);d==="星期日"?c===0?i.push(0):(s++,i.push(s*7)):i.push(ct(u)+s*7)}}if(o&&(t.reverse(),i.reverse()),uo(i)){const c=i[1]-i[0];return Ue(Rn(t,r,c,2),o)}return jt(t,r)}}},eu={type:_e.LOOP_SERIES,priority:800,match:n=>Yd(`${n==null?void 0:n.v}`||""),isContinue:(n,r)=>{var e;return n.type===_e.LOOP_SERIES?Yr(`${(e=n.cellData)==null?void 0:e.v}`||"").name===Yr(`${r==null?void 0:r.v}`||"").name:!1},applyFunctions:{[le.SERIES]:(n,r,e)=>{var c,d;const{data:t}=n,o=e===a.Direction.LEFT||e===a.Direction.UP,{series:i}=Yr(`${(c=t[0])==null?void 0:c.v}`||"");if(t.length===1){let u;return o?u=-1:u=1,Ue(Js(t,r,u,i),o)}const s=[];let l=0;for(let u=0;u<t.length;u++){const h=`${(d=t[u])==null?void 0:d.v}`;h&&(h===i[0]?u===0?s.push(0):(l++,s.push(l*i.length)):s.push(i.indexOf(h)+l*7))}if(o&&(t.reverse(),s.reverse()),uo(s)){const u=s[1]-s[0];return Ue(Js(t,r,u,i),o)}return jt(t,r)}}};function Ue(n,r){return r?n.reverse():n}var tu=Object.getOwnPropertyDescriptor,nu=(n,r,e,t)=>{for(var o=t>1?void 0:t?tu(r,e):r,i=n.length-1,s;i>=0;i--)(s=n[i])&&(o=s(o)||o);return o},rn=(n,r)=>(e,t)=>r(e,t,n);exports.AutoFillService=class extends a.Disposable{constructor(e,t,o,i,s,l){super();E(this,"_rules",[]);E(this,"_hooks",[]);E(this,"_applyType$",new O.BehaviorSubject(le.SERIES));E(this,"_isFillingStyle",!0);E(this,"_prevUndos",[]);E(this,"_autoFillLocation$",new O.BehaviorSubject(null));E(this,"autoFillLocation$",this._autoFillLocation$.asObservable());E(this,"_showMenu$",new O.BehaviorSubject(!1));E(this,"showMenu$",this._showMenu$.asObservable());E(this,"_direction",a.Direction.DOWN);E(this,"applyType$",this._applyType$.asObservable());E(this,"_menu$",new O.BehaviorSubject([{label:"autoFill.copy",value:le.COPY,disable:!1},{label:"autoFill.series",value:le.SERIES,disable:!1},{label:"autoFill.formatOnly",value:le.ONLY_FORMAT,disable:!1},{label:"autoFill.noFormat",value:le.NO_FORMAT,disable:!1}]));E(this,"menu$",this._menu$.asObservable());this._commandService=e,this._undoRedoService=t,this._renderManagerService=o,this._univerInstanceService=i,this._selectionManagerService=s,this._injector=l,this._init()}_init(){this._rules=[Zd,Kd,qd,Qd,Jd,$d,eu,el].sort((e,t)=>t.priority-e.priority),this._isFillingStyle=!0}_getOneByPriority(e){return e.length<=0?[]:[e.reduce((o,i)=>(i.priority||0)>(o.priority||0)?i:o,e[0])]}_initPrevUndo(){this._prevUndos=[]}async triggerAutoFill(e,t,o,i){var S;if(o.startColumn===i.startColumn&&o.startRow===i.startRow&&o.endColumn===i.endColumn&&o.endRow===i.endRow)return!1;if(i.endColumn<o.endColumn&&i.endColumn>o.startColumn)return this._commandService.executeCommand(En.id,{clearRange:{startRow:i.startRow,endRow:i.endRow,startColumn:i.endColumn+1,endColumn:o.endColumn},selectionRange:i});if(i.endRow<o.endRow&&i.endRow>o.startRow)return this._commandService.executeCommand(En.id,{clearRange:{startRow:i.endRow+1,endRow:o.endRow,startColumn:i.startColumn,endColumn:i.endColumn},selectionRange:i});const s={startRow:i.startRow,endRow:i.endRow,startColumn:i.startColumn,endColumn:i.endColumn};let l=null;if(i.startRow<o.startRow)l=a.Direction.UP,s.endRow=o.startRow-1;else if(i.endRow>o.endRow)l=a.Direction.DOWN,s.startRow=o.endRow+1;else if(i.startColumn<o.startColumn)l=a.Direction.LEFT,s.endColumn=o.startColumn-1;else if(i.endColumn>o.endColumn)l=a.Direction.RIGHT,s.startColumn=o.endColumn+1;else return!1;this.direction=l;const c=this._injector.invoke(f=>Sn(o,f)),d=this._injector.invoke(f=>Sn(s,f));if(!c||!d)return!1;this.autoFillLocation={source:c,target:d,unitId:e,subUnitId:t};const u=[];this.getActiveHooks().forEach(f=>{var v;const p=(v=f==null?void 0:f.onBeforeFillData)==null?void 0:v.call(f,{source:c,target:d,unitId:e,subUnitId:t},l);p&&u.unshift(p)}),this._initPrevUndo();for(let f=0;f<u.length;f++){const p=this.menu.find(v=>v.value===u[f]);if(p&&!p.disable)return this.fillData(u[f])}const g=(S=this.menu.find(f=>f.disable===!1))==null?void 0:S.value;return g?this.fillData(g):!1}addHook(e){if(this._hooks.find(t=>t.id===e.id))throw new Error(`Add hook failed, hook id '${e.id}' already exist!`);return e.priority===void 0&&(e.priority=0),e.type===void 0&&(e.type=mn.Append),this._hooks.push(e),a.toDisposable(()=>{const t=this._hooks.findIndex(o=>o===e);t>-1&&this._hooks.splice(t,1)})}registerRule(e){if(this._rules.find(o=>o.type===e.type))throw new Error(`Registry rule failed, type '${e.type}' already exist!`);const t=this._rules.findIndex(o=>o.priority<e.priority);this._rules.splice(t===-1?this._rules.length:t,0,e)}getRules(){return this._rules}getAllHooks(){return this._hooks}getActiveHooks(){const{source:e,target:t,unitId:o,subUnitId:i}=this.autoFillLocation||{};if(!e||!t||!o||!i)return[];const s=this._hooks.filter(u=>{var h;return!((h=u.disable)!=null&&h.call(u,{source:e,target:t,unitId:o,subUnitId:i},this._direction,this.applyType))}),l=s.filter(u=>u.type===mn.Only);if(l.length>0)return this._getOneByPriority(l);const c=this._getOneByPriority(s.filter(u=>u.type===mn.Default)),d=s.filter(u=>u.type===mn.Append)||[];return[...c,...d]}get applyType(){return this._applyType$.getValue()}set applyType(e){this._applyType$.next(e)}get menu(){return this._menu$.getValue()}get direction(){return this._direction}set direction(e){this._direction=e}isFillingStyle(){return this._isFillingStyle}setFillingStyle(e){this._isFillingStyle=e}get autoFillLocation(){return this._autoFillLocation$.getValue()}set autoFillLocation(e){this._autoFillLocation$.next(e)}setDisableApplyType(e,t){this._menu$.next(this._menu$.getValue().map(o=>o.value===e?{...o,disable:t}:o))}setShowMenu(e){this._showMenu$.next(e)}fillData(e){var C,b,R;this.applyType=e;const{source:t,target:o,unitId:i=this._univerInstanceService.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET).getUnitId(),subUnitId:s=(C=this._univerInstanceService.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET).getActiveSheet())==null?void 0:C.getSheetId()}=this.autoFillLocation||{};if(!t||!o||!i||!s)return!1;const l=this.direction;this._prevUndos.length>0&&this._prevUndos.forEach(T=>{this._commandService.syncExecuteCommand(T.id,T.params)}),this._prevUndos=[];const c=a.Rectangle.union(Et(t),Et(o)),d=this.getActiveHooks(),u=this._univerInstanceService.getUnit(i,a.UniverInstanceType.UNIVER_SHEET);this._commandService.syncExecuteCommand(m.SetSelectionsOperation.id,{selections:[{primary:{...(R=(b=this._selectionManagerService.getCurrentLastSelection())==null?void 0:b.primary)!=null?R:c},range:{...c,rangeType:a.RANGE_TYPE.NORMAL}}],unitId:i,subUnitId:s});const h=[],g=[];d.forEach(T=>{var P;const{undos:M,redos:y}=((P=T.onFillData)==null?void 0:P.call(T,{source:t,target:o,unitId:i,subUnitId:s},l,e))||{};M&&h.push(...M),y&&g.push(...y)});const S=g.every(T=>this._commandService.syncExecuteCommand(T.id,T.params)),f=[];e!==le.NO_FORMAT&&g.forEach(T=>{if(T.id===m.SetRangeValuesMutation.id){const{cellValue:M}=T.params;new a.ObjectMatrix(M).forValue((P,x,A)=>{const k=Object.keys(u.getStyles().get(A==null?void 0:A.s)||{});(A!=null&&A.p||k.length&&fs.some(N=>k.includes(N)))&&f.push({startRow:P,endRow:P,startColumn:x,endColumn:x})})}});const p=this._getAutoHeightUndoRedos(i,s,f);return p.redos.every(T=>this._commandService.syncExecuteCommand(T.id,T.params))&&(h.push(...p.undos),g.push(...p.redos)),S&&(this._prevUndos=h,this._undoRedoService.pushUndoRedo({unitID:i,undoMutations:h,redoMutations:g})),d.forEach(T=>{var M;(M=T.onAfterFillData)==null||M.call(T,{source:t,target:o,unitId:i,subUnitId:s},l,e)}),this.setShowMenu(!0),!0}_getAutoHeightUndoRedos(e,t,o){var h,g;const i=(h=this._renderManagerService.getRenderById(e))==null?void 0:h.with(exports.SheetSkeletonManagerService),s=(g=i==null?void 0:i.getCurrentParam())==null?void 0:g.skeleton;if(!s)return{redos:[],undos:[]};const l=s.calculateAutoHeightInRange(o),c={subUnitId:t,unitId:e,rowsAutoHeightInfo:l},d=s.worksheet,u=m.SetWorksheetRowAutoHeightMutationFactory(c,d);return{undos:[{id:m.SetWorksheetRowAutoHeightMutation.id,params:u}],redos:[{id:m.SetWorksheetRowAutoHeightMutation.id,params:c}]}}};exports.AutoFillService=nu([rn(0,a.ICommandService),rn(1,a.IUndoRedoService),rn(2,w.IRenderManagerService),rn(3,a.Inject(a.IUniverInstanceService)),rn(4,a.Inject(m.SheetsSelectionsService)),rn(5,a.Inject(a.Injector))],exports.AutoFillService);const Tt=a.createIdentifier("univer.auto-fill-service"),Ct={type:a.CommandType.COMMAND,id:"sheet.command.auto-fill",handler:async(n,r)=>{const e=n.get(Tt),t=n.get(a.IUniverInstanceService),{sourceRange:o,targetRange:i}=r,s=m.getSheetCommandTarget(t);if(!s)return!1;const{subUnitId:l,unitId:c}=s;return e.triggerAutoFill(c,l,o,i)}},En={id:"sheet.command.auto-clear-content",type:a.CommandType.COMMAND,handler:async(n,r)=>{const e=n.get(a.IUniverInstanceService),t=n.get(a.ICommandService),o=n.get(a.IUndoRedoService),i=n.get(m.SheetInterceptorService),s=m.getSheetCommandTarget(e);if(!s)return!1;const{unitId:l,subUnitId:c}=s,{clearRange:d,selectionRange:u}=r,h={subUnitId:c,unitId:l,cellValue:m.generateNullCellValue([d])},g=m.SetRangeValuesUndoMutationFactory(n,h),{startColumn:S,startRow:f}=u,p={selections:[{primary:{startColumn:S,startRow:f,endColumn:S,endRow:f,actualRow:f,actualColumn:S,isMerged:!1,isMergedMainCell:!1},range:{...u}}],unitId:l,subUnitId:c};if(t.executeCommand(m.SetSelectionsOperation.id,p),t.syncExecuteCommand(m.SetRangeValuesMutation.id,h)){const C=i.afterCommandExecute({id:m.SetRangeValuesMutation.id,params:h});return a.sequenceExecute(C.redos,t),o.pushUndoRedo({unitID:l,undoMutations:[{id:m.SetRangeValuesMutation.id,params:g},...C.undos],redoMutations:[{id:m.SetRangeValuesMutation.id,params:h},...C.redos]}),!0}return!1}},ho={id:"sheet.command.refill",type:a.CommandType.COMMAND,handler:async(n,r)=>n.get(Tt).fillData(r.type)};var ou=Object.getOwnPropertyDescriptor,ru=(n,r,e,t)=>{for(var o=t>1?void 0:t?ou(r,e):r,i=n.length-1,s;i>=0;i--)(s=n[i])&&(o=s(o)||o);return o},Pt=(n,r)=>(e,t)=>r(e,t,n);exports.EditorBridgeService=class extends a.Disposable{constructor(e,t,o,i,s,l,c){super();E(this,"_editorUnitId",a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY);E(this,"_editorIsDirty",!1);E(this,"_isDisabled",!1);E(this,"_visible",{visible:!1,eventType:w.DeviceInputEventType.Dblclick,unitId:""});E(this,"_currentEditCell",null);E(this,"_currentEditCellState",null);E(this,"_currentEditCellLayout",null);E(this,"_currentEditCellState$",new O.BehaviorSubject(null));E(this,"currentEditCellState$",this._currentEditCellState$.asObservable());E(this,"_currentEditCellLayout$",new O.BehaviorSubject(null));E(this,"currentEditCellLayout$",this._currentEditCellLayout$.asObservable());E(this,"currentEditCell$",this._currentEditCellState$.pipe(O.switchMap(e=>this._currentEditCellLayout$.pipe(O.map(t=>e&&t?{...e,...t}:null)))));E(this,"_visible$",new O.BehaviorSubject(this._visible));E(this,"visible$",this._visible$.asObservable());E(this,"_afterVisible$",new O.BehaviorSubject(this._visible));E(this,"afterVisible$",this._afterVisible$.asObservable());E(this,"_forceKeepVisible$",new O.BehaviorSubject(!1));E(this,"forceKeepVisible$",this._forceKeepVisible$.asObservable());this._sheetInterceptorService=e,this._renderManagerService=t,this._themeService=o,this._univerInstanceService=i,this._editorService=s,this._refSelectionsService=l,this._contextService=c,this.disposeWithMe(a.toDisposable(()=>{this._currentEditCellState$.complete(),this._currentEditCell=null})),this._univerInstanceService.getTypeOfUnitDisposed$(a.UniverInstanceType.UNIVER_SHEET).subscribe(d=>{var u;d.getUnitId()===((u=this._currentEditCellState)==null?void 0:u.unitId)&&this._clearCurrentEditCellState()})}refreshEditCellState(){const e=this.getLatestEditCellState();if(!e){this._currentEditCellState=null,this._currentEditCellLayout=null,this._currentEditCellState$.next(null),this._currentEditCellLayout$.next(null);return}const{position:t,scaleX:o,scaleY:i,canvasOffset:s,...l}=e;this._currentEditCellState=l,this._currentEditCellLayout={position:t,scaleX:o,scaleY:i,canvasOffset:s},this._currentEditCellState$.next(this._currentEditCellState),this._currentEditCellLayout$.next(this._currentEditCellLayout)}refreshEditCellPosition(e){var y;const t=this._currentEditCell;if(t==null)return;const o=this._renderManagerService.getCurrentTypeOfRenderer(a.UniverInstanceType.UNIVER_SHEET);if(!o)return;const i=(y=o.with(exports.SheetSkeletonManagerService).getSkeletonParam(t.sheetId))==null?void 0:y.skeleton,s=o.with(ve);if(!i||!this._currentEditCellState)return;const{primary:l,unitId:c,sheetId:d,scene:u,engine:h}=t,g=$n(i,l);if(g==null)return;const S=a.convertCellToRange(g),f=$.getCanvasOffsetByEngine(h);let{startX:p,startY:v,endX:C,endY:b}=S;const{scaleX:R,scaleY:T}=u.getAncestorScale(),M=u.getViewportScrollXY(s.getViewPort());p=w.convertTransformToOffsetX(p,R,M),v=w.convertTransformToOffsetY(v,T,M),C=w.convertTransformToOffsetX(C,R,M),b=w.convertTransformToOffsetY(b,T,M),e&&this._currentEditCellLayout&&(C=C-p+this._currentEditCellLayout.position.startX,b=b-v+this._currentEditCellLayout.position.startY,p=this._currentEditCellLayout.position.startX,v=this._currentEditCellLayout.position.startY),this._currentEditCellLayout={position:{startX:p,startY:v,endX:C,endY:b},canvasOffset:f,scaleX:R,scaleY:T},this._currentEditCellLayout$.next(this._currentEditCellLayout)}setEditCell(e){this._currentEditCell=e,this._editorService.getFocusEditor()||(this._editorService.focus(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY),this._contextService.setContextValue(a.EDITOR_ACTIVATED,!1),this._contextService.setContextValue(a.FOCUSING_EDITOR_STANDALONE,!1));const t=this.getLatestEditCellState();if(!t){this._currentEditCellState=t,this._currentEditCellLayout=t,this._currentEditCellState$.next(t),this._currentEditCellLayout$.next(t);return}const{position:o,canvasOffset:i,scaleX:s,scaleY:l,...c}=t;this._currentEditCellState=c,this._currentEditCellLayout={position:o,canvasOffset:i,scaleX:s,scaleY:l},this._currentEditCellState$.next(this._currentEditCellState),this._currentEditCellLayout$.next(this._currentEditCellLayout)}_clearCurrentEditCellState(){this._currentEditCellState=null,this._currentEditCellState$.next(null),this._currentEditCellLayout=null,this._currentEditCellLayout$.next(null)}getEditCellState(){return this._currentEditCellState==null||this._currentEditCellLayout==null?null:{...this._currentEditCellState,...this._currentEditCellLayout}}getEditCellLayout(){return this._currentEditCellLayout}getEditLocation(){return this._currentEditCellState}updateEditLocation(e,t){this._currentEditCellState&&(this._currentEditCellState={...this._currentEditCellState,row:e,column:t})}getLatestEditCellState(){var W,H,U;const e=this._currentEditCell;if(e==null)return;const t=this._renderManagerService.getCurrentTypeOfRenderer(a.UniverInstanceType.UNIVER_SHEET);if(!t)return;const o=t.with(exports.SheetSkeletonManagerService).getCurrentSkeleton(),i=t.with(ve);if(!o)return;const{primary:s,unitId:l,sheetId:c,scene:d,engine:u}=e,{startRow:h,startColumn:g}=s,S=$n(o,s);if(S==null)return;const f=a.convertCellToRange(S),p=$.getCanvasOffsetByEngine(u);let{startX:v,startY:C,endX:b,endY:R}=f;const{scaleX:T,scaleY:M}=d.getAncestorScale(),y=d.getViewportScrollXY(i.getViewPort());v=w.convertTransformToOffsetX(v,T,y),C=w.convertTransformToOffsetY(C,M,y),b=w.convertTransformToOffsetX(b,T,y),R=w.convertTransformToOffsetY(R,M,y);const P=this._univerInstanceService.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET),x=P.getActiveSheet();if(!x)return;const A={workbook:P,worksheet:x,unitId:P.getUnitId(),subUnitId:x.getSheetId(),row:h,col:g,origin:x.getCellRaw(h,g)};let k;const N=this._sheetInterceptorService.writeCellInterceptor.fetchThroughInterceptors(m.BEFORE_CELL_EDIT)(x.getCell(h,g),A);k=N&&o.getCellDocumentModelWithFormula(N);const D=(W=k==null?void 0:k.documentModel)==null?void 0:W.documentStyle.renderConfig;if(D!=null&&(D.cellValueType=a.CellValueType.STRING),!k||k.documentModel==null){const B=o.getBlankCellDocumentModel(N);if(k!=null){const{verticalAlign:F,horizontalAlign:L,wrapStrategy:j,textRotation:z,fill:q}=k,{centerAngle:te,vertexAngle:Q}=w.convertTextRotation(z);B.documentModel.documentStyle.renderConfig={...D,verticalAlign:F,horizontalAlign:L,wrapStrategy:j,background:{rgb:q},centerAngle:te,vertexAngle:Q}}k=B}if(k.fill=k.fill||"#fff",(H=k.documentModel)==null||H.setZoomRatio(Math.max(T,M)),(N==null?void 0:N.isInArrayFormulaRange)===!0){const B=(U=k.documentModel)==null?void 0:U.getBody();B&&(B.textRuns=[{st:0,ed:B.dataStream.length-2,ts:{cl:{rgb:this._themeService.getCurrentTheme().textColorSecondary}}}])}return{position:{startX:v,startY:C,endX:b,endY:R},scaleX:T,scaleY:M,canvasOffset:p,row:h,column:g,unitId:l,sheetId:c,documentLayoutObject:k,editorUnitId:this._editorUnitId,isInArrayFormulaRange:N==null?void 0:N.isInArrayFormulaRange}}getCurrentEditorId(){return this._editorUnitId}changeVisible(e){this._visible=e,e.visible&&(this._editorIsDirty=!1),this._visible$.next(this._visible),this._afterVisible$.next(this._visible)}isVisible(){return this._visible}enableForceKeepVisible(){this._forceKeepVisible$.next(!0)}disableForceKeepVisible(){this._forceKeepVisible$.next(!1)}isForceKeepVisible(){return this._forceKeepVisible$.getValue()}changeEditorDirty(e){this._editorIsDirty=e}getEditorDirty(){return this._editorIsDirty}};exports.EditorBridgeService=ru([Pt(0,a.Inject(m.SheetInterceptorService)),Pt(1,w.IRenderManagerService),Pt(2,a.Inject(a.ThemeService)),Pt(3,a.IUniverInstanceService),Pt(4,$.IEditorService),Pt(5,m.IRefSelectionsService),Pt(6,a.IContextService)],exports.EditorBridgeService);const Se=a.createIdentifier("univer.sheet-editor-bridge.service"),Ce={id:"sheet.operation.set-cell-edit-visible",type:a.CommandType.OPERATION,handler:(n,r)=>r?(n.get(Se).changeVisible(r),!0):!1},mo={id:"sheet.operation.set-cell-edit-visible-f2",type:a.CommandType.OPERATION,handler:(n,r)=>{const e=n.get(a.ICommandService),o=n.get(a.IUniverInstanceService).getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET);return o?(e.syncExecuteCommand(Ce.id,{...r,unitId:o.getUnitId()}),!0):!1}},Xt={id:"sheet.operation.set-cell-edit-visible-arrow",type:a.CommandType.OPERATION,handler:()=>!0},kn={id:"sheet.command.change-zoom-ratio",type:a.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;const e=n.get(a.IUniverInstanceService),t=m.getSheetCommandTarget(e);if(!t)return!1;const{worksheet:o,subUnitId:i,unitId:s}=t,{delta:l,reset:c}=r;let d=c?100:Math.round((o.getConfig().zoomRatio+l)*100);d=Math.max(Di[0],d),d=Math.min(Di[1],d);const u=d/100,g=n.get(Se).isVisible();return(g.unitId===s||g.unitId===a.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY)&&g.visible?!1:n.get(a.ICommandService).executeCommand(Le.id,{unitId:s,subUnitId:i,zoomRatio:u})}},Nn={id:"sheet.command.set-zoom-ratio",type:a.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;const{unitId:e,subUnitId:t,zoomRatio:o}=r,s=n.get(Se).isVisible();return(s.unitId===e||s.unitId===a.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY)&&s.visible?!1:n.get(a.ICommandService).executeCommand(Le.id,{unitId:e,subUnitId:t,zoomRatio:o})}};function iu(n){return typeof n.isMainScene>"u"}function Ge(n,r){const e=n instanceof a.Workbook?n:n.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET);if(!e)return null;const t=e.getUnitId();let o,i,s,l;if(iu(r)){const g=r.getRenderById(t);if(g==null)return null;o=g.components,o=g.components,i=g.mainComponent,s=g.scene,l=g.engine}else o=r.components,i=r.mainComponent,s=r.scene,l=r.engine;if(!o||!i)return null;const c=i,d=o.get(me.ROW),u=o.get(me.COLUMN),h=o.get(me.LEFT_TOP);return{spreadsheet:c,spreadsheetRowHeader:d,spreadsheetColumnHeader:u,spreadsheetLeftTopPlaceholder:h,scene:s,engine:l}}function Bi(n,r,e,t){const{startX:o,startY:i,endX:s,endY:l}=t.getCellWithCoordByIndex(n,r);return{startX:o,startY:i,endX:s,endY:l}}function qe(n,r,e,t,o,i){const s=e.getCoordRelativeToViewport(w.Vector2.FromArray([n,r])),{x:l,y:c}=s,d=e.getScrollXYInfoByViewport(s,o),{scaleX:u,scaleY:h}=e.getAncestorScale(),g=t.getCellIndexByOffset(l,c,u,h,d,{closeFirst:i}),{row:S,column:f}=g,p=t.getNoMergeCellWithCoordByIndex(S,f),{startX:v,startY:C,endX:b,endY:R}=p;return{startX:v,startY:C,endX:b,endY:R,row:S,column:f}}function Qn(n,r,e,t){const o=e.getCoordRelativeToViewport(w.Vector2.FromArray([n,r])),i=e.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN),s=e.getScrollXYInfoByViewport(o,i),{scaleX:l,scaleY:c}=e.getAncestorScale(),{x:d,y:u}=s,h=n/l+d,g=r/c+u;return{x:h,y:g}}var su=Object.getOwnPropertyDescriptor,au=(n,r,e,t)=>{for(var o=t>1?void 0:t?su(r,e):r,i=n.length-1,s;i>=0;i--)(s=n[i])&&(o=s(o)||o);return o},Lo=(n,r)=>(e,t)=>r(e,t,n);let eo=class extends a.Disposable{constructor(r,e,t,o,i){super();E(this,"_zoom");this._context=r,this._sheetSkeletonManagerService=e,this._commandService=t,this._contextService=o,this._editorBridgeService=i,this._initSkeletonListener(),this._initZoomEventListener()}updateZoom(r,e){const t=this._context.unit.getSheetBySheetId(r);return t?(t.getConfig().zoomRatio=e,t===this._context.unit.getActiveSheet()&&this._updateViewZoom(e),!0):!1}_initZoomEventListener(){const r=this._getSheetObject().scene;this.disposeWithMe(r.onMouseWheel$.subscribeEvent(e=>{if(!e.ctrlKey||!this._contextService.getContextValue(a.FOCUSING_SHEET))return;if(this._editorBridgeService){const d=this._editorBridgeService.isVisible();if((d.unitId===this._context.unitId||d.unitId===a.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY)&&d.visible)return}const t=Math.abs(e.deltaX);let o=t<40?.2:t<80?.4:.2;o*=e.deltaY>0?-1:1,r.scaleX<1&&(o/=2);const i=this._context.unit,s=i.getActiveSheet();if(!s)return;const l=s.getZoomRatio();let c=+Number.parseFloat(`${l+o}`).toFixed(1);c=c>=4?4:c<=.1?.1:c,this._commandService.executeCommand(Nn.id,{zoomRatio:Math.round(c*10)/10,unitId:i.getUnitId(),subUnitId:s.getSheetId()}),e.preventDefault()}))}_initSkeletonListener(){this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(r=>{if(r==null)return;const t=this._context.unit.getActiveSheet();if(!t)return;const o=t.getZoomRatio()||1;this._zoom!==o&&this._updateViewZoom(o),this._zoom=o}))}_updateViewZoom(r){const e=this._getSheetObject();e==null||e.scene.scale(r,r),e==null||e.spreadsheet.makeForceDirty()}_getSheetObject(){return Ge(this._context.unit,this._context)}};eo=au([Lo(1,a.Inject(exports.SheetSkeletonManagerService)),Lo(2,a.ICommandService),Lo(3,a.IContextService),Lo(4,a.Optional(Se))],eo);const Le={id:"sheet.operation.set-zoom-ratio",type:a.CommandType.OPERATION,handler:(n,r)=>{const t=n.get(w.IRenderManagerService).getRenderById(r.unitId);return t?t.with(eo).updateZoom(r.subUnitId,r.zoomRatio):!1}};var lu=Object.getOwnPropertyDescriptor,cu=(n,r,e,t)=>{for(var o=t>1?void 0:t?lu(r,e):r,i=n.length-1,s;i>=0;i--)(s=n[i])&&(o=s(o)||o);return o},Gr=(n,r)=>(e,t)=>r(e,t,n);const ea="univer-sheet-main-canvas";exports.SheetsRenderService=class extends a.RxDisposable{constructor(e,t,o){super();E(this,"_skeletonChangeMutations",new Set);this._contextService=e,this._instanceSrv=t,this._renderManagerService=o,Promise.resolve().then(()=>this._init())}registerSkeletonChangingMutations(e){return this._skeletonChangeMutations.has(e)?a.toDisposable(()=>{}):(this._skeletonChangeMutations.add(e),a.toDisposable(()=>this._skeletonChangeMutations.delete(e)))}checkMutationShouldTriggerRerender(e){return this._skeletonChangeMutations.has(e)}_init(){this._initWorkbookListener(),this._initContextListener()}_initWorkbookListener(){this._instanceSrv.getTypeOfUnitAdded$(a.UniverInstanceType.UNIVER_SHEET).pipe(O.takeUntil(this.dispose$)).subscribe(e=>this._createRenderer(e)),this._instanceSrv.getAllUnitsForType(a.UniverInstanceType.UNIVER_SHEET).forEach(e=>this._createRenderer(e)),this._instanceSrv.getTypeOfUnitDisposed$(a.UniverInstanceType.UNIVER_SHEET).pipe(O.takeUntil(this.dispose$)).subscribe(e=>this._disposeRenderer(e)),this.disposeWithMe(this._instanceSrv.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET).subscribe(e=>{e&&this._renderManagerService.setCurrent(e.getUnitId())}))}_createRenderer(e){const t=e.getUnitId();this._renderManagerService.created$.subscribe(o=>{o.unitId===t&&(o.engine.getCanvas().setId(`${ea}_${t}`),o.engine.getCanvas().getContext().setId(`${ea}_${t}`))}),this._renderManagerService.createRender(t)}_disposeRenderer(e){const t=e.getUnitId();this._renderManagerService.removeRender(t)}_initContextListener(){this.disposeWithMe(this._contextService.subscribeContextValue$(w.RENDER_RAW_FORMULA_KEY).pipe(O.distinctUntilChanged()).subscribe(()=>{this._renderManagerService.getRenderAll().forEach(e=>{e.mainComponent instanceof w.Spreadsheet&&e.mainComponent.makeForceDirty(!0)})}))}};exports.SheetsRenderService=cu([Gr(0,a.IContextService),Gr(1,a.IUniverInstanceService),Gr(2,w.IRenderManagerService)],exports.SheetsRenderService);var du=Object.getOwnPropertyDescriptor,uu=(n,r,e,t)=>{for(var o=t>1?void 0:t?du(r,e):r,i=n.length-1,s;i>=0;i--)(s=n[i])&&(o=s(o)||o);return o},Ot=(n,r)=>(e,t)=>r(e,t,n);exports.AutoFillController=class extends a.Disposable{constructor(e,t,o,i,s,l,c){super();E(this,"_beforeApplyData",[]);E(this,"_currentLocation",null);E(this,"_copyData",[]);E(this,"_defaultHook");this._univerInstanceService=e,this._commandService=t,this._autoFillService=o,this._editorBridgeService=i,this._renderManagerService=s,this._injector=l,this._sheetsRenderService=c,this._defaultHook={id:"default",type:mn.Default,priority:0,onBeforeFillData:(d,u)=>this._presetAndCacheData(d,u),onFillData:(d,u,h)=>this._fillData(d,u,h)},this._init()}_init(){this._initDefaultHook(),this._initSelectionControlFillChanged(),this._initQuitListener(),this._initSkeletonChange()}_initSkeletonChange(){this.disposeWithMe(this._sheetsRenderService.registerSkeletonChangingMutations(Ct.id))}_initDefaultHook(){this.disposeWithMe(this._autoFillService.addHook(this._defaultHook))}_initQuitListener(){const e=[Ce.id,En.id,m.SetRangeValuesCommand.id,Le.id,m.SetWorksheetActiveOperation.id,m.MoveRangeMutation.id,m.RemoveRowMutation.id,m.RemoveColMutation.id,m.InsertRowMutation.id,m.InsertColMutation.id,m.MoveRowsMutation.id,m.MoveColsMutation.id,m.SetWorksheetColWidthMutation.id,m.SetWorksheetRowHeightMutation.id,m.SetRangeValuesMutation.id];this.disposeWithMe(this._commandService.onCommandExecuted((t,o)=>{var c,d;const i=o==null?void 0:o.fromCollab,s=o==null?void 0:o.fromSync,l=o==null?void 0:o.fromFormula;e.includes(t.id)&&!i&&!s&&!l&&t.params.trigger!==Ct.id&&t.params.trigger!==ho.id&&this._quit(),t.id===m.RemoveSheetMutation.id&&t.params.unitId===((c=this._currentLocation)==null?void 0:c.unitId)&&t.params.subUnitId===((d=this._currentLocation)==null?void 0:d.subUnitId)&&this._quit()})),this.disposeWithMe(this._univerInstanceService.unitDisposed$.subscribe(t=>{var o;t.getUnitId()===((o=this._currentLocation)==null?void 0:o.unitId)&&this._quit()}))}_quit(){this._currentLocation=null,this._beforeApplyData=[],this._copyData=[],this._autoFillService.setShowMenu(!1)}_initSelectionControlFillChanged(){const e=new a.DisposableCollection,t=()=>{e.dispose();const o=this._renderManagerService.getCurrentTypeOfRenderer(a.UniverInstanceType.UNIVER_SHEET);if(!o)return;o.with(ve).getSelectionControls().forEach(l=>{e.add(l.selectionFilled$.subscribe(c=>{if(c==null||c.startColumn===-1||c.startRow===-1||c.endColumn===-1||c.endRow===-1)return;const d={startColumn:l.model.startColumn,endColumn:l.model.endColumn,startRow:l.model.startRow,endRow:l.model.endRow},u={startColumn:c.startColumn,endColumn:c.endColumn,startRow:c.startRow,endRow:c.endRow};this._commandService.executeCommand(Ct.id,{sourceRange:d,targetRange:u})})),e.add(l.fillControl.onDblclick$.subscribeEvent(()=>{const c={startColumn:l.model.startColumn,endColumn:l.model.endColumn,startRow:l.model.startRow,endRow:l.model.endRow};this._handleDbClickFill(c)})),e.add(l.fillControl.onPointerDown$.subscribeEvent(()=>{this._editorBridgeService.isVisible().visible&&this._commandService.syncExecuteCommand(Ce.id,{visible:!1,eventType:w.DeviceInputEventType.PointerDown,unitId:o.unitId})}))})};t(),this.disposeWithMe(this._commandService.onCommandExecuted(o=>{o.id===m.SetSelectionsOperation.id&&t()})),this.disposeWithMe(this._univerInstanceService.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET).subscribe(()=>t()))}_handleDbClickFill(e){const t=this._detectFillRange(e);t.endRow<=e.endRow||this._commandService.executeCommand(Ct.id,{sourceRange:e,targetRange:t})}_detectFillRange(e){var g,S,f,p,v,C;const{startRow:t,endRow:o,startColumn:i,endColumn:s}=e,l=(g=this._univerInstanceService.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET))==null?void 0:g.getActiveSheet();if(!l)return e;const c=l.getCellMatrix(),d=l.getMaxRows()-1,u=l.getMaxColumns()-1;let h=o;if(i>0&&((S=c.getValue(t,i-1))==null?void 0:S.v)!=null){let b=t;for(;((f=c.getValue(b,i-1))==null?void 0:f.v)!=null&&b<d;)b+=1;h=b-1}else if(s<u&&((p=c.getValue(o,s+1))==null?void 0:p.v)!=null){let b=t;for(;((v=c.getValue(b,s+1))==null?void 0:v.v)!=null&&b<d;)b+=1;h=b-1}for(let b=o+1;b<=h;b++)for(let R=i;R<=s;R++)if(((C=c.getValue(b,R))==null?void 0:C.v)!=null){h=b-1;break}return{startColumn:i,endColumn:s,startRow:t,endRow:h}}_getApplyData(e,t,o,i,s,l=!0){const c=[],d=Math.floor(o/t),u=o%t,h=this._autoFillService.getRules();if(!l&&s===le.ONLY_FORMAT)return console.error("ERROR: only format can not be applied when hasStyle is false"),[];const g={};h.forEach(S=>{g[S.type]=[]}),h.forEach(S=>{const{type:f,applyFunctions:p={}}=S,v=e[f];v&&v.forEach(C=>{const b=Ld(C.index,u),R=C.index.length*d+b,T=this._applyFunctions(C,R,i,s,p,e),M=Bd(t,o,C.index);g[f].push({data:T,index:M})})});for(let S=0;S<o;S++)h.forEach(f=>{const{type:p}=f,v=g[p];for(let C=0;C<v.length;C++)S in v[C].index&&c.push(v[C].data[v[C].index[S]])});return c}_applyFunctions(e,t,o,i,s,l){const{data:c}=e,d=o===a.Direction.UP||o===a.Direction.LEFT;if(i===le.COPY){const u=s==null?void 0:s[le.COPY];return u?u(e,t,o,l):(d&&c.reverse(),jt(c,t))}if(i===le.SERIES){const u=s==null?void 0:s[le.SERIES];return u?u(e,t,o,l):(d&&c.reverse(),s!=null&&s[le.COPY]?s[le.COPY](e,t,o,l):jt(c,t))}if(i===le.ONLY_FORMAT){const u=s==null?void 0:s[le.ONLY_FORMAT];return u?u(e,t,o,l):Fd(c,t)}}_getCopyData(e,t){const o=this._univerInstanceService.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET).getActiveSheet();if(!o)throw new Error("No active sheet found");const i=o.getCellMatrix(),s=this._autoFillService.getRules(),l=[],c=t===a.Direction.DOWN||t===a.Direction.UP;let d,u;return c?(d=e.cols,u=e.rows):(d=e.rows,u=e.cols),d.forEach(h=>{const g=this._getEmptyCopyDataPiece(),S={type:void 0,cellData:void 0};u.forEach(f=>{let p;c?p=i.getValue(f,h):p=i.getValue(h,f);const{type:v,isContinue:C}=s.find(b=>b.match(p,this._injector))||el;if(C(S,p)){const b=g[v],R=b[b.length-1];R.data.push(p),R.index.push(f-u[0])}else{const b=g[v];b?b.push({data:[p],index:[f-u[0]]}):g[v]=[{data:[p],index:[f-u[0]]}]}S.type=v,S.cellData=p}),l.push(g)}),l}_getEmptyCopyDataPiece(){const e={};return this._autoFillService.getRules().forEach(t=>{e[t.type]=[]}),e}_getMergeApplyData(e,t,o,i){const s=this._univerInstanceService.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET).getActiveSheet();if(!s)throw new Error("No active sheet found");const l=[];for(let c=e.startRow;c<=e.endRow;c++)for(let d=e.startColumn;d<=e.endColumn;d++){const{isMergedMainCell:u,startRow:h,startColumn:g,endRow:S,endColumn:f}=s.getCellInfoInMergeData(c,d);if(u){if(o===a.Direction.DOWN){let p=h+i,v=S+i;for(;v<=t.endRow;)l.push({startRow:p,startColumn:g,endRow:v,endColumn:f}),p+=i,v+=i}else if(o===a.Direction.UP){let p=h-i,v=S-i;for(;p>=t.startRow;)l.push({startRow:p,startColumn:g,endRow:v,endColumn:f}),p-=i,v-=i}else if(o===a.Direction.RIGHT){let p=g+i,v=f+i;for(;v<=t.endColumn;)l.push({startRow:h,startColumn:p,endRow:S,endColumn:v}),p+=i,v+=i}else if(o===a.Direction.LEFT){let p=g-i,v=f-i;for(;p>=t.startColumn;)l.push({startRow:h,startColumn:p,endRow:S,endColumn:v}),p-=i,v-=i}}}return l}_presetAndCacheData(e,t){const{source:o,target:i}=e,s=this._univerInstanceService.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET).getActiveSheet();if(!s)throw new Error("No active sheet found");const l=s.getCellMatrix(),c=[];return i.rows.forEach(d=>{const u=[];i.cols.forEach(h=>{u.push(a.Tools.deepClone(l.getValue(d,h)))}),c.push(u)}),this._beforeApplyData=c,this._copyData=this._getCopyData(o,t),this._currentLocation=e,this._shouldDisableSeries(this._copyData)?(this._autoFillService.setDisableApplyType(le.SERIES,!0),le.COPY):(this._autoFillService.setDisableApplyType(le.SERIES,!1),this._getPreferredApplyType(this._copyData))}_fillData(e,t,o){var W,H;const i=[],s=[];let l=!0;o===le.NO_FORMAT&&(l=!1,o=le.SERIES);const{source:c,target:d,unitId:u,subUnitId:h}=e;if(!c||!d||t==null)return{undos:i,redos:s};const g=Et(c),S=Et(d),{cols:f,rows:p}=d,{cols:v,rows:C}=c,b=this._copyData;let R;t===a.Direction.DOWN||t===a.Direction.UP?R=C.length:R=v.length;const T=[];if(t===a.Direction.DOWN||t===a.Direction.UP){const U=p.length,B=[];f.forEach((F,L)=>{const j=b[L],z=this._getApplyData(j,R,U,t,o,l);B.push(z)});for(let F=0;F<B[0].length;F++){const L=[];for(let j=0;j<B.length;j++)L.push({s:null,...B[j][F]});T.push(L)}}else{const U=f.length;p.forEach((B,F)=>{const L=b[F],j=this._getApplyData(L,R,U,t,o,l),z=[];for(let q=0;q<j.length;q++)z.push({s:null,...j[q]});T.push(z)})}let M=[];const y=this._univerInstanceService.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET).getStyles();if(l?(M=this._getMergeApplyData(g,S,t,R),T.forEach(U=>{U.forEach(B=>{B&&y&&y&&(B.s=y.getStyleByCell(B))})})):T.forEach((U,B)=>{U.forEach((F,L)=>{F&&y&&(F.s=y.getStyleByCell(this._beforeApplyData[B][L])||null)})}),o===le.ONLY_FORMAT&&T.forEach((U,B)=>{U.forEach((F,L)=>{if(F){const j=this._beforeApplyData[B][L]||{};F.f=j.f,F.si=j.si,F.t=j.t,F.v=j.v}})}),l){const U=[],B=(H=(W=this._univerInstanceService.getUniverSheetInstance(u))==null?void 0:W.getSheetBySheetId(h))==null?void 0:H.getMergeData();B&&B.forEach(j=>{a.Rectangle.intersects(j,S)&&U.push(j)});const F={unitId:u,subUnitId:h,ranges:U},L=this._injector.invoke(m.RemoveMergeUndoMutationFactory,F);U.length&&(s.push({id:m.RemoveWorksheetMergeMutation.id,params:F}),i.unshift({id:m.AddWorksheetMergeMutation.id,params:L}))}const P={subUnitId:h,unitId:u,cellValue:kd([d])},x=this._injector.invoke(m.SetRangeValuesUndoMutationFactory,P);s.push({id:m.SetRangeValuesMutation.id,params:P}),i.unshift({id:m.SetRangeValuesMutation.id,params:x});const A=new a.ObjectMatrix;p.forEach((U,B)=>{f.forEach((F,L)=>{T[B][L]&&A.setValue(U,F,T[B][L])})});const k=A.getMatrix(),N={subUnitId:h,unitId:u,cellValue:k},D=this._injector.invoke(m.SetRangeValuesUndoMutationFactory,N);if(this._autoFillService.getActiveHooks().forEach(U=>{var B;(B=U.onBeforeSubmit)==null||B.call(U,e,t,o,k)}),i.unshift({id:m.SetRangeValuesMutation.id,params:D}),s.push({id:m.SetRangeValuesMutation.id,params:N}),M!=null&&M.length){const U=m.getAddMergeMutationRangeByType(M),B={unitId:u,subUnitId:h,ranges:U},F=this._injector.invoke(m.AddMergeUndoMutationFactory,B);i.unshift({id:m.RemoveWorksheetMergeMutation.id,params:F}),s.push({id:m.AddWorksheetMergeMutation.id,params:B})}return{undos:i,redos:s}}_shouldDisableSeries(e){return e.every(t=>Object.keys(t).every(o=>{var i;return((i=t[o])==null?void 0:i.length)===0||[_e.OTHER,_e.FORMULA].includes(o)}))}_getPreferredApplyType(e){return e.every(o=>Object.keys(o).every(i=>{var s,l;return((s=o[i])==null?void 0:s.length)===0||((l=o[i])==null?void 0:l.length)===1&&o[i][0].data.length===1&&_e.NUMBER===i}))?le.COPY:le.SERIES}};exports.AutoFillController=uu([Ot(0,a.IUniverInstanceService),Ot(1,a.ICommandService),Ot(2,Tt),Ot(3,Se),Ot(4,w.IRenderManagerService),Ot(5,a.Inject(a.Injector)),Ot(6,a.Inject(exports.SheetsRenderService))],exports.AutoFillController);var hu=Object.getOwnPropertyDescriptor,mu=(n,r,e,t)=>{for(var o=t>1?void 0:t?hu(r,e):r,i=n.length-1,s;i>=0;i--)(s=n[i])&&(o=s(o)||o);return o},Zr=(n,r)=>(e,t)=>r(e,t,n);exports.CellCustomRenderController=class extends a.Disposable{constructor(e,t,o,i){super();E(this,"_enterActiveRender");this._context=e,this._sheetSkeletonManagerService=t,this._renderManagerService=o,this._permissionService=i,this._initEventBinding()}_initEventBinding(){const e=new a.DisposableCollection,t=this._context.unit,o=i=>{if(e.dispose(),!i)return;const s=this._context.unitId,{skeleton:l}=i,c=this._renderManagerService.getRenderById(s);if(c&&c.mainComponent){const d=c.mainComponent,u=S=>{const{offsetX:f,offsetY:p}=S,v=c.scene,C=t.getActiveSheet();if(!C)return;const b=v.getActiveViewportByCoord(w.Vector2.FromArray([f,p]));if(!b)return;const{scaleX:R,scaleY:T}=v.getAncestorScale(),M={x:b.viewportScrollX,y:b.viewportScrollY},y=l.getCellIndexByOffset(f,p,R,T,M),P=l.worksheet.getMergedCell(y.row,y.column),x={actualRow:P?P.startRow:y.row,actualCol:P?P.startColumn:y.column,row:y.row,col:y.column};if(!x||!l)return;const A=C.getCell(x.actualRow,x.actualCol);if(!A)return;const k=A.customRender;if(!(k!=null&&k.length))return;const N=x.actualRow,D=x.actualCol,W=k.sort(a.sortRules),H=C.getSheetId(),U={data:A,style:l.getStyles().getStyleByCell(A),primaryWithCoord:l.getCellWithCoordByIndex(x.actualRow,x.actualCol),unitId:s,subUnitId:H,row:N,col:D,workbook:t,worksheet:C},B={x:M.x+f/R,y:M.y+p/T},F=W.find(L=>{var j;return(j=L.isHit)==null?void 0:j.call(L,B,U)});if(F)return[F,U]},h=d.onPointerDown$.subscribeEvent(S=>{var p,v,C,b;const f=u(S);if(f){const[R,T]=f,{row:M,col:y,worksheet:P,unitId:x,subUnitId:A}=T;if(!((p=this._permissionService.composePermission([new m.WorkbookEditablePermission(x).id,new m.WorksheetEditPermission(x,A).id]))==null?void 0:p.every(D=>D.value)))return!1;const N=(C=(v=P.getCell(M,y))==null?void 0:v.selectionProtection)==null?void 0:C[0];if((N==null?void 0:N[m.UnitAction.Edit])===!1)return!1;(b=R.onPointerDown)==null||b.call(R,T,S)}}),g=a.fromEventSubject(d.onPointerMove$).pipe(O.throttleTime(30)).subscribe(S=>{var p,v,C,b,R,T;const f=u(S);if(f){const[M,y]=f;this._enterActiveRender?this._enterActiveRender.render!==M&&((v=(p=this._enterActiveRender.render).onPointerLeave)==null||v.call(p,this._enterActiveRender.cellContext,S),this._enterActiveRender={render:M,cellContext:y},(C=M.onPointerEnter)==null||C.call(M,y,S)):(this._enterActiveRender={render:M,cellContext:y},(b=M.onPointerEnter)==null||b.call(M,y,S))}else this._enterActiveRender&&((T=(R=this._enterActiveRender.render).onPointerLeave)==null||T.call(R,this._enterActiveRender.cellContext,S),this._enterActiveRender=null)});h&&e.add(h),g&&e.add(g)}};this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(o)),o(this._sheetSkeletonManagerService.getCurrentParam()),this.disposeWithMe(e)}};exports.CellCustomRenderController=mu([Zr(1,a.Inject(exports.SheetSkeletonManagerService)),Zr(2,w.IRenderManagerService),Zr(3,a.IPermissionService)],exports.CellCustomRenderController);class ps extends a.Disposable{constructor(){super(...arguments);E(this,"rangesStack",[]);E(this,"selectedRangeWorksheet","")}}var gu=Object.getOwnPropertyDescriptor,Su=(n,r,e,t)=>{for(var o=t>1?void 0:t?gu(r,e):r,i=n.length-1,s;i>=0;i--)(s=n[i])&&(o=s(o)||o);return o},ta=(n,r)=>(e,t)=>r(e,t,n);let Tn=class{constructor(n,r){E(this,"_current",null);E(this,"_shortcutParam",[]);this._univerInstanceService=n,this._localeService=r}dispose(){this._shortcutParam=[]}getCurrentBySearch(n){return this._getCurrentBySearch(n)}getCurrent(){return this._getCurrentBySearch(this._current)}addOrUpdate(n){const r=this._getCurrentBySearch({unitId:n.unitId,sheetId:n.sheetId,keycode:n.keycode});if(r!=null){const e=this._shortcutParam.indexOf(r);this._shortcutParam.splice(e,1)}return this._shortcutParam.push(n),r}remove(n){if(n==null)return;const r=this._getCurrentBySearch(n);if(r==null)return;const e=this._shortcutParam.indexOf(r);return this._shortcutParam.splice(e,1)[0]}_getCurrentBySearch(n){return n==null?void 0:this._shortcutParam.find(e=>e.unitId===n.unitId&&e.sheetId===n.sheetId&&e.keycode===n.keycode)}};Tn=Su([ta(0,a.IUniverInstanceService),ta(1,a.Inject(a.LocaleService))],Tn);var Nr=(n=>(n.MergeAll="mergeAll",n.MergeVertical="mergeVertical",n.MergeHorizontal="mergeHorizontal",n))(Nr||{});function It(n,r,e,t,o=!0,i=1,s=!0){let l={...n};t==null&&(t={startRow:0,endRow:e.getRowCount()-1,startColumn:0,endColumn:e.getColumnCount()-1});let c;switch(r){case a.Direction.UP:for(c=n.startRow-i;c>-1&&!e.getRowVisible(c);)c-=1;c>=t.startRow?(l.startRow=c,l.endRow=c):s&&(l.startRow=t.endRow,l.endRow=t.endRow,o&&(l=It(l,a.Direction.LEFT,e,t,!1)));break;case a.Direction.DOWN:for(c=n.endRow+i;c<e.getRowCount()&&!e.getRowVisible(c);)c+=1;c<=t.endRow?(l.startRow=c,l.endRow=c):s&&(l.startRow=t.startRow,l.endRow=t.startRow,o&&(l=It(l,a.Direction.RIGHT,e,t,!1)));break;case a.Direction.LEFT:for(c=n.startColumn-i;c>-1&&!e.getColVisible(c);)c-=1;c>=t.startColumn?(l.startColumn=c,l.endColumn=c):s&&(l.startColumn=t.endColumn,l.endColumn=t.endColumn,o&&(l=It(l,a.Direction.UP,e,t,!1)));break;case a.Direction.RIGHT:for(c=n.endColumn+i;c<e.getColumnCount()&&!e.getColVisible(c);)c+=1;c<=t.endColumn?(l.startColumn=c,l.endColumn=c):s&&(l.startColumn=t.startColumn,l.endColumn=t.startColumn,o&&(l=It(l,a.Direction.DOWN,e,t,!1)));break}return l}function vs(n,r,e){const t={...n},{startRow:o,startColumn:i,endRow:s,endColumn:l}=to(n,r,e);let c=Bn(e,o,i,s,l).hasValue,d=!0,u=!0;for(;u;){if(a.Direction.UP===r){let h=t.startRow-1;for(;h>-1&&!e.getRowVisible(h);)h-=1;if(h===-1){u=!1;break}const{hasValue:g,matrix:S}=Bn(e,h,t.startColumn,h,t.endColumn);if(c&&!g&&!d){u=!1;break}else{if(S.getLength()!==0){let f=h;S.forValue(p=>{f=Math.min(p,f)}),t.startRow=f}else t.startRow=h;if(t.endRow=t.startRow,!c&&g){u=!1;break}c=g,d=!1}}if(a.Direction.DOWN===r){let h=t.endRow+1;for(;h<e.getRowCount()&&!e.getRowVisible(h);)h+=1;if(h===e.getRowCount()){u=!1;break}const{hasValue:g,matrix:S}=Bn(e,h,t.startColumn,h,t.endColumn);if(c&&!g&&!d){u=!1;break}else{if(S.getLength()!==0){let f=h;S.forValue((p,v,C)=>{f=Math.max(p+(C.rowSpan||1)-1,f)}),t.endRow=f}else t.endRow=h;if(t.startRow=t.endRow,!c&&g){u=!1;break}c=g,d=!1}}if(a.Direction.LEFT===r){let h=t.startColumn-1;for(;h>-1&&!e.getColVisible(h);)h-=1;if(h===-1){u=!1;break}const{hasValue:g,matrix:S}=Bn(e,t.startRow,h,t.endRow,h);if(c&&!g&&!d){u=!1;break}else{if(S.getLength()!==0){let f=h;S.forValue((p,v)=>{f=Math.min(v,f)}),t.startColumn=f}else t.startColumn=h;if(t.endColumn=t.startColumn,!c&&g){u=!1;break}c=g,d=!1}}if(a.Direction.RIGHT===r){let h=t.endColumn+1;for(;h<e.getColumnCount()&&!e.getColVisible(h);)h+=1;if(h===e.getColumnCount()){u=!1;break}const{hasValue:g,matrix:S}=Bn(e,t.startRow,h,t.endRow,h);if(c&&!g&&!d){u=!1;break}else{if(S.getLength()!==0){let f=h;S.forValue((p,v,C)=>{f=Math.max(v+(C.colSpan||1)-1,f)}),t.endColumn=f}else t.endColumn=h;if(t.startColumn=t.endColumn,!c&&g){u=!1;break}c=g,d=!1}}}return m.alignToMergedCellsBorders(t,e,!0)}function tl(n,r,e){return It(n,r,e,void 0,!1,1,!1)}function fu(n,r,e){const t=vs(n,r,e);return m.alignToMergedCellsBorders(a.Rectangle.union(t,n),e,!0)}function pu(n,r,e){const t=tl(n,r,e),o={startRow:Math.min(n.startRow,t.startRow),startColumn:Math.min(n.startColumn,t.startColumn),endRow:Math.max(n.endRow,t.endRow),endColumn:Math.max(n.endColumn,t.endColumn)};return m.alignToMergedCellsBorders(a.Rectangle.union(n,o),e)}function vu(n,r,e,t){const o=a.getReverseDirection(e),i=vs(to(n,o,t),e,t);return e===a.Direction.UP&&i.startRow<=n.startRow?m.alignToMergedCellsBorders({...r,startColumn:n.startColumn,endColumn:n.endColumn},t,!0):e===a.Direction.DOWN&&i.endRow>=n.endRow?m.alignToMergedCellsBorders({...r,startColumn:n.startColumn,endColumn:n.endColumn},t,!0):e===a.Direction.LEFT&&i.startColumn<=n.startColumn?m.alignToMergedCellsBorders({...r,startRow:n.startRow,endRow:n.endRow},t,!0):e===a.Direction.RIGHT&&i.endColumn>=n.endColumn?m.alignToMergedCellsBorders({...r,startRow:n.startRow,endRow:n.endRow},t,!0):a.Rectangle.union(a.Rectangle.clone(r),i)}function Cu(n,r,e){const t=a.getReverseDirection(r),o=to(n,t,e),i=to(n,r,e),s=tl(o,r,e);return m.alignToMergedCellsBorders(a.Rectangle.union(i,s),e,!1)}function na(n){return{startRow:0,startColumn:0,endRow:n.getRowCount()-1,endColumn:n.getColumnCount()-1,rangeType:a.RANGE_TYPE.ALL}}function to(n,r,e){let t;switch(r){case a.Direction.UP:t={startRow:n.startRow,startColumn:n.startColumn,endRow:n.startRow,endColumn:n.endColumn,rangeType:a.RANGE_TYPE.NORMAL};break;case a.Direction.DOWN:t={startRow:n.endRow,startColumn:n.startColumn,endRow:n.endRow,endColumn:n.endColumn,rangeType:a.RANGE_TYPE.NORMAL};break;case a.Direction.LEFT:t={startRow:n.startRow,startColumn:n.startColumn,endRow:n.endRow,endColumn:n.startColumn,rangeType:a.RANGE_TYPE.NORMAL};break;case a.Direction.RIGHT:t={startRow:n.startRow,startColumn:n.endColumn,endRow:n.endRow,endColumn:n.endColumn,rangeType:a.RANGE_TYPE.NORMAL};break;default:throw new Error("Invalid direction")}return m.alignToMergedCellsBorders(t,e,!1)}function Bn(n,r,e,t,o){let i=!1;const s=n.getMatrixWithMergedCells(r,e,t,o).forValue((l,c,d)=>{if(_u(d))return i=!0,!1});return{hasValue:i,matrix:s}}function Fi(n,r,e){const t=a.Rectangle.clone(n);if(r==null)return t;switch(e){case a.Direction.UP:case a.Direction.DOWN:t.startColumn=t.endColumn=r.actualColumn;break;case a.Direction.LEFT:case a.Direction.RIGHT:t.startRow=t.endRow=r.actualRow;break}return t}function Iu(n,r,e){var l,c,d,u;const{primary:t,range:o}=n,i=a.Rectangle.clone(o);switch(r){case a.Direction.UP:case a.Direction.DOWN:i.startRow=(l=t==null?void 0:t.startRow)!=null?l:o.startRow,i.endRow=(c=t==null?void 0:t.endRow)!=null?c:o.startRow;break;case a.Direction.LEFT:case a.Direction.RIGHT:i.startColumn=(d=t==null?void 0:t.startColumn)!=null?d:o.startColumn,i.endColumn=(u=t==null?void 0:t.endColumn)!=null?u:o.startColumn;break}const s=to(i,r,e);switch(r){case a.Direction.DOWN:return o.startRow<s.startRow;case a.Direction.UP:return o.endRow>s.endRow;case a.Direction.LEFT:return s.endColumn<o.endColumn;case a.Direction.RIGHT:return s.startColumn>o.startColumn}}function nl(n,r){let e=n[0].startRow,t=n[0].endRow;n.forEach(i=>{const{startRow:s,endRow:l}=i;e=Math.min(e,s),t=Math.max(t,l)});const o=new Array(t-e+1).fill(!1);return r.forEach(i=>{const{startRow:s,endRow:l}=i;for(let c=Math.max(s,e);c<=Math.min(l,t);c++)o[c-e]=!0}),n.every(i=>{const{startRow:s,endRow:l}=i;for(let c=s;c<=l;c++)if(!o[c-e])return!1;return!0})}function ol(n,r){let e=n[0].startColumn,t=n[0].endColumn;n.forEach(i=>{const{startColumn:s,endColumn:l}=i;e=Math.min(e,s),t=Math.max(t,l)});const o=new Array(t-e+1).fill(!1);return r.forEach(i=>{const{startColumn:s,endColumn:l}=i;for(let c=Math.max(s,e);c<=Math.min(l,t);c++)o[c-e]=!0}),n.every(i=>{const{startColumn:s,endColumn:l}=i;for(let c=s;c<=l;c++)if(!o[c-e])return!1;return!0})}function Cs(n,r){return r?n==="mergeAll"?r.filter(e=>!(e.startRow===e.endRow&&e.startColumn===e.endColumn)):n==="mergeVertical"?r.filter(e=>e.startRow!==e.endRow):n==="mergeHorizontal"?r.filter(e=>e.startColumn!==e.endColumn):r:null}function _u(n){return n.v!==void 0&&n.v!==null&&n.v!==""||n.p!==void 0}var Je=(n=>(n[n.moveStopeOne=0]="moveStopeOne",n[n.moveGap=1]="moveGap",n[n.moveStepPage=2]="moveStepPage",n[n.moveStepEnd=3]="moveStepEnd",n))(Je||{});const xe={id:"sheet.command.move-selection",type:a.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;const e=m.getSheetCommandTarget(n.get(a.IUniverInstanceService));if(!e)return!1;const{workbook:t,worksheet:o}=e,i=m.getSelectionsService(n,r.fromCurrentSelection).getCurrentLastSelection();if(!i)return!1;const{direction:s,jumpOver:l,extra:c}=r,{range:d,primary:u}=i,h=Fi(d,u,s),g=l===1?vs(h,s,o):It(h,s,o),S=m.getCellAtRowCol(g.startRow,g.startColumn,o);if(a.Rectangle.equals(S,h))return!1;const f=t.getUnitId();n.get(Tn).remove({unitId:f,sheetId:o.getSheetId(),keycode:I.KeyCode.TAB});const p=[{range:a.Rectangle.clone(S),primary:{startRow:S.startRow,startColumn:S.startColumn,endRow:S.endRow,endColumn:S.endColumn,actualRow:g.startRow,actualColumn:g.startColumn,isMerged:S.isMerged,isMergedMainCell:S.startRow===g.startRow&&S.startColumn===g.startColumn}}];return n.get(a.ICommandService).executeCommand(m.SetSelectionsOperation.id,{unitId:t.getUnitId(),subUnitId:o.getSheetId(),selections:p,type:m.SelectionMoveType.MOVE_END,extra:c,reveal:!0})}},$e={id:"sheet.command.move-selection-enter-tab",type:a.CommandType.COMMAND,handler:(n,r)=>{var U;if(!r)return!1;const e=m.getSheetCommandTarget(n.get(a.IUniverInstanceService));if(!e)return!1;const{workbook:t,worksheet:o}=e,i=m.getSelectionsService(n),{direction:s,keycode:l}=r,c=s===a.Direction.LEFT||s===a.Direction.UP,d=i.getCurrentSelections().concat(),u=d.findIndex(B=>B.primary),h=d[u];if(!h)return!1;const g=c?-1:1,S=u+g!==d.length?d[u+g]:d[0],f=d.findIndex(B=>B===S),p=t.getUnitId(),v=o.getSheetId();if(!h)return!1;const{range:C}=h,b=h.primary;let R=Fi(C,b,s);const T=n.get(Tn),M=T.getCurrentBySearch({unitId:p,sheetId:v,keycode:I.KeyCode.TAB});let y;const{startRow:P,endRow:x,startColumn:A,endColumn:k}=C,N=c?b.startRow===P&&b.startColumn===A:b.endRow===x&&b.endColumn===k;if(a.Rectangle.equals(C,b)){if(l===I.KeyCode.TAB)M==null&&T.addOrUpdate({unitId:p,sheetId:v,keycode:I.KeyCode.TAB,selection:h});else{const L=M==null?void 0:M.selection;if(L!=null){const{range:j,primary:z}=L;R=Fi(j,z,s)}T.remove({unitId:p,sheetId:v,keycode:I.KeyCode.TAB})}const B=It(R,s,o),F=m.getCellAtRowCol(B.startRow,B.startColumn,o);if(a.Rectangle.equals(F,R))return!1;y={range:a.Rectangle.clone(F),primary:{startRow:F.startRow,startColumn:F.startColumn,endRow:F.endRow,endColumn:F.endColumn,actualRow:B.startRow,actualColumn:B.startColumn,isMerged:F.isMerged,isMergedMainCell:F.startRow===B.startRow&&F.startColumn===B.startColumn}}}else{T.remove({unitId:p,sheetId:v,keycode:I.KeyCode.TAB});const B=a.Tools.deepClone(b),F=N?S.range:It({startRow:B.startRow,startColumn:B.startColumn,endRow:B.endRow,endColumn:B.endColumn},s,o,{startRow:P,endRow:x,startColumn:A,endColumn:k}),L=N&&c,j=L?m.getCellAtRowCol(F.endRow,F.endColumn,o):m.getCellAtRowCol(F.startRow,F.startColumn,o);y={range:N?S.range:a.Rectangle.clone(C),primary:{startRow:j.startRow,startColumn:j.startColumn,endRow:j.endRow,endColumn:j.endColumn,actualRow:L?j.startRow:F.startRow,actualColumn:L?j.startColumn:F.startColumn,isMerged:j.isMerged,isMergedMainCell:j.startRow===F.startRow&&j.startColumn===F.startColumn},style:N?S.style:h.style}}N?(d[u].primary=null,d[f]=y,i.setSelections(p,v,[],m.SelectionMoveType.MOVE_END)):d[u]=y;const D=n.get(a.ICommandService).executeCommand(m.SetSelectionsOperation.id,{unitId:p,subUnitId:v,type:m.SelectionMoveType.MOVE_END,selections:d,reveal:!0,extra:r.extra}),H=(U=n.get(w.IRenderManagerService).getRenderById(p))==null?void 0:U.with(ve);return H==null||H.refreshSelectionMoveEnd(),D}},De={id:"sheet.command.expand-selection",type:a.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;const e=m.getSheetCommandTarget(n.get(a.IUniverInstanceService));if(!e)return!1;const{worksheet:t,unitId:o,subUnitId:i}=e,s=m.getSelectionsService(n).getCurrentLastSelection();if(!s)return!1;const{range:l,primary:c}=s,{jumpOver:d,direction:u,extra:h}=r,S=Iu(s,u,t)?d===1?vu(l,{...a.Rectangle.clone(c),rangeType:a.RANGE_TYPE.NORMAL},u,t):Cu(l,u,t):d===1?fu(l,u,t):pu(l,u,t);return S.rangeType=s.range.rangeType,a.Rectangle.equals(S,l)?!1:n.get(a.ICommandService).syncExecuteCommand(m.SetSelectionsOperation.id,{unitId:o,subUnitId:i,type:m.SelectionMoveType.ONLY_SET,selections:[{range:S,primary:c}],extra:h})}},Dr={id:"sheet.command.select-all",type:a.CommandType.COMMAND,handler:async(n,r={expandToGapFirst:!0,loop:!1})=>{const e=m.getSheetCommandTarget(n.get(a.IUniverInstanceService));if(!e)return!1;const t=m.getSelectionsService(n).getCurrentLastSelection();if(!t)return!1;const o=n.get(ps),{worksheet:i,unitId:s,subUnitId:l}=e,c=`${s}|${l}`;c!==o.selectedRangeWorksheet&&(o.rangesStack=[],o.selectedRangeWorksheet=c);const d=i.getMaxRows(),u=i.getMaxColumns(),{expandToGapFirst:h,loop:g}=r,{range:S,primary:f}=t,p=S.endColumn===u-1&&S.endRow===d-1&&S.startRow===0&&S.startColumn===0;o.rangesStack.some(C=>a.Rectangle.equals(C,S))||(o.rangesStack=[],o.rangesStack.push(S));let v;if(p)if(g){if(o.rangesStack.findIndex(b=>a.Rectangle.equals(b,S))!==o.rangesStack.length-1)return!1;v=o.rangesStack[0]}else return!1;else h?(v=m.expandToContinuousRange(S,{left:!0,right:!0,up:!0,down:!0},i),a.Rectangle.equals(v,S)&&(v=na(i))):v=na(i);return o.rangesStack.some(C=>a.Rectangle.equals(C,v))||o.rangesStack.push(v),n.get(a.ICommandService).executeCommand(m.SetSelectionsOperation.id,{unitId:s,subUnitId:l,reveal:!0,selections:[{range:v,primary:f}]})}};var bu=Object.getOwnPropertyDescriptor,Ru=(n,r,e,t)=>{for(var o=t>1?void 0:t?bu(r,e):r,i=n.length-1,s;i>=0;i--)(s=n[i])&&(o=s(o)||o);return o},Eu=(n,r)=>(e,t)=>r(e,t,n);exports.SheetScrollManagerService=class{constructor(r,e){E(this,"_scrollStateMap",new Map);E(this,"_rawScrollInfo$",new O.BehaviorSubject(null));E(this,"rawScrollInfo$",this._rawScrollInfo$.asObservable());E(this,"validViewportScrollInfo$",new O.BehaviorSubject(null));E(this,"_searchParamForScroll",null);this._context=r,this._sheetSkeletonManagerService=e}dispose(){this._rawScrollInfo$.complete()}calcViewportScrollFromRowColOffset(r){if(!r)return{viewportScrollX:0,viewportScrollY:0};let{sheetViewStartColumn:e,sheetViewStartRow:t,offsetX:o,offsetY:i}=r;t=t||0,i=i||0;const s=this._sheetSkeletonManagerService.getCurrentSkeleton(),l=(s==null?void 0:s.rowHeightAccumulation[t-1])||0,d=((s==null?void 0:s.columnWidthAccumulation[e-1])||0)+o,u=l+i;return{viewportScrollX:d,viewportScrollY:u}}setSearchParam(r){this._searchParamForScroll=r}getScrollStateByParam(r){return this._getCurrentScroll(r)}getCurrentScrollState(){return this._getCurrentScroll(this._searchParamForScroll)}setValidScrollState(r){this._setScrollState(r)}emitRawScrollParam(r){this._emitRawScroll(r)}setValidScrollStateToCurrSheet(r){if(this._searchParamForScroll==null)return;this._setScrollState({...this._searchParamForScroll,...r});const e=this._searchParamForScroll.sheetId,t=this._sheetSkeletonManagerService.getSkeleton(e);t&&t.setScroll(r.viewportScrollX,r.viewportScrollY)}clear(){this._searchParamForScroll!=null&&this._clearByParamAndNotify(this._searchParamForScroll)}_setScrollState(r){const{unitId:e,sheetId:t,sheetViewStartColumn:o,sheetViewStartRow:i,offsetX:s,offsetY:l}=r;this._scrollStateMap.has(e)||this._scrollStateMap.set(e,new Map);const c=this._scrollStateMap.get(e),d={sheetViewStartRow:i,sheetViewStartColumn:o,offsetX:s,offsetY:l};c.set(t,d)}_clearByParamAndNotify(r){this._setScrollState({...r,sheetViewStartRow:0,sheetViewStartColumn:0,offsetX:0,offsetY:0}),this._emitRawScroll({sheetViewStartRow:0,sheetViewStartColumn:0,offsetX:0,offsetY:0})}_getCurrentScroll(r){var s;const e={sheetViewStartRow:0,sheetViewStartColumn:0,offsetX:0,offsetY:0};if(r==null)return e;const{unitId:t,sheetId:o}=r;return((s=this._scrollStateMap.get(t))==null?void 0:s.get(o))||e}_emitRawScroll(r){this._rawScrollInfo$.next(r)}};exports.SheetScrollManagerService=Ru([Eu(1,a.Inject(exports.SheetSkeletonManagerService))],exports.SheetScrollManagerService);const je={id:"sheet.operation.set-scroll",type:a.CommandType.OPERATION,handler:(n,r)=>{if(!r)return!1;const{unitId:e,sheetId:t,offsetX:o,offsetY:i,sheetViewStartColumn:s,sheetViewStartRow:l}=r;return n.get(w.IRenderManagerService).getRenderById(e).with(exports.SheetScrollManagerService).emitRawScrollParam({unitId:e,sheetId:t,offsetX:o,offsetY:i,sheetViewStartRow:l,sheetViewStartColumn:s}),!0}},wn={id:"sheet.command.set-scroll-relative",type:a.CommandType.COMMAND,handler:async(n,r)=>{const e=n.get(a.ICommandService),t=n.get(a.IUniverInstanceService),o=n.get(w.IRenderManagerService),i=m.getSheetCommandTarget(t);if(!i)return!1;const{unitId:s,subUnitId:l}=i,d=o.getRenderById(s).with(exports.SheetScrollManagerService).getCurrentScrollState(),{offsetX:u=0,offsetY:h=0}=r||{},{sheetViewStartRow:g=0,sheetViewStartColumn:S=0,offsetX:f=0,offsetY:p=0}=d||{};return e.executeCommand(je.id,{unitId:s,sheetId:l,sheetViewStartRow:g,sheetViewStartColumn:S,offsetX:f+u,offsetY:p+h})}},ze={id:"sheet.command.scroll-view",type:a.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;const e=n.get(a.IUniverInstanceService),t=n.get(w.IRenderManagerService),o=m.getSheetCommandTarget(e);if(!o)return!1;const{workbook:i,worksheet:s,unitId:l}=o,d=t.getRenderById(l).with(exports.SheetScrollManagerService).getCurrentScrollState();if(!s)return!1;const{sheetViewStartRow:u,sheetViewStartColumn:h,offsetX:g,offsetY:S}=r,{sheetViewStartColumn:f,sheetViewStartRow:p,offsetX:v,offsetY:C}=d||{},{xSplit:b,ySplit:R}=o.worksheet.getConfig().freeze;return n.get(a.ICommandService).syncExecuteCommand(je.id,{unitId:i.getUnitId(),sheetId:s.getSheetId(),sheetViewStartRow:u!=null?u:p!=null?p:0+R,sheetViewStartColumn:h!=null?h:f!=null?f:0+b,offsetX:g!=null?g:v,offsetY:S!=null?S:C})}},Is={id:"sheet.command.scroll-to-cell",type:a.CommandType.COMMAND,handler:(n,r)=>{const e=n.get(a.IUniverInstanceService);return n.get(w.IRenderManagerService).getRenderById(e.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET).getUnitId()).with(exports.SheetsScrollRenderController).scrollToRange(r.range,r.forceTop,r.forceLeft)}},Tu={id:"sheet.command.scroll-view-reset",type:a.CommandType.COMMAND,handler:async n=>{const r=n.get(a.IUniverInstanceService),e=m.getSheetCommandTarget(r);if(!e)return!1;const{subUnitId:t,unitId:o}=e;return n.get(a.ICommandService).executeCommand(je.id,{unitId:o,sheetId:t,sheetViewStartRow:0,sheetViewStartColumn:0})}};var wu=Object.getOwnPropertyDescriptor,yu=(n,r,e,t)=>{for(var o=t>1?void 0:t?wu(r,e):r,i=n.length-1,s;i>=0;i--)(s=n[i])&&(o=s(o)||o);return o},sn=(n,r)=>(e,t)=>r(e,t,n);xe.id,$e.id;const Mu=3;exports.SheetsScrollRenderController=class extends a.Disposable{constructor(r,e,t,o,i,s,l){super(),this._context=r,this._injector=e,this._sheetSkeletonManagerService=t,this._contextService=o,this._commandService=i,this._renderManagerService=s,this._scrollManagerService=l,this._initCommandListener(),this._wheelEventListener(),this._scrollBarEventListener(),this._initSkeletonListener()}_wheelEventListener(){const{scene:r}=this._context;if(!r)return;const e=r.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN);e&&this.disposeWithMe(r.onMouseWheel$.subscribeEvent((t,o)=>{if(t.ctrlKey||!this._contextService.getContextValue(a.FOCUSING_SHEET))return;let i=0,s=0;i=t.deltaX,t.shiftKey?i=(t.deltaY||t.deltaX)*Mu:s=t.deltaY,this._commandService.executeCommand(wn.id,{offsetX:i,offsetY:s}),this._context.scene.makeDirty(!0);const l=e.limitedScroll(e.scrollX+i,e.scrollY+s);l&&!l.isLimitedX&&!l.isLimitedY&&(t.preventDefault(),r.getParent().classType===w.RENDER_CLASS_TYPE.SCENE_VIEWER&&o.stopPropagation()),e.isWheelPreventDefaultX&&e.isWheelPreventDefaultY&&t.preventDefault()}))}_scrollBarEventListener(){const{scene:r}=this._context;if(r==null)return;const e=r.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN);e&&(this.disposeWithMe(a.toDisposable(this._scrollManagerService.rawScrollInfo$.subscribe(t=>{var S;const o=(S=this._sheetSkeletonManagerService.getCurrentParam())==null?void 0:S.skeleton;if(!o)return;if(t==null){e.scrollToViewportPos({viewportScrollX:0,viewportScrollY:0});return}const{sheetViewStartRow:i,sheetViewStartColumn:s,offsetX:l,offsetY:c}=t,{startX:d,startY:u}=o.getCellWithCoordByIndex(i,s,!1),h=d+l,g=u+c;e.scrollToViewportPos({viewportScrollX:h,viewportScrollY:g})}))),this.disposeWithMe(e.onScrollAfter$.subscribeEvent(t=>{var p;const o=(p=this._sheetSkeletonManagerService.getCurrentParam())==null?void 0:p.skeleton;if(o==null||t.isTrigger===!1)return;const i=this._getSheetObject();if(o==null||i==null)return;const{viewportScrollX:s,viewportScrollY:l,scrollX:c,scrollY:d}=t,{row:u,column:h,rowOffset:g,columnOffset:S}=o.getOffsetRelativeToRowCol(s,l),f={sheetViewStartRow:u,sheetViewStartColumn:h,offsetX:S,offsetY:g,viewportScrollX:s,viewportScrollY:l,scrollX:c,scrollY:d};this._scrollManagerService.setValidScrollStateToCurrSheet(f),this._scrollManagerService.validViewportScrollInfo$.next({...f,viewportScrollX:s,viewportScrollY:l,scrollX:c,scrollY:d})})),this.disposeWithMe(e.onScrollByBar$.subscribeEvent(t=>{var g;const o=(g=this._sheetSkeletonManagerService.getCurrentParam())==null?void 0:g.skeleton;if(o==null||t.isTrigger===!1)return;const i=this._getSheetObject();if(o==null||i==null)return;const{viewportScrollX:s=0,viewportScrollY:l=0}=t;this._getFreeze();const{row:c,column:d,rowOffset:u,columnOffset:h}=o.getOffsetRelativeToRowCol(s,l);this._commandService.executeCommand(ze.id,{sheetViewStartRow:c,sheetViewStartColumn:d,offsetX:h,offsetY:u})})))}_initSkeletonListener(){this.disposeWithMe(a.toDisposable(this._sheetSkeletonManagerService.currentSkeletonBefore$.subscribe(r=>{if(r==null)return;const e={unitId:r.unitId,sheetId:r.sheetId};if(this._scrollManagerService.setSearchParam(e),!this._getSheetObject())return;const o=this._scrollManagerService.getScrollStateByParam(e),{viewportScrollX:i,viewportScrollY:s}=this._scrollManagerService.calcViewportScrollFromRowColOffset(o);o&&this._updateViewportScroll(i,s)})))}_updateViewportScroll(r=0,e=0){const t=this._getSheetObject();if(!t)return;const o=t.scene,i=o.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN),s=o.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_COLUMN_RIGHT),l=o.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_ROW_BOTTOM),c=o.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT),d=o.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP);i&&(i.viewportScrollX=r,i.viewportScrollY=e),l&&(l.viewportScrollY=e),s&&(s.viewportScrollX=r),c&&(c.viewportScrollY=e),d&&(d.viewportScrollX=r)}scrollToRange(r,e,t){let{endRow:o,endColumn:i,startColumn:s,startRow:l}=r;const c=this._getViewportBounding();if(r.rangeType===a.RANGE_TYPE.ROW?(s=0,i=0):r.rangeType===a.RANGE_TYPE.COLUMN&&(l=0,o=0),c&&!e&&!t){const d=c.startRow>o?l:o,u=c.startColumn>i?s:i;return this._scrollToCell(d,u)}else return this._scrollToCell(l,s,e,t)}scrollToCell(r,e){const t=this._context.unit.getActiveSheet(),{ySplit:o,xSplit:i}=t.getFreeze();return this._commandService.syncExecuteCommand(ze.id,{sheetViewStartRow:r-o,sheetViewStartColumn:e-i,offsetX:0,offsetY:0})}_initCommandListener(){this.disposeWithMe(this._commandService.onCommandExecuted(r=>{switch(r.id){case m.SetSelectionsOperation.id:{const e=r.params;e.unitId===this._context.unitId&&e.reveal&&this._scrollToSelection()}break;case m.ScrollToCellOperation.id:{const e=r.params;if(e.unitId===this._context.unitId){const t=e.range;this.scrollToRange(t)}}break;case De.id:{const e=r.params;this._scrollToSelectionForExpand(e)}break}}))}_scrollToSelectionForExpand(r){setTimeout(()=>{const e=this._getSelectionsService().getCurrentLastSelection();if(e==null)return;const{startRow:t,startColumn:o,endRow:i,endColumn:s}=e.range,l=this._getViewportBounding();if(l==null)return;const{startRow:c,startColumn:d,endRow:u,endColumn:h}=l;let g=0,S=0;t>c?g=i:i<u?g=t:g=c,o>d?S=s:s<h?S=o:S=d,r.direction===a.Direction.DOWN?g=i:r.direction===a.Direction.UP?g=t:r.direction===a.Direction.RIGHT?S=s:r.direction===a.Direction.LEFT&&(S=o),this._scrollToCell(g,S)},0)}_getFreeze(){var e;const r=(e=this._sheetSkeletonManagerService.getCurrentParam())==null?void 0:e.skeleton.getWorksheetConfig();if(r!=null)return r.freeze}_updateSceneSize(r){var h;if(r==null)return;const{unitId:e}=this._context,{skeleton:t}=r,o=(h=this._renderManagerService.getRenderById(e))==null?void 0:h.scene;if(t==null||o==null)return;const{rowTotalHeight:i,columnTotalWidth:s,rowHeaderWidthAndMarginLeft:l,columnHeaderHeightAndMarginTop:c}=t;this._context.unit.getActiveSheet()&&(o==null||o.transformByState({width:l+s,height:c+i}))}_getSheetObject(){return Ge(this._context.unit,this._context)}_scrollToSelectionByDirection(r){const e=this._getViewportBounding();if(e==null)return!1;const{startRow:t,startColumn:o,endRow:i,endColumn:s}=e;let l=0,c=0;const{startRow:d,startColumn:u,endRow:h,endColumn:g}=r;d>=t&&(l=h),h<=i&&(l=d),u>=o&&(c=g),g<=s&&(c=u),this._scrollToCell(l,c)}_scrollToSelection(r=!0){var d;const e=this._getSelectionsService().getCurrentLastSelection();if(!e)return;const{startRow:t,startColumn:o,actualRow:i,actualColumn:s}=(d=e.primary)!=null?d:e.range,l=r&&i!=null?i:t,c=r&&s!=null?s:o;this._scrollToCell(l,c)}_getSelectionsService(){return m.getSelectionsService(this._injector)}_getViewportBounding(){var i,s;const r=(i=this._getSheetObject())==null?void 0:i.scene;if(r==null)return;const e=r.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN);if(e==null)return;const t=(s=this._sheetSkeletonManagerService.getCurrentParam())==null?void 0:s.skeleton;if(t==null)return;const o=e.calcViewportInfo();return t.getRangeByViewBound(o.viewBound)}_scrollToCell(r,e,t=!1,o=!1){var k,N,D;const{rowHeightAccumulation:i,columnWidthAccumulation:s}=(k=this._sheetSkeletonManagerService.getCurrentSkeleton())!=null?k:{};if(i==null||s==null)return!1;const l=(N=this._getSheetObject())==null?void 0:N.scene;if(l==null)return!1;const c=l.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN);if(c==null)return!1;const d=(D=this._sheetSkeletonManagerService.getCurrentParam())==null?void 0:D.skeleton;if(d==null)return!1;const u=this._context.unit.getActiveSheet();if(!u)return!1;r=a.Tools.clamp(r,0,i.length-1),e=a.Tools.clamp(e,0,s.length-1);const{startColumn:h,startRow:g,ySplit:S,xSplit:f}=u.getFreeze(),p=this._getViewportBounding();if(p==null)return!1;const{startRow:v,startColumn:C,endRow:b,endColumn:R}=p;let T,M;if(r>=g&&e>=h-S&&(r<=v&&(T=r,t=!0),r>=b)){const W=i[r]-c.height;for(let H=v;H<=r&&(T=H+1,!(i[H]>=W));H++);}if(e>=h&&r>=g-S&&(e<=C&&(M=e,o=!0),e>=R)){const W=s[e]-c.width;for(let H=C;H<=e&&(M=H+1,!(s[H]>=W));H++);}if(T===void 0&&M===void 0)return!1;let{offsetX:y,offsetY:P,sheetViewStartRow:x,sheetViewStartColumn:A}=this._scrollManagerService.getCurrentScrollState()||{};if(T=T?Math.min(T,r):x+S,M=M?Math.min(M,e):A+f,o){y=0,M=e;const W=d.getHiddenColumnsInRange({startColumn:M-f,endColumn:M});M=M-W.length}if(t){P=0,T=r;const W=d.getHiddenRowsInRange({startRow:T-S,endRow:T});T=T-W.length}return this._commandService.syncExecuteCommand(ze.id,{sheetViewStartRow:Math.max(0,T-S),sheetViewStartColumn:Math.max(0,M-f),offsetX:y,offsetY:P})}};exports.SheetsScrollRenderController=yu([sn(1,a.Inject(a.Injector)),sn(2,a.Inject(exports.SheetSkeletonManagerService)),sn(3,a.IContextService),sn(4,a.ICommandService),sn(5,w.IRenderManagerService),sn(6,a.Inject(exports.SheetScrollManagerService))],exports.SheetsScrollRenderController);const _s={id:"sheet.operation.scroll-to-range",type:a.CommandType.OPERATION,handler:(n,r)=>{if(!r)return!1;const e=n.get(a.IUniverInstanceService);return n.get(w.IRenderManagerService).getRenderById(e.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET).getUnitId()).with(exports.SheetsScrollRenderController).scrollToRange(r.range,r.forceTop,r.forceLeft)}};class rl{constructor(){E(this,"_state",null);E(this,"_rect",null);E(this,"_state$",new O.BehaviorSubject(null));E(this,"state$",this._state$.asObservable());E(this,"_rect$",new O.BehaviorSubject(null));E(this,"rect$",this._rect$.asObservable());E(this,"_focus",!1);E(this,"_focus$",new O.BehaviorSubject(this._focus));E(this,"focus$",this._focus$.asObservable())}dispose(){this._state$.complete(),this._state=null,this._rect$.complete(),this._rect=null}setState(r){this._state=r,this._refresh(r)}getRect(){return this._rect}setRect(r){this._rect=r,this._rect$.next(r)}getState(){return this._state}setFocus(r=!1){this._focus=r,this._focus$.next(r)}_refresh(r){this._state$.next(r)}}const go=a.createIdentifier("univer.sheet-cell-editor-manager.service"),Pu="36",Ou="univer-sheet-container",il={sheetFooterBarHeight:Pu,sheetContainer:Ou};var xu=Object.getOwnPropertyDescriptor,Au=(n,r,e,t)=>{for(var o=t>1?void 0:t?xu(r,e):r,i=n.length-1,s;i>=0;i--)(s=n[i])&&(o=s(o)||o);return o},an=(n,r)=>(e,t)=>r(e,t,n);const oa=5,ra=2;exports.SheetCellEditorResizeService=class extends a.Disposable{constructor(r,e,t,o,i,s,l){super(),this._context=r,this._layoutService=e,this._cellEditorManagerService=t,this._editorBridgeService=o,this._renderManagerService=i,this._sheetSkeletonManagerService=s,this._univerInstanceService=l}fitTextSize(r){var A,k,N,D;const e=this._editorBridgeService.getEditCellState();if(!e)return;const{position:t,documentLayoutObject:o,canvasOffset:i,scaleX:s,scaleY:l}=e,{startX:c,startY:d,endX:u,endY:h}=t,g=this._univerInstanceService.getUnit(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY,a.UniverInstanceType.UNIVER_DOC);if(g==null)return;const S=this._getEditorSkeleton();if(!S)return;const f=this._predictingSize(t,i,S,o,s,l);if(!f)return;let{actualWidth:p,actualHeight:v}=f;const{verticalAlign:C,horizontalAlign:b,paddingData:R,fill:T}=o;p=p+((A=R.l)!=null?A:0)+((k=R.r)!=null?k:0),v=v+((N=R.t)!=null?N:0)+((D=R.b)!=null?D:0);let M=u-c,y=h-d;M<p&&(M=Math.ceil(p)),y<v&&(y=Math.ceil(v));let P=0;C===a.VerticalAlign.MIDDLE?P=(y-v)/2/l:C===a.VerticalAlign.TOP?P=R.t||0:P=(y-v)/l;let x=0;b===a.HorizontalAlign.CENTER?x=(M-p)/2/s:b===a.HorizontalAlign.RIGHT?x=(M-p)/s:x=R.l||0,P=P<(R.t||0)?R.t||0:P,x=x<(R.l||0)?R.l||0:x,g.updateDocumentDataMargin({t:P,l:x}),S.calculate(),this._editAreaProcessing(M,y,t,i,T,s,l,b,r)}_predictingSize(r,e,t,o,i=1,s=1){const{startX:l,endX:c}=r,{textRotation:d,wrapStrategy:u,paddingData:h}=o,g=this._univerInstanceService.getUnit(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY,a.UniverInstanceType.UNIVER_DOC),{vertexAngle:S}=w.convertTextRotation(d);if(u===a.WrapStrategy.WRAP&&S===0){g==null||g.updateDocumentDataPageSize(c-l),g==null||g.updateDocumentDataMargin({l:h.l,t:h.t}),t.calculate();const{actualWidth:C,actualHeight:b}=t.getActualSize();return{actualWidth:C*i,actualHeight:b*s}}const f=this._getEditorMaxSize(r,e,o.horizontalAlign);if(!f)return;g==null||g.updateDocumentDataPageSize(f.width/i),t.calculate();const p=t.getActualSize();let v=c-l;return v<p.actualWidth*i+oa*i&&(v=p.actualWidth*i+oa*i),g==null||g.updateDocumentDataPageSize(v/i),g==null||g.updateDocumentRenderConfig({horizontalAlign:a.HorizontalAlign.UNSPECIFIED,cellValueType:void 0}),{actualWidth:p.actualWidth*i,actualHeight:p.actualHeight*s}}_getEditorMaxSize(r,e,t){if(this._getEditorObject()==null)return;function i(b){return Number.parseInt(b.replace("px",""))}const l=this._context.engine.getCanvasElement(),c=l.getBoundingClientRect(),d=i(l.style.width),{width:u}=c,h=u/d,{startX:g,startY:S,endX:f}=r,p=this._context.engine.width,v=document.body.clientHeight-S-Number.parseFloat(il.sheetFooterBarHeight)-e.top-ra*2;let C=u-g;if(t===a.HorizontalAlign.CENTER){const b=p-f,R=g;C=f-g+Math.min(R,b)*2}else t===a.HorizontalAlign.RIGHT&&(C=f);return{height:v,width:C-ra,scaleAdjust:h}}_editAreaProcessing(r,e,t,o,i,s=1,l=1,c,d){var H;const u=this._getEditorObject();if(u==null)return;const g=this._context.engine.getCanvasElement();let{startX:S,startY:f}=t;const{document:p,scene:v,engine:C}=u,b=v.getViewport($.VIEWPORT_KEY.VIEW_MAIN),R=this._getEditorMaxSize(t,o,c),{height:T,width:M,scaleAdjust:y}=R;let P=e,x=b==null?void 0:b.getScrollBar();P>T?(x==null?b&&new w.ScrollBar(b,{enableHorizontal:!1,barSize:8}):b==null||b.resetCanvasSizeAndUpdateScroll(),b==null||b.scrollToViewportPos({viewportScrollY:P-T}),P=T):(x=null,(H=b==null?void 0:b.getScrollBar())==null||H.dispose()),r+=(x==null?void 0:x.barSize)||0,r>M&&(r=M),this._addBackground(v,r/s,e/l,i);const{scaleX:A,scaleY:k}=v.getPrecisionScale();v.transformByState({width:r*y/s,height:e*y/l,scaleX:s*y,scaleY:l*y}),p.resize(r*y/s,e*y/l),setTimeout(()=>{C.resizeBySize(w.fixLineWidthByScale(r,A),w.fixLineWidthByScale(P,k)),d==null||d()},0);const N=this._layoutService.getContentElement().getBoundingClientRect(),D=g.getBoundingClientRect();S=S*y+(D.left-N.left),f=f*y+(D.top-N.top);const W=t.endX-t.startX;c===a.HorizontalAlign.RIGHT?S+=(W-r)*y:c===a.HorizontalAlign.CENTER&&(S+=(W-r*y)/2),this._cellEditorManagerService.setState({startX:S,startY:f,endX:r*y+S,endY:P*y+f,show:!0})}_addBackground(r,e,t,o){const i="_backgroundRectHelperColor_",s=r.getObject(i);s==null&&o==null||(s==null?r.addObjects([new w.Rect(i,{width:e,height:t,fill:o,evented:!1})],$.DOCS_COMPONENT_MAIN_LAYER_INDEX):o==null?s.dispose():(s.setProps({fill:o}),s.transformByState({width:e,height:t})))}resizeCellEditor(r){var y;const e=this._cellEditorManagerService.getState();if(!e||!this._editorBridgeService.isVisible().visible)return;this._editorBridgeService.refreshEditCellPosition(!0);const t=this._editorBridgeService.getEditCellState();if(!t)return;const o=(y=this._sheetSkeletonManagerService.getSkeletonParam(t.sheetId))==null?void 0:y.skeleton;if(!o)return;const{row:i,column:s,scaleX:l,scaleY:c,position:d,canvasOffset:u,documentLayoutObject:h}=t,{horizontalAlign:g}=h,S=this._getEditorMaxSize(d,u,g);if(!S)return;const{height:f,width:p,scaleAdjust:v}=S,C=o.getCellWithCoordByIndex(i,s),b=Math.min((C.mergeInfo.endY-C.mergeInfo.startY)*c,f)*v,R=Math.min((C.mergeInfo.endX-C.mergeInfo.startX)*l,p)*v,T=e.endY-e.startY,M=e.endX-e.startX;if(T!==b||M!==R){if(this._editorBridgeService.refreshEditCellPosition(!0),!this._getEditorSkeleton())return;this.fitTextSize(r)}}_getEditorObject(){return Pr(this._editorBridgeService.getCurrentEditorId(),this._renderManagerService)}_getEditorSkeleton(){var r;return(r=this._renderManagerService.getRenderById(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY))==null?void 0:r.with(Re.DocSkeletonManagerService).getSkeleton()}};exports.SheetCellEditorResizeService=Au([an(1,I.ILayoutService),an(2,go),an(3,Se),an(4,w.IRenderManagerService),an(5,a.Inject(exports.SheetSkeletonManagerService)),an(6,a.IUniverInstanceService)],exports.SheetCellEditorResizeService);function bs(n){return n.getContextValue(a.FOCUSING_SHEET)}function ce(n){return n.getContextValue(a.FOCUSING_SHEET)&&n.getContextValue(a.FOCUSING_UNIVER_EDITOR)&&!n.getContextValue(a.EDITOR_ACTIVATED)&&!n.getContextValue(a.FOCUSING_COMMON_DRAWINGS)}function sl(n){return n.getContextValue(a.FOCUSING_SHEET)&&n.getContextValue(a.FOCUSING_UNIVER_EDITOR)&&!n.getContextValue(a.EDITOR_ACTIVATED)&&!n.getContextValue(a.FOCUSING_FX_BAR_EDITOR)&&!n.getContextValue(a.FOCUSING_COMMON_DRAWINGS)}function ku(n){return n.getContextValue(a.FOCUSING_SHEET)&&n.getContextValue(a.FOCUSING_UNIVER_EDITOR)&&n.getContextValue(a.EDITOR_ACTIVATED)}function Nu(n){return n.getContextValue(a.FOCUSING_UNIVER_EDITOR)&&n.getContextValue(a.EDITOR_ACTIVATED)}function al(n){return n.getContextValue(a.FOCUSING_FX_BAR_EDITOR)&&n.getContextValue(a.FOCUSING_UNIVER_EDITOR)}function Du(n){return n.getContextValue(a.FOCUSING_SHEET)&&n.getContextValue(a.EDITOR_ACTIVATED)&&n.getContextValue(a.FOCUSING_EDITOR_INPUT_FORMULA)&&n.getContextValue(a.FOCUSING_UNIVER_EDITOR)}function no(n){return n.getContextValue(a.FOCUSING_SHEET)&&n.getContextValue(a.FOCUSING_UNIVER_EDITOR)&&n.getContextValue(a.EDITOR_ACTIVATED)&&!n.getContextValue(a.FOCUSING_EDITOR_INPUT_FORMULA)&&!n.getContextValue(a.FOCUSING_EDITOR_STANDALONE)}const ll=[I.KeyCode.ARROW_DOWN,I.KeyCode.ARROW_UP,I.KeyCode.ARROW_LEFT,I.KeyCode.ARROW_RIGHT],Hu=[I.KeyCode.ENTER,I.KeyCode.TAB,...ll];function cl(){const n=[];for(const r of ll)n.push({id:Xt.id,binding:r,preconditions:e=>no(e),staticParameters:{visible:!1,eventType:w.DeviceInputEventType.Keyboard,keycode:r,isShift:!1}}),n.push({id:Xt.id,binding:r|I.MetaKeys.SHIFT,preconditions:e=>no(e),staticParameters:{visible:!1,eventType:w.DeviceInputEventType.Keyboard,keycode:r,isShift:!0}});return n}const dl={id:mo.id,binding:I.KeyCode.F2,description:"shortcut.sheet.start-editing",group:"4_sheet-edit",preconditions:ce,staticParameters:{visible:!0,eventType:w.DeviceInputEventType.Keyboard,keycode:I.KeyCode.F2}},ul={id:Ce.id,binding:I.KeyCode.ENTER,description:"shortcut.sheet.toggle-editing",group:"4_sheet-edit",preconditions:n=>no(n),staticParameters:{visible:!1,eventType:w.DeviceInputEventType.Keyboard,keycode:I.KeyCode.ENTER}},hl={id:Ce.id,binding:I.KeyCode.TAB,preconditions:n=>no(n),staticParameters:{visible:!1,eventType:w.DeviceInputEventType.Keyboard,keycode:I.KeyCode.TAB}},ml={id:Ce.id,binding:I.KeyCode.ESC,description:"shortcut.sheet.abort-editing",group:"4_sheet-edit",preconditions:n=>no(n),staticParameters:{visible:!1,eventType:w.DeviceInputEventType.Keyboard,keycode:I.KeyCode.ESC}},gl={id:$.BreakLineCommand.id,description:"shortcut.sheet.break-line",group:"4_sheet-edit",preconditions:n=>ku(n),binding:I.KeyCode.ENTER|I.MetaKeys.ALT},Sl={id:$.DeleteLeftCommand.id,preconditions:n=>Nu(n)||al(n),binding:I.KeyCode.BACKSPACE},fl={id:Ce.id,description:"shortcut.sheet.delete-and-start-editing",group:"4_sheet-edit",preconditions:n=>ce(n)&&!al(n),binding:I.KeyCode.BACKSPACE,staticParameters:{visible:!0,eventType:w.DeviceInputEventType.Keyboard,keycode:I.KeyCode.BACKSPACE}};function Vu(n){return n.startsWith("'")}function Wu(n){return n.slice(1)}const Uu={"0":"0","1":"1","2":"2","3":"3","4":"4","5":"5","6":"6","7":"7","8":"8","9":"9",A:"A",B:"B",C:"C",D:"D",E:"E",F:"F",G:"G",H:"H",I:"I",J:"J",K:"K",L:"L",M:"M",N:"N",O:"O",P:"P",Q:"Q",R:"R",S:"S",T:"T",U:"U",V:"V",W:"W",X:"X",Y:"Y",Z:"Z",a:"a",b:"b",c:"c",d:"d",e:"e",f:"f",g:"g",h:"h",i:"i",j:"j",k:"k",l:"l",m:"m",n:"n",o:"o",p:"p",q:"q",r:"r",s:"s",t:"t",u:"u",v:"v",w:"w",x:"x",y:"y",z:"z","%":"%","-":"-",".":".",":":":","/":"/","+":"+","@":"@","&":"&","*":"*","#":"#","=":"=",">":">","<":"<","$":"$",""":'"',"'":"'","(":"(",")":")"," ":" ",",":",","!":"!","?":"?",";":";","[":"[","]":"]","{":"{","}":"}"},ji={true:"TRUE",false:"FALSE"};function Lu(n){return[a.LocaleType.ZH_CN,a.LocaleType.ZH_TW].includes(n)}function Bu(n,r,e,t){let o=n;if(Lu(e)){if(n.startsWith("'")||n.startsWith("'"))return`'${n.slice(1)}`;o=Fu(o)}if(o.startsWith("="))return ju(n,o,r,t);const i=o.toLowerCase();return ji[i]?ji[i]:a.numfmt.parseValue(o)==null?n:o}function Fu(n){const r=/['"].*?['"]/g,e=[],t=n.split(r);n.replace(r,i=>(e.push(i),""));let o=t.join("").split("").map(Yu).join("");return e.forEach((i,s)=>{o=o.slice(0,s*2)+i+o.slice((s+1)*2)}),o}function ju(n,r,e,t){const o=e.sequenceNodesBuilder(r);if(!o)return n;let i=r,s=0;return o.forEach((l,c)=>{if(typeof l=="object"){const d=l.token;if(ji[d.toLowerCase()]){const u=l.startIndex+s+1,h=l.endIndex+s+2;i=ln(d.toLocaleUpperCase(),i,u,h)}else if(l.nodeType===K.sequenceNodeType.FUNCTION&&zu(d,t,o,c)||l.nodeType===K.sequenceNodeType.REFERENCE){const u=d.indexOf("!");if(u>-1){const h=d.substring(u+1),g=l.startIndex+s+(u+1)+1,S=l.endIndex+s+2;i=ln(h.toLocaleUpperCase(),i,g,S)}else{const h=l.startIndex+s+1,g=l.endIndex+s+2;i=ln(d.toLocaleUpperCase(),i,h,g)}}else if(d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'")){const u=l.startIndex+s+2,h=l.endIndex+s+1;i=ln(n.slice(u,h),i,u,h)}else if(l.nodeType!==K.sequenceNodeType.ARRAY){const u=a.numfmt.parseValue(d);if(u==null){const h=l.startIndex+s+1,g=l.endIndex+s+2;i=ln(n.slice(h,g),i,h,g)}else if(typeof u.v=="number"&&(u.z===void 0||!a.numfmt.isDate(u.z))){const h=`${u.v}`,g=l.startIndex+s+1,S=l.endIndex+s+2,{processedString:f,offset:p}=Gu(d,h);i=ln(f,i,g,S),s+=p}}}}),i}function zu(n,r,e,t){const o=r.getDescriptions();return e[t+1]!==K.matchToken.OPEN_BRACKET?!1:o.get(Xu(n).toLocaleUpperCase())!==void 0}function Xu(n){const r=/^@+/;return n.replace(r,"")}function Yu(n){return Uu[n]||n}function ln(n,r,e,t){return r.substring(0,e)+n+r.substring(t)}function Gu(n,r){var s,l;const e=((s=n.match(/^\s*/))==null?void 0:s[0])||"",t=((l=n.match(/\s*$/))==null?void 0:l[0])||"",o=e+r+t,i=o.length-n.length;return{processedString:o,offset:i}}const pl="range_selector",vl=n=>n.includes(pl);var Zu=Object.getOwnPropertyDescriptor,Ku=(n,r,e,t)=>{for(var o=t>1?void 0:t?Zu(r,e):r,i=n.length-1,s;i>=0;i--)(s=n[i])&&(o=s(o)||o);return o},ye=(n,r)=>(e,t)=>r(e,t,n);const ia=-1e3;exports.EditingRenderController=class extends a.Disposable{constructor(e,t,o,i,s,l,c,d,u,h,g,S,f,p,v,C){super();E(this,"_cursorChange",0);E(this,"_isUnitEditing",!1);E(this,"_workbookSelections");E(this,"_d");E(this,"_cursorTimeout");this._context=e,this._undoRedoService=o,this._contextService=i,this._renderManagerService=s,this._editorBridgeService=l,this._cellEditorManagerService=c,this._lexerTreeBuilder=d,this._functionService=u,this._textSelectionManagerService=h,this._commandService=g,this._localService=S,this._editorService=f,this._sheetCellEditorResizeService=p,this._univerInstanceService=v,this._sheetInterceptorService=C,this._workbookSelections=t.getWorkbookSelections(this._context.unitId),this.disposeWithMe(this._univerInstanceService.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET).subscribe(b=>{(b==null?void 0:b.getUnitId())===this._context.unitId?this._d=this._init():(this._disposeCurrent(),this._isUnitEditing&&(this._handleEditorInvisible({visible:!1,eventType:w.DeviceInputEventType.Keyboard,keycode:I.KeyCode.ESC,unitId:this._context.unitId}),this._isUnitEditing=!1))})),this._initEditorVisibilityListener()}dispose(){super.dispose(),this._disposeCurrent()}_disposeCurrent(){var e;(e=this._d)==null||e.dispose(),this._d=null}_init(){const e=new a.DisposableCollection;return this._subscribeToCurrentCell(e),this._initialCursorSync(e),this._listenEditorFocus(e),this._commandExecutedListener(e),this._initSkeletonListener(e),e.add(()=>{clearTimeout(this._cursorTimeout)}),this._cursorTimeout=setTimeout(()=>{this._cursorStateListener(e)},1e3),e}_initEditorVisibilityListener(){this.disposeWithMe(this._editorBridgeService.visible$.pipe(O.distinctUntilChanged((e,t)=>e.visible===t.visible)).subscribe(e=>{(e.unitId===a.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY||e.unitId===a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY||e.unitId===this._context.unitId)&&e.visible?(this._isUnitEditing=!0,this._handleEditorVisible(e)):this._isUnitEditing&&(this._handleEditorInvisible(e),this._isUnitEditing=!1)}))}_listenEditorFocus(e){const t=this._getEditorObject();t&&e.add(t.document.onPointerDown$.subscribeEvent(()=>{if(this._isUnitEditing&&this._editorBridgeService.isVisible()){const o=this._editorBridgeService.getEditCellState(),i=this._editorBridgeService.getCurrentEditorId();if(!o||!i)return;this._sheetCellEditorResizeService.fitTextSize()}}))}_initialCursorSync(e){e.add(this._cellEditorManagerService.focus$.pipe(O.filter(t=>!!t)).subscribe(()=>{var o;const t=(o=this._renderManagerService.getCurrentTypeOfRenderer(a.UniverInstanceType.UNIVER_DOC))==null?void 0:o.with($.DocSelectionRenderService);t&&t.sync()}))}_initSkeletonListener(e){const t=new Set(m.COMMAND_LISTENER_SKELETON_CHANGE);t.delete(m.SetWorksheetActiveOperation.id),e.add(this._commandService.onCommandExecuted(o=>{if(t.has(o.id)){switch(o.id){case m.MoveRowsMutation.id:case m.MoveColsMutation.id:case m.RemoveColMutation.id:case m.RemoveRowMutation.id:case m.InsertColMutation.id:case m.InsertRowMutation.id:{const i=this._editorBridgeService.getEditLocation();if(!i)break;const s={startRow:i.row,startColumn:i.column,endRow:i.row,endColumn:i.column},l=m.adjustRangeOnMutation(s,o);if(!l)break;const c=l.startRow,d=l.startColumn;this._editorBridgeService.updateEditLocation(c,d);break}}this._sheetCellEditorResizeService.resizeCellEditor(()=>{this._textSelectionManagerService.refreshSelection({unitId:a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY,subUnitId:a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY})})}}))}_subscribeToCurrentCell(e){e.add(this._editorBridgeService.currentEditCellState$.subscribe(t=>{var b,R;if(t==null||this._editorBridgeService.isForceKeepVisible())return;const o=this._editorBridgeService.getEditCellState();if(o==null)return;const{position:i,documentLayoutObject:s,scaleX:l,editorUnitId:c}=o;if(this._contextService.getContextValue(a.FOCUSING_EDITOR_STANDALONE))return;const d=this._getDocumentDataModel();if(d==null)return;const{startX:u,endX:h}=i,{textRotation:g,wrapStrategy:S,documentModel:f}=s,{vertexAngle:p}=w.convertTextRotation(g);S===a.WrapStrategy.WRAP&&p===0&&d.updateDocumentDataPageSize((h-u)/l),this._commandService.syncExecuteCommand($.ReplaceSnapshotCommand.id,{unitId:c,snapshot:f.getSnapshot()}),this._contextService.setContextValue(a.FOCUSING_EDITOR_BUT_HIDDEN,!0),this._textSelectionManagerService.replaceDocRanges([{startOffset:0,endOffset:0}],{unitId:a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY,subUnitId:a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY});const v=(b=this._renderManagerService.getRenderById(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY))==null?void 0:b.with($.DocSelectionRenderService),C=(R=this._renderManagerService.getRenderById(a.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY))==null?void 0:R.with($.DocSelectionRenderService);(v!=null&&v.canFocusing||C!=null&&C.canFocusing)&&(this._univerInstanceService.setCurrentUnitForType(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY),v==null||v.activate(ia,ia,!0))}))}_commandExecutedListener(e){e.add(this._commandService.onCommandExecuted(o=>{if(o.id===Re.RichTextEditingMutation.id){const i=o.params,{unitId:s}=i;if(!this._isCurrentSheetFocused()||vl(s)||(this._editorBridgeService.changeEditorDirty(!0),!this._editorBridgeService.isVisible().visible))return;s===a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY&&this._sheetCellEditorResizeService.fitTextSize()}}));const t=[Xt.id];e.add(this._commandService.onCommandExecuted(o=>{if(t.includes(o.id)){const i=o.params,{keycode:s,isShift:l}=i;if(s!=null&&(this._cursorChange===2||this._contextService.getContextValue(a.FOCUSING_FX_BAR_EDITOR))){this._moveInEditor(s,l);return}this._commandService.syncExecuteCommand(Ce.id,i)}o.id===mo.id&&(this._cursorChange=2)}))}_handleEditorVisible(e){var S,f,p;const{eventType:t,keycode:o}=e;this._cursorChange=t===w.DeviceInputEventType.PointerDown||t===w.DeviceInputEventType.Dblclick?2:1;const i=this._editorBridgeService.getEditLocation();if(i==null)return;this._commandService.syncExecuteCommand(_s.id,{range:{startRow:i.row,startColumn:i.column,endRow:i.row,endColumn:i.column}}),this._editorBridgeService.refreshEditCellPosition(!1);const{unitId:s,isInArrayFormulaRange:l=!1}=i,c=this._getEditorObject();if(c==null)return;const{document:d,scene:u}=c;this._contextService.setContextValue(a.EDITOR_ACTIVATED,!0);const h=this._getDocumentDataModel(),g=this._getEditorSkeleton(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY);if(!(!g||!h)){if(this._sheetCellEditorResizeService.fitTextSize(()=>{const v=u.getViewport($.VIEWPORT_KEY.VIEW_MAIN);v==null||v.scrollToViewportPos({viewportScrollX:Number.POSITIVE_INFINITY,viewportScrollY:Number.POSITIVE_INFINITY})}),t===w.DeviceInputEventType.Keyboard&&o===I.KeyCode.F2){d.makeDirty(),this._textSelectionManagerService.replaceDocRanges([{startOffset:0,endOffset:0}]);const v=((f=(S=h.getBody())==null?void 0:S.dataStream.length)!=null?f:2)-2;this._textSelectionManagerService.replaceDocRanges([{startOffset:v,endOffset:v}],{unitId:a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY,subUnitId:a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY})}else if(t===w.DeviceInputEventType.Keyboard||t===w.DeviceInputEventType.Dblclick&&l)this._emptyDocumentDataModel(h.getSnapshot().documentStyle,!!l),d.makeDirty(),(o===I.KeyCode.BACKSPACE||t===w.DeviceInputEventType.Dblclick)&&(g.calculate(),this._editorBridgeService.changeEditorDirty(!0)),this._textSelectionManagerService.replaceDocRanges([{startOffset:0,endOffset:0}],{unitId:a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY,subUnitId:a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY});else if(t===w.DeviceInputEventType.Dblclick){if(this._contextService.getContextValue(a.FOCUSING_EDITOR_INPUT_FORMULA))return;const v=h.getBody().dataStream.length-2||0;this._textSelectionManagerService.replaceDocRanges([{startOffset:v,endOffset:v}])}(p=this._renderManagerService.getRenderById(s))==null||p.scene.resetCursor()}}async _handleEditorInvisible(e){const t=this._editorBridgeService.getEditCellState(),o=this._univerInstanceService.getUnit(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY),i=a.Tools.deepClone(o==null?void 0:o.getSnapshot());let{keycode:s}=e;if(this._cursorChange=0,this._exitInput(e),t==null)return;this._editorBridgeService.getEditorDirty()===!1&&(s=I.KeyCode.ESC);const d=this._context.unit.getActiveSheet(),u=this._context.unitId,h=d.getSheetId(),{unitId:g,sheetId:S}=t;if(u===g&&S!==h&&await this._commandService.executeCommand(m.SetWorksheetActivateCommand.id,{subUnitId:S,unitId:g}),s===I.KeyCode.ESC){this._editorBridgeService.isForceKeepVisible()&&this._editorBridgeService.disableForceKeepVisible();const f=this._workbookSelections.getCurrentSelections();f&&(this._contextService.setContextValue(m.REF_SELECTIONS_ENABLED,!1),this._commandService.syncExecuteCommand(m.SetSelectionsOperation.id,{unitId:this._context.unit.getUnitId(),subUnitId:S,selections:f}));return}i&&await this._submitCellData(i),this._moveCursor(s)}_getEditorObject(){return Pr(this._editorBridgeService.getCurrentEditorId(),this._renderManagerService)}submitCellData(e){return this._submitCellData(e.getSnapshot())}async _submitCellData(e){const t=this._editorBridgeService.getEditCellState();if(t==null)return;const{unitId:o,sheetId:i,row:s,column:l}=t,c=this._context.unit;let d=c.getActiveSheet();if(!c.getSheetBySheetId(i))return;d=c.getActiveSheet();const h=qu({...d.getCellRaw(s,l)||{}},e,this._lexerTreeBuilder,this._localService,this._functionService,c.getStyles());if(!h)return;const g=await this._sheetInterceptorService.onWriteCell(c,d,s,l,h);g!==d.getCellRaw(s,l)&&this._commandService.executeCommand(m.SetRangeValuesCommand.id,{subUnitId:i,unitId:o,range:{startRow:s,startColumn:l,endRow:s,endColumn:l},value:g})}_exitInput(e){var i;this._contextService.setContextValue(a.FOCUSING_EDITOR_INPUT_FORMULA,!1),this._contextService.setContextValue(a.EDITOR_ACTIVATED,!1),this._contextService.setContextValue(a.FOCUSING_EDITOR_BUT_HIDDEN,!1),this._contextService.setContextValue(a.FOCUSING_FX_BAR_EDITOR,!1),this._cellEditorManagerService.setState({show:e.visible});const t=this._getEditorObject();(i=t==null?void 0:t.scene.getViewport($.VIEWPORT_KEY.VIEW_MAIN))==null||i.scrollToViewportPos({viewportScrollX:0,viewportScrollY:0});const o=this._editorBridgeService.getCurrentEditorId();o==null||!this._editorService.isSheetEditor(o)||(this._undoRedoService.clearUndoRedo(o),this._undoRedoService.clearUndoRedo(a.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY))}_moveCursor(e){if(e==null||!Hu.includes(e))return;let t=a.Direction.LEFT;switch(e){case I.KeyCode.ENTER:t=a.Direction.DOWN;break;case I.KeyCode.TAB:t=a.Direction.RIGHT;break;case I.KeyCode.ARROW_DOWN:t=a.Direction.DOWN;break;case I.KeyCode.ARROW_UP:t=a.Direction.UP;break;case I.KeyCode.ARROW_LEFT:t=a.Direction.LEFT;break;case I.KeyCode.ARROW_RIGHT:t=a.Direction.RIGHT;break}e===I.KeyCode.ENTER||e===I.KeyCode.TAB?this._commandService.executeCommand($e.id,{keycode:e,direction:t}):this._commandService.executeCommand(xe.id,{direction:t})}_cursorStateListener(e){const t=this._getEditorObject();if(!(t!=null&&t.document))return;const{document:o}=t;e.add(a.toDisposable(o.onPointerDown$.subscribeEvent(()=>{this._cursorChange===1&&(this._cursorChange=2)})))}_moveInEditor(e,t){let o=a.Direction.LEFT;e===I.KeyCode.ARROW_DOWN?o=a.Direction.DOWN:e===I.KeyCode.ARROW_UP?o=a.Direction.UP:e===I.KeyCode.ARROW_RIGHT&&(o=a.Direction.RIGHT),t?this._commandService.executeCommand($.MoveSelectionOperation.id,{direction:o}):this._commandService.executeCommand($.MoveCursorOperation.id,{direction:o})}_getDocumentDataModel(){return this._univerInstanceService.getUnit(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY,a.UniverInstanceType.UNIVER_DOC)}_isCurrentSheetFocused(){var e;return((e=this._univerInstanceService.getFocusedUnit())==null?void 0:e.getUnitId())===this._context.unitId}_getEditorSkeleton(e){var t;return(t=this._renderManagerService.getRenderById(e))==null?void 0:t.with(Re.DocSkeletonManagerService).getSkeleton()}_getEditorViewModel(e){var t;return(t=this._renderManagerService.getRenderById(e))==null?void 0:t.with(Re.DocSkeletonManagerService).getViewModel()}_emptyDocumentDataModel(e,t){const o=(l,c)=>{const d=a.Tools.deepClone(l.getSnapshot()),u=this._getEditorViewModel(l.getUnitId());u!=null&&(Qu(d.body,t),c&&(d.documentStyle=e),d.drawings={},d.drawingsOrder=[],l.reset(d),u.reset(l))},i=this._getDocumentDataModel();i&&o(i,!0);const s=this._univerInstanceService.getUnit(a.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,a.UniverInstanceType.UNIVER_DOC);s&&o(s)}};exports.EditingRenderController=Ku([ye(1,a.Inject(m.SheetsSelectionsService)),ye(2,a.IUndoRedoService),ye(3,a.IContextService),ye(4,w.IRenderManagerService),ye(5,Se),ye(6,go),ye(7,a.Inject(K.LexerTreeBuilder)),ye(8,K.IFunctionService),ye(9,a.Inject(Re.DocSelectionManagerService)),ye(10,a.ICommandService),ye(11,a.Inject(a.LocaleService)),ye(12,$.IEditorService),ye(13,a.Inject(exports.SheetCellEditorResizeService)),ye(14,a.IUniverInstanceService),ye(15,a.Inject(m.SheetInterceptorService))],exports.EditingRenderController);function qu(n,r,e,t,o,i){var h,g,S;if((r==null?void 0:r.body)==null)return null;const{body:s}=r;n.t=void 0;const l=s.dataStream;let d=l.substring(l.length-2,l.length)===a.DEFAULT_EMPTY_DOCUMENT_VALUE?l.substring(0,l.length-2):l;const u=t.getCurrentLocale();if(d=Bu(d,e,u,o),(h=r.drawingsOrder)!=null&&h.length)n.v="",n.f=null,n.si=null,n.p=r,n.t=a.CellValueType.STRING;else if(n.s&&Id.isTextFormat((S=(g=i==null?void 0:i.get(n.s))==null?void 0:g.n)==null?void 0:S.pattern)){n.v=d,n.f=null,n.si=null,n.p=null,n.t=a.CellValueType.STRING,zi(s)&&s.dataStream!==`\r
1
+ "use strict";var vd=Object.defineProperty;var Cd=(n,r,e)=>r in n?vd(n,r,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[r]=e;var E=(n,r,e)=>Cd(n,typeof r!="symbol"?r+"":r,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const $=require("@univerjs/docs-ui"),a=require("@univerjs/core"),w=require("@univerjs/engine-render"),I=require("@univerjs/ui"),V=require("react"),O=require("rxjs"),m=require("@univerjs/sheets"),Re=require("@univerjs/docs"),K=require("@univerjs/engine-formula"),Id=require("@univerjs/engine-numfmt"),Z=require("@univerjs/design"),_=require("react/jsx-runtime"),_d=require("@univerjs/telemetry"),Ka=require("rxjs/operators");function Pr(n,r){if(n==null)return;const e=r.getRenderById(n);if(e==null)return;const{mainComponent:t,scene:o,engine:i,components:s}=e,l=t,c=s.get($.DOCS_VIEW_KEY.BACKGROUND);return{document:l,docBackground:c,scene:o,engine:i}}const Di=[10,400],us="RANGE_SELECTOR_COMPONENT_KEY",Or="EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY";var me=(n=>(n.MAIN="__SpreadsheetRender__",n.ROW="__SpreadsheetRowHeader__",n.COLUMN="__SpreadsheetColumnHeader__",n.LEFT_TOP="__SpreadsheetLeftTopPlaceholder__",n))(me||{});const zs=0,tr=1,_t=10,bd=11,Xs=12,xr={id:"sheet.command.set-row-header-width",type:a.CommandType.COMMAND,handler:async(n,r)=>{if(!r)return!1;const e=n.get(w.IRenderManagerService);if(!e)return!1;const{unitId:t,subUnitId:o,size:i}=r,s=e.getRenderById(t);if(s){e.getRenderById(t).with(exports.SheetSkeletonManagerService).setRowHeaderSize(s,o,i);const{components:c}=s,d=c.get(me.ROW);d&&d.setCustomHeader({headerStyle:{size:i}})}return!0}},Ar={id:"sheet.command.set-col-header-height",type:a.CommandType.COMMAND,handler:async(n,r)=>{if(!r)return!1;const e=n.get(w.IRenderManagerService);if(!e)return!1;const{unitId:t,subUnitId:o,size:i}=r,s=e.getRenderById(t);if(s){e.getRenderById(t).with(exports.SheetSkeletonManagerService).setColumnHeaderSize(s,o,i);const{components:c}=s,d=c.get(me.COLUMN);d&&d.setCustomHeader({headerStyle:{size:i}})}return!0}},Hi=a.createInterceptorKey("rangeMovePermissionCheck"),Vi=a.createInterceptorKey("rangeFillPermissionCheck");var hs=(n=>(n[n.FORMULA_EDITOR_SHOW=100]="FORMULA_EDITOR_SHOW",n[n.MARK_SELECTION=1e4]="MARK_SELECTION",n))(hs||{});function bt(n){const r=n.getCurrentTheme(),e=new a.ColorKit(r.primaryColor).setAlpha(.07).toRgbString();return{strokeWidth:1,stroke:r.primaryColor,fill:e,widgets:{},widgetSize:6,widgetStrokeWidth:1,widgetStroke:r.colorWhite,autofillSize:6,autofillStrokeWidth:1,autofillStroke:r.colorWhite,rowHeaderFill:e,rowHeaderStroke:r.primaryColor,rowHeaderStrokeWidth:1,columnHeaderFill:e,columnHeaderStroke:r.primaryColor,columnHeaderStrokeWidth:1,expandCornerSize:40}}class Rd{constructor(){E(this,"_startColumn",-1);E(this,"_startRow",-1);E(this,"_endColumn",-1);E(this,"_endRow",-1);E(this,"_startX",0);E(this,"_startY",0);E(this,"_endX",0);E(this,"_endY",0);E(this,"_primary");E(this,"_rangeType",a.RANGE_TYPE.NORMAL)}get startColumn(){return this._startColumn}get startRow(){return this._startRow}get endColumn(){return this._endColumn}get endRow(){return this._endRow}get startX(){return this._startX}get startY(){return this._startY}get endX(){return this._endX}get endY(){return this._endY}get currentCell(){return this._primary}get rangeType(){return this._rangeType}isEqual(r){const{startColumn:e,startRow:t,endColumn:o,endRow:i}=this,{startColumn:s,startRow:l,endColumn:c,endRow:d}=r;return e===s&&t===l&&o===c&&i===d}isInclude(r){const{startColumn:e,startRow:t,endColumn:o,endRow:i}=this,{startColumn:s,startRow:l,endColumn:c,endRow:d}=r;return!(c<e||s>o||l>i||d<t)}highlightToSelection(){if(this._primary)return a.convertCellToRange(this._primary)}getRange(){return{startColumn:this._startColumn,startRow:this._startRow,endColumn:this._endColumn,endRow:this._endRow,startX:this._startX,startY:this._startY,endX:this._endX,endY:this._endY,rangeType:this.rangeType}}getCell(){return this._primary}getRangeType(){return this._rangeType}setRangeType(r){this._rangeType=r}getValue(){return{rangeWithCoord:this.getRange(),primaryWithCoord:this._primary}}setValue(r,e){const{startColumn:t,startRow:o,endColumn:i,endRow:s,startX:l,startY:c,endX:d,endY:u,rangeType:h}=r;this._startColumn=t,this._startRow=o,this._endColumn=i,this._endRow=s,this._startX=l,this._startY=c,this._endX=d,this._endY=u,h!==void 0&&(this._rangeType=h),e!==void 0&&this.setCurrentCell(e)}setCurrentCell(r){this._primary=r}clearCurrentCell(){this._primary=null}}function bn(n,r){const{startRow:e,startColumn:t,endRow:o,endColumn:i,rangeType:s}=r,l=o<e?o:e,c=o<e?e:o,d=i<t?i:t,u=i<t?t:i,h=n.getNoMergeCellWithCoordByIndex(l,d),g=n.getNoMergeCellWithCoordByIndex(c,u);return{startRow:e,startColumn:t,endRow:o,endColumn:i,rangeType:s,startY:(h==null?void 0:h.startY)||0,endY:(g==null?void 0:g.endY)||0,startX:(h==null?void 0:h.startX)||0,endX:(g==null?void 0:g.endX)||0}}function Me(n,r){const{range:e,primary:t,style:o}=n,i=bn(r,e),s=t&&$n(r,t);return{rangeWithCoord:i,primaryWithCoord:s,style:o}}function $n(n,r){const{actualRow:e,actualColumn:t,isMerged:o,isMergedMainCell:i,startRow:s,startColumn:l,endRow:c,endColumn:d}=r,u=n.getNoMergeCellWithCoordByIndex(e,t),h=n.getNoMergeCellWithCoordByIndex(s,l),g=n.getNoMergeCellWithCoordByIndex(c,d);return{actualRow:e,actualColumn:t,isMerged:o,isMergedMainCell:i,startX:u.startX,startY:u.startY,endX:u.endX,endY:u.endY,mergeInfo:{startRow:s,startColumn:l,endRow:c,endColumn:d,startY:(h==null?void 0:h.startY)||0,endY:(g==null?void 0:g.endY)||0,startX:(h==null?void 0:h.startX)||0,endX:(g==null?void 0:g.endX)||0}}}const Ys="__SpreadsheetHelperSelectionTempRect",Ed=35;class qa{constructor(r,e){E(this,"_startOffsetX",0);E(this,"_startOffsetY",0);E(this,"_relativeSelectionPositionRow",0);E(this,"_relativeSelectionPositionColumn",0);E(this,"_relativeSelectionRowLength",0);E(this,"_relativeSelectionColumnLength",0);E(this,"_scenePointerMoveSub");E(this,"_scenePointerUpSub");E(this,"_helperSelection");E(this,"_scrollTimer");E(this,"_activeViewport");E(this,"_targetSelection",{startY:0,endY:0,startX:0,endX:0,startRow:-1,endRow:-1,startColumn:-1,endColumn:-1});E(this,"_isInMergeState",!1);E(this,"_fillControlColors",[]);E(this,"_skeleton");E(this,"_scene");E(this,"_themeService");E(this,"_injector");E(this,"_selectionHooks");this._control=r,this._skeleton=e.skeleton,this._scene=e.scene,this._themeService=e.themeService,this._injector=e.injector,this._selectionHooks=e.selectionHooks,this._initialControl(),this._initialWidget(),this._initialAutoFill(),this._control.dispose$.subscribe(()=>{this.dispose()})}get isHelperSelection(){return this._control.isHelperSelection}dispose(){var r,e;(r=this._scrollTimer)==null||r.dispose(),this._fillControlColors=[],this._clearObserverEvent(),(e=this._helperSelection)==null||e.dispose()}_getFreeze(){var t,o;return(o=(t=this._injector.get(w.IRenderManagerService).withCurrentTypeOfUnit(a.UniverInstanceType.UNIVER_SHEET,exports.SheetSkeletonManagerService))==null?void 0:t.getCurrentParam())==null?void 0:o.skeleton.getWorksheetConfig().freeze}_isSelectionInViewport(r,e){const t=this._getFreeze()||{startRow:-1,startColumn:-1};switch(e.viewportKey){case w.SHEET_VIEWPORT_KEY.VIEW_MAIN:return r.endRow>=t.startRow&&r.endColumn>=t.startColumn;case w.SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP:case w.SHEET_VIEWPORT_KEY.VIEW_COLUMN_RIGHT:return r.endColumn>=t.startColumn&&r.startRow<t.startRow;case w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT:case w.SHEET_VIEWPORT_KEY.VIEW_ROW_BOTTOM:return r.endRow>=t.startRow&&r.startColumn<t.startColumn;case w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP:case w.SHEET_VIEWPORT_KEY.VIEW_COLUMN_LEFT:case w.SHEET_VIEWPORT_KEY.VIEW_ROW_TOP:case w.SHEET_VIEWPORT_KEY.VIEW_LEFT_TOP:return r.startRow<t.startRow&&r.startColumn<t.startColumn}}_clearObserverEvent(){var r,e;(r=this._scenePointerMoveSub)==null||r.unsubscribe(),(e=this._scenePointerUpSub)==null||e.unsubscribe(),this._scenePointerMoveSub=null,this._scenePointerUpSub=null}_initialControl(){const{leftControl:r,rightControl:e,topControl:t,bottomControl:o}=this._control;[r,e,t,o].forEach(i=>{i.onPointerEnter$.subscribeEvent(()=>{var l;((l=this._injector.get(ve,a.Quantity.OPTIONAL))==null?void 0:l.interceptor.fetchThroughInterceptors(Hi)(!1,null))!==!1&&i.setCursor(w.CURSOR_TYPE.MOVE)}),i.onPointerLeave$.subscribeEvent(()=>{i.resetCursor()}),i.onPointerDown$.subscribeEvent(this._controlPointerDownHandler.bind(this))})}_controlMoving(r,e){var A;const t=this._scene,o=t.getScrollXYInfoByViewport(w.Vector2.FromArray([r,e])),{scaleX:i,scaleY:s}=t.getAncestorScale(),l=this._skeleton.getCellIndexByOffset(r,e,i,s,o),{row:c,column:d}=l,u=this._skeleton.getRowCount()-1,h=this._skeleton.getColumnCount()-1;let g=Math.max(0,c+this._relativeSelectionPositionRow),S=g+this._relativeSelectionRowLength;S>u&&(S=u,S-g<this._relativeSelectionRowLength&&(g=S-this._relativeSelectionRowLength));let f=Math.max(0,d+this._relativeSelectionPositionColumn),p=f+this._relativeSelectionColumnLength;p>h&&(p=h,p-f<this._relativeSelectionColumnLength&&(f=p-this._relativeSelectionColumnLength));const v=this._skeleton.worksheet.getCellInfoInMergeData(g,f),b=Me({range:{startRow:g,endRow:S,startColumn:f,endColumn:p},primary:v,style:null},this._skeleton),R=this._skeleton.getNoMergeCellWithCoordByIndex(g,f),T=this._skeleton.getNoMergeCellWithCoordByIndex(S,p),M=(R==null?void 0:R.startY)||0,y=(T==null?void 0:T.endY)||0,P=(R==null?void 0:R.startX)||0,x=(T==null?void 0:T.endX)||0;(A=this._helperSelection)==null||A.transformByState({left:P,top:M,width:x-P,height:y-M}),this._targetSelection={...b.rangeWithCoord},this._control.selectionMoving$.next(b.rangeWithCoord)}_controlPointerDownHandler(r){const{offsetX:e,offsetY:t}=r,o=this._scene,i=o.getCoordRelativeToViewport(w.Vector2.FromArray([e,t])),{x:s,y:l}=i,c=o.getScrollXYInfoByViewport(i),{scaleX:d,scaleY:u}=o.getAncestorScale(),h=this._skeleton.getCellIndexByOffset(s,l,d,u,c);this._startOffsetX=s,this._startOffsetY=l;const{row:g,column:S}=h,{startRow:f,startColumn:p,endRow:v,endColumn:C}=this._control.model;let b=0,R=0;g<f?b-=1:g>v&&(b+=1),S<p?R-=1:S>C&&(R+=1),this._relativeSelectionPositionRow=f-g+b,this._relativeSelectionPositionColumn=p-S+R,this._relativeSelectionRowLength=v-f,this._relativeSelectionColumnLength=C-p;const T=this._control.currentStyle,M=this._getScale();this.isHelperSelection&&(this._helperSelection=new w.Rect(Ys,{stroke:T.stroke,strokeWidth:T.strokeWidth/M}),o.addObject(this._helperSelection));const y=o.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN),P=w.ScrollTimer.create(o);this._scrollTimer=P,P.startScroll(s,l,y),o.disableObjectsEvent(),this._scenePointerMoveSub=o.onPointerMove$.subscribeEvent(x=>{var H;const{offsetX:A,offsetY:k}=x;if(((H=this._injector.get(ve,a.Quantity.OPTIONAL))==null?void 0:H.interceptor.fetchThroughInterceptors(Hi)(!1,null))===!1)return;const{x:D,y:W}=o.getCoordRelativeToViewport(w.Vector2.FromArray([A,k]));this._controlMoving(D,W),o.setCursor(w.CURSOR_TYPE.MOVE),P.scrolling(D,W,()=>{this._controlMoving(D,W)})}),this._scenePointerUpSub=o.onPointerUp$.subscribeEvent(()=>{var A,k,N,D;(A=this._helperSelection)==null||A.dispose();const x=this._scene;x.resetCursor(),this._clearObserverEvent(),x.enableObjectsEvent(),(k=this._scrollTimer)==null||k.dispose(),this._control.selectionMoveEnd$.next(this._targetSelection),(D=(N=this._selectionHooks).selectionMoveEnd)==null||D.call(N)})}_initialWidget(){const{topLeftWidget:r,topCenterWidget:e,topRightWidget:t,middleLeftWidget:o,middleRightWidget:i,bottomLeftWidget:s,bottomCenterWidget:l,bottomRightWidget:c}=this._control,d=[w.CURSOR_TYPE.NORTH_WEST_RESIZE,w.CURSOR_TYPE.NORTH_RESIZE,w.CURSOR_TYPE.NORTH_EAST_RESIZE,w.CURSOR_TYPE.WEST_RESIZE,w.CURSOR_TYPE.EAST_RESIZE,w.CURSOR_TYPE.SOUTH_WEST_RESIZE,w.CURSOR_TYPE.SOUTH_RESIZE,w.CURSOR_TYPE.SOUTH_EAST_RESIZE];[r,e,t,o,i,s,l,c].forEach((u,h)=>{u.onPointerEnter$.subscribeEvent(()=>{u.setCursor(d[h])}),u.onPointerLeave$.subscribeEvent(()=>{u.resetCursor()}),u.onPointerDown$.subscribeEvent(g=>{this._widgetPointerDownEvent(g,d[h])})})}_widgetPointerDownEvent(r,e){const t=this._scene,{offsetX:o,offsetY:i}=r,s=t.getCoordRelativeToViewport(w.Vector2.FromArray([o,i])),{x:l,y:c}=s;this._startOffsetX=o,this._startOffsetY=i;const{startRow:d,startColumn:u,endRow:h,endColumn:g}=this._control.model,S=Math.min(d,h),f=Math.min(u,g),p=Math.max(d,h),v=Math.max(u,g);this._relativeSelectionPositionRow=S,this._relativeSelectionPositionColumn=f,this._relativeSelectionRowLength=p-S,this._relativeSelectionColumnLength=v-f,e===w.CURSOR_TYPE.NORTH_WEST_RESIZE?(this._relativeSelectionPositionRow=p,this._relativeSelectionPositionColumn=v):e===w.CURSOR_TYPE.NORTH_RESIZE?this._relativeSelectionPositionRow=p:e===w.CURSOR_TYPE.NORTH_EAST_RESIZE?this._relativeSelectionPositionRow=p:e===w.CURSOR_TYPE.WEST_RESIZE?this._relativeSelectionPositionColumn=v:e===w.CURSOR_TYPE.SOUTH_WEST_RESIZE?this._relativeSelectionPositionColumn=v:e===w.CURSOR_TYPE.SOUTH_RESIZE&&(this._relativeSelectionPositionRow=S);const C=w.ScrollTimer.create(t),b=t.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN);C.startScroll(l,c,b),this._scrollTimer=C,t.disableObjectsEvent(),this._scenePointerMoveSub=t.onPointerMove$.subscribeEvent(R=>{const{offsetX:T,offsetY:M}=R,{x:y,y:P}=t.getCoordRelativeToViewport(w.Vector2.FromArray([T,M]));this._widgetMoving(y,P,e),t.setCursor(e),C.scrolling(y,P,()=>{this._widgetMoving(y,P,e)})}),this._scenePointerUpSub=t.onPointerUp$.subscribeEvent(()=>{var T,M,y;const R=this._scene;R.resetCursor(),this._clearObserverEvent(),R.enableObjectsEvent(),(T=this._scrollTimer)==null||T.dispose(),this._control.selectionScaled$.next(this._targetSelection),(y=(M=this._selectionHooks).selectionMoveEnd)==null||y.call(M)})}_widgetMoving(r,e,t){const o=this._scene,i=o.getScrollXYInfoByViewport(w.Vector2.FromArray([this._startOffsetX,this._startOffsetY])),{scaleX:s,scaleY:l}=o.getAncestorScale(),c=this._skeleton.getCellIndexByOffset(r,e,s,l,i),{row:d,column:u}=c;let h=this._relativeSelectionPositionRow,g=this._relativeSelectionPositionColumn,S=d,f=u;t===w.CURSOR_TYPE.NORTH_WEST_RESIZE?(h=d,g=u,S=this._relativeSelectionPositionRow,f=this._relativeSelectionPositionColumn):t===w.CURSOR_TYPE.NORTH_RESIZE?(h=d,g=this._relativeSelectionPositionColumn,S=this._relativeSelectionPositionRow,f=this._relativeSelectionPositionColumn+this._relativeSelectionColumnLength):t===w.CURSOR_TYPE.NORTH_EAST_RESIZE?(h=d,g=this._relativeSelectionPositionColumn,S=this._relativeSelectionPositionRow,f=u):t===w.CURSOR_TYPE.WEST_RESIZE?(h=this._relativeSelectionPositionRow,g=u,S=this._relativeSelectionPositionRow+this._relativeSelectionRowLength,f=this._relativeSelectionPositionColumn):t===w.CURSOR_TYPE.EAST_RESIZE?S=this._relativeSelectionPositionRow+this._relativeSelectionRowLength:t===w.CURSOR_TYPE.SOUTH_WEST_RESIZE?(h=this._relativeSelectionPositionRow,g=u,S=d,f=this._relativeSelectionPositionColumn):t===w.CURSOR_TYPE.SOUTH_RESIZE&&(h=this._relativeSelectionPositionRow,g=this._relativeSelectionPositionColumn,S=d,f=this._relativeSelectionPositionColumn+this._relativeSelectionColumnLength);const p=this._swapPositions(h,g,S,f),v=this._skeleton.getCellWithMergeInfoByIndex(h,g),b=Me({range:p,primary:v,style:null},this._skeleton);this._targetSelection={...b.rangeWithCoord},this._control.updateRangeBySelectionWithCoord(b),this._control.selectionScaling$.next(this._targetSelection)}_initialAutoFill(){const{fillControl:r}=this._control;r.onPointerEnter$.subscribeEvent(e=>{this._injector.get(ve).interceptor.fetchThroughInterceptors(Vi)(!1,{x:e.offsetX,y:e.offsetY,skeleton:this._skeleton,scene:this._scene})&&r.setCursor(w.CURSOR_TYPE.CROSSHAIR)}),r.onPointerLeave$.subscribeEvent(()=>{r.resetCursor()}),r.onPointerDown$.subscribeEvent(this._autoFillForPointerdown.bind(this))}_autoFillMoving(r,e){var k,N,D;const t=this._scene,o=t.getViewportScrollXY(this._activeViewport),{scaleX:i,scaleY:s}=t.getAncestorScale(),l=this._skeleton.getCellIndexByOffset(r,e,i,s,o),{row:c,column:d}=l,u=t.getCoordRelativeToViewport(w.Vector2.FromArray([r,e])),h=this._skeleton.getRowCount()-1,g=this._skeleton.getColumnCount()-1;let S=this._relativeSelectionPositionRow,f=this._relativeSelectionPositionColumn,p=this._relativeSelectionPositionRow+this._relativeSelectionRowLength,v=this._relativeSelectionPositionColumn+this._relativeSelectionColumnLength,C=!1,b=!0;if((d<f||d>v)&&c>=S&&c<=p){const W=this._fillRuler(d,f,v,this._relativeSelectionColumnLength,g);f=W.startRowOrColumn,v=W.endRowOrColumn,C=W.isLighten,b=!1}else if((c<S||c>p)&&d>=f&&d<=v){const W=this._fillRuler(c,S,p,this._relativeSelectionRowLength,h);S=W.startRowOrColumn,p=W.endRowOrColumn,C=W.isLighten}else if(Math.abs(this._startOffsetX-u.x-o.x)/2>Math.abs(this._startOffsetY-u.y-o.y)){const W=this._fillRuler(d,f,v,this._relativeSelectionColumnLength,g);f=W.startRowOrColumn,v=W.endRowOrColumn,C=W.isLighten,b=!1}else{const W=this._fillRuler(c,S,p,this._relativeSelectionRowLength,h);S=W.startRowOrColumn,p=W.endRowOrColumn,C=W.isLighten}const R=this._skeleton.getNoMergeCellWithCoordByIndex(S,f),T=this._skeleton.getNoMergeCellWithCoordByIndex(p,v),M=(R==null?void 0:R.startY)||0,y=(T==null?void 0:T.endY)||0,P=(R==null?void 0:R.startX)||0,x=(T==null?void 0:T.endX)||0;C?this._controlHandler((W,H)=>{const U=new a.ColorKit(this._fillControlColors[H]).lighten(Ed).toRgbString();W.setProps({fill:U})}):this._controlHandler((W,H)=>{W.setProps({fill:this._fillControlColors[H]})});const A=m.SELECTION_CONTROL_BORDER_BUFFER_WIDTH/this._getScale();S===p&&b===!0||f===v&&b===!1?(k=this._helperSelection)==null||k.hide():((N=this._helperSelection)==null||N.transformByState({left:P-A/2,top:M-A/2,width:x-P,height:y-M}),(D=this._helperSelection)==null||D.show()),this._targetSelection={startY:M,endY:y,startX:P,endX:x,startRow:S,endRow:p,startColumn:f,endColumn:v},this._control.selectionFilling$.next(this._targetSelection)}_autoFillForPointerdown(r){const{offsetX:e,offsetY:t}=r,o=this._scene,i=o.getCoordRelativeToViewport(w.Vector2.FromArray([e,t])),{x:s,y:l}=i;this._startOffsetX=s,this._startOffsetY=l;const{startRow:c,startColumn:d,endRow:u,endColumn:h}=this._control.model;this._isInMergeState=this._hasMergeInRange(c,d,u,h),this._relativeSelectionPositionRow=c,this._relativeSelectionPositionColumn=d,this._relativeSelectionRowLength=u-c,this._relativeSelectionColumnLength=h-d;const g=this._control.currentStyle;let S=g==null?void 0:g.stroke,f=g==null?void 0:g.strokeWidth;const p=bt(this._themeService);S==null&&(S=p.stroke),f==null&&(f=p.strokeWidth);const v=this._getScale();f/=v;const C=m.SELECTION_CONTROL_BORDER_BUFFER_WIDTH/v,b=new a.ColorKit(S).darken(2).toRgbString();this.isHelperSelection&&(this._helperSelection=new w.Rect(Ys,{stroke:b,strokeWidth:f+C/2}),o.addObject(this._helperSelection)),this._activeViewport=o.getActiveViewportByCoord(w.Vector2.FromArray([e,t]));const R=o.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN),T=w.ScrollTimer.create(o,this._activeViewport.viewportKey===w.SHEET_VIEWPORT_KEY.VIEW_MAIN?w.ScrollTimerType.ALL:w.ScrollTimerType.NONE);T.startScroll(s,l,R),this._scrollTimer=T,o.disableObjectsEvent(),this._controlHandler(M=>{this._fillControlColors.push(M.fill)}),this._scenePointerMoveSub=o.onPointerMove$.subscribeEvent(M=>{var W;const{offsetX:y,offsetY:P}=M,x=o.getActiveViewportByCoord(w.Vector2.FromArray([y,P]));if(!this._injector.get(ve).interceptor.fetchThroughInterceptors(Vi)(!1,{x:r.offsetX,y:r.offsetY,skeleton:this._skeleton,scene:this._scene}))return;const{x:k,y:N}=o.getCoordRelativeToViewport(w.Vector2.FromArray([y,P]));this._autoFillMoving(k,N),o.setCursor(w.CURSOR_TYPE.CROSSHAIR);const D=this._targetSelection;if(R&&x&&((W=this._activeViewport)==null?void 0:W.viewportKey)!==(x==null?void 0:x.viewportKey)){let H;D.startRow!==c?(T.scrollTimerType=w.ScrollTimerType.Y,H={...D,endRow:D.startRow}):D.endRow!==u?(T.scrollTimerType=w.ScrollTimerType.Y,H={...D,startRow:D.endRow}):D.startColumn!==d?(T.scrollTimerType=w.ScrollTimerType.X,H={...D,endColumn:D.startColumn}):(T.scrollTimerType=w.ScrollTimerType.X,H={...D,startColumn:D.endColumn}),this._isSelectionInViewport(H,x)&&(R.scrollToBarPos({x:T.scrollTimerType===w.ScrollTimerType.X?0:void 0,y:T.scrollTimerType===w.ScrollTimerType.Y?0:void 0}),this._activeViewport=x)}T.scrolling(k,N,()=>{this._autoFillMoving(k,N)})}),this._scenePointerUpSub=o.onPointerUp$.subscribeEvent(()=>{var y,P;(y=this._helperSelection)==null||y.dispose();const M=this._scene;M.resetCursor(),this._clearObserverEvent(),M.enableObjectsEvent(),(P=this._scrollTimer)==null||P.dispose(),this._control.refreshSelectionFilled(this._targetSelection),this._isInMergeState=!1,this._controlHandler((x,A)=>{x.setProps({fill:this._fillControlColors[A]})}),this._fillControlColors=[]})}_hasMergeInRange(r,e,t,o){return this._skeleton.worksheet.getMergedCellRange(r,e,t,o).length>0}_swapPositions(r,e,t,o){const i=Math.min(r,t),s=Math.min(e,o),l=Math.max(r,t),c=Math.max(e,o);return{startRow:i,startColumn:s,endRow:l,endColumn:c}}_controlHandler(r){const{leftControl:e,rightControl:t,topControl:o,bottomControl:i,backgroundControlTop:s,backgroundControlMiddleLeft:l,backgroundControlMiddleRight:c,backgroundControlBottom:d,fillControl:u}=this._control,h=[e,t,o,i,s,l,c,d,u];for(let g=0,S=h.length;g<S;g++){const f=h[g];r(f,g)}}_fillRuler(r,e,t,o,i){let s=!1;if(r<e)if(this._isInMergeState&&r<e){const l=e-r,c=o+1,d=Math.ceil(l/c);let u=e-d*c;u<0&&(u=e-(d-1)*c),e=u}else e=r;else if(r>=e&&r<=t)s=!0,this._isInMergeState||(t=r);else if(this._isInMergeState&&r>t){const l=r-t,c=o+1,d=Math.ceil(l/c);let u=t+d*c;u>i&&(u=t+(d-1)*c),t=u}else t=r;return{rowOrColumn:r,startRowOrColumn:e,endRowOrColumn:t,isLighten:s}}_getScale(){const{scaleX:r,scaleY:e}=this._scene.getAncestorScale();return Math.max(r,e)}}var Wi=(n=>(n.Selection="__SpreadsheetSelectionShape__",n.top="__SpreadsheetSelectionTopControl__",n.bottom="__SpreadsheetSelectionBottomControl__",n.left="__SpreadsheetSelectionShapeLeftControl__",n.right="__SpreadsheetSelectionShapeRightControl__",n.backgroundTop="__SpreadsheetSelectionBackgroundControlTop__",n.backgroundMiddleLeft="__SpreadsheetSelectionBackgroundControlMiddleLeft__",n.backgroundMiddleRight="__SpreadsheetSelectionBackgroundControlMiddleRight__",n.backgroundBottom="__SpreadsheetSelectionBackgroundControlBottom__",n.fill="__SpreadsheetSelectionFillControl__",n.fillTopLeft="__SpreadsheetSelectionFillControlTopLeft__",n.fillBottomRight="__SpreadsheetSelectionFillControlBottomRight__",n.fillTopLeftInner="__SpreadsheetSelectionFillControlTopLeftInner__",n.fillBottomRightInner="__SpreadsheetSelectionFillControlBottomRightInner__",n.lineMain="__SpreadsheetDragLineMainControl__",n.lineContent="__SpreadsheetDragLineContentControl__",n.line="__SpreadsheetDragLineControl__",n.dash="__SpreadsheetDragDashControl__",n.rowHeaderBackground="__SpreadSheetSelectionRowHeaderBackground__",n.rowHeaderBorder="__SpreadSheetSelectionRowHeaderBorder__",n.rowHeaderGroup="__SpreadSheetSelectionRowHeaderGroup__",n.columnHeaderBackground="__SpreadSheetSelectionColumnHeaderBackground__",n.columnHeaderBorder="__SpreadSheetSelectionColumnHeaderBorder__",n.columnHeaderGroup="__SpreadSheetSelectionColumnHeaderGroup__",n.topLeftWidget="__SpreadSheetSelectionTopLeftWidget__",n.topCenterWidget="__SpreadSheetSelectionTopCenterWidget__",n.topRightWidget="__SpreadSheetSelectionTopRightWidget__",n.middleLeftWidget="__SpreadSheetSelectionMiddleLeftWidget__",n.middleRightWidget="__SpreadSheetSelectionMiddleRightWidget__",n.bottomLeftWidget="__SpreadSheetSelectionBottomLeftWidget__",n.bottomCenterWidget="__SpreadSheetSelectionBottomCenterWidget__",n.bottomRightWidget="__SpreadSheetSelectionBottomRightWidget__",n))(Wi||{});const Gs=.3;class co extends a.Disposable{constructor(e,t,o,i){var s,l,c,d;super();E(this,"_isHelperSelection",!0);E(this,"_enableAutoFill",!0);E(this,"_showAutoFill",!1);E(this,"_highlightHeader",!0);E(this,"_selectionRenderModel");E(this,"_leftBorder");E(this,"_rightBorder");E(this,"_topBorder");E(this,"_bottomBorder");E(this,"_backgroundControlTop");E(this,"_backgroundControlBottom");E(this,"_backgroundControlMiddleLeft");E(this,"_backgroundControlMiddleRight");E(this,"_autoFillControl");E(this,"_selectionShapeGroup");E(this,"_rowHeaderBackground");E(this,"_rowHeaderBorder");E(this,"_rowHeaderGroup");E(this,"_columnHeaderBackground");E(this,"_columnHeaderBorder");E(this,"_columnHeaderGroup");E(this,"_dashedRect");E(this,"_topLeftWidget");E(this,"_topCenterWidget");E(this,"_topRightWidget");E(this,"_middleLeftWidget");E(this,"_middleRightWidget");E(this,"_bottomLeftWidget");E(this,"_bottomCenterWidget");E(this,"_bottomRightWidget");E(this,"_defaultStyle");E(this,"_currentStyle");E(this,"_rowHeaderWidth",0);E(this,"_columnHeaderHeight",0);E(this,"_widgetRects",[]);E(this,"_controlExtension");E(this,"_dispose$",new O.BehaviorSubject(this));E(this,"dispose$",this._dispose$.asObservable());E(this,"selectionMoving$",new O.Subject);E(this,"selectionMoveEnd$",new O.Subject);E(this,"selectionScaling$",new O.Subject);E(this,"selectionScaled$",new O.Subject);E(this,"selectionFilling$",new O.Subject);E(this,"_selectionFilled$",new O.Subject);E(this,"selectionFilled$",this._selectionFilled$.asObservable());E(this,"_antLineOffset",0);E(this,"_antRequestNewFrame",-1);this._scene=e,this._zIndex=t,this._themeService=o,this._enableAutoFill=(s=i==null?void 0:i.enableAutoFill)!=null?s:!0,this._highlightHeader=(l=i==null?void 0:i.highlightHeader)!=null?l:!0,this._rowHeaderWidth=(c=i==null?void 0:i.rowHeaderWidth)!=null?c:0,this._columnHeaderHeight=(d=i==null?void 0:i.columnHeaderHeight)!=null?d:0,this._initializeSheetBody(),this._initialHeader()}_initializeSheetBody(){this._defaultStyle=bt(this._themeService),this._currentStyle=bt(this._themeService),this._selectionRenderModel=new Rd;const e=this._zIndex;this._leftBorder=new w.Rect("__SpreadsheetSelectionShapeLeftControl__"+e,{zIndex:e}),this._rightBorder=new w.Rect("__SpreadsheetSelectionShapeRightControl__"+e,{zIndex:e}),this._topBorder=new w.Rect("__SpreadsheetSelectionTopControl__"+e,{zIndex:e}),this._bottomBorder=new w.Rect("__SpreadsheetSelectionBottomControl__"+e,{zIndex:e}),this._backgroundControlTop=new w.Rect("__SpreadsheetSelectionBackgroundControlTop__"+e,{zIndex:e-1,evented:!1}),this._backgroundControlBottom=new w.Rect("__SpreadsheetSelectionBackgroundControlBottom__"+e,{zIndex:e-1,evented:!1}),this._backgroundControlMiddleLeft=new w.Rect("__SpreadsheetSelectionBackgroundControlMiddleLeft__"+e,{zIndex:e-1,evented:!1}),this._backgroundControlMiddleRight=new w.Rect("__SpreadsheetSelectionBackgroundControlMiddleRight__"+e,{zIndex:e-1,evented:!1}),this._autoFillControl=new w.Rect("__SpreadsheetSelectionFillControl__"+e,{zIndex:e+1}),this._autoFillControl.hide(),this._dashedRect=new w.DashedRect("__SpreadsheetDragDashControl__"+e,{zIndex:e+2,evented:!1,stroke:"#fff"});const t=[this._autoFillControl,this._leftBorder,this._rightBorder,this._topBorder,this._bottomBorder,this._backgroundControlTop,this._backgroundControlMiddleLeft,this._backgroundControlMiddleRight,this._backgroundControlBottom,this._dashedRect];this._widgetRects=this._initialWidget(),this._selectionShapeGroup=new w.Group("__SpreadsheetSelectionShape__"+e,...t,...this._widgetRects),this._selectionShapeGroup.hide(),this._selectionShapeGroup.evented=!1,this._selectionShapeGroup.zIndex=e;const o=this.getScene();o.addObject(this._selectionShapeGroup,tr),this.disposeWithMe(a.toDisposable(o.onTransformChange$.subscribeEvent(i=>{i.type===w.TRANSFORM_CHANGE_OBSERVABLE_TYPE.scale&&(this._updateLayoutOfSelectionControl(this._currentStyle),this._updateControlCoord())})))}_initialHeader(){const e=this._zIndex;this._rowHeaderBackground=new w.Rect("__SpreadSheetSelectionRowHeaderBackground__"+e,{zIndex:e-1,evented:!1}),this._rowHeaderBorder=new w.Rect("__SpreadSheetSelectionRowHeaderBorder__"+e,{zIndex:e-1,evented:!1}),this._rowHeaderGroup=new w.Group("__SpreadSheetSelectionRowHeaderGroup__"+e,this._rowHeaderBackground,this._rowHeaderBorder),this._rowHeaderGroup.hide(),this._rowHeaderGroup.evented=!1,this._rowHeaderGroup.zIndex=e,this._columnHeaderBackground=new w.Rect("__SpreadSheetSelectionColumnHeaderBackground__"+e,{zIndex:e-1,evented:!1}),this._columnHeaderBorder=new w.Rect("__SpreadSheetSelectionColumnHeaderBorder__"+e,{zIndex:e-1,evented:!1}),this._columnHeaderGroup=new w.Group("__SpreadSheetSelectionColumnHeaderGroup__"+e,this._columnHeaderBackground,this._columnHeaderBorder),this._columnHeaderGroup.hide(),this._columnHeaderGroup.evented=!1,this._columnHeaderGroup.zIndex=e,this.getScene().addObjects([this._rowHeaderGroup,this._columnHeaderGroup],bd)}_initialWidget(){const e=this._zIndex;return this._topLeftWidget=new w.Rect("__SpreadSheetSelectionTopLeftWidget__"+e,{zIndex:e+1}),this._topCenterWidget=new w.Rect("__SpreadSheetSelectionTopCenterWidget__"+e,{zIndex:e+1}),this._topRightWidget=new w.Rect("__SpreadSheetSelectionTopRightWidget__"+e,{zIndex:e+1}),this._middleLeftWidget=new w.Rect("__SpreadSheetSelectionMiddleLeftWidget__"+e,{zIndex:e+1}),this._middleRightWidget=new w.Rect("__SpreadSheetSelectionMiddleRightWidget__"+e,{zIndex:e+1}),this._bottomLeftWidget=new w.Rect("__SpreadSheetSelectionBottomLeftWidget__"+e,{zIndex:e+1}),this._bottomCenterWidget=new w.Rect("__SpreadSheetSelectionBottomCenterWidget__"+e,{zIndex:e+1}),this._bottomRightWidget=new w.Rect("__SpreadSheetSelectionBottomRightWidget__"+e,{zIndex:e+1}),[this._topLeftWidget,this._topCenterWidget,this._topRightWidget,this._middleLeftWidget,this._middleRightWidget,this._bottomLeftWidget,this._bottomCenterWidget,this._bottomRightWidget]}get zIndex(){return this._zIndex}get leftControl(){return this._leftBorder}get rightControl(){return this._rightBorder}get topControl(){return this._topBorder}get bottomControl(){return this._bottomBorder}get fillControl(){return this._autoFillControl}get backgroundControlTop(){return this._backgroundControlTop}get backgroundControlBottom(){return this._backgroundControlBottom}get backgroundControlMiddleLeft(){return this._backgroundControlMiddleLeft}get backgroundControlMiddleRight(){return this._backgroundControlMiddleRight}get selectionShape(){return this._selectionShapeGroup}get columnHeaderGroup(){return this._columnHeaderGroup}get rowHeaderGroup(){return this._rowHeaderGroup}get selectionShapeGroup(){return this._selectionShapeGroup}get model(){return this._selectionRenderModel}get topLeftWidget(){return this._topLeftWidget}get topCenterWidget(){return this._topCenterWidget}get topRightWidget(){return this._topRightWidget}get middleLeftWidget(){return this._middleLeftWidget}get middleRightWidget(){return this._middleRightWidget}get bottomLeftWidget(){return this._bottomLeftWidget}get bottomCenterWidget(){return this._bottomCenterWidget}get bottomRightWidget(){return this._bottomRightWidget}get themeService(){return this._themeService}get selectionModel(){return this._selectionRenderModel}set selectionModel(e){this._selectionRenderModel=e}get currentStyle(){return this._currentStyle}set currentStyle(e){this._currentStyle=e}get dashedRect(){return this._dashedRect}get isHelperSelection(){return this._isHelperSelection}get rowHeaderWidth(){return this._rowHeaderWidth}set rowHeaderWidth(e){this._rowHeaderWidth=e}get columnHeaderHeight(){return this._columnHeaderHeight}set columnHeaderHeight(e){this._columnHeaderHeight=e}setControlExtension(e){this._controlExtension=new qa(this,e)}setEvent(e){this.leftControl.evented=e,this.rightControl.evented=e,this.topControl.evented=e,this.bottomControl.evented=e}refreshSelectionFilled(e){this._selectionFilled$.next(e)}_updateLayoutOfSelectionControl(e){e&&(this.currentStyle=Object.assign({},this._defaultStyle,e));const t=this.currentStyle,{stroke:o,widgets:i,autofillStroke:s,strokeDash:l,isAnimationDash:c}=t;let d=t.autofillSize,u=t.strokeWidth,h=t.autofillStrokeWidth;const g=this._getScale(),S=(u+m.SELECTION_CONTROL_BORDER_BUFFER_WIDTH)/2/g;u/=g,d/=g,h/=g<1?1:g;const f=m.SELECTION_CONTROL_BORDER_BUFFER_WIDTH/g,p=w.FIX_ONE_PIXEL_BLUR_OFFSET/g,{startX:v,startY:C,endX:b,endY:R}=this._selectionRenderModel;if(this.leftControl.transformByState({height:R-C,left:-S+p,width:u,strokeWidth:f,top:-f/2+p}),this.leftControl.setProps({fill:o,stroke:m.SELECTION_CONTROL_BORDER_BUFFER_COLOR}),this.rightControl.transformByState({height:R-C,left:b-v-S+p,width:u,strokeWidth:f,top:-f/2+p}),this.rightControl.setProps({fill:o,stroke:m.SELECTION_CONTROL_BORDER_BUFFER_COLOR}),this.topControl.transformByState({width:b-v+u,top:-S+p,left:-S+p,height:u,strokeWidth:f}),this.topControl.setProps({fill:o,stroke:m.SELECTION_CONTROL_BORDER_BUFFER_COLOR}),this.bottomControl.transformByState({width:b-v+u,top:R-C-S+p,height:u,left:-S+p,strokeWidth:f}),this.bottomControl.setProps({fill:o,stroke:m.SELECTION_CONTROL_BORDER_BUFFER_COLOR}),l==null)this.dashedRect.hide(),this._stopAntLineAnimation();else{const T=t.strokeWidth*2/g;this.dashedRect.transformByState({height:R-C,width:b-v,strokeWidth:T,left:-T/2+p,top:-T/2+p}),this.dashedRect.setProps({strokeDashArray:[0,l/g]}),this._stopAntLineAnimation(),c!==!1&&this._startAntLineAnimation(),this.dashedRect.show()}if(this._showAutoFill=this._showAutoFill&&this._enableAutoFill,this._showAutoFill&&!this._hasWidgets(i)){const T={fill:o,stroke:s,strokeScaleEnabled:!1},M={width:d-h,height:d-h,left:b-v-d/2+h/2-p,top:R-C-d/2+h/2-p,strokeWidth:h};this._autoFillControl.setProps(T),this._autoFillControl.transformByState(M),this._autoFillControl.show()}else this._autoFillControl.hide();this._updateBackgroundControl(t),this._updateHeaderBackground(t),this._updateWidgets(t)}_updateControlCoord(){const{startX:e,startY:t}=this._selectionRenderModel;this.selectionShapeGroup.show(),this.selectionShapeGroup.translate(e,t),this.selectionShapeGroup.makeDirtyNoDebounce(!0)}updateStyle(e){this._updateLayoutOfSelectionControl(e),this._updateControlCoord()}updateRange(e,t){this._selectionRenderModel.setValue(e,t),this._showAutoFill=t!==null,this._updateLayoutOfSelectionControl(),this._updateControlCoord()}updateRangeBySelectionWithCoord(e,t){t&&(this._rowHeaderWidth=t.getWorksheetConfig().rowHeader.width,this._columnHeaderHeight=t.getWorksheetConfig().columnHeader.height),this._selectionRenderModel.setValue(e.rangeWithCoord,e.primaryWithCoord),this._showAutoFill=e.primaryWithCoord!==null,this._updateLayoutOfSelectionControl(e.style),this._updateControlCoord()}update(e,t=0,o=0,i,s){this._rowHeaderWidth=t,this._columnHeaderHeight=o,this.updateRangeBySelectionWithCoord({rangeWithCoord:e,primaryWithCoord:s,style:i}),i&&this.updateStyle(i)}updateCurrCell(e){this._showAutoFill=e!==null,this._selectionRenderModel.setCurrentCell(e)}clearHighlight(){this._showAutoFill=!1,this._selectionRenderModel.clearCurrentCell(),this._updateLayoutOfSelectionControl(this._currentStyle)}getScene(){return this._scene}dispose(){var e,t,o,i,s,l,c,d,u,h,g,S,f,p,v,C,b,R,T,M,y,P,x,A,k;(e=this._leftBorder)==null||e.dispose(),(t=this._rightBorder)==null||t.dispose(),(o=this._topBorder)==null||o.dispose(),(i=this._bottomBorder)==null||i.dispose(),(s=this._backgroundControlTop)==null||s.dispose(),(l=this._backgroundControlMiddleLeft)==null||l.dispose(),(c=this._backgroundControlMiddleRight)==null||c.dispose(),(d=this._backgroundControlBottom)==null||d.dispose(),this._autoFillControl.dispose(),(u=this._selectionShapeGroup)==null||u.dispose(),(h=this._rowHeaderBackground)==null||h.dispose(),(g=this._rowHeaderBorder)==null||g.dispose(),(S=this._rowHeaderGroup)==null||S.dispose(),(f=this._rowHeaderBackground)==null||f.dispose(),(p=this._columnHeaderBackground)==null||p.dispose(),(v=this._columnHeaderBorder)==null||v.dispose(),(C=this._columnHeaderGroup)==null||C.dispose(),(b=this._topLeftWidget)==null||b.dispose(),(R=this._topCenterWidget)==null||R.dispose(),(T=this._topRightWidget)==null||T.dispose(),(M=this._middleLeftWidget)==null||M.dispose(),(y=this._middleRightWidget)==null||y.dispose(),(P=this._bottomLeftWidget)==null||P.dispose(),(x=this._bottomCenterWidget)==null||x.dispose(),(A=this._bottomRightWidget)==null||A.dispose(),(k=this._controlExtension)==null||k.dispose(),super.dispose(),this._dispose$.next(this),this._dispose$.complete()}getCurrentCellInfo(){const e=this.model.currentCell;if(e){let t;if(e.isMerged){const o=e.mergeInfo;t={startRow:o.startRow,endRow:o.endRow,startColumn:o.startColumn,endColumn:o.endColumn,startX:o.startX,endX:o.endX,startY:o.startY,endY:o.endY}}else{const{actualRow:o,actualColumn:i,startX:s,endX:l,startY:c,endY:d}=e;t={startRow:o,endRow:o,startColumn:i,endColumn:i,startX:s,endX:l,startY:c,endY:d}}return t}}getValue(){return{...this._selectionRenderModel.getValue(),style:this._currentStyle}}getRange(){return this._selectionRenderModel.getValue().rangeWithCoord}enableHelperSelection(){this._isHelperSelection=!0}disableHelperSelection(){this._isHelperSelection=!1}_updateHeaderBackground(e){const{startX:t,startY:o,endX:i,endY:s,rangeType:l}=this._selectionRenderModel,c=this._currentStyle,d=this._getScale(),{stroke:u,rowHeaderFill:h=c.rowHeaderFill,rowHeaderStroke:g=c.rowHeaderStroke,columnHeaderFill:S=c.columnHeaderFill,columnHeaderStroke:f=c.columnHeaderStroke}=e;let{rowHeaderStrokeWidth:p=c.rowHeaderStrokeWidth,columnHeaderStrokeWidth:v=c.columnHeaderStrokeWidth}=e;p/=d,v/=d;const C=this._rowHeaderWidth,b=this._columnHeaderHeight;if(this._highlightHeader&&b>0){let R=S;l===a.RANGE_TYPE.COLUMN&&(R=new a.ColorKit(u).setAlpha(Gs).toString()),this._columnHeaderBackground.setProps({fill:R}),this._columnHeaderBackground.resize(i-t,b),this._columnHeaderBorder.setProps({fill:f}),this._columnHeaderBorder.transformByState({width:i-t,height:v,top:b-v+1/d}),this._columnHeaderGroup.show(),this._columnHeaderGroup.translate(t,0)}else this._columnHeaderGroup.hide();if(this._columnHeaderGroup.makeDirty(!0),this._highlightHeader&&C>0){let R=h;l===a.RANGE_TYPE.ROW&&(R=new a.ColorKit(u).setAlpha(Gs).toString()),this._rowHeaderBackground.setProps({fill:R}),this._rowHeaderBackground.resize(C,s-o),this._rowHeaderBorder.setProps({fill:g}),this._rowHeaderBorder.transformByState({width:p,height:s-o,left:C-p+1/d}),this._rowHeaderGroup.show(),this._rowHeaderGroup.translate(0,o)}else this._rowHeaderGroup.hide();this._rowHeaderGroup.makeDirty(!0)}_updateBackgroundControl(e){const{startX:t,startY:o,endX:i,endY:s}=this._selectionRenderModel,l=this._getScale(),{fill:c=e.fill}=e;let{strokeWidth:d}=e;d/=l;const u=this._selectionRenderModel.highlightToSelection();if(!u){this._backgroundControlTop.resize(i-t,s-o),this._backgroundControlTop.setProps({fill:c}),this._backgroundControlBottom.resize(0,0),this._backgroundControlMiddleLeft.resize(0,0),this._backgroundControlMiddleRight.resize(0,0);return}const{startX:h,startY:g,endX:S,endY:f}=u,p=d/2,v={left:-p,top:-p,width:i-t+p*2,height:g-o+p};v.height<0&&(v.width=0,v.height=0),this._backgroundControlTop.transformByState(v);const C={left:-p,top:g-o,width:h-t+p,height:f-g};C.width<0&&(C.width=0,C.height=0),this._backgroundControlMiddleLeft.transformByState(C);const b={left:S-t-p,top:g-o,width:i-S+p*2,height:f-g};b.width<0&&(b.width=0,b.height=0),this._backgroundControlMiddleRight.transformByState(b);const R={left:-p,top:f-o,width:i-t+p*2,height:s-f+p};R.height<0&&(R.width=0,R.height=0),this._backgroundControlBottom.transformByState(R),this._backgroundControlTop.setProps({fill:c}),this._backgroundControlMiddleLeft.setProps({fill:c}),this._backgroundControlMiddleRight.setProps({fill:c}),this._backgroundControlBottom.setProps({fill:c})}_updateWidgets(e){const{startX:t,startY:o,endX:i,endY:s}=this._selectionRenderModel,{stroke:l=e.stroke,widgets:c=e.widgets,widgetStroke:d=e.widgetStroke}=e,u=this._getScale();let{widgetSize:h,widgetStrokeWidth:g}=e;h/=u,g/=u;const S={left:-h/2+g/2,center:(i-t)/2-h/2+g/2,right:i-t-h/2+g/2,top:-h/2,middle:(s-o)/2-h/2,bottom:s-o-h/2+g/2},f=h-g;this._widgetRects.forEach(p=>{p.setProps({fill:l,stroke:d})}),c.tl===!0?(this._topLeftWidget.transformByState({height:f,width:f,left:S.left,top:S.top,strokeWidth:g}),this._topLeftWidget.show()):this._topLeftWidget.hide(),c.tc===!0?(this._topCenterWidget.transformByState({height:f,width:f,left:S.center,top:S.top,strokeWidth:g}),this._topCenterWidget.show()):this._topCenterWidget.hide(),c.tr===!0?(this._topRightWidget.transformByState({height:f,width:f,left:S.right,top:S.top,strokeWidth:g}),this._topRightWidget.show()):this._topRightWidget.hide(),c.ml===!0?(this._middleLeftWidget.transformByState({height:f,width:f,left:S.left,top:S.middle,strokeWidth:g}),this._middleLeftWidget.show()):this._middleLeftWidget.hide(),c.mr===!0?(this._middleRightWidget.transformByState({height:f,width:f,left:S.right,top:S.middle,strokeWidth:g}),this._middleRightWidget.show()):this._middleRightWidget.hide(),c.bl===!0?(this._bottomLeftWidget.transformByState({height:f,width:f,left:S.left,top:S.bottom,strokeWidth:g}),this._bottomLeftWidget.show()):this._bottomLeftWidget.hide(),c.bc===!0?(this._bottomCenterWidget.transformByState({height:f,width:f,left:S.center,top:S.bottom,strokeWidth:g}),this._bottomCenterWidget.show()):this._bottomCenterWidget.hide(),c.br===!0?(this._bottomRightWidget.transformByState({height:f,width:f,left:S.right,top:S.bottom,strokeWidth:g}),this._bottomRightWidget.show()):this._bottomRightWidget.hide()}_hasWidgets(e){if(e==null)return!1;const t=Object.keys(e);if(t.length===0)return!1;for(const o of t)if(e[o]===!0)return!0;return!1}_getScale(){const{scaleX:e,scaleY:t}=this._scene.getAncestorScale();return Math.max(e,t)}_stopAntLineAnimation(){this._antLineOffset=0,w.cancelRequestFrame(this._antRequestNewFrame)}_startAntLineAnimation(){const e=this._getScale();this._antLineOffset+=.6/e,this._antLineOffset>160/e&&(this._antLineOffset=0),this.dashedRect.setProps({strokeDashOffset:-this._antLineOffset}),this._antRequestNewFrame=w.requestNewFrame(()=>{this._startAntLineAnimation()})}}class Td extends w.Layer{render(r,e=!1){const t=a.Tools.now();return super.render(r,e),this._afterRender(t),this}_afterRender(r){this.scene.getEngine().renderFrameTimeMetric$.next(["selectionLayer",a.Tools.now()-r])}}const ve=a.createIdentifier("univer.sheet.selection-render-service");class ms extends a.Disposable{constructor(e,t,o,i,s){super();E(this,"_downObserver");E(this,"_scenePointerMoveSub");E(this,"_scenePointerUpSub");E(this,"_controlFillConfig$",new O.BehaviorSubject(null));E(this,"controlFillConfig$",this._controlFillConfig$.asObservable());E(this,"_selectionControls",[]);E(this,"_startRangeWhenPointerDown",{startY:0,endY:0,startX:0,endX:0,startRow:-1,endRow:-1,startColumn:-1,endColumn:-1});E(this,"_activeControlIndex",-1);E(this,"_startViewportPosX",0);E(this,"_startViewportPosY",0);E(this,"_scrollTimer");E(this,"_cancelDownSubscription");E(this,"_cancelUpSubscription");E(this,"_skeleton");E(this,"_scene");E(this,"_highlightHeader",!0);E(this,"_rangeType",a.RANGE_TYPE.NORMAL);E(this,"_selectionStyle");E(this,"_remainLastEnabled",!1);E(this,"_skipLastEnabled",!1);E(this,"_singleSelectionEnabled",!1);E(this,"_selectionMoveEnd$",new O.BehaviorSubject([]));E(this,"selectionMoveEnd$",this._selectionMoveEnd$.asObservable());E(this,"_selectionMoving$",new O.Subject);E(this,"selectionMoving$",this._selectionMoving$.asObservable());E(this,"_selectionMoveStart$",new O.Subject);E(this,"selectionMoveStart$",this._selectionMoveStart$.asObservable());E(this,"_selectionMoving",!1);E(this,"_selectionTheme");E(this,"_activeViewport");E(this,"interceptor",new a.InterceptorManager({RANGE_MOVE_PERMISSION_CHECK:Hi,RANGE_FILL_PERMISSION_CHECK:Vi}));E(this,"_escapeShortcutDisposable",null);this._injector=e,this._themeService=t,this._shortcutService=o,this._sheetSkeletonManagerService=i,this.contextService=s,this._initSelectionThemeFromThemeService(),this._initMoving()}get selectionMoving(){return this._selectionMoving}get _shouldDetectMergedCells(){return this._rangeType===a.RANGE_TYPE.NORMAL}_initMoving(){this.disposeWithMe(this._selectionMoving$.subscribe(()=>{this._selectionMoving=!0})),this.disposeWithMe(this._selectionMoveEnd$.subscribe(()=>{this._selectionMoving=!1}))}_setSelectionStyle(e){this._selectionStyle=e}getViewPort(){return this._activeViewport}setSingleSelectionEnabled(e=!1){this._singleSelectionEnabled=e}newSelectionControl(e,t,o){const i=this.getSelectionControls().length,{rowHeaderWidth:s,columnHeaderHeight:l}=t,c=new co(e,i,this._selectionTheme,{highlightHeader:this._highlightHeader,rowHeaderWidth:s,columnHeaderHeight:l});this._selectionControls.push(c);const d=Me(o,t);return c.updateRangeBySelectionWithCoord(d,t),c.setControlExtension({skeleton:t,scene:e,themeService:this._selectionTheme,injector:this._injector,selectionHooks:{selectionMoveEnd:()=>{this._selectionMoveEnd$.next(this.getSelectionDataWithStyle())}}}),c}resetSelectionsByModelData(e){const t=this.getSelectionControls(),o=this._skeleton;if(!(!t||!o)){for(let i=0,s=e.length;i<s;i++){const l=e[i],c=Me(l,this._skeleton),d=t[i];d?d.updateRangeBySelectionWithCoord(c,o):this.isSelectionEnabled()&&this.newSelectionControl(this._scene,o,l)}e.length<t.length&&t.splice(e.length).forEach(s=>s.dispose())}}refreshSelectionMoveStart(){this._selectionMoveStart$.next(this.getSelectionDataWithStyle())}refreshSelectionMoveEnd(){this._selectionMoveEnd$.next(this.getSelectionDataWithStyle())}_initSelectionThemeFromThemeService(){const e=this._themeService.getCurrentTheme();this._selectionTheme=new a.ThemeService,this._selectionTheme.setTheme(e)}setSelectionTheme(e){this._selectionTheme.setTheme(e)}_changeRuntime(e,t,o){this._skeleton=e,this._scene=t,this._activeViewport=o||(t==null?void 0:t.getViewports()[0]),t.findLayerByZIndex(tr)||t.addLayer(new Td(t,[],tr))}getSkeleton(){return this._skeleton}getSelectionDataWithStyle(){const e=this._selectionControls,[t,o]=this._skeleton.getLocation();return e.map(i=>{const s=i.getValue();return s.rangeWithCoord.sheetId=o,s.rangeWithCoord.unitId=t,s})}getSelectionControls(){return this._selectionControls}_addSelectionControlByModelData(e){var l;const t=this._skeleton,o=(l=e.style)!=null?l:bt(this._selectionTheme),i=this._scene;return e.style=o,this.newSelectionControl(i,t,e)}_clearAllSelectionControls(){const e=this._selectionControls;for(const t of e)t.dispose();this._selectionControls.length=0}_getFreeze(){var t;return(t=this._sheetSkeletonManagerService.getCurrentParam())==null?void 0:t.skeleton.getWorksheetConfig().freeze}_getViewportByCell(e,t){if(e===void 0||t===void 0)return null;const o=this._getFreeze();if(!o||o.startRow<=0&&o.startColumn<=0)return this._scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN);if(e>o.startRow&&t>o.startColumn)return this._scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN);if(e<=o.startRow&&t<=o.startColumn)return this._scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP);if(e<=o.startRow&&t>o.startColumn)return this._scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP);if(e>o.startRow&&t<=o.startColumn)return this._scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT)}getActiveRange(){const e=this.getSelectionControls(),t=e&&e[e.length-1].model;return t&&{startRow:t.startRow,startColumn:t.startColumn,endRow:t.endRow,endColumn:t.endColumn}}setActiveSelectionIndex(e){this._activeControlIndex=e}resetActiveSelectionIndex(){this._activeControlIndex=-1}getActiveSelectionControl(){const e=this.getSelectionControls();if(e)return this._activeControlIndex<0?e[e.length-1]:e[this._activeControlIndex]}endSelection(){var e;this._clearUpdatingListeners(),this._selectionMoveEnd$.next(this.getSelectionDataWithStyle()),(e=this._escapeShortcutDisposable)==null||e.dispose(),this._escapeShortcutDisposable=null}_reset(){var e;this._clearAllSelectionControls(),(e=this._downObserver)==null||e.unsubscribe(),this._downObserver=null}_setupPointerMoveListener(e,t,o,i=w.ScrollTimerType.ALL,s,l){var f,p;let c=0,d=0,u=s,h=l;this._scrollTimer=w.ScrollTimer.create(this._scene,i),this._scrollTimer.startScroll((f=e==null?void 0:e.left)!=null?f:0,(p=e==null?void 0:e.top)!=null?p:0,e);const g=this._scene,S=g.getActiveViewportByCoord(w.Vector2.FromArray([s,l]));this._scenePointerMoveSub=g.onPointerMove$.subscribeEvent(v=>{var D,W,H,U,B,F,L,j,z;const{offsetX:C,offsetY:b}=v,{x:R,y:T}=g.getCoordRelativeToViewport(w.Vector2.FromArray([C,b]));this._movingHandler(R,T,t,o);let M=R,y=T;const P=this.getActiveSelectionControl(),x=this._getFreeze(),A=P==null?void 0:P.model,k=(D=g.getActiveViewportByCoord(w.Vector2.FromArray([C,b])))!=null?D:this._getViewportByCell(A==null?void 0:A.endRow,A==null?void 0:A.endColumn);if((()=>{if(!S||!k||!e)return!1;const q=[w.SHEET_VIEWPORT_KEY.VIEW_MAIN,w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP,w.SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP,w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT];return q.includes(S.viewportKey)&&q.includes(k.viewportKey)})()){if(!S||!k||!e)return!1;const q=u<e.left&&R>e.left||u>e.left&&R<e.left,te=h<e.top&&T>e.top||h>e.top&&T<e.top;q&&(c+=1),te&&(d+=1);const Q=S.viewportKey,re=k.viewportKey;if(Q===w.SHEET_VIEWPORT_KEY.VIEW_ROW_TOP)b<e.top&&((W=A==null?void 0:A.endRow)!=null?W:0)<((H=x==null?void 0:x.startRow)!=null?H:0)?y=e.top:te&&d%2===1&&e.scrollToViewportPos({viewportScrollY:0});else if(Q===w.SHEET_VIEWPORT_KEY.VIEW_COLUMN_LEFT)C<e.left&&((U=A==null?void 0:A.endColumn)!=null?U:0)<((B=x==null?void 0:x.startColumn)!=null?B:0)?M=e.left:q&&c%2===1&&e.scrollToViewportPos({viewportScrollX:0});else if(Q===re){let se=!1,X=!1;Q===w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP?(se=!0,X=!0):Q===w.SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP?X=!0:Q===w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT&&(se=!0),((F=A==null?void 0:A.endRow)!=null?F:0)>((L=x==null?void 0:x.startRow)!=null?L:0)&&(X=!1),((j=A==null?void 0:A.endColumn)!=null?j:0)>((z=x==null?void 0:x.startColumn)!=null?z:0)&&(se=!1),se&&(M=e.left),X&&(y=e.top)}else{const se={x:S.scrollX,y:S.scrollY},X={x:k.scrollX,y:k.scrollY},Y=se.x!==X.x&&q&&c%2===1,G=se.y!==X.y&&te&&d%2===1;(Y||G)&&(e.scrollToBarPos({x:Y?se.x:void 0,y:G?se.y:void 0}),Y||(M=e.left),G||(y=e.top)),(Q===w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP&&re===w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT||re===w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP&&Q===w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT)&&(M=e.left),(Q===w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP&&re===w.SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP||re===w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT_TOP&&Q===w.SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP)&&(y=e.top)}u=R,h=T}this._scrollTimer.scrolling(M,y,()=>{this._movingHandler(R,T,t,o)})})}attachSelectionWithCoord(e){return Me(e,this._skeleton)}attachPrimaryWithCoord(e){return $n(this._skeleton,e)}getSelectionCellByPosition(e,t){return this.getCellWithCoordByOffset(e,t)}getCellWithCoordByOffset(e,t,o){const i=this._scene,s=o!=null?o:this._skeleton,l=i.getViewportScrollXY(i.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN)),{scaleX:c,scaleY:d}=i.getAncestorScale();return s.getCellWithCoordByOffset(e,t,c,d,l)}_movingHandler(e,t,o,i){var M,y,P,x,A;const s=this._skeleton,l=this._scene,[c,d]=s.getLocation(),u={startRow:(M=o==null?void 0:o.model.startRow)!=null?M:-1,endRow:(y=o==null?void 0:o.model.endRow)!=null?y:-1,startColumn:(P=o==null?void 0:o.model.startColumn)!=null?P:-1,endColumn:(x=o==null?void 0:o.model.endColumn)!=null?x:-1},h=l.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN),g=(A=this._getViewportByCell(u.endRow,u.endColumn))!=null?A:h,S=l.getScrollXYInfoByViewport(w.Vector2.FromArray([this._startViewportPosX,this._startViewportPosY]),g),{scaleX:f,scaleY:p}=l.getAncestorScale();i===a.RANGE_TYPE.ROW?e=Number.POSITIVE_INFINITY:i===a.RANGE_TYPE.COLUMN&&(t=Number.POSITIVE_INFINITY);const v=this._skeleton.getCellByOffset(e,t,f,p,S);if(!v)return;let C={startRow:Math.min(v.startRow,this._startRangeWhenPointerDown.startRow),startColumn:Math.min(v.startColumn,this._startRangeWhenPointerDown.startColumn),endRow:Math.max(v.endRow,this._startRangeWhenPointerDown.endRow),endColumn:Math.max(v.endColumn,this._startRangeWhenPointerDown.endColumn)};this._shouldDetectMergedCells&&(C=s.expandRangeByMerge(C));const R=Me({range:C,primary:void 0,style:null},s);R.rangeWithCoord.unitId=c,R.rangeWithCoord.sheetId=d,R.rangeWithCoord.rangeType=i;const T=u.startRow!==C.startRow||u.startColumn!==C.startColumn||u.endRow!==C.endRow||u.endColumn!==C.endColumn;o!=null&&T&&(o.updateRangeBySelectionWithCoord(R),this._selectionMoving$.next(this.getSelectionDataWithStyle()))}_clearUpdatingListeners(){var t,o,i,s,l;this._scene.enableObjectsEvent(),(t=this._scenePointerMoveSub)==null||t.unsubscribe(),this._scenePointerMoveSub=null,(o=this._scenePointerUpSub)==null||o.unsubscribe(),this._scenePointerUpSub=null,(i=this._cancelDownSubscription)==null||i.unsubscribe(),this._cancelDownSubscription=null,(s=this._cancelUpSubscription)==null||s.unsubscribe(),this._cancelUpSubscription=null,(l=this._scrollTimer)==null||l.dispose()}_addEndingListeners(){var o,i,s;const e=this._scene,t=(o=e.getEngine())==null?void 0:o.activeScene;!t||t===e||((i=this._cancelDownSubscription)==null||i.unsubscribe(),this._cancelDownSubscription=null,(s=this._cancelUpSubscription)==null||s.unsubscribe(),this._cancelUpSubscription=null,this._cancelDownSubscription=t.onPointerDown$.subscribeEvent(()=>this._clearUpdatingListeners()),this._cancelUpSubscription=t.onPointerUp$.subscribeEvent(()=>this._clearUpdatingListeners()))}_getSelectionWithCoordByOffset(e,t,o,i,s){const l=this._skeleton;if(l==null)return null;if(this._shouldDetectMergedCells){const C=l==null?void 0:l.getCellWithCoordByOffset(e,t,o,i,s,{firstMatch:!0});if(!C)return;const b=a.convertCellToRange(C);return{primaryWithCoord:C,rangeWithCoord:b}}const{row:c,column:d}=l.getCellIndexByOffset(e,t,o,i,s),u=l.getNoMergeCellWithCoordByIndex(c,d),{startX:h,startY:g,endX:S,endY:f}=u,p={startY:g,endY:f,startX:h,endX:S,startRow:c,endRow:c,startColumn:d,endColumn:d};return{primaryWithCoord:{mergeInfo:p,actualRow:c,actualColumn:d,isMerged:!1,isMergedMainCell:!1,startY:g,endY:f,startX:h,endX:S},rangeWithCoord:p}}_checkClearPreviousControls(e){this.getSelectionControls().length!==0&&(!e.ctrlKey&&!e.shiftKey&&!this._remainLastEnabled||this._singleSelectionEnabled&&!e.shiftKey)&&this._clearAllSelectionControls()}_makeSelectionByTwoCells(e,t,o,i,s){const{actualRow:l,actualColumn:c,mergeInfo:d}=e;this._startRangeWhenPointerDown={...e.mergeInfo};const u=Math.min(l,t.startRow,d.startRow),h=Math.max(l,t.endRow,d.endRow),g=Math.min(c,t.startColumn,d.startColumn),S=Math.max(c,t.endColumn,d.endColumn),p={range:o.expandRangeByMerge({startRow:u,startColumn:g,endRow:h,endColumn:S}),primary:null,style:null},v=Me(p,o);s.updateRangeBySelectionWithCoord(v)}isSelectionEnabled(){return this.contextService.getContextValue(m.SELECTIONS_ENABLED)}isSelectionDisabled(){return this.contextService.getContextValue(m.SELECTIONS_ENABLED)===!1}inRefSelectionMode(){return this.contextService.getContextValue(m.REF_SELECTIONS_ENABLED)}}function gs(n){return{range:{startRow:0,startColumn:0,endRow:n.getRowCount()-1,endColumn:n.getColumnCount()-1,rangeType:a.RANGE_TYPE.ALL},primary:kr(n).primary,style:null}}function kr(n){return Qa(n,{startRow:0,startColumn:0,endRow:0,endColumn:0})}function Qa(n,r){const e=n.worksheet.getCellInfoInMergeData(r.startRow,r.startColumn),t=n.worksheet.getCellInfoInMergeData(r.endRow,r.endColumn);return{range:{startRow:e.startRow,startColumn:e.startColumn,endRow:t.endRow,endColumn:t.endColumn,rangeType:a.RANGE_TYPE.NORMAL},primary:{actualRow:e.startRow,actualColumn:e.startColumn,startRow:e.startRow,startColumn:e.startColumn,endRow:e.endRow,endColumn:e.endColumn,isMerged:e.isMerged,isMergedMainCell:e.isMergedMainCell},style:null}}var wd=Object.getOwnPropertyDescriptor,yd=(n,r,e,t)=>{for(var o=t>1?void 0:t?wd(r,e):r,i=n.length-1,s;i>=0;i--)(s=n[i])&&(o=s(o)||o);return o},Zs=(n,r)=>(e,t)=>r(e,t,n);exports.SheetSkeletonManagerService=class extends a.Disposable{constructor(e,t,o){super();E(this,"_sheetId","");E(this,"_sheetSkeletonParamStore",new Map);E(this,"_currentSkeleton$",new O.BehaviorSubject(null));E(this,"currentSkeleton$",this._currentSkeleton$.asObservable());E(this,"_currentSkeletonBefore$",new O.BehaviorSubject(null));E(this,"currentSkeletonBefore$",this._currentSkeletonBefore$.asObservable());this._context=e,this._injector=t,this._sheetSkService=o,this.disposeWithMe(()=>{this._currentSkeletonBefore$.complete(),this._currentSkeleton$.complete(),this._sheetSkeletonParamStore.forEach(i=>this.disposeSkeleton(i.sheetId)),this._sheetSkeletonParamStore.clear()}),this._initRemoveSheet()}_initRemoveSheet(){this.disposeWithMe(this._context.unit.sheetDisposed$.subscribe(e=>{this.disposeSkeleton(e.getSheetId())}))}getCurrentSkeleton(){var e;return(e=this.getCurrentParam())==null?void 0:e.skeleton}getCurrent(){return this.getCurrentParam()}getCurrentParam(){return this._getSkeletonParam(this._sheetId)}getSkeleton(e){return this._getSkeleton(e)}getSkeletonParam(e){return this._getSkeletonParam(e)}getWorksheetSkeleton(e){return this.getSkeletonParam(e)}getUnitSkeleton(e,t){const o=this._getSkeletonParam(t);return o!=null&&(o.unitId=e),o}setCurrent(e){this._setCurrent(e.sheetId)}setSkeletonParam(e,t){this._sheetSkService.setSkeleton(t.unitId,e,t.skeleton),this._sheetSkeletonParamStore.set(e,t)}_setCurrent(e){this._sheetId=e;const t=this._getSkeletonParam(e),o=this._context.unitId;if(t!=null)this.reCalculate(t);else{const l=this._context.unit.getSheetBySheetId(e);if(l==null)return;const c=this._context.scene,d=this._buildSkeleton(l,c);this.setSkeletonParam(e,{unitId:o,sheetId:e,skeleton:d,dirty:!1})}const i=this._getSkeletonParam(e);this._currentSkeletonBefore$.next(i),this._currentSkeleton$.next(i)}reCalculate(e){e||(e=this.getCurrentParam()),e!=null&&(e.dirty&&(e.skeleton.makeDirty(!0),e.dirty=!1),e.skeleton.calculate())}makeDirty(e,t=!0){const o=this._getSkeletonParam(e.sheetId);o!=null&&(o.dirty=t)}getOrCreateSkeleton(e){return this.ensureSkeleton(e.sheetId)}ensureSkeleton(e){const t=this._getSkeletonParam(e);if(t)return t.skeleton;const i=this._context.unit.getSheetBySheetId(e);if(!i)return;const s=this._buildSkeleton(i);return this.setSkeletonParam(e,{unitId:this._context.unitId,sheetId:e,skeleton:s,dirty:!1}),s}disposeSkeleton(e){const t=this.getSkeletonParam(e);t&&(t.skeleton.dispose(),this._sheetSkeletonParamStore.delete(e),this._sheetSkService.deleteSkeleton(t.unitId,e))}attachRangeWithCoord(e){const t=this.getCurrentSkeleton();return t?bn(t,e):null}_getSkeletonParam(e){return this._sheetSkeletonParamStore.get(e)}_getSkeleton(e){const t=this._getSkeletonParam(e);return t?t.skeleton:null}_buildSkeleton(e,t){return this._injector.createInstance(w.SpreadsheetSkeleton,e,this._context.unit.getStyles())}setColumnHeaderSize(e,t,o){var u;if(!e)return;const i=(u=this.getWorksheetSkeleton(t))==null?void 0:u.skeleton;if(!i)return;i.columnHeaderHeight=o,e.scene.getViewports()[0].top=o,e.scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_COLUMN_RIGHT).setViewportSize({height:o}),e.scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_COLUMN_LEFT).setViewportSize({height:o}),e.scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_ROW_BOTTOM).setViewportSize({top:o}),e.scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_ROW_TOP).setViewportSize({top:o}),e.scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_LEFT_TOP).setViewportSize({height:o});const s=e==null?void 0:e.with(m.SheetsSelectionsService),l=e==null?void 0:e.with(ve),c=s.getCurrentSelections();l.resetSelectionsByModelData(c);const d=this.getUnitSkeleton(e.unitId,t);d&&(d.commandId=Ar.id,this._currentSkeleton$.next(d))}setRowHeaderSize(e,t,o){var f;const i=(f=this.getWorksheetSkeleton(t))==null?void 0:f.skeleton;if(!e||!i)return;i.rowHeaderWidth=o;const s=e.scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_LEFT_TOP).width||46,l=o-s,c=e.scene.getViewports()[0].left;e.scene.getViewports()[0].left=c+l,e.scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_ROW_BOTTOM).setViewportSize({width:o}),e.scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_ROW_TOP).setViewportSize({width:o}),e.scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_COLUMN_LEFT).setViewportSize({left:o});const d=e.scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_COLUMN_RIGHT).left||0;e.scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_COLUMN_RIGHT).setViewportSize({left:d+l}),e.scene.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_LEFT_TOP).setViewportSize({width:o});const u=e==null?void 0:e.with(m.SheetsSelectionsService),h=e==null?void 0:e.with(ve),g=u.getCurrentSelections();h.resetSelectionsByModelData(g);const S=this.getCurrent();S&&(S.commandId=xr.id,this._currentSkeleton$.next(S))}};exports.SheetSkeletonManagerService=yd([Zs(1,a.Inject(a.Injector)),Zs(2,a.Inject(m.SheetSkeletonService))],exports.SheetSkeletonManagerService);function ht(){const n=I.useDependency(a.IUniverInstanceService),r=I.useObservable(()=>n.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET),void 0,void 0,[]);return r!=null?r:null}function Md(n){return I.useObservable(()=>{var e;return(e=n==null?void 0:n.activeSheet$)!=null?e:O.of(null)},void 0,void 0,[n])}function Pd(){const n=I.useDependency(a.IUniverInstanceService);return I.useObservable(()=>O.merge([n.getTypeOfUnitAdded$(a.UniverInstanceType.UNIVER_SHEET),n.getTypeOfUnitDisposed$(a.UniverInstanceType.UNIVER_SHEET)]).pipe(O.map(()=>n.getAllUnitsForType(a.UniverInstanceType.UNIVER_SHEET)),O.startWith(n.getAllUnitsForType(a.UniverInstanceType.UNIVER_SHEET))),[],void 0,[n])}const Od="SheetUI";var Ss=(n=>(n.FILTER_PANEL_EMBED_POINT="filter-panel-embed-point",n.SHEETS_FOOTER="sheets-footer",n.FORMULA_AUX="formula-aux",n))(Ss||{});const Rt="sheets-ui.config",Ja=Symbol("HIDE_STATUS_BAR_STATISTIC"),Ui={formulaBar:!0,maxAutoHeightCount:1e3};var xd=Object.getOwnPropertyDescriptor,Ad=(n,r,e,t)=>{for(var o=t>1?void 0:t?xd(r,e):r,i=n.length-1,s;i>=0;i--)(s=n[i])&&(o=s(o)||o);return o},Ln=(n,r)=>(e,t)=>r(e,t,n);const fs=["ff","fs","tr","tb"];exports.AutoHeightController=class extends a.Disposable{constructor(r,e,t,o,i){super(),this._renderManagerService=r,this._sheetInterceptorService=e,this._selectionManagerService=t,this._univerInstanceService=o,this._configService=i,this._initialize()}_getRangesScope(r){let e,t;for(const{startRow:o,endRow:i}of r)e=e===void 0?o:Math.min(e,o),t=t===void 0?i:Math.max(t,i);return t-e+1}getUndoRedoParamsOfAutoHeight(r){var C;const{_univerInstanceService:e,_configService:t}=this,o=e.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET),i=o.getActiveSheet(),s=o.getUnitId(),l=i.getSheetId(),c=this._renderManagerService.getRenderById(s).with(exports.SheetSkeletonManagerService);if(!l||!c.getCurrentParam())return{redos:[],undos:[]};const d=t.getConfig(Rt);let u=r;Array.isArray(r)||(r.startRow!==void 0&&r.startRow!==void 0?u=[r]:u=[]);const h=this._getRangesScope(u);if(((C=d==null?void 0:d.maxAutoHeightCount)!=null?C:1e3)<h)return{redos:[],undos:[]};const{skeleton:S}=c.getCurrentParam(),f=S.calculateAutoHeightInRange(r),p={subUnitId:l,unitId:s,rowsAutoHeightInfo:f},v=m.SetWorksheetRowAutoHeightMutationFactory(p,i);return{undos:[{id:m.SetWorksheetRowAutoHeightMutation.id,params:v}],redos:[{id:m.SetWorksheetRowAutoHeightMutation.id,params:p}]}}_initialize(){const{_sheetInterceptorService:r,_selectionManagerService:e}=this;this.disposeWithMe(r.interceptCommand({getMutations:t=>{if(t.id===m.SetRangeValuesCommand.id){const o=t.params;return this.getUndoRedoParamsOfAutoHeight(o.range)}return{redos:[],undos:[]}}})),this.disposeWithMe(r.interceptCommand({getMutations:t=>t.id!==m.SetWorksheetRowIsAutoHeightCommand.id?{redos:[],undos:[]}:this.getUndoRedoParamsOfAutoHeight(t.params.ranges)})),this.disposeWithMe(r.interceptCommand({getMutations:t=>{var i,s;if(t.id!==m.SetStyleCommand.id)return{redos:[],undos:[]};if(!fs.includes((i=t.params)==null?void 0:i.style.type))return{redos:[],undos:[]};const o=(s=e.getCurrentSelections())==null?void 0:s.map(l=>l.range);return o!=null&&o.length?this.getUndoRedoParamsOfAutoHeight(o):{redos:[],undos:[]}}})),this.disposeWithMe(r.interceptAfterCommand({getMutations:t=>{if(t.id===m.MoveRangeCommand.id){const o=t.params;return this.getUndoRedoParamsOfAutoHeight([o.fromRange,o.toRange])}if(t.id===m.ReorderRangeCommand.id){const o=t.params;return this.getUndoRedoParamsOfAutoHeight([o.range])}return{redos:[],undos:[]}}}))}};exports.AutoHeightController=Ad([Ln(0,w.IRenderManagerService),Ln(1,a.Inject(m.SheetInterceptorService)),Ln(2,a.Inject(m.SheetsSelectionsService)),Ln(3,a.Inject(a.IUniverInstanceService)),Ln(4,a.IConfigService)],exports.AutoHeightController);function Sn(n,r,e,t){const o=r.get(a.IUniverInstanceService),i=e?o.getUnit(e,a.UniverInstanceType.UNIVER_SHEET):o.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET),s=t?i==null?void 0:i.getSheetBySheetId(t):i==null?void 0:i.getActiveSheet();if(!s)return null;const{startRow:l,endRow:c,startColumn:d,endColumn:u}=n,h=[],g=[];for(let S=l;S<=c;S++)s.getRowFiltered(S)||h.push(S);for(let S=d;S<=u;S++)g.push(S);return{rows:h,cols:g}}function Et(n){const{rows:r,cols:e}=n;return{startRow:r[0],endRow:r[r.length-1],startColumn:e[0],endColumn:e[e.length-1]}}function Kt(n){let r=[],e=[];const t=[];return n.forEach(o=>{r=r.concat(o.rows),e=e.concat(o.cols)}),r=Array.from(new Set(r)).sort((o,i)=>o-i),e=Array.from(new Set(e)).sort((o,i)=>o-i),n.forEach(o=>{t.push({startRow:r.findIndex(i=>i===o.rows[0]),endRow:r.findIndex(i=>i===o.rows[o.rows.length-1]),startColumn:e.findIndex(i=>i===o.cols[0]),endColumn:e.findIndex(i=>i===o.cols[o.cols.length-1])})}),{ranges:t,mapFunc:(o,i)=>({row:r[o],col:e[i]})}}function kd(n){const r=new a.ObjectMatrix;return n.forEach(e=>{const{rows:t,cols:o}=e;t.forEach(i=>{o.forEach(s=>{r.setValue(i,s,{v:null,p:null,f:null,si:null,custom:null})})})}),r.getData()}const Li={零:0,一:1,二:2,三:3,四:4,五:5,六:6,七:7,八:8,九:9},nr=["零","一","二","三","四","五","六","七","八","九"],Ks=["","万","亿","万亿","亿亿"],Nd=["","十","百","千"],$a={十:{value:10,secUnit:!1},百:{value:100,secUnit:!1},千:{value:1e3,secUnit:!1},万:{value:1e4,secUnit:!0},亿:{value:1e8,secUnit:!0}};function ct(n){if(!n)return 0;let r=0,e=0,t=0,o=!1;const i=n.split("");for(let s=0;s<i.length;s++){const l=Li[i[s]];if(typeof l<"u")t=l,s===i.length-1&&(e+=t);else{const c=$a[i[s]],d=c.value;o=c.secUnit,o?(e=(e+t)*d,r+=e,e=0):e+=t*d,t=0}}return r+e}function Dd(n){let r="",e="",t=0,o=!0;for(;n>0;){const i=n%10;i===0?o||(o=!0,e=nr[i]+e):(o=!1,r=nr[i],r+=Nd[t],e=r+e),t++,n=Math.floor(n/10)}return e}function Hd(n){let r=0,e="",t="",o=!1;if(n===0)return nr[0];for(;n>0;){const i=n%1e4;o&&(t=nr[0]+t),e=Dd(i),e+=i!==0?Ks[r]:Ks[0],t=e+t,o=i<1e3&&i>0,n=Math.floor(n/1e4),r++}return t}function Vd(n){if(!n)return!1;let r=!0;if(n)if(n.length===1)n==="日"||n in Li?r=!0:r=!1;else{const e=n.split("");for(let t=0;t<e.length;t++)if(!(e[t]in Li||e[t]in $a)){r=!1;break}}return r}function Uo(n){if(!n)return{isExtendNumber:!1};const r=/0|([1-9]+[0-9]*)/g,e=r.test(n);if(e){const t=n.match(r);if(t&&t.length>0){const o=t[t.length-1],i=n.lastIndexOf(o),s=n.substr(0,i),l=n.substr(i+o.length);return{isExtendNumber:!0,matchTxt:Number(o),beforeTxt:s,afterTxt:l}}return{isExtendNumber:!1}}return{isExtendNumber:e}}function Wd(n){let r;return n.length===2&&(n==="周一"||n==="周二"||n==="周三"||n==="周四"||n==="周五"||n==="周六"||n==="周日")?r=!0:r=!1,r}function Ud(n){let r;return n.length===3&&(n==="星期一"||n==="星期二"||n==="星期三"||n==="星期四"||n==="星期五"||n==="星期六"||n==="星期日")?r=!0:r=!1,r}function Ld(n,r){let e=0;for(let t=0;t<n.length&&n[t]<r;t++)e++;return e}function uo(n){let r=!0;const e=n[1]-n[0];for(let t=1;t<n.length;t++)if(n[t]-n[t-1]!==e){r=!1;break}return r}function Bd(n,r,e){const t=[],o=Math.floor(r/n),i=r%n;let s=0;if(o>0){for(let l=0;l<o;l++)for(let c=0;c<e.length;c++)t[e[c]+l*n]=s,s++;for(let l=0;l<e.length&&e[l]<i;l++)t[e[l]+n*o]=s,s++}else for(let l=0;l<e.length&&e[l]<i;l++)t[e[l]]=s,s++;return t}function jt(n,r){const e=[];for(let t=1;t<=r;t++){const o=(t-1)%n.length,i=a.Tools.deepClone(n[o]);zt(i),e.push({v:null,s:null,p:null,f:null,si:null,t:null,...i})}return e}function Fd(n,r){var t;const e=[];for(let o=1;o<=r;o++){const i=(o-1)%n.length,s={s:(t=n[i])==null?void 0:t.s};e.push(s)}return e}function jd(n){let r=!0;const e=n[1]/n[0];for(let t=1;t<n.length;t++)if(n[t]/n[t-1]!==e){r=!1;break}return r}function zd(n){const r=[];for(let e=1;e<=n;e++)r.push(e);return r}function or(n,r,e){var i,s,l,c;const t=[],o=[];for(let d=0;d<n.length;d++)o.push(Number((i=n[d])==null?void 0:i.v));if(n.length>2&&jd(o))for(let d=1;d<=r;d++){const u=(d-1)%n.length,h=a.Tools.deepClone(n[u]);zt(h);const g=Number((s=n[n.length-1])==null?void 0:s.v)*(Number((l=n[1])==null?void 0:l.v)/Number((c=n[0])==null?void 0:c.v))**d;h&&($s(h)&&(h.v=g),t.push(h))}else{const d=zd(n.length);for(let u=1;u<=r;u++){const h=(u-1)%n.length,g=a.Tools.deepClone(n[h]);zt(g);const S=e===a.Direction.DOWN||e===a.Direction.RIGHT,f=Xd(n.length+u,o,d,S);g&&($s(g)&&(g.v=f),t.push(g))}}return t}function Xd(n,r,e,t=!0){function o(h){let g=0;for(let S=0;S<h.length;S++)g+=h[S];return g/h.length}const i=o(e),s=o(r);let l=0,c=0;for(let h=0;h<e.length;h++)l+=(e[h]-i)*(r[h]-s),c+=(e[h]-i)*(e[h]-i);let d;c===0?d=t?1:-1:d=l/c;const u=s-d*i;return Math.round((u+d*n)*1e5)/1e5}function qs(n,r,e){var i;const t=[],o=/0|([1-9]+[0-9]*)/g;for(let s=1;s<=r;s++){const l=(s-1)%n.length,c=a.Tools.deepClone(n[l]);zt(c);const d=`${(i=n[n.length-1])==null?void 0:i.v}`,u=d==null?void 0:d.match(o),h=u==null?void 0:u[u.length-1],g=Math.abs(Number(h)+e*s);if(!d||!h)continue;const S=d.lastIndexOf(h),f=d.substr(0,S)+g.toString()+d.substr(S+h.length);c&&(c.v=f,t.push(c))}return t}function Rn(n,r,e,t=0){var l,c;const o=[["日","一","二","三","四","五","六"],["周日","周一","周二","周三","周四","周五","周六"],["星期日","星期一","星期二","星期三","星期四","星期五","星期六"]];if(t>=o.length)return[];const i=o[t],s=[];for(let d=1;d<=r;d++){const u=(d-1)%n.length,h=a.Tools.deepClone(n[u]);zt(h);let g=0;if(((l=n[n.length-1])==null?void 0:l.v)===i[0])g=7+e*d;else{const f=`${(c=n[n.length-1])==null?void 0:c.v}`;if(f){const p=f.substr(f.length-1,1);g=ct(p)+e*d}}g<0&&(g=Math.ceil(Math.abs(g)/7)*7+g);const S=g%7;h&&(h.v=i[S],s.push(h))}return s}function Qs(n,r,e){var o;const t=[];for(let i=1;i<=r;i++){const s=(i-1)%n.length,l=a.Tools.deepClone(n[s]);zt(l);const c=`${(o=n[n.length-1])==null?void 0:o.v}`,d=ct(c)+e*i;let u;d<=0?u="零":u=Hd(d),l&&(l.v=u,t.push(l))}return t}const qn={enWeek1:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],enWeek2:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],enMonth1:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],enMonth2:["January","February","March","April","May","June","July","August","September","October","November","December"],chnMonth1:["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],chnMonth2:["正月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","腊月"],chHour1:["子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"],chHour2:["子时","丑时","寅时","卯时","辰时","巳时","午时","未时","申时","酉时","戌时","亥时"],chYear1:["甲","乙","丙","丁","戊","己","庚","辛","壬","癸"],chSeason1:["春","夏","秋","冬"],chSeason2:["春季","夏季","秋季","冬季"]};function Yd(n){let r=!1;return Object.keys(qn).forEach(e=>{qn[e].includes(n)&&(r=!0)}),r}function Yr(n){let r="";const e=[];return Object.keys(qn).forEach(t=>{qn[t].includes(n)&&(r=t,e.push(...qn[t]))}),{name:r,series:e}}function Js(n,r,e,t){var s;const o=t.length,i=[];for(let l=1;l<=r;l++){const c=(l-1)%n.length,d=a.Tools.deepClone(n[c]);zt(d);const u=`${(s=n[n.length-1])==null?void 0:s.v}`;let h=t.indexOf(u)+e*l;h<0&&(h+=Math.abs(e)*o);const g=h%o;d&&(d.v=t[g],i.push(d))}return i}function Gd(n,r){const e=[];let t;if(r.startRow<n.startRow)t=a.Direction.UP;else if(r.endRow>n.endRow)t=a.Direction.DOWN;else if(r.startColumn<n.startColumn)t=a.Direction.LEFT;else if(r.endColumn>n.endColumn)t=a.Direction.RIGHT;else return[];if(t===a.Direction.DOWN||t===a.Direction.UP){const o=n.endRow-n.startRow+1,i=r.endRow-r.startRow+1,s=Math.floor(i/o),l=i%o,c={startRow:0,startColumn:0,endRow:n.endRow-n.startRow,endColumn:n.endColumn-n.startColumn};if(t===a.Direction.DOWN){for(let d=0;d<s;d++)e.push({repeatStartCell:{row:n.startRow+(d+1)*o,col:n.startColumn},relativeRange:c});l>0&&e.push({repeatStartCell:{row:n.startRow+(s+1)*o,col:n.startColumn},relativeRange:{startRow:0,startColumn:0,endRow:l-1,endColumn:n.endColumn-n.startColumn}})}else{for(let d=0;d<s;d++)e.push({repeatStartCell:{row:n.startRow-(d+1)*o,col:n.startColumn},relativeRange:c});l>0&&e.push({repeatStartCell:{row:n.startRow-(s+1)*o,col:n.startColumn},relativeRange:{startRow:o-l,endRow:o-1,startColumn:0,endColumn:n.endColumn-n.startColumn}})}}if(t===a.Direction.RIGHT||t===a.Direction.LEFT){const o=n.endColumn-n.startColumn+1,i=r.endColumn-r.startColumn+1,s=Math.floor(i/o),l=i%o,c={startRow:0,startColumn:0,endRow:n.endRow-n.startRow,endColumn:n.endColumn-n.startColumn};if(t===a.Direction.RIGHT){for(let d=0;d<s;d++)e.push({repeatStartCell:{row:n.startRow,col:n.startColumn+(d+1)*o},relativeRange:c});l>0&&e.push({repeatStartCell:{row:n.startRow,col:n.startColumn+(s+1)*o},relativeRange:{startRow:0,startColumn:0,endRow:n.endRow-n.startRow,endColumn:l-1}})}else{for(let d=0;d<s;d++)e.push({repeatStartCell:{row:n.startRow,col:n.startColumn-(d+1)*o},relativeRange:c});l>0&&e.push({repeatStartCell:{row:n.startRow,col:n.startColumn-(s+1)*o},relativeRange:{startRow:0,startColumn:o-l,endRow:n.endRow-n.startRow,endColumn:o-1}})}}return e}function $s(n){return!(a.isFormulaString(n.f)||a.isFormulaId(n.si)||n.t===a.CellValueType.BOOLEAN)}function zt(n){n&&"custom"in n&&delete n.custom}var mn=(n=>(n.Append="APPEND",n.Default="DEFAULT",n.Only="ONLY",n))(mn||{}),_e=(n=>(n.NUMBER="number",n.DATE="date",n.EXTEND_NUMBER="extendNumber",n.CHN_NUMBER="chnNumber",n.CHN_WEEK2="chnWeek2",n.CHN_WEEK3="chnWeek3",n.LOOP_SERIES="loopSeries",n.FORMULA="formula",n.OTHER="other",n))(_e||{}),le=(n=>(n.COPY="COPY",n.SERIES="SERIES",n.ONLY_FORMAT="ONLY_FORMAT",n.NO_FORMAT="NO_FORMAT",n))(le||{});const Zd={type:_e.DATE,priority:1100,match:(n,r)=>{var e;if(n!=null&&n.f||n!=null&&n.si)return!1;if((typeof(n==null?void 0:n.v)=="number"||(n==null?void 0:n.t)===a.CellValueType.NUMBER)&&n.s){if(typeof n.s=="string"){const o=r.get(a.IUniverInstanceService).getFocusedUnit().getStyles().get(n.s),i=(e=o==null?void 0:o.n)==null?void 0:e.pattern;if(i)return a.numfmt.getInfo(i).isDate}else if(n.s.n&&a.numfmt.getInfo(n.s.n.pattern).isDate)return!0}return!1},isContinue:(n,r)=>n.type===_e.DATE,applyFunctions:{[le.SERIES]:(n,r,e)=>{const{data:t}=n;return e===a.Direction.LEFT||e===a.Direction.UP?(t.reverse(),or(t,r,e).reverse()):or(t,r,e)}}},Kd={type:_e.NUMBER,priority:1e3,match:n=>typeof(n==null?void 0:n.v)=="number"||(n==null?void 0:n.t)===a.CellValueType.NUMBER,isContinue:(n,r)=>n.type===_e.NUMBER,applyFunctions:{[le.SERIES]:(n,r,e)=>{const{data:t}=n;return e===a.Direction.LEFT||e===a.Direction.UP?(t.reverse(),or(t,r,e).reverse()):or(t,r,e)}}},el={type:_e.OTHER,priority:0,match:()=>!0,isContinue:(n,r)=>n.type===_e.OTHER},qd={type:_e.EXTEND_NUMBER,priority:900,match:n=>Uo(`${n==null?void 0:n.v}`||"").isExtendNumber,isContinue:(n,r)=>{var e;if(n.type===_e.EXTEND_NUMBER){const{beforeTxt:t,afterTxt:o}=Uo(`${(e=n.cellData)==null?void 0:e.v}`||""),{beforeTxt:i,afterTxt:s}=Uo(`${r==null?void 0:r.v}`||"");if(t===i&&o===s)return!0}return!1},applyFunctions:{[le.SERIES]:(n,r,e)=>{var l;const{data:t}=n,o=e===a.Direction.UP||e===a.Direction.LEFT;let i;if(t.length===1)return i=o?-1:1,Ue(qs(t,r,i),o);const s=[];for(let c=0;c<t.length;c++){const d=`${(l=t[c])==null?void 0:l.v}`;d&&s.push(Number(Uo(d).matchTxt))}return o&&(t.reverse(),s.reverse()),uo(s)?(i=s[1]-s[0],Ue(qs(t,r,i),o)):jt(t,r)}}},Qd={type:_e.CHN_NUMBER,priority:830,match:n=>!!Vd(`${n==null?void 0:n.v}`||""),isContinue:(n,r)=>n.type===_e.CHN_NUMBER,applyFunctions:{[le.SERIES]:(n,r,e)=>{var c,d,u;const{data:t}=n,o=e===a.Direction.LEFT||e===a.Direction.UP;if(t.length===1){const h=`${(c=t[0])==null?void 0:c.v}`;let g;return o?g=-1:g=1,h&&(h==="日"||ct(h)<7)?Ue(Rn(t,r,g),o):Ue(Qs(t,r,g),o)}let i=!1;for(let h=0;h<t.length;h++)if(((d=t[h])==null?void 0:d.v)==="日"){i=!0;break}const s=[];let l=0;for(let h=0;h<t.length;h++){const g=`${(u=t[h])==null?void 0:u.v}`;g==="日"?h===0?s.push(0):(l++,s.push(l*7)):i&&ct(g)>0&&ct(g)<7?s.push(ct(g)+l*7):s.push(ct(g))}if(o&&(t.reverse(),s.reverse()),uo(s)){if(i||s[s.length-1]<6&&s[0]>0||s[0]<6&&s[s.length-1]>0){const g=s[1]-s[0];return Ue(Rn(t,r,g),o)}const h=s[1]-s[0];return Ue(Qs(t,r,h),o)}return jt(t,r)}}},Jd={type:_e.CHN_WEEK2,priority:820,match:n=>!!Wd(`${n==null?void 0:n.v}`||""),isContinue:(n,r)=>n.type===_e.CHN_WEEK2,applyFunctions:{[le.SERIES]:(n,r,e)=>{var l;const{data:t}=n,o=e===a.Direction.LEFT||e===a.Direction.UP;if(t.length===1){let c;return o?c=-1:c=1,Ue(Rn(t,r,c,1),o)}const i=[];let s=0;for(let c=0;c<t.length;c++){const d=`${(l=t[c])==null?void 0:l.v}`,u=d==null?void 0:d.substr(d.length-1,1);d==="周日"?c===0?i.push(0):(s++,i.push(s*7)):i.push(ct(u)+s*7)}if(o&&(t.reverse(),i.reverse()),uo(i)){const c=i[1]-i[0];return Ue(Rn(t,r,c,1),o)}return jt(t,r)}}},$d={type:_e.CHN_WEEK3,priority:810,match:n=>Ud(`${n==null?void 0:n.v}`||""),isContinue:(n,r)=>n.type===_e.CHN_WEEK3,applyFunctions:{[le.SERIES]:(n,r,e)=>{var l;const{data:t}=n,o=e===a.Direction.LEFT||e===a.Direction.UP;if(t.length===1){let c;return o?c=-1:c=1,Ue(Rn(t,r,c,2),o)}const i=[];let s=0;for(let c=0;c<t.length;c++){const d=`${(l=t[c])==null?void 0:l.v}`;if(d){const u=d.substr(d.length-1,1);d==="星期日"?c===0?i.push(0):(s++,i.push(s*7)):i.push(ct(u)+s*7)}}if(o&&(t.reverse(),i.reverse()),uo(i)){const c=i[1]-i[0];return Ue(Rn(t,r,c,2),o)}return jt(t,r)}}},eu={type:_e.LOOP_SERIES,priority:800,match:n=>Yd(`${n==null?void 0:n.v}`||""),isContinue:(n,r)=>{var e;return n.type===_e.LOOP_SERIES?Yr(`${(e=n.cellData)==null?void 0:e.v}`||"").name===Yr(`${r==null?void 0:r.v}`||"").name:!1},applyFunctions:{[le.SERIES]:(n,r,e)=>{var c,d;const{data:t}=n,o=e===a.Direction.LEFT||e===a.Direction.UP,{series:i}=Yr(`${(c=t[0])==null?void 0:c.v}`||"");if(t.length===1){let u;return o?u=-1:u=1,Ue(Js(t,r,u,i),o)}const s=[];let l=0;for(let u=0;u<t.length;u++){const h=`${(d=t[u])==null?void 0:d.v}`;h&&(h===i[0]?u===0?s.push(0):(l++,s.push(l*i.length)):s.push(i.indexOf(h)+l*7))}if(o&&(t.reverse(),s.reverse()),uo(s)){const u=s[1]-s[0];return Ue(Js(t,r,u,i),o)}return jt(t,r)}}};function Ue(n,r){return r?n.reverse():n}var tu=Object.getOwnPropertyDescriptor,nu=(n,r,e,t)=>{for(var o=t>1?void 0:t?tu(r,e):r,i=n.length-1,s;i>=0;i--)(s=n[i])&&(o=s(o)||o);return o},rn=(n,r)=>(e,t)=>r(e,t,n);exports.AutoFillService=class extends a.Disposable{constructor(e,t,o,i,s,l){super();E(this,"_rules",[]);E(this,"_hooks",[]);E(this,"_applyType$",new O.BehaviorSubject(le.SERIES));E(this,"_isFillingStyle",!0);E(this,"_prevUndos",[]);E(this,"_autoFillLocation$",new O.BehaviorSubject(null));E(this,"autoFillLocation$",this._autoFillLocation$.asObservable());E(this,"_showMenu$",new O.BehaviorSubject(!1));E(this,"showMenu$",this._showMenu$.asObservable());E(this,"_direction",a.Direction.DOWN);E(this,"applyType$",this._applyType$.asObservable());E(this,"_menu$",new O.BehaviorSubject([{label:"autoFill.copy",value:le.COPY,disable:!1},{label:"autoFill.series",value:le.SERIES,disable:!1},{label:"autoFill.formatOnly",value:le.ONLY_FORMAT,disable:!1},{label:"autoFill.noFormat",value:le.NO_FORMAT,disable:!1}]));E(this,"menu$",this._menu$.asObservable());this._commandService=e,this._undoRedoService=t,this._renderManagerService=o,this._univerInstanceService=i,this._selectionManagerService=s,this._injector=l,this._init()}_init(){this._rules=[Zd,Kd,qd,Qd,Jd,$d,eu,el].sort((e,t)=>t.priority-e.priority),this._isFillingStyle=!0}_getOneByPriority(e){return e.length<=0?[]:[e.reduce((o,i)=>(i.priority||0)>(o.priority||0)?i:o,e[0])]}_initPrevUndo(){this._prevUndos=[]}async triggerAutoFill(e,t,o,i){var S;if(o.startColumn===i.startColumn&&o.startRow===i.startRow&&o.endColumn===i.endColumn&&o.endRow===i.endRow)return!1;if(i.endColumn<o.endColumn&&i.endColumn>o.startColumn)return this._commandService.executeCommand(En.id,{clearRange:{startRow:i.startRow,endRow:i.endRow,startColumn:i.endColumn+1,endColumn:o.endColumn},selectionRange:i});if(i.endRow<o.endRow&&i.endRow>o.startRow)return this._commandService.executeCommand(En.id,{clearRange:{startRow:i.endRow+1,endRow:o.endRow,startColumn:i.startColumn,endColumn:i.endColumn},selectionRange:i});const s={startRow:i.startRow,endRow:i.endRow,startColumn:i.startColumn,endColumn:i.endColumn};let l=null;if(i.startRow<o.startRow)l=a.Direction.UP,s.endRow=o.startRow-1;else if(i.endRow>o.endRow)l=a.Direction.DOWN,s.startRow=o.endRow+1;else if(i.startColumn<o.startColumn)l=a.Direction.LEFT,s.endColumn=o.startColumn-1;else if(i.endColumn>o.endColumn)l=a.Direction.RIGHT,s.startColumn=o.endColumn+1;else return!1;this.direction=l;const c=this._injector.invoke(f=>Sn(o,f)),d=this._injector.invoke(f=>Sn(s,f));if(!c||!d)return!1;this.autoFillLocation={source:c,target:d,unitId:e,subUnitId:t};const u=[];this.getActiveHooks().forEach(f=>{var v;const p=(v=f==null?void 0:f.onBeforeFillData)==null?void 0:v.call(f,{source:c,target:d,unitId:e,subUnitId:t},l);p&&u.unshift(p)}),this._initPrevUndo();for(let f=0;f<u.length;f++){const p=this.menu.find(v=>v.value===u[f]);if(p&&!p.disable)return this.fillData(u[f])}const g=(S=this.menu.find(f=>f.disable===!1))==null?void 0:S.value;return g?this.fillData(g):!1}addHook(e){if(this._hooks.find(t=>t.id===e.id))throw new Error(`Add hook failed, hook id '${e.id}' already exist!`);return e.priority===void 0&&(e.priority=0),e.type===void 0&&(e.type=mn.Append),this._hooks.push(e),a.toDisposable(()=>{const t=this._hooks.findIndex(o=>o===e);t>-1&&this._hooks.splice(t,1)})}registerRule(e){if(this._rules.find(o=>o.type===e.type))throw new Error(`Registry rule failed, type '${e.type}' already exist!`);const t=this._rules.findIndex(o=>o.priority<e.priority);this._rules.splice(t===-1?this._rules.length:t,0,e)}getRules(){return this._rules}getAllHooks(){return this._hooks}getActiveHooks(){const{source:e,target:t,unitId:o,subUnitId:i}=this.autoFillLocation||{};if(!e||!t||!o||!i)return[];const s=this._hooks.filter(u=>{var h;return!((h=u.disable)!=null&&h.call(u,{source:e,target:t,unitId:o,subUnitId:i},this._direction,this.applyType))}),l=s.filter(u=>u.type===mn.Only);if(l.length>0)return this._getOneByPriority(l);const c=this._getOneByPriority(s.filter(u=>u.type===mn.Default)),d=s.filter(u=>u.type===mn.Append)||[];return[...c,...d]}get applyType(){return this._applyType$.getValue()}set applyType(e){this._applyType$.next(e)}get menu(){return this._menu$.getValue()}get direction(){return this._direction}set direction(e){this._direction=e}isFillingStyle(){return this._isFillingStyle}setFillingStyle(e){this._isFillingStyle=e}get autoFillLocation(){return this._autoFillLocation$.getValue()}set autoFillLocation(e){this._autoFillLocation$.next(e)}setDisableApplyType(e,t){this._menu$.next(this._menu$.getValue().map(o=>o.value===e?{...o,disable:t}:o))}setShowMenu(e){this._showMenu$.next(e)}fillData(e){var C,b,R;this.applyType=e;const{source:t,target:o,unitId:i=this._univerInstanceService.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET).getUnitId(),subUnitId:s=(C=this._univerInstanceService.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET).getActiveSheet())==null?void 0:C.getSheetId()}=this.autoFillLocation||{};if(!t||!o||!i||!s)return!1;const l=this.direction;this._prevUndos.length>0&&this._prevUndos.forEach(T=>{this._commandService.syncExecuteCommand(T.id,T.params)}),this._prevUndos=[];const c=a.Rectangle.union(Et(t),Et(o)),d=this.getActiveHooks(),u=this._univerInstanceService.getUnit(i,a.UniverInstanceType.UNIVER_SHEET);this._commandService.syncExecuteCommand(m.SetSelectionsOperation.id,{selections:[{primary:{...(R=(b=this._selectionManagerService.getCurrentLastSelection())==null?void 0:b.primary)!=null?R:c},range:{...c,rangeType:a.RANGE_TYPE.NORMAL}}],unitId:i,subUnitId:s});const h=[],g=[];d.forEach(T=>{var P;const{undos:M,redos:y}=((P=T.onFillData)==null?void 0:P.call(T,{source:t,target:o,unitId:i,subUnitId:s},l,e))||{};M&&h.push(...M),y&&g.push(...y)});const S=g.every(T=>this._commandService.syncExecuteCommand(T.id,T.params)),f=[];e!==le.NO_FORMAT&&g.forEach(T=>{if(T.id===m.SetRangeValuesMutation.id){const{cellValue:M}=T.params;new a.ObjectMatrix(M).forValue((P,x,A)=>{const k=Object.keys(u.getStyles().get(A==null?void 0:A.s)||{});(A!=null&&A.p||k.length&&fs.some(N=>k.includes(N)))&&f.push({startRow:P,endRow:P,startColumn:x,endColumn:x})})}});const p=this._getAutoHeightUndoRedos(i,s,f);return p.redos.every(T=>this._commandService.syncExecuteCommand(T.id,T.params))&&(h.push(...p.undos),g.push(...p.redos)),S&&(this._prevUndos=h,this._undoRedoService.pushUndoRedo({unitID:i,undoMutations:h,redoMutations:g})),d.forEach(T=>{var M;(M=T.onAfterFillData)==null||M.call(T,{source:t,target:o,unitId:i,subUnitId:s},l,e)}),this.setShowMenu(!0),!0}_getAutoHeightUndoRedos(e,t,o){var h,g;const i=(h=this._renderManagerService.getRenderById(e))==null?void 0:h.with(exports.SheetSkeletonManagerService),s=(g=i==null?void 0:i.getCurrentParam())==null?void 0:g.skeleton;if(!s)return{redos:[],undos:[]};const l=s.calculateAutoHeightInRange(o),c={subUnitId:t,unitId:e,rowsAutoHeightInfo:l},d=s.worksheet,u=m.SetWorksheetRowAutoHeightMutationFactory(c,d);return{undos:[{id:m.SetWorksheetRowAutoHeightMutation.id,params:u}],redos:[{id:m.SetWorksheetRowAutoHeightMutation.id,params:c}]}}};exports.AutoFillService=nu([rn(0,a.ICommandService),rn(1,a.IUndoRedoService),rn(2,w.IRenderManagerService),rn(3,a.Inject(a.IUniverInstanceService)),rn(4,a.Inject(m.SheetsSelectionsService)),rn(5,a.Inject(a.Injector))],exports.AutoFillService);const Tt=a.createIdentifier("univer.auto-fill-service"),Ct={type:a.CommandType.COMMAND,id:"sheet.command.auto-fill",handler:async(n,r)=>{const e=n.get(Tt),t=n.get(a.IUniverInstanceService),{sourceRange:o,targetRange:i}=r,s=m.getSheetCommandTarget(t);if(!s)return!1;const{subUnitId:l,unitId:c}=s;return e.triggerAutoFill(c,l,o,i)}},En={id:"sheet.command.auto-clear-content",type:a.CommandType.COMMAND,handler:async(n,r)=>{const e=n.get(a.IUniverInstanceService),t=n.get(a.ICommandService),o=n.get(a.IUndoRedoService),i=n.get(m.SheetInterceptorService),s=m.getSheetCommandTarget(e);if(!s)return!1;const{unitId:l,subUnitId:c}=s,{clearRange:d,selectionRange:u}=r,h={subUnitId:c,unitId:l,cellValue:m.generateNullCellValue([d])},g=m.SetRangeValuesUndoMutationFactory(n,h),{startColumn:S,startRow:f}=u,p={selections:[{primary:{startColumn:S,startRow:f,endColumn:S,endRow:f,actualRow:f,actualColumn:S,isMerged:!1,isMergedMainCell:!1},range:{...u}}],unitId:l,subUnitId:c};if(t.executeCommand(m.SetSelectionsOperation.id,p),t.syncExecuteCommand(m.SetRangeValuesMutation.id,h)){const C=i.afterCommandExecute({id:m.SetRangeValuesMutation.id,params:h});return a.sequenceExecute(C.redos,t),o.pushUndoRedo({unitID:l,undoMutations:[{id:m.SetRangeValuesMutation.id,params:g},...C.undos],redoMutations:[{id:m.SetRangeValuesMutation.id,params:h},...C.redos]}),!0}return!1}},ho={id:"sheet.command.refill",type:a.CommandType.COMMAND,handler:async(n,r)=>n.get(Tt).fillData(r.type)};var ou=Object.getOwnPropertyDescriptor,ru=(n,r,e,t)=>{for(var o=t>1?void 0:t?ou(r,e):r,i=n.length-1,s;i>=0;i--)(s=n[i])&&(o=s(o)||o);return o},Pt=(n,r)=>(e,t)=>r(e,t,n);exports.EditorBridgeService=class extends a.Disposable{constructor(e,t,o,i,s,l,c){super();E(this,"_editorUnitId",a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY);E(this,"_editorIsDirty",!1);E(this,"_isDisabled",!1);E(this,"_visible",{visible:!1,eventType:w.DeviceInputEventType.Dblclick,unitId:""});E(this,"_currentEditCell",null);E(this,"_currentEditCellState",null);E(this,"_currentEditCellLayout",null);E(this,"_currentEditCellState$",new O.BehaviorSubject(null));E(this,"currentEditCellState$",this._currentEditCellState$.asObservable());E(this,"_currentEditCellLayout$",new O.BehaviorSubject(null));E(this,"currentEditCellLayout$",this._currentEditCellLayout$.asObservable());E(this,"currentEditCell$",this._currentEditCellState$.pipe(O.switchMap(e=>this._currentEditCellLayout$.pipe(O.map(t=>e&&t?{...e,...t}:null)))));E(this,"_visible$",new O.BehaviorSubject(this._visible));E(this,"visible$",this._visible$.asObservable());E(this,"_afterVisible$",new O.BehaviorSubject(this._visible));E(this,"afterVisible$",this._afterVisible$.asObservable());E(this,"_forceKeepVisible$",new O.BehaviorSubject(!1));E(this,"forceKeepVisible$",this._forceKeepVisible$.asObservable());this._sheetInterceptorService=e,this._renderManagerService=t,this._themeService=o,this._univerInstanceService=i,this._editorService=s,this._refSelectionsService=l,this._contextService=c,this.disposeWithMe(a.toDisposable(()=>{this._currentEditCellState$.complete(),this._currentEditCell=null})),this._univerInstanceService.getTypeOfUnitDisposed$(a.UniverInstanceType.UNIVER_SHEET).subscribe(d=>{var u;d.getUnitId()===((u=this._currentEditCellState)==null?void 0:u.unitId)&&this._clearCurrentEditCellState()})}refreshEditCellState(){const e=this.getLatestEditCellState();if(!e){this._currentEditCellState=null,this._currentEditCellLayout=null,this._currentEditCellState$.next(null),this._currentEditCellLayout$.next(null);return}const{position:t,scaleX:o,scaleY:i,canvasOffset:s,...l}=e;this._currentEditCellState=l,this._currentEditCellLayout={position:t,scaleX:o,scaleY:i,canvasOffset:s},this._currentEditCellState$.next(this._currentEditCellState),this._currentEditCellLayout$.next(this._currentEditCellLayout)}refreshEditCellPosition(e){var y;const t=this._currentEditCell;if(t==null)return;const o=this._renderManagerService.getCurrentTypeOfRenderer(a.UniverInstanceType.UNIVER_SHEET);if(!o)return;const i=(y=o.with(exports.SheetSkeletonManagerService).getSkeletonParam(t.sheetId))==null?void 0:y.skeleton,s=o.with(ve);if(!i||!this._currentEditCellState)return;const{primary:l,unitId:c,sheetId:d,scene:u,engine:h}=t,g=$n(i,l);if(g==null)return;const S=a.convertCellToRange(g),f=$.getCanvasOffsetByEngine(h);let{startX:p,startY:v,endX:C,endY:b}=S;const{scaleX:R,scaleY:T}=u.getAncestorScale(),M=u.getViewportScrollXY(s.getViewPort());p=w.convertTransformToOffsetX(p,R,M),v=w.convertTransformToOffsetY(v,T,M),C=w.convertTransformToOffsetX(C,R,M),b=w.convertTransformToOffsetY(b,T,M),e&&this._currentEditCellLayout&&(C=C-p+this._currentEditCellLayout.position.startX,b=b-v+this._currentEditCellLayout.position.startY,p=this._currentEditCellLayout.position.startX,v=this._currentEditCellLayout.position.startY),this._currentEditCellLayout={position:{startX:p,startY:v,endX:C,endY:b},canvasOffset:f,scaleX:R,scaleY:T},this._currentEditCellLayout$.next(this._currentEditCellLayout)}setEditCell(e){this._currentEditCell=e,this._editorService.getFocusEditor()||(this._editorService.focus(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY),this._contextService.setContextValue(a.EDITOR_ACTIVATED,!1),this._contextService.setContextValue(a.FOCUSING_EDITOR_STANDALONE,!1));const t=this.getLatestEditCellState();if(!t){this._currentEditCellState=t,this._currentEditCellLayout=t,this._currentEditCellState$.next(t),this._currentEditCellLayout$.next(t);return}const{position:o,canvasOffset:i,scaleX:s,scaleY:l,...c}=t;this._currentEditCellState=c,this._currentEditCellLayout={position:o,canvasOffset:i,scaleX:s,scaleY:l},this._currentEditCellState$.next(this._currentEditCellState),this._currentEditCellLayout$.next(this._currentEditCellLayout)}_clearCurrentEditCellState(){this._currentEditCellState=null,this._currentEditCellState$.next(null),this._currentEditCellLayout=null,this._currentEditCellLayout$.next(null)}getEditCellState(){return this._currentEditCellState==null||this._currentEditCellLayout==null?null:{...this._currentEditCellState,...this._currentEditCellLayout}}getEditCellLayout(){return this._currentEditCellLayout}getEditLocation(){return this._currentEditCellState}updateEditLocation(e,t){this._currentEditCellState&&(this._currentEditCellState={...this._currentEditCellState,row:e,column:t})}getLatestEditCellState(){var W,H,U;const e=this._currentEditCell;if(e==null)return;const t=this._renderManagerService.getCurrentTypeOfRenderer(a.UniverInstanceType.UNIVER_SHEET);if(!t)return;const o=t.with(exports.SheetSkeletonManagerService).getCurrentSkeleton(),i=t.with(ve);if(!o)return;const{primary:s,unitId:l,sheetId:c,scene:d,engine:u}=e,{startRow:h,startColumn:g}=s,S=$n(o,s);if(S==null)return;const f=a.convertCellToRange(S),p=$.getCanvasOffsetByEngine(u);let{startX:v,startY:C,endX:b,endY:R}=f;const{scaleX:T,scaleY:M}=d.getAncestorScale(),y=d.getViewportScrollXY(i.getViewPort());v=w.convertTransformToOffsetX(v,T,y),C=w.convertTransformToOffsetY(C,M,y),b=w.convertTransformToOffsetX(b,T,y),R=w.convertTransformToOffsetY(R,M,y);const P=this._univerInstanceService.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET),x=P.getActiveSheet();if(!x)return;const A={workbook:P,worksheet:x,unitId:P.getUnitId(),subUnitId:x.getSheetId(),row:h,col:g,origin:x.getCellRaw(h,g)};let k;const N=this._sheetInterceptorService.writeCellInterceptor.fetchThroughInterceptors(m.BEFORE_CELL_EDIT)(x.getCell(h,g),A);k=N&&o.getCellDocumentModelWithFormula(N);const D=(W=k==null?void 0:k.documentModel)==null?void 0:W.documentStyle.renderConfig;if(D!=null&&(D.cellValueType=a.CellValueType.STRING),!k||k.documentModel==null){const B=o.getBlankCellDocumentModel(N);if(k!=null){const{verticalAlign:F,horizontalAlign:L,wrapStrategy:j,textRotation:z,fill:q}=k,{centerAngle:te,vertexAngle:Q}=w.convertTextRotation(z);B.documentModel.documentStyle.renderConfig={...D,verticalAlign:F,horizontalAlign:L,wrapStrategy:j,background:{rgb:q},centerAngle:te,vertexAngle:Q}}k=B}if(k.fill=k.fill||"#fff",(H=k.documentModel)==null||H.setZoomRatio(Math.max(T,M)),(N==null?void 0:N.isInArrayFormulaRange)===!0){const B=(U=k.documentModel)==null?void 0:U.getBody();B&&(B.textRuns=[{st:0,ed:B.dataStream.length-2,ts:{cl:{rgb:this._themeService.getCurrentTheme().textColorSecondary}}}])}return{position:{startX:v,startY:C,endX:b,endY:R},scaleX:T,scaleY:M,canvasOffset:p,row:h,column:g,unitId:l,sheetId:c,documentLayoutObject:k,editorUnitId:this._editorUnitId,isInArrayFormulaRange:N==null?void 0:N.isInArrayFormulaRange}}getCurrentEditorId(){return this._editorUnitId}changeVisible(e){this._visible=e,e.visible&&(this._editorIsDirty=!1),this._visible$.next(this._visible),this._afterVisible$.next(this._visible)}isVisible(){return this._visible}enableForceKeepVisible(){this._forceKeepVisible$.next(!0)}disableForceKeepVisible(){this._forceKeepVisible$.next(!1)}isForceKeepVisible(){return this._forceKeepVisible$.getValue()}changeEditorDirty(e){this._editorIsDirty=e}getEditorDirty(){return this._editorIsDirty}};exports.EditorBridgeService=ru([Pt(0,a.Inject(m.SheetInterceptorService)),Pt(1,w.IRenderManagerService),Pt(2,a.Inject(a.ThemeService)),Pt(3,a.IUniverInstanceService),Pt(4,$.IEditorService),Pt(5,m.IRefSelectionsService),Pt(6,a.IContextService)],exports.EditorBridgeService);const Se=a.createIdentifier("univer.sheet-editor-bridge.service"),Ce={id:"sheet.operation.set-cell-edit-visible",type:a.CommandType.OPERATION,handler:(n,r)=>r?(n.get(Se).changeVisible(r),!0):!1},mo={id:"sheet.operation.set-cell-edit-visible-f2",type:a.CommandType.OPERATION,handler:(n,r)=>{const e=n.get(a.ICommandService),o=n.get(a.IUniverInstanceService).getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET);return o?(e.syncExecuteCommand(Ce.id,{...r,unitId:o.getUnitId()}),!0):!1}},Xt={id:"sheet.operation.set-cell-edit-visible-arrow",type:a.CommandType.OPERATION,handler:()=>!0},kn={id:"sheet.command.change-zoom-ratio",type:a.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;const e=n.get(a.IUniverInstanceService),t=m.getSheetCommandTarget(e);if(!t)return!1;const{worksheet:o,subUnitId:i,unitId:s}=t,{delta:l,reset:c}=r;let d=c?100:Math.round((o.getConfig().zoomRatio+l)*100);d=Math.max(Di[0],d),d=Math.min(Di[1],d);const u=d/100,g=n.get(Se).isVisible();return(g.unitId===s||g.unitId===a.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY)&&g.visible?!1:n.get(a.ICommandService).executeCommand(Le.id,{unitId:s,subUnitId:i,zoomRatio:u})}},Nn={id:"sheet.command.set-zoom-ratio",type:a.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;const{unitId:e,subUnitId:t,zoomRatio:o}=r,s=n.get(Se).isVisible();return(s.unitId===e||s.unitId===a.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY)&&s.visible?!1:n.get(a.ICommandService).executeCommand(Le.id,{unitId:e,subUnitId:t,zoomRatio:o})}};function iu(n){return typeof n.isMainScene>"u"}function Ge(n,r){const e=n instanceof a.Workbook?n:n.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET);if(!e)return null;const t=e.getUnitId();let o,i,s,l;if(iu(r)){const g=r.getRenderById(t);if(g==null)return null;o=g.components,o=g.components,i=g.mainComponent,s=g.scene,l=g.engine}else o=r.components,i=r.mainComponent,s=r.scene,l=r.engine;if(!o||!i)return null;const c=i,d=o.get(me.ROW),u=o.get(me.COLUMN),h=o.get(me.LEFT_TOP);return{spreadsheet:c,spreadsheetRowHeader:d,spreadsheetColumnHeader:u,spreadsheetLeftTopPlaceholder:h,scene:s,engine:l}}function Bi(n,r,e,t){const{startX:o,startY:i,endX:s,endY:l}=t.getCellWithCoordByIndex(n,r);return{startX:o,startY:i,endX:s,endY:l}}function qe(n,r,e,t,o,i){const s=e.getCoordRelativeToViewport(w.Vector2.FromArray([n,r])),{x:l,y:c}=s,d=e.getScrollXYInfoByViewport(s,o),{scaleX:u,scaleY:h}=e.getAncestorScale(),g=t.getCellIndexByOffset(l,c,u,h,d,{closeFirst:i}),{row:S,column:f}=g,p=t.getNoMergeCellWithCoordByIndex(S,f),{startX:v,startY:C,endX:b,endY:R}=p;return{startX:v,startY:C,endX:b,endY:R,row:S,column:f}}function Qn(n,r,e,t){const o=e.getCoordRelativeToViewport(w.Vector2.FromArray([n,r])),i=e.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN),s=e.getScrollXYInfoByViewport(o,i),{scaleX:l,scaleY:c}=e.getAncestorScale(),{x:d,y:u}=s,h=n/l+d,g=r/c+u;return{x:h,y:g}}var su=Object.getOwnPropertyDescriptor,au=(n,r,e,t)=>{for(var o=t>1?void 0:t?su(r,e):r,i=n.length-1,s;i>=0;i--)(s=n[i])&&(o=s(o)||o);return o},Lo=(n,r)=>(e,t)=>r(e,t,n);let eo=class extends a.Disposable{constructor(r,e,t,o,i){super();E(this,"_zoom");this._context=r,this._sheetSkeletonManagerService=e,this._commandService=t,this._contextService=o,this._editorBridgeService=i,this._initSkeletonListener(),this._initZoomEventListener()}updateZoom(r,e){const t=this._context.unit.getSheetBySheetId(r);return t?(t.getConfig().zoomRatio=e,t===this._context.unit.getActiveSheet()&&this._updateViewZoom(e),!0):!1}_initZoomEventListener(){const r=this._getSheetObject().scene;this.disposeWithMe(r.onMouseWheel$.subscribeEvent(e=>{if(!e.ctrlKey||!this._contextService.getContextValue(a.FOCUSING_SHEET))return;if(this._editorBridgeService){const d=this._editorBridgeService.isVisible();if((d.unitId===this._context.unitId||d.unitId===a.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY)&&d.visible)return}const t=Math.abs(e.deltaX);let o=t<40?.2:t<80?.4:.2;o*=e.deltaY>0?-1:1,r.scaleX<1&&(o/=2);const i=this._context.unit,s=i.getActiveSheet();if(!s)return;const l=s.getZoomRatio();let c=+Number.parseFloat(`${l+o}`).toFixed(1);c=c>=4?4:c<=.1?.1:c,this._commandService.executeCommand(Nn.id,{zoomRatio:Math.round(c*10)/10,unitId:i.getUnitId(),subUnitId:s.getSheetId()}),e.preventDefault()}))}_initSkeletonListener(){this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(r=>{if(r==null)return;const t=this._context.unit.getActiveSheet();if(!t)return;const o=t.getZoomRatio()||1;this._zoom!==o&&this._updateViewZoom(o),this._zoom=o}))}_updateViewZoom(r){const e=this._getSheetObject();e==null||e.scene.scale(r,r),e==null||e.spreadsheet.makeForceDirty()}_getSheetObject(){return Ge(this._context.unit,this._context)}};eo=au([Lo(1,a.Inject(exports.SheetSkeletonManagerService)),Lo(2,a.ICommandService),Lo(3,a.IContextService),Lo(4,a.Optional(Se))],eo);const Le={id:"sheet.operation.set-zoom-ratio",type:a.CommandType.OPERATION,handler:(n,r)=>{const t=n.get(w.IRenderManagerService).getRenderById(r.unitId);return t?t.with(eo).updateZoom(r.subUnitId,r.zoomRatio):!1}};var lu=Object.getOwnPropertyDescriptor,cu=(n,r,e,t)=>{for(var o=t>1?void 0:t?lu(r,e):r,i=n.length-1,s;i>=0;i--)(s=n[i])&&(o=s(o)||o);return o},Gr=(n,r)=>(e,t)=>r(e,t,n);const ea="univer-sheet-main-canvas";exports.SheetsRenderService=class extends a.RxDisposable{constructor(e,t,o){super();E(this,"_skeletonChangeMutations",new Set);this._contextService=e,this._instanceSrv=t,this._renderManagerService=o,Promise.resolve().then(()=>this._init())}registerSkeletonChangingMutations(e){return this._skeletonChangeMutations.has(e)?a.toDisposable(()=>{}):(this._skeletonChangeMutations.add(e),a.toDisposable(()=>this._skeletonChangeMutations.delete(e)))}checkMutationShouldTriggerRerender(e){return this._skeletonChangeMutations.has(e)}_init(){this._initWorkbookListener(),this._initContextListener()}_initWorkbookListener(){this._instanceSrv.getTypeOfUnitAdded$(a.UniverInstanceType.UNIVER_SHEET).pipe(O.takeUntil(this.dispose$)).subscribe(e=>this._createRenderer(e)),this._instanceSrv.getAllUnitsForType(a.UniverInstanceType.UNIVER_SHEET).forEach(e=>this._createRenderer(e)),this._instanceSrv.getTypeOfUnitDisposed$(a.UniverInstanceType.UNIVER_SHEET).pipe(O.takeUntil(this.dispose$)).subscribe(e=>this._disposeRenderer(e)),this.disposeWithMe(this._instanceSrv.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET).subscribe(e=>{e&&this._renderManagerService.setCurrent(e.getUnitId())}))}_createRenderer(e){const t=e.getUnitId();this._renderManagerService.created$.subscribe(o=>{o.unitId===t&&(o.engine.getCanvas().setId(`${ea}_${t}`),o.engine.getCanvas().getContext().setId(`${ea}_${t}`))}),this._renderManagerService.createRender(t)}_disposeRenderer(e){const t=e.getUnitId();this._renderManagerService.removeRender(t)}_initContextListener(){this.disposeWithMe(this._contextService.subscribeContextValue$(w.RENDER_RAW_FORMULA_KEY).pipe(O.distinctUntilChanged()).subscribe(()=>{this._renderManagerService.getRenderAll().forEach(e=>{e.mainComponent instanceof w.Spreadsheet&&e.mainComponent.makeForceDirty(!0)})}))}};exports.SheetsRenderService=cu([Gr(0,a.IContextService),Gr(1,a.IUniverInstanceService),Gr(2,w.IRenderManagerService)],exports.SheetsRenderService);var du=Object.getOwnPropertyDescriptor,uu=(n,r,e,t)=>{for(var o=t>1?void 0:t?du(r,e):r,i=n.length-1,s;i>=0;i--)(s=n[i])&&(o=s(o)||o);return o},Ot=(n,r)=>(e,t)=>r(e,t,n);exports.AutoFillController=class extends a.Disposable{constructor(e,t,o,i,s,l,c){super();E(this,"_beforeApplyData",[]);E(this,"_currentLocation",null);E(this,"_copyData",[]);E(this,"_defaultHook");this._univerInstanceService=e,this._commandService=t,this._autoFillService=o,this._editorBridgeService=i,this._renderManagerService=s,this._injector=l,this._sheetsRenderService=c,this._defaultHook={id:"default",type:mn.Default,priority:0,onBeforeFillData:(d,u)=>this._presetAndCacheData(d,u),onFillData:(d,u,h)=>this._fillData(d,u,h)},this._init()}_init(){this._initDefaultHook(),this._initSelectionControlFillChanged(),this._initQuitListener(),this._initSkeletonChange()}_initSkeletonChange(){this.disposeWithMe(this._sheetsRenderService.registerSkeletonChangingMutations(Ct.id))}_initDefaultHook(){this.disposeWithMe(this._autoFillService.addHook(this._defaultHook))}_initQuitListener(){const e=[Ce.id,En.id,m.SetRangeValuesCommand.id,Le.id,m.SetWorksheetActiveOperation.id,m.MoveRangeMutation.id,m.RemoveRowMutation.id,m.RemoveColMutation.id,m.InsertRowMutation.id,m.InsertColMutation.id,m.MoveRowsMutation.id,m.MoveColsMutation.id,m.SetWorksheetColWidthMutation.id,m.SetWorksheetRowHeightMutation.id,m.SetRangeValuesMutation.id];this.disposeWithMe(this._commandService.onCommandExecuted((t,o)=>{var c,d;const i=o==null?void 0:o.fromCollab,s=o==null?void 0:o.fromSync,l=o==null?void 0:o.fromFormula;e.includes(t.id)&&!i&&!s&&!l&&t.params.trigger!==Ct.id&&t.params.trigger!==ho.id&&this._quit(),t.id===m.RemoveSheetMutation.id&&t.params.unitId===((c=this._currentLocation)==null?void 0:c.unitId)&&t.params.subUnitId===((d=this._currentLocation)==null?void 0:d.subUnitId)&&this._quit()})),this.disposeWithMe(this._univerInstanceService.unitDisposed$.subscribe(t=>{var o;t.getUnitId()===((o=this._currentLocation)==null?void 0:o.unitId)&&this._quit()}))}_quit(){this._currentLocation=null,this._beforeApplyData=[],this._copyData=[],this._autoFillService.setShowMenu(!1)}_initSelectionControlFillChanged(){const e=new a.DisposableCollection,t=()=>{e.dispose();const o=this._renderManagerService.getCurrentTypeOfRenderer(a.UniverInstanceType.UNIVER_SHEET);if(!o)return;o.with(ve).getSelectionControls().forEach(l=>{e.add(l.selectionFilled$.subscribe(c=>{if(c==null||c.startColumn===-1||c.startRow===-1||c.endColumn===-1||c.endRow===-1)return;const d={startColumn:l.model.startColumn,endColumn:l.model.endColumn,startRow:l.model.startRow,endRow:l.model.endRow},u={startColumn:c.startColumn,endColumn:c.endColumn,startRow:c.startRow,endRow:c.endRow};this._commandService.executeCommand(Ct.id,{sourceRange:d,targetRange:u})})),e.add(l.fillControl.onDblclick$.subscribeEvent(()=>{const c={startColumn:l.model.startColumn,endColumn:l.model.endColumn,startRow:l.model.startRow,endRow:l.model.endRow};this._handleDbClickFill(c)})),e.add(l.fillControl.onPointerDown$.subscribeEvent(()=>{this._editorBridgeService.isVisible().visible&&this._commandService.syncExecuteCommand(Ce.id,{visible:!1,eventType:w.DeviceInputEventType.PointerDown,unitId:o.unitId})}))})};t(),this.disposeWithMe(this._commandService.onCommandExecuted(o=>{o.id===m.SetSelectionsOperation.id&&t()})),this.disposeWithMe(this._univerInstanceService.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET).subscribe(()=>t()))}_handleDbClickFill(e){const t=this._detectFillRange(e);t.endRow<=e.endRow||this._commandService.executeCommand(Ct.id,{sourceRange:e,targetRange:t})}_detectFillRange(e){var g,S,f,p,v,C;const{startRow:t,endRow:o,startColumn:i,endColumn:s}=e,l=(g=this._univerInstanceService.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET))==null?void 0:g.getActiveSheet();if(!l)return e;const c=l.getCellMatrix(),d=l.getMaxRows()-1,u=l.getMaxColumns()-1;let h=o;if(i>0&&((S=c.getValue(t,i-1))==null?void 0:S.v)!=null){let b=t;for(;((f=c.getValue(b,i-1))==null?void 0:f.v)!=null&&b<d;)b+=1;h=b-1}else if(s<u&&((p=c.getValue(o,s+1))==null?void 0:p.v)!=null){let b=t;for(;((v=c.getValue(b,s+1))==null?void 0:v.v)!=null&&b<d;)b+=1;h=b-1}for(let b=o+1;b<=h;b++)for(let R=i;R<=s;R++)if(((C=c.getValue(b,R))==null?void 0:C.v)!=null){h=b-1;break}return{startColumn:i,endColumn:s,startRow:t,endRow:h}}_getApplyData(e,t,o,i,s,l=!0){const c=[],d=Math.floor(o/t),u=o%t,h=this._autoFillService.getRules();if(!l&&s===le.ONLY_FORMAT)return console.error("ERROR: only format can not be applied when hasStyle is false"),[];const g={};h.forEach(S=>{g[S.type]=[]}),h.forEach(S=>{const{type:f,applyFunctions:p={}}=S,v=e[f];v&&v.forEach(C=>{const b=Ld(C.index,u),R=C.index.length*d+b,T=this._applyFunctions(C,R,i,s,p,e),M=Bd(t,o,C.index);g[f].push({data:T,index:M})})});for(let S=0;S<o;S++)h.forEach(f=>{const{type:p}=f,v=g[p];for(let C=0;C<v.length;C++)S in v[C].index&&c.push(v[C].data[v[C].index[S]])});return c}_applyFunctions(e,t,o,i,s,l){const{data:c}=e,d=o===a.Direction.UP||o===a.Direction.LEFT;if(i===le.COPY){const u=s==null?void 0:s[le.COPY];return u?u(e,t,o,l):(d&&c.reverse(),jt(c,t))}if(i===le.SERIES){const u=s==null?void 0:s[le.SERIES];return u?u(e,t,o,l):(d&&c.reverse(),s!=null&&s[le.COPY]?s[le.COPY](e,t,o,l):jt(c,t))}if(i===le.ONLY_FORMAT){const u=s==null?void 0:s[le.ONLY_FORMAT];return u?u(e,t,o,l):Fd(c,t)}}_getCopyData(e,t){const o=this._univerInstanceService.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET).getActiveSheet();if(!o)throw new Error("No active sheet found");const i=o.getCellMatrix(),s=this._autoFillService.getRules(),l=[],c=t===a.Direction.DOWN||t===a.Direction.UP;let d,u;return c?(d=e.cols,u=e.rows):(d=e.rows,u=e.cols),d.forEach(h=>{const g=this._getEmptyCopyDataPiece(),S={type:void 0,cellData:void 0};u.forEach(f=>{let p;c?p=i.getValue(f,h):p=i.getValue(h,f);const{type:v,isContinue:C}=s.find(b=>b.match(p,this._injector))||el;if(C(S,p)){const b=g[v],R=b[b.length-1];R.data.push(p),R.index.push(f-u[0])}else{const b=g[v];b?b.push({data:[p],index:[f-u[0]]}):g[v]=[{data:[p],index:[f-u[0]]}]}S.type=v,S.cellData=p}),l.push(g)}),l}_getEmptyCopyDataPiece(){const e={};return this._autoFillService.getRules().forEach(t=>{e[t.type]=[]}),e}_getMergeApplyData(e,t,o,i){const s=this._univerInstanceService.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET).getActiveSheet();if(!s)throw new Error("No active sheet found");const l=[];for(let c=e.startRow;c<=e.endRow;c++)for(let d=e.startColumn;d<=e.endColumn;d++){const{isMergedMainCell:u,startRow:h,startColumn:g,endRow:S,endColumn:f}=s.getCellInfoInMergeData(c,d);if(u){if(o===a.Direction.DOWN){let p=h+i,v=S+i;for(;v<=t.endRow;)l.push({startRow:p,startColumn:g,endRow:v,endColumn:f}),p+=i,v+=i}else if(o===a.Direction.UP){let p=h-i,v=S-i;for(;p>=t.startRow;)l.push({startRow:p,startColumn:g,endRow:v,endColumn:f}),p-=i,v-=i}else if(o===a.Direction.RIGHT){let p=g+i,v=f+i;for(;v<=t.endColumn;)l.push({startRow:h,startColumn:p,endRow:S,endColumn:v}),p+=i,v+=i}else if(o===a.Direction.LEFT){let p=g-i,v=f-i;for(;p>=t.startColumn;)l.push({startRow:h,startColumn:p,endRow:S,endColumn:v}),p-=i,v-=i}}}return l}_presetAndCacheData(e,t){const{source:o,target:i}=e,s=this._univerInstanceService.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET).getActiveSheet();if(!s)throw new Error("No active sheet found");const l=s.getCellMatrix(),c=[];return i.rows.forEach(d=>{const u=[];i.cols.forEach(h=>{u.push(a.Tools.deepClone(l.getValue(d,h)))}),c.push(u)}),this._beforeApplyData=c,this._copyData=this._getCopyData(o,t),this._currentLocation=e,this._shouldDisableSeries(this._copyData)?(this._autoFillService.setDisableApplyType(le.SERIES,!0),le.COPY):(this._autoFillService.setDisableApplyType(le.SERIES,!1),this._getPreferredApplyType(this._copyData))}_fillData(e,t,o){var W,H;const i=[],s=[];let l=!0;o===le.NO_FORMAT&&(l=!1,o=le.SERIES);const{source:c,target:d,unitId:u,subUnitId:h}=e;if(!c||!d||t==null)return{undos:i,redos:s};const g=Et(c),S=Et(d),{cols:f,rows:p}=d,{cols:v,rows:C}=c,b=this._copyData;let R;t===a.Direction.DOWN||t===a.Direction.UP?R=C.length:R=v.length;const T=[];if(t===a.Direction.DOWN||t===a.Direction.UP){const U=p.length,B=[];f.forEach((F,L)=>{const j=b[L],z=this._getApplyData(j,R,U,t,o,l);B.push(z)});for(let F=0;F<B[0].length;F++){const L=[];for(let j=0;j<B.length;j++)L.push({s:null,...B[j][F]});T.push(L)}}else{const U=f.length;p.forEach((B,F)=>{const L=b[F],j=this._getApplyData(L,R,U,t,o,l),z=[];for(let q=0;q<j.length;q++)z.push({s:null,...j[q]});T.push(z)})}let M=[];const y=this._univerInstanceService.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET).getStyles();if(l?(M=this._getMergeApplyData(g,S,t,R),T.forEach(U=>{U.forEach(B=>{B&&y&&y&&(B.s=y.getStyleByCell(B))})})):T.forEach((U,B)=>{U.forEach((F,L)=>{F&&y&&(F.s=y.getStyleByCell(this._beforeApplyData[B][L])||null)})}),o===le.ONLY_FORMAT&&T.forEach((U,B)=>{U.forEach((F,L)=>{if(F){const j=this._beforeApplyData[B][L]||{};F.f=j.f,F.si=j.si,F.t=j.t,F.v=j.v}})}),l){const U=[],B=(H=(W=this._univerInstanceService.getUniverSheetInstance(u))==null?void 0:W.getSheetBySheetId(h))==null?void 0:H.getMergeData();B&&B.forEach(j=>{a.Rectangle.intersects(j,S)&&U.push(j)});const F={unitId:u,subUnitId:h,ranges:U},L=this._injector.invoke(m.RemoveMergeUndoMutationFactory,F);U.length&&(s.push({id:m.RemoveWorksheetMergeMutation.id,params:F}),i.unshift({id:m.AddWorksheetMergeMutation.id,params:L}))}const P={subUnitId:h,unitId:u,cellValue:kd([d])},x=this._injector.invoke(m.SetRangeValuesUndoMutationFactory,P);s.push({id:m.SetRangeValuesMutation.id,params:P}),i.unshift({id:m.SetRangeValuesMutation.id,params:x});const A=new a.ObjectMatrix;p.forEach((U,B)=>{f.forEach((F,L)=>{T[B][L]&&A.setValue(U,F,T[B][L])})});const k=A.getMatrix(),N={subUnitId:h,unitId:u,cellValue:k},D=this._injector.invoke(m.SetRangeValuesUndoMutationFactory,N);if(this._autoFillService.getActiveHooks().forEach(U=>{var B;(B=U.onBeforeSubmit)==null||B.call(U,e,t,o,k)}),i.unshift({id:m.SetRangeValuesMutation.id,params:D}),s.push({id:m.SetRangeValuesMutation.id,params:N}),M!=null&&M.length){const U=m.getAddMergeMutationRangeByType(M),B={unitId:u,subUnitId:h,ranges:U},F=this._injector.invoke(m.AddMergeUndoMutationFactory,B);i.unshift({id:m.RemoveWorksheetMergeMutation.id,params:F}),s.push({id:m.AddWorksheetMergeMutation.id,params:B})}return{undos:i,redos:s}}_shouldDisableSeries(e){return e.every(t=>Object.keys(t).every(o=>{var i;return((i=t[o])==null?void 0:i.length)===0||[_e.OTHER,_e.FORMULA].includes(o)}))}_getPreferredApplyType(e){return e.every(o=>Object.keys(o).every(i=>{var s,l;return((s=o[i])==null?void 0:s.length)===0||((l=o[i])==null?void 0:l.length)===1&&o[i][0].data.length===1&&_e.NUMBER===i}))?le.COPY:le.SERIES}};exports.AutoFillController=uu([Ot(0,a.IUniverInstanceService),Ot(1,a.ICommandService),Ot(2,Tt),Ot(3,Se),Ot(4,w.IRenderManagerService),Ot(5,a.Inject(a.Injector)),Ot(6,a.Inject(exports.SheetsRenderService))],exports.AutoFillController);var hu=Object.getOwnPropertyDescriptor,mu=(n,r,e,t)=>{for(var o=t>1?void 0:t?hu(r,e):r,i=n.length-1,s;i>=0;i--)(s=n[i])&&(o=s(o)||o);return o},Zr=(n,r)=>(e,t)=>r(e,t,n);exports.CellCustomRenderController=class extends a.Disposable{constructor(e,t,o,i){super();E(this,"_enterActiveRender");this._context=e,this._sheetSkeletonManagerService=t,this._renderManagerService=o,this._permissionService=i,this._initEventBinding()}_initEventBinding(){const e=new a.DisposableCollection,t=this._context.unit,o=i=>{if(e.dispose(),!i)return;const s=this._context.unitId,{skeleton:l}=i,c=this._renderManagerService.getRenderById(s);if(c&&c.mainComponent){const d=c.mainComponent,u=S=>{const{offsetX:f,offsetY:p}=S,v=c.scene,C=t.getActiveSheet();if(!C)return;const b=v.getActiveViewportByCoord(w.Vector2.FromArray([f,p]));if(!b)return;const{scaleX:R,scaleY:T}=v.getAncestorScale(),M={x:b.viewportScrollX,y:b.viewportScrollY},y=l.getCellIndexByOffset(f,p,R,T,M),P=l.worksheet.getMergedCell(y.row,y.column),x={actualRow:P?P.startRow:y.row,actualCol:P?P.startColumn:y.column,row:y.row,col:y.column};if(!x||!l)return;const A=C.getCell(x.actualRow,x.actualCol);if(!A)return;const k=A.customRender;if(!(k!=null&&k.length))return;const N=x.actualRow,D=x.actualCol,W=k.sort(a.sortRules),H=C.getSheetId(),U={data:A,style:l.getStyles().getStyleByCell(A),primaryWithCoord:l.getCellWithCoordByIndex(x.actualRow,x.actualCol),unitId:s,subUnitId:H,row:N,col:D,workbook:t,worksheet:C},B={x:M.x+f/R,y:M.y+p/T},F=W.find(L=>{var j;return(j=L.isHit)==null?void 0:j.call(L,B,U)});if(F)return[F,U]},h=d.onPointerDown$.subscribeEvent(S=>{var p,v,C,b;const f=u(S);if(f){const[R,T]=f,{row:M,col:y,worksheet:P,unitId:x,subUnitId:A}=T;if(!((p=this._permissionService.composePermission([new m.WorkbookEditablePermission(x).id,new m.WorksheetEditPermission(x,A).id]))==null?void 0:p.every(D=>D.value)))return!1;const N=(C=(v=P.getCell(M,y))==null?void 0:v.selectionProtection)==null?void 0:C[0];if((N==null?void 0:N[m.UnitAction.Edit])===!1)return!1;(b=R.onPointerDown)==null||b.call(R,T,S)}}),g=a.fromEventSubject(d.onPointerMove$).pipe(O.throttleTime(30)).subscribe(S=>{var p,v,C,b,R,T;const f=u(S);if(f){const[M,y]=f;this._enterActiveRender?this._enterActiveRender.render!==M&&((v=(p=this._enterActiveRender.render).onPointerLeave)==null||v.call(p,this._enterActiveRender.cellContext,S),this._enterActiveRender={render:M,cellContext:y},(C=M.onPointerEnter)==null||C.call(M,y,S)):(this._enterActiveRender={render:M,cellContext:y},(b=M.onPointerEnter)==null||b.call(M,y,S))}else this._enterActiveRender&&((T=(R=this._enterActiveRender.render).onPointerLeave)==null||T.call(R,this._enterActiveRender.cellContext,S),this._enterActiveRender=null)});h&&e.add(h),g&&e.add(g)}};this.disposeWithMe(this._sheetSkeletonManagerService.currentSkeleton$.subscribe(o)),o(this._sheetSkeletonManagerService.getCurrentParam()),this.disposeWithMe(e)}};exports.CellCustomRenderController=mu([Zr(1,a.Inject(exports.SheetSkeletonManagerService)),Zr(2,w.IRenderManagerService),Zr(3,a.IPermissionService)],exports.CellCustomRenderController);class ps extends a.Disposable{constructor(){super(...arguments);E(this,"rangesStack",[]);E(this,"selectedRangeWorksheet","")}}var gu=Object.getOwnPropertyDescriptor,Su=(n,r,e,t)=>{for(var o=t>1?void 0:t?gu(r,e):r,i=n.length-1,s;i>=0;i--)(s=n[i])&&(o=s(o)||o);return o},ta=(n,r)=>(e,t)=>r(e,t,n);let Tn=class{constructor(n,r){E(this,"_current",null);E(this,"_shortcutParam",[]);this._univerInstanceService=n,this._localeService=r}dispose(){this._shortcutParam=[]}getCurrentBySearch(n){return this._getCurrentBySearch(n)}getCurrent(){return this._getCurrentBySearch(this._current)}addOrUpdate(n){const r=this._getCurrentBySearch({unitId:n.unitId,sheetId:n.sheetId,keycode:n.keycode});if(r!=null){const e=this._shortcutParam.indexOf(r);this._shortcutParam.splice(e,1)}return this._shortcutParam.push(n),r}remove(n){if(n==null)return;const r=this._getCurrentBySearch(n);if(r==null)return;const e=this._shortcutParam.indexOf(r);return this._shortcutParam.splice(e,1)[0]}_getCurrentBySearch(n){return n==null?void 0:this._shortcutParam.find(e=>e.unitId===n.unitId&&e.sheetId===n.sheetId&&e.keycode===n.keycode)}};Tn=Su([ta(0,a.IUniverInstanceService),ta(1,a.Inject(a.LocaleService))],Tn);var Nr=(n=>(n.MergeAll="mergeAll",n.MergeVertical="mergeVertical",n.MergeHorizontal="mergeHorizontal",n))(Nr||{});function It(n,r,e,t,o=!0,i=1,s=!0){let l={...n};t==null&&(t={startRow:0,endRow:e.getRowCount()-1,startColumn:0,endColumn:e.getColumnCount()-1});let c;switch(r){case a.Direction.UP:for(c=n.startRow-i;c>-1&&!e.getRowVisible(c);)c-=1;c>=t.startRow?(l.startRow=c,l.endRow=c):s&&(l.startRow=t.endRow,l.endRow=t.endRow,o&&(l=It(l,a.Direction.LEFT,e,t,!1)));break;case a.Direction.DOWN:for(c=n.endRow+i;c<e.getRowCount()&&!e.getRowVisible(c);)c+=1;c<=t.endRow?(l.startRow=c,l.endRow=c):s&&(l.startRow=t.startRow,l.endRow=t.startRow,o&&(l=It(l,a.Direction.RIGHT,e,t,!1)));break;case a.Direction.LEFT:for(c=n.startColumn-i;c>-1&&!e.getColVisible(c);)c-=1;c>=t.startColumn?(l.startColumn=c,l.endColumn=c):s&&(l.startColumn=t.endColumn,l.endColumn=t.endColumn,o&&(l=It(l,a.Direction.UP,e,t,!1)));break;case a.Direction.RIGHT:for(c=n.endColumn+i;c<e.getColumnCount()&&!e.getColVisible(c);)c+=1;c<=t.endColumn?(l.startColumn=c,l.endColumn=c):s&&(l.startColumn=t.startColumn,l.endColumn=t.startColumn,o&&(l=It(l,a.Direction.DOWN,e,t,!1)));break}return l}function vs(n,r,e){const t={...n},{startRow:o,startColumn:i,endRow:s,endColumn:l}=to(n,r,e);let c=Bn(e,o,i,s,l).hasValue,d=!0,u=!0;for(;u;){if(a.Direction.UP===r){let h=t.startRow-1;for(;h>-1&&!e.getRowVisible(h);)h-=1;if(h===-1){u=!1;break}const{hasValue:g,matrix:S}=Bn(e,h,t.startColumn,h,t.endColumn);if(c&&!g&&!d){u=!1;break}else{if(S.getLength()!==0){let f=h;S.forValue(p=>{f=Math.min(p,f)}),t.startRow=f}else t.startRow=h;if(t.endRow=t.startRow,!c&&g){u=!1;break}c=g,d=!1}}if(a.Direction.DOWN===r){let h=t.endRow+1;for(;h<e.getRowCount()&&!e.getRowVisible(h);)h+=1;if(h===e.getRowCount()){u=!1;break}const{hasValue:g,matrix:S}=Bn(e,h,t.startColumn,h,t.endColumn);if(c&&!g&&!d){u=!1;break}else{if(S.getLength()!==0){let f=h;S.forValue((p,v,C)=>{f=Math.max(p+(C.rowSpan||1)-1,f)}),t.endRow=f}else t.endRow=h;if(t.startRow=t.endRow,!c&&g){u=!1;break}c=g,d=!1}}if(a.Direction.LEFT===r){let h=t.startColumn-1;for(;h>-1&&!e.getColVisible(h);)h-=1;if(h===-1){u=!1;break}const{hasValue:g,matrix:S}=Bn(e,t.startRow,h,t.endRow,h);if(c&&!g&&!d){u=!1;break}else{if(S.getLength()!==0){let f=h;S.forValue((p,v)=>{f=Math.min(v,f)}),t.startColumn=f}else t.startColumn=h;if(t.endColumn=t.startColumn,!c&&g){u=!1;break}c=g,d=!1}}if(a.Direction.RIGHT===r){let h=t.endColumn+1;for(;h<e.getColumnCount()&&!e.getColVisible(h);)h+=1;if(h===e.getColumnCount()){u=!1;break}const{hasValue:g,matrix:S}=Bn(e,t.startRow,h,t.endRow,h);if(c&&!g&&!d){u=!1;break}else{if(S.getLength()!==0){let f=h;S.forValue((p,v,C)=>{f=Math.max(v+(C.colSpan||1)-1,f)}),t.endColumn=f}else t.endColumn=h;if(t.startColumn=t.endColumn,!c&&g){u=!1;break}c=g,d=!1}}}return m.alignToMergedCellsBorders(t,e,!0)}function tl(n,r,e){return It(n,r,e,void 0,!1,1,!1)}function fu(n,r,e){const t=vs(n,r,e);return m.alignToMergedCellsBorders(a.Rectangle.union(t,n),e,!0)}function pu(n,r,e){const t=tl(n,r,e),o={startRow:Math.min(n.startRow,t.startRow),startColumn:Math.min(n.startColumn,t.startColumn),endRow:Math.max(n.endRow,t.endRow),endColumn:Math.max(n.endColumn,t.endColumn)};return m.alignToMergedCellsBorders(a.Rectangle.union(n,o),e)}function vu(n,r,e,t){const o=a.getReverseDirection(e),i=vs(to(n,o,t),e,t);return e===a.Direction.UP&&i.startRow<=n.startRow?m.alignToMergedCellsBorders({...r,startColumn:n.startColumn,endColumn:n.endColumn},t,!0):e===a.Direction.DOWN&&i.endRow>=n.endRow?m.alignToMergedCellsBorders({...r,startColumn:n.startColumn,endColumn:n.endColumn},t,!0):e===a.Direction.LEFT&&i.startColumn<=n.startColumn?m.alignToMergedCellsBorders({...r,startRow:n.startRow,endRow:n.endRow},t,!0):e===a.Direction.RIGHT&&i.endColumn>=n.endColumn?m.alignToMergedCellsBorders({...r,startRow:n.startRow,endRow:n.endRow},t,!0):a.Rectangle.union(a.Rectangle.clone(r),i)}function Cu(n,r,e){const t=a.getReverseDirection(r),o=to(n,t,e),i=to(n,r,e),s=tl(o,r,e);return m.alignToMergedCellsBorders(a.Rectangle.union(i,s),e,!1)}function na(n){return{startRow:0,startColumn:0,endRow:n.getRowCount()-1,endColumn:n.getColumnCount()-1,rangeType:a.RANGE_TYPE.ALL}}function to(n,r,e){let t;switch(r){case a.Direction.UP:t={startRow:n.startRow,startColumn:n.startColumn,endRow:n.startRow,endColumn:n.endColumn,rangeType:a.RANGE_TYPE.NORMAL};break;case a.Direction.DOWN:t={startRow:n.endRow,startColumn:n.startColumn,endRow:n.endRow,endColumn:n.endColumn,rangeType:a.RANGE_TYPE.NORMAL};break;case a.Direction.LEFT:t={startRow:n.startRow,startColumn:n.startColumn,endRow:n.endRow,endColumn:n.startColumn,rangeType:a.RANGE_TYPE.NORMAL};break;case a.Direction.RIGHT:t={startRow:n.startRow,startColumn:n.endColumn,endRow:n.endRow,endColumn:n.endColumn,rangeType:a.RANGE_TYPE.NORMAL};break;default:throw new Error("Invalid direction")}return m.alignToMergedCellsBorders(t,e,!1)}function Bn(n,r,e,t,o){let i=!1;const s=n.getMatrixWithMergedCells(r,e,t,o).forValue((l,c,d)=>{if(_u(d))return i=!0,!1});return{hasValue:i,matrix:s}}function Fi(n,r,e){const t=a.Rectangle.clone(n);if(r==null)return t;switch(e){case a.Direction.UP:case a.Direction.DOWN:t.startColumn=t.endColumn=r.actualColumn;break;case a.Direction.LEFT:case a.Direction.RIGHT:t.startRow=t.endRow=r.actualRow;break}return t}function Iu(n,r,e){var l,c,d,u;const{primary:t,range:o}=n,i=a.Rectangle.clone(o);switch(r){case a.Direction.UP:case a.Direction.DOWN:i.startRow=(l=t==null?void 0:t.startRow)!=null?l:o.startRow,i.endRow=(c=t==null?void 0:t.endRow)!=null?c:o.startRow;break;case a.Direction.LEFT:case a.Direction.RIGHT:i.startColumn=(d=t==null?void 0:t.startColumn)!=null?d:o.startColumn,i.endColumn=(u=t==null?void 0:t.endColumn)!=null?u:o.startColumn;break}const s=to(i,r,e);switch(r){case a.Direction.DOWN:return o.startRow<s.startRow;case a.Direction.UP:return o.endRow>s.endRow;case a.Direction.LEFT:return s.endColumn<o.endColumn;case a.Direction.RIGHT:return s.startColumn>o.startColumn}}function nl(n,r){let e=n[0].startRow,t=n[0].endRow;n.forEach(i=>{const{startRow:s,endRow:l}=i;e=Math.min(e,s),t=Math.max(t,l)});const o=new Array(t-e+1).fill(!1);return r.forEach(i=>{const{startRow:s,endRow:l}=i;for(let c=Math.max(s,e);c<=Math.min(l,t);c++)o[c-e]=!0}),n.every(i=>{const{startRow:s,endRow:l}=i;for(let c=s;c<=l;c++)if(!o[c-e])return!1;return!0})}function ol(n,r){let e=n[0].startColumn,t=n[0].endColumn;n.forEach(i=>{const{startColumn:s,endColumn:l}=i;e=Math.min(e,s),t=Math.max(t,l)});const o=new Array(t-e+1).fill(!1);return r.forEach(i=>{const{startColumn:s,endColumn:l}=i;for(let c=Math.max(s,e);c<=Math.min(l,t);c++)o[c-e]=!0}),n.every(i=>{const{startColumn:s,endColumn:l}=i;for(let c=s;c<=l;c++)if(!o[c-e])return!1;return!0})}function Cs(n,r){return r?n==="mergeAll"?r.filter(e=>!(e.startRow===e.endRow&&e.startColumn===e.endColumn)):n==="mergeVertical"?r.filter(e=>e.startRow!==e.endRow):n==="mergeHorizontal"?r.filter(e=>e.startColumn!==e.endColumn):r:null}function _u(n){return n.v!==void 0&&n.v!==null&&n.v!==""||n.p!==void 0}var Je=(n=>(n[n.moveStopeOne=0]="moveStopeOne",n[n.moveGap=1]="moveGap",n[n.moveStepPage=2]="moveStepPage",n[n.moveStepEnd=3]="moveStepEnd",n))(Je||{});const xe={id:"sheet.command.move-selection",type:a.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;const e=m.getSheetCommandTarget(n.get(a.IUniverInstanceService));if(!e)return!1;const{workbook:t,worksheet:o}=e,i=m.getSelectionsService(n,r.fromCurrentSelection).getCurrentLastSelection();if(!i)return!1;const{direction:s,jumpOver:l,extra:c}=r,{range:d,primary:u}=i,h=Fi(d,u,s),g=l===1?vs(h,s,o):It(h,s,o),S=m.getCellAtRowCol(g.startRow,g.startColumn,o);if(a.Rectangle.equals(S,h))return!1;const f=t.getUnitId();n.get(Tn).remove({unitId:f,sheetId:o.getSheetId(),keycode:I.KeyCode.TAB});const p=[{range:a.Rectangle.clone(S),primary:{startRow:S.startRow,startColumn:S.startColumn,endRow:S.endRow,endColumn:S.endColumn,actualRow:g.startRow,actualColumn:g.startColumn,isMerged:S.isMerged,isMergedMainCell:S.startRow===g.startRow&&S.startColumn===g.startColumn}}];return n.get(a.ICommandService).executeCommand(m.SetSelectionsOperation.id,{unitId:t.getUnitId(),subUnitId:o.getSheetId(),selections:p,type:m.SelectionMoveType.MOVE_END,extra:c,reveal:!0})}},$e={id:"sheet.command.move-selection-enter-tab",type:a.CommandType.COMMAND,handler:(n,r)=>{var U;if(!r)return!1;const e=m.getSheetCommandTarget(n.get(a.IUniverInstanceService));if(!e)return!1;const{workbook:t,worksheet:o}=e,i=m.getSelectionsService(n),{direction:s,keycode:l}=r,c=s===a.Direction.LEFT||s===a.Direction.UP,d=i.getCurrentSelections().concat(),u=d.findIndex(B=>B.primary),h=d[u];if(!h)return!1;const g=c?-1:1,S=u+g!==d.length?d[u+g]:d[0],f=d.findIndex(B=>B===S),p=t.getUnitId(),v=o.getSheetId();if(!h)return!1;const{range:C}=h,b=h.primary;let R=Fi(C,b,s);const T=n.get(Tn),M=T.getCurrentBySearch({unitId:p,sheetId:v,keycode:I.KeyCode.TAB});let y;const{startRow:P,endRow:x,startColumn:A,endColumn:k}=C,N=c?b.startRow===P&&b.startColumn===A:b.endRow===x&&b.endColumn===k;if(a.Rectangle.equals(C,b)){if(l===I.KeyCode.TAB)M==null&&T.addOrUpdate({unitId:p,sheetId:v,keycode:I.KeyCode.TAB,selection:h});else{const L=M==null?void 0:M.selection;if(L!=null){const{range:j,primary:z}=L;R=Fi(j,z,s)}T.remove({unitId:p,sheetId:v,keycode:I.KeyCode.TAB})}const B=It(R,s,o),F=m.getCellAtRowCol(B.startRow,B.startColumn,o);if(a.Rectangle.equals(F,R))return!1;y={range:a.Rectangle.clone(F),primary:{startRow:F.startRow,startColumn:F.startColumn,endRow:F.endRow,endColumn:F.endColumn,actualRow:B.startRow,actualColumn:B.startColumn,isMerged:F.isMerged,isMergedMainCell:F.startRow===B.startRow&&F.startColumn===B.startColumn}}}else{T.remove({unitId:p,sheetId:v,keycode:I.KeyCode.TAB});const B=a.Tools.deepClone(b),F=N?S.range:It({startRow:B.startRow,startColumn:B.startColumn,endRow:B.endRow,endColumn:B.endColumn},s,o,{startRow:P,endRow:x,startColumn:A,endColumn:k}),L=N&&c,j=L?m.getCellAtRowCol(F.endRow,F.endColumn,o):m.getCellAtRowCol(F.startRow,F.startColumn,o);y={range:N?S.range:a.Rectangle.clone(C),primary:{startRow:j.startRow,startColumn:j.startColumn,endRow:j.endRow,endColumn:j.endColumn,actualRow:L?j.startRow:F.startRow,actualColumn:L?j.startColumn:F.startColumn,isMerged:j.isMerged,isMergedMainCell:j.startRow===F.startRow&&j.startColumn===F.startColumn},style:N?S.style:h.style}}N?(d[u].primary=null,d[f]=y,i.setSelections(p,v,[],m.SelectionMoveType.MOVE_END)):d[u]=y;const D=n.get(a.ICommandService).executeCommand(m.SetSelectionsOperation.id,{unitId:p,subUnitId:v,type:m.SelectionMoveType.MOVE_END,selections:d,reveal:!0,extra:r.extra}),H=(U=n.get(w.IRenderManagerService).getRenderById(p))==null?void 0:U.with(ve);return H==null||H.refreshSelectionMoveEnd(),D}},De={id:"sheet.command.expand-selection",type:a.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;const e=m.getSheetCommandTarget(n.get(a.IUniverInstanceService));if(!e)return!1;const{worksheet:t,unitId:o,subUnitId:i}=e,s=m.getSelectionsService(n).getCurrentLastSelection();if(!s)return!1;const{range:l,primary:c}=s,{jumpOver:d,direction:u,extra:h}=r,S=Iu(s,u,t)?d===1?vu(l,{...a.Rectangle.clone(c),rangeType:a.RANGE_TYPE.NORMAL},u,t):Cu(l,u,t):d===1?fu(l,u,t):pu(l,u,t);return S.rangeType=s.range.rangeType,a.Rectangle.equals(S,l)?!1:n.get(a.ICommandService).syncExecuteCommand(m.SetSelectionsOperation.id,{unitId:o,subUnitId:i,type:m.SelectionMoveType.ONLY_SET,selections:[{range:S,primary:c}],extra:h})}},Dr={id:"sheet.command.select-all",type:a.CommandType.COMMAND,handler:async(n,r={expandToGapFirst:!0,loop:!1})=>{const e=m.getSheetCommandTarget(n.get(a.IUniverInstanceService));if(!e)return!1;const t=m.getSelectionsService(n).getCurrentLastSelection();if(!t)return!1;const o=n.get(ps),{worksheet:i,unitId:s,subUnitId:l}=e,c=`${s}|${l}`;c!==o.selectedRangeWorksheet&&(o.rangesStack=[],o.selectedRangeWorksheet=c);const d=i.getMaxRows(),u=i.getMaxColumns(),{expandToGapFirst:h,loop:g}=r,{range:S,primary:f}=t,p=S.endColumn===u-1&&S.endRow===d-1&&S.startRow===0&&S.startColumn===0;o.rangesStack.some(C=>a.Rectangle.equals(C,S))||(o.rangesStack=[],o.rangesStack.push(S));let v;if(p)if(g){if(o.rangesStack.findIndex(b=>a.Rectangle.equals(b,S))!==o.rangesStack.length-1)return!1;v=o.rangesStack[0]}else return!1;else h?(v=m.expandToContinuousRange(S,{left:!0,right:!0,up:!0,down:!0},i),a.Rectangle.equals(v,S)&&(v=na(i))):v=na(i);return o.rangesStack.some(C=>a.Rectangle.equals(C,v))||o.rangesStack.push(v),n.get(a.ICommandService).executeCommand(m.SetSelectionsOperation.id,{unitId:s,subUnitId:l,reveal:!0,selections:[{range:v,primary:f}]})}};var bu=Object.getOwnPropertyDescriptor,Ru=(n,r,e,t)=>{for(var o=t>1?void 0:t?bu(r,e):r,i=n.length-1,s;i>=0;i--)(s=n[i])&&(o=s(o)||o);return o},Eu=(n,r)=>(e,t)=>r(e,t,n);exports.SheetScrollManagerService=class{constructor(r,e){E(this,"_scrollStateMap",new Map);E(this,"_rawScrollInfo$",new O.BehaviorSubject(null));E(this,"rawScrollInfo$",this._rawScrollInfo$.asObservable());E(this,"validViewportScrollInfo$",new O.BehaviorSubject(null));E(this,"_searchParamForScroll",null);this._context=r,this._sheetSkeletonManagerService=e}dispose(){this._rawScrollInfo$.complete()}calcViewportScrollFromRowColOffset(r){if(!r)return{viewportScrollX:0,viewportScrollY:0};let{sheetViewStartColumn:e,sheetViewStartRow:t,offsetX:o,offsetY:i}=r;t=t||0,i=i||0;const s=this._sheetSkeletonManagerService.getCurrentSkeleton(),l=(s==null?void 0:s.rowHeightAccumulation[t-1])||0,d=((s==null?void 0:s.columnWidthAccumulation[e-1])||0)+o,u=l+i;return{viewportScrollX:d,viewportScrollY:u}}setSearchParam(r){this._searchParamForScroll=r}getScrollStateByParam(r){return this._getCurrentScroll(r)}getCurrentScrollState(){return this._getCurrentScroll(this._searchParamForScroll)}setValidScrollState(r){this._setScrollState(r)}emitRawScrollParam(r){this._emitRawScroll(r)}setValidScrollStateToCurrSheet(r){if(this._searchParamForScroll==null)return;this._setScrollState({...this._searchParamForScroll,...r});const e=this._searchParamForScroll.sheetId,t=this._sheetSkeletonManagerService.getSkeleton(e);t&&t.setScroll(r.viewportScrollX,r.viewportScrollY)}clear(){this._searchParamForScroll!=null&&this._clearByParamAndNotify(this._searchParamForScroll)}_setScrollState(r){const{unitId:e,sheetId:t,sheetViewStartColumn:o,sheetViewStartRow:i,offsetX:s,offsetY:l}=r;this._scrollStateMap.has(e)||this._scrollStateMap.set(e,new Map);const c=this._scrollStateMap.get(e),d={sheetViewStartRow:i,sheetViewStartColumn:o,offsetX:s,offsetY:l};c.set(t,d)}_clearByParamAndNotify(r){this._setScrollState({...r,sheetViewStartRow:0,sheetViewStartColumn:0,offsetX:0,offsetY:0}),this._emitRawScroll({sheetViewStartRow:0,sheetViewStartColumn:0,offsetX:0,offsetY:0})}_getCurrentScroll(r){var s;const e={sheetViewStartRow:0,sheetViewStartColumn:0,offsetX:0,offsetY:0};if(r==null)return e;const{unitId:t,sheetId:o}=r;return((s=this._scrollStateMap.get(t))==null?void 0:s.get(o))||e}_emitRawScroll(r){this._rawScrollInfo$.next(r)}};exports.SheetScrollManagerService=Ru([Eu(1,a.Inject(exports.SheetSkeletonManagerService))],exports.SheetScrollManagerService);const je={id:"sheet.operation.set-scroll",type:a.CommandType.OPERATION,handler:(n,r)=>{if(!r)return!1;const{unitId:e,sheetId:t,offsetX:o,offsetY:i,sheetViewStartColumn:s,sheetViewStartRow:l}=r;return n.get(w.IRenderManagerService).getRenderById(e).with(exports.SheetScrollManagerService).emitRawScrollParam({unitId:e,sheetId:t,offsetX:o,offsetY:i,sheetViewStartRow:l,sheetViewStartColumn:s}),!0}},wn={id:"sheet.command.set-scroll-relative",type:a.CommandType.COMMAND,handler:async(n,r)=>{const e=n.get(a.ICommandService),t=n.get(a.IUniverInstanceService),o=n.get(w.IRenderManagerService),i=m.getSheetCommandTarget(t);if(!i)return!1;const{unitId:s,subUnitId:l}=i,d=o.getRenderById(s).with(exports.SheetScrollManagerService).getCurrentScrollState(),{offsetX:u=0,offsetY:h=0}=r||{},{sheetViewStartRow:g=0,sheetViewStartColumn:S=0,offsetX:f=0,offsetY:p=0}=d||{};return e.executeCommand(je.id,{unitId:s,sheetId:l,sheetViewStartRow:g,sheetViewStartColumn:S,offsetX:f+u,offsetY:p+h})}},ze={id:"sheet.command.scroll-view",type:a.CommandType.COMMAND,handler:(n,r)=>{if(!r)return!1;const e=n.get(a.IUniverInstanceService),t=n.get(w.IRenderManagerService),o=m.getSheetCommandTarget(e);if(!o)return!1;const{workbook:i,worksheet:s,unitId:l}=o,d=t.getRenderById(l).with(exports.SheetScrollManagerService).getCurrentScrollState();if(!s)return!1;const{sheetViewStartRow:u,sheetViewStartColumn:h,offsetX:g,offsetY:S}=r,{sheetViewStartColumn:f,sheetViewStartRow:p,offsetX:v,offsetY:C}=d||{},{xSplit:b,ySplit:R}=o.worksheet.getConfig().freeze;return n.get(a.ICommandService).syncExecuteCommand(je.id,{unitId:i.getUnitId(),sheetId:s.getSheetId(),sheetViewStartRow:u!=null?u:p!=null?p:0+R,sheetViewStartColumn:h!=null?h:f!=null?f:0+b,offsetX:g!=null?g:v,offsetY:S!=null?S:C})}},Is={id:"sheet.command.scroll-to-cell",type:a.CommandType.COMMAND,handler:(n,r)=>{const e=n.get(a.IUniverInstanceService);return n.get(w.IRenderManagerService).getRenderById(e.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET).getUnitId()).with(exports.SheetsScrollRenderController).scrollToRange(r.range,r.forceTop,r.forceLeft)}},Tu={id:"sheet.command.scroll-view-reset",type:a.CommandType.COMMAND,handler:async n=>{const r=n.get(a.IUniverInstanceService),e=m.getSheetCommandTarget(r);if(!e)return!1;const{subUnitId:t,unitId:o}=e;return n.get(a.ICommandService).executeCommand(je.id,{unitId:o,sheetId:t,sheetViewStartRow:0,sheetViewStartColumn:0})}};var wu=Object.getOwnPropertyDescriptor,yu=(n,r,e,t)=>{for(var o=t>1?void 0:t?wu(r,e):r,i=n.length-1,s;i>=0;i--)(s=n[i])&&(o=s(o)||o);return o},sn=(n,r)=>(e,t)=>r(e,t,n);xe.id,$e.id;const Mu=3;exports.SheetsScrollRenderController=class extends a.Disposable{constructor(r,e,t,o,i,s,l){super(),this._context=r,this._injector=e,this._sheetSkeletonManagerService=t,this._contextService=o,this._commandService=i,this._renderManagerService=s,this._scrollManagerService=l,this._initCommandListener(),this._wheelEventListener(),this._scrollBarEventListener(),this._initSkeletonListener()}_wheelEventListener(){const{scene:r}=this._context;if(!r)return;const e=r.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN);e&&this.disposeWithMe(r.onMouseWheel$.subscribeEvent((t,o)=>{if(t.ctrlKey||!this._contextService.getContextValue(a.FOCUSING_SHEET))return;let i=0,s=0;i=t.deltaX,t.shiftKey?i=(t.deltaY||t.deltaX)*Mu:s=t.deltaY,this._commandService.executeCommand(wn.id,{offsetX:i,offsetY:s}),this._context.scene.makeDirty(!0);const l=e.limitedScroll(e.scrollX+i,e.scrollY+s);l&&!l.isLimitedX&&!l.isLimitedY&&(t.preventDefault(),r.getParent().classType===w.RENDER_CLASS_TYPE.SCENE_VIEWER&&o.stopPropagation()),e.isWheelPreventDefaultX&&e.isWheelPreventDefaultY&&t.preventDefault()}))}_scrollBarEventListener(){const{scene:r}=this._context;if(r==null)return;const e=r.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN);e&&(this.disposeWithMe(a.toDisposable(this._scrollManagerService.rawScrollInfo$.subscribe(t=>{var S;const o=(S=this._sheetSkeletonManagerService.getCurrentParam())==null?void 0:S.skeleton;if(!o)return;if(t==null){e.scrollToViewportPos({viewportScrollX:0,viewportScrollY:0});return}const{sheetViewStartRow:i,sheetViewStartColumn:s,offsetX:l,offsetY:c}=t,{startX:d,startY:u}=o.getCellWithCoordByIndex(i,s,!1),h=d+l,g=u+c;e.scrollToViewportPos({viewportScrollX:h,viewportScrollY:g})}))),this.disposeWithMe(e.onScrollAfter$.subscribeEvent(t=>{var p;const o=(p=this._sheetSkeletonManagerService.getCurrentParam())==null?void 0:p.skeleton;if(o==null||t.isTrigger===!1)return;const i=this._getSheetObject();if(o==null||i==null)return;const{viewportScrollX:s,viewportScrollY:l,scrollX:c,scrollY:d}=t,{row:u,column:h,rowOffset:g,columnOffset:S}=o.getOffsetRelativeToRowCol(s,l),f={sheetViewStartRow:u,sheetViewStartColumn:h,offsetX:S,offsetY:g,viewportScrollX:s,viewportScrollY:l,scrollX:c,scrollY:d};this._scrollManagerService.setValidScrollStateToCurrSheet(f),this._scrollManagerService.validViewportScrollInfo$.next({...f,viewportScrollX:s,viewportScrollY:l,scrollX:c,scrollY:d})})),this.disposeWithMe(e.onScrollByBar$.subscribeEvent(t=>{var g;const o=(g=this._sheetSkeletonManagerService.getCurrentParam())==null?void 0:g.skeleton;if(o==null||t.isTrigger===!1)return;const i=this._getSheetObject();if(o==null||i==null)return;const{viewportScrollX:s=0,viewportScrollY:l=0}=t;this._getFreeze();const{row:c,column:d,rowOffset:u,columnOffset:h}=o.getOffsetRelativeToRowCol(s,l);this._commandService.executeCommand(ze.id,{sheetViewStartRow:c,sheetViewStartColumn:d,offsetX:h,offsetY:u})})))}_initSkeletonListener(){this.disposeWithMe(a.toDisposable(this._sheetSkeletonManagerService.currentSkeletonBefore$.subscribe(r=>{if(r==null)return;const e={unitId:r.unitId,sheetId:r.sheetId};if(this._scrollManagerService.setSearchParam(e),!this._getSheetObject())return;const o=this._scrollManagerService.getScrollStateByParam(e),{viewportScrollX:i,viewportScrollY:s}=this._scrollManagerService.calcViewportScrollFromRowColOffset(o);o&&this._updateViewportScroll(i,s)})))}_updateViewportScroll(r=0,e=0){const t=this._getSheetObject();if(!t)return;const o=t.scene,i=o.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN),s=o.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_COLUMN_RIGHT),l=o.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_ROW_BOTTOM),c=o.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN_LEFT),d=o.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN_TOP);i&&(i.viewportScrollX=r,i.viewportScrollY=e),l&&(l.viewportScrollY=e),s&&(s.viewportScrollX=r),c&&(c.viewportScrollY=e),d&&(d.viewportScrollX=r)}scrollToRange(r,e,t){let{endRow:o,endColumn:i,startColumn:s,startRow:l}=r;const c=this._getViewportBounding();if(r.rangeType===a.RANGE_TYPE.ROW?(s=0,i=0):r.rangeType===a.RANGE_TYPE.COLUMN&&(l=0,o=0),c&&!e&&!t){const d=c.startRow>o?l:o,u=c.startColumn>i?s:i;return this._scrollToCell(d,u)}else return this._scrollToCell(l,s,e,t)}scrollToCell(r,e){const t=this._context.unit.getActiveSheet(),{ySplit:o,xSplit:i}=t.getFreeze();return this._commandService.syncExecuteCommand(ze.id,{sheetViewStartRow:r-o,sheetViewStartColumn:e-i,offsetX:0,offsetY:0})}_initCommandListener(){this.disposeWithMe(this._commandService.onCommandExecuted(r=>{switch(r.id){case m.SetSelectionsOperation.id:{const e=r.params;e.unitId===this._context.unitId&&e.reveal&&this._scrollToSelection()}break;case m.ScrollToCellOperation.id:{const e=r.params;if(e.unitId===this._context.unitId){const t=e.range;this.scrollToRange(t)}}break;case De.id:{const e=r.params;this._scrollToSelectionForExpand(e)}break}}))}_scrollToSelectionForExpand(r){setTimeout(()=>{const e=this._getSelectionsService().getCurrentLastSelection();if(e==null)return;const{startRow:t,startColumn:o,endRow:i,endColumn:s}=e.range,l=this._getViewportBounding();if(l==null)return;const{startRow:c,startColumn:d,endRow:u,endColumn:h}=l;let g=0,S=0;t>c?g=i:i<u?g=t:g=c,o>d?S=s:s<h?S=o:S=d,r.direction===a.Direction.DOWN?g=i:r.direction===a.Direction.UP?g=t:r.direction===a.Direction.RIGHT?S=s:r.direction===a.Direction.LEFT&&(S=o),this._scrollToCell(g,S)},0)}_getFreeze(){var e;const r=(e=this._sheetSkeletonManagerService.getCurrentParam())==null?void 0:e.skeleton.getWorksheetConfig();if(r!=null)return r.freeze}_updateSceneSize(r){var h;if(r==null)return;const{unitId:e}=this._context,{skeleton:t}=r,o=(h=this._renderManagerService.getRenderById(e))==null?void 0:h.scene;if(t==null||o==null)return;const{rowTotalHeight:i,columnTotalWidth:s,rowHeaderWidthAndMarginLeft:l,columnHeaderHeightAndMarginTop:c}=t;this._context.unit.getActiveSheet()&&(o==null||o.transformByState({width:l+s,height:c+i}))}_getSheetObject(){return Ge(this._context.unit,this._context)}_scrollToSelectionByDirection(r){const e=this._getViewportBounding();if(e==null)return!1;const{startRow:t,startColumn:o,endRow:i,endColumn:s}=e;let l=0,c=0;const{startRow:d,startColumn:u,endRow:h,endColumn:g}=r;d>=t&&(l=h),h<=i&&(l=d),u>=o&&(c=g),g<=s&&(c=u),this._scrollToCell(l,c)}_scrollToSelection(r=!0){var d;const e=this._getSelectionsService().getCurrentLastSelection();if(!e)return;const{startRow:t,startColumn:o,actualRow:i,actualColumn:s}=(d=e.primary)!=null?d:e.range,l=r&&i!=null?i:t,c=r&&s!=null?s:o;this._scrollToCell(l,c)}_getSelectionsService(){return m.getSelectionsService(this._injector)}_getViewportBounding(){var i,s;const r=(i=this._getSheetObject())==null?void 0:i.scene;if(r==null)return;const e=r.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN);if(e==null)return;const t=(s=this._sheetSkeletonManagerService.getCurrentParam())==null?void 0:s.skeleton;if(t==null)return;const o=e.calcViewportInfo();return t.getRangeByViewBound(o.viewBound)}_scrollToCell(r,e,t=!1,o=!1){var k,N,D;const{rowHeightAccumulation:i,columnWidthAccumulation:s}=(k=this._sheetSkeletonManagerService.getCurrentSkeleton())!=null?k:{};if(i==null||s==null)return!1;const l=(N=this._getSheetObject())==null?void 0:N.scene;if(l==null)return!1;const c=l.getViewport(w.SHEET_VIEWPORT_KEY.VIEW_MAIN);if(c==null)return!1;const d=(D=this._sheetSkeletonManagerService.getCurrentParam())==null?void 0:D.skeleton;if(d==null)return!1;const u=this._context.unit.getActiveSheet();if(!u)return!1;r=a.Tools.clamp(r,0,i.length-1),e=a.Tools.clamp(e,0,s.length-1);const{startColumn:h,startRow:g,ySplit:S,xSplit:f}=u.getFreeze(),p=this._getViewportBounding();if(p==null)return!1;const{startRow:v,startColumn:C,endRow:b,endColumn:R}=p;let T,M;if(r>=g&&e>=h-S&&(r<=v&&(T=r,t=!0),r>=b)){const W=i[r]-c.height;for(let H=v;H<=r&&(T=H+1,!(i[H]>=W));H++);}if(e>=h&&r>=g-S&&(e<=C&&(M=e,o=!0),e>=R)){const W=s[e]-c.width;for(let H=C;H<=e&&(M=H+1,!(s[H]>=W));H++);}if(T===void 0&&M===void 0)return!1;let{offsetX:y,offsetY:P,sheetViewStartRow:x,sheetViewStartColumn:A}=this._scrollManagerService.getCurrentScrollState()||{};if(T=T?Math.min(T,r):x+S,M=M?Math.min(M,e):A+f,o){y=0,M=e;const W=d.getHiddenColumnsInRange({startColumn:M-f,endColumn:M});M=M-W.length}if(t){P=0,T=r;const W=d.getHiddenRowsInRange({startRow:T-S,endRow:T});T=T-W.length}return this._commandService.syncExecuteCommand(ze.id,{sheetViewStartRow:Math.max(0,T-S),sheetViewStartColumn:Math.max(0,M-f),offsetX:y,offsetY:P})}};exports.SheetsScrollRenderController=yu([sn(1,a.Inject(a.Injector)),sn(2,a.Inject(exports.SheetSkeletonManagerService)),sn(3,a.IContextService),sn(4,a.ICommandService),sn(5,w.IRenderManagerService),sn(6,a.Inject(exports.SheetScrollManagerService))],exports.SheetsScrollRenderController);const _s={id:"sheet.operation.scroll-to-range",type:a.CommandType.OPERATION,handler:(n,r)=>{if(!r)return!1;const e=n.get(a.IUniverInstanceService);return n.get(w.IRenderManagerService).getRenderById(e.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET).getUnitId()).with(exports.SheetsScrollRenderController).scrollToRange(r.range,r.forceTop,r.forceLeft)}};class rl{constructor(){E(this,"_state",null);E(this,"_rect",null);E(this,"_state$",new O.BehaviorSubject(null));E(this,"state$",this._state$.asObservable());E(this,"_rect$",new O.BehaviorSubject(null));E(this,"rect$",this._rect$.asObservable());E(this,"_focus",!1);E(this,"_focus$",new O.BehaviorSubject(this._focus));E(this,"focus$",this._focus$.asObservable())}dispose(){this._state$.complete(),this._state=null,this._rect$.complete(),this._rect=null}setState(r){this._state=r,this._refresh(r)}getRect(){return this._rect}setRect(r){this._rect=r,this._rect$.next(r)}getState(){return this._state}setFocus(r=!1){this._focus=r,this._focus$.next(r)}_refresh(r){this._state$.next(r)}}const go=a.createIdentifier("univer.sheet-cell-editor-manager.service"),Pu="36",Ou="univer-sheet-container",il={sheetFooterBarHeight:Pu,sheetContainer:Ou};var xu=Object.getOwnPropertyDescriptor,Au=(n,r,e,t)=>{for(var o=t>1?void 0:t?xu(r,e):r,i=n.length-1,s;i>=0;i--)(s=n[i])&&(o=s(o)||o);return o},an=(n,r)=>(e,t)=>r(e,t,n);const oa=5,ra=2;exports.SheetCellEditorResizeService=class extends a.Disposable{constructor(r,e,t,o,i,s,l){super(),this._context=r,this._layoutService=e,this._cellEditorManagerService=t,this._editorBridgeService=o,this._renderManagerService=i,this._sheetSkeletonManagerService=s,this._univerInstanceService=l}fitTextSize(r){var A,k,N,D;const e=this._editorBridgeService.getEditCellState();if(!e)return;const{position:t,documentLayoutObject:o,canvasOffset:i,scaleX:s,scaleY:l}=e,{startX:c,startY:d,endX:u,endY:h}=t,g=this._univerInstanceService.getUnit(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY,a.UniverInstanceType.UNIVER_DOC);if(g==null)return;const S=this._getEditorSkeleton();if(!S)return;const f=this._predictingSize(t,i,S,o,s,l);if(!f)return;let{actualWidth:p,actualHeight:v}=f;const{verticalAlign:C,horizontalAlign:b,paddingData:R,fill:T}=o;p=p+((A=R.l)!=null?A:0)+((k=R.r)!=null?k:0),v=v+((N=R.t)!=null?N:0)+((D=R.b)!=null?D:0);let M=u-c,y=h-d;M<p&&(M=Math.ceil(p)),y<v&&(y=Math.ceil(v));let P=0;C===a.VerticalAlign.MIDDLE?P=(y-v)/2/l:C===a.VerticalAlign.TOP?P=R.t||0:P=(y-v)/l;let x=0;b===a.HorizontalAlign.CENTER?x=(M-p)/2/s:b===a.HorizontalAlign.RIGHT?x=(M-p)/s:x=R.l||0,P=P<(R.t||0)?R.t||0:P,x=x<(R.l||0)?R.l||0:x,g.updateDocumentDataMargin({t:P,l:x}),S.calculate(),this._editAreaProcessing(M,y,t,i,T,s,l,b,r)}_predictingSize(r,e,t,o,i=1,s=1){const{startX:l,endX:c}=r,{textRotation:d,wrapStrategy:u,paddingData:h}=o,g=this._univerInstanceService.getUnit(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY,a.UniverInstanceType.UNIVER_DOC),{vertexAngle:S}=w.convertTextRotation(d);if(u===a.WrapStrategy.WRAP&&S===0){g==null||g.updateDocumentDataPageSize(c-l),g==null||g.updateDocumentDataMargin({l:h.l,t:h.t}),t.calculate();const{actualWidth:C,actualHeight:b}=t.getActualSize();return{actualWidth:C*i,actualHeight:b*s}}const f=this._getEditorMaxSize(r,e,o.horizontalAlign);if(!f)return;g==null||g.updateDocumentDataPageSize(f.width/i),t.calculate();const p=t.getActualSize();let v=c-l;return v<p.actualWidth*i+oa*i&&(v=p.actualWidth*i+oa*i),g==null||g.updateDocumentDataPageSize(v/i),g==null||g.updateDocumentRenderConfig({horizontalAlign:a.HorizontalAlign.UNSPECIFIED,cellValueType:void 0}),{actualWidth:p.actualWidth*i,actualHeight:p.actualHeight*s}}_getEditorMaxSize(r,e,t){if(this._getEditorObject()==null)return;function i(b){return Number.parseInt(b.replace("px",""))}const l=this._context.engine.getCanvasElement(),c=l.getBoundingClientRect(),d=i(l.style.width),{width:u}=c,h=u/d,{startX:g,startY:S,endX:f}=r,p=this._context.engine.width,v=document.body.clientHeight-S-Number.parseFloat(il.sheetFooterBarHeight)-e.top-ra*2;let C=u-g;if(t===a.HorizontalAlign.CENTER){const b=p-f,R=g;C=f-g+Math.min(R,b)*2}else t===a.HorizontalAlign.RIGHT&&(C=f);return{height:v,width:C-ra,scaleAdjust:h}}_editAreaProcessing(r,e,t,o,i,s=1,l=1,c,d){var H;const u=this._getEditorObject();if(u==null)return;const g=this._context.engine.getCanvasElement();let{startX:S,startY:f}=t;const{document:p,scene:v,engine:C}=u,b=v.getViewport($.VIEWPORT_KEY.VIEW_MAIN),R=this._getEditorMaxSize(t,o,c),{height:T,width:M,scaleAdjust:y}=R;let P=e,x=b==null?void 0:b.getScrollBar();P>T?(x==null?b&&new w.ScrollBar(b,{enableHorizontal:!1,barSize:8}):b==null||b.resetCanvasSizeAndUpdateScroll(),b==null||b.scrollToViewportPos({viewportScrollY:P-T}),P=T):(x=null,(H=b==null?void 0:b.getScrollBar())==null||H.dispose()),r+=(x==null?void 0:x.barSize)||0,r>M&&(r=M),this._addBackground(v,r/s,e/l,i);const{scaleX:A,scaleY:k}=v.getPrecisionScale();v.transformByState({width:r*y/s,height:e*y/l,scaleX:s*y,scaleY:l*y}),p.resize(r*y/s,e*y/l),setTimeout(()=>{C.resizeBySize(w.fixLineWidthByScale(r,A),w.fixLineWidthByScale(P,k)),d==null||d()},0);const N=this._layoutService.getContentElement().getBoundingClientRect(),D=g.getBoundingClientRect();S=S*y+(D.left-N.left),f=f*y+(D.top-N.top);const W=t.endX-t.startX;c===a.HorizontalAlign.RIGHT?S+=(W-r)*y:c===a.HorizontalAlign.CENTER&&(S+=(W-r*y)/2),this._cellEditorManagerService.setState({startX:S,startY:f,endX:r*y+S,endY:P*y+f,show:!0})}_addBackground(r,e,t,o){const i="_backgroundRectHelperColor_",s=r.getObject(i);s==null&&o==null||(s==null?r.addObjects([new w.Rect(i,{width:e,height:t,fill:o,evented:!1})],$.DOCS_COMPONENT_MAIN_LAYER_INDEX):o==null?s.dispose():(s.setProps({fill:o}),s.transformByState({width:e,height:t})))}resizeCellEditor(r){var y;const e=this._cellEditorManagerService.getState();if(!e||!this._editorBridgeService.isVisible().visible)return;this._editorBridgeService.refreshEditCellPosition(!0);const t=this._editorBridgeService.getEditCellState();if(!t)return;const o=(y=this._sheetSkeletonManagerService.getSkeletonParam(t.sheetId))==null?void 0:y.skeleton;if(!o)return;const{row:i,column:s,scaleX:l,scaleY:c,position:d,canvasOffset:u,documentLayoutObject:h}=t,{horizontalAlign:g}=h,S=this._getEditorMaxSize(d,u,g);if(!S)return;const{height:f,width:p,scaleAdjust:v}=S,C=o.getCellWithCoordByIndex(i,s),b=Math.min((C.mergeInfo.endY-C.mergeInfo.startY)*c,f)*v,R=Math.min((C.mergeInfo.endX-C.mergeInfo.startX)*l,p)*v,T=e.endY-e.startY,M=e.endX-e.startX;if(T!==b||M!==R){if(this._editorBridgeService.refreshEditCellPosition(!0),!this._getEditorSkeleton())return;this.fitTextSize(r)}}_getEditorObject(){return Pr(this._editorBridgeService.getCurrentEditorId(),this._renderManagerService)}_getEditorSkeleton(){var r;return(r=this._renderManagerService.getRenderById(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY))==null?void 0:r.with(Re.DocSkeletonManagerService).getSkeleton()}};exports.SheetCellEditorResizeService=Au([an(1,I.ILayoutService),an(2,go),an(3,Se),an(4,w.IRenderManagerService),an(5,a.Inject(exports.SheetSkeletonManagerService)),an(6,a.IUniverInstanceService)],exports.SheetCellEditorResizeService);function bs(n){return n.getContextValue(a.FOCUSING_SHEET)}function ce(n){return n.getContextValue(a.FOCUSING_SHEET)&&n.getContextValue(a.FOCUSING_UNIVER_EDITOR)&&!n.getContextValue(a.EDITOR_ACTIVATED)&&!n.getContextValue(a.FOCUSING_COMMON_DRAWINGS)}function sl(n){return n.getContextValue(a.FOCUSING_SHEET)&&n.getContextValue(a.FOCUSING_UNIVER_EDITOR)&&!n.getContextValue(a.EDITOR_ACTIVATED)&&!n.getContextValue(a.FOCUSING_FX_BAR_EDITOR)&&!n.getContextValue(a.FOCUSING_COMMON_DRAWINGS)}function ku(n){return n.getContextValue(a.FOCUSING_SHEET)&&n.getContextValue(a.FOCUSING_UNIVER_EDITOR)&&n.getContextValue(a.EDITOR_ACTIVATED)}function Nu(n){return n.getContextValue(a.FOCUSING_UNIVER_EDITOR)&&n.getContextValue(a.EDITOR_ACTIVATED)}function al(n){return n.getContextValue(a.FOCUSING_FX_BAR_EDITOR)&&n.getContextValue(a.FOCUSING_UNIVER_EDITOR)}function Du(n){return n.getContextValue(a.FOCUSING_SHEET)&&n.getContextValue(a.EDITOR_ACTIVATED)&&n.getContextValue(a.FOCUSING_EDITOR_INPUT_FORMULA)&&n.getContextValue(a.FOCUSING_UNIVER_EDITOR)}function no(n){return n.getContextValue(a.FOCUSING_SHEET)&&n.getContextValue(a.FOCUSING_UNIVER_EDITOR)&&n.getContextValue(a.EDITOR_ACTIVATED)&&!n.getContextValue(a.FOCUSING_EDITOR_INPUT_FORMULA)&&!n.getContextValue(a.FOCUSING_EDITOR_STANDALONE)}const ll=[I.KeyCode.ARROW_DOWN,I.KeyCode.ARROW_UP,I.KeyCode.ARROW_LEFT,I.KeyCode.ARROW_RIGHT],Hu=[I.KeyCode.ENTER,I.KeyCode.TAB,...ll];function cl(){const n=[];for(const r of ll)n.push({id:Xt.id,binding:r,preconditions:e=>no(e),staticParameters:{visible:!1,eventType:w.DeviceInputEventType.Keyboard,keycode:r,isShift:!1}}),n.push({id:Xt.id,binding:r|I.MetaKeys.SHIFT,preconditions:e=>no(e),staticParameters:{visible:!1,eventType:w.DeviceInputEventType.Keyboard,keycode:r,isShift:!0}});return n}const dl={id:mo.id,binding:I.KeyCode.F2,description:"shortcut.sheet.start-editing",group:"4_sheet-edit",preconditions:ce,staticParameters:{visible:!0,eventType:w.DeviceInputEventType.Keyboard,keycode:I.KeyCode.F2}},ul={id:Ce.id,binding:I.KeyCode.ENTER,description:"shortcut.sheet.toggle-editing",group:"4_sheet-edit",preconditions:n=>no(n),staticParameters:{visible:!1,eventType:w.DeviceInputEventType.Keyboard,keycode:I.KeyCode.ENTER}},hl={id:Ce.id,binding:I.KeyCode.TAB,preconditions:n=>no(n),staticParameters:{visible:!1,eventType:w.DeviceInputEventType.Keyboard,keycode:I.KeyCode.TAB}},ml={id:Ce.id,binding:I.KeyCode.ESC,description:"shortcut.sheet.abort-editing",group:"4_sheet-edit",preconditions:n=>no(n),staticParameters:{visible:!1,eventType:w.DeviceInputEventType.Keyboard,keycode:I.KeyCode.ESC}},gl={id:$.BreakLineCommand.id,description:"shortcut.sheet.break-line",group:"4_sheet-edit",preconditions:n=>ku(n),binding:I.KeyCode.ENTER|I.MetaKeys.ALT},Sl={id:$.DeleteLeftCommand.id,preconditions:n=>Nu(n)||al(n),binding:I.KeyCode.BACKSPACE},fl={id:Ce.id,description:"shortcut.sheet.delete-and-start-editing",group:"4_sheet-edit",preconditions:n=>ce(n)&&!al(n),binding:I.KeyCode.BACKSPACE,staticParameters:{visible:!0,eventType:w.DeviceInputEventType.Keyboard,keycode:I.KeyCode.BACKSPACE}};function Vu(n){return n.startsWith("'")}function Wu(n){return n.slice(1)}const Uu={"0":"0","1":"1","2":"2","3":"3","4":"4","5":"5","6":"6","7":"7","8":"8","9":"9",A:"A",B:"B",C:"C",D:"D",E:"E",F:"F",G:"G",H:"H",I:"I",J:"J",K:"K",L:"L",M:"M",N:"N",O:"O",P:"P",Q:"Q",R:"R",S:"S",T:"T",U:"U",V:"V",W:"W",X:"X",Y:"Y",Z:"Z",a:"a",b:"b",c:"c",d:"d",e:"e",f:"f",g:"g",h:"h",i:"i",j:"j",k:"k",l:"l",m:"m",n:"n",o:"o",p:"p",q:"q",r:"r",s:"s",t:"t",u:"u",v:"v",w:"w",x:"x",y:"y",z:"z","%":"%","-":"-",".":".",":":":","/":"/","+":"+","@":"@","&":"&","*":"*","#":"#","=":"=",">":">","<":"<","$":"$",""":'"',"'":"'","(":"(",")":")"," ":" ",",":",","!":"!","?":"?",";":";","[":"[","]":"]","{":"{","}":"}"},ji={true:"TRUE",false:"FALSE"};function Lu(n){return[a.LocaleType.ZH_CN,a.LocaleType.ZH_TW].includes(n)}function Bu(n,r,e,t){let o=n;if(Lu(e)){if(n.startsWith("'")||n.startsWith("'"))return`'${n.slice(1)}`;o=Fu(o)}if(o.startsWith("="))return ju(n,o,r,t);const i=o.toLowerCase();return ji[i]?ji[i]:a.numfmt.parseValue(o)==null?n:o}function Fu(n){const r=/['"].*?['"]/g,e=[],t=n.split(r);n.replace(r,i=>(e.push(i),""));let o=t.join("").split("").map(Yu).join("");return e.forEach((i,s)=>{o=o.slice(0,s*2)+i+o.slice((s+1)*2)}),o}function ju(n,r,e,t){const o=e.sequenceNodesBuilder(r);if(!o)return n;let i=r,s=0;return o.forEach((l,c)=>{if(typeof l=="object"){const d=l.token;if(ji[d.toLowerCase()]){const u=l.startIndex+s+1,h=l.endIndex+s+2;i=ln(d.toLocaleUpperCase(),i,u,h)}else if(l.nodeType===K.sequenceNodeType.FUNCTION&&zu(d,t,o,c)||l.nodeType===K.sequenceNodeType.REFERENCE){const u=d.indexOf("!");if(u>-1){const h=d.substring(u+1),g=l.startIndex+s+(u+1)+1,S=l.endIndex+s+2;i=ln(h.toLocaleUpperCase(),i,g,S)}else{const h=l.startIndex+s+1,g=l.endIndex+s+2;i=ln(d.toLocaleUpperCase(),i,h,g)}}else if(d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'")){const u=l.startIndex+s+2,h=l.endIndex+s+1;i=ln(n.slice(u,h),i,u,h)}else if(l.nodeType!==K.sequenceNodeType.ARRAY){const u=a.numfmt.parseValue(d);if(u==null){const h=l.startIndex+s+1,g=l.endIndex+s+2;i=ln(n.slice(h,g),i,h,g)}else if(typeof u.v=="number"&&(u.z===void 0||!a.numfmt.isDate(u.z))){const h=`${u.v}`,g=l.startIndex+s+1,S=l.endIndex+s+2,{processedString:f,offset:p}=Gu(d,h);i=ln(f,i,g,S),s+=p}}}}),i}function zu(n,r,e,t){const o=r.getDescriptions();return e[t+1]!==K.matchToken.OPEN_BRACKET?!1:o.get(Xu(n).toLocaleUpperCase())!==void 0}function Xu(n){const r=/^@+/;return n.replace(r,"")}function Yu(n){return Uu[n]||n}function ln(n,r,e,t){return r.substring(0,e)+n+r.substring(t)}function Gu(n,r){var s,l;const e=((s=n.match(/^\s*/))==null?void 0:s[0])||"",t=((l=n.match(/\s*$/))==null?void 0:l[0])||"",o=e+r+t,i=o.length-n.length;return{processedString:o,offset:i}}const pl="range_selector",vl=n=>n.includes(pl);var Zu=Object.getOwnPropertyDescriptor,Ku=(n,r,e,t)=>{for(var o=t>1?void 0:t?Zu(r,e):r,i=n.length-1,s;i>=0;i--)(s=n[i])&&(o=s(o)||o);return o},ye=(n,r)=>(e,t)=>r(e,t,n);const ia=-1e3;exports.EditingRenderController=class extends a.Disposable{constructor(e,t,o,i,s,l,c,d,u,h,g,S,f,p,v,C){super();E(this,"_cursorChange",0);E(this,"_isUnitEditing",!1);E(this,"_workbookSelections");E(this,"_d");E(this,"_cursorTimeout");this._context=e,this._undoRedoService=o,this._contextService=i,this._renderManagerService=s,this._editorBridgeService=l,this._cellEditorManagerService=c,this._lexerTreeBuilder=d,this._functionService=u,this._textSelectionManagerService=h,this._commandService=g,this._localService=S,this._editorService=f,this._sheetCellEditorResizeService=p,this._univerInstanceService=v,this._sheetInterceptorService=C,this._workbookSelections=t.getWorkbookSelections(this._context.unitId),this.disposeWithMe(this._univerInstanceService.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_SHEET).subscribe(b=>{(b==null?void 0:b.getUnitId())===this._context.unitId?this._d=this._init():(this._disposeCurrent(),this._isUnitEditing&&(this._handleEditorInvisible({visible:!1,eventType:w.DeviceInputEventType.Keyboard,keycode:I.KeyCode.ESC,unitId:this._context.unitId}),this._isUnitEditing=!1))})),this._initEditorVisibilityListener()}dispose(){super.dispose(),this._disposeCurrent()}_disposeCurrent(){var e;(e=this._d)==null||e.dispose(),this._d=null}_init(){const e=new a.DisposableCollection;return this._subscribeToCurrentCell(e),this._initialCursorSync(e),this._listenEditorFocus(e),this._commandExecutedListener(e),this._initSkeletonListener(e),e.add(()=>{clearTimeout(this._cursorTimeout)}),this._cursorTimeout=setTimeout(()=>{this._cursorStateListener(e)},1e3),e}_initEditorVisibilityListener(){this.disposeWithMe(this._editorBridgeService.visible$.pipe(O.distinctUntilChanged((e,t)=>e.visible===t.visible)).subscribe(e=>{(e.unitId===a.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY||e.unitId===a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY||e.unitId===this._context.unitId)&&e.visible?(this._isUnitEditing=!0,this._handleEditorVisible(e)):this._isUnitEditing&&(this._handleEditorInvisible(e),this._isUnitEditing=!1)}))}_listenEditorFocus(e){const t=this._getEditorObject();t&&e.add(t.document.onPointerDown$.subscribeEvent(()=>{if(this._isUnitEditing&&this._editorBridgeService.isVisible()){const o=this._editorBridgeService.getEditCellState(),i=this._editorBridgeService.getCurrentEditorId();if(!o||!i)return;this._sheetCellEditorResizeService.fitTextSize()}}))}_initialCursorSync(e){e.add(this._cellEditorManagerService.focus$.pipe(O.filter(t=>!!t)).subscribe(()=>{var o;const t=(o=this._renderManagerService.getCurrentTypeOfRenderer(a.UniverInstanceType.UNIVER_DOC))==null?void 0:o.with($.DocSelectionRenderService);t&&t.sync()}))}_initSkeletonListener(e){const t=new Set(m.COMMAND_LISTENER_SKELETON_CHANGE);t.delete(m.SetWorksheetActiveOperation.id),e.add(this._commandService.onCommandExecuted(o=>{if(t.has(o.id)){switch(o.id){case m.MoveRowsMutation.id:case m.MoveColsMutation.id:case m.RemoveColMutation.id:case m.RemoveRowMutation.id:case m.InsertColMutation.id:case m.InsertRowMutation.id:{const i=this._editorBridgeService.getEditLocation();if(!i)break;const s={startRow:i.row,startColumn:i.column,endRow:i.row,endColumn:i.column},l=m.adjustRangeOnMutation(s,o);if(!l)break;const c=l.startRow,d=l.startColumn;this._editorBridgeService.updateEditLocation(c,d);break}}this._sheetCellEditorResizeService.resizeCellEditor(()=>{this._textSelectionManagerService.refreshSelection({unitId:a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY,subUnitId:a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY})})}}))}_subscribeToCurrentCell(e){e.add(this._editorBridgeService.currentEditCellState$.subscribe(t=>{var b,R;if(t==null||this._editorBridgeService.isForceKeepVisible())return;const o=this._editorBridgeService.getEditCellState();if(o==null)return;const{position:i,documentLayoutObject:s,scaleX:l,editorUnitId:c}=o;if(this._contextService.getContextValue(a.FOCUSING_EDITOR_STANDALONE))return;const d=this._getDocumentDataModel();if(d==null)return;const{startX:u,endX:h}=i,{textRotation:g,wrapStrategy:S,documentModel:f}=s,{vertexAngle:p}=w.convertTextRotation(g);S===a.WrapStrategy.WRAP&&p===0&&d.updateDocumentDataPageSize((h-u)/l),this._commandService.syncExecuteCommand($.ReplaceSnapshotCommand.id,{unitId:c,snapshot:f.getSnapshot()}),this._contextService.setContextValue(a.FOCUSING_EDITOR_BUT_HIDDEN,!0),this._textSelectionManagerService.replaceDocRanges([{startOffset:0,endOffset:0}],{unitId:a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY,subUnitId:a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY});const v=(b=this._renderManagerService.getRenderById(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY))==null?void 0:b.with($.DocSelectionRenderService),C=(R=this._renderManagerService.getRenderById(a.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY))==null?void 0:R.with($.DocSelectionRenderService);(v!=null&&v.canFocusing||C!=null&&C.canFocusing)&&(this._univerInstanceService.setCurrentUnitForType(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY),v==null||v.activate(ia,ia,!0))}))}_commandExecutedListener(e){e.add(this._commandService.onCommandExecuted(o=>{if(o.id===Re.RichTextEditingMutation.id){const i=o.params,{unitId:s}=i;if(!this._isCurrentSheetFocused()||vl(s)||(this._editorBridgeService.changeEditorDirty(!0),!this._editorBridgeService.isVisible().visible))return;s===a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY&&this._sheetCellEditorResizeService.fitTextSize()}}));const t=[Xt.id];e.add(this._commandService.onCommandExecuted(o=>{if(t.includes(o.id)){const i=o.params,{keycode:s,isShift:l}=i;if(s!=null&&(this._cursorChange===2||this._contextService.getContextValue(a.FOCUSING_FX_BAR_EDITOR))){this._moveInEditor(s,l);return}this._commandService.syncExecuteCommand(Ce.id,i)}o.id===mo.id&&(this._cursorChange=2)}))}_handleEditorVisible(e){var S,f,p;const{eventType:t,keycode:o}=e;this._cursorChange=t===w.DeviceInputEventType.PointerDown||t===w.DeviceInputEventType.Dblclick?2:1;const i=this._editorBridgeService.getEditLocation();if(i==null)return;this._commandService.syncExecuteCommand(_s.id,{range:{startRow:i.row,startColumn:i.column,endRow:i.row,endColumn:i.column}}),this._editorBridgeService.refreshEditCellPosition(!1);const{unitId:s,isInArrayFormulaRange:l=!1}=i,c=this._getEditorObject();if(c==null)return;const{document:d,scene:u}=c;this._contextService.setContextValue(a.EDITOR_ACTIVATED,!0);const h=this._getDocumentDataModel(),g=this._getEditorSkeleton(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY);if(!(!g||!h)){if(this._sheetCellEditorResizeService.fitTextSize(()=>{const v=u.getViewport($.VIEWPORT_KEY.VIEW_MAIN);v==null||v.scrollToViewportPos({viewportScrollX:Number.POSITIVE_INFINITY,viewportScrollY:Number.POSITIVE_INFINITY})}),t===w.DeviceInputEventType.Keyboard&&o===I.KeyCode.F2){d.makeDirty(),this._textSelectionManagerService.replaceDocRanges([{startOffset:0,endOffset:0}]);const v=((f=(S=h.getBody())==null?void 0:S.dataStream.length)!=null?f:2)-2;this._textSelectionManagerService.replaceDocRanges([{startOffset:v,endOffset:v}],{unitId:a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY,subUnitId:a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY})}else if(t===w.DeviceInputEventType.Keyboard||t===w.DeviceInputEventType.Dblclick&&l)this._emptyDocumentDataModel(h.getSnapshot().documentStyle,!!l),d.makeDirty(),(o===I.KeyCode.BACKSPACE||t===w.DeviceInputEventType.Dblclick)&&(g.calculate(),this._editorBridgeService.changeEditorDirty(!0)),this._textSelectionManagerService.replaceDocRanges([{startOffset:0,endOffset:0}],{unitId:a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY,subUnitId:a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY});else if(t===w.DeviceInputEventType.Dblclick){if(this._contextService.getContextValue(a.FOCUSING_EDITOR_INPUT_FORMULA))return;const v=h.getBody().dataStream.length-2||0;this._textSelectionManagerService.replaceDocRanges([{startOffset:v,endOffset:v}])}(p=this._renderManagerService.getRenderById(s))==null||p.scene.resetCursor()}}async _handleEditorInvisible(e){const t=this._editorBridgeService.getEditCellState(),o=this._univerInstanceService.getUnit(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY),i=a.Tools.deepClone(o==null?void 0:o.getSnapshot());let{keycode:s}=e;if(this._cursorChange=0,this._exitInput(e),t==null)return;this._editorBridgeService.getEditorDirty()===!1&&(s=I.KeyCode.ESC);const d=this._context.unit.getActiveSheet(),u=this._context.unitId,h=d.getSheetId(),{unitId:g,sheetId:S}=t;if(u===g&&S!==h&&await this._commandService.executeCommand(m.SetWorksheetActivateCommand.id,{subUnitId:S,unitId:g}),s===I.KeyCode.ESC){this._editorBridgeService.isForceKeepVisible()&&this._editorBridgeService.disableForceKeepVisible();const f=this._workbookSelections.getCurrentSelections();f&&(this._contextService.setContextValue(m.REF_SELECTIONS_ENABLED,!1),this._commandService.syncExecuteCommand(m.SetSelectionsOperation.id,{unitId:this._context.unit.getUnitId(),subUnitId:S,selections:f}));return}i&&await this._submitCellData(i),this._moveCursor(s)}_getEditorObject(){return Pr(this._editorBridgeService.getCurrentEditorId(),this._renderManagerService)}submitCellData(e){return this._submitCellData(e.getSnapshot())}async _submitCellData(e){const t=this._editorBridgeService.getEditCellState();if(t==null)return;const{unitId:o,sheetId:i,row:s,column:l}=t,c=this._context.unit;let d=c.getActiveSheet();if(!c.getSheetBySheetId(i))return;d=c.getActiveSheet();const h=qu({...d.getCellRaw(s,l)||{}},e,this._lexerTreeBuilder,this._localService,this._functionService,c.getStyles());if(!h)return;const g=await this._sheetInterceptorService.onWriteCell(c,d,s,l,h);g!==d.getCellRaw(s,l)&&this._commandService.executeCommand(m.SetRangeValuesCommand.id,{subUnitId:i,unitId:o,range:{startRow:s,startColumn:l,endRow:s,endColumn:l},value:g})}_exitInput(e){var i;this._contextService.setContextValue(a.FOCUSING_EDITOR_INPUT_FORMULA,!1),this._contextService.setContextValue(a.EDITOR_ACTIVATED,!1),this._contextService.setContextValue(a.FOCUSING_EDITOR_BUT_HIDDEN,!1),this._contextService.setContextValue(a.FOCUSING_FX_BAR_EDITOR,!1),this._cellEditorManagerService.setState({show:e.visible});const t=this._getEditorObject();(i=t==null?void 0:t.scene.getViewport($.VIEWPORT_KEY.VIEW_MAIN))==null||i.scrollToViewportPos({viewportScrollX:0,viewportScrollY:0});const o=this._editorBridgeService.getCurrentEditorId();o==null||!this._editorService.isSheetEditor(o)||(this._undoRedoService.clearUndoRedo(o),this._undoRedoService.clearUndoRedo(a.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY))}_moveCursor(e){if(e==null||!Hu.includes(e))return;let t=a.Direction.LEFT;switch(e){case I.KeyCode.ENTER:t=a.Direction.DOWN;break;case I.KeyCode.TAB:t=a.Direction.RIGHT;break;case I.KeyCode.ARROW_DOWN:t=a.Direction.DOWN;break;case I.KeyCode.ARROW_UP:t=a.Direction.UP;break;case I.KeyCode.ARROW_LEFT:t=a.Direction.LEFT;break;case I.KeyCode.ARROW_RIGHT:t=a.Direction.RIGHT;break}e===I.KeyCode.ENTER||e===I.KeyCode.TAB?this._commandService.executeCommand($e.id,{keycode:e,direction:t}):this._commandService.executeCommand(xe.id,{direction:t})}_cursorStateListener(e){const t=this._getEditorObject();if(!(t!=null&&t.document))return;const{document:o}=t;e.add(a.toDisposable(o.onPointerDown$.subscribeEvent(()=>{this._cursorChange===1&&(this._cursorChange=2)})))}_moveInEditor(e,t){let o=a.Direction.LEFT;e===I.KeyCode.ARROW_DOWN?o=a.Direction.DOWN:e===I.KeyCode.ARROW_UP?o=a.Direction.UP:e===I.KeyCode.ARROW_RIGHT&&(o=a.Direction.RIGHT),t?this._commandService.executeCommand($.MoveSelectionOperation.id,{direction:o}):this._commandService.executeCommand($.MoveCursorOperation.id,{direction:o})}_getDocumentDataModel(){return this._univerInstanceService.getUnit(a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY,a.UniverInstanceType.UNIVER_DOC)}_isCurrentSheetFocused(){var e;return((e=this._univerInstanceService.getFocusedUnit())==null?void 0:e.getUnitId())===this._context.unitId}_getEditorSkeleton(e){var t;return(t=this._renderManagerService.getRenderById(e))==null?void 0:t.with(Re.DocSkeletonManagerService).getSkeleton()}_getEditorViewModel(e){var t;return(t=this._renderManagerService.getRenderById(e))==null?void 0:t.with(Re.DocSkeletonManagerService).getViewModel()}_emptyDocumentDataModel(e,t){const o=(l,c)=>{const d=a.Tools.deepClone(l.getSnapshot()),u=this._getEditorViewModel(l.getUnitId());u!=null&&(Qu(d.body,t),c&&(d.documentStyle=e),d.drawings={},d.drawingsOrder=[],l.reset(d),u.reset(l))},i=this._getDocumentDataModel();i&&o(i,!0);const s=this._univerInstanceService.getUnit(a.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,a.UniverInstanceType.UNIVER_DOC);s&&o(s)}};exports.EditingRenderController=Ku([ye(1,a.Inject(m.SheetsSelectionsService)),ye(2,a.IUndoRedoService),ye(3,a.IContextService),ye(4,w.IRenderManagerService),ye(5,Se),ye(6,go),ye(7,a.Inject(K.LexerTreeBuilder)),ye(8,K.IFunctionService),ye(9,a.Inject(Re.DocSelectionManagerService)),ye(10,a.ICommandService),ye(11,a.Inject(a.LocaleService)),ye(12,$.IEditorService),ye(13,a.Inject(exports.SheetCellEditorResizeService)),ye(14,a.IUniverInstanceService),ye(15,a.Inject(m.SheetInterceptorService))],exports.EditingRenderController);function qu(n,r,e,t,o,i){var h,g,S;if((r==null?void 0:r.body)==null)return null;const{body:s}=r;n.t=void 0;const l=s.dataStream;let d=l.substring(l.length-2,l.length)===a.DEFAULT_EMPTY_DOCUMENT_VALUE?l.substring(0,l.length-2):l;const u=t.getCurrentLocale();if(d=Bu(d,e,u,o),(h=r.drawingsOrder)!=null&&h.length)n.v="",n.f=null,n.si=null,n.p=r,n.t=a.CellValueType.STRING;else if(n.s&&Id.isTextFormat((S=(g=i==null?void 0:i.get(n.s))==null?void 0:g.n)==null?void 0:S.pattern)){n.v=d,n.f=null,n.si=null,n.p=null,n.t=a.CellValueType.STRING,zi(s)&&s.dataStream!==`\r
2
2
  `&&(n.p=r);const f=sa(r);f&&(n.s=f)}else if(a.isFormulaString(d)){if(n.f===d)return null;const f=e.checkIfAddBracket(d);for(let p=0;p<f;p++)d+=K.matchToken.CLOSE_BRACKET;n.f=d,n.si=null,n.v=null,n.p=null}else if(Vu(d)){const f=Wu(d);n.v=f,n.f=null,n.si=null,n.p=null,n.t=a.CellValueType.FORCE_STRING}else if(zi(s))s.dataStream===`\r
3
3
  `?(n.v="",n.f=null,n.si=null,n.p=null):(n.p=r,n.v=null,n.f=null,n.si=null);else{if(d===""&&n.v==null&&n.p==null)return null;n.v=d,n.f=null,n.si=null,n.p=null;const f=sa(r);f&&(n.s=f)}return n}function zi(n){const{textRuns:r=[],paragraphs:e=[],customRanges:t,customBlocks:o=[]}=n,i=n.dataStream.replace(/(\r\n)+$/,""),s=["va"];return r.filter(l=>l.st<i.length).some(l=>{var d;return!!(l.ts&&Object.keys(l.ts).some(u=>s.includes(u)))||Object.keys((d=l.ts)!=null?d:{}).length&&l.ed-l.st<i.length})||e.some(l=>l.bullet)||e.length>=2||!!(t!=null&&t.length)||o.length>0}function sa(n){const{body:r}=n;if(!r)return null;const{textRuns:e=[]}=r;let t={};const o=r.dataStream.replace(`\r
4
4
  `,"");return e.forEach(i=>{const{st:s,ed:l,ts:c}=i;l-s>=o.length&&(t={...t,...c})}),Object.keys(t).length?t:null}function Qu(n,r=!1){n.dataStream=a.DEFAULT_EMPTY_DOCUMENT_VALUE,n.textRuns!=null&&(n.textRuns.length===1&&!r?(n.textRuns[0].st=0,n.textRuns[0].ed=1):n.textRuns=void 0),n.paragraphs!=null&&(n.paragraphs=[{startIndex:0}]),n.sectionBreaks!=null&&(n.sectionBreaks=void 0),n.tables!=null&&(n.tables=void 0),n.customRanges!=null&&(n.customRanges=void 0),n.customBlocks!=null&&(n.customBlocks=void 0)}var Ju=Object.getOwnPropertyDescriptor,$u=(n,r,e,t)=>{for(var o=t>1?void 0:t?Ju(r,e):r,i=n.length-1,s;i>=0;i--)(s=n[i])&&(o=s(o)||o);return o},Kr=(n,r)=>(e,t)=>r(e,t,n);const aa=hs.MARK_SELECTION,qt=a.createIdentifier("univer.mark-selection-service");exports.MarkSelectionService=class extends a.Disposable{constructor(e,t,o){super();E(this,"_shapeMap",new Map);this._currentService=e,this._renderManagerService=t,this._themeService=o}addShape(e,t=[],o=aa){var d;const i=this._currentService.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET),s=(d=i.getActiveSheet())==null?void 0:d.getSheetId();if(!s)return null;const l=a.Tools.generateRandomId(),c={selection:e,subUnitId:s,unitId:i.getUnitId(),zIndex:o,control:null,exits:t};return this._shapeMap.set(l,c),this.refreshShapes(),l}addShapeWithNoFresh(e,t=[],o=aa){var c;const i=this._currentService.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET),s=(c=i.getActiveSheet())==null?void 0:c.getSheetId();if(!s)return null;const l=a.Tools.generateRandomId();return this._shapeMap.set(l,{selection:e,subUnitId:s,unitId:i.getUnitId(),zIndex:o,control:null,exits:t}),l}refreshShapes(){var i;const e=this._currentService.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET);if(!e)return;const t=e.getUnitId(),o=(i=e.getActiveSheet())==null?void 0:i.getSheetId();this._shapeMap.forEach(s=>{var R;const{unitId:l,subUnitId:c,selection:d,control:u,zIndex:h}=s;if(u==null||u.dispose(),l!==t||c!==o)return;const g=this._renderManagerService.getRenderById(l);if(!g)return;const S=(R=this._renderManagerService.withCurrentTypeOfUnit(a.UniverInstanceType.UNIVER_SHEET,exports.SheetSkeletonManagerService))==null?void 0:R.getCurrentSkeleton();if(!S)return;const{scene:f}=g,{rowHeaderWidth:p,columnHeaderHeight:v}=S,C=new co(f,h,this._themeService,{enableAutoFill:!1,highlightHeader:!1,rowHeaderWidth:p,columnHeaderHeight:v}),b=Me(d,S);C.updateRangeBySelectionWithCoord(b),s.control=C})}getShapeMap(){return this._shapeMap}removeShape(e){const t=this._shapeMap.get(e);if(!t)return;const{control:o}=t;o==null||o.dispose(),this._shapeMap.delete(e)}removeAllShapes(){for(const e of this._shapeMap.values()){const{control:t}=e;t==null||t.dispose()}this._shapeMap.clear()}};exports.MarkSelectionService=$u([Kr(0,a.IUniverInstanceService),Kr(1,w.IRenderManagerService),Kr(2,a.Inject(a.ThemeService))],exports.MarkSelectionService);function Cl(n){return{strokeWidth:1.5,stroke:n.getCurrentTheme().primaryColor,fill:"rgba(178, 178, 178, 0.10)",widgets:{},strokeDash:8}}const eh=10,th=6;function nh(){return a.Tools.generateRandomId(th)}function oh(n){const r=n.match(/data-copy-id="([^\s]+)"/);return r&&r[1]?r[1]:null}class rh{constructor(){E(this,"_cache",new a.LRUMap(eh))}set(r,e){this._cache.set(r,e)}get(r){return this._cache.get(r)}del(r){this._cache.delete(r)}clear(){this._cache.clear()}clearWithUnitId(r){this._cache.forEach((e,t)=>{e.unitId===r&&this._cache.delete(t)})}}function rr(n,r){const e=r!=null?r:n.style,t={},o=n.tagName.toLowerCase();switch(o){case"b":case"em":case"strong":{t.bl=a.BooleanNumber.TRUE;break}case"s":{t.st={s:a.BooleanNumber.TRUE};break}case"u":{t.ul={s:a.BooleanNumber.TRUE};break}case"i":{t.it=a.BooleanNumber.TRUE;break}case"sub":case"sup":{t.va=o==="sup"?a.BaselineOffset.SUPERSCRIPT:a.BaselineOffset.SUBSCRIPT;break}}return ih(e,t),t}function ih(n,r){if(n instanceof CSSStyleDeclaration)for(let e=0;e<n.length;e++){const t=n[e],o=n.getPropertyValue(t);la(t,o,r)}else for(const e in n){const t=n[e];la(e,t,r)}}function la(n,r,e){switch(n){case"font-family":e.ff=r;break;case"font-size":{const t=Number.parseInt(r);Number.isNaN(t)||(r.endsWith("pt")?e.fs=t:r.endsWith("px")&&(e.fs=t*.75));break}case"font-style":r==="italic"&&(e.it=a.BooleanNumber.TRUE);break;case"font-weight":{(Number(r)>400||r==="bold")&&(e.bl=a.BooleanNumber.TRUE);break}case"text-decoration":{/underline/.test(r)?e.ul={s:a.BooleanNumber.TRUE}:/overline/.test(r)?e.ol={s:a.BooleanNumber.TRUE}:/line-through/.test(r)&&(e.st={s:a.BooleanNumber.TRUE});break}case"color":{try{const t=new a.ColorKit(r);t.isValid&&(e.cl={rgb:t.toRgbString()})}catch{}break}case"background-color":{const t=new a.ColorKit(r),o=t.isValid?t.toRgbString():"";o!==I.DEFAULT_BACKGROUND_COLOR_RGB&&o!==I.DEFAULT_BACKGROUND_COLOR_RGBA&&(e.bg={rgb:o});break}}}function sh(n){const r=document.createElement("body");return r.innerHTML=n,r}function Il(n){const r=n.style,e={};for(let t=0;t<r.length;t++){const o=r[t],i=r.getPropertyValue(o);switch(o){case"margin-top":{const s=Number.parseInt(i);e.spaceAbove={v:/pt/.test(i)?w.ptToPixel(s):s};break}case"margin-bottom":{const s=Number.parseInt(i);e.spaceBelow={v:/pt/.test(i)?w.ptToPixel(s):s};break}case"line-height":{const s=Number.parseFloat(i);e.lineSpacing=s;break}}}return Object.getOwnPropertyNames(e).length?e:null}function qr(n,r){const e=[];for(let t=0,o=n.length;t<o;t++)n[t]===a.DataStreamTreeTokenType.PARAGRAPH&&e.push({startIndex:t});return e}function ca(n,r,e){var s,l,c;const t=r.length,i=((s=e==null?void 0:e.length)!=null?s:0)===1&&e[0].st===0&&e[0].ed===t;return n.p?i&&((c=(l=n.p.body)==null?void 0:l.textRuns)!=null&&c.length)?(n.p.body.textRuns=[],{...n,s:e[0].ts}):n:i?{...n,s:e[0].ts}:n}const da=["color","background","font-size","text-align","vertical-align","font-weight","font-style","font-family","text-decoration","white-space","word-wrap","border-left","border-right","border-top","border-bottom","--data-rotate"];function ua(n,r){const e=n.tagName.toLowerCase();return typeof r=="string"?e===r:Array.isArray(r)?r.some(t=>t===e):r(n)}const Mr=class Mr{constructor(r){E(this,"_styleMap",new Map);E(this,"_styleCache",new Map);E(this,"_styleRules",[]);E(this,"_afterProcessRules",[]);E(this,"_dom",null);E(this,"_getCurrentSkeleton");this._getCurrentSkeleton=r.getCurrentSkeleton}static use(r){if(this._pluginList.includes(r))throw new Error(`Univer paste plugin ${r.name} already added`);this._pluginList.push(r)}convert(r){const e=Mr._pluginList.find(p=>p.checkPasteType(r));e&&(this._styleRules=[...e.stylesRules],this._afterProcessRules=[...e.afterProcessRules]);const t=new a.ObjectMatrix;this._dom=sh(r);const o=this._dom.querySelector("style");if(o){const p=document.createElement("div"),v=p.attachShadow({mode:"open"});document.body.appendChild(p),v.appendChild(o);for(const C of o.sheet.cssRules){const b=C,R=b.selectorText,T=b.style;this._styleMap.set(R,T)}o.remove(),p.remove()}const i={dataStream:"",textRuns:[]},s=[],l=[],c=r.match(/<table\b[^>]*>([\s\S]*?)<\/table>/gi),d=[];this.process(null,this._dom.childNodes,i,d);const{paragraphs:u,dataStream:h,textRuns:g,payloads:S,customRanges:f}=i;if(u){const p=u.map(v=>v.startIndex+1);p.unshift(0);for(let v=0;v<p.length;v++){let C;if(v===p.length-1){if(C=`${h.substring(p[v])}\r