2 Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
\r
3 For licensing, see LICENSE.html or http://ckeditor.com/license
\r
7 * @fileOverview Defines the {@link CKEDITOR.tools} object, which contains
\r
15 CKEDITOR.on( 'reset', function()
\r
21 * Utility functions.
\r
28 * Compare the elements of two arrays.
\r
29 * @param {Array} arrayA An array to be compared.
\r
30 * @param {Array} arrayB The other array to be compared.
\r
31 * @returns {Boolean} "true" is the arrays have the same lenght and
\r
32 * their elements match.
\r
34 * var a = [ 1, 'a', 3 ];
\r
35 * var b = [ 1, 3, 'a' ];
\r
36 * var c = [ 1, 'a', 3 ];
\r
37 * var d = [ 1, 'a', 3, 4 ];
\r
39 * alert( CKEDITOR.tools.arrayCompare( a, b ) ); // false
\r
40 * alert( CKEDITOR.tools.arrayCompare( a, c ) ); // true
\r
41 * alert( CKEDITOR.tools.arrayCompare( a, d ) ); // false
\r
43 arrayCompare : function( arrayA, arrayB )
\r
45 if ( !arrayA && !arrayB )
\r
48 if ( !arrayA || !arrayB || arrayA.length != arrayB.length )
\r
51 for ( var i = 0 ; i < arrayA.length ; i++ )
\r
53 if ( arrayA[ i ] != arrayB[ i ] )
\r
61 * Creates a deep copy of an object.
\r
62 * Attention: there is no support for recursive references.
\r
63 * @param {Object} object The object to be cloned.
\r
64 * @returns {Object} The object clone.
\r
71 * Mercedes : { color : 'blue' },
\r
72 * Porsche : { color : 'red' }
\r
75 * var clone = CKEDITOR.tools.clone( obj );
\r
76 * clone.name = 'Paul';
\r
77 * clone.cars.Porsche.color = 'silver';
\r
78 * alert( obj.name ); // John
\r
79 * alert( clone.name ); // Paul
\r
80 * alert( obj.cars.Porsche.color ); // red
\r
81 * alert( clone.cars.Porsche.color ); // silver
\r
83 clone : function( obj )
\r
88 if ( obj && ( obj instanceof Array ) )
\r
92 for ( var i = 0 ; i < obj.length ; i++ )
\r
93 clone[ i ] = this.clone( obj[ i ] );
\r
100 || ( typeof( obj ) != 'object' )
\r
101 || ( obj instanceof String )
\r
102 || ( obj instanceof Number )
\r
103 || ( obj instanceof Boolean )
\r
104 || ( obj instanceof Date )
\r
105 || ( obj instanceof RegExp) )
\r
111 clone = new obj.constructor();
\r
113 for ( var propertyName in obj )
\r
115 var property = obj[ propertyName ];
\r
116 clone[ propertyName ] = this.clone( property );
\r
123 * Turn the first letter of string to upper-case.
\r
124 * @param {String} str
\r
126 capitalize: function( str )
\r
128 return str.charAt( 0 ).toUpperCase() + str.substring( 1 ).toLowerCase();
\r
132 * Copy the properties from one object to another. By default, properties
\r
133 * already present in the target object <strong>are not</strong> overwritten.
\r
134 * @param {Object} target The object to be extended.
\r
135 * @param {Object} source[,souce(n)] The objects from which copy
\r
136 * properties. Any number of objects can be passed to this function.
\r
137 * @param {Boolean} [overwrite] If 'true' is specified it indicates that
\r
138 * properties already present in the target object could be
\r
139 * overwritten by subsequent objects.
\r
140 * @param {Object} [properties] Only properties within the specified names
\r
141 * list will be received from the source object.
\r
142 * @returns {Object} the extended object (target).
\r
144 * // Create the sample object.
\r
150 * // Extend the above object with two properties.
\r
151 * CKEDITOR.tools.extend( myObject,
\r
157 * // Alert "prop1", "prop2" and "prop3".
\r
158 * for ( var p in myObject )
\r
161 extend : function( target )
\r
163 var argsLength = arguments.length,
\r
164 overwrite, propertiesList;
\r
166 if ( typeof ( overwrite = arguments[ argsLength - 1 ] ) == 'boolean')
\r
168 else if ( typeof ( overwrite = arguments[ argsLength - 2 ] ) == 'boolean' )
\r
170 propertiesList = arguments [ argsLength -1 ];
\r
173 for ( var i = 1 ; i < argsLength ; i++ )
\r
175 var source = arguments[ i ];
\r
176 for ( var propertyName in source )
\r
178 // Only copy existed fields if in overwrite mode.
\r
179 if ( overwrite === true || target[ propertyName ] == undefined )
\r
181 // Only copy specified fields if list is provided.
\r
182 if ( !propertiesList || ( propertyName in propertiesList ) )
\r
183 target[ propertyName ] = source[ propertyName ];
\r
193 * Creates an object which is an instance of a class which prototype is a
\r
194 * predefined object. All properties defined in the source object are
\r
195 * automatically inherited by the resulting object, including future
\r
197 * @param {Object} source The source object to be used as the prototype for
\r
198 * the final object.
\r
199 * @returns {Object} The resulting copy.
\r
201 prototypedCopy : function( source )
\r
203 var copy = function()
\r
205 copy.prototype = source;
\r
210 * Checks if an object is an Array.
\r
211 * @param {Object} object The object to be checked.
\r
213 * @returns <i>true</i> if the object is an Array, otherwise <i>false</i>.
\r
215 * alert( CKEDITOR.tools.isArray( [] ) ); // "true"
\r
216 * alert( CKEDITOR.tools.isArray( 'Test' ) ); // "false"
\r
218 isArray : function( object )
\r
220 return ( !!object && object instanceof Array );
\r
224 * Whether the object contains no properties of it's own.
\r
227 isEmpty : function ( object )
\r
229 for ( var i in object )
\r
231 if ( object.hasOwnProperty( i ) )
\r
238 * Transforms a CSS property name to its relative DOM style name.
\r
239 * @param {String} cssName The CSS property name.
\r
240 * @returns {String} The transformed name.
\r
242 * alert( CKEDITOR.tools.cssStyleToDomStyle( 'background-color' ) ); // "backgroundColor"
\r
243 * alert( CKEDITOR.tools.cssStyleToDomStyle( 'float' ) ); // "cssFloat"
\r
245 cssStyleToDomStyle : ( function()
\r
247 var test = document.createElement( 'div' ).style;
\r
249 var cssFloat = ( typeof test.cssFloat != 'undefined' ) ? 'cssFloat'
\r
250 : ( typeof test.styleFloat != 'undefined' ) ? 'styleFloat'
\r
253 return function( cssName )
\r
255 if ( cssName == 'float' )
\r
259 return cssName.replace( /-./g, function( match )
\r
261 return match.substr( 1 ).toUpperCase();
\r
268 * Build the HTML snippet of a set of <style>/<link>.
\r
269 * @param css {String|Array} Each of which are url (absolute) of a CSS file or
\r
270 * a trunk of style text.
\r
272 buildStyleHtml : function ( css )
\r
274 css = [].concat( css );
\r
275 var item, retval = [];
\r
276 for ( var i = 0; i < css.length; i++ )
\r
279 // Is CSS style text ?
\r
280 if ( /@import|[{}]/.test(item) )
\r
281 retval.push('<style>' + item + '</style>');
\r
283 retval.push('<link type="text/css" rel=stylesheet href="' + item + '">');
\r
285 return retval.join( '' );
\r
289 * Replace special HTML characters in a string with their relative HTML
\r
291 * @param {String} text The string to be encoded.
\r
292 * @returns {String} The encode string.
\r
294 * alert( CKEDITOR.tools.htmlEncode( 'A > B & C < D' ) ); // "A &gt; B &amp; C &lt; D"
\r
296 htmlEncode : function( text )
\r
298 var standard = function( text )
\r
300 var span = new CKEDITOR.dom.element( 'span' );
\r
301 span.setText( text );
\r
302 return span.getHtml();
\r
305 var fix1 = ( standard( '\n' ).toLowerCase() == '<br>' ) ?
\r
308 // #3874 IE and Safari encode line-break into <br>
\r
309 return standard( text ).replace( /<br>/gi, '\n' );
\r
313 var fix2 = ( standard( '>' ) == '>' ) ?
\r
316 // WebKit does't encode the ">" character, which makes sense, but
\r
317 // it's different than other browsers.
\r
318 return fix1( text ).replace( />/g, '>' );
\r
322 var fix3 = ( standard( ' ' ) == ' ' ) ?
\r
325 // #3785 IE8 changes spaces (>= 2) to
\r
326 return fix2( text ).replace( / /g, ' ' );
\r
330 this.htmlEncode = fix3;
\r
332 return this.htmlEncode( text );
\r
336 * Replace special HTML characters in HTMLElement's attribute with their relative HTML entity values.
\r
337 * @param {String} The attribute's value to be encoded.
\r
338 * @returns {String} The encode value.
\r
340 * element.setAttribute( 'title', '<a " b >' );
\r
341 * alert( CKEDITOR.tools.htmlEncodeAttr( element.getAttribute( 'title' ) ); // ">a " b <"
\r
343 htmlEncodeAttr : function( text )
\r
345 return text.replace( /"/g, '"' ).replace( /</g, '<' ).replace( />/g, '>' );
\r
349 * Gets a unique number for this CKEDITOR execution session. It returns
\r
350 * progressive numbers starting at 1.
\r
352 * @returns {Number} A unique number.
\r
354 * alert( CKEDITOR.tools.<b>getNextNumber()</b> ); // "1" (e.g.)
\r
355 * alert( CKEDITOR.tools.<b>getNextNumber()</b> ); // "2"
\r
357 getNextNumber : (function()
\r
367 * Gets a unique ID for CKEditor's interface elements. It returns a
\r
368 * string with the "cke_" prefix and a progressive number.
\r
370 * @returns {String} A unique ID.
\r
372 * alert( CKEDITOR.tools.<b>getNextId()</b> ); // "cke_1" (e.g.)
\r
373 * alert( CKEDITOR.tools.<b>getNextId()</b> ); // "cke_2"
\r
375 getNextId : function()
\r
377 return 'cke_' + this.getNextNumber();
\r
381 * Creates a function override.
\r
382 * @param {Function} originalFunction The function to be overridden.
\r
383 * @param {Function} functionBuilder A function that returns the new
\r
384 * function. The original function reference will be passed to this
\r
386 * @returns {Function} The new function.
\r
390 * myFunction : function( name )
\r
392 * alert( 'Name: ' + name );
\r
396 * example.myFunction = CKEDITOR.tools.override( example.myFunction, function( myFunctionOriginal )
\r
398 * return function( name )
\r
400 * alert( 'Override Name: ' + name );
\r
401 * myFunctionOriginal.call( this, name );
\r
405 override : function( originalFunction, functionBuilder )
\r
407 return functionBuilder( originalFunction );
\r
411 * Executes a function after specified delay.
\r
412 * @param {Function} func The function to be executed.
\r
413 * @param {Number} [milliseconds] The amount of time (millisecods) to wait
\r
414 * to fire the function execution. Defaults to zero.
\r
415 * @param {Object} [scope] The object to hold the function execution scope
\r
416 * (the "this" object). By default the "window" object.
\r
417 * @param {Object|Array} [args] A single object, or an array of objects, to
\r
418 * pass as arguments to the function.
\r
419 * @param {Object} [ownerWindow] The window that will be used to set the
\r
420 * timeout. By default the current "window".
\r
421 * @returns {Object} A value that can be used to cancel the function execution.
\r
423 * CKEDITOR.tools.<b>setTimeout(
\r
426 * alert( 'Executed after 2 seconds' );
\r
430 setTimeout : function( func, milliseconds, scope, args, ownerWindow )
\r
432 if ( !ownerWindow )
\r
433 ownerWindow = window;
\r
436 scope = ownerWindow;
\r
438 return ownerWindow.setTimeout(
\r
442 func.apply( scope, [].concat( args ) ) ;
\r
444 func.apply( scope ) ;
\r
446 milliseconds || 0 );
\r
450 * Remove spaces from the start and the end of a string. The following
\r
451 * characters are removed: space, tab, line break, line feed.
\r
453 * @param {String} str The text from which remove the spaces.
\r
454 * @returns {String} The modified string without the boundary spaces.
\r
456 * alert( CKEDITOR.tools.trim( ' example ' ); // "example"
\r
460 // We are not using \s because we don't want "non-breaking spaces" to be caught.
\r
461 var trimRegex = /(?:^[ \t\n\r]+)|(?:[ \t\n\r]+$)/g;
\r
462 return function( str )
\r
464 return str.replace( trimRegex, '' ) ;
\r
469 * Remove spaces from the start (left) of a string. The following
\r
470 * characters are removed: space, tab, line break, line feed.
\r
472 * @param {String} str The text from which remove the spaces.
\r
473 * @returns {String} The modified string excluding the removed spaces.
\r
475 * alert( CKEDITOR.tools.ltrim( ' example ' ); // "example "
\r
477 ltrim : (function()
\r
479 // We are not using \s because we don't want "non-breaking spaces" to be caught.
\r
480 var trimRegex = /^[ \t\n\r]+/g;
\r
481 return function( str )
\r
483 return str.replace( trimRegex, '' ) ;
\r
488 * Remove spaces from the end (right) of a string. The following
\r
489 * characters are removed: space, tab, line break, line feed.
\r
491 * @param {String} str The text from which remove the spaces.
\r
492 * @returns {String} The modified string excluding the removed spaces.
\r
494 * alert( CKEDITOR.tools.ltrim( ' example ' ); // " example"
\r
496 rtrim : (function()
\r
498 // We are not using \s because we don't want "non-breaking spaces" to be caught.
\r
499 var trimRegex = /[ \t\n\r]+$/g;
\r
500 return function( str )
\r
502 return str.replace( trimRegex, '' ) ;
\r
507 * Returns the index of an element in an array.
\r
508 * @param {Array} array The array to be searched.
\r
509 * @param {Object} entry The element to be found.
\r
510 * @returns {Number} The (zero based) index of the first entry that matches
\r
511 * the entry, or -1 if not found.
\r
513 * var letters = [ 'a', 'b', 0, 'c', false ];
\r
514 * alert( CKEDITOR.tools.indexOf( letters, '0' ) ); "-1" because 0 !== '0'
\r
515 * alert( CKEDITOR.tools.indexOf( letters, false ) ); "4" because 0 !== false
\r
518 // #2514: We should try to use Array.indexOf if it does exist.
\r
519 ( Array.prototype.indexOf ) ?
\r
520 function( array, entry )
\r
522 return array.indexOf( entry );
\r
525 function( array, entry )
\r
527 for ( var i = 0, len = array.length ; i < len ; i++ )
\r
529 if ( array[ i ] === entry )
\r
536 * Creates a function that will always execute in the context of a
\r
537 * specified object.
\r
538 * @param {Function} func The function to be executed.
\r
539 * @param {Object} obj The object to which bind the execution context.
\r
540 * @returns {Function} The function that can be used to execute the
\r
541 * "func" function in the context of "obj".
\r
543 * var obj = { text : 'My Object' };
\r
545 * function alertText()
\r
547 * alert( this.text );
\r
550 * var newFunc = <b>CKEDITOR.tools.bind( alertText, obj )</b>;
\r
551 * newFunc(); // Alerts "My Object".
\r
553 bind : function( func, obj )
\r
555 return function() { return func.apply( obj, arguments ); };
\r
559 * Class creation based on prototype inheritance, with supports of the
\r
560 * following features:
\r
562 * <li> Static fields </li>
\r
563 * <li> Private fields </li>
\r
564 * <li> Public (prototype) fields </li>
\r
565 * <li> Chainable base class constructor </li>
\r
567 * @param {Object} definition The class definition object.
\r
568 * @returns {Function} A class-like JavaScript function.
\r
570 createClass : function( definition )
\r
572 var $ = definition.$,
\r
573 baseClass = definition.base,
\r
574 privates = definition.privates || definition._,
\r
575 proto = definition.proto,
\r
576 statics = definition.statics;
\r
580 var originalConstructor = $;
\r
583 // Create (and get) the private namespace.
\r
584 var _ = this._ || ( this._ = {} );
\r
586 // Make some magic so "this" will refer to the main
\r
587 // instance when coding private functions.
\r
588 for ( var privateName in privates )
\r
590 var priv = privates[ privateName ];
\r
593 ( typeof priv == 'function' ) ? CKEDITOR.tools.bind( priv, this ) : priv;
\r
596 originalConstructor.apply( this, arguments );
\r
602 $.prototype = this.prototypedCopy( baseClass.prototype );
\r
603 $.prototype.constructor = $;
\r
604 $.prototype.base = function()
\r
606 this.base = baseClass.prototype.base;
\r
607 baseClass.apply( this, arguments );
\r
608 this.base = arguments.callee;
\r
613 this.extend( $.prototype, proto, true );
\r
616 this.extend( $, statics, true );
\r
622 * Creates a function reference that can be called later using
\r
623 * CKEDITOR.tools.callFunction. This approach is specially useful to
\r
624 * make DOM attribute function calls to JavaScript defined functions.
\r
625 * @param {Function} fn The function to be executed on call.
\r
626 * @param {Object} [scope] The object to have the context on "fn" execution.
\r
627 * @returns {Number} A unique reference to be used in conjuction with
\r
628 * CKEDITOR.tools.callFunction.
\r
630 * var ref = <b>CKEDITOR.tools.addFunction</b>(
\r
633 * alert( 'Hello!');
\r
635 * CKEDITOR.tools.callFunction( ref ); // Hello!
\r
637 addFunction : function( fn, scope )
\r
639 return functions.push( function()
\r
641 return fn.apply( scope || this, arguments );
\r
646 * Removes the function reference created with {@see CKEDITOR.tools.addFunction}.
\r
647 * @param {Number} ref The function reference created with
\r
648 * CKEDITOR.tools.addFunction.
\r
650 removeFunction : function( ref )
\r
652 functions[ ref ] = null;
\r
656 * Executes a function based on the reference created with
\r
657 * CKEDITOR.tools.addFunction.
\r
658 * @param {Number} ref The function reference created with
\r
659 * CKEDITOR.tools.addFunction.
\r
660 * @param {[Any,[Any,...]} params Any number of parameters to be passed
\r
661 * to the executed function.
\r
662 * @returns {Any} The return value of the function.
\r
664 * var ref = CKEDITOR.tools.addFunction(
\r
667 * alert( 'Hello!');
\r
669 * <b>CKEDITOR.tools.callFunction( ref )</b>; // Hello!
\r
671 callFunction : function( ref )
\r
673 var fn = functions[ ref ];
\r
674 return fn && fn.apply( window, Array.prototype.slice.call( arguments, 1 ) );
\r
678 * Append the 'px' length unit to the size if it's missing.
\r
681 cssLength : (function()
\r
683 return function( length )
\r
685 return length + ( !length || isNaN( Number( length ) ) ? '' : 'px' );
\r
690 * Convert the specified CSS length value to the calculated pixel length inside this page.
\r
691 * <strong>Note:</strong> Percentage based value is left intact.
\r
692 * @param {String} cssLength CSS length value.
\r
694 convertToPx : ( function ()
\r
698 return function( cssLength )
\r
702 calculator = CKEDITOR.dom.element.createFromHtml(
\r
703 '<div style="position:absolute;left:-9999px;' +
\r
704 'top:-9999px;margin:0px;padding:0px;border:0px;"' +
\r
705 '></div>', CKEDITOR.document );
\r
706 CKEDITOR.document.getBody().append( calculator );
\r
709 if ( !(/%$/).test( cssLength ) )
\r
711 calculator.setStyle( 'width', cssLength );
\r
712 return calculator.$.clientWidth;
\r
720 * String specified by {@param str} repeats {@param times} times.
\r
724 repeat : function( str, times )
\r
726 return new Array( times + 1 ).join( str );
\r
730 * Return the first successfully executed function's return value that
\r
731 * doesn't throw any exception.
\r
733 tryThese : function()
\r
736 for ( var i = 0, length = arguments.length; i < length; i++ )
\r
738 var lambda = arguments[i];
\r
741 returnValue = lambda();
\r
746 return returnValue;
\r
750 * Generate a combined key from a series of params.
\r
751 * @param {String} subKey One or more string used as sub keys.
\r
753 * var key = CKEDITOR.tools.genKey( 'key1', 'key2', 'key3' );
\r
754 * alert( key ); // "key1-key2-key3".
\r
756 genKey : function()
\r
758 return Array.prototype.slice.call( arguments ).join( '-' );
\r
763 // PACKAGER_RENAME( CKEDITOR.tools )
\r