forked from travissimon/ghaml
/
view_writer.go
277 lines (227 loc) · 7.33 KB
/
view_writer.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
package main
import (
"bytes"
"github.com/travissimon/formatting"
"io"
"strings"
)
type ViewWriter struct {
context *ParseContext
rootNode *Node
writer io.Writer
destinationName string
}
func NewViewWriter(wr io.Writer, context *ParseContext, rootNode *Node, writerName string) *ViewWriter {
vw := &ViewWriter{
context: context,
rootNode: rootNode,
writer: wr,
destinationName: writerName,
}
return vw
}
func (w *ViewWriter) WriteView() {
src := formatting.NewIndentingWriter(w.writer)
htmlArr, srcOut := w.processNodes()
src.Printf("package %s\n", w.context.pkg)
src.Println("")
src.Println("// THIS IS A GENERATED FILE, EDITS WILL BE OVERWRITTEN")
src.Println("// EDIT THE .haml FILE INSTEAD")
src.Println("")
src.Println("import (")
src.IncrIndent()
src.Println("\"fmt\"")
src.Println("\"net/http\"")
for _, imp := range w.context.imports {
src.Printf("%q\n", imp)
}
src.DecrIndent()
src.Println(")")
src.Println("")
src.Printf("func New%sWriter(data %s) (*%sWriter) {\n", w.destinationName, w.context.dataType, w.destinationName)
src.IncrIndent()
src.Printf("wr := &%sWriter {\n", w.destinationName)
src.IncrIndent()
src.Printf("data: data,\n")
src.DecrIndent()
src.Println("}")
src.Println("")
src.Println("return wr")
src.DecrIndent()
src.Println("}")
src.Println("")
src.Printf("type %sWriter struct {\n", w.destinationName)
src.IncrIndent()
src.Printf("data %s\n", w.context.dataType)
src.DecrIndent()
src.Println("}")
src.Println("")
src.Printf("var %sHtml = [...]string{\n", w.destinationName)
src.Println(htmlArr)
src.Println("}")
src.Println("")
src.Printf("func (wr %sWriter) Execute(w http.ResponseWriter, r *http.Request) {\n", w.destinationName)
src.IncrIndent()
src.Println("wr.ExecuteData(w, r, wr.data)")
src.DecrIndent()
src.Println("}")
src.Println("")
src.Printf("func (wr *%sWriter) ExecuteData(w http.ResponseWriter, r *http.Request, data %s) {\n", w.destinationName, w.context.dataType)
// output from processNodes
// This is calls to htmlArray and code generated Prints
src.Print(srcOut)
src.Println("}")
}
// processNodes generates code from the parsed haml nodes
// htmlArray is a string array of the raw html parts.
// src is the go source that calls html array, and then user defined code.
// usually looks like this:
// fmt.Fprint(w, HtmlArray[0])
// fmt.Fprint(w, "Custom string: ", data)
// fmt.Fprint(w, HtmlArray[1]) ...
func (w *ViewWriter) processNodes() (htmlArray string, src string) {
htmlBuffer := bytes.NewBuffer(make([]byte, 0))
htmlWriter := formatting.NewIndentingWriter(htmlBuffer)
srcBuffer := bytes.NewBuffer(make([]byte, 0))
srcWriter := formatting.NewIndentingWriter(srcBuffer)
// initialise opening quote for htlmArray
htmlWriter.Print("`")
// initialise starting indent for src
srcWriter.IncrIndent()
currentHtmlIndex := 0
for n := w.rootNode.children.Front(); n != nil; n = n.Next() {
currentHtmlIndex = w.writeNode(n.Value.(*Node), htmlWriter, srcWriter, currentHtmlIndex)
}
// close quote for html Array
htmlWriter.Print("`,")
htmlArray = htmlBuffer.String()
src = srcBuffer.String()
return
}
// Recursive function to write parsed HAML Nodes
func (w *ViewWriter) writeNode(nd *Node, haml *formatting.IndentingWriter, src *formatting.IndentingWriter, currentHtmlIndex int) int {
if nd.name == "code_output" {
return w.writeCodeOutput(nd, haml, src, currentHtmlIndex)
} else if nd.name == "code_execution" {
return w.writeCodeExecution(nd, haml, src, currentHtmlIndex)
}
haml.Printf("<%s", nd.name)
if nd.id != nil {
w.writeAttribute(nd.id, haml)
}
if nd.class != nil {
w.writeAttribute(nd.class, haml)
}
for attrEl := nd.attributes.Front(); attrEl != nil; attrEl = attrEl.Next() {
attr := attrEl.Value.(*nameValueStr)
w.writeAttribute(attr, haml)
}
if nd.selfClosing {
haml.Println(" />`)")
return currentHtmlIndex
} else {
haml.Print(">")
}
// Outputting text.
// If tag only contains short text, add it on same line
if w.canChildContentFitOnOneLine(nd) {
haml.Printf("%s</%s>\n", nd.text, nd.name)
return currentHtmlIndex
}
// We either have long text, child tags or both
// so we add it as indented child content
haml.Println("")
haml.IncrIndent()
if len(nd.text) > 0 {
w.writeLongText(nd.text, haml)
}
for n := nd.children.Front(); n != nil; n = n.Next() {
currentHtmlIndex = w.writeNode(n.Value.(*Node), haml, src, currentHtmlIndex)
}
haml.DecrIndent()
haml.Printf("</%s>\n", nd.name)
return currentHtmlIndex
}
var TEXT_BREAK_LENGTH = 100
func (vw *ViewWriter) writeLongText(text string, w *formatting.IndentingWriter) {
// create index of spaces in string
spaces := vw.getWhitespaceIndicies(text)
// split string on space less than MAX_STRING_LENGTH
start := 0
for _, idx := range spaces {
distance := idx - start
if distance > TEXT_BREAK_LENGTH {
w.Println(text[start:idx])
start = idx + 1
}
}
w.Println(text[start:])
}
func (vw *ViewWriter) getWhitespaceIndicies(text string) []int {
spaces := make([]int, 0, 255)
for i, c := range text {
switch c {
case ' ', '\t', '\n':
spaces = append(spaces, i)
}
}
return spaces
}
// Child content can only fit on one line when there is short
// text and no child nodes
func (w *ViewWriter) canChildContentFitOnOneLine(nd *Node) bool {
return len(nd.text) < TEXT_BREAK_LENGTH && nd.children.Len() == 0
}
func (w *ViewWriter) writeAttribute(attribute *nameValueStr, haml *formatting.IndentingWriter) {
haml.Printf(" %s=\"%s\"", attribute.name, attribute.value)
}
func (w *ViewWriter) writeCodeOutput(nd *Node, haml *formatting.IndentingWriter, src *formatting.IndentingWriter, currentHtmlIndex int) int {
// end most recent haml output
haml.Println("`,")
// start next haml output (which will follow this code output
haml.Println("`")
// All call to write html from array
src.Printf("fmt.Fprint(w, %sHtml[%d])\n", w.destinationName, currentHtmlIndex)
currentHtmlIndex++
// add call to print output
src.Printf("fmt.Fprint(w, %s)\n", nd.text)
for n := nd.children.Front(); n != nil; n = n.Next() {
currentHtmlIndex = w.writeNode(n.Value.(*Node), haml, src, currentHtmlIndex)
}
return currentHtmlIndex
}
func (w *ViewWriter) writeCodeExecution(nd *Node, haml *formatting.IndentingWriter, src *formatting.IndentingWriter, currentHtmlIndex int) int {
// end most recent haml output
haml.Println("`,")
// start next haml output (which will follow this code output
haml.Println("`")
// All call to write html from array
src.Printf("fmt.Fprint(w, %sHtml[%d])\n", w.destinationName, currentHtmlIndex)
currentHtmlIndex++
// attempt to keep formatting across user code.
// Here we're checking to see if this is the end of a block statement
// if so, we need to decrease indent
first := getFirstChar(nd.text)
if first == '}' {
src.DecrIndent()
}
// add user's code
src.Printf("%s\n", nd.text)
// If user code ends in {, incr indent as they started a block statement
last := getLastChar(nd.text)
if last == '{' {
src.IncrIndent()
}
for n := nd.children.Front(); n != nil; n = n.Next() {
currentHtmlIndex = w.writeNode(n.Value.(*Node), haml, src, currentHtmlIndex)
}
return currentHtmlIndex
}
func getFirstChar(s string) byte {
trimmed := strings.TrimLeft(s, "\t ")
return trimmed[0]
}
func getLastChar(s string) byte {
trimmed := strings.TrimRight(s, "\t ")
return trimmed[len(trimmed)-1]
}