Selector
Selector is a implementation of JavaScripts querySelector. It is split between two files this file and the element
package to prevent circular dependancys, however this document will be the source for it. The best way to explain how this works is to start in the element
package with the querySelector
method and then take a look at the parts that make it up.
flowchart LR; QuerySelector-->TestSelector; TestSelector-->GetCSSSelectors; GetCSSSelectors-->SplitSelector; SplitSelector-->Contains; Contains-->True; Contains-->False; False-->Children; True-->QuerySelector; EOL-->Yes; EOL-->No; No-->TestSelector Yes-->QuerySelector; Children-->TestSelector; Children-->EOL;
flowchart LR; QuerySelectorAll-->TestSelector; TestSelector-->GetCSSSelectors; GetCSSSelectors-->SplitSelector; SplitSelector-->Contains; Contains-->True; Contains-->False; False-->QuerySelectorAll; True-->EOL; EOL-->Yes; EOL-->No; No-->TestSelector Yes-->QuerySelectorAll;
# QuerySelector?(go)
QuerySelector
works almost the same as JavaScripts querySelector method with a far limited scope. After a document is loaded from a HTML file it is compiled into element.Node
's which is a custom implementation of net/html.Node
. The reason the net/html
node is not used is it has already defined features that stray away from JavaScripts DOM.
if TestSelector(selectString, n) {return n}
To start out, we check the current element to see if the selectString
matches the element.Node (n) we called the method on using the TestSelector
function. If it does we can end the function there and return itself. If it does not we can continue and check its children. We do this process recursively to simplify the code.
if cr.Properties.Id != "" {return cr}
We also do a check to see if the element.Node.Properties.Id
has been assigned. This is a importaint step as this id is the the #id
used in html but a unqiue id generated at run time to be used as a internal reference. If it has not been assigned then the element does not exist.
# QuerySelectorAll?(go)
See QuerySelector. QuerySelectorAll
works the exact same as QuerySelector
with an added collector (results
) to collect all elements that match the selector throughout the recusive execution.
# TestSelector?(go)
TestSelector
is the foundation of the QuerySelector
and QuerySelectorAll
as seen above.
parts := strings.Split(selectString, ">")
It first starts off by splitting the selectString
in to parts divided by >
this is becuase when you have a selector like blockquote > p
you need to start at the first level (p
) to compare the current node to see if you will need to continue to check the parents of the element with the next selector.
selectors := []string{} if n.Properties.Focusable { if n.Properties.Focused { selectors = append(selectors, ":focus") } } classes := n.ClassList.Classes for _, v := range classes { selectors = append(selectors, "."+v) }
Then we need to build the selectors, so we start by creating an array to store them in (s
) and we check to see if the element is focusable and if the element is focused. If so we add the :focus
selector to the list. This is important because when targeting a :focus
ed element with a querySelector that is the text that is past. We then do the same for classes.
if n.Id != "" { selectors = append(selectors, "#"+n.Id) }
Then we add the id to the array to complete the current Nodes selectors.
part := selector.SplitSelector(strings.TrimSpace(parts[len(parts)-1])) has := selector.Contains(part, selectors)
After we have the current Nodes selectors we can use the SplitSelector and Contains methods to process the passed query (selectString) and compare the two arrays.
if len(parts) == 1 || !has { return has }
If we are on the last selector in the split selector (parts) or if we have a part that does not match (i.e. has == false) then we can go ahead and return the has value. We return this instead of just the constant false
becuase if we have gotten to this point in the recursive chain that mean every part has been true until now, so the value of has
weather true
or false
we detirmine if the selector matches for the entire selector string.
} else { return TestSelector(strings.Join(parts[0:len(parts)-1], ">"), n.Parent) }
If we are not on the last element and the selector matches for this Node then we can remove the last element from parts
as we have already checked to make sure it matches and join it be >
charectors as that is what it was split by at the beginning. Then we just recall the function passing the parent as the Node.
# SplitSelector?(go)
SplitSelector
works by simply spliting a CSS selector into it's individual parts see below for an example:
1func main() {
2 fmt.Println(SplitSelector("p.text[name='first']"))
3}
Result
1[p .text [name='first']]
# Contains?(go)
Contains
compares two arrays of selectors, the first argument is the array of the selector that will be use to detirmine if the Node is a match or not. The second argument is the selecter of the targeted Node, the Node need to have all of the selectors of the selector
array, however it can have additional selectors and it will still match.
1package selector
2
3import (
4 "slices"
5 "strings"
6
7 "golang.org/x/net/html"
8)
9
10// !ISSUE: Create :not and other selectors
11
12func GetInitCSSSelectors(node *html.Node, selectors []string) []string {
13 if node.Type == html.ElementNode {
14 selectors = append(selectors, node.Data)
15 for _, attr := range node.Attr {
16 if attr.Key == "class" {
17 classes := strings.Split(attr.Val, " ")
18 for _, class := range classes {
19 selectors = append(selectors, "."+class)
20 }
21 } else if attr.Key == "id" {
22 selectors = append(selectors, "#"+attr.Val)
23 } else {
24 selectors = append(selectors, "["+attr.Key+"=\""+attr.Val+"\"]")
25 }
26 }
27 }
28
29 return selectors
30}
31
32func SplitSelector(s string) []string {
33 var result []string
34 var current string
35
36 for _, char := range s {
37 switch char {
38 case '.', '#', '[', ']', ':':
39 if current != "" {
40 if string(char) == "]" {
41 current += string(char)
42 }
43 result = append(result, current)
44 }
45 current = ""
46 if string(char) != "]" {
47 current += string(char)
48 }
49 default:
50 current += string(char)
51 }
52 }
53
54 if current != "" && current != "]" {
55 result = append(result, current)
56 }
57
58 return result
59}
60
61func Contains(selector []string, node []string) bool {
62 has := true
63 for _, s := range selector {
64 if !slices.Contains(node, s) {
65 has = false
66 }
67 }
68 return has
69}
1package element
2
3import (
4 "fmt"
5 "gui/selector"
6 "image"
7 ic "image/color"
8 "math/rand"
9 "strings"
10
11 "golang.org/x/image/font"
12)
13
14type Node struct {
15 TagName string
16 InnerText string
17 InnerHTML string
18 OuterHTML string
19 Parent *Node `json:"-"`
20 Children []Node
21 Style map[string]string
22 Id string
23 ClassList ClassList
24 Href string
25 Src string
26 Title string
27 Attribute map[string]string
28
29 ScrollY float32
30 Value string
31 OnClick func(Event) `json:"-"`
32 OnContextMenu func(Event) `json:"-"`
33 OnMouseDown func(Event) `json:"-"`
34 OnMouseUp func(Event) `json:"-"`
35 OnMouseEnter func(Event) `json:"-"`
36 OnMouseLeave func(Event) `json:"-"`
37 OnMouseOver func(Event) `json:"-"`
38 OnMouseMove func(Event) `json:"-"`
39 OnScroll func(Event) `json:"-"`
40 Properties Properties
41}
42
43type State struct {
44 // Id string
45 X float32
46 Y float32
47 Z float32
48 Width float32
49 Height float32
50 Border Border
51 Texture *image.RGBA
52 EM float32
53 Background ic.RGBA
54 Color ic.RGBA
55 Hash string
56 Margin MarginPadding
57 Padding MarginPadding
58 Style map[string]string
59}
60
61// !FLAG: Plan to get rid of this
62
63type Properties struct {
64 Id string
65 EventListeners map[string][]func(Event) `json:"-"`
66 Focusable bool
67 Focused bool
68 Editable bool
69 Hover bool
70 Selected []float32
71}
72
73type ClassList struct {
74 Classes []string
75 Value string
76}
77
78type MarginPadding struct {
79 Top float32
80 Left float32
81 Right float32
82 Bottom float32
83}
84
85func (c *ClassList) Add(class string) {
86 c.Classes = append(c.Classes, class)
87 c.Value = strings.Join(c.Classes, " ")
88}
89
90func (c *ClassList) Remove(class string) {
91 for i, v := range c.Classes {
92 if v == class {
93 c.Classes = append(c.Classes[:i], c.Classes[i+1:]...)
94 break
95 }
96 }
97
98 c.Value = strings.Join(c.Classes, " ")
99}
100
101type Border struct {
102 Width float32
103 Style string
104 Color ic.RGBA
105 Radius string
106}
107
108type Text struct {
109 Font font.Face
110 Color ic.RGBA
111 Text string
112 Underlined bool
113 Overlined bool
114 LineThrough bool
115 DecorationColor ic.RGBA
116 DecorationThickness int
117 Align string
118 Indent int // very low priority
119 LetterSpacing int
120 LineHeight int
121 WordSpacing int
122 WhiteSpace string
123 Shadows []Shadow // need
124 Width int
125 WordBreak string
126 EM int
127 X int
128 LoadedFont string
129}
130
131type Shadow struct {
132 X int
133 Y int
134 Blur int
135 Color ic.RGBA
136}
137
138func (n *Node) GetAttribute(name string) string {
139 return n.Attribute[name]
140}
141
142func (n *Node) SetAttribute(key, value string) {
143 n.Attribute[key] = value
144}
145
146func (n *Node) CreateElement(name string) Node {
147 return Node{
148 TagName: name,
149 InnerText: "",
150 OuterHTML: "",
151 InnerHTML: "",
152 Children: []Node{},
153 Style: make(map[string]string),
154 Id: "",
155 ClassList: ClassList{
156 Classes: []string{},
157 Value: "",
158 },
159 Href: "",
160 Src: "",
161 Title: "",
162 Attribute: make(map[string]string),
163 Value: "",
164 Properties: Properties{
165 Id: "",
166 EventListeners: make(map[string][]func(Event)),
167 Focusable: false,
168 Focused: false,
169 Editable: false,
170 Hover: false,
171 Selected: []float32{},
172 },
173 }
174}
175
176func (n *Node) QuerySelectorAll(selectString string) *[]*Node {
177 results := []*Node{}
178 if TestSelector(selectString, n) {
179 results = append(results, n)
180 }
181
182 for i := range n.Children {
183 el := &n.Children[i]
184 cr := el.QuerySelectorAll(selectString)
185 if len(*cr) > 0 {
186 results = append(results, *cr...)
187 }
188 }
189 return &results
190}
191
192func (n *Node) QuerySelector(selectString string) *Node {
193 if TestSelector(selectString, n) {
194 return n
195 }
196
197 for i := range n.Children {
198 el := &n.Children[i]
199 cr := el.QuerySelector(selectString)
200 if cr.Properties.Id != "" {
201 return cr
202 }
203 }
204
205 return &Node{}
206}
207
208func TestSelector(selectString string, n *Node) bool {
209 parts := strings.Split(selectString, ">")
210
211 selectors := []string{}
212 if n.Properties.Focusable {
213 if n.Properties.Focused {
214 selectors = append(selectors, ":focus")
215 }
216 }
217
218 classes := n.ClassList.Classes
219
220 for _, v := range classes {
221 selectors = append(selectors, "."+v)
222 }
223
224 if n.Id != "" {
225 selectors = append(selectors, "#"+n.Id)
226 }
227
228 selectors = append(selectors, n.TagName)
229
230 part := selector.SplitSelector(strings.TrimSpace(parts[len(parts)-1]))
231
232 has := selector.Contains(part, selectors)
233
234 if len(parts) == 1 || !has {
235 return has
236 } else {
237 return TestSelector(strings.Join(parts[0:len(parts)-1], ">"), n.Parent)
238 }
239}
240
241func (n *Node) AppendChild(c Node) {
242 c.Parent = n
243 // Set Id
244 randomInt := rand.Intn(10000)
245
246 c.Properties.Id = c.TagName + fmt.Sprint(randomInt+len(c.Parent.Children))
247
248 n.Children = append(n.Children, c)
249}
250
251func (n *Node) InsertAfter(c, tgt Node) {
252 c.Parent = n
253 // Set Id
254 randomInt := rand.Intn(10000)
255
256 c.Properties.Id = c.TagName + fmt.Sprint(randomInt+len(c.Parent.Children))
257 nodeIndex := -1
258 for i, v := range n.Children {
259
260 if v.Properties.Id == tgt.Properties.Id {
261 nodeIndex = i
262 break
263 }
264 }
265 if nodeIndex > -1 {
266 n.Children = append(n.Children[:nodeIndex+1], append([]Node{c}, n.Children[nodeIndex+1:]...)...)
267 } else {
268 n.AppendChild(c)
269 }
270}
271
272func (n *Node) InsertBefore(c, tgt Node) {
273 c.Parent = n
274 // Set Id
275 randomInt := rand.Intn(10000)
276
277 c.Properties.Id = c.TagName + fmt.Sprint(randomInt+len(c.Parent.Children))
278 nodeIndex := -1
279 for i, v := range n.Children {
280 if v.Properties.Id == tgt.Properties.Id {
281 nodeIndex = i
282 break
283 }
284 }
285 if nodeIndex > 0 {
286 n.Children = append(n.Children[:nodeIndex], append([]Node{c}, n.Children[nodeIndex:]...)...)
287 } else {
288 n.AppendChild(c)
289 }
290
291}
292
293func (n *Node) Remove() {
294 nodeIndex := -1
295 for i, v := range n.Parent.Children {
296 if v.Properties.Id == n.Properties.Id {
297 nodeIndex = i
298 break
299 }
300 }
301 if nodeIndex > 0 {
302 n.Parent.Children = append(n.Parent.Children[:nodeIndex], n.Parent.Children[nodeIndex+1:]...)
303 }
304}
305
306func (n *Node) Focus() {
307 if n.Properties.Focusable {
308 n.Properties.Focused = true
309 n.ClassList.Add(":focus")
310 }
311}
312
313func (n *Node) Blur() {
314 if n.Properties.Focusable {
315 n.Properties.Focused = false
316 n.ClassList.Remove(":focus")
317 }
318}
319
320type Event struct {
321 X int
322 Y int
323 KeyCode int
324 Key string
325 CtrlKey bool
326 MetaKey bool
327 ShiftKey bool
328 AltKey bool
329 Click bool
330 ContextMenu bool
331 MouseDown bool
332 MouseUp bool
333 MouseEnter bool
334 MouseLeave bool
335 MouseOver bool
336 KeyUp bool
337 KeyDown bool
338 KeyPress bool
339 Input bool
340 Target Node
341}
342
343type EventList struct {
344 Event Event
345 List []string
346}
347
348func (node *Node) AddEventListener(name string, callback func(Event)) {
349 if node.Properties.EventListeners == nil {
350 node.Properties.EventListeners = make(map[string][]func(Event))
351 }
352 if node.Properties.EventListeners[name] == nil {
353 node.Properties.EventListeners[name] = []func(Event){}
354 }
355 node.Properties.EventListeners[name] = append(node.Properties.EventListeners[name], callback)
356}