gitstack

grindlemire/go-tui code browser

15.9 KB Go 737 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
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
package tuigen

import (
	"testing"
)

func TestParser_LetBinding(t *testing.T) {
	input := `package x
templ Test() {
	myText := <span>Hello</span>
	<div></div>
}`

	l := NewLexer("test.gsx", input)
	p := NewParser(l)
	file, err := p.ParseFile()
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	comp := file.Components[0]
	if len(comp.Body) != 2 {
		t.Fatalf("expected 2 body nodes, got %d", len(comp.Body))
	}

	let, ok := comp.Body[0].(*LetBinding)
	if !ok {
		t.Fatalf("expected *LetBinding, got %T", comp.Body[0])
	}

	if let.Name != "myText" {
		t.Errorf("Name = %q, want 'myText'", let.Name)
	}

	if let.Element == nil {
		t.Fatal("Element is nil")
	}

	if let.Element.Tag != "span" {
		t.Errorf("Element.Tag = %q, want 'span'", let.Element.Tag)
	}
}

func TestParser_ForLoop(t *testing.T) {
	type tc struct {
		input     string
		wantIndex string
		wantValue string
		wantIter  string
	}

	tests := map[string]tc{
		"index and value": {
			input: `package x
templ Test() {
	for i, item := range items {
		<span>Hello</span>
	}
}`,
			wantIndex: "i",
			wantValue: "item",
			wantIter:  "items",
		},
		"underscore index": {
			input: `package x
templ Test() {
	for _, item := range items {
		<span>Hello</span>
	}
}`,
			wantIndex: "_",
			wantValue: "item",
			wantIter:  "items",
		},
		"value only": {
			input: `package x
templ Test() {
	for item := range items {
		<span>Hello</span>
	}
}`,
			wantIndex: "",
			wantValue: "item",
			wantIter:  "items",
		},
	}

	for name, tt := range tests {
		t.Run(name, func(t *testing.T) {
			l := NewLexer("test.gsx", tt.input)
			p := NewParser(l)
			file, err := p.ParseFile()
			if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}

			forLoop, ok := file.Components[0].Body[0].(*ForLoop)
			if !ok {
				t.Fatalf("expected *ForLoop, got %T", file.Components[0].Body[0])
			}

			if forLoop.Index != tt.wantIndex {
				t.Errorf("Index = %q, want %q", forLoop.Index, tt.wantIndex)
			}
			if forLoop.Value != tt.wantValue {
				t.Errorf("Value = %q, want %q", forLoop.Value, tt.wantValue)
			}
			if forLoop.Iterable != tt.wantIter {
				t.Errorf("Iterable = %q, want %q", forLoop.Iterable, tt.wantIter)
			}
			if len(forLoop.Body) != 1 {
				t.Errorf("len(Body) = %d, want 1", len(forLoop.Body))
			}
		})
	}
}

func TestParser_IfStatement(t *testing.T) {
	type tc struct {
		input         string
		wantCondition string
		wantElse      bool
	}

	tests := map[string]tc{
		"simple if": {
			input: `package x
templ Test() {
	if showHeader {
		<span>Header</span>
	}
}`,
			wantCondition: "showHeader",
			wantElse:      false,
		},
		"if with else": {
			input: `package x
templ Test() {
	if isLoading {
		<span>Loading</span>
	} else {
		<span>Done</span>
	}
}`,
			wantCondition: "isLoading",
			wantElse:      true,
		},
		"complex condition": {
			input: `package x
templ Test() {
	if err != nil {
		<span>Error</span>
	}
}`,
			wantCondition: "err != nil",
			wantElse:      false,
		},
	}

	for name, tt := range tests {
		t.Run(name, func(t *testing.T) {
			l := NewLexer("test.gsx", tt.input)
			p := NewParser(l)
			file, err := p.ParseFile()
			if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}

			ifStmt, ok := file.Components[0].Body[0].(*IfStmt)
			if !ok {
				t.Fatalf("expected *IfStmt, got %T", file.Components[0].Body[0])
			}

			if ifStmt.Condition != tt.wantCondition {
				t.Errorf("Condition = %q, want %q", ifStmt.Condition, tt.wantCondition)
			}

			if len(ifStmt.Then) != 1 {
				t.Errorf("len(Then) = %d, want 1", len(ifStmt.Then))
			}

			hasElse := len(ifStmt.Else) > 0
			if hasElse != tt.wantElse {
				t.Errorf("hasElse = %v, want %v", hasElse, tt.wantElse)
			}
		})
	}
}

