gitstack

grindlemire/go-tui code browser

7.1 KB Go 363 lines 2026-06-03 ยท d15bb9f raw
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
363
package formatter

import (
	"go/format"
	"strings"

	"github.com/grindlemire/go-tui/internal/tuigen"
)

// printForLoop outputs a for loop.
func (p *printer) printForLoop(f *tuigen.ForLoop) {
	// Leading comments
	p.printLeadingComments(f.LeadingComments)

	p.writeIndent()
	p.write("for ")

	// Loop variables
	if f.Index != "" {
		p.write(f.Index)
		p.write(", ")
	}
	p.write(f.Value)
	p.write(" := range ")
	p.write(f.Iterable)
	p.write(" {")
	p.printTrailingComment(f.TrailingComments)
	p.newline()

	// Body
	p.depth++
	p.printOrphanComments(f.OrphanComments)
	p.printBody(f.Body)
	p.depth--

	p.writeIndent()
	p.write("}")
	p.newline()
}

// printIfStmt outputs an if statement.
func (p *printer) printIfStmt(stmt *tuigen.IfStmt) {
	// Leading comments
	p.printLeadingComments(stmt.LeadingComments)

	p.writeIndent()
	p.write("if ")
	p.write(stmt.Condition)
	p.write(" {")
	p.printTrailingComment(stmt.TrailingComments)
	p.newline()

	// Then branch
	p.depth++
	p.printOrphanComments(stmt.OrphanComments)
	p.printBody(stmt.Then)
	p.depth--

	// Else branch
	if len(stmt.Else) > 0 {
		p.writeIndent()
		p.write("} else ")

		// Check for else-if chain
		if len(stmt.Else) == 1 {
			if elseIf, ok := stmt.Else[0].(*tuigen.IfStmt); ok {
				// Print else-if without extra indent
				p.write("if ")
				p.write(elseIf.Condition)
				p.write(" {")
				p.printTrailingComment(elseIf.TrailingComments)
				p.newline()

				p.depth++
				p.printOrphanComments(elseIf.OrphanComments)
				p.printBody(elseIf.Then)
				p.depth--

				if len(elseIf.Else) > 0 {
					p.printElseBranch(elseIf.Else)
				} else {
					p.writeIndent()
					p.write("}")
					p.newline()
				}
				return
			}
		}

		// Regular else
		p.write("{")
		p.newline()
		p.depth++
		p.printBody(stmt.Else)
		p.depth--
		p.writeIndent()
		p.write("}")
		p.newline()
	} else {
		p.writeIndent()
		p.write("}")
		p.newline()
	}
}

// printElseBranch handles recursive else-if chains.
func (p *printer) printElseBranch(nodes []tuigen.Node) {
	p.writeIndent()
	p.write("} else ")

	if len(nodes) == 1 {
		if elseIf, ok := nodes[0].(*tuigen.IfStmt); ok {
			p.write("if ")
			p.write(elseIf.Condition)
			p.write(" {")
			p.printTrailingComment(elseIf.TrailingComments)
			p.newline()

			p.depth++
			p.printOrphanComments(elseIf.OrphanComments)
			p.printBody(elseIf.Then)
			p.depth--

			if len(elseIf.Else) > 0 {
				p.printElseBranch(elseIf.Else)
			} else {
				p.writeIndent()
				p.write("}")
				p.newline()
			}
			return
		}
	}

	p.write("{")
	p.newline()
	p.depth++
	p.printBody(nodes)
	p.depth--
	p.writeIndent()
	p.write("}")
	p.newline()
}

