Skip to content
Document Authoring DA  API Docs v1.22.0
npmGitHub

DocAuthEditor

DocAuthEditor:

{
addVisualHighlight(location: DocumentLocation, options?: Readonly<{ color?: string; opacity?: number }>): Promise<AddVisualHighlightResult>;
getSelectionContent(options: { format: F }): SelectionContentByFormat[F] | null;
setActions(actions: Action[]): void;
setZoom(factor: number): void;
on(event: EventName, handler: DocAuthEditorEventHandler<EventName>): DocAuthEditor;
off(event: EventName, handler?: DocAuthEditorEventHandler<EventName>): DocAuthEditor;
once(event: EventName, handler: DocAuthEditorEventHandler<EventName>): DocAuthEditor;
}

The visual editor UI. Binds to a DOM element and lets users edit documents.

Create editors using createDocAuthSystem.

find: FindNamespace

The Find namespace. Searches the document and provides programmatic control over the editor’s Find bar.

FindNamespace

setCurrentDocument(doc): void

Attaches the provided document as the current document to the editor.

DocAuthDocument

void


currentDocument(): DocAuthDocument

Returns a reference to the currently attached document.

DocAuthDocument


navigateTo(location): Promise<NavigateResult>

Reveals a portable document location without changing the current selection or focus.

DocumentLocation

A location created for the current saved document.

Promise<NavigateResult>

A tagged result describing whether the location was revealed.


addVisualHighlight(location, options?): Promise<AddVisualHighlightResult>

Adds a visual highlight to a ranged portable document location.

This method does not scroll, focus, select, or change document content. The SDK removes visual highlights when the document changes; hosts can remove one sooner through the returned handle.

DocumentLocation

A ranged location created for the current saved document.

Readonly<{ color?: string; opacity?: number; }>

Optional highlight color and opacity.

Promise<AddVisualHighlightResult>

A tagged result containing a removable highlight when successful.


destroy(): void

Removes all DOM elements and releases resources held by the editor. Note: This does not release the underlying DocAuthSystem. Use DocAuthSystem.destroy after calling DocAuthEditor.destroy for a complete teardown.

void


docAuthSystem(): DocAuthSystem

Retrieves the DocAuthSystem instance this editor is bound to.

DocAuthSystem


hasActiveCursor()

>= v1.9.0Section titled “hasActiveCursor()”

hasActiveCursor(): boolean

Checks if the editor has an active cursor/insertion point. This is useful for custom actions to determine if they should be enabled.

boolean

True if cursor is active and insertion is possible, false otherwise


insertTextAtCursor()

>= v1.9.0Section titled “insertTextAtCursor()”

insertTextAtCursor(text): void

Inserts text at the current cursor position. If there’s a selection, it will be replaced with the provided text.

string

The text to insert at the cursor position

void


insertContentAtCursor()

>= v1.15.0Section titled “insertContentAtCursor()”

insertContentAtCursor(options): void

Inserts content at the current cursor position. If there’s a range selection, it will be replaced. If there is no active cursor, this is a silent no-op.

format is the same discriminator used by getSelectionContent, so a fragment captured from the editor round-trips back through this method.

InsertContentAtCursorOptions

The content to insert, discriminated by format. See InsertContentAtCursorOptions.

void

import { isUnsupportedFragmentVersionError, isDocAuthError } from '@nutrient-sdk/document-authoring';
editor.insertContentAtCursor({ content: 'hello' });
const fragment = editor.getSelectionContent({ format: 'fragment' });
if (!fragment) return;
const transformed = await sendToModel(fragment);
try {
editor.insertContentAtCursor({ format: 'fragment', content: transformed });
} catch (err) {
console.error(`Need version ${err.expected}, got ${err.actual}`);
} else if (isDocAuthError(err)) {
console.error(err.type, err.message);
}
}

getSelectionContent()

>= v1.15.0Section titled “getSelectionContent()”

getSelectionContent<F>(options): SelectionContentByFormat[F] | null

Returns the current selection in the requested format, or null if there is no range selection.

  • format: 'text' returns the selected text as a plain string.
  • format: 'fragment' returns a structured fragment object that round-trips through insertContentAtCursor with format: 'fragment'. Treat as opaque JSON-serializable data; don’t depend on its internal shape.

