@univerjs/docs 1.0.0-alpha.0 → 1.0.0-alpha.2

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/umd/index.js CHANGED
@@ -1 +1,2 @@
1
- (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require("@univerjs/core"),require("@univerjs/engine-render"),require("rxjs")):typeof define==`function`&&define.amd?define([`exports`,`@univerjs/core`,`@univerjs/engine-render`,`rxjs`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.UniverDocs={},e.UniverCore,e.UniverEngineRender,e.rxjs))})(this,function(e,t,n,r){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});let i={id:`doc.operation.set-selections`,type:t.CommandType.OPERATION,handler:()=>!0};function a(e){"@babel/helpers - typeof";return a=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},a(e)}function o(e,t){if(a(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(a(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function s(e){var t=o(e,`string`);return a(t)==`symbol`?t:t+``}function c(e,t,n){return(t=s(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function l(e,t){return function(n,r){t(n,r,e)}}function u(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}let d=class extends t.RxDisposable{constructor(e,t){super(),this._commandService=e,this._univerInstanceService=t,c(this,`_currentSelection`,null),c(this,`_textSelectionInfo`,new Map),c(this,`_textSelection$`,new r.Subject),c(this,`textSelection$`,this._textSelection$.asObservable()),c(this,`_refreshSelection$`,new r.BehaviorSubject(null)),c(this,`refreshSelection$`,this._refreshSelection$.asObservable()),this._listenCurrentUnit()}_listenCurrentUnit(){this._univerInstanceService.getCurrentTypeOfUnit$(t.UniverInstanceType.UNIVER_DOC).pipe((0,r.takeUntil)(this.dispose$)).subscribe(e=>{if(e==null)return;let 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 t,n;let r=(t=this.getTextRanges(e))==null?[]:t,i=(n=this.getRectRanges(e))==null?[]:n;return[...r,...i].filter(e=>e.startOffset!=null&&e.endOffset!=null).sort((e,t)=>e.startOffset>t.startOffset?1:e.startOffset<t.startOffset?-1:0)}getActiveTextRange(){let e=this._getTextRanges(this._currentSelection);if(e==null)return;let{textRanges:t}=e;return t.find(e=>e.isActive)}getActiveRectRange(){let e=this._getTextRanges(this._currentSelection);if(e==null)return;let{rectRanges:t}=e;return t.find(e=>e.isActive)}__TEST_ONLY_add(e,t=!0){this._currentSelection!=null&&this._addByParam({...this._currentSelection,textRanges:e,rectRanges:[],segmentId:``,segmentPage:-1,isEditing:t,style:n.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,r){if(t==null)return;let{unitId:i,subUnitId:a}=t;this._refreshSelection$.next({unitId:i,subUnitId:a,docRanges:e,isEditing:n,options:r})}__replaceTextRangesWithNoRefresh(e,t){if(this._currentSelection==null)return;let n={...e,...t};this._replaceByParam(n),this._textSelection$.next(n);let{unitId:r,subUnitId:a,segmentId:o,style:s,textRanges:c,rectRanges:l,isEditing:u}=n,d=[...c,...l].filter(e=>e.startOffset!=null&&e.endOffset!=null).sort((e,t)=>e.startOffset>t.startOffset?1:e.startOffset<t.startOffset?-1:0);this._commandService.executeCommand(i.id,{unitId:r,subUnitId:a,segmentId:o,style:s,isEditing:u,ranges:d})}dispose(){this._textSelection$.complete(),this._refreshSelection$.complete()}_setCurrentSelectionNotRefresh(e){this._currentSelection=e}_getTextRanges(e){var t;if(e==null)return;let{unitId:n,subUnitId:r=``}=e;return(t=this._textSelectionInfo.get(n))==null?void 0:t.get(r)}_refresh(e){let t=this._getTextRanges(e);if(t==null)return;let{textRanges:n,rectRanges:r}=t,i=[...n,...r],{unitId:a,subUnitId:o}=e;this._refreshSelection$.next({unitId:a,subUnitId:o,docRanges:i,isEditing:!1})}_replaceByParam(e){let{unitId:t,subUnitId:n,...r}=e;this._textSelectionInfo.has(t)||this._textSelectionInfo.set(t,new Map),this._textSelectionInfo.get(t).set(n,{...r})}_addByParam(e){let{unitId:t,subUnitId:n,...r}=e;this._textSelectionInfo.has(t)||this._textSelectionInfo.set(t,new Map);let i=this._textSelectionInfo.get(t);i.has(n)?i.get(n).textRanges.push(...e.textRanges):i.set(n,{...r})}};d=u([l(0,t.ICommandService),l(1,t.IUniverInstanceService)],d);let f=class extends t.RxDisposable{constructor(e,n,i){super(),this._context=e,this._localeService=n,this._univerInstanceService=i,c(this,`_skeleton`,void 0),c(this,`_docViewModel`,void 0),c(this,`_currentSkeleton$`,new r.BehaviorSubject(null)),c(this,`currentSkeleton$`,this._currentSkeleton$.asObservable()),c(this,`_currentSkeletonBefore$`,new r.BehaviorSubject(null)),c(this,`currentSkeletonBefore$`,this._currentSkeletonBefore$.asObservable()),c(this,`_currentViewModel$`,new r.BehaviorSubject(null)),c(this,`currentViewModel$`,this._currentViewModel$.asObservable()),this._init(),this._univerInstanceService.getCurrentTypeOfUnit$(t.UniverInstanceType.UNIVER_DOC).pipe((0,r.takeUntil)(this.dispose$)).subscribe(e=>{e&&e.getUnitId()===this._context.unitId&&this._update(e)})}dispose(){super.dispose(),this._currentSkeletonBefore$.complete(),this._currentSkeleton$.complete()}getSkeleton(){return this._skeleton}getViewModel(){return this._docViewModel}_init(){let e=this._context.unit;this._update(e)}_update(e){let n=this._context.unitId;if(e.getBody()==null)return;this._docViewModel&&(0,t.isInternalEditorID)(n)?(this._docViewModel.reset(e),this._context.unit=e):this._docViewModel||(this._docViewModel=this._buildDocViewModel(e)),this._skeleton||(this._skeleton=this._buildSkeleton(this._docViewModel));let r=this._skeleton;r.calculate(),this._currentSkeletonBefore$.next(r),this._currentSkeleton$.next(r),this._currentViewModel$.next(this._docViewModel)}_buildSkeleton(e){return n.DocumentSkeleton.create(e,this._localeService)}_buildDocViewModel(e){return new n.DocumentViewModel(e)}};f=u([l(1,(0,t.Inject)(t.LocaleService)),l(2,t.IUniverInstanceService)],f);var p=class extends t.RxDisposable{constructor(){super(),c(this,`_docStateChangeParams$`,new r.BehaviorSubject(null)),c(this,`docStateChangeParams$`,this._docStateChangeParams$.asObservable())}emitStateChangeInfo(e){this._docStateChangeParams$.next(e)}dispose(){super.dispose(),this._docStateChangeParams$.complete()}};let m=`doc.mutation.rich-text-editing`,h={id:m,type:t.CommandType.MUTATION,handler:(e,r,i)=>{var a,o;let{unitId:s,segmentId:c=``,actions:l,textRanges:u,prevTextRanges:h,trigger:g,noHistory:_,isCompositionEnd:v,noNeedSetTextRange:y,debounce:b,isEditing:x=!0,isSync:S,syncer:C}=r,w=S||(i==null?void 0:i.fromCollab)||(i==null?void 0:i.fromChangeset),T=e.get(t.IUniverInstanceService),E=e.get(n.IRenderManagerService),D=e.get(p),O=T.getUnit(s,t.UniverInstanceType.UNIVER_DOC),k=(a=E.getRenderUnitById(s))==null?void 0:a.with(f).getViewModel();if(O==null)throw Error(`DocumentDataModel not found for unitId: ${s}`);let A=e.get(d),j=(o=A.getDocRanges())==null?[]:o,M=!!O.getSnapshot().disabled;if(t.JSONX.isNoop(l)||l&&l.length===0||M)return{unitId:s,actions:[],textRanges:j};let N=t.JSONX.invertWithDoc(l,O.getSnapshot());O.apply(l),k==null||k.reset(O),!y&&u&&g!=null&&!w&&queueMicrotask(()=>{A.replaceDocRanges(u,{unitId:s,subUnitId:s},x,r.options)});let P={commandId:m,unitId:s,segmentId:c,trigger:g,noHistory:_,debounce:b,redoState:{actions:l,textRanges:u},undoState:{actions:N,textRanges:h==null?j:h},isCompositionEnd:v,isSync:w,syncer:C};return D.emitStateChangeInfo(P),{unitId:s,actions:N,textRanges:j}}},g={id:`doc.command.insert-text`,type:t.CommandType.COMMAND,handler:(e,n)=>{var r;let i=e.get(t.ICommandService),{range:a,segmentId:o,body:s,unitId:c,cursorOffset:l}=n,u=e.get(d),f=e.get(t.IUniverInstanceService).getUnit(c,t.UniverInstanceType.UNIVER_DOC);if(f==null)return!1;let p=u.getActiveTextRange(),m=f.getSelfOrHeaderFooterModel((r=p==null?void 0:p.segmentId)==null?``:r).getBody();if(m==null)return!1;let{startOffset:g,collapsed:_}=a,v=l==null?s.dataStream.length:l,y=[{startOffset:g+v,endOffset:g+v,style:p==null?void 0:p.style,collapsed:_}],b={id:h.id,params:{unitId:c,actions:[],textRanges:y,debounce:!0}},x=new t.TextX,S=t.JSONX.getInstance();if(_)g>0&&x.push({t:t.TextXActionType.RETAIN,len:g}),x.push({t:t.TextXActionType.INSERT,body:s,len:s.dataStream.length});else{let e=t.BuildTextUtils.selection.delete([a],m,0,s);x.push(...e)}b.params.textRanges=[{startOffset:g+v,endOffset:g+v,collapsed:_}];let C=(0,t.getRichTextEditPath)(f,o);return b.params.actions=S.editOp(x.serialize(),C),!!i.syncExecuteCommand(b.id,b.params)}},_={id:`doc.command.delete-text`,type:t.CommandType.COMMAND,handler:(e,n)=>{var r;let i=e.get(t.ICommandService),a=e.get(t.IUniverInstanceService),{range:o,segmentId:s,unitId:c,direction:l,len:u=1}=n,d=a.getUnit(c,t.UniverInstanceType.UNIVER_DOC),f=d==null?void 0:d.getSelfOrHeaderFooterModel(s).getBody();if(d==null||f==null)return!1;let{startOffset:p}=o,m=l===t.DeleteDirection.LEFT?p-u:p,g=l===t.DeleteDirection.LEFT?p-1:p+u-1,_=(r=f.customRanges)==null?void 0:r.find(e=>e.startIndex<=m&&e.endIndex>=g);_!=null&&_.wholeEntity&&(m=_.startIndex,g=Math.max(g,_.endIndex));let v={id:h.id,params:{unitId:c,actions:[],textRanges:[{startOffset:m,endOffset:m,collapsed:!0}],debounce:!0}},y=new t.TextX,b=t.JSONX.getInstance();y.push({t:t.TextXActionType.RETAIN,len:m-0}),y.push({t:t.TextXActionType.DELETE,len:g-m+1});let x=(0,t.getRichTextEditPath)(d,s);return v.params.actions=b.editOp(y.serialize(),x),!!i.syncExecuteCommand(v.id,v.params)}},v={id:`doc.command.update-text`,type:t.CommandType.COMMAND,handler:(e,n)=>{let{range:r,segmentId:i,updateBody:a,coverType:o,unitId:s,textRanges:c}=n,l=e.get(t.ICommandService),u=e.get(t.IUniverInstanceService).getCurrentUniverDocInstance();if(u==null)return!1;let d={id:h.id,params:{unitId:s,actions:[],textRanges:c}},f=new t.TextX,p=t.JSONX.getInstance(),{startOffset:m,endOffset:g}=r;f.push({t:t.TextXActionType.RETAIN,len:m}),f.push({t:t.TextXActionType.RETAIN,body:a,len:g-m,coverType:o});let _=(0,t.getRichTextEditPath)(u,i);return d.params.actions=p.editOp(f.serialize(),_),!!l.syncExecuteCommand(d.id,d.params)}};var y=`@univerjs/docs`,b=`1.0.0-alpha.0`;let x={id:`doc.mutation.rename-doc`,type:t.CommandType.MUTATION,handler:(e,n)=>{let r=e.get(t.IUniverInstanceService).getUnit(n.unitId,t.UniverInstanceType.UNIVER_DOC);return r?(r.setName(n.name),!0):!1}},S={},C=class extends t.Disposable{constructor(e,t,n){super(),this._commandService=e,this._textSelectionManagerService=t,this._univerInstanceService=n,this._initSelectionChange()}_transformCustomRange(e,n){var r;let{startOffset:i,endOffset:a,collapsed:o}=n,s=(r=e.getCustomRanges())==null?void 0:r.filter(e=>!e.wholeEntity||i<=e.startIndex&&a>e.endIndex?!1:o?e.startIndex<i&&e.endIndex>=a:t.BuildTextUtils.range.isIntersects(i,a-1,e.startIndex,e.endIndex));if(s!=null&&s.length){let e=i,t=a;return s.forEach(n=>{e=Math.min(n.startIndex,e),t=Math.max(n.endIndex+1,t)}),{...n,startOffset:e,endOffset:t,collapsed:e===t}}return n}_initSelectionChange(){this.disposeWithMe(this._commandService.onCommandExecuted(e=>{if(e.id===i.id){let{unitId:t,ranges:n,isEditing:r}=e.params,i=this._univerInstanceService.getUnit(t);if(!i)return;let a=n.map(e=>this._transformCustomRange(i,e));a.some((e,t)=>n[t]!==e)&&this._textSelectionManagerService.replaceTextRanges(a,r)}}))}};C=u([l(0,t.ICommandService),l(1,(0,t.Inject)(d)),l(2,t.IUniverInstanceService)],C);var w=class extends t.Disposable{constructor(...e){super(...e),c(this,`_range`,null)}setInsertRange(e){this._range=e}consumeInsertRange(e){if(!this._range||e&&this._range.unitId!==e)return null;let t=this._range;return this._range=null,t}clearInsertRange(){this._range=null}};let T=(0,t.createIdentifier)(`doc.state-change-interceptor-service`),E=class extends t.RxDisposable{constructor(e,t,n,i,a){super(),this._undoRedoService=e,this._commandService=t,this._univerInstanceService=n,this._docStateEmitService=i,this._docStateChangeInterceptorService=a,c(this,`_docStateChange$`,new r.BehaviorSubject(null)),c(this,`docStateChange$`,this._docStateChange$.asObservable()),c(this,`_historyStateCache`,new Map),c(this,`_changeStateCache`,new Map),c(this,`_historyTimer`,null),c(this,`_changeStateCacheTimer`,null),this._initialize(),this._listenDocStateChange()}getStateCache(e){var t,n;return{history:(t=this._historyStateCache.get(e))==null?[]:t,collaboration:(n=this._changeStateCache.get(e))==null?[]:n}}setStateCache(e,t){this._historyStateCache.set(e,t.history),this._changeStateCache.set(e,t.collaboration)}_setChangeState(e){this._cacheChangeState(e,`history`),this._cacheChangeState(e,`collaboration`)}_initialize(){this.disposeWithMe(this._commandService.beforeCommandExecuted(e=>{if(e.id===t.UndoCommandId||e.id===t.RedoCommandId){let e=this._univerInstanceService.getCurrentUniverDocInstance();if(e==null)return;let t=e.getUnitId();this._pushHistory(t),this._emitChangeState(t)}}))}_listenDocStateChange(){this._docStateEmitService.docStateChangeParams$.pipe((0,r.takeUntil)(this.dispose$)).subscribe(e=>{var t,n;if(e==null)return;let r=(t=(n=this._docStateChangeInterceptorService)==null?void 0:n.transformChangeStateInfo(e))==null?e:t;if(r==null||r.isSync)return;let{isCompositionEnd:i,isSync:a,syncer:o,...s}=r;this._setChangeState(s)})}_cacheChangeState(e,n=`history`){let{trigger:r,unitId:i,noHistory:a,debounce:o=!1}=e;if(a||n===`history`&&r==null||n===`history`&&(r===t.RedoCommandId||r===t.UndoCommandId))return;let s=n===`history`?this._historyStateCache:this._changeStateCache,c=n===`history`?this._pushHistory.bind(this):this._emitChangeState.bind(this);if(s.has(i)){let t=s.get(i);t==null||t.push(e)}else s.set(i,[e]);o?n===`history`?(this._historyTimer&&clearTimeout(this._historyTimer),this._historyTimer=setTimeout(()=>{c(i)},300)):(this._changeStateCacheTimer&&clearTimeout(this._changeStateCacheTimer),this._changeStateCacheTimer=setTimeout(()=>{c(i)},300)):c(i)}_pushHistory(e){let n=this._undoRedoService,r=this._historyStateCache.get(e);if(n==null||!Array.isArray(r)||r.length===0)return;let i=r.length,a=r[0].commandId,o=r[0],s=r[i-1],c={unitId:e,actions:r.reduce((e,n)=>t.JSONX.compose(e,n.redoState.actions),null),textRanges:s.redoState.textRanges},l={unitId:e,actions:r.reverse().reduce((e,n)=>t.JSONX.compose(e,n.undoState.actions),null),textRanges:o.undoState.textRanges};n.pushUndoRedo({unitID:e,undoMutations:[{id:a,params:l}],redoMutations:[{id:a,params:c}]}),r.length=0}_emitChangeState(e){let n=this._changeStateCache.get(e);if(!Array.isArray(n)||n.length===0)return;let r=n.length,{commandId:i,trigger:a,segmentId:o,noHistory:s,debounce:c}=n[0],l=n[0],u=n[r-1],d={commandId:i,unitId:e,trigger:a,redoState:{unitId:e,actions:n.reduce((e,n)=>t.JSONX.compose(e,n.redoState.actions),null),textRanges:u.redoState.textRanges},undoState:{unitId:e,actions:n.reverse().reduce((e,n)=>t.JSONX.compose(e,n.undoState.actions),null),textRanges:l.undoState.textRanges},segmentId:o,noHistory:s,debounce:c};n.length=0,this._docStateChange$.next(d)}};E=u([l(0,(0,t.Optional)(t.IUndoRedoService)),l(1,t.ICommandService),l(2,t.IUniverInstanceService),l(3,(0,t.Inject)(p)),l(4,(0,t.Optional)(T))],E);let D=class extends t.Plugin{constructor(e=S,n,r){super(),this._config=e,this._injector=n,this._configService=r;let{...i}=(0,t.merge)({},S,this._config);this._configService.setConfig(`docs.config`,i)}onStarting(){this._initializeDependencies(),this._initializeCommands()}_initializeCommands(){[g,_,v,h,x,i].forEach(e=>{this._injector.get(t.ICommandService).registerCommand(e)})}_initializeDependencies(){[[d],[p],[E],[w],[C]].forEach(e=>this._injector.add(e))}onReady(){this._injector.get(E),this._injector.get(C)}};c(D,`pluginName`,`DOCS_PLUGIN`),c(D,`packageName`,y),c(D,`version`,b),D=u([l(1,(0,t.Inject)(t.Injector)),l(2,t.IConfigService)],D);let O={CUSTOM_RANGE:(0,t.createInterceptorKey)(`CUSTOM_RANGE`),CUSTOM_DECORATION:(0,t.createInterceptorKey)(`CUSTOM_DECORATION`)},k=class extends t.Disposable{constructor(e,n){super(),this._context=e,this._docSkeletonManagerService=n,c(this,`_interceptorsByName`,new Map);let r=this._docSkeletonManagerService.getViewModel(),i=r.getDataModel().getUnitId();if(i===t.DOCS_NORMAL_EDITOR_UNIT_ID_KEY||i===t.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY)return;this.disposeWithMe(this.interceptDocumentViewModel(r)),this.disposeWithMe(this.intercept(O.CUSTOM_RANGE,{priority:-1,handler:(e,t,n)=>n(e)}));let a=new t.DisposableCollection;r.segmentViewModels$.subscribe(e=>{a.dispose(),a=new t.DisposableCollection,e.forEach(e=>{a.add(this.interceptDocumentViewModel(e))})}),this.disposeWithMe(a)}intercept(e,n){let r=e;this._interceptorsByName.has(r)||this._interceptorsByName.set(r,[]);let i=this._interceptorsByName.get(r);return i.push(n),this._interceptorsByName.set(r,i.sort((e,t)=>{var n,r;return((n=t.priority)==null?0:n)-((r=e.priority)==null?0:r)})),this.disposeWithMe((0,t.toDisposable)(()=>(0,t.remove)(this._interceptorsByName.get(r),n)))}fetchThroughInterceptors(e){let n=e;return(0,t.composeInterceptors)(this._interceptorsByName.get(n)||[])}interceptDocumentViewModel(e){let n=new t.DisposableCollection;return n.add(e.registerCustomRangeInterceptor({getCustomRange:t=>{var n;return this.fetchThroughInterceptors(O.CUSTOM_RANGE)(e.getCustomRangeRaw(t),{index:t,unitId:e.getDataModel().getUnitId(),customRanges:(n=e.getDataModel().getCustomRanges())==null?[]:n})},getCustomDecoration:t=>{var n;return this.fetchThroughInterceptors(O.CUSTOM_DECORATION)(e.getCustomDecorationRaw(t),{index:t,unitId:e.getDataModel().getUnitId(),customDecorations:(n=e.getDataModel().getCustomDecorations())==null?[]:n})}})),n}};k=u([l(1,(0,t.Inject)(f))],k);function A(e,n,r){let{unitId:i,segmentId:a}=n,o=e.get(t.IUniverInstanceService).getUnit(i);if(!o)return!1;let s={id:h.id,params:{unitId:n.unitId,actions:[],textRanges:void 0}},c=t.JSONX.getInstance(),l=t.BuildTextUtils.customRange.add({...n,body:r});if(!l)return!1;let u=(0,t.getRichTextEditPath)(o,a);return s.params.actions=c.editOp(l.serialize(),u),s}function j(e,n){var r;let{rangeId:i,rangeType:a,wholeEntity:o,properties:s,unitId:c,selections:l}=n,u=e.get(d),f=e.get(t.IUniverInstanceService),p=l==null?u.getTextRanges({unitId:c,subUnitId:c}):l,m=p==null||(r=p[0])==null?void 0:r.segmentId;if(!(p!=null&&p.length))return!1;let g=f.getUnit(c,t.UniverInstanceType.UNIVER_DOC);if(!g)return!1;let _=g.getSelfOrHeaderFooterModel(m).getBody();if(!_)return!1;let v=t.BuildTextUtils.customRange.add({ranges:p,rangeId:i,rangeType:a,segmentId:m,wholeEntity:o,properties:s,body:_});if(!v)return!1;let y=t.JSONX.getInstance(),b={id:h.id,params:{unitId:c,actions:[],textRanges:v.selections,segmentId:m},textX:v},x=(0,t.getRichTextEditPath)(g,m);return b.params.actions=y.editOp(v.serialize(),x),b}function M(e,n){let{unitId:r,segmentId:i,insert:a}=n,o=e.get(t.IUniverInstanceService).getUnit(r);if(!o)return!1;let s={id:h.id,params:{unitId:n.unitId,actions:[],textRanges:void 0,segmentId:i}},c=t.JSONX.getInstance(),l=t.BuildTextUtils.customRange.delete({documentDataModel:o,rangeId:n.rangeId,insert:a,segmentId:i});if(!l)return!1;let u=(0,t.getRichTextEditPath)(o,i);return s.params.actions=c.editOp(l.serialize(),u),s.params.textRanges=l.selections,s}function N(e,n){var r,i,a,o;let{unitId:s,body:c,doc:l}=n,u=l;if(u||(u=e.get(t.IUniverInstanceService).getUnit(s)),!u)return!1;let f=(r=n.selection)==null?void 0:r.segmentId,p=(i=u.getSelfOrHeaderFooterModel(f))==null?void 0:i.getBody();if(!p)return!1;let m=e.get(d),g=(a=n.selection)==null?m.getActiveTextRange():a;if(!g||!p)return!1;let _=(o=n.textRanges)==null?[{startOffset:g.startOffset+c.dataStream.length,endOffset:g.startOffset+c.dataStream.length,collapsed:!0,segmentId:f}]:o,v=t.BuildTextUtils.selection.replace({selection:g,body:c,doc:u});if(!v)return!1;let y={id:h.id,params:{unitId:s,actions:[],textRanges:_,debounce:!0,segmentId:f},textX:v},b=t.JSONX.getInstance();return y.params.actions=b.editOp(v.serialize()),y}e.DOC_INTERCEPTOR_POINT=O,e.DeleteTextCommand=_,e.DocContentInsertService=w,Object.defineProperty(e,"DocInterceptorService",{enumerable:!0,get:function(){return k}}),Object.defineProperty(e,"DocSelectionManagerService",{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,"DocSkeletonManagerService",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"DocStateChangeManagerService",{enumerable:!0,get:function(){return E}}),e.DocStateEmitService=p,e.IDocStateChangeInterceptorService=T,e.InsertTextCommand=g,e.RichTextEditingMutation=h,e.SetTextSelectionsOperation=i,Object.defineProperty(e,"UniverDocsPlugin",{enumerable:!0,get:function(){return D}}),e.UpdateTextCommand=v,e.addCustomRangeBySelectionFactory=j,e.addCustomRangeFactory=A,e.deleteCustomRangeFactory=M,e.replaceSelectionFactory=N});
1
+ (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require("@univerjs/core"),require("@univerjs/engine-render"),require("rxjs")):typeof define==`function`&&define.amd?define([`exports`,`@univerjs/core`,`@univerjs/engine-render`,`rxjs`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.UniverDocs={},e.UniverCore,e.UniverEngineRender,e.rxjs))})(this,function(e,t,n,r){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});let i={id:`doc.operation.set-selections`,type:t.CommandType.OPERATION,handler:()=>!0};function a(e){"@babel/helpers - typeof";return a=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},a(e)}function o(e,t){if(a(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(a(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function s(e){var t=o(e,`string`);return a(t)==`symbol`?t:t+``}function c(e,t,n){return(t=s(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function l(e,t){return function(n,r){t(n,r,e)}}function u(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}let d=class extends t.RxDisposable{constructor(e,t){super(),this._commandService=e,this._univerInstanceService=t,c(this,`_currentSelection`,null),c(this,`_textSelectionInfo`,new Map),c(this,`_textSelection$`,new r.Subject),c(this,`textSelection$`,this._textSelection$.asObservable()),c(this,`_refreshSelection$`,new r.BehaviorSubject(null)),c(this,`refreshSelection$`,this._refreshSelection$.asObservable()),this._listenCurrentUnit()}_listenCurrentUnit(){this._univerInstanceService.getCurrentTypeOfUnit$(t.UniverInstanceType.UNIVER_DOC).pipe((0,r.takeUntil)(this.dispose$)).subscribe(e=>{if(e==null)return;let 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 t,n;let r=(t=this.getTextRanges(e))==null?[]:t,i=(n=this.getRectRanges(e))==null?[]:n;return[...r,...i].filter(e=>e.startOffset!=null&&e.endOffset!=null).sort((e,t)=>e.startOffset>t.startOffset?1:e.startOffset<t.startOffset?-1:0)}getActiveTextRange(){let e=this._getTextRanges(this._currentSelection);if(e==null)return;let{textRanges:t}=e;return t.find(e=>e.isActive)}getActiveRectRange(){let e=this._getTextRanges(this._currentSelection);if(e==null)return;let{rectRanges:t}=e;return t.find(e=>e.isActive)}__TEST_ONLY_add(e,t=!0){this._currentSelection!=null&&this._addByParam({...this._currentSelection,textRanges:e,rectRanges:[],segmentId:``,segmentPage:-1,isEditing:t,style:n.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,r){if(t==null)return;let{unitId:i,subUnitId:a}=t;this._refreshSelection$.next({unitId:i,subUnitId:a,docRanges:e,isEditing:n,options:r})}__replaceTextRangesWithNoRefresh(e,t){if(this._currentSelection==null)return;let n={...e,...t};this._replaceByParam(n),this._textSelection$.next(n);let{unitId:r,subUnitId:a,segmentId:o,style:s,textRanges:c,rectRanges:l,isEditing:u}=n,d=[...c,...l].filter(e=>e.startOffset!=null&&e.endOffset!=null).sort((e,t)=>e.startOffset>t.startOffset?1:e.startOffset<t.startOffset?-1:0);this._commandService.executeCommand(i.id,{unitId:r,subUnitId:a,segmentId:o,style:s,isEditing:u,ranges:d})}dispose(){this._textSelection$.complete(),this._refreshSelection$.complete()}_setCurrentSelectionNotRefresh(e){this._currentSelection=e}_getTextRanges(e){var t;if(e==null)return;let{unitId:n,subUnitId:r=``}=e;return(t=this._textSelectionInfo.get(n))==null?void 0:t.get(r)}_refresh(e){let t=this._getTextRanges(e);if(t==null)return;let{textRanges:n,rectRanges:r}=t,i=[...n,...r],{unitId:a,subUnitId:o}=e;this._refreshSelection$.next({unitId:a,subUnitId:o,docRanges:i,isEditing:!1})}_replaceByParam(e){let{unitId:t,subUnitId:n,...r}=e;this._textSelectionInfo.has(t)||this._textSelectionInfo.set(t,new Map),this._textSelectionInfo.get(t).set(n,{...r})}_addByParam(e){let{unitId:t,subUnitId:n,...r}=e;this._textSelectionInfo.has(t)||this._textSelectionInfo.set(t,new Map);let i=this._textSelectionInfo.get(t);i.has(n)?i.get(n).textRanges.push(...e.textRanges):i.set(n,{...r})}};d=u([l(0,t.ICommandService),l(1,t.IUniverInstanceService)],d);let f=class extends t.RxDisposable{constructor(e,n,i){super(),this._context=e,this._localeService=n,this._univerInstanceService=i,c(this,`_skeleton`,void 0),c(this,`_docViewModel`,void 0),c(this,`_currentSkeleton$`,new r.BehaviorSubject(null)),c(this,`currentSkeleton$`,this._currentSkeleton$.asObservable()),c(this,`_currentSkeletonBefore$`,new r.BehaviorSubject(null)),c(this,`currentSkeletonBefore$`,this._currentSkeletonBefore$.asObservable()),c(this,`_currentViewModel$`,new r.BehaviorSubject(null)),c(this,`currentViewModel$`,this._currentViewModel$.asObservable()),this._init(),this._univerInstanceService.getCurrentTypeOfUnit$(t.UniverInstanceType.UNIVER_DOC).pipe((0,r.takeUntil)(this.dispose$)).subscribe(e=>{e&&e.getUnitId()===this._context.unitId&&this._update(e)})}dispose(){super.dispose(),this._currentSkeletonBefore$.complete(),this._currentSkeleton$.complete()}getSkeleton(){return this._skeleton}getViewModel(){return this._docViewModel}_init(){let e=this._context.unit;this._update(e)}_update(e){let n=this._context.unitId;if(e.getBody()==null)return;this._docViewModel&&(0,t.isInternalEditorID)(n)?(this._docViewModel.reset(e),this._context.unit=e):this._docViewModel||(this._docViewModel=this._buildDocViewModel(e)),this._skeleton||(this._skeleton=this._buildSkeleton(this._docViewModel));let r=this._skeleton;r.calculate(),this._currentSkeletonBefore$.next(r),this._currentSkeleton$.next(r),this._currentViewModel$.next(this._docViewModel)}_buildSkeleton(e){return n.DocumentSkeleton.create(e,this._localeService)}_buildDocViewModel(e){return new n.DocumentViewModel(e)}};f=u([l(1,(0,t.Inject)(t.LocaleService)),l(2,t.IUniverInstanceService)],f);var p=class extends t.RxDisposable{constructor(){super(),c(this,`_docStateChangeParams$`,new r.BehaviorSubject(null)),c(this,`docStateChangeParams$`,this._docStateChangeParams$.asObservable())}emitStateChangeInfo(e){this._docStateChangeParams$.next(e)}dispose(){super.dispose(),this._docStateChangeParams$.complete()}};let m=`doc.mutation.rich-text-editing`,h={id:m,type:t.CommandType.MUTATION,handler:(e,r,i)=>{var a,o;let{unitId:s,segmentId:c=``,actions:l,textRanges:u,prevTextRanges:h,trigger:g,noHistory:_,isCompositionEnd:v,noNeedSetTextRange:y,debounce:b,isEditing:x=!0,isSync:S,syncer:C}=r,w=S||(i==null?void 0:i.fromCollab)||(i==null?void 0:i.fromChangeset),T=e.get(t.IUniverInstanceService),E=e.get(n.IRenderManagerService),D=e.get(p),O=T.getUnit(s,t.UniverInstanceType.UNIVER_DOC),k=(a=E.getRenderUnitById(s))==null?void 0:a.with(f).getViewModel();if(O==null)throw Error(`DocumentDataModel not found for unitId: ${s}`);let A=e.get(d),j=(o=A.getDocRanges())==null?[]:o,M=!!O.getSnapshot().disabled;if(t.JSONX.isNoop(l)||l&&l.length===0||M)return{unitId:s,actions:[],textRanges:j};let N=t.JSONX.invertWithDoc(l,O.getSnapshot());O.apply(l),k==null||k.reset(O),!y&&u&&g!=null&&!w&&queueMicrotask(()=>{A.replaceDocRanges(u,{unitId:s,subUnitId:s},x,r.options)});let P={commandId:m,unitId:s,segmentId:c,trigger:g,noHistory:_,debounce:b,redoState:{actions:l,textRanges:u},undoState:{actions:N,textRanges:h==null?j:h},isCompositionEnd:v,isSync:w,syncer:C};return D.emitStateChangeInfo(P),{unitId:s,actions:N,textRanges:j}}},g={id:`doc.command.insert-text`,type:t.CommandType.COMMAND,handler:(e,n)=>{var r,i;let a=e.get(t.ICommandService),{range:o,segmentId:s,body:c,unitId:l,cursorOffset:u}=n,f=e.get(d),p=e.get(t.IUniverInstanceService).getUnit(l,t.UniverInstanceType.UNIVER_DOC);if(p==null)return!1;let m=f.getActiveTextRange(),g=(r=p.getSelfOrHeaderFooterModel((i=m==null?void 0:m.segmentId)==null?``:i))==null?void 0:r.getBody();if(g==null)return!1;let{startOffset:_,collapsed:v}=o,y=u==null?c.dataStream.length:u,b=[{startOffset:_+y,endOffset:_+y,style:m==null?void 0:m.style,collapsed:v}],x={id:h.id,params:{unitId:l,actions:[],textRanges:b,debounce:!0}},S=new t.TextX,C=t.JSONX.getInstance();if(v)_>0&&S.push({t:t.TextXActionType.RETAIN,len:_}),S.push({t:t.TextXActionType.INSERT,body:c,len:c.dataStream.length});else{let e=t.BuildTextUtils.selection.delete([o],g,0,c);S.push(...e)}x.params.textRanges=[{startOffset:_+y,endOffset:_+y,collapsed:v}];let w=(0,t.getRichTextEditPath)(p,s);return x.params.actions=C.editOp(S.serialize(),w),!!a.syncExecuteCommand(x.id,x.params)}},_={id:`doc.command.delete-text`,type:t.CommandType.COMMAND,handler:(e,n)=>{var r,i;let a=e.get(t.ICommandService),o=e.get(t.IUniverInstanceService),{range:s,segmentId:c,unitId:l,direction:u,len:d=1}=n,f=o.getUnit(l,t.UniverInstanceType.UNIVER_DOC),p=f==null||(r=f.getSelfOrHeaderFooterModel(c))==null?void 0:r.getBody();if(f==null||p==null)return!1;let{startOffset:m}=s,g=u===t.DeleteDirection.LEFT?m-d:m,_=u===t.DeleteDirection.LEFT?m-1:m+d-1,v=(i=p.customRanges)==null?void 0:i.find(e=>e.startIndex<=g&&e.endIndex>=_);v!=null&&v.wholeEntity&&(g=v.startIndex,_=Math.max(_,v.endIndex));let y={id:h.id,params:{unitId:l,actions:[],textRanges:[{startOffset:g,endOffset:g,collapsed:!0}],debounce:!0}},b=new t.TextX,x=t.JSONX.getInstance();b.push({t:t.TextXActionType.RETAIN,len:g-0}),b.push({t:t.TextXActionType.DELETE,len:_-g+1});let S=(0,t.getRichTextEditPath)(f,c);return y.params.actions=x.editOp(b.serialize(),S),!!a.syncExecuteCommand(y.id,y.params)}},v={id:`doc.command.update-text`,type:t.CommandType.COMMAND,handler:(e,n)=>{let{range:r,segmentId:i,updateBody:a,coverType:o,unitId:s,textRanges:c}=n,l=e.get(t.ICommandService),u=e.get(t.IUniverInstanceService).getCurrentUnitOfType(t.UniverInstanceType.UNIVER_DOC);if(u==null)return!1;let d={id:h.id,params:{unitId:s,actions:[],textRanges:c}},f=new t.TextX,p=t.JSONX.getInstance(),{startOffset:m,endOffset:g}=r;f.push({t:t.TextXActionType.RETAIN,len:m}),f.push({t:t.TextXActionType.RETAIN,body:a,len:g-m,coverType:o});let _=(0,t.getRichTextEditPath)(u,i);return d.params.actions=p.editOp(f.serialize(),_),!!l.syncExecuteCommand(d.id,d.params)}},y=function(e){return e[e.FIRST_PAGE_HEADER=0]=`FIRST_PAGE_HEADER`,e[e.FIRST_PAGE_FOOTER=1]=`FIRST_PAGE_FOOTER`,e[e.DEFAULT_HEADER=2]=`DEFAULT_HEADER`,e[e.DEFAULT_FOOTER=3]=`DEFAULT_FOOTER`,e[e.EVEN_PAGE_HEADER=4]=`EVEN_PAGE_HEADER`,e[e.EVEN_PAGE_FOOTER=5]=`EVEN_PAGE_FOOTER`,e}({});function b(){return{dataStream:`\r
2
+ `,textRuns:[{st:0,ed:0,ts:{fs:9}}],customBlocks:[],paragraphs:[{startIndex:0,paragraphId:(0,t.createParagraphId)(new Set),paragraphStyle:{spaceAbove:{v:0},lineSpacing:1.5,spaceBelow:{v:0}}}],sectionBreaks:[{startIndex:1}]}}function x(e,n,r,i,a=`single`){let o=t.JSONX.getInstance(),s=e==null?(0,t.generateRandomId)(6):e,c=n===2||n===0||n===4,l=o.insertOp([c?`headers`:`footers`,s],{[c?`headerId`:`footerId`]:s,body:b()});i.push(l);let u=`defaultHeaderId`,d=`defaultFooterId`;switch(n){case 2:u=`defaultHeaderId`,d=`defaultFooterId`;break;case 3:u=`defaultFooterId`,d=`defaultHeaderId`;break;case 0:u=`firstPageHeaderId`,d=`firstPageFooterId`;break;case 1:u=`firstPageFooterId`,d=`firstPageHeaderId`;break;case 4:u=`evenPageHeaderId`,d=`evenPageFooterId`;break;case 5:u=`evenPageFooterId`,d=`evenPageHeaderId`;break;default:throw Error(`Unknown header footer type: ${n}`)}let f=[[u,s]];if(a===`pair`&&d!=null){let e=(0,t.generateRandomId)(6),n=o.insertOp([c?`footers`:`headers`,e],{[c?`footerId`:`headerId`]:e,body:b()});i.push(n),f.push([d,e])}for(let[e,t]of f)if(r[e]!=null){let n=o.replaceOp([`documentStyle`,e],r[e],t);i.push(n)}else{let n=o.insertOp([`documentStyle`,e],t);i.push(n)}return i}let S={id:`doc.command.create-header-footer`,type:t.CommandType.COMMAND,handler:(e,n)=>{let r=e.get(t.ICommandService),i=e.get(t.IUniverInstanceService),{unitId:a,segmentId:o,createType:s,headerFooterProps:c,createMode:l=`single`}=n,u=i.getUnit(a,t.UniverInstanceType.UNIVER_DOC);if(u==null)return!1;let{documentStyle:d}=u.getSnapshot();if(d.documentFlavor===t.DocumentFlavor.MODERN)return!1;let f=[],p=t.JSONX.getInstance();if(s!=null&&x(o,s,d,f,l),c!=null&&Object.keys(c).forEach(e=>{let t=c[e],n=d[e];if(t===n)return;let r=n===void 0?p.insertOp([`documentStyle`,e],t):p.replaceOp([`documentStyle`,e],n,t);f.push(r)}),f.length===0)return!1;let m={id:h.id,params:{unitId:a,actions:f.reduce((e,n)=>t.JSONX.compose(e,n),null),textRanges:[{startOffset:0,endOffset:0,collapsed:!0}],debounce:!0}};return((c==null?void 0:c.marginFooter)!=null||(c==null?void 0:c.marginHeader)!=null)&&(m.params.noNeedSetTextRange=!0),!!r.syncExecuteCommand(m.id,m.params)}};var C=`@univerjs/docs`,w=`1.0.0-alpha.2`;let T={id:`doc.mutation.rename-doc`,type:t.CommandType.MUTATION,handler:(e,n)=>{let r=e.get(t.IUniverInstanceService).getUnit(n.unitId,t.UniverInstanceType.UNIVER_DOC);return r?(r.setName(n.name),!0):!1}},E={},D=class extends t.Disposable{constructor(e,t,n){super(),this._commandService=e,this._textSelectionManagerService=t,this._univerInstanceService=n,this._initSelectionChange()}_transformCustomRange(e,n){var r;let{startOffset:i,endOffset:a,collapsed:o}=n,s=(r=e.getCustomRanges())==null?void 0:r.filter(e=>!e.wholeEntity||i<=e.startIndex&&a>e.endIndex?!1:o?e.startIndex<i&&e.endIndex>=a:t.BuildTextUtils.range.isIntersects(i,a-1,e.startIndex,e.endIndex));if(s!=null&&s.length){let e=i,t=a;return s.forEach(n=>{e=Math.min(n.startIndex,e),t=Math.max(n.endIndex+1,t)}),{...n,startOffset:e,endOffset:t,collapsed:e===t}}return n}_initSelectionChange(){this.disposeWithMe(this._commandService.onCommandExecuted(e=>{if(e.id===i.id){let{unitId:t,ranges:n,isEditing:r}=e.params,i=this._univerInstanceService.getUnit(t);if(!i)return;let a=n.map(e=>this._transformCustomRange(i,e));a.some((e,t)=>n[t]!==e)&&this._textSelectionManagerService.replaceTextRanges(a,r)}}))}};D=u([l(0,t.ICommandService),l(1,(0,t.Inject)(d)),l(2,t.IUniverInstanceService)],D);var O=class extends t.Disposable{constructor(...e){super(...e),c(this,`_validators`,[]),c(this,`_transformers`,[])}registerValidator(e){return this._validators.push(e),this.disposeWithMe((0,t.toDisposable)(()=>(0,t.remove)(this._validators,e)))}registerTransformer(e){return this._transformers.push(e),this.disposeWithMe((0,t.toDisposable)(()=>(0,t.remove)(this._transformers,e)))}canMoveBlock(e){return this._validators.every(t=>t(e))}transformMoveResult(e){return this._transformers.reduce((t,n)=>n({...e,result:t}),e.result)}},k=class extends t.Disposable{constructor(...e){super(...e),c(this,`_range`,null)}setInsertRange(e){this._range=e}consumeInsertRange(e){if(!this._range||e&&this._range.unitId!==e)return null;let t=this._range;return this._range=null,t}clearInsertRange(){this._range=null}};let A=(0,t.createIdentifier)(`doc.state-change-interceptor-service`),j=class extends t.RxDisposable{constructor(e,t,n,i,a){super(),this._undoRedoService=e,this._commandService=t,this._univerInstanceService=n,this._docStateEmitService=i,this._docStateChangeInterceptorService=a,c(this,`_docStateChange$`,new r.BehaviorSubject(null)),c(this,`docStateChange$`,this._docStateChange$.asObservable()),c(this,`_historyStateCache`,new Map),c(this,`_changeStateCache`,new Map),c(this,`_historyTimer`,null),c(this,`_changeStateCacheTimer`,null),this._initialize(),this._listenDocStateChange()}getStateCache(e){var t,n;return{history:(t=this._historyStateCache.get(e))==null?[]:t,collaboration:(n=this._changeStateCache.get(e))==null?[]:n}}setStateCache(e,t){this._historyStateCache.set(e,t.history),this._changeStateCache.set(e,t.collaboration)}_setChangeState(e){this._cacheChangeState(e,`history`),this._cacheChangeState(e,`collaboration`)}_initialize(){this.disposeWithMe(this._commandService.beforeCommandExecuted(e=>{if(e.id===t.UndoCommandId||e.id===t.RedoCommandId){let e=this._univerInstanceService.getCurrentUnitOfType(t.UniverInstanceType.UNIVER_DOC);if(e==null)return;let n=e.getUnitId();this._pushHistory(n),this._emitChangeState(n)}}))}_listenDocStateChange(){this._docStateEmitService.docStateChangeParams$.pipe((0,r.takeUntil)(this.dispose$)).subscribe(e=>{var t,n;if(e==null)return;let r=(t=(n=this._docStateChangeInterceptorService)==null?void 0:n.transformChangeStateInfo(e))==null?e:t;if(r==null||r.isSync)return;let{isCompositionEnd:i,isSync:a,syncer:o,...s}=r;this._setChangeState(s)})}_cacheChangeState(e,n=`history`){let{trigger:r,unitId:i,noHistory:a,debounce:o=!1}=e;if(a||n===`history`&&r==null||n===`history`&&(r===t.RedoCommandId||r===t.UndoCommandId))return;let s=n===`history`?this._historyStateCache:this._changeStateCache,c=n===`history`?this._pushHistory.bind(this):this._emitChangeState.bind(this);if(s.has(i)){let t=s.get(i);t==null||t.push(e)}else s.set(i,[e]);o?n===`history`?(this._historyTimer&&clearTimeout(this._historyTimer),this._historyTimer=setTimeout(()=>{c(i)},300)):(this._changeStateCacheTimer&&clearTimeout(this._changeStateCacheTimer),this._changeStateCacheTimer=setTimeout(()=>{c(i)},300)):c(i)}_pushHistory(e){let n=this._undoRedoService,r=this._historyStateCache.get(e);if(n==null||!Array.isArray(r)||r.length===0)return;let i=r.length,a=r[0].commandId,o=r[0],s=r[i-1],c={unitId:e,actions:r.reduce((e,n)=>t.JSONX.compose(e,n.redoState.actions),null),textRanges:s.redoState.textRanges},l={unitId:e,actions:r.reverse().reduce((e,n)=>t.JSONX.compose(e,n.undoState.actions),null),textRanges:o.undoState.textRanges};n.pushUndoRedo({unitID:e,undoMutations:[{id:a,params:l}],redoMutations:[{id:a,params:c}]}),r.length=0}_emitChangeState(e){let n=this._changeStateCache.get(e);if(!Array.isArray(n)||n.length===0)return;let r=n.length,{commandId:i,trigger:a,segmentId:o,noHistory:s,debounce:c}=n[0],l=n[0],u=n[r-1],d={commandId:i,unitId:e,trigger:a,redoState:{unitId:e,actions:n.reduce((e,n)=>t.JSONX.compose(e,n.redoState.actions),null),textRanges:u.redoState.textRanges},undoState:{unitId:e,actions:n.reverse().reduce((e,n)=>t.JSONX.compose(e,n.undoState.actions),null),textRanges:l.undoState.textRanges},segmentId:o,noHistory:s,debounce:c};n.length=0,this._docStateChange$.next(d)}};j=u([l(0,(0,t.Optional)(t.IUndoRedoService)),l(1,t.ICommandService),l(2,t.IUniverInstanceService),l(3,(0,t.Inject)(p)),l(4,(0,t.Optional)(A))],j);let M=class extends t.Plugin{constructor(e=E,n,r){super(),this._config=e,this._injector=n,this._configService=r;let{...i}=(0,t.merge)({},E,this._config);this._configService.setConfig(`docs.config`,i)}onStarting(){this._initializeDependencies(),this._initializeCommands()}_initializeCommands(){[g,_,v,S,h,T,i].forEach(e=>{this._injector.get(t.ICommandService).registerCommand(e)})}_initializeDependencies(){[[d],[p],[j],[O],[k],[D]].forEach(e=>this._injector.add(e))}onReady(){this._injector.get(j),this._injector.get(D)}};c(M,`pluginName`,`DOCS_PLUGIN`),c(M,`packageName`,C),c(M,`version`,w),M=u([l(1,(0,t.Inject)(t.Injector)),l(2,t.IConfigService)],M);let N={CUSTOM_RANGE:(0,t.createInterceptorKey)(`CUSTOM_RANGE`),CUSTOM_DECORATION:(0,t.createInterceptorKey)(`CUSTOM_DECORATION`)},P=class extends t.Disposable{constructor(e,n){super(),this._context=e,this._docSkeletonManagerService=n,c(this,`_interceptorsByName`,new Map);let r=this._docSkeletonManagerService.getViewModel(),i=r.getDataModel().getUnitId();if(i===t.DOCS_NORMAL_EDITOR_UNIT_ID_KEY||i===t.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY)return;this.disposeWithMe(this.interceptDocumentViewModel(r)),this.disposeWithMe(this.intercept(N.CUSTOM_RANGE,{priority:-1,handler:(e,t,n)=>n(e)}));let a=new t.DisposableCollection;r.segmentViewModels$.subscribe(e=>{a.dispose(),a=new t.DisposableCollection,e.forEach(e=>{a.add(this.interceptDocumentViewModel(e))})}),this.disposeWithMe(a)}intercept(e,n){let r=e;this._interceptorsByName.has(r)||this._interceptorsByName.set(r,[]);let i=this._interceptorsByName.get(r);return i.push(n),this._interceptorsByName.set(r,i.sort((e,t)=>{var n,r;return((n=t.priority)==null?0:n)-((r=e.priority)==null?0:r)})),this.disposeWithMe((0,t.toDisposable)(()=>(0,t.remove)(this._interceptorsByName.get(r),n)))}fetchThroughInterceptors(e){let n=e;return(0,t.composeInterceptors)(this._interceptorsByName.get(n)||[])}interceptDocumentViewModel(e){let n=new t.DisposableCollection;return n.add(e.registerCustomRangeInterceptor({getCustomRange:t=>{var n;return this.fetchThroughInterceptors(N.CUSTOM_RANGE)(e.getCustomRangeRaw(t),{index:t,unitId:e.getDataModel().getUnitId(),customRanges:(n=e.getDataModel().getCustomRanges())==null?[]:n})},getCustomDecoration:t=>{var n;return this.fetchThroughInterceptors(N.CUSTOM_DECORATION)(e.getCustomDecorationRaw(t),{index:t,unitId:e.getDataModel().getUnitId(),customDecorations:(n=e.getDataModel().getCustomDecorations())==null?[]:n})}})),n}};P=u([l(1,(0,t.Inject)(f))],P);function F(e,n,r){let{unitId:i,segmentId:a}=n,o=e.get(t.IUniverInstanceService).getUnit(i);if(!o)return!1;let s={id:h.id,params:{unitId:n.unitId,actions:[],textRanges:void 0}},c=t.JSONX.getInstance(),l=t.BuildTextUtils.customRange.add({...n,body:r});if(!l)return!1;let u=(0,t.getRichTextEditPath)(o,a);return s.params.actions=c.editOp(l.serialize(),u),s}function I(e,n){var r,i;let{rangeId:a,rangeType:o,wholeEntity:s,properties:c,unitId:l,selections:u}=n,f=e.get(d),p=e.get(t.IUniverInstanceService),m=u==null?f.getTextRanges({unitId:l,subUnitId:l}):u,g=m==null||(r=m[0])==null?void 0:r.segmentId;if(!(m!=null&&m.length))return!1;let _=p.getUnit(l,t.UniverInstanceType.UNIVER_DOC);if(!_)return!1;let v=(i=_.getSelfOrHeaderFooterModel(g))==null?void 0:i.getBody();if(!v)return!1;let y=t.BuildTextUtils.customRange.add({ranges:m,rangeId:a,rangeType:o,segmentId:g,wholeEntity:s,properties:c,body:v});if(!y)return!1;let b=t.JSONX.getInstance(),x={id:h.id,params:{unitId:l,actions:[],textRanges:y.selections,segmentId:g},textX:y},S=(0,t.getRichTextEditPath)(_,g);return x.params.actions=b.editOp(y.serialize(),S),x}function L(e,n){let{unitId:r,segmentId:i,insert:a}=n,o=e.get(t.IUniverInstanceService).getUnit(r);if(!o)return!1;let s={id:h.id,params:{unitId:n.unitId,actions:[],textRanges:void 0,segmentId:i}},c=t.JSONX.getInstance(),l=t.BuildTextUtils.customRange.delete({documentDataModel:o,rangeId:n.rangeId,insert:a,segmentId:i});if(!l)return!1;let u=(0,t.getRichTextEditPath)(o,i);return s.params.actions=c.editOp(l.serialize(),u),s.params.textRanges=l.selections,s}function R(e,n){var r,i,a,o;let{unitId:s,body:c,doc:l}=n,u=l;if(u||(u=e.get(t.IUniverInstanceService).getUnit(s)),!u)return!1;let f=(r=n.selection)==null?void 0:r.segmentId,p=(i=u.getSelfOrHeaderFooterModel(f))==null?void 0:i.getBody();if(!p)return!1;let m=e.get(d),g=(a=n.selection)==null?m.getActiveTextRange():a;if(!g||!p)return!1;let _=(o=n.textRanges)==null?[{startOffset:g.startOffset+c.dataStream.length,endOffset:g.startOffset+c.dataStream.length,collapsed:!0,segmentId:f}]:o,v=t.BuildTextUtils.selection.replace({selection:g,body:c,doc:u});if(!v)return!1;let y={id:h.id,params:{unitId:s,actions:[],textRanges:_,debounce:!0,segmentId:f},textX:v},b=t.JSONX.getInstance();return y.params.actions=b.editOp(v.serialize()),y}function z(e,t){try{return e.get(k).consumeInsertRange(t)}catch{return null}}function B(e){return!!(e!=null&&e.segmentId)}e.CreateHeaderFooterCommand=S,e.DOC_INTERCEPTOR_POINT=N,e.DeleteTextCommand=_,e.DocBlockMoveValidatorService=O,e.DocContentInsertService=k,Object.defineProperty(e,"DocInterceptorService",{enumerable:!0,get:function(){return P}}),Object.defineProperty(e,"DocSelectionManagerService",{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,"DocSkeletonManagerService",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"DocStateChangeManagerService",{enumerable:!0,get:function(){return j}}),e.DocStateEmitService=p,e.HeaderFooterType=y,e.IDocStateChangeInterceptorService=A,e.InsertTextCommand=g,e.RichTextEditingMutation=h,e.SetTextSelectionsOperation=i,Object.defineProperty(e,"UniverDocsPlugin",{enumerable:!0,get:function(){return M}}),e.UpdateTextCommand=v,e.addCustomRangeBySelectionFactory=I,e.addCustomRangeFactory=F,e.consumeContentInsertRange=z,e.deleteCustomRangeFactory=L,e.isHeaderFooterSelection=B,e.replaceSelectionFactory=R});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@univerjs/docs",
3
- "version": "1.0.0-alpha.0",
3
+ "version": "1.0.0-alpha.2",
4
4
  "private": false,
5
5
  "description": "Core document model and rich-text operations for Univer Docs.",
6
6
  "author": "DreamNum Co., Ltd. <developer@univer.ai>",
@@ -62,14 +62,14 @@
62
62
  "rxjs": ">=7.0.0"
63
63
  },
64
64
  "dependencies": {
65
- "@univerjs/core": "1.0.0-alpha.0",
66
- "@univerjs/engine-render": "1.0.0-alpha.0"
65
+ "@univerjs/engine-render": "1.0.0-alpha.2",
66
+ "@univerjs/core": "1.0.0-alpha.2"
67
67
  },
68
68
  "devDependencies": {
69
69
  "rxjs": "^7.8.2",
70
70
  "typescript": "^6.0.3",
71
71
  "vitest": "^4.1.9",
72
- "@univerjs-infra/shared": "1.0.0-alpha.0"
72
+ "@univerjs-infra/shared": "1.0.0-alpha.2"
73
73
  },
74
74
  "scripts": {
75
75
  "test": "vitest run",
@@ -1,84 +0,0 @@
1
- /**
2
- * Copyright 2023-present DreamNum Co., Ltd.
3
- *
4
- * Licensed under the Apache License, Version 2.0 (the "License");
5
- * you may not use this file except in compliance with the License.
6
- * You may obtain a copy of the License at
7
- *
8
- * http://www.apache.org/licenses/LICENSE-2.0
9
- *
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
- import type { IDocumentBody } from '@univerjs/core';
17
- /**
18
- * The top-level document body element types supported by the doc facade.
19
- */
20
- export type FDocElementType = 'paragraph' | 'table' | 'blockRange' | 'customBlock';
21
- /**
22
- * Error thrown when a facade element key can no longer be resolved uniquely.
23
- *
24
- * A stale paragraph usually means the paragraph was deleted, or the document no
25
- * longer contains exactly one paragraph with the requested `paragraphId`.
26
- *
27
- * @example
28
- * ```ts
29
- * const doc = univerAPI.getActiveDocument();
30
- * if (!doc) throw new Error('No active document');
31
- *
32
- * const paragraph = doc.getBody().getChild(0).asParagraph();
33
- * paragraph.removeFromParent();
34
- *
35
- * try {
36
- * paragraph.getText();
37
- * } catch (error) {
38
- * if (error instanceof DocElementStaleError) {
39
- * console.log('The paragraph handle is stale.');
40
- * }
41
- * }
42
- * ```
43
- */
44
- export declare class DocElementStaleError extends Error {
45
- /**
46
- * Create a stale element error.
47
- * @param {string} message The error message.
48
- */
49
- constructor(message?: string);
50
- }
51
- /**
52
- * @deprecated Paragraph facade identity is now resolved directly from persisted
53
- * `paragraphId` values. This class remains as a compatibility shell for callers
54
- * that constructed document facade internals directly.
55
- *
56
- * @hideconstructor
57
- */
58
- export declare class DocElementRegistry {
59
- /**
60
- * @deprecated Paragraph facade identity is now the persisted `paragraphId`.
61
- * @throws {Error} Always throws; use `paragraph.paragraphId` instead.
62
- */
63
- getParagraphKey(_segmentId: string, _body: IDocumentBody, _paragraphIndex: number): string;
64
- /**
65
- * @deprecated Paragraph facade identity is now the persisted `paragraphId`.
66
- * @throws {Error} Always throws; resolve paragraph handles by `paragraphId` instead.
67
- */
68
- resolveParagraphStartIndex(_segmentId: string, _key: string): number;
69
- /**
70
- * @deprecated Paragraph facade identity is now the persisted `paragraphId`.
71
- * @throws {Error} Always throws; resolve paragraph handles by `paragraphId` instead.
72
- */
73
- syncParagraph(_segmentId: string, _key: string, _body: IDocumentBody): number;
74
- /**
75
- * @deprecated Paragraph facade identity is now the persisted `paragraphId`.
76
- * @throws {Error} Always throws; stale state is detected from live `paragraphId` lookups.
77
- */
78
- markStale(_segmentId: string, _key: string): void;
79
- /**
80
- * @deprecated Paragraph facade identity is now the persisted `paragraphId`.
81
- * @throws {Error} Always throws; text edits no longer need registry offset tracking.
82
- */
83
- beforeTextEdit(_segmentId: string, _startOffset: number, _endOffset: number, _insertLength: number): void;
84
- }
@@ -1,139 +0,0 @@
1
- /**
2
- * Copyright 2023-present DreamNum Co., Ltd.
3
- *
4
- * Licensed under the Apache License, Version 2.0 (the "License");
5
- * you may not use this file except in compliance with the License.
6
- * You may obtain a copy of the License at
7
- *
8
- * http://www.apache.org/licenses/LICENSE-2.0
9
- *
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
- import type { DocumentBlockRangeType } from '@univerjs/core';
17
- import type { FDocBody } from './f-doc-body';
18
- /**
19
- * A facade wrapper for document block ranges, such as callout, quote, and code blocks.
20
- *
21
- * Block range identity is backed by the persisted `IDocumentBlockRange.blockId`,
22
- * so wrappers can be re-resolved after text is inserted before the block range.
23
- *
24
- * @hideconstructor
25
- */
26
- export declare class FDocBlockRange {
27
- protected readonly _body: FDocBody;
28
- protected readonly _key: string;
29
- constructor(_body: FDocBody, _key: string);
30
- /**
31
- * Get the document element type.
32
- * @returns {'blockRange'} The literal block range element type.
33
- * @example
34
- * ```ts
35
- * const doc = univerAPI.getActiveDocument();
36
- * if (!doc) throw new Error('No active document');
37
- *
38
- * const blockRange = doc.getBody().getChild(0).asBlockRange();
39
- * console.log(blockRange.getType());
40
- * ```
41
- */
42
- getType(): 'blockRange';
43
- /**
44
- * Get the block range key.
45
- * @returns {string} The persisted `blockId` for this block range.
46
- * @example
47
- * ```ts
48
- * const doc = univerAPI.getActiveDocument();
49
- * if (!doc) throw new Error('No active document');
50
- *
51
- * const blockRange = doc.getBody().getChild(0).asBlockRange();
52
- * console.log(blockRange.getKey());
53
- * ```
54
- */
55
- getKey(): string;
56
- /**
57
- * Get the parent body facade that owns this block range.
58
- * @returns {FDocBody} The document body facade.
59
- * @example
60
- * ```ts
61
- * const doc = univerAPI.getActiveDocument();
62
- * if (!doc) throw new Error('No active document');
63
- *
64
- * const blockRange = doc.getBody().getChild(0).asBlockRange();
65
- * console.log(blockRange.getParent().getChildIndex(blockRange));
66
- * ```
67
- */
68
- getParent(): FDocBody;
69
- /**
70
- * Remove this block range and its content from the parent body.
71
- * @returns {boolean} `true` if the block range content was removed.
72
- * @example
73
- * ```ts
74
- * const doc = univerAPI.getActiveDocument();
75
- * if (!doc) throw new Error('No active document');
76
- *
77
- * const blockRange = doc.getBody().getChild(0).asBlockRange();
78
- * blockRange.removeFromParent();
79
- * ```
80
- */
81
- removeFromParent(): boolean;
82
- /**
83
- * Get the block range type.
84
- * @returns {DocumentBlockRangeType} The block type, such as callout, quote, or code.
85
- * @example
86
- * ```ts
87
- * const doc = univerAPI.getActiveDocument();
88
- * if (!doc) throw new Error('No active document');
89
- *
90
- * const blockRange = doc.getBody().getChild(0).asBlockRange();
91
- * console.log(blockRange.getBlockType());
92
- * ```
93
- */
94
- getBlockType(): DocumentBlockRangeType;
95
- /**
96
- * Get the plain text inside this block range.
97
- * @returns {string} The block range text.
98
- * @example
99
- * ```ts
100
- * const doc = univerAPI.getActiveDocument();
101
- * if (!doc) throw new Error('No active document');
102
- *
103
- * const blockRange = doc.getBody().getChild(0).asBlockRange();
104
- * console.log(blockRange.getText());
105
- * ```
106
- */
107
- getText(): string;
108
- /**
109
- * Replace the plain text inside this block range.
110
- * @param {string} text The replacement text.
111
- * @returns {boolean} `true` if the block range text was replaced.
112
- * @example
113
- * ```ts
114
- * const doc = univerAPI.getActiveDocument();
115
- * if (!doc) throw new Error('No active document');
116
- *
117
- * const blockRange = doc.getBody().getChild(0).asBlockRange();
118
- * blockRange.setText('Updated block text');
119
- * ```
120
- */
121
- setText(text: string): boolean;
122
- /**
123
- * Remove this block range wrapper from the body.
124
- *
125
- * This currently removes the block range and its content, matching
126
- * `removeFromParent()`.
127
- *
128
- * @returns {boolean} `true` if the block range content was removed.
129
- * @example
130
- * ```ts
131
- * const doc = univerAPI.getActiveDocument();
132
- * if (!doc) throw new Error('No active document');
133
- *
134
- * const blockRange = doc.getBody().getChild(0).asBlockRange();
135
- * blockRange.unwrap();
136
- * ```
137
- */
138
- unwrap(): boolean;
139
- }