]> git.immae.eu Git - perso/Immae/Projets/packagist/connexionswing-ckeditor-component.git/blob - sources/core/style.js
Upgrade to 4.5.7 and add some plugin
[perso/Immae/Projets/packagist/connexionswing-ckeditor-component.git] / sources / core / style.js
1 /**
2 * @license Copyright (c) 2003-2016, 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 */
17 CKEDITOR.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 */
28 CKEDITOR.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 */
39 CKEDITOR.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
238 // which should be used developers were forced to hack the style object (see #10190).
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
572 // Some browsers don't support 'inherit' property value, leave them intact. (#5242)
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 }
1027 // Style already inherit from parents, left just to clear up any internal overrides. (#5931)
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
1045 // Minimize the result range to exclude empty text nodes. (#5374)
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(),
1061 startNode = bookmark.startNode;
1062
1063 if ( range.collapsed ) {
1064 var startPath = new CKEDITOR.dom.elementPath( startNode.getParent(), range.root ),
1065 // The topmost element in elementspatch which we should jump out of.
1066 boundaryElement;
1067
1068
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,
1074 // also make sure other inner styles were well preserverd.(#3309)
1075 if ( element == startPath.block || element == startPath.blockLimit )
1076 break;
1077
1078 if ( this.checkElementRemovable( element ) ) {
1079 var isStart;
1080
1081 if ( range.collapsed && ( range.checkBoundaryOfElement( element, CKEDITOR.END ) || ( isStart = range.checkBoundaryOfElement( element, CKEDITOR.START ) ) ) ) {
1082 boundaryElement = element;
1083 boundaryElement.match = isStart ? 'start' : 'end';
1084 } else {
1085 // Before removing the style node, there may be a sibling to the style node
1086 // that's exactly the same to the one to be removed. To the user, it makes
1087 // no difference that they're separate entities in the DOM tree. So, merge
1088 // them before removal.
1089 element.mergeSiblings();
1090 if ( element.is( this.element ) )
1091 removeFromElement.call( this, element );
1092 else
1093 removeOverrides( element, getOverrides( this )[ element.getName() ] );
1094 }
1095 }
1096 }
1097
1098 // Re-create the style tree after/before the boundary element,
1099 // the replication start from bookmark start node to define the
1100 // new range.
1101 if ( boundaryElement ) {
1102 var clonedElement = startNode;
1103 for ( i = 0; ; i++ ) {
1104 var newElement = startPath.elements[ i ];
1105 if ( newElement.equals( boundaryElement ) )
1106 break;
1107 // Avoid copying any matched element.
1108 else if ( newElement.match )
1109 continue;
1110 else
1111 newElement = newElement.clone();
1112 newElement.append( clonedElement );
1113 clonedElement = newElement;
1114 }
1115 clonedElement[ boundaryElement.match == 'start' ? 'insertBefore' : 'insertAfter' ]( boundaryElement );
1116 }
1117 } else {
1118 // Now our range isn't collapsed. Lets walk from the start node to the end
1119 // node via DFS and remove the styles one-by-one.
1120 var endNode = bookmark.endNode,
1121 me = this;
1122
1123 breakNodes();
1124
1125 // Now, do the DFS walk.
1126 var currentNode = startNode;
1127 while ( !currentNode.equals( endNode ) ) {
1128 // Need to get the next node first because removeFromElement() can remove
1129 // the current node from DOM tree.
1130 var nextNode = currentNode.getNextSourceNode();
1131 if ( currentNode.type == CKEDITOR.NODE_ELEMENT && this.checkElementRemovable( currentNode ) ) {
1132 // Remove style from element or overriding element.
1133 if ( currentNode.getName() == this.element )
1134 removeFromElement.call( this, currentNode );
1135 else
1136 removeOverrides( currentNode, getOverrides( this )[ currentNode.getName() ] );
1137
1138 // removeFromElement() may have merged the next node with something before
1139 // the startNode via mergeSiblings(). In that case, the nextNode would
1140 // contain startNode and we'll have to call breakNodes() again and also
1141 // reassign the nextNode to something after startNode.
1142 if ( nextNode.type == CKEDITOR.NODE_ELEMENT && nextNode.contains( startNode ) ) {
1143 breakNodes();
1144 nextNode = startNode.getNext();
1145 }
1146 }
1147 currentNode = nextNode;
1148 }
1149 }
1150
1151 range.moveToBookmark( bookmark );
1152 // See the comment for range.shrink in applyInlineStyle.
1153 range.shrink( CKEDITOR.NODE_ELEMENT, true );
1154
1155 // Find out the style ancestor that needs to be broken down at startNode
1156 // and endNode.
1157 function breakNodes() {
1158 var startPath = new CKEDITOR.dom.elementPath( startNode.getParent() ),
1159 endPath = new CKEDITOR.dom.elementPath( endNode.getParent() ),
1160 breakStart = null,
1161 breakEnd = null;
1162
1163 for ( var i = 0; i < startPath.elements.length; i++ ) {
1164 var element = startPath.elements[ i ];
1165
1166 if ( element == startPath.block || element == startPath.blockLimit )
1167 break;
1168
1169 if ( me.checkElementRemovable( element, true ) )
1170 breakStart = element;
1171 }
1172
1173 for ( i = 0; i < endPath.elements.length; i++ ) {
1174 element = endPath.elements[ i ];
1175
1176 if ( element == endPath.block || element == endPath.blockLimit )
1177 break;
1178
1179 if ( me.checkElementRemovable( element, true ) )
1180 breakEnd = element;
1181 }
1182
1183 if ( breakEnd )
1184 endNode.breakParent( breakEnd );
1185 if ( breakStart )
1186 startNode.breakParent( breakStart );
1187 }
1188 }
1189
1190 // Apply style to nested editables inside editablesContainer.
1191 // @param {CKEDITOR.dom.element} editablesContainer
1192 // @context CKEDITOR.style
1193 function applyStyleOnNestedEditables( editablesContainer ) {
1194 var editables = findNestedEditables( editablesContainer ),
1195 editable,
1196 l = editables.length,
1197 i = 0,
1198 range = l && new CKEDITOR.dom.range( editablesContainer.getDocument() );
1199
1200 for ( ; i < l; ++i ) {
1201 editable = editables[ i ];
1202 // Check if style is allowed by this editable's ACF.
1203 if ( checkIfAllowedInEditable( editable, this ) ) {
1204 range.selectNodeContents( editable );
1205 applyInlineStyle.call( this, range );
1206 }
1207 }
1208 }
1209
1210 // Finds nested editables within container. Does not return
1211 // editables nested in another editable (twice).
1212 function findNestedEditables( container ) {
1213 var editables = [];
1214
1215 container.forEach( function( element ) {
1216 if ( element.getAttribute( 'contenteditable' ) == 'true' ) {
1217 editables.push( element );
1218 return false; // Skip children.
1219 }
1220 }, CKEDITOR.NODE_ELEMENT, true );
1221
1222 return editables;
1223 }
1224
1225 // Checks if style is allowed in this editable.
1226 function checkIfAllowedInEditable( editable, style ) {
1227 var filter = CKEDITOR.filter.instances[ editable.data( 'cke-filter' ) ];
1228
1229 return filter ? filter.check( style ) : 1;
1230 }
1231
1232 // Checks if style is allowed by iterator's active filter.
1233 function checkIfAllowedByIterator( iterator, style ) {
1234 return iterator.activeFilter ? iterator.activeFilter.check( style ) : 1;
1235 }
1236
1237 function applyObjectStyle( range ) {
1238 // Selected or parent element. (#9651)
1239 var start = range.getEnclosedNode() || range.getCommonAncestor( false, true ),
1240 element = new CKEDITOR.dom.elementPath( start, range.root ).contains( this.element, 1 );
1241
1242 element && !element.isReadOnly() && setupElement( element, this );
1243 }
1244
1245 function removeObjectStyle( range ) {
1246 var parent = range.getCommonAncestor( true, true ),
1247 element = new CKEDITOR.dom.elementPath( parent, range.root ).contains( this.element, 1 );
1248
1249 if ( !element )
1250 return;
1251
1252 var style = this,
1253 def = style._.definition,
1254 attributes = def.attributes;
1255
1256 // Remove all defined attributes.
1257 if ( attributes ) {
1258 for ( var att in attributes )
1259 element.removeAttribute( att, attributes[ att ] );
1260 }
1261
1262 // Assign all defined styles.
1263 if ( def.styles ) {
1264 for ( var i in def.styles ) {
1265 if ( def.styles.hasOwnProperty( i ) )
1266 element.removeStyle( i );
1267 }
1268 }
1269 }
1270
1271 function applyBlockStyle( range ) {
1272 // Serializible bookmarks is needed here since
1273 // elements may be merged.
1274 var bookmark = range.createBookmark( true );
1275
1276 var iterator = range.createIterator();
1277 iterator.enforceRealBlocks = true;
1278
1279 // make recognize <br /> tag as a separator in ENTER_BR mode (#5121)
1280 if ( this._.enterMode )
1281 iterator.enlargeBr = ( this._.enterMode != CKEDITOR.ENTER_BR );
1282
1283 var block,
1284 doc = range.document,
1285 newBlock;
1286
1287 while ( ( block = iterator.getNextParagraph() ) ) {
1288 if ( !block.isReadOnly() && checkIfAllowedByIterator( iterator, this ) ) {
1289 newBlock = getElement( this, doc, block );
1290 replaceBlock( block, newBlock );
1291 }
1292 }
1293
1294 range.moveToBookmark( bookmark );
1295 }
1296
1297 function removeBlockStyle( range ) {
1298 // Serializible bookmarks is needed here since
1299 // elements may be merged.
1300 var bookmark = range.createBookmark( 1 );
1301
1302 var iterator = range.createIterator();
1303 iterator.enforceRealBlocks = true;
1304 iterator.enlargeBr = this._.enterMode != CKEDITOR.ENTER_BR;
1305
1306 var block,
1307 newBlock;
1308
1309 while ( ( block = iterator.getNextParagraph() ) ) {
1310 if ( this.checkElementRemovable( block ) ) {
1311 // <pre> get special treatment.
1312 if ( block.is( 'pre' ) ) {
1313 newBlock = this._.enterMode == CKEDITOR.ENTER_BR ? null :
1314 range.document.createElement( this._.enterMode == CKEDITOR.ENTER_P ? 'p' : 'div' );
1315
1316 newBlock && block.copyAttributes( newBlock );
1317 replaceBlock( block, newBlock );
1318 } else {
1319 removeFromElement.call( this, block );
1320 }
1321 }
1322 }
1323
1324 range.moveToBookmark( bookmark );
1325 }
1326
1327 // Replace the original block with new one, with special treatment
1328 // for <pre> blocks to make sure content format is well preserved, and merging/splitting adjacent
1329 // when necessary. (#3188)
1330 function replaceBlock( block, newBlock ) {
1331 // Block is to be removed, create a temp element to
1332 // save contents.
1333 var removeBlock = !newBlock;
1334 if ( removeBlock ) {
1335 newBlock = block.getDocument().createElement( 'div' );
1336 block.copyAttributes( newBlock );
1337 }
1338
1339 var newBlockIsPre = newBlock && newBlock.is( 'pre' ),
1340 blockIsPre = block.is( 'pre' ),
1341 isToPre = newBlockIsPre && !blockIsPre,
1342 isFromPre = !newBlockIsPre && blockIsPre;
1343
1344 if ( isToPre )
1345 newBlock = toPre( block, newBlock );
1346 else if ( isFromPre )
1347 // Split big <pre> into pieces before start to convert.
1348 newBlock = fromPres( removeBlock ? [ block.getHtml() ] : splitIntoPres( block ), newBlock );
1349 else
1350 block.moveChildren( newBlock );
1351
1352 newBlock.replace( block );
1353
1354 if ( newBlockIsPre ) {
1355 // Merge previous <pre> blocks.
1356 mergePre( newBlock );
1357 } else if ( removeBlock ) {
1358 removeNoAttribsElement( newBlock );
1359 }
1360 }
1361
1362 // Merge a <pre> block with a previous sibling if available.
1363 function mergePre( preBlock ) {
1364 var previousBlock;
1365 if ( !( ( previousBlock = preBlock.getPrevious( nonWhitespaces ) ) && previousBlock.type == CKEDITOR.NODE_ELEMENT && previousBlock.is( 'pre' ) ) )
1366 return;
1367
1368 // Merge the previous <pre> block contents into the current <pre>
1369 // block.
1370 //
1371 // Another thing to be careful here is that currentBlock might contain
1372 // a '\n' at the beginning, and previousBlock might contain a '\n'
1373 // towards the end. These new lines are not normally displayed but they
1374 // become visible after merging.
1375 var mergedHtml = replace( previousBlock.getHtml(), /\n$/, '' ) + '\n\n' +
1376 replace( preBlock.getHtml(), /^\n/, '' );
1377
1378 // Krugle: IE normalizes innerHTML from <pre>, breaking whitespaces.
1379 if ( CKEDITOR.env.ie )
1380 preBlock.$.outerHTML = '<pre>' + mergedHtml + '</pre>';
1381 else
1382 preBlock.setHtml( mergedHtml );
1383
1384 previousBlock.remove();
1385 }
1386
1387 // Split into multiple <pre> blocks separated by double line-break.
1388 function splitIntoPres( preBlock ) {
1389 // Exclude the ones at header OR at tail,
1390 // and ignore bookmark content between them.
1391 var duoBrRegex = /(\S\s*)\n(?:\s|(<span[^>]+data-cke-bookmark.*?\/span>))*\n(?!$)/gi,
1392 pres = [],
1393 splitedHtml = replace( preBlock.getOuterHtml(), duoBrRegex, function( match, charBefore, bookmark ) {
1394 return charBefore + '</pre>' + bookmark + '<pre>';
1395 } );
1396
1397 splitedHtml.replace( /<pre\b.*?>([\s\S]*?)<\/pre>/gi, function( match, preContent ) {
1398 pres.push( preContent );
1399 } );
1400 return pres;
1401 }
1402
1403 // Wrapper function of String::replace without considering of head/tail bookmarks nodes.
1404 function replace( str, regexp, replacement ) {
1405 var headBookmark = '',
1406 tailBookmark = '';
1407
1408 str = str.replace( /(^<span[^>]+data-cke-bookmark.*?\/span>)|(<span[^>]+data-cke-bookmark.*?\/span>$)/gi, function( str, m1, m2 ) {
1409 m1 && ( headBookmark = m1 );
1410 m2 && ( tailBookmark = m2 );
1411 return '';
1412 } );
1413 return headBookmark + str.replace( regexp, replacement ) + tailBookmark;
1414 }
1415
1416 // Converting a list of <pre> into blocks with format well preserved.
1417 function fromPres( preHtmls, newBlock ) {
1418 var docFrag;
1419 if ( preHtmls.length > 1 )
1420 docFrag = new CKEDITOR.dom.documentFragment( newBlock.getDocument() );
1421
1422 for ( var i = 0; i < preHtmls.length; i++ ) {
1423 var blockHtml = preHtmls[ i ];
1424
1425 // 1. Trim the first and last line-breaks immediately after and before <pre>,
1426 // they're not visible.
1427 blockHtml = blockHtml.replace( /(\r\n|\r)/g, '\n' );
1428 blockHtml = replace( blockHtml, /^[ \t]*\n/, '' );
1429 blockHtml = replace( blockHtml, /\n$/, '' );
1430 // 2. Convert spaces or tabs at the beginning or at the end to &nbsp;
1431 blockHtml = replace( blockHtml, /^[ \t]+|[ \t]+$/g, function( match, offset ) {
1432 if ( match.length == 1 ) // one space, preserve it
1433 return '&nbsp;';
1434 else if ( !offset ) // beginning of block
1435 return CKEDITOR.tools.repeat( '&nbsp;', match.length - 1 ) + ' ';
1436 else // end of block
1437 return ' ' + CKEDITOR.tools.repeat( '&nbsp;', match.length - 1 );
1438 } );
1439
1440 // 3. Convert \n to <BR>.
1441 // 4. Convert contiguous (i.e. non-singular) spaces or tabs to &nbsp;
1442 blockHtml = blockHtml.replace( /\n/g, '<br>' );
1443 blockHtml = blockHtml.replace( /[ \t]{2,}/g, function( match ) {
1444 return CKEDITOR.tools.repeat( '&nbsp;', match.length - 1 ) + ' ';
1445 } );
1446
1447 if ( docFrag ) {
1448 var newBlockClone = newBlock.clone();
1449 newBlockClone.setHtml( blockHtml );
1450 docFrag.append( newBlockClone );
1451 } else {
1452 newBlock.setHtml( blockHtml );
1453 }
1454 }
1455
1456 return docFrag || newBlock;
1457 }
1458
1459 // Converting from a non-PRE block to a PRE block in formatting operations.
1460 function toPre( block, newBlock ) {
1461 var bogus = block.getBogus();
1462 bogus && bogus.remove();
1463
1464 // First trim the block content.
1465 var preHtml = block.getHtml();
1466
1467 // 1. Trim head/tail spaces, they're not visible.
1468 preHtml = replace( preHtml, /(?:^[ \t\n\r]+)|(?:[ \t\n\r]+$)/g, '' );
1469 // 2. Delete ANSI whitespaces immediately before and after <BR> because
1470 // they are not visible.
1471 preHtml = preHtml.replace( /[ \t\r\n]*(<br[^>]*>)[ \t\r\n]*/gi, '$1' );
1472 // 3. Compress other ANSI whitespaces since they're only visible as one
1473 // single space previously.
1474 // 4. Convert &nbsp; to spaces since &nbsp; is no longer needed in <PRE>.
1475 preHtml = preHtml.replace( /([ \t\n\r]+|&nbsp;)/g, ' ' );
1476 // 5. Convert any <BR /> to \n. This must not be done earlier because
1477 // the \n would then get compressed.
1478 preHtml = preHtml.replace( /<br\b[^>]*>/gi, '\n' );
1479
1480 // Krugle: IE normalizes innerHTML to <pre>, breaking whitespaces.
1481 if ( CKEDITOR.env.ie ) {
1482 var temp = block.getDocument().createElement( 'div' );
1483 temp.append( newBlock );
1484 newBlock.$.outerHTML = '<pre>' + preHtml + '</pre>';
1485 newBlock.copyAttributes( temp.getFirst() );
1486 newBlock = temp.getFirst().remove();
1487 } else {
1488 newBlock.setHtml( preHtml );
1489 }
1490
1491 return newBlock;
1492 }
1493
1494 // Removes a style from an element itself, don't care about its subtree.
1495 function removeFromElement( element, keepDataAttrs ) {
1496 var def = this._.definition,
1497 attributes = def.attributes,
1498 styles = def.styles,
1499 overrides = getOverrides( this )[ element.getName() ],
1500 // If the style is only about the element itself, we have to remove the element.
1501 removeEmpty = CKEDITOR.tools.isEmpty( attributes ) && CKEDITOR.tools.isEmpty( styles );
1502
1503 // Remove definition attributes/style from the elemnt.
1504 for ( var attName in attributes ) {
1505 // The 'class' element value must match (#1318).
1506 if ( ( attName == 'class' || this._.definition.fullMatch ) && element.getAttribute( attName ) != normalizeProperty( attName, attributes[ attName ] ) )
1507 continue;
1508
1509 // Do not touch data-* attributes (#11011) (#11258).
1510 if ( keepDataAttrs && attName.slice( 0, 5 ) == 'data-' )
1511 continue;
1512
1513 removeEmpty = element.hasAttribute( attName );
1514 element.removeAttribute( attName );
1515 }
1516
1517 for ( var styleName in styles ) {
1518 // Full match style insist on having fully equivalence. (#5018)
1519 if ( this._.definition.fullMatch && element.getStyle( styleName ) != normalizeProperty( styleName, styles[ styleName ], true ) )
1520 continue;
1521
1522 removeEmpty = removeEmpty || !!element.getStyle( styleName );
1523 element.removeStyle( styleName );
1524 }
1525
1526 // Remove overrides, but don't remove the element if it's a block element
1527 removeOverrides( element, overrides, blockElements[ element.getName() ] );
1528
1529 if ( removeEmpty ) {
1530 if ( this._.definition.alwaysRemoveElement )
1531 removeNoAttribsElement( element, 1 );
1532 else {
1533 if ( !CKEDITOR.dtd.$block[ element.getName() ] || this._.enterMode == CKEDITOR.ENTER_BR && !element.hasAttributes() )
1534 removeNoAttribsElement( element );
1535 else
1536 element.renameNode( this._.enterMode == CKEDITOR.ENTER_P ? 'p' : 'div' );
1537 }
1538 }
1539 }
1540
1541 // Removes a style from inside an element. Called on applyStyle to make cleanup
1542 // before apply. During clean up this function keep data-* attribute in contrast
1543 // to removeFromElement.
1544 function removeFromInsideElement( element ) {
1545 var overrides = getOverrides( this ),
1546 innerElements = element.getElementsByTag( this.element ),
1547 innerElement;
1548
1549 for ( var i = innerElements.count(); --i >= 0; ) {
1550 innerElement = innerElements.getItem( i );
1551
1552 // Do not remove elements which are read only (e.g. duplicates inside widgets).
1553 if ( !innerElement.isReadOnly() )
1554 removeFromElement.call( this, innerElement, true );
1555 }
1556
1557 // Now remove any other element with different name that is
1558 // defined to be overriden.
1559 for ( var overrideElement in overrides ) {
1560 if ( overrideElement != this.element ) {
1561 innerElements = element.getElementsByTag( overrideElement );
1562
1563 for ( i = innerElements.count() - 1; i >= 0; i-- ) {
1564 innerElement = innerElements.getItem( i );
1565
1566 // Do not remove elements which are read only (e.g. duplicates inside widgets).
1567 if ( !innerElement.isReadOnly() )
1568 removeOverrides( innerElement, overrides[ overrideElement ] );
1569 }
1570 }
1571 }
1572 }
1573
1574 // Remove overriding styles/attributes from the specific element.
1575 // Note: Remove the element if no attributes remain.
1576 // @param {Object} element
1577 // @param {Object} overrides
1578 // @param {Boolean} Don't remove the element
1579 function removeOverrides( element, overrides, dontRemove ) {
1580 var attributes = overrides && overrides.attributes;
1581
1582 if ( attributes ) {
1583 for ( var i = 0; i < attributes.length; i++ ) {
1584 var attName = attributes[ i ][ 0 ],
1585 actualAttrValue;
1586
1587 if ( ( actualAttrValue = element.getAttribute( attName ) ) ) {
1588 var attValue = attributes[ i ][ 1 ];
1589
1590 // Remove the attribute if:
1591 // - The override definition value is null ;
1592 // - The override definition valie is a string that
1593 // matches the attribute value exactly.
1594 // - The override definition value is a regex that
1595 // has matches in the attribute value.
1596 if ( attValue === null || ( attValue.test && attValue.test( actualAttrValue ) ) || ( typeof attValue == 'string' && actualAttrValue == attValue ) )
1597 element.removeAttribute( attName );
1598 }
1599 }
1600 }
1601
1602 if ( !dontRemove )
1603 removeNoAttribsElement( element );
1604 }
1605
1606 // If the element has no more attributes, remove it.
1607 function removeNoAttribsElement( element, forceRemove ) {
1608 // If no more attributes remained in the element, remove it,
1609 // leaving its children.
1610 if ( !element.hasAttributes() || forceRemove ) {
1611 if ( CKEDITOR.dtd.$block[ element.getName() ] ) {
1612 var previous = element.getPrevious( nonWhitespaces ),
1613 next = element.getNext( nonWhitespaces );
1614
1615 if ( previous && ( previous.type == CKEDITOR.NODE_TEXT || !previous.isBlockBoundary( { br: 1 } ) ) )
1616 element.append( 'br', 1 );
1617 if ( next && ( next.type == CKEDITOR.NODE_TEXT || !next.isBlockBoundary( { br: 1 } ) ) )
1618 element.append( 'br' );
1619
1620 element.remove( true );
1621 } else {
1622 // Removing elements may open points where merging is possible,
1623 // so let's cache the first and last nodes for later checking.
1624 var firstChild = element.getFirst();
1625 var lastChild = element.getLast();
1626
1627 element.remove( true );
1628
1629 if ( firstChild ) {
1630 // Check the cached nodes for merging.
1631 firstChild.type == CKEDITOR.NODE_ELEMENT && firstChild.mergeSiblings();
1632
1633 if ( lastChild && !firstChild.equals( lastChild ) && lastChild.type == CKEDITOR.NODE_ELEMENT )
1634 lastChild.mergeSiblings();
1635 }
1636
1637 }
1638 }
1639 }
1640
1641 function getElement( style, targetDocument, element ) {
1642 var el,
1643 elementName = style.element;
1644
1645 // The "*" element name will always be a span for this function.
1646 if ( elementName == '*' )
1647 elementName = 'span';
1648
1649 // Create the element.
1650 el = new CKEDITOR.dom.element( elementName, targetDocument );
1651
1652 // #6226: attributes should be copied before the new ones are applied
1653 if ( element )
1654 element.copyAttributes( el );
1655
1656 el = setupElement( el, style );
1657
1658 // Avoid ID duplication.
1659 if ( targetDocument.getCustomData( 'doc_processing_style' ) && el.hasAttribute( 'id' ) )
1660 el.removeAttribute( 'id' );
1661 else
1662 targetDocument.setCustomData( 'doc_processing_style', 1 );
1663
1664 return el;
1665 }
1666
1667 function setupElement( el, style ) {
1668 var def = style._.definition,
1669 attributes = def.attributes,
1670 styles = CKEDITOR.style.getStyleText( def );
1671
1672 // Assign all defined attributes.
1673 if ( attributes ) {
1674 for ( var att in attributes )
1675 el.setAttribute( att, attributes[ att ] );
1676 }
1677
1678 // Assign all defined styles.
1679 if ( styles )
1680 el.setAttribute( 'style', styles );
1681
1682 return el;
1683 }
1684
1685 function replaceVariables( list, variablesValues ) {
1686 for ( var item in list ) {
1687 list[ item ] = list[ item ].replace( varRegex, function( match, varName ) {
1688 return variablesValues[ varName ];
1689 } );
1690 }
1691 }
1692
1693 // Returns an object that can be used for style matching comparison.
1694 // Attributes names and values are all lowercased, and the styles get
1695 // merged with the style attribute.
1696 function getAttributesForComparison( styleDefinition ) {
1697 // If we have already computed it, just return it.
1698 var attribs = styleDefinition._AC;
1699 if ( attribs )
1700 return attribs;
1701
1702 attribs = {};
1703
1704 var length = 0;
1705
1706 // Loop through all defined attributes.
1707 var styleAttribs = styleDefinition.attributes;
1708 if ( styleAttribs ) {
1709 for ( var styleAtt in styleAttribs ) {
1710 length++;
1711 attribs[ styleAtt ] = styleAttribs[ styleAtt ];
1712 }
1713 }
1714
1715 // Includes the style definitions.
1716 var styleText = CKEDITOR.style.getStyleText( styleDefinition );
1717 if ( styleText ) {
1718 if ( !attribs.style )
1719 length++;
1720 attribs.style = styleText;
1721 }
1722
1723 // Appends the "length" information to the object.
1724 attribs._length = length;
1725
1726 // Return it, saving it to the next request.
1727 return ( styleDefinition._AC = attribs );
1728 }
1729
1730 // Get the the collection used to compare the elements and attributes,
1731 // defined in this style overrides, with other element. All information in
1732 // it is lowercased.
1733 // @param {CKEDITOR.style} style
1734 function getOverrides( style ) {
1735 if ( style._.overrides )
1736 return style._.overrides;
1737
1738 var overrides = ( style._.overrides = {} ),
1739 definition = style._.definition.overrides;
1740
1741 if ( definition ) {
1742 // The override description can be a string, object or array.
1743 // Internally, well handle arrays only, so transform it if needed.
1744 if ( !CKEDITOR.tools.isArray( definition ) )
1745 definition = [ definition ];
1746
1747 // Loop through all override definitions.
1748 for ( var i = 0; i < definition.length; i++ ) {
1749 var override = definition[ i ],
1750 elementName,
1751 overrideEl,
1752 attrs;
1753
1754 // If can be a string with the element name.
1755 if ( typeof override == 'string' )
1756 elementName = override.toLowerCase();
1757 // Or an object.
1758 else {
1759 elementName = override.element ? override.element.toLowerCase() : style.element;
1760 attrs = override.attributes;
1761 }
1762
1763 // We can have more than one override definition for the same
1764 // element name, so we attempt to simply append information to
1765 // it if it already exists.
1766 overrideEl = overrides[ elementName ] || ( overrides[ elementName ] = {} );
1767
1768 if ( attrs ) {
1769 // The returning attributes list is an array, because we
1770 // could have different override definitions for the same
1771 // attribute name.
1772 var overrideAttrs = ( overrideEl.attributes = overrideEl.attributes || [] );
1773 for ( var attName in attrs ) {
1774 // Each item in the attributes array is also an array,
1775 // where [0] is the attribute name and [1] is the
1776 // override value.
1777 overrideAttrs.push( [ attName.toLowerCase(), attrs[ attName ] ] );
1778 }
1779 }
1780 }
1781 }
1782
1783 return overrides;
1784 }
1785
1786 // Make the comparison of attribute value easier by standardizing it.
1787 function normalizeProperty( name, value, isStyle ) {
1788 var temp = new CKEDITOR.dom.element( 'span' );
1789 temp[ isStyle ? 'setStyle' : 'setAttribute' ]( name, value );
1790 return temp[ isStyle ? 'getStyle' : 'getAttribute' ]( name );
1791 }
1792
1793 // Compare two bunch of styles, with the speciality that value 'inherit'
1794 // is treated as a wildcard which will match any value.
1795 // @param {Object/String} source
1796 // @param {Object/String} target
1797 function compareCssText( source, target ) {
1798 if ( typeof source == 'string' )
1799 source = CKEDITOR.tools.parseCssText( source );
1800 if ( typeof target == 'string' )
1801 target = CKEDITOR.tools.parseCssText( target, true );
1802
1803 for ( var name in source ) {
1804 if ( !( name in target && ( target[ name ] == source[ name ] || source[ name ] == 'inherit' || target[ name ] == 'inherit' ) ) )
1805 return false;
1806 }
1807 return true;
1808 }
1809
1810 function applyStyleOnSelection( selection, remove, editor ) {
1811 var doc = selection.document,
1812 ranges = selection.getRanges(),
1813 func = remove ? this.removeFromRange : this.applyToRange,
1814 range;
1815
1816 var iterator = ranges.createIterator();
1817 while ( ( range = iterator.getNextRange() ) )
1818 func.call( this, range, editor );
1819
1820 selection.selectRanges( ranges );
1821 doc.removeCustomData( 'doc_processing_style' );
1822 }
1823 } )();
1824
1825 /**
1826 * Generic style command. It applies a specific style when executed.
1827 *
1828 * var boldStyle = new CKEDITOR.style( { element: 'strong' } );
1829 * // Register the "bold" command, which applies the bold style.
1830 * editor.addCommand( 'bold', new CKEDITOR.styleCommand( boldStyle ) );
1831 *
1832 * @class
1833 * @constructor Creates a styleCommand class instance.
1834 * @extends CKEDITOR.commandDefinition
1835 * @param {CKEDITOR.style} style The style to be applied when command is executed.
1836 * @param {Object} [ext] Additional command definition's properties.
1837 */
1838 CKEDITOR.styleCommand = function( style, ext ) {
1839 this.style = style;
1840 this.allowedContent = style;
1841 this.requiredContent = style;
1842
1843 CKEDITOR.tools.extend( this, ext, true );
1844 };
1845
1846 /**
1847 * @param {CKEDITOR.editor} editor
1848 * @todo
1849 */
1850 CKEDITOR.styleCommand.prototype.exec = function( editor ) {
1851 editor.focus();
1852
1853 if ( this.state == CKEDITOR.TRISTATE_OFF )
1854 editor.applyStyle( this.style );
1855 else if ( this.state == CKEDITOR.TRISTATE_ON )
1856 editor.removeStyle( this.style );
1857 };
1858
1859 /**
1860 * Manages styles registration and loading. See also {@link CKEDITOR.config#stylesSet}.
1861 *
1862 * // The set of styles for the <b>Styles</b> drop-down list.
1863 * CKEDITOR.stylesSet.add( 'default', [
1864 * // Block Styles
1865 * { name: 'Blue Title', element: 'h3', styles: { 'color': 'Blue' } },
1866 * { name: 'Red Title', element: 'h3', styles: { 'color': 'Red' } },
1867 *
1868 * // Inline Styles
1869 * { name: 'Marker: Yellow', element: 'span', styles: { 'background-color': 'Yellow' } },
1870 * { name: 'Marker: Green', element: 'span', styles: { 'background-color': 'Lime' } },
1871 *
1872 * // Object Styles
1873 * {
1874 * name: 'Image on Left',
1875 * element: 'img',
1876 * attributes: {
1877 * style: 'padding: 5px; margin-right: 5px',
1878 * border: '2',
1879 * align: 'left'
1880 * }
1881 * }
1882 * ] );
1883 *
1884 * @since 3.2
1885 * @class
1886 * @singleton
1887 * @extends CKEDITOR.resourceManager
1888 */
1889 CKEDITOR.stylesSet = new CKEDITOR.resourceManager( '', 'stylesSet' );
1890
1891 // Backward compatibility (#5025).
1892 CKEDITOR.addStylesSet = CKEDITOR.tools.bind( CKEDITOR.stylesSet.add, CKEDITOR.stylesSet );
1893 CKEDITOR.loadStylesSet = function( name, url, callback ) {
1894 CKEDITOR.stylesSet.addExternal( name, url, '' );
1895 CKEDITOR.stylesSet.load( name, callback );
1896 };
1897
1898 CKEDITOR.tools.extend( CKEDITOR.editor.prototype, {
1899 /**
1900 * Registers a function to be called whenever the selection position changes in the
1901 * editing area. The current state is passed to the function. The possible
1902 * states are {@link CKEDITOR#TRISTATE_ON} and {@link CKEDITOR#TRISTATE_OFF}.
1903 *
1904 * // Create a style object for the <b> element.
1905 * var style = new CKEDITOR.style( { element: 'b' } );
1906 * var editor = CKEDITOR.instances.editor1;
1907 * editor.attachStyleStateChange( style, function( state ) {
1908 * if ( state == CKEDITOR.TRISTATE_ON )
1909 * alert( 'The current state for the B element is ON' );
1910 * else
1911 * alert( 'The current state for the B element is OFF' );
1912 * } );
1913 *
1914 * @member CKEDITOR.editor
1915 * @param {CKEDITOR.style} style The style to be watched.
1916 * @param {Function} callback The function to be called.
1917 */
1918 attachStyleStateChange: function( style, callback ) {
1919 // Try to get the list of attached callbacks.
1920 var styleStateChangeCallbacks = this._.styleStateChangeCallbacks;
1921
1922 // If it doesn't exist, it means this is the first call. So, let's create
1923 // all the structure to manage the style checks and the callback calls.
1924 if ( !styleStateChangeCallbacks ) {
1925 // Create the callbacks array.
1926 styleStateChangeCallbacks = this._.styleStateChangeCallbacks = [];
1927
1928 // Attach to the selectionChange event, so we can check the styles at
1929 // that point.
1930 this.on( 'selectionChange', function( ev ) {
1931 // Loop throw all registered callbacks.
1932 for ( var i = 0; i < styleStateChangeCallbacks.length; i++ ) {
1933 var callback = styleStateChangeCallbacks[ i ];
1934
1935 // Check the current state for the style defined for that callback.
1936 var currentState = callback.style.checkActive( ev.data.path, this ) ?
1937 CKEDITOR.TRISTATE_ON : CKEDITOR.TRISTATE_OFF;
1938
1939 // Call the callback function, passing the current state to it.
1940 callback.fn.call( this, currentState );
1941 }
1942 } );
1943 }
1944
1945 // Save the callback info, so it can be checked on the next occurrence of
1946 // selectionChange.
1947 styleStateChangeCallbacks.push( { style: style, fn: callback } );
1948 },
1949
1950 /**
1951 * Applies the style upon the editor's current selection. Shorthand for
1952 * {@link CKEDITOR.style#apply}.
1953 *
1954 * @member CKEDITOR.editor
1955 * @param {CKEDITOR.style} style
1956 */
1957 applyStyle: function( style ) {
1958 style.apply( this );
1959 },
1960
1961 /**
1962 * Removes the style from the editor's current selection. Shorthand for
1963 * {@link CKEDITOR.style#remove}.
1964 *
1965 * @member CKEDITOR.editor
1966 * @param {CKEDITOR.style} style
1967 */
1968 removeStyle: function( style ) {
1969 style.remove( this );
1970 },
1971
1972 /**
1973 * Gets the current `stylesSet` for this instance.
1974 *
1975 * editor.getStylesSet( function( stylesDefinitions ) {} );
1976 *
1977 * See also {@link CKEDITOR.editor#stylesSet} event.
1978 *
1979 * @member CKEDITOR.editor
1980 * @param {Function} callback The function to be called with the styles data.
1981 */
1982 getStylesSet: function( callback ) {
1983 if ( !this._.stylesDefinitions ) {
1984 var editor = this,
1985 // Respect the backwards compatible definition entry
1986 configStyleSet = editor.config.stylesCombo_stylesSet || editor.config.stylesSet;
1987
1988 // The false value means that none styles should be loaded.
1989 if ( configStyleSet === false ) {
1990 callback( null );
1991 return;
1992 }
1993
1994 // #5352 Allow to define the styles directly in the config object
1995 if ( configStyleSet instanceof Array ) {
1996 editor._.stylesDefinitions = configStyleSet;
1997 callback( configStyleSet );
1998 return;
1999 }
2000
2001 // Default value is 'default'.
2002 if ( !configStyleSet )
2003 configStyleSet = 'default';
2004
2005 var partsStylesSet = configStyleSet.split( ':' ),
2006 styleSetName = partsStylesSet[ 0 ],
2007 externalPath = partsStylesSet[ 1 ];
2008
2009 CKEDITOR.stylesSet.addExternal( styleSetName, externalPath ? partsStylesSet.slice( 1 ).join( ':' ) : CKEDITOR.getUrl( 'styles.js' ), '' );
2010
2011 CKEDITOR.stylesSet.load( styleSetName, function( stylesSet ) {
2012 editor._.stylesDefinitions = stylesSet[ styleSetName ];
2013 callback( editor._.stylesDefinitions );
2014 } );
2015 } else {
2016 callback( this._.stylesDefinitions );
2017 }
2018 }
2019 } );
2020
2021 /**
2022 * Indicates that fully selected read-only elements will be included when
2023 * applying the style (for inline styles only).
2024 *
2025 * @since 3.5
2026 * @property {Boolean} [includeReadonly=false]
2027 * @member CKEDITOR.style
2028 */
2029
2030 /**
2031 * Indicates that any matches element of this style will be eventually removed
2032 * when calling {@link CKEDITOR.editor#removeStyle}.
2033 *
2034 * @since 4.0
2035 * @property {Boolean} [alwaysRemoveElement=false]
2036 * @member CKEDITOR.style
2037 */
2038
2039 /**
2040 * Disables inline styling on read-only elements.
2041 *
2042 * @since 3.5
2043 * @cfg {Boolean} [disableReadonlyStyling=false]
2044 * @member CKEDITOR.config
2045 */
2046
2047 /**
2048 * The "styles definition set" to use in the editor. They will be used in the
2049 * styles combo and the style selector of the div container.
2050 *
2051 * The styles may be defined in the page containing the editor, or can be
2052 * loaded on demand from an external file. In the second case, if this setting
2053 * contains only a name, the `styles.js` file will be loaded from the
2054 * CKEditor root folder (what ensures backward compatibility with CKEditor 4.0).
2055 *
2056 * Otherwise, this setting has the `name:url` syntax, making it
2057 * possible to set the URL from which the styles file will be loaded.
2058 * Note that the `name` has to be equal to the name used in
2059 * {@link CKEDITOR.stylesSet#add} while registering the styles set.
2060 *
2061 * **Note**: Since 4.1 it is possible to set `stylesSet` to `false`
2062 * to prevent loading any styles set.
2063 *
2064 * Read more in the [documentation](#!/guide/dev_styles)
2065 * and see the [SDK sample](http://sdk.ckeditor.com/samples/styles.html).
2066 *
2067 * // Do not load any file. The styles set is empty.
2068 * config.stylesSet = false;
2069 *
2070 * // Load the 'mystyles' styles set from the styles.js file.
2071 * config.stylesSet = 'mystyles';
2072 *
2073 * // Load the 'mystyles' styles set from a relative URL.
2074 * config.stylesSet = 'mystyles:/editorstyles/styles.js';
2075 *
2076 * // Load the 'mystyles' styles set from a full URL.
2077 * config.stylesSet = 'mystyles:http://www.example.com/editorstyles/styles.js';
2078 *
2079 * // Load from a list of definitions.
2080 * config.stylesSet = [
2081 * { name: 'Strong Emphasis', element: 'strong' },
2082 * { name: 'Emphasis', element: 'em' },
2083 * ...
2084 * ];
2085 *
2086 * @since 3.3
2087 * @cfg {String/Array/Boolean} [stylesSet='default']
2088 * @member CKEDITOR.config
2089 */