A collapsed cursor (zero-width caret) returns null for either format. Use hasActiveCursor to distinguish a collapsed cursor from a missing one.

F extends SelectionContentFormat

The format to read the selection in. See SelectionContentFormat.

F

SelectionContentByFormat[F] | null

The selection in the requested format, or null if no range is selected.

const text = editor.getSelectionContent({ format: 'text' });
if (text !== null) console.log('Selected:', text);
const fragment = editor.getSelectionContent({ format: 'fragment' });
if (fragment !== null) editor.insertContentAtCursor({ format: 'fragment', content: fragment });

setActions(actions): void

Set all actions (replaces any existing actions). Allows setting and executing editor actions programmatically.

Action[]

Array of actions to register

void

import { defaultActions } from '@nutrient-sdk/document-authoring';
// Register custom actions alongside default actions
editor.setActions([
...defaultActions, // Keep default actions
{
id: 'custom.insert-signature',
label: 'Insert Signature',
handler: () => {
editor.insertTextAtCursor('\n\nBest regards,\nJohn Doe');
},
shortcuts: ['Mod+Shift+S'],
},
]);

setToolbarConfig()

>= v1.9.0Section titled “setToolbarConfig()”

setToolbarConfig(config): void

Set the toolbar configuration. Use this to customize the editor’s toolbar.

ToolbarConfig

Toolbar configuration object

void

import { defaultToolbarConfig } from '@nutrient-sdk/document-authoring';
// Use default toolbar config but add a custom item
editor.setToolbarConfig({
items: [...defaultToolbarConfig.items, { type: 'action', id: 'custom', actionId: 'custom.insert-signature' }],
});
// Or create a minimal toolbar
editor.setToolbarConfig({
items: [
{ type: 'built-in', id: 'undo', builtInType: 'undo' },
{ type: 'built-in', id: 'redo', builtInType: 'redo' },
{ type: 'separator', id: 'sep-1' },
{ type: 'built-in', id: 'bold', builtInType: 'bold' },
{ type: 'built-in', id: 'italic', builtInType: 'italic' },
{ type: 'action', id: 'custom', actionId: 'custom.insert-signature' },
],
});

setEditorMode()

>= v1.13.0Section titled “setEditorMode()”

setEditorMode(mode): void

Sets the current editor mode.

DocAuthEditorMode

The editor mode to use.

void


getEditorMode()

>= v1.13.0Section titled “getEditorMode()”

getEditorMode(): DocAuthEditorMode

Returns the current editor mode.

DocAuthEditorMode


setZoom(factor): void

Sets the zoom factor of the editor view. 1 means 100%, 0.5 means 50%.

Finite values are clamped to the supported range of 0.5 to 4 (50% to 400%), the same bounds the toolbar zoom control, the view.zoom-in / view.zoom-out shortcuts, and Ctrl+wheel zoom use. Non-finite values (NaN, Infinity) throw a RangeError and leave the zoom unchanged.

The change applies synchronously: page sizes are updated before this method returns, and editor.getZoom() immediately reflects the clamped value. Zoom is presentation state only. It does not modify the document, the saved output, the selection, or undo history, and it works in every editor mode, including view.

Zoom belongs to the editor view, not the document: editor.setCurrentDocument() rebuilds the view and resets zoom to the creation-time default (100% unless the host configured otherwise). Re-apply setZoom() after swapping documents if a different zoom is wanted.

number

The zoom factor to apply, where 1 is 100%. Clamped to 0.5..4.

void

// Show the document at 50% in a narrow sidebar
editor.setZoom(0.5);
// Back to 100%
editor.setZoom(1);

RangeError when factor is not a finite number.

editor.getZoom() to read the current zoom.


getZoom(): number

Returns the current zoom factor of the editor view, where 1 means 100%.

The value reflects every way zoom can change: editor.setZoom(), the toolbar zoom control, keyboard shortcuts, and Ctrl+wheel. It is always within 0.5..4. Values set from the toolbar are exact steps such as 1.25; wheel zoom can produce arbitrary fractions.

number

const percent = Math.round(editor.getZoom() * 100);

editor.setZoom() to change the zoom.


setAuthor(name): void

Sets the author name used when creating comments, replies, and tracked changes.

string

The author name to use for new comments

void

