### Install Rooster JS Editor Adapter Source: https://github.com/microsoft/roosterjs/blob/master/packages/roosterjs-editor-adapter/lib/README.md Install the adapter package using npm. ```sh npm install roosterjs-editor-adapter ``` -------------------------------- ### Example ContentDiv Styling Source: https://github.com/microsoft/roosterjs/wiki/Create-an-editor-using-Editor-class Example of how to style the contentDiv element to influence default editor formatting. ```html
``` -------------------------------- ### Build and Start Sample Editor Source: https://github.com/microsoft/roosterjs/blob/master/README.md Commands to build the source code and start the sample editor using Yarn or NPM. ```cmd yarn start ``` ```cmd npm start ``` -------------------------------- ### Install RoosterJS via NPM or Yarn Source: https://github.com/microsoft/roosterjs/blob/master/README.md Commands for installing the RoosterJS package using NPM or Yarn. ```cmd yarn add roosterjs ``` ```cmd yarn add roosterjs-content-model-core ``` ```cmd yarn add roosterjs-content-model-api ``` -------------------------------- ### Install Webpack Globally Source: https://github.com/microsoft/roosterjs/blob/master/README.md Command to install webpack globally, which may be required for running RoosterJS code. ```cmd yarn add webpack -g ``` -------------------------------- ### Initialize Editor without EditorAdapter (Before) Source: https://github.com/microsoft/roosterjs/blob/master/packages/roosterjs-editor-adapter/lib/README.md Example of initializing the Editor class before using the adapter. ```ts const options: EditorOptions = { plugins: [], /// Array of V8 plugins ... } new Editor(div, options); ``` -------------------------------- ### RoosterJs 8.x editor creation example Source: https://github.com/microsoft/roosterjs/wiki/RoosterJs-9 This is an example of how an editor was created using RoosterJs 8.x, before the introduction of the Content Model. ```typescript import { Editor } from 'roosterjs-editor-core'; const plugins = [new MyPlugin(), ...] const defaultFormat = { fontSize: '10pt', } const editor = new Editor(div, { defaultFormat: defaultFormat, plugins: plugins }); ``` -------------------------------- ### HTML Structure Example Source: https://github.com/microsoft/roosterjs/wiki/Selection-API An example HTML segment used to illustrate how the Position class properties, such as 'node' and 'offset', are determined. ```html
Text 1 Text 2
``` -------------------------------- ### initialContent Option Source: https://github.com/microsoft/roosterjs/wiki/Create-an-editor-using-Editor-class The `initialContent` option allows you to set the starting content of the editor when it is created. Content set this way is not undoable. ```APIDOC ### initialContent - **initialContent**: A string representing the content to be loaded into the editor upon creation. This content is not part of the undo history. Content can also be set later using `Editor.setContent()`, which is undoable. ``` -------------------------------- ### Customizing Tooltip with getTooltipCallback Source: https://github.com/microsoft/roosterjs/wiki/HyperLink-plugin Example of how to customize the tooltip text for hyperlinks by providing a callback function to the HyperLink constructor. ```APIDOC ## Example Usage ```typescript let hyperLinkPlugin = new HyperLink(href => 'Ctrl+Click to open link' + href); ``` This example creates a HyperLink plugin instance where the tooltip for each hyperlink will display 'Ctrl+Click to open link' followed by the actual link URL. ``` -------------------------------- ### Triggering a ContentChangedEvent with Source and Data Source: https://github.com/microsoft/roosterjs/wiki/Trigger-events-from-plugin This example demonstrates triggering a `ContentChangedEvent` using the shortcut method. It specifies 'Paste' as the change source and passes `clipboardData` as related data, allowing other plugins to understand the context of the change. ```typescript this.editor.triggerContentChangedEvent(ChangeSource.Paste, clipboardData); ``` -------------------------------- ### Handling Image Uploads with BeforePasteEvent Source: https://github.com/microsoft/roosterjs/wiki/BeforePasteEvent Example of how to handle image pasting by uploading the image and replacing a placeholder with the final image URL. This involves changing the paste option to HTML and modifying the fragment. ```typescript onPluginEvnet(event: PluginEvent) { // Check if the event is BeforePasteEvent if (event.eventType == PluginEventType.BeforePaste) { let beforePasteEvent = event; // Check if pasting image if (beforePasteEvent.pasteOption == PasteOption.PasteImage) { // Get image blob let image = beforePasteEvent.clipboardData.image; // Get placeholder DOM node let placeholder = this.createPlaceholder(image); // Modify the pasting content and option beforePasteEvent.fragment.appendChild(placeholder); beforePasteEvent.clipboardData.html = placeholder.outerHTML; beforePasteEvent.pasteOption = PasteOption.PasteHtml; // Start upload image and handle async result this.uploadImage(image).then((url: string) => { // Check editor availability in async callback if (this.editor) { // Create final IMG node let img = this.editor.getDocument().createElement('img') as HTMLImageElement; img.src = url; this.editor.replaceNode(placeholder, img); } }); } } } private createPlaceholder(img: File): Node { ... } private async uploadImage(img: File): Promise { ... } ``` -------------------------------- ### Selection Utilities Source: https://github.com/microsoft/roosterjs/wiki/Selection-API Provides utility functions for working with selections, such as getting the rectangular bounding box of a position. ```APIDOC ## Selection Utilities ### Get the rectangular bounding box of a position ```typescript function getPositionRect(position: NodePosition): Rect; ``` This function returns the top, bottom, left, and right coordinates of a given position. The left and right values will be the same as a position has no width. ``` -------------------------------- ### Paste Plugin Example Source: https://github.com/microsoft/roosterjs/wiki/Handle-more-DOM-events The Paste plugin demonstrates using addDomEventHandler to listen for the 'paste' event. Ensure the disposer function is called in the dispose method. ```typescript class Paste implements EditorPlugin { private pasteDisposer: () => void; public initialize(editor: Editor) { this.editor = editor; this.pasteDisposer = editor.addDomEventHandler('paste', this.onPaste); } public dispose() { this.pasteDisposer(); this.pasteDisposer = null; this.editor = null; } private onPaste = (event: Event) => { // Handle the event }; } ``` -------------------------------- ### Simple Editor Plugin Example Source: https://github.com/microsoft/roosterjs/wiki/Hello-plugin This plugin inserts an English word for each number typed into the editor. It handles KeyPress events, checks if the input is a number, and uses the editor's insertContent method. Ensure the editor instance is available before calling editor methods. ```typescript import { Editor, EditorPlugin } from 'roosterjs-editor-core'; import { PluginEvent, PluginEventType, PluginDomEvent } from 'roosterjs-editor-types'; import { createEditor } from 'roosterjs'; const NUMBERS = [ 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', ]; const KEY_0 = 0x30; const KEY_9 = 0x39; // This plugin will insert an English word when user is inputting numbers class MyPlugin implements EditorPlugin { private editor: Editor; getName() { return 'MyPlugin'; } initialize(editor: Editor) { this.editor = editor; } dispose() { this.editor = null; } onPluginEvent(event: PluginEvent) { if (event.eventType == PluginEventType.KeyPress) { let domEvent = event; let keyboardEvent = domEvent.rawEvent; if (keyboardEvent.which >= KEY_0 && keyboardEvent.which <= KEY_9) { let text = NUMBERS[keyboardEvent.which - KEY_0] + ' '; this.editor.insertContent(text); keyboardEvent.preventDefault(); } } } } let contentDiv = document.getElementById("contentDiv") as HTMLDivElement; let myPlugin = new MyPlugin(); let editor = createEditor(contentDiv, [ myPlugin ]); ``` -------------------------------- ### isPositionAtBeginningOf Source: https://github.com/microsoft/roosterjs/wiki/Selection-API Checks if a given position is at the beginning of a node. It returns true if there is no visible content between the start of the node and the given position, ignoring empty tags but considering visible elements. ```APIDOC ## isPositionAtBeginningOf ### Description Checks if a given position is at the beginning of a node. Returns true if there's no visible content between the start of the node and the position. Empty tags are ignored, but visible elements like IMG or LI will cause it to return false if they appear before the position. ### Signature ```typescript function isPositionAtBeginningOf(position: NodePosition, targetNode: Node): boolean; ``` ``` -------------------------------- ### GetContent Type Source: https://github.com/microsoft/roosterjs/wiki/RoosterJs-8-types Get current editor content as HTML string. ```APIDOC ## GetContent Type Get current editor content as HTML string. ``` -------------------------------- ### Selection API: getElementAtCursor Source: https://github.com/microsoft/roosterjs/wiki/Editor-API Gets an HTML element from the current cursor position. Optionally filters by expected tag names. ```APIDOC ## getElementAtCursor ### Description Get an HTML element from current cursor position. When expectedTags is not specified, return value is the current node (if it is HTML element) or its parent node (if current node is a Text node). When expectedTags is specified, return value is the first anscestor of current node which has one of the expected tags. If no element found within editor by the given tag, return null. ### Method Not specified (assumed to be a method call on an Editor instance) ### Parameters - **expectedTags**: Optional. An array of tag names to look for. ### Request Example ```javascript // Assuming 'editor' is an instance of the Editor class // Get the current element or its parent const element1 = editor.getElementAtCursor(); // Get the first ancestor with a 'P' or 'DIV' tag const element2 = editor.getElementAtCursor(['P', 'DIV']); ``` ### Response - **element**: The found HTML element, or null if none is found. ``` -------------------------------- ### Editor.insertContent() Source: https://github.com/microsoft/roosterjs/wiki/Modify-content Inserts a given HTML string into the editor at a specified position (beginning, end, or selection start). Options control replacement of selection, insertion on a new line, and cursor updates. Defaults are provided if options are omitted. ```APIDOC ## Editor.insertContent() ### Description Inserts a given HTML string into the editor at a specified position. Options allow control over replacing the current selection, inserting on a new line, and updating the cursor position. ### Method Signature ```typescript public insertContent(content: string, option?: InsertOption); ``` ### Parameters #### `content` (string) - The HTML string to insert. #### `option` (InsertOption, optional) - An object to configure insertion behavior. - `position` (ContentPosition): Where to insert the content. Defaults to `ContentPosition.SelectionStart`. - `replaceSelection` (boolean): Whether to replace the current selection. Defaults to `true`. - `insertOnNewLine` (boolean): Whether to insert the content on a new line. Defaults to `false`. - `updateCursor` (boolean): Whether to update the cursor position after insertion. Defaults to `true`. ### Default Options ```typescript { position: ContentPosition.SelectionStart, updateCursor: true, replaceSelection: true, insertOnNewLine: false, } ``` ``` -------------------------------- ### Triggering a BeforePasteEvent Source: https://github.com/microsoft/roosterjs/wiki/Trigger-events-from-plugin This example shows how the Paste plugin uses `triggerEvent` to fire a `BeforePasteEvent`. This allows other plugins to intercept and modify the paste content before it is applied to the editor. ```typescript let event: BeforePasteEvent = { eventType: PluginEventType.BeforePaste, clipboardData: clipboardData, fragment: fragment, pasteOption: pasteOption, }; this.editor.triggerEvent(event, true /*broadcast*/); ``` -------------------------------- ### Fail Fast in KeyDown Event Handler Source: https://github.com/microsoft/roosterjs/wiki/Best-practice Prioritize cheap checks before expensive DOM operations in event handlers. This example shows checking for KeyDown events and specific keys before attempting to auto-link. ```typescript public onPluginEvent(event: PluginEvent): void { switch (event.eventType) { case PluginEventType.KeyDown: let keyboardEvt = (event as PluginDomEvent).rawEvent as KeyboardEvent; if (keyboardEvt.which == KEY_ENTER || keyboardEvt.which == KEY_SPACE) { this.autoLink(event); // We will do DOM operation here } break; } } ``` -------------------------------- ### Initialize Editor with Options and Plugins Source: https://github.com/microsoft/roosterjs/wiki/Create-an-editor-using-Editor-class Use this snippet to create a new Editor instance. Configure plugins, default formatting, initial content, and undo/redo behavior through the `EditorOptions` object. Ensure the target DOM element exists and is accessible. ```typescript import { Editor, EditorPlugin, ContentEdit, DefaultShortcut, Paste, HyperLink, DefaultFormat, Undo, EditorOptions, } from 'roosterjs'; class MyPlugin implements EditorPlugin { initialize() {} dispose() {} } window.onload = () => { let plugins: EditorPlugin[] = [ new ContentEdit(), new DefaultShortcut(), new Paste(true /*useDirectPaste*/), new HyperLink(href => 'Ctrl+click to open link ' + href), new MyPlugin(), ]; let defaultFormat: DefaultFormat = { bold: true, fontFamily: 'Arial', textColor: 'green', }; let initialContent = '

Welcome to RoosterJs
'; let undo = new Undo(true /*preserveSnapshot*/); let options: EditorOptions = { plugins: plugins, defaultFormat: defaultFormat, initialContent: initialContent, undo: undo, }; let contentDiv = document.getElementById('div') as HTMLDivElement; let editor = new Editor(contentDiv, options); } ``` -------------------------------- ### Create HyperLink Plugin Instance Source: https://github.com/microsoft/roosterjs/wiki/HyperLink-plugin Manually create an instance of the HyperLink plugin using its constructor. The constructor accepts an optional callback for customizing tooltips and an optional target window name. ```APIDOC ## Constructor ```typescript constructor( private getTooltipCallback: (href: string) => string = href => href, private target?: string ); ``` ### Parameters * `getTooltipCallback` (function): A callback function that takes the hyperlink's href as input and returns the string to be displayed in the tooltip. Defaults to returning the href itself. * `target` (string, optional): The target window name for opening the hyperlink when Ctrl+Clicked. Defaults to `_blank`. ``` -------------------------------- ### Create ImageResize Plugin Instance Source: https://github.com/microsoft/roosterjs/wiki/ImageResize-plugin Instantiate the ImageResize plugin with optional parameters for minimum width, minimum height, selection border color, and forcing aspect ratio preservation. ```typescript constructor( private minWidth: number = 10, private minHeight: number = 10, private selectionBorderColor: string = '#DB626C', private forcePreserveRatio: boolean = false ); ``` -------------------------------- ### isDisposed Source: https://github.com/microsoft/roosterjs/wiki/RoosterJs-8-types Gets whether this editor instance has been disposed. ```APIDOC ## isDisposed ### Description Gets whether this editor instance has been disposed. ### Method (Implicitly a method call on an IEditor instance) ### Parameters None ### Response - **boolean**: True if the editor is disposed, false otherwise. ``` -------------------------------- ### Initialize Editor with EditorAdapter Source: https://github.com/microsoft/roosterjs/blob/master/packages/roosterjs-editor-adapter/lib/README.md Replace the Editor class with EditorAdapter and configure legacy and v9 plugins. ```ts const options: EditorAdapterOptions = { legacyPlugins: [], /// Array of V8 plugins plugins: [], /// Array of v9 plugins ... } return new EditorAdapter(div, options); ``` -------------------------------- ### Selection API: getCursorRect Source: https://github.com/microsoft/roosterjs/wiki/Editor-API Gets a rectangle representing the location of the cursor. ```APIDOC ## getCursorRect ### Description Get a rect representing the location of the cursor. ### Method Not specified (assumed to be a method call on an Editor instance) ### Request Example ```javascript // Assuming 'editor' is an instance of the Editor class const cursorRect = editor.getCursorRect(); ``` ### Response - **cursorRect**: A DOMRect object representing the cursor's location. ``` -------------------------------- ### Import EditorAdapter Source: https://github.com/microsoft/roosterjs/blob/master/packages/roosterjs-editor-adapter/lib/README.md Import the EditorAdapter class into your file when creating the editor instance. ```js import { EditorAdapter } from 'roosterjs-editor-adapter'; ``` -------------------------------- ### getBlockTraverser Source: https://github.com/microsoft/roosterjs/wiki/Editor-API Obtains a content traverser for the current block element, starting from a specified position. ```APIDOC ## getBlockTraverser ### Description Get a content traverser for current block element start from specified position. ### Method Not specified (assumed to be a method call on an Editor instance) ### Endpoint N/A (SDK method) ### Parameters - startPosition (any): The starting position for the traverser. ### Request Example ```javascript const traverser = editor.getBlockTraverser(startPosition); ``` ### Response - (Traverser): A traverser object for the current block element. ``` -------------------------------- ### getSelectionPath Source: https://github.com/microsoft/roosterjs/wiki/RoosterJs-8-types Gets the current selection in a serializable format by performing a live pull on the selection. ```APIDOC ## getSelectionPath ### Description Get current selection in a serializable format It does a live pull on the selection. ### Method (Not specified, likely a method call on an IEditor instance) ### Parameters (Not specified) ### Request Example (Not specified) ### Response (Not specified) ``` -------------------------------- ### Create a Custom HelloRooster Plugin Source: https://github.com/microsoft/roosterjs/blob/master/README.md This plugin triggers an alert when the 'a' key is pressed. It demonstrates how to implement a basic editor plugin by handling input events. ```typescript class HelloRooster implements EditorPlugin { getName() { return 'HelloRooster'; } initialize(editor: IEditor) {} dispose() {} onPluginEvent(e: PluginEvent) { if (e.eventType == 'input' && e.rawEvent.which == 65) { alert('Hello Rooster'); } } } ``` -------------------------------- ### ImageResize Plugin Constructor Source: https://github.com/microsoft/roosterjs/wiki/ImageResize-plugin Instantiate the ImageResize plugin with optional parameters to customize its behavior. ```APIDOC ## ImageResize Constructor ### Description Creates an instance of the ImageResize plugin. ### Parameters - **minWidth** (number) - Optional - Minimum width of the image during resize. Defaults to 10px. - **minHeight** (number) - Optional - Minimum height of the image during resize. Defaults to 10px. - **selectionBorderColor** (string) - Optional - Color of the resizing border and handle. Defaults to '#DB626C'. - **forcePreserveRatio** (boolean) - Optional - Whether to force the image to preserve its width/height ratio during resizing. Defaults to false. ``` -------------------------------- ### Node API: collapseNodes Source: https://github.com/microsoft/roosterjs/wiki/Editor-API Collapses nodes within the given start and end nodes to their common ancestor. ```APIDOC ## collapseNodes ### Description Collapse nodes within the given start and end nodes to their common ascenstor node. ### Method Not specified (assumed to be a method call on an Editor instance) ### Parameters - **startNode**: The starting node. - **endNode**: The ending node. ### Request Example ```javascript // Assuming 'editor' is an instance of the Editor class // and 'start' and 'end' are DOM Node objects editor.collapseNodes(start, end); ``` ### Response Not specified. ``` -------------------------------- ### Create Editor with Initial Content Source: https://github.com/microsoft/roosterjs/wiki/Create-an-editor-using-createEditor()-API Set initial content for the editor before user interaction. Content set this way is not undoable. Ensure the contentDiv element is correctly obtained. ```typescript let contentDiv = document.getElementById("contentDiv") as HTMLDivElement; let editor = createEditor( contentDiv, null, "
Welcome to RoosterJs!
" ); ``` -------------------------------- ### Get Format State Function Signature Source: https://github.com/microsoft/roosterjs/wiki/Show-format-state This is the function signature for `getFormatState`. It takes an optional `PluginEvent` for caching. ```typescript function getFormatState(editor: Editor, event?: PluginEvent): FormatState; ``` -------------------------------- ### Run Tests from Command Line Source: https://github.com/microsoft/roosterjs/blob/master/README.md Command to run all tests using Yarn. ```cmd yarn test ``` -------------------------------- ### Selection API: getFocusedPosition Source: https://github.com/microsoft/roosterjs/wiki/Editor-API Gets the current focused position within the editor. Returns null if the editor does not have focus. ```APIDOC ## getFocusedPosition ### Description Get current focused position. Return null if editor doesn't have focus at this time. ### Method Not specified (assumed to be a method call on an Editor instance) ### Request Example ```javascript // Assuming 'editor' is an instance of the Editor class const focusedPosition = editor.getFocusedPosition(); ``` ### Response - **focusedPosition**: The current focused Position object, or null. ``` -------------------------------- ### Position Creation Source: https://github.com/microsoft/roosterjs/wiki/Selection-API Demonstrates various ways to create a Position object, including cloning, normalizing, from node/offset, from node/PositionType, and from a Range. ```APIDOC ## Position Constructors ### Clone from an existing Position ```typescript class Position { constructor(position: NodePosition); } ``` ### Create from a node and an offset value ```typescript class Position { constructor(node: Node, offset: number); } ``` ### Create from a node and a PositionType value ```typescript class Position { constructor(node: Node, positionType: PositionType); } const enum PositionType { Begin = 0, End = -1, Before = -2, After = -3, } ``` ### Create from a Range ```typescript class Position { static getStart(range: Range): NodePosition; static getEnd(range: Range): NodePosition; } ``` ``` -------------------------------- ### cacheGetContentSearcher Source: https://github.com/microsoft/roosterjs/wiki/Event-Cache-API A wrapper function to get a PositionContentSearcher instance from the event cache. It uses `Editor.getContentSearcherOfCursor()` as the getter if the object is not already cached. ```APIDOC ## cacheGetContentSearcher ### Description A wrapper function to get a PositionContentSearcher instance from the event cache. It uses `Editor.getContentSearcherOfCursor()` as the getter if the object is not already cached. ### Function Signature ```typescript function cacheGetContentSearcher( event: PluginEvent, editor: Editor ): PositionContentSearcher; ``` ### Parameters #### Path Parameters - **event** (PluginEvent) - The event object. - **editor** (Editor) - The editor instance. ### Returns - **PositionContentSearcher** - The cached or newly created PositionContentSearcher instance. ``` -------------------------------- ### Initialize RoosterJS Editor and Basic Formatting Source: https://github.com/microsoft/roosterjs/blob/master/README.md This HTML and JavaScript snippet shows how to create a RoosterJS editor instance, set its content, and attach event listeners to buttons for toggling bold, italic, and underline formatting. ```html
``` -------------------------------- ### Wrapper for PositionContentSearcher Source: https://github.com/microsoft/roosterjs/wiki/Event-Cache-API A wrapper function to get a `PositionContentSearcher` instance from the event cache. It uses `Editor.getContentSearcherOfCursor()` as the getter if the object is not already cached. ```typescript const CONTENTSEARCHER_KEY = 'CONTENTSEARCHER'; function cacheGetContentSearcher( event: PluginEvent, editor: Editor ): PositionContentSearcher { return cacheGetEventData(event, CONTENTSEARCHER_KEY, () => editor.getContentSearcherOfCursor()); } ``` ```typescript let searcher = cacheGetContentSearcher(event, editor); ``` -------------------------------- ### Compatible Enum Definition in roosterjs-editor-types-compatible Source: https://github.com/microsoft/roosterjs/wiki/Work-with-isolatedModules This is an example of a compatible enum definition provided by the 'roosterjs-editor-types-compatible' package, designed to work with the '--isolatedModules' flag. ```typescript /** * enum for setting block alignment, used by setAlignment API */ export declare enum CompatibleAlignment { /** * Align left */ Left = 0, /** * Align center */ Center = 1, /** * Align right */ Right = 2 } ``` -------------------------------- ### cacheGetElementAtCursor Source: https://github.com/microsoft/roosterjs/wiki/Event-Cache-API A wrapper function to get an HTMLElement at the cursor position from the event cache. It uses `Editor.getElementAtCursor(selector)` as the getter if the object is not already cached. ```APIDOC ## cacheGetElementAtCursor ### Description A wrapper function to get an HTMLElement at the cursor position from the event cache. It uses `Editor.getElementAtCursor(selector)` as the getter if the object is not already cached. ### Function Signature ```typescript default function cacheGetElementAtCursor( editor: Editor, event: PluginEvent, selector: string ): HTMLElement; ``` ### Parameters #### Path Parameters - **editor** (Editor) - The editor instance. - **event** (PluginEvent) - The event object. - **selector** (string) - The CSS selector to find the element. ### Returns - **HTMLElement** - The cached or newly created HTMLElement. ``` -------------------------------- ### Watermark Plugin Constructor Source: https://github.com/microsoft/roosterjs/wiki/Watermark-plugin This section details how to create an instance of the Watermark plugin. The plugin can be added to the editor using the `createEditor()` API or the Editor class constructor. The constructor accepts the watermark text and an optional format object. ```APIDOC ## Watermark Plugin Constructor ### Description Creates an instance of the Watermark plugin. ### Signature ```typescript constructor(watermark: string, format?: DefaultFormat) ``` ### Parameters #### watermark - **watermark** (string) - Required - The string to display as the watermark text. #### format - **format** (DefaultFormat) - Optional - The formatting options for the watermark text. If not provided, default formatting (14px font size, #AAAAAA color) will be used. ### DefaultFormat Interface ```typescript interface DefaultFormat { fontFamily?: string; fontSize?: string; textColor?: string; backgroundColor?: string; bold?: boolean; italic?: boolean; underline?: boolean; } ``` ``` -------------------------------- ### isPositionAtBeginning Source: https://github.com/microsoft/roosterjs/wiki/RoosterJs-8-types Checks if the current cursor position is at the beginning of the editor content. ```APIDOC ## isPositionAtBeginning ### Description Checks if the current cursor position is at the beginning of the editor content. ### Method (Implicitly a method call on an IEditor instance) ### Parameters None ### Response - **boolean**: True if the cursor is at the beginning, false otherwise. ``` -------------------------------- ### Create a new Content Model based editor instance Source: https://github.com/microsoft/roosterjs/wiki/RoosterJs-9 Use the Editor class from 'roosterjs-content-model-core' to create a new instance. Configure default segment format, plugins implementing the new EditorPlugin interface, and initial content model. ```typescript import { Editor } from 'roosterjs-content-model-core'; const editor = new Editor(div, { defaultSegmentFormat: { fontSize: '10pt', }, plugins: [ new MyPlugin(), ...], initialModel: { ... } }); ``` -------------------------------- ### Get Position Rectangle Source: https://github.com/microsoft/roosterjs/wiki/Selection-API Retrieves the bounding rectangle (top, bottom, left, right) for a given Position. The left and right values will be identical as a position has no width. ```typescript function getPositionRect(position: NodePosition): Rect; ``` -------------------------------- ### Create Editor with Additional Plugins Source: https://github.com/microsoft/roosterjs/wiki/Create-an-editor-using-createEditor()-API Use this to add extra plugins like Watermark to the editor. Ensure the contentDiv element is correctly obtained. ```typescript let contentDiv = document.getElementById("contentDiv") as HTMLDivElement; let editor = createEditor( contentDiv, [ new Watermark("Please type here") ] ); ``` -------------------------------- ### RoosterJS Editor Initialization with Compatible Enum Source: https://github.com/microsoft/roosterjs/wiki/Work-with-isolatedModules This code shows how to correctly initialize a RoosterJS editor and use a compatible enum for alignment, resolving the TypeScript error when using '--isolatedModules'. ```typescript import * as RoosterJs from 'roosterjs'; let div: HTMLDivElement = document.createElement('div'); const editor = new RoosterJs.Editor(div); RoosterJs.setAlignment(editor, RoosterJs.CompatibleAlignment.Center); ``` -------------------------------- ### Create Position from Range Start/End Source: https://github.com/microsoft/roosterjs/wiki/Selection-API Creates a Position object from the start or end of a DOM Range. This is a convenient way to extract Position information from existing Range objects. ```typescript class Position { ... static getStart(range: Range): NodePosition; static getEnd(range: Range): NodePosition; } ``` -------------------------------- ### getStyleBasedFormatState Source: https://github.com/microsoft/roosterjs/wiki/RoosterJs-8-types Retrieves the format state based on the current selection's styles. ```APIDOC ## getStyleBasedFormatState ### Description Get style based format state from current selection. ### Method (Not specified, likely a method call on an IEditor instance) ### Parameters (Not specified) ### Request Example (Not specified) ### Response (Not specified) ``` -------------------------------- ### Remove Watermark from Editor Content Source: https://github.com/microsoft/roosterjs/wiki/ExtractContentEvent Example of how to use ExtractContentEvent to remove a watermark element from the editor's content. This involves replacing a specific HTML pattern with an empty string. ```typescript const WATERMARK_SPAN_ID = '_rooster_watermarkSpan'; const WATERMARK_REGEX = new RegExp( `]*id=['"]?${WATERMARK_SPAN_ID}['"]?[^>]*>[^<]*`, 'ig' ); private removeWartermarkFromHtml(event: ExtractContentEvent) { let content = event.content; content = content.replace(WATERMARK_REGEX, ''); event.content = content; } ``` -------------------------------- ### Check if Position is at Beginning of Node Source: https://github.com/microsoft/roosterjs/wiki/Selection-API Use this function to determine if a given position is at the start of a node, ignoring empty tags but considering visible elements. See isNodeEmpty() for more details. ```typescript function isPositionAtBeginningOf(position: NodePosition, targetNode: Node): boolean; ``` -------------------------------- ### Handling ContentChangedEvent for Hyperlinks Source: https://github.com/microsoft/roosterjs/wiki/HyperLink-plugin Demonstrates how to handle the `ContentChangedEvent` to detect when new hyperlinks are created, either automatically or via the `createLink()` API. ```APIDOC ## Event Handling ```typescript onPluginEvent(event: PluginEvent) { if (event.eventType == PluginEventType.ContentChanged) { let contentChangedEvent = event; if ( contentChangedEvent.source == ChangeSource.AutoLink || contentChangedEvent.source == ChangeSource.CreateLink ) { let hyperLinkNode = contentChangedEvent.data; // Add your code here to do customized handling } } } ``` This code snippet shows how to listen for `ContentChangedEvent`s where the source is either `ChangeSource.AutoLink` or `ChangeSource.CreateLink`. The `event.data` will contain the newly created hyperlink node (`` element), allowing for custom actions. ``` -------------------------------- ### TableResize Plugin Constructor Source: https://github.com/microsoft/roosterjs/wiki/TableResize-plugin Instantiate the TableResize plugin. The 'isRtl' parameter is deprecated and no longer required as the plugin auto-detects RTL mode. ```APIDOC ## Constructor ### Description Creates an instance of the TableResize plugin. ### Parameters This constructor previously accepted an optional `isRtl` boolean parameter, but it has been deprecated since version 6.8.0. The plugin now automatically detects the Right-to-Left (RTL) mode. ### Code Example ```typescript import { TableResize } from 'roosterjs-editor-plugins/lib/TableResize'; // Create an instance of the plugin (no parameters needed) const tableResizePlugin = new TableResize(); // Add the plugin to the editor // editor.addPlugin(tableResizePlugin); ``` ``` -------------------------------- ### Wrapper for Element at Cursor Source: https://github.com/microsoft/roosterjs/wiki/Event-Cache-API A wrapper function to get an element at the cursor position matching a given selector from the event cache. It uses `Editor.getElementAtCursor()` as the getter if the object is not already cached. ```typescript const CACHE_KEY_PREFIX = 'GET_ELEMENT_AT_CURSOR_'; default function cacheGetElementAtCursor( editor: Editor, event: PluginEvent, selector: string ): HTMLElement { return cacheGetEventData(event, CACHE_KEY_PREFIX + selector, () => editor.getElementAtCursor(selector) ); } ``` -------------------------------- ### select Source: https://github.com/microsoft/roosterjs/wiki/RoosterJs-8-types Selects content within the editor based on a specified range. ```APIDOC ## select ### Description Selects content within the editor based on a specified range. ### Method (Implicitly a method call on an IEditor instance) ### Parameters #### Request Body - **range** (Range) - Required - The range object defining the content to select. ``` -------------------------------- ### Overwrite Default ContentEdit Features Source: https://github.com/microsoft/roosterjs/wiki/ContentEdit-plugin Demonstrates how to get the default ContentEdit features, modify a specific feature (autoBullet), and then create a new ContentEdit plugin instance with the customized settings. ```typescript let features = getDefaultContentEditFeatures(); features.autoBullet = false; let contentEditPlugin = new ContentEdit(features); ``` -------------------------------- ### Use RoosterJs via NPM Packages in TypeScript Source: https://github.com/microsoft/roosterjs/wiki/Preparation Install RoosterJs as an NPM package and import it in your TypeScript project for a streamlined development workflow. Ensure 'roosterjs' is listed in your project's dependencies. ```json { "name": "editor", "version": "1.0.0", "description": "", "main": "index.js", "dependencies": { "roosterjs": "^6.4.1" } } ``` ```typescript import * as RoosterJs from 'roosterjs'; let contentDiv = document.getElementById("contentDiv") as HTMLDivElement; let editor = RoosterJs.createEditor(contentDiv); ``` -------------------------------- ### PickerPluginOptions Interface Source: https://github.com/microsoft/roosterjs/wiki/RoosterJs-8-types Interface for configuring the PickerPlugin. ```APIDOC ## PickerPluginOptions Interface ### Description Options for PickerPlugin. ### Reference https://microsoft.github.io/roosterjs/docs/interfaces/roosterjs_editor_types.pickerpluginoptions.html ``` -------------------------------- ### Watermark Plugin Constructor Source: https://github.com/microsoft/roosterjs/wiki/Watermark-plugin Instantiate the Watermark plugin with the desired watermark text and optional formatting. The default format uses a font size of 14px and a color of #AAAAAA if not specified. ```typescript interface DefaultFormat { fontFamily?: string; fontSize?: string; textColor?: string; backgroundColor?: string; bold?: boolean; italic?: boolean; underline?: boolean; } constructor(private watermark: string, private format?: DefaultFormat); ``` -------------------------------- ### runAsync Source: https://github.com/microsoft/roosterjs/wiki/Editor-API Executes a callback function asynchronously. ```APIDOC ## runAsync ### Description Run a callback function asynchronously. ### Method Not specified (assumed to be a method call on an Editor instance) ### Endpoint N/A (SDK method) ### Parameters - callback (function): The asynchronous function to execute. ### Request Example ```javascript editor.runAsync(asyncCallback); ``` ### Response N/A ``` -------------------------------- ### Plugin Order and Exclusive Event Handling Source: https://github.com/microsoft/roosterjs/wiki/Hello-plugin The order in which plugins are added to the editor determines which plugin handles an event exclusively if multiple plugins return `true` from `willHandleEventExclusively`. The first plugin in the list gets precedence. ```typescript let plugins = [ plugin1, plugin2 ]; let editor = createEditor(div, plugins); ``` -------------------------------- ### Create HyperLink Plugin Instance Source: https://github.com/microsoft/roosterjs/wiki/HyperLink-plugin Manually create an instance of the HyperLink plugin using its constructor. This plugin is typically included by default when creating an editor. ```typescript constructor( private getTooltipCallback: (href: string) => string = href => href, private target?: string ); ``` -------------------------------- ### replaceTextBeforeCursorWithNode Usage Source: https://github.com/microsoft/roosterjs/wiki/RoosterJs-7 To replace text before the cursor with a node, first obtain a content searcher using `Editor.getContentSearcherOfPosition()`. Then, get the range from the text using `searcher.getRangeFromText(text, exactMatch)`. Finally, use `replaceWithNode(editor, range, node, exactMatch)` to perform the replacement. ```APIDOC ## replaceTextBeforeCursorWithNode ### Description To replace text before the cursor with a node, first get the content searcher for the current position using `Editor.getContentSearcherOfPosition()`. Then, determine the range of the text to be replaced using `searcher.getRangeFromText(text, exactMatch)`. Finally, call `replaceWithNode(editor, range, node, exactMatch)` to perform the replacement. ### Method N/A (This describes a sequence of operations) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### createLink Source: https://github.com/microsoft/roosterjs/wiki/Format-API Inserts a hyperlink at the cursor position. If there is a selection, the hyperlink is applied to the selection; otherwise, it's inserted at the cursor. ```APIDOC ## createLink ### Description Insert a hyperlink at cursor. When there is a selection, hyperlink will be applied to the selection, otherwise a hyperlink will be inserted to the cursor position. ### Method [Method signature or relevant details if available, otherwise omit] ### Parameters [Parameters if available, otherwise omit] ### Request Example [Request example if available, otherwise omit] ### Response [Response details if available, otherwise omit] ``` -------------------------------- ### getUndoState Source: https://github.com/microsoft/roosterjs/wiki/RoosterJs-8-types Checks if there is an available undo or redo snapshot. ```APIDOC ## getUndoState ### Description Checks if there is an available undo or redo snapshot. ### Method (Implicitly a method call on an IEditor instance) ### Parameters None ### Response - **boolean**: True if an undo/redo snapshot is available, false otherwise. ``` -------------------------------- ### performAutoComplete Source: https://github.com/microsoft/roosterjs/wiki/Editor-API Performs an auto-complete action, saves a content snapshot, and triggers a ContentChangedEvent. ```APIDOC ## performAutoComplete ### Description Perform an auto complete action in the callback, save a snapshot of content before the action, and trigger ContentChangedEvent with the change source if specified. ### Method Not specified (assumed to be a method call on an Editor instance) ### Endpoint N/A (SDK method) ### Parameters - autoCompleteCallback (function): The callback function to perform the auto-complete action. - changeSource (string): Optional. The source of the content change. ### Request Example ```javascript editor.performAutoComplete(autoCompleteCallback, 'changeSource'); ``` ### Response N/A ``` -------------------------------- ### defaultFormat Option Source: https://github.com/microsoft/roosterjs/wiki/Create-an-editor-using-Editor-class The `defaultFormat` option allows you to define the initial formatting for the editor when there is no initial content or the first line is empty. ```APIDOC ### defaultFormat - **defaultFormat**: An object of type `DefaultFormat` to specify the default text styling. This includes properties like `fontFamily`, `fontSize`, `textColor`, `backgroundColor`, `bold`, `italic`, and `underline`. ```typescript interface DefaultFormat { fontFamily?: string; fontSize?: string; textColor?: string; backgroundColor?: string; bold?: boolean; italic?: boolean; underline?: boolean; } ``` If not specified, these properties default to values derived from the `contentDiv`'s CSS styles or default browser behavior. The default format is applied only when the editor is empty or the initial content is empty. ``` -------------------------------- ### FormatState Interface Source: https://github.com/microsoft/roosterjs/wiki/RoosterJs-8-types The format state of a given node. ```APIDOC ## FormatState Interface ### Description The format state of a given node. ### Removed Members - **canUndo**: Moved to [EditorUndoState](https://microsoft.github.io/roosterjs/docs/interfaces/roosterjs_editor_types.editorundostate.html) interface. - **canRedo**: Moved to [EditorUndoState](https://microsoft.github.io/roosterjs/docs/interfaces/roosterjs_editor_types.editorundostate.html) interface. ### New Base Interfaces - **EditorUndoState**: Specify if editor can undo/redo an editing operation. ``` -------------------------------- ### Editor Class Constructor Source: https://github.com/microsoft/roosterjs/wiki/Create-an-editor-using-Editor-class The Editor class constructor allows for direct instantiation of an editor with fine-grained control over its behavior and appearance. It takes a contentDiv element and an optional EditorOptions object. ```APIDOC ## Constructor of Editor ```typescript constructor(contentDiv: HTMLDivElement, options: EditorOptions = {}); ``` - **contentDiv**: An HTML DIV element that will be transformed into an editable editor. This element can be styled using CSS to fit the page design. - **options**: An optional object of type `EditorOptions` to customize the editor's behavior and features. ``` -------------------------------- ### Handle Hyperlink Creation Events Source: https://github.com/microsoft/roosterjs/wiki/HyperLink-plugin Implement the onPluginEvent method to react to hyperlink creation events. This allows for custom handling when hyperlinks are automatically created or added via the createLink() API. ```typescript onPluginEvent(event: PluginEvent) { if (event.eventType == PluginEventType.ContentChanged) { let contentChangedEvent = event; if ( contentChangedEvent.source == ChangeSource.AutoLink || contentChangedEvent.source == ChangeSource.CreateLink // This allows you to handle the new link added by createLink() API ) { let hyperLinkNode = contentChangedEvent.data; // Add your code here to do customized handling } } } ``` -------------------------------- ### Content API: getTextContent Source: https://github.com/microsoft/roosterjs/wiki/Editor-API Retrieves the plain text content within the editor. ```APIDOC ## getTextContent ### Description Get plain text content inside editor. ### Method Not specified (assumed to be a method call on an Editor instance) ### Request Example ```javascript // Assuming 'editor' is an instance of the Editor class const textContent = editor.getTextContent(); ``` ### Response - **textContent**: The plain text content of the editor. ``` -------------------------------- ### Handle KeyPress Event with PluginDomEvent Source: https://github.com/microsoft/roosterjs/wiki/PluginDomEvent Demonstrates how to use PluginDomEvent to access the raw KeyboardEvent, check for numeric input, insert content, and prevent default behavior. ```typescript onPluginEvent(event: PluginEvent) { if (event.eventType == PluginEventType.KeyPress) { let domEvent = event; let keyboardEvent = domEvent.rawEvent; if (keyboardEvent.which >= KEY_0 && keyboardEvent.which <= KEY_9) { let text = NUMBERS[keyboardEvent.which - KEY_0] + ' '; this.editor.insertContent(text); keyboardEvent.preventDefault(); } } } ``` -------------------------------- ### createRange and getRangeFromSelectionPath Source: https://github.com/microsoft/roosterjs/wiki/Selection-API Functions for creating Range objects from Nodes, Positions, or SelectionPaths. createRange can form a range from nodes or node positions, while getRangeFromSelectionPath reconstructs a Range from a SelectionPath. ```APIDOC ## createRange ### Description Creates a Range object from one or two Nodes or NodePositions. If one node is specified, the range covers that node. If two nodes are specified, the range starts before the first and ends after the second. If one NodePosition is specified, it creates a collapsed range at that position. If two NodePositions are specified, the range starts at the first and ends at the second. ### Signature ```typescript function createRange(node: Node, endNode?: Node): Range; function createRange(start: NodePosition, end?: NodePosition): Range; ``` ## getRangeFromSelectionPath ### Description Converts a SelectionPath object back into a Range object. This function requires a rootNode as a parameter, which is the root of the content, and the selection path is calculated relative to this node. ### Signature ```typescript function getRangeFromSelectionPath(rootNode: HTMLElement, path: SelectionPath): Range; ``` ``` -------------------------------- ### Selection API: select Source: https://github.com/microsoft/roosterjs/wiki/Editor-API Sets the editor's selection using provided information like a Position, Range, or node and offset. ```APIDOC ## select ### Description Set selection of editor, using the provided information, such as a Position, a Range, or node and offset. ### Method Not specified (assumed to be a method call on an Editor instance) ### Parameters - **selectionInfo**: Information defining the selection (e.g., a Range object, or an object with node and offset). ### Request Example ```javascript // Assuming 'editor' is an instance of the Editor class // and 'range' is a Range object editor.select(range); ``` ### Response Not specified. ``` -------------------------------- ### execFormatWithUndo Replacement Source: https://github.com/microsoft/roosterjs/wiki/RoosterJs-7 The `execFormatWithUndo` functionality is now handled by `Editor.addUndoSnapshot()`, which should be used before executing formatting operations to ensure undo/redo capabilities. This is part of the `roosterjs-editor-dom` package. ```APIDOC ## execFormatWithUndo ### Description Replaced by `Editor.addUndoSnapshot()`. This method is used to add an undo snapshot before performing formatting operations. Located in the `roosterjs-editor-dom` package. ### Method N/A (This is a method replacement) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### PluginWithState Interface Source: https://github.com/microsoft/roosterjs/wiki/RoosterJs-8-types An editor plugin that has a state object stored on the editor core for access. ```APIDOC ## PluginWithState ### New Members: - **getState**(): Get plugin state object ``` -------------------------------- ### PredefinedCssMap Type Source: https://github.com/microsoft/roosterjs/wiki/RoosterJs-8-types A map of predefined CSS styles for elements. ```APIDOC ## PredefinedCssMap Type A map of predefined CSS styles for elements. ``` -------------------------------- ### Create Paste Plugin Instance Source: https://github.com/microsoft/roosterjs/wiki/Paste-plugin Instantiate the Paste plugin manually. This plugin is included by default when creating an editor. ```typescript constructor(private useDirectPaste?: boolean); ``` -------------------------------- ### canRedo Source: https://github.com/microsoft/roosterjs/wiki/Editor-API Checks if there is an available redo snapshot to re-apply. ```APIDOC ## canRedo ### Description Whether there is an available redo snapshot. ### Method Not specified (assumed to be a method call on an Editor instance) ### Endpoint N/A (SDK method) ### Parameters None ### Request Example ```javascript const canRedo = editor.canRedo(); ``` ### Response - (boolean): True if a redo snapshot is available, false otherwise. ``` -------------------------------- ### CursorFeatureSettings Interface Source: https://github.com/microsoft/roosterjs/wiki/RoosterJs-8-types Settings for cursor features. ```APIDOC ## CursorFeatureSettings ### Description Settings for cursor features. ### Members - **noCycleCursorMove** (boolean): Chrome may make the cursor move to the end of the document if Ctrl+Left is pressed at the beginning of the document. This disables that behavior. ``` -------------------------------- ### setFontSize Source: https://github.com/microsoft/roosterjs/wiki/Format-API Sets the font size for the text at the selection. ```APIDOC ## setFontSize ### Description Set font size at selection. ### Method [Method signature or relevant details if available, otherwise omit] ### Parameters [Parameters if available, otherwise omit] ### Request Example [Request example if available, otherwise omit] ### Response [Response details if available, otherwise omit] ```