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

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.
@@ -13,11 +13,14 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
- import type { DocumentDataModel, IDocumentBody, IDocumentData } from '@univerjs/core';
16
+ import type { DocumentDataModel, IDocumentBody, IDocumentData, IParagraphBorder, ISectionBreak } from '@univerjs/core';
17
+ import type { IHeaderFooterProps } from '@univerjs/docs';
17
18
  import type { IFDocumentTextRange } from './utils';
18
19
  import { ICommandService, Injector, IResourceLoaderService, IUniverInstanceService } from '@univerjs/core';
19
20
  import { FBaseInitialable } from '@univerjs/core/facade';
20
21
  import { FDocumentParagraph } from './f-document-paragraph';
22
+ import { FDocumentSection } from './f-document-section';
23
+ import { FDocumentTextRange } from './f-document-text-range';
21
24
  export interface IFDocumentParagraphQuery {
22
25
  text?: string;
23
26
  paragraphId?: string;
@@ -169,6 +172,121 @@ export declare class FDocument extends FBaseInitialable {
169
172
  * ```
170
173
  */
171
174
  insertText(index: number, text: string, segmentId?: string): boolean;
175
+ /**
176
+ * Returns document-level header/footer switches and margins. Margin values are in points (pt).
177
+ * @example
178
+ * ```ts
179
+ * const fDocument = univerAPI.getActiveDocument();
180
+ * console.log(fDocument?.getHeaderFooterOptions());
181
+ * ```
182
+ */
183
+ getHeaderFooterOptions(): IHeaderFooterProps;
184
+ /**
185
+ * Updates document-level header/footer switches and margins in a traditional document.
186
+ * `marginHeader` and `marginFooter` are in points (pt).
187
+ * @example
188
+ * ```ts
189
+ * const fDocument = univerAPI.getActiveDocument();
190
+ * if (fDocument && !fDocument.isModern()) {
191
+ * fDocument.setHeaderFooterOptions({ marginHeader: 36, marginFooter: 36 });
192
+ * }
193
+ * ```
194
+ */
195
+ setHeaderFooterOptions(options: IHeaderFooterProps): boolean;
196
+ /**
197
+ * Creates a facade for reading and styling a document text range.
198
+ * The end offset is exclusive, and offsets are scoped to the selected body segment.
199
+ * @param {number} startOffset The inclusive start offset.
200
+ * @param {number} endOffset The exclusive end offset.
201
+ * @param {string} segmentId The header/footer segment id, or an empty string for the main body.
202
+ * @returns {FDocumentTextRange} A fixed text-range facade.
203
+ * @example
204
+ * ```ts
205
+ * const range = univerAPI.getActiveDocument()?.getTextRange(0, 5);
206
+ * console.log(range?.describe());
207
+ * range?.setTextStyle({ bl: 1 });
208
+ * ```
209
+ */
210
+ getTextRange(startOffset: number, endOffset: number, segmentId?: string): FDocumentTextRange;
211
+ /**
212
+ * Returns traditional document sections backed by persisted SectionBreak ids.
213
+ * Modern documents use ColumnGroup instead and return an empty array from this read API.
214
+ * @example
215
+ * ```ts
216
+ * const fDocument = univerAPI.getActiveDocument();
217
+ * const sections = fDocument?.getSections() ?? [];
218
+ * console.log(sections.map((section) => section.describe()));
219
+ * ```
220
+ */
221
+ getSections(): FDocumentSection[];
222
+ /**
223
+ * Returns a traditional section by zero-based index, or `null` in modern documents.
224
+ * @example
225
+ * ```ts
226
+ * const fDocument = univerAPI.getActiveDocument();
227
+ * const firstSection = fDocument?.getSection(0);
228
+ * console.log(firstSection?.describe());
229
+ * ```
230
+ */
231
+ getSection(index: number): FDocumentSection | null;
232
+ /**
233
+ * Returns the traditional section containing a data-stream offset, or `null` in modern documents.
234
+ * @example
235
+ * ```ts
236
+ * const fDocument = univerAPI.getActiveDocument();
237
+ * const paragraph = fDocument?.findParagraphByText('Launch');
238
+ * const offset = paragraph?.getInfo().startOffset;
239
+ * const section = offset == null ? null : fDocument?.getSectionAt(offset);
240
+ * console.log(section?.getId());
241
+ * ```
242
+ */
243
+ getSectionAt(offset: number): FDocumentSection | null;
244
+ /**
245
+ * Inserts a traditional document section break and returns its stable facade.
246
+ * Modern documents must use ColumnGroup and throw `DocsSectionUnsupportedDocumentFlavorError`.
247
+ * Numeric layout values in `config` are in points (pt).
248
+ * @example
249
+ * ```ts
250
+ * const fDocument = univerAPI.getActiveDocument();
251
+ * if (fDocument && !fDocument.isModern()) {
252
+ * const paragraph = fDocument.findParagraphByText('Appendix');
253
+ * const offset = paragraph?.getInfo().startOffset;
254
+ * const section = offset == null ? null : fDocument.insertSectionBreak(offset);
255
+ * console.log(section?.getId());
256
+ * }
257
+ * ```
258
+ */
259
+ insertSectionBreak(offset: number, config?: Partial<Omit<ISectionBreak, 'sectionId' | 'startIndex'>>): FDocumentSection | null;
260
+ /**
261
+ * Inserts a column-break token in a traditional document.
262
+ * Modern documents must use ColumnGroup and throw `DocsSectionUnsupportedDocumentFlavorError`.
263
+ * @example
264
+ * ```ts
265
+ * const fDocument = univerAPI.getActiveDocument();
266
+ * if (fDocument && !fDocument.isModern()) {
267
+ * const paragraph = fDocument.findParagraphByText('Continue in next column');
268
+ * const offset = paragraph?.getInfo().startOffset;
269
+ * if (offset != null) {
270
+ * fDocument.insertColumnBreak(offset);
271
+ * }
272
+ * }
273
+ * ```
274
+ */
275
+ insertColumnBreak(offset: number): boolean;
276
+ /**
277
+ * Inserts a horizontal rule using the existing paragraph `borderBottom` mechanism.
278
+ * The returned paragraph can be inspected or removed with normal paragraph APIs.
279
+ * Border width and padding are in points (pt).
280
+ * @example
281
+ * ```ts
282
+ * const fDocument = univerAPI.getActiveDocument();
283
+ * const paragraph = fDocument?.findParagraphByText('Summary');
284
+ * const offset = paragraph?.getInfo().startOffset;
285
+ * const rule = offset == null ? null : fDocument?.insertHorizontalRule(offset);
286
+ * console.log(rule?.getId());
287
+ * ```
288
+ */
289
+ insertHorizontalRule(offset: number, border?: IParagraphBorder, segmentId?: string): FDocumentParagraph | null;
172
290
  /**
173
291
  * Get all paragraphs in the document body or header/footer body by the segment id.
174
292
  * @param {string} segmentId The segment id of the body. Defaults to an empty string for the main body.
@@ -259,6 +377,7 @@ export declare class FDocument extends FBaseInitialable {
259
377
  /**
260
378
  * Append a plain-text paragraph at the end of the body.
261
379
  * @param {string} text The paragraph text. Defaults to an empty paragraph.
380
+ * @param {string} segmentId The segment id of the body. Defaults to an empty string for the main body.
262
381
  * @returns {FDocumentParagraph} The appended paragraph wrapper.
263
382
  * @example
264
383
  * ```ts
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Copyright 2023-present DreamNum Co., Ltd.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { ColumnSeparatorType, SectionType } from '@univerjs/core';
17
+ import { FEnum } from '@univerjs/core/facade';
18
+ /** @ignore */
19
+ export interface IFDocsEnumMixin {
20
+ /** OOXML-compatible section start types. */
21
+ SectionType: typeof SectionType;
22
+ /** Section column separator types. */
23
+ ColumnSeparatorType: typeof ColumnSeparatorType;
24
+ }
25
+ export declare class FDocsEnumMixin extends FEnum implements IFDocsEnumMixin {
26
+ get SectionType(): typeof SectionType;
27
+ get ColumnSeparatorType(): typeof ColumnSeparatorType;
28
+ }
29
+ declare module '@univerjs/core/facade' {
30
+ interface FEnum extends IFDocsEnumMixin {
31
+ }
32
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Copyright 2023-present DreamNum Co., Ltd.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ export type FDocEmbedUnitFacadeMapAugmentation = never;
@@ -14,8 +14,15 @@
14
14
  * limitations under the License.
15
15
  */
16
16
  import './f-univer';
17
+ import './f-enum';
17
18
  export { FDocument } from './f-document';
18
19
  export { FDocumentParagraph, isParagraphFacade } from './f-document-paragraph';
19
20
  export type { IFDocumentParagraphInfo } from './f-document-paragraph';
21
+ export { DocsSectionUnsupportedDocumentFlavorError, FDocumentSection } from './f-document-section';
22
+ export type { IFDocumentSectionColumnOptions, IFDocumentSectionDescription } from './f-document-section';
23
+ export { FDocumentTextRange } from './f-document-text-range';
24
+ export type { IFDocumentTextRangeDescription, IFDocumentTextStyleRun } from './f-document-text-range';
25
+ export * from './f-enum';
26
+ export type { FDocEmbedUnitFacadeMapAugmentation } from './f-types';
20
27
  export type { IFDocumentTextRange } from './utils';
21
28
  export { stripBlockTokens } from './utils';
@@ -16,15 +16,23 @@
16
16
  export { DeleteTextCommand, InsertTextCommand, UpdateTextCommand } from './commands/commands/core-editing.command';
17
17
  export type { IDeleteTextCommandParams, IInsertTextCommandParams, IUpdateTextCommandParams, } from './commands/commands/core-editing.command';
18
18
  export { CreateHeaderFooterCommand, HeaderFooterType } from './commands/commands/create-header-footer.command';
19
- export type { HeaderFooterCreateMode, ICreateHeaderFooterCommandParams, IHeaderFooterProps } from './commands/commands/create-header-footer.command';
19
+ export type { HeaderFooterCreateMode, ICreateHeaderFooterCommandParams, IHeaderFooterProps, } from './commands/commands/create-header-footer.command';
20
+ export { SetDocumentDefaultParagraphStyleCommand } from './commands/commands/set-document-default-paragraph-style.command';
21
+ export type { IDocumentDefaultParagraphStylePatch, ISetDocumentDefaultParagraphStyleCommandParams, } from './commands/commands/set-document-default-paragraph-style.command';
22
+ export { SetSectionHeaderFooterLinkCommand } from './commands/commands/set-section-header-footer-link.command';
23
+ export type { ISetSectionHeaderFooterLinkCommandParams } from './commands/commands/set-section-header-footer-link.command';
24
+ export { DeleteDocumentSectionBreakCommand, InsertDocumentSectionBreakCommand, UpdateDocumentSectionCommand } from './commands/commands/update-document-section.command';
25
+ export type { IDeleteDocumentSectionBreakCommandParams, IDocumentSectionConfig, IDocumentSectionUpdate, IInsertDocumentSectionBreakCommandParams, IUpdateDocumentSectionCommandParams } from './commands/commands/update-document-section.command';
20
26
  export { RichTextEditingMutation } from './commands/mutations/core-editing.mutation';
21
27
  export type { IRichTextEditingMutationParams } from './commands/mutations/core-editing.mutation';
22
28
  export { SetTextSelectionsOperation } from './commands/operations/text-selection.operation';
23
29
  export type { ISetTextSelectionsOperationParams } from './commands/operations/text-selection.operation';
24
30
  export type { IUniverDocsConfig } from './config/config';
31
+ export { createDocsCustomBlockDrawing, createDocsCustomBlockInsertMutation, createDocsCustomBlockRemoveMutation, createEmbedDocsCustomBlockData, createInsertCustomBlockActions, createRemoveCustomBlockActions, EMBED_DOCS_CUSTOM_BLOCK_DEFAULT_COMPONENT_KEY, isEmbedDocsCustomBlockData, isSheetLikeDocsCustomBlockChildType, resolveDocsCustomBlockSize, shouldUseInlineTextSelectionForDocsCustomBlockDrawing, } from './embed-host-anchor';
32
+ export type { EmbedDocsCustomBlockInteractionMode, IDocsCustomBlockMutationParams, IEmbedDocsCustomBlockData, } from './embed-host-anchor';
25
33
  export { UniverDocsPlugin } from './plugin';
26
34
  export { DocBlockMoveValidatorService } from './services/doc-block-move-validator.service';
27
- export type { DocBlockMoveTransformer, DocBlockMoveValidator, IDocBlockMoveResult, IDocBlockMoveTransformContext, IDocBlockMoveValidationContext } from './services/doc-block-move-validator.service';
35
+ export type { DocBlockMoveTransformer, DocBlockMoveValidator, IDocBlockMoveResult, IDocBlockMoveTransformContext, IDocBlockMoveValidationContext, } from './services/doc-block-move-validator.service';
28
36
  export { DocContentInsertService } from './services/doc-content-insert.service';
29
37
  export type { IDocContentInsertRange } from './services/doc-content-insert.service';
30
38
  export { DocInterceptorService } from './services/doc-interceptor/doc-interceptor.service';
@@ -35,5 +43,9 @@ export { DocStateChangeManagerService, IDocStateChangeInterceptorService, } from
35
43
  export type { IDocStateChangeInfo, IDocStateChangeParams } from './services/doc-state-emit.service';
36
44
  export { DocStateEmitService } from './services/doc-state-emit.service';
37
45
  export { addCustomRangeBySelectionFactory, addCustomRangeFactory, deleteCustomRangeFactory, } from './utils/custom-range-factory';
46
+ export { generateParagraphs } from './utils/paragraphs';
38
47
  export { replaceSelectionFactory } from './utils/replace-selection-factory';
39
- export { consumeContentInsertRange, isHeaderFooterSelection } from './utils/util';
48
+ export { createSectionColumnProperties } from './utils/section-columns';
49
+ export { getTopLevelSectionBreaks } from './utils/sections';
50
+ export { buildDocTransform, docDrawingPositionToTransform, transformToDocDrawingPosition } from './utils/transform-position';
51
+ export { consumeContentInsertRange, getContentInsertRange, isHeaderFooterSelection, normalizeTextRange } from './utils/util';
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Copyright 2023-present DreamNum Co., Ltd.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import type { IParagraph, IParagraphBorder } from '@univerjs/core';
17
+ /** Builds paragraph metadata for inserted paragraph tokens, including horizontal-rule borders. */
18
+ export declare function generateParagraphs(dataStream: string, prevParagraph?: IParagraph, borderBottom?: IParagraphBorder, existingParagraphIds?: Iterable<string>): IParagraph[];
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Copyright 2023-present DreamNum Co., Ltd.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import type { IDocumentStyle, ISectionBreak, ISectionColumnProperties } from '@univerjs/core';
17
+ /** Creates explicit OOXML section columns from a count, gap, and optional widths. */
18
+ export declare function createSectionColumnProperties(documentStyle: IDocumentStyle | undefined, section: ISectionBreak | undefined, columnCount: number, gap: number, widths?: number[]): ISectionColumnProperties[];
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Copyright 2023-present DreamNum Co., Ltd.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import type { IDocumentBody, ISectionBreak } from '@univerjs/core';
17
+ /** Returns document-level section breaks, excluding table-cell and modern-column sentinels. */
18
+ export declare function getTopLevelSectionBreaks(body: IDocumentBody): ISectionBreak[];
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Copyright 2023-present DreamNum Co., Ltd.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import type { IDocDrawingPosition, ITransformState } from '@univerjs/core';
17
+ export declare function buildDocTransform(width: number, height: number, position?: {
18
+ left?: number;
19
+ top?: number;
20
+ }): IDocDrawingPosition;
21
+ export declare function docDrawingPositionToTransform(position: IDocDrawingPosition): ITransformState;
22
+ export declare function transformToDocDrawingPosition(transform: ITransformState, marginLeft?: number, marginTop?: number): IDocDrawingPosition;
@@ -13,7 +13,12 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
- import type { IAccessor } from '@univerjs/core';
16
+ import type { IAccessor, ITextRangeParam } from '@univerjs/core';
17
17
  import type { ITextRangeWithStyle } from '@univerjs/engine-render';
18
- export declare function consumeContentInsertRange(accessor: IAccessor, unitId: string): import("..").IDocContentInsertRange | null;
18
+ import type { IDocContentInsertRange } from '../services/doc-content-insert.service';
19
+ export declare function consumeContentInsertRange(accessor: IAccessor, unitId: string): IDocContentInsertRange | null;
20
+ export declare function getContentInsertRange(accessor: IAccessor, unitId?: string): (IDocContentInsertRange & {
21
+ collapsed: boolean;
22
+ }) | null;
19
23
  export declare function isHeaderFooterSelection(range?: ITextRangeWithStyle): boolean;
24
+ export declare function normalizeTextRange(textRange: ITextRangeParam): ITextRangeParam;
package/lib/umd/facade.js CHANGED
@@ -1,3 +1,3 @@
1
1
  (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require("@univerjs/core"),require("@univerjs/core/facade"),require("@univerjs/docs")):typeof define==`function`&&define.amd?define([`exports`,`@univerjs/core`,`@univerjs/core/facade`,`@univerjs/docs`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.UniverDocsFacade={},e.UniverCore,e.UniverCoreFacade,e.UniverDocs))})(this,function(e,t,n,r){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});function i(e){return e==null?e:JSON.parse(JSON.stringify(e))}function a(e){return e.replace(/\r\n/g,`\r`).replace(/\n/g,`\r`)}function o(e,t){let n=a(e);return t&&n.length>1&&n.startsWith(`\r`)?1:0}function s(e,n={}){let r=a(e).slice(o(e,n.removeLeadingParagraphBreak)),s={dataStream:r,customDecorations:[],customRanges:[],textRuns:[]},c=[],l=new Set;for(let e=0;e<r.length;e++)r[e]===`\r`&&c.push({startIndex:e,paragraphId:(0,t.createParagraphId)(l),...n.paragraphStyle==null?{}:{paragraphStyle:i(n.paragraphStyle)}});return c.length>0&&(s.paragraphs=c),s}function c(e,n,i,a){let{startOffset:o,endOffset:s,segmentId:c}=e,l=new t.TextX;o>0&&l.push({t:t.TextXActionType.RETAIN,len:o}),s>o&&l.push({t:t.TextXActionType.DELETE,len:s-o}),n.dataStream.length>0&&l.push({t:t.TextXActionType.INSERT,body:n,len:n.dataStream.length});let u=t.JSONX.getInstance().editOp(l.serialize(),(0,t.getRichTextEditPath)(i,c)),d=a.get(t.ICommandService).syncExecuteCommand(r.RichTextEditingMutation.id,{unitId:i.getUnitId(),segmentId:c,actions:u,textRanges:[],isEditing:!1});return!!(d!=null&&d.actions&&d.actions.length>0)}function l(e,n,i,a,o){var s,c;let{startOffset:l,endOffset:u,segmentId:d}=e,f=o.get(t.ICommandService);if((s=n.textRuns)!=null&&s.length&&((c=a.getSelfOrHeaderFooterModel(d))==null||(c=c.getBody())==null?void 0:c.textRuns)==null){let e=t.JSONX.getInstance().replaceOp([...(0,t.getRichTextEditPath)(a,d),`textRuns`],void 0,[]);f.syncExecuteCommand(r.RichTextEditingMutation.id,{unitId:a.getUnitId(),segmentId:d,actions:e,textRanges:[],isEditing:!1})}let p=new t.TextX;l>0&&p.push({t:t.TextXActionType.RETAIN,len:l}),p.push({t:t.TextXActionType.RETAIN,body:n,coverType:i,len:u-l});let m=t.JSONX.getInstance().editOp(p.serialize(),(0,t.getRichTextEditPath)(a,d)),h=f.syncExecuteCommand(r.RichTextEditingMutation.id,{unitId:a.getUnitId(),segmentId:d,actions:m,textRanges:[],isEditing:!1});return!!(h!=null&&h.actions&&h.actions.length>0)}function u(e){return Array.from(e).map(e=>e===t.DataStreamTreeTokenType.PARAGRAPH?`
2
- `:e).filter(e=>e!==t.DataStreamTreeTokenType.BLOCK_START&&e!==t.DataStreamTreeTokenType.BLOCK_END&&e!==t.DataStreamTreeTokenType.SECTION_BREAK).join(``).replace(/\n$/,``)}var d=class{constructor(e,t,n=``,r){this._document=e,this._paragraphId=t,this._segmentId=n,this._injector=r}getId(){return this._paragraphId}getSegmentId(){return this._segmentId}getInfo(){let{paragraphs:e=[]}=this._document.getBody(this._segmentId),t=e.map((e,t)=>({paragraph:e,paragraphIndex:t})).filter(({paragraph:e})=>e.paragraphId===this._paragraphId);if(t.length===0)throw Error(`Document paragraph with id ${this._paragraphId} not found`);if(t.length>1)throw Error(`Multiple document paragraphs with id ${this._paragraphId} found`);let{paragraph:n,paragraphIndex:r}=t[0];return{paragraph:n,paragraphIndex:r,startOffset:r>0?e[r-1].startIndex+1:0,endOffset:n.startIndex}}getRange(){let{startOffset:e,endOffset:t}=this.getInfo();return{startOffset:e,endOffset:t,segmentId:this._segmentId}}getText(){let{dataStream:e}=this._document.getBody(this._segmentId),{startOffset:t,endOffset:n}=this.getInfo();return e.slice(t,n)}setText(e){let{startOffset:t,endOffset:n}=this.getInfo();return c({startOffset:t,endOffset:n,segmentId:this._segmentId},s(e),this._document.getDocumentDataModel(),this._injector)}appendText(e){let{endOffset:t}=this.getInfo();return this._document.insertText(t,e,this._segmentId)}setStyle(e){let{paragraph:n,startOffset:r,endOffset:i}=this.getInfo(),a=!0;e.textStyle&&r<i&&(a=l({startOffset:r,endOffset:i,segmentId:this._segmentId},{dataStream:``,textRuns:[{st:0,ed:i-r,ts:e.textStyle}]},t.UpdateDocsAttributeType.COVER,this._document.getDocumentDataModel(),this._injector));let o={dataStream:``,paragraphs:[{...n,startIndex:0,paragraphStyle:{...n.paragraphStyle,...e}}]};return this._preserveExplicitParagraphIds(o),l({startOffset:i,endOffset:i+1,segmentId:this._segmentId},o,t.UpdateDocsAttributeType.REPLACE,this._document.getDocumentDataModel(),this._injector)&&a}isListItem(){let{paragraph:e}=this.getInfo();return!!e.bullet}isTask(){var e;let{paragraph:n}=this.getInfo(),r=(e=n.bullet)==null?void 0:e.listType;return r===t.PresetListType.CHECK_LIST||r===t.PresetListType.CHECK_LIST_CHECKED}setTaskChecked(e){if(!this.isTask())return!1;let{paragraph:n,endOffset:r}=this.getInfo(),i=n.bullet,a={dataStream:``,paragraphs:[{...n,startIndex:0,bullet:{...i,listType:e?t.PresetListType.CHECK_LIST_CHECKED:t.PresetListType.CHECK_LIST}}]};return this._preserveExplicitParagraphIds(a),l({startOffset:r,endOffset:r+1,segmentId:this._segmentId},a,t.UpdateDocsAttributeType.REPLACE,this._document.getDocumentDataModel(),this._injector)}remove(){let{startOffset:e,endOffset:t}=this.getInfo();return this._document.deleteRange({startOffset:e,endOffset:t+1,segmentId:this._segmentId})}_preserveExplicitParagraphIds(e){e[t.RESTORE_INSERTED_PARAGRAPH_IDS]=!0}};function f(e){return typeof e!=`object`||!e?!1:typeof e.getId==`function`&&typeof e.getSegmentId==`function`&&typeof e.getInfo==`function`&&typeof e.getRange==`function`}function p(e){"@babel/helpers - typeof";return p=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},p(e)}function m(e,t){if(p(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(p(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function h(e){var t=m(e,`string`);return p(t)==`symbol`?t:t+``}function g(e,t,n){return(t=h(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function _(e,t){return function(n,r){t(n,r,e)}}function v(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}let y=class extends n.FBaseInitialable{constructor(e,t,n,r,i){super(t),this._documentDataModel=e,this._injector=t,this._univerInstanceService=n,this._resourceLoaderService=r,this._commandService=i,g(this,`id`,void 0),this.id=this._documentDataModel.getUnitId()}getDocumentDataModel(e=``){let t=this._documentDataModel.getSelfOrHeaderFooterModel(e);if(!t)throw Error(e===``?`Document data model is not found.`:`Document data model is not found in the segment: ${e}`);return t}getBody(e=``){var t;let n=(t=this._documentDataModel.getSelfOrHeaderFooterModel(e))==null?void 0:t.getBody();if(!n)throw Error(e===``?`Body is not found in the document.`:`Body is not found in the segment: ${e}`);return n}dispose(){super.dispose()}getId(){return this.id}getName(){return this._documentDataModel.getTitle()||``}isModern(){return this._documentDataModel.getSnapshot().documentStyle.documentFlavor===t.DocumentFlavor.MODERN}save(){return this._resourceLoaderService.saveUnit(this._documentDataModel.getUnitId())}undo(){return this._univerInstanceService.focusUnit(this.id),this._commandService.syncExecuteCommand(t.UndoCommand.id)}redo(){return this._univerInstanceService.focusUnit(this.id),this._commandService.syncExecuteCommand(t.RedoCommand.id)}ensurePageHeader(e=0){return this._ensureHeaderFooter(`header`,e)}ensurePageFooter(e=0){return this._ensureHeaderFooter(`footer`,e)}insertText(e,t,n=``){return c({startOffset:e,endOffset:e,segmentId:n},s(t),this._documentDataModel,this._injector)}getParagraphs(e=``){let{paragraphs:t=[]}=this.getBody(e);return t.map(t=>this._createFDocumentParagraph(t.paragraphId,e))}getParagraph(e,t=``){let{paragraphs:n=[]}=this.getBody(t);return n.find(t=>t.paragraphId===e)?this._createFDocumentParagraph(e,t):null}findParagraphByText(e,t=``){return this.findParagraphs({text:e,segmentId:t})[0]||null}findParagraphs(e){let{text:t,paragraphId:n,segmentId:r=``}=typeof e==`string`?{text:e}:e;return this.getParagraphs(r).filter(e=>!(n&&e.getId()!==n||t&&!e.getText().includes(t)))}insertParagraph(e,t=``,n=``){let r=this._getParagraphInsertOffset(e,n);if(!c({startOffset:r,endOffset:r,segmentId:n},s(`${t}\r`),this._documentDataModel,this._injector))throw Error(`Failed to insert paragraph.`);let{paragraphs:i=[]}=this.getBody(n),a=i[e];if(!a)throw Error(`Failed to insert paragraph.`);return this._createFDocumentParagraph(a.paragraphId,n)}appendParagraph(e=``,t=``){let{paragraphs:n=[]}=this.getBody(t);return this.insertParagraph(n.length,e,t)}deleteRange(e){let t=this._normalizeDeleteRange(e);return t.startOffset>=t.endOffset?!1:c(t,{dataStream:``},this._documentDataModel,this._injector)}_createFDocumentParagraph(e,t=``){return this._injector.createInstance(d,this,e,t,this._injector)}_normalizeDeleteRange(e){let t=this.getBody(e.segmentId),n=t.dataStream.endsWith(`\r
3
- `)?Math.max(0,t.dataStream.length-2):t.dataStream.length,r=Math.min(Math.max(e.endOffset,0),n);return{...e,startOffset:Math.min(Math.max(e.startOffset,0),r),endOffset:r}}_getParagraphInsertOffset(e,t=``){if(e<=0)return 0;let{dataStream:n,paragraphs:r=[]}=this.getBody(t);return r.length===0?Math.max(0,n.length-1):e>=r.length?r[r.length-1].startIndex+1:r[e-1].startIndex+1}_ensureHeaderFooter(e,n){if(this.isModern())throw Error(`The document is a modern document, header/footer is not supported.`);let{createType:i,segmentId:a}=this._getHeaderFooterCreateInfo(e,n);if(a)return a;let o=(0,t.generateRandomId)(6);if(!this._commandService.syncExecuteCommand(r.CreateHeaderFooterCommand.id,{unitId:this.getId(),segmentId:o,createType:i}))throw Error(`Failed to create page ${e}.`);return o}_getHeaderFooterCreateInfo(e,n){var i,a;let{documentStyle:o}=this._documentDataModel.getSnapshot(),s=n===0,c=(n+1)%2==0;if(s&&o.useFirstPageHeaderFooter===t.BooleanNumber.TRUE){var l,u;return e===`header`?{createType:r.HeaderFooterType.FIRST_PAGE_HEADER,segmentId:(l=o.firstPageHeaderId)==null?``:l}:{createType:r.HeaderFooterType.FIRST_PAGE_FOOTER,segmentId:(u=o.firstPageFooterId)==null?``:u}}if(c&&o.evenAndOddHeaders===t.BooleanNumber.TRUE){var d,f;return e===`header`?{createType:r.HeaderFooterType.EVEN_PAGE_HEADER,segmentId:(d=o.evenPageHeaderId)==null?``:d}:{createType:r.HeaderFooterType.EVEN_PAGE_FOOTER,segmentId:(f=o.evenPageFooterId)==null?``:f}}return e===`header`?{createType:r.HeaderFooterType.DEFAULT_HEADER,segmentId:(i=o.defaultHeaderId)==null?``:i}:{createType:r.HeaderFooterType.DEFAULT_FOOTER,segmentId:(a=o.defaultFooterId)==null?``:a}}};y=v([_(1,(0,t.Inject)(t.Injector)),_(2,t.IUniverInstanceService),_(3,(0,t.Inject)(t.IResourceLoaderService)),_(4,t.ICommandService)],y);var b=class extends n.FUniver{createDocument(e){let n=this._injector.get(t.IUniverInstanceService).createUnit(t.UniverInstanceType.UNIVER_DOC,e);return this._injector.createInstance(y,n)}getActiveDocument(){let e=this._univerInstanceService.getCurrentUnitOfType(t.UniverInstanceType.UNIVER_DOC);return e?this._injector.createInstance(y,e):null}getDocument(e){let n=this._univerInstanceService.getUnit(e,t.UniverInstanceType.UNIVER_DOC);return n?this._injector.createInstance(y,n):null}};n.FUniver.extend(b),Object.defineProperty(e,"FDocument",{enumerable:!0,get:function(){return y}}),e.FDocumentParagraph=d,e.isParagraphFacade=f,e.stripBlockTokens=u});
2
+ `:e).filter(e=>e!==t.DataStreamTreeTokenType.BLOCK_START&&e!==t.DataStreamTreeTokenType.BLOCK_END&&e!==t.DataStreamTreeTokenType.SECTION_BREAK).join(``).replace(/\n$/,``)}var d=class{constructor(e,t,n,r,i){this._document=e,this._startOffset=t,this._endOffset=n,this._segmentId=r,this._injector=i,this._validateRange()}getRange(){return{startOffset:this._startOffset,endOffset:this._endOffset,segmentId:this._segmentId}}getText(){return this._document.getBody(this._segmentId).dataStream.slice(this._startOffset,this._endOffset)}getExplicitTextStyleRuns(){let{textRuns:e=[]}=this._document.getBody(this._segmentId);return e.filter(e=>e.st<this._endOffset&&e.ed>this._startOffset).map(e=>{var n;return{startOffset:Math.max(e.st,this._startOffset),endOffset:Math.min(e.ed,this._endOffset),textStyle:t.Tools.deepClone((n=e.ts)==null?{}:n)}})}getTextStyleRuns(){return this.getExplicitTextStyleRuns()}getCommonExplicitTextStyle(){if(this._startOffset===this._endOffset)return{};let[e,...n]=this._getStyleSegments(),r=t.Tools.deepClone(e.textStyle);for(let e of Object.keys(r))n.some(t=>!f(t.textStyle[e],r[e]))&&delete r[e];return r}getCommonTextStyle(){return this.getCommonExplicitTextStyle()}describe(){let e=this.getExplicitTextStyleRuns(),t=this.getCommonExplicitTextStyle();return{...this.getRange(),text:this.getText(),length:this._endOffset-this._startOffset,explicitTextStyleRuns:e,commonExplicitTextStyle:t,textStyleRuns:e,commonTextStyle:t}}setTextStyle(e){return this._startOffset===this._endOffset?!1:l(this.getRange(),{dataStream:``,textRuns:[{st:0,ed:this._endOffset-this._startOffset,ts:t.Tools.deepClone(e)}]},t.UpdateDocsAttributeType.COVER,this._document.getDocumentDataModel(),this._injector)}setText(e){return c(this.getRange(),s(e),this._document.getDocumentDataModel(),this._injector)}_validateRange(){let e=this._document.getBody(this._segmentId).dataStream.length;if(!Number.isInteger(this._startOffset)||!Number.isInteger(this._endOffset)||this._startOffset<0||this._endOffset<this._startOffset||this._endOffset>e)throw RangeError(`Invalid document text range [${this._startOffset}, ${this._endOffset}) for body length ${e}.`)}_getStyleSegments(){let e=this.getExplicitTextStyleRuns(),t=[],n=this._startOffset;for(let r of e)n<r.startOffset&&t.push({startOffset:n,endOffset:r.startOffset,textStyle:{}}),t.push(r),n=r.endOffset;return n<this._endOffset&&t.push({startOffset:n,endOffset:this._endOffset,textStyle:{}}),t}};function f(e,t){return JSON.stringify(e)===JSON.stringify(t)}var p=class{constructor(e,t,n=``,r){this._document=e,this._paragraphId=t,this._segmentId=n,this._injector=r}getId(){return this._paragraphId}getSegmentId(){return this._segmentId}getInfo(){let e=this._document.getBody(this._segmentId),{paragraphs:n=[]}=e,r=n.map((e,t)=>({paragraph:e,paragraphIndex:t})).filter(({paragraph:e})=>e.paragraphId===this._paragraphId);if(r.length===0)throw Error(`Document paragraph with id ${this._paragraphId} not found`);if(r.length>1)throw Error(`Multiple document paragraphs with id ${this._paragraphId} found`);let{paragraph:i,paragraphIndex:a}=r[0];return{paragraph:i,paragraphIndex:a,startOffset:(0,t.getParagraphContentStartOffset)(e,i),endOffset:i.startIndex}}getRange(){let{startOffset:e,endOffset:t}=this.getInfo();return{startOffset:e,endOffset:t,segmentId:this._segmentId}}getTextRange(){let{startOffset:e,endOffset:t}=this.getInfo();return this._injector.createInstance(d,this._document,e,t,this._segmentId,this._injector)}getText(){let{dataStream:e}=this._document.getBody(this._segmentId),{startOffset:t,endOffset:n}=this.getInfo();return e.slice(t,n)}setText(e){let{startOffset:t,endOffset:n}=this.getInfo();return c({startOffset:t,endOffset:n,segmentId:this._segmentId},s(e),this._document.getDocumentDataModel(),this._injector)}appendText(e){let{endOffset:t}=this.getInfo();return this._document.insertText(t,e,this._segmentId)}setStyle(e){let{paragraph:n,startOffset:r,endOffset:i}=this.getInfo(),a=!0;e.textStyle&&r<i&&(a=l({startOffset:r,endOffset:i,segmentId:this._segmentId},{dataStream:``,textRuns:[{st:0,ed:i-r,ts:e.textStyle}]},t.UpdateDocsAttributeType.COVER,this._document.getDocumentDataModel(),this._injector));let o={dataStream:``,paragraphs:[{...n,startIndex:0,paragraphStyle:{...n.paragraphStyle,...e}}]};return this._preserveExplicitParagraphIds(o),l({startOffset:i,endOffset:i+1,segmentId:this._segmentId},o,t.UpdateDocsAttributeType.REPLACE,this._document.getDocumentDataModel(),this._injector)&&a}isListItem(){let{paragraph:e}=this.getInfo();return!!e.bullet}isTask(){var e;let{paragraph:n}=this.getInfo(),r=(e=n.bullet)==null?void 0:e.listType;return r===t.PresetListType.CHECK_LIST||r===t.PresetListType.CHECK_LIST_CHECKED}setTaskChecked(e){if(!this.isTask())return!1;let{paragraph:n,endOffset:r}=this.getInfo(),i=n.bullet,a={dataStream:``,paragraphs:[{...n,startIndex:0,bullet:{...i,listType:e?t.PresetListType.CHECK_LIST_CHECKED:t.PresetListType.CHECK_LIST}}]};return this._preserveExplicitParagraphIds(a),l({startOffset:r,endOffset:r+1,segmentId:this._segmentId},a,t.UpdateDocsAttributeType.REPLACE,this._document.getDocumentDataModel(),this._injector)}remove(){let{startOffset:e,endOffset:t}=this.getInfo();return this._document.deleteRange({startOffset:e,endOffset:t+1,segmentId:this._segmentId})}_preserveExplicitParagraphIds(e){e[t.RESTORE_INSERTED_PARAGRAPH_IDS]=!0}};function m(e){return typeof e!=`object`||!e?!1:typeof e.getId==`function`&&typeof e.getSegmentId==`function`&&typeof e.getInfo==`function`&&typeof e.getRange==`function`}var h=class extends Error{constructor(){super(`Section column APIs are supported only in traditional documents. Use ColumnGroup APIs for modern documents.`),this.name=`DocsSectionUnsupportedDocumentFlavorError`}},g=class{constructor(e,t,n){this._document=e,this._sectionId=t,this._injector=n}getId(){return this._sectionId}getIndex(){return this._resolve().index}getConfig(){let{sectionBreak:e}=this._resolve();return t.Tools.deepClone(e)}getRange(){let e=(0,r.getTopLevelSectionBreaks)(this._document.getBody()),{index:t,sectionBreak:n}=this._resolve();return{startOffset:t===0?0:e[t-1].startIndex+1,endOffset:n.startIndex,segmentId:``}}getColumns(){var e;return t.Tools.deepClone((e=this.getConfig().columnProperties)==null?[]:e)}describe(){var e,n,r;let i=this.getConfig(),a=(e=i.columnProperties)==null?[]:e,o={defaultHeader:this._describeHeaderFooterReference(`header`,`default`),defaultFooter:this._describeHeaderFooterReference(`footer`,`default`),firstHeader:this._describeHeaderFooterReference(`header`,`first`),firstFooter:this._describeHeaderFooterReference(`footer`,`first`),evenHeader:this._describeHeaderFooterReference(`header`,`even`),evenFooter:this._describeHeaderFooterReference(`footer`,`even`)};return{sectionId:this._sectionId,index:this.getIndex(),range:this.getRange(),columnCount:a.length||1,columns:t.Tools.deepClone(a),columnSeparatorType:(n=i.columnSeparatorType)==null?t.ColumnSeparatorType.NONE:n,sectionType:(r=i.sectionType)==null?t.SectionType.SECTION_TYPE_UNSPECIFIED:r,headerFooter:o,config:i}}setColumns(e,n={}){var i,a;if(this._assertTraditionalDocument(),!Number.isInteger(e)||e<1)throw RangeError(`Section column count must be a positive integer.`);if(n.widths&&n.widths.length!==e)throw RangeError(`Section column widths must match the column count.`);let o=Math.max(0,(i=n.gap)==null?18:i),s=this.getConfig(),c=(0,r.createSectionColumnProperties)(this._document.getDocumentDataModel().getSnapshot().documentStyle,s,e,o,n.widths),l=typeof n.separator==`boolean`?n.separator?t.ColumnSeparatorType.BETWEEN_EACH_COLUMN:t.ColumnSeparatorType.NONE:(a=n.separator)==null?t.ColumnSeparatorType.NONE:a;return this._update({columnProperties:c,columnSeparatorType:l,...n.sectionType==null?{}:{sectionType:n.sectionType}})}setColumnProperties(e,n=t.ColumnSeparatorType.NONE){if(this._assertTraditionalDocument(),e.some(({width:e,paddingEnd:t})=>e<0||t<0))throw RangeError(`Section column widths and padding must be non-negative.`);return this._update({columnProperties:t.Tools.deepClone(e),columnSeparatorType:n})}setSectionType(e){return this._assertTraditionalDocument(),this._update({sectionType:e})}ensureHeader(e=`default`){return this._ensureHeaderFooter(`header`,e)}ensureFooter(e=`default`){return this._ensureHeaderFooter(`footer`,e)}getHeaderId(e=`default`){var t;return(t=this._getHeaderFooterReference(`header`,e).segmentId)==null?null:t}getFooterId(e=`default`){var t;return(t=this._getHeaderFooterReference(`footer`,e).segmentId)==null?null:t}isHeaderLinkedToPrevious(e=`default`){return this._getHeaderFooterReference(`header`,e).linkedToPrevious}isFooterLinkedToPrevious(e=`default`){return this._getHeaderFooterReference(`footer`,e).linkedToPrevious}setHeaderLinkedToPrevious(e,t=`default`){return this._setHeaderFooterLinkedToPrevious(`header`,t,e)}setFooterLinkedToPrevious(e,t=`default`){return this._setHeaderFooterLinkedToPrevious(`footer`,t,e)}setHeaderFooterOptions(e){return this._assertTraditionalDocument(),this._update(e)}remove(){return this._assertTraditionalDocument(),this._injector.get(t.ICommandService).syncExecuteCommand(r.DeleteDocumentSectionBreakCommand.id,{unitId:this._document.getId(),sectionId:this._sectionId})}_update(e){let{sectionId:n,startIndex:i,...a}=e;return this._injector.get(t.ICommandService).syncExecuteCommand(r.UpdateDocumentSectionCommand.id,{unitId:this._document.getId(),updates:[{sectionId:this._sectionId,config:a}]})}_ensureHeaderFooter(e,n){this._assertTraditionalDocument();let{index:i}=this._resolve(),a=this.getConfig()[(0,t.getSectionHeaderFooterReferenceKey)(e,n)];if(typeof a==`string`&&a)return a;if(i>0){let i=(0,t.generateRandomId)(6);if(!this._injector.get(t.ICommandService).syncExecuteCommand(r.SetSectionHeaderFooterLinkCommand.id,{unitId:this._document.getId(),sectionId:this._sectionId,kind:e,variant:n,linkedToPrevious:!1,segmentId:i}))throw Error(`Failed to create section ${e}.`);return i}let o={default:e===`header`?r.HeaderFooterType.DEFAULT_HEADER:r.HeaderFooterType.DEFAULT_FOOTER,first:e===`header`?r.HeaderFooterType.FIRST_PAGE_HEADER:r.HeaderFooterType.FIRST_PAGE_FOOTER,even:e===`header`?r.HeaderFooterType.EVEN_PAGE_HEADER:r.HeaderFooterType.EVEN_PAGE_FOOTER},s=(0,t.generateRandomId)(6);if(!this._injector.get(t.ICommandService).syncExecuteCommand(r.CreateHeaderFooterCommand.id,{unitId:this._document.getId(),segmentId:s,createType:o[n],sectionId:this._sectionId}))throw Error(`Failed to create section ${e}.`);return s}_getHeaderFooterReference(e,n){let{index:i}=this._resolve();return(0,t.resolveSectionHeaderFooterReference)(this._document.getDocumentDataModel().getSnapshot().documentStyle,(0,r.getTopLevelSectionBreaks)(this._document.getBody()),i,(0,t.getSectionHeaderFooterReferenceKey)(e,n))}_describeHeaderFooterReference(e,t){var n;let r=this._getHeaderFooterReference(e,t);return{segmentId:(n=r.segmentId)==null?null:n,linkedToPrevious:r.linkedToPrevious}}_setHeaderFooterLinkedToPrevious(e,n,i){return this._assertTraditionalDocument(),this._injector.get(t.ICommandService).syncExecuteCommand(r.SetSectionHeaderFooterLinkCommand.id,{unitId:this._document.getId(),sectionId:this._sectionId,kind:e,variant:n,linkedToPrevious:i,...i?{}:{segmentId:(0,t.generateRandomId)(6)}})}_assertTraditionalDocument(){if(this._document.getDocumentDataModel().getSnapshot().documentStyle.documentFlavor!==t.DocumentFlavor.TRADITIONAL)throw new h}_resolve(){this._assertTraditionalDocument();let e=(0,r.getTopLevelSectionBreaks)(this._document.getBody()),t=e.findIndex(e=>e.sectionId===this._sectionId);if(t<0)throw Error(`Document section with id ${this._sectionId} not found.`);return{index:t,sectionBreak:e[t]}}};function _(e){"@babel/helpers - typeof";return _=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},_(e)}function v(e,t){if(_(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(_(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function y(e){var t=v(e,`string`);return _(t)==`symbol`?t:t+``}function b(e,t,n){return(t=y(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function x(e,t){return function(n,r){t(n,r,e)}}function S(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}let C=class extends n.FBaseInitialable{constructor(e,t,n,r,i){super(t),this._documentDataModel=e,this._injector=t,this._univerInstanceService=n,this._resourceLoaderService=r,this._commandService=i,b(this,`id`,void 0),this.id=this._documentDataModel.getUnitId()}getDocumentDataModel(e=``){let t=this._documentDataModel.getSelfOrHeaderFooterModel(e);if(!t)throw Error(e===``?`Document data model is not found.`:`Document data model is not found in the segment: ${e}`);return t}getBody(e=``){var t;let n=(t=this._documentDataModel.getSelfOrHeaderFooterModel(e))==null?void 0:t.getBody();if(!n)throw Error(e===``?`Body is not found in the document.`:`Body is not found in the segment: ${e}`);return n}dispose(){super.dispose()}getId(){return this.id}getName(){return this._documentDataModel.getTitle()||``}isModern(){return this._documentDataModel.getSnapshot().documentStyle.documentFlavor===t.DocumentFlavor.MODERN}save(){return this._resourceLoaderService.saveUnit(this._documentDataModel.getUnitId())}undo(){return this._univerInstanceService.focusUnit(this.id),this._commandService.syncExecuteCommand(t.UndoCommand.id)}redo(){return this._univerInstanceService.focusUnit(this.id),this._commandService.syncExecuteCommand(t.RedoCommand.id)}ensurePageHeader(e=0){return this._ensureHeaderFooter(`header`,e)}ensurePageFooter(e=0){return this._ensureHeaderFooter(`footer`,e)}insertText(e,t,n=``){return c({startOffset:e,endOffset:e,segmentId:n},s(t),this._documentDataModel,this._injector)}getHeaderFooterOptions(){let e=this._documentDataModel.getSnapshot().documentStyle;return{marginHeader:e.marginHeader,marginFooter:e.marginFooter,useFirstPageHeaderFooter:e.useFirstPageHeaderFooter,evenAndOddHeaders:e.evenAndOddHeaders}}setHeaderFooterOptions(e){if(this.isModern())throw Error(`The document is a modern document, header/footer is not supported.`);return this._commandService.syncExecuteCommand(r.CreateHeaderFooterCommand.id,{unitId:this.getId(),headerFooterProps:e})}getTextRange(e,t,n=``){return this._injector.createInstance(d,this,e,t,n,this._injector)}getSections(){return this._documentDataModel.getSnapshot().documentStyle.documentFlavor===t.DocumentFlavor.TRADITIONAL?(0,r.getTopLevelSectionBreaks)(this.getBody()).map(e=>this._injector.createInstance(g,this,e.sectionId,this._injector)):[]}getSection(e){var t;return(t=this.getSections()[e])==null?null:t}getSectionAt(e){var t;return(t=this.getSections().find(t=>{let n=t.getRange();return e>=n.startOffset&&e<=n.endOffset}))==null?null:t}insertSectionBreak(e,n={}){var i;if(this._documentDataModel.getSnapshot().documentStyle.documentFlavor!==t.DocumentFlavor.TRADITIONAL)throw new h;let a=(0,t.createSectionId)(new Set(((i=this.getBody().sectionBreaks)==null?[]:i).map(e=>e.sectionId)));return this._commandService.syncExecuteCommand(r.InsertDocumentSectionBreakCommand.id,{unitId:this.getId(),offset:e,sectionId:a,config:n})?this._injector.createInstance(g,this,a,this._injector):null}insertColumnBreak(e){if(this._documentDataModel.getSnapshot().documentStyle.documentFlavor!==t.DocumentFlavor.TRADITIONAL)throw new h;return this.insertText(e,t.DataStreamTreeTokenType.COLUMN_BREAK)}insertHorizontalRule(e,n={padding:5,color:{rgb:`#CDD0D8`},width:1,dashStyle:t.DashStyleType.SOLID},i=``){var a;let o=this.getBody(i),s=(0,r.generateParagraphs)(t.DataStreamTreeTokenType.PARAGRAPH,void 0,n,(a=o.paragraphs)==null?void 0:a.map(e=>e.paragraphId)),l=s[0].paragraphId;return c({startOffset:e,endOffset:e,segmentId:i},{dataStream:t.DataStreamTreeTokenType.PARAGRAPH,paragraphs:s},this._documentDataModel,this._injector)?this.getParagraph(l,i):null}getParagraphs(e=``){let{paragraphs:t=[]}=this.getBody(e);return t.map(t=>this._createFDocumentParagraph(t.paragraphId,e))}getParagraph(e,t=``){let{paragraphs:n=[]}=this.getBody(t);return n.find(t=>t.paragraphId===e)?this._createFDocumentParagraph(e,t):null}findParagraphByText(e,t=``){return this.findParagraphs({text:e,segmentId:t})[0]||null}findParagraphs(e){let{text:t,paragraphId:n,segmentId:r=``}=typeof e==`string`?{text:e}:e;return this.getParagraphs(r).filter(e=>!(n&&e.getId()!==n||t&&!e.getText().includes(t)))}insertParagraph(e,t=``,n=``){let r=this._getParagraphInsertOffset(e,n);if(!c({startOffset:r,endOffset:r,segmentId:n},s(`${t}\r`),this._documentDataModel,this._injector))throw Error(`Failed to insert paragraph.`);let{paragraphs:i=[]}=this.getBody(n),a=i[e];if(!a)throw Error(`Failed to insert paragraph.`);return this._createFDocumentParagraph(a.paragraphId,n)}appendParagraph(e=``,t=``){let{paragraphs:n=[]}=this.getBody(t);return this.insertParagraph(n.length,e,t)}deleteRange(e){let t=this._normalizeDeleteRange(e);return t.startOffset>=t.endOffset?!1:c(t,{dataStream:``},this._documentDataModel,this._injector)}_createFDocumentParagraph(e,t=``){return this._injector.createInstance(p,this,e,t,this._injector)}_normalizeDeleteRange(e){let t=this.getBody(e.segmentId),n=t.dataStream.endsWith(`\r
3
+ `)?Math.max(0,t.dataStream.length-2):t.dataStream.length,r=Math.min(Math.max(e.endOffset,0),n);return{...e,startOffset:Math.min(Math.max(e.startOffset,0),r),endOffset:r}}_getParagraphInsertOffset(e,n=``){if(e<=0)return 0;let r=this.getBody(n),{dataStream:i,paragraphs:a=[]}=r;return a.length===0?Math.max(0,i.length-1):e>=a.length?a[a.length-1].startIndex+1:(0,t.getParagraphContentStartOffset)(r,a[e])}_ensureHeaderFooter(e,n){if(this.isModern())throw Error(`The document is a modern document, header/footer is not supported.`);let{createType:i,segmentId:a}=this._getHeaderFooterCreateInfo(e,n);if(a)return a;let o=(0,t.generateRandomId)(6);if(!this._commandService.syncExecuteCommand(r.CreateHeaderFooterCommand.id,{unitId:this.getId(),segmentId:o,createType:i}))throw Error(`Failed to create page ${e}.`);return o}_getHeaderFooterCreateInfo(e,n){var i,a;let{documentStyle:o}=this._documentDataModel.getSnapshot(),s=n===0,c=(n+1)%2==0;if(s&&o.useFirstPageHeaderFooter===t.BooleanNumber.TRUE){var l,u;return e===`header`?{createType:r.HeaderFooterType.FIRST_PAGE_HEADER,segmentId:(l=o.firstPageHeaderId)==null?``:l}:{createType:r.HeaderFooterType.FIRST_PAGE_FOOTER,segmentId:(u=o.firstPageFooterId)==null?``:u}}if(c&&o.evenAndOddHeaders===t.BooleanNumber.TRUE){var d,f;return e===`header`?{createType:r.HeaderFooterType.EVEN_PAGE_HEADER,segmentId:(d=o.evenPageHeaderId)==null?``:d}:{createType:r.HeaderFooterType.EVEN_PAGE_FOOTER,segmentId:(f=o.evenPageFooterId)==null?``:f}}return e===`header`?{createType:r.HeaderFooterType.DEFAULT_HEADER,segmentId:(i=o.defaultHeaderId)==null?``:i}:{createType:r.HeaderFooterType.DEFAULT_FOOTER,segmentId:(a=o.defaultFooterId)==null?``:a}}};C=S([x(1,(0,t.Inject)(t.Injector)),x(2,t.IUniverInstanceService),x(3,(0,t.Inject)(t.IResourceLoaderService)),x(4,t.ICommandService)],C);var w=class extends n.FUniver{createDocument(e){let n=this._injector.get(t.IUniverInstanceService).createUnit(t.UniverInstanceType.UNIVER_DOC,e);return this._injector.createInstance(C,n)}getActiveDocument(){let e=this._univerInstanceService.getCurrentUnitOfType(t.UniverInstanceType.UNIVER_DOC);return e?this._injector.createInstance(C,e):null}getDocument(e){let n=this._univerInstanceService.getUnit(e,t.UniverInstanceType.UNIVER_DOC);return n?this._injector.createInstance(C,n):null}};n.FUniver.extend(w);var T=class extends n.FEnum{get SectionType(){return t.SectionType}get ColumnSeparatorType(){return t.ColumnSeparatorType}};n.FEnum.extend(T),e.DocsSectionUnsupportedDocumentFlavorError=h,e.FDocsEnumMixin=T,Object.defineProperty(e,"FDocument",{enumerable:!0,get:function(){return C}}),e.FDocumentParagraph=p,e.FDocumentSection=g,e.FDocumentTextRange=d,e.isParagraphFacade=m,e.stripBlockTokens=u});
package/lib/umd/index.js CHANGED
@@ -1,2 +1,2 @@
1
- (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require("@univerjs/core"),require("@univerjs/engine-render"),require("rxjs")):typeof define==`function`&&define.amd?define([`exports`,`@univerjs/core`,`@univerjs/engine-render`,`rxjs`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.UniverDocs={},e.UniverCore,e.UniverEngineRender,e.rxjs))})(this,function(e,t,n,r){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});let i={id:`doc.operation.set-selections`,type:t.CommandType.OPERATION,handler:()=>!0};function a(e){"@babel/helpers - typeof";return a=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},a(e)}function o(e,t){if(a(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(a(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function s(e){var t=o(e,`string`);return a(t)==`symbol`?t:t+``}function c(e,t,n){return(t=s(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function l(e,t){return function(n,r){t(n,r,e)}}function u(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}let d=class extends t.RxDisposable{constructor(e,t){super(),this._commandService=e,this._univerInstanceService=t,c(this,`_currentSelection`,null),c(this,`_textSelectionInfo`,new Map),c(this,`_textSelection$`,new r.Subject),c(this,`textSelection$`,this._textSelection$.asObservable()),c(this,`_refreshSelection$`,new r.BehaviorSubject(null)),c(this,`refreshSelection$`,this._refreshSelection$.asObservable()),this._listenCurrentUnit()}_listenCurrentUnit(){this._univerInstanceService.getCurrentTypeOfUnit$(t.UniverInstanceType.UNIVER_DOC).pipe((0,r.takeUntil)(this.dispose$)).subscribe(e=>{if(e==null)return;let t=e.getUnitId();this._setCurrentSelectionNotRefresh({unitId:t,subUnitId:t})})}__getCurrentSelection(){return this._currentSelection}getSelectionInfo(e=this._currentSelection){return this._getTextRanges(e)}refreshSelection(e=this._currentSelection){e!=null&&this._refresh(e)}__TEST_ONLY_setCurrentSelection(e){this._currentSelection=e,this._refresh(e)}getTextRanges(e=this._currentSelection){var t;return(t=this._getTextRanges(e))==null?void 0:t.textRanges}getRectRanges(e=this._currentSelection){var t;return(t=this._getTextRanges(e))==null?void 0:t.rectRanges}getDocRanges(e=this._currentSelection){var t,n;let r=(t=this.getTextRanges(e))==null?[]:t,i=(n=this.getRectRanges(e))==null?[]:n;return[...r,...i].filter(e=>e.startOffset!=null&&e.endOffset!=null).sort((e,t)=>e.startOffset>t.startOffset?1:e.startOffset<t.startOffset?-1:0)}getActiveTextRange(){let e=this._getTextRanges(this._currentSelection);if(e==null)return;let{textRanges:t}=e;return t.find(e=>e.isActive)}getActiveRectRange(){let e=this._getTextRanges(this._currentSelection);if(e==null)return;let{rectRanges:t}=e;return t.find(e=>e.isActive)}__TEST_ONLY_add(e,t=!0){this._currentSelection!=null&&this._addByParam({...this._currentSelection,textRanges:e,rectRanges:[],segmentId:``,segmentPage:-1,isEditing:t,style:n.NORMAL_TEXT_SELECTION_PLUGIN_STYLE})}replaceTextRanges(e,t=!0,n){return this.replaceDocRanges(e,this._currentSelection,t,n)}replaceDocRanges(e,t=this._currentSelection,n=!0,r){if(t==null)return;let{unitId:i,subUnitId:a}=t;this._refreshSelection$.next({unitId:i,subUnitId:a,docRanges:e,isEditing:n,options:r})}__replaceTextRangesWithNoRefresh(e,t){if(this._currentSelection==null)return;let n={...e,...t};this._replaceByParam(n),this._textSelection$.next(n);let{unitId:r,subUnitId:a,segmentId:o,style:s,textRanges:c,rectRanges:l,isEditing:u}=n,d=[...c,...l].filter(e=>e.startOffset!=null&&e.endOffset!=null).sort((e,t)=>e.startOffset>t.startOffset?1:e.startOffset<t.startOffset?-1:0);this._commandService.executeCommand(i.id,{unitId:r,subUnitId:a,segmentId:o,style:s,isEditing:u,ranges:d})}dispose(){this._textSelection$.complete(),this._refreshSelection$.complete()}_setCurrentSelectionNotRefresh(e){this._currentSelection=e}_getTextRanges(e){var t;if(e==null)return;let{unitId:n,subUnitId:r=``}=e;return(t=this._textSelectionInfo.get(n))==null?void 0:t.get(r)}_refresh(e){let t=this._getTextRanges(e);if(t==null)return;let{textRanges:n,rectRanges:r}=t,i=[...n,...r],{unitId:a,subUnitId:o}=e;this._refreshSelection$.next({unitId:a,subUnitId:o,docRanges:i,isEditing:!1})}_replaceByParam(e){let{unitId:t,subUnitId:n,...r}=e;this._textSelectionInfo.has(t)||this._textSelectionInfo.set(t,new Map),this._textSelectionInfo.get(t).set(n,{...r})}_addByParam(e){let{unitId:t,subUnitId:n,...r}=e;this._textSelectionInfo.has(t)||this._textSelectionInfo.set(t,new Map);let i=this._textSelectionInfo.get(t);i.has(n)?i.get(n).textRanges.push(...e.textRanges):i.set(n,{...r})}};d=u([l(0,t.ICommandService),l(1,t.IUniverInstanceService)],d);let f=class extends t.RxDisposable{constructor(e,n,i){super(),this._context=e,this._localeService=n,this._univerInstanceService=i,c(this,`_skeleton`,void 0),c(this,`_docViewModel`,void 0),c(this,`_currentSkeleton$`,new r.BehaviorSubject(null)),c(this,`currentSkeleton$`,this._currentSkeleton$.asObservable()),c(this,`_currentSkeletonBefore$`,new r.BehaviorSubject(null)),c(this,`currentSkeletonBefore$`,this._currentSkeletonBefore$.asObservable()),c(this,`_currentViewModel$`,new r.BehaviorSubject(null)),c(this,`currentViewModel$`,this._currentViewModel$.asObservable()),this._init(),this._univerInstanceService.getCurrentTypeOfUnit$(t.UniverInstanceType.UNIVER_DOC).pipe((0,r.takeUntil)(this.dispose$)).subscribe(e=>{e&&e.getUnitId()===this._context.unitId&&this._update(e)})}dispose(){super.dispose(),this._currentSkeletonBefore$.complete(),this._currentSkeleton$.complete()}getSkeleton(){return this._skeleton}getViewModel(){return this._docViewModel}_init(){let e=this._context.unit;this._update(e)}_update(e){let n=this._context.unitId;if(e.getBody()==null)return;this._docViewModel&&(0,t.isInternalEditorID)(n)?(this._docViewModel.reset(e),this._context.unit=e):this._docViewModel||(this._docViewModel=this._buildDocViewModel(e)),this._skeleton||(this._skeleton=this._buildSkeleton(this._docViewModel));let r=this._skeleton;r.calculate(),this._currentSkeletonBefore$.next(r),this._currentSkeleton$.next(r),this._currentViewModel$.next(this._docViewModel)}_buildSkeleton(e){return n.DocumentSkeleton.create(e,this._localeService)}_buildDocViewModel(e){return new n.DocumentViewModel(e)}};f=u([l(1,(0,t.Inject)(t.LocaleService)),l(2,t.IUniverInstanceService)],f);var p=class extends t.RxDisposable{constructor(){super(),c(this,`_docStateChangeParams$`,new r.BehaviorSubject(null)),c(this,`docStateChangeParams$`,this._docStateChangeParams$.asObservable())}emitStateChangeInfo(e){this._docStateChangeParams$.next(e)}dispose(){super.dispose(),this._docStateChangeParams$.complete()}};let m=`doc.mutation.rich-text-editing`,h={id:m,type:t.CommandType.MUTATION,handler:(e,r,i)=>{var a,o;let{unitId:s,segmentId:c=``,actions:l,textRanges:u,prevTextRanges:h,trigger:g,noHistory:_,isCompositionEnd:v,noNeedSetTextRange:y,debounce:b,isEditing:x=!0,isSync:S,syncer:C}=r,w=S||(i==null?void 0:i.fromCollab)||(i==null?void 0:i.fromChangeset),T=e.get(t.IUniverInstanceService),E=e.get(n.IRenderManagerService),D=e.get(p),O=T.getUnit(s,t.UniverInstanceType.UNIVER_DOC),k=(a=E.getRenderUnitById(s))==null?void 0:a.with(f).getViewModel();if(O==null)throw Error(`DocumentDataModel not found for unitId: ${s}`);let A=e.get(d),j=(o=A.getDocRanges())==null?[]:o,M=!!O.getSnapshot().disabled;if(t.JSONX.isNoop(l)||l&&l.length===0||M)return{unitId:s,actions:[],textRanges:j};let N=t.JSONX.invertWithDoc(l,O.getSnapshot());O.apply(l),k==null||k.reset(O),!y&&u&&g!=null&&!w&&queueMicrotask(()=>{A.replaceDocRanges(u,{unitId:s,subUnitId:s},x,r.options)});let P={commandId:m,unitId:s,segmentId:c,trigger:g,noHistory:_,debounce:b,redoState:{actions:l,textRanges:u},undoState:{actions:N,textRanges:h==null?j:h},isCompositionEnd:v,isSync:w,syncer:C};return D.emitStateChangeInfo(P),{unitId:s,actions:N,textRanges:j}}},g={id:`doc.command.insert-text`,type:t.CommandType.COMMAND,handler:(e,n)=>{var r,i;let a=e.get(t.ICommandService),{range:o,segmentId:s,body:c,unitId:l,cursorOffset:u}=n,f=e.get(d),p=e.get(t.IUniverInstanceService).getUnit(l,t.UniverInstanceType.UNIVER_DOC);if(p==null)return!1;let m=f.getActiveTextRange(),g=(r=p.getSelfOrHeaderFooterModel((i=m==null?void 0:m.segmentId)==null?``:i))==null?void 0:r.getBody();if(g==null)return!1;let{startOffset:_,collapsed:v}=o,y=u==null?c.dataStream.length:u,b=[{startOffset:_+y,endOffset:_+y,style:m==null?void 0:m.style,collapsed:v}],x={id:h.id,params:{unitId:l,actions:[],textRanges:b,debounce:!0}},S=new t.TextX,C=t.JSONX.getInstance();if(v)_>0&&S.push({t:t.TextXActionType.RETAIN,len:_}),S.push({t:t.TextXActionType.INSERT,body:c,len:c.dataStream.length});else{let e=t.BuildTextUtils.selection.delete([o],g,0,c);S.push(...e)}x.params.textRanges=[{startOffset:_+y,endOffset:_+y,collapsed:v}];let w=(0,t.getRichTextEditPath)(p,s);return x.params.actions=C.editOp(S.serialize(),w),!!a.syncExecuteCommand(x.id,x.params)}},_={id:`doc.command.delete-text`,type:t.CommandType.COMMAND,handler:(e,n)=>{var r,i;let a=e.get(t.ICommandService),o=e.get(t.IUniverInstanceService),{range:s,segmentId:c,unitId:l,direction:u,len:d=1}=n,f=o.getUnit(l,t.UniverInstanceType.UNIVER_DOC),p=f==null||(r=f.getSelfOrHeaderFooterModel(c))==null?void 0:r.getBody();if(f==null||p==null)return!1;let{startOffset:m}=s,g=u===t.DeleteDirection.LEFT?m-d:m,_=u===t.DeleteDirection.LEFT?m-1:m+d-1,v=(i=p.customRanges)==null?void 0:i.find(e=>e.startIndex<=g&&e.endIndex>=_);v!=null&&v.wholeEntity&&(g=v.startIndex,_=Math.max(_,v.endIndex));let y={id:h.id,params:{unitId:l,actions:[],textRanges:[{startOffset:g,endOffset:g,collapsed:!0}],debounce:!0}},b=new t.TextX,x=t.JSONX.getInstance();b.push({t:t.TextXActionType.RETAIN,len:g-0}),b.push({t:t.TextXActionType.DELETE,len:_-g+1});let S=(0,t.getRichTextEditPath)(f,c);return y.params.actions=x.editOp(b.serialize(),S),!!a.syncExecuteCommand(y.id,y.params)}},v={id:`doc.command.update-text`,type:t.CommandType.COMMAND,handler:(e,n)=>{let{range:r,segmentId:i,updateBody:a,coverType:o,unitId:s,textRanges:c}=n,l=e.get(t.ICommandService),u=e.get(t.IUniverInstanceService).getCurrentUnitOfType(t.UniverInstanceType.UNIVER_DOC);if(u==null)return!1;let d={id:h.id,params:{unitId:s,actions:[],textRanges:c}},f=new t.TextX,p=t.JSONX.getInstance(),{startOffset:m,endOffset:g}=r;f.push({t:t.TextXActionType.RETAIN,len:m}),f.push({t:t.TextXActionType.RETAIN,body:a,len:g-m,coverType:o});let _=(0,t.getRichTextEditPath)(u,i);return d.params.actions=p.editOp(f.serialize(),_),!!l.syncExecuteCommand(d.id,d.params)}},y=function(e){return e[e.FIRST_PAGE_HEADER=0]=`FIRST_PAGE_HEADER`,e[e.FIRST_PAGE_FOOTER=1]=`FIRST_PAGE_FOOTER`,e[e.DEFAULT_HEADER=2]=`DEFAULT_HEADER`,e[e.DEFAULT_FOOTER=3]=`DEFAULT_FOOTER`,e[e.EVEN_PAGE_HEADER=4]=`EVEN_PAGE_HEADER`,e[e.EVEN_PAGE_FOOTER=5]=`EVEN_PAGE_FOOTER`,e}({});function b(){return{dataStream:`\r
2
- `,textRuns:[{st:0,ed:0,ts:{fs:9}}],customBlocks:[],paragraphs:[{startIndex:0,paragraphId:(0,t.createParagraphId)(new Set),paragraphStyle:{spaceAbove:{v:0},lineSpacing:1.5,spaceBelow:{v:0}}}],sectionBreaks:[{startIndex:1}]}}function x(e,n,r,i,a=`single`){let o=t.JSONX.getInstance(),s=e==null?(0,t.generateRandomId)(6):e,c=n===2||n===0||n===4,l=o.insertOp([c?`headers`:`footers`,s],{[c?`headerId`:`footerId`]:s,body:b()});i.push(l);let u=`defaultHeaderId`,d=`defaultFooterId`;switch(n){case 2:u=`defaultHeaderId`,d=`defaultFooterId`;break;case 3:u=`defaultFooterId`,d=`defaultHeaderId`;break;case 0:u=`firstPageHeaderId`,d=`firstPageFooterId`;break;case 1:u=`firstPageFooterId`,d=`firstPageHeaderId`;break;case 4:u=`evenPageHeaderId`,d=`evenPageFooterId`;break;case 5:u=`evenPageFooterId`,d=`evenPageHeaderId`;break;default:throw Error(`Unknown header footer type: ${n}`)}let f=[[u,s]];if(a===`pair`&&d!=null){let e=(0,t.generateRandomId)(6),n=o.insertOp([c?`footers`:`headers`,e],{[c?`footerId`:`headerId`]:e,body:b()});i.push(n),f.push([d,e])}for(let[e,t]of f)if(r[e]!=null){let n=o.replaceOp([`documentStyle`,e],r[e],t);i.push(n)}else{let n=o.insertOp([`documentStyle`,e],t);i.push(n)}return i}let S={id:`doc.command.create-header-footer`,type:t.CommandType.COMMAND,handler:(e,n)=>{let r=e.get(t.ICommandService),i=e.get(t.IUniverInstanceService),{unitId:a,segmentId:o,createType:s,headerFooterProps:c,createMode:l=`single`}=n,u=i.getUnit(a,t.UniverInstanceType.UNIVER_DOC);if(u==null)return!1;let{documentStyle:d}=u.getSnapshot();if(d.documentFlavor===t.DocumentFlavor.MODERN)return!1;let f=[],p=t.JSONX.getInstance();if(s!=null&&x(o,s,d,f,l),c!=null&&Object.keys(c).forEach(e=>{let t=c[e],n=d[e];if(t===n)return;let r=n===void 0?p.insertOp([`documentStyle`,e],t):p.replaceOp([`documentStyle`,e],n,t);f.push(r)}),f.length===0)return!1;let m={id:h.id,params:{unitId:a,actions:f.reduce((e,n)=>t.JSONX.compose(e,n),null),textRanges:[{startOffset:0,endOffset:0,collapsed:!0}],debounce:!0}};return((c==null?void 0:c.marginFooter)!=null||(c==null?void 0:c.marginHeader)!=null)&&(m.params.noNeedSetTextRange=!0),!!r.syncExecuteCommand(m.id,m.params)}};var C=`@univerjs/docs`,w=`1.0.0-alpha.2`;let T={id:`doc.mutation.rename-doc`,type:t.CommandType.MUTATION,handler:(e,n)=>{let r=e.get(t.IUniverInstanceService).getUnit(n.unitId,t.UniverInstanceType.UNIVER_DOC);return r?(r.setName(n.name),!0):!1}},E={},D=class extends t.Disposable{constructor(e,t,n){super(),this._commandService=e,this._textSelectionManagerService=t,this._univerInstanceService=n,this._initSelectionChange()}_transformCustomRange(e,n){var r;let{startOffset:i,endOffset:a,collapsed:o}=n,s=(r=e.getCustomRanges())==null?void 0:r.filter(e=>!e.wholeEntity||i<=e.startIndex&&a>e.endIndex?!1:o?e.startIndex<i&&e.endIndex>=a:t.BuildTextUtils.range.isIntersects(i,a-1,e.startIndex,e.endIndex));if(s!=null&&s.length){let e=i,t=a;return s.forEach(n=>{e=Math.min(n.startIndex,e),t=Math.max(n.endIndex+1,t)}),{...n,startOffset:e,endOffset:t,collapsed:e===t}}return n}_initSelectionChange(){this.disposeWithMe(this._commandService.onCommandExecuted(e=>{if(e.id===i.id){let{unitId:t,ranges:n,isEditing:r}=e.params,i=this._univerInstanceService.getUnit(t);if(!i)return;let a=n.map(e=>this._transformCustomRange(i,e));a.some((e,t)=>n[t]!==e)&&this._textSelectionManagerService.replaceTextRanges(a,r)}}))}};D=u([l(0,t.ICommandService),l(1,(0,t.Inject)(d)),l(2,t.IUniverInstanceService)],D);var O=class extends t.Disposable{constructor(...e){super(...e),c(this,`_validators`,[]),c(this,`_transformers`,[])}registerValidator(e){return this._validators.push(e),this.disposeWithMe((0,t.toDisposable)(()=>(0,t.remove)(this._validators,e)))}registerTransformer(e){return this._transformers.push(e),this.disposeWithMe((0,t.toDisposable)(()=>(0,t.remove)(this._transformers,e)))}canMoveBlock(e){return this._validators.every(t=>t(e))}transformMoveResult(e){return this._transformers.reduce((t,n)=>n({...e,result:t}),e.result)}},k=class extends t.Disposable{constructor(...e){super(...e),c(this,`_range`,null)}setInsertRange(e){this._range=e}consumeInsertRange(e){if(!this._range||e&&this._range.unitId!==e)return null;let t=this._range;return this._range=null,t}clearInsertRange(){this._range=null}};let A=(0,t.createIdentifier)(`doc.state-change-interceptor-service`),j=class extends t.RxDisposable{constructor(e,t,n,i,a){super(),this._undoRedoService=e,this._commandService=t,this._univerInstanceService=n,this._docStateEmitService=i,this._docStateChangeInterceptorService=a,c(this,`_docStateChange$`,new r.BehaviorSubject(null)),c(this,`docStateChange$`,this._docStateChange$.asObservable()),c(this,`_historyStateCache`,new Map),c(this,`_changeStateCache`,new Map),c(this,`_historyTimer`,null),c(this,`_changeStateCacheTimer`,null),this._initialize(),this._listenDocStateChange()}getStateCache(e){var t,n;return{history:(t=this._historyStateCache.get(e))==null?[]:t,collaboration:(n=this._changeStateCache.get(e))==null?[]:n}}setStateCache(e,t){this._historyStateCache.set(e,t.history),this._changeStateCache.set(e,t.collaboration)}_setChangeState(e){this._cacheChangeState(e,`history`),this._cacheChangeState(e,`collaboration`)}_initialize(){this.disposeWithMe(this._commandService.beforeCommandExecuted(e=>{if(e.id===t.UndoCommandId||e.id===t.RedoCommandId){let e=this._univerInstanceService.getCurrentUnitOfType(t.UniverInstanceType.UNIVER_DOC);if(e==null)return;let n=e.getUnitId();this._pushHistory(n),this._emitChangeState(n)}}))}_listenDocStateChange(){this._docStateEmitService.docStateChangeParams$.pipe((0,r.takeUntil)(this.dispose$)).subscribe(e=>{var t,n;if(e==null)return;let r=(t=(n=this._docStateChangeInterceptorService)==null?void 0:n.transformChangeStateInfo(e))==null?e:t;if(r==null||r.isSync)return;let{isCompositionEnd:i,isSync:a,syncer:o,...s}=r;this._setChangeState(s)})}_cacheChangeState(e,n=`history`){let{trigger:r,unitId:i,noHistory:a,debounce:o=!1}=e;if(a||n===`history`&&r==null||n===`history`&&(r===t.RedoCommandId||r===t.UndoCommandId))return;let s=n===`history`?this._historyStateCache:this._changeStateCache,c=n===`history`?this._pushHistory.bind(this):this._emitChangeState.bind(this);if(s.has(i)){let t=s.get(i);t==null||t.push(e)}else s.set(i,[e]);o?n===`history`?(this._historyTimer&&clearTimeout(this._historyTimer),this._historyTimer=setTimeout(()=>{c(i)},300)):(this._changeStateCacheTimer&&clearTimeout(this._changeStateCacheTimer),this._changeStateCacheTimer=setTimeout(()=>{c(i)},300)):c(i)}_pushHistory(e){let n=this._undoRedoService,r=this._historyStateCache.get(e);if(n==null||!Array.isArray(r)||r.length===0)return;let i=r.length,a=r[0].commandId,o=r[0],s=r[i-1],c={unitId:e,actions:r.reduce((e,n)=>t.JSONX.compose(e,n.redoState.actions),null),textRanges:s.redoState.textRanges},l={unitId:e,actions:r.reverse().reduce((e,n)=>t.JSONX.compose(e,n.undoState.actions),null),textRanges:o.undoState.textRanges};n.pushUndoRedo({unitID:e,undoMutations:[{id:a,params:l}],redoMutations:[{id:a,params:c}]}),r.length=0}_emitChangeState(e){let n=this._changeStateCache.get(e);if(!Array.isArray(n)||n.length===0)return;let r=n.length,{commandId:i,trigger:a,segmentId:o,noHistory:s,debounce:c}=n[0],l=n[0],u=n[r-1],d={commandId:i,unitId:e,trigger:a,redoState:{unitId:e,actions:n.reduce((e,n)=>t.JSONX.compose(e,n.redoState.actions),null),textRanges:u.redoState.textRanges},undoState:{unitId:e,actions:n.reverse().reduce((e,n)=>t.JSONX.compose(e,n.undoState.actions),null),textRanges:l.undoState.textRanges},segmentId:o,noHistory:s,debounce:c};n.length=0,this._docStateChange$.next(d)}};j=u([l(0,(0,t.Optional)(t.IUndoRedoService)),l(1,t.ICommandService),l(2,t.IUniverInstanceService),l(3,(0,t.Inject)(p)),l(4,(0,t.Optional)(A))],j);let M=class extends t.Plugin{constructor(e=E,n,r){super(),this._config=e,this._injector=n,this._configService=r;let{...i}=(0,t.merge)({},E,this._config);this._configService.setConfig(`docs.config`,i)}onStarting(){this._initializeDependencies(),this._initializeCommands()}_initializeCommands(){[g,_,v,S,h,T,i].forEach(e=>{this._injector.get(t.ICommandService).registerCommand(e)})}_initializeDependencies(){[[d],[p],[j],[O],[k],[D]].forEach(e=>this._injector.add(e))}onReady(){this._injector.get(j),this._injector.get(D)}};c(M,`pluginName`,`DOCS_PLUGIN`),c(M,`packageName`,C),c(M,`version`,w),M=u([l(1,(0,t.Inject)(t.Injector)),l(2,t.IConfigService)],M);let N={CUSTOM_RANGE:(0,t.createInterceptorKey)(`CUSTOM_RANGE`),CUSTOM_DECORATION:(0,t.createInterceptorKey)(`CUSTOM_DECORATION`)},P=class extends t.Disposable{constructor(e,n){super(),this._context=e,this._docSkeletonManagerService=n,c(this,`_interceptorsByName`,new Map);let r=this._docSkeletonManagerService.getViewModel(),i=r.getDataModel().getUnitId();if(i===t.DOCS_NORMAL_EDITOR_UNIT_ID_KEY||i===t.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY)return;this.disposeWithMe(this.interceptDocumentViewModel(r)),this.disposeWithMe(this.intercept(N.CUSTOM_RANGE,{priority:-1,handler:(e,t,n)=>n(e)}));let a=new t.DisposableCollection;r.segmentViewModels$.subscribe(e=>{a.dispose(),a=new t.DisposableCollection,e.forEach(e=>{a.add(this.interceptDocumentViewModel(e))})}),this.disposeWithMe(a)}intercept(e,n){let r=e;this._interceptorsByName.has(r)||this._interceptorsByName.set(r,[]);let i=this._interceptorsByName.get(r);return i.push(n),this._interceptorsByName.set(r,i.sort((e,t)=>{var n,r;return((n=t.priority)==null?0:n)-((r=e.priority)==null?0:r)})),this.disposeWithMe((0,t.toDisposable)(()=>(0,t.remove)(this._interceptorsByName.get(r),n)))}fetchThroughInterceptors(e){let n=e;return(0,t.composeInterceptors)(this._interceptorsByName.get(n)||[])}interceptDocumentViewModel(e){let n=new t.DisposableCollection;return n.add(e.registerCustomRangeInterceptor({getCustomRange:t=>{var n;return this.fetchThroughInterceptors(N.CUSTOM_RANGE)(e.getCustomRangeRaw(t),{index:t,unitId:e.getDataModel().getUnitId(),customRanges:(n=e.getDataModel().getCustomRanges())==null?[]:n})},getCustomDecoration:t=>{var n;return this.fetchThroughInterceptors(N.CUSTOM_DECORATION)(e.getCustomDecorationRaw(t),{index:t,unitId:e.getDataModel().getUnitId(),customDecorations:(n=e.getDataModel().getCustomDecorations())==null?[]:n})}})),n}};P=u([l(1,(0,t.Inject)(f))],P);function F(e,n,r){let{unitId:i,segmentId:a}=n,o=e.get(t.IUniverInstanceService).getUnit(i);if(!o)return!1;let s={id:h.id,params:{unitId:n.unitId,actions:[],textRanges:void 0}},c=t.JSONX.getInstance(),l=t.BuildTextUtils.customRange.add({...n,body:r});if(!l)return!1;let u=(0,t.getRichTextEditPath)(o,a);return s.params.actions=c.editOp(l.serialize(),u),s}function I(e,n){var r,i;let{rangeId:a,rangeType:o,wholeEntity:s,properties:c,unitId:l,selections:u}=n,f=e.get(d),p=e.get(t.IUniverInstanceService),m=u==null?f.getTextRanges({unitId:l,subUnitId:l}):u,g=m==null||(r=m[0])==null?void 0:r.segmentId;if(!(m!=null&&m.length))return!1;let _=p.getUnit(l,t.UniverInstanceType.UNIVER_DOC);if(!_)return!1;let v=(i=_.getSelfOrHeaderFooterModel(g))==null?void 0:i.getBody();if(!v)return!1;let y=t.BuildTextUtils.customRange.add({ranges:m,rangeId:a,rangeType:o,segmentId:g,wholeEntity:s,properties:c,body:v});if(!y)return!1;let b=t.JSONX.getInstance(),x={id:h.id,params:{unitId:l,actions:[],textRanges:y.selections,segmentId:g},textX:y},S=(0,t.getRichTextEditPath)(_,g);return x.params.actions=b.editOp(y.serialize(),S),x}function L(e,n){let{unitId:r,segmentId:i,insert:a}=n,o=e.get(t.IUniverInstanceService).getUnit(r);if(!o)return!1;let s={id:h.id,params:{unitId:n.unitId,actions:[],textRanges:void 0,segmentId:i}},c=t.JSONX.getInstance(),l=t.BuildTextUtils.customRange.delete({documentDataModel:o,rangeId:n.rangeId,insert:a,segmentId:i});if(!l)return!1;let u=(0,t.getRichTextEditPath)(o,i);return s.params.actions=c.editOp(l.serialize(),u),s.params.textRanges=l.selections,s}function R(e,n){var r,i,a,o;let{unitId:s,body:c,doc:l}=n,u=l;if(u||(u=e.get(t.IUniverInstanceService).getUnit(s)),!u)return!1;let f=(r=n.selection)==null?void 0:r.segmentId,p=(i=u.getSelfOrHeaderFooterModel(f))==null?void 0:i.getBody();if(!p)return!1;let m=e.get(d),g=(a=n.selection)==null?m.getActiveTextRange():a;if(!g||!p)return!1;let _=(o=n.textRanges)==null?[{startOffset:g.startOffset+c.dataStream.length,endOffset:g.startOffset+c.dataStream.length,collapsed:!0,segmentId:f}]:o,v=t.BuildTextUtils.selection.replace({selection:g,body:c,doc:u});if(!v)return!1;let y={id:h.id,params:{unitId:s,actions:[],textRanges:_,debounce:!0,segmentId:f},textX:v},b=t.JSONX.getInstance();return y.params.actions=b.editOp(v.serialize()),y}function z(e,t){try{return e.get(k).consumeInsertRange(t)}catch{return null}}function B(e){return!!(e!=null&&e.segmentId)}e.CreateHeaderFooterCommand=S,e.DOC_INTERCEPTOR_POINT=N,e.DeleteTextCommand=_,e.DocBlockMoveValidatorService=O,e.DocContentInsertService=k,Object.defineProperty(e,"DocInterceptorService",{enumerable:!0,get:function(){return P}}),Object.defineProperty(e,"DocSelectionManagerService",{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,"DocSkeletonManagerService",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"DocStateChangeManagerService",{enumerable:!0,get:function(){return j}}),e.DocStateEmitService=p,e.HeaderFooterType=y,e.IDocStateChangeInterceptorService=A,e.InsertTextCommand=g,e.RichTextEditingMutation=h,e.SetTextSelectionsOperation=i,Object.defineProperty(e,"UniverDocsPlugin",{enumerable:!0,get:function(){return M}}),e.UpdateTextCommand=v,e.addCustomRangeBySelectionFactory=I,e.addCustomRangeFactory=F,e.consumeContentInsertRange=z,e.deleteCustomRangeFactory=L,e.isHeaderFooterSelection=B,e.replaceSelectionFactory=R});
1
+ (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require("@univerjs/core"),require("@univerjs/engine-render"),require("rxjs")):typeof define==`function`&&define.amd?define([`exports`,`@univerjs/core`,`@univerjs/engine-render`,`rxjs`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.UniverDocs={},e.UniverCore,e.UniverEngineRender,e.rxjs))})(this,function(e,t,n,r){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});let i={id:`doc.operation.set-selections`,type:t.CommandType.OPERATION,handler:()=>!0};function a(e){"@babel/helpers - typeof";return a=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},a(e)}function o(e,t){if(a(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(a(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function s(e){var t=o(e,`string`);return a(t)==`symbol`?t:t+``}function c(e,t,n){return(t=s(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function l(e,t){return function(n,r){t(n,r,e)}}function u(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}let d=class extends t.RxDisposable{constructor(e,t){super(),this._commandService=e,this._univerInstanceService=t,c(this,`_currentSelection`,null),c(this,`_textSelectionInfo`,new Map),c(this,`_textSelection$`,new r.Subject),c(this,`textSelection$`,this._textSelection$.asObservable()),c(this,`_refreshSelection$`,new r.BehaviorSubject(null)),c(this,`refreshSelection$`,this._refreshSelection$.asObservable()),this._listenCurrentUnit()}_listenCurrentUnit(){this._univerInstanceService.getCurrentTypeOfUnit$(t.UniverInstanceType.UNIVER_DOC).pipe((0,r.takeUntil)(this.dispose$)).subscribe(e=>{if(e==null)return;let t=e.getUnitId();this._setCurrentSelectionNotRefresh({unitId:t,subUnitId:t})})}__getCurrentSelection(){return this._currentSelection}getSelectionInfo(e=this._currentSelection){return this._getTextRanges(e)}refreshSelection(e=this._currentSelection){e!=null&&this._refresh(e)}__TEST_ONLY_setCurrentSelection(e){this._currentSelection=e,this._refresh(e)}getTextRanges(e=this._currentSelection){var t;return(t=this._getTextRanges(e))==null?void 0:t.textRanges}getRectRanges(e=this._currentSelection){var t;return(t=this._getTextRanges(e))==null?void 0:t.rectRanges}getDocRanges(e=this._currentSelection){var t,n;let r=(t=this.getTextRanges(e))==null?[]:t,i=(n=this.getRectRanges(e))==null?[]:n;return[...r,...i].filter(e=>e.startOffset!=null&&e.endOffset!=null).sort((e,t)=>e.startOffset>t.startOffset?1:e.startOffset<t.startOffset?-1:0)}getActiveTextRange(){let e=this._getTextRanges(this._currentSelection);if(e==null)return;let{textRanges:t}=e;return t.find(e=>e.isActive)}getActiveRectRange(){let e=this._getTextRanges(this._currentSelection);if(e==null)return;let{rectRanges:t}=e;return t.find(e=>e.isActive)}__TEST_ONLY_add(e,t=!0){this._currentSelection!=null&&this._addByParam({...this._currentSelection,textRanges:e,rectRanges:[],segmentId:``,segmentPage:-1,isEditing:t,style:n.NORMAL_TEXT_SELECTION_PLUGIN_STYLE})}replaceTextRanges(e,t=!0,n){return this.replaceDocRanges(e,this._currentSelection,t,n)}replaceDocRanges(e,t=this._currentSelection,n=!0,r){if(t==null)return;let{unitId:i,subUnitId:a}=t;this._refreshSelection$.next({unitId:i,subUnitId:a,docRanges:e,isEditing:n,options:r})}__replaceTextRangesWithNoRefresh(e,t){if(this._currentSelection==null)return;let n={...e,...t};this._replaceByParam(n),this._textSelection$.next(n);let{unitId:r,subUnitId:a,segmentId:o,style:s,textRanges:c,rectRanges:l,isEditing:u}=n,d=[...c,...l].filter(e=>e.startOffset!=null&&e.endOffset!=null).sort((e,t)=>e.startOffset>t.startOffset?1:e.startOffset<t.startOffset?-1:0);this._commandService.executeCommand(i.id,{unitId:r,subUnitId:a,segmentId:o,style:s,isEditing:u,ranges:d})}dispose(){this._textSelection$.complete(),this._refreshSelection$.complete()}_setCurrentSelectionNotRefresh(e){this._currentSelection=e}_getTextRanges(e){var t;if(e==null)return;let{unitId:n,subUnitId:r=``}=e;return(t=this._textSelectionInfo.get(n))==null?void 0:t.get(r)}_refresh(e){let t=this._getTextRanges(e);if(t==null)return;let{textRanges:n,rectRanges:r}=t,i=[...n,...r],{unitId:a,subUnitId:o}=e;this._refreshSelection$.next({unitId:a,subUnitId:o,docRanges:i,isEditing:!1})}_replaceByParam(e){let{unitId:t,subUnitId:n,...r}=e;this._textSelectionInfo.has(t)||this._textSelectionInfo.set(t,new Map),this._textSelectionInfo.get(t).set(n,{...r})}_addByParam(e){let{unitId:t,subUnitId:n,...r}=e;this._textSelectionInfo.has(t)||this._textSelectionInfo.set(t,new Map);let i=this._textSelectionInfo.get(t);i.has(n)?i.get(n).textRanges.push(...e.textRanges):i.set(n,{...r})}};d=u([l(0,t.ICommandService),l(1,t.IUniverInstanceService)],d);let f=class extends t.RxDisposable{constructor(e,n,i){super(),this._context=e,this._localeService=n,this._univerInstanceService=i,c(this,`_skeleton`,void 0),c(this,`_docViewModel`,void 0),c(this,`_currentSkeleton$`,new r.BehaviorSubject(null)),c(this,`currentSkeleton$`,this._currentSkeleton$.asObservable()),c(this,`_currentSkeletonBefore$`,new r.BehaviorSubject(null)),c(this,`currentSkeletonBefore$`,this._currentSkeletonBefore$.asObservable()),c(this,`_currentViewModel$`,new r.BehaviorSubject(null)),c(this,`currentViewModel$`,this._currentViewModel$.asObservable()),this._init(),this._univerInstanceService.getCurrentTypeOfUnit$(t.UniverInstanceType.UNIVER_DOC).pipe((0,r.takeUntil)(this.dispose$)).subscribe(e=>{e&&e.getUnitId()===this._context.unitId&&this._update(e)})}dispose(){super.dispose(),this._currentSkeletonBefore$.complete(),this._currentSkeleton$.complete()}getSkeleton(){return this._skeleton}getViewModel(){return this._docViewModel}_init(){let e=this._context.unit;this._update(e)}_update(e){let n=this._context.unitId;if(e.getBody()==null)return;this._docViewModel&&(0,t.isInternalEditorID)(n)?(this._docViewModel.reset(e),this._context.unit=e):this._docViewModel||(this._docViewModel=this._buildDocViewModel(e)),this._skeleton||(this._skeleton=this._buildSkeleton(this._docViewModel));let r=this._skeleton;r.calculate(),this._currentSkeletonBefore$.next(r),this._currentSkeleton$.next(r),this._currentViewModel$.next(this._docViewModel)}_buildSkeleton(e){return n.DocumentSkeleton.create(e,this._localeService)}_buildDocViewModel(e){return new n.DocumentViewModel(e)}};f=u([l(1,(0,t.Inject)(t.LocaleService)),l(2,t.IUniverInstanceService)],f);var p=class extends t.RxDisposable{constructor(){super(),c(this,`_docStateChangeParams$`,new r.BehaviorSubject(null)),c(this,`docStateChangeParams$`,this._docStateChangeParams$.asObservable())}emitStateChangeInfo(e){this._docStateChangeParams$.next(e)}dispose(){super.dispose(),this._docStateChangeParams$.complete()}};let m=`doc.mutation.rich-text-editing`;function h(e,t){if(!t)return`body`;let{headers:n,footers:r}=e.getSnapshot();return n!=null&&n[t]?`header`:r!=null&&r[t]?`footer`:`body`}function g(e,n){let r=e.getSelfOrHeaderFooterModel(n),i=r==null?void 0:r.getBody();if(!i)return;let a=h(e,n),o=(0,t.validateDocBodyStructure)(i,{segmentType:a,segmentId:n||void 0});if(!o.length)return;let s=o.map(e=>`${e.code}${e.index==null?``:`@${e.index}`}`).join(`, `),c=n?`${a} ${n}`:a;throw Error(`[DocStructure] ${c}: ${s}`)}let _={id:m,type:t.CommandType.MUTATION,handler:(e,r,i)=>{var a,o;let{unitId:s,segmentId:c=``,actions:l,textRanges:u,prevTextRanges:h,trigger:_,noHistory:v,isCompositionEnd:y,noNeedSetTextRange:b,debounce:x,isEditing:S=!0,isSync:C,syncer:w}=r,T=C||(i==null?void 0:i.fromCollab)||(i==null?void 0:i.fromChangeset),E=e.get(t.IUniverInstanceService),D=e.get(n.IRenderManagerService),O=e.get(p),k=E.getUnit(s,t.UniverInstanceType.UNIVER_DOC),A=(a=D.getRenderUnitById(s))==null?void 0:a.with(f).getViewModel();if(k==null)throw Error(`DocumentDataModel not found for unitId: ${s}`);let j=e.get(d),M=(o=j.getDocRanges())==null?[]:o,N=!!k.getSnapshot().disabled;if(t.JSONX.isNoop(l)||l&&l.length===0||N)return{unitId:s,actions:[],textRanges:M};let P=t.JSONX.invertWithDoc(l,k.getSnapshot());k.apply(l);try{g(k,c)}catch(e){throw k.apply(P),e}A==null||A.reset(k),!b&&u&&_!=null&&!T&&queueMicrotask(()=>{j.replaceDocRanges(u,{unitId:s,subUnitId:s},S,r.options)});let F={commandId:m,unitId:s,segmentId:c,trigger:_,noHistory:v,debounce:x,redoState:{actions:l,textRanges:u},undoState:{actions:P,textRanges:h==null?M:h},isCompositionEnd:y,isSync:T,syncer:w};return O.emitStateChangeInfo(F),{unitId:s,actions:P,textRanges:M}}},v={id:`doc.command.insert-text`,type:t.CommandType.COMMAND,handler:(e,n)=>{var r,i,a;let o=e.get(t.ICommandService),{range:s,segmentId:c,body:l,unitId:u,cursorOffset:f}=n,p=e.get(d),m=e.get(t.IUniverInstanceService).getUnit(u,t.UniverInstanceType.UNIVER_DOC);if(m==null)return!1;let h=p.getActiveTextRange(),g=`segmentId`in s?s.segmentId:void 0,v=(r=(i=c==null?g:c)==null?h==null?void 0:h.segmentId:i)==null?``:r,y=(a=m.getSelfOrHeaderFooterModel(v))==null?void 0:a.getBody();if(y==null)return!1;let{startOffset:b,collapsed:x}=s,S=f==null?l.dataStream.length:f,C=[{startOffset:b+S,endOffset:b+S,style:h==null?void 0:h.style,collapsed:x}],w={id:_.id,params:{unitId:u,actions:[],textRanges:C,debounce:!0}},T=new t.TextX,E=t.JSONX.getInstance();if(x)b>0&&T.push({t:t.TextXActionType.RETAIN,len:b}),T.push({t:t.TextXActionType.INSERT,body:l,len:l.dataStream.length});else{let e=t.BuildTextUtils.selection.delete([s],y,0,l);T.push(...e)}w.params.textRanges=[{startOffset:b+S,endOffset:b+S,collapsed:x}];let D=(0,t.getRichTextEditPath)(m,c);return w.params.actions=E.editOp(T.serialize(),D),!!o.syncExecuteCommand(w.id,w.params)}},y={id:`doc.command.delete-text`,type:t.CommandType.COMMAND,handler:(e,n)=>{var r,i;let a=e.get(t.ICommandService),o=e.get(t.IUniverInstanceService),{range:s,segmentId:c,unitId:l,direction:u,len:d=1}=n,f=o.getUnit(l,t.UniverInstanceType.UNIVER_DOC),p=f==null||(r=f.getSelfOrHeaderFooterModel(c))==null?void 0:r.getBody();if(f==null||p==null)return!1;let{startOffset:m}=s,h=u===t.DeleteDirection.LEFT?m-d:m,g=u===t.DeleteDirection.LEFT?m-1:m+d-1,v=(i=p.customRanges)==null?void 0:i.find(e=>e.startIndex<=h&&e.endIndex>=g);v!=null&&v.wholeEntity&&(h=v.startIndex,g=Math.max(g,v.endIndex));let y={id:_.id,params:{unitId:l,actions:[],textRanges:[{startOffset:h,endOffset:h,collapsed:!0}],debounce:!0}},b=new t.TextX,x=t.JSONX.getInstance();b.push(...t.BuildTextUtils.selection.delete([{...s,startOffset:h,endOffset:g+1,collapsed:!1}],p));let S=(0,t.getRichTextEditPath)(f,c);return y.params.actions=x.editOp(b.serialize(),S),!!a.syncExecuteCommand(y.id,y.params)}},b={id:`doc.command.update-text`,type:t.CommandType.COMMAND,handler:(e,n)=>{let{range:r,segmentId:i,updateBody:a,coverType:o,unitId:s,textRanges:c}=n,l=e.get(t.ICommandService),u=e.get(t.IUniverInstanceService).getCurrentUnitOfType(t.UniverInstanceType.UNIVER_DOC);if(u==null)return!1;let d={id:_.id,params:{unitId:s,actions:[],textRanges:c}},f=new t.TextX,p=t.JSONX.getInstance(),{startOffset:m,endOffset:h}=r;f.push({t:t.TextXActionType.RETAIN,len:m}),f.push({t:t.TextXActionType.RETAIN,body:a,len:h-m,coverType:o});let g=(0,t.getRichTextEditPath)(u,i);return d.params.actions=p.editOp(f.serialize(),g),!!l.syncExecuteCommand(d.id,d.params)}},x=function(e){return e[e.FIRST_PAGE_HEADER=0]=`FIRST_PAGE_HEADER`,e[e.FIRST_PAGE_FOOTER=1]=`FIRST_PAGE_FOOTER`,e[e.DEFAULT_HEADER=2]=`DEFAULT_HEADER`,e[e.DEFAULT_FOOTER=3]=`DEFAULT_FOOTER`,e[e.EVEN_PAGE_HEADER=4]=`EVEN_PAGE_HEADER`,e[e.EVEN_PAGE_FOOTER=5]=`EVEN_PAGE_FOOTER`,e}({});function S(){return{dataStream:`\r
2
+ `,textRuns:[{st:0,ed:0,ts:{fs:9}}],customBlocks:[],paragraphs:[{startIndex:0,paragraphId:(0,t.createParagraphId)(new Set),paragraphStyle:{spaceAbove:{v:0},lineSpacing:1.5,spaceBelow:{v:0}}}],sectionBreaks:[{sectionId:(0,t.createSectionId)(new Set),startIndex:1}]}}function C(e,n,r,i,a=`single`,o=[`documentStyle`]){let s=t.JSONX.getInstance(),c=e==null?(0,t.generateRandomId)(6):e,l=n===2||n===0||n===4,u=s.insertOp([l?`headers`:`footers`,c],{[l?`headerId`:`footerId`]:c,body:S()});i.push(u);let d=`defaultHeaderId`,f=`defaultFooterId`;switch(n){case 2:d=`defaultHeaderId`,f=`defaultFooterId`;break;case 3:d=`defaultFooterId`,f=`defaultHeaderId`;break;case 0:d=`firstPageHeaderId`,f=`firstPageFooterId`;break;case 1:d=`firstPageFooterId`,f=`firstPageHeaderId`;break;case 4:d=`evenPageHeaderId`,f=`evenPageFooterId`;break;case 5:d=`evenPageFooterId`,f=`evenPageHeaderId`;break;default:throw Error(`Unknown header footer type: ${n}`)}let p=[[d,c]];if(a===`pair`&&f!=null){let e=(0,t.generateRandomId)(6),n=s.insertOp([l?`footers`:`headers`,e],{[l?`footerId`:`headerId`]:e,body:S()});i.push(n),p.push([f,e])}for(let[e,t]of p)if(r[e]!=null){let n=s.replaceOp([...o,e],r[e],t);i.push(n)}else{let n=s.insertOp([...o,e],t);i.push(n)}return i}let w={id:`doc.command.create-header-footer`,type:t.CommandType.COMMAND,handler:(e,n)=>{var r,i,a;let o=e.get(t.ICommandService),s=e.get(t.IUniverInstanceService),{unitId:c,segmentId:l,createType:u,headerFooterProps:d,createMode:f=`single`,sectionId:p}=n,m=s.getUnit(c,t.UniverInstanceType.UNIVER_DOC);if(m==null)return!1;let{documentStyle:h,body:g}=m.getSnapshot();if(h.documentFlavor===t.DocumentFlavor.MODERN)return!1;let v=[],y=t.JSONX.getInstance(),b=p==null||(r=g==null||(i=g.sectionBreaks)==null?void 0:i.findIndex(e=>e.sectionId===p))==null?-1:r,x=b<0||g==null||(a=g.sectionBreaks)==null?void 0:a[b];if(p!=null&&!x)return!1;let S=x==null?h:x,w=p==null?[`documentStyle`]:[`body`,`sectionBreaks`,b];if(u!=null&&C(l,u,S,v,f,w),d!=null&&Object.keys(d).forEach(e=>{let t=d[e],n=S[e];if(t===n)return;let r=n===void 0?y.insertOp([...w,e],t):y.replaceOp([...w,e],n,t);v.push(r)}),v.length===0)return!1;let T={id:_.id,params:{unitId:c,actions:v.reduce((e,n)=>t.JSONX.compose(e,n),null),textRanges:[{startOffset:0,endOffset:0,collapsed:!0}],debounce:!0}};return((d==null?void 0:d.marginFooter)!=null||(d==null?void 0:d.marginHeader)!=null)&&(T.params.noNeedSetTextRange=!0),!!o.syncExecuteCommand(T.id,T.params)}},T={id:`doc.command.set-default-paragraph-style`,type:t.CommandType.COMMAND,handler:(e,n)=>{if(n==null)return!1;let r=e.get(t.ICommandService),i=e.get(t.IUniverInstanceService).getUnit(n.unitId,t.UniverInstanceType.UNIVER_DOC);if(i==null)return!1;let a=i.getSnapshot().documentStyle.defaultParagraphStyle,o=t.JSONX.getInstance(),s=[`documentStyle`,`defaultParagraphStyle`],c=[];if(n.defaultParagraphStyle==null)a!=null&&c.push(o.removeOp(s,a));else if(a==null){let e=Object.fromEntries(Object.entries(n.defaultParagraphStyle).filter(([,e])=>e!=null).map(([e,n])=>[e,t.Tools.deepClone(n)]));Object.keys(e).length>0&&c.push(o.insertOp(s,e))}else Object.entries(n.defaultParagraphStyle).forEach(([e,n])=>{let r=a[e],i=[...s,e];n==null?r!=null&&c.push(o.removeOp(i,r)):r==null?c.push(o.insertOp(i,t.Tools.deepClone(n))):c.push(o.replaceOp(i,r,t.Tools.deepClone(n)))});let l=c.reduce((e,n)=>t.JSONX.compose(e,n),null);if(c.length===0||t.JSONX.isNoop(l))return!1;let u={id:_.id,params:{unitId:n.unitId,actions:l,textRanges:null,noNeedSetTextRange:!0,debounce:!0,isEditing:!1}};return!!r.syncExecuteCommand(u.id,u.params)}};function E(e){var n;let r=new Map(((n=e.sectionBreaks)==null?[]:n).map(e=>[e.startIndex,e])),i=[],a=0,o=0;for(let n=0;n<e.dataStream.length;n++){let s=e.dataStream[n];if(s===t.DataStreamTreeTokenType.TABLE_CELL_START)a++;else if(s===t.DataStreamTreeTokenType.TABLE_CELL_END)a=Math.max(0,a-1);else if(s===t.DataStreamTreeTokenType.COLUMN_START)o++;else if(s===t.DataStreamTreeTokenType.COLUMN_END)o=Math.max(0,o-1);else if(s===t.DataStreamTreeTokenType.SECTION_BREAK&&a===0&&o===0){let e=r.get(n);e&&i.push(e)}}return i}let D={id:`doc.command.set-section-header-footer-link`,type:t.CommandType.COMMAND,handler:(e,n)=>{var r,i;if(!n)return!1;let a=e.get(t.IUniverInstanceService),o=e.get(t.ICommandService),s=a.getUnit(n.unitId,t.UniverInstanceType.UNIVER_DOC),c=s==null?void 0:s.getSnapshot();if(!s||!(c!=null&&c.body)||c.documentStyle.documentFlavor!==t.DocumentFlavor.TRADITIONAL)return!1;let l=E(c.body),u=l.findIndex(e=>e.sectionId===n.sectionId);if(u<=0)return!1;let d=(r=(i=c.body.sectionBreaks)==null?void 0:i.findIndex(e=>e.sectionId===n.sectionId))==null?-1:r;if(d<0)return!1;let f={snapshot:c,sections:l,sectionIndex:u,storageIndex:d,key:(0,t.getSectionHeaderFooterReferenceKey)(n.kind,n.variant)},p=n.linkedToPrevious?O(f,n.kind):k(f,n.kind,n.segmentId);if(!p)return!1;let m={id:_.id,params:{unitId:n.unitId,actions:p.reduce((e,n)=>t.JSONX.compose(e,n),null),textRanges:null,noNeedSetTextRange:!0,debounce:!0,isEditing:!1,trigger:D.id}};return!!o.syncExecuteCommand(m.id,m.params)}};function O(e,n){let{snapshot:r,sections:i,sectionIndex:a,storageIndex:o,key:s}=e,c=i[a],l=c[s];if(typeof l!=`string`||!l)return null;let u=t.JSONX.getInstance(),d=[u.removeOp([`body`,`sectionBreaks`,o,s],l)],f=n===`header`?[`defaultHeaderId`,`firstPageHeaderId`,`evenPageHeaderId`]:[`defaultFooterId`,`firstPageFooterId`,`evenPageFooterId`],p=f.some(e=>r.documentStyle[e]===l),m=i.some(e=>f.some(t=>!(e.sectionId===c.sectionId&&t===s)&&e[t]===l)),h=n===`header`?r.headers:r.footers;return!p&&!m&&h!=null&&h[l]&&d.push(u.removeOp([n===`header`?`headers`:`footers`,l],h[l])),d}function k(e,n,r){let{snapshot:i,sections:a,sectionIndex:o,storageIndex:s,key:c}=e,l=a[o][c];if(typeof l==`string`&&l)return null;let u=(0,t.resolveSectionHeaderFooterReference)(i.documentStyle,a,o-1,c).segmentId,d=r==null?(0,t.generateRandomId)(6):r,f=n===`header`?i.headers:i.footers;if(f!=null&&f[d])return null;let p=u?f==null?void 0:f[u]:void 0,m=n===`header`?`headerId`:`footerId`,h=p?{...t.Tools.deepClone(p),[m]:d}:{[m]:d,body:S()},g=t.JSONX.getInstance();return[g.insertOp([n===`header`?`headers`:`footers`,d],h),g.insertOp([`body`,`sectionBreaks`,s,c],d)]}let A={id:`doc.command.update-section`,type:t.CommandType.COMMAND,handler:(e,n)=>{if(!(n!=null&&n.updates.length)||n.updates.some(({sectionId:e,config:t})=>!e||Object.keys(t).length===0))return!1;let r=e.get(t.IUniverInstanceService),i=e.get(t.ICommandService),a=r.getUnit(n.unitId,t.UniverInstanceType.UNIVER_DOC);if(!a||a.getDocumentStyle().documentFlavor!==t.DocumentFlavor.TRADITIONAL)return!1;let o=a.getBody();if(!o)return!1;let s=new Map(n.updates.map(({sectionId:e,config:t})=>[e,t]));if(s.size!==n.updates.length)return!1;let c=new Set(s.keys()),l=E(o).filter(e=>c.has(e.sectionId)).sort((e,t)=>e.startIndex-t.startIndex);if(l.length!==c.size)return!1;let u=new t.MemoryCursor,d=new t.TextX;for(let e of l)d.push({t:t.TextXActionType.RETAIN,len:e.startIndex-u.cursor}),d.push({t:t.TextXActionType.RETAIN,len:1,coverType:t.UpdateDocsAttributeType.REPLACE,body:{dataStream:``,sectionBreaks:[{...t.Tools.deepClone(e),...t.Tools.deepClone(s.get(e.sectionId)),sectionId:e.sectionId,startIndex:0}]}}),u.moveCursorTo(e.startIndex+1);let f=t.JSONX.getInstance(),p={id:_.id,params:{unitId:n.unitId,actions:f.editOp(d.serialize(),(0,t.getRichTextEditPath)(a)),textRanges:null,noNeedSetTextRange:!0,debounce:!0,isEditing:!1,trigger:A.id}};return!!i.syncExecuteCommand(p.id,p.params)}},j={id:`doc.command.insert-section-break`,type:t.CommandType.COMMAND,handler:(e,n)=>{var r,i,a,o,s;if(!n)return!1;let c=N(e,n.unitId);if(!c||!n.sectionId||!Number.isInteger(n.offset))return!1;let{body:l,documentDataModel:u,commandService:d}=c;if(n.offset<0||n.offset>l.dataStream.length||(r=l.sectionBreaks)!=null&&r.some(e=>e.sectionId===n.sectionId)||(i=l.tables)!=null&&i.some(e=>(0,t.containsInteriorInsertionOffset)((0,t.getTableRangeInterval)(e),n.offset))||(a=l.columnGroups)!=null&&a.some(e=>(0,t.containsInteriorInsertionOffset)((0,t.getColumnGroupRangeInterval)(e),n.offset))||(o=l.blockRanges)!=null&&o.some(e=>(0,t.containsInteriorInsertionOffset)((0,t.getBlockRangeInterval)(e),n.offset)))return!1;let f=new t.TextX;return f.retain(n.offset),f.insert(1,{dataStream:t.DataStreamTreeTokenType.SECTION_BREAK,sectionBreaks:[{...t.Tools.deepClone((s=n.config)==null?{}:s),sectionId:n.sectionId,startIndex:0}]}),P(d,u,f,j.id)}},M={id:`doc.command.delete-section-break`,type:t.CommandType.COMMAND,handler:(e,n)=>{if(!n)return!1;let r=N(e,n.unitId);if(!r||!n.sectionId)return!1;let i=E(r.body);if(i.length<=1)return!1;let a=i.find(e=>e.sectionId===n.sectionId);if(!a)return!1;let o=new t.TextX;return o.retain(a.startIndex),o.delete(1),P(r.commandService,r.documentDataModel,o,M.id)}};function N(e,n){if(!n)return null;let r=e.get(t.IUniverInstanceService).getUnit(n,t.UniverInstanceType.UNIVER_DOC),i=r==null?void 0:r.getBody();return!r||!i||r.getDocumentStyle().documentFlavor!==t.DocumentFlavor.TRADITIONAL?null:{body:i,documentDataModel:r,commandService:e.get(t.ICommandService)}}function P(e,n,r,i){let a=t.JSONX.getInstance().editOp(r.serialize(),(0,t.getRichTextEditPath)(n));return!!e.syncExecuteCommand(_.id,{unitId:n.getUnitId(),actions:a,textRanges:null,noNeedSetTextRange:!0,debounce:!0,isEditing:!1,trigger:i})}let F=`UniverEmbedDocsCustomBlock`,ee={width:720,height:360},te={width:960,height:480},ne={width:720,height:405};function re(e){return H(e.unitId,e.segmentId,I(e))}function ie(e){return H(e.unitId,e.segmentId,L(e))}function I(e){let n=new t.TextX;return e.startIndex>0&&n.push({t:t.TextXActionType.RETAIN,len:e.startIndex}),n.push({t:t.TextXActionType.INSERT,body:{dataStream:`\b`,customBlocks:[{startIndex:0,blockId:e.blockId}]},len:1}),W([U(n,e.segmentId),se(e)])}function L(e){let n=new t.TextX;return e.startIndex>0&&n.push({t:t.TextXActionType.RETAIN,len:e.startIndex}),n.push({t:t.TextXActionType.DELETE,len:1}),W([U(n,e.segmentId),ce(e)])}function R(e){var n;let r=z(e.childType),i=e.interactionMode===`inline`;return{unitId:e.unitId,subUnitId:e.unitId,drawingId:e.blockId,drawingType:t.DrawingTypeEnum.DRAWING_DOM,componentKey:(n=e.componentKey)==null?F:n,data:B(e),title:e.blockId,description:`Univer embedded unit custom block`,layoutType:i?t.PositionedObjectLayoutType.INLINE:t.PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM,allowTransform:!1,docTransform:{size:{width:r.width,height:r.height},positionH:{relativeFrom:i?t.ObjectRelativeFromH.PAGE:t.ObjectRelativeFromH.COLUMN,...i?{posOffset:0}:{align:t.AlignTypeH.LEFT}},positionV:{relativeFrom:i?t.ObjectRelativeFromV.PAGE:t.ObjectRelativeFromV.PARAGRAPH,posOffset:0},angle:0},transform:{left:0,top:0,width:r.width,height:r.height}}}function z(e){return e===t.UniverInstanceType.UNIVER_SHEET||e===t.UniverInstanceType.UNIVER_BASE?te:e===t.UniverInstanceType.UNIVER_SLIDE?ne:ee}function ae(e){return e===t.UniverInstanceType.UNIVER_SHEET||e===t.UniverInstanceType.UNIVER_BASE}function B(e){var t,n;return{version:1,embedId:(t=e.embedId)==null?e.blockId:t,hostUnitId:e.unitId,hostAnchorId:e.blockId,childUnitId:e.childUnitId,childType:e.childType,interactionMode:(n=e.interactionMode)==null?`block`:n}}function V(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.version===1&&typeof t.embedId==`string`&&typeof t.hostAnchorId==`string`}function oe(e){let t=e&&typeof e==`object`?e.data:void 0;return V(t)?t.interactionMode===`inline`:!0}function H(e,t,n){return{id:_.id,params:{unitId:e,segmentId:t,actions:n,textRanges:[],isEditing:!1,noNeedSetTextRange:!0}}}function U(e,n){let r=t.JSONX.getInstance().editOp(e.serialize(),n?[`headers`,n,`body`]:[`body`]);return r==null?[]:r}function se(e){var n,r,i;if(e.segmentId)return[];let a=t.JSONX.getInstance(),o=R(e);return W([(n=a.insertOp([`drawings`,e.blockId],o))==null?[]:n,(r=a.insertOp([`drawingsOrder`,(i=e.drawingOrderIndex)==null?0:i],e.blockId))==null?[]:r])}function ce(e){var n,r,i;if(e.segmentId)return[];let a=t.JSONX.getInstance(),o=R(e);return W([(n=a.removeOp([`drawings`,e.blockId],o))==null?[]:n,(r=a.removeOp([`drawingsOrder`,(i=e.drawingOrderIndex)==null?0:i],e.blockId))==null?[]:r])}function W(e){return e.reduce((e,n)=>{var r;return!n||t.JSONX.isNoop(n)||n.length===0?e:!e||t.JSONX.isNoop(e)||e.length===0?n:(r=t.JSONX.compose(e,n))==null?[]:r},[])}var le=`@univerjs/docs`,ue=`1.0.0-alpha.4`;let de={id:`doc.mutation.rename-doc`,type:t.CommandType.MUTATION,handler:(e,n)=>{let r=e.get(t.IUniverInstanceService).getUnit(n.unitId,t.UniverInstanceType.UNIVER_DOC);return r?(r.setName(n.name),!0):!1}},G={},K=class extends t.Disposable{constructor(e,t,n){super(),this._commandService=e,this._textSelectionManagerService=t,this._univerInstanceService=n,this._initSelectionChange()}_transformCustomRange(e,n){var r;let{startOffset:i,endOffset:a,collapsed:o}=n,s=(r=e.getCustomRanges())==null?void 0:r.filter(e=>!e.wholeEntity||i<=e.startIndex&&a>e.endIndex?!1:o?e.startIndex<i&&e.endIndex>=a:t.BuildTextUtils.range.isIntersects(i,a-1,e.startIndex,e.endIndex));if(s!=null&&s.length){let e=i,t=a;return s.forEach(n=>{e=Math.min(n.startIndex,e),t=Math.max(n.endIndex+1,t)}),{...n,startOffset:e,endOffset:t,collapsed:e===t}}return n}_initSelectionChange(){this.disposeWithMe(this._commandService.onCommandExecuted(e=>{if(e.id===i.id){let{unitId:t,ranges:n,isEditing:r}=e.params,i=this._univerInstanceService.getUnit(t);if(!i)return;let a=n.map(e=>this._transformCustomRange(i,e));a.some((e,t)=>n[t]!==e)&&this._textSelectionManagerService.replaceTextRanges(a,r)}}))}};K=u([l(0,t.ICommandService),l(1,(0,t.Inject)(d)),l(2,t.IUniverInstanceService)],K);var q=class extends t.Disposable{constructor(...e){super(...e),c(this,`_validators`,[]),c(this,`_transformers`,[])}registerValidator(e){return this._validators.push(e),this.disposeWithMe((0,t.toDisposable)(()=>(0,t.remove)(this._validators,e)))}registerTransformer(e){return this._transformers.push(e),this.disposeWithMe((0,t.toDisposable)(()=>(0,t.remove)(this._transformers,e)))}canMoveBlock(e){return this._validators.every(t=>t(e))}transformMoveResult(e){return this._transformers.reduce((t,n)=>n({...e,result:t}),e.result)}},J=class extends t.Disposable{constructor(...e){super(...e),c(this,`_range`,null)}setInsertRange(e){this._range=e}consumeInsertRange(e){if(!this._range||e&&this._range.unitId!==e)return null;let t=this._range;return this._range=null,t}clearInsertRange(){this._range=null}};let Y=(0,t.createIdentifier)(`doc.state-change-interceptor-service`),X=class extends t.RxDisposable{constructor(e,t,n,i,a){super(),this._undoRedoService=e,this._commandService=t,this._univerInstanceService=n,this._docStateEmitService=i,this._docStateChangeInterceptorService=a,c(this,`_docStateChange$`,new r.BehaviorSubject(null)),c(this,`docStateChange$`,this._docStateChange$.asObservable()),c(this,`_historyStateCache`,new Map),c(this,`_changeStateCache`,new Map),c(this,`_historyTimer`,null),c(this,`_changeStateCacheTimer`,null),this._initialize(),this._listenDocStateChange()}getStateCache(e){var t,n;return{history:(t=this._historyStateCache.get(e))==null?[]:t,collaboration:(n=this._changeStateCache.get(e))==null?[]:n}}setStateCache(e,t){this._historyStateCache.set(e,t.history),this._changeStateCache.set(e,t.collaboration)}_setChangeState(e){this._cacheChangeState(e,`history`),this._cacheChangeState(e,`collaboration`)}_initialize(){this.disposeWithMe(this._commandService.beforeCommandExecuted(e=>{if(e.id===t.UndoCommandId||e.id===t.RedoCommandId){let e=this._univerInstanceService.getCurrentUnitOfType(t.UniverInstanceType.UNIVER_DOC);if(e==null)return;let n=e.getUnitId();this._pushHistory(n),this._emitChangeState(n)}}))}_listenDocStateChange(){this._docStateEmitService.docStateChangeParams$.pipe((0,r.takeUntil)(this.dispose$)).subscribe(e=>{var t,n;if(e==null)return;let r=(t=(n=this._docStateChangeInterceptorService)==null?void 0:n.transformChangeStateInfo(e))==null?e:t;if(r==null||r.isSync)return;let{isCompositionEnd:i,isSync:a,syncer:o,...s}=r;this._setChangeState(s)})}_cacheChangeState(e,n=`history`){let{trigger:r,unitId:i,noHistory:a,debounce:o=!1}=e;if(a||n===`history`&&r==null||n===`history`&&(r===t.RedoCommandId||r===t.UndoCommandId))return;let s=n===`history`?this._historyStateCache:this._changeStateCache,c=n===`history`?this._pushHistory.bind(this):this._emitChangeState.bind(this);if(s.has(i)){let t=s.get(i);t==null||t.push(e)}else s.set(i,[e]);o?n===`history`?(this._historyTimer&&clearTimeout(this._historyTimer),this._historyTimer=setTimeout(()=>{c(i)},300)):(this._changeStateCacheTimer&&clearTimeout(this._changeStateCacheTimer),this._changeStateCacheTimer=setTimeout(()=>{c(i)},300)):c(i)}_pushHistory(e){let n=this._undoRedoService,r=this._historyStateCache.get(e);if(n==null||!Array.isArray(r)||r.length===0)return;let i=r.length,a=r[0].commandId,o=r[0],s=r[i-1],c={unitId:e,actions:r.reduce((e,n)=>t.JSONX.compose(e,n.redoState.actions),null),textRanges:s.redoState.textRanges},l={unitId:e,actions:r.reverse().reduce((e,n)=>t.JSONX.compose(e,n.undoState.actions),null),textRanges:o.undoState.textRanges};n.pushUndoRedo({unitID:e,undoMutations:[{id:a,params:l}],redoMutations:[{id:a,params:c}]}),r.length=0}_emitChangeState(e){let n=this._changeStateCache.get(e);if(!Array.isArray(n)||n.length===0)return;let r=n.length,{commandId:i,trigger:a,segmentId:o,noHistory:s,debounce:c}=n[0],l=n[0],u=n[r-1],d={commandId:i,unitId:e,trigger:a,redoState:{unitId:e,actions:n.reduce((e,n)=>t.JSONX.compose(e,n.redoState.actions),null),textRanges:u.redoState.textRanges},undoState:{unitId:e,actions:n.reverse().reduce((e,n)=>t.JSONX.compose(e,n.undoState.actions),null),textRanges:l.undoState.textRanges},segmentId:o,noHistory:s,debounce:c};n.length=0,this._docStateChange$.next(d)}};X=u([l(0,(0,t.Optional)(t.IUndoRedoService)),l(1,t.ICommandService),l(2,t.IUniverInstanceService),l(3,(0,t.Inject)(p)),l(4,(0,t.Optional)(Y))],X);let Z=class extends t.Plugin{constructor(e=G,n,r){super(),this._config=e,this._injector=n,this._configService=r;let{...i}=(0,t.merge)({},G,this._config);this._configService.setConfig(`docs.config`,i)}onStarting(){this._initializeDependencies(),this._initializeCommands()}_initializeCommands(){[v,y,b,w,T,D,A,j,M,_,de,i].forEach(e=>{this._injector.get(t.ICommandService).registerCommand(e)})}_initializeDependencies(){[[d],[p],[X],[q],[J],[K]].forEach(e=>this._injector.add(e))}onReady(){this._injector.get(X),this._injector.get(K)}};c(Z,`pluginName`,`DOCS_PLUGIN`),c(Z,`packageName`,le),c(Z,`version`,ue),Z=u([l(1,(0,t.Inject)(t.Injector)),l(2,t.IConfigService)],Z);let Q={CUSTOM_RANGE:(0,t.createInterceptorKey)(`CUSTOM_RANGE`),CUSTOM_DECORATION:(0,t.createInterceptorKey)(`CUSTOM_DECORATION`)},$=class extends t.Disposable{constructor(e,n){super(),this._context=e,this._docSkeletonManagerService=n,c(this,`_interceptorsByName`,new Map);let r=this._docSkeletonManagerService.getViewModel(),i=r.getDataModel().getUnitId();if(i===t.DOCS_NORMAL_EDITOR_UNIT_ID_KEY||i===t.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY)return;this.disposeWithMe(this.interceptDocumentViewModel(r)),this.disposeWithMe(this.intercept(Q.CUSTOM_RANGE,{priority:-1,handler:(e,t,n)=>n(e)}));let a=new t.DisposableCollection;r.segmentViewModels$.subscribe(e=>{a.dispose(),a=new t.DisposableCollection,e.forEach(e=>{a.add(this.interceptDocumentViewModel(e))})}),this.disposeWithMe(a)}intercept(e,n){let r=e;this._interceptorsByName.has(r)||this._interceptorsByName.set(r,[]);let i=this._interceptorsByName.get(r);return i.push(n),this._interceptorsByName.set(r,i.sort((e,t)=>{var n,r;return((n=t.priority)==null?0:n)-((r=e.priority)==null?0:r)})),this.disposeWithMe((0,t.toDisposable)(()=>(0,t.remove)(this._interceptorsByName.get(r),n)))}fetchThroughInterceptors(e){let n=e;return(0,t.composeInterceptors)(this._interceptorsByName.get(n)||[])}interceptDocumentViewModel(e){let n=new t.DisposableCollection;return n.add(e.registerCustomRangeInterceptor({getCustomRange:t=>{var n;return this.fetchThroughInterceptors(Q.CUSTOM_RANGE)(e.getCustomRangeRaw(t),{index:t,unitId:e.getDataModel().getUnitId(),customRanges:(n=e.getDataModel().getCustomRanges())==null?[]:n})},getCustomDecoration:t=>{var n;return this.fetchThroughInterceptors(Q.CUSTOM_DECORATION)(e.getCustomDecorationRaw(t),{index:t,unitId:e.getDataModel().getUnitId(),customDecorations:(n=e.getDataModel().getCustomDecorations())==null?[]:n})}})),n}};$=u([l(1,(0,t.Inject)(f))],$);function fe(e,n,r){let{unitId:i,segmentId:a}=n,o=e.get(t.IUniverInstanceService).getUnit(i);if(!o)return!1;let s={id:_.id,params:{unitId:n.unitId,actions:[],textRanges:void 0}},c=t.JSONX.getInstance(),l=t.BuildTextUtils.customRange.add({...n,body:r});if(!l)return!1;let u=(0,t.getRichTextEditPath)(o,a);return s.params.actions=c.editOp(l.serialize(),u),s}function pe(e,n){var r,i;let{rangeId:a,rangeType:o,wholeEntity:s,properties:c,unitId:l,selections:u}=n,f=e.get(d),p=e.get(t.IUniverInstanceService),m=u==null?f.getTextRanges({unitId:l,subUnitId:l}):u,h=m==null||(r=m[0])==null?void 0:r.segmentId;if(!(m!=null&&m.length))return!1;let g=p.getUnit(l,t.UniverInstanceType.UNIVER_DOC);if(!g)return!1;let v=(i=g.getSelfOrHeaderFooterModel(h))==null?void 0:i.getBody();if(!v)return!1;let y=t.BuildTextUtils.customRange.add({ranges:m,rangeId:a,rangeType:o,segmentId:h,wholeEntity:s,properties:c,body:v});if(!y)return!1;let b=t.JSONX.getInstance(),x={id:_.id,params:{unitId:l,actions:[],textRanges:y.selections,segmentId:h},textX:y},S=(0,t.getRichTextEditPath)(g,h);return x.params.actions=b.editOp(y.serialize(),S),x}function me(e,n){let{unitId:r,segmentId:i,insert:a}=n,o=e.get(t.IUniverInstanceService).getUnit(r);if(!o)return!1;let s={id:_.id,params:{unitId:n.unitId,actions:[],textRanges:void 0,segmentId:i}},c=t.JSONX.getInstance(),l=t.BuildTextUtils.customRange.delete({documentDataModel:o,rangeId:n.rangeId,insert:a,segmentId:i});if(!l)return!1;let u=(0,t.getRichTextEditPath)(o,i);return s.params.actions=c.editOp(l.serialize(),u),s.params.textRanges=l.selections,s}function he(e,n,r,i=[]){let a=[],o=new Set(i);for(let n=0,r=e.length;n<r;n++)e[n]===t.DataStreamTreeTokenType.PARAGRAPH&&a.push({startIndex:n,paragraphId:(0,t.createParagraphId)(o)});for(let e of a)n!=null&&n.bullet&&(e.bullet=t.Tools.deepClone(n.bullet)),n!=null&&n.paragraphStyle&&(e.paragraphStyle=t.Tools.deepClone(n.paragraphStyle),delete e.paragraphStyle.borderBottom,n.paragraphStyle.headingId&&(e.paragraphStyle.headingId=(0,t.generateRandomId)(6))),r&&(e.paragraphStyle!=null||(e.paragraphStyle={}),e.paragraphStyle.borderBottom=t.Tools.deepClone(r));return a}function ge(e,n){var r,i,a,o;let{unitId:s,body:c,doc:l}=n,u=l;if(u||(u=e.get(t.IUniverInstanceService).getUnit(s)),!u)return!1;let f=(r=n.selection)==null?void 0:r.segmentId,p=(i=u.getSelfOrHeaderFooterModel(f))==null?void 0:i.getBody();if(!p)return!1;let m=e.get(d),h=(a=n.selection)==null?m.getActiveTextRange():a;if(!h||!p)return!1;let g=(o=n.textRanges)==null?[{startOffset:h.startOffset+c.dataStream.length,endOffset:h.startOffset+c.dataStream.length,collapsed:!0,segmentId:f}]:o,v=t.BuildTextUtils.selection.replace({selection:h,body:c,doc:u});if(!v)return!1;let y={id:_.id,params:{unitId:s,actions:[],textRanges:g,debounce:!0,segmentId:f},textX:v},b=t.JSONX.getInstance();return y.params.actions=b.editOp(v.serialize()),y}function _e(e,n,r,i,a){var o,s,c,l,u,d,f,p;if(r<=1)return[];let m=Math.max(0,i),h=(o=(s=n==null||(c=n.pageSize)==null?void 0:c.width)==null?e==null||(l=e.pageSize)==null?void 0:l.width:s)==null?t.PAGE_SIZE[t.PaperType.A4].width:o,g=Math.max(0,h-((u=(d=n==null?void 0:n.marginLeft)==null?e==null?void 0:e.marginLeft:d)==null?72:u)-((f=(p=n==null?void 0:n.marginRight)==null?e==null?void 0:e.marginRight:p)==null?72:f)),_=Math.max(0,g-m*(r-1));return(a==null?Array.from({length:r},()=>_/r):a).map((e,t)=>({width:Math.max(0,e),paddingEnd:t===r-1?0:m}))}function ve(e,n,r){var i,a;return{size:{width:e,height:n},positionH:{relativeFrom:t.ObjectRelativeFromH.PAGE,posOffset:(i=r==null?void 0:r.left)==null?0:i},positionV:{relativeFrom:t.ObjectRelativeFromV.PARAGRAPH,posOffset:(a=r==null?void 0:r.top)==null?0:a},angle:0}}function ye(e){return{left:e.positionH.posOffset,top:e.positionV.posOffset,width:e.size.width,height:e.size.height,flipX:e.flipX,flipY:e.flipY}}function be(e,n=0,r=0){return{size:{width:e.width,height:e.height},positionH:{relativeFrom:t.ObjectRelativeFromH.MARGIN,posOffset:(e.left||0)-n},positionV:{relativeFrom:t.ObjectRelativeFromV.PAGE,posOffset:(e.top||0)-r},angle:e.angle||0,flipX:e.flipX,flipY:e.flipY}}function xe(e,t){try{return e.get(J).consumeInsertRange(t)}catch{return null}}function Se(e,n){var r;let i=n==null?(r=e.get(t.IUniverInstanceService).getCurrentUnitOfType(t.UniverInstanceType.UNIVER_DOC))==null?void 0:r.getUnitId():n;if(!i)return null;let a=xe(e,i);return a?{...a,collapsed:(a==null?void 0:a.startOffset)===(a==null?void 0:a.endOffset)}:null}function Ce(e){return!!(e!=null&&e.segmentId)}function we(e){var t,n,r;let i=(t=e.endOffset)==null?e.startOffset:t;return{...e,endOffset:i,collapsed:(n=e.collapsed)==null?e.startOffset===i:n,segmentId:(r=e.segmentId)==null?``:r}}e.CreateHeaderFooterCommand=w,e.DOC_INTERCEPTOR_POINT=Q,e.DeleteDocumentSectionBreakCommand=M,e.DeleteTextCommand=y,e.DocBlockMoveValidatorService=q,e.DocContentInsertService=J,Object.defineProperty(e,"DocInterceptorService",{enumerable:!0,get:function(){return $}}),Object.defineProperty(e,"DocSelectionManagerService",{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,"DocSkeletonManagerService",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"DocStateChangeManagerService",{enumerable:!0,get:function(){return X}}),e.DocStateEmitService=p,e.EMBED_DOCS_CUSTOM_BLOCK_DEFAULT_COMPONENT_KEY=F,e.HeaderFooterType=x,e.IDocStateChangeInterceptorService=Y,e.InsertDocumentSectionBreakCommand=j,e.InsertTextCommand=v,e.RichTextEditingMutation=_,e.SetDocumentDefaultParagraphStyleCommand=T,e.SetSectionHeaderFooterLinkCommand=D,e.SetTextSelectionsOperation=i,Object.defineProperty(e,"UniverDocsPlugin",{enumerable:!0,get:function(){return Z}}),e.UpdateDocumentSectionCommand=A,e.UpdateTextCommand=b,e.addCustomRangeBySelectionFactory=pe,e.addCustomRangeFactory=fe,e.buildDocTransform=ve,e.consumeContentInsertRange=xe,e.createDocsCustomBlockDrawing=R,e.createDocsCustomBlockInsertMutation=re,e.createDocsCustomBlockRemoveMutation=ie,e.createEmbedDocsCustomBlockData=B,e.createInsertCustomBlockActions=I,e.createRemoveCustomBlockActions=L,e.createSectionColumnProperties=_e,e.deleteCustomRangeFactory=me,e.docDrawingPositionToTransform=ye,e.generateParagraphs=he,e.getContentInsertRange=Se,e.getTopLevelSectionBreaks=E,e.isEmbedDocsCustomBlockData=V,e.isHeaderFooterSelection=Ce,e.isSheetLikeDocsCustomBlockChildType=ae,e.normalizeTextRange=we,e.replaceSelectionFactory=ge,e.resolveDocsCustomBlockSize=z,e.shouldUseInlineTextSelectionForDocsCustomBlockDrawing=oe,e.transformToDocDrawingPosition=be});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@univerjs/docs",
3
- "version": "1.0.0-alpha.2",
3
+ "version": "1.0.0-alpha.4",
4
4
  "private": false,
5
5
  "description": "Core document model and rich-text operations for Univer Docs.",
6
6
  "author": "DreamNum Co., Ltd. <developer@univer.ai>",
@@ -62,14 +62,14 @@
62
62
  "rxjs": ">=7.0.0"
63
63
  },
64
64
  "dependencies": {
65
- "@univerjs/engine-render": "1.0.0-alpha.2",
66
- "@univerjs/core": "1.0.0-alpha.2"
65
+ "@univerjs/core": "1.0.0-alpha.4",
66
+ "@univerjs/engine-render": "1.0.0-alpha.4"
67
67
  },
68
68
  "devDependencies": {
69
69
  "rxjs": "^7.8.2",
70
70
  "typescript": "^6.0.3",
71
- "vitest": "^4.1.9",
72
- "@univerjs-infra/shared": "1.0.0-alpha.2"
71
+ "vitest": "^4.1.10",
72
+ "@univerjs-infra/shared": "1.0.0-alpha.4"
73
73
  },
74
74
  "scripts": {
75
75
  "test": "vitest run",