### Install Project Dependencies Source: https://editorjs.io/core-development Install the necessary dependencies for Editor.js using Yarn. ```bash yarn install ``` -------------------------------- ### Example Output Data with Multiple Blocks Source: https://editorjs.io/saving-data This example shows the structure of the output data for a page containing Header, Paragraph, and List blocks, illustrating the `type` and `data` fields for each block. ```json { "time": 1550476186479, "blocks": [ { "id": "oUq2g_tl8y", "type": "header", "data": { "text": "Editor.js", "level": 2 } }, { "id": "zbGZFPM-iI", "type": "paragraph", "data": { "text": "Hey. Meet the new Editor. On this page you can see it in action — try to edit this text. Source code of the page contains the example of connection and configuration." } }, { "id": "qYIGsjS5rt", "type": "header", "data": { "text": "Key features", "level": 3 } }, { "id": "XV87kJS_H1", "type": "list", "data": { "style": "unordered", "items": [ "It is a block-styled editor", "It returns clean data output in JSON", "Designed to be extendable and pluggable with a simple API" ] } }, { "id": "AOulAjL8XM", "type": "header", "data": { "text": "What does it mean «block-styled editor»", "level": 3 } }, { "id": "cyZjplMOZ0", "type": "paragraph", "data": { "text": "Workspace in classic editors is made of a single contenteditable element, used to create different HTML markups. Editor.js workspace consists of separate Blocks: paragraphs, headings, images, lists, quotes, etc. Each of them is an independent contenteditable element (or more complex structure) provided by Plugin and united by Editor's Core." } } ], "version": "2.8.1" } ``` -------------------------------- ### Install Editor.js via Yarn Source: https://editorjs.io/getting-started Install the Editor.js package using Yarn for Node.js projects. ```bash yarn add @editorjs/editorjs ``` -------------------------------- ### Install Editor.js via NPM Source: https://editorjs.io/getting-started Install the Editor.js package using npm for Node.js projects. ```bash npm i @editorjs/editorjs --save ``` -------------------------------- ### Initialize Editor with Block Settings Source: https://editorjs.io/making-a-block-settings Example of initializing Editor.js with a custom block and initial data, including block settings like 'withBackground'. ```javascript const editor = new EditorJS({ autofocus: true, tools: { image: SimpleImage }, data: { time: 1552744582955, blocks: [ { type: "image", data: { url: "https://cdn.pixabay.com/photo/2017/09/01/21/53/blue-2705642_1280.jpg", caption: 'Here is a caption field', withBorder: false, withBackground: true, stretched: false } } ], version: "2.11.10" } }); ``` -------------------------------- ### Connect Basic Tools to Editor.js Source: https://editorjs.io/getting-started Configure Editor.js to use the Header and List tools. Ensure these tools are installed separately. ```javascript import EditorJS from '@editorjs/editorjs'; import Header from '@editorjs/header'; import List from '@editorjs/list'; const editor = new EditorJS({ /** * Id of Element that should contain the Editor */ holder: 'editorjs', /** * Available Tools list. * Pass Tool's class or Settings object for each Tool you want to use */ tools: { header: Header, list: List } }); ``` -------------------------------- ### Initialize Editor with Saved Data Source: https://editorjs.io/fill-block-with-saved-data Example of initializing Editor.js with autofocus and pre-defined data, including an image block. ```javascript const editor = new EditorJS({ autofocus: true, tools: { image: SimpleImage }, data: { time: 1552744582955, blocks: [ { type: "image", data: { url: "https://cdn.pixabay.com/photo/2017/09/01/21/53/blue-2705642_1280.jpg" } } ], version: "2.11.10" } }); // ... save-buttons stuff ``` -------------------------------- ### Example: Defining Block Tunes with MenuConfig Source: https://editorjs.io/tools-api This snippet shows how to return an array of tune configurations using the MenuConfig format. Each tune is defined with an icon and a label, suitable for the standard Block Tunes menu. ```javascript class SimpleImage { // ... other methods renderSettings(){ return [ { icon: ``, label: 'With border' }, { icon: ``, label: 'Stretched' }, { icon: ``, label: 'With background' } ]; } } ``` -------------------------------- ### Tool Class Constructor Source: https://editorjs.io/tools-api Example of a Tool class constructor accepting data, api, config, readOnly, and block arguments. ```javascript class MyTool { constructor({data, api, config, readOnly, block}) { // ... use or store arguments as you want } } ``` -------------------------------- ### Block Tune: Render with MenuConfig Source: https://editorjs.io/block-tunes-api Implement the render method to define how a tune appears in the Block Tunes menu using MenuConfig. This example shows returning an icon and label, with an activate handler. ```javascript class MyBlockTune { constructor({ api }) { this.api = api; } render() { return { icon: '...', label: 'H', onActivate: () => { // do smth } }; } } ``` -------------------------------- ### Example: Creating Custom Block Settings UI with HTML Element Source: https://editorjs.io/tools-api This snippet demonstrates returning a custom HTML element for block settings, suitable for advanced use cases. It manually creates and appends setting buttons to a wrapper div. ```javascript class SimpleImage { // ... other methods renderSettings(){ const settings = [ { name: 'withBorder', icon: `` }, { name: 'stretched', icon: `` }, { name: 'withBackground', icon: `` } ]; const wrapper = document.createElement('div'); settings.forEach( tune => { let button = document.createElement('div'); button.classList.add('cdx-settings-button'); button.innerHTML = tune.icon; wrapper.appendChild(button); }); return wrapper; } } ``` -------------------------------- ### Implement MarkerTool for Highlighting Source: https://editorjs.io/inline-tool-basics This example implements a basic `MarkerTool` that highlights selected text with a <MARK> element. It includes logic to prevent re-highlighting and to determine if the current selection is already marked. ```javascript class MarkerTool { static get isInline() { return true; } constructor() { this.button = null; this.state = false; } render() { this.button = document.createElement('button'); this.button.type = 'button'; this.button.textContent = 'M'; return this.button; } surround(range) { if (this.state) { // If highlights is already applied, do nothing for now return; } const selectedText = range.extractContents(); // Create MARK element const mark = document.createElement('MARK'); // Append to the MARK element selected TextNode mark.appendChild(selectedText); // Insert new element range.insertNode(mark); } checkState(selection) { const text = selection.anchorNode; if (!text) { return; } const anchorElement = text instanceof Element ? text : text.parentElement; this.state = !!anchorElement.closest('MARK'); } } ``` -------------------------------- ### HTML Content Example Source: https://editorjs.io/sanitize-saved-data An example of editable HTML content within a caption field, including unwanted `div` tags. ```html
Here is
a
caption field
``` -------------------------------- ### Sanitizer Configuration Example Source: https://editorjs.io/sanitizer Defines rules for allowed HTML tags and their attributes. Keys are tags, and values are rules (boolean, object, or function). ```javascript const sanitizerConfig = { b: true, // leave without attributes p: {}, } ``` -------------------------------- ### Block Tune: Save Method Example Source: https://editorjs.io/block-tunes-api Implement the save method to return the tune's current state. This is crucial for persisting tune data when the editor content is saved. ```javascript class MyBlockTune { // ... other methods save() { return { prop: 'value' }; } } ``` -------------------------------- ### Output Data with Custom Block Type Source: https://editorjs.io/saving-data This example demonstrates the output data format when a custom block type ('heading') is configured, showing how the `type` field reflects the configuration change. ```json { "time": 1550476186479, "blocks": [ { "type": "heading", "data": { "text": "Editor.js", "level": 2 } }, { "type": "paragraph", "data": { "text": "Hey. Meet the new Editor. On this page you can see it in action — try to edit this text. Source code of the page contains the example of connection and configuration." } }, { "type": "heading", "data": { "text": "Key features", "level": 3 } } ], "version": "2.8.1" } ``` -------------------------------- ### Editor.js Clean Data Output Example Source: https://editorjs.io/base-concepts Compares the HTML output of a traditional editor with the clean JSON data structure returned by Editor.js for the same content. ```JSON { "time" : 1550476186479, "blocks" : [ { "type" : "paragraph", "data" : { "text" : "The example of text that was written in one of popular text editors." } }, { "type" : "header", "data" : { "text" : "With the header of course", "level" : 2 } }, { "type" : "paragraph", "data" : { "text" : "So what do we have?" } } ], "version" : "2.8.1" } ``` -------------------------------- ### Using i18n API for UI Texts in Tool Configuration Source: https://editorjs.io/provide-custom-configuration This example shows how to integrate the Editor.js i18n API to localize UI texts, ensuring that even configurable texts like placeholders are translatable. It wraps the placeholder string with `this.api.i18n.t()`. ```javascript class SimpleImage { // ... constructor({data, api, config}){ this.api = api; this.config = config || {}; //... } render(){ //... input.placeholder = this.config.placeholder || 'Paste an image URL...'; input.placeholder = this.api.i18n.t(this.config.placeholder || 'Paste an image URL...'); // ... } //... } ``` -------------------------------- ### Block Tune: Render with Button Element Source: https://editorjs.io/block-tunes-api Alternatively, the render method can return a custom HTML button element for the Block settings area. This example creates a button with specific text content. ```javascript class MyBlockTune { constructor({ api }) { this.api = api; } render() { const button = document.createElement('button'); button.classList.add(this.api.styles.button); button.textContent = 'H'; return button; } } ``` -------------------------------- ### Using t() in a Block or Inline Tool Source: https://editorjs.io/i18n-api Demonstrates how to use the `api.i18n.t()` method within a custom tool to translate a string. This example shows how to initialize Editor.js with a custom i18n dictionary for the tool. ```javascript /** * Using in a plugin */ class SimpleImage { constructor({data, api}) { this.api = api; } render() { const button = document.createElement('button'); button.textContent = this.api.i18n.t('Upload an image'); return button; } } /** * Editor.js initialization * Example of passing i18n dictionary */ new Editorjs({ // ... tools: { image: SimpleImage, }, i18n: { messages: { tools: { image: { 'Upload an image': 'Загрузить изображение', } } } } }) ``` -------------------------------- ### Block Tune: Wrap Method Example Source: https://editorjs.io/block-tunes-api Use the wrap method to modify the block's content element by wrapping it. This method is called during block rendering and can be used to apply styles or structural changes. ```javascript class MyBlockTune { // ... other methods wrap(blockContent) { const myWrapper = document.createElement('div'); myWrapper.append(blockContent); myWrapper.style.fontSize = '0.9em'; return myWrapper; } } ``` -------------------------------- ### Sanitized Data Output Example Source: https://editorjs.io/sanitize-saved-data Example JSON output after saving data, demonstrating that unwanted HTML tags like `div` have been sanitized from the caption. ```json { "time": 1553964811649, "blocks": [ { "type": "image", "data": { "url": "https://cdn.pixabay.com/photo/2017/09/01/21/53/blue-2705642_1280.jpg", "caption": "Here is a caption field", "withBorder": false, "withBackground": false, "stretched": false } } ], "version": "2.12.3" } ``` -------------------------------- ### On Source: https://editorjs.io/listeners Sets up a native DOM event listener and saves it to the Listeners storage. It takes an HTML element, event type, callback function, and an optional boolean for capturing. ```APIDOC ## On ### Description Sets up a native DOM event listener and saves it to the Listeners storage. ### Method `on(element: HTMLElement, eventType: string, handler: () => void, useCapture?: boolean): void` ### Parameters #### Path Parameters - **element** (HTMLElement) - Required - The HTML element to attach the event listener to. - **eventType** (String) - Required - The type of event to listen for (e.g., 'click', 'keyup'). - **handler** (Function) - Required - The callback function to execute when the event is triggered. - **useCapture** (Boolean) - Optional - Specifies whether to use event capturing. ### Example ```javascript class MyTool { constructor({data, api}) { this.api = api; this.button = document.createElement('div'); } myMethod() { this.api.listeners.on(this.button, 'click', () => { console.log('Button clicked!'); }, false); } } ``` ``` -------------------------------- ### Selection API Source: https://editorjs.io/api Methods for getting information about the current selection within the Editor.js workspace. ```APIDOC ## Selection API Methods for getting information about Selection inside the Editor.js workspace. ### `findParentTag(tag, className)` Looks ahead from the selection and finds a passed tag with a class name. ### `expandToTag(tag)` Expands the selection to the passed tag. ``` -------------------------------- ### Allowing 'a' tag without attributes Source: https://editorjs.io/sanitizer Example of configuring rules for the 'a' tag to allow it but strip all its attributes. ```javascript // leave without attributes a: {} ``` -------------------------------- ### Allowing 'a' tag with specific attributes Source: https://editorjs.io/sanitizer Example of configuring rules for the 'a' tag, allowing only the 'href' attribute. ```javascript // leave with only "href" attribute a: { href: true } ``` -------------------------------- ### Navigate to Project Directory Source: https://editorjs.io/core-development Change your current directory to the cloned Editor.js project folder. ```bash cd editor.js/ ``` -------------------------------- ### setToNextBlock Source: https://editorjs.io/caret Sets the caret to the next block. You can specify the position within the block ('start' or 'end') and an offset. ```APIDOC ## setToNextBlock ### Description Method sets caret to the next Block. ### Parameters - **position** (string) - Optional - Caret position at the Block (can be only `start` or `end`). Defaults to `this.Editor.Caret.positions.DEFAULT`. - **offset** (number) - Optional - Caret offset at the node. Defaults to 0. ### Return value - **boolean** - Returns `true` if caret was set. ### Method Signature `setToNextBlock(position: string = this.Editor.Caret.positions.DEFAULT, offset: number = 0): boolean` ### Example ```javascript class MyTool { constructor({data, api}) { this.api = api; // ... } setToNextBlock() { this.api.caret.setToNextBlock('start', 0); } // ... other methods } ``` ``` -------------------------------- ### Editor Ready Callback Source: https://editorjs.io/configuration Use the 'onReady' property in the configuration object to execute a function once the Editor.js instance is initialized and ready. ```javascript var editor = new EditorJS({ // Other configuration properties /** * onReady callback */ onReady: () => { console.log('Editor.js is ready to work!') } }); ``` -------------------------------- ### setToPreviousBlock Source: https://editorjs.io/caret Sets the caret to the previous block. You can specify the position within the block ('start' or 'end') and an offset. ```APIDOC ## setToPreviousBlock ### Description Method sets caret to the previous Block. ### Parameters - **position** (string) - Optional - Caret position at the Block (can be only `start` or `end`). Defaults to `this.Editor.Caret.positions.DEFAULT`. - **offset** (number) - Optional - Caret offset at the node. Defaults to 0. ### Return value - **boolean** - Returns `true` if caret was set. ### Method Signature `setToPreviousBlock(position: string = this.Editor.Caret.positions.DEFAULT, offset: number = 0): boolean` ### Example ```javascript class MyTool { constructor({data, api}) { this.api = api; // ... } setToPreviousBlock() { this.api.caret.setToPreviousBlock('start', 0); } // ... other methods } ``` ``` -------------------------------- ### Initialize Editor.js with Zero Configuration Source: https://editorjs.io/getting-started Initialize Editor.js with default settings. The editor will be attached to an element with the ID '_editorjs'. ```javascript import EditorJS from '@editorjs/editorjs'; const editor = new EditorJS(); ``` -------------------------------- ### Build Editor.js Source: https://editorjs.io/core-development Compile the Editor.js project. ```bash yarn build ``` -------------------------------- ### Get Blocks Count Source: https://editorjs.io/blocks Returns the total number of blocks currently rendered in the editor. Useful for validation or determining the last block. ```javascript class MyTool { constructor({data, api}){ this.api = api; // ... } isLastBlock() { return this.api.blocks.getCurrentBlockIndex() === this.api.blocks.getBlocksCount() - 1; } // ... other methods } ``` -------------------------------- ### Get Block by Index Source: https://editorjs.io/blocks Retrieves a BlockAPI object by its numerical index in the editor. Use this when you need to access a block based on its position. ```javascript class MyTool { constructor({data, api}){ this.api = api; // ... } myMethod() { this.api.blocks.getBlockByIndex(1); // get first Block contents } // ... other methods } ``` -------------------------------- ### setToBlock Source: https://editorjs.io/caret Sets the caret to a specific block identified by its index. You can also specify the position within the block ('start' or 'end') and an offset. ```APIDOC ## setToBlock ### Description Method sets caret to the Block with passed index. ### Parameters - **index** (number) - Required - Index of the Block. - **position** (string) - Optional - Caret position at the Block (can be only `start` or `end`). Defaults to `this.Editor.Caret.positions.DEFAULT`. - **offset** (number) - Optional - Caret offset at the node. Defaults to 0. ### Return value - **boolean** - Returns `true` if caret was set. ### Method Signature `setToBlock(index: number, position: string = this.Editor.Caret.positions.DEFAULT, offset: number = 0): boolean` ### Example ```javascript class MyTool { constructor({data, api}) { this.api = api; // ... } setToBlock() { this.api.caret.setToBlock('start', 0); // set caret at the start of first Block } // ... other methods } ``` ``` -------------------------------- ### Implement Tool UI with render() Source: https://editorjs.io/tools-api Use the render method to create the HTML element for your tool's UI. Ensure the returned element is focusable and can contain saved data. ```javascript class MyTool { render() { const wrapper = document.createElement('div'); wrapper.contentEditable = true; return wrapper; } } ``` -------------------------------- ### setToFirstBlock Source: https://editorjs.io/caret Sets the caret to the beginning (index 0) of the first block. You can specify the position within the block ('start' or 'end') and an offset. ```APIDOC ## setToFirstBlock ### Description Method sets caret to the first Block (with index = 0). ### Parameters - **position** (string) - Optional - Caret position at the Block (can be only `start` or `end`). Defaults to `this.Editor.Caret.positions.DEFAULT`. - **offset** (number) - Optional - Caret offset at the node. Defaults to 0. ### Return value - **boolean** - Returns `true` if caret was set. ### Method Signature `setToFirstBlock(position: string = this.Editor.Caret.positions.DEFAULT, offset: number = 0): boolean` ### Example ```javascript class MyTool { constructor({data, api}) { this.api = api; // ... } setAtTheEnd() { this.api.caret.setToFirstBlock('end', 0); } // ... other methods } ``` ``` -------------------------------- ### Set Custom Placeholder Source: https://editorjs.io/configuration Use the `placeholder` option to define custom placeholder text for the editor. This is useful for guiding users on what to write. ```javascript const editor = new EditorJS({ ... placeholder: 'Let`s write an awesome story!' ... }); ``` -------------------------------- ### Accessing Configuration in SimpleImage Tool Source: https://editorjs.io/provide-custom-configuration Demonstrates how the SimpleImage tool class accesses its configuration, including a custom placeholder, within its constructor and render methods. It provides a fallback default placeholder if none is provided. ```javascript class SimpleImage { // ... static get toolbox // ... static get pasteConfig // ... static get sanitize // ... constructor({data, api, config}){ this.api = api; this.config = config || {}; // ... this.data // ... this.wrapper // ... this.settings } render(){ this.wrapper = document.createElement('div'); this.wrapper.classList.add('simple-image'); if (this.data && this.data.url){ this._createImage(this.data.url, this.data.caption); return this.wrapper; } const input = document.createElement('input'); input.placeholder = 'Paste an image URL...'; input.placeholder = this.config.placeholder || 'Paste an image URL...'; input.addEventListener('paste', (event) => { this._createImage(event.clipboardData.getData('text')); }); this.wrapper.appendChild(input); return this.wrapper; } // ... _createImage // ... save // ... validate // ... renderSettings // ... _toggleTune // ... _acceptTuneView // ... onPaste } ``` -------------------------------- ### shortcut (static getter) Source: https://editorjs.io/inline-tools-api-1 Allows defining a keyboard shortcut for activating the tool, providing an alternative way to invoke its functionality. ```APIDOC ## shortcut() ### Description Provides keyboard shortcut for your Tool. ### Return value - `String`: Shortcut for Tool. Format described here. ### Example ```javascript class MyInlineTool { static get shortcut() { return 'CMD+K'; } /* ... */ } ``` ``` -------------------------------- ### Get Block by ID Source: https://editorjs.io/blocks Retrieves a BlockAPI object using its unique identifier. Useful for direct manipulation or data access of a specific block. ```javascript const editor = new EditorJS({ // ... configuration }) editor.blocks.getById('1sYMhUrznu'); // get Block with id "1sYMhUrznu" ``` -------------------------------- ### setToLastBlock Source: https://editorjs.io/caret Sets the caret to the end of the last block (with index = length - 1). You can specify the position within the block ('start' or 'end') and an offset. ```APIDOC ## setToLastBlock ### Description Method sets caret to the last Block (with index = length - 1). ### Parameters - **position** (string) - Optional - Caret position at the Block (can be only `start` or `end`). Defaults to `this.Editor.Caret.positions.DEFAULT`. - **offset** (number) - Optional - Caret offset at the node. Defaults to 0. ### Return value - **boolean** - Returns `true` if caret was set. ### Method Signature `setToLastBlock(position: string = this.Editor.Caret.positions.DEFAULT, offset: number = 0): boolean` ### Example ```javascript class MyTool { constructor({data, api}) { this.api = api; // ... } setAtTheStart() { this.api.caret.setToLastBlock('start', 0); } // ... other methods } ``` ``` -------------------------------- ### Initialize Editor with Save Button and Output Area Source: https://editorjs.io/the-first-plugin Set up the Editor.js instance, a save button, and a preformatted output area. The save button triggers the editor's save method, displaying the output in the designated area. ```javascript



```

--------------------------------

### Set Caret to First Block

Source: https://editorjs.io/caret

Sets the caret to the beginning or end of the first block. Useful for initializing cursor position or navigating to the start.

```typescript
class MyTool {
  constructor({data, api}){
    this.api = api;
    // ...
  }

  setAtTheEnd() {
    this.api.caret.setToFirstBlock('end', 0);
  }
  // ... other methods
}
```

--------------------------------

### renderSettings()

Source: https://editorjs.io/tools-api

This method allows you to define block tunes for your Editor.js tool. It can return a `MenuConfig` object for standard tune appearances or a single HTML element for custom UI elements.

```APIDOC
## renderSettings()

### Description
Method allows to define block tunes. Can either return MenuConfig or single HTML element with block tunes UI elements.

### Parameters
This method has no arguments.

### Return value
- `MenuConfig`: Configuration of tunes appearance inside Block Tunes menu.
- `Element`: Advanced. Single element that contains a Block Settings UI elements.

**Note:** Custom HTML return value format is only recommended for corner cases when it's not possible to define tune with `MenuConfig`. In other cases use simple config format.

### Example #1: TunesMenuConfig return value
```javascript
class SimpleImage {
  // ... other methods
  renderSettings() {
    return [
      {
        icon: ``,
        label: 'With border'
      },
      {
        icon: ``,
        label: 'Stretched'
      },
      {
        icon: ``,
        label: 'With background'
      }
    ];
  }
}
```

### Example #2: Element return value
```javascript
class SimpleImage {
  // ... other methods
  renderSettings() {
    const settings = [
      {
        name: 'withBorder',
        icon: ``
      },
      {
        name: 'stretched',
        icon: ``
      },
      {
        name: 'withBackground',
        icon: ``
      }
    ];
    const wrapper = document.createElement('div');
    settings.forEach(tune => {
      let button = document.createElement('div');
      button.classList.add('cdx-settings-button');
      button.innerHTML = tune.icon;
      wrapper.appendChild(button);
    });
    return wrapper;
  }
}

```

--------------------------------

### render()

Source: https://editorjs.io/inline-tools-api-1

Creates the UI for a tool's button in the Inline Toolbar. It can return either a MenuConfig object for standard button appearance or a single HTML element for custom button designs.

```APIDOC
## render()

### Description

Create Tool`s button for Inline Toolbar. Can either return MenuConfig or single HTML element with a button.

### Parameters

This method has no arguments.

### Return value

- `MenuConfig`: Configuration of the tune's appearance inside Inline Toolbar menu.
- `Button`: **Advanced**. HTML Element with button for Inline Toolbar.

### Example #1: MenuConfig return value
```javascript
class MyInlineTool {
  render () {
    return {
      icon: '...',
      onActivate: () => {
        // Handle click
      }
    }
  }
}
```

### Example #2: HTMLElement return value
```javascript
class MyInlineTool {
  render () {
    const button = document.createElement('button');
    button.type = 'button';
    button.innerHTML = '...';
    return button;
  }
}
```
```