-
Notifications
You must be signed in to change notification settings - Fork 43
/
element.go
327 lines (291 loc) · 7.85 KB
/
element.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
package gowd
import (
"fmt"
"io"
"os"
"strings"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
var (
//Order counts the number of elements rendered (for generating auto-ids)
Order int
//Output output render target (configurable for unit-tests)
Output io.Writer = os.Stdout
)
//Element represents a DOM element and its state.
type Element struct {
//Parent the parent element
Parent *Element
//eventHandlers holds event handlers for events
eventHandlers map[string]EventHandler
//Kids child elements
Kids []*Element
//Attributes element attributes...
Attributes []html.Attribute
//Object arbitrary user object that can be associated with element.
Object interface{}
//nodeType the element node type
nodeType html.NodeType
//data html tag or text
data string
//Hidden if true the element will not be rendered
Hidden bool
//renderHash after rendered get a hash to identify if should be rendered again.
renderHash []byte
}
//NewElement creates a new HTML element
func NewElement(tag string) *Element {
elem := &Element{
data: tag,
Attributes: make([]html.Attribute, 0),
nodeType: html.ElementNode,
Kids: make([]*Element, 0),
eventHandlers: make(map[string]EventHandler),
}
Order++
elem.SetID(fmt.Sprintf("_%s%d", elem.data, Order))
return elem
}
//SetAttributes sets attributes from an event element.
func (e *Element) SetAttributes(event *EventElement) {
e.Attributes = make([]html.Attribute, 0)
for key, value := range event.Properties {
e.Attributes = append(e.Attributes, html.Attribute{Key: key, Val: value})
}
}
//SetElement removes all child elemens and adds elem as first child
func (e *Element) SetElement(elem *Element) *Element {
e.RemoveElements()
return e.AddElement(elem)
}
//AddElement adds a child element
func (e *Element) AddElement(elem *Element) *Element {
if elem == nil {
panic("Cannot add nil element")
}
elem.Parent = e
e.Kids = append(e.Kids, elem)
return elem
}
//AddHTML parses the provided element and adds it to the current element. Returns a list of root elements from `html`.
//If em is not nil, for each HTML tag that has the `id` attribute set the corresponding element will be stored in the
//given ElementMap.
func (e *Element) AddHTML(innerHTML string, em ElementsMap) ([]*Element, error) {
elems, err := ParseElements(strings.NewReader(innerHTML), em)
if err != nil {
return nil, err
}
for _, elem := range elems {
e.Kids = append(e.Kids, elem)
}
return elems, nil
}
//RemoveElements remove all kids.
func (e *Element) RemoveElements() {
e.Kids = make([]*Element, 0)
}
//RemoveElement remove a specific kid
func (e *Element) RemoveElement(elem *Element) {
before := e.Kids
e.RemoveElements()
for _, kid := range before {
if kid.GetID() != elem.GetID() {
e.AddElement(kid)
}
}
}
//SetText Sets the element to hold ONLY the provided text
func (e *Element) SetText(text string) {
if e.nodeType == html.TextNode {
e.data = elementText(text)
} else {
e.RemoveElements()
e.AddElement(NewText(text))
}
}
//SetClass adds the given class name to the class attribute.
func (e *Element) SetClass(class string) {
prev, exists := e.GetAttribute("class")
if exists {
if strings.Contains(prev, class) {
return
}
}
e.SetAttribute("class", prev+" "+class)
}
//UnsetClass removes the given class name from the class attribute
func (e *Element) UnsetClass(class string) {
prev, exists := e.GetAttribute("class")
if !exists {
return
}
e.SetAttribute("class", strings.Replace(prev, class, "", -1))
}
//RemoveAttribute removes the provided attribute by name
func (e *Element) RemoveAttribute(key string) {
attributes := e.Attributes
e.Attributes = make([]html.Attribute, 0)
for _, attrib := range attributes {
if attrib.Key != key {
e.Attributes = append(e.Attributes, attrib)
}
}
}
//SetAttribute adds or set the attribute
func (e *Element) SetAttribute(key, val string) {
for i := range e.Attributes {
if e.Attributes[i].Key == key {
e.Attributes[i].Val = val
return
}
}
e.Attributes = append(e.Attributes, html.Attribute{Key: key, Val: val})
}
//GetAttribute returns value for attribute
func (e *Element) GetAttribute(key string) (string, bool) {
if e.Attributes == nil {
return "", false
}
for _, a := range e.Attributes {
if a.Key == key {
return a.Val, true
}
}
return "", false
}
//GetValue returns the value of the `value` attribute
func (e *Element) GetValue() string {
val, _ := e.GetAttribute("value")
return val
}
//GetID returns the value of the `id` attribute
func (e *Element) GetID() string {
val, _ := e.GetAttribute("id")
return val
}
//SetValue sets the 'value' attribute
func (e *Element) SetValue(val string) {
e.SetAttribute("value", val)
}
//SetID sets the `id` attribute
func (e *Element) SetID(id string) {
e.SetAttribute("id", id)
}
//Disable sets the `disabled` attribute
func (e *Element) Disable() {
e.SetAttribute("disabled", "true")
}
//Enable unsets the `disabled` attribute
func (e *Element) Enable() {
e.RemoveAttribute("disabled")
}
//AutoFocus adds the auto-focus atribute to the element
func (e *Element) AutoFocus() {
e.SetAttribute("autofocus", "")
}
//Hide if set, will not render the element.
func (e *Element) Hide() {
e.Hidden = true
}
//Show if set, will render the element.
func (e *Element) Show() {
e.Hidden = false
}
//Find returns the kid, or offspring with a specific `id` attribute value.
func (e *Element) Find(id string) *Element {
if e.GetID() == id {
return e
}
for i := range e.Kids {
elem := e.Kids[i].Find(id)
if elem != nil {
return elem
}
}
return nil
}
//OnKeyPressEvent register handler as an OnKeyPressed event.
func (e *Element) OnKeyPressEvent(event string, keyCode int, handler EventHandler) {
e.SetAttribute(event, fmt.Sprintf(`fire_keypressed_event(event,%d,'%s',this);`, keyCode, event))
e.eventHandlers[event] = handler
}
//OnEvent register an DOM element event.
func (e *Element) OnEvent(event string, handler EventHandler) {
e.SetAttribute(event, fmt.Sprintf(`fire_event('%s',this);`, event))
e.eventHandlers[event] = handler
}
func (e *Element) toNode() *html.Node {
node := &html.Node{Attr: e.Attributes, Data: e.data, Type: e.nodeType}
if e.Hidden {
node.Type = html.CommentNode // to a void returning null which may crash the caller
return node
}
for i := range e.Kids {
node.AppendChild(e.Kids[i].toNode())
}
return node
}
//Render renders the element.
func (e *Element) Render() error {
return render(e, Output)
}
//ProcessEvent fires the event provided
func (e *Element) ProcessEvent(event *Event) {
for _, input := range event.Inputs {
elementID := input.GetID()
if elementID != "" {
e.updateState(elementID, &input)
}
}
e.fireEvent(event.Name, event.Sender.GetID(), &event.Sender)
}
func (e *Element) updateState(elementID string, input *EventElement) {
for i := range e.Kids {
e.Kids[i].updateState(elementID, input)
}
if e.GetID() == elementID {
e.SetAttributes(input)
}
//special cases:
if e.data == atom.Select.String() {
for i := range e.Kids {
if e.Kids[i].GetValue() == e.GetValue() {
e.Kids[i].SetAttribute("selected", "true")
} else {
e.Kids[i].RemoveAttribute("selected")
}
}
}
}
func (e *Element) fireEvent(eventName string, senderID string, sender *EventElement) {
if senderID == "" {
return
}
kids := e.Kids //events may change the kids container
for i := range kids {
kids[i].fireEvent(eventName, senderID, sender)
}
if e.GetID() == senderID {
handler, exists := e.eventHandlers[eventName]
if exists {
handler(e, sender)
}
}
}
//stripchars strips chars from a string
func stripchars(input string, chars ...rune) string {
return strings.Map(
func(r rune) rune {
for _, c := range chars {
if c == r {
return -1
}
}
return r
}, input)
}
//make sure there are no CRLF in the input
func elementText(input string) string {
return strings.Trim(stripchars(input, '\r', '\n'), "\r\n\t ")
}