UNPKG

xmlapi

Version:

a common interface for Node and browser native XML APIs

113 lines (112 loc) 3.33 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const abstract_node_1 = require("./abstract_node"); const wu = require('wu'); class AbstractElement extends abstract_node_1.AbstractNode { name() { let ns = this.namespaceUri(); if (ns) { return '{' + ns + '}' + this.localName(); } return this.localName(); } /* * children */ children() { if (!this.firstChild()) { return wu([]); } return wu.chain([this.firstChild()], this.firstChild().nextSiblings()); } elementChildren() { return this.children().filter(x => x.isElement()); } firstElementChild() { return this.elementChildren().next().value || null; } elementChild(index) { return this.elementChildren().drop(index).next().value || null; // todo: wait for method in wu } lastElementChild() { return this.rchildren().filter(x => x.isElement()).next().value || null; } rchildren() { if (!this.lastChild()) { return wu([]); } return wu.chain([this.lastChild()], this.lastChild().previousSiblings()); } countChildren() { return [...this.children()].length; // todo: wait for .count() in wu } countElementChildren() { return [...this.children().filter(x => x.isElement())].length; // todo: wait for .count() in wu } clear() { for (let child = this.firstChild(); child; child = this.firstChild()) { child.remove(); } } /* * manipulation */ prependChild(child) { if (this.firstChild()) { this.firstChild().insertBefore(child); } else { this.appendChild(child); // see http://stackoverflow.com/a/13723325/5271870 } return child; } // attributeDefault(name: string, defaultValue = '') { // let ret = this.attribute(name) // if (ret === undefined) { // return defaultValue // } // return ret // } attributeUp(name) { for (let cursor = this /* wut?? */; cursor; cursor = cursor.parent()) { let value = cursor.attribute(name); if (value !== null) { return value; } } } setAttributes(keyvalue) { for (let key of Object.keys(keyvalue)) { this.setAttribute(key, keyvalue[key]); } return this; } attributesObj() { let ret = {}; this.attributes().forEach(x => ret[x.nameLocal().toString()] = x.value().toString()); // this.attributes().forEach(x => console.log(x.value())) return ret; } /* * other */ lang() { return wu.chain([this], this.ancestors()) .map(x => x.attribute('lang')) .find(x => x !== null); } unwrap() { while (this.firstChild()) { this.insertBefore(this.firstChild()); // todo: test webapi without remove() } return this.remove(); } rewrap(replacement) { while (this.firstChild()) { replacement.appendChild(this.firstChild()); } this.replace(replacement); return replacement; } } exports.AbstractElement = AbstractElement;