// printLetBinding outputs a let binding using := syntax.
func (p *printer) printLetBinding(let *tuigen.LetBinding) {
	// Leading comments
	p.printLeadingComments(let.LeadingComments)

	p.writeIndent()

	// Always emit :=
	p.write(let.Name)
	p.write(" := ")

	if let.Call != nil {
		p.write("@")
		p.write(let.Call.Name)
		p.write("(")
		p.write(formatInlineBlockComments(let.Call.Args))
		p.write(")")
		p.newline()
		return
	}

	if let.Expr != "" && let.Element == nil {
		p.write("@")
		p.write(let.Expr)
		p.newline()
		return
	}

	// Element RHS - print inline or multi-line
	savedDepth := p.depth
	p.depth = 0

	p.buf.WriteString("<")
	p.buf.WriteString(let.Element.Tag)

	// Emit ref={expr} if present (extracted from attributes during parsing)
	if let.Element.RefExpr != nil {
		p.buf.WriteString(" ref={")
		p.buf.WriteString(let.Element.RefExpr.Code)
		p.buf.WriteString("}")
	}

	for _, attr := range let.Element.Attributes {
		p.buf.WriteString(" ")
		p.printAttribute(attr)
	}

	if let.Element.SelfClose {
		p.buf.WriteString(" />")
		p.newline()
		p.depth = savedDepth
		return
	}

	p.buf.WriteString(">")

	// Check if children should be rendered inline (preserving user's source layout)
	if let.Element.InlineChildren && p.canStructurallyInline(let.Element.Children) {
		p.printChildrenInline(let.Element.Children)
		p.buf.WriteString("</")
		p.buf.WriteString(let.Element.Tag)
		p.buf.WriteString(">")
		p.newline()
		p.depth = savedDepth
		return
	}

	// Multi-line children
	p.newline()
	p.depth = savedDepth + 1
	p.printBody(let.Element.Children)
	p.depth = savedDepth
	p.writeIndent()
	p.buf.WriteString("</")
	p.buf.WriteString(let.Element.Tag)
	p.buf.WriteString(">")
	p.newline()
}

// printComponentCall outputs a component call.
func (p *printer) printComponentCall(call *tuigen.ComponentCall) {
	// Leading comments
	p.printLeadingComments(call.LeadingComments)

	p.writeIndent()
	p.write("@")
	p.write(call.Name)
	p.write("(")

	if call.MultiLineArgs {
		args := splitTopLevelArgs(call.Args)
		p.newline()
		p.depth++
		for i, arg := range args {
			p.writeIndent()
			p.write(arg)
			p.write(",")
			if i < len(args)-1 {
				p.newline()
			}
		}
		p.depth--
		p.newline()
		p.writeIndent()
	} else {
		p.write(formatInlineBlockComments(call.Args))
	}

	p.write(")")

	if len(call.Children) > 0 {
		p.write(" {")
		p.printTrailingComment(call.TrailingComments)
		p.newline()

		p.depth++
		p.printBody(call.Children)
		p.depth--

		p.writeIndent()
		p.write("}")
	} else {
		p.printTrailingComment(call.TrailingComments)
	}
	p.newline()
}

// splitTopLevelArgs splits a Go argument string by top-level commas,
// respecting nested parentheses, brackets, braces, and string literals.
func splitTopLevelArgs(args string) []string {
	var result []string
	depth := 0
	inString := false
	inRune := false
	inBacktick := false
	start := 0

	for i := 0; i < len(args); i++ {
		ch := args[i]
		switch {
		case inBacktick:
			if ch == '`' {
				inBacktick = false
			}
		case inString:
			switch ch {
			case '\\':
				i++ // skip escaped char
			case '"':
				inString = false
			}
		case inRune:
			switch ch {
			case '\\':
				i++
			case '\'':
				inRune = false
			}
		default:
			switch ch {
			case '"':
				inString = true
			case '\'':
				inRune = true
			case '`':
				inBacktick = true
			case '(', '[', '{':
				depth++
			case ')', ']', '}':
				depth--
			case ',':
				if depth == 0 {
					arg := strings.TrimSpace(args[start:i])
					if arg != "" {
						result = append(result, arg)
					}
					start = i + 1
				}
			}
		}
	}

	// Last argument (may have trailing comma already trimmed by parser)
	last := strings.TrimSpace(args[start:])
	if last != "" {
		result = append(result, last)
	}

	return result
}

// formatGoCode runs gofmt on a top-level Go declaration or function.
func formatGoCode(code string) string {
	wrapped := "package p\n\n" + code + "\n"
	formatted, err := format.Source([]byte(wrapped))
	if err != nil {
		return code
	}
	result := string(formatted)
	result = strings.TrimPrefix(result, "package p\n\n")
	result = strings.TrimSuffix(result, "\n")
	return result
}

// printGoFunc outputs a top-level Go function.
func (p *printer) printGoFunc(fn *tuigen.GoFunc) {
	p.printLeadingComments(fn.LeadingComments)
	p.write(formatGoCode(fn.Code))
	p.printTrailingComment(fn.TrailingComments)
	p.newline()
}

// printGoDecl outputs a top-level Go declaration (type, const, var).
func (p *printer) printGoDecl(decl *tuigen.GoDecl) {
	p.printLeadingComments(decl.LeadingComments)
	p.write(formatGoCode(decl.Code))
	p.printTrailingComment(decl.TrailingComments)
	p.newline()
}