func TestParser_IfElseIf(t *testing.T) {
	input := `package x
templ Test() {
	if a {
		<span>A</span>
	} else if b {
		<span>B</span>
	} else {
		<span>C</span>
	}
}`

	l := NewLexer("test.gsx", input)
	p := NewParser(l)
	file, err := p.ParseFile()
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	ifStmt, ok := file.Components[0].Body[0].(*IfStmt)
	if !ok {
		t.Fatalf("expected *IfStmt, got %T", file.Components[0].Body[0])
	}

	if ifStmt.Condition != "a" {
		t.Errorf("Condition = %q, want 'a'", ifStmt.Condition)
	}

	// Else should contain an IfStmt
	if len(ifStmt.Else) != 1 {
		t.Fatalf("len(Else) = %d, want 1", len(ifStmt.Else))
	}

	elseIf, ok := ifStmt.Else[0].(*IfStmt)
	if !ok {
		t.Fatalf("Else[0] expected *IfStmt, got %T", ifStmt.Else[0])
	}

	if elseIf.Condition != "b" {
		t.Errorf("elseIf.Condition = %q, want 'b'", elseIf.Condition)
	}

	// Inner else
	if len(elseIf.Else) != 1 {
		t.Fatalf("len(elseIf.Else) = %d, want 1", len(elseIf.Else))
	}
}

func TestParser_ControlFlowInChildren(t *testing.T) {
	input := `package x
templ Test(items []string) {
	<div>
		for _, item := range items {
			<span>{item}</span>
		}
		if len(items) == 0 {
			<span>No items</span>
		}
	</div>
}`

	l := NewLexer("test.gsx", input)
	p := NewParser(l)
	file, err := p.ParseFile()
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	box := file.Components[0].Body[0].(*Element)

	// Should have for loop and if statement as children
	hasFor := false
	hasIf := false
	for _, child := range box.Children {
		switch child.(type) {
		case *ForLoop:
			hasFor = true
		case *IfStmt:
			hasIf = true
		}
	}

	if !hasFor {
		t.Error("expected ForLoop child")
	}
	if !hasIf {
		t.Error("expected IfStmt child")
	}
}

