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

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 CHANGED
@@ -3,364 +3,243 @@ let _univerjs_core = require("@univerjs/core");
3
3
  let _univerjs_core_facade = require("@univerjs/core/facade");
4
4
  let _univerjs_docs = require("@univerjs/docs");
5
5
 
6
- //#region src/facade/doc-element-registry.ts
7
- const PARAGRAPH_REGISTRY_MIGRATION_ERROR = "DocElementRegistry no longer tracks paragraph identity; use paragraphId.";
6
+ //#region src/facade/f-document-element.ts
8
7
  /**
9
- * Error thrown when a facade element key can no longer be resolved uniquely.
10
- *
11
- * A stale paragraph usually means the paragraph was deleted, or the document no
12
- * longer contains exactly one paragraph with the requested `paragraphId`.
13
- *
14
- * @example
15
- * ```ts
16
- * const doc = univerAPI.getActiveDocument();
17
- * if (!doc) throw new Error('No active document');
18
- *
19
- * const paragraph = doc.getBody().getChild(0).asParagraph();
20
- * paragraph.removeFromParent();
21
- *
22
- * try {
23
- * paragraph.getText();
24
- * } catch (error) {
25
- * if (error instanceof DocElementStaleError) {
26
- * console.log('The paragraph handle is stale.');
27
- * }
28
- * }
29
- * ```
30
- */
31
- var DocElementStaleError = class extends Error {
32
- /**
33
- * Create a stale element error.
34
- * @param {string} message The error message.
35
- */
36
- constructor(message = "Doc element is stale") {
37
- super(message);
38
- this.name = "DocElementStaleError";
39
- }
40
- };
41
- /**
42
- * @deprecated Paragraph facade identity is now resolved directly from persisted
43
- * `paragraphId` values. This class remains as a compatibility shell for callers
44
- * that constructed document facade internals directly.
8
+ * A generic top-level document body element.
45
9
  *
46
- * @hideconstructor
47
- */
48
- var DocElementRegistry = class {
49
- /**
50
- * @deprecated Paragraph facade identity is now the persisted `paragraphId`.
51
- * @throws {Error} Always throws; use `paragraph.paragraphId` instead.
52
- */
53
- getParagraphKey(_segmentId, _body, _paragraphIndex) {
54
- throw new Error(PARAGRAPH_REGISTRY_MIGRATION_ERROR);
55
- }
56
- /**
57
- * @deprecated Paragraph facade identity is now the persisted `paragraphId`.
58
- * @throws {Error} Always throws; resolve paragraph handles by `paragraphId` instead.
59
- */
60
- resolveParagraphStartIndex(_segmentId, _key) {
61
- throw new Error(PARAGRAPH_REGISTRY_MIGRATION_ERROR);
62
- }
63
- /**
64
- * @deprecated Paragraph facade identity is now the persisted `paragraphId`.
65
- * @throws {Error} Always throws; resolve paragraph handles by `paragraphId` instead.
66
- */
67
- syncParagraph(_segmentId, _key, _body) {
68
- throw new Error(PARAGRAPH_REGISTRY_MIGRATION_ERROR);
69
- }
70
- /**
71
- * @deprecated Paragraph facade identity is now the persisted `paragraphId`.
72
- * @throws {Error} Always throws; stale state is detected from live `paragraphId` lookups.
73
- */
74
- markStale(_segmentId, _key) {
75
- throw new Error(PARAGRAPH_REGISTRY_MIGRATION_ERROR);
76
- }
77
- /**
78
- * @deprecated Paragraph facade identity is now the persisted `paragraphId`.
79
- * @throws {Error} Always throws; text edits no longer need registry offset tracking.
80
- */
81
- beforeTextEdit(_segmentId, _startOffset, _endOffset, _insertLength) {
82
- throw new Error(PARAGRAPH_REGISTRY_MIGRATION_ERROR);
83
- }
84
- };
85
-
86
- //#endregion
87
- //#region src/facade/utils.ts
88
- function cloneParagraphStyle(paragraphStyle) {
89
- return paragraphStyle == null ? paragraphStyle : JSON.parse(JSON.stringify(paragraphStyle));
90
- }
91
- function normalizePlainTextDataStream(dataStream) {
92
- return dataStream.replace(/\r\n/g, "\r").replace(/\n/g, "\r");
93
- }
94
- function getRemovedLeadingParagraphBreakLength(dataStream, removeLeadingParagraphBreak) {
95
- const normalized = normalizePlainTextDataStream(dataStream);
96
- if (removeLeadingParagraphBreak && normalized.length > 1 && normalized.startsWith("\r")) return 1;
97
- return 0;
98
- }
99
- function getNormalizedPlainTextCursorOffset(dataStream, cursorOffset, removeLeadingParagraphBreak) {
100
- const normalizedPrefixLength = normalizePlainTextDataStream(dataStream.slice(0, cursorOffset)).length;
101
- return Math.max(0, normalizedPrefixLength - getRemovedLeadingParagraphBreakLength(dataStream, removeLeadingParagraphBreak));
102
- }
103
- function getParagraphStyleAtOffset(body, offset) {
104
- var _body$paragraphs, _paragraphs$find;
105
- const paragraphs = (_body$paragraphs = body.paragraphs) !== null && _body$paragraphs !== void 0 ? _body$paragraphs : [];
106
- const paragraph = (_paragraphs$find = paragraphs.find((item) => item.startIndex >= offset)) !== null && _paragraphs$find !== void 0 ? _paragraphs$find : paragraphs[paragraphs.length - 1];
107
- return paragraph === null || paragraph === void 0 ? void 0 : paragraph.paragraphStyle;
108
- }
109
- function buildPlainTextInsertBody(dataStream, options = {}) {
110
- const normalizedDataStream = normalizePlainTextDataStream(dataStream).slice(getRemovedLeadingParagraphBreakLength(dataStream, options.removeLeadingParagraphBreak));
111
- const body = {
112
- dataStream: normalizedDataStream,
113
- customDecorations: [],
114
- customRanges: [],
115
- textRuns: []
116
- };
117
- const paragraphs = [];
118
- const existingParagraphIds = /* @__PURE__ */ new Set();
119
- for (let index = 0; index < normalizedDataStream.length; index++) if (normalizedDataStream[index] === "\r") paragraphs.push({
120
- startIndex: index,
121
- paragraphId: (0, _univerjs_core.createParagraphId)(existingParagraphIds),
122
- ...options.paragraphStyle == null ? {} : { paragraphStyle: cloneParagraphStyle(options.paragraphStyle) }
123
- });
124
- if (paragraphs.length > 0) body.paragraphs = paragraphs;
125
- return body;
126
- }
127
-
128
- //#endregion
129
- //#region src/facade/f-doc-block-range.ts
130
- /**
131
- * A facade wrapper for document block ranges, such as callout, quote, and code blocks.
10
+ * Use this wrapper when you need to inspect an element type first, navigate to
11
+ * neighboring elements, or cast the element to a more specific facade wrapper.
132
12
  *
133
- * Block range identity is backed by the persisted `IDocumentBlockRange.blockId`,
134
- * so wrappers can be re-resolved after text is inserted before the block range.
13
+ * Paragraph keys are persisted `paragraphId` values. Tables, block ranges, and
14
+ * custom blocks use their persisted ids.
135
15
  *
136
16
  * @hideconstructor
137
17
  */
