@docx-editor.dev/editor-api 2.30.0 → 2.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,6 +2,8 @@
2
2
 
3
3
  The public document model follows a documented subset of Word's Office.js API. Host creation, authentication, collaboration transport, and job lifetime belong outside that model.
4
4
 
5
+ Use this API for headless, server, and agent pipelines. To build a review UI in a React or Vue host, use `useReview()` and `DocxEditorReview` from `@docx-editor.dev/pro/react` or `@docx-editor.dev/pro/vue` instead. For the task-by-task choice, see `docs/index.md` in this package.
6
+
5
7
  ## A complete server example
6
8
 
7
9
  This function returns a DOCX containing one pending replacement. Supply the agent's author name. The `finally` block disposes the runtime after the job.
@@ -58,13 +60,28 @@ const snapshot = await runtime.run(async (context) => {
58
60
 
59
61
  This follows Microsoft's [split-loop and correlated-objects guidance](https://learn.microsoft.com/en-us/office/dev/add-ins/concepts/correlated-objects-pattern). Bound model input and member-property loads. The collection's `items` load still enumerates its members; slicing the array does not paginate the collection on the server.
60
62
 
63
+ To load members and one of their properties in one sync, use an `items/` path and bound the collection with `top`:
64
+
65
+ ```ts
66
+ const snapshot = await runtime.run(async (context) => {
67
+ const paragraphs = context.document.body.paragraphs;
68
+ paragraphs.load({ select: 'items/text', top: 40 });
69
+ await context.sync();
70
+ return paragraphs.items.map((paragraph) => paragraph.text);
71
+ });
72
+ ```
73
+
74
+ `collection.load('text')` means the same as `collection.load('items/text')`. Only one navigation level works: `items/font/bold` and `font/bold` fail with `InvalidArgument`.
75
+
61
76
  Supported read-derived proxies can share one `sync()` with their edits. For example, `body.getRange().insertText(text, 'Replace')` and `table.getCell(0, 0).value = text` resolve their reads before one atomic write transaction. This can use extra read-only transport calls. Every phase uses the same revision; concurrent changes cause `StaleDocument`.
62
77
 
63
78
  Proxies returned by insertions require a completed `sync()` before dependent operations. Do not configure a newly inserted table, image, list, or text range before that sync. If a prerequisite fails, the runtime commits no queued writes. Completed prerequisite reads can remain loaded after a later command fails.
64
79
 
65
80
  ## Keep writes within one story
66
81
 
67
- A story is the main body, a header, a footer, or another document text container. One `context.sync()` can write only one story. Writes across stories fail with `ConflictingChanges`. Reads from different stories can share a sync.
82
+ A story is the main body, a header, a footer, or another document text container. Text and formatting writes in one `context.sync()` must target one story. Writes to multiple stories fail with `ConflictingChanges`. Reads from different stories can share a sync.
83
+
84
+ Bookmark removal is an exception: `Document.deleteBookmark()` and `Bookmark.delete()` can share a sync with writes to another story. Inserting a bookmark can also move an existing name from another story in the same transaction.
68
85
 
69
86
  If the document has a primary header and footer, resolve both objects before formatting them. Then commit each story's writes separately:
70
87
 
@@ -111,6 +128,67 @@ A sync either supplies data for the next decision or commits a complete edit. Ba
111
128
 
112
129
  Always await sync. Do not replace sequential syncs with `Promise.all()` or `forEach(async ...)`. Use an explicit final sync when writes remain queued. Do not add an empty sync after a completed read-only batch. These conventions follow Microsoft's [application-specific API model](https://learn.microsoft.com/en-us/office/dev/add-ins/develop/application-specific-api-model).
113
130
 
131
+ ### Make a browser decision one undo step
132
+
133
+ Each sync that writes is its own undo step. In the browser runtime, a decision that also uses editor methods can be one undo step. Pass an open handle from `editor.beginHistoryGroup()` as run options. Every sync in the run joins the group, and so does each editor write that receives the same handle:
134
+
135
+ ```ts
136
+ const decision = editor.beginHistoryGroup();
137
+ try {
138
+ // Reply first: the card's key no longer exists after the change is accepted.
139
+ const reply = editor.replyToReviewItem(key, 'Accepted; see the new term.', {
140
+ historyGroup: decision,
141
+ });
142
+ const accepted = editor.acceptReviewItem(key, { historyGroup: decision });
143
+ if (!reply.ok || !accepted.ok) throw new Error('The review card was refused.');
144
+ await runtime.run({ historyGroup: decision }, async (context) => {
145
+ const ranges = context.document.body.search('30 days');
146
+ ranges.load('items');
147
+ await context.sync();
148
+ const target = ranges.items[0];
149
+ if (!target) throw new Error('The document has no "30 days" text.');
150
+ target.insertText('45 days', 'Replace');
151
+ await context.sync();
152
+ });
153
+ } finally {
154
+ decision.end();
155
+ }
156
+ ```
157
+
158
+ This option is DocxEditor infrastructure with no Office.js equivalent. Server and collaborative runtimes refuse it with `NotSupported`. A closed handle, or a handle from another editor, refuses with `InvalidArgument` and target `historyGroup` before the callback runs, and nothing is written. The whole run is one write of the group: after it finishes, `decision.lastOutcome` is `split` if any of its syncs split the group. Do not reuse a handle after `end()`; begin a new one.
159
+
160
+ ### Preview a change before the user accepts it
161
+
162
+ In the browser runtime, `runtime.preview(callback)` shows the edits of a callback in the page without writing them. The callback uses the same Office.js calls as `run()`. Its reads see the preview, so write the callback as you would write the final edit. Call the model before the preview, not inside it: the editor stays editable while the callback runs.
163
+
164
+ ```ts
165
+ const proposal = await model.propose(clauseText);
166
+ const preview = await runtime.preview(async (context) => {
167
+ context.document.changeTrackingMode = 'TrackMineOnly';
168
+ const ranges = context.document.body.search(proposal.find, {
169
+ matchCase: true,
170
+ });
171
+ ranges.load('items');
172
+ await context.sync();
173
+ if (ranges.items.length !== 1) throw new Error('Choose one deadline.');
174
+ ranges.items[0]!.insertText(proposal.replace, 'Replace');
175
+ await context.sync();
176
+ });
177
+ preview.reveal();
178
+ // Keep the preview, not its proxies. Decide later:
179
+ await preview.commit({ rebase: true }); // or preview.discard()
180
+ ```
181
+
182
+ `commit()` replays the recorded batches as one undo step. It never runs the callback again. Every replayed read must match its preview result. If the live document changed, `commit()` refuses with `StaleDocument` and keeps the preview open. That refusal writes nothing.
183
+
184
+ `commit({ rebase: true })` applies the recorded edits to the current document. Ranges follow their text. A changed read result or replacement target causes a refusal. The live editor can also refuse the commit, for example if permissions change. Commit validates all recorded batches on a fresh document copy before writing. A validation refusal ends the preview without changing live content or undo and redo history.
185
+
186
+ Editor event listeners and preview status listeners run after replay and its history group finish. They observe the completed edit. Listener edits cannot interrupt a partially committed preview, and listener exceptions do not change the commit result. Unexpected live replay failures undo earlier writes. If undo fails, inspect `GeneralException` with target `preview.rollback` before further writes.
187
+
188
+ After a replay refusal, read again and build a new preview. Never repeat the model's old edit without reconsidering it. While a preview shows, the editor refuses document writes. Other runs refuse writes with `PreviewActive`. A preview refuses unsupported writes, such as tables and pictures, with `NotSupported`.
189
+
190
+ Server and collaborative runtimes refuse `preview()` with `NotSupported`. This method is DocxEditor infrastructure with no Office.js equivalent.
191
+
114
192
  ## Keep proxy lifetimes clear
115
193
 
116
194
  Keep document proxies within their `runtime.run()` callback. Return plain text or structured snapshots to the model, not `Range` or `Paragraph` objects. Do not retain a proxy in a job record or reuse it after its run finishes. Explicit tracked-object adoption exists for advanced cases; fresh reads are simpler for background workers.
@@ -124,12 +202,13 @@ Use `isDocxEditorError(error)` and branch on `error.code`. `error.target` identi
124
202
  | Code | Next action |
125
203
  | --- | --- |
126
204
  | `PropertyNotLoaded` | Load the named property and await sync before reading it. |
127
- | `InvalidObjectPath` | Sync before using a newly returned proxy, or acquire a fresh proxy in a new run. |
205
+ | `InvalidObjectPath` | Sync before using a newly returned proxy, or acquire a fresh proxy in a new run. `debugInfo.innerError.code` `edit.stale-target` means the document no longer holds the object; read again. |
128
206
  | `StaleDocument` | Search again, reconsider the model proposal, then write. |
129
207
  | `ConflictingChanges` | Separate edits that claim the same paragraph and reconsider anchors between commits. |
130
- | `NotSupported` | Check the host, tracking mode, author, and operation against the [tracking subset](#tracking-subset). |
131
- | `NotImplemented` | Check the documented subset, including pending-revision boundaries. Reconsider the target; do not disable tracking. |
208
+ | `NotSupported` | The call is outside the supported subset for this host, mode, or content. Don't retry it. Read `debugInfo.innerError.code`, then check the host, tracking mode, author, and operation against the [tracking subset](#tracking-subset). |
209
+ | `NotImplemented` | The API does not implement the call for this target, such as a tracked edit beside your own pending change. Don't retry it. Read `debugInfo.innerError.code`, reconsider the target, and do not disable tracking. |
132
210
  | `InvalidArgument` | Validate the argument and consult the member's JSDoc. |
211
+ | `GeneralException` | Act on `error.debugInfo.innerError.code` (see [Diagnostics](https://www.docx-editor.dev/docs/2.x/guides/diagnostics#edit-internal-invariant)). For `edit.internal-invariant`, or when `innerError` is absent, report the failure with the engine version and do not retry the write unchanged. |
133
212
 
134
213
  ### Read why the engine refused
135
214
 
@@ -148,7 +227,7 @@ try {
148
227
  }
149
228
  ```
150
229
 
151
- For all codes, see [Diagnostics](/docs/2.x/guides/diagnostics). To record anonymous refusal events, add a telemetry module to `createServer({ modules })`. For more information, see [Server agents](/docs/2.x/telemetry/agents).
230
+ For all codes, see [Diagnostics](https://www.docx-editor.dev/docs/2.x/guides/diagnostics). To record anonymous refusal events, add a telemetry module to `createServer({ modules })`. For more information, see [Server agents](https://www.docx-editor.dev/docs/2.x/telemetry/agents).
152
231
 
153
232
  ### Recover from a stale range
154
233
 
@@ -202,6 +281,9 @@ await runtime.run(async (context) => {
202
281
  | Replace a range | `range.insertText(text, 'Replace')` |
203
282
  | Delete range content | `range.delete()` or `range.clear()` |
204
283
  | Propose removing a paragraph | `paragraph.delete()` |
284
+ | Propose a field | `range.insertField('After', 'Ref', '_Ref123456 \\h')` |
285
+ | Write a proposed field's result | Sync, then `field.result.insertText('Figure 3', 'Replace')` |
286
+ | Propose an equation | `range.insertOoxml(flatOpcWithOneEquation, 'After')` |
205
287
  | Read the current mode | `document.load('changeTrackingMode')`, then sync and read the property |
206
288
  | Make an intentional permanent edit | Explicitly set `changeTrackingMode = 'Off'` |
207
289
 
@@ -213,11 +295,36 @@ await runtime.run(async (context) => {
213
295
  | Paragraph deletion | `paragraph.delete()` records the text and the paragraph mark as deletions; accept removes the paragraph |
214
296
  | Font and paragraphs | Track font, paragraph-format, and paragraph-style edits as property revisions |
215
297
  | Paragraph insertion | Track inserted text and paragraph marks |
298
+ | Paragraph split | `insertText()` with `\n` tracks the text and each new paragraph mark; reject joins the paragraphs again |
216
299
  | Lists | Track creation, membership, and level changes; configure newly proposed definitions |
217
300
  | Tables | Track complete insertion, cell values, row additions, and partial row deletions |
218
301
  | Content controls | Wrap nonempty ordinary text in `PlainText`, `RichText`, or `DatePicker` controls outside collaboration |
302
+ | Fields | Insert an inert field as one complex field in one tracked insertion, and write the cached result of your own pending field into it; reject removes the whole field |
303
+ | Equations | `insertOoxml()` with one inline `m:oMath` in a Flat OPC package writes one tracked insertion; reject removes the whole equation |
304
+
305
+ Tracked range edits refuse table and wrapper boundaries. In collaboration, a tracked replacement must remain within one paragraph. One refusal refuses the whole sync.
306
+
307
+ A tracked paragraph deletion fails with `NotSupported` for these paragraphs:
308
+
309
+ - The last paragraph of a story, table cell, or content control.
310
+ - A paragraph directly before a table or a block content control.
311
+ - A paragraph whose mark ends a section.
312
+ - A paragraph with an inline content control.
313
+ - A paragraph that holds a complex field boundary whose matching boundary is in another paragraph.
314
+ - A paragraph that nests inline content more than 64 levels deep.
315
+
316
+ A tracked paragraph deletion fails with `NotImplemented` in these cases:
219
317
 
220
- Tracked range edits refuse table and wrapper boundaries. In collaboration, a tracked replacement must remain within one paragraph. A tracked paragraph deletion fails with `NotSupported` for the last paragraph of a story, table cell, or content control, a paragraph directly before a table or block content control, a paragraph whose mark ends a section, a paragraph with an inline content control, a paragraph that contains a complex field boundary whose matching boundary is in another paragraph, and a paragraph that nests inline content more than 64 levels deep. It fails with `NotImplemented` when the paragraph or the start of the next paragraph has a pending change, including your own. Delete adjacent paragraphs in one sync; a later sync beside your own pending deletion refuses. A tracked deletion or replacement at the start of a paragraph whose previous paragraph mark you already proposed deleting also fails with `NotImplemented`. One refusal refuses the whole sync. Text that another participant types into struck text joins the proposed deletion: reject restores it, and accept removes it with no separate revision. Targets that touch foreign pending revisions refuse. Continuation can extend the runtime author's text and paragraph proposals. Simple fields with nested fields or other result containers refuse tracked deletion and replacement. Direct result runs remain supported.
318
+ - The paragraph has your own pending change, or another author's pending paragraph mark, formatting, move, or structural change.
319
+ - The start of the next paragraph has a pending change.
320
+ - A later sync deletes beside your own pending deletion. Delete adjacent paragraphs in one sync instead.
321
+ - A tracked deletion or replacement starts a paragraph whose previous paragraph mark you already proposed deleting.
322
+
323
+ Text that another participant types into struck text joins the proposed deletion. Reject restores it, and accept removes it with no separate revision.
324
+
325
+ Tracked edits can go inside or beside another author's pending text insertion or deletion. A deletion of their inserted text is recorded inside their insertion. New text lands after any deleted text, and new text inside their insertion splits it into two halves. The returned range names the new text where it lands, and each author's change stays a separate decision. For more information, see [Edit another author's pending text](#edit-another-authors-pending-text). Continuation can extend the runtime author's text and paragraph proposals.
326
+
327
+ Simple fields with nested fields or other result containers refuse tracked deletion and replacement. Direct result runs remain supported. A tracked deletion or replacement that covers an equation strikes the whole equation: accepting removes it, and rejecting restores it.
221
328
 
222
329
  An author can configure a complete proposed table while it has no foreign revisions. Existing table properties and columns require permanent edits. Tracked table and cell value replacement refuse in collaboration. Row deletion suggestions must leave a row without a pending deletion. Pending row or cell structure revisions refuse tracked row deletion with `NotImplemented`.
223
330
 
@@ -229,6 +336,187 @@ When a person adopts an agent's suggestions, attribute them to that person with
229
336
 
230
337
  Standard `insertText('', 'Replace')` means deletion, and an empty insertion is a no-op. Agent tools should require nonempty insertion/replacement text and expose deletion as an explicit model decision. The shipped worker does this. The [compatibility manifest](https://github.com/eigenpal/docx-editor/blob/main/packages/editor-api/compat/manifest.json) records measured members and behavioral differences.
231
338
 
339
+ ### Propose a paragraph split
340
+
341
+ `insertText()` on a body, paragraph, or range treats `\n`, `\r`, and `\r\n` as paragraph breaks. The text after a break starts a new paragraph with the properties of the paragraph that you wrote into. With `TrackMineOnly`, the inserted text and each new paragraph mark are tracked insertions.
342
+
343
+ To split between two sentences, replace only the gap between them with `'\n'`:
344
+
345
+ ```ts
346
+ await runtime.run(async (context) => {
347
+ context.document.changeTrackingMode = 'TrackMineOnly';
348
+ const body = context.document.body;
349
+ const first = body.search('the goods.').getFirst();
350
+ const second = body.search('The buyer').getFirst();
351
+ const gap = first.getRange('End').expandTo(second.getRange('Start'));
352
+ gap.insertText('\n', 'Replace');
353
+ await context.sync();
354
+ });
355
+ ```
356
+
357
+ The proposal strikes the one space and adds one paragraph mark. Accept gives two paragraphs with no trailing space. Reject joins the paragraphs again. Don't replace a sentence with the same words and a break: that proposes deleting and inserting those words.
358
+
359
+ The returned range runs from the first inserted character to the end of the last inserted segment. Text that lands inside an inline content control refuses with `NotSupported` and `edit.indivisible-content`. A write with a break can't share a sync with another edit in the same paragraph. For the batching rules and a refusal table, see [Propose several structural edits in one run](https://www.docx-editor.dev/docs/2.x/editor-api/revisions#propose-several-structural-edits-in-one-run).
360
+
361
+ ### Edit another author's pending text
362
+
363
+ A counterparty's pending insertion is ordinary text to a tracked edit. Replace it, delete part of it, or write inside it. Your changes record under the runtime author, and each author's change stays a separate decision. New text inside their insertion splits it, so their insertion becomes two revisions, one on each side of your text. To accept or reject all of their insertion, decide both revisions, or pass both to `revisions.resolve(action, [first, second])`. The same edits work in a collaboration session; a participant's concurrent accept or reject of the counterparty's change applies to all of that change and to nothing else. In the following example, the agent replaces a counterparty's proposed term, then rejects only its own revisions:
364
+
365
+ ```ts
366
+ // Create runtime with author: 'Avery Chen' before this example.
367
+ await runtime.run(async (context) => {
368
+ context.document.changeTrackingMode = 'TrackMineOnly';
369
+ const proposed = context.document.body
370
+ .search('thirty (30) days of receipt', { matchCase: true })
371
+ .getFirst();
372
+ await context.sync();
373
+ proposed.insertText('forty-five (45) days of receipt', 'Replace');
374
+ await context.sync();
375
+
376
+ // Load the revisions again after the edit.
377
+ const revisions = context.document.body.revisions;
378
+ revisions.load('items/author');
379
+ await context.sync();
380
+
381
+ // Reject only this agent's changes. The counterparty's insertion stays pending.
382
+ for (const revision of revisions.items) {
383
+ if (revision.author === 'Avery Chen') revision.reject();
384
+ }
385
+ await context.sync();
386
+ });
387
+ ```
388
+
389
+ These tracked edits fail with `NotImplemented`. Read `error.debugInfo.innerError.code` for the rule:
390
+
391
+ | `innerError.code` | Edit |
392
+ | --- | --- |
393
+ | `edit.tracked-deleted-text-only` | A deletion or replacement that covers only deleted text and no paragraph mark |
394
+ | `edit.tracked-foreign-revision-unsupported` | An edit that touches another author's paragraph mark, formatting, move, or structural change, or new text inside a link or content control within their insertion |
395
+ | `edit.tracked-own-pending-change` | An edit that covers or borders your own pending change |
396
+
397
+ The range that a tracked `insertText()` returns names your own pending insertion. With tracking on, replacing or deleting that range fails with `edit.tracked-own-pending-change`, because the edit would cover your own pending text. Write the final text in one call, or reject your revision and write again.
398
+
399
+ ### Rewrite a paragraph word by word
400
+
401
+ To propose a model's rewrite of a paragraph, use `prepareRewrite` from `@docx-editor.dev/editor-api/agent`. It reads the paragraph into text for your model. `draft.apply()` then applies the steps in this section for you, keeps fields, equations, note references, and locked controls whole, and rejects only its own changes if a write fails. You own the prompt and the model call:
402
+
403
+ ```ts
404
+ import { prepareRewrite } from '@docx-editor.dev/editor-api/agent';
405
+
406
+ await runtime.run(async (context) => {
407
+ const paragraph = context.document.body.paragraphs.getFirst();
408
+ const draft = await prepareRewrite(context, paragraph);
409
+ const prompt = ['Make this clause shorter.', draft.legend, draft.text].join('\n\n');
410
+ await draft.apply(await callModel(prompt));
411
+ });
412
+ ```
413
+
414
+ `draft.text` holds the paragraph with numbered placeholders, and `draft.legend` states the placeholder rules. To check model text without writing, call `draft.check(modelText)`. For several paragraphs, prepare them all, call the model for every draft at once, and then apply the drafts one after another. For its guarantees and error codes, see [Propose an AI rewrite as tracked changes](https://www.docx-editor.dev/docs/2.x/recipes/propose-rewrite). The rest of this section shows the calls it makes.
415
+
416
+ Split a paragraph into word ranges with `paragraph.getTextRanges([' '])`. Each range keeps its trailing space, so a deleted word takes its space with it, and a replacement for a range ends with a space too. Address a run of words with `first.expandTo(last)`. After tracked edits, `paragraph.text` reads the deleted and the inserted words together. `getReviewedText('Current')` reads the text as if you accepted every change, and `'Original'` reads it as if you rejected every change.
417
+
418
+ Each word range is a snapshot. An edit before a range in its paragraph makes the range fail with `StaleDocument`, and an edit after it keeps it valid. Read the ranges once, before you edit. Pass the range texts to the model and plan the edits by range index, because a paragraph can repeat a word. Then apply the edits from the last index to the first, one sync per edit:
419
+
420
+ ```ts
421
+ await runtime.run(async (context) => {
422
+ context.document.changeTrackingMode = 'TrackMineOnly';
423
+ const paragraph = context.document.body.paragraphs.getFirst();
424
+ const words = paragraph.getTextRanges([' ']);
425
+ words.load('items/text');
426
+ await context.sync();
427
+
428
+ // Pass plain text to the model; keep the ranges in this run.
429
+ // ['The ', 'fee ', 'is ', 'due ', 'per ', 'unit ', 'and ', 'the ', 'buyer ', ...]
430
+ const tokens = words.items.map((range) => range.text);
431
+
432
+ // Edits by index, applied from the last index to the first.
433
+ words.items[7]!.delete();
434
+ await context.sync();
435
+ words.items[4]!.insertText('net ', 'After');
436
+ await context.sync();
437
+ words.items[0]!.expandTo(words.items[1]!).insertText('Each charge ', 'Replace');
438
+ await context.sync();
439
+
440
+ const proposed = paragraph.getReviewedText('Current');
441
+ await context.sync();
442
+ console.log(tokens.length, proposed.value);
443
+ });
444
+ ```
445
+
446
+ A field, an equation, a picture, or a note reference reads as one unit that never splits and joins the word it touches. A field reads as its result, which can contain spaces, such as `Section 4.2`. An equation, a picture, and a note reference read as U+FFFC. A tab ends a range only when you list `'\t'` as a mark. `trimSpacing` removes spaces, tabs, and column breaks from the edges of each range; use it to read words, not to plan deletions. `Range.getRange('Start')` and `'End'` answer an insertion point; `'After'` fails with `NotSupported`. Ranges in different stories make `expandTo()` fail with `InvalidArgument`.
447
+
448
+ A tracked deletion or replacement that covers an equation strikes the whole equation. Accept removes it, and reject restores it.
449
+
450
+ The words of an inline content control join the ranges around it. `paragraph.contentControls` and `range.contentControls` list the controls that the paragraph or range overlaps, including a control that holds the whole range. Before you plan edits, load them with `cannotEdit`, `tag`, and `text`, for each word range in one sync, and keep each locked control as one unit. A replacement or deletion of part of a content-locked control fails, and `error.debugInfo.innerError.code` is `edit.protected-content`. The outer code is `GeneralException` with `TrackMineOnly` and `InvalidArgument` without it, so branch on the inner code. With tracking on, a deletion or replacement that covers the whole control proposes removing the control as one deletion.
451
+
452
+ Map each difference between the old and the new words to one call. The last range of a paragraph has no space after it:
453
+
454
+ | Difference | Call |
455
+ | --- | --- |
456
+ | Replace one or more words | `first.expandTo(last).insertText(text, 'Replace')` |
457
+ | Delete one or more words | `first.expandTo(last).delete()` |
458
+ | Insert before the first word | `words[0].insertText(text, 'Before')` |
459
+ | Insert after a word | `word.insertText(text, 'After')` |
460
+ | Insert after the last word | `last.insertText(' ' + text, 'After')`, because the last word has no space after it |
461
+
462
+ Ranges follow the runtime's `revisionTextView`. Text that the view hides, such as a pending insertion in the `original` view, holds no ending mark, and a range starts and ends at characters that the view shows. Hidden text between two shown characters of one range stays inside the range, so an edit through that range also changes the hidden text.
463
+
464
+ Do not split the paragraph again after tracked edits to plan more edits. A range over pending revisions can join deleted and inserted text, such as `two2` after you replace `two` with `2`. An edit that touches your own pending change fails with `NotImplemented`, and `error.debugInfo.innerError.code` is `edit.tracked-own-pending-change`. Read the proposed text with `getReviewedText('Current')`, then edit a range outside your pending change. To change your proposal itself, reject it and propose again.
465
+
466
+ Catch a refused word-range edit and read its rule from `debugInfo`:
467
+
468
+ ```ts
469
+ import { DocxEditor, isDocxEditorError } from '@docx-editor.dev/editor-api';
470
+
471
+ const runtime = await DocxEditor.createServer(bytes, { author: 'Review agent' });
472
+ await runtime.run(async (context) => {
473
+ context.document.changeTrackingMode = 'TrackMineOnly';
474
+ const words = context.document.body.paragraphs.getFirst().getTextRanges([' ']);
475
+ words.load('items');
476
+ await context.sync();
477
+ try {
478
+ words.items[0]!.insertText('Each ', 'Replace');
479
+ await context.sync();
480
+ } catch (error) {
481
+ if (!isDocxEditorError(error)) throw error;
482
+ // For example, 'edit.protected-content' inside a content-locked control.
483
+ console.log(error.code, error.debugInfo.innerError?.code);
484
+ }
485
+ });
486
+ ```
487
+
488
+ ## Review changes in a range
489
+
490
+ Use `range.revisions` to reach the tracked changes inside a search result, a comment range, or any other range. The collection lists the changes the range overlaps in its own story, including a nested change or another author's change beside it. A partly covered change is listed whole, and a replacement lists its deletion and insertion separately. Load the members and decide on each one:
491
+
492
+ ```ts
493
+ await runtime.run(async (context) => {
494
+ const matches = context.document.body.search('within 30 days');
495
+ matches.load('items');
496
+ await context.sync();
497
+
498
+ const revisions = matches.items.map((match) => match.revisions);
499
+ for (const collection of revisions) collection.load('items');
500
+ await context.sync();
501
+
502
+ for (const collection of revisions) {
503
+ for (const revision of collection.items) revision.load('author');
504
+ }
505
+ await context.sync();
506
+
507
+ for (const collection of revisions) {
508
+ for (const revision of collection.items) {
509
+ if (revision.author === 'Agent') revision.accept();
510
+ }
511
+ }
512
+ await context.sync();
513
+ });
514
+ ```
515
+
516
+ `acceptAll()` and `rejectAll()` on a range collection resolve every change the range overlaps, whole, including structural changes that `items` omits. They fail with `NotImplemented` when one of those changes is read-only. When the range overlaps only part of a group of nested changes, only the overlapped changes resolve; the others stay pending. Two decisions in one sync that reach one change resolve it once; contrary decisions fail with `ConflictingChanges`. A change inside text that a decision in the same sync removes, such as a rejected insertion or an accepted deletion, goes with that text, so any decision on it in that sync is skipped. This also applies to `accept()` and `reject()` on single revisions. `resolve()` and `setAuthor()` refuse with `NotSupported` on a range collection. Use the story's `body.revisions` for them.
517
+
518
+ A browser review panel identifies cards by `key`. Pass the key to the DocxEditor function `getReviewItemRevisions(context, key)` to decide the card's own change, or the two halves of a paired replacement. `getReviewItemRange(context, key)` returns the range that a card covers; use `getReviewItemRangeOrNullObject(context, key)` when another reviewer can resolve the change first. Do not match cards to revisions by text.
519
+
232
520
  ## Set paragraph direction
233
521
 
234
522
  Office.js has no paragraph direction member. Use the DocxEditor addition `Paragraph.readingOrder` to write right-to-left paragraphs, such as Arabic or Hebrew text. Queue the direction writes for several paragraphs in one sync, then read them back in the next sync:
@@ -251,25 +539,73 @@ await runtime.run(async (context) => {
251
539
 
252
540
  A read returns the direction that the paragraph reads in, after its style. Writes accept only `LeftToRight` and `RightToLeft`; other values fail with `InvalidArgument`. A write of the direction that the paragraph already has changes nothing, so you can write back what you read. The write keeps `alignment` as authored: in a right-to-left paragraph, `Left` names the leading edge at the right margin. With `TrackMineOnly`, the write records a paragraph property revision.
253
541
 
542
+ ## Go to a bookmark
543
+
544
+ Go to a bookmark with the standard calls: `getBookmarkRangeOrNullObject(name)`, then `range.select()`. Check `isNullObject` after a sync instead of catching `ItemNotFound`. Selection needs a browser host (`runtime.capabilities.selection`). It opens the header, footer or note that holds the bookmark. A read-only editor refuses a selection outside the main text with `NotSupported`.
545
+
546
+ ```ts
547
+ await runtime.run(async (context) => {
548
+ const range = context.document.getBookmarkRangeOrNullObject('Intro');
549
+ await context.sync();
550
+ if (range.isNullObject) return;
551
+ range.select();
552
+ await context.sync();
553
+ });
554
+ ```
555
+
254
556
  ## Insert table rows
255
557
 
256
558
  `TableRow.insertRows('Before', count, values)` and `'After'` support ordinary source rows beside unrelated merged headers. Merged source rows and crossing vertical merges refuse. Keep each row insertion as the only write in its sync. Sync before editing returned rows. For more information, see [Tables and cells](https://docx-editor.dev/docs/2.x/editor-api/tables).
257
559
 
258
- ## Pictures and page fields
560
+ ## Merge and split cells
561
+
562
+ `Table.mergeCells(topRow, firstCell, bottomRow, lastCell)` merges a rectangle and returns the merged cell. Edits to that cell can share the sync. `TableCell.split(rowCount, columnCount)` splits one cell. A ragged rectangle refuses with `InvalidArgument` and `innerError.code` `edit.table-merge-not-rectangle`. A split the cell cannot take refuses with `InvalidArgument` and `edit.table-split-unsupported`. Both refuse with `NotSupported` in a tracking mode. Do not turn tracking off to make them succeed.
563
+
564
+ ```ts
565
+ import { DocxEditor, isDocxEditorError } from '@docx-editor.dev/editor-api';
566
+
567
+ const runtime = await DocxEditor.createServer(bytes);
568
+ await runtime.run(async (context) => {
569
+ const table = context.document.body.tables.getFirst();
570
+ const header = table.mergeCells(0, 0, 0, 2);
571
+ header.value = 'Quarterly results';
572
+ try {
573
+ await context.sync();
574
+ } catch (error) {
575
+ if (!isDocxEditorError(error)) throw error;
576
+ // A merged cell crosses the rectangle: read the table again and pick its real corners.
577
+ const reason = error.debugInfo.innerError;
578
+ if (reason?.code !== 'edit.table-merge-not-rectangle') throw error;
579
+ feedback.push(reason.message);
580
+ }
581
+ });
582
+ ```
583
+
584
+ ## Pictures and fields
259
585
 
260
- Insert a manual line break with `range.insertBreak('Line', 'After')` or `\v` in inserted text. Call `await context.sync()` after queuing the write. Manual line breaks support `TrackMineOnly` and text edits in the same sync. Single-line content controls refuse manual line breaks. Reads report manual line breaks as `\v`, column breaks as U+000E, and paragraph separators as `\r`. Text writes refuse U+000E and paragraph separators. Do not flatten these characters before sending read text back to the document.
586
+ Insert a manual line break with `range.insertBreak('Line', 'After')` or `\v` in inserted text. Call `await context.sync()` after queuing the write. Manual line breaks support `TrackMineOnly` and text edits in the same sync. Single-line content controls refuse manual line breaks. Reads report manual line breaks as `\v`, column breaks as U+000E, and paragraph separators as `\r`. Text writes refuse U+000E. `insertText()` on a body, paragraph, or range writes `\n`, `\r`, and `\r\n` as paragraph breaks. Other paragraph separators refuse. Do not flatten these characters before sending read text back to the document.
261
587
 
262
588
  Insert PNG or JPEG images with `range.insertInlinePictureFromBase64(data, 'After')`. Sync before setting properties on the returned picture. Width and height use points. New pictures lock the aspect ratio. Set `lockAspectRatio = false` before setting independent dimensions. Set `altTextDescription` to describe the image. Deletion preserves shared media relationships.
263
589
 
590
+ Insert an inert field with `range.insertField(location, type, text)`. The runtime inserts `Page`, `NumPages`, `Ref`, `PageRef`, `NoteRef`, `Seq`, `StyleRef`, `Date`, `Time`, and `TOC`. `text` holds the arguments, such as a bookmark name and switches: `range.insertField('After', 'Ref', '_Ref123456 \\h')`. With `Empty`, `text` holds the whole instruction. The runtime never evaluates an instruction, and a new field has an empty cached result.
591
+
592
+ Untracked `Page`, `NumPages`, and `TOC` fields are simple fields. Other fields, and every tracked field, are complex fields. Their runs take the formatting of the text before the insertion point. New `Ref`, `PageRef`, `NoteRef`, `Seq`, `StyleRef`, `Date`, and `Time` fields carry `w:dirty="true"`, so an application that evaluates fields recomputes them on open.
593
+
594
+ Write the cached result with `field.result.insertText(text, 'Replace')` after a sync, and read it with `field.load('result')`. The result range supports only `text` and that `insertText()` call. Its other members refuse with `NotImplemented` and `edit.field-result-unsupported`. With `TrackMineOnly`, the write works only on your own pending field and joins its insertion. If the write fails, `field.delete()` takes your own pending field back outright.
595
+
596
+ Field types that fetch, embed, link, run, or prompt, such as `DDE`, `IncludeText`, `IncludePicture`, `Link`, and `MacroButton`, fail with `InvalidArgument` and `edit.field-unsupported`. With `TrackMineOnly`, the field is one complex field inside one tracked insertion. Accept keeps it, and reject removes all of it. Tracked TOC creation refuses. For the refusal tables, see [Fields and pagination](https://www.docx-editor.dev/docs/2.x/editor-api/fields).
597
+
598
+ Insert one equation with `range.insertOoxml(ooxml, location)`. `ooxml` is a Flat OPC package (`pkg:package`) whose document part holds one paragraph with exactly one inline `m:oMath` and optional plain runs. The equation reads as U+FFFC. With `TrackMineOnly`, it is one tracked insertion, and reject removes it whole. Every other OOXML shape refuses and inserts nothing: other parts, relationships, images, fields, paragraph properties, display equations, and unknown elements fail with `NotSupported` and `edit.ooxml-unsupported`. Malformed XML, DTDs, and entities fail with `InvalidArgument` and `edit.invalid-argument`. For the accepted shape and every refusal, see [Insert an equation](https://www.docx-editor.dev/docs/2.x/editor-api/text-and-ranges#insert-an-equation).
599
+
264
600
  Use `range.insertField('Before', 'TOC', '\\o "1-3" \\h')` to insert an inert TOC instruction. This call saves no calculated entries. TOC evaluation and code writes refuse.
265
601
 
266
602
  Insert a page field with `range.insertField('After', 'Page')` or `'NumPages'`. Sync before using the returned field. `field.code = 'NUMPAGES'` changes its instruction; `field.updateResult()` computes and stores its result. These calls use separate syncs. Field updates can share a sync with other field updates. They cannot share a sync with layout-changing writes.
267
603
 
268
- Headless field calculation requires an explicit `pagination.measurer` when creating the server runtime. Use measurements from the document's fonts. Browser runtimes use the editor's measured layout. Without pagination, `updateResult()` fails with `NotSupported`. Other field instructions remain inert. The authoring subset refuses unsupported field codes and formatting switches.
604
+ Headless field calculation requires an explicit `pagination.measurer` when creating the server runtime. Use measurements from the document's fonts. Browser runtimes use the editor's measured layout. Without pagination, `updateResult()` fails with `NotSupported`. Other field instructions remain inert. The authoring subset refuses unsupported field codes and page-field switches. A field inside a pending tracked insertion refuses `updateResult()` and code writes until a reviewer accepts it.
269
605
 
270
606
  Character formatting also supports underline, strikethrough, exact Word-palette highlighting, subscript, and superscript. `font.underline = 'None'` removes an underline. Setting one script mode to `true` clears the other mode. The highlight setter keeps Office's pinned `string` type, although Microsoft documents runtime `null` for clearing. The runtime accepts this clearing value. The runtime rejects unsupported highlight colors.
271
607
 
272
- The workflow tests cover both hosts and save/reopen: `model-font-editing.test.ts`, `model-pictures.test.ts`, `model-fields.test.ts`, and `model-picture-field-parity.test.ts`. The final test includes primary footer creation and a saved `NUMPAGES` result.
608
+ The repository's tests run these workflows on both hosts and through save and reopen, including primary footer creation and a saved `NUMPAGES` result.
273
609
 
274
610
  ## Set document metadata
275
611
 
package/README.md CHANGED
@@ -35,12 +35,16 @@ Start with [Runtime and setup](https://www.docx-editor.dev/docs/2.x/editor-api/r
35
35
  | Task | Guide |
36
36
  | --- | --- |
37
37
  | Read, insert, replace, or remove text | [Text and ranges](https://www.docx-editor.dev/docs/2.x/editor-api/text-and-ranges) |
38
- | Find matches, split paragraphs, or use bookmarks | [Search and navigation](https://www.docx-editor.dev/docs/2.x/editor-api/search-and-navigation) |
38
+ | Split a paragraph with `insertText()` and `\n`, also as a tracked change | [Split a paragraph](https://www.docx-editor.dev/docs/2.x/editor-api/text-and-ranges#split-a-paragraph) |
39
+ | Find matches or use bookmarks | [Search and navigation](https://www.docx-editor.dev/docs/2.x/editor-api/search-and-navigation) |
39
40
  | Set fonts, paragraph properties, styles, or links | [Formatting and styles](https://www.docx-editor.dev/docs/2.x/editor-api/formatting) |
40
41
  | Create and configure lists | [Lists and numbering](https://www.docx-editor.dev/docs/2.x/editor-api/lists) |
41
42
  | Work with table values, rows, columns, and cells | [Tables and cells](https://www.docx-editor.dev/docs/2.x/editor-api/tables) |
42
43
  | Insert and resize images | [Inline pictures](https://www.docx-editor.dev/docs/2.x/editor-api/pictures) |
43
- | Calculate PAGE and NUMPAGES | [Fields and pagination](https://www.docx-editor.dev/docs/2.x/editor-api/fields) |
44
+ | Insert fields, write their cached results, or calculate PAGE and NUMPAGES | [Fields and pagination](https://www.docx-editor.dev/docs/2.x/editor-api/fields) |
45
+ | Insert an equation from OOXML | [Insert an equation](https://www.docx-editor.dev/docs/2.x/editor-api/text-and-ranges#insert-an-equation) |
46
+ | Propose a split, a field, or an equation as a tracked change | [Tracked changes](https://www.docx-editor.dev/docs/2.x/editor-api/revisions#propose-several-structural-edits-in-one-run) |
47
+ | Propose a model's paragraph rewrite as the fewest tracked changes | [Propose an AI rewrite](https://www.docx-editor.dev/docs/2.x/recipes/propose-rewrite), with `prepareRewrite` from `@docx-editor.dev/editor-api/agent` |
44
48
  | Set page geometry and edit headers, footers, or notes | [Page layout and stories](https://www.docx-editor.dev/docs/2.x/editor-api/page-layout-and-stories) |
45
49
  | Fill template controls and edit their metadata | [Content controls](https://www.docx-editor.dev/docs/2.x/editor-api/content-controls) |
46
50
  | Discuss content and manage threads | [Comments](https://www.docx-editor.dev/docs/2.x/editor-api/comments) |
@@ -100,7 +104,7 @@ await runtime.run(async (context) => {
100
104
 
101
105
  Use `range.insertText(text, 'Before' | 'After')` for insertions, and `range.delete()` or `range.clear()` for deletions. `insertText()` returns the inserted range. Mode assignments and edits commit together at `sync()`; failed batches preserve the previous mode and document. Load `document.changeTrackingMode` before reading it. `Off` is the initial mode.
102
106
 
103
- This is a supported Office.js subset. `TrackMineOnly` applies to this server host and persists across its `run()` calls. It does not change peers' tracking settings or save a document-wide tracking policy. `TrackAll` fails with `NotSupported`. Browser tracked writes require the Pro review module; the runtime setting does not change the editor UI mode. Tracked text edits support one paragraph, including table-cell text, and adjacent sibling paragraphs outside collaboration. Tracked `Paragraph.delete()` and `Range.delete()` over whole paragraphs record deleted text and deleted paragraph marks, also in collaboration. Font, paragraph-format, paragraph-style, and `readingOrder` changes record property revisions, and paragraph insertion records inserted text and paragraph marks. The runtime rejects targets touching pending revisions, including text inside a row with a pending insertion or deletion. Other structural changes refuse while tracking. For the complete list, see [Revisions](https://docx-editor.dev/docs/2.x/editor-api/revisions). Comments and revision decisions remain available. Set `Off` explicitly when permanent edits are intended.
107
+ This is a supported Office.js subset. `TrackMineOnly` applies to this server host and persists across its `run()` calls. It does not change peers' tracking settings or save a document-wide tracking policy. `TrackAll` fails with `NotSupported`. Browser tracked writes require the Pro review module; the runtime setting does not change the editor UI mode. Tracked text edits support one paragraph, including table-cell text, and adjacent sibling paragraphs outside collaboration. Tracked `Paragraph.delete()` and `Range.delete()` over whole paragraphs record deleted text and deleted paragraph marks, also in collaboration. Font, paragraph-format, paragraph-style, and `readingOrder` changes record property revisions, and paragraph insertion records inserted text and paragraph marks. Tracked edits can go inside or beside another author's pending text insertion or deletion, and each author's change stays a separate decision. The runtime refuses edits that touch your own pending change, another author's paragraph mark, formatting, move, or structural change, and text inside a row with a pending insertion or deletion. Tracked paragraph splits through `insertText()` with `\n`, fields through `insertField()` with results through `Field.result`, and one equation at a time through `insertOoxml()` produce native revisions. Other structural changes refuse while tracking. For the complete list, see [Revisions](https://docx-editor.dev/docs/2.x/editor-api/revisions). Comments and revision decisions remain available. Set `Off` explicitly when permanent edits are intended.
104
108
 
105
109
  See the [server-agent review example](../../examples/server-agent-review/README.md) for Hocuspocus, stale-read handling, and the review lifecycle.
106
110
 
@@ -160,6 +164,30 @@ To upgrade from the former reviewer, bridge, MCP, or chat APIs, see [Migration](
160
164
  | [`@docx-editor.dev/pro`](https://www.npmjs.com/package/@docx-editor.dev/pro) | Tracked changes, comments, and custom nodes. |
161
165
  | [`@docx-editor.dev/editor-api`](https://www.npmjs.com/package/@docx-editor.dev/editor-api) | Supported Office.js subset for document editing on a server or in an open editor. |
162
166
 
167
+ ## Which API for which job
168
+
169
+ | Job | Use |
170
+ | --- | --- |
171
+ | Build a review UI in the browser | The React or Vue adapter hooks, plus the review hooks and `DocxEditorReview` from `@docx-editor.dev/pro/react` or `@docx-editor.dev/pro/vue`. |
172
+ | Edit in a headless, server, or agent pipeline | The editing API in `@docx-editor.dev/editor-api`, which follows the Office.js object model. |
173
+
174
+ | Task | Browser host (React or Vue) | Headless, server, or agent |
175
+ | --- | --- | --- |
176
+ | [Comment on found text](https://www.docx-editor.dev/docs/2.x/recipes/comment-on-found-text) | `editor.findMatches`, `editor.selectMatch`, then `useReview().comment` | `body.search`, then `Range.insertComment` |
177
+ | Reply to a thread | `useReview().reply(item, text)` | `Comment.reply(text)` |
178
+ | [Record a tracked replacement](https://www.docx-editor.dev/docs/2.x/recipes/tracked-replacement) | Suggesting mode, then `editor.exec({ type: 'replaceMatch', match, text })` | `document.changeTrackingMode = 'TrackMineOnly'`, then `Range.insertText(text, 'Replace')` |
179
+ | [Propose an AI rewrite as tracked changes](https://www.docx-editor.dev/docs/2.x/recipes/propose-rewrite) | The same code through `DocxEditor.createBrowser` from `@docx-editor.dev/editor-api/browser` | `prepareRewrite` from `@docx-editor.dev/editor-api/agent` |
180
+ | [Accept or reject a change](https://www.docx-editor.dev/docs/2.x/recipes/accept-reject-without-scrolling) | `useReview().accept(item)` or `useReview().reject(item)` | `Revision.accept()` or `Revision.reject()` |
181
+ | [Open or reveal a change without scrolling](https://www.docx-editor.dev/docs/2.x/recipes/accept-reject-without-scrolling) | `useReview().setActive(key, { reveal: false })` | Not applicable: no viewport |
182
+ | [Highlight ranges](https://www.docx-editor.dev/docs/2.x/recipes/highlight-ranges) | `useHighlights(name, source, options)` | Not applicable |
183
+ | [Custom review rail cards](https://www.docx-editor.dev/docs/2.x/recipes/custom-review-cards) | `DocxEditorReview` with `preset` set to `false`, `useReview().items`, `useStackedReviewPositions`, and `useReviewRailMetrics` | Not applicable |
184
+ | Comment-on-selection button | `DocxEditorReview.AddComment` as a direct child of `DocxEditorReview`, or `useEditorCommand('review.addComment')` | Not applicable |
185
+ | Page setup and paragraph dialogs from a custom toolbar | `DocxEditor.PageSetupDialog` or `DocxEditor.ParagraphDialog` with `open` and a close handler (`onClose` in React, `@close` in Vue); enable the button from `usePageSetup().isEnabled` or `useParagraphFormat().isEnabled` | `Section.pageSetup`, and `Paragraph` properties such as `alignment` |
186
+
187
+ The review hooks need `reviewModule()` from `@docx-editor.dev/pro` in the editor's modules, and an editor `author` for comments and tracked changes. The editing API takes its author from the `author` option of `DocxEditor.createServer`, imported from `@docx-editor.dev/editor-api`, or of `DocxEditor.createBrowser`, imported from `@docx-editor.dev/editor-api/browser`.
188
+
189
+ This package ships the task recipes in [`docs/index.md`](./docs/index.md). They are also on the site: [Task recipes](https://www.docx-editor.dev/docs/2.x/recipes).
190
+
163
191
  ## License
164
192
 
165
193
  This package uses the [EigenPal Pro License](https://github.com/eigenpal/docx-editor/blob/main/packages/editor-api/LICENSE.md). See [pricing](https://www.docx-editor.dev/pricing) for license and support options.