Birch UI v0.1
Pricing

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.

Open .md

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.

TypeScript
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(): DocumentData
  • setJSON(data: DocumentInput): void
  • getText(): string
  • importDocx(input: ArrayBuffer \| Uint8Array \| Blob): Promise<void>
  • exportDocx(): Promise<Blob>
  • downloadDocx(fileName?: string): Promise<void>
  • exportHtml(options?: HtmlExportOptions): string
  • importHtml(html: string): void
  • print(): void
  • exec(command: DocumentCommand, value?: unknown): boolean
  • canExec(command: DocumentCommand, value?: unknown): boolean
  • getFormatState(): FormatState
  • getSelection(): { from: number; to: number; text: string }
  • setSelection(from: number, to?: number): void
  • undo(): boolean
  • redo(): boolean
  • canUndo(): boolean
  • canRedo(): boolean
  • find(query: string, options?: FindOptions): FindResult
  • findNext(): FindResult
  • findPrevious(): FindResult
  • replace(replacement: string): FindResult
  • replaceAll(query: string, replacement: string, options?: FindOptions): number
  • clearFind(): void
  • openFindPanel(mode?: 'find' \| 'replace'): void
  • setTrackChanges(enabled: boolean): void
  • isTrackingChanges(): boolean
  • setShowMarkup(visible: boolean): void
  • getTrackedChanges(): TrackedChange[]
  • acceptChange(id: string): boolean
  • rejectChange(id: string): boolean
  • acceptAllChanges(): number
  • rejectAllChanges(): number
  • addComment(text: string, options?: AddCommentOptions): string \| null
  • getComments(): CommentThread[]
  • replyToComment(id: string, text: string, options?: AddCommentOptions): string \| null
  • editComment(id: string, text: string): boolean
  • resolveComment(id: string, resolved?: boolean): boolean
  • deleteComment(id: string): boolean
  • selectComment(id: string): boolean
  • compareWith(revised: DocumentInput, options?: CompareOptions): number
  • proposeChange(change: ProposedChange): string[]
  • applySteps(steps: readonly unknown[]): boolean
  • insertField(name: string): boolean
  • getFieldNames(): string[]
  • merge(values: MergeValues, options?: MergeOptions): DocumentData
  • applyMerge(values: MergeValues, options?: MergeOptions): void
  • insertImage(src: string, options?: InsertImageOptions): boolean
  • insertTable(rows: number, columns: number): boolean
  • getWordCount(): WordCount
  • getPageCount(): number
  • getCurrentPage(): number
  • getPageSetup(): PageSetup
  • setPageSetup(setup: Partial<PageSetup>): void
  • setLayout(layout: DocumentLayout): void
  • getLayout(): DocumentLayout
  • setZoom(zoom: number): void
  • getZoom(): number
  • getOutline(): OutlineEntry[]
  • scrollToHeading(index: number): boolean
  • setReadOnly(readOnly: boolean): void
  • isReadOnly(): boolean
  • setAuthor(author: AuthorInfo \| string): void
  • editHeaderFooter(part: 'header' \| 'footer'): void
  • relayout(): void
  • focus(): void

Editing methods#

  • openPane(id: string): boolean
  • closePane(id: string): boolean
  • isPaneOpen(id: string): boolean
  • getStyles(): ParagraphStyleInfo[]
  • applyStyle(id: string): boolean
  • createStyle(name: string, format?: StyleFormat, basedOn?: string): string \| null
  • createStyleFromSelection(name: string): string \| null
  • modifyStyle(id: string, format: StyleFormat, name?: string): boolean
  • updateStyleToMatchSelection(id: string): boolean
  • deleteStyle(id: string): boolean
  • getFontFormat(): Required<FontFormat>
  • setFontFormat(format: FontFormat): boolean
  • setHyperlink(options: HyperlinkOptions \| null): boolean
  • getDocumentProperties(): DocumentProperties
  • setDocumentProperties(properties: Partial<DocumentProperties>): boolean (a property set to null is removed)
  • getAutocorrectOptions(): Required<AutocorrectOptions> \| null
  • setAutocorrectOptions(options: AutocorrectOptions): boolean
  • setParagraphFormat(format: ParagraphFormat): boolean
  • setParagraphBorders(borders: ParagraphBorders \| null, shading?: string \| null): boolean
  • changeCase(mode: CaseMode): boolean
  • setDropCap(mode: 'none' \| 'drop' \| 'margin', lines?: number): boolean
  • collapseHeading(index: number, collapsed: boolean): boolean
  • isHeadingCollapsed(index: number): boolean
  • moveSection(index: number, targetIndex: number): boolean
  • getDetailedWordCount(): DetailedWordCount
  • getFindResults(query: string, options?: FindOptions): FindPaneResult[]
  • getListDefinitions(): MultilevelListDefinition[]
  • defineMultilevelList(definition: Omit<MultilevelListDefinition, 'id'> & { id?: string }): string
  • pasteHtml(html: string, mode?: PasteMode): boolean
  • saveNow(): Promise<void>
  • isSaving(): boolean
  • getWatermark(): Watermark \| null
  • setWatermark(watermark: Watermark \| string \| null): boolean
  • getLineNumbers(): LineNumbering \| null
  • setLineNumbers(numbering: LineNumbering \| boolean \| null): boolean
  • getColumns(): ColumnSettings
  • setColumns(columns: ColumnSettings \| number): boolean
  • insertBreak(kind: BreakKind): boolean

