- /* returns Node */
- removeNamedItem: function removeNamedItem(key) {
- var attr = this.getNamedItem(key);
-
- _removeNamedNode(this._ownerElement, this, attr);
-
- return attr;
- },
- // raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
- //for level2
- removeNamedItemNS: function removeNamedItemNS(namespaceURI, localName) {
- var attr = this.getNamedItemNS(namespaceURI, localName);
-
- _removeNamedNode(this._ownerElement, this, attr);
-
- return attr;
- },
- getNamedItemNS: function getNamedItemNS(namespaceURI, localName) {
- var i = this.length;
-
- while (i--) {
- var node = this[i];
-
- if (node.localName == localName && node.namespaceURI == namespaceURI) {
- return node;
- }
- }
-
- return null;
- }
- };
- /**
- * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490
- */
-
- function DOMImplementation(
- /* Object */
- features) {
- this._features = {};
-
- if (features) {
- for (var feature in features) {
- this._features = features[feature];
- }
- }
- }
- DOMImplementation.prototype = {
- hasFeature: function hasFeature(
- /* string */
- feature,
- /* string */
- version) {
- var versions = this._features[feature.toLowerCase()];
-
- if (versions && (!version || version in versions)) {
- return true;
- } else {
- return false;
- }
- },
- // Introduced in DOM Level 2:
- createDocument: function createDocument(namespaceURI, qualifiedName, doctype) {
- // raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR,WRONG_DOCUMENT_ERR
- var doc = new Document();
- doc.implementation = this;
- doc.childNodes = new NodeList();
- doc.doctype = doctype;
-
- if (doctype) {
- doc.appendChild(doctype);
- }
-
- if (qualifiedName) {
- var root = doc.createElementNS(namespaceURI, qualifiedName);
- doc.appendChild(root);
- }
-
- return doc;
- },
- // Introduced in DOM Level 2:
- createDocumentType: function createDocumentType(qualifiedName, publicId, systemId) {
- // raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR
- var node = new DocumentType();
- node.name = qualifiedName;
- node.nodeName = qualifiedName;
- node.publicId = publicId;
- node.systemId = systemId; // Introduced in DOM Level 2:
- //readonly attribute DOMString internalSubset;
- //TODO:..
- // readonly attribute NamedNodeMap entities;
- // readonly attribute NamedNodeMap notations;
-
- return node;
- }
- };
- /**
- * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247
- */
-
- function Node() {}
- Node.prototype = {
- firstChild: null,
- lastChild: null,
- previousSibling: null,
- nextSibling: null,
- attributes: null,
- parentNode: null,
- childNodes: null,
- ownerDocument: null,
- nodeValue: null,
- namespaceURI: null,
- prefix: null,
- localName: null,
- // Modified in DOM Level 2:
- insertBefore: function insertBefore(newChild, refChild) {
- //raises
- return _insertBefore(this, newChild, refChild);
- },
- replaceChild: function replaceChild(newChild, oldChild) {
- //raises
- this.insertBefore(newChild, oldChild);
-
- if (oldChild) {
- this.removeChild(oldChild);
- }
- },
- removeChild: function removeChild(oldChild) {
- return _removeChild(this, oldChild);
- },
- appendChild: function appendChild(newChild) {
- return this.insertBefore(newChild, null);
- },
- hasChildNodes: function hasChildNodes() {
- return this.firstChild != null;
- },
- cloneNode: function cloneNode(deep) {
- return _cloneNode(this.ownerDocument || this, this, deep);
- },
- // Modified in DOM Level 2:
- normalize: function normalize() {
- var child = this.firstChild;
-
- while (child) {
- var next = child.nextSibling;
-
- if (next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE) {
- this.removeChild(next);
- child.appendData(next.data);
- } else {
- child.normalize();
- child = next;
- }
- }
- },
- // Introduced in DOM Level 2:
- isSupported: function isSupported(feature, version) {
- return this.ownerDocument.implementation.hasFeature(feature, version);
- },
- // Introduced in DOM Level 2:
- hasAttributes: function hasAttributes() {
- return this.attributes.length > 0;
- },
- lookupPrefix: function lookupPrefix(namespaceURI) {
- var el = this;
-
- while (el) {
- var map = el._nsMap; //console.dir(map)
-
- if (map) {
- for (var n in map) {
- if (map[n] == namespaceURI) {
- return n;
- }
- }
- }
-
- el = el.nodeType == ATTRIBUTE_NODE ? el.ownerDocument : el.parentNode;
- }
-
- return null;
- },
- // Introduced in DOM Level 3:
- lookupNamespaceURI: function lookupNamespaceURI(prefix) {
- var el = this;
-
- while (el) {
- var map = el._nsMap; //console.dir(map)
-
- if (map) {
- if (prefix in map) {
- return map[prefix];
- }
- }
-
- el = el.nodeType == ATTRIBUTE_NODE ? el.ownerDocument : el.parentNode;
- }
-
- return null;
- },
- // Introduced in DOM Level 3:
- isDefaultNamespace: function isDefaultNamespace(namespaceURI) {
- var prefix = this.lookupPrefix(namespaceURI);
- return prefix == null;
- }
- };
-
- function _xmlEncoder(c) {
- return c == '<' && '<' || c == '>' && '>' || c == '&' && '&' || c == '"' && '"' || '&#' + c.charCodeAt() + ';';
- }
-
- copy(NodeType, Node);
- copy(NodeType, Node.prototype);
- /**
- * @param callback return true for continue,false for break
- * @return boolean true: break visit;
- */
-
- function _visitNode(node, callback) {
- if (callback(node)) {
- return true;
- }
-
- if (node = node.firstChild) {
- do {
- if (_visitNode(node, callback)) {
- return true;
- }
- } while (node = node.nextSibling);
- }
- }
-
- function Document() {}
-
- function _onAddAttribute(doc, el, newAttr) {
- doc && doc._inc++;
- var ns = newAttr.namespaceURI;
-
- if (ns == 'http://www.w3.org/2000/xmlns/') {
- //update namespace
- el._nsMap[newAttr.prefix ? newAttr.localName : ''] = newAttr.value;
- }
- }
-
- function _onRemoveAttribute(doc, el, newAttr, remove) {
- doc && doc._inc++;
- var ns = newAttr.namespaceURI;
-
- if (ns == 'http://www.w3.org/2000/xmlns/') {
- //update namespace
- delete el._nsMap[newAttr.prefix ? newAttr.localName : ''];
- }
- }
-
- function _onUpdateChild(doc, el, newChild) {
- if (doc && doc._inc) {
- doc._inc++; //update childNodes
-
- var cs = el.childNodes;
-
- if (newChild) {
- cs[cs.length++] = newChild;
- } else {
- //console.log(1)
- var child = el.firstChild;
- var i = 0;
-
- while (child) {
- cs[i++] = child;
- child = child.nextSibling;
- }
-
- cs.length = i;
- }
- }
- }
- /**
- * attributes;
- * children;
- *
- * writeable properties:
- * nodeValue,Attr:value,CharacterData:data
- * prefix
- */
-
-
- function _removeChild(parentNode, child) {
- var previous = child.previousSibling;
- var next = child.nextSibling;
-
- if (previous) {
- previous.nextSibling = next;
- } else {
- parentNode.firstChild = next;
- }
-
- if (next) {
- next.previousSibling = previous;
- } else {
- parentNode.lastChild = previous;
- }
-
- _onUpdateChild(parentNode.ownerDocument, parentNode);
-
- return child;
- }
- /**
- * preformance key(refChild == null)
- */
-
-
- function _insertBefore(parentNode, newChild, nextChild) {
- var cp = newChild.parentNode;
-
- if (cp) {
- cp.removeChild(newChild); //remove and update
- }
-
- if (newChild.nodeType === DOCUMENT_FRAGMENT_NODE) {
- var newFirst = newChild.firstChild;
-
- if (newFirst == null) {
- return newChild;
- }
-
- var newLast = newChild.lastChild;
- } else {
- newFirst = newLast = newChild;
- }
-
- var pre = nextChild ? nextChild.previousSibling : parentNode.lastChild;
- newFirst.previousSibling = pre;
- newLast.nextSibling = nextChild;
-
- if (pre) {
- pre.nextSibling = newFirst;
- } else {
- parentNode.firstChild = newFirst;
- }
-
- if (nextChild == null) {
- parentNode.lastChild = newLast;
- } else {
- nextChild.previousSibling = newLast;
- }
-
- do {
- newFirst.parentNode = parentNode;
- } while (newFirst !== newLast && (newFirst = newFirst.nextSibling));
-
- _onUpdateChild(parentNode.ownerDocument || parentNode, parentNode); //console.log(parentNode.lastChild.nextSibling == null)
-
-
- if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
- newChild.firstChild = newChild.lastChild = null;
- }
-
- return newChild;
- }
-
- function _appendSingleChild(parentNode, newChild) {
- var cp = newChild.parentNode;
-
- if (cp) {
- var pre = parentNode.lastChild;
- cp.removeChild(newChild); //remove and update
-
- var pre = parentNode.lastChild;
- }
-
- var pre = parentNode.lastChild;
- newChild.parentNode = parentNode;
- newChild.previousSibling = pre;
- newChild.nextSibling = null;
-
- if (pre) {
- pre.nextSibling = newChild;
- } else {
- parentNode.firstChild = newChild;
- }
-
- parentNode.lastChild = newChild;
-
- _onUpdateChild(parentNode.ownerDocument, parentNode, newChild);
-
- return newChild; //console.log("__aa",parentNode.lastChild.nextSibling == null)
- }
-
- Document.prototype = {
- //implementation : null,
- nodeName: '#document',
- nodeType: DOCUMENT_NODE,
- doctype: null,
- documentElement: null,
- _inc: 1,
- insertBefore: function insertBefore(newChild, refChild) {
- //raises
- if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
- var child = newChild.firstChild;
-
- while (child) {
- var next = child.nextSibling;
- this.insertBefore(child, refChild);
- child = next;
- }
-
- return newChild;
- }
-
- if (this.documentElement == null && newChild.nodeType == ELEMENT_NODE) {
- this.documentElement = newChild;
- }
-
- return _insertBefore(this, newChild, refChild), newChild.ownerDocument = this, newChild;
- },
- removeChild: function removeChild(oldChild) {
- if (this.documentElement == oldChild) {
- this.documentElement = null;
- }
-
- return _removeChild(this, oldChild);
- },
- // Introduced in DOM Level 2:
- importNode: function importNode(importedNode, deep) {
- return _importNode(this, importedNode, deep);
- },
- // Introduced in DOM Level 2:
- getElementById: function getElementById(id) {
- var rtv = null;
-
- _visitNode(this.documentElement, function (node) {
- if (node.nodeType == ELEMENT_NODE) {
- if (node.getAttribute('id') == id) {
- rtv = node;
- return true;
- }
- }
- });
-
- return rtv;
- },
- //document factory method:
- createElement: function createElement(tagName) {
- var node = new Element();
- node.ownerDocument = this;
- node.nodeName = tagName;
- node.tagName = tagName;
- node.childNodes = new NodeList();
- var attrs = node.attributes = new NamedNodeMap();
- attrs._ownerElement = node;
- return node;
- },
- createDocumentFragment: function createDocumentFragment() {
- var node = new DocumentFragment();
- node.ownerDocument = this;
- node.childNodes = new NodeList();
- return node;
- },
- createTextNode: function createTextNode(data) {
- var node = new Text();
- node.ownerDocument = this;
- node.appendData(data);
- return node;
- },
- createComment: function createComment(data) {
- var node = new Comment();
- node.ownerDocument = this;
- node.appendData(data);
- return node;
- },
- createCDATASection: function createCDATASection(data) {
- var node = new CDATASection();
- node.ownerDocument = this;
- node.appendData(data);
- return node;
- },
- createProcessingInstruction: function createProcessingInstruction(target, data) {
- var node = new ProcessingInstruction();
- node.ownerDocument = this;
- node.tagName = node.target = target;
- node.nodeValue = node.data = data;
- return node;
- },
- createAttribute: function createAttribute(name) {
- var node = new Attr();
- node.ownerDocument = this;
- node.name = name;
- node.nodeName = name;
- node.localName = name;
- node.specified = true;
- return node;
- },
- createEntityReference: function createEntityReference(name) {
- var node = new EntityReference();
- node.ownerDocument = this;
- node.nodeName = name;
- return node;
- },
- // Introduced in DOM Level 2:
- createElementNS: function createElementNS(namespaceURI, qualifiedName) {
- var node = new Element();
- var pl = qualifiedName.split(':');
- var attrs = node.attributes = new NamedNodeMap();
- node.childNodes = new NodeList();
- node.ownerDocument = this;
- node.nodeName = qualifiedName;
- node.tagName = qualifiedName;
- node.namespaceURI = namespaceURI;
-
- if (pl.length == 2) {
- node.prefix = pl[0];
- node.localName = pl[1];
- } else {
- //el.prefix = null;
- node.localName = qualifiedName;
- }
-
- attrs._ownerElement = node;
- return node;
- },
- // Introduced in DOM Level 2:
- createAttributeNS: function createAttributeNS(namespaceURI, qualifiedName) {
- var node = new Attr();
- var pl = qualifiedName.split(':');
- node.ownerDocument = this;
- node.nodeName = qualifiedName;
- node.name = qualifiedName;
- node.namespaceURI = namespaceURI;
- node.specified = true;
-
- if (pl.length == 2) {
- node.prefix = pl[0];
- node.localName = pl[1];
- } else {
- //el.prefix = null;
- node.localName = qualifiedName;
- }
-
- return node;
- }
- };
-
- _extends(Document, Node);
-
- function Element() {
- this._nsMap = {};
- }
- Element.prototype = {
- nodeType: ELEMENT_NODE,
- hasAttribute: function hasAttribute(name) {
- return this.getAttributeNode(name) != null;
- },
- getAttribute: function getAttribute(name) {
- var attr = this.getAttributeNode(name);
- return attr && attr.value || '';
- },
- getAttributeNode: function getAttributeNode(name) {
- return this.attributes.getNamedItem(name);
- },
- setAttribute: function setAttribute(name, value) {
- var attr = this.ownerDocument.createAttribute(name);
- attr.value = attr.nodeValue = "" + value;
- this.setAttributeNode(attr);
- },
- removeAttribute: function removeAttribute(name) {
- var attr = this.getAttributeNode(name);
- attr && this.removeAttributeNode(attr);
- },
- //four real opeartion method
- appendChild: function appendChild(newChild) {
- if (newChild.nodeType === DOCUMENT_FRAGMENT_NODE) {
- return this.insertBefore(newChild, null);
- } else {
- return _appendSingleChild(this, newChild);
- }
- },
- setAttributeNode: function setAttributeNode(newAttr) {
- return this.attributes.setNamedItem(newAttr);
- },
- setAttributeNodeNS: function setAttributeNodeNS(newAttr) {
- return this.attributes.setNamedItemNS(newAttr);
- },
- removeAttributeNode: function removeAttributeNode(oldAttr) {
- //console.log(this == oldAttr.ownerElement)
- return this.attributes.removeNamedItem(oldAttr.nodeName);
- },
- //get real attribute name,and remove it by removeAttributeNode
- removeAttributeNS: function removeAttributeNS(namespaceURI, localName) {
- var old = this.getAttributeNodeNS(namespaceURI, localName);
- old && this.removeAttributeNode(old);
- },
- hasAttributeNS: function hasAttributeNS(namespaceURI, localName) {
- return this.getAttributeNodeNS(namespaceURI, localName) != null;
- },
- getAttributeNS: function getAttributeNS(namespaceURI, localName) {
- var attr = this.getAttributeNodeNS(namespaceURI, localName);
- return attr && attr.value || '';
- },
- setAttributeNS: function setAttributeNS(namespaceURI, qualifiedName, value) {
- var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
- attr.value = attr.nodeValue = "" + value;
- this.setAttributeNode(attr);
- },
- getAttributeNodeNS: function getAttributeNodeNS(namespaceURI, localName) {
- return this.attributes.getNamedItemNS(namespaceURI, localName);
- },
- getElementsByTagName: function getElementsByTagName(tagName) {
- return new LiveNodeList(this, function (base) {
- var ls = [];
-
- _visitNode(base, function (node) {
- if (node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)) {
- ls.push(node);
- }
- });
-
- return ls;
- });
- },
- getElementsByTagNameNS: function getElementsByTagNameNS(namespaceURI, localName) {
- return new LiveNodeList(this, function (base) {
- var ls = [];
-
- _visitNode(base, function (node) {
- if (node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)) {
- ls.push(node);
- }
- });
-
- return ls;
- });
- }
- };
- Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
- Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;
-
- _extends(Element, Node);
-
- function Attr() {}
- Attr.prototype.nodeType = ATTRIBUTE_NODE;
-
- _extends(Attr, Node);
-
- function CharacterData() {}
- CharacterData.prototype = {
- data: '',
- substringData: function substringData(offset, count) {
- return this.data.substring(offset, offset + count);
- },
- appendData: function appendData(text) {
- text = this.data + text;
- this.nodeValue = this.data = text;
- this.length = text.length;
- },
- insertData: function insertData(offset, text) {
- this.replaceData(offset, 0, text);
- },
- appendChild: function appendChild(newChild) {
- throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR]);
- },
- deleteData: function deleteData(offset, count) {
- this.replaceData(offset, count, "");
- },
- replaceData: function replaceData(offset, count, text) {
- var start = this.data.substring(0, offset);
- var end = this.data.substring(offset + count);
- text = start + text + end;
- this.nodeValue = this.data = text;
- this.length = text.length;
- }
- };
-
- _extends(CharacterData, Node);
-
- function Text() {}
- Text.prototype = {
- nodeName: "#text",
- nodeType: TEXT_NODE,
- splitText: function splitText(offset) {
- var text = this.data;
- var newText = text.substring(offset);
- text = text.substring(0, offset);
- this.data = this.nodeValue = text;
- this.length = text.length;
- var newNode = this.ownerDocument.createTextNode(newText);
-
- if (this.parentNode) {
- this.parentNode.insertBefore(newNode, this.nextSibling);
- }
-
- return newNode;
- }
- };
-
- _extends(Text, CharacterData);
-
- function Comment() {}
- Comment.prototype = {
- nodeName: "#comment",
- nodeType: COMMENT_NODE
- };
-
- _extends(Comment, CharacterData);
-
- function CDATASection() {}
- CDATASection.prototype = {
- nodeName: "#cdata-section",
- nodeType: CDATA_SECTION_NODE
- };
-
- _extends(CDATASection, CharacterData);
-
- function DocumentType() {}
- DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
-
- _extends(DocumentType, Node);
-
- function Notation() {}
- Notation.prototype.nodeType = NOTATION_NODE;
-
- _extends(Notation, Node);
-
- function Entity() {}
- Entity.prototype.nodeType = ENTITY_NODE;
-
- _extends(Entity, Node);
-
- function EntityReference() {}
- EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
-
- _extends(EntityReference, Node);
-
- function DocumentFragment() {}
- DocumentFragment.prototype.nodeName = "#document-fragment";
- DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;
-
- _extends(DocumentFragment, Node);
-
- function ProcessingInstruction() {}
-
- ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
-
- _extends(ProcessingInstruction, Node);
-
- function XMLSerializer$1() {}
-
- XMLSerializer$1.prototype.serializeToString = function (node, isHtml, nodeFilter) {
- return nodeSerializeToString.call(node, isHtml, nodeFilter);
- };
-
- Node.prototype.toString = nodeSerializeToString;
-
- function nodeSerializeToString(isHtml, nodeFilter) {
- var buf = [];
- var refNode = this.nodeType == 9 ? this.documentElement : this;
- var prefix = refNode.prefix;
- var uri = refNode.namespaceURI;
-
- if (uri && prefix == null) {
- //console.log(prefix)
- var prefix = refNode.lookupPrefix(uri);
-
- if (prefix == null) {
- //isHTML = true;
- var visibleNamespaces = [{
- namespace: uri,
- prefix: null
- } //{namespace:uri,prefix:''}
- ];
- }
- }
-
- serializeToString(this, buf, isHtml, nodeFilter, visibleNamespaces); //console.log('###',this.nodeType,uri,prefix,buf.join(''))
-
- return buf.join('');
- }
-
- function needNamespaceDefine(node, isHTML, visibleNamespaces) {
- var prefix = node.prefix || '';
- var uri = node.namespaceURI;
-
- if (!prefix && !uri) {
- return false;
- }
-
- if (prefix === "xml" && uri === "http://www.w3.org/XML/1998/namespace" || uri == 'http://www.w3.org/2000/xmlns/') {
- return false;
- }
-
- var i = visibleNamespaces.length; //console.log('@@@@',node.tagName,prefix,uri,visibleNamespaces)
-
- while (i--) {
- var ns = visibleNamespaces[i]; // get namespace prefix
- //console.log(node.nodeType,node.tagName,ns.prefix,prefix)
-
- if (ns.prefix == prefix) {
- return ns.namespace != uri;
- }
- } //console.log(isHTML,uri,prefix=='')
- //if(isHTML && prefix ==null && uri == 'http://www.w3.org/1999/xhtml'){
- // return false;
- //}
- //node.flag = '11111'
- //console.error(3,true,node.flag,node.prefix,node.namespaceURI)
-
-
- return true;
- }
-
- function serializeToString(node, buf, isHTML, nodeFilter, visibleNamespaces) {
- if (nodeFilter) {
- node = nodeFilter(node);
-
- if (node) {
- if (typeof node == 'string') {
- buf.push(node);
- return;
- }
- } else {
- return;
- } //buf.sort.apply(attrs, attributeSorter);
-
- }
-
- switch (node.nodeType) {
- case ELEMENT_NODE:
- if (!visibleNamespaces) visibleNamespaces = [];
- visibleNamespaces.length;
- var attrs = node.attributes;
- var len = attrs.length;
- var child = node.firstChild;
- var nodeName = node.tagName;
- isHTML = htmlns === node.namespaceURI || isHTML;
- buf.push('<', nodeName);
-
- for (var i = 0; i < len; i++) {
- // add namespaces for attributes
- var attr = attrs.item(i);
-
- if (attr.prefix == 'xmlns') {
- visibleNamespaces.push({
- prefix: attr.localName,
- namespace: attr.value
- });
- } else if (attr.nodeName == 'xmlns') {
- visibleNamespaces.push({
- prefix: '',
- namespace: attr.value
- });
- }
- }
-
- for (var i = 0; i < len; i++) {
- var attr = attrs.item(i);
-
- if (needNamespaceDefine(attr, isHTML, visibleNamespaces)) {
- var prefix = attr.prefix || '';
- var uri = attr.namespaceURI;
- var ns = prefix ? ' xmlns:' + prefix : " xmlns";
- buf.push(ns, '="', uri, '"');
- visibleNamespaces.push({
- prefix: prefix,
- namespace: uri
- });
- }
-
- serializeToString(attr, buf, isHTML, nodeFilter, visibleNamespaces);
- } // add namespace for current node
-
-
- if (needNamespaceDefine(node, isHTML, visibleNamespaces)) {
- var prefix = node.prefix || '';
- var uri = node.namespaceURI;
- var ns = prefix ? ' xmlns:' + prefix : " xmlns";
- buf.push(ns, '="', uri, '"');
- visibleNamespaces.push({
- prefix: prefix,
- namespace: uri
- });
- }
-
- if (child || isHTML && !/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)) {
- buf.push('>'); //if is cdata child node
-
- if (isHTML && /^script$/i.test(nodeName)) {
- while (child) {
- if (child.data) {
- buf.push(child.data);
- } else {
- serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces);
- }
-
- child = child.nextSibling;
- }
- } else {
- while (child) {
- serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces);
- child = child.nextSibling;
- }
- }
-
- buf.push('</', nodeName, '>');
- } else {
- buf.push('/>');
- } // remove added visible namespaces
- //visibleNamespaces.length = startVisibleNamespaces;
-
-
- return;
-
- case DOCUMENT_NODE:
- case DOCUMENT_FRAGMENT_NODE:
- var child = node.firstChild;
-
- while (child) {
- serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces);
- child = child.nextSibling;
- }
-
- return;
-
- case ATTRIBUTE_NODE:
- return buf.push(' ', node.name, '="', node.value.replace(/[<&"]/g, _xmlEncoder), '"');
-
- case TEXT_NODE:
- return buf.push(node.data.replace(/[<&]/g, _xmlEncoder));
-
- case CDATA_SECTION_NODE:
- return buf.push('<![CDATA[', node.data, ']]>');
-
- case COMMENT_NODE:
- return buf.push("<!--", node.data, "-->");
-
- case DOCUMENT_TYPE_NODE:
- var pubid = node.publicId;
- var sysid = node.systemId;
- buf.push('<!DOCTYPE ', node.name);
-
- if (pubid) {
- buf.push(' PUBLIC "', pubid);
-
- if (sysid && sysid != '.') {
- buf.push('" "', sysid);
- }
-
- buf.push('">');
- } else if (sysid && sysid != '.') {
- buf.push(' SYSTEM "', sysid, '">');
- } else {
- var sub = node.internalSubset;
-
- if (sub) {
- buf.push(" [", sub, "]");
- }
-
- buf.push(">");
- }
-
- return;
-
- case PROCESSING_INSTRUCTION_NODE:
- return buf.push("<?", node.target, " ", node.data, "?>");
-
- case ENTITY_REFERENCE_NODE:
- return buf.push('&', node.nodeName, ';');
- //case ENTITY_NODE:
- //case NOTATION_NODE:
-
- default:
- buf.push('??', node.nodeName);
- }
- }
-
- function _importNode(doc, node, deep) {
- var node2;
-
- switch (node.nodeType) {
- case ELEMENT_NODE:
- node2 = node.cloneNode(false);
- node2.ownerDocument = doc;
- //var attrs = node2.attributes;
- //var len = attrs.length;
- //for(var i=0;i<len;i++){
- //node2.setAttributeNodeNS(importNode(doc,attrs.item(i),deep));
- //}
-
- case DOCUMENT_FRAGMENT_NODE:
- break;
-
- case ATTRIBUTE_NODE:
- deep = true;
- break;
- //case ENTITY_REFERENCE_NODE:
- //case PROCESSING_INSTRUCTION_NODE:
- ////case TEXT_NODE:
- //case CDATA_SECTION_NODE:
- //case COMMENT_NODE:
- // deep = false;
- // break;
- //case DOCUMENT_NODE:
- //case DOCUMENT_TYPE_NODE:
- //cannot be imported.
- //case ENTITY_NODE:
- //case NOTATION_NODE:
- //can not hit in level3
- //default:throw e;
- }
-
- if (!node2) {
- node2 = node.cloneNode(false); //false
- }
-
- node2.ownerDocument = doc;
- node2.parentNode = null;
-
- if (deep) {
- var child = node.firstChild;
-
- while (child) {
- node2.appendChild(_importNode(doc, child, deep));
- child = child.nextSibling;
- }
- }
-
- return node2;
- } //
- //var _relationMap = {firstChild:1,lastChild:1,previousSibling:1,nextSibling:1,
- // attributes:1,childNodes:1,parentNode:1,documentElement:1,doctype,};
-
-
- function _cloneNode(doc, node, deep) {
- var node2 = new node.constructor();
-
- for (var n in node) {
- var v = node[n];
-
- if (_typeof(v) != 'object') {
- if (v != node2[n]) {
- node2[n] = v;
- }
- }
- }
-
- if (node.childNodes) {
- node2.childNodes = new NodeList();
- }
-
- node2.ownerDocument = doc;
-
- switch (node2.nodeType) {
- case ELEMENT_NODE:
- var attrs = node.attributes;
- var attrs2 = node2.attributes = new NamedNodeMap();
- var len = attrs.length;
- attrs2._ownerElement = node2;
-
- for (var i = 0; i < len; i++) {
- node2.setAttributeNode(_cloneNode(doc, attrs.item(i), true));
- }
-
- break;
-
- case ATTRIBUTE_NODE:
- deep = true;
- }
-
- if (deep) {
- var child = node.firstChild;
-
- while (child) {
- node2.appendChild(_cloneNode(doc, child, deep));
- child = child.nextSibling;
- }
- }
-
- return node2;
- }
-
- function __set__(object, key, value) {
- object[key] = value;
- } //do dynamic
-
-
- try {
- if (Object.defineProperty) {
- var getTextContent = function getTextContent(node) {
- switch (node.nodeType) {
- case ELEMENT_NODE:
- case DOCUMENT_FRAGMENT_NODE:
- var buf = [];
- node = node.firstChild;
-
- while (node) {
- if (node.nodeType !== 7 && node.nodeType !== 8) {
- buf.push(getTextContent(node));
- }
-
- node = node.nextSibling;
- }
-
- return buf.join('');
-
- default:
- return node.nodeValue;
- }
- };
-
- Object.defineProperty(LiveNodeList.prototype, 'length', {
- get: function get() {
- _updateLiveList(this);
-
- return this.$$length;
- }
- });
- Object.defineProperty(Node.prototype, 'textContent', {
- get: function get() {
- return getTextContent(this);
- },
- set: function set(data) {
- switch (this.nodeType) {
- case ELEMENT_NODE:
- case DOCUMENT_FRAGMENT_NODE:
- while (this.firstChild) {
- this.removeChild(this.firstChild);
- }
-
- if (data || String(data)) {
- this.appendChild(this.ownerDocument.createTextNode(data));
- }
-
- break;
-
- default:
- //TODO:
- this.data = data;
- this.value = data;
- this.nodeValue = data;
- }
- }
- });
-
- __set__ = function __set__(object, key, value) {
- //console.log(value)
- object['$$' + key] = value;
- };
- }
- } catch (e) {//ie8
- } //if(typeof require == 'function'){
-
-
- var DOMImplementation_1 = DOMImplementation;
- var XMLSerializer_1 = XMLSerializer$1; //}
-
- var dom = {
- DOMImplementation: DOMImplementation_1,
- XMLSerializer: XMLSerializer_1
- };
-
- var domParser = createCommonjsModule(function (module, exports) {
- function DOMParser(options) {
- this.options = options || {
- locator: {}
- };
- }
-
- DOMParser.prototype.parseFromString = function (source, mimeType) {
- var options = this.options;
- var sax = new XMLReader();
- var domBuilder = options.domBuilder || new DOMHandler(); //contentHandler and LexicalHandler
-
- var errorHandler = options.errorHandler;
- var locator = options.locator;
- var defaultNSMap = options.xmlns || {};
- var entityMap = {
- 'lt': '<',
- 'gt': '>',
- 'amp': '&',
- 'quot': '"',
- 'apos': "'"
- };
-
- if (locator) {
- domBuilder.setDocumentLocator(locator);
- }
-
- sax.errorHandler = buildErrorHandler(errorHandler, domBuilder, locator);
- sax.domBuilder = options.domBuilder || domBuilder;
-
- if (/\/x?html?$/.test(mimeType)) {
- entityMap.nbsp = '\xa0';
- entityMap.copy = '\xa9';
- defaultNSMap[''] = 'http://www.w3.org/1999/xhtml';
- }
-
- defaultNSMap.xml = defaultNSMap.xml || 'http://www.w3.org/XML/1998/namespace';
-
- if (source) {
- sax.parse(source, defaultNSMap, entityMap);
- } else {
- sax.errorHandler.error("invalid doc source");
- }
-
- return domBuilder.doc;
- };
-
- function buildErrorHandler(errorImpl, domBuilder, locator) {
- if (!errorImpl) {
- if (domBuilder instanceof DOMHandler) {
- return domBuilder;
- }
-
- errorImpl = domBuilder;
- }
-
- var errorHandler = {};
- var isCallback = errorImpl instanceof Function;
- locator = locator || {};
-
- function build(key) {
- var fn = errorImpl[key];
-
- if (!fn && isCallback) {
- fn = errorImpl.length == 2 ? function (msg) {
- errorImpl(key, msg);
- } : errorImpl;
- }
-
- errorHandler[key] = fn && function (msg) {
- fn('[xmldom ' + key + ']\t' + msg + _locator(locator));
- } || function () {};
- }
-
- build('warning');
- build('error');
- build('fatalError');
- return errorHandler;
- } //console.log('#\n\n\n\n\n\n\n####')
-
- /**
- * +ContentHandler+ErrorHandler
- * +LexicalHandler+EntityResolver2
- * -DeclHandler-DTDHandler
- *
- * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler
- * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2
- * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html
- */
-
-
- function DOMHandler() {
- this.cdata = false;
- }
-
- function position(locator, node) {
- node.lineNumber = locator.lineNumber;
- node.columnNumber = locator.columnNumber;
- }
- /**
- * @see org.xml.sax.ContentHandler#startDocument
- * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
- */
-
-
- DOMHandler.prototype = {
- startDocument: function startDocument() {
- this.doc = new DOMImplementation().createDocument(null, null, null);
-
- if (this.locator) {
- this.doc.documentURI = this.locator.systemId;
- }
- },
- startElement: function startElement(namespaceURI, localName, qName, attrs) {
- var doc = this.doc;
- var el = doc.createElementNS(namespaceURI, qName || localName);
- var len = attrs.length;
- appendElement(this, el);
- this.currentElement = el;
- this.locator && position(this.locator, el);
-
- for (var i = 0; i < len; i++) {
- var namespaceURI = attrs.getURI(i);
- var value = attrs.getValue(i);
- var qName = attrs.getQName(i);
- var attr = doc.createAttributeNS(namespaceURI, qName);
- this.locator && position(attrs.getLocator(i), attr);
- attr.value = attr.nodeValue = value;
- el.setAttributeNode(attr);
- }
- },
- endElement: function endElement(namespaceURI, localName, qName) {
- var current = this.currentElement;
- current.tagName;
- this.currentElement = current.parentNode;
- },
- startPrefixMapping: function startPrefixMapping(prefix, uri) {},
- endPrefixMapping: function endPrefixMapping(prefix) {},
- processingInstruction: function processingInstruction(target, data) {
- var ins = this.doc.createProcessingInstruction(target, data);
- this.locator && position(this.locator, ins);
- appendElement(this, ins);
- },
- ignorableWhitespace: function ignorableWhitespace(ch, start, length) {},
- characters: function characters(chars, start, length) {
- chars = _toString.apply(this, arguments); //console.log(chars)
-
- if (chars) {
- if (this.cdata) {
- var charNode = this.doc.createCDATASection(chars);
- } else {
- var charNode = this.doc.createTextNode(chars);
- }
-
- if (this.currentElement) {
- this.currentElement.appendChild(charNode);
- } else if (/^\s*$/.test(chars)) {
- this.doc.appendChild(charNode); //process xml
- }
-
- this.locator && position(this.locator, charNode);
- }
- },
- skippedEntity: function skippedEntity(name) {},
- endDocument: function endDocument() {
- this.doc.normalize();
- },
- setDocumentLocator: function setDocumentLocator(locator) {
- if (this.locator = locator) {
- // && !('lineNumber' in locator)){
- locator.lineNumber = 0;
- }
- },
- //LexicalHandler
- comment: function comment(chars, start, length) {
- chars = _toString.apply(this, arguments);
- var comm = this.doc.createComment(chars);
- this.locator && position(this.locator, comm);
- appendElement(this, comm);
- },
- startCDATA: function startCDATA() {
- //used in characters() methods
- this.cdata = true;
- },
- endCDATA: function endCDATA() {
- this.cdata = false;
- },
- startDTD: function startDTD(name, publicId, systemId) {
- var impl = this.doc.implementation;
-
- if (impl && impl.createDocumentType) {
- var dt = impl.createDocumentType(name, publicId, systemId);
- this.locator && position(this.locator, dt);
- appendElement(this, dt);
- }
- },
-
- /**
- * @see org.xml.sax.ErrorHandler
- * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
- */
- warning: function warning(error) {
- console.warn('[xmldom warning]\t' + error, _locator(this.locator));
- },
- error: function error(_error) {
- console.error('[xmldom error]\t' + _error, _locator(this.locator));
- },
- fatalError: function fatalError(error) {
- console.error('[xmldom fatalError]\t' + error, _locator(this.locator));
- throw error;
- }
- };
-
- function _locator(l) {
- if (l) {
- return '\n@' + (l.systemId || '') + '#[line:' + l.lineNumber + ',col:' + l.columnNumber + ']';
- }
- }
-
- function _toString(chars, start, length) {
- if (typeof chars == 'string') {
- return chars.substr(start, length);
- } else {
- //java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)")
- if (chars.length >= start + length || start) {
- return new java.lang.String(chars, start, length) + '';
- }
-
- return chars;
- }
- }
- /*
- * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html
- * used method of org.xml.sax.ext.LexicalHandler:
- * #comment(chars, start, length)
- * #startCDATA()
- * #endCDATA()
- * #startDTD(name, publicId, systemId)
- *
- *
- * IGNORED method of org.xml.sax.ext.LexicalHandler:
- * #endDTD()
- * #startEntity(name)
- * #endEntity(name)
- *
- *
- * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html
- * IGNORED method of org.xml.sax.ext.DeclHandler
- * #attributeDecl(eName, aName, type, mode, value)
- * #elementDecl(name, model)
- * #externalEntityDecl(name, publicId, systemId)
- * #internalEntityDecl(name, value)
- * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html
- * IGNORED method of org.xml.sax.EntityResolver2
- * #resolveEntity(String name,String publicId,String baseURI,String systemId)
- * #resolveEntity(publicId, systemId)
- * #getExternalSubset(name, baseURI)
- * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html
- * IGNORED method of org.xml.sax.DTDHandler
- * #notationDecl(name, publicId, systemId) {};
- * #unparsedEntityDecl(name, publicId, systemId, notationName) {};
- */
-
-
- "endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g, function (key) {
- DOMHandler.prototype[key] = function () {
- return null;
- };
- });
- /* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */
-
- function appendElement(hander, node) {
- if (!hander.currentElement) {
- hander.doc.appendChild(node);
- } else {
- hander.currentElement.appendChild(node);
- }
- } //appendChild and setAttributeNS are preformance key
- //if(typeof require == 'function'){
-
-
- var XMLReader = sax.XMLReader;
- var DOMImplementation = exports.DOMImplementation = dom.DOMImplementation;
- exports.XMLSerializer = dom.XMLSerializer;
- exports.DOMParser = DOMParser; //}
- });
-
- var togeojson = createCommonjsModule(function (module, exports) {
- var toGeoJSON = function () {
-
- var removeSpace = /\s*/g,
- trimSpace = /^\s*|\s*$/g,
- splitSpace = /\s+/; // generate a short, numeric hash of a string
-
- function okhash(x) {
- if (!x || !x.length) return 0;
-
- for (var i = 0, h = 0; i < x.length; i++) {
- h = (h << 5) - h + x.charCodeAt(i) | 0;
- }
-
- return h;
- } // all Y children of X
-
-
- function get(x, y) {
- return x.getElementsByTagName(y);
- }
-
- function attr(x, y) {
- return x.getAttribute(y);
- }
-
- function attrf(x, y) {
- return parseFloat(attr(x, y));
- } // one Y child of X, if any, otherwise null
-
-
- function get1(x, y) {
- var n = get(x, y);
- return n.length ? n[0] : null;
- } // https://developer.mozilla.org/en-US/docs/Web/API/Node.normalize
-
-
- function norm(el) {
- if (el.normalize) {
- el.normalize();
- }
-
- return el;
- } // cast array x into numbers
-
-
- function numarray(x) {
- for (var j = 0, o = []; j < x.length; j++) {
- o[j] = parseFloat(x[j]);
- }
-
- return o;
- } // get the content of a text node, if any
-
-
- function nodeVal(x) {
- if (x) {
- norm(x);
- }
-
- return x && x.textContent || '';
- } // get the contents of multiple text nodes, if present
-
-
- function getMulti(x, ys) {
- var o = {},
- n,
- k;
-
- for (k = 0; k < ys.length; k++) {
- n = get1(x, ys[k]);
- if (n) o[ys[k]] = nodeVal(n);
- }
-
- return o;
- } // add properties of Y to X, overwriting if present in both
-
-
- function extend(x, y) {
- for (var k in y) {
- x[k] = y[k];
- }
- } // get one coordinate from a coordinate array, if any
-
-
- function coord1(v) {
- return numarray(v.replace(removeSpace, '').split(','));
- } // get all coordinates from a coordinate array as [[],[]]
-
-
- function coord(v) {
- var coords = v.replace(trimSpace, '').split(splitSpace),
- o = [];
-
- for (var i = 0; i < coords.length; i++) {
- o.push(coord1(coords[i]));
- }
-
- return o;
- }
-
- function coordPair(x) {
- var ll = [attrf(x, 'lon'), attrf(x, 'lat')],
- ele = get1(x, 'ele'),
- // handle namespaced attribute in browser
- heartRate = get1(x, 'gpxtpx:hr') || get1(x, 'hr'),
- time = get1(x, 'time'),
- e;
-
- if (ele) {
- e = parseFloat(nodeVal(ele));
-
- if (!isNaN(e)) {
- ll.push(e);
- }
- }
-
- return {
- coordinates: ll,
- time: time ? nodeVal(time) : null,
- heartRate: heartRate ? parseFloat(nodeVal(heartRate)) : null
- };
- } // create a new feature collection parent object
-
-
- function fc() {
- return {
- type: 'FeatureCollection',
- features: []
- };
- }
-
- var serializer;
-
- if (typeof XMLSerializer !== 'undefined') {
- /* istanbul ignore next */
- serializer = new XMLSerializer(); // only require xmldom in a node environment
- } else if ((typeof process === "undefined" ? "undefined" : _typeof(process)) === 'object' && !process.browser) {
- serializer = new domParser.XMLSerializer();
- }
-
- function xml2str(str) {
- // IE9 will create a new XMLSerializer but it'll crash immediately.
- // This line is ignored because we don't run coverage tests in IE9
-
- /* istanbul ignore next */
- if (str.xml !== undefined) return str.xml;
- return serializer.serializeToString(str);
- }
-
- var t = {
- kml: function kml(doc) {
- var gj = fc(),
- // styleindex keeps track of hashed styles in order to match features
- styleIndex = {},
- styleByHash = {},
- // stylemapindex keeps track of style maps to expose in properties
- styleMapIndex = {},
- // atomic geospatial types supported by KML - MultiGeometry is
- // handled separately
- geotypes = ['Polygon', 'LineString', 'Point', 'Track', 'gx:Track'],
- // all root placemarks in the file
- placemarks = get(doc, 'Placemark'),
- styles = get(doc, 'Style'),
- styleMaps = get(doc, 'StyleMap');
-
- for (var k = 0; k < styles.length; k++) {
- var hash = okhash(xml2str(styles[k])).toString(16);
- styleIndex['#' + attr(styles[k], 'id')] = hash;
- styleByHash[hash] = styles[k];
- }
-
- for (var l = 0; l < styleMaps.length; l++) {
- styleIndex['#' + attr(styleMaps[l], 'id')] = okhash(xml2str(styleMaps[l])).toString(16);
- var pairs = get(styleMaps[l], 'Pair');
- var pairsMap = {};
-
- for (var m = 0; m < pairs.length; m++) {
- pairsMap[nodeVal(get1(pairs[m], 'key'))] = nodeVal(get1(pairs[m], 'styleUrl'));
- }
-
- styleMapIndex['#' + attr(styleMaps[l], 'id')] = pairsMap;
- }
-
- for (var j = 0; j < placemarks.length; j++) {
- gj.features = gj.features.concat(getPlacemark(placemarks[j]));
- }
-
- function kmlColor(v) {
- var color, opacity;
- v = v || '';
-
- if (v.substr(0, 1) === '#') {
- v = v.substr(1);
- }
-
- if (v.length === 6 || v.length === 3) {
- color = v;
- }
-
- if (v.length === 8) {
- opacity = parseInt(v.substr(0, 2), 16) / 255;
- color = '#' + v.substr(6, 2) + v.substr(4, 2) + v.substr(2, 2);
- }
-
- return [color, isNaN(opacity) ? undefined : opacity];
- }
-
- function gxCoord(v) {
- return numarray(v.split(' '));
- }
-
- function gxCoords(root) {
- var elems = get(root, 'coord'),
- coords = [],
- times = [];
- if (elems.length === 0) elems = get(root, 'gx:coord');
-
- for (var i = 0; i < elems.length; i++) {
- coords.push(gxCoord(nodeVal(elems[i])));
- }
-
- var timeElems = get(root, 'when');
-
- for (var j = 0; j < timeElems.length; j++) {
- times.push(nodeVal(timeElems[j]));
- }
-
- return {
- coords: coords,
- times: times
- };
- }
-
- function getGeometry(root) {
- var geomNode,
- geomNodes,
- i,
- j,
- k,
- geoms = [],
- coordTimes = [];
-
- if (get1(root, 'MultiGeometry')) {
- return getGeometry(get1(root, 'MultiGeometry'));
- }
-
- if (get1(root, 'MultiTrack')) {
- return getGeometry(get1(root, 'MultiTrack'));
- }
-
- if (get1(root, 'gx:MultiTrack')) {
- return getGeometry(get1(root, 'gx:MultiTrack'));
- }
-
- for (i = 0; i < geotypes.length; i++) {
- geomNodes = get(root, geotypes[i]);
-
- if (geomNodes) {
- for (j = 0; j < geomNodes.length; j++) {
- geomNode = geomNodes[j];
-
- if (geotypes[i] === 'Point') {
- geoms.push({
- type: 'Point',
- coordinates: coord1(nodeVal(get1(geomNode, 'coordinates')))
- });
- } else if (geotypes[i] === 'LineString') {
- geoms.push({
- type: 'LineString',
- coordinates: coord(nodeVal(get1(geomNode, 'coordinates')))
- });
- } else if (geotypes[i] === 'Polygon') {
- var rings = get(geomNode, 'LinearRing'),
- coords = [];
-
- for (k = 0; k < rings.length; k++) {
- coords.push(coord(nodeVal(get1(rings[k], 'coordinates'))));
- }
-
- geoms.push({
- type: 'Polygon',
- coordinates: coords
- });
- } else if (geotypes[i] === 'Track' || geotypes[i] === 'gx:Track') {
- var track = gxCoords(geomNode);
- geoms.push({
- type: 'LineString',
- coordinates: track.coords
- });
- if (track.times.length) coordTimes.push(track.times);
- }
- }
- }
- }
-
- return {
- geoms: geoms,
- coordTimes: coordTimes
- };
- }
-
- function getPlacemark(root) {
- var geomsAndTimes = getGeometry(root),
- i,
- properties = {},
- name = nodeVal(get1(root, 'name')),
- address = nodeVal(get1(root, 'address')),
- styleUrl = nodeVal(get1(root, 'styleUrl')),
- description = nodeVal(get1(root, 'description')),
- timeSpan = get1(root, 'TimeSpan'),
- timeStamp = get1(root, 'TimeStamp'),
- extendedData = get1(root, 'ExtendedData'),
- lineStyle = get1(root, 'LineStyle'),
- polyStyle = get1(root, 'PolyStyle'),
- visibility = get1(root, 'visibility');
- if (!geomsAndTimes.geoms.length) return [];
- if (name) properties.name = name;
- if (address) properties.address = address;
-
- if (styleUrl) {
- if (styleUrl[0] !== '#') {
- styleUrl = '#' + styleUrl;
- }
-
- properties.styleUrl = styleUrl;
-
- if (styleIndex[styleUrl]) {
- properties.styleHash = styleIndex[styleUrl];
- }
-
- if (styleMapIndex[styleUrl]) {
- properties.styleMapHash = styleMapIndex[styleUrl];
- properties.styleHash = styleIndex[styleMapIndex[styleUrl].normal];
- } // Try to populate the lineStyle or polyStyle since we got the style hash
-
-
- var style = styleByHash[properties.styleHash];
-
- if (style) {
- if (!lineStyle) lineStyle = get1(style, 'LineStyle');
- if (!polyStyle) polyStyle = get1(style, 'PolyStyle');
- }
- }
-
- if (description) properties.description = description;
-
- if (timeSpan) {
- var begin = nodeVal(get1(timeSpan, 'begin'));
- var end = nodeVal(get1(timeSpan, 'end'));
- properties.timespan = {
- begin: begin,
- end: end
- };
- }
-
- if (timeStamp) {
- properties.timestamp = nodeVal(get1(timeStamp, 'when'));
- }
-
- if (lineStyle) {
- var linestyles = kmlColor(nodeVal(get1(lineStyle, 'color'))),
- color = linestyles[0],
- opacity = linestyles[1],
- width = parseFloat(nodeVal(get1(lineStyle, 'width')));
- if (color) properties.stroke = color;
- if (!isNaN(opacity)) properties['stroke-opacity'] = opacity;
- if (!isNaN(width)) properties['stroke-width'] = width;
- }
-
- if (polyStyle) {
- var polystyles = kmlColor(nodeVal(get1(polyStyle, 'color'))),
- pcolor = polystyles[0],
- popacity = polystyles[1],
- fill = nodeVal(get1(polyStyle, 'fill')),
- outline = nodeVal(get1(polyStyle, 'outline'));
- if (pcolor) properties.fill = pcolor;
- if (!isNaN(popacity)) properties['fill-opacity'] = popacity;
- if (fill) properties['fill-opacity'] = fill === '1' ? properties['fill-opacity'] || 1 : 0;
- if (outline) properties['stroke-opacity'] = outline === '1' ? properties['stroke-opacity'] || 1 : 0;
- }
-
- if (extendedData) {
- var datas = get(extendedData, 'Data'),
- simpleDatas = get(extendedData, 'SimpleData');
-
- for (i = 0; i < datas.length; i++) {
- properties[datas[i].getAttribute('name')] = nodeVal(get1(datas[i], 'value'));
- }
-
- for (i = 0; i < simpleDatas.length; i++) {
- properties[simpleDatas[i].getAttribute('name')] = nodeVal(simpleDatas[i]);
- }
- }
-
- if (visibility) {
- properties.visibility = nodeVal(visibility);
- }
-
- if (geomsAndTimes.coordTimes.length) {
- properties.coordTimes = geomsAndTimes.coordTimes.length === 1 ? geomsAndTimes.coordTimes[0] : geomsAndTimes.coordTimes;
- }
-
- var feature = {
- type: 'Feature',
- geometry: geomsAndTimes.geoms.length === 1 ? geomsAndTimes.geoms[0] : {
- type: 'GeometryCollection',
- geometries: geomsAndTimes.geoms
- },
- properties: properties
- };
- if (attr(root, 'id')) feature.id = attr(root, 'id');
- return [feature];
- }
-
- return gj;
- },
- gpx: function gpx(doc) {
- var i,
- tracks = get(doc, 'trk'),
- routes = get(doc, 'rte'),
- waypoints = get(doc, 'wpt'),
- // a feature collection
- gj = fc(),
- feature;
-
- for (i = 0; i < tracks.length; i++) {
- feature = getTrack(tracks[i]);
- if (feature) gj.features.push(feature);
- }
-
- for (i = 0; i < routes.length; i++) {
- feature = getRoute(routes[i]);
- if (feature) gj.features.push(feature);
- }
-
- for (i = 0; i < waypoints.length; i++) {
- gj.features.push(getPoint(waypoints[i]));
- }
-
- function getPoints(node, pointname) {
- var pts = get(node, pointname),
- line = [],
- times = [],
- heartRates = [],
- l = pts.length;
- if (l < 2) return {}; // Invalid line in GeoJSON
-
- for (var i = 0; i < l; i++) {
- var c = coordPair(pts[i]);
- line.push(c.coordinates);
- if (c.time) times.push(c.time);
- if (c.heartRate) heartRates.push(c.heartRate);
- }
-
- return {
- line: line,
- times: times,
- heartRates: heartRates
- };
- }
-
- function getTrack(node) {
- var segments = get(node, 'trkseg'),
- track = [],
- times = [],
- heartRates = [],
- line;
-
- for (var i = 0; i < segments.length; i++) {
- line = getPoints(segments[i], 'trkpt');
-
- if (line) {
- if (line.line) track.push(line.line);
- if (line.times && line.times.length) times.push(line.times);
- if (line.heartRates && line.heartRates.length) heartRates.push(line.heartRates);
- }
- }
-
- if (track.length === 0) return;
- var properties = getProperties(node);
- extend(properties, getLineStyle(get1(node, 'extensions')));
- if (times.length) properties.coordTimes = track.length === 1 ? times[0] : times;
- if (heartRates.length) properties.heartRates = track.length === 1 ? heartRates[0] : heartRates;
- return {
- type: 'Feature',
- properties: properties,
- geometry: {
- type: track.length === 1 ? 'LineString' : 'MultiLineString',
- coordinates: track.length === 1 ? track[0] : track
- }
- };
- }
-
- function getRoute(node) {
- var line = getPoints(node, 'rtept');
- if (!line.line) return;
- var prop = getProperties(node);
- extend(prop, getLineStyle(get1(node, 'extensions')));
- var routeObj = {
- type: 'Feature',
- properties: prop,
- geometry: {
- type: 'LineString',
- coordinates: line.line
- }
- };
- return routeObj;
- }
-
- function getPoint(node) {
- var prop = getProperties(node);
- extend(prop, getMulti(node, ['sym']));
- return {
- type: 'Feature',
- properties: prop,
- geometry: {
- type: 'Point',
- coordinates: coordPair(node).coordinates
- }
- };
- }
-
- function getLineStyle(extensions) {
- var style = {};
-
- if (extensions) {
- var lineStyle = get1(extensions, 'line');
-
- if (lineStyle) {
- var color = nodeVal(get1(lineStyle, 'color')),
- opacity = parseFloat(nodeVal(get1(lineStyle, 'opacity'))),
- width = parseFloat(nodeVal(get1(lineStyle, 'width')));
- if (color) style.stroke = color;
- if (!isNaN(opacity)) style['stroke-opacity'] = opacity; // GPX width is in mm, convert to px with 96 px per inch
-
- if (!isNaN(width)) style['stroke-width'] = width * 96 / 25.4;
- }
- }
-
- return style;
- }
-
- function getProperties(node) {
- var prop = getMulti(node, ['name', 'cmt', 'desc', 'type', 'time', 'keywords']),
- links = get(node, 'link');
- if (links.length) prop.links = [];
-
- for (var i = 0, link; i < links.length; i++) {
- link = {
- href: attr(links[i], 'href')
- };
- extend(link, getMulti(links[i], ['text', 'type']));
- prop.links.push(link);
- }
-
- return prop;
- }
-
- return gj;
- }
- };
- return t;
- }();
-
- module.exports = toGeoJSON;
- });
-
- var _initialized = false;
- var _enabled = false;
-
- var _geojson;
-
- function svgData(projection, context, dispatch) {
- var throttledRedraw = throttle(function () {
- dispatch.call('change');
- }, 1000);
-
- var _showLabels = true;
- var detected = utilDetect();
- var layer = select(null);
-
- var _vtService;
-
- var _fileList;
-
- var _template;
-
- var _src;
-
- function init() {
- if (_initialized) return; // run once
-
- _geojson = {};
- _enabled = true;
-
- function over(d3_event) {
- d3_event.stopPropagation();
- d3_event.preventDefault();
- d3_event.dataTransfer.dropEffect = 'copy';
- }
-
- context.container().attr('dropzone', 'copy').on('drop.svgData', function (d3_event) {
- d3_event.stopPropagation();
- d3_event.preventDefault();
- if (!detected.filedrop) return;
- drawData.fileList(d3_event.dataTransfer.files);
- }).on('dragenter.svgData', over).on('dragexit.svgData', over).on('dragover.svgData', over);
- _initialized = true;
- }
-
- function getService() {
- if (services.vectorTile && !_vtService) {
- _vtService = services.vectorTile;
-
- _vtService.event.on('loadedData', throttledRedraw);
- } else if (!services.vectorTile && _vtService) {
- _vtService = null;
- }
-
- return _vtService;
- }
-
- function showLayer() {
- layerOn();
- layer.style('opacity', 0).transition().duration(250).style('opacity', 1).on('end', function () {
- dispatch.call('change');
- });
- }
-
- function hideLayer() {
- throttledRedraw.cancel();
- layer.transition().duration(250).style('opacity', 0).on('end', layerOff);
- }
-
- function layerOn() {
- layer.style('display', 'block');
- }