]>
git.immae.eu Git - perso/Immae/Projets/packagist/piedsjaloux-ckeditor-component.git/blob - sources/core/tools.js
2 * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
3 * For licensing, see LICENSE.md or http://ckeditor.com/license
7 * @fileOverview Defines the {@link CKEDITOR.tools} object that contains
14 CKEDITOR
. env
. gecko
? '-moz-' :
15 CKEDITOR
. env
. webkit
? '-webkit-' :
16 CKEDITOR
. env
. ie
? '-ms-' :
22 tokenCharset = 'abcdefghijklmnopqrstuvwxyz0123456789',
23 TOKEN_COOKIE_NAME = 'ckCsrfToken',
26 allEscRegex = /&(lt|gt|amp|quot|nbsp|shy|#\d{1,5});/g,
35 allEscDecode = function( match, code ) {
36 if ( code[ 0 ] == ' # ' ) {
37 return String.fromCharCode( parseInt( code.slice( 1 ), 10 ) );
39 return namedEntities[ code ];
43 CKEDITOR.on( ' reset
', function() {
55 * Compares the elements of two arrays.
57 * var a = [ 1, ' a
', 3 ];
58 * var b = [ 1, 3, ' a
' ];
59 * var c = [ 1, ' a
', 3 ];
60 * var d = [ 1, ' a
', 3, 4 ];
62 * alert( CKEDITOR.tools.arrayCompare( a, b ) ); // false
63 * alert( CKEDITOR.tools.arrayCompare( a, c ) ); // true
64 * alert( CKEDITOR.tools.arrayCompare( a, d ) ); // false
66 * @param {Array} arrayA An array to be compared.
67 * @param {Array} arrayB The other array to be compared.
68 * @returns {Boolean} `true` if the arrays have the same length and
69 * their elements match.
71 arrayCompare: function( arrayA, arrayB ) {
72 if ( !arrayA && !arrayB )
75 if ( !arrayA || !arrayB || arrayA.length != arrayB.length )
78 for ( var i = 0; i < arrayA.length; i++ ) {
79 if ( arrayA[ i ] != arrayB[ i ] )
87 * Finds the index of the first element in an array for which the `compareFunction` returns `true`.
89 * CKEDITOR.tools.getIndex( [ 1, 2, 4, 3, 5 ], function( el ) {
94 * @param {Array} array Array to search in.
95 * @param {Function} compareFunction Compare function.
96 * @returns {Number} The index of the first matching element or `-1` if none matches.
98 getIndex: function( arr, compareFunction ) {
99 for ( var i = 0; i < arr.length; ++i ) {
100 if ( compareFunction( arr[ i ] ) )
107 * Creates a deep copy of an object.
109 * **Note**: Recursive references are not supported.
114 * Mercedes: { color: ' blue
' },
115 * Porsche: { color: ' red
' }
118 * var clone = CKEDITOR.tools.clone( obj );
119 * clone.name = ' Paul
';
120 * clone.cars.Porsche.color = ' silver
';
122 * alert( obj.name ); // ' John
'
123 * alert( clone.name ); // ' Paul
'
124 * alert( obj.cars.Porsche.color ); // ' red
'
125 * alert( clone.cars.Porsche.color ); // ' silver
'
127 * @param {Object} object The object to be cloned.
128 * @returns {Object} The object clone.
130 clone: function( obj ) {
134 if ( obj && ( obj instanceof Array ) ) {
137 for ( var i = 0; i < obj.length; i++ )
138 clone[ i ] = CKEDITOR.tools.clone( obj[ i ] );
144 if ( obj === null || ( typeof obj != ' object
' ) || ( obj instanceof String ) || ( obj instanceof Number ) || ( obj instanceof Boolean ) || ( obj instanceof Date ) || ( obj instanceof RegExp ) )
147 // DOM objects and window.
148 if ( obj.nodeType || obj.window === obj )
152 clone = new obj.constructor();
154 for ( var propertyName in obj ) {
155 var property = obj[ propertyName ];
156 clone[ propertyName ] = CKEDITOR.tools.clone( property );
163 * Turns the first letter of a string to upper-case.
165 * @param {String} str
166 * @param {Boolean} [keepCase] Keep the case of 2nd to last letter.
169 capitalize: function( str, keepCase ) {
170 return str.charAt( 0 ).toUpperCase() + ( keepCase ? str.slice( 1 ) : str.slice( 1 ).toLowerCase() );
174 * Copies the properties from one object to another. By default, properties
175 * already present in the target object **are not** overwritten.
177 * // Create the sample object.
182 * // Extend the above object with two properties.
183 * CKEDITOR.tools.extend( myObject, {
188 * // Alert ' prop1
', ' prop2
' and ' prop3
'.
189 * for ( var p in myObject )
192 * @param {Object} target The object to be extended.
193 * @param {Object...} source The object(s) from properties will be
194 * copied. Any number of objects can be passed to this function.
195 * @param {Boolean} [overwrite] If `true` is specified, it indicates that
196 * properties already present in the target object could be
197 * overwritten by subsequent objects.
198 * @param {Object} [properties] Only properties within the specified names
199 * list will be received from the source object.
200 * @returns {Object} The extended object (target).
202 extend: function( target ) {
203 var argsLength = arguments.length,
204 overwrite, propertiesList;
206 if ( typeof ( overwrite = arguments[ argsLength - 1 ] ) == ' boolean ' )
208 else if ( typeof ( overwrite = arguments[ argsLength - 2 ] ) == ' boolean ' ) {
209 propertiesList = arguments[ argsLength - 1 ];
212 for ( var i = 1; i < argsLength; i++ ) {
213 var source = arguments[ i ];
214 for ( var propertyName in source ) {
215 // Only copy existed fields if in overwrite mode.
216 if ( overwrite === true || target[ propertyName ] == null ) {
217 // Only copy specified fields if list is provided.
218 if ( !propertiesList || ( propertyName in propertiesList ) )
219 target[ propertyName ] = source[ propertyName ];
229 * Creates an object which is an instance of a class whose prototype is a
230 * predefined object. All properties defined in the source object are
231 * automatically inherited by the resulting object, including future
234 * @param {Object} source The source object to be used as the prototype for
236 * @returns {Object} The resulting copy.
238 prototypedCopy: function( source ) {
239 var copy = function() {};
240 copy.prototype = source;
245 * Makes fast (shallow) copy of an object.
246 * This method is faster than {@link #clone} which does
247 * a deep copy of an object (including arrays).
250 * @param {Object} source The object to be copied.
251 * @returns {Object} Copy of `source`.
253 copy: function( source ) {
257 for ( name in source )
258 obj[ name ] = source[ name ];
264 * Checks if an object is an Array.
266 * alert( CKEDITOR.tools.isArray( [] ) ); // true
267 * alert( CKEDITOR.tools.isArray( ' Test
' ) ); // false
269 * @param {Object} object The object to be checked.
270 * @returns {Boolean} `true` if the object is an Array, otherwise `false`.
272 isArray: function( object ) {
273 return Object.prototype.toString.call( object ) == ' [ object Array
] ';
277 * Whether the object contains no properties of its own.
282 isEmpty: function( object ) {
283 for ( var i in object ) {
284 if ( object.hasOwnProperty( i ) )
291 * Generates an object or a string containing vendor-specific and vendor-free CSS properties.
293 * CKEDITOR.tools.cssVendorPrefix( ' border
- radius
', ' 0 ', true );
294 * // On Firefox: ' - moz
- border
- radius : 0 ; border
- radius : 0 '
295 * // On Chrome: ' - webkit
- border
- radius : 0 ; border
- radius : 0 '
297 * @param {String} property The CSS property name.
298 * @param {String} value The CSS value.
299 * @param {Boolean} [asString=false] If `true`, then the returned value will be a CSS string.
300 * @returns {Object/String} The object containing CSS properties or its stringified version.
302 cssVendorPrefix: function( property, value, asString ) {
304 return cssVendorPrefix + property + ' : ' + value + ' ; ' + property + ' : ' + value;
307 ret[ property ] = value;
308 ret[ cssVendorPrefix + property ] = value;
314 * Transforms a CSS property name to its relative DOM style name.
316 * alert( CKEDITOR.tools.cssStyleToDomStyle( ' background
- color
' ) ); // ' backgroundColor
'
317 * alert( CKEDITOR.tools.cssStyleToDomStyle( ' float ' ) ); // ' cssFloat
'
320 * @param {String} cssName The CSS property name.
321 * @returns {String} The transformed name.
323 cssStyleToDomStyle: ( function() {
324 var test = document.createElement( ' div
' ).style;
326 var cssFloat = ( typeof test.cssFloat != ' undefined ' ) ? ' cssFloat
' : ( typeof test.styleFloat != ' undefined ' ) ? ' styleFloat
' : ' float ';
328 return function( cssName ) {
329 if ( cssName == ' float ' )
332 return cssName.replace( /-./g, function( match ) {
333 return match.substr( 1 ).toUpperCase();
340 * Builds a HTML snippet from a set of `<style>/<link>`.
342 * @param {String/Array} css Each of which are URLs (absolute) of a CSS file or
343 * a trunk of style text.
346 buildStyleHtml: function( css ) {
347 css = [].concat( css );
350 for ( var i = 0; i < css.length; i++ ) {
351 if ( ( item = css[ i ] ) ) {
352 // Is CSS style text ?
353 if ( /@import|[{}]/.test( item ) )
354 retval.push( ' < style
> ' + item + ' </ style
> ' );
356 retval.push( ' < link type
= "text/css" rel
= stylesheet href
= "' + item + '" > ' );
359 return retval.join( ' ' );
363 * Replaces special HTML characters in a string with their relative HTML
366 * alert( CKEDITOR.tools.htmlEncode( ' A
> B
& C
< D
' ) ); // ' A
& gt
; B
& amp
; C
& lt
; D
'
368 * @param {String} text The string to be encoded.
369 * @returns {String} The encoded string.
371 htmlEncode: function( text ) {
372 // Backwards compatibility - accept also non-string values (casting is done below).
373 // Since 4.4.8 we return empty string for null and undefined because these values make no sense.
374 if ( text === undefined || text === null ) {
378 return String( text ).replace( ampRegex, ' & amp
; ' ).replace( gtRegex, ' & gt
; ' ).replace( ltRegex, ' & lt
; ' );
382 * Decodes HTML entities that browsers tend to encode when used in text nodes.
384 * alert( CKEDITOR.tools.htmlDecode( ' & lt
; a
& amp
; b
& gt
; ' ) ); // ' < a
& b
> '
386 * Read more about chosen entities in the [research](http://dev.ckeditor.com/ticket/13105#comment:8).
388 * @param {String} The string to be decoded.
389 * @returns {String} The decoded string.
391 htmlDecode: function( text ) {
393 // * http://dev.ckeditor.com/ticket/13105#comment:8 and comment:9,
394 // * http://jsperf.com/wth-is-going-on-with-jsperf JSPerf has some serious problems, but you can observe
395 // that combined regexp tends to be quicker (except on V8). It will also not be prone to fail on ' & amp
; lt
; '
396 // (see http://dev.ckeditor.com/ticket/13105#DXWTF:CKEDITOR.tools.htmlEnDecodeAttr).
397 return text.replace( allEscRegex, allEscDecode );
401 * Replaces special HTML characters in HTMLElement attribute with their relative HTML entity values.
403 * alert( CKEDITOR.tools.htmlEncodeAttr( ' < a
" b >' ) ); // '<a " b >'
405 * @param {String} The attribute value to be encoded.
406 * @returns {String} The encoded value.
408 htmlEncodeAttr: function( text ) {
409 return CKEDITOR.tools.htmlEncode( text ).replace( quoteRegex, '"' );
413 * Decodes HTML entities that browsers tend to encode when used in attributes.
415 * alert( CKEDITOR.tools.htmlDecodeAttr( '<a " b>' ) ); // '<a " b
> '
417 * Since CKEditor 4.5 this method simply executes {@link #htmlDecode} which covers
418 * all necessary entities.
420 * @param {String} text The text to be decoded.
421 * @returns {String} The decoded text.
423 htmlDecodeAttr: function( text ) {
424 return CKEDITOR.tools.htmlDecode( text );
428 * Transforms text to valid HTML: creates paragraphs, replaces tabs with non-breaking spaces etc.
431 * @param {String} text Text to transform.
432 * @param {Number} enterMode Editor {@link CKEDITOR.config#enterMode Enter mode}.
433 * @returns {String} HTML generated from the text.
435 transformPlainTextToHtml: function( text, enterMode ) {
436 var isEnterBrMode = enterMode == CKEDITOR.ENTER_BR,
438 html = this.htmlEncode( text.replace( / \r\n /g, ' \n ' ) );
441 html = html.replace( / \t /g, ' & nbsp
;& nbsp
; & nbsp
; ' );
443 var paragraphTag = enterMode == CKEDITOR.ENTER_P ? ' p
' : ' div
';
445 // Two line-breaks create one paragraphing block.
446 if ( !isEnterBrMode ) {
447 var duoLF = / \n {2}/g;
448 if ( duoLF.test( html ) ) {
449 var openTag = ' < ' + paragraphTag + ' > ', endTag = ' </ ' + paragraphTag + ' > ';
450 html = openTag + html.replace( duoLF, function() {
451 return endTag + openTag;
456 // One <br> per line-break.
457 html = html.replace( / \n /g, ' < br
> ' );
459 // Compensate padding <br> at the end of block, avoid loosing them during insertion.
460 if ( !isEnterBrMode ) {
461 html = html.replace( new RegExp( ' < br
>(?=</ ' + paragraphTag + ' >) ' ), function( match ) {
462 return CKEDITOR.tools.repeat( match, 2 );
466 // Preserve spaces at the ends, so they won' t be lost after
insertion ( merged
with adjacent ones
).
467 html
= html
. replace ( /^ | $/ g
, ' ' );
469 // Finally, preserve whitespaces that are to be lost.
470 html
= html
. replace ( /(>|\s) /g , function ( match
, before
) {
471 return before
+ ' ' ;
472 } ). replace ( / (?=<)/ g
, ' ' );
478 * Gets a unique number for this CKEDITOR execution session. It returns
479 * consecutive numbers starting from 1.
481 * alert( CKEDITOR.tools.getNextNumber() ); // (e.g.) 1
482 * alert( CKEDITOR.tools.getNextNumber() ); // 2
485 * @returns {Number} A unique number.
487 getNextNumber : ( function () {
495 * Gets a unique ID for CKEditor interface elements. It returns a
496 * string with the "cke_" prefix and a consecutive number.
498 * alert( CKEDITOR.tools.getNextId() ); // (e.g.) 'cke_1'
499 * alert( CKEDITOR.tools.getNextId() ); // 'cke_2'
501 * @returns {String} A unique ID.
503 getNextId : function () {
504 return 'cke_' + this . getNextNumber ();
508 * Gets a universally unique ID. It returns a random string
509 * compliant with ISO/IEC 11578:1996, without dashes, with the "e" prefix to
510 * make sure that the ID does not start with a number.
512 * @returns {String} A global unique ID.
514 getUniqueId : function () {
515 var uuid
= 'e' ; // Make sure that id does not start with number.
516 for ( var i
= 0 ; i
< 8 ; i
++ ) {
517 uuid
+= Math
. floor ( ( 1 + Math
. random () ) * 0x10000 ). toString ( 16 ). substring ( 1 );
523 * Creates a function override.
526 * myFunction: function( name ) {
527 * alert( 'Name: ' + name );
531 * obj.myFunction = CKEDITOR.tools.override( obj.myFunction, function( myFunctionOriginal ) {
532 * return function( name ) {
533 * alert( 'Overriden name: ' + name );
534 * myFunctionOriginal.call( this, name );
538 * @param {Function} originalFunction The function to be overridden.
539 * @param {Function} functionBuilder A function that returns the new
540 * function. The original function reference will be passed to this function.
541 * @returns {Function} The new function.
543 override : function ( originalFunction
, functionBuilder
) {
544 var newFn
= functionBuilder ( originalFunction
);
545 newFn
. prototype = originalFunction
. prototype ;
550 * Executes a function after a specified delay.
552 * CKEDITOR.tools.setTimeout( function() {
553 * alert( 'Executed after 2 seconds' );
556 * @param {Function} func The function to be executed.
557 * @param {Number} [milliseconds=0] The amount of time (in milliseconds) to wait
558 * to fire the function execution.
559 * @param {Object} [scope=window] The object to store the function execution scope
560 * (the `this` object).
561 * @param {Object/Array} [args] A single object, or an array of objects, to
562 * pass as argument to the function.
563 * @param {Object} [ownerWindow=window] The window that will be used to set the
565 * @returns {Object} A value that can be used to cancel the function execution.
567 setTimeout : function ( func
, milliseconds
, scope
, args
, ownerWindow
) {
569 ownerWindow
= window
;
574 return ownerWindow
. setTimeout ( function () {
576 func
. apply ( scope
, []. concat ( args
) );
579 }, milliseconds
|| 0 );
583 * Removes spaces from the start and the end of a string. The following
584 * characters are removed: space, tab, line break, line feed.
586 * alert( CKEDITOR.tools.trim( ' example ' ); // 'example'
589 * @param {String} str The text from which the spaces will be removed.
590 * @returns {String} The modified string without the boundary spaces.
593 // We are not using \s because we don't want "non-breaking spaces" to be caught.
594 var trimRegex
= /(?:^[ \t\n\r ]+)|(?:[ \t\n\r ]+$)/ g
;
595 return function ( str
) {
596 return str
. replace ( trimRegex
, '' );
601 * Removes spaces from the start (left) of a string. The following
602 * characters are removed: space, tab, line break, line feed.
604 * alert( CKEDITOR.tools.ltrim( ' example ' ); // 'example '
607 * @param {String} str The text from which the spaces will be removed.
608 * @returns {String} The modified string excluding the removed spaces.
610 ltrim : ( function () {
611 // We are not using \s because we don't want "non-breaking spaces" to be caught.
612 var trimRegex
= /^[ \t\n\r ]+/ g
;
613 return function ( str
) {
614 return str
. replace ( trimRegex
, '' );
619 * Removes spaces from the end (right) of a string. The following
620 * characters are removed: space, tab, line break, line feed.
622 * alert( CKEDITOR.tools.ltrim( ' example ' ); // ' example'
625 * @param {String} str The text from which spaces will be removed.
626 * @returns {String} The modified string excluding the removed spaces.
628 rtrim : ( function () {
629 // We are not using \s because we don't want "non-breaking spaces" to be caught.
630 var trimRegex
= /[ \t\n\r ]+$/ g
;
631 return function ( str
) {
632 return str
. replace ( trimRegex
, '' );
637 * Returns the index of an element in an array.
639 * var letters = [ 'a', 'b', 0, 'c', false ];
640 * alert( CKEDITOR.tools.indexOf( letters, '0' ) ); // -1 because 0 !== '0'
641 * alert( CKEDITOR.tools.indexOf( letters, false ) ); // 4 because 0 !== false
643 * @param {Array} array The array to be searched.
644 * @param {Object/Function} value The element to be found. This can be an
645 * evaluation function which receives a single parameter call for
646 * each entry in the array, returning `true` if the entry matches.
647 * @returns {Number} The (zero-based) index of the first entry that matches
648 * the entry, or `-1` if not found.
650 indexOf : function ( array
, value
) {
651 if ( typeof value
== 'function' ) {
652 for ( var i
= 0 , len
= array
. length
; i
< len
; i
++ ) {
653 if ( value ( array
[ i
] ) )
656 } else if ( array
. indexOf
)
657 return array
. indexOf ( value
);
659 for ( i
= 0 , len
= array
. length
; i
< len
; i
++ ) {
660 if ( array
[ i
] === value
)
668 * Returns the index of an element in an array.
670 * var obj = { prop: true };
671 * var letters = [ 'a', 'b', 0, obj, false ];
673 * alert( CKEDITOR.tools.indexOf( letters, '0' ) ); // null
674 * alert( CKEDITOR.tools.indexOf( letters, function( value ) {
675 * // Return true when passed value has property 'prop'.
676 * return value && 'prop' in value;
679 * @param {Array} array The array to be searched.
680 * @param {Object/Function} value The element to be found. Can be an
681 * evaluation function which receives a single parameter call for
682 * each entry in the array, returning `true` if the entry matches.
683 * @returns Object The value that was found in an array.
685 search : function ( array
, value
) {
686 var index
= CKEDITOR
. tools
. indexOf ( array
, value
);
687 return index
>= 0 ? array
[ index
] : null ;
691 * Creates a function that will always execute in the context of a
694 * var obj = { text: 'My Object' };
696 * function alertText() {
697 * alert( this.text );
700 * var newFunc = CKEDITOR.tools.bind( alertText, obj );
701 * newFunc(); // Alerts 'My Object'.
703 * @param {Function} func The function to be executed.
704 * @param {Object} obj The object to which the execution context will be bound.
705 * @returns {Function} The function that can be used to execute the
706 * `func` function in the context of `obj`.
708 bind : function ( func
, obj
) {
710 return func
. apply ( obj
, arguments
);
715 * Class creation based on prototype inheritance which supports of the
716 * following features:
720 * * Public (prototype) fields
721 * * Chainable base class constructor
723 * @param {Object} definition The class definition object.
724 * @returns {Function} A class-like JavaScript function.
726 createClass : function ( definition
) {
727 var $ = definition
.$,
728 baseClass
= definition
. base
,
729 privates
= definition
. privates
|| definition
. _
,
730 proto
= definition
. proto
,
731 statics
= definition
. statics
;
733 // Create the constructor, if not present in the definition.
734 !$ && ( $ = function () {
735 baseClass
&& this . base
. apply ( this , arguments
);
739 var originalConstructor
= $;
741 // Create (and get) the private namespace.
742 var _
= this . _
|| ( this . _
= {} );
744 // Make some magic so "this" will refer to the main
745 // instance when coding private functions.
746 for ( var privateName
in privates
) {
747 var priv
= privates
[ privateName
];
749 _
[ privateName
] = ( typeof priv
== 'function' ) ? CKEDITOR
. tools
. bind ( priv
, this ) : priv
;
752 originalConstructor
. apply ( this , arguments
);
757 $. prototype = this . prototypedCopy ( baseClass
. prototype );
758 $. prototype . constructor = $;
761 $. baseProto
= baseClass
. prototype ;
762 // Super constructor.
763 $. prototype . base = function () {
764 this . base
= baseClass
. prototype . base
;
765 baseClass
. apply ( this , arguments
);
766 this . base
= arguments
. callee
;
771 this . extend ( $. prototype , proto
, true );
774 this . extend ( $, statics
, true );
780 * Creates a function reference that can be called later using
781 * {@link #callFunction}. This approach is especially useful to
782 * make DOM attribute function calls to JavaScript-defined functions.
784 * var ref = CKEDITOR.tools.addFunction( function() {
787 * CKEDITOR.tools.callFunction( ref ); // 'Hello!'
789 * @param {Function} fn The function to be executed on call.
790 * @param {Object} [scope] The object to have the context on `fn` execution.
791 * @returns {Number} A unique reference to be used in conjuction with
792 * {@link #callFunction}.
794 addFunction : function ( fn
, scope
) {
795 return functions
. push ( function () {
796 return fn
. apply ( scope
|| this , arguments
);
801 * Removes the function reference created with {@link #addFunction}.
803 * @param {Number} ref The function reference created with
804 * {@link #addFunction}.
806 removeFunction : function ( ref
) {
807 functions
[ ref
] = null ;
811 * Executes a function based on the reference created with {@link #addFunction}.
813 * var ref = CKEDITOR.tools.addFunction( function() {
816 * CKEDITOR.tools.callFunction( ref ); // 'Hello!'
818 * @param {Number} ref The function reference created with {@link #addFunction}.
819 * @param {Mixed} params Any number of parameters to be passed to the executed function.
820 * @returns {Mixed} The return value of the function.
822 callFunction : function ( ref
) {
823 var fn
= functions
[ ref
];
824 return fn
&& fn
. apply ( window
, Array
. prototype . slice
. call ( arguments
, 1 ) );
828 * Appends the `px` length unit to the size value if it is missing.
830 * var cssLength = CKEDITOR.tools.cssLength;
831 * cssLength( 42 ); // '42px'
832 * cssLength( '42' ); // '42px'
833 * cssLength( '42px' ); // '42px'
834 * cssLength( '42%' ); // '42%'
835 * cssLength( 'bold' ); // 'bold'
836 * cssLength( false ); // ''
837 * cssLength( NaN ); // ''
840 * @param {Number/String/Boolean} length
842 cssLength : ( function () {
843 var pixelRegex
= /^-?\d+\.?\d*px$/ ,
846 return function ( length
) {
847 lengthTrimmed
= CKEDITOR
. tools
. trim ( length
+ '' ) + 'px' ;
849 if ( pixelRegex
. test ( lengthTrimmed
) )
850 return lengthTrimmed
;
857 * Converts the specified CSS length value to the calculated pixel length inside this page.
859 * **Note:** Percentage-based value is left intact.
862 * @param {String} cssLength CSS length value.
864 convertToPx : ( function () {
867 return function ( cssLength
) {
869 calculator
= CKEDITOR
. dom
. element
. createFromHtml ( '<div style="position:absolute;left:-9999px;' +
870 'top:-9999px;margin:0px;padding:0px;border:0px;"' +
871 '></div>' , CKEDITOR
. document
);
872 CKEDITOR
. document
. getBody (). append ( calculator
);
875 if ( !( /%$/ ). test ( cssLength
) ) {
876 calculator
. setStyle ( 'width' , cssLength
);
877 return calculator
.$. clientWidth
;
885 * String specified by `str` repeats `times` times.
887 * @param {String} str
888 * @param {Number} times
891 repeat : function ( str
, times
) {
892 return new Array ( times
+ 1 ). join ( str
);
896 * Returns the first successfully executed return value of a function that
897 * does not throw any exception.
899 * @param {Function...} fn
902 tryThese : function () {
904 for ( var i
= 0 , length
= arguments
. length
; i
< length
; i
++ ) {
905 var lambda
= arguments
[ i
];
907 returnValue
= lambda ();
915 * Generates a combined key from a series of params.
917 * var key = CKEDITOR.tools.genKey( 'key1', 'key2', 'key3' );
918 * alert( key ); // 'key1-key2-key3'.
920 * @param {String} subKey One or more strings used as subkeys.
924 return Array
. prototype . slice
. call ( arguments
). join ( '-' );
928 * Creates a "deferred" function which will not run immediately,
929 * but rather runs as soon as the interpreter’s call stack is empty.
930 * Behaves much like `window.setTimeout` with a delay.
932 * **Note:** The return value of the original function will be lost.
934 * @param {Function} fn The callee function.
935 * @returns {Function} The new deferred function.
937 defer : function ( fn
) {
939 var args
= arguments
,
941 window
. setTimeout ( function () {
942 fn
. apply ( self
, args
);
948 * Normalizes CSS data in order to avoid differences in the style attribute.
950 * @param {String} styleText The style data to be normalized.
951 * @param {Boolean} [nativeNormalize=false] Parse the data using the browser.
952 * @returns {String} The normalized value.
954 normalizeCssText : function ( styleText
, nativeNormalize
) {
957 parsedProps
= CKEDITOR
. tools
. parseCssText ( styleText
, true , nativeNormalize
);
959 for ( name
in parsedProps
)
960 props
. push ( name
+ ':' + parsedProps
[ name
] );
964 return props
. length
? ( props
. join ( ';' ) + ';' ) : '' ;
968 * Finds and converts `rgb(x,x,x)` color definition to hexadecimal notation.
970 * @param {String} styleText The style data (or just a string containing RGB colors) to be converted.
971 * @returns {String} The style data with RGB colors converted to hexadecimal equivalents.
973 convertRgbToHex : function ( styleText
) {
974 return styleText
. replace ( /(?:rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\))/gi , function ( match
, red
, green
, blue
) {
975 var color
= [ red
, green
, blue
];
976 // Add padding zeros if the hex value is less than 0x10.
977 for ( var i
= 0 ; i
< 3 ; i
++ )
978 color
[ i
] = ( '0' + parseInt ( color
[ i
], 10 ). toString ( 16 ) ). slice ( - 2 );
979 return '#' + color
. join ( '' );
984 * Turns inline style text properties into one hash.
986 * @param {String} styleText The style data to be parsed.
987 * @param {Boolean} [normalize=false] Normalize properties and values
988 * (e.g. trim spaces, convert to lower case).
989 * @param {Boolean} [nativeNormalize=false] Parse the data using the browser.
990 * @returns {Object} The object containing parsed properties.
992 parseCssText : function ( styleText
, normalize
, nativeNormalize
) {
995 if ( nativeNormalize
) {
996 // Injects the style in a temporary span object, so the browser parses it,
997 // retrieving its final format.
998 var temp
= new CKEDITOR
. dom
. element ( 'span' );
999 temp
. setAttribute ( 'style' , styleText
);
1000 styleText
= CKEDITOR
. tools
. convertRgbToHex ( temp
. getAttribute ( 'style' ) || '' );
1003 // IE will leave a single semicolon when failed to parse the style text. (#3891)
1004 if ( ! styleText
|| styleText
== ';' )
1007 styleText
. replace ( /"/g , '"' ). replace ( /\s*([^:;\s]+)\s*:\s*([^;]+)\s*(?=;|$)/g , function ( match
, name
, value
) {
1009 name
= name
. toLowerCase ();
1010 // Normalize font-family property, ignore quotes and being case insensitive. (#7322)
1011 // http://www.w3.org/TR/css3-fonts/#font-family-the-font-family-property
1012 if ( name
== 'font-family' )
1013 value
= value
. toLowerCase (). replace ( /["']/g , '' ). replace ( /\s*,\s*/g , ',' );
1014 value
= CKEDITOR
. tools
. trim ( value
);
1017 retval
[ name
] = value
;
1023 * Serializes the `style name => value` hash to a style text.
1025 * var styleObj = CKEDITOR.tools.parseCssText( 'color: red; border: none' );
1026 * console.log( styleObj.color ); // -> 'red'
1027 * CKEDITOR.tools.writeCssText( styleObj ); // -> 'color:red; border:none'
1028 * CKEDITOR.tools.writeCssText( styleObj, true ); // -> 'border:none; color:red'
1031 * @param {Object} styles The object contaning style properties.
1032 * @param {Boolean} [sort] Whether to sort CSS properties.
1033 * @returns {String} The serialized style text.
1035 writeCssText : function ( styles
, sort
) {
1039 for ( name
in styles
)
1040 stylesArr
. push ( name
+ ':' + styles
[ name
] );
1045 return stylesArr
. join ( '; ' );
1049 * Compares two objects.
1051 * **Note:** This method performs shallow, non-strict comparison.
1054 * @param {Object} left
1055 * @param {Object} right
1056 * @param {Boolean} [onlyLeft] Check only the properties that are present in the `left` object.
1057 * @returns {Boolean} Whether objects are identical.
1059 objectCompare : function ( left
, right
, onlyLeft
) {
1062 if ( ! left
&& ! right
)
1064 if ( ! left
|| ! right
)
1067 for ( name
in left
) {
1068 if ( left
[ name
] != right
[ name
] )
1074 for ( name
in right
) {
1075 if ( left
[ name
] != right
[ name
] )
1084 * Returns an array of passed object's keys.
1086 * console.log( CKEDITOR.tools.objectKeys( { foo: 1, bar: false } );
1087 * // -> [ 'foo', 'bar' ]
1090 * @param {Object} obj
1091 * @returns {Array} Object's keys.
1093 objectKeys : function ( obj
) {
1095 for ( var i
in obj
)
1102 * Converts an array to an object by rewriting array items
1103 * to object properties.
1105 * var arr = [ 'foo', 'bar', 'foo' ];
1106 * console.log( CKEDITOR.tools.convertArrayToObject( arr ) );
1107 * // -> { foo: true, bar: true }
1108 * console.log( CKEDITOR.tools.convertArrayToObject( arr, 1 ) );
1109 * // -> { foo: 1, bar: 1 }
1112 * @param {Array} arr The array to be converted to an object.
1113 * @param [fillWith=true] Set each property of an object to `fillWith` value.
1115 convertArrayToObject : function ( arr
, fillWith
) {
1118 if ( arguments
. length
== 1 )
1121 for ( var i
= 0 , l
= arr
. length
; i
< l
; ++ i
)
1122 obj
[ arr
[ i
] ] = fillWith
;
1128 * Tries to fix the `document.domain` of the current document to match the
1129 * parent window domain, avoiding "Same Origin" policy issues.
1130 * This is an Internet Explorer only requirement.
1133 * @returns {Boolean} `true` if the current domain is already good or if
1134 * it has been fixed successfully.
1136 fixDomain : function () {
1141 // Try to access the parent document. It throws
1142 // "access denied" if restricted by the "Same Origin" policy.
1143 domain
= window
. parent
. document
. domain
;
1146 // Calculate the value to set to document.domain.
1149 // If it is not the first pass, strip one part of the
1150 // name. E.g. "test.example.com" => "example.com"
1151 domain
. replace ( /.+?(?:\.|$)/ , '' ) :
1153 // In the first pass, we'll handle the
1154 // "document.domain = document.domain" case.
1157 // Stop here if there is no more domain parts available.
1161 document
. domain
= domain
;
1169 * Buffers `input` events (or any `input` calls)
1170 * and triggers `output` not more often than once per `minInterval`.
1172 * var buffer = CKEDITOR.tools.eventsBuffer( 200, function() {
1173 * console.log( 'foo!' );
1177 * // 'foo!' logged immediately.
1179 * // Nothing logged.
1181 * // Nothing logged.
1182 * // ... after 200ms a single 'foo!' will be logged.
1184 * Can be easily used with events:
1186 * var buffer = CKEDITOR.tools.eventsBuffer( 200, function() {
1187 * console.log( 'foo!' );
1190 * editor.on( 'key', buffer.input );
1191 * // Note: There is no need to bind buffer as a context.
1194 * @param {Number} minInterval Minimum interval between `output` calls in milliseconds.
1195 * @param {Function} output Function that will be executed as `output`.
1196 * @param {Object} [scopeObj] The object used to scope the listener call (the `this` object).
1198 * @returns {Function} return.input Buffer's input method.
1199 * @returns {Function} return.reset Resets buffered events — `output` will not be executed
1200 * until next `input` is triggered.
1202 eventsBuffer : function ( minInterval
, output
, scopeObj
) {
1206 function triggerOutput () {
1207 lastOutput
= ( new Date () ). getTime ();
1210 output
. call ( scopeObj
);
1221 var diff
= ( new Date () ). getTime () - lastOutput
;
1223 // If less than minInterval passed after last check,
1224 // schedule next for minInterval after previous one.
1225 if ( diff
< minInterval
)
1226 scheduled
= setTimeout ( triggerOutput
, minInterval
- diff
);
1233 clearTimeout ( scheduled
);
1235 scheduled
= lastOutput
= 0 ;
1241 * Enables HTML5 elements for older browsers (IE8) in the passed document.
1243 * In IE8 this method can also be executed on a document fragment.
1245 * **Note:** This method has to be used in the `<head>` section of the document.
1248 * @param {Object} doc Native `Document` or `DocumentFragment` in which the elements will be enabled.
1249 * @param {Boolean} [withAppend] Whether to append created elements to the `doc`.
1251 enableHtml5Elements : function ( doc
, withAppend
) {
1252 var els
= 'abbr,article,aside,audio,bdi,canvas,data,datalist,details,figcaption,figure,footer,header,hgroup,main,mark,meter,nav,output,progress,section,summary,time,video' . split ( ',' ),
1257 el
= doc
. createElement ( els
[ i
] );
1259 doc
. appendChild ( el
);
1264 * Checks if any of the `arr` items match the provided regular expression.
1266 * @param {Array} arr The array whose items will be checked.
1267 * @param {RegExp} regexp The regular expression.
1268 * @returns {Boolean} Returns `true` for the first occurrence of the search pattern.
1271 checkIfAnyArrayItemMatches : function ( arr
, regexp
) {
1272 for ( var i
= 0 , l
= arr
. length
; i
< l
; ++ i
) {
1273 if ( arr
[ i
]. match ( regexp
) )
1280 * Checks if any of the `obj` properties match the provided regular expression.
1282 * @param obj The object whose properties will be checked.
1283 * @param {RegExp} regexp The regular expression.
1284 * @returns {Boolean} Returns `true` for the first occurrence of the search pattern.
1287 checkIfAnyObjectPropertyMatches : function ( obj
, regexp
) {
1288 for ( var i
in obj
) {
1289 if ( i
. match ( regexp
) )
1296 * The data URI of a transparent image. May be used e.g. in HTML as an image source or in CSS in `url()`.
1301 transparentImageData : 'data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==' ,
1305 * Returns the value of the cookie with a given name or `null` if the cookie is not found.
1308 * @param {String} name
1311 getCookie : function ( name
) {
1312 name
= name
. toLowerCase ();
1313 var parts
= document
. cookie
. split ( ';' );
1316 for ( var i
= 0 ; i
< parts
. length
; i
++ ) {
1317 pair
= parts
[ i
]. split ( '=' );
1318 key
= decodeURIComponent ( CKEDITOR
. tools
. trim ( pair
[ 0 ] ). toLowerCase () );
1320 if ( key
=== name
) {
1321 return decodeURIComponent ( pair
. length
> 1 ? pair
[ 1 ] : '' );
1329 * Sets the value of the cookie with a given name.
1332 * @param {String} name
1333 * @param {String} value
1335 setCookie : function ( name
, value
) {
1336 document
. cookie
= encodeURIComponent ( name
) + '=' + encodeURIComponent ( value
) + ';path=/' ;
1340 * Returns the CSRF token value. The value is a hash stored in `document.cookie`
1341 * under the `ckCsrfToken` key. The CSRF token can be used to secure the communication
1342 * between the web browser and the server, i.e. for the file upload feature in the editor.
1347 getCsrfToken : function () {
1348 var token
= CKEDITOR
. tools
. getCookie ( TOKEN_COOKIE_NAME
);
1350 if ( ! token
|| token
. length
!= TOKEN_LENGTH
) {
1351 token
= generateToken ( TOKEN_LENGTH
);
1352 CKEDITOR
. tools
. setCookie ( TOKEN_COOKIE_NAME
, token
);
1359 // Generates a CSRF token with a given length.
1362 // @param {Number} length
1363 // @returns {string}
1364 function generateToken ( length
) {
1365 var randValues
= [];
1368 if ( window
. crypto
&& window
. crypto
. getRandomValues
) {
1369 randValues
= new Uint8Array ( length
);
1370 window
. crypto
. getRandomValues ( randValues
);
1372 for ( var i
= 0 ; i
< length
; i
++ ) {
1373 randValues
. push ( Math
. floor ( Math
. random () * 256 ) );
1377 for ( var j
= 0 ; j
< randValues
. length
; j
++ ) {
1378 var character
= tokenCharset
. charAt ( randValues
[ j
] % tokenCharset
. length
);
1379 result
+= Math
. random () > 0.5 ? character
. toUpperCase () : character
;
1386 // PACKAGER_RENAME( CKEDITOR.tools )