2010/01/01

Zoom Plugin for CKEditor

Recently all the browsers that are implementing the latest and greatest elements of CSS 3 have added support for CSS Transforms, and so I decided to have a little fun while creating a little example about how to create a custom dropdown element in the CKEditor toolbar.

The idea is to provide a new dropdown that allows the user to set the zoom level for the editor, this example is gonna be a little rough and it can be greatly improved, but this is mostly a proof of concept about how to do it.

The first step is to create the skeleton for the plugin:

CKEDITOR.plugins.add( 'zoom',
{
    requires : [ 'richcombo' ],

    init : function( editor )
    {

    } //Init
} );

That code should be placed in a "plugin.js" file located in the plugins/zoom folder of your CKEditor installation. If you want to create another plugin, you'll use another folder name and put that name as the first parameter in the call to CKEDITOR.plugins.add()

For this plugin we need to be sure that the code from the "richcombo" plugin is loaded, as that's the real code that will create the dropdown element, so we specify it in the requires field of the plugin.

Finally this plugin must be added to the CKEditor instance, so in your config.js (or whatever other place you want to specify it) add it to the plugins that must be loaded:

    config.extraPlugins = 'zoom';

You can place an alert() inside the init function to verify that the plugin is being loaded when you refresh the page with CKEditor. If it doesn't work, verify the error console and try to clear your cache.

Now we need to fill up the code in the init function to create the dropdown:

    init : function( editor )
    {
        var config = editor.config;

        editor.ui.addRichCombo( 'Zoom',
            {
                label : "100 %",
                title : 'Zoom',
                multiSelect : false,

                panel :
                {
                    css : [ CKEDITOR.getUrl( editor.skinPath + 'editor.css' ) ].concat( config.contentsCss )
                },

                init : function()
                {
                    var zoomOptions = [50, 75, 100, 125, 150, 200, 400],
                        zoom;
                   
                    this.startGroup( 'Zoom level' );
                    // Loop over the Array, adding all items to the
                    // combo.
                    for ( i = 0 ; i < zoomOptions.length ; i++ )
                    {
                        zoom = zoomOptions[ i ];
                        // value, html, text
                        this.add( zoom, zoom + " %", zoom + " %" );
                    }
                    // Default value on first click
                    this.setValue(100, "100 %");
                }
            });
        // End of richCombo element

    } //Init

In this function we are creating the dropdown as a "RichCombo" element with editor.ui.addRichCombo() The function takes as parameters the name of the RichCombo and the object that contains the definition. Inside this object there's an init() function that will be called to initialize the dropdown on first click, here we specify the options available in the RichCombo and add them with this.add()

So now we can add to the toolbar of our CKEditor this 'Zoom' RichCombo element:

...
    ['Maximize', 'ShowBlocks', 'Zoom'],
...

Refreshing the page will show now the dropdown and clicking on it will show the panel, although we still haven't specified what must be done  when an option is selected. Doing it in a simple way and not trying to optimize how it works we can add this function to the RichCombo definition:

...
                    // Default value on first click
                    this.setValue(100, "100 %");
                },

                onClick : function( value )
                {
                    var body = editor.document.getBody().$;
 
                    body.style.MozTransformOrigin = "top left";
                    body.style.MozTransform = "scale(" + (value/100)  + ")";

                    body.style.WebkitTransformOrigin = "top left";
                    body.style.WebkitTransform = "scale(" + (value/100)  + ")";

                    body.style.OTransformOrigin = "top left";
                    body.style.OTransform = "scale(" + (value/100)  + ")";

                    body.style.TransformOrigin = "top left";
                    body.style.Transform = "scale(" + (value/100)  + ")";
                    // IE
                    body.style.zoom = value/100;
                }
            });
        // End of richCombo element
...

This code blindly tries to set the property for each browser, without bothering about which one is being used of if it supports CSS Transforms at all. We know that IE doesn't support them, but it has supported since long ago the style.zoom so in this case we can use just that.

