gitstack

grindlemire/go-tui code browser

14.9 KB Go 481 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
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
package tuigen

import (
	"fmt"
)

// generateLetBinding generates code for a let binding.
func (g *Generator) generateLetBinding(let *LetBinding, parentVar string, inConditional bool, inForLoop bool) {
	if let.Call != nil {
		// RHS is a component call
		varName := g.generateComponentCallWithRefs(let.Call, "", inConditional, inForLoop)
		if g.returnsElement(let.Call) {
			g.writef("%s := %s\n", let.Name, varName)
		} else {
			g.writef("%s := %s.Root\n", let.Name, varName)
		}
		if parentVar != "" {
			g.writef("%s.AddChild(%s)\n", parentVar, let.Name)
		}
		return
	}

	if let.Expr != "" && let.Element == nil {
		// RHS is a Go expression (component expression like c.textarea)
		g.writef("%s := %s.Render(app)\n", let.Name, let.Expr)
		g.trackComponentExprField(let.Expr)
		if parentVar != "" {
			g.writef("%s.AddChild(%s)\n", parentVar, let.Name)
		}
		return
	}

	// RHS is an element (existing behavior)
	elemOpts := g.buildElementOptions(let.Element)

	if len(elemOpts.options) == 0 {
		g.writef("%s := tui.New()\n", let.Name)
	} else {
		g.writef("%s := tui.New(\n", let.Name)
		g.indent++
		for _, opt := range elemOpts.options {
			g.writef("%s,\n", opt)
		}
		g.indent--
		g.writeln(")")
	}

	// Generate children for the let-bound element - skip if text element already has content in WithText
	if !skipTextChildren(let.Element) {
		g.generateChildren(let.Name, let.Element.Children)
	}

	// Add to parent if specified
	if parentVar != "" {
		g.writef("%s.AddChild(%s)\n", parentVar, let.Name)
	}
}

