浏览代码

toWidget() should throw when attempting to create a widget out of a non-ContainerElement instance.

Aleksander Nowodzinski 5 年之前
父节点
当前提交
ea42b0dadb
共有 2 个文件被更改,包括 34 次插入0 次删除
  1. 16 0
      packages/ckeditor5-widget/src/utils.js
  2. 18 0
      packages/ckeditor5-widget/tests/utils.js

+ 16 - 0
packages/ckeditor5-widget/src/utils.js

@@ -12,6 +12,7 @@ import IconView from '@ckeditor/ckeditor5-ui/src/icon/iconview';
 import Rect from '@ckeditor/ckeditor5-utils/src/dom/rect';
 import BalloonPanelView from '@ckeditor/ckeditor5-ui/src/panel/balloon/balloonpanelview';
 import global from '@ckeditor/ckeditor5-utils/src/dom/global';
+import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
 
 import dragHandleIcon from '../theme/icons/drag-handle.svg';
 import { getTypeAroundFakeCaretPosition } from './widgettypearound/utils';
@@ -93,6 +94,21 @@ export function isWidget( node ) {
  */
 /* eslint-enable max-len */
 export function toWidget( element, writer, options = {} ) {
+	if ( !element.is( 'containerElement' ) ) {
+		/**
+		 * The element passed to `toWidget()` must be a {@link module:engine/view/containerelement~ContainerElement}
+		 * instance.
+		 *
+		 * @error widget-to-widget-wrong-element-type
+		 * @param {String} element The view element passed to `toWidget()`.
+		 */
+		throw new CKEditorError(
+			'widget-to-widget-wrong-element-type: The element passed to toWidget() must be a container element instance.',
+			null,
+			{ element }
+		);
+	}
+
 	writer.setAttribute( 'contenteditable', 'false', element );
 
 	writer.addClass( WIDGET_CLASS_NAME, element );

+ 18 - 0
packages/ckeditor5-widget/tests/utils.js

@@ -126,6 +126,24 @@ describe( 'widget utils', () => {
 			expect( icon.classList.contains( 'ck' ) ).to.be.true;
 			expect( icon.classList.contains( 'ck-icon' ) ).to.be.true;
 		} );
+
+		it( 'should throw when attempting to create a widget out of anything but ContainerElement', () => {
+			expect( () => {
+				toWidget( writer.createRawElement( 'div' ), writer );
+			}, 'raw element' ).to.throw( /^widget-to-widget-wrong-element-type/ );
+
+			expect( () => {
+				toWidget( writer.createEmptyElement( 'img' ), writer );
+			}, 'empty element' ).to.throw( /^widget-to-widget-wrong-element-type/ );
+
+			expect( () => {
+				toWidget( writer.createAttributeElement( 'a' ), writer );
+			}, 'attribute element' ).to.throw( /^widget-to-widget-wrong-element-type/ );
+
+			expect( () => {
+				toWidget( writer.createUIElement( 'span' ), writer );
+			}, 'UI element' ).to.throw( /^widget-to-widget-wrong-element-type/ );
+		} );
 	} );
 
 	describe( 'isWidget()', () => {