Options
All
  • Public
  • Public/Protected
  • All
Menu

Module roosterjs-editor-dom

Index

Classes

Type aliases

Variables

Functions

Type aliases

PendableFormatNames

PendableFormatNames: keyof PendableFormatState

Names of Pendable formats

Variables

Const Browser

Browser: BrowserInfo = ...

Browser object contains browser and operating system information of current environment

Const KnownCreateElementData

KnownCreateElementData: Record<KnownCreateElementDataIndex, CreateElementData> = ...

All known CreateElementData used by roosterjs to create elements

Const PendableFormatCommandMap

PendableFormatCommandMap: {[ key in PendableFormatNames]: DocumentCommand } = ...

A map from pendable format name to document command

Functions

addDelimiterAfter

  • addDelimiterAfter(element: Element): HTMLElement

addDelimiterBefore

  • addDelimiterBefore(element: Element): HTMLElement

addDelimiters

  • addDelimiters(node: Element): Element[]

addRangeToSelection

  • addRangeToSelection(range: Range, skipSameRange?: boolean): void
  • Add the given range into selection of the given document

    Parameters

    • range: Range

      The range to select

    • Optional skipSameRange: boolean

      When set to true, do nothing if the given range is the same with current selection, otherwise it will always remove current selection range and set to the given one. This parameter is always treat as true in Edge to avoid some weird runtime exception.

    Returns void

addSnapshot

  • addSnapshot(snapshots: Snapshots<string>, html: string, isAutoCompleteSnapshot: boolean): void
  • addSnapshot<T>(snapshots: Snapshots<T>, snapshot: T, isAutoCompleteSnapshot: boolean, getLength: (snapshot: T) => number, isSame: (snapshot1: T, snapshot2: T) => boolean): void
  • Add a new snapshot to the given snapshots data structure

    Parameters

    • snapshots: Snapshots<string>

      The snapshots data structure to add new snapshot into

    • html: string

      The snapshot HTML to add

    • isAutoCompleteSnapshot: boolean

      Whether this is a snapshot before auto complete action

    Returns void

  • Add a new snapshot to the given snapshots data structure

    Type parameters

    • T

    Parameters

    • snapshots: Snapshots<T>

      The snapshots data structure to add new snapshot into

    • snapshot: T

      The generic snapshot object to add

    • isAutoCompleteSnapshot: boolean

      Whether this is a snapshot before auto complete action

    • getLength: (snapshot: T) => number

      A callback function to calculate length of the snapshot

        • (snapshot: T): number
        • Parameters

          • snapshot: T

          Returns number

    • isSame: (snapshot1: T, snapshot2: T) => boolean

      A callback function to check if the given snapshots are the same

        • (snapshot1: T, snapshot2: T): boolean
        • Parameters

          • snapshot1: T
          • snapshot2: T

          Returns boolean

    Returns void

addSnapshotV2

adjustInsertPosition

applyFormat

  • Apply format to an HTML element

    Parameters

    • element: HTMLElement

      The HTML element to apply format to

    • format: DefaultFormat

      The format to apply

    • Optional isDarkMode: boolean

      Whether the content should be formatted in dark mode

    • Optional darkColorHandler: DarkColorHandler | null

      An optional dark color handler object. When it is passed, we will use this handler to do variable-based dark color instead of original dataset base dark color

    Returns void

applyTextStyle

  • applyTextStyle(container: Node, styler: (node: HTMLElement, isInnerNode?: boolean) => any, from?: NodePosition, to?: NodePosition): void
  • Apply style using a styler function to the given container node in the given range

    Parameters

    • container: Node

      The container node to apply style to

    • styler: (node: HTMLElement, isInnerNode?: boolean) => any

      The styler function

        • (node: HTMLElement, isInnerNode?: boolean): any
        • Parameters

          • node: HTMLElement
          • Optional isInnerNode: boolean

          Returns any

    • from: NodePosition = ...
    • to: NodePosition = ...

    Returns void

arrayPush

  • arrayPush<T>(mainArray: T[], itemsArray: T[]): void
  • A type-safe wrapper for Array.prototype.push.apply()

    Type parameters

    • T

    Parameters

    • mainArray: T[]

      The main array to push items into

    • itemsArray: T[]

      The items to push to main array

    Returns void

cacheGetEventData

  • cacheGetEventData<T>(event: PluginEvent | null, key: string, getter: () => T): T
  • Gets the cached event data by cache key from event object if there is already one. Otherwise, call getter function to create one, and cache it.

    Type parameters

    • T

    Parameters

    • event: PluginEvent | null

      The event object

    • key: string

      Cache key string, need to be unique

    • getter: () => T

      Getter function to get the object when it is not in cache yet

        • (): T
        • Returns T

    Returns T

canMoveCurrentSnapshot

  • canMoveCurrentSnapshot<T>(snapshots: Snapshots<T>, step: number): boolean
  • Check whether can move current snapshot with the given step

    Type parameters

    • T = string

    Parameters

    • snapshots: Snapshots<T>

      The snapshots data structure to check

    • step: number

      The step to check, can be positive, negative or 0

    Returns boolean

    True if can move current snapshot with the given step, otherwise false

