chore(linting): eslint updated, code linted (#2174)

* update eslint + autofix

* a bunch of eslint fixes

* some spelling & eslint fixes

* fix some eslint errors and spells

* Update __module.ts

* a bunch of eslint fixes in tests

* Update cypress.yml

* Update cypress.yml

* fix cypress docker image name

* fixes for tests

* more tests fixed

* rm rule ignore

* rm another ignored rule

* Update .eslintrc
This commit is contained in:
Peter Savchenko 2022-11-25 21:56:50 +04:00 committed by GitHub
parent 19f3790cfd
commit 3272efc3f7
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
73 changed files with 1157 additions and 892 deletions

View file

@ -1,27 +1,7 @@
{ {
"extends": [ "extends": [
"codex" "codex/ts"
], ],
"rules": {
/**
* Temporary suppress some errors. We need to fix them partially in next patches
*/
"import/no-duplicates": ["warn"],
"@typescript-eslint/triple-slash-reference": ["off"],
"jsdoc/no-undefined-types": ["warn", {"definedTypes": [
"ConstructorOptions",
"API",
"BlockToolConstructable",
"EditorConfig",
"Tool",
"ToolSettings"
]}]
},
"settings": {
"jsdoc": {
"mode": "typescript"
}
},
"globals": { "globals": {
"Node": true, "Node": true,
"Range": true, "Range": true,

View file

@ -4,7 +4,7 @@ jobs:
firefox: firefox:
runs-on: ubuntu-latest runs-on: ubuntu-latest
container: container:
image: cypress/browsers:node14.16.0-chrome89-ff86 image: cypress/browsers:node14.17.0-chrome88-ff89
options: --user 1001 options: --user 1001
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2

29
.vscode/settings.json vendored Normal file
View file

@ -0,0 +1,29 @@
{
"cSpell.words": [
"Behaviour",
"cacheable",
"codexteam",
"colspan",
"contenteditable",
"cssnano",
"Debouncer",
"devserver",
"editorjs",
"entrypoints",
"Flippable",
"hsablonniere",
"intellij",
"keydowns",
"Kilian",
"mergeable",
"movetostart",
"nofollow",
"opencollective",
"preconfigured",
"rowspan",
"selectall",
"sometool",
"stylelint",
"twitterwidget"
]
}

View file

@ -67,11 +67,11 @@
"cssnano": "^4.1.10", "cssnano": "^4.1.10",
"cypress": "^6.8.0", "cypress": "^6.8.0",
"cypress-intellij-reporter": "^0.0.6", "cypress-intellij-reporter": "^0.0.6",
"eslint": "^6.8.0", "eslint": "^8.28.0",
"eslint-config-codex": "^1.3.3", "eslint-config-codex": "^1.7.1",
"eslint-loader": "^4.0.2", "eslint-loader": "^4.0.2",
"eslint-plugin-chai-friendly": "^0.6.0", "eslint-plugin-chai-friendly": "^0.7.2",
"eslint-plugin-cypress": "^2.11.2", "eslint-plugin-cypress": "^2.12.1",
"extract-text-webpack-plugin": "^3.0.2", "extract-text-webpack-plugin": "^3.0.2",
"html-janitor": "^2.0.4", "html-janitor": "^2.0.4",
"license-webpack-plugin": "^2.1.4", "license-webpack-plugin": "^2.1.4",

View file

@ -19,7 +19,6 @@ declare const VERSION: string;
* Short Description (_눈;) * Short Description (_눈;)
* *
* @version 2.18.0 * @version 2.18.0
*
* @license Apache-2.0 * @license Apache-2.0
* @author CodeX-Team <https://ifmo.su> * @author CodeX-Team <https://ifmo.su>
*/ */

View file

@ -14,12 +14,11 @@ export type ModuleNodes = object;
* @abstract * @abstract
* @class Module * @class Module
* @classdesc All modules inherits from this class. * @classdesc All modules inherits from this class.
*
* @typedef {Module} Module * @typedef {Module} Module
* @property {object} config - Editor user settings * @property {object} config - Editor user settings
* @property {EditorModules} Editor - List of Editor modules * @property {EditorModules} Editor - List of Editor modules
*/ */
export default class Module<T extends ModuleNodes = {}> { export default class Module<T extends ModuleNodes = Record<string, HTMLElement>> {
/** /**
* Each module can provide some UI elements that will be stored in this property * Each module can provide some UI elements that will be stored in this property
*/ */
@ -92,8 +91,9 @@ export default class Module<T extends ModuleNodes = {}> {
/** /**
* @class * @class
* * @param options - Module options
* @param {ModuleConfig} - Module config * @param options.config - Module config
* @param options.eventsDispatcher - Common event bus
*/ */
constructor({ config, eventsDispatcher }: ModuleConfig) { constructor({ config, eventsDispatcher }: ModuleConfig) {
if (new.target === Module) { if (new.target === Module) {

View file

@ -1,7 +1,6 @@
/** /**
* @class DeleteTune * @class DeleteTune
* @classdesc Editor's default tune that moves up selected block * @classdesc Editor's default tune that moves up selected block
*
* @copyright <CodeX Team> 2018 * @copyright <CodeX Team> 2018
*/ */
import { API, BlockTune, PopoverItem } from '../../../types'; import { API, BlockTune, PopoverItem } from '../../../types';
@ -37,22 +36,21 @@ export default class DeleteTune implements BlockTune {
*/ */
public render(): PopoverItem { public render(): PopoverItem {
return { return {
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
icon: $.svg('cross', 14, 14).outerHTML, icon: $.svg('cross', 14, 14).outerHTML,
label: this.api.i18n.t('Delete'), label: this.api.i18n.t('Delete'),
name: 'delete', name: 'delete',
confirmation: { confirmation: {
label: this.api.i18n.t('Click to delete'), label: this.api.i18n.t('Click to delete'),
onActivate: (item, e): void => this.handleClick(e), onActivate: (): void => this.handleClick(),
}, },
}; };
} }
/** /**
* Delete block conditions passed * Delete block conditions passed
*
* @param {MouseEvent} event - click event
*/ */
public handleClick(event: MouseEvent): void { public handleClick(): void {
this.api.blocks.delete(); this.api.blocks.delete();
} }
} }

View file

@ -1,7 +1,6 @@
/** /**
* @class MoveDownTune * @class MoveDownTune
* @classdesc Editor's default tune - Moves down highlighted block * @classdesc Editor's default tune - Moves down highlighted block
*
* @copyright <CodeX Team> 2018 * @copyright <CodeX Team> 2018
*/ */
@ -46,6 +45,7 @@ export default class MoveDownTune implements BlockTune {
*/ */
public render(): PopoverItem { public render(): PopoverItem {
return { return {
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
icon: $.svg('arrow-down', 14, 14).outerHTML, icon: $.svg('arrow-down', 14, 14).outerHTML,
label: this.api.i18n.t('Move down'), label: this.api.i18n.t('Move down'),
onActivate: (item, event): void => this.handleClick(event), onActivate: (item, event): void => this.handleClick(event),
@ -72,6 +72,7 @@ export default class MoveDownTune implements BlockTune {
window.setTimeout(() => { window.setTimeout(() => {
button.classList.remove(this.CSS.animation); button.classList.remove(this.CSS.animation);
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
}, 500); }, 500);
return; return;

View file

@ -1,11 +1,10 @@
/** /**
* @class MoveUpTune * @class MoveUpTune
* @classdesc Editor's default tune that moves up selected block * @classdesc Editor's default tune that moves up selected block
*
* @copyright <CodeX Team> 2018 * @copyright <CodeX Team> 2018
*/ */
import $ from '../dom'; import $ from '../dom';
import { API, BlockTune, BlockAPI, PopoverItem } from '../../../types'; import { API, BlockTune, PopoverItem } from '../../../types';
import Popover from '../../components/utils/popover'; import Popover from '../../components/utils/popover';
/** /**
@ -45,6 +44,7 @@ export default class MoveUpTune implements BlockTune {
*/ */
public render(): PopoverItem { public render(): PopoverItem {
return { return {
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
icon: $.svg('arrow-up', 14, 14).outerHTML, icon: $.svg('arrow-up', 14, 14).outerHTML,
label: this.api.i18n.t('Move up'), label: this.api.i18n.t('Move up'),
onActivate: (item, e): void => this.handleClick(e), onActivate: (item, e): void => this.handleClick(e),
@ -71,6 +71,7 @@ export default class MoveUpTune implements BlockTune {
window.setTimeout(() => { window.setTimeout(() => {
button.classList.remove(this.CSS.animation); button.classList.remove(this.CSS.animation);
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
}, 500); }, 500);
return; return;

View file

@ -7,7 +7,6 @@ import { BlockAPI as BlockAPIInterface } from '../../../types/api';
* Constructs new BlockAPI object * Constructs new BlockAPI object
* *
* @class * @class
*
* @param {Block} block - Block to expose * @param {Block} block - Block to expose
*/ */
function BlockAPI( function BlockAPI(
@ -90,7 +89,6 @@ function BlockAPI(
* *
* @param {string} methodName - method to call * @param {string} methodName - method to call
* @param {object} param - object with parameters * @param {object} param - object with parameters
*
* @returns {unknown} * @returns {unknown}
*/ */
call(methodName: string, param?: object): unknown { call(methodName: string, param?: object): unknown {
@ -110,7 +108,6 @@ function BlockAPI(
* Validate Block data * Validate Block data
* *
* @param {BlockToolData} data - data to validate * @param {BlockToolData} data - data to validate
*
* @returns {Promise<boolean>} * @returns {Promise<boolean>}
*/ */
validate(data: BlockToolData): Promise<boolean> { validate(data: BlockToolData): Promise<boolean> {

View file

@ -60,10 +60,8 @@ interface BlockConstructorOptions {
/** /**
* @class Block * @class Block
* @classdesc This class describes editor`s block, including block`s HTMLElement, data and tool * @classdesc This class describes editor`s block, including block`s HTMLElement, data and tool
*
* @property {BlockTool} tool current block tool (Paragraph, for example) * @property {BlockTool} tool current block tool (Paragraph, for example)
* @property {object} CSS block`s css classes * @property {object} CSS block`s css classes
*
*/ */
/** /**
@ -74,11 +72,13 @@ export enum BlockToolAPI {
* @todo remove method in 3.0.0 * @todo remove method in 3.0.0
* @deprecated use 'rendered' hook instead * @deprecated use 'rendered' hook instead
*/ */
// eslint-disable-next-line @typescript-eslint/naming-convention
APPEND_CALLBACK = 'appendCallback', APPEND_CALLBACK = 'appendCallback',
RENDERED = 'rendered', RENDERED = 'rendered',
MOVED = 'moved', MOVED = 'moved',
UPDATED = 'updated', UPDATED = 'updated',
REMOVED = 'removed', REMOVED = 'removed',
// eslint-disable-next-line @typescript-eslint/naming-convention
ON_PASTE = 'onPaste', ON_PASTE = 'onPaste',
} }
@ -89,7 +89,6 @@ type BlockEvents = 'didMutated';
/** /**
* @classdesc Abstract Block class that contains Block information, Tool name and Tool class instance * @classdesc Abstract Block class that contains Block information, Tool name and Tool class instance
*
* @property {BlockTool} tool - Tool instance * @property {BlockTool} tool - Tool instance
* @property {HTMLElement} holder - Div element that wraps block content with Tool's content. Has `ce-block` CSS class * @property {HTMLElement} holder - Div element that wraps block content with Tool's content. Has `ce-block` CSS class
* @property {HTMLElement} pluginsContent - HTML content that returns by Tool's render function * @property {HTMLElement} pluginsContent - HTML content that returns by Tool's render function
@ -244,7 +243,7 @@ export default class Block extends EventsDispatcher<BlockEvents> {
* @param {object} options - block constructor options * @param {object} options - block constructor options
* @param {string} [options.id] - block's id. Will be generated if omitted. * @param {string} [options.id] - block's id. Will be generated if omitted.
* @param {BlockToolData} options.data - Tool's initial data * @param {BlockToolData} options.data - Tool's initial data
* @param {BlockToolConstructable} options.tool block's tool * @param {BlockTool} options.tool block's tool
* @param options.api - Editor API module for pass it to the Block Tunes * @param options.api - Editor API module for pass it to the Block Tunes
* @param {boolean} options.readOnly - Read-Only flag * @param {boolean} options.readOnly - Read-Only flag
*/ */
@ -281,7 +280,7 @@ export default class Block extends EventsDispatcher<BlockEvents> {
} }
/** /**
* Find and return all editable elements (contenteditables and native inputs) in the Tool HTML * Find and return all editable elements (contenteditable and native inputs) in the Tool HTML
* *
* @returns {HTMLElement[]} * @returns {HTMLElement[]}
*/ */
@ -396,7 +395,7 @@ export default class Block extends EventsDispatcher<BlockEvents> {
/** /**
* is block mergeable * is block mergeable
* We plugin have merge function then we call it mergable * We plugin have merge function then we call it mergeable
* *
* @returns {boolean} * @returns {boolean}
*/ */
@ -417,7 +416,7 @@ export default class Block extends EventsDispatcher<BlockEvents> {
} }
/** /**
* Check if block has a media content such as images, iframes and other * Check if block has a media content such as images, iframe and other
* *
* @returns {boolean} * @returns {boolean}
*/ */
@ -487,7 +486,7 @@ export default class Block extends EventsDispatcher<BlockEvents> {
/** /**
* Set stretched state * Set stretched state
* *
* @param {boolean} state - 'true' to enable, 'false' to disable stretched statte * @param {boolean} state - 'true' to enable, 'false' to disable stretched state
*/ */
public set stretched(state: boolean) { public set stretched(state: boolean) {
this.holder.classList.toggle(Block.CSS.wrapperStretched, state); this.holder.classList.toggle(Block.CSS.wrapperStretched, state);
@ -619,7 +618,7 @@ export default class Block extends EventsDispatcher<BlockEvents> {
}; };
}) })
.catch((error) => { .catch((error) => {
_.log(`Saving proccess for ${this.name} tool failed due to the ${error}`, 'log', 'red'); _.log(`Saving process for ${this.name} tool failed due to the ${error}`, 'log', 'red');
}); });
} }
@ -628,7 +627,6 @@ export default class Block extends EventsDispatcher<BlockEvents> {
* Tool's validation method is optional * Tool's validation method is optional
* *
* @description Method returns true|false whether data passed the validation or not * @description Method returns true|false whether data passed the validation or not
*
* @param {BlockToolData} data - data to validate * @param {BlockToolData} data - data to validate
* @returns {Promise<boolean>} valid * @returns {Promise<boolean>} valid
*/ */
@ -855,10 +853,10 @@ export default class Block extends EventsDispatcher<BlockEvents> {
* Update current input * Update current input
*/ */
this.updateCurrentInput(); this.updateCurrentInput();
} };
/** /**
* Adds focus event listeners to all inputs and contentEditables * Adds focus event listeners to all inputs and contenteditable
*/ */
private addInputEvents(): void { private addInputEvents(): void {
this.inputs.forEach(input => { this.inputs.forEach(input => {
@ -874,7 +872,7 @@ export default class Block extends EventsDispatcher<BlockEvents> {
} }
/** /**
* removes focus event listeners from all inputs and contentEditables * removes focus event listeners from all inputs and contenteditable
*/ */
private removeInputEvents(): void { private removeInputEvents(): void {
this.inputs.forEach(input => { this.inputs.forEach(input => {

View file

@ -6,11 +6,8 @@ import { MoveEvent } from '../../types/tools';
/** /**
* @class Blocks * @class Blocks
* @classdesc Class to work with Block instances array * @classdesc Class to work with Block instances array
*
* @private * @private
*
* @property {HTMLElement} workingArea editor`s working node * @property {HTMLElement} workingArea editor`s working node
*
*/ */
export default class Blocks { export default class Blocks {
/** /**
@ -25,7 +22,6 @@ export default class Blocks {
/** /**
* @class * @class
*
* @param {HTMLElement} workingArea editor`s working node * @param {HTMLElement} workingArea editor`s working node
*/ */
constructor(workingArea: HTMLElement) { constructor(workingArea: HTMLElement) {
@ -65,7 +61,6 @@ export default class Blocks {
* *
* @example * @example
* blocks[0] = new Block(...) * blocks[0] = new Block(...)
*
* @param {Blocks} instance Blocks instance * @param {Blocks} instance Blocks instance
* @param {PropertyKey} property block index or any Blocks class property key to set * @param {PropertyKey} property block index or any Blocks class property key to set
* @param {Block} value value to set * @param {Block} value value to set
@ -257,7 +252,6 @@ export default class Blocks {
* Insert Block after passed target * Insert Block after passed target
* *
* @todo decide if this method is necessary * @todo decide if this method is necessary
*
* @param {Block} targetBlock target after which Block should be inserted * @param {Block} targetBlock target after which Block should be inserted
* @param {Block} newBlock Block to insert * @param {Block} newBlock Block to insert
*/ */

View file

@ -30,12 +30,9 @@ contextRequire.keys().forEach((filename) => {
/** /**
* @class Core * @class Core
*
* @classdesc Editor.js core class * @classdesc Editor.js core class
*
* @property {EditorConfig} config - all settings * @property {EditorConfig} config - all settings
* @property {EditorModules} moduleInstances - constructed editor components * @property {EditorModules} moduleInstances - constructed editor components
*
* @type {Core} * @type {Core}
*/ */
export default class Core { export default class Core {
@ -61,7 +58,6 @@ export default class Core {
/** /**
* @param {EditorConfig} config - user configuration * @param {EditorConfig} config - user configuration
*
*/ */
constructor(config?: EditorConfig|string) { constructor(config?: EditorConfig|string) {
/** /**
@ -103,6 +99,7 @@ export default class Core {
* Resolve this.isReady promise * Resolve this.isReady promise
*/ */
onReady(); onReady();
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
}, 500); }, 500);
}) })
.catch((error) => { .catch((error) => {
@ -173,6 +170,7 @@ export default class Core {
* *
* @type {number} * @type {number}
*/ */
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
this.config.minHeight = this.config.minHeight !== undefined ? this.config.minHeight : 300; this.config.minHeight = this.config.minHeight !== undefined ? this.config.minHeight : 300;
/** /**

View file

@ -50,7 +50,6 @@ export default class Dom {
* @param {string} tagName - new Element tag name * @param {string} tagName - new Element tag name
* @param {string[]|string} [classNames] - list or name of CSS classname(s) * @param {string[]|string} [classNames] - list or name of CSS classname(s)
* @param {object} [attributes] - any attributes * @param {object} [attributes] - any attributes
*
* @returns {HTMLElement} * @returns {HTMLElement}
*/ */
public static make(tagName: string, classNames: string | string[] = null, attributes: object = {}): HTMLElement { public static make(tagName: string, classNames: string | string[] = null, attributes: object = {}): HTMLElement {
@ -75,7 +74,6 @@ export default class Dom {
* Creates Text Node with the passed content * Creates Text Node with the passed content
* *
* @param {string} content - text content * @param {string} content - text content
*
* @returns {Text} * @returns {Text}
*/ */
public static text(content: string): Text { public static text(content: string): Text {
@ -88,7 +86,6 @@ export default class Dom {
* @param {string} name - name (id) of icon from sprite * @param {string} name - name (id) of icon from sprite
* @param {number} [width] - icon width * @param {number} [width] - icon width
* @param {number} [height] - icon height * @param {number} [height] - icon height
*
* @returns {SVGElement} * @returns {SVGElement}
*/ */
public static svg(name: string, width = 14, height = 14): SVGElement { public static svg(name: string, width = 14, height = 14): SVGElement {
@ -165,7 +162,6 @@ export default class Dom {
* *
* @param {Element} el - element we searching inside. Default - DOM Document * @param {Element} el - element we searching inside. Default - DOM Document
* @param {string} selector - searching string * @param {string} selector - searching string
*
* @returns {Element} * @returns {Element}
*/ */
public static find(el: Element | Document = document, selector: string): Element { public static find(el: Element | Document = document, selector: string): Element {
@ -189,7 +185,6 @@ export default class Dom {
* *
* @param {Element|Document} el - element we searching inside. Default - DOM Document * @param {Element|Document} el - element we searching inside. Default - DOM Document
* @param {string} selector - searching string * @param {string} selector - searching string
*
* @returns {NodeList} * @returns {NodeList}
*/ */
public static findAll(el: Element | Document = document, selector: string): NodeList { public static findAll(el: Element | Document = document, selector: string): NodeList {
@ -230,11 +225,9 @@ export default class Dom {
* Leaf is the vertex that doesn't have any child nodes * Leaf is the vertex that doesn't have any child nodes
* *
* @description Method recursively goes throw the all Node until it finds the Leaf * @description Method recursively goes throw the all Node until it finds the Leaf
*
* @param {Node} node - root Node. From this vertex we start Deep-first search * @param {Node} node - root Node. From this vertex we start Deep-first search
* {@link https://en.wikipedia.org/wiki/Depth-first_search} * {@link https://en.wikipedia.org/wiki/Depth-first_search}
* @param {boolean} [atLast] - find last text node * @param {boolean} [atLast] - find last text node
*
* @returns {Node} - it can be text Node or Element Node, so that caret will able to work with it * @returns {Node} - it can be text Node or Element Node, so that caret will able to work with it
*/ */
public static getDeepestNode(node: Node, atLast = false): Node { public static getDeepestNode(node: Node, atLast = false): Node {
@ -287,7 +280,6 @@ export default class Dom {
* Check if object is DOM node * Check if object is DOM node
* *
* @param {*} node - object to check * @param {*} node - object to check
*
* @returns {boolean} * @returns {boolean}
*/ */
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
@ -318,7 +310,6 @@ export default class Dom {
* Check if passed element is contenteditable * Check if passed element is contenteditable
* *
* @param {HTMLElement} element - html element to check * @param {HTMLElement} element - html element to check
*
* @returns {boolean} * @returns {boolean}
*/ */
public static isContentEditable(element: HTMLElement): boolean { public static isContentEditable(element: HTMLElement): boolean {
@ -329,7 +320,6 @@ export default class Dom {
* Checks target if it is native input * Checks target if it is native input
* *
* @param {*} target - HTML element or string * @param {*} target - HTML element or string
*
* @returns {boolean} * @returns {boolean}
*/ */
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
@ -346,7 +336,6 @@ export default class Dom {
* Checks if we can set caret * Checks if we can set caret
* *
* @param {HTMLElement} target - target to check * @param {HTMLElement} target - target to check
*
* @returns {boolean} * @returns {boolean}
*/ */
public static canSetCaret(target: HTMLElement): boolean { public static canSetCaret(target: HTMLElement): boolean {
@ -377,9 +366,7 @@ export default class Dom {
* *
* @description Method checks simple Node without any childs for emptiness * @description Method checks simple Node without any childs for emptiness
* If you have Node with 2 or more children id depth, you better use {@link Dom#isEmpty} method * If you have Node with 2 or more children id depth, you better use {@link Dom#isEmpty} method
*
* @param {Node} node - node to check * @param {Node} node - node to check
*
* @returns {boolean} true if it is empty * @returns {boolean} true if it is empty
*/ */
public static isNodeEmpty(node: Node): boolean { public static isNodeEmpty(node: Node): boolean {
@ -402,7 +389,6 @@ export default class Dom {
* checks node if it is doesn't have any child nodes * checks node if it is doesn't have any child nodes
* *
* @param {Node} node - node to check * @param {Node} node - node to check
*
* @returns {boolean} * @returns {boolean}
*/ */
public static isLeaf(node: Node): boolean { public static isLeaf(node: Node): boolean {
@ -418,7 +404,6 @@ export default class Dom {
* {@link https://en.wikipedia.org/wiki/Breadth-first_search} * {@link https://en.wikipedia.org/wiki/Breadth-first_search}
* *
* @description Pushes to stack all DOM leafs and checks for emptiness * @description Pushes to stack all DOM leafs and checks for emptiness
*
* @param {Node} node - node to check * @param {Node} node - node to check
* @returns {boolean} * @returns {boolean}
*/ */
@ -453,7 +438,6 @@ export default class Dom {
* Check if string contains html elements * Check if string contains html elements
* *
* @param {string} str - string to check * @param {string} str - string to check
*
* @returns {boolean} * @returns {boolean}
*/ */
public static isHTMLString(str: string): boolean { public static isHTMLString(str: string): boolean {
@ -468,7 +452,6 @@ export default class Dom {
* Return length of node`s text content * Return length of node`s text content
* *
* @param {Node} node - node with content * @param {Node} node - node with content
*
* @returns {number} * @returns {number}
*/ */
public static getContentLength(node: Node): number { public static getContentLength(node: Node): number {
@ -536,7 +519,6 @@ export default class Dom {
* Check if passed content includes only inline elements * Check if passed content includes only inline elements
* *
* @param {string|HTMLElement} data - element or html string * @param {string|HTMLElement} data - element or html string
*
* @returns {boolean} * @returns {boolean}
*/ */
public static containsOnlyInlineElements(data: string | HTMLElement): boolean { public static containsOnlyInlineElements(data: string | HTMLElement): boolean {
@ -561,7 +543,6 @@ export default class Dom {
* Find and return all block elements in the passed parent (including subtree) * Find and return all block elements in the passed parent (including subtree)
* *
* @param {HTMLElement} parent - root element * @param {HTMLElement} parent - root element
*
* @returns {HTMLElement[]} * @returns {HTMLElement[]}
*/ */
public static getDeepestBlockElements(parent: HTMLElement): HTMLElement[] { public static getDeepestBlockElements(parent: HTMLElement): HTMLElement[] {
@ -578,7 +559,6 @@ export default class Dom {
* Helper for get holder from {string} or return HTMLElement * Helper for get holder from {string} or return HTMLElement
* *
* @param {string | HTMLElement} element - holder's id or holder's HTML Element * @param {string | HTMLElement} element - holder's id or holder's HTML Element
*
* @returns {HTMLElement} * @returns {HTMLElement}
*/ */
public static getHolder(element: string | HTMLElement): HTMLElement { public static getHolder(element: string | HTMLElement): HTMLElement {
@ -593,7 +573,6 @@ export default class Dom {
* Method checks passed Node if it is some extension Node * Method checks passed Node if it is some extension Node
* *
* @param {Node} node - any node * @param {Node} node - any node
*
* @returns {boolean} * @returns {boolean}
*/ */
public static isExtensionNode(node: Node): boolean { public static isExtensionNode(node: Node): boolean {
@ -608,7 +587,6 @@ export default class Dom {
* Returns true if element is anchor (is A tag) * Returns true if element is anchor (is A tag)
* *
* @param {Element} element - element to check * @param {Element} element - element to check
*
* @returns {boolean} * @returns {boolean}
*/ */
public static isAnchor(element: Element): element is HTMLAnchorElement { public static isAnchor(element: Element): element is HTMLAnchorElement {

View file

@ -175,6 +175,7 @@ export default class DomIterator {
/** /**
* Focus input with micro-delay to ensure DOM is updated * Focus input with micro-delay to ensure DOM is updated
*/ */
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
_.delay(() => SelectionUtils.setCursor(this.items[focusedButtonIndex]), 50)(); _.delay(() => SelectionUtils.setCursor(this.items[focusedButtonIndex]), 50)();
} }

View file

@ -74,7 +74,7 @@ export default class Flipper {
/** /**
* Contains list of callbacks to be executed on each flip * Contains list of callbacks to be executed on each flip
*/ */
private flipCallbacks: Array<() => void> = [] private flipCallbacks: Array<() => void> = [];
/** /**
* @param {FlipperOptions} options - different constructing settings * @param {FlipperOptions} options - different constructing settings

View file

@ -21,7 +21,6 @@ export default class I18n {
* Perform translation of the string by namespace and a key * Perform translation of the string by namespace and a key
* *
* @example I18n.ui(I18nInternalNS.ui.blockTunes.toggler, 'Click to tune') * @example I18n.ui(I18nInternalNS.ui.blockTunes.toggler, 'Click to tune')
*
* @param internalNamespace - path to translated string in dictionary * @param internalNamespace - path to translated string in dictionary
* @param dictKey - dictionary key. Better to use default locale original text * @param dictKey - dictionary key. Better to use default locale original text
*/ */

View file

@ -61,6 +61,7 @@ export default class BoldInlineTool implements InlineTool {
this.nodes.button = document.createElement('button') as HTMLButtonElement; this.nodes.button = document.createElement('button') as HTMLButtonElement;
this.nodes.button.type = 'button'; this.nodes.button.type = 'button';
this.nodes.button.classList.add(this.CSS.button, this.CSS.buttonModifier); this.nodes.button.classList.add(this.CSS.button, this.CSS.buttonModifier);
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
this.nodes.button.appendChild($.svg('bold', 12, 14)); this.nodes.button.appendChild($.svg('bold', 12, 14));
return this.nodes.button; return this.nodes.button;
@ -68,21 +69,17 @@ export default class BoldInlineTool implements InlineTool {
/** /**
* Wrap range with <b> tag * Wrap range with <b> tag
*
* @param {Range} range - range to wrap
*/ */
public surround(range: Range): void { public surround(): void {
document.execCommand(this.commandName); document.execCommand(this.commandName);
} }
/** /**
* Check selection and set activated state to button if there are <b> tag * Check selection and set activated state to button if there are <b> tag
* *
* @param {Selection} selection - selection to check
*
* @returns {boolean} * @returns {boolean}
*/ */
public checkState(selection: Selection): boolean { public checkState(): boolean {
const isActive = document.queryCommandState(this.commandName); const isActive = document.queryCommandState(this.commandName);
this.nodes.button.classList.toggle(this.CSS.buttonActive, isActive); this.nodes.button.classList.toggle(this.CSS.buttonActive, isActive);

View file

@ -61,6 +61,7 @@ export default class ItalicInlineTool implements InlineTool {
this.nodes.button = document.createElement('button') as HTMLButtonElement; this.nodes.button = document.createElement('button') as HTMLButtonElement;
this.nodes.button.type = 'button'; this.nodes.button.type = 'button';
this.nodes.button.classList.add(this.CSS.button, this.CSS.buttonModifier); this.nodes.button.classList.add(this.CSS.button, this.CSS.buttonModifier);
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
this.nodes.button.appendChild($.svg('italic', 4, 11)); this.nodes.button.appendChild($.svg('italic', 4, 11));
return this.nodes.button; return this.nodes.button;
@ -68,19 +69,15 @@ export default class ItalicInlineTool implements InlineTool {
/** /**
* Wrap range with <i> tag * Wrap range with <i> tag
*
* @param {Range} range - range to wrap
*/ */
public surround(range: Range): void { public surround(): void {
document.execCommand(this.commandName); document.execCommand(this.commandName);
} }
/** /**
* Check selection and set activated state to button if there are <i> tag * Check selection and set activated state to button if there are <i> tag
*
* @param {Selection} selection - selection to check
*/ */
public checkState(selection: Selection): boolean { public checkState(): boolean {
const isActive = document.queryCommandState(this.commandName); const isActive = document.queryCommandState(this.commandName);
this.nodes.button.classList.toggle(this.CSS.buttonActive, isActive); this.nodes.button.classList.toggle(this.CSS.buttonActive, isActive);

View file

@ -2,8 +2,8 @@ import SelectionUtils from '../selection';
import $ from '../dom'; import $ from '../dom';
import * as _ from '../utils'; import * as _ from '../utils';
import { InlineTool, SanitizerConfig } from '../../../types'; import { API, InlineTool, SanitizerConfig } from '../../../types';
import { Notifier, Toolbar, I18n } from '../../../types/api'; import { Notifier, Toolbar, I18n, InlineToolbar } from '../../../types/api';
/** /**
* Link Tool * Link Tool
@ -71,9 +71,9 @@ export default class LinkInlineTool implements InlineTool {
button: HTMLButtonElement; button: HTMLButtonElement;
input: HTMLInputElement; input: HTMLInputElement;
} = { } = {
button: null, button: null,
input: null, input: null,
}; };
/** /**
* SelectionUtils instance * SelectionUtils instance
@ -93,7 +93,7 @@ export default class LinkInlineTool implements InlineTool {
/** /**
* Available inline toolbar methods (open/close) * Available inline toolbar methods (open/close)
*/ */
private inlineToolbar: Toolbar; private inlineToolbar: InlineToolbar;
/** /**
* Notifier API methods * Notifier API methods
@ -106,9 +106,9 @@ export default class LinkInlineTool implements InlineTool {
private i18n: I18n; private i18n: I18n;
/** /**
* @param {API} api - Editor.js API * @param api - Editor.js API
*/ */
constructor({ api }) { constructor({ api }: { api: API }) {
this.toolbar = api.toolbar; this.toolbar = api.toolbar;
this.inlineToolbar = api.inlineToolbar; this.inlineToolbar = api.inlineToolbar;
this.notifier = api.notifier; this.notifier = api.notifier;
@ -123,7 +123,9 @@ export default class LinkInlineTool implements InlineTool {
this.nodes.button = document.createElement('button') as HTMLButtonElement; this.nodes.button = document.createElement('button') as HTMLButtonElement;
this.nodes.button.type = 'button'; this.nodes.button.type = 'button';
this.nodes.button.classList.add(this.CSS.button, this.CSS.buttonModifier); this.nodes.button.classList.add(this.CSS.button, this.CSS.buttonModifier);
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
this.nodes.button.appendChild($.svg('link', 14, 10)); this.nodes.button.appendChild($.svg('link', 14, 10));
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
this.nodes.button.appendChild($.svg('unlink', 15, 11)); this.nodes.button.appendChild($.svg('unlink', 15, 11));
return this.nodes.button; return this.nodes.button;
@ -187,10 +189,8 @@ export default class LinkInlineTool implements InlineTool {
/** /**
* Check selection and set activated state to button if there are <a> tag * Check selection and set activated state to button if there are <a> tag
*
* @param {Selection} selection - selection to check
*/ */
public checkState(selection?: Selection): boolean { public checkState(): boolean {
const anchorTag = this.selection.findParentTag('A'); const anchorTag = this.selection.findParentTag('A');
if (anchorTag) { if (anchorTag) {

View file

@ -58,7 +58,6 @@ export default class BlocksAPI extends Module {
* Returns the index of Block by id; * Returns the index of Block by id;
* *
* @param id - block id * @param id - block id
* @returns {number}
*/ */
public getBlockIndex(id: string): number | undefined { public getBlockIndex(id: string): number | undefined {
const block = this.Editor.BlockManager.getBlockById(id); const block = this.Editor.BlockManager.getBlockById(id);
@ -201,7 +200,6 @@ export default class BlocksAPI extends Module {
* *
* @param {number} index - index of Block to stretch * @param {number} index - index of Block to stretch
* @param {boolean} status - true to enable, false to disable * @param {boolean} status - true to enable, false to disable
*
* @deprecated Use BlockAPI interface to stretch Blocks * @deprecated Use BlockAPI interface to stretch Blocks
*/ */
public stretchBlock(index: number, status = true): void { public stretchBlock(index: number, status = true): void {
@ -233,6 +231,7 @@ export default class BlocksAPI extends Module {
public insert = ( public insert = (
type: string = this.config.defaultBlock, type: string = this.config.defaultBlock,
data: BlockToolData = {}, data: BlockToolData = {},
// eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars
config: ToolConfig = {}, config: ToolConfig = {},
index?: number, index?: number,
needToFocus?: boolean, needToFocus?: boolean,
@ -247,7 +246,7 @@ export default class BlocksAPI extends Module {
}); });
return new BlockAPI(insertedBlock); return new BlockAPI(insertedBlock);
} };
/** /**
* Creates data of an empty block with a passed type. * Creates data of an empty block with a passed type.
@ -265,14 +264,13 @@ export default class BlocksAPI extends Module {
}); });
return block.data; return block.data;
} };
/** /**
* Insert new Block * Insert new Block
* After set caret to this Block * After set caret to this Block
* *
* @todo remove in 3.0.0 * @todo remove in 3.0.0
*
* @deprecated with insert() method * @deprecated with insert() method
*/ */
public insertNewBlock(): void { public insertNewBlock(): void {
@ -307,5 +305,5 @@ export default class BlocksAPI extends Module {
replace: true, replace: true,
tunes: block.tunes, tunes: block.tunes,
}); });
} };
} }

View file

@ -27,7 +27,6 @@ export default class CaretAPI extends Module {
* *
* @param {string} position - position where to set caret * @param {string} position - position where to set caret
* @param {number} offset - caret offset * @param {number} offset - caret offset
*
* @returns {boolean} * @returns {boolean}
*/ */
private setToFirstBlock = (position: string = this.Editor.Caret.positions.DEFAULT, offset = 0): boolean => { private setToFirstBlock = (position: string = this.Editor.Caret.positions.DEFAULT, offset = 0): boolean => {
@ -38,14 +37,13 @@ export default class CaretAPI extends Module {
this.Editor.Caret.setToBlock(this.Editor.BlockManager.firstBlock, position, offset); this.Editor.Caret.setToBlock(this.Editor.BlockManager.firstBlock, position, offset);
return true; return true;
} };
/** /**
* Sets caret to the last Block * Sets caret to the last Block
* *
* @param {string} position - position where to set caret * @param {string} position - position where to set caret
* @param {number} offset - caret offset * @param {number} offset - caret offset
*
* @returns {boolean} * @returns {boolean}
*/ */
private setToLastBlock = (position: string = this.Editor.Caret.positions.DEFAULT, offset = 0): boolean => { private setToLastBlock = (position: string = this.Editor.Caret.positions.DEFAULT, offset = 0): boolean => {
@ -56,14 +54,13 @@ export default class CaretAPI extends Module {
this.Editor.Caret.setToBlock(this.Editor.BlockManager.lastBlock, position, offset); this.Editor.Caret.setToBlock(this.Editor.BlockManager.lastBlock, position, offset);
return true; return true;
} };
/** /**
* Sets caret to the previous Block * Sets caret to the previous Block
* *
* @param {string} position - position where to set caret * @param {string} position - position where to set caret
* @param {number} offset - caret offset * @param {number} offset - caret offset
*
* @returns {boolean} * @returns {boolean}
*/ */
private setToPreviousBlock = ( private setToPreviousBlock = (
@ -77,14 +74,13 @@ export default class CaretAPI extends Module {
this.Editor.Caret.setToBlock(this.Editor.BlockManager.previousBlock, position, offset); this.Editor.Caret.setToBlock(this.Editor.BlockManager.previousBlock, position, offset);
return true; return true;
} };
/** /**
* Sets caret to the next Block * Sets caret to the next Block
* *
* @param {string} position - position where to set caret * @param {string} position - position where to set caret
* @param {number} offset - caret offset * @param {number} offset - caret offset
*
* @returns {boolean} * @returns {boolean}
*/ */
private setToNextBlock = (position: string = this.Editor.Caret.positions.DEFAULT, offset = 0): boolean => { private setToNextBlock = (position: string = this.Editor.Caret.positions.DEFAULT, offset = 0): boolean => {
@ -95,7 +91,7 @@ export default class CaretAPI extends Module {
this.Editor.Caret.setToBlock(this.Editor.BlockManager.nextBlock, position, offset); this.Editor.Caret.setToBlock(this.Editor.BlockManager.nextBlock, position, offset);
return true; return true;
} };
/** /**
* Sets caret to the Block by passed index * Sets caret to the Block by passed index
@ -103,7 +99,6 @@ export default class CaretAPI extends Module {
* @param {number} index - index of Block where to set caret * @param {number} index - index of Block where to set caret
* @param {string} position - position where to set caret * @param {string} position - position where to set caret
* @param {number} offset - caret offset * @param {number} offset - caret offset
*
* @returns {boolean} * @returns {boolean}
*/ */
private setToBlock = ( private setToBlock = (
@ -118,13 +113,12 @@ export default class CaretAPI extends Module {
this.Editor.Caret.setToBlock(this.Editor.BlockManager.blocks[index], position, offset); this.Editor.Caret.setToBlock(this.Editor.BlockManager.blocks[index], position, offset);
return true; return true;
} };
/** /**
* Sets caret to the Editor * Sets caret to the Editor
* *
* @param {boolean} atEnd - if true, set Caret to the end of the Editor * @param {boolean} atEnd - if true, set Caret to the end of the Editor
*
* @returns {boolean} * @returns {boolean}
*/ */
private focus = (atEnd = false): boolean => { private focus = (atEnd = false): boolean => {
@ -133,5 +127,5 @@ export default class CaretAPI extends Module {
} }
return this.setToFirstBlock(this.Editor.Caret.positions.START); return this.setToFirstBlock(this.Editor.Caret.positions.START);
} };
} }

View file

@ -1,4 +1,3 @@
import EventsDispatcher from '../../utils/events';
import { Notifier as INotifier } from '../../../../types/api'; import { Notifier as INotifier } from '../../../../types/api';
import Notifier from '../../utils/notifier'; import Notifier from '../../utils/notifier';
import { ConfirmNotifierOptions, NotifierOptions, PromptNotifierOptions } from 'codex-notifier'; import { ConfirmNotifierOptions, NotifierOptions, PromptNotifierOptions } from 'codex-notifier';
@ -15,10 +14,9 @@ export default class NotifierAPI extends Module {
private notifier: Notifier; private notifier: Notifier;
/** /**
* @class * @param moduleConfiguration - Module Configuration
* @param {object} moduleConfiguration - Module Configuration * @param moduleConfiguration.config - Editor's config
* @param {EditorConfig} moduleConfiguration.config - Editor's config * @param moduleConfiguration.eventsDispatcher - Editor's event dispatcher
* @param {EventsDispatcher} moduleConfiguration.eventsDispatcher - Editor's event dispatcher
*/ */
constructor({ config, eventsDispatcher }: ModuleConfig) { constructor({ config, eventsDispatcher }: ModuleConfig) {
super({ super({

View file

@ -25,7 +25,6 @@ export default class ReadOnlyAPI extends Module {
* Set or toggle read-only state * Set or toggle read-only state
* *
* @param {boolean|undefined} state - set or toggle state * @param {boolean|undefined} state - set or toggle state
*
* @returns {boolean} current value * @returns {boolean} current value
*/ */
public toggle(state?: boolean): Promise<boolean> { public toggle(state?: boolean): Promise<boolean> {

View file

@ -24,7 +24,6 @@ export default class SanitizerAPI extends Module {
* *
* @param {string} taintString - what to sanitize * @param {string} taintString - what to sanitize
* @param {SanitizerConfig} config - sanitizer config * @param {SanitizerConfig} config - sanitizer config
*
* @returns {string} * @returns {string}
*/ */
public clean(taintString: string, config: SanitizerConfig): string { public clean(taintString: string, config: SanitizerConfig): string {

View file

@ -24,7 +24,6 @@ export default class SelectionAPI extends Module {
* *
* @param {string} tagName - tag to find * @param {string} tagName - tag to find
* @param {string} className - tag's class name * @param {string} className - tag's class name
*
* @returns {HTMLElement|null} * @returns {HTMLElement|null}
*/ */
public findParentTag(tagName: string, className?: string): HTMLElement | null { public findParentTag(tagName: string, className?: string): HTMLElement | null {

View file

@ -1,5 +1,5 @@
/** /**
* Contains keyboard and mouse events binded on each Block by Block Manager * Contains keyboard and mouse events bound on each Block by Block Manager
*/ */
import Module from '../__module'; import Module from '../__module';
import * as _ from '../utils'; import * as _ from '../utils';
@ -233,7 +233,7 @@ export default class BlockEvents extends Module {
} }
/** /**
* Allow to create linebreaks by Shift+Enter * Allow to create line breaks by Shift+Enter
*/ */
if (event.shiftKey) { if (event.shiftKey) {
return; return;
@ -424,6 +424,7 @@ export default class BlockEvents extends Module {
if (this.Editor.BlockManager.currentBlock) { if (this.Editor.BlockManager.currentBlock) {
this.Editor.BlockManager.currentBlock.updateCurrentInput(); this.Editor.BlockManager.currentBlock.updateCurrentInput();
} }
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
}, 20)(); }, 20)();
} }
@ -482,6 +483,7 @@ export default class BlockEvents extends Module {
if (this.Editor.BlockManager.currentBlock) { if (this.Editor.BlockManager.currentBlock) {
this.Editor.BlockManager.currentBlock.updateCurrentInput(); this.Editor.BlockManager.currentBlock.updateCurrentInput();
} }
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
}, 20)(); }, 20)();
} }

View file

@ -1,9 +1,7 @@
/** /**
* @class BlockManager * @class BlockManager
* @classdesc Manage editor`s blocks storage and appearance * @classdesc Manage editor`s blocks storage and appearance
*
* @module BlockManager * @module BlockManager
*
* @version 2.0.0 * @version 2.0.0
*/ */
import Block, { BlockToolAPI } from '../block'; import Block, { BlockToolAPI } from '../block';
@ -184,9 +182,7 @@ export default class BlockManager extends Module {
* this._blocks[0] = new Block(...); * this._blocks[0] = new Block(...);
* *
* block = this._blocks[0]; * block = this._blocks[0];
*
* @todo proxy the enumerate method * @todo proxy the enumerate method
*
* @type {Proxy} * @type {Proxy}
* @private * @private
*/ */
@ -229,7 +225,6 @@ export default class BlockManager extends Module {
* @param {string} options.tool - tools passed in editor config {@link EditorConfig#tools} * @param {string} options.tool - tools passed in editor config {@link EditorConfig#tools}
* @param {string} [options.id] - unique id for this block * @param {string} [options.id] - unique id for this block
* @param {BlockToolData} [options.data] - constructor params * @param {BlockToolData} [options.data] - constructor params
*
* @returns {Block} * @returns {Block}
*/ */
public composeBlock({ public composeBlock({
@ -266,7 +261,6 @@ export default class BlockManager extends Module {
* @param {number} [options.index] - index where to insert new Block * @param {number} [options.index] - index where to insert new Block
* @param {boolean} [options.needToFocus] - flag shows if needed to update current Block index * @param {boolean} [options.needToFocus] - flag shows if needed to update current Block index
* @param {boolean} [options.replace] - flag shows if block by passed index should be replaced with inserted one * @param {boolean} [options.replace] - flag shows if block by passed index should be replaced with inserted one
*
* @returns {Block} * @returns {Block}
*/ */
public insert({ public insert({
@ -333,7 +327,6 @@ export default class BlockManager extends Module {
* @param {object} options - replace options * @param {object} options - replace options
* @param {string} options.tool plugin name * @param {string} options.tool plugin name
* @param {BlockToolData} options.data plugin data * @param {BlockToolData} options.data plugin data
*
* @returns {Block} * @returns {Block}
*/ */
public replace({ public replace({
@ -381,7 +374,6 @@ export default class BlockManager extends Module {
* @param {boolean} needToFocus - if true, updates current Block index * @param {boolean} needToFocus - if true, updates current Block index
* *
* TODO: Remove method and use insert() with index instead (?) * TODO: Remove method and use insert() with index instead (?)
*
* @returns {Block} inserted Block * @returns {Block} inserted Block
*/ */
public insertDefaultBlockAtIndex(index: number, needToFocus = false): Block { public insertDefaultBlockAtIndex(index: number, needToFocus = false): Block {
@ -427,7 +419,6 @@ export default class BlockManager extends Module {
* *
* @param {Block} targetBlock - previous block will be append to this block * @param {Block} targetBlock - previous block will be append to this block
* @param {Block} blockToMerge - block that will be merged with target block * @param {Block} blockToMerge - block that will be merged with target block
*
* @returns {Promise} - the sequence that can be continued * @returns {Promise} - the sequence that can be continued
*/ */
public async mergeBlocks(targetBlock: Block, blockToMerge: Block): Promise<void> { public async mergeBlocks(targetBlock: Block, blockToMerge: Block): Promise<void> {
@ -559,7 +550,6 @@ export default class BlockManager extends Module {
* Returns Block by passed index * Returns Block by passed index
* *
* @param {number} index - index to get. -1 to get last * @param {number} index - index to get. -1 to get last
*
* @returns {Block} * @returns {Block}
*/ */
public getBlockByIndex(index): Block { public getBlockByIndex(index): Block {
@ -583,7 +573,6 @@ export default class BlockManager extends Module {
* Returns the Block by passed id * Returns the Block by passed id
* *
* @param id - id of block to get * @param id - id of block to get
*
* @returns {Block} * @returns {Block}
*/ */
public getBlockById(id): Block | undefined { public getBlockById(id): Block | undefined {
@ -594,8 +583,6 @@ export default class BlockManager extends Module {
* Get Block instance by html element * Get Block instance by html element
* *
* @param {Node} element - html element to get Block by * @param {Node} element - html element to get Block by
*
* @returns {Block}
*/ */
public getBlock(element: HTMLElement): Block { public getBlock(element: HTMLElement): Block {
if (!$.isElement(element) as boolean) { if (!$.isElement(element) as boolean) {
@ -690,7 +677,6 @@ export default class BlockManager extends Module {
* Return block which contents passed node * Return block which contents passed node
* *
* @param {Node} childNode - node to get Block by * @param {Node} childNode - node to get Block by
*
* @returns {Block} * @returns {Block}
*/ */
public getBlockByChildNode(childNode: Node): Block { public getBlockByChildNode(childNode: Node): Block {
@ -711,7 +697,6 @@ export default class BlockManager extends Module {
* *
* @param {number} fromIndex - index of first block * @param {number} fromIndex - index of first block
* @param {number} toIndex - index of second block * @param {number} toIndex - index of second block
*
* @deprecated use 'move' instead * @deprecated use 'move' instead
*/ */
public swap(fromIndex, toIndex): void { public swap(fromIndex, toIndex): void {
@ -855,7 +840,6 @@ export default class BlockManager extends Module {
* Validates that the given index is not lower than 0 or higher than the amount of blocks * Validates that the given index is not lower than 0 or higher than the amount of blocks
* *
* @param {number} index - index of blocks array to validate * @param {number} index - index of blocks array to validate
*
* @returns {boolean} * @returns {boolean}
*/ */
private validateIndex(index: number): boolean { private validateIndex(index: number): boolean {

View file

@ -1,7 +1,6 @@
/** /**
* @class BlockSelection * @class BlockSelection
* @classdesc Manages Block selection with shortcut CMD+A * @classdesc Manages Block selection with shortcut CMD+A
*
* @module BlockSelection * @module BlockSelection
* @version 1.0.0 * @version 1.0.0
*/ */
@ -190,10 +189,8 @@ export default class BlockSelection extends Module {
* *
* - Remove all ranges * - Remove all ranges
* - Unselect all Blocks * - Unselect all Blocks
*
* @param {boolean} readOnlyEnabled - "read only" state
*/ */
public toggleReadOnly(readOnlyEnabled: boolean): void { public toggleReadOnly(): void {
SelectionUtils.get() SelectionUtils.get()
.removeAllRanges(); .removeAllRanges();
@ -250,12 +247,13 @@ export default class BlockSelection extends Module {
const eventKey = (reason as KeyboardEvent).key; const eventKey = (reason as KeyboardEvent).key;
/** /**
* If event.key length >1 that means key is special (e.g. Enter or Dead or Unidentifier). * If event.key length >1 that means key is special (e.g. Enter or Dead or Unidentified).
* So we use empty string * So we use empty string
* *
* @see https://developer.mozilla.org/ru/docs/Web/API/KeyboardEvent/key * @see https://developer.mozilla.org/ru/docs/Web/API/KeyboardEvent/key
*/ */
Caret.insertContentAtCaretPosition(eventKey.length > 1 ? '' : eventKey); Caret.insertContentAtCaretPosition(eventKey.length > 1 ? '' : eventKey);
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
}, 20)(); }, 20)();
} }
@ -283,7 +281,6 @@ export default class BlockSelection extends Module {
* Reduce each Block and copy its content * Reduce each Block and copy its content
* *
* @param {ClipboardEvent} e - copy/cut event * @param {ClipboardEvent} e - copy/cut event
*
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
public copySelectedBlocks(e: ClipboardEvent): Promise<void> { public copySelectedBlocks(e: ClipboardEvent): Promise<void> {

View file

@ -3,9 +3,7 @@
* @classdesc Contains methods for working Caret * @classdesc Contains methods for working Caret
* *
* Uses Range methods to manipulate with caret * Uses Range methods to manipulate with caret
*
* @module Caret * @module Caret
*
* @version 2.0.0 * @version 2.0.0
*/ */
@ -110,7 +108,7 @@ export default class Caret extends Module {
* Workaround case when block starts with several <br>'s (created by SHIFT+ENTER) * Workaround case when block starts with several <br>'s (created by SHIFT+ENTER)
* *
* @see https://github.com/codex-team/editor.js/issues/726 * @see https://github.com/codex-team/editor.js/issues/726
* We need to allow to delete such linebreaks, so in this case caret IS NOT AT START * We need to allow to delete such line breaks, so in this case caret IS NOT AT START
*/ */
const regularLineBreak = $.isLineBreakTag(node); const regularLineBreak = $.isLineBreakTag(node);
/** /**
@ -162,7 +160,7 @@ export default class Caret extends Module {
* In this case, anchor node has ELEMENT_NODE node type. * In this case, anchor node has ELEMENT_NODE node type.
* Anchor offset shows amount of children between start of the element and caret position. * Anchor offset shows amount of children between start of the element and caret position.
* *
* So we use child with anchofocusOffset - 1 as new focusNode. * So we use child with focusOffset - 1 as new focusNode.
*/ */
let focusOffset = selection.focusOffset; let focusOffset = selection.focusOffset;
@ -262,6 +260,7 @@ export default class Caret extends Module {
*/ */
_.delay(() => { _.delay(() => {
this.set(nodeToSet as HTMLElement, offset); this.set(nodeToSet as HTMLElement, offset);
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
}, 20)(); }, 20)();
BlockManager.setCurrentBlockByChildNode(block.holder); BlockManager.setCurrentBlockByChildNode(block.holder);
@ -509,6 +508,7 @@ export default class Caret extends Module {
newRange.selectNode(shadowCaret); newRange.selectNode(shadowCaret);
newRange.extractContents(); newRange.extractContents();
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
}, 50); }, 50);
} }
@ -549,7 +549,7 @@ export default class Caret extends Module {
} }
/** /**
* Get all first-level (first child of [contenteditabel]) siblings from passed node * Get all first-level (first child of [contenteditable]) siblings from passed node
* Then you can check it for emptiness * Then you can check it for emptiness
* *
* @example * @example
@ -562,10 +562,8 @@ export default class Caret extends Module {
* <p></p> | right first-level siblings * <p></p> | right first-level siblings
* <p></p> | * <p></p> |
* </div> * </div>
*
* @param {HTMLElement} from - element from which siblings should be searched * @param {HTMLElement} from - element from which siblings should be searched
* @param {'left' | 'right'} direction - direction of search * @param {'left' | 'right'} direction - direction of search
*
* @returns {HTMLElement[]} * @returns {HTMLElement[]}
*/ */
private getHigherLevelSiblings(from: HTMLElement, direction?: 'left' | 'right'): HTMLElement[] { private getHigherLevelSiblings(from: HTMLElement, direction?: 'left' | 'right'): HTMLElement[] {

View file

@ -176,7 +176,7 @@ export default class CrossBlockSelection extends Module {
private onMouseUp = (): void => { private onMouseUp = (): void => {
this.listeners.off(document, 'mouseover', this.onMouseOver); this.listeners.off(document, 'mouseover', this.onMouseOver);
this.listeners.off(document, 'mouseup', this.onMouseUp); this.listeners.off(document, 'mouseup', this.onMouseUp);
} };
/** /**
* Mouse over event handler * Mouse over event handler
@ -222,7 +222,7 @@ export default class CrossBlockSelection extends Module {
this.toggleBlocksSelectedState(relatedBlock, targetBlock); this.toggleBlocksSelectedState(relatedBlock, targetBlock);
this.lastSelectedBlock = targetBlock; this.lastSelectedBlock = targetBlock;
} };
/** /**
* Change blocks selection state between passed two blocks. * Change blocks selection state between passed two blocks.

View file

@ -105,9 +105,7 @@ interface PasteData {
/** /**
* @class Paste * @class Paste
* @classdesc Contains methods to handle paste on editor * @classdesc Contains methods to handle paste on editor
*
* @module Paste * @module Paste
*
* @version 2.0.0 * @version 2.0.0
*/ */
export default class Paste extends Module { export default class Paste extends Module {
@ -316,7 +314,7 @@ export default class Paste extends Module {
e e
); );
} }
} };
/** /**
* Get tags name list from either tag name or sanitization config. * Get tags name list from either tag name or sanitization config.
@ -455,7 +453,6 @@ export default class Paste extends Module {
* Check if browser behavior suits better * Check if browser behavior suits better
* *
* @param {EventTarget} element - element where content has been pasted * @param {EventTarget} element - element where content has been pasted
*
* @returns {boolean} * @returns {boolean}
*/ */
private isNativeBehaviour(element: EventTarget): boolean { private isNativeBehaviour(element: EventTarget): boolean {
@ -489,7 +486,7 @@ export default class Paste extends Module {
BlockManager.clearFocused(); BlockManager.clearFocused();
Toolbar.close(); Toolbar.close();
} };
/** /**
* Get files from data transfer object and insert related Tools * Get files from data transfer object and insert related Tools
@ -528,6 +525,7 @@ export default class Paste extends Module {
const foundConfig = Object const foundConfig = Object
.entries(this.toolsFiles) .entries(this.toolsFiles)
// eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars
.find(([toolName, { mimeTypes, extensions } ]) => { .find(([toolName, { mimeTypes, extensions } ]) => {
const [fileType, fileSubtype] = file.type.split('/'); const [fileType, fileSubtype] = file.type.split('/');
@ -560,7 +558,6 @@ export default class Paste extends Module {
* Split HTML string to blocks and return it as array of Block data * Split HTML string to blocks and return it as array of Block data
* *
* @param {string} innerHTML - html string to process * @param {string} innerHTML - html string to process
*
* @returns {PasteData[]} * @returns {PasteData[]}
*/ */
private processHTML(innerHTML: string): PasteData[] { private processHTML(innerHTML: string): PasteData[] {
@ -576,7 +573,6 @@ export default class Paste extends Module {
* - https://github.com/codex-team/editor.js/issues/1427 * - https://github.com/codex-team/editor.js/issues/1427
* - https://github.com/codex-team/editor.js/issues/1244 * - https://github.com/codex-team/editor.js/issues/1244
* - https://github.com/codex-team/editor.js/issues/740 * - https://github.com/codex-team/editor.js/issues/740
*
*/ */
const wrapper = $.make('DIV'); const wrapper = $.make('DIV');
@ -689,7 +685,6 @@ export default class Paste extends Module {
* Split plain text by new line symbols and return it as array of Block data * Split plain text by new line symbols and return it as array of Block data
* *
* @param {string} plain - string to process * @param {string} plain - string to process
*
* @returns {PasteData[]} * @returns {PasteData[]}
*/ */
private processPlain(plain: string): PasteData[] { private processPlain(plain: string): PasteData[] {
@ -725,7 +720,7 @@ export default class Paste extends Module {
/** /**
* Process paste of single Block tool content * Process paste of single Block tool content
* *
* @param {PasteData} dataToInsert - data of Block to inseret * @param {PasteData} dataToInsert - data of Block to insert
*/ */
private async processSingleBlock(dataToInsert: PasteData): Promise<void> { private async processSingleBlock(dataToInsert: PasteData): Promise<void> {
const { Caret, BlockManager } = this.Editor; const { Caret, BlockManager } = this.Editor;
@ -795,7 +790,6 @@ export default class Paste extends Module {
* Get patterns` matches * Get patterns` matches
* *
* @param {string} text - text to process * @param {string} text - text to process
*
* @returns {Promise<{event: PasteEvent, tool: string}>} * @returns {Promise<{event: PasteEvent, tool: string}>}
*/ */
private async processPattern(text: string): Promise<{ event: PasteEvent; tool: string }> { private async processPattern(text: string): Promise<{ event: PasteEvent; tool: string }> {
@ -829,7 +823,6 @@ export default class Paste extends Module {
* *
* @param {PasteData} data - data to insert * @param {PasteData} data - data to insert
* @param {boolean} canReplaceCurrentBlock - if true and is current Block is empty, will replace current Block * @param {boolean} canReplaceCurrentBlock - if true and is current Block is empty, will replace current Block
*
* @returns {void} * @returns {void}
*/ */
private insertBlock(data: PasteData, canReplaceCurrentBlock = false): void { private insertBlock(data: PasteData, canReplaceCurrentBlock = false): void {
@ -853,7 +846,6 @@ export default class Paste extends Module {
* Insert data passed as application/x-editor-js JSON * Insert data passed as application/x-editor-js JSON
* *
* @param {Array} blocks Blocks' data to insert * @param {Array} blocks Blocks' data to insert
*
* @returns {void} * @returns {void}
*/ */
private insertEditorJSData(blocks: Pick<SavedData, 'id' | 'data' | 'tool'>[]): void { private insertEditorJSData(blocks: Pick<SavedData, 'id' | 'data' | 'tool'>[]): void {
@ -887,8 +879,6 @@ export default class Paste extends Module {
* @param {Node} node - current node * @param {Node} node - current node
* @param {Node[]} nodes - processed nodes * @param {Node[]} nodes - processed nodes
* @param {Node} destNode - destination node * @param {Node} destNode - destination node
*
* @returns {Node[]}
*/ */
private processElementNode(node: Node, nodes: Node[], destNode: Node): Node[] | void { private processElementNode(node: Node, nodes: Node[], destNode: Node): Node[] | void {
const tags = Object.keys(this.toolsTags); const tags = Object.keys(this.toolsTags);
@ -931,7 +921,6 @@ export default class Paste extends Module {
* 2. Document Fragments contained text and markup tags like a, b, i etc. * 2. Document Fragments contained text and markup tags like a, b, i etc.
* *
* @param {Node} wrapper - wrapper of paster HTML content * @param {Node} wrapper - wrapper of paster HTML content
*
* @returns {Node[]} * @returns {Node[]}
*/ */
private getNodes(wrapper: Node): Node[] { private getNodes(wrapper: Node): Node[] {

View file

@ -6,9 +6,7 @@ import { CriticalError } from '../errors/critical';
* *
* Has one important method: * Has one important method:
* - {Function} toggleReadonly - Set read-only mode or toggle current state * - {Function} toggleReadonly - Set read-only mode or toggle current state
*
* @version 1.0.0 * @version 1.0.0
*
* @typedef {ReadOnly} ReadOnly * @typedef {ReadOnly} ReadOnly
* @property {boolean} readOnlyEnabled - read-only state * @property {boolean} readOnlyEnabled - read-only state
*/ */

View file

@ -1,7 +1,6 @@
/** /**
* @class RectangleSelection * @class RectangleSelection
* @classdesc Manages Block selection with mouse * @classdesc Manages Block selection with mouse
*
* @module RectangleSelection * @module RectangleSelection
* @version 1.0.0 * @version 1.0.0
*/ */
@ -188,6 +187,7 @@ export default class RectangleSelection extends Module {
this.listeners.on(document.body, 'mousemove', _.throttle((mouseEvent: MouseEvent) => { this.listeners.on(document.body, 'mousemove', _.throttle((mouseEvent: MouseEvent) => {
this.processMouseMove(mouseEvent); this.processMouseMove(mouseEvent);
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
}, 10), { }, 10), {
passive: true, passive: true,
}); });
@ -198,6 +198,7 @@ export default class RectangleSelection extends Module {
this.listeners.on(window, 'scroll', _.throttle((mouseEvent: MouseEvent) => { this.listeners.on(window, 'scroll', _.throttle((mouseEvent: MouseEvent) => {
this.processScroll(mouseEvent); this.processScroll(mouseEvent);
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
}, 10), { }, 10), {
passive: true, passive: true,
}); });
@ -290,7 +291,7 @@ export default class RectangleSelection extends Module {
/** /**
* Generates required HTML elements * Generates required HTML elements
* *
* @returns {object<string, Element>} * @returns {Object<string, Element>}
*/ */
private genHTML(): {container: Element; overlay: Element} { private genHTML(): {container: Element; overlay: Element} {
const { UI } = this.Editor; const { UI } = this.Editor;

View file

@ -8,7 +8,6 @@ import BlockTool from '../tools/block';
* *
* @module Renderer * @module Renderer
* @author CodeX Team * @author CodeX Team
*
* @version 2.0.0 * @version 2.0.0
*/ */
export default class Renderer extends Module { export default class Renderer extends Module {
@ -37,7 +36,6 @@ export default class Renderer extends Module {
* } * }
* }, * },
* ] * ]
*
*/ */
/** /**
@ -68,7 +66,6 @@ export default class Renderer extends Module {
* Insert block to working zone * Insert block to working zone
* *
* @param {object} item - Block data to insert * @param {object} item - Block data to insert
*
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
public async insertBlock(item: OutputBlockData): Promise<void> { public async insertBlock(item: OutputBlockData): Promise<void> {

View file

@ -16,7 +16,6 @@ declare const VERSION: string;
/** /**
* @classdesc This method reduces all Blocks asyncronically and calls Block's save method to extract data * @classdesc This method reduces all Blocks asyncronically and calls Block's save method to extract data
*
* @typedef {Saver} Saver * @typedef {Saver} Saver
* @property {Element} html - Editor HTML content * @property {Element} html - Editor HTML content
* @property {string} json - Editor JSON output * @property {string} json - Editor JSON output

View file

@ -1,6 +1,5 @@
import Module from '../../__module'; import Module from '../../__module';
import $ from '../../dom'; import $ from '../../dom';
import * as _ from '../../utils';
import SelectionUtils from '../../selection'; import SelectionUtils from '../../selection';
import Block from '../../block'; import Block from '../../block';
import Popover, { PopoverEvent } from '../../utils/popover'; import Popover, { PopoverEvent } from '../../utils/popover';
@ -192,5 +191,5 @@ export default class BlockSettings extends Module<BlockSettingsNodes> {
*/ */
private onOverlayClicked = (): void => { private onOverlayClicked = (): void => {
this.close(); this.close();
} };
} }

View file

@ -50,7 +50,7 @@ export default class ConversionToolbar extends Module<ConversionToolbarNodes> {
/** /**
* Available tools data * Available tools data
*/ */
private tools: {name: string; toolboxItem: ToolboxConfigEntry; button: HTMLElement}[] = [] private tools: {name: string; toolboxItem: ToolboxConfigEntry; button: HTMLElement}[] = [];
/** /**
* Instance of class that responses for leafing buttons by arrows/tab * Instance of class that responses for leafing buttons by arrows/tab
@ -184,8 +184,6 @@ export default class ConversionToolbar extends Module<ConversionToolbarNodes> {
public async replaceWithBlock(replacingToolName: string, blockDataOverrides?: BlockToolData): Promise<void> { public async replaceWithBlock(replacingToolName: string, blockDataOverrides?: BlockToolData): Promise<void> {
/** /**
* At first, we get current Block data * At first, we get current Block data
*
* @type {BlockToolConstructable}
*/ */
const currentBlockTool = this.Editor.BlockManager.currentBlock.tool; const currentBlockTool = this.Editor.BlockManager.currentBlock.tool;
const savedBlock = await this.Editor.BlockManager.currentBlock.save() as SavedData; const savedBlock = await this.Editor.BlockManager.currentBlock.save() as SavedData;
@ -193,8 +191,6 @@ export default class ConversionToolbar extends Module<ConversionToolbarNodes> {
/** /**
* Getting a class of replacing Tool * Getting a class of replacing Tool
*
* @type {BlockToolConstructable}
*/ */
const replacingTool = this.Editor.Tools.blockTools.get(replacingToolName); const replacingTool = this.Editor.Tools.blockTools.get(replacingToolName);
@ -265,6 +261,7 @@ export default class ConversionToolbar extends Module<ConversionToolbarNodes> {
_.delay(() => { _.delay(() => {
this.Editor.Caret.setToBlock(this.Editor.BlockManager.currentBlock); this.Editor.Caret.setToBlock(this.Editor.BlockManager.currentBlock);
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
}, 10)(); }, 10)();
} }

View file

@ -12,21 +12,19 @@ import Toolbox, { ToolboxEvent } from '../../ui/toolbox';
/** /**
* @todo Tab on non-empty block should open Block Settings of the hoveredBlock (not where caret is set) * @todo Tab on non-empty block should open Block Settings of the hoveredBlock (not where caret is set)
* - make Block Settings a standalone module * - make Block Settings a standalone module
*
* @todo - Keyboard-only mode bug: * @todo - Keyboard-only mode bug:
* press Tab, flip to the Checkbox. press Enter (block will be added), Press Tab * press Tab, flip to the Checkbox. press Enter (block will be added), Press Tab
* (Block Tunes will be opened with Move up focused), press Enter, press Tab both Block Tunes and Toolbox will be opened * (Block Tunes will be opened with Move up focused), press Enter, press Tab both Block Tunes and Toolbox will be opened
* * @todo TEST CASE - show toggler after opening and closing the Inline Toolbar
* @todo TESTCASE - show toggler after opening and closing the Inline Toolbar * @todo TEST CASE - Click outside Editor holder should close Toolbar and Clear Focused blocks
* @todo TESTCASE - Click outside Editor holder should close Toolbar and Clear Focused blocks * @todo TEST CASE - Click inside Editor holder should close Toolbar and Clear Focused blocks
* @todo TESTCASE - Click inside Editor holder should close Toolbar and Clear Focused blocks * @todo TEST CASE - Click inside Redactor zone when Block Settings are opened:
* @todo TESTCASE - Click inside Redactor zone when Block Settings are opened:
* - should close Block Settings * - should close Block Settings
* - should not close Toolbar * - should not close Toolbar
* - should move Toolbar to the clicked Block * - should move Toolbar to the clicked Block
* @todo TESTCASE - Toolbar should be closed on the Cross Block Selection * @todo TEST CASE - Toolbar should be closed on the Cross Block Selection
* @todo TESTCASE - Toolbar should be closed on the Rectangle Selection * @todo TEST CASE - Toolbar should be closed on the Rectangle Selection
* @todo TESTCASE - If Block Settings or Toolbox are opened, the Toolbar should not be moved by Bocks hovering * @todo TEST CASE - If Block Settings or Toolbox are opened, the Toolbar should not be moved by Bocks hovering
*/ */
/** /**
@ -78,7 +76,6 @@ interface ToolbarNodes {
* *
* @class * @class
* @classdesc Toolbar module * @classdesc Toolbar module
*
* @typedef {Toolbar} Toolbar * @typedef {Toolbar} Toolbar
* @property {object} nodes - Toolbar nodes * @property {object} nodes - Toolbar nodes
* @property {Element} nodes.wrapper - Toolbar main element * @property {Element} nodes.wrapper - Toolbar main element
@ -300,12 +297,8 @@ export default class Toolbar extends Module<ToolbarNodes> {
* *
* @param {boolean} withBlockActions - by default, Toolbar opens with Block Actions. * @param {boolean} withBlockActions - by default, Toolbar opens with Block Actions.
* This flag allows to open Toolbar without Actions. * This flag allows to open Toolbar without Actions.
* @param {boolean} needToCloseToolbox - by default, Toolbar will be moved with opening
* (by click on Block, or by enter)
* with closing Toolbox and Block Settings
* This flag allows to open Toolbar with Toolbox
*/ */
private open(withBlockActions = true, needToCloseToolbox = true): void { private open(withBlockActions = true): void {
_.delay(() => { _.delay(() => {
this.nodes.wrapper.classList.add(this.CSS.toolbarOpened); this.nodes.wrapper.classList.add(this.CSS.toolbarOpened);
@ -314,6 +307,7 @@ export default class Toolbar extends Module<ToolbarNodes> {
} else { } else {
this.blockActions.hide(); this.blockActions.hide();
} }
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
}, 50)(); }, 50)();
} }
@ -342,6 +336,7 @@ export default class Toolbar extends Module<ToolbarNodes> {
* - Toolbox * - Toolbox
*/ */
this.nodes.plusButton = $.make('div', this.CSS.plusButton); this.nodes.plusButton = $.make('div', this.CSS.plusButton);
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
$.append(this.nodes.plusButton, $.svg('plus', 16, 16)); $.append(this.nodes.plusButton, $.svg('plus', 16, 16));
$.append(this.nodes.actions, this.nodes.plusButton); $.append(this.nodes.actions, this.nodes.plusButton);
@ -371,6 +366,7 @@ export default class Toolbar extends Module<ToolbarNodes> {
* - Settings Panel * - Settings Panel
*/ */
this.nodes.settingsToggler = $.make('span', this.CSS.settingsToggler); this.nodes.settingsToggler = $.make('span', this.CSS.settingsToggler);
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
const settingsIcon = $.svg('dots', 16, 16); const settingsIcon = $.svg('dots', 16, 16);
$.append(this.nodes.settingsToggler, settingsIcon); $.append(this.nodes.settingsToggler, settingsIcon);
@ -478,7 +474,7 @@ export default class Toolbar extends Module<ToolbarNodes> {
}, true); }, true);
/** /**
* Subscribe to the 'block-hovered' event if currenct view is not mobile * Subscribe to the 'block-hovered' event if current view is not mobile
* *
* @see https://github.com/codex-team/editor.js/issues/1972 * @see https://github.com/codex-team/editor.js/issues/1972
*/ */

View file

@ -280,7 +280,7 @@ export default class InlineToolbar extends Module<InlineToolbarNodes> {
/** /**
* Check if node is contained by Inline Toolbar * Check if node is contained by Inline Toolbar
* *
* @param {Node} node node to chcek * @param {Node} node node to check
*/ */
public containsNode(node: Node): boolean { public containsNode(node: Node): boolean {
return this.nodes.wrapper.contains(node); return this.nodes.wrapper.contains(node);
@ -322,7 +322,7 @@ export default class InlineToolbar extends Module<InlineToolbarNodes> {
const isClickedOnActionsWrapper = (event.target as Element).closest(`.${this.CSS.actionsWrapper}`); const isClickedOnActionsWrapper = (event.target as Element).closest(`.${this.CSS.actionsWrapper}`);
// If click is on actions wrapper, // If click is on actions wrapper,
// do not prevent default behaviour because actions might include interactive elements // do not prevent default behavior because actions might include interactive elements
if (!isClickedOnActionsWrapper) { if (!isClickedOnActionsWrapper) {
event.preventDefault(); event.preventDefault();
} }
@ -428,6 +428,7 @@ export default class InlineToolbar extends Module<InlineToolbarNodes> {
this.nodes.conversionToggler = $.make('div', this.CSS.conversionToggler); this.nodes.conversionToggler = $.make('div', this.CSS.conversionToggler);
this.nodes.conversionTogglerContent = $.make('div', this.CSS.conversionTogglerContent); this.nodes.conversionTogglerContent = $.make('div', this.CSS.conversionTogglerContent);
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
const icon = $.svg('toggler-down', 13, 13); const icon = $.svg('toggler-down', 13, 13);
this.nodes.conversionToggler.appendChild(this.nodes.conversionTogglerContent); this.nodes.conversionToggler.appendChild(this.nodes.conversionTogglerContent);

View file

@ -21,17 +21,8 @@ import ToolsCollection from '../tools/collection';
* Creates Instances from Plugins and binds external config to the instances * Creates Instances from Plugins and binds external config to the instances
*/ */
type ToolClass = BlockTool | InlineTool | BlockTune;
/** /**
* Class properties: * Modules that works with tools classes
*
* @typedef {Tools} Tools
* @property {Tools[]} toolsAvailable - available Tools
* @property {Tools[]} toolsUnavailable - unavailable Tools
* @property {object} toolsClasses - all classes
* @property {object} toolsSettings - Tools settings
* @property {EditorConfig} config - Editor config
*/ */
export default class Tools extends Module { export default class Tools extends Module {
/** /**
@ -44,8 +35,6 @@ export default class Tools extends Module {
/** /**
* Returns available Tools * Returns available Tools
*
* @returns {object<Tool>}
*/ */
public get available(): ToolsCollection { public get available(): ToolsCollection {
return this.toolsAvailable; return this.toolsAvailable;
@ -53,8 +42,6 @@ export default class Tools extends Module {
/** /**
* Returns unavailable Tools * Returns unavailable Tools
*
* @returns {Tool[]}
*/ */
public get unavailable(): ToolsCollection { public get unavailable(): ToolsCollection {
return this.toolsUnavailable; return this.toolsUnavailable;
@ -62,8 +49,6 @@ export default class Tools extends Module {
/** /**
* Return Tools for the Inline Toolbar * Return Tools for the Inline Toolbar
*
* @returns {object} - object of Inline Tool's classes
*/ */
public get inlineTools(): ToolsCollection<InlineTool> { public get inlineTools(): ToolsCollection<InlineTool> {
return this.available.inlineTools; return this.available.inlineTools;

View file

@ -16,6 +16,7 @@ import * as _ from '../utils';
import Selection from '../selection'; import Selection from '../selection';
import Block from '../block'; import Block from '../block';
import Flipper from '../flipper'; import Flipper from '../flipper';
import { mobileScreenBreakpoint } from '../utils';
/** /**
* HTML Elements used for UI * HTML Elements used for UI
@ -29,14 +30,12 @@ interface UINodes {
/** /**
* @class * @class
*
* @classdesc Makes Editor.js UI: * @classdesc Makes Editor.js UI:
* <codex-editor> * <codex-editor>
* <ce-redactor /> * <ce-redactor />
* <ce-toolbar /> * <ce-toolbar />
* <ce-inline-toolbar /> * <ce-inline-toolbar />
* </codex-editor> * </codex-editor>
*
* @typedef {UI} UI * @typedef {UI} UI
* @property {EditorConfig} config - editor configuration {@link EditorJS#configuration} * @property {EditorConfig} config - editor configuration {@link EditorJS#configuration}
* @property {object} Editor - available editor modules {@link EditorJS#moduleInstances} * @property {object} Editor - available editor modules {@link EditorJS#moduleInstances}
@ -125,6 +124,7 @@ export default class UI extends Module<UINodes> {
*/ */
private resizeDebouncer: () => void = _.debounce(() => { private resizeDebouncer: () => void = _.debounce(() => {
this.windowResize(); this.windowResize();
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
}, 200); }, 200);
/** /**
@ -235,12 +235,15 @@ export default class UI extends Module<UINodes> {
return true; return true;
} }
return Object.entries(this.Editor).filter(([moduleName, moduleClass]) => { /* eslint-disable @typescript-eslint/no-unused-vars, no-unused-vars */
return Object.entries(this.Editor).filter(([_moduleName, moduleClass]) => {
return moduleClass.flipper instanceof Flipper; return moduleClass.flipper instanceof Flipper;
}) })
.some(([moduleName, moduleClass]) => { .some(([_moduleName, moduleClass]) => {
return moduleClass.flipper.hasFocus(); return moduleClass.flipper.hasFocus();
}); });
/* eslint-enable @typescript-eslint/no-unused-vars, no-unused-vars */
} }
/** /**
@ -266,7 +269,7 @@ export default class UI extends Module<UINodes> {
* Check for mobile mode and cache a result * Check for mobile mode and cache a result
*/ */
private checkIsMobile(): void { private checkIsMobile(): void {
this.isMobile = window.innerWidth < 650; this.isMobile = window.innerWidth < mobileScreenBreakpoint;
} }
/** /**
@ -364,8 +367,8 @@ export default class UI extends Module<UINodes> {
/** /**
* Handle selection change to manipulate Inline Toolbar appearance * Handle selection change to manipulate Inline Toolbar appearance
*/ */
this.readOnlyMutableListeners.on(document, 'selectionchange', (event: Event) => { this.readOnlyMutableListeners.on(document, 'selectionchange', () => {
this.selectionChanged(event); this.selectionChanged();
}, true); }, true);
this.readOnlyMutableListeners.on(window, 'resize', () => { this.readOnlyMutableListeners.on(window, 'resize', () => {
@ -412,6 +415,7 @@ export default class UI extends Module<UINodes> {
this.eventsDispatcher.emit(this.events.blockHovered, { this.eventsDispatcher.emit(this.events.blockHovered, {
block: this.Editor.BlockManager.getBlockByChildNode(hoveredBlock), block: this.Editor.BlockManager.getBlockByChildNode(hoveredBlock),
}); });
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
}, 20), { }, 20), {
passive: true, passive: true,
}); });
@ -726,7 +730,6 @@ export default class UI extends Module<UINodes> {
* All clicks on the redactor zone * All clicks on the redactor zone
* *
* @param {MouseEvent} event - click event * @param {MouseEvent} event - click event
*
* @description * @description
* - By clicks on the Editor's bottom zone: * - By clicks on the Editor's bottom zone:
* - if last Block is empty, set a Caret to this * - if last Block is empty, set a Caret to this
@ -804,10 +807,8 @@ export default class UI extends Module<UINodes> {
/** /**
* Handle selection changes on mobile devices * Handle selection changes on mobile devices
* Uses for showing the Inline Toolbar * Uses for showing the Inline Toolbar
*
* @param {Event} event - selection event
*/ */
private selectionChanged(event: Event): void { private selectionChanged(): void {
const { CrossBlockSelection, BlockSelection } = this.Editor; const { CrossBlockSelection, BlockSelection } = this.Editor;
const focusedElement = Selection.anchorElement; const focusedElement = Selection.anchorElement;

View file

@ -19,7 +19,6 @@ interface Element {
* otherwise, returns false. * otherwise, returns false.
* *
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Element/matches#Polyfill} * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Element/matches#Polyfill}
*
* @param {string} s - selector * @param {string} s - selector
*/ */
if (!Element.prototype.matches) { if (!Element.prototype.matches) {
@ -46,7 +45,6 @@ if (!Element.prototype.matches) {
* If there isn't such an ancestor, it returns null. * If there isn't such an ancestor, it returns null.
* *
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill} * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill}
*
* @param {string} s - selector * @param {string} s - selector
*/ */
if (!Element.prototype.closest) { if (!Element.prototype.closest) {
@ -76,7 +74,6 @@ if (!Element.prototype.closest) {
* DOMString objects are inserted as equivalent Text nodes. * DOMString objects are inserted as equivalent Text nodes.
* *
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/prepend#Polyfill} * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/prepend#Polyfill}
*
* @param {Node | Node[] | string | string[]} nodes - nodes to prepend * @param {Node | Node[] | string | string[]} nodes - nodes to prepend
*/ */
if (!Element.prototype.prepend) { if (!Element.prototype.prepend) {

View file

@ -146,7 +146,7 @@ export default class SelectionUtils {
/** /**
* Check if passed selection is at Editor's zone * Check if passed selection is at Editor's zone
* *
* @param selection - Selectoin object to check * @param selection - Selection object to check
*/ */
public static isSelectionAtEditor(selection: Selection): boolean { public static isSelectionAtEditor(selection: Selection): boolean {
if (!selection) { if (!selection) {
@ -326,8 +326,6 @@ export default class SelectionUtils {
* *
* @param element - element where to set focus * @param element - element where to set focus
* @param offset - offset of cursor * @param offset - offset of cursor
*
* @returns {DOMRect} of range
*/ */
public static setCursor(element: HTMLElement, offset = 0): DOMRect { public static setCursor(element: HTMLElement, offset = 0): DOMRect {
const range = document.createRange(); const range = document.createRange();
@ -452,7 +450,6 @@ export default class SelectionUtils {
* @param {string} tagName - tag to found * @param {string} tagName - tag to found
* @param {string} [className] - tag's class name * @param {string} [className] - tag's class name
* @param {number} [searchDepth] - count of tags that can be included. For better performance. * @param {number} [searchDepth] - count of tags that can be included. For better performance.
*
* @returns {HTMLElement|null} * @returns {HTMLElement|null}
*/ */
public findParentTag(tagName: string, className?: string, searchDepth = 10): HTMLElement | null { public findParentTag(tagName: string, className?: string, searchDepth = 10): HTMLElement | null {
@ -526,7 +523,7 @@ export default class SelectionUtils {
/** /**
* Expands selection range to the passed parent node * Expands selection range to the passed parent node
* *
* @param {HTMLElement} element - element which contents should be selcted * @param {HTMLElement} element - element which contents should be selected
*/ */
public expandToTag(element: HTMLElement): void { public expandToTag(element: HTMLElement): void {
const selection = window.getSelection(); const selection = window.getSelection();

View file

@ -67,11 +67,11 @@ export enum CommonInternalSettings {
} }
/** /**
* Enum of Tool optoins provided by Block Tool * Enum of Tool options provided by Block Tool
*/ */
export enum InternalBlockToolSettings { export enum InternalBlockToolSettings {
/** /**
* Is linebreaks enabled for Tool * Is line breaks enabled for Tool
*/ */
IsEnabledLineBreaks = 'enableLineBreaks', IsEnabledLineBreaks = 'enableLineBreaks',
/** /**
@ -116,7 +116,7 @@ export enum InternalTuneSettings {
IsTune = 'isTune', IsTune = 'isTune',
} }
export type ToolOptions = Omit<ToolSettings, 'class'> export type ToolOptions = Omit<ToolSettings, 'class'>;
interface ConstructorOptions { interface ConstructorOptions {
name: string; name: string;
@ -174,8 +174,7 @@ export default abstract class BaseTool<Type extends Tool = Tool> {
/** /**
* @class * @class
* * @param {ConstructorOptions} options - Constructor options
* @param {ConstructorOptions} - Constructor options
*/ */
constructor({ constructor({
name, name,

View file

@ -29,7 +29,6 @@ export default class ToolsFactory {
/** /**
* @class * @class
*
* @param config - tools config * @param config - tools config
* @param editorConfig - EditorJS config * @param editorConfig - EditorJS config
* @param api - EditorJS API module * @param api - EditorJS API module

View file

@ -36,7 +36,7 @@ export enum ToolboxEvent {
/** /**
* Available i18n dict keys that should be passed to the constructor * Available i18n dict keys that should be passed to the constructor
*/ */
type toolboxTextLabelsKeys = 'filter' | 'nothingFound'; type ToolboxTextLabelsKeys = 'filter' | 'nothingFound';
/** /**
* Toolbox * Toolbox
@ -80,7 +80,7 @@ export default class Toolbox extends EventsDispatcher<ToolboxEvent> {
/** /**
* Text labels used in the Toolbox. Should be passed from the i18n module * Text labels used in the Toolbox. Should be passed from the i18n module
*/ */
private i18nLabels: Record<toolboxTextLabelsKeys, string>; private i18nLabels: Record<ToolboxTextLabelsKeys, string>;
/** /**
* Current module HTML Elements * Current module HTML Elements
@ -88,13 +88,13 @@ export default class Toolbox extends EventsDispatcher<ToolboxEvent> {
private nodes: { private nodes: {
toolbox: HTMLElement; toolbox: HTMLElement;
} = { } = {
toolbox: null, toolbox: null,
}; };
/** /**
* CSS styles * CSS styles
* *
* @returns {object.<string, string>} * @returns {Object<string, string>}
*/ */
private static get CSS(): { [name: string]: string } { private static get CSS(): { [name: string]: string } {
return { return {
@ -114,7 +114,7 @@ export default class Toolbox extends EventsDispatcher<ToolboxEvent> {
* @param options.api - Editor API methods * @param options.api - Editor API methods
* @param options.tools - Tools available to check whether some of them should be displayed at the Toolbox or not * @param options.tools - Tools available to check whether some of them should be displayed at the Toolbox or not
*/ */
constructor({ api, tools, i18nLabels }: {api: API; tools: ToolsCollection<BlockTool>; i18nLabels: Record<toolboxTextLabelsKeys, string>}) { constructor({ api, tools, i18nLabels }: {api: API; tools: ToolsCollection<BlockTool>; i18nLabels: Record<ToolboxTextLabelsKeys, string>}) {
super(); super();
this.api = api; this.api = api;
@ -219,7 +219,7 @@ export default class Toolbox extends EventsDispatcher<ToolboxEvent> {
*/ */
private onOverlayClicked = (): void => { private onOverlayClicked = (): void => {
this.close(); this.close();
} };
/** /**
* Returns list of tools that enables the Toolbox (by specifying the 'toolbox' getter) * Returns list of tools that enables the Toolbox (by specifying the 'toolbox' getter)
@ -259,7 +259,7 @@ export default class Toolbox extends EventsDispatcher<ToolboxEvent> {
icon: toolboxItem.icon, icon: toolboxItem.icon,
label: I18n.t(I18nInternalNS.toolNames, toolboxItem.title || _.capitalize(tool.name)), label: I18n.t(I18nInternalNS.toolNames, toolboxItem.title || _.capitalize(tool.name)),
name: tool.name, name: tool.name,
onActivate: (e): void => { onActivate: (): void => {
this.toolButtonActivated(tool.name, toolboxItem.data); this.toolButtonActivated(tool.name, toolboxItem.data);
}, },
secondaryLabel: tool.shortcut ? _.beautifyShortcut(tool.shortcut) : '', secondaryLabel: tool.shortcut ? _.beautifyShortcut(tool.shortcut) : '',

View file

@ -24,7 +24,6 @@ declare const VERSION: string;
* @typedef {object} ChainData * @typedef {object} ChainData
* @property {object} data - data that will be passed to the success or fallback * @property {object} data - data that will be passed to the success or fallback
* @property {Function} function - function's that must be called asynchronously * @property {Function} function - function's that must be called asynchronously
*
* @interface ChainData * @interface ChainData
*/ */
export interface ChainData { export interface ChainData {
@ -38,7 +37,7 @@ export interface ChainData {
*/ */
/** /**
* Returns basic keycodes as constants * Returns basic key codes as constants
* *
* @returns {{}} * @returns {{}}
*/ */
@ -178,7 +177,6 @@ export const logLabeled = _log.bind(window, true);
* Return string representation of the object type * Return string representation of the object type
* *
* @param {*} object - object to get type * @param {*} object - object to get type
*
* @returns {string} * @returns {string}
*/ */
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
@ -190,7 +188,6 @@ export function typeOf(object: any): string {
* Check if passed variable is a function * Check if passed variable is a function
* *
* @param {*} fn - function to check * @param {*} fn - function to check
*
* @returns {boolean} * @returns {boolean}
*/ */
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
@ -202,7 +199,6 @@ export function isFunction(fn: any): fn is (...args: any[]) => any {
* Checks if passed argument is an object * Checks if passed argument is an object
* *
* @param {*} v - object to check * @param {*} v - object to check
*
* @returns {boolean} * @returns {boolean}
*/ */
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
@ -214,7 +210,6 @@ export function isObject(v: any): v is object {
* Checks if passed argument is a string * Checks if passed argument is a string
* *
* @param {*} v - variable to check * @param {*} v - variable to check
*
* @returns {boolean} * @returns {boolean}
*/ */
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
@ -226,7 +221,6 @@ export function isString(v: any): v is string {
* Checks if passed argument is boolean * Checks if passed argument is boolean
* *
* @param {*} v - variable to check * @param {*} v - variable to check
*
* @returns {boolean} * @returns {boolean}
*/ */
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
@ -238,7 +232,6 @@ export function isBoolean(v: any): v is boolean {
* Checks if passed argument is number * Checks if passed argument is number
* *
* @param {*} v - variable to check * @param {*} v - variable to check
*
* @returns {boolean} * @returns {boolean}
*/ */
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
@ -250,7 +243,6 @@ export function isNumber(v: any): v is number {
* Checks if passed argument is undefined * Checks if passed argument is undefined
* *
* @param {*} v - variable to check * @param {*} v - variable to check
*
* @returns {boolean} * @returns {boolean}
*/ */
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
@ -262,7 +254,6 @@ export function isUndefined(v: any): v is undefined {
* Check if passed function is a class * Check if passed function is a class
* *
* @param {Function} fn - function to check * @param {Function} fn - function to check
*
* @returns {boolean} * @returns {boolean}
*/ */
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
@ -274,7 +265,6 @@ export function isClass(fn: any): boolean {
* Checks if object is empty * Checks if object is empty
* *
* @param {object} object - object to check * @param {object} object - object to check
*
* @returns {boolean} * @returns {boolean}
*/ */
export function isEmpty(object: object): boolean { export function isEmpty(object: object): boolean {
@ -296,22 +286,23 @@ export function isPromise(object: any): object is Promise<any> {
return Promise.resolve(object) === object; return Promise.resolve(object) === object;
} }
/* eslint-disable @typescript-eslint/no-magic-numbers */
/** /**
* Returns true if passed key code is printable (a-Z, 0-9, etc) character. * Returns true if passed key code is printable (a-Z, 0-9, etc) character.
* *
* @param {number} keyCode - key code * @param {number} keyCode - key code
*
* @returns {boolean} * @returns {boolean}
*/ */
export function isPrintableKey(keyCode: number): boolean { export function isPrintableKey(keyCode: number): boolean {
return (keyCode > 47 && keyCode < 58) || // number keys return (keyCode > 47 && keyCode < 58) || // number keys
keyCode === 32 || keyCode === 13 || // Spacebar & return key(s) keyCode === 32 || keyCode === 13 || // Space bar & return key(s)
keyCode === 229 || // processing key input for certain languages — Chinese, Japanese, etc. keyCode === 229 || // processing key input for certain languages — Chinese, Japanese, etc.
(keyCode > 64 && keyCode < 91) || // letter keys (keyCode > 64 && keyCode < 91) || // letter keys
(keyCode > 95 && keyCode < 112) || // Numpad keys (keyCode > 95 && keyCode < 112) || // Numpad keys
(keyCode > 185 && keyCode < 193) || // ;=,-./` (in order) (keyCode > 185 && keyCode < 193) || // ;=,-./` (in order)
(keyCode > 218 && keyCode < 223); // [\]' (in order) (keyCode > 218 && keyCode < 223); // [\]' (in order)
} }
/* eslint-enable @typescript-eslint/no-magic-numbers */
/** /**
* Fires a promise sequence asynchronously * Fires a promise sequence asynchronously
@ -319,7 +310,6 @@ export function isPrintableKey(keyCode: number): boolean {
* @param {ChainData[]} chains - list or ChainData's * @param {ChainData[]} chains - list or ChainData's
* @param {Function} success - success callback * @param {Function} success - success callback
* @param {Function} fallback - callback that fires in case of errors * @param {Function} fallback - callback that fires in case of errors
*
* @returns {Promise} * @returns {Promise}
*/ */
export async function sequence( export async function sequence(
@ -333,10 +323,8 @@ export async function sequence(
* Decorator * Decorator
* *
* @param {ChainData} chainData - Chain data * @param {ChainData} chainData - Chain data
*
* @param {Function} successCallback - success callback * @param {Function} successCallback - success callback
* @param {Function} fallbackCallback - fail callback * @param {Function} fallbackCallback - fail callback
*
* @returns {Promise} * @returns {Promise}
*/ */
async function waitNextBlock( async function waitNextBlock(
@ -370,7 +358,6 @@ export async function sequence(
* Make array from array-like collection * Make array from array-like collection
* *
* @param {ArrayLike} collection - collection to convert to array * @param {ArrayLike} collection - collection to convert to array
*
* @returns {Array} * @returns {Array}
*/ */
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
@ -400,7 +387,6 @@ export function delay(method: (...args: any[]) => any, timeout: number) {
* Get file extension * Get file extension
* *
* @param {File} file - file * @param {File} file - file
*
* @returns {string} * @returns {string}
*/ */
export function getFileExtension(file: File): string { export function getFileExtension(file: File): string {
@ -411,7 +397,6 @@ export function getFileExtension(file: File): string {
* Check if string is MIME type * Check if string is MIME type
* *
* @param {string} type - string to check * @param {string} type - string to check
*
* @returns {boolean} * @returns {boolean}
*/ */
export function isValidMimeType(type: string): boolean { export function isValidMimeType(type: string): boolean {
@ -492,6 +477,7 @@ export function throttle(func, wait, options: {leading?: boolean; trailing?: boo
const remaining = wait - (now - previous); const remaining = wait - (now - previous);
// eslint-disable-next-line @typescript-eslint/no-this-alias
context = this; context = this;
// eslint-disable-next-line prefer-rest-params // eslint-disable-next-line prefer-rest-params
@ -551,7 +537,7 @@ export function getUserOS(): {[key: string]: boolean} {
linux: false, linux: false,
}; };
const userOS = Object.keys(OS).find((os: string) => navigator.appVersion.toLowerCase().indexOf(os) !== -1); const userOS = Object.keys(OS).find((os: string) => window.navigator.appVersion.toLowerCase().indexOf(os) !== -1);
if (userOS) { if (userOS) {
OS[userOS] = true; OS[userOS] = true;
@ -566,7 +552,6 @@ export function getUserOS(): {[key: string]: boolean} {
* Capitalizes first letter of the string * Capitalizes first letter of the string
* *
* @param {string} text - text to capitalize * @param {string} text - text to capitalize
*
* @returns {string} * @returns {string}
*/ */
export function capitalize(text: string): string { export function capitalize(text: string): string {
@ -610,7 +595,6 @@ export function deepMerge<T extends object>(target, ...sources): T {
* To detect touch devices more carefully, use 'touchstart' event listener * To detect touch devices more carefully, use 'touchstart' event listener
* *
* @see http://www.stucox.com/blog/you-cant-detect-a-touchscreen/ * @see http://www.stucox.com/blog/you-cant-detect-a-touchscreen/
*
* @returns {boolean} * @returns {boolean}
*/ */
export const isTouchSupported: boolean = 'ontouchstart' in document.documentElement; export const isTouchSupported: boolean = 'ontouchstart' in document.documentElement;
@ -674,7 +658,9 @@ export function getValidUrl(url: string): string {
* @returns {string} * @returns {string}
*/ */
export function generateBlockId(): string { export function generateBlockId(): string {
return nanoid(10); const idLen = 10;
return nanoid(idLen);
} }
/** /**
@ -690,11 +676,10 @@ export function openTab(url: string): void {
* Returns random generated identifier * Returns random generated identifier
* *
* @param {string} prefix - identifier prefix * @param {string} prefix - identifier prefix
*
* @returns {string} * @returns {string}
*/ */
export function generateId(prefix = ''): string { export function generateId(prefix = ''): string {
// tslint:disable-next-line:no-bitwise // eslint-disable-next-line @typescript-eslint/no-magic-numbers
return `${prefix}${(Math.floor(Math.random() * 1e8)).toString(16)}`; return `${prefix}${(Math.floor(Math.random() * 1e8)).toString(16)}`;
} }
@ -761,13 +746,18 @@ export function cacheable<Target, Value, Arguments extends unknown[] = unknown[]
} }
return descriptor; return descriptor;
}; }
/**
* All screens below this width will be treated as mobile;
*/
export const mobileScreenBreakpoint = 650;
/** /**
* True if screen has mobile size * True if screen has mobile size
*/ */
export function isMobileScreen(): boolean { export function isMobileScreen(): boolean {
return window.matchMedia('(max-width: 650px)').matches; return window.matchMedia(`(max-width: ${mobileScreenBreakpoint}px)`).matches;
} }
/** /**

View file

@ -7,9 +7,7 @@ import { isEmpty } from '../utils';
* - {Function} on - appends subscriber to the event. If event doesn't exist - creates new one * - {Function} on - appends subscriber to the event. If event doesn't exist - creates new one
* - {Function} emit - fires all subscribers with data * - {Function} emit - fires all subscribers with data
* - {Function off - unsubscribes callback * - {Function off - unsubscribes callback
*
* @version 1.0.0 * @version 1.0.0
*
* @typedef {Events} Events * @typedef {Events} Events
* @property {object} subscribers - all subscribers grouped by event name * @property {object} subscribers - all subscribers grouped by event name
*/ */

View file

@ -62,8 +62,6 @@ export default class Listeners {
* @param {string} eventType - event type * @param {string} eventType - event type
* @param {Function} handler - method that will be fired on event * @param {Function} handler - method that will be fired on event
* @param {boolean|AddEventListenerOptions} options - useCapture or {capture, passive, once} * @param {boolean|AddEventListenerOptions} options - useCapture or {capture, passive, once}
*
* @returns {string}
*/ */
public on( public on(
element: EventTarget, element: EventTarget,
@ -104,6 +102,7 @@ export default class Listeners {
element: EventTarget, element: EventTarget,
eventType: string, eventType: string,
handler?: (event: Event) => void, handler?: (event: Event) => void,
// eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars
options?: boolean | AddEventListenerOptions options?: boolean | AddEventListenerOptions
): void { ): void {
const existingListeners = this.findAll(element, eventType, handler); const existingListeners = this.findAll(element, eventType, handler);
@ -140,7 +139,6 @@ export default class Listeners {
* @param {EventTarget} element - event target * @param {EventTarget} element - event target
* @param {string} [eventType] - event type * @param {string} [eventType] - event type
* @param {Function} [handler] - event handler * @param {Function} [handler] - event handler
*
* @returns {ListenerData|null} * @returns {ListenerData|null}
*/ */
public findOne(element: EventTarget, eventType?: string, handler?: (event: Event) => void): ListenerData { public findOne(element: EventTarget, eventType?: string, handler?: (event: Event) => void): ListenerData {
@ -155,7 +153,6 @@ export default class Listeners {
* @param {EventTarget} element - event target * @param {EventTarget} element - event target
* @param {string} eventType - event type * @param {string} eventType - event type
* @param {Function} handler - event handler * @param {Function} handler - event handler
*
* @returns {ListenerData[]} * @returns {ListenerData[]}
*/ */
public findAll(element: EventTarget, eventType?: string, handler?: (event: Event) => void): ListenerData[] { public findAll(element: EventTarget, eventType?: string, handler?: (event: Event) => void): ListenerData[] {
@ -195,7 +192,6 @@ export default class Listeners {
* Search method: looks for listener by passed element * Search method: looks for listener by passed element
* *
* @param {EventTarget} element - searching element * @param {EventTarget} element - searching element
*
* @returns {Array} listeners that found on element * @returns {Array} listeners that found on element
*/ */
private findByEventTarget(element: EventTarget): ListenerData[] { private findByEventTarget(element: EventTarget): ListenerData[] {
@ -210,7 +206,6 @@ export default class Listeners {
* Search method: looks for listener by passed event type * Search method: looks for listener by passed event type
* *
* @param {string} eventType - event type * @param {string} eventType - event type
*
* @returns {ListenerData[]} listeners that found on element * @returns {ListenerData[]} listeners that found on element
*/ */
private findByType(eventType: string): ListenerData[] { private findByType(eventType: string): ListenerData[] {
@ -225,7 +220,6 @@ export default class Listeners {
* Search method: looks for listener by passed handler * Search method: looks for listener by passed handler
* *
* @param {Function} handler - event handler * @param {Function} handler - event handler
*
* @returns {ListenerData[]} listeners that found on element * @returns {ListenerData[]} listeners that found on element
*/ */
private findByHandler(handler: (event: Event) => void): ListenerData[] { private findByHandler(handler: (event: Event) => void): ListenerData[] {
@ -240,7 +234,6 @@ export default class Listeners {
* Returns listener data found by id * Returns listener data found by id
* *
* @param {string} id - listener identifier * @param {string} id - listener identifier
*
* @returns {ListenerData} * @returns {ListenerData}
*/ */
private findById(id: string): ListenerData { private findById(id: string): ListenerData {

View file

@ -61,12 +61,12 @@ export default class Popover extends EventsDispatcher<PopoverEvent> {
nothingFound: HTMLElement; nothingFound: HTMLElement;
overlay: HTMLElement; overlay: HTMLElement;
} = { } = {
wrapper: null, wrapper: null,
popover: null, popover: null,
items: null, items: null,
nothingFound: null, nothingFound: null,
overlay: null, overlay: null,
} };
/** /**
* Additional wrapper's class name * Additional wrapper's class name
@ -150,7 +150,7 @@ export default class Popover extends EventsDispatcher<PopoverEvent> {
/** /**
* ScrollLocker instance * ScrollLocker instance
*/ */
private scrollLocker = new ScrollLocker() private scrollLocker = new ScrollLocker();
/** /**
* Editor container element * Editor container element
@ -236,6 +236,7 @@ export default class Popover extends EventsDispatcher<PopoverEvent> {
if (this.searchable) { if (this.searchable) {
setTimeout(() => { setTimeout(() => {
this.search.focus(); this.search.focus();
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
}, 100); }, 100);
} }
@ -601,7 +602,7 @@ export default class Popover extends EventsDispatcher<PopoverEvent> {
} }
el.classList.remove(Popover.CSS.itemNoHover); el.classList.remove(Popover.CSS.itemNoHover);
} };
/** /**
* Removes class responsible for special focus behavior on an item * Removes class responsible for special focus behavior on an item
@ -621,7 +622,7 @@ export default class Popover extends EventsDispatcher<PopoverEvent> {
*/ */
private onFlip = (): void => { private onFlip = (): void => {
this.disableSpecialHoverAndFocusBehavior(); this.disableSpecialHoverAndFocusBehavior();
} };
/** /**
* Reactivates flipper instance. * Reactivates flipper instance.

View file

@ -5,7 +5,6 @@
* Clears HTML from taint tags * Clears HTML from taint tags
* *
* @version 2.0.0 * @version 2.0.0
*
* @example * @example
* *
* clean(yourTaintString, yourConfig); * clean(yourTaintString, yourConfig);
@ -18,7 +17,6 @@ import * as _ from '../utils';
/** /**
* @typedef {object} SanitizerConfig * @typedef {object} SanitizerConfig
* @property {object} tags - define tags restrictions * @property {object} tags - define tags restrictions
*
* @example * @example
* *
* tags : { * tags : {
@ -65,7 +63,6 @@ export function sanitizeBlocks(
* *
* @param {string} taintString - taint string * @param {string} taintString - taint string
* @param {SanitizerConfig} customConfig - allowed tags * @param {SanitizerConfig} customConfig - allowed tags
*
* @returns {string} clean HTML * @returns {string} clean HTML
*/ */
export function clean(taintString: string, customConfig: SanitizerConfig = {} as SanitizerConfig): string { export function clean(taintString: string, customConfig: SanitizerConfig = {} as SanitizerConfig): string {
@ -163,7 +160,6 @@ function cleanObject(object: object, rules: SanitizerConfig|{[field: string]: Sa
* *
* @param {string} taintString - string to clean * @param {string} taintString - string to clean
* @param {SanitizerConfig|boolean} rule - sanitizer rule * @param {SanitizerConfig|boolean} rule - sanitizer rule
*
* @returns {string} * @returns {string}
*/ */
function cleanOneItem(taintString: string, rule: SanitizerConfig|boolean): string { function cleanOneItem(taintString: string, rule: SanitizerConfig|boolean): string {

View file

@ -10,12 +10,12 @@ export default class ScrollLocker {
private static CSS = { private static CSS = {
scrollLocked: 'ce-scroll-locked', scrollLocked: 'ce-scroll-locked',
scrollLockedHard: 'ce-scroll-locked--hard', scrollLockedHard: 'ce-scroll-locked--hard',
} };
/** /**
* Stores scroll position, used for hard scroll lock * Stores scroll position, used for hard scroll lock
*/ */
private scrollPosition: null|number private scrollPosition: null|number;
/** /**
* Locks body element scroll * Locks body element scroll

View file

@ -114,6 +114,7 @@ export default class SearchInput {
this.wrapper = Dom.make('div', SearchInput.CSS.wrapper); this.wrapper = Dom.make('div', SearchInput.CSS.wrapper);
const iconWrapper = Dom.make('div', SearchInput.CSS.icon); const iconWrapper = Dom.make('div', SearchInput.CSS.icon);
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
const icon = Dom.svg('search', 16, 16); const icon = Dom.svg('search', 16, 16);
this.input = Dom.make('input', SearchInput.CSS.input, { this.input = Dom.make('input', SearchInput.CSS.input, {

View file

@ -94,7 +94,6 @@ class Shortcuts {
* *
* @param element - Element shorcut is set for * @param element - Element shorcut is set for
* @param shortcut - shortcut name * @param shortcut - shortcut name
*
* @returns {number} index - shortcut index if exist * @returns {number} index - shortcut index if exist
*/ */
private findShortcut(element: Element, shortcut: string): Shortcut | void { private findShortcut(element: Element, shortcut: string): Shortcut | void {

View file

@ -92,6 +92,7 @@ export default class Stub implements BlockTool {
*/ */
private make(): HTMLElement { private make(): HTMLElement {
const wrapper = $.make('div', this.CSS.wrapper); const wrapper = $.make('div', this.CSS.wrapper);
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
const icon = $.svg('sad-face', 52, 52); const icon = $.svg('sad-face', 52, 52);
const infoContainer = $.make('div', this.CSS.info); const infoContainer = $.make('div', this.CSS.info);
const title = $.make('div', this.CSS.title, { const title = $.make('div', this.CSS.title, {

View file

@ -1,4 +1,5 @@
import { BlockMutationType } from '../../../../types/events/block/mutation-type'; import { BlockMutationType } from '../../../../types/events/block/mutation-type';
import EditorJS from '../../../../types';
/** /**
* There will be described test cases of BlockAPI * There will be described test cases of BlockAPI
@ -22,18 +23,22 @@ describe('BlockAPI', () => {
*/ */
const EditorJSApiMock = Cypress.sinon.match.any; const EditorJSApiMock = Cypress.sinon.match.any;
beforeEach(() => { beforeEach(function () {
if (this && this.editorInstance) { const config = {
data: editorDataMock,
onChange: (): void => {
console.log('something changed');
},
};
cy.createEditor(config).as('editorInstance');
cy.spy(config, 'onChange').as('onChange');
});
afterEach(function () {
if (this.editorInstance) {
this.editorInstance.destroy(); this.editorInstance.destroy();
} else {
const config = {
data: editorDataMock,
onChange: (): void => { console.log('something changed'); },
};
cy.createEditor(config).as('editorInstance');
cy.spy(config, 'onChange').as('onChange');
} }
}); });
@ -45,8 +50,8 @@ describe('BlockAPI', () => {
* Check that blocks.dispatchChange() triggers Editor 'onChange' callback * Check that blocks.dispatchChange() triggers Editor 'onChange' callback
*/ */
it('should trigger onChange with corresponded block', () => { it('should trigger onChange with corresponded block', () => {
cy.get('@editorInstance').then(async (editor: any) => { cy.get('@editorInstance').then(async (editor: unknown) => {
const block = editor.blocks.getById(firstBlock.id); const block = (editor as EditorJS).blocks.getById(firstBlock.id);
block.dispatchChange(); block.dispatchChange();
@ -59,5 +64,4 @@ describe('BlockAPI', () => {
}); });
}); });
}); });
}); });

View file

@ -16,13 +16,15 @@ describe('api.blocks', () => {
], ],
}; };
beforeEach(() => { beforeEach(function () {
if (this && this.editorInstance) { cy.createEditor({
data: editorDataMock,
}).as('editorInstance');
});
afterEach(function () {
if (this.editorInstance) {
this.editorInstance.destroy(); this.editorInstance.destroy();
} else {
cy.createEditor({
data: editorDataMock,
}).as('editorInstance');
} }
}); });

View file

@ -1,5 +1,6 @@
import { ToolboxConfig, BlockToolData, ToolboxConfigEntry, PasteConfig } from '../../../../types'; import { ToolboxConfig, BlockToolData, ToolboxConfigEntry, PasteConfig } from '../../../../types';
import { HTMLPasteEvent, PasteEvent, TunesMenuConfig } from '../../../../types/tools'; import EditorJS from '../../../../types';
import { HTMLPasteEvent, TunesMenuConfig } from '../../../../types/tools';
/* eslint-disable @typescript-eslint/no-empty-function */ /* eslint-disable @typescript-eslint/no-empty-function */
@ -97,22 +98,22 @@ describe('Editor Tools Api', () => {
.should('contain.text', TestTool.toolbox[1].title); .should('contain.text', TestTool.toolbox[1].title);
}); });
it('should insert block with overriden data on entry click in case toolbox entry provides data overrides', () => { it('should insert block with overridden data on entry click in case toolbox entry provides data overrides', () => {
const text = 'Text'; const text = 'Text';
const dataOverrides = { const dataOverrides = {
testProp: 'new value', testProp: 'new value',
}; };
/** /**
* Tool with default data to be overriden * Tool with default data to be overridden
*/ */
class TestTool { class TestTool {
private _data = { private _data = {
testProp: 'default value', testProp: 'default value',
} };
/** /**
* Tool contructor * Tool constructor
* *
* @param data - previously saved data * @param data - previously saved data
*/ */
@ -121,7 +122,7 @@ describe('Editor Tools Api', () => {
} }
/** /**
* Returns toolbox config as list of entries with overriden data * Returns toolbox config as list of entries with overridden data
*/ */
public static get toolbox(): ToolboxConfig { public static get toolbox(): ToolboxConfig {
return [ return [
@ -182,8 +183,8 @@ describe('Editor Tools Api', () => {
.type(text); .type(text);
cy.get('@editorInstance') cy.get('@editorInstance')
.then(async (editor: any) => { .then(async (editor: unknown) => {
const editorData = await editor.save(); const editorData = await (editor as EditorJS).save();
expect(editorData.blocks[0].data).to.be.deep.eq({ expect(editorData.blocks[0].data).to.be.deep.eq({
...dataOverrides, ...dataOverrides,
@ -535,6 +536,7 @@ describe('Editor Tools Api', () => {
.get('div.ce-block') .get('div.ce-block')
.click() .click()
.paste({ .paste({
// eslint-disable-next-line @typescript-eslint/naming-convention
'text/html': '<img>', 'text/html': '<img>',
}) })
.then(() => { .then(() => {
@ -591,6 +593,7 @@ describe('Editor Tools Api', () => {
.get('div.ce-block') .get('div.ce-block')
.click() .click()
.paste({ .paste({
// eslint-disable-next-line @typescript-eslint/naming-convention
'text/html': '<img src="foo" onerror="alert(123)"/>', // all attributes should be sanitized 'text/html': '<img src="foo" onerror="alert(123)"/>', // all attributes should be sanitized
}) })
.then(() => { .then(() => {
@ -661,6 +664,7 @@ describe('Editor Tools Api', () => {
.get('div.ce-block') .get('div.ce-block')
.click() .click()
.paste({ .paste({
// eslint-disable-next-line @typescript-eslint/naming-convention
'text/html': '<img src="foo" onerror="alert(123)"/>', 'text/html': '<img src="foo" onerror="alert(123)"/>',
}) })
.then(() => { .then(() => {
@ -738,6 +742,7 @@ describe('Editor Tools Api', () => {
.get('div.ce-block') .get('div.ce-block')
.click() .click()
.paste({ .paste({
// eslint-disable-next-line @typescript-eslint/naming-convention
'text/html': '<video width="100"><source src="movie.mp4" type="video/mp4"></video>', 'text/html': '<video width="100"><source src="movie.mp4" type="video/mp4"></video>',
}) })
.then(() => { .then(() => {
@ -821,6 +826,7 @@ describe('Editor Tools Api', () => {
.get('div.ce-block') .get('div.ce-block')
.click() .click()
.paste({ .paste({
// eslint-disable-next-line @typescript-eslint/naming-convention
'text/html': '<video width="100"><source src="movie.mp4" type="video/mp4"></video>', 'text/html': '<video width="100"><source src="movie.mp4" type="video/mp4"></video>',
}) })
.then(() => { .then(() => {
@ -896,6 +902,7 @@ describe('Editor Tools Api', () => {
.get('div.ce-block') .get('div.ce-block')
.click() .click()
.paste({ .paste({
// eslint-disable-next-line @typescript-eslint/naming-convention
'text/html': '<table><tr height="50"><td width="300">Ho-Ho-Ho</td></tr></table>', 'text/html': '<table><tr height="50"><td width="300">Ho-Ho-Ho</td></tr></table>',
}) })
.then(() => { .then(() => {

View file

@ -3,15 +3,17 @@ import Header from '@editorjs/header';
import { nanoid } from 'nanoid'; import { nanoid } from 'nanoid';
describe.only('Block ids', () => { describe.only('Block ids', () => {
beforeEach(() => { beforeEach(function () {
if (this && this.editorInstance) { cy.createEditor({
tools: {
header: Header,
},
}).as('editorInstance');
});
afterEach(function () {
if (this.editorInstance) {
this.editorInstance.destroy(); this.editorInstance.destroy();
} else {
cy.createEditor({
tools: {
header: Header,
},
}).as('editorInstance');
} }
}); });

View file

@ -2,48 +2,53 @@ import Header from '@editorjs/header';
import Image from '@editorjs/simple-image'; import Image from '@editorjs/simple-image';
import * as _ from '../../../src/components/utils'; import * as _ from '../../../src/components/utils';
describe('Copy pasting from Editor', () => { describe('Copy pasting from Editor', function () {
beforeEach(() => { beforeEach(function () {
if (this && this.editorInstance) { cy.createEditor({
tools: {
header: Header,
image: Image,
},
}).as('editorInstance');
});
afterEach(function () {
if (this.editorInstance) {
this.editorInstance.destroy(); this.editorInstance.destroy();
} else {
cy.createEditor({
tools: {
header: Header,
image: Image,
},
}).as('editorInstance');
} }
}); });
context('pasting', () => { context('pasting', function () {
it('should paste plain text', () => { it('should paste plain text', function () {
// eslint-disable-next-line cypress/no-unnecessary-waiting // eslint-disable-next-line cypress/no-unnecessary-waiting
cy.get('[data-cy=editorjs]') cy.get('[data-cy=editorjs]')
.get('div.ce-block') .get('div.ce-block')
.click() .click()
.paste({ .paste({
// eslint-disable-next-line @typescript-eslint/naming-convention
'text/plain': 'Some plain text', 'text/plain': 'Some plain text',
}) })
.wait(0) .wait(0)
.should('contain', 'Some plain text'); .should('contain', 'Some plain text');
}); });
it('should paste inline html data', () => { it('should paste inline html data', function () {
cy.get('[data-cy=editorjs]') cy.get('[data-cy=editorjs]')
.get('div.ce-block') .get('div.ce-block')
.click() .click()
.paste({ .paste({
// eslint-disable-next-line @typescript-eslint/naming-convention
'text/html': '<p><b>Some text</b></p>', 'text/html': '<p><b>Some text</b></p>',
}) })
.should('contain.html', '<b>Some text</b>'); .should('contain.html', '<b>Some text</b>');
}); });
it('should paste several blocks if plain text contains new lines', () => { it('should paste several blocks if plain text contains new lines', function () {
cy.get('[data-cy=editorjs]') cy.get('[data-cy=editorjs]')
.get('div.ce-block') .get('div.ce-block')
.click() .click()
.paste({ .paste({
// eslint-disable-next-line @typescript-eslint/naming-convention
'text/plain': 'First block\n\nSecond block', 'text/plain': 'First block\n\nSecond block',
}); });
@ -55,11 +60,12 @@ describe('Copy pasting from Editor', () => {
}); });
}); });
it('should paste several blocks if html contains several paragraphs', () => { it('should paste several blocks if html contains several paragraphs', function () {
cy.get('[data-cy=editorjs]') cy.get('[data-cy=editorjs]')
.get('div.ce-block') .get('div.ce-block')
.click() .click()
.paste({ .paste({
// eslint-disable-next-line @typescript-eslint/naming-convention
'text/html': '<p>First block</p><p>Second block</p>', 'text/html': '<p>First block</p><p>Second block</p>',
}); });
@ -71,11 +77,12 @@ describe('Copy pasting from Editor', () => {
}); });
}); });
it('should paste using custom data type', () => { it('should paste using custom data type', function () {
cy.get('[data-cy=editorjs]') cy.get('[data-cy=editorjs]')
.get('div.ce-block') .get('div.ce-block')
.click() .click()
.paste({ .paste({
// eslint-disable-next-line @typescript-eslint/naming-convention
'application/x-editor-js': JSON.stringify([ 'application/x-editor-js': JSON.stringify([
{ {
tool: 'paragraph', tool: 'paragraph',
@ -100,11 +107,12 @@ describe('Copy pasting from Editor', () => {
}); });
}); });
it('should parse block tags', () => { it('should parse block tags', function () {
cy.get('[data-cy=editorjs]') cy.get('[data-cy=editorjs]')
.get('div.ce-block') .get('div.ce-block')
.click() .click()
.paste({ .paste({
// eslint-disable-next-line @typescript-eslint/naming-convention
'text/html': '<h2>First block</h2><p>Second block</p>', 'text/html': '<h2>First block</h2><p>Second block</p>',
}); });
@ -117,11 +125,12 @@ describe('Copy pasting from Editor', () => {
.should('contain', 'Second block'); .should('contain', 'Second block');
}); });
it('should parse pattern', () => { it('should parse pattern', function () {
cy.get('[data-cy=editorjs]') cy.get('[data-cy=editorjs]')
.get('div.ce-block') .get('div.ce-block')
.click() .click()
.paste({ .paste({
// eslint-disable-next-line @typescript-eslint/naming-convention
'text/plain': 'https://codex.so/public/app/img/external/codex2x.png', 'text/plain': 'https://codex.so/public/app/img/external/codex2x.png',
}); });
@ -132,8 +141,8 @@ describe('Copy pasting from Editor', () => {
}); });
}); });
context('copying', () => { context('copying', function () {
it('should copy inline fragment', () => { it('should copy inline fragment', function () {
cy.get('[data-cy=editorjs]') cy.get('[data-cy=editorjs]')
.get('div.ce-block') .get('div.ce-block')
.click() .click()
@ -147,7 +156,7 @@ describe('Copy pasting from Editor', () => {
}); });
}); });
it('should copy several blocks', () => { it('should copy several blocks', function () {
cy.get('[data-cy=editorjs]') cy.get('[data-cy=editorjs]')
.get('div.ce-block') .get('div.ce-block')
.click() .click()
@ -171,7 +180,7 @@ describe('Copy pasting from Editor', () => {
* Need to wait for custom data as it is set asynchronously * Need to wait for custom data as it is set asynchronously
*/ */
// eslint-disable-next-line cypress/no-unnecessary-waiting // eslint-disable-next-line cypress/no-unnecessary-waiting
cy.wait(0).then(() => { cy.wait(0).then(function () {
expect(clipboardData['application/x-editor-js']).not.to.be.undefined; expect(clipboardData['application/x-editor-js']).not.to.be.undefined;
const data = JSON.parse(clipboardData['application/x-editor-js']); const data = JSON.parse(clipboardData['application/x-editor-js']);
@ -185,8 +194,8 @@ describe('Copy pasting from Editor', () => {
}); });
}); });
context('cutting', () => { context('cutting', function () {
it('should cut inline fragment', () => { it('should cut inline fragment', function () {
cy.get('[data-cy=editorjs]') cy.get('[data-cy=editorjs]')
.get('div.ce-block') .get('div.ce-block')
.click() .click()
@ -200,7 +209,7 @@ describe('Copy pasting from Editor', () => {
}); });
}); });
it('should cut several blocks', () => { it('should cut several blocks', function () {
cy.get('[data-cy=editorjs]') cy.get('[data-cy=editorjs]')
.get('div.ce-block') .get('div.ce-block')
.click() .click()
@ -224,7 +233,7 @@ describe('Copy pasting from Editor', () => {
* Need to wait for custom data as it is set asynchronously * Need to wait for custom data as it is set asynchronously
*/ */
// eslint-disable-next-line cypress/no-unnecessary-waiting // eslint-disable-next-line cypress/no-unnecessary-waiting
cy.wait(0).then(() => { cy.wait(0).then(function () {
expect(clipboardData['application/x-editor-js']).not.to.be.undefined; expect(clipboardData['application/x-editor-js']).not.to.be.undefined;
const data = JSON.parse(clipboardData['application/x-editor-js']); const data = JSON.parse(clipboardData['application/x-editor-js']);
@ -241,7 +250,7 @@ describe('Copy pasting from Editor', () => {
.should('not.contain', 'Second block'); .should('not.contain', 'Second block');
}); });
it('should cut lots of blocks', () => { it('should cut lots of blocks', function () {
const numberOfBlocks = 50; const numberOfBlocks = 50;
for (let i = 0; i < numberOfBlocks; i++) { for (let i = 0; i < numberOfBlocks; i++) {
@ -264,7 +273,7 @@ describe('Copy pasting from Editor', () => {
* Need to wait for custom data as it is set asynchronously * Need to wait for custom data as it is set asynchronously
*/ */
// eslint-disable-next-line cypress/no-unnecessary-waiting // eslint-disable-next-line cypress/no-unnecessary-waiting
cy.wait(0).then(() => { cy.wait(0).then(function () {
expect(clipboardData['application/x-editor-js']).not.to.be.undefined; expect(clipboardData['application/x-editor-js']).not.to.be.undefined;
const data = JSON.parse(clipboardData['application/x-editor-js']); const data = JSON.parse(clipboardData['application/x-editor-js']);

View file

@ -3,7 +3,7 @@ import { ToolboxConfig } from '../../../types';
describe('Editor i18n', () => { describe('Editor i18n', () => {
context('Toolbox', () => { context('Toolbox', () => {
it('should translate tool title in a toolbox', () => { it('should translate tool title in a toolbox', function () {
if (this && this.editorInstance) { if (this && this.editorInstance) {
this.editorInstance.destroy(); this.editorInstance.destroy();
} }
@ -35,7 +35,7 @@ describe('Editor i18n', () => {
.should('contain.text', toolNamesDictionary.Heading); .should('contain.text', toolNamesDictionary.Heading);
}); });
it('should translate titles of toolbox entries', () => { it('should translate titles of toolbox entries', function () {
if (this && this.editorInstance) { if (this && this.editorInstance) {
this.editorInstance.destroy(); this.editorInstance.destroy();
} }
@ -95,7 +95,7 @@ describe('Editor i18n', () => {
.should('contain.text', toolNamesDictionary.Title2); .should('contain.text', toolNamesDictionary.Title2);
}); });
it('should use capitalized tool name as translation key if toolbox title is missing', () => { it('should use capitalized tool name as translation key if toolbox title is missing', function () {
if (this && this.editorInstance) { if (this && this.editorInstance) {
this.editorInstance.destroy(); this.editorInstance.destroy();
} }
@ -141,4 +141,4 @@ describe('Editor i18n', () => {
.should('contain.text', toolNamesDictionary.TestTool); .should('contain.text', toolNamesDictionary.TestTool);
}); });
}); });
}); });

View file

@ -1,4 +1,4 @@
// eslint-disable-next-line spaced-comment // eslint-disable-next-line spaced-comment, @typescript-eslint/triple-slash-reference
/// <reference path="../support/index.d.ts" /> /// <reference path="../support/index.d.ts" />
describe('Editor basic initialization', () => { describe('Editor basic initialization', () => {
@ -8,11 +8,13 @@ describe('Editor basic initialization', () => {
*/ */
const editorConfig = {}; const editorConfig = {};
beforeEach(() => { beforeEach(function () {
if (this && this.editorInstance) { cy.createEditor(editorConfig).as('editorInstance');
});
afterEach(function () {
if (this.editorInstance) {
this.editorInstance.destroy(); this.editorInstance.destroy();
} else {
cy.createEditor(editorConfig).as('editorInstance');
} }
}); });

View file

@ -1,5 +1,5 @@
/* tslint:disable:max-classes-per-file */ /* tslint:disable:max-classes-per-file */
/* eslint-disable @typescript-eslint/ban-ts-ignore,@typescript-eslint/no-explicit-any,jsdoc/require-jsdoc */ /* eslint-disable @typescript-eslint/no-explicit-any, jsdoc/require-jsdoc */
import Tools from '../../../../src/components/modules/tools'; import Tools from '../../../../src/components/modules/tools';
import { EditorConfig } from '../../../../types'; import { EditorConfig } from '../../../../types';
import BlockTool from '../../../../src/components/tools/block'; import BlockTool from '../../../../src/components/tools/block';
@ -57,6 +57,7 @@ describe('Tools module', () => {
it('should throw an error if tools config is corrupted', async () => { it('should throw an error if tools config is corrupted', async () => {
const module = constructModule({ const module = constructModule({
tools: { tools: {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore // @ts-ignore
corruptedTool: 'value', corruptedTool: 'value',
}, },
@ -77,7 +78,7 @@ describe('Tools module', () => {
it('should call Tools prepare method with user config', async () => { it('should call Tools prepare method with user config', async () => {
class WithSuccessfulPrepare { class WithSuccessfulPrepare {
// eslint-disable-next-line @typescript-eslint/no-empty-function // eslint-disable-next-line @typescript-eslint/no-empty-function
public static prepare = cy.stub() public static prepare = cy.stub();
} }
const config = { const config = {
@ -134,7 +135,7 @@ describe('Tools module', () => {
}, },
blockToolWithoutSettings: class {} as any, blockToolWithoutSettings: class {} as any,
inlineTool: class { inlineTool: class {
public static isInline = true public static isInline = true;
// eslint-disable-next-line @typescript-eslint/no-empty-function // eslint-disable-next-line @typescript-eslint/no-empty-function
public render(): void {} public render(): void {}
@ -146,7 +147,7 @@ describe('Tools module', () => {
public checkState(): void {} public checkState(): void {}
} as any, } as any,
inlineTool2: class { inlineTool2: class {
public static isInline = true public static isInline = true;
// eslint-disable-next-line @typescript-eslint/no-empty-function // eslint-disable-next-line @typescript-eslint/no-empty-function
public render(): void {} public render(): void {}

View file

@ -1,6 +1,11 @@
import EditorJS, { EditorConfig } from '../../../types'; import EditorJS, { EditorConfig } from '../../../types';
describe('ReadOnly API spec', () => { describe('ReadOnly API spec', () => {
/**
* Creates the new editor instance
*
* @param config - Editor Config
*/
function createEditor(config?: EditorConfig): void { function createEditor(config?: EditorConfig): void {
const editorConfig = Object.assign({}, config || {}); const editorConfig = Object.assign({}, config || {});

View file

@ -1,10 +1,12 @@
/* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/no-explicit-any */
describe('Output sanitisation', () => { describe('Output sanitization', () => {
beforeEach(() => { beforeEach(function () {
if (this && this.editorInstance) { cy.createEditor({}).as('editorInstance');
});
afterEach(function () {
if (this.editorInstance) {
this.editorInstance.destroy(); this.editorInstance.destroy();
} else {
cy.createEditor({}).as('editorInstance');
} }
}); });
@ -52,7 +54,10 @@ describe('Output sanitisation', () => {
it('should save formatting for paragraph on paste', () => { it('should save formatting for paragraph on paste', () => {
cy.get('[data-cy=editorjs]') cy.get('[data-cy=editorjs]')
.get('div.ce-block') .get('div.ce-block')
.paste({ 'text/html': '<p>Text</p><p><b>Bold text</b></p>' }); .paste({
// eslint-disable-next-line @typescript-eslint/naming-convention
'text/html': '<p>Text</p><p><b>Bold text</b></p>',
});
cy.get('@editorInstance').then(async editorInstance => { cy.get('@editorInstance').then(async editorInstance => {
const output = await (editorInstance as any).save(); const output = await (editorInstance as any).save();

View file

@ -1,11 +1,13 @@
import * as _ from '../../../src/components/utils'; import * as _ from '../../../src/components/utils';
describe('Blocks selection', () => { describe('Blocks selection', () => {
beforeEach(() => { beforeEach(function () {
if (this && this.editorInstance) { cy.createEditor({}).as('editorInstance');
});
afterEach(function () {
if (this.editorInstance) {
this.editorInstance.destroy(); this.editorInstance.destroy();
} else {
cy.createEditor({}).as('editorInstance');
} }
}); });

View file

@ -17,7 +17,7 @@ describe('BlockTool', () => {
rule1: { rule1: {
div: true, div: true,
}, },
} };
public static toolbox = { public static toolbox = {
icon: 'Tool icon', icon: 'Tool icon',
@ -48,9 +48,7 @@ describe('BlockTool', () => {
public api: object; public api: object;
public config: ToolSettings; public config: ToolSettings;
/** // eslint-disable-next-line jsdoc/require-jsdoc
*
*/
constructor({ data, block, readOnly, api, config }) { constructor({ data, block, readOnly, api, config }) {
this.data = data; this.data = data;
this.block = block; this.block = block;
@ -151,7 +149,7 @@ describe('BlockTool', () => {
constructable: class { constructable: class {
public static sanitize = { public static sanitize = {
b: true, b: true,
} };
}, },
api: {}, api: {},
config: {}, config: {},
@ -183,7 +181,7 @@ describe('BlockTool', () => {
constructable: class { constructable: class {
public static sanitize = { public static sanitize = {
b: true, b: true,
} };
}, },
api: {}, api: {},
config: {}, config: {},
@ -194,7 +192,7 @@ describe('BlockTool', () => {
constructable: class { constructable: class {
public static sanitize = { public static sanitize = {
a: true, a: true,
} };
}, },
api: {}, api: {},
config: {}, config: {},
@ -502,7 +500,7 @@ describe('BlockTool', () => {
const tool = new BlockTool({ const tool = new BlockTool({
...options, ...options,
constructable: class { constructable: class {
public static toolbox = false public static toolbox = false;
}, },
} as any); } as any);
@ -513,7 +511,7 @@ describe('BlockTool', () => {
const tool = new BlockTool({ const tool = new BlockTool({
...options, ...options,
constructable: class { constructable: class {
public static toolbox = {} public static toolbox = {};
}, },
} as any); } as any);

View file

@ -20,9 +20,7 @@ describe('BlockTune', () => {
public data: BlockTuneData; public data: BlockTuneData;
public block: object; public block: object;
/** // eslint-disable-next-line jsdoc/require-jsdoc
*
*/
constructor({ api, config, block, data }) { constructor({ api, config, block, data }) {
this.api = api; this.api = api;
this.config = config; this.config = config;

View file

@ -13,9 +13,9 @@ describe('InlineTool', () => {
constructable: class { constructable: class {
public static sanitize = { public static sanitize = {
rule1: 'rule1', rule1: 'rule1',
} };
public static title = 'Title' public static title = 'Title';
public static reset; public static reset;
public static prepare; public static prepare;
@ -26,7 +26,9 @@ describe('InlineTool', () => {
public config: ToolSettings; public config: ToolSettings;
/** /**
* * @param options - constructor options
* @param options.api - EditorAPI
* @param options.config - tool config
*/ */
constructor({ api, config }) { constructor({ api, config }) {
this.api = api; this.api = api;

View file

@ -1,8 +1,14 @@
/* eslint-disable @typescript-eslint/no-empty-function */ /* eslint-disable @typescript-eslint/no-empty-function */
import { isFunction } from '../../../src/components/utils'; import { isFunction } from '../../../src/components/utils';
/**
* Example of typical synchronous function
*/
function syncFunction(): void {} function syncFunction(): void {}
/**
* Example of typical asynchronous function
*/
async function asyncFunction(): Promise<void> {} async function asyncFunction(): Promise<void> {}
const syncArrowFunction = (): void => {}; const syncArrowFunction = (): void => {};
@ -10,7 +16,7 @@ const syncArrowFunction = (): void => {};
const asyncArrowFunction = async (): Promise<void> => {}; const asyncArrowFunction = async (): Promise<void> => {};
describe('isFunction function', () => { describe('isFunction function', () => {
it('should recognise sync functions', () => { it('should recognize sync functions', () => {
/** /**
* Act * Act
*/ */
@ -24,7 +30,7 @@ describe('isFunction function', () => {
expect(arrowFunctionResult).to.eq(true); expect(arrowFunctionResult).to.eq(true);
}); });
it('should recognise async functions', () => { it('should recognize async functions', () => {
/** /**
* Act * Act
*/ */

View file

@ -5,7 +5,7 @@ import { PopoverItem } from '../../../../types/index.js';
*/ */
class SomePlugin { class SomePlugin {
/** /**
* Event handler to be spyed in test * Event handler to be spied in test
*/ */
// eslint-disable-next-line @typescript-eslint/no-empty-function // eslint-disable-next-line @typescript-eslint/no-empty-function
public static pluginInternalKeydownHandler(): void {} public static pluginInternalKeydownHandler(): void {}
@ -24,7 +24,7 @@ class SomePlugin {
} }
/** /**
* Used to display our tool in the Toolboz * Used to display our tool in the Toolbox
*/ */
public static get toolbox(): PopoverItem { public static get toolbox(): PopoverItem {
return { return {
@ -37,15 +37,17 @@ class SomePlugin {
} }
describe('Flipper', () => { describe('Flipper', () => {
beforeEach(() => { beforeEach(function () {
if (this && this.editorInstance) { cy.createEditor({
tools: {
sometool: SomePlugin,
},
}).as('editorInstance');
});
afterEach(function () {
if (this.editorInstance) {
this.editorInstance.destroy(); this.editorInstance.destroy();
} else {
cy.createEditor({
tools: {
sometool: SomePlugin,
},
}).as('editorInstance');
} }
}); });

1265
yarn.lock

File diff suppressed because it is too large Load diff