-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathtools.js
2374 lines (2127 loc) · 69.8 KB
/
tools.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.tools} object that contains
* utility functions.
*/
( function() {
var functions = [],
cssVendorPrefix =
CKEDITOR.env.gecko ? '-moz-' :
CKEDITOR.env.webkit ? '-webkit-' :
CKEDITOR.env.ie ? '-ms-' :
'',
ampRegex = /&/g,
gtRegex = />/g,
ltRegex = /</g,
quoteRegex = /"/g,
tokenCharset = 'abcdefghijklmnopqrstuvwxyz0123456789',
TOKEN_COOKIE_NAME = 'ckCsrfToken',
TOKEN_LENGTH = 40,
allEscRegex = /&(lt|gt|amp|quot|nbsp|shy|#\d{1,5});/g,
namedEntities = {
lt: '<',
gt: '>',
amp: '&',
quot: '"',
nbsp: '\u00a0',
shy: '\u00ad'
},
allEscDecode = function( match, code ) {
if ( code[ 0 ] == '#' ) {
return String.fromCharCode( parseInt( code.slice( 1 ), 10 ) );
} else {
return namedEntities[ code ];
}
};
CKEDITOR.on( 'reset', function() {
functions = [];
} );
/**
* Utility functions.
*
* @class
* @singleton
*/
CKEDITOR.tools = {
/**
* Compares the elements of two arrays.
*
* var a = [ 1, 'a', 3 ];
* var b = [ 1, 3, 'a' ];
* var c = [ 1, 'a', 3 ];
* var d = [ 1, 'a', 3, 4 ];
*
* alert( CKEDITOR.tools.arrayCompare( a, b ) ); // false
* alert( CKEDITOR.tools.arrayCompare( a, c ) ); // true
* alert( CKEDITOR.tools.arrayCompare( a, d ) ); // false
*
* @param {Array} arrayA An array to be compared.
* @param {Array} arrayB The other array to be compared.
* @returns {Boolean} `true` if the arrays have the same length and
* their elements match.
*/
arrayCompare: function( arrayA, arrayB ) {
if ( !arrayA && !arrayB )
return true;
if ( !arrayA || !arrayB || arrayA.length != arrayB.length )
return false;
for ( var i = 0; i < arrayA.length; i++ ) {
if ( arrayA[ i ] != arrayB[ i ] )
return false;
}
return true;
},
/**
* Finds the index of the first element in an array for which the `compareFunction` returns `true`.
*
* CKEDITOR.tools.getIndex( [ 1, 2, 4, 3, 5 ], function( el ) {
* return el >= 3;
* } ); // 2
*
* @since 4.5
* @param {Array} array Array to search in.
* @param {Function} compareFunction Compare function.
* @returns {Number} The index of the first matching element or `-1` if none matches.
*/
getIndex: function( arr, compareFunction ) {
for ( var i = 0; i < arr.length; ++i ) {
if ( compareFunction( arr[ i ] ) )
return i;
}
return -1;
},
/**
* Creates a deep copy of an object.
*
* **Note**: Recursive references are not supported.
*
* var obj = {
* name: 'John',
* cars: {
* Mercedes: { color: 'blue' },
* Porsche: { color: 'red' }
* }
* };
* var clone = CKEDITOR.tools.clone( obj );
* clone.name = 'Paul';
* clone.cars.Porsche.color = 'silver';
*
* alert( obj.name ); // 'John'
* alert( clone.name ); // 'Paul'
* alert( obj.cars.Porsche.color ); // 'red'
* alert( clone.cars.Porsche.color ); // 'silver'
*
* @param {Object} object The object to be cloned.
* @returns {Object} The object clone.
*/
clone: function( obj ) {
var clone;
// Array.
if ( obj && ( obj instanceof Array ) ) {
clone = [];
for ( var i = 0; i < obj.length; i++ )
clone[ i ] = CKEDITOR.tools.clone( obj[ i ] );
return clone;
}
// "Static" types.
if ( obj === null || ( typeof obj != 'object' ) || ( obj instanceof String ) || ( obj instanceof Number ) || ( obj instanceof Boolean ) || ( obj instanceof Date ) || ( obj instanceof RegExp ) )
return obj;
// DOM objects and window.
if ( obj.nodeType || obj.window === obj )
return obj;
// Objects.
clone = new obj.constructor();
for ( var propertyName in obj ) {
var property = obj[ propertyName ];
clone[ propertyName ] = CKEDITOR.tools.clone( property );
}
return clone;
},
/**
* Turns the first letter of a string to upper-case.
*
* @param {String} str
* @param {Boolean} [keepCase] Keep the case of 2nd to last letter.
* @returns {String}
*/
capitalize: function( str, keepCase ) {
return str.charAt( 0 ).toUpperCase() + ( keepCase ? str.slice( 1 ) : str.slice( 1 ).toLowerCase() );
},
/**
* Copies the properties from one object to another. By default, properties
* already present in the target object **are not** overwritten.
*
* // Create the sample object.
* var myObject = {
* prop1: true
* };
*
* // Extend the above object with two properties.
* CKEDITOR.tools.extend( myObject, {
* prop2: true,
* prop3: true
* } );
*
* // Alert 'prop1', 'prop2' and 'prop3'.
* for ( var p in myObject )
* alert( p );
*
* @param {Object} target The object to be extended.
* @param {Object...} source The object(s) from properties will be
* copied. Any number of objects can be passed to this function.
* @param {Boolean} [overwrite] If `true` is specified, it indicates that
* properties already present in the target object could be
* overwritten by subsequent objects.
* @param {Object} [properties] Only properties within the specified names
* list will be received from the source object.
* @returns {Object} The extended object (target).
*/
extend: function( target ) {
var argsLength = arguments.length,
overwrite, propertiesList;
if ( typeof ( overwrite = arguments[ argsLength - 1 ] ) == 'boolean' )
argsLength--;
else if ( typeof ( overwrite = arguments[ argsLength - 2 ] ) == 'boolean' ) {
propertiesList = arguments[ argsLength - 1 ];
argsLength -= 2;
}
for ( var i = 1; i < argsLength; i++ ) {
var source = arguments[ i ];
for ( var propertyName in source ) {
// Only copy existed fields if in overwrite mode.
if ( overwrite === true || target[ propertyName ] == null ) {
// Only copy specified fields if list is provided.
if ( !propertiesList || ( propertyName in propertiesList ) )
target[ propertyName ] = source[ propertyName ];
}
}
}
return target;
},
/**
* Creates an object which is an instance of a class whose prototype is a
* predefined object. All properties defined in the source object are
* automatically inherited by the resulting object, including future
* changes to it.
*
* @param {Object} source The source object to be used as the prototype for
* the final object.
* @returns {Object} The resulting copy.
*/
prototypedCopy: function( source ) {
var copy = function() {};
copy.prototype = source;
return new copy();
},
/**
* Makes fast (shallow) copy of an object.
* This method is faster than {@link #clone} which does
* a deep copy of an object (including arrays).
*
* @since 4.1
* @param {Object} source The object to be copied.
* @returns {Object} Copy of `source`.
*/
copy: function( source ) {
var obj = {},
name;
for ( name in source )
obj[ name ] = source[ name ];
return obj;
},
/**
* Checks if an object is an Array.
*
* alert( CKEDITOR.tools.isArray( [] ) ); // true
* alert( CKEDITOR.tools.isArray( 'Test' ) ); // false
*
* @param {Object} object The object to be checked.
* @returns {Boolean} `true` if the object is an Array, otherwise `false`.
*/
isArray: function( object ) {
return Object.prototype.toString.call( object ) == '[object Array]';
},
/**
* Whether the object contains no properties of its own.
*
* @param object
* @returns {Boolean}
*/
isEmpty: function( object ) {
for ( var i in object ) {
if ( object.hasOwnProperty( i ) )
return false;
}
return true;
},
/**
* Generates an object or a string containing vendor-specific and vendor-free CSS properties.
*
* CKEDITOR.tools.cssVendorPrefix( 'border-radius', '0', true );
* // On Firefox: '-moz-border-radius:0;border-radius:0'
* // On Chrome: '-webkit-border-radius:0;border-radius:0'
*
* @param {String} property The CSS property name.
* @param {String} value The CSS value.
* @param {Boolean} [asString=false] If `true`, then the returned value will be a CSS string.
* @returns {Object/String} The object containing CSS properties or its stringified version.
*/
cssVendorPrefix: function( property, value, asString ) {
if ( asString )
return cssVendorPrefix + property + ':' + value + ';' + property + ':' + value;
var ret = {};
ret[ property ] = value;
ret[ cssVendorPrefix + property ] = value;
return ret;
},
/**
* Transforms a CSS property name to its relative DOM style name.
*
* alert( CKEDITOR.tools.cssStyleToDomStyle( 'background-color' ) ); // 'backgroundColor'
* alert( CKEDITOR.tools.cssStyleToDomStyle( 'float' ) ); // 'cssFloat'
*
* @method
* @param {String} cssName The CSS property name.
* @returns {String} The transformed name.
*/
cssStyleToDomStyle: ( function() {
var test = document.createElement( 'div' ).style;
var cssFloat = ( typeof test.cssFloat != 'undefined' ) ? 'cssFloat' : ( typeof test.styleFloat != 'undefined' ) ? 'styleFloat' : 'float';
return function( cssName ) {
if ( cssName == 'float' )
return cssFloat;
else {
return cssName.replace( /-./g, function( match ) {
return match.substr( 1 ).toUpperCase();
} );
}
};
} )(),
/**
* Builds a HTML snippet from a set of `<style>/<link>`.
*
* @param {String/Array} css Each of which are URLs (absolute) of a CSS file or
* a trunk of style text.
* @returns {String}
*/
buildStyleHtml: function( css ) {
css = [].concat( css );
var item,
retval = [];
for ( var i = 0; i < css.length; i++ ) {
if ( ( item = css[ i ] ) ) {
// Is CSS style text ?
if ( /@import|[{}]/.test( item ) )
retval.push( '<style>' + item + '</style>' );
else
retval.push( '<link type="text/css" rel=stylesheet href="' + item + '">' );
}
}
return retval.join( '' );
},
/**
* Replaces special HTML characters in a string with their relative HTML
* entity values.
*
* alert( CKEDITOR.tools.htmlEncode( 'A > B & C < D' ) ); // 'A > B & C < D'
*
* @param {String} text The string to be encoded.
* @returns {String} The encoded string.
*/
htmlEncode: function( text ) {
// Backwards compatibility - accept also non-string values (casting is done below).
// Since 4.4.8 we return empty string for null and undefined because these values make no sense.
if ( text === undefined || text === null ) {
return '';
}
return String( text ).replace( ampRegex, '&' ).replace( gtRegex, '>' ).replace( ltRegex, '<' );
},
/**
* Decodes HTML entities that browsers tend to encode when used in text nodes.
*
* alert( CKEDITOR.tools.htmlDecode( '<a & b >' ) ); // '<a & b >'
*
* Read more about chosen entities in the [research](https://dev.ckeditor.com/ticket/13105#comment:8).
*
* @param {String} The string to be decoded.
* @returns {String} The decoded string.
*/
htmlDecode: function( text ) {
// See:
// * https://dev.ckeditor.com/ticket/13105#comment:8 and comment:9,
// * http://jsperf.com/wth-is-going-on-with-jsperf JSPerf has some serious problems, but you can observe
// that combined regexp tends to be quicker (except on V8). It will also not be prone to fail on '&lt;'
// (see https://dev.ckeditor.com/ticket/13105#DXWTF:CKEDITOR.tools.htmlEnDecodeAttr).
return text.replace( allEscRegex, allEscDecode );
},
/**
* Replaces special HTML characters in HTMLElement attribute with their relative HTML entity values.
*
* alert( CKEDITOR.tools.htmlEncodeAttr( '<a " b >' ) ); // '<a " b >'
*
* @param {String} The attribute value to be encoded.
* @returns {String} The encoded value.
*/
htmlEncodeAttr: function( text ) {
return CKEDITOR.tools.htmlEncode( text ).replace( quoteRegex, '"' );
},
/**
* Decodes HTML entities that browsers tend to encode when used in attributes.
*
* alert( CKEDITOR.tools.htmlDecodeAttr( '<a " b>' ) ); // '<a " b>'
*
* Since CKEditor 4.5 this method simply executes {@link #htmlDecode} which covers
* all necessary entities.
*
* @param {String} text The text to be decoded.
* @returns {String} The decoded text.
*/
htmlDecodeAttr: function( text ) {
return CKEDITOR.tools.htmlDecode( text );
},
/**
* Transforms text to valid HTML: creates paragraphs, replaces tabs with non-breaking spaces etc.
*
* @since 4.5
* @param {String} text Text to transform.
* @param {Number} enterMode Editor {@link CKEDITOR.config#enterMode Enter mode}.
* @returns {String} HTML generated from the text.
*/
transformPlainTextToHtml: function( text, enterMode ) {
var isEnterBrMode = enterMode == CKEDITOR.ENTER_BR,
// CRLF -> LF
html = this.htmlEncode( text.replace( /\r\n/g, '\n' ) );
// Tab ->   x 4;
html = html.replace( /\t/g, ' ' );
var paragraphTag = enterMode == CKEDITOR.ENTER_P ? 'p' : 'div';
// Two line-breaks create one paragraphing block.
if ( !isEnterBrMode ) {
var duoLF = /\n{2}/g;
if ( duoLF.test( html ) ) {
var openTag = '<' + paragraphTag + '>', endTag = '</' + paragraphTag + '>';
html = openTag + html.replace( duoLF, function() {
return endTag + openTag;
} ) + endTag;
}
}
// One <br> per line-break.
html = html.replace( /\n/g, '<br>' );
// Compensate padding <br> at the end of block, avoid loosing them during insertion.
if ( !isEnterBrMode ) {
html = html.replace( new RegExp( '<br>(?=</' + paragraphTag + '>)' ), function( match ) {
return CKEDITOR.tools.repeat( match, 2 );
} );
}
// Preserve spaces at the ends, so they won't be lost after insertion (merged with adjacent ones).
html = html.replace( /^ | $/g, ' ' );
// Finally, preserve whitespaces that are to be lost.
html = html.replace( /(>|\s) /g, function( match, before ) {
return before + ' ';
} ).replace( / (?=<)/g, ' ' );
return html;
},
/**
* Gets a unique number for this CKEDITOR execution session. It returns
* consecutive numbers starting from 1.
*
* alert( CKEDITOR.tools.getNextNumber() ); // (e.g.) 1
* alert( CKEDITOR.tools.getNextNumber() ); // 2
*
* @method
* @returns {Number} A unique number.
*/
getNextNumber: ( function() {
var last = 0;
return function() {
return ++last;
};
} )(),
/**
* Gets a unique ID for CKEditor interface elements. It returns a
* string with the "cke_" prefix and a consecutive number.
*
* alert( CKEDITOR.tools.getNextId() ); // (e.g.) 'cke_1'
* alert( CKEDITOR.tools.getNextId() ); // 'cke_2'
*
* @returns {String} A unique ID.
*/
getNextId: function() {
return 'cke_' + this.getNextNumber();
},
/**
* Gets a universally unique ID. It returns a random string
* compliant with ISO/IEC 11578:1996, without dashes, with the "e" prefix to
* make sure that the ID does not start with a number.
*
* @returns {String} A global unique ID.
*/
getUniqueId: function() {
var uuid = 'e'; // Make sure that id does not start with number.
for ( var i = 0; i < 8; i++ ) {
uuid += Math.floor( ( 1 + Math.random() ) * 0x10000 ).toString( 16 ).substring( 1 );
}
return uuid;
},
/**
* Creates a function override.
*
* var obj = {
* myFunction: function( name ) {
* alert( 'Name: ' + name );
* }
* };
*
* obj.myFunction = CKEDITOR.tools.override( obj.myFunction, function( myFunctionOriginal ) {
* return function( name ) {
* alert( 'Overriden name: ' + name );
* myFunctionOriginal.call( this, name );
* };
* } );
*
* @param {Function} originalFunction The function to be overridden.
* @param {Function} functionBuilder A function that returns the new
* function. The original function reference will be passed to this function.
* @returns {Function} The new function.
*/
override: function( originalFunction, functionBuilder ) {
var newFn = functionBuilder( originalFunction );
newFn.prototype = originalFunction.prototype;
return newFn;
},
/**
* Executes a function after a specified delay.
*
* CKEDITOR.tools.setTimeout( function() {
* alert( 'Executed after 2 seconds' );
* }, 2000 );
*
* @param {Function} func The function to be executed.
* @param {Number} [milliseconds=0] The amount of time (in milliseconds) to wait
* to fire the function execution.
* @param {Object} [scope=window] The object to store the function execution scope
* (the `this` object).
* @param {Object/Array} [args] A single object, or an array of objects, to
* pass as argument to the function.
* @param {Object} [ownerWindow=window] The window that will be used to set the
* timeout.
* @returns {Object} A value that can be used to cancel the function execution.
*/
setTimeout: function( func, milliseconds, scope, args, ownerWindow ) {
if ( !ownerWindow )
ownerWindow = window;
if ( !scope )
scope = ownerWindow;
return ownerWindow.setTimeout( function() {
if ( args )
func.apply( scope, [].concat( args ) );
else
func.apply( scope );
}, milliseconds || 0 );
},
/**
* Returns a wrapper that exposes an `input` function, which acts as a proxy to the given `output` function, providing throttling.
* This proxy guarantees that the `output` function is not called more often than the `minInterval`.
*
* If multiple calls occur within a single `minInterval` time, the most recent `input` call with its arguments will be used to schedule
* the next `output` call, and the previous throttled calls will be discarded.
*
* The first `input` call is always executed asynchronously which means that the `output` call will be executed immediately.
*
* ```javascript
* var buffer = CKEDITOR.tools.throttle( 200, function( message ) {
* console.log( message );
* } );
*
* buffer.input( 'foo!' );
* // 'foo!' logged immediately.
* buffer.input( 'bar!' );
* // Nothing logged.
* buffer.input( 'baz!' );
* // Nothing logged.
* // … after 200ms a single 'baz!' will be logged.
* ```
*
* It can be easily used with events:
*
* ```javascript
* var buffer = CKEDITOR.tools.throttle( 200, function( evt ) {
* console.log( evt.data.text );
* } );
*
* editor.on( 'key', buffer.input );
* // Note: There is no need to bind the buffer as a context.
* ```
*
* @since 4.10.0
* @param {Number} minInterval The minimum interval between `output` calls in milliseconds.
* @param {Function} output The function that will be executed as `output`.
* @param {Object} [contextObj] The object used as context to the listener call (the `this` object).
* @returns {Object}
* @returns {Function} return.input The buffer input method.
* Accepts parameters which will be directly passed to the `output` function.
* @returns {Function} return.reset Resets buffered calls — `output` will not be executed
* until the next `input` is triggered.
*/
throttle: createBufferFunction( true ),
/**
* Removes spaces from the start and the end of a string. The following
* characters are removed: space, tab, line break, line feed.
*
* alert( CKEDITOR.tools.trim( ' example ' ); // 'example'
*
* @method
* @param {String} str The text from which the spaces will be removed.
* @returns {String} The modified string without the boundary spaces.
*/
trim: ( function() {
// We are not using \s because we don't want "non-breaking spaces" to be caught.
var trimRegex = /(?:^[ \t\n\r]+)|(?:[ \t\n\r]+$)/g;
return function( str ) {
return str.replace( trimRegex, '' );
};
} )(),
/**
* Removes spaces from the start (left) of a string. The following
* characters are removed: space, tab, line break, line feed.
*
* alert( CKEDITOR.tools.ltrim( ' example ' ); // 'example '
*
* @method
* @param {String} str The text from which the spaces will be removed.
* @returns {String} The modified string excluding the removed spaces.
*/
ltrim: ( function() {
// We are not using \s because we don't want "non-breaking spaces" to be caught.
var trimRegex = /^[ \t\n\r]+/g;
return function( str ) {
return str.replace( trimRegex, '' );
};
} )(),
/**
* Removes spaces from the end (right) of a string. The following
* characters are removed: space, tab, line break, line feed.
*
* alert( CKEDITOR.tools.ltrim( ' example ' ); // ' example'
*
* @method
* @param {String} str The text from which spaces will be removed.
* @returns {String} The modified string excluding the removed spaces.
*/
rtrim: ( function() {
// We are not using \s because we don't want "non-breaking spaces" to be caught.
var trimRegex = /[ \t\n\r]+$/g;
return function( str ) {
return str.replace( trimRegex, '' );
};
} )(),
/**
* Returns the index of an element in an array.
*
* var letters = [ 'a', 'b', 0, 'c', false ];
* alert( CKEDITOR.tools.indexOf( letters, '0' ) ); // -1 because 0 !== '0'
* alert( CKEDITOR.tools.indexOf( letters, false ) ); // 4 because 0 !== false
*
* @param {Array} array The array to be searched.
* @param {Object/Function} value The element to be found. This can be an
* evaluation function which receives a single parameter call for
* each entry in the array, returning `true` if the entry matches.
* @returns {Number} The (zero-based) index of the first entry that matches
* the entry, or `-1` if not found.
*/
indexOf: function( array, value ) {
if ( typeof value == 'function' ) {
for ( var i = 0, len = array.length; i < len; i++ ) {
if ( value( array[ i ] ) )
return i;
}
} else if ( array.indexOf )
return array.indexOf( value );
else {
for ( i = 0, len = array.length; i < len; i++ ) {
if ( array[ i ] === value )
return i;
}
}
return -1;
},
/**
* Returns the index of an element in an array.
*
* var obj = { prop: true };
* var letters = [ 'a', 'b', 0, obj, false ];
*
* alert( CKEDITOR.tools.indexOf( letters, '0' ) ); // null
* alert( CKEDITOR.tools.indexOf( letters, function( value ) {
* // Return true when passed value has property 'prop'.
* return value && 'prop' in value;
* } ) ); // obj
*
* @param {Array} array The array to be searched.
* @param {Object/Function} value The element to be found. Can be an
* evaluation function which receives a single parameter call for
* each entry in the array, returning `true` if the entry matches.
* @returns Object The value that was found in an array.
*/
search: function( array, value ) {
var index = CKEDITOR.tools.indexOf( array, value );
return index >= 0 ? array[ index ] : null;
},
/**
* Creates a function that will always execute in the context of a
* specified object.
*
* var obj = { text: 'My Object' };
*
* function alertText() {
* alert( this.text );
* }
*
* var newFunc = CKEDITOR.tools.bind( alertText, obj );
* newFunc(); // Alerts 'My Object'.
*
* @param {Function} func The function to be executed.
* @param {Object} obj The object to which the execution context will be bound.
* @returns {Function} The function that can be used to execute the
* `func` function in the context of `obj`.
*/
bind: function( func, obj ) {
return function() {
return func.apply( obj, arguments );
};
},
/**
* Class creation based on prototype inheritance which supports of the
* following features:
*
* * Static fields
* * Private fields
* * Public (prototype) fields
* * Chainable base class constructor
*
* @param {Object} definition The class definition object.
* @returns {Function} A class-like JavaScript function.
*/
createClass: function( definition ) {
var $ = definition.$,
baseClass = definition.base,
privates = definition.privates || definition._,
proto = definition.proto,
statics = definition.statics;
// Create the constructor, if not present in the definition.
!$ && ( $ = function() {
baseClass && this.base.apply( this, arguments );
} );
if ( privates ) {
var originalConstructor = $;
$ = function() {
// Create (and get) the private namespace.
var _ = this._ || ( this._ = {} );
// Make some magic so "this" will refer to the main
// instance when coding private functions.
for ( var privateName in privates ) {
var priv = privates[ privateName ];
_[ privateName ] = ( typeof priv == 'function' ) ? CKEDITOR.tools.bind( priv, this ) : priv;
}
originalConstructor.apply( this, arguments );
};
}
if ( baseClass ) {
$.prototype = this.prototypedCopy( baseClass.prototype );
$.prototype.constructor = $;
// Super references.
$.base = baseClass;
$.baseProto = baseClass.prototype;
// Super constructor.
$.prototype.base = function() {
this.base = baseClass.prototype.base;
baseClass.apply( this, arguments );
this.base = arguments.callee;
};
}
if ( proto )
this.extend( $.prototype, proto, true );
if ( statics )
this.extend( $, statics, true );
return $;
},
/**
* Creates a function reference that can be called later using
* {@link #callFunction}. This approach is especially useful to
* make DOM attribute function calls to JavaScript-defined functions.
*
* var ref = CKEDITOR.tools.addFunction( function() {
* alert( 'Hello!');
* } );
* CKEDITOR.tools.callFunction( ref ); // 'Hello!'
*
* @param {Function} fn The function to be executed on call.
* @param {Object} [scope] The object to have the context on `fn` execution.
* @returns {Number} A unique reference to be used in conjuction with
* {@link #callFunction}.
*/
addFunction: function( fn, scope ) {
return functions.push( function() {
return fn.apply( scope || this, arguments );
} ) - 1;
},
/**
* Removes the function reference created with {@link #addFunction}.
*
* @param {Number} ref The function reference created with
* {@link #addFunction}.
*/
removeFunction: function( ref ) {
functions[ ref ] = null;
},
/**
* Executes a function based on the reference created with {@link #addFunction}.
*
* var ref = CKEDITOR.tools.addFunction( function() {
* alert( 'Hello!');
* } );
* CKEDITOR.tools.callFunction( ref ); // 'Hello!'
*
* @param {Number} ref The function reference created with {@link #addFunction}.
* @param {Mixed} params Any number of parameters to be passed to the executed function.
* @returns {Mixed} The return value of the function.
*/
callFunction: function( ref ) {
var fn = functions[ ref ];
return fn && fn.apply( window, Array.prototype.slice.call( arguments, 1 ) );
},
/**
* Appends the `px` length unit to the size value if it is missing.
*
* var cssLength = CKEDITOR.tools.cssLength;
* cssLength( 42 ); // '42px'
* cssLength( '42' ); // '42px'
* cssLength( '42px' ); // '42px'
* cssLength( '42%' ); // '42%'
* cssLength( 'bold' ); // 'bold'
* cssLength( false ); // ''
* cssLength( NaN ); // ''
*
* @method
* @param {Number/String/Boolean} length
*/
cssLength: ( function() {
var pixelRegex = /^-?\d+\.?\d*px$/,
lengthTrimmed;
return function( length ) {
lengthTrimmed = CKEDITOR.tools.trim( length + '' ) + 'px';
if ( pixelRegex.test( lengthTrimmed ) )
return lengthTrimmed;
else
return length || '';
};
} )(),
/**
* Converts the specified CSS length value to the calculated pixel length inside this page.
*
* **Note:** Percentage-based value is left intact.
*
* @method
* @param {String} cssLength CSS length value.
*/
convertToPx: ( function() {
var calculator;
return function( cssLength ) {
if ( !calculator ) {
calculator = CKEDITOR.dom.element.createFromHtml( '<div style="position:absolute;left:-9999px;' +
'top:-9999px;margin:0px;padding:0px;border:0px;"' +
'></div>', CKEDITOR.document );
CKEDITOR.document.getBody().append( calculator );
}
if ( !( /%$/ ).test( cssLength ) ) {
calculator.setStyle( 'width', cssLength );
return calculator.$.clientWidth;
}
return cssLength;
};
} )(),
/**
* String specified by `str` repeats `times` times.
*
* @param {String} str
* @param {Number} times
* @returns {String}
*/
repeat: function( str, times ) {
return new Array( times + 1 ).join( str );
},
/**
* Returns the first successfully executed return value of a function that
* does not throw any exception.
*
* @param {Function...} fn
* @returns {Mixed}
*/
tryThese: function() {
var returnValue;
for ( var i = 0, length = arguments.length; i < length; i++ ) {
var lambda = arguments[ i ];
try {
returnValue = lambda();
break;
} catch ( e ) {}
}
return returnValue;
},
/**
* Generates a combined key from a series of params.
*
* var key = CKEDITOR.tools.genKey( 'key1', 'key2', 'key3' );
* alert( key ); // 'key1-key2-key3'.
*
* @param {String} subKey One or more strings used as subkeys.
* @returns {String}
*/
genKey: function() {
return Array.prototype.slice.call( arguments ).join( '-' );
},
/**
* Creates a "deferred" function which will not run immediately,
* but rather runs as soon as the interpreter’s call stack is empty.
* Behaves much like `window.setTimeout` with a delay.
*
* **Note:** The return value of the original function will be lost.
*
* @param {Function} fn The callee function.
* @returns {Function} The new deferred function.
*/
defer: function( fn ) {
return function() {
var args = arguments,
self = this;
window.setTimeout( function() {
fn.apply( self, args );
}, 0 );
};
},
/**
* Normalizes CSS data in order to avoid differences in the style attribute.
*
* @param {String} styleText The style data to be normalized.
* @param {Boolean} [nativeNormalize=false] Parse the data using the browser.
* @returns {String} The normalized value.
*/
normalizeCssText: function( styleText, nativeNormalize ) {