canUndoAutoComplete

  • canUndoAutoComplete<T>(snapshots: Snapshots<T>): boolean

chainSanitizerCallback

  • chainSanitizerCallback<TOriginalArgs, TChainedFn, R>(map: Record<string, (...args: TOriginalArgs) => R>, name: string, newCallback: TChainedFn): void
  • Chain all callback for an attribute together

    Type parameters

    • TOriginalArgs: any[]

    • TChainedFn: (...args: TOriginalArgs) => R

    • R

    Parameters

    • map: Record<string, (...args: TOriginalArgs) => R>

      The source callback map

    • name: string

      Name of the property to chain

    • newCallback: TChainedFn

      A new callback to process the given name on the given map. If the same property got multiple callbacks, the final return value will be the return value of the latest callback

    Returns void

changeElementTag

  • changeElementTag<K>(element: HTMLElement, newTag: K): HTMLElementTagNameMap[K]
  • changeElementTag(element: HTMLElement, newTag: string): HTMLElement | null
  • Change tag of an HTML Element to a new one, and replace it from DOM tree

    Type parameters

    • K: keyof HTMLElementTagNameMap

    Parameters

    • element: HTMLElement

      The element to change tag

    • newTag: K

      New tag to change to

    Returns HTMLElementTagNameMap[K]

    The new element with new tag

  • Change tag of an HTML Element to a new one, and replace it from DOM tree

    Parameters

    • element: HTMLElement

      The element to change tag

    • newTag: string

      New tag to change to

    Returns HTMLElement | null

    The new element with new tag

clearEventDataCache

  • clearEventDataCache(event: PluginEvent, key?: string): void

clearProceedingSnapshots

  • clearProceedingSnapshots(snapshots: Snapshots<string>): void
  • clearProceedingSnapshots<T>(snapshots: Snapshots<T>, getLength: (snapshot: T) => number): void

clearProceedingSnapshotsV2

collapseNodes

  • collapseNodes(root: Node, start: Node, end: Node, canSplitParent: boolean): Node[]
  • Collapse nodes within the given start and end nodes to their common ancestor node, split parent nodes if necessary

    Parameters

    • root: Node

      The root node of the scope

    • start: Node

      The start node

    • end: Node

      The end node

    • canSplitParent: boolean

      True to allow split parent node there are nodes before start or after end under the same parent and the returned nodes will be all nodes from start through end after splitting False to disallow split parent

    Returns Node[]

    When canSplitParent is true, returns all node from start through end after splitting, otherwise just return start and end

collapseNodesInRegion

  • Collapse nodes within this region to their common ancestor node under this region

    Parameters

    • region: RegionBase

      The region to collapse nodes in.

    • nodesOrBlockElements: Node[] | BlockElement[]

      Nodes or block elements to collapse. When take BlockElement[] as input, start node of the first BlockElement and end node of the last BlockElement will be used as the nodes. All nodes not contained by the given region will be ignored.

    Returns Node[]

commitEntity

  • commitEntity(wrapper: HTMLElement, type: string, isReadonly: boolean, id?: string): void
  • Commit information of an entity (type, isReadonly, id) into the wrapper node as CSS Classes

    Parameters

    • wrapper: HTMLElement

      The entity wrapper element

    • type: string

      Entity type

    • isReadonly: boolean

      Whether this is a readonly entity

    • Optional id: string

      Optional Id of the entity

    Returns void

contains

  • contains(container: Node | null | undefined, contained: Node | null | undefined, treatSameNodeAsContain?: boolean): boolean
  • contains(container: Node | null | undefined, contained: Range | null | undefined): boolean
  • Test if a node contains another node

    Parameters

    • container: Node | null | undefined

      The container node

    • contained: Node | null | undefined

      The node to check if it is inside container

    • Optional treatSameNodeAsContain: boolean

      When container and contained are the same node, return true if this param is set to true, otherwise return false. Default value is false

    Returns boolean

    True if contained is inside container, or they are the same node when treatSameNodeAsContain is true. Otherwise false.

  • Test if a node contains a given range

    Parameters

    • container: Node | null | undefined

      The container node

    • contained: Range | null | undefined

      The range to check if it is inside container

    Returns boolean

    True if contained is inside container, otherwise false

convertDecimalsToAlpha

  • convertDecimalsToAlpha(decimal: number, isLowerCase?: boolean): string
  • Convert decimal numbers into english alphabet letters

    Parameters

    • decimal: number

      The decimal number that needs to be converted

    • Optional isLowerCase: boolean

      if true the roman value will appear in lower case

    Returns string

convertDecimalsToRoman

  • convertDecimalsToRoman(decimal: number, isLowerCase?: boolean): string

