5d402a9378eff1cb7f6b2359c95e0239ea168edf
[Packages/TYPO3.CMS.git] / typo3 / sysext / rtehtmlarea / htmlarea / plugins / TextStyle / text-style.js
1 /***************************************************************
2 * Copyright notice
3 *
4 * (c) 2007-2011 Stanislas Rolland <typo3(arobas)sjbr.ca>
5 * All rights reserved
6 *
7 * This script is part of the TYPO3 project. The TYPO3 project is
8 * free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * The GNU General Public License can be found at
14 * http://www.gnu.org/copyleft/gpl.html.
15 * A copy is found in the textfile GPL.txt and important notices to the license
16 * from the author is found in LICENSE.txt distributed with these scripts.
17 *
18 *
19 * This script is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
23 *
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /*
28 * Text Style Plugin for TYPO3 htmlArea RTE
29 *
30 * TYPO3 SVN ID: $Id$
31 */
32 /*
33 * Creation of the class of TextStyle plugins
34 */
35 HTMLArea.TextStyle = Ext.extend(HTMLArea.Plugin, {
36 /*
37 * This function gets called by the class constructor
38 */
39 configurePlugin: function (editor) {
40 this.cssArray = {};
41 this.classesUrl = this.editorConfiguration.classesUrl;
42 this.pageTSconfiguration = this.editorConfiguration.buttons.textstyle;
43 this.tags = (this.pageTSconfiguration && this.pageTSconfiguration.tags) ? this.pageTSconfiguration.tags : {};
44 if (typeof(this.editorConfiguration.classesTag) !== "undefined") {
45 if (this.editorConfiguration.classesTag.span) {
46 if (!this.tags.span) {
47 this.tags.span = new Object();
48 }
49 if (!this.tags.span.allowedClasses) {
50 this.tags.span.allowedClasses = this.editorConfiguration.classesTag.span;
51 }
52 }
53 }
54 var allowedClasses;
55 for (var tagName in this.tags) {
56 if (this.tags.hasOwnProperty(tagName)) {
57 if (this.tags[tagName].allowedClasses) {
58 allowedClasses = this.tags[tagName].allowedClasses.trim().split(",");
59 for (var cssClass in allowedClasses) {
60 if (allowedClasses.hasOwnProperty(cssClass)) {
61 allowedClasses[cssClass] = allowedClasses[cssClass].trim().replace(/\*/g, ".*");
62 }
63 }
64 this.tags[tagName].allowedClasses = new RegExp( "^(" + allowedClasses.join("|") + ")$", "i");
65 }
66 }
67 }
68 this.showTagFreeClasses = (this.pageTSconfiguration ? this.pageTSconfiguration.showTagFreeClasses : false) || this.editorConfiguration.showTagFreeClasses;
69 this.prefixLabelWithClassName = this.pageTSconfiguration ? this.pageTSconfiguration.prefixLabelWithClassName : false;
70 this.postfixLabelWithClassName = this.pageTSconfiguration ? this.pageTSconfiguration.postfixLabelWithClassName : false;
71 /*
72 * Regular expression to check if an element is an inline elment
73 */
74 this.REInlineTags = /^(a|abbr|acronym|b|bdo|big|cite|code|del|dfn|em|i|img|ins|kbd|q|samp|small|span|strike|strong|sub|sup|tt|u|var)$/;
75
76 // Allowed attributes on inline elements
77 this.allowedAttributes = new Array("id", "title", "lang", "xml:lang", "dir", "class");
78 if (Ext.isIE) {
79 this.addAllowedAttribute("className");
80 }
81 /*
82 * Registering plugin "About" information
83 */
84 var pluginInformation = {
85 version : '2.2',
86 developer : 'Stanislas Rolland',
87 developerUrl : 'http://www.sjbr.ca/',
88 copyrightOwner : 'Stanislas Rolland',
89 sponsor : this.localize('Technische Universitat Ilmenau'),
90 sponsorUrl : 'http://www.tu-ilmenau.de/',
91 license : 'GPL'
92 };
93 this.registerPluginInformation(pluginInformation);
94 /*
95 * Registering the dropdown list
96 */
97 var buttonId = 'TextStyle';
98 var fieldLabel = this.pageTSconfiguration ? this.pageTSconfiguration.fieldLabel : '';
99 if (Ext.isEmpty(fieldLabel) && this.isButtonInToolbar('I[text_style]')) {
100 fieldLabel = this.localize('text_style');
101 }
102 var dropDownConfiguration = {
103 id: buttonId,
104 tooltip: this.localize(buttonId + '-Tooltip'),
105 fieldLabel: fieldLabel,
106 options: [[this.localize('No style'), 'none']],
107 action: 'onChange',
108 storeFields: [ { name: 'text'}, { name: 'value'}, { name: 'style'} ],
109 tpl: '<tpl for="."><div ext:qtip="{value}" style="{style}text-align:left;font-size:11px;" class="x-combo-list-item">{text}</div></tpl>'
110 };
111 if (this.pageTSconfiguration) {
112 if (this.pageTSconfiguration.width) {
113 dropDownConfiguration.width = parseInt(this.pageTSconfiguration.width, 10);
114 }
115 if (this.pageTSconfiguration.listWidth) {
116 dropDownConfiguration.listWidth = parseInt(this.pageTSconfiguration.listWidth, 10);
117 }
118 if (this.pageTSconfiguration.maxHeight) {
119 dropDownConfiguration.maxHeight = parseInt(this.pageTSconfiguration.maxHeight, 10);
120 }
121 }
122 this.registerDropDown(dropDownConfiguration);
123 return true;
124 },
125
126 isInlineElement: function (el) {
127 return el && (el.nodeType === 1) && this.REInlineTags.test(el.nodeName.toLowerCase());
128 },
129 /*
130 * This function adds an attribute to the array of allowed attributes on inline elements
131 *
132 * @param string attribute: the name of the attribute to be added to the array
133 *
134 * @return void
135 */
136 addAllowedAttribute: function (attribute) {
137 this.allowedAttributes.push(attribute);
138 },
139 /*
140 * This function gets called when some style in the drop-down list applies it to the highlighted textt
141 */
142 onChange: function (editor, combo, record, index) {
143 var className = combo.getValue();
144 var classNames = null;
145 var fullNodeSelected = false;
146
147 this.editor.focus();
148 var selection = this.editor._getSelection();
149 var statusBarSelection = this.editor.statusBar ? this.editor.statusBar.getSelection() : null;
150 var range = this.editor._createRange(selection);
151 var parent = this.editor.getParentElement();
152 var selectionEmpty = this.editor._selectionEmpty(selection);
153 var ancestors = this.editor.getAllAncestors();
154 if (Ext.isIE) {
155 var bookmark = range.getBookmark();
156 }
157
158 if (!selectionEmpty) {
159 // The selection is not empty
160 for (var i = 0; i < ancestors.length; ++i) {
161 fullNodeSelected = (Ext.isIE && ((statusBarSelection === ancestors[i] && ancestors[i].innerText === range.text) || (!statusBarSelection && ancestors[i].innerText === range.text)))
162 || (!Ext.isIE && ((statusBarSelection === ancestors[i] && ancestors[i].textContent === range.toString()) || (!statusBarSelection && ancestors[i].textContent === range.toString())));
163 if (fullNodeSelected) {
164 if (this.isInlineElement(ancestors[i])) {
165 parent = ancestors[i];
166 }
167 break;
168 }
169 }
170 // Working around bug in Safari selectNodeContents
171 if (!fullNodeSelected && Ext.isWebKit && statusBarSelection && this.isInlineElement(statusBarSelection) && statusBarSelection.textContent === range.toString()) {
172 fullNodeSelected = true;
173 parent = statusBarSelection;
174 }
175 }
176 if (!selectionEmpty && !fullNodeSelected || (!selectionEmpty && fullNodeSelected && parent && HTMLArea.isBlockElement(parent))) {
177 // The selection is not empty, nor full element, or the selection is full block element
178 if (className !== "none") {
179 // Add span element with class attribute
180 var newElement = editor._doc.createElement("span");
181 HTMLArea.DOM.addClass(newElement, className);
182 editor.wrapWithInlineElement(newElement, selection, range);
183 if (!Ext.isIE) {
184 range.detach();
185 }
186 }
187 } else {
188 this.applyClassChange(parent, className);
189 }
190 },
191 /*
192 * This function applies the class change to the node
193 */
194 applyClassChange: function (node, className) {
195 // Add or remove class
196 if (node && !HTMLArea.isBlockElement(node)) {
197 if (className === 'none' && node.className && /\S/.test(node.className)) {
198 classNames = node.className.trim().split(' ');
199 HTMLArea.DOM.removeClass(node, classNames[classNames.length-1]);
200 }
201 if (className !== 'none') {
202 HTMLArea.DOM.addClass(node, className);
203 }
204 // Remove the span tag if it has no more attribute
205 if (/^span$/i.test(node.nodeName) && !HTMLArea.hasAllowedAttributes(node, this.allowedAttributes)) {
206 this.editor.removeMarkup(node);
207 }
208 }
209 },
210 /*
211 * This function gets called when the plugin is generated
212 * Get the classes configuration and initiate the parsing of the style sheets
213 */
214 onGenerate: function () {
215 // Monitor editor changing mode
216 this.editor.iframe.mon(this.editor, 'HTMLAreaEventModeChange', this.onModeChange, this);
217 // Create CSS Parser object
218 this.textStyles = new HTMLArea.CSS.Parser({
219 prefixLabelWithClassName: this.prefixLabelWithClassName,
220 postfixLabelWithClassName: this.postfixLabelWithClassName,
221 showTagFreeClasses: this.showTagFreeClasses,
222 tags: this.tags,
223 editor: this.editor
224 });
225 // Monitor css parsing being completed
226 this.editor.iframe.mon(this.textStyles, 'HTMLAreaEventCssParsingComplete', this.onCssParsingComplete, this);
227 this.textStyles.initiateParsing();
228 },
229 /*
230 * This handler gets called when parsing of css classes is completed
231 */
232 onCssParsingComplete: function () {
233 if (this.textStyles.isReady) {
234 this.cssArray = this.textStyles.getClasses();
235 }
236 if (this.getEditorMode() === 'wysiwyg' && this.editor.isEditable()) {
237 this.updateToolbar('TextStyle');
238 }
239 },
240 /*
241 * This handler gets called when the toolbar is being updated
242 */
243 onUpdateToolbar: function (button, mode, selectionEmpty, ancestors) {
244 if (mode === 'wysiwyg' && this.editor.isEditable()) {
245 this.updateToolbar(button.itemId);
246 }
247 },
248 /*
249 * This handler gets called when the editor has changed its mode to "wysiwyg"
250 */
251 onModeChange: function (mode) {
252 if (mode === 'wysiwyg' && this.editor.isEditable()) {
253 this.updateToolbar('TextStyle');
254 }
255 },
256 /*
257 * This function gets called when the drop-down list needs to be refreshed
258 */
259 updateToolbar: function(dropDownId) {
260 var editor = this.editor;
261 if (this.getEditorMode() === "wysiwyg" && this.editor.isEditable()) {
262 var tagName = false, classNames = Array(), fullNodeSelected = false;
263 var selection = editor._getSelection();
264 var statusBarSelection = editor.statusBar ? editor.statusBar.getSelection() : null;
265 var range = editor._createRange(selection);
266 var parent = editor.getParentElement(selection);
267 var ancestors = editor.getAllAncestors();
268 if (parent && !HTMLArea.isBlockElement(parent)) {
269 tagName = parent.nodeName.toLowerCase();
270 if (parent.className && /\S/.test(parent.className)) {
271 classNames = parent.className.trim().split(" ");
272 }
273 }
274 var selectionEmpty = editor._selectionEmpty(selection);
275 if (!selectionEmpty) {
276 for (var i = 0; i < ancestors.length; ++i) {
277 fullNodeSelected = (statusBarSelection === ancestors[i])
278 && ((!Ext.isIE && ancestors[i].textContent === range.toString()) || (Ext.isIE && ancestors[i].innerText === range.text));
279 if (fullNodeSelected) {
280 if (!HTMLArea.isBlockElement(ancestors[i])) {
281 tagName = ancestors[i].nodeName.toLowerCase();
282 if (ancestors[i].className && /\S/.test(ancestors[i].className)) {
283 classNames = ancestors[i].className.trim().split(" ");
284 }
285 }
286 break;
287 }
288 }
289 // Working around bug in Safari selectNodeContents
290 if (!fullNodeSelected && Ext.isWebKit && statusBarSelection && this.isInlineElement(statusBarSelection) && statusBarSelection.textContent === range.toString()) {
291 fullNodeSelected = true;
292 tagName = statusBarSelection.nodeName.toLowerCase();
293 if (statusBarSelection.className && /\S/.test(statusBarSelection.className)) {
294 classNames = statusBarSelection.className.trim().split(" ");
295 }
296 }
297 }
298 var selectionInInlineElement = tagName && this.REInlineTags.test(tagName);
299 var disabled = !editor.endPointsInSameBlock() || (fullNodeSelected && !tagName) || (selectionEmpty && !selectionInInlineElement);
300 if (!disabled && !tagName) {
301 tagName = "span";
302 }
303 this.updateValue(dropDownId, tagName, classNames, selectionEmpty, fullNodeSelected, disabled);
304 } else {
305 var dropDown = this.getButton(dropDownId);
306 if (dropDown) {
307 dropDown.setDisabled(!dropDown.textMode);
308 }
309 }
310 },
311 /*
312 * This function reinitializes the options of the dropdown
313 */
314 initializeDropDown: function (dropDown) {
315 var store = dropDown.getStore();
316 store.removeAll(false);
317 store.insert(0, new store.recordType({
318 text: this.localize('No style'),
319 value: 'none'
320 }));
321 dropDown.setValue('none');
322 },
323 /*
324 * This function builds the options to be displayed in the dropDown box
325 */
326 buildDropDownOptions: function (dropDown, nodeName) {
327 var store = dropDown.getStore();
328 this.initializeDropDown(dropDown);
329 if (this.textStyles.isReady) {
330 var allowedClasses = {};
331 if (this.REInlineTags.test(nodeName)) {
332 if (Ext.isDefined(this.cssArray[nodeName])) {
333 allowedClasses = this.cssArray[nodeName];
334 } else if (this.showTagFreeClasses && Ext.isDefined(this.cssArray['all'])) {
335 allowedClasses = this.cssArray['all'];
336 }
337 }
338 Ext.iterate(allowedClasses, function (cssClass, value) {
339 store.add(new store.recordType({
340 text: value,
341 value: cssClass,
342 style: (!this.editor.config.disablePCexamples && HTMLArea.classesValues && HTMLArea.classesValues[cssClass] && !HTMLArea.classesNoShow[cssClass]) ? HTMLArea.classesValues[cssClass] : null
343 }));
344 }, this);
345 }
346 },
347 /*
348 * This function sets the selected option of the dropDown box
349 */
350 setSelectedOption: function (dropDown, classNames, noUnknown, defaultClass) {
351 var store = dropDown.getStore();
352 dropDown.setValue('none');
353 if (classNames.length) {
354 var index = store.findExact('value', classNames[classNames.length-1]);
355 if (index != -1) {
356 dropDown.setValue(classNames[classNames.length-1]);
357 if (!defaultClass) {
358 store.getAt(0).set('text', this.localize('Remove style'));
359 }
360 }
361 if (index == -1 && !noUnknown) {
362 store.add(new store.recordType({
363 text: this.localize('Unknown style'),
364 value: classNames[classNames.length-1]
365 }));
366 index = store.getCount()-1;
367 dropDown.setValue(classNames[classNames.length-1]);
368 if (!defaultClass) {
369 store.getAt(0).set('text', this.localize('Remove style'));
370 }
371 }
372 store.each(function (option) {
373 if (("," + classNames.join(",") + ",").indexOf("," + option.get('value') + ",") != -1 && store.indexOf(option) != index) {
374 store.removeAt(store.indexOf(option));
375 }
376 return true;
377 });
378 }
379 dropDown.setDisabled(!(store.getCount()>1));
380 },
381 /*
382 * This function updates the current value of the dropdown list
383 */
384 updateValue: function (dropDownId, nodeName, classNames, selectionEmpty, fullNodeSelected, disabled) {
385 var editor = this.editor;
386 var dropDown = this.getButton(dropDownId);
387 if (dropDown) {
388 this.buildDropDownOptions(dropDown, nodeName);
389 if (classNames.length && (selectionEmpty || fullNodeSelected)) {
390 this.setSelectedOption(dropDown, classNames);
391 }
392 var store = dropDown.getStore();
393 dropDown.setDisabled(!(store.getCount()>1) || disabled);
394 }
395 }
396 });