From: Aleksander Ɓukasz Date: Mon, 25 Nov 2013 14:37:40 +0000 (+0100) Subject: smartxml: DocumentNode.getPath X-Git-Url: https://git.mdrn.pl/fnpeditor.git/commitdiff_plain/72da90cac0feafb35cac9292105e24f2b5094b45 smartxml: DocumentNode.getPath --- diff --git a/src/smartxml/smartxml.js b/src/smartxml/smartxml.js index a583848..0e05293 100644 --- a/src/smartxml/smartxml.js +++ b/src/smartxml/smartxml.js @@ -40,6 +40,26 @@ $.extend(DocumentNode.prototype, { return this.document.createDocumentNode(this._$.clone(true, true)[0]); }, + getPath: function(ancestor) { + var nodePath = [this].concat(this.parents()), + toret, idx; + ancestor = ancestor || this.document.root; + + nodePath.some(function(node, i) { + if(node.sameNode(ancestor)) { + idx = i; + return true; + } + }); + + if(idx !== 'undefined') { + nodePath = nodePath.slice(0, idx); + } + toret = nodePath.map(function(node) {return node.getIndex(); }); + toret.reverse(); + return toret; + }, + isRoot: function() { return this.document.root.sameNode(this); }, diff --git a/src/smartxml/smartxml.test.js b/src/smartxml/smartxml.test.js index e4dd1a7..180fa87 100644 --- a/src/smartxml/smartxml.test.js +++ b/src/smartxml/smartxml.test.js @@ -75,6 +75,24 @@ describe('smartxml', function() { expect(node.nativeNode.isEqualNode(clone.nativeNode)).to.equal(true, 'clone is identical as its originator' + suffix); }); }); + + it('knows its path in the document tree', function() { + var doc = getDocumentFromXML('text'), + root = doc.root, + a = root.contents()[0], + b = a.contents()[0], + text = b.contents()[1]; + + expect(root.getPath()).to.eql([], 'path of the root element is empty'); + expect(a.getPath()).to.eql([0]); + expect(b.getPath()).to.eql([0, 0]); + expect(text.getPath()).to.eql([0,0,1]); + + /* Paths relative to a given ancestor */ + expect(text.getPath(root)).to.eql([0,0,1]); + expect(text.getPath(a)).to.eql([0,1]); + expect(text.getPath(b)).to.eql([1]); + }); }); describe('Basic ElementNode properties', function() {