createArrayDefinition

  • createArrayDefinition<T>(itemDef: Definition<T>, isOptional?: boolean, minLength?: number, maxLength?: number, allowNull?: boolean): ArrayDefinition<T[]>
  • Create an array definition

    Type parameters

    • T

    Parameters

    • itemDef: Definition<T>

      Definition of each item of the related array

    • Optional isOptional: boolean

      Whether this property is optional

    • Optional minLength: number
    • Optional maxLength: number
    • Optional allowNull: boolean

      Allow the property to be null

    Returns ArrayDefinition<T[]>

    The array definition object

createBooleanDefinition

  • createBooleanDefinition(isOptional?: boolean, value?: boolean, allowNull?: boolean): BooleanDefinition

createDefaultHtmlSanitizerOptions

createElement

createEntityPlaceholder

  • createEntityPlaceholder(entity: Entity): HTMLElement

createNumberDefinition

  • createNumberDefinition(isOptional?: boolean, value?: number, minValue?: number, maxValue?: number, allowNull?: boolean): NumberDefinition
  • Create a number definition

    Parameters

    • Optional isOptional: boolean

      Whether this property is optional

    • Optional value: number

      Optional value of the number

    • Optional minValue: number

      Optional minimum value

    • Optional maxValue: number

      Optional maximum value

    • Optional allowNull: boolean

      Allow the property to be null

    Returns NumberDefinition

    The number definition object

createObjectDefinition

createRange

  • createRange(startNode: Node, endNode?: Node): Range
  • createRange(node: Node, offset: number | PositionType): Range
  • createRange(startNode: Node, startOffset: number | PositionType, endNode: Node, endOffset: number | PositionType): Range
  • createRange(rootNode: Node, startPath: number[], endPath?: number[]): Range
  • createRange(startPosition: NodePosition, endPosition?: NodePosition): Range
  • Create a range around the given node(s)

    Parameters

    • startNode: Node

      The start node to create range from

    • Optional endNode: Node

      The end node to create range from. If specified, the range will start before startNode and end after endNode, otherwise, the range will start before and end after the start node

    Returns Range

    A range start before the given node and end after the given node

  • Create a collapsed range at the given node and offset

    Parameters

    • node: Node

      The container node of the range

    • offset: number | PositionType

      The offset of the range, can be a number or value of PositionType

    Returns Range

    A range at the given node and offset

  • Create a range with the given start/end container node and offset

    Parameters

    • startNode: Node

      The start container node of the range

    • startOffset: number | PositionType

      The start offset of the range

    • endNode: Node

      The end container node of the range

    • endOffset: number | PositionType

      The end offset of the range

    Returns Range

    A range at the given start/end container node and offset

  • Create a range under the given rootNode with start and end selection paths

    Parameters

    • rootNode: Node

      The root node that the selection paths start from

    • startPath: number[]

      The selection path of the start position of the range

    • Optional endPath: number[]

      The selection path of the end position of the range

    Returns Range

    A range with the given start and end selection paths

  • Create a range with the start and end position

    Parameters

    • startPosition: NodePosition

      The start position of the range

    • Optional endPosition: NodePosition

      The end position of the range, if not specified, the range will be collapsed at start position

    Returns Range

    A range start at startPosition, end at endPosition, or startPosition when endPosition is not specified

createSnapshots

  • createSnapshots<T>(maxSize: number): Snapshots<T>

createStringDefinition

  • createStringDefinition(isOptional?: boolean, value?: string, allowNull?: boolean): StringDefinition

createVListFromRegion

  • createVListFromRegion(region: Region, includeSiblingLists?: boolean, startNode?: Node): VList | null
  • Create a VList object from the given region.

    Parameters

    • region: Region

      The region to get VList from

    • Optional includeSiblingLists: boolean

      True to also try get lists before and after the selection and merge them together, false to only include the list for the selected blocks

    • Optional startNode: Node

      (Optional) When specified, try get VList which will contain this node. If not specified, get VList from selection of this region

    Returns VList | null

deleteSelectedContent

  • deleteSelectedContent(root: HTMLElement, range: Range): NodePosition | null

extractClipboardEvent

  • deprecated

    Use extractClipboardItems and extractClipboardItemsForIE instead Extract a Clipboard event

    Parameters

    • event: ClipboardEvent

      The paste event

    • callback: (clipboardData: ClipboardData) => void

      Callback function when data is ready

    • Optional options: ExtractClipboardEventOption

      Options to retrieve more items from the event, including HTML string and other customized items

    • Optional rangeBeforePaste: Range

      Optional range to be removed when pasting in Android

    Returns void

    An object with the following properties: types: Available types from the clipboard event text: Plain text from the clipboard event image: Image file from the clipboard event html: Html string from the clipboard event. When set to null, it means there's no HTML found from the event. When set to undefined, it means can't retrieve HTML string, there may be HTML string but direct retrieving is not supported by browser.

