Creating a Simple CKEditor Plugin, Part 2

This website contains links to software which is either no longer maintained or will be supported only until the end of 2019 (CKFinder 2). For the latest documentation about current CKSource projects, including software like CKEditor 4/CKEditor 5, CKFinder 3, Cloud Services, Letters, Accessibility Checker, please visit the new documentation website.

If you look for an information about very old versions of CKEditor, FCKeditor and CKFinder check also the CKEditor forum, which was closed in 2015. If not, please head to StackOverflow for support.

The aim of this tutorial is to demonstrate how to extend an existing CKEditor plugin with context menu support as well as the possibility to edit a previously inserted element. Instead of creating a new plugin, this time we are going to expand on the functionality of the Abbreviation plugin created in the previous installment of the tutorial series.

We need to start where we previously left off — to see the full source code of the Abbreviation plugin, .

important note

You can also download the whole plugin folder inluding the icon and the fully commented source code.


CKEDITOR.plugins.add( 'abbr',
{
	init: function( editor )
	{
		editor.addCommand( 'abbrDialog',new CKEDITOR.dialogCommand( 'abbrDialog' ) );
		editor.ui.addButton( 'Abbr',
		{
			label: 'Insert Abbreviation',
			command: 'abbrDialog',
			icon: this.path + 'images/icon.png'
		} );
		CKEDITOR.dialog.add( 'abbrDialog', function( editor )
		{
			return {
				title : 'Abbreviation Properties',
				minWidth : 400,
				minHeight : 200,
				contents :
				[
					{
						id : 'tab1',
						label : 'Basic Settings',
						elements :
						[
							{
								type : 'text',
								id : 'abbr',
								label : 'Abbreviation',
								validate : CKEDITOR.dialog.validate.notEmpty( "Abbreviation field cannot be empty" )
							},
							{
								type : 'text',
								id : 'title',
								label : 'Explanation',
								validate : CKEDITOR.dialog.validate.notEmpty( "Explanation field cannot be empty" )
							}	 
						]
					},
					{
						id : 'tab2',
						label : 'Advanced Settings',
						elements :
						[
							{
								type : 'text',
								id : 'id',
								label : 'Id'
							}
						]
					}
				],
				onOk : function()
				{
					var dialog = this;

					var abbr = editor.document.createElement( 'abbr' );
					abbr.setAttribute( 'title', dialog.getValueOf( 'tab1', 'title' ) );
					abbr.setText( dialog.getValueOf( 'tab1', 'abbr' ) );
					var id = dialog.getValueOf( 'tab2', 'id' );
					if ( id )
						abbr.setAttribute( 'id', id );
					editor.insertElement( abbr );
				}
			};
		} );
	}
} );

If you have any doubts about the contents of the plugin and its configuration, refer to the Creating a Simple CKEditor Plugin, Part 1 tutorial.

Minor Code Refactoring

Since we are going to use the plugin toolbar button path more than once, it makes sense to refactor the code in order to place the icon path in a variable. The addButton function will then be modified to use the newly created iconPath variable.

var iconPath = this.path + 'images/icon.png';

editor.addCommand( 'abbrDialog',new CKEDITOR.dialogCommand( 'abbrDialog' ) );

editor.ui.addButton( 'Abbr',
{
	label: 'Insert Abbreviation',
	command: 'abbrDialog',
	icon: iconPath
} );

Context Menu Support

The context menu implementation should be placed inside the init function, below the command and button definitions.

Context menu support in CKEditor is implemented in the contextmenu plugin, which, in turn, is based on the contextmenu event.

Since we want the context menu option for the Abbreviation plugin to be separated from standard context menu items, we will need to use the addMenuGroup function to register a new menu group called myGroup. Using the addMenuItem function we can now register a new menu item that will belong to the newly created group. The label and icon properties let us set the context menu item name and its icon, respectively. To make the context menu item open the Abbreviation Properties dialog window, we need to set the command property to use the abbrDialog command.

if ( editor.contextMenu )
{
	editor.addMenuGroup( 'myGroup' );
	editor.addMenuItem( 'abbrItem',
	{
		label : 'Edit Abbreviation',
		icon : iconPath,
		command : 'abbrDialog',
		group : 'myGroup'
	});
}

