DocAuthEditor
DocAuthEditor:
{ addVisualHighlight(location: DocumentLocation, options?: Readonly<{ color?: string; opacity?: number }>): Promise<AddVisualHighlightResult>;}The visual editor UI. Binds to a DOM element and lets users edit documents.
Create editors using createDocAuthSystem.
Properties
Section titled “Properties”find:
FindNamespace
The Find namespace. Searches the document and provides programmatic control over the editor’s Find bar.
Methods
Section titled “Methods”setCurrentDocument()
Section titled “setCurrentDocument()”setCurrentDocument(
doc):void
Attaches the provided document as the current document to the editor.
Parameters
Section titled “Parameters”Returns
Section titled “Returns”currentDocument()
Section titled “currentDocument()”currentDocument():
DocAuthDocument
Returns a reference to the currently attached document.
Returns
Section titled “Returns”navigateTo(
location):Promise<NavigateResult>
Reveals a portable document location without changing the current selection or focus.
Parameters
Section titled “Parameters”location
Section titled “location”A location created for the current saved document.
Returns
Section titled “Returns”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.
Parameters
Section titled “Parameters”location
Section titled “location”A ranged location created for the current saved document.
options?
Section titled “options?”Readonly<{ color?: string; opacity?: number; }>
Optional highlight color and opacity.
Returns
Section titled “Returns”Promise<AddVisualHighlightResult>
A tagged result containing a removable highlight when successful.
destroy()
Section titled “destroy()”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.
Returns
Section titled “Returns”docAuthSystem()
Section titled “docAuthSystem()”docAuthSystem():
DocAuthSystem
Retrieves the DocAuthSystem instance this editor is bound to.
Returns
Section titled “Returns”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.
Returns
Section titled “Returns”True if cursor is active and insertion is possible, false otherwise
insertTextAtCursor(
text):void
Inserts text at the current cursor position. If there’s a selection, it will be replaced with the provided text.
Parameters
Section titled “Parameters”The text to insert at the cursor position
Returns
Section titled “Returns”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.
{ content: string }(format defaults to'text') inserts the given string. Newlines become paragraph breaks via the same logic as paste.{ format: 'fragment', content: object }inserts a structured fragment. Before importing resources or changing the document or selection, the SDK validates the complete value against the generated contract returned byDocAuthSystem.getFragmentContract. Invalid type tags, persistence versions, and missing content keep their taggedDocAuthErrorvalues — detect them withisDocAuthErroror one of the per-type guards (isInvalidFragmentTypeError,isUnsupportedFragmentVersionError,isMissingFragmentContentError). Other contract violations also throw before mutation; callDocAuthSystem.validateFragmentfirst when structured issues are needed.
Parameters
Section titled “Parameters”options
Section titled “options”The content to insert, discriminated by format. See
InsertContentAtCursorOptions.
Returns
Section titled “Returns”Example
Section titled “Example”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}`); console.error(err.type, err.message); }}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 throughinsertContentAtCursorwithformat: '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.
Type Parameters
Section titled “Type Parameters”F extends SelectionContentFormat
Parameters
Section titled “Parameters”options
Section titled “options”The format to read the selection in. See SelectionContentFormat.
format
Section titled “format”F
Returns
Section titled “Returns”SelectionContentByFormat[F] | null
The selection in the requested format, or null if no range is selected.
Example
Section titled “Example”const text = editor.getSelectionContent({ format: 'text' });
const fragment = editor.getSelectionContent({ format: 'fragment' });setActions(
actions):void
Set all actions (replaces any existing actions). Allows setting and executing editor actions programmatically.
The actions stay in effect when DocAuthEditor.setCurrentDocument switches documents.
Built-in toolbar controls and context menu items backed by a built-in action run it from this list, so a replacement with the same ID runs from them. A control or item whose action is left out is hidden, and one whose action can’t run is disabled.
Each action’s capabilities decide which editor modes it can run in. See
BuiltInAction and CustomAction for the defaults, and
DocAuthEditorMode for what each mode allows.
Parameters
Section titled “Parameters”actions
Section titled “actions”Action[]
Array of actions to register
Returns
Section titled “Returns”Example
Section titled “Example”
// Register custom actions alongside default actionseditor.setActions([ { id: 'custom.insert-signature', label: 'Insert Signature', handler: () => { editor.insertTextAtCursor('\n\nBest regards,\nJohn Doe'); }, shortcuts: ['Mod+Shift+S'], },]);isActionRegistered()
Section titled “isActionRegistered()”isActionRegistered(
id):boolean
Returns true if an action with this ID is registered on this editor.
A registered action may still be disabled; see isActionEnabled().
Parameters
Section titled “Parameters”Returns
Section titled “Returns”isActionEnabled()
Section titled “isActionEnabled()”isActionEnabled(
id):boolean
Returns true if the action is registered and can run now.
Parameters
Section titled “Parameters”Returns
Section titled “Returns”executeAction()
Section titled “executeAction()”Executes a registered action, checking availability again at invocation time.
Build calls to built-in actions with actionCalls, which types and documents
their arguments. For a custom action, pass an ActionCall object.
Rejects with a TypeError if call is not an object with a string id and an args
array. Rejects if the action is missing, unavailable, its arguments are invalid, or its
handler fails. Resolves when the handler completes.
The SDK validates arguments for built-in handlers. Custom and replacement
handlers are responsible for validating their own arguments.
Parameters
Section titled “Parameters”The ID of the action and the arguments for its handler.
Returns
Section titled “Returns”Example
Section titled “Example”
// Clear, like the toolbar: no highlight, even where the text's style has one.// Remove only the direct highlight; a highlight from the text's style shows again.
// A custom action registered with setActions()await editor.executeAction({ id: 'custom.save', args: ['/api/save'] });setToolbarConfig(
config):void
Set the toolbar configuration. Use this to customize the editor’s toolbar.
The configuration stays in effect when DocAuthEditor.setCurrentDocument switches documents.
Parameters
Section titled “Parameters”config
Section titled “config”Toolbar configuration object
Returns
Section titled “Returns”Example
Section titled “Example”
// Use default toolbar config but add a custom itemeditor.setToolbarConfig({ items: [...defaultToolbarConfig.items, { type: 'action', id: 'custom', actionId: 'custom.insert-signature' }],});
// Or create a minimal toolbareditor.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' }, ],});setContextMenuConfig(
config):void
Set the items the host app adds to the editor’s context menus. Replaces any items set before. Host items come after the built-in
items, which follow DocAuthEditor.setActions.
Parameters
Section titled “Parameters”config
Section titled “config”Context menu configuration object
Returns
Section titled “Returns”Example
Section titled “Example”
editor.setActions([ { id: 'custom.define', label: 'Look up definition', handler: () => showDefinition() },]);
editor.setContextMenuConfig({ text: { items: [{ type: 'action', id: 'define', actionId: 'custom.define' }] },});
// Remove all host itemseditor.setContextMenuConfig({});setEditorMode(
mode):void
Sets the current editor mode. The mode decides which actions can run; see
DocAuthEditorMode.
Parameters
Section titled “Parameters”The editor mode to use.
Returns
Section titled “Returns”getEditorMode():
DocAuthEditorMode
Returns the current editor mode.
Returns
Section titled “Returns”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.
Parameters
Section titled “Parameters”factor
Section titled “factor”The zoom factor to apply, where 1 is 100%. Clamped to 0.5..4.
Returns
Section titled “Returns”Example
Section titled “Example”// Show the document at 50% in a narrow sidebareditor.setZoom(0.5);
// Back to 100%editor.setZoom(1);Throws
Section titled “Throws”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.
Returns
Section titled “Returns”Example
Section titled “Example”editor.setZoom() to change the zoom.
setAuthor(
name):void
Sets the author name used when creating comments, replies, and tracked changes.
Parameters
Section titled “Parameters”The author name to use for new comments
Returns
Section titled “Returns”Example
Section titled “Example”editor.setAuthor('John Doe');
// Clear author when user logs out (will use localized "Anonymous")editor.setAuthor('');The author stays in effect when DocAuthEditor.setCurrentDocument switches documents.
UIOptions.author for setting the initial author.
getAuthor():
string
Returns the author name used when creating comments, replies, and tracked changes.
Returns
Section titled “Returns”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.
Parameters
Section titled “Parameters”language
Section titled “language”The spellcheck language to activate.
Returns
Section titled “Returns”Example
Section titled “Example”editor.enableSpellcheck('fr-FR');editor.enableSpellcheck('en-US');editor.disableSpellcheck()to turn spell checking off.UIOptions.spellcheckfor setting the initial language.
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.
Returns
Section titled “Returns”Example
Section titled “Example”editor.disableSpellcheck();editor.enableSpellcheck() to turn spell checking on.
on(
event,handler):DocAuthEditor
Adds an event listener that will be called every time the specified event is emitted.
Parameters
Section titled “Parameters”EventName
handler
Section titled “handler”(payload: EventPayload) => void
Returns
Section titled “Returns”DocAuthEditor
The editor instance for method chaining
Example
Section titled “Example”// Auto-save on content changeseditor.on('content.change', async () => { const doc = await editor.currentDocument().saveDocument();});
// Track document loadeditor.on('document.load', () => { console.log('Document loaded successfully');});
// Debounced save to prevent excessive API callslet saveTimeout;editor.on('content.change', async () => { clearTimeout(saveTimeout); saveTimeout = setTimeout(async () => { const doc = await editor.currentDocument().saveDocument(); await fetch('/api/save', { method: 'POST', }); }, 1000);});
// Method chainingeditor.on('document.load', () => console.log('loaded')).on('content.change', () => console.log('changed'));Available Events
Section titled “Available Events”| Event name | Event payload | Description |
|---|---|---|
document.load | none | Fired when a document is initially loaded into the editor. This event is triggered once per document load, including when switching documents. It is emitted before any content.change for that document. When the document was already laid out, for example because it was created some time before the editor, the event fires shortly after createEditor resolves or setCurrentDocument returns. |
content.change | none | Fired when the document content has changed due to user editing or programmatic modifications. Use this event to react to document changes, such as saving drafts or updating UI state. |
selection.change | none | Fired after the caret or selection changes, including when it is cleared. Read the updated state with getSelectionContent() and hasActiveCursor(). Adding a listener does not report the current selection, so read it once when you subscribe. Subscribe to content.change as well if selected content must stay up to date. |
tracked-change.lifecycle | `{ operation: “create”; phase: “attempted" | "denied” } |
comment.lifecycle | `{ operation: “create”; phase: “attempted” } | { operation: “create”; phase: “completed”; commentId: string } |
revision.created | RevisionEventPayload | Fired when one or more tracked-change revisions are created. |
revision.edited | RevisionEventPayload | Fired when one or more existing tracked-change revisions are edited. |
revision.accepted | RevisionEventPayload | Fired when one or more tracked-change revisions are accepted. |
revision.rejected | RevisionEventPayload | Fired when one or more tracked-change revisions are rejected. |
revision.withdrawn | RevisionEventPayload | Fired when one or more tracked-change revisions are withdrawn. |
comment.threadAdded | CommentEventPayload | Fired when one or more comment threads are added. |
comment.replied | CommentEventPayload | Fired when one or more replies are added to comment threads. |
comment.edited | CommentEventPayload | Fired when the text of one or more comments or replies is edited. |
comment.resolved | CommentEventPayload | Fired when one or more comment threads are resolved. |
comment.unresolved | CommentEventPayload | Fired when one or more comment threads are marked unresolved. |
comment.removed | `CommentEventPayload & { reason: “removed" | "anchor-deleted” }` |
content.change | none | Fired after every committed transaction following document initialization. |
off(
event,handler?):DocAuthEditor
Removes an event listener. If no handler is provided, removes all listeners for the event.
Parameters
Section titled “Parameters”EventName
handler?
Section titled “handler?”(payload: EventPayload) => void
Returns
Section titled “Returns”DocAuthEditor
The editor instance for method chaining
Example
Section titled “Example”// Remove specific handler (prevent memory leaks)const handleChange = async () => { const doc = await editor.currentDocument().saveDocument();};editor.on('content.change', handleChange);// ... later ...editor.off('content.change', handleChange);
// Remove all handlers for an eventeditor.off('content.change');
// Cleanup patternconst 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(); };};Available Events
Section titled “Available Events”| Event name | Event payload | Description |
|---|---|---|
document.load | none | Fired when a document is initially loaded into the editor. This event is triggered once per document load, including when switching documents. It is emitted before any content.change for that document. When the document was already laid out, for example because it was created some time before the editor, the event fires shortly after createEditor resolves or setCurrentDocument returns. |
content.change | none | Fired when the document content has changed due to user editing or programmatic modifications. Use this event to react to document changes, such as saving drafts or updating UI state. |
selection.change | none | Fired after the caret or selection changes, including when it is cleared. Read the updated state with getSelectionContent() and hasActiveCursor(). Adding a listener does not report the current selection, so read it once when you subscribe. Subscribe to content.change as well if selected content must stay up to date. |
tracked-change.lifecycle | `{ operation: “create”; phase: “attempted" | "denied” } |
comment.lifecycle | `{ operation: “create”; phase: “attempted” } | { operation: “create”; phase: “completed”; commentId: string } |
revision.created | RevisionEventPayload | Fired when one or more tracked-change revisions are created. |
revision.edited | RevisionEventPayload | Fired when one or more existing tracked-change revisions are edited. |
revision.accepted | RevisionEventPayload | Fired when one or more tracked-change revisions are accepted. |
revision.rejected | RevisionEventPayload | Fired when one or more tracked-change revisions are rejected. |
revision.withdrawn | RevisionEventPayload | Fired when one or more tracked-change revisions are withdrawn. |
comment.threadAdded | CommentEventPayload | Fired when one or more comment threads are added. |
comment.replied | CommentEventPayload | Fired when one or more replies are added to comment threads. |
comment.edited | CommentEventPayload | Fired when the text of one or more comments or replies is edited. |
comment.resolved | CommentEventPayload | Fired when one or more comment threads are resolved. |
comment.unresolved | CommentEventPayload | Fired when one or more comment threads are marked unresolved. |
comment.removed | `CommentEventPayload & { reason: “removed" | "anchor-deleted” }` |
content.change | none | Fired after every committed transaction following document initialization. |
once(
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.
Parameters
Section titled “Parameters”EventName
handler
Section titled “handler”(payload: EventPayload) => void
Returns
Section titled “Returns”DocAuthEditor
The editor instance for method chaining
Example
Section titled “Example”// Wait for initial document loadeditor.once('document.load', () => { console.log('Document loaded for the first time');});
// Perform action after first changeeditor.once('content.change', () => { console.log('User made their first edit');});
const waitForLoad = (editor) => { editor.once('document.load', resolve); });};await waitForLoad(editor);console.log('Ready to use');Available Events
Section titled “Available Events”| Event name | Event payload | Description |
|---|---|---|
document.load | none | Fired when a document is initially loaded into the editor. This event is triggered once per document load, including when switching documents. It is emitted before any content.change for that document. When the document was already laid out, for example because it was created some time before the editor, the event fires shortly after createEditor resolves or setCurrentDocument returns. |
content.change | none | Fired when the document content has changed due to user editing or programmatic modifications. Use this event to react to document changes, such as saving drafts or updating UI state. |
selection.change | none | Fired after the caret or selection changes, including when it is cleared. Read the updated state with getSelectionContent() and hasActiveCursor(). Adding a listener does not report the current selection, so read it once when you subscribe. Subscribe to content.change as well if selected content must stay up to date. |
tracked-change.lifecycle | `{ operation: “create”; phase: “attempted" | "denied” } |
comment.lifecycle | `{ operation: “create”; phase: “attempted” } | { operation: “create”; phase: “completed”; commentId: string } |
revision.created | RevisionEventPayload | Fired when one or more tracked-change revisions are created. |
revision.edited | RevisionEventPayload | Fired when one or more existing tracked-change revisions are edited. |
revision.accepted | RevisionEventPayload | Fired when one or more tracked-change revisions are accepted. |
revision.rejected | RevisionEventPayload | Fired when one or more tracked-change revisions are rejected. |
revision.withdrawn | RevisionEventPayload | Fired when one or more tracked-change revisions are withdrawn. |
comment.threadAdded | CommentEventPayload | Fired when one or more comment threads are added. |
comment.replied | CommentEventPayload | Fired when one or more replies are added to comment threads. |
comment.edited | CommentEventPayload | Fired when the text of one or more comments or replies is edited. |
comment.resolved | CommentEventPayload | Fired when one or more comment threads are resolved. |
comment.unresolved | CommentEventPayload | Fired when one or more comment threads are marked unresolved. |
comment.removed | `CommentEventPayload & { reason: “removed" | "anchor-deleted” }` |
content.change | none | Fired after every committed transaction following document initialization. |