-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtabSection.go
More file actions
286 lines (244 loc) · 8.65 KB
/
tabSection.go
File metadata and controls
286 lines (244 loc) · 8.65 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
package devtui
import (
"sync"
"time"
. "github.com/tinywasm/fmt"
)
// Interface for handling tab field sectionFields
// tabContent imprime contenido en la tui con id único
type tabContent struct {
Id string // unix number id eg: "1234567890" - INMUTABLE
Timestamp string // unix nano timestamp - MUTABLE (se actualiza en cada cambio)
Content string
Type MessageType
tabSection *tabSection
// NEW: Async fields (always present, nil when not async)
operationID *string // nil for sync messages, value for async operations
isProgress bool // true if this is a progress update
isComplete bool // true if async operation completed
// NEW: Handler identification
handlerName string // Formatted/padded Handler name for display
RawHandlerName string // Unformatted raw handler name used for matching/updating
handlerColor string // NEW: Handler-specific color for message formatting
handlerType handlerType // NEW: Type of handler (Interactive, Display, etc.) for formatting
}
// tabSection represents a tab section in the TUI with configurable fields and content
type tabSection struct {
Index int // index of the tab
Title string // eg: "BUILD", "TEST"
FieldHandlers []*field // Field actions configured for the section
SectionDescription string // eg: "Press 't' to compile", "Press 'r' to run tests"
// internal use
tabContents []tabContent // message contents
IndexActiveEditField int // Índice del campo de configuración seleccionado
tui *DevTUI
mu sync.RWMutex // Para proteger tabContents y writingHandlers de race conditions
// Writing handler registry for external handlers using new interfaces
writingHandlers []*anyHandler // CAMBIO: slice en lugar de map para thread-safety
// Animation state management
animationStopChans map[string]chan struct{}
}
// getWritingHandler busca un handler por nombre en el slice thread-safe
func (ts *tabSection) getWritingHandler(name string) *anyHandler {
ts.mu.RLock()
defer ts.mu.RUnlock()
for _, h := range ts.writingHandlers {
if h.Name() == name {
return h
}
}
return nil
}
func (hw *handlerWriter) Write(p []byte) (n int, err error) {
msg := Convert(string(p)).TrimSpace().String()
if msg != "" {
message, msgType := Translate(msg).StringType()
var handlerColor string
if handler := hw.tabSection.getWritingHandler(hw.handlerName); handler != nil {
handlerColor = handler.handlerColor // NEW: Get handler color
}
// operationID is now always the handlerName for tracking
trackingID := hw.handlerName
var hType handlerType = handlerTypeLoggable
if handler := hw.tabSection.getWritingHandler(hw.handlerName); handler != nil {
hType = handler.handlerType
}
hw.tabSection.tui.sendMessageWithHandler(message, msgType, hw.tabSection, hw.handlerName, trackingID, handlerColor, hType)
if msgType == Msg.Error {
hw.tabSection.tui.Logger(msg)
}
}
return len(p), nil
}
// HandlerLogger wraps tabSection with handler identification
type handlerWriter struct {
tabSection *tabSection
handlerName string
}
func (t *tabSection) addNewContent(msgType MessageType, content string) {
t.mu.Lock()
defer t.mu.Unlock()
t.tabContents = append(t.tabContents, t.tui.createTabContent(content, msgType, t, "", "", "", handlerTypeLoggable))
if len(t.tabContents) > 500 {
t.tabContents = t.tabContents[len(t.tabContents)-500:]
}
}
// NEW: updateOrAddContentWithHandler updates existing content by handler name (trackingID)
// Returns true if content was updated, false if new content was added
func (t *tabSection) updateOrAddContentWithHandler(msgType MessageType, content string, handlerName string, trackingID string, handlerColor string, hType handlerType) (updated bool, newContent tabContent) {
t.mu.Lock()
defer t.mu.Unlock()
// trackingID is now the handlerName for automatic tracking
if trackingID != "" {
for i := range t.tabContents {
if t.tabContents[i].RawHandlerName == trackingID {
// Update existing content
t.tabContents[i].Content = content
t.tabContents[i].Type = msgType
// Actualizar timestamp usando GetNewID directamente
if t.tui.id != nil {
t.tabContents[i].Timestamp = t.tui.id.GetNewID()
} else {
// Log the issue before using fallback
if t.tui.Logger != nil {
t.tui.Logger("Warning: unixid not initialized, using fallback timestamp for content update:", content)
}
// Graceful fallback when unixid initialization failed
t.tabContents[i].Timestamp = time.Now().Format("15:04:05")
}
// Move updated content to end
updatedContent := t.tabContents[i]
t.tabContents = append(t.tabContents[:i], t.tabContents[i+1:]...)
t.tabContents = append(t.tabContents, updatedContent)
return true, updatedContent
}
}
}
// If not found or no trackingID, add new content
newContent = t.tui.createTabContent(content, msgType, t, handlerName, trackingID, handlerColor, hType)
t.tabContents = append(t.tabContents, newContent)
// Keep only last 500 messages to prevent memory issues and slow rendering
if len(t.tabContents) > 500 {
t.tabContents = t.tabContents[len(t.tabContents)-500:]
}
return false, newContent
}
// NewTabSection creates a new tab section and returns it as any for interface decoupling.
// The returned value must be passed to the AddHandler method.
//
// Example:
//
// tab := tui.NewTabSection("BUILD", "Compiler Section")
// tui.AddHandler(myHandler, 2*time.Second, "#3b82f6", tab)
func (t *DevTUI) NewTabSection(title, description string) any {
tab := &tabSection{
Title: title,
SectionDescription: description,
tui: t,
animationStopChans: make(map[string]chan struct{}),
}
// Automatically add to TabSections and initialize
t.initTabSection(tab, len(t.TabSections))
t.TabSections = append(t.TabSections, tab)
return tab
}
// SetActiveTab sets the currently active tab by section reference.
func (t *DevTUI) SetActiveTab(section any) {
tab, ok := section.(*tabSection)
if !ok || tab == nil {
return
}
for i, ts := range t.TabSections {
if ts == tab {
t.activeTab = i
t.notifyTabActive(i) // Notify handlers that tab is now active
t.RefreshUI()
return
}
}
}
// notifyTabActive notifies all handlers in the specified tab that it has become active.
// Used for lazy execution or logging that requires the screen logger to be present.
func (t *DevTUI) notifyTabActive(tabIndex int) {
if tabIndex < 0 || tabIndex >= len(t.TabSections) {
return
}
tab := t.TabSections[tabIndex]
tab.mu.RLock()
defer tab.mu.RUnlock()
notified := make(map[any]bool)
// Notify all field handlers
for _, f := range tab.FieldHandlers {
if f.handler != nil && f.handler.origHandler != nil {
if aware, ok := f.handler.origHandler.(TabAware); ok {
if !notified[aware] {
notified[aware] = true
go aware.OnTabActive()
}
}
}
}
// Notify all writing-only handlers
for _, h := range tab.writingHandlers {
if h.origHandler != nil {
if aware, ok := h.origHandler.(TabAware); ok {
if !notified[aware] {
notified[aware] = true
go aware.OnTabActive()
}
}
}
}
}
// setActiveEditField sets the active edit field index
func (ts *tabSection) setActiveEditField(idx int) {
ts.IndexActiveEditField = idx
}
// Helper method to initialize a single tabSection
func (t *DevTUI) initTabSection(section *tabSection, index int) {
section.Index = index
section.tui = t
// Initialize field handlers
handlers := section.FieldHandlers
for j := range handlers {
handlers[j].index = j
handlers[j].cursor = 0
}
section.setFieldHandlers(handlers)
}
// stopAnimation stops any running animation for a given handler
func (ts *tabSection) stopAnimation(handlerName string) {
ts.mu.Lock()
defer ts.mu.Unlock()
if stopChan, ok := ts.animationStopChans[handlerName]; ok {
close(stopChan)
delete(ts.animationStopChans, handlerName)
}
}
// startAnimation starts a new auto-animation for a given handler
func (ts *tabSection) startAnimation(handlerName, baseMessage string, msgType MessageType, color string) {
// First stop any existing animation
ts.stopAnimation(handlerName)
stopChan := make(chan struct{})
ts.mu.Lock()
ts.animationStopChans[handlerName] = stopChan
ts.mu.Unlock()
go func() {
dots := ""
ticker := time.NewTicker(400 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-stopChan:
return
case <-ticker.C:
dots += " ."
if len(dots) > 6 { // Max 3 dots " . . ."
dots = ""
}
// Update the same line (using handlerName as trackingID)
ts.tui.sendMessageWithHandler(baseMessage+dots, msgType, ts, handlerName, handlerName, color, handlerTypeLoggable)
}
}
}()
}