@univerjs/docs 1.0.0-alpha.1 → 1.0.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/facade.js +458 -978
- package/lib/cjs/index.js +158 -9
- package/lib/es/facade.js +460 -977
- package/lib/es/index.js +156 -11
- package/lib/facade.js +460 -977
- package/lib/index.js +156 -11
- package/lib/types/commands/commands/create-header-footer.command.d.ts +41 -0
- package/lib/types/facade/f-document-paragraph.d.ts +73 -100
- package/lib/types/facade/f-document.d.ts +197 -26
- package/lib/types/facade/index.d.ts +4 -6
- package/lib/types/facade/utils.d.ts +15 -1
- package/lib/types/index.d.ts +3 -0
- package/lib/types/utils/util.d.ts +19 -0
- package/lib/umd/facade.js +3 -1
- package/lib/umd/index.js +2 -1
- package/package.json +4 -4
- package/lib/types/facade/f-document-block-range.d.ts +0 -132
- package/lib/types/facade/f-document-body.d.ts +0 -276
- package/lib/types/facade/f-document-custom-block.d.ts +0 -57
- package/lib/types/facade/f-document-element.d.ts +0 -193
- package/lib/types/facade/f-document-table.d.ts +0 -57
|
@@ -13,10 +13,16 @@
|
|
|
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 {
|
|
20
|
+
import { FDocumentParagraph } from './f-document-paragraph';
|
|
21
|
+
export interface IFDocumentParagraphQuery {
|
|
22
|
+
text?: string;
|
|
23
|
+
paragraphId?: string;
|
|
24
|
+
segmentId?: string;
|
|
25
|
+
}
|
|
20
26
|
/**
|
|
21
27
|
* Facade API object bounded to a document. It provides a set of methods to interact with the document.
|
|
22
28
|
* @hideconstructor
|
|
@@ -31,39 +37,34 @@ export declare class FDocument extends FBaseInitialable {
|
|
|
31
37
|
constructor(_documentDataModel: DocumentDataModel, _injector: Injector, _univerInstanceService: IUniverInstanceService, _resourceLoaderService: IResourceLoaderService, _commandService: ICommandService);
|
|
32
38
|
/**
|
|
33
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.
|
|
34
41
|
* @returns {DocumentDataModel} The document data model.
|
|
35
42
|
* @example
|
|
36
43
|
* ```typescript
|
|
37
44
|
* const fDocument = univerAPI.getActiveDocument();
|
|
38
|
-
*
|
|
39
|
-
*
|
|
45
|
+
* console.log(fDocument.getDocumentDataModel());
|
|
46
|
+
*
|
|
47
|
+
* const headerSegmentId = fDocument.ensurePageHeader();
|
|
48
|
+
* console.log(fDocument.getDocumentDataModel(headerSegmentId));
|
|
40
49
|
* ```
|
|
41
50
|
*/
|
|
42
|
-
getDocumentDataModel(): DocumentDataModel;
|
|
51
|
+
getDocumentDataModel(segmentId?: string): DocumentDataModel;
|
|
43
52
|
/**
|
|
44
|
-
* Get the document body
|
|
45
|
-
*
|
|
46
|
-
* The
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
* and custom blocks, use their existing ids.
|
|
50
|
-
*
|
|
51
|
-
* @returns {FDocumentBody} 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.
|
|
52
58
|
* @example
|
|
53
59
|
* ```typescript
|
|
54
60
|
* const fDocument = univerAPI.getActiveDocument();
|
|
55
|
-
*
|
|
56
|
-
* console.log(fDocumentBody.getBody());
|
|
61
|
+
* console.log(fDocument.getBody()); // Get the main body
|
|
57
62
|
*
|
|
58
|
-
* const
|
|
59
|
-
*
|
|
60
|
-
* const paragraph = element.asParagraph();
|
|
61
|
-
* paragraph.appendText(' updated');
|
|
62
|
-
* console.log(paragraph.getText());
|
|
63
|
-
* }
|
|
63
|
+
* const footerSegmentId = fDocument.ensurePageFooter();
|
|
64
|
+
* console.log(fDocument.getBody(footerSegmentId)); // Get the footer body
|
|
64
65
|
* ```
|
|
65
66
|
*/
|
|
66
|
-
getBody():
|
|
67
|
+
getBody(segmentId?: string): IDocumentBody;
|
|
67
68
|
dispose(): void;
|
|
68
69
|
/**
|
|
69
70
|
* Get the document id.
|
|
@@ -71,8 +72,7 @@ export declare class FDocument extends FBaseInitialable {
|
|
|
71
72
|
* @example
|
|
72
73
|
* ```typescript
|
|
73
74
|
* const fDocument = univerAPI.getActiveDocument();
|
|
74
|
-
*
|
|
75
|
-
* console.log(unitId);
|
|
75
|
+
* console.log(fDocument.getId());
|
|
76
76
|
* ```
|
|
77
77
|
*/
|
|
78
78
|
getId(): string;
|
|
@@ -82,11 +82,20 @@ export declare class FDocument extends FBaseInitialable {
|
|
|
82
82
|
* @example
|
|
83
83
|
* ```typescript
|
|
84
84
|
* const fDocument = univerAPI.getActiveDocument();
|
|
85
|
-
*
|
|
86
|
-
* console.log(name);
|
|
85
|
+
* console.log(fDocument.getName());
|
|
87
86
|
* ```
|
|
88
87
|
*/
|
|
89
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;
|
|
90
99
|
/**
|
|
91
100
|
* Save the document snapshot data, including the document content and resource data, etc.
|
|
92
101
|
* @returns {IDocumentData} The document snapshot data.
|
|
@@ -120,4 +129,166 @@ export declare class FDocument extends FBaseInitialable {
|
|
|
120
129
|
* ```
|
|
121
130
|
*/
|
|
122
131
|
redo(): boolean;
|
|
132
|
+
/**
|
|
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.
|
|
136
|
+
* @example
|
|
137
|
+
* ```ts
|
|
138
|
+
* const fDocument = univerAPI.getActiveDocument();
|
|
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);
|
|
153
|
+
* ```
|
|
154
|
+
*/
|
|
155
|
+
ensurePageFooter(pageIndex?: number): string;
|
|
156
|
+
/**
|
|
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.
|
|
162
|
+
* @example
|
|
163
|
+
* ```ts
|
|
164
|
+
* const fDocument = univerAPI.getActiveDocument();
|
|
165
|
+
* fDocument.insertText(0, 'Hello ');
|
|
166
|
+
*
|
|
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
|
|
178
|
+
* const fDocument = univerAPI.getActiveDocument();
|
|
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);
|
|
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);
|
|
198
|
+
*
|
|
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
|
|
212
|
+
* const fDocument = univerAPI.getActiveDocument();
|
|
213
|
+
* const paragraph = fDocument.findParagraphByText('Hello');
|
|
214
|
+
* console.log(paragraph);
|
|
215
|
+
*
|
|
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);
|
|
231
|
+
*
|
|
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.
|
|
247
|
+
* @example
|
|
248
|
+
* ```ts
|
|
249
|
+
* const fDocument = univerAPI.getActiveDocument();
|
|
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 });
|
|
286
|
+
* ```
|
|
287
|
+
*/
|
|
288
|
+
deleteRange(range: IFDocumentTextRange): boolean;
|
|
289
|
+
private _createFDocumentParagraph;
|
|
290
|
+
private _normalizeDeleteRange;
|
|
291
|
+
private _getParagraphInsertOffset;
|
|
292
|
+
private _ensureHeaderFooter;
|
|
293
|
+
private _getHeaderFooterCreateInfo;
|
|
123
294
|
}
|
|
@@ -15,9 +15,7 @@
|
|
|
15
15
|
*/
|
|
16
16
|
import './f-univer';
|
|
17
17
|
export { FDocument } from './f-document';
|
|
18
|
-
export {
|
|
19
|
-
export {
|
|
20
|
-
export {
|
|
21
|
-
export {
|
|
22
|
-
export { FDocumentParagraph } from './f-document-paragraph';
|
|
23
|
-
export { FDocumentTable } from './f-document-table';
|
|
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,12 +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, IParagraphStyle } from '@univerjs/core';
|
|
16
|
+
import type { DocumentDataModel, IDocumentBody, Injector, IParagraphStyle, UpdateDocsAttributeType } from '@univerjs/core';
|
|
17
17
|
export interface IBuildPlainTextInsertBodyOptions {
|
|
18
18
|
paragraphStyle?: IParagraphStyle;
|
|
19
19
|
removeLeadingParagraphBreak?: boolean;
|
|
20
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
|
+
}
|
|
21
32
|
export declare function getRemovedLeadingParagraphBreakLength(dataStream: string, removeLeadingParagraphBreak?: boolean): number;
|
|
22
33
|
export declare function getNormalizedPlainTextCursorOffset(dataStream: string, cursorOffset: number, removeLeadingParagraphBreak?: boolean): number;
|
|
23
34
|
export declare function getParagraphStyleAtOffset(body: IDocumentBody, offset: number): IParagraphStyle | undefined;
|
|
24
35
|
export declare function buildPlainTextInsertBody(dataStream: string, options?: IBuildPlainTextInsertBodyOptions): IDocumentBody;
|
|
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;
|
package/lib/types/index.d.ts
CHANGED
|
@@ -15,6 +15,8 @@
|
|
|
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';
|
|
@@ -34,3 +36,4 @@ export type { IDocStateChangeInfo, IDocStateChangeParams } from './services/doc-
|
|
|
34
36
|
export { DocStateEmitService } from './services/doc-state-emit.service';
|
|
35
37
|
export { addCustomRangeBySelectionFactory, addCustomRangeFactory, deleteCustomRangeFactory, } from './utils/custom-range-factory';
|
|
36
38
|
export { replaceSelectionFactory } from './utils/replace-selection-factory';
|
|
39
|
+
export { consumeContentInsertRange, isHeaderFooterSelection } from './utils/util';
|
|
@@ -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 +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`});var i=class extends n.FBase{constructor(e,t,n,r){super(),this._body=e,this._bodyEdit=t,this._info=n,this._injector=r}getType(){return this._info.type}isParagraph(){return this._info.type===t.DocumentBlockType.PARAGRAPH}isTable(){return this._info.type===t.DocumentBlockType.TABLE}isBlockRange(){return this._info.type===t.DocumentBlockType.BLOCK_RANGE}isCustomBlock(){return this._info.type===t.DocumentBlockType.CUSTOM_BLOCK}getKey(){return this._info.key}getParent(){return this._body}getResolvedInfo(){return this._info}getNextSibling(){return this._createSibling(1)}getPreviousSibling(){return this._createSibling(-1)}getSibling(e){return this._createSibling(e)}remove(){return this.isParagraph()?this._body.removeParagraph(this.asParagraph()):this.isBlockRange()?this._body.removeBlockRange(this.asBlockRange()):this.isTable()?this._body.removeTable(this.asTable()):this._body.removeCustomBlock(this.asCustomBlock())}_createSibling(e){if(e===0)throw Error(`Offset cannot be zero.`);let t=this._body.getElementIndex(this);return this._body.getElement(t+e)}};function a(e){return e==null?e:JSON.parse(JSON.stringify(e))}function o(e){return e.replace(/\r\n/g,`\r`).replace(/\n/g,`\r`)}function s(e,t){let n=o(e);return t&&n.length>1&&n.startsWith(`\r`)?1:0}function c(e,n={}){let r=o(e).slice(s(e,n.removeLeadingParagraphBreak)),i={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:a(n.paragraphStyle)}});return c.length>0&&(i.paragraphs=c),i}var l=class extends i{constructor(e,n,r,i){if(super(e,n,r,i),this.body=e,this.bodyEdit=n,this.info=r,this.injector=i,this.getType()!==t.DocumentBlockType.PARAGRAPH)throw Error(`Element type is not a paragraph: ${this.getType()}`)}getParagraphId(){return this.getKey()}getResolvedParagraphInfo(){let{paragraphs:e=[]}=this._body.getBody(),t=e.map((e,t)=>({paragraph:e,paragraphIndex:t})).filter(({paragraph:e})=>e.paragraphId===this.getKey());if(t.length===0)throw Error(`Document paragraph with id ${this.getKey()} not found`);if(t.length>1)throw Error(`Multiple document paragraphs with id ${this.getKey()} 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.getResolvedParagraphInfo();return{startOffset:e,endOffset:t,segmentId:this._body.getSegmentId()}}getText(){let{dataStream:e}=this._body.getBody(),{startOffset:t,endOffset:n}=this.getResolvedParagraphInfo();return e.slice(t,n)}setText(e){let{startOffset:t,endOffset:n}=this.getResolvedParagraphInfo();return this._bodyEdit.replaceRange({startOffset:t,endOffset:n},c(e))}appendText(e){let{endOffset:t}=this.getResolvedParagraphInfo();return this._body.insertText(t,e)}setStyle(e){let{paragraph:n,endOffset:r}=this.getResolvedParagraphInfo(),i={dataStream:``,paragraphs:[{...n,startIndex:0,paragraphStyle:{...n.paragraphStyle,...e}}]};return this._preserveExplicitParagraphIds(i),this._bodyEdit.retainRange({startOffset:r,endOffset:r+1},i,t.UpdateDocsAttributeType.REPLACE)}isListItem(){let{paragraph:e}=this.getResolvedParagraphInfo();return!!e.bullet}isTask(){var e;let{paragraph:n}=this.getResolvedParagraphInfo(),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.getResolvedParagraphInfo(),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),this._bodyEdit.retainRange({startOffset:r,endOffset:r+1},a,t.UpdateDocsAttributeType.REPLACE)}_preserveExplicitParagraphIds(e){e[t.RESTORE_INSERTED_PARAGRAPH_IDS]=!0}},u=class extends i{asParagraph(){if(this.getType()!==t.DocumentBlockType.PARAGRAPH)throw Error(`Element type is not a paragraph: ${this.getType()}`);return this._injector.createInstance(l,this._body,this._bodyEdit,this.getResolvedInfo(),this._injector)}};i.extend(u);function d(e){"@babel/helpers - typeof";return d=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},d(e)}function f(e,t){if(d(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(d(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function p(e){var t=f(e,`string`);return d(t)==`symbol`?t:t+``}function m(e,t,n){return(t=p(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var h=class{constructor(e,t,n=``){this._documentDataModel=e,this._injector=t,this._segmentId=n,m(this,`_bodyEdit`,void 0),this._bodyEdit={replaceRange:this._replaceBodyRange.bind(this),retainRange:this._retainBodyRange.bind(this)}}getSegmentId(){return this._segmentId}getBody(){let e=this._documentDataModel.getSelfOrHeaderFooterModel(this._segmentId).getBody();if(!e)throw Error(`The document body is empty`);return e}getElements(){return this._getChildren().map(e=>this._injector.createInstance(i,this,this._bodyEdit,e,this._injector))}getElement(e){var t;return(t=this.getElements()[e])==null?null:t}getElementIndex(e){let{type:t,key:n}=e.getResolvedInfo(),r=this._getChildren().findIndex(e=>e.type===t&&e.key===n);if(r<0)throw Error(`Doc element is stale`);return r}insertText(e,t){return this._replaceBodyRange({startOffset:e,endOffset:e},c(t))}setTextStyle(e,n){let r={dataStream:``,textRuns:[{st:0,ed:e.endOffset-e.startOffset,ts:n}]};return this._retainBodyRange(e,r,t.UpdateDocsAttributeType.COVER)}insertParagraph(e,t=``){var n;let r=this._getParagraphInsertOffset(e);if(!this._replaceBodyRange({startOffset:r,endOffset:r},c(`${t}\r`)))throw Error(`Failed to insert paragraph.`);let{paragraphs:i=[]}=this.getBody(),a=i[e];if(!a)throw Error(`Failed to insert paragraph.`);let o=this._resolveParagraphInfo(a,e,(n=i[e-1])==null?void 0:n.startIndex);return this._injector.createInstance(l,this,this._bodyEdit,o,this._injector)}appendParagraph(e=``){let{paragraphs:t=[]}=this.getBody();return this.insertParagraph(t.length,e)}deleteRange(e){return this._replaceBodyRange(e,{dataStream:``})}removeParagraph(e){let{startOffset:t,endOffset:n}=e.getResolvedParagraphInfo();return this.deleteRange({startOffset:t,endOffset:n+1})}removeBlockRange(e){let{startIndex:t,endIndex:n}=e.getBlockRange();return this.deleteRange({startOffset:t,endOffset:n+1})}removeTable(e){let{startIndex:t,endIndex:n}=e.getTable();return this.deleteRange({startOffset:t,endOffset:n+1})}removeCustomBlock(e){let{startIndex:t}=e.getCustomBlock();return this.deleteRange({startOffset:t,endOffset:t+1})}resolveElement(e){let{type:t,key:n}=e.getResolvedInfo(),r=this._getChildren().find(e=>e.type===t&&e.key===n);if(!r)throw Error(`Doc element is stale`);return r}_getChildren(){let{paragraphs:e,blockRanges:n,tables:r,customBlocks:i}=this.getBody(),a=[];if(e)for(let t=0;t<e.length;t++){var o;let n=e[t],r=this._resolveParagraphInfo(n,t,(o=e[t-1])==null?void 0:o.startIndex);a.push(r)}if(n)for(let e=0;e<n.length;e++){let r=n[e];a.push({type:t.DocumentBlockType.BLOCK_RANGE,key:r.blockId,position:r.startIndex,priority:0})}if(r)for(let e=0;e<r.length;e++){let n=r[e];a.push({type:t.DocumentBlockType.TABLE,key:n.tableId,position:n.startIndex,priority:1})}if(i)for(let e=0;e<i.length;e++){let n=i[e];a.push({type:t.DocumentBlockType.CUSTOM_BLOCK,key:n.blockId,position:n.startIndex,priority:2})}return a.sort((e,t)=>e.position-t.position||e.priority-t.priority)}_resolveParagraphInfo(e,n,r){return{type:t.DocumentBlockType.PARAGRAPH,key:this._getParagraphId(e,n),position:n>0?r+1:0,priority:3}}_getParagraphId(e,t){if(!e)throw Error(`Paragraph index ${t} is out of range.`);if(!e.paragraphId)throw Error(`Paragraph at index ${t} is missing paragraphId.`);return e.paragraphId}_getParagraphInsertOffset(e){if(e<=0)return 0;let{dataStream:t,paragraphs:n=[]}=this.getBody();return n.length===0?Math.max(0,t.length-1):e>=n.length?n[n.length-1].startIndex+1:n[e-1].startIndex+1}_replaceBodyRange(e,n){let{startOffset:r,endOffset:i}=e,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(){let e=t.JSONX.getInstance().replaceOp([...(0,t.getRichTextEditPath)(this._documentDataModel,this._segmentId),`textRuns`],void 0,[]);this._injector.get(t.ICommandService).syncExecuteCommand(r.RichTextEditingMutation.id,{unitId:this._documentDataModel.getUnitId(),segmentId:this._segmentId,actions:e,textRanges:[],isEditing:!1})}_executeTextX(e){let n=t.JSONX.getInstance().editOp(e.serialize(),(0,t.getRichTextEditPath)(this._documentDataModel,this._segmentId));return this._injector.get(t.ICommandService).syncExecuteCommand(r.RichTextEditingMutation.id,{unitId:this._documentDataModel.getUnitId(),segmentId:this._segmentId,actions:n,textRanges:[],isEditing:!1})!==!1}};function g(e,t){return function(n,r){t(n,r,e)}}function _(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 v=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,m(this,`id`,void 0),this.id=this._documentDataModel.getUnitId()}getDocumentDataModel(){return this._documentDataModel}getBody(){return this._injector.createInstance(h,this._documentDataModel,this._injector)}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)}};v=_([g(1,(0,t.Inject)(t.Injector)),g(2,t.IUniverInstanceService),g(3,(0,t.Inject)(t.IResourceLoaderService)),g(4,t.ICommandService)],v);var y=class extends n.FUniver{createDocument(e){let n=this._injector.get(t.IUniverInstanceService).createUnit(t.UniverInstanceType.UNIVER_DOC,e);return this._injector.createInstance(v,n)}getActiveDocument(){let e=this._univerInstanceService.getCurrentUnitOfType(t.UniverInstanceType.UNIVER_DOC);return e?this._injector.createInstance(v,e):null}getDocument(e){let n=this._univerInstanceService.getUnit(e,t.UniverInstanceType.UNIVER_DOC);return n?this._injector.createInstance(v,n):null}};n.FUniver.extend(y);var b=class extends i{constructor(e,n,r,i){if(super(e,n,r,i),this.body=e,this.bodyEdit=n,this.info=r,this.injector=i,this.getType()!==t.DocumentBlockType.BLOCK_RANGE)throw Error(`Element type is not a block range: ${this.getType()}`)}getBlockRange(){let{blockRanges:e=[]}=this._body.getBody(),t=e.find(e=>e.blockId===this.getKey());if(!t)throw Error(`Block range not found: ${this.getKey()}`);return t}getBlockType(){return this.getBlockRange().blockType}getText(){let{dataStream:e}=this._body.getBody(),{startIndex:t,endIndex:n}=this.getBlockRange();return e.slice(t,n)}setText(e){let t=this.getBlockRange(),{startIndex:n,endIndex:r}=t,i=c(`${e}\r`);return i.blockRanges=[{...t,startIndex:0,endIndex:e.length}],this._bodyEdit.replaceRange({startOffset:n,endOffset:r+1},i)}unwrap(){return this.remove()}},x=class extends i{asBlockRange(){if(this.getType()!==t.DocumentBlockType.BLOCK_RANGE)throw Error(`Element type is not a block range: ${this.getType()}`);return this._injector.createInstance(b,this._body,this._bodyEdit,this.getResolvedInfo(),this._injector)}};i.extend(x);var S=class extends i{constructor(e,n,r,i){if(super(e,n,r,i),this.body=e,this.bodyEdit=n,this.info=r,this.injector=i,this.getType()!==t.DocumentBlockType.CUSTOM_BLOCK)throw Error(`Element type is not a custom block: ${this.getType()}`)}getCustomBlock(){let{customBlocks:e=[]}=this._body.getBody(),t=e.find(e=>e.blockId===this.getKey());if(!t)throw Error(`Doc custom block is stale`);return t}},C=class extends i{asCustomBlock(){if(this.getType()!==t.DocumentBlockType.CUSTOM_BLOCK)throw Error(`Element type is not a custom block: ${this.getType()}`);return this._injector.createInstance(S,this._body,this._bodyEdit,this.getResolvedInfo(),this._injector)}};i.extend(C);var w=class extends i{constructor(e,n,r,i){if(super(e,n,r,i),this.body=e,this.bodyEdit=n,this.info=r,this.injector=i,this.getType()!==t.DocumentBlockType.TABLE)throw Error(`Element type is not a table: ${this.getType()}`)}getTable(){let{tables:e=[]}=this._body.getBody(),t=e.find(e=>e.tableId===this.getKey());if(!t)throw Error(`Doc table is stale`);return t}},T=class extends i{asTable(){if(this.getType()!==t.DocumentBlockType.TABLE)throw Error(`Element type is not a table: ${this.getType()}`);return this._injector.createInstance(w,this._body,this._bodyEdit,this.getResolvedInfo(),this._injector)}};i.extend(T),Object.defineProperty(e,"FDocument",{enumerable:!0,get:function(){return v}}),e.FDocumentBlockRange=b,e.FDocumentBody=h,e.FDocumentCustomBlock=S,e.FDocumentElement=i,e.FDocumentParagraph=l,e.FDocumentTable=w});
|
|
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});
|
package/lib/umd/index.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require("@univerjs/core"),require("@univerjs/engine-render"),require("rxjs")):typeof define==`function`&&define.amd?define([`exports`,`@univerjs/core`,`@univerjs/engine-render`,`rxjs`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.UniverDocs={},e.UniverCore,e.UniverEngineRender,e.rxjs))})(this,function(e,t,n,r){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});let i={id:`doc.operation.set-selections`,type:t.CommandType.OPERATION,handler:()=>!0};function a(e){"@babel/helpers - typeof";return a=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},a(e)}function o(e,t){if(a(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(a(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function s(e){var t=o(e,`string`);return a(t)==`symbol`?t:t+``}function c(e,t,n){return(t=s(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function l(e,t){return function(n,r){t(n,r,e)}}function u(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}let d=class extends t.RxDisposable{constructor(e,t){super(),this._commandService=e,this._univerInstanceService=t,c(this,`_currentSelection`,null),c(this,`_textSelectionInfo`,new Map),c(this,`_textSelection$`,new r.Subject),c(this,`textSelection$`,this._textSelection$.asObservable()),c(this,`_refreshSelection$`,new r.BehaviorSubject(null)),c(this,`refreshSelection$`,this._refreshSelection$.asObservable()),this._listenCurrentUnit()}_listenCurrentUnit(){this._univerInstanceService.getCurrentTypeOfUnit$(t.UniverInstanceType.UNIVER_DOC).pipe((0,r.takeUntil)(this.dispose$)).subscribe(e=>{if(e==null)return;let t=e.getUnitId();this._setCurrentSelectionNotRefresh({unitId:t,subUnitId:t})})}__getCurrentSelection(){return this._currentSelection}getSelectionInfo(e=this._currentSelection){return this._getTextRanges(e)}refreshSelection(e=this._currentSelection){e!=null&&this._refresh(e)}__TEST_ONLY_setCurrentSelection(e){this._currentSelection=e,this._refresh(e)}getTextRanges(e=this._currentSelection){var t;return(t=this._getTextRanges(e))==null?void 0:t.textRanges}getRectRanges(e=this._currentSelection){var t;return(t=this._getTextRanges(e))==null?void 0:t.rectRanges}getDocRanges(e=this._currentSelection){var t,n;let r=(t=this.getTextRanges(e))==null?[]:t,i=(n=this.getRectRanges(e))==null?[]:n;return[...r,...i].filter(e=>e.startOffset!=null&&e.endOffset!=null).sort((e,t)=>e.startOffset>t.startOffset?1:e.startOffset<t.startOffset?-1:0)}getActiveTextRange(){let e=this._getTextRanges(this._currentSelection);if(e==null)return;let{textRanges:t}=e;return t.find(e=>e.isActive)}getActiveRectRange(){let e=this._getTextRanges(this._currentSelection);if(e==null)return;let{rectRanges:t}=e;return t.find(e=>e.isActive)}__TEST_ONLY_add(e,t=!0){this._currentSelection!=null&&this._addByParam({...this._currentSelection,textRanges:e,rectRanges:[],segmentId:``,segmentPage:-1,isEditing:t,style:n.NORMAL_TEXT_SELECTION_PLUGIN_STYLE})}replaceTextRanges(e,t=!0,n){return this.replaceDocRanges(e,this._currentSelection,t,n)}replaceDocRanges(e,t=this._currentSelection,n=!0,r){if(t==null)return;let{unitId:i,subUnitId:a}=t;this._refreshSelection$.next({unitId:i,subUnitId:a,docRanges:e,isEditing:n,options:r})}__replaceTextRangesWithNoRefresh(e,t){if(this._currentSelection==null)return;let n={...e,...t};this._replaceByParam(n),this._textSelection$.next(n);let{unitId:r,subUnitId:a,segmentId:o,style:s,textRanges:c,rectRanges:l,isEditing:u}=n,d=[...c,...l].filter(e=>e.startOffset!=null&&e.endOffset!=null).sort((e,t)=>e.startOffset>t.startOffset?1:e.startOffset<t.startOffset?-1:0);this._commandService.executeCommand(i.id,{unitId:r,subUnitId:a,segmentId:o,style:s,isEditing:u,ranges:d})}dispose(){this._textSelection$.complete(),this._refreshSelection$.complete()}_setCurrentSelectionNotRefresh(e){this._currentSelection=e}_getTextRanges(e){var t;if(e==null)return;let{unitId:n,subUnitId:r=``}=e;return(t=this._textSelectionInfo.get(n))==null?void 0:t.get(r)}_refresh(e){let t=this._getTextRanges(e);if(t==null)return;let{textRanges:n,rectRanges:r}=t,i=[...n,...r],{unitId:a,subUnitId:o}=e;this._refreshSelection$.next({unitId:a,subUnitId:o,docRanges:i,isEditing:!1})}_replaceByParam(e){let{unitId:t,subUnitId:n,...r}=e;this._textSelectionInfo.has(t)||this._textSelectionInfo.set(t,new Map),this._textSelectionInfo.get(t).set(n,{...r})}_addByParam(e){let{unitId:t,subUnitId:n,...r}=e;this._textSelectionInfo.has(t)||this._textSelectionInfo.set(t,new Map);let i=this._textSelectionInfo.get(t);i.has(n)?i.get(n).textRanges.push(...e.textRanges):i.set(n,{...r})}};d=u([l(0,t.ICommandService),l(1,t.IUniverInstanceService)],d);let f=class extends t.RxDisposable{constructor(e,n,i){super(),this._context=e,this._localeService=n,this._univerInstanceService=i,c(this,`_skeleton`,void 0),c(this,`_docViewModel`,void 0),c(this,`_currentSkeleton$`,new r.BehaviorSubject(null)),c(this,`currentSkeleton$`,this._currentSkeleton$.asObservable()),c(this,`_currentSkeletonBefore$`,new r.BehaviorSubject(null)),c(this,`currentSkeletonBefore$`,this._currentSkeletonBefore$.asObservable()),c(this,`_currentViewModel$`,new r.BehaviorSubject(null)),c(this,`currentViewModel$`,this._currentViewModel$.asObservable()),this._init(),this._univerInstanceService.getCurrentTypeOfUnit$(t.UniverInstanceType.UNIVER_DOC).pipe((0,r.takeUntil)(this.dispose$)).subscribe(e=>{e&&e.getUnitId()===this._context.unitId&&this._update(e)})}dispose(){super.dispose(),this._currentSkeletonBefore$.complete(),this._currentSkeleton$.complete()}getSkeleton(){return this._skeleton}getViewModel(){return this._docViewModel}_init(){let e=this._context.unit;this._update(e)}_update(e){let n=this._context.unitId;if(e.getBody()==null)return;this._docViewModel&&(0,t.isInternalEditorID)(n)?(this._docViewModel.reset(e),this._context.unit=e):this._docViewModel||(this._docViewModel=this._buildDocViewModel(e)),this._skeleton||(this._skeleton=this._buildSkeleton(this._docViewModel));let r=this._skeleton;r.calculate(),this._currentSkeletonBefore$.next(r),this._currentSkeleton$.next(r),this._currentViewModel$.next(this._docViewModel)}_buildSkeleton(e){return n.DocumentSkeleton.create(e,this._localeService)}_buildDocViewModel(e){return new n.DocumentViewModel(e)}};f=u([l(1,(0,t.Inject)(t.LocaleService)),l(2,t.IUniverInstanceService)],f);var p=class extends t.RxDisposable{constructor(){super(),c(this,`_docStateChangeParams$`,new r.BehaviorSubject(null)),c(this,`docStateChangeParams$`,this._docStateChangeParams$.asObservable())}emitStateChangeInfo(e){this._docStateChangeParams$.next(e)}dispose(){super.dispose(),this._docStateChangeParams$.complete()}};let m=`doc.mutation.rich-text-editing`,h={id:m,type:t.CommandType.MUTATION,handler:(e,r,i)=>{var a,o;let{unitId:s,segmentId:c=``,actions:l,textRanges:u,prevTextRanges:h,trigger:g,noHistory:_,isCompositionEnd:v,noNeedSetTextRange:y,debounce:b,isEditing:x=!0,isSync:S,syncer:C}=r,w=S||(i==null?void 0:i.fromCollab)||(i==null?void 0:i.fromChangeset),T=e.get(t.IUniverInstanceService),E=e.get(n.IRenderManagerService),D=e.get(p),O=T.getUnit(s,t.UniverInstanceType.UNIVER_DOC),k=(a=E.getRenderUnitById(s))==null?void 0:a.with(f).getViewModel();if(O==null)throw Error(`DocumentDataModel not found for unitId: ${s}`);let A=e.get(d),j=(o=A.getDocRanges())==null?[]:o,M=!!O.getSnapshot().disabled;if(t.JSONX.isNoop(l)||l&&l.length===0||M)return{unitId:s,actions:[],textRanges:j};let N=t.JSONX.invertWithDoc(l,O.getSnapshot());O.apply(l),k==null||k.reset(O),!y&&u&&g!=null&&!w&&queueMicrotask(()=>{A.replaceDocRanges(u,{unitId:s,subUnitId:s},x,r.options)});let P={commandId:m,unitId:s,segmentId:c,trigger:g,noHistory:_,debounce:b,redoState:{actions:l,textRanges:u},undoState:{actions:N,textRanges:h==null?j:h},isCompositionEnd:v,isSync:w,syncer:C};return D.emitStateChangeInfo(P),{unitId:s,actions:N,textRanges:j}}},g={id:`doc.command.insert-text`,type:t.CommandType.COMMAND,handler:(e,n)=>{var r;let i=e.get(t.ICommandService),{range:a,segmentId:o,body:s,unitId:c,cursorOffset:l}=n,u=e.get(d),f=e.get(t.IUniverInstanceService).getUnit(c,t.UniverInstanceType.UNIVER_DOC);if(f==null)return!1;let p=u.getActiveTextRange(),m=f.getSelfOrHeaderFooterModel((r=p==null?void 0:p.segmentId)==null?``:r).getBody();if(m==null)return!1;let{startOffset:g,collapsed:_}=a,v=l==null?s.dataStream.length:l,y=[{startOffset:g+v,endOffset:g+v,style:p==null?void 0:p.style,collapsed:_}],b={id:h.id,params:{unitId:c,actions:[],textRanges:y,debounce:!0}},x=new t.TextX,S=t.JSONX.getInstance();if(_)g>0&&x.push({t:t.TextXActionType.RETAIN,len:g}),x.push({t:t.TextXActionType.INSERT,body:s,len:s.dataStream.length});else{let e=t.BuildTextUtils.selection.delete([a],m,0,s);x.push(...e)}b.params.textRanges=[{startOffset:g+v,endOffset:g+v,collapsed:_}];let C=(0,t.getRichTextEditPath)(f,o);return b.params.actions=S.editOp(x.serialize(),C),!!i.syncExecuteCommand(b.id,b.params)}},_={id:`doc.command.delete-text`,type:t.CommandType.COMMAND,handler:(e,n)=>{var r;let i=e.get(t.ICommandService),a=e.get(t.IUniverInstanceService),{range:o,segmentId:s,unitId:c,direction:l,len:u=1}=n,d=a.getUnit(c,t.UniverInstanceType.UNIVER_DOC),f=d==null?void 0:d.getSelfOrHeaderFooterModel(s).getBody();if(d==null||f==null)return!1;let{startOffset:p}=o,m=l===t.DeleteDirection.LEFT?p-u:p,g=l===t.DeleteDirection.LEFT?p-1:p+u-1,_=(r=f.customRanges)==null?void 0:r.find(e=>e.startIndex<=m&&e.endIndex>=g);_!=null&&_.wholeEntity&&(m=_.startIndex,g=Math.max(g,_.endIndex));let v={id:h.id,params:{unitId:c,actions:[],textRanges:[{startOffset:m,endOffset:m,collapsed:!0}],debounce:!0}},y=new t.TextX,b=t.JSONX.getInstance();y.push({t:t.TextXActionType.RETAIN,len:m-0}),y.push({t:t.TextXActionType.DELETE,len:g-m+1});let x=(0,t.getRichTextEditPath)(d,s);return v.params.actions=b.editOp(y.serialize(),x),!!i.syncExecuteCommand(v.id,v.params)}},v={id:`doc.command.update-text`,type:t.CommandType.COMMAND,handler:(e,n)=>{let{range:r,segmentId:i,updateBody:a,coverType:o,unitId:s,textRanges:c}=n,l=e.get(t.ICommandService),u=e.get(t.IUniverInstanceService).getCurrentUniverDocInstance();if(u==null)return!1;let d={id:h.id,params:{unitId:s,actions:[],textRanges:c}},f=new t.TextX,p=t.JSONX.getInstance(),{startOffset:m,endOffset:g}=r;f.push({t:t.TextXActionType.RETAIN,len:m}),f.push({t:t.TextXActionType.RETAIN,body:a,len:g-m,coverType:o});let _=(0,t.getRichTextEditPath)(u,i);return d.params.actions=p.editOp(f.serialize(),_),!!l.syncExecuteCommand(d.id,d.params)}};var y=`@univerjs/docs`,b=`1.0.0-alpha.1`;let x={id:`doc.mutation.rename-doc`,type:t.CommandType.MUTATION,handler:(e,n)=>{let r=e.get(t.IUniverInstanceService).getUnit(n.unitId,t.UniverInstanceType.UNIVER_DOC);return r?(r.setName(n.name),!0):!1}},S={},C=class extends t.Disposable{constructor(e,t,n){super(),this._commandService=e,this._textSelectionManagerService=t,this._univerInstanceService=n,this._initSelectionChange()}_transformCustomRange(e,n){var r;let{startOffset:i,endOffset:a,collapsed:o}=n,s=(r=e.getCustomRanges())==null?void 0:r.filter(e=>!e.wholeEntity||i<=e.startIndex&&a>e.endIndex?!1:o?e.startIndex<i&&e.endIndex>=a:t.BuildTextUtils.range.isIntersects(i,a-1,e.startIndex,e.endIndex));if(s!=null&&s.length){let e=i,t=a;return s.forEach(n=>{e=Math.min(n.startIndex,e),t=Math.max(n.endIndex+1,t)}),{...n,startOffset:e,endOffset:t,collapsed:e===t}}return n}_initSelectionChange(){this.disposeWithMe(this._commandService.onCommandExecuted(e=>{if(e.id===i.id){let{unitId:t,ranges:n,isEditing:r}=e.params,i=this._univerInstanceService.getUnit(t);if(!i)return;let a=n.map(e=>this._transformCustomRange(i,e));a.some((e,t)=>n[t]!==e)&&this._textSelectionManagerService.replaceTextRanges(a,r)}}))}};C=u([l(0,t.ICommandService),l(1,(0,t.Inject)(d)),l(2,t.IUniverInstanceService)],C);var w=class extends t.Disposable{constructor(...e){super(...e),c(this,`_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)}},T=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 E=(0,t.createIdentifier)(`doc.state-change-interceptor-service`),D=class extends t.RxDisposable{constructor(e,t,n,i,a){super(),this._undoRedoService=e,this._commandService=t,this._univerInstanceService=n,this._docStateEmitService=i,this._docStateChangeInterceptorService=a,c(this,`_docStateChange$`,new r.BehaviorSubject(null)),c(this,`docStateChange$`,this._docStateChange$.asObservable()),c(this,`_historyStateCache`,new Map),c(this,`_changeStateCache`,new Map),c(this,`_historyTimer`,null),c(this,`_changeStateCacheTimer`,null),this._initialize(),this._listenDocStateChange()}getStateCache(e){var t,n;return{history:(t=this._historyStateCache.get(e))==null?[]:t,collaboration:(n=this._changeStateCache.get(e))==null?[]:n}}setStateCache(e,t){this._historyStateCache.set(e,t.history),this._changeStateCache.set(e,t.collaboration)}_setChangeState(e){this._cacheChangeState(e,`history`),this._cacheChangeState(e,`collaboration`)}_initialize(){this.disposeWithMe(this._commandService.beforeCommandExecuted(e=>{if(e.id===t.UndoCommandId||e.id===t.RedoCommandId){let e=this._univerInstanceService.getCurrentUniverDocInstance();if(e==null)return;let t=e.getUnitId();this._pushHistory(t),this._emitChangeState(t)}}))}_listenDocStateChange(){this._docStateEmitService.docStateChangeParams$.pipe((0,r.takeUntil)(this.dispose$)).subscribe(e=>{var t,n;if(e==null)return;let r=(t=(n=this._docStateChangeInterceptorService)==null?void 0:n.transformChangeStateInfo(e))==null?e:t;if(r==null||r.isSync)return;let{isCompositionEnd:i,isSync:a,syncer:o,...s}=r;this._setChangeState(s)})}_cacheChangeState(e,n=`history`){let{trigger:r,unitId:i,noHistory:a,debounce:o=!1}=e;if(a||n===`history`&&r==null||n===`history`&&(r===t.RedoCommandId||r===t.UndoCommandId))return;let s=n===`history`?this._historyStateCache:this._changeStateCache,c=n===`history`?this._pushHistory.bind(this):this._emitChangeState.bind(this);if(s.has(i)){let t=s.get(i);t==null||t.push(e)}else s.set(i,[e]);o?n===`history`?(this._historyTimer&&clearTimeout(this._historyTimer),this._historyTimer=setTimeout(()=>{c(i)},300)):(this._changeStateCacheTimer&&clearTimeout(this._changeStateCacheTimer),this._changeStateCacheTimer=setTimeout(()=>{c(i)},300)):c(i)}_pushHistory(e){let n=this._undoRedoService,r=this._historyStateCache.get(e);if(n==null||!Array.isArray(r)||r.length===0)return;let i=r.length,a=r[0].commandId,o=r[0],s=r[i-1],c={unitId:e,actions:r.reduce((e,n)=>t.JSONX.compose(e,n.redoState.actions),null),textRanges:s.redoState.textRanges},l={unitId:e,actions:r.reverse().reduce((e,n)=>t.JSONX.compose(e,n.undoState.actions),null),textRanges:o.undoState.textRanges};n.pushUndoRedo({unitID:e,undoMutations:[{id:a,params:l}],redoMutations:[{id:a,params:c}]}),r.length=0}_emitChangeState(e){let n=this._changeStateCache.get(e);if(!Array.isArray(n)||n.length===0)return;let r=n.length,{commandId:i,trigger:a,segmentId:o,noHistory:s,debounce:c}=n[0],l=n[0],u=n[r-1],d={commandId:i,unitId:e,trigger:a,redoState:{unitId:e,actions:n.reduce((e,n)=>t.JSONX.compose(e,n.redoState.actions),null),textRanges:u.redoState.textRanges},undoState:{unitId:e,actions:n.reverse().reduce((e,n)=>t.JSONX.compose(e,n.undoState.actions),null),textRanges:l.undoState.textRanges},segmentId:o,noHistory:s,debounce:c};n.length=0,this._docStateChange$.next(d)}};D=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)(E))],D);let O=class extends t.Plugin{constructor(e=S,n,r){super(),this._config=e,this._injector=n,this._configService=r;let{...i}=(0,t.merge)({},S,this._config);this._configService.setConfig(`docs.config`,i)}onStarting(){this._initializeDependencies(),this._initializeCommands()}_initializeCommands(){[g,_,v,h,x,i].forEach(e=>{this._injector.get(t.ICommandService).registerCommand(e)})}_initializeDependencies(){[[d],[p],[D],[w],[T],[C]].forEach(e=>this._injector.add(e))}onReady(){this._injector.get(D),this._injector.get(C)}};c(O,`pluginName`,`DOCS_PLUGIN`),c(O,`packageName`,y),c(O,`version`,b),O=u([l(1,(0,t.Inject)(t.Injector)),l(2,t.IConfigService)],O);let k={CUSTOM_RANGE:(0,t.createInterceptorKey)(`CUSTOM_RANGE`),CUSTOM_DECORATION:(0,t.createInterceptorKey)(`CUSTOM_DECORATION`)},A=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(k.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(k.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(k.CUSTOM_DECORATION)(e.getCustomDecorationRaw(t),{index:t,unitId:e.getDataModel().getUnitId(),customDecorations:(n=e.getDataModel().getCustomDecorations())==null?[]:n})}})),n}};A=u([l(1,(0,t.Inject)(f))],A);function j(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 M(e,n){var r;let{rangeId:i,rangeType:a,wholeEntity:o,properties:s,unitId:c,selections:l}=n,u=e.get(d),f=e.get(t.IUniverInstanceService),p=l==null?u.getTextRanges({unitId:c,subUnitId:c}):l,m=p==null||(r=p[0])==null?void 0:r.segmentId;if(!(p!=null&&p.length))return!1;let g=f.getUnit(c,t.UniverInstanceType.UNIVER_DOC);if(!g)return!1;let _=g.getSelfOrHeaderFooterModel(m).getBody();if(!_)return!1;let v=t.BuildTextUtils.customRange.add({ranges:p,rangeId:i,rangeType:a,segmentId:m,wholeEntity:o,properties:s,body:_});if(!v)return!1;let y=t.JSONX.getInstance(),b={id:h.id,params:{unitId:c,actions:[],textRanges:v.selections,segmentId:m},textX:v},x=(0,t.getRichTextEditPath)(g,m);return b.params.actions=y.editOp(v.serialize(),x),b}function N(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 P(e,n){var r,i,a,o;let{unitId:s,body:c,doc:l}=n,u=l;if(u||(u=e.get(t.IUniverInstanceService).getUnit(s)),!u)return!1;let f=(r=n.selection)==null?void 0:r.segmentId,p=(i=u.getSelfOrHeaderFooterModel(f))==null?void 0:i.getBody();if(!p)return!1;let m=e.get(d),g=(a=n.selection)==null?m.getActiveTextRange():a;if(!g||!p)return!1;let _=(o=n.textRanges)==null?[{startOffset:g.startOffset+c.dataStream.length,endOffset:g.startOffset+c.dataStream.length,collapsed:!0,segmentId:f}]:o,v=t.BuildTextUtils.selection.replace({selection:g,body:c,doc:u});if(!v)return!1;let y={id:h.id,params:{unitId:s,actions:[],textRanges:_,debounce:!0,segmentId:f},textX:v},b=t.JSONX.getInstance();return y.params.actions=b.editOp(v.serialize()),y}e.DOC_INTERCEPTOR_POINT=k,e.DeleteTextCommand=_,e.DocBlockMoveValidatorService=w,e.DocContentInsertService=T,Object.defineProperty(e,"DocInterceptorService",{enumerable:!0,get:function(){return A}}),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 D}}),e.DocStateEmitService=p,e.IDocStateChangeInterceptorService=E,e.InsertTextCommand=g,e.RichTextEditingMutation=h,e.SetTextSelectionsOperation=i,Object.defineProperty(e,"UniverDocsPlugin",{enumerable:!0,get:function(){return O}}),e.UpdateTextCommand=v,e.addCustomRangeBySelectionFactory=M,e.addCustomRangeFactory=j,e.deleteCustomRangeFactory=N,e.replaceSelectionFactory=P});
|
|
1
|
+
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require("@univerjs/core"),require("@univerjs/engine-render"),require("rxjs")):typeof define==`function`&&define.amd?define([`exports`,`@univerjs/core`,`@univerjs/engine-render`,`rxjs`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.UniverDocs={},e.UniverCore,e.UniverEngineRender,e.rxjs))})(this,function(e,t,n,r){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});let i={id:`doc.operation.set-selections`,type:t.CommandType.OPERATION,handler:()=>!0};function a(e){"@babel/helpers - typeof";return a=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},a(e)}function o(e,t){if(a(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(a(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function s(e){var t=o(e,`string`);return a(t)==`symbol`?t:t+``}function c(e,t,n){return(t=s(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function l(e,t){return function(n,r){t(n,r,e)}}function u(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}let d=class extends t.RxDisposable{constructor(e,t){super(),this._commandService=e,this._univerInstanceService=t,c(this,`_currentSelection`,null),c(this,`_textSelectionInfo`,new Map),c(this,`_textSelection$`,new r.Subject),c(this,`textSelection$`,this._textSelection$.asObservable()),c(this,`_refreshSelection$`,new r.BehaviorSubject(null)),c(this,`refreshSelection$`,this._refreshSelection$.asObservable()),this._listenCurrentUnit()}_listenCurrentUnit(){this._univerInstanceService.getCurrentTypeOfUnit$(t.UniverInstanceType.UNIVER_DOC).pipe((0,r.takeUntil)(this.dispose$)).subscribe(e=>{if(e==null)return;let t=e.getUnitId();this._setCurrentSelectionNotRefresh({unitId:t,subUnitId:t})})}__getCurrentSelection(){return this._currentSelection}getSelectionInfo(e=this._currentSelection){return this._getTextRanges(e)}refreshSelection(e=this._currentSelection){e!=null&&this._refresh(e)}__TEST_ONLY_setCurrentSelection(e){this._currentSelection=e,this._refresh(e)}getTextRanges(e=this._currentSelection){var t;return(t=this._getTextRanges(e))==null?void 0:t.textRanges}getRectRanges(e=this._currentSelection){var t;return(t=this._getTextRanges(e))==null?void 0:t.rectRanges}getDocRanges(e=this._currentSelection){var t,n;let r=(t=this.getTextRanges(e))==null?[]:t,i=(n=this.getRectRanges(e))==null?[]:n;return[...r,...i].filter(e=>e.startOffset!=null&&e.endOffset!=null).sort((e,t)=>e.startOffset>t.startOffset?1:e.startOffset<t.startOffset?-1:0)}getActiveTextRange(){let e=this._getTextRanges(this._currentSelection);if(e==null)return;let{textRanges:t}=e;return t.find(e=>e.isActive)}getActiveRectRange(){let e=this._getTextRanges(this._currentSelection);if(e==null)return;let{rectRanges:t}=e;return t.find(e=>e.isActive)}__TEST_ONLY_add(e,t=!0){this._currentSelection!=null&&this._addByParam({...this._currentSelection,textRanges:e,rectRanges:[],segmentId:``,segmentPage:-1,isEditing:t,style:n.NORMAL_TEXT_SELECTION_PLUGIN_STYLE})}replaceTextRanges(e,t=!0,n){return this.replaceDocRanges(e,this._currentSelection,t,n)}replaceDocRanges(e,t=this._currentSelection,n=!0,r){if(t==null)return;let{unitId:i,subUnitId:a}=t;this._refreshSelection$.next({unitId:i,subUnitId:a,docRanges:e,isEditing:n,options:r})}__replaceTextRangesWithNoRefresh(e,t){if(this._currentSelection==null)return;let n={...e,...t};this._replaceByParam(n),this._textSelection$.next(n);let{unitId:r,subUnitId:a,segmentId:o,style:s,textRanges:c,rectRanges:l,isEditing:u}=n,d=[...c,...l].filter(e=>e.startOffset!=null&&e.endOffset!=null).sort((e,t)=>e.startOffset>t.startOffset?1:e.startOffset<t.startOffset?-1:0);this._commandService.executeCommand(i.id,{unitId:r,subUnitId:a,segmentId:o,style:s,isEditing:u,ranges:d})}dispose(){this._textSelection$.complete(),this._refreshSelection$.complete()}_setCurrentSelectionNotRefresh(e){this._currentSelection=e}_getTextRanges(e){var t;if(e==null)return;let{unitId:n,subUnitId:r=``}=e;return(t=this._textSelectionInfo.get(n))==null?void 0:t.get(r)}_refresh(e){let t=this._getTextRanges(e);if(t==null)return;let{textRanges:n,rectRanges:r}=t,i=[...n,...r],{unitId:a,subUnitId:o}=e;this._refreshSelection$.next({unitId:a,subUnitId:o,docRanges:i,isEditing:!1})}_replaceByParam(e){let{unitId:t,subUnitId:n,...r}=e;this._textSelectionInfo.has(t)||this._textSelectionInfo.set(t,new Map),this._textSelectionInfo.get(t).set(n,{...r})}_addByParam(e){let{unitId:t,subUnitId:n,...r}=e;this._textSelectionInfo.has(t)||this._textSelectionInfo.set(t,new Map);let i=this._textSelectionInfo.get(t);i.has(n)?i.get(n).textRanges.push(...e.textRanges):i.set(n,{...r})}};d=u([l(0,t.ICommandService),l(1,t.IUniverInstanceService)],d);let f=class extends t.RxDisposable{constructor(e,n,i){super(),this._context=e,this._localeService=n,this._univerInstanceService=i,c(this,`_skeleton`,void 0),c(this,`_docViewModel`,void 0),c(this,`_currentSkeleton$`,new r.BehaviorSubject(null)),c(this,`currentSkeleton$`,this._currentSkeleton$.asObservable()),c(this,`_currentSkeletonBefore$`,new r.BehaviorSubject(null)),c(this,`currentSkeletonBefore$`,this._currentSkeletonBefore$.asObservable()),c(this,`_currentViewModel$`,new r.BehaviorSubject(null)),c(this,`currentViewModel$`,this._currentViewModel$.asObservable()),this._init(),this._univerInstanceService.getCurrentTypeOfUnit$(t.UniverInstanceType.UNIVER_DOC).pipe((0,r.takeUntil)(this.dispose$)).subscribe(e=>{e&&e.getUnitId()===this._context.unitId&&this._update(e)})}dispose(){super.dispose(),this._currentSkeletonBefore$.complete(),this._currentSkeleton$.complete()}getSkeleton(){return this._skeleton}getViewModel(){return this._docViewModel}_init(){let e=this._context.unit;this._update(e)}_update(e){let n=this._context.unitId;if(e.getBody()==null)return;this._docViewModel&&(0,t.isInternalEditorID)(n)?(this._docViewModel.reset(e),this._context.unit=e):this._docViewModel||(this._docViewModel=this._buildDocViewModel(e)),this._skeleton||(this._skeleton=this._buildSkeleton(this._docViewModel));let r=this._skeleton;r.calculate(),this._currentSkeletonBefore$.next(r),this._currentSkeleton$.next(r),this._currentViewModel$.next(this._docViewModel)}_buildSkeleton(e){return n.DocumentSkeleton.create(e,this._localeService)}_buildDocViewModel(e){return new n.DocumentViewModel(e)}};f=u([l(1,(0,t.Inject)(t.LocaleService)),l(2,t.IUniverInstanceService)],f);var p=class extends t.RxDisposable{constructor(){super(),c(this,`_docStateChangeParams$`,new r.BehaviorSubject(null)),c(this,`docStateChangeParams$`,this._docStateChangeParams$.asObservable())}emitStateChangeInfo(e){this._docStateChangeParams$.next(e)}dispose(){super.dispose(),this._docStateChangeParams$.complete()}};let m=`doc.mutation.rich-text-editing`,h={id:m,type:t.CommandType.MUTATION,handler:(e,r,i)=>{var a,o;let{unitId:s,segmentId:c=``,actions:l,textRanges:u,prevTextRanges:h,trigger:g,noHistory:_,isCompositionEnd:v,noNeedSetTextRange:y,debounce:b,isEditing:x=!0,isSync:S,syncer:C}=r,w=S||(i==null?void 0:i.fromCollab)||(i==null?void 0:i.fromChangeset),T=e.get(t.IUniverInstanceService),E=e.get(n.IRenderManagerService),D=e.get(p),O=T.getUnit(s,t.UniverInstanceType.UNIVER_DOC),k=(a=E.getRenderUnitById(s))==null?void 0:a.with(f).getViewModel();if(O==null)throw Error(`DocumentDataModel not found for unitId: ${s}`);let A=e.get(d),j=(o=A.getDocRanges())==null?[]:o,M=!!O.getSnapshot().disabled;if(t.JSONX.isNoop(l)||l&&l.length===0||M)return{unitId:s,actions:[],textRanges:j};let N=t.JSONX.invertWithDoc(l,O.getSnapshot());O.apply(l),k==null||k.reset(O),!y&&u&&g!=null&&!w&&queueMicrotask(()=>{A.replaceDocRanges(u,{unitId:s,subUnitId:s},x,r.options)});let P={commandId:m,unitId:s,segmentId:c,trigger:g,noHistory:_,debounce:b,redoState:{actions:l,textRanges:u},undoState:{actions:N,textRanges:h==null?j:h},isCompositionEnd:v,isSync:w,syncer:C};return D.emitStateChangeInfo(P),{unitId:s,actions:N,textRanges:j}}},g={id:`doc.command.insert-text`,type:t.CommandType.COMMAND,handler:(e,n)=>{var r,i;let a=e.get(t.ICommandService),{range:o,segmentId:s,body:c,unitId:l,cursorOffset:u}=n,f=e.get(d),p=e.get(t.IUniverInstanceService).getUnit(l,t.UniverInstanceType.UNIVER_DOC);if(p==null)return!1;let m=f.getActiveTextRange(),g=(r=p.getSelfOrHeaderFooterModel((i=m==null?void 0:m.segmentId)==null?``:i))==null?void 0:r.getBody();if(g==null)return!1;let{startOffset:_,collapsed:v}=o,y=u==null?c.dataStream.length:u,b=[{startOffset:_+y,endOffset:_+y,style:m==null?void 0:m.style,collapsed:v}],x={id:h.id,params:{unitId:l,actions:[],textRanges:b,debounce:!0}},S=new t.TextX,C=t.JSONX.getInstance();if(v)_>0&&S.push({t:t.TextXActionType.RETAIN,len:_}),S.push({t:t.TextXActionType.INSERT,body:c,len:c.dataStream.length});else{let e=t.BuildTextUtils.selection.delete([o],g,0,c);S.push(...e)}x.params.textRanges=[{startOffset:_+y,endOffset:_+y,collapsed:v}];let w=(0,t.getRichTextEditPath)(p,s);return x.params.actions=C.editOp(S.serialize(),w),!!a.syncExecuteCommand(x.id,x.params)}},_={id:`doc.command.delete-text`,type:t.CommandType.COMMAND,handler:(e,n)=>{var r,i;let a=e.get(t.ICommandService),o=e.get(t.IUniverInstanceService),{range:s,segmentId:c,unitId:l,direction:u,len:d=1}=n,f=o.getUnit(l,t.UniverInstanceType.UNIVER_DOC),p=f==null||(r=f.getSelfOrHeaderFooterModel(c))==null?void 0:r.getBody();if(f==null||p==null)return!1;let{startOffset:m}=s,g=u===t.DeleteDirection.LEFT?m-d:m,_=u===t.DeleteDirection.LEFT?m-1:m+d-1,v=(i=p.customRanges)==null?void 0:i.find(e=>e.startIndex<=g&&e.endIndex>=_);v!=null&&v.wholeEntity&&(g=v.startIndex,_=Math.max(_,v.endIndex));let y={id:h.id,params:{unitId:l,actions:[],textRanges:[{startOffset:g,endOffset:g,collapsed:!0}],debounce:!0}},b=new t.TextX,x=t.JSONX.getInstance();b.push({t:t.TextXActionType.RETAIN,len:g-0}),b.push({t:t.TextXActionType.DELETE,len:_-g+1});let S=(0,t.getRichTextEditPath)(f,c);return y.params.actions=x.editOp(b.serialize(),S),!!a.syncExecuteCommand(y.id,y.params)}},v={id:`doc.command.update-text`,type:t.CommandType.COMMAND,handler:(e,n)=>{let{range:r,segmentId:i,updateBody:a,coverType:o,unitId:s,textRanges:c}=n,l=e.get(t.ICommandService),u=e.get(t.IUniverInstanceService).getCurrentUnitOfType(t.UniverInstanceType.UNIVER_DOC);if(u==null)return!1;let d={id:h.id,params:{unitId:s,actions:[],textRanges:c}},f=new t.TextX,p=t.JSONX.getInstance(),{startOffset:m,endOffset:g}=r;f.push({t:t.TextXActionType.RETAIN,len:m}),f.push({t:t.TextXActionType.RETAIN,body:a,len:g-m,coverType:o});let _=(0,t.getRichTextEditPath)(u,i);return d.params.actions=p.editOp(f.serialize(),_),!!l.syncExecuteCommand(d.id,d.params)}},y=function(e){return e[e.FIRST_PAGE_HEADER=0]=`FIRST_PAGE_HEADER`,e[e.FIRST_PAGE_FOOTER=1]=`FIRST_PAGE_FOOTER`,e[e.DEFAULT_HEADER=2]=`DEFAULT_HEADER`,e[e.DEFAULT_FOOTER=3]=`DEFAULT_FOOTER`,e[e.EVEN_PAGE_HEADER=4]=`EVEN_PAGE_HEADER`,e[e.EVEN_PAGE_FOOTER=5]=`EVEN_PAGE_FOOTER`,e}({});function b(){return{dataStream:`\r
|
|
2
|
+
`,textRuns:[{st:0,ed:0,ts:{fs:9}}],customBlocks:[],paragraphs:[{startIndex:0,paragraphId:(0,t.createParagraphId)(new Set),paragraphStyle:{spaceAbove:{v:0},lineSpacing:1.5,spaceBelow:{v:0}}}],sectionBreaks:[{startIndex:1}]}}function x(e,n,r,i,a=`single`){let o=t.JSONX.getInstance(),s=e==null?(0,t.generateRandomId)(6):e,c=n===2||n===0||n===4,l=o.insertOp([c?`headers`:`footers`,s],{[c?`headerId`:`footerId`]:s,body:b()});i.push(l);let u=`defaultHeaderId`,d=`defaultFooterId`;switch(n){case 2:u=`defaultHeaderId`,d=`defaultFooterId`;break;case 3:u=`defaultFooterId`,d=`defaultHeaderId`;break;case 0:u=`firstPageHeaderId`,d=`firstPageFooterId`;break;case 1:u=`firstPageFooterId`,d=`firstPageHeaderId`;break;case 4:u=`evenPageHeaderId`,d=`evenPageFooterId`;break;case 5:u=`evenPageFooterId`,d=`evenPageHeaderId`;break;default:throw Error(`Unknown header footer type: ${n}`)}let f=[[u,s]];if(a===`pair`&&d!=null){let e=(0,t.generateRandomId)(6),n=o.insertOp([c?`footers`:`headers`,e],{[c?`footerId`:`headerId`]:e,body:b()});i.push(n),f.push([d,e])}for(let[e,t]of f)if(r[e]!=null){let n=o.replaceOp([`documentStyle`,e],r[e],t);i.push(n)}else{let n=o.insertOp([`documentStyle`,e],t);i.push(n)}return i}let S={id:`doc.command.create-header-footer`,type:t.CommandType.COMMAND,handler:(e,n)=>{let r=e.get(t.ICommandService),i=e.get(t.IUniverInstanceService),{unitId:a,segmentId:o,createType:s,headerFooterProps:c,createMode:l=`single`}=n,u=i.getUnit(a,t.UniverInstanceType.UNIVER_DOC);if(u==null)return!1;let{documentStyle:d}=u.getSnapshot();if(d.documentFlavor===t.DocumentFlavor.MODERN)return!1;let f=[],p=t.JSONX.getInstance();if(s!=null&&x(o,s,d,f,l),c!=null&&Object.keys(c).forEach(e=>{let t=c[e],n=d[e];if(t===n)return;let r=n===void 0?p.insertOp([`documentStyle`,e],t):p.replaceOp([`documentStyle`,e],n,t);f.push(r)}),f.length===0)return!1;let m={id:h.id,params:{unitId:a,actions:f.reduce((e,n)=>t.JSONX.compose(e,n),null),textRanges:[{startOffset:0,endOffset:0,collapsed:!0}],debounce:!0}};return((c==null?void 0:c.marginFooter)!=null||(c==null?void 0:c.marginHeader)!=null)&&(m.params.noNeedSetTextRange=!0),!!r.syncExecuteCommand(m.id,m.params)}};var C=`@univerjs/docs`,w=`1.0.0-alpha.2`;let T={id:`doc.mutation.rename-doc`,type:t.CommandType.MUTATION,handler:(e,n)=>{let r=e.get(t.IUniverInstanceService).getUnit(n.unitId,t.UniverInstanceType.UNIVER_DOC);return r?(r.setName(n.name),!0):!1}},E={},D=class extends t.Disposable{constructor(e,t,n){super(),this._commandService=e,this._textSelectionManagerService=t,this._univerInstanceService=n,this._initSelectionChange()}_transformCustomRange(e,n){var r;let{startOffset:i,endOffset:a,collapsed:o}=n,s=(r=e.getCustomRanges())==null?void 0:r.filter(e=>!e.wholeEntity||i<=e.startIndex&&a>e.endIndex?!1:o?e.startIndex<i&&e.endIndex>=a:t.BuildTextUtils.range.isIntersects(i,a-1,e.startIndex,e.endIndex));if(s!=null&&s.length){let e=i,t=a;return s.forEach(n=>{e=Math.min(n.startIndex,e),t=Math.max(n.endIndex+1,t)}),{...n,startOffset:e,endOffset:t,collapsed:e===t}}return n}_initSelectionChange(){this.disposeWithMe(this._commandService.onCommandExecuted(e=>{if(e.id===i.id){let{unitId:t,ranges:n,isEditing:r}=e.params,i=this._univerInstanceService.getUnit(t);if(!i)return;let a=n.map(e=>this._transformCustomRange(i,e));a.some((e,t)=>n[t]!==e)&&this._textSelectionManagerService.replaceTextRanges(a,r)}}))}};D=u([l(0,t.ICommandService),l(1,(0,t.Inject)(d)),l(2,t.IUniverInstanceService)],D);var O=class extends t.Disposable{constructor(...e){super(...e),c(this,`_validators`,[]),c(this,`_transformers`,[])}registerValidator(e){return this._validators.push(e),this.disposeWithMe((0,t.toDisposable)(()=>(0,t.remove)(this._validators,e)))}registerTransformer(e){return this._transformers.push(e),this.disposeWithMe((0,t.toDisposable)(()=>(0,t.remove)(this._transformers,e)))}canMoveBlock(e){return this._validators.every(t=>t(e))}transformMoveResult(e){return this._transformers.reduce((t,n)=>n({...e,result:t}),e.result)}},k=class extends t.Disposable{constructor(...e){super(...e),c(this,`_range`,null)}setInsertRange(e){this._range=e}consumeInsertRange(e){if(!this._range||e&&this._range.unitId!==e)return null;let t=this._range;return this._range=null,t}clearInsertRange(){this._range=null}};let A=(0,t.createIdentifier)(`doc.state-change-interceptor-service`),j=class extends t.RxDisposable{constructor(e,t,n,i,a){super(),this._undoRedoService=e,this._commandService=t,this._univerInstanceService=n,this._docStateEmitService=i,this._docStateChangeInterceptorService=a,c(this,`_docStateChange$`,new r.BehaviorSubject(null)),c(this,`docStateChange$`,this._docStateChange$.asObservable()),c(this,`_historyStateCache`,new Map),c(this,`_changeStateCache`,new Map),c(this,`_historyTimer`,null),c(this,`_changeStateCacheTimer`,null),this._initialize(),this._listenDocStateChange()}getStateCache(e){var t,n;return{history:(t=this._historyStateCache.get(e))==null?[]:t,collaboration:(n=this._changeStateCache.get(e))==null?[]:n}}setStateCache(e,t){this._historyStateCache.set(e,t.history),this._changeStateCache.set(e,t.collaboration)}_setChangeState(e){this._cacheChangeState(e,`history`),this._cacheChangeState(e,`collaboration`)}_initialize(){this.disposeWithMe(this._commandService.beforeCommandExecuted(e=>{if(e.id===t.UndoCommandId||e.id===t.RedoCommandId){let e=this._univerInstanceService.getCurrentUnitOfType(t.UniverInstanceType.UNIVER_DOC);if(e==null)return;let n=e.getUnitId();this._pushHistory(n),this._emitChangeState(n)}}))}_listenDocStateChange(){this._docStateEmitService.docStateChangeParams$.pipe((0,r.takeUntil)(this.dispose$)).subscribe(e=>{var t,n;if(e==null)return;let r=(t=(n=this._docStateChangeInterceptorService)==null?void 0:n.transformChangeStateInfo(e))==null?e:t;if(r==null||r.isSync)return;let{isCompositionEnd:i,isSync:a,syncer:o,...s}=r;this._setChangeState(s)})}_cacheChangeState(e,n=`history`){let{trigger:r,unitId:i,noHistory:a,debounce:o=!1}=e;if(a||n===`history`&&r==null||n===`history`&&(r===t.RedoCommandId||r===t.UndoCommandId))return;let s=n===`history`?this._historyStateCache:this._changeStateCache,c=n===`history`?this._pushHistory.bind(this):this._emitChangeState.bind(this);if(s.has(i)){let t=s.get(i);t==null||t.push(e)}else s.set(i,[e]);o?n===`history`?(this._historyTimer&&clearTimeout(this._historyTimer),this._historyTimer=setTimeout(()=>{c(i)},300)):(this._changeStateCacheTimer&&clearTimeout(this._changeStateCacheTimer),this._changeStateCacheTimer=setTimeout(()=>{c(i)},300)):c(i)}_pushHistory(e){let n=this._undoRedoService,r=this._historyStateCache.get(e);if(n==null||!Array.isArray(r)||r.length===0)return;let i=r.length,a=r[0].commandId,o=r[0],s=r[i-1],c={unitId:e,actions:r.reduce((e,n)=>t.JSONX.compose(e,n.redoState.actions),null),textRanges:s.redoState.textRanges},l={unitId:e,actions:r.reverse().reduce((e,n)=>t.JSONX.compose(e,n.undoState.actions),null),textRanges:o.undoState.textRanges};n.pushUndoRedo({unitID:e,undoMutations:[{id:a,params:l}],redoMutations:[{id:a,params:c}]}),r.length=0}_emitChangeState(e){let n=this._changeStateCache.get(e);if(!Array.isArray(n)||n.length===0)return;let r=n.length,{commandId:i,trigger:a,segmentId:o,noHistory:s,debounce:c}=n[0],l=n[0],u=n[r-1],d={commandId:i,unitId:e,trigger:a,redoState:{unitId:e,actions:n.reduce((e,n)=>t.JSONX.compose(e,n.redoState.actions),null),textRanges:u.redoState.textRanges},undoState:{unitId:e,actions:n.reverse().reduce((e,n)=>t.JSONX.compose(e,n.undoState.actions),null),textRanges:l.undoState.textRanges},segmentId:o,noHistory:s,debounce:c};n.length=0,this._docStateChange$.next(d)}};j=u([l(0,(0,t.Optional)(t.IUndoRedoService)),l(1,t.ICommandService),l(2,t.IUniverInstanceService),l(3,(0,t.Inject)(p)),l(4,(0,t.Optional)(A))],j);let M=class extends t.Plugin{constructor(e=E,n,r){super(),this._config=e,this._injector=n,this._configService=r;let{...i}=(0,t.merge)({},E,this._config);this._configService.setConfig(`docs.config`,i)}onStarting(){this._initializeDependencies(),this._initializeCommands()}_initializeCommands(){[g,_,v,S,h,T,i].forEach(e=>{this._injector.get(t.ICommandService).registerCommand(e)})}_initializeDependencies(){[[d],[p],[j],[O],[k],[D]].forEach(e=>this._injector.add(e))}onReady(){this._injector.get(j),this._injector.get(D)}};c(M,`pluginName`,`DOCS_PLUGIN`),c(M,`packageName`,C),c(M,`version`,w),M=u([l(1,(0,t.Inject)(t.Injector)),l(2,t.IConfigService)],M);let N={CUSTOM_RANGE:(0,t.createInterceptorKey)(`CUSTOM_RANGE`),CUSTOM_DECORATION:(0,t.createInterceptorKey)(`CUSTOM_DECORATION`)},P=class extends t.Disposable{constructor(e,n){super(),this._context=e,this._docSkeletonManagerService=n,c(this,`_interceptorsByName`,new Map);let r=this._docSkeletonManagerService.getViewModel(),i=r.getDataModel().getUnitId();if(i===t.DOCS_NORMAL_EDITOR_UNIT_ID_KEY||i===t.DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY)return;this.disposeWithMe(this.interceptDocumentViewModel(r)),this.disposeWithMe(this.intercept(N.CUSTOM_RANGE,{priority:-1,handler:(e,t,n)=>n(e)}));let a=new t.DisposableCollection;r.segmentViewModels$.subscribe(e=>{a.dispose(),a=new t.DisposableCollection,e.forEach(e=>{a.add(this.interceptDocumentViewModel(e))})}),this.disposeWithMe(a)}intercept(e,n){let r=e;this._interceptorsByName.has(r)||this._interceptorsByName.set(r,[]);let i=this._interceptorsByName.get(r);return i.push(n),this._interceptorsByName.set(r,i.sort((e,t)=>{var n,r;return((n=t.priority)==null?0:n)-((r=e.priority)==null?0:r)})),this.disposeWithMe((0,t.toDisposable)(()=>(0,t.remove)(this._interceptorsByName.get(r),n)))}fetchThroughInterceptors(e){let n=e;return(0,t.composeInterceptors)(this._interceptorsByName.get(n)||[])}interceptDocumentViewModel(e){let n=new t.DisposableCollection;return n.add(e.registerCustomRangeInterceptor({getCustomRange:t=>{var n;return this.fetchThroughInterceptors(N.CUSTOM_RANGE)(e.getCustomRangeRaw(t),{index:t,unitId:e.getDataModel().getUnitId(),customRanges:(n=e.getDataModel().getCustomRanges())==null?[]:n})},getCustomDecoration:t=>{var n;return this.fetchThroughInterceptors(N.CUSTOM_DECORATION)(e.getCustomDecorationRaw(t),{index:t,unitId:e.getDataModel().getUnitId(),customDecorations:(n=e.getDataModel().getCustomDecorations())==null?[]:n})}})),n}};P=u([l(1,(0,t.Inject)(f))],P);function F(e,n,r){let{unitId:i,segmentId:a}=n,o=e.get(t.IUniverInstanceService).getUnit(i);if(!o)return!1;let s={id:h.id,params:{unitId:n.unitId,actions:[],textRanges:void 0}},c=t.JSONX.getInstance(),l=t.BuildTextUtils.customRange.add({...n,body:r});if(!l)return!1;let u=(0,t.getRichTextEditPath)(o,a);return s.params.actions=c.editOp(l.serialize(),u),s}function I(e,n){var r,i;let{rangeId:a,rangeType:o,wholeEntity:s,properties:c,unitId:l,selections:u}=n,f=e.get(d),p=e.get(t.IUniverInstanceService),m=u==null?f.getTextRanges({unitId:l,subUnitId:l}):u,g=m==null||(r=m[0])==null?void 0:r.segmentId;if(!(m!=null&&m.length))return!1;let _=p.getUnit(l,t.UniverInstanceType.UNIVER_DOC);if(!_)return!1;let v=(i=_.getSelfOrHeaderFooterModel(g))==null?void 0:i.getBody();if(!v)return!1;let y=t.BuildTextUtils.customRange.add({ranges:m,rangeId:a,rangeType:o,segmentId:g,wholeEntity:s,properties:c,body:v});if(!y)return!1;let b=t.JSONX.getInstance(),x={id:h.id,params:{unitId:l,actions:[],textRanges:y.selections,segmentId:g},textX:y},S=(0,t.getRichTextEditPath)(_,g);return x.params.actions=b.editOp(y.serialize(),S),x}function L(e,n){let{unitId:r,segmentId:i,insert:a}=n,o=e.get(t.IUniverInstanceService).getUnit(r);if(!o)return!1;let s={id:h.id,params:{unitId:n.unitId,actions:[],textRanges:void 0,segmentId:i}},c=t.JSONX.getInstance(),l=t.BuildTextUtils.customRange.delete({documentDataModel:o,rangeId:n.rangeId,insert:a,segmentId:i});if(!l)return!1;let u=(0,t.getRichTextEditPath)(o,i);return s.params.actions=c.editOp(l.serialize(),u),s.params.textRanges=l.selections,s}function R(e,n){var r,i,a,o;let{unitId:s,body:c,doc:l}=n,u=l;if(u||(u=e.get(t.IUniverInstanceService).getUnit(s)),!u)return!1;let f=(r=n.selection)==null?void 0:r.segmentId,p=(i=u.getSelfOrHeaderFooterModel(f))==null?void 0:i.getBody();if(!p)return!1;let m=e.get(d),g=(a=n.selection)==null?m.getActiveTextRange():a;if(!g||!p)return!1;let _=(o=n.textRanges)==null?[{startOffset:g.startOffset+c.dataStream.length,endOffset:g.startOffset+c.dataStream.length,collapsed:!0,segmentId:f}]:o,v=t.BuildTextUtils.selection.replace({selection:g,body:c,doc:u});if(!v)return!1;let y={id:h.id,params:{unitId:s,actions:[],textRanges:_,debounce:!0,segmentId:f},textX:v},b=t.JSONX.getInstance();return y.params.actions=b.editOp(v.serialize()),y}function z(e,t){try{return e.get(k).consumeInsertRange(t)}catch{return null}}function B(e){return!!(e!=null&&e.segmentId)}e.CreateHeaderFooterCommand=S,e.DOC_INTERCEPTOR_POINT=N,e.DeleteTextCommand=_,e.DocBlockMoveValidatorService=O,e.DocContentInsertService=k,Object.defineProperty(e,"DocInterceptorService",{enumerable:!0,get:function(){return P}}),Object.defineProperty(e,"DocSelectionManagerService",{enumerable:!0,get:function(){return d}}),Object.defineProperty(e,"DocSkeletonManagerService",{enumerable:!0,get:function(){return f}}),Object.defineProperty(e,"DocStateChangeManagerService",{enumerable:!0,get:function(){return j}}),e.DocStateEmitService=p,e.HeaderFooterType=y,e.IDocStateChangeInterceptorService=A,e.InsertTextCommand=g,e.RichTextEditingMutation=h,e.SetTextSelectionsOperation=i,Object.defineProperty(e,"UniverDocsPlugin",{enumerable:!0,get:function(){return M}}),e.UpdateTextCommand=v,e.addCustomRangeBySelectionFactory=I,e.addCustomRangeFactory=F,e.consumeContentInsertRange=z,e.deleteCustomRangeFactory=L,e.isHeaderFooterSelection=B,e.replaceSelectionFactory=R});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@univerjs/docs",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.2",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Core document model and rich-text operations for Univer Docs.",
|
|
6
6
|
"author": "DreamNum Co., Ltd. <developer@univer.ai>",
|
|
@@ -62,14 +62,14 @@
|
|
|
62
62
|
"rxjs": ">=7.0.0"
|
|
63
63
|
},
|
|
64
64
|
"dependencies": {
|
|
65
|
-
"@univerjs/
|
|
66
|
-
"@univerjs/
|
|
65
|
+
"@univerjs/engine-render": "1.0.0-alpha.2",
|
|
66
|
+
"@univerjs/core": "1.0.0-alpha.2"
|
|
67
67
|
},
|
|
68
68
|
"devDependencies": {
|
|
69
69
|
"rxjs": "^7.8.2",
|
|
70
70
|
"typescript": "^6.0.3",
|
|
71
71
|
"vitest": "^4.1.9",
|
|
72
|
-
"@univerjs-infra/shared": "1.0.0-alpha.
|
|
72
|
+
"@univerjs-infra/shared": "1.0.0-alpha.2"
|
|
73
73
|
},
|
|
74
74
|
"scripts": {
|
|
75
75
|
"test": "vitest run",
|