Browse Source

domquery updates

Cody Joyce 1 month ago
parent
commit
2a5237fafa
2 changed files with 36 additions and 31 deletions
  1. 30 21
      gen/domquery/htmlquery.go
  2. 6 10
      gen/domquery/node.go

+ 30 - 21
gen/domquery/htmlquery.go

@@ -9,12 +9,12 @@ import (
 
 /* End Node Functions */
 func LoadHTML(htmlStr string) *Node {
-	tokList := getTokenList(htmlStr)
-	bt := buildTree(tokList)
+	tokList := GetTokenList(htmlStr)
+	bt := BuildTree(tokList)
 	return bt
 }
 
-func getTokenList(htmlStr string) []string {
+func GetTokenList(htmlStr string) []string {
 	var tokList []string
 	var tok string
 
@@ -96,39 +96,48 @@ func getTokenList(htmlStr string) []string {
 	return tokList
 }
 
-func buildTree(tokList []string) *Node {
+func BuildTree(tokList []string, params ...*Node) *Node {
 	root := &Node{}
+	root.token = ""
 
-	node := &Node{}
-	node.Parent = root
+	if len(params) > 0 {
+		root = params[0]
+	}
 
-	for _, tok := range tokList {
-		prev := node
-		prev.token = tok
-		node = &Node{}
+	prev := root
 
+	for _, tok := range tokList {
+		node := &Node{}
+		node.token = tok
 		if getTokType(tok) == "open" {
 			node.Parent = prev
+			prev.Children = append(prev.Children, node)
+			prev = node
+			continue
+		}
+		if getTokType(tok) == "close" {
+			prev = prev.Parent
+			node.Parent = prev
+			prev.Children = append(prev.Children, node)
+			continue
 		}
-
 		if getTokType(tok) == "text" {
-			node.Parent = prev.Parent
+			node.Parent = prev
+			prev.Children = append(prev.Children, node)
+			continue
 		}
 
 		if getTokType(tok) == "selfclosing" {
-			node.Parent = prev.Parent
+			node.Parent = prev
+			prev.Children = append(prev.Children, node)
+			continue
 		}
 
 		if getTokType(tok) == "comment" {
-			node.Parent = prev.Parent
-		}
-
-		if getTokType(tok) == "close" {
-			prev.Parent = prev.Parent.Parent
-			node.Parent = prev.Parent
+			node.Parent = prev
+			prev.Children = append(prev.Children, node)
+			continue
 		}
-
-		prev.Parent.Children = append(prev.Parent.Children, prev)
 	}
 
 	return root

+ 6 - 10
gen/domquery/node.go

@@ -29,13 +29,9 @@ func (node *Node) SetOuterHTML(str string) {
 	node.token = ""
 	node.Children = []*Node{}
 
-	// regen parent
-	tokList := getTokenList(str)
-	tree := buildTree(tokList)
-	node.Children = tree.Children
-	for _, child := range tree.Children {
-		child.Parent = node
-	}
+	// build node
+	tokList := GetTokenList(str)
+	node = BuildTree(tokList, node)
 }
 
 func (node *Node) InnerHTML() string {
@@ -45,15 +41,15 @@ func (node *Node) InnerHTML() string {
 	for _, child := range node.Children {
 		str += child.token
 		str += child.InnerHTML()
-		//fmt.Println(child.token)
 	}
 
 	return str
 }
 
 func (node *Node) SetInnerHTML(str string) {
-	tokList := getTokenList(str)
-	document := buildTree(tokList)
+	tokList := GetTokenList(str)
+	node.Children = []*Node{}
+	document := BuildTree(tokList, node)
 	node.Children = document.Children
 }