func TestParser_RawGoStatements(t *testing.T) {
	type tc struct {
		input     string
		wantCodes []string
	}

	tests := map[string]tc{
		"simple assignment": {
			input: `package x
templ Test() {
	x := 1
	<span>{x}</span>
}`,
			wantCodes: []string{"x := 1"},
		},
		"function call": {
			input: `package x
templ Test() {
	fmt.Println("hello")
	<span>world</span>
}`,
			wantCodes: []string{`fmt.Println("hello")`},
		},
		"multi-line statement": {
			input: `package x
templ Test() {
	result := compute(
		arg1,
		arg2,
	)
	<span>{result}</span>
}`,
			wantCodes: []string{"result := compute(\n\t\targ1,\n\t\targ2,\n\t)"},
		},
		"multiple statements": {
			input: `package x
templ Test() {
	x := 1
	y := 2
	z := x + y
	<span>{z}</span>
}`,
			wantCodes: []string{"x := 1", "y := 2", "z := x + y"},
		},
		"typed var declaration": {
			input: `package x
templ Test() {
	var count int = 0
	<span>{count}</span>
}`,
			wantCodes: []string{"var count int = 0"},
		},
		"var without initializer": {
			input: `package x
templ Test() {
	var err error
	<span>{err}</span>
}`,
			wantCodes: []string{"var err error"},
		},
		"defer statement": {
			input: `package x
templ Test() {
	defer cleanup()
	<span>running</span>
}`,
			wantCodes: []string{"defer cleanup()"},
		},
		"go statement": {
			input: `package x
templ Test() {
	go doWork()
	<span>spawned</span>
}`,
			wantCodes: []string{"go doWork()"},
		},
		"for loop statement": {
			input: `package x
templ Test() {
	for i := 0; i < 10; i++ { sum += i }
	<span>{sum}</span>
}`,
			wantCodes: []string{"for i := 0; i < 10; i++ { sum += i }"},
		},
		"switch statement": {
			input: `package x
templ Test(x int) {
	switch x { case 1: y = "one"; case 2: y = "two" }
	<span>{y}</span>
}`,
			wantCodes: []string{`switch x { case 1: y = "one"; case 2: y = "two" }`},
		},
	}

	for name, tt := range tests {
		t.Run(name, func(t *testing.T) {
			l := NewLexer("test.gsx", tt.input)
			p := NewParser(l)
			file, err := p.ParseFile()
			if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}

			if len(file.Components) != 1 {
				t.Fatalf("expected 1 component, got %d", len(file.Components))
			}

			body := file.Components[0].Body

			// Count GoCode nodes
			var goCodes []*GoCode
			for _, node := range body {
				if gc, ok := node.(*GoCode); ok {
					goCodes = append(goCodes, gc)
				}
			}

			if len(goCodes) != len(tt.wantCodes) {
				t.Fatalf("expected %d GoCode nodes, got %d", len(tt.wantCodes), len(goCodes))
			}

			for i, wantCode := range tt.wantCodes {
				if goCodes[i].Code != wantCode {
					t.Errorf("GoCode[%d].Code = %q, want %q", i, goCodes[i].Code, wantCode)
				}
			}
		})
	}
}

func TestParser_GoStatementStopsAtClosingBrace(t *testing.T) {
	// Simulate what happens when parseGoStatement is called inside an if body
	// where the Go code and closing brace are on the same line.
	// This tests the raw parsing of a body containing "log.Error(err) }"
	// where } belongs to the parent, not the statement.
	input := `package x
templ Test() {
	if condition {
		log.Error(err)
	}
}`

	l := NewLexer("test.gsx", input)
	p := NewParser(l)
	file, err := p.ParseFile()
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	ifStmt, ok := file.Components[0].Body[0].(*IfStmt)
	if !ok {
		t.Fatalf("expected *IfStmt, got %T", file.Components[0].Body[0])
	}

	if len(ifStmt.Then) != 1 {
		t.Fatalf("expected 1 then node, got %d", len(ifStmt.Then))
	}

	gc, ok := ifStmt.Then[0].(*GoCode)
	if !ok {
		t.Fatalf("expected *GoCode, got %T", ifStmt.Then[0])
	}
	if gc.Code != "log.Error(err)" {
		t.Errorf("Code = %q, want %q", gc.Code, "log.Error(err)")
	}
}

func TestParser_GoStatementMultilineBraces(t *testing.T) {
	// Verify that multiline Go statements with braces (switch, select, etc.)
	// are NOT prematurely truncated by the depth-0 } stop.
	input := `package x
templ Test(x int) {
	switch x { case 1: y = "one"; case 2: y = "two" }
	<span>{y}</span>
}`

	l := NewLexer("test.gsx", input)
	p := NewParser(l)
	file, err := p.ParseFile()
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	gc, ok := file.Components[0].Body[0].(*GoCode)
	if !ok {
		t.Fatalf("expected *GoCode, got %T", file.Components[0].Body[0])
	}
	want := `switch x { case 1: y = "one"; case 2: y = "two" }`
	if gc.Code != want {
		t.Errorf("Code = %q, want %q", gc.Code, want)
	}
}

