-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfooterInput_test.go
More file actions
430 lines (344 loc) · 14.7 KB
/
footerInput_test.go
File metadata and controls
430 lines (344 loc) · 14.7 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
package devtui
import (
"strings"
"testing"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/muesli/termenv"
)
// TestFooterView verifica el comportamiento del renderizado del footer
func TestFooterView(t *testing.T) {
h := DefaultTUIForTest(func(messages ...any) {
// Test logger - do nothing
})
// Caso 1: Tab sin fields debe mostrar el scrollbar estándar
t.Run("Footer with no fields shows scrollbar", func(t *testing.T) {
// Guardar estado actual para restaurar después de la prueba
tab := h.TabSections[h.activeTab]
originalFields := tab.FieldHandlers
// Configurar pestaña sin fields
tab.setFieldHandlers([]*field{})
// Renderizar footer
result := h.footerView()
// Verificar que contiene indicador de scroll con iconos (no porcentaje)
hasScrollIcon := strings.Contains(result, "■") ||
strings.Contains(result, "▼") ||
strings.Contains(result, "▲")
if !hasScrollIcon {
t.Error("El footer sin campos debería mostrar indicador de scroll con iconos (■, ▼, ▲)")
}
// Restaurar estado
tab.setFieldHandlers(originalFields)
})
// Caso 2: Tab con fields debe mostrar el campo actual como input (ahora siempre, no solo en modo edición)
t.Run("Footer with fields shows field as input even when not editing", func(t *testing.T) {
// Crear un nuevo field con handler para la prueba
tab := h.TabSections[h.activeTab]
tab.setFieldHandlers([]*field{})
testHandler := NewTestEditableHandler("TestLabel", "TestValue Rendered")
h.AddHandler(testHandler, "", tab)
// Set viewport width for proper layout calculation
h.viewport.Width = 80
// Desactivar modo edición para verificar que aún así se muestra el campo
h.editModeActivated = false
tabSection := h.TabSections[h.activeTab]
tabSection.IndexActiveEditField = 0
// Renderizar footer
result := h.footerView()
// Verificar que contiene la etiqueta y valor del field
field := tab.FieldHandlers[0]
if !strings.Contains(result, field.Value()) {
t.Errorf("El footer debería mostrar:\n%v\n incluso sin estar en modo edición, pero muestra:\n%s\n", field.Value(), result)
}
})
}
// TestRenderFooterInput verifica el comportamiento específico del renderizado del input
func TestRenderFooterInput(t *testing.T) {
// Caso 1: Campo editable en modo edición debe mostrar cursor
t.Run("editable field in edit mode shows cursor", func(t *testing.T) {
h := DefaultTUIForTest(func(messages ...any) {})
h.editModeActivated = true
tab := h.TabSections[h.activeTab]
tab.setFieldHandlers([]*field{})
testHandler := NewTestEditableHandler("Test", "test value")
h.AddHandler(testHandler, "", tab)
// Set viewport width for proper layout calculation
h.viewport.Width = 80
field := tab.FieldHandlers[0]
field.setCursorForTest(2) // Cursor en posición 's': te[s]t value
field.setTempEditValueForTest("test value")
// Ensure cursor is visible for this test
h.cursorVisible = true
// Renderizar input
result := h.renderFooterInput()
// Con cursor Overlay, ya no buscamos "te▋st value"
// Sino que buscamos el carácter 's' resaltado (con estilo invertido)
char := "s"
expectedRender := lipgloss.NewStyle().
Background(lipgloss.Color(h.Foreground)).
Foreground(lipgloss.Color(h.Secondary)).
Render(char)
if !strings.Contains(result, expectedRender) {
t.Errorf("El cursor overlay para el carácter 's' no se encuentra en el resultado")
}
})
// Caso 2: Campo no editable no debe mostrar cursor
t.Run("Non-editable field doesn't show cursor", func(t *testing.T) {
h := DefaultTUIForTest(func(messages ...any) {
// Test logger - do nothing
})
// Limpiar todos los handlers existentes y crear explícitamente un handler no editable
tab := h.TabSections[h.activeTab]
tab.setFieldHandlers([]*field{}) // Limpiar cualquier handler por defecto
// Crear explícitamente un handler no editable (ExecutionHandler)
testHandler := NewTestNonEditableHandler("Test", "Value")
h.AddHandler(testHandler, "", tab)
h.editModeActivated = true
h.TabSections[h.activeTab].IndexActiveEditField = 0
// Renderizar input
result := h.renderFooterInput()
// No debe contener cursor porque es un handler de ejecución (no editable)
if strings.Contains(result, "▋") {
t.Error("Campo no editable no debería mostrar cursor")
}
})
// Nuevo test - Caso 4: Verificar que se maneja correctamente el índice fuera de rango
t.Run("Index out of range is handled correctly", func(t *testing.T) {
h := DefaultTUIForTest(func(messages ...any) {
// Test logger - do nothing
})
expectedLabel := "Test Handler"
// Configurar un índice activo fuera de rango
tab := h.TabSections[h.activeTab]
tab.setFieldHandlers([]*field{})
testHandler := NewTestNonEditableHandler(expectedLabel, "Some Value")
h.AddHandler(testHandler, "", tab)
// Set viewport width for proper layout calculation
h.viewport.Width = 80
h.TabSections[h.activeTab].IndexActiveEditField = 5 // Índice fuera de rango
// Renderizar - no debería producir pánico
result := h.renderFooterInput()
// Verificar que se resetea el índice y se muestra el primer campo
// Para handlers de ejecución, se muestra el Label() en el footer
if !strings.Contains(result, expectedLabel) {
t.Fatalf("No se manejó correctamente el índice fuera de rango. Esperado: %q, resultado:\n%s", expectedLabel, result)
}
})
// Nuevo test - Caso 5: Verificar el estilo correcto cuando está seleccionado pero no en modo edición
t.Run("Field has correct style when selected but not in edit mode", func(t *testing.T) {
h := DefaultTUIForTest(func(messages ...any) {
// Test logger - do nothing
})
tab := h.TabSections[h.activeTab]
tab.setFieldHandlers([]*field{})
testHandler := NewTestEditableHandler("Test", "Value")
h.AddHandler(testHandler, "", tab)
h.TabSections[h.activeTab].IndexActiveEditField = 0
h.editModeActivated = false // No en modo edición
// El estilo debe ser fieldSelectedStyle en vez de fieldEditingStyle
originalFieldSelectedStyle := h.fieldSelectedStyle
originalFieldEditingStyle := h.fieldEditingStyle
// Modificar temporalmente los estilos para distinguirlos claramente
h.fieldSelectedStyle = h.fieldSelectedStyle.Background(lipgloss.Color("blue"))
h.fieldEditingStyle = h.fieldEditingStyle.Background(lipgloss.Color("red"))
result := h.renderFooterInput()
// Restaurar estilos originales
h.fieldSelectedStyle = originalFieldSelectedStyle
h.fieldEditingStyle = originalFieldEditingStyle
// Verificar que no contiene el cursor de edición
if strings.Contains(result, "▋") {
t.Error("Campo seleccionado pero no en modo edición no debería mostrar cursor")
}
})
}
// Nuevos tests para la navegación y comportamiento de teclas
func TestInputNavigation(t *testing.T) {
h := DefaultTUIForTest(func(messages ...any) {
// Test logger - do nothing
})
// Configurar múltiples campos para prueba de navegación
tab := h.TabSections[h.activeTab]
tab.setFieldHandlers([]*field{})
testHandler1 := NewTestEditableHandler("Field1", "Value1")
testHandler2 := NewTestEditableHandler("Field2", "Value2")
testHandler3 := NewTestEditableHandler("Field3", "Value3")
h.AddHandler(testHandler1, "", tab)
h.AddHandler(testHandler2, "", tab)
h.AddHandler(testHandler3, "", tab)
h.TabSections[h.activeTab].IndexActiveEditField = 0
h.editModeActivated = false
t.Run("Right key navigates to next field", func(t *testing.T) {
// Simular pulsación de tecla derecha
_, _ = h.handleNormalModeKeyboard(tea.KeyMsg{Type: tea.KeyRight})
// Verificar que nos movimos al siguiente campo
if h.TabSections[h.activeTab].IndexActiveEditField != 1 {
t.Errorf("La tecla derecha debería navegar al siguiente campo, pero se quedó en: %d",
h.TabSections[h.activeTab].IndexActiveEditField)
}
})
t.Run("Left key navigates to previous field", func(t *testing.T) {
// Nos aseguramos de estar en el campo del medio
h.TabSections[h.activeTab].IndexActiveEditField = 1
// Simular pulsación de tecla izquierda
_, _ = h.handleNormalModeKeyboard(tea.KeyMsg{Type: tea.KeyLeft})
// Verificar que nos movimos al campo anterior
if h.TabSections[h.activeTab].IndexActiveEditField != 0 {
t.Errorf("La tecla izquierda debería navegar al campo anterior, pero se quedó en: %d",
h.TabSections[h.activeTab].IndexActiveEditField)
}
})
t.Run("Cyclical navigation wraps around at boundaries", func(t *testing.T) {
// Ir al primer campo
h.TabSections[h.activeTab].IndexActiveEditField = 0
// Simular pulsación de tecla izquierda (debe ir al último campo)
_, _ = h.handleNormalModeKeyboard(tea.KeyMsg{Type: tea.KeyLeft})
// Verificar que se movió al último campo
if h.TabSections[h.activeTab].IndexActiveEditField != 2 {
t.Errorf("La navegación cíclica debería ir al último campo, pero está en: %d",
h.TabSections[h.activeTab].IndexActiveEditField)
}
// Simular pulsación de tecla derecha (debe volver al primer campo)
_, _ = h.handleNormalModeKeyboard(tea.KeyMsg{Type: tea.KeyRight})
// Verificar que volvió al primer campo
if h.TabSections[h.activeTab].IndexActiveEditField != 0 {
t.Errorf("La navegación cíclica debería volver al primer campo, pero está en: %d",
h.TabSections[h.activeTab].IndexActiveEditField)
}
})
t.Run("Enter enters edit mode", func(t *testing.T) {
// Reset para esta prueba
h := DefaultTUIForTest(func(messages ...any) {
// Test logger - do nothing
})
// Configurar un campo editable
tab := h.TabSections[h.activeTab]
tab.setFieldHandlers([]*field{})
testHandler := NewTestEditableHandler("Test", "Value")
h.AddHandler(testHandler, "", tab)
// Asegurar que no estamos en modo edición
h.editModeActivated = false
h.TabSections[h.activeTab].IndexActiveEditField = 0
// Simular pulsación de Enter
_, _ = h.handleNormalModeKeyboard(tea.KeyMsg{Type: tea.KeyEnter})
// Verificar que entramos en modo edición
if !h.editModeActivated {
t.Error("Enter debería activar el modo edición")
}
})
t.Run("Esc exits edit mode", func(t *testing.T) {
// Reset para esta prueba
h := DefaultTUIForTest(func(messages ...any) {
// Test logger - do nothing
})
// Configurar un campo editable
tab := h.TabSections[h.activeTab]
tab.setFieldHandlers([]*field{})
testHandler := NewTestEditableHandler("Test", "Value")
h.AddHandler(testHandler, "", tab)
// Asegurar que estamos en modo edición
h.editModeActivated = true
h.TabSections[h.activeTab].IndexActiveEditField = 0
// Simular pulsación de Esc
_, _ = h.handleEditingConfigKeyboard(tea.KeyMsg{Type: tea.KeyEscape})
// Verificar que salimos del modo edición
if h.editModeActivated {
t.Error("Esc debería salir del modo edición")
}
})
t.Run("Left/right moves cursor in edit mode", func(t *testing.T) {
// Reset para esta prueba y configurar un campo editable
h := DefaultTUIForTest(func(messages ...any) {
// Test logger - do nothing
})
tab := h.TabSections[h.activeTab]
tab.setFieldHandlers([]*field{})
testHandler := NewTestEditableHandler("Test", "Value1")
h.AddHandler(testHandler, "", tab)
// Configurar para edición
h.editModeActivated = true
h.TabSections[h.activeTab].IndexActiveEditField = 0
field := tab.FieldHandlers[0]
field.setCursorAtEnd()
// Move cursor to position 3 for test
field.setCursorForTest(3)
// Simular pulsación de tecla izquierda
_, _ = h.handleEditingConfigKeyboard(tea.KeyMsg{Type: tea.KeyLeft})
// Verificar que el cursor se movió a la izquierda
if field.cursor != 2 {
t.Errorf("La tecla izquierda en modo edición debería mover el cursor a la izquierda, pero quedó en: %d",
field.cursor)
}
// Simular pulsación de tecla derecha
_, _ = h.handleEditingConfigKeyboard(tea.KeyMsg{Type: tea.KeyRight})
// Verificar que el cursor volvió a la posición original
if field.cursor != 3 {
t.Errorf("La tecla derecha en modo edición debería mover el cursor a la derecha, pero quedó en: %d",
field.cursor)
}
})
}
func TestCursorNoExtraSpace(t *testing.T) {
h := DefaultTUIForTest(func(messages ...any) {})
h.viewport.Width = 80
h.editModeActivated = true
tab := h.TabSections[h.activeTab]
tab.setFieldHandlers([]*field{})
// Texto original tiene largo 5
originalText := "value"
testHandler := NewTestEditableHandler("Test", originalText)
h.AddHandler(testHandler, "", tab)
f := tab.FieldHandlers[0]
f.setTempEditValueForTest(originalText)
f.setCursorForTest(3) // Cursor en medio: val|ue
// Render with cursor invisible (blinking off)
h.cursorVisible = false
result := h.renderFooterInput()
// El bug actual inserta un espacio: "val ue" (largo 6)
// El comportamiento deseado (Overlay) mantendrá "value" (largo 5)
if strings.Contains(result, "val ue") {
t.Errorf("DEBUG: Se detectó el bug del espacio extra ('val ue')")
}
if !strings.Contains(result, originalText) {
t.Errorf("El texto original %q debería estar presente sin espacios extra en medio", originalText)
}
}
func TestCursorNoTrail(t *testing.T) {
// Forzar perfil de color para que los tests sean consistentes
lipgloss.SetColorProfile(termenv.TrueColor)
h := DefaultTUIForTest(func(messages ...any) {})
h.viewport.Width = 80
h.editModeActivated = true
h.cursorVisible = true
tab := h.TabSections[h.activeTab]
tab.setFieldHandlers([]*field{})
testHandler := NewTestEditableHandler("Path", "abcdef")
h.AddHandler(testHandler, "", tab)
f := tab.FieldHandlers[0]
f.setTempEditValueForTest("abcdef")
f.setCursorForTest(2) // Cursor en 'c': ab[c]def
result := h.renderFooterInput()
// 1. Verificar que el texto 'def' está presente
if !strings.Contains(result, "def") {
t.Errorf("El texto 'def' después del cursor debería estar visible")
}
// 2. Verificar que NO hay trail (fondo negro después del cursor)
// El trail ocurre cuando hay un reset ANSI (\x1b[0m) seguido directamente por texto sin estilo
// Buscamos la secuencia: cursor + reset + texto sin estilo
cursorRender := lipgloss.NewStyle().
Background(lipgloss.Color(h.Foreground)).
Foreground(lipgloss.Color(h.Secondary)).
Render("c")
// Si hay trail, el patrón sería: cursorRender + "def" (sin estilo intermedio)
// Con el fix correcto, "def" está dentro del contenedor con fondo correcto
if strings.Contains(result, cursorRender+"def") {
t.Errorf("TRAIL DETECTADO: El texto posterior 'def' no tiene fondo (hereda reset del cursor)")
}
// 3. Verificar que todo el texto está dentro del mismo contenedor (sin trail visual)
// El ancho del resultado debe ser consistente independientemente de la posición del cursor
h.cursorVisible = false
resultNoCursor := h.renderFooterInput()
if lipgloss.Width(result) != lipgloss.Width(resultNoCursor) {
t.Errorf("El ancho del input no es consistente: conCursor=%d, sinCursor=%d",
lipgloss.Width(result), lipgloss.Width(resultNoCursor))
}
}