extractClipboardItems

  • Extract clipboard items to be a ClipboardData object for IE

    Parameters

    • items: DataTransferItem[]

      The clipboard items retrieve from a DataTransfer object

    • Optional options: ExtractClipboardItemsOption
    • Optional pasteNativeEvent: boolean

    Returns Promise<ClipboardData>

    An object with the following properties: types: Available types from the clipboard event text: Plain text from the clipboard event image: Image file from the clipboard event html: Html string from the clipboard event. When set to null, it means there's no HTML found from the event. When set to undefined, it means can't retrieve HTML string, there may be HTML string but direct retrieving is not supported by browser.

extractClipboardItemsForIE

  • Extract clipboard items to be a ClipboardData object for IE

    Parameters

    Returns void

    An object with the following properties: types: Available types from the clipboard event text: Plain text from the clipboard event image: Image file from the clipboard event html: Html string from the clipboard event. When set to null, it means there's no HTML found from the event. When set to undefined, it means can't retrieve HTML string, there may be HTML string but direct retrieving is not supported by browser.

extractContentMetadata

  • extractContentMetadata(rootNode: HTMLElement): ContentMetadata | undefined

findClosestElementAncestor

  • findClosestElementAncestor(node: Node | null, root?: Node, selector?: string): HTMLElement | null
  • Find closest element ancestor start from the given node which matches the given selector

    Parameters

    • node: Node | null

      Find ancestor start from this node

    • Optional root: Node

      Root node where the search should stop at. The return value can never be this node

    • Optional selector: string

      The expected selector. If null, return the first HTML Element found from start node

    Returns HTMLElement | null

    An HTML element which matches the given selector. If the given start node matches the selector, returns the given node

fromHtml

  • fromHtml(html: string, ownerDocument: HTMLDocument): Node[]
  • deprecated

    Creates an HTML node array from html

    Parameters

    • html: string

      the html string to create HTML elements from

    • ownerDocument: HTMLDocument

      Owner document of the result HTML elements

    Returns Node[]

    An HTML node array to represent the given html string

getBlockElementAtNode

  • getBlockElementAtNode(rootNode: Node, node: Node | null): BlockElement | null
  • This produces a block element from a a node It needs to account for various HTML structure. Examples:

    1. <root><div>abc</div></root> This is most common the case, user passes in a node pointing to abc, and get back a block representing <div>abc</div>
    2. <root><p><br></p></root> Common content for empty block, user passes node pointing to <br>, and get back a block representing <p><br></p>
    3. <root>abc</root> Not common, but does happen. It is still a block in user's view. User passes in abc, and get back a start-end block representing abc NOTE: abc could be just one node. However, since it is not a html block, it is more appropriate to use start-end block although they point to same node
    4. <root><div>abc<br>123</div></root> A bit tricky, but can happen when user use Ctrl+Enter which simply inserts a <BR> to create a link break. There're two blocks: block1: 1) abc<br> block2: 123
    5. <root><div>abc<div>123</div></div></root> Nesting div and there is text node in same level as a DIV. Two blocks: 1) abc 2) <div>123</div>
    6. <root><div>abc<span>123<br>456</span></div></root> This is really tricky. Essentially there is a <BR> in middle of a span breaking the span into two blocks; block1: abc<span>123<br> block2: 456 In summary, given any arbitrary node (leaf), to identify the head and tail of the block, following rules need to be followed:
    7. to identify the head, it needs to crawl DOM tre left/up till a block node or BR is encountered
    8. same for identifying tail
    9. should also apply a block ceiling, meaning as it crawls up, it should stop at a block node

    Parameters

    • rootNode: Node

      Root node of the scope, the block element will be inside of this node

    • node: Node | null

      The node to get BlockElement start from

    Returns BlockElement | null

getBrowserInfo

  • getBrowserInfo(userAgent: string, appVersion: string, vendor?: string): BrowserInfo
  • Get current browser information from user agent string

    Parameters

    • userAgent: string

      The userAgent string of a browser

    • appVersion: string

      The appVersion string of a browser

    • Optional vendor: string

      The vendor string of a browser

    Returns BrowserInfo

    The BrowserInfo object calculated from the given userAgent and appVersion

getComputedStyle

  • getComputedStyle(node: Node, styleName: string): string

getComputedStyles

  • getComputedStyles(node: Node, styleNames?: string | string[]): string[]
  • Get computed styles of a node

    Parameters

    • node: Node

      The node to get computed styles from

    • styleNames: string | string[] = ...

      Names of style to get, can be a single name or an array. Default value is font-family, font-size, color, background-color

    Returns string[]

    An array of the computed styles

getDelimiterFromElement

  • getDelimiterFromElement(element: Node | null | undefined): Element | null

getEntityFromElement

  • getEntityFromElement(element: HTMLElement): Entity | null

getEntitySelector

  • getEntitySelector(type?: string, id?: string): string

getFirstLastBlockElement

  • getFirstLastBlockElement(rootNode: Node, isFirst: boolean): BlockElement | null

getFirstLeafNode

  • getFirstLeafNode(rootNode: Node): Node | null

