New

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

API Referencev1.0.2

@eigenpal/docx-editor-core/utils

Editor utilities (curated public surface).

The named exports below are the public API contract. Adding a helper to a source module does not automatically make it public — it must be added to this barrel to be reachable from `@eigenpal/docx-editor-core/utils`.

Functions(153)

Check if selection styles are injected

declare function areSelectionStylesInjected(): boolean;

Blend two colors together

declare function blendColors(color1: ColorValue | undefined | null, color2: ColorValue | undefined | null, ratio: number, theme: Theme | null | undefined): string;

Convert a BorderSpec to CSS border properties

declare function borderToStyle(border: BorderSpec | undefined | null, side?: 'Top' | 'Bottom' | 'Left' | 'Right' | '', theme?: Theme | null): CSSProperties$1;

Build lookup maps from an anchor list — by start position and by covered slot.

declare function buildAnchorMaps<T>(anchors: CellAnchor<T>[]): {
    byStart: Map<string, CellAnchor<T>>;
    byCoveredSlot: Map<string, CellAnchor<T>>;
};

Check if a font is available on the system using canvas measurement

This uses the technique of comparing text width with the target font vs a known fallback font. If they differ, the font is available.

declare function canRenderFont(fontFamily: string, fallbackFont?: string): boolean;

Clamp a value between min and max

declare function clamp(value: number, min: number, max: number): number;

Clean Microsoft Word HTML

declare function cleanWordHtml(html: string): string;

Clear the current selection

declare function clearSelection(): void;

Collect all headings from a ProseMirror document.

Detection logic: 1. Check `outlineLevel` attr (set by OOXML parsing or style resolution) 2. Fallback to `styleId` matching /^[Hh]eading(d)$/

declare function collectHeadings(doc: Node): HeadingInfo[];

Check if two colors are equal

declare function colorsEqual(color1: ColorValue | undefined | null, color2: ColorValue | undefined | null, theme: Theme | null | undefined): boolean;

Compute the initial dialog values for a split-cell dialog.

declare function computeSplitDialogDefaults(rowspan: number, colspan: number): {
    minRows: number;
    minCols: number;
    initialRows: number;
    initialCols: number;
};

Compute the new anchor layout after splitting a target cell.

This is the core algorithm shared between ProseMirror and Document-model paths. It adjusts neighbor spans, shifts positions for inserted rows/cols, and creates placeholder anchors for the new split cells.

declare function computeSplitLayout<T>(anchors: CellAnchor<T>[], target: CellAnchor<T>, rows: number, cols: number, totalRows: number, createSplitCellData: (isOriginal: boolean, rowOffset: number, colOffset: number) => T): SplitLayoutResult<T>;

Copy paragraphs to clipboard with formatting

declare function copyParagraphs(paragraphs: Paragraph[], options?: ClipboardOptions): Promise<boolean>;

Copy runs to clipboard with formatting

declare function copyRuns(runs: Run[], options?: ClipboardOptions): Promise<boolean>;

Count page breaks in a document

declare function countPageBreaks(doc: Document): number;

Create clipboard keyboard handlers for an editor

declare function createClipboardHandlers(options: {
    onCopy?: () => {
        runs: Run[];
    } | null;
    onCut?: () => {
        runs: Run[];
    } | null;
    onPaste?: (content: ParsedClipboardContent) => void;
    clipboardOptions?: ClipboardOptions;
}): {
    handleCopy: (event: ClipboardEvent) => Promise<void>;
    handleCut: (event: ClipboardEvent) => Promise<void>;
    handlePaste: (event: ClipboardEvent) => void;
    handleKeyDown: (event: KeyboardEvent) => Promise<void>;
};

Create a column break content element

declare function createColumnBreak(): BreakContent;

Create a document with a single paragraph containing the given text

declare function createDocumentWithText(text: string, options?: Omit<CreateEmptyDocumentOptions, 'initialText'>): Document;

Create a double-click handler that selects words. Returns a function that should be called on dblclick events.

declare function createDoubleClickWordSelector(): (event: MouseEvent) => void;

