@docx-editor.dev/core
The framework-agnostic DOCX engine: OOXML read and write, layout, paint, and the Editor contract that adapters render.
Core is the DOCX engine: OOXML read and write, layout, and paint. It has no framework dependency and no UI.
Create an editor
Install Core. The React and Vue adapters require it as a peer dependency.
npm install @docx-editor.dev/coreThe following example creates an editor, mounts it, runs a command, and cleans up:
import { createDocxEditor } from '@docx-editor.dev/core';
const editor = createDocxEditor({ document: bytes, author: 'Reviewer' });
editor.attach(element);
const bold = { type: 'toggleMark', mark: 'bold' } as const;
if (editor.can(bold).ok) editor.exec(bold);
const off = editor.on('change', () => setDirty(true));
const output = await editor.save();
off();
editor.destroy();To mount at creation, pass container. For detach and pop-outs, see Editor mount modes.
Choose an import
Prefer the root import.
import { createDocxEditor, loadFonts, DEFAULT_FONT } from '@docx-editor.dev/core';
import type { Editor, EditorSnapshot } from '@docx-editor.dev/core';| Subpath | Contents |
|---|---|
. | createDocxEditor, the Editor contract, fonts, and the chrome registry. |
./editor | Root exports plus surface internals. For adapter authors. |
./contracts/editor | Editor, EditorCommand, EditorQuery, EditorSnapshot, DocumentSource, and PageSetup. |
./contracts/document | The document-level edit and query vocabulary. |
./contracts/types | Document model types. |
./contracts/modules | EditorModule, which @docx-editor.dev/pro implements. |
./contracts/interaction | SemanticTarget and InteractionOutcome. |
./store | The canonical tree and its transactional store. |
./layout | The DOM-free layout pass. |
./output | Paint: page DOM and the selection overlay. |
./automation | The object model behind @docx-editor.dev/editor-api. |
./styles/editor.css | The editor stylesheet. |
DEFAULT_FONT is Calibri at 11 points. WORD_DEFAULT_FONT is its deprecated alias. For the toolbar vocabulary, see the chrome slot reference.
Read state and run commands
The following function reads the page counter from a snapshot:
import type { Editor } from '@docx-editor.dev/core/contracts/editor';
function pageLabel(editor: Editor): string {
const { page } = editor.snapshot();
return `${page.current} / ${page.total}`;
}| Member | Use |
|---|---|
snapshot() | Read state. Same reference until state changes; sub-objects are stable. |
query(query) | Read document data, such as { type: 'watermark' }. |
can(command, options?) | Check a command. Returns { ok }, or a reason when it refuses. |
exec(command, options?) | Run a command. Returns an ExecResult. |
on(event, handler) | Subscribe. Returns an unsubscribe function. |
load(document) / save() | Replace the document, or serialize it to DOCX bytes. |
Stable snapshots let useEditorState skip deep compares.
| Event | Fires when |
|---|---|
change | A mutation commits. Carries the revision and block ids, not bytes. |
selectionChange | Selection, formatting, open header or footer, collaboration status, or page count changes. |
error | The editor reports an EditorError. |
diagnostic | An anonymous diagnostic, such as a refused edit or a failed font. |
historyDiagnostic | A history group split, or a gesture looks ungrouped or fragmented. |
reviewItemReveal | Navigation lands on a change, or setActiveReviewItem(key, { announce: true }) succeeds. |
reviewChangesResolved | An accept-all or reject-all decision commits. |
revisionMarkupChange | Local revision markup preferences change. |
hostChange | The pages move to another document, or detach (document is null). |
For page and heading navigation, see Navigate a document.
For a custom surface, pass the lineId from moveCaret (in ./layout) to the next MoveCaretOptions.lineId and to caretAt as preferredLineId.
Typing and undo
- A pause of 1 second, or 2 seconds of continuous typing, starts a new step.
- A caret move, another edit, undo, redo, or a remote edit to the same paragraph also starts a step.
- Each Backspace, Delete, and Enter is one step.
- Caret formatting, such as Bold with no selection, is a local step. It changes nothing until you type.
- Typing over a note reference or a whole comment removes it and inserts your text in one undo step.
- Undo restores the original selection. Redo restores the final selection.
- Collaborative sessions group typing the same way.
Group one gesture into one undo step
Group repeated slider or color-picker writes into one undo step. In React or Vue, use useEditorValueCommand and useHistoryGroup from the React hooks or Vue composables.
If your app owns the DOM, bind the control with bindHistoryGroup. Font-size commands take half-points; snapshot().formatting?.fontSizePt reports points:
import { bindHistoryGroup, type Editor } from '@docx-editor.dev/core';
function mountFontSize(editor: Editor, slider: HTMLInputElement) {
const gesture = bindHistoryGroup(editor, slider, { kind: 'range' });
const apply = () => {
const command = {
type: 'setMarkAttr',
mark: 'fontSize',
attr: 'val',
value: Number(slider.value) * 2, // points to half-points
} as const;
const result = editor.exec(command, gesture.options());
if (!result.ok) console.warn(result.reason);
};
slider.addEventListener('input', apply);
return () => {
slider.removeEventListener('input', apply);
gesture.dispose();
};
}kind | Gesture starts | Gesture ends |
|---|---|---|
range | pointerdown or first keydown | Pointer release, cancel, lost capture, keyup, or blur |
repeat | As range; you own the timer | Release |
native-color | Activation | change, next activation, Escape, blur, or disposal |
Call dispose() when you remove the control or replace the editor. For native-color, strip the leading # from the value.
- Each grouped value applies and synchronizes immediately. Undo restores the original formatting, even when mixed. Redo restores the final value.
- Repeated keys keep one handle. A pointer release outside the control ends the gesture after event handlers finish, including the final value handler.
Manage a handle explicitly
If your control has its own lifecycle callbacks, pass one handle to each write and end it on finish or cancel:
const group = editor.beginHistoryGroup();
try {
const result = editor.exec({ type: 'setParagraphSpacing', afterPt: 12 }, { historyGroup: group });
if (!result.ok) console.error(result.reason);
} finally {
group.end();
}end()is idempotent. Ending a canceled gesture keeps the edits already applied.- A handle belongs to one editor and one mounted document.
load, detach,destroy, and remount expire it. - DOM bindings create a new handle when the previous handle expires.
canandexecreturnunsupportedfor ended, expired, or foreign handles, and for objects not created bybeginHistoryGroup().
runToolbarCommand takes options last: runToolbarCommand(editor, 'text.color', '0070C0', { historyGroup }). An invalid value rejects the command.
Supported commands and history outcomes
| Family | Commands that accept historyGroup |
|---|---|
| Formatting | toggleMark, setMarkAttr, setAlignment, setParagraphDirection, clearFormatting, setLineSpacing, setParagraphSpacing, setParagraphStyle, setParagraphFormat |
| Tracked proposals | proposeInsertion, proposeDeletion, proposeReplacement |
| Review commands | resolveAllReviewChanges, setReviewChangesAuthor |
Review methods (last options argument) | addComment, replyToReviewItem, setCommentResolved, setCommentText, deleteReviewItem, acceptReviewItem, rejectReviewItem |
Other families reject historyGroup before they change the document: typing, structural edits, images, hyperlinks, notes, header and footer lifecycle, protection, form fields, and content controls.
Read result.history?.kind:
| Event | history.kind |
|---|---|
| First committed frame | started |
| Further frame on the same open entry | extended |
| Frame in another story or part | extended |
| Intervening write, another group, or typing flush | Next frame reports split |
| Undo or redo | Next frame starts a new entry; reason undo-redo |
| IME composition | split, reason composition |
| No effective change at a collapsed caret | none, no entry |
Read-only command without historyGroup, such as selectAll | Group stays open; next frame reports extended |
| Rejected before a store transaction | No history change |
| Ungrouped store transaction, even refused | Closes the group |
Caret formatting can return changed: false and still start or extend a local undo entry. Read history.kind separately.
The historyDiagnostic event reports split, possible-ungrouped-gesture (three ungrouped writes to one selection, each within 250 ms), and possible-fragmented-gesture (a new handle per frame). It does not change history.
Group a review decision
Pass one handle to each write of a review decision to make it one undo step. This requires the Pro review module:
// `keys` come from `editor.getReviewItems()`.
const decision = editor.beginHistoryGroup();
try {
const resolved = editor.exec(
{ type: 'resolveAllReviewChanges', action: 'reject', keys },
{ historyGroup: decision }
);
if (!resolved.ok) throw new Error(resolved.reason);
editor.addComment('Rejected: out of scope.', { historyGroup: decision });
} finally {
decision.end();
}
if (decision.lastOutcome?.kind === 'split') console.warn(decision.lastOutcome.reason);- A review method with a closed or foreign handle returns
{ ok: false, code: 'unsupported' }and changes nothing. - For
runtime.run({ historyGroup }, callback), read the outcome fromdecision.lastOutcome. For run rules and errors, see Browser runtime. - The history outcome rules also apply.
Collaboration boundaries
- Grouping affects undo only for the session that makes the edits. Each collaborator keeps its own history.
- Undoing a grouped decision reverts only the deciding session's writes.
- A later local entry, undo, redo, or rejected journal resets shared capture. The next frame reports
split. - Grouped writes can extend one entry beyond the capture timeout. Ungrouped writes can share an entry within that timeout.
- Each ungrouped review or comment write is its own undo entry. It never joins earlier typing.
- Commands that publish separate relationship journals, such as external hyperlink insertion, reject
historyGroup. - Custom collaboration ports must preserve journal identity and synchronous local capture.
historyGroupOfJournal(journal)reads local metadata that spreading,structuredClone, serialization, andpostMessagelose.
Limits
- Keep one resolved Core copy across adapters and extensions. Two copies break shared caches without an error.
- Document values you render, such as font names or link targets, are untrusted. Render them as text, never as markup or URLs.
- For the pipeline and preservation model, see Architecture.