Composables

Connect Vue controls to DOCX editor state and commands with composables.

Call these composables during setup() in components inside DocxEditorRoot. The packaged <DocxEditor> provides that root for its children.

Connect a command button

This button runs a toolbar command and shows why the command cannot run:

<script setup lang="ts">
import { useEditorCommand } from '@docx-editor.dev/vue';

const bold = useEditorCommand('text.bold');
</script>

<template>
  <button
    @mousedown.prevent
    :disabled="!bold.isEnabled.value"
    :data-active="bold.isActive.value || undefined"
    :title="bold.disabledReason.value ?? 'Bold'"
    @click="bold.execute()"
  >
    B
  </button>
</template>

useEditorCommand(target: MaybeRefOrGetter<ChromeSlotId | EditorCommand>): EditorCommandState takes a slot ID from the chrome slot reference, a raw EditorCommand, or a ref or getter that returns either.

MemberTypeDescription
execute(options?)booleanRuns the command. Returns true when it applied.
isActiveComputedRef<boolean>Command state at the caret.
isEnabledComputedRef<boolean>Whether the command can run.
disabledReasonComputedRef<string | null>Why the command cannot run.
valueComputedRef<string | null>Current value for value slots.

Read state and events

useEditorState returns a read-only shallow ref for one slice of the snapshot. The ref changes only when that slice changes:

<script setup lang="ts">
import { useEditorState } from '@docx-editor.dev/vue';

const page = useEditorState((s) => s.page);
</script>

<template>
  <span>{{ page.current }} / {{ page.total }}</span>
</template>

Pass a comparator for an object slice. Common fields include page, selection, selectionRange, formatting, editable, isLoading, editingMode, canUndo, pageSetup, and lastRejection. selectionRange holds anchor and head positions with blockId and offset, and keeps its reference until the selection moves, so the default comparator works for it.

Templates unwrap only top-level refs:

ValueIn a templateIn script
Top-level or destructured ref, such as pagepagepage.value
Ref inside a returned objectbold.isEnabled.valuebold.isEnabled.value
ComposableReturnsNotes
useEditorState(selector, isEqual?, options?)Readonly<ShallowRef<T>>Selected snapshot value.
useDocxEditor()ShallowRef<DocxEditorInstance | null>null before creation and outside a root.
useEditorEvent(event, handler)voidSubscribes for the component lifetime.
useEditorSnapshot(editor)Ref<number>Revision counter for an external store.
useEditorCaret()ShallowRef<{ blockId, offset } | null>Caret position. Also carries paragraphId for at parameters.
useEditorHostDocument()Readonly<ShallowRef<Document | null>>Document that holds the pages, also in a pop-out window. null on the server.
useEditorColorMode(){ colorMode: ComputedRef }'light' or 'dark'. 'light' outside a root.

selectionChange also fires when other state moves without a document change, such as the page count. Compare snapshot.selection with the previous value before you react.

paragraphsChange lists only the paragraphs that one commit touched, so a proofing tool can check those paragraphs instead of the whole document. For an example, see Check spelling and grammar.

useDocxEditor

Use the instance for actions and one-time reads:

<script setup lang="ts">
import { useDocxEditor } from '@docx-editor.dev/vue';

const props = defineProps<{ upload: (bytes: ArrayBuffer) => Promise<void> }>();
const editor = useDocxEditor();

async function save() {
  const bytes = await editor.value?.save();
  if (bytes) void props.upload(bytes);
}
</script>

A direct snapshot() call does not create a Vue subscription. For scrollToAnchor and highlightAnchor, see Navigation.

Choose a composable

State members are refs; function members are plain functions.

Formatting and page setup

ComposableReturns
useFontFamily(){ value, options, setValue, isEnabled }
useParagraphStyle(){ value, options, setValue, isEnabled } for paragraph styles
useParagraphFormat(){ format, apply, isEnabled }
useParagraphIndent(){ indent, apply, isEnabled }
usePageSetup(){ pageSetup, apply, isEnabled }
useEditorValueCommand(slotId){ value, options, execute, isEnabled, disabledReason }. See Apply a value.
useZoom(){ zoom, mode, levels, isFit, canZoomIn, canZoomOut, setZoom, setMode, zoomIn, zoomOut, reset, fitToWidth, auto }

