(function(l,r){typeof exports=="object"&&typeof module<"u"?r(exports,require("@univerjs/core"),require("@univerjs/engine-render"),require("rxjs")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","@univerjs/engine-render","rxjs"],r):(l=typeof globalThis<"u"?globalThis:l||self,r(l.UniverDocs={},l.UniverCore,l.UniverEngineRender,l.rxjs))})(this,function(l,r,v,m){"use strict";var Se=Object.defineProperty;var Ie=(l,r,v)=>r in l?Se(l,r,{enumerable:!0,configurable:!0,writable:!0,value:v}):l[r]=v;var g=(l,r,v)=>Ie(l,typeof r!="symbol"?r+"":r,v);var w;const M={id:"doc.operation.set-selections",type:r.CommandType.OPERATION,handler:()=>!0};var G=Object.defineProperty,k=Object.getOwnPropertyDescriptor,z=(c,i,e,t)=>{for(var n=t>1?void 0:t?k(i,e):i,s=c.length-1,o;s>=0;s--)(o=c[s])&&(n=(t?o(i,e,n):o(n))||n);return t&&n&&G(i,e,n),n},E=(c,i)=>(e,t)=>i(e,t,c);l.DocSelectionManagerService=class extends r.RxDisposable{constructor(e,t){super();g(this,"_currentSelection",null);g(this,"_textSelectionInfo",new Map);g(this,"_textSelection$",new m.Subject);g(this,"textSelection$",this._textSelection$.asObservable());g(this,"_refreshSelection$",new m.BehaviorSubject(null));g(this,"refreshSelection$",this._refreshSelection$.asObservable());this._commandService=e,this._univerInstanceService=t,this._listenCurrentUnit()}_listenCurrentUnit(){this._univerInstanceService.getCurrentTypeOfUnit$(r.UniverInstanceType.UNIVER_DOC).pipe(m.takeUntil(this.dispose$)).subscribe(e=>{if(e==null)return;const t=e.getUnitId();this._setCurrentSelectionNotRefresh({unitId:t,subUnitId:t})})}__getCurrentSelection(){return this._currentSelection}getSelectionInfo(e=this._currentSelection){return this._getTextRanges(e)}refreshSelection(e=this._currentSelection){e!=null&&this._refresh(e)}__TEST_ONLY_setCurrentSelection(e){this._currentSelection=e,this._refresh(e)}getTextRanges(e=this._currentSelection){var t;return(t=this._getTextRanges(e))==null?void 0:t.textRanges}getRectRanges(e=this._currentSelection){var t;return(t=this._getTextRanges(e))==null?void 0:t.rectRanges}getDocRanges(e=this._currentSelection){var o,a;const t=(o=this.getTextRanges(e))!=null?o:[],n=(a=this.getRectRanges(e))!=null?a:[];return[...t,...n].filter(u=>u.startOffset!=null&&u.endOffset!=null).sort((u,d)=>u.startOffset>d.startOffset?1:u.startOffsetn.isActive)}getActiveRectRange(){const e=this._getTextRanges(this._currentSelection);if(e==null)return;const{rectRanges:t}=e;return t.find(n=>n.isActive)}__TEST_ONLY_add(e,t=!0){this._currentSelection!=null&&this._addByParam({...this._currentSelection,textRanges:e,rectRanges:[],segmentId:"",segmentPage:-1,isEditing:t,style:v.NORMAL_TEXT_SELECTION_PLUGIN_STYLE})}replaceTextRanges(e,t=!0,n){return this.replaceDocRanges(e,this._currentSelection,t,n)}replaceDocRanges(e,t=this._currentSelection,n=!0,s){if(t==null)return;const{unitId:o,subUnitId:a}=t;this._refreshSelection$.next({unitId:o,subUnitId:a,docRanges:e,isEditing:n,options:s})}__replaceTextRangesWithNoRefresh(e,t){if(this._currentSelection==null)return;const n={...e,...t};this._replaceByParam(n),this._textSelection$.next(n);const{unitId:s,subUnitId:o,segmentId:a,style:u,textRanges:d,rectRanges:f,isEditing:h}=n,I=[...d,...f].filter(_=>_.startOffset!=null&&_.endOffset!=null).sort((_,S)=>_.startOffset>S.startOffset?1:_.startOffset{for(var n=t>1?void 0:t?J(i,e):i,s=c.length-1,o;s>=0;s--)(o=c[s])&&(n=(t?o(i,e,n):o(n))||n);return t&&n&&W(i,e,n),n},N=(c,i)=>(e,t)=>i(e,t,c);l.DocSkeletonManagerService=class extends r.RxDisposable{constructor(e,t,n){super();g(this,"_skeleton");g(this,"_docViewModel");g(this,"_currentSkeleton$",new m.BehaviorSubject(null));g(this,"currentSkeleton$",this._currentSkeleton$.asObservable());g(this,"_currentSkeletonBefore$",new m.BehaviorSubject(null));g(this,"currentSkeletonBefore$",this._currentSkeletonBefore$.asObservable());g(this,"_currentViewModel$",new m.BehaviorSubject(null));g(this,"currentViewModel$",this._currentViewModel$.asObservable());this._context=e,this._localeService=t,this._univerInstanceService=n,this._init(),this._univerInstanceService.getCurrentTypeOfUnit$(r.UniverInstanceType.UNIVER_DOC).pipe(m.takeUntil(this.dispose$)).subscribe(s=>{s&&s.getUnitId()===this._context.unitId&&this._update(s)})}dispose(){super.dispose(),this._currentSkeletonBefore$.complete(),this._currentSkeleton$.complete()}getSkeleton(){return this._skeleton}getViewModel(){return this._docViewModel}_init(){const e=this._context.unit;this._update(e)}_update(e){const t=this._context.unitId;if(e.getBody()==null)return;this._docViewModel&&r.isInternalEditorID(t)?(this._docViewModel.reset(e),this._context.unit=e):this._docViewModel||(this._docViewModel=this._buildDocViewModel(e)),this._skeleton||(this._skeleton=this._buildSkeleton(this._docViewModel));const n=this._skeleton;n.calculate(),this._currentSkeletonBefore$.next(n),this._currentSkeleton$.next(n),this._currentViewModel$.next(this._docViewModel)}_buildSkeleton(e){return v.DocumentSkeleton.create(e,this._localeService)}_buildDocViewModel(e){return new v.DocumentViewModel(e)}},l.DocSkeletonManagerService=Y([N(1,r.Inject(r.LocaleService)),N(2,r.IUniverInstanceService)],l.DocSkeletonManagerService);class U extends r.RxDisposable{constructor(){super();g(this,"_docStateChangeParams$",new m.BehaviorSubject(null));g(this,"docStateChangeParams$",this._docStateChangeParams$.asObservable())}emitStateChangeInfo(e){this._docStateChangeParams$.next(e)}dispose(){super.dispose(),this._docStateChangeParams$.complete()}}const $="doc.mutation.rich-text-editing",O={id:$,type:r.CommandType.MUTATION,handler:(c,i)=>{var F,L;const{unitId:e,segmentId:t="",actions:n,textRanges:s,prevTextRanges:o,trigger:a,noHistory:u,isCompositionEnd:d,noNeedSetTextRange:f,debounce:h,isEditing:I=!0,isSync:_,syncer:S}=i,D=c.get(r.IUniverInstanceService),R=c.get(v.IRenderManagerService),C=c.get(U),p=D.getUniverDocInstance(e),V=(F=R.getRenderById(e))==null?void 0:F.with(l.DocSkeletonManagerService).getViewModel();if(p==null||V==null)throw new Error(`DocumentDataModel or documentViewModel not found for unitId: ${e}`);const A=c.get(l.DocSelectionManagerService),P=(L=A.getDocRanges())!=null?L:[],_e=!!p.getSnapshot().disabled;if(r.JSONX.isNoop(n)||n&&n.length===0||_e)return{unitId:e,actions:[],textRanges:P};const X=r.JSONX.invertWithDoc(n,p.getSnapshot());p.apply(n),V.reset(p),!f&&s&&a!=null&&!_&&queueMicrotask(()=>{A.replaceDocRanges(s,{unitId:e,subUnitId:e},I,i.options)});const he={commandId:$,unitId:e,segmentId:t,trigger:a,noHistory:u,debounce:h,redoState:{actions:n,textRanges:s},undoState:{actions:X,textRanges:o!=null?o:P},isCompositionEnd:d,isSync:_,syncer:S};return C.emitStateChangeInfo(he),{unitId:e,actions:X,textRanges:P}}},K={id:"doc.mutation.rename-doc",type:r.CommandType.MUTATION,handler:(c,i)=>{const t=c.get(r.IUniverInstanceService).getUnit(i.unitId,r.UniverInstanceType.UNIVER_DOC);return t?(t.setName(i.name),!0):!1}},q="docs.config",B={};var H=Object.defineProperty,Q=Object.getOwnPropertyDescriptor,Z=(c,i,e,t)=>{for(var n=t>1?void 0:t?Q(i,e):i,s=c.length-1,o;s>=0;s--)(o=c[s])&&(n=(t?o(i,e,n):o(n))||n);return t&&n&&H(i,e,n),n},b=(c,i)=>(e,t)=>i(e,t,c);let T=class extends r.Disposable{constructor(c,i,e){super(),this._commandService=c,this._textSelectionManagerService=i,this._univerInstanceService=e,this._initSelectionChange()}_transformCustomRange(c,i){var o;const{startOffset:e,endOffset:t,collapsed:n}=i,s=(o=c.getCustomRanges())==null?void 0:o.filter(a=>!a.wholeEntity||e<=a.startIndex&&t>a.endIndex?!1:n?a.startIndex=t:r.BuildTextUtils.range.isIntersects(e,t-1,a.startIndex,a.endIndex));if(s!=null&&s.length){let a=e,u=t;return s.forEach(d=>{a=Math.min(d.startIndex,a),u=Math.max(d.endIndex+1,u)}),{...i,startOffset:a,endOffset:u,collapsed:a===u}}return i}_initSelectionChange(){this.disposeWithMe(this._commandService.onCommandExecuted(c=>{if(c.id===M.id){const i=c.params,{unitId:e,ranges:t,isEditing:n}=i,s=this._univerInstanceService.getUnit(e);if(!s)return;const o=t.map(a=>this._transformCustomRange(s,a));o.some((a,u)=>t[u]!==a)&&this._textSelectionManagerService.replaceTextRanges(o,n)}}))}};T=Z([b(0,r.ICommandService),b(1,r.Inject(l.DocSelectionManagerService)),b(2,r.IUniverInstanceService)],T);var ee=Object.defineProperty,te=Object.getOwnPropertyDescriptor,ne=(c,i,e,t)=>{for(var n=t>1?void 0:t?te(i,e):i,s=c.length-1,o;s>=0;s--)(o=c[s])&&(n=(t?o(i,e,n):o(n))||n);return t&&n&&ee(i,e,n),n},j=(c,i)=>(e,t)=>i(e,t,c);const ie="DOCS_PLUGIN";l.UniverDocsPlugin=(w=class extends r.Plugin{constructor(i=B,e,t){super(),this._config=i,this._injector=e,this._configService=t;const{...n}=r.merge({},B,this._config);this._configService.setConfig(q,n)}onStarting(){this._initializeDependencies(),this._initializeCommands()}_initializeCommands(){[O,K,M].forEach(i=>{this._injector.get(r.ICommandService).registerCommand(i)})}_initializeDependencies(){[[l.DocSelectionManagerService],[U],[T]].forEach(i=>this._injector.add(i))}onReady(){this._injector.get(T)}},g(w,"pluginName",ie),w),l.UniverDocsPlugin=ne([j(1,r.Inject(r.Injector)),j(2,r.IConfigService)],l.UniverDocsPlugin);const se=r.createInterceptorKey("CUSTOM_RANGE"),re=r.createInterceptorKey("CUSTOM_DECORATION"),x={CUSTOM_RANGE:se,CUSTOM_DECORATION:re};var oe=Object.defineProperty,ce=Object.getOwnPropertyDescriptor,ae=(c,i,e,t)=>{for(var n=t>1?void 0:t?ce(i,e):i,s=c.length-1,o;s>=0;s--)(o=c[s])&&(n=(t?o(i,e,n):o(n))||n);return t&&n&&oe(i,e,n),n},le=(c,i)=>(e,t)=>i(e,t,c);l.DocInterceptorService=class extends r.Disposable{constructor(e,t){super();g(this,"_interceptorsByName",new Map);this._context=e,this._docSkeletonManagerService=t;const n=this._docSkeletonManagerService.getViewModel(),s=n.getDataModel().getUnitId();if(s===r.DOCS_NORMAL_EDITOR_UNIT_ID_KEY||s===r.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY)return;this.disposeWithMe(this.interceptDocumentViewModel(n)),this.disposeWithMe(this.intercept(x.CUSTOM_RANGE,{priority:-1,handler:(a,u,d)=>d(a)}));let o=new r.DisposableCollection;n.segmentViewModels$.subscribe(a=>{o.dispose(),o=new r.DisposableCollection,a.forEach(u=>{o.add(this.interceptDocumentViewModel(u))})}),this.disposeWithMe(o)}intercept(e,t){const n=e;this._interceptorsByName.has(n)||this._interceptorsByName.set(n,[]);const s=this._interceptorsByName.get(n);return s.push(t),this._interceptorsByName.set(n,s.sort((o,a)=>{var u,d;return((u=a.priority)!=null?u:0)-((d=o.priority)!=null?d:0)})),this.disposeWithMe(r.toDisposable(()=>r.remove(this._interceptorsByName.get(n),t)))}fetchThroughInterceptors(e){const t=e,n=this._interceptorsByName.get(t);return r.composeInterceptors(n||[])}interceptDocumentViewModel(e){const t=new r.DisposableCollection;return t.add(e.registerCustomRangeInterceptor({getCustomRange:n=>{var s;return this.fetchThroughInterceptors(x.CUSTOM_RANGE)(e.getCustomRangeRaw(n),{index:n,unitId:e.getDataModel().getUnitId(),customRanges:(s=e.getDataModel().getCustomRanges())!=null?s:[]})},getCustomDecoration:n=>{var s;return this.fetchThroughInterceptors(x.CUSTOM_DECORATION)(e.getCustomDecorationRaw(n),{index:n,unitId:e.getDataModel().getUnitId(),customDecorations:(s=e.getDataModel().getCustomDecorations())!=null?s:[]})}})),t}},l.DocInterceptorService=ae([le(1,r.Inject(l.DocSkeletonManagerService))],l.DocInterceptorService);function y(c,i=""){if(!i)return["body"];const{headers:e,footers:t}=c.getSnapshot();if(e==null&&t==null)throw new Error("Document data model must have headers or footers when update by segment id");if((e==null?void 0:e[i])!=null)return["headers",i,"body"];if((t==null?void 0:t[i])!=null)return["footers",i,"body"];throw new Error("Segment id not found in headers or footers")}function ue(c,i,e){const{unitId:t,segmentId:n}=i,o=c.get(r.IUniverInstanceService).getUnit(t);if(!o)return!1;const a={id:O.id,params:{unitId:i.unitId,actions:[],textRanges:void 0}},u=r.JSONX.getInstance(),d=r.BuildTextUtils.customRange.add({...i,body:e});if(!d)return!1;const f=y(o,n);return a.params.actions=u.editOp(d.serialize(),f),a}function de(c,i){var p;const{rangeId:e,rangeType:t,wholeEntity:n,properties:s,unitId:o,selections:a}=i,u=c.get(l.DocSelectionManagerService),d=c.get(r.IUniverInstanceService),f=a!=null?a:u.getTextRanges({unitId:o,subUnitId:o}),h=(p=f==null?void 0:f[0])==null?void 0:p.segmentId;if(!(f!=null&&f.length))return!1;const I=d.getUnit(o,r.UniverInstanceType.UNIVER_DOC);if(!I)return!1;const _=I.getSelfOrHeaderFooterModel(h).getBody();if(!_)return!1;const S=r.BuildTextUtils.customRange.add({ranges:f,rangeId:e,rangeType:t,segmentId:h,wholeEntity:n,properties:s,body:_});if(!S)return!1;const D=r.JSONX.getInstance(),R={id:O.id,params:{unitId:o,actions:[],textRanges:S.selections,segmentId:h},textX:S},C=y(I,h);return R.params.actions=D.editOp(S.serialize(),C),R}function ge(c,i){const{unitId:e,segmentId:t,insert:n}=i,o=c.get(r.IUniverInstanceService).getUnit(e);if(!o)return!1;const a={id:O.id,params:{unitId:i.unitId,actions:[],textRanges:void 0,segmentId:t}},u=r.JSONX.getInstance(),d=r.BuildTextUtils.customRange.delete({documentDataModel:o,rangeId:i.rangeId,insert:n,segmentId:t});if(!d)return!1;const f=y(o,t);return a.params.actions=u.editOp(d.serialize(),f),a.params.textRanges=d.selections,a}function fe(c,i){var S,D,R,C;const{unitId:e,body:t,doc:n}=i;let s=n;if(s||(s=c.get(r.IUniverInstanceService).getUnit(e)),!s)return!1;const o=(S=i.selection)==null?void 0:S.segmentId,a=(D=s.getSelfOrHeaderFooterModel(o))==null?void 0:D.getBody();if(!a)return!1;const u=c.get(l.DocSelectionManagerService),d=(R=i.selection)!=null?R:u.getActiveTextRange();if(!d||!a)return!1;const f=(C=i.textRanges)!=null?C:[{startOffset:d.startOffset+t.dataStream.length,endOffset:d.startOffset+t.dataStream.length,collapsed:!0,segmentId:o}],h=r.BuildTextUtils.selection.replace({selection:d,body:t,doc:s});if(!h)return!1;const I={id:O.id,params:{unitId:e,actions:[],textRanges:f,debounce:!0,segmentId:o},textX:h},_=r.JSONX.getInstance();return I.params.actions=_.editOp(h.serialize()),I}l.DOC_INTERCEPTOR_POINT=x,l.DocStateEmitService=U,l.RichTextEditingMutation=O,l.SetTextSelectionsOperation=M,l.addCustomRangeBySelectionFactory=de,l.addCustomRangeFactory=ue,l.deleteCustomRangeFactory=ge,l.replaceSelectionFactory=fe,Object.defineProperty(l,Symbol.toStringTag,{value:"Module"})});