However, when we reload the CKEditor instance and add an abbreviation, the context menu does not contain the newly created Edit Abbreviation item. We now need to enable the Abbreviation context menu for each selected <abbr> element. Using the addListener function we will add an event listener that listens to the contextmenu event when such an element is selected.

The listener should cater for two scenarios and should act differently for an <abbr> element and for all other elements.

The first conditional statement uses the getAscendant function to get to the closest <abbr> element that contains the selection. The second conditional statement checks whether the <abbr> element exists, is not read-only and is not a fake element. If all these conditions are met, the listener returns an object in the format of contextMenuButtonName : CKEDITOR.TRISTATE_OFF. The TRISTATE_OFF setting means that the menu context option is enabled, but it is not being used at the moment. If the conditions are not met, the listener returns nothing.

if ( editor.contextMenu )
{
	// Code creating context menu items goes here.
	editor.contextMenu.addListener( function( element )
	{
		if ( element )
			element = element.getAscendant( 'abbr', true );
		if ( element && !element.isReadOnly() && !element.data( 'cke-realelement' ) )
 			return { abbrItem : CKEDITOR.TRISTATE_OFF };
		return null;
	});
}

The Edit Abbreviation item is now visible in the context menu of an <abbr> element. Once selected, it opens the Abbreviation Properties dialog window due to the use of the abbrDialog command.

Edit Abbreviation context menu item added to CKEditor


The context menu works — but only partially. It opens the Abbreviation Properties dialog window for the abbreviation, but the editing feature does not really work. The Abbreviation and Explanation fields are empty:

Abbreviation Properties is empty in editing mode


If you try to enter some values into these fields and accept the changes, a new <abbr> element will be added on the position of the cursor in the document.

New abbreviation element inserted into the document


It is time to work on the selection logic so that editing an inserted element would not create a new one, but use the previously entered values.

Dialog Window Logic

The editing behavior for a previously inserted element will use the onShow function that is defined for the plugin dialog window and is executed when the dialog window is opened. This function will be defined above the onOk function that we will also need to refactor later.

onShow : function()
{
	// The code that will be executed when a dialog window is loaded.
}

Selecting an Element

We will need to start with the selection logic. To get to the element that is selected by the user (either highlighted with a mouse or keyboard, or selected by placing the cursor inside), we will need to use the getSelection function. This function returns the current selection from CKEditor editing area when in WYSIWYG mode. We will also use the getStartElement to get the element in which the selection starts, and assign it to the element variable.

var sel = editor.getSelection(),
	element = sel.getStartElement();

Creating an Element

The first conditional statement again uses the getAscendant function to get to the closest <abbr> element that contains the selection. The second one will check whether a selected element exists, its name is not <abbr> and it is a real element, as opposed to a fake object. If any of these conditions are met, we will have to create a new <abbr> element by using the createElement function.

To differentiate between adding a new element and editing an existing one, we will create a new insertMode flag. It will be set to true in the "add new element" scenario. If an <abbr> element already exists, the insertMode flag will be set to false.

if ( element )
	element = element.getAscendant( 'abbr', true );
 
if ( !element || element.getName() != 'abbr' || element.data( 'cke-realelement' ) )
{
	element = editor.document.createElement( 'abbr' );
	this.insertMode = true;
}
else
	this.insertMode = false;

We will now store a reference to the <abbr>/code> element in the <code>element variable since we will need to access it in the new version of the onOK function later.

this.element = element;

Setup Functions

The onShow function will finish with a call to the setupContent function that will invoke the setup functions for the element. Each parameter that will be passed on to the setupContent function will also be passed on to the setup functions.

this.setupContent( this.element );

For the above code to work we will however first need to define the setup functions themselves. In order to do that, we will revisit the code of the dialog window UI elements.

The setup function for the Abbreviation text field needs to get the contents of the <abbr> element by using the getText function in order to populate the field with its value by using the setValue function.

A similar approach can be used for the Explanation field, although in this case we will need to get the contents of the title attribute of the <abbr> element by using the getAttribute function in order to populate the field with its value by using the setValue function again.

