gitstack

grindlemire/go-tui code browser

18.1 KB Go 523 lines 2026-06-13 · 488fbfe 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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
package tuigen

import (
	"fmt"
	"strconv"
	"strings"
)

// generateChildren generates code for element children.
func (g *Generator) generateChildren(parentVar string, children []Node) {
	g.generateChildrenWithRefs(parentVar, children, false, false, false)
}

// generateChildrenWithRefs generates code for element children with ref context tracking.
func (g *Generator) generateChildrenWithRefs(parentVar string, children []Node, inLoop bool, inConditional bool, inForLoop bool) {
	for _, child := range children {
		switch c := child.(type) {
		case *Element:
			g.generateElementWithRefs(c, parentVar, inLoop, inConditional, inForLoop)
		case *LetBinding:
			g.generateLetBinding(c, parentVar, inConditional, inForLoop)
		case *ForLoop:
			g.generateForLoopWithRefs(c, parentVar, inLoop, inConditional, inForLoop)
		case *IfStmt:
			g.generateIfStmtWithRefs(c, parentVar, inLoop, inForLoop)
		case *GoExpr:
			// GoExpr as child - create text element with the expression
			varName := g.nextVar()
			g.writef("%s := tui.New(tui.WithText(%s))\n", varName, textExpr(c.Code))
			g.writef("%s.AddChild(%s)\n", parentVar, varName)
		case *TextContent:
			// TextContent as child - create text element
			varName := g.nextVar()
			g.writef("%s := tui.New(tui.WithText(%s))\n", varName, strconv.Quote(c.Text))
			g.writef("%s.AddChild(%s)\n", parentVar, varName)
		case *RawGoExpr:
			// RawGoExpr is a variable reference - add directly
			g.writef("%s.AddChild(%s)\n", parentVar, c.Code)
		case *ComponentCall:
			g.generateComponentCallWithRefs(c, parentVar, inConditional, inForLoop)
		case *ComponentExpr:
			g.generateComponentExpr(c, parentVar)
		case *ChildrenSlot:
			// Expand the children parameter
			// In method templs, children are stored on the receiver struct
			childrenExpr := "children"
			if g.currentReceiver != "" {
				childrenExpr = g.currentReceiver + ".children"
			}
			g.writef("for _, __child := range %s {\n", childrenExpr)
			g.indent++
			g.writef("%s.AddChild(__child)\n", parentVar)
			g.indent--
			g.writeln("}")
		}
	}
}

// generateBodyNodeWithRefs generates code for a node with ref context tracking.
func (g *Generator) generateBodyNodeWithRefs(node Node, parentVar string, inLoop bool, inConditional bool, inForLoop bool) {
	switch n := node.(type) {
	case *Element:
		g.generateElementWithRefs(n, parentVar, inLoop, inConditional, inForLoop)
	case *LetBinding:
		g.generateLetBinding(n, parentVar, inConditional, inForLoop)
	case *ForLoop:
		g.generateForLoopWithRefs(n, parentVar, inLoop, inConditional, inForLoop)
	case *IfStmt:
		g.generateIfStmtWithRefs(n, parentVar, inLoop, inForLoop)
	case *GoCode:
		g.generateGoCode(n)
	case *GoExpr:
		if parentVar != "" {
			varName := g.nextVar()
			g.writef("%s := tui.New(tui.WithText(%s))\n", varName, textExpr(n.Code))
			g.writef("%s.AddChild(%s)\n", parentVar, varName)
		} else {
			g.writef("%s\n", n.Code)
		}
	case *TextContent:
		if parentVar != "" {
			varName := g.nextVar()
			g.writef("%s := tui.New(tui.WithText(%s))\n", varName, strconv.Quote(n.Text))
			g.writef("%s.AddChild(%s)\n", parentVar, varName)
		}
	case *RawGoExpr:
		if parentVar != "" {
			g.writef("%s.AddChild(%s)\n", parentVar, n.Code)
		}
	case *ComponentCall:
		g.generateComponentCallWithRefs(n, parentVar, inConditional, inForLoop)
	case *ComponentExpr:
		g.generateComponentExpr(n, parentVar)
	case *ChildrenSlot:
		if parentVar != "" {
			// In method templs, children are stored on the receiver struct
			childrenExpr := "children"
			if g.currentReceiver != "" {
				childrenExpr = g.currentReceiver + ".children"
			}
			g.writef("for _, __child := range %s {\n", childrenExpr)
			g.indent++
			g.writef("%s.AddChild(__child)\n", parentVar)
			g.indent--
			g.writeln("}")
		}
	}
}

