New

docx-editor 1.x has shipped. Vue support, i18n, agents. Read the migration guide →

API Referencev1.0.2

@eigenpal/docx-editor-react/hooks

React hooks for editor history, table selection, find/replace, autosave, clipboard, and zoom. Use alongside the main `DocxEditor` component.

Functions(22)

Clamp zoom to valid range

declare function clampZoom(zoom: number, minZoom?: number, maxZoom?: number): number;

Find nearest zoom preset

declare function findNearestZoomPreset(zoom: number): number;

Format zoom level for display

declare function formatZoom(zoom: number): string;

Generate selection overlay elements (for use in JSX)

Usage:

```tsx const { highlightRects } = useSelectionHighlight({ ... }); return ( <div style={{ position: 'relative' }}> {generateOverlayElements(highlightRects)} <div>... content ...</div> </div> ); ```

declare function generateOverlayElements(rects: HighlightRect[], config?: SelectionHighlightConfig): React__default.ReactNode[];

Get next zoom preset (for zoom in)

declare function getNextZoomPreset(zoom: number): number;

Get previous zoom preset (for zoom out)

declare function getPreviousZoomPreset(zoom: number): number;

Get zoom presets

declare function getZoomPresets(): number[];

Check if zoom level is at a preset

declare function isZoomPreset(zoom: number): boolean;

Parse zoom from percentage string

declare function parseZoom(zoomString: string): number | null;
declare function useAspectLockedSize(): UseAspectLockedSizeReturn;

Simplified hook that just tracks state changes automatically

declare function useAutoHistory<T>(value: T, options?: UseHistoryOptions<T>): Omit<UseHistoryReturn<T>, 'push'>;
declare function useAutoSave(document: Document | null | undefined, options?: UseAutoSaveOptions): UseAutoSaveReturn;
declare function useClipboard(options?: UseClipboardOptions): UseClipboardReturn;

Hook for document history with specialized comparison

declare function useDocumentHistory<T extends {
    package?: {
        document?: unknown;
        headers?: unknown;
        footers?: unknown;
    } | null;
} | null>(document: T, options?: Omit<UseHistoryOptions<T>, 'isEqual'>): UseHistoryReturn<T>;
declare function useDragAutoScroll(input: DragAutoScrollOptions): {
    updateMousePosition: (clientX: number, clientY: number) => void;
    stopAutoScroll: () => void;
};

Hook for managing find/replace dialog state

declare function useFindReplace(hookOptions?: FindReplaceOptions): UseFindReplaceReturn;
declare function useFixedDropdown(input: UseFixedDropdownOptions): UseFixedDropdownReturn;

Custom hook for managing undo/redo history

declare function useHistory<T>(initialState: T, options?: UseHistoryOptions<T>): UseHistoryReturn<T>;

Hook to manage selection highlighting in the editor

declare function useSelectionHighlight(options: UseSelectionHighlightOptions): UseSelectionHighlightReturn;
declare function useTableSelection(input: UseTableSelectionOptions): UseTableSelectionReturn;
declare function useVisualLineNavigation(input: VisualLineNavigationOptions): {
    stickyXRef: React$1.RefObject<number | null>;
    lastVisualLineIndexRef: React$1.RefObject<number>;
    getCaretClientX: (pmPos: number) => number | null;
    findLineElementAtPosition: (pmPos: number) => HTMLElement | null;
    findPositionOnLineAtClientX: (lineEl: HTMLElement, clientX: number) => number | null;
    handlePMKeyDown: (view: EditorView, event: KeyboardEvent) => boolean;
};

React hook for Ctrl+scroll zoom functionality

declare function useWheelZoom(options?: UseWheelZoomOptions): UseWheelZoomReturn;

Classes(1)

Create a history manager for non-React usage

declare class HistoryManager<T>
MemberTypeSummary
(constructor)Constructs a new instance of the `HistoryManager` class
canRedoboolean
canUndoboolean
clear
push
redo
reset
stateT
undo

Interfaces(23)

Drag Auto-Scroll Hook

When the user is drag-selecting text and moves the mouse near the top or bottom edge of the scroll container, this hook auto-scrolls the container and continues extending the selection.

interface DragAutoScrollOptions
MemberTypeSummary
onScrollExtendSelection(clientX: number, clientY: number) => voidCalled during auto-scroll to extend the selection at the current mouse position.
pagesContainerRefReact.RefObject<HTMLDivElement | null>Ref to the pages container (used to find the scroll parent).

Options for the useFindReplace hook

interface FindReplaceOptions
MemberTypeSummary
initialReplaceMode?booleanWhether to show replace functionality initially
onCurrentMatchChange?(match: FindMatch | null, index: number) => voidCallback when current match changes
onMatchesChange?(matches: FindMatch[]) => voidCallback when matches change

State for the find/replace hook

interface FindReplaceState
MemberTypeSummary
currentIndexnumberCurrent match index
isOpenbooleanWhether the dialog is open
matchesFindMatch[]All matches found
optionsFindOptionsFind options
replaceModebooleanWhether in replace mode
replaceTextstringCurrent replace text
searchTextstringCurrent search text

