Nils Diewald | 1eba657 | 2014-06-17 19:49:53 +0000 | [diff] [blame] | 1 | var cleanRegex = /^([^\/]+?\/)?[^\:]+?\:/; |
| 2 | |
| 3 | // SnippetTree constructor |
| 4 | function SnippetTree (obj) { |
| 5 | this.children = []; |
| 6 | this.data = obj; |
| 7 | |
| 8 | // Replace title |
| 9 | this.cleanTitle = function (title) { |
| 10 | return title.replace(cleanRegex, ""); |
| 11 | }; |
| 12 | |
| 13 | // Add new child to tree |
| 14 | this.addChild = function (childData) { |
| 15 | var c = new SnippetTree (childData); |
| 16 | this.children.push(c); |
| 17 | return c; |
| 18 | }; |
| 19 | |
| 20 | // Recursively parse children |
| 21 | this.parseChildren = function (children) { |
| 22 | for (var i in children) { |
| 23 | var c = children[i]; |
| 24 | if (c.nodeType === 1) { |
| 25 | if (c.getAttribute("title")) { |
| 26 | var title = this.cleanTitle(c.getAttribute("title")); |
| 27 | var childTree = this.addChild({ type : title }); |
| 28 | if (c.hasChildNodes()) |
| 29 | childTree.parseChildren(c.childNodes); |
| 30 | } |
| 31 | else if (c.hasChildNodes()) |
| 32 | this.parseChildren(c.childNodes); |
| 33 | } |
| 34 | else if (c.nodeType === 3) |
| 35 | if (c.nodeValue.match(/[-a-z0-9]/i)) { |
| 36 | this.addChild({ |
| 37 | type : "leaf", |
| 38 | word : c.nodeValue |
| 39 | }); |
| 40 | }; |
| 41 | }; |
| 42 | return this; |
| 43 | }; |
| 44 | }; |
| 45 | |
| 46 | // Make tree from snippet |
| 47 | function translateTree (snippet) { |
| 48 | var html = document.createElement("tree"); |
| 49 | html.innerHTML = snippet; |
| 50 | return new SnippetTree({ type : "ROOT" }).parseChildren(html.childNodes); |
| 51 | }; |
| 52 | |
| 53 | |