gitstack

grindlemire/go-tui code browser

25.6 KB Go 1007 lines 2026-06-19 · dfa2075 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
package tui

import (
	"testing"
)

func TestRichText_BoldSurvivesWrap(t *testing.T) {
	buf := NewBuffer(40, 6)
	// Paragraph fixed to width 10 so the bold run wraps.
	para := New(
		WithWidth(10),
		WithRichText(
			TextSpan{Text: "see "},
			TextSpan{Text: "this bold run", Style: NewStyle().Bold()},
			TextSpan{Text: " end"},
		),
	)
	para.Calculate(40, 6)
	RenderTree(buf, para)

	// Row 0 starts "see " (plain) then "this" (bold).
	if buf.Cell(0, 0).Rune != 's' || buf.Cell(0, 0).Style.Attrs&AttrBold != 0 {
		t.Errorf("cell(0,0) should be plain 's', got %q attrs=%v", buf.Cell(0, 0).Rune, buf.Cell(0, 0).Style.Attrs)
	}
	// "see " is 4 cells; the bold word "this" begins at x=4 on row 0.
	if buf.Cell(4, 0).Style.Attrs&AttrBold == 0 {
		t.Errorf("cell(4,0) should be bold (start of bold run)")
	}
	// The paragraph must occupy more than one row at width 10.
	rowsWithText := 0
	for y := range 6 {
		for x := range 10 {
			if buf.Cell(x, y).Rune != ' ' {
				rowsWithText++
				break
			}
		}
	}
	if rowsWithText < 2 {
		t.Errorf("expected the paragraph to wrap to >=2 rows, got %d", rowsWithText)
	}
}

func TestRichText_ClippedLinesBelowAnOverflowingLineStillRender(t *testing.T) {
	// Regression: drawSpanLines must clip an over-wide line and continue to the
	// next line, not abandon all remaining lines. Parent is overflow-hidden and
	// narrower (width 3) than the child (width 10), so each wrapped line is wider
	// than the clip. Line 0 must clip at 3 cols AND line 1 must still render.
	buf := NewBuffer(12, 6)
	child := New(
		WithWidth(10),
		WithFlexShrink(0), // keep the child wider than the clip
		WithRichText(TextSpan{Text: "aaaaa bbbbb"}), // wraps to "aaaaa" / "bbbbb" at width 10
	)
	parent := New(
		WithSize(3, 4),
		WithOverflow(OverflowHidden),
	)
	parent.AddChild(child)
	parent.Calculate(12, 6)
	RenderTree(buf, parent)

	// Line 0 is clipped to 3 columns.
	if buf.Cell(0, 0).Rune != 'a' || buf.Cell(2, 0).Rune != 'a' {
		t.Errorf("line 0 not rendered/clipped as expected: %q%q",
			buf.Cell(0, 0).Rune, buf.Cell(2, 0).Rune)
	}
	if buf.Cell(3, 0).Rune == 'a' {
		t.Errorf("line 0 leaked past the clip at x=3")
	}
	// The regression assertion: line 1 must still render after line 0 overflowed.
	if buf.Cell(0, 1).Rune != 'b' {
		t.Errorf("line 1 was dropped after line 0 hit the clip edge: cell(0,1)=%q, want 'b'", buf.Cell(0, 1).Rune)
	}
}

func TestRichText_RendersInsideScrollableContainer(t *testing.T) {
	buf := NewBuffer(20, 5)
	child := New(
		WithSize(10, 1),
		WithRichText(
			TextSpan{Text: "ab"},
			TextSpan{Text: "cd", Style: NewStyle().Bold()},
		),
	)
	container := New(
		WithSize(12, 3),
		WithScrollable(ScrollVertical),
	)
	container.AddChild(child)
	container.Calculate(20, 5)
	RenderTree(buf, container)

	// Text must appear (this is the bug the spec warns about).
	if got := buf.Cell(0, 0).Rune; got != 'a' {
		t.Errorf("rich text not rendered in scroll container: cell(0,0)=%q, want 'a'", got)
	}
	if buf.Cell(2, 0).Style.Attrs&AttrBold == 0 {
		t.Errorf("cell(2,0) should be bold inside scroll container")
	}
}

