gitstack

grindlemire/go-tui code browser

35.0 KB Go 1151 lines 2026-07-10 · 0592ab2 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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
package tuigen

import (
	"fmt"
	"regexp"
	"slices"
	"sort"
	"strings"
)

// generateComponent generates a Go function from a component.
// Dispatches to generateMethodComponent for method templs (has receiver)
// or generateFunctionComponent for function templs (no receiver).
func (g *Generator) generateComponent(comp *Component) {
	// Reset variable counter and watcher tracking for each component
	g.varCounter = 0
	g.condCounter = 0
	g.loopCounter = 0
	g.mountIndex = 0
	g.loopIndexStack = nil
	g.mountKeyParts = nil
	g.currentReceiver = ""
	g.componentVars = nil
	g.componentExprFields = nil
	g.stateVars = nil
	g.stateBindings = nil
	g.eventsVars = nil

	if comp.Receiver != "" {
		g.generateMethodComponent(comp)
	} else {
		g.generateFunctionComponent(comp)
	}
}

// generateMethodComponent generates a Render(app *tui.App) method on a struct receiver.
// Method components return *tui.Element directly — no view struct, no watcher
// aggregation. The receiver variable is available for expressions in the template.
//
// Generated form:
//
//	func (s *sidebar) Render(app *tui.App) *tui.Element { ... return __tui_0 }
func (g *Generator) generateMethodComponent(comp *Component) {
	g.currentReceiver = comp.ReceiverName
	defer func() { g.currentReceiver = "" }()

	// Method signature: func (recv) Render(app *tui.App) *tui.Element
	g.writef("func (%s) Render(app *tui.App) *tui.Element {\n", comp.Receiver)
	g.indent++

	// Track the root element variable name
	var rootVar string
	var rootIsComponent bool // Whether root is a function-component call (view struct, needs .Root accessor)

	// Generate body nodes
	for _, node := range comp.Body {
		switch n := node.(type) {
		case *Element:
			varName := g.generateElementWithRefs(n, "", false, false, false)
			if rootVar == "" {
				rootVar = varName
			}
		case *LetBinding:
			g.generateLetBinding(n, "", false, false)
		case *ForLoop:
			if rootVar == "" {
				rootVar = g.nextVar()
				g.writef("var %s *tui.Element\n", rootVar)
			}
			g.generateForLoopToRoot(n, rootVar, false)
		case *IfStmt:
			if rootVar == "" {
				rootVar = g.nextVar()
				g.writef("var %s *tui.Element\n", rootVar)
			}
			g.generateIfStmtToRoot(n, rootVar, false)
		case *GoCode:
			g.generateGoCode(n)
		case *GoExpr:
			g.writef("%s\n", n.Code)
		case *ComponentCall:
			varName := g.generateComponentCallWithRefs(n, "", false, false)
			if rootVar == "" {
				rootVar = varName
				// Struct mounts return *tui.Element directly; function templs
				// return *XView and need .Root access.
				if !g.returnsElement(n) {
					rootIsComponent = true
				}
			}
		case *ComponentExpr:
			varName := g.nextVar()
			g.writef("%s := %s.Render(app)\n", varName, n.Expr)
			if rootVar == "" {
				rootVar = varName
			}
			g.trackComponentExprField(n.Expr)
		}
	}

	// Return the root element directly
	g.writeln("")
	if rootVar != "" {
		if rootIsComponent {
			g.writef("return %s.Root\n", rootVar)
		} else {
			g.writef("return %s\n", rootVar)
		}
	} else {
		g.writeln("return nil")
	}

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

	// Generate UpdateProps method for prop updates on cached components
	g.generateUpdateProps(comp, g.fileDecls)

	// Generate BindApp method for app binding on State/Events fields
	g.generateBindApp(comp, g.fileDecls)
	g.generateUnbindApp(comp, g.fileDecls)
}