getHtmlWithSelectionPath

  • getHtmlWithSelectionPath(rootNode: HTMLElement | DocumentFragment, range: Range | null): string
  • Get inner Html of a root node with a selection path which can be used for restore selection. The result string can be used by setHtmlWithSelectionPath() to restore the HTML and selection.

    Parameters

    • rootNode: HTMLElement | DocumentFragment

      Root node to get inner Html from

    • range: Range | null

      The range of selection. If pass null, no selection path will be added

    Returns string

    Inner HTML of the root node, followed by HTML comment contains selection path if the given range is valid

getInheritableStyles

  • getInheritableStyles(element: HTMLElement | null): StringMap

getInlineElementAtNode

getInnerHTML

  • getInnerHTML(node: HTMLElement | DocumentFragment): string

getIntersectedRect

  • getIntersectedRect(elements: HTMLElement[], additionalRects?: Rect[]): Rect | null
  • Get the intersected Rect of elements provided

    example

    The result of the following Elements Rects would be: { top: Element2.top, bottom: Element1.bottom, left: Element2.left, right: Element2.right } +-------------------------+ | Element 1 | | +-----------------+ | | | Element2 | | | | | | | | | | +-------------------------+ | | +-----------------+

    Parameters

    • elements: HTMLElement[]

      Elements to use.

    • additionalRects: Rect[] = []

      additional rects to use

    Returns Rect | null

    If the Rect is valid return the rect, if not, return null.

getLastLeafNode

  • getLastLeafNode(rootNode: Node): Node | null

getMetadata

  • getMetadata<T>(element: HTMLElement, definition?: Definition<T>, defaultValue?: T): T | null
  • Get metadata object from an HTML element

    Type parameters

    • T

    Parameters

    • element: HTMLElement

      The HTML element to get metadata object from

    • Optional definition: Definition<T>

      The type definition of this metadata used for validate this metadata object. If not specified, no validation will be performed and always return whatever we get from the element

    • Optional defaultValue: T

      The default value to return if the retrieved object cannot pass the validation, or there is no metadata object at all

    Returns T | null

    The strong-type metadata object if it can be validated, or null

getNextLeafSibling

  • getNextLeafSibling(rootNode: Node, startNode: Node, skipTags?: string[]): Node | null
  • This walks forwards DOM tree to get next meaningful node

    Parameters

    • rootNode: Node

      Root node to scope the leaf sibling node

    • startNode: Node

      current node to get sibling node from

    • Optional skipTags: string[]

      (Optional) tags that child elements will be skipped

    Returns Node | null

getObjectKeys

  • getObjectKeys<T>(obj: Record<T, any> | Partial<Record<T, any>>): T[]
  • Provide a strong-typed version of Object.keys()

    Type parameters

    • T: string | number | symbol

    Parameters

    • obj: Record<T, any> | Partial<Record<T, any>>

      The source object

    Returns T[]

    Array of keys

getPasteSource

getPasteType

  • getPasteType(pasteAsText: boolean, applyCurrentStyle: boolean, pasteAsImage: boolean): PasteType
  • Get the paste type that will be used corresponding to the configuration

    Parameters

    • pasteAsText: boolean

      Whether to paste as Text

    • applyCurrentStyle: boolean

      Whether to apply the current format to the content

    • pasteAsImage: boolean

      Whether to only paste the image

    Returns PasteType

getPendableFormatState

getPositionRect

getPreviousLeafSibling

  • getPreviousLeafSibling(rootNode: Node, startNode: Node, skipTags?: string[]): Node | null
  • This walks backwards DOM tree to get next meaningful node

    Parameters

    • rootNode: Node

      Root node to scope the leaf sibling node

    • startNode: Node

      current node to get sibling node from

    • Optional skipTags: string[]

      (Optional) tags that child elements will be skipped

    Returns Node | null

getRegionsFromRange

getSelectedBlockElementsInRegion

  • getSelectedBlockElementsInRegion(regionBase: RegionBase, createBlockIfEmpty?: boolean, deprecated?: boolean): BlockElement[]
  • Get all block elements covered by the selection under this region

    Parameters

    • regionBase: RegionBase

      The region to get block elements from

    • Optional createBlockIfEmpty: boolean

      When set to true, a new empty block element will be created if there is not any blocks in the region. Default value is false

    • Optional deprecated: boolean

      Deprecated parameter, not used

    Returns BlockElement[]

getSelectionPath

  • getSelectionPath(rootNode: Node, range: Range | null): SelectionPath | null

getSelectionRangeInRegion

  • getSelectionRangeInRegion(regionBase: RegionBase): Range | null

getStyles

  • getStyles(element: HTMLElement): Record<string, string>

getTableCellMetadata

getTableFormatInfo

  • getTableFormatInfo(table: HTMLTableElement): Required<TableFormat>

getTagOfNode

  • getTagOfNode(node: Node | null): string
  • Get the html tag of a node, or empty if it is not an element

    Parameters

    • node: Node | null

      The node to get tag of

    Returns string

    Tag name in upper case if the given node is an Element, or empty string otherwise

