Skip to content
2 changes: 2 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
- `Fix` - Focus the contenteditable input when setting the caret, so autofocus works inside iframes
- `Fix` - Save failures now propagate to callers (#3030)
- `Fix` - `readOnly.toggle()` now restores editor to consistent state if save fails
- `Fix` - Inline formatting is no longer removed when a Block is converted to, or merged into, a Tool with per-field `sanitize` rules (`ConversionConfig.import` now receives the unsanitized exported string and sanitization runs on the returned data)
- `Fix` - Data of a Block merged into a Block of the same Tool is sanitized with the Tool's sanitize config

### 2.31.7

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@editorjs/editorjs",
"version": "2.32.0-rc.5",
"version": "2.32.0-rc.6",
"description": "Editor.js — open source block-style WYSIWYG editor with JSON output",
"main": "dist/editorjs.umd.js",
"module": "dist/editorjs.mjs",
Expand Down
50 changes: 36 additions & 14 deletions src/components/modules/blockManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import Module from '../__module';
import $ from '../dom';
import * as _ from '../utils';
import Blocks from '../blocks';
import type { BlockToolData, PasteEvent } from '../../../types';
import type { BlockToolData, PasteEvent, ToolConfig } from '../../../types';
import type { BlockTuneData } from '../../../types/block-tunes/block-tune-data';
import BlockAPI from '../block/api';
import type { BlockMutationEventMap, BlockMutationType } from '../../../types/events/block';
Expand All @@ -21,6 +21,7 @@ import { BlockChanged } from '../events';
import { clean, sanitizeBlocks } from '../utils/sanitizer';
import { convertStringToBlockData, isBlockConvertable } from '../utils/blocks';
import PromiseQueue from '../utils/promise-queue';
import type BlockToolAdapter from '../tools/block';

/**
* @typedef {BlockManager} BlockManager
Expand Down Expand Up @@ -501,7 +502,10 @@ export default class BlockManager extends Module {
return;
}

const [ cleanData ] = sanitizeBlocks([ blockToMergeDataRaw ], targetBlock.tool.sanitizeConfig);
const [ { data: cleanData } ] = sanitizeBlocks([ {
tool: targetBlock.name,
data: blockToMergeDataRaw,
} ], targetBlock.tool.sanitizeConfig);

blockToMergeData = cleanData;

Expand All @@ -510,9 +514,8 @@ export default class BlockManager extends Module {
*/
} else if (targetBlock.mergeable && isBlockConvertable(blockToMerge, 'export') && isBlockConvertable(targetBlock, 'import')) {
const blockToMergeDataStringified = await blockToMerge.exportDataAsString();
const cleanData = clean(blockToMergeDataStringified, targetBlock.tool.sanitizeConfig);

blockToMergeData = convertStringToBlockData(cleanData, targetBlock.tool.conversionConfig);
blockToMergeData = this.convertStringToSanitizedBlockData(blockToMergeDataStringified, targetBlock.tool, targetBlock.tool.settings);
}

