@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/cjs/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var _t=Object.defineProperty;var mt=(o,e,t)=>e in o?_t(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var D=(o,e,t)=>mt(o,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("@univerjs/core"),l=require("@univerjs/ui"),d=require("@univerjs/docs"),C=require("@univerjs/engine-render"),R=require("rxjs"),L=require("react"),H=require("@univerjs/design"),St=require("clsx");function P(o){return o.getContextValue(a.FOCUSING_DOC)&&o.getContextValue(a.FOCUSING_UNIVER_EDITOR)&&!o.getContextValue(a.FOCUSING_COMMON_DRAWINGS)}function ft(o){return o.getContextValue(a.FOCUSING_DOC)&&o.getContextValue(a.FOCUSING_UNIVER_EDITOR)&&!o.getContextValue(a.FOCUSING_UNIVER_EDITOR_STANDALONE_SINGLE_MODE)&&!o.getContextValue(a.FOCUSING_COMMON_DRAWINGS)}const vt=10,Ct=6;function It(){return a.Tools.generateRandomId(Ct)}function Ot(o){const e=o.match(/data-copy-id="([^\s]+)"/);return e&&e[1]?e[1]:null}class Tt{constructor(){D(this,"_cache",new a.LRUMap(vt))}set(e,t){this._cache.set(e,t)}get(e){return this._cache.get(e)}clear(){this._cache.clear()}}const Ue=new Tt;function Me(o){const e=o.style,t={},n=o.tagName.toLowerCase();switch(n){case"b":case"em":case"strong":{t.bl=a.BooleanNumber.TRUE;break}case"s":{t.st={s:a.BooleanNumber.TRUE};break}case"u":{t.ul={s:a.BooleanNumber.TRUE};break}case"i":{t.it=a.BooleanNumber.TRUE;break}case"sub":case"sup":{t.va=n==="sup"?a.BaselineOffset.SUPERSCRIPT:a.BaselineOffset.SUBSCRIPT;break}}for(let i=0;i<e.length;i++){const r=e[i],s=e.getPropertyValue(r);switch(r){case"font-family":{t.ff=s;break}case"font-size":{const c=Number.parseInt(s);Number.isNaN(c)||(s.endsWith("pt")?t.fs=c:s.endsWith("px")&&(t.fs=C.pixelToPt(c)));break}case"font-style":{s==="italic"&&(t.it=a.BooleanNumber.TRUE);break}case"font-weight":{(Number(s)>400||String(s)==="bold")&&(t.bl=a.BooleanNumber.TRUE);break}case"text-decoration":{/underline/.test(s)?t.ul={s:a.BooleanNumber.TRUE}:/overline/.test(s)?t.ol={s:a.BooleanNumber.TRUE}:/line-through/.test(s)&&(t.st={s:a.BooleanNumber.TRUE});break}case"color":{const c=new a.ColorKit(s);c.isValid&&(t.cl={rgb:c.toRgbString()});break}case"background-color":{const c=new a.ColorKit(s);c.isValid&&(t.bg={rgb:c.toRgbString()});break}}}return t}function Rt(o){const e=new DOMParser,t=`<x-univer id="univer-root">${o}</x-univer>`;return e.parseFromString(t,"text/html").querySelector("#univer-root")}function Fe(o,e){const t=o.tagName.toLowerCase();return typeof e=="string"?t===e:Array.isArray(e)?e.some(n=>n===t):e(o)}const ae=class ae{constructor(){D(this,"_styleCache",new Map);D(this,"_styleRules",[]);D(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=ae._pluginList.find(r=>r.checkPasteType(e)),n=Rt(e),i={dataStream:"",textRuns:[]};return t&&(this._styleRules=[...t.stylesRules],this._afterProcessRules=[...t.afterProcessRules]),this._styleCache.clear(),this._process(null,n==null?void 0:n.childNodes,i),this._styleCache.clear(),this._styleRules=[],this._afterProcessRules=[],i}_process(e,t,n){var i,r,s;for(const c of t)if(c.nodeType===Node.TEXT_NODE){if(((i=c.nodeValue)==null?void 0:i.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 _=a.Tools.generateRandomId();u=`${a.DataStreamTreeTokenType.CUSTOM_RANGE_START}${u}${a.DataStreamTreeTokenType.CUSTOM_RANGE_END}`,n.customRanges=[...(s=n.customRanges)!=null?s:[],{startIndex:n.dataStream.length,endIndex:n.dataStream.length+u.length-1,rangeId:_,rangeType:a.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(a.skipParseTagNames.includes(c.nodeName.toLowerCase()))continue;if(c.nodeType===Node.ELEMENT_NODE){const u=e?this._styleCache.get(e):{},h=this._styleRules.find(({filter:g})=>Fe(c,g)),_=h?h.getStyle(c):Me(c);this._styleCache.set(c,{...u,..._});const{childNodes:m}=c;this._process(c,m,n);const S=this._afterProcessRules.find(({filter:g})=>Fe(c,g));S&&S.handler(n,c)}}}};D(ae,"_pluginList",[]);let k=ae;const Mt={name:"univer-doc-paste-plugin-lark",checkPasteType(o){return/lark-record-clipboard/i.test(o)},stylesRules:[{filter:["s"],getStyle(o){const e=Me(o);return{st:{s:a.BooleanNumber.TRUE},...e}}}],afterProcessRules:[{filter(o){return o.tagName==="DIV"&&/ace-line/i.test(o.className)},handler(o){o.paragraphs==null&&(o.paragraphs=[]),o.paragraphs.push({startIndex:o.dataStream.length}),o.dataStream+="\r"}}]},Je=Mt;function qe(o){const e=o.style,t={};for(let n=0;n<e.length;n++){const i=e[n],r=e.getPropertyValue(i);switch(i){case"margin-top":{const s=Number.parseInt(r);t.spaceAbove={v:/pt/.test(r)?C.ptToPixel(s):s};break}case"margin-bottom":{const s=Number.parseInt(r);t.spaceBelow={v:/pt/.test(r)?C.ptToPixel(s):s};break}case"line-height":{const s=Number.parseFloat(r);t.lineSpacing=s;break}}}return Object.getOwnPropertyNames(t).length?t:null}const Et={name:"univer-doc-paste-plugin-word",checkPasteType(o){return/word|mso/i.test(o)},stylesRules:[{filter:["b"],getStyle(o){const e=Me(o);return{bl:a.BooleanNumber.TRUE,...e}}}],afterProcessRules:[{filter(o){return o.tagName==="P"},handler(o,e){o.paragraphs==null&&(o.paragraphs=[]);const t={startIndex:o.dataStream.length},n=qe(e);n&&(t.paragraphStyle=n),o.paragraphs.push(t),o.dataStream+="\r"}}]},Qe=Et,bt={name:"univer-doc-paste-plugin-univer",checkPasteType(o){return/UniverNormal/i.test(o)},stylesRules:[],afterProcessRules:[{filter(o){return o.tagName==="P"&&/UniverNormal/i.test(o.className)},handler(o,e){o.paragraphs==null&&(o.paragraphs=[]);const t={startIndex:o.dataStream.length},n=qe(e);n&&(t.paragraphStyle=n),o.paragraphs.push(t),o.dataStream+="\r"}}]},et=bt;function Le(o,e){const{st:t,ed:n,ts:i={}}=e,{ff:r,fs:s,it:c,bl:u,ul:h,st:_,ol:m,bg:S,cl:g,va:f}=i;let p=o.slice(t,n);const v=[];return c===a.BooleanNumber.TRUE&&(p=`<i>${p}</i>`),f===a.BaselineOffset.SUPERSCRIPT?p=`<sup>${p}</sup>`:f===a.BaselineOffset.SUBSCRIPT&&(p=`<sub>${p}</sub>`),(h==null?void 0:h.s)===a.BooleanNumber.TRUE&&(p=`<u>${p}</u>`),(_==null?void 0:_.s)===a.BooleanNumber.TRUE&&(p=`<s>${p}</s>`),u===a.BooleanNumber.TRUE&&(p=`<strong>${p}</strong>`),r&&v.push(`font-family: ${r}`),g&&v.push(`color: ${g.rgb}`),s&&v.push(`font-size: ${s}pt`),m&&v.push("text-decoration: overline"),S&&v.push(`background: ${S.rgb}`),v.length?`<span style="${v.join("; ")};">${p}</span>`:p}function he(o,e,t){const{dataStream:n,textRuns:i=[]}=o;let r=e;const s=[];for(const c of i){const{st:u,ed:h}=c;a.Tools.hasIntersectionBetweenTwoRanges(e,t,u,h)&&(u>r?(s.push(n.slice(r,u)),s.push(Le(n,{...c,ed:Math.min(h,t)}))):s.push(Le(n,{...c,st:r,ed:Math.min(h,t)}))),r=Math.max(e,Math.min(h,t))}return r!==t&&s.push(n.slice(r,t)),s.join("")}function Be(o,e=!0){var t;if(e&&((t=o.paragraphs)!=null&&t.length)){const{dataStream:n,paragraphs:i=[]}=o;let r="",s=-1;for(const c of i){const{startIndex:u,paragraphStyle:h={}}=c,{spaceAbove:_,spaceBelow:m,lineSpacing:S}=h,g=[];_!=null&&(typeof _=="number"?g.push(`margin-top: ${_}px`):g.push(`margin-top: ${_.v}px`)),m!=null&&(typeof m=="number"?g.push(`margin-bottom: ${m}px`):g.push(`margin-bottom: ${m.v}px`)),S!=null&&g.push(`line-height: ${S}`),u>s+1?r+=`<p class="UniverNormal" ${g.length?`style="${g.join("; ")};"`:""}>${he(o,s+1,u)}</p>`:r+=`<p class="UniverNormal" ${g.length?`style="${g.join("; ")};"`:""}></p>`,s=u}return s!==n.length&&(r+=he(o,s,n.length)),r}else return he(o,0,o.dataStream.length)}class Dt{convert(e){if(e.length===0)throw new Error("The bodyList length at least to be 1");if(e.length===1)return Be(e[0]);let t="";for(const n of e)t+='<p className="UniverNormal">',t+=Be(n,!1),t+="</p>";return t}}var yt=Object.defineProperty,Pt=Object.getOwnPropertyDescriptor,xt=(o,e,t,n)=>{for(var i=n>1?void 0:n?Pt(e,t):e,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&yt(e,t,i),i},V=(o,e)=>(t,n)=>e(t,n,o);k.use(Qe);k.use(Je);k.use(et);const K=a.createIdentifier("doc.clipboard-service");let Se=class extends a.Disposable{constructor(e,t,n,i,r,s){super();D(this,"_clipboardHooks",[]);D(this,"_htmlToUDM",new k);D(this,"_umdToHtml",new Dt);this._univerInstanceService=e,this._logService=t,this._commandService=n,this._clipboardInterfaceService=i,this._textSelectionManagerService=r,this._docCustomRangeService=s}async copy(e=a.SliceBodyType.copy){const t=this._getDocumentBodyInRanges(e);if(t.length===0)return!1;try{const n=this._textSelectionManagerService.getActiveRange(),i=!!(n!=null&&n.segmentId);this._setClipboardData(t,!i)}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:{},i=this._textSelectionManagerService.getCurrentSelections();if(e==null&&this._logService.error("[DocClipboardController] segmentId is not existed"),t==null||i==null)return!1;this.copy(a.SliceBodyType.cut);try{let s=t;for(const u of i){const{startOffset:h,endOffset:_}=u;h==null||_==null||_<=t&&(s-=_-h)}const c=[{startOffset:s,endOffset:s,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=a.normalizeBody(e);const n=(h=this._univerInstanceService.getCurrentUnitForType(a.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 i=this._textSelectionManagerService.getActiveRange(),{segmentId:r,endOffset:s,style:c}=i||{},u=this._textSelectionManagerService.getCurrentSelections();if(r==null&&this._logService.error("[DocClipboardController] segmentId does not exist!"),s==null||u==null)return!1;try{let m=s;for(const g of u){const{startOffset:f,endOffset:p}=g;f==null||p==null||p<=s&&(m+=t.dataStream.length-(p-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=It(),i=e.length>1?e.map(s=>s.dataStream).join(`
|
|
2
|
-
`):e[0].dataStream;let r=this._umdToHtml.convert(e);return e.length===1&&t&&(r=r.replace(/(<[a-z]+)/,(s,c)=>`${c} data-copy-id="${n}"`),Ue.set(n,e[0])),this._clipboardInterfaceService.write(i,r)}addClipboardHook(e){return this._clipboardHooks.push(e),a.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(),i=this._univerInstanceService.getCurrentUniverDocInstance(),r=[],s=i==null?void 0:i.getBody();if(t==null||i==null||s==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},s),g=i.getSelfOrHeaderFooterModel(c).sliceBody(S.startOffset,S.endOffset,e);if(g!=null){if(g.customRanges){const f=[];g.customRanges.forEach(I=>{I.startIndex===I.endIndex&&f.push(I)}),g.customRanges=g.customRanges.filter(I=>f.indexOf(I)===-1);let p="",v=0;f.forEach(I=>{p+=g.dataStream.slice(v,I.endIndex),v=I.endIndex+1}),p+=g.dataStream.slice(v,g.dataStream.length),g.dataStream=p}r.push(g)}}return r}async _generateBodyFromClipboardItems(e){try{let t="",n="";for(const i of e)for(const r of i.types)r===l.PLAIN_TEXT_CLIPBOARD_MIME_TYPE?n=await i.getType(r).then(s=>s&&s.text()):r===l.HTML_CLIPBOARD_MIME_TYPE&&(t=await i.getType(r).then(s=>s&&s.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")&&a.Tools.isLegalUrl(e)){const i=a.Tools.generateRandomId(),r=this._univerInstanceService.getCurrentUnitForType(a.UniverInstanceType.UNIVER_DOC),s=`${a.DataStreamTreeTokenType.CUSTOM_RANGE_START}${t}${a.DataStreamTreeTokenType.CUSTOM_RANGE_END}`,c=this._docCustomRangeService.copyCustomRange(r.getUnitId(),{startIndex:0,endIndex:s.length-1,rangeId:i,rangeType:a.CustomRangeType.HYPERLINK,data:e});return{dataStream:s,customRanges:[c]}}const n=[];for(let i=0;i<t.length;i++)t[i]==="\r"&&n.push({startIndex:i});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=Ot(e);if(n){const i=Ue.get(n);if(i)return i}return this._htmlToUDM.convert(e)}};Se=xt([V(0,a.IUniverInstanceService),V(1,a.ILogService),V(2,a.ICommandService),V(3,l.IClipboardInterfaceService),V(4,a.Inject(d.TextSelectionManagerService)),V(5,a.Inject(d.DocCustomRangeService))],Se);var At=Object.defineProperty,Nt=Object.getOwnPropertyDescriptor,Ut=(o,e,t,n)=>{for(var i=n>1?void 0:n?Nt(e,t):e,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&At(e,t,i),i},Q=(o,e)=>(t,n)=>e(t,n,o);const we=1.5;exports.DocBackScrollRenderController=class extends a.RxDisposable{constructor(e,t,n,i,r){super(),this._context=e,this._textSelectionManagerService=t,this._editorService=n,this._univerInstanceService=i,this._renderManagerService=r,this._init()}_init(){this._textSelectionManagerService.textSelection$.pipe(R.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),i=n==null?void 0:n.getSkeleton();if(!i)return;const{startOffset:r}=t,s=i.findNodePositionByCharIndex(r);this.scrollToNode(e,s)}scrollToNode(e,t){var Y;const n=this._getDocObject(),i=(Y=this._renderManagerService.getRenderById(e))==null?void 0:Y.with(d.DocSkeletonManagerService),r=i==null?void 0:i.getSkeleton();if(n==null||r==null)return;const s=n.document.getOffsetConfig(),{docsLeft:c,docsTop:u}=s,h=new C.NodePositionConvertToCursor(s,r),{contentBoxPointGroup:_}=h.getRangePointData(t,t),{left:m,top:S,height:g}=C.getAnchorBounding(_),f=m+c,p=S+u,v=n.scene.getViewport(d.VIEWPORT_KEY.VIEW_MAIN),I=!!this._editorService.getEditor(e);if(v==null)return;const{left:O,top:T,right:M,bottom:b}=v.getBounding().viewBound;let E=0,x=0;const F=I?0:100;p<T?E=p-T-F:p>b-g&&(E=p-b+g+F),f<O?x=f-O:f>M-we&&(x=f-M+we);const N=v.transViewportScroll2ScrollValue(x,E);v.scrollByBarDeltaValue(N)}_scrollToSelection(e){const t=this._textSelectionManagerService.getActiveRange();if(t==null)return;const{collapsed:n,startNodePosition:i}=t;n&&this.scrollToNode(e,i)}_getDocObject(){return d.getDocObject(this._univerInstanceService,this._renderManagerService)}};exports.DocBackScrollRenderController=Ut([Q(1,a.Inject(d.TextSelectionManagerService)),Q(2,l.IEditorService),Q(3,a.Inject(a.IUniverInstanceService)),Q(4,C.IRenderManagerService)],exports.DocBackScrollRenderController);const tt={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},nt={outerLeft:!1,outerRight:!1,header:!0,footer:!0,innerLeft:!1,innerRight:!1,frozenHeaderLT:!1,frozenHeaderRT:!1,frozenHeaderLM:!1,frozenContent:!1,infoBar:!0,toolbar:!0},ot={layout:{docContainerConfig:nt,toolbarConfig:tt}},it="DocUI",Ft={id:d.MoveCursorOperation.id,binding:l.KeyCode.ARROW_UP,preconditions:P,staticParameters:{direction:a.Direction.UP}},Lt={id:d.MoveCursorOperation.id,binding:l.KeyCode.ARROW_DOWN,preconditions:P,staticParameters:{direction:a.Direction.DOWN}},Bt={id:d.MoveCursorOperation.id,binding:l.KeyCode.ARROW_LEFT,preconditions:P,staticParameters:{direction:a.Direction.LEFT}},wt={id:d.MoveCursorOperation.id,binding:l.KeyCode.ARROW_RIGHT,preconditions:P,staticParameters:{direction:a.Direction.RIGHT}},$t={id:d.MoveSelectionOperation.id,binding:l.KeyCode.ARROW_UP|l.MetaKeys.SHIFT,preconditions:P,staticParameters:{direction:a.Direction.UP}},Ht={id:d.MoveSelectionOperation.id,binding:l.KeyCode.ARROW_DOWN|l.MetaKeys.SHIFT,preconditions:P,staticParameters:{direction:a.Direction.DOWN}},jt={id:d.MoveSelectionOperation.id,binding:l.KeyCode.ARROW_LEFT|l.MetaKeys.SHIFT,preconditions:P,staticParameters:{direction:a.Direction.LEFT}},Vt={id:d.MoveSelectionOperation.id,binding:l.KeyCode.ARROW_RIGHT|l.MetaKeys.SHIFT,preconditions:P,staticParameters:{direction:a.Direction.RIGHT}},Wt={id:d.SelectAllOperation.id,binding:l.KeyCode.A|l.MetaKeys.CTRL_COMMAND,preconditions:o=>o.getContextValue(a.FOCUSING_UNIVER_EDITOR)&&(o.getContextValue(a.FOCUSING_DOC)||o.getContextValue(a.EDITOR_ACTIVATED))};var Gt=Object.defineProperty,kt=Object.getOwnPropertyDescriptor,Kt=(o,e,t,n)=>{for(var i=n>1?void 0:n?kt(e,t):e,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&Gt(e,t,i),i},$e=(o,e)=>(t,n)=>e(t,n,o);let fe=class{constructor(o,e,t){D(this,"_docContainer");D(this,"getComponent",o=>{if(this._docContainer=o,!o.getContentRef().current)throw new Error("container is not ready")});D(this,"changeLocale",o=>{this._localeService.setLocale(o)});this._config=o,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(o){if(this._docContainer)return o(this._docContainer)}getDocContainer(){return this._docContainer}};fe=Kt([$e(1,a.Inject(a.LocaleService)),$e(2,a.Inject(a.Injector))],fe);var Yt=Object.defineProperty,zt=Object.getOwnPropertyDescriptor,Xt=(o,e,t,n)=>{for(var i=n>1?void 0:n?zt(e,t):e,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&Yt(e,t,i),i},ee=(o,e)=>(t,n)=>e(t,n,o);let J=class extends a.RxDisposable{constructor(e,t,n,i,r){super();D(this,"_docContainerController");D(this,"changeLocale",e=>{this._localeService.setLocale(e)});this._localeService=t,this._injector=n,this._textSelectionRenderManager=i,this._layoutService=r,this._docContainerController=this._injector.createInstance(fe,e),this._registerContainer()}_registerContainer(){this._layoutService&&this.disposeWithMe(this._layoutService.registerContainerElement(this._textSelectionRenderManager.__getEditorContainer()))}getDocContainerController(){return this._docContainerController}};J=Xt([ee(1,a.Inject(a.LocaleService)),ee(2,a.Inject(a.Injector)),ee(3,C.ITextSelectionRenderManager),ee(4,a.Optional(l.ILayoutService))],J);const ce="UI_PLUGIN_DOCS",Ee=`${ce}_COLOR_PICKER_COMPONENT`,rt=`${ce}_FONT_FAMILY_COMPONENT`,st=`${ce}_FONT_FAMILY_ITEM_COMPONENT`,at=`${ce}_FONT_SIZE_COMPONENT`;var ct={exports:{}},le={};/**
|
|
1
|
+
"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);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const core=require("@univerjs/core"),ui=require("@univerjs/ui"),docs=require("@univerjs/docs"),engineRender=require("@univerjs/engine-render"),rxjs=require("rxjs"),require$$0=require("react"),design=require("@univerjs/design"),clsx=require("clsx");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 _a19,_b,_c;for(const node of nodes)if(node.nodeType===Node.TEXT_NODE){if(((_a19=node.nodeValue)==null?void 0:_a19.trim())==="")continue;let text=(_b=node.nodeValue)==null?void 0:_b.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=[...(_c=doc.customRanges)!=null?_c:[],{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 wordPastePlugin$1={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"}}]},PastePluginLark=wordPastePlugin$1;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 wordPastePlugin={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"}}]},PastePluginWord=wordPastePlugin,univerPastePlugin={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"}}]},PastePluginUniver=univerPastePlugin;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 _a19;if(withParagraphInfo&&((_a19=body.paragraphs)!=null&&_a19.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");var _a;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 _a19;const{segmentId,endOffset:activeEndOffset,style}=(_a19=this._textSelectionManagerService.getActiveRange())!=null?_a19:{},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 _a19,_b;let body=core.normalizeBody(_body);const unitId=(_a19=this._univerInstanceService.getCurrentUnitForType(core.UniverInstanceType.UNIVER_DOC))==null?void 0:_a19.getUnitId();if(!unitId)return!1;this._clipboardHooks.forEach(hook=>{hook.onBeforePaste&&(body=hook.onBeforePaste(body))}),body.customRanges=(_b=body.customRanges)==null?void 0:_b.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;var _a2;exports.DocBackScrollRenderController=(_a2=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 _a19;const docSkeletonManagerService=(_a19=this._renderManagerService.getRenderById(unitId))==null?void 0:_a19.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 _a19;const docObject=this._getDocObject(),docSkeletonManagerService=(_a19=this._renderManagerService.getRenderById(unitId))==null?void 0:_a19.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(_a2,"DocBackScrollRenderController"),_a2);exports.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)],exports.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"),_a3;let DocContainerUIController=(_a3=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(_a3,"DocContainerUIController"),_a3);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"),_a4;let AppUIController=(_a4=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(_a4,"AppUIController"),_a4);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 Zt=L,Jt=Symbol.for("react.element"),qt=Symbol.for("react.fragment"),Qt=Object.prototype.hasOwnProperty,en=Zt.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,tn={key:!0,ref:!0,__self:!0,__source:!0};function lt(o,e,t){var n,i={},r=null,s=null;t!==void 0&&(r=""+t),e.key!==void 0&&(r=""+e.key),e.ref!==void 0&&(s=e.ref);for(n in e)Qt.call(e,n)&&!tn.hasOwnProperty(n)&&(i[n]=e[n]);if(o&&o.defaultProps)for(n in e=o.defaultProps,e)i[n]===void 0&&(i[n]=e[n]);return{$$typeof:Jt,type:o,key:r,ref:s,props:i,_owner:en.current}}le.Fragment=qt;le.jsx=lt;le.jsxs=lt;ct.exports=le;var y=ct.exports;const nn="univer-doc-count-bar",on={docCountBar:nn},rn=[50,80,100,130,150,170,200,400],sn=[10,400];function an(){const o=a.useDependency(a.ICommandService),e=a.useDependency(a.IUniverInstanceService),t=L.useMemo(()=>e.getCurrentTypeOfUnit$(a.UniverInstanceType.UNIVER_DOC),[]),n=a.useObservable(t),i=L.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,s]=L.useState(()=>i());L.useEffect(()=>(s(i()),o.onCommandExecuted(h=>{if(h.id===d.SetDocZoomRatioOperation.id){const _=i();s(_)}}).dispose),[o,i]);function c(u){if(s(u),n==null)return;const h=u/100;o.executeCommand(d.SetDocZoomRatioOperation.id,{unitId:n.getUnitId(),zoomRatio:h})}return y.jsx(H.Slider,{min:sn[0],value:r,shortcuts:rn,onChange:c})}function cn(o){return y.jsx("section",{className:on.docCountBar,children:y.jsx(an,{})})}const ln="univer-doc-footer-container",dn={docFooterContainer:ln},un=()=>y.jsxs("div",{className:dn.docFooterContainer,children:[y.jsx("div",{}),y.jsx(cn,{})]}),He=18,je=200,ge=6,hn=4;function gn(o,e){let{radius:t,width:n,height:i}=e;t=t!=null?t:0,n=n!=null?n:30,i=i!=null?i:30;let r=0;r=Math.min(t,n/2,i/2),o.beginPath(),o.moveTo(0,0),o.lineTo(n,0),o.lineTo(n,i-r),o.arc(n-r,i-r,r,0,Math.PI/2,!1),o.lineTo(0,i),o.lineTo(0,0),o.closePath(),e.fill&&(o.save(),o.fillStyle=e.fill,e.fillRule==="evenodd"?o.fill("evenodd"):o.fill(),o.restore())}class se extends C.Shape{constructor(t,n){super(t,n);D(this,"color");D(this,"text");this.color=n==null?void 0:n.color,this.text=n==null?void 0:n.text}static drawWith(t,n){const{text:i,color:r}=n;t.save(),t.font="13px Source Han Sans CN";const s=t.measureText(i).width,c=Math.min(s+2*ge,je);gn(t,{height:He,width:c,radius:4,fill:r,evented:!1}),t.fillStyle="rgba(58, 96, 247, 1)";const u=ge,h=He-hn,_=je-2*ge;if(s>_){let m="",S=0;for(const g of i){const f=t.measureText(g).width;if(S+f<=_-t.measureText("...").width)m+=g,S+=f;else{m+="...";break}}t.fillText(m,u,h)}else t.fillText(i,u,h);t.restore()}_draw(t){se.drawWith(t,this)}}const dt="COMPONENT_DOC_HEADER_FOOTER_PANEL",pn="univer-panel",_n="univer-options-section",mn="univer-options-form-item",Sn="univer-options-input",fn="univer-options-margin-setting",U={panel:pn,optionsSection:_n,optionsFormItem:mn,optionsInput:Sn,optionsMarginSetting:fn},vn=o=>{const e=a.useDependency(a.LocaleService),t=a.useDependency(a.IUniverInstanceService),n=a.useDependency(C.IRenderManagerService),i=a.useDependency(a.ICommandService),r=a.useDependency(C.ITextSelectionRenderManager),s=a.useDependency(d.TextSelectionManagerService),{unitId:c}=o,[u,h]=L.useState({}),_=(g,f)=>{var x;h(F=>({...F,[f]:g?a.BooleanNumber.TRUE:a.BooleanNumber.FALSE}));const p=t.getUniverDocInstance(c),v=p==null?void 0:p.getSnapshot().documentStyle,I=(x=n.getRenderById(c))==null?void 0:x.with(d.DocSkeletonManagerService),O=I==null?void 0:I.getViewModel();if(v==null||O==null)return;const T=O.getEditArea();let M=!1;const b=r.getSegmentPage();let E=!1;if(f==="useFirstPageHeaderFooter"&&g===!0&&((T===C.DocumentEditArea.HEADER&&!v.firstPageHeaderId||T===C.DocumentEditArea.FOOTER&&!v.firstPageFooterId)&&(M=!0),M&&b===0&&(E=!0)),f==="evenAndOddHeaders"&&g===!0&&((T===C.DocumentEditArea.HEADER&&!v.evenPageHeaderId||T===C.DocumentEditArea.FOOTER&&!v.evenPageFooterId)&&(M=!0),M&&b%2===1&&(E=!0)),M){const N=a.Tools.generateRandomId(6);E&&r.setSegment(N),i.executeCommand(oe,{unitId:c,segmentId:N,headerFooterProps:{[f]:g?a.BooleanNumber.TRUE:a.BooleanNumber.FALSE}})}else i.executeCommand(oe,{unitId:c,headerFooterProps:{[f]:g?a.BooleanNumber.TRUE:a.BooleanNumber.FALSE}})},m=async(g,f)=>{h(p=>({...p,[f]:g})),await i.executeCommand(oe,{unitId:c,headerFooterProps:{[f]:g}}),r.removeAllTextRanges(),r.blur()},S=()=>{var M;const g=n.getRenderById(c);if(g==null)return;const{scene:f}=g,p=f.getTransformerByCreate(),v=g.with(d.DocSkeletonManagerService),I=v==null?void 0:v.getSkeleton(),O=v==null?void 0:v.getViewModel(),T=n.getRenderById(c);T==null||O==null||I==null||(s.replaceTextRanges([]),p.clearSelectedObjects(),r.setSegment(""),r.setSegmentPage(-1),O.setEditArea(C.DocumentEditArea.BODY),I.calculate(),(M=T.mainComponent)==null||M.makeDirty(!0))};return L.useEffect(()=>{const g=t.getUniverDocInstance(c),f=g==null?void 0:g.getSnapshot().documentStyle;if(f){const{marginHeader:p,marginFooter:v,useFirstPageHeaderFooter:I,evenAndOddHeaders:O}=f;h({marginHeader:p,marginFooter:v,useFirstPageHeaderFooter:I,evenAndOddHeaders:O})}},[c]),y.jsxs("div",{className:U.options,children:[y.jsxs("div",{className:U.optionsSection,children:[y.jsx("div",{className:U.optionsFormItem,children:y.jsx(H.Checkbox,{checked:u.useFirstPageHeaderFooter===a.BooleanNumber.TRUE,onChange:g=>{_(g,"useFirstPageHeaderFooter")},children:e.t("headerFooter.firstPageCheckBox")})}),y.jsx("div",{className:U.optionsFormItem,children:y.jsx(H.Checkbox,{checked:u.evenAndOddHeaders===a.BooleanNumber.TRUE,onChange:g=>{_(g,"evenAndOddHeaders")},children:e.t("headerFooter.oddEvenCheckBox")})})]}),y.jsxs("div",{className:St(U.optionsSection,U.optionsMarginSetting),children:[y.jsxs("div",{className:U.optionsMarginItem,children:[y.jsx("span",{children:e.t("headerFooter.headerTopMargin")}),y.jsx(H.InputNumber,{min:0,max:200,precision:1,value:u.marginHeader,onChange:g=>{m(g,"marginHeader")},className:U.optionsInput})]}),y.jsxs("div",{className:U.optionsMarginItem,children:[y.jsx("span",{children:e.t("headerFooter.footerBottomMargin")}),y.jsx(H.InputNumber,{min:0,max:200,precision:1,value:u.marginFooter,onChange:g=>{m(g,"marginFooter")},className:U.optionsInput})]})]}),y.jsx("div",{className:U.optionsSection,children:y.jsx(H.Button,{onClick:S,children:e.t("headerFooter.closeHeaderFooter")})})]})},Cn=()=>{var h;const o=a.useDependency(a.LocaleService),e=a.useDependency(C.IRenderManagerService),i=a.useDependency(a.IUniverInstanceService).getCurrentUniverDocInstance().getUnitId(),s=((h=e.getRenderById(i))==null?void 0:h.with(d.DocSkeletonManagerService)).getViewModel(),[c,u]=L.useState(!0);return L.useEffect(()=>{const _=s.getEditArea();u(_!==C.DocumentEditArea.BODY);const m=s.editAreaChange$.subscribe(S=>{S!=null&&u(S!==C.DocumentEditArea.BODY)});return()=>{m.unsubscribe()}},[]),y.jsx("div",{className:U.panel,children:c?y.jsx(vn,{unitId:i}):y.jsx("div",{className:U.panelDisableText,children:o.t("headerFooter.disableText")})})},ut={id:"sidebar.operation.doc-header-footer-panel",type:a.CommandType.COMMAND,handler:async(o,e)=>{const t=o.get(l.ISidebarService),n=o.get(a.LocaleService);switch(e.value){case"open":t.open({header:{title:n.t("headerFooter.panel")},children:{label:dt},onClose:()=>{},width:400});break;case"close":default:t.close();break}return!0}};var In=Object.defineProperty,On=Object.getOwnPropertyDescriptor,Tn=(o,e,t,n)=>{for(var i=n>1?void 0:n?On(e,t):e,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&In(e,t,i),i},B=(o,e)=>(t,n)=>e(t,n,o);const Ve="rgba(58, 96, 247, 1)",We="rgba(58, 96, 247, 0.08)";var A=(o=>(o[o.FIRST_PAGE_HEADER=0]="FIRST_PAGE_HEADER",o[o.FIRST_PAGE_FOOTER=1]="FIRST_PAGE_FOOTER",o[o.DEFAULT_HEADER=2]="DEFAULT_HEADER",o[o.DEFAULT_FOOTER=3]="DEFAULT_FOOTER",o[o.EVEN_PAGE_HEADER=4]="EVEN_PAGE_HEADER",o[o.EVEN_PAGE_FOOTER=5]="EVEN_PAGE_FOOTER",o))(A||{});function Rn(o,e,t){const{documentStyle:n}=o.getDataModel().getSnapshot(),{defaultHeaderId:i,defaultFooterId:r,evenPageHeaderId:s,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===a.BooleanNumber.TRUE&&!u?{createType:0,headerFooterId:null}:_===a.BooleanNumber.TRUE&&t%2===0&&!s?{createType:4,headerFooterId:null}:i?{createType:null,headerFooterId:i}:{createType:2,headerFooterId:null};case C.DocumentEditArea.FOOTER:return m===a.BooleanNumber.TRUE&&!h?{createType:1,headerFooterId:null}:_===a.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 a.Disposable{constructor(e,t,n,i,r,s,c,u,h){super();D(this,"_loadedMap",new WeakSet);this._context=e,this._commandService=t,this._editorService=n,this._instanceSrv=i,this._renderManagerService=r,this._docSkeletonManagerService=s,this._textSelectionRenderManager=c,this._localeService=u,this._componentManager=h,this._initialize()}_initialize(){this._context.unit.getSnapshot().documentStyle.documentFlavor===a.DocumentFlavor.TRADITIONAL&&(this._init(),this._drawHeaderFooterLabel(),this._registerCommands(),this._initCustomComponents())}_registerCommands(){[ke,ht,ut].forEach(e=>this.disposeWithMe(this._commandService.registerCommand(e)))}_initCustomComponents(){const e=this._componentManager;this.disposeWithMe(e.register(dt,Cn))}_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 i=>{if(this._isEditorReadOnly(e))return;const{offsetX:r,offsetY:s}=i,{pageLayoutType:c=C.PageLayoutType.VERTICAL,pageMarginLeft:u,pageMarginTop:h}=n.getOffsetConfig(),_=this._getTransformCoordForDocumentOffset(r,s);if(_==null)return;const m=this._docSkeletonManagerService.getViewModel(),S=this._docSkeletonManagerService.getSkeleton(),g=m.getEditArea(),{editArea:f,pageNumber:p}=S.findEditAreaByCoord(_,c,u,h);if(g===f)return;m.setEditArea(f);const{createType:v,headerFooterId:I}=Rn(m,f,p);if(f===C.DocumentEditArea.BODY)this._textSelectionRenderManager.setSegment(""),this._textSelectionRenderManager.setSegmentPage(-1),this._textSelectionRenderManager.setCursorManually(r,s);else if(v!=null){const T=a.Tools.generateRandomId(6);this._textSelectionRenderManager.setSegment(T),this._textSelectionRenderManager.setSegmentPage(p),await this._commandService.executeCommand(ke.id,{unitId:e,createType:v,segmentId:T})}else I!=null&&(this._textSelectionRenderManager.setSegment(I),this._textSelectionRenderManager.setSegmentPage(p),this._textSelectionRenderManager.setCursorManually(r,s))}))}_getTransformCoordForDocumentOffset(e,t){const n=d.neoGetDocObject(this._context),{document:i,scene:r}=n,{documentTransform:s}=i.getOffsetConfig(),c=r.getViewports()[0];if(c==null)return;const u=c.transformVector2SceneCoord(C.Vector2.FromArray([e,t]));return s.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:i}=n,r=i;this.disposeWithMe(a.toDisposable(r.pageRender$.subscribe(s=>{if(this._editorService.isEditor(t))return;const h=this._docSkeletonManagerService.getViewModel().getEditArea()===C.DocumentEditArea.BODY,{page:_,pageLeft:m,pageTop:S,ctx:g}=s,{pageWidth:f,pageHeight:p,marginTop:v,marginBottom:I}=_;if(g.save(),g.translate(m-.5,S-.5),h?(C.Rect.drawWith(g,{left:0,top:0,width:f,height:v,fill:"rgba(255, 255, 255, 0.5)"}),g.save(),g.translate(0,p-I),C.Rect.drawWith(g,{left:0,top:0,width:f,height:I,fill:"rgba(255, 255, 255, 0.5)"}),g.restore()):(g.save(),g.translate(0,v),C.Rect.drawWith(g,{left:0,top:v,width:f,height:p-v-I,fill:"rgba(255, 255, 255, 0.5)"}),g.restore()),!h){const O={dataArray:[{command:"M",points:[0,v]},{command:"L",points:[f,v]}],strokeWidth:1,stroke:Ve},T={dataArray:[{command:"M",points:[0,p-I]},{command:"L",points:[f,p-I]}],strokeWidth:1,stroke:Ve};C.Path.drawWith(g,O),C.Path.drawWith(g,T),g.translate(0,v+1),se.drawWith(g,{text:e.t("headerFooter.header"),color:We}),g.translate(0,p-v-I),se.drawWith(g,{text:e.t("headerFooter.footer"),color:We})}g.restore()})))})}_isEditorReadOnly(e){const t=this._editorService.getEditor(e);return t?t.isReadOnly():!1}_getDocDataModel(){return this._context.unit}};ve=Tn([B(1,a.ICommandService),B(2,l.IEditorService),B(3,a.IUniverInstanceService),B(4,C.IRenderManagerService),B(5,a.Inject(d.DocSkeletonManagerService)),B(6,C.ITextSelectionRenderManager),B(7,a.Inject(a.LocaleService)),B(8,a.Inject(l.ComponentManager))],ve);function Ge(){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 pe(o,e,t,n){const i=a.JSONX.getInstance(),r=6,s=o!=null?o:a.Tools.generateRandomId(r),c=e===A.DEFAULT_HEADER||e===A.FIRST_PAGE_HEADER||e===A.EVEN_PAGE_HEADER,u=i.insertOp([c?"headers":"footers",s],{[c?"headerId":"footerId"]:s,body:Ge()});n.push(u);const h=a.Tools.generateRandomId(r),_=i.insertOp([c?"footers":"headers",h],{[c?"footers":"headers"]:h,body:Ge()});n.push(_);let m="defaultHeaderId",S="defaultFooterId";switch(e){case A.DEFAULT_HEADER:m="defaultHeaderId",S="defaultFooterId";break;case A.DEFAULT_FOOTER:m="defaultFooterId",S="defaultHeaderId";break;case A.FIRST_PAGE_HEADER:m="firstPageHeaderId",S="firstPageFooterId";break;case A.FIRST_PAGE_FOOTER:m="firstPageFooterId",S="firstPageHeaderId";break;case A.EVEN_PAGE_HEADER:m="evenPageHeaderId",S="evenPageFooterId";break;case A.EVEN_PAGE_FOOTER:m="evenPageFooterId",S="evenPageHeaderId";break;default:throw new Error(`Unknown header footer type: ${e}`)}for(const[g,f]of[[m,s],[S,h]])if(t[g]!=null){const p=i.replaceOp(["documentStyle",g],t[g],f);n.push(p)}else{const p=i.insertOp(["documentStyle",g],f);n.push(p)}return n}const oe="doc.command.core-header-footer",ke={id:oe,type:a.CommandType.COMMAND,handler:async(o,e)=>{var M;const t=o.get(a.ICommandService),n=o.get(a.IUniverInstanceService),i=o.get(C.IRenderManagerService),{unitId:r,segmentId:s,createType:c,headerFooterProps:u}=e,h=(M=i.getRenderById(r))==null?void 0:M.with(d.DocSkeletonManagerService),_=n.getUniverDocInstance(r),m=h==null?void 0:h.getViewModel();if(_==null||m==null)return!1;const S=m.getEditArea(),{documentStyle:g}=_.getSnapshot(),f=(u==null?void 0:u.marginFooter)!=null||(u==null?void 0:u.marginHeader)!=null,p=[{startOffset:0,endOffset:0,collapsed:!0}],v={id:d.RichTextEditingMutation.id,params:{unitId:r,actions:[],textRanges:p,debounce:!0}};f&&(v.params.noNeedSetTextRange=!0);const I=a.JSONX.getInstance(),O=[];return c!=null&&pe(s,c,g,O),u!=null&&Object.keys(u).forEach(b=>{const E=u[b],x=g[b];if(E===x)return;let F;if(x===void 0?F=I.insertOp(["documentStyle",b],E):F=I.replaceOp(["documentStyle",b],x,E),O.push(F),b==="useFirstPageHeaderFooter"&&E===a.BooleanNumber.TRUE&&!g.firstPageHeaderId){const N=S===C.DocumentEditArea.HEADER?A.FIRST_PAGE_HEADER:A.FIRST_PAGE_FOOTER;pe(s,N,g,O)}else if(b==="evenAndOddHeaders"&&E===a.BooleanNumber.TRUE&&!g.evenPageHeaderId){const N=S===C.DocumentEditArea.HEADER?A.EVEN_PAGE_HEADER:A.EVEN_PAGE_FOOTER;pe(s,N,g,O)}}),O.length===0?!1:(v.params.actions=O.reduce((b,E)=>a.JSONX.compose(b,E),null),!!t.syncExecuteCommand(v.id,v.params))}},ht={id:"doc.command.open-header-footer-panel",type:a.CommandType.COMMAND,handler:async(o,e)=>o.get(a.ICommandService).executeCommand(ut.id,{value:"open"})};function Mn(o){const e=o.get(a.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 R.Observable(t=>{const n=e.onCommandExecuted(i=>{var s;const r=i.id;if(r===d.SetTextSelectionsOperation.id||r===d.SetInlineFormatCommand.id){const c=w(o);if(c==null)return;const u=(s=c.ts)==null?void 0:s.bl;t.next(u===a.BooleanNumber.TRUE)}});return t.next(!1),n.dispose}),hidden$:l.getMenuHiddenObservable(o,a.UniverInstanceType.UNIVER_DOC)}}function En(o){const e=o.get(a.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 R.Observable(t=>{const n=e.onCommandExecuted(i=>{var s;const r=i.id;if(r===d.SetTextSelectionsOperation.id||r===d.SetInlineFormatCommand.id){const c=w(o);if(c==null)return;const u=(s=c.ts)==null?void 0:s.it;t.next(u===a.BooleanNumber.TRUE)}});return t.next(!1),n.dispose}),hidden$:l.getMenuHiddenObservable(o,a.UniverInstanceType.UNIVER_DOC)}}function bn(o){const e=o.get(a.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 R.Observable(t=>{const n=e.onCommandExecuted(i=>{var s;const r=i.id;if(r===d.SetTextSelectionsOperation.id||r===d.SetInlineFormatCommand.id){const c=w(o);if(c==null)return;const u=(s=c.ts)==null?void 0:s.ul;t.next((u==null?void 0:u.s)===a.BooleanNumber.TRUE)}});return t.next(!1),n.dispose}),hidden$:l.getMenuHiddenObservable(o,a.UniverInstanceType.UNIVER_DOC)}}function Dn(o){const e=o.get(a.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 R.Observable(t=>{const n=e.onCommandExecuted(i=>{var s;const r=i.id;if(r===d.SetTextSelectionsOperation.id||r===d.SetInlineFormatCommand.id){const c=w(o);if(c==null)return;const u=(s=c.ts)==null?void 0:s.st;t.next((u==null?void 0:u.s)===a.BooleanNumber.TRUE)}});return t.next(!1),n.dispose}),hidden$:l.getMenuHiddenObservable(o,a.UniverInstanceType.UNIVER_DOC)}}function yn(o){const e=o.get(a.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 R.Observable(t=>{const n=e.onCommandExecuted(i=>{var s;const r=i.id;if(r===d.SetTextSelectionsOperation.id||r===d.SetInlineFormatCommand.id){const c=w(o);if(c==null)return;const u=(s=c.ts)==null?void 0:s.va;t.next(u===a.BaselineOffset.SUBSCRIPT)}});return t.next(!1),n.dispose}),hidden$:l.getMenuHiddenObservable(o,a.UniverInstanceType.UNIVER_DOC)}}function Pn(o){const e=o.get(a.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 R.Observable(t=>{const n=e.onCommandExecuted(i=>{var s;const r=i.id;if(r===d.SetTextSelectionsOperation.id||r===d.SetInlineFormatCommand.id){const c=w(o);if(c==null)return;const u=(s=c.ts)==null?void 0:s.va;t.next(u===a.BaselineOffset.SUPERSCRIPT)}});return t.next(!1),n.dispose}),hidden$:l.getMenuHiddenObservable(o,a.UniverInstanceType.UNIVER_DOC)}}function xn(o){const e=o.get(a.ICommandService);return{id:d.SetInlineFormatFontFamilyCommand.id,tooltip:"toolbar.font",group:l.MenuGroup.TOOLBAR_FORMAT,type:l.MenuItemType.SELECTOR,label:rt,positions:[l.MenuPosition.TOOLBAR_START],selections:l.FONT_FAMILY_LIST.map(t=>({label:{name:st,hoverable:!0},value:t.value})),value$:new R.Observable(t=>{const n=l.FONT_FAMILY_LIST[0].value,i=e.onCommandExecuted(r=>{var c;const s=r.id;if(s===d.SetTextSelectionsOperation.id||s===d.SetInlineFormatFontFamilyCommand.id){const u=w(o);if(u==null)return;const h=(c=u.ts)==null?void 0:c.ff;t.next(h!=null?h:n)}});return t.next(n),i.dispose}),hidden$:l.getMenuHiddenObservable(o,a.UniverInstanceType.UNIVER_DOC)}}function An(o){const e=o.get(a.ICommandService);return{id:d.SetInlineFormatFontSizeCommand.id,group:l.MenuGroup.TOOLBAR_FORMAT,type:l.MenuItemType.SELECTOR,tooltip:"toolbar.fontSize",label:{name:at,props:{min:1,max:400}},positions:[l.MenuPosition.TOOLBAR_START],selections:l.FONT_SIZE_LIST,value$:new R.Observable(t=>{const i=e.onCommandExecuted(r=>{var c;const s=r.id;if(s===d.SetTextSelectionsOperation.id||s===d.SetInlineFormatFontSizeCommand.id){const u=w(o);if(u==null)return;const h=(c=u.ts)==null?void 0:c.fs;t.next(h!=null?h:14)}});return t.next(14),i.dispose}),hidden$:l.getMenuHiddenObservable(o,a.UniverInstanceType.UNIVER_DOC)}}function Nn(o){const e=o.get(a.ICommandService),t=o.get(a.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:Ee,hoverable:!1}}],value$:new R.Observable(n=>{const i=t.getCurrentTheme().textColor,r=e.onCommandExecuted(s=>{if(s.id===d.SetInlineFormatTextColorCommand.id){const c=s.params.value;n.next(c!=null?c:i)}});return n.next(i),r.dispose}),hidden$:l.getMenuHiddenObservable(o,a.UniverInstanceType.UNIVER_DOC)}}function Un(o){return{id:ht.id,group:l.MenuGroup.TOOLBAR_OTHERS,type:l.MenuItemType.BUTTON,icon:"FreezeRowSingle",tooltip:"toolbar.headerFooter",positions:[l.MenuPosition.TOOLBAR_START],hidden$:R.combineLatest(l.getMenuHiddenObservable(o,a.UniverInstanceType.UNIVER_DOC),l.getHeaderFooterMenuHiddenObservable(o),(e,t)=>e||t)}}function Fn(o){const e=o.get(a.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 R.Observable(t=>{const n=e.onCommandExecuted(i=>{var s;const r=i.id;if(r===d.SetTextSelectionsOperation.id||r===d.AlignOperationCommand.id){const c=de(o);if(c==null)return;const u=(s=c.paragraphStyle)==null?void 0:s.horizontalAlign;t.next(u===a.HorizontalAlign.LEFT)}});return t.next(!1),n.dispose}),hidden$:l.getMenuHiddenObservable(o,a.UniverInstanceType.UNIVER_DOC)}}function Ln(o){const e=o.get(a.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 R.Observable(t=>{const n=e.onCommandExecuted(i=>{var s;const r=i.id;if(r===d.SetTextSelectionsOperation.id||r===d.AlignOperationCommand.id){const c=de(o);if(c==null)return;const u=(s=c.paragraphStyle)==null?void 0:s.horizontalAlign;t.next(u===a.HorizontalAlign.CENTER)}});return t.next(!1),n.dispose}),hidden$:l.getMenuHiddenObservable(o,a.UniverInstanceType.UNIVER_DOC)}}function Bn(o){const e=o.get(a.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 R.Observable(t=>{const n=e.onCommandExecuted(i=>{var s;const r=i.id;if(r===d.SetTextSelectionsOperation.id||r===d.AlignOperationCommand.id){const c=de(o);if(c==null)return;const u=(s=c.paragraphStyle)==null?void 0:s.horizontalAlign;t.next(u===a.HorizontalAlign.RIGHT)}});return t.next(!1),n.dispose}),hidden$:l.getMenuHiddenObservable(o,a.UniverInstanceType.UNIVER_DOC)}}function wn(o){const e=o.get(a.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 R.Observable(t=>{const n=e.onCommandExecuted(i=>{var s;const r=i.id;if(r===d.SetTextSelectionsOperation.id||r===d.AlignOperationCommand.id){const c=de(o);if(c==null)return;const u=(s=c.paragraphStyle)==null?void 0:s.horizontalAlign;t.next(u===a.HorizontalAlign.JUSTIFIED)}});return t.next(!1),n.dispose}),hidden$:l.getMenuHiddenObservable(o,a.UniverInstanceType.UNIVER_DOC)}}function $n(o){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(o,a.UniverInstanceType.UNIVER_DOC)}}function Hn(o){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(o,a.UniverInstanceType.UNIVER_DOC)}}function jn(o){return{id:d.ResetInlineFormatTextBackgroundColorCommand.id,type:l.MenuItemType.BUTTON,title:"toolbar.resetColor",icon:"NoColor",positions:d.SetInlineFormatTextBackgroundColorCommand.id}}function Vn(o){const e=o.get(a.ICommandService),t=o.get(a.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:Ee,hoverable:!1}}],value$:new R.Observable(n=>{const i=t.getCurrentTheme().primaryColor,r=e.onCommandExecuted(s=>{if(s.id===d.SetInlineFormatTextBackgroundColorCommand.id){const c=s.params.value;n.next(c!=null?c:i)}});return n.next(i),r.dispose}),hidden$:l.getMenuHiddenObservable(o,a.UniverInstanceType.UNIVER_DOC)}}function w(o){var h;const e=o.get(a.IUniverInstanceService),t=o.get(d.TextSelectionManagerService),n=e.getCurrentUniverDocInstance(),i=t.getActiveRange();if(n==null||i==null)return;const{startOffset:r,segmentId:s}=i,c=(h=n.getSelfOrHeaderFooterModel(s).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 de(o){var h;const e=o.get(a.IUniverInstanceService),t=o.get(d.TextSelectionManagerService),n=e.getCurrentUniverDocInstance(),i=t.getActiveRange();if(n==null||i==null)return;const{startOffset:r,segmentId:s}=i,c=(h=n.getSelfOrHeaderFooterModel(s).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 ue(o){return o.getContextValue(a.FOCUSING_DOC)||o.getContextValue(a.EDITOR_ACTIVATED)}const be=999,De={id:l.CopyCommand.id,name:"doc.command.copy",type:a.CommandType.COMMAND,multi:!0,priority:be,preconditions:ue,handler:async o=>o.get(K).copy()},ye={id:l.CutCommand.id,name:"doc.command.cut",type:a.CommandType.COMMAND,multi:!0,priority:be,preconditions:ue,handler:async o=>o.get(K).cut()},Pe={id:l.PasteCommand.id,name:"doc.command.paste",type:a.CommandType.COMMAND,multi:!0,priority:be,preconditions:ue,handler:async o=>{const e=o.get(K),n=await o.get(l.IClipboardInterfaceService).read();return n.length===0?!1:e.paste(n)}},xe=o=>{const e=o.get(d.TextSelectionManagerService);return new R.Observable(t=>{const n=e.textSelection$.subscribe(i=>{const r=e.getActiveRange();r&&!r.collapsed?t.next(!1):t.next(!0)});return()=>n.unsubscribe()})},Wn=o=>({id:De.id,group:l.MenuGroup.CONTEXT_MENU_FORMAT,type:l.MenuItemType.BUTTON,icon:"Copy",title:"rightClick.copy",positions:[l.MenuPosition.CONTEXT_MENU],disabled$:xe(o),hidden$:l.getMenuHiddenObservable(o,a.UniverInstanceType.UNIVER_DOC)}),Gn=o=>({id:ye.id,group:l.MenuGroup.CONTEXT_MENU_FORMAT,type:l.MenuItemType.BUTTON,icon:"Copy",title:"rightClick.cut",positions:[l.MenuPosition.CONTEXT_MENU],disabled$:xe(o),hidden$:l.getMenuHiddenObservable(o,a.UniverInstanceType.UNIVER_DOC)}),kn=o=>({id:Pe.id,group:l.MenuGroup.CONTEXT_MENU_FORMAT,type:l.MenuItemType.BUTTON,icon:"PasteSpecial",title:"rightClick.paste",positions:[l.MenuPosition.CONTEXT_MENU],hidden$:l.getMenuHiddenObservable(o,a.UniverInstanceType.UNIVER_DOC)}),Kn=o=>({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$:xe(o),hidden$:l.getMenuHiddenObservable(o,a.UniverInstanceType.UNIVER_DOC)}),Yn={id:d.SetInlineFormatBoldCommand.id,binding:l.KeyCode.B|l.MetaKeys.CTRL_COMMAND,preconditions:P},zn={id:d.SetInlineFormatItalicCommand.id,binding:l.KeyCode.I|l.MetaKeys.CTRL_COMMAND,preconditions:P},Xn={id:d.SetInlineFormatUnderlineCommand.id,binding:l.KeyCode.U|l.MetaKeys.CTRL_COMMAND,preconditions:P},Zn={id:d.SetInlineFormatStrikethroughCommand.id,binding:l.KeyCode.X|l.MetaKeys.SHIFT|l.MetaKeys.CTRL_COMMAND,preconditions:P},Jn={id:d.SetInlineFormatSubscriptCommand.id,binding:l.KeyCode.COMMA|l.MetaKeys.CTRL_COMMAND,preconditions:P},qn={id:d.SetInlineFormatSuperscriptCommand.id,binding:l.KeyCode.PERIOD|l.MetaKeys.CTRL_COMMAND,preconditions:P},Qn={id:d.AlignLeftCommand.id,binding:l.KeyCode.L|l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT,preconditions:P},eo={id:d.AlignRightCommand.id,binding:l.KeyCode.R|l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT,preconditions:P},to={id:d.AlignCenterCommand.id,binding:l.KeyCode.E|l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT,preconditions:P},no={id:d.AlignJustifyCommand.id,binding:l.KeyCode.J|l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT,preconditions:P},oo={id:d.OrderListCommand.id,binding:l.KeyCode.Digit7|l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT,preconditions:P},io={id:d.BulletListCommand.id,binding:l.KeyCode.Digit8|l.MetaKeys.CTRL_COMMAND|l.MetaKeys.SHIFT,preconditions:P};var ro=Object.defineProperty,so=Object.getOwnPropertyDescriptor,ao=(o,e,t,n)=>{for(var i=n>1?void 0:n?so(e,t):e,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&ro(e,t,i),i},$=(o,e)=>(t,n)=>e(t,n,o);let q=class extends a.Disposable{constructor(o,e,t,n,i,r,s,c){super(),this._config=o,this._injector=e,this._componentManager=t,this._layoutService=n,this._menuService=i,this._uiPartsService=r,this._univerInstanceService=s,this._shortcutService=c,this._init()}_initCustomComponents(){const o=this._componentManager;this.disposeWithMe(o.register(Ee,H.ColorPicker)),this.disposeWithMe(o.register(rt,l.FontFamily)),this.disposeWithMe(o.register(st,l.FontFamilyItem)),this.disposeWithMe(o.register(at,l.FontSize))}_initUiParts(){var e,t;const o=this._univerInstanceService.getCurrentUnitForType(a.UniverInstanceType.UNIVER_SHEET);(t=(e=this._config.layout)==null?void 0:e.docContainerConfig)!=null&&t.footer&&!o&&this.disposeWithMe(this._uiPartsService.registerComponent(l.BuiltInUIPart.FOOTER,()=>a.connectInjector(un,this._injector)))}_initMenus(){const{menu:o={}}=this._config;[Mn,En,bn,Dn,yn,Pn,An,xn,Nn,Un,Fn,Ln,Bn,wn,$n,Hn,jn,Vn].forEach(e=>{this.disposeWithMe(this._menuService.addMenuItem(this._injector.invoke(e),o))}),[Wn,Gn,kn,Kn].forEach(e=>{try{this.disposeWithMe(this._menuService.addMenuItem(this._injector.invoke(e),o))}catch{}})}_initShortCut(){[Yn,zn,Xn,Zn,Jn,qn,to,no,eo,Qn,oo,io].forEach(o=>{this.disposeWithMe(this._shortcutService.registerShortcut(o))})}_init(){this._initCustomComponents(),this._initMenus(),this._initFocusHandler(),this._initUiParts(),this._initShortCut()}_initFocusHandler(){this.disposeWithMe(this._layoutService.registerFocusHandler(a.UniverInstanceType.UNIVER_DOC,()=>{this._injector.get(C.ITextSelectionRenderManager).focus()}))}};q=ao([a.OnLifecycle(a.LifecycleStages.Rendered,q),$(1,a.Inject(a.Injector)),$(2,a.Inject(l.ComponentManager)),$(3,l.ILayoutService),$(4,l.IMenuService),$(5,l.IUIPartsService),$(6,a.IUniverInstanceService),$(7,l.IShortcutService)],q);const co={id:d.BreakLineCommand.id,preconditions:ft,binding:l.KeyCode.ENTER},lo={id:d.DeleteLeftCommand.id,preconditions:P,binding:l.KeyCode.BACKSPACE},uo={id:d.DeleteRightCommand.id,preconditions:P,binding:l.KeyCode.DELETE};var ho=Object.defineProperty,go=Object.getOwnPropertyDescriptor,po=(o,e,t,n)=>{for(var i=n>1?void 0:n?go(e,t):e,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&ho(e,t,i),i},z=(o,e)=>(t,n)=>e(t,n,o);let ie=class extends a.RxDisposable{constructor(o,e,t,n,i){super(),this._commandService=o,this._clipboardInterfaceService=e,this._docClipboardService=t,this._textSelectionRenderManager=n,this._contextService=i,this._init()}_init(){[De,ye,Pe].forEach(o=>this.disposeWithMe(this._commandService.registerMultipleCommand(o))),[d.InnerPasteCommand,d.CutContentCommand].forEach(o=>this.disposeWithMe(this._commandService.registerCommand(o))),this._initLegacyPasteCommand()}_initLegacyPasteCommand(){var o;(o=this._textSelectionRenderManager)==null||o.onPaste$.pipe(R.takeUntil(this.dispose$)).subscribe(e=>{var r,s;if(!ue(this._contextService))return;e.event.preventDefault();const t=e.event,n=(r=t.clipboardData)==null?void 0:r.getData("text/html"),i=(s=t.clipboardData)==null?void 0:s.getData("text/plain");this._docClipboardService.legacyPaste(n,i)})}};ie=po([a.OnLifecycle(a.LifecycleStages.Rendered,ie),z(0,a.ICommandService),z(1,l.IClipboardInterfaceService),z(2,K),z(3,C.ITextSelectionRenderManager),z(4,a.IContextService)],ie);var _o=Object.defineProperty,mo=Object.getOwnPropertyDescriptor,So=(o,e,t,n)=>{for(var i=n>1?void 0:n?mo(e,t):e,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&_o(e,t,i),i},X=(o,e)=>(t,n)=>e(t,n,o);let re=class extends a.Disposable{constructor(e,t,n,i,r){super();D(this,"_initialEditors",new Set);this._univerInstanceService=e,this._editorService=t,this._commandService=n,this._textSelectionRenderManager=i,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 T,M,b;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 i=(T=this._renderManagerService.getRenderById(n.getUnitId()))==null?void 0:T.with(d.DocSkeletonManagerService).getSkeleton();if(t==null||t.render==null||i==null||n==null)return;i.calculate();const{marginTop:r=0,marginBottom:s=0,marginLeft:c=0,marginRight:u=0}=n.getSnapshot().documentStyle,{scene:h,mainComponent:_}=t.render;let{actualHeight:m,actualWidth:S}=i.getActualSize();m+=r+s,S+=c+u;const{width:g,height:f}=t.getBoundingClientRect(),p=h.getViewport(d.VIEWPORT_KEY.VIEW_MAIN);let v=p==null?void 0:p.getScrollBar();const I=Math.max(S,g),O=Math.max(m,f);h.transformByState({width:I,height:O}),_==null||_.resize(I,O),t.isSingle()?S>g?v==null?p&&new C.ScrollBar(p,{barSize:8,enableVertical:!1}):p==null||p.resetCanvasSizeAndUpdateScroll():(v=null,p==null||p.scrollToBarPos({x:0,y:0}),(b=p==null?void 0:p.getScrollBar())==null||b.dispose()):m>f?v==null?p&&new C.ScrollBar(p,{enableHorizontal:!1,barSize:8}):p==null||p.resetCanvasSizeAndUpdateScroll():(v=null,p==null||p.scrollToBarPos({x:0,y:0}),(M=p==null?void 0:p.getScrollBar())==null||M.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 i;const e=(i=this._univerInstanceService.getCurrentUniverDocInstance())==null?void 0:i.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(R.fromEvent(window,"mousedown").subscribe(n=>{const r=n.target.classList[0]||"";if(a.checkForSubstrings(r,e)){this._editorService.changeSpreadsheetFocusState(!0),n.stopPropagation();return}this._editorService.changeSpreadsheetFocusState(!1)})),this._univerInstanceService.getAllUnitsForType(a.UniverInstanceType.UNIVER_SHEET).forEach(n=>{const i=n.getUnitId(),r=this._renderManagerService.getRenderById(i),s=r==null?void 0:r.engine.getCanvas().getCanvasEle();s!=null&&R.fromEvent(s,"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:i}=n;if(this._editorService.isSheetEditor(i))return;this._resize(i),this._valueChange()}}))}};re=So([a.OnLifecycle(a.LifecycleStages.Rendered,re),X(0,a.IUniverInstanceService),X(1,l.IEditorService),X(2,a.ICommandService),X(3,C.ITextSelectionRenderManager),X(4,C.IRenderManagerService)],re);var fo=Object.defineProperty,vo=Object.getOwnPropertyDescriptor,Co=(o,e,t,n)=>{for(var i=n>1?void 0:n?vo(e,t):e,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&fo(e,t,i),i},Z=(o,e)=>(t,n)=>e(t,n,o);exports.DocRenderController=class extends a.RxDisposable{constructor(e,t,n,i,r,s){super(),this._context=e,this._commandService=t,this._docSkeletonManagerService=n,this._configService=i,this._editorService=r,this._renderManagerService=s,this._addNewRender(),this._initRenderRefresh(),this._initCommandListener()}reRender(e){var r,s;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)){(s=this._context.mainComponent)==null||s.makeDirty();return}this._recalculateSizeBySkeleton(n)}}_addNewRender(){const{scene:e,engine:t,unit:n}=this._context,i=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 i.onMouseWheel(h,u)}),this._configService.getConfig("hasScroll")!==!1&&new C.ScrollBar(i),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,i={pageMarginLeft:t.documentStyle.marginLeft||0,pageMarginTop:t.documentStyle.marginTop||0},r=new C.Documents(d.DOCS_VIEW_KEY.MAIN,void 0,i);r.zIndex=d.DOCS_COMPONENT_DEFAULT_Z_INDEX;const s=new C.DocBackground(d.DOCS_VIEW_KEY.BACKGROUND,void 0,i);s.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,s),e.addObjects([r],d.DOCS_COMPONENT_MAIN_LAYER_INDEX),e.addObjects([s],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(R.takeUntil(this.dispose$)).subscribe(e=>{this._create(e)})}_create(e){if(!e)return;const{mainComponent:t,components:n}=this._context,i=t,r=n.get(d.DOCS_VIEW_KEY.BACKGROUND);i.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:i}=n;this.reRender(i)}}))}_recalculateSizeBySkeleton(e){var m;const{mainComponent:t,scene:n,unitId:i,components:r}=this._context,s=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,g=u.length;S<g;S++){const f=u[S],{pageWidth:p,pageHeight:v}=f;s.pageLayoutType===C.PageLayoutType.VERTICAL?(_+=v,_+=s.pageMarginTop,S===g-1&&(_+=s.pageMarginTop),h=Math.max(h,p)):s.pageLayoutType===C.PageLayoutType.HORIZONTAL&&(h+=p,S!==g-1&&(h+=s.pageMarginLeft),_=Math.max(_,v))}s.resize(h,_),c.resize(h,_),this._editorService.isEditor(i)||n.resize(h,_)}};exports.DocRenderController=Co([Z(1,a.ICommandService),Z(2,a.Inject(d.DocSkeletonManagerService)),Z(3,a.IConfigService),Z(4,l.IEditorService),Z(5,C.IRenderManagerService)],exports.DocRenderController);class Ae extends a.Disposable{constructor(e){super(),this._context=e}calculatePagePosition(){var M,b;const e=d.neoGetDocObject(this._context),n=(b=(M=this._context.unit.getSettings())==null?void 0:M.zoomRatio)!=null?b:1,{document:i,scene:r,docBackground:s}=e,c=r==null?void 0:r.getParent(),{width:u,height:h,pageMarginLeft:_,pageMarginTop:m}=i;if(c==null||u===Number.POSITIVE_INFINITY||h===Number.POSITIVE_INFINITY)return;const{width:S,height:g}=c;let f=0,p=0,v=0,I=0,O=Number.POSITIVE_INFINITY;S>(u+_*2)*n?(f=S/2-u*n/2,f/=n,v=(S-_*2)/n,O=0):(f=_,v=u+_*2,O=(v-S/n)/2),g>h?(p=g/2-h/2,I=(g-m*2)/n):(p=m,I=h+m*2),r.resize(v,I+200),i.translate(f,p),s.translate(f,p);const T=r.getViewport(d.VIEWPORT_KEY.VIEW_MAIN);return O!==Number.POSITIVE_INFINITY&&T!=null&&T.scrollToViewportPos({viewportScrollX:O}),this}}var Io=Object.defineProperty,Oo=Object.getOwnPropertyDescriptor,To=(o,e,t,n)=>{for(var i=n>1?void 0:n?Oo(e,t):e,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&Io(e,t,i),i},W=(o,e)=>(t,n)=>e(t,n,o);let Ce=class extends a.Disposable{constructor(o,e,t,n,i,r,s){super(),this._context=o,this._docSkeletonManagerService=e,this._univerInstanceService=t,this._commandService=n,this._textSelectionManagerService=i,this._editorService=r,this._docPageLayoutService=s,this._init()}_init(){this._initSkeletonListener(),this._initCommandExecutedListener(),this._initRenderRefresher(),setTimeout(()=>this.updateViewZoom(1,!0),20)}_initRenderRefresher(){this._docSkeletonManagerService.currentSkeleton$.subscribe(o=>{if(o==null)return;const{unitId:e,scene:t}=this._context;this._editorService.isEditor(e)||this.disposeWithMe(t.onMouseWheel$.subscribeEvent(n=>{if(!n.ctrlKey)return;const i=this._univerInstanceService.getCurrentUniverDocInstance();if(!i)return;const r=Math.abs(n.deltaX);let s=r<40?.2:r<80?.4:.2;s*=n.deltaY>0?-1:1,t.scaleX<1&&(s/=2);const c=i.zoomRatio;let u=+Number.parseFloat(`${c+s}`).toFixed(1);u=u>=4?4:u<=.1?.1:u,this._commandService.executeCommand(d.SetDocZoomRatioCommand.id,{zoomRatio:u,unitId:i.getUnitId()}),n.preventDefault()}))})}_initSkeletonListener(){this.disposeWithMe(this._docSkeletonManagerService.currentSkeleton$.subscribe(o=>{if(o==null)return;const e=this._univerInstanceService.getCurrentUniverDocInstance();if(!e)return;const t=e.zoomRatio||1;this.updateViewZoom(t,!1)}))}_initCommandExecutedListener(){const o=[d.SetDocZoomRatioOperation.id];this.disposeWithMe(this._commandService.onCommandExecuted(e=>{if(o.includes(e.id)){const t=this._univerInstanceService.getCurrentUniverDocInstance();if(!t)return;const n=e.params,{unitId:i}=n;if(i!==t.getUnitId())return;const r=t.zoomRatio||1;this.updateViewZoom(r)}}))}updateViewZoom(o,e=!0){var n;const t=d.neoGetDocObject(this._context);t.scene.scale(o,o),this._docPageLayoutService.calculatePagePosition(),e&&!this._editorService.isEditor(this._context.unitId)&&this._textSelectionManagerService.refreshSelection(),(n=t.scene.getTransformer())==null||n.clearSelectedObjects()}};Ce=To([W(1,a.Inject(d.DocSkeletonManagerService)),W(2,a.IUniverInstanceService),W(3,a.ICommandService),W(4,a.Inject(d.TextSelectionManagerService)),W(5,l.IEditorService),W(6,a.Inject(Ae))],Ce);var Ro=Object.defineProperty,Mo=Object.getOwnPropertyDescriptor,Eo=(o,e,t,n)=>{for(var i=n>1?void 0:n?Mo(e,t):e,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&Ro(e,t,i),i},G=(o,e)=>(t,n)=>e(t,n,o);let Ie=class extends a.Disposable{constructor(e,t,n,i,r,s,c){super();D(this,"_loadedMap",new WeakSet);this._context=e,this._commandService=t,this._editorService=n,this._instanceSrv=i,this._textSelectionRenderManager=r,this._docSkeletonManagerService=s,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:i}=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,i.resetCursor()})),this.disposeWithMe(n.onPointerDown$.subscribeEvent((r,s)=>{if(this._isEditorReadOnly(e))return;const c=this._instanceSrv.getCurrentUnitForType(a.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:g,pageMarginTop:f}=n.getOffsetConfig(),{editArea:p}=u.findEditAreaByCoord(m,S,g,f),v=this._docSkeletonManagerService.getViewModel(),I=v.getEditArea();I!==C.DocumentEditArea.BODY&&p!==C.DocumentEditArea.BODY&&p!==I&&v.setEditArea(p)}if(this._textSelectionRenderManager.eventTrigger(r),this._editorService.getEditor(e)){this._setEditorFocus(e);const{offsetX:S,offsetY:g}=r;setTimeout(()=>{this._setEditorFocus(e),this._textSelectionRenderManager.setCursorManually(S,g)},0)}r.button!==2&&s.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:i,scene:r}=n,{documentTransform:s}=i.getOffsetConfig(),c=r.getViewports()[0];if(c==null)return;const u=c.transformVector2SceneCoord(C.Vector2.FromArray([e,t]));return s.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 i=t.params,{unitId:r}=i,s=(n=this._textSelectionManagerService.getCurrentSelection())==null?void 0:n.unitId;if(r!==s)return;this._textSelectionManagerService.refreshSelection()}}))}_skeletonListener(){this.disposeWithMe(this._docSkeletonManagerService.currentSkeleton$.subscribe(e=>{if(e==null)return;const{scene:t,mainComponent:n,unitId:i}=this._context;this._textSelectionRenderManager.changeRuntime(e,t,n),this._textSelectionManagerService.setCurrentSelectionNotRefresh({unitId:i,subUnitId:""}),a.isInternalEditorID(i)||this._textSelectionManagerService.replaceTextRanges([{startOffset:0,endOffset:0}],!1)}))}};Ie=Eo([G(1,a.ICommandService),G(2,l.IEditorService),G(3,a.IUniverInstanceService),G(4,C.ITextSelectionRenderManager),G(5,a.Inject(d.DocSkeletonManagerService)),G(6,a.Inject(d.TextSelectionManagerService))],Ie);var bo=Object.defineProperty,Do=Object.getOwnPropertyDescriptor,yo=(o,e,t,n)=>{for(var i=n>1?void 0:n?Do(e,t):e,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&bo(e,t,i),i},te=(o,e)=>(t,n)=>e(t,n,o);function Ke(o,e){const t=Ye(o.left,o.top,e),n=Ye(o.right,o.bottom,e);return{left:t.x,top:t.y,right:n.x,bottom:n.y}}function Ye(o,e,t){const{scaleX:n,scaleY:i}=t.getAncestorScale(),r=t.getViewport(d.VIEWPORT_KEY.VIEW_MAIN);if(!r)return{x:o,y:e};const{viewportScrollX:s,viewportScrollY:c}=r,u=(o-s)*n,h=(e-c)*i;return{x:u,y:h}}exports.DocCanvasPopManagerService=class extends a.Disposable{constructor(e,t,n,i){super(),this._globalPopupManagerService=e,this._renderManagerService=t,this._univerInstanceService=n,this._commandService=i}_createObjectPositionObserver(e,t){const n=()=>{const{scene:u,engine:h}=t,{left:_,top:m,width:S,height:g}=e,f={left:_,right:_+S,top:m,bottom:m+g},p=h.getCanvasElement(),v=p.getBoundingClientRect(),I=C.pxToNum(p.style.width),O=Ke(f,u),{top:T,left:M,width:b}=v,E=b/I;return{left:O.left*E+M,right:O.right*E+M,top:O.top*E+T,bottom:O.bottom*E+T}},i=n(),r=new R.BehaviorSubject(i),s=new a.DisposableCollection;s.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&&s.add(c.onScrollAfter$.subscribeEvent(()=>{r.next(n())})),{position:i,position$:r,disposable:s}}_createRangePositionObserver(e,t){var u;const n=()=>{const{scene:h,mainComponent:_,engine:m}=t,S=t.with(d.DocSkeletonManagerService).getSkeleton(),g=S.findNodePositionByCharIndex(e.startOffset),f=S.findNodePositionByCharIndex(e.endOffset),p=_;if(!f||!g)return;const v=p.getOffsetConfig(),{docsLeft:I,docsTop:O}=v,T=m.getCanvasElement(),M=T.getBoundingClientRect(),b=C.pxToNum(T.style.width),{top:E,left:x,width:F}=M,N=F/b,{scaleX:Y,scaleY:Ne}=h.getAncestorScale(),gt=new C.NodePositionConvertToCursor(v,S),{borderBoxPointGroup:pt}=gt.getRangePointData(g,f);return C.getLineBounding(pt).map(j=>Ke(j,h)).map(j=>({left:(j.left+I*Y)*N+x,right:(j.right+I*Y)*N+x,top:(j.top+O*Ne)*N+E,bottom:(j.bottom+O*Ne)*N+E}))},i=(u=n())!=null?u:[],r=new R.BehaviorSubject(i),s=new a.DisposableCollection;s.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&&s.add(c.onScrollAfter$.subscribeEvent(()=>{const h=n();h&&r.next(h)})),{positions:i,positions$:r,disposable:s}}attachPopupToObject(e,t){const i=this._univerInstanceService.getCurrentUnitForType(a.UniverInstanceType.UNIVER_DOC).getUnitId(),r=this._renderManagerService.getRenderById(i);if(!r)return{dispose:()=>{}};const{position:s,position$:c,disposable:u}=this._createObjectPositionObserver(e,r),h=this._globalPopupManagerService.addPopup({...t,unitId:i,subUnitId:"default",anchorRect:s,anchorRect$:c});return{dispose:()=>{this._globalPopupManagerService.removePopup(h),c.complete(),u.dispose()}}}attachPopupToRange(e,t){const i=this._univerInstanceService.getCurrentUnitForType(a.UniverInstanceType.UNIVER_DOC).getUnitId(),{direction:r="top"}=t,s=this._renderManagerService.getRenderById(i);if(!s)return{dispose:()=>{}};const{positions:c,positions$:u,disposable:h}=this._createRangePositionObserver(e,s),_=u.pipe(R.map(S=>r==="top"?S[0]:S[S.length-1])),m=this._globalPopupManagerService.addPopup({...t,unitId:i,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()}}}};exports.DocCanvasPopManagerService=yo([te(0,a.Inject(l.ICanvasPopupService)),te(1,C.IRenderManagerService),te(2,a.IUniverInstanceService),te(3,a.ICommandService)],exports.DocCanvasPopManagerService);var Po=Object.defineProperty,xo=Object.getOwnPropertyDescriptor,Ao=(o,e,t,n)=>{for(var i=n>1?void 0:n?xo(e,t):e,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&Po(e,t,i),i},ze=(o,e)=>(t,n)=>e(t,n,o);exports.DocsRenderService=class extends a.RxDisposable{constructor(e,t){super(),this._instanceSrv=e,this._renderManagerService=t,this._init()}_init(){this._renderManagerService.createRender$.pipe(R.takeUntil(this.dispose$)).subscribe(e=>this._createRenderWithId(e)),this._instanceSrv.getTypeOfUnitAdded$(a.UniverInstanceType.UNIVER_DOC).pipe(R.takeUntil(this.dispose$)).subscribe(e=>this._createRenderer(e)),this._instanceSrv.getAllUnitsForType(a.UniverInstanceType.UNIVER_DOC).forEach(e=>this._createRenderer(e)),this._instanceSrv.getTypeOfUnitDisposed$(a.UniverInstanceType.UNIVER_DOC).pipe(R.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)}};exports.DocsRenderService=Ao([a.OnLifecycle(a.LifecycleStages.Ready,exports.DocsRenderService),ze(0,a.IUniverInstanceService),ze(1,C.IRenderManagerService)],exports.DocsRenderService);var No=Object.defineProperty,Uo=Object.getOwnPropertyDescriptor,Fo=(o,e,t,n)=>{for(var i=n>1?void 0:n?Uo(e,t):e,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&No(e,t,i),i},_e=(o,e)=>(t,n)=>e(t,n,o);const Lo=[a.DEFAULT_EMPTY_DOCUMENT_VALUE,a.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY,a.DOCS_ZEN_EDITOR_UNIT_ID_KEY];let Oe=class extends a.Disposable{constructor(o,e,t,n){super(),this._context=o,this._contextMenuService=e,this._textSelectionManagerService=t,this._commandService=n,Lo.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(i=>{i.button===2&&this._contextMenuService.triggerContextMenu(i,l.MenuPosition.CONTEXT_MENU)});this.disposeWithMe(e)}_initEditChange(){this.disposeWithMe(this._commandService.onCommandExecuted(o=>{o.id===d.RichTextEditingMutation.id&&this._contextMenuService.visible&&this._contextMenuService.hideContextMenu()}))}};Oe=Fo([_e(1,l.IContextMenuService),_e(2,a.Inject(d.TextSelectionManagerService)),_e(3,a.ICommandService)],Oe);var Bo=Object.defineProperty,wo=Object.getOwnPropertyDescriptor,$o=(o,e,t,n)=>{for(var i=n>1?void 0:n?wo(e,t):e,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&Bo(e,t,i),i},Xe=(o,e)=>(t,n)=>e(t,n,o);const Ho=[a.DEFAULT_EMPTY_DOCUMENT_VALUE,a.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,a.DOCS_NORMAL_EDITOR_UNIT_ID_KEY];let Te=class extends a.Disposable{constructor(o,e,t){super(),this._context=o,this._docPageLayoutService=e,this._textSelectionManagerService=t,Ho.includes(this._context.unitId)||this._initResize()}_initResize(){this.disposeWithMe(a.fromEventSubject(this._context.engine.onTransformChange$).pipe(R.filter(o=>o.type===C.TRANSFORM_CHANGE_OBSERVABLE_TYPE.resize),R.throttleTime(16)).subscribe(()=>{this._docPageLayoutService.calculatePagePosition(),this._textSelectionManagerService.refreshSelection()}))}};Te=$o([Xe(1,a.Inject(Ae)),Xe(2,a.Inject(d.TextSelectionManagerService))],Te);var jo=Object.defineProperty,Vo=Object.getOwnPropertyDescriptor,Wo=(o,e,t,n)=>{for(var i=n>1?void 0:n?Vo(e,t):e,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&jo(e,t,i),i},Ze=(o,e)=>(t,n)=>e(t,n,o);exports.DocHoverManagerService=class extends a.Disposable{constructor(t,n){super();D(this,"_activeCustomRanges$",new R.BehaviorSubject([]));D(this,"activeCustomRanges$",this._activeCustomRanges$.asObservable());D(this,"_activeIndex$",new R.BehaviorSubject(null));D(this,"activeIndex$",this._activeIndex$.asObservable());D(this,"_scrolling",!1);this._univerInstanceService=t,this._renderManagerService=n,this.disposeWithMe(()=>{this._activeCustomRanges$.complete(),this._activeIndex$.complete()})}_getTransformCoordForDocumentOffset(t,n,i,r){const{documentTransform:s}=t.getOffsetConfig(),c=n.transformVector2SceneCoord(C.Vector2.FromArray([i,r]));if(c)return s.clone().invert().applyPoint(c)}_calcActiveCustomRanges(t,n){var p,v;const i=this._univerInstanceService.getCurrentUnitForType(a.UniverInstanceType.UNIVER_DOC);if(!i){this._activeCustomRanges$.next([]);return}const r=this._renderManagerService.getRenderById(i.getUnitId());if(!r)return null;const s=r.mainComponent,c=r.with(d.DocSkeletonManagerService).getSkeleton(),{pageLayoutType:u=C.PageLayoutType.VERTICAL,pageMarginLeft:h,pageMarginTop:_,docsLeft:m,docsTop:S}=s.getOffsetConfig(),g=this._getTransformCoordForDocumentOffset(s,r.scene.getViewport(d.VIEWPORT_KEY.VIEW_MAIN),t,n);if(!g)return;const f=c.findNodeByCoord(g,u,h,_);if(f&&f.node){const I=f.node.left+h,O=f.node.left+f.node.width+h;if(g.x<I||g.x>O){this._activeIndex$.next(null),this._activeCustomRanges$.next([]);return}const T=f.node.parent.st+f.node.parent.glyphGroup.indexOf(f.node);T!==this._activeIndex$.value&&this._activeIndex$.next(T);const M=(v=(p=i.getCustomRanges())==null?void 0:p.filter(E=>E.startIndex<=T&&E.endIndex>=T))!=null?v:[],b=this._activeCustomRanges$.value;if(b.length===M.length&&b.every((E,x)=>E.rangeId===M[x].rangeId))return;this._activeCustomRanges$.next(M)}}onMouseMove(t){if(this._scrolling)return;const{offsetX:n,offsetY:i}=t;this._calcActiveCustomRanges(n,i)}startScroll(){this._scrolling||(this._scrolling=!0)}endScroll(){this._scrolling=!1}};exports.DocHoverManagerService=Wo([Ze(0,a.IUniverInstanceService),Ze(1,C.IRenderManagerService)],exports.DocHoverManagerService);var Go=Object.defineProperty,ko=Object.getOwnPropertyDescriptor,Ko=(o,e,t,n)=>{for(var i=n>1?void 0:n?ko(e,t):e,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&Go(e,t,i),i},Yo=(o,e)=>(t,n)=>e(t,n,o);let Re=class extends a.Disposable{constructor(o,e){super(),this._context=o,this._docHoverManagerService=e,this._initPointerDown(),this._initScroll()}_initPointerDown(){this.disposeWithMe(a.fromEventSubject(this._context.scene.onPointerMove$).pipe(R.throttleTime(16)).subscribe(o=>{this._docHoverManagerService.onMouseMove(o)}))}_initScroll(){const o=this._context.scene.getViewport(d.VIEWPORT_KEY.VIEW_MAIN);o&&(this.disposeWithMe(a.fromEventSubject(o.onScrollAfter$).pipe(R.debounceTime(60)).subscribe(()=>{this._docHoverManagerService.endScroll()})),this.disposeWithMe(o.onScrollBefore$.subscribeEvent(()=>{this._docHoverManagerService.startScroll()})))}};Re=Ko([Yo(1,a.Inject(exports.DocHoverManagerService))],Re);var zo=Object.defineProperty,Xo=Object.getOwnPropertyDescriptor,Zo=(o,e,t,n)=>{for(var i=n>1?void 0:n?Xo(e,t):e,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&zo(e,t,i),i},me=(o,e)=>(t,n)=>e(t,n,o),ne;exports.UniverDocsUIPlugin=(ne=class extends a.Plugin{constructor(e,t,n,i){super(),this._config=e,this._injector=t,this._renderManagerSrv=n,this._logService=i,this._config=a.Tools.deepMerge({},ot,this._config),this._initDependencies(t),this._initializeCommands()}onReady(){this._initRenderBasics()}onRendered(){this._initUI(),this._initRenderModules(),this._markDocAsFocused()}_initializeCommands(){[Ft,Lt,wt,Bt,$t,Ht,jt,Vt,Wt,lo,uo,co].forEach(e=>{this._injector.get(l.IShortcutService).registerShortcut(e)})}_initDependencies(e){[[q,{useFactory:()=>this._injector.createInstance(q,this._config)}],[ie],[re],[exports.DocsRenderService],[J,{useFactory:()=>this._injector.createInstance(J,this._config)}],[K,{useClass:Se}],[exports.DocCanvasPopManagerService],[exports.DocHoverManagerService]].forEach(n=>e.add(n))}_markDocAsFocused(){const e=this._injector.get(a.IUniverInstanceService),t=this._injector.get(l.IEditorService);try{const n=e.getCurrentUnitForType(a.UniverInstanceType.UNIVER_DOC);if(!n)return;const i=n.getUnitId();t.isEditor(i)||e.focusUnit(n.getUnitId())}catch(n){this._logService.warn(n)}}_initUI(){this._injector.get(J)}_initRenderBasics(){[[d.DocSkeletonManagerService],[d.DocInterceptorService],[Ae],[exports.DocRenderController],[Ce]].forEach(e=>{this._renderManagerSrv.registerRenderModule(a.UniverInstanceType.UNIVER_DOC,e)})}_initRenderModules(){[[exports.DocBackScrollRenderController],[Ie],[ve],[Te],[Re],[Oe]].forEach(e=>{this._renderManagerSrv.registerRenderModule(a.UniverInstanceType.UNIVER_DOC,e)})}},D(ne,"pluginName",it),D(ne,"type",a.UniverInstanceType.UNIVER_DOC),ne);exports.UniverDocsUIPlugin=Zo([me(1,a.Inject(a.Injector)),me(2,C.IRenderManagerService),me(3,a.ILogService)],exports.UniverDocsUIPlugin);function Jo(o){return{left:o.positionH.posOffset,top:o.positionV.posOffset,width:o.size.width,height:o.size.height}}function qo(o,e=0,t=0){return{size:{width:o.width,height:o.height},positionH:{relativeFrom:a.ObjectRelativeFromH.MARGIN,posOffset:(o.left||0)-e},positionV:{relativeFrom:a.ObjectRelativeFromV.PAGE,posOffset:(o.top||0)-t},angle:o.angle||0}}exports.DOC_UI_PLUGIN_NAME=it;exports.DefaultDocContainerConfig=nt;exports.DefaultDocUiConfig=ot;exports.DefaultToolbarConfig=tt;exports.DocCopyCommand=De;exports.DocCutCommand=ye;exports.DocPasteCommand=Pe;exports.IDocClipboardService=K;exports.PastePluginLark=Je;exports.PastePluginUniver=et;exports.PastePluginWord=Qe;exports.docDrawingPositionToTransform=Jo;exports.transformToDocDrawingPosition=qo;exports.whenDocAndEditorFocused=P;
|
|
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 docCountBar="univer-doc-count-bar",styles$2={docCountBar},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 _a19,_b;if(!documentDataModel)return 100;const currentZoom=((_b=(_a19=documentDataModel.getSettings())==null?void 0:_a19.zoomRatio)!=null?_b: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 docFooterContainer="univer-doc-footer-container",styles$1={docFooterContainer},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",panel="univer-panel",optionsSection="univer-options-section",optionsFormItem="univer-options-form-item",optionsInput="univer-options-input",optionsMarginSetting="univer-options-margin-setting",styles={panel,optionsSection,optionsFormItem,optionsInput,optionsMarginSetting},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 _a19;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=(_a19=renderManagerService.getRenderById(unitId))==null?void 0:_a19.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 _a19;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(),(_a19=render.mainComponent)==null||_a19.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 _a19;const localeService=core.useDependency(core.LocaleService),renderManagerService=core.useDependency(engineRender.IRenderManagerService),unitId=core.useDependency(core.IUniverInstanceService).getCurrentUniverDocInstance().getUnitId(),viewModel=((_a19=renderManagerService.getRenderById(unitId))==null?void 0:_a19.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");var _a5;let DocHeaderFooterController=(_a5=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(_a5,"DocHeaderFooterController"),_a5);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 _a19;const commandService=accessor.get(core.ICommandService),univerInstanceService=accessor.get(core.IUniverInstanceService),renderManagerService=accessor.get(engineRender.IRenderManagerService),{unitId,segmentId,createType,headerFooterProps}=params,docSkeletonManagerService=(_a19=renderManagerService.getRenderById(unitId))==null?void 0:_a19.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 _a19;const id=c.id;if(id===docs.SetTextSelectionsOperation.id||id===docs.SetInlineFormatCommand.id){const textRun=getFontStyleAtCursor(accessor);if(textRun==null)return;const bl=(_a19=textRun.ts)==null?void 0:_a19.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 _a19;const id=c.id;if(id===docs.SetTextSelectionsOperation.id||id===docs.SetInlineFormatCommand.id){const textRun=getFontStyleAtCursor(accessor);if(textRun==null)return;const it=(_a19=textRun.ts)==null?void 0:_a19.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 _a19;const id=c.id;if(id===docs.SetTextSelectionsOperation.id||id===docs.SetInlineFormatCommand.id){const textRun=getFontStyleAtCursor(accessor);if(textRun==null)return;const ul=(_a19=textRun.ts)==null?void 0:_a19.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 _a19;const id=c.id;if(id===docs.SetTextSelectionsOperation.id||id===docs.SetInlineFormatCommand.id){const textRun=getFontStyleAtCursor(accessor);if(textRun==null)return;const st=(_a19=textRun.ts)==null?void 0:_a19.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 _a19;const id=c.id;if(id===docs.SetTextSelectionsOperation.id||id===docs.SetInlineFormatCommand.id){const textRun=getFontStyleAtCursor(accessor);if(textRun==null)return;const va=(_a19=textRun.ts)==null?void 0:_a19.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 _a19;const id=c.id;if(id===docs.SetTextSelectionsOperation.id||id===docs.SetInlineFormatCommand.id){const textRun=getFontStyleAtCursor(accessor);if(textRun==null)return;const va=(_a19=textRun.ts)==null?void 0:_a19.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 _a19;const id=c.id;if(id===docs.SetTextSelectionsOperation.id||id===docs.SetInlineFormatFontFamilyCommand.id){const textRun=getFontStyleAtCursor(accessor);if(textRun==null)return;const ff=(_a19=textRun.ts)==null?void 0:_a19.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 _a19;const id=c.id;if(id===docs.SetTextSelectionsOperation.id||id===docs.SetInlineFormatFontSizeCommand.id){const textRun=getFontStyleAtCursor(accessor);if(textRun==null)return;const fs=(_a19=textRun.ts)==null?void 0:_a19.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 _a19;const id=c.id;if(id===docs.SetTextSelectionsOperation.id||id===docs.AlignOperationCommand.id){const paragraph=getParagraphStyleAtCursor(accessor);if(paragraph==null)return;const alignType=(_a19=paragraph.paragraphStyle)==null?void 0:_a19.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 _a19;const id=c.id;if(id===docs.SetTextSelectionsOperation.id||id===docs.AlignOperationCommand.id){const paragraph=getParagraphStyleAtCursor(accessor);if(paragraph==null)return;const alignType=(_a19=paragraph.paragraphStyle)==null?void 0:_a19.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 _a19;const id=c.id;if(id===docs.SetTextSelectionsOperation.id||id===docs.AlignOperationCommand.id){const paragraph=getParagraphStyleAtCursor(accessor);if(paragraph==null)return;const alignType=(_a19=paragraph.paragraphStyle)==null?void 0:_a19.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 _a19;const id=c.id;if(id===docs.SetTextSelectionsOperation.id||id===docs.AlignOperationCommand.id){const paragraph=getParagraphStyleAtCursor(accessor);if(paragraph==null)return;const alignType=(_a19=paragraph.paragraphStyle)==null?void 0:_a19.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 _a19;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=(_a19=docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody())==null?void 0:_a19.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 _a19;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=(_a19=docDataModel.getSelfOrHeaderFooterModel(segmentId).getBody())==null?void 0:_a19.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"),_a6;let DocUIController=(_a6=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 _a19,_b;const workbook=this._univerInstanceService.getCurrentUnitForType(core.UniverInstanceType.UNIVER_SHEET);(_b=(_a19=this._config.layout)==null?void 0:_a19.docContainerConfig)!=null&&_b.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(_a6,"DocUIController"),_a6);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"),_a7;let DocClipboardController=(_a7=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 _a19;(_a19=this._textSelectionRenderManager)==null||_a19.onPaste$.pipe(rxjs.takeUntil(this.dispose$)).subscribe(config=>{var _a20,_b;if(!whenDocOrEditor(this._contextService))return;config.event.preventDefault();const clipboardEvent=config.event,htmlContent=(_a20=clipboardEvent.clipboardData)==null?void 0:_a20.getData("text/html"),textContent=(_b=clipboardEvent.clipboardData)==null?void 0:_b.getData("text/plain");this._docClipboardService.legacyPaste(htmlContent,textContent)})}},__name(_a7,"DocClipboardController"),_a7);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"),_a8;let DocEditorBridgeController=(_a8=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 _a19,_b,_c;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=(_a19=this._renderManagerService.getRenderById(editorDataModel.getUnitId()))==null?void 0:_a19.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}),(_c=viewportMain==null?void 0:viewportMain.getScrollBar())==null||_c.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}),(_b=viewportMain==null?void 0:viewportMain.getScrollBar())==null||_b.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 _a19;const unitId=(_a19=this._univerInstanceService.getCurrentUniverDocInstance())==null?void 0:_a19.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 _a19;const unitId=(_a19=this._univerInstanceService.getCurrentUniverDocInstance())==null?void 0:_a19.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(_a8,"DocEditorBridgeController"),_a8);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"),_a9;exports.DocRenderController=(_a9=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 _a19,_b;const docSkeletonManagerService=(_a19=this._renderManagerService.getRenderById(unitId))==null?void 0:_a19.with(docs.DocSkeletonManagerService),skeleton=docSkeletonManagerService==null?void 0:docSkeletonManagerService.getSkeleton();if(!(!skeleton||skeleton.getViewModel().getDataModel().getSnapshot().disabled)){if(skeleton.calculate(),this._editorService.isEditor(unitId)){(_b=this._context.mainComponent)==null||_b.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 _a19;const{mainComponent,scene,unitId,components}=this._context,docsComponent=mainComponent,docBackground=components.get(docs.DOCS_VIEW_KEY.BACKGROUND),pages=(_a19=skeleton.getSkeletonData())==null?void 0:_a19.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(_a9,"DocRenderController"),_a9);exports.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)],exports.DocRenderController);const _DocPageLayoutService=class _DocPageLayoutService extends core.Disposable{constructor(_context){super(),this._context=_context}calculatePagePosition(){var _a19,_b;const docObject=docs.neoGetDocObject(this._context),zoomRatio=(_b=(_a19=this._context.unit.getSettings())==null?void 0:_a19.zoomRatio)!=null?_b: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"),_a10;let DocZoomRenderController=(_a10=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 _a19;const docObject=docs.neoGetDocObject(this._context);docObject.scene.scale(zoomRatio,zoomRatio),this._docPageLayoutService.calculatePagePosition(),needRefreshSelection&&!this._editorService.isEditor(this._context.unitId)&&this._textSelectionManagerService.refreshSelection(),(_a19=docObject.scene.getTransformer())==null||_a19.clearSelectedObjects()}},__name(_a10,"DocZoomRenderController"),_a10);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"),_a11;let DocTextSelectionRenderController=(_a11=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 _a19;if(updateCommandList.includes(command.id)){const params=command.params,{unitId:documentId}=params,unitId=(_a19=this._textSelectionManagerService.getCurrentSelection())==null?void 0:_a19.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(_a11,"DocTextSelectionRenderController"),_a11);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");var _a12;exports.DocCanvasPopManagerService=(_a12=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 _a19;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=(_a19=calc())!=null?_a19:[],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(_a12,"DocCanvasPopManagerService"),_a12);exports.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)],exports.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"),_a13;exports.DocsRenderService=(_a13=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(_a13,"DocsRenderService"),_a13);exports.DocsRenderService=__decorateClass$5([core.OnLifecycle(core.LifecycleStages.Ready,exports.DocsRenderService),__decorateParam$5(0,core.IUniverInstanceService),__decorateParam$5(1,engineRender.IRenderManagerService)],exports.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];var _a14;let DocContextMenuRenderController=(_a14=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 _a19,_b;const documentsSubscription=((_b=(_a19=this._context)==null?void 0:_a19.mainComponent)==null?void 0:_b.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(_a14,"DocContextMenuRenderController"),_a14);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];var _a15;let DocResizeRenderController=(_a15=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(_a15,"DocResizeRenderController"),_a15);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"),_a16;exports.DocHoverManagerService=(_a16=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 _a19,_b;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=(_b=(_a19=document.getCustomRanges())==null?void 0:_a19.filter(range=>range.startIndex<=index&&range.endIndex>=index))!=null?_b:[],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(_a16,"DocHoverManagerService"),_a16);exports.DocHoverManagerService=__decorateClass$2([__decorateParam$2(0,core.IUniverInstanceService),__decorateParam$2(1,engineRender.IRenderManagerService)],exports.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"),_a17;let DocHoverRenderController=(_a17=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(_a17,"DocHoverRenderController"),_a17);DocHoverRenderController=__decorateClass$1([__decorateParam$1(1,core.Inject(exports.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"),_a18;exports.UniverDocsUIPlugin=(_a18=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],[exports.DocsRenderService],[AppUIController,{useFactory:__name(()=>this._injector.createInstance(AppUIController,this._config),"useFactory")}],[IDocClipboardService,{useClass:DocClipboardService}],[exports.DocCanvasPopManagerService],[exports.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],[exports.DocRenderController],[DocZoomRenderController]].forEach(m2=>{this._renderManagerSrv.registerRenderModule(core.UniverInstanceType.UNIVER_DOC,m2)})}_initRenderModules(){[[exports.DocBackScrollRenderController],[DocTextSelectionRenderController],[DocHeaderFooterController],[DocResizeRenderController],[DocHoverRenderController],[DocContextMenuRenderController]].forEach(m2=>{this._renderManagerSrv.registerRenderModule(core.UniverInstanceType.UNIVER_DOC,m2)})}},__name(_a18,"UniverDocsUIPlugin"),__publicField(_a18,"pluginName",DOC_UI_PLUGIN_NAME),__publicField(_a18,"type",core.UniverInstanceType.UNIVER_DOC),_a18);exports.UniverDocsUIPlugin=__decorateClass([__decorateParam(1,core.Inject(core.Injector)),__decorateParam(2,engineRender.IRenderManagerService),__decorateParam(3,core.ILogService)],exports.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");exports.DOC_UI_PLUGIN_NAME=DOC_UI_PLUGIN_NAME;exports.DefaultDocContainerConfig=DefaultDocContainerConfig;exports.DefaultDocUiConfig=DefaultDocUiConfig;exports.DefaultToolbarConfig=DefaultToolbarConfig;exports.DocCopyCommand=DocCopyCommand;exports.DocCutCommand=DocCutCommand;exports.DocPasteCommand=DocPasteCommand;exports.IDocClipboardService=IDocClipboardService;exports.PastePluginLark=PastePluginLark;exports.PastePluginUniver=PastePluginUniver;exports.PastePluginWord=PastePluginWord;exports.docDrawingPositionToTransform=docDrawingPositionToTransform;exports.transformToDocDrawingPosition=transformToDocDrawingPosition;exports.whenDocAndEditorFocused=whenDocAndEditorFocused;
|