elements :
[
	{
		type : 'text',
		id : 'abbr',
		label : 'Abbreviation',
		validate : CKEDITOR.dialog.validate.notEmpty( "Abbreviation cannot be empty" ),
		setup : function( element )
		{
			this.setValue( element.getText() );
		}
},
	{
		type : 'text',
		id : 'title',
		label : 'Explanation',
		validate : CKEDITOR.dialog.validate.notEmpty( "Title cannot be empty" ),
		setup : function( element )
		{
			this.setValue( element.getAttribute( "title" ) );
		}
	}
]

Since the Advanced Settings tab contains a single Id text field that reflects the contents of the id attribute, we will use the same combination of the getAttribute and setValue function as in case of the Explanation text field.

elements :
[
	{
		type : 'text',
		id : 'id',
		label : 'Id',
		setup : function( element )
		{
			this.setValue( element.getAttribute( "id" ) );
		}
	}
]

When you reload the page, add an abbreviation, and then attempt to modify it by opening the context menu and selecting Edit Abbreviation, the Abbreviation Properties dialog window will now re-open with the Abbreviation and Explanation fields already filled in with the contents of the edited element.

Modifying an abbreviation in CKEditor


Suppose you were to change the abbreviation spelling into lower case. Replace the contents of the text fields as follows and click the OK button.

Modifying an abbreviation in CKEditor


This operation fails! The modified values do not replace the contents of the first abbreviation, but are used to create a new abbreviation element inserted inside the first one, at the position of the cursor.

Abbreviation duplicate added in CKEditor


Why is that so? It is because the current edition of the onOk function does not differentiate between adding an element and modifying it, so it simply inserts the values supplied in the dialog window fields into the <abbr> that it creates and adds this element to the document.

Commit Functions

To correct this error, we will need to re-write the code of the onOk function to account for both scenarios. The function can now, in fact, be stripped to the minimum.

Firstly, we will define the variables for the dialog window (dialog) and the <abbr> element (abbr).

The insertMode flag created in the onShow function can then be used to switch between the creation of a new element and modification of the existing one. If we are in the insert mode, we add a new <abbr> element to the document. We then use the commitContent function to populate the element with values entered by the user. Every parameter that is passed to the commitContent function will also be passed on to the commit functions themselves.

onOk : function()
{
	var dialog = this,
		abbr = this.element;
	if ( this.insertMode )
		editor.insertElement( abbr );
	this.commitContent( abbr );
}

To make the commitContent method work we will however first need to define the commit functions themselves. In order to do that, we will have to revise the code of the dialog window UI elements again.

The commit function for the Abbreviation text field needs to get the value entered by the user by using the getValue function in order to set the contents of the <abbr> element by using the setText function.

A similar approach can be used for the retrieval of the Explanation field contents, although in this case we will need to set the contents of the title attribute of the <abbr> element by using the setAttribute function.

elements :
[
	{
		type : 'text',
		id : 'abbr',
		label : 'Abbreviation',
		validate : CKEDITOR.dialog.validate.notEmpty( "Abbreviation cannot be empty" ),
		setup : function( element )
		{
			this.setValue( element.getText() );
		},
		commit : function( element )
		{
			element.setText( this.getValue() );
		}
	},
	{
		type : 'text',
		id : 'title',
		label : 'Explanation',
		validate : CKEDITOR.dialog.validate.notEmpty( "Title cannot be empty" ),
		setup : function( element )
		{
			this.setValue( element.getAttribute( "title" ) );
		},
		commit : function( element )
		{
			element.setAttribute( "title", this.getValue() );
		}
	}
]

Similarly, since the Advanced Settings tab contains an Id text field that reflects the contents of the id attribute, we will use the same combination of the getValue and setAttribute function as in case of the Explanation text field. This time, however, we will also need to account for the possibility of removing the attribute value by the user during the modification of the element. If we are not in the insert mode (which means we are editing an existing element) and the Id field is empty, we will use the removeAttribute method to delete the id element of an existing abbreviation.

elements :
[
	{
		type : 'text',
		id : 'id',
		label : 'Id',
		setup : function( element )
		{
			this.setValue( element.getAttribute( "id" ) );
		},
		commit : function ( element )
		{
			var id = this.getValue();
			if ( id )
				element.setAttribute( 'id', id );
			else if ( !this.insertMode )
				element.removeAttribute( 'id' );
		}
	}
]

Full Source Code