// generateGoCode generates a raw Go statement.
func (g *Generator) generateGoCode(gc *GoCode) {
	g.writef("%s\n", gc.Code)
}

// generateGoFunc generates a top-level Go function.
func (g *Generator) generateGoFunc(fn *GoFunc) {
	g.generatePassthroughCode(fn.Code, fn.Position)
	g.writeln("")
}

// generateGoDecl generates a top-level Go declaration (type, const, var).
func (g *Generator) generateGoDecl(decl *GoDecl) {
	g.generatePassthroughCode(decl.Code, decl.Position)
	g.writeln("")
}

// generatePassthroughCode generates code that is passed through from .gsx to .go
// and records source map mappings for each line.
func (g *Generator) generatePassthroughCode(code string, pos Position) {
	lines := strings.Split(code, "\n")
	// Convert to 0-indexed. We count newlines in the Code to determine the
	// actual starting line, since Position.Line may point to inside the declaration.
	codeLines := strings.Count(code, "\n") + 1
	// gsxLine is where this code block ENDS, so start = end - count + 1
	// But we use Position.Line as the start, just convert to 0-indexed
	gsxLine := pos.Line - 1 // Convert to 0-indexed

	for i, line := range lines {
		// Record mapping for this line
		if g.sourceMap != nil {
			g.sourceMap.AddMapping(SourceMapping{
				GoLine:  g.currentLine,
				GoCol:   0,
				GsxLine: gsxLine + i,
				GsxCol:  0,
				Length:  len(line),
			})
		}
		g.writeln(line)
	}
	_ = codeLines // unused for now
}

// generateComponentCallWithRefs generates code for a component call.
// Returns the variable name holding the result.
//
// For struct component mounts (IsStructMount=true), generates:
//
//	app.Mount(receiverVar, index, func() tui.Component { return Name(args) })
//
// For function component calls (IsStructMount=false), generates the existing
// view struct pattern: varName := Name(args)
//
// Function templs defined in the same file are always called directly (not mounted),
// even when inside a method templ. They are stateless views — calling them fresh
// each render ensures updated props. Cross-package function templs that are unknown
// to the generator still get mounted, but their view types have UpdateProps so the
// mount system can refresh them.
func (g *Generator) generateComponentCallWithRefs(call *ComponentCall, parentVar string, inConditional bool, inForLoop bool) string {
	if call.IsStructMount && !g.functionTempls[call.Name] {
		return g.generateStructMount(call, parentVar)
	}
	return g.generateFunctionComponentCall(call, parentVar, inConditional, inForLoop)
}

// returnsElement reports whether a ComponentCall produces a *tui.Element directly
// (true for actual struct mounts) vs a view struct that needs .Root (false for
// function templs, even when IsStructMount is set by parser context).
func (g *Generator) returnsElement(call *ComponentCall) bool {
	return call.IsStructMount && !g.functionTempls[call.Name]
}

