@univerjs/docs 0.1.17 → 0.2.0

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.
@@ -0,0 +1,25 @@
1
+ import { CustomDecorationType, IMutationInfo, ITextRange } from '@univerjs/core';
2
+ import { IAccessor } from '@wendellhu/redi';
3
+ import { IRichTextEditingMutationParams } from '../commands/mutations/core-editing.mutation';
4
+
5
+ interface IAddCustomDecorationParam {
6
+ unitId: string;
7
+ range: ITextRange;
8
+ segmentId?: string;
9
+ id: string;
10
+ type: CustomDecorationType;
11
+ }
12
+ export declare function addCustomDecorationFactory(param: IAddCustomDecorationParam): IMutationInfo<IRichTextEditingMutationParams>;
13
+ interface IAddCustomDecorationFactoryParam {
14
+ segmentId?: string;
15
+ id: string;
16
+ type: CustomDecorationType;
17
+ }
18
+ export declare function addCustomDecorationBySelectionFactory(accessor: IAccessor, param: IAddCustomDecorationFactoryParam): false | IMutationInfo<IRichTextEditingMutationParams>;
19
+ export interface IDeleteCustomRangeParam {
20
+ unitId: string;
21
+ id: string;
22
+ segmentId?: string;
23
+ }
24
+ export declare function deleteCustomDecorationFactory(accessor: IAccessor, params: IDeleteCustomRangeParam): false | IMutationInfo<IRichTextEditingMutationParams>;
25
+ export {};
@@ -0,0 +1,25 @@
1
+ import { CustomRangeType, IDocumentBody, IMutationInfo, ITextRange } from '@univerjs/core';
2
+ import { IAccessor } from '@wendellhu/redi';
3
+ import { IRichTextEditingMutationParams } from '../commands/mutations/core-editing.mutation';
4
+
5
+ interface IAddCustomRangeParam {
6
+ unitId: string;
7
+ range: ITextRange;
8
+ segmentId?: string;
9
+ rangeId: string;
10
+ rangeType: CustomRangeType;
11
+ }
12
+ export declare function addCustomRangeFactory(param: IAddCustomRangeParam, body: IDocumentBody): false | IMutationInfo<IRichTextEditingMutationParams>;
13
+ interface IAddCustomRangeFactoryParam {
14
+ segmentId?: string;
15
+ rangeId: string;
16
+ rangeType: CustomRangeType;
17
+ }
18
+ export declare function addCustomRangeBySelectionFactory(accessor: IAccessor, param: IAddCustomRangeFactoryParam): false | IMutationInfo<IRichTextEditingMutationParams>;
19
+ export interface IDeleteCustomRangeParam {
20
+ unitId: string;
21
+ rangeId: string;
22
+ segmentId?: string;
23
+ }
24
+ export declare function deleteCustomRangeFactory(accessor: IAccessor, params: IDeleteCustomRangeParam): false | IMutationInfo<IRichTextEditingMutationParams>;
25
+ export {};
@@ -0,0 +1,5 @@
1
+ import { ICustomRange, DataStreamTreeTokenType } from '@univerjs/core';
2
+
3
+ export declare function isCustomRangeSplitSymbol(text: string): text is DataStreamTreeTokenType.CUSTOM_RANGE_START | DataStreamTreeTokenType.CUSTOM_RANGE_END;
4
+ export declare function isIntersecting(line1Start: number, line1End: number, line2Start: number, line2End: number): boolean;
5
+ export declare function shouldDeleteCustomRange(deleteStart: number, deleteLen: number, customRange: ICustomRange, dataStream: string): boolean;
@@ -1,3 +1,7 @@
1
- import { IDeleteAction, IRetainAction, ITextRange } from '@univerjs/core';
1
+ import { IDeleteAction, IDocumentBody, IRetainAction, ITextRange } from '@univerjs/core';
2
2
 
