...
1 package goquery
2
3 import (
4 "bytes"
5 "io"
6
7 "golang.org/x/net/html"
8 )
9
10
11
12
13 const minNodesForSet = 1000
14
15 var nodeNames = []string{
16 html.ErrorNode: "#error",
17 html.TextNode: "#text",
18 html.DocumentNode: "#document",
19 html.CommentNode: "#comment",
20 }
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36 func NodeName(s *Selection) string {
37 if s.Length() == 0 {
38 return ""
39 }
40 return nodeName(s.Get(0))
41 }
42
43
44
45 func nodeName(node *html.Node) string {
46 if node == nil {
47 return ""
48 }
49
50 switch node.Type {
51 case html.ElementNode, html.DoctypeNode:
52 return node.Data
53 default:
54 if int(node.Type) < len(nodeNames) {
55 return nodeNames[node.Type]
56 }
57 return ""
58 }
59 }
60
61
62
63
64 func Render(w io.Writer, s *Selection) error {
65 if s.Length() == 0 {
66 return nil
67 }
68 n := s.Get(0)
69 return html.Render(w, n)
70 }
71
72
73
74
75
76
77
78
79 func OuterHtml(s *Selection) (string, error) {
80 var buf bytes.Buffer
81 if err := Render(&buf, s); err != nil {
82 return "", err
83 }
84 return buf.String(), nil
85 }
86
87
88 func sliceContains(container []*html.Node, contained *html.Node) bool {
89 for _, n := range container {
90 if nodeContains(n, contained) {
91 return true
92 }
93 }
94
95 return false
96 }
97
98
99 func nodeContains(container *html.Node, contained *html.Node) bool {
100
101
102 for contained = contained.Parent; contained != nil; contained = contained.Parent {
103 if container == contained {
104 return true
105 }
106 }
107 return false
108 }
109
110
111 func isInSlice(slice []*html.Node, node *html.Node) bool {
112 return indexInSlice(slice, node) > -1
113 }
114
115
116 func indexInSlice(slice []*html.Node, node *html.Node) int {
117 if node != nil {
118 for i, n := range slice {
119 if n == node {
120 return i
121 }
122 }
123 }
124 return -1
125 }
126
127
128
129
130
131
132 func appendWithoutDuplicates(target []*html.Node, nodes []*html.Node, targetSet map[*html.Node]bool) []*html.Node {
133
134
135 if targetSet == nil && len(target)+len(nodes) < minNodesForSet {
136 for _, n := range nodes {
137 if !isInSlice(target, n) {
138 target = append(target, n)
139 }
140 }
141 return target
142 }
143
144
145
146 if targetSet == nil {
147 targetSet = make(map[*html.Node]bool, len(target))
148 for _, n := range target {
149 targetSet[n] = true
150 }
151 }
152 for _, n := range nodes {
153 if !targetSet[n] {
154 target = append(target, n)
155 targetSet[n] = true
156 }
157 }
158
159 return target
160 }
161
162
163
164 func grep(sel *Selection, predicate func(i int, s *Selection) bool) (result []*html.Node) {
165 for i, n := range sel.Nodes {
166 if predicate(i, newSingleSelection(n, sel.document)) {
167 result = append(result, n)
168 }
169 }
170 return result
171 }
172
173
174
175 func pushStack(fromSel *Selection, nodes []*html.Node) *Selection {
176 result := &Selection{nodes, fromSel.document, fromSel}
177 return result
178 }
179
View as plain text