138
- var FDocBlockRange = class {
139
- constructor(_body, _key) {
18
+ var FDocumentElement = class extends _univerjs_core_facade.FBase {
19
+ constructor(_body, _bodyEdit, _info, _injector) {
20
+ super();
140
21
  this._body = _body;
141
- this._key = _key;
22
+ this._bodyEdit = _bodyEdit;
23
+ this._info = _info;
24
+ this._injector = _injector;
142
25
  }
143
26
  /**
144
27
  * Get the document element type.
145
- * @returns {'blockRange'} The literal block range element type.
28
+ * @returns {DocumentBlockType} The element type, such as `paragraph`, `table`, `blockRange`, or `customBlock`.
146
29
  * @example
147
30
  * ```ts
148
- * const doc = univerAPI.getActiveDocument();
149
- * if (!doc) throw new Error('No active document');
150
- *
151
- * const blockRange = doc.getBody().getChild(0).asBlockRange();
152
- * console.log(blockRange.getType());
31
+ * const fDocument = univerAPI.getActiveDocument();
32
+ * const fDocumentBody = fDocument.getBody();
33
+ * const element = fDocumentBody.getElement(0);
34
+ * console.log(element?.getType());
153
35
  * ```
154
36
  */
155
37
  getType() {
156
- return "blockRange";
38
+ return this._info.type;
157
39
  }
158
40
  /**
159
- * Get the block range key.
160
- * @returns {string} The persisted `blockId` for this block range.
41
+ * Whether this element is a paragraph.
42
+ * @returns {boolean} `true` if this element is a paragraph.
161
43
  * @example
162
44
  * ```ts
163
- * const doc = univerAPI.getActiveDocument();
164
- * if (!doc) throw new Error('No active document');
165
- *
166
- * const blockRange = doc.getBody().getChild(0).asBlockRange();
167
- * console.log(blockRange.getKey());
45
+ * const fDocument = univerAPI.getActiveDocument();
46
+ * const fDocumentBody = fDocument.getBody();
47
+ * const element = fDocumentBody.getElement(0);
48
+ * console.log(element?.isParagraph());
168
49
  * ```
169
50
  */
170
- getKey() {
171
- return this._key;
51
+ isParagraph() {
52
+ return this._info.type === _univerjs_core.DocumentBlockType.PARAGRAPH;
172
53
  }
173
54
  /**
174
- * Get the parent body facade that owns this block range.
175
- * @returns {FDocBody} The document body facade.
55
+ * Whether this element is a table.
56
+ * @returns {boolean} `true` if this element is a table.
176
57
  * @example
177
58
  * ```ts
178
- * const doc = univerAPI.getActiveDocument();
179
- * if (!doc) throw new Error('No active document');
180
- *
181
- * const blockRange = doc.getBody().getChild(0).asBlockRange();
182
- * console.log(blockRange.getParent().getChildIndex(blockRange));
59
+ * const fDocument = univerAPI.getActiveDocument();
60
+ * const fDocumentBody = fDocument.getBody();
61
+ * const element = fDocumentBody.getElement(0);
62
+ * console.log(element?.isTable());
183
63
  * ```
184
64
  */
185
- getParent() {
186
- return this._body;
65
+ isTable() {
66
+ return this._info.type === _univerjs_core.DocumentBlockType.TABLE;
187
67
  }
188
68
  /**
189
- * Remove this block range and its content from the parent body.
190
- * @returns {boolean} `true` if the block range content was removed.
69
+ * Whether this element is a block range, such as a callout, quote, or code block.
70
+ * @returns {boolean} `true` if this element is a block range.
191
71
  * @example
192
72
  * ```ts
193
- * const doc = univerAPI.getActiveDocument();
194
- * if (!doc) throw new Error('No active document');
195
- *
196
- * const blockRange = doc.getBody().getChild(0).asBlockRange();
197
- * blockRange.removeFromParent();
73
+ * const fDocument = univerAPI.getActiveDocument();
74
+ * const fDocumentBody = fDocument.getBody();
75
+ * const element = fDocumentBody.getElement(0);
76
+ * console.log(element?.isBlockRange());
198
77
  * ```
199
78
  */
200
- removeFromParent() {
201
- return this._body.removeBlockRange(this._key);
79
+ isBlockRange() {
80
+ return this._info.type === _univerjs_core.DocumentBlockType.BLOCK_RANGE;
202
81
  }
203
82
  /**
204
- * Get the block range type.
205
- * @returns {DocumentBlockRangeType} The block type, such as callout, quote, or code.
83
+ * Whether this element is a custom block.
84
+ * @returns {boolean} `true` if this element is a custom block.
206
85
  * @example
207
86
  * ```ts
208
- * const doc = univerAPI.getActiveDocument();
209
- * if (!doc) throw new Error('No active document');
210
- *
211
- * const blockRange = doc.getBody().getChild(0).asBlockRange();
212
- * console.log(blockRange.getBlockType());
87
+ * const fDocument = univerAPI.getActiveDocument();
88
+ * const fDocumentBody = fDocument.getBody();
89
+ * const element = fDocumentBody.getElement(0);
90
+ * console.log(element?.isCustomBlock());
213
91
  * ```
214
92
  */
215
- getBlockType() {
216
- return this._body.getBlockRange(this._key).blockType;
93
+ isCustomBlock() {
94
+ return this._info.type === _univerjs_core.DocumentBlockType.CUSTOM_BLOCK;
217
95
  }
218
96
  /**
219
- * Get the plain text inside this block range.
220
- * @returns {string} The block range text.
97
+ * Get the facade key used to resolve this element.
98
+ * @returns {string} The paragraph `paragraphId` or persisted table/block/custom block id.
221
99
  * @example
222
100
  * ```ts
223
- * const doc = univerAPI.getActiveDocument();
224
- * if (!doc) throw new Error('No active document');
225
- *
226
- * const blockRange = doc.getBody().getChild(0).asBlockRange();
227
- * console.log(blockRange.getText());
101
+ * const fDocument = univerAPI.getActiveDocument();
102
+ * const fDocumentBody = fDocument.getBody();
103
+ * const element = fDocumentBody.getElement(0);
104
+ * console.log(element?.getKey());
228
105
  * ```
229
106
  */
230
- getText() {
231
- return this._body.getBlockRangeText(this._key);
107
+ getKey() {
108
+ return this._info.key;
232
109
  }
233
110
  /**
234
- * Replace the plain text inside this block range.
235
- * @param {string} text The replacement text.
236
- * @returns {boolean} `true` if the block range text was replaced.
111
+ * Get the parent body facade that owns this element.
112
+ * @returns {FDocumentBody} The document body facade.
237
113
  * @example
238
114
  * ```ts
239
- * const doc = univerAPI.getActiveDocument();
240
- * if (!doc) throw new Error('No active document');
241
- *
242
- * const blockRange = doc.getBody().getChild(0).asBlockRange();
243
- * blockRange.setText('Updated block text');
115
+ * const fDocument = univerAPI.getActiveDocument();
116
+ * const fDocumentBody = fDocument.getBody();
117
+ * const element = fDocumentBody.getElement(0);
118
+ * console.log(element?.getParent());
244
119
  * ```
245
120
  */
246
- setText(text) {
247
- return this._body.setBlockRangeText(this._key, text);
121
+ getParent() {
122
+ return this._body;
248
123
  }
249
124
  /**
250
- * Remove this block range wrapper from the body.
251
- *
252
- * This currently removes the block range and its content, matching
253
- * `removeFromParent()`.
254
- *
255
- * @returns {boolean} `true` if the block range content was removed.
125
+ * Get the resolved element info for this wrapper.
126
+ * @returns {IFDocumentElementInfo} The resolved element info, including type, key, position, and priority.
256
127
  * @example
257
128
  * ```ts
258
- * const doc = univerAPI.getActiveDocument();
259
- * if (!doc) throw new Error('No active document');
260
- *
261
- * const blockRange = doc.getBody().getChild(0).asBlockRange();
262
- * blockRange.unwrap();
129
+ * const fDocument = univerAPI.getActiveDocument();
130
+ * const fDocumentBody = fDocument.getBody();
131
+ * const element = fDocumentBody.getElement(0);
132
+ * console.log(element?.getResolvedInfo());
263
133
  * ```
264
134
  */
265
- unwrap() {
266
- return this.removeFromParent();
267
- }
268
- };
269
-
270
- //#endregion
271
- //#region src/facade/f-doc-custom-block.ts
272
- /**
273
- * A facade wrapper for a document custom block, such as an embedded drawing or widget.
274
- *
275
- * Custom block identity is backed by the persisted `ICustomBlock.blockId`, so the
276
- * wrapper can be re-resolved after text is inserted before the custom block.
277
- *
278
- * @hideconstructor
279
- */
280
- var FDocCustomBlock = class {
281
- constructor(_body, _key) {
282
- this._body = _body;
283
- this._key = _key;
135
+ getResolvedInfo() {
136
+ return this._info;
284
137
  }
285
138
  /**
286
- * Get the document element type.
287
- * @returns {'customBlock'} The literal custom block element type.
139
+ * Get the next sibling element in the current body order.
140
+ * @returns {FDocumentElement | null} The next sibling wrapper, or `null` when this is the last child.
288
141
  * @example
289
142
  * ```ts
290
- * const doc = univerAPI.getActiveDocument();
291
- * if (!doc) throw new Error('No active document');
292
- *
293
- * const customBlock = doc.getBody().getChild(0).asCustomBlock();
294
- * console.log(customBlock.getType());
143
+ * const fDocument = univerAPI.getActiveDocument();
144
+ * const fDocumentBody = fDocument.getBody();
145
+ * const element = fDocumentBody.getElement(0);
146
+ * console.log(element?.getNextSibling());
295
147
  * ```
296
148
  */
297
- getType() {
298
- return "customBlock";
149
+ getNextSibling() {
150
+ return this._createSibling(1);
299
151
  }
300
152
  /**
301
- * Get the custom block key.
302
- * @returns {string} The persisted `blockId` for this custom block.
153
+ * Get the previous sibling element in the current body order.
154
+ * @returns {FDocumentElement | null} The previous sibling wrapper, or `null` when this is the first child.
303
155
  * @example
304
156
  * ```ts
305
- * const doc = univerAPI.getActiveDocument();
306
- * if (!doc) throw new Error('No active document');
307
- *
308
- * const customBlock = doc.getBody().getChild(0).asCustomBlock();
309
- * console.log(customBlock.getKey());
157
+ * const fDocument = univerAPI.getActiveDocument();
158
+ * const fDocumentBody = fDocument.getBody();
159
+ * const element = fDocumentBody.getElement(1);
160
+ * console.log(element?.getPreviousSibling());
310
161
  * ```
311
162
  */
312
- getKey() {
313
- return this._key;
163
+ getPreviousSibling() {
164
+ return this._createSibling(-1);
314
165
  }
315
166
  /**
316
- * Get the parent body facade that owns this custom block.
317
- * @returns {FDocBody} The document body facade.
167
+ * Get the sibling element at a relative offset from this element.
168
+ * @param {number} offset The relative offset from this element. Use `1` for the next sibling, `-1` for the previous sibling, and so on.
169
+ * @returns {FDocumentElement | null} The sibling wrapper at the specified offset, or `null` when the offset is out of range.
318
170
  * @example
319
171
  * ```ts
320
- * const doc = univerAPI.getActiveDocument();
321
- * if (!doc) throw new Error('No active document');
172
+ * const fDocument = univerAPI.getActiveDocument();
173
+ * const fDocumentBody = fDocument.getBody();
174
+ * const element = fDocumentBody.getElement(0);
322
175
  *
323
- * const customBlock = doc.getBody().getChild(0).asCustomBlock();
324
- * console.log(customBlock.getParent().getChildIndex(customBlock));
176
+ * // Get the third sibling after this element
177
+ * const nextThirdSibling = element?.getSibling(3);
178
+ * console.log(nextThirdSibling?.getType());
325
179
  * ```
326
180
  */
327
- getParent() {
328
- return this._body;
181
+ getSibling(offset) {
182
+ return this._createSibling(offset);
329
183
  }
330
184
  /**
331
- * Remove this custom block from the parent body.
332
- * @returns {boolean} `true` if the custom block placeholder was removed.
185
+ * Remove this element from its parent body.
186
+ * @returns {boolean} `true` if the element content was removed.
333
187
  * @example
334
188
  * ```ts
335
- * const doc = univerAPI.getActiveDocument();
336
- * if (!doc) throw new Error('No active document');
337
- *
338
- * const customBlock = doc.getBody().getChild(0).asCustomBlock();
339
- * customBlock.removeFromParent();
189
+ * const fDocument = univerAPI.getActiveDocument();
190
+ * const fDocumentBody = fDocument.getBody();
191
+ * const element = fDocumentBody.getElement(0);
192
+ * const removed = element?.remove();
193
+ * console.log(removed);
340
194
  * ```
341
195
  */
342
- removeFromParent() {
343
- return this._body.removeCustomBlock(this._key);
196
+ remove() {
197
+ if (this.isParagraph()) return this._body.removeParagraph(this.asParagraph());
198
+ if (this.isBlockRange()) return this._body.removeBlockRange(this.asBlockRange());
199
+ if (this.isTable()) return this._body.removeTable(this.asTable());
200
+ return this._body.removeCustomBlock(this.asCustomBlock());
344
201
  }
345
- /**
346
- * Get the persisted custom block id.
347
- * @returns {string} The `ICustomBlock.blockId` value.
348
- * @example
349
- * ```ts
350
- * const doc = univerAPI.getActiveDocument();
351
- * if (!doc) throw new Error('No active document');
352
- *
353
- * const customBlock = doc.getBody().getChild(0).asCustomBlock();
354
- * console.log(customBlock.getBlockId());
355
- * ```
356
- */
357
- getBlockId() {
358
- return this._body.getCustomBlock(this._key).blockId;
202
+ _createSibling(offset) {
203
+ if (offset === 0) throw new Error("Offset cannot be zero.");
204
+ const index = this._body.getElementIndex(this);
205
+ return this._body.getElement(index + offset);
359
206
  }
360
207
  };
361
208
 
362
209
  //#endregion
363
- //#region src/facade/f-doc-paragraph.ts
210
+ //#region src/facade/utils.ts
211
+ function cloneParagraphStyle(paragraphStyle) {
212
+ return paragraphStyle == null ? paragraphStyle : JSON.parse(JSON.stringify(paragraphStyle));
213
+ }
214
+ function normalizePlainTextDataStream(dataStream) {
215
+ return dataStream.replace(/\r\n/g, "\r").replace(/\n/g, "\r");
216
+ }
217
+ function getRemovedLeadingParagraphBreakLength(dataStream, removeLeadingParagraphBreak) {
218
+ const normalized = normalizePlainTextDataStream(dataStream);
219
+ if (removeLeadingParagraphBreak && normalized.length > 1 && normalized.startsWith("\r")) return 1;
220
+ return 0;
221
+ }
222
+ function buildPlainTextInsertBody(dataStream, options = {}) {
223
+ const normalizedDataStream = normalizePlainTextDataStream(dataStream).slice(getRemovedLeadingParagraphBreakLength(dataStream, options.removeLeadingParagraphBreak));
224
+ const body = {
225
+ dataStream: normalizedDataStream,
226
+ customDecorations: [],
227
+ customRanges: [],
228
+ textRuns: []
229
+ };
230
+ const paragraphs = [];
231
+ const existingParagraphIds = /* @__PURE__ */ new Set();
232
+ for (let index = 0; index < normalizedDataStream.length; index++) if (normalizedDataStream[index] === "\r") paragraphs.push({
233
+ startIndex: index,
234
+ paragraphId: (0, _univerjs_core.createParagraphId)(existingParagraphIds),
235
+ ...options.paragraphStyle == null ? {} : { paragraphStyle: cloneParagraphStyle(options.paragraphStyle) }
236
+ });
237
+ if (paragraphs.length > 0) body.paragraphs = paragraphs;
238
+ return body;
239
+ }
240
+
241
+ //#endregion
242
+ //#region src/facade/f-document-paragraph.ts
364
243
  /**
365
244
  * A paragraph facade wrapper.
366
245
  *
@@ -370,100 +249,107 @@ var FDocCustomBlock = class {
370
249
  *
371
250
  * @hideconstructor
372
251
  */
373
- var FDocParagraph = class {
374
- constructor(_body, _key) {
375
- this._body = _body;
376
- this._key = _key;
377
- }
378
- /**
379
- * Get the document element type.
380
- * @returns {'paragraph'} The literal paragraph element type.
381
- * @example
382
- * ```ts
383
- * const doc = univerAPI.getActiveDocument();
384
- * if (!doc) throw new Error('No active document');
385
- *
386
- * const paragraph = doc.getBody().getChild(0).asParagraph();
387
- * console.log(paragraph.getType());
388
- * ```
389
- */
390
- getType() {
391
- return "paragraph";
392
- }
393
- /**
394
- * Get the persisted paragraph id.
395
- * @returns {string} The paragraph id.
396
- * @example
397
- * ```ts
398
- * const doc = univerAPI.getActiveDocument();
399
- * if (!doc) throw new Error('No active document');
400
- *
401
- * const paragraph = doc.getBody().getChild(0).asParagraph();
402
- * console.log(paragraph.getKey());
403
- * ```
404
- */
405
- getKey() {
406
- return this._key;
252
+ var FDocumentParagraph = class extends FDocumentElement {
253
+ constructor(body, bodyEdit, info, injector) {
254
+ super(body, bodyEdit, info, injector);
255
+ this.body = body;
256
+ this.bodyEdit = bodyEdit;
257
+ this.info = info;
258
+ this.injector = injector;
259
+ if (this.getType() !== _univerjs_core.DocumentBlockType.PARAGRAPH) throw new Error(`Element type is not a paragraph: ${this.getType()}`);
407
260
  }
408
261
  /**
409
262
  * Get the persisted paragraph id.
410
263
  * @returns {string} The paragraph id.
411
264
  * @example
412
265
  * ```ts
413
- * const doc = univerAPI.getActiveDocument();
414
- * if (!doc) throw new Error('No active document');
266
+ * const fDocument = univerAPI.getActiveDocument();
267
+ * const fDocumentBody = fDocument.getBody();
268
+ * const element = fDocumentBody.getElement(0);
415
269
  *
416
- * const paragraph = doc.getBody().getChild(0).asParagraph();
417
- * console.log(paragraph.getId());
270
+ * if (element?.isParagraph()) {
271
+ * const paragraph = element.asParagraph();
272
+ * console.log(paragraph.getParagraphId());
273
+ * }
418
274
  * ```
419
275
  */
420
- getId() {
421
- return this._key;
276
+ getParagraphId() {
277
+ return this.getKey();
422
278
  }
423
279
  /**
424
- * Get the parent body facade that owns this paragraph.
425
- * @returns {FDocBody} The document body facade.
280
+ * Get the resolved paragraph info for this wrapper.
281
+ * @returns {IFDocumentResolvedParagraph} The resolved paragraph info, including the paragraph object, its index, and its text range.
426
282
  * @example
427
283
  * ```ts
428
- * const doc = univerAPI.getActiveDocument();
429
- * if (!doc) throw new Error('No active document');
284
+ * const fDocument = univerAPI.getActiveDocument();
285
+ * const fDocumentBody = fDocument.getBody();
286
+ * const element = fDocumentBody.getElement(0);
430
287
  *
431
- * const paragraph = doc.getBody().getChild(0).asParagraph();
432
- * console.log(paragraph.getParent().getChildIndex(paragraph));
288
+ * if (element?.isParagraph()) {
289
+ * const paragraph = element.asParagraph();
290
+ * console.log(paragraph.getResolvedParagraphInfo());
291
+ * }
433
292
  * ```
434
293
  */
435
- getParent() {
436
- return this._body;
294
+ getResolvedParagraphInfo() {
295
+ const { paragraphs = [] } = this._body.getBody();
296
+ const matches = paragraphs.map((paragraph, paragraphIndex) => ({
297
+ paragraph,
298
+ paragraphIndex
299
+ })).filter(({ paragraph }) => paragraph.paragraphId === this.getKey());
300
+ if (matches.length === 0) throw new Error(`Document paragraph with id ${this.getKey()} not found`);
301
+ if (matches.length > 1) throw new Error(`Multiple document paragraphs with id ${this.getKey()} found`);
302
+ const { paragraph, paragraphIndex } = matches[0];
303
+ return {
304
+ paragraph,
305
+ paragraphIndex,
306
+ startOffset: paragraphIndex > 0 ? paragraphs[paragraphIndex - 1].startIndex + 1 : 0,
307
+ endOffset: paragraph.startIndex
308
+ };
437
309
  }
438
310
  /**
439
- * Remove this paragraph from its parent body.
440
- * @returns {boolean} `true` if the paragraph was removed.
311
+ * Get the current text range occupied by this paragraph.
312
+ * @returns {IFDocumentTextRange} The paragraph text range, excluding the trailing paragraph break.
441
313
  * @example
442
314
  * ```ts
443
- * const doc = univerAPI.getActiveDocument();
444
- * if (!doc) throw new Error('No active document');
315
+ * const fDocument = univerAPI.getActiveDocument();
316
+ * const fDocumentBody = fDocument.getBody();
317
+ * const element = fDocumentBody.getElement(0);
445
318
  *
446
- * const paragraph = doc.getBody().getChild(0).asParagraph();
447
- * paragraph.removeFromParent();
319
+ * if (element?.isParagraph()) {
320
+ * const paragraph = element.asParagraph();
321
+ * const range = paragraph.getRange();
322
+ * fDocumentBody.setTextStyle(range, { bl: 1 });
323
+ * }
448
324
  * ```
449
325
  */
450
- removeFromParent() {
451
- return this._body.removeParagraph(this._key);
326
+ getRange() {
327
+ const { startOffset, endOffset } = this.getResolvedParagraphInfo();
328
+ return {
329
+ startOffset,
330
+ endOffset,
331
+ segmentId: this._body.getSegmentId()
332
+ };
452
333
  }
453
334
  /**
454
335
  * Get this paragraph's plain text.
455
336
  * @returns {string} The paragraph text without the trailing paragraph break.
456
337
  * @example
457
338
  * ```ts
458
- * const doc = univerAPI.getActiveDocument();
459
- * if (!doc) throw new Error('No active document');
339
+ * const fDocument = univerAPI.getActiveDocument();
340
+ * const fDocumentBody = fDocument.getBody();
341
+ * const element = fDocumentBody.getElement(0);
460
342
  *
461
- * const paragraph = doc.getBody().getChild(0).asParagraph();
462
- * console.log(paragraph.getText());
343
+ * if (element?.isParagraph()) {
344
+ * const paragraph = element.asParagraph();
345
+ * console.log(paragraph.getText());
346
+ * }
463
347
  * ```
464
348
  */
465
349
  getText() {
466
- return this._body.getParagraphText(this._key);
350
+ const { dataStream } = this._body.getBody();
351
+ const { startOffset, endOffset } = this.getResolvedParagraphInfo();
352
+ return dataStream.slice(startOffset, endOffset);
467
353
  }
468
354
  /**
469
355
  * Replace this paragraph's plain text.
@@ -471,15 +357,23 @@ var FDocParagraph = class {
471
357
  * @returns {boolean} `true` if the paragraph text was replaced.
472
358
  * @example
473
359
  * ```ts
474
- * const doc = univerAPI.getActiveDocument();
475
- * if (!doc) throw new Error('No active document');
360
+ * const fDocument = univerAPI.getActiveDocument();
361
+ * const fDocumentBody = fDocument.getBody();
362
+ * const element = fDocumentBody.getElement(0);
476
363
  *
477
- * const paragraph = doc.getBody().getChild(0).asParagraph();
478
- * paragraph.setText('Updated title');
364
+ * if (element?.isParagraph()) {
365
+ * const paragraph = element.asParagraph();
366
+ * const success = paragraph.setText('Updated title');
367
+ * console.log(success ? 'Text updated' : 'Failed to update text');
368
+ * }
479
369
  * ```
480
370
  */
481
371
  setText(text) {
482
- return this._body.setParagraphText(this._key, text);
372
+ const { startOffset, endOffset } = this.getResolvedParagraphInfo();
373
+ return this._bodyEdit.replaceRange({
374
+ startOffset,
375
+ endOffset
376
+ }, buildPlainTextInsertBody(text));
483
377
  }
484
378
  /**
485
379
  * Append plain text before this paragraph's trailing paragraph break.
@@ -487,63 +381,95 @@ var FDocParagraph = class {
487
381
  * @returns {boolean} `true` if the text was appended.
488
382
  * @example
489
383
  * ```ts
490
- * const doc = univerAPI.getActiveDocument();
491
- * if (!doc) throw new Error('No active document');
384
+ * const fDocument = univerAPI.getActiveDocument();
385
+ * const fDocumentBody = fDocument.getBody();
386
+ * const element = fDocumentBody.getElement(0);
492
387
  *
493
- * const paragraph = doc.getBody().getChild(0).asParagraph();
494
- * paragraph.appendText(' suffix');
388
+ * if (element?.isParagraph()) {
389
+ * const paragraph = element.asParagraph();
390
+ * const success = paragraph.appendText(' Appended text');
391
+ * console.log(success ? 'Text appended' : 'Failed to append text');
392
+ * }
495
393
  * ```
496
394
  */
497
395
  appendText(text) {
498
- return this._body.appendParagraphText(this._key, text);
396
+ const { endOffset } = this.getResolvedParagraphInfo();
397
+ return this._body.insertText(endOffset, text);
499
398
  }
500
399
  /**
501
- * Get the current text range occupied by this paragraph.
502
- * @returns {IFDocTextRange} The paragraph text range, excluding the trailing paragraph break.
400
+ * Apply paragraph style to a paragraph handle or text range.
401
+ * @param {IParagraphStyle} style The Univer paragraph style patch.
402
+ * @returns {boolean} `true` if the style was applied.
503
403
  * @example
504
404
  * ```ts
505
- * const doc = univerAPI.getActiveDocument();
506
- * if (!doc) throw new Error('No active document');
405
+ * const fDocument = univerAPI.getActiveDocument();
406
+ * const fDocumentBody = fDocument.getBody();
407
+ * const element = fDocumentBody.getElement(0);
507
408
  *
508
- * const paragraph = doc.getBody().getChild(0).asParagraph();
509
- * const range = paragraph.getRange();
510
- * doc.getBody().setTextStyle(range, { bl: 1 });
409
+ * if (element?.isParagraph()) {
410
+ * const paragraph = element.asParagraph();
411
+ * paragraph.setStyle({ horizontalAlign: 2 });
412
+ * }
511
413
  * ```
512
414
  */
513
- getRange() {
514
- return this._body.getParagraphRange(this._key);
415
+ setStyle(style) {
416
+ const { paragraph, endOffset } = this.getResolvedParagraphInfo();
417
+ const updateBody = {
418
+ dataStream: "",
419
+ paragraphs: [{
420
+ ...paragraph,
421
+ startIndex: 0,
422
+ paragraphStyle: {
423
+ ...paragraph.paragraphStyle,
424
+ ...style
425
+ }
426
+ }]
427
+ };
428
+ this._preserveExplicitParagraphIds(updateBody);
429
+ return this._bodyEdit.retainRange({
430
+ startOffset: endOffset,
431
+ endOffset: endOffset + 1
432
+ }, updateBody, _univerjs_core.UpdateDocsAttributeType.REPLACE);
515
433
  }
516
434
  /**
517
435
  * Check whether this paragraph is a bullet, ordered, or checklist item.
518
436
  * @returns {boolean} `true` if the paragraph has list metadata.
519
437
  * @example
520
438
  * ```ts
521
- * const doc = univerAPI.getActiveDocument();
522
- * if (!doc) throw new Error('No active document');
439
+ * const fDocument = univerAPI.getActiveDocument();
440
+ * const fDocumentBody = fDocument.getBody();
441
+ * const element = fDocumentBody.getElement(0);
523
442
  *
524
- * const paragraph = doc.getBody().getChild(0).asParagraph();
525
- * console.log(paragraph.isListItem());
443
+ * if (element?.isParagraph()) {
444
+ * const paragraph = element.asParagraph();
445
+ * console.log(paragraph.isListItem() ? 'This is a list item' : 'This is not a list item');
446
+ * }
526
447
  * ```
527
448
  */
528
449
  isListItem() {
529
- return this._body.isListParagraph(this._key);
450
+ const { paragraph } = this.getResolvedParagraphInfo();
451
+ return Boolean(paragraph.bullet);
530
452
  }
531
453
  /**
532
454
  * Check whether this paragraph is a task/checklist item.
533
455
  * @returns {boolean} `true` if this paragraph is an unchecked or checked task item.
534
456
  * @example
535
457
  * ```ts
536
- * const doc = univerAPI.getActiveDocument();
537
- * if (!doc) throw new Error('No active document');
458
+ * const fDocument = univerAPI.getActiveDocument();
459
+ * const fDocumentBody = fDocument.getBody();
460
+ * const element = fDocumentBody.getElement(0);
538
461
  *
539
- * const paragraph = doc.getBody().getChild(0).asParagraph();
540
- * if (paragraph.isTask()) {
541
- * paragraph.setTaskChecked(true);
462
+ * if (element?.isParagraph()) {
463
+ * const paragraph = element.asParagraph();
464
+ * console.log(paragraph.isTask() ? 'This is a task item' : 'This is not a task item');
542
465
  * }
543
466
  * ```
544
467
  */
545
468
  isTask() {
546
- return this._body.isTaskParagraph(this._key);
469
+ var _paragraph$bullet;
470
+ const { paragraph } = this.getResolvedParagraphInfo();
471
+ const listType = (_paragraph$bullet = paragraph.bullet) === null || _paragraph$bullet === void 0 ? void 0 : _paragraph$bullet.listType;
472
+ return listType === _univerjs_core.PresetListType.CHECK_LIST || listType === _univerjs_core.PresetListType.CHECK_LIST_CHECKED;
547
473
  }
548
474
  /**
549
475
  * Set the checked state of this task/checklist paragraph.
@@ -551,377 +477,196 @@ var FDocParagraph = class {
551
477
  * @returns {boolean} `true` if the task state was updated, or `false` if this paragraph is not a task item.
552
478
  * @example
553
479
  * ```ts
554
- * const doc = univerAPI.getActiveDocument();
555
- * if (!doc) throw new Error('No active document');
480
+ * const fDocument = univerAPI.getActiveDocument();
481
+ * const fDocumentBody = fDocument.getBody();
482
+ * const element = fDocumentBody.getElement(0);
483
+ *
484
+ * if (element?.isParagraph()) {
485
+ * const paragraph = element.asParagraph();
556
486
  *
557
- * const paragraph = doc.getBody().getChild(0).asParagraph();
558
- * if (paragraph.isTask()) {
559
- * paragraph.setTaskChecked(false);
487
+ * if (paragraph.isTask()) {
488
+ * const success = paragraph.setTaskChecked(true);
489
+ * console.log(success ? 'Task checked' : 'Failed to check task');
490
+ * }
560
491
  * }
561
492
  * ```
562
493
  */
563
494
  setTaskChecked(checked) {
564
- return this._body.setTaskChecked(this._key, checked);
495
+ if (!this.isTask()) return false;
496
+ const { paragraph, endOffset } = this.getResolvedParagraphInfo();
497
+ const bullet = paragraph.bullet;
498
+ const updateBody = {
499
+ dataStream: "",
500
+ paragraphs: [{
501
+ ...paragraph,
502
+ startIndex: 0,
503
+ bullet: {
504
+ ...bullet,
505
+ listType: checked ? _univerjs_core.PresetListType.CHECK_LIST_CHECKED : _univerjs_core.PresetListType.CHECK_LIST
506
+ }
507
+ }]
508
+ };
509
+ this._preserveExplicitParagraphIds(updateBody);
510
+ return this._bodyEdit.retainRange({
511
+ startOffset: endOffset,
512
+ endOffset: endOffset + 1
513
+ }, updateBody, _univerjs_core.UpdateDocsAttributeType.REPLACE);
514
+ }
515
+ _preserveExplicitParagraphIds(body) {
516
+ body[_univerjs_core.RESTORE_INSERTED_PARAGRAPH_IDS] = true;
517
+ }
518
+ };
519
+ var FDocumentParagraphMixin = class extends FDocumentElement {
520
+ asParagraph() {
521
+ if (this.getType() !== _univerjs_core.DocumentBlockType.PARAGRAPH) throw new Error(`Element type is not a paragraph: ${this.getType()}`);
522
+ return this._injector.createInstance(FDocumentParagraph, this._body, this._bodyEdit, this.getResolvedInfo(), this._injector);
565
523
  }
566
524
  };
525
+ FDocumentElement.extend(FDocumentParagraphMixin);
567
526
 
568
527
  //#endregion
569
- //#region src/facade/f-doc-table.ts
570
- /**
571
- * A facade wrapper for a document table marker.
572
- *
573
- * Table identity is backed by the persisted `ICustomTable.tableId`, so the
574
- * wrapper can be re-resolved after text is inserted before the table.
575
- *
576
- * @hideconstructor
577
- */
578
- var FDocTable = class {
579
- constructor(_body, _key) {
580
- this._body = _body;
581
- this._key = _key;
582
- }
583
- /**
584
- * Get the document element type.
585
- * @returns {'table'} The literal table element type.
586
- * @example
587
- * ```ts
588
- * const doc = univerAPI.getActiveDocument();
589
- * if (!doc) throw new Error('No active document');
590
- *
591
- * const table = doc.getBody().getChild(0).asTable();
592
- * console.log(table.getType());
593
- * ```
594
- */
595
- getType() {
596
- return "table";
597
- }
598
- /**
599
- * Get the table key.
600
- * @returns {string} The persisted `tableId` for this table.
601
- * @example
602
- * ```ts
603
- * const doc = univerAPI.getActiveDocument();
604
- * if (!doc) throw new Error('No active document');
605
- *
606
- * const table = doc.getBody().getChild(0).asTable();
607
- * console.log(table.getKey());
608
- * ```
609
- */
610
- getKey() {
611
- return this._key;
612
- }
613
- /**
614
- * Get the parent body facade that owns this table.
615
- * @returns {FDocBody} The document body facade.
616
- * @example
617
- * ```ts
618
- * const doc = univerAPI.getActiveDocument();
619
- * if (!doc) throw new Error('No active document');
620
- *
621
- * const table = doc.getBody().getChild(0).asTable();
622
- * console.log(table.getParent().getChildIndex(table));
623
- * ```
624
- */
625
- getParent() {
626
- return this._body;
627
- }
628
- /**
629
- * Remove this table from the parent body.
630
- * @returns {boolean} `true` if the table range was removed.
631
- * @example
632
- * ```ts
633
- * const doc = univerAPI.getActiveDocument();
634
- * if (!doc) throw new Error('No active document');
635
- *
636
- * const table = doc.getBody().getChild(0).asTable();
637
- * table.removeFromParent();
638
- * ```
639
- */
640
- removeFromParent() {
641
- return this._body.removeTable(this._key);
642
- }
643
- /**
644
- * Get the persisted table id.
645
- * @returns {string} The `ICustomTable.tableId` value.
646
- * @example
647
- * ```ts
648
- * const doc = univerAPI.getActiveDocument();
649
- * if (!doc) throw new Error('No active document');
650
- *
651
- * const table = doc.getBody().getChild(0).asTable();
652
- * console.log(table.getTableId());
653
- * ```
654
- */
655
- getTableId() {
656
- return this._body.getTable(this._key).tableId;
528
+ //#region \0@oxc-project+runtime@0.137.0/helpers/esm/typeof.js
529
+ function _typeof(o) {
530
+ "@babel/helpers - typeof";
531
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
532
+ return typeof o;
533
+ } : function(o) {
534
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
535
+ }, _typeof(o);
536
+ }
537
+
538
+ //#endregion
539
+ //#region \0@oxc-project+runtime@0.137.0/helpers/esm/toPrimitive.js
540
+ function toPrimitive(t, r) {
541
+ if ("object" != _typeof(t) || !t) return t;
542
+ var e = t[Symbol.toPrimitive];
543
+ if (void 0 !== e) {
544
+ var i = e.call(t, r || "default");
545
+ if ("object" != _typeof(i)) return i;
546
+ throw new TypeError("@@toPrimitive must return a primitive value.");
657
547
  }
658
- };
548
+ return ("string" === r ? String : Number)(t);
549
+ }
550
+
551
+ //#endregion
552
+ //#region \0@oxc-project+runtime@0.137.0/helpers/esm/toPropertyKey.js
553
+ function toPropertyKey(t) {
554
+ var i = toPrimitive(t, "string");
555
+ return "symbol" == _typeof(i) ? i : i + "";
556
+ }
557
+
558
+ //#endregion
559
+ //#region \0@oxc-project+runtime@0.137.0/helpers/esm/defineProperty.js
560
+ function _defineProperty(e, r, t) {
561
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
562
+ value: t,
563
+ enumerable: !0,
564
+ configurable: !0,
565
+ writable: !0
566
+ }) : e[r] = t, e;
567
+ }
659
568
 
660
569
  //#endregion
661
- //#region src/facade/f-doc-element.ts
570
+ //#region src/facade/f-document-body.ts
662
571
  /**
663
- * A generic top-level document body element.
664
- *
665
- * Use this wrapper when you need to inspect an element type first, navigate to
666
- * neighboring elements, or cast the element to a more specific facade wrapper.
572
+ * A Facade API object bounded to a document body or header/footer segment.
573
+ * It provides Google Docs-like element access and range editing methods.
667
574
  *
668
- * Paragraph keys are persisted `paragraphId` values. Tables, block ranges, and
575
+ * Paragraph elements use their persisted `paragraphId`. Tables, block ranges, and
669
576
  * custom blocks use their persisted ids.
670
577
  *
671
578
  * @hideconstructor
672
579
  */
673
- var FDocElement = class {
674
- constructor(_body, _type, _key) {
675
- this._body = _body;
676
- this._type = _type;
677
- this._key = _key;
678
- }
679
- /**
680
- * Get the document element type.
681
- * @returns {FDocElementType} The element type, such as `paragraph`, `table`, `blockRange`, or `customBlock`.
682
- * @example
683
- * ```ts
684
- * const doc = univerAPI.getActiveDocument();
685
- * if (!doc) throw new Error('No active document');
686
- *
687
- * const element = doc.getBody().getChild(0);
688
- * console.log(element.getType());
689
- * ```
690
- */
691
- getType() {
692
- return this._type;
693
- }
694
- /**
695
- * Get the facade key used to resolve this element.
696
- * @returns {string} The paragraph `paragraphId` or persisted table/block/custom block id.
697
- * @example
698
- * ```ts
699
- * const doc = univerAPI.getActiveDocument();
700
- * if (!doc) throw new Error('No active document');
701
- *
702
- * const body = doc.getBody();
703
- * const element = body.getChild(0);
704
- * console.log(element.getKey());
705
- * ```
706
- */
707
- getKey() {
708
- return this._key;
709
- }
710
- /**
711
- * Get the parent body facade that owns this element.
712
- * @returns {FDocBody} The document body facade.
713
- * @example
714
- * ```ts
715
- * const doc = univerAPI.getActiveDocument();
716
- * if (!doc) throw new Error('No active document');
717
- *
718
- * const element = doc.getBody().getChild(0);
719
- * console.log(element.getParent().getNumChildren());
720
- * ```
721
- */
722
- getParent() {
723
- return this._body;
724
- }
725
- /**
726
- * Get the next sibling element in the current body order.
727
- * @returns {FDocElement | null} The next sibling wrapper, or `null` when this is the last child.
728
- * @example
729
- * ```ts
730
- * const doc = univerAPI.getActiveDocument();
731
- * if (!doc) throw new Error('No active document');
732
- *
733
- * const first = doc.getBody().getChild(0);
734
- * const next = first.getNextSibling();
735
- * console.log(next?.getType());
736
- * ```
737
- */
738
- getNextSibling() {
739
- return this._body.createSibling(this._type, this._key, 1);
740
- }
741
- /**
742
- * Get the previous sibling element in the current body order.
743
- * @returns {FDocElement | null} The previous sibling wrapper, or `null` when this is the first child.
744
- * @example
745
- * ```ts
746
- * const doc = univerAPI.getActiveDocument();
747
- * if (!doc) throw new Error('No active document');
748
- *
749
- * const second = doc.getBody().getChild(1);
750
- * const previous = second.getPreviousSibling();
751
- * console.log(previous?.getType());
752
- * ```
753
- */
754
- getPreviousSibling() {
755
- return this._body.createSibling(this._type, this._key, -1);
756
- }
757
- /**
758
- * Remove this element from its parent body.
759
- * @returns {boolean} `true` if the element content was removed.
760
- * @example
761
- * ```ts
762
- * const doc = univerAPI.getActiveDocument();
763
- * if (!doc) throw new Error('No active document');
764
- *
765
- * const body = doc.getBody();
766
- * const element = body.getChild(0);
767
- * element.removeFromParent();
768
- * ```
769
- */
770
- removeFromParent() {
771
- if (this._type === "paragraph") return this._body.removeParagraph(this._key);
772
- if (this._type === "blockRange") return this._body.removeBlockRange(this._key);
773
- if (this._type === "table") return this._body.removeTable(this._key);
774
- return this._body.removeCustomBlock(this._key);
775
- }
776
- /**
777
- * Cast this generic element to a paragraph facade.
778
- * @returns {FDocParagraph} The paragraph facade wrapper.
779
- * @throws {TypeError} If the element is not a paragraph.
780
- * @example
781
- * ```ts
782
- * const doc = univerAPI.getActiveDocument();
783
- * if (!doc) throw new Error('No active document');
784
- *
785
- * const paragraph = doc.getBody().getChild(0).asParagraph();
786
- * console.log(paragraph.getText());
787
- * ```
788
- */
789
- asParagraph() {
790
- this._assertType("paragraph");
791
- return new FDocParagraph(this._body, this._key);
792
- }
793
- /**
794
- * Cast this generic element to a table facade.
795
- * @returns {FDocTable} The table facade wrapper.
796
- * @throws {TypeError} If the element is not a table.
797
- * @example
798
- * ```ts
799
- * const doc = univerAPI.getActiveDocument();
800
- * if (!doc) throw new Error('No active document');
801
- *
802
- * const table = doc.getBody().getChild(0).asTable();
803
- * console.log(table.getTableId());
804
- * ```
805
- */
806
- asTable() {
807
- this._assertType("table");
808
- return new FDocTable(this._body, this._key);
580
+ var FDocumentBody = class {
581
+ constructor(_documentDataModel, _injector, _segmentId = "") {
582
+ this._documentDataModel = _documentDataModel;
583
+ this._injector = _injector;
584
+ this._segmentId = _segmentId;
585
+ _defineProperty(this, "_bodyEdit", void 0);
586
+ this._bodyEdit = {
587
+ replaceRange: this._replaceBodyRange.bind(this),
588
+ retainRange: this._retainBodyRange.bind(this)
589
+ };
809
590
  }
810
591
  /**
811
- * Cast this generic element to a callout, quote, or code block range facade.
812
- * @returns {FDocBlockRange} The block range facade wrapper.
813
- * @throws {TypeError} If the element is not a block range.
592
+ * Get the segment id of this document body facade.
593
+ * The main body has an empty string segment id.
594
+ * The header and footer FDocumentBody instances have their respective segment ids.
595
+ * @returns {string} The segment id of this document body facade.
814
596
  * @example
815
597
  * ```ts
816
- * const doc = univerAPI.getActiveDocument();
817
- * if (!doc) throw new Error('No active document');
818
- *
819
- * const blockRange = doc.getBody().getChild(0).asBlockRange();
820
- * console.log(blockRange.getBlockType());
598
+ * const fDocument = univerAPI.getActiveDocument();
599
+ * const fDocumentBody = fDocument.getBody();
600
+ * console.log(fDocumentBody.getSegmentId());
821
601
  * ```
822
602
  */
823
- asBlockRange() {
824
- this._assertType("blockRange");
825
- return new FDocBlockRange(this._body, this._key);
603
+ getSegmentId() {
604
+ return this._segmentId;
826
605
  }
827
606
  /**
828
- * Cast this generic element to a custom block facade.
829
- * @returns {FDocCustomBlock} The custom block facade wrapper.
830
- * @throws {TypeError} If the element is not a custom block.
607
+ * Get the underlying document body snapshot.
608
+ * @returns {IDocumentBody} The document body snapshot.
831
609
  * @example
832
610
  * ```ts
833
- * const doc = univerAPI.getActiveDocument();
834
- * if (!doc) throw new Error('No active document');
835
- *
836
- * const customBlock = doc.getBody().getChild(0).asCustomBlock();
837
- * console.log(customBlock.getBlockId());
611
+ * const fDocument = univerAPI.getActiveDocument();
612
+ * const fDocumentBody = fDocument.getBody();
613
+ * console.log(fDocumentBody.getBody());
838
614
  * ```
839
615
  */
840
- asCustomBlock() {
841
- this._assertType("customBlock");
842
- return new FDocCustomBlock(this._body, this._key);
843
- }
844
- _assertType(type) {
845
- if (this._type !== type) throw new TypeError(`Cannot cast ${this._type} to ${type}.`);
846
- }
847
- };
848
-
849
- //#endregion
850
- //#region src/facade/f-doc-body.ts
851
- function isRichTextLike(value) {
852
- return typeof value === "object" && value !== null && "getData" in value && typeof value.getData === "function";
853
- }
854
- const FACADE_TRIGGER = "doc-facade";
855
- const RESTORE_INSERTED_PARAGRAPH_IDS = "__textXRestoreParagraphIds";
856
- /**
857
- * A Facade API object bounded to a document body or header/footer segment.
858
- * It provides Google Docs-like element access and range editing methods.
859
- *
860
- * Paragraph elements use their persisted `paragraphId`. Tables, block ranges, and
861
- * custom blocks use their persisted ids.
862
- *
863
- * @hideconstructor
864
- */
865
- var FDocBody = class {
866
- constructor(_documentDataModel, _commandService, _registry, _segmentId = "") {
867
- this._documentDataModel = _documentDataModel;
868
- this._commandService = _commandService;
869
- this._segmentId = _segmentId;
616
+ getBody() {
617
+ const body = this._documentDataModel.getSelfOrHeaderFooterModel(this._segmentId).getBody();
618
+ if (!body) throw new Error("The document body is empty");
619
+ return body;
870
620
  }
871
621
  /**
872
- * Get the number of top-level child elements in the body.
873
- * @returns {number} The number of child elements.
622
+ * Get a list of top-level child elements in the body.
623
+ * @returns {FDocumentElement[]} The list of top-level document elements.
874
624
  * @example
875
625
  * ```ts
876
- * const doc = univerAPI.getActiveDocument();
877
- * if (!doc) throw new Error('No active document');
878
- *
879
- * const body = doc.getBody();
880
- * console.log(body.getNumChildren());
626
+ * const fDocument = univerAPI.getActiveDocument();
627
+ * const fDocumentBody = fDocument.getBody();
628
+ * const elements = fDocumentBody.getElements();
629
+ * console.log(elements);
881
630
  * ```
882
631
  */
883
- getNumChildren() {
884
- return this._getChildren().length;
632
+ getElements() {
633
+ return this._getChildren().map((child) => {
634
+ return this._injector.createInstance(FDocumentElement, this, this._bodyEdit, child, this._injector);
635
+ });
885
636
  }
886
637
  /**
887
638
  * Get a top-level child element by child index.
888
639
  * @param {number} index The zero-based child index.
889
- * @returns {FDocElement} The child element wrapper.
640
+ * @returns {FDocumentElement} The top-level child element wrapper.
890
641
  * @example
891
642
  * ```ts
892
- * const doc = univerAPI.getActiveDocument();
893
- * if (!doc) throw new Error('No active document');
894
- *
895
- * const body = doc.getBody();
896
- * const firstChild = body.getChild(0);
897
- * console.log(firstChild.getType());
643
+ * const fDocument = univerAPI.getActiveDocument();
644
+ * const fDocumentBody = fDocument.getBody();
645
+ * const element = fDocumentBody.getElement(0);
646
+ * console.log(element);
898
647
  * ```
899
648
  */
900
- getChild(index) {
901
- const child = this._getChildren()[index];
902
- if (!child) throw new RangeError(`Child index ${index} is out of range.`);
903
- return this._createElement(child.type, child.key);
649
+ getElement(index) {
650
+ var _this$getElements$ind;
651
+ return (_this$getElements$ind = this.getElements()[index]) !== null && _this$getElements$ind !== void 0 ? _this$getElements$ind : null;
904
652
  }
905
653
  /**
906
654
  * Get the current child index of an element handle.
907
655
  * The index is resolved from the element key, so a paragraph handle keeps pointing
908
656
  * to the same paragraph after facade edits insert content before it.
909
- * @param {IFDocElementHandle} element The element handle to locate.
657
+ * @param {FDocumentElement} element The element handle to locate.
910
658
  * @returns {number} The current zero-based child index.
911
659
  * @example
912
660
  * ```ts
913
- * const doc = univerAPI.getActiveDocument();
914
- * if (!doc) throw new Error('No active document');
915
- *
916
- * const body = doc.getBody();
917
- * const paragraph = body.getChild(1).asParagraph();
918
- * body.insertParagraph(0, 'Intro');
919
- * console.log(body.getChildIndex(paragraph));
661
+ * const fDocument = univerAPI.getActiveDocument();
662
+ * const fDocumentBody = fDocument.getBody();
663
+ * const element = fDocumentBody.getElement(0);
664
+ * console.log(fDocumentBody.getElementIndex(element));
920
665
  * ```
921
666
  */
922
- getChildIndex(element) {
923
- const resolved = this.resolveElement(element.getType(), element.getKey());
924
- const index = this._getChildren().findIndex((child) => child.type === resolved.type && child.key === resolved.key);
667
+ getElementIndex(element) {
668
+ const { type, key } = element.getResolvedInfo();
669
+ const index = this._getChildren().findIndex((child) => child.type === type && child.key === key);
925
670
  if (index < 0) throw new Error("Doc element is stale");
926
671
  return index;
927
672
  }
@@ -932,11 +677,9 @@ var FDocBody = class {
932
677
  * @returns {boolean} `true` if the edit was applied.
933
678
  * @example
934
679
  * ```ts
935
- * const doc = univerAPI.getActiveDocument();
936
- * if (!doc) throw new Error('No active document');
937
- *
938
- * const body = doc.getBody();
939
- * body.insertText(0, 'Hello ');
680
+ * const fDocument = univerAPI.getActiveDocument();
681
+ * const fDocumentBody = fDocument.getBody();
682
+ * fDocumentBody.insertText(0, 'Hello ');
940
683
  * ```
941
684
  */
942
685
  insertText(index, text) {
@@ -946,103 +689,15 @@ var FDocBody = class {
946
689
  }, buildPlainTextInsertBody(text));
947
690
  }
948
691
  /**
949
- * Insert a plain-text paragraph before the paragraph at the given paragraph index.
950
- * @param {number} index The zero-based paragraph insertion index.
951
- * @param {string} text The paragraph text. Defaults to an empty paragraph.
952
- * @returns {FDocParagraph} The inserted paragraph wrapper.
953
- * @example
954
- * ```ts
955
- * const doc = univerAPI.getActiveDocument();
956
- * if (!doc) throw new Error('No active document');
957
- *
958
- * const body = doc.getBody();
959
- * const paragraph = body.insertParagraph(0, 'Document title');
960
- * paragraph.appendText(' suffix');
961
- * ```
962
- */
963
- insertParagraph(index, text = "") {
964
- var _this$_getBody$paragr;
965
- const offset = this._getParagraphInsertOffset(index);
966
- if (!this._replaceBodyRange({
967
- startOffset: offset,
968
- endOffset: offset
969
- }, buildPlainTextInsertBody(`${text}\r`))) throw new Error("Failed to insert paragraph.");
970
- const paragraphIndex = this._normalizeInsertedParagraphIndex(index);
971
- const paragraph = (_this$_getBody$paragr = this._getBody().paragraphs) === null || _this$_getBody$paragr === void 0 ? void 0 : _this$_getBody$paragr[paragraphIndex];
972
- return new FDocParagraph(this, this._getParagraphId(paragraph, paragraphIndex));
973
- }
974
- /**
975
- * Append a plain-text paragraph at the end of the body.
976
- * @param {string} text The paragraph text. Defaults to an empty paragraph.
977
- * @returns {FDocParagraph} The appended paragraph wrapper.
978
- * @example
979
- * ```ts
980
- * const doc = univerAPI.getActiveDocument();
981
- * if (!doc) throw new Error('No active document');
982
- *
983
- * const body = doc.getBody();
984
- * const paragraph = body.appendParagraph('Summary');
985
- * console.log(paragraph.getText());
986
- * ```
987
- */
988
- appendParagraph(text = "") {
989
- var _this$_getBody$paragr2, _this$_getBody$paragr3;
990
- return this.insertParagraph((_this$_getBody$paragr2 = (_this$_getBody$paragr3 = this._getBody().paragraphs) === null || _this$_getBody$paragr3 === void 0 ? void 0 : _this$_getBody$paragr3.length) !== null && _this$_getBody$paragr2 !== void 0 ? _this$_getBody$paragr2 : 0, text);
991
- }
992
- /**
993
- * Delete a range from the body.
994
- * @param {IFDocTextRange} range The text range to delete.
995
- * @returns {boolean} `true` if the range was deleted.
996
- * @example
997
- * ```ts
998
- * const doc = univerAPI.getActiveDocument();
999
- * if (!doc) throw new Error('No active document');
1000
- *
1001
- * const body = doc.getBody();
1002
- * body.deleteRange({ startOffset: 0, endOffset: 5 });
1003
- * ```
1004
- */
1005
- deleteRange(range) {
1006
- return this._replaceBodyRange(range, { dataStream: "" });
1007
- }
1008
- /**
1009
- * Replace a range with plain text or rich text body data.
1010
- * @param {IFDocTextRange} range The text range to replace.
1011
- * @param {string | IFDocRichTextLike | { body?: IDocumentBody }} value The replacement text or rich-text-like value.
1012
- * @returns {boolean} `true` if the replacement was applied.
1013
- * @example
1014
- * ```ts
1015
- * const doc = univerAPI.getActiveDocument();
1016
- * if (!doc) throw new Error('No active document');
1017
- *
1018
- * const body = doc.getBody();
1019
- * body.replaceRange({ startOffset: 0, endOffset: 5 }, 'Hello');
1020
- * ```
1021
- */
1022
- replaceRange(range, value) {
1023
- let body;
1024
- if (typeof value === "string") body = buildPlainTextInsertBody(value);
1025
- else if (isRichTextLike(value)) {
1026
- var _value$getData$body;
1027
- body = (_value$getData$body = value.getData().body) !== null && _value$getData$body !== void 0 ? _value$getData$body : { dataStream: "" };
1028
- } else {
1029
- var _value$body;
1030
- body = (_value$body = value.body) !== null && _value$body !== void 0 ? _value$body : { dataStream: "" };
1031
- }
1032
- return this._replaceBodyRange(range, body);
1033
- }
1034
- /**
1035
692
  * Apply text style to a body range.
1036
- * @param {IFDocTextRange} range The range to style.
693
+ * @param {IFDocumentTextRange} range The range to style.
1037
694
  * @param {ITextStyle} style The Univer text style patch.
1038
695
  * @returns {boolean} `true` if the style was applied.
1039
696
  * @example
1040
697
  * ```ts
1041
- * const doc = univerAPI.getActiveDocument();
1042
- * if (!doc) throw new Error('No active document');
1043
- *
1044
- * const body = doc.getBody();
1045
- * body.setTextStyle({ startOffset: 0, endOffset: 5 }, { bl: 1 });
698
+ * const fDocument = univerAPI.getActiveDocument();
699
+ * const fDocumentBody = fDocument.getBody();
700
+ * fDocumentBody.setTextStyle({ startOffset: 0, endOffset: 5 }, { bl: 1 });
1046
701
  * ```
1047
702
  */
1048
703
  setTextStyle(range, style) {
@@ -1057,525 +712,235 @@ var FDocBody = class {
1057
712
  return this._retainBodyRange(range, updateBody, _univerjs_core.UpdateDocsAttributeType.COVER);
1058
713
  }
1059
714
  /**
1060
- * Apply paragraph style to a paragraph handle or text range.
1061
- * @param {FDocElement | FDocParagraph | IFDocTextRange} paragraph The paragraph handle or a range inside the paragraph.
1062
- * @param {IParagraphStyle} style The Univer paragraph style patch.
1063
- * @returns {boolean} `true` if the style was applied.
1064
- * @example
1065
- * ```ts
1066
- * const doc = univerAPI.getActiveDocument();
1067
- * if (!doc) throw new Error('No active document');
1068
- *
1069
- * const body = doc.getBody();
1070
- * const paragraph = body.getChild(0).asParagraph();
1071
- * body.setParagraphStyle(paragraph, { horizontalAlign: 2 });
1072
- * ```
1073
- */
1074
- setParagraphStyle(paragraph, style) {
1075
- const resolved = paragraph instanceof FDocElement || paragraph instanceof FDocParagraph ? this.resolveParagraph(paragraph.getKey()) : this._findParagraphByRange(paragraph);
1076
- const updateBody = {
1077
- dataStream: "",
1078
- paragraphs: [{
1079
- ...resolved.paragraph,
1080
- startIndex: 0,
1081
- paragraphStyle: {
1082
- ...resolved.paragraph.paragraphStyle,
1083
- ...style
1084
- }
1085
- }]
1086
- };
1087
- this._preserveExplicitParagraphIds(updateBody);
1088
- return this._retainBodyRange({
1089
- startOffset: resolved.endOffset,
1090
- endOffset: resolved.endOffset + 1
1091
- }, updateBody, _univerjs_core.UpdateDocsAttributeType.REPLACE);
1092
- }
1093
- /**
1094
- * Get the text content of a paragraph by paragraph id.
1095
- * @param {string} key The paragraph id.
1096
- * @returns {string} The paragraph text without the trailing paragraph break.
715
+ * Insert a plain-text paragraph before the paragraph at the given paragraph index.
716
+ * @param {number} index The zero-based paragraph insertion index.
717
+ * @param {string} text The paragraph text. Defaults to an empty paragraph.
718
+ * @returns {FDocumentParagraph} The inserted paragraph wrapper.
1097
719
  * @example
1098
720
  * ```ts
1099
- * const doc = univerAPI.getActiveDocument();
1100
- * if (!doc) throw new Error('No active document');
1101
- *
1102
- * const paragraph = doc.getBody().getChild(0).asParagraph();
1103
- * console.log(doc.getBody().getParagraphText(paragraph.getKey()));
721
+ * const fDocument = univerAPI.getActiveDocument();
722
+ * const fDocumentBody = fDocument.getBody();
723
+ * const paragraph = fDocumentBody.insertParagraph(0, 'Document title');
724
+ * paragraph.appendText(' suffix');
1104
725
  * ```
1105
726
  */
1106
- getParagraphText(key) {
1107
- const resolved = this.resolveParagraph(key);
1108
- return this._getBody().dataStream.slice(resolved.startOffset, resolved.endOffset);
727
+ insertParagraph(index, text = "") {
728
+ var _paragraphs;
729
+ const offset = this._getParagraphInsertOffset(index);
730
+ if (!this._replaceBodyRange({
731
+ startOffset: offset,
732
+ endOffset: offset
733
+ }, buildPlainTextInsertBody(`${text}\r`))) throw new Error("Failed to insert paragraph.");
734
+ const { paragraphs = [] } = this.getBody();
735
+ const paragraph = paragraphs[index];
736
+ if (!paragraph) throw new Error("Failed to insert paragraph.");
737
+ const info = this._resolveParagraphInfo(paragraph, index, (_paragraphs = paragraphs[index - 1]) === null || _paragraphs === void 0 ? void 0 : _paragraphs.startIndex);
738
+ return this._injector.createInstance(FDocumentParagraph, this, this._bodyEdit, info, this._injector);
1109
739
  }
1110
740
  /**
1111
- * Replace the text content of a paragraph by paragraph id.
1112
- * @param {string} key The paragraph id.
1113
- * @param {string} text The replacement paragraph text.
1114
- * @returns {boolean} `true` if the paragraph text was replaced.
741
+ * Append a plain-text paragraph at the end of the body.
742
+ * @param {string} text The paragraph text. Defaults to an empty paragraph.
743
+ * @returns {FDocumentParagraph} The appended paragraph wrapper.
1115
744
  * @example
1116
745
  * ```ts
1117
- * const doc = univerAPI.getActiveDocument();
1118
- * if (!doc) throw new Error('No active document');
1119
- *
1120
- * const paragraph = doc.getBody().getChild(0).asParagraph();
1121
- * doc.getBody().setParagraphText(paragraph.getKey(), 'Updated text');
746
+ * const fDocument = univerAPI.getActiveDocument();
747
+ * const fDocumentBody = fDocument.getBody();
748
+ * const paragraph = fDocumentBody.appendParagraph('Summary');
749
+ * console.log(paragraph.getText());
1122
750
  * ```
1123
751
  */
1124
- setParagraphText(key, text) {
1125
- const resolved = this.resolveParagraph(key);
1126
- return this.replaceRange({
1127
- startOffset: resolved.startOffset,
1128
- endOffset: resolved.endOffset
1129
- }, text);
752
+ appendParagraph(text = "") {
753
+ const { paragraphs = [] } = this.getBody();
754
+ return this.insertParagraph(paragraphs.length, text);
1130
755
  }
1131
756
  /**
1132
- * Append text to a paragraph by paragraph id.
1133
- * @param {string} key The paragraph id.
1134
- * @param {string} text The text to append before the paragraph break.
1135
- * @returns {boolean} `true` if the text was appended.
757
+ * Delete a range from the body.
758
+ * @param {IFDocumentTextRange} range The text range to delete.
759
+ * @returns {boolean} `true` if the range was deleted.
1136
760
  * @example
1137
761
  * ```ts
1138
- * const doc = univerAPI.getActiveDocument();
1139
- * if (!doc) throw new Error('No active document');
1140
- *
1141
- * const paragraph = doc.getBody().getChild(0).asParagraph();
1142
- * doc.getBody().appendParagraphText(paragraph.getKey(), ' suffix');
762
+ * const fDocument = univerAPI.getActiveDocument();
763
+ * const fDocumentBody = fDocument.getBody();
764
+ * fDocumentBody.deleteRange({ startOffset: 0, endOffset: 5 });
1143
765
  * ```
1144
766
  */
1145
- appendParagraphText(key, text) {
1146
- const resolved = this.resolveParagraph(key);
1147
- return this.insertText(resolved.endOffset, text);
767
+ deleteRange(range) {
768
+ return this._replaceBodyRange(range, { dataStream: "" });
1148
769
  }
1149
770
  /**
1150
771
  * Remove a paragraph by paragraph id.
1151
- * @param {string} key The paragraph id.
772
+ * @param {FDocumentParagraph} paragraph The paragraph handle to remove.
1152
773
  * @returns {boolean} `true` if the paragraph was removed.
1153
774
  * @example
1154
775
  * ```ts
1155
- * const doc = univerAPI.getActiveDocument();
1156
- * if (!doc) throw new Error('No active document');
1157
- *
1158
- * const paragraph = doc.getBody().getChild(0).asParagraph();
1159
- * doc.getBody().removeParagraph(paragraph.getKey());
1160
- * ```
1161
- */
1162
- removeParagraph(key) {
1163
- const resolved = this.resolveParagraph(key);
1164
- return this.deleteRange({
1165
- startOffset: resolved.startOffset,
1166
- endOffset: resolved.endOffset + 1
1167
- });
1168
- }
1169
- /**
1170
- * Get a paragraph text range by paragraph id.
1171
- * @param {string} key The paragraph id.
1172
- * @returns {IFDocTextRange} The paragraph range excluding the trailing paragraph break.
1173
- * @example
1174
- * ```ts
1175
- * const doc = univerAPI.getActiveDocument();
1176
- * if (!doc) throw new Error('No active document');
1177
- *
1178
- * const paragraph = doc.getBody().getChild(0).asParagraph();
1179
- * const range = doc.getBody().getParagraphRange(paragraph.getKey());
1180
- * console.log(range.startOffset, range.endOffset);
1181
- * ```
1182
- */
1183
- getParagraphRange(key) {
1184
- const resolved = this.resolveParagraph(key);
1185
- return {
1186
- startOffset: resolved.startOffset,
1187
- endOffset: resolved.endOffset,
1188
- segmentId: this._segmentId
1189
- };
1190
- }
1191
- /**
1192
- * Check whether a paragraph has list metadata.
1193
- * @param {string} key The paragraph id.
1194
- * @returns {boolean} `true` if the paragraph is a list item.
1195
- * @example
1196
- * ```ts
1197
- * const doc = univerAPI.getActiveDocument();
1198
- * if (!doc) throw new Error('No active document');
1199
- *
1200
- * const paragraph = doc.getBody().getChild(0).asParagraph();
1201
- * console.log(doc.getBody().isListParagraph(paragraph.getKey()));
1202
- * ```
1203
- */
1204
- isListParagraph(key) {
1205
- return Boolean(this.resolveParagraph(key).paragraph.bullet);
1206
- }
1207
- /**
1208
- * Check whether a paragraph is a task/checklist item.
1209
- * @param {string} key The paragraph id.
1210
- * @returns {boolean} `true` if the paragraph is an unchecked or checked task item.
1211
- * @example
1212
- * ```ts
1213
- * const doc = univerAPI.getActiveDocument();
1214
- * if (!doc) throw new Error('No active document');
1215
- *
1216
- * const paragraph = doc.getBody().getChild(0).asParagraph();
1217
- * console.log(doc.getBody().isTaskParagraph(paragraph.getKey()));
1218
- * ```
1219
- */
1220
- isTaskParagraph(key) {
1221
- var _this$resolveParagrap;
1222
- const listType = (_this$resolveParagrap = this.resolveParagraph(key).paragraph.bullet) === null || _this$resolveParagrap === void 0 ? void 0 : _this$resolveParagrap.listType;
1223
- return listType === _univerjs_core.PresetListType.CHECK_LIST || listType === _univerjs_core.PresetListType.CHECK_LIST_CHECKED;
1224
- }
1225
- /**
1226
- * Set the checked state of a task/checklist paragraph.
1227
- * @param {string} key The paragraph id.
1228
- * @param {boolean} checked Whether the task should be checked.
1229
- * @returns {boolean} `true` if the task state was updated, or `false` if the paragraph is not a task item.
1230
- * @example
1231
- * ```ts
1232
- * const doc = univerAPI.getActiveDocument();
1233
- * if (!doc) throw new Error('No active document');
1234
- *
1235
- * const paragraph = doc.getBody().getChild(0).asParagraph();
1236
- * doc.getBody().setTaskChecked(paragraph.getKey(), true);
1237
- * ```
1238
- */
1239
- setTaskChecked(key, checked) {
1240
- const resolved = this.resolveParagraph(key);
1241
- const bullet = resolved.paragraph.bullet;
1242
- if (!bullet || !this.isTaskParagraph(key)) return false;
1243
- const updateBody = {
1244
- dataStream: "",
1245
- paragraphs: [{
1246
- ...resolved.paragraph,
1247
- startIndex: 0,
1248
- bullet: {
1249
- ...bullet,
1250
- listType: checked ? _univerjs_core.PresetListType.CHECK_LIST_CHECKED : _univerjs_core.PresetListType.CHECK_LIST
1251
- }
1252
- }]
1253
- };
1254
- this._preserveExplicitParagraphIds(updateBody);
1255
- return this._retainBodyRange({
1256
- startOffset: resolved.endOffset,
1257
- endOffset: resolved.endOffset + 1
1258
- }, updateBody, _univerjs_core.UpdateDocsAttributeType.REPLACE);
1259
- }
1260
- /**
1261
- * Resolve a paragraph id to its current paragraph metadata.
1262
- * @param {string} key The paragraph id.
1263
- * @returns {IFDocResolvedParagraph} The current paragraph metadata.
1264
- * @example
1265
- * ```ts
1266
- * const doc = univerAPI.getActiveDocument();
1267
- * if (!doc) throw new Error('No active document');
1268
- *
1269
- * const paragraph = doc.getBody().getChild(0).asParagraph();
1270
- * const resolved = doc.getBody().resolveParagraph(paragraph.getKey());
1271
- * console.log(resolved.paragraphIndex);
1272
- * ```
1273
- */
1274
- resolveParagraph(key) {
1275
- var _body$paragraphs;
1276
- const body = this._getBody();
1277
- const matches = ((_body$paragraphs = body.paragraphs) !== null && _body$paragraphs !== void 0 ? _body$paragraphs : []).map((paragraph, paragraphIndex) => ({
1278
- paragraph,
1279
- paragraphIndex
1280
- })).filter(({ paragraph }) => paragraph.paragraphId === key);
1281
- if (matches.length !== 1) throw new DocElementStaleError(matches.length > 1 ? `Doc paragraph id "${key}" is duplicated.` : `Doc paragraph id "${key}" is stale.`);
1282
- const { paragraph, paragraphIndex } = matches[0];
1283
- return {
1284
- paragraph,
1285
- paragraphIndex,
1286
- startOffset: paragraphIndex > 0 ? body.paragraphs[paragraphIndex - 1].startIndex + 1 : 0,
1287
- endOffset: paragraph.startIndex
1288
- };
1289
- }
1290
- /**
1291
- * Resolve an element key to its current child metadata.
1292
- * @param {FDocElementType} type The element type.
1293
- * @param {string} key The persisted element key.
1294
- * @returns {object} The current child metadata used by the facade.
1295
- * @example
1296
- * ```ts
1297
- * const doc = univerAPI.getActiveDocument();
1298
- * if (!doc) throw new Error('No active document');
1299
- *
1300
- * const element = doc.getBody().getChild(0);
1301
- * const resolved = doc.getBody().resolveElement(element.getType(), element.getKey());
1302
- * console.log(resolved.position);
1303
- * ```
1304
- */
1305
- resolveElement(type, key) {
1306
- if (type === "paragraph") return {
1307
- type,
1308
- key,
1309
- position: this.resolveParagraph(key).startOffset,
1310
- priority: 3
1311
- };
1312
- const child = this._getChildren().find((item) => item.type === type && item.key === key);
1313
- if (!child) throw new Error("Doc element is stale");
1314
- return child;
1315
- }
1316
- /**
1317
- * Get a callout, quote, or code block range by block id.
1318
- * @param {string} key The persisted block range id.
1319
- * @returns {IDocumentBlockRange} The matching block range snapshot.
1320
- * @example
1321
- * ```ts
1322
- * const doc = univerAPI.getActiveDocument();
1323
- * if (!doc) throw new Error('No active document');
1324
- *
1325
- * const block = doc.getBody().getChild(0).asBlockRange();
1326
- * console.log(doc.getBody().getBlockRange(block.getKey()).blockType);
1327
- * ```
1328
- */
1329
- getBlockRange(key) {
1330
- var _this$_getBody$blockR;
1331
- const blockRange = (_this$_getBody$blockR = this._getBody().blockRanges) === null || _this$_getBody$blockR === void 0 ? void 0 : _this$_getBody$blockR.find((item) => item.blockId === key);
1332
- if (!blockRange) throw new Error("Doc element is stale");
1333
- return blockRange;
1334
- }
1335
- /**
1336
- * Get the text inside a callout, quote, or code block range.
1337
- * @param {string} key The persisted block range id.
1338
- * @returns {string} The block range text.
1339
- * @example
1340
- * ```ts
1341
- * const doc = univerAPI.getActiveDocument();
1342
- * if (!doc) throw new Error('No active document');
1343
- *
1344
- * const block = doc.getBody().getChild(0).asBlockRange();
1345
- * console.log(doc.getBody().getBlockRangeText(block.getKey()));
1346
- * ```
1347
- */
1348
- getBlockRangeText(key) {
1349
- const blockRange = this.getBlockRange(key);
1350
- return this._getBody().dataStream.slice(blockRange.startIndex, blockRange.endIndex);
1351
- }
1352
- /**
1353
- * Replace the text inside a callout, quote, or code block range.
1354
- * @param {string} key The persisted block range id.
1355
- * @param {string} text The replacement text.
1356
- * @returns {boolean} `true` if the text was replaced.
1357
- * @example
1358
- * ```ts
1359
- * const doc = univerAPI.getActiveDocument();
1360
- * if (!doc) throw new Error('No active document');
1361
- *
1362
- * const block = doc.getBody().getChild(0).asBlockRange();
1363
- * doc.getBody().setBlockRangeText(block.getKey(), 'Updated block');
1364
- * ```
1365
- */
1366
- setBlockRangeText(key, text) {
1367
- const blockRange = this.getBlockRange(key);
1368
- const body = buildPlainTextInsertBody(`${text}\r`);
1369
- body.blockRanges = [{
1370
- ...blockRange,
1371
- startIndex: 0,
1372
- endIndex: text.length
1373
- }];
1374
- return this.replaceRange({
1375
- startOffset: blockRange.startIndex,
1376
- endOffset: blockRange.endIndex + 1
1377
- }, { body });
1378
- }
1379
- /**
1380
- * Remove a callout, quote, or code block range and its content.
1381
- * @param {string} key The persisted block range id.
1382
- * @returns {boolean} `true` if the block range content was removed.
1383
- * @example
1384
- * ```ts
1385
- * const doc = univerAPI.getActiveDocument();
1386
- * if (!doc) throw new Error('No active document');
776
+ * const fDocument = univerAPI.getActiveDocument();
777
+ * const fDocumentBody = fDocument.getBody();
778
+ * const element = fDocumentBody.getElement(0);
1387
779
  *
1388
- * const block = doc.getBody().getChild(0).asBlockRange();
1389
- * doc.getBody().removeBlockRange(block.getKey());
780
+ * if (element?.isParagraph()) {
781
+ * const paragraph = element.asParagraph();
782
+ * const removed = fDocumentBody.removeParagraph(paragraph);
783
+ * console.log(removed ? 'Paragraph removed' : 'Failed to remove paragraph');
784
+ * }
1390
785
  * ```
1391
786
  */
1392
- removeBlockRange(key) {
1393
- const blockRange = this.getBlockRange(key);
787
+ removeParagraph(paragraph) {
788
+ const { startOffset, endOffset } = paragraph.getResolvedParagraphInfo();
1394
789
  return this.deleteRange({
1395
- startOffset: blockRange.startIndex,
1396
- endOffset: blockRange.endIndex + 1
1397
- });
1398
- }
1399
- /**
1400
- * Get a table marker by table id.
1401
- * @param {string} key The persisted table id.
1402
- * @returns {ICustomTable} The matching table marker.
1403
- * @example
1404
- * ```ts
1405
- * const doc = univerAPI.getActiveDocument();
1406
- * if (!doc) throw new Error('No active document');
1407
- *
1408
- * const table = doc.getBody().getChild(0).asTable();
1409
- * console.log(doc.getBody().getTable(table.getTableId()));
1410
- * ```
1411
- */
1412
- getTable(key) {
1413
- var _this$_getBody$tables;
1414
- const table = (_this$_getBody$tables = this._getBody().tables) === null || _this$_getBody$tables === void 0 ? void 0 : _this$_getBody$tables.find((item) => item.tableId === key);
1415
- if (!table) throw new Error("Doc element is stale");
1416
- return table;
790
+ startOffset,
791
+ endOffset: endOffset + 1
792
+ });
1417
793
  }
1418
794
  /**
1419
- * Remove a table marker and its content range.
1420
- * @param {string} key The persisted table id.
1421
- * @returns {boolean} `true` if the table range was removed.
795
+ * Remove a callout, quote, or code block range and its content.
796
+ * @param {FDocumentBlockRange} blockRange The block range handle to remove.
797
+ * @returns {boolean} `true` if the block range content was removed.
1422
798
  * @example
1423
799
  * ```ts
1424
- * const doc = univerAPI.getActiveDocument();
1425
- * if (!doc) throw new Error('No active document');
800
+ * const fDocument = univerAPI.getActiveDocument();
801
+ * const fDocumentBody = fDocument.getBody();
802
+ * const element = fDocumentBody.getElement(0);
1426
803
  *
1427
- * const table = doc.getBody().getChild(0).asTable();
1428
- * doc.getBody().removeTable(table.getTableId());
804
+ * if (element?.isBlockRange()) {
805
+ * const blockRange = element.asBlockRange();
806
+ * const removed = fDocumentBody.removeBlockRange(blockRange);
807
+ * console.log(removed ? 'Block range removed' : 'Failed to remove block range');
808
+ * }
1429
809
  * ```
1430
810
  */
1431
- removeTable(key) {
1432
- const table = this.getTable(key);
811
+ removeBlockRange(blockRange) {
812
+ const { startIndex, endIndex } = blockRange.getBlockRange();
1433
813
  return this.deleteRange({
1434
- startOffset: table.startIndex,
1435
- endOffset: table.endIndex + 1
814
+ startOffset: startIndex,
815
+ endOffset: endIndex + 1
1436
816
  });
1437
817
  }
1438
818
  /**
1439
- * Get a custom block marker by block id.
1440
- * @param {string} key The persisted custom block id.
1441
- * @returns {ICustomBlock} The matching custom block marker.
819
+ * Remove a table marker and its content range.
820
+ * @returns {boolean} `true` if the table range was removed.
1442
821
  * @example
1443
822
  * ```ts
1444
- * const doc = univerAPI.getActiveDocument();
1445
- * if (!doc) throw new Error('No active document');
823
+ * const fDocument = univerAPI.getActiveDocument();
824
+ * const fDocumentBody = fDocument.getBody();
825
+ * const element = fDocumentBody.getElement(0);
1446
826
  *
1447
- * const customBlock = doc.getBody().getChild(0).asCustomBlock();
1448
- * console.log(doc.getBody().getCustomBlock(customBlock.getBlockId()));
827
+ * if (element?.isTable()) {
828
+ * const table = element.asTable();
829
+ * const removed = fDocumentBody.removeTable(table);
830
+ * console.log(removed ? 'Table removed' : 'Failed to remove table');
831
+ * }
1449
832
  * ```
1450
833
  */
1451
- getCustomBlock(key) {
1452
- var _this$_getBody$custom;
1453
- const block = (_this$_getBody$custom = this._getBody().customBlocks) === null || _this$_getBody$custom === void 0 ? void 0 : _this$_getBody$custom.find((item) => item.blockId === key);
1454
- if (!block) throw new Error("Doc element is stale");
1455
- return block;
834
+ removeTable(table) {
835
+ const { startIndex, endIndex } = table.getTable();
836
+ return this.deleteRange({
837
+ startOffset: startIndex,
838
+ endOffset: endIndex + 1
839
+ });
1456
840
  }
1457
841
  /**
1458
842
  * Remove a custom block marker and its placeholder character.
1459
- * @param {string} key The persisted custom block id.
843
+ * @param {FDocumentCustomBlock} customBlock The custom block handle to remove.
1460
844
  * @returns {boolean} `true` if the custom block placeholder was removed.
1461
845
  * @example
1462
846
  * ```ts
1463
- * const doc = univerAPI.getActiveDocument();
1464
- * if (!doc) throw new Error('No active document');
847
+ * const fDocument = univerAPI.getActiveDocument();
848
+ * const fDocumentBody = fDocument.getBody();
849
+ * const element = fDocumentBody.getElement(0);
1465
850
  *
1466
- * const customBlock = doc.getBody().getChild(0).asCustomBlock();
1467
- * doc.getBody().removeCustomBlock(customBlock.getBlockId());
851
+ * if (element?.isCustomBlock()) {
852
+ * const customBlock = element.asCustomBlock();
853
+ * const removed = fDocumentBody.removeCustomBlock(customBlock);
854
+ * console.log(removed ? 'Custom block removed' : 'Failed to remove custom block');
855
+ * }
1468
856
  * ```
1469
857
  */
1470
- removeCustomBlock(key) {
1471
- const block = this.getCustomBlock(key);
858
+ removeCustomBlock(customBlock) {
859
+ const { startIndex } = customBlock.getCustomBlock();
1472
860
  return this.deleteRange({
1473
- startOffset: block.startIndex,
1474
- endOffset: block.startIndex + 1
861
+ startOffset: startIndex,
862
+ endOffset: startIndex + 1
1475
863
  });
1476
864
  }
1477
865
  /**
1478
- * Create a sibling element wrapper relative to the current element key.
1479
- * @param {FDocElementType} type The current element type.
1480
- * @param {string} key The current element key.
1481
- * @param {-1 | 1} direction `-1` for previous sibling, `1` for next sibling.
1482
- * @returns {FDocElement | null} The sibling wrapper, or `null` if none exists.
866
+ * Resolve an element key to its current child metadata.
867
+ * @param {FDocumentElement} element The element handle to resolve.
868
+ * @returns {IFDocumentElementInfo} The current child metadata used by the facade.
1483
869
  * @example
1484
870
  * ```ts
1485
- * const doc = univerAPI.getActiveDocument();
1486
- * if (!doc) throw new Error('No active document');
1487
- *
1488
- * const element = doc.getBody().getChild(0);
1489
- * const next = doc.getBody().createSibling(element.getType(), element.getKey(), 1);
1490
- * console.log(next?.getType());
871
+ * const fDocument = univerAPI.getActiveDocument();
872
+ * const fDocumentBody = fDocument.getBody();
873
+ * const element = fDocumentBody.getElement(0);
874
+ * const resolved = fDocumentBody.resolveElement(element);
875
+ * console.log(resolved);
1491
876
  * ```
1492
877
  */
1493
- createSibling(type, key, direction) {
1494
- const index = this.getChildIndex(this._createElement(type, key));
1495
- const child = this._getChildren()[index + direction];
1496
- return child ? this._createElement(child.type, child.key) : null;
878
+ resolveElement(element) {
879
+ const { type, key } = element.getResolvedInfo();
880
+ const child = this._getChildren().find((item) => item.type === type && item.key === key);
881
+ if (!child) throw new Error("Doc element is stale");
882
+ return child;
1497
883
  }
1498
884
  _getChildren() {
1499
- var _body$paragraphs$leng, _body$paragraphs2, _body$blockRanges, _body$tables, _body$customBlocks;
1500
- const body = this._getBody();
885
+ const { paragraphs, blockRanges, tables, customBlocks } = this.getBody();
1501
886
  const children = [];
1502
- for (let index = 0; index < ((_body$paragraphs$leng = (_body$paragraphs2 = body.paragraphs) === null || _body$paragraphs2 === void 0 ? void 0 : _body$paragraphs2.length) !== null && _body$paragraphs$leng !== void 0 ? _body$paragraphs$leng : 0); index++) {
1503
- const paragraph = body.paragraphs[index];
887
+ if (paragraphs) for (let i = 0; i < paragraphs.length; i++) {
888
+ var _paragraphs2;
889
+ const paragraph = paragraphs[i];
890
+ const info = this._resolveParagraphInfo(paragraph, i, (_paragraphs2 = paragraphs[i - 1]) === null || _paragraphs2 === void 0 ? void 0 : _paragraphs2.startIndex);
891
+ children.push(info);
892
+ }
893
+ if (blockRanges) for (let i = 0; i < blockRanges.length; i++) {
894
+ const blockRange = blockRanges[i];
1504
895
  children.push({
1505
- type: "paragraph",
1506
- key: this._getParagraphId(paragraph, index),
1507
- position: index > 0 ? body.paragraphs[index - 1].startIndex + 1 : 0,
1508
- priority: 3
896
+ type: _univerjs_core.DocumentBlockType.BLOCK_RANGE,
897
+ key: blockRange.blockId,
898
+ position: blockRange.startIndex,
899
+ priority: 0
900
+ });
901
+ }
902
+ if (tables) for (let i = 0; i < tables.length; i++) {
903
+ const table = tables[i];
904
+ children.push({
905
+ type: _univerjs_core.DocumentBlockType.TABLE,
906
+ key: table.tableId,
907
+ position: table.startIndex,
908
+ priority: 1
909
+ });
910
+ }
911
+ if (customBlocks) for (let i = 0; i < customBlocks.length; i++) {
912
+ const customBlock = customBlocks[i];
913
+ children.push({
914
+ type: _univerjs_core.DocumentBlockType.CUSTOM_BLOCK,
915
+ key: customBlock.blockId,
916
+ position: customBlock.startIndex,
917
+ priority: 2
1509
918
  });
1510
919
  }
1511
- (_body$blockRanges = body.blockRanges) === null || _body$blockRanges === void 0 || _body$blockRanges.forEach((blockRange) => children.push({
1512
- type: "blockRange",
1513
- key: blockRange.blockId,
1514
- position: blockRange.startIndex,
1515
- priority: 0
1516
- }));
1517
- (_body$tables = body.tables) === null || _body$tables === void 0 || _body$tables.forEach((table) => children.push({
1518
- type: "table",
1519
- key: table.tableId,
1520
- position: table.startIndex,
1521
- priority: 1
1522
- }));
1523
- (_body$customBlocks = body.customBlocks) === null || _body$customBlocks === void 0 || _body$customBlocks.forEach((customBlock) => children.push({
1524
- type: "customBlock",
1525
- key: customBlock.blockId,
1526
- position: customBlock.startIndex,
1527
- priority: 2
1528
- }));
1529
920
  return children.sort((a, b) => a.position - b.position || a.priority - b.priority);
1530
921
  }
1531
- _createElement(type, key) {
1532
- return new FDocElement(this, type, key);
922
+ _resolveParagraphInfo(paragraph, paragraphIndex, previousParagraphStartIndex) {
923
+ return {
924
+ type: _univerjs_core.DocumentBlockType.PARAGRAPH,
925
+ key: this._getParagraphId(paragraph, paragraphIndex),
926
+ position: paragraphIndex > 0 ? previousParagraphStartIndex + 1 : 0,
927
+ priority: 3
928
+ };
1533
929
  }
1534
- _getBody() {
1535
- const body = this._documentDataModel.getSelfOrHeaderFooterModel(this._segmentId).getBody();
1536
- if (!body) throw new Error("The document body is empty");
1537
- return body;
930
+ _getParagraphId(paragraph, paragraphIndex) {
931
+ if (!paragraph) throw new Error(`Paragraph index ${paragraphIndex} is out of range.`);
932
+ if (!paragraph.paragraphId) throw new Error(`Paragraph at index ${paragraphIndex} is missing paragraphId.`);
933
+ return paragraph.paragraphId;
1538
934
  }
1539
935
  _getParagraphInsertOffset(index) {
1540
- var _body$paragraphs3;
1541
- const body = this._getBody();
1542
936
  if (index <= 0) return 0;
1543
- const paragraphs = (_body$paragraphs3 = body.paragraphs) !== null && _body$paragraphs3 !== void 0 ? _body$paragraphs3 : [];
1544
- if (paragraphs.length === 0) return Math.max(0, body.dataStream.length - 1);
937
+ const { dataStream, paragraphs = [] } = this.getBody();
938
+ if (paragraphs.length === 0) return Math.max(0, dataStream.length - 1);
1545
939
  if (index >= paragraphs.length) return paragraphs[paragraphs.length - 1].startIndex + 1;
1546
940
  return paragraphs[index - 1].startIndex + 1;
1547
941
  }
1548
- _normalizeInsertedParagraphIndex(index) {
1549
- var _this$_getBody$paragr4;
1550
- const paragraphs = (_this$_getBody$paragr4 = this._getBody().paragraphs) !== null && _this$_getBody$paragr4 !== void 0 ? _this$_getBody$paragr4 : [];
1551
- return Math.max(0, Math.min(index, paragraphs.length - 1));
1552
- }
1553
- _getParagraphId(paragraph, paragraphIndex) {
1554
- if (!paragraph) throw new RangeError(`Paragraph index ${paragraphIndex} is out of range.`);
1555
- if (!paragraph.paragraphId) throw new DocElementStaleError(`Paragraph at index ${paragraphIndex} is missing paragraphId.`);
1556
- return paragraph.paragraphId;
1557
- }
1558
- _preserveExplicitParagraphIds(body) {
1559
- body[RESTORE_INSERTED_PARAGRAPH_IDS] = true;
1560
- }
1561
- _findParagraphByRange(range) {
1562
- var _this$_getBody$paragr5;
1563
- const paragraphs = (_this$_getBody$paragr5 = this._getBody().paragraphs) !== null && _this$_getBody$paragr5 !== void 0 ? _this$_getBody$paragr5 : [];
1564
- const paragraphIndex = paragraphs.findIndex((paragraph, index) => {
1565
- return (index > 0 ? paragraphs[index - 1].startIndex + 1 : 0) <= range.startOffset && range.endOffset <= paragraph.startIndex;
1566
- });
1567
- if (paragraphIndex < 0) throw new RangeError("Range does not resolve to a paragraph.");
1568
- const paragraph = paragraphs[paragraphIndex];
1569
- return {
1570
- paragraph,
1571
- paragraphIndex,
1572
- startOffset: paragraphIndex > 0 ? paragraphs[paragraphIndex - 1].startIndex + 1 : 0,
1573
- endOffset: paragraph.startIndex
1574
- };
1575
- }
1576
942
  _replaceBodyRange(range, insertBody) {
1577
- const startOffset = range.startOffset;
1578
- const endOffset = range.endOffset;
943
+ const { startOffset, endOffset } = range;
1579
944
  const textX = new _univerjs_core.TextX();
1580
945
  if (startOffset > 0) textX.push({
1581
946
  t: _univerjs_core.TextXActionType.RETAIN,
@@ -1594,7 +959,7 @@ var FDocBody = class {
1594
959
  }
1595
960
  _retainBodyRange(range, body, coverType) {
1596
961
  var _body$textRuns;
1597
- if (((_body$textRuns = body.textRuns) === null || _body$textRuns === void 0 ? void 0 : _body$textRuns.length) && this._getBody().textRuns == null) this._ensureTextRuns();
962
+ if (((_body$textRuns = body.textRuns) === null || _body$textRuns === void 0 ? void 0 : _body$textRuns.length) && this.getBody().textRuns == null) this._ensureTextRuns();
1598
963
  const textX = new _univerjs_core.TextX();
1599
964
  if (range.startOffset > 0) textX.push({
1600
965
  t: _univerjs_core.TextXActionType.RETAIN,
@@ -1609,73 +974,27 @@ var FDocBody = class {
1609
974
  return this._executeTextX(textX);
1610
975
  }
1611
976
  _ensureTextRuns() {
1612
- if (this._getBody().textRuns != null) return;
1613
977
  const actions = _univerjs_core.JSONX.getInstance().replaceOp([...(0, _univerjs_core.getRichTextEditPath)(this._documentDataModel, this._segmentId), "textRuns"], void 0, []);
1614
- this._commandService.syncExecuteCommand(_univerjs_docs.RichTextEditingMutation.id, {
978
+ this._injector.get(_univerjs_core.ICommandService).syncExecuteCommand(_univerjs_docs.RichTextEditingMutation.id, {
1615
979
  unitId: this._documentDataModel.getUnitId(),
1616
980
  segmentId: this._segmentId,
1617
981
  actions,
1618
982
  textRanges: [],
1619
- trigger: FACADE_TRIGGER,
1620
983
  isEditing: false
1621
984
  });
1622
985
  }
1623
986
  _executeTextX(textX) {
1624
987
  const actions = _univerjs_core.JSONX.getInstance().editOp(textX.serialize(), (0, _univerjs_core.getRichTextEditPath)(this._documentDataModel, this._segmentId));
1625
- const result = this._commandService.syncExecuteCommand(_univerjs_docs.RichTextEditingMutation.id, {
988
+ return this._injector.get(_univerjs_core.ICommandService).syncExecuteCommand(_univerjs_docs.RichTextEditingMutation.id, {
1626
989
  unitId: this._documentDataModel.getUnitId(),
1627
990
  segmentId: this._segmentId,
1628
991
  actions,
1629
992
  textRanges: [],
1630
- trigger: FACADE_TRIGGER,
1631
993
  isEditing: false
1632
- });
1633
- return Boolean(result);
994
+ }) !== false;
1634
995
  }
1635
996
  };
1636
997
 
1637
- //#endregion
1638
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/typeof.js
1639
- function _typeof(o) {
1640
- "@babel/helpers - typeof";
1641
- return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
1642
- return typeof o;
1643
- } : function(o) {
1644
- return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
1645
- }, _typeof(o);
1646
- }
1647
-
1648
- //#endregion
1649
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/toPrimitive.js
1650
- function toPrimitive(t, r) {
1651
- if ("object" != _typeof(t) || !t) return t;
1652
- var e = t[Symbol.toPrimitive];
1653
- if (void 0 !== e) {
1654
- var i = e.call(t, r || "default");
1655
- if ("object" != _typeof(i)) return i;
1656
- throw new TypeError("@@toPrimitive must return a primitive value.");
1657
- }
1658
- return ("string" === r ? String : Number)(t);
1659
- }
1660
-
1661
- //#endregion
1662
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/toPropertyKey.js
1663
- function toPropertyKey(t) {
1664
- var i = toPrimitive(t, "string");
1665
- return "symbol" == _typeof(i) ? i : i + "";
1666
- }
1667
-
1668
- //#endregion
1669
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/defineProperty.js
1670
- function _defineProperty(e, r, t) {
1671
- return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
1672
- value: t,
1673
- enumerable: !0,
1674
- configurable: !0,
1675
- writable: !0
1676
- }) : e[r] = t, e;
1677
- }
1678
-
1679
998
  //#endregion
1680
999
  //#region \0@oxc-project+runtime@0.137.0/helpers/esm/decorateParam.js
1681
1000
  function __decorateParam(paramIndex, decorator) {
@@ -1704,7 +1023,6 @@ let FDocument = class FDocument extends _univerjs_core_facade.FBaseInitialable {
1704
1023
  this._resourceLoaderService = _resourceLoaderService;
1705
1024
  this._commandService = _commandService;
1706
1025
  _defineProperty(this, "id", void 0);
1707
- _defineProperty(this, "_docElementRegistry", new DocElementRegistry());
1708
1026
  this.id = this._documentDataModel.getUnitId();
1709
1027
  }
1710
1028
  /**
@@ -1728,19 +1046,23 @@ let FDocument = class FDocument extends _univerjs_core_facade.FBaseInitialable {
1728
1046
  * use their persisted `paragraphId` values. Persisted elements, such as tables
1729
1047
  * and custom blocks, use their existing ids.
1730
1048
  *
1731
- * @returns {FDocBody} The document body API instance.
1049
+ * @returns {FDocumentBody} The document body API instance.
1732
1050
  * @example
1733
1051
  * ```typescript
1734
- * const doc = univerAPI.getActiveDocument();
1735
- * if (!doc) throw new Error('No active document');
1736
- *
1737
- * const body = doc.getBody();
1738
- * const paragraph = body.getChild(0).asParagraph();
1739
- * paragraph.appendText(' updated');
1052
+ * const fDocument = univerAPI.getActiveDocument();
1053
+ * const fDocumentBody = fDocument.getBody();
1054
+ * console.log(fDocumentBody.getBody());
1055
+ *
1056
+ * const element = fDocumentBody.getElement(0);
1057
+ * if (element.isParagraph()) {
1058
+ * const paragraph = element.asParagraph();
1059
+ * paragraph.appendText(' updated');
1060
+ * console.log(paragraph.getText());
1061
+ * }
1740
1062
  * ```
1741
1063
  */
1742
1064
  getBody() {
1743
- return new FDocBody(this._documentDataModel, this._commandService, this._docElementRegistry);
1065
+ return this._injector.createInstance(FDocumentBody, this._documentDataModel, this._injector);
1744
1066
  }
1745
1067
  dispose() {
1746
1068
  super.dispose();
@@ -1812,168 +1134,275 @@ let FDocument = class FDocument extends _univerjs_core_facade.FBaseInitialable {
1812
1134
  this._univerInstanceService.focusUnit(this.id);
1813
1135
  return this._commandService.syncExecuteCommand(_univerjs_core.RedoCommand.id);
1814
1136
  }
1137
+ };
1138
+ FDocument = __decorate([
1139
+ __decorateParam(1, (0, _univerjs_core.Inject)(_univerjs_core.Injector)),
1140
+ __decorateParam(2, _univerjs_core.IUniverInstanceService),
1141
+ __decorateParam(3, (0, _univerjs_core.Inject)(_univerjs_core.IResourceLoaderService)),
1142
+ __decorateParam(4, _univerjs_core.ICommandService)
1143
+ ], FDocument);
1144
+
1145
+ //#endregion
1146
+ //#region src/facade/f-univer.ts
1147
+ var FUniverDocsMixin = class extends _univerjs_core_facade.FUniver {
1148
+ createDocument(data) {
1149
+ const document = this._injector.get(_univerjs_core.IUniverInstanceService).createUnit(_univerjs_core.UniverInstanceType.UNIVER_DOC, data);
1150
+ return this._injector.createInstance(FDocument, document);
1151
+ }
1152
+ getActiveDocument() {
1153
+ const document = this._univerInstanceService.getCurrentUnitOfType(_univerjs_core.UniverInstanceType.UNIVER_DOC);
1154
+ if (!document) return null;
1155
+ return this._injector.createInstance(FDocument, document);
1156
+ }
1157
+ getDocument(id) {
1158
+ const document = this._univerInstanceService.getUnit(id, _univerjs_core.UniverInstanceType.UNIVER_DOC);
1159
+ if (!document) return null;
1160
+ return this._injector.createInstance(FDocument, document);
1161
+ }
1162
+ };
1163
+ _univerjs_core_facade.FUniver.extend(FUniverDocsMixin);
1164
+
1165
+ //#endregion
1166
+ //#region src/facade/f-document-block-range.ts
1167
+ /**
1168
+ * A facade wrapper for document block ranges, such as callout, quote, and code blocks.
1169
+ *
1170
+ * Block range identity is backed by the persisted `IDocumentBlockRange.blockId`,
1171
+ * so wrappers can be re-resolved after text is inserted before the block range.
1172
+ *
1173
+ * @hideconstructor
1174
+ */
1175
+ var FDocumentBlockRange = class extends FDocumentElement {
1176
+ constructor(body, bodyEdit, info, injector) {
1177
+ super(body, bodyEdit, info, injector);
1178
+ this.body = body;
1179
+ this.bodyEdit = bodyEdit;
1180
+ this.info = info;
1181
+ this.injector = injector;
1182
+ if (this.getType() !== _univerjs_core.DocumentBlockType.BLOCK_RANGE) throw new Error(`Element type is not a block range: ${this.getType()}`);
1183
+ }
1815
1184
  /**
1816
- * Adds the specified text to the end of this text region.
1817
- * @param {string} text - The text to be added to the end of this text region.
1818
- * @return {boolean} `true` if the text was successfully appended, or `false` if it failed.
1185
+ * Get the top-level block range data model.
1186
+ * @returns {IDocumentBlockRange} The block range data model.
1819
1187
  * @example
1820
- * ```typescript
1188
+ * ```ts
1821
1189
  * const fDocument = univerAPI.getActiveDocument();
1822
- * const success = fDocument.appendText('Hello, world!');
1823
- * console.log(success);
1190
+ * const fDocumentBody = fDocument.getBody();
1191
+ * const element = fDocumentBody.getElement(0);
1192
+ *
1193
+ * if (element?.isBlockRange()) {
1194
+ * const blockRange = element.asBlockRange();
1195
+ * console.log(blockRange.getBlockRange());
1196
+ * }
1824
1197
  * ```
1825
1198
  */
1826
- appendText(text) {
1827
- const { body } = this.save();
1828
- if (!body) throw new Error("The document body is empty");
1829
- const lastPosition = body.dataStream.length - 2;
1830
- return this.insertText(text, {
1831
- startOffset: lastPosition,
1832
- endOffset: lastPosition,
1833
- segmentId: ""
1834
- });
1199
+ getBlockRange() {
1200
+ const { blockRanges = [] } = this._body.getBody();
1201
+ const blockRange = blockRanges.find((blockRange) => blockRange.blockId === this.getKey());
1202
+ if (!blockRange) throw new Error(`Block range not found: ${this.getKey()}`);
1203
+ return blockRange;
1835
1204
  }
1836
1205
  /**
1837
- * Inserts text at the provided document range. Defaults to appending before the final section break.
1838
- * @param {string} text - The text to insert.
1839
- * @param {IDocumentInsertTextFacadeOptions} options - Optional target range, segment id, and cursor offset.
1840
- * @returns {boolean} `true` if the text was successfully inserted, or `false` if it failed.
1206
+ * Get the block range type.
1207
+ * @returns {DocumentBlockRangeType} The block type, such as callout, quote, or code.
1841
1208
  * @example
1842
- *
1843
- * // Insert text at a specific range in the document body
1844
- * ```typescript
1209
+ * ```ts
1845
1210
  * const fDocument = univerAPI.getActiveDocument();
1846
- * const success = fDocument.insertText('Hello, world!', {
1847
- * startOffset: 5,
1848
- * endOffset: 5,
1849
- * segmentId: '',
1850
- * cursorOffset: 13,
1851
- * });
1852
- * console.log(success);
1211
+ * const fDocumentBody = fDocument.getBody();
1212
+ * const element = fDocumentBody.getElement(0);
1213
+ *
1214
+ * if (element?.isBlockRange()) {
1215
+ * const blockRange = element.asBlockRange();
1216
+ * console.log(blockRange.getBlockType());
1217
+ * }
1853
1218
  * ```
1219
+ */
1220
+ getBlockType() {
1221
+ return this.getBlockRange().blockType;
1222
+ }
1223
+ /**
1224
+ * Get the plain text inside this block range.
1225
+ * @returns {string} The block range text.
1226
+ * @example
1227
+ * ```ts
1228
+ * const fDocument = univerAPI.getActiveDocument();
1229
+ * const fDocumentBody = fDocument.getBody();
1230
+ * const element = fDocumentBody.getElement(0);
1854
1231
  *
1855
- * // Insert text at the beginning of a header or footer segment
1856
- * ```typescript
1232
+ * if (element?.isBlockRange()) {
1233
+ * const blockRange = element.asBlockRange();
1234
+ * console.log(blockRange.getText());
1235
+ * }
1236
+ * ```
1237
+ */
1238
+ getText() {
1239
+ const { dataStream } = this._body.getBody();
1240
+ const { startIndex, endIndex } = this.getBlockRange();
1241
+ return dataStream.slice(startIndex, endIndex);
1242
+ }
1243
+ /**
1244
+ * Replace the plain text inside this block range.
1245
+ * @param {string} text The replacement text.
1246
+ * @returns {boolean} `true` if the block range text was replaced.
1247
+ * @example
1248
+ * ```ts
1857
1249
  * const fDocument = univerAPI.getActiveDocument();
1858
- * const snapshot = fDocument.save();
1859
- * const { headers, footers } = snapshot;
1250
+ * const fDocumentBody = fDocument.getBody();
1251
+ * const element = fDocumentBody.getElement(0);
1860
1252
  *
1861
- * if (headers) {
1862
- * for (const headerId in headers) {
1863
- * if (headerId === 'target-header-id') {
1864
- * fDocument.insertText('Hello, header!', {
1865
- * startOffset: 0,
1866
- * endOffset: 0,
1867
- * segmentId: headerId,
1868
- * });
1869
- * }
1870
- * }
1253
+ * if (element?.isBlockRange()) {
1254
+ * const blockRange = element.asBlockRange();
1255
+ * blockRange.setText('Updated block text');
1256
+ * console.log(blockRange.getText());
1871
1257
  * }
1258
+ * ```
1259
+ */
1260
+ setText(text) {
1261
+ const blockRange = this.getBlockRange();
1262
+ const { startIndex, endIndex } = blockRange;
1263
+ const updateBody = buildPlainTextInsertBody(`${text}\r`);
1264
+ updateBody.blockRanges = [{
1265
+ ...blockRange,
1266
+ startIndex: 0,
1267
+ endIndex: text.length
1268
+ }];
1269
+ return this._bodyEdit.replaceRange({
1270
+ startOffset: startIndex,
1271
+ endOffset: endIndex + 1
1272
+ }, updateBody);
1273
+ }
1274
+ /**
1275
+ * Remove this block range wrapper from the body.
1872
1276
  *
1873
- * if (footers) {
1874
- * for (const footerId in footers) {
1875
- * if (footerId === 'target-footer-id') {
1876
- * fDocument.insertText('Hello, footer!', {
1877
- * startOffset: 0,
1878
- * endOffset: 0,
1879
- * segmentId: footerId,
1880
- * });
1881
- * }
1882
- * }
1277
+ * This currently removes the block range and its content, matching
1278
+ * `remove()`.
1279
+ *
1280
+ * @returns {boolean} `true` if the block range content was removed.
1281
+ * @example
1282
+ * ```ts
1283
+ * const fDocument = univerAPI.getActiveDocument();
1284
+ * const fDocumentBody = fDocument.getBody();
1285
+ * const element = fDocumentBody.getElement(0);
1286
+ *
1287
+ * if (element?.isBlockRange()) {
1288
+ * const blockRange = element.asBlockRange();
1289
+ * const removed = blockRange.unwrap();
1290
+ * console.log(removed ? 'Block range removed' : 'Failed to remove block range');
1883
1291
  * }
1884
1292
  * ```
1885
1293
  */
1886
- insertText(text, options = {}) {
1887
- var _options$startOffset, _options$endOffset, _options$segmentId;
1888
- const unitId = this.id;
1889
- const { body } = this.save();
1890
- if (!body) throw new Error("The document body is empty");
1891
- const startOffset = (_options$startOffset = options.startOffset) !== null && _options$startOffset !== void 0 ? _options$startOffset : Math.max(0, body.dataStream.length - 2);
1892
- const endOffset = (_options$endOffset = options.endOffset) !== null && _options$endOffset !== void 0 ? _options$endOffset : startOffset;
1893
- const segmentId = (_options$segmentId = options.segmentId) !== null && _options$segmentId !== void 0 ? _options$segmentId : "";
1894
- const activeRange = {
1895
- startOffset,
1896
- endOffset,
1897
- collapsed: startOffset === endOffset,
1898
- segmentId
1899
- };
1900
- const removeLeadingParagraphBreak = startOffset === 0;
1901
- const insertBody = buildPlainTextInsertBody(text, {
1902
- paragraphStyle: getParagraphStyleAtOffset(body, startOffset),
1903
- removeLeadingParagraphBreak
1904
- });
1905
- const cursorOffset = options.cursorOffset == null ? void 0 : getNormalizedPlainTextCursorOffset(text, options.cursorOffset, removeLeadingParagraphBreak);
1906
- return this._commandService.syncExecuteCommand(_univerjs_docs.InsertTextCommand.id, {
1907
- unitId,
1908
- body: insertBody,
1909
- range: activeRange,
1910
- segmentId,
1911
- ...cursorOffset == null ? {} : { cursorOffset }
1912
- });
1294
+ unwrap() {
1295
+ return this.remove();
1296
+ }
1297
+ };
1298
+ var FDocumentBlockRangeMixin = class extends FDocumentElement {
1299
+ asBlockRange() {
1300
+ if (this.getType() !== _univerjs_core.DocumentBlockType.BLOCK_RANGE) throw new Error(`Element type is not a block range: ${this.getType()}`);
1301
+ return this._injector.createInstance(FDocumentBlockRange, this._body, this._bodyEdit, this.getResolvedInfo(), this._injector);
1302
+ }
1303
+ };
1304
+ FDocumentElement.extend(FDocumentBlockRangeMixin);
1305
+
1306
+ //#endregion
1307
+ //#region src/facade/f-document-custom-block.ts
1308
+ /**
1309
+ * A facade wrapper for document top-level custom blocks.
1310
+ * @hideconstructor
1311
+ */
1312
+ var FDocumentCustomBlock = class extends FDocumentElement {
1313
+ constructor(body, bodyEdit, info, injector) {
1314
+ super(body, bodyEdit, info, injector);
1315
+ this.body = body;
1316
+ this.bodyEdit = bodyEdit;
1317
+ this.info = info;
1318
+ this.injector = injector;
1319
+ if (this.getType() !== _univerjs_core.DocumentBlockType.CUSTOM_BLOCK) throw new Error(`Element type is not a custom block: ${this.getType()}`);
1913
1320
  }
1914
1321
  /**
1915
- * Inserts one or more plain-text paragraphs at the provided document range.
1916
- * @param {string} text - The paragraph text to insert. Newlines are normalized to document paragraph separators.
1917
- * @param {IDocumentInsertTextFacadeOptions} options - Optional target range, segment id, and cursor offset.
1918
- * @returns {boolean} `true` if the paragraphs were successfully inserted, or `false` if it failed.
1322
+ * Get the custom block marker.
1323
+ * @returns {ICustomBlock} The custom block marker.
1919
1324
  * @example
1920
- * ```typescript
1325
+ * ```ts
1921
1326
  * const fDocument = univerAPI.getActiveDocument();
1922
- * const success = fDocument.insertParagraph('Hello, world! This is a new paragraph.', {
1923
- * startOffset: 5,
1924
- * endOffset: 5,
1925
- * });
1926
- * console.log(success);
1327
+ * const fDocumentBody = fDocument.getBody();
1328
+ * const element = fDocumentBody.getElement(0);
1329
+ *
1330
+ * if (element?.isCustomBlock()) {
1331
+ * const customBlock = element.asCustomBlock();
1332
+ * console.log(customBlock.getCustomBlock());
1333
+ * }
1927
1334
  * ```
1928
1335
  */
1929
- insertParagraph(text = "", options = {}) {
1930
- var _options$cursorOffset;
1931
- const dataStream = `${text.replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n").join("\r\n")}\r\n`;
1932
- return this.insertText(dataStream, {
1933
- ...options,
1934
- cursorOffset: (_options$cursorOffset = options.cursorOffset) !== null && _options$cursorOffset !== void 0 ? _options$cursorOffset : dataStream.length
1935
- });
1336
+ getCustomBlock() {
1337
+ const { customBlocks = [] } = this._body.getBody();
1338
+ const block = customBlocks.find((item) => item.blockId === this.getKey());
1339
+ if (!block) throw new Error("Doc custom block is stale");
1340
+ return block;
1936
1341
  }
1937
1342
  };
1938
- FDocument = __decorate([
1939
- __decorateParam(1, (0, _univerjs_core.Inject)(_univerjs_core.Injector)),
1940
- __decorateParam(2, _univerjs_core.IUniverInstanceService),
1941
- __decorateParam(3, (0, _univerjs_core.Inject)(_univerjs_core.IResourceLoaderService)),
1942
- __decorateParam(4, _univerjs_core.ICommandService)
1943
- ], FDocument);
1343
+ var FDocumentCustomBlockMixin = class extends FDocumentElement {
1344
+ asCustomBlock() {
1345
+ if (this.getType() !== _univerjs_core.DocumentBlockType.CUSTOM_BLOCK) throw new Error(`Element type is not a custom block: ${this.getType()}`);
1346
+ return this._injector.createInstance(FDocumentCustomBlock, this._body, this._bodyEdit, this.getResolvedInfo(), this._injector);
1347
+ }
1348
+ };
1349
+ FDocumentElement.extend(FDocumentCustomBlockMixin);
1944
1350
 
1945
1351
  //#endregion
1946
- //#region src/facade/f-univer.ts
1947
- var FUniverDocsMixin = class extends _univerjs_core_facade.FUniver {
1948
- createDocument(data) {
1949
- const document = this._injector.get(_univerjs_core.IUniverInstanceService).createUnit(_univerjs_core.UniverInstanceType.UNIVER_DOC, data);
1950
- return this._injector.createInstance(FDocument, document);
1352
+ //#region src/facade/f-document-table.ts
1353
+ /**
1354
+ * A facade wrapper for document top-level tables.
1355
+ * @hideconstructor
1356
+ */
1357
+ var FDocumentTable = class extends FDocumentElement {
1358
+ constructor(body, bodyEdit, info, injector) {
1359
+ super(body, bodyEdit, info, injector);
1360
+ this.body = body;
1361
+ this.bodyEdit = bodyEdit;
1362
+ this.info = info;
1363
+ this.injector = injector;
1364
+ if (this.getType() !== _univerjs_core.DocumentBlockType.TABLE) throw new Error(`Element type is not a table: ${this.getType()}`);
1951
1365
  }
1952
- getActiveDocument() {
1953
- const document = this._univerInstanceService.getCurrentUnitOfType(_univerjs_core.UniverInstanceType.UNIVER_DOC);
1954
- if (!document) return null;
1955
- return this._injector.createInstance(FDocument, document);
1366
+ /**
1367
+ * Get the table marker.
1368
+ * @returns {ICustomTable} The table marker.
1369
+ * @example
1370
+ * ```ts
1371
+ * const fDocument = univerAPI.getActiveDocument();
1372
+ * const fDocumentBody = fDocument.getBody();
1373
+ * const element = fDocumentBody.getElement(0);
1374
+ *
1375
+ * if (element?.isTable()) {
1376
+ * const table = element.asTable();
1377
+ * console.log(table.getTable());
1378
+ * }
1379
+ * ```
1380
+ */
1381
+ getTable() {
1382
+ const { tables = [] } = this._body.getBody();
1383
+ const table = tables.find((item) => item.tableId === this.getKey());
1384
+ if (!table) throw new Error("Doc table is stale");
1385
+ return table;
1956
1386
  }
1957
- getDocument(id) {
1958
- const document = this._univerInstanceService.getUnit(id, _univerjs_core.UniverInstanceType.UNIVER_DOC);
1959
- if (!document) return null;
1960
- return this._injector.createInstance(FDocument, document);
1387
+ };
1388
+ var FDocumentTableMixin = class extends FDocumentElement {
1389
+ asTable() {
1390
+ if (this.getType() !== _univerjs_core.DocumentBlockType.TABLE) throw new Error(`Element type is not a table: ${this.getType()}`);
1391
+ return this._injector.createInstance(FDocumentTable, this._body, this._bodyEdit, this.getResolvedInfo(), this._injector);
1961
1392
  }
1962
1393
  };
1963
- _univerjs_core_facade.FUniver.extend(FUniverDocsMixin);
1394
+ FDocumentElement.extend(FDocumentTableMixin);
1964
1395
 
1965
1396
  //#endregion
1966
- exports.DocElementRegistry = DocElementRegistry;
1967
- exports.DocElementStaleError = DocElementStaleError;
1968
- exports.FDocBlockRange = FDocBlockRange;
1969
- exports.FDocBody = FDocBody;
1970
- exports.FDocCustomBlock = FDocCustomBlock;
1971
- exports.FDocElement = FDocElement;
1972
- exports.FDocParagraph = FDocParagraph;
1973
- exports.FDocTable = FDocTable;
1974
1397
  Object.defineProperty(exports, 'FDocument', {
1975
1398
  enumerable: true,
1976
1399
  get: function () {
1977
1400
  return FDocument;
1978
1401
  }
1979
- });
1402
+ });
1403
+ exports.FDocumentBlockRange = FDocumentBlockRange;
1404
+ exports.FDocumentBody = FDocumentBody;
1405
+ exports.FDocumentCustomBlock = FDocumentCustomBlock;
1406
+ exports.FDocumentElement = FDocumentElement;
1407
+ exports.FDocumentParagraph = FDocumentParagraph;
1408
+ exports.FDocumentTable = FDocumentTable;