// generateStructMount generates an app.Mount() call for struct components.
// Returns the variable name holding the *tui.Element result.
func (g *Generator) generateStructMount(call *ComponentCall, parentVar string) string {
	varName := g.nextVar()
	baseIndex := g.mountIndex
	g.mountIndex++

	// Component calls have no key attribute; a keyed wrapper element keys them.
	indexExpr := g.mountKeyExpr(baseIndex)

	// Build children slice if the component call has children
	childrenVar := ""
	if len(call.Children) > 0 {
		childrenVar = varName + "_children"
		g.writef("%s := []*tui.Element{}\n", childrenVar)

		for _, child := range call.Children {
			switch c := child.(type) {
			case *Element:
				elemVar := g.generateElement(c, "")
				g.writef("%s = append(%s, %s)\n", childrenVar, childrenVar, elemVar)
			case *ComponentCall:
				innerVar := g.generateComponentCallWithRefs(c, "", false, false)
				if g.returnsElement(c) {
					g.writef("%s = append(%s, %s)\n", childrenVar, childrenVar, innerVar)
				} else {
					g.writef("%s = append(%s, %s.Root)\n", childrenVar, childrenVar, innerVar)
				}
			case *LetBinding:
				g.generateLetBinding(c, "", false, false)
				g.writef("%s = append(%s, %s)\n", childrenVar, childrenVar, c.Name)
			case *ForLoop:
				g.generateForLoopForSlice(c, childrenVar)
			case *IfStmt:
				g.generateIfStmtForSlice(c, childrenVar)
			case *GoExpr:
				elemVar := g.nextVar()
				g.writef("%s := tui.New(tui.WithText(%s))\n", elemVar, textExpr(c.Code))
				g.writef("%s = append(%s, %s)\n", childrenVar, childrenVar, elemVar)
			case *TextContent:
				elemVar := g.nextVar()
				g.writef("%s := tui.New(tui.WithText(%s))\n", elemVar, strconv.Quote(c.Text))
				g.writef("%s = append(%s, %s)\n", childrenVar, childrenVar, elemVar)
			case *RawGoExpr:
				g.writef("%s = append(%s, %s)\n", childrenVar, childrenVar, c.Code)
			}
		}
	}

	// Generate: varName := app.Mount(receiverVar, indexExpr, func() tui.Component { return Name(args) })
	g.writef("%s := app.Mount(%s, %s, func() tui.Component {\n", varName, g.currentReceiver, indexExpr)
	g.indent++

	// Build the argument list, appending children if present
	args := call.Args
	if childrenVar != "" {
		if args == "" {
			args = childrenVar
		} else {
			args = args + ", " + childrenVar
		}
	}

	if args == "" {
		g.writef("return %s()\n", call.Name)
	} else {
		g.writef("return %s(%s)\n", call.Name, args)
	}
	g.indent--
	g.writeln("})")

	// Add to parent if specified — Mount returns *tui.Element directly
	if parentVar != "" {
		g.writef("%s.AddChild(%s)\n", parentVar, varName)
	}

	return varName
}

// generateFunctionComponentCall generates a function component call (existing behavior).
// Returns the variable name holding the view struct result.
func (g *Generator) generateFunctionComponentCall(call *ComponentCall, parentVar string, inConditional bool, inForLoop bool) string {
	varName := g.nextVar()

	// When inside a block scope in a function templ, use assignment (=) instead of
	// short declaration (:=) because the variable will be hoisted to function scope.
	// Method templs don't need hoisting since they don't have watcher/bind/unbind
	// wiring that references component vars outside the block.
	// Exception: for-loop bodies use := (local per iteration) and collect views into a slice.
	decl := ":="
	if inConditional && !inForLoop && g.currentReceiver == "" {
		decl = "="
	}

	if len(call.Children) == 0 {
		// No children - simple call, returns view struct
		if call.Args == "" {
			g.writef("%s %s %s()\n", varName, decl, call.Name)
		} else {
			g.writef("%s %s %s(%s)\n", varName, decl, call.Name, call.Args)
		}
	} else {
		// Has children - build children slice first
		childrenVar := g.nextVar() + "_children"
		g.writef("%s := []*tui.Element{}\n", childrenVar)

		// Generate each child and append to slice
		for _, child := range call.Children {
			switch c := child.(type) {
			case *Element:
				elemVar := g.generateElement(c, "")
				g.writef("%s = append(%s, %s)\n", childrenVar, childrenVar, elemVar)
			case *ComponentCall:
				innerVar := g.generateComponentCallWithRefs(c, "", false, false)
				if g.returnsElement(c) {
					// Struct mount returns *tui.Element directly
					g.writef("%s = append(%s, %s)\n", childrenVar, childrenVar, innerVar)
				} else {
					// Function component returns view struct — extract .Root
					g.writef("%s = append(%s, %s.Root)\n", childrenVar, childrenVar, innerVar)
				}
			case *LetBinding:
				g.generateLetBinding(c, "", false, false)
				g.writef("%s = append(%s, %s)\n", childrenVar, childrenVar, c.Name)
			case *ForLoop:
				// For loops generate multiple elements - use a temp slice
				g.generateForLoopForSlice(c, childrenVar)
			case *IfStmt:
				// If statements may or may not generate elements
				g.generateIfStmtForSlice(c, childrenVar)
			case *GoExpr:
				// Expression - wrap in text element
				elemVar := g.nextVar()
				g.writef("%s := tui.New(tui.WithText(%s))\n", elemVar, textExpr(c.Code))
				g.writef("%s = append(%s, %s)\n", childrenVar, childrenVar, elemVar)
			case *TextContent:
				elemVar := g.nextVar()
				g.writef("%s := tui.New(tui.WithText(%s))\n", elemVar, strconv.Quote(c.Text))
				g.writef("%s = append(%s, %s)\n", childrenVar, childrenVar, elemVar)
			case *RawGoExpr:
				g.writef("%s = append(%s, %s)\n", childrenVar, childrenVar, c.Code)
			}
		}

		// Call component with children
		if call.Args == "" {
			g.writef("%s %s %s(%s)\n", varName, decl, call.Name, childrenVar)
		} else {
			g.writef("%s %s %s(%s, %s)\n", varName, decl, call.Name, call.Args, childrenVar)
		}
	}

	// Track this component call for watcher aggregation
	g.componentVars = append(g.componentVars, componentVarEntry{
		name:          varName,
		componentName: call.Name,
		inConditional: inConditional || inForLoop,
		inForLoop:     inForLoop,
	})

	// Add to parent if specified - use .Root to get the element from the view struct
	if parentVar != "" {
		g.writef("%s.AddChild(%s.Root)\n", parentVar, varName)
	}

	// For loop-scoped component calls in function templs, collect views for
	// watcher/bind/unbind aggregation across all iterations.
	if inForLoop && g.currentReceiver == "" {
		g.writef("%s_views = append(%s_views, %s)\n", varName, varName, varName)
	}

	return varName
}

