source: trunk/library/tiny_mce/plugins/paste/editor_plugin_src.js @ 4829

Revision 4829, 32.0 KB checked in by airton, 13 years ago (diff)

Ticket #2146 - Implementacao da funcionalidade de multiplas assinaturas - Adicao da biblioteca TinyMCE

  • Property svn:executable set to *
Line 
1/**
2 * editor_plugin_src.js
3 *
4 * Copyright 2009, Moxiecode Systems AB
5 * Released under LGPL License.
6 *
7 * License: http://tinymce.moxiecode.com/license
8 * Contributing: http://tinymce.moxiecode.com/contributing
9 */
10
11(function() {
12        var each = tinymce.each,
13                defs = {
14                        paste_auto_cleanup_on_paste : true,
15                        paste_enable_default_filters : true,
16                        paste_block_drop : false,
17                        paste_retain_style_properties : "none",
18                        paste_strip_class_attributes : "mso",
19                        paste_remove_spans : false,
20                        paste_remove_styles : false,
21                        paste_remove_styles_if_webkit : true,
22                        paste_convert_middot_lists : true,
23                        paste_convert_headers_to_strong : false,
24                        paste_dialog_width : "450",
25                        paste_dialog_height : "400",
26                        paste_text_use_dialog : false,
27                        paste_text_sticky : false,
28                        paste_text_sticky_default : false,
29                        paste_text_notifyalways : false,
30                        paste_text_linebreaktype : "p",
31                        paste_text_replacements : [
32                                [/\u2026/g, "..."],
33                                [/[\x93\x94\u201c\u201d]/g, '"'],
34                                [/[\x60\x91\x92\u2018\u2019]/g, "'"]
35                        ]
36                };
37
38        function getParam(ed, name) {
39                return ed.getParam(name, defs[name]);
40        }
41
42        tinymce.create('tinymce.plugins.PastePlugin', {
43                init : function(ed, url) {
44                        var t = this;
45
46                        t.editor = ed;
47                        t.url = url;
48
49                        // Setup plugin events
50                        t.onPreProcess = new tinymce.util.Dispatcher(t);
51                        t.onPostProcess = new tinymce.util.Dispatcher(t);
52
53                        // Register default handlers
54                        t.onPreProcess.add(t._preProcess);
55                        t.onPostProcess.add(t._postProcess);
56
57                        // Register optional preprocess handler
58                        t.onPreProcess.add(function(pl, o) {
59                                ed.execCallback('paste_preprocess', pl, o);
60                        });
61
62                        // Register optional postprocess
63                        t.onPostProcess.add(function(pl, o) {
64                                ed.execCallback('paste_postprocess', pl, o);
65                        });
66
67                        ed.onKeyDown.addToTop(function(ed, e) {
68                                // Block ctrl+v from adding an undo level since the default logic in tinymce.Editor will add that
69                                if (((tinymce.isMac ? e.metaKey : e.ctrlKey) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45))
70                                        return false; // Stop other listeners
71                        });
72
73                        // Initialize plain text flag
74                        ed.pasteAsPlainText = getParam(ed, 'paste_text_sticky_default');
75
76                        // This function executes the process handlers and inserts the contents
77                        // force_rich overrides plain text mode set by user, important for pasting with execCommand
78                        function process(o, force_rich) {
79                                var dom = ed.dom, rng, nodes;
80
81                                // Execute pre process handlers
82                                t.onPreProcess.dispatch(t, o);
83
84                                // Create DOM structure
85                                o.node = dom.create('div', 0, o.content);
86
87                                // If pasting inside the same element and the contents is only one block
88                                // remove the block and keep the text since Firefox will copy parts of pre and h1-h6 as a pre element
89                                if (tinymce.isGecko) {
90                                        rng = ed.selection.getRng(true);
91                                        if (rng.startContainer == rng.endContainer && rng.startContainer.nodeType == 3) {
92                                                nodes = dom.select('p,h1,h2,h3,h4,h5,h6,pre', o.node);
93
94                                                // Is only one block node and it doesn't contain word stuff
95                                                if (nodes.length == 1 && o.content.indexOf('__MCE_ITEM__') === -1)
96                                                        dom.remove(nodes.reverse(), true);
97                                        }
98                                }
99
100                                // Execute post process handlers
101                                t.onPostProcess.dispatch(t, o);
102
103                                // Serialize content
104                                o.content = ed.serializer.serialize(o.node, {getInner : 1});
105
106                                // Plain text option active?
107                                if ((!force_rich) && (ed.pasteAsPlainText)) {
108                                        t._insertPlainText(ed, dom, o.content);
109
110                                        if (!getParam(ed, "paste_text_sticky")) {
111                                                ed.pasteAsPlainText = false;
112                                                ed.controlManager.setActive("pastetext", false);
113                                        }
114                                } else {
115                                        t._insert(o.content);
116                                }
117                        }
118
119                        // Add command for external usage
120                        ed.addCommand('mceInsertClipboardContent', function(u, o) {
121                                process(o, true);
122                        });
123
124                        if (!getParam(ed, "paste_text_use_dialog")) {
125                                ed.addCommand('mcePasteText', function(u, v) {
126                                        var cookie = tinymce.util.Cookie;
127
128                                        ed.pasteAsPlainText = !ed.pasteAsPlainText;
129                                        ed.controlManager.setActive('pastetext', ed.pasteAsPlainText);
130
131                                        if ((ed.pasteAsPlainText) && (!cookie.get("tinymcePasteText"))) {
132                                                if (getParam(ed, "paste_text_sticky")) {
133                                                        ed.windowManager.alert(ed.translate('paste.plaintext_mode_sticky'));
134                                                } else {
135                                                        ed.windowManager.alert(ed.translate('paste.plaintext_mode_sticky'));
136                                                }
137
138                                                if (!getParam(ed, "paste_text_notifyalways")) {
139                                                        cookie.set("tinymcePasteText", "1", new Date(new Date().getFullYear() + 1, 12, 31))
140                                                }
141                                        }
142                                });
143                        }
144
145                        ed.addButton('pastetext', {title: 'paste.paste_text_desc', cmd: 'mcePasteText'});
146                        ed.addButton('selectall', {title: 'paste.selectall_desc', cmd: 'selectall'});
147
148                        // This function grabs the contents from the clipboard by adding a
149                        // hidden div and placing the caret inside it and after the browser paste
150                        // is done it grabs that contents and processes that
151                        function grabContent(e) {
152                                var n, or, rng, oldRng, sel = ed.selection, dom = ed.dom, body = ed.getBody(), posY, textContent;
153
154                                // Check if browser supports direct plaintext access
155                                if (e.clipboardData || dom.doc.dataTransfer) {
156                                        textContent = (e.clipboardData || dom.doc.dataTransfer).getData('Text');
157
158                                        if (ed.pasteAsPlainText) {
159                                                e.preventDefault();
160                                                process({content : textContent.replace(/\r?\n/g, '<br />')});
161                                                return;
162                                        }
163                                }
164
165                                if (dom.get('_mcePaste'))
166                                        return;
167
168                                // Create container to paste into
169                                n = dom.add(body, 'div', {id : '_mcePaste', 'class' : 'mcePaste', 'data-mce-bogus' : '1'}, '\uFEFF\uFEFF');
170
171                                // If contentEditable mode we need to find out the position of the closest element
172                                if (body != ed.getDoc().body)
173                                        posY = dom.getPos(ed.selection.getStart(), body).y;
174                                else
175                                        posY = body.scrollTop + dom.getViewPort().y;
176
177                                // Styles needs to be applied after the element is added to the document since WebKit will otherwise remove all styles
178                                dom.setStyles(n, {
179                                        position : 'absolute',
180                                        left : -10000,
181                                        top : posY,
182                                        width : 1,
183                                        height : 1,
184                                        overflow : 'hidden'
185                                });
186
187                                if (tinymce.isIE) {
188                                        // Store away the old range
189                                        oldRng = sel.getRng();
190
191                                        // Select the container
192                                        rng = dom.doc.body.createTextRange();
193                                        rng.moveToElementText(n);
194                                        rng.execCommand('Paste');
195
196                                        // Remove container
197                                        dom.remove(n);
198
199                                        // Check if the contents was changed, if it wasn't then clipboard extraction failed probably due
200                                        // to IE security settings so we pass the junk though better than nothing right
201                                        if (n.innerHTML === '\uFEFF\uFEFF') {
202                                                ed.execCommand('mcePasteWord');
203                                                e.preventDefault();
204                                                return;
205                                        }
206
207                                        // Restore the old range and clear the contents before pasting
208                                        sel.setRng(oldRng);
209                                        sel.setContent('');
210
211                                        // For some odd reason we need to detach the the mceInsertContent call from the paste event
212                                        // It's like IE has a reference to the parent element that you paste in and the selection gets messed up
213                                        // when it tries to restore the selection
214                                        setTimeout(function() {
215                                                // Process contents
216                                                process({content : n.innerHTML});
217                                        }, 0);
218
219                                        // Block the real paste event
220                                        return tinymce.dom.Event.cancel(e);
221                                } else {
222                                        function block(e) {
223                                                e.preventDefault();
224                                        };
225
226                                        // Block mousedown and click to prevent selection change
227                                        dom.bind(ed.getDoc(), 'mousedown', block);
228                                        dom.bind(ed.getDoc(), 'keydown', block);
229
230                                        or = ed.selection.getRng();
231
232                                        // Move select contents inside DIV
233                                        n = n.firstChild;
234                                        rng = ed.getDoc().createRange();
235                                        rng.setStart(n, 0);
236                                        rng.setEnd(n, 2);
237                                        sel.setRng(rng);
238
239                                        // Wait a while and grab the pasted contents
240                                        window.setTimeout(function() {
241                                                var h = '', nl;
242
243                                                // Paste divs duplicated in paste divs seems to happen when you paste plain text so lets first look for that broken behavior in WebKit
244                                                if (!dom.select('div.mcePaste > div.mcePaste').length) {
245                                                        nl = dom.select('div.mcePaste');
246
247                                                        // WebKit will split the div into multiple ones so this will loop through then all and join them to get the whole HTML string
248                                                        each(nl, function(n) {
249                                                                var child = n.firstChild;
250
251                                                                // WebKit inserts a DIV container with lots of odd styles
252                                                                if (child && child.nodeName == 'DIV' && child.style.marginTop && child.style.backgroundColor) {
253                                                                        dom.remove(child, 1);
254                                                                }
255
256                                                                // Remove apply style spans
257                                                                each(dom.select('span.Apple-style-span', n), function(n) {
258                                                                        dom.remove(n, 1);
259                                                                });
260
261                                                                // Remove bogus br elements
262                                                                each(dom.select('br[data-mce-bogus]', n), function(n) {
263                                                                        dom.remove(n);
264                                                                });
265
266                                                                // WebKit will make a copy of the DIV for each line of plain text pasted and insert them into the DIV
267                                                                if (n.parentNode.className != 'mcePaste')
268                                                                        h += n.innerHTML;
269                                                        });
270                                                } else {
271                                                        // Found WebKit weirdness so force the content into plain text mode
272                                                        h = '<pre>' + dom.encode(textContent).replace(/\r?\n/g, '<br />') + '</pre>';
273                                                }
274
275                                                // Remove the nodes
276                                                each(dom.select('div.mcePaste'), function(n) {
277                                                        dom.remove(n);
278                                                });
279
280                                                // Restore the old selection
281                                                if (or)
282                                                        sel.setRng(or);
283
284                                                process({content : h});
285
286                                                // Unblock events ones we got the contents
287                                                dom.unbind(ed.getDoc(), 'mousedown', block);
288                                                dom.unbind(ed.getDoc(), 'keydown', block);
289                                        }, 0);
290                                }
291                        }
292
293                        // Check if we should use the new auto process method                   
294                        if (getParam(ed, "paste_auto_cleanup_on_paste")) {
295                                // Is it's Opera or older FF use key handler
296                                if (tinymce.isOpera || /Firefox\/2/.test(navigator.userAgent)) {
297                                        ed.onKeyDown.addToTop(function(ed, e) {
298                                                if (((tinymce.isMac ? e.metaKey : e.ctrlKey) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45))
299                                                        grabContent(e);
300                                        });
301                                } else {
302                                        // Grab contents on paste event on Gecko and WebKit
303                                        ed.onPaste.addToTop(function(ed, e) {
304                                                return grabContent(e);
305                                        });
306                                }
307                        }
308
309                        ed.onInit.add(function() {
310                                ed.controlManager.setActive("pastetext", ed.pasteAsPlainText);
311
312                                // Block all drag/drop events
313                                if (getParam(ed, "paste_block_drop")) {
314                                        ed.dom.bind(ed.getBody(), ['dragend', 'dragover', 'draggesture', 'dragdrop', 'drop', 'drag'], function(e) {
315                                                e.preventDefault();
316                                                e.stopPropagation();
317
318                                                return false;
319                                        });
320                                }
321                        });
322
323                        // Add legacy support
324                        t._legacySupport();
325                },
326
327                getInfo : function() {
328                        return {
329                                longname : 'Paste text/word',
330                                author : 'Moxiecode Systems AB',
331                                authorurl : 'http://tinymce.moxiecode.com',
332                                infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/paste',
333                                version : tinymce.majorVersion + "." + tinymce.minorVersion
334                        };
335                },
336
337                _preProcess : function(pl, o) {
338                        var ed = this.editor,
339                                h = o.content,
340                                grep = tinymce.grep,
341                                explode = tinymce.explode,
342                                trim = tinymce.trim,
343                                len, stripClass;
344
345                        //console.log('Before preprocess:' + o.content);
346
347                        function process(items) {
348                                each(items, function(v) {
349                                        // Remove or replace
350                                        if (v.constructor == RegExp)
351                                                h = h.replace(v, '');
352                                        else
353                                                h = h.replace(v[0], v[1]);
354                                });
355                        }
356                       
357                        if (ed.settings.paste_enable_default_filters == false) {
358                                return;
359                        }
360
361                        // IE9 adds BRs before/after block elements when contents is pasted from word or for example another browser
362                        if (tinymce.isIE && document.documentMode >= 9)
363                                process([[/(?:<br>&nbsp;[\s\r\n]+|<br>)*(<\/?(h[1-6r]|p|div|address|pre|form|table|tbody|thead|tfoot|th|tr|td|li|ol|ul|caption|blockquote|center|dl|dt|dd|dir|fieldset)[^>]*>)(?:<br>&nbsp;[\s\r\n]+|<br>)*/g, '$1']]);
364
365                        // Detect Word content and process it more aggressive
366                        if (/class="?Mso|style="[^"]*\bmso-|w:WordDocument/i.test(h) || o.wordContent) {
367                                o.wordContent = true;                   // Mark the pasted contents as word specific content
368                                //console.log('Word contents detected.');
369
370                                // Process away some basic content
371                                process([
372                                        /^\s*(&nbsp;)+/gi,                              // &nbsp; entities at the start of contents
373                                        /(&nbsp;|<br[^>]*>)+\s*$/gi             // &nbsp; entities at the end of contents
374                                ]);
375
376                                if (getParam(ed, "paste_convert_headers_to_strong")) {
377                                        h = h.replace(/<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>");
378                                }
379
380                                if (getParam(ed, "paste_convert_middot_lists")) {
381                                        process([
382                                                [/<!--\[if !supportLists\]-->/gi, '$&__MCE_ITEM__'],                                    // Convert supportLists to a list item marker
383                                                [/(<span[^>]+(?:mso-list:|:\s*symbol)[^>]+>)/gi, '$1__MCE_ITEM__'],             // Convert mso-list and symbol spans to item markers
384                                                [/(<p[^>]+(?:MsoListParagraph)[^>]+>)/gi, '$1__MCE_ITEM__']                             // Convert mso-list and symbol paragraphs to item markers (FF)
385                                        ]);
386                                }
387
388                                process([
389                                        // Word comments like conditional comments etc
390                                        /<!--[\s\S]+?-->/gi,
391
392                                        // Remove comments, scripts (e.g., msoShowComment), XML tag, VML content, MS Office namespaced tags, and a few other tags
393                                        /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi,
394
395                                        // Convert <s> into <strike> for line-though
396                                        [/<(\/?)s>/gi, "<$1strike>"],
397
398                                        // Replace nsbp entites to char since it's easier to handle
399                                        [/&nbsp;/gi, "\u00a0"]
400                                ]);
401
402                                // Remove bad attributes, with or without quotes, ensuring that attribute text is really inside a tag.
403                                // If JavaScript had a RegExp look-behind, we could have integrated this with the last process() array and got rid of the loop. But alas, it does not, so we cannot.
404                                do {
405                                        len = h.length;
406                                        h = h.replace(/(<[a-z][^>]*\s)(?:id|name|language|type|on\w+|\w+:\w+)=(?:"[^"]*"|\w+)\s?/gi, "$1");
407                                } while (len != h.length);
408
409                                // Remove all spans if no styles is to be retained
410                                if (getParam(ed, "paste_retain_style_properties").replace(/^none$/i, "").length == 0) {
411                                        h = h.replace(/<\/?span[^>]*>/gi, "");
412                                } else {
413                                        // We're keeping styles, so at least clean them up.
414                                        // CSS Reference: http://msdn.microsoft.com/en-us/library/aa155477.aspx
415
416                                        process([
417                                                // Convert <span style="mso-spacerun:yes">___</span> to string of alternating breaking/non-breaking spaces of same length
418                                                [/<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi,
419                                                        function(str, spaces) {
420                                                                return (spaces.length > 0)? spaces.replace(/./, " ").slice(Math.floor(spaces.length/2)).split("").join("\u00a0") : "";
421                                                        }
422                                                ],
423
424                                                // Examine all styles: delete junk, transform some, and keep the rest
425                                                [/(<[a-z][^>]*)\sstyle="([^"]*)"/gi,
426                                                        function(str, tag, style) {
427                                                                var n = [],
428                                                                        i = 0,
429                                                                        s = explode(trim(style).replace(/&quot;/gi, "'"), ";");
430
431                                                                // Examine each style definition within the tag's style attribute
432                                                                each(s, function(v) {
433                                                                        var name, value,
434                                                                                parts = explode(v, ":");
435
436                                                                        function ensureUnits(v) {
437                                                                                return v + ((v !== "0") && (/\d$/.test(v)))? "px" : "";
438                                                                        }
439
440                                                                        if (parts.length == 2) {
441                                                                                name = parts[0].toLowerCase();
442                                                                                value = parts[1].toLowerCase();
443
444                                                                                // Translate certain MS Office styles into their CSS equivalents
445                                                                                switch (name) {
446                                                                                        case "mso-padding-alt":
447                                                                                        case "mso-padding-top-alt":
448                                                                                        case "mso-padding-right-alt":
449                                                                                        case "mso-padding-bottom-alt":
450                                                                                        case "mso-padding-left-alt":
451                                                                                        case "mso-margin-alt":
452                                                                                        case "mso-margin-top-alt":
453                                                                                        case "mso-margin-right-alt":
454                                                                                        case "mso-margin-bottom-alt":
455                                                                                        case "mso-margin-left-alt":
456                                                                                        case "mso-table-layout-alt":
457                                                                                        case "mso-height":
458                                                                                        case "mso-width":
459                                                                                        case "mso-vertical-align-alt":
460                                                                                                n[i++] = name.replace(/^mso-|-alt$/g, "") + ":" + ensureUnits(value);
461                                                                                                return;
462
463                                                                                        case "horiz-align":
464                                                                                                n[i++] = "text-align:" + value;
465                                                                                                return;
466
467                                                                                        case "vert-align":
468                                                                                                n[i++] = "vertical-align:" + value;
469                                                                                                return;
470
471                                                                                        case "font-color":
472                                                                                        case "mso-foreground":
473                                                                                                n[i++] = "color:" + value;
474                                                                                                return;
475
476                                                                                        case "mso-background":
477                                                                                        case "mso-highlight":
478                                                                                                n[i++] = "background:" + value;
479                                                                                                return;
480
481                                                                                        case "mso-default-height":
482                                                                                                n[i++] = "min-height:" + ensureUnits(value);
483                                                                                                return;
484
485                                                                                        case "mso-default-width":
486                                                                                                n[i++] = "min-width:" + ensureUnits(value);
487                                                                                                return;
488
489                                                                                        case "mso-padding-between-alt":
490                                                                                                n[i++] = "border-collapse:separate;border-spacing:" + ensureUnits(value);
491                                                                                                return;
492
493                                                                                        case "text-line-through":
494                                                                                                if ((value == "single") || (value == "double")) {
495                                                                                                        n[i++] = "text-decoration:line-through";
496                                                                                                }
497                                                                                                return;
498
499                                                                                        case "mso-zero-height":
500                                                                                                if (value == "yes") {
501                                                                                                        n[i++] = "display:none";
502                                                                                                }
503                                                                                                return;
504                                                                                }
505
506                                                                                // Eliminate all MS Office style definitions that have no CSS equivalent by examining the first characters in the name
507                                                                                if (/^(mso|column|font-emph|lang|layout|line-break|list-image|nav|panose|punct|row|ruby|sep|size|src|tab-|table-border|text-(?!align|decor|indent|trans)|top-bar|version|vnd|word-break)/.test(name)) {
508                                                                                        return;
509                                                                                }
510
511                                                                                // If it reached this point, it must be a valid CSS style
512                                                                                n[i++] = name + ":" + parts[1];         // Lower-case name, but keep value case
513                                                                        }
514                                                                });
515
516                                                                // If style attribute contained any valid styles the re-write it; otherwise delete style attribute.
517                                                                if (i > 0) {
518                                                                        return tag + ' style="' + n.join(';') + '"';
519                                                                } else {
520                                                                        return tag;
521                                                                }
522                                                        }
523                                                ]
524                                        ]);
525                                }
526                        }
527
528                        // Replace headers with <strong>
529                        if (getParam(ed, "paste_convert_headers_to_strong")) {
530                                process([
531                                        [/<h[1-6][^>]*>/gi, "<p><strong>"],
532                                        [/<\/h[1-6][^>]*>/gi, "</strong></p>"]
533                                ]);
534                        }
535
536                        process([
537                                // Copy paste from Java like Open Office will produce this junk on FF
538                                [/Version:[\d.]+\nStartHTML:\d+\nEndHTML:\d+\nStartFragment:\d+\nEndFragment:\d+/gi, '']
539                        ]);
540
541                        // Class attribute options are: leave all as-is ("none"), remove all ("all"), or remove only those starting with mso ("mso").
542                        // Note:-  paste_strip_class_attributes: "none", verify_css_classes: true is also a good variation.
543                        stripClass = getParam(ed, "paste_strip_class_attributes");
544
545                        if (stripClass !== "none") {
546                                function removeClasses(match, g1) {
547                                                if (stripClass === "all")
548                                                        return '';
549
550                                                var cls = grep(explode(g1.replace(/^(["'])(.*)\1$/, "$2"), " "),
551                                                        function(v) {
552                                                                return (/^(?!mso)/i.test(v));
553                                                        }
554                                                );
555
556                                                return cls.length ? ' class="' + cls.join(" ") + '"' : '';
557                                };
558
559                                h = h.replace(/ class="([^"]+)"/gi, removeClasses);
560                                h = h.replace(/ class=([\-\w]+)/gi, removeClasses);
561                        }
562
563                        // Remove spans option
564                        if (getParam(ed, "paste_remove_spans")) {
565                                h = h.replace(/<\/?span[^>]*>/gi, "");
566                        }
567
568                        //console.log('After preprocess:' + h);
569
570                        o.content = h;
571                },
572
573                /**
574                 * Various post process items.
575                 */
576                _postProcess : function(pl, o) {
577                        var t = this, ed = t.editor, dom = ed.dom, styleProps;
578
579                        if (ed.settings.paste_enable_default_filters == false) {
580                                return;
581                        }
582                       
583                        if (o.wordContent) {
584                                // Remove named anchors or TOC links
585                                each(dom.select('a', o.node), function(a) {
586                                        if (!a.href || a.href.indexOf('#_Toc') != -1)
587                                                dom.remove(a, 1);
588                                });
589
590                                if (getParam(ed, "paste_convert_middot_lists")) {
591                                        t._convertLists(pl, o);
592                                }
593
594                                // Process styles
595                                styleProps = getParam(ed, "paste_retain_style_properties"); // retained properties
596
597                                // Process only if a string was specified and not equal to "all" or "*"
598                                if ((tinymce.is(styleProps, "string")) && (styleProps !== "all") && (styleProps !== "*")) {
599                                        styleProps = tinymce.explode(styleProps.replace(/^none$/i, ""));
600
601                                        // Retains some style properties
602                                        each(dom.select('*', o.node), function(el) {
603                                                var newStyle = {}, npc = 0, i, sp, sv;
604
605                                                // Store a subset of the existing styles
606                                                if (styleProps) {
607                                                        for (i = 0; i < styleProps.length; i++) {
608                                                                sp = styleProps[i];
609                                                                sv = dom.getStyle(el, sp);
610
611                                                                if (sv) {
612                                                                        newStyle[sp] = sv;
613                                                                        npc++;
614                                                                }
615                                                        }
616                                                }
617
618                                                // Remove all of the existing styles
619                                                dom.setAttrib(el, 'style', '');
620
621                                                if (styleProps && npc > 0)
622                                                        dom.setStyles(el, newStyle); // Add back the stored subset of styles
623                                                else // Remove empty span tags that do not have class attributes
624                                                        if (el.nodeName == 'SPAN' && !el.className)
625                                                                dom.remove(el, true);
626                                        });
627                                }
628                        }
629
630                        // Remove all style information or only specifically on WebKit to avoid the style bug on that browser
631                        if (getParam(ed, "paste_remove_styles") || (getParam(ed, "paste_remove_styles_if_webkit") && tinymce.isWebKit)) {
632                                each(dom.select('*[style]', o.node), function(el) {
633                                        el.removeAttribute('style');
634                                        el.removeAttribute('data-mce-style');
635                                });
636                        } else {
637                                if (tinymce.isWebKit) {
638                                        // We need to compress the styles on WebKit since if you paste <img border="0" /> it will become <img border="0" style="... lots of junk ..." />
639                                        // Removing the mce_style that contains the real value will force the Serializer engine to compress the styles
640                                        each(dom.select('*', o.node), function(el) {
641                                                el.removeAttribute('data-mce-style');
642                                        });
643                                }
644                        }
645                },
646
647                /**
648                 * Converts the most common bullet and number formats in Office into a real semantic UL/LI list.
649                 */
650                _convertLists : function(pl, o) {
651                        var dom = pl.editor.dom, listElm, li, lastMargin = -1, margin, levels = [], lastType, html;
652
653                        // Convert middot lists into real semantic lists
654                        each(dom.select('p', o.node), function(p) {
655                                var sib, val = '', type, html, idx, parents;
656
657                                // Get text node value at beginning of paragraph
658                                for (sib = p.firstChild; sib && sib.nodeType == 3; sib = sib.nextSibling)
659                                        val += sib.nodeValue;
660
661                                val = p.innerHTML.replace(/<\/?\w+[^>]*>/gi, '').replace(/&nbsp;/g, '\u00a0');
662
663                                // Detect unordered lists look for bullets
664                                if (/^(__MCE_ITEM__)+[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*\u00a0*/.test(val))
665                                        type = 'ul';
666
667                                // Detect ordered lists 1., a. or ixv.
668                                if (/^__MCE_ITEM__\s*\w+\.\s*\u00a0+/.test(val))
669                                        type = 'ol';
670
671                                // Check if node value matches the list pattern: o&nbsp;&nbsp;
672                                if (type) {
673                                        margin = parseFloat(p.style.marginLeft || 0);
674
675                                        if (margin > lastMargin)
676                                                levels.push(margin);
677
678                                        if (!listElm || type != lastType) {
679                                                listElm = dom.create(type);
680                                                dom.insertAfter(listElm, p);
681                                        } else {
682                                                // Nested list element
683                                                if (margin > lastMargin) {
684                                                        listElm = li.appendChild(dom.create(type));
685                                                } else if (margin < lastMargin) {
686                                                        // Find parent level based on margin value
687                                                        idx = tinymce.inArray(levels, margin);
688                                                        parents = dom.getParents(listElm.parentNode, type);
689                                                        listElm = parents[parents.length - 1 - idx] || listElm;
690                                                }
691                                        }
692
693                                        // Remove middot or number spans if they exists
694                                        each(dom.select('span', p), function(span) {
695                                                var html = span.innerHTML.replace(/<\/?\w+[^>]*>/gi, '');
696
697                                                // Remove span with the middot or the number
698                                                if (type == 'ul' && /^__MCE_ITEM__[\u2022\u00b7\u00a7\u00d8o\u25CF]/.test(html))
699                                                        dom.remove(span);
700                                                else if (/^__MCE_ITEM__[\s\S]*\w+\.(&nbsp;|\u00a0)*\s*/.test(html))
701                                                        dom.remove(span);
702                                        });
703
704                                        html = p.innerHTML;
705
706                                        // Remove middot/list items
707                                        if (type == 'ul')
708                                                html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*(&nbsp;|\u00a0)+\s*/, '');
709                                        else
710                                                html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^\s*\w+\.(&nbsp;|\u00a0)+\s*/, '');
711
712                                        // Create li and add paragraph data into the new li
713                                        li = listElm.appendChild(dom.create('li', 0, html));
714                                        dom.remove(p);
715
716                                        lastMargin = margin;
717                                        lastType = type;
718                                } else
719                                        listElm = lastMargin = 0; // End list element
720                        });
721
722                        // Remove any left over makers
723                        html = o.node.innerHTML;
724                        if (html.indexOf('__MCE_ITEM__') != -1)
725                                o.node.innerHTML = html.replace(/__MCE_ITEM__/g, '');
726                },
727
728                /**
729                 * Inserts the specified contents at the caret position.
730                 */
731                _insert : function(h, skip_undo) {
732                        var ed = this.editor, r = ed.selection.getRng();
733
734                        // First delete the contents seems to work better on WebKit when the selection spans multiple list items or multiple table cells.
735                        if (!ed.selection.isCollapsed() && r.startContainer != r.endContainer)
736                                ed.getDoc().execCommand('Delete', false, null);
737
738                        ed.execCommand('mceInsertContent', false, h, {skip_undo : skip_undo});
739                },
740
741                /**
742                 * Instead of the old plain text method which tried to re-create a paste operation, the
743                 * new approach adds a plain text mode toggle switch that changes the behavior of paste.
744                 * This function is passed the same input that the regular paste plugin produces.
745                 * It performs additional scrubbing and produces (and inserts) the plain text.
746                 * This approach leverages all of the great existing functionality in the paste
747                 * plugin, and requires minimal changes to add the new functionality.
748                 * Speednet - June 2009
749                 */
750                _insertPlainText : function(ed, dom, h) {
751                        var i, len, pos, rpos, node, breakElms, before, after,
752                                w = ed.getWin(),
753                                d = ed.getDoc(),
754                                sel = ed.selection,
755                                is = tinymce.is,
756                                inArray = tinymce.inArray,
757                                linebr = getParam(ed, "paste_text_linebreaktype"),
758                                rl = getParam(ed, "paste_text_replacements");
759
760                        function process(items) {
761                                each(items, function(v) {
762                                        if (v.constructor == RegExp)
763                                                h = h.replace(v, "");
764                                        else
765                                                h = h.replace(v[0], v[1]);
766                                });
767                        };
768
769                        if ((typeof(h) === "string") && (h.length > 0)) {
770                                // If HTML content with line-breaking tags, then remove all cr/lf chars because only tags will break a line
771                                if (/<(?:p|br|h[1-6]|ul|ol|dl|table|t[rdh]|div|blockquote|fieldset|pre|address|center)[^>]*>/i.test(h)) {
772                                        process([
773                                                /[\n\r]+/g
774                                        ]);
775                                } else {
776                                        // Otherwise just get rid of carriage returns (only need linefeeds)
777                                        process([
778                                                /\r+/g
779                                        ]);
780                                }
781
782                                process([
783                                        [/<\/(?:p|h[1-6]|ul|ol|dl|table|div|blockquote|fieldset|pre|address|center)>/gi, "\n\n"],               // Block tags get a blank line after them
784                                        [/<br[^>]*>|<\/tr>/gi, "\n"],                           // Single linebreak for <br /> tags and table rows
785                                        [/<\/t[dh]>\s*<t[dh][^>]*>/gi, "\t"],           // Table cells get tabs betweem them
786                                        /<[a-z!\/?][^>]*>/gi,                                           // Delete all remaining tags
787                                        [/&nbsp;/gi, " "],                                                      // Convert non-break spaces to regular spaces (remember, *plain text*)
788                                        [/(?:(?!\n)\s)*(\n+)(?:(?!\n)\s)*/gi, "$1"],    // Cool little RegExp deletes whitespace around linebreak chars.
789                                        [/\n{3,}/g, "\n\n"],                                                    // Max. 2 consecutive linebreaks
790                                        /^\s+|\s+$/g                                                                    // Trim the front & back
791                                ]);
792
793                                h = dom.decode(tinymce.html.Entities.encodeRaw(h));
794
795                                // Delete any highlighted text before pasting
796                                if (!sel.isCollapsed()) {
797                                        d.execCommand("Delete", false, null);
798                                }
799
800                                // Perform default or custom replacements
801                                if (is(rl, "array") || (is(rl, "array"))) {
802                                        process(rl);
803                                }
804                                else if (is(rl, "string")) {
805                                        process(new RegExp(rl, "gi"));
806                                }
807
808                                // Treat paragraphs as specified in the config
809                                if (linebr == "none") {
810                                        process([
811                                                [/\n+/g, " "]
812                                        ]);
813                                }
814                                else if (linebr == "br") {
815                                        process([
816                                                [/\n/g, "<br />"]
817                                        ]);
818                                }
819                                else {
820                                        process([
821                                                /^\s+|\s+$/g,
822                                                [/\n\n/g, "</p><p>"],
823                                                [/\n/g, "<br />"]
824                                        ]);
825                                }
826
827                                // This next piece of code handles the situation where we're pasting more than one paragraph of plain
828                                // text, and we are pasting the content into the middle of a block node in the editor.  The block
829                                // node gets split at the selection point into "Para A" and "Para B" (for the purposes of explaining).
830                                // The first paragraph of the pasted text is appended to "Para A", and the last paragraph of the
831                                // pasted text is prepended to "Para B".  Any other paragraphs of pasted text are placed between
832                                // "Para A" and "Para B".  This code solves a host of problems with the original plain text plugin and
833                                // now handles styles correctly.  (Pasting plain text into a styled paragraph is supposed to make the
834                                // plain text take the same style as the existing paragraph.)
835                                if ((pos = h.indexOf("</p><p>")) != -1) {
836                                        rpos = h.lastIndexOf("</p><p>");
837                                        node = sel.getNode();
838                                        breakElms = [];         // Get list of elements to break
839
840                                        do {
841                                                if (node.nodeType == 1) {
842                                                        // Don't break tables and break at body
843                                                        if (node.nodeName == "TD" || node.nodeName == "BODY") {
844                                                                break;
845                                                        }
846
847                                                        breakElms[breakElms.length] = node;
848                                                }
849                                        } while (node = node.parentNode);
850
851                                        // Are we in the middle of a block node?
852                                        if (breakElms.length > 0) {
853                                                before = h.substring(0, pos);
854                                                after = "";
855
856                                                for (i=0, len=breakElms.length; i<len; i++) {
857                                                        before += "</" + breakElms[i].nodeName.toLowerCase() + ">";
858                                                        after += "<" + breakElms[breakElms.length-i-1].nodeName.toLowerCase() + ">";
859                                                }
860
861                                                if (pos == rpos) {
862                                                        h = before + after + h.substring(pos+7);
863                                                }
864                                                else {
865                                                        h = before + h.substring(pos+4, rpos+4) + after + h.substring(rpos+7);
866                                                }
867                                        }
868                                }
869
870                                // Insert content at the caret, plus add a marker for repositioning the caret
871                                ed.execCommand("mceInsertRawHTML", false, h + '<span id="_plain_text_marker">&nbsp;</span>');
872
873                                // Reposition the caret to the marker, which was placed immediately after the inserted content.
874                                // Needs to be done asynchronously (in window.setTimeout) or else it doesn't work in all browsers.
875                                // The second part of the code scrolls the content up if the caret is positioned off-screen.
876                                // This is only necessary for WebKit browsers, but it doesn't hurt to use for all.
877                                window.setTimeout(function() {
878                                        var marker = dom.get('_plain_text_marker'),
879                                                elm, vp, y, elmHeight;
880
881                                        sel.select(marker, false);
882                                        d.execCommand("Delete", false, null);
883                                        marker = null;
884
885                                        // Get element, position and height
886                                        elm = sel.getStart();
887                                        vp = dom.getViewPort(w);
888                                        y = dom.getPos(elm).y;
889                                        elmHeight = elm.clientHeight;
890
891                                        // Is element within viewport if not then scroll it into view
892                                        if ((y < vp.y) || (y + elmHeight > vp.y + vp.h)) {
893                                                d.body.scrollTop = y < vp.y ? y : y - vp.h + 25;
894                                        }
895                                }, 0);
896                        }
897                },
898
899                /**
900                 * This method will open the old style paste dialogs. Some users might want the old behavior but still use the new cleanup engine.
901                 */
902                _legacySupport : function() {
903                        var t = this, ed = t.editor;
904
905                        // Register command(s) for backwards compatibility
906                        ed.addCommand("mcePasteWord", function() {
907                                ed.windowManager.open({
908                                        file: t.url + "/pasteword.htm",
909                                        width: parseInt(getParam(ed, "paste_dialog_width")),
910                                        height: parseInt(getParam(ed, "paste_dialog_height")),
911                                        inline: 1
912                                });
913                        });
914
915                        if (getParam(ed, "paste_text_use_dialog")) {
916                                ed.addCommand("mcePasteText", function() {
917                                        ed.windowManager.open({
918                                                file : t.url + "/pastetext.htm",
919                                                width: parseInt(getParam(ed, "paste_dialog_width")),
920                                                height: parseInt(getParam(ed, "paste_dialog_height")),
921                                                inline : 1
922                                        });
923                                });
924                        }
925
926                        // Register button for backwards compatibility
927                        ed.addButton("pasteword", {title : "paste.paste_word_desc", cmd : "mcePasteWord"});
928                }
929        });
930
931        // Register plugin
932        tinymce.PluginManager.add("paste", tinymce.plugins.PastePlugin);
933})();
Note: See TracBrowser for help on using the repository browser.