@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)
areSelectionStylesInjected
Check if selection styles are injected
declare function areSelectionStylesInjected(): boolean;blendColors
Blend two colors together
declare function blendColors(color1: ColorValue | undefined | null, color2: ColorValue | undefined | null, ratio: number, theme: Theme | null | undefined): string;borderToStyle
Convert a BorderSpec to CSS border properties
declare function borderToStyle(border: BorderSpec | undefined | null, side?: 'Top' | 'Bottom' | 'Left' | 'Right' | '', theme?: Theme | null): CSSProperties$1;buildAnchorMaps
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>>;
};canRenderFont
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;cleanWordHtml
Clean Microsoft Word HTML
declare function cleanWordHtml(html: string): string;clearSelection
Clear the current selection
declare function clearSelection(): void;collectHeadings
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[];colorsEqual
Check if two colors are equal
declare function colorsEqual(color1: ColorValue | undefined | null, color2: ColorValue | undefined | null, theme: Theme | null | undefined): boolean;computeSplitDialogDefaults
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;
};computeSplitLayout
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>;copyParagraphs
Copy paragraphs to clipboard with formatting
declare function copyParagraphs(paragraphs: Paragraph[], options?: ClipboardOptions): Promise<boolean>;copyRuns
Copy runs to clipboard with formatting
declare function copyRuns(runs: Run[], options?: ClipboardOptions): Promise<boolean>;countPageBreaks
Count page breaks in a document
declare function countPageBreaks(doc: Document): number;createClipboardHandlers
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>;
};createColumnBreak
Create a column break content element
declare function createColumnBreak(): BreakContent;createDocumentWithText
Create a document with a single paragraph containing the given text
declare function createDocumentWithText(text: string, options?: Omit<CreateEmptyDocumentOptions, 'initialText'>): Document;createDoubleClickWordSelector
Create a double-click handler that selects words. Returns a function that should be called on dblclick events.
declare function createDoubleClickWordSelector(): (event: MouseEvent) => void;createEmptyDocument
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!'
});
```createHorizontalRule
Create a horizontal rule paragraph Uses a paragraph with bottom border to simulate horizontal rule
declare function createHorizontalRule(): Paragraph;createLineBreak
Create a text wrapping break (line break)
declare function createLineBreak(clear?: 'none' | 'left' | 'right' | 'all'): BreakContent;createPageBreak
Create a page break content element
declare function createPageBreak(): BreakContent;createPageBreakParagraph
Create an empty paragraph with a page break before it
declare function createPageBreakParagraph(): Paragraph;createPageBreakRun
Create a run containing a page break
declare function createPageBreakRun(): Run;createRgbColor
Create a ColorValue from RGB hex
declare function createRgbColor(hex: string): ColorValue;createSelectionChangeHandler
Create a selection change handler that updates highlight rects
declare function createSelectionChangeHandler(containerElement: HTMLElement | null, onRectsChange: (rects: HighlightRect[]) => void, merge?: boolean): () => void;createTemplateProcessor
Create a template processor with preset options
declare function createTemplateProcessor(defaultOptions?: ProcessTemplateOptions): (buffer: ArrayBuffer, variables: Record<string, string>) => ArrayBuffer;createThemeColor
Create a ColorValue from theme color reference
declare function createThemeColor(themeColor: ThemeColorSlot, tint?: number, shade?: number): ColorValue;createTripleClickParagraphSelector
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;darkenColor
Darken a color by a percentage
declare function darkenColor(color: ColorValue | undefined | null, theme: Theme | null | undefined, percent: number): string;describeShortcut
Get a human-readable description of a shortcut
declare function describeShortcut(shortcut: KeyboardShortcut): string;eighthsToPixels
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;emuToPixels
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;emuToTwips
Convert EMUs to twips
declare function emuToTwips(emu: number): number;ensureHexPrefix
Ensure a hex color string has a '#' prefix.
declare function ensureHexPrefix(hex: string): string;expandSelectionToWord
Expand selection to word boundaries Used for double-click word selection
declare function expandSelectionToWord(): boolean;expandSelectionToWordBoundaries
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;extendSelectionTo
Extend selection to a specific position
declare function extendSelectionTo(node: Node, offset: number): void;extractFontsFromDocument
Extract all font families used in a document
Uses loose typing to handle any document-like structure.
declare function extractFontsFromDocument(document: unknown): Set<string>;findNextWordStart
Find the next word start (for Ctrl+Right navigation)
declare function findNextWordStart(text: string, position: number): number;findPageBreaks
Find all page break positions in a document
declare function findPageBreaks(doc: Document): InsertPosition[];findPreviousWordStart
Find the previous word start (for Ctrl+Left navigation)
declare function findPreviousWordStart(text: string, position: number): number;findVisualLineEnd
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;findVisualLineStart
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;findWordAt
Find the word at a position and return detailed info
declare function findWordAt(text: string, position: number): WordSelectionResult;findWordBoundaries
Find word boundaries around a position in text Returns [startIndex, endIndex] inclusive start, exclusive end
declare function findWordBoundaries(text: string, position: number): [number, number];findWordEnd
Find the end of the current or next word
declare function findWordEnd(text: string, position: number): number;findWordStart
Find the start of the current or previous word
declare function findWordStart(text: string, position: number): number;formatPx
Format a pixel value as CSS string
declare function formatPx(px: number): string;generateSelectionCSS
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;generateThemeTintShadeMatrix
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[][];getClipboardImageFiles
Extract image files from clipboard data (if present).
declare function getClipboardImageFiles(clipboardData: DataTransfer | null): File[];getContrastingColor
Get contrasting text color for a background
declare function getContrastingColor(backgroundColor: ColorValue | undefined | null, theme: Theme | null | undefined): string;getGoogleFontEquivalent
Get the Google Fonts equivalent for a font name
declare function getGoogleFontEquivalent(fontName: string): string;getHighlightRectStyle
Generate CSS styles for a highlight rectangle
declare function getHighlightRectStyle(rect: HighlightRect, config?: SelectionHighlightConfig): CSSProperties;getLoadedFonts
Get list of all loaded fonts
declare function getLoadedFonts(): string[];getMergedSelectionRects
Get selection rectangles with merging applied
declare function getMergedSelectionRects(containerElement?: HTMLElement | null): HighlightRect[];getMissingVariables
Check if all required variables have values
declare function getMissingVariables(tags: string[], variables: Record<string, string>): string[];Get the selected text
declare function getSelectedText(): string;getSelectionBoundingRect
Get the bounding rect of the current selection
declare function getSelectionBoundingRect(): DOMRect | null;getSelectionInfo
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;getSelectionRects
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[];getThemeTintShadeHex
Compute a single tinted or shaded hex color from a base color.
declare function getThemeTintShadeHex(baseHex: string, type: 'tint' | 'shade', fraction: number): string;getWordAt
Get the word at a position in text
declare function getWordAt(text: string, position: number): string;getWordAtCursor
Get the word at the current cursor position
declare function getWordAtCursor(): string | null;halfPointsToPixels
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;halfPointsToPoints
Convert half-points to points
declare function halfPointsToPoints(halfPoints: number): number;handleClickForMultiClick
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;handlePasteEvent
Handle paste event
declare function handlePasteEvent(event: ClipboardEvent, options?: ClipboardOptions): ParsedClipboardContent | null;hasActiveSelection
Check if there is an active text selection (not collapsed)
declare function hasActiveSelection(): boolean;hasPageBreakBefore
Check if a paragraph has pageBreakBefore
declare function hasPageBreakBefore(paragraph: Paragraph): boolean;highlightTextRange
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;htmlToRuns
Convert HTML to runs
declare function htmlToRuns(html: string, plainTextFallback: string): Run[];injectSelectionStyles
Inject selection highlight CSS into document
declare function injectSelectionStyles(config?: SelectionHighlightConfig): void;insertHorizontalRule
Insert a horizontal rule at a position in the document
declare function insertHorizontalRule(doc: Document, position: InsertPosition): Document;insertPageBreak
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;isBreakContent
Check if content is any type of break
declare function isBreakContent(content: RunContent): content is BreakContent;isColumnBreak
Check if content is a column break
declare function isColumnBreak(content: RunContent): boolean;isEditorHtml
Check if HTML is from our editor
declare function isEditorHtml(html: string): boolean;isFontLoaded
Check if a font is loaded
declare function isFontLoaded(fontFamily: string): boolean;isLineBreak
Check if content is a line break
declare function isLineBreak(content: RunContent): boolean;isLoading
Check if any fonts are currently loading
declare function isLoading(): boolean;isPageBreak
Check if content is a page break
declare function isPageBreak(content: RunContent): boolean;isPunctuation
Check if a character is a punctuation character
declare function isPunctuation(char: string): boolean;isSelectionBackwards
Check if selection is backwards (focus before anchor)
declare function isSelectionBackwards(): boolean;isSelectionWithin
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;isWhitespace
Check if a character is whitespace
declare function isWhitespace(char: string): boolean;isWordCharacter
Check if a character is a word character (letter, digit, or underscore)
declare function isWordCharacter(char: string): boolean;isWordHtml
Check if HTML is from Microsoft Word
declare function isWordHtml(html: string): boolean;lightenColor
Lighten a color by a percentage
declare function lightenColor(color: ColorValue | undefined | null, theme: Theme | null | undefined, percent: number): string;loadDocumentFonts
Extract fonts from a document and load them from Google Fonts
declare function loadDocumentFonts(document: unknown): Promise<void>;loadFont
Load a font from Google Fonts
declare function loadFont(fontFamily: string, options?: {
weights?: number[];
styles?: ('normal' | 'italic')[];
}): Promise<boolean>;loadFontFromBuffer
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>;loadFonts
Load multiple fonts from Google Fonts
declare function loadFonts(families: string[], options?: {
weights?: number[];
styles?: ('normal' | 'italic')[];
}): Promise<void>;loadFontsWithMapping
Load multiple fonts with automatic mapping to Google Fonts equivalents
declare function loadFontsWithMapping(families: string[]): Promise<void>;loadFontWithMapping
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>;matchesShortcut
Check if a keyboard event matches a shortcut definition
declare function matchesShortcut(event: KeyboardEvent, shortcut: KeyboardShortcut): boolean;mergeAdjacentRects
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[];mergeStyles
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;moveToLineEdge
Move to start/end of line
declare function moveToLineEdge(edge: 'start' | 'end', extend?: boolean): boolean;normalizeSelectionDirection
Normalize selection to always be forward (start before end)
declare function normalizeSelectionDirection(): void;onFontsLoaded
Register a callback to be notified when fonts are loaded
declare function onFontsLoaded(callback: (fonts: string[]) => void): () => void;paragraphsToClipboardContent
Convert paragraphs to clipboard content.
declare function paragraphsToClipboardContent(paragraphs: Paragraph[], includeFormatting?: boolean, theme?: Theme | null): ClipboardContent;paragraphToStyle
Convert ParagraphFormatting to CSS properties
declare function paragraphToStyle(formatting: ParagraphFormatting | undefined | null, theme?: Theme | null): CSSProperties$1;parseClipboardHtml
Parse HTML from clipboard
declare function parseClipboardHtml(html: string, plainText: string, cleanWordFormatting?: boolean): ParsedClipboardContent;parseColorString
Parse a color string (various formats) to ColorValue
declare function parseColorString(colorString: string | undefined): ColorValue | undefined;pixelsToEmu
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;pixelsToTwips
Convert pixels to twips
declare function pixelsToTwips(px: number): number;pointsToHalfPoints
Convert points to half-points
declare function pointsToHalfPoints(points: number): number;pointsToPixels
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;preloadCommonFonts
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>;previewTemplate
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;processTemplate
Process a DOCX template with variable substitution
declare function processTemplate(buffer: ArrayBuffer, variables: Record<string, string>, options?: ProcessTemplateOptions): ArrayBuffer;processTemplateAdvanced
Process template with conditional sections Supports #if, #unless, #each loops
declare function processTemplateAdvanced(buffer: ArrayBuffer, data: Record<string, unknown>, options?: ProcessTemplateOptions): ArrayBuffer;processTemplateAndDownload
Process template and trigger download
declare function processTemplateAndDownload(buffer: ArrayBuffer, variables: Record<string, string>, filename?: string, options?: ProcessTemplateOptions): void;processTemplateAsBlob
Process template and return as Blob
declare function processTemplateAsBlob(buffer: ArrayBuffer, variables: Record<string, string>, options?: ProcessTemplateOptions): Blob;processTemplateDetailed
Process template with detailed result
declare function processTemplateDetailed(buffer: ArrayBuffer, variables: Record<string, string>, options?: ProcessTemplateOptions): ProcessTemplateResult;readDocxFileFromInput
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>;readFromClipboard
Read content from clipboard
declare function readFromClipboard(options?: ClipboardOptions): Promise<ParsedClipboardContent | null>;redistributeColumnWidths
Redistribute column widths when splitting a cell's column span.
declare function redistributeColumnWidths(existing: number[], startCol: number, currentSpan: number, targetSpan: number): number[];removePageBreak
Remove a page break at a specific position
declare function removePageBreak(doc: Document, position: InsertPosition): Document;removeSelectionStyles
Remove injected selection styles
declare function removeSelectionStyles(): void;resolveColor
Resolve a ColorValue to a CSS color string
declare function resolveColor(color: ColorValue | undefined | null, theme: Theme | null | undefined, defaultColor?: string): string;resolveColorToHex
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;resolveHighlightColor
Resolve a highlight color name to CSS
declare function resolveHighlightColor(highlight: string | undefined): string;resolveHighlightToCss
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;resolveShadingColor
Resolve a shading fill or pattern color to CSS
declare function resolveShadingColor(color: ColorValue | undefined | null, theme: Theme | null | undefined): string;resolveShadingFill
Convert ShadingProperties to background color
declare function resolveShadingFill(shading: ShadingProperties | undefined | null, theme?: Theme | null): string;roundPixels
Round a pixel value to avoid sub-pixel rendering issues
declare function roundPixels(px: number, decimalPlaces?: number): number;runsToClipboardContent
Convert runs to clipboard content (HTML and plain text).
declare function runsToClipboardContent(runs: Run[], includeFormatting?: boolean, theme?: Theme | null): ClipboardContent;sectionToStyle
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;selectParagraphAtCursor
Select the entire paragraph containing the current selection. Looks for the nearest element with [data-paragraph-index] attribute.
declare function selectParagraphAtCursor(): boolean;selectRange
Select a text range programmatically
declare function selectRange(range: Range): void;selectWordAtCursor
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;selectWordInTextNode
Select a word in a specific text node at the given offset
declare function selectWordInTextNode(textNode: Text, offset: number): boolean;setSelectionPosition
Set the selection to a specific position
declare function setSelectionPosition(node: Node, offset: number): void;sumColumnWidths
declare function sumColumnWidths(widths: number[], start: number, span: number): number;tableCellToStyle
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;textToStyle
Convert TextFormatting to CSS properties for a run/span
declare function textToStyle(formatting: TextFormatting | undefined | null, theme?: Theme | null): CSSProperties$1;toArrayBuffer
Normalize any [DocxInput](DocxInput) into an `ArrayBuffer` for internal use.
declare function toArrayBuffer(input: DocxInput): Promise<ArrayBuffer>;twipsToEmu
Convert twips to EMUs
declare function twipsToEmu(twips: number): number;twipsToPixels
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;validateTemplate
Validate that a document is a valid docxtemplater template
declare function validateTemplate(buffer: ArrayBuffer): {
valid: boolean;
errors: TemplateError[];
tags: string[];
};writeToClipboard
Write content to clipboard
declare function writeToClipboard(content: ClipboardContent): Promise<boolean>;Interfaces(20)
CellAnchor
A cell's position and span within the logical grid.
interface CellAnchor<T>| Member | Type | Summary |
|---|---|---|
| col | number | |
| colspan | number | |
| data | T | Opaque payload — the caller's cell type (PMNode, TableCell, etc.) |
| row | number | |
| rowspan | number |
ClipboardContent
Clipboard content format
interface ClipboardContent| Member | Type | Summary |
|---|---|---|
| html | string | HTML representation |
| internal? | string | Internal format (JSON) for preserving full formatting |
| plainText | string | Plain text representation |
ClipboardOptions
Options for clipboard operations
interface ClipboardOptions| Member | Type | Summary |
|---|---|---|
| cleanWordFormatting? | boolean | Whether to clean Word-specific formatting |
| includeFormatting? | boolean | Whether to include formatting in copy |
| onError? | (error: Error) => void | Callback for handling errors |
| theme? | Theme | null | Document theme — required to resolve themed text/shading colors in HTML. |
CreateEmptyDocumentOptions
Options for creating an empty document
interface CreateEmptyDocumentOptions| Member | Type | Summary |
|---|---|---|
| initialText? | string | Initial text content (default: empty string) |
| marginBottom? | number | Bottom margin in twips (default: 1440 = 1 inch) |
| marginLeft? | number | Left margin in twips (default: 1440 = 1 inch) |
| marginRight? | number | Right margin in twips (default: 1440 = 1 inch) |
| marginTop? | number | Top margin in twips (default: 1440 = 1 inch) |
| orientation? | 'portrait' | 'landscape' | Page orientation (default: 'portrait') |
| pageHeight? | number | Page height in twips (default: 15840 = 11 inches) |
| pageWidth? | number | Page width in twips (default: 12240 = 8.5 inches) |
HeadingInfo
Information about a heading found in the document.
interface HeadingInfo| Member | Type | Summary |
|---|---|---|
| level | number | Outline level (0 = Heading 1, 1 = Heading 2, etc.) |
| pmPos | number | ProseMirror document position of the paragraph node |
| text | string | The text content of the heading |
HighlightRect
Highlight rectangle representing a selected region
interface HighlightRect| Member | Type | Summary |
|---|---|---|
| height | number | Height in pixels |
| left | number | Left position in pixels |
| top | number | Top position in pixels |
| width | number | Width in pixels |
InsertPosition_2
Insert position in the document
interface InsertPosition| Member | Type | Summary |
|---|---|---|
| offset? | number | Character offset within the run (optional) |
| paragraphIndex | number | Paragraph index in the document body |
| runIndex? | number | Run index within the paragraph (optional) |
KeyboardShortcut
Keyboard shortcut definition
interface KeyboardShortcut| Member | Type | Summary |
|---|---|---|
| altKey? | boolean | |
| ctrlKey? | boolean | |
| key | string | |
| metaKey? | boolean | |
| shiftKey? | boolean |
ParsedClipboardContent
Parsed clipboard content
interface ParsedClipboardContent| Member | Type | Summary |
|---|---|---|
| fromEditor | boolean | Whether content came from our editor |
| fromWord | boolean | Whether content came from Word |
| plainText | string | Original plain text |
| runs | Run[] | Runs parsed from clipboard |
ProcessTemplateOptions
Options for template processing
interface ProcessTemplateOptions| Member | Type | Summary |
|---|---|---|
| delimiters? | {
start?: string;
end?: string;
} | Delimiter settings |
| linebreaks? | boolean | Line 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 |
ProcessTemplateResult
Result of template processing
interface ProcessTemplateResult| Member | Type | Summary |
|---|---|---|
| buffer | ArrayBuffer | The processed document buffer |
| replacedVariables | string[] | Variables that were found and replaced |
| unreplacedVariables | string[] | Variables that were not replaced (no value provided) |
| warnings | string[] | Any warnings during processing |
ReadDocxFileResult
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| Member | Type | Summary |
|---|---|---|
| buffer | ArrayBuffer | ArrayBuffer ready to feed into `loadBuffer` / `parseDocx`. |
| name | string | File name with the trailing `.docx` extension stripped. |
SelectionHighlightConfig
Selection highlight configuration
interface SelectionHighlightConfig| Member | Type | Summary |
|---|---|---|
| backgroundColor | string | Background color for selection |
| borderColor? | string | Optional border color for selection |
| borderRadius? | number | Optional border radius |
| mixBlendMode? | CSSProperties['mixBlendMode'] | Mix blend mode |
| opacity? | number | Opacity for highlight |
| zIndex? | number | Z-index for overlay |
SelectionRange
Selection range in document coordinates
interface SelectionRange| Member | Type | Summary |
|---|---|---|
| end | {
paragraphIndex: number;
contentIndex: number;
offset: number;
} | End position |
| start | {
paragraphIndex: number;
contentIndex: number;
offset: number;
} | Start position |
SplitLayoutResult
Result of `computeSplitLayout`.
interface SplitLayoutResult<T>| Member | Type | Summary |
|---|---|---|
| anchors | CellAnchor<T>[] | All anchors after the split (neighbors adjusted + new split cells). |
| deltaCols | number | |
| deltaRows | number | |
| newRowCount | number |
SplitTarget
Parameters describing the split target.
interface SplitTarget| Member | Type | Summary |
|---|---|---|
| col | number | |
| colspan | number | |
| row | number | |
| rowspan | number |
TemplateError
Error details from template processing
interface TemplateError| Member | Type | Summary |
|---|---|---|
| message | string | Error message |
| originalError? | Error | Original error |
| type | 'parse' | 'render' | 'undefined' | 'unknown' | Error type |
| variable? | string | Variable name that caused the error (if applicable) |
ThemeMatrixCell
Theme color matrix cell
interface ThemeMatrixCell| Member | Type | Summary |
|---|---|---|
| hex | string | Resolved hex color (6 chars, no #) |
| label | string | Human-readable label (e.g., "Accent 1, Lighter 60%") |
| shade? | string | Shade hex modifier if applicable (e.g., "BF") |
| themeSlot | ThemeColorSlot | Theme color slot |
| tint? | string | Tint hex modifier if applicable (e.g., "CC") |
WordSelectionResult
Word selection result
interface WordSelectionResult| Member | Type | Summary |
|---|---|---|
| endIndex | number | End index in the text (exclusive) |
| startIndex | number | Start index in the text (inclusive) |
| word | string | The selected word |
Type aliases(3)
DocxInput
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)
CLIPBOARD_TYPES
Standard clipboard MIME types
CLIPBOARD_TYPES: {
readonly HTML: "text/html";
readonly PLAIN: "text/plain";
}DEFAULT_SELECTION_STYLE
Default selection highlight style (matches Word/Google Docs)
DEFAULT_SELECTION_STYLE: SelectionHighlightConfigFONT_MAPPING
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>HIGH_CONTRAST_SELECTION_STYLE
High contrast selection style
HIGH_CONTRAST_SELECTION_STYLE: SelectionHighlightConfigINTERNAL_CLIPBOARD_TYPE
Custom MIME type for internal clipboard format
INTERNAL_CLIPBOARD_TYPE = "application/x-docx-editor"MIN_CARD_GAP
MIN_CARD_GAP = 8PIXELS_PER_INCH
Pixels per inch at standard DPI
PIXELS_PER_INCH = 96SELECTION_CSS_VARS
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
Twips per inch (1 inch = 1440 twips)
TWIPS_PER_INCH = 1440