/**
 * Minified by jsDelivr using Terser v5.48.0.
 * Original file: /npm/@univerjs/sheets-drawing-ui@0.25.1/lib/es/index.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
import{BooleanNumber,BuildTextUtils,CommandType,DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,DOCS_NORMAL_EDITOR_UNIT_ID_KEY,DOCS_ZEN_EDITOR_UNIT_ID_KEY,DependentOn,Direction,Disposable,DisposableCollection,DrawingTypeEnum,FOCUSING_COMMON_DRAWINGS,FOCUSING_FX_BAR_EDITOR,FOCUSING_PANEL_EDITOR,FOCUSING_SHAPE_TEXT_EDITOR,FOCUSING_SHEET,ICommandService,IConfigService,IContextService,IImageIoService,IPermissionService,IURLImageService,IUndoRedoService,IUniverInstanceService,ImageSourceType,Inject,Injector,InterceptorEffectEnum,LifecycleService,LifecycleStages,LocaleService,ObjectMatrix,ObjectRelativeFromH,ObjectRelativeFromV,PRINT_CHART_COMPONENT_KEY,Plugin,PositionedObjectLayoutType,RANGE_TYPE,Rectangle,RxDisposable,Tools,UniverInstanceType,UserManagerService,WrapTextType,createDocumentModelWithStyle,createIdentifier,fromEventSubject,generateRandomId,merge,registerDependencies,sequenceExecute,touchDependencies}from"@univerjs/core";import{ClearSheetDrawingTransformerOperation,DrawingApplyType,ISheetDrawingService,InsertSheetDrawingCommand,RemoveSheetDrawingCommand,SetDrawingApplyMutation,SetDrawingArrangeCommand,SetSheetDrawingCommand,SheetDrawingAnchorType,UniverSheetsDrawingPlugin,drawingPositionToTransform,transformToAxisAlignPosition,transformToDrawingPosition}from"@univerjs/sheets-drawing";import{CURSOR_TYPE,DRAWING_OBJECT_LAYER_INDEX,IRenderManagerService,ObjectType,Rect,SHEET_VIEWPORT_KEY,getCurrentTypeOfRenderer,getGroupState,transformObjectOutOfGroup}from"@univerjs/engine-render";import{Button,Checkbox,CheckboxGroup,FormLayout,MessageType,Radio,RadioGroup,Select,clsx,render,unmount}from"@univerjs/design";import{InnerPasteCommand,ReplaceSnapshotCommand,docDrawingPositionToTransform}from"@univerjs/docs-ui";import{DRAWING_IMAGE_ALLOW_IMAGE_LIST,DRAWING_IMAGE_COUNT_LIMIT,DRAWING_IMAGE_HEIGHT_LIMIT,DRAWING_IMAGE_WIDTH_LIMIT,IDrawingManagerService,IImageIoService as IImageIoService$1,ImageSourceType as ImageSourceType$1,ImageUploadStatusType,SetDrawingSelectedOperation,UniverDrawingPlugin,getDrawingImageAllowSize,getDrawingShapeKeyByDrawingSearch,getImageSize}from"@univerjs/drawing";import{COMMAND_LISTENER_SKELETON_CHANGE,DeleteRangeMoveLeftCommand,DeleteRangeMoveUpCommand,DeltaColumnWidthCommand,DeltaRowHeightCommand,IAutoFillService,INTERCEPTOR_POINT,InsertColCommand,InsertRangeMoveDownCommand,InsertRangeMoveRightCommand,InsertRowCommand,InterceptCellContentPriority,MoveColsCommand,MoveRangeCommand,MoveRowsCommand,RangeProtectionPermissionEditPoint,RemoveColCommand,RemoveRowCommand,SetColHiddenCommand,SetColHiddenMutation,SetColVisibleMutation,SetColWidthCommand,SetFrozenMutation,SetRangeValuesCommand,SetRowHeightCommand,SetRowHiddenCommand,SetRowHiddenMutation,SetRowVisibleMutation,SetSelectionsOperation,SetSpecificColsVisibleCommand,SetSpecificRowsVisibleCommand,SetWorksheetActiveOperation,SetWorksheetColWidthMutation,SetWorksheetRowAutoHeightMutation,SetWorksheetRowHeightMutation,SetWorksheetRowIsAutoHeightMutation,SheetInterceptorService,SheetPermissionCheckController,SheetSkeletonService,SheetsSelectionsService,WorkbookEditablePermission,WorkbookViewPermission,WorksheetEditPermission,WorksheetViewPermission,attachRangeWithCoord,discreteRangeToRange,getSheetCommandTarget}from"@univerjs/sheets";import{COPY_TYPE,EditingRenderController,HoverManagerService,IEditorBridgeService,ISheetClipboardService,ISheetSelectionRenderService,PREDEFINED_HOOK_NAME_PASTE,SetCellEditVisibleOperation,SetScrollOperation,SetZoomRatioOperation,SheetCanvasPopManagerService,SheetPrintInterceptorService,SheetSkeletonManagerService,getCurrentRangeDisable$,useHighlightRange,virtualizeDiscreteRanges}from"@univerjs/sheets-ui";import{CanvasFloatDomService,ComponentManager,ContextMenuGroup,ContextMenuPosition,IClipboardInterfaceService,IContextMenuService,IDialogService,ILocalFileService,IMenuManagerService,IMessageService,IShortcutService,ISidebarService,KeyCode,MenuItemType,PrintFloatDomSingle,RibbonInsertGroup,connectInjector,getMenuHiddenObservable,useDependency}from"@univerjs/ui";import{DocDrawingController,UniverDocsDrawingPlugin}from"@univerjs/docs-drawing";import{COMPONENT_IMAGE_POPUP_MENU,DrawingCommonPanel,DrawingRenderService,ImageCropperObject,ImageResetSizeOperation,OpenImageCropOperation,UniverDrawingUIPlugin}from"@univerjs/drawing-ui";import{BehaviorSubject,EMPTY,Subject,combineLatest,distinctUntilChanged,filter,map,of,switchMap,take,tap,throttleTime}from"rxjs";import{useCallback,useEffect,useMemo,useState}from"react";import{jsx,jsxs}from"react/jsx-runtime";const DeleteDrawingsCommand={id:"sheet.command.delete-drawing",type:CommandType.COMMAND,handler:e=>{const t=e.get(ICommandService),n=e.get(ISheetDrawingService).getFocusDrawings();if(0===n.length)return!1;const r=n[0].unitId,i=n.map(e=>{const{unitId:t,subUnitId:n,drawingId:r,drawingType:i}=e;return{unitId:t,subUnitId:n,drawingId:r,drawingType:i}});return t.executeCommand(RemoveSheetDrawingCommand.id,{unitId:r,drawings:i})}};function ungroupToGroup(e){const t=[];return e.forEach(e=>{const{parent:n,children:r}=e,{unitId:i,subUnitId:o,drawingId:a}=n,s=getGroupState(0,0,r.map(e=>e.transform||{})),d=r.map(e=>{const t=e.transform||{left:0,top:0},{unitId:n,subUnitId:r,drawingId:i}=e;return{unitId:n,subUnitId:r,drawingId:i,transform:{...t,left:t.left,top:t.top},groupId:a}}),c={unitId:i,subUnitId:o,drawingId:a,drawingType:DrawingTypeEnum.DRAWING_GROUP,groupBaseBound:{...n.groupBaseBound},transform:s};t.push({parent:c,children:d})}),t}function groupToUngroup(e){const t=[];return e.forEach(e=>{const{parent:n,children:r}=e,{unitId:i,subUnitId:o,drawingId:a,transform:s={width:0,height:0}}=n;if(null==s)return;const d=r.map(e=>{const{transform:t}=e,{unitId:r,subUnitId:i,drawingId:o}=e;return{unitId:r,subUnitId:i,drawingId:o,transform:transformObjectOutOfGroup(t||{},s,s.width||0,s.height||0,n.groupBaseBound),groupId:void 0}}),c={unitId:i,subUnitId:o,drawingId:a,drawingType:DrawingTypeEnum.DRAWING_GROUP,transform:{left:0,top:0}};t.push({parent:c,children:d})}),t}function cloneGroupParams(e){var t;const n=new Map;null===(t=e.flatChildren)||void 0===t||t.forEach(e=>n.set(e.drawingId,generateRandomId(10))),e.groups.forEach(e=>n.set(e.drawingId,generateRandomId(10)));const r={};for(const[t,a]of Object.entries(e.nestedIdRecord)){var i,o;const e=null!==(i=n.get(t))&&void 0!==i?i:t;r[e]={drawingId:e,children:null===(o=a.children)||void 0===o?void 0:o.map(e=>{var t;return null!==(t=n.get(e))&&void 0!==t?t:e})}}const a=[],s=[];for(const t of e.groups){var d,c;const e=null!==(d=n.get(t.drawingId))&&void 0!==d?d:t.drawingId,r=t.groupId?null!==(c=n.get(t.groupId))&&void 0!==c?c:t.groupId:void 0;s.push(cloneDrawingParam(t,e,r))}for(const t of e.flatChildren||[]){var l,u;const e=null!==(l=n.get(t.drawingId))&&void 0!==l?l:t.drawingId,r=t.groupId?null!==(u=n.get(t.groupId))&&void 0!==u?u:t.groupId:void 0;a.push(cloneDrawingParam(t,e,r))}return{cloned:{nestedIdRecord:r,flatChildren:a,groups:s},idMap:n}}function cloneDrawingParam(e,t,n){const r={...e};return t&&(r.drawingId=t),n?r.groupId=n:delete r.groupId,JSON.parse(JSON.stringify(r))}const GroupSheetDrawingCommand={id:"sheet.command.group-sheet-image",type:CommandType.COMMAND,handler:(e,t)=>{const n=e.get(ICommandService),r=e.get(IUndoRedoService),i=e.get(ISheetDrawingService);if(!t)return!1;const o=[];t.forEach(({parent:e,children:t})=>{o.push(e.unitId),t.forEach(e=>{o.push(e.unitId)})});const{unitId:a,subUnitId:s,undo:d,redo:c,objects:l}=i.getGroupDrawingOp(t);return!!n.syncExecuteCommand(SetDrawingApplyMutation.id,{op:c,unitId:a,subUnitId:s,objects:l,type:DrawingApplyType.GROUP})&&(r.pushUndoRedo({unitID:a,undoMutations:[{id:SetDrawingApplyMutation.id,params:{op:d,unitId:a,subUnitId:s,objects:groupToUngroup(l),type:DrawingApplyType.UNGROUP}},{id:ClearSheetDrawingTransformerOperation.id,params:o}],redoMutations:[{id:SetDrawingApplyMutation.id,params:{op:c,unitId:a,subUnitId:s,objects:l,type:DrawingApplyType.GROUP}},{id:ClearSheetDrawingTransformerOperation.id,params:o}]}),!0)}},UngroupSheetDrawingCommand={id:"sheet.command.ungroup-sheet-image",type:CommandType.COMMAND,handler:(e,t)=>{const n=e.get(ICommandService),r=e.get(IUndoRedoService),i=e.get(ISheetDrawingService);if(!t)return!1;const o=[];t.forEach(({parent:e,children:t})=>{o.push(e.unitId),t.forEach(e=>{o.push(e.unitId)})});const{unitId:a,subUnitId:s,undo:d,redo:c,objects:l}=i.getUngroupDrawingOp(t);return!!n.syncExecuteCommand(SetDrawingApplyMutation.id,{op:c,unitId:a,subUnitId:s,objects:l,type:DrawingApplyType.UNGROUP})&&(r.pushUndoRedo({unitID:a,undoMutations:[{id:SetDrawingApplyMutation.id,params:{op:d,unitId:a,subUnitId:s,objects:ungroupToGroup(l),type:DrawingApplyType.GROUP}},{id:ClearSheetDrawingTransformerOperation.id,params:o}],redoMutations:[{id:SetDrawingApplyMutation.id,params:{op:c,unitId:a,subUnitId:s,objects:l,type:DrawingApplyType.UNGROUP}},{id:ClearSheetDrawingTransformerOperation.id,params:o}]}),!0)}};function _typeof(e){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof(e)}function toPrimitive(e,t){if("object"!=_typeof(e)||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t||"default");if("object"!=_typeof(r))return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}function toPropertyKey(e){var t=toPrimitive(e,"string");return"symbol"==_typeof(t)?t:t+""}function _defineProperty(e,t,n){return(t=toPropertyKey(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function __decorateParam(e,t){return function(n,r){t(n,r,e)}}function __decorate(e,t,n,r){var i,o=arguments.length,a=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(a=(o<3?i(a):o>3?i(t,n,a):i(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}function rotatedBoundingBox(e,t,n){const r=n*Math.PI/180;return{rotatedWidth:Math.abs(e*Math.cos(r))+Math.abs(t*Math.sin(r)),rotatedHeight:Math.abs(e*Math.sin(r))+Math.abs(t*Math.cos(r))}}function getDrawingSizeByCell(e,t,n,r,i){var o;const{rotatedHeight:a,rotatedWidth:s}=rotatedBoundingBox(n,r,i),d=e.get(IRenderManagerService).getRenderById(t.unitId);if(!d)return!1;const c=null===(o=d.with(SheetSkeletonManagerService).getSkeletonParam(t.subUnitId))||void 0===o?void 0:o.skeleton;if(null==c)return!1;const l=c.getCellByIndex(t.row,t.col),u=l.mergeInfo.endX-l.mergeInfo.startX-2,g=l.mergeInfo.endY-l.mergeInfo.startY-2,h=s/a,m=Math.ceil(Math.min(u,g*h))/s,p=!m||Number.isNaN(m)?.001:m;return{width:n*p,height:r*p}}let SheetDrawingUpdateController=class extends Disposable{constructor(e,t,n,r,i,o,a,s,d,c,l,u,g,h,m){super(),this._context=e,this._commandService=t,this._sheetInterceptorService=n,this._selectionRenderService=r,this._imageIoService=i,this._fileOpenerService=o,this._sheetDrawingService=a,this._drawingManagerService=s,this._contextService=d,this._messageService=c,this._localeService=l,this._sheetSkeletonService=g,this._injector=h,this._urlImageService=m,_defineProperty(this,"_workbookSelections",void 0),this._workbookSelections=u.getWorkbookSelections(this._context.unitId),this._updateDrawingListener(),this._updateOrderListener(),this._groupDrawingListener(),this._focusDrawingListener()}async insertFloatImage(){const e=await this._fileOpenerService.openFile({multiple:!0,accept:DRAWING_IMAGE_ALLOW_IMAGE_LIST.map(e=>`.${e.replace("image/","")}`).join(",")}),t=e.length;return t>DRAWING_IMAGE_COUNT_LIMIT?(this._messageService.show({type:MessageType.Error,content:this._localeService.t("sheets-drawing-ui.update-status.exceedMaxCount",String(DRAWING_IMAGE_COUNT_LIMIT))}),!1):0!==t&&(e.forEach(async e=>await this.insertFloatImageByFile(e)),!0)}async insertCellImage(){const e=(await this._fileOpenerService.openFile({multiple:!1,accept:DRAWING_IMAGE_ALLOW_IMAGE_LIST.map(e=>`.${e.replace("image/","")}`).join(",")}))[0];return!!e&&(await this._insertCellImage(e),!0)}insertCellImageByFile(e,t){return this._insertCellImage(e,t)}async insertFloatImageByFile(e){var t;let n;try{n=await this._imageIoService.saveImage(e)}catch(e){const t=e.message;t===ImageUploadStatusType.ERROR_EXCEED_SIZE?this._messageService.show({type:MessageType.Error,content:this._localeService.t("sheets-drawing-ui.update-status.exceedMaxSize",String(getDrawingImageAllowSize()/1048576))}):t===ImageUploadStatusType.ERROR_IMAGE_TYPE?this._messageService.show({type:MessageType.Error,content:this._localeService.t("sheets-drawing-ui.update-status.invalidImageType")}):t===ImageUploadStatusType.ERROR_IMAGE&&this._messageService.show({type:MessageType.Error,content:this._localeService.t("sheets-drawing-ui.update-status.invalidImage")})}if(null==n)return;const{unitId:r,subUnitId:i}=this._getUnitInfo(),{imageId:o,imageSourceType:a,source:s,base64Cache:d}=n,{width:c,height:l,image:u}=await getImageSize(d||""),{width:g,height:h}=this._context.scene;this._imageIoService.addImageSourceCache(s,a,u);let m=1;if(c>DRAWING_IMAGE_WIDTH_LIMIT||l>DRAWING_IMAGE_HEIGHT_LIMIT){const e=DRAWING_IMAGE_WIDTH_LIMIT/c,t=DRAWING_IMAGE_HEIGHT_LIMIT/l;m=Math.max(e,t)}const p=this._sheetSkeletonService.getSkeletonParam(r,i);if(!p)return;const{skeleton:S}=p,I=this._getImagePosition(c*m,l*m,g,h,S);if(!I)return;const w=drawingPositionToTransform(I,p);if(!w)return;const f={unitId:r,subUnitId:i,drawingId:o,drawingType:DrawingTypeEnum.DRAWING_IMAGE,imageSourceType:a,source:s,transform:w,sheetTransform:I,axisAlignSheetTransform:null!==(t=transformToAxisAlignPosition(w,S))&&void 0!==t?t:I};return this._commandService.executeCommand(InsertSheetDrawingCommand.id,{unitId:r,drawings:[f]})}async _insertCellImage(e,t){let n;try{n=await this._imageIoService.saveImage(e)}catch(e){const t=e.message;t===ImageUploadStatusType.ERROR_EXCEED_SIZE?this._messageService.show({type:MessageType.Error,content:this._localeService.t("sheets-drawing-ui.update-status.exceedMaxSize",String(getDrawingImageAllowSize()/1048576))}):t===ImageUploadStatusType.ERROR_IMAGE_TYPE?this._messageService.show({type:MessageType.Error,content:this._localeService.t("sheets-drawing-ui.update-status.invalidImageType")}):t===ImageUploadStatusType.ERROR_IMAGE&&this._messageService.show({type:MessageType.Error,content:this._localeService.t("sheets-drawing-ui.update-status.invalidImage")})}if(null==n)return!1;const{imageId:r,imageSourceType:i,source:o,base64Cache:a}=n,{width:s,height:d,image:c}=await getImageSize(a||"");this._imageIoService.addImageSourceCache(o,i,c);const l=this._workbookSelections.getCurrentLastSelection();if(!l)return!1;let u=l.primary.actualRow,g=l.primary.actualColumn;l.primary.isMerged&&(u=l.primary.startRow,g=l.primary.startColumn);const h=createDocumentModelWithStyle("",{}),m=getDrawingSizeByCell(this._injector,{unitId:this._context.unitId,subUnitId:this._context.unit.getActiveSheet().getSheetId(),row:u,col:g},s,d,0);if(!m)return!1;const p={size:{width:m.width,height:m.height},positionH:{relativeFrom:ObjectRelativeFromH.PAGE,posOffset:0},positionV:{relativeFrom:ObjectRelativeFromV.PARAGRAPH,posOffset:0},angle:0},S={unitId:h.getUnitId(),subUnitId:h.getUnitId(),drawingId:r,drawingType:DrawingTypeEnum.DRAWING_IMAGE,imageSourceType:i,source:o,transform:docDrawingPositionToTransform(p),docTransform:p,behindDoc:BooleanNumber.FALSE,title:"",description:"",layoutType:PositionedObjectLayoutType.INLINE,wrapText:WrapTextType.BOTH_SIDES,distB:0,distL:0,distR:0,distT:0},I=BuildTextUtils.drawing.add({documentDataModel:h,drawings:[S],selection:{collapsed:!0,startOffset:0,endOffset:0}});var w,f;return!!I&&(h.apply(I),this._commandService.syncExecuteCommand(SetRangeValuesCommand.id,{value:{[null!==(w=null==t?void 0:t.row)&&void 0!==w?w:u]:{[null!==(f=null==t?void 0:t.col)&&void 0!==f?f:g]:{p:h.getSnapshot(),t:1}}},unitId:null==t?void 0:t.unitId,subUnitId:null==t?void 0:t.subUnitId}))}async insertCellImageByUrl(e,t){let n=e;try{n=await this._urlImageService.getImage(e)}catch(t){console.error(`Failed to get image from URLImageService: ${e}`,t)}const{width:r,height:i,image:o}=await getImageSize(n||"");this._imageIoService.addImageSourceCache(e,ImageSourceType.URL,o);const a=this._workbookSelections.getCurrentLastSelection();if(!a)return!1;const s=createDocumentModelWithStyle("",{}),d=getDrawingSizeByCell(this._injector,{unitId:this._context.unitId,subUnitId:this._context.unit.getActiveSheet().getSheetId(),row:a.primary.actualRow,col:a.primary.actualColumn},r,i,0);if(!d)return!1;const c={size:{width:d.width,height:d.height},positionH:{relativeFrom:ObjectRelativeFromH.PAGE,posOffset:0},positionV:{relativeFrom:ObjectRelativeFromV.PARAGRAPH,posOffset:0},angle:0},l={unitId:s.getUnitId(),subUnitId:s.getUnitId(),drawingId:generateRandomId(),drawingType:DrawingTypeEnum.DRAWING_IMAGE,imageSourceType:ImageSourceType.URL,source:e,transform:docDrawingPositionToTransform(c),docTransform:c,behindDoc:BooleanNumber.FALSE,title:"",description:"",layoutType:PositionedObjectLayoutType.INLINE,wrapText:WrapTextType.BOTH_SIDES,distB:0,distL:0,distR:0,distT:0},u=BuildTextUtils.drawing.add({documentDataModel:s,drawings:[l],selection:{collapsed:!0,startOffset:0,endOffset:0}});var g,h;return!!u&&(s.apply(u),this._commandService.syncExecuteCommand(SetRangeValuesCommand.id,{value:{[null!==(g=null==t?void 0:t.row)&&void 0!==g?g:a.primary.actualRow]:{[null!==(h=null==t?void 0:t.col)&&void 0!==h?h:a.primary.actualColumn]:{p:s.getSnapshot(),t:1}}},unitId:null==t?void 0:t.unitId,subUnitId:null==t?void 0:t.subUnitId}))}_getUnitInfo(){const e=this._context.unit,t=e.getActiveSheet();return{unitId:e.getUnitId(),subUnitId:t.getSheetId()}}_getImagePosition(e,t,n,r,i){const o=this._workbookSelections.getCurrentSelections();let a={startRow:0,endRow:0,startColumn:0,endColumn:0};o&&o.length>0&&(a=o[o.length-1].range);const s=attachRangeWithCoord(i,a);if(null==s)return;let{startColumn:d,startRow:c,startX:l,startY:u}=s,g=!1;if(l+e>n&&(l=n-e,l<0&&(l=0,e=n),g=!0),u+t>r&&(u=r-t,u<0&&(u=0,t=r),g=!0),g){const e=this._selectionRenderService.getCellWithCoordByOffset(l,u);if(null==e)return;l=e.startX,u=e.startY,d=e.actualColumn,c=e.actualRow}const h={column:d,columnOffset:0,row:c,rowOffset:0},m=this._selectionRenderService.getCellWithCoordByOffset(l+e,u+t);return null!=m?{from:h,to:{column:m.actualColumn,columnOffset:l+e-m.startX,row:m.actualRow,rowOffset:u+t-m.startY}}:void 0}_updateOrderListener(){this.disposeWithMe(this._drawingManagerService.featurePluginOrderUpdate$.subscribe(e=>{const{unitId:t,subUnitId:n,drawingIds:r,arrangeType:i}=e;this._commandService.executeCommand(SetDrawingArrangeCommand.id,{unitId:t,subUnitId:n,drawingIds:r,arrangeType:i})}))}_updateDrawingListener(){this.disposeWithMe(this._drawingManagerService.featurePluginUpdate$.subscribe(e=>{const t=[];0!==e.length&&(e.forEach(e=>{const{unitId:n,subUnitId:r,drawingId:i,transform:o}=e,a=this._sheetSkeletonService.getSkeletonParam(n,r);if(!o||!a)return;const{skeleton:s}=a,d=this._sheetDrawingService.getDrawingByParam({unitId:n,subUnitId:r,drawingId:i});if(null==d||d.unitId!==this._context.unitId)return;const c=transformToDrawingPosition({...d.transform,...o},s),l=transformToAxisAlignPosition({...d.transform,...o},s);if(null==c||null==l)return;const u={...e,transform:{...d.transform,...o,...drawingPositionToTransform(c,a)},sheetTransform:{...c},axisAlignSheetTransform:{...l}};t.push(u)}),t.length>0&&this._commandService.executeCommand(SetSheetDrawingCommand.id,{unitId:e[0].unitId,drawings:t}))}))}_getSheetTransformByParam(e,t){const{unitId:n,subUnitId:r,drawingId:i,transform:o}=e,a=this._sheetSkeletonService.getSkeleton(n,r);if(!o||!a)return null;const s=this._sheetDrawingService.getDrawingByParam({unitId:n,subUnitId:r,drawingId:i});let d=null==s?void 0:s.transform;if(t&&(d={}),!(t||s&&s.unitId===this._context.unitId))return null;const c=transformToDrawingPosition({...d,...o},a),l=transformToAxisAlignPosition({...d,...o},a);return c&&l?{sheetTransform:c,axisAlignSheetTransform:l}:null}_groupDrawingListener(){this.disposeWithMe(this._drawingManagerService.featurePluginGroupUpdate$.subscribe(e=>{const t=[];for(const n of e){const e=this._getSheetTransformByParam(n.parent,!0),r=[];for(const e of n.children){const t=this._getSheetTransformByParam(e,!1);null!=t&&r.push({...e,sheetTransform:t.sheetTransform,axisAlignSheetTransform:t.axisAlignSheetTransform})}const i={parent:{...n.parent,sheetTransform:null==e?void 0:e.sheetTransform,axisAlignSheetTransform:null==e?void 0:e.axisAlignSheetTransform},children:r};t.push(i)}if(t.length>0){this._commandService.executeCommand(GroupSheetDrawingCommand.id,t);const{unitId:n,subUnitId:r,drawingId:i}=e[0].parent;this._commandService.syncExecuteCommand(SetDrawingSelectedOperation.id,[{unitId:n,subUnitId:r,drawingId:i}])}})),this.disposeWithMe(this._drawingManagerService.featurePluginUngroupUpdate$.subscribe(e=>{const t=[];for(const n of e){const{children:e}=n,r=[];for(const t of e){const e=this._getSheetTransformByParam(t,!1);null!=e&&r.push({...t,sheetTransform:e.sheetTransform,axisAlignSheetTransform:e.axisAlignSheetTransform})}t.push({...n,children:r})}this._commandService.executeCommand(UngroupSheetDrawingCommand.id,t)}))}_focusDrawingListener(){this.disposeWithMe(this._drawingManagerService.focus$.subscribe(e=>{null==e||0===e.length?(this._contextService.setContextValue(FOCUSING_COMMON_DRAWINGS,!1),this._sheetDrawingService.focusDrawing([])):(this._contextService.setContextValue(FOCUSING_COMMON_DRAWINGS,!0),this._sheetDrawingService.focusDrawing(e))}))}};SheetDrawingUpdateController=__decorate([__decorateParam(1,ICommandService),__decorateParam(2,Inject(SheetInterceptorService)),__decorateParam(3,ISheetSelectionRenderService),__decorateParam(4,IImageIoService$1),__decorateParam(5,ILocalFileService),__decorateParam(6,ISheetDrawingService),__decorateParam(7,IDrawingManagerService),__decorateParam(8,IContextService),__decorateParam(9,IMessageService),__decorateParam(10,Inject(LocaleService)),__decorateParam(11,Inject(SheetsSelectionsService)),__decorateParam(12,Inject(SheetSkeletonService)),__decorateParam(13,Inject(Injector)),__decorateParam(14,IURLImageService)],SheetDrawingUpdateController);const InsertFloatImageCommand={id:"sheet.command.insert-float-image",type:CommandType.COMMAND,handler:async(e,t)=>{var n;const r=e.get(IUniverInstanceService),i=e.get(IRenderManagerService),o=null===(n=getCurrentTypeOfRenderer(UniverInstanceType.UNIVER_SHEET,r,i))||void 0===n?void 0:n.with(SheetDrawingUpdateController);if(!o)return!1;const a=null==t?void 0:t.files;if(a){const e=a.map(e=>o.insertFloatImageByFile(e));return(await Promise.all(e)).every(e=>e)}var s;return null!==(s=o.insertFloatImage())&&void 0!==s&&s}},InsertCellImageCommand={id:"sheet.command.insert-cell-image",type:CommandType.COMMAND,handler:e=>{var t,n;const r=e.get(IUniverInstanceService),i=e.get(IRenderManagerService);return null!==(t=null===(n=getCurrentTypeOfRenderer(UniverInstanceType.UNIVER_SHEET,r,i))||void 0===n?void 0:n.with(SheetDrawingUpdateController).insertCellImage())&&void 0!==t&&t}},MoveDrawingsCommand={id:"sheet.command.move-drawing",type:CommandType.COMMAND,handler:(e,t)=>{const n=e.get(ICommandService),r=e.get(ISheetDrawingService),i=e.get(SheetSkeletonService),{direction:o}=t,a=r.getFocusDrawings();if(0===a.length)return!1;const s=a[0].unitId,d=a.map(e=>{const{transform:t,unitId:n,subUnitId:r}=e,a=i.getSkeleton(n,r);if(!t||!a)return null;const s={...t},{left:d=0,top:c=0}=t;return o===Direction.UP?s.top=c-1:o===Direction.DOWN?s.top=c+1:o===Direction.LEFT?s.left=d-1:o===Direction.RIGHT&&(s.left=d+1),{...e,transform:s,sheetTransform:transformToDrawingPosition(s,a),axisAlignSheetTransform:transformToAxisAlignPosition(s,a)}}).filter(e=>null!=e);return!!n.syncExecuteCommand(SetSheetDrawingCommand.id,{unitId:s,drawings:d})&&(n.syncExecuteCommand(ClearSheetDrawingTransformerOperation.id,[s]),!0)}};let FileNamePart=function(e){return e.CELL_ADDRESS="cellAddress",e.COLUMN_VALUE="columnValue",e}({});const IBatchSaveImagesService=createIdentifier("sheets-drawing-ui.batch-save-images.service");function columnIndexToLetter(e){let t="",n=e;for(;n>=0;)t=String.fromCharCode(n%26+65)+t,n=Math.floor(n/26)-1;return t}function toA1Notation(e,t){return`${columnIndexToLetter(t)}${e+1}`}function rangeToA1Notation(e){const t=toA1Notation(e.startRow,e.startColumn),n=toA1Notation(e.endRow,e.endColumn);return t===n?t:`${t}:${n}`}function cellHasImage$1(e){var t,n;return!!((null==e||null===(t=e.p)||void 0===t||null===(t=t.drawingsOrder)||void 0===t?void 0:t.length)&&(null==e||null===(n=e.p)||void 0===n||null===(n=n.drawingsOrder)||void 0===n?void 0:n.length)>0)}function getCellImageData(e){var t,n;if(!(null===(t=e.p)||void 0===t||null===(t=t.drawingsOrder)||void 0===t?void 0:t.length)||!(null===(n=e.p)||void 0===n?void 0:n.drawings))return null;const r=e.p.drawingsOrder[0],i=e.p.drawings[r];return i&&"source"in i&&"imageSourceType"in i?i:null}function getFileExtension(e,t){if(t===ImageSourceType.BASE64){const t=e.match(/^data:image\/(\w+);/);if(t)return"jpeg"===t[1]?"jpg":t[1]}if(t===ImageSourceType.URL){const t=e.match(/\.(\w+)(?:\?|$)/);if(t)return t[1].toLowerCase()}return"png"}async function imageSourceToBlob(e,t){if(t===ImageSourceType.BASE64)return(await fetch(e)).blob();if(t===ImageSourceType.URL)return(await fetch(e)).blob();throw new Error("UUID image type requires additional handling")}let BatchSaveImagesService=class extends Disposable{constructor(e,t,n,r){super(),this._univerInstanceService=e,this._selectionService=t,this._imageIoService=n,this._urlImageService=r}registerURLImageDownloader(e){return this._urlImageService.registerURLImageDownloader(e)}getCellImagesInSelection(){const e=this._univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_SHEET);if(!e)return[];const t=e.getActiveSheet();if(!t)return[];const n=this._selectionService.getCurrentSelections();if(!n||0===n.length)return[];const r=t.getCellMatrix(),i=[];for(const e of n){const{startRow:t,endRow:n,startColumn:o,endColumn:a}=e.range;for(let e=t;e<=n;e++)for(let t=o;t<=a;t++){const n=r.getValue(e,t);if(cellHasImage$1(n)){const r=getCellImageData(n);r&&i.push({row:e,col:t,cellAddress:toA1Notation(e,t),source:r.source,imageSourceType:r.imageSourceType,imageId:r.drawingId})}}}return i}getCellImagesFromRanges(e,t,n){const r=this._univerInstanceService.getUnit(e,UniverInstanceType.UNIVER_SHEET);if(!r)return[];const i=r.getSheetBySheetId(t);if(!i)return[];const o=i.getCellMatrix(),a=[];for(const e of n){const{startRow:t,endRow:n,startColumn:r,endColumn:i}=e;for(let e=t;e<=n;e++)for(let t=r;t<=i;t++){const n=o.getValue(e,t);if(cellHasImage$1(n)){const r=getCellImageData(n);r&&a.push({row:e,col:t,cellAddress:toA1Notation(e,t),source:r.source,imageSourceType:r.imageSourceType,imageId:r.drawingId})}}}return a}getDataColumns(){const e=this._univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_SHEET);if(!e)return[];const t=e.getActiveSheet();if(!t)return[];const n=this._selectionService.getCurrentSelections();if(!n||0===n.length)return[];const r=t.getCellMatrix(),i=r.getDataRange();let o=1/0,a=-1/0;const s=new Set;for(const e of n){o=Math.min(o,e.range.startRow),a=Math.max(a,e.range.endRow);for(let t=e.range.startColumn;t<=e.range.endColumn;t++)s.add(t)}const d=new Set;for(let e=i.startColumn;e<=i.endColumn;e++)if(!s.has(e))for(let t=o;t<=a;t++){const n=r.getValue(t,e);var c,l;if(n)if((null===(c=n.v)||void 0===c?void 0:c.toString())||(null===(l=n.p)||void 0===l||null===(l=l.body)||void 0===l||null===(l=l.dataStream)||void 0===l?void 0:l.trim())){d.add(e);break}}const u=[],g=Array.from(d).sort((e,t)=>e-t);for(const e of g)u.push({index:e,label:columnIndexToLetter(e)});return u}getDataColumnsForRanges(e,t,n){const r=this._univerInstanceService.getUnit(e,UniverInstanceType.UNIVER_SHEET);if(!r)return[];const i=r.getSheetBySheetId(t);if(!i)return[];const o=i.getCellMatrix(),a=o.getDataRange();let s=1/0,d=-1/0;const c=new Set;for(const e of n){s=Math.min(s,e.startRow),d=Math.max(d,e.endRow);for(let t=e.startColumn;t<=e.endColumn;t++)c.add(t)}const l=new Set;for(let e=a.startColumn;e<=a.endColumn;e++)if(!c.has(e))for(let t=s;t<=d;t++){const n=o.getValue(t,e);var u,g;if(n)if((null===(u=n.v)||void 0===u?void 0:u.toString())||(null===(g=n.p)||void 0===g||null===(g=g.body)||void 0===g||null===(g=g.dataStream)||void 0===g?void 0:g.trim())){l.add(e);break}}const h=[],m=Array.from(l).sort((e,t)=>e-t);for(const e of m)h.push({index:e,label:columnIndexToLetter(e)});return h}getSelectionRangeNotation(){const e=this._selectionService.getCurrentSelections();return e&&0!==e.length?e.map(e=>rangeToA1Notation(e.range)).join(", "):""}getSelectionRowRange(){const e=this._selectionService.getCurrentSelections();if(!e||0===e.length)return null;let t=1/0,n=-1/0;for(const r of e)t=Math.min(t,r.range.startRow),n=Math.max(n,r.range.endRow);return{startRow:t,endRow:n}}getSelectionColumnIndices(){const e=this._selectionService.getCurrentSelections();if(!e||0===e.length)return new Set;const t=new Set;for(const n of e)for(let e=n.range.startColumn;e<=n.range.endColumn;e++)t.add(e);return t}generateFileName(e,t){const n=this._univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_SHEET),r=getFileExtension(e.source,e.imageSourceType),i=[];for(const r of t.fileNameParts)if("cellAddress"===r)i.push(e.cellAddress);else if("columnValue"===r&&void 0!==t.columnIndex){const r=null==n?void 0:n.getActiveSheet();if(r){const n=r.getCellMatrix().getValue(e.row,t.columnIndex);if(n){var o,a;const e=(null===(o=n.v)||void 0===o?void 0:o.toString())||(null===(a=n.p)||void 0===a||null===(a=a.body)||void 0===a||null===(a=a.dataStream)||void 0===a?void 0:a.trim())||"";if(e){const t=e.replace(/[<>:"/\\|?*]/g,"_").trim();t&&i.push(t)}}}}return 0===i.length?`${e.cellAddress}.${r}`:`${i.join("_")}.${r}`}generateFileNameWithContext(e,t,n,r){const i=this._univerInstanceService.getUnit(n,UniverInstanceType.UNIVER_SHEET),o=getFileExtension(e.source,e.imageSourceType),a=[];for(const n of t.fileNameParts)if("cellAddress"===n)a.push(e.cellAddress);else if("columnValue"===n&&void 0!==t.columnIndex){const n=null==i?void 0:i.getSheetBySheetId(r);if(n){const r=n.getCellMatrix().getValue(e.row,t.columnIndex);if(r){var s,d;const e=(null===(s=r.v)||void 0===s?void 0:s.toString())||(null===(d=r.p)||void 0===d||null===(d=d.body)||void 0===d||null===(d=d.dataStream)||void 0===d?void 0:d.trim())||"";if(e){const t=e.replace(/[<>:"/\\|?*]/g,"_").trim();t&&a.push(t)}}}}return 0===a.length?`${e.cellAddress}.${o}`:`${a.join("_")}.${o}`}async saveImages(e,t){const n=await window.showDirectoryPicker({mode:"readwrite"}),r=new Map;for(const o of e){var i;let e=this.generateFileName(o,t);const a=e.replace(/\.\w+$/,""),s=(null===(i=e.match(/\.\w+$/))||void 0===i?void 0:i[0])||".png",d=r.get(a)||0;d>0&&(e=`${a}_${d}${s}`),r.set(a,d+1);try{const t=await this._getImageBlob(o),r=await(await n.getFileHandle(e,{create:!0})).createWritable();await r.write(t),await r.close()}catch(t){throw console.error(`Failed to save image ${e}:`,t),t}}}async saveImagesWithContext(e,t,n,r){const i=await window.showDirectoryPicker({mode:"readwrite"}),o=new Map;for(const s of e){var a;let e=this.generateFileNameWithContext(s,t,n,r);const d=e.replace(/\.\w+$/,""),c=(null===(a=e.match(/\.\w+$/))||void 0===a?void 0:a[0])||".png",l=o.get(d)||0;l>0&&(e=`${d}_${l}${c}`),o.set(d,l+1);try{const t=await this._getImageBlob(s),n=await(await i.getFileHandle(e,{create:!0})).createWritable();await n.write(t),await n.close()}catch(t){throw console.error(`Failed to save image ${e}:`,t),t}}}async downloadSingleImage(e){const t=getFileExtension(e.source,e.imageSourceType),n=`${e.cellAddress}.${t}`;try{const t=await this._getImageBlob(e),r=URL.createObjectURL(t),i=document.createElement("a");i.href=r,i.download=n,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(r)}catch(e){throw console.error(`Failed to download image ${n}:`,e),e}}async _getImageBlob(e){return e.imageSourceType===ImageSourceType.UUID?imageSourceToBlob(await this._imageIoService.getImage(e.source),ImageSourceType.URL):e.imageSourceType===ImageSourceType.URL?this._urlImageService.downloadImage(e.source):imageSourceToBlob(e.source,e.imageSourceType)}};BatchSaveImagesService=__decorate([__decorateParam(0,IUniverInstanceService),__decorateParam(1,Inject(SheetsSelectionsService)),__decorateParam(2,IImageIoService),__decorateParam(3,IURLImageService)],BatchSaveImagesService);const BATCH_SAVE_IMAGES_DIALOG_ID="sheet.dialog.batch-save-images",SaveCellImagesCommand={id:"sheet.command.save-cell-images",type:CommandType.COMMAND,handler:async e=>{const t=e.get(IDialogService),n=e.get(IBatchSaveImagesService),r=n.getCellImagesInSelection();if(1===r.length)try{return await n.downloadSingleImage(r[0]),!0}catch(e){return console.error("Failed to download image:",e),!1}const i=e.get(LocaleService),o=n.getSelectionRangeNotation(),a=`${i.t("sheets-drawing-ui.save.title")} (${o})`;return t.open({id:BATCH_SAVE_IMAGES_DIALOG_ID,draggable:!0,width:360,title:{title:a},children:{label:BATCH_SAVE_IMAGES_DIALOG_ID},destroyOnClose:!0,preservePositionOnDestroy:!0,onClose:()=>t.close(BATCH_SAVE_IMAGES_DIALOG_ID)}),!0}},COMPONENT_SHEET_DRAWING_PANEL="COMPONENT_SHEET_DRAWING_PANEL",SidebarSheetDrawingOperation={id:"sidebar.operation.sheet-image",type:CommandType.COMMAND,handler:async(e,t)=>{const n=e.get(ISidebarService),r=e.get(LocaleService),i=e.get(IUniverInstanceService),o=e.get(ICommandService);if(!getSheetCommandTarget(i))return!1;if("open"===t.value)n.open({header:{title:r.t("sheets-drawing-ui.panel.title")},children:{label:COMPONENT_SHEET_DRAWING_PANEL},onClose:()=>{o.syncExecuteCommand(SetDrawingSelectedOperation.id,[])},width:360});else n.close();return!0}},EditSheetDrawingOperation={id:"sheet.operation.edit-sheet-image",type:CommandType.OPERATION,handler:(e,t)=>{const n=e.get(ICommandService);return null!=t&&(n.syncExecuteCommand(SetDrawingSelectedOperation.id,[t]),n.executeCommand(SidebarSheetDrawingOperation.id,{value:"open"}),!0)}},specialPastes$1=[PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_COL_WIDTH,PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_VALUE,PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_FORMAT,PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_FORMULA];let SheetsDrawingGroupCopyPasteController=class extends Disposable{constructor(e,t,n,r,i){super(),this._sheetClipboardService=e,this._renderManagerService=t,this._sheetSkeletonService=n,this._sheetDrawingService=r,this._drawingManagerService=i,_defineProperty(this,"_featurePasteHooks",[]),_defineProperty(this,"_copyInfo",void 0),this._initCopyPaste()}get _focusedDrawings(){return this._sheetDrawingService.getFocusDrawings()}_initCopyPaste(){this._sheetClipboardService.addClipboardHook({id:"SHEET_DRAWING_GROUP",onBeforeCopy:(e,t)=>{this._copyInfo=null;const n=this._focusedDrawings;if(0===n.length)return;const r=n.find(e=>e.drawingType===DrawingTypeEnum.DRAWING_GROUP);if(!r)return;const i=this._drawingManagerService.getDrawingsByGroupNested({unitId:r.unitId,subUnitId:r.subUnitId,drawingId:r.drawingId});i&&(this._copyInfo={unitId:r.unitId,subUnitId:r.subUnitId,groupNestedParam:i})},onPasteCells:(e,t,n,r)=>{if(!this._copyInfo)return{redos:[],undos:[]};const{pasteType:i}=r;return specialPastes$1.includes(i)?{redos:[],undos:[]}:this._generateGroupPasteMutations(t)},onPasteUnrecognized:e=>this._copyInfo?this._generateGroupPasteMutations(e):{redos:[],undos:[]}})}registerFeaturePasteHook(e){this._featurePasteHooks.push(e)}_getGroupFeaturePasteMutations(e){const t=[],n=[];for(const r of this._featurePasteHooks){const i=r(e);t.push(...i.redos),n.push(...i.undos)}return{redos:t,undos:n}}_generateGroupPasteMutations(e){var t;if(!this._copyInfo)return{redos:[],undos:[]};const{unitId:n,subUnitId:r,range:i}=e,o=this._sheetSkeletonService.getSkeleton(n,r);if(!o)return{redos:[],undos:[]};const{groupNestedParam:a}=this._copyInfo,s=a.groups[a.groups.length-1],{cloned:d,idMap:c}=cloneGroupParams(a),l=d.groups[d.groups.length-1].drawingId,u=discreteRangeToRange(i),g=attachRangeWithCoord(o,{startRow:u.startRow,endRow:u.endRow,startColumn:u.startColumn,endColumn:u.endColumn});if(!g)return{redos:[],undos:[]};const h={...s.transform,left:g.startX,top:g.startY},m=[...(null!==(t=d.flatChildren)&&void 0!==t?t:[]).map(e=>({...e,unitId:n,subUnitId:r})),...d.groups.map(e=>{var t,i;return e.drawingId!==l?{...e,unitId:n,subUnitId:r}:{...e,unitId:n,subUnitId:r,transform:h,sheetTransform:null!==(t=transformToDrawingPosition(h,o))&&void 0!==t?t:s.sheetTransform,axisAlignSheetTransform:null!==(i=transformToAxisAlignPosition(h,o))&&void 0!==i?i:s.sheetTransform}})],{undo:p,redo:S,objects:I}=this._sheetDrawingService.getBatchAddOp(m),w=[{id:SetDrawingApplyMutation.id,params:{op:S,unitId:n,subUnitId:r,objects:I,type:DrawingApplyType.INSERT}}],f=[{id:SetDrawingApplyMutation.id,params:{op:p,unitId:n,subUnitId:r,objects:I,type:DrawingApplyType.REMOVE}}],_=this._getGroupFeaturePasteMutations({fromUnitId:this._copyInfo.unitId,fromSubUnitId:this._copyInfo.subUnitId,toUnitId:n,toSubUnitId:r,idMap:c,cloned:d});return w.push(..._.redos),f.push(..._.undos),{redos:w,undos:f}}dispose(){this._copyInfo=null,this._featurePasteHooks.length=0,super.dispose()}};SheetsDrawingGroupCopyPasteController=__decorate([__decorateParam(0,ISheetClipboardService),__decorateParam(1,IRenderManagerService),__decorateParam(2,Inject(SheetSkeletonService)),__decorateParam(3,ISheetDrawingService),__decorateParam(4,IDrawingManagerService)],SheetsDrawingGroupCopyPasteController);const SHEETS_IMAGE_MENU_ID="sheet.menu.image";function ImageMenuFactory(e){return{id:"sheet.menu.image",type:MenuItemType.SUBITEMS,icon:"AddImageIcon",tooltip:"sheets-drawing-ui.title",hidden$:getMenuHiddenObservable(e,UniverInstanceType.UNIVER_SHEET),disabled$:getCurrentRangeDisable$(e,{workbookTypes:[WorkbookEditablePermission],worksheetTypes:[WorksheetEditPermission],rangeTypes:[RangeProtectionPermissionEditPoint]})}}function UploadFloatImageMenuFactory(e){return{id:InsertFloatImageCommand.id,title:"sheets-drawing-ui.upload.float",type:MenuItemType.BUTTON,hidden$:getMenuHiddenObservable(e,UniverInstanceType.UNIVER_SHEET)}}function UploadCellImageMenuFactory(e){return{id:InsertCellImageCommand.id,title:"sheets-drawing-ui.upload.cell",type:MenuItemType.BUTTON,hidden$:getMenuHiddenObservable(e,UniverInstanceType.UNIVER_SHEET)}}var name="@univerjs/sheets-drawing-ui",version="0.25.1";const SHEETS_DRAWING_UI_PLUGIN_CONFIG_KEY="sheets-drawing-ui.config",configSymbol=Symbol("sheets-drawing-ui.config"),defaultPluginConfig={};let DrawingContextMenuController=class extends RxDisposable{constructor(e,t,n,r){super(),this._drawingManagerService=e,this._contextMenuService=t,this._renderManagerService=n,this._univerInstanceService=r,this._init()}_init(){this._univerInstanceService.getAllUnitsForType(UniverInstanceType.UNIVER_SHEET).forEach(e=>this._contextMenuListener(e))}_contextMenuListener(e){var t;if(!e)return;const n=null===(t=this._renderManagerService.getRenderById(e.getUnitId()))||void 0===t?void 0:t.scene;if(!n)return;const r=n.getTransformerByCreate();r&&this.disposeWithMe(r.changeEnd$.subscribe(e=>{const{event:t}=e;if(2!==t.button)return;const n=r.getSelectedObjectMap();if(0!==n.size){for(const e of n.values()){const t=e.oKey;if(!this._drawingManagerService.getDrawingOKey(t))return}this._contextMenuService.triggerContextMenu(t,ContextMenuPosition.DRAWING)}}))}};DrawingContextMenuController=__decorate([__decorateParam(0,IDrawingManagerService),__decorateParam(1,IContextMenuService),__decorateParam(2,IRenderManagerService),__decorateParam(3,IUniverInstanceService)],DrawingContextMenuController);let SheetCellImageHoverRenderController=class extends Disposable{constructor(e,t,n,r,i){super(),this._context=e,this._hoverManagerService=t,this._selectionsService=n,this._drawingRenderService=r,this._sheetSkeletonManagerService=i,_defineProperty(this,"_isSetCursor",!1),this._initHover(),this._initImageClick()}_initHover(){this.disposeWithMe(this._hoverManagerService.currentRichTextNoDistinct$.pipe(throttleTime(33)).subscribe(e=>{var t,n;let r=[];null!==e&&(r=this._selectionsService.getWorkbookSelections(this._context.unitId).getCurrentSelections()),r.length>0&&(null==e?void 0:e.unitId)===this._context.unitId&&(null==e?void 0:e.drawing)&&1===r.length&&(null===(t=r[0].primary)||void 0===t?void 0:t.actualRow)===e.row&&(null===(n=r[0].primary)||void 0===n?void 0:n.actualColumn)===e.col?(this._isSetCursor=!0,this._context.scene.setCursor(CURSOR_TYPE.ZOOM_IN)):this._isSetCursor&&(this._isSetCursor=!1,this._context.scene.resetCursor())}))}_initImageClick(){this.disposeWithMe(this._hoverManagerService.currentClickedCell$.subscribe(e=>{if((null==e?void 0:e.drawing)&&this._isSetCursor){var t;const n=e.drawing.drawing.drawingOrigin,r=null===(t=this._sheetSkeletonManagerService.getCurrentSkeleton())||void 0===t?void 0:t.imageCacheMap.getImage(n.imageSourceType,n.source);if(!r)return;this._drawingRenderService.previewImage("preview-cell-image",r.src,r.width,r.height),this._context.scene.resetCursor(),this._isSetCursor=!1}}))}};SheetCellImageHoverRenderController=__decorate([__decorateParam(1,Inject(HoverManagerService)),__decorateParam(2,Inject(SheetsSelectionsService)),__decorateParam(3,Inject(DrawingRenderService)),__decorateParam(4,Inject(SheetSkeletonManagerService))],SheetCellImageHoverRenderController);let SheetsDrawingRenderController=class extends Disposable{constructor(e,t,n,r){super(),this._context=e,this._sheetDrawingService=t,this._drawingManagerService=n,this._sheetSkeletonService=r,this._init()}_init(){this._drawingInitializeListener()}_drawingInitializeListener(){this._sheetDrawingService.initializeNotification(this._context.unitId);const e=this._sheetDrawingService.getDrawingDataForUnit(this._context.unitId);for(const t in e){const n=e[t];for(const e in n.data){const t=n.data[e],{unitId:r,subUnitId:i}=t,o=this._sheetSkeletonService.getSkeletonParam(r,i);o&&t.sheetTransform&&(t.transform=drawingPositionToTransform(t.sheetTransform,o))}}this._drawingManagerService.registerDrawingData(this._context.unitId,this._sheetDrawingService.getDrawingDataForUnit(this._context.unitId)),this._drawingManagerService.initializeNotification(this._context.unitId)}};function resizeImageByCell(e,t,n){var r,i;if(3===(null==n||null===(r=n.p)||void 0===r||null===(r=r.body)||void 0===r?void 0:r.dataStream.length)&&1===(null===(i=n.p)||void 0===i||null===(i=i.drawingsOrder)||void 0===i?void 0:i.length)){const r=n.p.drawings[n.p.drawingsOrder[0]],i=getDrawingSizeByCell(e,{unitId:t.unitId,subUnitId:t.subUnitId,row:t.row,col:t.col},r.docTransform.size.width,r.docTransform.size.height,r.docTransform.angle);if(i)return r.transform.width=i.width,r.transform.height=i.height,r.docTransform.size.width=i.width,r.docTransform.size.height=i.height,r.transform.left=0,r.transform.top=0,r.docTransform.positionH.posOffset=0,r.docTransform.positionV.posOffset=0,n.p.documentStyle.pageSize.width=1/0,n.p.documentStyle.pageSize.height=1/0,!0}return!1}SheetsDrawingRenderController=__decorate([__decorateParam(1,ISheetDrawingService),__decorateParam(2,IDrawingManagerService),__decorateParam(3,Inject(SheetSkeletonService))],SheetsDrawingRenderController);let SheetCellImageController=class extends Disposable{constructor(e,t,n,r,i,o){super(),this._commandService=e,this._sheetInterceptorService=t,this._injector=n,this._drawingManagerService=r,this._docDrawingController=i,this._editorBridgeService=o,this._handleInitEditor(),this._initCellContentInterceptor()}_handleInitEditor(){this.disposeWithMe(this._editorBridgeService.visible$.subscribe(e=>{e.visible?e.visible&&(this._drawingManagerService.removeDrawingDataForUnit(DOCS_NORMAL_EDITOR_UNIT_ID_KEY),this._docDrawingController.loadDrawingDataForUnit(DOCS_NORMAL_EDITOR_UNIT_ID_KEY),this._drawingManagerService.initializeNotification(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)):this._drawingManagerService.removeDrawingDataForUnit(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)})),this.disposeWithMe(this._commandService.onCommandExecuted(e=>{e.id===ReplaceSnapshotCommand.id&&e.params.unitId===DOCS_ZEN_EDITOR_UNIT_ID_KEY&&(this._drawingManagerService.removeDrawingDataForUnit(DOCS_ZEN_EDITOR_UNIT_ID_KEY),this._docDrawingController.loadDrawingDataForUnit(DOCS_ZEN_EDITOR_UNIT_ID_KEY),this._drawingManagerService.initializeNotification(DOCS_ZEN_EDITOR_UNIT_ID_KEY))}))}_initCellContentInterceptor(){this.disposeWithMe(this._sheetInterceptorService.intercept(INTERCEPTOR_POINT.CELL_CONTENT,{effect:InterceptorEffectEnum.Style,priority:InterceptCellContentPriority.CELL_IMAGE,handler:(e,t,n)=>{var r;return(null==e?void 0:e.p)&&(null===(r=e.p.drawingsOrder)||void 0===r?void 0:r.length)&&(e===t.rawData&&(e={...t.rawData}),e.interceptorStyle||(e.interceptorStyle={}),e.interceptorStyle.tr={a:0},resizeImageByCell(this._injector,{unitId:t.unitId,subUnitId:t.subUnitId,row:t.row,col:t.col},e)),n(e)}}))}};SheetCellImageController=__decorate([__decorateParam(0,ICommandService),__decorateParam(1,Inject(SheetInterceptorService)),__decorateParam(2,Inject(Injector)),__decorateParam(3,IDrawingManagerService),__decorateParam(4,Inject(DocDrawingController)),__decorateParam(5,Inject(IEditorBridgeService))],SheetCellImageController);let SheetCellImageAutofillController=class extends Disposable{constructor(e,t){super(),this._autoFillService=e,this._injector=t,this._initAutoFillHooks()}_initAutoFillHooks(){this.disposeWithMe(this._autoFillService.addHook({id:"sheet-cell-image-autofill",onBeforeSubmit:(e,t,n,r)=>{new ObjectMatrix(r).forValue((t,n,r)=>{resizeImageByCell(this._injector,{unitId:e.unitId,subUnitId:e.subUnitId,row:t,col:n},r)})}}))}};SheetCellImageAutofillController=__decorate([__decorateParam(0,Inject(IAutoFillService)),__decorateParam(1,Inject(Injector))],SheetCellImageAutofillController);const DISABLE_UNITS=[DOCS_NORMAL_EDITOR_UNIT_ID_KEY,DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,DOCS_ZEN_EDITOR_UNIT_ID_KEY];let SheetCellImageCopyPasteController=class extends Disposable{constructor(e,t,n,r,i){super(),this._commandService=e,this._univerInstanceService=t,this._dialogService=n,this._renderManagerService=r,this._localeService=i,this._initDocImageCopyPasteHooks()}_setCellImage(e){var t;const n=createDocumentModelWithStyle("",{}),r=null===(t=getCurrentTypeOfRenderer(UniverInstanceType.UNIVER_SHEET,this._univerInstanceService,this._renderManagerService))||void 0===t?void 0:t.with(EditingRenderController),i=BuildTextUtils.drawing.add({documentDataModel:n,drawings:[e],selection:{collapsed:!0,startOffset:0,endOffset:0}});i&&(n.apply(i),r&&r.submitCellData(n))}_initDocImageCopyPasteHooks(){this.disposeWithMe(this._commandService.beforeCommandExecuted(e=>{if(e.id===InnerPasteCommand.id){var t;const{doc:r}=e.params,i=this._univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_DOC);if(null==i||!Object.keys(null!==(t=r.drawings)&&void 0!==t?t:{}).length)return;const o=i.getUnitId();if(DISABLE_UNITS.includes(o)&&o!==DOCS_ZEN_EDITOR_UNIT_ID_KEY){var n;const e=()=>{this._dialogService.close("sheet-cell-image-copy-paste"),this._commandService.syncExecuteCommand(SetCellEditVisibleOperation.id,{visible:!1})};"\r\n"===(null===(n=i.getBody())||void 0===n?void 0:n.dataStream)?(this._commandService.syncExecuteCommand(SetCellEditVisibleOperation.id,{visible:!1}),this._setCellImage(Object.values(r.drawings)[0])):this._dialogService.open({id:"sheet-cell-image-copy-paste",title:{label:this._localeService.t("sheets-drawing-ui.cell-image.pasteTitle")},children:{label:this._localeService.t("sheets-drawing-ui.cell-image.pasteContent")},width:320,destroyOnClose:!0,onClose:e,showOk:!0,showCancel:!0,onOk:()=>{e(),this._setCellImage(Object.values(r.drawings)[0])},onCancel:e})}}}))}};SheetCellImageCopyPasteController=__decorate([__decorateParam(0,ICommandService),__decorateParam(1,IUniverInstanceService),__decorateParam(2,IDialogService),__decorateParam(3,IRenderManagerService),__decorateParam(4,Inject(LocaleService))],SheetCellImageCopyPasteController);const IMAGE_PNG_MIME_TYPE="image/png";function base64ToBlob(e){const t=e.split(","),n=atob(t[1]),r=n.length,i=new Uint8Array(r);for(let e=0;e<r;e++)i[e]=n.charCodeAt(e);return new Blob([i],{type:"image/png"})}function copyBase64ToClipboard(e){const t=new ClipboardItem({[IMAGE_PNG_MIME_TYPE]:base64ToBlob(e)});navigator.clipboard.write([t]).catch(e=>{console.error("Could not copy image using clipboard API: ",e)})}function focusDocument(){const e=document.activeElement,t=function(){const e=document.createElement("input");return e.style.position="absolute",e.style.height="1px",e.style.width="1px",e.style.opacity="0",e}();return document.body.appendChild(t),t.focus(),()=>{t.blur(),document.body.removeChild(t),e instanceof HTMLElement&&e.focus()}}const specialPastes=[PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_COL_WIDTH,PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_VALUE,PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_FORMAT,PREDEFINED_HOOK_NAME_PASTE.SPECIAL_PASTE_FORMULA];let SheetsDrawingCopyPasteController=class extends Disposable{constructor(e,t,n,r,i,o){super(),this._sheetClipboardService=e,this._renderManagerService=t,this._sheetSkeletonService=n,this._drawingService=r,this._clipboardInterfaceService=i,this._commandService=o,_defineProperty(this,"_copyInfo",void 0),this._initCopyPaste()}get _focusedDrawings(){return this._drawingService.getFocusDrawings()}_initCopyPaste(){this._sheetClipboardService.addClipboardHook({id:"SHEET_IMAGE_UI_PLUGIN",onBeforeCopy:(e,t,n,r)=>{this._copyInfo=null;const i=this._focusedDrawings;if(i.length>0){const[t]=i;if(t.drawingType!==DrawingTypeEnum.DRAWING_IMAGE)return;if(r===COPY_TYPE.CUT){const n={unitId:e,drawings:[t]};this._commandService.executeCommand(RemoveSheetDrawingCommand.id,n)}setTimeout(()=>{const e=focusDocument();t.drawingType===DrawingTypeEnum.DRAWING_IMAGE&&t.imageSourceType===ImageSourceType$1.BASE64?copyBase64ToClipboard(t.source):this._clipboardInterfaceService.writeText(""),e()},200);const n={unitId:t.unitId,subUnitId:t.subUnitId,drawings:[t]};this._copyInfo=n}else{const r=this._createDrawingsCopyInfoByRange(e,t,n);this._copyInfo=r}},onPasteCells:(e,t,n,r)=>{if(!this._copyInfo)return{redos:[],undos:[]};const{copyType:i=COPY_TYPE.COPY,pasteType:o}=r,{range:a,unitId:s,subUnitId:d}=e||{},{range:c,unitId:l,subUnitId:u}=t;return this._copyInfo.copyRange?this._generateRangeDrawingsPasteMutations({unitId:l,subUnitId:u,pasteRange:c,pasteType:o},{unitId:s,subUnitId:d,copyType:i,copyRange:a}):this._generateSingleDrawingPasteMutations({pasteTo:t,pasteType:o},COPY_TYPE.COPY)},onPastePlainText:(e,t)=>({undos:[],redos:[]}),onPasteUnrecognized:e=>this._copyInfo?this._generateSingleDrawingPasteMutations({pasteTo:e,pasteType:PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE},COPY_TYPE.COPY):{undos:[],redos:[]},onPasteFiles:(e,t)=>{if(this._copyInfo)return this._generateSingleDrawingPasteMutations({pasteTo:e,pasteType:PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE},COPY_TYPE.COPY);{const e=t.filter(e=>e.type.includes("image"));if(e.length)return{undos:[],redos:[{id:InsertFloatImageCommand.id,params:{files:e}}]}}return{undos:[],redos:[]}}})}_createDrawingsCopyInfoByRange(e,t,n){const r=this._sheetSkeletonService.getSkeleton(e,t);if(!r)return;const i=attachRangeWithCoord(r,n);if(!i)return;const{startX:o,endX:a,startY:s,endY:d}=i,c=this._drawingService.getDrawingData(e,t),l=this._focusedDrawings.slice();return Object.keys(c).forEach(e=>{const t=c[e];if(t.drawingType!==DrawingTypeEnum.DRAWING_IMAGE)return;const{transform:n}=t;if(t.anchorType!==SheetDrawingAnchorType.Both)return;if(!n)return;const{left:r=0,top:i=0,width:u=0,height:g=0}=n,{drawingStartX:h,drawingEndX:m,drawingStartY:p,drawingEndY:S}={drawingStartX:r,drawingEndX:r+u,drawingStartY:i,drawingEndY:i+g};o<=h&&m<=a&&s<=p&&S<=d&&l.push(t)}),l.length?{copyRange:n,drawings:l,unitId:e,subUnitId:t}:void 0}_generateSingleDrawingPasteMutations(e,t){const{pasteType:n,pasteTo:r}=e;if(specialPastes.includes(n))return{redos:[],undos:[]};const{unitId:i,subUnitId:o,range:a}=r,s=this._sheetSkeletonService.getSkeleton(i,o);if(!s)return{redos:[],undos:[]};const{drawings:d}=this._copyInfo,c=discreteRangeToRange(a);return this._generateMutations(d,{unitId:i,subUnitId:o,isCut:t===COPY_TYPE.CUT,getTransform:(e,t)=>{var n,r;const i=attachRangeWithCoord(s,{startRow:c.startRow,endRow:c.endRow,startColumn:c.startColumn,endColumn:c.endColumn}),o={...e,left:null==i?void 0:i.startX,top:null==i?void 0:i.startY};return{transform:o,sheetTransform:null!==(n=transformToDrawingPosition(o,s))&&void 0!==n?n:t,axisAlignSheetTransform:null!==(r=transformToAxisAlignPosition(o,s))&&void 0!==r?r:t}}})}_generateMutations(e,t){const{unitId:n,subUnitId:r,getTransform:i,isCut:o}=t,a=[],s=[],{_drawingService:d}=this;return e.forEach(e=>{const{transform:t,sheetTransform:c}=e;if(!t)return;const l=i(t,c),u={...e,unitId:n,subUnitId:r,drawingId:o?e.drawingId:generateRandomId(),transform:l.transform,sheetTransform:l.sheetTransform,axisAlignSheetTransform:l.axisAlignSheetTransform};if(o){const{undo:e,redo:t,objects:i}=d.getBatchUpdateOp([u]);a.push({id:SetDrawingApplyMutation.id,params:{unitId:n,subUnitId:r,type:DrawingApplyType.UPDATE,op:t,objects:i}}),s.push({id:SetDrawingApplyMutation.id,params:{unitId:n,subUnitId:r,type:DrawingApplyType.UPDATE,op:e,objects:i}})}else{const{undo:e,redo:t,objects:i}=d.getBatchAddOp([u]);a.push({id:SetDrawingApplyMutation.id,params:{op:t,unitId:n,subUnitId:r,objects:i,type:DrawingApplyType.INSERT}}),s.push({id:SetDrawingApplyMutation.id,params:{op:e,unitId:n,subUnitId:r,objects:i,type:DrawingApplyType.REMOVE}})}}),{redos:a,undos:s}}_generateRangeDrawingsPasteMutations(e,t){if(!this._copyInfo)return{redos:[],undos:[]};const{unitId:n,subUnitId:r,pasteRange:i,pasteType:o}=e,{unitId:a,subUnitId:s,copyRange:d,copyType:c}=t;if(specialPastes.includes(o))return{redos:[],undos:[]};const l=this._sheetSkeletonService.getSkeleton(n,r);if(!l)return{redos:[],undos:[]};const{drawings:u}=this._copyInfo;if(!d)return this._generateSingleDrawingPasteMutations({pasteTo:{unitId:n,subUnitId:r,range:discreteRangeToRange(i)},pasteType:o},c);const g=this._sheetSkeletonService.getSkeleton(a,s);if(!g)return{redos:[],undos:[]};const{ranges:[h,m],mapFunc:p}=virtualizeDiscreteRanges([d,i]),{row:S,col:I}=p(h.startRow,h.startColumn),{row:w,col:f}=p(m.startRow,m.startColumn),_=attachRangeWithCoord(g,{startRow:S,endRow:S,startColumn:I,endColumn:I}),v=attachRangeWithCoord(l,{startRow:w,endRow:w,startColumn:f,endColumn:f});if(!_||!v)return{redos:[],undos:[]};const D=v.startX-_.startX,T=v.startY-_.startY,C=w-S,y=f-I;return this._generateMutations(u,{unitId:n,subUnitId:r,getTransform:(e,t)=>{var n,r,i;const o={...e,left:(null!==(n=null==e?void 0:e.left)&&void 0!==n?n:0)+D,top:(null!==(r=null==e?void 0:e.top)&&void 0!==r?r:0)+T};return{transform:o,sheetTransform:{...t,to:{...t.to,row:t.to.row+C,column:t.to.column+y},from:{...t.from,row:t.from.row+C,column:t.from.column+y}},axisAlignSheetTransform:null!==(i=transformToAxisAlignPosition(o,l))&&void 0!==i?i:t}},isCut:c===COPY_TYPE.CUT})}};SheetsDrawingCopyPasteController=__decorate([__decorateParam(0,ISheetClipboardService),__decorateParam(1,IRenderManagerService),__decorateParam(2,Inject(SheetSkeletonService)),__decorateParam(3,IDrawingManagerService),__decorateParam(4,IClipboardInterfaceService),__decorateParam(5,ICommandService)],SheetsDrawingCopyPasteController);const drawingObjectTypes=[ObjectType.IMAGE,ObjectType.SHAPE,ObjectType.CHART,ObjectType.DRAWING_DOM];let SheetDrawingPermissionController=class extends Disposable{constructor(e,t,n,r,i,o,a,s){super(),this._commandService=e,this._localeService=t,this._renderManagerService=n,this._permissionService=r,this._univerInstanceService=i,this._userManagerService=o,this._sheetPermissionCheckController=a,this._sheetDrawingService=s,this._initDrawingVisible(),this._initDrawingEditable(),this._initViewPermissionChange(),this._initEditPermissionChange(),this._initCommandPermissionCheck()}_initDrawingVisible(){const e=this._univerInstanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_SHEET),t=this._userManagerService.currentUser$,n=combineLatest([e,t]);this.disposeWithMe(n.pipe(switchMap(([e,t])=>e?e.activeSheet$.pipe(tap(t=>{if(!t)return void this._sheetDrawingService.setDrawingVisible(!1);const n=e.getUnitId(),r=t.getSheetId();this._permissionService.composePermission([new WorkbookViewPermission(n).id,new WorksheetViewPermission(n,r).id]).every(e=>e.value)?this._sheetDrawingService.setDrawingVisible(!0):this._handleDrawingVisibilityFalse(e,t)})):(this._sheetDrawingService.setDrawingVisible(!1),EMPTY))).subscribe())}_handleDrawingVisibilityFalse(e,t){this._sheetDrawingService.setDrawingVisible(!1);const n=e.getUnitId(),r=t.getSheetId(),i=this._sheetDrawingService.getDrawingData(n,r),o=Object.values(i),a=this._renderManagerService.getRenderById(n),s=null==a?void 0:a.scene;s&&s.getAllObjectsByOrder().forEach(e=>{drawingObjectTypes.includes(e.objectType)&&o.some(t=>e.oKey.includes(t.drawingId))&&s.removeObject(e)})}_initDrawingEditable(){const e=this._univerInstanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_SHEET),t=this._userManagerService.currentUser$,n=combineLatest([e,t]);this.disposeWithMe(n.pipe(switchMap(([e,t])=>e?e.activeSheet$.pipe(tap(t=>{if(!t)return void this._sheetDrawingService.setDrawingEditable(!1);const n=e.getUnitId(),r=t.getSheetId();this._permissionService.composePermission([new WorkbookEditablePermission(n).id,new WorksheetEditPermission(n,r).id]).every(e=>e.value)?this._sheetDrawingService.setDrawingEditable(!0):this._handleDrawingEditableFalse(e,t)})):(this._sheetDrawingService.setDrawingEditable(!1),EMPTY))).subscribe())}_handleDrawingEditableFalse(e,t){this._sheetDrawingService.setDrawingEditable(!1);const n=e.getUnitId(),r=t.getSheetId(),i=this._sheetDrawingService.getDrawingData(n,r),o=Object.values(i),a=this._renderManagerService.getRenderById(n),s=null==a?void 0:a.scene;s&&s.getAllObjectsByOrder().forEach(e=>{drawingObjectTypes.includes(e.objectType)&&o.some(t=>e.oKey.includes(t.drawingId))&&s.detachTransformerFrom(e)})}_initViewPermissionChange(){const e=this._univerInstanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_SHEET),t=this._userManagerService.currentUser$;this.disposeWithMe(combineLatest([e,t]).pipe(switchMap(([e,t])=>e?e.activeSheet$.pipe(switchMap(t=>{if(!t)return EMPTY;const n=e.getUnitId(),r=t.getSheetId(),i=this._renderManagerService.getRenderById(n),o=null==i?void 0:i.scene;if(!o)return EMPTY;const a=o.getTransformerByCreate();return this._permissionService.composePermission$([new WorkbookViewPermission(n).id,new WorksheetViewPermission(n,r).id]).pipe(map(e=>e.every(e=>e.value)),distinctUntilChanged()).pipe(map(e=>({permission:e,scene:o,transformer:a,unitId:n,subUnitId:r})))})):EMPTY)).subscribe({next:({permission:e,scene:t,transformer:n,unitId:r,subUnitId:i})=>{this._sheetDrawingService.setDrawingVisible(e);const o=t.getAllObjectsByOrder(),a=this._sheetDrawingService.getDrawingData(r,i),s=Object.values(a);e?this._sheetDrawingService.addNotification(s):(o.forEach(e=>{drawingObjectTypes.includes(e.objectType)&&s.some(t=>e.oKey.includes(t.drawingId))&&t.removeObject(e)}),n.clearSelectedObjects())},complete:()=>{this._sheetDrawingService.setDrawingVisible(!0);const e=this._univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_SHEET),t=null==e?void 0:e.getActiveSheet(),n=null==e?void 0:e.getUnitId(),r=null==t?void 0:t.getSheetId();if(!n||!r)return;const i=this._sheetDrawingService.getDrawingData(n,r),o=Object.values(i);this._sheetDrawingService.addNotification(o)}}))}_initEditPermissionChange(){const e=this._univerInstanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_SHEET),t=this._userManagerService.currentUser$;this.disposeWithMe(combineLatest([e,t]).pipe(switchMap(([e,t])=>e?e.activeSheet$.pipe(switchMap(t=>{if(!t)return EMPTY;const n=e.getUnitId(),r=t.getSheetId(),i=this._renderManagerService.getRenderById(n),o=null==i?void 0:i.scene;if(!o)return EMPTY;const a=o.getTransformerByCreate();return this._permissionService.composePermission$([new WorkbookEditablePermission(n).id,new WorksheetEditPermission(n,r).id]).pipe(map(e=>e.every(e=>e.value)),distinctUntilChanged()).pipe(map(e=>({permission:e,scene:o,transformer:a,unitId:n,subUnitId:r})))})):EMPTY)).subscribe({next:({permission:e,scene:t,transformer:n,unitId:r,subUnitId:i})=>{this._sheetDrawingService.setDrawingEditable(e);const o=t.getAllObjectsByOrder(),a=this._sheetDrawingService.getDrawingData(r,i),s=Object.values(a);e?(o.forEach(e=>{drawingObjectTypes.includes(e.objectType)&&s.some(t=>e.oKey.includes(t.drawingId))&&t.attachTransformerTo(e)}),this._sheetDrawingService.addNotification(s)):(o.forEach(e=>{drawingObjectTypes.includes(e.objectType)&&s.some(t=>e.oKey.includes(t.drawingId))&&t.detachTransformerFrom(e)}),n.clearSelectedObjects())},complete:()=>{const e=this._univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_SHEET);if(!e)return;const t=e.getUnitId(),n=e.getActiveSheet();if(!n)return;const r=n.getSheetId(),i=this._renderManagerService.getRenderById(t),o=null==i?void 0:i.scene;if(!o)return;const a=this._sheetDrawingService.getDrawingData(t,r),s=Object.values(a);this._sheetDrawingService.setDrawingEditable(!0),o.getAllObjectsByOrder().forEach(e=>{drawingObjectTypes.includes(e.objectType)&&s.some(t=>e.oKey.includes(t.drawingId))&&o.detachTransformerFrom(e)})}}))}_initCommandPermissionCheck(){this.disposeWithMe(this._commandService.beforeCommandExecuted(e=>{let t,n;if(e.id===InsertSheetDrawingCommand.id||e.id===RemoveSheetDrawingCommand.id||e.id===SetSheetDrawingCommand.id){var r,i;const{drawings:o}=e.params;t=null==o||null===(r=o[0])||void 0===r?void 0:r.unitId,n=null==o||null===(i=o[0])||void 0===i?void 0:i.subUnitId}else if(e.id===SetDrawingArrangeCommand.id){const r=e.params;t=r.unitId,n=r.subUnitId}t&&n&&(this._sheetPermissionCheckController.permissionCheckWithoutRange({workbookTypes:[WorkbookEditablePermission],worksheetTypes:[WorksheetEditPermission]},t,n)||this._sheetPermissionCheckController.blockExecuteWithoutPermission(this._localeService.t("sheets-drawing-ui.permission.dialog.editErr")))}))}};SheetDrawingPermissionController=__decorate([__decorateParam(0,Inject(ICommandService)),__decorateParam(1,Inject(LocaleService)),__decorateParam(2,IRenderManagerService),__decorateParam(3,IPermissionService),__decorateParam(4,IUniverInstanceService),__decorateParam(5,Inject(UserManagerService)),__decorateParam(6,Inject(SheetPermissionCheckController)),__decorateParam(7,Inject(ISheetDrawingService))],SheetDrawingPermissionController);const SHEET_FLOAT_DOM_PREFIX="univer-sheet-float-dom-";function transformBound2DOMBound(e,t,n,r,i,o=!1){const{scaleX:a,scaleY:s}=t.getAncestorScale(),d=t.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN),{startColumn:c,startRow:l,xSplit:u,ySplit:g}=r.getFreeze(),h={left:!0,top:!0};if(!d)return{...e,absolute:h};const{left:m,right:p,top:S,bottom:I}=e;let{top:w,left:f,viewportScrollX:_,viewportScrollY:v}=d;const{boundsOfViewArea:D,scrollDirectionResponse:T}=i||{},{rowHeaderWidth:C,columnHeaderHeight:y}=n,b={top:o?0:y,left:o?0:C};D&&(Tools.isDefine(b.top)&&(b.top=D.top),Tools.isDefine(b.left)&&(b.left=D.left)),"HORIZONTAL"===T&&(v=0),"VERTICAL"===T&&(_=0);let E=0,P=0;const M=n.rowStartY(l-g)+y,R=n.colStartX(c-u)+C,A=n.rowStartY(l)+y,U=n.colStartX(c)+C;if(0===u)h.left=!1,E=(m-_)*a,P=(p-_)*a;else{const e=m-(R-C);p<U?(E=e*a,P=(p-(R-C))*a):m<=U&&p>=U?(E=e*a,P=Math.max(f,(p-_)*a)):m>U&&(h.left=!1,E=Math.max((m-_)*a,f),P=Math.max((p-_)*a,f))}let O=0,x=0;if(0===g)h.top=!1,O=(S-v)*s,x=(I-v)*s;else{const e=S-(M-y);I<A?(O=e*s,x=(I-(M-y))*s):S<=A&&I>=A?(O=e*s,x=Math.max(w,(I-v)*s)):S>A&&(h.top=!1,O=Math.max((S-v)*s,w),x=Math.max((I-v)*s,w))}return E=Math.max(E,b.left),O=Math.max(O,b.top),P=Math.max(P,b.left),x=Math.max(x,b.top),{left:E,right:P,top:O,bottom:x,absolute:h}}const calcSheetFloatDomPosition=(e,t,n,r,i)=>{const{left:o,top:a,width:s,height:d,angle:c}=e,l=transformBound2DOMBound({left:o,right:o+s,top:a,bottom:a+d},t,n,r,i),{scaleX:u,scaleY:g}=t.getAncestorScale();return{startX:l.left,endX:l.right,startY:l.top,endY:l.bottom,rotate:c,width:s*u,height:d*g,absolute:l.absolute}};let SheetCanvasFloatDomManagerService=class extends Disposable{constructor(e,t,n,r,i,o,a){super(),this._renderManagerService=e,this._univerInstanceService=t,this._commandService=n,this._drawingManagerService=r,this._canvasFloatDomService=i,this._sheetDrawingService=o,this._lifecycleService=a,_defineProperty(this,"_domLayerInfoMap",new Map),_defineProperty(this,"_transformChange$",new Subject),_defineProperty(this,"transformChange$",this._transformChange$.asObservable()),_defineProperty(this,"_add$",new Subject),_defineProperty(this,"add$",this._add$.asObservable()),_defineProperty(this,"_remove$",new Subject),_defineProperty(this,"remove$",this._remove$.asObservable()),this._drawingAddListener(),this._featureUpdateListener(),this._deleteListener(),this._bindScrollEvent()}_bindScrollEvent(){this._lifecycleService.lifecycle$.pipe(filter(e=>e===LifecycleStages.Rendered),take(1)).subscribe(()=>{this._scrollUpdateListener()})}getFloatDomInfo(e){return this._domLayerInfoMap.get(e)}getFloatDomsBySubUnitId(e,t){return Array.from(this._domLayerInfoMap.values()).filter(n=>n.subUnitId===t&&n.unitId===e)}_getSceneAndTransformerByDrawingSearch(e){if(null==e)return;const t=this._renderManagerService.getRenderById(e),n=null==t?void 0:t.scene;return null==t||null==n?null:{scene:n,transformer:n.getTransformerByCreate(),renderUnit:t,canvas:t.engine.getCanvasElement()}}_drawingAddListener(){this.disposeWithMe(this._drawingManagerService.add$.subscribe(e=>{e.forEach(e=>{var t;const{unitId:n,subUnitId:r,drawingId:i}=e,o=getSheetCommandTarget(this._univerInstanceService,{unitId:n,subUnitId:r}),a=this._drawingManagerService.getDrawingByParam(e),s=this._univerInstanceService.getUnit(n,UniverInstanceType.UNIVER_SHEET);if(!s)return;const d=s.getActiveSheet().getSheetId();if(!a||!o)return;const c=null===(t=this._renderManagerService.getRenderById(n))||void 0===t?void 0:t.with(SheetSkeletonManagerService).getSkeletonParam(r);if(!c)return;const{transform:l,drawingType:u,data:g,hidden:h}=a;if(u!==DrawingTypeEnum.DRAWING_DOM&&u!==DrawingTypeEnum.DRAWING_CHART)return;const m=this._getSceneAndTransformerByDrawingSearch(n);if(null==m)return;if(h)return;const{scene:p,canvas:S}=m;if(null==l)return!0;if(d!==r)return;const{left:I,top:w,width:f,height:_,angle:v,flipX:D,flipY:T,skewX:C,skewY:y}=l,b=getDrawingShapeKeyByDrawingSearch({unitId:n,subUnitId:r,drawingId:i}),E=p.getObject(b);if(null!=E)return void E.transformByState({left:I,top:w,width:f,height:_,angle:v,flipX:D,flipY:T,skewX:C,skewY:y});const P={left:I,top:w,width:f,height:_,zIndex:this._drawingManagerService.getDrawingOrder(n,r).length-1},M=u===DrawingTypeEnum.DRAWING_CHART;P.rotateEnabled=!1,M&&(P.fill=g?g.backgroundColor:"white",g&&g.border&&(P.stroke=g.border),P.paintFirst="stroke",P.strokeWidth=1,P.borderEnabled=!1,P.radius=8);const R=new Rect(b,P);M?R.setObjectType(ObjectType.CHART):u===DrawingTypeEnum.DRAWING_DOM&&R.setObjectType(ObjectType.DRAWING_DOM),p.addObject(R,DRAWING_OBJECT_LAYER_INDEX),!1!==a.allowTransform&&p.attachTransformerTo(R);const A=new DisposableCollection,U=new BehaviorSubject(calcSheetFloatDomPosition(R,m.renderUnit.scene,c.skeleton,o.worksheet)),O=`${SHEET_FLOAT_DOM_PREFIX}${generateRandomId(6)}`,x={dispose:A,rect:R,position$:U,unitId:n,subUnitId:r,id:i,domId:O};this._canvasFloatDomService.addFloatDom({position$:U,id:i,domId:O,componentKey:a.componentKey,onPointerDown:e=>{S.dispatchEvent(new PointerEvent(e.type,e))},onPointerMove:e=>{S.dispatchEvent(new PointerEvent(e.type,e))},onPointerUp:e=>{S.dispatchEvent(new PointerEvent(e.type,e))},onWheel:e=>{S.dispatchEvent(new WheelEvent(e.type,e))},data:g,unitId:n});const N=R.onTransformChange$.subscribeEvent(()=>{const e=calcSheetFloatDomPosition(R,m.renderUnit.scene,c.skeleton,o.worksheet);U.next(e)});A.add(()=>{this._canvasFloatDomService.removeFloatDom(i)}),N&&A.add(N),this._domLayerInfoMap.set(i,x)})})),this.disposeWithMe(this._drawingManagerService.remove$.subscribe(e=>{e.forEach(e=>{const{unitId:t,subUnitId:n,drawingId:r}=e,i=getDrawingShapeKeyByDrawingSearch({unitId:t,subUnitId:n,drawingId:r}),o=this._getSceneAndTransformerByDrawingSearch(t);if(null==o)return;const{transformer:a,scene:s}=o,d=s.getObject(i);var c;(null==d?void 0:d.oKey)&&(a.clearControlByIds([null==d?void 0:d.oKey]),null===(c=s.getTransformer())||void 0===c||c.clearSelectedObjects())})}))}_scrollUpdateListener(){const e=(e,t)=>{var n;const r=this._getSceneAndTransformerByDrawingSearch(e),i=Array.from(this._domLayerInfoMap.keys()).map(e=>({id:e,...this._domLayerInfoMap.get(e)})).filter(n=>n.subUnitId===t&&n.unitId===e).map(e=>e.id),o=getSheetCommandTarget(this._univerInstanceService,{unitId:e,subUnitId:t}),a=null===(n=this._renderManagerService.getRenderById(e))||void 0===n?void 0:n.with(SheetSkeletonManagerService).getSkeletonParam(t);r&&o&&a&&i.forEach(e=>{const t=this._domLayerInfoMap.get(e);if(t){const e=calcSheetFloatDomPosition(t.rect,r.renderUnit.scene,a.skeleton,o.worksheet,t);t.position$.next(e)}})};this.disposeWithMe(this._univerInstanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_SHEET).pipe(switchMap(e=>e?e.activeSheet$:of(null)),map(e=>{if(!e)return null;const t=e.getUnitId(),n=this._renderManagerService.getRenderById(t);return n?{render:n,unitId:t,subUnitId:e.getSheetId()}:null}),switchMap(e=>e?fromEventSubject(e.render.scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN).onScrollAfter$).pipe(map(()=>({unitId:e.unitId,subUnitId:e.subUnitId}))):of(null))).subscribe(t=>{if(!t)return;const{unitId:n,subUnitId:r}=t;e(n,r)})),this.disposeWithMe(this._commandService.onCommandExecuted(t=>{if(t.id===SetZoomRatioOperation.id){const{unitId:n}=t.params;Array.from(this._domLayerInfoMap.values()).filter(e=>e.unitId===n).map(e=>e.subUnitId).forEach(t=>{e(n,t)})}else if(t.id===SetFrozenMutation.id){const{unitId:n,subUnitId:r}=t.params;e(n,r)}else if(t.id===SetSelectionsOperation.id){const{unitId:n,subUnitId:r}=t.params;e(n,r)}}))}updateFloatDomProps(e,t,n,r){const i=this._domLayerInfoMap.get(n),o=this._getSceneAndTransformerByDrawingSearch(e);if(i&&o){const{scene:i}=o,a=getDrawingShapeKeyByDrawingSearch({unitId:e,subUnitId:t,drawingId:n}),s=i.getObject(a);s&&s instanceof Rect&&s.setProps(r)}}_getPosition(e,t){var n;const{startX:r,endX:i,startY:o,endY:a}=e,s=null===(n=this._renderManagerService.getRenderById(t))||void 0===n?void 0:n.with(ISheetSelectionRenderService);if(null==s)return;const d=s.getCellWithCoordByOffset(r,o);if(null==d)return;const c={column:d.actualColumn,columnOffset:r-d.startX,row:d.actualRow,rowOffset:o-d.startY},l=s.getCellWithCoordByOffset(i,a);return null!=l?{from:c,to:{column:l.actualColumn,columnOffset:i-l.startX,row:l.actualRow,rowOffset:a-l.startY}}:void 0}_featureUpdateListener(){this.disposeWithMe(this._drawingManagerService.update$.subscribe(e=>{e.forEach(e=>{const t=this._drawingManagerService.getDrawingByParam(e);if(!t)return;if(t.drawingType!==DrawingTypeEnum.DRAWING_DOM&&t.drawingType!==DrawingTypeEnum.DRAWING_CHART)return;const n={...t.transform};this._transformChange$.next({id:e.drawingId,value:n}),this._canvasFloatDomService.updateFloatDom(e.drawingId,{...t});const r=this._getSceneAndTransformerByDrawingSearch(e.unitId);if(r&&t.drawingType!==DrawingTypeEnum.DRAWING_CHART){const{scene:n}=r,i=this._domLayerInfoMap.get(e.drawingId);(null==i?void 0:i.rect)&&(!1===t.allowTransform?n.detachTransformerFrom(i.rect):n.attachTransformerTo(i.rect))}})}))}_deleteListener(){this.disposeWithMe(this._drawingManagerService.remove$.subscribe(e=>{e.forEach(e=>{this._removeDom(e.drawingId)})}))}addFloatDomToPosition(e,t){const n=getSheetCommandTarget(this._univerInstanceService,{unitId:e.unitId,subUnitId:e.subUnitId});if(!n)throw new Error("cannot find current target!");const{unitId:r,subUnitId:i}=n,{initPosition:o,componentKey:a,data:s,allowTransform:d=!0}=e,c=null!=t?t:generateRandomId(),l=this._getPosition(o,r);if(null==l)return;const u={unitId:r,subUnitId:i,drawingId:c,drawingType:e.type||DrawingTypeEnum.DRAWING_DOM,componentKey:a,sheetTransform:l,transform:{left:o.startX,top:o.startY,width:o.endX-o.startX,height:o.endY-o.startY},axisAlignSheetTransform:l,data:s,allowTransform:d};return this._commandService.executeCommand(InsertSheetDrawingCommand.id,{unitId:r,drawings:[u]}),this._add$.next({unitId:r,subUnitId:i,id:c}),{id:c,dispose:()=>{this._removeDom(c,!0)}}}_removeDom(e,t=!1){const n=this._domLayerInfoMap.get(e);if(!n)return;const{unitId:r,subUnitId:i}=n;this._domLayerInfoMap.delete(e),n.dispose.dispose();const o=this._getSceneAndTransformerByDrawingSearch(r);if(o&&o.scene.removeObject(n.rect),t){const t=this._drawingManagerService.getDrawingByParam({unitId:r,subUnitId:i,drawingId:e});if(!t)return;const{redo:n,objects:o}=this._sheetDrawingService.getBatchRemoveOp([t]);this._commandService.syncExecuteCommand(SetDrawingApplyMutation.id,{unitId:r,subUnitId:i,op:n,objects:o,type:DrawingApplyType.REMOVE})}}removeFloatDom(e,t=!0){this._removeDom(e,t)}addFloatDomToRange(e,t,n,r){var i;const o=getSheetCommandTarget(this._univerInstanceService,{unitId:t.unitId,subUnitId:t.subUnitId});if(!o)throw new Error("cannot find current target!");const{unitId:a,subUnitId:s}=o,d=this._getSceneAndTransformerByDrawingSearch(a);if(!d)return;const c=this._renderManagerService.getRenderById(a);if(!c)return;const l=null===(i=this._renderManagerService.getRenderById(a))||void 0===i?void 0:i.with(SheetSkeletonManagerService).getSkeletonParam(s);if(!l)return;const{componentKey:u,data:g,allowTransform:h=!0}=t,m=null!=r?r:generateRandomId(),{position:p,position$:S}=this._createRangePositionObserver(e,c,l.skeleton),I=this._getPosition(p,a);if(null==I)return;const{scaleX:w}=d.scene.getAncestorScale(),f=calcDomPositionByAnchor(p,n,w),_={unitId:a,subUnitId:s,drawingId:m,drawingType:t.type||DrawingTypeEnum.DRAWING_DOM,componentKey:u,sheetTransform:I,axisAlignSheetTransform:I,transform:{left:f.startX,top:f.startY,width:f.width,height:f.height},data:g,allowTransform:h};{var v,D;const{unitId:e,subUnitId:r,drawingId:i}=_,o=getSheetCommandTarget(this._univerInstanceService,{unitId:e,subUnitId:r}),a=_,s=this._univerInstanceService.getUnit(e,UniverInstanceType.UNIVER_SHEET);if(!s)return;const d=s.getActiveSheet().getSheetId();if(!a||!o)return;const c=null===(v=this._renderManagerService.getRenderById(e))||void 0===v?void 0:v.with(SheetSkeletonManagerService);if(!c)return;const l=c.getSkeletonParam(r);if(!l)return;const{transform:u,drawingType:g,data:h}=a;if(g!==DrawingTypeEnum.DRAWING_DOM&&g!==DrawingTypeEnum.DRAWING_CHART)return;const I=this._getSceneAndTransformerByDrawingSearch(e);if(null==I)return;const{scene:w,canvas:f}=I;if(null==u)return;if(d!==r)return;const{left:T,top:C,width:y,height:b,angle:E,flipX:P,flipY:M,skewX:R,skewY:A}=u,U=getDrawingShapeKeyByDrawingSearch({unitId:e,subUnitId:r,drawingId:i}),O=w.getObject(U);if(null!=O)return void O.transformByState({left:T,top:C,width:y,height:b,angle:E,flipX:P,flipY:M,skewX:R,skewY:A});const x={left:T,top:C,width:y,height:b,zIndex:this._drawingManagerService.getDrawingOrder(e,r).length-1},N=g===DrawingTypeEnum.DRAWING_CHART;N&&(x.fill=h?h.backgroundColor:"white",x.rotateEnabled=!1,h&&h.border&&(x.stroke=h.border),x.paintFirst="stroke",x.strokeWidth=1,x.borderEnabled=!1,x.radius=8);const k=new Rect(U,x);N&&k.setObjectType(ObjectType.CHART),w.addObject(k,DRAWING_OBJECT_LAYER_INDEX),!1!==a.allowTransform&&w.attachTransformerTo(k);const j=new DisposableCollection,F=w.getMainViewport(),{rowHeaderWidth:B,columnHeaderHeight:W}=l.skeleton,L={dispose:j,rect:k,boundsOfViewArea:{top:W,left:B,bottom:F.bottom,right:F.right},domAnchor:n,unitId:e,subUnitId:r,id:i},G=new BehaviorSubject(calcSheetFloatDomPosition(k,I.renderUnit.scene,l.skeleton,o.worksheet,L));L.position$=G;let H={position$:G,id:i,componentKey:a.componentKey,onPointerDown:()=>{},onPointerMove:()=>{},onPointerUp:()=>{},onWheel:e=>{f.dispatchEvent(new WheelEvent(e.type,e))},data:h,unitId:e};t.eventPassThrough&&(H={...H,onPointerDown:e=>{f.dispatchEvent(new PointerEvent(e.type,e))},onPointerMove:e=>{f.dispatchEvent(new PointerEvent(e.type,e))},onPointerUp:e=>{f.dispatchEvent(new PointerEvent(e.type,e))}}),this._canvasFloatDomService.addFloatDom(H),this.disposeWithMe(S.subscribe(t=>{var a,s,d,c;const u=calcDomPositionByAnchor({rotate:0,startX:t.startX,startY:t.startY,endX:t.endX,endY:t.endY,width:null!==(a=n.width)&&void 0!==a?a:t.width,height:null!==(s=n.height)&&void 0!==s?s:t.height,absolute:{left:p.absolute.left,top:p.absolute.top}},n),g=calcSheetFloatDomPosition(new Rect(getDrawingShapeKeyByDrawingSearch({unitId:e,subUnitId:r,drawingId:i}),{left:u.startX,top:u.startY,width:null!==(d=n.width)&&void 0!==d?d:t.width,height:null!==(c=n.height)&&void 0!==c?c:t.height,zIndex:this._drawingManagerService.getDrawingOrder(e,r).length-1}),I.renderUnit.scene,l.skeleton,o.worksheet,L);G.next(g)}));const Y=null===(D=this._renderManagerService.getRenderById(e))||void 0===D?void 0:D.with(SheetSkeletonManagerService),V=null==Y?void 0:Y.currentSkeleton$.subscribe(e=>{e&&l.sheetId!==e.sheetId&&this._removeDom(m,!0)});V&&j.add(V);const $=k.onTransformChange$.subscribeEvent(()=>{const e=calcSheetFloatDomPosition(k,I.renderUnit.scene,l.skeleton,o.worksheet,L);G.next(e)});j.add(()=>{this._canvasFloatDomService.removeFloatDom(i)}),$&&j.add($),this._domLayerInfoMap.set(i,L)}return{id:m,dispose:()=>{this._removeDom(m,!0)}}}addFloatDomToColumnHeader(e,t,n,r){var i;const o=getSheetCommandTarget(this._univerInstanceService,{unitId:t.unitId,subUnitId:t.subUnitId});if(!o)throw new Error("cannot find current target!");const{unitId:a,subUnitId:s}=o;if(!this._getSceneAndTransformerByDrawingSearch(a))return;const d=this._renderManagerService.getRenderById(a);if(!d)return;const c=null===(i=this._renderManagerService.getRenderById(a))||void 0===i?void 0:i.with(SheetSkeletonManagerService).getSkeletonParam(s);if(!c)return;const{componentKey:l,data:u,allowTransform:g=!0}=t,h=null!=r?r:generateRandomId(),{position:m,position$:p}=this._createRangePositionObserver({startRow:0,endRow:0,startColumn:e,endColumn:e},d,c.skeleton),S=m;S.startY=0;const I=this._getPosition(m,a);if(null==I)return;const w={unitId:a,subUnitId:s,drawingId:h,drawingType:t.type||DrawingTypeEnum.DRAWING_DOM,componentKey:l,sheetTransform:I,axisAlignSheetTransform:I,transform:{left:S.startX,top:S.startY,width:S.width,height:S.height},data:u,allowTransform:g};{var f,_;const{unitId:e,subUnitId:r,drawingId:i}=w,o=getSheetCommandTarget(this._univerInstanceService,{unitId:e,subUnitId:r}),a=w,s=this._univerInstanceService.getUnit(e,UniverInstanceType.UNIVER_SHEET);if(!s)return;const d=s.getActiveSheet().getSheetId();if(!a||!o)return;const l=null===(f=this._renderManagerService.getRenderById(e))||void 0===f?void 0:f.with(SheetSkeletonManagerService);if(!l)return;const u=l.getSkeletonParam(r);if(!u)return;const{transform:g,data:I}=a,v=this._getSceneAndTransformerByDrawingSearch(e);if(null==v)return;const{scene:D,canvas:T}=v;if(null==g)return;if(d!==r)return;const{left:C,top:y,width:b,height:E,angle:P,flipX:M,flipY:R,skewX:A,skewY:U}=g,O=getDrawingShapeKeyByDrawingSearch({unitId:e,subUnitId:r,drawingId:i}),x=D.getObject(O);if(null!=x)return void x.transformByState({left:C,top:y,width:b,height:E,angle:P,flipX:M,flipY:R,skewX:A,skewY:U});const N=calcDomPositionByAnchor({rotate:0,startX:S.startX,startY:0,endX:m.endX,endY:m.endY,width:n.width,height:n.height,absolute:{left:m.absolute.left,top:m.absolute.top}},n),k=new Rect(O,{left:N.startX,top:N.startY,width:N.width,height:N.height,zIndex:this._drawingManagerService.getDrawingOrder(e,r).length-1});D.addObject(k,DRAWING_OBJECT_LAYER_INDEX),!1!==a.allowTransform&&D.attachTransformerTo(k);const j=new DisposableCollection,F=D.getMainViewport(),B={dispose:j,rect:k,unitId:e,subUnitId:r,id:i,boundsOfViewArea:{top:0,left:F.left,bottom:F.bottom,right:F.right},domAnchor:n,scrollDirectionResponse:"HORIZONTAL"},W=new BehaviorSubject(calcSheetFloatDomPosition(k,v.renderUnit.scene,u.skeleton,o.worksheet,B));B.position$=W;let L={position$:W,id:i,componentKey:a.componentKey,onPointerDown:()=>{},onPointerMove:()=>{},onPointerUp:()=>{},onWheel:e=>{T.dispatchEvent(new WheelEvent(e.type,e))},data:I,unitId:e};t.eventPassThrough&&(L={...L,onPointerDown:e=>{T.dispatchEvent(new PointerEvent(e.type,e))},onPointerMove:e=>{T.dispatchEvent(new PointerEvent(e.type,e))},onPointerUp:e=>{T.dispatchEvent(new PointerEvent(e.type,e))}}),this._canvasFloatDomService.addFloatDom(L);const G=k.onTransformChange$.subscribeEvent(()=>{const e=calcSheetFloatDomPosition(k,v.renderUnit.scene,u.skeleton,o.worksheet,B);W.next(e)});this.disposeWithMe(p.subscribe(t=>{const a=calcDomPositionByAnchor({rotate:0,startX:t.startX,startY:0,endX:t.endX,endY:t.endY,width:n.width,height:n.height,absolute:{left:m.absolute.left,top:m.absolute.top}},n),s=calcSheetFloatDomPosition(new Rect(getDrawingShapeKeyByDrawingSearch({unitId:e,subUnitId:r,drawingId:i}),{left:a.startX,top:0,width:n.width,height:n.height,zIndex:this._drawingManagerService.getDrawingOrder(e,r).length-1}),v.renderUnit.scene,u.skeleton,o.worksheet,B);W.next(s)}));const H=null===(_=this._renderManagerService.getRenderById(e))||void 0===_?void 0:_.with(SheetSkeletonManagerService);null==H||H.currentSkeleton$.subscribe(e=>{e&&c.sheetId!==e.sheetId&&this._removeDom(h,!0)}),j.add(()=>{this._canvasFloatDomService.removeFloatDom(i)}),G&&j.add(G),this._domLayerInfoMap.set(i,B)}return{id:h,dispose:()=>{this._removeDom(h,!0)}}}_createRangePositionObserver(e,t,n){let{startRow:r,startColumn:i}=e;const o=calcCellPositionByCell(r,i,n),a=new BehaviorSubject(o),s=calcCellPositionByCell(e.endRow,e.endColumn,n),d=new BehaviorSubject(s),c=()=>{const t=calcCellPositionByCell(r,i,n),o=calcCellPositionByCell(e.endRow,e.endColumn,n);a.next(t),d.next(o)},l=new DisposableCollection;l.add(t.engine.clientRect$.subscribe(()=>c())),l.add(this._commandService.onCommandExecuted(e=>{(e.id===SetWorksheetRowAutoHeightMutation.id&&e.params.rowsAutoHeightInfo.findIndex(e=>e.row===r)>-1||COMMAND_LISTENER_SKELETON_CHANGE.indexOf(e.id)>-1||e.id===SetScrollOperation.id||e.id===SetZoomRatioOperation.id)&&c()}));return{position$:a.pipe(map(t=>{const r=calcCellPositionByCell(e.endRow,e.endColumn,n);return{rotate:0,width:r.right-t.left,height:r.bottom-t.top,absolute:{left:!0,top:!0},startX:t.left,startY:t.top,endX:r.right,endY:r.bottom}})),position:{rotate:0,width:s.right-o.left,height:s.bottom-o.top,absolute:{left:!0,top:!0},startX:o.left,startY:o.top,endX:s.right,endY:s.bottom},updateRowCol:(e,t)=>{r=e,i=t,c()},topLeftPos$:a,rightBottomPos$:d,disposable:l}}};function calcCellPositionByCell(e,t,n){const r=n.getCellWithCoordByIndex(e,t),i=r.isMergedMainCell?r.mergeInfo:r;return{left:i.startX,right:i.endX,top:i.startY,bottom:i.endY}}function calcDomPositionByAnchor(e,t,n){var r,i,o;n=null!==(r=n)&&void 0!==r?r:1;const a=e.endX-e.startX,s=e.endY-e.startY,d=null!==(i=null==t?void 0:t.width)&&void 0!==i?i:a,c=null!==(o=null==t?void 0:t.height)&&void 0!==o?o:s;let l=0,u=0;if(t){if("right"===t.horizonOffsetAlign){const r=calculateOffset(t.marginX,a*n);l=e.endX-r-d}else l=e.startX+calculateOffset(t.marginX,a);if("bottom"===t.verticalOffsetAlign){const r=calculateOffset(t.marginY,s*n);u=e.endY-r-c}else u=e.startY+calculateOffset(t.marginY,s)}return{rotate:0,startX:l,startY:u,endX:e.endX,endY:e.endY,width:d,height:c,absolute:{left:e.absolute.left,top:e.absolute.top}}}function calculateOffset(e,t){return void 0===e?0:"number"==typeof e?e:t*Number.parseFloat(e)/100}SheetCanvasFloatDomManagerService=__decorate([__decorateParam(0,Inject(IRenderManagerService)),__decorateParam(1,IUniverInstanceService),__decorateParam(2,Inject(ICommandService)),__decorateParam(3,IDrawingManagerService),__decorateParam(4,Inject(CanvasFloatDomService)),__decorateParam(5,ISheetDrawingService),__decorateParam(6,Inject(LifecycleService))],SheetCanvasFloatDomManagerService);const PrintingFloatDom=e=>{const{floatDomInfos:t,scene:n,skeleton:r,worksheet:i}=e;return jsx("div",{style:{position:"absolute",top:0,left:0},children:useMemo(()=>t.map(e=>{const{width:t,height:o,angle:a,left:s,top:d}=e.transform,c=transformBound2DOMBound({left:null!=s?s:0,right:(null!=s?s:0)+(null!=t?t:0),top:null!=d?d:0,bottom:(null!=d?d:0)+(null!=o?o:0)},n,r,i,void 0,!0),{scaleX:l,scaleY:u}=n.getAncestorScale(),g={startX:c.left,endX:c.right,startY:c.top,endY:c.bottom,rotate:a,width:t*l,height:o*u,absolute:c.absolute},h={position$:new BehaviorSubject(g),position:g,id:e.drawingId,componentKey:e.componentKey,onPointerMove:()=>{},onPointerDown:()=>{},onPointerUp:()=>{},onWheel:()=>{},unitId:e.unitId,data:e.data};return[e.drawingId,h]}),[t,n,r,i]).map(([e,t])=>jsx(PrintFloatDomSingle,{layer:t,id:e,position:t.position},e))})};let SheetDrawingPrintingController=class extends Disposable{constructor(e,t,n,r,i,o,a){super(),this._sheetPrintInterceptorService=e,this._drawingRenderService=t,this._drawingManagerService=n,this._renderManagerService=r,this._canvasFloatDomManagerService=i,this._componetManager=o,this._injector=a,this._initPrinting(),this._initPrintingDom()}_initPrinting(){this.disposeWithMe(this._sheetPrintInterceptorService.interceptor.intercept(this._sheetPrintInterceptorService.interceptor.getInterceptPoints().PRINTING_COMPONENT_COLLECT,{handler:(e,t,n)=>{const{unitId:r,scene:i,subUnitId:o}=t,a=this._drawingManagerService.getDrawingDataForUnit(r),s=null==a?void 0:a[o];return s&&s.order.forEach(e=>{const t=s.data[e];t.drawingType!==DrawingTypeEnum.DRAWING_CHART&&t.drawingType!==DrawingTypeEnum.DRAWING_DOM&&this._drawingRenderService.renderDrawing(t,i)}),n()}})),this.disposeWithMe(this._sheetPrintInterceptorService.interceptor.intercept(this._sheetPrintInterceptorService.interceptor.getInterceptPoints().PRINTING_RANGE,{handler:(e,t,n)=>{const{unitId:r,subUnitId:i}=t,o=this._renderManagerService.getRenderById(r);if(!o)return n(e);const a=o.with(SheetSkeletonManagerService).getSkeletonParam(i);if(!a)return n(e);const s=this._drawingManagerService.getDrawingDataForUnit(r),d=null==s?void 0:s[t.subUnitId];if(!d)return n(e);const{scaleX:c,scaleY:l}=o.scene,u=e?{...e}:{startColumn:0,endColumn:0,endRow:0,startRow:0},g=d.order.map(e=>d.data[e]);return g.length?(g.forEach(e=>{if(!e.groupId&&e.transform&&Tools.isDefine(e.transform.left)&&Tools.isDefine(e.transform.top)&&Tools.isDefine(e.transform.width)&&Tools.isDefine(e.transform.height)){const t=a.skeleton.getCellIndexByOffset(e.transform.left,e.transform.top,c,l,{x:0,y:0}),n=a.skeleton.getCellIndexByOffset(e.transform.left+e.transform.width,e.transform.top+e.transform.height,c,l,{x:0,y:0});t.column<u.startColumn&&(u.startColumn=t.column),t.row<u.startRow&&(u.startRow=t.row),u.endRow<n.row&&(u.endRow=n.row),u.endColumn<n.column&&(u.endColumn=n.column)}}),n(u)):n(e)}}))}_initPrintingDom(){this.disposeWithMe(this._sheetPrintInterceptorService.interceptor.intercept(this._sheetPrintInterceptorService.interceptor.getInterceptPoints().PRINTING_DOM_COLLECT,{handler:(e,t,n)=>{const{unitId:r,subUnitId:i}=t,o=this._drawingManagerService.getDrawingDataForUnit(r),a=null==o?void 0:o[i];if(a){const r=a.order.map(e=>{const t=a.data[e];if(t.drawingType===DrawingTypeEnum.DRAWING_CHART)return{...t,componentKey:this._componetManager.get(PRINT_CHART_COMPONENT_KEY)};if(t.drawingType===DrawingTypeEnum.DRAWING_DOM){const e=this._sheetPrintInterceptorService.getPrintComponent(t.componentKey);return{...t,componentKey:this._componetManager.get(e||t.componentKey)}}return null}).filter(Boolean);return render(jsx(connectInjector(PrintingFloatDom,this._injector),{floatDomInfos:r,scene:t.scene,skeleton:t.skeleton,worksheet:t.worksheet}),t.root),null==e||e.add(()=>{unmount(t.root)}),n(e)}}}))}};SheetDrawingPrintingController=__decorate([__decorateParam(0,Inject(SheetPrintInterceptorService)),__decorateParam(1,Inject(DrawingRenderService)),__decorateParam(2,IDrawingManagerService),__decorateParam(3,IRenderManagerService),__decorateParam(4,Inject(SheetCanvasFloatDomManagerService)),__decorateParam(5,Inject(ComponentManager)),__decorateParam(6,Inject(Injector))],SheetDrawingPrintingController);const UPDATE_COMMANDS=[InsertRowCommand.id,InsertColCommand.id,RemoveRowCommand.id,RemoveColCommand.id,DeleteRangeMoveLeftCommand.id,DeleteRangeMoveUpCommand.id,InsertRangeMoveDownCommand.id,InsertRangeMoveRightCommand.id,DeltaRowHeightCommand.id,SetRowHeightCommand.id,DeltaColumnWidthCommand.id,SetColWidthCommand.id,SetRowHiddenCommand.id,SetSpecificRowsVisibleCommand.id,SetSpecificColsVisibleCommand.id,SetColHiddenCommand.id,MoveColsCommand.id,MoveRowsCommand.id,MoveRangeCommand.id],REFRESH_MUTATIONS=[SetRowVisibleMutation.id,SetRowHiddenMutation.id,SetColVisibleMutation.id,SetColHiddenMutation.id,SetWorksheetRowHeightMutation.id,SetWorksheetRowAutoHeightMutation.id,SetWorksheetRowIsAutoHeightMutation.id,SetWorksheetColWidthMutation.id];let SheetDrawingTransformAffectedController=class extends Disposable{constructor(e,t,n,r,i,o,a,s,d){super(),this._context=e,this._commandService=t,this._sheetSkeletonService=n,this._selectionRenderService=r,this._sheetInterceptorService=i,this._selectionManagerService=o,this._sheetDrawingService=a,this._drawingManagerService=s,this._univerInstanceService=d,this._sheetInterceptorListener(),this._commandListener(),this._sheetRefreshListener()}_sheetInterceptorListener(){this.disposeWithMe(this._sheetInterceptorService.interceptAfterCommand({getMutations:e=>{const{id:t,params:n}=e;if(!UPDATE_COMMANDS.includes(t)||!n)return{redos:[],undos:[]};if(t===InsertRowCommand.id)return this._moveRowInterceptor(n,"insert");if([MoveColsCommand.id,MoveRowsCommand.id,MoveRangeCommand.id].includes(t)){let e;if(t===MoveRangeCommand.id){const t=n;if(t.toUnitId&&t.fromUnitId&&t.toUnitId!==t.fromUnitId||t.toSubUnitId&&t.fromSubUnitId&&t.toSubUnitId!==t.fromSubUnitId)return{redos:[],undos:[]};e=getSheetCommandTarget(this._univerInstanceService,{unitId:t.toUnitId,subUnitId:t.toSubUnitId})}else e=getSheetCommandTarget(this._univerInstanceService,n);if(!e)return{redos:[],undos:[]};const{unitId:r,subUnitId:i}=e,{fromRange:o,toRange:a}=n;return this._moveRangeInterceptor(r,i,o,a)}if(t===InsertColCommand.id)return this._moveColInterceptor(n,"insert");if(t===RemoveRowCommand.id)return this._moveRowInterceptor(n,"remove");if(t===RemoveColCommand.id)return this._moveColInterceptor(n,"remove");if(t===DeleteRangeMoveLeftCommand.id){const{range:e}=n;return this._getRangeMoveUndo(e,0)}if(t===DeleteRangeMoveUpCommand.id){const{range:e}=n;return this._getRangeMoveUndo(e,1)}if(t===InsertRangeMoveDownCommand.id){const{range:e}=n;return this._getRangeMoveUndo(e,2)}if(t===InsertRangeMoveRightCommand.id){const{range:e}=n;return this._getRangeMoveUndo(e,3)}if(t===SetRowHiddenCommand.id||t===SetSpecificRowsVisibleCommand.id){var r;const e=n,t=getSheetCommandTarget(this._univerInstanceService,e);if(!t)return{redos:[],undos:[]};const{unitId:i,subUnitId:o}=t,a=e.ranges||(null===(r=this._selectionManagerService.getCurrentSelections())||void 0===r?void 0:r.map(e=>e.range).filter(e=>e.rangeType===RANGE_TYPE.ROW));return a&&0!==a.length?this._getDrawingUndoForRowVisible(i,o,a):{redos:[],undos:[]}}if(t===SetColHiddenCommand.id||t===SetSpecificColsVisibleCommand.id){var i;const e=n,t=getSheetCommandTarget(this._univerInstanceService,e);if(!t)return{redos:[],undos:[]};const{unitId:r,subUnitId:o}=t,a=e.ranges||(null===(i=this._selectionManagerService.getCurrentSelections())||void 0===i?void 0:i.map(e=>e.range).filter(e=>e.rangeType===RANGE_TYPE.COLUMN));return a&&0!==a.length?this._getDrawingUndoForColVisible(r,o,a):{redos:[],undos:[]}}if(t===DeltaRowHeightCommand.id||t===DeltaColumnWidthCommand.id){const e=getSheetCommandTarget(this._univerInstanceService);if(!e)return{redos:[],undos:[]};const{unitId:r,subUnitId:i,worksheet:o}=e,a=[];return t===DeltaRowHeightCommand.id?a.push({startRow:n.anchorRow,endRow:n.anchorRow,startColumn:0,endColumn:o.getColumnCount()-1}):a.push({startRow:0,endRow:o.getRowCount()-1,startColumn:n.anchorCol,endColumn:n.anchorCol}),this._getDrawingUndoForRowAndColSize(r,i,a)}if(t===SetRowHeightCommand.id||t===SetColWidthCommand.id){var o;const e=n,t=getSheetCommandTarget(this._univerInstanceService,e);if(!t)return{redos:[],undos:[]};const{unitId:r,subUnitId:i}=t,a=e.ranges||(null===(o=this._selectionManagerService.getCurrentSelections())||void 0===o?void 0:o.map(e=>e.range));return a&&0!==a.length?this._getDrawingUndoForRowAndColSize(r,i,a):{redos:[],undos:[]}}return{redos:[],undos:[]}}}))}_getRangeMoveUndo(e,t){const n=getSheetCommandTarget(this._univerInstanceService);if(!n)return{redos:[],undos:[]};const{unitId:r,subUnitId:i}=n,o=this._sheetDrawingService.getDrawingData(r,i),a=[],s=[],d=[],c=[];if(Object.keys(o).forEach(n=>{const r=o[n],{updateDrawings:i,deleteDrawings:a}=this._getUpdateOrDeleteDrawings(e,t,r);d.push(...i),c.push(...a)}),0===d.length&&0===c.length)return{redos:[],undos:[]};if(d.length>0){const{undo:e,redo:t,objects:n}=this._sheetDrawingService.getBatchUpdateOp(d);a.push({id:SetDrawingApplyMutation.id,params:{unitId:r,subUnitId:i,op:t,objects:n,type:DrawingApplyType.UPDATE}}),s.push({id:SetDrawingApplyMutation.id,params:{unitId:r,subUnitId:i,op:e,objects:n,type:DrawingApplyType.UPDATE}})}if(c.length>0){const e=this._sheetDrawingService.getBatchRemoveOp(c),t=e.undo,n=e.redo,o=e.objects;a.push({id:SetDrawingApplyMutation.id,params:{unitId:r,subUnitId:i,op:n,objects:o,type:DrawingApplyType.REMOVE}}),s.push({id:SetDrawingApplyMutation.id,params:{unitId:r,subUnitId:i,op:t,objects:o,type:DrawingApplyType.INSERT}})}return a.push({id:ClearSheetDrawingTransformerOperation.id,params:[r]}),s.push({id:ClearSheetDrawingTransformerOperation.id,params:[r]}),{redos:a,undos:s}}_getUpdateOrDeleteDrawings(e,t,n){const r=[],i=[],{sheetTransform:o,anchorType:a=SheetDrawingAnchorType.Position,transform:s,unitId:d,subUnitId:c,drawingId:l}=n,u=this._sheetSkeletonService.getSkeletonParam(d,c);if(!o||!s||!u)return{updateDrawings:r,deleteDrawings:i};const{from:g,to:h}=o,{row:m,column:p}=g,{row:S,column:I}=h,{startRow:w,endRow:f,startColumn:_,endColumn:v}=e;let D,T=null,C=null;if(0===t&&m>=w&&S<=f)if(p>=_&&I<=v)i.push({unitId:d,subUnitId:c,drawingId:l});else{var y;const e=this._shrinkCol(_,v,{sheetSkeletonParam:u,sheetTransform:o,transform:s,anchorType:a});T=null==e?void 0:e.newSheetTransform,C=null==e?void 0:e.newTransform,D=null!==(y=null==e?void 0:e.axisAlignSheetTransform)&&void 0!==y?y:void 0}else if(1===t&&p>=_&&I<=v)if(m>=w&&S<=f)i.push({unitId:d,subUnitId:c,drawingId:l});else{var b;const e=this._shrinkRow(w,f,{sheetSkeletonParam:u,sheetTransform:o,transform:s,anchorType:a});T=null==e?void 0:e.newSheetTransform,C=null==e?void 0:e.newTransform,D=null!==(b=null==e?void 0:e.axisAlignSheetTransform)&&void 0!==b?b:void 0}else if(2===t){var E;const e=this._expandRow(w,f,{sheetSkeletonParam:u,sheetTransform:o,transform:s,anchorType:a});T=null==e?void 0:e.newSheetTransform,C=null==e?void 0:e.newTransform,D=null!==(E=null==e?void 0:e.axisAlignSheetTransform)&&void 0!==E?E:void 0}else if(3===t){var P;const e=this._expandCol(_,v,{sheetSkeletonParam:u,sheetTransform:o,transform:s,anchorType:a});T=null==e?void 0:e.newSheetTransform,C=null==e?void 0:e.newTransform,D=null!==(P=null==e?void 0:e.axisAlignSheetTransform)&&void 0!==P?P:void 0}if(T&&C){const e=drawingPositionToTransform(T,u);r.push({...n,sheetTransform:T,transform:e,axisAlignSheetTransform:D})}return{updateDrawings:r,deleteDrawings:i}}_remainDrawingSize(e,t,n,r){const i=transformToDrawingPosition({...e},r);if(i){const o=transformToAxisAlignPosition({...e},r);t.push({...n,sheetTransform:i,axisAlignSheetTransform:o})}}_getDrawingUndoForColVisible(e,t,n){const r=this._sheetSkeletonService.getSkeleton(e,t);if(!r)return{redos:[],undos:[]};const i=this._drawingManagerService.getDrawingData(e,t),o=[],a=[];if(Object.keys(i).forEach(e=>{const t=i[e],{sheetTransform:s,transform:d,anchorType:c=SheetDrawingAnchorType.Position}=t;if(c===SheetDrawingAnchorType.None)this._remainDrawingSize(d,o,t,r);else{const{from:e,to:i}=s,{row:l,column:u}=e,{row:g,column:h}=i;for(let e=0;e<n.length;e++){const{startColumn:i,endColumn:s}=n[e];if(h<i)continue;if(c===SheetDrawingAnchorType.Position){let e=null,n=null;if(u>=i&&u<=s){const e=attachRangeWithCoord(r,{startColumn:u,endColumn:s,startRow:l,endRow:g});n={...d,left:e.startX}}if(n){e=transformToDrawingPosition(n,r);const i=transformToAxisAlignPosition(n,r);if(e&&n){o.push({...t,sheetTransform:e,transform:n,axisAlignSheetTransform:i});break}}continue}if(u>=i&&h<=s)continue;let m=null,p=null;if(u>=i&&u<=s){const e=attachRangeWithCoord(r,{startColumn:u,endColumn:s,startRow:l,endRow:g});p={...d,left:(null==e?void 0:e.startX)||0,width:((null==d?void 0:d.width)||0)-e.endX+e.startX}}else if(h>=i&&h<=s){const e=attachRangeWithCoord(r,{startColumn:i,endColumn:h,startRow:l,endRow:g});p={...d,left:e.startX-((null==d?void 0:d.width)||0)}}else{const e=attachRangeWithCoord(r,{startColumn:i,endColumn:s,startRow:l,endRow:g});if(p={...d,width:((null==d?void 0:d.width)||0)-e.endX+e.startX},m=transformToDrawingPosition(p,r),m&&p){const e=transformToAxisAlignPosition(p,r);a.push({...t,sheetTransform:m,transform:p,axisAlignSheetTransform:e});break}}if(p&&(m=transformToDrawingPosition(p,r)),p&&m){const e=transformToAxisAlignPosition(p,r);o.push({...t,sheetTransform:m,transform:p,axisAlignSheetTransform:e});break}this._remainDrawingSize(d,o,t,r)}}}),0===o.length&&0===a.length)return{redos:[],undos:[]};const{redos:s,undos:d}=this._createUndoAndRedoMutation(e,t,o),c=[],l=[];if(a.length>0){const{redos:n,undos:r}=this._createUndoAndRedoMutation(e,t,a);c.push(...n),l.push(...r)}return{redos:s,undos:d,preRedos:c,preUndos:l}}_createUndoAndRedoMutation(e,t,n){const{undo:r,redo:i,objects:o}=this._sheetDrawingService.getBatchUpdateOp(n);return{redos:[{id:SetDrawingApplyMutation.id,params:{unitId:e,subUnitId:t,op:i,objects:o,type:DrawingApplyType.UPDATE}},{id:ClearSheetDrawingTransformerOperation.id,params:[e]}],undos:[{id:SetDrawingApplyMutation.id,params:{unitId:e,subUnitId:t,op:r,objects:o,type:DrawingApplyType.UPDATE}},{id:ClearSheetDrawingTransformerOperation.id,params:[e]}]}}_getDrawingUndoForRowVisible(e,t,n){const r=this._sheetSkeletonService.getSkeleton(e,t);if(!r)return{redos:[],undos:[]};const i=this._drawingManagerService.getDrawingData(e,t),o=[],a=[];if(Object.keys(i).forEach(e=>{const t=i[e],{sheetTransform:s,transform:d,anchorType:c=SheetDrawingAnchorType.Position}=t;if(c===SheetDrawingAnchorType.None)this._remainDrawingSize(d,o,t,r);else{const{from:e,to:i}=s,{row:l,column:u}=e,{row:g,column:h}=i;for(let e=0;e<n.length;e++){const{startRow:i,endRow:s}=n[e];if(g<i)continue;if(c===SheetDrawingAnchorType.Position){let e=null,n=null;if(l>=i&&l<=s){const e=attachRangeWithCoord(r,{startColumn:u,endColumn:h,startRow:l,endRow:s});n={...d,top:e.startY}}if(n){e=transformToDrawingPosition(n,r);const i=transformToAxisAlignPosition(n,r);if(e&&n){o.push({...t,sheetTransform:e,transform:n,axisAlignSheetTransform:i});break}}continue}if(l>=i&&g<=s)continue;let m=null,p=null;if(l>=i&&l<=s){const e=attachRangeWithCoord(r,{startColumn:u,endColumn:h,startRow:l,endRow:s});p={...d,top:(null==e?void 0:e.startY)||0,height:((null==d?void 0:d.height)||0)-e.endY+e.startY}}else if(g>=i&&g<=s){const e=attachRangeWithCoord(r,{startColumn:u,endColumn:h,startRow:i,endRow:g});p={...d,top:e.startY-((null==d?void 0:d.height)||0)}}else{const e=attachRangeWithCoord(r,{startColumn:u,endColumn:h,startRow:i,endRow:s});if(p={...d,height:((null==d?void 0:d.height)||0)-e.endY+e.startY},m=transformToDrawingPosition(p,r),m&&p){const e=transformToAxisAlignPosition(p,r);a.push({...t,sheetTransform:m,transform:p,axisAlignSheetTransform:e});break}}if(p&&(m=transformToDrawingPosition(p,r)),p&&m){const e=transformToAxisAlignPosition(p,r);o.push({...t,sheetTransform:m,transform:p,axisAlignSheetTransform:e});break}this._remainDrawingSize(d,o,t,r)}}}),0===o.length&&0===a.length)return{redos:[],undos:[]};const{redos:s,undos:d}=this._createUndoAndRedoMutation(e,t,o),c=[],l=[];if(a.length>0){const{redos:n,undos:r}=this._createUndoAndRedoMutation(e,t,a);c.push(...n),l.push(...r)}return{redos:s,undos:d,preRedos:c,preUndos:l}}_getDrawingUndoForRowAndColSize(e,t,n){const r=this._sheetSkeletonService.getSkeletonParam(e,t);if(!r)return{redos:[],undos:[]};const{skeleton:i}=r,o=this._drawingManagerService.getDrawingData(e,t),a=[];return Object.keys(o).forEach(e=>{const t=o[e],{sheetTransform:s,transform:d,anchorType:c=SheetDrawingAnchorType.Position}=t;if(c===SheetDrawingAnchorType.None)this._remainDrawingSize(d,a,t,i);else{const{from:e,to:o}=s,{row:l,column:u}=e,{row:g,column:h}=o;for(let e=0;e<n.length;e++){const{startRow:o,endRow:m,startColumn:p,endColumn:S}=n[e];if(g<o||h<p)continue;if(c===SheetDrawingAnchorType.Position&&(l<=o&&g>=m||u<=p&&h>=S)){this._remainDrawingSize(d,a,t,i);continue}const I=drawingPositionToTransform({...s},r);if(I){a.push({...t,transform:I});break}}}}),0===a.length?{redos:[],undos:[]}:this._createUndoAndRedoMutation(e,t,a)}_getUnitIdAndSubUnitId(e,t){let n;if(n="insert"===t?getSheetCommandTarget(this._univerInstanceService,e):getSheetCommandTarget(this._univerInstanceService),!n)return;const{unitId:r,subUnitId:i}=n;return{unitId:r,subUnitId:i}}_moveRangeInterceptor(e,t,n,r){const i=this._sheetSkeletonService.getSkeletonParam(e,t);if(!i)return{redos:[],undos:[]};const{skeleton:o}=i,a=attachRangeWithCoord(o,n);if(!a)return{redos:[],undos:[]};const{startX:s,endX:d,startY:c,endY:l}=a,u=this._sheetDrawingService.getDrawingData(e,t),g=[];Object.keys(u).forEach(e=>{const t=u[e];if(t.anchorType!==SheetDrawingAnchorType.Both)return;const{transform:n}=t;if(!n)return;const{left:r=0,top:i=0,width:o=0,height:a=0}=n,{drawingStartX:h,drawingEndX:m,drawingStartY:p,drawingEndY:S}={drawingStartX:r,drawingEndX:r+o,drawingStartY:i,drawingEndY:i+a};s<=h&&m<=d&&c<=p&&S<=l&&g.push(t)});const h=[],m=[],p=r.startRow-n.startRow,S=r.startColumn-n.startColumn,I=g.map(n=>{const r=n.sheetTransform,o={to:{...r.to,row:r.to.row+p,column:r.to.column+S},from:{...r.from,row:r.from.row+p,column:r.from.column+S}},a=drawingPositionToTransform(o,i);return{unitId:e,subUnitId:t,drawingId:n.drawingId,transform:a,sheetTransform:o}});if(I.length){const{undo:n,redo:r,objects:i}=this._sheetDrawingService.getBatchUpdateOp(I);h.push({id:SetDrawingApplyMutation.id,params:{unitId:e,subUnitId:t,op:r,objects:i,type:DrawingApplyType.UPDATE}}),m.push({id:SetDrawingApplyMutation.id,params:{unitId:e,subUnitId:t,op:n,objects:i,type:DrawingApplyType.UPDATE}})}return{redos:h,undos:m}}_moveRowInterceptor(e,t){const n=this._getUnitIdAndSubUnitId(e,t);if(!n)return{redos:[],undos:[]};const{unitId:r,subUnitId:i}=n,o=this._sheetSkeletonService.getSkeletonParam(r,i);if(!o)return{redos:[],undos:[]};const{range:a}=e,s=a.startRow,d=a.endRow,c=[],l=[],u=this._sheetDrawingService.getDrawingData(r,i),g=[],h=[];if(Object.keys(u).forEach(e=>{const{sheetTransform:n,transform:a,anchorType:c=SheetDrawingAnchorType.Position}=u[e];if(!n||!a)return;let l,m,p;if("insert"===t){var S;const e=this._expandRow(s,d,{sheetSkeletonParam:o,sheetTransform:n,transform:a,anchorType:c});l=null==e?void 0:e.newSheetTransform,m=null==e?void 0:e.newTransform,p=null!==(S=null==e?void 0:e.axisAlignSheetTransform)&&void 0!==S?S:void 0}else{const{from:t,to:u}=n,{row:g}=t,{row:S}=u;if(c===SheetDrawingAnchorType.Both&&g>=s&&S<=d)h.push({unitId:r,subUnitId:i,drawingId:e});else{var I;const e=this._shrinkRow(s,d,{sheetSkeletonParam:o,sheetTransform:n,transform:a,anchorType:c});l=null==e?void 0:e.newSheetTransform,m=null==e?void 0:e.newTransform,p=null!==(I=null==e?void 0:e.axisAlignSheetTransform)&&void 0!==I?I:void 0}}if(!l||!m)return;const w={unitId:r,subUnitId:i,drawingId:e,transform:m,sheetTransform:l,axisAlignSheetTransform:p};g.push(w)}),0===g.length&&0===h.length)return{redos:[],undos:[]};if(g.length>0){const{undo:e,redo:t,objects:n}=this._sheetDrawingService.getBatchUpdateOp(g);c.push({id:SetDrawingApplyMutation.id,params:{unitId:r,subUnitId:i,op:t,objects:n,type:DrawingApplyType.UPDATE}}),l.push({id:SetDrawingApplyMutation.id,params:{unitId:r,subUnitId:i,op:e,objects:n,type:DrawingApplyType.UPDATE}})}if(h.length>0){const e=this._sheetDrawingService.getBatchRemoveOp(h),t=e.undo,n=e.redo,o=e.objects;c.push({id:SetDrawingApplyMutation.id,params:{unitId:r,subUnitId:i,op:n,objects:o,type:DrawingApplyType.REMOVE}}),l.push({id:SetDrawingApplyMutation.id,params:{unitId:r,subUnitId:i,op:t,objects:o,type:DrawingApplyType.INSERT}})}return c.push({id:ClearSheetDrawingTransformerOperation.id,params:[r]}),l.push({id:ClearSheetDrawingTransformerOperation.id,params:[r]}),{redos:c,undos:l}}_moveColInterceptor(e,t){const n=this._getUnitIdAndSubUnitId(e,t);if(!n)return{redos:[],undos:[]};const{unitId:r,subUnitId:i}=n,o=this._sheetSkeletonService.getSkeletonParam(r,i);if(!o)return{redos:[],undos:[]};const{range:a}=e,s=a.startColumn,d=a.endColumn,c=[],l=[],u=this._sheetDrawingService.getDrawingData(r,i),g=[],h=[];if(Object.keys(u).forEach(e=>{const{sheetTransform:n,transform:a,anchorType:c=SheetDrawingAnchorType.Position}=u[e];if(!n||!a)return;let l,m,p;if("insert"===t){var S;const e=this._expandCol(s,d,{sheetSkeletonParam:o,sheetTransform:n,transform:a,anchorType:c});l=null==e?void 0:e.newSheetTransform,m=null==e?void 0:e.newTransform,p=null!==(S=null==e?void 0:e.axisAlignSheetTransform)&&void 0!==S?S:void 0}else{const{from:t,to:u}=n,{column:g}=t,{column:S}=u;if(c===SheetDrawingAnchorType.Both&&g>=s&&S<=d)h.push({unitId:r,subUnitId:i,drawingId:e});else{var I;const e=this._shrinkCol(s,d,{sheetSkeletonParam:o,sheetTransform:n,transform:a,anchorType:c});l=null==e?void 0:e.newSheetTransform,m=null==e?void 0:e.newTransform,p=null!==(I=null==e?void 0:e.axisAlignSheetTransform)&&void 0!==I?I:void 0}}if(!l||!m)return;const w={unitId:r,subUnitId:i,drawingId:e,transform:m,sheetTransform:l,axisAlignSheetTransform:p};g.push(w)}),0===g.length&&0===h.length)return{redos:[],undos:[]};if(g.length>0){const{undo:e,redo:t,objects:n}=this._sheetDrawingService.getBatchUpdateOp(g);c.push({id:SetDrawingApplyMutation.id,params:{unitId:r,subUnitId:i,op:t,objects:n,type:DrawingApplyType.UPDATE}}),l.push({id:SetDrawingApplyMutation.id,params:{unitId:r,subUnitId:i,op:e,objects:n,type:DrawingApplyType.UPDATE}})}if(h.length>0){const e=this._sheetDrawingService.getBatchRemoveOp(h),t=e.undo,n=e.redo,o=e.objects;c.push({id:SetDrawingApplyMutation.id,params:{unitId:r,subUnitId:i,op:n,objects:o,type:DrawingApplyType.REMOVE}}),l.push({id:SetDrawingApplyMutation.id,params:{unitId:r,subUnitId:i,op:t,objects:o,type:DrawingApplyType.INSERT}})}return c.push({id:ClearSheetDrawingTransformerOperation.id,params:[r]}),l.push({id:ClearSheetDrawingTransformerOperation.id,params:[r]}),{redos:c,undos:l}}_expandCol(e,t,n){const{sheetSkeletonParam:r,sheetTransform:i,transform:o,anchorType:a=SheetDrawingAnchorType.Position}=n,{skeleton:s}=r,d=t-e+1,{from:c,to:l}=i,{column:u}=c,{column:g}=l;if(a===SheetDrawingAnchorType.None)return{newSheetTransform:transformToDrawingPosition({...o},s),newTransform:o,axisAlignSheetTransform:transformToAxisAlignPosition({...o},s)};let h=null,m=null,p=null;if(u>=e){const n=attachRangeWithCoord(s,{startColumn:e,endColumn:t,startRow:c.row,endRow:l.row});m={...o,left:(o.left||0)+n.endX-n.startX},h=transformToDrawingPosition(m,s),p=transformToAxisAlignPosition(m,s)}else if(g>=t){if(a!==SheetDrawingAnchorType.Both)return{newSheetTransform:transformToDrawingPosition({...o},s),newTransform:o,axisAlignSheetTransform:transformToAxisAlignPosition({...o},s)};h={from:{...c},to:{...l,column:g+d}},m=drawingPositionToTransform(h,r)}return h&&m?{newSheetTransform:h,newTransform:m,axisAlignSheetTransform:p}:null}_shrinkCol(e,t,n){const{sheetSkeletonParam:r,sheetTransform:i,transform:o,anchorType:a=SheetDrawingAnchorType.Position}=n,{skeleton:s}=r,d=t-e+1,{from:c,to:l}=i,{column:u}=c,{column:g}=l;if(a===SheetDrawingAnchorType.None)return{newSheetTransform:transformToDrawingPosition({...o},s),newTransform:o,axisAlignSheetTransform:transformToAxisAlignPosition({...o},s)};let h=null,m=null,p=null;if(u>t)h={from:{...c,column:u-d},to:{...l,column:g-d}},m=drawingPositionToTransform(h,r);else{if(u>=e&&g<=t)return null;if(u<e&&g>t){if(a!==SheetDrawingAnchorType.Both)return{newSheetTransform:transformToDrawingPosition({...o},s),newTransform:o,axisAlignSheetTransform:transformToAxisAlignPosition({...o},s)};h={from:{...c},to:{...l,column:g-d}},m=drawingPositionToTransform(h,r)}else if(u>=e&&u<=t){if(u===e)m={...o,left:(o.left||0)-i.from.columnOffset};else{const t=attachRangeWithCoord(s,{startColumn:e,endColumn:u-1,startRow:c.row,endRow:l.row});m={...o,left:(o.left||0)-t.endX+t.startX-i.from.columnOffset}}h=transformToDrawingPosition(m,s),p=transformToAxisAlignPosition(m,s)}else if(g>=e&&g<=t&&a===SheetDrawingAnchorType.Both){const t=attachRangeWithCoord(s,{startColumn:e-1,endColumn:e-1,startRow:c.row,endRow:l.row});h={from:{...c},to:{...l,column:e-1,columnOffset:t.endX-t.startX}},m=drawingPositionToTransform(h,r)}}return h&&m?{newSheetTransform:h,newTransform:m,axisAlignSheetTransform:p}:null}_expandRow(e,t,n){const{sheetSkeletonParam:r,sheetTransform:i,transform:o,anchorType:a=SheetDrawingAnchorType.Position}=n,{skeleton:s}=r,d=t-e+1,{from:c,to:l}=i,{row:u}=c,{row:g}=l;if(a===SheetDrawingAnchorType.None)return{newSheetTransform:transformToDrawingPosition({...o},s),newTransform:o,axisAlignSheetTransform:transformToAxisAlignPosition({...o},s)};let h=null,m=null,p=null;if(u>=e){const n=attachRangeWithCoord(s,{startRow:e,endRow:t,startColumn:c.column,endColumn:l.column});m={...o,top:(o.top||0)+n.endY-n.startY},h=transformToDrawingPosition(m,s),p=transformToAxisAlignPosition(m,s)}else if(g>=t){if(a!==SheetDrawingAnchorType.Both)return{newSheetTransform:transformToDrawingPosition({...o},s),newTransform:o,axisAlignSheetTransform:transformToAxisAlignPosition({...o},s)};h={from:{...c},to:{...l,row:g+d}},m=drawingPositionToTransform(h,r)}return h&&m?{newSheetTransform:h,newTransform:m,axisAlignSheetTransform:p}:null}_shrinkRow(e,t,n){const{sheetSkeletonParam:r,sheetTransform:i,transform:o,anchorType:a=SheetDrawingAnchorType.Position}=n,{skeleton:s}=r,d=t-e+1,{from:c,to:l}=i,{row:u}=c,{row:g}=l;if(a===SheetDrawingAnchorType.None)return{newSheetTransform:transformToDrawingPosition({...o},s),newTransform:o,axisAlignSheetTransform:transformToAxisAlignPosition({...o},s)};let h=null,m=null,p=null;if(u>t)h={from:{...c,row:u-d},to:{...l,row:g-d}},m=drawingPositionToTransform(h,r);else{if(u>=e&&g<=t)return null;if(u<e&&g>t){if(a!==SheetDrawingAnchorType.Both)return{newSheetTransform:transformToDrawingPosition({...o},s),newTransform:o,axisAlignSheetTransform:transformToAxisAlignPosition({...o},s)};h={from:{...c},to:{...l,row:g-d}},m=drawingPositionToTransform(h,r)}else if(u>=e&&u<=t){if(u===e)m={...o,top:(o.top||0)-i.from.rowOffset};else{const t=attachRangeWithCoord(s,{startRow:e,endRow:u-1,startColumn:c.column,endColumn:l.column});m={...o,top:(o.top||0)-t.endY+t.startY-i.from.rowOffset}}h=transformToDrawingPosition(m,s),p=transformToAxisAlignPosition(m,s)}else if(g>=e&&g<=t&&a===SheetDrawingAnchorType.Both){const t=attachRangeWithCoord(s,{startColumn:c.column,endColumn:c.column,startRow:e-1,endRow:e-1});h={from:{...c},to:{...l,row:e-1,rowOffset:t.endY-t.startY}},m=drawingPositionToTransform(h,r)}}return h&&m?{newSheetTransform:h,newTransform:m,axisAlignSheetTransform:p}:null}_commandListener(){this.disposeWithMe(this._commandService.onCommandExecuted(e=>{if(e.id===SetWorksheetActiveOperation.id){const{unitId:t,subUnitId:n}=e.params;this._updateDrawings(t,n)}})),this.disposeWithMe(this._context.activated$.subscribe(e=>{const{unit:t,unitId:n}=this._context;if(e){const e=t.getActiveSheet().getSheetId();this._updateDrawings(n,e)}else this._clearDrawings(n)}))}_clearDrawings(e){setTimeout(()=>{const t=this._drawingManagerService.drawingManagerData,n=[];Object.keys(t).forEach(r=>{const i=t[r];Object.keys(i).forEach(t=>{const o=i[t].data;Object.keys(o).forEach(t=>{r===e&&n.push(o[t])})})}),this._sheetDrawingService.removeNotification(n),this._drawingManagerService.removeNotification(n)})}_updateDrawings(e,t){setTimeout(()=>{const n=this._sheetSkeletonService.getSkeletonParam(e,t),r=this._drawingManagerService.drawingManagerData,i=[],o=[];Object.keys(r).forEach(a=>{const s=r[a];Object.keys(s).forEach(r=>{const d=s[r].data;Object.keys(d).forEach(s=>{if(a===e&&r===t){const e=d[s];e.sheetTransform&&(e.transform=drawingPositionToTransform(e.sheetTransform,n)),i.push(d[s])}else o.push(d[s])})})}),this._sheetDrawingService.removeNotification(o),this._sheetDrawingService.addNotification(i),this._drawingManagerService.removeNotification(o),this._drawingManagerService.addNotification(i)},0)}_sheetRefreshListener(){this.disposeWithMe(this._commandService.onCommandExecuted(e=>{REFRESH_MUTATIONS.includes(e.id)&&requestIdleCallback(()=>{const t=e.params,n=getSheetCommandTarget(this._univerInstanceService,t);if(!n)return;const{unitId:r,subUnitId:i,worksheet:o}=n;let a=[];"ranges"in t?a=t.ranges:"rowsAutoHeightInfo"in t&&(a=t.rowsAutoHeightInfo.map(e=>({startRow:e.row,endRow:e.row,startColumn:0,endColumn:o.getColumnCount()-1}))),this._refreshDrawingTransform(r,i,a)})}))}_refreshDrawingTransform(e,t,n){const r=this._sheetSkeletonService.getSkeletonParam(e,t),i=this._drawingManagerService.getDrawingData(e,t),o=[];Object.keys(i).forEach(e=>{const t=i[e],{sheetTransform:a,transform:s,anchorType:d=SheetDrawingAnchorType.Position}=t;if(d===SheetDrawingAnchorType.None)return!0;const{from:c,to:l}=a,{row:u,column:g}=c,{row:h,column:m}=l;for(let e=0;e<n.length;e++){const{startRow:i,endRow:c,startColumn:l,endColumn:p}=n[e];if(Rectangle.intersects({startRow:i,endRow:c,startColumn:l,endColumn:p},{startRow:u,endRow:h,startColumn:g,endColumn:m})||u>c||g>p){const e=d===SheetDrawingAnchorType.Position,n=drawingPositionToTransform(a,r);o.push({...t,transform:{...n,width:e?null==s?void 0:s.width:null==n?void 0:n.width,height:e?null==s?void 0:s.height:null==n?void 0:n.height}});break}}}),0!==o.length&&(this._sheetDrawingService.refreshTransform(o),this._drawingManagerService.refreshTransform(o),this._commandService.syncExecuteCommand(ClearSheetDrawingTransformerOperation.id,[e]))}};SheetDrawingTransformAffectedController=__decorate([__decorateParam(1,ICommandService),__decorateParam(2,Inject(SheetSkeletonService)),__decorateParam(3,ISheetSelectionRenderService),__decorateParam(4,Inject(SheetInterceptorService)),__decorateParam(5,Inject(SheetsSelectionsService)),__decorateParam(6,ISheetDrawingService),__decorateParam(7,IDrawingManagerService),__decorateParam(8,IUniverInstanceService)],SheetDrawingTransformAffectedController);const FlipSheetDrawingCommand={id:"sheet.command.toggle-flip-drawings",type:CommandType.COMMAND,handler:(e,t)=>{if(!t)return!1;const n=e.get(ICommandService),r=e.get(IUndoRedoService),i=e.get(ISheetDrawingService),o=e.get(SheetSkeletonService),{drawings:a}=t,s=t.flipH,d=t.flipV,c=[],l=[];for(const t of a){const{unitId:n,subUnitId:r,drawingId:a}=t;c.push(n);const u=i.getDrawingData(n,r),g=null==u?void 0:u[a];if(!g)continue;const h=o.getSkeleton(n,r);if(!h)continue;const m={...g.transform};s&&(m.flipX=!m.flipX),d&&(m.flipY=!m.flipY);const p=transformToDrawingPosition(m,h),S=transformToAxisAlignPosition(m,h),I={unitId:n,subUnitId:r,drawingType:g.drawingType,drawingId:a,transform:m,sheetTransform:p,axisAlignSheetTransform:S};if(g.drawingType===DrawingTypeEnum.DRAWING_IMAGE){const t=getSceneByDrawingSearch(e,n);if(t){const e=getDrawingShapeKeyByDrawingSearch({unitId:n,subUnitId:r,drawingId:a}),i=t.getObject(e);if(i){const e=i.srcRect;if(e){let t;const{left:n=0,top:r=0,right:i=0,bottom:o=0}=e;if(s){const e=n+(i-n)/2;t={left:e-(i-n)/2,top:r,right:e+(i-n)/2,bottom:o}}if(d){const e=r+(o-r)/2;t={left:n,top:e-(o-r)/2,right:i,bottom:e+(o-r)/2}}t&&(I.srcRect=t)}}}}l.push(I)}if(0===l.length)return!1;const{unitId:u,subUnitId:g,undo:h,redo:m,objects:p}=i.getBatchUpdateOp(l),S={id:SetDrawingApplyMutation.id,params:{unitId:u,subUnitId:g,op:m,objects:p,type:DrawingApplyType.UPDATE}},I={id:SetDrawingApplyMutation.id,params:{unitId:u,subUnitId:g,op:h,objects:p,type:DrawingApplyType.UPDATE}};return!!sequenceExecute([S],n).result&&(r.pushUndoRedo({unitID:u,undoMutations:[I,{id:ClearSheetDrawingTransformerOperation.id,params:c}],redoMutations:[S,{id:ClearSheetDrawingTransformerOperation.id,params:c}]}),!0)}};function getSceneByDrawingSearch(e,t){const n=e.get(IRenderManagerService).getRenderById(t);return n?n.scene:null}function cellHasImage(e){var t,n;return!!((null==e||null===(t=e.p)||void 0===t||null===(t=t.drawingsOrder)||void 0===t?void 0:t.length)&&(null==e||null===(n=e.p)||void 0===n||null===(n=n.drawingsOrder)||void 0===n?void 0:n.length)>0)}function selectionHasImages(e,t){const n=e.getActiveSheet();if(!n)return!1;const r=n.getCellMatrix(),{startRow:i,endRow:o,startColumn:a,endColumn:s}=t;for(let e=i;e<=o;e++)for(let t=a;t<=s;t++)if(cellHasImage(r.getValue(e,t)))return!0;return!1}function isFileSystemAccessSupported(){return"showDirectoryPicker"in window}function SaveCellImagesMenuFactory(e){const t=e.get(IUniverInstanceService),n=e.get(SheetsSelectionsService),r=combineLatest([getMenuHiddenObservable(e,UniverInstanceType.UNIVER_SHEET),t.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_SHEET).pipe(switchMap(e=>e?n.selectionMoveEnd$.pipe(map(()=>{if(!isFileSystemAccessSupported())return!0;const t=n.getCurrentSelections();if(!t||0===t.length)return!0;for(const n of t)if(selectionHasImages(e,n.range))return!1;return!0})):of(!0)))]).pipe(map(([e,t])=>e||t));return{id:SaveCellImagesCommand.id,type:MenuItemType.BUTTON,icon:"DownloadImageIcon",title:"sheets-drawing-ui.save.menuLabel",hidden$:r}}const menuSchema={[RibbonInsertGroup.MEDIA]:{[SHEETS_IMAGE_MENU_ID]:{order:0,menuItemFactory:ImageMenuFactory,[InsertFloatImageCommand.id]:{order:0,menuItemFactory:UploadFloatImageMenuFactory},[InsertCellImageCommand.id]:{order:1,menuItemFactory:UploadCellImageMenuFactory}}},[ContextMenuPosition.MAIN_AREA]:{[ContextMenuGroup.OTHERS]:{[SaveCellImagesCommand.id]:{order:10,menuItemFactory:SaveCellImagesMenuFactory}}},[ContextMenuPosition.COL_HEADER]:{[ContextMenuGroup.OTHERS]:{[SaveCellImagesCommand.id]:{order:10,menuItemFactory:SaveCellImagesMenuFactory}}},[ContextMenuPosition.ROW_HEADER]:{[ContextMenuGroup.OTHERS]:{[SaveCellImagesCommand.id]:{order:10,menuItemFactory:SaveCellImagesMenuFactory}}}};function BatchSaveImagesDialog(){const e=useDependency(LocaleService),t=useDependency(IDialogService),n=useDependency(IBatchSaveImagesService),[r,i]=useState(["cellAddress"]),[o,a]=useState(!1),[s,d]=useState(null),c=useMemo(()=>n.getCellImagesInSelection(),[n]),l=useMemo(()=>n.getDataColumns(),[n]),u=useMemo(()=>n.getSelectionRowRange(),[n]),g=l.length>0,h=useMemo(()=>l.map(e=>({label:e.label,value:String(e.index)})),[l]),[m,p]=useState(()=>h.length>0?h[0].value:"0");useHighlightRange(useMemo(()=>{if(!r.includes("columnValue")||!u)return[];const e=Number(m);return[{startRow:u.startRow,endRow:u.endRow,startColumn:e,endColumn:e}]},[r,m,u]));const S=useCallback(e=>{0!==e.length&&i(e)},[]),I=useCallback(e=>{p(String(e))},[]),w=useCallback(()=>{t.close(BATCH_SAVE_IMAGES_DIALOG_ID)},[t]),f=useCallback(async()=>{if(0!==c.length){a(!0),d(null);try{await n.saveImages(c,{fileNameParts:r,columnIndex:r.includes("columnValue")?Number(m):void 0}),t.close(BATCH_SAVE_IMAGES_DIALOG_ID)}catch(t){console.error("Failed to save images:",t),d(e.t("sheets-drawing-ui.save.error"))}finally{a(!1)}}},[n,c,r,m,t,e]),_=r.includes("columnValue");return jsxs("div",{className:"univer-flex univer-flex-col",children:[jsx(FormLayout,{label:e.t("sheets-drawing-ui.save.imageCount"),children:jsx("div",{className:"univer-text-sm univer-text-gray-600",children:c.length})}),jsx(FormLayout,{label:e.t("sheets-drawing-ui.save.fileNameConfig"),children:jsxs(CheckboxGroup,{value:r,onChange:S,direction:"vertical",children:[jsx(Checkbox,{value:"cellAddress",disabled:!g,children:e.t("sheets-drawing-ui.save.useRowCol")}),g&&jsx(Checkbox,{value:"columnValue",children:e.t("sheets-drawing-ui.save.useColumnValue")})]})}),_&&jsx(FormLayout,{label:e.t("sheets-drawing-ui.save.selectColumn"),children:jsx(Select,{value:m,options:h,onChange:I})}),s&&jsx("div",{className:"univer-text-xs univer-text-red-500",children:s}),jsxs("div",{className:"univer-flex univer-justify-end univer-gap-2 univer-border-t univer-border-gray-200 univer-pt-3",children:[jsx(Button,{onClick:w,disabled:o,children:e.t("sheets-drawing-ui.save.cancel")}),jsx(Button,{variant:"primary",onClick:f,disabled:o||0===c.length,children:o?e.t("sheets-drawing-ui.save.saving"):e.t("sheets-drawing-ui.save.confirm")})]})]})}const SheetDrawingAnchor=e=>{var t;const n=useDependency(ICommandService),r=useDependency(LocaleService),i=useDependency(IDrawingManagerService),o=useDependency(IRenderManagerService),{drawings:a}=e,s=a[0];if(null==s)return;const{unitId:d}=s,c=o.getRenderById(d),l=null==c?void 0:c.scene;if(null==l)return;const u=l.getTransformerByCreate(),[g,h]=useState(!0),[m,p]=useState(null!==(t=s.anchorType)&&void 0!==t?t:SheetDrawingAnchorType.Position);return useEffect(()=>{const e=u.clearControl$.subscribe(e=>{!0===e&&h(!1)}),t=u.changeStart$.subscribe(e=>{const{objects:t}=e,n=function(e,t){const n=[];return e.forEach(e=>{const{oKey:r}=e,i=t.getDrawingOKey(r);if(null==i)return n.push(null),!0;const{unitId:o,subUnitId:a,drawingId:s,drawingType:d,anchorType:c,sheetTransform:l,axisAlignSheetTransform:u}=i;n.push({unitId:o,subUnitId:a,drawingId:s,anchorType:c,sheetTransform:l,drawingType:d,axisAlignSheetTransform:u})}),n}(t,i);if(0===n.length)h(!1);else if(n.length>=1){var r;h(!0),p((null===(r=n[0])||void 0===r?void 0:r.anchorType)||SheetDrawingAnchorType.Position)}});return()=>{t.unsubscribe(),e.unsubscribe()}},[]),jsxs("div",{className:clsx("univer-grid univer-gap-2 univer-py-2 univer-text-gray-400",{"univer-hidden":!g}),children:[jsx("header",{className:"univer-text-gray-600 dark:!univer-text-gray-200",children:jsx("div",{children:r.t("sheets-drawing-ui.drawing-anchor.title")})}),jsx("div",{children:jsxs(RadioGroup,{value:m,onChange:function(e){p(e);const t=i.getFocusDrawings();if(0===t.length)return;const r=t.map(t=>({unitId:t.unitId,subUnitId:t.subUnitId,drawingId:t.drawingId,anchorType:e}));n.executeCommand(SetSheetDrawingCommand.id,{unitId:t[0].unitId,drawings:r})},direction:"vertical",children:[jsx(Radio,{value:SheetDrawingAnchorType.Both,children:r.t("sheets-drawing-ui.drawing-anchor.both")}),jsx(Radio,{value:SheetDrawingAnchorType.Position,children:r.t("sheets-drawing-ui.drawing-anchor.position")}),jsx(Radio,{value:SheetDrawingAnchorType.None,children:r.t("sheets-drawing-ui.drawing-anchor.none")})]})})]})},SheetDrawingPanel=()=>{const e=useDependency(IDrawingManagerService),[t,n]=useState(e.getFocusDrawings());return useEffect(()=>{const t=e.focus$.subscribe(e=>{n(e)});return()=>{t.unsubscribe()}},[]),!!(null==t?void 0:t.length)&&jsxs("div",{className:"univer-text-sm",children:[jsx(DrawingCommonPanel,{drawings:t}),jsx(SheetDrawingAnchor,{drawings:t})]})};function whenSheetDrawingFocused(e){return e.getContextValue(FOCUSING_SHEET)&&!e.getContextValue(FOCUSING_FX_BAR_EDITOR)&&!e.getContextValue(FOCUSING_PANEL_EDITOR)&&e.getContextValue(FOCUSING_COMMON_DRAWINGS)&&!e.getContextValue(FOCUSING_SHAPE_TEXT_EDITOR)}const MoveDrawingDownShortcutItem={id:MoveDrawingsCommand.id,description:"sheets-drawing-ui.shortcut.drawing-move-down",group:"4_drawing-view",groupTitle:"sheets-drawing-ui.shortcut.drawing-view",binding:KeyCode.ARROW_DOWN,priority:100,preconditions:whenSheetDrawingFocused,staticParameters:{direction:Direction.DOWN}},MoveDrawingUpShortcutItem={id:MoveDrawingsCommand.id,description:"sheets-drawing-ui.shortcut.drawing-move-up",group:"4_drawing-view",groupTitle:"sheets-drawing-ui.shortcut.drawing-view",binding:KeyCode.ARROW_UP,priority:100,preconditions:whenSheetDrawingFocused,staticParameters:{direction:Direction.UP}},MoveDrawingLeftShortcutItem={id:MoveDrawingsCommand.id,description:"sheets-drawing-ui.shortcut.drawing-move-left",group:"4_drawing-view",groupTitle:"sheets-drawing-ui.shortcut.drawing-view",binding:KeyCode.ARROW_LEFT,priority:100,preconditions:whenSheetDrawingFocused,staticParameters:{direction:Direction.LEFT}},MoveDrawingRightShortcutItem={id:MoveDrawingsCommand.id,description:"sheets-drawing-ui.shortcut.drawing-move-right",group:"4_drawing-view",groupTitle:"sheets-drawing-ui.shortcut.drawing-view",binding:KeyCode.ARROW_RIGHT,priority:100,preconditions:whenSheetDrawingFocused,staticParameters:{direction:Direction.RIGHT}},DeleteDrawingsShortcutItem={id:DeleteDrawingsCommand.id,description:"sheets-drawing-ui.shortcut.drawing-delete",group:"4_drawing-view",groupTitle:"sheets-drawing-ui.shortcut.drawing-view",priority:100,preconditions:whenSheetDrawingFocused,binding:KeyCode.DELETE,mac:KeyCode.BACKSPACE};let SheetDrawingUIController=class extends Disposable{constructor(e,t,n,r){super(),this._componentManager=e,this._menuManagerService=t,this._commandService=n,this._shortcutService=r,this._init()}_initCustomComponents(){const e=this._componentManager;this.disposeWithMe(e.register(COMPONENT_SHEET_DRAWING_PANEL,SheetDrawingPanel)),this.disposeWithMe(e.register(BATCH_SAVE_IMAGES_DIALOG_ID,BatchSaveImagesDialog))}_initMenus(){this._menuManagerService.mergeMenu(menuSchema)}_initCommands(){[InsertFloatImageCommand,InsertCellImageCommand,SidebarSheetDrawingOperation,EditSheetDrawingOperation,GroupSheetDrawingCommand,UngroupSheetDrawingCommand,MoveDrawingsCommand,DeleteDrawingsCommand,SaveCellImagesCommand,FlipSheetDrawingCommand].forEach(e=>this.disposeWithMe(this._commandService.registerCommand(e)))}_initShortcuts(){[MoveDrawingDownShortcutItem,MoveDrawingUpShortcutItem,MoveDrawingLeftShortcutItem,MoveDrawingRightShortcutItem,DeleteDrawingsShortcutItem].forEach(e=>{this.disposeWithMe(this._shortcutService.registerShortcut(e))})}_init(){this._initCommands(),this._initCustomComponents(),this._initMenus(),this._initShortcuts()}};SheetDrawingUIController=__decorate([__decorateParam(0,Inject(ComponentManager)),__decorateParam(1,IMenuManagerService),__decorateParam(2,ICommandService),__decorateParam(3,IShortcutService)],SheetDrawingUIController);let DrawingPopupMenuController=class extends RxDisposable{constructor(e,t,n,r,i,o,a,s,d,c){super(),this._injector=e,this._localeService=t,this._drawingManagerService=n,this._canvasPopManagerService=r,this._renderManagerService=i,this._univerInstanceService=o,this._messageService=a,this._contextService=s,this._ioService=d,this._commandService=c,_defineProperty(this,"_initImagePopupMenu",new Set),this._init()}_init(){this._univerInstanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_SHEET).subscribe(e=>this._create(e)),this._univerInstanceService.getTypeOfUnitDisposed$(UniverInstanceType.UNIVER_SHEET).subscribe(e=>this._dispose(e)),this._univerInstanceService.getAllUnitsForType(UniverInstanceType.UNIVER_SHEET).forEach(e=>this._create(e)),this._setupLoadingStatus()}_setupLoadingStatus(){let e;this.disposeWithMe(this._ioService.change$.subscribe(t=>{t>0&&!e?e=this._messageService.show({id:"image-upload-loading",type:MessageType.Loading,content:`${this._localeService.t("sheets-ui.uploadLoading.loading")}: ${t}`,duration:0}):0===t&&(null==e||e.dispose(),e=void 0)}))}_dispose(e){super.dispose();const t=e.getUnitId();this._renderManagerService.removeRender(t),this._initImagePopupMenu.delete(t)}_create(e){if(!e)return;const t=e.getUnitId();this._renderManagerService.has(t)&&!this._initImagePopupMenu.has(t)&&(this._popupMenuListener(t),this._initImagePopupMenu.add(t))}_hasCropObject(e){const t=e.getAllObjectsByOrder();for(const e of t)if(e instanceof ImageCropperObject)return!0;return!1}_popupMenuListener(e){var t;const n=null===(t=this._renderManagerService.getRenderById(e))||void 0===t?void 0:t.scene;if(!n)return;const r=n.getTransformerByCreate();if(!r)return;let i;this.disposeWithMe(r.createControl$.subscribe(()=>{if(this._contextService.setContextValue(FOCUSING_COMMON_DRAWINGS,!0),this._hasCropObject(n))return;const e=r.getSelectedObjectMap();if(e.size>1)return void(null==i||i.dispose());const t=e.values().next().value;if(!t)return;const o=t.oKey,a=this._drawingManagerService.getDrawingOKey(o);if(!a)return;const{unitId:s,subUnitId:d,drawingId:c,drawingType:l}=a,u=a.data;if(u&&u.disablePopup)return;null==i||i.dispose();const g=this._canvasPopManagerService.getFeatureMenu(s,d,c,l);i=this.disposeWithMe(this._canvasPopManagerService.attachPopupToObject(t,{componentKey:COMPONENT_IMAGE_POPUP_MENU,direction:"horizontal",offset:[2,0],extraProps:{menuItems:g||this._getImageMenuItems(s,d,c,l)}}))})),this.disposeWithMe(r.clearControl$.subscribe(()=>{null==i||i.dispose(),this._contextService.setContextValue(FOCUSING_COMMON_DRAWINGS,!1),this._commandService.syncExecuteCommand(SetDrawingSelectedOperation.id,[])})),this.disposeWithMe(this._contextService.contextChanged$.subscribe(e=>{!1===e[FOCUSING_COMMON_DRAWINGS]&&(null==i||i.dispose())})),this.disposeWithMe(r.changing$.subscribe(()=>{null==i||i.dispose()}))}_getImageMenuItems(e,t,n,r){return[{label:"sheets-drawing-ui.image-popup.edit",index:0,commandId:EditSheetDrawingOperation.id,commandParams:{unitId:e,subUnitId:t,drawingId:n},disable:r===DrawingTypeEnum.DRAWING_DOM},{label:"sheets-drawing-ui.image-popup.delete",index:1,commandId:RemoveSheetDrawingCommand.id,commandParams:{unitId:e,drawings:[{unitId:e,subUnitId:t,drawingId:n}]},disable:!1},{label:"sheets-drawing-ui.image-popup.crop",index:2,commandId:OpenImageCropOperation.id,commandParams:{unitId:e,subUnitId:t,drawingId:n},disable:r===DrawingTypeEnum.DRAWING_DOM},{label:"sheets-drawing-ui.image-popup.flipH",index:2,commandId:FlipSheetDrawingCommand.id,commandParams:{unitId:e,flipH:!0,drawings:[{unitId:e,subUnitId:t,drawingId:n}]},disable:r===DrawingTypeEnum.DRAWING_DOM},{label:"sheets-drawing-ui.image-popup.flipV",index:2,commandId:FlipSheetDrawingCommand.id,commandParams:{unitId:e,flipV:!0,drawings:[{unitId:e,subUnitId:t,drawingId:n}]},disable:r===DrawingTypeEnum.DRAWING_DOM},{label:"sheets-drawing-ui.image-popup.reset",index:3,commandId:ImageResetSizeOperation.id,commandParams:[{unitId:e,subUnitId:t,drawingId:n}],disable:r===DrawingTypeEnum.DRAWING_DOM}]}};DrawingPopupMenuController=__decorate([__decorateParam(0,Inject(Injector)),__decorateParam(1,Inject(LocaleService)),__decorateParam(2,IDrawingManagerService),__decorateParam(3,Inject(SheetCanvasPopManagerService)),__decorateParam(4,IRenderManagerService),__decorateParam(5,IUniverInstanceService),__decorateParam(6,IMessageService),__decorateParam(7,IContextService),__decorateParam(8,IImageIoService),__decorateParam(9,ICommandService)],DrawingPopupMenuController);let UniverSheetsDrawingUIPlugin=class extends Plugin{constructor(e=defaultPluginConfig,t,n,r){super(),this._config=e,this._injector=t,this._renderManagerService=n,this._configService=r;const{menu:i,...o}=merge({},defaultPluginConfig,this._config);i&&this._configService.setConfig("menu",i,{merge:!0}),this._configService.setConfig("sheets-drawing-ui.config",o)}onStarting(){registerDependencies(this._injector,[[SheetCanvasFloatDomManagerService],[SheetDrawingUIController],[DrawingPopupMenuController],[SheetDrawingPrintingController],[SheetDrawingPermissionController],[SheetsDrawingCopyPasteController],[SheetsDrawingGroupCopyPasteController],[SheetCellImageController],[SheetCellImageAutofillController],[SheetCellImageCopyPasteController],[IBatchSaveImagesService,{useClass:BatchSaveImagesService}],[DrawingContextMenuController]]),touchDependencies(this._injector,[[SheetCanvasFloatDomManagerService]])}onReady(){touchDependencies(this._injector,[[SheetsDrawingCopyPasteController],[SheetCellImageCopyPasteController],[SheetsDrawingGroupCopyPasteController]])}onRendered(){this._registerRenderModules(),touchDependencies(this._injector,[[SheetDrawingPermissionController],[SheetDrawingPrintingController],[SheetDrawingUIController],[SheetCellImageController],[SheetCellImageAutofillController]])}onSteady(){this._injector.get(DrawingPopupMenuController),this._injector.get(DrawingContextMenuController)}_registerRenderModules(){[[SheetDrawingUpdateController],[SheetDrawingTransformAffectedController],[SheetsDrawingRenderController],[SheetCellImageHoverRenderController]].forEach(e=>{this.disposeWithMe(this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET,e))})}};_defineProperty(UniverSheetsDrawingUIPlugin,"type",UniverInstanceType.UNIVER_SHEET),_defineProperty(UniverSheetsDrawingUIPlugin,"pluginName","SHEET_IMAGE_UI_PLUGIN"),_defineProperty(UniverSheetsDrawingUIPlugin,"packageName",name),_defineProperty(UniverSheetsDrawingUIPlugin,"version",version),UniverSheetsDrawingUIPlugin=__decorate([DependentOn(UniverDrawingPlugin,UniverDocsDrawingPlugin,UniverDrawingUIPlugin,UniverSheetsDrawingPlugin),__decorateParam(1,Inject(Injector)),__decorateParam(2,IRenderManagerService),__decorateParam(3,IConfigService)],UniverSheetsDrawingUIPlugin);export{BatchSaveImagesService,DeleteDrawingsCommand,EditSheetDrawingOperation,FileNamePart,GroupSheetDrawingCommand,IBatchSaveImagesService,InsertFloatImageCommand,MoveDrawingsCommand,SHEETS_IMAGE_MENU_ID,SHEET_FLOAT_DOM_PREFIX,SaveCellImagesCommand,SheetCanvasFloatDomManagerService,SheetDrawingAnchor,SheetDrawingUpdateController,SheetsDrawingGroupCopyPasteController,SidebarSheetDrawingOperation,UngroupSheetDrawingCommand,UniverSheetsDrawingUIPlugin,calcSheetFloatDomPosition};
//# sourceMappingURL=/sm/70a443fe71c93577f2943c01dfd908449a6388e3bf69a6e02e568c9d5fcaee1c.map