@univerjs/docs-ui 0.2.5 → 0.2.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/index.js +4 -4
- package/lib/es/index.js +2029 -1971
- package/lib/umd/index.js +4 -4
- package/package.json +15 -15
package/lib/umd/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
(function(I,s){typeof exports=="object"&&typeof module<"u"?s(exports,require("@univerjs/core"),require("@univerjs/ui"),require("@univerjs/docs"),require("@univerjs/engine-render"),require("rxjs"),require("react"),require("@univerjs/design"),require("clsx")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","@univerjs/ui","@univerjs/docs","@univerjs/engine-render","rxjs","react","@univerjs/design","clsx"],s):(I=typeof globalThis<"u"?globalThis:I||self,s(I.UniverDocsUi={},I.UniverCore,I.UniverUi,I.UniverDocs,I.UniverEngineRender,I.rxjs,I.React,I.UniverDesign,I.clsx))})(this,function(I,s,l,d,C,M,B,H,gt){"use strict";var Vi=Object.defineProperty;var ji=(I,s,l)=>s in I?Vi(I,s,{enumerable:!0,configurable:!0,writable:!0,value:l}):I[s]=l;var y=(I,s,l)=>ji(I,typeof s!="symbol"?s+"":s,l);var he;function A(i){return i.getContextValue(s.FOCUSING_DOC)&&i.getContextValue(s.FOCUSING_UNIVER_EDITOR)&&!i.getContextValue(s.FOCUSING_COMMON_DRAWINGS)}function _t(i){return i.getContextValue(s.FOCUSING_DOC)&&i.getContextValue(s.FOCUSING_UNIVER_EDITOR)&&!i.getContextValue(s.FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE)&&!i.getContextValue(s.FOCUSING_COMMON_DRAWINGS)}const mt=10,St=6;function ft(){return s.Tools.generateRandomId(St)}function vt(i){const e=i.match(/data-copy-id="([^\s]+)"/);return e&&e[1]?e[1]:null}class Ct{constructor(){y(this,"_cache",new s.LRUMap(mt))}set(e,t){this._cache.set(e,t)}get(e){return this._cache.get(e)}clear(){this._cache.clear()}}const xe=new Ct;function pe(i){const e=i.style,t={},n=i.tagName.toLowerCase();switch(n){case"b":case"em":case"strong":{t.bl=s.BooleanNumber.TRUE;break}case"s":{t.st={s:s.BooleanNumber.TRUE};break}case"u":{t.ul={s:s.BooleanNumber.TRUE};break}case"i":{t.it=s.BooleanNumber.TRUE;break}case"sub":case"sup":{t.va=n==="sup"?s.BaselineOffset.SUPERSCRIPT:s.BaselineOffset.SUBSCRIPT;break}}for(let o=0;o<e.length;o++){const r=e[o],a=e.getPropertyValue(r);switch(r){case"font-family":{t.ff=a;break}case"font-size":{const c=Number.parseInt(a);Number.isNaN(c)||(a.endsWith("pt")?t.fs=c:a.endsWith("px")&&(t.fs=C.pixelToPt(c)));break}case"font-style":{a==="italic"&&(t.it=s.BooleanNumber.TRUE);break}case"font-weight":{(Number(a)>400||String(a)==="bold")&&(t.bl=s.BooleanNumber.TRUE);break}case"text-decoration":{/underline/.test(a)?t.ul={s:s.BooleanNumber.TRUE}:/overline/.test(a)?t.ol={s:s.BooleanNumber.TRUE}:/line-through/.test(a)&&(t.st={s:s.BooleanNumber.TRUE});break}case"color":{const c=new s.ColorKit(a);c.isValid&&(t.cl={rgb:c.toRgbString()});break}case"background-color":{const c=new s.ColorKit(a);c.isValid&&(t.bg={rgb:c.toRgbString()});break}}}return t}function It(i){const e=new DOMParser,t=`<x-univer id="univer-root">${i}</x-univer>`;return e.parseFromString(t,"text/html").querySelector("#univer-root")}function Fe(i,e){const t=i.tagName.toLowerCase();return typeof e=="string"?t===e:Array.isArray(e)?e.some(n=>n===t):e(i)}const ue=class ue{constructor(){y(this,"_styleCache",new Map);y(this,"_styleRules",[]);y(this,"_afterProcessRules",[])}static use(e){if(this._pluginList.includes(e))throw new Error(`Univer paste plugin ${e.name} already added`);this._pluginList.push(e)}convert(e){const t=ue._pluginList.find(r=>r.checkPasteType(e)),n=It(e),o={dataStream:"",textRuns:[]};return t&&(this._styleRules=[...t.stylesRules],this._afterProcessRules=[...t.afterProcessRules]),this._styleCache.clear(),this._process(null,n==null?void 0:n.childNodes,o),this._styleCache.clear(),this._styleRules=[],this._afterProcessRules=[],o}_process(e,t,n){var o,r,a;for(const c of t)if(c.nodeType===Node.TEXT_NODE){if(((o=c.nodeValue)==null?void 0:o.trim())==="")continue;let u=(r=c.nodeValue)==null?void 0:r.replace(/[\r\n]/g,""),h;if(e&&e.nodeType===Node.ELEMENT_NODE&&e.tagName.toUpperCase()==="A"){const _=s.Tools.generateRandomId();u=`${s.DataStreamTreeTokenType.CUSTOM_RANGE_START}${u}${s.DataStreamTreeTokenType.CUSTOM_RANGE_END}`,n.customRanges=[...(a=n.customRanges)!=null?a:[],{startIndex:n.dataStream.length,endIndex:n.dataStream.length+u.length-1,rangeId:_,rangeType:s.CustomRangeType.HYPERLINK}],n.payloads={...n.payloads,[_]:e.href}}e&&this._styleCache.has(e)&&(h=this._styleCache.get(e)),n.dataStream+=u,h&&Object.getOwnPropertyNames(h).length&&n.textRuns.push({st:n.dataStream.length-u.length,ed:n.dataStream.length,ts:h})}else{if(s.skipParseTagNames.includes(c.nodeName.toLowerCase()))continue;if(c.nodeType===Node.ELEMENT_NODE){const u=e?this._styleCache.get(e):{},h=this._styleRules.find(({filter:p})=>Fe(c,p)),_=h?h.getStyle(c):pe(c);this._styleCache.set(c,{...u,..._});const{childNodes:m}=c;this._process(c,m,n);const S=this._afterProcessRules.find(({filter:p})=>Fe(c,p));S&&S.handler(n,c)}}}};y(ue,"_pluginList",[]);let j=ue;const Le={name:"univer-doc-paste-plugin-lark",checkPasteType(i){return/lark-record-clipboard/i.test(i)},stylesRules:[{filter:["s"],getStyle(i){const e=pe(i);return{st:{s:s.BooleanNumber.TRUE},...e}}}],afterProcessRules:[{filter(i){return i.tagName==="DIV"&&/ace-line/i.test(i.className)},handler(i){i.paragraphs==null&&(i.paragraphs=[]),i.paragraphs.push({startIndex:i.dataStream.length}),i.dataStream+="\r"}}]};function Be(i){const e=i.style,t={};for(let n=0;n<e.length;n++){const o=e[n],r=e.getPropertyValue(o);switch(o){case"margin-top":{const a=Number.parseInt(r);t.spaceAbove={v:/pt/.test(r)?C.ptToPixel(a):a};break}case"margin-bottom":{const a=Number.parseInt(r);t.spaceBelow={v:/pt/.test(r)?C.ptToPixel(a):a};break}case"line-height":{const a=Number.parseFloat(r);t.lineSpacing=a;break}}}return Object.getOwnPropertyNames(t).length?t:null}const we={name:"univer-doc-paste-plugin-word",checkPasteType(i){return/word|mso/i.test(i)},stylesRules:[{filter:["b"],getStyle(i){const e=pe(i);return{bl:s.BooleanNumber.TRUE,...e}}}],afterProcessRules:[{filter(i){return i.tagName==="P"},handler(i,e){i.paragraphs==null&&(i.paragraphs=[]);const t={startIndex:i.dataStream.length},n=Be(e);n&&(t.paragraphStyle=n),i.paragraphs.push(t),i.dataStream+="\r"}}]},$e={name:"univer-doc-paste-plugin-univer",checkPasteType(i){return/UniverNormal/i.test(i)},stylesRules:[],afterProcessRules:[{filter(i){return i.tagName==="P"&&/UniverNormal/i.test(i.className)},handler(i,e){i.paragraphs==null&&(i.paragraphs=[]);const t={startIndex:i.dataStream.length},n=Be(e);n&&(t.paragraphStyle=n),i.paragraphs.push(t),i.dataStream+="\r"}}]};function He(i,e){const{st:t,ed:n,ts:o={}}=e,{ff:r,fs:a,it:c,bl:u,ul:h,st:_,ol:m,bg:S,cl:p,va:f}=o;let g=i.slice(t,n);const v=[];return c===s.BooleanNumber.TRUE&&(g=`<i>${g}</i>`),f===s.BaselineOffset.SUPERSCRIPT?g=`<sup>${g}</sup>`:f===s.BaselineOffset.SUBSCRIPT&&(g=`<sub>${g}</sub>`),(h==null?void 0:h.s)===s.BooleanNumber.TRUE&&(g=`<u>${g}</u>`),(_==null?void 0:_.s)===s.BooleanNumber.TRUE&&(g=`<s>${g}</s>`),u===s.BooleanNumber.TRUE&&(g=`<strong>${g}</strong>`),r&&v.push(`font-family: ${r}`),p&&v.push(`color: ${p.rgb}`),a&&v.push(`font-size: ${a}pt`),m&&v.push("text-decoration: overline"),S&&v.push(`background: ${S.rgb}`),v.length?`<span style="${v.join("; ")};">${g}</span>`:g}function ge(i,e,t){const{dataStream:n,textRuns:o=[]}=i;let r=e;const a=[];for(const c of o){const{st:u,ed:h}=c;s.Tools.hasIntersectionBetweenTwoRanges(e,t,u,h)&&(u>r?(a.push(n.slice(r,u)),a.push(He(n,{...c,ed:Math.min(h,t)}))):a.push(He(n,{...c,st:r,ed:Math.min(h,t)}))),r=Math.max(e,Math.min(h,t))}return r!==t&&a.push(n.slice(r,t)),a.join("")}function Ve(i,e=!0){var t;if(e&&((t=i.paragraphs)!=null&&t.length)){const{dataStream:n,paragraphs:o=[]}=i;let r="",a=-1;for(const c of o){const{startIndex:u,paragraphStyle:h={}}=c,{spaceAbove:_,spaceBelow:m,lineSpacing:S}=h,p=[];_!=null&&(typeof _=="number"?p.push(`margin-top: ${_}px`):p.push(`margin-top: ${_.v}px`)),m!=null&&(typeof m=="number"?p.push(`margin-bottom: ${m}px`):p.push(`margin-bottom: ${m.v}px`)),S!=null&&p.push(`line-height: ${S}`),u>a+1?r+=`<p class="UniverNormal" ${p.length?`style="${p.join("; ")};"`:""}>${ge(i,a+1,u)}</p>`:r+=`<p class="UniverNormal" ${p.length?`style="${p.join("; ")};"`:""}></p>`,a=u}return a!==n.length&&(r+=ge(i,a,n.length)),r}else return ge(i,0,i.dataStream.length)}class Ot{convert(e){if(e.length===0)throw new Error("The bodyList length at least to be 1");if(e.length===1)return Ve(e[0]);let t="";for(const n of e)t+='<p className="UniverNormal">',t+=Ve(n,!1),t+="</p>";return t}}var Tt=Object.defineProperty,Mt=Object.getOwnPropertyDescriptor,Et=(i,e,t,n)=>{for(var o=n>1?void 0:n?Mt(e,t):e,r=i.length-1,a;r>=0;r--)(a=i[r])&&(o=(n?a(e,t,o):a(o))||o);return n&&o&&Tt(e,t,o),o},W=(i,e)=>(t,n)=>e(t,n,i);j.use(we),j.use(Le),j.use($e);const G=s.createIdentifier("doc.clipboard-service");let _e=class extends s.Disposable{constructor(e,t,n,o,r,a){super();y(this,"_clipboardHooks",[]);y(this,"_htmlToUDM",new j);y(this,"_umdToHtml",new Ot);this._univerInstanceService=e,this._logService=t,this._commandService=n,this._clipboardInterfaceService=o,this._textSelectionManagerService=r,this._docCustomRangeService=a}async copy(e=s.SliceBodyType.copy){const t=this._getDocumentBodyInRanges(e);if(t.length===0)return!1;try{const n=this._textSelectionManagerService.getActiveRange(),o=!!(n!=null&&n.segmentId);this._setClipboardData(t,!o)}catch(n){return this._logService.error("[DocClipboardService] copy failed",n),!1}return!0}async cut(){return this._cut()}async paste(e){const t=await this._generateBodyFromClipboardItems(e);return this._paste(t)}async legacyPaste(e,t){const n=this._generateBodyFromHtmlAndText(e,t);return this._paste(n)}async _cut(){var r;const{segmentId:e,endOffset:t,style:n}=(r=this._textSelectionManagerService.getActiveRange())!=null?r:{},o=this._textSelectionManagerService.getCurrentSelections();if(e==null&&this._logService.error("[DocClipboardController] segmentId is not existed"),t==null||o==null)return!1;this.copy(s.SliceBodyType.cut);try{let a=t;for(const u of o){const{startOffset:h,endOffset:_}=u;h==null||_==null||_<=t&&(a-=_-h)}const c=[{startOffset:a,endOffset:a,style:n}];return this._commandService.executeCommand(d.CutContentCommand.id,{segmentId:e,textRanges:c})}catch{return this._logService.error("[DocClipboardController] cut content failed"),!1}}async _paste(e){var h,_;let t=s.normalizeBody(e);const n=(h=this._univerInstanceService.getCurrentUnitForType(s.UniverInstanceType.UNIVER_DOC))==null?void 0:h.getUnitId();if(!n)return!1;this._clipboardHooks.forEach(m=>{m.onBeforePaste&&(t=m.onBeforePaste(t))}),t.customRanges=(_=t.customRanges)==null?void 0:_.map(m=>this._docCustomRangeService.copyCustomRange(n,m));const o=this._textSelectionManagerService.getActiveRange(),{segmentId:r,endOffset:a,style:c}=o||{},u=this._textSelectionManagerService.getCurrentSelections();if(r==null&&this._logService.error("[DocClipboardController] segmentId does not exist!"),a==null||u==null)return!1;try{let m=a;for(const p of u){const{startOffset:f,endOffset:g}=p;f==null||g==null||g<=a&&(m+=t.dataStream.length-(g-f))}const S=[{startOffset:m,endOffset:m,style:c}];return this._commandService.executeCommand(d.InnerPasteCommand.id,{body:t,segmentId:r,textRanges:S})}catch{return this._logService.error("[DocClipboardController]","clipboard is empty."),!1}}async _setClipboardData(e,t=!0){const n=ft(),o=e.length>1?e.map(a=>a.dataStream).join(`
|
|
2
|
-
`):e[0].dataStream;let r=this._umdToHtml.convert(e);return e.length===1&&t&&(r=r.replace(/(<[a-z]+)/,(a,c)=>`${c} data-copy-id="${n}"`),xe.set(n,e[0])),this._clipboardInterfaceService.write(o,r)}addClipboardHook(e){return this._clipboardHooks.push(e),s.toDisposable(()=>{const t=this._clipboardHooks.indexOf(e);t>-1&&this._clipboardHooks.splice(t,1)})}_getDocumentBodyInRanges(e){const t=this._textSelectionManagerService.getCurrentSelections(),n=this._textSelectionManagerService.getActiveRange(),o=this._univerInstanceService.getCurrentUniverDocInstance(),r=[],a=o==null?void 0:o.getBody();if(t==null||o==null||a==null||n==null)return r;const{segmentId:c}=n;for(const u of t){const{startOffset:h,endOffset:_,collapsed:m}=u;if(m||h==null||_==null)continue;const S=d.getDeleteSelection({startOffset:h,endOffset:_,collapsed:m},a),p=o.getSelfOrHeaderFooterModel(c).sliceBody(S.startOffset,S.endOffset,e);if(p!=null){if(p.customRanges){const f=[];p.customRanges.forEach(O=>{O.startIndex===O.endIndex&&f.push(O)}),p.customRanges=p.customRanges.filter(O=>f.indexOf(O)===-1);let g="",v=0;f.forEach(O=>{g+=p.dataStream.slice(v,O.endIndex),v=O.endIndex+1}),g+=p.dataStream.slice(v,p.dataStream.length),p.dataStream=g}r.push(p)}}return r}async _generateBodyFromClipboardItems(e){try{let t="",n="";for(const o of e)for(const r of o.types)r===l.PLAIN_TEXT_CLIPBOARD_MIME_TYPE?n=await o.getType(r).then(a=>a&&a.text()):r===l.HTML_CLIPBOARD_MIME_TYPE&&(t=await o.getType(r).then(a=>a&&a.text()));return this._generateBodyFromHtmlAndText(t,n)}catch(t){return Promise.reject(t)}}_generateBody(e){const t=e.replace(/\n/g,"\r");if(!e.includes("\r")&&s.Tools.isLegalUrl(e)){const o=s.Tools.generateRandomId(),r=this._univerInstanceService.getCurrentUnitForType(s.UniverInstanceType.UNIVER_DOC),a=`${s.DataStreamTreeTokenType.CUSTOM_RANGE_START}${t}${s.DataStreamTreeTokenType.CUSTOM_RANGE_END}`,c=this._docCustomRangeService.copyCustomRange(r.getUnitId(),{startIndex:0,endIndex:a.length-1,rangeId:o,rangeType:s.CustomRangeType.HYPERLINK,data:e});return{dataStream:a,customRanges:[c]}}const n=[];for(let o=0;o<t.length;o++)t[o]==="\r"&&n.push({startIndex:o});return{dataStream:t,paragraphs:n}}_generateBodyFromHtmlAndText(e,t){if(!e){if(t)return this._generateBody(t);throw new Error("[DocClipboardService] html and text cannot be both empty!")}const n=vt(e);if(n){const o=xe.get(n);if(o)return o}return this._htmlToUDM.convert(e)}};_e=Et([W(0,s.IUniverInstanceService),W(1,s.ILogService),W(2,s.ICommandService),W(3,l.IClipboardInterfaceService),W(4,s.Inject(d.TextSelectionManagerService)),W(5,s.Inject(d.DocCustomRangeService))],_e);var Rt=Object.defineProperty,bt=Object.getOwnPropertyDescriptor,Dt=(i,e,t,n)=>{for(var o=n>1?void 0:n?bt(e,t):e,r=i.length-1,a;r>=0;r--)(a=i[r])&&(o=(n?a(e,t,o):a(o))||o);return n&&o&&Rt(e,t,o),o},ee=(i,e)=>(t,n)=>e(t,n,i);const je=1.5;I.DocBackScrollRenderController=class extends s.RxDisposable{constructor(e,t,n,o,r){super(),this._context=e,this._textSelectionManagerService=t,this._editorService=n,this._univerInstanceService=o,this._renderManagerService=r,this._init()}_init(){this._textSelectionManagerService.textSelection$.pipe(M.takeUntil(this.dispose$)).subscribe(e=>{if(e==null)return;const{isEditing:t,unitId:n}=e;t&&this._scrollToSelection(n)})}scrollToRange(e,t){var c;const n=(c=this._renderManagerService.getRenderById(e))==null?void 0:c.with(d.DocSkeletonManagerService),o=n==null?void 0:n.getSkeleton();if(!o)return;const{startOffset:r}=t,a=o.findNodePositionByCharIndex(r);this.scrollToNode(e,a)}scrollToNode(e,t){var Q;const n=this._getDocObject(),o=(Q=this._renderManagerService.getRenderById(e))==null?void 0:Q.with(d.DocSkeletonManagerService),r=o==null?void 0:o.getSkeleton();if(n==null||r==null)return;const a=n.document.getOffsetConfig(),{docsLeft:c,docsTop:u}=a,h=new C.NodePositionConvertToCursor(a,r),{contentBoxPointGroup:_}=h.getRangePointData(t,t),{left:m,top:S,height:p}=C.getAnchorBounding(_),f=m+c,g=S+u,v=n.scene.getViewport(d.VIEWPORT_KEY.VIEW_MAIN),O=!!this._editorService.getEditor(e);if(v==null)return;const{left:T,top:E,right:R,bottom:D}=v.getBounding().viewBound;let b=0,N=0;const L=O?0:100;g<E?b=g-E-L:g>D-p&&(b=g-D+p+L),f<T?N=f-T:f>R-je&&(N=f-R+je);const F=v.transViewportScroll2ScrollValue(N,b);v.scrollByBarDeltaValue(F)}_scrollToSelection(e){const t=this._textSelectionManagerService.getActiveRange();if(t==null)return;const{collapsed:n,startNodePosition:o}=t;n&&this.scrollToNode(e,o)}_getDocObject(){return d.getDocObject(this._univerInstanceService,this._renderManagerService)}},I.DocBackScrollRenderController=Dt([ee(1,s.Inject(d.TextSelectionManagerService)),ee(2,l.IEditorService),ee(3,s.Inject(s.IUniverInstanceService)),ee(4,C.IRenderManagerService)],I.DocBackScrollRenderController);const We={undo:!0,redo:!0,font:!0,fontSize:!0,bold:!0,italic:!0,strikethrough:!0,underline:!0,textColor:!0,fillColor:!0,horizontalAlignMode:!0,verticalAlignMode:!0,textWrapMode:!0,textRotateMode:!0},Ge={outerLeft:!1,outerRight:!1,header:!0,footer:!0,innerLeft:!1,innerRight:!1,frozenHeaderLT:!1,frozenHeaderRT:!1,frozenHeaderLM:!1,frozenContent:!1,infoBar:!0,toolbar:!0},ke={layout:{docContainerConfig:Ge,toolbarConfig:We}},Ke="DocUI",yt={id:d.MoveCursorOperation.id,binding:l.KeyCode.ARROW_UP,preconditions:A,staticParameters:{direction:s.Direction.UP}},Pt={id:d.MoveCursorOperation.id,binding:l.KeyCode.ARROW_DOWN,preconditions:A,staticParameters:{direction:s.Direction.DOWN}},At={id:d.MoveCursorOperation.id,binding:l.KeyCode.ARROW_LEFT,preconditions:A,staticParameters:{direction:s.Direction.LEFT}},Nt={id:d.MoveCursorOperation.id,binding:l.KeyCode.ARROW_RIGHT,preconditions:A,staticParameters:{direction:s.Direction.RIGHT}},Ut={id:d.MoveSelectionOperation.id,binding:l.KeyCode.ARROW_UP|l.MetaKeys.SHIFT,preconditions:A,staticParameters:{direction:s.Direction.UP}},xt={id:d.MoveSelectionOperation.id,binding:l.KeyCode.ARROW_DOWN|l.MetaKeys.SHIFT,preconditions:A,staticParameters:{direction:s.Direction.DOWN}},Ft={id:d.MoveSelectionOperation.id,binding:l.KeyCode.ARROW_LEFT|l.MetaKeys.SHIFT,preconditions:A,staticParameters:{direction:s.Direction.LEFT}},Lt={id:d.MoveSelectionOperation.id,binding:l.KeyCode.ARROW_RIGHT|l.MetaKeys.SHIFT,preconditions:A,staticParameters:{direction:s.Direction.RIGHT}},Bt={id:d.SelectAllOperation.id,binding:l.KeyCode.A|l.MetaKeys.CTRL_COMMAND,preconditions:i=>i.getContextValue(s.FOCUSING_UNIVER_EDITOR)&&(i.getContextValue(s.FOCUSING_DOC)||i.getContextValue(s.EDITOR_ACTIVATED))};var wt=Object.defineProperty,$t=Object.getOwnPropertyDescriptor,Ht=(i,e,t,n)=>{for(var o=n>1?void 0:n?$t(e,t):e,r=i.length-1,a;r>=0;r--)(a=i[r])&&(o=(n?a(e,t,o):a(o))||o);return n&&o&&wt(e,t,o),o},Ye=(i,e)=>(t,n)=>e(t,n,i);let me=class{constructor(i,e,t){y(this,"_docContainer");y(this,"getComponent",i=>{if(this._docContainer=i,!i.getContentRef().current)throw new Error("container is not ready")});y(this,"changeLocale",i=>{this._localeService.setLocale(i)});this._config=i,this._localeService=e,this._injector=t}getUIConfig(){return{injector:this._injector,config:this._config,changeLocale:this.changeLocale,getComponent:this.getComponent}}getContentRef(){return this._docContainer.getContentRef()}UIDidMount(i){if(this._docContainer)return i(this._docContainer)}getDocContainer(){return this._docContainer}};me=Ht([Ye(1,s.Inject(s.LocaleService)),Ye(2,s.Inject(s.Injector))],me);var Vt=Object.defineProperty,jt=Object.getOwnPropertyDescriptor,Wt=(i,e,t,n)=>{for(var o=n>1?void 0:n?jt(e,t):e,r=i.length-1,a;r>=0;r--)(a=i[r])&&(o=(n?a(e,t,o):a(o))||o);return n&&o&&Vt(e,t,o),o},te=(i,e)=>(t,n)=>e(t,n,i);let z=class extends s.RxDisposable{constructor(e,t,n,o,r){super();y(this,"_docContainerController");y(this,"changeLocale",e=>{this._localeService.setLocale(e)});this._localeService=t,this._injector=n,this._textSelectionRenderManager=o,this._layoutService=r,this._docContainerController=this._injector.createInstance(me,e),this._registerContainer()}_registerContainer(){this._layoutService&&this.disposeWithMe(this._layoutService.registerContainerElement(this._textSelectionRenderManager.__getEditorContainer()))}getDocContainerController(){return this._docContainerController}};z=Wt([te(1,s.Inject(s.LocaleService)),te(2,s.Inject(s.Injector)),te(3,C.ITextSelectionRenderManager),te(4,s.Optional(l.ILayoutService))],z);const ne="UI_PLUGIN_DOCS",Se=`${ne}_COLOR_PICKER_COMPONENT`,ze=`${ne}_FONT_FAMILY_COMPONENT`,Xe=`${ne}_FONT_FAMILY_ITEM_COMPONENT`,Ze=`${ne}_FONT_SIZE_COMPONENT`;var Je={exports:{}},ie={};/**
|
|
1
|
+
(function(global,factory){typeof exports=="object"&&typeof module<"u"?factory(exports,require("@univerjs/core"),require("@univerjs/ui"),require("@univerjs/docs"),require("@univerjs/engine-render"),require("rxjs"),require("react"),require("@univerjs/design"),require("clsx")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","@univerjs/ui","@univerjs/docs","@univerjs/engine-render","rxjs","react","@univerjs/design","clsx"],factory):(global=typeof globalThis<"u"?globalThis:global||self,factory(global.UniverDocsUi={},global.UniverCore,global.UniverUi,global.UniverDocs,global.UniverEngineRender,global.rxjs,global.React,global.UniverDesign,global.clsx))})(this,function(exports2,core,ui,docs,engineRender,rxjs,require$$0,design,clsx){"use strict";var __defProp=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!="symbol"?key+"":key,value);var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n,_o,_p,_q,_r;function whenDocAndEditorFocused(contextService){return contextService.getContextValue(core.FOCUSING_DOC)&&contextService.getContextValue(core.FOCUSING_UNIVER_EDITOR)&&!contextService.getContextValue(core.FOCUSING_COMMON_DRAWINGS)}__name(whenDocAndEditorFocused,"whenDocAndEditorFocused");function whenDocAndEditorFocusedWithBreakLine(contextService){return contextService.getContextValue(core.FOCUSING_DOC)&&contextService.getContextValue(core.FOCUSING_UNIVER_EDITOR)&&!contextService.getContextValue(core.FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE)&&!contextService.getContextValue(core.FOCUSING_COMMON_DRAWINGS)}__name(whenDocAndEditorFocusedWithBreakLine,"whenDocAndEditorFocusedWithBreakLine");const COPY_CONTENT_CACHE_LIMIT=10,ID_LENGTH=6;function genId(){return core.Tools.generateRandomId(ID_LENGTH)}__name(genId,"genId");function extractId(html){const match=html.match(/data-copy-id="([^\s]+)"/);return match&&match[1]?match[1]:null}__name(extractId,"extractId");const _CopyContentCache=class _CopyContentCache{constructor(){__publicField(this,"_cache",new core.LRUMap(COPY_CONTENT_CACHE_LIMIT))}set(id,clipboardData){this._cache.set(id,clipboardData)}get(id){return this._cache.get(id)}clear(){this._cache.clear()}};__name(_CopyContentCache,"CopyContentCache");let CopyContentCache=_CopyContentCache;const copyContentCache=new CopyContentCache;function extractNodeStyle(node){const styles2=node.style,docStyles={},tagName=node.tagName.toLowerCase();switch(tagName){case"b":case"em":case"strong":{docStyles.bl=core.BooleanNumber.TRUE;break}case"s":{docStyles.st={s:core.BooleanNumber.TRUE};break}case"u":{docStyles.ul={s:core.BooleanNumber.TRUE};break}case"i":{docStyles.it=core.BooleanNumber.TRUE;break}case"sub":case"sup":{docStyles.va=tagName==="sup"?core.BaselineOffset.SUPERSCRIPT:core.BaselineOffset.SUBSCRIPT;break}}for(let i=0;i<styles2.length;i++){const cssRule=styles2[i],cssValue=styles2.getPropertyValue(cssRule);switch(cssRule){case"font-family":{docStyles.ff=cssValue;break}case"font-size":{const fontSize=Number.parseInt(cssValue);Number.isNaN(fontSize)||(cssValue.endsWith("pt")?docStyles.fs=fontSize:cssValue.endsWith("px")&&(docStyles.fs=engineRender.pixelToPt(fontSize)));break}case"font-style":{cssValue==="italic"&&(docStyles.it=core.BooleanNumber.TRUE);break}case"font-weight":{(Number(cssValue)>400||String(cssValue)==="bold")&&(docStyles.bl=core.BooleanNumber.TRUE);break}case"text-decoration":{/underline/.test(cssValue)?docStyles.ul={s:core.BooleanNumber.TRUE}:/overline/.test(cssValue)?docStyles.ol={s:core.BooleanNumber.TRUE}:/line-through/.test(cssValue)&&(docStyles.st={s:core.BooleanNumber.TRUE});break}case"color":{const color=new core.ColorKit(cssValue);color.isValid&&(docStyles.cl={rgb:color.toRgbString()});break}case"background-color":{const color=new core.ColorKit(cssValue);color.isValid&&(docStyles.bg={rgb:color.toRgbString()});break}}}return docStyles}__name(extractNodeStyle,"extractNodeStyle");function parseToDom(rawHtml){const parser=new DOMParser,html=`<x-univer id="univer-root">${rawHtml}</x-univer>`;return parser.parseFromString(html,"text/html").querySelector("#univer-root")}__name(parseToDom,"parseToDom");function matchFilter(node,filter){const tagName=node.tagName.toLowerCase();return typeof filter=="string"?tagName===filter:Array.isArray(filter)?filter.some(name=>name===tagName):filter(node)}__name(matchFilter,"matchFilter");const _HtmlToUDMService=class _HtmlToUDMService{constructor(){__publicField(this,"_styleCache",new Map);__publicField(this,"_styleRules",[]);__publicField(this,"_afterProcessRules",[])}static use(plugin){if(this._pluginList.includes(plugin))throw new Error(`Univer paste plugin ${plugin.name} already added`);this._pluginList.push(plugin)}convert(html){const pastePlugin=_HtmlToUDMService._pluginList.find(plugin=>plugin.checkPasteType(html)),dom=parseToDom(html),newDocBody={dataStream:"",textRuns:[]};return pastePlugin&&(this._styleRules=[...pastePlugin.stylesRules],this._afterProcessRules=[...pastePlugin.afterProcessRules]),this._styleCache.clear(),this._process(null,dom==null?void 0:dom.childNodes,newDocBody),this._styleCache.clear(),this._styleRules=[],this._afterProcessRules=[],newDocBody}_process(parent,nodes,doc){var _a2,_b2,_c2;for(const node of nodes)if(node.nodeType===Node.TEXT_NODE){if(((_a2=node.nodeValue)==null?void 0:_a2.trim())==="")continue;let text=(_b2=node.nodeValue)==null?void 0:_b2.replace(/[\r\n]/g,""),style;if(parent&&parent.nodeType===Node.ELEMENT_NODE&&parent.tagName.toUpperCase()==="A"){const id=core.Tools.generateRandomId();text=`${core.DataStreamTreeTokenType.CUSTOM_RANGE_START}${text}${core.DataStreamTreeTokenType.CUSTOM_RANGE_END}`,doc.customRanges=[...(_c2=doc.customRanges)!=null?_c2:[],{startIndex:doc.dataStream.length,endIndex:doc.dataStream.length+text.length-1,rangeId:id,rangeType:core.CustomRangeType.HYPERLINK}],doc.payloads={...doc.payloads,[id]:parent.href}}parent&&this._styleCache.has(parent)&&(style=this._styleCache.get(parent)),doc.dataStream+=text,style&&Object.getOwnPropertyNames(style).length&&doc.textRuns.push({st:doc.dataStream.length-text.length,ed:doc.dataStream.length,ts:style})}else{if(core.skipParseTagNames.includes(node.nodeName.toLowerCase()))continue;if(node.nodeType===Node.ELEMENT_NODE){const parentStyles=parent?this._styleCache.get(parent):{},styleRule=this._styleRules.find(({filter})=>matchFilter(node,filter)),nodeStyles=styleRule?styleRule.getStyle(node):extractNodeStyle(node);this._styleCache.set(node,{...parentStyles,...nodeStyles});const{childNodes}=node;this._process(node,childNodes,doc);const afterProcessRule=this._afterProcessRules.find(({filter})=>matchFilter(node,filter));afterProcessRule&&afterProcessRule.handler(doc,node)}}}};__name(_HtmlToUDMService,"HtmlToUDMService"),__publicField(_HtmlToUDMService,"_pluginList",[]);let HtmlToUDMService=_HtmlToUDMService;const PastePluginLark={name:"univer-doc-paste-plugin-lark",checkPasteType(html){return/lark-record-clipboard/i.test(html)},stylesRules:[{filter:["s"],getStyle(node){const inlineStyle=extractNodeStyle(node);return{st:{s:core.BooleanNumber.TRUE},...inlineStyle}}}],afterProcessRules:[{filter(el){return el.tagName==="DIV"&&/ace-line/i.test(el.className)},handler(doc){doc.paragraphs==null&&(doc.paragraphs=[]),doc.paragraphs.push({startIndex:doc.dataStream.length}),doc.dataStream+="\r"}}]};function getParagraphStyle(el){const styles2=el.style,paragraphStyle={};for(let i=0;i<styles2.length;i++){const cssRule=styles2[i],cssValue=styles2.getPropertyValue(cssRule);switch(cssRule){case"margin-top":{const marginTopValue=Number.parseInt(cssValue);paragraphStyle.spaceAbove={v:/pt/.test(cssValue)?engineRender.ptToPixel(marginTopValue):marginTopValue};break}case"margin-bottom":{const marginBottomValue=Number.parseInt(cssValue);paragraphStyle.spaceBelow={v:/pt/.test(cssValue)?engineRender.ptToPixel(marginBottomValue):marginBottomValue};break}case"line-height":{const lineHeightValue=Number.parseFloat(cssValue);paragraphStyle.lineSpacing=lineHeightValue;break}}}return Object.getOwnPropertyNames(paragraphStyle).length?paragraphStyle:null}__name(getParagraphStyle,"getParagraphStyle");const PastePluginWord={name:"univer-doc-paste-plugin-word",checkPasteType(html){return/word|mso/i.test(html)},stylesRules:[{filter:["b"],getStyle(node){const inlineStyle=extractNodeStyle(node);return{bl:core.BooleanNumber.TRUE,...inlineStyle}}}],afterProcessRules:[{filter(el){return el.tagName==="P"},handler(doc,el){doc.paragraphs==null&&(doc.paragraphs=[]);const paragraph={startIndex:doc.dataStream.length},paragraphStyle=getParagraphStyle(el);paragraphStyle&&(paragraph.paragraphStyle=paragraphStyle),doc.paragraphs.push(paragraph),doc.dataStream+="\r"}}]},PastePluginUniver={name:"univer-doc-paste-plugin-univer",checkPasteType(html){return/UniverNormal/i.test(html)},stylesRules:[],afterProcessRules:[{filter(el){return el.tagName==="P"&&/UniverNormal/i.test(el.className)},handler(doc,el){doc.paragraphs==null&&(doc.paragraphs=[]);const paragraph={startIndex:doc.dataStream.length},paragraphStyle=getParagraphStyle(el);paragraphStyle&&(paragraph.paragraphStyle=paragraphStyle),doc.paragraphs.push(paragraph),doc.dataStream+="\r"}}]};function covertTextRunToHtml(dataStream,textRun){const{st:start,ed,ts={}}=textRun,{ff,fs,it,bl,ul,st,ol,bg,cl,va}=ts;let html=dataStream.slice(start,ed);const style=[];return it===core.BooleanNumber.TRUE&&(html=`<i>${html}</i>`),va===core.BaselineOffset.SUPERSCRIPT?html=`<sup>${html}</sup>`:va===core.BaselineOffset.SUBSCRIPT&&(html=`<sub>${html}</sub>`),(ul==null?void 0:ul.s)===core.BooleanNumber.TRUE&&(html=`<u>${html}</u>`),(st==null?void 0:st.s)===core.BooleanNumber.TRUE&&(html=`<s>${html}</s>`),bl===core.BooleanNumber.TRUE&&(html=`<strong>${html}</strong>`),ff&&style.push(`font-family: ${ff}`),cl&&style.push(`color: ${cl.rgb}`),fs&&style.push(`font-size: ${fs}pt`),ol&&style.push("text-decoration: overline"),bg&&style.push(`background: ${bg.rgb}`),style.length?`<span style="${style.join("; ")};">${html}</span>`:html}__name(covertTextRunToHtml,"covertTextRunToHtml");function getBodySliceHtml(body,startIndex,endIndex){const{dataStream,textRuns=[]}=body;let cursorIndex=startIndex;const spanList=[];for(const textRun of textRuns){const{st,ed}=textRun;core.Tools.hasIntersectionBetweenTwoRanges(startIndex,endIndex,st,ed)&&(st>cursorIndex?(spanList.push(dataStream.slice(cursorIndex,st)),spanList.push(covertTextRunToHtml(dataStream,{...textRun,ed:Math.min(ed,endIndex)}))):spanList.push(covertTextRunToHtml(dataStream,{...textRun,st:cursorIndex,ed:Math.min(ed,endIndex)}))),cursorIndex=Math.max(startIndex,Math.min(ed,endIndex))}return cursorIndex!==endIndex&&spanList.push(dataStream.slice(cursorIndex,endIndex)),spanList.join("")}__name(getBodySliceHtml,"getBodySliceHtml");function convertBodyToHtml(body,withParagraphInfo=!0){var _a2;if(withParagraphInfo&&((_a2=body.paragraphs)!=null&&_a2.length)){const{dataStream,paragraphs=[]}=body;let result="",cursorIndex=-1;for(const paragraph of paragraphs){const{startIndex,paragraphStyle={}}=paragraph,{spaceAbove,spaceBelow,lineSpacing}=paragraphStyle,style=[];spaceAbove!=null&&(typeof spaceAbove=="number"?style.push(`margin-top: ${spaceAbove}px`):style.push(`margin-top: ${spaceAbove.v}px`)),spaceBelow!=null&&(typeof spaceBelow=="number"?style.push(`margin-bottom: ${spaceBelow}px`):style.push(`margin-bottom: ${spaceBelow.v}px`)),lineSpacing!=null&&style.push(`line-height: ${lineSpacing}`),startIndex>cursorIndex+1?result+=`<p class="UniverNormal" ${style.length?`style="${style.join("; ")};"`:""}>${getBodySliceHtml(body,cursorIndex+1,startIndex)}</p>`:result+=`<p class="UniverNormal" ${style.length?`style="${style.join("; ")};"`:""}></p>`,cursorIndex=startIndex}return cursorIndex!==dataStream.length&&(result+=getBodySliceHtml(body,cursorIndex,dataStream.length)),result}else return getBodySliceHtml(body,0,body.dataStream.length)}__name(convertBodyToHtml,"convertBodyToHtml");const _UDMToHtmlService=class _UDMToHtmlService{convert(bodyList){if(bodyList.length===0)throw new Error("The bodyList length at least to be 1");if(bodyList.length===1)return convertBodyToHtml(bodyList[0]);let html="";for(const body of bodyList)html+='<p className="UniverNormal">',html+=convertBodyToHtml(body,!1),html+="</p>";return html}};__name(_UDMToHtmlService,"UDMToHtmlService");let UDMToHtmlService=_UDMToHtmlService;var __defProp$h=Object.defineProperty,__getOwnPropDesc$h=Object.getOwnPropertyDescriptor,__decorateClass$h=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$h(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$h(target,key,result),result},"__decorateClass$h"),__decorateParam$h=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$h");HtmlToUDMService.use(PastePluginWord),HtmlToUDMService.use(PastePluginLark),HtmlToUDMService.use(PastePluginUniver);const IDocClipboardService=core.createIdentifier("doc.clipboard-service");let DocClipboardService=(_a=class extends core.Disposable{constructor(_univerInstanceService,_logService,_commandService,_clipboardInterfaceService,_textSelectionManagerService,_docCustomRangeService){super();__publicField(this,"_clipboardHooks",[]);__publicField(this,"_htmlToUDM",new HtmlToUDMService);__publicField(this,"_umdToHtml",new UDMToHtmlService);this._univerInstanceService=_univerInstanceService,this._logService=_logService,this._commandService=_commandService,this._clipboardInterfaceService=_clipboardInterfaceService,this._textSelectionManagerService=_textSelectionManagerService,this._docCustomRangeService=_docCustomRangeService}async copy(sliceType=core.SliceBodyType.copy){const documentBodyList=this._getDocumentBodyInRanges(sliceType);if(documentBodyList.length===0)return!1;try{const activeRange=this._textSelectionManagerService.getActiveRange(),isCopyInHeaderFooter=!!(activeRange!=null&&activeRange.segmentId);this._setClipboardData(documentBodyList,!isCopyInHeaderFooter)}catch(e){return this._logService.error("[DocClipboardService] copy failed",e),!1}return!0}async cut(){return this._cut()}async paste(items){const body=await this._generateBodyFromClipboardItems(items);return this._paste(body)}async legacyPaste(html,text){const body=this._generateBodyFromHtmlAndText(html,text);return this._paste(body)}async _cut(){var _a2;const{segmentId,endOffset:activeEndOffset,style}=(_a2=this._textSelectionManagerService.getActiveRange())!=null?_a2:{},ranges=this._textSelectionManagerService.getCurrentSelections();if(segmentId==null&&this._logService.error("[DocClipboardController] segmentId is not existed"),activeEndOffset==null||ranges==null)return!1;this.copy(core.SliceBodyType.cut);try{let cursor=activeEndOffset;for(const range of ranges){const{startOffset,endOffset}=range;startOffset==null||endOffset==null||endOffset<=activeEndOffset&&(cursor-=endOffset-startOffset)}const textRanges=[{startOffset:cursor,endOffset:cursor,style}];return this._commandService.executeCommand(docs.CutContentCommand.id,{segmentId,textRanges})}catch{return this._logService.error("[DocClipboardController] cut content failed"),!1}}async _paste(_body){var _a2,_b2;let body=core.normalizeBody(_body);const unitId=(_a2=this._univerInstanceService.getCurrentUnitForType(core.UniverInstanceType.UNIVER_DOC))==null?void 0:_a2.getUnitId();if(!unitId)return!1;this._clipboardHooks.forEach(hook=>{hook.onBeforePaste&&(body=hook.onBeforePaste(body))}),body.customRanges=(_b2=body.customRanges)==null?void 0:_b2.map(range=>this._docCustomRangeService.copyCustomRange(unitId,range));const activeRange=this._textSelectionManagerService.getActiveRange(),{segmentId,endOffset:activeEndOffset,style}=activeRange||{},ranges=this._textSelectionManagerService.getCurrentSelections();if(segmentId==null&&this._logService.error("[DocClipboardController] segmentId does not exist!"),activeEndOffset==null||ranges==null)return!1;try{let cursor=activeEndOffset;for(const range of ranges){const{startOffset,endOffset}=range;startOffset==null||endOffset==null||endOffset<=activeEndOffset&&(cursor+=body.dataStream.length-(endOffset-startOffset))}const textRanges=[{startOffset:cursor,endOffset:cursor,style}];return this._commandService.executeCommand(docs.InnerPasteCommand.id,{body,segmentId,textRanges})}catch{return this._logService.error("[DocClipboardController]","clipboard is empty."),!1}}async _setClipboardData(documentBodyList,needCache=!0){const copyId=genId(),text=documentBodyList.length>1?documentBodyList.map(body=>body.dataStream).join(`
|
|
2
|
+
`):documentBodyList[0].dataStream;let html=this._umdToHtml.convert(documentBodyList);return documentBodyList.length===1&&needCache&&(html=html.replace(/(<[a-z]+)/,(_p0,p1)=>`${p1} data-copy-id="${copyId}"`),copyContentCache.set(copyId,documentBodyList[0])),this._clipboardInterfaceService.write(text,html)}addClipboardHook(hook){return this._clipboardHooks.push(hook),core.toDisposable(()=>{const index=this._clipboardHooks.indexOf(hook);index>-1&&this._clipboardHooks.splice(index,1)})}_getDocumentBodyInRanges(sliceType){const ranges=this._textSelectionManagerService.getCurrentSelections(),activeRange=this._textSelectionManagerService.getActiveRange(),docDataModel=this._univerInstanceService.getCurrentUniverDocInstance(),results=[],body=docDataModel==null?void 0:docDataModel.getBody();if(ranges==null||docDataModel==null||body==null||activeRange==null)return results;const{segmentId}=activeRange;for(const range of ranges){const{startOffset,endOffset,collapsed}=range;if(collapsed||startOffset==null||endOffset==null)continue;const deleteRange=docs.getDeleteSelection({startOffset,endOffset,collapsed},body),docBody=docDataModel.getSelfOrHeaderFooterModel(segmentId).sliceBody(deleteRange.startOffset,deleteRange.endOffset,sliceType);if(docBody!=null){if(docBody.customRanges){const deleteRange2=[];docBody.customRanges.forEach(range2=>{range2.startIndex===range2.endIndex&&deleteRange2.push(range2)}),docBody.customRanges=docBody.customRanges.filter(range2=>deleteRange2.indexOf(range2)===-1);let text="",cursor=0;deleteRange2.forEach(range2=>{text+=docBody.dataStream.slice(cursor,range2.endIndex),cursor=range2.endIndex+1}),text+=docBody.dataStream.slice(cursor,docBody.dataStream.length),docBody.dataStream=text}results.push(docBody)}}return results}async _generateBodyFromClipboardItems(items){try{let html="",text="";for(const clipboardItem of items)for(const type of clipboardItem.types)type===ui.PLAIN_TEXT_CLIPBOARD_MIME_TYPE?text=await clipboardItem.getType(type).then(blob=>blob&&blob.text()):type===ui.HTML_CLIPBOARD_MIME_TYPE&&(html=await clipboardItem.getType(type).then(blob=>blob&&blob.text()));return this._generateBodyFromHtmlAndText(html,text)}catch(e){return Promise.reject(e)}}_generateBody(text){const dataStream=text.replace(/\n/g,"\r");if(!text.includes("\r")&&core.Tools.isLegalUrl(text)){const id=core.Tools.generateRandomId(),docDataModel=this._univerInstanceService.getCurrentUnitForType(core.UniverInstanceType.UNIVER_DOC),urlText=`${core.DataStreamTreeTokenType.CUSTOM_RANGE_START}${dataStream}${core.DataStreamTreeTokenType.CUSTOM_RANGE_END}`,range=this._docCustomRangeService.copyCustomRange(docDataModel.getUnitId(),{startIndex:0,endIndex:urlText.length-1,rangeId:id,rangeType:core.CustomRangeType.HYPERLINK,data:text});return{dataStream:urlText,customRanges:[range]}}const paragraphs=[];for(let i=0;i<dataStream.length;i++)dataStream[i]==="\r"&¶graphs.push({startIndex:i});return{dataStream,paragraphs}}_generateBodyFromHtmlAndText(html,text){if(!html){if(text)return this._generateBody(text);throw new Error("[DocClipboardService] html and text cannot be both empty!")}const copyId=extractId(html);if(copyId){const copyCache=copyContentCache.get(copyId);if(copyCache)return copyCache}return this._htmlToUDM.convert(html)}},__name(_a,"DocClipboardService"),_a);DocClipboardService=__decorateClass$h([__decorateParam$h(0,core.IUniverInstanceService),__decorateParam$h(1,core.ILogService),__decorateParam$h(2,core.ICommandService),__decorateParam$h(3,ui.IClipboardInterfaceService),__decorateParam$h(4,core.Inject(docs.TextSelectionManagerService)),__decorateParam$h(5,core.Inject(docs.DocCustomRangeService))],DocClipboardService);var __defProp$g=Object.defineProperty,__getOwnPropDesc$g=Object.getOwnPropertyDescriptor,__decorateClass$g=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$g(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$g(target,key,result),result},"__decorateClass$g"),__decorateParam$g=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$g");const ANCHOR_WIDTH=1.5;exports2.DocBackScrollRenderController=(_b=class extends core.RxDisposable{constructor(_context,_textSelectionManagerService,_editorService,_univerInstanceService,_renderManagerService){super(),this._context=_context,this._textSelectionManagerService=_textSelectionManagerService,this._editorService=_editorService,this._univerInstanceService=_univerInstanceService,this._renderManagerService=_renderManagerService,this._init()}_init(){this._textSelectionManagerService.textSelection$.pipe(rxjs.takeUntil(this.dispose$)).subscribe(params=>{if(params==null)return;const{isEditing,unitId}=params;isEditing&&this._scrollToSelection(unitId)})}scrollToRange(unitId,range){var _a2;const docSkeletonManagerService=(_a2=this._renderManagerService.getRenderById(unitId))==null?void 0:_a2.with(docs.DocSkeletonManagerService),skeleton=docSkeletonManagerService==null?void 0:docSkeletonManagerService.getSkeleton();if(!skeleton)return;const{startOffset}=range,anchorNodePosition=skeleton.findNodePositionByCharIndex(startOffset);this.scrollToNode(unitId,anchorNodePosition)}scrollToNode(unitId,startNodePosition){var _a2;const docObject=this._getDocObject(),docSkeletonManagerService=(_a2=this._renderManagerService.getRenderById(unitId))==null?void 0:_a2.with(docs.DocSkeletonManagerService),skeleton=docSkeletonManagerService==null?void 0:docSkeletonManagerService.getSkeleton();if(docObject==null||skeleton==null)return;const documentOffsetConfig=docObject.document.getOffsetConfig(),{docsLeft,docsTop}=documentOffsetConfig,convertor=new engineRender.NodePositionConvertToCursor(documentOffsetConfig,skeleton),{contentBoxPointGroup}=convertor.getRangePointData(startNodePosition,startNodePosition),{left:aLeft,top:aTop,height}=engineRender.getAnchorBounding(contentBoxPointGroup),left=aLeft+docsLeft,top=aTop+docsTop,viewportMain=docObject.scene.getViewport(docs.VIEWPORT_KEY.VIEW_MAIN),isEditor=!!this._editorService.getEditor(unitId);if(viewportMain==null)return;const{left:boundLeft,top:boundTop,right:boundRight,bottom:boundBottom}=viewportMain.getBounding().viewBound;let offsetY=0,offsetX=0;const delta=isEditor?0:100;top<boundTop?offsetY=top-boundTop-delta:top>boundBottom-height&&(offsetY=top-boundBottom+height+delta),left<boundLeft?offsetX=left-boundLeft:left>boundRight-ANCHOR_WIDTH&&(offsetX=left-boundRight+ANCHOR_WIDTH);const config=viewportMain.transViewportScroll2ScrollValue(offsetX,offsetY);viewportMain.scrollByBarDeltaValue(config)}_scrollToSelection(unitId){const activeTextRange=this._textSelectionManagerService.getActiveRange();if(activeTextRange==null)return;const{collapsed,startNodePosition}=activeTextRange;collapsed&&this.scrollToNode(unitId,startNodePosition)}_getDocObject(){return docs.getDocObject(this._univerInstanceService,this._renderManagerService)}},__name(_b,"DocBackScrollRenderController"),_b),exports2.DocBackScrollRenderController=__decorateClass$g([__decorateParam$g(1,core.Inject(docs.TextSelectionManagerService)),__decorateParam$g(2,ui.IEditorService),__decorateParam$g(3,core.Inject(core.IUniverInstanceService)),__decorateParam$g(4,engineRender.IRenderManagerService)],exports2.DocBackScrollRenderController);const DefaultToolbarConfig={undo:!0,redo:!0,font:!0,fontSize:!0,bold:!0,italic:!0,strikethrough:!0,underline:!0,textColor:!0,fillColor:!0,horizontalAlignMode:!0,verticalAlignMode:!0,textWrapMode:!0,textRotateMode:!0},DefaultDocContainerConfig={outerLeft:!1,outerRight:!1,header:!0,footer:!0,innerLeft:!1,innerRight:!1,frozenHeaderLT:!1,frozenHeaderRT:!1,frozenHeaderLM:!1,frozenContent:!1,infoBar:!0,toolbar:!0},DefaultDocUiConfig={layout:{docContainerConfig:DefaultDocContainerConfig,toolbarConfig:DefaultToolbarConfig}},DOC_UI_PLUGIN_NAME="DocUI",MoveCursorUpShortcut={id:docs.MoveCursorOperation.id,binding:ui.KeyCode.ARROW_UP,preconditions:whenDocAndEditorFocused,staticParameters:{direction:core.Direction.UP}},MoveCursorDownShortcut={id:docs.MoveCursorOperation.id,binding:ui.KeyCode.ARROW_DOWN,preconditions:whenDocAndEditorFocused,staticParameters:{direction:core.Direction.DOWN}},MoveCursorLeftShortcut={id:docs.MoveCursorOperation.id,binding:ui.KeyCode.ARROW_LEFT,preconditions:whenDocAndEditorFocused,staticParameters:{direction:core.Direction.LEFT}},MoveCursorRightShortcut={id:docs.MoveCursorOperation.id,binding:ui.KeyCode.ARROW_RIGHT,preconditions:whenDocAndEditorFocused,staticParameters:{direction:core.Direction.RIGHT}},MoveSelectionUpShortcut={id:docs.MoveSelectionOperation.id,binding:ui.KeyCode.ARROW_UP|ui.MetaKeys.SHIFT,preconditions:whenDocAndEditorFocused,staticParameters:{direction:core.Direction.UP}},MoveSelectionDownShortcut={id:docs.MoveSelectionOperation.id,binding:ui.KeyCode.ARROW_DOWN|ui.MetaKeys.SHIFT,preconditions:whenDocAndEditorFocused,staticParameters:{direction:core.Direction.DOWN}},MoveSelectionLeftShortcut={id:docs.MoveSelectionOperation.id,binding:ui.KeyCode.ARROW_LEFT|ui.MetaKeys.SHIFT,preconditions:whenDocAndEditorFocused,staticParameters:{direction:core.Direction.LEFT}},MoveSelectionRightShortcut={id:docs.MoveSelectionOperation.id,binding:ui.KeyCode.ARROW_RIGHT|ui.MetaKeys.SHIFT,preconditions:whenDocAndEditorFocused,staticParameters:{direction:core.Direction.RIGHT}},SelectAllShortcut={id:docs.SelectAllOperation.id,binding:ui.KeyCode.A|ui.MetaKeys.CTRL_COMMAND,preconditions:__name(contextService=>contextService.getContextValue(core.FOCUSING_UNIVER_EDITOR)&&(contextService.getContextValue(core.FOCUSING_DOC)||contextService.getContextValue(core.EDITOR_ACTIVATED)),"preconditions")};var __defProp$f=Object.defineProperty,__getOwnPropDesc$f=Object.getOwnPropertyDescriptor,__decorateClass$f=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$f(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$f(target,key,result),result},"__decorateClass$f"),__decorateParam$f=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$f");let DocContainerUIController=(_c=class{constructor(_config,_localeService,_injector){__publicField(this,"_docContainer");__publicField(this,"getComponent",__name(ref=>{if(this._docContainer=ref,!ref.getContentRef().current)throw new Error("container is not ready")},"getComponent"));__publicField(this,"changeLocale",__name(locale=>{this._localeService.setLocale(locale)},"changeLocale"));this._config=_config,this._localeService=_localeService,this._injector=_injector}getUIConfig(){return{injector:this._injector,config:this._config,changeLocale:this.changeLocale,getComponent:this.getComponent}}getContentRef(){return this._docContainer.getContentRef()}UIDidMount(cb){if(this._docContainer)return cb(this._docContainer)}getDocContainer(){return this._docContainer}},__name(_c,"DocContainerUIController"),_c);DocContainerUIController=__decorateClass$f([__decorateParam$f(1,core.Inject(core.LocaleService)),__decorateParam$f(2,core.Inject(core.Injector))],DocContainerUIController);var __defProp$e=Object.defineProperty,__getOwnPropDesc$e=Object.getOwnPropertyDescriptor,__decorateClass$e=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$e(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$e(target,key,result),result},"__decorateClass$e"),__decorateParam$e=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$e");let AppUIController=(_d=class extends core.RxDisposable{constructor(_config,_localeService,_injector,_textSelectionRenderManager,_layoutService){super();__publicField(this,"_docContainerController");__publicField(this,"changeLocale",__name(locale=>{this._localeService.setLocale(locale)},"changeLocale"));this._localeService=_localeService,this._injector=_injector,this._textSelectionRenderManager=_textSelectionRenderManager,this._layoutService=_layoutService,this._docContainerController=this._injector.createInstance(DocContainerUIController,_config),this._registerContainer()}_registerContainer(){this._layoutService&&this.disposeWithMe(this._layoutService.registerContainerElement(this._textSelectionRenderManager.__getEditorContainer()))}getDocContainerController(){return this._docContainerController}},__name(_d,"AppUIController"),_d);AppUIController=__decorateClass$e([__decorateParam$e(1,core.Inject(core.LocaleService)),__decorateParam$e(2,core.Inject(core.Injector)),__decorateParam$e(3,engineRender.ITextSelectionRenderManager),__decorateParam$e(4,core.Optional(ui.ILayoutService))],AppUIController);const COMPONENT_PREFIX="UI_PLUGIN_DOCS",COLOR_PICKER_COMPONENT=`${COMPONENT_PREFIX}_COLOR_PICKER_COMPONENT`,FONT_FAMILY_COMPONENT=`${COMPONENT_PREFIX}_FONT_FAMILY_COMPONENT`,FONT_FAMILY_ITEM_COMPONENT=`${COMPONENT_PREFIX}_FONT_FAMILY_ITEM_COMPONENT`,FONT_SIZE_COMPONENT=`${COMPONENT_PREFIX}_FONT_SIZE_COMPONENT`;var jsxRuntime={exports:{}},reactJsxRuntime_production_min={};/**
|
|
3
3
|
* @license React
|
|
4
4
|
* react-jsx-runtime.production.min.js
|
|
5
5
|
*
|
|
@@ -7,5 +7,5 @@
|
|
|
7
7
|
*
|
|
8
8
|
* This source code is licensed under the MIT license found in the
|
|
9
9
|
* LICENSE file in the root directory of this source tree.
|
|
10
|
-
*/var Gt=B,kt=Symbol.for("react.element"),Kt=Symbol.for("react.fragment"),Yt=Object.prototype.hasOwnProperty,zt=Gt.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,Xt={key:!0,ref:!0,__self:!0,__source:!0};function qe(i,e,t){var n,o={},r=null,a=null;t!==void 0&&(r=""+t),e.key!==void 0&&(r=""+e.key),e.ref!==void 0&&(a=e.ref);for(n in e)Yt.call(e,n)&&!Xt.hasOwnProperty(n)&&(o[n]=e[n]);if(i&&i.defaultProps)for(n in e=i.defaultProps,e)o[n]===void 0&&(o[n]=e[n]);return{$$typeof:kt,type:i,key:r,ref:a,props:o,_owner:zt.current}}ie.Fragment=Kt,ie.jsx=qe,ie.jsxs=qe,Je.exports=ie;var P=Je.exports;const Zt={docCountBar:"univer-doc-count-bar"},Jt=[50,80,100,130,150,170,200,400],qt=[10,400];function Qt(){const i=s.useDependency(s.ICommandService),e=s.useDependency(s.IUniverInstanceService),t=B.useMemo(()=>e.getCurrentTypeOfUnit$(s.UniverInstanceType.UNIVER_DOC),[]),n=s.useObservable(t),o=B.useCallback(()=>{var h,_;if(!n)return 100;const u=((_=(h=n.getSettings())==null?void 0:h.zoomRatio)!=null?_:1)*100;return Math.round(u)},[n]),[r,a]=B.useState(()=>o());B.useEffect(()=>(a(o()),i.onCommandExecuted(h=>{if(h.id===d.SetDocZoomRatioOperation.id){const _=o();a(_)}}).dispose),[i,o]);function c(u){if(a(u),n==null)return;const h=u/100;i.executeCommand(d.SetDocZoomRatioOperation.id,{unitId:n.getUnitId(),zoomRatio:h})}return P.jsx(H.Slider,{min:qt[0],value:r,shortcuts:Jt,onChange:c})}function en(i){return P.jsx("section",{className:Zt.docCountBar,children:P.jsx(Qt,{})})}const tn={docFooterContainer:"univer-doc-footer-container"},nn=()=>P.jsxs("div",{className:tn.docFooterContainer,children:[P.jsx("div",{}),P.jsx(en,{})]}),Qe=18,et=200,fe=6,on=4;function rn(i,e){let{radius:t,width:n,height:o}=e;t=t!=null?t:0,n=n!=null?n:30,o=o!=null?o:30;let r=0;r=Math.min(t,n/2,o/2),i.beginPath(),i.moveTo(0,0),i.lineTo(n,0),i.lineTo(n,o-r),i.arc(n-r,o-r,r,0,Math.PI/2,!1),i.lineTo(0,o),i.lineTo(0,0),i.closePath(),e.fill&&(i.save(),i.fillStyle=e.fill,e.fillRule==="evenodd"?i.fill("evenodd"):i.fill(),i.restore())}class oe extends C.Shape{constructor(t,n){super(t,n);y(this,"color");y(this,"text");this.color=n==null?void 0:n.color,this.text=n==null?void 0:n.text}static drawWith(t,n){const{text:o,color:r}=n;t.save(),t.font="13px Source Han Sans CN";const a=t.measureText(o).width,c=Math.min(a+2*fe,et);rn(t,{height:Qe,width:c,radius:4,fill:r,evented:!1}),t.fillStyle="rgba(58, 96, 247, 1)";const u=fe,h=Qe-on,_=et-2*fe;if(a>_){let m="",S=0;for(const p of o){const f=t.measureText(p).width;if(S+f<=_-t.measureText("...").width)m+=p,S+=f;else{m+="...";break}}t.fillText(m,u,h)}else t.fillText(o,u,h);t.restore()}_draw(t){oe.drawWith(t,this)}}const tt="COMPONENT_DOC_HEADER_FOOTER_PANEL",x={panel:"univer-panel",optionsSection:"univer-options-section",optionsFormItem:"univer-options-form-item",optionsInput:"univer-options-input",optionsMarginSetting:"univer-options-margin-setting"},sn=i=>{const e=s.useDependency(s.LocaleService),t=s.useDependency(s.IUniverInstanceService),n=s.useDependency(C.IRenderManagerService),o=s.useDependency(s.ICommandService),r=s.useDependency(C.ITextSelectionRenderManager),a=s.useDependency(d.TextSelectionManagerService),{unitId:c}=i,[u,h]=B.useState({}),_=(p,f)=>{var N;h(L=>({...L,[f]:p?s.BooleanNumber.TRUE:s.BooleanNumber.FALSE}));const g=t.getUniverDocInstance(c),v=g==null?void 0:g.getSnapshot().documentStyle,O=(N=n.getRenderById(c))==null?void 0:N.with(d.DocSkeletonManagerService),T=O==null?void 0:O.getViewModel();if(v==null||T==null)return;const E=T.getEditArea();let R=!1;const D=r.getSegmentPage();let b=!1;if(f==="useFirstPageHeaderFooter"&&p===!0&&((E===C.DocumentEditArea.HEADER&&!v.firstPageHeaderId||E===C.DocumentEditArea.FOOTER&&!v.firstPageFooterId)&&(R=!0),R&&D===0&&(b=!0)),f==="evenAndOddHeaders"&&p===!0&&((E===C.DocumentEditArea.HEADER&&!v.evenPageHeaderId||E===C.DocumentEditArea.FOOTER&&!v.evenPageFooterId)&&(R=!0),R&&D%2===1&&(b=!0)),R){const F=s.Tools.generateRandomId(6);b&&r.setSegment(F),o.executeCommand(re,{unitId:c,segmentId:F,headerFooterProps:{[f]:p?s.BooleanNumber.TRUE:s.BooleanNumber.FALSE}})}else o.executeCommand(re,{unitId:c,headerFooterProps:{[f]:p?s.BooleanNumber.TRUE:s.BooleanNumber.FALSE}})},m=async(p,f)=>{h(g=>({...g,[f]:p})),await o.executeCommand(re,{unitId:c,headerFooterProps:{[f]:p}}),r.removeAllTextRanges(),r.blur()},S=()=>{var R;const p=n.getRenderById(c);if(p==null)return;const{scene:f}=p,g=f.getTransformerByCreate(),v=p.with(d.DocSkeletonManagerService),O=v==null?void 0:v.getSkeleton(),T=v==null?void 0:v.getViewModel(),E=n.getRenderById(c);E==null||T==null||O==null||(a.replaceTextRanges([]),g.clearSelectedObjects(),r.setSegment(""),r.setSegmentPage(-1),T.setEditArea(C.DocumentEditArea.BODY),O.calculate(),(R=E.mainComponent)==null||R.makeDirty(!0))};return B.useEffect(()=>{const p=t.getUniverDocInstance(c),f=p==null?void 0:p.getSnapshot().documentStyle;if(f){const{marginHeader:g,marginFooter:v,useFirstPageHeaderFooter:O,evenAndOddHeaders:T}=f;h({marginHeader:g,marginFooter:v,useFirstPageHeaderFooter:O,evenAndOddHeaders:T})}},[c]),P.jsxs("div",{className:x.options,children:[P.jsxs("div",{className:x.optionsSection,children:[P.jsx("div",{className:x.optionsFormItem,children:P.jsx(H.Checkbox,{checked:u.useFirstPageHeaderFooter===s.BooleanNumber.TRUE,onChange:p=>{_(p,"useFirstPageHeaderFooter")},children:e.t("headerFooter.firstPageCheckBox")})}),P.jsx("div",{className:x.optionsFormItem,children:P.jsx(H.Checkbox,{checked:u.evenAndOddHeaders===s.BooleanNumber.TRUE,onChange:p=>{_(p,"evenAndOddHeaders")},children:e.t("headerFooter.oddEvenCheckBox")})})]}),P.jsxs("div",{className:gt(x.optionsSection,x.optionsMarginSetting),children:[P.jsxs("div",{className:x.optionsMarginItem,children:[P.jsx("span",{children:e.t("headerFooter.headerTopMargin")}),P.jsx(H.InputNumber,{min:0,max:200,precision:1,value:u.marginHeader,onChange:p=>{m(p,"marginHeader")},className:x.optionsInput})]}),P.jsxs("div",{className:x.optionsMarginItem,children:[P.jsx("span",{children:e.t("headerFooter.footerBottomMargin")}),P.jsx(H.InputNumber,{min:0,max:200,precision:1,value:u.marginFooter,onChange:p=>{m(p,"marginFooter")},className:x.optionsInput})]})]}),P.jsx("div",{className:x.optionsSection,children:P.jsx(H.Button,{onClick:S,children:e.t("headerFooter.closeHeaderFooter")})})]})},an=()=>{var h;const i=s.useDependency(s.LocaleService),e=s.useDependency(C.IRenderManagerService),o=s.useDependency(s.IUniverInstanceService).getCurrentUniverDocInstance().getUnitId(),a=((h=e.getRenderById(o))==null?void 0:h.with(d.DocSkeletonManagerService)).getViewModel(),[c,u]=B.useState(!0);return B.useEffect(()=>{const _=a.getEditArea();u(_!==C.DocumentEditArea.BODY);const m=a.editAreaChange$.subscribe(S=>{S!=null&&u(S!==C.DocumentEditArea.BODY)});return()=>{m.unsubscribe()}},[]),P.jsx("div",{className:x.panel,children:c?P.jsx(sn,{unitId:o}):P.jsx("div",{className:x.panelDisableText,children:i.t("headerFooter.disableText")})})},nt={id:"sidebar.operation.doc-header-footer-panel",type:s.CommandType.COMMAND,handler:async(i,e)=>{const t=i.get(l.ISidebarService),n=i.get(s.LocaleService);switch(e.value){case"open":t.open({header:{title:n.t("headerFooter.panel")},children:{label:tt},onClose:()=>{},width:400});break;case"close":default:t.close();break}return!0}};var cn=Object.defineProperty,ln=Object.getOwnPropertyDescriptor,dn=(i,e,t,n)=>{for(var o=n>1?void 0:n?ln(e,t):e,r=i.length-1,a;r>=0;r--)(a=i[r])&&(o=(n?a(e,t,o):a(o))||o);return n&&o&&cn(e,t,o),o},w=(i,e)=>(t,n)=>e(t,n,i);const it="rgba(58, 96, 247, 1)",ot="rgba(58, 96, 247, 0.08)";var U=(i=>(i[i.FIRST_PAGE_HEADER=0]="FIRST_PAGE_HEADER",i[i.FIRST_PAGE_FOOTER=1]="FIRST_PAGE_FOOTER",i[i.DEFAULT_HEADER=2]="DEFAULT_HEADER",i[i.DEFAULT_FOOTER=3]="DEFAULT_FOOTER",i[i.EVEN_PAGE_HEADER=4]="EVEN_PAGE_HEADER",i[i.EVEN_PAGE_FOOTER=5]="EVEN_PAGE_FOOTER",i))(U||{});function un(i,e,t){const{documentStyle:n}=i.getDataModel().getSnapshot(),{defaultHeaderId:o,defaultFooterId:r,evenPageHeaderId:a,evenPageFooterId:c,firstPageHeaderId:u,firstPageFooterId:h,evenAndOddHeaders:_,useFirstPageHeaderFooter:m}=n;switch(e){case C.DocumentEditArea.BODY:return{createType:null,headerFooterId:null};case C.DocumentEditArea.HEADER:return m===s.BooleanNumber.TRUE&&!u?{createType:0,headerFooterId:null}:_===s.BooleanNumber.TRUE&&t%2===0&&!a?{createType:4,headerFooterId:null}:o?{createType:null,headerFooterId:o}:{createType:2,headerFooterId:null};case C.DocumentEditArea.FOOTER:return m===s.BooleanNumber.TRUE&&!h?{createType:1,headerFooterId:null}:_===s.BooleanNumber.TRUE&&t%2===0&&!c?{createType:5,headerFooterId:null}:r?{createType:null,headerFooterId:r}:{createType:3,headerFooterId:null};default:throw new Error(`Invalid editArea: ${e}`)}}let ve=class extends s.Disposable{constructor(e,t,n,o,r,a,c,u,h){super();y(this,"_loadedMap",new WeakSet);this._context=e,this._commandService=t,this._editorService=n,this._instanceSrv=o,this._renderManagerService=r,this._docSkeletonManagerService=a,this._textSelectionRenderManager=c,this._localeService=u,this._componentManager=h,this._initialize()}_initialize(){this._context.unit.getSnapshot().documentStyle.documentFlavor===s.DocumentFlavor.TRADITIONAL&&(this._init(),this._drawHeaderFooterLabel(),this._registerCommands(),this._initCustomComponents())}_registerCommands(){[st,at,nt].forEach(e=>this.disposeWithMe(this._commandService.registerCommand(e)))}_initCustomComponents(){const e=this._componentManager;this.disposeWithMe(e.register(tt,an))}_init(){const{unitId:e}=this._context,t=d.neoGetDocObject(this._context);t==null||t.document==null||this._loadedMap.has(t.document)||(this._initialMain(e),this._loadedMap.add(t.document))}_initialMain(e){const t=d.neoGetDocObject(this._context),{document:n}=t;this.disposeWithMe(n.onDblclick$.subscribeEvent(async o=>{if(this._isEditorReadOnly(e))return;const{offsetX:r,offsetY:a}=o,{pageLayoutType:c=C.PageLayoutType.VERTICAL,pageMarginLeft:u,pageMarginTop:h}=n.getOffsetConfig(),_=this._getTransformCoordForDocumentOffset(r,a);if(_==null)return;const m=this._docSkeletonManagerService.getViewModel(),S=this._docSkeletonManagerService.getSkeleton(),p=m.getEditArea(),{editArea:f,pageNumber:g}=S.findEditAreaByCoord(_,c,u,h);if(p===f)return;m.setEditArea(f);const{createType:v,headerFooterId:O}=un(m,f,g);if(f===C.DocumentEditArea.BODY)this._textSelectionRenderManager.setSegment(""),this._textSelectionRenderManager.setSegmentPage(-1),this._textSelectionRenderManager.setCursorManually(r,a);else if(v!=null){const E=s.Tools.generateRandomId(6);this._textSelectionRenderManager.setSegment(E),this._textSelectionRenderManager.setSegmentPage(g),await this._commandService.executeCommand(st.id,{unitId:e,createType:v,segmentId:E})}else O!=null&&(this._textSelectionRenderManager.setSegment(O),this._textSelectionRenderManager.setSegmentPage(g),this._textSelectionRenderManager.setCursorManually(r,a))}))}_getTransformCoordForDocumentOffset(e,t){const n=d.neoGetDocObject(this._context),{document:o,scene:r}=n,{documentTransform:a}=o.getOffsetConfig(),c=r.getViewports()[0];if(c==null)return;const u=c.transformVector2SceneCoord(C.Vector2.FromArray([e,t]));return a.clone().invert().applyPoint(u)}_drawHeaderFooterLabel(){const e=this._localeService;this._renderManagerService.currentRender$.subscribe(t=>{if(t==null)return;const n=this._renderManagerService.getRenderById(t);if(this._editorService.isEditor(t)||this._instanceSrv.getUniverDocInstance(t)==null||n==null)return;const{mainComponent:o}=n,r=o;this.disposeWithMe(s.toDisposable(r.pageRender$.subscribe(a=>{if(this._editorService.isEditor(t))return;const h=this._docSkeletonManagerService.getViewModel().getEditArea()===C.DocumentEditArea.BODY,{page:_,pageLeft:m,pageTop:S,ctx:p}=a,{pageWidth:f,pageHeight:g,marginTop:v,marginBottom:O}=_;if(p.save(),p.translate(m-.5,S-.5),h?(C.Rect.drawWith(p,{left:0,top:0,width:f,height:v,fill:"rgba(255, 255, 255, 0.5)"}),p.save(),p.translate(0,g-O),C.Rect.drawWith(p,{left:0,top:0,width:f,height:O,fill:"rgba(255, 255, 255, 0.5)"}),p.restore()):(p.save(),p.translate(0,v),C.Rect.drawWith(p,{left:0,top:v,width:f,height:g-v-O,fill:"rgba(255, 255, 255, 0.5)"}),p.restore()),!h){const T={dataArray:[{command:"M",points:[0,v]},{command:"L",points:[f,v]}],strokeWidth:1,stroke:it},E={dataArray:[{command:"M",points:[0,g-O]},{command:"L",points:[f,g-O]}],strokeWidth:1,stroke:it};C.Path.drawWith(p,T),C.Path.drawWith(p,E),p.translate(0,v+1),oe.drawWith(p,{text:e.t("headerFooter.header"),color:ot}),p.translate(0,g-v-O),oe.drawWith(p,{text:e.t("headerFooter.footer"),color:ot})}p.restore()})))})}_isEditorReadOnly(e){const t=this._editorService.getEditor(e);return t?t.isReadOnly():!1}_getDocDataModel(){return this._context.unit}};ve=dn([w(1,s.ICommandService),w(2,l.IEditorService),w(3,s.IUniverInstanceService),w(4,C.IRenderManagerService),w(5,s.Inject(d.DocSkeletonManagerService)),w(6,C.ITextSelectionRenderManager),w(7,s.Inject(s.LocaleService)),w(8,s.Inject(l.ComponentManager))],ve);function rt(){return{dataStream:`\r
|
|
11
|
-
`,textRuns:[{st:0,ed:0,ts:{fs:9}}],customBlocks:[],paragraphs:[{startIndex:0,paragraphStyle:{spaceAbove:{v:0},lineSpacing:1.5,spaceBelow:{v:0}}}],sectionBreaks:[{startIndex:1}]}}function Ce(i,e,t,n){const o=s.JSONX.getInstance(),r=6,a=i!=null?i:s.Tools.generateRandomId(r),c=e===U.DEFAULT_HEADER||e===U.FIRST_PAGE_HEADER||e===U.EVEN_PAGE_HEADER,u=o.insertOp([c?"headers":"footers",a],{[c?"headerId":"footerId"]:a,body:rt()});n.push(u);const h=s.Tools.generateRandomId(r),_=o.insertOp([c?"footers":"headers",h],{[c?"footers":"headers"]:h,body:rt()});n.push(_);let m="defaultHeaderId",S="defaultFooterId";switch(e){case U.DEFAULT_HEADER:m="defaultHeaderId",S="defaultFooterId";break;case U.DEFAULT_FOOTER:m="defaultFooterId",S="defaultHeaderId";break;case U.FIRST_PAGE_HEADER:m="firstPageHeaderId",S="firstPageFooterId";break;case U.FIRST_PAGE_FOOTER:m="firstPageFooterId",S="firstPageHeaderId";break;case U.EVEN_PAGE_HEADER:m="evenPageHeaderId",S="evenPageFooterId";break;case U.EVEN_PAGE_FOOTER:m="evenPageFooterId",S="evenPageHeaderId";break;default:throw new Error(`Unknown header footer type: ${e}`)}for(const[p,f]of[[m,a],[S,h]])if(t[p]!=null){const g=o.replaceOp(["documentStyle",p],t[p],f);n.push(g)}else{const g=o.insertOp(["documentStyle",p],f);n.push(g)}return n}const re="doc.command.core-header-footer",st={id:re,type:s.CommandType.COMMAND,handler:async(i,e)=>{var R;const t=i.get(s.ICommandService),n=i.get(s.IUniverInstanceService),o=i.get(C.IRenderManagerService),{unitId:r,segmentId:a,createType:c,headerFooterProps:u}=e,h=(R=o.getRenderById(r))==null?void 0:R.with(d.DocSkeletonManagerService),_=n.getUniverDocInstance(r),m=h==null?void 0:h.getViewModel();if(_==null||m==null)return!1;const S=m.getEditArea(),{documentStyle:p}=_.getSnapshot(),f=(u==null?void 0:u.marginFooter)!=null||(u==null?void 0:u.marginHeader)!=null,g=[{startOffset:0,endOffset:0,collapsed:!0}],v={id:d.RichTextEditingMutation.id,params:{unitId:r,actions:[],textRanges:g,debounce:!0}};f&&(v.params.noNeedSetTextRange=!0);const O=s.JSONX.getInstance(),T=[];return c!=null&&Ce(a,c,p,T),u!=null&&Object.keys(u).forEach(D=>{const b=u[D],N=p[D];if(b===N)return;let L;if(N===void 0?L=O.insertOp(["documentStyle",D],b):L=O.replaceOp(["documentStyle",D],N,b),T.push(L),D==="useFirstPageHeaderFooter"&&b===s.BooleanNumber.TRUE&&!p.firstPageHeaderId){const F=S===C.DocumentEditArea.HEADER?U.FIRST_PAGE_HEADER:U.FIRST_PAGE_FOOTER;Ce(a,F,p,T)}else if(D==="evenAndOddHeaders"&&b===s.BooleanNumber.TRUE&&!p.evenPageHeaderId){const F=S===C.DocumentEditArea.HEADER?U.EVEN_PAGE_HEADER:U.EVEN_PAGE_FOOTER;Ce(a,F,p,T)}}),T.length===0?!1:(v.params.actions=T.reduce((D,b)=>s.JSONX.compose(D,b),null),!!t.syncExecuteCommand(v.id,v.params))}},at={id:"doc.command.open-header-footer-panel",type:s.CommandType.COMMAND,handler:async(i,e)=>i.get(s.ICommandService).executeCommand(nt.id,{value:"open"})};function hn(i){const e=i.get(s.ICommandService);return{id:d.SetInlineFormatBoldCommand.id,group:l.MenuGroup.TOOLBAR_FORMAT,type:l.MenuItemType.BUTTON,icon:"BoldSingle",title:"Set bold",tooltip:"toolbar.bold",positions:[l.MenuPosition.TOOLBAR_START],activated$:new M.Observable(t=>{const n=e.onCommandExecuted(o=>{var a;const r=o.id;if(r===d.SetTextSelectionsOperation.id||r===d.SetInlineFormatCommand.id){const c=$(i);if(c==null)return;const u=(a=c.ts)==null?void 0:a.bl;t.next(u===s.BooleanNumber.TRUE)}});return t.next(!1),n.dispose}),hidden$:l.getMenuHiddenObservable(i,s.UniverInstanceType.UNIVER_DOC)}}function pn(i){const e=i.get(s.ICommandService);return{id:d.SetInlineFormatItalicCommand.id,group:l.MenuGroup.TOOLBAR_FORMAT,type:l.MenuItemType.BUTTON,icon:"ItalicSingle",title:"Set italic",tooltip:"toolbar.italic",positions:[l.MenuPosition.TOOLBAR_START],activated$:new M.Observable(t=>{const n=e.onCommandExecuted(o=>{var a;const r=o.id;if(r===d.SetTextSelectionsOperation.id||r===d.SetInlineFormatCommand.id){const c=$(i);if(c==null)return;const u=(a=c.ts)==null?void 0:a.it;t.next(u===s.BooleanNumber.TRUE)}});return t.next(!1),n.dispose}),hidden$:l.getMenuHiddenObservable(i,s.UniverInstanceType.UNIVER_DOC)}}function gn(i){const e=i.get(s.ICommandService);return{id:d.SetInlineFormatUnderlineCommand.id,group:l.MenuGroup.TOOLBAR_FORMAT,type:l.MenuItemType.BUTTON,icon:"UnderlineSingle",title:"Set underline",tooltip:"toolbar.underline",positions:[l.MenuPosition.TOOLBAR_START],activated$:new M.Observable(t=>{const n=e.onCommandExecuted(o=>{var a;const r=o.id;if(r===d.SetTextSelectionsOperation.id||r===d.SetInlineFormatCommand.id){const c=$(i);if(c==null)return;const u=(a=c.ts)==null?void 0:a.ul;t.next((u==null?void 0:u.s)===s.BooleanNumber.TRUE)}});return t.next(!1),n.dispose}),hidden$:l.getMenuHiddenObservable(i,s.UniverInstanceType.UNIVER_DOC)}}function _n(i){const e=i.get(s.ICommandService);return{id:d.SetInlineFormatStrikethroughCommand.id,group:l.MenuGroup.TOOLBAR_FORMAT,type:l.MenuItemType.BUTTON,icon:"StrikethroughSingle",title:"Set strike through",tooltip:"toolbar.strikethrough",positions:[l.MenuPosition.TOOLBAR_START],activated$:new M.Observable(t=>{const n=e.onCommandExecuted(o=>{var a;const r=o.id;if(r===d.SetTextSelectionsOperation.id||r===d.SetInlineFormatCommand.id){const c=$(i);if(c==null)return;const u=(a=c.ts)==null?void 0:a.st;t.next((u==null?void 0:u.s)===s.BooleanNumber.TRUE)}});return t.next(!1),n.dispose}),hidden$:l.getMenuHiddenObservable(i,s.UniverInstanceType.UNIVER_DOC)}}function mn(i){const e=i.get(s.ICommandService);return{id:d.SetInlineFormatSubscriptCommand.id,group:l.MenuGroup.TOOLBAR_FORMAT,type:l.MenuItemType.BUTTON,icon:"SubscriptSingle",tooltip:"toolbar.subscript",positions:[l.MenuPosition.TOOLBAR_START],activated$:new M.Observable(t=>{const n=e.onCommandExecuted(o=>{var a;const r=o.id;if(r===d.SetTextSelectionsOperation.id||r===d.SetInlineFormatCommand.id){const c=$(i);if(c==null)return;const u=(a=c.ts)==null?void 0:a.va;t.next(u===s.BaselineOffset.SUBSCRIPT)}});return t.next(!1),n.dispose}),hidden$:l.getMenuHiddenObservable(i,s.UniverInstanceType.UNIVER_DOC)}}function Sn(i){const e=i.get(s.ICommandService);return{id:d.SetInlineFormatSuperscriptCommand.id,group:l.MenuGroup.TOOLBAR_FORMAT,type:l.MenuItemType.BUTTON,icon:"SuperscriptSingle",tooltip:"toolbar.superscript",positions:[l.MenuPosition.TOOLBAR_START],activated$:new M.Observable(t=>{const n=e.onCommandExecuted(o=>{var a;const r=o.id;if(r===d.SetTextSelectionsOperation.id||r===d.SetInlineFormatCommand.id){const c=$(i);if(c==null)return;const u=(a=c.ts)==null?void 0:a.va;t.next(u===s.BaselineOffset.SUPERSCRIPT)}});return t.next(!1),n.dispose}),hidden$:l.getMenuHiddenObservable(i,s.UniverInstanceType.UNIVER_DOC)}}function fn(i){const e=i.get(s.ICommandService);return{id:d.SetInlineFormatFontFamilyCommand.id,tooltip:"toolbar.font",group:l.MenuGroup.TOOLBAR_FORMAT,type:l.MenuItemType.SELECTOR,label:ze,positions:[l.MenuPosition.TOOLBAR_START],selections:l.FONT_FAMILY_LIST.map(t=>({label:{name:Xe,hoverable:!0},value:t.value})),value$:new M.Observable(t=>{const n=l.FONT_FAMILY_LIST[0].value,o=e.onCommandExecuted(r=>{var c;const a=r.id;if(a===d.SetTextSelectionsOperation.id||a===d.SetInlineFormatFontFamilyCommand.id){const u=$(i);if(u==null)return;const h=(c=u.ts)==null?void 0:c.ff;t.next(h!=null?h:n)}});return t.next(n),o.dispose}),hidden$:l.getMenuHiddenObservable(i,s.UniverInstanceType.UNIVER_DOC)}}function vn(i){const e=i.get(s.ICommandService);return{id:d.SetInlineFormatFontSizeCommand.id,group:l.MenuGroup.TOOLBAR_FORMAT,type:l.MenuItemType.SELECTOR,tooltip:"toolbar.fontSize",label:{name:Ze,props:{min:1,max:400}},positions:[l.MenuPosition.TOOLBAR_START],selections:l.FONT_SIZE_LIST,value$:new M.Observable(t=>{const o=e.onCommandExecuted(r=>{var c;const a=r.id;if(a===d.SetTextSelectionsOperation.id||a===d.SetInlineFormatFontSizeCommand.id){const u=$(i);if(u==null)return;const h=(c=u.ts)==null?void 0:c.fs;t.next(h!=null?h:14)}});return t.next(14),o.dispose}),hidden$:l.getMenuHiddenObservable(i,s.UniverInstanceType.UNIVER_DOC)}}function Cn(i){const e=i.get(s.ICommandService),t=i.get(s.ThemeService);return{id:d.SetInlineFormatTextColorCommand.id,icon:"FontColor",tooltip:"toolbar.textColor.main",group:l.MenuGroup.TOOLBAR_FORMAT,type:l.MenuItemType.BUTTON_SELECTOR,positions:[l.MenuPosition.TOOLBAR_START],selections:[{label:{name:Se,hoverable:!1}}],value$:new M.Observable(n=>{const o=t.getCurrentTheme().textColor,r=e.onCommandExecuted(a=>{if(a.id===d.SetInlineFormatTextColorCommand.id){const c=a.params.value;n.next(c!=null?c:o)}});return n.next(o),r.dispose}),hidden$:l.getMenuHiddenObservable(i,s.UniverInstanceType.UNIVER_DOC)}}function In(i){return{id:at.id,group:l.MenuGroup.TOOLBAR_OTHERS,type:l.MenuItemType.BUTTON,icon:"FreezeRowSingle",tooltip:"toolbar.headerFooter",positions:[l.MenuPosition.TOOLBAR_START],hidden$:M.combineLatest(l.getMenuHiddenObservable(i,s.UniverInstanceType.UNIVER_DOC),l.getHeaderFooterMenuHiddenObservable(i),(e,t)=>e||t)}}function On(i){const e=i.get(s.ICommandService);return{id:d.AlignLeftCommand.id,group:l.MenuGroup.TOOLBAR_LAYOUT,type:l.MenuItemType.BUTTON,icon:"LeftJustifyingSingle",tooltip:"toolbar.alignLeft",positions:[l.MenuPosition.TOOLBAR_START],activated$:new M.Observable(t=>{const n=e.onCommandExecuted(o=>{var a;const r=o.id;if(r===d.SetTextSelectionsOperation.id||r===d.AlignOperationCommand.id){const c=se(i);if(c==null)return;const u=(a=c.paragraphStyle)==null?void 0:a.horizontalAlign;t.next(u===s.HorizontalAlign.LEFT)}});return t.next(!1),n.dispose}),hidden$:l.getMenuHiddenObservable(i,s.UniverInstanceType.UNIVER_DOC)}}function Tn(i){const e=i.get(s.ICommandService);return{id:d.AlignCenterCommand.id,group:l.MenuGroup.TOOLBAR_LAYOUT,type:l.MenuItemType.BUTTON,icon:"HorizontallySingle",tooltip:"toolbar.alignCenter",positions:[l.MenuPosition.TOOLBAR_START],activated$:new M.Observable(t=>{const n=e.onCommandExecuted(o=>{var a;const r=o.id;if(r===d.SetTextSelectionsOperation.id||r===d.AlignOperationCommand.id){const c=se(i);if(c==null)return;const u=(a=c.paragraphStyle)==null?void 0:a.horizontalAlign;t.next(u===s.HorizontalAlign.CENTER)}});return t.next(!1),n.dispose}),hidden$:l.getMenuHiddenObservable(i,s.UniverInstanceType.UNIVER_DOC)}}function Mn(i){const e=i.get(s.ICommandService);return{id:d.AlignRightCommand.id,group:l.MenuGroup.TOOLBAR_LAYOUT,type:l.MenuItemType.BUTTON,icon:"RightJustifyingSingle",tooltip:"toolbar.alignRight",positions:[l.MenuPosition.TOOLBAR_START],activated$:new M.Observable(t=>{const n=e.onCommandExecuted(o=>{var a;const r=o.id;if(r===d.SetTextSelectionsOperation.id||r===d.AlignOperationCommand.id){const c=se(i);if(c==null)return;const u=(a=c.paragraphStyle)==null?void 0:a.horizontalAlign;t.next(u===s.HorizontalAlign.RIGHT)}});return t.next(!1),n.dispose}),hidden$:l.getMenuHiddenObservable(i,s.UniverInstanceType.UNIVER_DOC)}}function En(i){const e=i.get(s.ICommandService);return{id:d.AlignJustifyCommand.id,group:l.MenuGroup.TOOLBAR_LAYOUT,type:l.MenuItemType.BUTTON,icon:"AlignTextBothSingle",tooltip:"toolbar.alignJustify",positions:[l.MenuPosition.TOOLBAR_START],activated$:new M.Observable(t=>{const n=e.onCommandExecuted(o=>{var a;const r=o.id;if(r===d.SetTextSelectionsOperation.id||r===d.AlignOperationCommand.id){const c=se(i);if(c==null)return;const u=(a=c.paragraphStyle)==null?void 0:a.horizontalAlign;t.next(u===s.HorizontalAlign.JUSTIFIED)}});return t.next(!1),n.dispose}),hidden$:l.getMenuHiddenObservable(i,s.UniverInstanceType.UNIVER_DOC)}}function Rn(i){return{id:d.OrderListCommand.id,group:l.MenuGroup.TOOLBAR_LAYOUT,type:l.MenuItemType.BUTTON,icon:"OrderSingle",tooltip:"toolbar.order",positions:[l.MenuPosition.TOOLBAR_START],hidden$:l.getMenuHiddenObservable(i,s.UniverInstanceType.UNIVER_DOC)}}function bn(i){return{id:d.BulletListCommand.id,group:l.MenuGroup.TOOLBAR_LAYOUT,type:l.MenuItemType.BUTTON,icon:"UnorderSingle",tooltip:"toolbar.unorder",positions:[l.MenuPosition.TOOLBAR_START],hidden$:l.getMenuHiddenObservable(i,s.UniverInstanceType.UNIVER_DOC)}}function Dn(i){return{id:d.ResetInlineFormatTextBackgroundColorCommand.id,type:l.MenuItemType.BUTTON,title:"toolbar.resetColor",icon:"NoColor",positions:d.SetInlineFormatTextBackgroundColorCommand.id}}function yn(i){const e=i.get(s.ICommandService),t=i.get(s.ThemeService);return{id:d.SetInlineFormatTextBackgroundColorCommand.id,tooltip:"toolbar.fillColor.main",group:l.MenuGroup.TOOLBAR_FORMAT,type:l.MenuItemType.BUTTON_SELECTOR,positions:[l.MenuPosition.TOOLBAR_START],icon:"PaintBucket",selections:[{label:{name:Se,hoverable:!1}}],value$:new M.Observable(n=>{const o=t.getCurrentTheme().primaryColor,r=e.onCommandExecuted(a=>{if(a.id===d.SetInlineFormatTextBackgroundColorCommand.id){const c=a.params.value;n.next(c!=null?c:o)}});return n.next(o),r.dispose}),hidden$:l.getMenuHiddenObservable(i,s.UniverInstanceType.UNIVER_DOC)}}function $(i){var h;const e=i.get(s.IUniverInstanceService),t=i.get(d.TextSelectionManagerService),n=e.getCurrentUniverDocInstance(),o=t.getActiveRange();if(n==null||o==null)return;const{startOffset:r,segmentId:a}=o,c=(h=n.getSelfOrHeaderFooterModel(a).getBody())==null?void 0:h.textRuns;if(c==null)return;let u;for(let _=0;_<c.length;_++){const m=c[_],S=c[_+1];if(S&&S.st===S.ed&&r===S.st){u=S;break}if(m.st<=r&&r<=m.ed){u=m;break}}return u}function se(i){var h;const e=i.get(s.IUniverInstanceService),t=i.get(d.TextSelectionManagerService),n=e.getCurrentUniverDocInstance(),o=t.getActiveRange();if(n==null||o==null)return;const{startOffset:r,segmentId:a}=o,c=(h=n.getSelfOrHeaderFooterModel(a).getBody())==null?void 0:h.paragraphs;if(c==null)return;let u=-1;for(const _ of c){const{startIndex:m}=_;if(r>u&&r<=m)return _;u=m}return null}function ae(i){return i.getContextValue(s.FOCUSING_DOC)||i.getContextValue(s.EDITOR_ACTIVATED)}const Ie=999,Oe={id:l.CopyCommand.id,name:"doc.command.copy",type:s.CommandType.COMMAND,multi:!0,priority:Ie,preconditions:ae,handler:async i=>i.get(G).copy()},Te={id:l.CutCommand.id,name:"doc.command.cut",type:s.CommandType.COMMAND,multi:!0,priority:Ie,preconditions:ae,handler:async i=>i.get(G).cut()},Me={id:l.PasteCommand.id,name:"doc.command.paste",type:s.CommandType.COMMAND,multi:!0,priority:Ie,preconditions:ae,handler:async i=>{const e=i.get(G),n=await i.get(l.IClipboardInterfaceService).read();return n.length===0?!1:e.paste(n)}},Ee=i=>{const e=i.get(d.TextSelectionManagerService);return new M.Observable(t=>{const n=e.textSelection$.subscribe(o=>{const r=e.getActiveRange();r&&!r.collapsed?t.next(!1):t.next(!0)});return()=>n.unsubscribe()})},Pn=i=>({id:Oe.id,group:l.MenuGroup.CONTEXT_MENU_FORMAT,type:l.MenuItemType.BUTTON,icon:"Copy",title:"rightClick.copy",positions:[l.MenuPosition.CONTEXT_MENU],disabled$:Ee(i),hidden$:l.getMenuHiddenObservable(i,s.UniverInstanceType.UNIVER_DOC)}),An=i=>({id:Te.id,group:l.MenuGroup.CONTEXT_MENU_FORMAT,type:l.MenuItemType.BUTTON,icon:"Copy",title:"rightClick.cut",positions:[l.MenuPosition.CONTEXT_MENU],disabled$:Ee(i),hidden$:l.getMenuHiddenObservable(i,s.UniverInstanceType.UNIVER_DOC)}),Nn=i=>({id:Me.id,group:l.MenuGroup.CONTEXT_MENU_FORMAT,type:l.MenuItemType.BUTTON,icon:"PasteSpecial",title:"rightClick.paste",positions:[l.MenuPosition.CONTEXT_MENU],hidden$:l.getMenuHiddenObservable(i,s.UniverInstanceType.UNIVER_DOC)}),Un=i=>({id:d.DeleteLeftCommand.id,group:l.MenuGroup.CONTEXT_MENU_FORMAT,type:l.MenuItemType.BUTTON,icon:"PasteSpecial",title:"rightClick.delete",positions:[l.MenuPosition.CONTEXT_MENU],disabled$:Ee(i),hidden$:l.getMenuHiddenObservable(i,s.UniverInstanceType.UNIVER_DOC)}),xn={id:d.SetInlineFormatBoldCommand.id,binding:l.KeyCode.B|l.MetaKeys.CTRL_COMMAND,preconditions:A},Fn={id:d.SetInlineFormatItalicCommand.id,binding:l.KeyCode.I|l.MetaKeys.CTRL_COMMAND,preconditions:A},Ln={id:d.SetInlineFormatUnderlineCommand.id,binding:l.KeyCode.U|l.MetaKeys.CTRL_COMMAND,preconditions:A},Bn={id:d.SetInlineFormatStrikethroughCommand.id,binding:l.KeyCode.X|l.MetaKeys.SHIFT|l.MetaKeys.CTRL_COMMAND,preconditions:A},wn={id:d.SetInlineFormatSubscriptCommand.id,binding:l.KeyCode.COMMA|l.MetaKeys.CTRL_COMMAND,preconditions:A},$n={id:d.SetInlineFormatSuperscriptCommand.id,binding:l.KeyCode.PERIOD|l.MetaKeys.CTRL_COMMAND,preconditions:A},Hn={id:d.AlignLeftCommand.id,binding:l.KeyCode.L|l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT,preconditions:A},Vn={id:d.AlignRightCommand.id,binding:l.KeyCode.R|l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT,preconditions:A},jn={id:d.AlignCenterCommand.id,binding:l.KeyCode.E|l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT,preconditions:A},Wn={id:d.AlignJustifyCommand.id,binding:l.KeyCode.J|l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT,preconditions:A},Gn={id:d.OrderListCommand.id,binding:l.KeyCode.Digit7|l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT,preconditions:A},kn={id:d.BulletListCommand.id,binding:l.KeyCode.Digit8|l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT,preconditions:A};var Kn=Object.defineProperty,Yn=Object.getOwnPropertyDescriptor,zn=(i,e,t,n)=>{for(var o=n>1?void 0:n?Yn(e,t):e,r=i.length-1,a;r>=0;r--)(a=i[r])&&(o=(n?a(e,t,o):a(o))||o);return n&&o&&Kn(e,t,o),o},V=(i,e)=>(t,n)=>e(t,n,i);let X=class extends s.Disposable{constructor(i,e,t,n,o,r,a,c){super(),this._config=i,this._injector=e,this._componentManager=t,this._layoutService=n,this._menuService=o,this._uiPartsService=r,this._univerInstanceService=a,this._shortcutService=c,this._init()}_initCustomComponents(){const i=this._componentManager;this.disposeWithMe(i.register(Se,H.ColorPicker)),this.disposeWithMe(i.register(ze,l.FontFamily)),this.disposeWithMe(i.register(Xe,l.FontFamilyItem)),this.disposeWithMe(i.register(Ze,l.FontSize))}_initUiParts(){var e,t;const i=this._univerInstanceService.getCurrentUnitForType(s.UniverInstanceType.UNIVER_SHEET);(t=(e=this._config.layout)==null?void 0:e.docContainerConfig)!=null&&t.footer&&!i&&this.disposeWithMe(this._uiPartsService.registerComponent(l.BuiltInUIPart.FOOTER,()=>s.connectInjector(nn,this._injector)))}_initMenus(){const{menu:i={}}=this._config;[hn,pn,gn,_n,mn,Sn,vn,fn,Cn,In,On,Tn,Mn,En,Rn,bn,Dn,yn].forEach(e=>{this.disposeWithMe(this._menuService.addMenuItem(this._injector.invoke(e),i))}),[Pn,An,Nn,Un].forEach(e=>{try{this.disposeWithMe(this._menuService.addMenuItem(this._injector.invoke(e),i))}catch{}})}_initShortCut(){[xn,Fn,Ln,Bn,wn,$n,jn,Wn,Vn,Hn,Gn,kn].forEach(i=>{this.disposeWithMe(this._shortcutService.registerShortcut(i))})}_init(){this._initCustomComponents(),this._initMenus(),this._initFocusHandler(),this._initUiParts(),this._initShortCut()}_initFocusHandler(){this.disposeWithMe(this._layoutService.registerFocusHandler(s.UniverInstanceType.UNIVER_DOC,()=>{this._injector.get(C.ITextSelectionRenderManager).focus()}))}};X=zn([s.OnLifecycle(s.LifecycleStages.Rendered,X),V(1,s.Inject(s.Injector)),V(2,s.Inject(l.ComponentManager)),V(3,l.ILayoutService),V(4,l.IMenuService),V(5,l.IUIPartsService),V(6,s.IUniverInstanceService),V(7,l.IShortcutService)],X);const Xn={id:d.BreakLineCommand.id,preconditions:_t,binding:l.KeyCode.ENTER},Zn={id:d.DeleteLeftCommand.id,preconditions:A,binding:l.KeyCode.BACKSPACE},Jn={id:d.DeleteRightCommand.id,preconditions:A,binding:l.KeyCode.DELETE};var qn=Object.defineProperty,Qn=Object.getOwnPropertyDescriptor,ei=(i,e,t,n)=>{for(var o=n>1?void 0:n?Qn(e,t):e,r=i.length-1,a;r>=0;r--)(a=i[r])&&(o=(n?a(e,t,o):a(o))||o);return n&&o&&qn(e,t,o),o},Z=(i,e)=>(t,n)=>e(t,n,i);let ce=class extends s.RxDisposable{constructor(i,e,t,n,o){super(),this._commandService=i,this._clipboardInterfaceService=e,this._docClipboardService=t,this._textSelectionRenderManager=n,this._contextService=o,this._init()}_init(){[Oe,Te,Me].forEach(i=>this.disposeWithMe(this._commandService.registerMultipleCommand(i))),[d.InnerPasteCommand,d.CutContentCommand].forEach(i=>this.disposeWithMe(this._commandService.registerCommand(i))),this._initLegacyPasteCommand()}_initLegacyPasteCommand(){var i;(i=this._textSelectionRenderManager)==null||i.onPaste$.pipe(M.takeUntil(this.dispose$)).subscribe(e=>{var r,a;if(!ae(this._contextService))return;e.event.preventDefault();const t=e.event,n=(r=t.clipboardData)==null?void 0:r.getData("text/html"),o=(a=t.clipboardData)==null?void 0:a.getData("text/plain");this._docClipboardService.legacyPaste(n,o)})}};ce=ei([s.OnLifecycle(s.LifecycleStages.Rendered,ce),Z(0,s.ICommandService),Z(1,l.IClipboardInterfaceService),Z(2,G),Z(3,C.ITextSelectionRenderManager),Z(4,s.IContextService)],ce);var ti=Object.defineProperty,ni=Object.getOwnPropertyDescriptor,ii=(i,e,t,n)=>{for(var o=n>1?void 0:n?ni(e,t):e,r=i.length-1,a;r>=0;r--)(a=i[r])&&(o=(n?a(e,t,o):a(o))||o);return n&&o&&ti(e,t,o),o},J=(i,e)=>(t,n)=>e(t,n,i);let le=class extends s.Disposable{constructor(e,t,n,o,r){super();y(this,"_initialEditors",new Set);this._univerInstanceService=e,this._editorService=t,this._commandService=n,this._textSelectionRenderManager=o,this._renderManagerService=r,this._initialize()}_initialize(){this.disposeWithMe(this._editorService.resize$.subscribe(e=>{this._resize(e)})),this._editorService.getAllEditor().forEach(e=>{const t=e.editorUnitId;this._initialEditors.has(t)||(this._initialEditors.add(t),this._resize(t))}),this._commandExecutedListener(),this._initialSetValue(),this._initialBlur(),this._initialFocus(),this._initialValueChange()}_resize(e){var E,R,D;if(e==null)return;const t=this._editorService.getEditor(e);if((t==null?void 0:t.cancelDefaultResizeListener)===!0)return;const n=this._univerInstanceService.getUniverDocInstance(e);if(!n)return;const o=(E=this._renderManagerService.getRenderById(n.getUnitId()))==null?void 0:E.with(d.DocSkeletonManagerService).getSkeleton();if(t==null||t.render==null||o==null||n==null)return;o.calculate();const{marginTop:r=0,marginBottom:a=0,marginLeft:c=0,marginRight:u=0}=n.getSnapshot().documentStyle,{scene:h,mainComponent:_}=t.render;let{actualHeight:m,actualWidth:S}=o.getActualSize();m+=r+a,S+=c+u;const{width:p,height:f}=t.getBoundingClientRect(),g=h.getViewport(d.VIEWPORT_KEY.VIEW_MAIN);let v=g==null?void 0:g.getScrollBar();const O=Math.max(S,p),T=Math.max(m,f);h.transformByState({width:O,height:T}),_==null||_.resize(O,T),t.isSingle()?S>p?v==null?g&&new C.ScrollBar(g,{barSize:8,enableVertical:!1}):g==null||g.resetCanvasSizeAndUpdateScroll():(v=null,g==null||g.scrollToBarPos({x:0,y:0}),(D=g==null?void 0:g.getScrollBar())==null||D.dispose()):m>f?v==null?g&&new C.ScrollBar(g,{enableHorizontal:!1,barSize:8}):g==null||g.resetCanvasSizeAndUpdateScroll():(v=null,g==null||g.scrollToBarPos({x:0,y:0}),(R=g==null?void 0:g.getScrollBar())==null||R.dispose())}_initialSetValue(){this.disposeWithMe(this._editorService.setValue$.subscribe(e=>{this._commandService.executeCommand(d.CoverContentCommand.id,{unitId:e.editorUnitId,body:e.body,segmentId:null})}))}_initialBlur(){this.disposeWithMe(this._editorService.blur$.subscribe(()=>{this._textSelectionRenderManager.removeAllTextRanges(),this._textSelectionRenderManager.blur()})),this.disposeWithMe(this._textSelectionRenderManager.onBlur$.subscribe(()=>{var o;const e=(o=this._univerInstanceService.getCurrentUniverDocInstance())==null?void 0:o.getUnitId();if(e==null)return;const t=this._editorService.getEditor(e),n=this._editorService.getFocusEditor();t==null||t.isSheetEditor()||n&&n.editorUnitId===e||this._editorService.blur()}))}_initialFocus(){this.disposeWithMe(this._editorService.focus$.subscribe(n=>{this._textSelectionRenderManager.removeAllTextRanges(),this._textSelectionRenderManager.addTextRanges([n])}));const e=["univer-formula-search","univer-formula-help","formula-help-decorator","univer-formula-help-param"];this.disposeWithMe(M.fromEvent(window,"mousedown").subscribe(n=>{const r=n.target.classList[0]||"";if(s.checkForSubstrings(r,e)){this._editorService.changeSpreadsheetFocusState(!0),n.stopPropagation();return}this._editorService.changeSpreadsheetFocusState(!1)})),this._univerInstanceService.getAllUnitsForType(s.UniverInstanceType.UNIVER_SHEET).forEach(n=>{const o=n.getUnitId(),r=this._renderManagerService.getRenderById(o),a=r==null?void 0:r.engine.getCanvas().getCanvasEle();a!=null&&M.fromEvent(a,"mousedown").subscribe(c=>{this._editorService.changeSpreadsheetFocusState(!0),c.stopPropagation()})})}_initialValueChange(){this.disposeWithMe(this._textSelectionRenderManager.onCompositionupdate$.subscribe(this._valueChange.bind(this))),this.disposeWithMe(this._textSelectionRenderManager.onInput$.subscribe(this._valueChange.bind(this))),this.disposeWithMe(this._textSelectionRenderManager.onKeydown$.subscribe(this._valueChange.bind(this))),this.disposeWithMe(this._textSelectionRenderManager.onPaste$.subscribe(this._valueChange.bind(this)))}_valueChange(){var n;const e=(n=this._univerInstanceService.getCurrentUniverDocInstance())==null?void 0:n.getUnitId();if(e==null)return;const t=this._editorService.getEditor(e);t==null||t.isSheetEditor()||this._editorService.refreshValueChange(e)}_commandExecutedListener(){const e=[d.RichTextEditingMutation.id,l.SetEditorResizeOperation.id];this.disposeWithMe(this._commandService.onCommandExecuted(t=>{if(e.includes(t.id)){const n=t.params,{unitId:o}=n;if(this._editorService.isSheetEditor(o))return;this._resize(o),this._valueChange()}}))}};le=ii([s.OnLifecycle(s.LifecycleStages.Rendered,le),J(0,s.IUniverInstanceService),J(1,l.IEditorService),J(2,s.ICommandService),J(3,C.ITextSelectionRenderManager),J(4,C.IRenderManagerService)],le);var oi=Object.defineProperty,ri=Object.getOwnPropertyDescriptor,si=(i,e,t,n)=>{for(var o=n>1?void 0:n?ri(e,t):e,r=i.length-1,a;r>=0;r--)(a=i[r])&&(o=(n?a(e,t,o):a(o))||o);return n&&o&&oi(e,t,o),o},q=(i,e)=>(t,n)=>e(t,n,i);I.DocRenderController=class extends s.RxDisposable{constructor(e,t,n,o,r,a){super(),this._context=e,this._commandService=t,this._docSkeletonManagerService=n,this._configService=o,this._editorService=r,this._renderManagerService=a,this._addNewRender(),this._initRenderRefresh(),this._initCommandListener()}reRender(e){var r,a;const t=(r=this._renderManagerService.getRenderById(e))==null?void 0:r.with(d.DocSkeletonManagerService),n=t==null?void 0:t.getSkeleton();if(!(!n||n.getViewModel().getDataModel().getSnapshot().disabled)){if(n.calculate(),this._editorService.isEditor(e)){(a=this._context.mainComponent)==null||a.makeDirty();return}this._recalculateSizeBySkeleton(n)}}_addNewRender(){const{scene:e,engine:t,unit:n}=this._context,o=new C.Viewport(d.VIEWPORT_KEY.VIEW_MAIN,e,{left:0,top:0,bottom:0,right:0,isRelativeX:!0,isRelativeY:!0,isWheelPreventDefaultX:!0});e.attachControl(),e.onMouseWheel$.subscribeEvent((c,u)=>{const h=c;if(h.ctrlKey){const _=Math.abs(h.deltaX);let m=_<40?.2:_<80?.4:.2;m*=h.deltaY>0?-1:1,e.scaleX<1&&(m/=2),e.scaleX+m>4?e.scale(4,4):e.scaleX+m<.1?e.scale(.1,.1):h.preventDefault()}else o.onMouseWheel(h,u)}),this._configService.getConfig("hasScroll")!==!1&&new C.ScrollBar(o),e.addLayer(new C.Layer(e,[],d.DOCS_COMPONENT_MAIN_LAYER_INDEX),new C.Layer(e,[],d.DOCS_COMPONENT_HEADER_LAYER_INDEX)),this._addComponent(),n.getShouldRenderLoopImmediately()&&t.runRenderLoop(()=>{e.render()})}_addComponent(){const{scene:e,unit:t,components:n}=this._context,o={pageMarginLeft:t.documentStyle.marginLeft||0,pageMarginTop:t.documentStyle.marginTop||0},r=new C.Documents(d.DOCS_VIEW_KEY.MAIN,void 0,o);r.zIndex=d.DOCS_COMPONENT_DEFAULT_Z_INDEX;const a=new C.DocBackground(d.DOCS_VIEW_KEY.BACKGROUND,void 0,o);a.zIndex=d.DOCS_COMPONENT_DEFAULT_Z_INDEX,this._context.mainComponent=r,n.set(d.DOCS_VIEW_KEY.MAIN,r),n.set(d.DOCS_VIEW_KEY.BACKGROUND,a),e.addObjects([r],d.DOCS_COMPONENT_MAIN_LAYER_INDEX),e.addObjects([a],d.DOCS_COMPONENT_BACKGROUND_LAYER_INDEX),this._editorService.getEditor(t.getUnitId())==null&&e.enableLayerCache(d.DOCS_COMPONENT_MAIN_LAYER_INDEX)}_initRenderRefresh(){this._docSkeletonManagerService.currentSkeletonBefore$.pipe(M.takeUntil(this.dispose$)).subscribe(e=>{this._create(e)})}_create(e){if(!e)return;const{mainComponent:t,components:n}=this._context,o=t,r=n.get(d.DOCS_VIEW_KEY.BACKGROUND);o.changeSkeleton(e),r.changeSkeleton(e),this._recalculateSizeBySkeleton(e)}_initCommandListener(){const e=[d.RichTextEditingMutation.id];this.disposeWithMe(this._commandService.onCommandExecuted(t=>{if(e.includes(t.id)){const n=t.params,{unitId:o}=n;this.reRender(o)}}))}_recalculateSizeBySkeleton(e){var m;const{mainComponent:t,scene:n,unitId:o,components:r}=this._context,a=t,c=r.get(d.DOCS_VIEW_KEY.BACKGROUND),u=(m=e.getSkeletonData())==null?void 0:m.pages;if(u==null)return;let h=0,_=0;for(let S=0,p=u.length;S<p;S++){const f=u[S],{pageWidth:g,pageHeight:v}=f;a.pageLayoutType===C.PageLayoutType.VERTICAL?(_+=v,_+=a.pageMarginTop,S===p-1&&(_+=a.pageMarginTop),h=Math.max(h,g)):a.pageLayoutType===C.PageLayoutType.HORIZONTAL&&(h+=g,S!==p-1&&(h+=a.pageMarginLeft),_=Math.max(_,v))}a.resize(h,_),c.resize(h,_),this._editorService.isEditor(o)||n.resize(h,_)}},I.DocRenderController=si([q(1,s.ICommandService),q(2,s.Inject(d.DocSkeletonManagerService)),q(3,s.IConfigService),q(4,l.IEditorService),q(5,C.IRenderManagerService)],I.DocRenderController);class Re extends s.Disposable{constructor(e){super(),this._context=e}calculatePagePosition(){var R,D;const e=d.neoGetDocObject(this._context),n=(D=(R=this._context.unit.getSettings())==null?void 0:R.zoomRatio)!=null?D:1,{document:o,scene:r,docBackground:a}=e,c=r==null?void 0:r.getParent(),{width:u,height:h,pageMarginLeft:_,pageMarginTop:m}=o;if(c==null||u===Number.POSITIVE_INFINITY||h===Number.POSITIVE_INFINITY)return;const{width:S,height:p}=c;let f=0,g=0,v=0,O=0,T=Number.POSITIVE_INFINITY;S>(u+_*2)*n?(f=S/2-u*n/2,f/=n,v=(S-_*2)/n,T=0):(f=_,v=u+_*2,T=(v-S/n)/2),p>h?(g=p/2-h/2,O=(p-m*2)/n):(g=m,O=h+m*2),r.resize(v,O+200),o.translate(f,g),a.translate(f,g);const E=r.getViewport(d.VIEWPORT_KEY.VIEW_MAIN);return T!==Number.POSITIVE_INFINITY&&E!=null&&E.scrollToViewportPos({viewportScrollX:T}),this}}var ai=Object.defineProperty,ci=Object.getOwnPropertyDescriptor,li=(i,e,t,n)=>{for(var o=n>1?void 0:n?ci(e,t):e,r=i.length-1,a;r>=0;r--)(a=i[r])&&(o=(n?a(e,t,o):a(o))||o);return n&&o&&ai(e,t,o),o},k=(i,e)=>(t,n)=>e(t,n,i);let be=class extends s.Disposable{constructor(i,e,t,n,o,r,a){super(),this._context=i,this._docSkeletonManagerService=e,this._univerInstanceService=t,this._commandService=n,this._textSelectionManagerService=o,this._editorService=r,this._docPageLayoutService=a,this._init()}_init(){this._initSkeletonListener(),this._initCommandExecutedListener(),this._initRenderRefresher(),setTimeout(()=>this.updateViewZoom(1,!0),20)}_initRenderRefresher(){this._docSkeletonManagerService.currentSkeleton$.subscribe(i=>{if(i==null)return;const{unitId:e,scene:t}=this._context;this._editorService.isEditor(e)||this.disposeWithMe(t.onMouseWheel$.subscribeEvent(n=>{if(!n.ctrlKey)return;const o=this._univerInstanceService.getCurrentUniverDocInstance();if(!o)return;const r=Math.abs(n.deltaX);let a=r<40?.2:r<80?.4:.2;a*=n.deltaY>0?-1:1,t.scaleX<1&&(a/=2);const c=o.zoomRatio;let u=+Number.parseFloat(`${c+a}`).toFixed(1);u=u>=4?4:u<=.1?.1:u,this._commandService.executeCommand(d.SetDocZoomRatioCommand.id,{zoomRatio:u,unitId:o.getUnitId()}),n.preventDefault()}))})}_initSkeletonListener(){this.disposeWithMe(this._docSkeletonManagerService.currentSkeleton$.subscribe(i=>{if(i==null)return;const e=this._univerInstanceService.getCurrentUniverDocInstance();if(!e)return;const t=e.zoomRatio||1;this.updateViewZoom(t,!1)}))}_initCommandExecutedListener(){const i=[d.SetDocZoomRatioOperation.id];this.disposeWithMe(this._commandService.onCommandExecuted(e=>{if(i.includes(e.id)){const t=this._univerInstanceService.getCurrentUniverDocInstance();if(!t)return;const n=e.params,{unitId:o}=n;if(o!==t.getUnitId())return;const r=t.zoomRatio||1;this.updateViewZoom(r)}}))}updateViewZoom(i,e=!0){var n;const t=d.neoGetDocObject(this._context);t.scene.scale(i,i),this._docPageLayoutService.calculatePagePosition(),e&&!this._editorService.isEditor(this._context.unitId)&&this._textSelectionManagerService.refreshSelection(),(n=t.scene.getTransformer())==null||n.clearSelectedObjects()}};be=li([k(1,s.Inject(d.DocSkeletonManagerService)),k(2,s.IUniverInstanceService),k(3,s.ICommandService),k(4,s.Inject(d.TextSelectionManagerService)),k(5,l.IEditorService),k(6,s.Inject(Re))],be);var di=Object.defineProperty,ui=Object.getOwnPropertyDescriptor,hi=(i,e,t,n)=>{for(var o=n>1?void 0:n?ui(e,t):e,r=i.length-1,a;r>=0;r--)(a=i[r])&&(o=(n?a(e,t,o):a(o))||o);return n&&o&&di(e,t,o),o},K=(i,e)=>(t,n)=>e(t,n,i);let De=class extends s.Disposable{constructor(e,t,n,o,r,a,c){super();y(this,"_loadedMap",new WeakSet);this._context=e,this._commandService=t,this._editorService=n,this._instanceSrv=o,this._textSelectionRenderManager=r,this._docSkeletonManagerService=a,this._textSelectionManagerService=c,this._initialize()}_initialize(){this._init(),this._skeletonListener(),this._commandExecutedListener()}_init(){const{unitId:e}=this._context,t=d.neoGetDocObject(this._context);t==null||t.document==null||this._loadedMap.has(t.document)||(this._initialMain(e),this._loadedMap.add(t.document))}_initialMain(e){const t=d.neoGetDocObject(this._context),{document:n,scene:o}=t;this.disposeWithMe(n.onPointerEnter$.subscribeEvent(()=>{this._isEditorReadOnly(e)||(n.cursor=C.CURSOR_TYPE.TEXT)})),this.disposeWithMe(n.onPointerLeave$.subscribeEvent(()=>{n.cursor=C.CURSOR_TYPE.DEFAULT,o.resetCursor()})),this.disposeWithMe(n.onPointerDown$.subscribeEvent((r,a)=>{if(this._isEditorReadOnly(e))return;const c=this._instanceSrv.getCurrentUnitForType(s.UniverInstanceType.UNIVER_DOC);(c==null?void 0:c.getUnitId())!==e&&this._instanceSrv.setCurrentUnitForType(e);const u=this._docSkeletonManagerService.getSkeleton(),{offsetX:h,offsetY:_}=r,m=this._getTransformCoordForDocumentOffset(h,_);if(m!=null){const{pageLayoutType:S=C.PageLayoutType.VERTICAL,pageMarginLeft:p,pageMarginTop:f}=n.getOffsetConfig(),{editArea:g}=u.findEditAreaByCoord(m,S,p,f),v=this._docSkeletonManagerService.getViewModel(),O=v.getEditArea();O!==C.DocumentEditArea.BODY&&g!==C.DocumentEditArea.BODY&&g!==O&&v.setEditArea(g)}if(this._textSelectionRenderManager.eventTrigger(r),this._editorService.getEditor(e)){this._setEditorFocus(e);const{offsetX:S,offsetY:p}=r;setTimeout(()=>{this._setEditorFocus(e),this._textSelectionRenderManager.setCursorManually(S,p)},0)}r.button!==2&&a.stopPropagation()})),this.disposeWithMe(n.onDblclick$.subscribeEvent(r=>{this._isEditorReadOnly(e)||this._textSelectionRenderManager.handleDblClick(r)})),this.disposeWithMe(n.onTripleClick$.subscribeEvent(r=>{this._isEditorReadOnly(e)||this._textSelectionRenderManager.handleTripleClick(r)}))}_getTransformCoordForDocumentOffset(e,t){const n=d.neoGetDocObject(this._context),{document:o,scene:r}=n,{documentTransform:a}=o.getOffsetConfig(),c=r.getViewports()[0];if(c==null)return;const u=c.transformVector2SceneCoord(C.Vector2.FromArray([e,t]));return a.clone().invert().applyPoint(u)}_isEditorReadOnly(e){const t=this._editorService.getEditor(e);return t?t.isReadOnly():!1}_setEditorFocus(e){this._editorService.focusStyle(e)}_commandExecutedListener(){const e=[d.SetDocZoomRatioOperation.id];this.disposeWithMe(this._commandService.onCommandExecuted(t=>{var n;if(e.includes(t.id)){const o=t.params,{unitId:r}=o,a=(n=this._textSelectionManagerService.getCurrentSelection())==null?void 0:n.unitId;if(r!==a)return;this._textSelectionManagerService.refreshSelection()}}))}_skeletonListener(){this.disposeWithMe(this._docSkeletonManagerService.currentSkeleton$.subscribe(e=>{if(e==null)return;const{scene:t,mainComponent:n,unitId:o}=this._context;this._textSelectionRenderManager.changeRuntime(e,t,n),this._textSelectionManagerService.setCurrentSelectionNotRefresh({unitId:o,subUnitId:""}),s.isInternalEditorID(o)||this._textSelectionManagerService.replaceTextRanges([{startOffset:0,endOffset:0}],!1)}))}};De=hi([K(1,s.ICommandService),K(2,l.IEditorService),K(3,s.IUniverInstanceService),K(4,C.ITextSelectionRenderManager),K(5,s.Inject(d.DocSkeletonManagerService)),K(6,s.Inject(d.TextSelectionManagerService))],De);var pi=Object.defineProperty,gi=Object.getOwnPropertyDescriptor,_i=(i,e,t,n)=>{for(var o=n>1?void 0:n?gi(e,t):e,r=i.length-1,a;r>=0;r--)(a=i[r])&&(o=(n?a(e,t,o):a(o))||o);return n&&o&&pi(e,t,o),o},de=(i,e)=>(t,n)=>e(t,n,i);function ct(i,e){const t=lt(i.left,i.top,e),n=lt(i.right,i.bottom,e);return{left:t.x,top:t.y,right:n.x,bottom:n.y}}function lt(i,e,t){const{scaleX:n,scaleY:o}=t.getAncestorScale(),r=t.getViewport(d.VIEWPORT_KEY.VIEW_MAIN);if(!r)return{x:i,y:e};const{viewportScrollX:a,viewportScrollY:c}=r,u=(i-a)*n,h=(e-c)*o;return{x:u,y:h}}I.DocCanvasPopManagerService=class extends s.Disposable{constructor(e,t,n,o){super(),this._globalPopupManagerService=e,this._renderManagerService=t,this._univerInstanceService=n,this._commandService=o}_createObjectPositionObserver(e,t){const n=()=>{const{scene:u,engine:h}=t,{left:_,top:m,width:S,height:p}=e,f={left:_,right:_+S,top:m,bottom:m+p},g=h.getCanvasElement(),v=g.getBoundingClientRect(),O=C.pxToNum(g.style.width),T=ct(f,u),{top:E,left:R,width:D}=v,b=D/O;return{left:T.left*b+R,right:T.right*b+R,top:T.top*b+E,bottom:T.bottom*b+E}},o=n(),r=new M.BehaviorSubject(o),a=new s.DisposableCollection;a.add(this._commandService.onCommandExecuted(u=>{u.id===d.SetDocZoomRatioOperation.id&&r.next(n())}));const c=t.scene.getViewport(d.VIEWPORT_KEY.VIEW_MAIN);return c&&a.add(c.onScrollAfter$.subscribeEvent(()=>{r.next(n())})),{position:o,position$:r,disposable:a}}_createRangePositionObserver(e,t){var u;const n=()=>{const{scene:h,mainComponent:_,engine:m}=t,S=t.with(d.DocSkeletonManagerService).getSkeleton(),p=S.findNodePositionByCharIndex(e.startOffset),f=S.findNodePositionByCharIndex(e.endOffset),g=_;if(!f||!p)return;const v=g.getOffsetConfig(),{docsLeft:O,docsTop:T}=v,E=m.getCanvasElement(),R=E.getBoundingClientRect(),D=C.pxToNum(E.style.width),{top:b,left:N,width:L}=R,F=L/D,{scaleX:Q,scaleY:pt}=h.getAncestorScale(),$i=new C.NodePositionConvertToCursor(v,S),{borderBoxPointGroup:Hi}=$i.getRangePointData(p,f);return C.getLineBounding(Hi).map(Y=>ct(Y,h)).map(Y=>({left:(Y.left+O*Q)*F+N,right:(Y.right+O*Q)*F+N,top:(Y.top+T*pt)*F+b,bottom:(Y.bottom+T*pt)*F+b}))},o=(u=n())!=null?u:[],r=new M.BehaviorSubject(o),a=new s.DisposableCollection;a.add(this._commandService.onCommandExecuted(h=>{if(h.id===d.SetDocZoomRatioOperation.id){const _=n();_&&r.next(_)}}));const c=t.scene.getViewport(d.VIEWPORT_KEY.VIEW_MAIN);return c&&a.add(c.onScrollAfter$.subscribeEvent(()=>{const h=n();h&&r.next(h)})),{positions:o,positions$:r,disposable:a}}attachPopupToObject(e,t){const o=this._univerInstanceService.getCurrentUnitForType(s.UniverInstanceType.UNIVER_DOC).getUnitId(),r=this._renderManagerService.getRenderById(o);if(!r)return{dispose:()=>{}};const{position:a,position$:c,disposable:u}=this._createObjectPositionObserver(e,r),h=this._globalPopupManagerService.addPopup({...t,unitId:o,subUnitId:"default",anchorRect:a,anchorRect$:c});return{dispose:()=>{this._globalPopupManagerService.removePopup(h),c.complete(),u.dispose()}}}attachPopupToRange(e,t){const o=this._univerInstanceService.getCurrentUnitForType(s.UniverInstanceType.UNIVER_DOC).getUnitId(),{direction:r="top"}=t,a=this._renderManagerService.getRenderById(o);if(!a)return{dispose:()=>{}};const{positions:c,positions$:u,disposable:h}=this._createRangePositionObserver(e,a),_=u.pipe(M.map(S=>r==="top"?S[0]:S[S.length-1])),m=this._globalPopupManagerService.addPopup({...t,unitId:o,subUnitId:"default",anchorRect:r==="top"?c[0]:c[c.length-1],anchorRect$:_,excludeRects:c,excludeRects$:u,direction:r==="top"?"top":"bottom"});return{dispose:()=>{this._globalPopupManagerService.removePopup(m),u.complete(),h.dispose()}}}},I.DocCanvasPopManagerService=_i([de(0,s.Inject(l.ICanvasPopupService)),de(1,C.IRenderManagerService),de(2,s.IUniverInstanceService),de(3,s.ICommandService)],I.DocCanvasPopManagerService);var mi=Object.defineProperty,Si=Object.getOwnPropertyDescriptor,fi=(i,e,t,n)=>{for(var o=n>1?void 0:n?Si(e,t):e,r=i.length-1,a;r>=0;r--)(a=i[r])&&(o=(n?a(e,t,o):a(o))||o);return n&&o&&mi(e,t,o),o},dt=(i,e)=>(t,n)=>e(t,n,i);I.DocsRenderService=class extends s.RxDisposable{constructor(e,t){super(),this._instanceSrv=e,this._renderManagerService=t,this._init()}_init(){this._renderManagerService.createRender$.pipe(M.takeUntil(this.dispose$)).subscribe(e=>this._createRenderWithId(e)),this._instanceSrv.getTypeOfUnitAdded$(s.UniverInstanceType.UNIVER_DOC).pipe(M.takeUntil(this.dispose$)).subscribe(e=>this._createRenderer(e)),this._instanceSrv.getAllUnitsForType(s.UniverInstanceType.UNIVER_DOC).forEach(e=>this._createRenderer(e)),this._instanceSrv.getTypeOfUnitDisposed$(s.UniverInstanceType.UNIVER_DOC).pipe(M.takeUntil(this.dispose$)).subscribe(e=>this._disposeRenderer(e))}_createRenderer(e){const t=e.getUnitId();this._renderManagerService.has(t)||(this._createRenderWithId(t),this._renderManagerService.setCurrent(t))}_createRenderWithId(e){this._renderManagerService.createRender(e)}_disposeRenderer(e){const t=e.getUnitId();this._renderManagerService.removeRender(t)}},I.DocsRenderService=fi([s.OnLifecycle(s.LifecycleStages.Ready,I.DocsRenderService),dt(0,s.IUniverInstanceService),dt(1,C.IRenderManagerService)],I.DocsRenderService);var vi=Object.defineProperty,Ci=Object.getOwnPropertyDescriptor,Ii=(i,e,t,n)=>{for(var o=n>1?void 0:n?Ci(e,t):e,r=i.length-1,a;r>=0;r--)(a=i[r])&&(o=(n?a(e,t,o):a(o))||o);return n&&o&&vi(e,t,o),o},ye=(i,e)=>(t,n)=>e(t,n,i);const Oi=[s.DEFAULT_EMPTY_DOCUMENT_VALUE,s.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,s.DOCS_NORMAL_EDITOR_UNIT_ID_KEY,s.DOCS_ZEN_EDITOR_UNIT_ID_KEY];let Pe=class extends s.Disposable{constructor(i,e,t,n){super(),this._context=i,this._contextMenuService=e,this._textSelectionManagerService=t,this._commandService=n,Oi.includes(this._context.unitId)||(this._initPointerDown(),this._initEditChange())}_initPointerDown(){var t,n;const e=((n=(t=this._context)==null?void 0:t.mainComponent)==null?void 0:n.onPointerDown$).subscribeEvent(o=>{o.button===2&&this._contextMenuService.triggerContextMenu(o,l.MenuPosition.CONTEXT_MENU)});this.disposeWithMe(e)}_initEditChange(){this.disposeWithMe(this._commandService.onCommandExecuted(i=>{i.id===d.RichTextEditingMutation.id&&this._contextMenuService.visible&&this._contextMenuService.hideContextMenu()}))}};Pe=Ii([ye(1,l.IContextMenuService),ye(2,s.Inject(d.TextSelectionManagerService)),ye(3,s.ICommandService)],Pe);var Ti=Object.defineProperty,Mi=Object.getOwnPropertyDescriptor,Ei=(i,e,t,n)=>{for(var o=n>1?void 0:n?Mi(e,t):e,r=i.length-1,a;r>=0;r--)(a=i[r])&&(o=(n?a(e,t,o):a(o))||o);return n&&o&&Ti(e,t,o),o},ut=(i,e)=>(t,n)=>e(t,n,i);const Ri=[s.DEFAULT_EMPTY_DOCUMENT_VALUE,s.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,s.DOCS_NORMAL_EDITOR_UNIT_ID_KEY];let Ae=class extends s.Disposable{constructor(i,e,t){super(),this._context=i,this._docPageLayoutService=e,this._textSelectionManagerService=t,Ri.includes(this._context.unitId)||this._initResize()}_initResize(){this.disposeWithMe(s.fromEventSubject(this._context.engine.onTransformChange$).pipe(M.filter(i=>i.type===C.TRANSFORM_CHANGE_OBSERVABLE_TYPE.resize),M.throttleTime(16)).subscribe(()=>{this._docPageLayoutService.calculatePagePosition(),this._textSelectionManagerService.refreshSelection()}))}};Ae=Ei([ut(1,s.Inject(Re)),ut(2,s.Inject(d.TextSelectionManagerService))],Ae);var bi=Object.defineProperty,Di=Object.getOwnPropertyDescriptor,yi=(i,e,t,n)=>{for(var o=n>1?void 0:n?Di(e,t):e,r=i.length-1,a;r>=0;r--)(a=i[r])&&(o=(n?a(e,t,o):a(o))||o);return n&&o&&bi(e,t,o),o},ht=(i,e)=>(t,n)=>e(t,n,i);I.DocHoverManagerService=class extends s.Disposable{constructor(t,n){super();y(this,"_activeCustomRanges$",new M.BehaviorSubject([]));y(this,"activeCustomRanges$",this._activeCustomRanges$.asObservable());y(this,"_activeIndex$",new M.BehaviorSubject(null));y(this,"activeIndex$",this._activeIndex$.asObservable());y(this,"_scrolling",!1);this._univerInstanceService=t,this._renderManagerService=n,this.disposeWithMe(()=>{this._activeCustomRanges$.complete(),this._activeIndex$.complete()})}_getTransformCoordForDocumentOffset(t,n,o,r){const{documentTransform:a}=t.getOffsetConfig(),c=n.transformVector2SceneCoord(C.Vector2.FromArray([o,r]));if(c)return a.clone().invert().applyPoint(c)}_calcActiveCustomRanges(t,n){var g,v;const o=this._univerInstanceService.getCurrentUnitForType(s.UniverInstanceType.UNIVER_DOC);if(!o){this._activeCustomRanges$.next([]);return}const r=this._renderManagerService.getRenderById(o.getUnitId());if(!r)return null;const a=r.mainComponent,c=r.with(d.DocSkeletonManagerService).getSkeleton(),{pageLayoutType:u=C.PageLayoutType.VERTICAL,pageMarginLeft:h,pageMarginTop:_,docsLeft:m,docsTop:S}=a.getOffsetConfig(),p=this._getTransformCoordForDocumentOffset(a,r.scene.getViewport(d.VIEWPORT_KEY.VIEW_MAIN),t,n);if(!p)return;const f=c.findNodeByCoord(p,u,h,_);if(f&&f.node){const O=f.node.left+h,T=f.node.left+f.node.width+h;if(p.x<O||p.x>T){this._activeIndex$.next(null),this._activeCustomRanges$.next([]);return}const E=f.node.parent.st+f.node.parent.glyphGroup.indexOf(f.node);E!==this._activeIndex$.value&&this._activeIndex$.next(E);const R=(v=(g=o.getCustomRanges())==null?void 0:g.filter(b=>b.startIndex<=E&&b.endIndex>=E))!=null?v:[],D=this._activeCustomRanges$.value;if(D.length===R.length&&D.every((b,N)=>b.rangeId===R[N].rangeId))return;this._activeCustomRanges$.next(R)}}onMouseMove(t){if(this._scrolling)return;const{offsetX:n,offsetY:o}=t;this._calcActiveCustomRanges(n,o)}startScroll(){this._scrolling||(this._scrolling=!0)}endScroll(){this._scrolling=!1}},I.DocHoverManagerService=yi([ht(0,s.IUniverInstanceService),ht(1,C.IRenderManagerService)],I.DocHoverManagerService);var Pi=Object.defineProperty,Ai=Object.getOwnPropertyDescriptor,Ni=(i,e,t,n)=>{for(var o=n>1?void 0:n?Ai(e,t):e,r=i.length-1,a;r>=0;r--)(a=i[r])&&(o=(n?a(e,t,o):a(o))||o);return n&&o&&Pi(e,t,o),o},Ui=(i,e)=>(t,n)=>e(t,n,i);let Ne=class extends s.Disposable{constructor(i,e){super(),this._context=i,this._docHoverManagerService=e,this._initPointerDown(),this._initScroll()}_initPointerDown(){this.disposeWithMe(s.fromEventSubject(this._context.scene.onPointerMove$).pipe(M.throttleTime(16)).subscribe(i=>{this._docHoverManagerService.onMouseMove(i)}))}_initScroll(){const i=this._context.scene.getViewport(d.VIEWPORT_KEY.VIEW_MAIN);i&&(this.disposeWithMe(s.fromEventSubject(i.onScrollAfter$).pipe(M.debounceTime(60)).subscribe(()=>{this._docHoverManagerService.endScroll()})),this.disposeWithMe(i.onScrollBefore$.subscribeEvent(()=>{this._docHoverManagerService.startScroll()})))}};Ne=Ni([Ui(1,s.Inject(I.DocHoverManagerService))],Ne);var xi=Object.defineProperty,Fi=Object.getOwnPropertyDescriptor,Li=(i,e,t,n)=>{for(var o=n>1?void 0:n?Fi(e,t):e,r=i.length-1,a;r>=0;r--)(a=i[r])&&(o=(n?a(e,t,o):a(o))||o);return n&&o&&xi(e,t,o),o},Ue=(i,e)=>(t,n)=>e(t,n,i);I.UniverDocsUIPlugin=(he=class extends s.Plugin{constructor(e,t,n,o){super(),this._config=e,this._injector=t,this._renderManagerSrv=n,this._logService=o,this._config=s.Tools.deepMerge({},ke,this._config),this._initDependencies(t),this._initializeCommands()}onReady(){this._initRenderBasics()}onRendered(){this._initUI(),this._initRenderModules(),this._markDocAsFocused()}_initializeCommands(){[yt,Pt,Nt,At,Ut,xt,Ft,Lt,Bt,Zn,Jn,Xn].forEach(e=>{this._injector.get(l.IShortcutService).registerShortcut(e)})}_initDependencies(e){[[X,{useFactory:()=>this._injector.createInstance(X,this._config)}],[ce],[le],[I.DocsRenderService],[z,{useFactory:()=>this._injector.createInstance(z,this._config)}],[G,{useClass:_e}],[I.DocCanvasPopManagerService],[I.DocHoverManagerService]].forEach(n=>e.add(n))}_markDocAsFocused(){const e=this._injector.get(s.IUniverInstanceService),t=this._injector.get(l.IEditorService);try{const n=e.getCurrentUnitForType(s.UniverInstanceType.UNIVER_DOC);if(!n)return;const o=n.getUnitId();t.isEditor(o)||e.focusUnit(n.getUnitId())}catch(n){this._logService.warn(n)}}_initUI(){this._injector.get(z)}_initRenderBasics(){[[d.DocSkeletonManagerService],[d.DocInterceptorService],[Re],[I.DocRenderController],[be]].forEach(e=>{this._renderManagerSrv.registerRenderModule(s.UniverInstanceType.UNIVER_DOC,e)})}_initRenderModules(){[[I.DocBackScrollRenderController],[De],[ve],[Ae],[Ne],[Pe]].forEach(e=>{this._renderManagerSrv.registerRenderModule(s.UniverInstanceType.UNIVER_DOC,e)})}},y(he,"pluginName",Ke),y(he,"type",s.UniverInstanceType.UNIVER_DOC),he),I.UniverDocsUIPlugin=Li([Ue(1,s.Inject(s.Injector)),Ue(2,C.IRenderManagerService),Ue(3,s.ILogService)],I.UniverDocsUIPlugin);function Bi(i){return{left:i.positionH.posOffset,top:i.positionV.posOffset,width:i.size.width,height:i.size.height}}function wi(i,e=0,t=0){return{size:{width:i.width,height:i.height},positionH:{relativeFrom:s.ObjectRelativeFromH.MARGIN,posOffset:(i.left||0)-e},positionV:{relativeFrom:s.ObjectRelativeFromV.PAGE,posOffset:(i.top||0)-t},angle:i.angle||0}}I.DOC_UI_PLUGIN_NAME=Ke,I.DefaultDocContainerConfig=Ge,I.DefaultDocUiConfig=ke,I.DefaultToolbarConfig=We,I.DocCopyCommand=Oe,I.DocCutCommand=Te,I.DocPasteCommand=Me,I.IDocClipboardService=G,I.PastePluginLark=Le,I.PastePluginUniver=$e,I.PastePluginWord=we,I.docDrawingPositionToTransform=Bi,I.transformToDocDrawingPosition=wi,I.whenDocAndEditorFocused=A,Object.defineProperty(I,Symbol.toStringTag,{value:"Module"})});
|
|
10
|
+
*/var f=require$$0,k=Symbol.for("react.element"),l=Symbol.for("react.fragment"),m=Object.prototype.hasOwnProperty,n=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,p={key:!0,ref:!0,__self:!0,__source:!0};function q(c,a,g){var b,d={},e=null,h=null;g!==void 0&&(e=""+g),a.key!==void 0&&(e=""+a.key),a.ref!==void 0&&(h=a.ref);for(b in a)m.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps,a)d[b]===void 0&&(d[b]=a[b]);return{$$typeof:k,type:c,key:e,ref:h,props:d,_owner:n.current}}__name(q,"q"),reactJsxRuntime_production_min.Fragment=l,reactJsxRuntime_production_min.jsx=q,reactJsxRuntime_production_min.jsxs=q,jsxRuntime.exports=reactJsxRuntime_production_min;var jsxRuntimeExports=jsxRuntime.exports;const styles$2={docCountBar:"univer-doc-count-bar"},ZOOM_MAP=[50,80,100,130,150,170,200,400],DOC_ZOOM_RANGE=[10,400];function ZoomSlider(){const commandService=core.useDependency(core.ICommandService),univerInstanceService=core.useDependency(core.IUniverInstanceService),currentDoc$=require$$0.useMemo(()=>univerInstanceService.getCurrentTypeOfUnit$(core.UniverInstanceType.UNIVER_DOC),[]),documentDataModel=core.useObservable(currentDoc$),getCurrentZoom=require$$0.useCallback(()=>{var _a2,_b2;if(!documentDataModel)return 100;const currentZoom=((_b2=(_a2=documentDataModel.getSettings())==null?void 0:_a2.zoomRatio)!=null?_b2:1)*100;return Math.round(currentZoom)},[documentDataModel]),[zoom,setZoom]=require$$0.useState(()=>getCurrentZoom());require$$0.useEffect(()=>(setZoom(getCurrentZoom()),commandService.onCommandExecuted(commandInfo=>{if(commandInfo.id===docs.SetDocZoomRatioOperation.id){const currentZoom=getCurrentZoom();setZoom(currentZoom)}}).dispose),[commandService,getCurrentZoom]);function handleChange(value){if(setZoom(value),documentDataModel==null)return;const zoomRatio=value/100;commandService.executeCommand(docs.SetDocZoomRatioOperation.id,{unitId:documentDataModel.getUnitId(),zoomRatio})}return __name(handleChange,"handleChange"),jsxRuntimeExports.jsx(design.Slider,{min:DOC_ZOOM_RANGE[0],value:zoom,shortcuts:ZOOM_MAP,onChange:handleChange})}__name(ZoomSlider,"ZoomSlider");function CountBar(props){return jsxRuntimeExports.jsx("section",{className:styles$2.docCountBar,children:jsxRuntimeExports.jsx(ZoomSlider,{})})}__name(CountBar,"CountBar");const styles$1={docFooterContainer:"univer-doc-footer-container"},DocFooter=__name(()=>jsxRuntimeExports.jsxs("div",{className:styles$1.docFooterContainer,children:[jsxRuntimeExports.jsx("div",{}),jsxRuntimeExports.jsx(CountBar,{})]}),"DocFooter"),COLLAB_CURSOR_LABEL_HEIGHT=18,COLLAB_CURSOR_LABEL_MAX_WIDTH=200,COLLAB_CURSOR_LABEL_TEXT_PADDING_LR=6,COLLAB_CURSOR_LABEL_TEXT_PADDING_TB=4;function drawBubble(ctx,props){let{radius,width,height}=props;radius=radius!=null?radius:0,width=width!=null?width:30,height=height!=null?height:30;let bottomRight=0;bottomRight=Math.min(radius,width/2,height/2),ctx.beginPath(),ctx.moveTo(0,0),ctx.lineTo(width,0),ctx.lineTo(width,height-bottomRight),ctx.arc(width-bottomRight,height-bottomRight,bottomRight,0,Math.PI/2,!1),ctx.lineTo(0,height),ctx.lineTo(0,0),ctx.closePath(),props.fill&&(ctx.save(),ctx.fillStyle=props.fill,props.fillRule==="evenodd"?ctx.fill("evenodd"):ctx.fill(),ctx.restore())}__name(drawBubble,"drawBubble");const _TextBubbleShape=class _TextBubbleShape extends engineRender.Shape{constructor(key,props){super(key,props);__publicField(this,"color");__publicField(this,"text");this.color=props==null?void 0:props.color,this.text=props==null?void 0:props.text}static drawWith(ctx,props){const{text,color}=props;ctx.save(),ctx.font="13px Source Han Sans CN";const textWidth=ctx.measureText(text).width,realInfoWidth=Math.min(textWidth+2*COLLAB_CURSOR_LABEL_TEXT_PADDING_LR,COLLAB_CURSOR_LABEL_MAX_WIDTH);drawBubble(ctx,{height:COLLAB_CURSOR_LABEL_HEIGHT,width:realInfoWidth,radius:4,fill:color,evented:!1}),ctx.fillStyle="rgba(58, 96, 247, 1)";const offsetX=COLLAB_CURSOR_LABEL_TEXT_PADDING_LR,offsetY=COLLAB_CURSOR_LABEL_HEIGHT-COLLAB_CURSOR_LABEL_TEXT_PADDING_TB,maxTextWidth=COLLAB_CURSOR_LABEL_MAX_WIDTH-2*COLLAB_CURSOR_LABEL_TEXT_PADDING_LR;if(textWidth>maxTextWidth){let truncatedText="",currentWidth=0;for(const element of text){const charWidth=ctx.measureText(element).width;if(currentWidth+charWidth<=maxTextWidth-ctx.measureText("...").width)truncatedText+=element,currentWidth+=charWidth;else{truncatedText+="...";break}}ctx.fillText(truncatedText,offsetX,offsetY)}else ctx.fillText(text,offsetX,offsetY);ctx.restore()}_draw(ctx){_TextBubbleShape.drawWith(ctx,this)}};__name(_TextBubbleShape,"TextBubbleShape");let TextBubbleShape=_TextBubbleShape;const COMPONENT_DOC_HEADER_FOOTER_PANEL="COMPONENT_DOC_HEADER_FOOTER_PANEL",styles={panel:"univer-panel",optionsSection:"univer-options-section",optionsFormItem:"univer-options-form-item",optionsInput:"univer-options-input",optionsMarginSetting:"univer-options-margin-setting"},DocHeaderFooterOptions=__name(props=>{const localeService=core.useDependency(core.LocaleService),univerInstanceService=core.useDependency(core.IUniverInstanceService),renderManagerService=core.useDependency(engineRender.IRenderManagerService),commandService=core.useDependency(core.ICommandService),textSelectionRenderService=core.useDependency(engineRender.ITextSelectionRenderManager),textSelectionManagerService=core.useDependency(docs.TextSelectionManagerService),{unitId}=props,[options,setOptions]=require$$0.useState({}),handleCheckboxChange=__name((val,type)=>{var _a2;setOptions(prev=>({...prev,[type]:val?core.BooleanNumber.TRUE:core.BooleanNumber.FALSE}));const docDataModel=univerInstanceService.getUniverDocInstance(unitId),documentStyle=docDataModel==null?void 0:docDataModel.getSnapshot().documentStyle,docSkeletonManagerService=(_a2=renderManagerService.getRenderById(unitId))==null?void 0:_a2.with(docs.DocSkeletonManagerService),viewModel=docSkeletonManagerService==null?void 0:docSkeletonManagerService.getViewModel();if(documentStyle==null||viewModel==null)return;const editArea=viewModel.getEditArea();let needCreateHeaderFooter=!1;const segmentPage=textSelectionRenderService.getSegmentPage();let needChangeSegmentId=!1;if(type==="useFirstPageHeaderFooter"&&val===!0&&((editArea===engineRender.DocumentEditArea.HEADER&&!documentStyle.firstPageHeaderId||editArea===engineRender.DocumentEditArea.FOOTER&&!documentStyle.firstPageFooterId)&&(needCreateHeaderFooter=!0),needCreateHeaderFooter&&segmentPage===0&&(needChangeSegmentId=!0)),type==="evenAndOddHeaders"&&val===!0&&((editArea===engineRender.DocumentEditArea.HEADER&&!documentStyle.evenPageHeaderId||editArea===engineRender.DocumentEditArea.FOOTER&&!documentStyle.evenPageFooterId)&&(needCreateHeaderFooter=!0),needCreateHeaderFooter&&segmentPage%2===1&&(needChangeSegmentId=!0)),needCreateHeaderFooter){const segmentId=core.Tools.generateRandomId(6);needChangeSegmentId&&textSelectionRenderService.setSegment(segmentId),commandService.executeCommand(CoreHeaderFooterCommandId,{unitId,segmentId,headerFooterProps:{[type]:val?core.BooleanNumber.TRUE:core.BooleanNumber.FALSE}})}else commandService.executeCommand(CoreHeaderFooterCommandId,{unitId,headerFooterProps:{[type]:val?core.BooleanNumber.TRUE:core.BooleanNumber.FALSE}})},"handleCheckboxChange"),handleMarginChange=__name(async(val,type)=>{setOptions(prev=>({...prev,[type]:val})),await commandService.executeCommand(CoreHeaderFooterCommandId,{unitId,headerFooterProps:{[type]:val}}),textSelectionRenderService.removeAllTextRanges(),textSelectionRenderService.blur()},"handleMarginChange"),closeHeaderFooter=__name(()=>{var _a2;const renderObject=renderManagerService.getRenderById(unitId);if(renderObject==null)return;const{scene}=renderObject,transformer=scene.getTransformerByCreate(),docSkeletonManagerService=renderObject.with(docs.DocSkeletonManagerService),skeleton=docSkeletonManagerService==null?void 0:docSkeletonManagerService.getSkeleton(),viewModel=docSkeletonManagerService==null?void 0:docSkeletonManagerService.getViewModel(),render=renderManagerService.getRenderById(unitId);render==null||viewModel==null||skeleton==null||(textSelectionManagerService.replaceTextRanges([]),transformer.clearSelectedObjects(),textSelectionRenderService.setSegment(""),textSelectionRenderService.setSegmentPage(-1),viewModel.setEditArea(engineRender.DocumentEditArea.BODY),skeleton.calculate(),(_a2=render.mainComponent)==null||_a2.makeDirty(!0))},"closeHeaderFooter");return require$$0.useEffect(()=>{const docDataModel=univerInstanceService.getUniverDocInstance(unitId),documentStyle=docDataModel==null?void 0:docDataModel.getSnapshot().documentStyle;if(documentStyle){const{marginHeader,marginFooter,useFirstPageHeaderFooter,evenAndOddHeaders}=documentStyle;setOptions({marginHeader,marginFooter,useFirstPageHeaderFooter,evenAndOddHeaders})}},[unitId]),jsxRuntimeExports.jsxs("div",{className:styles.options,children:[jsxRuntimeExports.jsxs("div",{className:styles.optionsSection,children:[jsxRuntimeExports.jsx("div",{className:styles.optionsFormItem,children:jsxRuntimeExports.jsx(design.Checkbox,{checked:options.useFirstPageHeaderFooter===core.BooleanNumber.TRUE,onChange:__name(val=>{handleCheckboxChange(val,"useFirstPageHeaderFooter")},"onChange"),children:localeService.t("headerFooter.firstPageCheckBox")})}),jsxRuntimeExports.jsx("div",{className:styles.optionsFormItem,children:jsxRuntimeExports.jsx(design.Checkbox,{checked:options.evenAndOddHeaders===core.BooleanNumber.TRUE,onChange:__name(val=>{handleCheckboxChange(val,"evenAndOddHeaders")},"onChange"),children:localeService.t("headerFooter.oddEvenCheckBox")})})]}),jsxRuntimeExports.jsxs("div",{className:clsx(styles.optionsSection,styles.optionsMarginSetting),children:[jsxRuntimeExports.jsxs("div",{className:styles.optionsMarginItem,children:[jsxRuntimeExports.jsx("span",{children:localeService.t("headerFooter.headerTopMargin")}),jsxRuntimeExports.jsx(design.InputNumber,{min:0,max:200,precision:1,value:options.marginHeader,onChange:__name(val=>{handleMarginChange(val,"marginHeader")},"onChange"),className:styles.optionsInput})]}),jsxRuntimeExports.jsxs("div",{className:styles.optionsMarginItem,children:[jsxRuntimeExports.jsx("span",{children:localeService.t("headerFooter.footerBottomMargin")}),jsxRuntimeExports.jsx(design.InputNumber,{min:0,max:200,precision:1,value:options.marginFooter,onChange:__name(val=>{handleMarginChange(val,"marginFooter")},"onChange"),className:styles.optionsInput})]})]}),jsxRuntimeExports.jsx("div",{className:styles.optionsSection,children:jsxRuntimeExports.jsx(design.Button,{onClick:closeHeaderFooter,children:localeService.t("headerFooter.closeHeaderFooter")})})]})},"DocHeaderFooterOptions"),DocHeaderFooterPanel=__name(()=>{var _a2;const localeService=core.useDependency(core.LocaleService),renderManagerService=core.useDependency(engineRender.IRenderManagerService),unitId=core.useDependency(core.IUniverInstanceService).getCurrentUniverDocInstance().getUnitId(),viewModel=((_a2=renderManagerService.getRenderById(unitId))==null?void 0:_a2.with(docs.DocSkeletonManagerService)).getViewModel(),[isEditHeaderFooter,setIsEditHeaderFooter]=require$$0.useState(!0);return require$$0.useEffect(()=>{const editArea=viewModel.getEditArea();setIsEditHeaderFooter(editArea!==engineRender.DocumentEditArea.BODY);const subscription=viewModel.editAreaChange$.subscribe(editArea2=>{editArea2!=null&&setIsEditHeaderFooter(editArea2!==engineRender.DocumentEditArea.BODY)});return()=>{subscription.unsubscribe()}},[]),jsxRuntimeExports.jsx("div",{className:styles.panel,children:isEditHeaderFooter?jsxRuntimeExports.jsx(DocHeaderFooterOptions,{unitId}):jsxRuntimeExports.jsx("div",{className:styles.panelDisableText,children:localeService.t("headerFooter.disableText")})})},"DocHeaderFooterPanel"),SidebarDocHeaderFooterPanelOperation={id:"sidebar.operation.doc-header-footer-panel",type:core.CommandType.COMMAND,handler:__name(async(accessor,params)=>{const sidebarService=accessor.get(ui.ISidebarService),localeService=accessor.get(core.LocaleService);switch(params.value){case"open":sidebarService.open({header:{title:localeService.t("headerFooter.panel")},children:{label:COMPONENT_DOC_HEADER_FOOTER_PANEL},onClose:__name(()=>{},"onClose"),width:400});break;case"close":default:sidebarService.close();break}return!0},"handler")};var __defProp$d=Object.defineProperty,__getOwnPropDesc$d=Object.getOwnPropertyDescriptor,__decorateClass$d=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$d(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$d(target,key,result),result},"__decorateClass$d"),__decorateParam$d=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$d");const HEADER_FOOTER_STROKE_COLOR="rgba(58, 96, 247, 1)",HEADER_FOOTER_FILL_COLOR="rgba(58, 96, 247, 0.08)";var HeaderFooterType=(HeaderFooterType2=>(HeaderFooterType2[HeaderFooterType2.FIRST_PAGE_HEADER=0]="FIRST_PAGE_HEADER",HeaderFooterType2[HeaderFooterType2.FIRST_PAGE_FOOTER=1]="FIRST_PAGE_FOOTER",HeaderFooterType2[HeaderFooterType2.DEFAULT_HEADER=2]="DEFAULT_HEADER",HeaderFooterType2[HeaderFooterType2.DEFAULT_FOOTER=3]="DEFAULT_FOOTER",HeaderFooterType2[HeaderFooterType2.EVEN_PAGE_HEADER=4]="EVEN_PAGE_HEADER",HeaderFooterType2[HeaderFooterType2.EVEN_PAGE_FOOTER=5]="EVEN_PAGE_FOOTER",HeaderFooterType2))(HeaderFooterType||{});function checkCreateHeaderFooterType(viewModel,editArea,segmentPage){const{documentStyle}=viewModel.getDataModel().getSnapshot(),{defaultHeaderId,defaultFooterId,evenPageHeaderId,evenPageFooterId,firstPageHeaderId,firstPageFooterId,evenAndOddHeaders,useFirstPageHeaderFooter}=documentStyle;switch(editArea){case engineRender.DocumentEditArea.BODY:return{createType:null,headerFooterId:null};case engineRender.DocumentEditArea.HEADER:return useFirstPageHeaderFooter===core.BooleanNumber.TRUE&&!firstPageHeaderId?{createType:0,headerFooterId:null}:evenAndOddHeaders===core.BooleanNumber.TRUE&&segmentPage%2===0&&!evenPageHeaderId?{createType:4,headerFooterId:null}:defaultHeaderId?{createType:null,headerFooterId:defaultHeaderId}:{createType:2,headerFooterId:null};case engineRender.DocumentEditArea.FOOTER:return useFirstPageHeaderFooter===core.BooleanNumber.TRUE&&!firstPageFooterId?{createType:1,headerFooterId:null}:evenAndOddHeaders===core.BooleanNumber.TRUE&&segmentPage%2===0&&!evenPageFooterId?{createType:5,headerFooterId:null}:defaultFooterId?{createType:null,headerFooterId:defaultFooterId}:{createType:3,headerFooterId:null};default:throw new Error(`Invalid editArea: ${editArea}`)}}__name(checkCreateHeaderFooterType,"checkCreateHeaderFooterType");let DocHeaderFooterController=(_e=class extends core.Disposable{constructor(_context,_commandService,_editorService,_instanceSrv,_renderManagerService,_docSkeletonManagerService,_textSelectionRenderManager,_localeService,_componentManager){super();__publicField(this,"_loadedMap",new WeakSet);this._context=_context,this._commandService=_commandService,this._editorService=_editorService,this._instanceSrv=_instanceSrv,this._renderManagerService=_renderManagerService,this._docSkeletonManagerService=_docSkeletonManagerService,this._textSelectionRenderManager=_textSelectionRenderManager,this._localeService=_localeService,this._componentManager=_componentManager,this._initialize()}_initialize(){this._context.unit.getSnapshot().documentStyle.documentFlavor===core.DocumentFlavor.TRADITIONAL&&(this._init(),this._drawHeaderFooterLabel(),this._registerCommands(),this._initCustomComponents())}_registerCommands(){[CoreHeaderFooterCommand,OpenHeaderFooterPanelCommand,SidebarDocHeaderFooterPanelOperation].forEach(command=>this.disposeWithMe(this._commandService.registerCommand(command)))}_initCustomComponents(){const componentManager=this._componentManager;this.disposeWithMe(componentManager.register(COMPONENT_DOC_HEADER_FOOTER_PANEL,DocHeaderFooterPanel))}_init(){const{unitId}=this._context,docObject=docs.neoGetDocObject(this._context);docObject==null||docObject.document==null||this._loadedMap.has(docObject.document)||(this._initialMain(unitId),this._loadedMap.add(docObject.document))}_initialMain(unitId){const docObject=docs.neoGetDocObject(this._context),{document}=docObject;this.disposeWithMe(document.onDblclick$.subscribeEvent(async evt=>{if(this._isEditorReadOnly(unitId))return;const{offsetX,offsetY}=evt,{pageLayoutType=engineRender.PageLayoutType.VERTICAL,pageMarginLeft,pageMarginTop}=document.getOffsetConfig(),coord=this._getTransformCoordForDocumentOffset(offsetX,offsetY);if(coord==null)return;const viewModel=this._docSkeletonManagerService.getViewModel(),skeleton=this._docSkeletonManagerService.getSkeleton(),preEditArea=viewModel.getEditArea(),{editArea,pageNumber}=skeleton.findEditAreaByCoord(coord,pageLayoutType,pageMarginLeft,pageMarginTop);if(preEditArea===editArea)return;viewModel.setEditArea(editArea);const{createType,headerFooterId}=checkCreateHeaderFooterType(viewModel,editArea,pageNumber);if(editArea===engineRender.DocumentEditArea.BODY)this._textSelectionRenderManager.setSegment(""),this._textSelectionRenderManager.setSegmentPage(-1),this._textSelectionRenderManager.setCursorManually(offsetX,offsetY);else if(createType!=null){const segmentId=core.Tools.generateRandomId(6);this._textSelectionRenderManager.setSegment(segmentId),this._textSelectionRenderManager.setSegmentPage(pageNumber),await this._commandService.executeCommand(CoreHeaderFooterCommand.id,{unitId,createType,segmentId})}else headerFooterId!=null&&(this._textSelectionRenderManager.setSegment(headerFooterId),this._textSelectionRenderManager.setSegmentPage(pageNumber),this._textSelectionRenderManager.setCursorManually(offsetX,offsetY))}))}_getTransformCoordForDocumentOffset(evtOffsetX,evtOffsetY){const docObject=docs.neoGetDocObject(this._context),{document,scene}=docObject,{documentTransform}=document.getOffsetConfig(),activeViewport=scene.getViewports()[0];if(activeViewport==null)return;const originCoord=activeViewport.transformVector2SceneCoord(engineRender.Vector2.FromArray([evtOffsetX,evtOffsetY]));return documentTransform.clone().invert().applyPoint(originCoord)}_drawHeaderFooterLabel(){const localeService=this._localeService;this._renderManagerService.currentRender$.subscribe(unitId=>{if(unitId==null)return;const currentRender=this._renderManagerService.getRenderById(unitId);if(this._editorService.isEditor(unitId)||this._instanceSrv.getUniverDocInstance(unitId)==null||currentRender==null)return;const{mainComponent}=currentRender,docsComponent=mainComponent;this.disposeWithMe(core.toDisposable(docsComponent.pageRender$.subscribe(config=>{if(this._editorService.isEditor(unitId))return;const isEditBody=this._docSkeletonManagerService.getViewModel().getEditArea()===engineRender.DocumentEditArea.BODY,{page,pageLeft,pageTop,ctx}=config,{pageWidth,pageHeight,marginTop,marginBottom}=page;if(ctx.save(),ctx.translate(pageLeft-.5,pageTop-.5),isEditBody?(engineRender.Rect.drawWith(ctx,{left:0,top:0,width:pageWidth,height:marginTop,fill:"rgba(255, 255, 255, 0.5)"}),ctx.save(),ctx.translate(0,pageHeight-marginBottom),engineRender.Rect.drawWith(ctx,{left:0,top:0,width:pageWidth,height:marginBottom,fill:"rgba(255, 255, 255, 0.5)"}),ctx.restore()):(ctx.save(),ctx.translate(0,marginTop),engineRender.Rect.drawWith(ctx,{left:0,top:marginTop,width:pageWidth,height:pageHeight-marginTop-marginBottom,fill:"rgba(255, 255, 255, 0.5)"}),ctx.restore()),!isEditBody){const headerPathConfigIPathProps={dataArray:[{command:"M",points:[0,marginTop]},{command:"L",points:[pageWidth,marginTop]}],strokeWidth:1,stroke:HEADER_FOOTER_STROKE_COLOR},footerPathConfigIPathProps={dataArray:[{command:"M",points:[0,pageHeight-marginBottom]},{command:"L",points:[pageWidth,pageHeight-marginBottom]}],strokeWidth:1,stroke:HEADER_FOOTER_STROKE_COLOR};engineRender.Path.drawWith(ctx,headerPathConfigIPathProps),engineRender.Path.drawWith(ctx,footerPathConfigIPathProps),ctx.translate(0,marginTop+1),TextBubbleShape.drawWith(ctx,{text:localeService.t("headerFooter.header"),color:HEADER_FOOTER_FILL_COLOR}),ctx.translate(0,pageHeight-marginTop-marginBottom),TextBubbleShape.drawWith(ctx,{text:localeService.t("headerFooter.footer"),color:HEADER_FOOTER_FILL_COLOR})}ctx.restore()})))})}_isEditorReadOnly(unitId){const editor=this._editorService.getEditor(unitId);return editor?editor.isReadOnly():!1}_getDocDataModel(){return this._context.unit}},__name(_e,"DocHeaderFooterController"),_e);DocHeaderFooterController=__decorateClass$d([__decorateParam$d(1,core.ICommandService),__decorateParam$d(2,ui.IEditorService),__decorateParam$d(3,core.IUniverInstanceService),__decorateParam$d(4,engineRender.IRenderManagerService),__decorateParam$d(5,core.Inject(docs.DocSkeletonManagerService)),__decorateParam$d(6,engineRender.ITextSelectionRenderManager),__decorateParam$d(7,core.Inject(core.LocaleService)),__decorateParam$d(8,core.Inject(ui.ComponentManager))],DocHeaderFooterController);function getEmptyHeaderFooterBody(){return{dataStream:`\r
|
|
11
|
+
`,textRuns:[{st:0,ed:0,ts:{fs:9}}],customBlocks:[],paragraphs:[{startIndex:0,paragraphStyle:{spaceAbove:{v:0},lineSpacing:1.5,spaceBelow:{v:0}}}],sectionBreaks:[{startIndex:1}]}}__name(getEmptyHeaderFooterBody,"getEmptyHeaderFooterBody");function createHeaderFooterAction(segmentId,createType,documentStyle,actions){const jsonX=core.JSONX.getInstance(),ID_LEN=6,firstSegmentId=segmentId!=null?segmentId:core.Tools.generateRandomId(ID_LEN),isHeader=createType===HeaderFooterType.DEFAULT_HEADER||createType===HeaderFooterType.FIRST_PAGE_HEADER||createType===HeaderFooterType.EVEN_PAGE_HEADER,insertAction=jsonX.insertOp([isHeader?"headers":"footers",firstSegmentId],{[isHeader?"headerId":"footerId"]:firstSegmentId,body:getEmptyHeaderFooterBody()});actions.push(insertAction);const secondSegmentId=core.Tools.generateRandomId(ID_LEN),insertPairAction=jsonX.insertOp([isHeader?"footers":"headers",secondSegmentId],{[isHeader?"footers":"headers"]:secondSegmentId,body:getEmptyHeaderFooterBody()});actions.push(insertPairAction);let key="defaultHeaderId",pairKey="defaultFooterId";switch(createType){case HeaderFooterType.DEFAULT_HEADER:key="defaultHeaderId",pairKey="defaultFooterId";break;case HeaderFooterType.DEFAULT_FOOTER:key="defaultFooterId",pairKey="defaultHeaderId";break;case HeaderFooterType.FIRST_PAGE_HEADER:key="firstPageHeaderId",pairKey="firstPageFooterId";break;case HeaderFooterType.FIRST_PAGE_FOOTER:key="firstPageFooterId",pairKey="firstPageHeaderId";break;case HeaderFooterType.EVEN_PAGE_HEADER:key="evenPageHeaderId",pairKey="evenPageFooterId";break;case HeaderFooterType.EVEN_PAGE_FOOTER:key="evenPageFooterId",pairKey="evenPageHeaderId";break;default:throw new Error(`Unknown header footer type: ${createType}`)}for(const[k2,id]of[[key,firstSegmentId],[pairKey,secondSegmentId]])if(documentStyle[k2]!=null){const replaceAction=jsonX.replaceOp(["documentStyle",k2],documentStyle[k2],id);actions.push(replaceAction)}else{const insertAction2=jsonX.insertOp(["documentStyle",k2],id);actions.push(insertAction2)}return actions}__name(createHeaderFooterAction,"createHeaderFooterAction");const CoreHeaderFooterCommandId="doc.command.core-header-footer",CoreHeaderFooterCommand={id:CoreHeaderFooterCommandId,type:core.CommandType.COMMAND,handler:__name(async(accessor,params)=>{var _a2;const commandService=accessor.get(core.ICommandService),univerInstanceService=accessor.get(core.IUniverInstanceService),renderManagerService=accessor.get(engineRender.IRenderManagerService),{unitId,segmentId,createType,headerFooterProps}=params,docSkeletonManagerService=(_a2=renderManagerService.getRenderById(unitId))==null?void 0:_a2.with(docs.DocSkeletonManagerService),docDataModel=univerInstanceService.getUniverDocInstance(unitId),docViewModel=docSkeletonManagerService==null?void 0:docSkeletonManagerService.getViewModel();if(docDataModel==null||docViewModel==null)return!1;const editArea=docViewModel.getEditArea(),{documentStyle}=docDataModel.getSnapshot(),isUpdateMargin=(headerFooterProps==null?void 0:headerFooterProps.marginFooter)!=null||(headerFooterProps==null?void 0:headerFooterProps.marginHeader)!=null,textRanges=[{startOffset:0,endOffset:0,collapsed:!0}],doMutation={id:docs.RichTextEditingMutation.id,params:{unitId,actions:[],textRanges,debounce:!0}};isUpdateMargin&&(doMutation.params.noNeedSetTextRange=!0);const jsonX=core.JSONX.getInstance(),rawActions=[];return createType!=null&&createHeaderFooterAction(segmentId,createType,documentStyle,rawActions),headerFooterProps!=null&&Object.keys(headerFooterProps).forEach(key=>{const value=headerFooterProps[key],oldValue=documentStyle[key];if(value===oldValue)return;let action;if(oldValue===void 0?action=jsonX.insertOp(["documentStyle",key],value):action=jsonX.replaceOp(["documentStyle",key],oldValue,value),rawActions.push(action),key==="useFirstPageHeaderFooter"&&value===core.BooleanNumber.TRUE&&!documentStyle.firstPageHeaderId){const headerFooterType=editArea===engineRender.DocumentEditArea.HEADER?HeaderFooterType.FIRST_PAGE_HEADER:HeaderFooterType.FIRST_PAGE_FOOTER;createHeaderFooterAction(segmentId,headerFooterType,documentStyle,rawActions)}else if(key==="evenAndOddHeaders"&&value===core.BooleanNumber.TRUE&&!documentStyle.evenPageHeaderId){const headerFooterType=editArea===engineRender.DocumentEditArea.HEADER?HeaderFooterType.EVEN_PAGE_HEADER:HeaderFooterType.EVEN_PAGE_FOOTER;createHeaderFooterAction(segmentId,headerFooterType,documentStyle,rawActions)}}),rawActions.length===0?!1:(doMutation.params.actions=rawActions.reduce((acc,cur)=>core.JSONX.compose(acc,cur),null),!!commandService.syncExecuteCommand(doMutation.id,doMutation.params))},"handler")},OpenHeaderFooterPanelCommand={id:"doc.command.open-header-footer-panel",type:core.CommandType.COMMAND,handler:__name(async(accessor,_params)=>accessor.get(core.ICommandService).executeCommand(SidebarDocHeaderFooterPanelOperation.id,{value:"open"}),"handler")};function BoldMenuItemFactory(accessor){const commandService=accessor.get(core.ICommandService);return{id:docs.SetInlineFormatBoldCommand.id,group:ui.MenuGroup.TOOLBAR_FORMAT,type:ui.MenuItemType.BUTTON,icon:"BoldSingle",title:"Set bold",tooltip:"toolbar.bold",positions:[ui.MenuPosition.TOOLBAR_START],activated$:new rxjs.Observable(subscriber=>{const disposable=commandService.onCommandExecuted(c=>{var _a2;const id=c.id;if(id===docs.SetTextSelectionsOperation.id||id===docs.SetInlineFormatCommand.id){const textRun=getFontStyleAtCursor(accessor);if(textRun==null)return;const bl=(_a2=textRun.ts)==null?void 0:_a2.bl;subscriber.next(bl===core.BooleanNumber.TRUE)}});return subscriber.next(!1),disposable.dispose}),hidden$:ui.getMenuHiddenObservable(accessor,core.UniverInstanceType.UNIVER_DOC)}}__name(BoldMenuItemFactory,"BoldMenuItemFactory");function ItalicMenuItemFactory(accessor){const commandService=accessor.get(core.ICommandService);return{id:docs.SetInlineFormatItalicCommand.id,group:ui.MenuGroup.TOOLBAR_FORMAT,type:ui.MenuItemType.BUTTON,icon:"ItalicSingle",title:"Set italic",tooltip:"toolbar.italic",positions:[ui.MenuPosition.TOOLBAR_START],activated$:new rxjs.Observable(subscriber=>{const disposable=commandService.onCommandExecuted(c=>{var _a2;const id=c.id;if(id===docs.SetTextSelectionsOperation.id||id===docs.SetInlineFormatCommand.id){const textRun=getFontStyleAtCursor(accessor);if(textRun==null)return;const it=(_a2=textRun.ts)==null?void 0:_a2.it;subscriber.next(it===core.BooleanNumber.TRUE)}});return subscriber.next(!1),disposable.dispose}),hidden$:ui.getMenuHiddenObservable(accessor,core.UniverInstanceType.UNIVER_DOC)}}__name(ItalicMenuItemFactory,"ItalicMenuItemFactory");function UnderlineMenuItemFactory(accessor){const commandService=accessor.get(core.ICommandService);return{id:docs.SetInlineFormatUnderlineCommand.id,group:ui.MenuGroup.TOOLBAR_FORMAT,type:ui.MenuItemType.BUTTON,icon:"UnderlineSingle",title:"Set underline",tooltip:"toolbar.underline",positions:[ui.MenuPosition.TOOLBAR_START],activated$:new rxjs.Observable(subscriber=>{const disposable=commandService.onCommandExecuted(c=>{var _a2;const id=c.id;if(id===docs.SetTextSelectionsOperation.id||id===docs.SetInlineFormatCommand.id){const textRun=getFontStyleAtCursor(accessor);if(textRun==null)return;const ul=(_a2=textRun.ts)==null?void 0:_a2.ul;subscriber.next((ul==null?void 0:ul.s)===core.BooleanNumber.TRUE)}});return subscriber.next(!1),disposable.dispose}),hidden$:ui.getMenuHiddenObservable(accessor,core.UniverInstanceType.UNIVER_DOC)}}__name(UnderlineMenuItemFactory,"UnderlineMenuItemFactory");function StrikeThroughMenuItemFactory(accessor){const commandService=accessor.get(core.ICommandService);return{id:docs.SetInlineFormatStrikethroughCommand.id,group:ui.MenuGroup.TOOLBAR_FORMAT,type:ui.MenuItemType.BUTTON,icon:"StrikethroughSingle",title:"Set strike through",tooltip:"toolbar.strikethrough",positions:[ui.MenuPosition.TOOLBAR_START],activated$:new rxjs.Observable(subscriber=>{const disposable=commandService.onCommandExecuted(c=>{var _a2;const id=c.id;if(id===docs.SetTextSelectionsOperation.id||id===docs.SetInlineFormatCommand.id){const textRun=getFontStyleAtCursor(accessor);if(textRun==null)return;const st=(_a2=textRun.ts)==null?void 0:_a2.st;subscriber.next((st==null?void 0:st.s)===core.BooleanNumber.TRUE)}});return subscriber.next(!1),disposable.dispose}),hidden$:ui.getMenuHiddenObservable(accessor,core.UniverInstanceType.UNIVER_DOC)}}__name(StrikeThroughMenuItemFactory,"StrikeThroughMenuItemFactory");function SubscriptMenuItemFactory(accessor){const commandService=accessor.get(core.ICommandService);return{id:docs.SetInlineFormatSubscriptCommand.id,group:ui.MenuGroup.TOOLBAR_FORMAT,type:ui.MenuItemType.BUTTON,icon:"SubscriptSingle",tooltip:"toolbar.subscript",positions:[ui.MenuPosition.TOOLBAR_START],activated$:new rxjs.Observable(subscriber=>{const disposable=commandService.onCommandExecuted(c=>{var _a2;const id=c.id;if(id===docs.SetTextSelectionsOperation.id||id===docs.SetInlineFormatCommand.id){const textRun=getFontStyleAtCursor(accessor);if(textRun==null)return;const va=(_a2=textRun.ts)==null?void 0:_a2.va;subscriber.next(va===core.BaselineOffset.SUBSCRIPT)}});return subscriber.next(!1),disposable.dispose}),hidden$:ui.getMenuHiddenObservable(accessor,core.UniverInstanceType.UNIVER_DOC)}}__name(SubscriptMenuItemFactory,"SubscriptMenuItemFactory");function SuperscriptMenuItemFactory(accessor){const commandService=accessor.get(core.ICommandService);return{id:docs.SetInlineFormatSuperscriptCommand.id,group:ui.MenuGroup.TOOLBAR_FORMAT,type:ui.MenuItemType.BUTTON,icon:"SuperscriptSingle",tooltip:"toolbar.superscript",positions:[ui.MenuPosition.TOOLBAR_START],activated$:new rxjs.Observable(subscriber=>{const disposable=commandService.onCommandExecuted(c=>{var _a2;const id=c.id;if(id===docs.SetTextSelectionsOperation.id||id===docs.SetInlineFormatCommand.id){const textRun=getFontStyleAtCursor(accessor);if(textRun==null)return;const va=(_a2=textRun.ts)==null?void 0:_a2.va;subscriber.next(va===core.BaselineOffset.SUPERSCRIPT)}});return subscriber.next(!1),disposable.dispose}),hidden$:ui.getMenuHiddenObservable(accessor,core.UniverInstanceType.UNIVER_DOC)}}__name(SuperscriptMenuItemFactory,"SuperscriptMenuItemFactory");function FontFamilySelectorMenuItemFactory(accessor){const commandService=accessor.get(core.ICommandService);return{id:docs.SetInlineFormatFontFamilyCommand.id,tooltip:"toolbar.font",group:ui.MenuGroup.TOOLBAR_FORMAT,type:ui.MenuItemType.SELECTOR,label:FONT_FAMILY_COMPONENT,positions:[ui.MenuPosition.TOOLBAR_START],selections:ui.FONT_FAMILY_LIST.map(item=>({label:{name:FONT_FAMILY_ITEM_COMPONENT,hoverable:!0},value:item.value})),value$:new rxjs.Observable(subscriber=>{const defaultValue=ui.FONT_FAMILY_LIST[0].value,disposable=commandService.onCommandExecuted(c=>{var _a2;const id=c.id;if(id===docs.SetTextSelectionsOperation.id||id===docs.SetInlineFormatFontFamilyCommand.id){const textRun=getFontStyleAtCursor(accessor);if(textRun==null)return;const ff=(_a2=textRun.ts)==null?void 0:_a2.ff;subscriber.next(ff!=null?ff:defaultValue)}});return subscriber.next(defaultValue),disposable.dispose}),hidden$:ui.getMenuHiddenObservable(accessor,core.UniverInstanceType.UNIVER_DOC)}}__name(FontFamilySelectorMenuItemFactory,"FontFamilySelectorMenuItemFactory");function FontSizeSelectorMenuItemFactory(accessor){const commandService=accessor.get(core.ICommandService);return{id:docs.SetInlineFormatFontSizeCommand.id,group:ui.MenuGroup.TOOLBAR_FORMAT,type:ui.MenuItemType.SELECTOR,tooltip:"toolbar.fontSize",label:{name:FONT_SIZE_COMPONENT,props:{min:1,max:400}},positions:[ui.MenuPosition.TOOLBAR_START],selections:ui.FONT_SIZE_LIST,value$:new rxjs.Observable(subscriber=>{const disposable=commandService.onCommandExecuted(c=>{var _a2;const id=c.id;if(id===docs.SetTextSelectionsOperation.id||id===docs.SetInlineFormatFontSizeCommand.id){const textRun=getFontStyleAtCursor(accessor);if(textRun==null)return;const fs=(_a2=textRun.ts)==null?void 0:_a2.fs;subscriber.next(fs!=null?fs:14)}});return subscriber.next(14),disposable.dispose}),hidden$:ui.getMenuHiddenObservable(accessor,core.UniverInstanceType.UNIVER_DOC)}}__name(FontSizeSelectorMenuItemFactory,"FontSizeSelectorMenuItemFactory");function TextColorSelectorMenuItemFactory(accessor){const commandService=accessor.get(core.ICommandService),themeService=accessor.get(core.ThemeService);return{id:docs.SetInlineFormatTextColorCommand.id,icon:"FontColor",tooltip:"toolbar.textColor.main",group:ui.MenuGroup.TOOLBAR_FORMAT,type:ui.MenuItemType.BUTTON_SELECTOR,positions:[ui.MenuPosition.TOOLBAR_START],selections:[{label:{name:COLOR_PICKER_COMPONENT,hoverable:!1}}],value$:new rxjs.Observable(subscriber=>{const defaultColor=themeService.getCurrentTheme().textColor,disposable=commandService.onCommandExecuted(c=>{if(c.id===docs.SetInlineFormatTextColorCommand.id){const color=c.params.value;subscriber.next(color!=null?color:defaultColor)}});return subscriber.next(defaultColor),disposable.dispose}),hidden$:ui.getMenuHiddenObservable(accessor,core.UniverInstanceType.UNIVER_DOC)}}__name(TextColorSelectorMenuItemFactory,"TextColorSelectorMenuItemFactory");function HeaderFooterMenuItemFactory(accessor){return{id:OpenHeaderFooterPanelCommand.id,group:ui.MenuGroup.TOOLBAR_OTHERS,type:ui.MenuItemType.BUTTON,icon:"FreezeRowSingle",tooltip:"toolbar.headerFooter",positions:[ui.MenuPosition.TOOLBAR_START],hidden$:rxjs.combineLatest(ui.getMenuHiddenObservable(accessor,core.UniverInstanceType.UNIVER_DOC),ui.getHeaderFooterMenuHiddenObservable(accessor),(one,two)=>one||two)}}__name(HeaderFooterMenuItemFactory,"HeaderFooterMenuItemFactory");function AlignLeftMenuItemFactory(accessor){const commandService=accessor.get(core.ICommandService);return{id:docs.AlignLeftCommand.id,group:ui.MenuGroup.TOOLBAR_LAYOUT,type:ui.MenuItemType.BUTTON,icon:"LeftJustifyingSingle",tooltip:"toolbar.alignLeft",positions:[ui.MenuPosition.TOOLBAR_START],activated$:new rxjs.Observable(subscriber=>{const disposable=commandService.onCommandExecuted(c=>{var _a2;const id=c.id;if(id===docs.SetTextSelectionsOperation.id||id===docs.AlignOperationCommand.id){const paragraph=getParagraphStyleAtCursor(accessor);if(paragraph==null)return;const alignType=(_a2=paragraph.paragraphStyle)==null?void 0:_a2.horizontalAlign;subscriber.next(alignType===core.HorizontalAlign.LEFT)}});return subscriber.next(!1),disposable.dispose}),hidden$:ui.getMenuHiddenObservable(accessor,core.UniverInstanceType.UNIVER_DOC)}}__name(AlignLeftMenuItemFactory,"AlignLeftMenuItemFactory");function AlignCenterMenuItemFactory(accessor){const commandService=accessor.get(core.ICommandService);return{id:docs.AlignCenterCommand.id,group:ui.MenuGroup.TOOLBAR_LAYOUT,type:ui.MenuItemType.BUTTON,icon:"HorizontallySingle",tooltip:"toolbar.alignCenter",positions:[ui.MenuPosition.TOOLBAR_START],activated$:new rxjs.Observable(subscriber=>{const disposable=commandService.onCommandExecuted(c=>{var _a2;const id=c.id;if(id===docs.SetTextSelectionsOperation.id||id===docs.AlignOperationCommand.id){const paragraph=getParagraphStyleAtCursor(accessor);if(paragraph==null)return;const alignType=(_a2=paragraph.paragraphStyle)==null?void 0:_a2.horizontalAlign;subscriber.next(alignType===core.HorizontalAlign.CENTER)}});return subscriber.next(!1),disposable.dispose}),hidden$:ui.getMenuHiddenObservable(accessor,core.UniverInstanceType.UNIVER_DOC)}}__name(AlignCenterMenuItemFactory,"AlignCenterMenuItemFactory");function AlignRightMenuItemFactory(accessor){const commandService=accessor.get(core.ICommandService);return{id:docs.AlignRightCommand.id,group:ui.MenuGroup.TOOLBAR_LAYOUT,type:ui.MenuItemType.BUTTON,icon:"RightJustifyingSingle",tooltip:"toolbar.alignRight",positions:[ui.MenuPosition.TOOLBAR_START],activated$:new rxjs.Observable(subscriber=>{const disposable=commandService.onCommandExecuted(c=>{var _a2;const id=c.id;if(id===docs.SetTextSelectionsOperation.id||id===docs.AlignOperationCommand.id){const paragraph=getParagraphStyleAtCursor(accessor);if(paragraph==null)return;const alignType=(_a2=paragraph.paragraphStyle)==null?void 0:_a2.horizontalAlign;subscriber.next(alignType===core.HorizontalAlign.RIGHT)}});return subscriber.next(!1),disposable.dispose}),hidden$:ui.getMenuHiddenObservable(accessor,core.UniverInstanceType.UNIVER_DOC)}}__name(AlignRightMenuItemFactory,"AlignRightMenuItemFactory");function AlignJustifyMenuItemFactory(accessor){const commandService=accessor.get(core.ICommandService);return{id:docs.AlignJustifyCommand.id,group:ui.MenuGroup.TOOLBAR_LAYOUT,type:ui.MenuItemType.BUTTON,icon:"AlignTextBothSingle",tooltip:"toolbar.alignJustify",positions:[ui.MenuPosition.TOOLBAR_START],activated$:new rxjs.Observable(subscriber=>{const disposable=commandService.onCommandExecuted(c=>{var _a2;const id=c.id;if(id===docs.SetTextSelectionsOperation.id||id===docs.AlignOperationCommand.id){const paragraph=getParagraphStyleAtCursor(accessor);if(paragraph==null)return;const alignType=(_a2=paragraph.paragraphStyle)==null?void 0:_a2.horizontalAlign;subscriber.next(alignType===core.HorizontalAlign.JUSTIFIED)}});return subscriber.next(!1),disposable.dispose}),hidden$:ui.getMenuHiddenObservable(accessor,core.UniverInstanceType.UNIVER_DOC)}}__name(AlignJustifyMenuItemFactory,"AlignJustifyMenuItemFactory");function OrderListMenuItemFactory(accessor){return{id:docs.OrderListCommand.id,group:ui.MenuGroup.TOOLBAR_LAYOUT,type:ui.MenuItemType.BUTTON,icon:"OrderSingle",tooltip:"toolbar.order",positions:[ui.MenuPosition.TOOLBAR_START],hidden$:ui.getMenuHiddenObservable(accessor,core.UniverInstanceType.UNIVER_DOC)}}__name(OrderListMenuItemFactory,"OrderListMenuItemFactory");function BulletListMenuItemFactory(accessor){return{id:docs.BulletListCommand.id,group:ui.MenuGroup.TOOLBAR_LAYOUT,type:ui.MenuItemType.BUTTON,icon:"UnorderSingle",tooltip:"toolbar.unorder",positions:[ui.MenuPosition.TOOLBAR_START],hidden$:ui.getMenuHiddenObservable(accessor,core.UniverInstanceType.UNIVER_DOC)}}__name(BulletListMenuItemFactory,"BulletListMenuItemFactory");function ResetBackgroundColorMenuItemFactory(accessor){return{id:docs.ResetInlineFormatTextBackgroundColorCommand.id,type:ui.MenuItemType.BUTTON,title:"toolbar.resetColor",icon:"NoColor",positions:docs.SetInlineFormatTextBackgroundColorCommand.id}}__name(ResetBackgroundColorMenuItemFactory,"ResetBackgroundColorMenuItemFactory");function BackgroundColorSelectorMenuItemFactory(accessor){const commandService=accessor.get(core.ICommandService),themeService=accessor.get(core.ThemeService);return{id:docs.SetInlineFormatTextBackgroundColorCommand.id,tooltip:"toolbar.fillColor.main",group:ui.MenuGroup.TOOLBAR_FORMAT,type:ui.MenuItemType.BUTTON_SELECTOR,positions:[ui.MenuPosition.TOOLBAR_START],icon:"PaintBucket",selections:[{label:{name:COLOR_PICKER_COMPONENT,hoverable:!1}}],value$:new rxjs.Observable(subscriber=>{const defaultColor=themeService.getCurrentTheme().primaryColor,disposable=commandService.onCommandExecuted(c=>{if(c.id===docs.SetInlineFormatTextBackgroundColorCommand.id){const color=c.params.value;subscriber.next(color!=null?color:defaultColor)}});return subscriber.next(defaultColor),disposable.dispose}),hidden$:ui.getMenuHiddenObservable(accessor,core.UniverInstanceType.UNIVER_DOC)}}__name(BackgroundColorSelectorMenuItemFactory,"BackgroundColorSelectorMenuItemFactory");function getFontStyleAtCursor(accessor){var _a2;const univerInstanceService=accessor.get(core.IUniverInstanceService),textSelectionService=accessor.get(docs.TextSelectionManagerService),docDataModel=univerInstanceService.getCurrentUniverDocInstance(),activeTextRange=textSelectionService.getActiveRange();if(docDataModel==null||activeTextRange==null)return;const{startOffset,segmentId}=activeTextRange,textRuns=(_a2=docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody())==null?void 0:_a2.textRuns;if(textRuns==null)return;let textRun;for(let i=0;i<textRuns.length;i++){const curTextRun=textRuns[i],nextTextRun=textRuns[i+1];if(nextTextRun&&nextTextRun.st===nextTextRun.ed&&startOffset===nextTextRun.st){textRun=nextTextRun;break}if(curTextRun.st<=startOffset&&startOffset<=curTextRun.ed){textRun=curTextRun;break}}return textRun}__name(getFontStyleAtCursor,"getFontStyleAtCursor");function getParagraphStyleAtCursor(accessor){var _a2;const univerInstanceService=accessor.get(core.IUniverInstanceService),textSelectionService=accessor.get(docs.TextSelectionManagerService),docDataModel=univerInstanceService.getCurrentUniverDocInstance(),activeTextRange=textSelectionService.getActiveRange();if(docDataModel==null||activeTextRange==null)return;const{startOffset,segmentId}=activeTextRange,paragraphs=(_a2=docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody())==null?void 0:_a2.paragraphs;if(paragraphs==null)return;let prevIndex=-1;for(const paragraph of paragraphs){const{startIndex}=paragraph;if(startOffset>prevIndex&&startOffset<=startIndex)return paragraph;prevIndex=startIndex}return null}__name(getParagraphStyleAtCursor,"getParagraphStyleAtCursor");function whenDocOrEditor(contextService){return contextService.getContextValue(core.FOCUSING_DOC)||contextService.getContextValue(core.EDITOR_ACTIVATED)}__name(whenDocOrEditor,"whenDocOrEditor");const DOC_CLIPBOARD_PRIORITY=999,DocCopyCommand={id:ui.CopyCommand.id,name:"doc.command.copy",type:core.CommandType.COMMAND,multi:!0,priority:DOC_CLIPBOARD_PRIORITY,preconditions:whenDocOrEditor,handler:__name(async accessor=>accessor.get(IDocClipboardService).copy(),"handler")},DocCutCommand={id:ui.CutCommand.id,name:"doc.command.cut",type:core.CommandType.COMMAND,multi:!0,priority:DOC_CLIPBOARD_PRIORITY,preconditions:whenDocOrEditor,handler:__name(async accessor=>accessor.get(IDocClipboardService).cut(),"handler")},DocPasteCommand={id:ui.PasteCommand.id,name:"doc.command.paste",type:core.CommandType.COMMAND,multi:!0,priority:DOC_CLIPBOARD_PRIORITY,preconditions:whenDocOrEditor,handler:__name(async accessor=>{const docClipboardService=accessor.get(IDocClipboardService),clipboardItems=await accessor.get(ui.IClipboardInterfaceService).read();return clipboardItems.length===0?!1:docClipboardService.paste(clipboardItems)},"handler")},getDisableOnCollapsedObservable=__name(accessor=>{const textSelectionManagerService=accessor.get(docs.TextSelectionManagerService);return new rxjs.Observable(subscriber=>{const observable=textSelectionManagerService.textSelection$.subscribe(selections=>{const range=textSelectionManagerService.getActiveRange();range&&!range.collapsed?subscriber.next(!1):subscriber.next(!0)});return()=>observable.unsubscribe()})},"getDisableOnCollapsedObservable"),CopyMenuFactory=__name(accessor=>({id:DocCopyCommand.id,group:ui.MenuGroup.CONTEXT_MENU_FORMAT,type:ui.MenuItemType.BUTTON,icon:"Copy",title:"rightClick.copy",positions:[ui.MenuPosition.CONTEXT_MENU],disabled$:getDisableOnCollapsedObservable(accessor),hidden$:ui.getMenuHiddenObservable(accessor,core.UniverInstanceType.UNIVER_DOC)}),"CopyMenuFactory"),CutMenuFactory=__name(accessor=>({id:DocCutCommand.id,group:ui.MenuGroup.CONTEXT_MENU_FORMAT,type:ui.MenuItemType.BUTTON,icon:"Copy",title:"rightClick.cut",positions:[ui.MenuPosition.CONTEXT_MENU],disabled$:getDisableOnCollapsedObservable(accessor),hidden$:ui.getMenuHiddenObservable(accessor,core.UniverInstanceType.UNIVER_DOC)}),"CutMenuFactory"),PasteMenuFactory=__name(accessor=>({id:DocPasteCommand.id,group:ui.MenuGroup.CONTEXT_MENU_FORMAT,type:ui.MenuItemType.BUTTON,icon:"PasteSpecial",title:"rightClick.paste",positions:[ui.MenuPosition.CONTEXT_MENU],hidden$:ui.getMenuHiddenObservable(accessor,core.UniverInstanceType.UNIVER_DOC)}),"PasteMenuFactory"),DeleteMenuFactory=__name(accessor=>({id:docs.DeleteLeftCommand.id,group:ui.MenuGroup.CONTEXT_MENU_FORMAT,type:ui.MenuItemType.BUTTON,icon:"PasteSpecial",title:"rightClick.delete",positions:[ui.MenuPosition.CONTEXT_MENU],disabled$:getDisableOnCollapsedObservable(accessor),hidden$:ui.getMenuHiddenObservable(accessor,core.UniverInstanceType.UNIVER_DOC)}),"DeleteMenuFactory"),BoldShortCut={id:docs.SetInlineFormatBoldCommand.id,binding:ui.KeyCode.B|ui.MetaKeys.CTRL_COMMAND,preconditions:whenDocAndEditorFocused},ItalicShortCut={id:docs.SetInlineFormatItalicCommand.id,binding:ui.KeyCode.I|ui.MetaKeys.CTRL_COMMAND,preconditions:whenDocAndEditorFocused},UnderlineShortCut={id:docs.SetInlineFormatUnderlineCommand.id,binding:ui.KeyCode.U|ui.MetaKeys.CTRL_COMMAND,preconditions:whenDocAndEditorFocused},StrikeThroughShortCut={id:docs.SetInlineFormatStrikethroughCommand.id,binding:ui.KeyCode.X|ui.MetaKeys.SHIFT|ui.MetaKeys.CTRL_COMMAND,preconditions:whenDocAndEditorFocused},SubscriptShortCut={id:docs.SetInlineFormatSubscriptCommand.id,binding:ui.KeyCode.COMMA|ui.MetaKeys.CTRL_COMMAND,preconditions:whenDocAndEditorFocused},SuperscriptShortCut={id:docs.SetInlineFormatSuperscriptCommand.id,binding:ui.KeyCode.PERIOD|ui.MetaKeys.CTRL_COMMAND,preconditions:whenDocAndEditorFocused},AlignLeftShortCut={id:docs.AlignLeftCommand.id,binding:ui.KeyCode.L|ui.MetaKeys.CTRL_COMMAND|ui.MetaKeys.SHIFT,preconditions:whenDocAndEditorFocused},AlignRightShortCut={id:docs.AlignRightCommand.id,binding:ui.KeyCode.R|ui.MetaKeys.CTRL_COMMAND|ui.MetaKeys.SHIFT,preconditions:whenDocAndEditorFocused},AlignCenterShortCut={id:docs.AlignCenterCommand.id,binding:ui.KeyCode.E|ui.MetaKeys.CTRL_COMMAND|ui.MetaKeys.SHIFT,preconditions:whenDocAndEditorFocused},AlignJustifyShortCut={id:docs.AlignJustifyCommand.id,binding:ui.KeyCode.J|ui.MetaKeys.CTRL_COMMAND|ui.MetaKeys.SHIFT,preconditions:whenDocAndEditorFocused},OrderListShortCut={id:docs.OrderListCommand.id,binding:ui.KeyCode.Digit7|ui.MetaKeys.CTRL_COMMAND|ui.MetaKeys.SHIFT,preconditions:whenDocAndEditorFocused},BulletListShortCut={id:docs.BulletListCommand.id,binding:ui.KeyCode.Digit8|ui.MetaKeys.CTRL_COMMAND|ui.MetaKeys.SHIFT,preconditions:whenDocAndEditorFocused};var __defProp$c=Object.defineProperty,__getOwnPropDesc$c=Object.getOwnPropertyDescriptor,__decorateClass$c=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$c(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$c(target,key,result),result},"__decorateClass$c"),__decorateParam$c=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$c");let DocUIController=(_f=class extends core.Disposable{constructor(_config,_injector,_componentManager,_layoutService,_menuService,_uiPartsService,_univerInstanceService,_shortcutService){super(),this._config=_config,this._injector=_injector,this._componentManager=_componentManager,this._layoutService=_layoutService,this._menuService=_menuService,this._uiPartsService=_uiPartsService,this._univerInstanceService=_univerInstanceService,this._shortcutService=_shortcutService,this._init()}_initCustomComponents(){const componentManager=this._componentManager;this.disposeWithMe(componentManager.register(COLOR_PICKER_COMPONENT,design.ColorPicker)),this.disposeWithMe(componentManager.register(FONT_FAMILY_COMPONENT,ui.FontFamily)),this.disposeWithMe(componentManager.register(FONT_FAMILY_ITEM_COMPONENT,ui.FontFamilyItem)),this.disposeWithMe(componentManager.register(FONT_SIZE_COMPONENT,ui.FontSize))}_initUiParts(){var _a2,_b2;const workbook=this._univerInstanceService.getCurrentUnitForType(core.UniverInstanceType.UNIVER_SHEET);(_b2=(_a2=this._config.layout)==null?void 0:_a2.docContainerConfig)!=null&&_b2.footer&&!workbook&&this.disposeWithMe(this._uiPartsService.registerComponent(ui.BuiltInUIPart.FOOTER,()=>core.connectInjector(DocFooter,this._injector)))}_initMenus(){const{menu={}}=this._config;[BoldMenuItemFactory,ItalicMenuItemFactory,UnderlineMenuItemFactory,StrikeThroughMenuItemFactory,SubscriptMenuItemFactory,SuperscriptMenuItemFactory,FontSizeSelectorMenuItemFactory,FontFamilySelectorMenuItemFactory,TextColorSelectorMenuItemFactory,HeaderFooterMenuItemFactory,AlignLeftMenuItemFactory,AlignCenterMenuItemFactory,AlignRightMenuItemFactory,AlignJustifyMenuItemFactory,OrderListMenuItemFactory,BulletListMenuItemFactory,ResetBackgroundColorMenuItemFactory,BackgroundColorSelectorMenuItemFactory].forEach(factory=>{this.disposeWithMe(this._menuService.addMenuItem(this._injector.invoke(factory),menu))}),[CopyMenuFactory,CutMenuFactory,PasteMenuFactory,DeleteMenuFactory].forEach(factory=>{try{this.disposeWithMe(this._menuService.addMenuItem(this._injector.invoke(factory),menu))}catch{}})}_initShortCut(){[BoldShortCut,ItalicShortCut,UnderlineShortCut,StrikeThroughShortCut,SubscriptShortCut,SuperscriptShortCut,AlignCenterShortCut,AlignJustifyShortCut,AlignRightShortCut,AlignLeftShortCut,OrderListShortCut,BulletListShortCut].forEach(shortcut=>{this.disposeWithMe(this._shortcutService.registerShortcut(shortcut))})}_init(){this._initCustomComponents(),this._initMenus(),this._initFocusHandler(),this._initUiParts(),this._initShortCut()}_initFocusHandler(){this.disposeWithMe(this._layoutService.registerFocusHandler(core.UniverInstanceType.UNIVER_DOC,()=>{this._injector.get(engineRender.ITextSelectionRenderManager).focus()}))}},__name(_f,"DocUIController"),_f);DocUIController=__decorateClass$c([core.OnLifecycle(core.LifecycleStages.Rendered,DocUIController),__decorateParam$c(1,core.Inject(core.Injector)),__decorateParam$c(2,core.Inject(ui.ComponentManager)),__decorateParam$c(3,ui.ILayoutService),__decorateParam$c(4,ui.IMenuService),__decorateParam$c(5,ui.IUIPartsService),__decorateParam$c(6,core.IUniverInstanceService),__decorateParam$c(7,ui.IShortcutService)],DocUIController);const BreakLineShortcut={id:docs.BreakLineCommand.id,preconditions:whenDocAndEditorFocusedWithBreakLine,binding:ui.KeyCode.ENTER},DeleteLeftShortcut={id:docs.DeleteLeftCommand.id,preconditions:whenDocAndEditorFocused,binding:ui.KeyCode.BACKSPACE},DeleteRightShortcut={id:docs.DeleteRightCommand.id,preconditions:whenDocAndEditorFocused,binding:ui.KeyCode.DELETE};var __defProp$b=Object.defineProperty,__getOwnPropDesc$b=Object.getOwnPropertyDescriptor,__decorateClass$b=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$b(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$b(target,key,result),result},"__decorateClass$b"),__decorateParam$b=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$b");let DocClipboardController=(_g=class extends core.RxDisposable{constructor(_commandService,_clipboardInterfaceService,_docClipboardService,_textSelectionRenderManager,_contextService){super(),this._commandService=_commandService,this._clipboardInterfaceService=_clipboardInterfaceService,this._docClipboardService=_docClipboardService,this._textSelectionRenderManager=_textSelectionRenderManager,this._contextService=_contextService,this._init()}_init(){[DocCopyCommand,DocCutCommand,DocPasteCommand].forEach(command=>this.disposeWithMe(this._commandService.registerMultipleCommand(command))),[docs.InnerPasteCommand,docs.CutContentCommand].forEach(command=>this.disposeWithMe(this._commandService.registerCommand(command))),this._initLegacyPasteCommand()}_initLegacyPasteCommand(){var _a2;(_a2=this._textSelectionRenderManager)==null||_a2.onPaste$.pipe(rxjs.takeUntil(this.dispose$)).subscribe(config=>{var _a3,_b2;if(!whenDocOrEditor(this._contextService))return;config.event.preventDefault();const clipboardEvent=config.event,htmlContent=(_a3=clipboardEvent.clipboardData)==null?void 0:_a3.getData("text/html"),textContent=(_b2=clipboardEvent.clipboardData)==null?void 0:_b2.getData("text/plain");this._docClipboardService.legacyPaste(htmlContent,textContent)})}},__name(_g,"DocClipboardController"),_g);DocClipboardController=__decorateClass$b([core.OnLifecycle(core.LifecycleStages.Rendered,DocClipboardController),__decorateParam$b(0,core.ICommandService),__decorateParam$b(1,ui.IClipboardInterfaceService),__decorateParam$b(2,IDocClipboardService),__decorateParam$b(3,engineRender.ITextSelectionRenderManager),__decorateParam$b(4,core.IContextService)],DocClipboardController);var __defProp$a=Object.defineProperty,__getOwnPropDesc$a=Object.getOwnPropertyDescriptor,__decorateClass$a=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$a(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$a(target,key,result),result},"__decorateClass$a"),__decorateParam$a=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$a");let DocEditorBridgeController=(_h=class extends core.Disposable{constructor(_univerInstanceService,_editorService,_commandService,_textSelectionRenderManager,_renderManagerService){super();__publicField(this,"_initialEditors",new Set);this._univerInstanceService=_univerInstanceService,this._editorService=_editorService,this._commandService=_commandService,this._textSelectionRenderManager=_textSelectionRenderManager,this._renderManagerService=_renderManagerService,this._initialize()}_initialize(){this.disposeWithMe(this._editorService.resize$.subscribe(unitId=>{this._resize(unitId)})),this._editorService.getAllEditor().forEach(editor=>{const unitId=editor.editorUnitId;this._initialEditors.has(unitId)||(this._initialEditors.add(unitId),this._resize(unitId))}),this._commandExecutedListener(),this._initialSetValue(),this._initialBlur(),this._initialFocus(),this._initialValueChange()}_resize(unitId){var _a2,_b2,_c2;if(unitId==null)return;const editor=this._editorService.getEditor(unitId);if((editor==null?void 0:editor.cancelDefaultResizeListener)===!0)return;const editorDataModel=this._univerInstanceService.getUniverDocInstance(unitId);if(!editorDataModel)return;const skeleton=(_a2=this._renderManagerService.getRenderById(editorDataModel.getUnitId()))==null?void 0:_a2.with(docs.DocSkeletonManagerService).getSkeleton();if(editor==null||editor.render==null||skeleton==null||editorDataModel==null)return;skeleton.calculate();const{marginTop=0,marginBottom=0,marginLeft=0,marginRight=0}=editorDataModel.getSnapshot().documentStyle,{scene,mainComponent}=editor.render;let{actualHeight,actualWidth}=skeleton.getActualSize();actualHeight+=marginTop+marginBottom,actualWidth+=marginLeft+marginRight;const{width,height}=editor.getBoundingClientRect(),viewportMain=scene.getViewport(docs.VIEWPORT_KEY.VIEW_MAIN);let scrollBar=viewportMain==null?void 0:viewportMain.getScrollBar();const contentWidth=Math.max(actualWidth,width),contentHeight=Math.max(actualHeight,height);scene.transformByState({width:contentWidth,height:contentHeight}),mainComponent==null||mainComponent.resize(contentWidth,contentHeight),editor.isSingle()?actualWidth>width?scrollBar==null?viewportMain&&new engineRender.ScrollBar(viewportMain,{barSize:8,enableVertical:!1}):viewportMain==null||viewportMain.resetCanvasSizeAndUpdateScroll():(scrollBar=null,viewportMain==null||viewportMain.scrollToBarPos({x:0,y:0}),(_c2=viewportMain==null?void 0:viewportMain.getScrollBar())==null||_c2.dispose()):actualHeight>height?scrollBar==null?viewportMain&&new engineRender.ScrollBar(viewportMain,{enableHorizontal:!1,barSize:8}):viewportMain==null||viewportMain.resetCanvasSizeAndUpdateScroll():(scrollBar=null,viewportMain==null||viewportMain.scrollToBarPos({x:0,y:0}),(_b2=viewportMain==null?void 0:viewportMain.getScrollBar())==null||_b2.dispose())}_initialSetValue(){this.disposeWithMe(this._editorService.setValue$.subscribe(param=>{this._commandService.executeCommand(docs.CoverContentCommand.id,{unitId:param.editorUnitId,body:param.body,segmentId:null})}))}_initialBlur(){this.disposeWithMe(this._editorService.blur$.subscribe(()=>{this._textSelectionRenderManager.removeAllTextRanges(),this._textSelectionRenderManager.blur()})),this.disposeWithMe(this._textSelectionRenderManager.onBlur$.subscribe(()=>{var _a2;const unitId=(_a2=this._univerInstanceService.getCurrentUniverDocInstance())==null?void 0:_a2.getUnitId();if(unitId==null)return;const editor=this._editorService.getEditor(unitId),focusEditor=this._editorService.getFocusEditor();editor==null||editor.isSheetEditor()||focusEditor&&focusEditor.editorUnitId===unitId||this._editorService.blur()}))}_initialFocus(){this.disposeWithMe(this._editorService.focus$.subscribe(textRange=>{this._textSelectionRenderManager.removeAllTextRanges(),this._textSelectionRenderManager.addTextRanges([textRange])}));const focusExcepts=["univer-formula-search","univer-formula-help","formula-help-decorator","univer-formula-help-param"];this.disposeWithMe(rxjs.fromEvent(window,"mousedown").subscribe(event=>{const hasSearch=event.target.classList[0]||"";if(core.checkForSubstrings(hasSearch,focusExcepts)){this._editorService.changeSpreadsheetFocusState(!0),event.stopPropagation();return}this._editorService.changeSpreadsheetFocusState(!1)})),this._univerInstanceService.getAllUnitsForType(core.UniverInstanceType.UNIVER_SHEET).forEach(unit=>{const unitId=unit.getUnitId(),render=this._renderManagerService.getRenderById(unitId),canvasEle=render==null?void 0:render.engine.getCanvas().getCanvasEle();canvasEle!=null&&rxjs.fromEvent(canvasEle,"mousedown").subscribe(evt=>{this._editorService.changeSpreadsheetFocusState(!0),evt.stopPropagation()})})}_initialValueChange(){this.disposeWithMe(this._textSelectionRenderManager.onCompositionupdate$.subscribe(this._valueChange.bind(this))),this.disposeWithMe(this._textSelectionRenderManager.onInput$.subscribe(this._valueChange.bind(this))),this.disposeWithMe(this._textSelectionRenderManager.onKeydown$.subscribe(this._valueChange.bind(this))),this.disposeWithMe(this._textSelectionRenderManager.onPaste$.subscribe(this._valueChange.bind(this)))}_valueChange(){var _a2;const unitId=(_a2=this._univerInstanceService.getCurrentUniverDocInstance())==null?void 0:_a2.getUnitId();if(unitId==null)return;const editor=this._editorService.getEditor(unitId);editor==null||editor.isSheetEditor()||this._editorService.refreshValueChange(unitId)}_commandExecutedListener(){const updateCommandList=[docs.RichTextEditingMutation.id,ui.SetEditorResizeOperation.id];this.disposeWithMe(this._commandService.onCommandExecuted(command=>{if(updateCommandList.includes(command.id)){const params=command.params,{unitId}=params;if(this._editorService.isSheetEditor(unitId))return;this._resize(unitId),this._valueChange()}}))}},__name(_h,"DocEditorBridgeController"),_h);DocEditorBridgeController=__decorateClass$a([core.OnLifecycle(core.LifecycleStages.Rendered,DocEditorBridgeController),__decorateParam$a(0,core.IUniverInstanceService),__decorateParam$a(1,ui.IEditorService),__decorateParam$a(2,core.ICommandService),__decorateParam$a(3,engineRender.ITextSelectionRenderManager),__decorateParam$a(4,engineRender.IRenderManagerService)],DocEditorBridgeController);var __defProp$9=Object.defineProperty,__getOwnPropDesc$9=Object.getOwnPropertyDescriptor,__decorateClass$9=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$9(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$9(target,key,result),result},"__decorateClass$9"),__decorateParam$9=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$9");exports2.DocRenderController=(_i=class extends core.RxDisposable{constructor(_context,_commandService,_docSkeletonManagerService,_configService,_editorService,_renderManagerService){super(),this._context=_context,this._commandService=_commandService,this._docSkeletonManagerService=_docSkeletonManagerService,this._configService=_configService,this._editorService=_editorService,this._renderManagerService=_renderManagerService,this._addNewRender(),this._initRenderRefresh(),this._initCommandListener()}reRender(unitId){var _a2,_b2;const docSkeletonManagerService=(_a2=this._renderManagerService.getRenderById(unitId))==null?void 0:_a2.with(docs.DocSkeletonManagerService),skeleton=docSkeletonManagerService==null?void 0:docSkeletonManagerService.getSkeleton();if(!(!skeleton||skeleton.getViewModel().getDataModel().getSnapshot().disabled)){if(skeleton.calculate(),this._editorService.isEditor(unitId)){(_b2=this._context.mainComponent)==null||_b2.makeDirty();return}this._recalculateSizeBySkeleton(skeleton)}}_addNewRender(){const{scene,engine,unit}=this._context,viewMain=new engineRender.Viewport(docs.VIEWPORT_KEY.VIEW_MAIN,scene,{left:0,top:0,bottom:0,right:0,isRelativeX:!0,isRelativeY:!0,isWheelPreventDefaultX:!0});scene.attachControl(),scene.onMouseWheel$.subscribeEvent((evt,state)=>{const e=evt;if(e.ctrlKey){const deltaFactor=Math.abs(e.deltaX);let scrollNum=deltaFactor<40?.2:deltaFactor<80?.4:.2;scrollNum*=e.deltaY>0?-1:1,scene.scaleX<1&&(scrollNum/=2),scene.scaleX+scrollNum>4?scene.scale(4,4):scene.scaleX+scrollNum<.1?scene.scale(.1,.1):e.preventDefault()}else viewMain.onMouseWheel(e,state)}),this._configService.getConfig("hasScroll")!==!1&&new engineRender.ScrollBar(viewMain),scene.addLayer(new engineRender.Layer(scene,[],docs.DOCS_COMPONENT_MAIN_LAYER_INDEX),new engineRender.Layer(scene,[],docs.DOCS_COMPONENT_HEADER_LAYER_INDEX)),this._addComponent(),unit.getShouldRenderLoopImmediately()&&engine.runRenderLoop(()=>{scene.render()})}_addComponent(){const{scene,unit:documentModel,components}=this._context,config={pageMarginLeft:documentModel.documentStyle.marginLeft||0,pageMarginTop:documentModel.documentStyle.marginTop||0},documents=new engineRender.Documents(docs.DOCS_VIEW_KEY.MAIN,void 0,config);documents.zIndex=docs.DOCS_COMPONENT_DEFAULT_Z_INDEX;const docBackground=new engineRender.DocBackground(docs.DOCS_VIEW_KEY.BACKGROUND,void 0,config);docBackground.zIndex=docs.DOCS_COMPONENT_DEFAULT_Z_INDEX,this._context.mainComponent=documents,components.set(docs.DOCS_VIEW_KEY.MAIN,documents),components.set(docs.DOCS_VIEW_KEY.BACKGROUND,docBackground),scene.addObjects([documents],docs.DOCS_COMPONENT_MAIN_LAYER_INDEX),scene.addObjects([docBackground],docs.DOCS_COMPONENT_BACKGROUND_LAYER_INDEX),this._editorService.getEditor(documentModel.getUnitId())==null&&scene.enableLayerCache(docs.DOCS_COMPONENT_MAIN_LAYER_INDEX)}_initRenderRefresh(){this._docSkeletonManagerService.currentSkeletonBefore$.pipe(rxjs.takeUntil(this.dispose$)).subscribe(param=>{this._create(param)})}_create(skeleton){if(!skeleton)return;const{mainComponent,components}=this._context,docsComponent=mainComponent,docBackground=components.get(docs.DOCS_VIEW_KEY.BACKGROUND);docsComponent.changeSkeleton(skeleton),docBackground.changeSkeleton(skeleton),this._recalculateSizeBySkeleton(skeleton)}_initCommandListener(){const updateCommandList=[docs.RichTextEditingMutation.id];this.disposeWithMe(this._commandService.onCommandExecuted(command=>{if(updateCommandList.includes(command.id)){const params=command.params,{unitId}=params;this.reRender(unitId)}}))}_recalculateSizeBySkeleton(skeleton){var _a2;const{mainComponent,scene,unitId,components}=this._context,docsComponent=mainComponent,docBackground=components.get(docs.DOCS_VIEW_KEY.BACKGROUND),pages=(_a2=skeleton.getSkeletonData())==null?void 0:_a2.pages;if(pages==null)return;let width=0,height=0;for(let i=0,len=pages.length;i<len;i++){const page=pages[i],{pageWidth,pageHeight}=page;docsComponent.pageLayoutType===engineRender.PageLayoutType.VERTICAL?(height+=pageHeight,height+=docsComponent.pageMarginTop,i===len-1&&(height+=docsComponent.pageMarginTop),width=Math.max(width,pageWidth)):docsComponent.pageLayoutType===engineRender.PageLayoutType.HORIZONTAL&&(width+=pageWidth,i!==len-1&&(width+=docsComponent.pageMarginLeft),height=Math.max(height,pageHeight))}docsComponent.resize(width,height),docBackground.resize(width,height),this._editorService.isEditor(unitId)||scene.resize(width,height)}},__name(_i,"DocRenderController"),_i),exports2.DocRenderController=__decorateClass$9([__decorateParam$9(1,core.ICommandService),__decorateParam$9(2,core.Inject(docs.DocSkeletonManagerService)),__decorateParam$9(3,core.IConfigService),__decorateParam$9(4,ui.IEditorService),__decorateParam$9(5,engineRender.IRenderManagerService)],exports2.DocRenderController);const _DocPageLayoutService=class _DocPageLayoutService extends core.Disposable{constructor(_context){super(),this._context=_context}calculatePagePosition(){var _a2,_b2;const docObject=docs.neoGetDocObject(this._context),zoomRatio=(_b2=(_a2=this._context.unit.getSettings())==null?void 0:_a2.zoomRatio)!=null?_b2:1,{document:docsComponent,scene,docBackground}=docObject,parent=scene==null?void 0:scene.getParent(),{width:docsWidth,height:docsHeight,pageMarginLeft,pageMarginTop}=docsComponent;if(parent==null||docsWidth===Number.POSITIVE_INFINITY||docsHeight===Number.POSITIVE_INFINITY)return;const{width:engineWidth,height:engineHeight}=parent;let docsLeft=0,docsTop=0,sceneWidth=0,sceneHeight=0,scrollToX=Number.POSITIVE_INFINITY;engineWidth>(docsWidth+pageMarginLeft*2)*zoomRatio?(docsLeft=engineWidth/2-docsWidth*zoomRatio/2,docsLeft/=zoomRatio,sceneWidth=(engineWidth-pageMarginLeft*2)/zoomRatio,scrollToX=0):(docsLeft=pageMarginLeft,sceneWidth=docsWidth+pageMarginLeft*2,scrollToX=(sceneWidth-engineWidth/zoomRatio)/2),engineHeight>docsHeight?(docsTop=engineHeight/2-docsHeight/2,sceneHeight=(engineHeight-pageMarginTop*2)/zoomRatio):(docsTop=pageMarginTop,sceneHeight=docsHeight+pageMarginTop*2),scene.resize(sceneWidth,sceneHeight+200),docsComponent.translate(docsLeft,docsTop),docBackground.translate(docsLeft,docsTop);const viewport=scene.getViewport(docs.VIEWPORT_KEY.VIEW_MAIN);return scrollToX!==Number.POSITIVE_INFINITY&&viewport!=null&&viewport.scrollToViewportPos({viewportScrollX:scrollToX}),this}};__name(_DocPageLayoutService,"DocPageLayoutService");let DocPageLayoutService=_DocPageLayoutService;var __defProp$8=Object.defineProperty,__getOwnPropDesc$8=Object.getOwnPropertyDescriptor,__decorateClass$8=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$8(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$8(target,key,result),result},"__decorateClass$8"),__decorateParam$8=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$8");let DocZoomRenderController=(_j=class extends core.Disposable{constructor(_context,_docSkeletonManagerService,_univerInstanceService,_commandService,_textSelectionManagerService,_editorService,_docPageLayoutService){super(),this._context=_context,this._docSkeletonManagerService=_docSkeletonManagerService,this._univerInstanceService=_univerInstanceService,this._commandService=_commandService,this._textSelectionManagerService=_textSelectionManagerService,this._editorService=_editorService,this._docPageLayoutService=_docPageLayoutService,this._init()}_init(){this._initSkeletonListener(),this._initCommandExecutedListener(),this._initRenderRefresher(),setTimeout(()=>this.updateViewZoom(1,!0),20)}_initRenderRefresher(){this._docSkeletonManagerService.currentSkeleton$.subscribe(param=>{if(param==null)return;const{unitId,scene}=this._context;this._editorService.isEditor(unitId)||this.disposeWithMe(scene.onMouseWheel$.subscribeEvent(e=>{if(!e.ctrlKey)return;const documentModel=this._univerInstanceService.getCurrentUniverDocInstance();if(!documentModel)return;const deltaFactor=Math.abs(e.deltaX);let ratioDelta=deltaFactor<40?.2:deltaFactor<80?.4:.2;ratioDelta*=e.deltaY>0?-1:1,scene.scaleX<1&&(ratioDelta/=2);const currentRatio=documentModel.zoomRatio;let nextRatio=+Number.parseFloat(`${currentRatio+ratioDelta}`).toFixed(1);nextRatio=nextRatio>=4?4:nextRatio<=.1?.1:nextRatio,this._commandService.executeCommand(docs.SetDocZoomRatioCommand.id,{zoomRatio:nextRatio,unitId:documentModel.getUnitId()}),e.preventDefault()}))})}_initSkeletonListener(){this.disposeWithMe(this._docSkeletonManagerService.currentSkeleton$.subscribe(param=>{if(param==null)return;const documentModel=this._univerInstanceService.getCurrentUniverDocInstance();if(!documentModel)return;const zoomRatio=documentModel.zoomRatio||1;this.updateViewZoom(zoomRatio,!1)}))}_initCommandExecutedListener(){const updateCommandList=[docs.SetDocZoomRatioOperation.id];this.disposeWithMe(this._commandService.onCommandExecuted(command=>{if(updateCommandList.includes(command.id)){const documentModel=this._univerInstanceService.getCurrentUniverDocInstance();if(!documentModel)return;const params=command.params,{unitId}=params;if(unitId!==documentModel.getUnitId())return;const zoomRatio=documentModel.zoomRatio||1;this.updateViewZoom(zoomRatio)}}))}updateViewZoom(zoomRatio,needRefreshSelection=!0){var _a2;const docObject=docs.neoGetDocObject(this._context);docObject.scene.scale(zoomRatio,zoomRatio),this._docPageLayoutService.calculatePagePosition(),needRefreshSelection&&!this._editorService.isEditor(this._context.unitId)&&this._textSelectionManagerService.refreshSelection(),(_a2=docObject.scene.getTransformer())==null||_a2.clearSelectedObjects()}},__name(_j,"DocZoomRenderController"),_j);DocZoomRenderController=__decorateClass$8([__decorateParam$8(1,core.Inject(docs.DocSkeletonManagerService)),__decorateParam$8(2,core.IUniverInstanceService),__decorateParam$8(3,core.ICommandService),__decorateParam$8(4,core.Inject(docs.TextSelectionManagerService)),__decorateParam$8(5,ui.IEditorService),__decorateParam$8(6,core.Inject(DocPageLayoutService))],DocZoomRenderController);var __defProp$7=Object.defineProperty,__getOwnPropDesc$7=Object.getOwnPropertyDescriptor,__decorateClass$7=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$7(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$7(target,key,result),result},"__decorateClass$7"),__decorateParam$7=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$7");let DocTextSelectionRenderController=(_k=class extends core.Disposable{constructor(_context,_commandService,_editorService,_instanceSrv,_textSelectionRenderManager,_docSkeletonManagerService,_textSelectionManagerService){super();__publicField(this,"_loadedMap",new WeakSet);this._context=_context,this._commandService=_commandService,this._editorService=_editorService,this._instanceSrv=_instanceSrv,this._textSelectionRenderManager=_textSelectionRenderManager,this._docSkeletonManagerService=_docSkeletonManagerService,this._textSelectionManagerService=_textSelectionManagerService,this._initialize()}_initialize(){this._init(),this._skeletonListener(),this._commandExecutedListener()}_init(){const{unitId}=this._context,docObject=docs.neoGetDocObject(this._context);docObject==null||docObject.document==null||this._loadedMap.has(docObject.document)||(this._initialMain(unitId),this._loadedMap.add(docObject.document))}_initialMain(unitId){const docObject=docs.neoGetDocObject(this._context),{document,scene}=docObject;this.disposeWithMe(document.onPointerEnter$.subscribeEvent(()=>{this._isEditorReadOnly(unitId)||(document.cursor=engineRender.CURSOR_TYPE.TEXT)})),this.disposeWithMe(document.onPointerLeave$.subscribeEvent(()=>{document.cursor=engineRender.CURSOR_TYPE.DEFAULT,scene.resetCursor()})),this.disposeWithMe(document.onPointerDown$.subscribeEvent((evt,state)=>{if(this._isEditorReadOnly(unitId))return;const docDataModel=this._instanceSrv.getCurrentUnitForType(core.UniverInstanceType.UNIVER_DOC);(docDataModel==null?void 0:docDataModel.getUnitId())!==unitId&&this._instanceSrv.setCurrentUnitForType(unitId);const skeleton=this._docSkeletonManagerService.getSkeleton(),{offsetX,offsetY}=evt,coord=this._getTransformCoordForDocumentOffset(offsetX,offsetY);if(coord!=null){const{pageLayoutType=engineRender.PageLayoutType.VERTICAL,pageMarginLeft,pageMarginTop}=document.getOffsetConfig(),{editArea}=skeleton.findEditAreaByCoord(coord,pageLayoutType,pageMarginLeft,pageMarginTop),viewModel=this._docSkeletonManagerService.getViewModel(),preEditArea=viewModel.getEditArea();preEditArea!==engineRender.DocumentEditArea.BODY&&editArea!==engineRender.DocumentEditArea.BODY&&editArea!==preEditArea&&viewModel.setEditArea(editArea)}if(this._textSelectionRenderManager.eventTrigger(evt),this._editorService.getEditor(unitId)){this._setEditorFocus(unitId);const{offsetX:offsetX2,offsetY:offsetY2}=evt;setTimeout(()=>{this._setEditorFocus(unitId),this._textSelectionRenderManager.setCursorManually(offsetX2,offsetY2)},0)}evt.button!==2&&state.stopPropagation()})),this.disposeWithMe(document.onDblclick$.subscribeEvent(evt=>{this._isEditorReadOnly(unitId)||this._textSelectionRenderManager.handleDblClick(evt)})),this.disposeWithMe(document.onTripleClick$.subscribeEvent(evt=>{this._isEditorReadOnly(unitId)||this._textSelectionRenderManager.handleTripleClick(evt)}))}_getTransformCoordForDocumentOffset(evtOffsetX,evtOffsetY){const docObject=docs.neoGetDocObject(this._context),{document,scene}=docObject,{documentTransform}=document.getOffsetConfig(),activeViewport=scene.getViewports()[0];if(activeViewport==null)return;const originCoord=activeViewport.transformVector2SceneCoord(engineRender.Vector2.FromArray([evtOffsetX,evtOffsetY]));return documentTransform.clone().invert().applyPoint(originCoord)}_isEditorReadOnly(unitId){const editor=this._editorService.getEditor(unitId);return editor?editor.isReadOnly():!1}_setEditorFocus(unitId){this._editorService.focusStyle(unitId)}_commandExecutedListener(){const updateCommandList=[docs.SetDocZoomRatioOperation.id];this.disposeWithMe(this._commandService.onCommandExecuted(command=>{var _a2;if(updateCommandList.includes(command.id)){const params=command.params,{unitId:documentId}=params,unitId=(_a2=this._textSelectionManagerService.getCurrentSelection())==null?void 0:_a2.unitId;if(documentId!==unitId)return;this._textSelectionManagerService.refreshSelection()}}))}_skeletonListener(){this.disposeWithMe(this._docSkeletonManagerService.currentSkeleton$.subscribe(skeleton=>{if(skeleton==null)return;const{scene,mainComponent,unitId}=this._context;this._textSelectionRenderManager.changeRuntime(skeleton,scene,mainComponent),this._textSelectionManagerService.setCurrentSelectionNotRefresh({unitId,subUnitId:""}),core.isInternalEditorID(unitId)||this._textSelectionManagerService.replaceTextRanges([{startOffset:0,endOffset:0}],!1)}))}},__name(_k,"DocTextSelectionRenderController"),_k);DocTextSelectionRenderController=__decorateClass$7([__decorateParam$7(1,core.ICommandService),__decorateParam$7(2,ui.IEditorService),__decorateParam$7(3,core.IUniverInstanceService),__decorateParam$7(4,engineRender.ITextSelectionRenderManager),__decorateParam$7(5,core.Inject(docs.DocSkeletonManagerService)),__decorateParam$7(6,core.Inject(docs.TextSelectionManagerService))],DocTextSelectionRenderController);var __defProp$6=Object.defineProperty,__getOwnPropDesc$6=Object.getOwnPropertyDescriptor,__decorateClass$6=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$6(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$6(target,key,result),result},"__decorateClass$6"),__decorateParam$6=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$6");function transformBound2OffsetBound(originBound,scene){const topLeft=transformPosition2Offset(originBound.left,originBound.top,scene),bottomRight=transformPosition2Offset(originBound.right,originBound.bottom,scene);return{left:topLeft.x,top:topLeft.y,right:bottomRight.x,bottom:bottomRight.y}}__name(transformBound2OffsetBound,"transformBound2OffsetBound");function transformPosition2Offset(x,y,scene){const{scaleX,scaleY}=scene.getAncestorScale(),viewMain=scene.getViewport(docs.VIEWPORT_KEY.VIEW_MAIN);if(!viewMain)return{x,y};const{viewportScrollX:actualScrollX,viewportScrollY:actualScrollY}=viewMain,offsetX=(x-actualScrollX)*scaleX,offsetY=(y-actualScrollY)*scaleY;return{x:offsetX,y:offsetY}}__name(transformPosition2Offset,"transformPosition2Offset"),exports2.DocCanvasPopManagerService=(_l=class extends core.Disposable{constructor(_globalPopupManagerService,_renderManagerService,_univerInstanceService,_commandService){super(),this._globalPopupManagerService=_globalPopupManagerService,this._renderManagerService=_renderManagerService,this._univerInstanceService=_univerInstanceService,this._commandService=_commandService}_createObjectPositionObserver(targetObject,currentRender){const calc=__name(()=>{const{scene,engine}=currentRender,{left,top,width,height}=targetObject,bound={left,right:left+width,top,bottom:top+height},canvasElement=engine.getCanvasElement(),canvasClientRect=canvasElement.getBoundingClientRect(),widthOfCanvas=engineRender.pxToNum(canvasElement.style.width),offsetBound=transformBound2OffsetBound(bound,scene),{top:topOffset,left:leftOffset,width:domWidth}=canvasClientRect,scaleAdjust=domWidth/widthOfCanvas;return{left:offsetBound.left*scaleAdjust+leftOffset,right:offsetBound.right*scaleAdjust+leftOffset,top:offsetBound.top*scaleAdjust+topOffset,bottom:offsetBound.bottom*scaleAdjust+topOffset}},"calc"),position=calc(),position$=new rxjs.BehaviorSubject(position),disposable=new core.DisposableCollection;disposable.add(this._commandService.onCommandExecuted(commandInfo=>{commandInfo.id===docs.SetDocZoomRatioOperation.id&&position$.next(calc())}));const viewMain=currentRender.scene.getViewport(docs.VIEWPORT_KEY.VIEW_MAIN);return viewMain&&disposable.add(viewMain.onScrollAfter$.subscribeEvent(()=>{position$.next(calc())})),{position,position$,disposable}}_createRangePositionObserver(range,currentRender){var _a2;const calc=__name(()=>{const{scene,mainComponent,engine}=currentRender,skeleton=currentRender.with(docs.DocSkeletonManagerService).getSkeleton(),startPosition=skeleton.findNodePositionByCharIndex(range.startOffset),endPosition=skeleton.findNodePositionByCharIndex(range.endOffset),document=mainComponent;if(!endPosition||!startPosition)return;const documentOffsetConfig=document.getOffsetConfig(),{docsLeft,docsTop}=documentOffsetConfig,canvasElement=engine.getCanvasElement(),canvasClientRect=canvasElement.getBoundingClientRect(),widthOfCanvas=engineRender.pxToNum(canvasElement.style.width),{top,left,width}=canvasClientRect,scaleAdjust=width/widthOfCanvas,{scaleX,scaleY}=scene.getAncestorScale(),convertor=new engineRender.NodePositionConvertToCursor(documentOffsetConfig,skeleton),{borderBoxPointGroup}=convertor.getRangePointData(startPosition,endPosition);return engineRender.getLineBounding(borderBoxPointGroup).map(bound=>transformBound2OffsetBound(bound,scene)).map(i=>({left:(i.left+docsLeft*scaleX)*scaleAdjust+left,right:(i.right+docsLeft*scaleX)*scaleAdjust+left,top:(i.top+docsTop*scaleY)*scaleAdjust+top,bottom:(i.bottom+docsTop*scaleY)*scaleAdjust+top}))},"calc"),positions=(_a2=calc())!=null?_a2:[],positions$=new rxjs.BehaviorSubject(positions),disposable=new core.DisposableCollection;disposable.add(this._commandService.onCommandExecuted(commandInfo=>{if(commandInfo.id===docs.SetDocZoomRatioOperation.id){const position=calc();position&&positions$.next(position)}}));const viewMain=currentRender.scene.getViewport(docs.VIEWPORT_KEY.VIEW_MAIN);return viewMain&&disposable.add(viewMain.onScrollAfter$.subscribeEvent(()=>{const position=calc();position&&positions$.next(position)})),{positions,positions$,disposable}}attachPopupToObject(targetObject,popup){const unitId=this._univerInstanceService.getCurrentUnitForType(core.UniverInstanceType.UNIVER_DOC).getUnitId(),currentRender=this._renderManagerService.getRenderById(unitId);if(!currentRender)return{dispose:__name(()=>{},"dispose")};const{position,position$,disposable}=this._createObjectPositionObserver(targetObject,currentRender),id=this._globalPopupManagerService.addPopup({...popup,unitId,subUnitId:"default",anchorRect:position,anchorRect$:position$});return{dispose:__name(()=>{this._globalPopupManagerService.removePopup(id),position$.complete(),disposable.dispose()},"dispose")}}attachPopupToRange(range,popup){const unitId=this._univerInstanceService.getCurrentUnitForType(core.UniverInstanceType.UNIVER_DOC).getUnitId(),{direction="top"}=popup,currentRender=this._renderManagerService.getRenderById(unitId);if(!currentRender)return{dispose:__name(()=>{},"dispose")};const{positions:bounds,positions$:bounds$,disposable}=this._createRangePositionObserver(range,currentRender),position$=bounds$.pipe(rxjs.map(bounds2=>direction==="top"?bounds2[0]:bounds2[bounds2.length-1])),id=this._globalPopupManagerService.addPopup({...popup,unitId,subUnitId:"default",anchorRect:direction==="top"?bounds[0]:bounds[bounds.length-1],anchorRect$:position$,excludeRects:bounds,excludeRects$:bounds$,direction:direction==="top"?"top":"bottom"});return{dispose:__name(()=>{this._globalPopupManagerService.removePopup(id),bounds$.complete(),disposable.dispose()},"dispose")}}},__name(_l,"DocCanvasPopManagerService"),_l),exports2.DocCanvasPopManagerService=__decorateClass$6([__decorateParam$6(0,core.Inject(ui.ICanvasPopupService)),__decorateParam$6(1,engineRender.IRenderManagerService),__decorateParam$6(2,core.IUniverInstanceService),__decorateParam$6(3,core.ICommandService)],exports2.DocCanvasPopManagerService);var __defProp$5=Object.defineProperty,__getOwnPropDesc$5=Object.getOwnPropertyDescriptor,__decorateClass$5=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$5(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$5(target,key,result),result},"__decorateClass$5"),__decorateParam$5=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$5");exports2.DocsRenderService=(_m=class extends core.RxDisposable{constructor(_instanceSrv,_renderManagerService){super(),this._instanceSrv=_instanceSrv,this._renderManagerService=_renderManagerService,this._init()}_init(){this._renderManagerService.createRender$.pipe(rxjs.takeUntil(this.dispose$)).subscribe(unitId=>this._createRenderWithId(unitId)),this._instanceSrv.getTypeOfUnitAdded$(core.UniverInstanceType.UNIVER_DOC).pipe(rxjs.takeUntil(this.dispose$)).subscribe(doc=>this._createRenderer(doc)),this._instanceSrv.getAllUnitsForType(core.UniverInstanceType.UNIVER_DOC).forEach(documentModel=>this._createRenderer(documentModel)),this._instanceSrv.getTypeOfUnitDisposed$(core.UniverInstanceType.UNIVER_DOC).pipe(rxjs.takeUntil(this.dispose$)).subscribe(doc=>this._disposeRenderer(doc))}_createRenderer(doc){const unitId=doc.getUnitId();this._renderManagerService.has(unitId)||(this._createRenderWithId(unitId),this._renderManagerService.setCurrent(unitId))}_createRenderWithId(unitId){this._renderManagerService.createRender(unitId)}_disposeRenderer(doc){const unitId=doc.getUnitId();this._renderManagerService.removeRender(unitId)}},__name(_m,"DocsRenderService"),_m),exports2.DocsRenderService=__decorateClass$5([core.OnLifecycle(core.LifecycleStages.Ready,exports2.DocsRenderService),__decorateParam$5(0,core.IUniverInstanceService),__decorateParam$5(1,engineRender.IRenderManagerService)],exports2.DocsRenderService);var __defProp$4=Object.defineProperty,__getOwnPropDesc$4=Object.getOwnPropertyDescriptor,__decorateClass$4=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$4(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$4(target,key,result),result},"__decorateClass$4"),__decorateParam$4=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$4");const SKIP_UNIT_IDS$1=[core.DEFAULT_EMPTY_DOCUMENT_VALUE,core.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,core.DOCS_NORMAL_EDITOR_UNIT_ID_KEY,core.DOCS_ZEN_EDITOR_UNIT_ID_KEY];let DocContextMenuRenderController=(_n=class extends core.Disposable{constructor(_context,_contextMenuService,_textSelectionManagerService,_commandService){super(),this._context=_context,this._contextMenuService=_contextMenuService,this._textSelectionManagerService=_textSelectionManagerService,this._commandService=_commandService,SKIP_UNIT_IDS$1.includes(this._context.unitId)||(this._initPointerDown(),this._initEditChange())}_initPointerDown(){var _a2,_b2;const documentsSubscription=((_b2=(_a2=this._context)==null?void 0:_a2.mainComponent)==null?void 0:_b2.onPointerDown$).subscribeEvent(event=>{event.button===2&&this._contextMenuService.triggerContextMenu(event,ui.MenuPosition.CONTEXT_MENU)});this.disposeWithMe(documentsSubscription)}_initEditChange(){this.disposeWithMe(this._commandService.onCommandExecuted(command=>{command.id===docs.RichTextEditingMutation.id&&this._contextMenuService.visible&&this._contextMenuService.hideContextMenu()}))}},__name(_n,"DocContextMenuRenderController"),_n);DocContextMenuRenderController=__decorateClass$4([__decorateParam$4(1,ui.IContextMenuService),__decorateParam$4(2,core.Inject(docs.TextSelectionManagerService)),__decorateParam$4(3,core.ICommandService)],DocContextMenuRenderController);var __defProp$3=Object.defineProperty,__getOwnPropDesc$3=Object.getOwnPropertyDescriptor,__decorateClass$3=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$3(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$3(target,key,result),result},"__decorateClass$3"),__decorateParam$3=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$3");const SKIP_UNIT_IDS=[core.DEFAULT_EMPTY_DOCUMENT_VALUE,core.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,core.DOCS_NORMAL_EDITOR_UNIT_ID_KEY];let DocResizeRenderController=(_o=class extends core.Disposable{constructor(_context,_docPageLayoutService,_textSelectionManagerService){super(),this._context=_context,this._docPageLayoutService=_docPageLayoutService,this._textSelectionManagerService=_textSelectionManagerService,SKIP_UNIT_IDS.includes(this._context.unitId)||this._initResize()}_initResize(){this.disposeWithMe(core.fromEventSubject(this._context.engine.onTransformChange$).pipe(rxjs.filter(evt=>evt.type===engineRender.TRANSFORM_CHANGE_OBSERVABLE_TYPE.resize),rxjs.throttleTime(16)).subscribe(()=>{this._docPageLayoutService.calculatePagePosition(),this._textSelectionManagerService.refreshSelection()}))}},__name(_o,"DocResizeRenderController"),_o);DocResizeRenderController=__decorateClass$3([__decorateParam$3(1,core.Inject(DocPageLayoutService)),__decorateParam$3(2,core.Inject(docs.TextSelectionManagerService))],DocResizeRenderController);var __defProp$2=Object.defineProperty,__getOwnPropDesc$2=Object.getOwnPropertyDescriptor,__decorateClass$2=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$2(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$2(target,key,result),result},"__decorateClass$2"),__decorateParam$2=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$2");exports2.DocHoverManagerService=(_p=class extends core.Disposable{constructor(_univerInstanceService,_renderManagerService){super();__publicField(this,"_activeCustomRanges$",new rxjs.BehaviorSubject([]));__publicField(this,"activeCustomRanges$",this._activeCustomRanges$.asObservable());__publicField(this,"_activeIndex$",new rxjs.BehaviorSubject(null));__publicField(this,"activeIndex$",this._activeIndex$.asObservable());__publicField(this,"_scrolling",!1);this._univerInstanceService=_univerInstanceService,this._renderManagerService=_renderManagerService,this.disposeWithMe(()=>{this._activeCustomRanges$.complete(),this._activeIndex$.complete()})}_getTransformCoordForDocumentOffset(document,viewport,evtOffsetX,evtOffsetY){const{documentTransform}=document.getOffsetConfig(),originCoord=viewport.transformVector2SceneCoord(engineRender.Vector2.FromArray([evtOffsetX,evtOffsetY]));if(originCoord)return documentTransform.clone().invert().applyPoint(originCoord)}_calcActiveCustomRanges(offsetX,offsetY){var _a2,_b2;const document=this._univerInstanceService.getCurrentUnitForType(core.UniverInstanceType.UNIVER_DOC);if(!document){this._activeCustomRanges$.next([]);return}const currentRender=this._renderManagerService.getRenderById(document.getUnitId());if(!currentRender)return null;const documentComponent=currentRender.mainComponent,skeleton=currentRender.with(docs.DocSkeletonManagerService).getSkeleton(),{pageLayoutType=engineRender.PageLayoutType.VERTICAL,pageMarginLeft,pageMarginTop,docsLeft,docsTop}=documentComponent.getOffsetConfig(),coord=this._getTransformCoordForDocumentOffset(documentComponent,currentRender.scene.getViewport(docs.VIEWPORT_KEY.VIEW_MAIN),offsetX,offsetY);if(!coord)return;const node=skeleton.findNodeByCoord(coord,pageLayoutType,pageMarginLeft,pageMarginTop);if(node&&node.node){const left=node.node.left+pageMarginLeft,right=node.node.left+node.node.width+pageMarginLeft;if(coord.x<left||coord.x>right){this._activeIndex$.next(null),this._activeCustomRanges$.next([]);return}const index=node.node.parent.st+node.node.parent.glyphGroup.indexOf(node.node);index!==this._activeIndex$.value&&this._activeIndex$.next(index);const ranges=(_b2=(_a2=document.getCustomRanges())==null?void 0:_a2.filter(range=>range.startIndex<=index&&range.endIndex>=index))!=null?_b2:[],currentRanges=this._activeCustomRanges$.value;if(currentRanges.length===ranges.length&¤tRanges.every((range,i)=>range.rangeId===ranges[i].rangeId))return;this._activeCustomRanges$.next(ranges)}}onMouseMove(evt){if(this._scrolling)return;const{offsetX,offsetY}=evt;this._calcActiveCustomRanges(offsetX,offsetY)}startScroll(){this._scrolling||(this._scrolling=!0)}endScroll(){this._scrolling=!1}},__name(_p,"DocHoverManagerService"),_p),exports2.DocHoverManagerService=__decorateClass$2([__decorateParam$2(0,core.IUniverInstanceService),__decorateParam$2(1,engineRender.IRenderManagerService)],exports2.DocHoverManagerService);var __defProp$1=Object.defineProperty,__getOwnPropDesc$1=Object.getOwnPropertyDescriptor,__decorateClass$1=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc$1(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp$1(target,key,result),result},"__decorateClass$1"),__decorateParam$1=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam$1");let DocHoverRenderController=(_q=class extends core.Disposable{constructor(_context,_docHoverManagerService){super(),this._context=_context,this._docHoverManagerService=_docHoverManagerService,this._initPointerDown(),this._initScroll()}_initPointerDown(){this.disposeWithMe(core.fromEventSubject(this._context.scene.onPointerMove$).pipe(rxjs.debounceTime(200)).subscribe(evt=>{this._docHoverManagerService.onMouseMove(evt)}))}_initScroll(){const viewMain=this._context.scene.getViewport(docs.VIEWPORT_KEY.VIEW_MAIN);viewMain&&(this.disposeWithMe(core.fromEventSubject(viewMain.onScrollAfter$).pipe(rxjs.debounceTime(60)).subscribe(()=>{this._docHoverManagerService.endScroll()})),this.disposeWithMe(viewMain.onScrollBefore$.subscribeEvent(()=>{this._docHoverManagerService.startScroll()})))}},__name(_q,"DocHoverRenderController"),_q);DocHoverRenderController=__decorateClass$1([__decorateParam$1(1,core.Inject(exports2.DocHoverManagerService))],DocHoverRenderController);var __defProp2=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__decorateClass=__name((decorators,target,key,kind)=>{for(var result=kind>1?void 0:kind?__getOwnPropDesc(target,key):target,i=decorators.length-1,decorator;i>=0;i--)(decorator=decorators[i])&&(result=(kind?decorator(target,key,result):decorator(result))||result);return kind&&result&&__defProp2(target,key,result),result},"__decorateClass"),__decorateParam=__name((index,decorator)=>(target,key)=>decorator(target,key,index),"__decorateParam");exports2.UniverDocsUIPlugin=(_r=class extends core.Plugin{constructor(_config,_injector,_renderManagerSrv,_logService){super(),this._config=_config,this._injector=_injector,this._renderManagerSrv=_renderManagerSrv,this._logService=_logService,this._config=core.Tools.deepMerge({},DefaultDocUiConfig,this._config),this._initDependencies(_injector),this._initializeCommands()}onReady(){this._initRenderBasics(),this._markDocAsFocused()}onRendered(){this._initUI(),this._initRenderModules()}_initializeCommands(){[MoveCursorUpShortcut,MoveCursorDownShortcut,MoveCursorRightShortcut,MoveCursorLeftShortcut,MoveSelectionUpShortcut,MoveSelectionDownShortcut,MoveSelectionLeftShortcut,MoveSelectionRightShortcut,SelectAllShortcut,DeleteLeftShortcut,DeleteRightShortcut,BreakLineShortcut].forEach(shortcut=>{this._injector.get(ui.IShortcutService).registerShortcut(shortcut)})}_initDependencies(injector){[[DocUIController,{useFactory:__name(()=>this._injector.createInstance(DocUIController,this._config),"useFactory")}],[DocClipboardController],[DocEditorBridgeController],[exports2.DocsRenderService],[AppUIController,{useFactory:__name(()=>this._injector.createInstance(AppUIController,this._config),"useFactory")}],[IDocClipboardService,{useClass:DocClipboardService}],[exports2.DocCanvasPopManagerService],[exports2.DocHoverManagerService]].forEach(d=>injector.add(d))}_markDocAsFocused(){const currentService=this._injector.get(core.IUniverInstanceService),editorService=this._injector.get(ui.IEditorService);try{const doc=currentService.getCurrentUnitForType(core.UniverInstanceType.UNIVER_DOC);if(!doc)return;const id=doc.getUnitId();editorService.isEditor(id)||currentService.focusUnit(doc.getUnitId())}catch(err){this._logService.warn(err)}}_initUI(){this._injector.get(AppUIController)}_initRenderBasics(){[[docs.DocSkeletonManagerService],[docs.DocInterceptorService],[DocPageLayoutService],[exports2.DocRenderController],[DocZoomRenderController]].forEach(m2=>{this._renderManagerSrv.registerRenderModule(core.UniverInstanceType.UNIVER_DOC,m2)})}_initRenderModules(){[[exports2.DocBackScrollRenderController],[DocTextSelectionRenderController],[DocHeaderFooterController],[DocResizeRenderController],[DocHoverRenderController],[DocContextMenuRenderController]].forEach(m2=>{this._renderManagerSrv.registerRenderModule(core.UniverInstanceType.UNIVER_DOC,m2)})}},__name(_r,"UniverDocsUIPlugin"),__publicField(_r,"pluginName",DOC_UI_PLUGIN_NAME),__publicField(_r,"type",core.UniverInstanceType.UNIVER_DOC),_r),exports2.UniverDocsUIPlugin=__decorateClass([__decorateParam(1,core.Inject(core.Injector)),__decorateParam(2,engineRender.IRenderManagerService),__decorateParam(3,core.ILogService)],exports2.UniverDocsUIPlugin);function docDrawingPositionToTransform(position){return{left:position.positionH.posOffset,top:position.positionV.posOffset,width:position.size.width,height:position.size.height}}__name(docDrawingPositionToTransform,"docDrawingPositionToTransform");function transformToDocDrawingPosition(transform,marginLeft=0,marginTop=0){return{size:{width:transform.width,height:transform.height},positionH:{relativeFrom:core.ObjectRelativeFromH.MARGIN,posOffset:(transform.left||0)-marginLeft},positionV:{relativeFrom:core.ObjectRelativeFromV.PAGE,posOffset:(transform.top||0)-marginTop},angle:transform.angle||0}}__name(transformToDocDrawingPosition,"transformToDocDrawingPosition"),exports2.DOC_UI_PLUGIN_NAME=DOC_UI_PLUGIN_NAME,exports2.DefaultDocContainerConfig=DefaultDocContainerConfig,exports2.DefaultDocUiConfig=DefaultDocUiConfig,exports2.DefaultToolbarConfig=DefaultToolbarConfig,exports2.DocCopyCommand=DocCopyCommand,exports2.DocCutCommand=DocCutCommand,exports2.DocPasteCommand=DocPasteCommand,exports2.IDocClipboardService=IDocClipboardService,exports2.PastePluginLark=PastePluginLark,exports2.PastePluginUniver=PastePluginUniver,exports2.PastePluginWord=PastePluginWord,exports2.docDrawingPositionToTransform=docDrawingPositionToTransform,exports2.transformToDocDrawingPosition=transformToDocDrawingPosition,exports2.whenDocAndEditorFocused=whenDocAndEditorFocused,Object.defineProperty(exports2,Symbol.toStringTag,{value:"Module"})});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@univerjs/docs-ui",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.6",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Univer normal ui-plugin-docs",
|
|
6
6
|
"author": "DreamNum <developer@univer.ai>",
|
|
@@ -53,11 +53,11 @@
|
|
|
53
53
|
"clsx": ">=2.0.0",
|
|
54
54
|
"react": "^16.9.0 || ^17.0.0 || ^18.0.0",
|
|
55
55
|
"rxjs": ">=7.0.0",
|
|
56
|
-
"@univerjs/core": "0.2.
|
|
57
|
-
"@univerjs/design": "0.2.
|
|
58
|
-
"@univerjs/
|
|
59
|
-
"@univerjs/
|
|
60
|
-
"@univerjs/
|
|
56
|
+
"@univerjs/core": "0.2.6",
|
|
57
|
+
"@univerjs/design": "0.2.6",
|
|
58
|
+
"@univerjs/engine-render": "0.2.6",
|
|
59
|
+
"@univerjs/docs": "0.2.6",
|
|
60
|
+
"@univerjs/ui": "0.2.6"
|
|
61
61
|
},
|
|
62
62
|
"devDependencies": {
|
|
63
63
|
"@types/react": "^18.3.3",
|
|
@@ -65,15 +65,15 @@
|
|
|
65
65
|
"less": "^4.2.0",
|
|
66
66
|
"react": "18.3.1",
|
|
67
67
|
"rxjs": "^7.8.1",
|
|
68
|
-
"typescript": "^5.5.
|
|
69
|
-
"vite": "^5.3.
|
|
70
|
-
"vitest": "^2.0.
|
|
71
|
-
"@univerjs/core": "0.2.
|
|
72
|
-
"@univerjs/design": "0.2.
|
|
73
|
-
"@univerjs/
|
|
74
|
-
"@univerjs/
|
|
75
|
-
"@univerjs/
|
|
76
|
-
"@univerjs/ui": "0.2.
|
|
68
|
+
"typescript": "^5.5.4",
|
|
69
|
+
"vite": "^5.3.5",
|
|
70
|
+
"vitest": "^2.0.4",
|
|
71
|
+
"@univerjs/core": "0.2.6",
|
|
72
|
+
"@univerjs/design": "0.2.6",
|
|
73
|
+
"@univerjs/docs": "0.2.6",
|
|
74
|
+
"@univerjs/shared": "0.2.6",
|
|
75
|
+
"@univerjs/engine-render": "0.2.6",
|
|
76
|
+
"@univerjs/ui": "0.2.6"
|
|
77
77
|
},
|
|
78
78
|
"univerSpace": {
|
|
79
79
|
".": {
|