if (blockToMergeData === undefined) {
Expand Down Expand Up @@ -861,17 +864,9 @@ export default class BlockManager extends Module {
const exportedData = await blockToConvert.exportDataAsString();

/**
* Clean exported data with replacing sanitizer config
* Convert the exported string to the replacing Tool's data and sanitize it
*/
Comment on lines 866 to 868

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Simpler wording:

Suggested change
/**
* Clean exported data with replacing sanitizer config
* Now using Conversion Config "import" we compose a new Block data, cleaned with the replacing Tool's sanitizer config
*/
/**
* Convert the exported string to the replacing Tool's data and sanitize it
*/

const cleanData: string = clean(
exportedData,
replacingTool.sanitizeConfig
);

/**
* Now using Conversion Config "import" we compose a new Block data
*/
let newBlockData = convertStringToBlockData(cleanData, replacingTool.conversionConfig, replacingTool.settings);
let newBlockData = this.convertStringToSanitizedBlockData(exportedData, replacingTool, replacingTool.settings);

/**
* Optional data overrides.
Expand Down Expand Up @@ -935,6 +930,33 @@ export default class BlockManager extends Module {
}));
}

/**
* Converts a string exported from another Block to the passed Tool's data
* and sanitizes this data with the Tool's sanitizer config, the same way as on saving
*
* @param exportedString - string got from another Block via its Conversion Config "export"
* @param tool - Tool to convert the string to
* @param toolConfig - Tool's user config (`tools.<name>.config`), passed as the 2nd argument to the Conversion Config "import" function
*/
private convertStringToSanitizedBlockData(exportedString: string, tool: BlockToolAdapter, toolConfig?: ToolConfig): BlockToolData {
/**
* The Tool has no sanitizer rules (no own `sanitize` and no Inline Tools or Tunes with rules).
* sanitizeBlocks() leaves data untouched in this case, but the converted string must not bring
* any markup to such a Tool, so strip all tags before importing
*/
Comment on lines +942 to +946

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This case is hard to follow, let's spell it out:

Suggested change
/**
* A Tool without any sanitizer rules allows no tags. sanitizeBlocks() skips an empty config, so clean the string itself
*/
/**
* The Tool has no sanitizer rules (no own `sanitize` and no Inline Tools or Tunes with rules).
* sanitizeBlocks() leaves data untouched in this case, but the converted string must not bring
* any markup to such a Tool, so strip all tags before importing
*/

if (_.isEmpty(tool.sanitizeConfig)) {
return convertStringToBlockData(clean(exportedString), tool.conversionConfig, toolConfig);
}

const data = convertStringToBlockData(exportedString, tool.conversionConfig, toolConfig);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that the Conversion Config import function now receives the raw, unsanitized string (before, it got an already cleaned one), and sanitization happens on the resulting data. This is a contract change for third-party Tools. Please either document it (CHANGELOG + JSDoc of ConversionConfig.import), or, for a string import, pre-clean the string with that field's rule before importing.

const [ sanitized ] = sanitizeBlocks([ {
tool: tool.name,
data,
} ], tool.sanitizeConfig);

return sanitized.data;
}

/**
* Bind Block events
*
Expand Down
60 changes: 59 additions & 1 deletion test/cypress/tests/api/blocks.cy.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type EditorJS from '../../../../types/index';
import type { ConversionConfig, ToolboxConfig, ToolConfig } from '../../../../types';
import type { ConversionConfig, SanitizerConfig, ToolboxConfig, ToolConfig } from '../../../../types';
import ToolMock, { type MockToolData } from '../../fixtures/tools/ToolMock';
import { nanoid } from 'nanoid';

Expand Down Expand Up @@ -361,6 +361,64 @@ describe('api.blocks', () => {
});
});

it('should keep inline formatting allowed by the target Tool sanitize config for the imported field', function () {
/**
* Mock of Tool whose sanitize config describes its data fields
*/
class ConvertableTool extends ToolMock {
/**
* Specify how to import string data to this Tool
*/
public static get conversionConfig(): ConversionConfig {
return {
import: 'text',
};
}

/**
* Rules for the "text" field: only bold is allowed
*/
public static get sanitize(): SanitizerConfig {
return {
text: {
b: true,
},
};
}
}

const existingBlock = {
id: 'test-id-123',
type: 'paragraph',
data: {
text: 'Some <b>bold</b> and <u>underlined</u> text',
},
};

cy.createEditor({
tools: {
convertableTool: {
class: ConvertableTool,
inlineToolbar: false,
},
},
data: {
blocks: [
existingBlock,
],
},
}).then(async (editor) => {
await editor.blocks.convert(existingBlock.id, 'convertableTool');

/**
* Check the rendered Block: saving sanitizes the data once more and would hide the data passed to the Tool
*/
cy.get('[data-cy=editorjs]')
.find('.ce-block__content [contenteditable]')
.should('have.html', 'Some <b>bold</b> and underlined text');
});
});