Objects, references and forms methods#

  • getFootnotes(kind?: NoteKind): FootnoteInfo[]
  • getBookmarks(includeHidden?: boolean): BookmarkInfo[]
  • goToBookmark(name: string): boolean
  • updateFields(): number
  • setFormMode(enabled: boolean): void
  • isFormMode(): boolean
  • getFormData(): Record<string, unknown>
  • setFormData(data: Record<string, unknown>): number
  • validateForm(): FormFieldError[]
  • openObjectDialog(name: ObjectDialogName): boolean
  • evaluateTableFormula(formula: string): string \| null
  • getProtection(): DocumentProtection \| null
  • protectDocument(mode: ProtectionMode, password?: string): Promise<boolean>
  • unprotectDocument(password?: string): Promise<boolean>
  • isPasswordProtected(): boolean
  • insertEmbeddedObject(options: InsertEmbeddedObjectOptions): boolean
  • getEmbeddedObjects(): EmbeddedObjectInfo[]
  • openEmbeddedObject(pos?: number): boolean
  • downloadEmbeddedObject(pos?: number): boolean

Citation methods#

  • getSources(): BibliographySource[]
  • setSources(sources: readonly BibliographySource[]): void
  • addSource(source: Omit<BibliographySource, 'tag'> & { tag?: string }): string \| null
  • removeSource(tag: string): boolean
  • getCitationStyle(): CitationStyle
  • setCitationStyle(style: CitationStyle): void
  • insertCitation(citation: string \| CitationOptions): boolean
  • insertBibliography(): boolean
  • updateCitations(): number

Review methods#

  • getMarkupMode(): MarkupMode
  • setMarkupMode(mode: MarkupMode): void
  • getMarkupVisibility(): MarkupVisibility
  • setMarkupVisibility(visibility: Partial<MarkupVisibility>): void
  • getRevisions(filter?: RevisionFilter): RevisionChange[]
  • acceptChanges(filter?: RevisionFilter): number
  • rejectChanges(filter?: RevisionFilter): number
  • nextChange(): RevisionChange \| null
  • previousChange(): RevisionChange \| null
  • goToChange(id: string): boolean
  • editReply(threadId: string, replyId: string, text: string): boolean
  • deleteReply(threadId: string, replyId: string): boolean
  • saveSnapshot(label?: string): SnapshotInfo \| null
  • getSnapshots(): SnapshotInfo[]
  • restoreSnapshot(id: string): boolean
  • compareWithSnapshot(id: string, options?: CompareOptions): number
  • deleteSnapshot(id: string): boolean
  • getSnapshotDocument(id: string): DocumentData \| null
  • compareWithDocx(input: ArrayBuffer \| Uint8Array \| Blob, options?: CompareOptions): Promise<number>

Collaboration methods#

  • getCollabVersion(): number
  • getCollabStatus(): CollabStatus
  • getCollabConnection(): CollabConnectionStatus
  • saveCollabVersion(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): void
  • getLocks(): CollabLock[]
  • sendableSteps(): CollabStepsPayload \| null
  • receiveSteps(payload: CollabRemotePayload): boolean
  • resetCollab(snapshot: CollabSnapshot): void
  • getCollaborators(): Collaborator[]

Ribbon and view methods#

  • getRibbonTab(): string \| null
  • setRibbonTab(tab: RibbonTabName): boolean
  • isRibbonCollapsed(): boolean
  • setRibbonCollapsed(collapsed: boolean): void
  • getViewMode(): DocumentViewMode
  • setViewMode(mode: DocumentViewMode): void
  • fitZoom(mode: 'width' \| 'page'): number
  • getTabStops(): TabStop[]
  • setTabStops(stops: readonly TabStop[]): boolean

File methods#

See The File tab.

  • newDocument(): void
  • openFile(input: Blob \| ArrayBuffer \| Uint8Array, options?: FileOpenOptions): Promise<FileImportFormat>
  • exportFile(format: FileExportFormat, options?: { password?: string \| null }): Promise<Blob>
  • setFilePassword(password: string \| null): void, hasFilePassword(): boolean
  • downloadFile(format: FileExportFormat, fileName?: string): Promise<void>
  • saveFile(): Promise<boolean>
  • getFileName(): string
  • setFileName(name: string): void
  • isModified(): boolean
  • openFileMenu(): boolean
  • closeFileMenu(): void
  • isFileMenuOpen(): boolean

Layout and PDF methods#

  • whenLayoutReady(): Promise<void>
  • isLayoutComplete(): boolean
  • getPageInfo(page: number): PageInfo \| null
  • getPageText(page: number): string
  • getLayoutStats(): LayoutStats
  • getPrintHtml(): string
  • exportPdf(options?: PdfExportOptions): Promise<Blob>

Spelling methods#

  • getSpellingIssues(): SpellingMatch[]
  • checkSpelling(): Promise<void>
  • ignoreSpelling(word: string): void
  • replaceSpelling(from: number, text: string): boolean

Widget contract methods#

  • readonly element: HTMLElement
  • update(options: Partial<TOptions>): void
  • on<K extends keyof TEvents & string>(event: K, listener: Listener<TEvents[K]>): () => void
  • destroy(): 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.
TypeScript
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.

TypeScript
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:

TypeScript
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.

↑ ↓ to move, Enter to open, Esc to close