forked from davidroman0O/vtable
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterfaces.go
More file actions
622 lines (517 loc) · 17.5 KB
/
interfaces.go
File metadata and controls
622 lines (517 loc) · 17.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
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
// Package vtable provides a virtualized table and list component for Bubble Tea.
// It efficiently handles large datasets by only loading and rendering the visible portion.
//
// # Easy Usage Examples
//
// Creating a simple table (easiest way):
//
// columns := []vtable.TableColumn{
// vtable.NewColumn("Name", 20),
// vtable.NewRightColumn("Size", 10),
// vtable.NewColumn("Location", 30),
// }
// table, err := vtable.NewSimpleTeaTable(columns, provider)
//
// Or even simpler with auto-sized columns:
//
// columns := vtable.CreateColumnsFromTitles("Name", "Size", "Location")
// table, err := vtable.NewSimpleTeaTable(columns, provider)
//
// Creating a table with custom height:
//
// table, err := vtable.NewTeaTableWithHeight(columns, provider, 15)
//
// The library automatically calculates proper threshold values based on height,
// eliminating configuration errors. Manual configuration is still possible
// for advanced use cases, but auto-correction prevents most common mistakes.
package vtable
import (
"strings"
"time"
"github.com/charmbracelet/lipgloss"
"github.com/mattn/go-runewidth"
)
// DataRequest represents a request for data with optional filtering and sorting.
type DataRequest struct {
// Start is the index of the first item to return
Start int
// Count is the number of items to return
Count int
// SortFields specifies the fields to sort by in order of priority
SortFields []string
// SortDirections specifies the sort directions ("asc" or "desc") corresponding to SortFields
SortDirections []string
// Filters is a map of field names to filter values
Filters map[string]any
}
// AddSortField adds a sort field with direction to a DataRequest
func (r *DataRequest) AddSortField(field string, direction string) {
// Normalize direction
if direction != "asc" && direction != "desc" {
direction = "asc" // Default to ascending
}
// Add the sort field and direction
r.SortFields = append(r.SortFields, field)
r.SortDirections = append(r.SortDirections, direction)
}
// ClearSort clears all sort fields and directions
func (r *DataRequest) ClearSort() {
r.SortFields = nil
r.SortDirections = nil
}
// HasSort returns true if the request has any sort fields
func (r *DataRequest) HasSort() bool {
return len(r.SortFields) > 0
}
// IsFieldSortedAscending checks if a field is sorted ascending
// Returns: sorted ascending (true), sorted descending (false), not sorted (false, false)
func (r *DataRequest) IsFieldSortedAscending(field string) (bool, bool) {
for i, f := range r.SortFields {
if f == field {
return r.SortDirections[i] == "asc", true
}
}
return false, false
}
// SelectionMode defines how selection behaves
type SelectionMode int
const (
// SelectionSingle allows only one item to be selected at a time
SelectionSingle SelectionMode = iota
// SelectionMultiple allows multiple items to be selected
SelectionMultiple
// SelectionNone disables selection
SelectionNone
)
// MetadataKey represents a type-safe key for metadata values
type MetadataKey[T any] struct {
Key string
DefaultValue T
Validator func(T) error
}
// TypedMetadata provides type-safe metadata operations
type TypedMetadata struct {
data map[string]any
}
// NewTypedMetadata creates a new TypedMetadata instance
func NewTypedMetadata() TypedMetadata {
return TypedMetadata{
data: make(map[string]any),
}
}
// Set stores a value with type safety and validation
func SetTypedMetadata[T any](tm *TypedMetadata, key MetadataKey[T], value T) error {
if key.Validator != nil {
if err := key.Validator(value); err != nil {
return err
}
}
tm.data[key.Key] = value
return nil
}
// Get retrieves a value with type safety
func GetTypedMetadata[T any](tm *TypedMetadata, key MetadataKey[T]) T {
if val, ok := tm.data[key.Key]; ok {
if typedVal, ok := val.(T); ok {
return typedVal
}
}
return key.DefaultValue
}
// GetRaw returns the raw map for backward compatibility
func (tm *TypedMetadata) GetRaw() map[string]any {
return tm.data
}
// SetRaw sets a raw value (for backward compatibility)
func (tm *TypedMetadata) SetRaw(key string, value any) {
tm.data[key] = value
}
// Common metadata keys
var (
StatusColorKey = MetadataKey[string]{"status_color", "#ffffff", nil}
PriorityKey = MetadataKey[int]{"priority", 0, nil}
TooltipKey = MetadataKey[string]{"tooltip", "", nil}
IconKey = MetadataKey[string]{"icon", "", nil}
BadgeKey = MetadataKey[string]{"badge", "", nil}
)
// FocusState contains component focus information
type FocusState struct {
HasFocus bool
FocusedCell string // ID of focused cell (for tables)
}
// Data wraps an item with its state and metadata for rendering
type Data[T any] struct {
// ID is a stable unique identifier for this item
ID string
// Item is the actual data item
Item T
// Selected indicates if this item is selected
Selected bool
// Metadata contains custom rendering metadata with type safety
Metadata TypedMetadata
// Disabled indicates if this item should be rendered as disabled
Disabled bool
// Hidden indicates if this item should be hidden from view
Hidden bool
// Error contains any error state for this item
Error error
// Loading indicates if this item is currently loading
Loading bool
}
// RenderContext provides dimensional constraints and utilities for formatting
type RenderContext struct {
// Dimensional constraints
MaxWidth int
MaxHeight int
// Component context
ColumnIndex int
ColumnConfig *TableColumn
// Styling & theming
Theme *Theme
BaseStyle lipgloss.Style
// Terminal capabilities
ColorSupport bool
UnicodeSupport bool
// Accessibility
HighContrast bool
ReducedMotion bool
ScreenReader bool
// Global state
CurrentTime time.Time
FocusState FocusState
DeltaTime time.Duration // Time since last render for smooth animations
// Utility functions
Truncate func(string, int) string
Wrap func(string, int) []string
Measure func(string) (int, int)
// Error handling
OnError func(error)
}
// DefaultRenderContext creates a RenderContext with sensible defaults
func DefaultRenderContext() RenderContext {
return RenderContext{
MaxWidth: 80,
MaxHeight: 1,
ColorSupport: true,
UnicodeSupport: true,
HighContrast: false,
ReducedMotion: false,
ScreenReader: false,
CurrentTime: time.Now(),
Truncate: defaultTruncate,
Wrap: defaultWrap,
Measure: defaultMeasure,
OnError: defaultOnError,
}
}
// Default utility functions
func defaultTruncate(text string, maxWidth int) string {
if len(text) <= maxWidth {
return text
}
if maxWidth <= 3 {
return strings.Repeat(".", maxWidth)
}
return text[:maxWidth-3] + "..."
}
func defaultWrap(text string, maxWidth int) []string {
if maxWidth <= 0 {
return []string{}
}
words := strings.Fields(text)
if len(words) == 0 {
return []string{}
}
var lines []string
currentLine := ""
for _, word := range words {
if len(currentLine) == 0 {
currentLine = word
} else if len(currentLine)+1+len(word) <= maxWidth {
currentLine += " " + word
} else {
lines = append(lines, currentLine)
currentLine = word
}
}
if len(currentLine) > 0 {
lines = append(lines, currentLine)
}
return lines
}
func defaultMeasure(text string) (int, int) {
lines := strings.Split(text, "\n")
height := len(lines)
width := 0
for _, line := range lines {
if w := properDisplayWidth(line); w > width {
width = w
}
}
return width, height
}
func defaultOnError(err error) {
// Default: silent ignore (can be overridden)
_ = err
}
// TableColumn defines a table column configuration.
type TableColumn struct {
// Title is the column header text
Title string
// Width is the column width in characters
Width int
// Alignment defines how text is aligned in the column (left, right, center)
Alignment int
// Field is the identifier used for sorting/filtering operations
Field string
}
// NewColumn creates a new table column with the specified title and width.
// Uses left alignment by default.
// Example: col := vtable.NewColumn("Name", 20)
func NewColumn(title string, width int) TableColumn {
return TableColumn{
Title: title,
Width: width,
Alignment: AlignLeft,
Field: title, // Use title as field by default
}
}
// NewColumnWithAlignment creates a new table column with specified alignment.
// Example: col := vtable.NewColumnWithAlignment("Price", 10, vtable.AlignRight)
func NewColumnWithAlignment(title string, width int, alignment int) TableColumn {
return TableColumn{
Title: title,
Width: width,
Alignment: alignment,
Field: title, // Use title as field by default
}
}
// NewColumnWithField creates a new table column with a custom field name for sorting/filtering.
// Example: col := vtable.NewColumnWithField("Full Name", "name", 25, vtable.AlignLeft)
func NewColumnWithField(title, field string, width int, alignment int) TableColumn {
return TableColumn{
Title: title,
Width: width,
Alignment: alignment,
Field: field,
}
}
// NewLeftColumn creates a left-aligned column.
// Example: col := vtable.NewLeftColumn("Name", 20)
func NewLeftColumn(title string, width int) TableColumn {
return NewColumnWithAlignment(title, width, AlignLeft)
}
// NewRightColumn creates a right-aligned column.
// Example: col := vtable.NewRightColumn("Price", 10)
func NewRightColumn(title string, width int) TableColumn {
return NewColumnWithAlignment(title, width, AlignRight)
}
// NewCenterColumn creates a center-aligned column.
// Example: col := vtable.NewCenterColumn("Status", 12)
func NewCenterColumn(title string, width int) TableColumn {
return NewColumnWithAlignment(title, width, AlignCenter)
}
// CreateSimpleColumns creates columns from title/width pairs.
// This is useful for quickly setting up tables with basic columns.
// Example: columns := vtable.CreateSimpleColumns(map[string]int{"Name": 20, "Age": 10, "City": 15})
func CreateSimpleColumns(titleWidths map[string]int) []TableColumn {
columns := make([]TableColumn, 0, len(titleWidths))
for title, width := range titleWidths {
columns = append(columns, NewColumn(title, width))
}
return columns
}
// CreateColumnsFromTitles creates columns with auto-calculated widths based on title length.
// Minimum width is 8 characters, and it adds some padding.
// Example: columns := vtable.CreateColumnsFromTitles("Name", "Email Address", "Status")
func CreateColumnsFromTitles(titles ...string) []TableColumn {
columns := make([]TableColumn, len(titles))
for i, title := range titles {
width := len(title) + 4 // Add padding
if width < 8 {
width = 8 // Minimum width
}
columns[i] = NewColumn(title, width)
}
return columns
}
// ViewportState represents the current state of the viewport.
type ViewportState struct {
// ViewportStartIndex is the absolute index of the first item in the viewport.
ViewportStartIndex int
// CursorIndex is the absolute index of the selected item in the dataset.
CursorIndex int
// CursorViewportIndex is the relative index of the cursor within the viewport.
CursorViewportIndex int
// IsAtTopThreshold indicates if the cursor is at the top threshold.
IsAtTopThreshold bool
// IsAtBottomThreshold indicates if the cursor is at the bottom threshold.
IsAtBottomThreshold bool
// AtDatasetStart indicates if the viewport is at the start of the dataset.
AtDatasetStart bool
// AtDatasetEnd indicates if the viewport is at the end of the dataset.
AtDatasetEnd bool
}
// ChunkInfo represents information about a loaded data chunk.
type ChunkInfo struct {
// StartIndex is the absolute index of the first item in the chunk.
StartIndex int
// EndIndex is the absolute index of the last item in the chunk.
EndIndex int
// ItemCount is the number of items in the chunk.
ItemCount int
}
const (
// AlignLeft aligns text to the left
AlignLeft = iota
// AlignCenter aligns text to the center
AlignCenter
// AlignRight aligns text to the right
AlignRight
)
// DataProvider is an interface for providing data to virtualized components.
// It returns Data[T] objects that contain the item plus all rendering state.
type DataProvider[T any] interface {
// GetTotal returns the total number of items in the dataset.
GetTotal() int
// GetItems returns a slice of Data objects based on the provided request.
// Each Data object contains the item plus selection state and metadata.
GetItems(request DataRequest) ([]Data[T], error)
// GetSelectionMode returns the current selection mode
GetSelectionMode() SelectionMode
// SetSelected sets the selection state for an item at the given index.
// Returns true if the operation was successful.
SetSelected(index int, selected bool) bool
// SetSelectedByIDs sets the selection state for items with the given IDs.
// Returns true if the operation was successful.
SetSelectedByIDs(ids []string, selected bool) bool
// SelectRange selects items between startID and endID (inclusive).
// Returns true if the operation was successful.
SelectRange(startID, endID string) bool
// SelectAll selects all items
SelectAll() bool
// ClearSelection clears all selections
ClearSelection()
// GetSelectedIndices returns the indices of all selected items
GetSelectedIndices() []int
// GetSelectedIDs returns the IDs of all selected items
GetSelectedIDs() []string
// GetItemID extracts the unique identifier from an item.
// We don't know the ID field by default, so each provider must implement this.
GetItemID(item *T) string
}
// SearchableDataProvider extends DataProvider with search capabilities.
type SearchableDataProvider[T any] interface {
DataProvider[T]
// FindItemIndex searches for an item based on the given criteria and returns its index.
// The criteria is provided as a key-value pair.
// If the item is found, its index and true are returned.
// If the item is not found, -1 and false are returned.
FindItemIndex(key string, value any) (int, bool)
}
// ItemFormatter is a function type for formatting items in the viewport.
// It receives the Data object which contains the item, selection state, and metadata.
type ItemFormatter[T any] func(data Data[T], index int, ctx RenderContext, isCursor bool, isTopThreshold bool, isBottomThreshold bool) string
// ItemFormatterAnimated is an enhanced formatter that supports animations.
// It returns a RenderResult that can trigger refreshes for dynamic content.
type ItemFormatterAnimated[T any] func(
data Data[T],
index int,
ctx RenderContext,
animationState map[string]any,
isCursor bool,
isTopThreshold bool,
isBottomThreshold bool,
) RenderResult
// CellFormatterAnimated is a formatter for individual table cells with animation support.
// This enables true cell-level animations like horizontal text scrolling, smooth transitions, etc.
type CellFormatterAnimated func(
cellValue string,
rowIndex int,
columnIndex int,
columnConfig TableColumn,
ctx RenderContext,
animationState map[string]any,
isCursor bool,
isSelected bool,
isTopThreshold bool,
isBottomThreshold bool,
) CellRenderResult
// CellRenderResult contains the result of rendering an individual cell with animation support
type CellRenderResult struct {
// Content is the rendered cell content
Content string
// RefreshTriggers specify when this cell should be re-rendered
RefreshTriggers []RefreshTrigger
// AnimationState stores state between renders for this specific cell
AnimationState map[string]any
// Error contains any rendering error
Error error
// Fallback content to use if there's an error
Fallback string
}
// TriggerType defines when a render refresh should occur
type TriggerType int
const (
// TriggerTimer refreshes at regular intervals
TriggerTimer TriggerType = iota
// TriggerEvent refreshes when specific events occur
TriggerEvent
// TriggerConditional refreshes when conditions are met
TriggerConditional
// TriggerOnce refreshes only once after initial render
TriggerOnce
)
// RefreshTrigger defines when a cell should be re-rendered
type RefreshTrigger struct {
Type TriggerType
Interval time.Duration // For timer-based triggers
Event string // For event-based triggers
Condition func() bool // For conditional triggers
}
// RenderResult contains both the visual output and refresh instructions
type RenderResult struct {
// Content is the rendered string
Content string
// RefreshTriggers specify when this cell should be re-rendered
RefreshTriggers []RefreshTrigger
// AnimationState stores state between renders
AnimationState map[string]any
// Error contains any rendering error
Error error
// Fallback content to use if there's an error
Fallback string
}
// Animation represents an active animation
type Animation struct {
State map[string]any
Triggers []RefreshTrigger
LastRender time.Time
IsVisible bool
}
// AnimationConfig configures animation behavior
type AnimationConfig struct {
Enabled bool
ReducedMotion bool
MaxAnimations int
BatchUpdates bool
TickInterval time.Duration // Time between animation ticks
}
// DefaultAnimationConfig returns sensible animation defaults
func DefaultAnimationConfig() AnimationConfig {
return AnimationConfig{
Enabled: true,
ReducedMotion: false,
MaxAnimations: 50,
BatchUpdates: true,
TickInterval: 100 * time.Millisecond, // Default tick interval
}
}
// properDisplayWidth calculates the correct display width of a string
// This function combines lipgloss (for ANSI code handling) and go-runewidth (for proper Unicode width)
func properDisplayWidth(text string) int {
// First, let lipgloss strip ANSI escape codes
stripped := lipgloss.NewStyle().Render(text)
// Then use go-runewidth for proper Unicode character width calculation
return runewidth.StringWidth(stripped)
}