diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index abf876ec0..cc81b3b4f 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -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 diff --git a/package.json b/package.json index 11493b908..85dfb2833 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/src/components/modules/blockManager.ts b/src/components/modules/blockManager.ts index 31a867498..875851f41 100644 --- a/src/components/modules/blockManager.ts +++ b/src/components/modules/blockManager.ts @@ -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'; @@ -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 @@ -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; @@ -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) { @@ -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 */ - 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. @@ -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..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 + */ + if (_.isEmpty(tool.sanitizeConfig)) { + return convertStringToBlockData(clean(exportedString), tool.conversionConfig, toolConfig); + } + + const data = convertStringToBlockData(exportedString, tool.conversionConfig, toolConfig); + const [ sanitized ] = sanitizeBlocks([ { + tool: tool.name, + data, + } ], tool.sanitizeConfig); + + return sanitized.data; + } + /** * Bind Block events * diff --git a/test/cypress/tests/api/blocks.cy.ts b/test/cypress/tests/api/blocks.cy.ts index ab97b8b5c..86a1dd0a4 100644 --- a/test/cypress/tests/api/blocks.cy.ts +++ b/test/cypress/tests/api/blocks.cy.ts @@ -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'; @@ -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 bold and underlined 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 bold and underlined text'); + }); + }); + it('should throw an error if nonexisting Block id passed', function () { cy.createEditor({}) .then((editor) => { diff --git a/test/cypress/tests/modules/BlockEvents/Backspace.cy.ts b/test/cypress/tests/modules/BlockEvents/Backspace.cy.ts index bb36e6503..d48f26af4 100644 --- a/test/cypress/tests/modules/BlockEvents/Backspace.cy.ts +++ b/test/cypress/tests/modules/BlockEvents/Backspace.cy.ts @@ -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 () { @@ -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 gets into the Block + */ + text: 'bold and underlined', + }, + }, + ], + }, + }); + + 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 bold 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: { @@ -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: 'bold and underlined', + }, + }, + ], + }, + }).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 bold and underlined'); + + cy.get('@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 bold 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 diff --git a/types/configs/conversion-config.ts b/types/configs/conversion-config.ts index 0f7e27480..0dd6a87ed 100644 --- a/types/configs/conversion-config.ts +++ b/types/configs/conversion-config.ts @@ -7,6 +7,9 @@ export interface ConversionConfig { /** * How to import string to this Tool. * + * Receives the raw exported string from the source Block; resulting data is + * sanitized afterward against the target Tool's sanitizer config. + * * Can be a String or Function: * * 1. String — the key of Tool data object to fill it with imported string on render.