### 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 1Text 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,
"