Table of contents

Selection

This module provides several helpful methods working with browser selection.

findParentTag — looks ahead from selection and finds passed tag with class name

expandToTag — expands selection to the passed tag

save – saves selection for later restoring

restore – restores previously saved selection

setFakeBackground – imitates real selection by painting text's background blue

removeFakeBackground – removes blue selection imitation

Finds parent tag with passed class name

String tag's name that will be found
String tag's class name must match this argument
?HTMLElement found HTML element or null if not found
findParentTag(tagName: string, className?: string): HTMLElement|null
class MyInlineTool { constructor({api}) { this.api = api; } surround(range) { if (range) { const parentAnchor = this.selection.findParentTag('A'); if (parentAnchor) { // found closest 'A' tag that wraps current selection // do something } } } }

Wraps current selection with passed tag

HTMLElement HTML element that will wrap the selection

Method does not return anything

expandToTag(node: HTMLElement): void
class MyInlineTool { constructor({api}) { this.api = api; } surround(range) { if (range) { const parentAnchor = this.api.selection.findParentTag('A'); if (parentAnchor) { // found closest 'A' tag that wraps current selection this.api.selection.expandToTag(parentAnchor); } } } }

Allows to save selection to be able to temporally move focus away and restore it later. Might be useful for creating inline tools. To keep the appearance of the selection while it is saved, use  with setFakeBackground()

None

void

Restores previously saved selection

None

void

Imitates the real selection by creating a blue background behind the text. This can be useful for creating inline tools, as it allows the selection to persist when the focus moves from the text to the tool's controls.

None

void

Removes blue background behind the text that imitates selection

None

void

/** * Example of inline tool with nested menu */ class ConvertToInlineTool { /** * Specifies Tool as Inline Tool */ public static isInline = true; /** * API for working with Selection */ private readonly selectionAPI: Selection; /** * @param api - Editor.js API */ constructor({ api }: { api: API }) { this.selectionAPI = api.selection; } /** * Returns tools Toolbar appearance config */ public render(): MenuConfig { return { icon: '<svg>...</svg>', children: { items: [...], /* Nested menu items */ onOpen: () => { /* Save selection once nested menu opens */ this.selectionAPI.setFakeBackground(); this.selectionAPI.save(); }, onClose: () => { /* Restore selection once nested menu closes */ this.selectionAPI.restore(); this.selectionAPI.removeFakeBackground(); } } }; } }