it('should throw an error if nonexisting Block id passed', function () {
cy.createEditor({})
.then((editor) => {
Expand Down
189 changes: 188 additions & 1 deletion test/cypress/tests/modules/BlockEvents/Backspace.cy.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type EditorJS from '../../../../../types/index';
import { SimpleHeader } from '../../../fixtures/tools/SimpleHeader';
import type { ConversionConfig } from '../../../../../types/index';
import type { ConversionConfig, SanitizerConfig } from '../../../../../types/index';
import ToolMock, { type MockToolData } from '../../../fixtures/tools/ToolMock';
import { createEditorWithTextBlocks } from '../../../support/utils/createEditorWithTextBlocks';

describe('Backspace keydown', function () {
Expand Down Expand Up @@ -414,6 +415,94 @@ describe('Backspace keydown', function () {
.should('not.have.class', 'ce-toolbar--opened');
});

it('should sanitize merged data with the Tool sanitize config when merging blocks of the same tool', function () {
/**
* Mock of Tool whose sanitize config describes its data fields and supports merging
*/
class MergeableSanitizeTool extends ToolMock {
/**
* Rendered block element
*/
private element: HTMLElement | undefined;

/**
* Rules for the "text" field: only bold is allowed
*/
public static get sanitize(): SanitizerConfig {
return {
text: {
b: true,
},
};
}

/**
* Render element and keep a reference for merge()
*/
public render(): HTMLElement {
this.element = super.render();

return this.element;
}

/**
* Append merged data to the block element
*
* @param data - sanitized data of the Block being merged
*/
public merge(data: MockToolData): void {
if (this.element) {
this.element.innerHTML += data.text;
}
}
}

cy.createEditor({
tools: {
mergeableTool: {
class: MergeableSanitizeTool,
inlineToolbar: false,
},
},
data: {
blocks: [
{
id: 'block1',
type: 'mergeableTool',
data: {
text: 'Start ',
},
},
{
id: 'block2',
type: 'mergeableTool',
data: {
/**
* Initial data is rendered as is, so the disallowed <u> gets into the Block
*/
text: '<b>bold</b> and <u>underlined</u>',
},
},
],
},
});

cy.get('[data-cy=editorjs]')
.find('[data-cy="block-wrapper"][data-id="block2"] [contenteditable]')
.click()
.type('{home}')
.type('{backspace}');

/**
* Check the rendered Block: saving sanitizes the data once more and would hide the data passed to merge()
*/
cy.get('[data-cy=editorjs]')
.find('[data-cy="block-wrapper"]')
.should('have.length', 1)
.find('[contenteditable]')
.should('have.html', 'Start <b>bold</b> and underlined');
});

it('should merge blocks of different types (Paragraph -> Header) if they have a valid conversion config. Also, should close the Toolbox. Caret should be places in a place of glue', function () {
cy.createEditor({
tools: {
Expand Down Expand Up @@ -545,6 +634,104 @@ describe('Backspace keydown', function () {
.should('not.have.class', 'ce-toolbar--opened');
});

it('should keep inline formatting allowed by per-field sanitize when merging blocks of different tools', function () {
/**
* Mock of Tool whose sanitize config describes its data fields and supports merging
*/
class MergeableSanitizeTool extends ToolMock {
/**
* Rendered block element
*/
private element: HTMLElement | undefined;

/**
* Specify how to import string data to this Tool
*/
public static get conversionConfig(): ConversionConfig {
return {
import: 'text',
};
}

/**
* Rules for the "text" field: only bold is allowed
*/
public static get sanitize(): SanitizerConfig {
return {
text: {
b: true,
},
};
}

/**
* Render element and keep a reference for merge()
*/
public render(): HTMLElement {
this.element = super.render();

return this.element;
}

/**
* Append merged data to the block element
*
* @param data - imported and sanitized block data
*/
public merge(data: MockToolData): void {
if (this.element) {
this.element.innerHTML += data.text;
}
}
}

cy.createEditor({
tools: {
mergeableTool: {
class: MergeableSanitizeTool,
inlineToolbar: false,
},
},
data: {
blocks: [
{
id: 'block1',
type: 'mergeableTool',
data: {
text: 'Start ',
},
},
{
id: 'block2',
type: 'paragraph',
data: {
text: '<b>bold</b> and <u>underlined</u>',
},
},
],
},
}).as('editorInstance');

cy.get('[data-cy=editorjs]')
.find('[data-cy="block-wrapper"][data-id="block2"] .ce-paragraph')
.click()
.type('{home}')
.type('{backspace}');

cy.get('[data-cy=editorjs]')
.find('.ce-block__content [contenteditable]')
.should('have.html', 'Start <b>bold</b> and underlined');

cy.get<EditorJS>('@editorInstance')
.then(async (editor) => {
const { blocks } = await editor.save();

expect(blocks.length).to.eq(1);
expect(blocks[0].id).to.eq('block1');
expect(blocks[0].data.text).to.eq('Start <b>bold</b> and underlined');
});
});

it('should simply set Caret to the end of the previous Block if Caret at the start of the Block but Blocks are not mergeable (target Bock is lack of merge() and conversionConfig). Also, should close the Toolbox.', function () {
/**
* Mock of tool without merge() method
Expand Down
Loading
Loading