2 * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
3 * For licensing, see LICENSE.md or http://ckeditor.com/license
7 * @fileOverview [Widget](http://ckeditor.com/addon/widget) plugin.
13 var DRAG_HANDLER_SIZE
= 15;
15 CKEDITOR
.plugins
.add( 'widget', {
16 // jscs:disable maximumLineLength
17 lang: 'af,ar,bg,ca,cs,cy,da,de,de-ch,el,en,en-gb,eo,es,eu,fa,fi,fr,gl,he,hr,hu,id,it,ja,km,ko,ku,lv,nb,nl,no,pl,pt,pt-br,ru,sk,sl,sq,sv,tr,tt,ug,uk,vi,zh,zh-cn', // %REMOVE_LINE_CORE%
18 // jscs:enable maximumLineLength
19 requires: 'lineutils,clipboard',
22 '.cke_widget_wrapper{' +
23 'position:relative;' +
26 '.cke_widget_inline{' +
27 'display:inline-block' +
29 '.cke_widget_wrapper:hover>.cke_widget_element{' +
30 'outline:2px solid yellow;' +
33 '.cke_widget_wrapper:hover .cke_widget_editable{' +
34 'outline:2px solid yellow' +
36 '.cke_widget_wrapper.cke_widget_focused>.cke_widget_element,' +
37 // We need higher specificity than hover style.
38 '.cke_widget_wrapper .cke_widget_editable.cke_widget_editable_focused{' +
39 'outline:2px solid #ace' +
41 '.cke_widget_editable{' +
44 '.cke_widget_drag_handler_container{' +
45 'position:absolute;' +
46 'width:' + DRAG_HANDLER_SIZE
+ 'px;' +
48 // Initially drag handler should not be visible, until its position will be
49 // calculated (#11177).
50 // We need to hide unpositined handlers, so they don't extend
51 // widget's outline far to the left (#12024).
54 'transition:height 0s 0.2s;' + // Delay hiding drag handler.
55 // Prevent drag handler from being misplaced (#11198).
58 '.cke_widget_wrapper:hover>.cke_widget_drag_handler_container{' +
59 'height:' + DRAG_HANDLER_SIZE
+ 'px;' +
62 '.cke_widget_drag_handler_container:hover{' +
65 'img.cke_widget_drag_handler{' +
67 'width:' + DRAG_HANDLER_SIZE
+ 'px;' +
68 'height:' + DRAG_HANDLER_SIZE
+ 'px;' +
69 'display:inline-block' +
72 'position:absolute;' +
79 '.cke_editable.cke_widget_dragging, .cke_editable.cke_widget_dragging *{' +
80 'cursor:move !important' +
85 beforeInit: function( editor
) {
87 * An instance of widget repository. It contains all
88 * {@link CKEDITOR.plugins.widget.repository#registered registered widget definitions} and
89 * {@link CKEDITOR.plugins.widget.repository#instances initialized instances}.
91 * editor.widgets.add( 'someName', {
92 * // Widget definition...
95 * editor.widgets.registered.someName; // -> Widget definition
99 * @property {CKEDITOR.plugins.widget.repository} widgets
100 * @member CKEDITOR.editor
102 editor
.widgets
= new Repository( editor
);
105 afterInit: function( editor
) {
106 addWidgetButtons( editor
);
107 setupContextMenu( editor
);
112 * Widget repository. It keeps track of all {@link #registered registered widget definitions} and
113 * {@link #instances initialized instances}. An instance of the repository is available under
114 * the {@link CKEDITOR.editor#widgets} property.
116 * @class CKEDITOR.plugins.widget.repository
117 * @mixins CKEDITOR.event
118 * @constructor Creates a widget repository instance. Note that the widget plugin automatically
119 * creates a repository instance which is available under the {@link CKEDITOR.editor#widgets} property.
120 * @param {CKEDITOR.editor} editor The editor instance for which the repository will be created.
122 function Repository( editor
) {
124 * The editor instance for which this repository was created.
127 * @property {CKEDITOR.editor} editor
129 this.editor
= editor
;
132 * A hash of registered widget definitions (definition name => {@link CKEDITOR.plugins.widget.definition}).
134 * To register a definition use the {@link #add} method.
138 this.registered
= {};
141 * An object containing initialized widget instances (widget id => {@link CKEDITOR.plugins.widget}).
148 * An array of selected widget instances.
151 * @property {CKEDITOR.plugins.widget[]} selected
156 * The focused widget instance. See also {@link CKEDITOR.plugins.widget#event-focus}
157 * and {@link CKEDITOR.plugins.widget#event-blur} events.
159 * editor.on( 'selectionChange', function() {
160 * if ( editor.widgets.focused ) {
161 * // Do something when a widget is focused...
166 * @property {CKEDITOR.plugins.widget} focused
171 * The widget instance that contains the nested editable which is currently focused.
174 * @property {CKEDITOR.plugins.widget} widgetHoldingFocusedEditable
176 this.widgetHoldingFocusedEditable
= null;
185 setupWidgetsLifecycle( this );
186 setupSelectionObserver( this );
187 setupMouseObserver( this );
188 setupKeyboardObserver( this );
189 setupDragAndDrop( this );
190 setupNativeCutAndCopy( this );
193 Repository
.prototype = {
195 * Minimum interval between selection checks.
199 MIN_SELECTION_CHECK_INTERVAL: 500,
202 * Adds a widget definition to the repository. Fires the {@link CKEDITOR.editor#widgetDefinition} event
203 * which allows to modify the widget definition which is going to be registered.
205 * @param {String} name The name of the widget definition.
206 * @param {CKEDITOR.plugins.widget.definition} widgetDef Widget definition.
207 * @returns {CKEDITOR.plugins.widget.definition}
209 add: function( name
, widgetDef
) {
210 // Create prototyped copy of original widget definition, so we won't modify it.
211 widgetDef
= CKEDITOR
.tools
.prototypedCopy( widgetDef
);
212 widgetDef
.name
= name
;
214 widgetDef
._
= widgetDef
._
|| {};
216 this.editor
.fire( 'widgetDefinition', widgetDef
);
218 if ( widgetDef
.template
)
219 widgetDef
.template
= new CKEDITOR
.template( widgetDef
.template
);
221 addWidgetCommand( this.editor
, widgetDef
);
222 addWidgetProcessors( this, widgetDef
);
224 this.registered
[ name
] = widgetDef
;
230 * Adds a callback for element upcasting. Each callback will be executed
231 * for every element which is later tested by upcast methods. If a callback
232 * returns `false`, the element will not be upcasted.
234 * // Images with the "banner" class will not be upcasted (e.g. to the image widget).
235 * editor.widgets.addUpcastCallback( function( element ) {
236 * if ( element.name == 'img' && element.hasClass( 'banner' ) )
240 * @param {Function} callback
241 * @param {CKEDITOR.htmlParser.element} callback.element
243 addUpcastCallback: function( callback
) {
244 this._
.upcastCallbacks
.push( callback
);
248 * Checks the selection to update widget states (selection and focus).
250 * This method is triggered by the {@link #event-checkSelection} event.
252 checkSelection: function() {
253 var sel
= this.editor
.getSelection(),
254 selectedElement
= sel
.getSelectedElement(),
255 updater
= stateUpdater( this ),
258 // Widget is focused so commit and finish checking.
259 if ( selectedElement
&& ( widget
= this.getByElement( selectedElement
, true ) ) )
260 return updater
.focus( widget
).select( widget
).commit();
262 var range
= sel
.getRanges()[ 0 ];
264 // No ranges or collapsed range mean that nothing is selected, so commit and finish checking.
265 if ( !range
|| range
.collapsed
)
266 return updater
.commit();
268 // Range is not empty, so create walker checking for wrappers.
269 var walker
= new CKEDITOR
.dom
.walker( range
),
272 walker
.evaluator
= Widget
.isDomWidgetWrapper
;
274 while ( ( wrapper
= walker
.next() ) )
275 updater
.select( this.getByElement( wrapper
) );
281 * Checks if all widget instances are still present in the DOM.
282 * Destroys those instances that are not present.
283 * Reinitializes widgets on widget wrappers for which widget instances
284 * cannot be found. Takes nested widgets into account, too.
286 * This method triggers the {@link #event-checkWidgets} event whose listeners
287 * can cancel the method's execution or modify its options.
289 * @param [options] The options object.
290 * @param {Boolean} [options.initOnlyNew] Initializes widgets only on newly wrapped
291 * widget elements (those which still have the `cke_widget_new` class). When this option is
292 * set to `true`, widgets which were invalidated (e.g. by replacing with a cloned DOM structure)
293 * will not be reinitialized. This makes the check faster.
294 * @param {Boolean} [options.focusInited] If only one widget is initialized by
295 * the method, it will be focused.
297 checkWidgets: function( options
) {
298 this.fire( 'checkWidgets', CKEDITOR
.tools
.copy( options
|| {} ) );
302 * Removes the widget from the editor and moves the selection to the closest
303 * editable position if the widget was focused before.
305 * @param {CKEDITOR.plugins.widget} widget The widget instance to be deleted.
307 del: function( widget
) {
308 if ( this.focused
=== widget
) {
309 var editor
= widget
.editor
,
310 range
= editor
.createRange(),
313 // If haven't found place for caret on the default side,
314 // try to find it on the other side.
315 if ( !( found
= range
.moveToClosestEditablePosition( widget
.wrapper
, true ) ) )
316 found
= range
.moveToClosestEditablePosition( widget
.wrapper
, false );
319 editor
.getSelection().selectRanges( [ range
] );
322 widget
.wrapper
.remove();
323 this.destroy( widget
, true );
327 * Destroys the widget instance and all its nested widgets (widgets inside its nested editables).
329 * @param {CKEDITOR.plugins.widget} widget The widget instance to be destroyed.
330 * @param {Boolean} [offline] Whether the widget is offline (detached from the DOM tree) —
331 * in this case the DOM (attributes, classes, etc.) will not be cleaned up.
333 destroy: function( widget
, offline
) {
334 if ( this.widgetHoldingFocusedEditable
=== widget
)
335 setFocusedEditable( this, widget
, null, offline
);
337 widget
.destroy( offline
);
338 delete this.instances
[ widget
.id
];
339 this.fire( 'instanceDestroyed', widget
);
343 * Destroys all widget instances.
345 * @param {Boolean} [offline] Whether the widgets are offline (detached from the DOM tree) —
346 * in this case the DOM (attributes, classes, etc.) will not be cleaned up.
347 * @param {CKEDITOR.dom.element} [container] The container within widgets will be destroyed.
348 * This option will be ignored if the `offline` flag was set to `true`, because in such case
349 * it is not possible to find widgets within the passed block.
351 destroyAll: function( offline
, container
) {
354 instances
= this.instances
;
356 if ( container
&& !offline
) {
357 var wrappers
= container
.find( '.cke_widget_wrapper' ),
358 l
= wrappers
.count(),
361 // Length is constant, because this is not a live node list.
362 // Note: since querySelectorAll returns nodes in document order,
363 // outer widgets are always placed before their nested widgets and therefore
364 // are destroyed before them.
365 for ( ; i
< l
; ++i
) {
366 widget
= this.getByElement( wrappers
.getItem( i
), true );
367 // Widget might not be found, because it could be a nested widget,
368 // which would be destroyed when destroying its parent.
370 this.destroy( widget
);
376 for ( id
in instances
) {
377 widget
= instances
[ id
];
378 this.destroy( widget
, offline
);
383 * Finalizes a process of widget creation. This includes:
385 * * inserting widget element into editor,
386 * * marking widget instance as ready (see {@link CKEDITOR.plugins.widget#event-ready}),
387 * * focusing widget instance.
389 * This method is used by the default widget's command and is called
390 * after widget's dialog (if set) is closed. It may also be used in a
391 * customized process of widget creation and insertion.
393 * widget.once( 'edit', function() {
394 * // Finalize creation only of not ready widgets.
395 * if ( widget.isReady() )
398 * // Cancel edit event to prevent automatic widget insertion.
401 * CustomDialog.open( widget.data, function saveCallback( savedData ) {
402 * // Cache the container, because widget may be destroyed while saving data,
403 * // if this process will require some deep transformations.
404 * var container = widget.wrapper.getParent();
406 * widget.setData( savedData );
408 * // Widget will be retrieved from container and inserted into editor.
409 * editor.widgets.finalizeCreation( container );
413 * @param {CKEDITOR.dom.element/CKEDITOR.dom.documentFragment} container The element
414 * or document fragment which contains widget wrapper. The container is used, so before
415 * finalizing creation the widget can be freely transformed (even destroyed and reinitialized).
417 finalizeCreation: function( container
) {
418 var wrapper
= container
.getFirst();
419 if ( wrapper
&& Widget
.isDomWidgetWrapper( wrapper
) ) {
420 this.editor
.insertElement( wrapper
);
422 var widget
= this.getByElement( wrapper
);
423 // Fire postponed #ready event.
425 widget
.fire( 'ready' );
431 * Finds a widget instance which contains a given element. The element will be the {@link CKEDITOR.plugins.widget#wrapper wrapper}
432 * of the returned widget or a descendant of this {@link CKEDITOR.plugins.widget#wrapper wrapper}.
434 * editor.widgets.getByElement( someWidget.wrapper ); // -> someWidget
435 * editor.widgets.getByElement( someWidget.parts.caption ); // -> someWidget
437 * // Check wrapper only:
438 * editor.widgets.getByElement( someWidget.wrapper, true ); // -> someWidget
439 * editor.widgets.getByElement( someWidget.parts.caption, true ); // -> null
441 * @param {CKEDITOR.dom.element} element The element to be checked.
442 * @param {Boolean} [checkWrapperOnly] If set to `true`, the method will not check wrappers' descendants.
443 * @returns {CKEDITOR.plugins.widget} The widget instance or `null`.
445 getByElement: ( function() {
446 var validWrapperElements
= { div: 1, span: 1 };
447 function getWidgetId( element
) {
448 return element
.is( validWrapperElements
) && element
.data( 'cke-widget-id' );
451 return function( element
, checkWrapperOnly
) {
455 var id
= getWidgetId( element
);
457 // There's no need to check element parents if element is a wrapper.
458 if ( !checkWrapperOnly
&& !id
) {
459 var limit
= this.editor
.editable();
461 // Try to find a closest ascendant which is a widget wrapper.
463 element
= element
.getParent();
464 } while ( element
&& !element
.equals( limit
) && !( id
= getWidgetId( element
) ) );
467 return this.instances
[ id
] || null;
472 * Initializes a widget on a given element if the widget has not been initialized on it yet.
474 * @param {CKEDITOR.dom.element} element The future widget element.
475 * @param {String/CKEDITOR.plugins.widget.definition} [widgetDef] Name of a widget or a widget definition.
476 * The widget definition should be previously registered by using the
477 * {@link CKEDITOR.plugins.widget.repository#add} method.
478 * @param [startupData] Widget startup data (has precedence over default one).
479 * @returns {CKEDITOR.plugins.widget} The widget instance or `null` if a widget could not be initialized on
482 initOn: function( element
, widgetDef
, startupData
) {
484 widgetDef
= this.registered
[ element
.data( 'widget' ) ];
485 else if ( typeof widgetDef
== 'string' )
486 widgetDef
= this.registered
[ widgetDef
];
491 // Wrap element if still wasn't wrapped (was added during runtime by method that skips dataProcessor).
492 var wrapper
= this.wrapElement( element
, widgetDef
.name
);
495 // Check if widget wrapper is new (widget hasn't been initialized on it yet).
496 // This class will be removed by widget constructor to avoid locking snapshot twice.
497 if ( wrapper
.hasClass( 'cke_widget_new' ) ) {
498 var widget
= new Widget( this, this._
.nextId
++, element
, widgetDef
, startupData
);
500 // Widget could be destroyed when initializing it.
501 if ( widget
.isInited() ) {
502 this.instances
[ widget
.id
] = widget
;
510 // Widget already has been initialized, so try to get widget by element.
511 // Note - it may happen that other instance will returned than the one created above,
512 // if for example widget was destroyed and reinitialized.
513 return this.getByElement( element
);
516 // No wrapper means that there's no widget for this element.
521 * Initializes widgets on all elements which were wrapped by {@link #wrapElement} and
522 * have not been initialized yet.
524 * @param {CKEDITOR.dom.element} [container=editor.editable()] The container which will be checked for not
525 * initialized widgets. Defaults to editor's {@link CKEDITOR.editor#editable editable} element.
526 * @returns {CKEDITOR.plugins.widget[]} Array of widget instances which have been initialized.
527 * Note: Only first-level widgets are returned — without nested widgets.
529 initOnAll: function( container
) {
530 var newWidgets
= ( container
|| this.editor
.editable() ).find( '.cke_widget_new' ),
534 for ( var i
= newWidgets
.count(); i
--; ) {
535 instance
= this.initOn( newWidgets
.getItem( i
).getFirst( Widget
.isDomWidgetElement
) );
537 newInstances
.push( instance
);
544 * Allows to listen to events on specific types of widgets, even if they are not created yet.
546 * Please note that this method inherits parameters from the {@link CKEDITOR.event#method-on} method with one
547 * extra parameter at the beginning which is the widget name.
549 * editor.widgets.onWidget( 'image', 'action', function( evt ) {
550 * // Event `action` occurs on `image` widget.
554 * @param {String} widgetName
555 * @param {String} eventName
556 * @param {Function} listenerFunction
557 * @param {Object} [scopeObj]
558 * @param {Object} [listenerData]
559 * @param {Number} [priority=10]
561 onWidget: function( widgetName
) {
562 var args
= Array
.prototype.slice
.call( arguments
);
566 for ( var i
in this.instances
) {
567 var instance
= this.instances
[ i
];
569 if ( instance
.name
== widgetName
) {
570 instance
.on
.apply( instance
, args
);
574 this.on( 'instanceCreated', function( evt
) {
575 var widget
= evt
.data
;
577 if ( widget
.name
== widgetName
) {
578 widget
.on
.apply( widget
, args
);
584 * Parses element classes string and returns an object
585 * whose keys contain class names. Skips all `cke_*` classes.
587 * This method is used by the {@link CKEDITOR.plugins.widget#getClasses} method and
588 * may be used when overriding that method.
591 * @param {String} classes String (value of `class` attribute).
592 * @returns {Object} Object containing classes or `null` if no classes found.
594 parseElementClasses: function( classes
) {
598 classes
= CKEDITOR
.tools
.trim( classes
).split( /\s+/ );
604 while ( ( cl
= classes
.pop() ) ) {
605 if ( cl
.indexOf( 'cke_' ) == -1 )
606 obj
[ cl
] = hasClasses
= 1;
609 return hasClasses
? obj : null;
613 * Wraps an element with a widget's non-editable container.
615 * If this method is called on an {@link CKEDITOR.htmlParser.element}, then it will
616 * also take care of fixing the DOM after wrapping (the wrapper may not be allowed in element's parent).
618 * @param {CKEDITOR.dom.element/CKEDITOR.htmlParser.element} element The widget element to be wrapped.
619 * @param {String} [widgetName] The name of the widget definition. Defaults to element's `data-widget`
621 * @returns {CKEDITOR.dom.element/CKEDITOR.htmlParser.element} The wrapper element or `null` if
622 * the widget definition of this name is not registered.
624 wrapElement: function( element
, widgetName
) {
629 if ( element
instanceof CKEDITOR
.dom
.element
) {
630 widgetDef
= this.registered
[ widgetName
|| element
.data( 'widget' ) ];
634 // Do not wrap already wrapped element.
635 wrapper
= element
.getParent();
636 if ( wrapper
&& wrapper
.type
== CKEDITOR
.NODE_ELEMENT
&& wrapper
.data( 'cke-widget-wrapper' ) )
639 // If attribute isn't already set (e.g. for pasted widget), set it.
640 if ( !element
.hasAttribute( 'data-cke-widget-keep-attr' ) )
641 element
.data( 'cke-widget-keep-attr', element
.data( 'widget' ) ? 1 : 0 );
643 element
.data( 'widget', widgetName
);
645 isInline
= isWidgetInline( widgetDef
, element
.getName() );
647 wrapper
= new CKEDITOR
.dom
.element( isInline
? 'span' : 'div' );
648 wrapper
.setAttributes( getWrapperAttributes( isInline
) );
650 wrapper
.data( 'cke-display-name', widgetDef
.pathName
? widgetDef
.pathName : element
.getName() );
652 // Replace element unless it is a detached one.
653 if ( element
.getParent( true ) )
654 wrapper
.replace( element
);
655 element
.appendTo( wrapper
);
657 else if ( element
instanceof CKEDITOR
.htmlParser
.element
) {
658 widgetDef
= this.registered
[ widgetName
|| element
.attributes
[ 'data-widget' ] ];
662 wrapper
= element
.parent
;
663 if ( wrapper
&& wrapper
.type
== CKEDITOR
.NODE_ELEMENT
&& wrapper
.attributes
[ 'data-cke-widget-wrapper' ] )
666 // If attribute isn't already set (e.g. for pasted widget), set it.
667 if ( !( 'data-cke-widget-keep-attr' in element
.attributes
) )
668 element
.attributes
[ 'data-cke-widget-keep-attr' ] = element
.attributes
[ 'data-widget' ] ? 1 : 0;
670 element
.attributes
[ 'data-widget' ] = widgetName
;
672 isInline
= isWidgetInline( widgetDef
, element
.name
);
674 wrapper
= new CKEDITOR
.htmlParser
.element( isInline
? 'span' : 'div', getWrapperAttributes( isInline
) );
676 wrapper
.attributes
[ 'data-cke-display-name' ] = widgetDef
.pathName
? widgetDef
.pathName : element
.name
;
678 var parent
= element
.parent
,
681 // Don't detach already detached element.
683 index
= element
.getIndex();
687 wrapper
.add( element
);
689 // Insert wrapper fixing DOM (splitting parents if wrapper is not allowed inside them).
690 parent
&& insertElement( parent
, index
, wrapper
);
697 _tests_createEditableFilter: createEditableFilter
700 CKEDITOR
.event
.implementOn( Repository
.prototype );
703 * An event fired when a widget instance is created, but before it is fully initialized.
705 * @event instanceCreated
706 * @param {CKEDITOR.plugins.widget} data The widget instance.
710 * An event fired when a widget instance was destroyed.
712 * See also {@link CKEDITOR.plugins.widget#event-destroy}.
714 * @event instanceDestroyed
715 * @param {CKEDITOR.plugins.widget} data The widget instance.
719 * An event fired to trigger the selection check.
721 * See the {@link #method-checkSelection} method.
723 * @event checkSelection
727 * An event fired by the the {@link #method-checkWidgets} method.
729 * It can be canceled in order to stop the {@link #method-checkWidgets}
730 * method execution or the event listener can modify the method's options.
732 * @event checkWidgets
734 * @param {Boolean} [data.initOnlyNew] Initialize widgets only on newly wrapped
735 * widget elements (those which still have the `cke_widget_new` class). When this option is
736 * set to `true`, widgets which were invalidated (e.g. by replacing with a cloned DOM structure)
737 * will not be reinitialized. This makes the check faster.
738 * @param {Boolean} [data.focusInited] If only one widget is initialized by
739 * the method, it will be focused.
744 * An instance of a widget. Together with {@link CKEDITOR.plugins.widget.repository} these
745 * two classes constitute the core of the Widget System.
747 * Note that neither the repository nor the widget instances can be created by using their constructors.
748 * A repository instance is automatically set up by the Widget plugin and is accessible under
749 * {@link CKEDITOR.editor#widgets}, while widget instances are created and destroyed by the repository.
751 * To create a widget, first you need to {@link CKEDITOR.plugins.widget.repository#add register} its
752 * {@link CKEDITOR.plugins.widget.definition definition}:
754 * editor.widgets.add( 'simplebox', {
755 * upcast: function( element ) {
756 * // Defines which elements will become widgets.
757 * if ( element.hasClass( 'simplebox' ) )
765 * Once the widget definition is registered, widgets will be automatically
766 * created when loading data:
768 * editor.setData( '<div class="simplebox">foo</div>', function() {
769 * console.log( editor.widgets.instances ); // -> An object containing one instance.
772 * It is also possible to create instances during runtime by using a command
773 * (if a {@link CKEDITOR.plugins.widget.definition#template} property was defined):
775 * // You can execute an automatically defined command to
776 * // insert a new simplebox widget or edit the one currently focused.
777 * editor.execCommand( 'simplebox' );
779 * Note: Since CKEditor 4.5 widget's `startupData` can be passed as the command argument:
781 * editor.execCommand( 'simplebox', {
787 * A widget can also be created in a completely custom way:
789 * var element = editor.document.createElement( 'div' );
790 * editor.insertElement( element );
791 * var widget = editor.widgets.initOn( element, 'simplebox' );
794 * @class CKEDITOR.plugins.widget
795 * @mixins CKEDITOR.event
796 * @extends CKEDITOR.plugins.widget.definition
797 * @constructor Creates an instance of the widget class. Do not use it directly, but instead initialize widgets
798 * by using the {@link CKEDITOR.plugins.widget.repository#initOn} method or by the upcasting system.
799 * @param {CKEDITOR.plugins.widget.repository} widgetsRepo
800 * @param {Number} id Unique ID of this widget instance.
801 * @param {CKEDITOR.dom.element} element The widget element.
802 * @param {CKEDITOR.plugins.widget.definition} widgetDef Widget's registered definition.
803 * @param [startupData] Initial widget data. This data object will overwrite the default data and
804 * the data loaded from the DOM.
806 function Widget( widgetsRepo
, id
, element
, widgetDef
, startupData
) {
807 var editor
= widgetsRepo
.editor
;
809 // Extend this widget with widgetDef-specific methods and properties.
810 CKEDITOR
.tools
.extend( this, widgetDef
, {
812 * The editor instance.
815 * @property {CKEDITOR.editor}
820 * This widget's unique (per editor instance) ID.
828 * Whether this widget is an inline widget (based on an inline element unless
829 * forced otherwise by {@link CKEDITOR.plugins.widget.definition#inline}).
831 * **Note:** This option does not allow to turn a block element into an inline widget.
832 * However, it makes it possible to turn an inline element into a block widget or to
833 * force a correct type in case when automatic recognition fails.
836 * @property {Boolean}
838 inline: element
.getParent().getName() == 'span',
841 * The widget element — the element on which the widget was initialized.
844 * @property {CKEDITOR.dom.element} element
849 * Widget's data object.
851 * The data can only be set by using the {@link #setData} method.
852 * Changes made to the data fire the {@link #event-data} event.
856 data: CKEDITOR
.tools
.extend( {}, typeof widgetDef
.defaults
== 'function' ? widgetDef
.defaults() : widgetDef
.defaults
),
859 * Indicates if a widget is data-ready. Set to `true` when data from all sources
860 * ({@link CKEDITOR.plugins.widget.definition#defaults}, set in the
861 * {@link #init} method, loaded from the widget's element and startup data coming from the constructor)
862 * are finally loaded. This is immediately followed by the first {@link #event-data}.
869 * Whether a widget instance was initialized. This means that:
871 * * An instance was created,
872 * * Its properties were set,
873 * * The `init` method was executed.
875 * **Note**: The first {@link #event-data} event could not be fired yet which
876 * means that the widget's DOM has not been set up yet. Wait for the {@link #event-ready}
877 * event to be notified when a widget is fully initialized and ready.
879 * **Note**: Use the {@link #isInited} method to check whether a widget is initialized and
880 * has not been destroyed.
887 * Whether a widget instance is ready. This means that the widget is {@link #inited} and
888 * that its DOM was finally set up.
890 * **Note:** Use the {@link #isReady} method to check whether a widget is ready and
891 * has not been destroyed.
897 // Revert what widgetDef could override (automatic #edit listener).
898 edit: Widget
.prototype.edit
,
901 * The nested editable element which is currently focused.
904 * @property {CKEDITOR.plugins.widget.nestedEditable}
906 focusedEditable: null,
909 * The widget definition from which this instance was created.
912 * @property {CKEDITOR.plugins.widget.definition} definition
914 definition: widgetDef
,
917 * Link to the widget repository which created this instance.
920 * @property {CKEDITOR.plugins.widget.repository} repository
922 repository: widgetsRepo
,
924 draggable: widgetDef
.draggable
!== false,
926 // WAAARNING: Overwrite widgetDef's priv object, because otherwise violent unicorn's gonna visit you.
928 downcastFn: ( widgetDef
.downcast
&& typeof widgetDef
.downcast
== 'string' ) ?
929 widgetDef
.downcasts
[ widgetDef
.downcast
] : widgetDef
.downcast
934 * An object of widget component elements.
936 * For every `partName => selector` pair in {@link CKEDITOR.plugins.widget.definition#parts},
937 * one `partName => element` pair is added to this object during the widget initialization.
940 * @property {Object} parts
944 * The template which will be used to create a new widget element (when the widget's command is executed).
945 * It will be populated with {@link #defaults default values}.
948 * @property {CKEDITOR.template} template
952 * The widget wrapper — a non-editable `div` or `span` element (depending on {@link #inline})
953 * which is a parent of the {@link #element} and widget compontents like the drag handler and the {@link #mask}.
954 * It is the outermost widget element.
957 * @property {CKEDITOR.dom.element} wrapper
960 widgetsRepo
.fire( 'instanceCreated', this );
962 setupWidget( this, widgetDef
);
964 this.init
&& this.init();
966 // Finally mark widget as inited.
969 setupWidgetData( this, startupData
);
971 // If at some point (e.g. in #data listener) widget hasn't been destroyed
972 // and widget is already attached to document then fire #ready.
973 if ( this.isInited() && editor
.editable().contains( this.wrapper
) ) {
975 this.fire( 'ready' );
981 * Adds a class to the widget element. This method is used by
982 * the {@link #applyStyle} method and should be overriden by widgets
983 * which should handle classes differently (e.g. add them to other elements).
985 * **Note**: This method should not be used directly. Use the {@link #setData} method to
986 * set the `classes` property. Read more in the {@link #setData} documentation.
988 * See also: {@link #removeClass}, {@link #hasClass}, {@link #getClasses}.
991 * @param {String} className The class name to be added.
993 addClass: function( className
) {
994 this.element
.addClass( className
);
998 * Applies the specified style to the widget. It is highly recommended to use the
999 * {@link CKEDITOR.editor#applyStyle} or {@link CKEDITOR.style#apply} methods instead of
1000 * using this method directly, because unlike editor's and style's methods, this one
1001 * does not perform any checks.
1003 * By default this method handles only classes defined in the style. It clones existing
1004 * classes which are stored in the {@link #property-data widget data}'s `classes` property,
1005 * adds new classes, and calls the {@link #setData} method if at least one new class was added.
1006 * Then, using the {@link #event-data} event listener widget applies modifications passing
1007 * new classes to the {@link #addClass} method.
1009 * If you need to handle classes differently than in the default way, you can override the
1010 * {@link #addClass} and related methods. You can also handle other style properties than `classes`
1011 * by overriding this method.
1013 * See also: {@link #checkStyleActive}, {@link #removeStyle}.
1016 * @param {CKEDITOR.style} style The custom widget style to be applied.
1018 applyStyle: function( style
) {
1019 applyRemoveStyle( this, style
, 1 );
1023 * Checks if the specified style is applied to this widget. It is highly recommended to use the
1024 * {@link CKEDITOR.style#checkActive} method instead of using this method directly,
1025 * because unlike style's method, this one does not perform any checks.
1027 * By default this method handles only classes defined in the style and passes
1028 * them to the {@link #hasClass} method. You can override these methods to handle classes
1029 * differently or to handle more of the style properties.
1031 * See also: {@link #applyStyle}, {@link #removeStyle}.
1034 * @param {CKEDITOR.style} style The custom widget style to be checked.
1035 * @returns {Boolean} Whether the style is applied to this widget.
1037 checkStyleActive: function( style
) {
1038 var classes
= getStyleClasses( style
),
1044 while ( ( cl
= classes
.pop() ) ) {
1045 if ( !this.hasClass( cl
) )
1052 * Destroys this widget instance.
1054 * Use {@link CKEDITOR.plugins.widget.repository#destroy} when possible instead of this method.
1056 * This method fires the {#event-destroy} event.
1058 * @param {Boolean} [offline] Whether a widget is offline (detached from the DOM tree) —
1059 * in this case the DOM (attributes, classes, etc.) will not be cleaned up.
1061 destroy: function( offline
) {
1062 this.fire( 'destroy' );
1064 if ( this.editables
) {
1065 for ( var name
in this.editables
)
1066 this.destroyEditable( name
, offline
);
1070 if ( this.element
.data( 'cke-widget-keep-attr' ) == '0' )
1071 this.element
.removeAttribute( 'data-widget' );
1072 this.element
.removeAttributes( [ 'data-cke-widget-data', 'data-cke-widget-keep-attr' ] );
1073 this.element
.removeClass( 'cke_widget_element' );
1074 this.element
.replace( this.wrapper
);
1077 this.wrapper
= null;
1081 * Destroys a nested editable and all nested widgets.
1083 * @param {String} editableName Nested editable name.
1084 * @param {Boolean} [offline] See {@link #method-destroy} method.
1086 destroyEditable: function( editableName
, offline
) {
1087 var editable
= this.editables
[ editableName
];
1089 editable
.removeListener( 'focus', onEditableFocus
);
1090 editable
.removeListener( 'blur', onEditableBlur
);
1091 this.editor
.focusManager
.remove( editable
);
1094 this.repository
.destroyAll( false, editable
);
1095 editable
.removeClass( 'cke_widget_editable' );
1096 editable
.removeClass( 'cke_widget_editable_focused' );
1097 editable
.removeAttributes( [ 'contenteditable', 'data-cke-widget-editable', 'data-cke-enter-mode' ] );
1100 delete this.editables
[ editableName
];
1104 * Starts widget editing.
1106 * This method fires the {@link CKEDITOR.plugins.widget#event-edit} event
1107 * which may be canceled in order to prevent it from opening a dialog window.
1109 * The dialog window name is obtained from the event's data `dialog` property or
1110 * from {@link CKEDITOR.plugins.widget.definition#dialog}.
1112 * @returns {Boolean} Returns `true` if a dialog window was opened.
1115 var evtData
= { dialog: this.dialog
},
1118 // Edit event was blocked or there's no dialog to be automatically opened.
1119 if ( this.fire( 'edit', evtData
) === false || !evtData
.dialog
)
1122 this.editor
.openDialog( evtData
.dialog
, function( dialog
) {
1126 // Allow to add a custom dialog handler.
1127 if ( that
.fire( 'dialog', dialog
) === false )
1130 showListener
= dialog
.on( 'show', function() {
1131 dialog
.setupContent( that
);
1134 okListener
= dialog
.on( 'ok', function() {
1135 // Commit dialog's fields, but prevent from
1136 // firing data event for every field. Fire only one,
1137 // bulk event at the end.
1139 dataListener
= that
.on( 'data', function( evt
) {
1144 // Create snapshot preceeding snapshot with changed widget...
1145 // TODO it should not be required, but it is and I found similar
1146 // code in dialog#ok listener in dialog/plugin.js.
1147 that
.editor
.fire( 'saveSnapshot' );
1148 dialog
.commitContent( that
);
1150 dataListener
.removeListener();
1151 if ( dataChanged
) {
1152 that
.fire( 'data', that
.data
);
1153 that
.editor
.fire( 'saveSnapshot' );
1157 dialog
.once( 'hide', function() {
1158 showListener
.removeListener();
1159 okListener
.removeListener();
1167 * Returns widget element classes parsed to an object. This method
1168 * is used to populate the `classes` property of widget's {@link #property-data}.
1170 * This method reuses {@link CKEDITOR.plugins.widget.repository#parseElementClasses}.
1171 * It should be overriden if a widget should handle classes differently (e.g. on other elements).
1173 * See also: {@link #removeClass}, {@link #addClass}, {@link #hasClass}.
1178 getClasses: function() {
1179 return this.repository
.parseElementClasses( this.element
.getAttribute( 'class' ) );
1183 * Checks if the widget element has specified class. This method is used by
1184 * the {@link #checkStyleActive} method and should be overriden by widgets
1185 * which should handle classes differently (e.g. on other elements).
1187 * See also: {@link #removeClass}, {@link #addClass}, {@link #getClasses}.
1190 * @param {String} className The class to be checked.
1191 * @param {Boolean} Whether a widget has specified class.
1193 hasClass: function( className
) {
1194 return this.element
.hasClass( className
);
1198 * Initializes a nested editable.
1200 * **Note**: Only elements from {@link CKEDITOR.dtd#$editable} may become editables.
1202 * @param {String} editableName The nested editable name.
1203 * @param {CKEDITOR.plugins.widget.nestedEditable.definition} definition The definition of the nested editable.
1204 * @returns {Boolean} Whether an editable was successfully initialized.
1206 initEditable: function( editableName
, definition
) {
1207 // Don't fetch just first element which matched selector but look for a correct one. (#13334)
1208 var editable
= this._findOneNotNested( definition
.selector
);
1210 if ( editable
&& editable
.is( CKEDITOR
.dtd
.$editable
) ) {
1211 editable
= new NestedEditable( this.editor
, editable
, {
1212 filter: createEditableFilter
.call( this.repository
, this.name
, editableName
, definition
)
1214 this.editables
[ editableName
] = editable
;
1216 editable
.setAttributes( {
1217 contenteditable: 'true',
1218 'data-cke-widget-editable': editableName
,
1219 'data-cke-enter-mode': editable
.enterMode
1222 if ( editable
.filter
)
1223 editable
.data( 'cke-filter', editable
.filter
.id
);
1225 editable
.addClass( 'cke_widget_editable' );
1226 // This class may be left when d&ding widget which
1227 // had focused editable. Clean this class here, not in
1228 // cleanUpWidgetElement for performance and code size reasons.
1229 editable
.removeClass( 'cke_widget_editable_focused' );
1231 if ( definition
.pathName
)
1232 editable
.data( 'cke-display-name', definition
.pathName
);
1234 this.editor
.focusManager
.add( editable
);
1235 editable
.on( 'focus', onEditableFocus
, this );
1236 CKEDITOR
.env
.ie
&& editable
.on( 'blur', onEditableBlur
, this );
1238 // Finally, process editable's data. This data wasn't processed when loading
1239 // editor's data, becuase they need to be processed separately, with its own filters and settings.
1240 editable
._
.initialSetData
= true;
1241 editable
.setData( editable
.getHtml() );
1250 * Looks inside wrapper element to find a node that
1251 * matches given selector and is not nested in other widget. (#13334)
1255 * @param {String} selector Selector to match.
1256 * @returns {CKEDITOR.dom.element} Matched element or `null` if a node has not been found.
1258 _findOneNotNested: function( selector
) {
1259 var matchedElements
= this.wrapper
.find( selector
),
1263 for ( var i
= 0; i
< matchedElements
.count(); i
++ ) {
1264 match
= matchedElements
.getItem( i
);
1265 closestWrapper
= match
.getAscendant( Widget
.isDomWidgetWrapper
);
1267 // The closest ascendant-wrapper of this match defines to which widget
1268 // this match belongs. If the ascendant is this widget's wrapper
1269 // it means that the match is not nested in other widget.
1270 if ( this.wrapper
.equals( closestWrapper
) ) {
1279 * Checks if a widget has already been initialized and has not been destroyed yet.
1281 * See {@link #inited} for more details.
1283 * @returns {Boolean}
1285 isInited: function() {
1286 return !!( this.wrapper
&& this.inited
);
1290 * Checks if a widget is ready and has not been destroyed yet.
1292 * See {@link #property-ready} for more details.
1294 * @returns {Boolean}
1296 isReady: function() {
1297 return this.isInited() && this.ready
;
1301 * Focuses a widget by selecting it.
1304 var sel
= this.editor
.getSelection();
1306 // Fake the selection before focusing editor, to avoid unpreventable viewports scrolling
1307 // on Webkit/Blink/IE which is done because there's no selection or selection was somewhere else than widget.
1309 var isDirty
= this.editor
.checkDirty();
1311 sel
.fake( this.wrapper
);
1313 !isDirty
&& this.editor
.resetDirty();
1316 // Always focus editor (not only when focusManger.hasFocus is false) (because of #10483).
1317 this.editor
.focus();
1321 * Removes a class from the widget element. This method is used by
1322 * the {@link #removeStyle} method and should be overriden by widgets
1323 * which should handle classes differently (e.g. on other elements).
1325 * **Note**: This method should not be used directly. Use the {@link #setData} method to
1326 * set the `classes` property. Read more in the {@link #setData} documentation.
1328 * See also: {@link #hasClass}, {@link #addClass}.
1331 * @param {String} className The class to be removed.
1333 removeClass: function( className
) {
1334 this.element
.removeClass( className
);
1338 * Removes the specified style from the widget. It is highly recommended to use the
1339 * {@link CKEDITOR.editor#removeStyle} or {@link CKEDITOR.style#remove} methods instead of
1340 * using this method directly, because unlike editor's and style's methods, this one
1341 * does not perform any checks.
1343 * Read more about how applying/removing styles works in the {@link #applyStyle} method documentation.
1345 * See also {@link #checkStyleActive}, {@link #applyStyle}, {@link #getClasses}.
1348 * @param {CKEDITOR.style} style The custom widget style to be removed.
1350 removeStyle: function( style
) {
1351 applyRemoveStyle( this, style
, 0 );
1355 * Sets widget value(s) in the {@link #property-data} object.
1356 * If the given value(s) modifies current ones, the {@link #event-data} event is fired.
1358 * this.setData( 'align', 'left' );
1359 * this.data.align; // -> 'left'
1361 * this.setData( { align: 'right', opened: false } );
1362 * this.data.align; // -> 'right'
1363 * this.data.opened; // -> false
1365 * Set values are stored in {@link #element}'s attribute (`data-cke-widget-data`),
1366 * in a JSON string, therefore {@link #property-data} should contain
1367 * only serializable data.
1369 * **Note:** A special data property, `classes`, exists. It contains an object with
1370 * classes which were returned by the {@link #getClasses} method during the widget initialization.
1371 * This property is then used by the {@link #applyStyle} and {@link #removeStyle} methods.
1372 * When it is changed (the reference to object must be changed!), the widget updates its classes by
1373 * using the {@link #addClass} and {@link #removeClass} methods.
1375 * // Adding a new class.
1376 * var classes = CKEDITOR.tools.clone( widget.data.classes );
1377 * classes.newClass = 1;
1378 * widget.setData( 'classes', classes );
1380 * // Removing a class.
1381 * var classes = CKEDITOR.tools.clone( widget.data.classes );
1382 * delete classes.newClass;
1383 * widget.setData( 'classes', classes );
1385 * @param {String/Object} keyOrData
1386 * @param {Object} value
1389 setData: function( key
, value
) {
1390 var data
= this.data
,
1393 if ( typeof key
== 'string' ) {
1394 if ( data
[ key
] !== value
) {
1395 data
[ key
] = value
;
1402 for ( key
in newData
) {
1403 if ( data
[ key
] !== newData
[ key
] ) {
1405 data
[ key
] = newData
[ key
];
1410 // Block firing data event and overwriting data element before setupWidgetData is executed.
1411 if ( modified
&& this.dataReady
) {
1412 writeDataToElement( this );
1413 this.fire( 'data', data
);
1420 * Changes the widget's focus state. This method is executed automatically after
1421 * a widget was focused by the {@link #method-focus} method or the selection was moved
1422 * out of the widget.
1424 * This is a low-level method which is not integrated with e.g. the undo manager.
1425 * Use the {@link #method-focus} method instead.
1427 * @param {Boolean} selected Whether to select or deselect this widget.
1430 setFocused: function( focused
) {
1431 this.wrapper
[ focused
? 'addClass' : 'removeClass' ]( 'cke_widget_focused' );
1432 this.fire( focused
? 'focus' : 'blur' );
1437 * Changes the widget's select state. This method is executed automatically after
1438 * a widget was selected by the {@link #method-focus} method or the selection
1439 * was moved out of the widget.
1441 * This is a low-level method which is not integrated with e.g. the undo manager.
1442 * Use the {@link #method-focus} method instead or simply change the selection.
1444 * @param {Boolean} selected Whether to select or deselect this widget.
1447 setSelected: function( selected
) {
1448 this.wrapper
[ selected
? 'addClass' : 'removeClass' ]( 'cke_widget_selected' );
1449 this.fire( selected
? 'select' : 'deselect' );
1454 * Repositions drag handler according to the widget's element position. Should be called from events, like mouseover.
1456 updateDragHandlerPosition: function() {
1457 var editor
= this.editor
,
1458 domElement
= this.element
.$,
1459 oldPos
= this._
.dragHandlerOffset
,
1461 x: domElement
.offsetLeft
,
1462 y: domElement
.offsetTop
- DRAG_HANDLER_SIZE
1465 if ( oldPos
&& newPos
.x
== oldPos
.x
&& newPos
.y
== oldPos
.y
)
1468 // We need to make sure that dirty state is not changed (#11487).
1469 var initialDirty
= editor
.checkDirty();
1471 editor
.fire( 'lockSnapshot' );
1472 this.dragHandlerContainer
.setStyles( {
1473 top: newPos
.y
+ 'px',
1474 left: newPos
.x
+ 'px',
1477 editor
.fire( 'unlockSnapshot' );
1478 !initialDirty
&& editor
.resetDirty();
1480 this._
.dragHandlerOffset
= newPos
;
1484 CKEDITOR
.event
.implementOn( Widget
.prototype );
1487 * Gets the {@link #isDomNestedEditable nested editable}
1488 * (returned as a {@link CKEDITOR.dom.element}, not as a {@link CKEDITOR.plugins.widget.nestedEditable})
1489 * closest to the `node` or the `node` if it is a nested editable itself.
1493 * @param {CKEDITOR.dom.element} guard Stop ancestor search on this node (usually editor's editable).
1494 * @param {CKEDITOR.dom.node} node Start the search from this node.
1495 * @returns {CKEDITOR.dom.element/null} Element or `null` if not found.
1497 Widget
.getNestedEditable = function( guard
, node
) {
1498 if ( !node
|| node
.equals( guard
) )
1501 if ( Widget
.isDomNestedEditable( node
) )
1504 return Widget
.getNestedEditable( guard
, node
.getParent() );
1508 * Checks whether the `node` is a widget's drag handle element.
1512 * @param {CKEDITOR.dom.node} node
1513 * @returns {Boolean}
1515 Widget
.isDomDragHandler = function( node
) {
1516 return node
.type
== CKEDITOR
.NODE_ELEMENT
&& node
.hasAttribute( 'data-cke-widget-drag-handler' );
1520 * Checks whether the `node` is a container of the widget's drag handle element.
1524 * @param {CKEDITOR.dom.node} node
1525 * @returns {Boolean}
1527 Widget
.isDomDragHandlerContainer = function( node
) {
1528 return node
.type
== CKEDITOR
.NODE_ELEMENT
&& node
.hasClass( 'cke_widget_drag_handler_container' );
1532 * Checks whether the `node` is a {@link CKEDITOR.plugins.widget#editables nested editable}.
1533 * Note that this function only checks whether it is the right element, not whether
1534 * the passed `node` is an instance of {@link CKEDITOR.plugins.widget.nestedEditable}.
1538 * @param {CKEDITOR.dom.node} node
1539 * @returns {Boolean}
1541 Widget
.isDomNestedEditable = function( node
) {
1542 return node
.type
== CKEDITOR
.NODE_ELEMENT
&& node
.hasAttribute( 'data-cke-widget-editable' );
1546 * Checks whether the `node` is a {@link CKEDITOR.plugins.widget#element widget element}.
1550 * @param {CKEDITOR.dom.node} node
1551 * @returns {Boolean}
1553 Widget
.isDomWidgetElement = function( node
) {
1554 return node
.type
== CKEDITOR
.NODE_ELEMENT
&& node
.hasAttribute( 'data-widget' );
1558 * Checks whether the `node` is a {@link CKEDITOR.plugins.widget#wrapper widget wrapper}.
1562 * @param {CKEDITOR.dom.element} node
1563 * @returns {Boolean}
1565 Widget
.isDomWidgetWrapper = function( node
) {
1566 return node
.type
== CKEDITOR
.NODE_ELEMENT
&& node
.hasAttribute( 'data-cke-widget-wrapper' );
1570 * Checks whether the `node` is a {@link CKEDITOR.plugins.widget#element widget element}.
1574 * @param {CKEDITOR.htmlParser.node} node
1575 * @returns {Boolean}
1577 Widget
.isParserWidgetElement = function( node
) {
1578 return node
.type
== CKEDITOR
.NODE_ELEMENT
&& !!node
.attributes
[ 'data-widget' ];
1582 * Checks whether the `node` is a {@link CKEDITOR.plugins.widget#wrapper widget wrapper}.
1586 * @param {CKEDITOR.htmlParser.element} node
1587 * @returns {Boolean}
1589 Widget
.isParserWidgetWrapper = function( node
) {
1590 return node
.type
== CKEDITOR
.NODE_ELEMENT
&& !!node
.attributes
[ 'data-cke-widget-wrapper' ];
1594 * An event fired when a widget is ready (fully initialized). This event is fired after:
1596 * * {@link #init} is called,
1597 * * The first {@link #event-data} event is fired,
1598 * * A widget is attached to the document.
1600 * Therefore, in case of widget creation with a command which opens a dialog window, this event
1601 * will be delayed after the dialog window is closed and the widget is finally inserted into the document.
1603 * **Note**: If your widget does not use automatic dialog window binding (i.e. you open the dialog window manually)
1604 * or another situation in which the widget wrapper is not attached to document at the time when it is
1605 * initialized occurs, you need to take care of firing {@link #event-ready} yourself.
1607 * See also {@link #property-ready} and {@link #property-inited} properties, and
1608 * {@link #isReady} and {@link #isInited} methods.
1614 * An event fired when a widget is about to be destroyed, but before it is
1621 * An event fired when a widget is focused.
1623 * Widget can be focused by executing {@link #method-focus}.
1629 * An event fired when a widget is blurred.
1635 * An event fired when a widget is selected.
1641 * An event fired when a widget is deselected.
1647 * An event fired by the {@link #method-edit} method. It can be canceled
1648 * in order to stop the default action (opening a dialog window and/or
1649 * {@link CKEDITOR.plugins.widget.repository#finalizeCreation finalizing widget creation}).
1653 * @param {String} data.dialog Defaults to {@link CKEDITOR.plugins.widget.definition#dialog}
1654 * and can be changed or set by the listener.
1658 * An event fired when a dialog window for widget editing is opened.
1659 * This event can be canceled in order to handle the editing dialog in a custom manner.
1662 * @param {CKEDITOR.dialog} data The opened dialog window instance.
1666 * An event fired when a key is pressed on a focused widget.
1667 * This event is forwarded from the {@link CKEDITOR.editor#key} event and
1668 * has the ability to block editor keystrokes if it is canceled.
1672 * @param {Number} data.keyCode A number representing the key code (or combination).
1676 * An event fired when a widget is double clicked.
1678 * **Note:** If a default editing action is executed on double click (i.e. a widget has a
1679 * {@link CKEDITOR.plugins.widget.definition#dialog dialog} defined and the {@link #event-doubleclick} event was not
1680 * canceled), this event will be automatically canceled, so a listener added with the default priority (10)
1681 * will not be executed. Use a listener with low priority (e.g. 5) to be sure that it will be executed.
1683 * widget.on( 'doubleclick', function( evt ) {
1684 * console.log( 'widget#doubleclick' );
1685 * }, null, null, 5 );
1687 * If your widget handles double click in a special way (so the default editing action is not executed),
1688 * make sure you cancel this event, because otherwise it will be propagated to {@link CKEDITOR.editor#doubleclick}
1689 * and another feature may step in (e.g. a Link dialog window may be opened if your widget was inside a link).
1691 * @event doubleclick
1693 * @param {CKEDITOR.dom.element} data.element The double-clicked element.
1697 * An event fired when the context menu is opened for a widget.
1699 * @event contextMenu
1700 * @param data The object containing context menu options to be added
1701 * for this widget. See {@link CKEDITOR.plugins.contextMenu#addListener}.
1705 * An event fired when the widget data changed. See the {@link #setData} method and the {@link #property-data} property.
1713 * The wrapper class for editable elements inside widgets.
1715 * Do not use directly. Use {@link CKEDITOR.plugins.widget.definition#editables} or
1716 * {@link CKEDITOR.plugins.widget#initEditable}.
1718 * @class CKEDITOR.plugins.widget.nestedEditable
1719 * @extends CKEDITOR.dom.element
1721 * @param {CKEDITOR.editor} editor
1722 * @param {CKEDITOR.dom.element} element
1724 * @param {CKEDITOR.filter} [config.filter]
1726 function NestedEditable( editor
, element
, config
) {
1727 // Call the base constructor.
1728 CKEDITOR
.dom
.element
.call( this, element
.$ );
1729 this.editor
= editor
;
1731 var filter
= this.filter
= config
.filter
;
1733 // If blockless editable - always use BR mode.
1734 if ( !CKEDITOR
.dtd
[ this.getName() ].p
)
1735 this.enterMode
= this.shiftEnterMode
= CKEDITOR
.ENTER_BR
;
1737 this.enterMode
= filter
? filter
.getAllowedEnterMode( editor
.enterMode
) : editor
.enterMode
;
1738 this.shiftEnterMode
= filter
? filter
.getAllowedEnterMode( editor
.shiftEnterMode
, true ) : editor
.shiftEnterMode
;
1742 NestedEditable
.prototype = CKEDITOR
.tools
.extend( CKEDITOR
.tools
.prototypedCopy( CKEDITOR
.dom
.element
.prototype ), {
1744 * Sets the editable data. The data will be passed through the {@link CKEDITOR.editor#dataProcessor}
1745 * and the {@link CKEDITOR.editor#filter}. This ensures that the data was filtered and prepared to be
1746 * edited like the {@link CKEDITOR.editor#method-setData editor data}.
1748 * Before content is changed, all nested widgets are destroyed. Afterwards, after new content is loaded,
1749 * all nested widgets are initialized.
1751 * @param {String} data
1753 setData: function( data
) {
1754 // For performance reasons don't call destroyAll when initializing a nested editable,
1755 // because there are no widgets inside.
1756 if ( !this._
.initialSetData
) {
1757 // Destroy all nested widgets before setting data.
1758 this.editor
.widgets
.destroyAll( false, this );
1760 this._
.initialSetData
= false;
1762 data
= this.editor
.dataProcessor
.toHtml( data
, {
1763 context: this.getName(),
1764 filter: this.filter
,
1765 enterMode: this.enterMode
1767 this.setHtml( data
);
1769 this.editor
.widgets
.initOnAll( this );
1773 * Gets the editable data. Like {@link #setData}, this method will process and filter the data.
1777 getData: function() {
1778 return this.editor
.dataProcessor
.toDataFormat( this.getHtml(), {
1779 context: this.getName(),
1780 filter: this.filter
,
1781 enterMode: this.enterMode
1787 * The editor instance.
1790 * @property {CKEDITOR.editor} editor
1794 * The filter instance if allowed content rules were defined.
1797 * @property {CKEDITOR.filter} filter
1801 * The enter mode active in this editable.
1802 * It is determined from editable's name (whether it is a blockless editable),
1803 * its allowed content rules (if defined) and the default editor's mode.
1806 * @property {Number} enterMode
1810 * The shift enter move active in this editable.
1813 * @property {Number} shiftEnterMode
1818 // REPOSITORY helpers -----------------------------------------------------
1821 function addWidgetButtons( editor
) {
1822 var widgets
= editor
.widgets
.registered
,
1827 for ( widgetName
in widgets
) {
1828 widget
= widgets
[ widgetName
];
1830 // Create button if defined.
1831 widgetButton
= widget
.button
;
1832 if ( widgetButton
&& editor
.ui
.addButton
) {
1833 editor
.ui
.addButton( CKEDITOR
.tools
.capitalize( widget
.name
, true ), {
1834 label: widgetButton
,
1835 command: widget
.name
,
1836 toolbar: 'insert,10'
1842 // Create a command creating and editing widget.
1845 // @param {CKEDITOR.plugins.widget.definition} widgetDef
1846 function addWidgetCommand( editor
, widgetDef
) {
1847 editor
.addCommand( widgetDef
.name
, {
1848 exec: function( editor
, commandData
) {
1849 var focused
= editor
.widgets
.focused
;
1850 // If a widget of the same type is focused, start editing.
1851 if ( focused
&& focused
.name
== widgetDef
.name
)
1854 // ... use insert method is was defined.
1855 else if ( widgetDef
.insert
)
1857 // ... or create a brand-new widget from template.
1858 else if ( widgetDef
.template
) {
1859 var defaults
= typeof widgetDef
.defaults
== 'function' ? widgetDef
.defaults() : widgetDef
.defaults
,
1860 element
= CKEDITOR
.dom
.element
.createFromHtml( widgetDef
.template
.output( defaults
) ),
1862 wrapper
= editor
.widgets
.wrapElement( element
, widgetDef
.name
),
1863 temp
= new CKEDITOR
.dom
.documentFragment( wrapper
.getDocument() );
1865 // Append wrapper to a temporary document. This will unify the environment
1866 // in which #data listeners work when creating and editing widget.
1867 temp
.append( wrapper
);
1868 instance
= editor
.widgets
.initOn( element
, widgetDef
, commandData
&& commandData
.startupData
);
1870 // Instance could be destroyed during initialization.
1871 // In this case finalize creation if some new widget
1872 // was left in temporary document fragment.
1878 // Listen on edit to finalize widget insertion.
1880 // * If dialog was set, then insert widget after dialog was successfully saved or destroy this
1881 // temporary instance.
1882 // * If dialog wasn't set and edit wasn't canceled, insert widget.
1883 var editListener
= instance
.once( 'edit', function( evt
) {
1884 if ( evt
.data
.dialog
) {
1885 instance
.once( 'dialog', function( evt
) {
1886 var dialog
= evt
.data
,
1890 // Finalize creation AFTER (20) new data was set.
1891 okListener
= dialog
.once( 'ok', finalizeCreation
, null, null, 20 );
1893 cancelListener
= dialog
.once( 'cancel', function( evt
) {
1894 if ( !( evt
.data
&& evt
.data
.hide
=== false ) ) {
1895 editor
.widgets
.destroy( instance
, true );
1899 dialog
.once( 'hide', function() {
1900 okListener
.removeListener();
1901 cancelListener
.removeListener();
1905 // Dialog hasn't been set, so insert widget now.
1908 }, null, null, 999 );
1912 // Remove listener in case someone canceled it before this
1913 // listener was executed.
1914 editListener
.removeListener();
1917 function finalizeCreation() {
1918 editor
.widgets
.finalizeCreation( temp
);
1922 allowedContent: widgetDef
.allowedContent
,
1923 requiredContent: widgetDef
.requiredContent
,
1924 contentForms: widgetDef
.contentForms
,
1925 contentTransformations: widgetDef
.contentTransformations
1929 function addWidgetProcessors( widgetsRepo
, widgetDef
) {
1930 var upcast
= widgetDef
.upcast
,
1932 priority
= widgetDef
.upcastPriority
|| 10;
1937 // Multiple upcasts defined in string.
1938 if ( typeof upcast
== 'string' ) {
1939 upcasts
= upcast
.split( ',' );
1940 while ( upcasts
.length
) {
1941 addUpcast( widgetDef
.upcasts
[ upcasts
.pop() ], widgetDef
.name
, priority
);
1944 // Single rule which is automatically activated.
1946 addUpcast( upcast
, widgetDef
.name
, priority
);
1949 function addUpcast( upcast
, name
, priority
) {
1950 // Find index of the first higher (in terms of value) priority upcast.
1951 var index
= CKEDITOR
.tools
.getIndex( widgetsRepo
._
.upcasts
, function( element
) {
1952 return element
[ 2 ] > priority
;
1954 // Add at the end if it is the highest priority so far.
1956 index
= widgetsRepo
._
.upcasts
.length
;
1959 widgetsRepo
._
.upcasts
.splice( index
, 0, [ upcast
, name
, priority
] );
1963 function blurWidget( widgetsRepo
, widget
) {
1964 widgetsRepo
.focused
= null;
1966 if ( widget
.isInited() ) {
1967 var isDirty
= widget
.editor
.checkDirty();
1969 // Widget could be destroyed in the meantime - e.g. data could be set.
1970 widgetsRepo
.fire( 'widgetBlurred', { widget: widget
} );
1971 widget
.setFocused( false );
1973 !isDirty
&& widget
.editor
.resetDirty();
1977 function checkWidgets( evt
) {
1978 var options
= evt
.data
;
1980 if ( this.editor
.mode
!= 'wysiwyg' )
1983 var editable
= this.editor
.editable(),
1984 instances
= this.instances
,
1985 newInstances
, i
, count
, wrapper
, notYetInitialized
;
1990 // Remove widgets which have no corresponding elements in DOM.
1991 for ( i
in instances
) {
1992 // #13410 Remove widgets that are ready. This prevents from destroying widgets that are during loading process.
1993 if ( instances
[ i
].isReady() && !editable
.contains( instances
[ i
].wrapper
) )
1994 this.destroy( instances
[ i
], true );
1997 // Init on all (new) if initOnlyNew option was passed.
1998 if ( options
&& options
.initOnlyNew
)
1999 newInstances
= this.initOnAll();
2001 var wrappers
= editable
.find( '.cke_widget_wrapper' );
2004 // Create widgets on existing wrappers if they do not exists.
2005 for ( i
= 0, count
= wrappers
.count(); i
< count
; i
++ ) {
2006 wrapper
= wrappers
.getItem( i
);
2007 notYetInitialized
= !this.getByElement( wrapper
, true );
2010 // * there's no instance for this widget
2011 // * wrapper is not inside some temporary element like copybin (#11088)
2012 // * it was a nested widget's wrapper which has been detached from DOM,
2013 // when nested editable has been initialized (it overwrites its innerHTML
2014 // and initializes nested widgets).
2015 if ( notYetInitialized
&& !findParent( wrapper
, isDomTemp
) && editable
.contains( wrapper
) ) {
2016 // Add cke_widget_new class because otherwise
2017 // widget will not be created on such wrapper.
2018 wrapper
.addClass( 'cke_widget_new' );
2019 newInstances
.push( this.initOn( wrapper
.getFirst( Widget
.isDomWidgetElement
) ) );
2024 // If only single widget was initialized and focusInited was passed, focus it.
2025 if ( options
&& options
.focusInited
&& newInstances
.length
== 1 )
2026 newInstances
[ 0 ].focus();
2029 // Unwraps widget element and clean up element.
2031 // This function is used to clean up pasted widgets.
2032 // It should have similar result to widget#destroy plus
2033 // some additional adjustments, specific for pasting.
2035 // @param {CKEDITOR.htmlParser.element} el
2036 function cleanUpWidgetElement( el
) {
2037 var parent
= el
.parent
;
2038 if ( parent
.type
== CKEDITOR
.NODE_ELEMENT
&& parent
.attributes
[ 'data-cke-widget-wrapper' ] )
2039 parent
.replaceWith( el
);
2042 // Similar to cleanUpWidgetElement, but works on DOM and finds
2043 // widget elements by its own.
2045 // Unlike cleanUpWidgetElement it will wrap element back.
2047 // @param {CKEDITOR.dom.element} container
2048 function cleanUpAllWidgetElements( widgetsRepo
, container
) {
2049 var wrappers
= container
.find( '.cke_widget_wrapper' ),
2052 l
= wrappers
.count();
2054 for ( ; i
< l
; ++i
) {
2055 wrapper
= wrappers
.getItem( i
);
2056 element
= wrapper
.getFirst( Widget
.isDomWidgetElement
);
2057 // If wrapper contains widget element - unwrap it and wrap again.
2058 if ( element
.type
== CKEDITOR
.NODE_ELEMENT
&& element
.data( 'widget' ) ) {
2059 element
.replace( wrapper
);
2060 widgetsRepo
.wrapElement( element
);
2062 // Otherwise - something is wrong... clean this up.
2068 // Creates {@link CKEDITOR.filter} instance for given widget, editable and rules.
2070 // Once filter for widget-editable pair is created it is cached, so the same instance
2071 // will be returned when method is executed again.
2073 // @param {String} widgetName
2074 // @param {String} editableName
2075 // @param {CKEDITOR.plugins.widget.nestedEditableDefinition} editableDefinition The nested editable definition.
2076 // @returns {CKEDITOR.filter} Filter instance or `null` if rules are not defined.
2077 // @context CKEDITOR.plugins.widget.repository
2078 function createEditableFilter( widgetName
, editableName
, editableDefinition
) {
2079 if ( !editableDefinition
.allowedContent
)
2082 var editables
= this._
.filters
[ widgetName
];
2085 this._
.filters
[ widgetName
] = editables
= {};
2087 var filter
= editables
[ editableName
];
2090 editables
[ editableName
] = filter
= new CKEDITOR
.filter( editableDefinition
.allowedContent
);
2095 // Creates an iterator function which when executed on all
2096 // elements in DOM tree will gather elements that should be wrapped
2097 // and initialized as widgets.
2098 function createUpcastIterator( widgetsRepo
) {
2099 var toBeWrapped
= [],
2100 upcasts
= widgetsRepo
._
.upcasts
,
2101 upcastCallbacks
= widgetsRepo
._
.upcastCallbacks
;
2104 toBeWrapped: toBeWrapped
,
2106 iterator: function( element
) {
2107 var upcast
, upcasted
,
2111 upcastCallbacksLength
;
2113 // Wrapper found - find widget element, add it to be
2114 // cleaned up (unwrapped) and wrapped and stop iterating in this branch.
2115 if ( 'data-cke-widget-wrapper' in element
.attributes
) {
2116 element
= element
.getFirst( Widget
.isParserWidgetElement
);
2119 toBeWrapped
.push( [ element
] );
2121 // Do not iterate over descendants.
2124 // Widget element found - add it to be cleaned up (just in case)
2125 // and wrapped and stop iterating in this branch.
2126 else if ( 'data-widget' in element
.attributes
) {
2127 toBeWrapped
.push( [ element
] );
2129 // Do not iterate over descendants.
2132 else if ( ( upcastsLength
= upcasts
.length
) ) {
2133 // Ignore elements with data-cke-widget-upcasted to avoid multiple upcasts (#11533).
2134 // Do not iterate over descendants.
2135 if ( element
.attributes
[ 'data-cke-widget-upcasted' ] )
2138 // Check element with upcast callbacks first.
2139 // If any of them return false abort upcasting.
2140 for ( i
= 0, upcastCallbacksLength
= upcastCallbacks
.length
; i
< upcastCallbacksLength
; ++i
) {
2141 if ( upcastCallbacks
[ i
]( element
) === false )
2143 // Return nothing in order to continue iterating over ascendants.
2144 // See http://dev.ckeditor.com/ticket/11186#comment:6
2147 for ( i
= 0; i
< upcastsLength
; ++i
) {
2148 upcast
= upcasts
[ i
];
2151 if ( ( upcasted
= upcast
[ 0 ]( element
, data
) ) ) {
2152 // If upcast function returned element, upcast this one.
2153 // It can be e.g. a new element wrapping the original one.
2154 if ( upcasted
instanceof CKEDITOR
.htmlParser
.element
)
2157 // Set initial data attr with data from upcast method.
2158 element
.attributes
[ 'data-cke-widget-data' ] = encodeURIComponent( JSON
.stringify( data
) );
2159 element
.attributes
[ 'data-cke-widget-upcasted' ] = 1;
2161 toBeWrapped
.push( [ element
, upcast
[ 1 ] ] );
2163 // Do not iterate over descendants.
2172 // Finds a first parent that matches query.
2174 // @param {CKEDITOR.dom.element} element
2175 // @param {Function} query
2176 function findParent( element
, query
) {
2177 var parent
= element
;
2179 while ( ( parent
= parent
.getParent() ) ) {
2180 if ( query( parent
) )
2186 function getWrapperAttributes( inlineWidget
) {
2188 // tabindex="-1" means that it can receive focus by code.
2190 contenteditable: 'false',
2191 'data-cke-widget-wrapper': 1,
2192 'data-cke-filter': 'off',
2193 // Class cke_widget_new marks widgets which haven't been initialized yet.
2194 'class': 'cke_widget_wrapper cke_widget_new cke_widget_' +
2195 ( inlineWidget
? 'inline' : 'block' )
2199 // Inserts element at given index.
2200 // It will check DTD and split ancestor elements up to the first
2201 // that can contain this element.
2203 // @param {CKEDITOR.htmlParser.element} parent
2204 // @param {Number} index
2205 // @param {CKEDITOR.htmlParser.element} element
2206 function insertElement( parent
, index
, element
) {
2207 // Do not split doc fragment...
2208 if ( parent
.type
== CKEDITOR
.NODE_ELEMENT
) {
2209 var parentAllows
= CKEDITOR
.dtd
[ parent
.name
];
2210 // Parent element is known (included in DTD) and cannot contain
2212 if ( parentAllows
&& !parentAllows
[ element
.name
] ) {
2213 var parent2
= parent
.split( index
),
2214 parentParent
= parent
.parent
;
2216 // Element will now be inserted at right parent's index.
2217 index
= parent2
.getIndex();
2219 // If left part of split is empty - remove it.
2220 if ( !parent
.children
.length
) {
2225 // If right part of split is empty - remove it.
2226 if ( !parent2
.children
.length
)
2229 // Try inserting as grandpas' children.
2230 return insertElement( parentParent
, index
, element
);
2234 // Finally we can add this element.
2235 parent
.add( element
, index
);
2238 // Checks whether for the given widget definition and element widget should be created in inline or block mode.
2240 // See also: {@link CKEDITOR.plugins.widget.definition#inline} and {@link CKEDITOR.plugins.widget#element}.
2242 // @param {CKEDITOR.plugins.widget.definition} widgetDef The widget definition.
2243 // @param {String} elementName The name of the widget element.
2244 // @returns {Boolean}
2245 function isWidgetInline( widgetDef
, elementName
) {
2246 return typeof widgetDef
.inline
== 'boolean' ? widgetDef
.inline : !!CKEDITOR
.dtd
.$inline
[ elementName
];
2249 // @param {CKEDITOR.dom.element}
2250 // @returns {Boolean}
2251 function isDomTemp( element
) {
2252 return element
.hasAttribute( 'data-cke-temp' );
2255 function onEditableKey( widget
, keyCode
) {
2256 var focusedEditable
= widget
.focusedEditable
,
2260 if ( keyCode
== CKEDITOR
.CTRL
+ 65 ) {
2261 var bogus
= focusedEditable
.getBogus();
2263 range
= widget
.editor
.createRange();
2264 range
.selectNodeContents( focusedEditable
);
2265 // Exclude bogus if exists.
2267 range
.setEndAt( bogus
, CKEDITOR
.POSITION_BEFORE_START
);
2270 // Cancel event - block default.
2273 // DEL or BACKSPACE.
2274 else if ( keyCode
== 8 || keyCode
== 46 ) {
2275 var ranges
= widget
.editor
.getSelection().getRanges();
2277 range
= ranges
[ 0 ];
2279 // Block del or backspace if at editable's boundary.
2280 return !( ranges
.length
== 1 && range
.collapsed
&&
2281 range
.checkBoundaryOfElement( focusedEditable
, CKEDITOR
[ keyCode
== 8 ? 'START' : 'END' ] ) );
2285 function setFocusedEditable( widgetsRepo
, widget
, editableElement
, offline
) {
2286 var editor
= widgetsRepo
.editor
;
2288 editor
.fire( 'lockSnapshot' );
2290 if ( editableElement
) {
2291 var editableName
= editableElement
.data( 'cke-widget-editable' ),
2292 editableInstance
= widget
.editables
[ editableName
];
2294 widgetsRepo
.widgetHoldingFocusedEditable
= widget
;
2295 widget
.focusedEditable
= editableInstance
;
2296 editableElement
.addClass( 'cke_widget_editable_focused' );
2298 if ( editableInstance
.filter
)
2299 editor
.setActiveFilter( editableInstance
.filter
);
2300 editor
.setActiveEnterMode( editableInstance
.enterMode
, editableInstance
.shiftEnterMode
);
2303 widget
.focusedEditable
.removeClass( 'cke_widget_editable_focused' );
2305 widget
.focusedEditable
= null;
2306 widgetsRepo
.widgetHoldingFocusedEditable
= null;
2307 editor
.setActiveFilter( null );
2308 editor
.setActiveEnterMode( null, null );
2311 editor
.fire( 'unlockSnapshot' );
2314 function setupContextMenu( editor
) {
2315 if ( !editor
.contextMenu
)
2318 editor
.contextMenu
.addListener( function( element
) {
2319 var widget
= editor
.widgets
.getByElement( element
, true );
2322 return widget
.fire( 'contextMenu', {} );
2326 // And now we've got two problems - original problem and RegExp.
2328 // * FF tends to copy all blocks up to the copybin container.
2329 // * IE tends to copy only the copybin, without its container.
2330 // * We use spans on IE and blockless editors, but divs in other cases.
2331 var pasteReplaceRegex
= new RegExp(
2333 '(?:<(?:div|span)(?: data-cke-temp="1")?(?: id="cke_copybin")?(?: data-cke-temp="1")?>)?' +
2334 '(?:<(?:div|span)(?: style="[^"]+")?>)?' +
2335 '<span [^>]*data-cke-copybin-start="1"[^>]*>.?</span>([\\s\\S]+)<span [^>]*data-cke-copybin-end="1"[^>]*>.?</span>' +
2336 '(?:</(?:div|span)>)?' +
2337 '(?:</(?:div|span)>)?' +
2339 // IE8 prefers uppercase when browsers stick to lowercase HTML (#13460).
2343 function pasteReplaceFn( match
, wrapperHtml
) {
2344 // Avoid polluting pasted data with any whitspaces,
2345 // what's going to break check whether only one widget was pasted.
2346 return CKEDITOR
.tools
.trim( wrapperHtml
);
2349 function setupDragAndDrop( widgetsRepo
) {
2350 var editor
= widgetsRepo
.editor
,
2351 lineutils
= CKEDITOR
.plugins
.lineutils
;
2353 // These listeners handle inline and block widgets drag and drop.
2354 // The only thing we need to do to make block widgets custom drag and drop functionality
2355 // is to fire those events with the right properties (like the target which must be the drag handle).
2356 editor
.on( 'dragstart', function( evt
) {
2357 var target
= evt
.data
.target
;
2359 if ( Widget
.isDomDragHandler( target
) ) {
2360 var widget
= widgetsRepo
.getByElement( target
);
2362 evt
.data
.dataTransfer
.setData( 'cke/widget-id', widget
.id
);
2367 // and widget need to be focused on drag start (#12172#comment:10).
2372 editor
.on( 'drop', function( evt
) {
2373 var dataTransfer
= evt
.data
.dataTransfer
,
2374 id
= dataTransfer
.getData( 'cke/widget-id' ),
2375 transferType
= dataTransfer
.getTransferType( editor
),
2376 dragRange
= editor
.createRange(),
2379 // Disable cross-editor drag & drop for widgets - #13599.
2380 if ( id
!== '' && transferType
=== CKEDITOR
.DATA_TRANSFER_CROSS_EDITORS
) {
2385 if ( id
=== '' || transferType
!= CKEDITOR
.DATA_TRANSFER_INTERNAL
) {
2389 sourceWidget
= widgetsRepo
.instances
[ id
];
2390 if ( !sourceWidget
) {
2394 dragRange
.setStartBefore( sourceWidget
.wrapper
);
2395 dragRange
.setEndAfter( sourceWidget
.wrapper
);
2396 evt
.data
.dragRange
= dragRange
;
2398 // [IE8-9] Reset state of the clipboard#fixSplitNodesAfterDrop fix because by setting evt.data.dragRange
2399 // (see above) after drop happened we do not need it. That fix is needed only if dragRange was created
2400 // before drop (before text node was split).
2401 delete CKEDITOR
.plugins
.clipboard
.dragStartContainerChildCount
;
2402 delete CKEDITOR
.plugins
.clipboard
.dragEndContainerChildCount
;
2404 evt
.data
.dataTransfer
.setData( 'text/html', editor
.editable().getHtmlFromRange( dragRange
).getHtml() );
2405 editor
.widgets
.destroy( sourceWidget
, true );
2408 editor
.on( 'contentDom', function() {
2409 var editable
= editor
.editable();
2411 // Register Lineutils's utilities as properties of repo.
2412 CKEDITOR
.tools
.extend( widgetsRepo
, {
2413 finder: new lineutils
.finder( editor
, {
2415 // Element is block but not list item and not in nested editable.
2416 'default': function( el
) {
2417 if ( el
.is( CKEDITOR
.dtd
.$listItem
) )
2420 if ( !el
.is( CKEDITOR
.dtd
.$block
) )
2423 // Allow drop line inside, but never before or after nested editable (#12006).
2424 if ( Widget
.isDomNestedEditable( el
) )
2427 // Do not allow droping inside the widget being dragged (#13397).
2428 if ( widgetsRepo
._
.draggedWidget
.wrapper
.contains( el
) ) {
2432 // If element is nested editable, make sure widget can be dropped there (#12006).
2433 var nestedEditable
= Widget
.getNestedEditable( editable
, el
);
2434 if ( nestedEditable
) {
2435 var draggedWidget
= widgetsRepo
._
.draggedWidget
;
2437 // Don't let the widget to be dropped into its own nested editable.
2438 if ( widgetsRepo
.getByElement( nestedEditable
) == draggedWidget
)
2441 var filter
= CKEDITOR
.filter
.instances
[ nestedEditable
.data( 'cke-filter' ) ],
2442 draggedRequiredContent
= draggedWidget
.requiredContent
;
2444 // There will be no relation if the filter of nested editable does not allow
2445 // requiredContent of dragged widget.
2446 if ( filter
&& draggedRequiredContent
&& !filter
.check( draggedRequiredContent
) )
2450 return CKEDITOR
.LINEUTILS_BEFORE
| CKEDITOR
.LINEUTILS_AFTER
;
2454 locator: new lineutils
.locator( editor
),
2455 liner: new lineutils
.liner( editor
, {
2457 cursor: 'move !important',
2458 'border-top-color': '#666'
2461 'border-left-color': '#666'
2464 'border-right-color': '#666'
2471 // Setup mouse observer which will trigger:
2472 // * widget focus on widget click,
2473 // * widget#doubleclick forwarded from editor#doubleclick.
2474 function setupMouseObserver( widgetsRepo
) {
2475 var editor
= widgetsRepo
.editor
;
2477 editor
.on( 'contentDom', function() {
2478 var editable
= editor
.editable(),
2479 evtRoot
= editable
.isInline() ? editable : editor
.document
,
2481 mouseDownOnDragHandler
;
2483 editable
.attachListener( evtRoot
, 'mousedown', function( evt
) {
2484 var target
= evt
.data
.getTarget();
2486 // #10887 Clicking scrollbar in IE8 will invoke event with empty target object.
2490 widget
= widgetsRepo
.getByElement( target
);
2491 mouseDownOnDragHandler
= 0; // Reset.
2493 // Widget was clicked, but not editable nested in it.
2495 // Ignore mousedown on drag and drop handler if the widget is inline.
2496 // Block widgets are handled by Lineutils.
2497 if ( widget
.inline
&& target
.type
== CKEDITOR
.NODE_ELEMENT
&& target
.hasAttribute( 'data-cke-widget-drag-handler' ) ) {
2498 mouseDownOnDragHandler
= 1;
2500 // When drag handler is pressed we have to clear current selection if it wasn't already on this widget.
2501 // Otherwise, the selection may be in a fillingChar, which prevents dragging a widget. (#13284, see comment 8 and 9.)
2502 if ( widgetsRepo
.focused
!= widget
)
2503 editor
.getSelection().removeAllRanges();
2508 if ( !Widget
.getNestedEditable( widget
.wrapper
, target
) ) {
2509 evt
.data
.preventDefault();
2510 if ( !CKEDITOR
.env
.ie
)
2513 // Reset widget so mouseup listener is not confused.
2519 // Focus widget on mouseup if mousedown was fired on drag handler.
2520 // Note: mouseup won't be fired at all if widget was dragged and dropped, so
2521 // this code will be executed only when drag handler was clicked.
2522 editable
.attachListener( evtRoot
, 'mouseup', function() {
2523 // Check if widget is not destroyed (if widget is destroyed the wrapper will be null).
2524 if ( mouseDownOnDragHandler
&& widget
&& widget
.wrapper
) {
2525 mouseDownOnDragHandler
= 0;
2530 // On IE it is not enough to block mousedown. If widget wrapper (element with
2531 // contenteditable=false attribute) is clicked directly (it is a target),
2532 // then after mouseup/click IE will select that element.
2533 // It is not possible to prevent that default action,
2534 // so we force fake selection after everything happened.
2535 if ( CKEDITOR
.env
.ie
) {
2536 editable
.attachListener( evtRoot
, 'mouseup', function() {
2537 setTimeout( function() {
2538 // Check if widget is not destroyed (if widget is destroyed the wrapper will be null) and
2539 // in editable contains widget (it could be dragged and removed).
2540 if ( widget
&& widget
.wrapper
&& editable
.contains( widget
.wrapper
) ) {
2549 editor
.on( 'doubleclick', function( evt
) {
2550 var widget
= widgetsRepo
.getByElement( evt
.data
.element
);
2552 // Not in widget or in nested editable.
2553 if ( !widget
|| Widget
.getNestedEditable( widget
.wrapper
, evt
.data
.element
) )
2556 return widget
.fire( 'doubleclick', { element: evt
.data
.element
} );
2560 // Setup editor#key observer which will forward it
2561 // to focused widget.
2562 function setupKeyboardObserver( widgetsRepo
) {
2563 var editor
= widgetsRepo
.editor
;
2565 editor
.on( 'key', function( evt
) {
2566 var focused
= widgetsRepo
.focused
,
2567 widgetHoldingFocusedEditable
= widgetsRepo
.widgetHoldingFocusedEditable
,
2571 ret
= focused
.fire( 'key', { keyCode: evt
.data
.keyCode
} );
2572 else if ( widgetHoldingFocusedEditable
)
2573 ret
= onEditableKey( widgetHoldingFocusedEditable
, evt
.data
.keyCode
);
2579 // Setup copybin on native copy and cut events in order to handle copy and cut commands
2580 // if user accepted security alert on IEs.
2581 // Note: when copying or cutting using keystroke, copySingleWidget will be first executed
2582 // by the keydown listener. Conflict between two calls will be resolved by copy_bin existence check.
2583 function setupNativeCutAndCopy( widgetsRepo
) {
2584 var editor
= widgetsRepo
.editor
;
2586 editor
.on( 'contentDom', function() {
2587 var editable
= editor
.editable();
2589 editable
.attachListener( editable
, 'copy', eventListener
);
2590 editable
.attachListener( editable
, 'cut', eventListener
);
2593 function eventListener( evt
) {
2594 if ( widgetsRepo
.focused
)
2595 copySingleWidget( widgetsRepo
.focused
, evt
.name
== 'cut' );
2599 // Setup selection observer which will trigger:
2600 // * widget select & focus on selection change,
2601 // * nested editable focus (related properites and classes) on selection change,
2602 // * deselecting and blurring all widgets on data,
2603 // * blurring widget on editor blur.
2604 function setupSelectionObserver( widgetsRepo
) {
2605 var editor
= widgetsRepo
.editor
;
2607 editor
.on( 'selectionCheck', function() {
2608 widgetsRepo
.fire( 'checkSelection' );
2611 widgetsRepo
.on( 'checkSelection', widgetsRepo
.checkSelection
, widgetsRepo
);
2613 editor
.on( 'selectionChange', function( evt
) {
2614 var nestedEditable
= Widget
.getNestedEditable( editor
.editable(), evt
.data
.selection
.getStartElement() ),
2615 newWidget
= nestedEditable
&& widgetsRepo
.getByElement( nestedEditable
),
2616 oldWidget
= widgetsRepo
.widgetHoldingFocusedEditable
;
2619 if ( oldWidget
!== newWidget
|| !oldWidget
.focusedEditable
.equals( nestedEditable
) ) {
2620 setFocusedEditable( widgetsRepo
, oldWidget
, null );
2622 if ( newWidget
&& nestedEditable
)
2623 setFocusedEditable( widgetsRepo
, newWidget
, nestedEditable
);
2626 // It may happen that there's no widget even if editable was found -
2627 // e.g. if selection was automatically set in editable although widget wasn't initialized yet.
2628 else if ( newWidget
&& nestedEditable
) {
2629 setFocusedEditable( widgetsRepo
, newWidget
, nestedEditable
);
2633 // Invalidate old widgets early - immediately on dataReady.
2634 editor
.on( 'dataReady', function() {
2635 // Deselect and blur all widgets.
2636 stateUpdater( widgetsRepo
).commit();
2639 editor
.on( 'blur', function() {
2642 if ( ( widget
= widgetsRepo
.focused
) )
2643 blurWidget( widgetsRepo
, widget
);
2645 if ( ( widget
= widgetsRepo
.widgetHoldingFocusedEditable
) )
2646 setFocusedEditable( widgetsRepo
, widget
, null );
2650 // Set up actions like:
2651 // * processing in toHtml/toDataFormat,
2652 // * pasting handling,
2653 // * insertion handling,
2654 // * editable reload handling (setData, mode switch, undo/redo),
2655 // * DOM invalidation handling,
2656 // * widgets checks.
2657 function setupWidgetsLifecycle( widgetsRepo
) {
2658 setupWidgetsLifecycleStart( widgetsRepo
);
2659 setupWidgetsLifecycleEnd( widgetsRepo
);
2661 widgetsRepo
.on( 'checkWidgets', checkWidgets
);
2662 widgetsRepo
.editor
.on( 'contentDomInvalidated', widgetsRepo
.checkWidgets
, widgetsRepo
);
2665 function setupWidgetsLifecycleEnd( widgetsRepo
) {
2666 var editor
= widgetsRepo
.editor
,
2667 downcastingSessions
= {};
2669 // Listen before htmlDP#htmlFilter is applied to cache all widgets, because we'll
2670 // loose data-cke-* attributes.
2671 editor
.on( 'toDataFormat', function( evt
) {
2672 // To avoid conflicts between htmlDP#toDF calls done at the same time
2673 // (e.g. nestedEditable#getData called during downcasting some widget)
2674 // mark every toDataFormat event chain with the downcasting session id.
2675 var id
= CKEDITOR
.tools
.getNextNumber(),
2676 toBeDowncasted
= [];
2677 evt
.data
.downcastingSessionId
= id
;
2678 downcastingSessions
[ id
] = toBeDowncasted
;
2680 evt
.data
.dataValue
.forEach( function( element
) {
2681 var attrs
= element
.attributes
,
2682 widget
, widgetElement
;
2685 // Perform first part of downcasting (cleanup) and cache widgets,
2686 // because after applying DP's filter all data-cke-* attributes will be gone.
2687 if ( 'data-cke-widget-id' in attrs
) {
2688 widget
= widgetsRepo
.instances
[ attrs
[ 'data-cke-widget-id' ] ];
2690 widgetElement
= element
.getFirst( Widget
.isParserWidgetElement
);
2691 toBeDowncasted
.push( {
2693 element: widgetElement
,
2698 // If widget did not have data-cke-widget attribute before upcasting remove it.
2699 if ( widgetElement
.attributes
[ 'data-cke-widget-keep-attr' ] != '1' )
2700 delete widgetElement
.attributes
[ 'data-widget' ];
2704 else if ( 'data-cke-widget-editable' in attrs
) {
2705 // Save the reference to this nested editable in the closest widget to be downcasted.
2706 // Nested editables are downcasted in the successive toDataFormat to create an opportunity
2707 // for dataFilter's "excludeNestedEditable" option to do its job (that option relies on
2708 // contenteditable="true" attribute) (#11372).
2709 toBeDowncasted
[ toBeDowncasted
.length
- 1 ].editables
[ attrs
[ 'data-cke-widget-editable' ] ] = element
;
2711 // Don't check children - there won't be next wrapper or nested editable which we
2712 // should process in this session.
2715 }, CKEDITOR
.NODE_ELEMENT
, true );
2718 // Listen after dataProcessor.htmlFilter and ACF were applied
2719 // so wrappers securing widgets' contents are removed after all filtering was done.
2720 editor
.on( 'toDataFormat', function( evt
) {
2721 // Ignore some unmarked sessions.
2722 if ( !evt
.data
.downcastingSessionId
)
2725 var toBeDowncasted
= downcastingSessions
[ evt
.data
.downcastingSessionId
],
2726 toBe
, widget
, widgetElement
, retElement
, editableElement
, e
;
2728 while ( ( toBe
= toBeDowncasted
.shift() ) ) {
2729 widget
= toBe
.widget
;
2730 widgetElement
= toBe
.element
;
2731 retElement
= widget
._
.downcastFn
&& widget
._
.downcastFn
.call( widget
, widgetElement
);
2733 // Replace nested editables' content with their output data.
2734 for ( e
in toBe
.editables
) {
2735 editableElement
= toBe
.editables
[ e
];
2737 delete editableElement
.attributes
.contenteditable
;
2738 editableElement
.setHtml( widget
.editables
[ e
].getData() );
2741 // Returned element always defaults to widgetElement.
2743 retElement
= widgetElement
;
2745 toBe
.wrapper
.replaceWith( retElement
);
2747 }, null, null, 13 );
2750 editor
.on( 'contentDomUnload', function() {
2751 widgetsRepo
.destroyAll( true );
2755 function setupWidgetsLifecycleStart( widgetsRepo
) {
2756 var editor
= widgetsRepo
.editor
,
2757 processedWidgetOnly
,
2760 // Listen after ACF (so data are filtered),
2761 // but before dataProcessor.dataFilter was applied (so we can secure widgets' internals).
2762 editor
.on( 'toHtml', function( evt
) {
2763 var upcastIterator
= createUpcastIterator( widgetsRepo
),
2766 evt
.data
.dataValue
.forEach( upcastIterator
.iterator
, CKEDITOR
.NODE_ELEMENT
, true );
2768 // Clean up and wrap all queued elements.
2769 while ( ( toBeWrapped
= upcastIterator
.toBeWrapped
.pop() ) ) {
2770 cleanUpWidgetElement( toBeWrapped
[ 0 ] );
2771 widgetsRepo
.wrapElement( toBeWrapped
[ 0 ], toBeWrapped
[ 1 ] );
2774 // Used to determine whether only widget was pasted.
2775 if ( evt
.data
.protectedWhitespaces
) {
2776 // Whitespaces are protected by wrapping content with spans. Take the middle node only.
2777 processedWidgetOnly
= evt
.data
.dataValue
.children
.length
== 3 &&
2778 Widget
.isParserWidgetWrapper( evt
.data
.dataValue
.children
[ 1 ] );
2780 processedWidgetOnly
= evt
.data
.dataValue
.children
.length
== 1 &&
2781 Widget
.isParserWidgetWrapper( evt
.data
.dataValue
.children
[ 0 ] );
2785 editor
.on( 'dataReady', function() {
2786 // Clean up all widgets loaded from snapshot.
2787 if ( snapshotLoaded
)
2788 cleanUpAllWidgetElements( widgetsRepo
, editor
.editable() );
2791 // Some widgets were destroyed on contentDomUnload,
2792 // some on loadSnapshot, but that does not include
2793 // e.g. setHtml on inline editor or widgets removed just
2794 // before setting data.
2795 widgetsRepo
.destroyAll( true );
2796 widgetsRepo
.initOnAll();
2799 // Set flag so dataReady will know that additional
2800 // cleanup is needed, because snapshot containing widgets was loaded.
2801 editor
.on( 'loadSnapshot', function( evt
) {
2802 // Primitive but sufficient check which will prevent from executing
2803 // heavier cleanUpAllWidgetElements if not needed.
2804 if ( ( /data-cke-widget/ ).test( evt
.data
) )
2807 widgetsRepo
.destroyAll( true );
2810 // Handle pasted single widget.
2811 editor
.on( 'paste', function( evt
) {
2812 var data
= evt
.data
;
2814 data
.dataValue
= data
.dataValue
.replace( pasteReplaceRegex
, pasteReplaceFn
);
2816 // If drag'n'drop kind of paste into nested editable (data.range), selection is set AFTER
2817 // data is pasted, which means editor has no chance to change activeFilter's context.
2818 // As a result, pasted data is filtered with default editor's filter instead of NE's and
2819 // funny things get inserted. Changing the filter by analysis of the paste range below (#13186).
2821 // Check if pasting into nested editable.
2822 var nestedEditable
= Widget
.getNestedEditable( editor
.editable(), data
.range
.startContainer
);
2824 if ( nestedEditable
) {
2825 // Retrieve the filter from NE's data and set it active before editor.insertHtml is done
2826 // in clipboard plugin.
2827 var filter
= CKEDITOR
.filter
.instances
[ nestedEditable
.data( 'cke-filter' ) ];
2830 editor
.setActiveFilter( filter
);
2836 // Listen with high priority to check widgets after data was inserted.
2837 editor
.on( 'afterInsertHtml', function( evt
) {
2838 if ( evt
.data
.intoRange
) {
2839 widgetsRepo
.checkWidgets( { initOnlyNew: true } );
2841 editor
.fire( 'lockSnapshot' );
2842 // Init only new for performance reason.
2843 // Focus inited if only widget was processed.
2844 widgetsRepo
.checkWidgets( { initOnlyNew: true, focusInited: processedWidgetOnly
} );
2846 editor
.fire( 'unlockSnapshot' );
2851 // Helper for coordinating which widgets should be
2852 // selected/deselected and which one should be focused/blurred.
2853 function stateUpdater( widgetsRepo
) {
2854 var currentlySelected
= widgetsRepo
.selected
,
2856 toBeDeselected
= currentlySelected
.slice( 0 ),
2860 select: function( widget
) {
2861 if ( CKEDITOR
.tools
.indexOf( currentlySelected
, widget
) < 0 )
2862 toBeSelected
.push( widget
);
2864 var index
= CKEDITOR
.tools
.indexOf( toBeDeselected
, widget
);
2866 toBeDeselected
.splice( index
, 1 );
2871 focus: function( widget
) {
2876 commit: function() {
2877 var focusedChanged
= widgetsRepo
.focused
!== focused
,
2880 widgetsRepo
.editor
.fire( 'lockSnapshot' );
2882 if ( focusedChanged
&& ( widget
= widgetsRepo
.focused
) )
2883 blurWidget( widgetsRepo
, widget
);
2885 while ( ( widget
= toBeDeselected
.pop() ) ) {
2886 currentlySelected
.splice( CKEDITOR
.tools
.indexOf( currentlySelected
, widget
), 1 );
2887 // Widget could be destroyed in the meantime - e.g. data could be set.
2888 if ( widget
.isInited() ) {
2889 isDirty
= widget
.editor
.checkDirty();
2891 widget
.setSelected( false );
2893 !isDirty
&& widget
.editor
.resetDirty();
2897 if ( focusedChanged
&& focused
) {
2898 isDirty
= widgetsRepo
.editor
.checkDirty();
2900 widgetsRepo
.focused
= focused
;
2901 widgetsRepo
.fire( 'widgetFocused', { widget: focused
} );
2902 focused
.setFocused( true );
2904 !isDirty
&& widgetsRepo
.editor
.resetDirty();
2907 while ( ( widget
= toBeSelected
.pop() ) ) {
2908 currentlySelected
.push( widget
);
2909 widget
.setSelected( true );
2912 widgetsRepo
.editor
.fire( 'unlockSnapshot' );
2919 // WIDGET helpers ---------------------------------------------------------
2922 // LEFT, RIGHT, UP, DOWN, DEL, BACKSPACE - unblock default fake sel handlers.
2923 var keystrokesNotBlockedByWidget
= { 37: 1, 38: 1, 39: 1, 40: 1, 8: 1, 46: 1 };
2925 // Applies or removes style's classes from widget.
2926 // @param {CKEDITOR.style} style Custom widget style.
2927 // @param {Boolean} apply Whether to apply or remove style.
2928 function applyRemoveStyle( widget
, style
, apply
) {
2930 classes
= getStyleClasses( style
),
2931 updatedClasses
= widget
.data
.classes
|| {},
2934 // Ee... Something is wrong with this style.
2938 // Clone, because we need to break reference.
2939 updatedClasses
= CKEDITOR
.tools
.clone( updatedClasses
);
2941 while ( ( cl
= classes
.pop() ) ) {
2943 if ( !updatedClasses
[ cl
] )
2944 changed
= updatedClasses
[ cl
] = 1;
2946 if ( updatedClasses
[ cl
] ) {
2947 delete updatedClasses
[ cl
];
2953 widget
.setData( 'classes', updatedClasses
);
2956 function cancel( evt
) {
2960 function copySingleWidget( widget
, isCut
) {
2961 var editor
= widget
.editor
,
2962 doc
= editor
.document
;
2964 // We're still handling previous copy/cut.
2965 // When keystroke is used to copy/cut this will also prevent
2966 // conflict with copySingleWidget called again for native copy/cut event.
2967 if ( doc
.getById( 'cke_copybin' ) )
2970 // [IE] Use span for copybin and its container to avoid bug with expanding editable height by
2971 // absolutely positioned element.
2972 var copybinName
= ( editor
.blockless
|| CKEDITOR
.env
.ie
) ? 'span' : 'div',
2973 copybin
= doc
.createElement( copybinName
),
2974 copybinContainer
= doc
.createElement( copybinName
),
2975 // IE8 always jumps to the end of document.
2976 needsScrollHack
= CKEDITOR
.env
.ie
&& CKEDITOR
.env
.version
< 9;
2978 copybinContainer
.setAttributes( {
2980 'data-cke-temp': '1'
2983 // Position copybin element outside current viewport.
2984 copybin
.setStyles( {
2985 position: 'absolute',
2991 copybin
.setStyle( editor
.config
.contentsLangDirection
== 'ltr' ? 'left' : 'right', '-5000px' );
2993 var range
= editor
.createRange();
2994 range
.setStartBefore( widget
.wrapper
);
2995 range
.setEndAfter( widget
.wrapper
);
2998 '<span data-cke-copybin-start="1">\u200b</span>' +
2999 editor
.editable().getHtmlFromRange( range
).getHtml() +
3000 '<span data-cke-copybin-end="1">\u200b</span>' );
3002 // Save snapshot with the current state.
3003 editor
.fire( 'saveSnapshot' );
3006 editor
.fire( 'lockSnapshot' );
3008 copybinContainer
.append( copybin
);
3009 editor
.editable().append( copybinContainer
);
3011 var listener1
= editor
.on( 'selectionChange', cancel
, null, null, 0 ),
3012 listener2
= widget
.repository
.on( 'checkSelection', cancel
, null, null, 0 );
3014 if ( needsScrollHack
) {
3015 var docElement
= doc
.getDocumentElement().$,
3016 scrollTop
= docElement
.scrollTop
;
3019 // Once the clone of the widget is inside of copybin, select
3020 // the entire contents. This selection will be copied by the
3021 // native browser's clipboard system.
3022 range
= editor
.createRange();
3023 range
.selectNodeContents( copybin
);
3026 if ( needsScrollHack
)
3027 docElement
.scrollTop
= scrollTop
;
3029 setTimeout( function() {
3030 // [IE] Focus widget before removing copybin to avoid scroll jump.
3034 copybinContainer
.remove();
3036 listener1
.removeListener();
3037 listener2
.removeListener();
3039 editor
.fire( 'unlockSnapshot' );
3042 widget
.repository
.del( widget
);
3043 editor
.fire( 'saveSnapshot' );
3045 }, 100 ); // Use 100ms, so Chrome (@Mac) will be able to grab the content.
3048 // Extracts classes array from style instance.
3049 function getStyleClasses( style
) {
3050 var attrs
= style
.getDefinition().attributes
,
3051 classes
= attrs
&& attrs
[ 'class' ];
3053 return classes
? classes
.split( /\s+/ ) : null;
3056 // [IE] Force keeping focus because IE sometimes forgets to fire focus on main editable
3057 // when blurring nested editable.
3059 function onEditableBlur() {
3060 var active
= CKEDITOR
.document
.getActive(),
3061 editor
= this.editor
,
3062 editable
= editor
.editable();
3064 // If focus stays within editor override blur and set currentActive because it should be
3065 // automatically changed to editable on editable#focus but it is not fired.
3066 if ( ( editable
.isInline() ? editable : editor
.document
.getWindow().getFrame() ).equals( active
) )
3067 editor
.focusManager
.focus( editable
);
3070 // Force selectionChange when editable was focused.
3071 // Similar to hack in selection.js#~620.
3073 function onEditableFocus() {
3074 // Gecko does not support 'DOMFocusIn' event on which we unlock selection
3075 // in selection.js to prevent selection locking when entering nested editables.
3076 if ( CKEDITOR
.env
.gecko
)
3077 this.editor
.unlockSelection();
3079 // We don't need to force selectionCheck on Webkit, because on Webkit
3080 // we do that on DOMFocusIn in selection.js.
3081 if ( !CKEDITOR
.env
.webkit
) {
3082 this.editor
.forceNextSelectionCheck();
3083 this.editor
.selectionChange( 1 );
3087 // Setup listener on widget#data which will update (remove/add) classes
3088 // by comparing newly set classes with the old ones.
3089 function setupDataClassesListener( widget
) {
3090 // Note: previousClasses and newClasses may be null!
3091 // Tip: for ( cl in null ) is correct.
3092 var previousClasses
= null;
3094 widget
.on( 'data', function() {
3095 var newClasses
= this.data
.classes
,
3098 // When setting new classes one need to remember
3099 // that he must break reference.
3100 if ( previousClasses
== newClasses
)
3103 for ( cl
in previousClasses
) {
3104 // Avoid removing and adding classes again.
3105 if ( !( newClasses
&& newClasses
[ cl
] ) )
3106 this.removeClass( cl
);
3108 for ( cl
in newClasses
)
3109 this.addClass( cl
);
3111 previousClasses
= newClasses
;
3115 function setupDragHandler( widget
) {
3116 if ( !widget
.draggable
)
3119 var editor
= widget
.editor
,
3120 // Use getLast to find wrapper's direct descendant (#12022).
3121 container
= widget
.wrapper
.getLast( Widget
.isDomDragHandlerContainer
),
3124 // Reuse drag handler if already exists (#11281).
3126 img
= container
.findOne( 'img' );
3128 container
= new CKEDITOR
.dom
.element( 'span', editor
.document
);
3129 container
.setAttributes( {
3130 'class': 'cke_reset cke_widget_drag_handler_container',
3131 // Split background and background-image for IE8 which will break on rgba().
3132 style: 'background:rgba(220,220,220,0.5);background-image:url(' + editor
.plugins
.widget
.path
+ 'images/handle.png)'
3135 img
= new CKEDITOR
.dom
.element( 'img', editor
.document
);
3136 img
.setAttributes( {
3137 'class': 'cke_reset cke_widget_drag_handler',
3138 'data-cke-widget-drag-handler': '1',
3139 src: CKEDITOR
.tools
.transparentImageData
,
3140 width: DRAG_HANDLER_SIZE
,
3141 title: editor
.lang
.widget
.move,
3142 height: DRAG_HANDLER_SIZE
3144 widget
.inline
&& img
.setAttribute( 'draggable', 'true' );
3146 container
.append( img
);
3147 widget
.wrapper
.append( container
);
3150 // Preventing page reload when dropped content on widget wrapper (#13015).
3151 // Widget is not editable so by default drop on it isn't allowed what means that
3152 // browser handles it (there's no editable#drop event). If there's no drop event we cannot block
3153 // the drop, so page is reloaded. This listener enables drop on widget wrappers.
3154 widget
.wrapper
.on( 'dragover', function( evt
) {
3155 evt
.data
.preventDefault();
3158 widget
.wrapper
.on( 'mouseenter', widget
.updateDragHandlerPosition
, widget
);
3159 setTimeout( function() {
3160 widget
.on( 'data', widget
.updateDragHandlerPosition
, widget
);
3163 if ( !widget
.inline
) {
3164 img
.on( 'mousedown', onBlockWidgetDrag
, widget
);
3166 // On IE8 'dragstart' is propagated to editable, so editor#dragstart is fired twice on block widgets.
3167 if ( CKEDITOR
.env
.ie
&& CKEDITOR
.env
.version
< 9 ) {
3168 img
.on( 'dragstart', function( evt
) {
3169 evt
.data
.preventDefault( true );
3174 widget
.dragHandlerContainer
= container
;
3177 function onBlockWidgetDrag( evt
) {
3178 var finder
= this.repository
.finder
,
3179 locator
= this.repository
.locator
,
3180 liner
= this.repository
.liner
,
3181 editor
= this.editor
,
3182 editable
= editor
.editable(),
3186 // Mark dragged widget for repository#finder.
3187 this.repository
._
.draggedWidget
= this;
3189 // Harvest all possible relations and display some closest.
3190 var relations
= finder
.greedySearch(),
3192 buffer
= CKEDITOR
.tools
.eventsBuffer( 50, function() {
3193 locations
= locator
.locate( relations
);
3195 // There's only a single line displayed for D&D.
3196 sorted
= locator
.sort( y
, 1 );
3198 if ( sorted
.length
) {
3199 liner
.prepare( relations
, locations
);
3200 liner
.placeLine( sorted
[ 0 ] );
3207 // Let's have the "dragging cursor" over entire editable.
3208 editable
.addClass( 'cke_widget_dragging' );
3210 // Cache mouse position so it is re-used in events buffer.
3211 listeners
.push( editable
.on( 'mousemove', function( evt
) {
3212 y
= evt
.data
.$.clientY
;
3216 // Fire drag start as it happens during the native D&D.
3217 editor
.fire( 'dragstart', { target: evt
.sender
} );
3219 function onMouseUp() {
3224 // Stop observing events.
3225 while ( ( l
= listeners
.pop() ) )
3228 onBlockWidgetDrop
.call( this, sorted
, evt
.sender
);
3231 // Mouseup means "drop". This is when the widget is being detached
3232 // from DOM and placed at range determined by the line (location).
3233 listeners
.push( editor
.document
.once( 'mouseup', onMouseUp
, this ) );
3235 // Prevent calling 'onBlockWidgetDrop' twice in the inline editor.
3236 // `removeListener` does not work if it is called at the same time event is fired.
3237 if ( !editable
.isInline() ) {
3238 // Mouseup may occur when user hovers the line, which belongs to
3239 // the outer document. This is, of course, a valid listener too.
3240 listeners
.push( CKEDITOR
.document
.once( 'mouseup', onMouseUp
, this ) );
3244 function onBlockWidgetDrop( sorted
, dragTarget
) {
3245 var finder
= this.repository
.finder
,
3246 liner
= this.repository
.liner
,
3247 editor
= this.editor
,
3248 editable
= this.editor
.editable();
3250 if ( !CKEDITOR
.tools
.isEmpty( liner
.visible
) ) {
3251 // Retrieve range for the closest location.
3252 var dropRange
= finder
.getRange( sorted
[ 0 ] );
3254 // Focus widget (it could lost focus after mousedown+mouseup)
3255 // and save this state as the one where we want to be taken back when undoing.
3258 // Drag range will be set in the drop listener.
3259 editor
.fire( 'drop', {
3260 dropRange: dropRange
,
3261 target: dropRange
.startContainer
3265 // Clean-up custom cursor for editable.
3266 editable
.removeClass( 'cke_widget_dragging' );
3268 // Clean-up all remaining lines.
3269 liner
.hideVisible();
3271 // Clean-up drag & drop.
3272 editor
.fire( 'dragend', { target: dragTarget
} );
3275 function setupEditables( widget
) {
3278 definedEditables
= widget
.editables
;
3280 widget
.editables
= {};
3282 if ( !widget
.editables
)
3285 for ( editableName
in definedEditables
) {
3286 editableDef
= definedEditables
[ editableName
];
3287 widget
.initEditable( editableName
, typeof editableDef
== 'string' ? { selector: editableDef
} : editableDef
);
3291 function setupMask( widget
) {
3295 // Reuse mask if already exists (#11281).
3296 var img
= widget
.wrapper
.findOne( '.cke_widget_mask' );
3299 img
= new CKEDITOR
.dom
.element( 'img', widget
.editor
.document
);
3300 img
.setAttributes( {
3301 src: CKEDITOR
.tools
.transparentImageData
,
3302 'class': 'cke_reset cke_widget_mask'
3304 widget
.wrapper
.append( img
);
3310 // Replace parts object containing:
3311 // partName => selector pairs
3313 // partName => element pairs
3314 function setupParts( widget
) {
3315 if ( widget
.parts
) {
3319 for ( partName
in widget
.parts
) {
3320 el
= widget
.wrapper
.findOne( widget
.parts
[ partName
] );
3321 parts
[ partName
] = el
;
3323 widget
.parts
= parts
;
3327 function setupWidget( widget
, widgetDef
) {
3328 setupWrapper( widget
);
3329 setupParts( widget
);
3330 setupEditables( widget
);
3331 setupMask( widget
);
3332 setupDragHandler( widget
);
3333 setupDataClassesListener( widget
);
3335 // #11145: [IE8] Non-editable content of widget is draggable.
3336 if ( CKEDITOR
.env
.ie
&& CKEDITOR
.env
.version
< 9 ) {
3337 widget
.wrapper
.on( 'dragstart', function( evt
) {
3338 var target
= evt
.data
.getTarget();
3340 // Allow text dragging inside nested editables or dragging inline widget's drag handler.
3341 if ( !Widget
.getNestedEditable( widget
, target
) && !( widget
.inline
&& Widget
.isDomDragHandler( target
) ) )
3342 evt
.data
.preventDefault();
3346 widget
.wrapper
.removeClass( 'cke_widget_new' );
3347 widget
.element
.addClass( 'cke_widget_element' );
3349 widget
.on( 'key', function( evt
) {
3350 var keyCode
= evt
.data
.keyCode
;
3353 if ( keyCode
== 13 ) {
3355 // CTRL+C or CTRL+X.
3356 } else if ( keyCode
== CKEDITOR
.CTRL
+ 67 || keyCode
== CKEDITOR
.CTRL
+ 88 ) {
3357 copySingleWidget( widget
, keyCode
== CKEDITOR
.CTRL
+ 88 );
3358 return; // Do not preventDefault.
3359 } else if ( keyCode
in keystrokesNotBlockedByWidget
|| ( CKEDITOR
.CTRL
& keyCode
) || ( CKEDITOR
.ALT
& keyCode
) ) {
3360 // Pass chosen keystrokes to other plugins or default fake sel handlers.
3361 // Pass all CTRL/ALT keystrokes.
3366 }, null, null, 999 );
3367 // Listen with high priority so it's possible
3368 // to overwrite this callback.
3370 widget
.on( 'doubleclick', function( evt
) {
3371 if ( widget
.edit() ) {
3372 // We have to cancel event if edit method opens a dialog, otherwise
3373 // link plugin may open extra dialog (#12140).
3378 if ( widgetDef
.data
)
3379 widget
.on( 'data', widgetDef
.data
);
3381 if ( widgetDef
.edit
)
3382 widget
.on( 'edit', widgetDef
.edit
);
3385 function setupWidgetData( widget
, startupData
) {
3386 var widgetDataAttr
= widget
.element
.data( 'cke-widget-data' );
3388 if ( widgetDataAttr
)
3389 widget
.setData( JSON
.parse( decodeURIComponent( widgetDataAttr
) ) );
3391 widget
.setData( startupData
);
3393 // Populate classes if they are not preset.
3394 if ( !widget
.data
.classes
)
3395 widget
.setData( 'classes', widget
.getClasses() );
3397 // Unblock data and...
3398 widget
.dataReady
= true;
3400 // Write data to element because this was blocked when data wasn't ready.
3401 writeDataToElement( widget
);
3403 // Fire data event first time, because this was blocked when data wasn't ready.
3404 widget
.fire( 'data', widget
.data
);
3407 function setupWrapper( widget
) {
3408 // Retrieve widget wrapper. Assign an id to it.
3409 var wrapper
= widget
.wrapper
= widget
.element
.getParent();
3410 wrapper
.setAttribute( 'data-cke-widget-id', widget
.id
);
3413 function writeDataToElement( widget
) {
3414 widget
.element
.data( 'cke-widget-data', encodeURIComponent( JSON
.stringify( widget
.data
) ) );
3418 // WIDGET STYLE HANDLER ---------------------------------------------------
3424 * The class representing a widget style. It is an {@link CKEDITOR#STYLE_OBJECT object} like
3425 * the styles handler for widgets.
3427 * **Note:** This custom style handler does not support all methods of the {@link CKEDITOR.style} class.
3428 * Not supported methods: {@link #applyToRange}, {@link #removeFromRange}, {@link #applyToObject}.
3431 * @class CKEDITOR.style.customHandlers.widget
3432 * @extends CKEDITOR.style
3434 CKEDITOR
.style
.addCustomHandler( {
3437 setup: function( styleDefinition
) {
3439 * The name of widget to which this style can be applied.
3440 * It is extracted from style definition's `widget` property.
3442 * @property {String} widget
3444 this.widget
= styleDefinition
.widget
;
3447 apply: function( editor
) {
3448 // Before CKEditor 4.4 wasn't a required argument, so we need to
3449 // handle a case when it wasn't provided.
3450 if ( !( editor
instanceof CKEDITOR
.editor
) )
3453 // Theoretically we could bypass checkApplicable, get widget from
3454 // widgets.focused and check its name, what would be faster, but then
3455 // this custom style would work differently than the default style
3456 // which checks if it's applicable before applying or removeing itself.
3457 if ( this.checkApplicable( editor
.elementPath(), editor
) )
3458 editor
.widgets
.focused
.applyStyle( this );
3461 remove: function( editor
) {
3462 // Before CKEditor 4.4 wasn't a required argument, so we need to
3463 // handle a case when it wasn't provided.
3464 if ( !( editor
instanceof CKEDITOR
.editor
) )
3467 if ( this.checkApplicable( editor
.elementPath(), editor
) )
3468 editor
.widgets
.focused
.removeStyle( this );
3471 checkActive: function( elementPath
, editor
) {
3472 return this.checkElementMatch( elementPath
.lastElement
, 0, editor
);
3475 checkApplicable: function( elementPath
, editor
) {
3476 // Before CKEditor 4.4 wasn't a required argument, so we need to
3477 // handle a case when it wasn't provided.
3478 if ( !( editor
instanceof CKEDITOR
.editor
) )
3481 return this.checkElement( elementPath
.lastElement
);
3484 checkElementMatch: checkElementMatch
,
3486 checkElementRemovable: checkElementMatch
,
3489 * Checks if an element is a {@link CKEDITOR.plugins.widget#wrapper wrapper} of a
3490 * widget whose name matches the {@link #widget widget name} specified in the style definition.
3492 * @param {CKEDITOR.dom.element} element
3493 * @returns {Boolean}
3495 checkElement: function( element
) {
3496 if ( !Widget
.isDomWidgetWrapper( element
) )
3499 var widgetElement
= element
.getFirst( Widget
.isDomWidgetElement
);
3500 return widgetElement
&& widgetElement
.data( 'widget' ) == this.widget
;
3503 buildPreview: function( label
) {
3504 return label
|| this._
.definition
.name
;
3508 * Returns allowed content rules which should be registered for this style.
3509 * Uses widget's {@link CKEDITOR.plugins.widget.definition#styleableElements} to make a rule
3510 * allowing classes on specified elements or use widget's
3511 * {@link CKEDITOR.plugins.widget.definition#styleToAllowedContentRules} method to transform a style
3512 * into allowed content rules.
3514 * @param {CKEDITOR.editor} The editor instance.
3515 * @returns {CKEDITOR.filter.allowedContentRules}
3517 toAllowedContentRules: function( editor
) {
3521 var widgetDef
= editor
.widgets
.registered
[ this.widget
],
3528 if ( widgetDef
.styleableElements
) {
3529 classes
= this.getClassesArray();
3533 rule
[ widgetDef
.styleableElements
] = {
3535 propertiesOnly: true
3539 if ( widgetDef
.styleToAllowedContentRules
)
3540 return widgetDef
.styleToAllowedContentRules( this );
3545 * Returns classes defined in the style in form of an array.
3547 * @returns {String[]}
3549 getClassesArray: function() {
3550 var classes
= this._
.definition
.attributes
&& this._
.definition
.attributes
[ 'class' ];
3552 return classes
? CKEDITOR
.tools
.trim( classes
).split( /\s+/ ) : null;
3558 * @method applyToRange
3560 applyToRange: notImplemented
,
3565 * @method removeFromRange
3567 removeFromRange: notImplemented
,
3572 * @method applyToObject
3574 applyToObject: notImplemented
3577 function notImplemented() {}
3580 function checkElementMatch( element
, fullMatch
, editor
) {
3581 // Before CKEditor 4.4 wasn't a required argument, so we need to
3582 // handle a case when it wasn't provided.
3586 if ( !this.checkElement( element
) )
3589 var widget
= editor
.widgets
.getByElement( element
, true );
3590 return widget
&& widget
.checkStyleActive( this );
3596 // EXPOSE PUBLIC API ------------------------------------------------------
3599 CKEDITOR
.plugins
.widget
= Widget
;
3600 Widget
.repository
= Repository
;
3601 Widget
.nestedEditable
= NestedEditable
;
3605 * An event fired when a widget definition is registered by the {@link CKEDITOR.plugins.widget.repository#add} method.
3606 * It is possible to modify the definition being registered.
3608 * @event widgetDefinition
3609 * @member CKEDITOR.editor
3610 * @param {CKEDITOR.plugins.widget.definition} data Widget definition.
3614 * This is an abstract class that describes the definition of a widget.
3615 * It is a type of {@link CKEDITOR.plugins.widget.repository#add} method's second argument.
3617 * Widget instances inherit from registered widget definitions, although not in a prototypal way.
3618 * They are simply extended with corresponding widget definitions. Note that not all properties of
3619 * the widget definition become properties of a widget. Some, like {@link #data} or {@link #edit}, become
3620 * widget's events listeners.
3622 * @class CKEDITOR.plugins.widget.definition
3624 * @mixins CKEDITOR.feature
3628 * Widget definition name. It is automatically set when the definition is
3629 * {@link CKEDITOR.plugins.widget.repository#add registered}.
3631 * @property {String} name
3635 * The method executed while initializing a widget, after a widget instance
3636 * is created, but before it is ready. It is executed before the first
3637 * {@link CKEDITOR.plugins.widget#event-data} is fired so it is common to
3638 * use the `init` method to populate widget data with information loaded from
3639 * the DOM, like for exmaple:
3641 * init: function() {
3642 * this.setData( 'width', this.element.getStyle( 'width' ) );
3644 * if ( this.parts.caption.getStyle( 'display' ) != 'none' )
3645 * this.setData( 'showCaption', true );
3648 * @property {Function} init
3652 * The function to be used to upcast an element to this widget or a
3653 * comma-separated list of upcast methods from the {@link #upcasts} object.
3655 * The upcast function **is not** executed in the widget context (because the widget
3656 * does not exist yet) and two arguments are passed:
3658 * * `element` ({@link CKEDITOR.htmlParser.element}) – The element to be checked.
3659 * * `data` (`Object`) – The object which can be extended with data which will then be passed to the widget.
3661 * An element will be upcasted if a function returned `true` or an instance of
3662 * a {@link CKEDITOR.htmlParser.element} if upcasting meant DOM structure changes
3663 * (in this case the widget will be initialized on the returned element).
3665 * @property {String/Function} upcast
3669 * The object containing functions which can be used to upcast this widget.
3670 * Only those pointed by the {@link #upcast} property will be used.
3672 * In most cases it is appropriate to use {@link #upcast} directly,
3673 * because majority of widgets need just one method.
3674 * However, in some cases the widget author may want to expose more than one variant
3675 * and then this property may be used.
3678 * // This function may upcast only figure elements.
3679 * figure: function() {
3682 * // This function may upcast only image elements.
3683 * image: function() {
3686 * // More variants...
3689 * // Then, widget user may choose which upcast methods will be enabled.
3690 * editor.on( 'widgetDefinition', function( evt ) {
3691 * if ( evt.data.name == 'image' )
3692 * evt.data.upcast = 'figure,image'; // Use both methods.
3695 * @property {Object} upcasts
3699 * The {@link #upcast} method(s) priority. The upcast with a lower priority number will be called before
3700 * the one with a higher number. The default priority is `10`.
3703 * @property {Number} [upcastPriority=10]
3707 * The function to be used to downcast this widget or
3708 * a name of the downcast option from the {@link #downcasts} object.
3710 * The downcast funciton will be executed in the {@link CKEDITOR.plugins.widget} context
3711 * and with `widgetElement` ({@link CKEDITOR.htmlParser.element}) argument which is
3712 * the widget's main element.
3714 * The function may return an instance of the {@link CKEDITOR.htmlParser.node} class if the widget
3715 * needs to be downcasted to a different node than the widget's main element.
3717 * @property {String/Function} downcast
3721 * The object containing functions which can be used to downcast this widget.
3722 * Only the one pointed by the {@link #downcast} property will be used.
3724 * In most cases it is appropriate to use {@link #downcast} directly,
3725 * because majority of widgets have just one variant of downcasting (or none at all).
3726 * However, in some cases the widget author may want to expose more than one variant
3727 * and then this property may be used.
3730 * // This downcast may transform the widget into the figure element.
3731 * figure: function() {
3734 * // This downcast may transform the widget into the image element with data-* attributes.
3735 * image: function() {
3740 * // Then, the widget user may choose one of the downcast options when setting up his editor.
3741 * editor.on( 'widgetDefinition', function( evt ) {
3742 * if ( evt.data.name == 'image' )
3743 * evt.data.downcast = 'figure';
3746 * @property downcasts
3750 * If set, it will be added as the {@link CKEDITOR.plugins.widget#event-edit} event listener.
3751 * This means that it will be executed when a widget is being edited.
3752 * See the {@link CKEDITOR.plugins.widget#method-edit} method.
3754 * @property {Function} edit
3758 * If set, it will be added as the {@link CKEDITOR.plugins.widget#event-data} event listener.
3759 * This means that it will be executed every time the {@link CKEDITOR.plugins.widget#property-data widget data} changes.
3761 * @property {Function} data
3765 * The method to be executed when the widget's command is executed in order to insert a new widget
3766 * (widget of this type is not focused). If not defined, then the default action will be
3767 * performed which means that:
3769 * * An instance of the widget will be created in a detached {@link CKEDITOR.dom.documentFragment document fragment},
3770 * * The {@link CKEDITOR.plugins.widget#method-edit} method will be called to trigger widget editing,
3771 * * The widget element will be inserted into DOM.
3773 * @property {Function} insert
3777 * The name of a dialog window which will be opened on {@link CKEDITOR.plugins.widget#method-edit}.
3778 * If not defined, then the {@link CKEDITOR.plugins.widget#method-edit} method will not perform any action and
3779 * widget's command will insert a new widget without opening a dialog window first.
3781 * @property {String} dialog
3785 * The template which will be used to create a new widget element (when the widget's command is executed).
3786 * This string is populated with {@link #defaults default values} by using the {@link CKEDITOR.template} format.
3787 * Therefore it has to be a valid {@link CKEDITOR.template} argument.
3789 * @property {String} template
3793 * The data object which will be used to populate the data of a newly created widget.
3794 * See {@link CKEDITOR.plugins.widget#property-data}.
3797 * showCaption: true,
3801 * @property defaults
3805 * An object containing definitions of widget components (part name => CSS selector).
3809 * caption: 'div.caption'
3816 * An object containing definitions of nested editables (editable name => {@link CKEDITOR.plugins.widget.nestedEditable.definition}).
3817 * Note that editables *have to* be defined in the same order as they are in DOM / {@link CKEDITOR.plugins.widget.definition#template template}.
3818 * Otherwise errors will occur when nesting widgets inside each other.
3823 * selector: 'div.content',
3824 * allowedContent: 'p strong em; a[!href]'
3828 * @property editables
3832 * Widget name displayed in elements path.
3834 * @property {String} pathName
3838 * If set to `true`, the widget's element will be covered with a transparent mask.
3839 * This will prevent its content from being clickable, which matters in case
3840 * of special elements like embedded Flash or iframes that generate a separate "context".
3842 * @property {Boolean} mask
3846 * If set to `true/false`, it will force the widget to be either an inline or a block widget.
3847 * If not set, the widget type will be determined from the widget element.
3849 * Widget type influences whether a block (`div`) or an inline (`span`) element is used
3852 * @property {Boolean} inline
3856 * The label for the widget toolbar button.
3858 * editor.widgets.add( 'simplebox', {
3859 * button: 'Create a simple box'
3862 * editor.widgets.add( 'simplebox', {
3863 * button: editor.lang.simplebox.title
3866 * @property {String} button
3870 * Whether widget should be draggable. Defaults to `true`.
3871 * If set to `false` drag handler will not be displayed when hovering widget.
3873 * @property {Boolean} draggable
3877 * Names of element(s) (separated by spaces) for which the {@link CKEDITOR.filter} should allow classes
3878 * defined in the widget styles. For example if your widget is upcasted from a simple `<div>`
3879 * element, then in order to make it styleable you can set:
3881 * editor.widgets.add( 'customWidget', {
3882 * upcast: function( element ) {
3883 * return element.name == 'div';
3888 * styleableElements: 'div'
3891 * Then, when the following style is defined:
3894 * name: 'Thick border', type: 'widget', widget: 'customWidget',
3895 * attributes: { 'class': 'thickBorder' }
3898 * a rule allowing the `thickBorder` class for `div` elements will be registered in the {@link CKEDITOR.filter}.
3900 * If you need to have more freedom when transforming widget style to allowed content rules,
3901 * you can use the {@link #styleToAllowedContentRules} callback.
3904 * @property {String} styleableElements
3908 * Function transforming custom widget's {@link CKEDITOR.style} instance into
3909 * {@link CKEDITOR.filter.allowedContentRules}. It may be used when a static
3910 * {@link #styleableElements} property is not enough to inform the {@link CKEDITOR.filter}
3911 * what HTML features should be enabled when allowing the given style.
3913 * In most cases, when style's classes just have to be added to element name(s) used by
3914 * the widget element, it is recommended to use simpler {@link #styleableElements} property.
3916 * In order to get parsed classes from the style definition you can use
3917 * {@link CKEDITOR.style.customHandlers.widget#getClassesArray}.
3919 * For example, if you want to use the [object format of allowed content rules](#!/guide/dev_allowed_content_rules-section-object-format),
3920 * to specify `match` validator, your implementation could look like this:
3922 * editor.widgets.add( 'customWidget', {
3925 * styleToAllowedContentRules: funciton( style ) {
3926 * // Retrieve classes defined in the style.
3927 * var classes = style.getClassesArray();
3929 * // Do something crazy - for example return allowed content rules in object format,
3930 * // with custom match property and propertiesOnly flag.
3933 * match: isWidgetElement,
3934 * propertiesOnly: true,
3942 * @property {Function} styleToAllowedContentRules
3943 * @param {CKEDITOR.style.customHandlers.widget} style The style to be transformed.
3944 * @returns {CKEDITOR.filter.allowedContentRules}
3948 * This is an abstract class that describes the definition of a widget's nested editable.
3949 * It is a type of values in the {@link CKEDITOR.plugins.widget.definition#editables} object.
3951 * In the simplest case the definition is a string which is a CSS selector used to
3952 * find an element that will become a nested editable inside the widget. Note that
3953 * the widget element can be a nested editable, too.
3955 * In the more advanced case a definition is an object with a required `selector` property.
3960 * selector: 'div.content',
3961 * allowedContent: 'p strong em; a[!href]'
3965 * @class CKEDITOR.plugins.widget.nestedEditable.definition
3970 * The CSS selector used to find an element which will become a nested editable.
3972 * @property {String} selector
3976 * The [Advanced Content Filter](#!/guide/dev_advanced_content_filter) rules
3977 * which will be used to limit the content allowed in this nested editable.
3978 * This option is similar to {@link CKEDITOR.config#allowedContent} and one can
3979 * use it to limit the editor features available in the nested editable.
3981 * @property {CKEDITOR.filter.allowedContentRules} allowedContent
3985 * Nested editable name displayed in elements path.
3987 * @property {String} pathName