History entry containing state and metadata

interface HistoryEntry<T>
MemberTypeSummary
description?stringOptional description of what changed
stateTThe state at this point
timestampnumberTimestamp when this entry was created

Props for selection overlay component

interface SelectionOverlayProps
MemberTypeSummary
className?stringAdditional class name
config?SelectionHighlightConfigStyle configuration
rectsHighlightRect[]Highlight rectangles to render

useTableSelection Hook

Thin React wrapper around the framework-agnostic TableSelectionManager. Provides table selection tracking and table operation dispatch.

interface TableSelectionState
MemberTypeSummary
columnIndexnumber | null
contextTableContext | null
rowIndexnumber | null
tableTable | null
tableIndexnumber | null

Width/height inputs with an optional aspect-ratio lock. `width`/`height` are `number | ''` so a cleared field shows empty instead of 0.

interface UseAspectLockedSizeReturn
MemberTypeSummary
handleHeightChange(raw: string) => void
handleWidthChange(raw: string) => voidNumber-input onChange handlers. Empty string clears, otherwise clamps to = 1.
heightnumber | ''
lockAspectboolean
seed(w: number | null | undefined, h: number | null | undefined) => voidSeed both fields and re-lock. Null/undefined values clear the input.
setLockAspect(locked: boolean) => void
widthnumber | ''

Options for useAutoSave hook

interface UseAutoSaveOptions
MemberTypeSummary
debounceDelay?numberDebounce delay for saveOnChange in milliseconds (default: 2000)
enabled?booleanWhether auto-save is enabled (default: true)
interval?numberSave interval in milliseconds (default: 30000 - 30 seconds)
maxAge?numberMaximum age of auto-save in milliseconds before it's considered stale (default: 24 hours)
onError?(error: Error) => voidCallback when save fails
onRecoveryAvailable?(savedDocument: SavedDocumentData) => voidCallback when recovery data is found
onSave?(timestamp: Date) => voidCallback when save succeeds
saveOnChange?booleanWhether to save immediately when document changes (debounced)
storageKey?stringStorage key for localStorage (default: 'docx-editor-autosave')

Return value of useAutoSave hook

interface UseAutoSaveReturn
MemberTypeSummary
acceptRecovery() => Document | null
clearAutoSave() => void
disable() => void
dismissRecovery() => void
enable() => void
getRecoveryData() => SavedDocumentData | null
hasRecoveryDataboolean
isEnabledboolean
lastSaveTimeDate | null
save() => Promise<boolean>
statusAutoSaveStatus

useClipboard Hook

Thin React wrapper around the framework-agnostic ClipboardManager. Handles clipboard operations with formatting preservation.

interface UseClipboardOptions
MemberTypeSummary
cleanWordFormatting?boolean
editable?boolean
onCopy?(selection: ClipboardSelection) => void
onCut?(selection: ClipboardSelection) => void
onError?(error: Error) => void
onPaste?(content: ParsedClipboardContent, asPlainText: boolean) => void
theme?Theme | nullDocument theme — used to resolve themed colors in the HTML clipboard payload.
interface UseClipboardReturn
MemberTypeSummary
copy(selection: ClipboardSelection) => Promise<boolean>
cut(selection: ClipboardSelection) => Promise<boolean>
handleCopy(event: ClipboardEvent) => void
handleCut(event: ClipboardEvent) => void
handleKeyDown(event: KeyboardEvent) => void
handlePaste(event: ClipboardEvent) => void
isProcessingboolean
lastPastedContentParsedClipboardContent | null
paste(asPlainText?: boolean) => Promise<ParsedClipboardContent | null>

Return type for the useFindReplace hook

interface UseFindReplaceReturn
MemberTypeSummary
close() => voidClose the dialog
getCurrentMatch() => FindMatch | nullGet current match
goToMatch(index: number) => voidGo to a specific match by index
goToNextMatch() => numberGo to next match
goToPreviousMatch() => numberGo to previous match
hasMatches() => booleanCheck if has matches
openFind(selectedText?: string) => voidOpen the find dialog
openReplace(selectedText?: string) => voidOpen the replace dialog
setMatches(matches: FindMatch[], currentIndex?: number) => voidSet search results
setOptions(options: Partial<FindOptions>) => voidUpdate find options
setReplaceText(text: string) => voidUpdate replace text
setSearchText(text: string) => voidUpdate search text
stateFindReplaceStateCurrent state
toggle() => voidToggle dialog visibility

Hook for toolbar dropdowns that need position:fixed to escape overflow:auto/hidden ancestors.

Returns refs and styles for a dropdown that positions itself below its trigger using fixed coordinates (like MenuDropdown), so it isn't clipped by the toolbar's overflow-x-auto container.

interface UseFixedDropdownOptions
MemberTypeSummary
align?'left' | 'right''left' aligns dropdown left edge to trigger, 'right' aligns right edge
isOpenboolean
onClose() => void
interface UseFixedDropdownReturn
MemberTypeSummary
containerRefRefObject<HTMLDivElement | null>
dropdownRefRefObject<HTMLDivElement | null>
dropdownStyleCSSProperties
handleMouseDown(e: React.MouseEvent) => void