func TestRenderTree_RichTextStylesPerSegment(t *testing.T) {
	buf := NewBuffer(20, 3)
	e := New(
		WithSize(10, 1),
		WithRichText(
			TextSpan{Text: "ab"},
			TextSpan{Text: "cd", Style: NewStyle().Bold()},
		),
	)
	e.Calculate(20, 3)
	RenderTree(buf, e)

	// "abcd" laid out left to right.
	for x, want := range []rune{'a', 'b', 'c', 'd'} {
		if got := buf.Cell(x, 0).Rune; got != want {
			t.Errorf("cell(%d,0).Rune = %q, want %q", x, got, want)
		}
	}
	// First two cells plain, last two bold.
	if buf.Cell(0, 0).Style.Attrs&AttrBold != 0 {
		t.Errorf("cell(0,0) should not be bold")
	}
	if buf.Cell(2, 0).Style.Attrs&AttrBold == 0 {
		t.Errorf("cell(2,0) should be bold")
	}
	if buf.Cell(3, 0).Style.Attrs&AttrBold == 0 {
		t.Errorf("cell(3,0) should be bold")
	}
}

func TestRenderTree_DrawsBackground(t *testing.T) {
	buf := NewBuffer(20, 10)
	bgStyle := NewStyle().Background(Blue)
	e := New(
		WithSize(10, 5),
		WithBackground(bgStyle),
	)
	e.Calculate(20, 10)

	RenderTree(buf, e)

	// Check that background was filled
	// The entire 10x5 area should have the background style
	for y := range 5 {
		for x := range 10 {
			cell := buf.Cell(x, y)
			if cell.Rune != ' ' {
				t.Errorf("cell(%d,%d).Rune = %q, want ' '", x, y, cell.Rune)
			}
			if cell.Style.Bg != Blue {
				t.Errorf("cell(%d,%d).Style.Bg = %v, want Blue", x, y, cell.Style.Bg)
			}
		}
	}
}

func TestRenderTree_DrawsBorder(t *testing.T) {
	buf := NewBuffer(20, 10)
	e := New(
		WithSize(10, 5),
		WithBorder(BorderSingle),
		WithBorderStyle(NewStyle().Foreground(Red)),
	)
	e.Calculate(20, 10)

	RenderTree(buf, e)

	// Check corners
	topLeft := buf.Cell(0, 0)
	if topLeft.Rune != '┌' {
		t.Errorf("top-left corner = %q, want '┌'", topLeft.Rune)
	}
	if topLeft.Style.Fg != Red {
		t.Errorf("top-left color = %v, want Red", topLeft.Style.Fg)
	}

	topRight := buf.Cell(9, 0)
	if topRight.Rune != '┐' {
		t.Errorf("top-right corner = %q, want '┐'", topRight.Rune)
	}

	bottomLeft := buf.Cell(0, 4)
	if bottomLeft.Rune != '└' {
		t.Errorf("bottom-left corner = %q, want '└'", bottomLeft.Rune)
	}

	bottomRight := buf.Cell(9, 4)
	if bottomRight.Rune != '┘' {
		t.Errorf("bottom-right corner = %q, want '┘'", bottomRight.Rune)
	}

	// Check horizontal edges
	for x := 1; x < 9; x++ {
		top := buf.Cell(x, 0)
		if top.Rune != '─' {
			t.Errorf("top edge at %d = %q, want '─'", x, top.Rune)
		}
		bottom := buf.Cell(x, 4)
		if bottom.Rune != '─' {
			t.Errorf("bottom edge at %d = %q, want '─'", x, bottom.Rune)
		}
	}

	// Check vertical edges
	for y := 1; y < 4; y++ {
		left := buf.Cell(0, y)
		if left.Rune != '│' {
			t.Errorf("left edge at %d = %q, want '│'", y, left.Rune)
		}
		right := buf.Cell(9, y)
		if right.Rune != '│' {
			t.Errorf("right edge at %d = %q, want '│'", y, right.Rune)
		}
	}
}