getTextContent

  • getTextContent(rootNode: Node): string

handleImagePaste

  • handleImagePaste(imageDataUri: string, fragment: DocumentFragment): void

handleTextPaste

  • handleTextPaste(text: string, position: NodePosition | null, fragment: DocumentFragment): void

isBlockElement

  • isBlockElement(node: Node): node is HTMLElement
  • Checks if the node is a block like element. Block like element are usually those P, DIV, LI, TD etc.

    Parameters

    • node: Node

      The node to check

    Returns node is HTMLElement

    True if the node is a block element, otherwise false

isCharacterValue

  • isCharacterValue(event: KeyboardEvent): boolean
  • Returns true when the event was fired from a key that produces a character value, otherwise false This detection is not 100% accurate. event.key is not fully supported by all browsers, and in some browsers (e.g. IE), event.key is longer than 1 for num pad input. But here we just want to improve performance as much as possible. So if we missed some case here it is still acceptable.

    Parameters

    • event: KeyboardEvent

      The keyboard event object

    Returns boolean

isCtrlOrMetaPressed

  • isCtrlOrMetaPressed(event: KeyboardEvent | MouseEvent): boolean
  • Check if Ctrl key (Windows) or Meta key (Mac) is pressed for the given Event

    Parameters

    • event: KeyboardEvent | MouseEvent

      A Keyboard event or Mouse event object

    Returns boolean

    True if Ctrl key is pressed on Windows or Meta key is pressed on Mac

isModifierKey

  • isModifierKey(event: KeyboardEvent): boolean

isNodeAfter

  • isNodeAfter(node1: Node, node2: Node): boolean
  • Checks if node1 is after node2

    Parameters

    • node1: Node

      The node to check if it is after another node

    • node2: Node

      The node to check if another node is after this one

    Returns boolean

    True if node1 is after node2, otherwise false

isNodeEmpty

  • isNodeEmpty(node: Node, trimContent?: boolean, shouldCountBrAsVisible?: boolean): boolean
  • Check if a given node has no visible content

    Parameters

    • node: Node

      The node to check

    • Optional trimContent: boolean

      Whether trim the text content so that spaces will be treated as empty. Default value is false

    • Optional shouldCountBrAsVisible: boolean

    Returns boolean

    True if there isn't any visible element inside node, otherwise false

isNodeInRegion

  • isNodeInRegion(region: RegionBase, node: Node): boolean

isPositionAtBeginningOf

  • isPositionAtBeginningOf(position: NodePosition, targetNode: Node | null): boolean
  • Check if this position is at beginning of the given node. This will return true if all nodes between the beginning of target node and the position are empty.

    Parameters

    • position: NodePosition

      The position to check

    • targetNode: Node | null

      The node to check

    Returns boolean

    True if position is at beginning of the node, otherwise false

isVoidHtmlElement

  • isVoidHtmlElement(node: Node): boolean

isWholeTableSelected

matchLink

  • matchLink(url: string): LinkData | null
  • Try to match a given string with link match rules, return matched link

    Parameters

    • url: string

      Input url to match

    Returns LinkData | null

    The matched link data, or null if no match found. The link data includes an original url and a normalized url

matchesSelector

  • matchesSelector(element: Node, selector: string): boolean

mergeBlocksInRegion

  • mergeBlocksInRegion(region: RegionBase, refNode: Node, targetNode: Node): void

moveChildNodes

  • moveChildNodes(target: Node, source?: Node, keepExistingChildren?: boolean): void
  • Replace all child nodes of the given target node to the child nodes of source node.

    Parameters

    • target: Node

      Target node, all child nodes of this node will be removed if keepExistingChildren is not set to true

    • Optional source: Node

      (Optional) source node, all child nodes of this node will be move to target node

    • Optional keepExistingChildren: boolean

      (Optional) When set to true, all existing child nodes of target will be kept

    Returns void

moveContentWithEntityPlaceholders

  • moveContentWithEntityPlaceholders(root: HTMLDivElement, entities: Record<string, HTMLElement>): DocumentFragment
  • Move content from a container into a new Document fragment, and try keep entities to be reusable by creating placeholder for them in the document fragment. If an entity is directly under root container, the whole entity can be reused and no need to move it at all. If an entity is not directly under root container, it is still reusable, but it may need some movement. In any case, entities will be replaced with a placeholder in the target document fragment. We will use an entity map (the "entities" parameter) to save the map from entity id to its wrapper element.

    Parameters

    • root: HTMLDivElement

      The root element

    • entities: Record<string, HTMLElement>

      A map from entity id to entity wrapper element

    Returns DocumentFragment

    A new document fragment contains all the content and entity placeholders

moveCurrentSnapshot

  • moveCurrentSnapshot<T>(snapshots: Snapshots<T>, step: number): T | null
  • Move current snapshot with the given step if can move this step. Otherwise no action and return null

    Type parameters

    • T = string

    Parameters

    • snapshots: Snapshots<T>

      The snapshots data structure to move

    • step: number

      The step to move

    Returns T | null

    If can move with the given step, returns the snapshot after move, otherwise null