apply sends one command and returns true when it applied.

apply inputResult
Omitted fieldStays unchanged.
null on spacing or indentClears the local value.
0Sets an explicit zero.

In useParagraphFormat().format, a field is null when the selected paragraphs differ. usePageSetup uses twips for sizes and margins, and scope takes 'section' or 'document'.

For const font = useFontFamily(), read the current family as font.value.value.

useZoom

For a complete zoom control, see Zoom.

Document content

ComposableReturns
useWatermark(){ watermark, apply, read, isEnabled }
useBookmarks(){ bookmarks, insert, remove, goTo, keepFirst, isWritable }
useGoToBookmark(options?){ query, setQuery, rows, bookmarks, activeIndex, setActiveIndex, move, go, problem, problemName, sortBy, setSortBy, showHidden, setShowHidden }
useCommentDraftRequest(handler)void

useWatermark

apply sends one setWatermark command, so each call is one undo step. Pass null to remove the watermark. read() returns the current watermark as a setWatermark value, including picture bytes.

useBookmarks

Each action sends one command and returns ExecResult. goTo works in a read-only document; isWritable reports whether edits are accepted.

Each name has one entry; duplicates counts copies, and keepFirst(name) removes them without moving the selection.

useGoToBookmark(() => ({ enabled: isOpen.value })) reads bookmarks only while your UI is open. For details, see Bookmarks.

go(name?) targets name, then the highlighted row. For a nonempty query, it then tries an exact name match, ignoring case, then the first result. It returns ExecResult.

useCommentDraftRequest

Register this handler for your own comment UI. review.addComment stays disabled until a handler is registered, and the latest registration wins. To stop serving requests, unmount the component, for example with v-if.

The handler takes no arguments. Read the selection with editor.getSelectionPlacement(), and pin it with editor.retainSelection() while the draft is open.

ComposableReturns
useDocumentOutline(){ items, headings, selectedBlockId, goTo, isEmpty }
useDocumentSearch(options?){ query, setQuery, find, matches, activeIndex, activeMatch, next, previous, goTo, clear, isPending, truncated, matchCase, setMatchCase, wholeWord, setWholeWord }
useHighlights(name, source, options?)ComputedRef<UseHighlightsReturn>: { applied, unavailable, refresh }
useHighlightAt(name?)Readonly<ShallowRef> with the highlight under the pointer, or null
useNavigationPane(options?){ open, setOpen, toggle, tab, setTab, paneWidth, shift, overlay }
usePaneRequest(listener, options?)Nothing. Calls listener with { pane, focus } when Insert > Chart, Edit chart, or Format shape asks for a pane that options.panes names. panes defaults to ['chart']. Answer it with any UI. See Place shape and chart controls.
useObjectControl(slotId)Refs of one shape.* or chart.* slot: a typed value, options, isActive, isEnabled, disabledReason, and label, with execute and, on toggle slots, toggle. See Place shape and chart controls.
useSelectedChart()UseSelectedChartReturn: computed refs of the selected chart, its data and format, whether each can change, execute for the chart commands, and editData for one checked data change. See Build your own chart pane.
useSelectedShape()UseSelectedShapeReturn: computed refs of the selected shape's drawingNodeId and format, whether the fill, transparency, and outline can change with reasons, execute for setShapeFill and setShapeOutline, and edit for one checked pane change. See Format a shape.
useNavigationShift()ShallowRef<number>, the page offset for an open pane

Each outline item is { heading, depth }, and depth counts from the shallowest heading. Search options accept a value, ref, or getter.

setQuery waits 150 milliseconds; find searches at once. truncated means the search stopped at 2,000 matches. For examples, see Navigation.

useHighlights