func TestRenderTree_NestedElements(t *testing.T) {
	buf := NewBuffer(30, 20)

	parent := New(
		WithSize(20, 15),
		WithPadding(2),
		WithBackground(NewStyle().Background(Blue)),
	)

	child := New(
		WithSize(10, 5),
		WithBorder(BorderSingle),
	)

	parent.AddChild(child)
	parent.Calculate(30, 20)

	RenderTree(buf, parent)

	// Parent background should cover 20x15
	// Child should be at (2, 2) with 10x5 size
	childRect := child.Rect()
	if childRect.X != 2 || childRect.Y != 2 {
		t.Errorf("child position = (%d,%d), want (2,2)", childRect.X, childRect.Y)
	}

	// Check child border corner exists
	topLeft := buf.Cell(2, 2)
	if topLeft.Rune != '┌' {
		t.Errorf("child top-left = %q, want '┌'", topLeft.Rune)
	}
}

func TestRenderTree_CullsElementsOutsideBuffer(t *testing.T) {
	buf := NewBuffer(10, 10)

	// Element positioned outside buffer
	e := New(WithSize(5, 5))
	e.Calculate(100, 100)
	// Manually set position outside buffer
	e.layout.Rect = NewRect(50, 50, 5, 5)

	// Should not panic and should not draw anything
	RenderTree(buf, e)

	// All cells should be spaces (untouched)
	for y := range 10 {
		for x := range 10 {
			cell := buf.Cell(x, y)
			if cell.Rune != ' ' {
				t.Errorf("cell(%d,%d) should be space, got %q", x, y, cell.Rune)
			}
		}
	}
}

func TestRenderTree_DrawsTextContent(t *testing.T) {
	buf := NewBuffer(30, 10)

	elem := New(
		WithText("Hello"),
		WithTextStyle(NewStyle().Foreground(Green)),
		WithSize(20, 3),
	)
	elem.Calculate(30, 10)

	RenderTree(buf, elem)

	// Check that text was drawn at left-aligned position
	// Text should start at (0, 0) with content "Hello"
	checkString(t, buf, 0, 0, "Hello")

	// Check style
	cell := buf.Cell(0, 0)
	if cell.Style.Fg != Green {
		t.Errorf("text style.Fg = %v, want Green", cell.Style.Fg)
	}
}

func TestRenderTree_TextCenterAlignment(t *testing.T) {
	buf := NewBuffer(30, 10)

	elem := New(
		WithText("Hi"),
		WithTextAlign(TextAlignCenter),
		WithSize(10, 3),
	)
	elem.Calculate(30, 10)

	RenderTree(buf, elem)

	// "Hi" is 2 chars wide, in a 10-wide container
	// Center position: (10 - 2) / 2 = 4
	// Text should be at x=4
	cell := buf.Cell(4, 0)
	if cell.Rune != 'H' {
		t.Errorf("centered text at x=4 = %q, want 'H'", cell.Rune)
	}
	cell = buf.Cell(5, 0)
	if cell.Rune != 'i' {
		t.Errorf("centered text at x=5 = %q, want 'i'", cell.Rune)
	}
}

func TestRenderTree_TextRightAlignment(t *testing.T) {
	buf := NewBuffer(30, 10)

	elem := New(
		WithText("Hi"),
		WithTextAlign(TextAlignRight),
		WithSize(10, 3),
	)
	elem.Calculate(30, 10)

	RenderTree(buf, elem)

	// "Hi" is 2 chars wide, in a 10-wide container
	// Right-aligned position: 10 - 2 = 8
	cell := buf.Cell(8, 0)
	if cell.Rune != 'H' {
		t.Errorf("right-aligned text at x=8 = %q, want 'H'", cell.Rune)
	}
	cell = buf.Cell(9, 0)
	if cell.Rune != 'i' {
		t.Errorf("right-aligned text at x=9 = %q, want 'i'", cell.Rune)
	}
}