// generateForLoopWithRefs generates code for a for loop with ref context tracking.
// When the loop body references state variables (and we're not already in a loop/reactive context),
// generates a reactive wrapper that rebuilds loop children when state changes.
// The inForLoop parameter is accepted for call-chain uniformity with other *WithRefs
// functions but intentionally ignored: this function always sets bodyInForLoop=true
// for its own loop body.
func (g *Generator) generateForLoopWithRefs(loop *ForLoop, parentVar string, inLoop bool, inConditional bool, _ bool) {
	// Check if this loop body references state and we're not in a loop context
	if !inLoop && parentVar != "" {
		deps := collectForLoopDeps(loop, g.stateNameSet())
		if len(deps) > 0 {
			g.generateReactiveForLoop(loop, parentVar, deps)
			return
		}
	}

	// Push the loop index variable for use in struct mount calls.
	// This ensures each loop iteration gets a unique mount key.
	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 != "_" {
		// User provided a usable index variable
		loopVars = fmt.Sprintf("%s, %s", loop.Index, loop.Value)
	} else if loop.Index == "_" {
		// User explicitly ignored index, but we need one for mount keys
		loopVars = fmt.Sprintf("%s, %s", idxVar, loop.Value)
	} else {
		// No index in original, need to add one for mount keys
		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 index is not used elsewhere
	// (it will be used in mount calls, but Go doesn't know that at compile time
	// if there are no struct component calls in the loop body)
	if loop.Index != "" && loop.Index != "_" {
		g.writef("_ = %s\n", loop.Index)
	} else {
		g.writef("_ = %s\n", idxVar)
	}

	// Generate loop body - now inside a loop context.
	// The for-loop body is a block scope, so all component calls and let bindings
	// inside it must be treated as conditional (hoisted + nil-guarded).
	// inForLoop is set to true so component calls collect views into a slice
	// for proper watcher/bind/unbind aggregation across all iterations.
	bodyInForLoop := true
	for _, node := range loop.Body {
		switch n := node.(type) {
		case *Element:
			g.generateElementWithRefs(n, parentVar, true, true, bodyInForLoop)
		case *LetBinding:
			g.generateLetBinding(n, parentVar, true, bodyInForLoop)
		case *ForLoop:
			g.generateForLoopWithRefs(n, parentVar, true, true, bodyInForLoop) // nested loop inside loop context
		case *IfStmt:
			g.generateIfStmtWithRefs(n, parentVar, true, bodyInForLoop) // now in loop context
		case *GoCode:
			g.generateGoCode(n)
		case *GoExpr:
			// Bare expression in loop body
			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 *ComponentCall:
			g.generateComponentCallWithRefs(n, parentVar, true, bodyInForLoop)
		case *ComponentExpr:
			g.generateComponentExpr(n, parentVar)
		case *ChildrenSlot:
			if parentVar != "" {
				g.writeln("for _, __child := range children {")
				g.indent++
				g.writef("%s.AddChild(__child)\n", parentVar)
				g.indent--
				g.writeln("}")
			}
		}
	}

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

// generateIfStmtWithRefs generates code for an if statement with ref context tracking.
// When the condition references state variables (and we're not in a loop), generates
// a reactive wrapper that rebuilds its children when state changes.
func (g *Generator) generateIfStmtWithRefs(stmt *IfStmt, parentVar string, inLoop bool, inForLoop bool) {
	// Check if this condition references state and we're not in a loop context
	if !inLoop && parentVar != "" {
		deps := collectAllIfStmtDeps(stmt, g.stateNameSet())
		if len(deps) > 0 {
			g.generateReactiveIfStmt(stmt, parentVar, deps)
			return
		}
	}

	g.writef("if %s {\n", stmt.Condition)
	g.indent++

	// Generate then body - now inside conditional context
	for _, node := range stmt.Then {
		g.generateBodyNodeWithRefs(node, parentVar, inLoop, true, inForLoop)
	}

	g.indent--

	// Generate else branch if present
	if len(stmt.Else) > 0 {
		g.write("} else ")

		// Check if else contains a single IfStmt (else-if chain)
		if len(stmt.Else) == 1 {
			if elseIf, ok := stmt.Else[0].(*IfStmt); ok {
				g.generateIfStmtWithRefs(elseIf, parentVar, inLoop, inForLoop)
				return
			}
		}

		g.writeln("{")
		g.indent++
		for _, node := range stmt.Else {
			g.generateBodyNodeWithRefs(node, parentVar, inLoop, true, inForLoop)
		}
		g.indent--
		g.writeln("}")
	} else {
		g.writeln("}")
	}
}

// generateIfStmtToRoot generates an if statement where rendered element output
// should assign to the component root variable. This is used for top-level
// control flow in method/function components where no parent element exists.
func (g *Generator) generateIfStmtToRoot(stmt *IfStmt, rootVar string, inLoop bool) {
	g.writef("if %s {\n", stmt.Condition)
	g.indent++
	g.generateNodesToRoot(stmt.Then, rootVar, inLoop, true, false)
	g.indent--

	if len(stmt.Else) > 0 {
		g.write("} else ")
		if len(stmt.Else) == 1 {
			if elseIf, ok := stmt.Else[0].(*IfStmt); ok {
				g.generateIfStmtToRoot(elseIf, rootVar, inLoop)
				return
			}
		}

		g.writeln("{")
		g.indent++
		g.generateNodesToRoot(stmt.Else, rootVar, inLoop, true, false)
		g.indent--
		g.writeln("}")
	} else {
		g.writeln("}")
	}
}

// generateForLoopToRoot emits a top-level for loop as a synthetic container root.
// Without a parent element there is no legal way to emit multiple siblings.
func (g *Generator) generateForLoopToRoot(loop *ForLoop, rootVar string, inLoop bool) {
	loopRoot := g.nextVar()
	g.writef("%s := tui.New()\n", loopRoot)
	g.generateForLoopWithRefs(loop, loopRoot, inLoop, false, false)
	g.writef("if %s == nil {\n", rootVar)
	g.indent++
	g.writef("%s = %s\n", rootVar, loopRoot)
	g.indent--
	g.writeln("}")
}

// generateNodesToRoot emits nodes and assigns the first rendered element in the
// sequence to rootVar, preserving existing first-root behavior.
func (g *Generator) generateNodesToRoot(nodes []Node, rootVar string, inLoop bool, inConditional bool, inForLoop bool) {
	for _, node := range nodes {
		switch n := node.(type) {
		case *Element:
			varName := g.generateElementWithRefs(n, "", inLoop, inConditional, inForLoop)
			g.assignIfNil(rootVar, varName)
		case *ComponentCall:
			varName := g.generateComponentCallWithRefs(n, "", inConditional, inForLoop)
			if g.returnsElement(n) {
				g.assignIfNil(rootVar, varName)
			} else {
				g.assignIfNil(rootVar, varName+".Root")
			}
		case *ComponentExpr:
			varName := g.nextVar()
			g.writef("%s := %s.Render(app)\n", varName, n.Expr)
			g.assignIfNil(rootVar, varName)
			g.trackComponentExprField(n.Expr)
		case *IfStmt:
			g.generateIfStmtToRoot(n, rootVar, inLoop)
		case *ForLoop:
			g.generateForLoopToRoot(n, rootVar, inLoop)
		case *LetBinding:
			g.generateLetBinding(n, "", inConditional, inForLoop)
		case *GoCode:
			g.generateGoCode(n)
		case *GoExpr:
			g.writef("%s\n", n.Code)
		case *ChildrenSlot:
			// children slots are only valid in function components with parent containers.
		}
	}
}

func (g *Generator) assignIfNil(rootVar, value string) {
	g.writef("if %s == nil {\n", rootVar)
	g.indent++
	g.writef("%s = %s\n", rootVar, value)
	g.indent--
	g.writeln("}")
}

// generateReactiveIfStmt generates a reactive if block that rebuilds when state changes.
// It creates a wrapper element, an update closure, and state bindings.
func (g *Generator) generateReactiveIfStmt(stmt *IfStmt, parentVar string, deps []string) {
	condVar := g.nextCondVar()
	updateFn := fmt.Sprintf("__update_%s", condVar)

	// Create wrapper element and add to parent
	g.writef("%s := tui.New()\n", condVar)
	g.writef("%s.AddChild(%s)\n", parentVar, condVar)

	// Generate update function
	g.writef("%s := func() {\n", updateFn)
	g.indent++
	g.writef("%s.RemoveAllChildren()\n", condVar)

	// Record buffer position, line, and component var count so we can splice in
	// views slice resets after discovering which for-loop component vars
	// the if body creates.
	resetPos := g.buf.Len()
	resetLine := g.currentLine
	prevVarCount := len(g.componentVars)

	// Generate the if/else structure inside the closure with wrapper as parent.
	// Use inLoop=true to prevent nested reactive handling and skip text bindings.
	g.generateIfStmtWithRefs(stmt, condVar, true, false)

	// Splice resets for any for-loop component view slices created by the body.
	g.spliceForLoopViewResets(resetPos, resetLine, prevVarCount)

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

	// Call initially
	g.writef("%s()\n", updateFn)

	// Bind to all referenced state variables
	stateTypes := make(map[string]string)
	for _, sv := range g.stateVars {
		stateTypes[sv.Name] = sv.Type
	}
	for _, dep := range deps {
		stateType := stateTypes[dep]
		g.writef("%s.Bind(func(_ %s) { %s() })\n", dep, stateType, updateFn)
	}
}

// collectAllIfStmtDeps collects all state variable dependencies from an if statement,
// including the condition, else-if conditions, and all expressions in the body.
// This ensures the reactive update fires for any state change that could affect the block.
func collectAllIfStmtDeps(stmt *IfStmt, stateNames map[string]bool) []string {
	seen := make(map[string]bool)
	var deps []string

	addDeps := func(expr string) {
		for _, d := range detectGetCallsInExpr(expr, stateNames) {
			if !seen[d] {
				seen[d] = true
				deps = append(deps, d)
			}
		}
	}

	var collectFromNodes func(nodes []Node)
	collectFromNodes = func(nodes []Node) {
		for _, node := range nodes {
			switch n := node.(type) {
			case *Element:
				for _, attr := range n.Attributes {
					if goExpr, ok := attr.Value.(*GoExpr); ok {
						addDeps(goExpr.Code)
					}
				}
				collectFromNodes(n.Children)
			case *GoExpr:
				addDeps(n.Code)
			case *IfStmt:
				addDeps(n.Condition)
				collectFromNodes(n.Then)
				collectFromNodes(n.Else)
			case *ForLoop:
				addDeps(n.Iterable)
				collectFromNodes(n.Body)
			case *ComponentCall:
				addDeps(n.Args)
				collectFromNodes(n.Children)
			}
		}
	}

	// Collect from the top-level condition
	addDeps(stmt.Condition)

	// Collect from then/else bodies
	collectFromNodes(stmt.Then)
	collectFromNodes(stmt.Else)

	return deps
}

// generateReactiveForLoop generates a reactive for loop that rebuilds when state changes.
// It creates a wrapper element, an update closure, and state bindings.
func (g *Generator) generateReactiveForLoop(loop *ForLoop, parentVar string, deps []string) {
	loopVar := g.nextLoopVar()
	updateFn := fmt.Sprintf("__update_%s", loopVar)

	// Create wrapper element that inherits parent's container layout, and add to parent.
	// This ensures loop children are laid out the same way they would be as direct children.
	parentStyle := fmt.Sprintf("%s_style", loopVar)
	g.writef("%s := %s.LayoutStyle()\n", parentStyle, parentVar)
	g.writef("%s := tui.New(tui.WithDirection(%s.Direction), tui.WithGap(%s.Gap))\n", loopVar, parentStyle, parentStyle)
	g.writef("%s.AddChild(%s)\n", parentVar, loopVar)

	// Generate update function
	g.writef("%s := func() {\n", updateFn)
	g.indent++
	g.writef("%s.RemoveAllChildren()\n", loopVar)

	// Record buffer position, line, and component var count so we can splice in
	// views slice resets after discovering which for-loop component vars
	// the loop body creates.
	resetPos := g.buf.Len()
	resetLine := g.currentLine
	prevVarCount := len(g.componentVars)

	// Generate the for loop inside the closure with wrapper as parent.
	// Use inLoop=true to prevent nested reactive handling.
	g.generateForLoopWithRefs(loop, loopVar, true, false, false)

	// Splice resets for any for-loop component view slices created by the loop body.
	// Without this, the slices would grow unboundedly across reactive update invocations
	// since they live at function scope and the closure appends on every call.
	g.spliceForLoopViewResets(resetPos, resetLine, prevVarCount)

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

	// Call initially
	g.writef("%s()\n", updateFn)

	// Bind to all referenced state variables
	stateTypes := make(map[string]string)
	for _, sv := range g.stateVars {
		stateTypes[sv.Name] = sv.Type
	}
	for _, dep := range deps {
		stateType := stateTypes[dep]
		g.writef("%s.Bind(func(_ %s) { %s() })\n", dep, stateType, updateFn)
	}
}

// collectForLoopDeps collects all state variable dependencies from a for loop body.
// This scans the iterable expression and all nested nodes for state .Get() calls.
func collectForLoopDeps(loop *ForLoop, stateNames map[string]bool) []string {
	seen := make(map[string]bool)
	var deps []string

	addDeps := func(expr string) {
		for _, d := range detectGetCallsInExpr(expr, stateNames) {
			if !seen[d] {
				seen[d] = true
				deps = append(deps, d)
			}
		}
	}

	// Check the iterable expression
	addDeps(loop.Iterable)

	// Collect from body nodes
	var collectFromNodes func(nodes []Node)
	collectFromNodes = func(nodes []Node) {
		for _, node := range nodes {
			switch n := node.(type) {
			case *Element:
				for _, attr := range n.Attributes {
					if goExpr, ok := attr.Value.(*GoExpr); ok {
						addDeps(goExpr.Code)
					}
				}
				collectFromNodes(n.Children)
			case *GoExpr:
				addDeps(n.Code)
			case *IfStmt:
				addDeps(n.Condition)
				collectFromNodes(n.Then)
				collectFromNodes(n.Else)
			case *ForLoop:
				addDeps(n.Iterable)
				collectFromNodes(n.Body)
			case *ComponentCall:
				addDeps(n.Args)
				collectFromNodes(n.Children)
			}
		}
	}

	collectFromNodes(loop.Body)
	return deps
}