A function source reruns after document changes and when the refs it reads change. If the source reads state that is not reactive, call result.value.refresh() after that state changes. For options, see Highlight text ranges.

Loading, fonts, and locale

ComposableReturns
useDocxSource(source, options?){ document, fonts, error, isLoading }
useFonts(source, ...fragments) or useFonts(...origins)MarkedFontResolver
useOpenFailure(options?){ failure, message, dismiss }
useTranslation(){ t, catalogue, lang }
useChromeTranslate(overrides?)ComputedRef<ChromeTranslate> that checks the override Map first
useChromeDir()Readonly<ShallowRef<'ltr' | 'rtl' | undefined>>

useDocxSource

useDocxSource fetches the document and its fonts. It accepts a URL string, URL, Uint8Array, or ArrayBuffer, as a value, ref, or getter.

For font origins, see Fonts. For refused opens, see Open failures.

Review

ComposableReturns
useReviewAuthors()Readonly<ShallowRef<readonly ReviewAuthorInfo[]>>, tracked-change authors first
useReviewGutter()ShallowRef<{ inlineStart, inlineEnd }> reserved by the review rail

@docx-editor.dev/pro/vue adds useReview, useReviewOf, useReviewItem, useReviewAuthor, useReviewCardHeights, useStackedReviewPositions, and useReviewRailMetrics. See Tracked changes.

Popovers, scopes, and toolbar helpers

ComposableReturns
useHyperlinkPopup(){ state, open, openAtCaret, close, beginEdit, commitEdit, setUrl, setText, copy, unlink, openTarget }
useHyperlinkPopupInstance(active?)Same, outside the owning part
useContentControl(){ control, controls, setValue, remove, formFill, ... }
useContentControlInstance()Same, outside the owning part
useContentControlWidget()Value popup draft, calendar, and actions. selectDay(iso) and selectToday() apply the date at once. listId and listNavigation are plain values, not refs. See Compose the value popup.
useHeaderFooterState()ShallowRef with the active header or footer scope, or null
useNoteScopeState()Active footnote or endnote scope
useNotePropertiesState()ShallowRef with note numbering properties, or null
useContextMenuTarget()HTMLElement | null that received the last context-menu action
useContextMenuAnchor()ComputedRef with { x, y, trigger } where the open context menu is anchored, or null; trigger is 'pointer' or 'keyboard'
useContextMenuHighlights(name?)Readonly<ShallowRef> with the highlights at the opening right-click, or at the caret for a keyboard open. See Read highlights in the context menu.
useTableBorderTargetLabel()ComputedRef<string> label of the table-border target
useToolbarContext()ComputedRef<{ t, onSave }>
useToolbarLabel()(key) => string for the active scope
useToolbarLabelFor(t)(key) => string for a given translator
useScopeClassName()'', 'docx-editor ', or 'docx-editor dark '
useScopedChromeAnchor(findAnchor, placement){ ref, style } for overlay chrome

Dialog draft contexts

Call these composables in a child of the matching dialog. Each returns values, setValue(name, value), errors, isEnabled, apply(), and cancel(). State members are refs:

ComposableDraft typeDraft keys
usePageSetupDialog()PageSetupDialogFieldspageWidth, pageHeight, orientation, marginTop, marginBottom, marginLeft, marginRight, scope
useParagraphDialog()UseParagraphDialogReturn['values']['value']alignment, indentLeft, indentRight, special, specialBy, spaceBefore, spaceAfter, lineRule, lineValue, contextualSpacing, keepNext, keepLines, widowControl, pageBreakBefore, tabStops, clearedAllTabStops
useTextFormFieldDialog()TextFormFieldDialogFieldsdefaultText, type, maxLength, format, enabled
useRevisionMarkupDialog()ResolvedRevisionMarkupinsertions, deletions, changedLines, movedFrom, movedTo, cells, formatting, trackMoves, trackFormatting
useCompareDocumentsDialog()CompareDocumentsDialogValuesrevised, authorName, detectFormatChanges, removeDateAndTime
useWatermarkDialog()WatermarkDialogFieldskind, imageData, imageName, scale, washout, text, fontFamily, fontSizePt, bold, italic, transparency, color, layout
useBookmarkDialog()BookmarkDialogFieldsname, sortBy, showHidden
useSplitCellDialog()SplitCellDialogFieldscolumns, rows (strings)