func TestRenderTree_TextWithBorderAndPadding(t *testing.T) {
	buf := NewBuffer(30, 10)

	// Border takes 1 cell on each side, padding adds additional space inside.
	// With border + padding=1, content starts at position 2 (1 for border + 1 for padding).
	elem := New(
		WithText("Test"),
		WithSize(20, 5),
		WithBorder(BorderSingle),
		WithPadding(1), // 1 cell padding inside the border
	)
	elem.Calculate(30, 10)

	RenderTree(buf, elem)

	// Border should be drawn at edge
	corner := buf.Cell(0, 0)
	if corner.Rune != '┌' {
		t.Errorf("border corner = %q, want '┌'", corner.Rune)
	}

	// Content rect accounts for border (1) + padding (1) = 2
	contentRect := elem.ContentRect()
	if contentRect.X != 2 || contentRect.Y != 2 {
		t.Errorf("content rect starts at (%d,%d), want (2,2)", contentRect.X, contentRect.Y)
	}

	// Text "Test" should be at content rect position (2, 2)
	checkString(t, buf, 2, 2, "Test")
}

func TestElement_Render_CalculatesIfDirty(t *testing.T) {
	buf := NewBuffer(30, 20)

	e := New(
		WithSize(20, 10),
		WithBorder(BorderSingle),
	)

	// Element starts dirty, Render should calculate
	e.Render(buf, 30, 20)

	if e.IsDirty() {
		t.Error("Render should clear dirty flag after calculating")
	}

	// Border should be drawn
	corner := buf.Cell(0, 0)
	if corner.Rune != '┌' {
		t.Errorf("border corner = %q, want '┌'", corner.Rune)
	}
}

func TestElement_Render_SkipsCalculateIfClean(t *testing.T) {
	buf := NewBuffer(30, 20)

	e := New(WithSize(20, 10))
	// Manually calculate and clear dirty
	e.Calculate(30, 20)

	// Manually set a different position to verify Calculate isn't called
	originalX := e.layout.Rect.X
	e.layout.Rect.X = 100

	// Render should skip calculate since not dirty
	e.Render(buf, 30, 20)

	// Position should be unchanged (Calculate wasn't called)
	if e.layout.Rect.X != 100 {
		t.Errorf("Render called Calculate when element was clean")
	}

	_ = originalX // Unused intentionally
}

func TestRenderTree_EmptyTextDoesNotRender(t *testing.T) {
	buf := NewBuffer(20, 10)

	// Element with empty text and background
	elem := New(
		WithText(""),
		WithSize(10, 5),
		WithBackground(NewStyle().Background(Blue)),
	)
	elem.Calculate(20, 10)

	RenderTree(buf, elem)

	// Background should be drawn, but no text rendering should occur
	// This just verifies no panic and background is correct
	cell := buf.Cell(5, 2)
	if cell.Style.Bg != Blue {
		t.Errorf("background not drawn correctly, got Bg=%v", cell.Style.Bg)
	}
}

func TestRenderTree_NestedTextElements(t *testing.T) {
	buf := NewBuffer(40, 20)

	parent := New(
		WithSize(30, 10),
		WithPadding(2),
		WithBackground(NewStyle().Background(Blue)),
	)

	child := New(
		WithText("Hello"),
		WithTextStyle(NewStyle().Foreground(Green)),
	)

	parent.AddChild(child)
	parent.Calculate(40, 20)

	RenderTree(buf, parent)

	// Child should be positioned at (2, 2) due to padding
	childRect := child.Rect()
	if childRect.X != 2 || childRect.Y != 2 {
		t.Errorf("child position = (%d,%d), want (2,2)", childRect.X, childRect.Y)
	}

	// Text should be rendered at child position
	checkString(t, buf, 2, 2, "Hello")

	// Check text style
	cell := buf.Cell(2, 2)
	if cell.Style.Fg != Green {
		t.Errorf("text style.Fg = %v, want Green", cell.Style.Fg)
	}
}

func TestStringWidth(t *testing.T) {
	type tc struct {
		input    string
		expected int
	}

	tests := map[string]tc{
		"ASCII":       {input: "Hello", expected: 5},
		"empty":       {input: "", expected: 0},
		"with spaces": {input: "Hi there", expected: 8},
	}

	for name, tt := range tests {
		t.Run(name, func(t *testing.T) {
			got := stringWidth(tt.input)
			if got != tt.expected {
				t.Errorf("stringWidth(%q) = %d, want %d", tt.input, got, tt.expected)
			}
		})
	}
}

