@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/core

The 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';
SubpathContents
.createDocxEditor, the Editor contract, fonts, and the chrome registry.
./editorRoot exports plus surface internals. For adapter authors.
./contracts/editorEditor, EditorCommand, EditorQuery, EditorSnapshot, DocumentSource, and PageSetup.
./contracts/documentThe document-level edit and query vocabulary.
./contracts/typesDocument model types.
./contracts/modulesEditorModule, which @docx-editor.dev/pro implements.
./contracts/interactionSemanticTarget and InteractionOutcome.
./storeThe canonical tree and its transactional store.
./layoutThe DOM-free layout pass.
./outputPaint: page DOM and the selection overlay.
./automationThe object model behind @docx-editor.dev/editor-api.
./styles/editor.cssThe 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}`;
}
MemberUse
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.

EventFires when
changeA mutation commits. Carries the revision and block ids, not bytes.
selectionChangeSelection, formatting, open header or footer, collaboration status, or page count changes.
errorThe editor reports an EditorError.
diagnosticAn anonymous diagnostic, such as a refused edit or a failed font.
historyDiagnosticA history group split, or a gesture looks ungrouped or fragmented.
reviewItemRevealNavigation lands on a change, or setActiveReviewItem(key, { announce: true }) succeeds.
reviewChangesResolvedAn accept-all or reject-all decision commits.
revisionMarkupChangeLocal revision markup preferences change.
hostChangeThe 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();
  };
}
kindGesture startsGesture ends
rangepointerdown or first keydownPointer release, cancel, lost capture, keyup, or blur
repeatAs range; you own the timerRelease
native-colorActivationchange, 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.
  • can and exec return unsupported for ended, expired, or foreign handles, and for objects not created by beginHistoryGroup().

runToolbarCommand takes options last: runToolbarCommand(editor, 'text.color', '0070C0', { historyGroup }). An invalid value rejects the command.

Supported commands and history outcomes

FamilyCommands that accept historyGroup
FormattingtoggleMark, setMarkAttr, setAlignment, setParagraphDirection, clearFormatting, setLineSpacing, setParagraphSpacing, setParagraphStyle, setParagraphFormat
Tracked proposalsproposeInsertion, proposeDeletion, proposeReplacement
Review commandsresolveAllReviewChanges, 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:

Eventhistory.kind
First committed framestarted
Further frame on the same open entryextended
Frame in another story or partextended
Intervening write, another group, or typing flushNext frame reports split
Undo or redoNext frame starts a new entry; reason undo-redo
IME compositionsplit, reason composition
No effective change at a collapsed caretnone, no entry
Read-only command without historyGroup, such as selectAllGroup stays open; next frame reports extended
Rejected before a store transactionNo history change
Ungrouped store transaction, even refusedCloses 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 from decision.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, and postMessage lose.

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.

See also