-
-
Notifications
You must be signed in to change notification settings - Fork 366
/
raw.go
128 lines (102 loc) · 2.03 KB
/
raw.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
package app
import (
"fmt"
"io"
"reflect"
"strings"
"github.com/maxence-charriere/go-app/v6/pkg/log"
)
type rawNode interface {
UI
raw() string
mount() error
}
// Raw returns a node from the given raw value.
//
// Note that it is not recommended to use this kind of node since there is no
// check on the raw string content.
func Raw(v string) UI {
v = strings.TrimSpace(v)
tag := rawOpenTag(v)
if tag == "" {
log.Error("creating raw node failed").
T("error", "no opening tag").
Panic()
return nil
}
return &raw{
tagName: tag,
outerHTML: v,
}
}
type raw struct {
parentNode UI
jsValue Value
tagName string
outerHTML string
}
func (r *raw) nodeType() reflect.Type {
return reflect.TypeOf(r)
}
func (r *raw) JSValue() Value {
return r.jsValue
}
func (r *raw) parent() UI {
return r.parentNode
}
func (r *raw) setParent(p UI) {
r.parentNode = p
}
func (r *raw) dismount() {
r.jsValue = nil
}
func (r *raw) raw() string {
return r.outerHTML
}
func (r *raw) mount() error {
if r.jsValue != nil {
return fmt.Errorf("node already mounted: %+v", r)
}
var v Value
switch r.tagName {
case "svg":
v = Window().
Get("document").
Call("createElementNS", "http://www.w3.org/2000/svg", r.tagName)
default:
v = Window().Get("document").Call("createElement", r.tagName)
}
tmpParent := Window().Get("document").Call("createElement", "div")
tmpParent.Call("appendChild", v)
v.Set("outerHTML", r.outerHTML)
r.jsValue = tmpParent.Get("firstChild")
return nil
}
func (r *raw) html(w io.Writer) {
r.htmlWithIndent(w, 0)
}
func (r *raw) htmlWithIndent(w io.Writer, indent int) {
writeIndent(w, indent)
w.Write(stob(r.outerHTML))
w.Write(ln())
}
func rawOpenTag(raw string) string {
raw = strings.TrimSpace(raw)
if strings.HasPrefix(raw, "</") || !strings.HasPrefix(raw, "<") {
return ""
}
end := -1
for i := 1; i < len(raw); i++ {
if raw[i] == ' ' ||
raw[i] == '\t' ||
raw[i] == '\n' ||
raw[i] == '>' {
end = i
break
}
}
if end <= 0 {
return ""
}
return raw[1:end]
}