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