// checkString verifies that the given string appears at the specified position in the buffer.
func checkString(t *testing.T, buf *Buffer, x, y int, expected string) {
	t.Helper()
	curX := x
	for _, r := range expected {
		cell := buf.Cell(curX, y)
		if cell.Rune != r {
			t.Errorf("buf.Cell(%d,%d).Rune = %q, want %q", curX, y, cell.Rune, r)
		}
		curX += RuneWidth(r)
	}
}

func TestRenderTree_TextWithBorder(t *testing.T) {
	type tc struct {
		text       string
		wantWidth  int
		wantHeight int
	}

	tests := map[string]tc{
		"short text with border": {
			text:       "Hi",
			wantWidth:  4, // 2 + border(2)
			wantHeight: 3, // 1 + border(2)
		},
		"longer text with border": {
			text:       "Text Styles",
			wantWidth:  13, // 11 + border(2)
			wantHeight: 3,  // 1 + border(2)
		},
	}

	for name, tt := range tests {
		t.Run(name, func(t *testing.T) {
			span := New(
				WithText(tt.text),
				WithBorder(BorderSingle),
			)

			parent := New(
				WithDirection(Column),
				WithSize(40, 20),
				WithAlign(AlignStart),
			)
			parent.AddChild(span)

			buf := NewBuffer(40, 20)
			parent.Render(buf, 40, 20)

			rect := span.Rect()
			if rect.Width != tt.wantWidth {
				t.Errorf("Rect.Width = %d, want %d", rect.Width, tt.wantWidth)
			}
			if rect.Height != tt.wantHeight {
				t.Errorf("Rect.Height = %d, want %d", rect.Height, tt.wantHeight)
			}

			// Check border corners render correctly
			topLeft := buf.Cell(rect.X, rect.Y)
			if topLeft.Rune != '┌' {
				t.Errorf("top-left = %q, want '┌'", topLeft.Rune)
			}
			topRight := buf.Cell(rect.X+rect.Width-1, rect.Y)
			if topRight.Rune != '┐' {
				t.Errorf("top-right = %q, want '┐'", topRight.Rune)
			}
			bottomLeft := buf.Cell(rect.X, rect.Y+rect.Height-1)
			if bottomLeft.Rune != '└' {
				t.Errorf("bottom-left = %q, want '└'", bottomLeft.Rune)
			}
			bottomRight := buf.Cell(rect.X+rect.Width-1, rect.Y+rect.Height-1)
			if bottomRight.Rune != '┘' {
				t.Errorf("bottom-right = %q, want '┘'", bottomRight.Rune)
			}

			// Text inside border
			checkString(t, buf, rect.X+1, rect.Y+1, tt.text)
		})
	}
}

func TestRenderTree_TextBorderInScrollable(t *testing.T) {
	buf := NewBuffer(40, 20)

	// Scrollable parent (mirrors the styling example)
	parent := New(
		WithDirection(Column),
		WithGap(1),
		WithPadding(2),
		WithBorder(BorderRounded),
		WithHeightPercent(100),
		WithScrollable(ScrollVertical),
	)

	// Text span with border
	span := New(
		WithText("Text Styles"),
		WithBorder(BorderSingle),
		WithBorderStyle(NewStyle().Foreground(White)),
		WithTextStyle(NewStyle().Bold()),
	)
	parent.AddChild(span)

	parent.Render(buf, 40, 20)

	// Check span border corners in scrollable context
	parentCR := parent.ContentRect()
	spanR := span.Rect()
	sx := parentCR.X + spanR.X
	sy := parentCR.Y + spanR.Y

	topLeft := buf.Cell(sx, sy)
	if topLeft.Rune != '┌' {
		t.Errorf("span top-left at (%d,%d) = %q, want '┌'", sx, sy, topLeft.Rune)
	}

	topRight := buf.Cell(sx+spanR.Width-1, sy)
	if topRight.Rune != '┐' {
		t.Errorf("span top-right at (%d,%d) = %q, want '┐'", sx+spanR.Width-1, sy, topRight.Rune)
	}

	bottomLeft := buf.Cell(sx, sy+spanR.Height-1)
	if bottomLeft.Rune != '└' {
		t.Errorf("span bottom-left at (%d,%d) = %q, want '└'", sx, sy+spanR.Height-1, bottomLeft.Rune)
	}

	bottomRight := buf.Cell(sx+spanR.Width-1, sy+spanR.Height-1)
	if bottomRight.Rune != '┘' {
		t.Errorf("span bottom-right at (%d,%d) = %q, want '┘'", sx+spanR.Width-1, sy+spanR.Height-1, bottomRight.Rune)
	}

	// Text should be inside the border
	checkString(t, buf, sx+1, sy+1, "Text Styles")
}

