Document Editor API and eventsDocument
Every option, method, event, command and export of Birch UI Document Editor, generated from the TypeScript declarations of the package.
This page lists the complete public API of @birchui/document. The lists are generated from src/types.ts and the feature contracts it merges, so each signature is the one the compiler sees. The guides explain behaviour: Editing, Ribbon and panes, Tables and images, Page layout, Footnotes and references, Content controls and forms, Track changes, Comments, Compare and version history, Collaboration, DOCX, Other formats, PDF export and print and Mail merge.
import { createDocumentEditor, type DocumentEditorApi, type DocumentEditorOptions } from '@birchui/document';
const editor: DocumentEditorApi = createDocumentEditor(container, options);documentEditorDefinition is the same widget wrapped for the shared Birch UI widget contract (name, tagName, events), which the framework adapters use.
Options#
createDocumentEditor(container, options) takes these options, and update(partial) applies any of them later without recreating the editor. Defaults and behaviour are described in the guide named in each heading.
Core options#
| Option | Type |
|---|---|
licenseKey |
string |
injectStyles |
boolean |
content |
DocumentInput |
page |
Partial<PageSetup> |
layout |
DocumentLayout |
zoom |
number |
readOnly |
boolean |
author |
AuthorInfo | string |
trackChanges |
boolean |
showMarkup |
boolean |
toolbar |
boolean | readonly ToolbarItemId[] |
statusBar |
boolean |
ruler |
boolean |
outline |
boolean |
commentsPanel |
boolean |
spellcheck |
boolean | SpellChecker |
placeholder |
string |
fonts |
readonly string[] |
fontSizes |
readonly number[] |
mergeFields |
readonly MergeFieldDefinition[] |
height |
number | string |
ariaLabel |
string |
announcements |
boolean | AnnouncementOptions |
localeText |
LocaleTextInput |
rtl |
boolean |
uploadImage |
(file: File) => Promise<string> |
chartProvider |
ChartProvider |
file |
boolean | FileOptions |
Editing options#
| Option | Type |
|---|---|
autocorrect |
boolean | AutocorrectOptions |
autocorrectStorage |
AutocorrectStorage |
clickAndType |
boolean |
autosave |
AutosaveOptions |
pasteOptions |
boolean |
defaultPasteMode |
PasteMode |
showFormattingMarks |
boolean |
hyphenation |
boolean |
Objects, references and forms options#
| Option | Type |
|---|---|
formMode |
boolean |
showBookmarks |
boolean |
noteNumberFormat |
Partial<Record<NoteKind, NoteNumberFormat>> |
mergeRecords |
readonly Record<string, unknown>[] |
Review options#
| Option | Type |
|---|---|
markupMode |
MarkupMode |
changeBars |
boolean |
changeBalloons |
boolean |
commentsLayout |
'margin' | 'panel' |
mentions |
MentionOptions |
snapshots |
SnapshotStorage |
Collaboration options#
| Option | Type |
|---|---|
collab |
CollabProvider | null |
collabStorage |
CollabOfflineStore | null |
Ribbon and view options#
| Option | Type |
|---|---|
ribbon |
boolean | RibbonConfig |
miniToolbar |
boolean |
viewMode |
DocumentViewMode |
theme |
'auto' | 'light' | 'dark' |
darkPage |
'white' | 'dark' |
verticalRuler |
boolean |
commandSearch |
boolean |
Layout and PDF options#
| Option | Type |
|---|---|
layoutCompatibility |
'word' | 'legacy' |
virtualize |
boolean | 'auto' |
pdfFonts |
readonly PdfFontSource[] |
isFontAvailable |
(family: string) => boolean |
Security options#
| Option | Type |
|---|---|
linkSchemes |
string[]: schemes whose links can be followed besides http, https, mailto and tel; see Addresses |
allowRemoteImages |
boolean (default false) |
resolveImage |
(url: string) => string | null | Promise<string | null> |
resolvePastedImage |
(src: string, context: PastedImageContext) => string | null | Promise<string | null>: supplies a data:image/… URL for a picture pasted with a file:// address; see Editing |
limits |
Partial<ZipLimits> |
Methods#
Core methods#
getJSON(): DocumentDatasetJSON(data: DocumentInput): voidgetText(): stringimportDocx(input: ArrayBuffer \| Uint8Array \| Blob): Promise<void>exportDocx(): Promise<Blob>downloadDocx(fileName?: string): Promise<void>exportHtml(options?: HtmlExportOptions): stringimportHtml(html: string): voidprint(): voidexec(command: DocumentCommand, value?: unknown): booleancanExec(command: DocumentCommand, value?: unknown): booleangetFormatState(): FormatStategetSelection(): { from: number; to: number; text: string }setSelection(from: number, to?: number): voidundo(): booleanredo(): booleancanUndo(): booleancanRedo(): booleanfind(query: string, options?: FindOptions): FindResultfindNext(): FindResultfindPrevious(): FindResultreplace(replacement: string): FindResultreplaceAll(query: string, replacement: string, options?: FindOptions): numberclearFind(): voidopenFindPanel(mode?: 'find' \| 'replace'): voidsetTrackChanges(enabled: boolean): voidisTrackingChanges(): booleansetShowMarkup(visible: boolean): voidgetTrackedChanges(): TrackedChange[]acceptChange(id: string): booleanrejectChange(id: string): booleanacceptAllChanges(): numberrejectAllChanges(): numberaddComment(text: string, options?: AddCommentOptions): string \| nullgetComments(): CommentThread[]replyToComment(id: string, text: string, options?: AddCommentOptions): string \| nulleditComment(id: string, text: string): booleanresolveComment(id: string, resolved?: boolean): booleandeleteComment(id: string): booleanselectComment(id: string): booleancompareWith(revised: DocumentInput, options?: CompareOptions): numberproposeChange(change: ProposedChange): string[]applySteps(steps: readonly unknown[]): booleaninsertField(name: string): booleangetFieldNames(): string[]merge(values: MergeValues, options?: MergeOptions): DocumentDataapplyMerge(values: MergeValues, options?: MergeOptions): voidinsertImage(src: string, options?: InsertImageOptions): booleaninsertTable(rows: number, columns: number): booleangetWordCount(): WordCountgetPageCount(): numbergetCurrentPage(): numbergetPageSetup(): PageSetupsetPageSetup(setup: Partial<PageSetup>): voidsetLayout(layout: DocumentLayout): voidgetLayout(): DocumentLayoutsetZoom(zoom: number): voidgetZoom(): numbergetOutline(): OutlineEntry[]scrollToHeading(index: number): booleansetReadOnly(readOnly: boolean): voidisReadOnly(): booleansetAuthor(author: AuthorInfo \| string): voideditHeaderFooter(part: 'header' \| 'footer'): voidrelayout(): voidfocus(): void
Editing methods#
openPane(id: string): booleanclosePane(id: string): booleanisPaneOpen(id: string): booleangetStyles(): ParagraphStyleInfo[]applyStyle(id: string): booleancreateStyle(name: string, format?: StyleFormat, basedOn?: string): string \| nullcreateStyleFromSelection(name: string): string \| nullmodifyStyle(id: string, format: StyleFormat, name?: string): booleanupdateStyleToMatchSelection(id: string): booleandeleteStyle(id: string): booleangetFontFormat(): Required<FontFormat>setFontFormat(format: FontFormat): booleansetHyperlink(options: HyperlinkOptions \| null): booleangetDocumentProperties(): DocumentPropertiessetDocumentProperties(properties: Partial<DocumentProperties>): boolean(a property set tonullis removed)getAutocorrectOptions(): Required<AutocorrectOptions> \| nullsetAutocorrectOptions(options: AutocorrectOptions): booleansetParagraphFormat(format: ParagraphFormat): booleansetParagraphBorders(borders: ParagraphBorders \| null, shading?: string \| null): booleanchangeCase(mode: CaseMode): booleansetDropCap(mode: 'none' \| 'drop' \| 'margin', lines?: number): booleancollapseHeading(index: number, collapsed: boolean): booleanisHeadingCollapsed(index: number): booleanmoveSection(index: number, targetIndex: number): booleangetDetailedWordCount(): DetailedWordCountgetFindResults(query: string, options?: FindOptions): FindPaneResult[]getListDefinitions(): MultilevelListDefinition[]defineMultilevelList(definition: Omit<MultilevelListDefinition, 'id'> & { id?: string }): stringpasteHtml(html: string, mode?: PasteMode): booleansaveNow(): Promise<void>isSaving(): booleangetWatermark(): Watermark \| nullsetWatermark(watermark: Watermark \| string \| null): booleangetLineNumbers(): LineNumbering \| nullsetLineNumbers(numbering: LineNumbering \| boolean \| null): booleangetColumns(): ColumnSettingssetColumns(columns: ColumnSettings \| number): booleaninsertBreak(kind: BreakKind): boolean
Objects, references and forms methods#
getFootnotes(kind?: NoteKind): FootnoteInfo[]getBookmarks(includeHidden?: boolean): BookmarkInfo[]goToBookmark(name: string): booleanupdateFields(): numbersetFormMode(enabled: boolean): voidisFormMode(): booleangetFormData(): Record<string, unknown>setFormData(data: Record<string, unknown>): numbervalidateForm(): FormFieldError[]openObjectDialog(name: ObjectDialogName): booleanevaluateTableFormula(formula: string): string \| nullgetProtection(): DocumentProtection \| nullprotectDocument(mode: ProtectionMode, password?: string): Promise<boolean>unprotectDocument(password?: string): Promise<boolean>isPasswordProtected(): booleaninsertEmbeddedObject(options: InsertEmbeddedObjectOptions): booleangetEmbeddedObjects(): EmbeddedObjectInfo[]openEmbeddedObject(pos?: number): booleandownloadEmbeddedObject(pos?: number): boolean
Citation methods#
getSources(): BibliographySource[]setSources(sources: readonly BibliographySource[]): voidaddSource(source: Omit<BibliographySource, 'tag'> & { tag?: string }): string \| nullremoveSource(tag: string): booleangetCitationStyle(): CitationStylesetCitationStyle(style: CitationStyle): voidinsertCitation(citation: string \| CitationOptions): booleaninsertBibliography(): booleanupdateCitations(): number
Review methods#
getMarkupMode(): MarkupModesetMarkupMode(mode: MarkupMode): voidgetMarkupVisibility(): MarkupVisibilitysetMarkupVisibility(visibility: Partial<MarkupVisibility>): voidgetRevisions(filter?: RevisionFilter): RevisionChange[]acceptChanges(filter?: RevisionFilter): numberrejectChanges(filter?: RevisionFilter): numbernextChange(): RevisionChange \| nullpreviousChange(): RevisionChange \| nullgoToChange(id: string): booleaneditReply(threadId: string, replyId: string, text: string): booleandeleteReply(threadId: string, replyId: string): booleansaveSnapshot(label?: string): SnapshotInfo \| nullgetSnapshots(): SnapshotInfo[]restoreSnapshot(id: string): booleancompareWithSnapshot(id: string, options?: CompareOptions): numberdeleteSnapshot(id: string): booleangetSnapshotDocument(id: string): DocumentData \| nullcompareWithDocx(input: ArrayBuffer \| Uint8Array \| Blob, options?: CompareOptions): Promise<number>
Collaboration methods#
getCollabVersion(): numbergetCollabStatus(): CollabStatusgetCollabConnection(): CollabConnectionStatussaveCollabVersion(name: string): Promise<CollabVersionInfo \| null>listCollabVersions(): Promise<CollabVersionInfo[]>restoreCollabVersion(id: string): Promise<boolean>diffCollabVersions(from: string, to: string \| null, options?: CollabVersionDiffOptions): Promise<DocNodeJSON \| null>lockRange(range?: { from: number; to: number }): Promise<CollabLock \| null>unlockRange(id: string): voidgetLocks(): CollabLock[]sendableSteps(): CollabStepsPayload \| nullreceiveSteps(payload: CollabRemotePayload): booleanresetCollab(snapshot: CollabSnapshot): voidgetCollaborators(): Collaborator[]
Ribbon and view methods#
getRibbonTab(): string \| nullsetRibbonTab(tab: RibbonTabName): booleanisRibbonCollapsed(): booleansetRibbonCollapsed(collapsed: boolean): voidgetViewMode(): DocumentViewModesetViewMode(mode: DocumentViewMode): voidfitZoom(mode: 'width' \| 'page'): numbergetTabStops(): TabStop[]setTabStops(stops: readonly TabStop[]): boolean
File methods#
See The File tab.
newDocument(): voidopenFile(input: Blob \| ArrayBuffer \| Uint8Array, options?: FileOpenOptions): Promise<FileImportFormat>exportFile(format: FileExportFormat, options?: { password?: string \| null }): Promise<Blob>setFilePassword(password: string \| null): void,hasFilePassword(): booleandownloadFile(format: FileExportFormat, fileName?: string): Promise<void>saveFile(): Promise<boolean>getFileName(): stringsetFileName(name: string): voidisModified(): booleanopenFileMenu(): booleancloseFileMenu(): voidisFileMenuOpen(): boolean
Layout and PDF methods#
whenLayoutReady(): Promise<void>isLayoutComplete(): booleangetPageInfo(page: number): PageInfo \| nullgetPageText(page: number): stringgetLayoutStats(): LayoutStatsgetPrintHtml(): stringexportPdf(options?: PdfExportOptions): Promise<Blob>
Spelling methods#
getSpellingIssues(): SpellingMatch[]checkSpelling(): Promise<void>ignoreSpelling(word: string): voidreplaceSpelling(from: number, text: string): boolean
Widget contract methods#
readonly element: HTMLElementupdate(options: Partial<TOptions>): voidon<K extends keyof TEvents & string>(event: K, listener: Listener<TEvents[K]>): () => voiddestroy(): void
Events#
Subscribe with editor.on(name, listener); it returns an unsubscribe function. DOCUMENT_EVENT_NAMES lists every name. Listener errors are caught and reported with console.error.
| Event | Payload |
|---|---|
ready |
{ api: DocumentEditorApi } |
contentChange |
{ source: 'user' | 'api'; wordCount: number } |
selectionChange |
{ from: number; to: number; format: FormatState } |
pageCountChange |
{ pageCount: number } |
commentsChange |
{ comments: CommentThread[] } |
trackedChangesChange |
{ changes: TrackedChange[] } |
historyChange |
{ canUndo: boolean; canRedo: boolean } |
readOnlyChange |
{ readOnly: boolean } |
transaction |
{ steps: unknown[]; origin: 'local' | 'remote'; docChanged: boolean } |
focus |
{ editor: DocumentEditorApi } |
blur |
{ editor: DocumentEditorApi } |
autosaveStart |
{ reason: 'change' | 'manual' | 'destroy' } |
autosaveEnd |
{ savedAt: string } |
autosaveError |
{ error: unknown } |
stylesChange |
{ styles: ParagraphStyleInfo[] } |
autocorrectChange |
{ options: AutocorrectOptions } |
formChange |
{ tag: string; value: unknown; data: Record<string, unknown> } |
fieldsUpdate |
{ count: number } |
embeddedObjectOpen |
{ fileName: string; mimeType: string; progId: string; data: Uint8Array } |
revisionsChange |
{ revisions: RevisionChange[] } |
markupModeChange |
{ mode: MarkupMode } |
snapshotsChange |
{ snapshots: SnapshotInfo[] } |
collabStatus |
CollabStatus |
collabConnection |
{ status: CollabConnectionStatus; previous: CollabConnectionStatus } |
collabRejected |
{ reason: CollabRejectReason; steps: number } |
collabRestored |
{ steps: number; version: number } |
locksChange |
{ locks: CollabLock[] } |
presenceChange |
{ collaborators: Collaborator[] } |
ribbonTabChange |
{ tab: string } |
viewModeChange |
{ mode: DocumentViewMode } |
fileOpened |
{ fileName: string; format: FileImportFormat } |
fileSaved |
{ fileName: string; format: FileExportFormat | null; target: 'download' | 'host' } |
fileError |
{ action: 'open' | 'save' | 'new'; error: unknown; fileName: string } |
fileMenuChange |
{ open: boolean } |
sourcesChange |
{ sources: BibliographySource[]; style: CitationStyle } |
layoutComplete |
{ pageCount: number; durationMs: number } |
fontsMissing |
{ fonts: { family: string; substitute: string | null }[] } |
steps of the transaction event is serialised when a listener first reads it.
Commands#
exec(command, value?) runs a command and returns whether it applied; canExec(command, value?) tests it without changing anything. Commands that open a dialog or a pane take no value.
Core commands#
bold, italic, underline, strike, superscript, subscript, clearFormatting, formatPainter, fontFamily, fontSize, textColor, highlight, paragraphStyle, align, alignLeft, alignCenter, alignRight, alignJustify, lineSpacing, spaceBefore, spaceAfter, indent, outdent, bulletList, orderedList, listStyle, link, unlink, pageBreak, horizontalRule, insertSymbol, insertText, hardBreak, insertTable, addRowBefore, addRowAfter, deleteRow, addColumnBefore, addColumnAfter, deleteColumn, deleteTable, mergeCells, splitCell, toggleHeaderRow, cellBackground, tableBorders, insertImage, imageAlt, imageSize, insertField, insertPageNumber, insertPageCount, insertTableOfContents, updateTableOfContents, addComment, textDirection, selectAll, undo, redo
Editing commands#
fontDialog, fontFormat, hyperlinkDialog, hyperlink, pasteSpecialDialog, autocorrectDialog, documentPropertiesDialog, documentProperties, defaultTabStop, revealFormatting, clearParagraphFormatting, clearCharacterFormatting, clearCharacterStyle, columnsDialog, noteOptionsDialog, numberFormatDialog, paragraphDialog, paragraphFormat, bordersDialog, paragraphBorders, paragraphShading, listLibrary, applyListFormat, defineMultilevelList, applyMultilevelList, applyStyle, stylesPane, formatPainterLock, findPane, replacePane, navigationPane, moveSectionUp, moveSectionDown, promoteHeading, demoteHeading, changeCase, cycleCase, dropCap, symbolDialog, dateTimeDialog, insertDateTime, wordCountDialog, pasteText, pasteMode, insertBreak, pageSetupDialog, columns, lineNumbers, watermark, watermarkDialog, multilevelDialog, formattingMarks, insertSpecialCharacter
Objects, references and forms commands#
objectDialog, updateFields, cellBorders, cellShading, cellVerticalAlign, cellTextDirection, cellMargins, distributeRows, distributeColumns, autofitTable, rowHeight, columnWidth, sortTable, insertFormula, textToTable, tableToText, tableStyle, tableStyleOptions, tableProperties, splitCells, selectRow, selectColumn, selectTable, deleteCells, drawBorders, imageWrap, imagePosition, imageRotate, imageFlip, imageCrop, imageCropMode, imageReset, imageReplace, imageCompress, imageDecorative, imageNudge, insertShape, insertTextBox, shapeStyle, insertEquation, insertEmbeddedObject, openEmbeddedObject, downloadEmbeddedObject, insertBookmark, deleteBookmark, goToBookmark, showBookmarks, insertCrossReference, insertCaption, insertTableOfFigures, tableOfContentsOptions, insertFootnote, insertEndnote, nextFootnote, previousFootnote, convertNotes, deleteNote, noteFormat, insertContentControl, contentControlProperties, removeContentControl, formMode, insertDateField, insertCells, shapeEditText, restrictEditing, toggleFieldCodes, mergePreview, tableTool, paintCellEdges, imageBorder, insertChart, editChart
Citation commands#
insertCitation (value: a source tag or a CitationOptions; without a value it opens the New source dialog), insertBibliography, citationStyle (value: 'apa', 'mla' or 'chicago'), manageSources
Review commands#
markupMode, acceptChange, rejectChange, acceptAndNext, rejectAndNext, acceptShownChanges, rejectShownChanges, nextChange, previousChange, revisionsPane, compareDialog, saveSnapshot, versionHistoryPane, compareSideBySide, closeSideBySide, combineDialog
Ribbon and view commands#
cut, copy, paste, toggleRibbon, readMode, focusMode, fitWidth, fitPage, setTabStops, clearTabStops, tabsDialog, toggleGridlines, commandSearch, keyboardShortcuts
File commands#
fileMenu, newDocument, openFile, saveFile, downloadFile (value: a FileExportFormat), printDocument
Exported functions and constants#
createDocumentEditor, documentEditorDefinition, DOCUMENT_EVENT_NAMES, documentStyles, docxToDocument, readDocx, documentToDocx, buildDocxParts, validateDocxPackage, validateDocxParts, embeddedObjectNode, embeddedObjectFile, metafileToSvg, numberingLabels, formatNumber, updateFields, parseFieldInstruction, formatDatePicture, documentSections, documentToMarkdown, markdownToDocument, documentToHtml, htmlToDocument, rtfToDocument, docToDocument, DocFormatError, DEFAULT_DOC_LIMITS, documentToOdt, odtToDocument, ODT_MIME, DOCX_MIME, mergeDocument, mergeContent, mergeFieldNames, compareDocuments, combineDocuments, markMoves, countRevisions, acceptAllRevisions, rejectAllRevisions, emptyDocument, normalizeDocument, wordCount, documentText, outlineOf, PAGE_SIZES, DEFAULT_PAGE_SETUP, normalizePageSetup, pageDimensions, contentBox, PARAGRAPH_STYLES, findMatches, paginate, breakGaps, DEFAULT_TOOLBAR, SHORTCUTS, createLoopbackHub, createCollabAuthority, createAuthorityBackend, createCollabProvider, createSocketBackend, createBroadcastChannelBackend, hostBroadcastChannel, createWireBackend, createWireEndpoint, createCollabId, createCollabDocument, DEFAULT_COLLAB_LIMITS, createIndexedDbOfflineStore, createMemoryOfflineStore, sanitizeHref, sanitizeImageSrc, imageSourceKind, DEFAULT_ZIP_LIMITS, ZipLimitError, DocumentFormatError, FileOpenError, registerFonts, registeredFonts, clearRegisteredFonts, fontSubstitutes, fontFamilyStack, FONT_SUBSTITUTIONS, PdfFontError, layoutToPdf, writePdf, documentToPdf, renderDocumentPdf, layoutDocument, multiplyMatrix, rotationMatrix
Entry points#
The package has seven entry points, so an application bundles only what it uses.
| Import | Contains | Needs a DOM |
|---|---|---|
@birchui/document |
The editor (createDocumentEditor) and, for convenience, everything below |
Only createDocumentEditor |
@birchui/document/docx |
docxToDocument, readDocx, documentToDocx, buildDocxParts, validateDocxPackage, validateDocxParts, DOCX_MIME |
No |
@birchui/document/formats |
The Markdown, HTML, RTF and OpenDocument converters | No |
@birchui/document/pdf |
layoutToPdf, writePdf and the PDF layout types |
No |
@birchui/document/collab |
The collaboration authority, backends, provider and loopback hub | No |
@birchui/document/headless |
DOCX, formats and PDF plus mail merge, compare, fields, numbering, page setup and paginate |
No |
@birchui/document/locales |
documentEn, documentDe, documentEs, documentFr, documentJa, documentPt, documentZh and DOCUMENT_LOCALES |
No |
The editor loads the DOCX reader and writer and the PDF writer on demand: importDocx, exportDocx, compareWithDocx and exportPdf fetch them the first time they are called, so they are not part of the editor's start-up code when your bundler splits dynamic imports. Every dialog and the Reveal formatting pane are loaded the same way the first time one of them is opened: the command returns true at once when the dialog applies, and the dialog appears when its code has arrived, so a test has to wait for it. The functions that the main entry re-exports from the other entries are dropped by tree shaking when you do not use them. Sizes are in the package README.
DOCX write options#
documentToDocx(data, options?) and buildDocxParts(data, options?) take DocxWriteOptions:
| Option | Type | Effect |
|---|---|---|
preserveSource |
boolean | 'exact' |
How content read from a DOCX file is written back. true (the default) writes every block that was not edited with its original XML and rebuilds a block whose original XML breaks the schema. 'exact' writes unedited blocks byte for byte, also the invalid ones. false generates the whole file from the model and ignores the preserved XML. |
trackRevisions |
boolean |
Writes w:trackRevisions, so Word opens the file with change tracking on. |
pageCount |
number |
The page count written to docProps/app.xml. exportDocx() passes the count of the layout. |
pages |
DocxPageMap |
The page of each bookmark and heading and the first page of each header and footer, so that the stored results of PAGE fields in headers and footers, PAGEREF fields and table of contents entries are the real page numbers. exportDocx() fills it from the layout. Without it the results are written as before. |
zoom |
number |
The zoom percentage stored in the settings. |
compress |
boolean |
false stores the parts without compression. |
now |
Date |
The modification time; set it for reproducible output. |
import { documentToDocx } from '@birchui/document/docx';
const fromModel = await documentToDocx(data, { preserveSource: false });
const untouched = await documentToDocx(data, { preserveSource: 'exact', now: new Date('2027-03-12T09:00:00Z') });
notify(fromModel.byteLength, untouched.byteLength);What each mode keeps is measured on the DOCX page.
Exported types#
AbstractNumbering, AddCommentOptions, AnnouncementOptions, AuthorInfo, AutocorrectOptions, AutocorrectStorage, AutosaveOptions, BookmarkInfo, BorderEdge, BorderLine, BorderLineStyle, BorderSet, BreakKind, BulletListStyle, CaptionValue, CaseMode, CellBordersValue, CellRevisionInfo, ChartProvider, ChartResult, CollabApi, CollabClientId, CollabCommand, CollabCommentChannel, CollabCommentOperation, CollabEvents, CollabMetaOperation, CollabOptions, CollabPresenceChannel, CollabProvider, CollabRemotePayload, CollabSnapshot, CollabState, CollabStatus, CollabStepsPayload, Collaborator, ColumnSettings, CombineOptions, CommentReply, CommentThread, CompareOptions, ContentControl, ContentControlKind, ContentControlValue, CrossReferenceDisplay, CrossReferenceTarget, CrossReferenceValue, DetailedWordCount, DocMarkJSON, DocNodeJSON, DocumentCommand, DocumentData, DocumentDefaults, DocumentEditorApi, DocumentEditorEvents, DocumentEditorOptions, DocumentInput, DocumentLayout, DocumentProperties, DocumentProtection, DocumentSection, DocumentSettings, DocumentSnapshot, DocumentStyle, DocumentStyleType, DocumentViewMode, DocxImportFeature, DocxImportReport, DocxPageMap, DocxPackage, DocxReadResult, DocxValidationIssue, DocxValidationResult, DocxWriteOptions, EditingApi, EditingCommand, EditingEvents, EditingOptions, FieldContext, FieldKind, FindOptions, FindPaneResult, FindResult, FontFormat, FootnoteInfo, FormControlKind, FormFieldError, FormatState, HeaderFooterContent, HtmlDocumentOptions, HtmlExportOptions, HyperlinkOptions, ImageAnchor, ImageBorder, ImageCrop, ImageWrap, InsertImageOptions, InsertShapeValue, LayoutApi, LayoutBlock, LayoutBlockKind, LayoutBreak, LayoutCommand, LayoutEvents, LayoutOptions, LayoutStats, LineNumbering, LineRule, ListLevelFormat, LoopbackConnection, LoopbackHub, LoopbackHubOptions, MarkdownOptions, MarkupMode, MarkupVisibility, MentionEvent, MentionOptions, MergeFieldDefinition, MergeOptions, MergeValues, MultilevelListDefinition, NoteKind, NoteNumberFormat, NoteSettings, NumberingDefinitions, NumberingInstance, NumberingLabel, NumberingLevel, NumberingOverride, ObjectDialogName, ObjectWrap, ObjectsApi, ObjectsCommand, ObjectsEvents, ObjectsOptions, OrderedListStyle, OutlineEntry, PageInfo, PageMargins, PageNumberFormat, PageNumbering, PageOrientation, PageSetup, PageSizeName, PageSlice, PaginateOptions, PaginationResult, ParagraphBorder, ParagraphBorders, ParagraphFormat, ParagraphFormatChange, ParagraphStyleDefinition, ParagraphStyleId, ParagraphStyleInfo, ParsedField, PasteMode, PdfColor, PdfDestination, PdfDocumentLayout, PdfExportOptions, PdfFontSource, PdfImage, PdfItem, PdfLine, PdfLinkArea, PdfOutlineEntry, PdfPage, PdfRect, PdfTextRun, PdfWriteOptions, Person, PresenceState, PreservedPart, PreservedRelationship, PreservedXml, ProposedChange, ProtectionMode, ReviewApi, ReviewCommand, ReviewEvents, ReviewOptions, RevisionChange, RevisionChangeKind, RevisionFilter, RevisionInfo, RibbonApi, RibbonCommand, RibbonConfig, RibbonCustomControl, RibbonCustomGroup, RibbonEvents, RibbonOptions, RibbonTabName, RunFormatChange, SearchBlock, SearchMatch, SectionBreakType, SectionColumns, SectionHeaders, ShapeKind, SnapshotInfo, SnapshotStorage, SortTableValue, SpellChecker, SpellingApi, SpellingIssue, SpellingMatch, StyleFormat, TabStop, TabStopAlignment, TabStopLeader, TableDirection, TableLook, TableOfContentsOptions, TablePropertiesValue, TextAlignment, TextToTableValue, ToolbarItemId, TrackedChange, TrackedChangeKind, UnderlineStyle, Watermark, WordCount
Collaboration backends, tagged PDF and document metadata add: CollabAuthority, CollabAuthorityOptions, CollabAuthorityPeer, CollabBackend, CollabBackendEvent, CollabBackendProvider, CollabBackendProviderOptions, CollabBackendStart, CollabBroadcastBackendOptions, CollabBroadcastPort, CollabConnectionStatus, CollabLock, CollabLockChannel, CollabLockRequest, CollabLockState, CollabLogEntry, CollabRejectReason, CollabSendResult, CollabSnapshotChannel, CollabSocketBackendOptions, CollabSocketLike, CollabStepFootprint, CollabSubmitResult, CollabVersionChannel, CollabVersionDiffOptions, CollabVersionInfo, CollabVersionInput, CollabVersionRecord, CollabWireBackendOptions, CollabWireEndpoint, CollabWireLink, CollabWireMessage, CommentMention, CompatibilitySettings, DocumentPdfOptions, DocumentPdfResult, DocumentPerson, PdfArtifactType, PdfCluster, PdfFontLoader, PdfGroup, PdfMatrix, PdfPath, PdfPathCommand, PdfStructNode, PdfStructType, PdfTagging, PdfWriteResult
Document data#
getJSON() returns DocumentData, and setJSON, the content option and every converter accept it.
interface DocumentData {
version: 1;
content: DocNodeJSON; // { type: 'doc', content: [...] }
page: PageSetup; // the first section
header: DocNodeJSON | null;
footer: DocNodeJSON | null;
firstHeader: DocNodeJSON | null;
firstFooter: DocNodeJSON | null;
evenHeader?: DocNodeJSON | null;
evenFooter?: DocNodeJSON | null;
comments: CommentThread[];
properties: DocumentProperties;
defaults: DocumentDefaults; // { fontFamily, fontSize }
settings?: DocumentSettings;
styles?: DocumentStyle[];
numbering?: NumberingDefinitions;
protection?: DocumentProtection | null;
watermark?: Watermark | null;
lineNumbers?: LineNumbering | null;
lists?: MultilevelListDefinition[];
sources?: BibliographySource[]; // the sources that citations name
citationStyle?: CitationStyle; // 'apa' | 'mla' | 'chicago'
docx?: DocxPackage | null; // preserved parts of an imported file
}getJSON() leaves out attributes that equal their defaults, so read attributes with a fallback.
Block and inline nodes with attributes: paragraph, bullet_list, ordered_list, table, table_row, table_cell, table_header, image, field, table_of_contents, page_break, section_break, footnote, drawing, sdt_block, sdt_inline, opaque_inline, opaque_block and marker; plus list_item, hard_break, horizontal_rule and text. opaque_inline and opaque_block hold preserved DOCX content such as equations and charts, and marker holds the ends of ranges such as bookmarks.
Marks, in the order they nest: link, bold, italic, underline, strike, superscript, subscript, font_family, font_size, color, highlight, run_props (preserved run properties), format_change, insertion, deletion and comment.
Translation keys#
Every string of the interface goes through the shared Birch UI translator with a key that starts with document.. Pass replacements in localeText; see Keyboard and accessibility.
The package ships all 1,237 keys in English, German, Spanish, French, Japanese, Brazilian Portuguese and Simplified Chinese, the locales the core package ships:
import { createDocumentEditor } from '@birchui/document';
import { documentDe } from '@birchui/document/locales';
createDocumentEditor(document.querySelector<HTMLElement>('#editor')!, { localeText: documentDe });documentEn is the complete list of keys with their English text, and DOCUMENT_LOCALES maps 'en', 'de', 'es', 'fr', 'ja', 'pt' and 'zh' to the packs. A test fails when a key used in the source is missing from any pack. node packages/document/scripts/extract-locale-keys.mjs --check reports keys that were added without a translation. Common keys: document.bold, document.italic, document.underline, document.paragraphStyle, document.style.Heading1, document.fontFamily, document.fontSize, document.textColor, document.highlight, document.link, document.image, document.table, document.comment, document.trackChanges, document.showMarkup, document.find, document.replace, document.replaceAll, document.pageSetup, document.print, document.pageOf, document.wordCount, document.comments, document.reply, document.resolve, document.acceptChange, document.rejectChange, document.header, document.footer.