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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,15 +13,15 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
- import type { DocumentDataModel, IDocumentData } from '@univerjs/core';
16
+ import type { DocumentDataModel, IDocumentBody, IDocumentData } from '@univerjs/core';
17
+ import type { IFDocumentTextRange } from './utils';
17
18
  import { ICommandService, Injector, IResourceLoaderService, IUniverInstanceService } from '@univerjs/core';
18
19
  import { FBaseInitialable } from '@univerjs/core/facade';
19
- import { FDocBody } from './f-doc-body';
20
- export interface IDocumentInsertTextFacadeOptions {
21
- startOffset?: number;
22
- endOffset?: number;
20
+ import { FDocumentParagraph } from './f-document-paragraph';
21
+ export interface IFDocumentParagraphQuery {
22
+ text?: string;
23
+ paragraphId?: string;
23
24
  segmentId?: string;
24
- cursorOffset?: number;
25
25
  }
26
26
  /**
27
27
  * Facade API object bounded to a document. It provides a set of methods to interact with the document.
@@ -34,39 +34,37 @@ export declare class FDocument extends FBaseInitialable {
34
34
  protected readonly _resourceLoaderService: IResourceLoaderService;
35
35
  private readonly _commandService;
36
36
  readonly id: string;
37
- private readonly _docElementRegistry;
38
37
  constructor(_documentDataModel: DocumentDataModel, _injector: Injector, _univerInstanceService: IUniverInstanceService, _resourceLoaderService: IResourceLoaderService, _commandService: ICommandService);
39
38
  /**
40
39
  * Get the document data model of the document.
40
+ * @param {string} segmentId The segment id used to get the header/footer data model. Defaults to an empty string for the document data model of the document.
41
41
  * @returns {DocumentDataModel} The document data model.
42
42
  * @example
43
43
  * ```typescript
44
44
  * const fDocument = univerAPI.getActiveDocument();
45
- * const documentDataModel = fDocument.getDocumentDataModel();
46
- * console.log(documentDataModel);
45
+ * console.log(fDocument.getDocumentDataModel());
46
+ *
47
+ * const headerSegmentId = fDocument.ensurePageHeader();
48
+ * console.log(fDocument.getDocumentDataModel(headerSegmentId));
47
49
  * ```
48
50
  */
49
- getDocumentDataModel(): DocumentDataModel;
51
+ getDocumentDataModel(segmentId?: string): DocumentDataModel;
50
52
  /**
51
- * Get the document body facade.
52
- *
53
- * The returned body facade provides synchronous Google Docs-like element APIs
54
- * for reading and editing top-level document body elements. Paragraph elements
55
- * use their persisted `paragraphId` values. Persisted elements, such as tables
56
- * and custom blocks, use their existing ids.
57
- *
58
- * @returns {FDocBody} The document body API instance.
53
+ * Get the document body or header/footer body by the segment id.
54
+ * The main body has an empty segment id.
55
+ * The header and footer body have their respective segment ids.
56
+ * @param {string} segmentId The segment id of the body. Defaults to an empty string for the main body.
57
+ * @returns {IDocumentBody} The document body.
59
58
  * @example
60
59
  * ```typescript
61
- * const doc = univerAPI.getActiveDocument();
62
- * if (!doc) throw new Error('No active document');
60
+ * const fDocument = univerAPI.getActiveDocument();
61
+ * console.log(fDocument.getBody()); // Get the main body
63
62
  *
64
- * const body = doc.getBody();
65
- * const paragraph = body.getChild(0).asParagraph();
66
- * paragraph.appendText(' updated');
63
+ * const footerSegmentId = fDocument.ensurePageFooter();
64
+ * console.log(fDocument.getBody(footerSegmentId)); // Get the footer body
67
65
  * ```
68
66
  */
69
- getBody(): FDocBody;
67
+ getBody(segmentId?: string): IDocumentBody;
70
68
  dispose(): void;
71
69
  /**
72
70
  * Get the document id.
@@ -74,8 +72,7 @@ export declare class FDocument extends FBaseInitialable {
74
72
  * @example
75
73
  * ```typescript
76
74
  * const fDocument = univerAPI.getActiveDocument();
77
- * const unitId = fDocument.getId();
78
- * console.log(unitId);
75
+ * console.log(fDocument.getId());
79
76
  * ```
80
77
  */
81
78
  getId(): string;
@@ -85,11 +82,20 @@ export declare class FDocument extends FBaseInitialable {
85
82
  * @example
86
83
  * ```typescript
87
84
  * const fDocument = univerAPI.getActiveDocument();
88
- * const name = fDocument.getName();
89
- * console.log(name);
85
+ * console.log(fDocument.getName());
90
86
  * ```
91
87
  */
92
88
  getName(): string;
89
+ /**
90
+ * Whether the document is a modern document or not.
91
+ * @returns {boolean} `true` if the document is a modern document, or `false` if it is not.
92
+ * @example
93
+ * ```typescript
94
+ * const fDocument = univerAPI.getActiveDocument();
95
+ * console.log(fDocument.isModern());
96
+ * ```
97
+ */
98
+ isModern(): boolean;
93
99
  /**
94
100
  * Save the document snapshot data, including the document content and resource data, etc.
95
101
  * @returns {IDocumentData} The document snapshot data.
@@ -124,82 +130,165 @@ export declare class FDocument extends FBaseInitialable {
124
130
  */
125
131
  redo(): boolean;
126
132
  /**
127
- * Adds the specified text to the end of this text region.
128
- * @param {string} text - The text to be added to the end of this text region.
129
- * @return {boolean} `true` if the text was successfully appended, or `false` if it failed.
133
+ * Ensure the page header segment exists and return its segment id.
134
+ * @param {number} pageIndex The zero-based page index. Defaults to the first page.
135
+ * @returns {string} The header segment id.
130
136
  * @example
131
- * ```typescript
137
+ * ```ts
132
138
  * const fDocument = univerAPI.getActiveDocument();
133
- * const success = fDocument.appendText('Hello, world!');
134
- * console.log(success);
139
+ * const headerSegmentId = fDocument.ensurePageHeader();
140
+ * fDocument.insertText(0, 'Header text', headerSegmentId);
141
+ * ```
142
+ */
143
+ ensurePageHeader(pageIndex?: number): string;
144
+ /**
145
+ * Ensure the page footer segment exists and return its segment id.
146
+ * @param {number} pageIndex The zero-based page index. Defaults to the first page.
147
+ * @returns {string} The footer segment id.
148
+ * @example
149
+ * ```ts
150
+ * const fDocument = univerAPI.getActiveDocument();
151
+ * const footerSegmentId = fDocument.ensurePageFooter();
152
+ * fDocument.insertText(0, 'Footer text', footerSegmentId);
135
153
  * ```
136
154
  */
137
- appendText(text: string): boolean;
155
+ ensurePageFooter(pageIndex?: number): string;
138
156
  /**
139
- * Inserts text at the provided document range. Defaults to appending before the final section break.
140
- * @param {string} text - The text to insert.
141
- * @param {IDocumentInsertTextFacadeOptions} options - Optional target range, segment id, and cursor offset.
142
- * @returns {boolean} `true` if the text was successfully inserted, or `false` if it failed.
157
+ * Insert plain text at a document body offset.
158
+ * @param {number} index The zero-based insertion offset.
159
+ * @param {string} text The plain text to insert.
160
+ * @param {string} segmentId The segment id of the body. Defaults to an empty string for the main body.
161
+ * @returns {boolean} `true` if the edit was applied.
143
162
  * @example
163
+ * ```ts
164
+ * const fDocument = univerAPI.getActiveDocument();
165
+ * fDocument.insertText(0, 'Hello ');
144
166
  *
145
- * // Insert text at a specific range in the document body
146
- * ```typescript
167
+ * const headerSegmentId = fDocument.ensurePageHeader();
168
+ * fDocument.insertText(0, 'Header text', headerSegmentId);
169
+ * ```
170
+ */
171
+ insertText(index: number, text: string, segmentId?: string): boolean;
172
+ /**
173
+ * Get all paragraphs in the document body or header/footer body by the segment id.
174
+ * @param {string} segmentId The segment id of the body. Defaults to an empty string for the main body.
175
+ * @returns {FDocumentParagraph[]} An array of paragraph facade instances.
176
+ * @example
177
+ * ```ts
147
178
  * const fDocument = univerAPI.getActiveDocument();
148
- * const success = fDocument.insertText('Hello, world!', {
149
- * startOffset: 5,
150
- * endOffset: 5,
151
- * segmentId: '',
152
- * cursorOffset: 13,
153
- * });
154
- * console.log(success);
179
+ * const paragraphs = fDocument.getParagraphs();
180
+ * console.log(paragraphs);
181
+ *
182
+ * const headerSegmentId = fDocument.ensurePageHeader();
183
+ * const headerParagraphs = fDocument.getParagraphs(headerSegmentId);
184
+ * console.log(headerParagraphs);
155
185
  * ```
186
+ */
187
+ getParagraphs(segmentId?: string): FDocumentParagraph[];
188
+ /**
189
+ * Get a paragraph by its paragraph id and segment id.
190
+ * @param {string} paragraphId The paragraph id.
191
+ * @param {string} segmentId The segment id of the body. Defaults to an empty string for the main body.
192
+ * @returns {FDocumentParagraph | null} The paragraph facade instance, or `null` if the paragraph is not found.
193
+ * @example
194
+ * ```ts
195
+ * const fDocument = univerAPI.getActiveDocument();
196
+ * const paragraph = fDocument.getParagraph('paragraph-01');
197
+ * console.log(paragraph);
156
198
  *
157
- * // Insert text at the beginning of a header or footer segment
158
- * ```typescript
199
+ * const headerSegmentId = fDocument.ensurePageHeader();
200
+ * const headerParagraph = fDocument.getParagraph('header-paragraph-01', headerSegmentId);
201
+ * console.log(headerParagraph);
202
+ * ```
203
+ */
204
+ getParagraph(paragraphId: string, segmentId?: string): FDocumentParagraph | null;
205
+ /**
206
+ * Find a paragraph by its text content and segment id.
207
+ * @param {string} text The text content to search for.
208
+ * @param {string} segmentId The segment id of the body. Defaults to an empty string for the main body.
209
+ * @returns {FDocumentParagraph | null} The paragraph facade instance, or `null` if the paragraph is not found.
210
+ * @example
211
+ * ```ts
159
212
  * const fDocument = univerAPI.getActiveDocument();
160
- * const snapshot = fDocument.save();
161
- * const { headers, footers } = snapshot;
213
+ * const paragraph = fDocument.findParagraphByText('Hello');
214
+ * console.log(paragraph);
162
215
  *
163
- * if (headers) {
164
- * for (const headerId in headers) {
165
- * if (headerId === 'target-header-id') {
166
- * fDocument.insertText('Hello, header!', {
167
- * startOffset: 0,
168
- * endOffset: 0,
169
- * segmentId: headerId,
170
- * });
171
- * }
172
- * }
173
- * }
216
+ * const footerSegmentId = fDocument.ensurePageFooter();
217
+ * const footerParagraph = fDocument.findParagraphByText('Page', footerSegmentId);
218
+ * console.log(footerParagraph);
219
+ * ```
220
+ */
221
+ findParagraphByText(text: string, segmentId?: string): FDocumentParagraph | null;
222
+ /**
223
+ * Find paragraphs by a query object, which can include text content, paragraph id, and segment id.
224
+ * @param {string | IFDocumentParagraphQuery} query The query object or text content to search for.
225
+ * @returns {FDocumentParagraph[]} An array of paragraph facade instances that match the query.
226
+ * @example
227
+ * ```ts
228
+ * const fDocument = univerAPI.getActiveDocument();
229
+ * const paragraphsWithText = fDocument.findParagraphs('Hello');
230
+ * console.log(paragraphsWithText);
174
231
  *
175
- * if (footers) {
176
- * for (const footerId in footers) {
177
- * if (footerId === 'target-footer-id') {
178
- * fDocument.insertText('Hello, footer!', {
179
- * startOffset: 0,
180
- * endOffset: 0,
181
- * segmentId: footerId,
182
- * });
183
- * }
184
- * }
185
- * }
186
- * ```
187
- */
188
- insertText(text: string, options?: IDocumentInsertTextFacadeOptions): boolean;
189
- /**
190
- * Inserts one or more plain-text paragraphs at the provided document range.
191
- * @param {string} text - The paragraph text to insert. Newlines are normalized to document paragraph separators.
192
- * @param {IDocumentInsertTextFacadeOptions} options - Optional target range, segment id, and cursor offset.
193
- * @returns {boolean} `true` if the paragraphs were successfully inserted, or `false` if it failed.
232
+ * const paragraphsWithId = fDocument.findParagraphs({ paragraphId: 'paragraph-01' });
233
+ * console.log(paragraphsWithId);
234
+ *
235
+ * const headerSegmentId = fDocument.ensurePageHeader();
236
+ * const paragraphsWithSegment = fDocument.findParagraphs({ segmentId: headerSegmentId });
237
+ * console.log(paragraphsWithSegment);
238
+ * ```
239
+ */
240
+ findParagraphs(query: string | IFDocumentParagraphQuery): FDocumentParagraph[];
241
+ /**
242
+ * Insert a plain-text paragraph before the paragraph at the given paragraph index.
243
+ * @param {number} index The zero-based paragraph insertion index.
244
+ * @param {string} text The paragraph text. Defaults to an empty paragraph.
245
+ * @param {string} segmentId The segment id of the body. Defaults to an empty string for the main body.
246
+ * @returns {FDocumentParagraph} The inserted paragraph facade instance.
194
247
  * @example
195
- * ```typescript
248
+ * ```ts
196
249
  * const fDocument = univerAPI.getActiveDocument();
197
- * const success = fDocument.insertParagraph('Hello, world! This is a new paragraph.', {
198
- * startOffset: 5,
199
- * endOffset: 5,
200
- * });
201
- * console.log(success);
250
+ * const paragraph = fDocument.insertParagraph(0, 'Document title');
251
+ * paragraph.appendText(' suffix');
252
+ *
253
+ * const headerSegmentId = fDocument.ensurePageHeader();
254
+ * const headerParagraph = fDocument.insertParagraph(0, 'Header title', headerSegmentId);
255
+ * headerParagraph.appendText(' suffix');
256
+ * ```
257
+ */
258
+ insertParagraph(index: number, text?: string, segmentId?: string): FDocumentParagraph;
259
+ /**
260
+ * Append a plain-text paragraph at the end of the body.
261
+ * @param {string} text The paragraph text. Defaults to an empty paragraph.
262
+ * @returns {FDocumentParagraph} The appended paragraph wrapper.
263
+ * @example
264
+ * ```ts
265
+ * const fDocument = univerAPI.getActiveDocument();
266
+ * const paragraph = fDocument.appendParagraph('Summary');
267
+ * console.log(paragraph.getText());
268
+ *
269
+ * const footerSegmentId = fDocument.ensurePageFooter();
270
+ * const footerParagraph = fDocument.appendParagraph('Confidential', footerSegmentId);
271
+ * console.log(footerParagraph.getText());
272
+ * ```
273
+ */
274
+ appendParagraph(text?: string, segmentId?: string): FDocumentParagraph;
275
+ /**
276
+ * Delete a range from the body.
277
+ * @param {IFDocumentTextRange} range The text range to delete.
278
+ * @returns {boolean} `true` if the range was deleted.
279
+ * @example
280
+ * ```ts
281
+ * const fDocument = univerAPI.getActiveDocument();
282
+ * fDocument.deleteRange({ startOffset: 0, endOffset: 5 });
283
+ *
284
+ * const headerSegmentId = fDocument.ensurePageHeader();
285
+ * fDocument.deleteRange({ startOffset: 0, endOffset: 5, segmentId: headerSegmentId });
202
286
  * ```
203
287
  */
204
- insertParagraph(text?: string, options?: IDocumentInsertTextFacadeOptions): boolean;
288
+ deleteRange(range: IFDocumentTextRange): boolean;
289
+ private _createFDocumentParagraph;
290
+ private _normalizeDeleteRange;
291
+ private _getParagraphInsertOffset;
292
+ private _ensureHeaderFooter;
293
+ private _getHeaderFooterCreateInfo;
205
294
  }
@@ -14,12 +14,8 @@
14
14
  * limitations under the License.
15
15
  */
16
16
  import './f-univer';
17
- export { DocElementRegistry, DocElementStaleError, type FDocElementType } from './doc-element-registry';
18
- export { FDocBlockRange } from './f-doc-block-range';
19
- export { FDocBody, type IFDocElementHandle, type IFDocResolvedParagraph, type IFDocRichTextLike, type IFDocTextRange } from './f-doc-body';
20
- export { FDocCustomBlock } from './f-doc-custom-block';
21
- export { FDocElement } from './f-doc-element';
22
- export { FDocParagraph } from './f-doc-paragraph';
23
- export { FDocTable } from './f-doc-table';
24
17
  export { FDocument } from './f-document';
25
- export type * from './f-univer';
18
+ export { FDocumentParagraph, isParagraphFacade } from './f-document-paragraph';
19
+ export type { IFDocumentParagraphInfo } from './f-document-paragraph';
20
+ export type { IFDocumentTextRange } from './utils';
21
+ export { stripBlockTokens } from './utils';
@@ -13,14 +13,26 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
- import type { IDocumentBody } from '@univerjs/core';
17
- type IParagraphStyle = NonNullable<IDocumentBody['paragraphs']>[number]['paragraphStyle'];
16
+ import type { DocumentDataModel, IDocumentBody, Injector, IParagraphStyle, UpdateDocsAttributeType } from '@univerjs/core';
18
17
  export interface IBuildPlainTextInsertBodyOptions {
19
18
  paragraphStyle?: IParagraphStyle;
20
19
  removeLeadingParagraphBreak?: boolean;
21
20
  }
21
+ /**
22
+ * A text range in a document segment. Offsets are zero-based positions in the segment data stream.
23
+ */
24
+ export interface IFDocumentTextRange {
25
+ /** The inclusive start offset of the range. */
26
+ startOffset: number;
27
+ /** The exclusive end offset of the range. */
28
+ endOffset: number;
29
+ /** The header/footer segment id. Omit or use an empty string for the main body. */
30
+ segmentId?: string;
31
+ }
22
32
  export declare function getRemovedLeadingParagraphBreakLength(dataStream: string, removeLeadingParagraphBreak?: boolean): number;
23
33
  export declare function getNormalizedPlainTextCursorOffset(dataStream: string, cursorOffset: number, removeLeadingParagraphBreak?: boolean): number;
24
- export declare function getParagraphStyleAtOffset(body: IDocumentBody, offset: number): IParagraphStyle;
34
+ export declare function getParagraphStyleAtOffset(body: IDocumentBody, offset: number): IParagraphStyle | undefined;
25
35
  export declare function buildPlainTextInsertBody(dataStream: string, options?: IBuildPlainTextInsertBodyOptions): IDocumentBody;
26
- export {};
36
+ export declare function replaceBodyRange(range: IFDocumentTextRange, insertBody: IDocumentBody, docDataModel: DocumentDataModel, injector: Injector): boolean;
37
+ export declare function retainBodyRange(range: IFDocumentTextRange, updateBody: IDocumentBody, coverType: UpdateDocsAttributeType, docDataModel: DocumentDataModel, injector: Injector): boolean;
38
+ export declare function stripBlockTokens(text: string): string;
@@ -15,12 +15,16 @@
15
15
  */
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
+ export { CreateHeaderFooterCommand, HeaderFooterType } from './commands/commands/create-header-footer.command';
19
+ export type { HeaderFooterCreateMode, ICreateHeaderFooterCommandParams, IHeaderFooterProps } from './commands/commands/create-header-footer.command';
18
20
  export { RichTextEditingMutation } from './commands/mutations/core-editing.mutation';
19
21
  export type { IRichTextEditingMutationParams } from './commands/mutations/core-editing.mutation';
20
22
  export { SetTextSelectionsOperation } from './commands/operations/text-selection.operation';
21
23
  export type { ISetTextSelectionsOperationParams } from './commands/operations/text-selection.operation';
22
24
  export type { IUniverDocsConfig } from './config/config';
23
25
  export { UniverDocsPlugin } from './plugin';
26
+ export { DocBlockMoveValidatorService } from './services/doc-block-move-validator.service';
27
+ export type { DocBlockMoveTransformer, DocBlockMoveValidator, IDocBlockMoveResult, IDocBlockMoveTransformContext, IDocBlockMoveValidationContext } from './services/doc-block-move-validator.service';
24
28
  export { DocContentInsertService } from './services/doc-content-insert.service';
25
29
  export type { IDocContentInsertRange } from './services/doc-content-insert.service';
26
30
  export { DocInterceptorService } from './services/doc-interceptor/doc-interceptor.service';
@@ -32,3 +36,4 @@ export type { IDocStateChangeInfo, IDocStateChangeParams } from './services/doc-
32
36
  export { DocStateEmitService } from './services/doc-state-emit.service';
33
37
  export { addCustomRangeBySelectionFactory, addCustomRangeFactory, deleteCustomRangeFactory, } from './utils/custom-range-factory';
34
38
  export { replaceSelectionFactory } from './utils/replace-selection-factory';
39
+ export { consumeContentInsertRange, isHeaderFooterSelection } from './utils/util';
@@ -0,0 +1,46 @@
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 { IDisposable, IDocumentData } from '@univerjs/core';
17
+ import { Disposable } from '@univerjs/core';
18
+ export interface IDocBlockMoveValidationContext {
19
+ unitId: string;
20
+ sourceRange: {
21
+ startOffset: number;
22
+ endOffset: number;
23
+ };
24
+ targetOffset: number;
25
+ }
26
+ export type DocBlockMoveValidator = (context: IDocBlockMoveValidationContext) => boolean;
27
+ export interface IDocBlockMoveResult {
28
+ nextDocumentData: IDocumentData;
29
+ movedRange: {
30
+ startOffset: number;
31
+ endOffset: number;
32
+ };
33
+ }
34
+ export interface IDocBlockMoveTransformContext extends IDocBlockMoveValidationContext {
35
+ previousDocumentData: IDocumentData;
36
+ result: IDocBlockMoveResult;
37
+ }
38
+ export type DocBlockMoveTransformer = (context: IDocBlockMoveTransformContext) => IDocBlockMoveResult;
39
+ export declare class DocBlockMoveValidatorService extends Disposable {
40
+ private readonly _validators;
41
+ private readonly _transformers;
42
+ registerValidator(validator: DocBlockMoveValidator): IDisposable;
43
+ registerTransformer(transformer: DocBlockMoveTransformer): IDisposable;
44
+ canMoveBlock(context: IDocBlockMoveValidationContext): boolean;
45
+ transformMoveResult(context: IDocBlockMoveTransformContext): IDocBlockMoveResult;
46
+ }
@@ -0,0 +1,19 @@
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 { IAccessor } from '@univerjs/core';
17
+ import type { ITextRangeWithStyle } from '@univerjs/engine-render';
18
+ export declare function consumeContentInsertRange(accessor: IAccessor, unitId: string): import("..").IDocContentInsertRange | null;
19
+ export declare function isHeaderFooterSelection(range?: ITextRangeWithStyle): boolean;
package/lib/umd/facade.js CHANGED
@@ -1,5 +1,3 @@
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`});let i=`DocElementRegistry no longer tracks paragraph identity; use paragraphId.`;var a=class extends Error{constructor(e=`Doc element is stale`){super(e),this.name=`DocElementStaleError`}},o=class{getParagraphKey(e,t,n){throw Error(i)}resolveParagraphStartIndex(e,t){throw Error(i)}syncParagraph(e,t,n){throw Error(i)}markStale(e,t){throw Error(i)}beforeTextEdit(e,t,n,r){throw Error(i)}};function s(e){return e==null?e:JSON.parse(JSON.stringify(e))}function c(e){return e.replace(/\r\n/g,`\r`).replace(/\n/g,`\r`)}function l(e,t){let n=c(e);return t&&n.length>1&&n.startsWith(`\r`)?1:0}function u(e,t,n){let r=c(e.slice(0,t)).length;return Math.max(0,r-l(e,n))}function d(e,t){var n,r;let i=(n=e.paragraphs)==null?[]:n,a=(r=i.find(e=>e.startIndex>=t))==null?i[i.length-1]:r;return a==null?void 0:a.paragraphStyle}function f(e,n={}){let r=c(e).slice(l(e,n.removeLeadingParagraphBreak)),i={dataStream:r,customDecorations:[],customRanges:[],textRuns:[]},a=[],o=new Set;for(let e=0;e<r.length;e++)r[e]===`\r`&&a.push({startIndex:e,paragraphId:(0,t.createParagraphId)(o),...n.paragraphStyle==null?{}:{paragraphStyle:s(n.paragraphStyle)}});return a.length>0&&(i.paragraphs=a),i}var p=class{constructor(e,t){this._body=e,this._key=t}getType(){return`blockRange`}getKey(){return this._key}getParent(){return this._body}removeFromParent(){return this._body.removeBlockRange(this._key)}getBlockType(){return this._body.getBlockRange(this._key).blockType}getText(){return this._body.getBlockRangeText(this._key)}setText(e){return this._body.setBlockRangeText(this._key,e)}unwrap(){return this.removeFromParent()}},m=class{constructor(e,t){this._body=e,this._key=t}getType(){return`customBlock`}getKey(){return this._key}getParent(){return this._body}removeFromParent(){return this._body.removeCustomBlock(this._key)}getBlockId(){return this._body.getCustomBlock(this._key).blockId}},h=class{constructor(e,t){this._body=e,this._key=t}getType(){return`paragraph`}getKey(){return this._key}getId(){return this._key}getParent(){return this._body}removeFromParent(){return this._body.removeParagraph(this._key)}getText(){return this._body.getParagraphText(this._key)}setText(e){return this._body.setParagraphText(this._key,e)}appendText(e){return this._body.appendParagraphText(this._key,e)}getRange(){return this._body.getParagraphRange(this._key)}isListItem(){return this._body.isListParagraph(this._key)}isTask(){return this._body.isTaskParagraph(this._key)}setTaskChecked(e){return this._body.setTaskChecked(this._key,e)}},g=class{constructor(e,t){this._body=e,this._key=t}getType(){return`table`}getKey(){return this._key}getParent(){return this._body}removeFromParent(){return this._body.removeTable(this._key)}getTableId(){return this._body.getTable(this._key).tableId}},_=class{constructor(e,t,n){this._body=e,this._type=t,this._key=n}getType(){return this._type}getKey(){return this._key}getParent(){return this._body}getNextSibling(){return this._body.createSibling(this._type,this._key,1)}getPreviousSibling(){return this._body.createSibling(this._type,this._key,-1)}removeFromParent(){return this._type===`paragraph`?this._body.removeParagraph(this._key):this._type===`blockRange`?this._body.removeBlockRange(this._key):this._type===`table`?this._body.removeTable(this._key):this._body.removeCustomBlock(this._key)}asParagraph(){return this._assertType(`paragraph`),new h(this._body,this._key)}asTable(){return this._assertType(`table`),new g(this._body,this._key)}asBlockRange(){return this._assertType(`blockRange`),new p(this._body,this._key)}asCustomBlock(){return this._assertType(`customBlock`),new m(this._body,this._key)}_assertType(e){if(this._type!==e)throw TypeError(`Cannot cast ${this._type} to ${e}.`)}};function v(e){return typeof e==`object`&&!!e&&`getData`in e&&typeof e.getData==`function`}let y=`doc-facade`;var b=class{constructor(e,t,n,r=``){this._documentDataModel=e,this._commandService=t,this._segmentId=r}getNumChildren(){return this._getChildren().length}getChild(e){let t=this._getChildren()[e];if(!t)throw RangeError(`Child index ${e} is out of range.`);return this._createElement(t.type,t.key)}getChildIndex(e){let t=this.resolveElement(e.getType(),e.getKey()),n=this._getChildren().findIndex(e=>e.type===t.type&&e.key===t.key);if(n<0)throw Error(`Doc element is stale`);return n}insertText(e,t){return this._replaceBodyRange({startOffset:e,endOffset:e},f(t))}insertParagraph(e,t=``){var n;let r=this._getParagraphInsertOffset(e);if(!this._replaceBodyRange({startOffset:r,endOffset:r},f(`${t}\r`)))throw Error(`Failed to insert paragraph.`);let i=this._normalizeInsertedParagraphIndex(e),a=(n=this._getBody().paragraphs)==null?void 0:n[i];return new h(this,this._getParagraphId(a,i))}appendParagraph(e=``){var t,n;return this.insertParagraph((t=(n=this._getBody().paragraphs)==null?void 0:n.length)==null?0:t,e)}deleteRange(e){return this._replaceBodyRange(e,{dataStream:``})}replaceRange(e,t){let n;if(typeof t==`string`)n=f(t);else if(v(t)){var r;n=(r=t.getData().body)==null?{dataStream:``}:r}else{var i;n=(i=t.body)==null?{dataStream:``}:i}return this._replaceBodyRange(e,n)}setTextStyle(e,n){let r={dataStream:``,textRuns:[{st:0,ed:e.endOffset-e.startOffset,ts:n}]};return this._retainBodyRange(e,r,t.UpdateDocsAttributeType.COVER)}setParagraphStyle(e,n){let r=e instanceof _||e instanceof h?this.resolveParagraph(e.getKey()):this._findParagraphByRange(e),i={dataStream:``,paragraphs:[{...r.paragraph,startIndex:0,paragraphStyle:{...r.paragraph.paragraphStyle,...n}}]};return this._preserveExplicitParagraphIds(i),this._retainBodyRange({startOffset:r.endOffset,endOffset:r.endOffset+1},i,t.UpdateDocsAttributeType.REPLACE)}getParagraphText(e){let t=this.resolveParagraph(e);return this._getBody().dataStream.slice(t.startOffset,t.endOffset)}setParagraphText(e,t){let n=this.resolveParagraph(e);return this.replaceRange({startOffset:n.startOffset,endOffset:n.endOffset},t)}appendParagraphText(e,t){let n=this.resolveParagraph(e);return this.insertText(n.endOffset,t)}removeParagraph(e){let t=this.resolveParagraph(e);return this.deleteRange({startOffset:t.startOffset,endOffset:t.endOffset+1})}getParagraphRange(e){let t=this.resolveParagraph(e);return{startOffset:t.startOffset,endOffset:t.endOffset,segmentId:this._segmentId}}isListParagraph(e){return!!this.resolveParagraph(e).paragraph.bullet}isTaskParagraph(e){var n;let r=(n=this.resolveParagraph(e).paragraph.bullet)==null?void 0:n.listType;return r===t.PresetListType.CHECK_LIST||r===t.PresetListType.CHECK_LIST_CHECKED}setTaskChecked(e,n){let r=this.resolveParagraph(e),i=r.paragraph.bullet;if(!i||!this.isTaskParagraph(e))return!1;let a={dataStream:``,paragraphs:[{...r.paragraph,startIndex:0,bullet:{...i,listType:n?t.PresetListType.CHECK_LIST_CHECKED:t.PresetListType.CHECK_LIST}}]};return this._preserveExplicitParagraphIds(a),this._retainBodyRange({startOffset:r.endOffset,endOffset:r.endOffset+1},a,t.UpdateDocsAttributeType.REPLACE)}resolveParagraph(e){var t;let n=this._getBody(),r=((t=n.paragraphs)==null?[]:t).map((e,t)=>({paragraph:e,paragraphIndex:t})).filter(({paragraph:t})=>t.paragraphId===e);if(r.length!==1)throw new a(r.length>1?`Doc paragraph id "${e}" is duplicated.`:`Doc paragraph id "${e}" is stale.`);let{paragraph:i,paragraphIndex:o}=r[0];return{paragraph:i,paragraphIndex:o,startOffset:o>0?n.paragraphs[o-1].startIndex+1:0,endOffset:i.startIndex}}resolveElement(e,t){if(e===`paragraph`)return{type:e,key:t,position:this.resolveParagraph(t).startOffset,priority:3};let n=this._getChildren().find(n=>n.type===e&&n.key===t);if(!n)throw Error(`Doc element is stale`);return n}getBlockRange(e){var t;let n=(t=this._getBody().blockRanges)==null?void 0:t.find(t=>t.blockId===e);if(!n)throw Error(`Doc element is stale`);return n}getBlockRangeText(e){let t=this.getBlockRange(e);return this._getBody().dataStream.slice(t.startIndex,t.endIndex)}setBlockRangeText(e,t){let n=this.getBlockRange(e),r=f(`${t}\r`);return r.blockRanges=[{...n,startIndex:0,endIndex:t.length}],this.replaceRange({startOffset:n.startIndex,endOffset:n.endIndex+1},{body:r})}removeBlockRange(e){let t=this.getBlockRange(e);return this.deleteRange({startOffset:t.startIndex,endOffset:t.endIndex+1})}getTable(e){var t;let n=(t=this._getBody().tables)==null?void 0:t.find(t=>t.tableId===e);if(!n)throw Error(`Doc element is stale`);return n}removeTable(e){let t=this.getTable(e);return this.deleteRange({startOffset:t.startIndex,endOffset:t.endIndex+1})}getCustomBlock(e){var t;let n=(t=this._getBody().customBlocks)==null?void 0:t.find(t=>t.blockId===e);if(!n)throw Error(`Doc element is stale`);return n}removeCustomBlock(e){let t=this.getCustomBlock(e);return this.deleteRange({startOffset:t.startIndex,endOffset:t.startIndex+1})}createSibling(e,t,n){let r=this.getChildIndex(this._createElement(e,t)),i=this._getChildren()[r+n];return i?this._createElement(i.type,i.key):null}_getChildren(){var e,t,n,r,i;let a=this._getBody(),o=[];for(let n=0;n<((e=(t=a.paragraphs)==null?void 0:t.length)==null?0:e);n++){let e=a.paragraphs[n];o.push({type:`paragraph`,key:this._getParagraphId(e,n),position:n>0?a.paragraphs[n-1].startIndex+1:0,priority:3})}return(n=a.blockRanges)==null||n.forEach(e=>o.push({type:`blockRange`,key:e.blockId,position:e.startIndex,priority:0})),(r=a.tables)==null||r.forEach(e=>o.push({type:`table`,key:e.tableId,position:e.startIndex,priority:1})),(i=a.customBlocks)==null||i.forEach(e=>o.push({type:`customBlock`,key:e.blockId,position:e.startIndex,priority:2})),o.sort((e,t)=>e.position-t.position||e.priority-t.priority)}_createElement(e,t){return new _(this,e,t)}_getBody(){let e=this._documentDataModel.getSelfOrHeaderFooterModel(this._segmentId).getBody();if(!e)throw Error(`The document body is empty`);return e}_getParagraphInsertOffset(e){var t;let n=this._getBody();if(e<=0)return 0;let r=(t=n.paragraphs)==null?[]:t;return r.length===0?Math.max(0,n.dataStream.length-1):e>=r.length?r[r.length-1].startIndex+1:r[e-1].startIndex+1}_normalizeInsertedParagraphIndex(e){var t;let n=(t=this._getBody().paragraphs)==null?[]:t;return Math.max(0,Math.min(e,n.length-1))}_getParagraphId(e,t){if(!e)throw RangeError(`Paragraph index ${t} is out of range.`);if(!e.paragraphId)throw new a(`Paragraph at index ${t} is missing paragraphId.`);return e.paragraphId}_preserveExplicitParagraphIds(e){e.__textXRestoreParagraphIds=!0}_findParagraphByRange(e){var t;let n=(t=this._getBody().paragraphs)==null?[]:t,r=n.findIndex((t,r)=>(r>0?n[r-1].startIndex+1:0)<=e.startOffset&&e.endOffset<=t.startIndex);if(r<0)throw RangeError(`Range does not resolve to a paragraph.`);let i=n[r];return{paragraph:i,paragraphIndex:r,startOffset:r>0?n[r-1].startIndex+1:0,endOffset:i.startIndex}}_replaceBodyRange(e,n){let r=e.startOffset,i=e.endOffset,a=new t.TextX;return r>0&&a.push({t:t.TextXActionType.RETAIN,len:r}),i>r&&a.push({t:t.TextXActionType.DELETE,len:i-r}),n.dataStream.length>0&&a.push({t:t.TextXActionType.INSERT,body:n,len:n.dataStream.length}),this._executeTextX(a)}_retainBodyRange(e,n,r){var i;(i=n.textRuns)!=null&&i.length&&this._getBody().textRuns==null&&this._ensureTextRuns();let a=new t.TextX;return e.startOffset>0&&a.push({t:t.TextXActionType.RETAIN,len:e.startOffset}),a.push({t:t.TextXActionType.RETAIN,body:n,coverType:r,len:e.endOffset-e.startOffset}),this._executeTextX(a)}_ensureTextRuns(){if(this._getBody().textRuns!=null)return;let e=t.JSONX.getInstance().replaceOp([...(0,t.getRichTextEditPath)(this._documentDataModel,this._segmentId),`textRuns`],void 0,[]);this._commandService.syncExecuteCommand(r.RichTextEditingMutation.id,{unitId:this._documentDataModel.getUnitId(),segmentId:this._segmentId,actions:e,textRanges:[],trigger:y,isEditing:!1})}_executeTextX(e){let n=t.JSONX.getInstance().editOp(e.serialize(),(0,t.getRichTextEditPath)(this._documentDataModel,this._segmentId));return!!this._commandService.syncExecuteCommand(r.RichTextEditingMutation.id,{unitId:this._documentDataModel.getUnitId(),segmentId:this._segmentId,actions:n,textRanges:[],trigger:y,isEditing:!1})}};function x(e){"@babel/helpers - typeof";return x=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},x(e)}function S(e,t){if(x(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(x(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function C(e){var t=S(e,`string`);return x(t)==`symbol`?t:t+``}function w(e,t,n){return(t=C(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function T(e,t){return function(n,r){t(n,r,e)}}function E(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 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,w(this,`id`,void 0),w(this,`_docElementRegistry`,new o),this.id=this._documentDataModel.getUnitId()}getDocumentDataModel(){return this._documentDataModel}getBody(){return new b(this._documentDataModel,this._commandService,this._docElementRegistry)}dispose(){super.dispose()}getId(){return this.id}getName(){return this._documentDataModel.getTitle()||``}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)}appendText(e){let{body:t}=this.save();if(!t)throw Error(`The document body is empty`);let n=t.dataStream.length-2;return this.insertText(e,{startOffset:n,endOffset:n,segmentId:``})}insertText(e,t={}){var n,i,a;let o=this.id,{body:s}=this.save();if(!s)throw Error(`The document body is empty`);let c=(n=t.startOffset)==null?Math.max(0,s.dataStream.length-2):n,l=(i=t.endOffset)==null?c:i,p=(a=t.segmentId)==null?``:a,m={startOffset:c,endOffset:l,collapsed:c===l,segmentId:p},h=c===0,g=f(e,{paragraphStyle:d(s,c),removeLeadingParagraphBreak:h}),_=t.cursorOffset==null?void 0:u(e,t.cursorOffset,h);return this._commandService.syncExecuteCommand(r.InsertTextCommand.id,{unitId:o,body:g,range:m,segmentId:p,..._==null?{}:{cursorOffset:_}})}insertParagraph(e=``,t={}){var n;let r=`${e.replace(/\r\n/g,`
2
- `).replace(/\r/g,`
3
- `).split(`
4
- `).join(`\r
5
- `)}\r\n`;return this.insertText(r,{...t,cursorOffset:(n=t.cursorOffset)==null?r.length:n})}};D=E([T(1,(0,t.Inject)(t.Injector)),T(2,t.IUniverInstanceService),T(3,(0,t.Inject)(t.IResourceLoaderService)),T(4,t.ICommandService)],D);var O=class extends n.FUniver{createDocument(e){let n=this._injector.get(t.IUniverInstanceService).createUnit(t.UniverInstanceType.UNIVER_DOC,e);return this._injector.createInstance(D,n)}getActiveDocument(){let e=this._univerInstanceService.getCurrentUnitOfType(t.UniverInstanceType.UNIVER_DOC);return e?this._injector.createInstance(D,e):null}getDocument(e){let n=this._univerInstanceService.getUnit(e,t.UniverInstanceType.UNIVER_DOC);return n?this._injector.createInstance(D,n):null}};n.FUniver.extend(O),e.DocElementRegistry=o,e.DocElementStaleError=a,e.FDocBlockRange=p,e.FDocBody=b,e.FDocCustomBlock=m,e.FDocElement=_,e.FDocParagraph=h,e.FDocTable=g,Object.defineProperty(e,"FDocument",{enumerable:!0,get:function(){return D}})});
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});