Const moveCurrentSnapsnot

  • moveCurrentSnapsnot<T>(snapshots: Snapshots<T>, step: number): T | null

normalizeRect

  • normalizeRect(clientRect: DOMRect): Rect | null
  • A ClientRect of all 0 is possible. i.e. chrome returns a ClientRect of 0 when the cursor is on an empty p We validate that and only return a rect when the passed in ClientRect is valid

    Parameters

    • clientRect: DOMRect

    Returns Rect | null

parseColor

  • parseColor(color: string): [number, number, number] | null

queryElements

  • queryElements(container: ParentNode, selector: string, forEachCallback?: ((node: HTMLElement) => any) | null, scope?: QueryScope | CompatibleQueryScope, range?: Range): HTMLElement[]
  • Query HTML elements in the container by a selector string

    Parameters

    • container: ParentNode

      Container element to query from

    • selector: string

      Selector string to query

    • Optional forEachCallback: ((node: HTMLElement) => any) | null

      An optional callback to be invoked on each node in query result

    • scope: QueryScope | CompatibleQueryScope = ...

      The scope of the query, default value is QueryScope.Body

    • Optional range: Range

      The selection range to query with. This is required when scope is not Body

    Returns HTMLElement[]

    HTML Element array of the query result

readFile

  • readFile(file: File, callback: (dataUrl: string | null) => void): void
  • Read a file object and invoke a callback function with the data url of this file

    Parameters

    • file: File

      The file to read

    • callback: (dataUrl: string | null) => void

      the callback to invoke with data url of the file. If fail to read, dataUrl will be null

        • (dataUrl: string | null): void
        • Parameters

          • dataUrl: string | null

          Returns void

    Returns void

removeGlobalCssStyle

  • removeGlobalCssStyle(doc: Document, styleId: string): void

removeImportantStyleRule

  • removeImportantStyleRule(element: HTMLElement, styleProperties: string[]): void
  • Removes the css important rule from some css properties

    Parameters

    • element: HTMLElement

      The HTMLElement

    • styleProperties: string[]

      The css properties that important must be removed. Ex: ['background-color', 'background']

    Returns void

removeMetadata

  • removeMetadata<T>(element: HTMLElement, metadataKey?: string): void
  • Remove metadata from the given element if any

    Type parameters

    • T

    Parameters

    • element: HTMLElement

      The element to remove metadata from

    • Optional metadataKey: string

      The metadata key to remove, if none provided it will delete all metadata

    Returns void

restoreContentWithEntityPlaceholder

  • restoreContentWithEntityPlaceholder(source: ParentNode, target: HTMLElement, entities: Record<string, HTMLElement | KnownEntityItem> | null, insertClonedNode?: boolean): void
  • Restore HTML content from a document fragment that may contain entity placeholders.

    Parameters

    • source: ParentNode

      Source document fragment that contains HTML content and entity placeholders

    • target: HTMLElement

      Target container, usually to be editor root container

    • entities: Record<string, HTMLElement | KnownEntityItem> | null

      A map from entity id to entity wrapper, used for reusing existing DOM structure for entity

    • Optional insertClonedNode: boolean

      When pass true, merge with a cloned copy of the nodes from source fragment rather than the nodes themselves @default false

    Returns void

retrieveMetadataFromClipboard

safeInstanceOf

  • safeInstanceOf<T, W>(obj: any, typeName: T): obj is W[T]

sanitizePasteContent

saveTableCellMetadata

setColor

  • setColor(element: HTMLElement, color: string | ModeIndependentColor, isBackgroundColor: boolean, isDarkMode?: boolean, shouldAdaptTheFontColor?: boolean, darkColorHandler?: DarkColorHandler | null): void
  • Set text color or background color to the given element

    Parameters

    • element: HTMLElement

      The element to set color to

    • color: string | ModeIndependentColor

      The color to set, it can be a string of color name/value or a ModeIndependentColor object

    • isBackgroundColor: boolean

      Whether set background color or text color

    • Optional isDarkMode: boolean

      Whether current mode is dark mode. @default false

    • Optional shouldAdaptTheFontColor: boolean

      Whether the font color needs to be adapted to be visible in a dark or bright background color. @default false

    • Optional darkColorHandler: DarkColorHandler | null

      A dark color handler object. This is now required. We keep it optional only for backward compatibility. If it is not passed, color will not be set.

    Returns void

setGlobalCssStyles

  • setGlobalCssStyles(doc: Document, cssRule: string, styleId: string): void

setHtmlWithMetadata