func TestRenderTree_TextStyleInheritance(t *testing.T) {
	type tc struct {
		parentOpts []Option
		childOpts  []Option
		wantFg     Color
		wantAttrs  Attr
	}

	tests := map[string]tc{
		"child inherits parent fg color": {
			parentOpts: []Option{WithSize(20, 10), WithTextStyle(NewStyle().Foreground(Cyan))},
			childOpts:  []Option{WithText("hi")},
			wantFg:     Cyan,
			wantAttrs:  AttrNone,
		},
		"child inherits parent bold attr": {
			parentOpts: []Option{WithSize(20, 10), WithTextStyle(NewStyle().Bold())},
			childOpts:  []Option{WithText("hi")},
			wantFg:     DefaultColor(),
			wantAttrs:  AttrBold,
		},
		"child inherits parent fg and bold": {
			parentOpts: []Option{WithSize(20, 10), WithTextStyle(NewStyle().Foreground(Red).Bold())},
			childOpts:  []Option{WithText("hi")},
			wantFg:     Red,
			wantAttrs:  AttrBold,
		},
		"child with explicit style overrides parent": {
			parentOpts: []Option{WithSize(20, 10), WithTextStyle(NewStyle().Foreground(Red).Bold())},
			childOpts:  []Option{WithText("hi"), WithTextStyle(NewStyle().Foreground(Green))},
			wantFg:     Green,
			wantAttrs:  AttrNone, // child's style replaces entirely, no bold
		},
		"child with explicit default style overrides parent": {
			parentOpts: []Option{WithSize(20, 10), WithTextStyle(NewStyle().Foreground(Red))},
			childOpts:  []Option{WithText("hi"), WithTextStyle(NewStyle())},
			wantFg:     DefaultColor(),
			wantAttrs:  AttrNone,
		},
	}

	for name, tt := range tests {
		t.Run(name, func(t *testing.T) {
			parent := New(tt.parentOpts...)
			child := New(tt.childOpts...)
			parent.AddChild(child)

			buf := NewBuffer(20, 10)
			parent.Render(buf, 20, 10)

			childRect := child.Rect()
			cell := buf.Cell(childRect.X, childRect.Y)
			if cell.Style.Fg != tt.wantFg {
				t.Errorf("text Fg = %v, want %v", cell.Style.Fg, tt.wantFg)
			}
			if cell.Style.Attrs != tt.wantAttrs {
				t.Errorf("text Attrs = %v, want %v", cell.Style.Attrs, tt.wantAttrs)
			}
		})
	}
}

func TestRenderTree_BackgroundInheritance(t *testing.T) {
	type tc struct {
		parentOpts []Option
		childOpts  []Option
		wantBg     Color
	}

	tests := map[string]tc{
		"child inherits parent background": {
			parentOpts: []Option{WithSize(20, 10), WithBackground(NewStyle().Background(Blue))},
			childOpts:  []Option{WithText("hi")},
			wantBg:     Blue,
		},
		"child with explicit background overrides parent": {
			parentOpts: []Option{WithSize(20, 10), WithBackground(NewStyle().Background(Blue))},
			childOpts:  []Option{WithText("hi"), WithBackground(NewStyle().Background(Red))},
			wantBg:     Red,
		},
	}

	for name, tt := range tests {
		t.Run(name, func(t *testing.T) {
			parent := New(tt.parentOpts...)
			child := New(tt.childOpts...)
			parent.AddChild(child)

			buf := NewBuffer(20, 10)
			parent.Render(buf, 20, 10)

			// Check text cell has inherited/overridden background
			childRect := child.Rect()
			cell := buf.Cell(childRect.X, childRect.Y)
			if cell.Style.Bg != tt.wantBg {
				t.Errorf("text Bg = %v, want %v", cell.Style.Bg, tt.wantBg)
			}
		})
	}
}

