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.
| Member | Type | Description |
|---|---|---|
execute(options?) | boolean | Runs the command. Returns true when it applied. |
isActive | ComputedRef<boolean> | Command state at the caret. |
isEnabled | ComputedRef<boolean> | Whether the command can run. |
disabledReason | ComputedRef<string | null> | Why the command cannot run. |
value | ComputedRef<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:
| Value | In a template | In script |
|---|---|---|
Top-level or destructured ref, such as page | page | page.value |
| Ref inside a returned object | bold.isEnabled.value | bold.isEnabled.value |
| Composable | Returns | Notes |
|---|---|---|
useEditorState(selector, isEqual?, options?) | Readonly<ShallowRef<T>> | Selected snapshot value. |
useDocxEditor() | ShallowRef<DocxEditorInstance | null> | null before creation and outside a root. |
useEditorEvent(event, handler) | void | Subscribes 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
| Composable | Returns |
|---|---|
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 input | Result |
|---|---|
| Omitted field | Stays unchanged. |
null on spacing or indent | Clears the local value. |
0 | Sets 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
| Composable | Returns |
|---|---|
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.
Navigation and search
| Composable | Returns |
|---|---|
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
| Composable | Returns |
|---|---|
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
| Composable | Returns |
|---|---|
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
| Composable | Returns |
|---|---|
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:
| Composable | Draft type | Draft keys |
|---|---|---|
usePageSetupDialog() | PageSetupDialogFields | pageWidth, 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() | TextFormFieldDialogFields | defaultText, type, maxLength, format, enabled |
useRevisionMarkupDialog() | ResolvedRevisionMarkup | insertions, deletions, changedLines, movedFrom, movedTo, cells, formatting, trackMoves, trackFormatting |
useCompareDocumentsDialog() | CompareDocumentsDialogValues | revised, authorName, detectFormatChanges, removeDateAndTime |
useWatermarkDialog() | WatermarkDialogFields | kind, imageData, imageName, scale, washout, text, fontFamily, fontSizePt, bold, italic, transparency, color, layout |
useBookmarkDialog() | BookmarkDialogFields | name, sortBy, showHidden |
useSplitCellDialog() | SplitCellDialogFields | columns, rows (strings) |
Most custom Field names match draft keys, with two exceptions:
| Dialog | Field name | Draft keys |
|---|---|---|
| Page Setup | pageSize | Updates pageWidth and pageHeight. Neither is a Field name. |
| Paragraph | None | clearedAllTabStops is draft state only. |
| Composable | Extra 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:
| Field | Meaning |
|---|---|
ok | false when the editor refused the command. |
code, reason | Present when ok is false. Use code in logic and show reason. |
changed | true when the document changed. Formatting at a caret can change only the typing format. |
history?.kind | started, 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:
kind | Use it for | What ends the gesture |
|---|---|---|
range, repeat | A slider, or a button that repeats while held | Pointer release or cancel, lost capture, keyup, or blur |
keyboard | Repeated keydown events | Keyup, Escape, or blur |
native-color | An HTML color input | Native 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()insideDocxEditorRoot. Outside it,useDocxEditor().valueisnull. canUndoreports undo availability, not unsaved changes. Track save completion yourself.selectionChangealso fires for state unrelated to the selection.- Dialog draft composables read a draft; they do not open the dialog.
- Image value commands reject the
historyGroupoption. useContentControlWidget().showMonth(year, month)accepts integer years 100 through 9999 and zero-based months 0 through 11.