A correct implementation of the plugin should verify that the browser does support CSS Transforms (or is IE and can use .zoom) before adding the RichCombo, and in the onClick event handler should use just the correct property instead of trying all of them.

This plugin also lacks internationalization, because that wasn't the point of this test, but it should be easy to add and to fix other little things.

But there are two problems that can be seen with just this code:

The first one is that the width of the combo in the toolbar is a little too big to specify some little text like "100%". This is being tracked in ticket 4559 but as you can see by reading all the comments there's no easy solution that can be applied to automatically fix it. So the solution is to add some rules in the stylesheet, although that makes deploying the plugin a little harder. Maybe the RichCombo should be allowed to specify a width in its definition?

The second problem appears only in Webkit browsers (Safari and Chrome), when you open up the panel it will take full height, and it's a little ugly. Other combos have their size specified in the skins css but that doesn't seems like a good solution if you want to publish a plugin that will be used for other people, as well as making upgrading a little harder.

Browser support: The zoom feature should work in IE6+, Firefox 3.5+, current Safari and Chrome (I don't have old versions to test) and Opera 10.5+ (still in alpha)

Happy 2010

Edit may-2013:

A new version of the plugin compatible with CKEditor 4 is available at the plugins repository. Zoom plugin.

2009/12/19

GeckoSpellChecker plugin for CKEditor

A little while ago I created the GeckoSpellChecker plugin for FCKeditor that allows to use the internal Firefox spellchecker from the editing area without any external server.

Now the plugin has a version ready for CKEditor. Be sure to download the 1.0 version for CKEditor, the 0.7 version will remain there for the people using FCKeditor.

I hope that you can find this useful.

2009/12/18

Recompressing ckeditor.js to fit your needs

Note:
Most of the content of this post as well as some corrections are available now at the official documentation for CKEditor: CKPackager - Compressing CKEditor
This post will remain here only for historical reference and to link to the new documentation (the one that you should read)

The javascript code of CKEditor is delivered as one main ckeditor.js where all the code has been compressed and merged (of course, not ALL the code, just the code that is needed for the core and the default plugins, the code of the dialogs for example is loaded on demand). And one question that you might have is: how can I compress my own version? I'll try to provide here some explanations and notes about this, but despite its length it is far from a full guide and it might contain some incorrect parts.

First you have download the ckpackager.jar (there's also an .exe for those in windows that haven't installed Java) from
http://svn.fckeditor.net/CKPackager/trunk/bin/ckpackager.jar and put it at the root of your CKEditor folder. (Note that this is a SVN repository so it should contain the latest version)

Backup the existing ckeditor.js and ckeditor_basic.js so you can check that the process is working correctly.

Now the first step is to verify that you have Java correctly installed and that everything is correct in your environment, so fire up the console/terminal/command prompt and navigate to the CKEditor folder and type there the command to start the compilation. This should generate identical files to the previous ckeditor.js and ckeditor_basic.js if you haven't changed anything in the _source folder:

java -jar ckpackager.jar ckeditor.pack

Maybe the js files aren't identical to the previous ones due to some change in the version of CKPackager used to compress the released version of CKEditor and some fix/improvement made to CKPackager since that moment, but the overall should be similar and you should be able to use the new files without differences.

Working with the source files

Now you can try to apply changes to the files under _source and test them using the ckeditor_source.js, and when you are ready to deploy you just have to compress them all again. You should be careful with your changes because compressing the source means that any slight error can be fatal.

The new packager is based on Rhino, the javascript implementation in Java from the people at Mozilla, so I don't know how it does deal with missing semicolons, and other minor issues that can be fatal with some compression systems. Of course it's better to write code without problems instead of relying on the tools to fix them.

Selecting just what you want

The ckeditor.js file includes all the plugins (but not all the code of the plugins: the dialogs are lazy loaded only when needed as I said). So if you don't want to provide several options to your users you could remove those plugins, not only from the toolbar, but also from the packaged file so you can end up with a much smaller ckeditor.js file.

In order to change what's included you need to edit ckeditor.pack and remove the entries about plugins that you don't need.

Don't alter the entries under '_source/core/*' because the editor probably will fail. Remember that if you mess with the packaging process no one else can help you, you are the one that is editing the file and not knowing what to do isn't a good idea here.

An example of a change would be to remove the line

                '_source/plugins/elementspath/plugin.js',

if you don't want to show the elements path at the bottom of the editor (there's the config.removePlugins = 'elementspath' option but that means that the code is still loaded so if you are sure that you never need this option you can save some bytes). Then you save the file and issue the recompress command, and now the ckeditor.js is 2Kb smaller.

Of course it seems that it would be a trial/error the process to find what are the files that you can remove as one plugin might depend upon another and so you need it to run correctly. In order to generate the default ckeditor.pack file, the SVN version of CKEditor includes a _dev folder with some development tools and that includes a packager folder with a HTML file created to generate the correct content according to the current configuration (this is meant to be used in the SVN version, I don't know how it will deal with the released version).

Optimizing the downloads

If you check the ckeditor.pack file you can see that the lang file isn't compressed, this is due to the fact that not everybody speaks English, so packaging the en.js file for everybody would mean a waste of bytes, but if you know that your users speak only one language, then you could specify that language in the ckeditor.pack file and get it bundled along the others.

This will increase the size of ckeditor.js but remember that those bytes were downloaded separately as another request, so now the editor will be slightly faster as we have avoided that extra step.

At the bottom of the file you can see that the kama.js file is also being bundled, so if you are using another skin you could adjust that to remove the kama and put your own one, avoiding the extra download of your selected skin.

And if you are using some custom plugin you can include it in the list so it's ready along the rest of files and the user don't suffer an extra delay for the usage of your plugins.

This is just a quick explanation, but it should be enough to get started about how to recompress the code.

Note:
Most of the content of this post as well as some corrections are available now at the official documentation for CKEditor: CKPackager - Compressing CKEditor
This post will remain here only for historical reference and to link to the new documentation (the one that you should read)

2009/12/16

Adjusting the preview text in easyUpload

Over the years people have reported that sometimes the users don't understand what's the Lorem Ipsum text that appears in the preview of the image and flash dialogs, claiming that it's not English and it's not what they have written.

The solution is to point them to the source of those dialogs and then remove the offending text (of course they will lose then the ability to understand how the various align values will affect their layout, but it's their choice).

With the improved capabilities of CKEditor this can be done much easier. For example I've added just an id to the uiElement that it's used to create the preview:

        {
            type : 'html',
            id : 'htmlPreview',
            html : '<div>' + CKEDITOR.tools.htmlEncode( editor.lang.image.preview ) +'<br>'+
...

The first motivation to add this id was to provide a way to remove the preview for those that didn't want that in a dialog with simple options. But with just that addition it's possible to write a little code using the 'dialogDefinition' event. First we check that it's loading our dialog and then we can change both the label over the preview as well as the context of the preview:

    var preview = infoTab.get('htmlPreview');
    preview.html = '<div>My image preview<br>' +
        '<div id="ImagePreviewLoader" style="display:none"><div class="loading">&nbsp;</div></div>'+
        '<div id="ImagePreviewBox">'+
        '<a href="javascript:void(0)" target="_blank" onclick="return false;" id="previewLink">'+
        '<img id="previewImage" alt="" /></a>This is some example text around the image' +
        '</div>'+'</div>';

We could change the html to whatever we would like, but in order to mantain compability and keep the preview working we should preserve the "placeholder" elements (div, a, img) and change only the texts (in this case "My image preview" and "This is some example text around the image")

This is the complete function:

// When opening a dialog, its "definition" is created for it, for
// each editor instance. The "dialogDefinition" event is then
// fired. We should use this event to make customizations to the
// definition of existing dialogs.
CKEDITOR.on( 'dialogDefinition', function( ev )
    {
        // Take the dialog name and its definition from the event
        // data.
        var dialogName = ev.data.name;
        var dialogDefinition = ev.data.definition;

        // Check if the definition is from the dialog we're
        // interested on (the "easyImage" dialog).
        if ( dialogName == 'easyImage' )
        {
            // Get a reference to the "Info" tab.
            var infoTab = dialogDefinition.getContents( 'info' );

            var preview = infoTab.get('htmlPreview');
            preview.html = '<div>Image preview<br>' +
                '<div id="ImagePreviewLoader" style="display:none"><div class="loading">&nbsp;</div></div>'+
                                    '<div id="ImagePreviewBox">'+
                                    '<a href="javascript:void(0)" target="_blank" onclick="return false;" id="previewLink">'+
                                    '<img id="previewImage" alt="" /></a>This is some example text around the image' +
                                    '</div>'+'</div>';
        }
    });

Another option to customize the lorem ipsum text would be to mark is as a configuration option or language item (like the title above it: editor.lang.image.preview), but this is a worse move in my point of view. I haven't studied if I'm wrong and it can't be done other ways, but it seems that then it will specify the whole "Lorem ipsum... " text at the plugin.js level or in each language file. Either of those options means that all that text will be loaded whenever the editor is loaded even if you are not going to use the image dialog, and the reality is that very few people don't understand that this is just some placeholder and the important thing is only the image, not the text.

Going even further with the customization, the first option (despite its simplicity) is more powerful because it could be used to inject other elements in the html so you could turn it into a real preview by changing the contents of the box with parts of the current content of the editor each time the dialog is loaded. I won't recomend that as it might mean some extra work to make it work as desired, but it's certainly doable.

So I would say that just adding the id is enough and it can allow the developer to chose betweeen removing the preview (this requires some other fixes in that dialog) or change its contents.

2009/12/12

Uploading .app files

Developing an extension for an application like CKEditor means that you have to be aware of the environment. CKEditor tries to cover the differences between the browsers and even adds workarounds for the bugs that are known in each one (as long as it's possible of course)

So when you are writting your code and something doesn't work as expected you have to start searching for bugs in your own code (the usual culprit), then you have to review how you are using the CKEditor API, verify that you have understood the explanation and that it matches the actual code that you have written. Then you escalate up the problem to the CKEditor source code, maybe there's some bug there that it's causing your problems. And sometimes you have to get even higher in the chain...

One of these situations is an issue that I've talked about in the post about uploads in CKEditor, I did try to apply an onChange listener for an uiElement with type="file", but it didn't work. After debugging the issue I found that despite the huge differences in DOM (this element was created as an iframe with a form and the <input type="file">), the event listeners aren't aware of this difference, so they apply the listeners to the container <div>.

This week I've been writing the code to fix this problem (that's the beauty of open source, when a problem is spotted it's possible to really check what's going on under the hood and create the patch without waiting for a company to include it in their plans), and after some tests it seemed to work: as soon as the user picks an image from their computer it is uploaded to the server and they just have to review the Alt attribute, the Class or the Title.

I had to review that the events are being reapplied correctly when the iframe recreates, so the tests (somewhat random) also included uploading non image files to verify that they are handled properly and everything still works.

Then I started to find that something was wrong, I selected an application, the file picker showed the name but there was no message. I debugged it further and the onChange event was being correctly fired (well, at first it was fired too many times due to a bug in the logic to append the listeners, but this is what these tests were about).

Maybe not CKEditor?

I had this form inside an iframe in a lot of nested code with lots of javascript, custom events and God knows what else. The next step was to create a simple testcase to focus on the problem:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
    <head>
    <title>Upload test</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <script type="text/javascript">
            function fileChanged(e)
            {
                var input = document.getElementById("upload");
                console.log("Selected file: " + input.value);
                //input.form.submit();
            }
        </script>
    </head>
<body>
    <form method="POST" enctype="multipart/form-data">
        <input type="file" name="upload" id="upload" onchange="fileChanged(event)">
        <input type="submit">
    </form>
</body>
</html>

This showed that I could select any file and it showed the name correctly and the form was posted by pressing the submit button or with the js call. But if I selected an application (I'm using currently a MacBook) then it showed the name and the form wasn't submitted. No error message, no warning, nothing.

The simple test removed CKEditor out of the equation and avoided long hours trying to find a non-existing problem in that code, and instead it pointed to some other basic issue with the browser and the upload of Applications (.app)

The current browser was Firefox 3.5, so I searched bugzilla but I wasn't able to find any report about this, the only bug that reported some strange problem was one about sending sometimes files with 0 size to the server.

So I added

                console.log("File size: " + input.files[0].fileSize);

and it showed the .app to be files of 0 size.

Something is quite wrong here!. I tested Safari and it seemed to allow the upload the .app but it showed the size as 102 bytes instead of several Mb.

Then I finally realized that an Application in Mac OS X is really a folder with subfolders and files, so this is the reason why it fails. Firefox accepts the .app in the filepicker but at the upload time it somehow sees that it is a folder (or that it isn't a real file) and rejects to send the form, but as I said, there's no warning about the problem. Testing with Opera did provide a message stating that the path pointed to some file that it couldn't find.

The most interesting situation was Safari, I changed the form to point to a real script that would handle the file and the result was that the application has been compressed on the fly and sent to the server as a .zip

How does each browser behave?

This is a live test with some code similar to the above:

So on one hand we have Firefox, it doesn't allow to upload the .app and doesn't provide any hint that there's a problem with the selected file. Also shows the size as 0.

Opera does its job much better and shows a tooltip on the <input type="file"> explaining that there's a problem there. Better but still not good enough as people might get confused about the reason of the problem. It hasn't implemented the API to get the size of a selected file.

Safari is quite different, if you select an .app then it will compress it and send it as a .zip so even if the user might find it a little strange that it has bothered to compress the data he finds that he was able to upload the file that he wanted. The only issue is that it shows the size as 102 instead of showing the same data that it's in the Finder.

The final test was the new beta of Google Chrome. Like Safari it showed the size of an .app as 102 bytes, but when I tried to upload it to the server (localhost) it just hanged. It showed a warning about a non responding page and no matter if I selected to close the page or ignore the warning. Chrome was dead and the only solution was to force quit it, even if the tab can be closed, something remains working there that didn't allow a clean exit.

So this can lead to one bug report for each browser (well Opera is almost OK, so it should be just a feature request), so much fun and job for a little test trying to find a bug in my code or CKEditor.

2009/12/11

Adjusting the context menu of CKEditor

The easyUpload plugin aims to replace the default image & link plugins as they can be seen as too complex, so we can expect that the config won't include their buttons in the toolbar, but the context menu entries will still be shown even if the command isn't available in the toolbar.

So you might think that it's just a matter of removing the "image" plugin, but you'll find that the context menu is still there. After a little digging you might be able that this is due because the "forms" plugin has stated that "image" is a requirement (for the input type="image). Then the next step would be to remove the forms plugin, but maybe that's a little too much.

Or what about the link plugin? It does include the unlink command as well as the anchor, so if we remove that plugin we need to copy all that code to another file.

The solution would be to remove just the context menu entries for those items that we don't want. In order to do this you need to study a little how the context menu plugin works and you'll find that it stores the available items in an object: editor._.menuItems and when the context menu is fired, every listener returns the object that should be shown at that time, but if that entry doesn't in the editor._.menuItems then it just skips that order.

So we can do this in our plugin to remove the context menu for the image plugin:

    afterInit: function(editor)
    {
        delete editor._.menuItems.image;
    },

On the other side, this plugin creates its own entries for images and links, but maybe you want to use only the new image dialog, so we need to apply some cleanup to the context menu.

Then instead of just hardcoding the elements to remove from the context menu the approach is to review the elements that are defined for the toolbar comparing them with a list of items that can be removed if they aren't used and then finally remove from the context menu all such items.

    afterInit: function(editor)
    {
        // Remove the default context menu for elements that aren't being used in the toolbar.
        // This object is composed of the button name and the name of the context menu entry
        var removableEntries = {Image:'image',Link:'link',Unlink:'unlink',EasyImage:'easyimage',EasyLink:'easylink',EasyUnlink:'easyunlink'},
            // Get the data that is being used for the toolbar, we end with an array of arrays.
            toolbar =
                    ( editor.config.toolbar instanceof Array ) ?
                        editor.config.toolbar
                    :
                        editor.config[ 'toolbar_' + editor.config.toolbar ];

        // Loop the main array (composed of groups of commands)
        for (var i=0; i<toolbar.length; i++)
        {
            var items = toolbar[i];
            if (!items)
                continue;
           
            for (var j=0; j<items.length; j++)
            {
                var buttonName = items[j];
                // If it was marked at our check object remove it because it's in use
                if (removableEntries[buttonName])
                    delete removableEntries[buttonName] ;
            }
        }
       
        // Remove all the entries that aren't used in the toolbar
        for (var command in removableEntries)
            delete editor._.menuItems[ removableEntries[command] ];
    },

With this code our plugin will take care of leaving only the correct entries in the context menu without any extra configuration

2009/12/09

Plugin localization in CKEditor (vs FCKeditor)

If you work in the web you should have already realized that there are tons of people from every where and that not all of them speak English, and even if they are able to understand it they might to work with their native tonge, so providing the ability to translate your plugins it's important if you want them to be used anywhere.

Adding the plugin

In FCKeditor the registration call of the plugin did specify the available languages:

FCKConfig.Plugins.Add( 'easyupload', 'de,en') ;

In CKEditor there's no call to add a plugin, just a list of plugins and two other lists to add extra plugins or remove existing ones (each list is just a comma separated string with the names of the plugins). So that call would be something along the lines:

config.extraPlugins = 'easyupload';

But that doesn't specify the languages available for the plugin, now instead is the plugin itself the one that specifies what are its available languages:

CKEDITOR.plugins.add( 'easyupload',
{
    // translations
    lang : ['en'],
...

The translation file

The available translations must be placed as previously under the pluginfolder/lang/languagecode.js being pluginfolder the name of your plugin and languagecode the code of the language ('en' in the above case), so we would end with a file under plugins/easyupload/lang/en.js for example.

The structure of this file is quite different from the previous one. In FCKeditor the file was a simple list of properties added to the FCKLang object:

FCKLang['EuImgDialogTitle']  = 'Insert / Edit Image' ;

Now the file is made of one (or several depending on how you have defined your data) call to the CKEDITOR.plugins.setLang method that gets as parameters the name of the plugin, the language code and an object that contains the definitions of the strings:

CKEDITOR.plugins.setLang( 'easyupload', 'en',
    {
        easyimage :
        {
            toolbar: 'Insert/Edit an image',
...
        }
    }
)

Usage

And so the way to use it now is also slightly different, the "lang" object of the current editor instance has been augmented with your definitions:

        editor.ui.addButton( 'EasyImage',
            {
                label : editor.lang.easyimage.toolbar,
                command : 'easyimage',
                icon : this.path + 'images/image.gif'
            } );

Dialogs

Now all the dialogs are created from javascript objects, there are no html parts to load so there is no need for the "fcklang" attribute and the call to FCKLanguageManager.TranslatePage(document)