@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 (23)

clampZoomfunctionSource ↗

Clamp zoom to valid range

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

findNearestZoomPresetfunctionSource ↗

Find nearest zoom preset

declare function findNearestZoomPreset(zoom: number): number;

formatZoomfunctionSource ↗

Format zoom level for display

declare function formatZoom(zoom: number): string;

generateOverlayElementsfunctionSource ↗

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[];

getNextZoomPresetfunctionSource ↗

Get next zoom preset (for zoom in)

declare function getNextZoomPreset(zoom: number): number;

getPreviousZoomPresetfunctionSource ↗

Get previous zoom preset (for zoom out)

declare function getPreviousZoomPreset(zoom: number): number;

getZoomPresetsfunctionSource ↗

Get zoom presets

declare function getZoomPresets(): number[];

isZoomPresetfunctionSource ↗

Check if zoom level is at a preset

declare function isZoomPreset(zoom: number): boolean;

parseZoomfunctionSource ↗

Parse zoom from percentage string

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

useAspectLockedSizefunctionSource ↗

declare function useAspectLockedSize(): UseAspectLockedSizeReturn;

useAutoHistoryfunctionSource ↗

Simplified hook that just tracks state changes automatically

declare function useAutoHistory<T>(value: T, options?: UseHistoryOptions<T>): Omit<UseHistoryReturn<T>, 'push'>;

useAutoSavefunctionSource ↗

declare function useAutoSave(document: Document | null | undefined, options?: UseAutoSaveOptions): UseAutoSaveReturn;

useClipboardfunctionSource ↗

declare function useClipboard(options?: UseClipboardOptions): UseClipboardReturn;

useDocumentHistoryfunctionSource ↗

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>;

useDragAutoScrollfunctionSource ↗

declare function useDragAutoScroll(input: DragAutoScrollOptions): {
    updateMousePosition: (clientX: number, clientY: number) => void;
    stopAutoScroll: () => void;
};

useFindReplacefunctionSource ↗

Hook for managing find/replace dialog state

declare function useFindReplace(hookOptions?: FindReplaceOptions): UseFindReplaceReturn;

useFixedDropdownfunctionSource ↗

declare function useFixedDropdown(input: UseFixedDropdownOptions): UseFixedDropdownReturn;

useHistoryfunctionSource ↗

Custom hook for managing undo/redo history

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

useSelectionHighlightfunctionSource ↗

Hook to manage selection highlighting in the editor

declare function useSelectionHighlight(options: UseSelectionHighlightOptions): UseSelectionHighlightReturn;

useTableSelectionfunctionSource ↗

declare function useTableSelection(input: UseTableSelectionOptions): UseTableSelectionReturn;

useTrackedChangesfunctionSource ↗

Returns tracked changes (and the comment→revision overlap map for threading) derived from the latest PM state. Memoized on state identity, so derivation only re-runs when PM state changes (which happens on every doc-changing transaction, including remote ones via ySyncPlugin).

No debounce: a single O(N) doc walk, cheap enough to run per transaction. If you see jank on huge documents, wrap the setter that drives the state argument in requestAnimationFrame rather than reintroducing a delay here — a delay makes the sidebar feel laggy.

declare function useTrackedChanges(state: EditorState | null): TrackedChangesResult;

useVisualLineNavigationfunctionSource ↗

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;
};

useWheelZoomfunctionSource ↗

React hook for Ctrl+scroll zoom functionality

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

Classes (1)

HistoryManagerclassSource ↗

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)

DragAutoScrollOptionsinterfaceSource ↗

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).

FindReplaceOptionsinterfaceSource ↗

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

FindReplaceStateinterfaceSource ↗

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

HistoryEntryinterfaceSource ↗

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

SelectionOverlayPropsinterfaceSource ↗

Props for selection overlay component

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

TableSelectionStateinterfaceSource ↗

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

UseAspectLockedSizeReturninterfaceSource ↗

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 | ''

UseAutoSaveOptionsinterfaceSource ↗

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')

UseAutoSaveReturninterfaceSource ↗

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

UseClipboardOptionsinterfaceSource ↗

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.

UseClipboardReturninterfaceSource ↗

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>

UseFindReplaceReturninterfaceSource ↗

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

UseFixedDropdownOptionsinterfaceSource ↗

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

UseFixedDropdownReturninterfaceSource ↗

interface UseFixedDropdownReturn
MemberTypeSummary
containerRefRefObject<HTMLDivElement | null>
dropdownRefRefObject<HTMLDivElement | null>
dropdownStyleCSSProperties
handleMouseDown(e: React.MouseEvent) => void

UseHistoryOptionsinterfaceSource ↗

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

UseHistoryReturninterfaceSource ↗

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

UseSelectionHighlightOptionsinterfaceSource ↗

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)

UseSelectionHighlightReturninterfaceSource ↗

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

UseTableSelectionOptionsinterfaceSource ↗

interface UseTableSelectionOptions
MemberTypeSummary
documentDocument | null
onChange?(document: Document) => void
onSelectionChange?(context: TableContext | null) => void

UseTableSelectionReturninterfaceSource ↗

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

UseWheelZoomOptionsinterfaceSource ↗

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)

UseWheelZoomReturninterfaceSource ↗

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

VisualLineNavigationOptionsinterfaceSource ↗

interface VisualLineNavigationOptions
MemberTypeSummary
pagesContainerRefReact.RefObject<HTMLDivElement | null>

Variables (1)

ZOOM_PRESETSconstSource ↗

Preset zoom levels for snapping

ZOOM_PRESETS: number[]

On this page