func TestRenderTree_DeepInheritance(t *testing.T) {
	// grandparent (red, bold) -> parent (no style) -> child (text)
	// child should inherit red+bold through the parent
	grandparent := New(WithSize(30, 10), WithTextStyle(NewStyle().Foreground(Red).Bold()))
	parent := New() // no explicit style
	child := New(WithText("deep"))

	grandparent.AddChild(parent)
	parent.AddChild(child)

	buf := NewBuffer(30, 10)
	grandparent.Render(buf, 30, 10)

	childRect := child.Rect()
	cell := buf.Cell(childRect.X, childRect.Y)
	if cell.Style.Fg != Red {
		t.Errorf("deeply inherited Fg = %v, want Red", cell.Style.Fg)
	}
	if cell.Style.Attrs != AttrBold {
		t.Errorf("deeply inherited Attrs = %v, want Bold", cell.Style.Attrs)
	}
}

func TestRenderTree_BorderStyleDoesNotInherit(t *testing.T) {
	parent := New(
		WithSize(20, 10),
		WithBorderStyle(NewStyle().Foreground(Red)),
	)
	child := New(
		WithSize(10, 5),
		WithBorder(BorderSingle),
	)
	parent.AddChild(child)

	buf := NewBuffer(20, 10)
	parent.Render(buf, 20, 10)

	// Child's border should use default style, not parent's red border style
	childRect := child.Rect()
	corner := buf.Cell(childRect.X, childRect.Y)
	if corner.Rune != '┌' {
		t.Errorf("child border corner = %q, want '┌'", corner.Rune)
	}
	if corner.Style.Fg != DefaultColor() {
		t.Errorf("child border Fg = %v, want Default (border should not inherit)", corner.Style.Fg)
	}
}

func TestRenderTree_HRInheritsTextStyle(t *testing.T) {
	parent := New(
		WithSize(20, 10),
		WithDirection(Column),
		WithTextStyle(NewStyle().Foreground(Cyan)),
	)
	hr := New(WithHR())
	parent.AddChild(hr)

	buf := NewBuffer(20, 10)
	parent.Render(buf, 20, 10)

	// HR should render with inherited cyan color
	hrRect := hr.Rect()
	cell := buf.Cell(hrRect.X, hrRect.Y)
	if cell.Rune != '─' {
		t.Errorf("HR rune = %q, want '─'", cell.Rune)
	}
	if cell.Style.Fg != Cyan {
		t.Errorf("HR inherited Fg = %v, want Cyan", cell.Style.Fg)
	}
}

func TestRenderTree_AutoContrast(t *testing.T) {
	type tc struct {
		bgColor   Color
		textStyle Style
		wantFg    Color
		desc      string
	}

	tests := map[string]tc{
		"light background gets black text": {
			bgColor:   White,
			textStyle: Style{}, // default fg
			wantFg:    Black,
			desc:      "white bg should auto-set black text",
		},
		"bright white background gets black text": {
			bgColor:   BrightWhite,
			textStyle: Style{}, // default fg
			wantFg:    Black,
			desc:      "bright white bg should auto-set black text",
		},
		"bright yellow background gets black text": {
			bgColor:   BrightYellow,
			textStyle: Style{}, // default fg
			wantFg:    Black,
			desc:      "bright yellow bg should auto-set black text",
		},
		"dark background keeps default text": {
			bgColor:   Black,
			textStyle: Style{}, // default fg
			wantFg:    DefaultColor(),
			desc:      "black bg should keep default text",
		},
		"blue background keeps default text": {
			bgColor:   Blue,
			textStyle: Style{}, // default fg
			wantFg:    DefaultColor(),
			desc:      "blue bg should keep default text",
		},
		"explicit fg color not overridden on light bg": {
			bgColor:   White,
			textStyle: NewStyle().Foreground(Red),
			wantFg:    Red,
			desc:      "explicit red fg should not be changed by auto-contrast",
		},
		"light RGB background gets black text": {
			bgColor:   RGBColor(255, 255, 200), // light yellow
			textStyle: Style{},
			wantFg:    Black,
			desc:      "light RGB bg should auto-set black text",
		},
		"dark RGB background keeps default text": {
			bgColor:   RGBColor(20, 20, 30), // dark blue
			textStyle: Style{},
			wantFg:    DefaultColor(),
			desc:      "dark RGB bg should keep default text",
		},
	}

	for name, tt := range tests {
		t.Run(name, func(t *testing.T) {
			var parentOpts []Option
			parentOpts = append(parentOpts,
				WithSize(20, 10),
				WithBackground(NewStyle().Background(tt.bgColor)),
			)
			if !tt.textStyle.Fg.IsDefault() || tt.textStyle.Attrs != AttrNone {
				parentOpts = append(parentOpts, WithTextStyle(tt.textStyle))
			}

			parent := New(parentOpts...)
			child := New(WithText("test"))
			parent.AddChild(child)

			buf := NewBuffer(20, 10)
			parent.Render(buf, 20, 10)

			childRect := child.Rect()
			cell := buf.Cell(childRect.X, childRect.Y)
			if cell.Style.Fg != tt.wantFg {
				t.Errorf("%s: text Fg = %v, want %v", tt.desc, cell.Style.Fg, tt.wantFg)
			}
		})
	}
}

