JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
c9d9877dc1c1e5fb410427c1b9a9301a71800936
[ckeditor.git] / _source / core / tools.js
1 /*\r
2 Copyright (c) 2003-2009, CKSource - Frederico Knabben. All rights reserved.\r
3 For licensing, see LICENSE.html or http://ckeditor.com/license\r
4 */\r
5 \r
6 /**\r
7  * @fileOverview Defines the {@link CKEDITOR.tools} object, which contains\r
8  *              utility functions.\r
9  */\r
10 \r
11 (function()\r
12 {\r
13         var functions = [];\r
14 \r
15         /**\r
16          * Utility functions.\r
17          * @namespace\r
18          * @example\r
19          */\r
20         CKEDITOR.tools =\r
21         {\r
22                 /**\r
23                  * Compare the elements of two arrays.\r
24                  * @param {Array} arrayA An array to be compared.\r
25                  * @param {Array} arrayB The other array to be compared.\r
26                  * @returns {Boolean} "true" is the arrays have the same lenght and\r
27                  *              their elements match.\r
28                  * @example\r
29                  * var a = [ 1, 'a', 3 ];\r
30                  * var b = [ 1, 3, 'a' ];\r
31                  * var c = [ 1, 'a', 3 ];\r
32                  * var d = [ 1, 'a', 3, 4 ];\r
33                  *\r
34                  * alert( CKEDITOR.tools.arrayCompare( a, b ) );  // false\r
35                  * alert( CKEDITOR.tools.arrayCompare( a, c ) );  // true\r
36                  * alert( CKEDITOR.tools.arrayCompare( a, d ) );  // false\r
37                  */\r
38                 arrayCompare : function( arrayA, arrayB )\r
39                 {\r
40                         if ( !arrayA && !arrayB )\r
41                                 return true;\r
42 \r
43                         if ( !arrayA || !arrayB || arrayA.length != arrayB.length )\r
44                                 return false;\r
45 \r
46                         for ( var i = 0 ; i < arrayA.length ; i++ )\r
47                         {\r
48                                 if ( arrayA[ i ] != arrayB[ i ] )\r
49                                         return false;\r
50                         }\r
51 \r
52                         return true;\r
53                 },\r
54 \r
55                 /**\r
56                  * Creates a deep copy of an object.\r
57                  * Attention: there is no support for recursive references.\r
58                  * @param {Object} object The object to be cloned.\r
59                  * @returns {Object} The object clone.\r
60                  * @example\r
61                  * var obj =\r
62                  *     {\r
63                  *         name : 'John',\r
64                  *         cars :\r
65                  *             {\r
66                  *                 Mercedes : { color : 'blue' },\r
67                  *                 Porsche : { color : 'red' }\r
68                  *             }\r
69                  *     };\r
70                  * var clone = CKEDITOR.tools.clone( obj );\r
71                  * clone.name = 'Paul';\r
72                  * clone.cars.Porsche.color = 'silver';\r
73                  * alert( obj.name );   // John\r
74                  * alert( clone.name ); // Paul\r
75                  * alert( obj.cars.Porsche.color );     // red\r
76                  * alert( clone.cars.Porsche.color );   // silver\r
77                  */\r
78                 clone : function( obj )\r
79                 {\r
80                         var clone;\r
81 \r
82                         // Array.\r
83                         if ( obj && ( obj instanceof Array ) )\r
84                         {\r
85                                 clone = [];\r
86 \r
87                                 for ( var i = 0 ; i < obj.length ; i++ )\r
88                                         clone[ i ] = this.clone( obj[ i ] );\r
89 \r
90                                 return clone;\r
91                         }\r
92 \r
93                         // "Static" types.\r
94                         if ( obj === null\r
95                                 || ( typeof( obj ) != 'object' )\r
96                                 || ( obj instanceof String )\r
97                                 || ( obj instanceof Number )\r
98                                 || ( obj instanceof Boolean )\r
99                                 || ( obj instanceof Date ) )\r
100                         {\r
101                                 return obj;\r
102                         }\r
103 \r
104                         // Objects.\r
105                         clone = new obj.constructor();\r
106 \r
107                         for ( var propertyName in obj )\r
108                         {\r
109                                 var property = obj[ propertyName ];\r
110                                 clone[ propertyName ] = this.clone( property );\r
111                         }\r
112 \r
113                         return clone;\r
114                 },\r
115 \r
116                 /**\r
117                  * Copy the properties from one object to another. By default, properties\r
118                  * already present in the target object <strong>are not</strong> overwritten.\r
119                  * @param {Object} target The object to be extended.\r
120                  * @param {Object} source[,souce(n)] The objects from which copy\r
121                  *              properties. Any number of objects can be passed to this function.\r
122                  * @param {Boolean} [overwrite] If 'true' is specified it indicates that\r
123                  *            properties already present in the target object could be\r
124                  *            overwritten by subsequent objects.\r
125                  * @param {Object} [properties] Only properties within the specified names\r
126                  *            list will be received from the source object.\r
127                  * @returns {Object} the extended object (target).\r
128                  * @example\r
129                  * // Create the sample object.\r
130                  * var myObject =\r
131                  * {\r
132                  *     prop1 : true\r
133                  * };\r
134                  *\r
135                  * // Extend the above object with two properties.\r
136                  * CKEDITOR.tools.extend( myObject,\r
137                  *     {\r
138                  *         prop2 : true,\r
139                  *         prop3 : true\r
140                  *     } );\r
141                  *\r
142                  * // Alert "prop1", "prop2" and "prop3".\r
143                  * for ( var p in myObject )\r
144                  *     alert( p );\r
145                  */\r
146                 extend : function( target )\r
147                 {\r
148                         var argsLength = arguments.length,\r
149                                 overwrite, propertiesList;\r
150 \r
151                         if ( typeof ( overwrite = arguments[ argsLength - 1 ] ) == 'boolean')\r
152                                 argsLength--;\r
153                         else if ( typeof ( overwrite = arguments[ argsLength - 2 ] ) == 'boolean' )\r
154                         {\r
155                                 propertiesList = arguments [ argsLength -1 ];\r
156                                 argsLength-=2;\r
157                         }\r
158                         for ( var i = 1 ; i < argsLength ; i++ )\r
159                         {\r
160                                 var source = arguments[ i ];\r
161                                 for ( var propertyName in source )\r
162                                 {\r
163                                         // Only copy existed fields if in overwrite mode.\r
164                                         if ( overwrite === true || target[ propertyName ] == undefined )\r
165                                         {\r
166                                                 // Only copy  specified fields if list is provided.\r
167                                                 if ( !propertiesList || ( propertyName in propertiesList ) )\r
168                                                         target[ propertyName ] = source[ propertyName ];\r
169 \r
170                                         }\r
171                                 }\r
172                         }\r
173 \r
174                         return target;\r
175                 },\r
176 \r
177                 /**\r
178                  * Creates an object which is an instance of a class which prototype is a\r
179                  * predefined object. All properties defined in the source object are\r
180                  * automatically inherited by the resulting object, including future\r
181                  * changes to it.\r
182                  * @param {Object} source The source object to be used as the prototype for\r
183                  *              the final object.\r
184                  * @returns {Object} The resulting copy.\r
185                  */\r
186                 prototypedCopy : function( source )\r
187                 {\r
188                         var copy = function()\r
189                         {};\r
190                         copy.prototype = source;\r
191                         return new copy();\r
192                 },\r
193 \r
194                 /**\r
195                  * Checks if an object is an Array.\r
196                  * @param {Object} object The object to be checked.\r
197                  * @type Boolean\r
198                  * @returns <i>true</i> if the object is an Array, otherwise <i>false</i>.\r
199                  * @example\r
200                  * alert( CKEDITOR.tools.isArray( [] ) );      // "true"\r
201                  * alert( CKEDITOR.tools.isArray( 'Test' ) );  // "false"\r
202                  */\r
203                 isArray : function( object )\r
204                 {\r
205                         return ( !!object && object instanceof Array );\r
206                 },\r
207 \r
208                 isEmpty : function ( object )\r
209                 {\r
210                         for ( var i in object )\r
211                         {\r
212                                 if ( object.hasOwnProperty( i ) )\r
213                                         return false;\r
214                         }\r
215                         return true;\r
216                 },\r
217                 /**\r
218                  * Transforms a CSS property name to its relative DOM style name.\r
219                  * @param {String} cssName The CSS property name.\r
220                  * @returns {String} The transformed name.\r
221                  * @example\r
222                  * alert( CKEDITOR.tools.cssStyleToDomStyle( 'background-color' ) );  // "backgroundColor"\r
223                  * alert( CKEDITOR.tools.cssStyleToDomStyle( 'float' ) );             // "cssFloat"\r
224                  */\r
225                 cssStyleToDomStyle : ( function()\r
226                 {\r
227                         var test = document.createElement( 'div' ).style;\r
228 \r
229                         var cssFloat = ( typeof test.cssFloat != 'undefined' ) ? 'cssFloat'\r
230                                 : ( typeof test.styleFloat != 'undefined' ) ? 'styleFloat'\r
231                                 : 'float';\r
232 \r
233                         return function( cssName )\r
234                         {\r
235                                 if ( cssName == 'float' )\r
236                                         return cssFloat;\r
237                                 else\r
238                                 {\r
239                                         return cssName.replace( /-./g, function( match )\r
240                                                 {\r
241                                                         return match.substr( 1 ).toUpperCase();\r
242                                                 });\r
243                                 }\r
244                         };\r
245                 } )(),\r
246 \r
247                 /**\r
248                  * Replace special HTML characters in a string with their relative HTML\r
249                  * entity values.\r
250                  * @param {String} text The string to be encoded.\r
251                  * @returns {String} The encode string.\r
252                  * @example\r
253                  * alert( CKEDITOR.tools.htmlEncode( 'A > B & C < D' ) );  // "A &amp;gt; B &amp;amp; C &amp;lt; D"\r
254                  */\r
255                 htmlEncode : function( text )\r
256                 {\r
257                         var standard = function( text )\r
258                         {\r
259                                 var span = new CKEDITOR.dom.element( 'span' );\r
260                                 span.setText( text );\r
261                                 return span.getHtml();\r
262                         };\r
263 \r
264                         var fix1 = ( standard( '\n' ).toLowerCase() == '<br>' ) ?\r
265                                 function( text )\r
266                                 {\r
267                                         // #3874 IE and Safari encode line-break into <br>\r
268                                         return standard( text ).replace( /<br>/gi, '\n' );\r
269                                 } :\r
270                                 standard;\r
271 \r
272                         var fix2 = ( standard( '>' ) == '>' ) ?\r
273                                 function( text )\r
274                                 {\r
275                                         // WebKit does't encode the ">" character, which makes sense, but\r
276                                         // it's different than other browsers.\r
277                                         return fix1( text ).replace( />/g, '&gt;' );\r
278                                 } :\r
279                                 fix1;\r
280 \r
281                         var fix3 = ( standard( '  ' ) == '&nbsp; ' ) ?\r
282                                 function( text )\r
283                                 {\r
284                                         // #3785 IE8 changes spaces (>= 2) to &nbsp;\r
285                                         return fix2( text ).replace( /&nbsp;/g, ' ' );\r
286                                 } :\r
287                                 fix2;\r
288 \r
289                         this.htmlEncode = fix3;\r
290 \r
291                         return this.htmlEncode( text );\r
292                 },\r
293 \r
294                 /**\r
295                  * Replace characters can't be represented through CSS Selectors string\r
296                  * by CSS Escape Notation where the character escape sequence consists\r
297                  * of a backslash character (\) followed by the orginal characters.\r
298                  * Ref: http://www.w3.org/TR/css3-selectors/#grammar\r
299                  * @param cssSelectText\r
300                  * @return the escaped selector text.\r
301                  */\r
302                 escapeCssSelector : function( cssSelectText )\r
303                 {\r
304                         return cssSelectText.replace( /[\s#:.,$*^\[\]()~=+>]/g, '\\$&' );\r
305                 },\r
306 \r
307                 /**\r
308                  * Gets a unique number for this CKEDITOR execution session. It returns\r
309                  * progressive numbers starting at 1.\r
310                  * @function\r
311                  * @returns {Number} A unique number.\r
312                  * @example\r
313                  * alert( CKEDITOR.tools.<b>getNextNumber()</b> );  // "1" (e.g.)\r
314                  * alert( CKEDITOR.tools.<b>getNextNumber()</b> );  // "2"\r
315                  */\r
316                 getNextNumber : (function()\r
317                 {\r
318                         var last = 0;\r
319                         return function()\r
320                         {\r
321                                 return ++last;\r
322                         };\r
323                 })(),\r
324 \r
325                 /**\r
326                  * Creates a function override.\r
327                  * @param {Function} originalFunction The function to be overridden.\r
328                  * @param {Function} functionBuilder A function that returns the new\r
329                  *              function. The original function reference will be passed to this\r
330                  *              function.\r
331                  * @returns {Function} The new function.\r
332                  * @example\r
333                  * var example =\r
334                  * {\r
335                  *     myFunction : function( name )\r
336                  *     {\r
337                  *         alert( 'Name: ' + name );\r
338                  *     }\r
339                  * };\r
340                  *\r
341                  * example.myFunction = CKEDITOR.tools.override( example.myFunction, function( myFunctionOriginal )\r
342                  *     {\r
343                  *         return function( name )\r
344                  *             {\r
345                  *                 alert( 'Override Name: ' + name );\r
346                  *                 myFunctionOriginal.call( this, name );\r
347                  *             };\r
348                  *     });\r
349                  */\r
350                 override : function( originalFunction, functionBuilder )\r
351                 {\r
352                         return functionBuilder( originalFunction );\r
353                 },\r
354 \r
355                 /**\r
356                  * Executes a function after specified delay.\r
357                  * @param {Function} func The function to be executed.\r
358                  * @param {Number} [milliseconds] The amount of time (millisecods) to wait\r
359                  *              to fire the function execution. Defaults to zero.\r
360                  * @param {Object} [scope] The object to hold the function execution scope\r
361                  *              (the "this" object). By default the "window" object.\r
362                  * @param {Object|Array} [args] A single object, or an array of objects, to\r
363                  *              pass as arguments to the function.\r
364                  * @param {Object} [ownerWindow] The window that will be used to set the\r
365                  *              timeout. By default the current "window".\r
366                  * @returns {Object} A value that can be used to cancel the function execution.\r
367                  * @example\r
368                  * CKEDITOR.tools.<b>setTimeout(\r
369                  *     function()\r
370                  *     {\r
371                  *         alert( 'Executed after 2 seconds' );\r
372                  *     },\r
373                  *     2000 )</b>;\r
374                  */\r
375                 setTimeout : function( func, milliseconds, scope, args, ownerWindow )\r
376                 {\r
377                         if ( !ownerWindow )\r
378                                 ownerWindow = window;\r
379 \r
380                         if ( !scope )\r
381                                 scope = ownerWindow;\r
382 \r
383                         return ownerWindow.setTimeout(\r
384                                 function()\r
385                                 {\r
386                                         if ( args )\r
387                                                 func.apply( scope, [].concat( args ) ) ;\r
388                                         else\r
389                                                 func.apply( scope ) ;\r
390                                 },\r
391                                 milliseconds || 0 );\r
392                 },\r
393 \r
394                 /**\r
395                  * Remove spaces from the start and the end of a string. The following\r
396                  * characters are removed: space, tab, line break, line feed.\r
397                  * @function\r
398                  * @param {String} str The text from which remove the spaces.\r
399                  * @returns {String} The modified string without the boundary spaces.\r
400                  * @example\r
401                  * alert( CKEDITOR.tools.trim( '  example ' );  // "example"\r
402                  */\r
403                 trim : (function()\r
404                 {\r
405                         // We are not using \s because we don't want "non-breaking spaces" to be caught.\r
406                         var trimRegex = /(?:^[ \t\n\r]+)|(?:[ \t\n\r]+$)/g;\r
407                         return function( str )\r
408                         {\r
409                                 return str.replace( trimRegex, '' ) ;\r
410                         };\r
411                 })(),\r
412 \r
413                 /**\r
414                  * Remove spaces from the start (left) of a string. The following\r
415                  * characters are removed: space, tab, line break, line feed.\r
416                  * @function\r
417                  * @param {String} str The text from which remove the spaces.\r
418                  * @returns {String} The modified string excluding the removed spaces.\r
419                  * @example\r
420                  * alert( CKEDITOR.tools.ltrim( '  example ' );  // "example "\r
421                  */\r
422                 ltrim : (function()\r
423                 {\r
424                         // We are not using \s because we don't want "non-breaking spaces" to be caught.\r
425                         var trimRegex = /^[ \t\n\r]+/g;\r
426                         return function( str )\r
427                         {\r
428                                 return str.replace( trimRegex, '' ) ;\r
429                         };\r
430                 })(),\r
431 \r
432                 /**\r
433                  * Remove spaces from the end (right) of a string. The following\r
434                  * characters are removed: space, tab, line break, line feed.\r
435                  * @function\r
436                  * @param {String} str The text from which remove the spaces.\r
437                  * @returns {String} The modified string excluding the removed spaces.\r
438                  * @example\r
439                  * alert( CKEDITOR.tools.ltrim( '  example ' );  // "  example"\r
440                  */\r
441                 rtrim : (function()\r
442                 {\r
443                         // We are not using \s because we don't want "non-breaking spaces" to be caught.\r
444                         var trimRegex = /[ \t\n\r]+$/g;\r
445                         return function( str )\r
446                         {\r
447                                 return str.replace( trimRegex, '' ) ;\r
448                         };\r
449                 })(),\r
450 \r
451                 /**\r
452                  * Returns the index of an element in an array.\r
453                  * @param {Array} array The array to be searched.\r
454                  * @param {Object} entry The element to be found.\r
455                  * @returns {Number} The (zero based) index of the first entry that matches\r
456                  *              the entry, or -1 if not found.\r
457                  * @example\r
458                  * var letters = [ 'a', 'b', 0, 'c', false ];\r
459                  * alert( CKEDITOR.tools.indexOf( letters, '0' ) );  "-1" because 0 !== '0'\r
460                  * alert( CKEDITOR.tools.indexOf( letters, false ) );  "4" because 0 !== false\r
461                  */\r
462                 indexOf :\r
463                         // #2514: We should try to use Array.indexOf if it does exist.\r
464                         ( Array.prototype.indexOf ) ?\r
465                                 function( array, entry )\r
466                                         {\r
467                                                 return array.indexOf( entry );\r
468                                         }\r
469                         :\r
470                                 function( array, entry )\r
471                                 {\r
472                                         for ( var i = 0, len = array.length ; i < len ; i++ )\r
473                                         {\r
474                                                 if ( array[ i ] === entry )\r
475                                                         return i;\r
476                                         }\r
477                                         return -1;\r
478                                 },\r
479 \r
480                 /**\r
481                  * Creates a function that will always execute in the context of a\r
482                  * specified object.\r
483                  * @param {Function} func The function to be executed.\r
484                  * @param {Object} obj The object to which bind the execution context.\r
485                  * @returns {Function} The function that can be used to execute the\r
486                  *              "func" function in the context of "obj".\r
487                  * @example\r
488                  * var obj = { text : 'My Object' };\r
489                  *\r
490                  * function alertText()\r
491                  * {\r
492                  *     alert( this.text );\r
493                  * }\r
494                  *\r
495                  * var newFunc = <b>CKEDITOR.tools.bind( alertText, obj )</b>;\r
496                  * newFunc();  // Alerts "My Object".\r
497                  */\r
498                 bind : function( func, obj )\r
499                 {\r
500                         return function() { return func.apply( obj, arguments ); };\r
501                 },\r
502 \r
503                 /**\r
504                  * Class creation based on prototype inheritance, with supports of the\r
505                  * following features:\r
506                  * <ul>\r
507                  * <li> Static fields </li>\r
508                  * <li> Private fields </li>\r
509                  * <li> Public (prototype) fields </li>\r
510                  * <li> Chainable base class constructor </li>\r
511                  * </ul>\r
512                  * @param {Object} definiton The class definiton object.\r
513                  * @returns {Function} A class-like JavaScript function.\r
514                  */\r
515                 createClass : function( definition )\r
516                 {\r
517                         var $ = definition.$,\r
518                                 baseClass = definition.base,\r
519                                 privates = definition.privates || definition._,\r
520                                 proto = definition.proto,\r
521                                 statics = definition.statics;\r
522 \r
523                         if ( privates )\r
524                         {\r
525                                 var originalConstructor = $;\r
526                                 $ = function()\r
527                                 {\r
528                                         // Create (and get) the private namespace.\r
529                                         var _ = this._ || ( this._ = {} );\r
530 \r
531                                         // Make some magic so "this" will refer to the main\r
532                                         // instance when coding private functions.\r
533                                         for ( var privateName in privates )\r
534                                         {\r
535                                                 var priv = privates[ privateName ];\r
536 \r
537                                                 _[ privateName ] =\r
538                                                         ( typeof priv == 'function' ) ? CKEDITOR.tools.bind( priv, this ) : priv;\r
539                                         }\r
540 \r
541                                         originalConstructor.apply( this, arguments );\r
542                                 };\r
543                         }\r
544 \r
545                         if ( baseClass )\r
546                         {\r
547                                 $.prototype = this.prototypedCopy( baseClass.prototype );\r
548                                 $.prototype.constructor = $;\r
549                                 $.prototype.base = function()\r
550                                 {\r
551                                         this.base = baseClass.prototype.base;\r
552                                         baseClass.apply( this, arguments );\r
553                                         this.base = arguments.callee;\r
554                                 };\r
555                         }\r
556 \r
557                         if ( proto )\r
558                                 this.extend( $.prototype, proto, true );\r
559 \r
560                         if ( statics )\r
561                                 this.extend( $, statics, true );\r
562 \r
563                         return $;\r
564                 },\r
565 \r
566                 /**\r
567                  * Creates a function reference that can be called later using\r
568                  * CKEDITOR.tools.callFunction. This approach is specially useful to\r
569                  * make DOM attribute function calls to JavaScript defined functions.\r
570                  * @param {Function} fn The function to be executed on call.\r
571                  * @param {Object} [scope] The object to have the context on "fn" execution.\r
572                  * @returns {Number} A unique reference to be used in conjuction with\r
573                  *              CKEDITOR.tools.callFunction.\r
574                  * @example\r
575                  * var ref = <b>CKEDITOR.tools.addFunction</b>(\r
576                  *     function()\r
577                  *     {\r
578                  *         alert( 'Hello!');\r
579                  *     });\r
580                  * CKEDITOR.tools.callFunction( ref );  // Hello!\r
581                  */\r
582                 addFunction : function( fn, scope )\r
583                 {\r
584                         return functions.push( function()\r
585                                 {\r
586                                         fn.apply( scope || this, arguments );\r
587                                 }) - 1;\r
588                 },\r
589 \r
590                 /**\r
591                  * Executes a function based on the reference created with\r
592                  * CKEDITOR.tools.addFunction.\r
593                  * @param {Number} ref The function reference created with\r
594                  *              CKEDITOR.tools.addFunction.\r
595                  * @param {[Any,[Any,...]} params Any number of parameters to be passed\r
596                  *              to the executed function.\r
597                  * @returns {Any} The return value of the function.\r
598                  * @example\r
599                  * var ref = CKEDITOR.tools.addFunction(\r
600                  *     function()\r
601                  *     {\r
602                  *         alert( 'Hello!');\r
603                  *     });\r
604                  * <b>CKEDITOR.tools.callFunction( ref )</b>;  // Hello!\r
605                  */\r
606                 callFunction : function( ref )\r
607                 {\r
608                         var fn = functions[ ref ];\r
609                         return fn && fn.apply( window, Array.prototype.slice.call( arguments, 1 ) );\r
610                 },\r
611 \r
612                 cssLength : (function()\r
613                 {\r
614                         var decimalRegex = /^\d+(?:\.\d+)?$/;\r
615                         return function( length )\r
616                         {\r
617                                 return length + ( decimalRegex.test( length ) ? 'px' : '' );\r
618                         };\r
619                 })(),\r
620 \r
621                 repeat : function( str, times )\r
622                 {\r
623                         return new Array( times + 1 ).join( str );\r
624                 }\r
625         };\r
626 })();\r
627 \r
628 // PACKAGER_RENAME( CKEDITOR.tools )\r