func TestParser_ShortBinding(t *testing.T) {
	type tc struct {
		input       string
		wantName    string
		wantElement string // expected element tag, empty if not element RHS
		wantCall    string // expected component call name, empty if not call RHS
		wantShort   bool   // IsShortForm
	}

	tests := map[string]tc{
		"short element binding": {
			input:       "package x\ntempl Test() {\n\tlabel := <span>Hello</span>\n\t<div></div>\n}",
			wantName:    "label",
			wantElement: "span",
			wantShort:   true,
		},
		"short component binding": {
			input:     "package x\ntempl Test() {\n\tfoo := @MyComponent()\n\t<div></div>\n}",
			wantName:  "foo",
			wantCall:  "MyComponent",
			wantShort: true,
		},
		"var element binding": {
			input:       "package x\ntempl Test() {\n\tvar label = <span>Hello</span>\n\t<div></div>\n}",
			wantName:    "label",
			wantElement: "span",
			wantShort:   false,
		},
		"var component binding": {
			input:     "package x\ntempl Test() {\n\tvar foo = @MyComponent()\n\t<div></div>\n}",
			wantName:  "foo",
			wantCall:  "MyComponent",
			wantShort: false,
		},
	}

	for name, tt := range tests {
		t.Run(name, func(t *testing.T) {
			l := NewLexer("test.gsx", tt.input)
			p := NewParser(l)
			file, err := p.ParseFile()
			if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}

			let, ok := file.Components[0].Body[0].(*LetBinding)
			if !ok {
				t.Fatalf("expected *LetBinding, got %T", file.Components[0].Body[0])
			}

			if let.Name != tt.wantName {
				t.Errorf("Name = %q, want %q", let.Name, tt.wantName)
			}
			if let.IsShortForm != tt.wantShort {
				t.Errorf("IsShortForm = %v, want %v", let.IsShortForm, tt.wantShort)
			}
			if tt.wantElement != "" {
				if let.Element == nil {
					t.Fatal("Element is nil")
				}
				if let.Element.Tag != tt.wantElement {
					t.Errorf("Element.Tag = %q, want %q", let.Element.Tag, tt.wantElement)
				}
			}
			if tt.wantCall != "" {
				if let.Call == nil {
					t.Fatal("Call is nil")
				}
				if let.Call.Name != tt.wantCall {
					t.Errorf("Call.Name = %q, want %q", let.Call.Name, tt.wantCall)
				}
			}
		})
	}
}

func TestParser_BareIfStatement(t *testing.T) {
	input := `package x
templ Test() {
	if showHeader {
		<span>Header</span>
	}
}`

	l := NewLexer("test.gsx", input)
	p := NewParser(l)
	file, err := p.ParseFile()
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	ifStmt, ok := file.Components[0].Body[0].(*IfStmt)
	if !ok {
		t.Fatalf("expected *IfStmt, got %T", file.Components[0].Body[0])
	}
	if ifStmt.Condition != "showHeader" {
		t.Errorf("Condition = %q, want 'showHeader'", ifStmt.Condition)
	}
}

func TestParser_BareElseIf(t *testing.T) {
	input := `package x
templ Test() {
	if a {
		<span>A</span>
	} else if b {
		<span>B</span>
	} else {
		<span>C</span>
	}
}`

	l := NewLexer("test.gsx", input)
	p := NewParser(l)
	file, err := p.ParseFile()
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	ifStmt, ok := file.Components[0].Body[0].(*IfStmt)
	if !ok {
		t.Fatalf("expected *IfStmt, got %T", file.Components[0].Body[0])
	}
	if ifStmt.Condition != "a" {
		t.Errorf("Condition = %q, want 'a'", ifStmt.Condition)
	}
	if len(ifStmt.Else) != 1 {
		t.Fatalf("len(Else) = %d, want 1", len(ifStmt.Else))
	}
	elseIf, ok := ifStmt.Else[0].(*IfStmt)
	if !ok {
		t.Fatalf("Else[0] expected *IfStmt, got %T", ifStmt.Else[0])
	}
	if elseIf.Condition != "b" {
		t.Errorf("elseIf.Condition = %q, want 'b'", elseIf.Condition)
	}
	if len(elseIf.Else) != 1 {
		t.Fatalf("len(elseIf.Else) = %d, want 1", len(elseIf.Else))
	}
}