// Set author when user logs in
editor.setAuthor('John Doe');
// Clear author when user logs out (will use localized "Anonymous")
editor.setAuthor('');

UIOptions.author for setting the initial author.


getAuthor(): string

Returns the author name used when creating comments, replies, and tracked changes.

string


enableSpellcheck()

>= v1.13.0Section titled “enableSpellcheck()”

enableSpellcheck(language): void

Enables spell checking for the given language. Returns immediately; misspelled words begin to be underlined shortly after, once the dictionary has loaded. Also works to switch from one language to another — call again with a different language at any time.

SpellcheckLanguage

The spellcheck language to activate.

void

editor.enableSpellcheck('fr-FR');
editor.enableSpellcheck('en-US');

disableSpellcheck()

>= v1.13.0Section titled “disableSpellcheck()”

disableSpellcheck(): void

Disables spell checking. Removes any misspelled-word underlines currently drawn and stops checking new edits. Safe to call when spell checking is already off.

void

editor.disableSpellcheck();

editor.enableSpellcheck() to turn spell checking on.


on<EventName>(event, handler): DocAuthEditor

Adds an event listener that will be called every time the specified event is emitted.

EventName extends keyof DocAuthDocumentEvents | "document.load" | "selection.change" | "tracked-change.lifecycle" | "comment.lifecycle"

EventName

The event name to listen for

DocAuthEditorEventHandler<EventName>

The function to call when the event is emitted

DocAuthEditor

The editor instance for method chaining

// Auto-save on content changes
editor.on('content.change', async () => {
const doc = await editor.currentDocument().saveDocument();
localStorage.setItem('draft', JSON.stringify(doc));
});
// Track document load
editor.on('document.load', () => {
console.log('Document loaded successfully');
});
// Debounced save to prevent excessive API calls
let saveTimeout;
editor.on('content.change', async () => {
clearTimeout(saveTimeout);
saveTimeout = setTimeout(async () => {
const doc = await editor.currentDocument().saveDocument();
await fetch('/api/save', {
method: 'POST',
body: JSON.stringify(doc),
});
}, 1000);
});
// Method chaining
editor.on('document.load', () => console.log('loaded')).on('content.change', () => console.log('changed'));

DocAuthEditorEvents


off<EventName>(event, handler?): DocAuthEditor

Removes an event listener. If no handler is provided, removes all listeners for the event.

EventName extends keyof DocAuthDocumentEvents | "document.load" | "selection.change" | "tracked-change.lifecycle" | "comment.lifecycle"

EventName

The event name to remove listeners from

DocAuthEditorEventHandler<EventName>

The specific handler to remove (optional)

DocAuthEditor

The editor instance for method chaining

// Remove specific handler (prevent memory leaks)
const handleChange = async () => {
const doc = await editor.currentDocument().saveDocument();
localStorage.setItem('draft', JSON.stringify(doc));
};
editor.on('content.change', handleChange);
// ... later ...
editor.off('content.change', handleChange);
// Remove all handlers for an event
editor.off('content.change');
// Cleanup pattern
const setupEditor = (target) => {
const editor = await system.createEditor(target);
const handleChange = () => console.log('changed');
const handleLoad = () => console.log('loaded');
editor.on('content.change', handleChange);
editor.on('document.load', handleLoad);
return () => {
editor.off('content.change', handleChange);
editor.off('document.load', handleLoad);
editor.destroy();
};
};

DocAuthEditorEvents


once<EventName>(event, handler): DocAuthEditor

Adds an event listener that will be called only once when the specified event is emitted. The listener is automatically removed after being called.

EventName extends keyof DocAuthDocumentEvents | "document.load" | "selection.change" | "tracked-change.lifecycle" | "comment.lifecycle"

EventName

The event name to listen for

DocAuthEditorEventHandler<EventName>

The function to call when the event is emitted

DocAuthEditor

The editor instance for method chaining

// Wait for initial document load
editor.once('document.load', () => {
console.log('Document loaded for the first time');
});
// Perform action after first change
editor.once('content.change', () => {
console.log('User made their first edit');
});
// Promise-based pattern for waiting on load
const waitForLoad = (editor) => {
return new Promise((resolve) => {
editor.once('document.load', resolve);
});
};
await waitForLoad(editor);
console.log('Ready to use');

DocAuthEditorEvents