To see the full contents of the updated plugin.js file, .

important note

You can also download the whole modified plugin folder inluding the icon and the fully commented updated source code.


CKEDITOR.plugins.add( 'abbr',
{
	init: function( editor )
	{
		var iconPath = this.path + 'images/icon.png';
		
		editor.addCommand( 'abbrDialog',new CKEDITOR.dialogCommand( 'abbrDialog' ) );
		
		editor.ui.addButton( 'Abbr',
		{
			label: 'Insert Abbreviation',
			command: 'abbrDialog',
			icon: iconPath
		} );
		
		if ( editor.contextMenu )
		{
			editor.addMenuGroup( 'myGroup' );
			editor.addMenuItem( 'abbrItem',
			{
				label : 'Edit Abbreviation',
				icon : iconPath,
				command : 'abbrDialog',
				group : 'myGroup'
			});
			editor.contextMenu.addListener( function( element )
			{
				if ( element )
					element = element.getAscendant( 'abbr', true );
				if ( element && !element.isReadOnly() && !element.data( 'cke-realelement' ) )
 					return { abbrItem : CKEDITOR.TRISTATE_OFF };
				return null;
			});
		}
		
		CKEDITOR.dialog.add( 'abbrDialog', function( editor )
		{
			return {
				title : 'Abbreviation Properties',
				minWidth : 400,
				minHeight : 200,
				contents :
				[
					{
						id : 'tab1',
						label : 'Basic Settings',
						elements :
						[
							{
								type : 'text',
								id : 'abbr',
								label : 'Abbreviation',
								validate : CKEDITOR.dialog.validate.notEmpty( "Abbreviation field cannot be empty" ),
								setup : function( element )
								{
									this.setValue( element.getText() );
								},
								commit : function( element )
								{
									element.setText( this.getValue() );
								}
							},
							{
								type : 'text',
								id : 'title',
								label : 'Explanation',
								validate : CKEDITOR.dialog.validate.notEmpty( "Explanation field cannot be empty" ),
								setup : function( element )
								{
									this.setValue( element.getAttribute( "title" ) );
								},
								commit : function( element )
								{
									element.setAttribute( "title", this.getValue() );
								}
							}	 
						]
					},
					{
						id : 'tab2',
						label : 'Advanced Settings',
						elements :
						[
							{
								type : 'text',
								id : 'id',
								label : 'Id',
								setup : function( element )
								{
									this.setValue( element.getAttribute( "id" ) );
								},
								commit : function ( element )
								{
									var id = this.getValue();
									if ( id )
										element.setAttribute( 'id', id );
									else if ( !this.insertMode )
										element.removeAttribute( 'id' );
								}
							}
						]
					}
				],
				onShow : function()
				{
					var sel = editor.getSelection(),
						element = sel.getStartElement();
					if ( element )
						element = element.getAscendant( 'abbr', true );
 
					if ( !element || element.getName() != 'abbr' || element.data( 'cke-realelement' ) )
					{
						element = editor.document.createElement( 'abbr' );
						this.insertMode = true;
					}
					else
						this.insertMode = false;
					
					this.element = element;
					
					this.setupContent( this.element );
				},
				onOk : function()
				{
					var dialog = this,
						abbr = this.element;

					if ( this.insertMode )
						editor.insertElement( abbr );
					this.commitContent( abbr );
				}
			};
		} );
	}
} );

Working Example

The code of the extended Abbreviation plugin is now ready. When you click the Insert Abbreviation toolbar button, the Abbreviation Properties dialog window will open. Fill in the obligatory Abbreviation and Explanation fields and click the OK button.

Abbreviation added in the dialog window


The newly added abbreviation will be inserted into the document and will be displayed using the default styling of your browser. In Firefox, for example, the abbreviation will be underlined using a dotted line and the explanation will be displayed in a tooltip.

Abbreviation added in the dialog window


If you want to edit the abbreviation, select it and open its context menu. Choose the Edit Abbreviation option to open the dialog window again, filled in with the contents of the element. Modify the abbreviation and click OK.

Abbreviation edited in the dialog window


Voilà! The abbreviation was updated and its contents replaced with texts entered in the dialog window.

Abbreviation edited in the dialog window
This page was last edited on 9 May 2012, at 13:33.