-
Notifications
You must be signed in to change notification settings - Fork 0
/
element.go
362 lines (322 loc) · 8.13 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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
package objhtml
import (
"bytes"
"crypto/md5"
"fmt"
"io"
"reflect"
"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 bytes.Buffer
//Output io.Writer = os.Stdout
)
//Element represents a DOM element and its state.
type (
//EventHandler handler for DOM event.
EventHandler func(sender *Element, event *EventElement, change *Element)
EventHandlerStruct struct {
Func EventHandler
Sender *Element
Change *Element
}
Element struct {
//Parent the parent element
Parent *Element
//eventHandlers holds event handlers for events
eventHandlers map[string]EventHandlerStruct
//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
}
)
//Render renders the element.
func (e *Element) Render() error {
return ElementRender(e, &Output)
}
func ElementRender(e *Element, w io.Writer) error {
renderMutex.Lock()
defer renderMutex.Unlock()
node := e.toNode()
h := md5.New()
err := html.Render(h, node)
if err != nil {
return err
}
sum := h.Sum(nil)
if reflect.DeepEqual(e.renderHash, sum) {
return nil //already rendered
}
e.renderHash = sum
err = html.Render(w, node)
if err != nil {
return err
}
_, err = fmt.Fprintln(w)
return err
}
//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]EventHandlerStruct),
}
Order++
//elem.SetID(fmt.Sprintf("_%s%d", elem.data, Order))
elem.SetID(Ids.New("_"))
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})
}
}
//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
}
//AddElements adds a multiple child elements
func (e *Element) AddElements(elems ...*Element) []*Element {
if elems != nil {
for _, el := range elems {
e.AddElement(el)
}
}
return elems
}
//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
}
//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)
}
}
}
//RemoveElements remove all kids.
func (e *Element) RemoveElements() {
e.Kids = make([]*Element, 0)
}
//SetText Sets the element to hold ONLY the provided text
func (e *Element) SetText(text string) {
if e.nodeType == html.TextNode {
e.data = 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))
}
//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})
}
//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)
}
}
}
//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
}
//SetValue set the `value` attribute
func (e *Element) SetValue(value string) {
e.SetAttribute("value", value)
}
//GetValue returns the value of the `value` attribute
func (e *Element) GetValue() string {
val, _ := e.GetAttribute("value")
return val
}
//SetID sets the `id` attribute
func (e *Element) SetID(id string) {
e.SetAttribute("id", id)
}
//GetID returns the value of the `id` attribute
func (e *Element) GetID() string {
val, _ := e.GetAttribute("id")
return val
}
//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")
}
//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
}
//OnEvent register an DOM element event.
func (e *Element) OnEvent(event string, handler EventHandler, change *Element) {
e.SetAttribute("onevent", "")
Handler := new(EventHandlerStruct)
Handler.Func = handler
Handler.Sender = e
if change != nil {
Handler.Change = change
}
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
}
//ProcessEvent fires the event provided
func (e *Element) ProcessEvent(event *Event) {
if e == nil {
return
}
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) {
if e == nil {
return
}
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 e == nil {
return
}
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 {
fmt.Println(eventName)
//, changeID string, change *Element
handler, exists := e.eventHandlers[eventName]
fmt.Println(eventName, exists)
if exists {
handler.Func(e, sender, handler.Change)
}
}
}