Options for the useHistory hook

interface UseHistoryOptions<T>
MemberTypeSummary
containerRef?React.RefObject<HTMLElement>Ref to the container element for keyboard events
enableKeyboardShortcuts?booleanWhether to enable keyboard shortcuts (default: true)
groupingInterval?numberTime in ms to group rapid changes (default: 500)
isEqual?(a: T, b: T) => booleanCustom comparison function for detecting changes
maxEntries?numberMaximum number of entries in history (default: 100)
onRedo?(state: T) => voidCallback when redo is triggered
onUndo?(state: T) => voidCallback when undo is triggered

Return type of the useHistory hook

interface UseHistoryReturn<T>
MemberTypeSummary
canRedobooleanWhether redo is available
canUndobooleanWhether undo is available
clear() => voidClear all history
getRedoStack() => HistoryEntry<T>[]Get all redo entries (for debugging/display)
getUndoStack() => HistoryEntry<T>[]Get all undo entries (for debugging/display)
push(newState: T, description?: string) => voidPush a new state to history
redo() => T | undefinedRedo to next state
redoCountnumberNumber of entries in redo stack
reset(newInitialState?: T) => voidReset to initial state and clear history
stateTCurrent state
transformAll(fn: (state: T) => T) => voidTransform all stored states (current + undo/redo stacks)
undo() => T | undefinedUndo to previous state
undoCountnumberNumber of entries in undo stack
interface

UseSelectionHighlightOptions

packages/react/src/hooks/useSelectionHighlight.ts:36

Options for the useSelectionHighlight hook

interface UseSelectionHighlightOptions
MemberTypeSummary
config?SelectionHighlightConfigCustom highlight configuration
containerRefReact__default.RefObject<HTMLElement>Reference to the container element
debounceMs?numberDebounce delay for rect updates in ms (default: 16)
enabled?booleanWhether to enable selection highlighting
onSelectionChange?(hasSelection: boolean, text: string) => voidCallback when selection changes
useOverlay?booleanWhether to use overlay rectangles (default: false, uses CSS)

Return value from the useSelectionHighlight hook

interface UseSelectionHighlightReturn
MemberTypeSummary
getOverlayStyle(rect: HighlightRect) => CSSPropertiesGet styles for a highlight rect overlay
hasSelectionbooleanWhether there is an active selection
highlightRectsHighlightRect[]Highlight rectangles (only populated if useOverlay is true)
isSelectionInContainerbooleanWhether selection is within the container
refresh() => voidRefresh the highlight state
selectedTextstringThe selected text
interface UseTableSelectionOptions
MemberTypeSummary
documentDocument | null
onChange?(document: Document) => void
onSelectionChange?(context: TableContext | null) => void
interface UseTableSelectionReturn
MemberTypeSummary
applySplitCell(rows: number, cols: number) => void
clearSelection() => void
getSplitCellConfig() => TableSplitConfig | null
handleAction(action: TableAction) => void
handleCellClick(tableIndex: number, rowIndex: number, columnIndex: number) => void
isCellSelected(tableIndex: number, rowIndex: number, columnIndex: number) => boolean
stateTableSelectionState
tableContextTableContext | null

Options for useWheelZoom hook

interface UseWheelZoomOptions
MemberTypeSummary
containerRef?React.RefObject<HTMLElement>Container element ref to attach wheel listener
enabled?booleanWhether zoom is enabled (default: true)
enableKeyboardShortcuts?booleanWhether to enable keyboard shortcuts (Ctrl++, Ctrl+-, Ctrl+0)
initialZoom?numberInitial zoom level (default: 1.0)
maxZoom?numberMaximum zoom level (default: 4.0)
minZoom?numberMinimum zoom level (default: 0.25)
onZoomChange?(zoom: number) => voidCallback when zoom changes
preventDefault?booleanWhether to prevent default browser zoom behavior
zoomStep?numberZoom step for each scroll event (default: 0.1)

Return value of useWheelZoom hook

interface UseWheelZoomReturn
MemberTypeSummary
handleKeyDown(event: KeyboardEvent) => voidKeyboard event handler (for manual attachment)
handleWheel(event: WheelEvent) => voidWheel event handler (for manual attachment)
isMaxZoombooleanWhether currently at maximum zoom
isMinZoombooleanWhether currently at minimum zoom
resetZoom() => voidReset zoom to initial level
setZoom(zoom: number) => voidSet zoom level directly
zoomnumberCurrent zoom level
zoomIn() => voidZoom in by step
zoomOut() => voidZoom out by step
zoomPercentnumberZoom percentage (e.g., 100 for zoom level 1.0)
zoomTo100() => voidReset zoom to 100%
zoomToFit(containerWidth: number, contentWidth: number) => voidZoom to fit width
interface VisualLineNavigationOptions
MemberTypeSummary
pagesContainerRefReact.RefObject<HTMLDivElement | null>

Variables(1)

Preset zoom levels for snapping

ZOOM_PRESETS: number[]