3
- export declare function getRetainAndDeleteFromReplace(range: ITextRange, segmentId?: string, memoryCursor?: number): Array<IRetainAction | IDeleteAction>;
3
+ export declare function getRetainAndDeleteFromReplace(range: ITextRange, segmentId: string | undefined, memoryCursor: number, body: IDocumentBody): {
4
+ dos: (IRetainAction | IDeleteAction)[];
5
+ cursor: number;
6
+ retain: number;
7
+ };
@@ -0,0 +1,28 @@
1
+ import { IDocumentBody, ITextRange, Nullable } from '@univerjs/core';
2
+
3
+ export declare function normalizeSelection(selection: ITextRange): {
4
+ startOffset: number;
5
+ endOffset: number;
6
+ collapsed: boolean;
7
+ };
8
+ export declare function getSelectionWithSymbolMax(selection: ITextRange, body: IDocumentBody): {
9
+ startOffset: number;
10
+ endOffset: number;
11
+ };
12
+ export declare function getSelectionWithNoSymbolSide(selection: ITextRange, body: IDocumentBody): {
13
+ startOffset: number;
14
+ endOffset: number;
15
+ };
16
+ export declare function getDeleteSelection(selection: ITextRange, body: IDocumentBody): {
17
+ collapsed: boolean;
18
+ startOffset: number;
19
+ endOffset: number;
20
+ };
21
+ export declare function getInsertSelection(selection: ITextRange, body: IDocumentBody): ITextRange;
22
+ /**
23
+ * Ensure custom-range has a correct order,
24
+ * when range contains range, it won't be present as intersect. <br/>
25
+ * For Example `\s1\s2 text \s1\s2` is not allowed, expect `\s1\s2 text \s2\s1`
26
+ */
27
+ export declare function getSelectionForAddCustomRange(selection: ITextRange, body: IDocumentBody): Nullable<ITextRange>;
28
+ export declare function getSelectionText(dataStream: string, start: number, end: number): string;
@@ -5,12 +5,12 @@ import { DocumentSkeleton, IRender, IRenderContext, IRenderModule, DocumentViewM
5
5
  export declare function createCommandTestBed(workbookData?: IDocumentData, dependencies?: Dependency[]): {
6
6
  univer: Univer;
7
7
  get: {
8
- <T>(id: DependencyIdentifier<T>, lookUp?: import('@wendellhu/redi').LookUp | undefined): T;
9
- <T_1>(id: DependencyIdentifier<T_1>, quantity: import("@wendellhu/redi").Quantity.MANY, lookUp?: import('@wendellhu/redi').LookUp | undefined): T_1[];
10
- <T_2>(id: DependencyIdentifier<T_2>, quantity: import("@wendellhu/redi").Quantity.OPTIONAL, lookUp?: import('@wendellhu/redi').LookUp | undefined): T_2 | null;
11
- <T_3>(id: DependencyIdentifier<T_3>, quantity: import("@wendellhu/redi").Quantity.REQUIRED, lookUp?: import('@wendellhu/redi').LookUp | undefined): T_3;
12
- <T_4>(id: DependencyIdentifier<T_4>, quantity?: import('@wendellhu/redi').Quantity | undefined, lookUp?: import('@wendellhu/redi').LookUp | undefined): T_4 | T_4[] | null;
13
- <T_5>(id: DependencyIdentifier<T_5>, quantityOrLookup?: import('@wendellhu/redi').Quantity | import('@wendellhu/redi').LookUp | undefined, lookUp?: import('@wendellhu/redi').LookUp | undefined): T_5 | T_5[] | null;
8
+ <T>(id: DependencyIdentifier<T>, lookUp?: import('@wendellhu/redi').LookUp): T;
9
+ <T>(id: DependencyIdentifier<T>, quantity: import("@wendellhu/redi").Quantity.MANY, lookUp?: import('@wendellhu/redi').LookUp): T[];
10
+ <T>(id: DependencyIdentifier<T>, quantity: import("@wendellhu/redi").Quantity.OPTIONAL, lookUp?: import('@wendellhu/redi').LookUp): T | null;
11
+ <T>(id: DependencyIdentifier<T>, quantity: import("@wendellhu/redi").Quantity.REQUIRED, lookUp?: import('@wendellhu/redi').LookUp): T;
12
+ <T>(id: DependencyIdentifier<T>, quantity?: import('@wendellhu/redi').Quantity, lookUp?: import('@wendellhu/redi').LookUp): T[] | T | null;
13
+ <T>(id: DependencyIdentifier<T>, quantityOrLookup?: import('@wendellhu/redi').Quantity | import('@wendellhu/redi').LookUp, lookUp?: import('@wendellhu/redi').LookUp): T[] | T | null;
14
14
  };
15
15
  doc: DocumentDataModel;
16
16
  };
@@ -5,8 +5,9 @@ export interface IInsertCommandParams {
5
5
  unitId: string;
6
6
  body: IDocumentBody;
7
7
  range: ITextRange;
8
- textRanges: ITextRangeWithStyle[];
8
+ textRanges?: ITextRangeWithStyle[];
9
9
  segmentId?: string;
10
+ cursorOffset?: number;
10
11
  }
11
12
  export declare const EditorInsertTextCommandId = "doc.command.insert-text";
12
13
  /**
@@ -21,7 +22,6 @@ export interface IDeleteCommandParams {
21
22
  unitId: string;
22
23
  range: ITextRange;
23
24
  direction: DeleteDirection;
24
- textRanges: ITextRangeWithStyle[];
25
25
  len?: number;
26
26
  segmentId?: string;
27
27
  }
@@ -2,11 +2,11 @@ import { ICommand } from '@univerjs/core';
2
2
  import { IActiveTextRange } from '@univerjs/engine-render';
3
3
  import { DeleteDirection } from './core-editing.command';
4
4
 
5
- export declare const DeleteLeftCommand: ICommand;
6
- export declare const DeleteRightCommand: ICommand;
7
5
  interface IMergeTwoParagraphParams {
8
6
  direction: DeleteDirection;
9
7
  range: IActiveTextRange;
10
8
  }
11
9
  export declare const MergeTwoParagraphCommand: ICommand<IMergeTwoParagraphParams>;
10
+ export declare const DeleteLeftCommand: ICommand;
11
+ export declare const DeleteRightCommand: ICommand;
12
12
  export {};
@@ -1,4 +1,5 @@
1
1
  import { IAccessor } from '@wendellhu/redi';
2
+ import { DocumentDataModel } from '@univerjs/core';
2
3
  import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.service';
3
4
 
4
5
  /**
@@ -7,3 +8,4 @@ import { DocSkeletonManagerService } from '../services/doc-skeleton-manager.serv
7
8
  * @param unitId Unit ID.
8
9
  */
9
10
  export declare function getCommandSkeleton(accessor: IAccessor, unitId: string): DocSkeletonManagerService | undefined;
11
+ export declare function getRichTextEditPath(docDataModel: DocumentDataModel, segmentId?: string): string[];
@@ -14,7 +14,7 @@ export declare class MoveCursorController extends Disposable {
14
14
  private _handleShiftMoveSelection;
15
15
  private _handleMoveCursor;
16
16
  private _getTopOrBottomPosition;
17
- private _getSpanLeftOffsetInLine;
17
+ private _getGlyphLeftOffsetInLine;
18
18
  private _matchPositionByLeftOffset;
19
19
  private _getNextOrPrevLine;
20
20
  private _getDocObject;
@@ -13,26 +13,32 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
+ export { getSelectionText, getDeleteSelection, getInsertSelection } from './basics/selection';
16
17
  export type { IDocObjectParam } from './basics/component-tools';
17
18
  export { getDocObject, neoGetDocObject, getDocObjectById } from './basics/component-tools';
18
19
  export * from './basics/docs-view-key';
19
- export { BreakLineCommand } from './commands/commands/break-line.command';
20
- export { DeleteCommand, type ICoverCommandParams, type IDeleteCommandParams, type IInsertCommandParams, InsertCommand, type IUpdateCommandParams, UpdateCommand, EditorInsertTextCommandId, } from './commands/commands/core-editing.command';
21
- export { DeleteLeftCommand, DeleteRightCommand } from './commands/commands/delete.command';
22
- export { type IIMEInputCommandParams, IMEInputCommand } from './commands/commands/ime-input.command';
23
- export { SetInlineFormatBoldCommand, SetInlineFormatCommand, SetInlineFormatFontFamilyCommand, SetInlineFormatFontSizeCommand, SetInlineFormatItalicCommand, SetInlineFormatStrikethroughCommand, SetInlineFormatSubscriptCommand, SetInlineFormatSuperscriptCommand, SetInlineFormatTextColorCommand, SetInlineFormatUnderlineCommand, ResetInlineFormatTextBackgroundColorCommand, SetInlineFormatTextBackgroundColorCommand, } from './commands/commands/inline-format.command';
24
- export { AlignOperationCommand, AlignLeftCommand, AlignCenterCommand, AlignRightCommand, AlignJustifyCommand, } from './commands/commands/paragraph-align.command';
25
- export { BulletListCommand, OrderListCommand } from './commands/commands/list.command';
26
- export { CoverContentCommand, ReplaceContentCommand } from './commands/commands/replace-content.command';
27
- export { type IRichTextEditingMutationParams, RichTextEditingMutation, } from './commands/mutations/core-editing.mutation';
28
- export { MoveCursorOperation, MoveSelectionOperation } from './commands/operations/cursor.operation';
29
- export { type ISetTextSelectionsOperationParams, SetTextSelectionsOperation, } from './commands/operations/text-selection.operation';
30
20
  export { type IUniverDocsConfig, UniverDocsPlugin } from './doc-plugin';
31
21
  export { DocSkeletonManagerService } from './services/doc-skeleton-manager.service';
32
22
  export { TextSelectionManagerService, serializeTextRange } from './services/text-selection-manager.service';
33
23
  export { DocStateChangeManagerService, type IDocStateChangeParams } from './services/doc-state-change-manager.service';
34
24
  export { IMEInputManagerService } from './services/ime-input-manager.service';
35
- export { SelectAllOperation } from './commands/operations/select-all.operation';
25
+ export { DocCustomRangeService, type ICustomRangeHook } from './services/doc-custom-range.service';
26
+ export { BreakLineCommand } from './commands/commands/break-line.command';
36
27
  export { CutContentCommand, InnerPasteCommand } from './commands/commands/clipboard.inner.command';
37
- export { SetDocZoomRatioOperation, type ISetDocZoomRatioOperationParams } from './commands/operations/set-doc-zoom-ratio.operation';
28
+ export { InsertCommand, DeleteCommand, UpdateCommand, EditorInsertTextCommandId, type ICoverCommandParams, type IDeleteCommandParams, type IInsertCommandParams, type IUpdateCommandParams, } from './commands/commands/core-editing.command';
29
+ export { DeleteLeftCommand, DeleteRightCommand, MergeTwoParagraphCommand } from './commands/commands/delete.command';
30
+ export { IMEInputCommand, type IIMEInputCommandParams } from './commands/commands/ime-input.command';
31
+ export { SetInlineFormatBoldCommand, SetInlineFormatItalicCommand, SetInlineFormatUnderlineCommand, SetInlineFormatStrikethroughCommand, SetInlineFormatSubscriptCommand, SetInlineFormatSuperscriptCommand, SetInlineFormatFontSizeCommand, SetInlineFormatFontFamilyCommand, SetInlineFormatTextColorCommand, SetInlineFormatTextBackgroundColorCommand, ResetInlineFormatTextBackgroundColorCommand, SetInlineFormatCommand, } from './commands/commands/inline-format.command';
32
+ export { ListOperationCommand, BulletListCommand, OrderListCommand } from './commands/commands/list.command';
33
+ export { AlignOperationCommand, AlignLeftCommand, AlignCenterCommand, AlignRightCommand, AlignJustifyCommand, } from './commands/commands/paragraph-align.command';
34
+ export { ReplaceContentCommand, CoverContentCommand } from './commands/commands/replace-content.command';
38
35
  export { SetDocZoomRatioCommand } from './commands/commands/set-doc-zoom-ratio.command';
36
+ export { addCustomRangeFactory, addCustomRangeBySelectionFactory, deleteCustomRangeFactory } from './basics/custom-range-factory';
37
+ export { addCustomDecorationBySelectionFactory, addCustomDecorationFactory, deleteCustomDecorationFactory } from './basics/custom-decoration-factory';
38
+ export { DocInterceptorService } from './services/doc-interceptor/doc-interceptor.service';
39
+ export { DOC_INTERCEPTOR_POINT } from './services/doc-interceptor/interceptor-const';
40
+ export { RichTextEditingMutation, type IRichTextEditingMutationParams, } from './commands/mutations/core-editing.mutation';
41
+ export { MoveCursorOperation, MoveSelectionOperation } from './commands/operations/cursor.operation';
42
+ export { SelectAllOperation } from './commands/operations/select-all.operation';
43
+ export { SetDocZoomRatioOperation, type ISetDocZoomRatioOperationParams } from './commands/operations/set-doc-zoom-ratio.operation';
44
+ export { SetTextSelectionsOperation, type ISetTextSelectionsOperationParams, } from './commands/operations/text-selection.operation';
@@ -0,0 +1,18 @@
1
+ import { CustomRangeType } from '@univerjs/core';
2
+ import { IDisposable } from '@wendellhu/redi';
3
+
4
+ export interface ICustomRangeBase {
5
+ rangeId: string;
6
+ rangeType: CustomRangeType;
7
+ }
8
+ export interface ICustomRangeHook {
9
+ onCopyCustomRange?: (range: ICustomRangeBase) => ICustomRangeBase;
10
+ }
11
+ export declare class DocCustomRangeService {
12
+ private _customRangeHooks;
13
+ addClipboardHook(hook: ICustomRangeHook): IDisposable;
14
+ copyCustomRange(range: ICustomRangeBase): {
15
+ rangeId: string;
16
+ rangeType: CustomRangeType;
17
+ };
18
+ }
@@ -0,0 +1,13 @@
1
+ import { DocumentDataModel, IInterceptor, Disposable, DisposableCollection } from '@univerjs/core';
2
+ import { DocumentViewModel, IRenderContext, IRenderModule } from '@univerjs/engine-render';
3
+ import { DocSkeletonManagerService } from '../doc-skeleton-manager.service';
4
+
5
+ export declare class DocInterceptorService extends Disposable implements IRenderModule {
6
+ private readonly _context;
7
+ private readonly _docSkeletonManagerService;
8
+ private _interceptorsByName;
9
+ constructor(_context: IRenderContext<DocumentDataModel>, _docSkeletonManagerService: DocSkeletonManagerService);
10
+ intercept<T extends IInterceptor<any, any>>(name: T, interceptor: T): import('@wendellhu/redi').IDisposable;
11
+ fetchThroughInterceptors<T, C>(name: IInterceptor<T, C>): (initValue: import('@univerjs/core/common/type-util.js').Nullable<T>, initContext: C) => import('@univerjs/core/common/type-util.js').Nullable<T>;
12
+ interceptDocumentViewModel(viewModel: DocumentViewModel): DisposableCollection;
13
+ }
@@ -0,0 +1,14 @@
1
+ import { ICustomDecoration, ICustomDecorationForInterceptor, ICustomRange, ICustomRangeForInterceptor } from '@univerjs/core';
2
+
3
+ export declare const DOC_INTERCEPTOR_POINT: {
4
+ CUSTOM_RANGE: import('@univerjs/core').IInterceptor<ICustomRangeForInterceptor, {
5
+ index: number;
6
+ unitId: string;
7
+ customRanges: ICustomRange[];
8
+ }>;
9
+ CUSTOM_DECORATION: import('@univerjs/core').IInterceptor<ICustomDecorationForInterceptor, {
10
+ index: number;
11
+ unitId: string;
12
+ customDecorations: ICustomDecoration[];
13
+ }>;
14
+ };
@@ -15,12 +15,14 @@ export declare class DocSkeletonManagerService extends RxDisposable implements I
15
15
  readonly currentSkeleton$: import('rxjs').Observable<Nullable<DocumentSkeleton>>;
16
16
  private readonly _currentSkeletonBefore$;
17
17
  readonly currentSkeletonBefore$: import('rxjs').Observable<Nullable<DocumentSkeleton>>;
18
+ private readonly _currentViewModel$;
19
+ readonly currentViewModel$: import('rxjs').Observable<Nullable<DocumentViewModel>>;
18
20
  constructor(_context: IRenderContext<DocumentDataModel>, _localeService: LocaleService, _univerInstanceService: IUniverInstanceService);
19
21
  dispose(): void;
20
- private _init;
21
- private _update;
22
22
  getSkeleton(): DocumentSkeleton;
23
23
  getViewModel(): DocumentViewModel;
24
+ private _init;
25
+ private _update;
24
26
  private _buildSkeleton;
25
27
  private _buildDocViewModel;
26
28
  }
@@ -15,6 +15,8 @@ export declare class DocViewModelManagerService extends RxDisposable implements
15
15
  private _docViewModelMap;
16
16
  private readonly _currentDocViewModel$;
17
17
  readonly currentDocViewModel$: import('rxjs').Observable<Nullable<IDocumentViewModelManagerParam>>;
18
+ private readonly _docViewModelAdd$;
19
+ readonly docViewModelAdd$: import('rxjs').Observable<DocumentViewModel>;
18
20
  constructor(_context: IRenderContext<DocumentDataModel>, _univerInstanceService: IUniverInstanceService);
19
21
  private _initialize;
20
22
  dispose(): void;
@@ -14,6 +14,7 @@ export interface ITextActiveRange {
14
14
  direction: RANGE_DIRECTION;
15
15
  segmentId: string;
16
16
  style: ITextSelectionStyle;
17
+ segmentPage: number;
17
18
  }
18
19
  interface ITextSelectionManagerInsertParam extends ITextSelectionManagerSearchParam, ITextSelectionInnerParam {
19
20
  }
package/lib/umd/index.js CHANGED
@@ -1 +1 @@
1
- (function(d,n){typeof exports=="object"&&typeof module<"u"?n(exports,require("@univerjs/core"),require("@univerjs/engine-render"),require("rxjs"),require("@wendellhu/redi")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","@univerjs/engine-render","rxjs","@wendellhu/redi"],n):(d=typeof globalThis<"u"?globalThis:d||self,n(d.UniverDocs={},d.UniverCore,d.UniverEngineRender,d.rxjs,d["@wendellhu/redi"]))})(this,function(d,n,M,$,z){"use strict";var Zt=Object.defineProperty;var Kt=(d,n,M)=>n in d?Zt(d,n,{enumerable:!0,configurable:!0,writable:!0,value:M}):d[n]=M;var O=(d,n,M)=>Kt(d,typeof n!="symbol"?n+"":n,M);var Se;var V=(s=>(s.MAIN="__Document_Render_Main__",s.BACKGROUND="__Document_Render_Background__",s))(V||{}),De=(s=>(s.VIEW_MAIN="viewMain",s.VIEW_TOP="viewTop",s.VIEW_LEFT="viewLeft",s.VIEW_LEFT_TOP="viewLeftTop",s))(De||{});const ut=0,mt=2,gt=4,St=10,ft="normalTextSelectionPluginName";function ht(s){const{mainComponent:i,scene:e,engine:t,components:a}=s,o=i,r=a.get(V.BACKGROUND);return{document:o,docBackground:r,scene:e,engine:t}}function Ee(s,i){const e=s.getCurrentUnitForType(n.UniverInstanceType.UNIVER_DOC);if(!e)return null;const t=e.getUnitId(),a=i.getRenderById(t);if(a==null)return;const{mainComponent:o,scene:r,engine:c,components:l}=a,u=o,m=l.get(V.BACKGROUND);return{document:u,docBackground:m,scene:r,engine:c}}function pt(s,i){const e=i.getRenderById(s);if(e==null)return;const{mainComponent:t,scene:a,engine:o,components:r}=e,c=t,l=r.get(V.BACKGROUND);return{document:c,docBackground:l,scene:a,engine:o}}const he={id:"doc.operation.set-selections",type:n.CommandType.OPERATION,handler:(s,i)=>!0};var It=Object.defineProperty,vt=Object.getOwnPropertyDescriptor,Ct=(s,i,e,t)=>{for(var a=t>1?void 0:t?vt(i,e):i,o=s.length-1,r;o>=0;o--)(r=s[o])&&(a=(t?r(i,e,a):r(a))||a);return t&&a&&It(i,e,a),a},Ae=(s,i)=>(e,t)=>i(e,t,s);function F(s){const{startOffset:i,endOffset:e,collapsed:t}=s,a={startOffset:i,endOffset:e,collapsed:t};return typeof s.isActive=="function"&&(a.isActive=s.isActive()),a}d.TextSelectionManagerService=class extends n.RxDisposable{constructor(e,t){super();O(this,"_currentSelection",null);O(this,"_textSelectionInfo",new Map);O(this,"_textSelection$",new $.BehaviorSubject(null));O(this,"textSelection$",this._textSelection$.asObservable());this._textSelectionRenderManager=e,this._commandService=t,this._syncSelectionFromRenderService()}getCurrentSelection(){return this._currentSelection}getCurrentSelectionInfo(){return this._getTextRanges(this._currentSelection)}dispose(){this._textSelection$.complete()}refreshSelection(){this._currentSelection!=null&&this._refresh(this._currentSelection)}setCurrentSelection(e){this._currentSelection=e,this._refresh(e)}setCurrentSelectionNotRefresh(e){this._currentSelection=e}getSelections(){var e;return(e=this._getTextRanges(this._currentSelection))==null?void 0:e.textRanges}getActiveTextRange(){const e=this._getTextRanges(this._currentSelection);if(e==null)return;const{textRanges:t}=e;return t.find(a=>a.isActive())}getActiveRange(){const e=this._getTextRanges(this._currentSelection);if(e==null)return;const{textRanges:t,segmentId:a,style:o}=e,r=t.find(f=>f.isActive());if(r==null)return null;const{startOffset:c,endOffset:l,collapsed:u,startNodePosition:m,endNodePosition:g,direction:S}=r;return c==null||l==null?null:{startOffset:c,endOffset:l,collapsed:u,startNodePosition:m,endNodePosition:g,direction:S,segmentId:a,style:o}}add(e,t=!0){this._currentSelection!=null&&this._addByParam({...this._currentSelection,textRanges:e,segmentId:"",isEditing:t,style:M.NORMAL_TEXT_SELECTION_PLUGIN_STYLE})}replaceTextRanges(e,t=!0){this._currentSelection!=null&&(this._textSelectionRenderManager.removeAllTextRanges(),this._textSelectionRenderManager.addTextRanges(e,t))}_syncSelectionFromRenderService(){this._textSelectionRenderManager.textSelectionInner$.pipe($.takeUntil(this.dispose$)).subscribe(e=>{e!=null&&this._replaceTextRangesWithNoRefresh(e)})}_replaceTextRangesWithNoRefresh(e){if(this._currentSelection==null)return;const t={...this._currentSelection,...e};this._replaceByParam(t),this._textSelection$.next(t);const{unitId:a,subUnitId:o,segmentId:r,style:c,textRanges:l,isEditing:u}=t;this._commandService.executeCommand(he.id,{unitId:a,subUnitId:o,segmentId:r,style:c,isEditing:u,ranges:l.map(F)})}_getTextRanges(e){var o;if(e==null)return;const{unitId:t,subUnitId:a=""}=e;return(o=this._textSelectionInfo.get(t))==null?void 0:o.get(a)}_refresh(e){const t=this._getTextRanges(e);this._textSelectionRenderManager.removeAllTextRanges(),t&&Array.isArray(t.textRanges)&&t.textRanges.length&&this._textSelectionRenderManager.addTextRanges(t.textRanges.map(F))}_replaceByParam(e){const{unitId:t,subUnitId:a,style:o,segmentId:r,textRanges:c,isEditing:l}=e;this._textSelectionInfo.has(t)||this._textSelectionInfo.set(t,new Map),this._textSelectionInfo.get(t).set(a,{textRanges:c,style:o,segmentId:r,isEditing:l})}_addByParam(e){const{unitId:t,subUnitId:a,textRanges:o,style:r,segmentId:c,isEditing:l}=e;this._textSelectionInfo.has(t)||this._textSelectionInfo.set(t,new Map);const u=this._textSelectionInfo.get(t);u.has(a)?u.get(a).textRanges.push(...o):u.set(a,{textRanges:o,style:r,segmentId:c,isEditing:l})}},d.TextSelectionManagerService=Ct([Ae(0,M.ITextSelectionRenderManager),Ae(1,n.ICommandService)],d.TextSelectionManagerService);function pe(s,i="",e=0){const{startOffset:t,endOffset:a}=s,o=[],r=t-e,c=a-e;return r>0&&o.push({t:n.TextXActionType.RETAIN,len:r,segmentId:i}),o.push({t:n.TextXActionType.DELETE,len:c-r,line:0,segmentId:i}),o}var _t=Object.defineProperty,Tt=Object.getOwnPropertyDescriptor,yt=(s,i,e,t)=>{for(var a=t>1?void 0:t?Tt(i,e):i,o=s.length-1,r;o>=0;o--)(r=s[o])&&(a=(t?r(i,e,a):r(a))||a);return t&&a&&_t(i,e,a),a},Ie=(s,i)=>(e,t)=>i(e,t,s);const Ne=300;d.DocStateChangeManagerService=class extends n.RxDisposable{constructor(e,t,a){super();O(this,"_docStateChange$",new $.BehaviorSubject(null));O(this,"docStateChange$",this._docStateChange$.asObservable());O(this,"_historyStateCache",new Map);O(this,"_changeStateCache",new Map);O(this,"_historyTimer",null);O(this,"_changeStateCacheTimer",null);this._undoRedoService=e,this._commandService=t,this._univerInstanceService=a,this._initialize()}setChangeState(e){this._cacheChangeState(e,"history"),this._cacheChangeState(e,"collaboration")}_initialize(){this.disposeWithMe(this._commandService.beforeCommandExecuted(e=>{if(e.id===n.UndoCommandId||e.id===n.RedoCommandId){const t=this._univerInstanceService.getCurrentUniverDocInstance();if(t==null)return;const a=t.getUnitId();this._pushHistory(a),this._emitChangeState(a)}}))}_cacheChangeState(e,t="history"){const{trigger:a,unitId:o,noHistory:r,debounce:c=!1}=e;if(r||t==="history"&&(a===n.RedoCommandId||a===n.UndoCommandId))return;const l=t==="history"?this._historyStateCache:this._changeStateCache,u=t==="history"?this._pushHistory.bind(this):this._emitChangeState.bind(this);if(l.has(o)){const m=l.get(o);m==null||m.push(e)}else l.set(o,[e]);c?t==="history"?(this._historyTimer&&clearTimeout(this._historyTimer),this._historyTimer=setTimeout(()=>{u(o)},Ne)):(this._changeStateCacheTimer&&clearTimeout(this._changeStateCacheTimer),this._changeStateCacheTimer=setTimeout(()=>{u(o)},Ne)):u(o)}_pushHistory(e){const t=this._undoRedoService,a=this._historyStateCache.get(e);if(!Array.isArray(a)||a.length===0)return;const o=a.length,r=a[0].commandId,c=a[0],l=a[o-1],u={unitId:e,actions:a.reduce((g,S)=>n.JSONX.compose(g,S.redoState.actions),null),textRanges:l.redoState.textRanges},m={unitId:e,actions:a.reverse().reduce((g,S)=>n.JSONX.compose(g,S.undoState.actions),null),textRanges:c.undoState.textRanges};t.pushUndoRedo({unitID:e,undoMutations:[{id:r,params:m}],redoMutations:[{id:r,params:u}]}),a.length=0}_emitChangeState(e){const t=this._changeStateCache.get(e);if(!Array.isArray(t)||t.length===0)return;const a=t.length,{commandId:o,trigger:r,segmentId:c,noHistory:l,debounce:u}=t[0],m=t[0],g=t[a-1],S={unitId:e,actions:t.reduce((h,p)=>n.JSONX.compose(h,p.redoState.actions),null),textRanges:g.redoState.textRanges},f={unitId:e,actions:t.reverse().reduce((h,p)=>n.JSONX.compose(h,p.undoState.actions),null),textRanges:m.undoState.textRanges},v={commandId:o,unitId:e,trigger:r,redoState:S,undoState:f,segmentId:c,noHistory:l,debounce:u};t.length=0,this._docStateChange$.next(v)}},d.DocStateChangeManagerService=yt([Ie(0,z.Inject(n.IUndoRedoService)),Ie(1,n.ICommandService),Ie(2,n.IUniverInstanceService)],d.DocStateChangeManagerService);class H{constructor(){O(this,"_previousActiveRange",null);O(this,"_undoMutationParamsCache",[]);O(this,"_redoMutationParamsCache",[])}clearUndoRedoMutationParamsCache(){this._undoMutationParamsCache=[],this._redoMutationParamsCache=[]}getUndoRedoMutationParamsCache(){return{undoCache:this._undoMutationParamsCache,redoCache:this._redoMutationParamsCache}}setUndoRedoMutationParamsCache({undoCache:i=[],redoCache:e=[]}){this._undoMutationParamsCache=i,this._redoMutationParamsCache=e}getActiveRange(){return this._previousActiveRange}setActiveRange(i){this._previousActiveRange=i}pushUndoRedoMutationParams(i,e){this._undoMutationParamsCache.push(i),this._redoMutationParamsCache.push(e)}fetchComposedUndoRedoMutationParams(){if(this._undoMutationParamsCache.length===0||this._previousActiveRange==null||this._redoMutationParamsCache.length===0)return null;const{unitId:i}=this._undoMutationParamsCache[0],e={unitId:i,actions:this._undoMutationParamsCache.reverse().reduce((a,o)=>n.JSONX.compose(a,o.actions),null),textRanges:[]};return{redoMutationParams:{unitId:i,actions:this._redoMutationParamsCache.reduce((a,o)=>n.JSONX.compose(a,o.actions),null),textRanges:[]},undoMutationParams:e,previousActiveRange:this._previousActiveRange}}dispose(){this._undoMutationParamsCache=[],this._redoMutationParamsCache=[],this._previousActiveRange=null}}var Mt=Object.defineProperty,Ot=Object.getOwnPropertyDescriptor,Rt=(s,i,e,t)=>{for(var a=t>1?void 0:t?Ot(i,e):i,o=s.length-1,r;o>=0;o--)(r=s[o])&&(a=(t?r(i,e,a):r(a))||a);return t&&a&&Mt(i,e,a),a},be=(s,i)=>(e,t)=>i(e,t,s);d.DocSkeletonManagerService=class extends n.RxDisposable{constructor(e,t,a){super();O(this,"_skeleton");O(this,"_docViewModel");O(this,"_currentSkeleton$",new $.BehaviorSubject(null));O(this,"currentSkeleton$",this._currentSkeleton$.asObservable());O(this,"_currentSkeletonBefore$",new $.BehaviorSubject(null));O(this,"currentSkeletonBefore$",this._currentSkeletonBefore$.asObservable());this._context=e,this._localeService=t,this._univerInstanceService=a,this._init(),this._univerInstanceService.getCurrentTypeOfUnit$(n.UniverInstanceType.UNIVER_DOC).pipe($.takeUntil(this.dispose$)).subscribe(o=>{(o==null?void 0:o.getUnitId())===this._context.unitId&&this._update(o)})}dispose(){super.dispose(),this._currentSkeletonBefore$.complete(),this._currentSkeleton$.complete()}_init(){const e=this._context.unit;this._update(e)}_update(e){const t=this._context.unitId;if(e.getBody()==null)return;this._docViewModel&&t===n.DOCS_NORMAL_EDITOR_UNIT_ID_KEY?(this._docViewModel.reset(e),this._context.unit=e):this._docViewModel||(this._docViewModel=this._buildDocViewModel(e)),this._skeleton||(this._skeleton=this._buildSkeleton(this._docViewModel));const a=this._skeleton;a.calculate(),this._currentSkeletonBefore$.next(a),this._currentSkeleton$.next(a)}getSkeleton(){return this._skeleton}getViewModel(){return this._docViewModel}_buildSkeleton(e){return M.DocumentSkeleton.create(e,this._localeService)}_buildDocViewModel(e){return new M.DocumentViewModel(e)}},d.DocSkeletonManagerService=Rt([be(1,z.Inject(n.LocaleService)),be(2,n.IUniverInstanceService)],d.DocSkeletonManagerService);const Pe="doc.mutation.rich-text-editing",b={id:Pe,type:n.CommandType.MUTATION,handler:(s,i)=>{var R,E;const{unitId:e,segmentId:t="",actions:a,textRanges:o,prevTextRanges:r,trigger:c,noHistory:l,isCompositionEnd:u,noNeedSetTextRange:m,debounce:g}=i,S=s.get(n.IUniverInstanceService),f=s.get(M.IRenderManagerService),v=S.getUniverDocInstance(e),h=(R=f.getRenderById(e))==null?void 0:R.with(d.DocSkeletonManagerService).getViewModel();if(v==null||h==null)throw new Error(`DocumentDataModel or documentViewModel not found for unitId: ${e}`);const p=s.get(d.TextSelectionManagerService),I=((E=p.getSelections())!=null?E:[]).map(F),_=s.get(d.DocStateChangeManagerService),y=s.get(H),T=!!v.getSnapshot().disabled;if(n.JSONX.isNoop(a)||a&&a.length===0||T)return{unitId:e,actions:[],textRanges:I};const D=n.JSONX.invertWithDoc(a,v.getSnapshot());v.apply(a);const x=v.getSelfOrHeaderFooterModel(t);h.getSelfOrHeaderFooterViewModel(t).reset(x),!m&&o&&c!=null&&queueMicrotask(()=>{p.replaceTextRanges(o)});const A={commandId:Pe,unitId:e,segmentId:t,trigger:c,noHistory:l,debounce:g,redoState:{actions:a,textRanges:o},undoState:{actions:D,textRanges:r!=null?r:I}};if(u){const N=y.fetchComposedUndoRedoMutationParams();if(N==null)throw new Error("historyParams is null in RichTextEditingMutation");const{undoMutationParams:j,redoMutationParams:fe,previousActiveRange:L}=N;A.redoState.actions=fe.actions,A.undoState.actions=j.actions,A.undoState.textRanges=[L]}return _.setChangeState(A),{unitId:e,actions:D,textRanges:I}}},Ue="doc.command.insert-text",W={id:Ue,type:n.CommandType.COMMAND,handler:async(s,i)=>{const e=s.get(n.ICommandService),{range:t,segmentId:a,body:o,unitId:r,textRanges:c}=i,{startOffset:l,collapsed:u}=t,m={id:b.id,params:{unitId:r,actions:[],textRanges:c,debounce:!0}},g=new n.TextX,S=n.JSONX.getInstance();return u?l>0&&g.push({t:n.TextXActionType.RETAIN,len:l,segmentId:a}):g.push(...pe(t,a)),g.push({t:n.TextXActionType.INSERT,body:o,len:o.dataStream.length,line:0,segmentId:a}),m.params.actions=S.editOp(g.serialize()),!!e.syncExecuteCommand(m.id,m.params)}};var w=(s=>(s[s.LEFT=0]="LEFT",s[s.RIGHT=1]="RIGHT",s))(w||{});const Z={id:"doc.command.delete-text",type:n.CommandType.COMMAND,handler:async(s,i)=>{const e=s.get(n.ICommandService),{range:t,segmentId:a,unitId:o,direction:r,textRanges:c,len:l=1}=i,{startOffset:u}=t,m={id:b.id,params:{unitId:o,actions:[],textRanges:c,debounce:!0}},g=new n.TextX,S=n.JSONX.getInstance();return u>0&&g.push({t:n.TextXActionType.RETAIN,len:r===0?u-l:u,segmentId:a}),g.push({t:n.TextXActionType.DELETE,len:l,line:0,segmentId:a}),m.params.actions=S.editOp(g.serialize()),!!e.syncExecuteCommand(m.id,m.params)}},ve={id:"doc.command.update-text",type:n.CommandType.COMMAND,handler:async(s,i)=>{const{range:e,segmentId:t,updateBody:a,coverType:o,unitId:r,textRanges:c}=i,l=s.get(n.ICommandService),u={id:b.id,params:{unitId:r,actions:[],textRanges:c}},m=new n.TextX,g=n.JSONX.getInstance(),{startOffset:S,endOffset:f}=e;return m.push({t:n.TextXActionType.RETAIN,len:S,segmentId:t}),m.push({t:n.TextXActionType.RETAIN,body:a,len:f-S,segmentId:t,coverType:o}),u.params.actions=g.editOp(m.serialize()),!!l.syncExecuteCommand(u.id,u.params)}};function xt(s,i){const e=[];for(let t=0,a=s.length;t<a;t++)s[t]===n.DataStreamTreeTokenType.PARAGRAPH&&e.push({startIndex:t});if(i)for(const t of e)i.bullet&&(t.bullet=n.Tools.deepClone(i.bullet)),i.paragraphStyle&&(t.paragraphStyle=n.Tools.deepClone(i.paragraphStyle));return e}const Be={id:"doc.command.break-line",type:n.CommandType.COMMAND,handler:async s=>{var v,h;const i=s.get(d.TextSelectionManagerService),e=s.get(n.IUniverInstanceService),t=s.get(n.ICommandService),a=i.getActiveRange();if(a==null)return!1;const o=e.getCurrentUniverDocInstance();if(!o)return!1;const r=o.getUnitId(),{startOffset:c,segmentId:l,style:u}=a,m=[{startOffset:c+1,endOffset:c+1,style:u}],S=((h=(v=o.getBody())==null?void 0:v.paragraphs)!=null?h:[]).find(p=>p.startIndex>=c);return await t.executeCommand(W.id,{unitId:r,body:{dataStream:n.DataStreamTreeTokenType.PARAGRAPH,paragraphs:xt(n.DataStreamTreeTokenType.PARAGRAPH,S)},range:a,textRanges:m,segmentId:l})}};function Le(s,i){var t;return(t=s.get(M.IRenderManagerService).getRenderById(i))==null?void 0:t.with(d.DocSkeletonManagerService)}const Dt={id:"doc.command.inner-paste",type:n.CommandType.COMMAND,handler:async(s,i)=>{const{segmentId:e,body:t,textRanges:a}=i,o=s.get(n.ICommandService),r=s.get(d.TextSelectionManagerService),c=s.get(n.IUniverInstanceService),l=r.getSelections();if(!Array.isArray(l)||l.length===0)return!1;const u=c.getCurrentUniverDocInstance();if(!u)return!1;const m=u.getUnitId(),g={id:b.id,params:{unitId:m,actions:[],textRanges:a}},S=new n.MemoryCursor;S.reset();const f=new n.TextX,v=n.JSONX.getInstance();for(const p of l){const{startOffset:C,endOffset:I,collapsed:_}=p,y=C-S.cursor;_?f.push({t:n.TextXActionType.RETAIN,len:y,segmentId:e}):f.push(...pe(p,e,S.cursor)),f.push({t:n.TextXActionType.INSERT,body:t,len:t.dataStream.length,line:0,segmentId:e}),S.reset(),S.moveCursor(I)}return g.params.actions=v.editOp(f.serialize()),!!o.syncExecuteCommand(g.id,g.params)}},Ce={id:"doc.command.inner-cut",type:n.CommandType.COMMAND,handler:async(s,i)=>{var p;const{segmentId:e,textRanges:t}=i,a=s.get(n.ICommandService),o=s.get(d.TextSelectionManagerService),r=s.get(n.IUniverInstanceService),c=o.getSelections();if(!Array.isArray(c)||c.length===0)return!1;const l=(p=r.getCurrentUniverDocInstance())==null?void 0:p.getUnitId();if(!l)return!1;const u=r.getUniverDocInstance(l),m=n.getDocsUpdateBody(u.getSnapshot(),e);if(m==null)return!1;const g={id:b.id,params:{unitId:l,actions:[],textRanges:t}},S=new n.MemoryCursor;S.reset();const f=new n.TextX,v=n.JSONX.getInstance();for(const C of c){const{startOffset:I,endOffset:_,collapsed:y}=C,T=I-S.cursor;y?f.push({t:n.TextXActionType.RETAIN,len:T,segmentId:e}):f.push(...Et(C,m,e,S.cursor)),S.reset(),S.moveCursor(_)}return g.params.actions=v.editOp(f.serialize()),!!a.syncExecuteCommand(g.id,g.params)}};function Et(s,i,e="",t=0){const{startOffset:a,endOffset:o}=s,r=[],{paragraphs:c=[]}=i,l=a-t,u=o-t,m=c==null?void 0:c.find(g=>g.startIndex-t>=l&&g.startIndex-t<=u);if(l>0&&r.push({t:n.TextXActionType.RETAIN,len:l,segmentId:e}),m&&m.startIndex-t>l){const g=m.startIndex-t;r.push({t:n.TextXActionType.DELETE,len:g-l,line:0,segmentId:e}),r.push({t:n.TextXActionType.RETAIN,len:1,segmentId:e}),u>g+1&&r.push({t:n.TextXActionType.DELETE,len:u-g-1,line:0,segmentId:e})}else r.push({t:n.TextXActionType.DELETE,len:u-l,line:0,segmentId:e});return r}const we={id:"doc.command.delete-left",type:n.CommandType.COMMAND,handler:async s=>{const i=s.get(d.TextSelectionManagerService),e=s.get(n.IUniverInstanceService),t=s.get(n.ICommandService);let a=!0;const o=e.getCurrentUniverDocInstance();if(!o)return!1;const r=o.getUnitId(),c=Le(s,r),l=i.getActiveRange(),u=i.getSelections(),m=c==null?void 0:c.getSkeleton();if(l==null||m==null||u==null)return!1;const{startOffset:g,collapsed:S,segmentId:f,style:v}=l,h=m.findNodeByCharIndex(g),p=M.hasListGlyph(h),C=M.isIndentByGlyph(h,o.getBody());let I=g;const _=m.findNodeByCharIndex(g-1);if(M.isFirstGlyph(h)&&_!==h&&(p===!0||C===!0)&&S){const T=M.getParagraphByGlyph(h,o.getBody());if(T==null)return!1;const D=T==null?void 0:T.startIndex,x={startIndex:0},P=T.paragraphStyle;if(p===!0){const R=T.paragraphStyle;if(R){x.paragraphStyle=R;const{hanging:E}=R;E&&(x.paragraphStyle.indentStart=E,x.paragraphStyle.hanging=void 0)}}else if(C===!0){const R=T.bullet;R&&(x.bullet=R),P!=null&&(x.paragraphStyle={...P},delete x.paragraphStyle.hanging,delete x.paragraphStyle.indentStart)}const A=[{startOffset:I,endOffset:I,style:v}];a=await t.executeCommand(ve.id,{unitId:o.getUnitId(),updateBody:{dataStream:"",paragraphs:[{...x}]},range:{startOffset:D,endOffset:D+1},textRanges:A,coverType:n.UpdateDocsAttributeType.REPLACE,segmentId:f})}else if(S===!0){if(_==null)return!0;if(_.content==="\r")a=await t.executeCommand(_e.id,{direction:w.LEFT,range:l});else{I-=_.count;const T=[{startOffset:I,endOffset:I,style:v}];a=await t.executeCommand(Z.id,{unitId:o.getUnitId(),range:l,segmentId:f,direction:w.LEFT,len:_.count,textRanges:T})}}else{const T=Fe(l,u);a=await t.executeCommand(Ce.id,{segmentId:f,textRanges:T})}return a}},Xe={id:"doc.command.delete-right",type:n.CommandType.COMMAND,handler:async s=>{const i=s.get(d.TextSelectionManagerService),t=s.get(n.IUniverInstanceService).getCurrentUniverDocInstance();if(!t)return!1;const a=Le(s,t.getUnitId()),o=s.get(n.ICommandService),r=i.getActiveRange(),c=i.getSelections(),l=a==null?void 0:a.getSkeleton();if(r==null||l==null||c==null)return!1;const{startOffset:u,collapsed:m,segmentId:g,style:S}=r;if(u===t.getBody().dataStream.length-2&&m)return!0;let f=!1;if(m===!0){const v=l.findNodeByCharIndex(u);if(v.content==="\r")f=await o.executeCommand(_e.id,{direction:w.RIGHT,range:r});else{const h=[{startOffset:u,endOffset:u,style:S}];f=await o.executeCommand(Z.id,{unitId:t.getUnitId(),range:r,segmentId:g,direction:w.RIGHT,textRanges:h,len:v.count})}}else{const v=Fe(r,c);f=await o.executeCommand(Ce.id,{segmentId:g,textRanges:v})}return f}},_e={id:"doc.command.merge-two-paragraph",type:n.CommandType.COMMAND,handler:async(s,i)=>{var P,A,R;const e=s.get(d.TextSelectionManagerService),t=s.get(n.IUniverInstanceService),a=s.get(n.ICommandService),{direction:o,range:r}=i,c=e.getActiveRange(),l=e.getSelections();if(c==null||l==null)return!1;const u=t.getCurrentUniverDocInstance();if(!u)return!1;const{startOffset:m,collapsed:g,segmentId:S,style:f}=c;if(!g)return!1;const v=o===w.LEFT?m:m+1,h=(R=(A=(P=u.getBody())==null?void 0:P.paragraphs)==null?void 0:A.find(E=>E.startIndex>=v))==null?void 0:R.startIndex,p=At(u.getBody(),v,h),C=o===w.LEFT?m-1:m,I=u.getUnitId(),_=[{startOffset:C,endOffset:C,style:f}],y={id:b.id,params:{unitId:I,actions:[],textRanges:_,prevTextRanges:[r]}},T=new n.TextX,D=n.JSONX.getInstance();return T.push({t:n.TextXActionType.RETAIN,len:o===w.LEFT?m-1:m,segmentId:S}),p.dataStream.length&&T.push({t:n.TextXActionType.INSERT,body:p,len:p.dataStream.length,line:0,segmentId:S}),T.push({t:n.TextXActionType.RETAIN,len:1,segmentId:S}),T.push({t:n.TextXActionType.DELETE,len:h+1-v,line:0,segmentId:S}),y.params.actions=D.editOp(T.serialize()),!!a.syncExecuteCommand(y.id,y.params)}};function At(s,i,e){const{textRuns:t}=s,a=s.dataStream.substring(i,e);if(t==null)return{dataStream:a};const o=[];for(const r of t){const{st:c,ed:l}=r;l<=i||c>=e||(c<i?o.push({...r,st:0,ed:l-i}):l>e?o.push({...r,st:c-i,ed:e-i}):o.push({...r,st:c-i,ed:l-i}))}return{dataStream:a,textRuns:o}}function Fe(s,i){let e=s.endOffset;for(const a of i){const{startOffset:o,endOffset:r}=a;o==null||r==null||r<=s.endOffset&&(e-=r-o)}return[{startOffset:e,endOffset:e,style:s.style}]}const Te={id:"doc.command.ime-input",type:n.CommandType.COMMAND,handler:async(s,i)=>{const{unitId:e,newText:t,oldTextLen:a,isCompositionEnd:o,isCompositionStart:r}=i,c=s.get(n.ICommandService),l=s.get(H),u=l.getActiveRange();if(u==null)return!1;const{startOffset:m,style:g,segmentId:S}=u,f=t.length,v=[{startOffset:m+f,endOffset:m+f,collapsed:!0,style:g}],h={id:b.id,params:{unitId:e,actions:[],textRanges:v}},p=new n.TextX,C=n.JSONX.getInstance();!u.collapsed&&r?p.push(...pe(u,S)):p.push({t:n.TextXActionType.RETAIN,len:m,segmentId:S}),a>0&&p.push({t:n.TextXActionType.DELETE,len:a,line:0,segmentId:S}),p.push({t:n.TextXActionType.INSERT,body:{dataStream:t},len:t.length,line:0,segmentId:S}),h.params.actions=C.editOp(p.serialize()),h.params.noHistory=!o,h.params.isCompositionEnd=o;const I=c.syncExecuteCommand(h.id,h.params);return l.pushUndoRedoMutationParams(I,h.params),!!I}};function U(s,i,e,t){var o;const{segmentId:a}=(o=e.getActiveRange())!=null?o:{};return a==null?!1:t.executeCommand(ye.id,{segmentId:a,preCommandId:s,...i!=null?i:{}})}const je="doc.command.set-inline-format-bold",K={id:je,type:n.CommandType.COMMAND,handler:async(s,i)=>{const e=s.get(n.ICommandService),t=s.get(d.TextSelectionManagerService);return U(je,i,t,e)}},$e="doc.command.set-inline-format-italic",q={id:$e,type:n.CommandType.COMMAND,handler:async(s,i)=>{const e=s.get(n.ICommandService),t=s.get(d.TextSelectionManagerService);return U($e,i,t,e)}},ze="doc.command.set-inline-format-underline",Q={id:ze,type:n.CommandType.COMMAND,handler:async(s,i)=>{const e=s.get(n.ICommandService),t=s.get(d.TextSelectionManagerService);return U(ze,i,t,e)}},ke="doc.command.set-inline-format-strikethrough",ee={id:ke,type:n.CommandType.COMMAND,handler:async(s,i)=>{const e=s.get(n.ICommandService),t=s.get(d.TextSelectionManagerService);return U(ke,i,t,e)}},Ge="doc.command.set-inline-format-subscript",k={id:Ge,type:n.CommandType.COMMAND,handler:async(s,i)=>{const e=s.get(n.ICommandService),t=s.get(d.TextSelectionManagerService);return U(Ge,i,t,e)}},Ve="doc.command.set-inline-format-superscript",te={id:Ve,type:n.CommandType.COMMAND,handler:async(s,i)=>{const e=s.get(n.ICommandService),t=s.get(d.TextSelectionManagerService);return U(Ve,i,t,e)}},He="doc.command.set-inline-format-fontsize",ne={id:He,type:n.CommandType.COMMAND,handler:async(s,i)=>{const e=s.get(n.ICommandService),t=s.get(d.TextSelectionManagerService);return U(He,i,t,e)}},Je="doc.command.set-inline-format-font-family",ie={id:Je,type:n.CommandType.COMMAND,handler:async(s,i)=>{const e=s.get(n.ICommandService),t=s.get(d.TextSelectionManagerService);return U(Je,i,t,e)}},Ye="doc.command.set-inline-format-text-color",ae={id:Ye,type:n.CommandType.COMMAND,handler:async(s,i)=>{const e=s.get(n.ICommandService),t=s.get(d.TextSelectionManagerService);return U(Ye,i,t,e)}},We="doc.command.set-inline-format-text-background-color",se={id:We,type:n.CommandType.COMMAND,handler:async(s,i)=>{const e=s.get(n.ICommandService),t=s.get(d.TextSelectionManagerService);return U(We,i,t,e)}},Ze="doc.command.reset-inline-format-text-background-color",oe={id:Ze,type:n.CommandType.COMMAND,handler:async(s,i)=>{const e=s.get(n.ICommandService),t=s.get(d.TextSelectionManagerService);return U(Ze,i,t,e)}},Ke={[K.id]:"bl",[q.id]:"it",[Q.id]:"ul",[ee.id]:"st",[ne.id]:"fs",[ie.id]:"ff",[ae.id]:"cl",[se.id]:"bg",[oe.id]:"bg",[k.id]:"va",[te.id]:"va"},ye={id:"doc.command.set-inline-format",type:n.CommandType.COMMAND,handler:async(s,i)=>{const{segmentId:e,value:t,preCommandId:a}=i,o=s.get(n.ICommandService),r=s.get(d.TextSelectionManagerService),c=s.get(n.IUniverInstanceService),l=r.getSelections();if(!Array.isArray(l)||l.length===0)return!1;const u=c.getCurrentUniverDocInstance();if(!u)return!1;const m=u.getUnitId();let g;switch(a){case K.id:case q.id:case Q.id:case ee.id:case k.id:case te.id:{g=bt(u.getBody().textRuns,a,l);break}case ne.id:case ie.id:{g=t;break}case ae.id:case se.id:{g={rgb:t};break}case oe.id:{g={rgb:null};break}default:throw new Error(`Unknown command: ${a} in handleInlineFormat`)}const S={id:b.id,params:{unitId:m,actions:[],textRanges:l.map(F)}},f=new n.TextX,v=n.JSONX.getInstance(),h=new n.MemoryCursor;h.reset();for(const C of l){const{startOffset:I,endOffset:_}=C,y={dataStream:"",textRuns:[{st:0,ed:_-I,ts:{[Ke[a]]:g}}]},T=I-h.cursor;T!==0&&f.push({t:n.TextXActionType.RETAIN,len:T,segmentId:e}),f.push({t:n.TextXActionType.RETAIN,body:y,len:_-I,segmentId:e}),h.reset(),h.moveCursor(_)}return S.params.actions=v.editOp(f.serialize()),!!o.syncExecuteCommand(S.id,S.params)}};function Nt(s){return s!==null&&typeof s=="object"}function bt(s,i,e){let t=0,a=0;const o=Ke[i];for(;t!==s.length&&a!==e.length;){const{startOffset:r,endOffset:c}=e[a],{st:l,ed:u,ts:m}=s[t];if(c<=l)a++;else if(u<=r)t++;else{if(/bl|it/.test(o))return(m==null?void 0:m[o])===n.BooleanNumber.TRUE?n.BooleanNumber.FALSE:n.BooleanNumber.TRUE;if(/ul|st/.test(o))return Nt(m==null?void 0:m[o])&&(m==null?void 0:m[o]).s===n.BooleanNumber.TRUE?{s:n.BooleanNumber.FALSE}:{s:n.BooleanNumber.TRUE};if(/va/.test(o))return i===k.id?(m==null?void 0:m[o])===n.BaselineOffset.SUBSCRIPT?n.BaselineOffset.NORMAL:n.BaselineOffset.SUBSCRIPT:(m==null?void 0:m[o])===n.BaselineOffset.SUPERSCRIPT?n.BaselineOffset.NORMAL:n.BaselineOffset.SUPERSCRIPT;t++}}return/bl|it/.test(o)?n.BooleanNumber.TRUE:/ul|st/.test(o)?{s:n.BooleanNumber.TRUE}:i===k.id?n.BaselineOffset.SUBSCRIPT:n.BaselineOffset.SUPERSCRIPT}const Me={id:"doc.command.list-operation",type:n.CommandType.COMMAND,handler:(s,i)=>{var E,N,j,fe;const e=s.get(d.TextSelectionManagerService),t=s.get(n.IUniverInstanceService),a=s.get(n.ICommandService),{listType:o}=i,r=t.getCurrentUniverDocInstance();if(!r)return!1;const c=e.getActiveRange(),l=(E=e.getSelections())!=null?E:[],u=(N=r.getBody())==null?void 0:N.paragraphs,m=l.map(F);if(c==null||u==null)return!1;const g=et(c,u),{segmentId:S}=c,f=r.getUnitId(),v=g.every(L=>{var B;return((B=L.bullet)==null?void 0:B.listType)===o});let p=n.Tools.generateRandomId(6);if(g.length===1){const L=u.indexOf(g[0]),B=u[L-1],X=u[L+1];B&&B.bullet&&B.bullet.listType===o?p=B.bullet.listId:X&&X.bullet&&X.bullet.listType===o&&(p=X.bullet.listId)}const C={id:b.id,params:{unitId:f,actions:[],textRanges:m}},I=new n.MemoryCursor;I.reset();const _=new n.TextX,y=n.JSONX.getInstance(),T=(j=r.getSnapshot().lists)!=null?j:{},D={...n.PRESET_LIST_TYPE,...T},{charSpace:x,defaultTabStop:P=36,gridType:A}=r.getSnapshot().documentStyle;for(const L of g){const{startIndex:B,paragraphStyle:X={}}=L,{indentFirstLine:Yt=0,snapToGrid:Wt,indentStart:Oe=0}=X,{hanging:Re,indentStart:dt}=D[o].nestingLevel[0],xe=M.getCharSpaceApply(x,P,A,Wt);_.push({t:n.TextXActionType.RETAIN,len:B-I.cursor,segmentId:S}),_.push({t:n.TextXActionType.RETAIN,len:1,body:{dataStream:"",paragraphs:[v?{paragraphStyle:{...X,hanging:void 0,indentStart:Oe?Math.max(0,M.getNumberUnitValue(Oe,xe)+Re-dt):void 0},startIndex:0}:{startIndex:0,paragraphStyle:{...X,indentFirstLine:void 0,hanging:Re,indentStart:dt-Re+M.getNumberUnitValue(Yt,xe)+M.getNumberUnitValue(Oe,xe)},bullet:{...(fe=L.bullet)!=null?fe:{nestingLevel:0,textStyle:{fs:20}},listType:o,listId:p}}]},segmentId:S,coverType:n.UpdateDocsAttributeType.REPLACE}),I.moveCursorTo(B+1)}return C.params.actions=y.editOp(_.serialize()),!!a.syncExecuteCommand(C.id,C.params)}},qe={id:"doc.command.bullet-list",type:n.CommandType.COMMAND,handler:s=>s.get(n.ICommandService).syncExecuteCommand(Me.id,{listType:n.PresetListType.BULLET_LIST})},Qe={id:"doc.command.order-list",type:n.CommandType.COMMAND,handler:s=>s.get(n.ICommandService).syncExecuteCommand(Me.id,{listType:n.PresetListType.ORDER_LIST})};function et(s,i){const{startOffset:e,endOffset:t}=s,a=[];let o=-1;for(const r of i){const{startIndex:c}=r;(e>o&&e<=c||t>o&&t<=c||c>=e&&c<=t)&&a.push(r),o=c}return a}const G={id:"doc.command.align-operation",type:n.CommandType.COMMAND,handler:(s,i)=>{var y,T;const e=s.get(d.TextSelectionManagerService),t=s.get(n.IUniverInstanceService),a=s.get(n.ICommandService),{alignType:o}=i,r=t.getCurrentUniverDocInstance();if(!r)return!1;const c=e.getActiveRange(),l=(y=e.getSelections())!=null?y:[],u=(T=r.getBody())==null?void 0:T.paragraphs,m=l.map(F);if(c==null||u==null)return!1;const g=et(c,u),{segmentId:S}=c,f=r.getUnitId(),v=g.every(D=>{var x;return((x=D.paragraphStyle)==null?void 0:x.horizontalAlign)===o}),h={id:b.id,params:{unitId:f,actions:[],textRanges:m}},p=new n.MemoryCursor;p.reset();const C=new n.TextX,I=n.JSONX.getInstance();for(const D of g){const{startIndex:x}=D;C.push({t:n.TextXActionType.RETAIN,len:x-p.cursor,segmentId:S});const P={...D.paragraphStyle,horizontalAlign:v?n.HorizontalAlign.UNSPECIFIED:o};C.push({t:n.TextXActionType.RETAIN,len:1,body:{dataStream:"",paragraphs:[{...D,paragraphStyle:P,startIndex:0}]},segmentId:S,coverType:n.UpdateDocsAttributeType.REPLACE}),p.moveCursorTo(x+1)}return h.params.actions=I.editOp(C.serialize()),!!a.syncExecuteCommand(h.id,h.params)}},tt={id:"doc.command.align-left",type:n.CommandType.COMMAND,handler:s=>s.get(n.ICommandService).syncExecuteCommand(G.id,{alignType:n.HorizontalAlign.LEFT})},nt={id:"doc.command.align-center",type:n.CommandType.COMMAND,handler:s=>s.get(n.ICommandService).syncExecuteCommand(G.id,{alignType:n.HorizontalAlign.CENTER})},it={id:"doc.command.align-right",type:n.CommandType.COMMAND,handler:s=>s.get(n.ICommandService).syncExecuteCommand(G.id,{alignType:n.HorizontalAlign.RIGHT})},at={id:"doc.command.align-justify",type:n.CommandType.COMMAND,handler:s=>s.get(n.ICommandService).syncExecuteCommand(G.id,{alignType:n.HorizontalAlign.JUSTIFIED})},st={id:"doc.command-replace-content",type:n.CommandType.COMMAND,handler:async(s,i)=>{var f;const{unitId:e,body:t,textRanges:a,segmentId:o=""}=i,r=s.get(n.IUniverInstanceService),c=s.get(n.ICommandService),l=s.get(d.TextSelectionManagerService),u=(f=r.getUniverDocInstance(e))==null?void 0:f.getSnapshot().body,m=l.getSelections();if(u==null||!Array.isArray(m)||m.length===0)return!1;const g=rt(e,o,u,t);return g.params.textRanges=a,!!c.syncExecuteCommand(g.id,g.params)}},ot={id:"doc.command-cover-content",type:n.CommandType.COMMAND,handler:async(s,i)=>{var m;const{unitId:e,body:t,segmentId:a=""}=i,o=s.get(n.IUniverInstanceService),r=s.get(n.ICommandService),c=s.get(n.IUndoRedoService),l=(m=o.getUniverDocInstance(e))==null?void 0:m.getSnapshot().body;if(l==null)return!1;const u=rt(e,a,l,t);return u.params.noNeedSetTextRange=!0,u.params.noHistory=!0,r.syncExecuteCommand(u.id,u.params),c.clearUndoRedo(e),!0}};function rt(s,i,e,t){const a={id:b.id,params:{unitId:s,actions:[],textRanges:[]}},o=new n.TextX,r=n.JSONX.getInstance(),c=(e==null?void 0:e.dataStream.length)-2;return c>0&&o.push({t:n.TextXActionType.DELETE,len:c,line:0,segmentId:i}),t.dataStream.length>0&&o.push({t:n.TextXActionType.INSERT,body:t,len:t.dataStream.length,line:0,segmentId:i}),a.params.actions=r.editOp(o.serialize()),a}const re={id:"doc.operation.move-cursor",type:n.CommandType.OPERATION,handler:(s,i)=>!!i},ce={id:"doc.operation.move-selection",type:n.CommandType.OPERATION,handler:(s,i)=>!!i},Pt=(s,i)=>{const e=s.get(n.IUniverInstanceService).getUniverDocInstance(i.unitId),t=(e==null?void 0:e.zoomRatio)||1;return{...n.Tools.deepClone(i),zoomRatio:t}},J={id:"doc.operation.set-zoom-ratio",type:n.CommandType.OPERATION,handler:(s,i)=>{const e=s.get(n.IUniverInstanceService).getUniverDocInstance(i.unitId);if(!e)return!1;const t=e.getSnapshot();return t.settings==null?t.settings={zoomRatio:i.zoomRatio}:t.settings.zoomRatio=i.zoomRatio,!0}},ct={type:n.CommandType.COMMAND,id:"doc.command.set-zoom-ratio",handler:async(s,i)=>{var g,S,f;const e=s.get(n.ICommandService),t=s.get(n.IUndoRedoService),a=s.get(n.IUniverInstanceService);let o=(g=a.getCurrentUniverDocInstance())==null?void 0:g.getUnitId();if(!o)return!1;let r=1;if(i&&(o=(S=i.documentId)!=null?S:o,r=(f=i.zoomRatio)!=null?f:r),!a.getUniverDocInstance(o))return!1;const l={zoomRatio:r,unitId:o},u=Pt(s,l);return e.syncExecuteCommand(J.id,l)?(t.pushUndoRedo({unitID:o,undoMutations:[{id:J.id,params:u}],redoMutations:[{id:J.id,params:l}]}),!0):!1}},lt={id:"doc.operation.select-all",type:n.CommandType.COMMAND,handler:async s=>{const i=s.get(n.IUniverInstanceService),e=s.get(d.TextSelectionManagerService),t=i.getCurrentUniverDocInstance();if(!t)return!1;const a=t.getSnapshot().body;if(a==null)return!1;const o=[{startOffset:0,endOffset:a.dataStream.length-2}];return e.replaceTextRanges(o,!1),!0}};var Ut=Object.defineProperty,Bt=Object.getOwnPropertyDescriptor,Lt=(s,i,e,t)=>{for(var a=t>1?void 0:t?Bt(i,e):i,o=s.length-1,r;o>=0;o--)(r=s[o])&&(a=(t?r(i,e,a):r(a))||a);return t&&a&&Ut(i,e,a),a},Y=(s,i)=>(e,t)=>i(e,t,s);let le=class extends n.Disposable{constructor(i,e,t,a,o){super();O(this,"_previousIMEContent","");O(this,"_isCompositionStart",!0);O(this,"_onStartSubscription");O(this,"_onUpdateSubscription");O(this,"_onEndSubscription");this._univerInstanceService=i,this._renderManagerSrv=e,this._textSelectionRenderManager=t,this._imeInputManagerService=a,this._commandService=o,this._initialize()}dispose(){var i,e,t;(i=this._onStartSubscription)==null||i.unsubscribe(),(e=this._onUpdateSubscription)==null||e.unsubscribe(),(t=this._onEndSubscription)==null||t.unsubscribe()}_initialize(){this._initialOnCompositionstart(),this._initialOnCompositionUpdate(),this._initialOnCompositionend()}_initialOnCompositionstart(){this._onStartSubscription=this._textSelectionRenderManager.onCompositionstart$.subscribe(i=>{if(i==null)return;this._resetIME();const{activeRange:e}=i;e!=null&&this._imeInputManagerService.setActiveRange(n.Tools.deepClone(e))})}_initialOnCompositionUpdate(){this._onUpdateSubscription=this._textSelectionRenderManager.onCompositionupdate$.subscribe(async i=>{this._updateContent(i,!0)})}_initialOnCompositionend(){this._onEndSubscription=this._textSelectionRenderManager.onCompositionend$.subscribe(i=>{this._updateContent(i,!1)})}async _updateContent(i,e){var u;if(i==null)return;const t=this._univerInstanceService.getCurrentUniverDocInstance();if(!t)return;const a=(u=this._renderManagerSrv.getRenderById(t.getUnitId()))==null?void 0:u.with(d.DocSkeletonManagerService).getSkeleton(),{event:o,activeRange:r}=i;if(a==null||r==null)return;const l=o.data;l===this._previousIMEContent&&e||(await this._commandService.executeCommand(Te.id,{unitId:t.getUnitId(),newText:l,oldTextLen:this._previousIMEContent.length,isCompositionStart:this._isCompositionStart,isCompositionEnd:!e}),e?(this._isCompositionStart&&(this._isCompositionStart=!1),this._previousIMEContent=l):this._resetIME())}_resetIME(){this._previousIMEContent="",this._isCompositionStart=!0,this._imeInputManagerService.clearUndoRedoMutationParamsCache(),this._imeInputManagerService.setActiveRange(null)}};le=Lt([n.OnLifecycle(n.LifecycleStages.Rendered,le),Y(0,n.IUniverInstanceService),Y(1,M.IRenderManagerService),Y(2,M.ITextSelectionRenderManager),Y(3,z.Inject(H)),Y(4,n.ICommandService)],le);var wt=Object.defineProperty,Xt=Object.getOwnPropertyDescriptor,Ft=(s,i,e,t)=>{for(var a=t>1?void 0:t?Xt(i,e):i,o=s.length-1,r;o>=0;o--)(r=s[o])&&(a=(t?r(i,e,a):r(a))||a);return t&&a&&wt(i,e,a),a},de=(s,i)=>(e,t)=>i(e,t,s);let ue=class extends n.Disposable{constructor(i,e,t,a){super();O(this,"_onInputSubscription");this._univerInstanceService=i,this._renderManagerService=e,this._textSelectionManagerService=t,this._commandService=a,this._commandExecutedListener()}dispose(){var i;super.dispose(),(i=this._onInputSubscription)==null||i.unsubscribe()}_commandExecutedListener(){const i=[re.id,ce.id];this.disposeWithMe(this._commandService.onCommandExecuted(e=>{if(!i.includes(e.id))return;const t=e.params;switch(e.id){case re.id:return this._handleMoveCursor(t.direction);case ce.id:return this._handleShiftMoveSelection(t.direction);default:throw new Error("Unknown command")}}))}_handleShiftMoveSelection(i){var h,p,C;const e=this._textSelectionManagerService.getActiveRange(),t=this._textSelectionManagerService.getSelections(),a=this._univerInstanceService.getCurrentUniverDocInstance();if(!a)return;const o=(h=this._renderManagerService.getRenderById(a.getUnitId()))==null?void 0:h.with(d.DocSkeletonManagerService).getSkeleton(),r=this._getDocObject();if(e==null||o==null||r==null)return;const{startOffset:c,endOffset:l,style:u,collapsed:m,direction:g}=e;if(t.length>1){let I=Number.POSITIVE_INFINITY,_=Number.NEGATIVE_INFINITY;for(const y of t)I=Math.min(I,y.startOffset),_=Math.max(_,y.endOffset);this._textSelectionManagerService.replaceTextRanges([{startOffset:i===n.Direction.LEFT||i===n.Direction.UP?_:I,endOffset:i===n.Direction.LEFT||i===n.Direction.UP?I:_,style:u}],!1);return}const S=m||g===M.RANGE_DIRECTION.FORWARD?c:l;let f=m||g===M.RANGE_DIRECTION.FORWARD?l:c;const v=(p=a.getBody().dataStream.length)!=null?p:Number.POSITIVE_INFINITY;if(i===n.Direction.LEFT||i===n.Direction.RIGHT){const I=o.findNodeByCharIndex(f-1),_=o.findNodeByCharIndex(f);f=i===n.Direction.RIGHT?f+_.count:f-((C=I==null?void 0:I.count)!=null?C:0),f=Math.min(v-2,Math.max(0,f)),this._textSelectionManagerService.replaceTextRanges([{startOffset:S,endOffset:f,style:u}],!1)}else{const I=o.findNodeByCharIndex(f),_=r.document.getOffsetConfig(),y=this._getTopOrBottomPosition(o,I,i===n.Direction.DOWN);if(y==null){const D=i===n.Direction.UP?0:v-2;if(D===f)return;this._textSelectionManagerService.replaceTextRanges([{startOffset:S,endOffset:D,style:u}],!1);return}const T=new M.NodePositionConvertToCursor(_,o).getRangePointData(y,y).cursorList[0];this._textSelectionManagerService.replaceTextRanges([{startOffset:S,endOffset:T.endOffset,style:u}],!1)}}_handleMoveCursor(i){var S,f,v;const e=this._textSelectionManagerService.getActiveRange(),t=this._textSelectionManagerService.getSelections(),a=this._univerInstanceService.getCurrentUniverDocInstance();if(!a)return!1;const o=(S=this._renderManagerService.getRenderById(a.getUnitId()))==null?void 0:S.with(d.DocSkeletonManagerService).getSkeleton(),r=this._getDocObject();if(e==null||o==null||r==null||t==null)return;const{startOffset:c,endOffset:l,style:u,collapsed:m}=e,g=(f=a.getBody().dataStream.length)!=null?f:Number.POSITIVE_INFINITY;if(i===n.Direction.LEFT||i===n.Direction.RIGHT){let h;if(!e.collapsed||t.length>1){let p=Number.POSITIVE_INFINITY,C=Number.NEGATIVE_INFINITY;for(const I of t)p=Math.min(p,I.startOffset),C=Math.max(C,I.endOffset);h=i===n.Direction.LEFT?p:C}else{const p=o.findNodeByCharIndex(c-1),C=o.findNodeByCharIndex(c);i===n.Direction.LEFT?h=Math.max(0,c-((v=p==null?void 0:p.count)!=null?v:0)):h=Math.min(g-2,l+C.count)}this._textSelectionManagerService.replaceTextRanges([{startOffset:h,endOffset:h,style:u}],!1)}else{const h=o.findNodeByCharIndex(c),p=o.findNodeByCharIndex(l),C=r.document.getOffsetConfig(),I=this._getTopOrBottomPosition(o,i===n.Direction.UP?h:p,i===n.Direction.DOWN);if(I==null){let y;m?y=i===n.Direction.UP?0:g-2:y=i===n.Direction.UP?c:l,this._textSelectionManagerService.replaceTextRanges([{startOffset:y,endOffset:y,style:u}],!1);return}const _=new M.NodePositionConvertToCursor(C,o).getRangePointData(I,I).cursorList[0];this._textSelectionManagerService.replaceTextRanges([{..._,style:u}],!1)}}_getTopOrBottomPosition(i,e,t){if(e==null)return;const a=this._getSpanLeftOffsetInLine(e),o=this._getNextOrPrevLine(e,t);if(o==null)return;const r=this._matchPositionByLeftOffset(i,o,a);if(r!=null)return{...r,isBack:!0}}_getSpanLeftOffsetInLine(i){const e=i.parent;if(e==null)return Number.NEGATIVE_INFINITY;const t=e.left,{left:a}=i;return t+a}_matchPositionByLeftOffset(i,e,t){const a={distance:Number.POSITIVE_INFINITY};for(const o of e.divides){const r=o.left;for(const c of o.glyphGroup){const{left:l}=c,u=r+l,m=Math.abs(t-u);m<a.distance&&(a.glyph=c,a.distance=m)}}if(a.glyph!=null)return i.findPositionByGlyph(a.glyph)}_getNextOrPrevLine(i,e){var v,h,p,C,I,_,y,T,D,x,P,A;const t=i.parent;if(t==null)return;const a=t.parent;if(a==null)return;const o=a.parent;if(o==null)return;const r=o.lines.indexOf(a);if(r===-1)return;let c;if(e===!0?c=o.lines[r+1]:c=o.lines[r-1],c!=null)return c;const l=o.parent;if(l==null)return;const u=l.columns.indexOf(o);if(u===-1)return;if(e===!0)c=(v=l.columns[u+1])==null?void 0:v.lines[0];else{const R=(p=(h=l.columns)==null?void 0:h[u-1])==null?void 0:p.lines;c=R==null?void 0:R[R.length-1]}if(c!=null)return c;const m=l.parent;if(m==null)return;const g=m.sections.indexOf(l);if(g===-1)return;if(e===!0)c=(I=(C=m.sections[g-1])==null?void 0:C.columns[0])==null?void 0:I.lines[0];else{const R=(y=(_=m.sections)==null?void 0:_[g-1])==null?void 0:y.columns,E=R==null?void 0:R[R.length-1],N=E==null?void 0:E.lines;c=N==null?void 0:N[N.length-1]}if(c!=null)return c;const S=m.parent;if(S==null)return;const f=S.pages.indexOf(m);if(f!==-1){if(e===!0)c=(x=(D=(T=S.pages[f+1])==null?void 0:T.sections[0])==null?void 0:D.columns[0])==null?void 0:x.lines[0];else{const R=(P=S.pages[f-1])==null?void 0:P.sections;if(R==null)return;const E=(A=R[R.length-1])==null?void 0:A.columns,N=E[E.length-1],j=N==null?void 0:N.lines;c=j[j.length-1]}if(c!=null)return c}}_getDocObject(){return Ee(this._univerInstanceService,this._renderManagerService)}};ue=Ft([n.OnLifecycle(n.LifecycleStages.Rendered,ue),de(0,n.IUniverInstanceService),de(1,M.IRenderManagerService),de(2,z.Inject(d.TextSelectionManagerService)),de(3,n.ICommandService)],ue);var jt=Object.defineProperty,$t=Object.getOwnPropertyDescriptor,zt=(s,i,e,t)=>{for(var a=t>1?void 0:t?$t(i,e):i,o=s.length-1,r;o>=0;o--)(r=s[o])&&(a=(t?r(i,e,a):r(a))||a);return t&&a&&jt(i,e,a),a},me=(s,i)=>(e,t)=>i(e,t,s);let ge=class extends n.Disposable{constructor(i,e,t,a){super();O(this,"_onInputSubscription");this._univerInstanceService=i,this._renderManagerService=e,this._textSelectionRenderManager=t,this._commandService=a,this._init()}dispose(){var i;super.dispose(),(i=this._onInputSubscription)==null||i.unsubscribe()}_init(){this._initialNormalInput()}_initialNormalInput(){this._onInputSubscription=this._textSelectionRenderManager.onInput$.subscribe(async i=>{var v;if(i==null)return;const e=this._univerInstanceService.getCurrentUniverDocInstance();if(!e)return;const t=e.getUnitId(),{event:a,content:o="",activeRange:r}=i,c=a,l=(v=this._renderManagerService.getRenderById(e.getUnitId()))==null?void 0:v.with(d.DocSkeletonManagerService).getSkeleton();if(c.data==null||l==null||!l||!r)return;const{startOffset:u,segmentId:m,style:g}=r,S=o.length,f=[{startOffset:u+S,endOffset:u+S,style:g}];await this._commandService.executeCommand(W.id,{unitId:t,body:{dataStream:o},range:r,textRanges:f,segmentId:m})})}};ge=zt([n.OnLifecycle(n.LifecycleStages.Rendered,ge),me(0,n.IUniverInstanceService),me(1,M.IRenderManagerService),me(2,M.ITextSelectionRenderManager),me(3,n.ICommandService)],ge);var kt=Object.defineProperty,Gt=Object.getOwnPropertyDescriptor,Vt=(s,i,e,t)=>{for(var a=t>1?void 0:t?Gt(i,e):i,o=s.length-1,r;o>=0;o--)(r=s[o])&&(a=(t?r(i,e,a):r(a))||a);return t&&a&&kt(i,e,a),a},Ht=(s,i)=>(e,t)=>i(e,t,s);const Jt="docs";d.UniverDocsPlugin=(Se=class extends n.Plugin{constructor(i={},e){super(),this._injector=e,this._initializeDependencies(e),this._initializeCommands()}_initializeCommands(){[re,ce,we,Xe,K,q,Q,ee,k,te,ne,ie,ae,oe,se,ye,Be,W,Z,ve,Te,_e,b,st,ot,ct,J,he,lt,Qe,qe,Me,tt,nt,it,G,at].forEach(i=>{this._injector.get(n.ICommandService).registerCommand(i)})}_initializeDependencies(i){[[d.DocStateChangeManagerService],[H],[M.ITextSelectionRenderManager,{useClass:M.TextSelectionRenderManager}],[d.TextSelectionManagerService],[ge],[le],[ue]].forEach(e=>i.add(e))}},O(Se,"pluginName",Jt),O(Se,"type",n.UniverInstanceType.UNIVER_DOC),Se),d.UniverDocsPlugin=Vt([Ht(1,z.Inject(z.Injector))],d.UniverDocsPlugin),d.AlignCenterCommand=nt,d.AlignJustifyCommand=at,d.AlignLeftCommand=tt,d.AlignOperationCommand=G,d.AlignRightCommand=it,d.BreakLineCommand=Be,d.BulletListCommand=qe,d.CoverContentCommand=ot,d.CutContentCommand=Ce,d.DOCS_COMPONENT_BACKGROUND_LAYER_INDEX=ut,d.DOCS_COMPONENT_DEFAULT_Z_INDEX=St,d.DOCS_COMPONENT_HEADER_LAYER_INDEX=gt,d.DOCS_COMPONENT_MAIN_LAYER_INDEX=mt,d.DOCS_VIEW_KEY=V,d.DeleteCommand=Z,d.DeleteLeftCommand=we,d.DeleteRightCommand=Xe,d.EditorInsertTextCommandId=Ue,d.IMEInputCommand=Te,d.IMEInputManagerService=H,d.InnerPasteCommand=Dt,d.InsertCommand=W,d.MoveCursorOperation=re,d.MoveSelectionOperation=ce,d.NORMAL_TEXT_SELECTION_PLUGIN_NAME=ft,d.OrderListCommand=Qe,d.ReplaceContentCommand=st,d.ResetInlineFormatTextBackgroundColorCommand=oe,d.RichTextEditingMutation=b,d.SelectAllOperation=lt,d.SetDocZoomRatioCommand=ct,d.SetDocZoomRatioOperation=J,d.SetInlineFormatBoldCommand=K,d.SetInlineFormatCommand=ye,d.SetInlineFormatFontFamilyCommand=ie,d.SetInlineFormatFontSizeCommand=ne,d.SetInlineFormatItalicCommand=q,d.SetInlineFormatStrikethroughCommand=ee,d.SetInlineFormatSubscriptCommand=k,d.SetInlineFormatSuperscriptCommand=te,d.SetInlineFormatTextBackgroundColorCommand=se,d.SetInlineFormatTextColorCommand=ae,d.SetInlineFormatUnderlineCommand=Q,d.SetTextSelectionsOperation=he,d.UpdateCommand=ve,d.VIEWPORT_KEY=De,d.getDocObject=Ee,d.getDocObjectById=pt,d.neoGetDocObject=ht,d.serializeTextRange=F,Object.defineProperty(d,Symbol.toStringTag,{value:"Module"})});
1
+ (function(m,t){typeof exports=="object"&&typeof module<"u"?t(exports,require("@univerjs/core"),require("@univerjs/engine-render"),require("@wendellhu/redi"),require("rxjs")):typeof define=="function"&&define.amd?define(["exports","@univerjs/core","@univerjs/engine-render","@wendellhu/redi","rxjs"],t):(m=typeof globalThis<"u"?globalThis:m||self,t(m.UniverDocs={},m.UniverCore,m.UniverEngineRender,m["@wendellhu/redi"],m.rxjs))})(this,function(m,t,E,k,G){"use strict";var Rn=Object.defineProperty;var Mn=(m,t,E)=>t in m?Rn(m,t,{enumerable:!0,configurable:!0,writable:!0,value:E}):m[t]=E;var D=(m,t,E)=>Mn(m,typeof t!="symbol"?t+"":t,E);var ye;function ee(s){return s===t.DataStreamTreeTokenType.CUSTOM_RANGE_END||s===t.DataStreamTreeTokenType.CUSTOM_RANGE_START}function Oe(s,a,e,n){return s<=e&&a>=e||s>=e&&s<=n}function Re(s,a,e,n){const i=n.slice(e.startIndex+1,e.endIndex),o=Math.max(s-(e.startIndex+1),0),r=s+a-1-(e.startIndex+1);if(r<0)return!1;if(o===0&&r>=i.length)return!0;const l=i.slice(0,o)+i.slice(o+a);for(let c=0,d=l.length;c<d;c++){const u=l[c];if(!ee(u))return!1}return!0}function V(s){const{startOffset:a,endOffset:e,collapsed:n}=s,i=Math.min(a,e),o=Math.max(a,e);return{startOffset:i,endOffset:o,collapsed:n}}function Me(s,a){let{startOffset:e,endOffset:n}=V(s);for(;a.dataStream[e-1]===t.DataStreamTreeTokenType.CUSTOM_RANGE_START;)e-=1;for(;a.dataStream[n]===t.DataStreamTreeTokenType.CUSTOM_RANGE_END;)n+=1;return{startOffset:e,endOffset:n}}function te(s,a){let{startOffset:e,endOffset:n,collapsed:i}=V(s);if(i){for(;ee(a.dataStream[e-1]);)n-=1,e-=1;return{startOffset:e,endOffset:n,collapsed:i}}else return{...Me(s,a),collapsed:!1}}function J(s,a){let{startOffset:e,endOffset:n,collapsed:i}=V(s);if(i){for(;a.dataStream[n]===t.DataStreamTreeTokenType.CUSTOM_RANGE_END;)n+=1,e+=1;for(;a.dataStream[n-1]===t.DataStreamTreeTokenType.CUSTOM_RANGE_START;)n-=1,e-=1;return{startOffset:e,endOffset:n,collapsed:i}}else return{...Me(s,a),collapsed:!1}}function Ot(s,a){if(s.startOffset===s.endOffset)return null;const e=a.customRanges;if(!e)return V(s);let{startOffset:n,endOffset:i}=Me(s,a);for(;ee(a.dataStream[n]);){if(a.dataStream[n]===t.DataStreamTreeTokenType.CUSTOM_RANGE_START){const o=e.find(r=>r.startIndex===n);if(!o)throw new Error("No custom-range matched");if(o.endIndex===i-1)return{startOffset:n,endOffset:i,collapsed:!1};if(o.endIndex<i-1)break}n+=1}for(;ee(a.dataStream[i-1]);){if(a.dataStream[n]===t.DataStreamTreeTokenType.CUSTOM_RANGE_END){const o=e.find(r=>r.endIndex===i-1);if(!o)throw new Error("No custom-range matched");if(o.startIndex===n)return{startOffset:n,endOffset:i,collapsed:!1};if(o.startIndex>n)break}i-=1}return i<=n?null:{startOffset:n,endOffset:i,collapsed:!1}}const Rt=[t.DataStreamTreeTokenType.PARAGRAPH,t.DataStreamTreeTokenType.SECTION_BREAK,t.DataStreamTreeTokenType.TABLE_START,t.DataStreamTreeTokenType.TABLE_ROW_START,t.DataStreamTreeTokenType.TABLE_CELL_START,t.DataStreamTreeTokenType.TABLE_CELL_END,t.DataStreamTreeTokenType.TABLE_ROW_END,t.DataStreamTreeTokenType.TABLE_END,t.DataStreamTreeTokenType.CUSTOM_RANGE_START,t.DataStreamTreeTokenType.CUSTOM_RANGE_END,t.DataStreamTreeTokenType.COLUMN_BREAK,t.DataStreamTreeTokenType.PAGE_BREAK,t.DataStreamTreeTokenType.DOCS_END,t.DataStreamTreeTokenType.TAB,t.DataStreamTreeTokenType.CUSTOM_BLOCK];function Mt(s,a,e){const n=s.slice(a,e);return Rt.reduce((i,o)=>i.replaceAll(o,""),n)}var W=(s=>(s.MAIN="__Document_Render_Main__",s.BACKGROUND="__Document_Render_Background__",s))(W||{}),Xe=(s=>(s.VIEW_MAIN="viewMain",s.VIEW_TOP="viewTop",s.VIEW_LEFT="viewLeft",s.VIEW_LEFT_TOP="viewLeftTop",s))(Xe||{});const xt=0,Dt=2,Et=4,At=10,Nt="normalTextSelectionPluginName";function Ut(s){const{mainComponent:a,scene:e,engine:n,components:i}=s,o=a,r=i.get(W.BACKGROUND);return{document:o,docBackground:r,scene:e,engine:n}}function Le(s,a){const e=s.getCurrentUnitForType(t.UniverInstanceType.UNIVER_DOC);if(!e)return null;const n=e.getUnitId(),i=a.getRenderById(n);if(i==null)return;const{mainComponent:o,scene:r,engine:l,components:c}=i,d=o,u=c.get(W.BACKGROUND);return{document:d,docBackground:u,scene:r,engine:l}}function bt(s,a){const e=a.getRenderById(s);if(e==null)return;const{mainComponent:n,scene:i,engine:o,components:r}=e,l=n,c=r.get(W.BACKGROUND);return{document:l,docBackground:c,scene:i,engine:o}}const xe={id:"doc.operation.set-selections",type:t.CommandType.OPERATION,handler:(s,a)=>!0};var Pt=Object.defineProperty,Bt=Object.getOwnPropertyDescriptor,wt=(s,a,e,n)=>{for(var i=n>1?void 0:n?Bt(a,e):a,o=s.length-1,r;o>=0;o--)(r=s[o])&&(i=(n?r(a,e,i):r(i))||i);return n&&i&&Pt(a,e,i),i},Fe=(s,a)=>(e,n)=>a(e,n,s);function j(s){const{startOffset:a,endOffset:e,collapsed:n}=s,i={startOffset:a,endOffset:e,collapsed:n};return typeof s.isActive=="function"&&(i.isActive=s.isActive()),i}m.TextSelectionManagerService=class extends t.RxDisposable{constructor(e,n){super();D(this,"_currentSelection",null);D(this,"_textSelectionInfo",new Map);D(this,"_textSelection$",new G.BehaviorSubject(null));D(this,"textSelection$",this._textSelection$.asObservable());this._textSelectionRenderManager=e,this._commandService=n,this._syncSelectionFromRenderService()}getCurrentSelection(){return this._currentSelection}getCurrentSelectionInfo(){return this._getTextRanges(this._currentSelection)}dispose(){this._textSelection$.complete()}refreshSelection(){this._currentSelection!=null&&this._refresh(this._currentSelection)}setCurrentSelection(e){this._currentSelection=e,this._refresh(e)}setCurrentSelectionNotRefresh(e){this._currentSelection=e}getSelections(){var e;return(e=this._getTextRanges(this._currentSelection))==null?void 0:e.textRanges}getActiveTextRange(){const e=this._getTextRanges(this._currentSelection);if(e==null)return;const{textRanges:n}=e;return n.find(i=>i.isActive())}getActiveRange(){const e=this._getTextRanges(this._currentSelection);if(e==null)return;const{textRanges:n,segmentId:i,style:o,segmentPage:r}=e,l=n.find(h=>h.isActive());if(l==null)return null;const{startOffset:c,endOffset:d,collapsed:u,startNodePosition:S,endNodePosition:g,direction:v}=l;return c==null||d==null?null:{startOffset:c,endOffset:d,collapsed:u,startNodePosition:S,endNodePosition:g,direction:v,segmentId:i,segmentPage:r,style:o}}add(e,n=!0){this._currentSelection!=null&&this._addByParam({...this._currentSelection,textRanges:e,segmentId:"",segmentPage:-1,isEditing:n,style:E.NORMAL_TEXT_SELECTION_PLUGIN_STYLE})}replaceTextRanges(e,n=!0){this._currentSelection!=null&&(this._textSelectionRenderManager.removeAllTextRanges(),this._textSelectionRenderManager.addTextRanges(e,n))}_syncSelectionFromRenderService(){this._textSelectionRenderManager.textSelectionInner$.pipe(G.takeUntil(this.dispose$)).subscribe(e=>{e!=null&&this._replaceTextRangesWithNoRefresh(e)})}_replaceTextRangesWithNoRefresh(e){if(this._currentSelection==null)return;const n={...this._currentSelection,...e};this._replaceByParam(n),this._textSelection$.next(n);const{unitId:i,subUnitId:o,segmentId:r,style:l,textRanges:c,isEditing:d}=n;this._commandService.executeCommand(xe.id,{unitId:i,subUnitId:o,segmentId:r,style:l,isEditing:d,ranges:c.map(j)})}_getTextRanges(e){var o;if(e==null)return;const{unitId:n,subUnitId:i=""}=e;return(o=this._textSelectionInfo.get(n))==null?void 0:o.get(i)}_refresh(e){const n=this._getTextRanges(e);this._textSelectionRenderManager.removeAllTextRanges(),n&&Array.isArray(n.textRanges)&&n.textRanges.length&&this._textSelectionRenderManager.addTextRanges(n.textRanges.map(j))}_replaceByParam(e){const{unitId:n,subUnitId:i,style:o,segmentId:r,textRanges:l,isEditing:c,segmentPage:d}=e;this._textSelectionInfo.has(n)||this._textSelectionInfo.set(n,new Map),this._textSelectionInfo.get(n).set(i,{textRanges:l,style:o,segmentId:r,isEditing:c,segmentPage:d})}_addByParam(e){const{unitId:n,subUnitId:i,textRanges:o,style:r,segmentId:l,isEditing:c,segmentPage:d}=e;this._textSelectionInfo.has(n)||this._textSelectionInfo.set(n,new Map);const u=this._textSelectionInfo.get(n);u.has(i)?u.get(i).textRanges.push(...o):u.set(i,{textRanges:o,style:r,segmentId:l,isEditing:c,segmentPage:d})}},m.TextSelectionManagerService=wt([Fe(0,E.ITextSelectionRenderManager),Fe(1,t.ICommandService)],m.TextSelectionManagerService);function De(s,a="",e,n){var T;const{startOffset:i,endOffset:o}=s,r=[],l=i-e,c=o-e,d=n.dataStream,u=(T=n.customRanges)==null?void 0:T.filter(f=>Oe(f.startIndex,f.endIndex,i,o)),S=new Set(u==null?void 0:u.filter(f=>Re(i,o-i,f,d))),g=new Set;u==null||u.forEach(f=>{S.has(f)||(f.startIndex-e>=l&&f.startIndex-e<=c&&f.endIndex-e>c&&g.add(f.startIndex),f.endIndex-e>=l&&f.endIndex-e<=c&&f.startIndex<l&&g.add(f.endIndex))}),l>0&&r.push({t:t.TextXActionType.RETAIN,len:l,segmentId:a});const v=[...g].sort((f,p)=>f-p);let h=l;return v.forEach(f=>{const p=f-h;p>0&&r.push({t:t.TextXActionType.DELETE,len:p,line:0,segmentId:a}),r.push({t:t.TextXActionType.RETAIN,len:1,segmentId:a}),h=f+1}),h<c&&(r.push({t:t.TextXActionType.DELETE,len:c-h,line:0,segmentId:a}),h=c+1),{dos:r,cursor:h,retain:g.size}}var Xt=Object.defineProperty,Lt=Object.getOwnPropertyDescriptor,Ft=(s,a,e,n)=>{for(var i=n>1?void 0:n?Lt(a,e):a,o=s.length-1,r;o>=0;o--)(r=s[o])&&(i=(n?r(a,e,i):r(i))||i);return n&&i&&Xt(a,e,i),i},Ee=(s,a)=>(e,n)=>a(e,n,s);const ke=300;m.DocStateChangeManagerService=class extends t.RxDisposable{constructor(e,n,i){super();D(this,"_docStateChange$",new G.BehaviorSubject(null));D(this,"docStateChange$",this._docStateChange$.asObservable());D(this,"_historyStateCache",new Map);D(this,"_changeStateCache",new Map);D(this,"_historyTimer",null);D(this,"_changeStateCacheTimer",null);this._undoRedoService=e,this._commandService=n,this._univerInstanceService=i,this._initialize()}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){const n=this._univerInstanceService.getCurrentUniverDocInstance();if(n==null)return;const i=n.getUnitId();this._pushHistory(i),this._emitChangeState(i)}}))}_cacheChangeState(e,n="history"){const{trigger:i,unitId:o,noHistory:r,debounce:l=!1}=e;if(r||n==="history"&&(i===t.RedoCommandId||i===t.UndoCommandId))return;const c=n==="history"?this._historyStateCache:this._changeStateCache,d=n==="history"?this._pushHistory.bind(this):this._emitChangeState.bind(this);if(c.has(o)){const u=c.get(o);u==null||u.push(e)}else c.set(o,[e]);l?n==="history"?(this._historyTimer&&clearTimeout(this._historyTimer),this._historyTimer=setTimeout(()=>{d(o)},ke)):(this._changeStateCacheTimer&&clearTimeout(this._changeStateCacheTimer),this._changeStateCacheTimer=setTimeout(()=>{d(o)},ke)):d(o)}_pushHistory(e){const n=this._undoRedoService,i=this._historyStateCache.get(e);if(!Array.isArray(i)||i.length===0)return;const o=i.length,r=i[0].commandId,l=i[0],c=i[o-1],d={unitId:e,actions:i.reduce((S,g)=>t.JSONX.compose(S,g.redoState.actions),null),textRanges:c.redoState.textRanges},u={unitId:e,actions:i.reverse().reduce((S,g)=>t.JSONX.compose(S,g.undoState.actions),null),textRanges:l.undoState.textRanges};n.pushUndoRedo({unitID:e,undoMutations:[{id:r,params:u}],redoMutations:[{id:r,params:d}]}),i.length=0}_emitChangeState(e){const n=this._changeStateCache.get(e);if(!Array.isArray(n)||n.length===0)return;const i=n.length,{commandId:o,trigger:r,segmentId:l,noHistory:c,debounce:d}=n[0],u=n[0],S=n[i-1],g={unitId:e,actions:n.reduce((T,f)=>t.JSONX.compose(T,f.redoState.actions),null),textRanges:S.redoState.textRanges},v={unitId:e,actions:n.reverse().reduce((T,f)=>t.JSONX.compose(T,f.undoState.actions),null),textRanges:u.undoState.textRanges},h={commandId:o,unitId:e,trigger:r,redoState:g,undoState:v,segmentId:l,noHistory:c,debounce:d};n.length=0,this._docStateChange$.next(h)}},m.DocStateChangeManagerService=Ft([Ee(0,k.Inject(t.IUndoRedoService)),Ee(1,t.ICommandService),Ee(2,t.IUniverInstanceService)],m.DocStateChangeManagerService);class Y{constructor(){D(this,"_previousActiveRange",null);D(this,"_undoMutationParamsCache",[]);D(this,"_redoMutationParamsCache",[])}clearUndoRedoMutationParamsCache(){this._undoMutationParamsCache=[],this._redoMutationParamsCache=[]}getUndoRedoMutationParamsCache(){return{undoCache:this._undoMutationParamsCache,redoCache:this._redoMutationParamsCache}}setUndoRedoMutationParamsCache({undoCache:a=[],redoCache:e=[]}){this._undoMutationParamsCache=a,this._redoMutationParamsCache=e}getActiveRange(){return this._previousActiveRange}setActiveRange(a){this._previousActiveRange=a}pushUndoRedoMutationParams(a,e){this._undoMutationParamsCache.push(a),this._redoMutationParamsCache.push(e)}fetchComposedUndoRedoMutationParams(){if(this._undoMutationParamsCache.length===0||this._previousActiveRange==null||this._redoMutationParamsCache.length===0)return null;const{unitId:a}=this._undoMutationParamsCache[0],e={unitId:a,actions:this._undoMutationParamsCache.reverse().reduce((i,o)=>t.JSONX.compose(i,o.actions),null),textRanges:[]};return{redoMutationParams:{unitId:a,actions:this._redoMutationParamsCache.reduce((i,o)=>t.JSONX.compose(i,o.actions),null),textRanges:[]},undoMutationParams:e,previousActiveRange:this._previousActiveRange}}dispose(){this._undoMutationParamsCache=[],this._redoMutationParamsCache=[],this._previousActiveRange=null}}var kt=Object.defineProperty,Gt=Object.getOwnPropertyDescriptor,jt=(s,a,e,n)=>{for(var i=n>1?void 0:n?Gt(a,e):a,o=s.length-1,r;o>=0;o--)(r=s[o])&&(i=(n?r(a,e,i):r(i))||i);return n&&i&&kt(a,e,i),i},Ge=(s,a)=>(e,n)=>a(e,n,s);m.DocSkeletonManagerService=class extends t.RxDisposable{constructor(e,n,i){super();D(this,"_skeleton");D(this,"_docViewModel");D(this,"_currentSkeleton$",new G.BehaviorSubject(null));D(this,"currentSkeleton$",this._currentSkeleton$.asObservable());D(this,"_currentSkeletonBefore$",new G.BehaviorSubject(null));D(this,"currentSkeletonBefore$",this._currentSkeletonBefore$.asObservable());D(this,"_currentViewModel$",new G.BehaviorSubject(null));D(this,"currentViewModel$",this._currentViewModel$.asObservable());this._context=e,this._localeService=n,this._univerInstanceService=i,this._init(),this._univerInstanceService.getCurrentTypeOfUnit$(t.UniverInstanceType.UNIVER_DOC).pipe(G.takeUntil(this.dispose$)).subscribe(o=>{(o==null?void 0:o.getUnitId())===this._context.unitId&&this._update(o)})}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 n=this._context.unitId;if(e.getBody()==null)return;this._docViewModel&&n===t.DOCS_NORMAL_EDITOR_UNIT_ID_KEY?(this._docViewModel.reset(e),this._context.unit=e):this._docViewModel||(this._docViewModel=this._buildDocViewModel(e)),this._skeleton||(this._skeleton=this._buildSkeleton(this._docViewModel));const i=this._skeleton;i.calculate(),this._currentSkeletonBefore$.next(i),this._currentSkeleton$.next(i),this._currentViewModel$.next(this._docViewModel)}_buildSkeleton(e){return E.DocumentSkeleton.create(e,this._localeService)}_buildDocViewModel(e){return new E.DocumentViewModel(e)}},m.DocSkeletonManagerService=jt([Ge(1,k.Inject(t.LocaleService)),Ge(2,t.IUniverInstanceService)],m.DocSkeletonManagerService);const je="doc.mutation.rich-text-editing",U={id:je,type:t.CommandType.MUTATION,handler:(s,a)=>{var R,A;const{unitId:e,segmentId:n="",actions:i,textRanges:o,prevTextRanges:r,trigger:l,noHistory:c,isCompositionEnd:d,noNeedSetTextRange:u,debounce:S}=a,g=s.get(t.IUniverInstanceService),v=s.get(E.IRenderManagerService),h=g.getUniverDocInstance(e),T=(R=v.getRenderById(e))==null?void 0:R.with(m.DocSkeletonManagerService).getViewModel();if(h==null||T==null)throw new Error(`DocumentDataModel or documentViewModel not found for unitId: ${e}`);const f=s.get(m.TextSelectionManagerService),I=((A=f.getSelections())!=null?A:[]).map(j),_=s.get(m.DocStateChangeManagerService),y=s.get(Y),x=!!h.getSnapshot().disabled;if(t.JSONX.isNoop(i)||i&&i.length===0||x)return{unitId:e,actions:[],textRanges:I};const C=t.JSONX.invertWithDoc(i,h.getSnapshot());h.apply(i),T.reset(h),!u&&o&&l!=null&&queueMicrotask(()=>{f.replaceTextRanges(o)});const M={commandId:je,unitId:e,segmentId:n,trigger:l,noHistory:c,debounce:S,redoState:{actions:i,textRanges:o},undoState:{actions:C,textRanges:r!=null?r:I}};if(d){const O=y.fetchComposedUndoRedoMutationParams();if(O==null)throw new Error("historyParams is null in RichTextEditingMutation");const{undoMutationParams:N,redoMutationParams:b,previousActiveRange:P}=O;M.redoState.actions=b.actions,M.undoState.actions=N.actions,M.undoState.textRanges=[P]}return _.setChangeState(M),{unitId:e,actions:C,textRanges:I}}};function $e(s,a){var n;return(n=s.get(E.IRenderManagerService).getRenderById(a))==null?void 0:n.with(m.DocSkeletonManagerService)}function B(s,a=""){if(!a)return["body"];const{headers:e,footers:n}=s.getSnapshot();if(e==null&&n==null)throw new Error("Document data model must have headers or footers when update by segment id");if((e==null?void 0:e[a])!=null)return["headers",a,"body"];if((n==null?void 0:n[a])!=null)return["footers",a,"body"];throw new Error("Segment id not found in headers or footers")}const ze="doc.command.insert-text",K={id:ze,type:t.CommandType.COMMAND,handler:async(s,a)=>{var R;const e=s.get(t.ICommandService),{range:n,segmentId:i,body:o,unitId:r,textRanges:l,cursorOffset:c}=a,d=s.get(m.TextSelectionManagerService),S=s.get(t.IUniverInstanceService).getUnit(r,t.UniverInstanceType.UNIVER_DOC);if(S==null)return!1;const g=d.getActiveRange(),v=S.getSelfOrHeaderFooterModel((R=g==null?void 0:g.segmentId)!=null?R:"").getBody();if(!v)return!1;const h=J(n,v),{startOffset:T,collapsed:f}=h,p=c!=null?c:o.dataStream.length,I=[{startOffset:T+p,endOffset:T+p,style:g==null?void 0:g.style,collapsed:f}],_={id:U.id,params:{unitId:r,actions:[],textRanges:l!=null?l:I,debounce:!0}},y=new t.TextX,x=t.JSONX.getInstance();if(f)T>0&&y.push({t:t.TextXActionType.RETAIN,len:T,segmentId:i});else{const{dos:A,retain:O}=De(h,i,0,v);y.push(...A),l||(_.params.textRanges=[{startOffset:T+p+O,endOffset:T+p+O,collapsed:f}])}y.push({t:t.TextXActionType.INSERT,body:o,len:o.dataStream.length,line:0,segmentId:i});const C=B(S,i);return _.params.actions=x.editOp(y.serialize(),C),!!e.syncExecuteCommand(_.id,_.params)}};var L=(s=>(s[s.LEFT=0]="LEFT",s[s.RIGHT=1]="RIGHT",s))(L||{});const ne={id:"doc.command.delete-text",type:t.CommandType.COMMAND,handler:async(s,a)=>{var A;const e=s.get(t.ICommandService),n=s.get(t.IUniverInstanceService),{range:i,segmentId:o,unitId:r,direction:l,len:c=1}=a,d=n.getUnit(r,t.UniverInstanceType.UNIVER_DOC),u=d==null?void 0:d.getSelfOrHeaderFooterModel(o).getBody();if(d==null||u==null)return!1;const{startOffset:S}=i,g=u.dataStream,v=l===0?S-c:S,h=v+c-1,T=(A=u.customRanges)==null?void 0:A.filter(O=>Oe(O.startIndex,O.endIndex,v,h)),f=T==null?void 0:T.filter(O=>Re(v,c,O,g)),p=[];for(let O=0;O<c;O++)p.push(v+O);f==null||f.forEach(O=>{p.push(O.startIndex,O.endIndex)}),p.sort((O,N)=>O-N);const I=p[0],_={id:U.id,params:{unitId:r,actions:[],textRanges:[{startOffset:I,endOffset:I,collapsed:!0}],debounce:!0}},y=new t.TextX,x=t.JSONX.getInstance();let C=0;for(let O=0;O<p.length;O++){const N=p[O];N-C>0&&y.push({t:t.TextXActionType.RETAIN,len:N-C,segmentId:o}),y.push({t:t.TextXActionType.DELETE,len:1,segmentId:o,line:0}),C=N+1}const M=B(d,o);return _.params.actions=x.editOp(y.serialize(),M),!!e.syncExecuteCommand(_.id,_.params)}},Ae={id:"doc.command.update-text",type:t.CommandType.COMMAND,handler:async(s,a)=>{const{range:e,segmentId:n,updateBody:i,coverType:o,unitId:r,textRanges:l}=a,c=s.get(t.ICommandService),u=s.get(t.IUniverInstanceService).getCurrentUniverDocInstance();if(u==null)return!1;const S={id:U.id,params:{unitId:r,actions:[],textRanges:l}},g=new t.TextX,v=t.JSONX.getInstance(),{startOffset:h,endOffset:T}=e;g.push({t:t.TextXActionType.RETAIN,len:h,segmentId:n}),g.push({t:t.TextXActionType.RETAIN,body:i,len:T-h,segmentId:n,coverType:o});const f=B(u,n);return S.params.actions=v.editOp(g.serialize(),f),!!c.syncExecuteCommand(S.id,S.params)}};function He(s,a){const e=[];for(let n=0,i=s.length;n<i;n++)s[n]===t.DataStreamTreeTokenType.PARAGRAPH&&e.push({startIndex:n});if(a)for(const n of e)a.bullet&&(n.bullet=t.Tools.deepClone(a.bullet)),a.paragraphStyle&&(n.paragraphStyle=t.Tools.deepClone(a.paragraphStyle));return e}const Ve={id:"doc.command.break-line",type:t.CommandType.COMMAND,handler:async s=>{var v,h;const a=s.get(m.TextSelectionManagerService),e=s.get(t.IUniverInstanceService),n=s.get(t.ICommandService),i=a.getActiveRange();if(i==null)return!1;const o=e.getCurrentUniverDocInstance(),r=o==null?void 0:o.getBody();if(!o||!r)return!1;const l=o.getUnitId(),{startOffset:c,endOffset:d}=J(i,r),{segmentId:u}=i,g=((h=(v=o.getSelfOrHeaderFooterModel(u).getBody())==null?void 0:v.paragraphs)!=null?h:[]).find(T=>T.startIndex>=c);if(g&&g.startIndex>d){const T=t.normalizeBody(t.getBodySlice(r,d,g.startIndex)),f={startOffset:c,endOffset:g.startIndex,collapsed:!1};return t.updateAttributeByInsert(T,{dataStream:t.DataStreamTreeTokenType.PARAGRAPH,paragraphs:He(t.DataStreamTreeTokenType.PARAGRAPH,g)},1,0),await n.executeCommand(K.id,{unitId:l,body:T,range:f,segmentId:u,cursorOffset:1})}else return await n.executeCommand(K.id,{unitId:l,body:{dataStream:t.DataStreamTreeTokenType.PARAGRAPH,paragraphs:He(t.DataStreamTreeTokenType.PARAGRAPH,g)},range:i,segmentId:u})}},$t={id:"doc.command.inner-paste",type:t.CommandType.COMMAND,handler:async(s,a)=>{const{segmentId:e,textRanges:n}=a,i=a.body,o=s.get(t.ICommandService),r=s.get(m.TextSelectionManagerService),l=s.get(t.IUniverInstanceService),c=r.getSelections();if(!Array.isArray(c)||c.length===0)return!1;const d=l.getCurrentUniverDocInstance(),u=d==null?void 0:d.getSelfOrHeaderFooterModel(e).getBody();if(d==null||u==null)return!1;const S=d.getUnitId(),g={id:U.id,params:{unitId:S,actions:[],textRanges:n}},v=new t.MemoryCursor;v.reset();const h=new t.TextX,T=t.JSONX.getInstance();for(const I of c){const{startOffset:_,endOffset:y,collapsed:x}=I,C=_-v.cursor;if(x)h.push({t:t.TextXActionType.RETAIN,len:C,segmentId:e});else{const{dos:M}=De(I,e,v.cursor,u);h.push(...M)}h.push({t:t.TextXActionType.INSERT,body:i,len:i.dataStream.length,line:0,segmentId:e}),v.reset(),v.moveCursor(y)}const f=B(d,e);return g.params.actions=T.editOp(h.serialize(),f),!!o.syncExecuteCommand(g.id,g.params)}},Ne={id:"doc.command.inner-cut",type:t.CommandType.COMMAND,handler:async(s,a)=>{var p;const{segmentId:e,textRanges:n}=a,i=s.get(t.ICommandService),o=s.get(m.TextSelectionManagerService),r=s.get(t.IUniverInstanceService),l=o.getSelections();if(!Array.isArray(l)||l.length===0)return!1;const c=(p=r.getCurrentUniverDocInstance())==null?void 0:p.getUnitId();if(!c)return!1;const d=r.getUniverDocInstance(c),u=t.getDocsUpdateBody(d.getSnapshot(),e);if(d==null||u==null)return!1;const S={id:U.id,params:{unitId:c,actions:[],textRanges:n}},g=new t.MemoryCursor;g.reset();const v=new t.TextX,h=t.JSONX.getInstance();for(const I of l){const{startOffset:_,endOffset:y,collapsed:x}=I,C=_-g.cursor;x?v.push({t:t.TextXActionType.RETAIN,len:C,segmentId:e}):v.push(...zt(I,u,e,g.cursor)),g.reset(),g.moveCursor(y)}const T=B(d,e);return S.params.actions=h.editOp(v.serialize(),T),!!i.syncExecuteCommand(S.id,S.params)}};function zt(s,a,e="",n=0){var p;const{startOffset:i,endOffset:o}=te(s,a),r=[],{paragraphs:l=[],dataStream:c}=a,d=i-n,u=o-n,S=l==null?void 0:l.find(I=>I.startIndex-n>=d&&I.startIndex-n<=u),g=(p=a.customRanges)==null?void 0:p.filter(I=>Oe(I.startIndex,I.endIndex,i,o)),v=new Set(g==null?void 0:g.filter(I=>Re(i,o-i,I,c))),h=new Set;if(g==null||g.forEach(I=>{v.has(I)||(I.startIndex-n>=d&&I.startIndex-n<=u&&I.endIndex-n>u&&h.add(I.startIndex),I.endIndex-n>=d&&I.endIndex-n<=u&&I.startIndex<d&&h.add(I.endIndex))}),d>0&&r.push({t:t.TextXActionType.RETAIN,len:d,segmentId:e}),S&&S.startIndex-n>d){const I=S.startIndex-n;h.add(I)}const T=[...h].sort((I,_)=>I-_);let f=d;return T.forEach(I=>{const _=I-f;_>0&&r.push({t:t.TextXActionType.DELETE,len:_,line:0,segmentId:e}),r.push({t:t.TextXActionType.RETAIN,len:1,segmentId:e}),f=I+1}),f<u&&r.push({t:t.TextXActionType.DELETE,len:u-f,line:0,segmentId:e}),r}const ae={id:"doc.command.merge-two-paragraph",type:t.CommandType.COMMAND,handler:async(s,a)=>{var N,b;const e=s.get(m.TextSelectionManagerService),n=s.get(t.IUniverInstanceService),i=s.get(t.ICommandService),{direction:o,range:r}=a,l=e.getActiveRange(),c=e.getSelections();if(l==null||c==null)return!1;const{segmentId:d,style:u}=l,S=n.getCurrentUniverDocInstance(),g=S==null?void 0:S.getSelfOrHeaderFooterModel(d).getBody();if(!S||!g)return!1;const v=te(l,g),{startOffset:h,collapsed:T}=v;if(!T)return!1;const f=o===L.LEFT?h:h+1,p=(b=(N=g.paragraphs)==null?void 0:N.find(P=>P.startIndex>=f))==null?void 0:b.startIndex,I=Ht(g,f,p),_=o===L.LEFT?h-1:h,y=S.getUnitId(),x=[{startOffset:_,endOffset:_,style:u}],C={id:U.id,params:{unitId:y,actions:[],textRanges:x,prevTextRanges:[r]}},M=new t.TextX,R=t.JSONX.getInstance();M.push({t:t.TextXActionType.RETAIN,len:o===L.LEFT?h-1:h,segmentId:d}),I.dataStream.length&&M.push({t:t.TextXActionType.INSERT,body:I,len:I.dataStream.length,line:0,segmentId:d}),M.push({t:t.TextXActionType.RETAIN,len:1,segmentId:d}),M.push({t:t.TextXActionType.DELETE,len:p+1-f,line:0,segmentId:d});const A=B(S,d);return C.params.actions=R.editOp(M.serialize(),A),!!i.syncExecuteCommand(C.id,C.params)}},Je={id:"doc.command.delete-left",type:t.CommandType.COMMAND,handler:async s=>{const a=s.get(m.TextSelectionManagerService),e=s.get(t.IUniverInstanceService),n=s.get(t.ICommandService);let i=!0;const o=e.getCurrentUniverDocInstance();if(!o)return!1;const r=o.getUnitId(),l=$e(s,r),c=a.getActiveRange(),d=a.getSelections(),u=l==null?void 0:l.getSkeleton();if(c==null||u==null||d==null)return!1;const{segmentId:S,style:g,segmentPage:v}=c,h=o.getSelfOrHeaderFooterModel(S).getBody();if(h==null)return!1;const T=te(c,h),{startOffset:f,collapsed:p}=T,I=u.findNodeByCharIndex(f,S,v),_=E.hasListGlyph(I),y=E.isIndentByGlyph(I,h);let x=f;const C=u.findNodeByCharIndex(f-1,S,v);if(E.isFirstGlyph(I)&&C!==I&&(_===!0||y===!0)&&p){const R=E.getParagraphByGlyph(I,h);if(R==null)return!1;const A=R==null?void 0:R.startIndex,O={startIndex:0},N=R.paragraphStyle;if(_===!0){const P=R.paragraphStyle;if(P){O.paragraphStyle=P;const{hanging:Q}=P;Q&&(O.paragraphStyle.indentStart=Q,O.paragraphStyle.hanging=void 0)}}else if(y===!0){const P=R.bullet;P&&(O.bullet=P),N!=null&&(O.paragraphStyle={...N},delete O.paragraphStyle.hanging,delete O.paragraphStyle.indentStart)}const b=[{startOffset:x,endOffset:x,style:g}];i=await n.executeCommand(Ae.id,{unitId:o.getUnitId(),updateBody:{dataStream:"",paragraphs:[{...O}]},range:{startOffset:A,endOffset:A+1},textRanges:b,coverType:t.UpdateDocsAttributeType.REPLACE,segmentId:S})}else if(p===!0){if(C==null)return!0;C.content==="\r"?i=await n.executeCommand(ae.id,{direction:L.LEFT,range:T}):(x-=C.count,i=await n.executeCommand(ne.id,{unitId:o.getUnitId(),range:T,segmentId:S,direction:L.LEFT,len:C.count}))}else{const R=Ye({...c,...T},d);i=await n.executeCommand(Ne.id,{segmentId:S,textRanges:R})}return i}},We={id:"doc.command.delete-right",type:t.CommandType.COMMAND,handler:async s=>{const a=s.get(m.TextSelectionManagerService),n=s.get(t.IUniverInstanceService).getCurrentUniverDocInstance();if(!n)return!1;const i=$e(s,n.getUnitId()),o=s.get(t.ICommandService),r=a.getActiveRange(),l=a.getSelections(),c=i==null?void 0:i.getSkeleton();if(r==null||c==null||l==null)return!1;const{segmentId:d,style:u,segmentPage:S}=r,g=n==null?void 0:n.getSelfOrHeaderFooterModel(d).getBody();if(!n||!g)return!1;const v=J(r,g),{startOffset:h,collapsed:T}=v;if(h===g.dataStream.length-2&&T)return!0;let f=!1;if(T===!0){const p=c.findNodeByCharIndex(h,d,S);if(p.content==="\r")f=await o.executeCommand(ae.id,{direction:L.RIGHT,range:r});else{const I=[{startOffset:h,endOffset:h,style:u}];f=await o.executeCommand(ne.id,{unitId:n.getUnitId(),range:{startOffset:h,endOffset:h,collapsed:T},segmentId:d,direction:L.RIGHT,textRanges:I,len:p.count})}}else{const p=Ye(r,l);f=await o.executeCommand(Ne.id,{segmentId:d,textRanges:p})}return f}};function Ht(s,a,e){const{textRuns:n}=s,i=s.dataStream.substring(a,e);if(n==null)return{dataStream:i,customRanges:t.getCustomRangeSlice(s,a,e).customRanges,customDecorations:t.getCustomDecorationSlice(s,a,e)};const o=[];for(const r of n){const{st:l,ed:c}=r;c<=a||l>=e||(l<a?o.push({...r,st:0,ed:c-a}):c>e?o.push({...r,st:l-a,ed:e-a}):o.push({...r,st:l-a,ed:c-a}))}return{dataStream:i,textRuns:o,customRanges:t.getCustomRangeSlice(s,a,e).customRanges,customDecorations:t.getCustomDecorationSlice(s,a,e)}}function Ye(s,a){let e=s.endOffset;for(const i of a){const{startOffset:o,endOffset:r}=i;o==null||r==null||r<=s.endOffset&&(e-=r-o)}return[{startOffset:e,endOffset:e,style:s.style}]}const Ue={id:"doc.command.ime-input",type:t.CommandType.COMMAND,handler:async(s,a)=>{const{unitId:e,newText:n,oldTextLen:i,isCompositionEnd:o,isCompositionStart:r}=a,l=s.get(t.ICommandService),c=s.get(Y),u=s.get(t.IUniverInstanceService).getCurrentUniverDocInstance();if(u==null)return!1;const S=c.getActiveRange();if(!S)return!1;const{startOffset:g,style:v,segmentId:h}=S,T=u.getSelfOrHeaderFooterModel(h).getBody();if(T==null)return!1;const f=J(S,T);Object.assign(S,f);const p=n.length,I=[{startOffset:g+p,endOffset:g+p,collapsed:!0,style:v}],_={id:U.id,params:{unitId:e,actions:[],textRanges:I}},y=new t.TextX,x=t.JSONX.getInstance();if(!S.collapsed&&r){const{dos:R,retain:A,cursor:O}=De(S,h,0,T);y.push(...R),_.params.textRanges=[{startOffset:g+p+A,endOffset:g+p+A,collapsed:!0}]}else y.push({t:t.TextXActionType.RETAIN,len:g,segmentId:h});i>0&&y.push({t:t.TextXActionType.DELETE,len:i,line:0,segmentId:h}),y.push({t:t.TextXActionType.INSERT,body:{dataStream:n},len:n.length,line:0,segmentId:h});const C=B(u,h);_.params.actions=x.editOp(y.serialize(),C),_.params.noHistory=!o,_.params.isCompositionEnd=o;const M=l.syncExecuteCommand(_.id,_.params);return c.pushUndoRedoMutationParams(M,_.params),!!M}};function w(s,a,e,n){var o;const{segmentId:i}=(o=e.getActiveRange())!=null?o:{};return i==null?!1:n.executeCommand(be.id,{segmentId:i,preCommandId:s,...a!=null?a:{}})}const Ke="doc.command.set-inline-format-bold",ie={id:Ke,type:t.CommandType.COMMAND,handler:async(s,a)=>{const e=s.get(t.ICommandService),n=s.get(m.TextSelectionManagerService);return w(Ke,a,n,e)}},Ze="doc.command.set-inline-format-italic",se={id:Ze,type:t.CommandType.COMMAND,handler:async(s,a)=>{const e=s.get(t.ICommandService),n=s.get(m.TextSelectionManagerService);return w(Ze,a,n,e)}},qe="doc.command.set-inline-format-underline",oe={id:qe,type:t.CommandType.COMMAND,handler:async(s,a)=>{const e=s.get(t.ICommandService),n=s.get(m.TextSelectionManagerService);return w(qe,a,n,e)}},Qe="doc.command.set-inline-format-strikethrough",re={id:Qe,type:t.CommandType.COMMAND,handler:async(s,a)=>{const e=s.get(t.ICommandService),n=s.get(m.TextSelectionManagerService);return w(Qe,a,n,e)}},et="doc.command.set-inline-format-subscript",z={id:et,type:t.CommandType.COMMAND,handler:async(s,a)=>{const e=s.get(t.ICommandService),n=s.get(m.TextSelectionManagerService);return w(et,a,n,e)}},tt="doc.command.set-inline-format-superscript",ce={id:tt,type:t.CommandType.COMMAND,handler:async(s,a)=>{const e=s.get(t.ICommandService),n=s.get(m.TextSelectionManagerService);return w(tt,a,n,e)}},nt="doc.command.set-inline-format-fontsize",le={id:nt,type:t.CommandType.COMMAND,handler:async(s,a)=>{const e=s.get(t.ICommandService),n=s.get(m.TextSelectionManagerService);return w(nt,a,n,e)}},at="doc.command.set-inline-format-font-family",de={id:at,type:t.CommandType.COMMAND,handler:async(s,a)=>{const e=s.get(t.ICommandService),n=s.get(m.TextSelectionManagerService);return w(at,a,n,e)}},it="doc.command.set-inline-format-text-color",ue={id:it,type:t.CommandType.COMMAND,handler:async(s,a)=>{const e=s.get(t.ICommandService),n=s.get(m.TextSelectionManagerService);return w(it,a,n,e)}},st="doc.command.set-inline-format-text-background-color",me={id:st,type:t.CommandType.COMMAND,handler:async(s,a)=>{const e=s.get(t.ICommandService),n=s.get(m.TextSelectionManagerService);return w(st,a,n,e)}},ot="doc.command.reset-inline-format-text-background-color",ge={id:ot,type:t.CommandType.COMMAND,handler:async(s,a)=>{const e=s.get(t.ICommandService),n=s.get(m.TextSelectionManagerService);return w(ot,a,n,e)}},rt={[ie.id]:"bl",[se.id]:"it",[oe.id]:"ul",[re.id]:"st",[le.id]:"fs",[de.id]:"ff",[ue.id]:"cl",[me.id]:"bg",[ge.id]:"bg",[z.id]:"va",[ce.id]:"va"},be={id:"doc.command.set-inline-format",type:t.CommandType.COMMAND,handler:async(s,a)=>{const{segmentId:e,value:n,preCommandId:i}=a,o=s.get(t.ICommandService),r=s.get(m.TextSelectionManagerService),l=s.get(t.IUniverInstanceService),c=r.getSelections();if(!Array.isArray(c)||c.length===0)return!1;const d=l.getCurrentUniverDocInstance();if(d==null)return!1;const u=d.getUnitId();let S;switch(i){case ie.id:case se.id:case oe.id:case re.id:case z.id:case ce.id:{S=Jt(d.getSelfOrHeaderFooterModel(e).getBody().textRuns,i,c);break}case le.id:case de.id:{S=n;break}case ue.id:case me.id:{S={rgb:n};break}case ge.id:{S={rgb:null};break}default:throw new Error(`Unknown command: ${i} in handleInlineFormat`)}const g={id:U.id,params:{unitId:u,actions:[],textRanges:c.map(j)}},v=new t.TextX,h=t.JSONX.getInstance(),T=new t.MemoryCursor;T.reset();for(const I of c){const{startOffset:_,endOffset:y}=I,x={dataStream:"",textRuns:[{st:0,ed:y-_,ts:{[rt[i]]:S}}]},C=_-T.cursor;C!==0&&v.push({t:t.TextXActionType.RETAIN,len:C,segmentId:e}),v.push({t:t.TextXActionType.RETAIN,body:x,len:y-_,segmentId:e}),T.reset(),T.moveCursor(y)}const f=B(d,e);return g.params.actions=h.editOp(v.serialize(),f),!!o.syncExecuteCommand(g.id,g.params)}};function Vt(s){return s!==null&&typeof s=="object"}function Jt(s,a,e){let n=0,i=0;const o=rt[a];for(;n!==s.length&&i!==e.length;){const{startOffset:r,endOffset:l}=e[i],{st:c,ed:d,ts:u}=s[n];if(l<=c)i++;else if(d<=r)n++;else{if(/bl|it/.test(o))return(u==null?void 0:u[o])===t.BooleanNumber.TRUE?t.BooleanNumber.FALSE:t.BooleanNumber.TRUE;if(/ul|st/.test(o))return Vt(u==null?void 0:u[o])&&(u==null?void 0:u[o]).s===t.BooleanNumber.TRUE?{s:t.BooleanNumber.FALSE}:{s:t.BooleanNumber.TRUE};if(/va/.test(o))return a===z.id?(u==null?void 0:u[o])===t.BaselineOffset.SUBSCRIPT?t.BaselineOffset.NORMAL:t.BaselineOffset.SUBSCRIPT:(u==null?void 0:u[o])===t.BaselineOffset.SUPERSCRIPT?t.BaselineOffset.NORMAL:t.BaselineOffset.SUPERSCRIPT;n++}}return/bl|it/.test(o)?t.BooleanNumber.TRUE:/ul|st/.test(o)?{s:t.BooleanNumber.TRUE}:a===z.id?t.BaselineOffset.SUBSCRIPT:t.BaselineOffset.SUPERSCRIPT}const Se={id:"doc.command.list-operation",type:t.CommandType.COMMAND,handler:(s,a)=>{var b,P,Q,_t;const e=s.get(m.TextSelectionManagerService),n=s.get(t.IUniverInstanceService),i=s.get(t.ICommandService),{listType:o}=a,r=n.getCurrentUniverDocInstance(),l=e.getActiveRange();if(r==null||l==null)return!1;const{segmentId:c}=l,d=(b=e.getSelections())!=null?b:[],u=(P=r.getSelfOrHeaderFooterModel(c).getBody())==null?void 0:P.paragraphs,S=d.map(j);if(u==null)return!1;const g=dt(l,u),v=r.getUnitId(),h=g.every($=>{var X;return((X=$.bullet)==null?void 0:X.listType)===o});let f=t.Tools.generateRandomId(6);if(g.length===1){const $=u.indexOf(g[0]),X=u[$-1],F=u[$+1];X&&X.bullet&&X.bullet.listType===o?f=X.bullet.listId:F&&F.bullet&&F.bullet.listType===o&&(f=F.bullet.listId)}const p={id:U.id,params:{unitId:v,actions:[],textRanges:S}},I=new t.MemoryCursor;I.reset();const _=new t.TextX,y=t.JSONX.getInstance(),x=(Q=r.getSnapshot().lists)!=null?Q:{},C={...t.PRESET_LIST_TYPE,...x},{charSpace:M,defaultTabStop:R=36,gridType:A}=r.getSnapshot().documentStyle;for(const $ of g){const{startIndex:X,paragraphStyle:F={}}=$,{indentFirstLine:yn=0,snapToGrid:On,indentStart:Pe=0}=F,{hanging:Be,indentStart:yt}=C[o].nestingLevel[0],we=E.getCharSpaceApply(M,R,A,On);_.push({t:t.TextXActionType.RETAIN,len:X-I.cursor,segmentId:c}),_.push({t:t.TextXActionType.RETAIN,len:1,body:{dataStream:"",paragraphs:[h?{paragraphStyle:{...F,hanging:void 0,indentStart:Pe?Math.max(0,E.getNumberUnitValue(Pe,we)+Be-yt):void 0},startIndex:0}:{startIndex:0,paragraphStyle:{...F,indentFirstLine:void 0,hanging:Be,indentStart:yt-Be+E.getNumberUnitValue(yn,we)+E.getNumberUnitValue(Pe,we)},bullet:{...(_t=$.bullet)!=null?_t:{nestingLevel:0,textStyle:{fs:20}},listType:o,listId:f}}]},segmentId:c,coverType:t.UpdateDocsAttributeType.REPLACE}),I.moveCursorTo(X+1)}const O=B(r,c);return p.params.actions=y.editOp(_.serialize(),O),!!i.syncExecuteCommand(p.id,p.params)}},ct={id:"doc.command.bullet-list",type:t.CommandType.COMMAND,handler:s=>s.get(t.ICommandService).syncExecuteCommand(Se.id,{listType:t.PresetListType.BULLET_LIST})},lt={id:"doc.command.order-list",type:t.CommandType.COMMAND,handler:s=>s.get(t.ICommandService).syncExecuteCommand(Se.id,{listType:t.PresetListType.ORDER_LIST})};function dt(s,a){const{startOffset:e,endOffset:n}=s,i=[];let o=-1;for(const r of a){const{startIndex:l}=r;(e>o&&e<=l||n>o&&n<=l||l>=e&&l<=n)&&i.push(r),o=l}return i}const ut={id:"doc.command-replace-content",type:t.CommandType.COMMAND,handler:async(s,a)=>{const{unitId:e,body:n,textRanges:i,segmentId:o=""}=a,r=s.get(t.IUniverInstanceService),l=s.get(t.ICommandService),c=s.get(m.TextSelectionManagerService),d=r.getUniverDocInstance(e),u=d==null?void 0:d.getSnapshot().body,S=c.getSelections();if(d==null||u==null||!Array.isArray(S)||S.length===0)return!1;const g=gt(e,o,d,u,n);return g.params.textRanges=i,!!l.syncExecuteCommand(g.id,g.params)}},mt={id:"doc.command-cover-content",type:t.CommandType.COMMAND,handler:async(s,a)=>{const{unitId:e,body:n,segmentId:i=""}=a,o=s.get(t.IUniverInstanceService),r=s.get(t.ICommandService),l=s.get(t.IUndoRedoService),c=o.getUniverDocInstance(e),d=c==null?void 0:c.getSnapshot().body;if(c==null||d==null)return!1;const u=gt(e,i,c,d,n);return u.params.noNeedSetTextRange=!0,u.params.noHistory=!0,r.syncExecuteCommand(u.id,u.params),l.clearUndoRedo(e),!0}};function gt(s,a,e,n,i){const o={id:U.id,params:{unitId:s,actions:[],textRanges:[]}},r=new t.TextX,l=t.JSONX.getInstance(),c=(n==null?void 0:n.dataStream.length)-2;c>0&&r.push({t:t.TextXActionType.DELETE,len:c,line:0,segmentId:a}),i.dataStream.length>0&&r.push({t:t.TextXActionType.INSERT,body:i,len:i.dataStream.length,line:0,segmentId:a});const d=B(e,a);return o.params.actions=l.editOp(r.serialize(),d),o}const Wt=(s,a)=>{const e=s.get(t.IUniverInstanceService).getUniverDocInstance(a.unitId),n=(e==null?void 0:e.zoomRatio)||1;return{...t.Tools.deepClone(a),zoomRatio:n}},Z={id:"doc.operation.set-zoom-ratio",type:t.CommandType.OPERATION,handler:(s,a)=>{const e=s.get(t.IUniverInstanceService).getUniverDocInstance(a.unitId);if(!e)return!1;const n=e.getSnapshot();return n.settings==null?n.settings={zoomRatio:a.zoomRatio}:n.settings.zoomRatio=a.zoomRatio,!0}},St={type:t.CommandType.COMMAND,id:"doc.command.set-zoom-ratio",handler:async(s,a)=>{var S,g,v;const e=s.get(t.ICommandService),n=s.get(t.IUndoRedoService),i=s.get(t.IUniverInstanceService);let o=(S=i.getCurrentUniverDocInstance())==null?void 0:S.getUnitId();if(!o)return!1;let r=1;if(a&&(o=(g=a.documentId)!=null?g:o,r=(v=a.zoomRatio)!=null?v:r),!i.getUniverDocInstance(o))return!1;const c={zoomRatio:r,unitId:o},d=Wt(s,c);return e.syncExecuteCommand(Z.id,c)?(n.pushUndoRedo({unitID:o,undoMutations:[{id:Z.id,params:d}],redoMutations:[{id:Z.id,params:c}]}),!0):!1}},fe={id:"doc.operation.move-cursor",type:t.CommandType.OPERATION,handler:(s,a)=>!!a},he={id:"doc.operation.move-selection",type:t.CommandType.OPERATION,handler:(s,a)=>!!a},ft={id:"doc.operation.select-all",type:t.CommandType.COMMAND,handler:async s=>{const a=s.get(t.IUniverInstanceService),e=s.get(m.TextSelectionManagerService),n=a.getCurrentUniverDocInstance(),i=e.getActiveRange();if(n==null||i==null)return!1;const{segmentId:o}=i,r=n.getSelfOrHeaderFooterModel(o).getSnapshot().body;if(r==null)return!1;const l=[{startOffset:0,endOffset:r.dataStream.length-2}];return e.replaceTextRanges(l,!1),!0}};var Yt=Object.defineProperty,Kt=Object.getOwnPropertyDescriptor,Zt=(s,a,e,n)=>{for(var i=n>1?void 0:n?Kt(a,e):a,o=s.length-1,r;o>=0;o--)(r=s[o])&&(i=(n?r(a,e,i):r(i))||i);return n&&i&&Yt(a,e,i),i},q=(s,a)=>(e,n)=>a(e,n,s);let pe=class extends t.Disposable{constructor(a,e,n,i,o){super();D(this,"_previousIMEContent","");D(this,"_isCompositionStart",!0);D(this,"_onStartSubscription");D(this,"_onUpdateSubscription");D(this,"_onEndSubscription");this._univerInstanceService=a,this._renderManagerSrv=e,this._textSelectionRenderManager=n,this._imeInputManagerService=i,this._commandService=o,this._initialize()}dispose(){var a,e,n;(a=this._onStartSubscription)==null||a.unsubscribe(),(e=this._onUpdateSubscription)==null||e.unsubscribe(),(n=this._onEndSubscription)==null||n.unsubscribe()}_initialize(){this._initialOnCompositionstart(),this._initialOnCompositionUpdate(),this._initialOnCompositionend()}_initialOnCompositionstart(){this._onStartSubscription=this._textSelectionRenderManager.onCompositionstart$.subscribe(a=>{if(a==null)return;this._resetIME();const{activeRange:e}=a;e!=null&&this._imeInputManagerService.setActiveRange(t.Tools.deepClone(e))})}_initialOnCompositionUpdate(){this._onUpdateSubscription=this._textSelectionRenderManager.onCompositionupdate$.subscribe(async a=>{this._updateContent(a,!0)})}_initialOnCompositionend(){this._onEndSubscription=this._textSelectionRenderManager.onCompositionend$.subscribe(a=>{this._updateContent(a,!1)})}async _updateContent(a,e){var d;if(a==null)return;const n=this._univerInstanceService.getCurrentUniverDocInstance();if(!n)return;const i=(d=this._renderManagerSrv.getRenderById(n.getUnitId()))==null?void 0:d.with(m.DocSkeletonManagerService).getSkeleton(),{event:o,activeRange:r}=a;if(i==null||r==null)return;const c=o.data;c===this._previousIMEContent&&e||(await this._commandService.executeCommand(Ue.id,{unitId:n.getUnitId(),newText:c,oldTextLen:this._previousIMEContent.length,isCompositionStart:this._isCompositionStart,isCompositionEnd:!e}),e?(this._isCompositionStart&&(this._isCompositionStart=!1),this._previousIMEContent=c):this._resetIME())}_resetIME(){this._previousIMEContent="",this._isCompositionStart=!0,this._imeInputManagerService.clearUndoRedoMutationParamsCache(),this._imeInputManagerService.setActiveRange(null)}};pe=Zt([t.OnLifecycle(t.LifecycleStages.Rendered,pe),q(0,t.IUniverInstanceService),q(1,E.IRenderManagerService),q(2,E.ITextSelectionRenderManager),q(3,k.Inject(Y)),q(4,t.ICommandService)],pe);var qt=Object.defineProperty,Qt=Object.getOwnPropertyDescriptor,en=(s,a,e,n)=>{for(var i=n>1?void 0:n?Qt(a,e):a,o=s.length-1,r;o>=0;o--)(r=s[o])&&(i=(n?r(a,e,i):r(i))||i);return n&&i&&qt(a,e,i),i},Ie=(s,a)=>(e,n)=>a(e,n,s);let Te=class extends t.Disposable{constructor(a,e,n,i){super();D(this,"_onInputSubscription");this._univerInstanceService=a,this._renderManagerService=e,this._textSelectionManagerService=n,this._commandService=i,this._commandExecutedListener()}dispose(){var a;super.dispose(),(a=this._onInputSubscription)==null||a.unsubscribe()}_commandExecutedListener(){const a=[fe.id,he.id];this.disposeWithMe(this._commandService.onCommandExecuted(e=>{if(!a.includes(e.id))return;const n=e.params;switch(e.id){case fe.id:return this._handleMoveCursor(n.direction);case he.id:return this._handleShiftMoveSelection(n.direction);default:throw new Error("Unknown command")}}))}_handleShiftMoveSelection(a){var _,y,x;const e=this._textSelectionManagerService.getActiveRange(),n=this._textSelectionManagerService.getSelections(),i=this._univerInstanceService.getCurrentUniverDocInstance();if(!i)return;const o=(_=this._renderManagerService.getRenderById(i.getUnitId()))==null?void 0:_.with(m.DocSkeletonManagerService).getSkeleton(),r=this._getDocObject();if(e==null||o==null||r==null)return;const{startOffset:l,endOffset:c,style:d,collapsed:u,direction:S,segmentId:g,startNodePosition:v,endNodePosition:h,segmentPage:T}=e;if(n.length>1){let C=Number.POSITIVE_INFINITY,M=Number.NEGATIVE_INFINITY;for(const R of n)C=Math.min(C,R.startOffset),M=Math.max(M,R.endOffset);this._textSelectionManagerService.replaceTextRanges([{startOffset:a===t.Direction.LEFT||a===t.Direction.UP?M:C,endOffset:a===t.Direction.LEFT||a===t.Direction.UP?C:M,style:d}],!1);return}const f=u||S===E.RANGE_DIRECTION.FORWARD?l:c;let p=u||S===E.RANGE_DIRECTION.FORWARD?c:l;const I=(y=i.getSelfOrHeaderFooterModel(g).getBody().dataStream.length)!=null?y:Number.POSITIVE_INFINITY;if(a===t.Direction.LEFT||a===t.Direction.RIGHT){const C=o.findNodeByCharIndex(p-1,g,T),M=o.findNodeByCharIndex(p,g,T);p=a===t.Direction.RIGHT?p+M.count:p-((x=C==null?void 0:C.count)!=null?x:0),p=Math.min(I-2,Math.max(0,p)),this._textSelectionManagerService.replaceTextRanges([{startOffset:f,endOffset:p,style:d}],!1)}else{const C=o.findNodeByCharIndex(p,g,T),M=r.document.getOffsetConfig(),R=u?v:S===E.RANGE_DIRECTION.FORWARD?h:v,A=this._getTopOrBottomPosition(o,C,R,a===t.Direction.DOWN);if(A==null){const N=a===t.Direction.UP?0:I-2;if(N===p)return;this._textSelectionManagerService.replaceTextRanges([{startOffset:f,endOffset:N,style:d}],!1);return}const O=new E.NodePositionConvertToCursor(M,o).getRangePointData(A,A).cursorList[0];this._textSelectionManagerService.replaceTextRanges([{startOffset:f,endOffset:O.endOffset,style:d}],!1)}}_handleMoveCursor(a){var f,p,I;const e=this._textSelectionManagerService.getActiveRange(),n=this._textSelectionManagerService.getSelections(),i=this._univerInstanceService.getCurrentUniverDocInstance();if(!i)return!1;const o=(f=this._renderManagerService.getRenderById(i.getUnitId()))==null?void 0:f.with(m.DocSkeletonManagerService).getSkeleton(),r=this._getDocObject();if(e==null||o==null||r==null||n==null)return;const{startOffset:l,endOffset:c,style:d,collapsed:u,segmentId:S,startNodePosition:g,endNodePosition:v,segmentPage:h}=e,T=(p=i.getSelfOrHeaderFooterModel(S).getBody().dataStream.length)!=null?p:Number.POSITIVE_INFINITY;if(a===t.Direction.LEFT||a===t.Direction.RIGHT){let _;if(!e.collapsed||n.length>1){let y=Number.POSITIVE_INFINITY,x=Number.NEGATIVE_INFINITY;for(const C of n)y=Math.min(y,C.startOffset),x=Math.max(x,C.endOffset);_=a===t.Direction.LEFT?y:x}else{const y=o.findNodeByCharIndex(l-1,S,h),x=o.findNodeByCharIndex(l,S,h);a===t.Direction.LEFT?_=Math.max(0,l-((I=y==null?void 0:y.count)!=null?I:0)):_=Math.min(T-2,c+x.count)}this._textSelectionManagerService.replaceTextRanges([{startOffset:_,endOffset:_,style:d}],!1)}else{const _=o.findNodeByCharIndex(l,S,h),y=o.findNodeByCharIndex(c,S,h),x=r.document.getOffsetConfig(),C=this._getTopOrBottomPosition(o,a===t.Direction.UP?_:y,a===t.Direction.UP?g:v,a===t.Direction.DOWN);if(C==null){let R;u?R=a===t.Direction.UP?0:T-2:R=a===t.Direction.UP?l:c,this._textSelectionManagerService.replaceTextRanges([{startOffset:R,endOffset:R,style:d}],!1);return}const M=new E.NodePositionConvertToCursor(x,o).getRangePointData(C,C).cursorList[0];this._textSelectionManagerService.replaceTextRanges([{...M,style:d}],!1)}}_getTopOrBottomPosition(a,e,n,i){if(e==null||n==null)return;const o=this._getGlyphLeftOffsetInLine(e),r=this._getNextOrPrevLine(e,i);if(r==null)return;const l=this._matchPositionByLeftOffset(a,r,o,n);if(l!=null)return{...l,isBack:!0}}_getGlyphLeftOffsetInLine(a){const e=a.parent;if(e==null)return Number.NEGATIVE_INFINITY;const n=e.left,{left:i}=a;return n+i}_matchPositionByLeftOffset(a,e,n,i){const o={distance:Number.POSITIVE_INFINITY};for(const l of e.divides){const c=l.left;for(const d of l.glyphGroup){const{left:u}=d,S=c+u,g=Math.abs(n-S);g<o.distance&&(o.glyph=d,o.distance=g)}}if(o.glyph==null)return;const{segmentPage:r}=i;return a.findPositionByGlyph(o.glyph,r)}_getNextOrPrevLine(a,e){var h,T,f,p,I,_,y,x,C,M,R,A;const n=a.parent;if(n==null)return;const i=n.parent;if(i==null)return;const o=i.parent;if(o==null)return;const r=o.lines.indexOf(i);if(r===-1)return;let l;if(e===!0?l=o.lines[r+1]:l=o.lines[r-1],l!=null)return l;const c=o.parent;if(c==null)return;const d=c.columns.indexOf(o);if(d===-1)return;if(e===!0)l=(h=c.columns[d+1])==null?void 0:h.lines[0];else{const O=(f=(T=c.columns)==null?void 0:T[d-1])==null?void 0:f.lines;l=O==null?void 0:O[O.length-1]}if(l!=null)return l;const u=c.parent;if(u==null)return;const S=u.sections.indexOf(c);if(S===-1)return;if(e===!0)l=(I=(p=u.sections[S-1])==null?void 0:p.columns[0])==null?void 0:I.lines[0];else{const O=(y=(_=u.sections)==null?void 0:_[S-1])==null?void 0:y.columns,N=O==null?void 0:O[O.length-1],b=N==null?void 0:N.lines;l=b==null?void 0:b[b.length-1]}if(l!=null)return l;const g=u.parent;if(g==null)return;const v=g.pages.indexOf(u);if(v!==-1){if(e===!0)l=(M=(C=(x=g.pages[v+1])==null?void 0:x.sections[0])==null?void 0:C.columns[0])==null?void 0:M.lines[0];else{const O=(R=g.pages[v-1])==null?void 0:R.sections;if(O==null)return;const N=(A=O[O.length-1])==null?void 0:A.columns,b=N[N.length-1],P=b==null?void 0:b.lines;l=P[P.length-1]}if(l!=null)return l}}_getDocObject(){return Le(this._univerInstanceService,this._renderManagerService)}};Te=en([t.OnLifecycle(t.LifecycleStages.Rendered,Te),Ie(0,t.IUniverInstanceService),Ie(1,E.IRenderManagerService),Ie(2,k.Inject(m.TextSelectionManagerService)),Ie(3,t.ICommandService)],Te);var tn=Object.defineProperty,nn=Object.getOwnPropertyDescriptor,an=(s,a,e,n)=>{for(var i=n>1?void 0:n?nn(a,e):a,o=s.length-1,r;o>=0;o--)(r=s[o])&&(i=(n?r(a,e,i):r(i))||i);return n&&i&&tn(a,e,i),i},ve=(s,a)=>(e,n)=>a(e,n,s);let Ce=class extends t.Disposable{constructor(a,e,n,i){super();D(this,"_onInputSubscription");this._univerInstanceService=a,this._renderManagerService=e,this._textSelectionRenderManager=n,this._commandService=i,this._init()}dispose(){var a;super.dispose(),(a=this._onInputSubscription)==null||a.unsubscribe()}_init(){this._initialNormalInput()}_initialNormalInput(){this._onInputSubscription=this._textSelectionRenderManager.onInput$.subscribe(async a=>{var T;if(a==null)return;const e=this._univerInstanceService.getCurrentUniverDocInstance();if(!e)return;const n=e.getUnitId(),{event:i,content:o="",activeRange:r}=a,l=i,c=(T=this._renderManagerService.getRenderById(e.getUnitId()))==null?void 0:T.with(m.DocSkeletonManagerService).getSkeleton();if(l.data==null||c==null||!c||!r)return;const{startOffset:d,segmentId:u,style:S,segmentPage:g}=r,v=o.length,h=[{startOffset:d+v,endOffset:d+v,segmentId:u,segmentPage:g,style:S}];await this._commandService.executeCommand(K.id,{unitId:n,body:{dataStream:o},textRanges:h,range:r,segmentId:u})})}};Ce=an([t.OnLifecycle(t.LifecycleStages.Rendered,Ce),ve(0,t.IUniverInstanceService),ve(1,E.IRenderManagerService),ve(2,E.ITextSelectionRenderManager),ve(3,t.ICommandService)],Ce);const H={id:"doc.command.align-operation",type:t.CommandType.COMMAND,handler:(s,a)=>{var x,C;const e=s.get(m.TextSelectionManagerService),n=s.get(t.IUniverInstanceService),i=s.get(t.ICommandService),{alignType:o}=a,r=n.getCurrentUniverDocInstance(),l=e.getActiveRange();if(r==null||l==null)return!1;const{segmentId:c}=l,d=(x=e.getSelections())!=null?x:[],u=(C=r.getSelfOrHeaderFooterModel(c).getBody())==null?void 0:C.paragraphs,S=d.map(j);if(u==null)return!1;const g=dt(l,u),v=r.getUnitId(),h=g.every(M=>{var R;return((R=M.paragraphStyle)==null?void 0:R.horizontalAlign)===o}),T={id:U.id,params:{unitId:v,actions:[],textRanges:S}},f=new t.MemoryCursor;f.reset();const p=new t.TextX,I=t.JSONX.getInstance();for(const M of g){const{startIndex:R}=M;p.push({t:t.TextXActionType.RETAIN,len:R-f.cursor,segmentId:c});const A={...M.paragraphStyle,horizontalAlign:h?t.HorizontalAlign.UNSPECIFIED:o};p.push({t:t.TextXActionType.RETAIN,len:1,body:{dataStream:"",paragraphs:[{...M,paragraphStyle:A,startIndex:0}]},segmentId:c,coverType:t.UpdateDocsAttributeType.REPLACE}),f.moveCursorTo(R+1)}const _=B(r,c);return T.params.actions=I.editOp(p.serialize(),_),!!i.syncExecuteCommand(T.id,T.params)}},ht={id:"doc.command.align-left",type:t.CommandType.COMMAND,handler:s=>s.get(t.ICommandService).syncExecuteCommand(H.id,{alignType:t.HorizontalAlign.LEFT})},pt={id:"doc.command.align-center",type:t.CommandType.COMMAND,handler:s=>s.get(t.ICommandService).syncExecuteCommand(H.id,{alignType:t.HorizontalAlign.CENTER})},It={id:"doc.command.align-right",type:t.CommandType.COMMAND,handler:s=>s.get(t.ICommandService).syncExecuteCommand(H.id,{alignType:t.HorizontalAlign.RIGHT})},Tt={id:"doc.command.align-justify",type:t.CommandType.COMMAND,handler:s=>s.get(t.ICommandService).syncExecuteCommand(H.id,{alignType:t.HorizontalAlign.JUSTIFIED})};class vt{constructor(){D(this,"_customRangeHooks",[])}addClipboardHook(a){return this._customRangeHooks.push(a),t.toDisposable(()=>{const e=this._customRangeHooks.indexOf(a);e>-1&&this._customRangeHooks.splice(e,1)})}copyCustomRange(a){let e={...a};return this._customRangeHooks.forEach(n=>{n.onCopyCustomRange&&(e=n.onCopyCustomRange(e))}),e}}var sn=Object.defineProperty,on=Object.getOwnPropertyDescriptor,rn=(s,a,e,n)=>{for(var i=n>1?void 0:n?on(a,e):a,o=s.length-1,r;o>=0;o--)(r=s[o])&&(i=(n?r(a,e,i):r(i))||i);return n&&i&&sn(a,e,i),i},cn=(s,a)=>(e,n)=>a(e,n,s);const ln="docs";m.UniverDocsPlugin=(ye=class extends t.Plugin{constructor(a={},e){super(),this._injector=e,this._initializeDependencies(e),this._initializeCommands()}_initializeCommands(){[fe,he,Je,We,ie,se,oe,re,z,ce,le,de,ue,ge,me,be,Ve,K,ne,Ae,Ue,ae,U,ut,mt,St,Z,xe,ft,lt,ct,Se,ht,pt,It,H,Tt].forEach(a=>{this._injector.get(t.ICommandService).registerCommand(a)})}_initializeDependencies(a){[[m.DocStateChangeManagerService],[Y],[E.ITextSelectionRenderManager,{useClass:E.TextSelectionRenderManager}],[m.TextSelectionManagerService],[vt],[Ce],[pe],[Te]].forEach(e=>a.add(e))}},D(ye,"pluginName",ln),D(ye,"type",t.UniverInstanceType.UNIVER_DOC),ye),m.UniverDocsPlugin=rn([cn(1,k.Inject(k.Injector))],m.UniverDocsPlugin);function dn(s,a){const{range:e,rangeId:n,rangeType:i,segmentId:o}=s,r=Ot(e,a);if(!r)return null;const{startOffset:l,endOffset:c}=r,d=new t.TextX;return l>0&&d.push({t:t.TextXActionType.RETAIN,len:l,segmentId:o}),d.push({t:t.TextXActionType.INSERT,body:{dataStream:t.DataStreamTreeTokenType.CUSTOM_RANGE_START},len:1,line:0}),d.push({t:t.TextXActionType.RETAIN,body:{dataStream:""},len:c-l,segmentId:o}),d.push({t:t.TextXActionType.INSERT,body:{dataStream:t.DataStreamTreeTokenType.CUSTOM_RANGE_END,customRanges:[{rangeId:n,rangeType:i,startIndex:-(c-l)-1,endIndex:0}]},len:1,line:0}),d}function un(s,a){const e={id:U.id,params:{unitId:s.unitId,actions:[],textRanges:void 0}},n=t.JSONX.getInstance(),i=dn(s,a);return i?(e.params.actions=n.editOp(i.serialize()),e):!1}function mn(s,a){var x;const{segmentId:e,rangeId:n,rangeType:i}=a,o=s.get(m.TextSelectionManagerService),r=s.get(t.IUniverInstanceService),l=o.getActiveRange();if(!l)return!1;const c=r.getCurrentUnitForType(t.UniverInstanceType.UNIVER_DOC);if(!c)return!1;const d=c.getBody(),u=c.getUnitId();if(!d)return!1;const{startOffset:S,endOffset:g}=V(l),v=(x=d.customRanges)!=null?x:[],h=[];for(let C=0,M=v.length;C<M;C++){const R=v[C];if(R.rangeType===i&&Math.max(R.startIndex,S)<=Math.min(R.endIndex,g-1)&&h.push({...R}),R.startIndex>=g)break}const T=h.map(C=>[C.startIndex,C.endIndex]).flat().sort((C,M)=>C-M);let f=0;const p=new t.TextX,I=T.length?{startOffset:Math.min(T[0],S),endOffset:Math.max(T[T.length-1]+1,g)}:l;I.startOffset!==f&&(p.push({t:t.TextXActionType.RETAIN,len:I.startOffset-f,segmentId:e}),f=I.startOffset),p.push({t:t.TextXActionType.INSERT,body:{dataStream:t.DataStreamTreeTokenType.CUSTOM_RANGE_START},len:1,line:0,segmentId:e}),T.forEach((C,M)=>{C!==f&&(p.push({t:t.TextXActionType.RETAIN,len:C-f,segmentId:e}),f=C),p.push({t:t.TextXActionType.DELETE,len:1,line:0,segmentId:e}),f++}),f!==I.endOffset&&(p.push({t:t.TextXActionType.RETAIN,len:I.endOffset-f,segmentId:e}),f=I.endOffset),p.push({t:t.TextXActionType.INSERT,body:{dataStream:t.DataStreamTreeTokenType.CUSTOM_RANGE_END,customRanges:[{rangeId:n,rangeType:i,startIndex:-(I.endOffset-I.startOffset-T.length+1),endIndex:0}]},len:1,line:0,segmentId:e});const _=t.JSONX.getInstance(),y={id:U.id,params:{unitId:u,actions:[],textRanges:void 0}};return y.params.actions=_.editOp(p.serialize()),y}function gn(s,a){var g,v;const{unitId:e,rangeId:n,segmentId:i}=a,r=s.get(t.IUniverInstanceService).getUnit(e);if(!r)return!1;const l=(v=(g=r.getBody())==null?void 0:g.customRanges)==null?void 0:v.find(h=>h.rangeId===n);if(!l)return!1;const{startIndex:c,endIndex:d}=l,u=new t.TextX,S=d-c+1;return c>0&&u.push({t:t.TextXActionType.RETAIN,len:c,segmentId:i}),u.push({t:t.TextXActionType.DELETE,len:1,segmentId:i,line:0}),S-2>0&&u.push({t:t.TextXActionType.RETAIN,len:S-2,segmentId:i}),u.push({t:t.TextXActionType.DELETE,len:1,segmentId:i,line:0}),u}function Sn(s,a){const e={id:U.id,params:{unitId:a.unitId,actions:[],textRanges:void 0}},n=t.JSONX.getInstance(),i=gn(s,a);return i?(e.params.actions=n.editOp(i.serialize()),e):!1}function Ct(s){const{unitId:a,range:e,id:n,type:i,segmentId:o}=s,{startOffset:r,endOffset:l}=e,c={id:U.id,params:{unitId:a,actions:[],textRanges:void 0}},d=new t.TextX,u=t.JSONX.getInstance();return r>0&&d.push({t:t.TextXActionType.RETAIN,len:r,segmentId:o}),d.push({t:t.TextXActionType.RETAIN,body:{dataStream:"",customDecorations:[{id:n,type:i,startIndex:0,endIndex:l-r-1}]},len:l-r,segmentId:o}),c.params.actions=u.editOp(d.serialize()),c}function fn(s,a){const{segmentId:e,id:n,type:i}=a,o=s.get(m.TextSelectionManagerService),r=s.get(t.IUniverInstanceService),l=o.getActiveRange();if(!l)return!1;const c=r.getCurrentUnitForType(t.UniverInstanceType.UNIVER_DOC);if(!c)return!1;const d=c.getBody(),u=c.getUnitId();return d?Ct({unitId:u,range:{startOffset:l.startOffset,endOffset:l.endOffset,collapsed:!0},id:n,type:i,segmentId:e}):!1}function hn(s,a){var T,f;const{unitId:e,id:n,segmentId:i}=a,r=s.get(t.IUniverInstanceService).getUnit(e),l=r==null?void 0:r.getBody();if(!r||!l)return!1;const c=(f=(T=r.getBody())==null?void 0:T.customDecorations)==null?void 0:f.filter(p=>p.id===n);if(!(c!=null&&c.length))return!1;const d=c.map(p=>t.getBodySlice(l,p.startIndex,p.endIndex+1)),u=d.map(p=>{var _;const I=t.Tools.deepClone(p);return I.customDecorations=(_=I.customDecorations)==null?void 0:_.filter(y=>y.id!==n),I}),S={id:U.id,params:{unitId:e,actions:[],textRanges:void 0}},g=new t.TextX,v=t.JSONX.getInstance();let h=0;return c.forEach((p,I)=>{const _=u[I],y=d[I];p.startIndex!==h&&g.push({t:t.TextXActionType.RETAIN,len:p.startIndex-h,segmentId:i}),h=p.startIndex,g.push({t:t.TextXActionType.RETAIN,len:p.endIndex-p.startIndex+1,segmentId:i,body:_,oldBody:y,coverType:t.UpdateDocsAttributeType.REPLACE}),h=h+(p.endIndex-p.startIndex+1)}),S.params.actions=v.editOp(g.serialize()),S}const pn=t.createInterceptorKey("CUSTOM_RANGE"),In=t.createInterceptorKey("CUSTOM_DECORATION"),_e={CUSTOM_RANGE:pn,CUSTOM_DECORATION:In};var Tn=Object.defineProperty,vn=Object.getOwnPropertyDescriptor,Cn=(s,a,e,n)=>{for(var i=n>1?void 0:n?vn(a,e):a,o=s.length-1,r;o>=0;o--)(r=s[o])&&(i=(n?r(a,e,i):r(i))||i);return n&&i&&Tn(a,e,i),i},_n=(s,a)=>(e,n)=>a(e,n,s);m.DocInterceptorService=class extends t.Disposable{constructor(e,n){super();D(this,"_interceptorsByName",new Map);this._context=e,this._docSkeletonManagerService=n,this.disposeWithMe(this._docSkeletonManagerService.currentViewModel$.subscribe(i=>{if(i){const o=i.getDataModel().getUnitId();if(o===t.DOCS_NORMAL_EDITOR_UNIT_ID_KEY||o===t.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY)return;this.interceptDocumentViewModel(i)}})),this.disposeWithMe(this.intercept(_e.CUSTOM_RANGE,{priority:-1,handler:(i,o,r)=>r(i)}))}intercept(e,n){const i=e;this._interceptorsByName.has(i)||this._interceptorsByName.set(i,[]);const o=this._interceptorsByName.get(i);return o.push(n),this._interceptorsByName.set(i,o.sort((r,l)=>{var c,d;return((c=l.priority)!=null?c:0)-((d=r.priority)!=null?d:0)})),this.disposeWithMe(t.toDisposable(()=>t.remove(this._interceptorsByName.get(i),n)))}fetchThroughInterceptors(e){const n=e,i=this._interceptorsByName.get(n);return t.composeInterceptors(i||[])}interceptDocumentViewModel(e){const n=new t.DisposableCollection;return n.add(e.registerCustomRangeInterceptor({getCustomRange:i=>{var o;return this.fetchThroughInterceptors(_e.CUSTOM_RANGE)(e.getCustomRangeRaw(i),{index:i,unitId:e.getDataModel().getUnitId(),customRanges:(o=e.getDataModel().getCustomRanges())!=null?o:[]})},getCustomDecoration:i=>{var o;return this.fetchThroughInterceptors(_e.CUSTOM_DECORATION)(e.getCustomDecorationRaw(i),{index:i,unitId:e.getDataModel().getUnitId(),customDecorations:(o=e.getDataModel().getCustomDecorations())!=null?o:[]})}})),n}},m.DocInterceptorService=Cn([t.OnLifecycle(t.LifecycleStages.Starting,m.DocInterceptorService),_n(1,k.Inject(m.DocSkeletonManagerService))],m.DocInterceptorService),m.AlignCenterCommand=pt,m.AlignJustifyCommand=Tt,m.AlignLeftCommand=ht,m.AlignOperationCommand=H,m.AlignRightCommand=It,m.BreakLineCommand=Ve,m.BulletListCommand=ct,m.CoverContentCommand=mt,m.CutContentCommand=Ne,m.DOCS_COMPONENT_BACKGROUND_LAYER_INDEX=xt,m.DOCS_COMPONENT_DEFAULT_Z_INDEX=At,m.DOCS_COMPONENT_HEADER_LAYER_INDEX=Et,m.DOCS_COMPONENT_MAIN_LAYER_INDEX=Dt,m.DOCS_VIEW_KEY=W,m.DOC_INTERCEPTOR_POINT=_e,m.DeleteCommand=ne,m.DeleteLeftCommand=Je,m.DeleteRightCommand=We,m.DocCustomRangeService=vt,m.EditorInsertTextCommandId=ze,m.IMEInputCommand=Ue,m.IMEInputManagerService=Y,m.InnerPasteCommand=$t,m.InsertCommand=K,m.ListOperationCommand=Se,m.MergeTwoParagraphCommand=ae,m.MoveCursorOperation=fe,m.MoveSelectionOperation=he,m.NORMAL_TEXT_SELECTION_PLUGIN_NAME=Nt,m.OrderListCommand=lt,m.ReplaceContentCommand=ut,m.ResetInlineFormatTextBackgroundColorCommand=ge,m.RichTextEditingMutation=U,m.SelectAllOperation=ft,m.SetDocZoomRatioCommand=St,m.SetDocZoomRatioOperation=Z,m.SetInlineFormatBoldCommand=ie,m.SetInlineFormatCommand=be,m.SetInlineFormatFontFamilyCommand=de,m.SetInlineFormatFontSizeCommand=le,m.SetInlineFormatItalicCommand=se,m.SetInlineFormatStrikethroughCommand=re,m.SetInlineFormatSubscriptCommand=z,m.SetInlineFormatSuperscriptCommand=ce,m.SetInlineFormatTextBackgroundColorCommand=me,m.SetInlineFormatTextColorCommand=ue,m.SetInlineFormatUnderlineCommand=oe,m.SetTextSelectionsOperation=xe,m.UpdateCommand=Ae,m.VIEWPORT_KEY=Xe,m.addCustomDecorationBySelectionFactory=fn,m.addCustomDecorationFactory=Ct,m.addCustomRangeBySelectionFactory=mn,m.addCustomRangeFactory=un,m.deleteCustomDecorationFactory=hn,m.deleteCustomRangeFactory=Sn,m.getDeleteSelection=te,m.getDocObject=Le,m.getDocObjectById=bt,m.getInsertSelection=J,m.getSelectionText=Mt,m.neoGetDocObject=Ut,m.serializeTextRange=j,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})});