]> git.immae.eu Git - perso/Immae/Projets/packagist/ludivine-ckeditor-component.git/blame - sources/core/style.js
Update to 4.7.3
[perso/Immae/Projets/packagist/ludivine-ckeditor-component.git] / sources / core / style.js
CommitLineData
c63493c8
IB
1/**
2 * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
3 * For licensing, see LICENSE.md or http://ckeditor.com/license
4 */
5
6'use strict';
7
8/**
9 * Block style type.
10 *
11 * Read more in the {@link CKEDITOR.style} class documentation.
12 *
13 * @readonly
14 * @property {Number} [=1]
15 * @member CKEDITOR
16 */
17CKEDITOR.STYLE_BLOCK = 1;
18
19/**
20 * Inline style type.
21 *
22 * Read more in the {@link CKEDITOR.style} class documentation.
23 *
24 * @readonly
25 * @property {Number} [=2]
26 * @member CKEDITOR
27 */
28CKEDITOR.STYLE_INLINE = 2;
29
30/**
31 * Object style type.
32 *
33 * Read more in the {@link CKEDITOR.style} class documentation.
34 *
35 * @readonly
36 * @property {Number} [=3]
37 * @member CKEDITOR
38 */
39CKEDITOR.STYLE_OBJECT = 3;
40
41( function() {
42 var blockElements = {
43 address: 1, div: 1, h1: 1, h2: 1, h3: 1, h4: 1, h5: 1, h6: 1, p: 1,
44 pre: 1, section: 1, header: 1, footer: 1, nav: 1, article: 1, aside: 1, figure: 1,
45 dialog: 1, hgroup: 1, time: 1, meter: 1, menu: 1, command: 1, keygen: 1, output: 1,
46 progress: 1, details: 1, datagrid: 1, datalist: 1
47 },
48
49 objectElements = {
50 a: 1, blockquote: 1, embed: 1, hr: 1, img: 1, li: 1, object: 1, ol: 1, table: 1, td: 1,
51 tr: 1, th: 1, ul: 1, dl: 1, dt: 1, dd: 1, form: 1, audio: 1, video: 1
52 };
53
54 var semicolonFixRegex = /\s*(?:;\s*|$)/,
55 varRegex = /#\((.+?)\)/g;
56
57 var notBookmark = CKEDITOR.dom.walker.bookmark( 0, 1 ),
58 nonWhitespaces = CKEDITOR.dom.walker.whitespaces( 1 );
59
60 /**
61 * A class representing a style instance for the specific style definition.
62 * In this approach, a style is a set of properties, like attributes and styles,
63 * which can be applied to and removed from a {@link CKEDITOR.dom.selection selection} through
64 * {@link CKEDITOR.editor editor} methods: {@link CKEDITOR.editor#applyStyle} and {@link CKEDITOR.editor#removeStyle},
65 * respectively.
66 *
67 * Three default style types are available: {@link CKEDITOR#STYLE_BLOCK STYLE_BLOCK}, {@link CKEDITOR#STYLE_INLINE STYLE_INLINE},
68 * and {@link CKEDITOR#STYLE_OBJECT STYLE_OBJECT}. Based on its type, a style heavily changes its behavior.
69 * You can read more about style types in the [Style Types section of the Styles guide](#!/guide/dev_styles-section-style-types).
70 *
71 * It is possible to define a custom style type by subclassing this class by using the {@link #addCustomHandler} method.
72 * However, because of great complexity of the styles handling job, it is only possible in very specific cases.
73 *
74 * ### Usage
75 *
76 * Basic usage:
77 *
78 * // Define a block style.
79 * var style = new CKEDITOR.style( { element: 'h1' } );
80 *
81 * // Considering the following selection:
82 * // <p>Foo</p><p>Bar^</p>
83 * // Executing:
84 * editor.applyStyle( style );
85 * // Will give:
86 * // <p>Foo</p><h1>Bar^</h1>
87 * style.checkActive( editor.elementPath(), editor ); // -> true
88 *
89 * editor.removeStyle( style );
90 * // Will give:
91 * // <p>Foo</p><p>Bar^</p>
92 *
93 * style.checkActive( editor.elementPath(), editor ); // -> false
94 *
95 * Object style:
96 *
97 * // Define an object style.
98 * var style = new CKEDITOR.style( { element: 'img', attributes: { 'class': 'foo' } } );
99 *
100 * // Considering the following selection:
101 * // <p><img src="bar.png" alt="" />Foo^</p>
102 * // Executing:
103 * editor.applyStyle( style );
104 * // Will not apply the style, because the image is not selected.
105 * // You can check if a style can be applied on the current selection with:
106 * style.checkApplicable( editor.elementPath(), editor ); // -> false
107 *
108 * // Considering the following selection:
109 * // <p>[<img src="bar.png" alt="" />]Foo</p>
110 * // Executing
111 * editor.applyStyle( style );
112 * // Will give:
113 * // <p>[<img src="bar.png" alt="" class="foo" />]Foo</p>
114 *
115 * ### API changes introduced in CKEditor 4.4
116 *
117 * Before CKEditor 4.4 all style instances had no access at all to the {@link CKEDITOR.editor editor instance}
118 * within which the style is used. Neither the style constructor, nor style methods were requiring
119 * passing the editor instance which made styles independent of the editor and hence its settings and state.
120 * This design decision came from CKEditor 3; it started causing problems and became an unsolvable obstacle for
121 * the {@link CKEDITOR.style.customHandlers.widget widget style handler} which we introduced in CKEditor 4.4.
122 *
123 * There were two possible solutions. Passing an editor instance to the style constructor or to every method.
124 * The first approach would be clean, however, having in mind the backward compatibility, we did not decide
125 * to go for it. It would bind the style to one editor instance, making it unusable with other editor instances.
126 * That could break many implementations reusing styles between editors. Therefore, we decided to take the longer
127 * but safer path &mdash; the editor instance became an argument for nearly all style methods, however,
128 * for backward compatibility reasons, all these methods will work without it. Even the newly
129 * implemented {@link CKEDITOR.style.customHandlers.widget widget style handler}'s methods will not fail,
130 * although they will also not work by aborting at an early stage.
131 *
132 * Therefore, you can safely upgrade to CKEditor 4.4 even if you use style methods without providing
133 * the editor instance. You must only align your code if your implementation should handle widget styles
134 * or any other custom style handler. Of course, we recommend doing this in any case to avoid potential
135 * problems in the future.
136 *
137 * @class
138 * @constructor Creates a style class instance.
139 * @param styleDefinition
140 * @param variablesValues
141 */
142 CKEDITOR.style = function( styleDefinition, variablesValues ) {
143 if ( typeof styleDefinition.type == 'string' )
144 return new CKEDITOR.style.customHandlers[ styleDefinition.type ]( styleDefinition );
145
146 // Inline style text as attribute should be converted
147 // to styles object.
148 var attrs = styleDefinition.attributes;
149 if ( attrs && attrs.style ) {
150 styleDefinition.styles = CKEDITOR.tools.extend( {},
151 styleDefinition.styles, CKEDITOR.tools.parseCssText( attrs.style ) );
152 delete attrs.style;
153 }
154
155 if ( variablesValues ) {
156 styleDefinition = CKEDITOR.tools.clone( styleDefinition );
157
158 replaceVariables( styleDefinition.attributes, variablesValues );
159 replaceVariables( styleDefinition.styles, variablesValues );
160 }
161
162 var element = this.element = styleDefinition.element ?
163 (
164 typeof styleDefinition.element == 'string' ?
165 styleDefinition.element.toLowerCase() : styleDefinition.element
166 ) : '*';
167
168 this.type = styleDefinition.type ||
169 (
170 blockElements[ element ] ? CKEDITOR.STYLE_BLOCK :
171 objectElements[ element ] ? CKEDITOR.STYLE_OBJECT :
172 CKEDITOR.STYLE_INLINE
173 );
174
175 // If the 'element' property is an object with a set of possible element, it will be applied like an object style: only to existing elements
176 if ( typeof this.element == 'object' )
177 this.type = CKEDITOR.STYLE_OBJECT;
178
179 this._ = {
180 definition: styleDefinition
181 };
182 };
183
184 CKEDITOR.style.prototype = {
185 /**
186 * Applies the style on the editor's current selection.
187 *
188 * Before the style is applied, the method checks if the {@link #checkApplicable style is applicable}.
189 *
190 * **Note:** The recommended way of applying the style is by using the
191 * {@link CKEDITOR.editor#applyStyle} method, which is a shorthand for this method.
192 *
193 * @param {CKEDITOR.editor/CKEDITOR.dom.document} editor The editor instance in which
194 * the style will be applied.
195 * A {@link CKEDITOR.dom.document} instance is accepted for backward compatibility
196 * reasons, although since CKEditor 4.4 this type of argument is deprecated. Read more about
197 * the signature change in the {@link CKEDITOR.style} documentation.
198 */
199 apply: function( editor ) {
200 // Backward compatibility.
201 if ( editor instanceof CKEDITOR.dom.document )
202 return applyStyleOnSelection.call( this, editor.getSelection() );
203
204 if ( this.checkApplicable( editor.elementPath(), editor ) ) {
205 var initialEnterMode = this._.enterMode;
206
207 // See comment in removeStyle.
208 if ( !initialEnterMode )
209 this._.enterMode = editor.activeEnterMode;
210 applyStyleOnSelection.call( this, editor.getSelection(), 0, editor );
211 this._.enterMode = initialEnterMode;
212 }
213 },
214
215 /**
216 * Removes the style from the editor's current selection.
217 *
218 * Before the style is applied, the method checks if {@link #checkApplicable style could be applied}.
219 *
220 * **Note:** The recommended way of removing the style is by using the
221 * {@link CKEDITOR.editor#removeStyle} method, which is a shorthand for this method.
222 *
223 * @param {CKEDITOR.editor/CKEDITOR.dom.document} editor The editor instance in which
224 * the style will be removed.
225 * A {@link CKEDITOR.dom.document} instance is accepted for backward compatibility
226 * reasons, although since CKEditor 4.4 this type of argument is deprecated. Read more about
227 * the signature change in the {@link CKEDITOR.style} documentation.
228 */
229 remove: function( editor ) {
230 // Backward compatibility.
231 if ( editor instanceof CKEDITOR.dom.document )
232 return applyStyleOnSelection.call( this, editor.getSelection(), 1 );
233
234 if ( this.checkApplicable( editor.elementPath(), editor ) ) {
235 var initialEnterMode = this._.enterMode;
236
237 // Before CKEditor 4.4 style knew nothing about editor, so in order to provide enterMode
1794320d 238 // which should be used developers were forced to hack the style object (see http://dev.ckeditor.com/ticket/10190).
c63493c8
IB
239 // Since CKEditor 4.4 style knows about editor (at least when it's being applied/removed), but we
240 // use _.enterMode for backward compatibility with those hacks.
241 // Note: we should not change style's enter mode if it was already set.
242 if ( !initialEnterMode )
243 this._.enterMode = editor.activeEnterMode;
244 applyStyleOnSelection.call( this, editor.getSelection(), 1, editor );
245 this._.enterMode = initialEnterMode;
246 }
247 },
248
249 /**
250 * Applies the style on the provided range. Unlike {@link #apply} this
251 * method does not take care of setting the selection, however, the range
252 * is updated to the correct place.
253 *
254 * **Note:** If you want to apply the style on the editor selection,
255 * you probably want to use {@link CKEDITOR.editor#applyStyle}.
256 *
257 * @param {CKEDITOR.dom.range} range
258 * @param {CKEDITOR.editor} editor The editor instance. Required argument since
259 * CKEditor 4.4. The style system will work without it, but it is highly
260 * recommended to provide it for integration with all features. Read more about
261 * the signature change in the {@link CKEDITOR.style} documentation.
262 */
263 applyToRange: function( range ) {
264 this.applyToRange =
265 this.type == CKEDITOR.STYLE_INLINE ? applyInlineStyle :
266 this.type == CKEDITOR.STYLE_BLOCK ? applyBlockStyle :
267 this.type == CKEDITOR.STYLE_OBJECT ? applyObjectStyle :
268 null;
269
270 return this.applyToRange( range );
271 },
272
273 /**
274 * Removes the style from the provided range. Unlike {@link #remove} this
275 * method does not take care of setting the selection, however, the range
276 * is updated to the correct place.
277 *
278 * **Note:** If you want to remove the style from the editor selection,
279 * you probably want to use {@link CKEDITOR.editor#removeStyle}.
280 *
281 * @param {CKEDITOR.dom.range} range
282 * @param {CKEDITOR.editor} editor The editor instance. Required argument since
283 * CKEditor 4.4. The style system will work without it, but it is highly
284 * recommended to provide it for integration with all features. Read more about
285 * the signature change in the {@link CKEDITOR.style} documentation.
286 */
287 removeFromRange: function( range ) {
288 this.removeFromRange =
289 this.type == CKEDITOR.STYLE_INLINE ? removeInlineStyle :
290 this.type == CKEDITOR.STYLE_BLOCK ? removeBlockStyle :
291 this.type == CKEDITOR.STYLE_OBJECT ? removeObjectStyle :
292 null;
293
294 return this.removeFromRange( range );
295 },
296
297 /**
298 * Applies the style to the element. This method bypasses all checks
299 * and applies the style attributes directly on the provided element. Use with caution.
300 *
301 * See {@link CKEDITOR.editor#applyStyle}.
302 *
303 * @param {CKEDITOR.dom.element} element
304 * @param {CKEDITOR.editor} editor The editor instance. Required argument since
305 * CKEditor 4.4. The style system will work without it, but it is highly
306 * recommended to provide it for integration with all features. Read more about
307 * the signature change in the {@link CKEDITOR.style} documentation.
308 */
309 applyToObject: function( element ) {
310 setupElement( element, this );
311 },
312
313 /**
314 * Gets the style state inside the elements path.
315 *
316 * @param {CKEDITOR.dom.elementPath} elementPath
317 * @param {CKEDITOR.editor} editor The editor instance. Required argument since
318 * CKEditor 4.4. The style system will work without it, but it is highly
319 * recommended to provide it for integration with all features. Read more about
320 * the signature change in the {@link CKEDITOR.style} documentation.
321 * @returns {Boolean} `true` if the element is active in the elements path.
322 */
323 checkActive: function( elementPath, editor ) {
324 switch ( this.type ) {
325 case CKEDITOR.STYLE_BLOCK:
326 return this.checkElementRemovable( elementPath.block || elementPath.blockLimit, true, editor );
327
328 case CKEDITOR.STYLE_OBJECT:
329 case CKEDITOR.STYLE_INLINE:
330
331 var elements = elementPath.elements;
332
333 for ( var i = 0, element; i < elements.length; i++ ) {
334 element = elements[ i ];
335
336 if ( this.type == CKEDITOR.STYLE_INLINE && ( element == elementPath.block || element == elementPath.blockLimit ) )
337 continue;
338
339 if ( this.type == CKEDITOR.STYLE_OBJECT ) {
340 var name = element.getName();
341 if ( !( typeof this.element == 'string' ? name == this.element : name in this.element ) )
342 continue;
343 }
344
345 if ( this.checkElementRemovable( element, true, editor ) )
346 return true;
347 }
348 }
349 return false;
350 },
351
352 /**
353 * Whether this style can be applied at the specified elements path.
354 *
355 * @param {CKEDITOR.dom.elementPath} elementPath The elements path to
356 * check the style against.
357 * @param {CKEDITOR.editor} editor The editor instance. Required argument since
358 * CKEditor 4.4. The style system will work without it, but it is highly
359 * recommended to provide it for integration with all features. Read more about
360 * the signature change in the {@link CKEDITOR.style} documentation.
361 * @param {CKEDITOR.filter} [filter] If defined, the style will be
362 * checked against this filter as well.
363 * @returns {Boolean} `true` if this style can be applied at the elements path.
364 */
365 checkApplicable: function( elementPath, editor, filter ) {
366 // Backward compatibility.
367 if ( editor && editor instanceof CKEDITOR.filter )
368 filter = editor;
369
370 if ( filter && !filter.check( this ) )
371 return false;
372
373 switch ( this.type ) {
374 case CKEDITOR.STYLE_OBJECT:
375 return !!elementPath.contains( this.element );
376 case CKEDITOR.STYLE_BLOCK:
377 return !!elementPath.blockLimit.getDtd()[ this.element ];
378 }
379
380 return true;
381 },
382
383 /**
384 * Checks if the element matches the current style definition.
385 *
386 * @param {CKEDITOR.dom.element} element
387 * @param {Boolean} fullMatch
388 * @param {CKEDITOR.editor} editor The editor instance. Required argument since
389 * CKEditor 4.4. The style system will work without it, but it is highly
390 * recommended to provide it for integration with all features. Read more about
391 * the signature change in the {@link CKEDITOR.style} documentation.
392 * @returns {Boolean}
393 */
394 checkElementMatch: function( element, fullMatch ) {
395 var def = this._.definition;
396
397 if ( !element || !def.ignoreReadonly && element.isReadOnly() )
398 return false;
399
400 var attribs,
401 name = element.getName();
402
403 // If the element name is the same as the style name.
404 if ( typeof this.element == 'string' ? name == this.element : name in this.element ) {
405 // If no attributes are defined in the element.
406 if ( !fullMatch && !element.hasAttributes() )
407 return true;
408
409 attribs = getAttributesForComparison( def );
410
411 if ( attribs._length ) {
412 for ( var attName in attribs ) {
413 if ( attName == '_length' )
414 continue;
415
416 var elementAttr = element.getAttribute( attName ) || '';
417
418 // Special treatment for 'style' attribute is required.
419 if ( attName == 'style' ? compareCssText( attribs[ attName ], elementAttr ) : attribs[ attName ] == elementAttr ) {
420 if ( !fullMatch )
421 return true;
422 } else if ( fullMatch ) {
423 return false;
424 }
425 }
426 if ( fullMatch )
427 return true;
428 } else {
429 return true;
430 }
431 }
432
433 return false;
434 },
435
436 /**
437 * Checks if an element, or any of its attributes, is removable by the
438 * current style definition.
439 *
440 * @param {CKEDITOR.dom.element} element
441 * @param {Boolean} fullMatch
442 * @param {CKEDITOR.editor} editor The editor instance. Required argument since
443 * CKEditor 4.4. The style system will work without it, but it is highly
444 * recommended to provide it for integration with all features. Read more about
445 * the signature change in the {@link CKEDITOR.style} documentation.
446 * @returns {Boolean}
447 */
448 checkElementRemovable: function( element, fullMatch, editor ) {
449 // Check element matches the style itself.
450 if ( this.checkElementMatch( element, fullMatch, editor ) )
451 return true;
452
453 // Check if the element matches the style overrides.
454 var override = getOverrides( this )[ element.getName() ];
455 if ( override ) {
456 var attribs, attName;
457
458 // If no attributes have been defined, remove the element.
459 if ( !( attribs = override.attributes ) )
460 return true;
461
462 for ( var i = 0; i < attribs.length; i++ ) {
463 attName = attribs[ i ][ 0 ];
464 var actualAttrValue = element.getAttribute( attName );
465 if ( actualAttrValue ) {
466 var attValue = attribs[ i ][ 1 ];
467
468 // Remove the attribute if:
469 // - The override definition value is null;
470 // - The override definition value is a string that
471 // matches the attribute value exactly.
472 // - The override definition value is a regex that
473 // has matches in the attribute value.
474 if ( attValue === null )
475 return true;
476 if ( typeof attValue == 'string' ) {
477 if ( actualAttrValue == attValue )
478 return true;
479 } else if ( attValue.test( actualAttrValue ) ) {
480 return true;
481 }
482 }
483 }
484 }
485 return false;
486 },
487
488 /**
489 * Builds the preview HTML based on the styles definition.
490 *
491 * @param {String} [label] The label used in the style preview.
492 * @return {String} The HTML of preview.
493 */
494 buildPreview: function( label ) {
495 var styleDefinition = this._.definition,
496 html = [],
497 elementName = styleDefinition.element;
498
499 // Avoid <bdo> in the preview.
500 if ( elementName == 'bdo' )
501 elementName = 'span';
502
503 html = [ '<', elementName ];
504
505 // Assign all defined attributes.
506 var attribs = styleDefinition.attributes;
507 if ( attribs ) {
508 for ( var att in attribs )
509 html.push( ' ', att, '="', attribs[ att ], '"' );
510 }
511
512 // Assign the style attribute.
513 var cssStyle = CKEDITOR.style.getStyleText( styleDefinition );
514 if ( cssStyle )
515 html.push( ' style="', cssStyle, '"' );
516
517 html.push( '>', ( label || styleDefinition.name ), '</', elementName, '>' );
518
519 return html.join( '' );
520 },
521
522 /**
523 * Returns the style definition.
524 *
525 * @since 4.1
526 * @returns {Object}
527 */
528 getDefinition: function() {
529 return this._.definition;
530 }
531
532 /**
533 * If defined (for example by {@link CKEDITOR.style#addCustomHandler custom style handler}), it returns
534 * the {@link CKEDITOR.filter.allowedContentRules allowed content rules} which should be added to the
535 * {@link CKEDITOR.filter} when enabling this style.
536 *
537 * **Note:** This method is not defined in the {@link CKEDITOR.style} class.
538 *
539 * @since 4.4
540 * @method toAllowedContentRules
541 * @param {CKEDITOR.editor} [editor] The editor instance.
542 * @returns {CKEDITOR.filter.allowedContentRules} The rules that should represent this style in the {@link CKEDITOR.filter}.
543 */
544 };
545
546 /**
547 * Builds the inline style text based on the style definition.
548 *
549 * @static
550 * @param styleDefinition
551 * @returns {String} Inline style text.
552 */
553 CKEDITOR.style.getStyleText = function( styleDefinition ) {
554 // If we have already computed it, just return it.
555 var stylesDef = styleDefinition._ST;
556 if ( stylesDef )
557 return stylesDef;
558
559 stylesDef = styleDefinition.styles;
560
561 // Builds the StyleText.
562 var stylesText = ( styleDefinition.attributes && styleDefinition.attributes.style ) || '',
563 specialStylesText = '';
564
565 if ( stylesText.length )
566 stylesText = stylesText.replace( semicolonFixRegex, ';' );
567
568 for ( var style in stylesDef ) {
569 var styleVal = stylesDef[ style ],
570 text = ( style + ':' + styleVal ).replace( semicolonFixRegex, ';' );
571
1794320d 572 // Some browsers don't support 'inherit' property value, leave them intact. (http://dev.ckeditor.com/ticket/5242)
c63493c8
IB
573 if ( styleVal == 'inherit' )
574 specialStylesText += text;
575 else
576 stylesText += text;
577 }
578
579 // Browsers make some changes to the style when applying them. So, here
580 // we normalize it to the browser format.
581 if ( stylesText.length )
582 stylesText = CKEDITOR.tools.normalizeCssText( stylesText, true );
583
584 stylesText += specialStylesText;
585
586 // Return it, saving it to the next request.
587 return ( styleDefinition._ST = stylesText );
588 };
589
590 /**
591 * Namespace containing custom style handlers added with {@link CKEDITOR.style#addCustomHandler}.
592 *
593 * @since 4.4
594 * @class
595 * @singleton
596 */
597 CKEDITOR.style.customHandlers = {};
598
599 /**
600 * Creates a {@link CKEDITOR.style} subclass and registers it in the style system.
601 * Registered class will be used as a handler for a style of this type. This allows
602 * to extend the styles system, which by default uses only the {@link CKEDITOR.style}, with
603 * new functionality. Registered classes are accessible in the {@link CKEDITOR.style.customHandlers}.
604 *
605 * ### The Style Class Definition
606 *
607 * The definition object is used to override properties in a prototype inherited
608 * from the {@link CKEDITOR.style} class. It must contain a `type` property which is
609 * a name of the new type and therefore it must be unique. The default style types
610 * ({@link CKEDITOR#STYLE_BLOCK STYLE_BLOCK}, {@link CKEDITOR#STYLE_INLINE STYLE_INLINE},
611 * and {@link CKEDITOR#STYLE_OBJECT STYLE_OBJECT}) are integers, but for easier identification
612 * it is recommended to use strings as custom type names.
613 *
614 * Besides `type`, the definition may contain two more special properties:
615 *
616 * * `setup {Function}` &ndash; An optional callback executed when a style instance is created.
617 * Like the style constructor, it is executed in style context and with the style definition as an argument.
618 * * `assignedTo {Number}` &ndash; Can be set to one of the default style types. Some editor
619 * features like the Styles drop-down assign styles to one of the default groups based on
620 * the style type. By using this property it is possible to notify them to which group this
621 * custom style should be assigned. It defaults to the {@link CKEDITOR#STYLE_OBJECT}.
622 *
623 * Other properties of the definition object will just be used to extend the prototype inherited
624 * from the {@link CKEDITOR.style} class. So if the definition contains an `apply` method, it will
625 * override the {@link CKEDITOR.style#apply} method.
626 *
627 * ### Usage
628 *
629 * Registering a basic handler:
630 *
631 * var styleClass = CKEDITOR.style.addCustomHandler( {
632 * type: 'custom'
633 * } );
634 *
635 * var style = new styleClass( { ... } );
636 * style instanceof styleClass; // -> true
637 * style instanceof CKEDITOR.style; // -> true
638 * style.type; // -> 'custom'
639 *
640 * The {@link CKEDITOR.style} constructor used as a factory:
641 *
642 * var styleClass = CKEDITOR.style.addCustomHandler( {
643 * type: 'custom'
644 * } );
645 *
646 * // Style constructor accepts style definition (do not confuse with style class definition).
647 * var style = new CKEDITOR.style( { type: 'custom', attributes: ... } );
648 * style instanceof styleClass; // -> true
649 *
650 * Thanks to that, integration code using styles does not need to know
651 * which style handler it should use. It is determined by the {@link CKEDITOR.style} constructor.
652 *
653 * Overriding existing {@link CKEDITOR.style} methods:
654 *
655 * var styleClass = CKEDITOR.style.addCustomHandler( {
656 * type: 'custom',
657 * apply: function( editor ) {
658 * console.log( 'apply' );
659 * },
660 * remove: function( editor ) {
661 * console.log( 'remove' );
662 * }
663 * } );
664 *
665 * var style = new CKEDITOR.style( { type: 'custom', attributes: ... } );
666 * editor.applyStyle( style ); // logged 'apply'
667 *
668 * style = new CKEDITOR.style( { element: 'img', attributes: { 'class': 'foo' } } );
669 * editor.applyStyle( style ); // style is really applied if image was selected
670 *
671 * ### Practical Recommendations
672 *
673 * The style handling job, which includes such tasks as applying, removing, checking state, and
674 * checking if a style can be applied, is very complex. Therefore without deep knowledge
675 * about DOM and especially {@link CKEDITOR.dom.range ranges} and {@link CKEDITOR.dom.walker DOM walker} it is impossible
676 * to implement a completely custom style handler able to handle block, inline, and object type styles.
677 * However, it is possible to customize the default implementation by overriding default methods and
678 * reusing them.
679 *
680 * The only style handler which can be implemented from scratch without huge effort is a style
681 * applicable to objects ([read more about types](http://docs.ckeditor.com/#!/guide/dev_styles-section-style-types)).
682 * Such style can only be applied when a specific object is selected. An example implementation can
683 * be found in the [widget plugin](https://github.com/ckeditor/ckeditor-dev/blob/master/plugins/widget/plugin.js).
684 *
685 * When implementing a style handler from scratch at least the following methods must be defined:
686 *
687 * * {@link CKEDITOR.style#apply apply} and {@link CKEDITOR.style#remove remove},
688 * * {@link CKEDITOR.style#checkElementRemovable checkElementRemovable} and
689 * {@link CKEDITOR.style#checkElementMatch checkElementMatch} &ndash; Note that both methods reuse the same logic,
690 * * {@link CKEDITOR.style#checkActive checkActive} &ndash; Reuses
691 * {@link CKEDITOR.style#checkElementMatch checkElementMatch},
692 * * {@link CKEDITOR.style#toAllowedContentRules toAllowedContentRules} &ndash; Not required, but very useful in
693 * case of a custom style that has to notify the {@link CKEDITOR.filter} which rules it allows when registered.
694 *
695 * @since 4.4
696 * @static
697 * @member CKEDITOR.style
698 * @param definition The style class definition.
699 * @returns {CKEDITOR.style} The new style class created for the provided definition.
700 */
701 CKEDITOR.style.addCustomHandler = function( definition ) {
702 var styleClass = function( styleDefinition ) {
703 this._ = {
704 definition: styleDefinition
705 };
706
707 if ( this.setup )
708 this.setup( styleDefinition );
709 };
710
711 styleClass.prototype = CKEDITOR.tools.extend(
712 // Prototype of CKEDITOR.style.
713 CKEDITOR.tools.prototypedCopy( CKEDITOR.style.prototype ),
714 // Defaults.
715 {
716 assignedTo: CKEDITOR.STYLE_OBJECT
717 },
718 // Passed definition - overrides.
719 definition,
720 true
721 );
722
723 this.customHandlers[ definition.type ] = styleClass;
724
725 return styleClass;
726 };
727
728 // Gets the parent element which blocks the styling for an element. This
729 // can be done through read-only elements (contenteditable=false) or
730 // elements with the "data-nostyle" attribute.
731 function getUnstylableParent( element, root ) {
732 var unstylable, editable;
733
734 while ( ( element = element.getParent() ) ) {
735 if ( element.equals( root ) )
736 break;
737
738 if ( element.getAttribute( 'data-nostyle' ) )
739 unstylable = element;
740 else if ( !editable ) {
741 var contentEditable = element.getAttribute( 'contentEditable' );
742
743 if ( contentEditable == 'false' )
744 unstylable = element;
745 else if ( contentEditable == 'true' )
746 editable = 1;
747 }
748 }
749
750 return unstylable;
751 }
752
753 var posPrecedingIdenticalContained =
754 CKEDITOR.POSITION_PRECEDING | CKEDITOR.POSITION_IDENTICAL | CKEDITOR.POSITION_IS_CONTAINED,
755 posFollowingIdenticalContained =
756 CKEDITOR.POSITION_FOLLOWING | CKEDITOR.POSITION_IDENTICAL | CKEDITOR.POSITION_IS_CONTAINED;
757
758 // Checks if the current node can be a child of the style element.
759 function checkIfNodeCanBeChildOfStyle( def, currentNode, lastNode, nodeName, dtd, nodeIsNoStyle, nodeIsReadonly, includeReadonly ) {
760 // Style can be applied to text node.
761 if ( !nodeName )
762 return 1;
763
764 // Style definitely cannot be applied if DTD or data-nostyle do not allow.
765 if ( !dtd[ nodeName ] || nodeIsNoStyle )
766 return 0;
767
768 // Non-editable element cannot be styled is we shouldn't include readonly elements.
769 if ( nodeIsReadonly && !includeReadonly )
770 return 0;
771
772 // Check that we haven't passed lastNode yet and that style's childRule allows this style on current element.
773 return checkPositionAndRule( currentNode, lastNode, def, posPrecedingIdenticalContained );
774 }
775
776 // Check if the style element can be a child of the current
777 // node parent or if the element is not defined in the DTD.
778 function checkIfStyleCanBeChildOf( def, currentParent, elementName, isUnknownElement ) {
779 return currentParent &&
780 ( ( currentParent.getDtd() || CKEDITOR.dtd.span )[ elementName ] || isUnknownElement ) &&
781 ( !def.parentRule || def.parentRule( currentParent ) );
782 }
783
784 function checkIfStartsRange( nodeName, currentNode, lastNode ) {
785 return (
786 !nodeName || !CKEDITOR.dtd.$removeEmpty[ nodeName ] ||
787 ( currentNode.getPosition( lastNode ) | posPrecedingIdenticalContained ) == posPrecedingIdenticalContained
788 );
789 }
790
791 function checkIfTextOrReadonlyOrEmptyElement( currentNode, nodeIsReadonly ) {
792 var nodeType = currentNode.type;
793 return nodeType == CKEDITOR.NODE_TEXT || nodeIsReadonly || ( nodeType == CKEDITOR.NODE_ELEMENT && !currentNode.getChildCount() );
794 }
795
796 // Checks if position is a subset of posBitFlags and that nodeA fulfills style def rule.
797 function checkPositionAndRule( nodeA, nodeB, def, posBitFlags ) {
798 return ( nodeA.getPosition( nodeB ) | posBitFlags ) == posBitFlags &&
799 ( !def.childRule || def.childRule( nodeA ) );
800 }
801
802 function applyInlineStyle( range ) {
803 var document = range.document;
804
805 if ( range.collapsed ) {
806 // Create the element to be inserted in the DOM.
807 var collapsedElement = getElement( this, document );
808
809 // Insert the empty element into the DOM at the range position.
810 range.insertNode( collapsedElement );
811
812 // Place the selection right inside the empty element.
813 range.moveToPosition( collapsedElement, CKEDITOR.POSITION_BEFORE_END );
814
815 return;
816 }
817
818 var elementName = this.element,
819 def = this._.definition,
820 isUnknownElement;
821
822 // Indicates that fully selected read-only elements are to be included in the styling range.
823 var ignoreReadonly = def.ignoreReadonly,
824 includeReadonly = ignoreReadonly || def.includeReadonly;
825
826 // If the read-only inclusion is not available in the definition, try
827 // to get it from the root data (most often it's the editable).
828 if ( includeReadonly == null )
829 includeReadonly = range.root.getCustomData( 'cke_includeReadonly' );
830
831 // Get the DTD definition for the element. Defaults to "span".
832 var dtd = CKEDITOR.dtd[ elementName ];
833 if ( !dtd ) {
834 isUnknownElement = true;
835 dtd = CKEDITOR.dtd.span;
836 }
837
838 // Expand the range.
839 range.enlarge( CKEDITOR.ENLARGE_INLINE, 1 );
840 range.trim();
841
842 // Get the first node to be processed and the last, which concludes the processing.
843 var boundaryNodes = range.createBookmark(),
844 firstNode = boundaryNodes.startNode,
845 lastNode = boundaryNodes.endNode,
846 currentNode = firstNode,
847 styleRange;
848
849 if ( !ignoreReadonly ) {
850 // Check if the boundaries are inside non stylable elements.
851 var root = range.getCommonAncestor(),
852 firstUnstylable = getUnstylableParent( firstNode, root ),
853 lastUnstylable = getUnstylableParent( lastNode, root );
854
855 // If the first element can't be styled, we'll start processing right
856 // after its unstylable root.
857 if ( firstUnstylable )
858 currentNode = firstUnstylable.getNextSourceNode( true );
859
860 // If the last element can't be styled, we'll stop processing on its
861 // unstylable root.
862 if ( lastUnstylable )
863 lastNode = lastUnstylable;
864 }
865
866 // Do nothing if the current node now follows the last node to be processed.
867 if ( currentNode.getPosition( lastNode ) == CKEDITOR.POSITION_FOLLOWING )
868 currentNode = 0;
869
870 while ( currentNode ) {
871 var applyStyle = false;
872
873 if ( currentNode.equals( lastNode ) ) {
874 currentNode = null;
875 applyStyle = true;
876 } else {
877 var nodeName = currentNode.type == CKEDITOR.NODE_ELEMENT ? currentNode.getName() : null,
878 nodeIsReadonly = nodeName && ( currentNode.getAttribute( 'contentEditable' ) == 'false' ),
879 nodeIsNoStyle = nodeName && currentNode.getAttribute( 'data-nostyle' );
880
881 // Skip bookmarks.
882 if ( nodeName && currentNode.data( 'cke-bookmark' ) ) {
883 currentNode = currentNode.getNextSourceNode( true );
884 continue;
885 }
886
887 // Find all nested editables of a non-editable block and apply this style inside them.
888 if ( nodeIsReadonly && includeReadonly && CKEDITOR.dtd.$block[ nodeName ] )
889 applyStyleOnNestedEditables.call( this, currentNode );
890
891 // Check if the current node can be a child of the style element.
892 if ( checkIfNodeCanBeChildOfStyle( def, currentNode, lastNode, nodeName, dtd, nodeIsNoStyle, nodeIsReadonly, includeReadonly ) ) {
893 var currentParent = currentNode.getParent();
894
895 // Check if the style element can be a child of the current
896 // node parent or if the element is not defined in the DTD.
897 if ( checkIfStyleCanBeChildOf( def, currentParent, elementName, isUnknownElement ) ) {
898 // This node will be part of our range, so if it has not
899 // been started, place its start right before the node.
900 // In the case of an element node, it will be included
901 // only if it is entirely inside the range.
902 if ( !styleRange && checkIfStartsRange( nodeName, currentNode, lastNode ) ) {
903 styleRange = range.clone();
904 styleRange.setStartBefore( currentNode );
905 }
906
907 // Non element nodes, readonly elements, or empty
908 // elements can be added completely to the range.
909 if ( checkIfTextOrReadonlyOrEmptyElement( currentNode, nodeIsReadonly ) ) {
910 var includedNode = currentNode;
911 var parentNode;
912
913 // This node is about to be included completelly, but,
914 // if this is the last node in its parent, we must also
915 // check if the parent itself can be added completelly
916 // to the range, otherwise apply the style immediately.
917 while (
918 ( applyStyle = !includedNode.getNext( notBookmark ) ) &&
919 ( parentNode = includedNode.getParent(), dtd[ parentNode.getName() ] ) &&
920 checkPositionAndRule( parentNode, firstNode, def, posFollowingIdenticalContained )
921 ) {
922 includedNode = parentNode;
923 }
924
925 styleRange.setEndAfter( includedNode );
926
927 }
928 } else {
929 applyStyle = true;
930 }
931 }
932 // Style isn't applicable to current element, so apply style to
933 // range ending at previously chosen position, or nowhere if we haven't
934 // yet started styleRange.
935 else {
936 applyStyle = true;
937 }
938
939 // Get the next node to be processed.
940 // If we're currently on a non-editable element or non-styleable element,
941 // then we'll be moved to current node's sibling (or even further), so we'll
942 // avoid messing up its content.
943 currentNode = currentNode.getNextSourceNode( nodeIsNoStyle || nodeIsReadonly );
944 }
945
946 // Apply the style if we have something to which apply it.
947 if ( applyStyle && styleRange && !styleRange.collapsed ) {
948 // Build the style element, based on the style object definition.
949 var styleNode = getElement( this, document ),
950 styleHasAttrs = styleNode.hasAttributes();
951
952 // Get the element that holds the entire range.
953 var parent = styleRange.getCommonAncestor();
954
955 var removeList = {
956 styles: {},
957 attrs: {},
958 // Styles cannot be removed.
959 blockedStyles: {},
960 // Attrs cannot be removed.
961 blockedAttrs: {}
962 };
963
964 var attName, styleName, value;
965
966 // Loop through the parents, removing the redundant attributes
967 // from the element to be applied.
968 while ( styleNode && parent ) {
969 if ( parent.getName() == elementName ) {
970 for ( attName in def.attributes ) {
971 if ( removeList.blockedAttrs[ attName ] || !( value = parent.getAttribute( styleName ) ) )
972 continue;
973
974 if ( styleNode.getAttribute( attName ) == value )
975 removeList.attrs[ attName ] = 1;
976 else
977 removeList.blockedAttrs[ attName ] = 1;
978 }
979
980 for ( styleName in def.styles ) {
981 if ( removeList.blockedStyles[ styleName ] || !( value = parent.getStyle( styleName ) ) )
982 continue;
983
984 if ( styleNode.getStyle( styleName ) == value )
985 removeList.styles[ styleName ] = 1;
986 else
987 removeList.blockedStyles[ styleName ] = 1;
988 }
989 }
990
991 parent = parent.getParent();
992 }
993
994 for ( attName in removeList.attrs )
995 styleNode.removeAttribute( attName );
996
997 for ( styleName in removeList.styles )
998 styleNode.removeStyle( styleName );
999
1000 if ( styleHasAttrs && !styleNode.hasAttributes() )
1001 styleNode = null;
1002
1003 if ( styleNode ) {
1004 // Move the contents of the range to the style element.
1005 styleRange.extractContents().appendTo( styleNode );
1006
1007 // Insert it into the range position (it is collapsed after
1008 // extractContents.
1009 styleRange.insertNode( styleNode );
1010
1011 // Here we do some cleanup, removing all duplicated
1012 // elements from the style element.
1013 removeFromInsideElement.call( this, styleNode );
1014
1015 // Let's merge our new style with its neighbors, if possible.
1016 styleNode.mergeSiblings();
1017
1018 // As the style system breaks text nodes constantly, let's normalize
1019 // things for performance.
1020 // With IE, some paragraphs get broken when calling normalize()
1021 // repeatedly. Also, for IE, we must normalize body, not documentElement.
1022 // IE is also known for having a "crash effect" with normalize().
1023 // We should try to normalize with IE too in some way, somewhere.
1024 if ( !CKEDITOR.env.ie )
1025 styleNode.$.normalize();
1026 }
1794320d 1027 // Style already inherit from parents, left just to clear up any internal overrides. (http://dev.ckeditor.com/ticket/5931)
c63493c8
IB
1028 else {
1029 styleNode = new CKEDITOR.dom.element( 'span' );
1030 styleRange.extractContents().appendTo( styleNode );
1031 styleRange.insertNode( styleNode );
1032 removeFromInsideElement.call( this, styleNode );
1033 styleNode.remove( true );
1034 }
1035
1036 // Style applied, let's release the range, so it gets
1037 // re-initialization in the next loop.
1038 styleRange = null;
1039 }
1040 }
1041
1042 // Remove the bookmark nodes.
1043 range.moveToBookmark( boundaryNodes );
1044
1794320d 1045 // Minimize the result range to exclude empty text nodes. (http://dev.ckeditor.com/ticket/5374)
c63493c8
IB
1046 range.shrink( CKEDITOR.SHRINK_TEXT );
1047
1048 // Get inside the remaining element if range.shrink( TEXT ) has failed because of non-editable elements inside.
1049 // E.g. range.shrink( TEXT ) will not get inside:
1050 // [<b><i contenteditable="false">x</i></b>]
1051 // but range.shrink( ELEMENT ) will.
1052 range.shrink( CKEDITOR.NODE_ELEMENT, true );
1053 }
1054
1055 function removeInlineStyle( range ) {
1056 // Make sure our range has included all "collpased" parent inline nodes so
1057 // that our operation logic can be simpler.
1058 range.enlarge( CKEDITOR.ENLARGE_INLINE, 1 );
1059
1060 var bookmark = range.createBookmark(),
1794320d
IB
1061 startNode = bookmark.startNode,
1062 alwaysRemoveElement = this._.definition.alwaysRemoveElement;
c63493c8
IB
1063
1064 if ( range.collapsed ) {
1065 var startPath = new CKEDITOR.dom.elementPath( startNode.getParent(), range.root ),
1794320d 1066 // The topmost element in elements path which we should jump out of.
c63493c8
IB
1067 boundaryElement;
1068
c63493c8
IB
1069 for ( var i = 0, element; i < startPath.elements.length && ( element = startPath.elements[ i ] ); i++ ) {
1070 // 1. If it's collaped inside text nodes, try to remove the style from the whole element.
1071 //
1072 // 2. Otherwise if it's collapsed on element boundaries, moving the selection
1073 // outside the styles instead of removing the whole tag,
1794320d
IB
1074 // also make sure other inner styles were well preserved.(http://dev.ckeditor.com/ticket/3309)
1075 //
1076 // 3. Force removing the element even if it's an boundary element when alwaysRemoveElement is true.
1077 // Without it, the links won't be unlinked if the cursor is placed right before/after it. (http://dev.ckeditor.com/ticket/13062)
1078 if ( element == startPath.block || element == startPath.blockLimit ) {
c63493c8 1079 break;
1794320d 1080 }
c63493c8
IB
1081
1082 if ( this.checkElementRemovable( element ) ) {
1083 var isStart;
1084
1794320d 1085 if ( !alwaysRemoveElement && range.collapsed && ( range.checkBoundaryOfElement( element, CKEDITOR.END ) || ( isStart = range.checkBoundaryOfElement( element, CKEDITOR.START ) ) ) ) {
c63493c8
IB
1086 boundaryElement = element;
1087 boundaryElement.match = isStart ? 'start' : 'end';
1088 } else {
1089 // Before removing the style node, there may be a sibling to the style node
1090 // that's exactly the same to the one to be removed. To the user, it makes
1091 // no difference that they're separate entities in the DOM tree. So, merge
1092 // them before removal.
1093 element.mergeSiblings();
1794320d 1094 if ( element.is( this.element ) ) {
c63493c8 1095 removeFromElement.call( this, element );
1794320d 1096 } else {
c63493c8 1097 removeOverrides( element, getOverrides( this )[ element.getName() ] );
1794320d 1098 }
c63493c8
IB
1099 }
1100 }
1101 }
1102
1103 // Re-create the style tree after/before the boundary element,
1104 // the replication start from bookmark start node to define the
1105 // new range.
1106 if ( boundaryElement ) {
1107 var clonedElement = startNode;
1108 for ( i = 0; ; i++ ) {
1109 var newElement = startPath.elements[ i ];
1110 if ( newElement.equals( boundaryElement ) )
1111 break;
1112 // Avoid copying any matched element.
1113 else if ( newElement.match )
1114 continue;
1115 else
1116 newElement = newElement.clone();
1117 newElement.append( clonedElement );
1118 clonedElement = newElement;
1119 }
1120 clonedElement[ boundaryElement.match == 'start' ? 'insertBefore' : 'insertAfter' ]( boundaryElement );
1121 }
1122 } else {
1123 // Now our range isn't collapsed. Lets walk from the start node to the end
1124 // node via DFS and remove the styles one-by-one.
1125 var endNode = bookmark.endNode,
1126 me = this;
1127
1128 breakNodes();
1129
1130 // Now, do the DFS walk.
1131 var currentNode = startNode;
1132 while ( !currentNode.equals( endNode ) ) {
1133 // Need to get the next node first because removeFromElement() can remove
1134 // the current node from DOM tree.
1135 var nextNode = currentNode.getNextSourceNode();
1136 if ( currentNode.type == CKEDITOR.NODE_ELEMENT && this.checkElementRemovable( currentNode ) ) {
1137 // Remove style from element or overriding element.
1138 if ( currentNode.getName() == this.element )
1139 removeFromElement.call( this, currentNode );
1140 else
1141 removeOverrides( currentNode, getOverrides( this )[ currentNode.getName() ] );
1142
1143 // removeFromElement() may have merged the next node with something before
1144 // the startNode via mergeSiblings(). In that case, the nextNode would
1145 // contain startNode and we'll have to call breakNodes() again and also
1146 // reassign the nextNode to something after startNode.
1147 if ( nextNode.type == CKEDITOR.NODE_ELEMENT && nextNode.contains( startNode ) ) {
1148 breakNodes();
1149 nextNode = startNode.getNext();
1150 }
1151 }
1152 currentNode = nextNode;
1153 }
1154 }
1155
1156 range.moveToBookmark( bookmark );
1157 // See the comment for range.shrink in applyInlineStyle.
1158 range.shrink( CKEDITOR.NODE_ELEMENT, true );
1159
1160 // Find out the style ancestor that needs to be broken down at startNode
1161 // and endNode.
1162 function breakNodes() {
1163 var startPath = new CKEDITOR.dom.elementPath( startNode.getParent() ),
1164 endPath = new CKEDITOR.dom.elementPath( endNode.getParent() ),
1165 breakStart = null,
1166 breakEnd = null;
1167
1168 for ( var i = 0; i < startPath.elements.length; i++ ) {
1169 var element = startPath.elements[ i ];
1170
1171 if ( element == startPath.block || element == startPath.blockLimit )
1172 break;
1173
1174 if ( me.checkElementRemovable( element, true ) )
1175 breakStart = element;
1176 }
1177
1178 for ( i = 0; i < endPath.elements.length; i++ ) {
1179 element = endPath.elements[ i ];
1180
1181 if ( element == endPath.block || element == endPath.blockLimit )
1182 break;
1183
1184 if ( me.checkElementRemovable( element, true ) )
1185 breakEnd = element;
1186 }
1187
1188 if ( breakEnd )
1189 endNode.breakParent( breakEnd );
1190 if ( breakStart )
1191 startNode.breakParent( breakStart );
1192 }
1193 }
1194
1195 // Apply style to nested editables inside editablesContainer.
1196 // @param {CKEDITOR.dom.element} editablesContainer
1197 // @context CKEDITOR.style
1198 function applyStyleOnNestedEditables( editablesContainer ) {
1199 var editables = findNestedEditables( editablesContainer ),
1200 editable,
1201 l = editables.length,
1202 i = 0,
1203 range = l && new CKEDITOR.dom.range( editablesContainer.getDocument() );
1204
1205 for ( ; i < l; ++i ) {
1206 editable = editables[ i ];
1207 // Check if style is allowed by this editable's ACF.
1208 if ( checkIfAllowedInEditable( editable, this ) ) {
1209 range.selectNodeContents( editable );
1210 applyInlineStyle.call( this, range );
1211 }
1212 }
1213 }
1214
1215 // Finds nested editables within container. Does not return
1216 // editables nested in another editable (twice).
1217 function findNestedEditables( container ) {
1218 var editables = [];
1219
1220 container.forEach( function( element ) {
1221 if ( element.getAttribute( 'contenteditable' ) == 'true' ) {
1222 editables.push( element );
1223 return false; // Skip children.
1224 }
1225 }, CKEDITOR.NODE_ELEMENT, true );
1226
1227 return editables;
1228 }
1229
1230 // Checks if style is allowed in this editable.
1231 function checkIfAllowedInEditable( editable, style ) {
1232 var filter = CKEDITOR.filter.instances[ editable.data( 'cke-filter' ) ];
1233
1234 return filter ? filter.check( style ) : 1;
1235 }
1236
1237 // Checks if style is allowed by iterator's active filter.
1238 function checkIfAllowedByIterator( iterator, style ) {
1239 return iterator.activeFilter ? iterator.activeFilter.check( style ) : 1;
1240 }
1241
1242 function applyObjectStyle( range ) {
1794320d 1243 // Selected or parent element. (http://dev.ckeditor.com/ticket/9651)
c63493c8
IB
1244 var start = range.getEnclosedNode() || range.getCommonAncestor( false, true ),
1245 element = new CKEDITOR.dom.elementPath( start, range.root ).contains( this.element, 1 );
1246
1247 element && !element.isReadOnly() && setupElement( element, this );
1248 }
1249
1250 function removeObjectStyle( range ) {
1251 var parent = range.getCommonAncestor( true, true ),
1252 element = new CKEDITOR.dom.elementPath( parent, range.root ).contains( this.element, 1 );
1253
1254 if ( !element )
1255 return;
1256
1257 var style = this,
1258 def = style._.definition,
1259 attributes = def.attributes;
1260
1261 // Remove all defined attributes.
1262 if ( attributes ) {
1263 for ( var att in attributes )
1264 element.removeAttribute( att, attributes[ att ] );
1265 }
1266
1267 // Assign all defined styles.
1268 if ( def.styles ) {
1269 for ( var i in def.styles ) {
1270 if ( def.styles.hasOwnProperty( i ) )
1271 element.removeStyle( i );
1272 }
1273 }
1274 }
1275
1276 function applyBlockStyle( range ) {
1277 // Serializible bookmarks is needed here since
1278 // elements may be merged.
1279 var bookmark = range.createBookmark( true );
1280
1281 var iterator = range.createIterator();
1282 iterator.enforceRealBlocks = true;
1283
1794320d 1284 // make recognize <br /> tag as a separator in ENTER_BR mode (http://dev.ckeditor.com/ticket/5121)
c63493c8
IB
1285 if ( this._.enterMode )
1286 iterator.enlargeBr = ( this._.enterMode != CKEDITOR.ENTER_BR );
1287
1288 var block,
1289 doc = range.document,
1290 newBlock;
1291
1292 while ( ( block = iterator.getNextParagraph() ) ) {
1293 if ( !block.isReadOnly() && checkIfAllowedByIterator( iterator, this ) ) {
1294 newBlock = getElement( this, doc, block );
1295 replaceBlock( block, newBlock );
1296 }
1297 }
1298
1299 range.moveToBookmark( bookmark );
1300 }
1301
1302 function removeBlockStyle( range ) {
1303 // Serializible bookmarks is needed here since
1304 // elements may be merged.
1305 var bookmark = range.createBookmark( 1 );
1306
1307 var iterator = range.createIterator();
1308 iterator.enforceRealBlocks = true;
1309 iterator.enlargeBr = this._.enterMode != CKEDITOR.ENTER_BR;
1310
1311 var block,
1312 newBlock;
1313
1314 while ( ( block = iterator.getNextParagraph() ) ) {
1315 if ( this.checkElementRemovable( block ) ) {
1316 // <pre> get special treatment.
1317 if ( block.is( 'pre' ) ) {
1318 newBlock = this._.enterMode == CKEDITOR.ENTER_BR ? null :
1319 range.document.createElement( this._.enterMode == CKEDITOR.ENTER_P ? 'p' : 'div' );
1320
1321 newBlock && block.copyAttributes( newBlock );
1322 replaceBlock( block, newBlock );
1323 } else {
1324 removeFromElement.call( this, block );
1325 }
1326 }
1327 }
1328
1329 range.moveToBookmark( bookmark );
1330 }
1331
1332 // Replace the original block with new one, with special treatment
1333 // for <pre> blocks to make sure content format is well preserved, and merging/splitting adjacent
1794320d 1334 // when necessary. (http://dev.ckeditor.com/ticket/3188)
c63493c8
IB
1335 function replaceBlock( block, newBlock ) {
1336 // Block is to be removed, create a temp element to
1337 // save contents.
1338 var removeBlock = !newBlock;
1339 if ( removeBlock ) {
1340 newBlock = block.getDocument().createElement( 'div' );
1341 block.copyAttributes( newBlock );
1342 }
1343
1344 var newBlockIsPre = newBlock && newBlock.is( 'pre' ),
1345 blockIsPre = block.is( 'pre' ),
1346 isToPre = newBlockIsPre && !blockIsPre,
1347 isFromPre = !newBlockIsPre && blockIsPre;
1348
1349 if ( isToPre )
1350 newBlock = toPre( block, newBlock );
1351 else if ( isFromPre )
1352 // Split big <pre> into pieces before start to convert.
1353 newBlock = fromPres( removeBlock ? [ block.getHtml() ] : splitIntoPres( block ), newBlock );
1354 else
1355 block.moveChildren( newBlock );
1356
1357 newBlock.replace( block );
1358
1359 if ( newBlockIsPre ) {
1360 // Merge previous <pre> blocks.
1361 mergePre( newBlock );
1362 } else if ( removeBlock ) {
1363 removeNoAttribsElement( newBlock );
1364 }
1365 }
1366
1367 // Merge a <pre> block with a previous sibling if available.
1368 function mergePre( preBlock ) {
1369 var previousBlock;
1370 if ( !( ( previousBlock = preBlock.getPrevious( nonWhitespaces ) ) && previousBlock.type == CKEDITOR.NODE_ELEMENT && previousBlock.is( 'pre' ) ) )
1371 return;
1372
1373 // Merge the previous <pre> block contents into the current <pre>
1374 // block.
1375 //
1376 // Another thing to be careful here is that currentBlock might contain
1377 // a '\n' at the beginning, and previousBlock might contain a '\n'
1378 // towards the end. These new lines are not normally displayed but they
1379 // become visible after merging.
1380 var mergedHtml = replace( previousBlock.getHtml(), /\n$/, '' ) + '\n\n' +
1381 replace( preBlock.getHtml(), /^\n/, '' );
1382
1383 // Krugle: IE normalizes innerHTML from <pre>, breaking whitespaces.
1384 if ( CKEDITOR.env.ie )
1385 preBlock.$.outerHTML = '<pre>' + mergedHtml + '</pre>';
1386 else
1387 preBlock.setHtml( mergedHtml );
1388
1389 previousBlock.remove();
1390 }
1391
1392 // Split into multiple <pre> blocks separated by double line-break.
1393 function splitIntoPres( preBlock ) {
1394 // Exclude the ones at header OR at tail,
1395 // and ignore bookmark content between them.
1396 var duoBrRegex = /(\S\s*)\n(?:\s|(<span[^>]+data-cke-bookmark.*?\/span>))*\n(?!$)/gi,
1397 pres = [],
1398 splitedHtml = replace( preBlock.getOuterHtml(), duoBrRegex, function( match, charBefore, bookmark ) {
1399 return charBefore + '</pre>' + bookmark + '<pre>';
1400 } );
1401
1402 splitedHtml.replace( /<pre\b.*?>([\s\S]*?)<\/pre>/gi, function( match, preContent ) {
1403 pres.push( preContent );
1404 } );
1405 return pres;
1406 }
1407
1408 // Wrapper function of String::replace without considering of head/tail bookmarks nodes.
1409 function replace( str, regexp, replacement ) {
1410 var headBookmark = '',
1411 tailBookmark = '';
1412
1413 str = str.replace( /(^<span[^>]+data-cke-bookmark.*?\/span>)|(<span[^>]+data-cke-bookmark.*?\/span>$)/gi, function( str, m1, m2 ) {
1414 m1 && ( headBookmark = m1 );
1415 m2 && ( tailBookmark = m2 );
1416 return '';
1417 } );
1418 return headBookmark + str.replace( regexp, replacement ) + tailBookmark;
1419 }
1420
1421 // Converting a list of <pre> into blocks with format well preserved.
1422 function fromPres( preHtmls, newBlock ) {
1423 var docFrag;
1424 if ( preHtmls.length > 1 )
1425 docFrag = new CKEDITOR.dom.documentFragment( newBlock.getDocument() );
1426
1427 for ( var i = 0; i < preHtmls.length; i++ ) {
1428 var blockHtml = preHtmls[ i ];
1429
1430 // 1. Trim the first and last line-breaks immediately after and before <pre>,
1431 // they're not visible.
1432 blockHtml = blockHtml.replace( /(\r\n|\r)/g, '\n' );
1433 blockHtml = replace( blockHtml, /^[ \t]*\n/, '' );
1434 blockHtml = replace( blockHtml, /\n$/, '' );
1435 // 2. Convert spaces or tabs at the beginning or at the end to &nbsp;
1436 blockHtml = replace( blockHtml, /^[ \t]+|[ \t]+$/g, function( match, offset ) {
1437 if ( match.length == 1 ) // one space, preserve it
1438 return '&nbsp;';
1439 else if ( !offset ) // beginning of block
1440 return CKEDITOR.tools.repeat( '&nbsp;', match.length - 1 ) + ' ';
1441 else // end of block
1442 return ' ' + CKEDITOR.tools.repeat( '&nbsp;', match.length - 1 );
1443 } );
1444
1445 // 3. Convert \n to <BR>.
1446 // 4. Convert contiguous (i.e. non-singular) spaces or tabs to &nbsp;
1447 blockHtml = blockHtml.replace( /\n/g, '<br>' );
1448 blockHtml = blockHtml.replace( /[ \t]{2,}/g, function( match ) {
1449 return CKEDITOR.tools.repeat( '&nbsp;', match.length - 1 ) + ' ';
1450 } );
1451
1452 if ( docFrag ) {
1453 var newBlockClone = newBlock.clone();
1454 newBlockClone.setHtml( blockHtml );
1455 docFrag.append( newBlockClone );
1456 } else {
1457 newBlock.setHtml( blockHtml );
1458 }
1459 }
1460
1461 return docFrag || newBlock;
1462 }
1463
1464 // Converting from a non-PRE block to a PRE block in formatting operations.
1465 function toPre( block, newBlock ) {
1466 var bogus = block.getBogus();
1467 bogus && bogus.remove();
1468
1469 // First trim the block content.
1470 var preHtml = block.getHtml();
1471
1472 // 1. Trim head/tail spaces, they're not visible.
1473 preHtml = replace( preHtml, /(?:^[ \t\n\r]+)|(?:[ \t\n\r]+$)/g, '' );
1474 // 2. Delete ANSI whitespaces immediately before and after <BR> because
1475 // they are not visible.
1476 preHtml = preHtml.replace( /[ \t\r\n]*(<br[^>]*>)[ \t\r\n]*/gi, '$1' );
1477 // 3. Compress other ANSI whitespaces since they're only visible as one
1478 // single space previously.
1479 // 4. Convert &nbsp; to spaces since &nbsp; is no longer needed in <PRE>.
1480 preHtml = preHtml.replace( /([ \t\n\r]+|&nbsp;)/g, ' ' );
1481 // 5. Convert any <BR /> to \n. This must not be done earlier because
1482 // the \n would then get compressed.
1483 preHtml = preHtml.replace( /<br\b[^>]*>/gi, '\n' );
1484
1485 // Krugle: IE normalizes innerHTML to <pre>, breaking whitespaces.
1486 if ( CKEDITOR.env.ie ) {
1487 var temp = block.getDocument().createElement( 'div' );
1488 temp.append( newBlock );
1489 newBlock.$.outerHTML = '<pre>' + preHtml + '</pre>';
1490 newBlock.copyAttributes( temp.getFirst() );
1491 newBlock = temp.getFirst().remove();
1492 } else {
1493 newBlock.setHtml( preHtml );
1494 }
1495
1496 return newBlock;
1497 }
1498
1499 // Removes a style from an element itself, don't care about its subtree.
1500 function removeFromElement( element, keepDataAttrs ) {
1501 var def = this._.definition,
1502 attributes = def.attributes,
1503 styles = def.styles,
1504 overrides = getOverrides( this )[ element.getName() ],
1505 // If the style is only about the element itself, we have to remove the element.
1506 removeEmpty = CKEDITOR.tools.isEmpty( attributes ) && CKEDITOR.tools.isEmpty( styles );
1507
1508 // Remove definition attributes/style from the elemnt.
1509 for ( var attName in attributes ) {
1794320d 1510 // The 'class' element value must match (http://dev.ckeditor.com/ticket/1318).
c63493c8
IB
1511 if ( ( attName == 'class' || this._.definition.fullMatch ) && element.getAttribute( attName ) != normalizeProperty( attName, attributes[ attName ] ) )
1512 continue;
1513
1794320d 1514 // Do not touch data-* attributes (http://dev.ckeditor.com/ticket/11011) (http://dev.ckeditor.com/ticket/11258).
c63493c8
IB
1515 if ( keepDataAttrs && attName.slice( 0, 5 ) == 'data-' )
1516 continue;
1517
1518 removeEmpty = element.hasAttribute( attName );
1519 element.removeAttribute( attName );
1520 }
1521
1522 for ( var styleName in styles ) {
1794320d 1523 // Full match style insist on having fully equivalence. (http://dev.ckeditor.com/ticket/5018)
c63493c8
IB
1524 if ( this._.definition.fullMatch && element.getStyle( styleName ) != normalizeProperty( styleName, styles[ styleName ], true ) )
1525 continue;
1526
1527 removeEmpty = removeEmpty || !!element.getStyle( styleName );
1528 element.removeStyle( styleName );
1529 }
1530
1531 // Remove overrides, but don't remove the element if it's a block element
1532 removeOverrides( element, overrides, blockElements[ element.getName() ] );
1533
1534 if ( removeEmpty ) {
1535 if ( this._.definition.alwaysRemoveElement )
1536 removeNoAttribsElement( element, 1 );
1537 else {
1538 if ( !CKEDITOR.dtd.$block[ element.getName() ] || this._.enterMode == CKEDITOR.ENTER_BR && !element.hasAttributes() )
1539 removeNoAttribsElement( element );
1540 else
1541 element.renameNode( this._.enterMode == CKEDITOR.ENTER_P ? 'p' : 'div' );
1542 }
1543 }
1544 }
1545
1546 // Removes a style from inside an element. Called on applyStyle to make cleanup
1547 // before apply. During clean up this function keep data-* attribute in contrast
1548 // to removeFromElement.
1549 function removeFromInsideElement( element ) {
1550 var overrides = getOverrides( this ),
1551 innerElements = element.getElementsByTag( this.element ),
1552 innerElement;
1553
1554 for ( var i = innerElements.count(); --i >= 0; ) {
1555 innerElement = innerElements.getItem( i );
1556
1557 // Do not remove elements which are read only (e.g. duplicates inside widgets).
1558 if ( !innerElement.isReadOnly() )
1559 removeFromElement.call( this, innerElement, true );
1560 }
1561
1562 // Now remove any other element with different name that is
1563 // defined to be overriden.
1564 for ( var overrideElement in overrides ) {
1565 if ( overrideElement != this.element ) {
1566 innerElements = element.getElementsByTag( overrideElement );
1567
1568 for ( i = innerElements.count() - 1; i >= 0; i-- ) {
1569 innerElement = innerElements.getItem( i );
1570
1571 // Do not remove elements which are read only (e.g. duplicates inside widgets).
1572 if ( !innerElement.isReadOnly() )
1573 removeOverrides( innerElement, overrides[ overrideElement ] );
1574 }
1575 }
1576 }
1577 }
1578
1579 // Remove overriding styles/attributes from the specific element.
1580 // Note: Remove the element if no attributes remain.
1581 // @param {Object} element
1582 // @param {Object} overrides
1583 // @param {Boolean} Don't remove the element
1584 function removeOverrides( element, overrides, dontRemove ) {
1585 var attributes = overrides && overrides.attributes;
1586
1587 if ( attributes ) {
1588 for ( var i = 0; i < attributes.length; i++ ) {
1589 var attName = attributes[ i ][ 0 ],
1590 actualAttrValue;
1591
1592 if ( ( actualAttrValue = element.getAttribute( attName ) ) ) {
1593 var attValue = attributes[ i ][ 1 ];
1594
1595 // Remove the attribute if:
1596 // - The override definition value is null ;
1597 // - The override definition valie is a string that
1598 // matches the attribute value exactly.
1599 // - The override definition value is a regex that
1600 // has matches in the attribute value.
1601 if ( attValue === null || ( attValue.test && attValue.test( actualAttrValue ) ) || ( typeof attValue == 'string' && actualAttrValue == attValue ) )
1602 element.removeAttribute( attName );
1603 }
1604 }
1605 }
1606
1607 if ( !dontRemove )
1608 removeNoAttribsElement( element );
1609 }
1610
1611 // If the element has no more attributes, remove it.
1612 function removeNoAttribsElement( element, forceRemove ) {
1613 // If no more attributes remained in the element, remove it,
1614 // leaving its children.
1615 if ( !element.hasAttributes() || forceRemove ) {
1616 if ( CKEDITOR.dtd.$block[ element.getName() ] ) {
1617 var previous = element.getPrevious( nonWhitespaces ),
1618 next = element.getNext( nonWhitespaces );
1619
1620 if ( previous && ( previous.type == CKEDITOR.NODE_TEXT || !previous.isBlockBoundary( { br: 1 } ) ) )
1621 element.append( 'br', 1 );
1622 if ( next && ( next.type == CKEDITOR.NODE_TEXT || !next.isBlockBoundary( { br: 1 } ) ) )
1623 element.append( 'br' );
1624
1625 element.remove( true );
1626 } else {
1627 // Removing elements may open points where merging is possible,
1628 // so let's cache the first and last nodes for later checking.
1629 var firstChild = element.getFirst();
1630 var lastChild = element.getLast();
1631
1632 element.remove( true );
1633
1634 if ( firstChild ) {
1635 // Check the cached nodes for merging.
1636 firstChild.type == CKEDITOR.NODE_ELEMENT && firstChild.mergeSiblings();
1637
1638 if ( lastChild && !firstChild.equals( lastChild ) && lastChild.type == CKEDITOR.NODE_ELEMENT )
1639 lastChild.mergeSiblings();
1640 }
1641
1642 }
1643 }
1644 }
1645
1646 function getElement( style, targetDocument, element ) {
1647 var el,
1648 elementName = style.element;
1649
1650 // The "*" element name will always be a span for this function.
1651 if ( elementName == '*' )
1652 elementName = 'span';
1653
1654 // Create the element.
1655 el = new CKEDITOR.dom.element( elementName, targetDocument );
1656
1794320d 1657 // http://dev.ckeditor.com/ticket/6226: attributes should be copied before the new ones are applied
c63493c8
IB
1658 if ( element )
1659 element.copyAttributes( el );
1660
1661 el = setupElement( el, style );
1662
1663 // Avoid ID duplication.
1664 if ( targetDocument.getCustomData( 'doc_processing_style' ) && el.hasAttribute( 'id' ) )
1665 el.removeAttribute( 'id' );
1666 else
1667 targetDocument.setCustomData( 'doc_processing_style', 1 );
1668
1669 return el;
1670 }
1671
1672 function setupElement( el, style ) {
1673 var def = style._.definition,
1674 attributes = def.attributes,
1675 styles = CKEDITOR.style.getStyleText( def );
1676
1677 // Assign all defined attributes.
1678 if ( attributes ) {
1679 for ( var att in attributes )
1680 el.setAttribute( att, attributes[ att ] );
1681 }
1682
1683 // Assign all defined styles.
1684 if ( styles )
1685 el.setAttribute( 'style', styles );
1686
1687 return el;
1688 }
1689
1690 function replaceVariables( list, variablesValues ) {
1691 for ( var item in list ) {
1692 list[ item ] = list[ item ].replace( varRegex, function( match, varName ) {
1693 return variablesValues[ varName ];
1694 } );
1695 }
1696 }
1697
1698 // Returns an object that can be used for style matching comparison.
1699 // Attributes names and values are all lowercased, and the styles get
1700 // merged with the style attribute.
1701 function getAttributesForComparison( styleDefinition ) {
1702 // If we have already computed it, just return it.
1703 var attribs = styleDefinition._AC;
1704 if ( attribs )
1705 return attribs;
1706
1707 attribs = {};
1708
1709 var length = 0;
1710
1711 // Loop through all defined attributes.
1712 var styleAttribs = styleDefinition.attributes;
1713 if ( styleAttribs ) {
1714 for ( var styleAtt in styleAttribs ) {
1715 length++;
1716 attribs[ styleAtt ] = styleAttribs[ styleAtt ];
1717 }
1718 }
1719
1720 // Includes the style definitions.
1721 var styleText = CKEDITOR.style.getStyleText( styleDefinition );
1722 if ( styleText ) {
1723 if ( !attribs.style )
1724 length++;
1725 attribs.style = styleText;
1726 }
1727
1728 // Appends the "length" information to the object.
1729 attribs._length = length;
1730
1731 // Return it, saving it to the next request.
1732 return ( styleDefinition._AC = attribs );
1733 }
1734
1735 // Get the the collection used to compare the elements and attributes,
1736 // defined in this style overrides, with other element. All information in
1737 // it is lowercased.
1738 // @param {CKEDITOR.style} style
1739 function getOverrides( style ) {
1740 if ( style._.overrides )
1741 return style._.overrides;
1742
1743 var overrides = ( style._.overrides = {} ),
1744 definition = style._.definition.overrides;
1745
1746 if ( definition ) {
1747 // The override description can be a string, object or array.
1748 // Internally, well handle arrays only, so transform it if needed.
1749 if ( !CKEDITOR.tools.isArray( definition ) )
1750 definition = [ definition ];
1751
1752 // Loop through all override definitions.
1753 for ( var i = 0; i < definition.length; i++ ) {
1754 var override = definition[ i ],
1755 elementName,
1756 overrideEl,
1757 attrs;
1758
1759 // If can be a string with the element name.
1760 if ( typeof override == 'string' )
1761 elementName = override.toLowerCase();
1762 // Or an object.
1763 else {
1764 elementName = override.element ? override.element.toLowerCase() : style.element;
1765 attrs = override.attributes;
1766 }
1767
1768 // We can have more than one override definition for the same
1769 // element name, so we attempt to simply append information to
1770 // it if it already exists.
1771 overrideEl = overrides[ elementName ] || ( overrides[ elementName ] = {} );
1772
1773 if ( attrs ) {
1774 // The returning attributes list is an array, because we
1775 // could have different override definitions for the same
1776 // attribute name.
1777 var overrideAttrs = ( overrideEl.attributes = overrideEl.attributes || [] );
1778 for ( var attName in attrs ) {
1779 // Each item in the attributes array is also an array,
1780 // where [0] is the attribute name and [1] is the
1781 // override value.
1782 overrideAttrs.push( [ attName.toLowerCase(), attrs[ attName ] ] );
1783 }
1784 }
1785 }
1786 }
1787
1788 return overrides;
1789 }
1790
1791 // Make the comparison of attribute value easier by standardizing it.
1792 function normalizeProperty( name, value, isStyle ) {
1793 var temp = new CKEDITOR.dom.element( 'span' );
1794 temp[ isStyle ? 'setStyle' : 'setAttribute' ]( name, value );
1795 return temp[ isStyle ? 'getStyle' : 'getAttribute' ]( name );
1796 }
1797
1798 // Compare two bunch of styles, with the speciality that value 'inherit'
1799 // is treated as a wildcard which will match any value.
1800 // @param {Object/String} source
1801 // @param {Object/String} target
1802 // @returns {Boolean}
1803 function compareCssText( source, target ) {
1804 function filter( string, propertyName ) {
1794320d 1805 // In case of font-families we'll skip quotes. (http://dev.ckeditor.com/ticket/10750)
c63493c8
IB
1806 return propertyName.toLowerCase() == 'font-family' ? string.replace( /["']/g, '' ) : string;
1807 }
1808
1809 if ( typeof source == 'string' )
1810 source = CKEDITOR.tools.parseCssText( source );
1811 if ( typeof target == 'string' )
1812 target = CKEDITOR.tools.parseCssText( target, true );
1813
1814 for ( var name in source ) {
1815 if ( !( name in target ) ) {
1816 return false;
1817 }
1818
1819 if ( !( filter( target[ name ], name ) == filter( source[ name ], name ) ||
1820 source[ name ] == 'inherit' ||
1821 target[ name ] == 'inherit' ) ) {
1822 return false;
1823 }
1824 }
1825 return true;
1826 }
1827
1828 function applyStyleOnSelection( selection, remove, editor ) {
1829 var doc = selection.document,
1830 ranges = selection.getRanges(),
1831 func = remove ? this.removeFromRange : this.applyToRange,
1794320d
IB
1832 originalRanges,
1833 range,
1834 i;
1835
1836 // In case of fake table selection, we would like to apply all styles and then select
1837 // the original ranges. Otherwise browsers would complain about discontiguous selection.
1838 if ( selection.isFake && selection.isInTable() ) {
1839 originalRanges = [];
1840
1841 for ( i = 0; i < ranges.length; i++ ) {
1842 originalRanges.push( ranges[ i ].clone() );
1843 }
1844 }
c63493c8
IB
1845
1846 var iterator = ranges.createIterator();
1847 while ( ( range = iterator.getNextRange() ) )
1848 func.call( this, range, editor );
1849
1794320d 1850 selection.selectRanges( originalRanges || ranges );
c63493c8
IB
1851 doc.removeCustomData( 'doc_processing_style' );
1852 }
1853} )();
1854
1855/**
1856 * Generic style command. It applies a specific style when executed.
1857 *
1858 * var boldStyle = new CKEDITOR.style( { element: 'strong' } );
1859 * // Register the "bold" command, which applies the bold style.
1860 * editor.addCommand( 'bold', new CKEDITOR.styleCommand( boldStyle ) );
1861 *
1862 * @class
1863 * @constructor Creates a styleCommand class instance.
1864 * @extends CKEDITOR.commandDefinition
1865 * @param {CKEDITOR.style} style The style to be applied when command is executed.
1866 * @param {Object} [ext] Additional command definition's properties.
1867 */
1868CKEDITOR.styleCommand = function( style, ext ) {
1869 this.style = style;
1870 this.allowedContent = style;
1871 this.requiredContent = style;
1872
1873 CKEDITOR.tools.extend( this, ext, true );
1874};
1875
1876/**
1877 * @param {CKEDITOR.editor} editor
1878 * @todo
1879 */
1880CKEDITOR.styleCommand.prototype.exec = function( editor ) {
1881 editor.focus();
1882
1883 if ( this.state == CKEDITOR.TRISTATE_OFF )
1884 editor.applyStyle( this.style );
1885 else if ( this.state == CKEDITOR.TRISTATE_ON )
1886 editor.removeStyle( this.style );
1887};
1888
1889/**
1890 * Manages styles registration and loading. See also {@link CKEDITOR.config#stylesSet}.
1891 *
1892 * // The set of styles for the <b>Styles</b> drop-down list.
1893 * CKEDITOR.stylesSet.add( 'default', [
1894 * // Block Styles
1895 * { name: 'Blue Title', element: 'h3', styles: { 'color': 'Blue' } },
1896 * { name: 'Red Title', element: 'h3', styles: { 'color': 'Red' } },
1897 *
1898 * // Inline Styles
1899 * { name: 'Marker: Yellow', element: 'span', styles: { 'background-color': 'Yellow' } },
1900 * { name: 'Marker: Green', element: 'span', styles: { 'background-color': 'Lime' } },
1901 *
1902 * // Object Styles
1903 * {
1904 * name: 'Image on Left',
1905 * element: 'img',
1906 * attributes: {
1907 * style: 'padding: 5px; margin-right: 5px',
1908 * border: '2',
1909 * align: 'left'
1910 * }
1911 * }
1912 * ] );
1913 *
1914 * @since 3.2
1915 * @class
1916 * @singleton
1917 * @extends CKEDITOR.resourceManager
1918 */
1919CKEDITOR.stylesSet = new CKEDITOR.resourceManager( '', 'stylesSet' );
1920
1794320d 1921// Backward compatibility (http://dev.ckeditor.com/ticket/5025).
c63493c8
IB
1922CKEDITOR.addStylesSet = CKEDITOR.tools.bind( CKEDITOR.stylesSet.add, CKEDITOR.stylesSet );
1923CKEDITOR.loadStylesSet = function( name, url, callback ) {
1924 CKEDITOR.stylesSet.addExternal( name, url, '' );
1925 CKEDITOR.stylesSet.load( name, callback );
1926};
1927
1928CKEDITOR.tools.extend( CKEDITOR.editor.prototype, {
1929 /**
1930 * Registers a function to be called whenever the selection position changes in the
1931 * editing area. The current state is passed to the function. The possible
1932 * states are {@link CKEDITOR#TRISTATE_ON} and {@link CKEDITOR#TRISTATE_OFF}.
1933 *
1934 * // Create a style object for the <b> element.
1935 * var style = new CKEDITOR.style( { element: 'b' } );
1936 * var editor = CKEDITOR.instances.editor1;
1937 * editor.attachStyleStateChange( style, function( state ) {
1938 * if ( state == CKEDITOR.TRISTATE_ON )
1939 * alert( 'The current state for the B element is ON' );
1940 * else
1941 * alert( 'The current state for the B element is OFF' );
1942 * } );
1943 *
1944 * @member CKEDITOR.editor
1945 * @param {CKEDITOR.style} style The style to be watched.
1946 * @param {Function} callback The function to be called.
1947 */
1948 attachStyleStateChange: function( style, callback ) {
1949 // Try to get the list of attached callbacks.
1950 var styleStateChangeCallbacks = this._.styleStateChangeCallbacks;
1951
1952 // If it doesn't exist, it means this is the first call. So, let's create
1953 // all the structure to manage the style checks and the callback calls.
1954 if ( !styleStateChangeCallbacks ) {
1955 // Create the callbacks array.
1956 styleStateChangeCallbacks = this._.styleStateChangeCallbacks = [];
1957
1958 // Attach to the selectionChange event, so we can check the styles at
1959 // that point.
1960 this.on( 'selectionChange', function( ev ) {
1961 // Loop throw all registered callbacks.
1962 for ( var i = 0; i < styleStateChangeCallbacks.length; i++ ) {
1963 var callback = styleStateChangeCallbacks[ i ];
1964
1965 // Check the current state for the style defined for that callback.
1966 var currentState = callback.style.checkActive( ev.data.path, this ) ?
1967 CKEDITOR.TRISTATE_ON : CKEDITOR.TRISTATE_OFF;
1968
1969 // Call the callback function, passing the current state to it.
1970 callback.fn.call( this, currentState );
1971 }
1972 } );
1973 }
1974
1975 // Save the callback info, so it can be checked on the next occurrence of
1976 // selectionChange.
1977 styleStateChangeCallbacks.push( { style: style, fn: callback } );
1978 },
1979
1980 /**
1981 * Applies the style upon the editor's current selection. Shorthand for
1982 * {@link CKEDITOR.style#apply}.
1983 *
1984 * @member CKEDITOR.editor
1985 * @param {CKEDITOR.style} style
1986 */
1987 applyStyle: function( style ) {
1988 style.apply( this );
1989 },
1990
1991 /**
1992 * Removes the style from the editor's current selection. Shorthand for
1993 * {@link CKEDITOR.style#remove}.
1994 *
1995 * @member CKEDITOR.editor
1996 * @param {CKEDITOR.style} style
1997 */
1998 removeStyle: function( style ) {
1999 style.remove( this );
2000 },
2001
2002 /**
2003 * Gets the current `stylesSet` for this instance.
2004 *
2005 * editor.getStylesSet( function( stylesDefinitions ) {} );
2006 *
2007 * See also {@link CKEDITOR.editor#stylesSet} event.
2008 *
2009 * @member CKEDITOR.editor
2010 * @param {Function} callback The function to be called with the styles data.
2011 */
2012 getStylesSet: function( callback ) {
2013 if ( !this._.stylesDefinitions ) {
2014 var editor = this,
2015 // Respect the backwards compatible definition entry
2016 configStyleSet = editor.config.stylesCombo_stylesSet || editor.config.stylesSet;
2017
2018 // The false value means that none styles should be loaded.
2019 if ( configStyleSet === false ) {
2020 callback( null );
2021 return;
2022 }
2023
1794320d 2024 // http://dev.ckeditor.com/ticket/5352 Allow to define the styles directly in the config object
c63493c8
IB
2025 if ( configStyleSet instanceof Array ) {
2026 editor._.stylesDefinitions = configStyleSet;
2027 callback( configStyleSet );
2028 return;
2029 }
2030
2031 // Default value is 'default'.
2032 if ( !configStyleSet )
2033 configStyleSet = 'default';
2034
2035 var partsStylesSet = configStyleSet.split( ':' ),
2036 styleSetName = partsStylesSet[ 0 ],
2037 externalPath = partsStylesSet[ 1 ];
2038
2039 CKEDITOR.stylesSet.addExternal( styleSetName, externalPath ? partsStylesSet.slice( 1 ).join( ':' ) : CKEDITOR.getUrl( 'styles.js' ), '' );
2040
2041 CKEDITOR.stylesSet.load( styleSetName, function( stylesSet ) {
2042 editor._.stylesDefinitions = stylesSet[ styleSetName ];
2043 callback( editor._.stylesDefinitions );
2044 } );
2045 } else {
2046 callback( this._.stylesDefinitions );
2047 }
2048 }
2049} );
2050
2051/**
2052 * Indicates that fully selected read-only elements will be included when
2053 * applying the style (for inline styles only).
2054 *
2055 * @since 3.5
2056 * @property {Boolean} [includeReadonly=false]
2057 * @member CKEDITOR.style
2058 */
2059
2060/**
2061 * Indicates that any matches element of this style will be eventually removed
2062 * when calling {@link CKEDITOR.editor#removeStyle}.
2063 *
2064 * @since 4.0
2065 * @property {Boolean} [alwaysRemoveElement=false]
2066 * @member CKEDITOR.style
2067 */
2068
2069/**
2070 * Disables inline styling on read-only elements.
2071 *
2072 * @since 3.5
2073 * @cfg {Boolean} [disableReadonlyStyling=false]
2074 * @member CKEDITOR.config
2075 */
2076
2077/**
2078 * The "styles definition set" to use in the editor. They will be used in the
2079 * styles combo and the style selector of the div container.
2080 *
2081 * The styles may be defined in the page containing the editor, or can be
2082 * loaded on demand from an external file. In the second case, if this setting
2083 * contains only a name, the `styles.js` file will be loaded from the
2084 * CKEditor root folder (what ensures backward compatibility with CKEditor 4.0).
2085 *
2086 * Otherwise, this setting has the `name:url` syntax, making it
2087 * possible to set the URL from which the styles file will be loaded.
2088 * Note that the `name` has to be equal to the name used in
2089 * {@link CKEDITOR.stylesSet#add} while registering the styles set.
2090 *
2091 * **Note**: Since 4.1 it is possible to set `stylesSet` to `false`
2092 * to prevent loading any styles set.
2093 *
2094 * Read more in the [documentation](#!/guide/dev_styles)
2095 * and see the [SDK sample](http://sdk.ckeditor.com/samples/styles.html).
2096 *
2097 * // Do not load any file. The styles set is empty.
2098 * config.stylesSet = false;
2099 *
2100 * // Load the 'mystyles' styles set from the styles.js file.
2101 * config.stylesSet = 'mystyles';
2102 *
2103 * // Load the 'mystyles' styles set from a relative URL.
2104 * config.stylesSet = 'mystyles:/editorstyles/styles.js';
2105 *
2106 * // Load the 'mystyles' styles set from a full URL.
2107 * config.stylesSet = 'mystyles:http://www.example.com/editorstyles/styles.js';
2108 *
2109 * // Load from a list of definitions.
2110 * config.stylesSet = [
2111 * { name: 'Strong Emphasis', element: 'strong' },
2112 * { name: 'Emphasis', element: 'em' },
2113 * ...
2114 * ];
2115 *
2116 * @since 3.3
2117 * @cfg {String/Array/Boolean} [stylesSet='default']
2118 * @member CKEDITOR.config
2119 */