// generateFunctionComponent generates a function component (existing behavior).
// Function components return a ComponentNameView struct.
func (g *Generator) generateFunctionComponent(comp *Component) {
	// Collect refs from this component
	analyzer := NewAnalyzer()
	g.refs = analyzer.CollectRefs(comp)

	// Detect state variables, events variables, and bindings
	g.stateVars = analyzer.DetectStateVars(comp)
	g.eventsVars = analyzer.DetectEventsVars(comp)
	g.stateBindings = analyzer.DetectStateBindings(comp, g.stateVars)

	// Generate view struct for this component (always generated)
	structName := comp.Name + "View"
	g.generateViewStruct(comp.Name, g.refs)

	// Generate function signature - always returns struct
	g.writef("func %s(", comp.Name)
	for i, param := range comp.Params {
		if i > 0 {
			g.write(", ")
		}
		g.writef("%s %s", param.Name, param.Type)
	}
	// Add children parameter if component accepts children
	if comp.AcceptsChildren {
		if len(comp.Params) > 0 {
			g.write(", ")
		}
		g.write("children []*tui.Element")
	}
	g.writef(") *%s {\n", structName)
	g.indent++

	// Pre-declare view variable so closures can capture it
	g.writef("var view %s\n", structName)
	g.writeln("var watchers []tui.Watcher")
	g.writeln("")

	// No forward declarations needed — refs are user-declared Go variables
	// (e.g., content := tui.NewRef()) written in the component body Go code

	// Track the root element variable name
	// The root is the first top-level Element (not LetBinding, which is typically a child reference)
	var rootVar string
	var rootIsComponent bool // Whether root is a component call (needs .Root accessor)

	// Save buffer position before body generation so we can splice in
	// hoisted declarations for conditional component variables afterward.
	bodyStartPos := g.buf.Len()
	bodyStartLine := g.currentLine

	// Generate body nodes
	for _, node := range comp.Body {
		switch n := node.(type) {
		case *Element:
			varName := g.generateElementWithRefs(n, "", false, false, false)
			if rootVar == "" {
				rootVar = varName
			}
		case *LetBinding:
			// Let bindings create elements that are typically used as children
			// They are NOT the root element unless explicitly used
			g.generateLetBinding(n, "", false, false)
		case *ForLoop:
			if rootVar == "" {
				rootVar = g.nextVar()
				g.writef("var %s *tui.Element\n", rootVar)
			}
			g.generateForLoopToRoot(n, rootVar, false)
		case *IfStmt:
			if rootVar == "" {
				rootVar = g.nextVar()
				g.writef("var %s *tui.Element\n", rootVar)
			}
			g.generateIfStmtToRoot(n, rootVar, false)
		case *GoCode:
			g.generateGoCode(n)
		case *GoExpr:
			// A bare expression in component body - treat as statement
			g.writef("%s\n", n.Code)
		case *ComponentCall:
			varName := g.generateComponentCallWithRefs(n, "", false, false)
			if rootVar == "" {
				rootVar = varName
				rootIsComponent = true
			}
		case *ComponentExpr:
			varName := g.nextVar()
			g.writef("%s := %s.Render(app)\n", varName, n.Expr)
			if rootVar == "" {
				rootVar = varName
			}
		}
	}

	// Hoist declarations for component variables declared inside conditional blocks.
	// These variables use = (not :=) inside the if block and need a var declaration
	// at function scope so they're accessible in the watcher/bind/unbind code below.
	g.spliceConditionalComponentHoists(bodyStartPos, bodyStartLine)

	// Emit watcher collection statements (collected during element generation)
	if len(g.componentVars) > 0 {
		g.writeln("")
		// Aggregate watchers from child component calls
		for _, cv := range g.componentVars {
			if cv.inForLoop {
				g.writef("for _, __cv := range %s_views {\n", cv.name)
				g.indent++
				g.writeln("watchers = append(watchers, __cv.GetWatchers()...)")
				g.indent--
				g.writeln("}")
			} else if cv.inConditional {
				g.writef("if %s != nil {\n", cv.name)
				g.indent++
				g.writef("watchers = append(watchers, %s.GetWatchers()...)\n", cv.name)
				g.indent--
				g.writeln("}")
			} else {
				g.writef("watchers = append(watchers, %s.GetWatchers()...)\n", cv.name)
			}
		}
	}

	// Generate state bindings (reactive updates)
	g.generateStateBindings()

	// Generate bindApp closure capturing local state, events, and child views
	g.generateBindAppClosure()

	// Populate view struct before returning
	g.writeln("")
	g.writef("view = %s{\n", structName)
	g.indent++
	if rootVar != "" {
		if rootIsComponent {
			g.writef("Root: %s.Root,\n", rootVar)
		} else {
			g.writef("Root: %s,\n", rootVar)
		}
	} else {
		g.writeln("Root: nil,")
	}
	g.writeln("watchers: watchers,")
	g.writeln("bindApp: __bindApp,")
	g.writeln("unbindApp: __unbindApp,")
	for _, ref := range g.refs {
		// View struct exposes *tui.Element (not ref types)
		switch ref.RefKind {
		case RefSingle:
			g.writef("%s: %s.El(),\n", ref.ExportName, ref.Name)
		case RefList:
			g.writef("%s: %s.All(),\n", ref.ExportName, ref.Name)
		case RefMap:
			g.writef("%s: %s.All(),\n", ref.ExportName, ref.Name)
		}
	}
	g.indent--
	g.writeln("}")

	g.writeln("return &view")

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

// generateViewStruct generates the ComponentNameView struct definition.
func (g *Generator) generateViewStruct(compName string, refs []RefInfo) {
	structName := compName + "View"

	g.writef("type %s struct {\n", structName)
	g.indent++
	g.writeln("Root     *tui.Element")
	g.writeln("watchers []tui.Watcher")
	g.writeln("bindApp  func(*tui.App)")
	g.writeln("unbindApp func()")

	for _, ref := range refs {
		switch ref.RefKind {
		case RefSingle:
			if ref.InConditional {
				g.writef("%s *tui.Element // may be nil\n", ref.ExportName)
			} else {
				g.writef("%s *tui.Element\n", ref.ExportName)
			}
		case RefList:
			g.writef("%s []*tui.Element\n", ref.ExportName)
		case RefMap:
			g.writef("%s map[%s]*tui.Element\n", ref.ExportName, ref.KeyType)
		}
	}

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

	// Generate UnbindApp method to implement tui.AppUnbinder
	g.writef("func (v *%s) UnbindApp() {\n", structName)
	g.indent++
	g.writeln("if v.unbindApp != nil {")
	g.indent++
	g.writeln("v.unbindApp()")
	g.indent--
	g.writeln("}")
	g.indent--
	g.writeln("}")
	g.writeln("")

	// All methods use pointer receivers so the mount system can store and
	// mutate cached *XxxView instances via UpdateProps.

	// Generate GetRoot() method to implement tui.Viewable
	g.writef("func (v *%s) GetRoot() *tui.Element { return v.Root }\n", structName)
	g.writeln("")

	// Generate GetWatchers() method to implement tui.Viewable
	g.writef("func (v *%s) GetWatchers() []tui.Watcher { return v.watchers }\n", structName)
	g.writeln("")

	// Generate Render() method to implement tui.Component
	g.writef("func (v *%s) Render(app *tui.App) *tui.Element { return v.Root }\n", structName)
	g.writeln("")

	// Generate BindApp method to implement tui.AppBinder
	g.writef("func (v *%s) BindApp(app *tui.App) {\n", structName)
	g.indent++
	g.writeln("if v.bindApp != nil {")
	g.indent++
	g.writeln("v.bindApp(app)")
	g.indent--
	g.writeln("}")
	g.indent--
	g.writeln("}")
	g.writeln("")

	// Generate UpdateProps method so the mount system can refresh cached views
	// with new props when cross-package function templs are mounted.
	g.writef("func (v *%s) UpdateProps(fresh tui.Component) {\n", structName)
	g.indent++
	g.writef("f, ok := fresh.(*%s)\n", structName)
	g.writeln("if !ok {")
	g.indent++
	g.writeln("return")
	g.indent--
	g.writeln("}")
	g.writeln("v.Root = f.Root")
	g.writeln("v.watchers = f.watchers")
	g.writeln("v.bindApp = f.bindApp")
	g.writeln("v.unbindApp = f.unbindApp")
	for _, ref := range refs {
		g.writef("v.%s = f.%s\n", ref.ExportName, ref.ExportName)
	}
	g.indent--
	g.writeln("}")
	g.writeln("")

	g.writef("var _ tui.AppBinder = (*%s)(nil)\n", structName)
	g.writeln("")
	g.writef("var _ tui.AppUnbinder = (*%s)(nil)\n", structName)
	g.writeln("")
	g.writef("var _ tui.PropsUpdater = (*%s)(nil)\n", structName)
	g.writeln("")
}

// StructField represents a parsed field from a struct definition.
type StructField struct {
	Name string
	Type string
}

// parseStructFields extracts field names and types from a struct definition.
// Input: "type foo struct {\n    field1 Type1\n    field2 Type2\n}"
// Returns: [{Name: "field1", Type: "Type1"}, {Name: "field2", Type: "Type2"}]
func parseStructFields(structCode string) []StructField {
	var fields []StructField

	// Find the struct body between { and }
	start := strings.Index(structCode, "{")
	end := strings.LastIndex(structCode, "}")
	if start == -1 || end == -1 || start >= end {
		return fields
	}

	body := structCode[start+1 : end]
	lines := strings.Split(body, "\n")

	// Pattern to match field declarations: name type or name, name2 type
	// Handles: "field Type", "field *Type", "field Type // comment"
	fieldPattern := regexp.MustCompile(`^\s*(\w+)\s+(\S+.*)$`)

	for _, line := range lines {
		line = strings.TrimSpace(line)
		if line == "" || strings.HasPrefix(line, "//") {
			continue
		}

		// Remove trailing comments
		if idx := strings.Index(line, "//"); idx != -1 {
			line = strings.TrimSpace(line[:idx])
		}

		matches := fieldPattern.FindStringSubmatch(line)
		if len(matches) >= 3 {
			fields = append(fields, StructField{
				Name: matches[1],
				Type: strings.TrimSpace(matches[2]),
			})
		}
	}

	return fields
}

// isTUIType checks if fieldType belongs to the TUI package and matches one of baseNames.
// It deliberately strips the '*' prefix (to support both pointer and non-pointer forms)
// and generic type parameters like '[T]' (to match base generic types against baseNames).
func (g *Generator) isTUIType(fieldType string, baseNames ...string) bool {
	t := strings.TrimPrefix(fieldType, "*")
	if idx := strings.Index(t, "["); idx != -1 {
		t = t[:idx]
	}
	before, after, ok := strings.Cut(t, ".")
	if !ok {
		if g.tuiAlias == "." {
			if slices.Contains(baseNames, t) {
				return true
			}
		}
		if g.isTuiPackage {
			if slices.Contains(baseNames, t) {
				return true
			}
		}
		return false
	}
	prefix := before
	typeName := after
	if prefix != g.tuiAlias {
		return false
	}
	return slices.Contains(baseNames, typeName)
}

// isInternalStateType returns true if the type is an internal state type
// that should NOT be updated via UpdateProps.
func (g *Generator) isInternalStateType(fieldType string) bool {
	if g.isTUIType(fieldType, "Ref", "RefList", "RefMap", "State") {
		return true
	}

	// Channels and functions are runtime state, not props.
	// Copying them in UpdateProps breaks watchers subscribed to the original channel.
	if strings.HasPrefix(fieldType, "chan ") ||
		strings.HasPrefix(fieldType, "<-chan ") ||
		strings.HasPrefix(fieldType, "chan<-") ||
		fieldType == "chan" ||
		strings.HasPrefix(fieldType, "func(") ||
		fieldType == "func" {
		return true
	}

	return false
}

// findStructDecl finds the struct declaration for a given type name in the file's declarations.
func findStructDecl(decls []*GoDecl, typeName string) *GoDecl {
	// Remove pointer prefix if present
	typeName = strings.TrimPrefix(typeName, "*")

	// Look for "type TypeName struct"
	pattern := regexp.MustCompile(`type\s+` + regexp.QuoteMeta(typeName) + `\s+struct\s*\{`)

	for _, decl := range decls {
		if decl.Kind == "type" && pattern.MatchString(decl.Code) {
			return decl
		}
	}
	return nil
}

// hasUserBindAppMethod returns true when the user already declares a BindApp
// method on the receiver type, in this file or a sibling file of the package.
func (g *Generator) hasUserBindAppMethod(receiverType string) bool {
	return g.userDeclaresMethod(receiverType, "BindApp")
}

// hasUserUnbindAppMethod returns true when the user already declares an
// UnbindApp method on the receiver type. Kept distinct from BindApp detection
// so that users who override BindApp alone still receive an auto-generated
// UnbindApp (otherwise their Events fields would leak subscriptions).
func (g *Generator) hasUserUnbindAppMethod(receiverType string) bool {
	return g.userDeclaresMethod(receiverType, "UnbindApp")
}

// hasUserUpdatePropsMethod returns true when the user already declares an
// UpdateProps method on the receiver type.
func (g *Generator) hasUserUpdatePropsMethod(receiverType string) bool {
	return g.userDeclaresMethod(receiverType, "UpdateProps")
}

// userDeclaresMethod reports whether the user declares the method on the
// receiver type, checking the current file and any sibling-file context.
func (g *Generator) userDeclaresMethod(receiverType, methodName string) bool {
	if hasUserMethod(g.fileDecls, g.fileFuncs, receiverType, methodName) {
		return true
	}
	if g.pkgCtx != nil {
		return g.pkgCtx.HasMethod(strings.TrimPrefix(receiverType, "*"), methodName)
	}
	return false
}

func hasUserMethod(decls []*GoDecl, funcs []*GoFunc, receiverType, methodName string) bool {
	typeName := strings.TrimPrefix(receiverType, "*")
	// The receiver name is optional: func (*row) M() is legal Go.
	pattern := regexp.MustCompile(`func\s*\(\s*(?:\w+\s+)?\*?` + regexp.QuoteMeta(typeName) + `\s*\)\s*` + regexp.QuoteMeta(methodName) + `\s*\(`)

	for _, decl := range decls {
		if decl.Kind == "func" && pattern.MatchString(decl.Code) {
			return true
		}
	}
	for _, fn := range funcs {
		if pattern.MatchString(fn.Code) {
			return true
		}
	}
	return false
}

// generateUpdateProps generates an UpdateProps method for a method component.
// This allows Mount to update cached component instances with fresh props.
//
// Like generateBindApp, the generator always emits an updatePropsFields helper
// so a user-defined UpdateProps override can delegate the prop copying to it.
// The public UpdateProps is only auto-generated when the user has not declared
// their own; emitting it unconditionally would produce a duplicate method.
func (g *Generator) generateUpdateProps(comp *Component, decls []*GoDecl) {
	// Find the struct declaration for this component's receiver type
	structDecl := findStructDecl(decls, comp.ReceiverType)
	if structDecl == nil {
		return // No struct found, skip generating UpdateProps
	}

	// Parse the struct fields
	fields := parseStructFields(structDecl.Code)
	if len(fields) == 0 {
		return
	}

	// Find prop fields (non-internal-state types)
	var propFields []StructField
	for _, f := range fields {
		if !g.isInternalStateType(f.Type) {
			propFields = append(propFields, f)
		}
	}

	if len(propFields) == 0 {
		return // No props to update
	}

	// Get the receiver type name without pointer
	typeName := strings.TrimPrefix(comp.ReceiverType, "*")

	// Always emit the updatePropsFields helper so user-defined UpdateProps
	// overrides can call it instead of hand-maintaining the copy list.
	g.emitUpdatePropsFieldsHelper(comp, propFields)

	if g.hasUserUpdatePropsMethod(comp.ReceiverType) {
		// Still assert PropsUpdater so a user UpdateProps with the wrong
		// signature fails at compile time instead of silently dropping
		// prop refresh on cached components.
		g.writef("var _ tui.PropsUpdater = (*%s)(nil)\n", typeName)
		g.writeln("")
		return
	}

	// Auto-generate UpdateProps: a thin wrapper that calls the helper.
	g.writef("func (%s) UpdateProps(fresh tui.Component) {\n", comp.Receiver)
	g.indent++
	g.writef("%s.updatePropsFields(fresh)\n", comp.ReceiverName)
	g.indent--
	g.writeln("}")
	g.writeln("")

	// Add a compile-time check that the type implements PropsUpdater
	g.writef("var _ tui.PropsUpdater = (*%s)(nil)\n", typeName)
	g.writeln("")
}

// emitUpdatePropsFieldsHelper writes the unexported updatePropsFields method
// containing the actual prop copying: type-asserting fresh to the receiver
// type and copying each prop field onto the receiver.
func (g *Generator) emitUpdatePropsFieldsHelper(comp *Component, propFields []StructField) {
	// Pick a local name for the type-asserted fresh component that does not
	// shadow the receiver; shadowing would turn every prop copy below into a
	// self-assignment.
	freshName := "f"
	for freshName == comp.ReceiverName {
		freshName += "f"
	}

	g.writef("// updatePropsFields is generated. It copies prop fields from fresh onto\n")
	g.writef("// the receiver. When you override UpdateProps, call this helper instead\n")
	g.writef("// of hand-maintaining the copy list.\n")
	g.writef("func (%s) updatePropsFields(fresh tui.Component) {\n", comp.Receiver)
	g.indent++
	g.writef("%s, ok := fresh.(%s)\n", freshName, comp.ReceiverType)
	g.writeln("if !ok {")
	g.indent++
	g.writeln("return")
	g.indent--
	g.writeln("}")

	// Copy each prop field
	for _, f := range propFields {
		g.writef("%s.%s = %s.%s\n", comp.ReceiverName, f.Name, freshName, f.Name)
	}

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

// isAppBindableType returns true if the field type has a BindApp method
// (i.e., *tui.State[...] or *tui.Events[...]).
func (g *Generator) isAppBindableType(fieldType string) bool {
	return g.isTUIType(fieldType, "State", "Events", "TextArea")
}

// generateBindApp generates a BindApp method for a method component.
// This allows the mount system to bind the app to State/Events fields.
//
// The generator always emits an unexported bindAppFields helper when the
// component has any *tui.App, State, Events, or component-expression fields.
// The public BindApp is either auto-generated (and just calls the helper) or,
// when the user overrides BindApp, the helper remains callable from user code
// so that delegations don't have to be hand-maintained.
func (g *Generator) generateBindApp(comp *Component, decls []*GoDecl) {
	// Find the struct declaration for this component's receiver type
	structDecl := findStructDecl(decls, comp.ReceiverType)
	if structDecl == nil {
		return
	}

	// Parse the struct fields
	fields := parseStructFields(structDecl.Code)
	if len(fields) == 0 {
		return
	}

	// Find *tui.App fields to set directly (c.app = app)
	var appFields []StructField
	for _, f := range fields {
		if f.Type == "*tui.App" {
			appFields = append(appFields, f)
		}
	}

	// Find fields that need BindApp (known types like State, Events, TextArea)
	var bindableFields []StructField
	for _, f := range fields {
		if g.isAppBindableType(f.Type) {
			bindableFields = append(bindableFields, f)
		}
	}

	// Find component expression fields that may implement AppBinder.
	// These are fields used as @receiver.field in the template (e.g., @c.settingsView).
	// Since the generator can't do full type checking, we use a runtime type assertion.
	componentExprFieldSet := make(map[string]bool)
	for _, name := range g.componentExprFields {
		componentExprFieldSet[name] = true
	}
	// Remove fields already in bindableFields to avoid duplicate binding
	for _, f := range bindableFields {
		delete(componentExprFieldSet, f.Name)
	}
	var componentBindFields []string
	for _, f := range fields {
		if componentExprFieldSet[f.Name] {
			componentBindFields = append(componentBindFields, f.Name)
		}
	}

	if len(appFields) == 0 && len(bindableFields) == 0 && len(componentBindFields) == 0 {
		return
	}

	// Get the receiver type name without pointer
	typeName := strings.TrimPrefix(comp.ReceiverType, "*")

	// Always emit the bindAppFields helper so user-defined BindApp overrides
	// can call it instead of hand-maintaining the delegation list.
	g.emitBindAppFieldsHelper(comp, appFields, bindableFields, componentBindFields)

	if g.hasUserBindAppMethod(comp.ReceiverType) {
		return
	}

	// Auto-generate BindApp: a thin wrapper that calls the helper.
	g.writef("func (%s) BindApp(app *tui.App) {\n", comp.Receiver)
	g.indent++
	g.writef("%s.bindAppFields(app)\n", comp.ReceiverName)
	g.indent--
	g.writeln("}")
	g.writeln("")

	// Add a compile-time check that the type implements AppBinder
	g.writef("var _ tui.AppBinder = (*%s)(nil)\n", typeName)
	g.writeln("")
}

// emitBindAppFieldsHelper writes the unexported bindAppFields method containing
// the actual delegation logic: assigning *tui.App fields, calling BindApp on
// State/Events/TextArea fields, and AppBinder type-asserting component-expr fields.
func (g *Generator) emitBindAppFieldsHelper(comp *Component, appFields, bindableFields []StructField, componentBindFields []string) {
	g.writef("// bindAppFields is generated. It wires the component's *tui.App,\n")
	g.writef("// State, Events, and TextArea fields to app. When you override BindApp,\n")
	g.writef("// call this helper instead of hand-maintaining the delegation list.\n")
	g.writef("func (%s) bindAppFields(app *tui.App) {\n", comp.Receiver)
	g.indent++
	for _, f := range appFields {
		g.writef("%s.%s = app\n", comp.ReceiverName, f.Name)
	}
	for _, f := range bindableFields {
		g.writef("if %s.%s != nil {\n", comp.ReceiverName, f.Name)
		g.indent++
		g.writef("%s.%s.BindApp(app)\n", comp.ReceiverName, f.Name)
		g.indent--
		g.writeln("}")
	}
	for _, name := range componentBindFields {
		g.writef("if binder, ok := any(%s.%s).(tui.AppBinder); ok {\n", comp.ReceiverName, name)
		g.indent++
		g.writeln("binder.BindApp(app)")
		g.indent--
		g.writeln("}")
	}
	g.indent--
	g.writeln("}")
	g.writeln("")
}

// generateUnbindApp generates an UnbindApp method for a method component.
// This allows mount sweep to detach topic-based Events subscriptions.
//
// Like generateBindApp, the generator always emits an unbindAppFields helper
// so a user-defined UnbindApp override can delegate to it by calling the
// helper instead of hand-maintaining the unbind list. Detection keys on the
// user's UnbindApp independently from BindApp so that overriding one method
// does not suppress auto-generation of the other.
func (g *Generator) generateUnbindApp(comp *Component, decls []*GoDecl) {
	structDecl := findStructDecl(decls, comp.ReceiverType)
	if structDecl == nil {
		return
	}

	fields := parseStructFields(structDecl.Code)
	if len(fields) == 0 {
		return
	}

	componentExprFieldSet := make(map[string]bool)
	for _, name := range g.componentExprFields {
		componentExprFieldSet[name] = true
	}

	var unbindFields []StructField
	for _, f := range fields {
		if g.isTUIType(f.Type, "Events") {
			unbindFields = append(unbindFields, f)
		}
	}
	// Remove fields already handled explicitly
	for _, f := range unbindFields {
		delete(componentExprFieldSet, f.Name)
	}
	var componentUnbindFields []string
	for _, f := range fields {
		if componentExprFieldSet[f.Name] {
			componentUnbindFields = append(componentUnbindFields, f.Name)
		}
	}

	if len(unbindFields) == 0 && len(componentUnbindFields) == 0 {
		return
	}

	typeName := strings.TrimPrefix(comp.ReceiverType, "*")

	// Always emit the unbindAppFields helper.
	g.emitUnbindAppFieldsHelper(comp, unbindFields, componentUnbindFields)

	if g.hasUserUnbindAppMethod(comp.ReceiverType) {
		return
	}

	// Auto-generate UnbindApp as a thin wrapper around the helper.
	g.writef("func (%s) UnbindApp() {\n", comp.Receiver)
	g.indent++
	g.writef("%s.unbindAppFields()\n", comp.ReceiverName)
	g.indent--
	g.writeln("}")
	g.writeln("")
	g.writef("var _ tui.AppUnbinder = (*%s)(nil)\n", typeName)
	g.writeln("")
}

// emitUnbindAppFieldsHelper writes the unexported unbindAppFields method.
func (g *Generator) emitUnbindAppFieldsHelper(comp *Component, unbindFields []StructField, componentUnbindFields []string) {
	g.writef("// unbindAppFields is generated. It detaches topic-based Events\n")
	g.writef("// subscriptions and any component-expression AppUnbinder fields.\n")
	g.writef("// Call this from your UnbindApp if you override it.\n")
	g.writef("func (%s) unbindAppFields() {\n", comp.Receiver)
	g.indent++
	for _, f := range unbindFields {
		g.writef("if %s.%s != nil {\n", comp.ReceiverName, f.Name)
		g.indent++
		g.writef("%s.%s.UnbindApp()\n", comp.ReceiverName, f.Name)
		g.indent--
		g.writeln("}")
	}
	for _, name := range componentUnbindFields {
		g.writef("if unbinder, ok := any(%s.%s).(tui.AppUnbinder); ok {\n", comp.ReceiverName, name)
		g.indent++
		g.writeln("unbinder.UnbindApp()")
		g.indent--
		g.writeln("}")
	}
	g.indent--
	g.writeln("}")
	g.writeln("")
}

// interfaceCheck maps a method name pattern to the tui interface it satisfies.
type interfaceCheck struct {
	// methodPattern matches the method signature in Go source code.
	methodPattern string
	// interfaceName is the tui interface (e.g., "tui.KeyListener").
	interfaceName string
}

// optionalInterfaces lists the user-facing component interfaces that are
// discovered via type assertion at runtime. A wrong method signature silently
// fails the assertion, so we emit compile-time checks when we detect these
// methods on component receiver types.
var optionalInterfaces = []interfaceCheck{
	{`\bKeyMap\s*\(`, "tui.KeyListener"},
	{`\bHandleMouse\s*\(`, "tui.MouseListener"},
	{`\bInit\s*\(`, "tui.Initializer"},
	{`\bWatchers\s*\(`, "tui.WatcherProvider"},
}

// generateInterfaceChecks emits compile-time interface satisfaction checks
// for method component receiver types that define optional interface methods.
// This catches signature mismatches (e.g., returning []tui.KeyBinding instead
// of tui.KeyMap) at compile time rather than failing silently at runtime.
func (g *Generator) generateInterfaceChecks(file *File) {
	// Collect receiver types that are method templ components.
	componentTypes := make(map[string]bool)
	for _, comp := range file.Components {
		if comp.ReceiverType != "" {
			typeName := strings.TrimPrefix(comp.ReceiverType, "*")
			componentTypes[typeName] = true
		}
	}
	if len(componentTypes) == 0 {
		return
	}

	// For each optional interface, check if any GoFunc defines a matching
	// method on a component receiver type.
	type check struct {
		typeName      string
		interfaceName string
	}
	var checks []check
	seen := make(map[check]bool)

	for _, iface := range optionalInterfaces {
		for _, typeName := range sortedKeys(componentTypes) {
			pattern := regexp.MustCompile(
				`func\s*\(\s*\w+\s+\*?` + regexp.QuoteMeta(typeName) + `\s*\)\s*` + iface.methodPattern,
			)
			for _, fn := range file.Funcs {
				if pattern.MatchString(fn.Code) {
					c := check{typeName, iface.interfaceName}
					if !seen[c] {
						seen[c] = true
						checks = append(checks, c)
					}
					break
				}
			}
		}
	}

	if len(checks) == 0 {
		return
	}

	g.writeln("// Compile-time interface satisfaction checks.")
	g.writeln("var (")
	g.indent++
	for _, c := range checks {
		g.writef("_ %s = (*%s)(nil)\n", c.interfaceName, c.typeName)
	}
	g.indent--
	g.writeln(")")
	g.writeln("")
}

// sortedKeys returns the keys of a map in sorted order.
func sortedKeys(m map[string]bool) []string {
	keys := make([]string, 0, len(m))
	for k := range m {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	return keys
}

// trackComponentExprField extracts and tracks receiver field names from
// component expressions (e.g., "c.settingsView" → tracks "settingsView").
// Only tracks when inside a method component (currentReceiver is set).
func (g *Generator) trackComponentExprField(expr string) {
	if g.currentReceiver == "" {
		return
	}
	prefix := g.currentReceiver + "."
	if !strings.HasPrefix(expr, prefix) {
		return
	}
	fieldName := expr[len(prefix):]
	// Only track simple field names (no further dots or method calls)
	if strings.ContainsAny(fieldName, ".()") {
		return
	}
	// Avoid duplicates
	if slices.Contains(g.componentExprFields, fieldName) {
		return
	}
	g.componentExprFields = append(g.componentExprFields, fieldName)
}

// generateBindAppClosure emits a __bindApp closure for function components.
// The closure captures local state vars, events vars, and child component views,
// binding them all to the app when called.
func (g *Generator) generateBindAppClosure() {
	g.writeln("")
	g.writeln("__bindApp := func(app *tui.App) {")
	g.indent++

	// Bind local state variables
	for _, sv := range g.stateVars {
		if sv.IsParameter {
			continue // Parameters are already bound by the caller
		}
		g.writef("%s.BindApp(app)\n", sv.Name)
	}

	// Bind local events variables
	for _, ev := range g.eventsVars {
		g.writef("%s.BindApp(app)\n", ev.Name)
	}

	// Bind child function component views (they implement AppBinder)
	for _, cv := range g.componentVars {
		if cv.inForLoop {
			g.writef("for _, __cv := range %s_views {\n", cv.name)
			g.indent++
			g.writeln("if binder, ok := any(__cv).(tui.AppBinder); ok {")
			g.indent++
			g.writeln("binder.BindApp(app)")
			g.indent--
			g.writeln("}")
			g.indent--
			g.writeln("}")
		} else if cv.inConditional {
			g.writef("if %s != nil {\n", cv.name)
			g.indent++
			g.writef("if binder, ok := any(%s).(tui.AppBinder); ok {\n", cv.name)
			g.indent++
			g.writeln("binder.BindApp(app)")
			g.indent--
			g.writeln("}")
			g.indent--
			g.writeln("}")
		} else {
			g.writef("if binder, ok := any(%s).(tui.AppBinder); ok {\n", cv.name)
			g.indent++
			g.writeln("binder.BindApp(app)")
			g.indent--
			g.writeln("}")
		}
	}

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

	g.writeln("")
	g.writeln("__unbindApp := func() {")
	g.indent++

	// Unbind local events variables
	for _, ev := range g.eventsVars {
		g.writef("%s.UnbindApp()\n", ev.Name)
	}

	// Unbind child function component views (they may implement AppUnbinder)
	for _, cv := range g.componentVars {
		if cv.inForLoop {
			g.writef("for _, __cv := range %s_views {\n", cv.name)
			g.indent++
			g.writeln("if unbinder, ok := any(__cv).(tui.AppUnbinder); ok {")
			g.indent++
			g.writeln("unbinder.UnbindApp()")
			g.indent--
			g.writeln("}")
			g.indent--
			g.writeln("}")
		} else if cv.inConditional {
			g.writef("if %s != nil {\n", cv.name)
			g.indent++
			g.writef("if unbinder, ok := any(%s).(tui.AppUnbinder); ok {\n", cv.name)
			g.indent++
			g.writeln("unbinder.UnbindApp()")
			g.indent--
			g.writeln("}")
			g.indent--
			g.writeln("}")
		} else {
			g.writef("if unbinder, ok := any(%s).(tui.AppUnbinder); ok {\n", cv.name)
			g.indent++
			g.writeln("unbinder.UnbindApp()")
			g.indent--
			g.writeln("}")
		}
	}

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

// spliceConditionalComponentHoists inserts hoisted declarations at bodyStartPos
// for component variables declared inside block scopes.
// For conditional (if/else) vars: "var __tui_N *XxxView" (single pointer, nil-guarded).
// For for-loop vars: "var __tui_N_views []*XxxView" (slice, range-iterated).
func (g *Generator) spliceConditionalComponentHoists(bodyStartPos int, bodyStartLine int) {
	// Collect hoisted declarations
	var hoistLines []string
	for _, cv := range g.componentVars {
		if cv.inForLoop {
			hoistLines = append(hoistLines, fmt.Sprintf("var %s_views []%s", cv.name, viewTypeName(cv.componentName)))
		} else if cv.inConditional {
			hoistLines = append(hoistLines, fmt.Sprintf("var %s %s", cv.name, viewTypeName(cv.componentName)))
		}
	}
	if len(hoistLines) == 0 {
		return
	}

	// Save body bytes written after bodyStartPos
	bodyBytes := make([]byte, g.buf.Len()-bodyStartPos)
	copy(bodyBytes, g.buf.Bytes()[bodyStartPos:])
	g.buf.Truncate(bodyStartPos)

	// Write hoisted declarations at the saved position (uses current indent)
	hoistLineCount := len(hoistLines)
	for _, line := range hoistLines {
		g.writeln(line)
	}

	// Write body bytes back
	g.buf.Write(bodyBytes)

	// Adjust source map entries: all mappings recorded during body generation
	// have line numbers that are now shifted down by hoistLineCount.
	if g.sourceMap != nil {
		for i := range g.sourceMap.Mappings {
			if g.sourceMap.Mappings[i].GoLine >= bodyStartLine {
				g.sourceMap.Mappings[i].GoLine += hoistLineCount
			}
		}
	}
}

// spliceForLoopViewResets inserts slice reset statements at resetPos for any
// for-loop component variables added after prevVarCount. This prevents unbounded
// growth of views slices in reactive for-loop closures that fire on every state change.
func (g *Generator) spliceForLoopViewResets(resetPos int, resetLine int, prevVarCount int) {
	var resetLines []string
	for _, cv := range g.componentVars[prevVarCount:] {
		if cv.inForLoop {
			resetLines = append(resetLines, fmt.Sprintf("%s_views = %s_views[:0]", cv.name, cv.name))
		}
	}
	if len(resetLines) == 0 {
		return
	}

	// Save bytes written after resetPos
	tailBytes := make([]byte, g.buf.Len()-resetPos)
	copy(tailBytes, g.buf.Bytes()[resetPos:])
	g.buf.Truncate(resetPos)

	// Write reset statements at the saved position
	resetLineCount := len(resetLines)
	for _, line := range resetLines {
		g.writeln(line)
	}

	// Write tail bytes back
	g.buf.Write(tailBytes)

	// Adjust source map entries shifted by the spliced lines.
	if g.sourceMap != nil {
		for i := range g.sourceMap.Mappings {
			if g.sourceMap.Mappings[i].GoLine >= resetLine {
				g.sourceMap.Mappings[i].GoLine += resetLineCount
			}
		}
	}
}