Most custom Field names match draft keys, with two exceptions:

DialogField nameDraft keys
Page SetuppageSizeUpdates pageWidth and pageHeight. Neither is a Field name.
ParagraphNoneclearedAllTabStops is draft state only.
ComposableExtra member
useParagraphDialog()mixed
useRevisionMarkupDialog()reset() restores default draft values. Call apply() to apply them.
useSplitCellDialog()limits: the selected cell's maximum row and column counts, or null

Page sizes, margins, and indents use twips (1,440 per inch). Paragraph spacing uses points, except lineValue with lineRule: 'multiple', which is a line multiple. For the compare dialog's progress and cancel state, see Compare documents.

For a custom input, see Connect a custom input.

Apply a value

useEditorValueCommand reads the selected value and applies a new one. This slider sets the font size:

<script setup lang="ts">
import { ref } from 'vue';
import { useEditorValueCommand, useHistoryGroup } from '@docx-editor.dev/vue';

const size = useEditorValueCommand('font.size');
const gesture = useHistoryGroup({ kind: 'range' });
const input = (node: unknown) => gesture.ref(node as HTMLInputElement | null);
const error = ref<string | null>(null);

function apply(event: Event) {
  const result = size.execute(Number((event.target as HTMLInputElement).value), gesture.options());
  error.value = result.ok ? null : result.reason;
}
</script>

<template>
  <label :title="size.disabledReason.value ?? undefined">
    {{ size.value.value === null ? 'Mixed' : `${size.value.value / 2} pt` }}
    <input
      :ref="input"
      type="range"
      min="16"
      max="144"
      :value="size.value.value ?? 22"
      :disabled="!size.isEnabled.value"
      @input="apply"
    />
    <output aria-live="polite">{{ error }}</output>
  </label>
</template>

Font size uses half-points: 24 means 12 pt. null means mixed or unavailable, and value follows undo and redo. Other value slots include text.color (six hex digits without #), font.family, text.highlight, styles.style, list.lineSpacing, and image slots.

execute(value, options?) returns ExecResult:

FieldMeaning
okfalse when the editor refused the command.
code, reasonPresent when ok is false. Use code in logic and show reason.
changedtrue when the document changed. Formatting at a caret can change only the typing format.
history?.kindstarted, extended, split, or none for grouped writes. split does not mean failure.

useEditorCommand().execute(options) takes the same options but returns a boolean. For the full result of a raw command, call editor.value.exec(command, options).

Group an input gesture

useHistoryGroup({ kind }): { ref, options } makes a continuous gesture one undo step. Bind ref to the control through a callback ref, and pass options() to each command from that gesture:

kindUse it forWhat ends the gesture
range, repeatA slider, or a button that repeats while heldPointer release or cancel, lost capture, keyup, or blur
keyboardRepeated keydown eventsKeyup, Escape, or blur
native-colorAn HTML color inputNative change, next activation, Escape, or blur

The binding disposes the group on unmount or editor replacement. For repeat, your app owns the timer. For a color input, apply values in @input; a native change does not guarantee that the picker closed.

useEditorEvent('historyDiagnostic', handler) reports interrupted groups. To group a review decision, see Group a review decision.

Limits

  • Call composables during setup() inside DocxEditorRoot. Outside it, useDocxEditor().value is null.
  • canUndo reports undo availability, not unsaved changes. Track save completion yourself.
  • selectionChange also fires for state unrelated to the selection.
  • Dialog draft composables read a draft; they do not open the dialog.
  • Image value commands reject the historyGroup option.
  • useContentControlWidget().showMonth(year, month) accepts integer years 100 through 9999 and zero-based months 0 through 11.

See also