Create an empty document with a single paragraph

declare function createEmptyDocument(options?: CreateEmptyDocumentOptions): Document;
```ts
// Create a blank document
const doc = createEmptyDocument();

// Create with custom margins
const doc = createEmptyDocument({
  marginTop: 720,  // 0.5 inch
  marginBottom: 720,
});

// Create with initial text
const doc = createEmptyDocument({
  initialText: 'Hello, World!'
});
```

Create a horizontal rule paragraph Uses a paragraph with bottom border to simulate horizontal rule

declare function createHorizontalRule(): Paragraph;

Create a text wrapping break (line break)

declare function createLineBreak(clear?: 'none' | 'left' | 'right' | 'all'): BreakContent;

Create a page break content element

declare function createPageBreak(): BreakContent;

Create an empty paragraph with a page break before it

declare function createPageBreakParagraph(): Paragraph;

Create a run containing a page break

declare function createPageBreakRun(): Run;

Create a ColorValue from RGB hex

declare function createRgbColor(hex: string): ColorValue;

Create a selection change handler that updates highlight rects

declare function createSelectionChangeHandler(containerElement: HTMLElement | null, onRectsChange: (rects: HighlightRect[]) => void, merge?: boolean): () => void;

Create a template processor with preset options

declare function createTemplateProcessor(defaultOptions?: ProcessTemplateOptions): (buffer: ArrayBuffer, variables: Record<string, string>) => ArrayBuffer;

Create a ColorValue from theme color reference

declare function createThemeColor(themeColor: ThemeColorSlot, tint?: number, shade?: number): ColorValue;
fn

createTripleClickParagraphSelector

packages/core/src/utils/textSelection.ts:440

Create a triple-click handler that selects paragraphs. This uses our custom click counting since browsers have inconsistent triple-click.

declare function createTripleClickParagraphSelector(): (event: MouseEvent) => void;

Darken a color by a percentage

declare function darkenColor(color: ColorValue | undefined | null, theme: Theme | null | undefined, percent: number): string;

Get a human-readable description of a shortcut

declare function describeShortcut(shortcut: KeyboardShortcut): string;

Convert eighths of a point to pixels (at 96 DPI)

Eighths of a point are used for border widths in OOXML.

declare function eighthsToPixels(eighths: number): number;

Convert EMUs to pixels (at 96 DPI)

1 inch = 914400 EMUs = 96 pixels Returns 0 for null/undefined/NaN inputs.

declare function emuToPixels(emu: number | undefined | null): number;

Convert EMUs to twips

declare function emuToTwips(emu: number): number;

Ensure a hex color string has a '#' prefix.

declare function ensureHexPrefix(hex: string): string;

Expand selection to word boundaries Used for double-click word selection

declare function expandSelectionToWord(): boolean;
fn

expandSelectionToWordBoundaries

packages/core/src/utils/textSelection.ts:248

Expand the current selection to word boundaries. If there's a collapsed selection (cursor), selects the word at cursor. If there's an existing selection, expands to include complete words.

declare function expandSelectionToWordBoundaries(): boolean;

Extend selection to a specific position

declare function extendSelectionTo(node: Node, offset: number): void;

Extract all font families used in a document

Uses loose typing to handle any document-like structure.

declare function extractFontsFromDocument(document: unknown): Set<string>;

Find the next word start (for Ctrl+Right navigation)

declare function findNextWordStart(text: string, position: number): number;

Find all page break positions in a document

declare function findPageBreaks(doc: Document): InsertPosition[];

Find the previous word start (for Ctrl+Left navigation)

declare function findPreviousWordStart(text: string, position: number): number;

Find the end of the current line in a text node Uses visual line detection based on bounding rectangles

declare function findVisualLineEnd(container: Node, offset: number): {
    node: Node;
    offset: number;
} | null;

Find the start of the current line in a text node Uses visual line detection based on bounding rectangles

declare function findVisualLineStart(container: Node, offset: number): {
    node: Node;
    offset: number;
} | null;

Find the word at a position and return detailed info