setHtmlWithSelectionPath

  • setHtmlWithSelectionPath(rootNode: HTMLElement, html: string, trustedHTMLHandler?: TrustedHTMLHandler): Range | null
  • deprecated

    Use setHtmlWithMetadata instead Restore inner HTML of a root element from given html string. If the string contains selection path, remove the selection path and return a range represented by the path

    Parameters

    • rootNode: HTMLElement
    • html: string

      The HTML to restore

    • Optional trustedHTMLHandler: TrustedHTMLHandler

      An optional trusted HTML handler to convert HTML string to security string

    Returns Range | null

    A selection range if the html contains a valid selection path, otherwise null

setListItemStyle

  • setListItemStyle(element: HTMLLIElement, styles: string[], isCssStyle?: boolean): void
  • Set the Style of a List Item provided, with the styles that the inline child elements have If the child inline elements have different styles, it will not modify the styles of the list item

    Parameters

    • element: HTMLLIElement

      the LI Element to set the styles

    • styles: string[]

      The styles that should be applied to the element.

    • isCssStyle: boolean = true

      True means the given styles are CSS style names, false means they are HTML attributes @default true

    Returns void

setMetadata

  • setMetadata<T>(element: HTMLElement, metadata: T, def?: Definition<T>): boolean
  • Set metadata object into an HTML element

    Type parameters

    • T

    Parameters

    • element: HTMLElement

      The HTML element to set metadata object to

    • metadata: T

      The metadata object to set

    • Optional def: Definition<T>

      An optional type definition object used for validate this metadata object. If not specified, metadata will be set without validation

    Returns boolean

    True if metadata is set, otherwise false

setStyles

  • setStyles(element: HTMLElement, styles: Record<string, string>): void
  • Set styles to an HTML element. If styles are empty, remove 'style' attribute

    Parameters

    • element: HTMLElement

      The element to set styles

    • styles: Record<string, string>

      The styles to set, in name-value pair format

    Returns void

splitBalancedNodeRange

  • splitBalancedNodeRange(nodes: Node | Node[]): Node | null
  • Split parent node by a balanced node range

    Parameters

    • nodes: Node | Node[]

      The nodes to split from. If only one node is passed, split it from all its siblings. If two or nodes are passed, will split before the first one and after the last one, all other nodes will be ignored

    Returns Node | null

    The parent node of the given node range if the given nodes are balanced, otherwise null

splitParentNode

  • splitParentNode(node: Node, splitBefore: boolean): Node | null
  • Split parent node of the given node before/after the given node. When a parent node contains [A,B,C] and pass B as the given node, If split before, the new nodes will be [A][B,C] and returns [A]; otherwise, it will be [A,B][C] and returns [C].

    Parameters

    • node: Node

      The node to split before/after

    • splitBefore: boolean

      Whether split before or after

    Returns Node | null

    The new parent node

splitTextNode

  • splitTextNode(textNode: Text, offset: number, returnFirstPart: boolean): Text
  • Split a text node into two parts by an offset number, and return one of them

    Parameters

    • textNode: Text

      The text node to split

    • offset: number

      The offset number to split at

    • returnFirstPart: boolean

      True to return the first part, then the passed in textNode will become the second part. Otherwise return the second part, and the passed in textNode will become the first part

    Returns Text

toArray

  • toArray(collection: NamedNodeMap): Attr[]
  • toArray(collection: DataTransferItemList): DataTransferItem[]
  • toArray<T>(collection: NodeListOf<T>): T[]
  • toArray<T>(collection: HTMLCollectionOf<T>): T[]
  • toArray<T>(array: readonly T[]): T[]

unwrap

  • unwrap(node: Node): Node | null
  • Removes the node and keep all children in place, return the parentNode where the children are attached

    Parameters

    • node: Node

      the node to remove

    Returns Node | null

validate

  • validate<T>(input: any, def: Definition<T>): input is T
  • Validate the given object with a type definition object

    Type parameters

    • T

    Parameters

    • input: any

      The object to validate

    • def: Definition<T>

      The type definition object used for validation

    Returns input is T

    True if the object passed the validation, otherwise false

wrap

  • Wrap all the node with html and return the wrapped node, and put the wrapper node under the parent of the first node

    Type parameters

    • T: keyof HTMLElementTagNameMap

    Parameters

    • nodes: Node | Node[]

      The node or node array to wrap

    • Optional wrapper: T

      The wrapper HTML tag name

    Returns HTMLElementTagNameMap[T]

    The wrapper element

  • deprecated

    Wrap all the nodes with html and return the wrapped node, and put the wrapper node under the parent of the first node

    Parameters

    • nodes: Node | Node[]

      The node or node array to wrap

    • Optional wrapper: string

      The wrapper HTML string, default value is DIV

    Returns HTMLElement

    The wrapper element

  • Wrap all the nodes with html and return the wrapped node, and put the wrapper node under the parent of the first node

    Parameters

    • nodes: Node | Node[]

      The node or node array to wrap

    • Optional wrapper: HTMLElement

      The wrapper HTML element, default value is a new DIV element

    Returns HTMLElement

    The wrapper element

  • Wraps all the nodes with CreateElementData or an index of a known CreateElementData

    Parameters

    Returns HTMLElement

Generated using TypeDoc