r104666 MediaWiki - Code Review archive

Repository:MediaWiki
Revision:r104665‎ | r104666 | r104667 >
Date:12:28, 30 November 2011
Author:gwicke
Status:deferred
Tags:
Comment:
Simplify DOM paragraph wrapping postprocessor
Modified paths:
  • /trunk/extensions/VisualEditor/modules/parser/mediawiki.DOMPostProcessor.js (modified) (history)

Diff [purge]

Index: trunk/extensions/VisualEditor/modules/parser/mediawiki.DOMPostProcessor.js
@@ -24,55 +24,42 @@
2525 }
2626 };
2727
 28+// Wrap all top-level inline elements in paragraphs. This should also be
 29+// applied inside block-level elements, but in that case the first paragraph
 30+// usually remains plain inline.
2831 var process_inlines_in_p = function ( document ) {
29 - // document.body does not always work in jsdom
 32+ // document.body does not always work in jsdom, so work around it.
3033 var body = document.getElementsByTagName('body')[0],
31 - children = body.cloneNode(false),
 34+ newP = document.createElement('p'),
3235 cnodes = body.childNodes,
33 - inlineStack = [];
 36+ haveInlines = false,
 37+ deleted = 0;
3438
35 - function wrapInlines (inlines) {
36 - var newp = document.createElement('p');
37 - for(var i = 0, length = inlines.length; i < length; i++) {
38 - newp.appendChild(inlines[i]);
39 - }
40 - body.appendChild(newp);
41 - inlineStack = [];
42 - }
43 - var i,
44 - length = cnodes.length;
45 - // Clear body
46 - for(i = 0; i < length; i++) {
47 - var cnode = body.firstChild;
48 - children.appendChild(cnode);
49 - }
50 -
5139 function isElementContentWhitespace ( e ) {
5240 return (e.data.match(/^[ \r\n\t]*$/) !== null);
5341 }
5442
55 - // Now re-append all block elements and inline elements wrapped in
56 - // paragraphs.
57 - for(i = 0; i < length; i++) {
58 - var child = children.firstChild,
 43+ for(var i = 0, length = cnodes.length; i < length; i++) {
 44+ var child = cnodes[i - deleted],
5945 ctype = child.nodeType;
6046 //console.log(child + ctype);
61 - if ((ctype === 3 && (inlineStack.length || !isElementContentWhitespace(child))) ||
62 - (ctype !== 3 && // text
63 - ctype !== 8 && // comment
64 - !isBlock(child.nodeName))) {
 47+ if (ctype === 3 && (haveInlines || !isElementContentWhitespace(child))) ||
 48+ (ctype !== 3 && // text
 49+ ctype !== 8 && // comment
 50+ !isBlock(child.nodeName))) {
6551 // text node
66 - inlineStack.push(child);
67 - } else if (inlineStack.length) {
68 - wrapInlines(inlineStack);
69 - body.appendChild(child);
70 - } else {
71 - body.appendChild(child);
72 - }
 52+ newP.appendChild(child);
 53+ haveInlines = true;
 54+ deleted++;
 55+ } else if (haveInlines) {
 56+ body.insertBefore(newP, child);
 57+ newP = document.createElement('p');
 58+ haveInlines = false;
 59+ }
7360 }
7461
75 - if (inlineStack.length) {
76 - wrapInlines(inlineStack);
 62+ if (haveInlines) {
 63+ body.appendChild(newP);
7764 }
7865 };
7966

Status & tagging log