/**
 * Minified by jsDelivr using Terser v5.48.0.
 * Original file: /npm/@univerjs/docs-drawing-ui@1.0.3/lib/es/index.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
import{AlignTypeH,AlignTypeV,BooleanNumber,COLORS,CommandType,DOC_DRAWING_PRINTING_COMPONENT_KEY,DependentOn,Direction,Disposable,DisposableCollection,DocumentFlavor,DrawingTypeEnum,FOCUSING_COMMON_DRAWINGS,FOCUSING_DOC,FOCUSING_UNIVER_EDITOR,ICommandService,IConfigService,IContextService,IImageIoService,IPermissionService,IUniverInstanceService,ImageSourceType,ImageUploadStatusType,Inject,Injector,JSON1,JSONX,LifecycleService,LifecycleStages,LocaleService,ObjectRelativeFromH,ObjectRelativeFromV,Plugin,PositionedObjectLayoutType,RedoCommand,RxDisposable,TextX,TextXActionType,Tools,UndoCommand,UniverInstanceType,WrapTextType,fromEventSubject,generateRandomId,getRichTextEditPath,isInternalEditorID,merge,throttle,toDisposable}from"@univerjs/core";import{IDocDrawingAdapterService,IDocDrawingService,InsertDocDrawingCommand,RemoveDocDrawingCommand,SetDocDrawingArrangeCommand,TextWrappingStyle,UniverDocsDrawingPlugin,UpdateDocDrawingWrappingStyleCommand,UpdateDrawingDocTransformCommand,collectDocDrawings,findDocDrawing,getDocDrawingRenderOrder}from"@univerjs/docs-drawing";import{DOC_CONTENT_INSERT_MENU_ID,DOC_PARAGRAPH_T_INSERT_BELOW_MENU_ID,DOC_PARAGRAPH_T_INSERT_MENU_ID,DocCanvasPopManagerService,DocPrintInterceptorService,DocSelectionRenderService,EMPTY_PARAGRAPH_MENU_ID,IEditorService,INSERT_BELLOW_MENU_ID,MOBILE_DOC_ELEMENT_MENU,NodePositionConvertToCursor,SetDocZoomRatioOperation,TEXT_RANGE_LAYER_INDEX,UniverDocsMobileUIPlugin,UniverDocsUIPlugin,VIEWPORT_KEY,getAnchorBounding,getOneTextSelectionRange,neoGetDocObject}from"@univerjs/docs-ui";import{CURSOR_TYPE,DocumentEditArea,DocumentSkeletonPageType,Documents,IRenderManagerService,Liquid,PageLayoutType,Rect,TRANSFORM_CHANGE_OBSERVABLE_TYPE,UniverRenderEnginePlugin,Vector2,getColor,getCurrentTypeOfRenderer,getDocsTableRenderViewport,getTableIdAndSliceIndex}from"@univerjs/engine-render";import{DocSelectionManagerService,DocSkeletonManagerService,RichTextEditingMutation,UniverDocsPlugin,buildDocTransform,canEditDocumentTargets,docDrawingPositionToTransform,getDocumentDrawingSegmentId,getDocumentEditTargetObjectIds,getDocumentEntityParentPermissionObjectIds,getDocumentEntityPermissionObjectId,isSheetLikeDocsCustomBlockChildType}from"@univerjs/docs";import{Checkbox,InputNumber,MessageType,MobileActionRow,Radio,RadioGroup,Select,clsx,render,unmount}from"@univerjs/design";import{DRAWING_IMAGE_ALLOW_IMAGE_LIST,DRAWING_IMAGE_COUNT_LIMIT,DRAWING_IMAGE_HEIGHT_LIMIT,DRAWING_IMAGE_WIDTH_LIMIT,IDrawingManagerService,UniverDrawingPlugin,getDrawingImageAllowSize,getDrawingShapeKeyByDrawingSearch,getImageSize}from"@univerjs/drawing";import{CanvasFloatDomService,ComponentManager,ContextMenuGroup,ContextMenuPosition,FloatingObjectToolbarPosition,IContextMenuService,ILocalFileService,IMenuManagerService,IMessageService,IShortcutService,ISidebarService,KeyCode,MenuItemType,PrintFloatDomSingle,RibbonInsertGroup,connectInjector,getMenuHiddenObservable,useDependency,useObservable}from"@univerjs/ui";import{BehaviorSubject,EMPTY,Observable,animationFrames,debounceTime,filter,map,merge as merge$1,of,startWith,switchMap,take,takeUntil}from"rxjs";import{COMPONENT_IMAGE_POPUP_MENU,COMPONENT_MOBILE_IMAGE_POPUP_MENU,DrawingCommonPanel,DrawingRenderService,ImageCropperObject,ImageResetSizeOperation,OpenImageCropOperation,UniverDrawingMobileUIPlugin,UniverDrawingUIPlugin}from"@univerjs/drawing-ui";import{useEffect,useMemo,useState}from"react";import{jsx,jsxs}from"react/jsx-runtime";import{CheckMarkIcon}from"@univerjs/icons";const DeleteDocDrawingsCommand={id:"doc.command.delete-drawing",type:CommandType.COMMAND,handler:async e=>{var t;const n=e.get(ICommandService),i=e.get(IDocDrawingService).getFocusDrawings();if(0===i.length)return!1;const{unitId:r}=i[0],o=null===(t=e.get(IRenderManagerService).getRenderUnitById(r))||void 0===t?void 0:t.with(DocSelectionRenderService);null==o||o.focus();const a=i.map(e=>{const{unitId:t,subUnitId:n,drawingId:i,drawingType:r}=e;return{unitId:t,subUnitId:n,drawingId:i,drawingType:r}}),s=await n.executeCommand(RemoveDocDrawingCommand.id,{unitId:r,drawings:a});return s&&(null==o||o.focus()),s}};function findAnchor(e,t){const n=e.getSnapshot(),i=[["",n.body],...Object.entries(n.headers??{}).map(([e,t])=>[e,t.body]),...Object.entries(n.footers??{}).map(([e,t])=>[e,t.body]),...Object.entries(n.notes??{}).map(([e,t])=>[e,t.body])];for(const[e,n]of i){var r;const i=null==n||null===(r=n.customBlocks)||void 0===r?void 0:r.find(e=>e.blockId===t);if(i)return{segmentId:e,index:i.startIndex}}}function docTransformFromScene(e,t,n){const{positionH:i,positionV:r}=t.docTransform;return{size:{width:e.width??0,height:e.height??0},positionH:{relativeFrom:i.relativeFrom,posOffset:(i.posOffset??0)+(e.left??0)-(n.left??0)},positionV:{relativeFrom:r.relativeFrom,posOffset:(r.posOffset??0)+(e.top??0)-(n.top??0)},angle:e.angle??0,flipX:e.flipX,flipY:e.flipY}}function ungroupDrawings({parent:e,children:t},n,i,{changes:r,replacements:o}){const a=i[0],s=n[e.drawingId],d=new Set(t.map(e=>e.drawingId));if(!s||s.groupId||s.drawingType!==DrawingTypeEnum.DRAWING_GROUP||Object.values(n).some(t=>t.groupId===e.drawingId&&!d.has(t.drawingId)))return!1;o.set(a.index,t.map(e=>e.drawingId)),r.set(e.drawingId,void 0);for(const i of t){if(!i.transform||n[i.drawingId].groupId!==e.drawingId)return!1;const t={...n[i.drawingId]};delete t.groupId,t.layoutType=PositionedObjectLayoutType.WRAP_NONE,t.behindDoc=s.behindDoc,t.docTransform=docTransformFromScene(i.transform,s,e.transform),r.set(i.drawingId,t)}return!0}function groupDrawings({parent:e,children:t},n,i,{changes:r,replacements:o}){if(t.length<2||n[e.drawingId]||t.some(e=>n[e.drawingId].groupId||!e.transform))return!1;const a=Math.min(...i.map(e=>e.index)),s=t[i.findIndex(e=>e.index===a)],d=n[s.drawingId],c=e.transform,l={...e,drawingType:DrawingTypeEnum.DRAWING_GROUP,layoutType:d.layoutType,behindDoc:d.behindDoc,layoutInCell:d.layoutInCell,allowOverlap:d.allowOverlap,wrapText:d.wrapText,distL:d.distL,distR:d.distR,distT:d.distT,distB:d.distB,docTransform:docTransformFromScene(c,d,s.transform),groupBaseBound:{left:0,top:0,width:c.width??0,height:c.height??0}};r.set(e.drawingId,l);for(let s=0;s<t.length;s++){const d=t[s];o.set(i[s].index,i[s].index===a?[e.drawingId]:[]);const g=docTransformFromScene(d.transform,l,c);g.positionH={relativeFrom:ObjectRelativeFromH.PAGE,posOffset:(d.transform.left??0)-(c.left??0)},g.positionV={relativeFrom:ObjectRelativeFromV.PAGE,posOffset:(d.transform.top??0)-(c.top??0)},r.set(d.drawingId,{...n[d.drawingId],groupId:e.drawingId,docTransform:g})}return!0}function buildDrawingChanges(e,t,n){const i=JSONX.getInstance(),r=[];for(const[o,a]of n){const n=e[o],s=[...t,"drawings",o];if(a)if(n)for(const e of["groupId","docTransform","layoutType","behindDoc"])a[e]!==n[e]&&(void 0===a[e]?r.push(i.removeOp([...s,e],n[e])):void 0===n[e]?r.push(i.insertOp([...s,e],a[e])):r.push(i.replaceOp([...s,e],n[e],a[e])));else r.push(i.insertOp(s,a));else r.push(i.removeOp(s,n))}return r}function buildGroupActions(e,t,n,i,{changes:r,replacements:o}){var a,s;const d=e.getSnapshot(),{drawings:c}=collectDocDrawings(d),l=(null===(a=d.notes)||void 0===a?void 0:a[t])??d,g=(null===(s=d.notes)||void 0===s?void 0:s[t])?["notes",t]:[],u=new TextX;let p=0;for(const[e,t]of[...o].sort(([e],[t])=>e-t))e>p&&u.push({t:TextXActionType.RETAIN,len:e-p}),u.push({t:TextXActionType.DELETE,len:1}),t.length>0&&u.push({t:TextXActionType.INSERT,len:t.length,body:{dataStream:"\b".repeat(t.length),customBlocks:t.map((e,t)=>({blockId:e,startIndex:t}))}}),p=e+1;const h=JSONX.getInstance(),m=[h.editOp(u.serialize(),getRichTextEditPath(e,t))];m.push(...buildDrawingChanges(c,g,r));const v=l.drawingsOrder??Object.keys(l.drawings??{}),f=v.filter(e=>!r.has(e)||r.get(e));for(const{parent:e,children:t}of n)i||f.splice(Math.max(0,f.indexOf(t[0].drawingId)),0,e.drawingId);return m.push(l.drawingsOrder?h.replaceOp([...g,"drawingsOrder"],v,f):h.insertOp([...g,"drawingsOrder"],f)),m}function changeDocDrawingGroups(e,t,n){if(!(null==t?void 0:t.length))return!1;const i=t[0].parent.unitId,r=e.get(IUniverInstanceService).getUnit(i,UniverInstanceType.UNIVER_DOC);if(!r||t.some(({parent:e,children:t})=>e.unitId!==i||t.some(e=>e.unitId!==i)))return!1;const o=r.getSnapshot(),{drawings:a}=collectDocDrawings(o),s=new Map,d=new Map;let c;for(const{parent:e,children:i}of t){const t=(n?[e]:i).map(({drawingId:e})=>findAnchor(r,e));if(!i.length||t.some(e=>!e)||!e.transform)return!1;const o=t[0];if(c??=o.segmentId,t.some(e=>e.segmentId!==c)||i.some(e=>!a[e.drawingId]||s.has(e.drawingId)))return!1;if(!(n?ungroupDrawings({parent:e,children:i},a,t,{changes:s,replacements:d}):groupDrawings({parent:e,children:i},a,t,{changes:s,replacements:d})))return!1}const l=buildGroupActions(r,c,t,n,{changes:s,replacements:d});return Boolean(e.get(ICommandService).syncExecuteCommand(RichTextEditingMutation.id,{unitId:i,segmentId:c,actions:l.reduce((e,t)=>JSONX.compose(e,t),null),textRanges:[]}))}const GroupDocDrawingCommand={id:"doc.command.group-doc-image",type:CommandType.COMMAND,handler:(e,t)=>changeDocDrawingGroups(e,t,!1)},UngroupDocDrawingCommand={id:"doc.command.ungroup-doc-image",type:CommandType.COMMAND,handler:(e,t)=>changeDocDrawingGroups(e,t,!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 i=n.call(e,t||"default");if("object"!=_typeof(i))return i;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}var DocRefreshDrawingsService=class{constructor(){_defineProperty(this,"_refreshDrawings$",new BehaviorSubject(null)),_defineProperty(this,"refreshDrawings$",this._refreshDrawings$.asObservable())}refreshDrawings(e){this._refreshDrawings$.next(e)}};function getDocImageCropUpdates(e,t,n){const{drawingId:i,transform:r}=e;if((null==t?void 0:t.drawingType)!==DrawingTypeEnum.DRAWING_IMAGE||null==(null==n?void 0:n.transform))return[];const o=["prstGeom","adjustValues"].filter(t=>Object.prototype.hasOwnProperty.call(e,t)).map(t=>({drawingId:i,key:t,value:e[t]??null}));if(null==r||void 0===e.srcRect)return o;const a={...n.transform,...r};if(o.push({drawingId:i,key:"srcRect",value:e.srcRect}),null!=a.width&&null!=a.height&&o.push({drawingId:i,key:"size",value:{width:a.width,height:a.height}}),t.layoutType===PositionedObjectLayoutType.INLINE||n.isMultiTransform===BooleanNumber.TRUE)return o;const s=(a.left??0)-(n.transform.left??0),d=(a.top??0)-(n.transform.top??0),{positionH:c,positionV:l}=t.docTransform;return 0!==s&&null!=c.posOffset&&o.push({drawingId:i,key:"positionH",value:{relativeFrom:c.relativeFrom,posOffset:c.posOffset+s}}),0!==d&&null!=l.posOffset&&o.push({drawingId:i,key:"positionV",value:{relativeFrom:l.relativeFrom,posOffset:l.posOffset+d}}),o}function getDocMutationAffectedDrawingIds(e){if(!Array.isArray(e)||0===e.length)return null;const t=new Set;let n=!1,i=!1;try{const r=JSON1.type.readCursor(e);r.traverse(null,()=>{n=!0;const e=r.getPath(),o=String(e[0]),a="notes"===o?2:0;if("drawings"===e[a]){const n=e[a+1];"string"==typeof n&&n.length>0?t.add(n):i=!0}else("drawingsOrder"===e[a]||"notes"===o&&e.length<=2||e.includes("customBlocks"))&&(i=!0)})}catch{return null}return!n||i?null:t}function __decorateParam(e,t){return function(n,i){t(n,i,e)}}function __decorate(e,t,n,i){var r,o=arguments.length,a=o<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(t,n,a):r(t,n))||a);return o>3&&a&&Object.defineProperty(t,n,a),a}let DocDrawingUpdateRenderController=class extends Disposable{constructor(e,t,n,i,r,o,a,s,d,c,l,g,u,p){super(),this._context=e,this._commandService=t,this._docSelectionManagerService=n,this._renderManagerSrv=i,this._imageIoService=r,this._docDrawingService=o,this._drawingManagerService=a,this._permissionService=s,this._contextService=d,this._messageService=c,this._localeService=l,this._docSelectionRenderService=g,this._docRefreshDrawingsService=u,this._fileOpenerService=p,_defineProperty(this,"_editableTransformerConfigs",new WeakMap),_defineProperty(this,"_editableEventedStates",new WeakMap),_defineProperty(this,"_editStatusUpdateScheduled",!1),_defineProperty(this,"_pendingEditStatusDrawingIds",void 0),_defineProperty(this,"_lastEditStatusContextKey",null),this._updateOrderListener(),this._updateImageCropListener(),this._groupDrawingListener(),this._focusDrawingListener(),this._transformDrawingListener(),this._editAreaChangeListener();const h=e=>{const t=e.filter(e=>{var t;return e.unitId===(null===(t=this._context)||void 0===t?void 0:t.unitId)});if(t.length>0){const e=t.map(e=>e.drawingId).filter(e=>"string"==typeof e&&e.length>0);this._scheduleDrawingsEditStatusUpdate(e.length===t.length?new Set(e):void 0)}};this.disposeWithMe(this._drawingManagerService.add$.subscribe(h)),this.disposeWithMe(this._drawingManagerService.update$.subscribe(h)),this.disposeWithMe(this._permissionService.permissionPointUpdate$.subscribe(()=>{this._updateDrawingsEditStatus(void 0,!0)}))}dispose(){super.dispose(),delete this._context}async insertDocImage(){const e=this._getCurrentImageInsertPosition(),t=this._getCurrentImageInsertTextRange();if(!this._canInsertDocImage(t))return!1;const n=await this._fileOpenerService.openFile({multiple:!0,accept:DRAWING_IMAGE_ALLOW_IMAGE_LIST.map(e=>`.${e.replace("image/","")}`).join(",")});if(this._disposed||!this._canInsertDocImage(t))return!1;const i=n.length;return i>DRAWING_IMAGE_COUNT_LIMIT?(this._messageService.show({type:MessageType.Error,content:this._localeService.t("docs-drawing-ui.update-status.exceedMaxCount",String(DRAWING_IMAGE_COUNT_LIMIT))}),!1):0!==i&&await this._insertFloatImages(n,e,t)}async _insertFloatImages(e,t,n){let i=[];try{i=await Promise.all(e.map(e=>this._imageIoService.saveImage(e)))}catch(e){let t="";switch(e.message){case ImageUploadStatusType.ERROR_EXCEED_SIZE:t=this._localeService.t("docs-drawing-ui.update-status.exceedMaxSize",String(getDrawingImageAllowSize()/1048576));break;case ImageUploadStatusType.ERROR_IMAGE_TYPE:t=this._localeService.t("docs-drawing-ui.update-status.invalidImageType");break;case ImageUploadStatusType.ERROR_IMAGE:t=this._localeService.t("docs-drawing-ui.update-status.invalidImage")}this._messageService.show({type:MessageType.Error,content:t})}if(this._disposed||0===i.length||!this._canInsertDocImage(n))return!1;const{unitId:r}=this._context,o=[];for(const e of i){if(null==e)continue;const{imageId:i,imageSourceType:a,source:s,base64Cache:d}=e,{width:c,height:l,image:g}=await getImageSize(d||"");if(this._disposed||!this._canInsertDocImage(n))return!1;this._imageIoService.addImageSourceCache(i,a,g);let u=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;u=Math.min(e,t)}const p=t??this._getCurrentImageInsertPosition(),h=this._getImagePosition(c*u,l*u,p);if(null==h)return!1;const m=docDrawingPositionToTransform(h);null!=m&&null!=p&&(m.top=p.top);const v={unitId:r,subUnitId:r,drawingId:i,drawingType:DrawingTypeEnum.DRAWING_IMAGE,imageSourceType:a,source:s,transform:m,docTransform:h,behindDoc:BooleanNumber.FALSE,title:"",description:"",layoutType:PositionedObjectLayoutType.INLINE,wrapText:WrapTextType.BOTH_SIDES,distB:0,distL:0,distR:0,distT:0};this._isInsertInHeaderFooter()&&(v.isMultiTransform=BooleanNumber.TRUE,v.transforms=v.transform?[v.transform]:null),o.push(v)}return await this._commandService.executeCommand(InsertDocDrawingCommand.id,{unitId:r,drawings:o,textRange:n??void 0})}_isInsertInHeaderFooter(){var e;const{unitId:t}=this._context,n=null===(e=this._renderManagerSrv.getRenderUnitById(t))||void 0===e?void 0:e.with(DocSkeletonManagerService).getViewModel(),i=null==n?void 0:n.getEditArea();return i===DocumentEditArea.HEADER||i===DocumentEditArea.FOOTER}_getImagePosition(e,t,n){const i=n??this._getCurrentImageInsertPosition()??{left:0,top:0};return buildDocTransform(e,t,{left:i.left})}_getCurrentImageInsertPosition(){var e;const t=null===(e=this._docSelectionRenderService.getActiveTextRange())||void 0===e?void 0:e.getAbsolutePosition();return null==t?null:{left:t.left,top:t.top}}_getCurrentImageInsertTextRange(){return this._docSelectionRenderService.getAllTextRanges().find(e=>e.isActive)??this._docSelectionManagerService.getActiveTextRange()}_updateOrderListener(){this.disposeWithMe(this._drawingManagerService.featurePluginOrderUpdate$.subscribe(e=>{const{unitId:t,subUnitId:n,drawingIds:i,arrangeType:r}=e;this._commandService.executeCommand(SetDocDrawingArrangeCommand.id,{unitId:t,subUnitId:n,drawingIds:i,arrangeType:r})}))}_updateImageCropListener(){this.disposeWithMe(this._drawingManagerService.featurePluginUpdate$.subscribe(e=>{const t=e.flatMap(e=>this._getImageCropUpdates(e));if(t.length>0){const{unitId:e}=this._context;this._commandService.executeCommand(UpdateDrawingDocTransformCommand.id,{unitId:e,subUnitId:e,drawings:t})}}))}_getImageCropUpdates(e){const{unitId:t,subUnitId:n,drawingId:i}=e;return[t,n].some(e=>e!==this._context.unitId)?[]:getDocImageCropUpdates(e,this._getDocDrawing(i),this._drawingManagerService.getDrawingByParam({unitId:t,subUnitId:n,drawingId:i})??void 0)}_getDocDrawing(e){var t;return null===(t=findDocDrawing(this._context.unit.getSnapshot(),e))||void 0===t?void 0:t.drawing}_groupDrawingListener(){this.disposeWithMe(this._drawingManagerService.featurePluginGroupUpdate$.subscribe(e=>{this._commandService.executeCommand(GroupDocDrawingCommand.id,e)})),this.disposeWithMe(this._drawingManagerService.featurePluginUngroupUpdate$.subscribe(e=>{this._commandService.executeCommand(UngroupDocDrawingCommand.id,e)}))}_getCurrentSceneAndTransformer(){const{scene:e,mainComponent:t}=this._context;if(null==e||null==t)return;const n=e.getTransformerByCreate(),{docsLeft:i,docsTop:r}=t.getOffsetConfig();return{scene:e,transformer:n,docsLeft:i,docsTop:r}}_getTransformerInteractionOptions(){return{moveOnlyWhenSelected:!1}}_isDocumentInteractionFocusing(e){return this._docSelectionRenderService.isFocusing||this._drawingManagerService.getFocusDrawings().some(t=>t.unitId===e)}_transformDrawingListener(){const e=this._getCurrentSceneAndTransformer();if(!e||!e.transformer)throw new Error("transformer is not init");e.transformer.resetProps(this._getTransformerInteractionOptions()),this.disposeWithMe(e.transformer.changeEnd$.pipe(debounceTime(30)).subscribe(()=>{this._docSelectionManagerService.refreshSelection()}))}_focusDrawingListener(){this.disposeWithMe(this._drawingManagerService.focus$.subscribe(e=>{const{transformer:t,docsLeft:n,docsTop:i}=this._getCurrentSceneAndTransformer()??{};if(null==e||0===e.length)this._contextService.setContextValue(FOCUSING_COMMON_DRAWINGS,!1),this._docDrawingService.focusDrawing([]),t&&t.resetProps({zeroTop:0,zeroLeft:0});else{this._contextService.setContextValue(FOCUSING_COMMON_DRAWINGS,!0),this._docDrawingService.focusDrawing(e),this._setDrawingSelections(e);const r=this._docSelectionRenderService.getSegment(),o=getDocumentDrawingSegmentId(this._context.unit,e[0].drawingId);r!==o&&this._docSelectionRenderService.setSegment(o),t&&t.resetProps({zeroTop:i,zeroLeft:n})}this._updateDrawingsEditStatus()}))}_updateDrawingsEditStatus(e,t=!1){var n;if(!this._context)return;const{unit:i,scene:r,unitId:o}=this._context,a=null===(n=this._renderManagerSrv.getRenderUnitById(o))||void 0===n?void 0:n.with(DocSkeletonManagerService).getViewModel();if(null==a||null==i)return;const s=i.getSnapshot(),{drawings:d}=collectDocDrawings(s),c=a.getEditArea()===DocumentEditArea.BODY,l=this._isDocumentInteractionFocusing(o),g=`${a.getEditArea()}:${l}`,u=null!=e&&g===this._lastEditStatusContextKey?e:void 0;if(null==u){if(!t&&g===this._lastEditStatusContextKey)return;this._lastEditStatusContextKey=g}const p=new Set,h=this._indexDrawingShapes(r.getAllObjects(),o);for(const e of Object.keys(d)){const t=d[e];if(null!=u&&!u.has(t.drawingId))continue;const n=getDocumentDrawingSegmentId(i,t.drawingId),a=canEditDocumentTargets(this._permissionService,o,[...getDocumentEntityParentPermissionObjectIds(i,n,"drawing",t.drawingId),getDocumentEntityPermissionObjectId(n,"drawing",t.drawingId)]);this._recordReadOnlyDrawing(p,t.drawingId,a);const s=h.get(t.drawingId)??[];if(s.length)for(const e of s){r.detachTransformerFrom(e),this._setTransformerEditable(e,a);try{const n=l&&t.isMultiTransform!==BooleanNumber.TRUE;e.setOpacity(n?.5:1)}catch{}if(l&&(c&&t.isMultiTransform!==BooleanNumber.TRUE||!c&&t.isMultiTransform===BooleanNumber.TRUE)){this._attachTransformerIfEditable(e,a,t.allowTransform);try{e.setOpacity(1)}catch{}}}}this._clearReadOnlyDrawingFocus(o,p)}_indexDrawingShapes(e,t){const n=getDrawingShapeKeyByDrawingSearch({unitId:t,subUnitId:t,drawingId:""}),i=new Map;for(const t of e){if(!t.oKey.startsWith(n))continue;const e=t.oKey.slice(n.length).split("#-#",1)[0];if(!e)continue;const r=i.get(e)??[];r.push(t),i.set(e,r)}return i}_recordReadOnlyDrawing(e,t,n){n||e.add(t)}_attachTransformerIfEditable(e,t,n){t&&!1!==n&&this._context.scene.attachTransformerTo(e)}_clearReadOnlyDrawingFocus(e,t){if(0===t.size)return;const n=this._drawingManagerService.getFocusDrawings(),i=n.filter(n=>n.unitId!==e||!t.has(n.drawingId));i.length!==n.length&&this._drawingManagerService.focusDrawing(i)}_setTransformerEditable(e,t){var n;if(t){const t=this._editableTransformerConfigs.get(e);t&&(e.transformerConfig=t,this._editableTransformerConfigs.delete(e));const n=this._editableEventedStates.get(e);return void(void 0!==n&&(e.evented=n,this._editableEventedStates.delete(e)))}this._editableTransformerConfigs.has(e)||this._editableTransformerConfigs.set(e,e.transformerConfig),this._editableEventedStates.has(e)||this._editableEventedStates.set(e,e.evented),e.evented=!1,null===(n=this._context.scene.getTransformer())||void 0===n||n.clearControlByIds([e.oKey]),e.transformerConfig={...e.transformerConfig,moveEnabled:!1,resizeEnabled:!1,rotateEnabled:!1}}_scheduleDrawingsEditStatusUpdate(e){null==e?(this._pendingEditStatusDrawingIds=null,this._lastEditStatusContextKey=null):null!==this._pendingEditStatusDrawingIds&&(this._pendingEditStatusDrawingIds??=new Set,e.forEach(e=>{var t;return null===(t=this._pendingEditStatusDrawingIds)||void 0===t?void 0:t.add(e)})),this._editStatusUpdateScheduled||(this._editStatusUpdateScheduled=!0,queueMicrotask(()=>{if(this._editStatusUpdateScheduled=!1,!this._disposed){const e=this._pendingEditStatusDrawingIds;this._pendingEditStatusDrawingIds=void 0,this._updateDrawingsEditStatus(e??void 0)}}))}_canInsertDocImage(e){const{unit:t,unitId:n}=this._context,i=null==(null==e?void 0:e.startOffset)||null==e.endOffset?[]:getDocumentEditTargetObjectIds(t,e.segmentId??"",e);return canEditDocumentTargets(this._permissionService,n,i)}_editAreaChangeListener(){var e;const{unitId:t}=this._context,n=null===(e=this._renderManagerSrv.getRenderUnitById(t))||void 0===e?void 0:e.with(DocSkeletonManagerService).getViewModel();null!=n&&(this._updateDrawingsEditStatus(),this.disposeWithMe(n.editAreaChange$.subscribe(()=>{this._updateDrawingsEditStatus()})),this.disposeWithMe(this._docSelectionRenderService.onFocus$.subscribe(()=>{this._updateDrawingsEditStatus()})),this.disposeWithMe(this._docSelectionRenderService.onBlur$.subscribe(()=>{this._updateDrawingsEditStatus()})),this.disposeWithMe(this._docRefreshDrawingsService.refreshDrawings$.subscribe(e=>{null!=e&&queueMicrotask(()=>{this._updateDrawingsEditStatus(void 0,!0)})})),this.disposeWithMe(this._commandService.onCommandExecuted(async e=>{if(e.id!==RichTextEditingMutation.id)return;const t=e.params;if((null==t?void 0:t.unitId)&&t.unitId!==this._context.unitId)return;const n=getDocMutationAffectedDrawingIds((null==t?void 0:t.actions)??null);0!==(null==n?void 0:n.size)&&this._scheduleDrawingsEditStatusUpdate(n??void 0)})))}_setDrawingSelections(e){const{unit:t}=this._context,n=e.flatMap(e=>{var n,i;const r=getDocumentDrawingSegmentId(t,e.drawingId),o=null===(n=t.getSelfOrHeaderFooterModel(r))||void 0===n?void 0:n.getBody(),a=null==o||null===(i=o.customBlocks)||void 0===i?void 0:i.find(t=>t.blockId===e.drawingId);return a?[{startOffset:a.startIndex,endOffset:a.startIndex+1,segmentId:r}]:[]});this._docSelectionManagerService.replaceDocRanges(n)}};DocDrawingUpdateRenderController=__decorate([__decorateParam(1,ICommandService),__decorateParam(2,Inject(DocSelectionManagerService)),__decorateParam(3,IRenderManagerService),__decorateParam(4,IImageIoService),__decorateParam(5,IDocDrawingService),__decorateParam(6,IDrawingManagerService),__decorateParam(7,IPermissionService),__decorateParam(8,IContextService),__decorateParam(9,IMessageService),__decorateParam(10,Inject(LocaleService)),__decorateParam(11,Inject(DocSelectionRenderService)),__decorateParam(12,Inject(DocRefreshDrawingsService)),__decorateParam(13,ILocalFileService)],DocDrawingUpdateRenderController);const InsertDocImageCommand={id:"doc.command.insert-float-image",type:CommandType.COMMAND,handler:e=>{var t;const n=e.get(IUniverInstanceService),i=e.get(IRenderManagerService);return(null===(t=getCurrentTypeOfRenderer(UniverInstanceType.UNIVER_DOC,n,i))||void 0===t?void 0:t.with(DocDrawingUpdateRenderController).insertDocImage())??!1}},DOC_SHAPE_FILL="#3A60F7",DOC_SHAPE_STROKE="#1D3EA6";function createShapeSvgSource(e,t,n){return`data:image/svg+xml;utf8,${encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${n}" viewBox="0 0 ${t} ${n}" fill="none">${"ellipse"===e?`<ellipse cx="${t/2}" cy="${n/2}" rx="${(t-8)/2}" ry="${(n-8)/2}" fill="#3A60F7" stroke="#1D3EA6" stroke-width="4" />`:`<rect x="4" y="4" width="${t-8}" height="${n-8}" rx="14" fill="#3A60F7" stroke="#1D3EA6" stroke-width="4" />`}</svg>`)}`}function createShapeInsertCommand(e,t,n,i){return{id:i,type:CommandType.COMMAND,handler:async i=>{var r;const o=i.get(ICommandService),a=null===(r=i.get(IUniverInstanceService).getCurrentUnitOfType(UniverInstanceType.UNIVER_DOC))||void 0===r?void 0:r.getUnitId();if(!a)return!1;const s=buildDocTransform(t,n);return o.executeCommand(InsertDocDrawingCommand.id,{unitId:a,drawings:[{unitId:a,subUnitId:a,drawingId:generateRandomId(6),drawingType:DrawingTypeEnum.DRAWING_IMAGE,imageSourceType:ImageSourceType.BASE64,source:createShapeSvgSource(e,t,n),transform:docDrawingPositionToTransform(s),docTransform:s,behindDoc:BooleanNumber.FALSE,title:"",description:"",layoutType:PositionedObjectLayoutType.INLINE,wrapText:WrapTextType.BOTH_SIDES,distB:0,distL:0,distR:0,distT:0}]})}}}const InsertDocRectangleShapeCommand=createShapeInsertCommand("rectangle",144,96,"doc.command.insert-float-shape.rectangle"),InsertDocEllipseShapeCommand=createShapeInsertCommand("ellipse",112,112,"doc.command.insert-float-shape.ellipse");function findDrawingAnchorInPage(e,t,n,i){const r=e.skeDrawings.get(t);if(r)return{skeDrawing:r,pageMarginTop:n,pageMarginLeft:i};for(const n of e.skeTables.values())for(const e of n.rows)for(const n of e.cells){const e=findDrawingAnchorInPage(n,t,n.marginTop,n.marginLeft);if(e)return e}return null}function resolveDrawingAnchorOffsets(e,t,n){const{skeDrawing:i,pageMarginTop:r,pageMarginLeft:o}=e;let a=i.aLeft,s=i.aTop;return t.relativeFrom===ObjectRelativeFromH.MARGIN?a-=o:t.relativeFrom===ObjectRelativeFromH.COLUMN&&(a-=i.columnLeft),n.relativeFrom===ObjectRelativeFromV.PAGE?s+=r:n.relativeFrom===ObjectRelativeFromV.LINE?s-=i.lineTop:n.relativeFrom===ObjectRelativeFromV.PARAGRAPH&&(s-=i.blockAnchorTop),{horizontal:a,vertical:s}}const MoveDocDrawingsCommand={id:"doc.command.move-drawing",type:CommandType.COMMAND,handler:(e,t)=>{var n;const i=e.get(ICommandService),r=e.get(IDocDrawingService),o=e.get(IUniverInstanceService),a=e.get(IRenderManagerService),{direction:s}=t,d=r.getFocusDrawings();if(0===d.length)return!1;const c=d[0].unitId,l=a.getRenderUnitById(c),g=null==l?void 0:l.scene;if(null==g)return!1;const u=g.getTransformerByCreate(),p=null==l||null===(n=l.with(DocSkeletonManagerService).getSkeleton())||void 0===n?void 0:n.getSkeletonData(),h=o.getUnit(c,UniverInstanceType.UNIVER_DOC),m=d.map(e=>{var t;const{drawingId:n}=e,i=null==h||null===(t=h.getSnapshot().drawings)||void 0===t?void 0:t[n];if(null==i||i.layoutType===PositionedObjectLayoutType.INLINE)return null;const{positionH:r,positionV:o}=i.docTransform,a=null==p?{anchor:null,previewOnly:!1}:findDrawingAnchor(p,n);if(a.previewOnly)return null;const{anchor:d}=a,c=null==d?{horizontal:r.posOffset??0,vertical:o.posOffset??0}:resolveDrawingAnchorOffsets(d,r,o),l={...null==r.relativeFrom?{}:{relativeFrom:r.relativeFrom},posOffset:c.horizontal},g={...null==o.relativeFrom?{}:{relativeFrom:o.relativeFrom},posOffset:c.vertical};return s===Direction.UP?g.posOffset=(g.posOffset??0)-2:s===Direction.DOWN?g.posOffset=(g.posOffset??0)+2:s===Direction.LEFT?l.posOffset=(l.posOffset??0)-2:s===Direction.RIGHT&&(l.posOffset=(l.posOffset??0)+2),{drawingId:n,key:s===Direction.UP||s===Direction.DOWN?"positionV":"positionH",value:s===Direction.UP||s===Direction.DOWN?g:l}}).filter(e=>null!=e);if(0===m.length)return!1;const v=i.syncExecuteCommand(UpdateDrawingDocTransformCommand.id,{unitId:c,subUnitId:c,drawings:m});return u.refreshControls(),Boolean(v)}};function findDrawingAnchor(e,t){let n=!1;for(const o of e.pages){var i,r;const a=findDrawingAnchorInPage(o,t,o.marginTop,o.marginLeft),s=null==o.headerId||null===(i=e.skeHeaders.get(o.headerId))||void 0===i?void 0:i.get(o.pageWidth),d=null==s?null:findDrawingAnchorInPage(s,t,s.marginTop,o.marginLeft),c=null==o.footerId||null===(r=e.skeFooters.get(o.footerId))||void 0===r?void 0:r.get(o.pageWidth),l=null==c?0:o.pageHeight-o.marginBottom+c.marginTop,g=null==c?null:findDrawingAnchorInPage(c,t,l,o.marginLeft),u=a??d??g;if(null!=u){if(!o.isLayoutPlaceholder&&!o.isMaterializationPlaceholder)return{anchor:u,previewOnly:!1};n=!0}}return{anchor:null,previewOnly:n}}const ClearDocDrawingTransformerOperation={id:"doc.operation.clear-drawing-transformer",type:CommandType.MUTATION,handler:(e,t)=>{const n=e.get(IRenderManagerService);return t.forEach(e=>{var t;null===(t=n.getRenderUnitById(e))||void 0===t||null===(t=t.scene.getTransformer())||void 0===t||t.debounceRefreshControls()}),!0}},COMPONENT_DOC_DRAWING_PANEL="COMPONENT_DOC_DRAWING_PANEL",SidebarDocDrawingOperation={id:"sidebar.operation.doc-image",type:CommandType.COMMAND,handler:async(e,t)=>{const n=e.get(ISidebarService),i=e.get(LocaleService),r=e.get(IDrawingManagerService);if("open"===t.value)n.open({header:{title:i.t("docs-drawing-ui.panel.title")},children:{label:COMPONENT_DOC_DRAWING_PANEL},onClose:()=>{r.focusDrawing(null)},width:360});else n.close();return!0}},EditDocDrawingOperation={id:"doc.operation.edit-doc-image",type:CommandType.OPERATION,handler:(e,t)=>{const n=e.get(IDrawingManagerService),i=e.get(ICommandService);return null!=t&&(n.focusDrawing([t]),i.executeCommand(SidebarDocDrawingOperation.id,{value:"open"}),!0)}};function calcDocFloatDomPositionByRect(e,t,n=1,i=0){const{top:r,left:o,bottom:a,right:s}=e,d=s-o,c=a-r,{viewportScrollX:l,viewportScrollY:g}=t.getViewport(VIEWPORT_KEY.VIEW_MAIN),{scaleX:u,scaleY:p}=t.getAncestorScale();return{startX:(o-l)*u,startY:(r-g)*p,endX:(o+d-l)*u,endY:(r+c-g)*p,width:d*u,height:c*p,rotate:i,absolute:{left:!1,top:!1},opacity:n??1}}function calcDocFloatDomPosition(e,t){const{top:n,left:i,width:r,height:o,angle:a,opacity:s}=e;return calcDocFloatDomPositionByRect({top:n,left:i,bottom:n+o,right:i+r},t.scene,s,a)}function mergeDocFloatDomRuntimeProps(e,t){const n=pickValidCustomBlockRenderViewport(t.customBlockRenderViewport);return n?{...e,customBlockRenderViewport:n}:e}function pickValidCustomBlockRenderViewport(e){const t={};isNonNegativeNumber(null==e?void 0:e.bleedLeft)&&(t.bleedLeft=e.bleedLeft),isPositiveNumber(null==e?void 0:e.bleedWidth)&&(t.bleedWidth=e.bleedWidth),isPositiveNumber(null==e?void 0:e.contentHeight)&&(t.contentHeight=e.contentHeight),isPositiveNumber(null==e?void 0:e.contentWidth)&&(t.contentWidth=e.contentWidth),isPositiveNumber(null==e?void 0:e.height)&&(t.height=e.height),isPositiveNumber(null==e?void 0:e.pageContentWidth)&&(t.pageContentWidth=e.pageContentWidth);const n=null==e?void 0:e.viewScale;return isPositiveNumber(n)&&(t.viewScale=n),isPositiveNumber(null==e?void 0:e.viewportHeight)&&(t.viewportHeight=e.viewportHeight),Object.keys(t).length?t:void 0}function isPositiveNumber(e){return"number"==typeof e&&Number.isFinite(e)&&e>0}function isNonNegativeNumber(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0}let DocFloatDomController=class extends Disposable{constructor(e,t,n,i,r,o,a){super(),this._renderManagerService=e,this._drawingManagerService=t,this._drawingRenderService=n,this._canvasFloatDomService=i,this._univerInstanceService=r,this._commandService=o,this._docRefreshDrawingsService=a,_defineProperty(this,"_domLayerInfoMap",new Map),_defineProperty(this,"_pendingRuntimeGeometry",new Map),_defineProperty(this,"_pendingRuntimeGeometryInsert",new Map),_defineProperty(this,"_pendingRuntimeGeometryRefresh",new Map),this._initialize()}dispose(){this._pendingRuntimeGeometry.clear(),this._pendingRuntimeGeometryInsert.clear();for(const e of this._pendingRuntimeGeometryRefresh.values())e.dispose();this._pendingRuntimeGeometryRefresh.clear(),super.dispose()}_initialize(){this._renderLifecycleListener(),this._drawingAddRemoveListener(),this._drawingRuntimePropsListener(),this._initScrollAndZoomEvent()}_renderLifecycleListener(){this.disposeWithMe(this._renderManagerService.disposed$.subscribe(e=>{this._disposePendingRuntimeGeometryRefresh(e)})),this.disposeWithMe(this._renderManagerService.created$.subscribe(e=>{this._hasPendingRuntimeGeometryForUnit(e.unitId)&&this._refreshDrawingsFromCurrentLayout(e.unitId)}))}_getSceneAndTransformerByDrawingSearch(e){if(null==e)return;const t=this._renderManagerService.getRenderUnitById(e);if(null==t)return null;const n=t.scene;return{scene:n,transformer:n.getTransformerByCreate(),renderUnit:t,canvas:t.engine.getCanvasElement()}}_drawingAddRemoveListener(){this.disposeWithMe(this._drawingManagerService.add$.subscribe(e=>{const t=[],n=new Set;for(const i of e)if(isEmbedFloatDomRuntimeParam(this._drawingManagerService.getDrawingByParam(i))&&null!=this._univerInstanceService.getUnit(i.unitId,UniverInstanceType.UNIVER_DOC)){if(this._pendingRuntimeGeometryInsert.has(i.drawingId))continue;this._pendingRuntimeGeometryInsert.set(i.drawingId,i),n.add(i.unitId),this._pendingRuntimeGeometry.has(i.drawingId)&&t.push(i)}else t.push(i);this._insertRects(t);for(const e of n)this._refreshDrawingsFromCurrentLayout(e)})),this.disposeWithMe(this._drawingManagerService.remove$.subscribe(e=>{e.forEach(e=>{this._removeDom(e.drawingId)})}))}_refreshDrawingsFromCurrentLayout(e){const t=this._renderManagerService.getRenderUnitById(e);if(null==t||t.type!==UniverInstanceType.UNIVER_DOC||t.isDisposed())return;const n=t.with(DocSkeletonManagerService).getSkeleton();if(null!=n){if(!this._pendingRuntimeGeometryRefresh.has(e)){const t=n.dirty$.subscribe(()=>{this._hasPendingRuntimeGeometryForUnit(e)?this._docRefreshDrawingsService.refreshDrawings(n):this._disposePendingRuntimeGeometryRefresh(e)});this._pendingRuntimeGeometryRefresh.set(e,toDisposable(()=>t.unsubscribe()))}this._docRefreshDrawingsService.refreshDrawings(n)}}_hasPendingRuntimeGeometryForUnit(e){for(const t of this._pendingRuntimeGeometryInsert.values())if(t.unitId===e)return!0;return!1}_disposePendingRuntimeGeometryRefresh(e){var t;null===(t=this._pendingRuntimeGeometryRefresh.get(e))||void 0===t||t.dispose(),this._pendingRuntimeGeometryRefresh.delete(e)}_insertRects(e){for(const n of e){const{unitId:e}=n;if(!this._univerInstanceService.getUnit(e,UniverInstanceType.UNIVER_DOC))continue;const i=this._getSceneAndTransformerByDrawingSearch(e);if(null==i)continue;const r=this._drawingManagerService.getDrawingByParam(n);if(null==r)continue;const o=isEmbedFloatDomRuntimeParam(r),a=this._pendingRuntimeGeometry.get(n.drawingId);if(o&&(null==a||this._pendingRuntimeGeometryInsert.get(n.drawingId)!==n))continue;const s=this._drawingRenderService.renderFloatDom(r,i.scene);if(null!=s&&0!==s.length){for(const n of s){var t;const s=a??r,d=pickValidCustomBlockRenderViewport(s.customBlockRenderViewport);syncRectWithRuntimeParam(n,s,d,void 0,o);const c=d||o?createTransformFromRect(n):void 0;this._addHoverForRect(n);const l=new DisposableCollection,g=calcDocFloatDomPosition(n,i.renderUnit),u=new BehaviorSubject(g),p=i.canvas,h=r.data,m={dispose:l,preserveRuntimeGeometry:o,rect:n,runtimeTransform:c,runtimeViewport:d,position$:u,unitId:e};this._canvasFloatDomService.addFloatDom({position$:u,id:r.drawingId,componentKey:r.componentKey,contentBox:isSheetLikeEmbedFloatDomRuntimeParam(r)?{contentInset:0,wrapperInset:0}:void 0,eventPassThrough:!o&&void 0,preserveOnFocusChange:o,onPointerDown:e=>{p.dispatchEvent(new PointerEvent(e.type,e))},onPointerMove:e=>{p.dispatchEvent(new PointerEvent(e.type,e))},onPointerUp:e=>{p.dispatchEvent(new PointerEvent(e.type,e))},onWheel:e=>{p.dispatchEvent(new WheelEvent(e.type,e))},data:h,props:mergeDocFloatDomRuntimeProps(void 0,r),unitId:e});const v=n.onTransformChange$.subscribeEvent(()=>{const e=calcDocFloatDomPosition(n,i.renderUnit);u.next(e)}),f=subscribeViewportScrollAfter(null===(t=i.scene.getViewport(VIEWPORT_KEY.VIEW_MAIN))||void 0===t?void 0:t.onScrollAfter$,()=>u.next(calcDocFloatDomPosition(n,i.renderUnit)));l.add(()=>{this._canvasFloatDomService.removeFloatDom(r.drawingId)}),v&&l.add(v),f&&l.add(f),this._domLayerInfoMap.set(r.drawingId,m)}this._pendingRuntimeGeometry.delete(n.drawingId),this._pendingRuntimeGeometryInsert.delete(n.drawingId),this._hasPendingRuntimeGeometryForUnit(e)||this._disposePendingRuntimeGeometryRefresh(e)}}}_drawingRuntimePropsListener(){this.disposeWithMe(this._drawingManagerService.refreshTransform$.subscribe(e=>{e.forEach(e=>{var t;const n=this._domLayerInfoMap.get(e.drawingId);if(!n){const t=this._pendingRuntimeGeometryInsert.get(e.drawingId),n=this._drawingManagerService.getDrawingByParam(e);if(null!=t||isEmbedFloatDomRuntimeParam(n)){if(!0===e.hidden)return;this._pendingRuntimeGeometry.set(e.drawingId,e),null!=t&&this._insertRects([t])}return}if(n.unitId!==e.unitId)return;if(n.preserveRuntimeGeometry&&!0===e.hidden)return;const i=e,r=pickValidCustomBlockRenderViewport(i.customBlockRenderViewport);if(r&&(n.runtimeViewport=r),syncRectWithRuntimeParam(n.rect,i,n.runtimeViewport,n.runtimeTransform,n.preserveRuntimeGeometry)){(r||n.preserveRuntimeGeometry)&&(n.runtimeTransform=createTransformFromRect(n.rect));const e=this._getSceneAndTransformerByDrawingSearch(n.unitId);e&&n.position$.next(calcDocFloatDomPosition(n.rect,e.renderUnit))}const o=null===(t=this._canvasFloatDomService.domLayers.find(([t])=>t===e.drawingId))||void 0===t?void 0:t[1].props;this._canvasFloatDomService.updateFloatDom(e.drawingId,{props:mergeDocFloatDomRuntimeProps(o,e)})})}))}_addHoverForRect(e){this.disposeWithMe(toDisposable(e.onPointerEnter$.subscribeEvent(()=>{e.cursor=CURSOR_TYPE.GRAB}))),this.disposeWithMe(toDisposable(e.onPointerLeave$.subscribeEvent(()=>{e.cursor=CURSOR_TYPE.DEFAULT})))}_removeDom(e){var t;const n=null===(t=this._pendingRuntimeGeometryInsert.get(e))||void 0===t?void 0:t.unitId;this._pendingRuntimeGeometry.delete(e),this._pendingRuntimeGeometryInsert.delete(e),null==n||this._hasPendingRuntimeGeometryForUnit(n)||this._disposePendingRuntimeGeometryRefresh(n);const i=this._domLayerInfoMap.get(e);if(!i)return;const{unitId:r}=i;this._domLayerInfoMap.delete(e),i.dispose.dispose();const o=this._getSceneAndTransformerByDrawingSearch(r);o&&o.scene.removeObject(i.rect)}_initScrollAndZoomEvent(){const e=e=>{const t=this._getSceneAndTransformerByDrawingSearch(e);t&&this._domLayerInfoMap.forEach(n=>{if(n.unitId!==e)return;const i=calcDocFloatDomPosition(n.rect,t.renderUnit);n.position$.next(i)})};this.disposeWithMe(this._univerInstanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_DOC).pipe(map(e=>{if(!e)return null;const t=e.getUnitId(),n=this._renderManagerService.getRenderUnitById(t);return n?{render:n,unitId:t}:null}),switchMap(e=>e?fromEventSubject(e.render.scene.getViewport(VIEWPORT_KEY.VIEW_MAIN).onScrollAfter$).pipe(map(()=>({unitId:e.unitId}))):of(null))).subscribe(t=>{if(!t)return;const{unitId:n}=t;e(n)})),this.disposeWithMe(this._commandService.onCommandExecuted(t=>{if(t.id===SetDocZoomRatioOperation.id){const{unitId:n}=t.params;globalThis.queueMicrotask(()=>{this._disposed||e(n)})}}))}insertFloatDom(e,t){var n;const i=this._univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_DOC);if(!i)return!1;const r=this._getSceneAndTransformerByDrawingSearch(i.getUnitId());if(!r)return!1;const o=null===(n=r.renderUnit.with(DocSkeletonManagerService).getSkeleton().getSkeletonData())||void 0===n?void 0:n.pages[0];if(!o)return!1;const{pageWidth:a,marginLeft:s,marginRight:d}=o,c=a-s-d,l={size:{width:t.width??c,height:t.height},positionH:{relativeFrom:ObjectRelativeFromH.PAGE,posOffset:0},positionV:{relativeFrom:ObjectRelativeFromV.PAGE,posOffset:0},angle:0},g=t.drawingId??generateRandomId(),u={unitId:i.getUnitId(),drawings:[{drawingId:g,drawingType:DrawingTypeEnum.DRAWING_DOM,subUnitId:i.getUnitId(),unitId:i.getUnitId(),...e,title:"",description:"",docTransform:l,layoutType:PositionedObjectLayoutType.INLINE,transform:docDrawingPositionToTransform(l)}]};return this._commandService.syncExecuteCommand(InsertDocDrawingCommand.id,u),g}};function syncRectWithRuntimeParam(e,t,n,i,r){const o=getRuntimeTransform(t,e,n,i,r);return!!o&&(e.transformByState(o),!0)}function getRuntimeTransform(e,t,n,i,r){var o;const a=e.transform??(null===(o=e.transforms)||void 0===o?void 0:o[0]),s=e.customBlockRenderViewport??n;if(!e.customBlockRenderViewport&&r&&i&&a)return{...a,width:i.width??a.width,height:i.height??a.height};if(!a){const e=(null==s?void 0:s.height)??(null==s?void 0:s.contentHeight);if(!isPositiveNumber(e))return;return{left:t.left,top:t.top,width:t.width,height:e,angle:t.angle}}const d=(null==s?void 0:s.height)??(null==s?void 0:s.contentHeight);return isPositiveNumber(d)?{...a,height:d}:a}function isEmbedFloatDomRuntimeParam(e){if(null==e||"object"!=typeof e||!("data"in e))return!1;const t=e.data;if(!t||"object"!=typeof t)return!1;const n=t;return 1===n.version&&"string"==typeof n.embedId&&"string"==typeof n.hostAnchorId}function isSheetLikeEmbedFloatDomRuntimeParam(e){if(!isEmbedFloatDomRuntimeParam(e))return!1;const t=e.data;return!!t&&"object"==typeof t&&"childType"in t&&"number"==typeof t.childType&&isSheetLikeDocsCustomBlockChildType(t.childType)}function createTransformFromRect(e){return{angle:e.angle,height:e.height,left:e.left,top:e.top,width:e.width}}function subscribeViewportScrollAfter(e,t){if(!e||"object"!=typeof e)return;const n=e;if("function"==typeof n.subscribeEvent)return n.subscribeEvent(t);const i=e;if("function"==typeof i.subscribe){const e=i.subscribe(t);return toDisposable(()=>{var t;return null===(t=e.unsubscribe)||void 0===t?void 0:t.call(e)})}}DocFloatDomController=__decorate([__decorateParam(0,IRenderManagerService),__decorateParam(1,IDrawingManagerService),__decorateParam(2,Inject(DrawingRenderService)),__decorateParam(3,Inject(CanvasFloatDomService)),__decorateParam(4,IUniverInstanceService),__decorateParam(5,ICommandService),__decorateParam(6,Inject(DocRefreshDrawingsService))],DocFloatDomController);const DOCS_IMAGE_MENU_ID="doc.menu.image",IMAGE_MENU_UPLOAD_FLOAT_ID=InsertDocImageCommand.id,getDisableWhenSelectionInTableObservable=e=>{const t=e.get(DocSelectionManagerService),n=e.get(IUniverInstanceService);return new Observable(e=>{const i=t.textSelection$.subscribe(()=>{const i=t.getActiveTextRange();if(i){{var r;const{segmentId:t,startOffset:o,endOffset:a}=i,s=n.getCurrentUnitOfType(UniverInstanceType.UNIVER_DOC),d=null==s||null===(r=s.getSelfOrHeaderFooterModel(t))||void 0===r||null===(r=r.getBody())||void 0===r?void 0:r.tables;if(d&&d.length&&d.some(e=>{const{startIndex:t,endIndex:n}=e;return o>=t&&o<n||a>=t&&a<n}))return void e.next(!0)}e.next(!1)}else e.next(!0)});return()=>i.unsubscribe()})};function ImageMenuFactory(e){return{id:"doc.menu.image",commandId:IMAGE_MENU_UPLOAD_FLOAT_ID,type:MenuItemType.BUTTON,icon:"AddImageIcon",tooltip:"docs-drawing-ui.title",disabled$:getDisableWhenSelectionInTableObservable(e),hidden$:getMenuHiddenObservable(e,UniverInstanceType.UNIVER_DOC)}}function UploadFloatImageMenuFactory(e){return{id:IMAGE_MENU_UPLOAD_FLOAT_ID,title:"docs-drawing-ui.upload.float",type:MenuItemType.BUTTON,icon:"AddImageIcon",hidden$:getMenuHiddenObservable(e,UniverInstanceType.UNIVER_DOC)}}function UploadFloatImageBelowMenuFactory(e){return{id:`${IMAGE_MENU_UPLOAD_FLOAT_ID}.below`,commandId:IMAGE_MENU_UPLOAD_FLOAT_ID,title:"docs-drawing-ui.upload.float",type:MenuItemType.BUTTON,icon:"AddImageIcon",params:{paragraphMenuPlacement:"below"},hidden$:getMenuHiddenObservable(e,UniverInstanceType.UNIVER_DOC)}}const DOCS_SHAPE_MENU_ID="doc.command.menu-insert-shape",DOCS_SHAPE_BELOW_MENU_ID="doc.command.menu-insert-shape.below";function ShapeMenuFactory(e){return{id:DOCS_SHAPE_MENU_ID,type:MenuItemType.SUBITEMS,icon:"ShapeIcon",title:"docs-drawing-ui.shape.insert.title",tooltip:"docs-drawing-ui.shape.insert.title",hidden$:getMenuHiddenObservable(e,UniverInstanceType.UNIVER_DOC)}}function ShapeBelowMenuFactory(e){return{id:DOCS_SHAPE_BELOW_MENU_ID,type:MenuItemType.SUBITEMS,icon:"ShapeIcon",title:"docs-drawing-ui.shape.insert.title",tooltip:"docs-drawing-ui.shape.insert.title",hidden$:getMenuHiddenObservable(e,UniverInstanceType.UNIVER_DOC)}}function InsertRectangleShapeMenuFactory(e){return{id:InsertDocRectangleShapeCommand.id,title:"docs-drawing-ui.shape.insert.rectangle",type:MenuItemType.BUTTON,hidden$:getMenuHiddenObservable(e,UniverInstanceType.UNIVER_DOC)}}function InsertEllipseShapeMenuFactory(e){return{id:InsertDocEllipseShapeCommand.id,title:"docs-drawing-ui.shape.insert.ellipse",type:MenuItemType.BUTTON,hidden$:getMenuHiddenObservable(e,UniverInstanceType.UNIVER_DOC)}}function InsertRectangleShapeBelowMenuFactory(e){return{id:`${InsertDocRectangleShapeCommand.id}.below`,commandId:InsertDocRectangleShapeCommand.id,title:"docs-drawing-ui.shape.insert.rectangle",type:MenuItemType.BUTTON,params:{paragraphMenuPlacement:"below"},hidden$:getMenuHiddenObservable(e,UniverInstanceType.UNIVER_DOC)}}function InsertEllipseShapeBelowMenuFactory(e){return{id:`${InsertDocEllipseShapeCommand.id}.below`,commandId:InsertDocEllipseShapeCommand.id,title:"docs-drawing-ui.shape.insert.ellipse",type:MenuItemType.BUTTON,params:{paragraphMenuPlacement:"below"},hidden$:getMenuHiddenObservable(e,UniverInstanceType.UNIVER_DOC)}}const menuSchema={[RibbonInsertGroup.MEDIA]:{[DOCS_IMAGE_MENU_ID]:{order:0,gridLayout:{row:1,column:4},menuItemFactory:ImageMenuFactory}},[ContextMenuPosition.PARAGRAPH]:{[ContextMenuGroup.LAYOUT]:{[INSERT_BELLOW_MENU_ID]:{[IMAGE_MENU_UPLOAD_FLOAT_ID]:{order:5,menuItemFactory:UploadFloatImageMenuFactory}}},[EMPTY_PARAGRAPH_MENU_ID]:{[ContextMenuGroup.LAYOUT]:{[IMAGE_MENU_UPLOAD_FLOAT_ID]:{order:5,menuItemFactory:UploadFloatImageMenuFactory}}},[DOC_CONTENT_INSERT_MENU_ID]:{[ContextMenuGroup.LAYOUT]:{[IMAGE_MENU_UPLOAD_FLOAT_ID]:{order:5,menuItemFactory:UploadFloatImageMenuFactory}}},[DOC_PARAGRAPH_T_INSERT_MENU_ID]:{insert:{[IMAGE_MENU_UPLOAD_FLOAT_ID]:{order:1,menuItemFactory:UploadFloatImageMenuFactory},[DOCS_SHAPE_MENU_ID]:{order:2,menuItemFactory:ShapeMenuFactory}}},[DOC_PARAGRAPH_T_INSERT_BELOW_MENU_ID]:{insert:{[`${IMAGE_MENU_UPLOAD_FLOAT_ID}.below`]:{order:1,menuItemFactory:UploadFloatImageBelowMenuFactory},[DOCS_SHAPE_BELOW_MENU_ID]:{order:2,menuItemFactory:ShapeBelowMenuFactory}}},[DOCS_SHAPE_MENU_ID]:{shapes:{order:0,[InsertDocRectangleShapeCommand.id]:{order:0,menuItemFactory:InsertRectangleShapeMenuFactory},[InsertDocEllipseShapeCommand.id]:{order:1,menuItemFactory:InsertEllipseShapeMenuFactory}}},[DOCS_SHAPE_BELOW_MENU_ID]:{shapes:{order:0,[`${InsertDocRectangleShapeCommand.id}.below`]:{order:0,menuItemFactory:InsertRectangleShapeBelowMenuFactory},[`${InsertDocEllipseShapeCommand.id}.below`]:{order:1,menuItemFactory:InsertEllipseShapeBelowMenuFactory}}}}};var name="@univerjs/docs-drawing-ui",version="1.0.3";const DOCS_DRAWING_UI_PLUGIN_CONFIG_KEY="docs-drawing-ui.config",DOCS_DRAWING_UI_PLUGIN_NAME="DOC_DRAWING_UI_PLUGIN",configSymbol=Symbol("docs-drawing-ui.config"),defaultPluginConfig={};function getAddOrRemoveDrawings(e){if(JSONX.isNoop(e))return null;const t=[],n=JSON1.type.readCursor(e);return n.traverse(null,()=>{const e=n.getPath();if(2!==e.length||"drawings"!==e[0]||"string"!=typeof e[1])return;const i=n.getComponent();void 0!==(null==i?void 0:i.r)&&t.push({type:"remove",drawingId:e[1]}),void 0!==(null==i?void 0:i.i)&&t.push({type:"add",drawingId:e[1],drawing:i.i})}),t.length?t:null}function getReOrderedDrawings(e){if(!Array.isArray(e)||e.length<3||"drawingsOrder"!==e[0])return[];const t=[];for(let n=1;n<e.length;n++){const i=e[n];if(!Array.isArray(i)||"number"!=typeof i[0]||"object"!=typeof i[1]){t.length=0;break}t.push(i[0])}return t}function collectUpdatedDrawingIds(e,t=new Set){if(JSONX.isNoop(e)||!Array.isArray(e))return t;if("drawings"===e[0]){const n=e[1];return"string"==typeof n?(t.add(n),t):(e.slice(1).forEach(e=>{Array.isArray(e)&&"string"==typeof e[0]&&t.add(e[0])}),t)}return e.forEach(e=>{Array.isArray(e)&&collectUpdatedDrawingIds(e,t)}),t}let DocDrawingAddRemoveController=class extends Disposable{constructor(e,t,n,i,r,o){super(),this._univerInstanceService=e,this._commandService=t,this._drawingManagerService=n,this._docDrawingService=i,this._renderManagerService=r,this._docRefreshDrawingsService=o,this._initialize()}_initialize(){this._commandExecutedListener()}_commandExecutedListener(){this.disposeWithMe(this._commandService.beforeCommandExecuted(e=>{if(e.id!==RichTextEditingMutation.id)return;const{unitId:t,actions:n,isSync:i,syncer:r}=e.params,o=getAddOrRemoveDrawings(n);if(null!=o)for(const{type:e,drawingId:n,drawing:a}of o)i&&(null==a?void 0:a.unitId)===r||("add"===e?this._addDrawings(t,[a]):this._removeDrawings(t,[n]))})),this.disposeWithMe(this._commandService.beforeCommandExecuted(e=>{e.id===UpdateDocDrawingWrappingStyleCommand.id&&this._preserveWrappingStylePosition(e.params)})),this.disposeWithMe(this._commandService.onCommandExecuted(e=>{if(e.id!==RichTextEditingMutation.id)return;const{unitId:t,actions:n}=e.params;let i=!1;if(!JSONX.isNoop(n)){const e=JSON1.type.readCursor(n);e.traverse(null,()=>{i||="notes"===e.getPath()[0]})}i&&this._syncNoteDrawings(t),getReOrderedDrawings(n).length>0&&this._updateDrawingsOrder(t);const r=[...collectUpdatedDrawingIds(n)];r.length>0&&this._syncDrawingDataFromSnapshot(t,r)})),this.disposeWithMe(this._commandService.onCommandExecuted(e=>{if(e.id!==UpdateDrawingDocTransformCommand.id&&e.id!==UpdateDocDrawingWrappingStyleCommand.id)return;const{unitId:t}=e.params,n=this._renderManagerService.getRenderUnitById(t),i=null==n?void 0:n.scene;null!=n&&null!=i&&(e.id===UpdateDocDrawingWrappingStyleCommand.id&&this._docRefreshDrawingsService.refreshDrawings(n.with(DocSkeletonManagerService).getSkeleton()),i.getTransformerByCreate().refreshControls())})),this.disposeWithMe(this._commandService.onCommandExecuted(e=>{var t;if(e.id!==UndoCommand.id&&e.id!==RedoCommand.id)return;const n=null===(t=this._univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_DOC))||void 0===t?void 0:t.getUnitId(),i=this._drawingManagerService.getFocusDrawings();if(null==n||0===i.length)return;const r=this._renderManagerService.getRenderUnitById(n),o=null==r?void 0:r.scene;if(null==r||null==o)return!1;this._docRefreshDrawingsService.refreshDrawings(r.with(DocSkeletonManagerService).getSkeleton()),o.getTransformerByCreate().refreshControls()}))}_preserveWrappingStylePosition(e){if(e.wrappingStyle===TextWrappingStyle.INLINE)return;const{unitId:t}=e,n=this._univerInstanceService.getUnit(t,UniverInstanceType.UNIVER_DOC),i=this._renderManagerService.getRenderUnitById(t),r=null==i?void 0:i.with(DocSkeletonManagerService),o=null==r?void 0:r.getSkeleton().getSkeletonData(),a=null==r?void 0:r.getViewModel();if(!n||!o||!a)return;const s=a.getEditArea(),{pages:d,skeHeaders:c,skeFooters:l}=o,g=n.getDrawings()??{};e.drawings=e.drawings.map(e=>{const t=g[e.drawingId];if(!t)return e;let n=null;for(const t of d){const{headerId:o,footerId:a,marginTop:d,marginLeft:g,marginBottom:u,pageWidth:p,pageHeight:h}=t;if(s===DocumentEditArea.HEADER){var i;const t=null===(i=c.get(o))||void 0===i?void 0:i.get(p);t&&(n=findDrawingAnchorInPage(t,e.drawingId,t.marginTop,g))}else if(s===DocumentEditArea.FOOTER){var r;const t=null===(r=l.get(a))||void 0===r?void 0:r.get(p);t&&(n=findDrawingAnchorInPage(t,e.drawingId,h-u+t.marginTop,g))}else n=findDrawingAnchorInPage(t,e.drawingId,d,g);if(n)break}if(!n)return e;const o=t.docTransform.positionH,a=t.docTransform.positionV,{horizontal:u,vertical:p}=resolveDrawingAnchorOffsets(n,o,a);return{...t,...e,docTransform:{...t.docTransform,...e.docTransform,positionH:{relativeFrom:o.relativeFrom,posOffset:u},positionV:{relativeFrom:a.relativeFrom,posOffset:p}}}})}_addDrawings(e,t){const n=this._drawingManagerService,i=this._docDrawingService,{subUnitId:r,redo:o,objects:a}=this._docDrawingService.getBatchAddOp(t.map(t=>({...t,unitId:e,subUnitId:e})));n.applyJson1(e,r,o),i.applyJson1(e,r,o),n.addNotification(a),i.addNotification(a)}_removeDrawings(e,t){const n=this._drawingManagerService,i=this._docDrawingService,r=t.filter(t=>i.getDrawingByParam({unitId:e,subUnitId:e,drawingId:t}));if(0===r.length)return;const{subUnitId:o,redo:a,objects:s}=this._docDrawingService.getBatchRemoveOp(r.map(t=>({unitId:e,subUnitId:e,drawingId:t})));n.applyJson1(e,o,a),i.applyJson1(e,o,a),n.removeNotification(s),i.removeNotification(s)}_updateDrawingsOrder(e){const t=this._univerInstanceService.getUnit(e,UniverInstanceType.UNIVER_DOC);if(null==t)return;const{drawings:n,drawingsOrder:i}=collectDocDrawings(t.getSnapshot());if(null==i)return;const r=getDocDrawingRenderOrder(i,n),o=this._drawingManagerService,a=this._docDrawingService;o.setDrawingOrder(e,e,r),a.setDrawingOrder(e,e,i);const s={unitId:e,subUnitId:e,drawingIds:r};o.orderNotification(s),a.orderNotification({unitId:e,subUnitId:e,drawingIds:i})}_syncNoteDrawings(e){const t=this._univerInstanceService.getUnit(e,UniverInstanceType.UNIVER_DOC);if(!t)return;const{drawings:n}=collectDocDrawings(t.getSnapshot()),i=this._docDrawingService.getDrawingData(e,e)??{},r=Object.keys(n).filter(e=>!i[e]),o=Object.keys(i).filter(e=>!n[e]),a=Object.keys(n).filter(e=>n[e]!==i[e]);r.length>0&&this._addDrawings(e,r.map(t=>({...n[t],unitId:e,subUnitId:e}))),o.length>0&&this._removeDrawings(e,o),a.length>0&&this._syncDrawingDataFromSnapshot(e,a)}_syncDrawingDataFromSnapshot(e,t){const n=this._univerInstanceService.getUnit(e,UniverInstanceType.UNIVER_DOC);if(null==n)return;const{drawings:i,drawingsOrder:r}=collectDocDrawings(n.getSnapshot()),o=Object.fromEntries(Object.entries(i).map(([t,n])=>[t,{...n,unitId:e,subUnitId:e}])),a=this._docDrawingService.getDrawingData(e,e),s=this._drawingManagerService.getDrawingData(e,e),d=Object.keys(o).filter(e=>!s[e]),c=[...new Set([...t,...d])],l=r!==this._docDrawingService.getDrawingOrder(e,e)||c.some(e=>{const t=a[e],n=o[e];return((null==t?void 0:t.layoutType)===PositionedObjectLayoutType.WRAP_NONE&&t.behindDoc===BooleanNumber.TRUE)!=((null==n?void 0:n.layoutType)===PositionedObjectLayoutType.WRAP_NONE&&n.behindDoc===BooleanNumber.TRUE)}),g=c.some(e=>{var t,n;return(null===(t=a[e])||void 0===t?void 0:t.groupId)!==(null===(n=o[e])||void 0===n?void 0:n.groupId)});g&&this._drawingManagerService.removeNotification(Object.values(this._drawingManagerService.getDrawingData(e,e)));const u={...this._drawingManagerService.getDrawingData(e,e)};for(const e of c){const t=o[e];t?u[e]={...t}:delete u[e]}this._docDrawingService.setDrawingData(e,e,o),this._drawingManagerService.setDrawingData(e,e,u),l&&(this._docDrawingService.setDrawingOrder(e,e,r),this._drawingManagerService.setDrawingOrder(e,e,getDocDrawingRenderOrder(r,i)));const p=c.filter(e=>null!=o[e]).map(t=>({unitId:e,subUnitId:e,drawingId:t}));0!==p.length&&(g&&this._drawingManagerService.addNotification(Object.values(u)),this._docDrawingService.updateNotification(p),this._drawingManagerService.updateNotification(p))}};DocDrawingAddRemoveController=__decorate([__decorateParam(0,IUniverInstanceService),__decorateParam(1,ICommandService),__decorateParam(2,IDrawingManagerService),__decorateParam(3,IDocDrawingService),__decorateParam(4,IRenderManagerService),__decorateParam(5,Inject(DocRefreshDrawingsService))],DocDrawingAddRemoveController);const DocPrintingFloatDom=e=>{const{floatDomInfos:t,scene:n,offset:i,bound:r}=e,o=r.right-r.left,a=r.bottom-r.top,s=useMemo(()=>t.map(e=>{const{width:t=0,height:i=0,left:r=0,top:o=0}=e.transform,a=calcDocFloatDomPositionByRect({left:r,right:r+t,top:o,bottom:o+i},n),s={position$:new BehaviorSubject(a),position:a,id:e.drawingId,componentKey:e.componentKey,onPointerMove:()=>{},onPointerDown:()=>{},onPointerUp:()=>{},onWheel:()=>{},unitId:e.unitId,data:e.data};return[e.drawingId,s]}).filter(([e,t])=>!(t.position.endX<0||t.position.endY<0||t.position.startX>o||t.position.startY>a)),[t,n,i,o,a]);return jsx("div",{className:"univer-absolute univer-left-0 univer-top-0",children:s.map(([e,t])=>jsx(PrintFloatDomSingle,{layer:t,id:e,position:t.position},e))})};function mountDocPrintingFloatDom(e,t,n){const i=connectInjector(DocPrintingFloatDom,n);return render(jsx(i,{...e}),t),()=>unmount(t)}let DocDrawingPrintingController=class extends Disposable{constructor(e,t,n,i,r){super(),this._docPrintInterceptorService=e,this._drawingRenderService=t,this._drawingManagerService=n,this._componetManager=i,this._injector=r,this._initPrinting(),this._initPrintingDom()}_initPrinting(){this.disposeWithMe(this._docPrintInterceptorService.interceptor.intercept(this._docPrintInterceptorService.interceptor.getInterceptPoints().PRINTING_COMPONENT_COLLECT,{handler:(e,t,n)=>{const{unitId:i,scene:r,skeleton:o,pageIndex:a}=t,s=this._drawingManagerService.getDrawingDataForUnit(i),d=null==s?void 0:s[i],c=this._docPrintInterceptorService.getPageDrawingIds(o,a);return d&&d.order.forEach(e=>{if(c&&!c.has(e))return;const t=d.data[e];t.drawingType!==DrawingTypeEnum.DRAWING_CHART&&t.drawingType!==DrawingTypeEnum.DRAWING_DOM&&this._drawingRenderService.renderDrawing(t,r)}),n()}}))}_initPrintingDom(){this.disposeWithMe(this._docPrintInterceptorService.interceptor.intercept(this._docPrintInterceptorService.interceptor.getInterceptPoints().PRINTING_DOM_COLLECT,{handler:(e,t,n)=>{const{unitId:i,skeleton:r,pageIndex:o}=t,a=this._drawingManagerService.getDrawingDataForUnit(i),s=null==a?void 0:a[i],d=this._docPrintInterceptorService.getPageDrawingIds(r,o);if(s){const r=mountDocPrintingFloatDom({unitId:i,floatDomInfos:s.order.filter(e=>!d||d.has(e)).map(e=>{const t=s.data[e];if(t.drawingType===DrawingTypeEnum.DRAWING_CHART)return{...t,componentKey:this._componetManager.get(DOC_DRAWING_PRINTING_COMPONENT_KEY)};if(t.drawingType===DrawingTypeEnum.DRAWING_DOM){const e=this._docPrintInterceptorService.getPrintComponent(t.componentKey);return{...t,componentKey:this._componetManager.get(e||t.componentKey)}}return null}).filter(Boolean),scene:t.scene,skeleton:t.skeleton,offset:t.offset,bound:t.bound},t.root,this._injector);return null==e||e.add(()=>{r()}),n(e)}}}))}};function getDeleteAndInsertCustomBlockActions(e,t,n,i,r,o,a){var s,d,c;const l=new TextX,g=JSONX.getInstance(),u=[],p=null===(s=o.getSelfOrHeaderFooterModel(t))||void 0===s?void 0:s.getBody(),h=null===(d=o.getSelfOrHeaderFooterModel(e))||void 0===d?void 0:d.getBody();if(null==p||null==h)return;const m=null===(c=p.customBlocks)||void 0===c||null===(c=c.find(e=>e.blockId===r))||void 0===c?void 0:c.startIndex;if(null!=m){if(i=Math.min(h.dataStream.length-2,i),e===t){if(i<m?(i>0&&l.push({t:TextXActionType.RETAIN,len:i}),l.push({t:TextXActionType.INSERT,body:{dataStream:"\b",customBlocks:[{startIndex:0,blockId:r}]},len:1}),l.push({t:TextXActionType.RETAIN,len:m-i}),l.push({t:TextXActionType.DELETE,len:1})):(m>0&&l.push({t:TextXActionType.RETAIN,len:m}),l.push({t:TextXActionType.DELETE,len:1}),i-m-1>0&&l.push({t:TextXActionType.RETAIN,len:i-m-1}),l.push({t:TextXActionType.INSERT,body:{dataStream:"\b",customBlocks:[{startIndex:0,blockId:r}]},len:1})),i!==m){const e=getRichTextEditPath(o,t),n=g.editOp(l.serialize(),e);u.push(n)}}else{m>0&&l.push({t:TextXActionType.RETAIN,len:m}),l.push({t:TextXActionType.DELETE,len:1});let s=getRichTextEditPath(o,t),d=g.editOp(l.serialize(),s);u.push(d),l.empty(),i>0&&l.push({t:TextXActionType.RETAIN,len:i}),l.push({t:TextXActionType.INSERT,body:{dataStream:"\b",customBlocks:[{startIndex:0,blockId:r}]},len:1}),s=getRichTextEditPath(o,e),d=g.editOp(l.serialize(),s),u.push(d),a.setSegment(e),a.setSegmentPage(n)}return u}}DocDrawingPrintingController=__decorate([__decorateParam(0,Inject(DocPrintInterceptorService)),__decorateParam(1,Inject(DrawingRenderService)),__decorateParam(2,IDrawingManagerService),__decorateParam(3,Inject(ComponentManager)),__decorateParam(4,Inject(Injector))],DocDrawingPrintingController);const UpdateDocDrawingDistanceCommand={id:"doc.command.update-doc-drawing-distance",type:CommandType.COMMAND,handler:(e,t)=>{if(null==t)return!1;const n=e.get(ICommandService),i=e.get(IUniverInstanceService),{drawings:r,dist:o,unitId:a}=t,s=i.getUnit(a,UniverInstanceType.UNIVER_DOC);if(null==s)return!1;const d=JSONX.getInstance(),c=[],{drawings:l={}}=s.getSnapshot();for(const e of r){const{drawingId:t}=e;for(const[e,n]of Object.entries(o)){const i=l[t][e];if(i!==n){const r=d.replaceOp(["drawings",t,e],i,n);c.push(r)}}}const g={id:RichTextEditingMutation.id,params:{unitId:a,actions:[],textRanges:null}};g.params.actions=c.reduce((e,t)=>JSONX.compose(e,t),null);const u=n.syncExecuteCommand(g.id,g.params);return Boolean(u)}},UpdateDocDrawingWrapTextCommand={id:"doc.command.update-doc-drawing-wrap-text",type:CommandType.COMMAND,handler:(e,t)=>{if(null==t)return!1;const n=e.get(ICommandService),i=e.get(IUniverInstanceService),{drawings:r,wrapText:o,unitId:a}=t,s=i.getUnit(a,UniverInstanceType.UNIVER_DOC);if(null==s)return!1;const d=JSONX.getInstance(),c=[],{drawings:l={}}=s.getSnapshot();for(const e of r){const{drawingId:t}=e,n=l[t].wrapText;if(n!==o){const e=d.replaceOp(["drawings",t,"wrapText"],n,o);c.push(e)}}const g={id:RichTextEditingMutation.id,params:{unitId:a,actions:[],textRanges:null}};g.params.actions=c.reduce((e,t)=>JSONX.compose(e,t),null);const u=n.syncExecuteCommand(g.id,g.params);return Boolean(u)}},IMoveInlineDrawingCommand={id:"doc.command.move-inline-drawing",type:CommandType.COMMAND,handler:(e,t)=>{var n;if(null==t)return!1;const{drawing:i,unitId:r,offset:o,segmentId:a,segmentPage:s,needRefreshDrawings:d}=t,c=e.get(IRenderManagerService),l=null===(n=c.getRenderUnitById(r))||void 0===n?void 0:n.with(DocSelectionRenderService),g=e.get(DocRefreshDrawingsService),u=c.getRenderUnitById(r),p=null==u?void 0:u.scene,h=null==u?void 0:u.with(DocSkeletonManagerService).getSkeleton();if(null==p||null==l)return!1;const m=p.getTransformerByCreate(),v=e.get(ICommandService),f=e.get(IUniverInstanceService).getUnit(r,UniverInstanceType.UNIVER_DOC);if(null==f)return!1;if(d)return g.refreshDrawings(h),m.refreshControls(),!0;const I=[],{drawingId:_}=i,D=getDeleteAndInsertCustomBlockActions(a,l.getSegment()??"",s,o,_,f,l);if(null==D||0===D.length)return g.refreshDrawings(h),m.refreshControls(),!1;I.push(...D);const w={id:RichTextEditingMutation.id,params:{unitId:r,actions:[],textRanges:null}};w.params.actions=I.reduce((e,t)=>JSONX.compose(e,t),null);const S=v.syncExecuteCommand(w.id,w.params);return m.refreshControls(),Boolean(S)}},ITransformNonInlineDrawingCommand={id:"doc.command.transform-non-inline-drawing",type:CommandType.COMMAND,handler:(e,t)=>{var n;if(null==t)return!1;const{drawing:i,unitId:r,offset:o,docTransform:a,segmentId:s,segmentPage:d}=t,c=e.get(IRenderManagerService),l=null===(n=c.getRenderUnitById(r))||void 0===n?void 0:n.with(DocSelectionRenderService),g=c.getRenderUnitById(r),u=null==g?void 0:g.scene;if(null==g||null==u||null==l)return!1;const p=u.getTransformerByCreate(),h=e.get(ICommandService),m=e.get(IUniverInstanceService).getUnit(r,UniverInstanceType.UNIVER_DOC);if(null==m)return!1;const v=[],{drawingId:f}=i,I=getDeleteAndInsertCustomBlockActions(s,l.getSegment()??"",d,o,f,m,l);if(null==I)return!1;I.length>0&&v.push(...I);const _=JSONX.getInstance(),{drawings:D={}}=m.getSnapshot(),{positionH:w,positionV:S,size:T,angle:y}=D[f].docTransform;if(!Tools.diffValue(w,a.positionH)){const e=_.replaceOp(["drawings",f,"docTransform","positionH"],w,a.positionH);v.push(e)}if(!Tools.diffValue(S,a.positionV)){const e=_.replaceOp(["drawings",f,"docTransform","positionV"],S,a.positionV);v.push(e)}if(!Tools.diffValue(T,a.size)){const e=_.replaceOp(["drawings",f,"docTransform","size"],T,a.size);v.push(e)}if(!Tools.diffValue(y,a.angle)){const e=_.replaceOp(["drawings",f,"docTransform","angle"],y,a.angle);v.push(e)}const b={id:RichTextEditingMutation.id,params:{unitId:r,actions:[],textRanges:null,debounce:!0}};b.params.actions=v.reduce((e,t)=>JSONX.compose(e,t),null);const P=h.syncExecuteCommand(b.id,b.params),M=g.with(DocSkeletonManagerService).getSkeleton();return e.get(DocRefreshDrawingsService).refreshDrawings(M),p.refreshControls(),Boolean(P)}};function mergePublishedDrawing(e,t){const n=e[t.drawingId];null!=n?(t.selectable&&!n.selectable&&(n.selectable=!0,n.transform=t.transform),t.isMultiTransform===BooleanNumber.TRUE&&n.transforms.push(t.transform)):e[t.drawingId]=t}function isSameTransformValue(e,t){return e===t||JSON.stringify(e)===JSON.stringify(t)}function shouldRefreshDocDrawingTransform(e,t){return!e||null!=t.customBlockRenderViewport||(!isSameTransformValue(e.transform,t.transform)||!isSameTransformValue(e.transforms,t.transforms)||e.isMultiTransform!==t.isMultiTransform||e.hidden!==t.hidden||e.behindText!==t.behindText||e.selectable!==t.selectable)}function getDocsOverlayRuntimeDrawing(e,t,n){return e.layoutType===PositionedObjectLayoutType.WRAP_NONE&&(null==t?void 0:t.layoutType)===PositionedObjectLayoutType.WRAP_NONE?t:n?{...e,docTransform:{...e.docTransform,size:n}}:e}var DocDrawingPublicationTracker=class{constructor(){_defineProperty(this,"_generation",-1),_defineProperty(this,"_publishedPageCount",0),_defineProperty(this,"_drawingOccurrenceCount",0)}reset(){this._generation=-1,this._publishedPageCount=0,this._drawingOccurrenceCount=0}shouldRefresh(e,t){if(!t.didPublish&&!t.complete)return!1;const n=t.generation!==this._generation;n&&(this._generation=t.generation,this._publishedPageCount=0,this._drawingOccurrenceCount=0);const i=e.getSkeletonData();if(null==i)return!1;const r=this._publishedPageCount,o=Math.min(t.publishedPageCount,i.pages.length);this._publishedPageCount=Math.max(r,o);const a=countPublishedDrawingOccurrences(i,o),s=!(n&&"edit"===t.reason)&&a!==this._drawingOccurrenceCount;return this._drawingOccurrenceCount=a,!!(t.complete||t.didPublishAnchor||s)||(!n||"edit"!==t.reason)&&hasNewPublishedPageDrawings(i,r,o)}};function getDocsDrawingPageClipBounds(e){const{docsLeft:t,docsTop:n,pageOffsetLeft:i,pageOffsetTop:r,clipOffsetLeft:o=0,clipOffsetTop:a=0,page:s}=e;if(s.type===DocumentSkeletonPageType.CELL&&e.drawingLayoutType===PositionedObjectLayoutType.WRAP_NONE&&null!=e.overflowClipBounds)return e.overflowClipBounds;const{pageWidth:d,pageHeight:c}=s;if(!Number.isFinite(d)||!Number.isFinite(c)||d<=0||c<=0)return;return{left:t+i+o-(s.type===DocumentSkeletonPageType.CELL?s.marginLeft??0:0),top:n+r+a-(s.type===DocumentSkeletonPageType.CELL?s.marginTop??0:0),width:d,height:c}}function getDocsDrawingClipPage(e){const{drawing:t,hostPage:n,page:i}=e;if(n&&(i.type===DocumentSkeletonPageType.HEADER||i.type===DocumentSkeletonPageType.FOOTER))return n;if(null==n||!0!==t.behindText||null==t.transform)return i;const{width:r,height:o}=t.transform;if(null==r||null==o)return i;if(r>i.pageWidth||o>i.pageHeight)return n;const a=r/n.pageWidth,s=o/n.pageHeight;return a>=.8&&s>=.8?n:i}function getDocsPageRelativeDrawingLeft(e){const{hostPage:t,positionH:n,width:i}=e;if(n.relativeFrom===ObjectRelativeFromH.PAGE)return n.align===AlignTypeH.RIGHT?t.pageWidth-i:n.align===AlignTypeH.CENTER?t.pageWidth/2-i/2:null!=n.posOffset?n.posOffset:0}function getDocsPageRelativeDrawingTop(e){const{hostPage:t,positionV:n,height:i}=e;if(n.relativeFrom===ObjectRelativeFromV.PAGE)return n.align===AlignTypeV.BOTTOM?t.pageHeight-i:n.align===AlignTypeV.CENTER?t.pageHeight/2-i/2:null!=n.posOffset?n.posOffset:0}function getDocsPageRelativeDrawingAnchorPage(e){const{page:t,clipPage:n,hostPage:i}=e;if(e.drawingLayoutType!==PositionedObjectLayoutType.INLINE)return null!=i&&i===n?i:null==i&&t===n&&t.type!==DocumentSkeletonPageType.CELL?t:void 0}function getDocsDrawingBehindText(e){const{drawingOrigin:t,hostPage:n}=e;return null!=n||t.layoutType===PositionedObjectLayoutType.WRAP_NONE&&t.behindDoc===BooleanNumber.TRUE}function getDocsTableCellDrawingOffset(e,t,n,i){const r=getTableIdAndSliceIndex(t.tableId).tableId,o=getDocsTableRenderViewport(e,r),a=hasHorizontalTableViewport(o)?o.scrollLeft:0;return{left:t.left+i.left-a+i.marginLeft,top:t.top+n.top+i.marginTop}}function hasHorizontalTableViewport(e){return null!=e&&(e.leadingInsetLeft??0)+e.contentWidth+(e.trailingInsetRight??0)>e.viewportWidth}function hasSkeletonPageDrawings(e){var t,n,i;if(e.skeDrawings.size>0||(null===(t=e.notes)||void 0===t?void 0:t.some(e=>hasSkeletonPageDrawings(e.page))))return!0;let r=!1;return null===(n=e.skeTables)||void 0===n||n.forEach(e=>{e.rows.forEach(e=>{e.cells.forEach(e=>{hasSkeletonPageDrawings(e)&&(r=!0)})})}),null===(i=e.skeColumnGroups)||void 0===i||i.forEach(e=>{e.columns.forEach(e=>{hasSkeletonPageDrawings(e.page)&&(r=!0)})}),r}function countSkeletonPageDrawings(e){var t,n,i;let r=e.skeDrawings.size;return null===(t=e.notes)||void 0===t||t.forEach(e=>{r+=countSkeletonPageDrawings(e.page)}),null===(n=e.skeTables)||void 0===n||n.forEach(e=>{e.rows.forEach(e=>{e.cells.forEach(e=>{r+=countSkeletonPageDrawings(e)})})}),null===(i=e.skeColumnGroups)||void 0===i||i.forEach(e=>{e.columns.forEach(e=>{r+=countSkeletonPageDrawings(e.page)})}),r}function countPublishedDrawingOccurrences(e,t){let n=0;for(let o=0;o<t;o++){var i,r;const t=e.pages[o];n+=countSkeletonPageDrawings(t);const a=null==t.headerId||null===(i=e.skeHeaders.get(t.headerId))||void 0===i?void 0:i.get(t.pageWidth);null!=a&&(n+=countSkeletonPageDrawings(a));const s=null==t.footerId||null===(r=e.skeFooters.get(t.footerId))||void 0===r?void 0:r.get(t.pageWidth);null!=s&&(n+=countSkeletonPageDrawings(s))}return n}function hasNewPublishedPageDrawings(e,t,n){for(let o=t;o<n;o++){var i,r;const t=e.pages[o];if(hasSkeletonPageDrawings(t))return!0;const n=null==t.headerId||null===(i=e.skeHeaders.get(t.headerId))||void 0===i?void 0:i.get(t.pageWidth);if(null!=n&&hasSkeletonPageDrawings(n))return!0;const a=null==t.footerId||null===(r=e.skeFooters.get(t.footerId))||void 0===r?void 0:r.get(t.pageWidth);if(null!=a&&hasSkeletonPageDrawings(a))return!0}return!1}let DocDrawingTransformUpdateController=class extends Disposable{constructor(e,t,n,i,r,o,a,s){super(),this._context=e,this._docSkeletonManagerService=t,this._commandService=n,this._editorService=i,this._drawingManagerService=r,this._docRefreshDrawingsService=o,this._univerInstanceService=a,this._lifecycleService=s,_defineProperty(this,"_liquid",new Liquid),_defineProperty(this,"_changesetDrawingRefreshScheduled",!1),_defineProperty(this,"_publicationTracker",new DocDrawingPublicationTracker),this._initialize(),this._commandExecutedListener()}_initialize(){this._initialRenderRefresh(),this._drawingInitializeListener(),this._initTransformRefresh()}_initialRenderRefresh(){this.disposeWithMe(this._docSkeletonManagerService.currentSkeleton$.pipe(switchMap(e=>{if(this._publicationTracker.reset(),null==e)return EMPTY;this._refreshDrawing(e);const t=animationFrames().pipe(startWith(null),map(()=>this._context.mainComponent),filter(e=>e instanceof Documents&&e.left>-1e4&&e.top>-1e4),take(1),switchMap(t=>fromEventSubject(t.onTransformChange$).pipe(filter(e=>e.type===TRANSFORM_CHANGE_OBSERVABLE_TYPE.translate&&"left"in e.value&&"left"in e.preValue&&(e.value.left!==e.preValue.left||e.value.top!==e.preValue.top)),map(()=>({documentSkeleton:e,progress:null})),startWith({documentSkeleton:e,progress:null}))));return merge$1(e.layoutProgress$.pipe(map(t=>({documentSkeleton:e,progress:t}))),e.layoutPageMaterialized$.pipe(map(()=>({documentSkeleton:e,progress:null}))),t)})).subscribe(({documentSkeleton:e,progress:t})=>{(null==t||this._publicationTracker.shouldRefresh(e,t))&&this._refreshDrawing(e)})),this.disposeWithMe(this._docRefreshDrawingsService.refreshDrawings$.subscribe(e=>{null!=e&&this._refreshDrawing(e)}))}_commandExecutedListener(){const e=[RichTextEditingMutation.id,SetDocZoomRatioOperation.id];this.disposeWithMe(this._commandService.onCommandExecuted((t,n)=>{if(e.includes(t.id)){const e=t.params,{unitId:i}=e,{unitId:r}=this._context;if(i!==r)return;const o=t.id===RichTextEditingMutation.id?getDocMutationAffectedDrawingIds(e.actions):null;if(0===(null==o?void 0:o.size))return;if(t.id===RichTextEditingMutation.id&&(null==n?void 0:n.fromChangeset))return void this._scheduleChangesetDrawingRefresh();this._refreshCurrentDrawing(o??void 0)}}))}_scheduleChangesetDrawingRefresh(){this._changesetDrawingRefreshScheduled||(this._changesetDrawingRefreshScheduled=!0,queueMicrotask(()=>{queueMicrotask(()=>{this._changesetDrawingRefreshScheduled=!1,this._disposed||this._refreshCurrentDrawing()})}))}_refreshCurrentDrawing(e){const t=this._docSkeletonManagerService.getSkeleton();if(null==t)return;const{unitId:n,mainComponent:i}=this._context;this._editorService.isEditor(n)?null==i||i.makeDirty():this._refreshDrawing(t,e)}_initTransformRefresh(){this.disposeWithMe(merge$1(fromEventSubject(this._context.engine.onTransformChange$).pipe(filter(e=>e.type===TRANSFORM_CHANGE_OBSERVABLE_TYPE.resize)),fromEventSubject(this._context.scene.onTransformChange$).pipe(filter(e=>e.type===TRANSFORM_CHANGE_OBSERVABLE_TYPE.scale))).pipe(debounceTime(16)).subscribe(()=>{var e;const t=this._docSkeletonManagerService.getSkeleton(),{scene:n}=this._context;null===(e=n.getTransformer())||void 0===e||e.refreshControls(),this._refreshDrawing(t)}))}_refreshDrawing(e,t){const n=null==e?void 0:e.getSkeletonData(),{mainComponent:i,unitId:r}=this._context,o=i;if(!n)return;const{left:a,top:s,pageLayoutType:d,pageMarginLeft:c,pageMarginTop:l}=o;if(a<=-1e4||s<=-1e4)return;const{pages:g,skeHeaders:u,skeFooters:p}=n,h={};this._liquid.reset();for(let e=0,t=g.length;e<t;e++){const t=g[e];this._collectPublishedPageDrawingPositions(r,t,u,p,a,s,h),this._liquid.translatePage(t,d,c,l)}const m=this._includeGroupChildren(t),v=Object.values(h).filter(e=>null==m||m.has(e.drawingId));for(const e of v)e.hidden=!1;const f=this._getStaleNonMultiDrawings(r,h,m),I=v.filter(e=>!e.isMultiTransform).concat(f).filter(e=>shouldRefreshDocDrawingTransform(this._drawingManagerService.getDrawingByParam({unitId:r,subUnitId:r,drawingId:e.drawingId}),e));I.length>0&&this._drawingManagerService.refreshTransform(I);const _=null!=m&&[...m].some(e=>{var t,n;return(null===(t=h[e])||void 0===t?void 0:t.isMultiTransform)===BooleanNumber.TRUE||(null===(n=this._drawingManagerService.getDrawingByParam({unitId:r,subUnitId:r,drawingId:e}))||void 0===n?void 0:n.isMultiTransform)===BooleanNumber.TRUE});if(null==m||_){const e=Object.values(h).filter(e=>e.isMultiTransform);this._handleMultiDrawingsTransform(e)}}_includeGroupChildren(e){if(null==e)return;const t=new Set(e),{drawings:n}=collectDocDrawings(this._context.unit.getSnapshot());let i=-1;for(;i!==t.size;){i=t.size;for(const e of Object.values(n))e.groupId&&t.has(e.groupId)&&t.add(e.drawingId)}return t}_collectPublishedPageDrawingPositions(e,t,n,i,r,o,a){var s,d;const c=!t.isLayoutPlaceholder&&!t.isMaterializationPlaceholder,{headerId:l,footerId:g,pageWidth:u}=t,p=l?null===(s=n.get(l))||void 0===s?void 0:s.get(u):void 0;null!=p&&this._collectSegmentDrawingPositions(e,p,r,o,a,p.marginTop,t.marginLeft,t,c);const h=g?null===(d=i.get(g))||void 0===d?void 0:d.get(u):void 0;if(null!=h){const n=t.pageHeight-h.height-h.marginBottom;this._collectSegmentDrawingPositions(e,h,r,o,a,n,t.marginLeft,t,c)}this._collectSegmentDrawingPositions(e,t,r,o,a,t.marginTop,t.marginLeft,void 0,c);for(const n of t.notes??[])this._collectSegmentDrawingPositions(e,n.page,r,o,a,n.top,n.left,void 0,c,{top:n.top,left:n.left})}_collectSegmentDrawingPositions(e,t,n,i,r,o,a,s,d,c){const l=getDocsDrawingPageClipBounds({docsLeft:n,docsTop:i,pageOffsetLeft:this._liquid.x,pageOffsetTop:this._liquid.y,page:s??t});this._calculateDrawingPosition(e,t,n,i,r,o,a,s,d,c,l),this._calculateTableCellDrawingPositions(e,t,n,i,r,o,a,d,l),this._calculateColumnGroupDrawingPositions(e,t,n,i,r,o,a,d,l)}_getStaleNonMultiDrawings(e,t,n){const i=this._drawingManagerService.getDrawingData(e,e)??{};return Object.values(i).filter(e=>e.isMultiTransform!==BooleanNumber.TRUE).filter(e=>null==n||n.has(e.drawingId)).filter(e=>null==t[e.drawingId]).map(t=>({unitId:e,subUnitId:e,drawingId:t.drawingId,behindText:!1,hidden:!0,selectable:!0,transform:t.transform,transforms:t.transforms??[],isMultiTransform:t.isMultiTransform??BooleanNumber.FALSE}))}_handleMultiDrawingsTransform(e){const{scene:t,unitId:n}=this._context,i=t.getTransformerByCreate();e.forEach(e=>{const t=this._drawingManagerService.getDrawingByParam(e);null!=t&&Object.assign(t,e)});const r=[...i.getSelectedObjectMap().keys()],o=Object.values(this._drawingManagerService.getDrawingData(n,n)).filter(e=>e.isMultiTransform===BooleanNumber.TRUE);this._drawingManagerService.removeNotification(o),e.length>0&&this._drawingManagerService.addNotification(e);for(const e of r){const n=t.getObject(e);n&&i.setSelectedControl(n)}}_calculateDrawingPosition(e,t,n,i,r,o,a,s,d=!0,c,l){const{skeDrawings:g}=t,u=this._liquid.x,p=this._liquid.y;this._liquid.translatePagePadding({marginTop:o,marginLeft:a});const h={unitId:e,page:t,docsLeft:n,docsTop:i,pageOffsetLeft:u,pageOffsetTop:p,updateDrawingMap:r,hostPage:s,selectable:d,clipOffset:c,overflowClipBounds:l};g.forEach(e=>this._collectDrawingPosition(e,h)),this._liquid.restorePagePadding({marginTop:o,marginLeft:a})}_collectDrawingPosition(e,t){var n,i;const{aLeft:r,aTop:o,angle:a,drawingId:s,drawingOrigin:d,height:c,width:l}=e,g=getDocsOverlayRuntimeDrawing(d,null===(n=this._context.unit)||void 0===n||null===(i=n.getSnapshot)||void 0===i||null===(i=i.call(n).drawings)||void 0===i?void 0:i[s],e.customBlockRenderViewport?{width:l,height:c}:void 0),{angle:u=a,size:p}=g.docTransform,h=(null==p?void 0:p.height)??c,m=(null==p?void 0:p.width)??l,{left:v,top:f}=t.clipOffset??{},I=getDocsDrawingBehindText({drawingOrigin:g,hostPage:t.hostPage}),{isMultiTransform:_=BooleanNumber.FALSE}=g,D=getDocsDrawingClipPage({drawing:{behindText:I,transform:{width:m,height:h}},hostPage:t.hostPage,page:t.page}),w=getDocsDrawingPageClipBounds({docsLeft:t.docsLeft,docsTop:t.docsTop,pageOffsetLeft:t.pageOffsetLeft,pageOffsetTop:t.pageOffsetTop,clipOffsetLeft:v,clipOffsetTop:f,page:D,drawingLayoutType:g.layoutType,overflowClipBounds:t.overflowClipBounds}),S=getDocsPageRelativeDrawingAnchorPage({page:t.page,clipPage:D,hostPage:t.hostPage,drawingLayoutType:g.layoutType}),T=null==S?void 0:getDocsPageRelativeDrawingLeft({hostPage:S,positionH:g.docTransform.positionH,width:m}),y=null==S?void 0:getDocsPageRelativeDrawingTop({hostPage:S,positionV:g.docTransform.positionV,height:h}),b={left:(T??r)+t.docsLeft+(null==T?this._liquid.x:t.pageOffsetLeft),top:(y??o)+t.docsTop+(null==y?this._liquid.y:t.pageOffsetTop),width:m,height:h,angle:u,flipX:g.docTransform.flipX,flipY:g.docTransform.flipY,clipBounds:w};mergePublishedDrawing(t.updateDrawingMap,{unitId:t.unitId,subUnitId:t.unitId,drawingId:s,behindText:I,selectable:t.selectable,transform:b,transforms:[b],customBlockRenderViewport:e.customBlockRenderViewport,isMultiTransform:_}),g.drawingType===DrawingTypeEnum.DRAWING_GROUP&&this._collectGroupChildren(s,t,I,_,new Set([s]))}_collectGroupChildren(e,t,n,i,r){const{drawings:o}=collectDocDrawings(this._context.unit.getSnapshot());for(const a of Object.values(o)){if(a.groupId!==e||r.has(a.drawingId))continue;r.add(a.drawingId);const{size:o,positionH:s,positionV:d,angle:c,flipX:l,flipY:g}=a.docTransform,u={left:s.posOffset??0,top:d.posOffset??0,width:o.width,height:o.height,angle:c,flipX:l,flipY:g};mergePublishedDrawing(t.updateDrawingMap,{unitId:t.unitId,subUnitId:t.unitId,drawingId:a.drawingId,behindText:n,selectable:t.selectable,transform:u,transforms:[u],isMultiTransform:i}),this._collectGroupChildren(a.drawingId,t,n,i,r)}}_calculateTableCellDrawingPositions(e,t,n,i,r,o,a,s,d){var c;null===(c=t.skeTables)||void 0===c||c.forEach(t=>{t.rows.forEach(c=>{c.cells.forEach(l=>{var g,u,p;if(0===((null===(g=l.skeDrawings)||void 0===g?void 0:g.size)??0)&&0===((null===(u=l.skeTables)||void 0===u?void 0:u.size)??0)&&0===((null===(p=l.skeColumnGroups)||void 0===p?void 0:p.size)??0))return;const h=getDocsTableCellDrawingOffset(e,t,c,l),m=o+h.top,v=a+h.left;this._calculateDrawingPosition(e,l,n,i,r,m,v,void 0,s,{left:v,top:m},d),this._calculateTableCellDrawingPositions(e,l,n,i,r,m,v,s,d),this._calculateColumnGroupDrawingPositions(e,l,n,i,r,m,v,s,d)})})})}_calculateColumnGroupDrawingPositions(e,t,n,i,r,o,a,s,d){var c;null===(c=t.skeColumnGroups)||void 0===c||c.forEach(t=>{t.columns.forEach(c=>{const l=c.page,g=o+t.top+c.top+l.marginTop,u=a+t.left+c.left+l.marginLeft,p={left:u,top:g};this._calculateDrawingPosition(e,l,n,i,r,g,u,void 0,s,p,d),this._calculateTableCellDrawingPositions(e,l,n,i,r,g,u,s,d),this._calculateColumnGroupDrawingPositions(e,l,n,i,r,g,u,s,d)})})}_drawingInitializeListener(){const e=()=>{const e=this._docSkeletonManagerService.getSkeleton();null!=e&&(this._drawingManagerService.initializeNotification(this._context.unitId),this._refreshDrawing(e))};this._lifecycleService.stage>=LifecycleStages.Rendered?this._docSkeletonManagerService.getSkeleton()?e():setTimeout(e,500):this.disposeWithMe(this._lifecycleService.lifecycle$.pipe(filter(e=>e===LifecycleStages.Rendered)).subscribe(e))}};DocDrawingTransformUpdateController=__decorate([__decorateParam(1,Inject(DocSkeletonManagerService)),__decorateParam(2,ICommandService),__decorateParam(3,IEditorService),__decorateParam(4,IDrawingManagerService),__decorateParam(5,Inject(DocRefreshDrawingsService)),__decorateParam(6,IUniverInstanceService),__decorateParam(7,Inject(LifecycleService))],DocDrawingTransformUpdateController);const INLINE_DRAWING_ANCHOR_KEY_PREFIX="__InlineDrawingAnchor__";function getDocsTableCellAnchorContext(e,t){var n;const i=t.parent,r=null==i?void 0:i.parent,o=null==r?void 0:r.parent;return i&&r&&o&&(null===(n=i.cells)||void 0===n?void 0:n.includes(t))?{cell:t,hostPage:o,offset:getDocsTableCellDrawingOffset(e,r,i,t),row:i,table:r}:null}function shouldUseDocsDrawingOuterPageOrigin(e){const{drawing:t,height:n,hostPage:i,page:r,width:o}=e;if(t.layoutType!==PositionedObjectLayoutType.WRAP_NONE)return!1;return null!=getDocsPageRelativeDrawingAnchorPage({page:r,clipPage:getDocsDrawingClipPage({drawing:{behindText:getDocsDrawingBehindText({drawingOrigin:t,hostPage:i}),transform:{width:o,height:n}},hostPage:i,page:r}),hostPage:i})}let DocDrawingTransformerController=class extends Disposable{constructor(e,t,n,i){super(),this._commandService=e,this._univerInstanceService=t,this._drawingManagerService=n,this._renderManagerService=i,_defineProperty(this,"_liquid",new Liquid),_defineProperty(this,"_listenerOnImageMap",new Set),_defineProperty(this,"_transformerCache",new Map),_defineProperty(this,"_anchorShape",void 0),this._init()}_init(){this._listenDrawingFocus()}_listenDrawingFocus(){this.disposeWithMe(this._drawingManagerService.add$.subscribe(e=>{if(0!==e.length)for(const t of e){const{unitId:e}=t;this._listenerOnImageMap.has(e)||(this._listenTransformerChange(e),this._listenerOnImageMap.add(e))}}))}_listenTransformerChange(e){var t;const n=null===(t=this._getSceneAndTransformerByDrawingSearch(e))||void 0===t?void 0:t.transformer;if(null==n)return;this.disposeWithMe(toDisposable(n.changeStart$.subscribe(e=>{this._transformerCache.clear();const{objects:t}=e;for(const e of t.values()){var n;const{oKey:t,width:i,height:r,left:o,top:a,angle:s}=e,d=this._drawingManagerService.getDrawingOKey(t);if(null==d)continue;const c=this._univerInstanceService.getUnit(d.unitId,UniverInstanceType.UNIVER_DOC),l=c?null===(n=findDocDrawing(c.getSnapshot(),d.drawingId))||void 0===n?void 0:n.drawing:void 0;if((null==l?void 0:l.layoutType)===PositionedObjectLayoutType.INLINE)try{e.setOpacity(.2)}catch(e){}null!=l&&this._transformerCache.set(d.drawingId,{drawing:l,top:a,left:o,width:i,height:r,angle:s})}})));const i=throttle(this._updateMultipleDrawingDocTransform.bind(this),50);this.disposeWithMe(toDisposable(n.changing$.subscribe(e=>{const{objects:t,offsetX:n,offsetY:r}=e;if(t.size>1)i(t);else if(1===t.size){const e=this._transformerCache.values().next().value,{width:i,height:o,top:a,left:s,angle:d}=t.values().next().value;if(e&&i===e.width&&o===e.height&&a===e.top&&s===e.left&&d===e.angle)return;e&&e.drawing.layoutType===PositionedObjectLayoutType.INLINE&&null!=n&&null!=r&&this._updateInlineDrawingAnchor(e.drawing,n,r)}}))),this.disposeWithMe(toDisposable(n.changeEnd$.subscribe(e=>{const{objects:t,offsetX:n,offsetY:i}=e;for(const e of t.values()){const t=this._drawingManagerService.getDrawingOKey(e.oKey);if(null==t)continue;const n=this._transformerCache.get(null==t?void 0:t.drawingId);if((null==n?void 0:n.drawing.layoutType)===PositionedObjectLayoutType.INLINE)try{e.setOpacity(1)}catch(e){}}if(this._anchorShape&&this._anchorShape.hide(),t.size>1)this._updateMultipleDrawingDocTransform(t);else if(1===t.size){const e=this._transformerCache.values().next().value,r=t.values().next().value,{width:o,height:a,top:s,left:d,angle:c}=r;if(e&&o===e.width&&a===e.height&&s===e.top&&d===e.left&&c===e.angle)return;e&&e.drawing.layoutType===PositionedObjectLayoutType.INLINE?o!==e.width||a!==e.height||c!==e.angle?this._updateDrawingSize(e,r):null!=n&&null!=i&&this._moveInlineDrawing(e.drawing,n,i):e&&this._nonInlineDrawingTransform(e.drawing,r)}this._transformerCache.clear()})))}_updateMultipleDrawingDocTransform(e){if(e.size<1)return;const t=[];let n,i;for(const r of e.values()){const{oKey:e,left:o,top:a,angle:s}=r;let{width:d,height:c}=r;const l=this._drawingManagerService.getDrawingOKey(e);if(null==l)continue;null==n&&(n=l.unitId),null==i&&(i=l.subUnitId);const g=this._transformerCache.get(l.drawingId);if(null==g)continue;const{drawing:u,top:p,left:h,width:m,height:v,angle:f}=g,{width:I,height:_}=this._getPageContentSize(u);if(d=Math.min(d,I),c=Math.min(c,_),m===d&&v===c||t.push({drawingId:l.drawingId,key:"size",value:{width:d,height:c}}),f!==s&&t.push({drawingId:l.drawingId,key:"angle",value:s}),p!==a||h!==o){const e=a-p,n=o-h;0!==e&&t.push({drawingId:l.drawingId,key:"positionV",value:{relativeFrom:u.docTransform.positionV.relativeFrom,posOffset:u.docTransform.positionV.posOffset+e}}),0!==n&&t.push({drawingId:l.drawingId,key:"positionH",value:{relativeFrom:u.docTransform.positionH.relativeFrom,posOffset:u.docTransform.positionH.posOffset+n}})}}t.length>0&&n&&i&&this._commandService.executeCommand(UpdateDrawingDocTransformCommand.id,{unitId:n,subUnitId:i,drawings:t})}_updateDrawingAnchor(e){if(1!==this._transformerCache.size)return;const t=this._transformerCache.values().next().value,n=e.values().next().value;this._getDrawingAnchor(t.drawing,n)}_updateInlineDrawingAnchor(e,t,n){if(1!==this._transformerCache.size)return;const{contentBoxPointGroup:i}=this._getInlineDrawingAnchor(e,t,n)??{};null!=i&&this._createOrUpdateInlineAnchor(e.unitId,i)}_getInlineDrawingAnchor(e,t,n){var i;const r=this._renderManagerService.getRenderUnitById(e.unitId),o=null==r?void 0:r.with(DocSkeletonManagerService).getSkeleton();if(null==r)return;const{mainComponent:a,scene:s}=r,d=a,c=s.getViewports()[0],{pageLayoutType:l=PageLayoutType.VERTICAL,pageMarginLeft:g,pageMarginTop:u}=d.getOffsetConfig();let p=null,h=!1,m=-1,v="";const f=this._getTransformCoordForDocumentOffset(d,c,t,n);if(null==f)return;const I=null===(i=this._renderManagerService.getRenderUnitById(e.unitId))||void 0===i?void 0:i.with(DocSelectionRenderService);if(null==I)return;const _=null==o?void 0:o.findNodeByCoord(f,l,g,u,{strict:!1,segmentId:I.getSegment(),segmentPage:I.getSegmentPage()});if(_){const{node:e,ratioX:t,segmentPage:n,segmentId:i}=_;h=t<.5,p=e,m=n,v=i}if(null==p)return;const D=null==o?void 0:o.findPositionByGlyph(p,m),w=neoGetDocObject(r);if(null==D||null==o)return;const S={...D,isBack:h},T=w.document.getOffsetConfig(),{cursorList:y,contentBoxPointGroup:b}=new NodePositionConvertToCursor(T,o).getRangePointData(S,S),{startOffset:P}=getOneTextSelectionRange(y)??{};return null!=P?{offset:P,contentBoxPointGroup:b,segmentId:v,segmentPage:m}:void 0}_getDrawingAnchor(e,t){var n,i,r,o;const a=this._renderManagerService.getRenderUnitById(e.unitId),s=null==a?void 0:a.with(DocSkeletonManagerService).getSkeleton(),d=null==s?void 0:s.getSkeletonData();if(null==d||null==a)return;const{pages:c,skeHeaders:l,skeFooters:g}=d,{mainComponent:u,scene:p}=a,h=u,m=p.getViewports()[0],{pageLayoutType:v=PageLayoutType.VERTICAL,pageMarginLeft:f,pageMarginTop:I,docsLeft:_,docsTop:D}=h.getOffsetConfig(),{left:w,top:S,angle:T}=t;let{width:y,height:b}=t;const{positionV:P,positionH:M}=e.docTransform,{width:O,height:C}=this._getPageContentSize(e);y=Math.min(y,O),b=Math.min(b,C);let R=null,E="",U=-1;const x={...e.docTransform,size:{width:y,height:b},angle:T},{x:N,y:A}=p.getViewportScrollXY(m),F=this._getTransformCoordForDocumentOffset(h,m,w-N,S-A);if(null==F)return;const L=null===(n=this._renderManagerService.getRenderUnitById(e.unitId))||void 0===n?void 0:n.with(DocSelectionRenderService);if(null==L)return;const j=null==s?void 0:s.findNodeByCoord(F,v,f,I,{strict:!1,segmentId:L.getSegment(),segmentPage:L.getSegmentPage()});if(j){const{node:e,segmentPage:t,segmentId:n}=j;R=e,U=t,E=n}if(null==R)return;const B=null===(i=R.parent)||void 0===i?void 0:i.parent,W=null==B?void 0:B.parent,k=(null==W||null===(r=W.parent)||void 0===r?void 0:r.top)??0,G=(null==W?void 0:W.lines.find(e=>e.paragraphIndex===(null==B?void 0:B.paragraphIndex)&&e.paragraphStart))??(null==W?void 0:W.lines[0]),V=null==W||null===(o=W.parent)||void 0===o?void 0:o.parent;if(null==B||null==W||null==G||null==V)return;this._liquid.reset();const H=V.type===DocumentSkeletonPageType.CELL?getDocsTableCellAnchorContext(e.unitId,V):null,$=(null==H?void 0:H.hostPage)??V,z=$.type,X=(V.type===DocumentSkeletonPageType.HEADER||V.type===DocumentSkeletonPageType.FOOTER)&&U>-1?c[U]:void 0,q=shouldUseDocsDrawingOuterPageOrigin({drawing:e,height:t.height,hostPage:X,page:V,width:t.width});let K=this._liquid.x,Y=this._liquid.y;for(const e of c){const{headerId:t,footerId:n,pageHeight:i,pageWidth:r,marginLeft:o,marginBottom:a}=e,s=c.indexOf(e);if(U>-1&&s===U){switch(K=this._liquid.x,Y=this._liquid.y,z){case DocumentSkeletonPageType.HEADER:{var J;const e=null===(J=l.get(t))||void 0===J?void 0:J.get(r);if(!e)throw new Error("header skeleton not found");this._liquid.translatePagePadding({marginTop:e.marginTop,marginLeft:o});break}case DocumentSkeletonPageType.FOOTER:{var Z;const e=null===(Z=g.get(n))||void 0===Z?void 0:Z.get(r);if(!e)throw new Error("footer skeleton not found");this._liquid.translatePagePadding({marginTop:i-a+e.marginTop,marginLeft:o});break}default:this._liquid.translatePagePadding(e)}break}if(e===$&&(K=this._liquid.x,Y=this._liquid.y),this._liquid.translatePagePadding(e),e===$)break;this._liquid.restorePagePadding(e),this._liquid.translatePage(e,v,f,I)}var Q;(H&&this._liquid.translate(H.offset.left,H.offset.top),P.relativeFrom===ObjectRelativeFromV.LINE)?R=B.divides[0].glyphGroup[0]:R=(null===(Q=G.divides)||void 0===Q||null===(Q=Q[0])||void 0===Q||null===(Q=Q.glyphGroup)||void 0===Q?void 0:Q[0])??R;switch(x.positionH={relativeFrom:M.relativeFrom,posOffset:w-this._liquid.x-_},M.relativeFrom){case ObjectRelativeFromH.PAGE:q&&(x.positionH.posOffset=w-K-_);break;case ObjectRelativeFromH.MARGIN:x.positionH.posOffset=w-this._liquid.x-_-V.marginLeft;break;case ObjectRelativeFromH.COLUMN:x.positionH.posOffset=w-this._liquid.x-_-W.left}switch(x.positionV={relativeFrom:P.relativeFrom,posOffset:S-this._liquid.y-D},P.relativeFrom){case ObjectRelativeFromV.PAGE:x.positionV.posOffset=q?S-Y-D:S-this._liquid.y-D+V.marginTop;break;case ObjectRelativeFromV.LINE:x.positionV.posOffset=S-this._liquid.y-D-k-B.top;break;case ObjectRelativeFromV.PARAGRAPH:x.positionV.posOffset=S-this._liquid.y-D-k-G.top}if(null==R)return;const ee=null==s?void 0:s.findPositionByGlyph(R,U),te=neoGetDocObject(a);if(null==ee||null==s)return;const ne={...ee,isBack:!0},ie=te.document.getOffsetConfig(),{cursorList:re}=new NodePositionConvertToCursor(ie,s).getRangePointData(ne,ne),{startOffset:oe}=getOneTextSelectionRange(re)??{};return null!=oe?{offset:oe,docTransform:x,segmentId:E,segmentPage:U}:void 0}_updateDrawingSize(e,t){const n=[],{drawing:i,width:r,height:o,angle:a}=e,{unitId:s,subUnitId:d}=i;let{width:c,height:l,angle:g}=t;const{width:u,height:p}=this._getPageContentSize(i);c=Math.min(u,c),l=Math.min(p,l),c===r&&l===o||n.push({drawingId:i.drawingId,key:"size",value:{width:c,height:l}}),g!==a&&n.push({drawingId:i.drawingId,key:"angle",value:g}),n.length>0&&s&&d&&this._commandService.executeCommand(UpdateDrawingDocTransformCommand.id,{unitId:s,subUnitId:d,drawings:n})}_moveInlineDrawing(e,t,n){const{offset:i,segmentId:r,segmentPage:o}=this._getInlineDrawingAnchor(e,t,n)??{};return this._commandService.executeCommand(IMoveInlineDrawingCommand.id,{unitId:e.unitId,subUnitId:e.unitId,drawing:e,offset:i,segmentId:r,segmentPage:o,needRefreshDrawings:null==i})}_limitDrawingInPage(e,t){const n=this._renderManagerService.getRenderUnitById(e.unitId),{left:i,top:r,width:o,height:a,angle:s}=t,d=null==n?void 0:n.with(DocSkeletonManagerService).getSkeleton(),c=null==d?void 0:d.getSkeletonData(),{pages:l}=c??{};if(null==c||null==n||null==l)return{left:i,top:r,width:o,height:a,angle:s};const{mainComponent:g}=n,{top:u,pageLayoutType:p,pageMarginLeft:h,pageMarginTop:m}=g;let v=r;this._liquid.reset();for(const e of l){const{marginBottom:t,pageHeight:n}=e,i=l[l.indexOf(e)+1];null!=i&&(Tools.hasIntersectionBetweenTwoRanges(r,r+a,this._liquid.y+u+n-t,this._liquid.y+u+n+m+i.marginTop)&&(v=r+a/2<this._liquid.y+u+n+m/2?Math.min(r,this._liquid.y+u+n-t-a):Math.max(r,this._liquid.y+u+n+m+i.marginTop)),this._liquid.translatePage(e,p,h,m))}return{left:i,top:v,width:o,height:a,angle:s}}_nonInlineDrawingTransform(e,t,n=!1){const i=e.isMultiTransform===BooleanNumber.TRUE?t:this._limitDrawingInPage(e,t);if(n&&i.top!==t.top)return;const{offset:r,docTransform:o,segmentId:a,segmentPage:s}=this._getDrawingAnchor(e,i)??{};return null==r||null==o?this._updateMultipleDrawingDocTransform(new Map([[e.drawingId,t]])):this._commandService.executeCommand(ITransformNonInlineDrawingCommand.id,{unitId:e.unitId,subUnitId:e.unitId,drawing:e,offset:r,docTransform:o,segmentId:a,segmentPage:s})}_getSceneAndTransformerByDrawingSearch(e){if(null==e)return;const t=this._renderManagerService.getRenderUnitById(e),n=null==t?void 0:t.scene;return null!=n?{scene:n,transformer:n.getTransformerByCreate()}:void 0}_getTransformCoordForDocumentOffset(e,t,n,i){const{documentTransform:r}=e.getOffsetConfig(),o=t.transformVector2SceneCoord(Vector2.FromArray([n,i]));if(o)return r.clone().invert().applyPoint(o)}_createOrUpdateInlineAnchor(e,t){const n=this._renderManagerService.getRenderUnitById(e);if(null==n)return;const{mainComponent:i,scene:r}=n,{docsLeft:o,docsTop:a}=i.getOffsetConfig(),{left:s,top:d,height:c}=getAnchorBounding(t),l=s+o,g=d+a;if(this._anchorShape)return this._anchorShape.transformByState({left:l,top:g,height:c}),void this._anchorShape.show();const u=new Rect("__InlineDrawingAnchor__"+generateRandomId(6),{left:l,top:g,height:c,strokeWidth:2,stroke:getColor(COLORS.darkgray,1),evented:!1});this._anchorShape=u,r.addObject(u,TEXT_RANGE_LAYER_INDEX)}_getPageContentSize(e){const t=this._renderManagerService.getRenderUnitById(e.unitId),n=null==t?void 0:t.with(DocSkeletonManagerService).getSkeleton(),i=null==n?void 0:n.getSkeletonData();if(null==i||null==t)return{width:500,height:500};const{pages:r}=i;let o=null;for(const t of r){if(t.isLayoutPlaceholder||t.isMaterializationPlaceholder)continue;const{skeDrawings:n}=t;if(n.has(e.drawingId)){o=t;break}}if(o){const{pageWidth:e,pageHeight:t,marginLeft:n,marginBottom:i,marginRight:r,marginTop:a}=o;return{width:Math.max(500,e-n-r),height:Math.max(500,t-a-i)}}return{width:500,height:500}}};DocDrawingTransformerController=__decorate([__decorateParam(0,ICommandService),__decorateParam(1,IUniverInstanceService),__decorateParam(2,IDrawingManagerService),__decorateParam(3,IRenderManagerService)],DocDrawingTransformerController);const MIN_OFFSET=-1e3,MAX_OFFSET=1e3;function useDocDrawingPosition(e){const t=useDependency(ICommandService),n=useDependency(LocaleService),i=useDependency(IDrawingManagerService),r=useDependency(IRenderManagerService),o=useDependency(IUniverInstanceService),{drawings:a}=e,{unitId:s}=a[0],d=o.getUnit(s,UniverInstanceType.UNIVER_DOC),c=null==d?void 0:d.getSnapshot().documentStyle.documentFlavor,l=r.getRenderUnitById(s).scene.getTransformerByCreate(),g=[{label:n.t("docs-drawing-ui.image-position.column"),value:String(ObjectRelativeFromH.COLUMN)},{label:n.t("docs-drawing-ui.image-position.page"),value:String(ObjectRelativeFromH.PAGE)},{label:n.t("docs-drawing-ui.image-position.margin"),value:String(ObjectRelativeFromH.MARGIN)}],u=[{label:n.t("docs-drawing-ui.image-position.line"),value:String(ObjectRelativeFromV.LINE),disabled:c===DocumentFlavor.MODERN},{label:n.t("docs-drawing-ui.image-position.page"),value:String(ObjectRelativeFromV.PAGE),disabled:c===DocumentFlavor.MODERN},{label:n.t("docs-drawing-ui.image-position.margin"),value:String(ObjectRelativeFromV.MARGIN),disabled:c===DocumentFlavor.MODERN},{label:n.t("docs-drawing-ui.image-position.paragraph"),value:String(ObjectRelativeFromV.PARAGRAPH)}],[p,h]=useState(!0),[m,v]=useState({relativeFrom:ObjectRelativeFromH.PAGE,posOffset:0}),[f,I]=useState({relativeFrom:ObjectRelativeFromV.PAGE,posOffset:0}),[_,D]=useState(!0),[w,S]=useState(!0);function T(e,n){var o;const a=i.getFocusDrawings();if(0===a.length)return;const d=a.map(e=>({unitId:e.unitId,subUnitId:e.subUnitId,drawingId:e.drawingId}));t.executeCommand(UpdateDrawingDocTransformCommand.id,{unitId:a[0].unitId,subUnitId:a[0].subUnitId,drawings:d.map(t=>({drawingId:t.drawingId,key:e,value:n}))});const c=null===(o=r.getRenderUnitById(s))||void 0===o?void 0:o.with(DocSelectionRenderService);c&&c.blur(),l.refreshControls()}function y(e){var t,n,a,s,d;const c=f.relativeFrom,l=f.posOffset,g=[ObjectRelativeFromV.LINE,ObjectRelativeFromV.PAGE,ObjectRelativeFromV.MARGIN,ObjectRelativeFromV.PARAGRAPH].find(t=>String(t)===e);if(null==g)return;if(c===g)return;const u=i.getFocusDrawings();if(0===u.length)return;const{drawingId:p,unitId:h}=u[0],m=o.getUnit(h,UniverInstanceType.UNIVER_DOC),v=null===(t=r.getRenderUnitById(h))||void 0===t?void 0:t.with(DocSkeletonManagerService).getSkeleton(),I=null===(n=r.getRenderUnitById(h))||void 0===n?void 0:n.with(DocSelectionRenderService),_=null==I?void 0:I.getSegment(),D=null==I?void 0:I.getSegmentPage(),w=null==m||null===(a=m.getSelfOrHeaderFooterModel(_))||void 0===a||null===(a=a.getBody())||void 0===a||null===(a=a.customBlocks)||void 0===a?void 0:a.find(e=>e.blockId===p);if(null==w||null==v||null==I)return;const{startIndex:S}=w,y=v.findNodeByCharIndex(S,_,D),b=null==y||null===(s=y.parent)||void 0===s?void 0:s.parent,P=null==b?void 0:b.parent,M=null==P?void 0:P.lines.find(e=>e.paragraphIndex===(null==b?void 0:b.paragraphIndex)&&e.paragraphStart),O=null==P||null===(d=P.parent)||void 0===d?void 0:d.parent;if(null==y||null==b||null==M||null==P||null==O)return;let C=0;c===ObjectRelativeFromV.PARAGRAPH?C-=M.top:c===ObjectRelativeFromV.LINE?C-=b.top:c===ObjectRelativeFromV.PAGE&&(C+=O.marginTop),g===ObjectRelativeFromV.PARAGRAPH?C+=M.top:g===ObjectRelativeFromV.LINE?C+=b.top:g===ObjectRelativeFromV.PAGE&&(C-=O.marginTop),T("positionV",{relativeFrom:g,posOffset:(l??0)-C})}return useEffect(()=>{function e(e){var t;const n=null==d?void 0:d.getSnapshot(),i=null==n||null===(t=n.drawings)||void 0===t?void 0:t[e.drawingId];if(null==i)return;const{layoutType:r}=i,{positionH:o,positionV:a}=i.docTransform;v(o),I(a),h(r===PositionedObjectLayoutType.INLINE),D(a.relativeFrom===ObjectRelativeFromV.PARAGRAPH||a.relativeFrom===ObjectRelativeFromV.LINE)}function n(){const t=i.getFocusDrawings();0!==t.length&&e(t[0])}n();const r=i.focus$.subscribe(t=>{0!==t.length?(S(!0),e(t[0])):S(!1)}),o=t.onCommandExecuted(async e=>{e.id===RichTextEditingMutation.id&&n()});return()=>{r.unsubscribe(),o.dispose()}},[t,d,i]),{localeService:n,showPanel:w,disabled:p,hPosition:m,vPosition:f,followTextMove:_,documentFlavor:c,HORIZONTAL_RELATIVE_FROM:g,VERTICAL_RELATIVE_FROM:u,handlePositionChange:T,handleHorizontalRelativeFromChange:function(e){var t;const n=m.relativeFrom,o=m.posOffset,a=[ObjectRelativeFromH.COLUMN,ObjectRelativeFromH.PAGE,ObjectRelativeFromH.MARGIN].find(t=>String(t)===e);if(null==a)return;if(n===a)return;const s=i.getFocusDrawings();if(0===s.length)return;const d=s[0].drawingId,c=s[0].unitId;let l=null,g=0;const u=null===(t=r.getRenderUnitById(c))||void 0===t?void 0:t.with(DocSkeletonManagerService).getSkeleton(),p=null==u?void 0:u.getSkeletonData();if(null==p)return;const{pages:h,skeHeaders:v,skeFooters:f}=p;for(const e of h){var I,_;const{marginLeft:t,skeDrawings:n,headerId:i,footerId:r,pageWidth:o}=e;if(n.has(d)){l=n.get(d),g=t;break}const a=null===(I=v.get(i))||void 0===I?void 0:I.get(o);if(null==a?void 0:a.skeDrawings.has(d)){l=null==a?void 0:a.skeDrawings.get(d),g=t;break}const s=null===(_=f.get(r))||void 0===_?void 0:_.get(o);if(null==s?void 0:s.skeDrawings.has(d)){l=null==s?void 0:s.skeDrawings.get(d),g=t;break}}if(null==l)return;let D=0;n===ObjectRelativeFromH.COLUMN?D-=l.columnLeft:n===ObjectRelativeFromH.MARGIN&&(D-=g),a===ObjectRelativeFromH.COLUMN?D+=l.columnLeft:a===ObjectRelativeFromH.MARGIN?D+=g:ObjectRelativeFromH.PAGE,T("positionH",{relativeFrom:a,posOffset:(o??0)-D})},handleVerticalRelativeFromChange:y,handleFollowTextMoveCheck:function(e){y(String(e?ObjectRelativeFromV.PARAGRAPH:ObjectRelativeFromV.PAGE))},MIN_OFFSET:-1e3,MAX_OFFSET:1e3}}function MobileDocDrawingPositionControls(e){const t=useDependency(LocaleService),n=[{title:"docs-drawing-ui.image-position.horizontal",reference:"docs-drawing-ui.image-position.toTheRightOf",position:e.hPosition,options:e.horizontalOptions,onOffsetChange:e.onHorizontalOffsetChange,onReferenceChange:e.onHorizontalReferenceChange},{title:"docs-drawing-ui.image-position.vertical",reference:"docs-drawing-ui.image-position.bellow",position:e.vPosition,options:e.verticalOptions,onOffsetChange:e.onVerticalOffsetChange,onReferenceChange:e.onVerticalReferenceChange}];return jsxs("div",{className:"univer-grid univer-gap-5",children:[n.map(n=>jsxs("section",{className:"univer-grid univer-gap-3",children:[jsx("h3",{className:"univer-m-0 univer-text-sm univer-font-medium",children:t.t(n.title)}),jsxs("label",{className:"univer-grid univer-gap-2 univer-text-sm",children:[t.t("docs-drawing-ui.image-position.absolutePosition"),jsx(InputNumber,{disabled:e.disabled,className:"univer-h-12 univer-w-full",inputClassName:"[&_input]:!univer-h-12 [&_input]:!univer-text-base",controls:!1,min:e.minOffset,max:e.maxOffset,precision:1,value:n.position.posOffset??0,onChange:e=>{null!=e&&n.onOffsetChange(e)}})]}),jsx("div",{className:"univer-grid univer-grid-cols-2 univer-gap-2",role:"group","aria-label":t.t(n.reference),children:n.options.map(t=>jsx(MobileActionRow,{title:t.label,variant:"subtle",disabled:e.disabled||t.disabled,"aria-pressed":String(n.position.relativeFrom)===t.value,className:"univer-px-3 univer-text-center univer-text-sm aria-pressed:!univer-bg-primary-50 aria-pressed:!univer-text-primary-600",onClick:()=>n.onReferenceChange(t.value)},t.value))})]},n.title)),jsx(MobileActionRow,{role:"switch",title:t.t("docs-drawing-ui.image-position.moveObjectWithText"),variant:"subtle","aria-checked":e.followTextMove,disabled:e.disabled||e.disableFollowTextMove,trailing:e.followTextMove?jsx(CheckMarkIcon,{className:"univer-text-primary-600"}):void 0,onClick:()=>e.onFollowTextMoveChange(!e.followTextMove)})]})}function MobileDocDrawingPosition(e){var t;const n=useDependency(IRenderManagerService),i=e.drawings[0];return i&&(null===(t=n.getRenderUnitById(i.unitId))||void 0===t?void 0:t.scene)?jsx(MobileDocDrawingPositionContent,{...e}):null}function MobileDocDrawingPositionContent(e){const{showPanel:t,disabled:n,hPosition:i,vPosition:r,followTextMove:o,documentFlavor:a,HORIZONTAL_RELATIVE_FROM:s,VERTICAL_RELATIVE_FROM:d,handlePositionChange:c,handleHorizontalRelativeFromChange:l,handleVerticalRelativeFromChange:g,handleFollowTextMoveCheck:u,MIN_OFFSET:p,MAX_OFFSET:h}=useDocDrawingPosition(e);return t?jsx(MobileDocDrawingPositionControls,{disabled:n,followTextMove:o,disableFollowTextMove:a===DocumentFlavor.MODERN,hPosition:i,vPosition:r,horizontalOptions:s,verticalOptions:d,minOffset:p,maxOffset:h,onHorizontalOffsetChange:e=>c("positionH",{...i,posOffset:e}),onVerticalOffsetChange:e=>c("positionV",{...r,posOffset:e}),onHorizontalReferenceChange:l,onVerticalReferenceChange:g,onFollowTextMoveChange:u}):null}const MIN_MARGIN=0,MAX_MARGIN=100;function useDocDrawingTextWrap(e){const t=useDependency(ICommandService),n=useDependency(LocaleService),i=useDependency(IDrawingManagerService),r=useDependency(IUniverInstanceService),{drawings:o}=e,{unitId:a}=o[0],s=r.getUnit(a,UniverInstanceType.UNIVER_DOC),[d,c]=useState(!0),[l,g]=useState(!0),[u,p]=useState(!0),[h,m]=useState(TextWrappingStyle.INLINE),[v,f]=useState(WrapTextType.BOTH_SIDES),[I,_]=useState({distT:0,distL:0,distB:0,distR:0}),[D,w]=useState(!0);return useEffect(()=>{function e(){const e=i.getFocusDrawings();0!==e.length&&n(e[0])}function n(e){var t;const n=null==s||null===(t=s.getSnapshot())||void 0===t||null===(t=t.drawings)||void 0===t?void 0:t[e.drawingId];if(null==n)return;const{distT:i=0,distL:r=0,distB:o=0,distR:a=0,layoutType:d=PositionedObjectLayoutType.INLINE,behindDoc:l=BooleanNumber.FALSE,wrapText:u=WrapTextType.BOTH_SIDES}=n;if(_({distT:i,distL:r,distB:o,distR:a}),f(u),c(d!==PositionedObjectLayoutType.WRAP_SQUARE),d===PositionedObjectLayoutType.WRAP_NONE||d===PositionedObjectLayoutType.INLINE?g(!0):g(!1),d===PositionedObjectLayoutType.WRAP_NONE||d===PositionedObjectLayoutType.INLINE||d===PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM?p(!0):p(!1),d===PositionedObjectLayoutType.WRAP_NONE)l===BooleanNumber.TRUE?m(TextWrappingStyle.BEHIND_TEXT):m(TextWrappingStyle.IN_FRONT_OF_TEXT);else switch(d){case PositionedObjectLayoutType.INLINE:m(TextWrappingStyle.INLINE);break;case PositionedObjectLayoutType.WRAP_SQUARE:m(TextWrappingStyle.WRAP_SQUARE);break;case PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM:m(TextWrappingStyle.WRAP_TOP_AND_BOTTOM);break;default:throw new Error(`Unsupported layout type: ${d}`)}}e();const r=i.focus$.subscribe(e=>{0!==e.length?(w(!0),n(e[0])):w(!1)}),o=t.onCommandExecuted(async t=>{t.id===RichTextEditingMutation.id&&e()});return()=>{r.unsubscribe(),o.dispose()}},[t,s,i]),{localeService:n,showPanel:D,wrappingStyle:h,wrapText:v,distToText:I,disableWrapText:d,disableDistTB:l,disableDistLR:u,handleWrappingStyleChange:function(e){const n=Object.values(TextWrappingStyle).find(t=>t===e);if(null==n)return;const r=i.getFocusDrawings();if(0===r.length)return;const{unitId:o,subUnitId:a}=r[0],s=r.map(({unitId:e,subUnitId:t,drawingId:n})=>({unitId:e,subUnitId:t,drawingId:n}));t.executeCommand(UpdateDocDrawingWrappingStyleCommand.id,{unitId:o,subUnitId:a,drawings:s,wrappingStyle:n})},handleWrapTextChange:function(e){const n=[WrapTextType.BOTH_SIDES,WrapTextType.LEFT,WrapTextType.RIGHT].find(t=>String(t)===String(e));if(null==n)return;const r=i.getFocusDrawings();if(0===r.length)return;const o=r.map(e=>({unitId:e.unitId,subUnitId:e.subUnitId,drawingId:e.drawingId}));t.executeCommand(UpdateDocDrawingWrapTextCommand.id,{unitId:r[0].unitId,subUnitId:r[0].subUnitId,drawings:o,wrapText:n})},handleDistToTextChange:function(e,n){if(null==e)return;const r=i.getFocusDrawings();if(0===r.length)return;const o=r.map(e=>({unitId:e.unitId,subUnitId:e.subUnitId,drawingId:e.drawingId}));t.executeCommand(UpdateDocDrawingDistanceCommand.id,{unitId:r[0].unitId,subUnitId:r[0].subUnitId,drawings:o,dist:{[n]:e}})},MIN_MARGIN:0,MAX_MARGIN:100}}const styles=[{value:TextWrappingStyle.INLINE,label:"docs-drawing-ui.image-text-wrap.inline"},{value:TextWrappingStyle.WRAP_SQUARE,label:"docs-drawing-ui.image-text-wrap.square"},{value:TextWrappingStyle.WRAP_TOP_AND_BOTTOM,label:"docs-drawing-ui.image-text-wrap.topAndBottom"},{value:TextWrappingStyle.BEHIND_TEXT,label:"docs-drawing-ui.image-text-wrap.behindText"},{value:TextWrappingStyle.IN_FRONT_OF_TEXT,label:"docs-drawing-ui.image-text-wrap.inFrontText"}],sides=[{value:WrapTextType.BOTH_SIDES,label:"docs-drawing-ui.image-text-wrap.bothSide"},{value:WrapTextType.LEFT,label:"docs-drawing-ui.image-text-wrap.leftOnly"},{value:WrapTextType.RIGHT,label:"docs-drawing-ui.image-text-wrap.rightOnly"}],distances=[{key:"distT",label:"docs-drawing-ui.image-text-wrap.top"},{key:"distB",label:"docs-drawing-ui.image-text-wrap.bottom"},{key:"distL",label:"docs-drawing-ui.image-text-wrap.left"},{key:"distR",label:"docs-drawing-ui.image-text-wrap.right"}];function MobileDocDrawingTextWrapControls(e){const t=useDependency(LocaleService);return jsxs("div",{className:"univer-flex univer-flex-col univer-gap-5",children:[jsx("div",{role:"group","aria-label":t.t("docs-drawing-ui.image-text-wrap.wrappingStyle"),className:"univer-grid univer-gap-2",children:styles.map(n=>jsx(MobileActionRow,{title:t.t(n.label),variant:"subtle","aria-pressed":e.wrappingStyle===n.value,className:"aria-pressed:!univer-bg-primary-50 aria-pressed:!univer-text-primary-600",trailing:e.wrappingStyle===n.value?jsx(CheckMarkIcon,{}):void 0,onClick:()=>e.onStyleChange(n.value)},n.value))}),!e.disableWrapText&&jsxs("section",{className:"univer-grid univer-gap-2",children:[jsx("h3",{className:"univer-m-0 univer-text-sm univer-font-medium",children:t.t("docs-drawing-ui.image-text-wrap.wrapText")}),jsx("div",{className:"univer-grid univer-grid-cols-3 univer-gap-2",children:sides.map(n=>jsx(MobileActionRow,{title:t.t(n.label),variant:"subtle","aria-pressed":e.wrapText===n.value,className:"univer-px-2 univer-text-center univer-text-sm aria-pressed:!univer-bg-primary-50 aria-pressed:!univer-text-primary-600",onClick:()=>e.onWrapTextChange(n.value)},n.value))})]}),(!e.disableDistTB||!e.disableDistLR)&&jsxs("section",{className:"univer-grid univer-gap-3",children:[jsx("h3",{className:"univer-m-0 univer-text-sm univer-font-medium",children:t.t("docs-drawing-ui.image-text-wrap.distanceFromText")}),jsx("div",{className:"univer-grid univer-grid-cols-2 univer-gap-3",children:distances.filter(({key:t})=>"distT"===t||"distB"===t?!e.disableDistTB:!e.disableDistLR).map(({key:n,label:i})=>jsxs("label",{className:"univer-grid univer-gap-2 univer-text-sm",children:[t.t(i),jsx(InputNumber,{className:"univer-h-12 univer-w-full",inputClassName:"[&_input]:!univer-h-12 [&_input]:!univer-text-base",controls:!1,min:e.minMargin,max:e.maxMargin,precision:1,value:e.distToText[n]??0,onChange:t=>e.onDistanceChange(t,n)})]},n))})]})]})}function MobileDocDrawingTextWrap(e){var t;const n=useDependency(IRenderManagerService),i=e.drawings[0];return i&&(null===(t=n.getRenderUnitById(i.unitId))||void 0===t?void 0:t.scene)?jsx(MobileDocDrawingTextWrapContent,{...e}):null}function MobileDocDrawingTextWrapContent(e){const{showPanel:t,wrappingStyle:n,wrapText:i,distToText:r,disableWrapText:o,disableDistTB:a,disableDistLR:s,handleWrappingStyleChange:d,handleWrapTextChange:c,handleDistToTextChange:l,MIN_MARGIN:g,MAX_MARGIN:u}=useDocDrawingTextWrap(e);return t?jsx(MobileDocDrawingTextWrapControls,{wrappingStyle:n,wrapText:i,distToText:r,minMargin:g,maxMargin:u,disableWrapText:o,disableDistTB:a,disableDistLR:s,onStyleChange:d,onWrapTextChange:c,onDistanceChange:l}):null}const tabs=[{value:"image",label:"docs-drawing-ui.title"},{value:"wrap",label:"docs-drawing-ui.image-text-wrap.title"},{value:"position",label:"docs-drawing-ui.image-position.title"}];function MobileDocDrawingPanel(){const e=useDependency(IDrawingManagerService),t=useObservable(e.focus$,e.getFocusDrawings())??[],n=useDependency(LocaleService),i=useDependency(ICommandService),[r,o]=useState("image");return jsxs("div",{className:"univer-flex univer-min-w-0 univer-flex-col univer-gap-4 univer-pb-2",children:[jsx("div",{className:"univer-grid univer-grid-cols-3 univer-gap-2",role:"group",children:tabs.map(e=>jsx(MobileActionRow,{"aria-pressed":r===e.value,title:n.t(e.label),variant:"subtle",className:"univer-min-w-0 univer-px-2 univer-text-center univer-text-sm aria-pressed:!univer-bg-primary-50 aria-pressed:!univer-text-primary-600",onClick:()=>o(e.value)},e.value))}),jsxs("div",{children:["image"===r&&jsx(DrawingCommonPanel,{drawings:t,hasAlign:!1,hasCropper:!0,hasGroup:!1,hasTransform:!1,onCropStart:()=>i.executeCommand(SidebarDocDrawingOperation.id,{value:"close"})}),"wrap"===r&&jsx(MobileDocDrawingTextWrap,{drawings:t}),"position"===r&&jsx(MobileDocDrawingPosition,{drawings:t})]})]})}let MobileComponentsController=class extends Disposable{constructor(e){super(),this.disposeWithMe(e.register(COMPONENT_DOC_DRAWING_PANEL,MobileDocDrawingPanel))}};MobileComponentsController=__decorate([__decorateParam(0,Inject(ComponentManager))],MobileComponentsController);const SidebarDocDrawingMobileOperation={id:SidebarDocDrawingOperation.id,type:CommandType.COMMAND,handler:async(e,t)=>{const n=e.get(ISidebarService),i=e.get(LocaleService),r=e.get(IDrawingManagerService);switch(t.value){case"open":{const e={layout:"canvas",header:{title:i.t("docs-drawing-ui.panel.title")},children:{label:COMPONENT_DOC_DRAWING_PANEL},onClose:()=>{r.focusDrawing(null)},width:360};n.open(e);break}default:n.close()}return!0}};var DocDrawingFloatingToolbarAdapterService=class{constructor(){_defineProperty(this,"_adapters",[])}registerAdapter(e){return this._adapters.push(e),toDisposable(()=>{const t=this._adapters.indexOf(e);t>=0&&this._adapters.splice(t,1)})}getItems(e){for(const t of this._adapters){const n=t.getItems(e);if(n)return[...n].sort((e,t)=>e.index-t.index)}return null}};let MobileDocDrawingPopupMenuController=class extends RxDisposable{constructor(e,t,n,i,r,o,a,s,d,c,l){super(),this._drawingManagerService=e,this._canvasPopManagerService=t,this._renderManagerService=n,this._univerInstanceService=i,this._contextService=r,this._drawingAdapterService=o,this._docDrawingService=a,this._floatingToolbarAdapterService=s,this._commandService=d,this._menuManagerService=c,this._permissionService=l,_defineProperty(this,"_initImagePopupMenu",new Set),_defineProperty(this,"_embeddedRenderUnits",new Set),_defineProperty(this,"_popupMenuListeners",new Map),_defineProperty(this,"_disposePopupsByUnit",new Map),_defineProperty(this,"_popupTargetsByUnit",new Map),_defineProperty(this,"_isDrawingPanelOpen",!1),this._init()}_init(){this.disposeWithMe(this._commandService.onCommandExecuted(e=>{const t=[...this._popupTargetsByUnit.values()].some(t=>{const n=this._docDrawingService.getDrawingByParam(t),i=n&&this._drawingAdapterService.getEditDrawingCommandInfo({...t,drawing:n});return(null==i?void 0:i.commandId)===e.id});if((e.id===EditDocDrawingOperation.id||t)&&(this._isDrawingPanelOpen=!0,this._clearPopups(void 0,!0)),e.id===SidebarDocDrawingMobileOperation.id){const t=e.params;this._isDrawingPanelOpen="open"===(null==t?void 0:t.value),this._isDrawingPanelOpen&&this._clearPopups(void 0,!0)}})),this.disposeWithMe(this._drawingManagerService.focus$.subscribe(e=>{0===e.length&&(this._isDrawingPanelOpen=!1)})),this.disposeWithMe(this._drawingManagerService.remove$.subscribe(e=>{for(const n of e)for(const[e,i]of this._popupTargetsByUnit)if(i.unitId===n.unitId&&i.subUnitId===n.subUnitId&&i.drawingId===n.drawingId){var t;this._clearPopups(e,!0),null===(t=this._renderManagerService.getRenderUnitById(e))||void 0===t||t.scene.getTransformerByCreate().clearSelectedObjects()}})),this.disposeWithMe(this._permissionService.permissionPointUpdate$.subscribe(()=>{for(const[e,t]of this._popupTargetsByUnit)this._canEditDrawing(t.unitId,t.drawingId)||this._clearPopups(e,!0)})),this.disposeWithMe(this._univerInstanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_DOC).pipe(takeUntil(this.dispose$)).subscribe(e=>this._create(e))),this.disposeWithMe(this._univerInstanceService.getTypeOfUnitDisposed$(UniverInstanceType.UNIVER_DOC).pipe(takeUntil(this.dispose$)).subscribe(e=>this._dispose(e))),this.disposeWithMe(this._renderManagerService.created$.pipe(takeUntil(this.dispose$)).subscribe(e=>{e.type!==UniverInstanceType.UNIVER_DOC||e.isMainScene||(this._embeddedRenderUnits.add(e.unitId),this._create(this._univerInstanceService.getUnit(e.unitId,UniverInstanceType.UNIVER_DOC)))})),this.disposeWithMe(this._renderManagerService.disposed$.pipe(takeUntil(this.dispose$)).subscribe(e=>{this._embeddedRenderUnits.delete(e)&&this._disposePopupMenuListener(e)})),this._univerInstanceService.getAllUnitsForType(UniverInstanceType.UNIVER_DOC).forEach(e=>this._create(e))}_dispose(e){const t=e.getUnitId();this._clearPopups(t,!0),this._disposePopupMenuListener(t),this._renderManagerService.removeRender(t)}_clearPopups(e,t=!1){if(null==e)return void[...this._disposePopupsByUnit.keys()].forEach(e=>this._clearPopups(e,t));const n=this._disposePopupsByUnit.get(e);if(n){for(let e=n.length-1;e>=0;e-=1){const i=n[e];(t||i.canDispose())&&(i.dispose(),n.splice(e,1))}0===n.length&&(this._disposePopupsByUnit.delete(e),this._popupTargetsByUnit.delete(e))}}_getDisposePopups(e){const t=this._disposePopupsByUnit.get(e);if(t)return t;const n=[];return this._disposePopupsByUnit.set(e,n),n}_create(e){if(!e)return;const t=e.getUnitId();if(!isInternalEditorID(t)&&this._renderManagerService.has(t)&&!this._initImagePopupMenu.has(t)){const e=this._popupMenuListener(t);e&&(this._popupMenuListeners.set(t,e),this._initImagePopupMenu.add(t))}}_disposePopupMenuListener(e){var t;null===(t=this._popupMenuListeners.get(e))||void 0===t||t.dispose(),this._popupMenuListeners.delete(e),this._initImagePopupMenu.delete(e),this._clearPopups(e,!0)}_hasCropObject(e){const t=e.getAllObjects();for(const e of t)if(e instanceof ImageCropperObject)return!0;return!1}_handleClearControl(e,t,n){this._clearPopups(e,n),queueMicrotask(()=>{t.getSelectedObjectMap().size>0||(this._contextService.setContextValue(FOCUSING_COMMON_DRAWINGS,!1),this._drawingManagerService.focusDrawing(null))})}_registerDrawingPopup(e,t,n){this.disposeWithMe(t),this._getDisposePopups(e).push(t),this._popupTargetsByUnit.set(e,n),this._drawingManagerService.getFocusDrawings().find(e=>e.unitId===n.unitId&&e.subUnitId===n.subUnitId&&e.drawingId===n.drawingId)||this._drawingManagerService.focusDrawing([n])}_isSamePopupTarget(e,t){return(null==e?void 0:e.unitId)===t.unitId&&e.subUnitId===t.subUnitId&&e.drawingId===t.drawingId}_popupMenuListener(e){var t;const n=null===(t=this._renderManagerService.getRenderUnitById(e))||void 0===t?void 0:t.scene;if(!n)return;const i=n.getTransformerByCreate(),r=[i.createControl$.subscribe(()=>{if(this._hasCropObject(n))return void this._clearPopups(e,!0);const t=i.getSelectedObjectMap();if(this._isDrawingPanelOpen||t.size>1)return void this._clearPopups(e,this._isDrawingPanelOpen);const r=t.values().next().value;if(!r)return void this._clearPopups(e);const o=this._drawingManagerService.getDrawingOKey(r.oKey);if(!o||o.drawingType===DrawingTypeEnum.DRAWING_DOM||o.drawingType===DrawingTypeEnum.DRAWING_SHAPE)return void this._clearPopups(e);const{unitId:a,subUnitId:s,drawingId:d,drawingType:c}=o;if(!this._canEditDrawing(a,d))return void this._clearPopups(e,!0);const l=this._disposePopupsByUnit.get(e),g=this._popupTargetsByUnit.get(e),u={unitId:a,subUnitId:s,drawingId:d};if(this._isSamePopupTarget(g,u)&&l&&l.length>0)return;this._clearPopups(e,null!=g);const p=c===DrawingTypeEnum.DRAWING_IMAGE,h=c===DrawingTypeEnum.DRAWING_CHART,m=this._canvasPopManagerService.attachPopupToObject(r,{componentKey:p||h?COMPONENT_MOBILE_IMAGE_POPUP_MENU:MOBILE_DOC_ELEMENT_MENU,requiresStableLayout:!1,direction:p||h?"top-center":"horizontal",offset:p||h?[0,8]:[2,0],extraProps:{onClose:()=>this._clearPopups(e,!0),onEdit:()=>{const t=this._docDrawingService.getDrawingByParam(o),n=t&&this._drawingAdapterService.getEditDrawingCommandInfo({unitId:a,subUnitId:s,drawing:t});return this._clearPopups(e,!0),this._commandService.executeCommand((null==n?void 0:n.commandId)??EditDocDrawingOperation.id,(null==n?void 0:n.commandParams)??{unitId:a,subUnitId:s,drawingId:d})},onDelete:()=>(this._clearPopups(e,!0),this._commandService.executeCommand(RemoveDocDrawingCommand.id,{unitId:a,drawings:[{unitId:a,subUnitId:s,drawingId:d}]})),menuItems:this._getDrawingPopupMenuItems(a,s,d,c),variant:p?"doc-floating-toolbar":h?"doc-chart-floating-toolbar":void 0,unitId:a,subUnitId:s,drawingId:d}},a);this._registerDrawingPopup(e,m,{unitId:a,subUnitId:s,drawingId:d})}),i.clearControl$.subscribe(t=>this._handleClearControl(e,i,t)),i.changing$.subscribe(()=>{this._clearPopups(e,!0)})],o=toDisposable(()=>r.forEach(e=>e.unsubscribe()));return this.disposeWithMe(o),o}_canEditDrawing(e,t){const n=this._univerInstanceService.getUnit(e,UniverInstanceType.UNIVER_DOC);if(!n)return!1;const i=getDocumentDrawingSegmentId(n,t);return canEditDocumentTargets(this._permissionService,e,[...getDocumentEntityParentPermissionObjectIds(n,i,"drawing",t),getDocumentEntityPermissionObjectId(i,"drawing",t)])}_getDrawingPopupMenuItems(e,t,n,i){const r=this._docDrawingService.getDrawingByParam({unitId:e,subUnitId:t,drawingId:n}),o=r?this._floatingToolbarAdapterService.getItems({unitId:e,subUnitId:t,drawing:r}):null,a=r?this._drawingAdapterService.getEditDrawingCommandInfo({unitId:e,subUnitId:t,drawing:r}):null,s=[{label:(null==a?void 0:a.label)??"docs-drawing-ui.image-popup.edit",index:0,commandId:(null==a?void 0:a.commandId)??EditDocDrawingOperation.id,commandParams:(null==a?void 0:a.commandParams)??{unitId:e,subUnitId:t,drawingId:n},disable:(null==a?void 0:a.disable)??i===DrawingTypeEnum.DRAWING_DOM,hideOnClick:!0,icon:"DrawingEditIcon"},{label:"docs-drawing-ui.image-popup.crop",index:1,commandId:OpenImageCropOperation.id,commandParams:{unitId:e,subUnitId:t,drawingId:n},disable:i===DrawingTypeEnum.DRAWING_DOM,icon:"DrawingCropIcon"},{label:"docs-drawing-ui.image-popup.delete",index:2,commandId:RemoveDocDrawingCommand.id,commandParams:{unitId:e,drawings:[{unitId:e,subUnitId:t,drawingId:n}]},disable:!1,icon:"DrawingDeleteIcon"},{label:"docs-drawing-ui.image-popup.reset",index:3,commandId:ImageResetSizeOperation.id,commandParams:[{unitId:e,subUnitId:t,drawingId:n}],disable:!0}];return i===DrawingTypeEnum.DRAWING_IMAGE?s.slice(0,3):i===DrawingTypeEnum.DRAWING_CHART?[{...s[0],label:"docs-drawing-ui.image-popup.edit"},s[2]]:[...o??s,...this._getFloatingObjectMenuItems()]}_getFloatingObjectMenuItems(){return this._menuManagerService.getFlatMenuByPositionKey(FloatingObjectToolbarPosition.DOC).flatMap(({item:e},t)=>e&&e.type===MenuItemType.BUTTON&&e.title&&"string"==typeof e.icon?[{type:"button",label:e.title,index:100+t,commandId:e.commandId??e.id,commandParams:"function"==typeof e.params?e.params():e.params,disable:!1,icon:e.icon}]:[])}};MobileDocDrawingPopupMenuController=__decorate([__decorateParam(0,IDrawingManagerService),__decorateParam(1,Inject(DocCanvasPopManagerService)),__decorateParam(2,IRenderManagerService),__decorateParam(3,IUniverInstanceService),__decorateParam(4,IContextService),__decorateParam(5,IDocDrawingAdapterService),__decorateParam(6,IDocDrawingService),__decorateParam(7,Inject(DocDrawingFloatingToolbarAdapterService)),__decorateParam(8,ICommandService),__decorateParam(9,IMenuManagerService),__decorateParam(10,IPermissionService)],MobileDocDrawingPopupMenuController);let MobileDocDrawingUIController=class extends Disposable{constructor(e,t){super(),this._menuManagerService=e,this._commandService=t,this._initCommands(),this._initMenus()}_initCommands(){[InsertDocImageCommand,InsertDocRectangleShapeCommand,InsertDocEllipseShapeCommand,UpdateDocDrawingDistanceCommand,UpdateDocDrawingWrapTextCommand,IMoveInlineDrawingCommand,ITransformNonInlineDrawingCommand,SidebarDocDrawingMobileOperation,ClearDocDrawingTransformerOperation,EditDocDrawingOperation,GroupDocDrawingCommand,UngroupDocDrawingCommand,MoveDocDrawingsCommand,DeleteDocDrawingsCommand].forEach(e=>this.disposeWithMe(this._commandService.registerCommand(e)))}_initMenus(){this._menuManagerService.mergeMenu(menuSchema)}};MobileDocDrawingUIController=__decorate([__decorateParam(0,IMenuManagerService),__decorateParam(1,ICommandService)],MobileDocDrawingUIController);var MobileDocDrawingUpdateRenderController=class extends DocDrawingUpdateRenderController{_getTransformerInteractionOptions(){return{moveOnlyWhenSelected:!0}}_isDocumentInteractionFocusing(e){return!0}};let UniverDocsDrawingMobileUIPlugin=class extends Plugin{constructor(e=defaultPluginConfig,t,n,i){super(),this._config=e,this._injector=t,this._renderManagerSrv=n,this._configService=i;const{...r}=merge({},defaultPluginConfig,this._config);this._configService.setConfig("docs-drawing-ui.config",r)}onStarting(){[[MobileComponentsController],[MobileDocDrawingUIController],[MobileDocDrawingPopupMenuController],[DocDrawingTransformerController],[DocDrawingAddRemoveController],[DocRefreshDrawingsService],[DocDrawingFloatingToolbarAdapterService],[DocFloatDomController],[DocDrawingPrintingController]].forEach(e=>this._injector.add(e)),this._injector.get(MobileComponentsController)}onReady(){[[DocDrawingUpdateRenderController,{useClass:MobileDocDrawingUpdateRenderController}],[DocDrawingTransformUpdateController]].forEach(e=>this._renderManagerSrv.registerRenderModule(UniverInstanceType.UNIVER_DOC,e)),this._injector.get(DocDrawingAddRemoveController),this._injector.get(MobileDocDrawingUIController),this._injector.get(DocDrawingTransformerController),this._injector.get(DocDrawingPrintingController)}onRendered(){this._injector.get(MobileDocDrawingPopupMenuController),this._injector.get(DocFloatDomController)}};_defineProperty(UniverDocsDrawingMobileUIPlugin,"type",UniverInstanceType.UNIVER_DOC),_defineProperty(UniverDocsDrawingMobileUIPlugin,"pluginName","DOC_DRAWING_UI_PLUGIN"),_defineProperty(UniverDocsDrawingMobileUIPlugin,"packageName",name),_defineProperty(UniverDocsDrawingMobileUIPlugin,"version",version),UniverDocsDrawingMobileUIPlugin=__decorate([DependentOn(UniverDocsPlugin,UniverDrawingPlugin,UniverRenderEnginePlugin,UniverDocsDrawingPlugin,UniverDocsMobileUIPlugin,UniverDrawingMobileUIPlugin),__decorateParam(1,Inject(Injector)),__decorateParam(2,IRenderManagerService),__decorateParam(3,IConfigService)],UniverDocsDrawingMobileUIPlugin);const DocDrawingPosition=e=>{var t;const n=useDependency(IRenderManagerService),i=e.drawings[0],r=i?null===(t=n.getRenderUnitById(i.unitId))||void 0===t?void 0:t.scene:void 0;return i&&r?jsx(DocDrawingPositionContent,{...e}):null};function DocDrawingPositionContent(e){const{localeService:t,showPanel:n,disabled:i,hPosition:r,vPosition:o,followTextMove:a,HORIZONTAL_RELATIVE_FROM:s,VERTICAL_RELATIVE_FROM:d,handlePositionChange:c,handleHorizontalRelativeFromChange:l,handleVerticalRelativeFromChange:g,handleFollowTextMoveCheck:u,MIN_OFFSET:p,MAX_OFFSET:h}=useDocDrawingPosition(e);return jsxs("div",{className:clsx("univer-grid univer-gap-2 univer-py-2 univer-text-gray-400",{"univer-hidden":!n}),children:[jsx("header",{className:"univer-text-gray-600 dark:!univer-text-gray-200",children:jsx("div",{children:t.t("docs-drawing-ui.image-position.title")})}),jsx("div",{className:"univer-text-gray-600 dark:!univer-text-gray-200",children:jsx("div",{children:t.t("docs-drawing-ui.image-position.horizontal")})}),jsxs("div",{className:"univer-grid univer-grid-cols-2 univer-gap-2 [&>div]:univer-grid [&>div]:univer-gap-2",children:[jsxs("div",{children:[jsx("span",{children:t.t("docs-drawing-ui.image-position.absolutePosition")}),jsx(InputNumber,{min:p,max:h,precision:1,disabled:i,value:r.posOffset,onChange:e=>{null!=e&&c("positionH",{relativeFrom:r.relativeFrom,posOffset:e})}})]}),jsxs("div",{children:[jsx("span",{children:t.t("docs-drawing-ui.image-position.toTheRightOf")}),jsx(Select,{value:String(r.relativeFrom),disabled:i,options:s,onChange:l})]})]}),jsx("div",{className:"univer-text-gray-600 dark:!univer-text-gray-200",children:jsx("div",{children:t.t("docs-drawing-ui.image-position.vertical")})}),jsxs("div",{className:"univer-grid univer-grid-cols-2 univer-gap-2 [&>div]:univer-grid [&>div]:univer-gap-2",children:[jsxs("div",{children:[jsx("span",{children:t.t("docs-drawing-ui.image-position.absolutePosition")}),jsx(InputNumber,{min:p,max:h,precision:1,disabled:i,value:o.posOffset,onChange:e=>{null!=e&&c("positionV",{relativeFrom:o.relativeFrom,posOffset:e})}})]}),jsxs("div",{children:[jsx("span",{children:t.t("docs-drawing-ui.image-position.bellow")}),jsx(Select,{disabled:i,value:String(o.relativeFrom),options:d,onChange:g})]})]}),jsx("div",{className:"univer-text-gray-600 dark:!univer-text-gray-200",children:jsx("div",{children:t.t("docs-drawing-ui.image-position.options")})}),jsx("div",{children:jsx(Checkbox,{disabled:i,checked:a,onChange:u,children:t.t("docs-drawing-ui.image-position.moveObjectWithText")})})]})}const DocDrawingTextWrap=e=>{var t;const n=useDependency(IRenderManagerService),i=e.drawings[0],r=i?null===(t=n.getRenderUnitById(i.unitId))||void 0===t?void 0:t.scene:void 0;return i&&r?jsx(DocDrawingTextWrapContent,{...e}):null};function DocDrawingTextWrapContent(e){const{localeService:t,showPanel:n,wrappingStyle:i,wrapText:r,distToText:o,disableWrapText:a,disableDistTB:s,disableDistLR:d,handleWrappingStyleChange:c,handleWrapTextChange:l,handleDistToTextChange:g,MIN_MARGIN:u,MAX_MARGIN:p}=useDocDrawingTextWrap(e);return jsxs("div",{className:clsx("univer-grid univer-gap-2 univer-py-2 univer-text-gray-400",{"univer-hidden":!n}),children:[jsx("header",{className:"univer-text-gray-600 dark:!univer-text-gray-200",children:jsx("div",{children:t.t("docs-drawing-ui.image-text-wrap.title")})}),jsx("div",{className:"univer-text-gray-600 dark:!univer-text-gray-200",children:jsx("div",{children:t.t("docs-drawing-ui.image-text-wrap.wrappingStyle")})}),jsx("div",{children:jsxs(RadioGroup,{value:i,onChange:c,direction:"vertical",children:[jsx(Radio,{value:TextWrappingStyle.INLINE,children:t.t("docs-drawing-ui.image-text-wrap.inline")}),jsx(Radio,{value:TextWrappingStyle.WRAP_SQUARE,children:t.t("docs-drawing-ui.image-text-wrap.square")}),jsx(Radio,{value:TextWrappingStyle.WRAP_TOP_AND_BOTTOM,children:t.t("docs-drawing-ui.image-text-wrap.topAndBottom")}),jsx(Radio,{value:TextWrappingStyle.BEHIND_TEXT,children:t.t("docs-drawing-ui.image-text-wrap.behindText")}),jsx(Radio,{value:TextWrappingStyle.IN_FRONT_OF_TEXT,children:t.t("docs-drawing-ui.image-text-wrap.inFrontText")})]})}),jsx("div",{className:"univer-text-gray-600 dark:!univer-text-gray-200",children:jsx("div",{children:t.t("docs-drawing-ui.image-text-wrap.wrapText")})}),jsx("div",{children:jsxs(RadioGroup,{disabled:a,value:String(r),onChange:l,direction:"horizontal",children:[jsx(Radio,{value:String(WrapTextType.BOTH_SIDES),children:t.t("docs-drawing-ui.image-text-wrap.bothSide")}),jsx(Radio,{value:String(WrapTextType.LEFT),children:t.t("docs-drawing-ui.image-text-wrap.leftOnly")}),jsx(Radio,{value:String(WrapTextType.RIGHT),children:t.t("docs-drawing-ui.image-text-wrap.rightOnly")})]})}),jsx("div",{className:"univer-text-gray-600 dark:!univer-text-gray-200",children:jsx("div",{children:t.t("docs-drawing-ui.image-text-wrap.distanceFromText")})}),jsxs("div",{className:"univer-grid univer-grid-cols-2 univer-gap-2 [&>div]:univer-grid [&>div]:univer-gap-2",children:[jsxs("div",{children:[jsx("span",{children:t.t("docs-drawing-ui.image-text-wrap.top")}),jsx(InputNumber,{min:u,max:p,disabled:s,precision:1,value:o.distT,onChange:e=>{g(e,"distT")}})]}),jsxs("div",{children:[jsx("span",{children:t.t("docs-drawing-ui.image-text-wrap.left")}),jsx(InputNumber,{min:u,max:p,disabled:d,precision:1,value:o.distL,onChange:e=>{g(e,"distL")}})]})]}),jsxs("div",{className:"univer-grid univer-grid-cols-2 univer-gap-2 [&>div]:univer-grid [&>div]:univer-gap-2",children:[jsxs("div",{children:[jsx("span",{children:t.t("docs-drawing-ui.image-text-wrap.bottom")}),jsx(InputNumber,{min:u,max:p,disabled:s,precision:1,value:o.distB,onChange:e=>{g(e,"distB")}})]}),jsxs("div",{children:[jsx("span",{children:t.t("docs-drawing-ui.image-text-wrap.right")}),jsx(InputNumber,{min:u,max:p,disabled:d,precision:1,value:o.distR,onChange:e=>{g(e,"distR")}})]})]})]})}const DocDrawingPanel=()=>{const e=useDependency(IDrawingManagerService),t=useObservable(()=>e.focus$,e.getFocusDrawings(),!1,[e]);return!!(null==t?void 0:t.length)&&jsxs("div",{className:"univer-text-sm",children:[jsx(DrawingCommonPanel,{drawings:t,hasAlign:!1,hasCropper:!0,hasGroup:!1,hasTransform:!1}),jsx(DocDrawingTextWrap,{drawings:t}),jsx(DocDrawingPosition,{drawings:t})]})};let ComponentsController=class extends Disposable{constructor(e){super(),this._componentManager=e,this._registerComponents()}_registerComponents(){this.disposeWithMe(this._componentManager.register(COMPONENT_DOC_DRAWING_PANEL,DocDrawingPanel))}};function whenDocDrawingFocused(e){return e.getContextValue(FOCUSING_DOC)&&e.getContextValue(FOCUSING_UNIVER_EDITOR)&&e.getContextValue(FOCUSING_COMMON_DRAWINGS)}ComponentsController=__decorate([__decorateParam(0,Inject(ComponentManager))],ComponentsController);const MoveDrawingDownShortcutItem={id:MoveDocDrawingsCommand.id,description:"docs-drawing-ui.shortcut.drawing-move-down",group:"4_drawing-view",groupTitle:"docs-drawing-ui.shortcut.drawing-view",binding:KeyCode.ARROW_DOWN,priority:100,preconditions:whenDocDrawingFocused,staticParameters:{direction:Direction.DOWN}},MoveDrawingUpShortcutItem={id:MoveDocDrawingsCommand.id,description:"docs-drawing-ui.shortcut.drawing-move-up",group:"4_drawing-view",groupTitle:"docs-drawing-ui.shortcut.drawing-view",binding:KeyCode.ARROW_UP,priority:100,preconditions:whenDocDrawingFocused,staticParameters:{direction:Direction.UP}},MoveDrawingLeftShortcutItem={id:MoveDocDrawingsCommand.id,description:"docs-drawing-ui.shortcut.drawing-move-left",group:"4_drawing-view",groupTitle:"docs-drawing-ui.shortcut.drawing-view",binding:KeyCode.ARROW_LEFT,priority:100,preconditions:whenDocDrawingFocused,staticParameters:{direction:Direction.LEFT}},MoveDrawingRightShortcutItem={id:MoveDocDrawingsCommand.id,description:"docs-drawing-ui.shortcut.drawing-move-right",group:"4_drawing-view",groupTitle:"docs-drawing-ui.shortcut.drawing-view",binding:KeyCode.ARROW_RIGHT,priority:100,preconditions:whenDocDrawingFocused,staticParameters:{direction:Direction.RIGHT}},DeleteDrawingsShortcutItem={id:DeleteDocDrawingsCommand.id,description:"docs-drawing-ui.shortcut.drawing-delete",group:"4_drawing-view",groupTitle:"docs-drawing-ui.shortcut.drawing-view",preconditions:whenDocDrawingFocused,binding:KeyCode.DELETE,mac:KeyCode.BACKSPACE};let DocDrawingUIController=class extends Disposable{constructor(e,t,n){super(),this._menuManagerService=e,this._commandService=t,this._shortcutService=n,this._init()}_initCustomComponents(){}_initMenus(){this._menuManagerService.mergeMenu(menuSchema)}_initCommands(){[InsertDocImageCommand,InsertDocRectangleShapeCommand,InsertDocEllipseShapeCommand,UpdateDocDrawingDistanceCommand,UpdateDocDrawingWrapTextCommand,IMoveInlineDrawingCommand,ITransformNonInlineDrawingCommand,SidebarDocDrawingOperation,ClearDocDrawingTransformerOperation,EditDocDrawingOperation,GroupDocDrawingCommand,UngroupDocDrawingCommand,MoveDocDrawingsCommand,DeleteDocDrawingsCommand].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()}};DocDrawingUIController=__decorate([__decorateParam(0,IMenuManagerService),__decorateParam(1,ICommandService),__decorateParam(2,IShortcutService)],DocDrawingUIController);let DocDrawingPopupMenuController=class extends RxDisposable{constructor(e,t,n,i,r,o,a,s,d,c,l,g){super(),this._drawingManagerService=e,this._canvasPopManagerService=t,this._renderManagerService=n,this._univerInstanceService=i,this._contextService=r,this._drawingAdapterService=o,this._docDrawingService=a,this._floatingToolbarAdapterService=s,this._commandService=d,this._menuManagerService=c,this._permissionService=l,this._contextMenuService=g,_defineProperty(this,"_initImagePopupMenu",new Set),_defineProperty(this,"_embeddedRenderUnits",new Set),_defineProperty(this,"_popupMenuListeners",new Map),_defineProperty(this,"_disposePopupsByUnit",new Map),_defineProperty(this,"_popupTargetsByUnit",new Map),_defineProperty(this,"_isDrawingPanelOpen",!1),this._init()}_init(){this.disposeWithMe(this._commandService.onCommandExecuted(e=>{const t=[...this._popupTargetsByUnit.values()].some(t=>{const n=this._docDrawingService.getDrawingByParam(t),i=n&&this._drawingAdapterService.getEditDrawingCommandInfo({...t,drawing:n});return(null==i?void 0:i.commandId)===e.id});if((e.id===EditDocDrawingOperation.id||t)&&(this._isDrawingPanelOpen=!0,this._clearPopups(void 0,!0)),e.id===SidebarDocDrawingOperation.id){const t=e.params;this._isDrawingPanelOpen="open"===(null==t?void 0:t.value),this._isDrawingPanelOpen&&this._clearPopups(void 0,!0)}})),this.disposeWithMe(this._drawingManagerService.focus$.subscribe(e=>{0===e.length&&(this._isDrawingPanelOpen=!1)})),this.disposeWithMe(this._drawingManagerService.remove$.subscribe(e=>{for(const n of e)for(const[e,i]of this._popupTargetsByUnit)if(i.unitId===n.unitId&&i.subUnitId===n.subUnitId&&i.drawingId===n.drawingId){var t;this._clearPopups(e,!0),null===(t=this._renderManagerService.getRenderUnitById(e))||void 0===t||t.scene.getTransformerByCreate().clearSelectedObjects()}})),this.disposeWithMe(this._permissionService.permissionPointUpdate$.subscribe(()=>{for(const[e,t]of this._popupTargetsByUnit)this._canEditDrawing(t.unitId,t.drawingId)||this._clearPopups(e,!0)})),this.disposeWithMe(this._univerInstanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_DOC).pipe(takeUntil(this.dispose$)).subscribe(e=>this._create(e))),this.disposeWithMe(this._univerInstanceService.getTypeOfUnitDisposed$(UniverInstanceType.UNIVER_DOC).pipe(takeUntil(this.dispose$)).subscribe(e=>this._dispose(e))),this.disposeWithMe(this._renderManagerService.created$.pipe(takeUntil(this.dispose$)).subscribe(e=>{e.type!==UniverInstanceType.UNIVER_DOC||e.isMainScene||(this._embeddedRenderUnits.add(e.unitId),this._create(this._univerInstanceService.getUnit(e.unitId,UniverInstanceType.UNIVER_DOC)))})),this.disposeWithMe(this._renderManagerService.disposed$.pipe(takeUntil(this.dispose$)).subscribe(e=>{this._embeddedRenderUnits.delete(e)&&this._disposePopupMenuListener(e)})),this._univerInstanceService.getAllUnitsForType(UniverInstanceType.UNIVER_DOC).forEach(e=>this._create(e))}_dispose(e){const t=e.getUnitId();this._clearPopups(t,!0),this._disposePopupMenuListener(t),this._renderManagerService.removeRender(t)}_clearPopups(e,t=!1){if(null==e)return void[...this._disposePopupsByUnit.keys()].forEach(e=>this._clearPopups(e,t));const n=this._disposePopupsByUnit.get(e);if(n){for(let e=n.length-1;e>=0;e-=1){const i=n[e];(t||i.canDispose())&&(i.dispose(),n.splice(e,1))}0===n.length&&(this._disposePopupsByUnit.delete(e),this._popupTargetsByUnit.delete(e))}}_getDisposePopups(e){const t=this._disposePopupsByUnit.get(e);if(t)return t;const n=[];return this._disposePopupsByUnit.set(e,n),n}_create(e){if(!e)return;const t=e.getUnitId();if(!isInternalEditorID(t)&&this._renderManagerService.has(t)&&!this._initImagePopupMenu.has(t)){const e=this._popupMenuListener(t);e&&(this._popupMenuListeners.set(t,e),this._initImagePopupMenu.add(t))}}_disposePopupMenuListener(e){var t;null===(t=this._popupMenuListeners.get(e))||void 0===t||t.dispose(),this._popupMenuListeners.delete(e),this._initImagePopupMenu.delete(e),this._clearPopups(e,!0)}_hasCropObject(e){const t=e.getAllObjects();for(const e of t)if(e instanceof ImageCropperObject)return!0;return!1}_handleClearControl(e,t,n){this._clearPopups(e,n),queueMicrotask(()=>{t.getSelectedObjectMap().size>0||(this._contextService.setContextValue(FOCUSING_COMMON_DRAWINGS,!1),this._drawingManagerService.focusDrawing(null))})}_registerDrawingPopup(e,t,n){this.disposeWithMe(t),this._getDisposePopups(e).push(t),this._popupTargetsByUnit.set(e,n),this._drawingManagerService.getFocusDrawings().find(e=>e.unitId===n.unitId&&e.subUnitId===n.subUnitId&&e.drawingId===n.drawingId)||this._drawingManagerService.focusDrawing([n])}_isSamePopupTarget(e,t){return(null==e?void 0:e.unitId)===t.unitId&&e.subUnitId===t.subUnitId&&e.drawingId===t.drawingId}_popupMenuListener(e){var t;const n=null===(t=this._renderManagerService.getRenderUnitById(e))||void 0===t?void 0:t.scene;if(!n)return;const i=n.getTransformerByCreate(),r=[i.changeEnd$.subscribe(({event:e})=>{var t;if(2!==e.button)return;const n=[...i.getSelectedObjectMap().values()].map(e=>this._drawingManagerService.getDrawingOKey(e.oKey));0===n.length||1===n.length&&(null===(t=n[0])||void 0===t?void 0:t.drawingType)!==DrawingTypeEnum.DRAWING_GROUP||n.some(e=>!e||!this._canEditDrawing(e.unitId,e.drawingId))||this._contextMenuService.triggerContextMenu(e,ContextMenuPosition.DRAWING)}),i.createControl$.subscribe(()=>{if(this._hasCropObject(n))return void this._clearPopups(e,!0);const t=i.getSelectedObjectMap();if(this._isDrawingPanelOpen||t.size>1)return void this._clearPopups(e,this._isDrawingPanelOpen);const r=t.values().next().value;if(!r)return void this._clearPopups(e);const o=this._drawingManagerService.getDrawingOKey(r.oKey);if(!o||o.drawingType===DrawingTypeEnum.DRAWING_DOM||o.drawingType===DrawingTypeEnum.DRAWING_SHAPE)return void this._clearPopups(e);const{unitId:a,subUnitId:s,drawingId:d,drawingType:c}=o;if(!this._canEditDrawing(a,d))return void this._clearPopups(e,!0);const l=this._disposePopupsByUnit.get(e),g=this._popupTargetsByUnit.get(e),u={unitId:a,subUnitId:s,drawingId:d};if(this._isSamePopupTarget(g,u)&&l&&l.length>0)return;this._clearPopups(e,null!=g);const p=c===DrawingTypeEnum.DRAWING_IMAGE,h=c===DrawingTypeEnum.DRAWING_CHART,m=this._canvasPopManagerService.attachPopupToObject(r,{componentKey:COMPONENT_IMAGE_POPUP_MENU,requiresStableLayout:!1,direction:p||h?"top-center":"horizontal",offset:p||h?[0,8]:[2,0],extraProps:{menuItems:this._getDrawingPopupMenuItems(a,s,d,c),variant:p?"doc-floating-toolbar":h?"doc-chart-floating-toolbar":void 0,unitId:a,subUnitId:s,drawingId:d}},a);this._registerDrawingPopup(e,m,{unitId:a,subUnitId:s,drawingId:d})}),i.clearControl$.subscribe(t=>this._handleClearControl(e,i,t)),i.changing$.subscribe(()=>{this._clearPopups(e,!0)})],o=toDisposable(()=>r.forEach(e=>e.unsubscribe()));return this.disposeWithMe(o),o}_canEditDrawing(e,t){const n=this._univerInstanceService.getUnit(e,UniverInstanceType.UNIVER_DOC);if(!n)return!1;const i=getDocumentDrawingSegmentId(n,t);return canEditDocumentTargets(this._permissionService,e,[...getDocumentEntityParentPermissionObjectIds(n,i,"drawing",t),getDocumentEntityPermissionObjectId(i,"drawing",t)])}_getDrawingPopupMenuItems(e,t,n,i){const r=this._docDrawingService.getDrawingByParam({unitId:e,subUnitId:t,drawingId:n}),o=r?this._floatingToolbarAdapterService.getItems({unitId:e,subUnitId:t,drawing:r}):null,a=r?this._drawingAdapterService.getEditDrawingCommandInfo({unitId:e,subUnitId:t,drawing:r}):null,s=[{label:(null==a?void 0:a.label)??"docs-drawing-ui.image-popup.edit",index:0,commandId:(null==a?void 0:a.commandId)??EditDocDrawingOperation.id,commandParams:(null==a?void 0:a.commandParams)??{unitId:e,subUnitId:t,drawingId:n},disable:(null==a?void 0:a.disable)??i===DrawingTypeEnum.DRAWING_DOM,hideOnClick:!0,icon:"DrawingEditIcon"},{label:"docs-drawing-ui.image-popup.crop",index:1,commandId:OpenImageCropOperation.id,commandParams:{unitId:e,subUnitId:t,drawingId:n},disable:i===DrawingTypeEnum.DRAWING_DOM,icon:"DrawingCropIcon"},{label:"docs-drawing-ui.image-popup.delete",index:2,commandId:RemoveDocDrawingCommand.id,commandParams:{unitId:e,drawings:[{unitId:e,subUnitId:t,drawingId:n}]},disable:!1,icon:"DrawingDeleteIcon"},{label:"docs-drawing-ui.image-popup.reset",index:3,commandId:ImageResetSizeOperation.id,commandParams:[{unitId:e,subUnitId:t,drawingId:n}],disable:!0}];return[...o??s,...this._getFloatingObjectMenuItems()]}_getFloatingObjectMenuItems(){return this._menuManagerService.getFlatMenuByPositionKey(FloatingObjectToolbarPosition.DOC).flatMap(({item:e},t)=>e&&e.type===MenuItemType.BUTTON&&e.title&&"string"==typeof e.icon?[{type:"button",label:e.title,index:100+t,commandId:e.commandId??e.id,commandParams:"function"==typeof e.params?e.params():e.params,disable:!1,icon:e.icon}]:[])}};DocDrawingPopupMenuController=__decorate([__decorateParam(0,IDrawingManagerService),__decorateParam(1,Inject(DocCanvasPopManagerService)),__decorateParam(2,IRenderManagerService),__decorateParam(3,IUniverInstanceService),__decorateParam(4,IContextService),__decorateParam(5,IDocDrawingAdapterService),__decorateParam(6,IDocDrawingService),__decorateParam(7,Inject(DocDrawingFloatingToolbarAdapterService)),__decorateParam(8,ICommandService),__decorateParam(9,IMenuManagerService),__decorateParam(10,IPermissionService),__decorateParam(11,IContextMenuService)],DocDrawingPopupMenuController);let UniverDocsDrawingUIPlugin=class extends Plugin{constructor(e=defaultPluginConfig,t,n,i){super(),this._config=e,this._injector=t,this._renderManagerSrv=n,this._configService=i;const{...r}=merge({},defaultPluginConfig,this._config);this._configService.setConfig("docs-drawing-ui.config",r)}onStarting(){[[ComponentsController],[DocDrawingUIController],[DocDrawingPopupMenuController],[DocDrawingTransformerController],[DocDrawingAddRemoveController],[DocRefreshDrawingsService],[DocDrawingFloatingToolbarAdapterService],[DocFloatDomController],[DocDrawingPrintingController]].forEach(e=>this._injector.add(e)),this._injector.get(ComponentsController)}onReady(){[[DocDrawingUpdateRenderController],[DocDrawingTransformUpdateController]].forEach(e=>this._renderManagerSrv.registerRenderModule(UniverInstanceType.UNIVER_DOC,e)),this._injector.get(DocDrawingAddRemoveController),this._injector.get(DocDrawingUIController),this._injector.get(DocDrawingTransformerController),this._injector.get(DocDrawingPrintingController)}onRendered(){this._injector.get(DocDrawingPopupMenuController),this._injector.get(DocFloatDomController)}};_defineProperty(UniverDocsDrawingUIPlugin,"type",UniverInstanceType.UNIVER_DOC),_defineProperty(UniverDocsDrawingUIPlugin,"pluginName","DOC_DRAWING_UI_PLUGIN"),_defineProperty(UniverDocsDrawingUIPlugin,"packageName",name),_defineProperty(UniverDocsDrawingUIPlugin,"version",version),UniverDocsDrawingUIPlugin=__decorate([DependentOn(UniverDocsPlugin,UniverDrawingPlugin,UniverRenderEnginePlugin,UniverDocsDrawingPlugin,UniverDocsUIPlugin,UniverDrawingUIPlugin),__decorateParam(1,Inject(Injector)),__decorateParam(2,IRenderManagerService),__decorateParam(3,IConfigService)],UniverDocsDrawingUIPlugin);export{ClearDocDrawingTransformerOperation,DOCS_IMAGE_MENU_ID,DOCS_SHAPE_BELOW_MENU_ID,DOCS_SHAPE_MENU_ID,DeleteDocDrawingsCommand,DocDrawingFloatingToolbarAdapterService,DocDrawingPosition,DocDrawingTextWrap,DocFloatDomController,menuSchema as DocsDrawingUIMenuSchema,EditDocDrawingOperation,GroupDocDrawingCommand,InsertDocEllipseShapeCommand,InsertDocImageCommand,InsertDocRectangleShapeCommand,MobileDocDrawingPosition,MobileDocDrawingTextWrap,MoveDocDrawingsCommand,SidebarDocDrawingOperation,UngroupDocDrawingCommand,UniverDocsDrawingMobileUIPlugin,UniverDocsDrawingUIPlugin};
//# sourceMappingURL=/sm/4e8838f02454394fdb66beb54ba88dfe26206ff7735795f99cd48e104049d94a.map