// generateComponentExpr generates code for a component expression like @c.textarea.
// It calls .Render() on the expression and adds the result to the parent.
func (g *Generator) generateComponentExpr(expr *ComponentExpr, parentVar string) {
	varName := g.nextVar()
	g.writef("%s := %s.Render(app)\n", varName, expr.Expr)
	if parentVar != "" {
		g.writef("%s.AddChild(%s)\n", parentVar, varName)
	}

	// Track receiver field accesses for BindApp generation in method components.
	// e.g., @c.settingsView → track "settingsView" so generateBindApp can bind it.
	g.trackComponentExprField(expr.Expr)
}

// generateForLoopForSlice generates a for loop that appends elements to a slice.
// This is the children-building path (component slot children), not the main body path.
// Component calls here pass inForLoop=false because they build element slices to pass
// as children, not function-level watcher/bind/unbind aggregation.
func (g *Generator) generateForLoopForSlice(loop *ForLoop, sliceVar string) {
	// Push the loop index variable for use in struct mount calls
	idxVar := g.pushLoopIndex(loop)
	defer g.popLoopIndex()

	// Build loop header - may need to generate a synthetic index variable
	var loopVars string
	if loop.Index != "" && loop.Index != "_" {
		loopVars = fmt.Sprintf("%s, %s", loop.Index, loop.Value)
	} else if loop.Index == "_" {
		loopVars = fmt.Sprintf("%s, %s", idxVar, loop.Value)
	} else {
		loopVars = fmt.Sprintf("%s, %s", idxVar, loop.Value)
	}

	g.writef("for %s := range %s {\n", loopVars, loop.Iterable)
	g.indent++

	// Silence unused variable warnings
	if loop.Index != "" && loop.Index != "_" {
		g.writef("_ = %s\n", loop.Index)
	} else {
		g.writef("_ = %s\n", idxVar)
	}

	for _, node := range loop.Body {
		switch n := node.(type) {
		case *Element:
			elemVar := g.generateElement(n, "")
			g.writef("%s = append(%s, %s)\n", sliceVar, sliceVar, elemVar)
		case *ComponentCall:
			callVar := g.generateComponentCallWithRefs(n, "", true, false)
			if g.returnsElement(n) {
				g.writef("%s = append(%s, %s)\n", sliceVar, sliceVar, callVar)
			} else {
				g.writef("%s = append(%s, %s.Root)\n", sliceVar, sliceVar, callVar)
			}
		case *ComponentExpr:
			elemVar := g.nextVar()
			g.writef("%s := %s.Render(app)\n", elemVar, n.Expr)
			g.writef("%s = append(%s, %s)\n", sliceVar, sliceVar, elemVar)
		case *LetBinding:
			g.generateLetBinding(n, "", true, false)
			g.writef("%s = append(%s, %s)\n", sliceVar, sliceVar, n.Name)
		case *ForLoop:
			g.generateForLoopForSlice(n, sliceVar)
		case *IfStmt:
			g.generateIfStmtForSlice(n, sliceVar)
		case *GoCode:
			g.generateGoCode(n)
		case *GoExpr:
			elemVar := g.nextVar()
			g.writef("%s := tui.New(tui.WithText(%s))\n", elemVar, textExpr(n.Code))
			g.writef("%s = append(%s, %s)\n", sliceVar, sliceVar, elemVar)
		}
	}

	g.indent--
	g.writeln("}")
}