func TestRenderTree_TextWrapping(t *testing.T) {
	type tc struct {
		text      string
		width     int
		height    int
		textAlign TextAlign
		wantLines []string // expected text at each row within content rect
	}

	tests := map[string]tc{
		"wraps text to width": {
			text:      "hello world",
			width:     7,
			height:    5,
			wantLines: []string{"hello", "world"},
		},
		"right aligned wrapped text": {
			text:      "hi world",
			width:     7,
			height:    5,
			textAlign: TextAlignRight,
			wantLines: []string{"hi", "world"},
		},
	}

	for name, tt := range tests {
		t.Run(name, func(t *testing.T) {
			buf := NewBuffer(tt.width, tt.height)
			e := New(
				WithText(tt.text),
				WithSize(tt.width, tt.height),
				WithTextAlign(tt.textAlign),
			)
			e.Calculate(tt.width, tt.height)
			RenderTree(buf, e)

			for lineIdx, wantLine := range tt.wantLines {
				checkString(t, buf, getAlignedX(tt.textAlign, tt.width, stringWidth(wantLine)), lineIdx, wantLine)
			}
		})
	}
}

// getAlignedX returns the expected x position for aligned text.
func getAlignedX(align TextAlign, containerWidth, textWidth int) int {
	switch align {
	case TextAlignCenter:
		return (containerWidth - textWidth) / 2
	case TextAlignRight:
		return containerWidth - textWidth
	default:
		return 0
	}
}

func TestRenderTree_TextWrapAutoScroll(t *testing.T) {
	type tc struct {
		text    string
		width   int
		height  int
		scrollY int
		want    []string // expected visible lines
	}

	tests := map[string]tc{
		"clips wrapped text to height": {
			text:    "aaa bbb ccc",
			width:   5,
			height:  2,
			scrollY: 0,
			want:    []string{"aaa", "bbb"},
		},
		"scroll offset shows later lines": {
			text:    "aaa bbb ccc",
			width:   5,
			height:  2,
			scrollY: 1,
			want:    []string{"bbb", "ccc"},
		},
	}

	for name, tt := range tests {
		t.Run(name, func(t *testing.T) {
			buf := NewBuffer(tt.width, tt.height)
			e := New(
				WithText(tt.text),
				WithSize(tt.width, tt.height),
			)
			e.scrollY = tt.scrollY
			e.Calculate(tt.width, tt.height)
			RenderTree(buf, e)

			for lineIdx, wantLine := range tt.want {
				checkString(t, buf, 0, lineIdx, wantLine)
			}
		})
	}
}

func TestRichText_LinkReachesCell(t *testing.T) {
	buf := NewBuffer(10, 1)
	e := New(
		WithSize(6, 1),
		WithRichText(TextSpan{Text: "ab", Link: "https://example.com"}),
	)
	e.Calculate(10, 1)
	RenderTree(buf, e)
	if got := buf.Cell(0, 0).Link; got != "https://example.com" {
		t.Errorf("cell(0,0).Link = %q, want the URL", got)
	}
	if got := buf.Cell(1, 0).Link; got != "https://example.com" {
		t.Errorf("cell(1,0).Link = %q, want the URL", got)
	}
}