declare function findWordAt(text: string, position: number): WordSelectionResult;

Find word boundaries around a position in text Returns [startIndex, endIndex] inclusive start, exclusive end

declare function findWordBoundaries(text: string, position: number): [number, number];

Find the end of the current or next word

declare function findWordEnd(text: string, position: number): number;

Find the start of the current or previous word

declare function findWordStart(text: string, position: number): number;

Format a pixel value as CSS string

declare function formatPx(px: number): string;

Generate inline CSS for selection pseudo-elements

This is used to inject consistent selection styling across all editable elements.

declare function generateSelectionCSS(selector: string, config?: SelectionHighlightConfig): string;

Generate the 10×6 theme color matrix for an advanced color picker.

Columns: lt1, dk1, lt2, dk2, accent1-6 (matches Word's order) Rows: base, 80% tint, 60% tint, 40% tint, 25% shade, 50% shade

declare function generateThemeTintShadeMatrix(colorScheme?: ThemeColorScheme | null): ThemeMatrixCell[][];

Extract image files from clipboard data (if present).

declare function getClipboardImageFiles(clipboardData: DataTransfer | null): File[];

Get contrasting text color for a background

declare function getContrastingColor(backgroundColor: ColorValue | undefined | null, theme: Theme | null | undefined): string;

Get the Google Fonts equivalent for a font name

declare function getGoogleFontEquivalent(fontName: string): string;

Generate CSS styles for a highlight rectangle

declare function getHighlightRectStyle(rect: HighlightRect, config?: SelectionHighlightConfig): CSSProperties;

Get list of all loaded fonts

declare function getLoadedFonts(): string[];

Get selection rectangles with merging applied

declare function getMergedSelectionRects(containerElement?: HTMLElement | null): HighlightRect[];

Check if all required variables have values

declare function getMissingVariables(tags: string[], variables: Record<string, string>): string[];
fn

getNavigationShortcutDescriptions

packages/core/src/utils/keyboardNavigation.ts:696

Get all navigation shortcuts with descriptions

declare function getNavigationShortcutDescriptions(): Array<{
    action: string;
    shortcut: string;
}>;

Get the selected text

declare function getSelectedText(): string;

Get the bounding rect of the current selection

declare function getSelectionBoundingRect(): DOMRect | null;

Get the current selection info

declare function getSelectionInfo(): {
    node: Node;
    offset: number;
    anchorNode: Node | null;
    anchorOffset: number;
    focusNode: Node | null;
    focusOffset: number;
    isCollapsed: boolean;
    text: string;
} | null;

Get all selection rectangles from the current DOM selection

Uses getClientRects() to get accurate rectangles even when selection spans multiple inline elements.

declare function getSelectionRects(containerElement?: HTMLElement | null): HighlightRect[];

Get all template tags in a document without processing

declare function getTemplateTags(buffer: ArrayBuffer): string[];

Compute a single tinted or shaded hex color from a base color.

declare function getThemeTintShadeHex(baseHex: string, type: 'tint' | 'shade', fraction: number): string;

Get the word at a position in text

declare function getWordAt(text: string, position: number): string;

Get the word at the current cursor position

declare function getWordAtCursor(): string | null;

Convert half-points to pixels (at 96 DPI)

Half-points are commonly used for font sizes in OOXML (w:sz).

declare function halfPointsToPixels(halfPoints: number): number;

Convert half-points to points

declare function halfPointsToPoints(halfPoints: number): number;

Handle click event for multi-click detection. Call this in your click handler. Returns the click count (1 = single, 2 = double, 3 = triple).

declare function handleClickForMultiClick(event: MouseEvent): number;

Handle a keyboard navigation event Returns true if the event was handled

declare function handleNavigationKey(event: KeyboardEvent, options?: {
    onDocumentStart?: () => void;
    onDocumentEnd?: () => void;
}): boolean;

Handle paste event

declare function handlePasteEvent(event: ClipboardEvent, options?: ClipboardOptions): ParsedClipboardContent | null;

Check if there is an active text selection (not collapsed)

declare function hasActiveSelection(): boolean;

Check if a paragraph has pageBreakBefore

declare function hasPageBreakBefore(paragraph: Paragraph): boolean;

Create a selection highlight for a specific text range

This is useful for find/replace highlighting, AI action previews, etc.

declare function highlightTextRange(_containerElement: HTMLElement, startNode: Node, startOffset: number, endNode: Node, endOffset: number): Range | null;

Convert HTML to runs

declare function htmlToRuns(html: string, plainTextFallback: string): Run[];

Inject selection highlight CSS into document

declare function injectSelectionStyles(config?: SelectionHighlightConfig): void;

Insert a horizontal rule at a position in the document

declare function insertHorizontalRule(doc: Document, position: InsertPosition): Document;

Insert a page break at a position in the document This inserts a new paragraph with pageBreakBefore: true

declare function insertPageBreak(doc: Document, position: InsertPosition): Document;

Check if a color is effectively black

declare function isBlack(color: ColorValue | undefined | null, theme: Theme | null | undefined): boolean;

Check if content is any type of break

declare function isBreakContent(content: RunContent): content is BreakContent;

Check if content is a column break

declare function isColumnBreak(content: RunContent): boolean;

Check if HTML is from our editor

declare function isEditorHtml(html: string): boolean;

Check if a font is loaded

declare function isFontLoaded(fontFamily: string): boolean;

Check if content is a line break

declare function isLineBreak(content: RunContent): boolean;

Check if any fonts are currently loading

declare function isLoading(): boolean;

Check if an event is a navigation key event

declare function isNavigationKey(event: KeyboardEvent): boolean;

Check if content is a page break

declare function isPageBreak(content: RunContent): boolean;

Check if a character is a punctuation character

declare function isPunctuation(char: string): boolean;

Check if selection is backwards (focus before anchor)

declare function isSelectionBackwards(): boolean;

Check if selection is within a specific element

declare function isSelectionWithin(element: HTMLElement): boolean;

Check if a color is effectively white

declare function isWhite(color: ColorValue | undefined | null, theme: Theme | null | undefined): boolean;

Check if a character is whitespace

declare function isWhitespace(char: string): boolean;

Check if a character is a word character (letter, digit, or underscore)

declare function isWordCharacter(char: string): boolean;

Check if HTML is from Microsoft Word

declare function isWordHtml(html: string): boolean;

Lighten a color by a percentage

declare function lightenColor(color: ColorValue | undefined | null, theme: Theme | null | undefined, percent: number): string;

Extract fonts from a document and load them from Google Fonts

declare function loadDocumentFonts(document: unknown): Promise<void>;

Load a font from Google Fonts

declare function loadFont(fontFamily: string, options?: {
    weights?: number[];
    styles?: ('normal' | 'italic')[];
}): Promise<boolean>;

Load a font from a raw buffer (e.g., embedded in DOCX)

declare function loadFontFromBuffer(fontFamily: string, buffer: ArrayBuffer, options?: {
    weight?: number | string;
    style?: 'normal' | 'italic';
}): Promise<boolean>;

Load multiple fonts from Google Fonts

declare function loadFonts(families: string[], options?: {
    weights?: number[];
    styles?: ('normal' | 'italic')[];
}): Promise<void>;

Load multiple fonts with automatic mapping to Google Fonts equivalents

declare function loadFontsWithMapping(families: string[]): Promise<void>;

Load a font, automatically mapping to Google Fonts equivalent if needed. If the font needs mapping, also creates a CSS alias so the original font name works in stylesheets.

declare function loadFontWithMapping(fontFamily: string): Promise<boolean>;

Check if a keyboard event matches a shortcut definition

declare function matchesShortcut(event: KeyboardEvent, shortcut: KeyboardShortcut): boolean;

Merge adjacent or overlapping rectangles

This reduces the number of highlight elements needed and creates a cleaner visual appearance.

declare function mergeAdjacentRects(rects: HighlightRect[], tolerance?: number): HighlightRect[];

Merge multiple CSSProperties objects

Later objects override earlier ones for conflicting properties.

declare function mergeStyles(...styles: (CSSProperties$1 | undefined | null)[]): CSSProperties$1;

Move selection by word in a text node

declare function moveByWord(direction: 'left' | 'right', extend?: boolean): boolean;

Move to start/end of line

declare function moveToLineEdge(edge: 'start' | 'end', extend?: boolean): boolean;

Normalize selection to always be forward (start before end)

declare function normalizeSelectionDirection(): void;

Register a callback to be notified when fonts are loaded

declare function onFontsLoaded(callback: (fonts: string[]) => void): () => void;
fn

paragraphsToClipboardContent

packages/core/src/utils/clipboard.ts:218

Convert paragraphs to clipboard content.

declare function paragraphsToClipboardContent(paragraphs: Paragraph[], includeFormatting?: boolean, theme?: Theme | null): ClipboardContent;

Convert ParagraphFormatting to CSS properties

declare function paragraphToStyle(formatting: ParagraphFormatting | undefined | null, theme?: Theme | null): CSSProperties$1;

Parse HTML from clipboard

declare function parseClipboardHtml(html: string, plainText: string, cleanWordFormatting?: boolean): ParsedClipboardContent;

Parse a color string (various formats) to ColorValue

declare function parseColorString(colorString: string | undefined): ColorValue | undefined;

Parse a keyboard event into a navigation action

declare function parseNavigationAction(event: KeyboardEvent): NavigationAction | null;

Convert pixels to EMUs. EMU coordinates in OOXML are integer-typed (xs:long); rounding here keeps floating-point drift (e.g. 52 px → 495299.99999999994) out of the document.

declare function pixelsToEmu(px: number): number;

Convert pixels to twips

declare function pixelsToTwips(px: number): number;

Convert points to half-points

declare function pointsToHalfPoints(points: number): number;

Convert points to pixels (at 96 DPI)

1 inch = 72 points = 96 pixels → 1 point = 96/72 pixels = 4/3 pixels

declare function pointsToPixels(points: number): number;

Preload a list of common document fonts

This preloads fonts commonly used in DOCX documents that have Google Fonts equivalents.

declare function preloadCommonFonts(): Promise<void>;

Preview what the document will look like after processing Returns the document text with variables replaced (for preview purposes)

declare function previewTemplate(buffer: ArrayBuffer, variables: Record<string, string>): string;

Process a DOCX template with variable substitution

declare function processTemplate(buffer: ArrayBuffer, variables: Record<string, string>, options?: ProcessTemplateOptions): ArrayBuffer;

Process template with conditional sections Supports #if, #unless, #each loops

declare function processTemplateAdvanced(buffer: ArrayBuffer, data: Record<string, unknown>, options?: ProcessTemplateOptions): ArrayBuffer;

Process template and trigger download

declare function processTemplateAndDownload(buffer: ArrayBuffer, variables: Record<string, string>, filename?: string, options?: ProcessTemplateOptions): void;

Process template and return as Blob

declare function processTemplateAsBlob(buffer: ArrayBuffer, variables: Record<string, string>, options?: ProcessTemplateOptions): Blob;

Process template with detailed result

declare function processTemplateDetailed(buffer: ArrayBuffer, variables: Record<string, string>, options?: ProcessTemplateOptions): ProcessTemplateResult;

Read the first selected file out of an `<input type="file">` change event, return its ArrayBuffer + a stem-form name. Always resets `input.value` so re-selecting the same file in the same picker fires the next `change` event.

declare function readDocxFileFromInput(event: Event): Promise<ReadDocxFileResult | null>;

Read content from clipboard

declare function readFromClipboard(options?: ClipboardOptions): Promise<ParsedClipboardContent | null>;

Redistribute column widths when splitting a cell's column span.

declare function redistributeColumnWidths(existing: number[], startCol: number, currentSpan: number, targetSpan: number): number[];

Remove a page break at a specific position

declare function removePageBreak(doc: Document, position: InsertPosition): Document;

Remove injected selection styles

declare function removeSelectionStyles(): void;

Resolve a ColorValue to a CSS color string

declare function resolveColor(color: ColorValue | undefined | null, theme: Theme | null | undefined, defaultColor?: string): string;

Resolve any ColorValue (text, fill/shading, border, underline) to a 6-char uppercase hex string — or `undefined` if transparent/unset/unresolvable.

Shared display-side resolver. Prefer this over reading `.rgb` directly so that `themeColor` + `themeTint`/`themeShade` are honored consistently across all render paths (PM attrs, layout-bridge, clipboard HTML, toolbar swatches).

When a themed color is present but `theme` is null/undefined, falls back to `color.rgb` if Word wrote one for compat; otherwise returns `undefined`.

declare function resolveColorToHex(color: ColorValue | undefined | null, theme: Theme | null | undefined): string | undefined;

Resolve a highlight color name to CSS

declare function resolveHighlightColor(highlight: string | undefined): string;

Resolve a highlight color value to a CSS-ready string. Tries OOXML named highlight first, then ensures hex prefix.

declare function resolveHighlightToCss(value: string): string;

Resolve a shading fill or pattern color to CSS

declare function resolveShadingColor(color: ColorValue | undefined | null, theme: Theme | null | undefined): string;

Convert ShadingProperties to background color

declare function resolveShadingFill(shading: ShadingProperties | undefined | null, theme?: Theme | null): string;

Round a pixel value to avoid sub-pixel rendering issues

declare function roundPixels(px: number, decimalPlaces?: number): number;

Convert runs to clipboard content (HTML and plain text).

declare function runsToClipboardContent(runs: Run[], includeFormatting?: boolean, theme?: Theme | null): ClipboardContent;

Get CSS for page/section container

declare function sectionToStyle(sectionProps: {
    pageWidth?: number;
    pageHeight?: number;
    marginTop?: number;
    marginBottom?: number;
    marginLeft?: number;
    marginRight?: number;
    background?: {
        color?: {
            rgb?: string;
            themeColor?: string;
        };
    };
} | undefined | null, theme?: Theme | null): CSSProperties$1;

Select the entire paragraph containing the current selection. Looks for the nearest element with [data-paragraph-index] attribute.

declare function selectParagraphAtCursor(): boolean;

Select a text range programmatically

declare function selectRange(range: Range): void;

Select a word at the current cursor position using the browser's native APIs. This works reliably across different browsers and handles contentEditable well.

declare function selectWordAtCursor(): boolean;

Select a word in a specific text node at the given offset

declare function selectWordInTextNode(textNode: Text, offset: number): boolean;

Set the selection to a specific position

declare function setSelectionPosition(node: Node, offset: number): void;
declare function sumColumnWidths(widths: number[], start: number, span: number): number;

Get CSS for a table cell based on formatting

declare function tableCellToStyle(formatting: {
    verticalAlign?: 'top' | 'center' | 'bottom';
    textDirection?: string;
    shading?: ShadingProperties;
    borders?: {
        top?: BorderSpec;
        bottom?: BorderSpec;
        left?: BorderSpec;
        right?: BorderSpec;
    };
    margins?: {
        top?: {
            value: number;
            type: string;
        };
        bottom?: {
            value: number;
            type: string;
        };
        left?: {
            value: number;
            type: string;
        };
        right?: {
            value: number;
            type: string;
        };
    };
} | undefined | null, theme?: Theme | null): CSSProperties$1;

Convert TextFormatting to CSS properties for a run/span

declare function textToStyle(formatting: TextFormatting | undefined | null, theme?: Theme | null): CSSProperties$1;

Normalize any [DocxInput](DocxInput) into an `ArrayBuffer` for internal use.

declare function toArrayBuffer(input: DocxInput): Promise<ArrayBuffer>;

Convert twips to EMUs

declare function twipsToEmu(twips: number): number;

Convert twips to pixels (at 96 DPI)

1 inch = 1440 twips = 96 pixels → 1 twip = 96/1440 pixels = 1/15 pixels

declare function twipsToPixels(twips: number): number;

Validate that a document is a valid docxtemplater template

declare function validateTemplate(buffer: ArrayBuffer): {
    valid: boolean;
    errors: TemplateError[];
    tags: string[];
};

Write content to clipboard

declare function writeToClipboard(content: ClipboardContent): Promise<boolean>;

Interfaces(20)

A cell's position and span within the logical grid.

interface CellAnchor<T>
MemberTypeSummary
colnumber
colspannumber
dataTOpaque payload — the caller's cell type (PMNode, TableCell, etc.)
rownumber
rowspannumber

Clipboard content format

interface ClipboardContent
MemberTypeSummary
htmlstringHTML representation
internal?stringInternal format (JSON) for preserving full formatting
plainTextstringPlain text representation

Options for clipboard operations

interface ClipboardOptions
MemberTypeSummary
cleanWordFormatting?booleanWhether to clean Word-specific formatting
includeFormatting?booleanWhether to include formatting in copy
onError?(error: Error) => voidCallback for handling errors
theme?Theme | nullDocument theme — required to resolve themed text/shading colors in HTML.
interface

CreateEmptyDocumentOptions

packages/core/src/utils/createDocument.ts:220

Options for creating an empty document

interface CreateEmptyDocumentOptions
MemberTypeSummary
initialText?stringInitial text content (default: empty string)
marginBottom?numberBottom margin in twips (default: 1440 = 1 inch)
marginLeft?numberLeft margin in twips (default: 1440 = 1 inch)
marginRight?numberRight margin in twips (default: 1440 = 1 inch)
marginTop?numberTop margin in twips (default: 1440 = 1 inch)
orientation?'portrait' | 'landscape'Page orientation (default: 'portrait')
pageHeight?numberPage height in twips (default: 15840 = 11 inches)
pageWidth?numberPage width in twips (default: 12240 = 8.5 inches)

Information about a heading found in the document.

interface HeadingInfo
MemberTypeSummary
levelnumberOutline level (0 = Heading 1, 1 = Heading 2, etc.)
pmPosnumberProseMirror document position of the paragraph node
textstringThe text content of the heading

Highlight rectangle representing a selected region

interface HighlightRect
MemberTypeSummary
heightnumberHeight in pixels
leftnumberLeft position in pixels
topnumberTop position in pixels
widthnumberWidth in pixels
interface

InsertPosition_2

Insert position in the document

interface InsertPosition
MemberTypeSummary
offset?numberCharacter offset within the run (optional)
paragraphIndexnumberParagraph index in the document body
runIndex?numberRun index within the paragraph (optional)

Keyboard shortcut definition

interface KeyboardShortcut
MemberTypeSummary
altKey?boolean
ctrlKey?boolean
keystring
metaKey?boolean
shiftKey?boolean
interface

ParsedClipboardContent

packages/core/src/utils/clipboard.ts:33

Parsed clipboard content

interface ParsedClipboardContent
MemberTypeSummary
fromEditorbooleanWhether content came from our editor
fromWordbooleanWhether content came from Word
plainTextstringOriginal plain text
runsRun[]Runs parsed from clipboard

Options for template processing

interface ProcessTemplateOptions
MemberTypeSummary
delimiters?{ start?: string; end?: string; }Delimiter settings
linebreaks?booleanLine breaks: keep raw n or convert to w:br
nullGetter?'keep' | 'empty' | 'error'How to handle undefined variables
parser?(tag: string) => { get: (scope: Record<string, unknown>) => unknown; }Custom parser for variable names

Result of template processing

interface ProcessTemplateResult
MemberTypeSummary
bufferArrayBufferThe processed document buffer
replacedVariablesstring[]Variables that were found and replaced
unreplacedVariablesstring[]Variables that were not replaced (no value provided)
warningsstring[]Any warnings during processing

Shared file-input → docx-buffer reader.

React (DocxEditor.tsx `handleDocxFileChange`) and Vue (DocxEditor.vue `handleDocxFileChange`) had byte-equivalent `await file.arrayBuffer()` + `name.replace(/\.docx$/i, '')` boilerplate around their hidden file inputs. This helper folds the common steps into one place so the two adapters can never drift on filename normalization or on the "reset input.value so re-picking the same file fires `change` again" detail.

Returns `null` when the user cancelled the picker (no file chosen).

interface ReadDocxFileResult
MemberTypeSummary
bufferArrayBufferArrayBuffer ready to feed into `loadBuffer` / `parseDocx`.
namestringFile name with the trailing `.docx` extension stripped.

Selection highlight configuration

interface SelectionHighlightConfig
MemberTypeSummary
backgroundColorstringBackground color for selection
borderColor?stringOptional border color for selection
borderRadius?numberOptional border radius
mixBlendMode?CSSProperties['mixBlendMode']Mix blend mode
opacity?numberOpacity for highlight
zIndex?numberZ-index for overlay

Selection range in document coordinates

interface SelectionRange
MemberTypeSummary
end{ paragraphIndex: number; contentIndex: number; offset: number; }End position
start{ paragraphIndex: number; contentIndex: number; offset: number; }Start position

Result of `computeSplitLayout`.

interface SplitLayoutResult<T>
MemberTypeSummary
anchorsCellAnchor<T>[]All anchors after the split (neighbors adjusted + new split cells).
deltaColsnumber
deltaRowsnumber
newRowCountnumber

Parameters describing the split target.

interface SplitTarget
MemberTypeSummary
colnumber
colspannumber
rownumber
rowspannumber

Error details from template processing

interface TemplateError
MemberTypeSummary
messagestringError message
originalError?ErrorOriginal error
type'parse' | 'render' | 'undefined' | 'unknown'Error type
variable?stringVariable name that caused the error (if applicable)

Theme color matrix cell

interface ThemeMatrixCell
MemberTypeSummary
hexstringResolved hex color (6 chars, no #)
labelstringHuman-readable label (e.g., "Accent 1, Lighter 60%")
shade?stringShade hex modifier if applicable (e.g., "BF")
themeSlotThemeColorSlotTheme color slot
tint?stringTint hex modifier if applicable (e.g., "CC")

Word selection result

interface WordSelectionResult
MemberTypeSummary
endIndexnumberEnd index in the text (exclusive)
startIndexnumberStart index in the text (inclusive)
wordstringThe selected word

Type aliases(3)

Any binary representation of a DOCX file that the editor can consume.

- `ArrayBuffer` — from `FileReader.readAsArrayBuffer()` or `fetch().arrayBuffer()` - `Uint8Array` — from Node.js `fs.readFile()` or streaming APIs - `Blob` — from drag-and-drop or `<input type="file">` - `File` — subclass of Blob, from `<input type="file">`

type DocxInput = ArrayBuffer | Uint8Array | Blob | File;

Variables(13)

Standard clipboard MIME types

CLIPBOARD_TYPES: {
    readonly HTML: "text/html";
    readonly PLAIN: "text/plain";
}

Default selection highlight style (matches Word/Google Docs)

DEFAULT_SELECTION_STYLE: SelectionHighlightConfig

Mapping from common Office/system fonts to Google Fonts equivalents

Google Fonts doesn't have exact matches for many Microsoft fonts, but these are close alternatives that work well for document rendering.

FONT_MAPPING: Record<string, string>
const

HIGH_CONTRAST_SELECTION_STYLE

packages/core/src/utils/selectionHighlight.ts:90

High contrast selection style

HIGH_CONTRAST_SELECTION_STYLE: SelectionHighlightConfig
const

INTERNAL_CLIPBOARD_TYPE

packages/core/src/utils/clipboard.ts:65

Custom MIME type for internal clipboard format

INTERNAL_CLIPBOARD_TYPE = "application/x-docx-editor"
MIN_CARD_GAP = 8

Pixels per inch at standard DPI

PIXELS_PER_INCH = 96

Selection highlight CSS custom properties

SELECTION_CSS_VARS: {
    readonly backgroundColor: "--docx-selection-bg";
    readonly borderColor: "--docx-selection-border";
    readonly textColor: "--docx-selection-text";
}

Twips per inch (1 inch = 1440 twips)

TWIPS_PER_INCH = 1440