Browse Source

Fix: Paragraph command should check whether it can be applied to the selection. Closes #24.

Aleksander Nowodzinski 8 years ago
parent
commit
1e0440ceb2

+ 17 - 7
packages/ckeditor5-paragraph/src/paragraphcommand.js

@@ -29,14 +29,11 @@ export default class ParagraphCommand extends Command {
 	 * @inheritDoc
 	 */
 	refresh() {
-		const block = first( this.editor.document.selection.getSelectedBlocks() );
+		const document = this.editor.document;
+		const block = first( document.selection.getSelectedBlocks() );
 
 		this.value = !!block && block.is( 'paragraph' );
-
-		this.isEnabled = !!block && this.editor.document.schema.check( {
-			name: 'paragraph',
-			inside: Position.createBefore( block )
-		} );
+		this.isEnabled = !!block && checkCanBecomeParagraph( block, document.schema );
 	}
 
 	/**
@@ -58,10 +55,23 @@ export default class ParagraphCommand extends Command {
 			const blocks = ( options.selection || document.selection ).getSelectedBlocks();
 
 			for ( const block of blocks ) {
-				if ( !block.is( 'paragraph' ) ) {
+				if ( !block.is( 'paragraph' ) && checkCanBecomeParagraph( block, document.schema ) ) {
 					batch.rename( block, 'paragraph' );
 				}
 			}
 		} );
 	}
 }
+
+// Checks whether the given block can be replaced by a paragraph.
+//
+// @private
+// @param {module:engine/model/element~Element} block A block to be tested.
+// @param {module:engine/model/schema~Schema} schema The schema of the document.
+// @returns {Boolean}
+function checkCanBecomeParagraph( block, schema ) {
+	return schema.check( {
+		name: 'paragraph',
+		inside: Position.createBefore( block )
+	} );
+}

+ 25 - 0
packages/ckeditor5-paragraph/tests/paragraphcommand.js

@@ -99,6 +99,31 @@ describe( 'ParagraphCommand', () => {
 			expect( command.value ).to.be.true;
 		} );
 
+		// https://github.com/ckeditor/ckeditor5-paragraph/issues/24
+		it( 'should not rename blocks which cannot become paragraphs', () => {
+			document.schema.registerItem( 'restricted' );
+			document.schema.allow( { name: 'restricted', inside: '$root' } );
+			document.schema.disallow( { name: 'paragraph', inside: 'restricted' } );
+
+			document.schema.registerItem( 'fooBlock', '$block' );
+			document.schema.allow( { name: 'fooBlock', inside: 'restricted' } );
+
+			setData(
+				document,
+				'<heading1>a[bc</heading1>' +
+				'<restricted><fooBlock></fooBlock></restricted>' +
+				'<heading1>de]f</heading1>'
+			);
+
+			command.execute();
+
+			expect( getData( document ) ).to.equal(
+				'<paragraph>a[bc</paragraph>' +
+				'<restricted><fooBlock></fooBlock></restricted>' +
+				'<paragraph>de]f</paragraph>'
+			);
+		} );
+
 		it( 'should not rename blocks which already are pargraphs', () => {
 			const batch = editor.document.batch();