forked from unxed/vtui
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommon_dialogs_test.go
More file actions
563 lines (480 loc) · 15.5 KB
/
Copy pathcommon_dialogs_test.go
File metadata and controls
563 lines (480 loc) · 15.5 KB
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
package vtui
import (
"context"
"github.com/unxed/vtinput"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// testVFS implements VFSMinimal for testing
type testVFS struct{ currentPath string }
func (v *testVFS) GetPath() string { return v.currentPath }
func (v *testVFS) SetPath(p string) error { v.currentPath = p; return nil }
func (v *testVFS) ReadDir(ctx context.Context, p string, onChunk func([]FSItem)) error {
entries, _ := os.ReadDir(p)
items := make([]FSItem, 0)
for _, e := range entries {
items = append(items, FSItem{Name: e.Name(), IsDir: e.IsDir()})
}
if len(items) > 0 && onChunk != nil {
onChunk(items)
}
return nil
}
func (v *testVFS) Join(elem ...string) string { return filepath.Join(elem...) }
func (v *testVFS) Dir(p string) string { return filepath.Dir(p) }
func (v *testVFS) Base(p string) string { return filepath.Base(p) }
// pumpTasks executes all pending tasks in the FrameManager queue.
func pumpTasks() {
for {
select {
case task := <-FrameManager.TaskChan:
task()
default:
return
}
}
}
// waitForCondition waits for a predicate to become true, pumping tasks in between.
func waitForCondition(t *testing.T, timeout time.Duration, condition func() bool) {
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
pumpTasks()
if condition() {
return
}
time.Sleep(10 * time.Millisecond)
}
t.Fatal("Timeout waiting for condition in async test")
}
func TestSelectDirDialog_ArrowVsEnter(t *testing.T) {
SetDefaultPalette()
FrameManager.Init(NewSilentScreenBuf())
tmpDir := t.TempDir()
vfs := &testVFS{currentPath: tmpDir}
dlg := SelectDirDialog("Test", tmpDir, vfs)
var lb *ListBox
for _, item := range dlg.rootGroup.items {
if l, ok := item.(*ListBox); ok {
lb = l
break
}
}
initialPath := vfs.GetPath()
// 1. Simulate Down Arrow (Select index 0, which is "..")
// This should trigger OnChange but NOT change the VFS path.
lb.ProcessKey(&vtinput.InputEvent{Type: vtinput.KeyEventType, KeyDown: true, VirtualKeyCode: vtinput.VK_DOWN})
if vfs.GetPath() != initialPath {
t.Errorf("Path changed on Arrow Key! Expected %s, got %s", initialPath, vfs.GetPath())
}
// 2. Simulate Enter (Action)
// This should change the VFS path.
lb.ProcessKey(&vtinput.InputEvent{Type: vtinput.KeyEventType, KeyDown: true, VirtualKeyCode: vtinput.VK_RETURN})
if vfs.GetPath() == initialPath {
t.Error("Path DID NOT change on Enter Key")
}
}
func TestInputBox_OkCallback(t *testing.T) {
SetDefaultPalette()
FrameManager.Init(NewSilentScreenBuf())
received := ""
onOk := func(s string) { received = s }
dlg := InputBox("Title", "Prompt", "DefaultValue", onOk)
// Find Edit and Button
var edit *Edit
var okBtn *Button
for _, item := range dlg.rootGroup.items {
if e, ok := item.(*Edit); ok {
edit = e
}
if b, ok := item.(*Button); ok && b.hotkey == 'o' {
okBtn = b
}
}
if edit == nil || okBtn == nil {
t.Fatal("Dialog structure missing components")
}
edit.SetText("NewValue")
if okBtn.OnClick != nil {
okBtn.OnClick()
}
if received != "NewValue" {
t.Errorf("Expected 'NewValue', got '%s'", received)
}
if !dlg.IsDone() {
t.Error("Dialog should be finished after Ok")
}
}
func TestSelectFileDialog_Selection(t *testing.T) {
SetDefaultPalette()
FrameManager.Init(NewSilentScreenBuf())
tmpDir := t.TempDir()
v := &testVFS{currentPath: tmpDir}
os.WriteFile(filepath.Join(tmpDir, "dummy.txt"), []byte("data"), 0644)
dlg := SelectFileDialog("Title", tmpDir, v, nil)
var lb *ListBox
var fileEdit *Edit
walk(dlg.rootGroup, func(el UIElement) bool {
if l, ok := el.(*ListBox); ok {
lb = l
}
if t, ok := el.(*Text); ok && el.GetHotkey() == 'f' {
if e, ok := t.FocusLink.(*Edit); ok {
fileEdit = e
}
}
return true
})
// Wait for async loading
waitForCondition(t, time.Second, func() bool {
for _, item := range lb.Items {
if item == "dummy.txt" {
return true
}
}
return false
})
// Change selection and check if Edit field updates
lb.SelectName("dummy.txt")
if lb.OnSelect != nil {
lb.OnSelect(lb.SelectPos)
}
if fileEdit.GetText() != "dummy.txt" {
t.Errorf("File Edit not updated. Got %q", fileEdit.GetText())
}
}
func TestSelectDirDialog_Filtering(t *testing.T) {
SetDefaultPalette()
FrameManager.Init(NewSilentScreenBuf())
tmpDir := t.TempDir()
os.Mkdir(filepath.Join(tmpDir, "subfolder"), 0755)
os.WriteFile(filepath.Join(tmpDir, "should_be_hidden.txt"), []byte("data"), 0644)
v := &testVFS{currentPath: tmpDir}
dlg := SelectDirDialog("Select Dir", tmpDir, v)
var lb *ListBox
walk(dlg.rootGroup, func(el UIElement) bool {
if l, ok := el.(*ListBox); ok {
lb = l
return false
}
return true
})
waitForCondition(t, time.Second, func() bool {
return len(lb.Items) > 1 // ".." + "subfolder"
})
for _, item := range lb.Items {
if item == "should_be_hidden.txt" {
t.Error("SelectDirDialog MUST NOT show files, only directories")
}
}
}
func TestDialogNavigation_UX(t *testing.T) {
SetDefaultPalette()
FrameManager.Init(NewSilentScreenBuf())
tmpDir := t.TempDir()
subPath := filepath.Join(tmpDir, "my_work_folder")
os.Mkdir(subPath, 0755)
v := &testVFS{currentPath: tmpDir}
dlg := SelectFileDialog("UX Test", tmpDir, v, nil)
var lb *ListBox
walk(dlg.rootGroup, func(el UIElement) bool {
if l, ok := el.(*ListBox); ok {
lb = l
return false
}
return true
})
// 1. Enter into "my_work_folder"
waitForCondition(t, time.Second, func() bool {
for _, item := range lb.Items {
if item == "my_work_folder" {
return true
}
}
return false
})
lb.SelectName("my_work_folder")
lb.ProcessKey(&vtinput.InputEvent{Type: vtinput.KeyEventType, KeyDown: true, VirtualKeyCode: vtinput.VK_RETURN})
// 2. Assert path changed and UI updated (list should now contain only "..")
waitForCondition(t, time.Second, func() bool {
return v.GetPath() == subPath && len(lb.Items) == 1 && lb.Items[0] == ".."
})
if lb.SelectPos != 0 {
t.Errorf("UX FAIL: Cursor must be on '..' (0) when entering an empty directory. Got pos: %d", lb.SelectPos)
}
// 3. Exit back to parent via ".."
lb.SelectName("..")
lb.ProcessKey(&vtinput.InputEvent{Type: vtinput.KeyEventType, KeyDown: true, VirtualKeyCode: vtinput.VK_RETURN})
// 4. Assert path restored and UI updated (cursor should land on "my_work_folder")
waitForCondition(t, time.Second, func() bool {
return v.GetPath() == tmpDir && lb.Items[lb.SelectPos] == "my_work_folder"
})
}
func TestSelectFileDialog_LayoutBestPractice(t *testing.T) {
SetDefaultPalette()
FrameManager.Init(NewSilentScreenBuf())
v := &testVFS{currentPath: filepath.FromSlash("/tmp")}
// Create dialog (55x20)
dlg := SelectFileDialog("LayoutTest", filepath.FromSlash("/tmp"), v, nil)
var fileEdit *Edit
var btnOk *Button
var lb *ListBox
walk(dlg.rootGroup, func(el UIElement) bool {
if t, ok := el.(*Text); ok && el.GetHotkey() == 'f' {
if e, ok := t.FocusLink.(*Edit); ok {
fileEdit = e
}
}
if b, ok := el.(*Button); ok && b.GetHotkey() == 'o' {
btnOk = b
}
if l, ok := el.(*ListBox); ok {
lb = l
}
return true
})
if fileEdit == nil || btnOk == nil || lb == nil {
t.Fatal("Required components not found in dialog")
}
// 1. Check ListBox stretch
lx1, _, lx2, _ := lb.GetPosition()
if lx1 < dlg.X1 || lx2 > dlg.X2 {
t.Errorf("ListBox bounds invalid: %d..%d", lx1, lx2)
}
// 2. Check File Edit stretch
ex1, _, ex2, _ := fileEdit.GetPosition()
if ex1 <= dlg.X1+2 {
t.Errorf("File Edit overlap with label: X1=%d", ex1)
}
if ex2 < ex1 {
t.Errorf("File Edit has negative width: X1=%d, X2=%d", ex1, ex2)
}
// 3. Check Button centering
bx1, _, _, _ := btnOk.GetPosition()
if bx1 < dlg.X1 {
t.Errorf("Button out of bounds: X1=%d", bx1)
}
}
func TestLayout_StandardDialogs_Validity(t *testing.T) {
SetDefaultPalette()
fmscr := NewSilentScreenBuf()
fmscr.AllocBuf(80, 25)
FrameManager.Init(fmscr)
v := &testVFS{currentPath: filepath.FromSlash("/tmp")}
t.Run("SelectFileDialog", func(t *testing.T) {
dlg := SelectFileDialog("Test", filepath.FromSlash("/tmp"), v, nil)
AssertLayout(t, dlg)
})
t.Run("InputBox", func(t *testing.T) {
dlg := InputBox("Title", "Prompt", "Val", nil)
AssertLayout(t, dlg)
})
t.Run("MessageDialog", func(t *testing.T) {
dlg := createMessageDialog("Title", "Multi\nLine\nText", []string{"&Ok", "&Cancel"}, MessageInfo)
AssertLayout(t, dlg)
})
t.Run("ComboBoxDialog", func(t *testing.T) {
dlg := NewCenteredDialog(40, 10, "Combo Test")
cb := NewComboBox(0, 0, 20, []string{"A", "B"})
dlg.AddItem(cb)
vbox := NewVBoxLayout(dlg.X1+2, dlg.Y1+2, 40-4, 10-4)
vbox.Add(cb, Margins{}, AlignLeft)
vbox.Apply()
AssertLayout(t, dlg)
})
}
func TestShowMessage_WideButtons_Layout(t *testing.T) {
SetDefaultPalette()
scr := NewSilentScreenBuf()
scr.AllocBuf(80, 25)
FrameManager.Init(scr)
// A large set of buttons that will exceed 72 columns and force stacking.
// 7 buttons * ~15 chars = 105 cols horizontally.
buttons := []string{"Button One", "Button Two", "Button Three", "Button Four", "Button Five", "Button Six", "Button Seven"}
// Create dialog. Logic: 1 line text + 4 padding/borders + 14 (7 buttons * 2).
// Expected Height = 19.
dlg := createMessageDialog(" Stacking Test ", "Testing vertical button stacking logic.", buttons, MessageInfo)
// Layout validation (includes width/overlap/padding checks)
AssertLayout(t, dlg)
// Verify it switched to stacked mode
height := dlg.Y2 - dlg.Y1 + 1
if height != 19 {
t.Errorf("Stacked dialog height mismatch: expected 19, got %d", height)
}
// Verify width is constrained to maxDialogWidth
width := dlg.X2 - dlg.X1 + 1
if width > 72 {
t.Errorf("Dialog width %d exceeds maxDialogWidth (72)", width)
}
}
func TestShowMessage_HeightTruncation(t *testing.T) {
SetDefaultPalette()
scr := NewSilentScreenBuf()
scr.AllocBuf(80, 25)
FrameManager.Init(scr)
// Create a message with 50 lines (exceeds screen height 25)
var text string
for i := 0; i < 50; i++ {
text += "Line\n"
}
dlg := createMessageDialog(" Overflow Test ", text, []string{"&Ok"}, MessageInfo)
// Expected height is exactly screen height - 2 (23)
height := dlg.Y2 - dlg.Y1 + 1
if height != 23 {
t.Errorf("Dialog height truncation failed: expected 23, got %d", height)
}
// Ensure the truncation marker is present
foundTruncationMarker := false
for _, itm := range dlg.GetChildren() {
if txt, ok := itm.(*Text); ok {
if strings.Contains(txt.GetText(), "(truncated)") {
foundTruncationMarker = true
break
}
}
}
if !foundTruncationMarker {
t.Error("Truncation marker '... (truncated)' was not found in the dialog text")
}
// Ensure button is still there even if text is truncated
foundButton := false
for _, itm := range dlg.GetChildren() {
if _, ok := itm.(*Button); ok {
foundButton = true
break
}
}
if !foundButton {
t.Error("Button lost during height truncation")
}
// Should pass layout validation
AssertLayout(t, dlg)
}
func TestMessageDialog_IndicTextMatchesTerminalWidth(t *testing.T) {
SetDefaultPalette()
FrameManager.Init(NewSilentScreenBuf())
dlg := createMessageDialog("Title", "संस्कृतम्", []string{"&Ok"}, MessageInfo)
var txt *Text
for _, item := range dlg.GetChildren() {
if candidate, ok := item.(*Text); ok {
txt = candidate
break
}
}
if txt == nil {
t.Fatal("message dialog text element not found")
}
if got, want := txt.X2-txt.X1+1, StringWidth("संस्कृतम्"); got != want {
t.Fatalf("dialog text width = %d, want StringWidth %d", got, want)
}
if got, want := len(StringToCharInfo("संस्कृतम्", 0)), StringWidth("संस्कृतम्"); got != want {
t.Fatalf("rendered cell count = %d, want StringWidth %d", got, want)
}
}
func TestCommonDialogs_WarningMapping(t *testing.T) {
SetDefaultPalette()
FrameManager.Init(NewSilentScreenBuf())
// 1. Create a warning dialog with the explicit kind (recommended API).
dlg := createMessageDialog(" Warning ", "This is a test warning.", []string{"&Ok"}, MessageWarn)
if !dlg.IsWarning {
t.Error("Expected IsWarning to be true for MessageWarn kind")
}
// 2. Check that the frame's ColorBackgroundIdx maps to ColWarnText after rendering
scr := NewSilentScreenBuf()
scr.AllocBuf(80, 25)
dlg.Show(scr)
if dlg.frame.ColorBackgroundIdx != ColWarnText {
t.Errorf("Expected ColorBackgroundIdx to be ColWarnText (%d), got %d", ColWarnText, dlg.frame.ColorBackgroundIdx)
}
// 3. Find the text element and check its resolved color
var txt *Text
walk(dlg.rootGroup, func(el UIElement) bool {
if t, ok := el.(*Text); ok {
txt = t
return false
}
return true
})
if txt == nil {
t.Fatal("Text element not found in dialog")
}
// Since we are inside a warning dialog, GetStateAttr(ColDialogText, ColDialogText) must resolve to Palette[ColWarnText]
resolvedAttr := txt.GetStateAttr(ColDialogText, ColDialogText)
expectedAttr := Palette[ColWarnText]
if resolvedAttr != expectedAttr {
t.Errorf("Expected resolved text attribute to be %016X (ColWarnText), got %016X", expectedAttr, resolvedAttr)
}
}
func TestShowMessage_Structure(t *testing.T) {
SetDefaultPalette()
FrameManager.Init(NewSilentScreenBuf())
title := "Warning"
text := "This is a test message\nwith two lines."
buttons := []string{"&Yes", "&No", "&Cancel"}
dlg := ShowMessage(title, text, buttons)
// Check the number of elements:
// 2 lines of text + 3 buttons = 5 elements
if len(dlg.rootGroup.items) != 5 {
t.Errorf("Wrong item count. Got %d, want 5", len(dlg.rootGroup.items))
}
// Check the frame title
if dlg.frame.title != title {
t.Errorf("Wrong title. Got %q, want %q", dlg.frame.title, title)
}
// Check that buttons return the correct ExitCode
for i := 0; i < 3; i++ {
btn := dlg.rootGroup.items[2+i].(*Button)
if btn.OnClick != nil {
btn.OnClick()
}
if dlg.ExitCode != i {
t.Errorf("Button %d failed to set exit code. Got %d", i, dlg.ExitCode)
}
}
}
// TestShowMessage_LegacyTitleInference guards the backward-compat path:
// pre-existing callers pass no MessageKind and rely on the title being
// one of "Warning" / "Error" / "Confirm" to get the warning palette.
// New code should use ShowMessageEx with an explicit MessageWarn, but
// the legacy inference must keep working for existing call sites.
func TestShowMessage_LegacyTitleInference(t *testing.T) {
SetDefaultPalette()
FrameManager.Init(NewSilentScreenBuf())
cases := []struct {
title string
warn bool
}{
{" Warning ", true},
{"Error", true},
{" Confirm ", true},
{" Info ", false},
{" File already open ", false},
{"", false},
}
for _, tc := range cases {
dlg := ShowMessage(tc.title, "body", []string{"&Ok"})
if dlg.IsWarning != tc.warn {
t.Errorf("ShowMessage(%q).IsWarning = %v, want %v", tc.title, dlg.IsWarning, tc.warn)
}
}
}
// TestShowMessageEx_ExplicitKindOverridesTitle is the whole point of the
// new API: the caller decides the palette, not the title. A "Warning"
// title with MessageInfo stays blue; a benign title with MessageWarn
// goes red. This decouples wording (which is localised) from styling.
func TestShowMessageEx_ExplicitKindOverridesTitle(t *testing.T) {
SetDefaultPalette()
FrameManager.Init(NewSilentScreenBuf())
// Title looks like a warning; caller says no — stay blue.
dlg := ShowMessageEx(" Warning ", "not really a warning", []string{"&Ok"}, MessageInfo)
if dlg.IsWarning {
t.Error("ShowMessageEx(MessageInfo) must not set IsWarning regardless of title")
}
// Title is neutral; caller says warn — go red.
dlg = ShowMessageEx(" File already open ", "reopen?", []string{"&Ok"}, MessageWarn)
if !dlg.IsWarning {
t.Error("ShowMessageEx(MessageWarn) must set IsWarning regardless of title")
}
}