func TestParser_BareForLoop(t *testing.T) {
	input := `package x
templ Test() {
	for i, item := range items {
		<span>{item}</span>
	}
}`

	l := NewLexer("test.gsx", input)
	p := NewParser(l)
	file, err := p.ParseFile()
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	forLoop, ok := file.Components[0].Body[0].(*ForLoop)
	if !ok {
		t.Fatalf("expected *ForLoop, got %T", file.Components[0].Body[0])
	}
	if forLoop.Index != "i" {
		t.Errorf("Index = %q, want 'i'", forLoop.Index)
	}
	if forLoop.Value != "item" {
		t.Errorf("Value = %q, want 'item'", forLoop.Value)
	}
	if forLoop.Iterable != "items" {
		t.Errorf("Iterable = %q, want 'items'", forLoop.Iterable)
	}
}

func TestParser_CStyleForLoopStaysGoCode(t *testing.T) {
	input := `package x
templ Test() {
	for i := 0; i < 10; i++ { sum += i }
	<span>{sum}</span>
}`

	l := NewLexer("test.gsx", input)
	p := NewParser(l)
	file, err := p.ParseFile()
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	gc, ok := file.Components[0].Body[0].(*GoCode)
	if !ok {
		t.Fatalf("expected *GoCode for C-style for loop, got %T", file.Components[0].Body[0])
	}
	if gc.Code != "for i := 0; i < 10; i++ { sum += i }" {
		t.Errorf("Code = %q", gc.Code)
	}
}

func TestParser_ShortBindingGoExprStaysGoCode(t *testing.T) {
	// name := goExpr should still be parsed as GoCode, not LetBinding
	input := `package x
templ Test() {
	formatted := fmt.Sprintf("%d", count)
	<span>{formatted}</span>
}`

	l := NewLexer("test.gsx", input)
	p := NewParser(l)
	file, err := p.ParseFile()
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	gc, ok := file.Components[0].Body[0].(*GoCode)
	if !ok {
		t.Fatalf("expected *GoCode for Go expression, got %T", file.Components[0].Body[0])
	}
	_ = gc
}

func TestParser_RawGoStatementsWithElements(t *testing.T) {
	// Test that Go statements and elements can be mixed in component body
	input := `package x
templ Counter(count int) {
	formattedCount := fmt.Sprintf("%d", count)
	log.Printf("Rendering counter")
	<div>
		<span>{formattedCount}</span>
	</div>
}`

	l := NewLexer("test.gsx", input)
	p := NewParser(l)
	file, err := p.ParseFile()
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	body := file.Components[0].Body
	if len(body) != 3 {
		t.Fatalf("expected 3 body nodes, got %d", len(body))
	}

	// First two should be GoCode
	gc1, ok := body[0].(*GoCode)
	if !ok {
		t.Fatalf("body[0]: expected *GoCode, got %T", body[0])
	}
	if gc1.Code != `formattedCount := fmt.Sprintf("%d", count)` {
		t.Errorf("body[0].Code = %q", gc1.Code)
	}

	gc2, ok := body[1].(*GoCode)
	if !ok {
		t.Fatalf("body[1]: expected *GoCode, got %T", body[1])
	}
	if gc2.Code != `log.Printf("Rendering counter")` {
		t.Errorf("body[1].Code = %q", gc2.Code)
	}

	// Third should be Element
	elem, ok := body[2].(*Element)
	if !ok {
		t.Fatalf("body[2]: expected *Element, got %T", body[2])
	}
	if elem.Tag != "div" {
		t.Errorf("body[2].Tag = %q, want 'div'", elem.Tag)
	}
}