// generateIfStmtForSlice generates an if statement that appends elements to a slice.
func (g *Generator) generateIfStmtForSlice(stmt *IfStmt, sliceVar string) {
	g.writef("if %s {\n", stmt.Condition)
	g.indent++

	for _, node := range stmt.Then {
		switch n := node.(type) {
		case *Element:
			elemVar := g.generateElement(n, "")
			g.writef("%s = append(%s, %s)\n", sliceVar, sliceVar, elemVar)
		case *ComponentCall:
			callVar := g.generateComponentCallWithRefs(n, "", true, false)
			if g.returnsElement(n) {
				g.writef("%s = append(%s, %s)\n", sliceVar, sliceVar, callVar)
			} else {
				g.writef("%s = append(%s, %s.Root)\n", sliceVar, sliceVar, callVar)
			}
		case *ComponentExpr:
			elemVar := g.nextVar()
			g.writef("%s := %s.Render(app)\n", elemVar, n.Expr)
			g.writef("%s = append(%s, %s)\n", sliceVar, sliceVar, elemVar)
		case *LetBinding:
			g.generateLetBinding(n, "", true, false)
			g.writef("%s = append(%s, %s)\n", sliceVar, sliceVar, n.Name)
		case *ForLoop:
			g.generateForLoopForSlice(n, sliceVar)
		case *IfStmt:
			g.generateIfStmtForSlice(n, sliceVar)
		case *GoCode:
			g.generateGoCode(n)
		case *GoExpr:
			elemVar := g.nextVar()
			g.writef("%s := tui.New(tui.WithText(%s))\n", elemVar, textExpr(n.Code))
			g.writef("%s = append(%s, %s)\n", sliceVar, sliceVar, elemVar)
		}
	}

	g.indent--

	if len(stmt.Else) > 0 {
		g.write("} else ")

		if len(stmt.Else) == 1 {
			if elseIf, ok := stmt.Else[0].(*IfStmt); ok {
				g.generateIfStmtForSlice(elseIf, sliceVar)
				return
			}
		}

		g.writeln("{")
		g.indent++
		for _, node := range stmt.Else {
			switch n := node.(type) {
			case *Element:
				elemVar := g.generateElement(n, "")
				g.writef("%s = append(%s, %s)\n", sliceVar, sliceVar, elemVar)
			case *ComponentCall:
				callVar := g.generateComponentCallWithRefs(n, "", true, false)
				if g.returnsElement(n) {
					g.writef("%s = append(%s, %s)\n", sliceVar, sliceVar, callVar)
				} else {
					g.writef("%s = append(%s, %s.Root)\n", sliceVar, sliceVar, callVar)
				}
			case *ComponentExpr:
				elemVar := g.nextVar()
				g.writef("%s := %s.Render(app)\n", elemVar, n.Expr)
				g.writef("%s = append(%s, %s)\n", sliceVar, sliceVar, elemVar)
			case *LetBinding:
				g.generateLetBinding(n, "", true, false)
				g.writef("%s = append(%s, %s)\n", sliceVar, sliceVar, n.Name)
			case *ForLoop:
				g.generateForLoopForSlice(n, sliceVar)
			case *IfStmt:
				g.generateIfStmtForSlice(n, sliceVar)
			case *GoCode:
				g.generateGoCode(n)
			case *GoExpr:
				elemVar := g.nextVar()
				g.writef("%s := tui.New(tui.WithText(%s))\n", elemVar, textExpr(n.Code))
				g.writef("%s = append(%s, %s)\n", sliceVar, sliceVar, elemVar)
			}
		}
		g.indent--
		g.writeln("}")
	} else {
		g.writeln("}")
	}
}