From: Aleksander Ɓukasz Date: Tue, 19 Nov 2013 14:23:40 +0000 (+0100) Subject: smartxml: fix detaching element node with adjacent text nodes X-Git-Url: https://git.mdrn.pl/fnpeditor.git/commitdiff_plain/fadd66e0cc7a22d06a1d8f4ab08871fec8dafcdf smartxml: fix detaching element node with adjacent text nodes --- diff --git a/src/smartxml/smartxml.js b/src/smartxml/smartxml.js index c176f08..40f3aad 100644 --- a/src/smartxml/smartxml.js +++ b/src/smartxml/smartxml.js @@ -68,6 +68,20 @@ $.extend(DocumentNode.prototype, { return parents; }, + prev: function() { + var myIdx = this.getIndex(); + return myIdx > 0 ? this.parent().contents()[myIdx-1] : null; + }, + + next: function() { + if(this.isRoot()) { + return null; + } + var myIdx = this.getIndex(), + parentContents = this.parent().contents(); + return myIdx < parentContents.length - 1 ? parentContents[myIdx+1] : null; + }, + after: INSERTION(function(nativeNode) { return this._$.after(nativeNode); }), @@ -118,6 +132,18 @@ ElementNode.prototype = Object.create(DocumentNode.prototype); $.extend(ElementNode.prototype, { nodeType: Node.ELEMENT_NODE, + detach: function() { + var prev = this.prev(), + next = this.next(); + if(parent) { + if(prev && prev.nodeType === Node.TEXT_NODE && next && next.nodeType === Node.TEXT_NODE) { + prev.appendText(next.getText()); + next.detach(); + } + } + return DocumentNode.prototype.detach.call(this); + }, + setData: function(key, value) { if(value !== undefined) { this._$.data(key, value); diff --git a/src/smartxml/smartxml.test.js b/src/smartxml/smartxml.test.js index 09fdfeb..67ada78 100644 --- a/src/smartxml/smartxml.test.js +++ b/src/smartxml/smartxml.test.js @@ -262,6 +262,17 @@ describe('smartxml', function() { describe('Manipulations', function() { + it('merges adjacent text nodes resulting from detaching an element node in between', function() { + var doc = getDocumentFromXML('
Alice hasa cat
'), + span = doc.root.contents()[1]; + + span.detach(); + + var rootContents = doc.root.contents(); + expect(rootContents).to.have.length(1, 'one child left'); + expect(rootContents[0].getText()).to.equal('Alice a cat'); + }); + it('appends element node to another element node', function() { var node1 = elementNodeFromParams({tag: 'div'}), node2 = elementNodeFromParams({tag: 'a'}),